upstreamtoken

package
v0.70.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: Apache-2.0 Imports: 13 Imported by: 2 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package upstreamtoken provides a service for managing upstream IDP token lifecycle, including transparent refresh of expired access tokens.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrSessionNotFound indicates no upstream tokens exist for the session.
	ErrSessionNotFound = errors.New("upstream tokens not found for session")

	// ErrNoRefreshToken indicates the access token is expired but no refresh
	// token is available to perform a refresh.
	ErrNoRefreshToken = errors.New("no refresh token available")

	// ErrRefreshFailed indicates a refresh failure (e.g., the
	// refresh token was revoked by the upstream IDP). It wraps the underlying
	// cause, so a definitive upstream rejection is also reachable with
	// errors.Is(err, upstream.ErrGrantRejected), and a token endpoint answer
	// keeps its *oauth2.RetrieveError reachable for the oautherr predicates.
	ErrRefreshFailed = errors.New("upstream token refresh failed")

	// ErrInvalidBinding indicates token binding validation failed (e.g.,
	// subject or client ID mismatch between the stored token and the session).
	ErrInvalidBinding = errors.New("upstream token binding validation failed")

	// ErrNeedsAuthorization indicates the user has no usable connection to the
	// provider and must authorize again: there is no row, the row holds no
	// tokens, the access token is expired and cannot be refreshed, or the
	// provider rejected the refresh with invalid_grant. It is returned together
	// with its cause, which stays reachable with errors.Is.
	//
	// When only the ID token needed refreshing and the access token is still
	// live, a failed refresh, including invalid_grant, does not produce it: the
	// stored credential is returned and the failure is logged at WARN. It
	// follows when the access token expires.
	ErrNeedsAuthorization = errors.New("upstream authorization required")

	// ErrNoCanonicalUser is storage.ErrNoCanonicalUser, re-exported so callers
	// outside the authorization server can match it without importing storage.
	ErrNoCanonicalUser = storage.ErrNoCanonicalUser
)

Sentinel errors returned by Service.GetValidTokens and UserCredentialReader.GetValidTokensForUser.

Functions

This section is empty.

Types

type InProcessService

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

InProcessService implements the Service interface for in-process use. It composes storage (read) and refresher (refresh + persist) to provide a single GetValidTokens call. Concurrent-refresh deduplication is delegated to the refresher's own singleflight.Group keyed by an opaque storage-row identity, so the same Group covers both the handler's chain-walk path and the runtime token-swap path within this process.

Refresh is triggered by an expired access token or by an expired ID token (its `exp` claim, read without re-verifying the signature it was validated with when stored). The ID-token trigger serves providers whose ID-token lifetime is shorter than their access-token lifetime (e.g. Microsoft Entra ID), which would otherwise hand consumers an expired ID token for part of every access-token lifetime. It never fires when the row has no refresh token, or for an empty, unparsable or `exp`-less ID token.

It cannot help when the provider omits id_token on refresh (OIDC Core 1.0 §12.2): the expired ID token is then carried forward, and the trigger is suppressed for that row until the access token next expires so reads do not loop on refresh. After a failed ID-token-triggered refresh the trigger backs off briefly (idTokenRefreshFailureBackoff). Consumers that need a currently valid ID token must therefore still check `exp` themselves.

Suppression state is held in process memory: replicas sharing storage each keep their own, so each may perform one extra refresh per access-token lifetime for a provider that omits id_token. Likewise, refresh deduplication is per process; replicas that refresh the same row at the same moment can each redeem its refresh token (see upstreamTokenRefresher), which a provider enforcing single-use refresh-token rotation may treat as reuse. The ID-token trigger adds refresh events, but no new race shape.

func NewInProcessService

func NewInProcessService(
	stor storage.UpstreamTokenStorage,
	refresher storage.UpstreamTokenRefresher,
) *InProcessService

NewInProcessService creates a new InProcessService. The refresher may be nil if upstream token refresh is not configured; expired tokens will return ErrNoRefreshToken in that case.

func (*InProcessService) GetAllUpstreamCredentials added in v0.32.0

func (s *InProcessService) GetAllUpstreamCredentials(
	ctx context.Context, sessionID string,
) (map[string]UpstreamCredential, map[string]error, error)

