Documentation
¶
Overview ¶
Package auth provides authentication primitives and principal handling for Keel application services.
Responsibilities:
- Principal type carrying verified identity claims
- Context getter/setter for propagating principals through the call stack
- TokenVerifier and SubjectStateChecker interfaces (adapters live outside this package)
- RBAC helpers for role and scope inspection
- HTTP middleware that authenticates requests via Bearer tokens
This package handles authentication only. Authorization (resource ownership, policy evaluation) must be implemented in project-specific code.
Production usage requires an OIDC+JWKS verifier. The HMACVerifier provided in platform/testkit is test-only and must not be used in production deployments.
Index ¶
Constants ¶
This section is empty.
Variables ¶
var DefaultAllowedAlgorithms = []string{"RS256", "RS384", "RS512", "ES256", "ES384"}
DefaultAllowedAlgorithms is the default set of algorithms accepted by JWKSVerifier when JWKSConfig.AllowedAlgorithms is empty. Per security-baseline.md §4 only asymmetric algorithms are permitted.
Functions ¶
func Middleware ¶
func Middleware(verifier TokenVerifier, opts ...MiddlewareOption) httpx.Middleware
Middleware returns an httpx.Middleware that authenticates incoming requests using a Bearer token extracted from the Authorization header.
On success the verified Principal is stored in the request context via WithPrincipal. On any failure the middleware writes a problem+json response with status 401 and does NOT call the next handler (fail-closed).
The middleware never silently bypasses authentication. There is no environment-profile toggle or test shortcut inside this function.
Usage:
mux.Handle("/api/", httpx.Adapt(
httpx.Chain(handler, auth.Middleware(verifier)),
nil,
))
Types ¶
type JWKSConfig ¶
type JWKSConfig struct {
// IssuerURL is the OIDC issuer base URL (e.g. "https://auth.example.com").
// Must not be empty. Used for iss claim validation and OIDC discovery.
IssuerURL string
// Audience is the expected JWT "aud" claim value. Must not be empty.
Audience string
// JWKSURL is the direct JWKS endpoint URL. When empty the verifier performs
// OIDC discovery by fetching IssuerURL+"/.well-known/openid-configuration".
JWKSURL string
// AllowedAlgorithms is the explicit set of signature algorithms this
// service accepts. Per security-baseline.md §4 accepted algorithms must
// be explicitly configured. When empty, DefaultAllowedAlgorithms is used.
// HMAC algorithms (HS*) and "none" are always rejected regardless of
// this setting.
AllowedAlgorithms []string
// CacheTTL controls how long the fetched key set is considered valid.
// Defaults to 5 minutes when zero or negative.
CacheTTL time.Duration
// HTTPClient is used for all outbound HTTP requests. When nil a client
// with a 10-second timeout is created automatically. Caller-supplied
// clients must keep TLS verification enabled and set a positive Timeout.
HTTPClient *http.Client
}
JWKSConfig holds the configuration for a JWKSVerifier.
type JWKSVerifier ¶
type JWKSVerifier struct {
// contains filtered or unexported fields
}
JWKSVerifier is the production TokenVerifier that validates JWTs against a remote JWKS endpoint. It is safe for concurrent use.
func NewJWKSVerifier ¶
func NewJWKSVerifier(cfg JWKSConfig) (*JWKSVerifier, error)
NewJWKSVerifier constructs and initialises a JWKSVerifier from cfg. When cfg.JWKSURL is empty, OIDC discovery is performed automatically. The initial JWKS fetch happens during construction; an error is returned if it fails.
func (*JWKSVerifier) Verify ¶
Verify implements TokenVerifier.
Steps:
- Split and base64url-decode header, payload, and signature segments.
- Extract "alg" and "kid" from the decoded header.
- Reject HMAC algorithms immediately (before any key lookup).
- Locate the matching public key; refresh the cache once on a miss.
- Verify the asymmetric signature over "header.payload".
- Decode and validate the JWT claims (iss, aud, exp, iat, sub, jti).
- Return a populated Principal.
type MiddlewareOption ¶
type MiddlewareOption func(*middlewareConfig)
MiddlewareOption is a functional option for the auth Middleware.
func WithSubjectStateChecker ¶
func WithSubjectStateChecker(checker SubjectStateChecker) MiddlewareOption
WithSubjectStateChecker attaches a SubjectStateChecker to the middleware. When set, the checker is called after successful token verification. A non-nil error from the checker rejects the request with CodeUnauthenticated.
type Principal ¶
type Principal struct {
// Subject is the unique identifier of the authenticated entity (JWT "sub").
Subject string
// Issuer identifies the token issuer (JWT "iss").
Issuer string
// Audience lists the intended recipients of the token (JWT "aud").
Audience []string
// SessionID is the optional session identifier (JWT "sid").
SessionID string
// Roles contains application-specific role names (JWT "roles").
Roles []string
// Scopes contains OAuth2 scope strings (JWT "scope", space-split or array).
Scopes []string
// TokenVersion is used for revocation via version comparison (JWT "ver").
TokenVersion int
// ExpiresAt is the token expiry time (JWT "exp").
ExpiresAt time.Time
// IssuedAt is the time the token was issued (JWT "iat").
IssuedAt time.Time
// JTI is the unique token identifier (JWT "jti").
JTI string
}
Principal carries the verified identity claims extracted from an access token. All fields are populated by the TokenVerifier; consumers must treat the value as read-only after it has been placed into a context.
func PrincipalFromContext ¶
PrincipalFromContext retrieves the Principal previously stored by WithPrincipal. Returns the zero Principal and false when no principal is present.
func (Principal) HasAnyRole ¶
HasAnyRole reports whether the principal holds at least one of the given roles.
func (Principal) HasAnyScope ¶
HasAnyScope reports whether the principal holds at least one of the given scopes.
type SubjectStateChecker ¶
SubjectStateChecker performs a secondary check against live subject state, such as revocation lists or token-version databases.
A non-nil error causes the middleware to reject the request with CodeUnauthenticated regardless of the token's cryptographic validity.
type TokenVerifier ¶
TokenVerifier verifies a raw access token string and returns the verified Principal on success. Implementations must reject expired tokens, tokens with invalid signatures, and tokens missing required claims.
Errors returned must be platform errors with CodeUnauthenticated so that the middleware can translate them correctly.