oauth

package
v5.34.13 Latest Latest
Warning

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

Go to latest
Published: Oct 1, 2026 License: Apache-2.0 Imports: 26 Imported by: 0 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 oauth implements OAuth 2.1 proxy functionality for remote MCP server authentication.

This package provides the server-side OAuth client and proxy implementation that allows the Muster Server to authenticate with remote MCP servers on behalf of users without exposing sensitive tokens to the Muster Agent.

Architecture

The OAuth proxy follows a three-legged OAuth 2.1 Authorization Code flow:

  1. User requests a tool that requires authentication
  2. Muster Server detects 401 Unauthorized from the remote MCP server
  3. Muster Server generates an authorization URL and returns "Auth Required" challenge
  4. User authenticates via their browser with the Identity Provider
  5. Browser redirects to Muster Server's callback endpoint with authorization code
  6. Muster Server exchanges code for tokens and stores them securely
  7. User retries the original request, which now succeeds with the stored token

Components

  • TokenStore: In-memory storage for OAuth tokens, indexed by session and issuer
  • StateStore: Manages OAuth state parameters for CSRF protection
  • ClientCredentialStore: Issuer-keyed storage for DCR-issued client credentials
  • Client: Handles OAuth flows, code exchange, and token refresh
  • Handler: HTTP handler for the /oauth/callback endpoint
  • Manager: Coordinates OAuth flows and integrates with the aggregator

Client Identification (CIMD vs DCR)

