oauth

package
v5.32.5 Latest Latest
Warning

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

Go to latest
Published: Sep 25, 2026 License: Apache-2.0 Imports: 22 Imported by: 1 module, 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 provides shared OAuth 2.1 types and utilities used by both the Muster Agent and Server.

This package contains the common OAuth functionality that is shared between the agent-side OAuth implementation (internal/agent/oauth) and the server-side OAuth implementation (internal/oauth).

Core Components

  • Token: OAuth token representation with expiry checking
  • Metadata: OAuth/OIDC server metadata (RFC 8414)
  • AuthChallenge: Parsed WWW-Authenticate header information
  • PKCE: Proof Key for Code Exchange generation (RFC 7636)
  • Client: OAuth client for metadata discovery and token operations

Usage

Both the agent and server import this package for shared types and utilities, then wrap it with their specific storage backends and UI handling.

Agent usage (file-based storage, browser opening):

import "github.com/giantswarm/muster/v5/pkg/oauth"

challenge, err := oauth.ParseWWWAuthenticate(header)
pkce, err := oauth.GeneratePKCE() // Uses golang.org/x/oauth2 under the hood

Server usage (in-memory storage, HTTP callbacks):

import "github.com/giantswarm/muster/v5/pkg/oauth"

client := oauth.NewClient(httpClient, logger)
metadata, err := client.DiscoverMetadata(ctx, issuer)

Index

Constants

View Source
const (
	// DefaultHTTPTimeout is the default timeout for HTTP requests.
	DefaultHTTPTimeout = 30 * time.Second

	// DefaultMetadataCacheTTL is the default TTL for cached OAuth metadata.
	DefaultMetadataCacheTTL = 30 * time.Minute
)
View Source
const (
	// WellKnownAuthorizationServer is the RFC 8414 §3 path suffix for
	// OAuth 2.0 Authorization Server Metadata.
	WellKnownAuthorizationServer = "/.well-known/oauth-authorization-server"
	// WellKnownOpenIDConfiguration is the OpenID Connect Discovery 1.0 §4
	// path suffix for OpenID provider metadata.
	WellKnownOpenIDConfiguration = "/.well-known/openid-configuration"
	// WellKnownProtectedResource is the RFC 9728 path suffix for OAuth 2.0
	// Protected Resource Metadata.
	WellKnownProtectedResource = "/.well-known/oauth-protected-resource"
)

Well-known URI suffixes for OAuth/OIDC metadata discovery.

View Source
const (
	HeaderAuthorization = "Authorization"
	HeaderWWWAuth       = "WWW-Authenticate"

	SchemeBearer = "Bearer"
)

HTTP header names and authentication scheme used by OAuth/OIDC flows. These match RFC 6749 / 6750 / 8693 wire format and must not be renamed.

View Source
const (
	FormFieldGrantType     = "grant_type"
	FormFieldClientID      = "client_id"
	FormFieldClientSecret  = "client_secret"
	FormFieldCode          = "code"
	FormFieldCodeVerifier  = "code_verifier"
	FormFieldRefreshToken  = "refresh_token"
	FormFieldRedirectURI   = "redirect_uri"
	FormFieldScope         = "scope"
	FormFieldSubjectToken  = "subject_token"
	FormFieldRequestedAud  = "audience"
	FormFieldSubjectTokenT = "subject_token_type"
)

Token-endpoint form field names (RFC 6749 §4 + RFC 7636 PKCE + RFC 8693).

View Source
const (
	GrantTypeAuthorizationCode = "authorization_code"
	GrantTypeRefreshToken      = "refresh_token"
	GrantTypeTokenExchange     = "urn:ietf:params:oauth:grant-type:token-exchange" //nolint:gosec // G101: RFC 8693 grant-type URN, a protocol constant, not a credential
)

Grant types accepted at the token endpoint.

View Source
const (
	CodeChallengeMethodS256  = "S256"
	CodeChallengeMethodPlain = "plain"
)

Authorization-request PKCE challenge methods (RFC 7636).

View Source
const (
	JSONFieldAccessToken      = "access_token"
	JSONFieldRefreshToken     = "refresh_token"
	JSONFieldIDToken          = "id_token"
	JSONFieldTokenType        = "token_type"
	JSONFieldExpiresIn        = "expires_in"
	JSONFieldError            = "error"
	JSONFieldErrorDescription = "error_description"
)

JSON field names returned in token-endpoint and error responses.

View Source
const (
	ErrInvalidRequest       = "invalid_request"
	ErrInvalidClient        = "invalid_client"
	ErrInvalidGrant         = "invalid_grant"
	ErrUnauthorizedClient   = "unauthorized_client"
	ErrUnsupportedGrantType = "unsupported_grant_type"
	ErrInvalidScope         = "invalid_scope"
	ErrAccessDenied         = "access_denied"
	ErrServerError          = "server_error"
	ErrInvalidToken         = "invalid_token"
)

OAuth 2.0 error codes (RFC 6749 §5.2, §4.1.2.1).

View Source
const DefaultExpiryMargin = 30 * time.Second

