auth

package
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Oct 13, 2026 License: Apache-2.0 Imports: 20 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 auth provides authentication and authorization for the MCP server.

Package auth provides authentication and authorization for the MCP server.

Package auth provides authentication and authorization for the MCP server.

Package auth provides authentication and authorization for the MCP server.

Package auth provides authentication and authorization for the MCP server.

Package auth provides authentication and authorization for the MCP server.

Index

Constants

View Source
const (
	// DefaultJWKSRefreshInterval is how often the Dapr Sentry JWKS is refreshed when not configured.
	DefaultJWKSRefreshInterval = 5 * time.Minute
	// MinJWKSRefreshInterval is the shortest allowed JWKS refresh interval.
	// It is also the cooldown between JWKS fetch attempts, successful or not.
	MinJWKSRefreshInterval = 30 * time.Second
)
View Source
const SPIFFEConnectionTimeout = 10 * time.Second

SPIFFEConnectionTimeout is the maximum time to wait for SPIRE agent connection.

Variables

View Source
var (
	// ErrNoToken is returned when a request carries no token.
	ErrNoToken = errors.New("no authentication token provided")
	// ErrInvalidToken is returned when a token is malformed, badly signed or fails claim checks.
	ErrInvalidToken = errors.New("invalid authentication token")
	// ErrTokenExpired is returned when a token's exp is in the past.
	ErrTokenExpired = errors.New("authentication token expired")
	// ErrInvalidIssuer is returned when a token comes from an unexpected issuer or trust domain.
	ErrInvalidIssuer = errors.New("invalid token issuer")
	// ErrInvalidAudience is returned when a token is not issued for this server.
	ErrInvalidAudience = errors.New("invalid token audience")
	// ErrAuthDisabled is returned when authentication is requested but disabled.
	ErrAuthDisabled = errors.New("authentication is disabled")
	// ErrUnsupportedMethod is returned when the configured auth mode is unknown or its method is not enabled.
	ErrUnsupportedMethod = errors.New("unsupported authentication method")
)

Authentication errors. Authenticators wrap one of these so callers can classify failures with errors.Is.

View Source
var (
	// ErrAuthEnabledRemoved is returned when the removed AUTH_ENABLED variable is set.
	ErrAuthEnabledRemoved = errors.New("AUTH_ENABLED is no longer supported; AUTH_MODE alone turns authentication on (unset or \"disabled\" turns it off)")
	// ErrAuthSkipPathsRemoved is returned when the removed AUTH_SKIP_PATHS variable is set.
	ErrAuthSkipPathsRemoved = errors.New("AUTH_SKIP_PATHS is no longer supported; health endpoints never require authentication and every other path, including the MCP endpoint, always does")
	// ErrOIDCIssuerURLRequired is returned when OIDC is enabled without OIDC_ISSUER_URL.
	ErrOIDCIssuerURLRequired = errors.New("OIDC_ISSUER_URL is required")
	// ErrOIDCClientIDRequired is returned when OIDC is enabled without OIDC_CLIENT_ID.
	ErrOIDCClientIDRequired = errors.New("OIDC_CLIENT_ID is required")
	// ErrSPIFFETrustDomainRequired is returned when SPIFFE is enabled without SPIFFE_TRUST_DOMAIN.
	ErrSPIFFETrustDomainRequired = errors.New("SPIFFE_TRUST_DOMAIN is required")
	// ErrSPIFFEServerIDRequired is returned when SPIFFE is enabled without SPIFFE_SERVER_ID.
	ErrSPIFFEServerIDRequired = errors.New("SPIFFE_SERVER_ID is required")
	// ErrSentryJWKSURLRequired is returned when Dapr Sentry is enabled without DAPR_SENTRY_JWKS_URL.
	ErrSentryJWKSURLRequired = errors.New("DAPR_SENTRY_JWKS_URL is required")
	// ErrSentryTrustDomainRequired is returned when Dapr Sentry is enabled without DAPR_SENTRY_TRUST_DOMAIN.
	ErrSentryTrustDomainRequired = errors.New("DAPR_SENTRY_TRUST_DOMAIN is required")
	// ErrSentryAudienceRequired is returned when Dapr Sentry is enabled without DAPR_SENTRY_AUDIENCE.
	ErrSentryAudienceRequired = errors.New("DAPR_SENTRY_AUDIENCE is required: set it to the audience your Sentry tokens are issued for")
	// ErrSentryRefreshInterval is returned when DAPR_SENTRY_JWKS_REFRESH_INTERVAL is invalid or too short.
	ErrSentryRefreshInterval = errors.New("invalid DAPR_SENTRY_JWKS_REFRESH_INTERVAL")
)

Configuration errors returned by the Validate methods.

View Source
var (
	// ErrJWKSUnavailable is returned when no usable JWKS is cached.
	ErrJWKSUnavailable = errors.New("no JWKS available")
	// ErrJWKSStale is returned when cached keys are older than the maximum staleness
	// because Sentry could not be reached.
	ErrJWKSStale = errors.New("cached JWKS is stale")
	// ErrSigningKeyNotFound is returned when no JWKS key matches the token header.
	ErrSigningKeyNotFound = errors.New("signing key not found in JWKS")
)

