Documentation
¶
Overview ¶
Package middleware provides composable HTTP middleware for fleet services.
Canonical middleware included:
- RequestID — generates X-Request-ID; injects into context
- Logging — slog JSON per-request log; injects child logger into ctx
- Metrics — per-request counters for /metrics/json
- CORS — canonical CORS headers with safe defaults
- TokenAuth — static-token Bearer validation
- TokenAuthKeystore — fleet-canonical keystore auth
- Chain — compose multiple middlewares left=outermost
Logger retrieval in handlers:
log := middleware.LoggerFromContext(r.Context())
log.Info("processing", "user", userID)
Index ¶
- Constants
- func Chain(h http.Handler, mws ...Middleware) http.Handler
- func ExtractToken(r *http.Request) string
- func GetRequestID(ctx context.Context) string
- func LoggerFromContext(ctx context.Context) *slog.Logger
- func Logging(next http.Handler) http.Handler
- func MatchPublicPathPrefix(path string, prefixes []string) (prefix string, ok bool)
- func RequestID(next http.Handler) http.Handler
- func SPIFFEIDFromContext(ctx context.Context) string
- func SetLogger(l *slog.Logger)
- func WithLogger(ctx context.Context, logger *slog.Logger) context.Context
- type AuthEvent
- type AuthObserver
- type AuthResult
- type AuthSource
- type CORSOptions
- type IdempotencyConfig
- type IdentityAuthenticator
- type IdentityDecision
- type IdentityObserver
- type KeystoreOpts
- type Middleware
- type RateLimiter
- type ScopeChecker
Constants ¶
const IdempotencyCachedHeader = "Idempotency-Cached"
IdempotencyCachedHeader is set on replayed responses so a client (or a debug proxy) can tell a cached reply from a freshly-computed one.
const IdempotencyKeyHeader = "Idempotency-Key"
IdempotencyKeyHeader is the request header used to key the cache. Standard across the fleet — clients retrying a mutating request set the same key so the server can dedupe.
const RequestIDKey contextKey = "request_id"
Variables ¶
This section is empty.
Functions ¶
func Chain ¶
func Chain(h http.Handler, mws ...Middleware) http.Handler
Chain applies a list of middlewares to a handler
func ExtractToken ¶
ExtractToken pulls the API key from the three canonical sources, in priority order:
- Authorization: Bearer <key> — what every SDK and API gateway sends
- X-API-Key: <key> — legacy header alias
- ?api_key=<key> — accepted for compatibility; avoid it because URLs are commonly copied into logs and browser history.
Path-token extraction is not supported. Send credentials in a header.
Exported (v0.76.0) so callers outside this package can forward the SAME credential the middleware itself trusts — canonically go-common/ledger.CredentialFromRequest, which needs the caller's own token to attribute a metered charge to the right account instead of the forwarding service's own FLEET_API_KEY.
func GetRequestID ¶
GetRequestID helper to extract ID from context
func LoggerFromContext ¶
LoggerFromContext retrieves the per-request logger injected by the Logging middleware. Falls back to the default slog logger so callers don't need to handle the nil case.
func MyHandler(w http.ResponseWriter, r *http.Request) {
log := middleware.LoggerFromContext(r.Context())
log.Info("processing", "user", userID)
}
func Logging ¶
Logging logs request details using slog and injects a per-request child logger (enriched with request_id, method, path) into the context so downstream handlers can call middleware.LoggerFromContext(r.Context()).
When LOG_SKIP_PATHS is set (comma-separated path prefixes, e.g. "/health,/metrics"), the request_completed entry for matching paths is emitted at DEBUG level instead of INFO. This suppresses health-check noise without losing the events entirely. When LOG_SKIP_PATHS is unset or empty, all requests are logged at INFO (fully backward-compatible).
func MatchPublicPathPrefix ¶
MatchPublicPathPrefix reports the first of prefixes that makes KeystoreOpts.PublicPathPrefixes treat path as public, and whether there is one. It is the gate's own prefix test, a plain prefix match in which "" and "/" never match, exposed so that a router can check its routes against the rule the gate applies instead of keeping a second copy of it. It looks only at the string it is given: the gate also requires the request path to be canonical, see KeystoreOpts.PublicPathPrefixes.
func SPIFFEIDFromContext ¶ added in v0.113.0
SPIFFEIDFromContext returns the verified SPIFFE ID of a request that TokenAuthKeystore authenticated through the SPIFFE path, or "".
Types ¶
type AuthEvent ¶
type AuthEvent struct {
Source AuthSource
Result AuthResult
Duration time.Duration
}
AuthEvent is the per-request payload handed to an AuthObserver. Source records which code path made the decision (so operators can see, e.g., what fraction of traffic is already gateway-authenticated vs. hitting the keystore). Result records the outcome.
type AuthObserver ¶
type AuthObserver interface {
ObserveAuth(AuthEvent)
}
AuthObserver receives one event per request that passes through TokenAuthKeystore. Implementations MUST NOT block — callbacks run inline on the request hot path. The canonical implementation lives in go-common/promx and records Prometheus counters/histograms.
middleware deliberately defines the contract here rather than importing a metrics library directly: go-common/middleware keeps zero metric-stack deps, services pull in promx (and its client_golang transitive set) only when they want fleet metrics.
type AuthResult ¶
type AuthResult string
AuthResult buckets the outcome.
const ( AuthResultAllow AuthResult = "allow" AuthResultDeny AuthResult = "deny" // 401: invalid or missing token // AuthResultTierDenied: the caller authenticated fine but their tier // (possibly "", e.g. the local-token/private-mesh paths, which never // verify a tier at all) doesn't satisfy KeystoreOpts.RequiredTier, and // TierEnforce is true — 403, request rejected. AuthResultTierDenied AuthResult = "deny-tier" // AuthResultTierShadowDenied: same mismatch as above, but TierEnforce // is false — the request is ALLOWED (shadow mode: observe what would // happen without actually breaking traffic) while this result still // fires so an operator can watch the would-be-denied rate before // flipping TierEnforce to true. AuthResultTierShadowDenied AuthResult = "shadow-deny-tier" )
type AuthSource ¶
type AuthSource string
AuthSource buckets the path that produced the auth decision.
const ( // AuthSourceSPIFFEMTLS: authenticated by an X.509-SVID presented over mTLS // and mapped to a principal (package spiffeauth). AuthSourceSPIFFEMTLS AuthSource = "spiffe-mtls" // AuthSourceSPIFFEJWT: authenticated by an audience-scoped JWT-SVID. AuthSourceSPIFFEJWT AuthSource = "spiffe-jwt" )
const ( AuthSourceBypass AuthSource = "bypass" // exempt path: /health, /version, /_gw_health, /capabilities, /openapi.json, /agent.json AuthSourceGateway AuthSource = "gateway" // upstream nginx set the trust header AuthSourceLocal AuthSource = "local" // local-token fast path AuthSourceKeystore AuthSource = "keystore" // upstream keystore call (possibly cached) AuthSourceMissing AuthSource = "missing" // no token presented // AuthSourcePrivateMesh: trusted because the actual TCP peer is a // private/mesh IP with no gateway header (opt-in TrustPrivateMesh). AuthSourcePrivateMesh AuthSource = "private-mesh" )
type CORSOptions ¶
type CORSOptions struct {
// AllowedOrigins is the list of origins that are allowed. Use "*"
// to allow all origins (not recommended for credentialed requests).
// An empty list disables CORS (no Access-Control-Allow-Origin header).
AllowedOrigins []string
// AllowedMethods lists the HTTP methods allowed for CORS requests.
// Default (when nil): GET, POST, PUT, PATCH, DELETE, OPTIONS.
AllowedMethods []string
// AllowedHeaders lists the request headers allowed in CORS requests.
// Default (when nil): Content-Type, Authorization, X-API-Key,
// X-Request-ID.
AllowedHeaders []string
// ExposedHeaders lists response headers accessible to the browser.
ExposedHeaders []string
// AllowCredentials sets Access-Control-Allow-Credentials: true.
// Must NOT be combined with AllowedOrigins=["*"] — browsers block that.
AllowCredentials bool
// MaxAgeSecs sets Access-Control-Max-Age (preflight cache duration).
// Default 3600 (1 hour). Set to -1 to omit the header.
MaxAgeSecs int
}
CORSOptions configures the CORS middleware. The zero value is safe and denies all cross-origin requests (same as no CORS headers).
type IdempotencyConfig ¶
type IdempotencyConfig struct {
// TTL is the maximum age of a cached response. After TTL elapses,
// the next request with the same key re-executes the handler.
// Default: 1 hour.
TTL time.Duration
// MaxEntries caps the in-memory cache size to bound RAM. Eviction is
// LRU. Default: 10000.
MaxEntries int
// RequiredMethods is the set of HTTP methods that consult the cache.
// Default: {POST, PUT, PATCH, DELETE}. GET/HEAD are skipped (no
// body, idempotent by HTTP spec).
RequiredMethods []string
// contains filtered or unexported fields
}
IdempotencyConfig configures the idempotency-key cache.
type IdentityAuthenticator ¶ added in v0.113.0
type IdentityAuthenticator interface {
AuthenticateIdentity(r *http.Request) IdentityDecision
// ExpectedPrincipal reports whether keystoreUser is a principal that has a
// SPIFFE mapping (so a request that authenticated it with an API key is a
// fallback), and returns the operator-configured principal string.
ExpectedPrincipal(keystoreUser string) (string, bool)
}
IdentityAuthenticator verifies the SPIFFE identity of a request. Implemented by spiffeauth.Authenticator. Methods run on the request hot path and must not block on the network.
type IdentityDecision ¶ added in v0.113.0
type IdentityDecision struct {
// Presented: the caller offered a SPIFFE identity (an SVID certificate or a
// JWT-SVID). false means nothing in this request concerns the SPIFFE path.
Presented bool
// Allowed: the identity verified and maps to a principal. Principal, Scope,
// Tier and SPIFFEID are set.
Allowed bool
// Source is AuthSourceSPIFFEMTLS or AuthSourceSPIFFEJWT (when Presented).
Source AuthSource
// SPIFFEID is the verified SPIFFE ID (only when Allowed).
SPIFFEID string
// Principal, Scope and Tier come from the operator's peer map.
Principal, Scope, Tier string
// Reason is a short, bounded token naming why a presented identity was not
// allowed (for the failure counter). Never request data.
Reason string
// Deny: refuse the request now with Status (401 or 403) instead of trying
// the API key path (an SVID of an ID that is not in the map, by default).
Deny bool
Status int
// BearerIsSVID: the Authorization bearer value was a JWT-SVID, so the API key
// path must not read it as an API key (and must not send it to the keystore).
BearerIsSVID bool
}
IdentityDecision is what an IdentityAuthenticator concludes about one request.
type IdentityObserver ¶ added in v0.113.0
type IdentityObserver interface {
// ObserveIdentityFailure: a presented SPIFFE identity was not accepted.
// reason is one of the spiffeauth.Reason* tokens.
ObserveIdentityFailure(source AuthSource, reason string)
// ObserveIdentityFallback: SPIFFE was expected for principal (it has a
// mapping) but the request was authenticated with an API key. reason is
// "no_svid" or the reason the presented identity failed.
ObserveIdentityFallback(principal, reason string)
}
IdentityObserver is optional: an AuthObserver that also implements it receives the SPIFFE failure and fallback events. promx.AuthCollectors does.
type KeystoreOpts ¶
type KeystoreOpts struct {
// Verifier is the keystore client (or its Cache wrapper). Required.
Verifier apikey.Verifier
// LocalTokens are optional service-owned credentials accepted without
// hitting the keystore. Retired public fallback values are always denied.
LocalTokens []string
// TrustGatewayHeader: if non-empty, requests carrying this header are
// treated as already-authenticated (the gateway sets X-Auth-User after
// the keystore returned 200). Skip both keystore and local check.
// Default header.AuthUser.
TrustGatewayHeader string
// TrustedGatewayCIDRs optionally constrains the gateway header fast path
// to real TCP peers in these CIDRs. When empty, legacy behavior is
// preserved for existing fleet services. Security-sensitive services that
// accept direct private-network connections must set this: otherwise any
// direct caller able to reach their port could forge X-Auth-User.
//
// Invalid entries are ignored and never widen trust. With a non-empty but
// wholly invalid list, no peer is trusted and callers must present a key.
TrustedGatewayCIDRs []string
// TrustPrivateMesh, when true, treats a request whose actual TCP peer
// (r.RemoteAddr — NOT a spoofable header) is a private/loopback IP AND
// that carries no gateway trust header as already-authenticated. This is
// the "container-to-container on the docker mesh" trust the fleet fetch
// cache relies on, made reusable: an expensive internal-only service
// (e.g. the chromedp js-proxy) can be reached no-auth by sibling
// containers while its PUBLIC gateway URL stays fully keystore-gated.
//
// Safe because: public clients can only reach the container via nginx,
// which connects from the gateway and sets the trust header (so they take
// the gateway path, not this one); a public client cannot present a
// private source IP on the container's network. Default false — no effect
// on any service that doesn't opt in.
TrustPrivateMesh bool
// VerifyTimeout caps the upstream keystore call. Default 3s.
VerifyTimeout time.Duration
// Logger receives one-line audit lines for accepted/rejected requests.
// nil = use the default package log. Pass a no-op to silence.
Logger *log.Logger
// Observer (optional) receives one AuthEvent per request describing
// which code path made the decision and how long the verifier call
// took. promx.NewAuthCollectors() returns an implementation that
// records fleet-canonical Prometheus metrics.
Observer AuthObserver
// OutOfBandScopeCheck enables defense-in-depth verification that the
// gateway-supplied X-Auth-Scope matches what the keystore actually
// reports for the principal. Opt-in (default false) because it costs
// one extra keystore call per (key, scope) per 5 min per service.
//
// Threat model: if the gateway were ever compromised (or a non-gateway
// caller forged X-Auth-* headers and bypassed nginx via the docker
// mesh), a service trusting only the gateway header would honor a
// forged scope. With this on, every request whose scope is consumed
// for an authorization decision is independently re-verified via
// apikey.Client.VerifyScope, which calls /verify and compares the
// keystore's authoritative scope to the claimed one.
//
// On mismatch the request is rejected 401. On keystore outage the
// request follows the same fail-closed path as the primary keystore
// check (503).
//
// The check only runs on the gateway-header trust path (step 2) —
// the keystore-lookup path (step 5) already sets X-Auth-Scope from
// the same authoritative response and is not vulnerable.
//
// Requires ScopeChecker to be set (typically the underlying
// *apikey.Client) AND the request to carry a usable token (Bearer /
// X-API-Key / ?api_key). If only the gateway header is set with no
// key, the check cannot run and the request is rejected.
OutOfBandScopeCheck bool
// ScopeChecker performs the out-of-band re-verification. Required
// when OutOfBandScopeCheck is true. Typically the underlying
// *apikey.Client (the *apikey.Cache wrapper used as Verifier does
// not expose VerifyScope — keep a reference to the raw client).
ScopeChecker ScopeChecker
// RequiredTier, when non-empty, gates every authenticated request
// through apikey.TierSatisfies(callerTier, RequiredTier) before
// dispatch — regardless of WHICH trust path authenticated the caller.
// Paths that never verify a real tier (the local-token fast path,
// TrustPrivateMesh) are treated as callerTier == "", which fails
// closed against any non-empty RequiredTier by construction: a demo
// key or a container-to-container call can never satisfy a tier gate,
// there is no special-case to forget. Default "" — no effect on any
// service that doesn't opt in (the ~100+ existing keystore consumers
// that predate tiering are unaffected).
RequiredTier string
// TierEnforce controls whether a tier mismatch actually rejects the
// request (true → 403) or only observes it (false → shadow mode:
// the request is allowed and an AuthResultTierShadowDenied event
// fires, so an operator can watch the would-be-denied rate via
// Observer/metrics before flipping this on). Mirrors this fleet's own
// LEDGER_OVERFLOW_ENABLED/ENFORCE pattern (ADR-0036/0037) for the same
// reason: don't cliff-edge a new authorization rule into production.
// Has no effect when RequiredTier == "".
TierEnforce bool
// PublicPathPrefixes name request paths that bypass the keystore gate
// entirely, in addition to the fixed /health, /version, /selftest, ...
// list — a prefix match, so "/c/" also covers "/c/<token>/<id>". For a
// handler whose OWN unguessable value is its access control (an
// out-of-band callback catcher keyed on a random token in the path,
// not a keystore credential — the caller is a scanned target that can
// never be handed a service's key), declaring its exact prefix here is
// the supported way to exempt it, in place of hand-rolling a bypass
// inside the handler. An empty string or "/" is ignored rather than
// honored: either would make every route public, the one widening this
// field must never cause by a configuration mistake. Default nil — no
// effect on any service that doesn't opt in.
//
// The exemption applies only to a canonical path (the same rule covers the
// fixed /health, /version, ... list): no "." or ".." segment, no "//", no
// encoded dot, slash or backslash (%2e, %2f, %5c) in the raw or the decoded
// form, and at most a trailing slash. A request that names a public path in
// any other form is answered 400 and goes no further, with or without a key,
// because routers differ in how they read such a path (one redirects it, one
// cleans it, one decodes it twice), and the exemption must not depend on that.
// The refusal is observed as AuthSourceBypass with AuthResultDeny. Send the
// canonical path.
//
// Never declare a prefix that also serves a keystore-gated route:
// everything under it is unauthenticated, for every method, with no
// per-route override. server.WithKeystoreAuthPublicPrefixes checks the
// routes registered through the server's own helpers against the prefixes
// when Start runs; this field cannot, because it sees no routes.
PublicPathPrefixes []string
// Identity (optional) adds the SPIFFE identity path in DUAL MODE: a request
// carrying a valid X.509-SVID (mTLS) or JWT-SVID that the operator's peer
// map knows is authenticated as the mapped principal and tier, before the
// gateway, local-token and keystore checks; a request with no SPIFFE
// identity goes through those checks exactly as when this is nil. Nothing
// is ever rejected for lacking a SPIFFE identity. Implemented by
// spiffeauth.Authenticator; server.New wires it from SPIFFEAUTH_MODE.
// Default nil: no effect on any service that doesn't opt in.
Identity IdentityAuthenticator
}
TokenAuthKeystore is the canonical fleet auth middleware once a service has been migrated to keystore-backed validation.
- Trust the gateway. Every request that reaches the service through nginx has already been validated by the gateway's auth_request → keystore /verify chain. We don't second-guess.
- Local fallback only. If the gateway is somehow bypassed (direct container access during dev, internal mesh callers without nginx), fall back to the same static-list check as the legacy TokenAuth so existing behavior doesn't regress.
Migration path for a service:
r := mux.NewRouter()
import "github.com/baditaflorin/go-common/middleware"
import "github.com/baditaflorin/go-common/apikey"
ks := apikey.NewCache(apikey.New())
r.Use(middleware.TokenAuth([]string{os.Getenv("API_KEYS")…}))
r.Use(middleware.TokenAuthKeystore(middleware.KeystoreOpts{
Verifier: ks,
LocalTokens: strings.Split(os.Getenv("API_KEYS"), ","),
}))
One-line library change → every service that bumps go-common picks up keystore auth. No per-repo handler rewrite.
type Middleware ¶
Middleware is a standard function that wraps an http.Handler
func CORS ¶
func CORS(opts CORSOptions) Middleware
CORS returns an http.Handler middleware that sets canonical CORS response headers according to opts. It handles OPTIONS preflight requests by returning 204 No Content immediately, and sets CORS headers on all other responses.
Secure defaults:
- AllowedOrigins must be explicit; "*" is accepted but logged.
- AllowCredentials + wildcard origin is rejected with a panic.
- MaxAgeSecs defaults to 3600.
Usage:
server.New(cfg, server.WithMiddleware(
middleware.CORS(middleware.CORSOptions{
AllowedOrigins: []string{"https://app.example.com"},
}),
))
func IdempotencyKey ¶
func IdempotencyKey(cfg IdempotencyConfig) Middleware
IdempotencyKey returns a middleware that dedupes mutating requests bearing an Idempotency-Key header. See IdempotencyConfig for tuning.
Behavior:
- Empty header: passthrough (no caching).
- Method not in RequiredMethods (default POST/PUT/PATCH/DELETE): passthrough.
- Cache HIT: cached body, status, and Content-Type are replayed. The handler is NOT invoked. Idempotency-Cached: true is set.
- Cache MISS: handler runs once (via singleflight). 2xx and 4xx responses are cached; 5xx is NOT (transient errors should be retriable, not poisoned into the cache).
Caveats:
- Only body, status, and Content-Type are cached. Custom headers set by the handler do not survive a replay.
- The cache is process-local. Multi-replica services need an external store (out of scope for this middleware).
func Metrics ¶
func Metrics(stats *metrics.Stats) Middleware
MetricsMiddleware records request stats
func RateLimit ¶
func RateLimit(limit int, burst int) Middleware
RateLimit creates a middleware that enforces rate limits
func TokenAuth ¶
func TokenAuth(validTokens []string) Middleware
TokenAuth creates a middleware that validates against a list of allowed tokens. Sources checked, in order of precedence:
- Authorization: Bearer <token>
- X-API-Key: <token>
- ?api_key=<token> query param (compatibility only; avoid in new clients)
The /health, /version, /selftest, /capabilities, /openapi.json, and /agent.json paths bypass auth regardless of token. /capabilities and /openapi.json are scraped unauthenticated by the catalog and hub so users can discover query flags and the API surface; /agent.json is the agent contract — an agent must read it BEFORE it has a key, so it must be reachable unauthenticated.
func TokenAuthKeystore ¶
func TokenAuthKeystore(opts KeystoreOpts) Middleware
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter manages rate limits per visitor
func NewRateLimiter ¶
func NewRateLimiter(r rate.Limit, b int) *RateLimiter
NewRateLimiter creates a new rate limiter r: limit (events per second) b: burst size