middleware

package
v0.135.1 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: Apache-2.0 Imports: 28 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 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

View Source
const (
	EnvXAuthTrustMode    = "XAUTH_TRUST_MODE"
	EnvXAuthTrustedCIDRs = "XAUTH_TRUSTED_CIDRS"

	XAuthModeOff     = "off"
	XAuthModeShadow  = "shadow"
	XAuthModeEnforce = "enforce"

	// DefaultXAuthTrustedCIDRs is the CT10 nginx gateway: every request that came through it reaches
	// the upstream with that TCP peer address (measured 2026-11-01 for infrastructure-fetch-cache).
	DefaultXAuthTrustedCIDRs = "10.10.10.10/32"
)

X-Auth-* trust (ephemeral-credentials program, phase 3 stream "xauth").

The gateway (CT10 nginx) verifies a caller's key and forwards the request with X-Auth-User/Scope/Tier from the keystore's answer; TokenAuthKeystore admits a request that carries X-Auth-User without asking the keystore again. Without KeystoreOpts.TrustedGatewayCIDRs that trust is given to ANY TCP peer (the legacy contract every WithKeystoreAuth* option keeps): whoever can reach the container port directly (the host's 10.10.10.0/24 address, a published port on 0.0.0.0, a tailnet address, a docker-network neighbour) can send X-Auth-User and use the service without a key. infrastructure-fetch-cache closed it for itself in 0.3.62 (XAUTH_TRUST_MODE). The variables below give every service the same switch without touching its code.

XAUTH_TRUST_MODE      off (default): today's behavior, no counting, nothing read from the request
                      shadow: the same behavior, plus xauth_untrusted_total counts every request
                      that carries X-Auth-User from a peer outside XAUTH_TRUSTED_CIDRS and logs
                      one line per peer, caller and credential per minute
                      enforce: X-Auth-* is trusted only from XAUTH_TRUSTED_CIDRS; from any other
                      peer the headers are dropped and the request goes through the ordinary
                      JWT-SVID / API key checks (a valid key or JWT-SVID is still served, a
                      request with neither gets 401)
XAUTH_TRUSTED_CIDRS   comma separated, default 10.10.10.10/32 (the CT10 gateway, the one address
                      that forwards verified headers to a service on the 0docker dockerhost)

An explicit KeystoreOpts.TrustedGatewayCIDRs (server.WithKeystoreAuthTierTrustedProxy) always wins: the variables are then ignored. An unknown mode is off, and says so in the log. A trusted list that parses to nothing falls back to the default address in enforce mode, so a typo can never turn enforce into "trust everyone".

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

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

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

func ExtractToken(r *http.Request) string

ExtractToken pulls the API key from the three canonical sources, in priority order:

  1. Authorization: Bearer <key> — what every SDK and API gateway sends
  2. X-API-Key: <key> — legacy header alias
  3. ?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

func GetRequestID(ctx context.Context) string

GetRequestID helper to extract ID from context

func LoggerFromContext

func LoggerFromContext(ctx context.Context) *slog.Logger

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

func Logging(next http.Handler) http.Handler

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

func MatchPublicPathPrefix(path string, prefixes []string) (prefix string, ok bool)

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 RequestID

func RequestID(next http.Handler) http.Handler

RequestID generates a unique ID for each request if not present

func SPIFFEIDFromContext added in v0.113.0

func SPIFFEIDFromContext(ctx context.Context) string

SPIFFEIDFromContext returns the verified SPIFFE ID of a request that TokenAuthKeystore authenticated through the SPIFFE path, or "".

func SetLogger

func SetLogger(l *slog.Logger)

SetLogger replaces the logger the access log, and the per-request child logger handed out by LoggerFromContext, are built from. server.New calls it when structured logging is switched on. It assigns a plain variable: call it once at start-up, before serving.

func WithLogger

func WithLogger(ctx context.Context, logger *slog.Logger) context.Context

WithLogger injects logger into ctx. Used internally by the Logging middleware and available for testing (inject a no-op logger).

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
	AuthResultUnavailable AuthResult = "unavailable" // 503: keystore down + no cache

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

type Middleware func(http.Handler) http.Handler

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:

  1. Authorization: Bearer <token>
  2. X-API-Key: <token>
  3. ?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

type ScopeChecker

type ScopeChecker interface {
	VerifyScope(ctx context.Context, key, claimedScope string) error
}

ScopeChecker is the abstract interface for out-of-band scope verification. *apikey.Client satisfies it via its VerifyScope method.

type StrictIdentity added in v0.115.2

type StrictIdentity interface {
	StrictPresented() bool
}

StrictIdentity is optional: an IdentityAuthenticator that also implements it can ask TokenAuthKeystore to be strict about a request that PRESENTED a SPIFFE identity which was not accepted (a JWT-SVID that does not verify, an unmapped ID with SPIFFEAUTH_UNMAPPED=fallback). When StrictPresented reports true, such a request is not admitted by private-mesh trust (KeystoreOpts.TrustPrivateMesh): it must carry an API key (or a gateway-validated one) or it is refused with 401. Off by default (dual mode lets the private mesh admit it, as before). It is the prerequisite for a gateway that skips its own key check for a request carrying X-Spiffe-Jwt: without it, a forged token arriving from the gateway's private IP would fall through to TrustPrivateMesh.

type XAuthObserver added in v0.116.0

type XAuthObserver interface {
	ObserveXAuthUntrusted(mode, src, caller, credential string)
}

XAuthObserver is the optional second interface of KeystoreOpts.Observer: it receives one call per request that carried X-Auth-User from a peer outside the trusted list, in shadow and enforce mode. credential is none, key, jwt or key+jwt (what else the request carried); only none depends on the forgeable header alone. promx.AuthCollectors implements it as xauth_untrusted_total{service,mode,src,caller,credential}. Implementations must not block.

Jump to

Keyboard shortcuts

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