Errors returned while fetching or using the Dapr Sentry JWKS.

View Source
var ErrSPIFFEClientNotAllowed = errors.New("SPIFFE client not in allowlist")

ErrSPIFFEClientNotAllowed is returned when a valid SPIFFE ID is not in the configured allowlist.

Functions

func CloseAuthenticators

func CloseAuthenticators(authenticators []Authenticator) error

CloseAuthenticators closes every authenticator that implements io.Closer, such as the SPIFFE authenticator's Workload API connection, and joins any errors.

func IsAuthenticated

func IsAuthenticated(ctx context.Context) bool

IsAuthenticated returns true if the context has an authenticated identity.

func NoopMiddleware

func NoopMiddleware(next http.Handler) http.Handler

NoopMiddleware returns a middleware that does nothing (for disabled auth).

func WithIdentity

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

WithIdentity adds an identity to the context.

Types

type AuthMode

type AuthMode string

AuthMode represents the authentication mode.

const (
	// ModeDisabled disables authentication (for local development).
	ModeDisabled AuthMode = "disabled"
	// ModeOIDC uses OAuth2.0/OIDC for authentication.
	ModeOIDC AuthMode = "oidc"
	// ModeSPIFFE uses SPIFFE JWT-SVIDs for service-to-service auth.
	ModeSPIFFE AuthMode = "spiffe"
	// ModeHybrid accepts both OIDC and SPIFFE tokens.
	ModeHybrid AuthMode = "hybrid"
	// ModeDaprSentry uses Dapr Sentry JWT tokens for authentication.
	ModeDaprSentry AuthMode = "dapr-sentry"
)

type Authenticator

type Authenticator interface {
	// Authenticate validates a token and returns the identity.
	Authenticate(ctx context.Context, token string) (*Identity, error)
	// Mode returns the authentication mode.
	Mode() AuthMode
}

Authenticator is the interface for authentication providers.

type Config

type Config struct {
	// Mode is the authentication mode.
	// Only ModeDisabled turns authentication off; any other value, including
	// the empty string of a zero-value Config, requires authentication and
	// fails Validate unless it names a supported mode.
	// DefaultConfig maps an unset AUTH_MODE to ModeDisabled.
	Mode AuthMode

	// OIDC configuration
	OIDC OIDCConfig

	// SPIFFE configuration
	SPIFFE SPIFFEConfig

	// DaprSentry configuration
	DaprSentry DaprSentryConfig
	// contains filtered or unexported fields
}

Config holds the authentication configuration.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns configuration from environment variables. Values that cannot be parsed are reported by Validate.

func (Config) Enabled

func (c Config) Enabled() bool

Enabled reports whether authentication is required. It is true for every mode other than ModeDisabled, so an unrecognized mode fails closed.

func (*Config) Validate

func (c *Config) Validate() error

Validate reports environment parse errors and missing settings for the selected authentication mode.

type DaprSentryAuthenticator

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

DaprSentryAuthenticator validates JWT tokens issued by Dapr Sentry.

func NewDaprSentryAuthenticator

func NewDaprSentryAuthenticator(ctx context.Context, cfg DaprSentryConfig) (*DaprSentryAuthenticator, error)

NewDaprSentryAuthenticator creates a new Dapr Sentry authenticator that logs to slog.Default.

func NewDaprSentryAuthenticatorWithLogger

func NewDaprSentryAuthenticatorWithLogger(ctx context.Context, cfg DaprSentryConfig, logger *slog.Logger) (*DaprSentryAuthenticator, error)

NewDaprSentryAuthenticatorWithLogger creates a new Dapr Sentry authenticator with a custom logger. A nil logger means slog.Default. The JWKS is fetched once before returning.

func (*DaprSentryAuthenticator) Authenticate

func (a *DaprSentryAuthenticator) Authenticate(ctx context.Context, token string) (*Identity, error)

Authenticate validates a Dapr Sentry JWT token and returns the identity.

func (*DaprSentryAuthenticator) Close

func (a *DaprSentryAuthenticator) Close() error

Close releases idle JWKS connections.

func (*DaprSentryAuthenticator) Mode

Mode returns the authentication mode.

type DaprSentryConfig

type DaprSentryConfig struct {
	// Enabled determines if Dapr Sentry authentication is enabled.
	Enabled bool
	// JWKSUrl is the URL to fetch JWKS from Dapr Sentry.
	JWKSUrl string
	// TrustDomain is the expected trust domain in SPIFFE IDs.
	TrustDomain string
	// Audience is the expected audience claim. It is required.
	Audience string
	// Issuer is the expected iss claim. It is checked only when set.
	Issuer string
	// TokenHeader is the custom header to extract the token from (default: Authorization).
	TokenHeader string
	// RefreshInterval is the interval for refreshing the JWKS cache.
	// Zero means DefaultJWKSRefreshInterval.
	RefreshInterval time.Duration
}