GetAllUpstreamCredentials returns access tokens and ID tokens for all upstream providers in a session in a single storage round-trip. Expired access tokens are refreshed transparently; providers whose access token cannot be refreshed are included in the returned failed map, keyed by provider name with the refresh error as the value, so downstream middleware can return a clean 401 for the access-token use case. The IDToken on a returned entry is the rotated ID token when a refresh produced one (OIDC Core 1.0 §12.2), otherwise the original JWT captured at the initial OIDC login; it is not independently validated for freshness and may be empty if the upstream login never yielded one. An expired ID token also triggers a refresh (see InProcessService); a failed ID-token-triggered refresh does not put the provider in the failed map, since its access token is still valid, unless the refresher removed the row or cleared its refresh token because it could not save a rotated refresh token. Callers that PRESENT it as a credential must expect expiry to be rejected; callers that only READ ITS CLAIMS are unaffected by expiry. See Identity.UpstreamIDTokens for both consumers.

Returns an empty map and nil failed map (not error) for unknown sessions.

Unlike GetValidTokensForUser, it waits for an in-flight refresh to return even if ctx ends, because the caller may hold a generation lease on ctx until the read returns.

func (*InProcessService) GetValidTokens

func (s *InProcessService) GetValidTokens(ctx context.Context, sessionID, providerName string) (*UpstreamCredential, error)

GetValidTokens returns a valid upstream credential for a session and provider. It transparently refreshes expired access tokens using the refresh token, and refreshes expired ID tokens where possible (see InProcessService). Unlike GetValidTokensForUser, it waits for an in-flight refresh to return even if ctx ends, because the caller may hold a generation lease on ctx until the read returns.

func (*InProcessService) GetValidTokensForUser added in v0.70.0

func (s *InProcessService) GetValidTokensForUser(
	ctx context.Context, userID, providerName string,
) (*UpstreamCredential, error)

GetValidTokensForUser returns a valid upstream credential for one user and provider, refreshing an expired row. It sets the canonical user on the context, so over user-keyed storage the user's row is read whatever login session the caller has. It compares the row's UserID with userID itself before any refresh, so it is also safe over storage that is not user-keyed.

It returns, all wrapped so the cause stays reachable with errors.Is:

  • ErrSessionNotFound for an empty userID
  • ErrNeedsAuthorization (with ErrSessionNotFound, ErrNoRefreshToken or ErrRefreshFailed and its upstream.ErrGrantRejected cause) when the user has no usable connection: no row, a placeholder row, a live row with an empty access token, an expired row that cannot be refreshed, or a refresh the provider rejected with invalid_grant. A refresh that succeeds but yields an empty access token counts as a row with no access token
  • ErrInvalidBinding for a row owned by another user, whether found on the first read or during the refresh
  • ErrNoCanonicalUser (from storage, passed through) is a separate case that callers must refuse: it is not a missing connection
  • any other error for a storage failure or a transient refresh failure

When only the ID token needed refreshing and the access token is still live, a failed refresh, including invalid_grant, is not an error: the stored credential is returned and the failure is logged at WARN, because the caller never sees it. If ctx ended during the refresh, see below. Needs-authorization follows once the access token expires. The exception is a refresh after which the refresher removed the row, or cleared its refresh token, because it could not save a rotated refresh token: that needs authorization at once, unless ctx ends during the refresh. In that case this read still returns the stored credential and the next read reports needs-authorization. The refresher still logs on its own paths, so a rare refresher failure (a lost refresh race, or a row it could not delete or clear) shows up both in its own line and in this WARN.

For a failed refresh of an expired access token it adds no WARN of its own: the caller decides how loudly that failure is reported, so one failure does not produce two WARN lines. The refresher still logs on its own paths.

The read returns promptly when ctx ends, even if a refresh is in progress. A detached refresh can finish and persist the updated row in the background under the refresher's own timeout. Cancellation while waiting for an expired access token to refresh matches both ErrRefreshFailed and ctx.Err(). When only the ID token needed refreshing and ctx ends during the refresh, the read returns the stored credential with a nil error and does not re-read storage. In every ID-token-only case, if the stored access token has expired by the time the refresh fails, the read returns the refresh error instead; when ctx ended, that error also matches ErrRefreshFailed and ctx.Err(). If an ID-token-only refresh fails in the background after the caller left, the failure is logged once at WARN, and the ID-token trigger backs off only while the access token is still live. A failure that reports the row missing or owned by another user is not logged or backed off there; the next read reports it. The initial read, row-ID lookup and ID-token re-read use the caller's ctx; the refresher runs detached from its cancellation and deadline, under its own deadline of refreshWorkerTimeout. The worker's recording resolves the row ID with its own bounded context, not the caller's ctx, and shares that refreshWorkerTimeout deadline with the refresh.