DefaultExpiryMargin is the default margin when checking token expiry. This accounts for clock skew and network latency.

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

DefaultSessionDuration is the expected maximum session duration before re-authentication is required. This should match the server-side RefreshTokenTTL and is used by the CLI to estimate session expiry from the stored token's CreatedAt timestamp. Aligned with Dex's absoluteLifetime (720h = 30 days).

View Source
const DefaultTokenStorageDir = ".config/muster/tokens" //nolint:gosec

DefaultTokenStorageDir is the default directory for storing OAuth tokens, relative to the user's home directory. This follows XDG conventions. This constant is shared across all OAuth implementations for consistency.

View Source
const (
	// DisplayAuthRequired is the formatted string shown in CLI prompts when servers require authentication.
	// This is displayed prominently in uppercase because it requires user action (running 'auth login').
	// Example prompt: "muster staging [AUTH REQUIRED] > "
	DisplayAuthRequired = "[AUTH REQUIRED]"
)

Display constants for user-facing output. These are formatted strings suitable for CLI prompts and status displays.

View Source
const ErrBadRefreshToken = "bad_refresh_token"

ErrBadRefreshToken is GitHub's error code for a refresh token that is expired, revoked or already rotated away (RFC 6749 servers answer invalid_grant for the same condition).

View Source
const HeaderMusterIDToken = "X-Muster-Id-Token" //nolint:gosec // G101: a header name, not a credential

HeaderMusterIDToken carries the session's upstream ID token to an MCPServer with spec.auth.forwardIdentity, next to the pinned grant in Authorization. Servers read it by this name: it must not be renamed.

Variables

View Source
var ErrTokenExpMissing = errors.New("token missing exp claim")

ErrTokenExpMissing is returned by Expiry when a token parses successfully but carries no exp claim. Callers can errors.Is against it to distinguish "couldn't decode" from "decoded fine, no exp" without parsing error text.

Functions

func Audience

func Audience(token string) ([]string, error)

Audience returns the aud claim of a trusted JWT as a list, whether the token carries it as a single string or as an array. Returns (nil, nil) when the token parses but carries no aud; returns a wrapped error on decode failure.

Audiences are client identifiers, not secrets: a backend that rejects a forwarded token because none of its audiences is trusted is attributable from this list alone, so callers may put it in logs and status output.

func DefaultTokenDir

func DefaultTokenDir() (string, error)

DefaultTokenDir returns the absolute path to the default token storage directory (~/.config/muster/tokens). It does not create the directory; callers that need it to exist should call os.MkdirAll themselves.

func DeriveResourceURI

func DeriveResourceURI(raw string) (string, error)

DeriveResourceURI derives a resource identifier for an MCP server from a URL, for the case where the server declares none. Use the declared value unchanged whenever there is one, and reach for this only to derive one.

The derivation drops the query and the fragment and changes nothing else: the scheme and host keep their case, an explicit port stays, and a trailing slash on the path stays. That is the rule mcp-go applies to the same URL when it derives its own indicator (client/transport/streamable_http.go clears RawQuery and Fragment, and client/transport/oauth.go falls back to that value when the metadata omits the field). mcp-go owns token refresh on both the agent path and the backend path, so a derivation that normalized anything further would bind the initial token and the refreshed token to different audiences.

func Email

func Email(token string) (string, error)

Email returns the email claim of a trusted ID token. Returns "" with a wrapped error on decode failure; returns ("", nil) when the token parses but has no email claim. Intended for OIDC ID tokens; access tokens typically don't carry an email claim.

func EmailVerified

func EmailVerified(token string) (bool, error)

EmailVerified returns the email_verified claim of a trusted ID token. Returns false with a wrapped error on decode failure; returns (false, nil) when the token parses but has no email_verified claim.

func Expiry

func Expiry(token string) (time.Time, error)

Expiry returns the exp claim of a trusted JWT. Returns ErrTokenExpMissing when the token parses but has no exp; wraps the underlying decode error otherwise.

func GeneratePKCERaw

func GeneratePKCERaw() (verifier, challenge string)

GeneratePKCERaw generates a PKCE code verifier and challenge as raw strings. This is useful when you don't need the full PKCEChallenge struct.

This implementation uses the standard golang.org/x/oauth2 library which provides RFC 7636 compliant PKCE generation.

Returns the verifier and S256 challenge. This function cannot fail as it uses the standard library's implementation.

func GenerateState

func GenerateState() (string, error)

GenerateState generates a random state parameter for OAuth. The state is used to prevent CSRF attacks and link the authorization response back to the original request.

Returns a base64url-encoded random string.

func IsExpired

func IsExpired(token string) (bool, error)

IsExpired reports whether a trusted JWT's exp claim is in the past or within DefaultExpiryMargin of now. Returns (true, nil) when the token parses and is actually past expiry; returns (true, err) when the token is unparseable or has no exp — callers should treat both as unusable but can use the error to distinguish them. Mirrors Token.IsExpired for raw-string JWTs.

func IsInvalidClientError

func IsInvalidClientError(err error) bool

