Documentation
¶
Index ¶
- Constants
- Variables
- func AccessTokenHash(token string) string
- func ApplicationInfoPath(appId string) string
- func BuildVerificationURL(baseURL, cliVersion, targetAppID string) string
- func FetchRemoteScopes(brand core.LarkBrand) (map[string][]string, bool)
- func IsNeedUserAuthorizationError(err error) bool
- func MaskToken(token string) string
- func MissingScopes(storedScope string, required []string) []string
- func NewNeedUserAuthorizationError(userOpenID string) error
- func NoRefreshTokenFix(brand core.LarkBrand, appID string) string
- func NoRefreshTokenSettingsURL(brand core.LarkBrand, appID string) string
- func PrepareFormTokenRequest(req *http.Request, key *dpop.Key, form url.Values, paired bool) (*http.Request, error)
- func RememberProofMethod(brand core.LarkBrand, appID, name string) error
- func RemoveStoredToken(appId, userOpenId string) error
- func ResolveConfigSigner(cfg *core.CliConfig, kc keychain.KeychainAccess) (keysigner.Signer, error)
- func RevokeToken(ctx context.Context, httpClient *http.Client, ca ClientAuth, ...) error
- func SetStoredToken(token *StoredUAToken) error
- func TokenStatus(token *StoredUAToken) string
- func VerifyUserToken(ctx context.Context, sdk *lark.Client, accessToken string, ...) error
- func WithTATIssuanceLock(ctx context.Context, appID string, fn func() error) error
- type AccessTokenResult
- type AppRegUserInfo
- type AppRegistrationBeginOptions
- type AppRegistrationInit
- type AppRegistrationRemoteError
- type AppRegistrationResponse
- type AppRegistrationResult
- type AuthHelperAssertionProvider
- type ClientAssertionProvider
- type ClientAssertionRequest
- type ClientAuth
- type DeviceAuthResponse
- type DeviceFlow
- type DeviceFlowResult
- type DeviceFlowTokenData
- type LocalAssertionProvider
- type NeedAuthorizationError
- type OAuthEndpoints
- type ProofProviderConfig
- type ProofProviderConfigList
- func (c ProofProviderConfigList) Preferred(brand core.LarkBrand, appID string) (string, error)
- func (c ProofProviderConfigList) RestoreBinding(ctx context.Context, stored *StoredUAToken, store *dpop.KeyStore) (*dpop.Binding, error)
- func (c ProofProviderConfigList) Try(ctx context.Context, preferred string, required bool, warnings io.Writer, ...) error
- type SecurityPolicyError
- type SecurityPolicyTransport
- type StoredUAToken
- type UATCallOptions
- type UATStatus
Constants ¶
const ( // PathDeviceAuthorization is the endpoint for device authorization. PathDeviceAuthorization = "/oauth/v1/device_authorization" // PathOAuthRevoke is the endpoint for revoking an OAuth token. PathOAuthRevoke = "/oauth/v1/revoke" // PathAppRegistration is the endpoint for application registration. PathAppRegistration = "/oauth/v1/app/registration" // PathOAuthTokenV2 is the endpoint for requesting an OAuth token (v2). PathOAuthTokenV2 = "/open-apis/authen/v2/oauth/token" // PathUserInfoV1 is the endpoint for fetching user information. PathUserInfoV1 = "/open-apis/authen/v1/user_info" // PathApplicationInfoV6Prefix is the prefix endpoint for fetching application info. PathApplicationInfoV6Prefix = "/open-apis/application/v6/applications/" )
Common authentication paths used for logging and API calls.
const ( StoredTokenTypeBearer = "Bearer" StoredTokenTypeDPoP = dpop.TokenType )
const NoRefreshTokenCause = `` /* 214-byte string literal not displayed */
NoRefreshTokenCause states why a login can end up without a refresh_token. Requesting offline_access is not enough: the token endpoint only issues a refresh_token after the app turns on "Refresh user_access_token" in its security settings and publishes an app version containing that change. Until then it still echoes offline_access in the granted scope.
const PathDeviceFlowConfiguration = "/oauth/v1/device_flow_configuration"
Variables ¶
var ( ErrRegistrationDeniedByUser = errors.New("app registration denied by user") ErrRegistrationDenied = errors.New("app registration denied") ErrRegistrationExpired = errors.New("device code expired, please try again") ErrRegistrationTimedOut = errors.New("app registration timed out, please try again") )
Terminal registration outcomes, exposed for typed classification by callers.
var ErrGrantAttempted = errors.New("token grant was already attempted")
ErrGrantAttempted prevents retrying a grant with another provider after an OAuth request.
var TokenRetryCodes = map[int]bool{ output.LarkErrTokenInvalid: true, output.LarkErrTokenExpired: true, }
TokenRetryCodes contains error codes that allow retry after token refresh.
Functions ¶
func AccessTokenHash ¶
AccessTokenHash identifies a grant during recovery without retaining its access token.
func ApplicationInfoPath ¶ added in v1.0.4
ApplicationInfoPath returns the full API path for querying an application's information.
func BuildVerificationURL ¶
BuildVerificationURL appends CLI tracking parameters to the verification URL. When targetAppID is non-empty, it is also included so the launcher can lock authorization to that existing app.
func FetchRemoteScopes ¶ added in v1.0.94
FetchRemoteScopes fetches and binary-validates the remote scopes.json. It returns (domain -> user_scopes, true) when the whole file is usable, or (nil, false) when the caller should fall back to the local set. Any failure (network / timeout / non-2xx / empty / bad JSON / structure mismatch / malformed scope) returns (nil, false) silently — no warning, no telemetry.
func IsNeedUserAuthorizationError ¶ added in v1.0.26
IsNeedUserAuthorizationError reports whether err represents a missing-UAT failure. It matches the legacy *NeedAuthorizationError sentinel, which is preserved in the Cause chain of the typed missing-UAT error, so errors.As traverses into the typed *errs.AuthenticationError as well.
func MissingScopes ¶
MissingScopes returns the elements of required that are absent from storedScope. storedScope is a space-separated list of granted scope strings (as stored in the token).
func NewNeedUserAuthorizationError ¶ added in v1.0.56
NewNeedUserAuthorizationError builds the typed *errs.AuthenticationError returned when no valid UAT exists for userOpenID. The Message keeps the need_user_authorization marker, the Hint converges on the same auth-login recovery vocabulary as the token-missing surface in internal/client, and the legacy *NeedAuthorizationError sentinel is preserved in the Cause chain for errors.As / errors.Is traversal.
func NoRefreshTokenFix ¶ added in v1.0.99
NoRefreshTokenFix tells the user how to make future logins renewable.
func NoRefreshTokenSettingsURL ¶ added in v1.0.99
NoRefreshTokenSettingsURL returns the developer-console security settings page where "Refresh user_access_token" is turned on for appID.
func PrepareFormTokenRequest ¶
func PrepareFormTokenRequest(req *http.Request, key *dpop.Key, form url.Values, paired bool) (*http.Request, error)
PrepareFormTokenRequest preserves the grant fields when refreshing a pair on retry.
func RemoveStoredToken ¶
RemoveStoredToken removes a stored UAT.
func ResolveConfigSigner ¶
ResolveConfigSigner resolves the host-local credential signer required by cfg.
func RevokeToken ¶ added in v1.0.53
func RevokeToken(ctx context.Context, httpClient *http.Client, ca ClientAuth, brand core.LarkBrand, token, tokenTypeHint string) error
RevokeToken revokes a previously issued OAuth token.
func SetStoredToken ¶
func SetStoredToken(token *StoredUAToken) error
SetStoredToken persists a newly authorized UAT in v2.
func TokenStatus ¶
func TokenStatus(token *StoredUAToken) string
TokenStatus determines the freshness of a stored token.
func VerifyUserToken ¶
func VerifyUserToken(ctx context.Context, sdk *lark.Client, accessToken string, binding *dpop.Binding) error
VerifyUserToken calls /authen/v1/user_info to confirm the token is accepted server-side. Returns nil on success or an error describing why the server rejected the token.
Types ¶
type AccessTokenResult ¶ added in v1.0.98
AccessTokenResult carries the token together with its proof-of-possession binding. Binding is nil for Bearer tokens.
func GetValidAccessToken ¶
func GetValidAccessToken(ctx context.Context, httpClient *http.Client, opts UATCallOptions) (*AccessTokenResult, error)
GetValidAccessToken obtains a valid user token and restores its local DPoP binding.
func ReissueAccessToken ¶
func ReissueAccessToken(ctx context.Context, httpClient *http.Client, opts UATCallOptions, rejectedTokenHash string) (*AccessTokenResult, error)
ReissueAccessToken refreshes a challenged UAT or uses a newer grant already stored for this account.
type AppRegUserInfo ¶
AppRegUserInfo contains user info returned from app registration.
type AppRegistrationBeginOptions ¶
type AppRegistrationBeginOptions struct {
AuthMethod string // client_secret or private_key_jwt_local_keypair
AuthAttestation string // private_key_jwt_local_keypair attestation JWT
TargetAppID string // existing app to update; empty creates a new app
}
AppRegistrationBeginOptions parametrizes the registration begin request.
type AppRegistrationInit ¶
type AppRegistrationInit struct {
Nonce string
SupportedAuthMethods []string // e.g. ["client_secret", "private_key_jwt_local_keypair"]
}
AppRegistrationInit is the response from the app registration init endpoint.
func RequestAppRegistrationInit ¶
func RequestAppRegistrationInit(ctx context.Context, httpClient *http.Client) (*AppRegistrationInit, error)
RequestAppRegistrationInit performs the init step of the registration flow, returning a server nonce (to be embedded in a TEE-signed attestation JWT) and the auth methods the server supports for this archetype.
type AppRegistrationRemoteError ¶
AppRegistrationRemoteError preserves structured registration failures that need command-specific recovery guidance.
func (*AppRegistrationRemoteError) Error ¶
func (e *AppRegistrationRemoteError) Error() string
type AppRegistrationResponse ¶
type AppRegistrationResponse struct {
DeviceCode string
UserCode string
VerificationUri string
VerificationUriComplete string
ExpiresIn int
Interval int
RequestedAuthMethod string
}
AppRegistrationResponse is the response from the app registration begin endpoint.
func RequestAppRegistration ¶
func RequestAppRegistration(ctx context.Context, httpClient *http.Client, brand core.LarkBrand, opts AppRegistrationBeginOptions, errOut io.Writer) (*AppRegistrationResponse, error)
RequestAppRegistration initiates the app registration device flow (begin step). The registration protocol always bootstraps on Feishu; brand selects the user-facing verification host. The request is bounded by ctx and a timeout.
type AppRegistrationResult ¶
type AppRegistrationResult struct {
ClientID string
ClientSecret string
UserInfo *AppRegUserInfo
}
AppRegistrationResult is the result of a successful app registration poll.
func RegisterAppWithDiscovery ¶ added in v1.0.69
func RegisterAppWithDiscovery(ctx context.Context, httpClient *http.Client, resp *AppRegistrationResponse, errOut io.Writer) (*AppRegistrationResult, core.LarkBrand, error)
RegisterAppWithDiscovery polls for credentials, mirroring the official SDK flow: the first poll and the (at most one) cross-brand switch are immediate, non-error responses without complete credentials keep polling, and one deadline from the begin expiry bounds all waits and in-flight requests. The returned brand is the one the credentials were issued on.
type AuthHelperAssertionProvider ¶
type AuthHelperAssertionProvider struct{ authhelper.IPCClient }
func (*AuthHelperAssertionProvider) Name ¶
func (*AuthHelperAssertionProvider) Name() string
func (*AuthHelperAssertionProvider) PrepareClientAssertion ¶
func (p *AuthHelperAssertionProvider) PrepareClientAssertion(_ context.Context, _ url.Values, request ClientAssertionRequest) (bool, error)
type ClientAssertionProvider ¶
type ClientAssertionProvider interface {
Name() string
PrepareClientAssertion(ctx context.Context, form url.Values, request ClientAssertionRequest) (paired bool, err error)
}
ClientAssertionProvider adds the assertion or requests a pair to be signed at send time.
type ClientAssertionRequest ¶
type ClientAuth ¶
type ClientAuth struct {
AppID string
AppSecret string
AssertionProvider ClientAssertionProvider
}
ClientAuth describes how to authenticate the OAuth client at the token endpoint: with a client_secret (default) or a signed client_assertion.
func ClientAuthFromConfig ¶
func ClientAuthFromConfig(cfg *core.CliConfig, signer keysigner.Signer) ClientAuth
ClientAuthFromConfig builds a ClientAuth from resolved config using the invocation-scoped signer selected by the caller.
func (ClientAuth) ApplyTokenAuth ¶
func (c ClientAuth) ApplyTokenAuth(ctx context.Context, form url.Values, audience string, credentialType extcred.TokenType, key *dpop.Key) (paired bool, err error)
ApplyTokenAuth prepares client authentication for a grant. A paired assertion is filled in alongside its DPoP header when the HTTP attempt is signed.
func (ClientAuth) WithProofProvider ¶
func (c ClientAuth) WithProofProvider(p ProofProviderConfig) ClientAuth
type DeviceAuthResponse ¶
type DeviceAuthResponse struct {
DeviceCode string `json:"device_code"`
UserCode string `json:"user_code"`
VerificationUri string `json:"verification_uri"`
VerificationUriComplete string `json:"verification_uri_complete"`
ExpiresIn int `json:"expires_in"`
Interval int `json:"interval"`
ProofProvider string `json:"-"` // Selected locally for polling this device code.
AuthHelperEndpoint string `json:"-"`
// contains filtered or unexported fields
}
DeviceAuthResponse is the response from the device authorization endpoint.
type DeviceFlow ¶
type DeviceFlow struct {
HTTPClient *http.Client
ClientAuth ClientAuth
Brand core.LarkBrand
DPoPMode core.DPoPMode
ProofProviderConfigs ProofProviderConfigList
ErrOut io.Writer
// contains filtered or unexported fields
}
DeviceFlow carries the app credentials and proof policy for a device login.
func (DeviceFlow) Authorize ¶
func (f DeviceFlow) Authorize(ctx context.Context, scope string) (*DeviceAuthResponse, error)
Authorize requests a device code and records the proof provider that obtained it.
func (DeviceFlow) PollToken ¶
func (f DeviceFlow) PollToken(ctx context.Context, grant DeviceAuthResponse) (*DeviceFlowResult, error)
PollToken exchanges the device code using the proof policy for this login.
type DeviceFlowResult ¶
type DeviceFlowResult struct {
OK bool
Token *DeviceFlowTokenData
Error string
Message string
Err error
}
DeviceFlowResult is the result of polling the token endpoint.
type DeviceFlowTokenData ¶
type DeviceFlowTokenData struct {
AccessToken string
RefreshToken string
ExpiresIn int
RefreshExpiresIn int
Scope string
TokenType string
StatusMessage string
DPoP *dpop.Binding
}
DeviceFlowTokenData contains the token data from a successful device flow.
type LocalAssertionProvider ¶
func (*LocalAssertionProvider) Name ¶
func (*LocalAssertionProvider) Name() string
func (*LocalAssertionProvider) PrepareClientAssertion ¶
func (p *LocalAssertionProvider) PrepareClientAssertion(ctx context.Context, form url.Values, request ClientAssertionRequest) (bool, error)
type NeedAuthorizationError ¶
type NeedAuthorizationError struct {
UserOpenId string
}
NeedAuthorizationError is the sentinel preserved in the Cause chain of the typed missing-UAT error so existing errors.As(&NeedAuthorizationError{}) consumers keep matching after the construction site moved to the typed taxonomy. It is never surfaced on the wire on its own.
func (*NeedAuthorizationError) Error ¶
func (e *NeedAuthorizationError) Error() string
Error returns the error message for NeedAuthorizationError.
type OAuthEndpoints ¶
OAuthEndpoints contains the OAuth endpoint URLs.
func ResolveOAuthEndpoints ¶
func ResolveOAuthEndpoints(brand core.LarkBrand) OAuthEndpoints
ResolveOAuthEndpoints resolves OAuth endpoint URLs based on brand.
type ProofProviderConfig ¶
type ProofProviderConfig struct {
Name string
DeviceCertSelector keysigner.DeviceCertSelector
AuthHelper authhelper.IPCClient
}
ProofProviderConfig selects the DPoP signer and, for Auth-Helper, the client assertion signer.
func (ProofProviderConfig) ResolveDPoPProvider ¶
func (p ProofProviderConfig) ResolveDPoPProvider(store *dpop.KeyStore, clientID string, credentialType extcred.TokenType) (dpop.DPoPProofProvider, error)
ResolveDPoPProvider binds the selected signer to the grant. The zero value uses the local key store.
type ProofProviderConfigList ¶
type ProofProviderConfigList []ProofProviderConfig
ProofProviderConfigList holds the app's enterprise proof configurations in Terminal policy order.
func FetchTerminalConfig ¶
func FetchTerminalConfig(ctx context.Context, httpClient *http.Client, brand core.LarkBrand, ca ClientAuth, warnings io.Writer) (ProofProviderConfigList, error)
FetchTerminalConfig discovers the ordered proof providers for the current application. A malformed success response warns and allows ordinary authentication. Local private_key_jwt skips the lookup and returns nil.
func RequeryAfterHelperFailure ¶
func RequeryAfterHelperFailure(ctx context.Context, httpClient *http.Client, brand core.LarkBrand, ca ClientAuth, failure error, warnings io.Writer) (ProofProviderConfigList, error)
RequeryAfterHelperFailure selects a replacement grant from the latest Terminal policy. An empty list allows ordinary authentication. A skipped lookup does not.
func (ProofProviderConfigList) Preferred ¶
Only the successfully used method is cached. Endpoints and selectors come from the current policy.
func (ProofProviderConfigList) RestoreBinding ¶
func (c ProofProviderConfigList) RestoreBinding(ctx context.Context, stored *StoredUAToken, store *dpop.KeyStore) (*dpop.Binding, error)
RestoreBinding tries only candidates for the provider recorded on this UAT.
func (ProofProviderConfigList) Try ¶
func (c ProofProviderConfigList) Try(ctx context.Context, preferred string, required bool, warnings io.Writer, requery func(error) (ProofProviderConfigList, error), attempt func(ProofProviderConfig) error) error
Try uses the first candidate that can produce the requested proof. Only failures before the OAuth request was sent may move the grant to another provider.
type SecurityPolicyError ¶
type SecurityPolicyError = errs.SecurityPolicyError
SecurityPolicyError is preserved as a Go type alias so existing errors.As(&SecurityPolicyError{}) consumers (cmd/root.go etc.) keep working. The concrete struct lives in errs/types.go.
type SecurityPolicyTransport ¶
type SecurityPolicyTransport struct {
Base http.RoundTripper
}
SecurityPolicyTransport is an http.RoundTripper that intercepts all responses and checks for security policy errors.
func (*SecurityPolicyTransport) BaseRoundTripper ¶ added in v1.0.82
func (t *SecurityPolicyTransport) BaseRoundTripper() http.RoundTripper
func (*SecurityPolicyTransport) WithBaseRoundTripper ¶ added in v1.0.82
func (t *SecurityPolicyTransport) WithBaseRoundTripper(base http.RoundTripper) http.RoundTripper
type StoredUAToken ¶
type StoredUAToken struct {
UserOpenId string `json:"userOpenId"`
AppId string `json:"appId"`
AccessToken string `json:"accessToken"`
RefreshToken string `json:"refreshToken"`
ExpiresAt int64 `json:"expiresAt"` // Unix ms
RefreshExpiresAt int64 `json:"refreshExpiresAt"` // Unix ms
Scope string `json:"scope"`
GrantedAt int64 `json:"grantedAt"` // Unix ms
TokenType string `json:"tokenType,omitempty"`
DPoPProvider string `json:"dpopProvider,omitempty"`
AuthHelperEndpoint string `json:"authHelperEndpoint,omitempty"`
DPoPKeyID string `json:"dpopKeyId,omitempty"`
DPoPJKT string `json:"dpopJkt,omitempty"`
DPoPKeySecurityLevel string `json:"dpopKeySecurityLevel,omitempty"`
ClockOffsetMs int64 `json:"clockOffsetMs,omitempty"`
ClockSyncedAtMs int64 `json:"clockSyncedAtMs,omitempty"`
}
StoredUAToken represents a stored user access token.
func GetStoredToken ¶
func GetStoredToken(appId, userOpenId string) (*StoredUAToken, error)
GetStoredToken reads the stored UAT and preserves storage and decode errors.
func (*StoredUAToken) SetDPoPBinding ¶
func (token *StoredUAToken) SetDPoPBinding(binding *dpop.Binding)
SetDPoPBinding records the signer and its clock in the token transaction.
type UATCallOptions ¶
type UATCallOptions struct {
ProofProviderConfigs ProofProviderConfigList
UserOpenId string
AppId string
AppSecret string
Domain core.LarkBrand
ErrOut io.Writer // diagnostic/status output (caller injects f.IOStreams.ErrOut)
DPoPMode core.DPoPMode
DPoPKeyStore *dpop.KeyStore
AssertionProvider ClientAssertionProvider
}
UATCallOptions contains options for UAT API calls.
func NewUATCallOptions ¶
func NewUATCallOptions(cfg *core.CliConfig, errOut io.Writer, signer keysigner.Signer, candidates ProofProviderConfigList) UATCallOptions
NewUATCallOptions creates UATCallOptions from a CLI config.
type UATStatus ¶
type UATStatus struct {
Authorized bool `json:"authorized"`
UserOpenId string `json:"userOpenId"`
Scope string `json:"scope,omitempty"`
ExpiresAt int64 `json:"expiresAt,omitempty"`
RefreshExpiresAt int64 `json:"refreshExpiresAt,omitempty"`
GrantedAt int64 `json:"grantedAt,omitempty"`
TokenStatus string `json:"tokenStatus,omitempty"`
}
UATStatus represents the status of a user access token.