Error text can include provider-supplied detail, such as an OAuth error_description. Never return it to a client. Wrapped causes stay reachable with errors.Is and errors.As.

func (*InProcessService) UserKeyed added in v0.70.0

func (s *InProcessService) UserKeyed() bool

UserKeyed reports whether the service reads storage keyed by user: the user-keyed layer itself, or a decorator above it that exposes Unwrap() storage.Storage or Unwrap() storage.UpstreamTokenStorage.

type Service

type Service interface {
	// GetValidTokens returns a valid upstream credential for a session and provider.
	// It transparently refreshes expired access tokens using the refresh token.
	// The providerName identifies which upstream provider's tokens to retrieve.
	//
	// Returns:
	//   - *UpstreamCredential on success
	//   - ErrSessionNotFound if no upstream tokens exist for the session/provider
	//   - ErrNoRefreshToken if the access token is expired and no refresh token is available
	//   - ErrRefreshFailed if the refresh attempt fails (e.g., revoked refresh token).
	//     When the upstream IdP definitively rejected the refresh with
	//     invalid_grant, the error also satisfies errors.Is(err, upstream.ErrGrantRejected);
	//     a network or 5xx failure does not. Any token endpoint answer also keeps
	//     its *oauth2.RetrieveError in the chain for the oautherr predicates; use
	//     IsRejectedRefreshGrant, not IsPermanentCredentialError, to decide
	//     whether the user must log in again.
	//
	// The returned UpstreamCredential.IDToken may be empty or expired. Callers that
	// PRESENT it as a credential (e.g. as the subject_token of an RFC 8693 token
	// exchange) must check its `exp` claim first or handle the resulting rejection;
	// callers that only READ ITS CLAIMS are unaffected by expiry. See
	// UpstreamCredential for details.
	GetValidTokens(ctx context.Context, sessionID, providerName string) (*UpstreamCredential, error)
}

Service owns the upstream token lifecycle: read, refresh, error handling.

type TokenReader added in v0.13.0

type TokenReader interface {
	// GetAllUpstreamCredentials returns the access tokens (refreshing them if
	// expired) and ID tokens for every upstream provider associated with the
	// given session ID. Returns an empty map if the session has no stored
	// upstream tokens.
	//
	// The second return value maps each provider whose access token was expired
	// and could not be refreshed (e.g. the refresh token is missing or the
	// upstream IDP rejected the refresh) to the reason, using the same sentinel
	// errors as Service.GetValidTokens. Those providers are omitted from the
	// creds map. Callers should treat a non-empty failed map as a signal to
	// return HTTP 401 + WWW-Authenticate so the client can re-authenticate. An
	// upstream that definitively rejected the refresh (the IdP answered
	// invalid_grant) satisfies errors.Is(err, upstream.ErrGrantRejected); a
	// network or 5xx failure does not. When the token endpoint answered, the
	// error also carries its *oauth2.RetrieveError, so oautherr's
	// IsPermanentCredentialError tells a structured OAuth verdict (such as
	// invalid_client) from an outage (5xx, 429, or a 4xx with no OAuth code).
	// "Permanent" means only that retrying will not help: invalid_client
	// indicts the client registration, not the refresh token, so a caller
	// deciding whether to ask the user to reconnect wants
	// oautherr.IsRejectedRefreshGrant.
	//
	// Each returned IDToken is the rotated ID token when a refresh produced
	// one (OIDC Core 1.0 §12.2), otherwise the original JWT captured at OIDC
	// login (OIDC Core 1.0 §3.1.3.7), and it may be expired. Callers that PRESENT
	// it as a credential (e.g. RFC 8693 subject-token exchange) must check `exp`
	// first or handle the resulting rejection; callers that only READ ITS CLAIMS
	// are unaffected by expiry. See UpstreamCredential for both consumers.
	//
	// Returns an empty map and nil failed map (not error) for unknown sessions.
	GetAllUpstreamCredentials(ctx context.Context, sessionID string) (
		creds map[string]UpstreamCredential, failed map[string]error, err error)
}

TokenReader retrieves upstream provider credentials for a session. This narrow interface decouples the auth middleware from storage internals.

type UpstreamCredential