Muster identifies itself to upstream authorization servers per issuer, in this order:

  1. CIMD: when the AS metadata advertises client_id_metadata_document_supported, muster's self-hosted Client ID Metadata Document URL is used as client_id. This is stateless, secret-free, and portable across authorization servers (SEP-2352).
  2. DCR: otherwise, when the AS advertises a registration_endpoint, muster registers itself once via RFC 7591 Dynamic Client Registration (requesting token_endpoint_auth_method "none" and sending application_type "web" per SEP-837, with no scope — RFC 7591 makes it optional and ASes reject scopes they don't know) and uses the issued credentials. Credentials are keyed by issuer and stored in the ClientCredentialStore (in-memory by default, Valkey-backed when configured) — they are never reused against a different issuer.
  3. Fallback: when the AS advertises neither, the CIMD URL is sent anyway (some servers resolve CIMDs without advertising the flag). The auth challenge marks this case ("cimd-fallback") so front-ends can warn that the AS may reject the sign-in. A rejected registration falls back the same way but is marked "dcr-failed", with the AS's rejection carried in the challenge message.

The resolved client_id (and secret, if any) is used consistently across the authorization request, the authorization-code exchange, and mcp-go's transport-level token refresh.

Security

## Token Storage

By default, tokens are stored in-memory and are lost when the Muster Server restarts. When Valkey storage is configured (storage.type: valkey), tokens are persisted in Valkey, surviving pod restarts and enabling multi-pod deployments without sticky sessions.

The TokenStorer and StateStorer interfaces allow swapping between in-memory (default) and Valkey-backed implementations via functional options on the Manager constructor.

## Encryption at Rest (Valkey)

When using Valkey storage, token values (access tokens, refresh tokens, ID tokens, and OAuth state including code verifiers) are encrypted at rest using AES-256-GCM if an encryption key is configured (oauthServer.encryptionKey or encryptionKeyFile). The same key protects both the mcp-oauth server stores and the OAuth proxy stores.

Production deployments using Valkey MUST:

  • Configure an AES-256 encryption key (32 bytes, base64-encoded)
  • Enable TLS for Valkey connections (storage.valkey.tlsEnabled: true)
  • Use Valkey ACLs to restrict access to the muster key prefix
  • Ensure the Valkey storage volume is encrypted (e.g., via StorageClass)

Without encryption, a Valkey compromise (unauthorized access, RDB dump exfiltration, or replication snooping) exposes all stored tokens in plaintext.

## Session Isolation

Tokens are stored with a composite key of (SessionID, Issuer, Scope), where SessionID is the mcp-oauth token family ID. Each login creates a new token family, so tokens are isolated per login session. Logout on device A does not affect device B's tokens. Each token entry also records the owning user ID (sub claim) for bulk operations like "sign out everywhere".

For stdio transport (single-user CLI), a default session ID is used. This is acceptable since stdio is inherently single-user (one process = one user).

## TLS/HTTPS Requirements (CRITICAL)

Production deployments MUST use HTTPS for all OAuth-related endpoints:

  • Muster Server's public URL (oauth.publicUrl configuration): The OAuth callback endpoint receives authorization codes. Without HTTPS, attackers could intercept these codes and exchange them for tokens.

  • OAuth Issuer URLs: All communication with Identity Providers (metadata discovery, token exchange, token refresh) must be over HTTPS. The issuer's TLS certificate provides integrity and authenticity guarantees for OAuth metadata.

  • Remote MCP Server URLs: When MCP servers require OAuth authentication, their endpoints should use HTTPS to protect the bearer tokens in Authorization headers.

Without TLS, the following attacks become possible:

  • Authorization code interception during OAuth callback
  • Token theft via man-in-the-middle attacks
  • Metadata manipulation to redirect token exchanges to malicious endpoints
  • Bearer token theft from Authorization headers

## Rate Limiting Recommendations

The OAuth callback endpoint (/oauth/callback by default) should be protected by rate limiting at the infrastructure level (ingress controller, load balancer, or API gateway). Recommended limits:

  • Per-IP rate limit: 10-20 requests per minute
  • Global rate limit: 100-500 requests per minute (depending on expected user base)

Rate limiting protects against:

  • Denial of service attacks on the OAuth callback endpoint
  • Brute-force attempts to guess authorization codes or state parameters
  • Resource exhaustion from excessive token exchange requests

Example Kubernetes Ingress annotation (nginx):

nginx.ingress.kubernetes.io/limit-rps: "10"
nginx.ingress.kubernetes.io/limit-connections: "5"

## Logging Security

Session IDs are truncated in log output to prevent full session identifiers from appearing in logs. Only the first 8 characters are logged (e.g., "abc12345..."). Access tokens and refresh tokens are never logged.

Token refresh operations are logged at INFO level for operational monitoring, including duration metrics for performance tracking.

SSO Support

The package supports Single Sign-On (SSO) through Token Forwarding and Token Exchange. When a user authenticates with muster, the token can be forwarded to downstream servers (Token Forwarding) or exchanged for a token valid on a remote IdP (Token Exchange).

Index

Constants

View Source
const (
	// ClientIDMethodCIMD: the AS advertises
	// client_id_metadata_document_supported, so muster's self-hosted CIMD URL
	// is used as client_id (stateless, spec-preferred).
	ClientIDMethodCIMD = "cimd"

	// ClientIDMethodDCR: the AS does not advertise CIMD support but offers a
	// registration_endpoint; muster registered itself via RFC 7591 and uses
	// the issued, issuer-bound credentials.
	ClientIDMethodDCR = "dcr"

	// ClientIDMethodCIMDFallback: the AS advertises neither CIMD support nor
	// a registration endpoint. Muster sends the CIMD URL anyway (some ASes
	// resolve CIMDs without advertising the flag), but the AS may reject the
	// flow with a client-not-registered error.
	ClientIDMethodCIMDFallback = "cimd-fallback"

	// ClientIDMethodDCRFailed: the AS advertises a registration endpoint but
	// rejected muster's RFC 7591 registration request. Muster sends the CIMD
	// URL anyway, like the plain fallback, but the challenge carries the
	// rejection so front-ends can show the real reason instead of claiming
	// the AS supports neither mechanism.
	ClientIDMethodDCRFailed = "dcr-failed"
)

Client identification methods, reported on auth challenges so front-ends can tell users how muster identifies itself to the authorization server.

View Source
const ClientIDMethodPreregistered = "preregistered"

ClientIDMethodPreregistered marks a client the operator registered with the authorization server out of band (spec.auth.authorizationServer. clientCredentialsSecretRef): the only way in against an authorization server that supports neither CIMD nor RFC 7591, GitHub being the case.

View Source
const DefaultOIDCScopes = "openid profile email groups"

DefaultOIDCScopes is the default set of scopes requested for OIDC token exchange. These scopes provide identity (openid), user profile info (profile, email), and group membership (groups) for RBAC decisions.

View Source
const DefaultTokenStoreTTL = 30 * 24 * time.Hour

DefaultTokenStoreTTL is the session-level TTL for OAuth token entries in Valkey. Matching the capability store TTL (30 days) so tokens survive inactivity. Tokens self-expire based on their ExpiresAt; this TTL is only for Valkey key garbage collection of abandoned sessions.

View Source
const LoginIDTokenScope = "urn:muster:login-id-token" //nolint:gosec // G101: a scope token that names a slot, not a credential

LoginIDTokenScope is the scope the session's login ID token is filed under in the token store (see api.LoginTokenMirror): a scope token no authorization server grants, so the entry never shares a key with a proxy grant from the same issuer.

Variables

This section is empty.

Functions

func GetExpectedIssuer

func GetExpectedIssuer(config *api.TokenExchangeConfig) string

GetExpectedIssuer returns the expected issuer URL for token validation. If ExpectedIssuer is explicitly set in the config, it is used directly. Otherwise, the issuer is derived from DexTokenEndpoint (backward compatible).

This separation is important for proxied access scenarios:

Types

type Adapter

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

Adapter implements api.OAuthHandler by wrapping the OAuth Manager. This follows the service locator pattern where packages communicate through interfaces defined in the api package.

func NewAdapter

func NewAdapter(manager *Manager) *Adapter

NewAdapter creates a new OAuth API adapter wrapping the given manager.

func (*Adapter) ClearTokenByIssuer

func (a *Adapter) ClearTokenByIssuer(sessionID, issuer string)

ClearTokenByIssuer removes all tokens for a given session and issuer.

func (*Adapter) ClearTokenByIssuerForUser

func (a *Adapter) ClearTokenByIssuerForUser(sessionID, userID, issuer string)

ClearTokenByIssuerForUser implements api.SubjectGrantHandler.

func (*Adapter) CreateAuthChallenge

func (a *Adapter) CreateAuthChallenge(ctx context.Context, params api.AuthChallengeParams) (*api.AuthChallenge, error)

CreateAuthChallenge creates an authentication challenge for a 401 response.

func (*Adapter) DeleteTokensBySession

func (a *Adapter) DeleteTokensBySession(sessionID string)

DeleteTokensBySession removes all downstream tokens for a given session.

func (*Adapter) DeleteTokensByUser

func (a *Adapter) DeleteTokensByUser(userID string)

DeleteTokensByUser removes all downstream tokens for a given user across all sessions.

func (*Adapter) ExchangeTokenForRemoteCluster

func (a *Adapter) ExchangeTokenForRemoteCluster(ctx context.Context, localToken, userID string, config *api.TokenExchangeConfig) (string, error)

ExchangeTokenForRemoteCluster exchanges a local token for one valid on a remote cluster. This implements RFC 8693 Token Exchange for cross-cluster SSO scenarios.

func (*Adapter) FindTokenWithIDToken

func (a *Adapter) FindTokenWithIDToken(sessionID string) *api.OAuthToken

FindTokenWithIDToken searches for any token in the session that has an ID token. This is used as a fallback when the muster issuer is not explicitly configured.

func (*Adapter) GetCIMDHandler

func (a *Adapter) GetCIMDHandler() http.HandlerFunc

GetCIMDHandler returns the HTTP handler for serving the CIMD.

func (*Adapter) GetCIMDPath

func (a *Adapter) GetCIMDPath() string

GetCIMDPath returns the path for serving the CIMD.

func (*Adapter) GetCallbackPath

func (a *Adapter) GetCallbackPath() string

GetCallbackPath returns the configured callback path.

func (*Adapter) GetClientCredentialsForIssuer

func (a *Adapter) GetClientCredentialsForIssuer(ctx context.Context, issuer string) (clientID, clientSecret string)

GetClientCredentialsForIssuer returns the client_id and client_secret the OAuth flows use against the given issuer, without triggering a new registration.

func (*Adapter) GetFullTokenByIssuer

func (a *Adapter) GetFullTokenByIssuer(sessionID, issuer string) *api.OAuthToken

GetFullTokenByIssuer retrieves the full token (including ID token if available) for the given session and issuer. Returns nil if no valid token exists.

func (*Adapter) GetFullTokenByIssuerForUser

func (a *Adapter) GetFullTokenByIssuerForUser(sessionID, userID, issuer string) *api.OAuthToken

GetFullTokenByIssuerForUser implements api.SubjectGrantHandler.

func (*Adapter) GetHTTPHandler

func (a *Adapter) GetHTTPHandler() http.Handler

GetHTTPHandler returns the HTTP handler for OAuth callback endpoints.

func (*Adapter) GetStartHandler

func (a *Adapter) GetStartHandler() http.HandlerFunc

GetStartHandler returns the HTTP handler for the OAuth proxy start endpoint.

func (*Adapter) GetStartPath

func (a *Adapter) GetStartPath() string

GetStartPath returns the path of the OAuth proxy start endpoint.

func (*Adapter) GetToken

func (a *Adapter) GetToken(sessionID, serverName string) *api.OAuthToken

GetToken retrieves a valid token for the given session and server.

func (*Adapter) GetTokenByIssuer

func (a *Adapter) GetTokenByIssuer(sessionID, issuer string) *api.OAuthToken

GetTokenByIssuer retrieves a valid token for the given session and issuer.

func (*Adapter) IsEnabled

func (a *Adapter) IsEnabled() bool

IsEnabled returns whether OAuth proxy functionality is active.

func (*Adapter) IssuerSubjectScoped

func (a *Adapter) IssuerSubjectScoped(issuer string) bool

IssuerSubjectScoped implements api.SubjectGrantHandler.

func (*Adapter) LoginIDToken

func (a *Adapter) LoginIDToken(sessionID, issuer string) *api.OAuthToken

LoginIDToken implements api.LoginTokenMirror.

func (*Adapter) PinIssuer

func (a *Adapter) PinIssuer(issuer string, pin api.IssuerPin)

PinIssuer implements api.IssuerPinner.

func (*Adapter) ProbeTokenEndpoint added in v5.34.9

func (a *Adapter) ProbeTokenEndpoint(ctx context.Context, config *api.TokenExchangeConfig) error

ProbeTokenEndpoint implements api.TokenEndpointProber.

func (*Adapter) Register

func (a *Adapter) Register()

Register registers this adapter with the API layer.

func (*Adapter) RegisterServer

func (a *Adapter) RegisterServer(serverName, issuer, scope string)

RegisterServer registers OAuth configuration for a remote MCP server.

func (*Adapter) SetAuthCompletionCallback

func (a *Adapter) SetAuthCompletionCallback(callback api.AuthCompletionCallback)

SetAuthCompletionCallback sets the callback to be called after successful authentication.

func (*Adapter) ShouldServeCIMD

func (a *Adapter) ShouldServeCIMD() bool

ShouldServeCIMD returns true if muster should serve its own CIMD.

func (*Adapter) Stop

func (a *Adapter) Stop()

Stop stops the OAuth handler and cleans up resources.

func (*Adapter) StoreLoginIDToken

func (a *Adapter) StoreLoginIDToken(sessionID, userID, issuer, idToken string, expiresAt time.Time)

StoreLoginIDToken implements api.LoginTokenMirror.

func (*Adapter) StoreToken

func (a *Adapter) StoreToken(sessionID, userID, issuer string, token *api.OAuthToken)

StoreToken persists a token for the given session and issuer.

func (*Adapter) SubjectGrantForRelease

func (a *Adapter) SubjectGrantForRelease(ctx context.Context, userID, issuer string) *api.OAuthToken

SubjectGrantForRelease implements api.GrantReleaser.

func (*Adapter) UnpinIssuer

func (a *Adapter) UnpinIssuer(issuer string)

UnpinIssuer implements api.IssuerPinner.

type AuthChallengeParams

type AuthChallengeParams struct {
	// SessionID links the OAuth flow to the caller's login session.
	SessionID string

	// UserID is the authenticated user's identity (sub claim).
	UserID string

	// ServerName is the MCP server that requires authentication.
	ServerName string

	// Issuer is the authorization server the flow runs against.
	Issuer string

	// Resource is the canonical URI of the MCP server the token is for. It
	// goes on the authorization request and on the token request (RFC 8707).
	Resource string

	// Scope is the space-separated scope list to request.
	Scope string

	// ResetClientRegistration discards muster's stored RFC 7591 registration
	// with the issuer before the flow starts, so muster registers again.
	ResetClientRegistration bool
}

AuthChallengeParams carries the per-flow values a proxy authentication challenge is built from. The fields are grouped in a struct because they are all strings: a transposed pair, such as resource and scope, would fail only at the authorization server.

type AuthCompletionCallback

type AuthCompletionCallback func(ctx context.Context, sessionID, userID, serverName, accessToken string) error

AuthCompletionCallback is called after successful OAuth authentication.

type AuthRequiredResponse

type AuthRequiredResponse struct {
	// Status indicates this is an auth required response.
	Status string `json:"status"` // "auth_required"

	// AuthURL is the OAuth authorization URL the user should visit.
	AuthURL string `json:"auth_url"`

	// ServerName is the name of the MCP server requiring authentication.
	ServerName string `json:"server_name,omitempty"`

	// Message is a human-readable description of why auth is needed.
	Message string `json:"message,omitempty"`

	// ClientIDMethod reports how muster identifies itself to the
	// authorization server for this flow: "cimd" (AS advertises CIMD
	// support), "dcr" (RFC 7591 registered credentials), "cimd-fallback"
	// (neither advertised — the AS may reject the sign-in), or "dcr-failed"
	// (the AS rejected muster's registration; the CIMD URL is sent anyway).
	ClientIDMethod string `json:"client_id_method,omitempty"`
}

AuthRequiredResponse represents an authentication challenge returned when a remote MCP server requires OAuth authentication. Note: This is different from pkgoauth.AuthChallenge which represents parsed WWW-Authenticate header data. This is a user-facing response.

type AuthServerConfig

type AuthServerConfig struct {
	ServerName string
	Issuer     string
	Scope      string
}

AuthServerConfig holds OAuth configuration for a specific remote MCP server.

type BrokerExchanger

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

BrokerExchanger implements mcp-oauth's server.Exchanger on top of muster's TokenExchanger, turning muster into a shared RFC 8693 token broker: an external confidential client (e.g. a developer-portal backend) presents a subject token plus an audience name and receives a token issued by the audience's downstream OIDC/Dex token endpoint.

mcp-oauth owns subject-token validation (TrustedIssuers), client authentication, the per-client audience allowlist (Config.TokenExchangeClientAudiences), and audit. BrokerExchanger owns the audience → target dispatch and the downstream exchange.

The exchanger instance is deliberately separate from the OAuth manager's internal SSO exchanger: broker targets carry their own scope sets (e.g. the Dex cross-client scope for kube-apiserver-bound audiences), and sharing the cache with the internal SSO path could serve a token issued with different scopes for the same (endpoint, connector, user) key.

Thread-safe: Yes.

func NewBrokerExchanger

func NewBrokerExchanger(cfg config.TokenExchangeBrokerConfig) *BrokerExchanger

NewBrokerExchanger creates a BrokerExchanger for the configured targets.

func (*BrokerExchanger) Exchange

Exchange maps the requested audience to its downstream token endpoint and performs the RFC 8693 exchange, forwarding the (already validated) subject token verbatim. Unknown audiences return errors wrapping server.ErrInvalidTarget so the client receives invalid_target.

Cache keying: req.Subject.Subject (the impersonated identity) is used as TokenExchanger's UserID. Do NOT substitute the actor subject here: if two different impersonated subjects were keyed on the same actor, the cache would serve the first subject's token to the second caller. Authorization is enforced upstream by mcp-oauth before Exchange is called.

type Client

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

Client handles OAuth 2.1 flows for remote MCP server authentication.

func NewClient

func NewClient(clientID, publicURL, callbackPath, cimdScopes string, opts ...ClientOption) *Client

NewClient creates a new OAuth client with the given configuration. By default, in-memory stores are used. Use WithTokenStorer / WithStateStorer to inject Valkey-backed implementations.

func (*Client) DeleteByIssuerForUser

func (c *Client) DeleteByIssuerForUser(sessionID, userID, issuer string)

DeleteByIssuerForUser removes the session's tokens for an issuer and, for a subject-scoped issuer, the person's grant as well: an explicit sign-out from the server disconnects the person, not just this session.

func (*Client) DiscoverMetadata

func (c *Client) DiscoverMetadata(ctx context.Context, issuer string) (*pkgoauth.Metadata, error)

DiscoverMetadata fetches OAuth metadata for an issuer. This is exposed for external access to metadata discovery.

func (*Client) ExchangeCode

func (c *Client) ExchangeCode(ctx context.Context, code, codeVerifier, issuer, resource, requestedScope string) (*pkgoauth.Token, error)

ExchangeCode exchanges an authorization code for tokens. resource is the RFC 8707 indicator recorded with the flow's state; it must match the value sent on the authorization request. requestedScope is the scope the authorization request asked for: an authorization server that omits `scope` from its token response granted exactly that (RFC 6749 §5.1), so the token is recorded with it. Dex omits the parameter; without this every Dex grant was filed under an empty scope -- the token-store key of the session's own login token when the pinned issuer is muster's IdP (giantswarm/muster#1174).

An invalid_client answer from the token endpoint means the AS no longer accepts the DCR credentials the flow was started with; they are dropped so the next sign-in registers muster again instead of failing the same way.

func (*Client) ForgetRegistrationOnAuthorizationError

func (c *Client) ForgetRegistrationOnAuthorizationError(issuer, errorCode string)

ForgetRegistrationOnAuthorizationError drops the stored DCR credentials for the issuer when an authorization response reports invalid_client: the AS redirected the refusal of muster's client identification to the callback, so the registration it refers to is dead. Other error codes (access_denied, invalid_scope, ...) say nothing about the registration and change nothing.

func (*Client) GenerateAuthURL

func (c *Client) GenerateAuthURL(ctx context.Context, params AuthChallengeParams) (string, *resolvedClient, error)

GenerateAuthURL creates an OAuth authorization URL for user authentication. Returns the URL and the resolved client identification (its Method is one of the ClientIDMethod* constants). The code verifier is stored with the state for later retrieval.

params.Resource is recorded with the state so the token request carries the same RFC 8707 value as the authorization request.

func (*Client) GetByIssuerForUser

func (c *Client) GetByIssuerForUser(sessionID, userID, issuer string) *pkgoauth.Token

GetByIssuerForUser is the issuer-only lookup with subject-scoped grants, see GetTokenForUser.

func (*Client) GetCIMDURL

func (c *Client) GetCIMDURL() string

GetCIMDURL returns the URL where the Client ID Metadata Document is served. This is derived from the clientID which is expected to be the CIMD URL.

func (*Client) GetClientCredentialsForIssuer

func (c *Client) GetClientCredentialsForIssuer(ctx context.Context, issuer string) (clientID, clientSecret string)

GetClientCredentialsForIssuer returns the client_id and client_secret the OAuth flows use against the given issuer, without triggering a new DCR registration. This backs mcp-go's transport-level token refresh, which must present the same client identification the token was issued under.

func (*Client) GetClientMetadata

func (c *Client) GetClientMetadata() *pkgoauth.ClientMetadata

GetClientMetadata returns the Client ID Metadata Document for this client. ApplicationType "web" is included per SEP-837: authorization servers that resolve the CIMD and synthesize a registration would otherwise apply an OIDC default that can reject non-localhost redirect URIs.

func (*Client) GetRedirectURI

func (c *Client) GetRedirectURI() string

GetRedirectURI returns the full redirect URI for OAuth callbacks.

func (*Client) GetRegistrationMetadata

func (c *Client) GetRegistrationMetadata() *pkgoauth.ClientMetadata

GetRegistrationMetadata returns the RFC 7591 client metadata muster sends on Dynamic Client Registration requests. It mirrors the CIMD content but omits client_id (forbidden on registration requests) and requests token_endpoint_auth_method "none" — muster is a public client protected by PKCE, and staying secret-free keeps the DCR path as close to the CIMD path as the AS allows. ASes that insist on issuing a secret still can; the response's client_secret is honored either way.

scope is omitted as well: RFC 7591 makes it optional, and ASes reject registrations naming scopes they don't know (Miro answers invalid_client_metadata for the dex-oriented CIMD scopes). The authorization request carries the per-server scope discovered from the protected-resource metadata, so registration never needs one.

func (*Client) GetStartURL

func (c *Client) GetStartURL(encodedState string) string

GetStartURL returns the muster-hosted start URL for an encoded state. The browser is redirected from there to the upstream authorization server.

func (*Client) GetStateStore

func (c *Client) GetStateStore() StateStorer

GetStateStore returns the state store for external access.

func (*Client) GetToken

func (c *Client) GetToken(sessionID, issuer, scope string) *pkgoauth.Token

GetToken retrieves a valid token for the given session and issuer. Returns nil if no valid token exists.

func (*Client) GetTokenForUser

func (c *Client) GetTokenForUser(sessionID, userID, issuer, scope string) *pkgoauth.Token

GetTokenForUser is GetToken with subject-scoped grants: for an issuer pinned with grantScope: subject the person's grant is the canonical token -- refreshed on the way when it is due (see SubjectGrant) -- and the session's own copy is consulted only when the person holds no grant. For every other issuer the session's token is returned as before.

func (*Client) GetTokenStore

func (c *Client) GetTokenStore() TokenStorer

GetTokenStore returns the token store for external access.

func (*Client) IssuerSubjectScoped

func (c *Client) IssuerSubjectScoped(issuer string) bool

IssuerSubjectScoped is the exported form of subjectScoped: whether the operator pinned the issuer with grantScope: subject.

func (*Client) PinIssuer

func (c *Client) PinIssuer(issuer string, pin IssuerPin, metadata *pkgoauth.Metadata)

PinIssuer records the operator's description of an authorization server: the pre-registered client to identify with, whether its grants are subject-scoped, and -- for an AS without a discovery document -- its metadata. Calling it again for the same issuer replaces the pin, which is how a rotated client secret takes effect.

func (*Client) ResetClientRegistration

func (c *Client) ResetClientRegistration(issuer string) bool

ResetClientRegistration discards whatever DCR credentials are stored for the issuer, so the next flow registers muster again. This is the explicit escape hatch (core_auth_login with reset_client_registration) for an AS whose refusal the automatic checks cannot see. Returns whether credentials were stored.

func (*Client) Stop

func (c *Client) Stop()

Stop stops background cleanup goroutines.

func (*Client) StoreToken

func (c *Client) StoreToken(sessionID, userID string, token *pkgoauth.Token)

StoreToken stores a token in the token store. A token from a subject-scoped issuer is filed under the person's identity as well, so any later session of the same person reuses it (see GetTokenForUser).

func (*Client) SubjectGrant

func (c *Client) SubjectGrant(ctx context.Context, userID, issuer string) *pkgoauth.Token

SubjectGrant returns the person's grant for a subject-scoped issuer, refreshed when it has expired or is about to. The grant filed under the subject key is the canonical copy: it is what gets refreshed, and the rotated token is written back to it and to every session copy of the person, so no session redeems the old refresh token again (GitHub rotates refresh tokens on use and rejects a second redemption). Refreshes are single-flighted per person and issuer, and the store is re-read inside the flight, so concurrent lookups -- several sessions, several tool calls -- cost one token request.

Returns nil when the person holds no grant, when the grant has expired and carries no refresh token, or when the authorization server rejected the refresh token; in the last case the grant is removed for the person, so the next use starts a fresh sign-in instead of retrying a dead token.

func (*Client) UnpinIssuer

func (c *Client) UnpinIssuer(issuer string)

UnpinIssuer forgets the operator's description of an authorization server: the pre-registered client, the grant scope and any pinned metadata. The next flow against the issuer discovers the AS again and identifies to it as it would without a pin. Called when no MCPServer describes the issuer any more, or before a changed description is recorded.

type ClientCredentialStore

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

ClientCredentialStore provides thread-safe in-memory storage for DCR-issued client credentials, keyed by issuer. Registrations represent muster itself (not a user or session), so there is one entry per authorization server. Losing the store on restart is harmless: the next auth flow simply registers again.

func NewClientCredentialStore

func NewClientCredentialStore() *ClientCredentialStore

NewClientCredentialStore creates a new in-memory client credential store.

func (*ClientCredentialStore) Delete

func (s *ClientCredentialStore) Delete(issuer string)

Delete removes the credentials for the issuer.

func (*ClientCredentialStore) Get

Get returns the credentials for the issuer, or nil if absent or expired.

func (*ClientCredentialStore) Stop

func (s *ClientCredentialStore) Stop()

Stop is a no-op for the in-memory store.

func (*ClientCredentialStore) Store

func (s *ClientCredentialStore) Store(issuer string, creds *pkgoauth.ClientCredentials)

Store saves credentials for the issuer, replacing any previous entry.

type ClientCredentialStorer

type ClientCredentialStorer interface {
	// Get returns the credentials registered with the given issuer, or nil
	// when none are stored or the stored secret has expired.
	Get(issuer string) *pkgoauth.ClientCredentials

	// Store saves credentials for the issuer, replacing any previous entry.
	Store(issuer string, creds *pkgoauth.ClientCredentials)

	// Delete removes the credentials for the issuer (e.g. after the AS
	// stopped accepting them, so the next flow re-registers).
	Delete(issuer string)

	// Stop releases resources (background goroutines, connections, etc.).
	Stop()
}

ClientCredentialStorer is the interface for issuer-keyed OAuth client credentials obtained via Dynamic Client Registration (RFC 7591). Implementations must be safe for concurrent use.

Per SEP-2352 credentials are bound to the issuer they were registered with; there is deliberately no way to look up credentials without naming the issuer.

type ClientOption

type ClientOption func(*Client)

ClientOption configures optional Client parameters.

func WithClientCredentialStorer

func WithClientCredentialStorer(cs ClientCredentialStorer) ClientOption

WithClientCredentialStorer sets a custom ClientCredentialStorer implementation (e.g., Valkey-backed) for DCR-issued client credentials.

func WithStateStorer

func WithStateStorer(ss StateStorer) ClientOption

WithStateStorer sets a custom StateStorer implementation (e.g., Valkey-backed).

func WithTokenStorer

func WithTokenStorer(ts TokenStorer) ClientOption

WithTokenStorer sets a custom TokenStorer implementation (e.g., Valkey-backed).

type CompletedFlow

type CompletedFlow struct {
	ServerName  string `json:"srv"`
	RedirectURI string `json:"ru,omitempty"`
}

CompletedFlow is what a duplicate callback delivery needs to re-render a completed flow's outcome: the server name for the success page and the allowlist-validated post-login redirect target, if the flow recorded one. Deliberately no tokens, code verifier, or session identifiers.

type ExchangeRequest

type ExchangeRequest struct {
	// Config is the token exchange configuration for the target cluster.
	// Uses the API type directly to avoid duplication (DRY principle).
	Config *api.TokenExchangeConfig

	// SubjectToken is the local token to exchange (ID token or access token).
	SubjectToken string

	// SubjectTokenType specifies whether SubjectToken is an ID token or access token.
	// Use oidc.TokenTypeIDToken or oidc.TokenTypeAccessToken.
	// Defaults to TokenTypeIDToken if not specified.
	SubjectTokenType string

	// UserID is extracted from the validated subject token's "sub" claim.
	// CRITICAL: This must come from validated JWT claims, not user input.
	// Used for cache key generation.
	UserID string
}

ExchangeRequest contains the parameters for a token exchange operation.

type ExchangeResult

type ExchangeResult struct {
	// AccessToken is the exchanged token valid on the remote cluster.
	AccessToken string

	// IssuedTokenType is the type of the issued token.
	IssuedTokenType string

	// ExpiresAt is the exchanged token's expiry. Derived from the token
	// endpoint's expires_in (or, failing that, the token's exp claim).
	// Zero when neither is available.
	ExpiresAt time.Time

	// FromCache indicates whether the token was served from cache.
	FromCache bool
}

ExchangeResult contains the result of a successful token exchange.

type Handler

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

Handler provides HTTP handlers for OAuth callback endpoints.

func NewHandler

func NewHandler(client *Client) *Handler

NewHandler creates a new OAuth HTTP handler.

func (*Handler) HandleCallback

func (h *Handler) HandleCallback(w http.ResponseWriter, r *http.Request)

HandleCallback handles the OAuth callback endpoint. This is called by the browser after the user authenticates with the IdP.

The RFC 9207 `iss` check runs before anything else is read from the response: an authorization response that does not come from the expected authorization server is rejected whole, including its error parameters.

func (*Handler) HandleStart

func (h *Handler) HandleStart(w http.ResponseWriter, r *http.Request)

HandleStart handles the OAuth proxy start endpoint. Auth challenges point the browser here; it redirects to the upstream authorization URL stored with the flow's state. An optional "redirect" query parameter, validated against the operator allowlist, is recorded on the state so a successful callback sends the browser there instead of the static success page. An unacceptable redirect target is dropped (the login still proceeds).

func (*Handler) ServeCIMD

func (h *Handler) ServeCIMD(w http.ResponseWriter, r *http.Request)

ServeCIMD handles GET requests to serve the Client ID Metadata Document (CIMD). This allows muster to self-host its own CIMD without requiring external static hosting. The CIMD is dynamically generated from the OAuth configuration.

func (*Handler) ServeHTTP

func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler for the OAuth handler.

func (*Handler) SetManager

func (h *Handler) SetManager(manager *Manager)

SetManager sets the manager reference for callback handling. This is called by the Manager after creating the Handler.

func (*Handler) SetPostLoginRedirectAllowlist

func (h *Handler) SetPostLoginRedirectAllowlist(prefixes []*url.URL)

SetPostLoginRedirectAllowlist sets the operator-configured URL prefixes the start endpoint accepts as post-login redirect targets. An empty list keeps the static success page for every flow.

type IssuerPin

type IssuerPin struct {
	ClientID      string
	ClientSecret  string
	SubjectScoped bool

	// ExpectedIssuer is what a present iss on the authorization response has
	// to equal instead of the pinned identity; empty for the identity itself.
	// The identity stays the grant key either way.
	ExpectedIssuer string
}

IssuerPin is what an operator configured for one authorization server on an MCPServer (spec.auth.authorizationServer) beyond the issuer itself: a pre-registered client, whether the tokens the AS issues belong to the person (subject) or to the login session that obtained them, and the issuer identifier the AS puts in the RFC 9207 iss parameter when the pinned identity is not it.

type Manager

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

Manager coordinates OAuth flows for remote MCP server authentication. It manages the OAuth MCP client, HTTP handlers, and integrates with the aggregator.

func NewManager

func NewManager(cfg config.OAuthMCPClientConfig, opts ...ManagerOption) *Manager

NewManager creates a new OAuth manager with the given configuration. The cfg parameter contains the OAuth MCP client/proxy configuration for authenticating TO remote MCP servers.

func (*Manager) ClearTokenByIssuer

func (m *Manager) ClearTokenByIssuer(sessionID, issuer string)

ClearTokenByIssuer removes all tokens for a given session and issuer.

func (*Manager) ClearTokenByIssuerForUser

func (m *Manager) ClearTokenByIssuerForUser(sessionID, userID, issuer string)

ClearTokenByIssuerForUser removes the session's tokens for an issuer and, for a subject-scoped issuer, the person's grant, see Client.DeleteByIssuerForUser.

func (*Manager) CreateAuthChallenge

func (m *Manager) CreateAuthChallenge(ctx context.Context, params AuthChallengeParams) (*AuthRequiredResponse, error)

CreateAuthChallenge creates an authentication challenge for a 401 response. Returns the auth URL the user should visit and the challenge response.

func (*Manager) DeleteTokensBySession

func (m *Manager) DeleteTokensBySession(sessionID string)

DeleteTokensBySession removes all downstream tokens for a given session. This is used during per-session logout via token family revocation.

func (*Manager) DeleteTokensByUser

func (m *Manager) DeleteTokensByUser(userID string)

DeleteTokensByUser removes all downstream tokens for a given user across all sessions. This is used during "sign out everywhere" to clear all server-side token state.

func (*Manager) ExchangeTokenForRemoteCluster

func (m *Manager) ExchangeTokenForRemoteCluster(ctx context.Context, localToken, userID string, config *api.TokenExchangeConfig) (string, error)

ExchangeTokenForRemoteCluster exchanges a local token for one valid on a remote cluster. This implements RFC 8693 Token Exchange for cross-cluster SSO scenarios.

Args:

  • ctx: Context for the operation
  • localToken: The local ID token to exchange
  • userID: The user's unique identifier (from validated JWT 'sub' claim)
  • config: Token exchange configuration for the remote cluster

Returns the exchanged access token, or an error if exchange fails.

func (*Manager) GetCIMDHandler

func (m *Manager) GetCIMDHandler() http.HandlerFunc

GetCIMDHandler returns the HTTP handler for serving the CIMD.

func (*Manager) GetCIMDPath

func (m *Manager) GetCIMDPath() string

GetCIMDPath returns the path for serving the CIMD.

func (*Manager) GetCallbackPath

func (m *Manager) GetCallbackPath() string

GetCallbackPath returns the configured callback path.

func (*Manager) GetClientCredentialsForIssuer

func (m *Manager) GetClientCredentialsForIssuer(ctx context.Context, issuer string) (clientID, clientSecret string)

GetClientCredentialsForIssuer returns the client_id and client_secret the OAuth flows use against the given issuer (CIMD URL or DCR-issued credentials), without triggering a new registration. Used to configure mcp-go's transport-level token refresh.

func (*Manager) GetHTTPHandler

func (m *Manager) GetHTTPHandler() http.Handler

GetHTTPHandler returns the HTTP handler for OAuth endpoints.

func (*Manager) GetServerConfig

func (m *Manager) GetServerConfig(serverName string) *AuthServerConfig

GetServerConfig returns the OAuth configuration for a server.

func (*Manager) GetStartHandler

func (m *Manager) GetStartHandler() http.HandlerFunc

GetStartHandler returns the HTTP handler for the OAuth proxy start endpoint.

func (*Manager) GetStartPath

func (m *Manager) GetStartPath() string

GetStartPath returns the path of the OAuth proxy start endpoint.

func (*Manager) GetToken

func (m *Manager) GetToken(sessionID, serverName string) *pkgoauth.Token

GetToken retrieves a valid token for the given session and server. mcp-go handles token refresh via its transport layer, so this method simply returns the stored token without proactive refresh.

func (*Manager) GetTokenByIssuer

func (m *Manager) GetTokenByIssuer(sessionID, issuer string) *pkgoauth.Token

GetTokenByIssuer retrieves a valid token for the given session and issuer. This is used for SSO when we have the issuer from a 401 response.

func (*Manager) GetTokenByIssuerForUser

func (m *Manager) GetTokenByIssuerForUser(sessionID, userID, issuer string) *pkgoauth.Token

GetTokenByIssuerForUser is GetTokenByIssuer with the subject-scoped grant fallback, see Client.GetByIssuerForUser.

func (*Manager) GetTokenExchanger

func (m *Manager) GetTokenExchanger() *TokenExchanger

GetTokenExchanger returns the token exchanger for direct access. This is useful for cache management and monitoring.

func (*Manager) IsEnabled

func (m *Manager) IsEnabled() bool

IsEnabled returns whether OAuth proxy is enabled.

func (*Manager) IssuerSubjectScoped

func (m *Manager) IssuerSubjectScoped(issuer string) bool

IssuerSubjectScoped reports whether the issuer's grants belong to the person, see Client.IssuerSubjectScoped.

func (*Manager) PinIssuer

func (m *Manager) PinIssuer(issuer string, pin IssuerPin, metadata *pkgoauth.Metadata)

PinIssuer records an operator-configured authorization server, see Client.PinIssuer.

func (*Manager) ProbeTokenEndpoint added in v5.34.9

func (m *Manager) ProbeTokenEndpoint(ctx context.Context, config *api.TokenExchangeConfig) error

ProbeTokenEndpoint checks that the token endpoint of config answers as an authorization server (see TokenExchanger.Probe).

func (*Manager) RegisterServer

func (m *Manager) RegisterServer(serverName, issuer, scope string)

RegisterServer registers OAuth configuration for a remote MCP server.

func (*Manager) SetAuthCompletionCallback

func (m *Manager) SetAuthCompletionCallback(callback AuthCompletionCallback)

SetAuthCompletionCallback sets the callback to be called after successful authentication. The aggregator uses this to establish session connections after browser OAuth completes.

func (*Manager) ShouldServeCIMD

func (m *Manager) ShouldServeCIMD() bool

ShouldServeCIMD returns true if muster should serve its own CIMD.

func (*Manager) Stop

func (m *Manager) Stop()

Stop stops the OAuth manager and cleans up resources.

func (*Manager) StoreToken

func (m *Manager) StoreToken(sessionID, userID, issuer string, token *pkgoauth.Token)

StoreToken persists a token for the given session and issuer. The userID is stored alongside for reverse-lookup by user.

func (*Manager) SubjectGrantForRelease

func (m *Manager) SubjectGrantForRelease(ctx context.Context, userID, issuer string) *pkgoauth.Token

SubjectGrantForRelease returns the person's grant for a subject-scoped issuer, refreshed when due, for release to a trusted relying party through the token broker; nil when the person holds none. See Client.SubjectGrant.

func (*Manager) UnpinIssuer

func (m *Manager) UnpinIssuer(issuer string)

UnpinIssuer forgets an operator-configured authorization server, see Client.UnpinIssuer.

type ManagerOption

type ManagerOption func(*managerOptions)

ManagerOption configures optional Manager parameters.

func WithValkeyClientCredentialStore

func WithValkeyClientCredentialStore(cs ClientCredentialStorer) ManagerOption

WithValkeyClientCredentialStore injects a Valkey-backed ClientCredentialStorer into the OAuth client, so DCR-issued client credentials are shared across replicas.

func WithValkeyStateStore

func WithValkeyStateStore(ss StateStorer) ManagerOption

WithValkeyStateStore injects a Valkey-backed StateStorer into the OAuth client.

func WithValkeyTokenStore

func WithValkeyTokenStore(ts TokenStorer) ManagerOption

WithValkeyTokenStore injects a Valkey-backed TokenStorer into the OAuth client.

type OAuthState

type OAuthState struct {
	// SessionID links the OAuth flow to the login session (token family ID).
	SessionID string `json:"session_id"`

	// UserID is the user's identity (sub claim), carried for token store indexing.
	UserID string `json:"user_id"`

	// ServerName is the MCP server that requires authentication.
	ServerName string `json:"server_name"`

	// Nonce is a random value for CSRF protection.
	Nonce string `json:"nonce"`

	// CreatedAt is when the state was created (for expiration).
	CreatedAt time.Time `json:"created_at"`

	// RedirectURI is where to redirect the browser after a successful
	// callback, instead of the static success page. Set server-side by the
	// start endpoint after allowlist validation; never taken from the
	// callback request.
	RedirectURI string `json:"redirect_uri,omitempty"`

	// AuthorizationURL is the upstream authorization-server URL this flow
	// continues to. Set server-side after the URL is built; the start
	// endpoint redirects the browser here.
	AuthorizationURL string `json:"authorization_url,omitempty"`

	// Issuer is the OAuth issuer URL for token exchange.
	Issuer string `json:"issuer,omitempty"`

	// Resource is the canonical URI of the MCP server this flow obtains a
	// token for (RFC 8707). The same value goes on the authorization
	// request and on the token request.
	Resource string `json:"resource,omitempty"`

	// Scope is the scope the authorization request asked for; the granted
	// scope when the token response omits one (RFC 6749 §5.1).
	Scope string `json:"scope,omitempty"`

	// CodeVerifier is the PKCE code verifier for this flow.
	// Stored server-side only, not transmitted in the state parameter.
	CodeVerifier string `json:"-"`
}

OAuthState represents the state parameter data for OAuth flows. This is serialized and passed through the OAuth flow to link the callback to the original request. This is server-specific as it handles CSRF protection for server-side OAuth.

type StateParams

type StateParams struct {
	// SessionID links the OAuth flow to the login session.
	SessionID string

	// UserID is the user's identity (sub claim).
	UserID string

	// ServerName is the MCP server that requires authentication.
	ServerName string

	// Issuer is the authorization server the flow runs against. The
	// callback compares the RFC 9207 `iss` parameter against it.
	Issuer string

	// Resource is the canonical URI of the MCP server (RFC 8707).
	Resource string

	// Scope is the scope the authorization request asked for. RFC 6749 §5.1
	// lets the authorization server omit `scope` from its token response
	// when it granted exactly that, so the callback needs it to record the
	// granted scope on the token.
	Scope string

	// CodeVerifier is the PKCE code verifier for this flow.
	CodeVerifier string
}

StateParams carries the per-flow values recorded with a new OAuth state.

type StateStore

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

StateStore provides thread-safe in-memory storage for OAuth state parameters. State parameters are used to link OAuth callbacks to original requests and provide CSRF protection.

IMPORTANT: StateStore starts a background goroutine for cleanup. Callers MUST call Stop() when done to prevent goroutine leaks. Typically this is done via defer after creating the store, or in a shutdown hook for long-lived stores.

func NewStateStore

func NewStateStore() *StateStore

NewStateStore creates a new state store with default expiration.

func (*StateStore) Completed

func (ss *StateStore) Completed(encodedState string) *CompletedFlow

Completed returns the recorded outcome for a recently completed flow, or nil (see StateStorer).

func (*StateStore) Delete

func (ss *StateStore) Delete(nonce string)

Delete removes a state from the store.

func (*StateStore) GenerateState

func (ss *StateStore) GenerateState(params StateParams,
	buildAuthorizationURL func(encodedState string) (string, error)) (encodedState string, err error)

GenerateState creates a new OAuth state parameter and stores it. Returns the encoded state string to include in the authorization URL. The nonce is embedded within the encoded state and used for server-side lookup.

func (*StateStore) MarkCompleted

func (ss *StateStore) MarkCompleted(encodedState string, done *CompletedFlow)

MarkCompleted records a finished flow's outcome for duplicate callback deliveries (see StateStorer).

func (*StateStore) Stop

func (ss *StateStore) Stop()

Stop stops the background cleanup goroutine.

func (*StateStore) Update

func (ss *StateStore) Update(encodedState string, mutate func(*OAuthState)) *OAuthState

Update applies mutate to a stored state without consuming it. Returns a copy of the updated state, or nil if the state is invalid, expired, or absent.

func (*StateStore) ValidateState

func (ss *StateStore) ValidateState(encodedState string) *OAuthState

ValidateState validates an OAuth state parameter from a callback. Returns the original state data if valid, nil if invalid or expired.

type StateStorer

type StateStorer interface {
	// GenerateState creates a new OAuth state, stores it, and returns the
	// base64-encoded state string the start endpoint resolves. When
	// buildAuthorizationURL is non-nil it is called with the encoded state
	// and its result is stored as the flow's upstream authorization URL, so
	// state and URL land in a single write; an error aborts without storing.
	GenerateState(params StateParams,
		buildAuthorizationURL func(encodedState string) (string, error)) (encodedState string, err error)

	// ValidateState validates an encoded state from a callback. Returns the
	// original state if valid; nil if invalid, expired, or already consumed.
	// Valid states are consumed (single-use) to prevent replay attacks.
	ValidateState(encodedState string) *OAuthState

	// Update applies mutate to a stored state without consuming it and
	// returns a copy of the updated state; nil if the state is invalid,
	// expired, or absent. The TTL is unchanged.
	Update(encodedState string, mutate func(*OAuthState)) *OAuthState

	// MarkCompleted records that the flow behind an encoded state finished
	// successfully. Browsers and IdP redirect pages deliver the callback
	// navigation more than once; the record lets a duplicate delivery of an
	// already-consumed state render the flow's outcome again instead of an
	// error. The record expires after completionGrace.
	MarkCompleted(encodedState string, done *CompletedFlow)

	// Completed returns the recorded outcome for an encoded state whose flow
	// recently completed, or nil. The record is not consumed — every
	// duplicate within the grace window renders the same outcome.
	Completed(encodedState string) *CompletedFlow

	// Delete removes a state entry by nonce.
	Delete(nonce string)

	// Stop releases resources (background goroutines, connections, etc.).
	Stop()
}

StateStorer is the interface for OAuth state parameter storage. Implementations must be safe for concurrent use.

type TokenExchanger

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

TokenExchanger performs RFC 8693 OAuth 2.0 Token Exchange for cross-cluster SSO. It enables users authenticated to muster (Cluster A) to access MCP servers on remote clusters (Cluster B) by exchanging their local token for a token valid on the remote cluster's Identity Provider.

This is different from token forwarding (ForwardToken), which forwards muster's ID token directly. Token exchange is useful when:

  • Remote clusters have separate Dex instances
  • The remote Dex is configured with an OIDC connector pointing to muster's Dex
  • You need a token issued by the remote cluster's IdP

Thread-safe: Yes, the underlying TokenExchangeClient is thread-safe.

func NewTokenExchangerWithOptions

func NewTokenExchangerWithOptions(opts TokenExchangerOptions) *TokenExchanger

NewTokenExchangerWithOptions creates a new TokenExchanger with custom options.

func (*TokenExchanger) Cleanup

func (e *TokenExchanger) Cleanup() int

Cleanup removes expired tokens from the cache. This should be called periodically for long-running services.

func (*TokenExchanger) ClearAllCache

func (e *TokenExchanger) ClearAllCache()

ClearAllCache removes all cached tokens.

func (*TokenExchanger) ClearCache

func (e *TokenExchanger) ClearCache(tokenEndpoint, connectorID, userID string)

ClearCache removes a cached token for the given parameters. This is useful when a cached token is rejected by the remote server.

func (*TokenExchanger) Exchange

Exchange exchanges a local token for a token valid on a remote cluster. The token is cached to reduce the number of exchange requests.

Args:

  • ctx: Context for cancellation and timeouts
  • req: Exchange request parameters

Returns the exchanged token or an error if exchange fails.

func (*TokenExchanger) GetCacheStats

func (e *TokenExchanger) GetCacheStats() tokencache.Stats

GetCacheStats returns statistics about the token exchange cache.

func (*TokenExchanger) Probe added in v5.34.9

func (e *TokenExchanger) Probe(ctx context.Context, config *api.TokenExchangeConfig) error

Probe checks that the token endpoint of config answers as an authorization server, with the client credentials and HTTP client every exchange uses. It sends an exchange with a subject token no issuer signed and returns the error that produced -- an OAuth rejection of the subject token when the endpoint is up (see api.ClassifyTokenExchangeError) -- or nil in the unlikely case the endpoint accepted it. Nothing is cached.

type TokenExchangerOptions

type TokenExchangerOptions struct {
	// Logger for debug/info messages (nil uses default logger).
	Logger *slog.Logger

	// AllowPrivateIP allows token endpoints to resolve to private IP addresses.
	// WARNING: Reduces SSRF protection. Only enable for internal/VPN deployments.
	AllowPrivateIP bool

	// CacheMaxEntries is the maximum number of cached tokens (0 = default: 10000).
	CacheMaxEntries int

	// HTTPClient is the HTTP client to use for token exchange requests.
	// If nil, an appropriate client is created based on AllowPrivateIP setting.
	// Use this to configure custom TLS settings (e.g., for self-signed certs).
	HTTPClient *http.Client
}

TokenExchangerOptions configures the TokenExchanger.

type TokenKey

type TokenKey struct {
	SessionID string
	Issuer    string
	Scope     string
}

TokenKey uniquely identifies a token in the store. Tokens are indexed by session ID (token family), issuer, and scope to enable per-login-session isolation. Each login creates a new token family, and tokens are scoped to that family so logout on one device does not affect another.

type TokenStore

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

TokenStore provides thread-safe in-memory storage for OAuth tokens. Tokens are indexed by session ID (token family), issuer, and scope to support per-login-session isolation. Each entry also records the owning user ID to support bulk operations like "sign out everywhere".

IMPORTANT: TokenStore starts a background goroutine for cleanup. Callers MUST call Stop() when done to prevent goroutine leaks. Typically this is done via defer after creating the store, or in a shutdown hook for long-lived stores.

func NewTokenStore

func NewTokenStore() *TokenStore

NewTokenStore creates a new in-memory token store. It starts a background goroutine for periodic cleanup of expired tokens.

func (*TokenStore) Count

func (ts *TokenStore) Count() int

Count returns the number of tokens in the store.

func (*TokenStore) Delete

func (ts *TokenStore) Delete(key TokenKey)

Delete removes a token from the store.

func (*TokenStore) DeleteByIssuer

func (ts *TokenStore) DeleteByIssuer(sessionID, issuer string)

DeleteByIssuer removes all tokens for a given session and issuer. This is used to clear invalid/expired tokens before requesting fresh authentication.

func (*TokenStore) DeleteBySession

func (ts *TokenStore) DeleteBySession(sessionID string)

func (*TokenStore) DeleteByUser

func (ts *TokenStore) DeleteByUser(userID string)

DeleteByUser removes all tokens for a given user across all sessions. This is used during "sign out everywhere" to clear all server-side token state.

func (*TokenStore) DeleteByUserAndIssuer

func (ts *TokenStore) DeleteByUserAndIssuer(userID, issuer string)

DeleteBySession removes all tokens for a given session. This is used during per-session logout via token family revocation. DeleteByUserAndIssuer removes the user's tokens for one issuer across all sessions.

func (*TokenStore) Get

func (ts *TokenStore) Get(key TokenKey) *pkgoauth.Token

Get retrieves a token from the store by key. Returns nil if the token doesn't exist or has expired.

func (*TokenStore) GetAllForSession

func (ts *TokenStore) GetAllForSession(sessionID string) map[TokenKey]*pkgoauth.Token

GetAllForSession returns all valid tokens for a session.

func (*TokenStore) GetAllForUser

func (ts *TokenStore) GetAllForUser(userID string) map[TokenKey]*pkgoauth.Token

GetAllForUser returns all valid tokens for a user across all sessions. This iterates all entries and filters by the stored user ID.

func (*TokenStore) GetByIssuer

func (ts *TokenStore) GetByIssuer(sessionID, issuer string) *pkgoauth.Token

GetByIssuer finds a token for the given session and issuer, regardless of scope. This enables SSO when the exact scope doesn't match but the issuer does.

When multiple tokens match (e.g., an ID-only token from SetSessionCreationHandler and a full token from a downstream OAuth callback), tokens with an AccessToken are preferred. This prevents non-deterministic map iteration from returning an ID-only token that would cause DynamicAuthClient to report ErrNoToken.

func (*TokenStore) GetByIssuerIncludingExpired

func (ts *TokenStore) GetByIssuerIncludingExpired(sessionID, issuer string) *pkgoauth.Token

GetByIssuerIncludingExpired returns the session's token for the issuer regardless of expiry, see TokenStorer.

func (*TokenStore) ReplaceByUserAndIssuer

func (ts *TokenStore) ReplaceByUserAndIssuer(userID, issuer string, token *pkgoauth.Token) int

ReplaceByUserAndIssuer overwrites the user's tokens for one issuer in every session that holds one, see TokenStorer.

func (*TokenStore) Stop

func (ts *TokenStore) Stop()

Stop stops the background cleanup goroutine.

func (*TokenStore) Store

func (ts *TokenStore) Store(key TokenKey, token *pkgoauth.Token, userID string)

Store saves a token in the store, indexed by the given key. The userID is stored alongside for reverse-lookup by user (e.g., "sign out everywhere").

type TokenStorer

type TokenStorer interface {
	// Store saves a token indexed by the given key, recording userID for
	// reverse-lookup operations (e.g., "sign out everywhere").
	Store(key TokenKey, token *pkgoauth.Token, userID string)

	// Get retrieves a token by exact key. Returns nil if not found or expired.
	Get(key TokenKey) *pkgoauth.Token

	// GetByIssuer finds a token for the given session and issuer, regardless
	// of scope. Returns nil if not found or expired.
	GetByIssuer(sessionID, issuer string) *pkgoauth.Token

	// GetAllForSession returns all valid (non-expired) tokens for a session.
	GetAllForSession(sessionID string) map[TokenKey]*pkgoauth.Token

	// Delete removes a single token by key.
	Delete(key TokenKey)

	// DeleteByUser removes all tokens for a user across all sessions.
	DeleteByUser(userID string)

	// DeleteByUserAndIssuer removes the user's tokens for one issuer across
	// all sessions, including a subject-scoped grant: signing out of a
	// server as the person disconnects every session of that person.
	DeleteByUserAndIssuer(userID, issuer string)

	// GetByIssuerIncludingExpired is GetByIssuer without the expiry filter:
	// it returns the session's token for the issuer even when it has expired,
	// so a refresh path can redeem the refresh token it carries. Tokens with
	// an access token are preferred, then the one that expires last. Returns
	// nil when the session holds nothing for the issuer.
	GetByIssuerIncludingExpired(sessionID, issuer string) *pkgoauth.Token

	// ReplaceByUserAndIssuer overwrites the user's tokens for one issuer in
	// every session that holds one -- the subject-scoped grant included --
	// with token, keeping each entry's key. It reports how many entries were
	// replaced. Used after a refresh so every session of the person sees the
	// rotated token and nobody redeems the old refresh token again.
	ReplaceByUserAndIssuer(userID, issuer string, token *pkgoauth.Token) int

	// DeleteBySession removes all tokens for a session.
	DeleteBySession(sessionID string)

	// DeleteByIssuer removes all tokens for a session+issuer combination.
	DeleteByIssuer(sessionID, issuer string)

	// Count returns the total number of tokens in the store.
	Count() int

	// Stop releases resources (background goroutines, connections, etc.).
	Stop()
}

TokenStorer is the interface for OAuth token storage. Implementations must be safe for concurrent use. The aggregator-side OAuth proxy stores tokens here after successful authentication flows.

type ValkeyClientCredentialStore

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

ValkeyClientCredentialStore stores DCR-issued client credentials in Valkey with optional AES-256-GCM encryption at rest. Sharing the store across replicas matters more here than for tokens: the authorization request and the callback's code exchange may land on different replicas, and both must resolve the same issuer-bound client_id.

Data model:

Key:    {keyPrefix}oauth:client_creds
Fields: {issuer} -> [encrypted] JSON(pkgoauth.ClientCredentials)
TTL:    none — registrations represent muster itself and stay valid
        until the AS revokes them; expired secrets are dropped on read.

func NewValkeyClientCredentialStore

func NewValkeyClientCredentialStore(client valkey.Client, keyPrefix string, encryptor *security.Encryptor) *ValkeyClientCredentialStore

NewValkeyClientCredentialStore creates a Valkey-backed client credential store. keyPrefix is prepended to all Valkey keys (default "muster:" if empty). encryptor enables AES-256-GCM encryption at rest; pass nil to disable.

func (*ValkeyClientCredentialStore) Delete

func (s *ValkeyClientCredentialStore) Delete(issuer string)

Delete removes the credentials for the issuer.

func (*ValkeyClientCredentialStore) Get

Get returns the credentials for the issuer, or nil if absent or expired.

func (*ValkeyClientCredentialStore) Stop

func (s *ValkeyClientCredentialStore) Stop()

Stop is a no-op; the Valkey client lifecycle is owned by the caller.

func (*ValkeyClientCredentialStore) Store

Store saves credentials for the issuer, replacing any previous entry.

type ValkeyStateStore

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

ValkeyStateStore stores OAuth state parameters in Valkey with automatic expiration and optional AES-256-GCM encryption at rest. Each state is stored as a single key with a 10-minute TTL, matching the in-memory StateStore behaviour.

Data model:

Key:   {keyPrefix}oauth:state:{nonce}
Value: [encrypted] JSON(valkeyStateEntry)
TTL:   10 minutes

func NewValkeyStateStore

func NewValkeyStateStore(client valkey.Client, keyPrefix string, encryptor *security.Encryptor) *ValkeyStateStore

NewValkeyStateStore creates a Valkey-backed OAuth state store. keyPrefix is prepended to all Valkey keys (default "muster:" if empty). encryptor enables AES-256-GCM encryption at rest; pass nil to disable.

func (*ValkeyStateStore) Completed

func (s *ValkeyStateStore) Completed(encodedState string) *CompletedFlow

Completed returns the recorded outcome for a recently completed flow, or nil (see StateStorer).

func (*ValkeyStateStore) Delete

func (s *ValkeyStateStore) Delete(nonce string)

func (*ValkeyStateStore) GenerateState

func (s *ValkeyStateStore) GenerateState(params StateParams,
	buildAuthorizationURL func(encodedState string) (string, error)) (string, error)

func (*ValkeyStateStore) MarkCompleted

func (s *ValkeyStateStore) MarkCompleted(encodedState string, done *CompletedFlow)

MarkCompleted records a finished flow's outcome for duplicate callback deliveries (see StateStorer). The record shares the state keyspace under its own suffix, encrypted like the states themselves, and Valkey's TTL enforces the grace window across replicas.

func (*ValkeyStateStore) Stop

func (s *ValkeyStateStore) Stop()

Stop is a no-op for the Valkey implementation (no background goroutines). The Valkey client is closed separately during server shutdown.

func (*ValkeyStateStore) Update

func (s *ValkeyStateStore) Update(encodedState string, mutate func(*OAuthState)) *OAuthState

Update applies mutate to a stored state without consuming it. Returns the updated state, or nil if the state is invalid, expired, or absent. The key's TTL is preserved.

func (*ValkeyStateStore) ValidateState

func (s *ValkeyStateStore) ValidateState(encodedState string) *OAuthState

type ValkeyTokenStore

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

ValkeyTokenStore stores OAuth tokens in Valkey hashes with optional AES-256-GCM encryption at rest.

Data model:

Session key:  {keyPrefix}oauth:token:{sessionID}
  Fields:     {issuer}|{scope} -> [encrypted] JSON(valkeyTokenEntry)
  TTL:        session-level, reset on every Store

User index:   {keyPrefix}oauth:token:user:{userID}
  Members:    sessionIDs (for DeleteByUser reverse lookup)
  TTL:        same as session key

func NewValkeyTokenStore

func NewValkeyTokenStore(client valkey.Client, ttl time.Duration, keyPrefix string, encryptor *security.Encryptor) *ValkeyTokenStore

NewValkeyTokenStore creates a Valkey-backed OAuth token store. keyPrefix is prepended to all Valkey keys (default "muster:" if empty). encryptor enables AES-256-GCM encryption at rest; pass nil to disable.

func (*ValkeyTokenStore) Count

func (s *ValkeyTokenStore) Count() int

Count returns the total number of tokens across all sessions. This operation is bounded by a 10-second timeout to prevent Valkey overload. Intended for diagnostics only; avoid calling on hot paths.

func (*ValkeyTokenStore) Delete

func (s *ValkeyTokenStore) Delete(key TokenKey)

func (*ValkeyTokenStore) DeleteByIssuer

func (s *ValkeyTokenStore) DeleteByIssuer(sessionID, issuer string)

func (*ValkeyTokenStore) DeleteBySession

func (s *ValkeyTokenStore) DeleteBySession(sessionID string)

func (*ValkeyTokenStore) DeleteByUser

func (s *ValkeyTokenStore) DeleteByUser(userID string)

func (*ValkeyTokenStore) DeleteByUserAndIssuer

func (s *ValkeyTokenStore) DeleteByUserAndIssuer(userID, issuer string)

DeleteByUserAndIssuer removes the user's tokens for one issuer from every session in the user's session set (the subject-scoped grant is one of them).

func (*ValkeyTokenStore) Get

func (s *ValkeyTokenStore) Get(key TokenKey) *pkgoauth.Token

func (*ValkeyTokenStore) GetAllForSession

func (s *ValkeyTokenStore) GetAllForSession(sessionID string) map[TokenKey]*pkgoauth.Token

func (*ValkeyTokenStore) GetByIssuer

func (s *ValkeyTokenStore) GetByIssuer(sessionID, issuer string) *pkgoauth.Token

func (*ValkeyTokenStore) GetByIssuerIncludingExpired

func (s *ValkeyTokenStore) GetByIssuerIncludingExpired(sessionID, issuer string) *pkgoauth.Token

GetByIssuerIncludingExpired returns the session's token for the issuer regardless of expiry, see TokenStorer.

func (*ValkeyTokenStore) ReplaceByUserAndIssuer

func (s *ValkeyTokenStore) ReplaceByUserAndIssuer(userID, issuer string, token *pkgoauth.Token) int

ReplaceByUserAndIssuer overwrites the user's tokens for one issuer in every session of the user's session set (the subject-scoped grant is one of them), see TokenStorer.

func (*ValkeyTokenStore) Stop

func (s *ValkeyTokenStore) Stop()

Stop is a no-op for the Valkey implementation (no background goroutines). The Valkey client is closed separately during server shutdown.

func (*ValkeyTokenStore) Store

func (s *ValkeyTokenStore) Store(key TokenKey, token *pkgoauth.Token, userID string)

Directories

Path Synopsis
Package store provides per-session authentication and capability stores for the token broker layer.
Package store provides per-session authentication and capability stores for the token broker layer.

Jump to

Keyboard shortcuts

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