IsInvalidClientError reports whether err is a token endpoint response with the error code invalid_client: the authorization server no longer accepts the client identification that was presented, as opposed to rejecting the grant (invalid_grant) or the request shape (invalid_request).

func IsOAuthUnauthorizedError

func IsOAuthUnauthorizedError(err error) bool

IsOAuthUnauthorizedError checks if an error indicates an OAuth authorization failure using mcp-go's typed error detection. Returns true for both transport.OAuthAuthorizationRequiredError (when WithHTTPOAuth is configured), transport.ErrUnauthorized (the SSE transport's bare 401 without an OAuth handler), transport.ErrAuthorizationRequired (the streamable HTTP transport's bare 401 without one: a transport.AuthorizationRequiredError, which unwraps to it) and transport.ErrOAuthAuthorizationRequired (no token in the store to send).

func IsRefreshTokenRejected

func IsRefreshTokenRejected(err error) bool

IsRefreshTokenRejected reports whether the token endpoint refused a refresh because the refresh token itself is no longer good: RFC 6749 invalid_grant, or GitHub's bad_refresh_token. Anything else -- a network failure, a 5xx, an invalid_client -- says nothing about the grant and is not a rejection.

func Issuer

func Issuer(token string) (string, error)

Issuer returns the iss claim of a trusted JWT. Returns ("", nil) when the token parses but carries no iss; returns a wrapped error on decode failure.

func NormalizeServerURL

func NormalizeServerURL(serverURL string) string

NormalizeServerURL normalizes a server URL by stripping transport-specific path suffixes (/mcp, /sse) and trailing slashes to get the base server URL. This ensures consistent token storage and OAuth metadata discovery regardless of which endpoint path is used when connecting.

This function is shared across all OAuth implementations for consistency.

func ProtectedResourceMetadataURLs

func ProtectedResourceMetadataURLs(serverURL string) ([]string, error)

ProtectedResourceMetadataURLs returns the RFC 9728 well-known URLs to probe for an MCP server, most specific first: the path-inserted form the MCP specification mandates, then the root form for a server that serves one document for every path. A document these URLs reach is bound to the server by the URL construction, which is why its declared resource needs no further origin check.

func Subject

func Subject(token string) (string, error)

Subject returns the sub claim of a trusted JWT. Returns "" with a wrapped error on decode failure; returns ("", nil) when the token parses but has no sub claim.

func ValidateAdvertisedMetadataURL

func ValidateAdvertisedMetadataURL(candidate, serverURL string) error

ValidateAdvertisedMetadataURL reports whether a protected resource metadata URL taken from an untrusted source may be fetched for a given MCP server. The candidate must be absolute and must share the server's scheme and host.

RFC 9728 §3.2 requires a protected resource to serve its own metadata. A resource that points a client at another origin is either misconfigured or hostile: the document it names states both the authorization server to use and the resource identifier to bind the token to, so following it lets the resource obtain a token for something it does not own.

func ValidateAdvertisedResource

func ValidateAdvertisedResource(declared, serverURL string) error

ValidateAdvertisedResource reports whether a resource identifier declared in a metadata document that an untrusted pointer named may be used for a given MCP server. The declared value must be on the server's own origin.

A document the well-known path reaches is bound to the server by the URL construction. One an advertised pointer named is not, so the identifier it declares is checked here. The rule is the origin and not the whole URI, because a server legitimately declares an identifier whose path differs from its MCP endpoint: an mcp-oauth backend serving at "<base>/mcp" declares "<base>". What the check does refuse is an identifier belonging to another party, which is the value that would turn muster's token into one minted for a resource the backend does not own.

func ValidateResourceURI

func ValidateResourceURI(raw string) error

ValidateResourceURI reports whether raw is usable as an RFC 8707 `resource` value: an absolute URI with a host, without userinfo and without a fragment.

It does not rewrite the value. A resource identifier a protected resource declares for itself must be sent exactly as declared, because the authorization server compares it against the identifier it registered for that resource.

Types

type AuthChallenge

type AuthChallenge struct {
	// Scheme is the authentication scheme (typically "Bearer" for OAuth 2.0).
	Scheme string

	// Realm is the protection realm (often the authorization server name or URL).
	Realm string

	// Issuer is the OAuth/OIDC issuer URL.
	// This may be derived from the Realm if it's a URL.
	Issuer string

	// ResourceMetadataURL is the URL to the protected resource metadata.
	// This follows RFC 9728 for OAuth 2.0 Protected Resource Metadata.
	ResourceMetadataURL string

	// Scope is the space-separated list of required OAuth scopes.
	Scope string

	// Error is the error code from the WWW-Authenticate header (if any).
	Error string

	// ErrorDescription is a human-readable error description (if any).
	ErrorDescription string
}

AuthChallenge represents parsed information from a WWW-Authenticate header. This contains the OAuth server metadata needed to initiate the auth flow.

func ParseWWWAuthenticate

func ParseWWWAuthenticate(header string) (*AuthChallenge, error)

ParseWWWAuthenticate parses a WWW-Authenticate header value. It supports the Bearer scheme with OAuth 2.0 and MCP-specific parameters.

Example headers:

Bearer realm="https://auth.example.com"
Bearer realm="https://auth.example.com", scope="openid profile"
Bearer realm="https://auth.example.com", resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource"

Returns an AuthChallenge with the parsed parameters, or an error if parsing fails.

func (*AuthChallenge) GetIssuer

func (c *AuthChallenge) GetIssuer() string

GetIssuer returns the OAuth issuer URL. It prefers the explicit Issuer field, falls back to Realm if it's a URL.

func (*AuthChallenge) IsOAuthChallenge

func (c *AuthChallenge) IsOAuthChallenge() bool

IsOAuthChallenge returns true if this represents an OAuth authentication challenge.

type AuthRequiredInfo

type AuthRequiredInfo struct {
	Server   string `json:"server"`
	Issuer   string `json:"issuer"`
	Scope    string `json:"scope,omitempty"`
	AuthTool string `json:"auth_tool"` // Always "core_auth_login" per ADR-008
}

AuthRequiredInfo contains information about a server requiring authentication. This is a simplified view used by the agent to build human-readable notifications.

Per ADR-008, AuthTool is always "core_auth_login" - callers can use this tool with the Server field as the argument to authenticate.

type AuthStatusResponse

type AuthStatusResponse struct {
	Servers []ServerAuthStatus `json:"servers"`
}

AuthStatusResponse is the structured response from the auth://status MCP resource. It provides the AI with complete information about which servers need authentication. This type is shared between the aggregator (producer) and agent (consumer).

type AuthorizationRequest

type AuthorizationRequest struct {
	// AuthorizationEndpoint is the authorization endpoint of the AS.
	AuthorizationEndpoint string

	// ClientID identifies the client. Muster uses its CIMD URL.
	ClientID string

	// RedirectURI is where the AS returns the authorization response.
	RedirectURI string

	// State is the opaque CSRF value returned on the authorization response.
	State string

	// Scope is the space-separated scope list, optional.
	Scope string

	// Resource is the canonical URI of the MCP server the token is for
	// (RFC 8707). Empty omits the parameter.
	Resource string

	// PKCE holds the code challenge, optional.
	PKCE *PKCEChallenge
}

AuthorizationRequest carries the parameters of an OAuth authorization request. The fields are grouped in a struct because several of them are URLs that are easy to transpose in a positional argument list.

type Client

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

Client handles OAuth 2.1 protocol operations. It provides metadata discovery, token exchange, and token refresh.

func NewClient

func NewClient(opts ...ClientOption) *Client

NewClient creates a new OAuth client.

func (*Client) BuildAuthorizationURL

func (c *Client) BuildAuthorizationURL(request AuthorizationRequest) (string, error)

BuildAuthorizationURL constructs an OAuth authorization URL.

MCP 2026-07-28 requires the RFC 8707 `resource` parameter on the authorization request regardless of whether the authorization server supports it, so it is sent whenever the caller supplies one.

func (*Client) ClearMetadataCache

func (c *Client) ClearMetadataCache()

ClearMetadataCache clears the metadata cache. Useful for testing or when metadata needs to be refreshed immediately.

func (*Client) DiscoverMetadata

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

DiscoverMetadata fetches OAuth metadata from the issuer's well-known endpoint. It tries RFC 8414 (/.well-known/oauth-authorization-server) first, then falls back to OpenID Connect (/.well-known/openid-configuration).

Results are cached with a TTL to reduce network requests.

func (*Client) ExchangeCode

func (c *Client) ExchangeCode(ctx context.Context, tokenEndpoint, code, redirectURI, clientID, clientSecret, codeVerifier, resource string) (*Token, error)

ExchangeCode exchanges an authorization code for tokens.

clientSecret is empty for public clients (CIMD, or DCR registrations with token_endpoint_auth_method "none"); when set it is sent as client_secret_post, which every AS that issues secrets via DCR accepts.

resource is the canonical URI of the MCP server the token is for. MCP 2026-07-28 requires the RFC 8707 `resource` parameter on the token request regardless of whether the authorization server supports it, so it is sent whenever the caller supplies one.

func (*Client) PinMetadata

func (c *Client) PinMetadata(issuer string, metadata *Metadata)

cacheMetadata stores metadata in the cache. PinMetadata supplies the metadata of an authorization server that publishes no RFC 8414 / OIDC discovery document (GitHub). DiscoverMetadata answers from the pin from then on, without a network request, until PinMetadata is called again for the issuer. When the pinned document lists no code_challenge_methods_supported, S256 is assumed: the operator vouching for the endpoints is the only source of that fact, and MCP's refusal rule exists for servers that could have advertised it.

func (*Client) ProbeClientRegistration

func (c *Client) ProbeClientRegistration(ctx context.Context, authorizationEndpoint, clientID, redirectURI string) (RegistrationStatus, error)

ProbeClientRegistration asks the authorization endpoint whether it still recognizes the client_id / redirect_uri pair, for authorization servers that offer no RFC 7592 endpoint.

The probe is an authorization request that carries only client_id and redirect_uri. It cannot start an authorization — response_type is missing — but RFC 6749 §4.1.2.1 fixes how that failure is reported, and the shape reveals what the client needs to know: a server that recognizes client_id and redirect_uri redirects the error to that redirect_uri, while a server that does not MUST NOT redirect and answers the user agent directly. The MCP TypeScript SDK, for one, answers an unknown client_id with a direct 400 carrying {"error":"invalid_client"}. So a redirect to the client's own redirect_uri means the registration is alive; a 4xx that names invalid_client means it is gone; anything else is inconclusive.

Redirects are not followed and the response body is not acted on, so the probe leaves no authorization state behind at the server.

func (*Client) ReadClientRegistration

func (c *Client) ReadClientRegistration(ctx context.Context, registrationClientURI, registrationAccessToken string) (RegistrationStatus, error)

ReadClientRegistration performs the RFC 7592 §2.1 client read request: GET registration_client_uri with the registration_access_token as bearer credential. A 200 confirms the registration; RFC 7592 §2.3 requires a 401 when the token is invalid or the client no longer exists, which is the signal that the credentials are dead. Every other answer (403, 404, 5xx, transport errors) is inconclusive, because it can as well mean the server stopped serving the endpoint.

func (*Client) RefreshToken

func (c *Client) RefreshToken(ctx context.Context, tokenEndpoint, refreshToken, clientID, clientSecret string) (*Token, error)

RefreshToken redeems a refresh token at the token endpoint (RFC 6749 §6) with the client identification the grant was issued under; clientSecret is empty for public clients. The answer is the authorization server's new token set. An authorization server that rotates refresh tokens (GitHub) answers with a new refresh_token and invalidates the old one; one that does not rotate answers without a refresh_token, and the caller keeps the one it has. A rejected refresh token comes back as a TokenEndpointError whose Code names the reason (invalid_grant, or GitHub's bad_refresh_token), see IsRefreshTokenRejected.

