auth

package
v0.6.4 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2025 License: Apache-2.0 Imports: 24 Imported by: 0

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

View Source
const GitHubTokenCheckURL = "api.github.com/applications"

GitHubTokenCheckURL is the base URL pattern for GitHub OAuth token validation

View Source
const GoogleTokeninfoURL = "https://oauth2.googleapis.com/tokeninfo" //nolint:gosec

GoogleTokeninfoURL is the Google OAuth2 tokeninfo endpoint URL

View Source
const (
	MiddlewareType = "auth"
)

Middleware type constant

View Source
const WellKnownOAuthResourcePath = "/.well-known/oauth-protected-resource"

WellKnownOAuthResourcePath is the RFC 9728 standard path for OAuth Protected Resource metadata. Per RFC 9728 Section 3, this endpoint and any subpaths under it should be accessible without authentication to enable OIDC/OAuth discovery.

Example valid paths:

  • /.well-known/oauth-protected-resource
  • /.well-known/oauth-protected-resource/mcp
  • /.well-known/oauth-protected-resource/v1/metadata

Variables

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

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

func AnonymousMiddleware(next http.Handler) http.Handler

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

func EscapeQuotes(s string) string

EscapeQuotes escapes quotes in a string for use in a quoted-string context.

func ExtractBearerToken added in v0.5.2

func ExtractBearerToken(r *http.Request) (string, error)

ExtractBearerToken extracts and validates a Bearer token from the Authorization header. It performs the following validations:

  1. Verifies the Authorization header is present
  2. Checks for the "Bearer " prefix (case-sensitive per RFC 6750)
  3. 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,
) (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 middleware. Otherwise, it returns local user middleware.

func LocalUserMiddleware added in v0.0.38

func LocalUserMiddleware(username string) func(http.Handler) http.Handler

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

func NewAuthInfoHandler(issuer, jwksURL, resourceURL string, scopes []string) http.Handler

NewAuthInfoHandler creates an HTTP handler that returns RFC-9728 compliant OAuth Protected Resource metadata

func NewWellKnownHandler added in v0.5.2

func NewWellKnownHandler(authInfoHandler http.Handler) http.Handler

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, this function returns nil (no handler registration needed).

Usage:

authInfoHandler := auth.NewAuthInfoHandler(issuer, jwksURL, resourceURL, scopes)
wellKnownHandler := auth.NewWellKnownHandler(authInfoHandler)
if wellKnownHandler != nil {
    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.

func WithIdentity added in v0.6.0

func WithIdentity(ctx context.Context, identity *Identity) context.Context

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{Subject: "user123", Name: "Alice"}
ctx = WithIdentity(ctx, identity)

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

func (g *GitHubProvider) IntrospectToken(ctx context.Context, token string) (jwt.MapClaims, error)

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

func (g *GoogleProvider) IntrospectToken(ctx context.Context, token string) (jwt.MapClaims, error)

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 {
	// 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

	// Name is the human-readable name (from 'name' claim).
	Name string

	// Email is the email address (from 'email' claim, if available).
	Email string

	// 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

	// Claims contains additional claims from the auth token.
	// This preserves all JWT claims for authorization policies.
	Claims map[string]any

	// 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
}

Identity represents an authenticated user or service account. This is the primary type for representing authenticated principals throughout ToolHive.

func IdentityFromContext added in v0.6.0

func IdentityFromContext(ctx context.Context) (*Identity, bool)

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) MarshalJSON added in v0.6.0

func (i *Identity) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler to redact sensitive fields during JSON serialization. This prevents accidental token leakage in structured logs, API responses, or audit logs.

func (*Identity) String added in v0.6.0

func (i *Identity) String() string

String returns a string representation of the Identity with sensitive fields redacted. This prevents accidental token leakage when the Identity is logged or printed.

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 automatically marks workloads as unauthenticated when tokens expire or fail. It provides both per-request token retrieval and background monitoring.

func NewMonitoredTokenSource added in v0.6.0

func NewMonitoredTokenSource(
	ctx context.Context,
	tokenSource oauth2.TokenSource,
	workloadName string,
	statusUpdater StatusUpdater,
) *MonitoredTokenSource

NewMonitoredTokenSource creates a new MonitoredTokenSource that wraps the provided oauth2.TokenSource and monitors it for authentication failures.

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) Token added in v0.6.0

func (mts *MonitoredTokenSource) Token() (*oauth2.Token, error)

Token retrieves a token from the token source and will mark the workload as unauthenticated if the token retrieval fails.

type OIDCDiscoveryDocument added in v0.0.39

type OIDCDiscoveryDocument struct {
	Issuer                string `json:"issuer"`
	AuthorizationEndpoint string `json:"authorization_endpoint"`
	TokenEndpoint         string `json:"token_endpoint"`
	UserinfoEndpoint      string `json:"userinfo_endpoint"`
	JWKSURI               string `json:"jwks_uri"`
	IntrospectionEndpoint string `json:"introspection_endpoint"`
}

OIDCDiscoveryDocument represents the OIDC discovery document structure

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

func (r *RFC7662Provider) IntrospectToken(ctx context.Context, token string) (jwt.MapClaims, error)

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"`
	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) (*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

	// 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
	// contains filtered or unexported fields
}

TokenValidatorConfig contains configuration for the token validator.

func NewTokenValidatorConfig added in v0.1.3

func NewTokenValidatorConfig(issuer, audience, jwksURL, clientID string, clientSecret string) *TokenValidatorConfig

NewTokenValidatorConfig creates a new TokenValidatorConfig with the provided parameters

Directories

Path Synopsis
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 remote provides authentication handling for remote MCP servers.
Package remote provides authentication handling for remote MCP servers.
Package tokenexchange provides OAuth 2.0 Token Exchange (RFC 8693) support.
Package tokenexchange provides OAuth 2.0 Token Exchange (RFC 8693) support.

Jump to

Keyboard shortcuts

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