Documentation
¶
Overview ¶
Package auth wraps MSAL Go: profiles, the interactive and device-code flows, silent acquisition, the token stores and the friendly errors PLAN.md requires.
Design points that come from the Phase 1 spike and PLAN.md:
- Silent refresh is ours to call, once per operation, through Silent/Token.
- The MSAL cache is exported by MSAL only after a *successful network acquisition*, so we record "last refresh" ourselves for the status output (refs/msal-go/apps/internal/base/base.go:545-573).
- The feature matrix comes from the token's `scp` claim, which lists every scope consented for the app, not just the requested subset (docs/spike/phase1.md:17).
- `TEAMS_ACCESS_TOKEN` short-circuits everything: it is a decode-only check on an unsigned token, so it catches the common mistakes and nothing else.
Index ¶
- Constants
- func AADSTSCode(err error) string
- func Classify(err error, profile string) error
- func IsConsentError(err error) bool
- func IsRedirectURIError(err error) bool
- func IsSignedOut(err error) bool
- func MSALVerbose(err error) string
- func SaveMetadata(path string, m Metadata) error
- type Claims
- type Client
- func (c *Client) Accounts(ctx context.Context) ([]public.Account, error)
- func (c *Client) Authority() string
- func (c *Client) Effective() config.Effective
- func (c *Client) GrantedScopes(ctx context.Context) ([]string, error)
- func (c *Client) Login(ctx context.Context, opts LoginOptions) (Result, error)
- func (c *Client) Logout(ctx context.Context) error
- func (c *Client) Metadata() Metadata
- func (c *Client) Paths() store.Paths
- func (c *Client) Silent(ctx context.Context, scopes []string) (public.AuthResult, error)
- func (c *Client) Static() bool
- func (c *Client) StaticClaims() Claims
- func (c *Client) Status(ctx context.Context) (Status, error)
- func (c *Client) Store() tokenstore.Store
- func (c *Client) Token(ctx context.Context) (string, error)
- func (c *Client) TokenWithClaims(ctx context.Context, claims string) (string, error)
- type DeviceCode
- type LoginOptions
- type Metadata
- type Options
- type Result
- type Status
Constants ¶
const GraphAppIDAudience = "00000003-0000-0000-c000-000000000000"
GraphAppIDAudience is the audience a delegated Graph token carries. The spike saw the GUID form, not the URL form PLAN.md assumed (docs/spike/phase1.md:16), so both are accepted where a token is inspected.
const InteractiveTimeout = interactiveTimeout
InteractiveTimeout is exported so the CLI can tell the user how long it will wait, without repeating the number.
const (
RefreshTokenLifetime = 90 * 24 * time.Hour
)
RefreshTokenLifetime is the documented maximum age of a refresh token (refs/entra/docs/identity-platform/refresh-tokens.md: 90 days, sliding while it keeps being used). We warn well before it, because a dead bot token means a failed job rather than a prompt.
Variables ¶
This section is empty.
Functions ¶
func AADSTSCode ¶
AADSTSCode extracts the first AADSTS code from an error, or "".
func Classify ¶
Classify maps an auth error to a coded error with a hint. It never returns a nil error for a non-nil input, and it leaves an already-classified *output.Error alone (except to add a missing hint).
func IsConsentError ¶
IsConsentError reports whether err is an AADSTS65001-style consent failure.
func IsRedirectURIError ¶
IsRedirectURIError reports whether err is the AADSTS50011 the spike hit, which makes `auth login` fall back to device code (PLAN.md:110).
func IsSignedOut ¶
IsSignedOut reports whether err means "there is no usable account": MSAL's two distinct no-cache errors, a dead refresh token, or a consent failure.
func MSALVerbose ¶
MSALVerbose returns MSAL's verbose rendering of an error, which includes the request and response. It is only used behind -v, and its output can contain tokens, so it is never printed by default.
func SaveMetadata ¶
SaveMetadata writes the metadata file atomically as 0600.
Types ¶
type Claims ¶
type Claims struct {
Audience string
Issuer string
TenantID string
AppID string
Subject string
Name string
PreferredUsername string
Scopes []string
Capabilities []string
ExpiresOn time.Time
NotBefore time.Time
IssuedAt time.Time
Raw map[string]any
}
Claims is the decoded (unverified) payload of a JWT access token. Only the fields the CLI actually reads are typed; Raw keeps everything else.
This is a decode, not a verification: it exists to produce clear errors for the common mistakes (wrong audience, expired token) and it is never a security control. PLAN.md says so explicitly for the TEAMS_ACCESS_TOKEN escape hatch.
func ParseClaims ¶
ParseClaims decodes the payload of a JWT. It does not check the signature.
func ValidateAccessToken ¶
ValidateAccessToken checks the audience and lifetime of a token we did not obtain ourselves (TEAMS_ACCESS_TOKEN). allowedAudiences lists the audience values that are acceptable for the configured cloud; the Graph app GUID is always accepted.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the profile's auth session.
func (*Client) Accounts ¶
Accounts lists the cached accounts for this profile.
An empty token store short-circuits: reading it would mean a keychain round trip (about a second on macOS) to learn what a stat(2) already told us, and a profile that has never signed in is the most common case for the first commands a user runs.
func (*Client) GrantedScopes ¶
GrantedScopes returns the scopes the current token carries. The `scp` claim lists every consented scope, so this is the feature matrix with no extra probing (PLAN.md:66).
func (*Client) Login ¶
Login signs in. It uses the browser (auth code + PKCE) unless Device is set, and it falls back to device code when Entra rejects the redirect URI, which is the AADSTS50011 the spike hit while the app registration lacked http://localhost.
func (*Client) Logout ¶
Logout removes the account from the cache and deletes the token store material. MSAL only exports the cache through RemoveAccount, so signing out any other way would leave the refresh token on disk (refs/msal-go/apps/internal/base/base.go:609-622).
func (*Client) Silent ¶
Silent acquires a token without prompting, refreshing only when MSAL decides the cached one is too close to expiry.
func (*Client) Static ¶
Static reports whether the session uses the TEAMS_ACCESS_TOKEN escape hatch.
func (*Client) StaticClaims ¶
StaticClaims returns the decoded claims of the static token.
func (*Client) Status ¶
Status summarizes the profile for `teams auth status` and `teams doctor`. A missing or dead account comes back as a Status plus an exit-3 error, so the caller can print the diagnosis before exiting.
func (*Client) Store ¶
func (c *Client) Store() tokenstore.Store
Store returns the token store (nil when TEAMS_ACCESS_TOKEN is in use).
func (*Client) TokenWithClaims ¶ added in v1.1.1
TokenWithClaims implements graph.ClaimsTokenSource: Graph revoked the token through continuous access evaluation (a policy change, a revoked session) and answered a 401 with a claims challenge. The cached access token must not be used again: a silent acquisition with the claims bypasses it and redeems the refresh token, which mints a token under the current policies (refs/entra/docs/identity-platform/claims-challenge.md). When the refresh token itself is no longer accepted, this fails as an interaction-required error and `teams auth login` is the fix.
type DeviceCode ¶
type DeviceCode struct {
UserCode string
VerificationURL string
Message string
ExpiresOn time.Time
}
DeviceCode carries what the user has to type.
type LoginOptions ¶
type LoginOptions struct {
// Device forces the device-code flow.
Device bool
// Scopes defaults to the profile's scopes.
Scopes []string
// Interactive reports whether prompting is allowed at all. When it is false
// and Device is not set, Login fails with a usage error instead of blocking.
Interactive bool
// OnDeviceCode is called with the code and URL; the CLI prints it.
OnDeviceCode func(DeviceCode)
// OnFallback is called when the browser flow fails with AADSTS50011 and we
// retry with device code (PLAN.md:110).
OnFallback func(err error)
// OnBrowser is called with the authorization URL just before the browser is
// opened, so the CLI can show it (and the AADSTS50011 hint) instead of
// appearing to do nothing while it waits for the callback.
OnBrowser func(url string)
}
LoginOptions configures Login.
type Metadata ¶
type Metadata struct {
Version int `json:"version"`
Profile string `json:"profile,omitempty"`
HomeAccountID string `json:"home_account_id,omitempty"`
Account string `json:"account,omitempty"`
TenantID string `json:"tenant_id,omitempty"`
LastRefresh time.Time `json:"last_refresh,omitempty"`
Scopes []string `json:"scopes,omitempty"`
}
Metadata is the bookkeeping we keep ourselves, because MSAL's cache blob is explicitly opaque and unsupported: the refresh-token age cannot be read out of it (PLAN.md:92). It lives beside the token cache with the same 0600/0700 rules.
func LoadMetadata ¶
LoadMetadata reads the metadata file; a missing or unreadable file yields an empty struct, because the file only ever improves the output.
func (Metadata) RefreshAge ¶
RefreshAge reports how long ago the refresh token was last renewed.
type Options ¶
type Options struct {
// Effective is the resolved profile.
Effective config.Effective
// Paths is the on-disk layout for that profile.
Paths store.Paths
// Clock defaults to the system clock.
Clock clock.Clock
// Environ defaults to os.Environ(); TEAMS_ACCESS_TOKEN is read from it.
Environ []string
// HTTPClient is MSAL's HTTP client. Tests point it at fakeidp. A nil value
// means "use the default client"; it must stay a concrete *http.Client so
// that an unset field is a real nil rather than a typed-nil interface, which
// MSAL would dereference on the first request (see msalHTTPClientFor).
HTTPClient *http.Client
// DisableInstanceDiscovery turns off the discovery round trip, which the
// fake identity provider needs (its host is not a trusted authority).
DisableInstanceDiscovery bool
// Authority overrides the MSAL authority URL. Tests point it at fakeidp; in
// production it is derived from the profile's cloud and tenant, and there is
// no flag or environment variable for it.
Authority string
// OpenURL opens the authorization URL in a browser. It defaults to MSAL's
// own browser opener; tests pass fakeidp's in-process browser, and a future
// `--no-browser` flag would print the URL instead
// (refs/msal-go/apps/public/public.go:645-658).
OpenURL func(url string) error
// Store overrides the token store (tests, and `auth export`).
Store tokenstore.Store
// Keyring overrides the OS keychain (tests use an in-memory one).
Keyring tokenstore.Keyring
}
Options configures a Client.
type Result ¶
type Result struct {
Account string
HomeAccountID string
TenantID string
Scopes []string
ExpiresOn time.Time
// FromCache reports that no network call was needed.
FromCache bool
// DiscardedCache reports that an unreadable token cache was thrown away so
// this sign-in could start a new session.
DiscardedCache bool
}
Result is a successful acquisition, reduced to what the CLI shows.
type Status ¶
type Status struct {
Profile string
Account string
HomeAccountID string
Tenant string
TenantID string
Cloud string
ClientID string
Mode string
ReadOnly bool
SignedIn bool
AccessTokenFromEnv bool
Scopes []string
RequestedScopes []string
ScopesSpec string
ExpiresOn time.Time
LastRefresh time.Time
FromCache bool
StoreKind string
StoreDescription string
StoreWarning string
GraphBaseURL string
}
Status is the profile's auth state.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package tokenstore holds the MSAL cache backends.
|
Package tokenstore holds the MSAL cache backends. |