func (*Client) RegisterClient

func (c *Client) RegisterClient(ctx context.Context, registrationEndpoint string, metadata *ClientMetadata) (*ClientRegistrationResponse, error)

RegisterClient performs OAuth 2.0 Dynamic Client Registration (RFC 7591) against the given registration endpoint. The metadata must not carry a client_id — the authorization server assigns one in the response.

func (*Client) UnpinMetadata

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

UnpinMetadata drops the operator-pinned metadata for an issuer, so the next DiscoverMetadata fetches the authorization server's own document again. It reports whether a pinned entry was dropped. A discovered entry is left alone: it came from the authorization server itself and expires with the cache TTL.

Pinned entries never expire, so without this a pin that an MCPServer no longer carries -- removed, or changed to a different authorization server -- would keep answering every flow against the issuer until the process restarts (giantswarm/muster#1175).

type ClientCredentials

type ClientCredentials struct {
	// Issuer is the authorization server these credentials were issued by.
	Issuer string `json:"issuer"`

	// ClientID is the registered client identifier.
	ClientID string `json:"client_id"`

	// ClientSecret is set only when the AS issued one; muster requests
	// token_endpoint_auth_method "none" but must honor what it gets.
	ClientSecret string `json:"client_secret,omitempty"`

	// ClientSecretExpiresAt is when the secret expires (RFC 7591); zero
	// means no expiry.
	ClientSecretExpiresAt time.Time `json:"client_secret_expires_at,omitempty"`

	// RegistrationAccessToken and RegistrationClientURI enable RFC 7592
	// management of the registration (unused today, kept for completeness).
	RegistrationAccessToken string `json:"registration_access_token,omitempty"`
	RegistrationClientURI   string `json:"registration_client_uri,omitempty"`

	// CreatedAt is when muster performed the registration.
	CreatedAt time.Time `json:"created_at,omitempty"`
}

ClientCredentials are issuer-bound OAuth client credentials obtained via Dynamic Client Registration. Per SEP-2352 ("Authorization Server Binding"), DCR-issued credentials MUST be keyed by the issuer they were registered with and MUST NOT be reused against a different authorization server.

func (*ClientCredentials) IsExpired

func (c *ClientCredentials) IsExpired() bool

IsExpired reports whether the credentials carry an expired client secret. Credentials without a secret (public clients) never expire.

type ClientMetadata

type ClientMetadata struct {
	ClientID                string   `json:"client_id,omitempty"`
	ClientName              string   `json:"client_name,omitempty"`
	ClientURI               string   `json:"client_uri,omitempty"`
	RedirectURIs            []string `json:"redirect_uris"`
	GrantTypes              []string `json:"grant_types,omitempty"`
	ResponseTypes           []string `json:"response_types,omitempty"`
	TokenEndpointAuthMethod string   `json:"token_endpoint_auth_method,omitempty"`
	Scope                   string   `json:"scope,omitempty"`
	LogoURI                 string   `json:"logo_uri,omitempty"`
	PolicyURI               string   `json:"policy_uri,omitempty"`
	TermsOfServiceURI       string   `json:"tos_uri,omitempty"`
	SoftwareID              string   `json:"software_id,omitempty"`
	SoftwareVersion         string   `json:"software_version,omitempty"`

	// ApplicationType is the OIDC DCR client type hint ("web" or "native").
	// MCP (SEP-837) requires clients to send it on DCR requests to OIDC-aware
	// servers; muster's server-side proxy is a remote browser-based client,
	// so it sends "web". Non-OIDC servers ignore the field.
	ApplicationType string `json:"application_type,omitempty"`
}

ClientMetadata represents OAuth 2.0 Client Metadata as defined in RFC 7591. Used for Client ID Metadata Documents (CIMD) in MCP OAuth and as the request body for Dynamic Client Registration. ClientID is omitted on DCR requests (RFC 7591 forbids it there); the AS assigns it in the response.

type ClientOption

type ClientOption func(*Client)

ClientOption configures the OAuth client.

func WithHTTPClient

func WithHTTPClient(httpClient *http.Client) ClientOption

WithHTTPClient sets a custom HTTP client.

func WithMetadataCacheTTL

func WithMetadataCacheTTL(ttl time.Duration) ClientOption

WithMetadataCacheTTL sets the metadata cache TTL.

type ClientRegistrationResponse

type ClientRegistrationResponse struct {
	ClientID              string `json:"client_id"`
	ClientSecret          string `json:"client_secret,omitempty"`
	ClientIDIssuedAt      int64  `json:"client_id_issued_at,omitempty"`
	ClientSecretExpiresAt int64  `json:"client_secret_expires_at,omitempty"`

	// RegistrationAccessToken and RegistrationClientURI enable RFC 7592
	// management of the registration. Stored for completeness; muster does
	// not manage registrations after creation.
	RegistrationAccessToken string `json:"registration_access_token,omitempty"`
	RegistrationClientURI   string `json:"registration_client_uri,omitempty"`
}

ClientRegistrationResponse is the RFC 7591 §3.2.1 client information response returned by an authorization server's registration endpoint.

type Metadata

type Metadata struct {
	// Issuer is the authorization server's issuer identifier.
	Issuer string `json:"issuer"`

	// AuthorizationEndpoint is the URL of the authorization endpoint.
	AuthorizationEndpoint string `json:"authorization_endpoint"`

	// TokenEndpoint is the URL of the token endpoint.
	TokenEndpoint string `json:"token_endpoint"`

	// UserinfoEndpoint is the URL of the userinfo endpoint (OIDC).
	UserinfoEndpoint string `json:"userinfo_endpoint,omitempty"`

	// JwksURI is the URL of the JSON Web Key Set.
	JwksURI string `json:"jwks_uri,omitempty"`

	// RegistrationEndpoint is the URL for dynamic client registration.
	RegistrationEndpoint string `json:"registration_endpoint,omitempty"`

	// ScopesSupported lists the OAuth 2.0 scope values supported.
	ScopesSupported []string `json:"scopes_supported,omitempty"`

	// ResponseTypesSupported lists the response_type values supported.
	ResponseTypesSupported []string `json:"response_types_supported,omitempty"`

	// GrantTypesSupported lists the grant types supported.
	GrantTypesSupported []string `json:"grant_types_supported,omitempty"`

	// TokenEndpointAuthMethodsSupported lists the client authentication methods.
	TokenEndpointAuthMethodsSupported []string `json:"token_endpoint_auth_methods_supported,omitempty"`

	// CodeChallengeMethodsSupported lists the PKCE code challenge methods.
	CodeChallengeMethodsSupported []string `json:"code_challenge_methods_supported,omitempty"`

	// AuthorizationResponseIssParameterSupported reports whether the
	// authorization server sends the RFC 9207 `iss` parameter on
	// authorization responses. When true, a response without `iss` must be
	// rejected.
	AuthorizationResponseIssParameterSupported bool `json:"authorization_response_iss_parameter_supported,omitempty"`
	// ClientIDMetadataDocumentSupported reports whether the authorization
	// server resolves Client ID Metadata Document URLs as client_id values
	// (MCP authorization / SEP-991). When absent or false, the AS may treat a
	// CIMD URL as an unknown literal client identifier and reject the flow.
	ClientIDMetadataDocumentSupported bool `json:"client_id_metadata_document_supported,omitempty"`
}

Metadata represents OAuth 2.0 Authorization Server Metadata as defined in RFC 8414.

func (*Metadata) SupportsS256PKCE

func (m *Metadata) SupportsS256PKCE() bool

SupportsS256PKCE reports whether the AS metadata advertises S256 PKCE.

MCP 2025-11-25 §"Authorization Code Protection" mandates clients refuse to proceed if `code_challenge_methods_supported` is absent — overriding the OAuth 2.1 default-true convention. An empty / missing list returns false.

type PKCEChallenge

type PKCEChallenge struct {
	// CodeVerifier is the cryptographically random string (32-96 bytes, base64url-encoded).
	// This is kept secret and never transmitted to the authorization server.
	CodeVerifier string

	// CodeChallenge is the SHA256 hash of the verifier (base64url-encoded).
	// This is sent in the authorization request.
	CodeChallenge string

	// CodeChallengeMethod is always "S256" for security (plain is not allowed in OAuth 2.1).
	CodeChallengeMethod string
}

PKCEChallenge represents a PKCE (Proof Key for Code Exchange) challenge. PKCE is required for OAuth 2.1 public clients to prevent authorization code interception.

func GeneratePKCE

func GeneratePKCE() (*PKCEChallenge, error)

GeneratePKCE generates a new PKCE code verifier and challenge. The code verifier is 32 random bytes (256 bits), base64url-encoded. The code challenge is the S256 (SHA256) hash of the verifier.

This implementation delegates to the standard golang.org/x/oauth2 library for RFC 7636 compliant PKCE generation.

Returns a PKCEChallenge ready for use in an authorization request.

type RegistrationStatus

type RegistrationStatus int

RegistrationStatus is the outcome of asking an authorization server whether it still recognizes a client registration.

const (
	// RegistrationUnknown means the check could not tell: the request failed,
	// or the server answered in a way that names neither outcome. Callers
	// keep the credentials they have.
	RegistrationUnknown RegistrationStatus = iota

	// RegistrationActive means the server confirmed it still knows the client.
	RegistrationActive

	// RegistrationGone means the server no longer knows the client. Credentials
	// tied to it will be refused; the client has to register again.
	RegistrationGone
)

func (RegistrationStatus) String

func (s RegistrationStatus) String() string

String returns the status name for log lines.

type ResourceIndicator

type ResourceIndicator struct {
	// Value is the indicator to send, or empty for a target that needs none.
	Value string

	// DeclaredErr is set when the target declared a value that was unusable.
	// Value then holds one derived from the target URL instead, so the login
	// still completes; callers log DeclaredErr.
	DeclaredErr error
}

ResourceIndicator is the outcome of resolving an RFC 8707 `resource` value for a target.

func ResolveResourceIndicator

func ResolveResourceIndicator(declared, targetURL string) (ResourceIndicator, error)

ResolveResourceIndicator picks the RFC 8707 `resource` value for a target: the URI the target declares in its RFC 9728 metadata, sent exactly as declared, or a value derived from targetURL when the target declares none.

A declared value is never rewritten. The authorization server compares it against the identifier registered for that target, and mcp-go sends the declared value verbatim on token refresh, so any normalization here would bind the initial token and the refreshed token to different audiences.

An empty targetURL yields an empty value and no error, for a target that needs no indicator.

type ServerAuthStatus

type ServerAuthStatus struct {
	Name     string              `json:"name"`
	Status   SessionServerStatus `json:"status"` // "connected", "auth_required", "reauth_required", "sso_pending", "disconnected", "error"
	Issuer   string              `json:"issuer,omitempty"`
	Scope    string              `json:"scope,omitempty"`
	AuthTool string              `json:"auth_tool,omitempty"` // "core_auth_login" for non-SSO servers; empty for SSO servers (per ADR-008)

	// Error says why the server is not connected for this session, when muster
	// knows. For an SSO server whose attempt failed (SSOAttemptFailed) it is
	// the failed attempt's own account: the connect error with the forwarded
	// token's issuer and audiences and, when the backend's 401 carried one,
	// its WWW-Authenticate error_description. Clients show it verbatim; it
	// never contains a token.
	Error string `json:"error,omitempty"`

	// Suspended reports that the server's MCPServer spec holds its service
	// down (spec.suspended=true, written by core_service_stop — the portal's
	// Deactivate). Status is then "disconnected" for every session and
	// core_auth_login refuses the server; core_service_start activates it
	// again. Absent while the server is up.
	Suspended bool `json:"suspended,omitempty"`

	// TokenForwardingEnabled indicates this server uses SSO via ID token forwarding.
	// When true, muster forwards its own ID token (from muster's OAuth server protection)
	// to this downstream server, rather than requiring a separate OAuth flow.
	TokenForwardingEnabled bool `json:"token_forwarding_enabled,omitempty"`

	// TokenExchangeEnabled indicates this server uses SSO via RFC 8693 Token Exchange.
	// When true, muster exchanges its local token for one valid on the remote cluster's
	// Identity Provider (e.g., Dex). This enables cross-cluster SSO when clusters have
	// separate Dex instances. Token exchange takes precedence over token forwarding.
	TokenExchangeEnabled bool `json:"token_exchange_enabled,omitempty"`

	// SSOAttemptFailed indicates that SSO authentication was attempted but failed.
	// This occurs when token forwarding is enabled but the downstream server
	// rejected the forwarded token (e.g., audience mismatch, token expired).
	// When true, the status will be "auth_required" and users should check
	// server trust configuration.
	SSOAttemptFailed bool `json:"sso_attempt_failed,omitempty"`
}

ServerAuthStatus represents the authentication status of a single MCP server. The Issuer field enables SSO detection - servers with the same issuer can share auth.

SSO in muster has two mechanisms:

  • Token Forwarding: When TokenForwardingEnabled is true, muster forwards its own ID token to the downstream server (requires forwardToken: true in MCPServer config).
  • Token Exchange: When TokenExchangeEnabled is true, muster exchanges its token for one valid on the remote cluster's IdP (for cross-cluster SSO).

type SessionServerStatus

type SessionServerStatus string

SessionServerStatus represents the per-user session authentication status of an MCP server. This is distinct from api.ServiceState which tracks global server lifecycle state.

const (
	// SessionServerStatusConnected indicates the server is connected and operational.
	// Tools from this server are available for use.
	SessionServerStatusConnected SessionServerStatus = "connected"

	// SessionServerStatusAuthRequired indicates the server requires OAuth authentication.
	// This is an important status that requires user action: run 'muster auth login --server <name>'.
	// The server is reachable but needs authentication before tools become available.
	//
	// This status is more informative than a generic "Disconnected" because it tells
	// users exactly what action is needed to restore connectivity.
	SessionServerStatusAuthRequired SessionServerStatus = "auth_required"

	// SessionServerStatusDisconnected indicates the server is disconnected.
	// The connection was previously established but is no longer active.
	SessionServerStatusDisconnected SessionServerStatus = "disconnected"

	// SessionServerStatusError indicates the server encountered an error.
	// Check the error field for details about what went wrong.
	SessionServerStatusError SessionServerStatus = "error"

	// SessionServerStatusUnreachable indicates the server endpoint cannot be reached.
	// This is distinct from auth_required - unreachable means network/connectivity failure,
	// not an authentication issue. Users should not be prompted to authenticate
	// for unreachable servers.
	SessionServerStatusUnreachable SessionServerStatus = "unreachable"

	// SessionServerStatusFailed indicates a session-level failure (e.g., connection dropped,
	// unexpected error during communication). This is distinct from infrastructure
	// failures (tracked in MCPServer Phase) and auth failures (tracked in AuthStatus).
	SessionServerStatusFailed SessionServerStatus = "failed"

	// SessionServerStatusSSOPending indicates that SSO authentication is in progress for this
	// server. The server is SSO-enabled and muster is currently establishing the
	// connection via token forwarding or token exchange. This is a transient state
	// that will resolve to "connected" (on success) or "auth_required" with
	// sso_attempt_failed=true (on failure).
	//
	// Clients should NOT call core_auth_login for servers in this state -- they
	// should wait for the SSO process to complete.
	SessionServerStatusSSOPending SessionServerStatus = "sso_pending"

	// SessionServerStatusReauthRequired indicates the user's session has a broken
	// upstream token refresh chain (e.g., Dex -> GitHub returned 401). The ID token
	// has expired or is no longer available, so SSO connections cannot be maintained.
	// The user must re-authenticate via 'muster auth login' to restore SSO access.
	// This is distinct from auth_required (initial auth needed) -- reauth_required
	// means a previously working session has degraded.
	SessionServerStatusReauthRequired SessionServerStatus = "reauth_required"
)

Session server status constants for use in ServerAuthStatus.Status field. These are the primary status values visible to users and AI assistants.

type Token

type Token struct {
	// AccessToken is the bearer token used for authorization.
	AccessToken string `json:"access_token"`

	// TokenType is typically "Bearer".
	TokenType string `json:"token_type,omitempty"`

	// RefreshToken is used to obtain new access tokens (optional).
	RefreshToken string `json:"refresh_token,omitempty"`

	// ExpiresIn is the token lifetime in seconds (from token response).
	ExpiresIn int `json:"expires_in,omitempty"`

	// ExpiresAt is the calculated expiration timestamp.
	ExpiresAt time.Time `json:"expires_at,omitempty"`

	// Scope is the granted scope(s), space-separated.
	Scope string `json:"scope,omitempty"`

	// Issuer is the token issuer (Identity Provider URL).
	Issuer string `json:"issuer,omitempty"`

	// IDToken is the OIDC ID token (if available).
	IDToken string `json:"id_token,omitempty"`
}

Token represents an OAuth access token with associated metadata.

func (*Token) IsExpired

func (t *Token) IsExpired() bool

IsExpired checks if the token has expired. Returns true if the token is expired or will expire within the given margin.

func (*Token) IsExpiredWithMargin

func (t *Token) IsExpiredWithMargin(margin time.Duration) bool

IsExpiredWithMargin checks if the token has expired or will expire within the margin.

func (*Token) Scopes

func (t *Token) Scopes() []string

Scopes returns the scope as a slice of individual scopes.

func (*Token) SetExpiresAtFromExpiresIn

func (t *Token) SetExpiresAtFromExpiresIn()

SetExpiresAtFromExpiresIn calculates and sets ExpiresAt from ExpiresIn.

func (*Token) ToOAuth2Token

func (t *Token) ToOAuth2Token() *oauth2.Token

ToOAuth2Token converts the Token to an oauth2.Token for compatibility with golang.org/x/oauth2.

type TokenEndpointError

type TokenEndpointError struct {
	StatusCode  int
	Code        string
	Description string
}

TokenEndpointError is an error response from a token endpoint (RFC 6749 §5.2). Code and Description are empty when the response body carried no OAuth error object; StatusCode is always set.

func (*TokenEndpointError) Error

func (e *TokenEndpointError) Error() string

Error renders the same text the untyped error used to carry, so log lines and messages built from it are unchanged.

Jump to

Keyboard shortcuts

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