Documentation
¶
Overview ¶
Package auth provides authentication and authorization utilities.
Package auth provides authentication and authorization utilities.
Package auth provides authentication and authorization utilities.
Package auth provides authentication and authorization utilities.
Package auth provides authentication and authorization utilities.
Package auth provides authentication and authorization utilities.
Package auth provides authentication and authorization utilities.
Package auth provides authentication and authorization utilities.
Index ¶
- Constants
- Variables
- func AnonymousMiddleware(next http.Handler) http.Handler
- func CanonicalUserFromContext(ctx context.Context) (string, bool)
- func CreateMiddleware(config *types.MiddlewareConfig, runner types.MiddlewareRunner) error
- func EscapeQuotes(s string) string
- func ExtractBearerToken(r *http.Request) (string, error)
- func GetAuthenticationMiddleware(ctx context.Context, oidcConfig *TokenValidatorConfig, ...) (func(http.Handler) http.Handler, http.Handler, error)
- func LocalUserMiddleware(username string) func(http.Handler) http.Handler
- func NewAuthInfoHandler(issuer, resourceURL string, scopes []string) http.Handler
- func NewWellKnownHandler(authInfoHandler http.Handler) http.Handler
- func PlatformUserFromContext(ctx context.Context) (string, bool)
- func WithIdentity(ctx context.Context, identity *Identity) context.Context
- func WithPlatformUser(ctx context.Context, userID string) context.Context
- type GitHubProvider
- type GoogleProvider
- type Identity
- type IdentityContextKey
- type Middleware
- type MiddlewareParams
- type MonitoredTokenSource
- type PlatformUserContextKey
- type PrincipalInfo
- type RFC6750Error
- type RFC7662Provider
- type RFC9728AuthInfo
- type Registry
- type StatusUpdater
- type TokenIntrospector
- type TokenValidator
- type TokenValidatorConfig
- type TokenValidatorOption
Constants ¶
const ( OAuthErrInvalidRequest = "invalid_request" OAuthErrInvalidToken = "invalid_token" OAuthErrInsufficientScope = "insufficient_scope" )
RFC 6750 error code constants for Bearer token authentication.
const GitHubTokenCheckURL = "api.github.com/applications"
GitHubTokenCheckURL is the base URL pattern for GitHub OAuth token validation
const GoogleTokeninfoURL = "https://oauth2.googleapis.com/tokeninfo" //nolint:gosec
GoogleTokeninfoURL is the Google OAuth2 tokeninfo endpoint URL
const (
MiddlewareType = "auth"
)
Middleware type constant
Variables ¶
var ( ErrNoToken = errors.New("no token provided") ErrInvalidToken = errors.New("invalid token") ErrTokenExpired = errors.New("token expired") ErrInvalidIssuer = errors.New("invalid issuer") ErrInvalidAudience = errors.New("invalid audience") ErrMissingJWKSURL = errors.New("missing JWKS URL") ErrFailedToFetchJWKS = errors.New("failed to fetch JWKS") ErrFailedToDiscoverOIDC = errors.New("failed to discover OIDC configuration") ErrMissingIssuerAndJWKSURL = errors.New("either issuer or JWKS URL must be provided") )
Common errors
var ( ErrAuthHeaderMissing = errors.New("authorization header required") ErrInvalidAuthHeaderFormat = errors.New("invalid authorization header format, expected 'Bearer <token>'") ErrEmptyBearerToken = errors.New("empty token in authorization header") )
Common Bearer token extraction errors
Functions ¶
func AnonymousMiddleware ¶ added in v0.0.38
AnonymousMiddleware creates an HTTP middleware that sets up anonymous identity. This is useful for testing and local environments where authorization policies need to work without requiring actual authentication.
The middleware sets up basic anonymous identity that can be used by authorization policies, allowing them to function even when authentication is disabled. This is heavily discouraged in production settings but is handy for testing and local development environments.
func CanonicalUserFromContext ¶ added in v0.30.1
CanonicalUserFromContext returns the platform's canonical user identifier for storage keying. It is the single accessor storage layers should use, regardless of which path produced the context.
It prefers the dedicated platform-user key (set on identity-less paths such as the OAuth callback) and falls back to the authenticated Identity's PlatformUserID (set on request-serving paths). Returns "" and false if neither is present. The dedicated key wins so an explicit WithPlatformUser can override the identity-derived value.
func CreateMiddleware ¶ added in v0.2.8
func CreateMiddleware(config *types.MiddlewareConfig, runner types.MiddlewareRunner) error
CreateMiddleware factory function for authentication middleware
func EscapeQuotes ¶ added in v0.2.13
EscapeQuotes escapes quotes in a string for use in a quoted-string context.
func ExtractBearerToken ¶ added in v0.5.2
ExtractBearerToken extracts and validates a Bearer token from the Authorization header. It performs the following validations:
- Verifies the Authorization header is present
- Checks for the "Bearer " prefix (case-sensitive per RFC 6750)
- Ensures the token is not empty after removing the prefix
The function returns the token string (without "Bearer " prefix) and any validation error. Callers are responsible for further token validation (JWT parsing, introspection, etc.) and for converting errors to appropriate HTTP responses.
This function implements RFC 6750 Section 2.1 (Bearer Token Authorization Header). See: https://datatracker.ietf.org/doc/html/rfc6750#section-2.1
func GetAuthenticationMiddleware ¶ added in v0.0.38
func GetAuthenticationMiddleware(ctx context.Context, oidcConfig *TokenValidatorConfig, opts ...TokenValidatorOption, ) (func(http.Handler) http.Handler, http.Handler, error)
GetAuthenticationMiddleware returns the appropriate authentication middleware based on the configuration. If OIDC config is provided, it returns JWT validation middleware. Otherwise it returns local-user middleware and logs a WARNING: with no OIDC config, the proxy accepts every request and forwards it under a synthetic local-user identity with no token or credential check. This unauthenticated fallback is intended for local/development use; configure an OIDC provider to enforce authentication per request.
func LocalUserMiddleware ¶ added in v0.0.38
LocalUserMiddleware creates an HTTP middleware that sets up local user identity. This allows specifying a local username while still bypassing authentication.
This middleware is useful for development and testing scenarios where you want to simulate a specific user without going through the full authentication flow. Like AnonymousMiddleware, this is heavily discouraged in production settings.
func NewAuthInfoHandler ¶ added in v0.2.4
NewAuthInfoHandler creates an HTTP handler that returns RFC-9728 compliant OAuth Protected Resource metadata
func NewWellKnownHandler ¶ added in v0.5.2
NewWellKnownHandler creates an HTTP handler that routes requests under the /.well-known/ path space to the appropriate handler.
Per RFC 9728, the /.well-known/oauth-protected-resource endpoint and any subpaths under it must be accessible without authentication. This handler ensures proper routing of discovery requests while returning 404 for unknown paths.
If authInfoHandler is nil, the returned handler responds with HTTP 404 and a JSON body for all /.well-known/ paths. This ensures OAuth discovery clients (e.g., Claude Code) receive a clean, parseable "not found" instead of falling through to the MCP handler, which would reject the GET with an HTTP 406 JSON-RPC error that breaks OAuth error parsing.
Usage:
authInfoHandler := auth.NewAuthInfoHandler(issuer, resourceURL, scopes)
wellKnownHandler := auth.NewWellKnownHandler(authInfoHandler)
mux.Handle("/.well-known/", wellKnownHandler)
This handler matches:
- /.well-known/oauth-protected-resource (exact)
- /.well-known/oauth-protected-resource/* (subpaths)
Returns 404 for other /.well-known/* paths or when auth is not configured.
func PlatformUserFromContext ¶ added in v0.30.1
PlatformUserFromContext retrieves the platform's canonical user identifier from the dedicated platform-user key. Returns the identifier and true if present, "" and false otherwise.
Most callers should use CanonicalUserFromContext, which also resolves the user from a validated Identity on request-serving paths. Use this only when you specifically need the dedicated key and must NOT fall back to an Identity.
func WithIdentity ¶ added in v0.6.0
WithIdentity stores an Identity in the context. If identity is nil, the original context is returned unchanged.
This function is typically called by authentication middleware after successful authentication to make the identity available to downstream handlers.
Example:
identity := &Identity{PrincipalInfo: PrincipalInfo{Subject: "user123", Name: "Alice"}}
ctx = WithIdentity(ctx, identity)
func WithPlatformUser ¶ added in v0.30.1
WithPlatformUser stores the platform's canonical user identifier in the context. If userID is empty, the original context is returned unchanged.
Use this — not WithIdentity — on paths that have resolved the user but have no validated identity to assert (e.g. the OAuth callback, which resolves the user while it is still minting the ToolHive bearer, so no validated token/claims exist yet). Reusing WithIdentity there would place a credential-free stub under the identity key that later readers could mistake for an authenticated principal.
Request-serving paths that already carry a validated identity do NOT need to call this — CanonicalUserFromContext falls back to the Identity's PlatformUserID there, so the canonical user is read from one accessor without storing it twice.
Types ¶
type GitHubProvider ¶ added in v0.5.0
type GitHubProvider struct {
// contains filtered or unexported fields
}
GitHubProvider implements token introspection for GitHub.com's OAuth token validation API GitHub uses a non-standard token validation endpoint that differs from RFC 7662 Endpoint: POST /applications/{client_id}/token Auth: Basic (client_id:client_secret) Body: {"access_token": "gho_..."}
Note: This provider is designed for GitHub.com only, not GitHub Enterprise Server
func NewGitHubProvider ¶ added in v0.5.0
func NewGitHubProvider( introspectURL, clientID, clientSecret, caCertPath string, allowPrivateIP bool, ) (*GitHubProvider, error)
NewGitHubProvider creates a new GitHub token introspection provider Parameters:
- introspectURL: GitHub token validation endpoint (must be api.github.com with HTTPS)
- clientID: OAuth App client ID
- clientSecret: OAuth App client secret
- caCertPath: Path to CA certificate bundle (optional)
- allowPrivateIP: Allow private IP addresses (should be false for production)
func (*GitHubProvider) CanHandle ¶ added in v0.5.0
func (*GitHubProvider) CanHandle(introspectURL string) bool
CanHandle returns true if this provider can handle the given introspection URL This validates that the URL is a legitimate GitHub.com token validation endpoint Note: GitHub Enterprise Server is NOT supported - use corporate IdP instead
func (*GitHubProvider) IntrospectToken ¶ added in v0.5.0
IntrospectToken introspects a GitHub OAuth token and returns JWT claims This calls GitHub's token validation API to verify the token and extract user information
func (*GitHubProvider) Name ¶ added in v0.5.0
func (*GitHubProvider) Name() string
Name returns the provider name
type GoogleProvider ¶ added in v0.2.17
type GoogleProvider struct {
// contains filtered or unexported fields
}
GoogleProvider implements token introspection for Google's tokeninfo API
func NewGoogleProvider ¶ added in v0.2.17
func NewGoogleProvider(introspectURL string) *GoogleProvider
NewGoogleProvider creates a new Google token introspection provider
func (*GoogleProvider) CanHandle ¶ added in v0.2.17
func (g *GoogleProvider) CanHandle(introspectURL string) bool
CanHandle returns true if this provider can handle the given introspection URL
func (*GoogleProvider) IntrospectToken ¶ added in v0.2.17
IntrospectToken introspects a Google opaque token and returns JWT claims
func (*GoogleProvider) Name ¶ added in v0.2.17
func (*GoogleProvider) Name() string
Name returns the provider name
type Identity ¶ added in v0.6.0
type Identity struct {
PrincipalInfo
// Token is the original authentication token (for pass-through scenarios).
// This is redacted in String() and MarshalJSON() to prevent leakage.
Token string
// TokenType is the type of token (e.g., "Bearer", "JWT").
TokenType string
// Metadata stores additional identity information.
Metadata map[string]string
// UpstreamTokens maps upstream provider names to their access tokens.
// This is populated by the auth middleware when an embedded auth server
// is active and the JWT contains a token session ID (tsid claim).
// Redacted in MarshalJSON() to prevent token leakage.
//
// MUST NOT be mutated after the Identity is placed in the publicly-reachable
// request context. It MAY be mutated while the Identity is reachable only via
// a load-scoped ctx, provided the loader does not share that ctx with
// concurrent code. See TokenValidator.Middleware for the canonical pattern.
UpstreamTokens map[string]string
}
Identity represents an authenticated user or service account. This is the primary type for representing authenticated principals throughout ToolHive.
It embeds PrincipalInfo (the credential-free subset) and adds sensitive fields (Token, TokenType) and internal metadata that must never be externalized.
func IdentityFromContext ¶ added in v0.6.0
IdentityFromContext retrieves an Identity from the context. Returns the identity and true if present, nil and false otherwise.
This function is typically called by authorization middleware or handlers that need to check who the authenticated user is.
Example:
identity, ok := IdentityFromContext(ctx)
if !ok {
return errors.New("no authenticated identity")
}
log.Printf("Request from user: %s", identity.Subject)
func (*Identity) GetPrincipalInfo ¶ added in v0.12.5
func (i *Identity) GetPrincipalInfo() *PrincipalInfo
GetPrincipalInfo returns a copy of the credential-free PrincipalInfo suitable for external consumption (webhook payloads, audit logs, etc.). Token, TokenType, and Metadata are structurally excluded.
func (*Identity) MarshalJSON ¶ added in v0.6.0
MarshalJSON implements json.Marshaler to redact sensitive fields during JSON serialization. This prevents accidental token leakage in structured logs, API responses, or audit logs.
type IdentityContextKey ¶ added in v0.6.0
type IdentityContextKey struct{}
IdentityContextKey is the key used to store Identity in the request context. This provides type-safe context storage and retrieval for authenticated identities.
Using an empty struct as the key prevents collisions with other context keys, as each empty struct type is distinct even if they have the same name in different packages.
type Middleware ¶ added in v0.2.8
type Middleware struct {
// contains filtered or unexported fields
}
Middleware wraps authentication middleware functionality
func (*Middleware) AuthInfoHandler ¶ added in v0.2.8
func (m *Middleware) AuthInfoHandler() http.Handler
AuthInfoHandler returns the authentication info handler.
func (*Middleware) Close ¶ added in v0.2.8
func (*Middleware) Close() error
Close cleans up any resources used by the middleware.
func (*Middleware) Handler ¶ added in v0.2.8
func (m *Middleware) Handler() types.MiddlewareFunction
Handler returns the middleware function used by the proxy.
type MiddlewareParams ¶ added in v0.2.8
type MiddlewareParams struct {
OIDCConfig *TokenValidatorConfig `json:"oidc_config,omitempty"`
}
MiddlewareParams represents the parameters for authentication middleware
type MonitoredTokenSource ¶ added in v0.6.0
type MonitoredTokenSource struct {
// contains filtered or unexported fields
}
MonitoredTokenSource is a wrapper around an oauth2.TokenSource that monitors authentication failures and surfaces them through workload status transitions. It provides both per-request token retrieval and background monitoring.
Failure handling has two layers:
Short retry (inside transientRefresher.retry): exponential backoff up to a ~5min total window. Retries transient failures (DNS errors, dropped connections, OAuth server 5xx/429, WAF 4xx-with-HTML) without changing workload status. Failures that resolve within the window never leave Running; failures that outlast the window fall through to AuthRetrying.
AuthRetrying ceiling (this struct): after the short retry exhausts on a still-transient error, the workload transitions to AuthRetrying and the monitor keeps running on a longer cadence (default 10min). On the next successful refresh, the workload returns to Running. After a ceiling (default 24h) the workload is finally marked Unauthenticated and the monitor stops.
Hot callers — request-path Token() calls, e.g. from the token injection middleware serving a live MCP request — fast-fail with the cached error during AuthRetrying so they return 503+Retry-After immediately rather than blocking on a singleflight retry that would exhaust again on every call.
Hot callers and the background monitor can both drive state transitions independently (the monitor via its tick, hot callers via short-retry exhaustion in Token). When the upstream alternates between transient failures and brief recoveries, the workload status oscillates with it.
func NewMonitoredTokenSource ¶ added in v0.6.0
func NewMonitoredTokenSource( ctx context.Context, tokenSource oauth2.TokenSource, workloadName string, upstream string, clientID string, statusUpdater StatusUpdater, ) *MonitoredTokenSource
NewMonitoredTokenSource creates a new MonitoredTokenSource that wraps the provided oauth2.TokenSource and monitors it for authentication failures.
upstream and clientID annotate structured logs emitted by the token source, most importantly the DCR/CIMD remediation warning fired on the transition to Unauthenticated when the token endpoint returns a permanent 4xx (which frequently indicates stale cached credentials). Pass empty strings when the workload does not use DCR/CIMD or the upstream issuer is unknown; the remediation log will be suppressed when clientID is empty since its operator-correlation field would be blank.
The fields are fixed at construction time rather than exposed via a setter so there is no data race between a late writer and the readers in Token() / transientRefresher.retry() — both of which may run on the background monitor goroutine started by StartBackgroundMonitoring.
func (*MonitoredTokenSource) StartBackgroundMonitoring ¶ added in v0.6.0
func (mts *MonitoredTokenSource) StartBackgroundMonitoring()
StartBackgroundMonitoring starts the background monitoring goroutine that checks token validity at expiry time and marks the workload as unauthenticated on the failure.
func (*MonitoredTokenSource) Stopped ¶ added in v0.12.5
func (mts *MonitoredTokenSource) Stopped() <-chan struct{}
Stopped returns a channel that is closed when background monitoring has stopped, regardless of the reason (context cancellation, auth failure, or clean shutdown).
func (*MonitoredTokenSource) Token ¶ added in v0.6.0
func (mts *MonitoredTokenSource) Token() (*oauth2.Token, error)
Token retrieves a token. On a non-transient error, it marks the workload unauthenticated and returns immediately. On a transient error, behavior depends on monitor state — see the paragraphs below. Context cancellation (workload removal) stops any in-flight retry without marking the workload unauthenticated. See isTransientNetworkError for the classification rule.
When the monitor is in the AuthRetrying transient-failure window (short retry exhausted, ceiling not yet reached), Token() fast-fails with the cached error rather than joining a singleflight retry that would hang for the full short-retry duration on every call. Hot callers see 503+Retry-After until the next monitor tick observes upstream recovery and clears the state — only the monitor's onTick (which calls the raw token source directly) can do that.
If a hot caller's own short retry exhausts on a still-transient error, the workload transitions to AuthRetrying and the monitor stays alive — subsequent hot callers fast-fail until the next monitor tick clears the state or extends it. If the monitor has already stopped (a prior permanent error closed it), enterAuthRetrying is a no-op; the hot caller returns the error without changing workload status.
During the short retry on a transient failure, concurrent callers joining at the same time are deduplicated via singleflight so that only one retry loop runs at a time. Callers that arrive AFTER the leader's singleflight call has returned start their own retry — they are not deduplicated against past calls. This is why hot-caller- driven AuthRetrying entry (after the retry exhausts) is load-bearing: without it, sequential hot callers would each pay the full short- retry duration against a broken endpoint.
type PlatformUserContextKey ¶ added in v0.30.1
type PlatformUserContextKey struct{}
PlatformUserContextKey is the key used to store the platform's canonical user identifier in the request context. It is deliberately distinct from IdentityContextKey.
A value under this key means only "this is the canonical user to key storage on" — it is NOT proof that an authenticated principal is present. The two are kept structurally separate so a storage-scoped user id can never be mistaken for a validated identity: authorizers and other consumers that need the authenticated caller use IdentityFromContext (which carries the validated token and claims), while storage layers that key on the canonical user use CanonicalUserFromContext.
type PrincipalInfo ¶ added in v0.12.5
type PrincipalInfo struct {
// Subject is the unique identifier for the principal (from 'sub' claim).
// This is always required per OIDC Core 1.0 spec § 5.1.
Subject string `json:"sub,omitempty"`
// PlatformUserID is the platform's canonical user identifier.
//
// It defaults to the sub claim (see claimsToIdentity). That default is
// correct for standalone OSS use (where sub IS the canonical local User.ID)
// and for AS-bearer paths under an enterprise directory binding (where the
// AS-minted sub equals the directory user_id). It is INCORRECT for any
// middleware that validates a JWT issued by a different IdP whose sub is not
// the platform-canonical user identifier (e.g. a corporate IdP whose sub
// rotates per-application). Such middleware MUST override PlatformUserID
// (typically via a resolution call into a directory service) before calling
// WithIdentity. On request-serving paths storage reads this value via
// CanonicalUserFromContext (which falls back to this field when no dedicated
// platform-user key is set); an unresolved PlatformUserID from a corporate-IdP
// bearer will silently mis-key writes.
//
// Only claimsToIdentity populates this field today. Other Identity
// constructors in this repo (local.go, anonymous.go, vmcp session restore)
// intentionally leave it unset for now: standalone OSS keys upstream-token
// storage on the session, not PlatformUserID, so those paths have no
// canonical-user reader to satisfy. Populating them is deferred until a
// storage layer that reads PlatformUserID on those paths exists.
PlatformUserID string `json:"platform_user_id,omitempty"`
// Name is the human-readable name (from 'name' claim).
Name string `json:"name,omitempty"`
// Email is the email address (from 'email' claim, if available).
Email string `json:"email,omitempty"`
// Groups are the groups this identity belongs to.
//
// NOTE: This field is intentionally NOT populated by authentication middleware.
// Authorization logic MUST extract groups from the Claims map, as group claim
// names vary by provider (e.g., "groups", "roles", "cognito:groups").
Groups []string `json:"groups,omitempty"`
// Claims contains additional claims from the auth token.
// This preserves all JWT claims for authorization policies.
Claims map[string]any `json:"claims,omitempty"`
}
PrincipalInfo contains the non-sensitive identity fields safe for external consumption. This is the canonical projection of Identity for webhook payloads, audit logs, and any context where credentials must not appear — not even in redacted form.
Identity embeds this type, so fields are accessible directly on Identity (e.g., identity.Subject, identity.Email) while keeping the credential-free subset available as a first-class type for external APIs.
type RFC6750Error ¶ added in v0.11.3
type RFC6750Error struct {
Error string `json:"error"`
ErrorDescription string `json:"error_description"`
}
RFC6750Error represents an RFC 6750 compliant OAuth error response body.
type RFC7662Provider ¶ added in v0.2.17
type RFC7662Provider struct {
// contains filtered or unexported fields
}
RFC7662Provider implements standard RFC 7662 OAuth 2.0 Token Introspection
func NewRFC7662Provider ¶ added in v0.2.17
func NewRFC7662Provider(introspectURL string) *RFC7662Provider
NewRFC7662Provider creates a new RFC 7662 token introspection provider
func NewRFC7662ProviderWithAuth ¶ added in v0.2.17
func NewRFC7662ProviderWithAuth( introspectURL, clientID, clientSecret, caCertPath, authTokenFile string, allowPrivateIP bool, ) (*RFC7662Provider, error)
NewRFC7662ProviderWithAuth creates a new RFC 7662 provider with client credentials
func (*RFC7662Provider) CanHandle ¶ added in v0.2.17
func (r *RFC7662Provider) CanHandle(introspectURL string) bool
CanHandle returns true if this provider can handle the given introspection URL Returns true for any URL when no specific URL was configured (fallback behavior) or when the URL matches the configured URL
func (*RFC7662Provider) IntrospectToken ¶ added in v0.2.17
IntrospectToken introspects a token using RFC 7662 standard
func (*RFC7662Provider) Name ¶ added in v0.2.17
func (*RFC7662Provider) Name() string
Name returns the provider name
type RFC9728AuthInfo ¶ added in v0.2.4
type RFC9728AuthInfo struct {
Resource string `json:"resource"`
AuthorizationServers []string `json:"authorization_servers"`
BearerMethodsSupported []string `json:"bearer_methods_supported"`
JWKSURI string `json:"jwks_uri,omitempty"`
ScopesSupported []string `json:"scopes_supported"`
}
RFC9728AuthInfo represents the OAuth Protected Resource metadata as defined in RFC 9728
type Registry ¶ added in v0.2.17
type Registry struct {
// contains filtered or unexported fields
}
Registry maintains a list of available token introspection providers
func NewRegistry ¶ added in v0.2.17
func NewRegistry() *Registry
NewRegistry creates a new provider registry
func (*Registry) AddProvider ¶ added in v0.2.17
func (r *Registry) AddProvider(provider TokenIntrospector)
AddProvider adds a new provider to the registry
func (*Registry) GetIntrospector ¶ added in v0.2.17
func (r *Registry) GetIntrospector(introspectURL string) TokenIntrospector
GetIntrospector returns the appropriate provider for the given introspection URL
type StatusUpdater ¶ added in v0.6.0
type StatusUpdater interface {
SetWorkloadStatus(ctx context.Context, workloadName string, status runtime.WorkloadStatus, reason string) error
}
StatusUpdater is an interface for updating workload authentication status. This abstraction allows the monitored token source to work with any status management system without creating import cycles.
type TokenIntrospector ¶ added in v0.2.17
type TokenIntrospector interface {
// Name returns the provider name
Name() string
// CanHandle returns true if this provider can handle the given introspection URL
CanHandle(introspectURL string) bool
// IntrospectToken introspects an opaque token and returns JWT claims
IntrospectToken(ctx context.Context, token string) (jwt.MapClaims, error)
}
TokenIntrospector defines the interface for token introspection providers
type TokenValidator ¶ added in v0.1.3
type TokenValidator struct {
// contains filtered or unexported fields
}
TokenValidator validates JWT or opaque tokens using OIDC configuration.
func NewTokenValidator ¶ added in v0.1.3
func NewTokenValidator(ctx context.Context, config TokenValidatorConfig, opts ...TokenValidatorOption) (*TokenValidator, error)
NewTokenValidator creates a new token validator.
func (*TokenValidator) Middleware ¶ added in v0.1.3
func (v *TokenValidator) Middleware(next http.Handler) http.Handler
Middleware creates an HTTP middleware that validates JWT tokens and creates Identity.
func (*TokenValidator) ValidateToken ¶ added in v0.1.3
func (v *TokenValidator) ValidateToken(ctx context.Context, tokenString string) (jwt.MapClaims, error)
ValidateToken validates a token.
type TokenValidatorConfig ¶ added in v0.1.3
type TokenValidatorConfig struct {
// Issuer is the OIDC issuer URL (e.g., https://accounts.google.com)
Issuer string
// Audience is the expected audience for the token
Audience string
// JWKSURL is the URL to fetch the JWKS from
JWKSURL string
// ClientID is the OIDC client ID
ClientID string
// ClientSecret is the optional OIDC client secret for introspection
ClientSecret string // #nosec G117 -- not a hardcoded credential, populated at runtime from config
// CACertPath is the path to the CA certificate bundle for HTTPS requests
CACertPath string
// AuthTokenFile is the path to file containing bearer token for authentication
AuthTokenFile string
// AllowPrivateIP allows JWKS/OIDC endpoints on private IP addresses
AllowPrivateIP bool
// InsecureAllowHTTP allows HTTP (non-HTTPS) OIDC issuers for development/testing
// WARNING: This is insecure and should NEVER be used in production
InsecureAllowHTTP bool
// IntrospectionURL is the optional introspection endpoint for validating tokens
IntrospectionURL string
// ResourceURL is the explicit resource URL for OAuth discovery (RFC 9728)
ResourceURL string
// Scopes is the list of OAuth scopes to advertise in the well-known endpoint (RFC 9728)
// If empty, defaults to ["openid"]
Scopes []string
// contains filtered or unexported fields
}
TokenValidatorConfig contains configuration for the token validator.
type TokenValidatorOption ¶ added in v0.9.2
type TokenValidatorOption func(*tokenValidatorOptions)
TokenValidatorOption is a functional option for NewTokenValidator.
func WithEnvReader ¶ added in v0.9.2
func WithEnvReader(reader env.Reader) TokenValidatorOption
WithEnvReader overrides the default environment variable reader. This is primarily used in tests to avoid process-wide env var manipulation.
func WithKeyProvider ¶ added in v0.15.0
func WithKeyProvider(provider keys.PublicKeyProvider) TokenValidatorOption
WithKeyProvider configures the token validator to use an in-process key provider for JWKS lookups instead of fetching keys over HTTP. This is used when the embedded auth server's key provider is available in the same process, eliminating self-referential HTTP calls and the need for insecureAllowHTTP and jwksAllowPrivateIP flags.
Only PublicKeyProvider is required — the validator never signs tokens.
func WithUpstreamTokenReader ¶ added in v0.13.0
func WithUpstreamTokenReader(reader upstreamtoken.TokenReader) TokenValidatorOption
WithUpstreamTokenReader configures the token validator to enrich Identity with upstream provider tokens. When set, the Middleware extracts the token session ID (tsid) from JWT claims, loads all upstream tokens into Identity.UpstreamTokens, and then places the enriched Identity in the request context.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package awssts provides AWS STS token exchange with SigV4 signing support.
|
Package awssts provides AWS STS token exchange with SigV4 signing support. |
|
Package dcr is the shared RFC 7591 Dynamic Client Registration client used by every consumer in the codebase that needs to register a downstream OAuth 2.x client at runtime.
|
Package dcr is the shared RFC 7591 Dynamic Client Registration client used by every consumer in the codebase that needs to register a downstream OAuth 2.x client at runtime. |
|
Package discovery provides authentication discovery utilities for detecting authentication requirements from remote servers.
|
Package discovery provides authentication discovery utilities for detecting authentication requirements from remote servers. |
|
Package oauth provides OAuth 2.0 and OIDC authentication functionality.
|
Package oauth provides OAuth 2.0 and OIDC authentication functionality. |
|
Package obo provides the proxy-runtime middleware factory hook for the on-behalf-of (OBO) external auth type.
|
Package obo provides the proxy-runtime middleware factory hook for the on-behalf-of (OBO) external auth type. |
|
Package remote provides authentication handling for remote MCP servers.
|
Package remote provides authentication handling for remote MCP servers. |
|
Package secrets provides generic secret management utilities for authentication.
|
Package secrets provides generic secret management utilities for authentication. |
|
Package tokensource provides a shared OIDC-backed OAuth token source used by both the LLM gateway client and the registry authentication client.
|
Package tokensource provides a shared OIDC-backed OAuth token source used by both the LLM gateway client and the registry authentication client. |
|
Package upstreamswap provides middleware for exchanging embedded auth server access tokens with upstream IdP tokens.
|
Package upstreamswap provides middleware for exchanging embedded auth server access tokens with upstream IdP tokens. |
|
Package upstreamtoken provides a service for managing upstream IDP token lifecycle, including transparent refresh of expired access tokens.
|
Package upstreamtoken provides a service for managing upstream IDP token lifecycle, including transparent refresh of expired access tokens. |
|
mocks
Package mocks is a generated GoMock package.
|
Package mocks is a generated GoMock package. |