auth

package
v1.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 14, 2026 License: MIT Imports: 21 Imported by: 0

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

View Source
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.

View Source
const InteractiveTimeout = interactiveTimeout

InteractiveTimeout is exported so the CLI can tell the user how long it will wait, without repeating the number.

View Source
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

func AADSTSCode(err error) string

AADSTSCode extracts the first AADSTS code from an error, or "".

func Classify

func Classify(err error, profile string) error

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

func IsConsentError(err error) bool

IsConsentError reports whether err is an AADSTS65001-style consent failure.

func IsRedirectURIError

func IsRedirectURIError(err error) bool

IsRedirectURIError reports whether err is the AADSTS50011 the spike hit, which makes `auth login` fall back to device code (PLAN.md:110).

func IsSignedOut

func IsSignedOut(err error) bool

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

func MSALVerbose(err error) string

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

func SaveMetadata(path string, m Metadata) error

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

func ParseClaims(token string) (Claims, error)

ParseClaims decodes the payload of a JWT. It does not check the signature.

func ValidateAccessToken

func ValidateAccessToken(token string, allowedAudiences []string, now time.Time) (Claims, error)

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.

func (Claims) Expired

func (c Claims) Expired(now time.Time) bool

Expired reports whether the token is expired at now (a token with no exp claim counts as expired: we cannot tell, so we do not trust it).

func (Claims) HasScope

func (c Claims) HasScope(scope string) bool

HasScope reports whether the token carries a scope. The `scp` claim is a space separated list (refs/entra/docs/identity-platform/access-token-claims-reference.md:59).

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is the profile's auth session.

func New

func New(_ context.Context, opts Options) (*Client, error)

New prepares the auth session for a profile.

func (*Client) Accounts

func (c *Client) Accounts(ctx context.Context) ([]public.Account, error)

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) Authority

func (c *Client) Authority() string

Authority is the MSAL authority URL for the profile's tenant.

func (*Client) Effective

func (c *Client) Effective() config.Effective

Effective returns the resolved profile.

func (*Client) GrantedScopes

func (c *Client) GrantedScopes(ctx context.Context) ([]string, error)

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

func (c *Client) Login(ctx context.Context, opts LoginOptions) (Result, error)

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

func (c *Client) Logout(ctx context.Context) error

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) Metadata

func (c *Client) Metadata() Metadata

Metadata returns our refresh bookkeeping.

func (*Client) Paths

func (c *Client) Paths() store.Paths

Paths returns the on-disk layout.

func (*Client) Silent

func (c *Client) Silent(ctx context.Context, scopes []string) (public.AuthResult, error)

Silent acquires a token without prompting, refreshing only when MSAL decides the cached one is too close to expiry.

func (*Client) Static

func (c *Client) Static() bool

Static reports whether the session uses the TEAMS_ACCESS_TOKEN escape hatch.

func (*Client) StaticClaims

func (c *Client) StaticClaims() Claims

StaticClaims returns the decoded claims of the static token.

func (*Client) Status

func (c *Client) Status(ctx context.Context) (Status, error)

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) Token

func (c *Client) Token(ctx context.Context) (string, error)

Token implements graph.TokenSource.

func (*Client) TokenWithClaims added in v1.1.1

func (c *Client) TokenWithClaims(ctx context.Context, claims string) (string, error)

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

func LoadMetadata(path string) Metadata

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

func (m Metadata) RefreshAge(now time.Time) time.Duration

RefreshAge reports how long ago the refresh token was last renewed.

func (Metadata) RefreshWarning

func (m Metadata) RefreshWarning(now time.Time) string

RefreshWarning returns a warning when the refresh token is close to its documented 90-day lifetime, and "" when it is not (or when we have no timestamp yet).

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.

func (Status) RefreshAge

func (s Status) RefreshAge(now time.Time) time.Duration

RefreshAge is how long ago the refresh token was last renewed.

Directories

Path Synopsis
Package tokenstore holds the MSAL cache backends.
Package tokenstore holds the MSAL cache backends.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址