DaprSentryConfig holds Dapr Sentry JWT-specific configuration.

func (*DaprSentryConfig) Validate

func (c *DaprSentryConfig) Validate() error

Validate reports missing or invalid settings when Dapr Sentry is enabled.

type Identity

type Identity struct {
	// Subject is the unique identifier for the identity (e.g., user ID or SPIFFE ID).
	Subject string
	// Issuer is the identity provider that issued the token.
	Issuer string
	// Audience is the intended audience of the token.
	Audience []string
	// Email is the email address (for OIDC identities).
	Email string
	// Name is the display name (for OIDC identities).
	Name string
	// Claims contains all claims from the token.
	Claims map[string]interface{}
	// AuthMethod indicates how the identity was authenticated.
	AuthMethod AuthMode
}

Identity represents an authenticated identity.

func GetIdentity

func GetIdentity(ctx context.Context) *Identity

GetIdentity retrieves the identity from the context.

type Middleware

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

Middleware provides HTTP authentication middleware.

func NewMiddleware

func NewMiddleware(cfg Config, authenticators []Authenticator, logger *slog.Logger) *Middleware

NewMiddleware creates a new authentication middleware.

func (*Middleware) Handler

func (m *Middleware) Handler(next http.Handler) http.Handler

Handler returns an HTTP middleware that authenticates requests.

Every request it wraps is authenticated, with no path exemptions. Health endpoints are registered outside this middleware instead.

type OIDCAuthenticator

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

OIDCAuthenticator authenticates requests using OIDC tokens.

func NewOIDCAuthenticator

func NewOIDCAuthenticator(ctx context.Context, cfg OIDCConfig) (*OIDCAuthenticator, error)

NewOIDCAuthenticator creates a new OIDC authenticator that logs to slog.Default.

func NewOIDCAuthenticatorWithLogger

func NewOIDCAuthenticatorWithLogger(ctx context.Context, cfg OIDCConfig, logger *slog.Logger) (*OIDCAuthenticator, error)

NewOIDCAuthenticatorWithLogger creates a new OIDC authenticator with a custom logger. A nil logger means slog.Default.

func (*OIDCAuthenticator) Authenticate

func (a *OIDCAuthenticator) Authenticate(ctx context.Context, token string) (*Identity, error)

Authenticate validates an OIDC token and returns the identity. Identity.Email is set only when the provider marks the address as verified.

func (*OIDCAuthenticator) Mode

func (a *OIDCAuthenticator) Mode() AuthMode

Mode returns the authentication mode.

type OIDCConfig

type OIDCConfig struct {
	// Enabled determines if OIDC authentication is enabled.
	Enabled bool
	// IssuerURL is the OIDC provider URL.
	IssuerURL string
	// ClientID is the expected audience (aud claim).
	ClientID string
	// AllowedAlgorithms are the allowed signing algorithms.
	AllowedAlgorithms []string
	// SkipIssuerCheck skips issuer validation (dev only).
	SkipIssuerCheck bool
}

OIDCConfig holds OIDC-specific configuration.

func (*OIDCConfig) Validate

func (c *OIDCConfig) Validate() error

Validate reports missing settings when OIDC is enabled.

type SPIFFEAuthenticator

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

SPIFFEAuthenticator authenticates requests using SPIFFE JWT-SVIDs.

func NewSPIFFEAuthenticator

func NewSPIFFEAuthenticator(ctx context.Context, cfg SPIFFEConfig) (*SPIFFEAuthenticator, error)

NewSPIFFEAuthenticator creates a new SPIFFE authenticator. The configuration is validated before connecting to the Workload API.

func (*SPIFFEAuthenticator) Authenticate

func (a *SPIFFEAuthenticator) Authenticate(_ context.Context, token string) (*Identity, error)

Authenticate validates a SPIFFE JWT-SVID and returns the identity.

func (*SPIFFEAuthenticator) Close

func (a *SPIFFEAuthenticator) Close() error

Close closes the Workload API connection. It is safe to call on a partially built authenticator.

func (*SPIFFEAuthenticator) Mode

func (a *SPIFFEAuthenticator) Mode() AuthMode

Mode returns the authentication mode.

type SPIFFEConfig

type SPIFFEConfig struct {
	// Enabled determines if SPIFFE authentication is enabled.
	Enabled bool
	// TrustDomain is the SPIFFE trust domain.
	TrustDomain string
	// ServerID is this server's SPIFFE ID.
	ServerID string
	// EndpointSocket is the Workload API socket path.
	EndpointSocket string
	// AllowedClients are the allowed client SPIFFE IDs.
	AllowedClients []string
}

SPIFFEConfig holds SPIFFE-specific configuration.

func (*SPIFFEConfig) Validate

func (c *SPIFFEConfig) Validate() error

Validate reports missing settings when SPIFFE is enabled.

Jump to

Keyboard shortcuts

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