type UpstreamCredential struct {
	AccessToken string
	IDToken     string
}

UpstreamCredential bundles the access token and the ID token for a single upstream provider. Access tokens are refreshed when expired.

The IDToken is the rotated ID token when a refresh produced one (OIDC Core 1.0 §12.2 permits but does not require a new id_token on refresh), otherwise the original JWT captured at the initial OIDC login (OIDC Core 1.0 §3.1.3.7). InProcessService refreshes when the stored ID token has expired, so it is usually current, but it is not guaranteed to be: it can still be expired when the provider omits id_token on refresh or the refresh fails.

Callers that PRESENT it as a credential — e.g. as the subject_token of an RFC 8693 token exchange — are subject to expiry and must either check its `exp` claim first or handle the resulting rejection. Today's such consumer (pkg/vmcp/auth/strategies) deliberately takes the second option: it lets the IdP reject the exchange and surfaces the `invalid_grant`. Note also that the ID token's `aud` is this auth server's client registration with the issuing upstream, not the token-exchange endpoint — whether a target authorization server accepts it as a subject token is governed by that server's policy and is typically limited to the same issuer/audience.

Callers that only READ ITS CLAIMS are a different case and deliberately do not check `exp`: the token is then evidence of what the upstream asserted at login, and expiry says nothing about whether that assertion happened. See Identity.UpstreamIDTokens for the two consumers and why they differ.

IDToken may be empty when the upstream login did not return an id_token (e.g. the provider was not asked for the openid scope). An empty IDToken is a legitimate state, not an error. Note that Identity.UpstreamTokens and Identity.UpstreamIDTokens are projected independently and are NOT guaranteed to share the same key set: a provider with an access token but no ID token appears only in UpstreamTokens.

type UserCredentialReader added in v0.70.0

type UserCredentialReader interface {
	// GetValidTokensForUser returns a valid upstream credential for userID and
	// providerName, refreshing an expired access token. It returns
	// ErrNeedsAuthorization when the user must connect the provider again,
	// ErrInvalidBinding for a row owned by another user, ErrSessionNotFound for
	// an empty userID, ErrNoCanonicalUser (passed through from storage, not a
	// missing connection) when the storage cannot resolve a user, and any other
	// error for an infrastructure failure.
	//
	// The read returns promptly when ctx ends; an in-flight detached refresh
	// can finish and persist the updated row in the background. Error text can
	// include detail the provider supplied: never return it to a client.
	// Wrapped causes stay reachable with errors.Is and errors.As. If ctx ends
	// while an expired access token is being refreshed, the error matches both
	// ErrRefreshFailed and ctx.Err().
	//
	// When only the ID token needed refreshing and the access token is still
	// live, a failed refresh, including invalid_grant, returns the stored
	// credential and is logged at WARN; needs-authorization follows once the
	// access token expires. If the stored access token has expired by the time
	// the refresh fails, the read returns the refresh error instead. The
	// exception is ctx ending during that refresh: the read then returns the
	// stored credential with no error, or, if the access token has expired in
	// the meantime, an error matching both ErrRefreshFailed and ctx.Err(). A
	// later failure of that refresh is logged once at WARN and backs off the
	// ID-token refresh while the access token is live, unless it reports the
	// row missing or owned by another user. A refresh after which the refresher
	// removed or cleared the row, because it could not save a rotated refresh
	// token, needs authorization at once, unless ctx ends during the refresh:
	// that read still returns the stored credential and the next read reports
	// needs-authorization. See InProcessService.GetValidTokensForUser for the
	// full contract.
	GetValidTokensForUser(ctx context.Context, userID, providerName string) (*UpstreamCredential, error)
}

UserCredentialReader retrieves one user's upstream credential for one provider, independent of any login session.

type UserKeyedReader added in v0.70.0

type UserKeyedReader interface {
	// UserKeyed reports whether the reader's storage is keyed by user.
	UserKeyed() bool
}

UserKeyedReader is implemented by a TokenReader that reads upstream tokens from storage keyed by user (the user-keyed layer of the embedded authorization server). auth.NewTokenValidator uses it to refuse, at startup, a validator that could not load such tokens for an interactive session.

A TokenReader that wraps another must implement it and forward the wrapped reader's answer; otherwise the validator cannot see the user-keyed storage behind it, and a misconfiguration only shows up at request time.

Directories

Path Synopsis
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.

Jump to

Keyboard shortcuts

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