oidcauth

package
v0.41.0 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: Apache-2.0 Imports: 16 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 oidcauth is the one OIDC bearer-token verifier in this repository (R53, docs/55 D2): the relay's admin API (internal/ops), the moderation portal (gawk-admin) and the telemetry service all verify through it.

R39 shipped the same verifier twice — once in the relay, once in the portal — and kept the copies in step by review (docs/42 §11.1, twice). What they would otherwise diverge on is security-critical: the JWKS fetch floor, the `alg` allowlist, the capped body, the discovery retry. A third consumer made sharing it cheaper than keeping three copies honest, so this package is the lifted union of the two, with the relay's containment rule extended to cover it (internal/ops/auth_import_test.go): inside the relay module only the ops auth path may import it.

Every protected request proves who it is with an `Authorization: Bearer <JWT>` minted by the configured OIDC provider. Validation is stateless — signature against the issuer's JWKS, then `iss`, `aud`, `exp`, `nbf` — and authorization is a role read out of a claim in that same token. There is no session, no cookie and therefore no CSRF surface at all (docs/42 D17): a `Set-Cookie` on any response is a bug.

The properties this package is built around:

  • **Per-request verification is offline.** The JWKS is cached by go-oidc's oidc.RemoteKeySet, whose cache has no expiry, so an operator can act while the IdP is slow or down. The only request that reaches the IdP is one whose signature no cached key verifies — a key rotation, or a forgery — and even that fetch is rate-floored so a fuzzing loop cannot turn into a stampede against the IdP (keyset.go).
  • **The refresh horizon is the revocation horizon.** A JWT cannot be revoked server-side before it expires, so removing a role at the IdP takes effect at the next access-token refresh — which is exactly why docs/42 §4.8 recommends 5–15 minute access tokens.
  • **An unreachable IdP degrades the service; it does not kill the pod.** Discovery happens in the background, with retries, so New never fails on a transient IdP outage. Until it succeeds, Verify fails with ErrNotReady, Middleware answers 401 and Ready reports false — the signal a consumer folds into /readyz. Refusing to boot instead would turn a 30-second IdP blip into a CrashLoopBackOff, and would buy no safety: New already refuses a configuration that could serve with authorization effectively off (docs/42 D7).

A consumer wires the exported surface like this (gawk-admin's shape):

v, err := oidcauth.New(ctx, cfg, oidcauth.Options{Logger: log})
mux.Handle("GET /auth/config", v.ConfigHandler())
mux.Handle("/api/v1/", v.Middleware(v.RequireRole(cfg.Role)(apiHandler)))
srv.Handler = oidcauth.SecurityHeaders(cfg.Issuer)(mux)
ready := store.Ready() && v.Ready()

or calls Verify directly, as the relay's ops listener does to put its own static machine token in front of the same check.

SecurityHeaders MUST wrap the whole mux: the SPA, /healthz and every other response need the CSP too, and only the mux-level wrap can guarantee that (docs/42 §4.8 "headers on every response"). Middleware and ConfigHandler set the same headers themselves so a protected response is never bare even if that wiring is forgotten; setting them twice is idempotent.

Index

Constants

View Source
const (
	// CodeUnauthorized: no credential, or one this deployment will not accept.
	// Deliberately says nothing about WHICH check failed.
	CodeUnauthorized = "unauthorized"
	// CodeIDPUnavailable: discovery has not resolved yet, so no credential can
	// be judged. A 401 rather than a 500 — nothing is broken, and retrying is
	// the right reaction.
	CodeIDPUnavailable = "idp_unavailable"
	// CodeForbidden: a VALID token whose identity lacks the required role.
	CodeForbidden = "forbidden"
	// CodeRateLimited: too many invalid credentials from one address. Carries
	// Retry-After.
	CodeRateLimited = "rate_limited"
	// CodeMethodNotAllowed is /auth/config's alone. gawk-admin's OpenAPI
	// document does not list it: under its /api/v1 a method mismatch matches
	// the catch-all instead and answers 404.
	CodeMethodNotAllowed = "method_not_allowed"
	// CodeInternal: the middleware is not wired. A programming error, not a
	// client one.
	CodeInternal = "internal"
)

The `code` values this package writes into the error envelope.

They are CONTRACT: a client branches on `code`. They matter more than most, because these are the codes a caller meets FIRST — a missing, expired or unprivileged token is the failure every new integration hits before it ever reaches a handler.

gawk-admin's R48 OpenAPI drift check derives its `ErrorCode` enum by walking the `Code*` string constants of its own internal/api AND of this package's source, so a code added here without a line in gawk-admin's `openapi.yaml` fails its `go test`. Keep them named constants with literal values: anything else is invisible to that walk.

View Source
const (
	// DefaultJWKSFetchInterval and DefaultJWKSFetchBurst size the JWKS fetch
	// bucket (keyset.go): three fetches per minute, bucket full at startup.
	// The burst is what makes a genuine rotation free — the herd it produces
	// is coalesced into one fetch upstream, and the bucket has three. The
	// interval is what an attacker feeding unverifiable tokens is reduced to,
	// and it is also the worst case a rotation landing mid-attack waits: 20
	// seconds, one retry away for the operator.
	DefaultJWKSFetchInterval = 20 * time.Second
	DefaultJWKSFetchBurst    = 3
)

Defaults. Every one of these is overridable through Options, but the zero Options value is what production runs.

View Source
const DevProxyPath = "/idp/"

DevProxyPath is where the dev-only IdP reverse proxy is mounted. Every binary that offers it mounts it here, so the docs/41 compose lane can put each one's issuer at <externalUrl>/idp and get the identical route.

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

ProtectedResourceWellKnown is RFC 9728's well-known URI suffix.

Variables

View Source
var ErrNotReady = errors.New("oidcauth: the identity provider has not been reached yet")

ErrNotReady is what Verify returns while OIDC discovery has not resolved: no credential can be judged yet. Callers answer it with 401 — nothing is broken, and retrying is the right reaction — and, unlike an invalid credential, it must not spend the caller's failure budget: the failure is ours, not theirs.

Functions

func AsymmetricSigningAlgs

func AsymmetricSigningAlgs() []string

AsymmetricSigningAlgs returns (a copy of) the asymmetric JWS algorithm allowlist every verification is narrowed to.

func Challenge

func Challenge(resourceURL func(*http.Request) string) func(http.Handler) http.Handler

Challenge returns middleware that adds `WWW-Authenticate` to every 401 the wrapped handler writes — Middleware's own refusals included. With a resourceURL the challenge names the metadata document (`Bearer resource_metadata="…"`, the MCP authorization spec); with nil it is the bare RFC 6750 `Bearer`.

Only a 401 is a challenge: a 403 (valid token, missing role) or a success carries no header.

func NewContext

func NewContext(ctx context.Context, id Identity) context.Context

NewContext returns ctx carrying id. Called by Middleware once per request, after the token validates.

func NewDevProxy

func NewDevProxy(target string) (http.Handler, error)

NewDevProxy reverse-proxies /idp/* to the dev IdP at target (the -dev-oidc-proxy flag, docs/42 §11.1). Mount the result at DevProxyPath.

It exists for exactly one URL problem: the SPA fetches the issuer's discovery document FROM THE BROWSER and the server fetches the same URL from inside its container, so the issuer must resolve in both worlds. With the issuer at <externalUrl>/idp, the browser reaches it through the published port and the server through its own listener — the Keycloak frontend/backchannel split, answered with one path instead of two knobs.

Dev only (docs/41): the flag that enables it is deliberately absent from every chart, and a caller that mounts it should say so loudly in its log on every startup.

func ProtectedResourceHandler

func ProtectedResourceHandler(issuer string, resourceURL func(*http.Request) string) http.Handler

ProtectedResourceHandler serves the metadata document for the resource resourceURL derives, naming issuer as its only authorization server. Mount it, unauthenticated, at ProtectedResourceMetadataPath of the resource's path — and nowhere else: a copy at the bare well-known URI would describe the whole origin (§3.1).

It panics on a blank issuer: routes are wired at startup, and a document naming no authorization server can never lead a client to a token.

func ProtectedResourceMetadataPath

func ProtectedResourceMetadataPath(resourcePath string) string

ProtectedResourceMetadataPath is where the metadata for a resource at resourcePath is served on the same origin: the well-known segment inserted before the path (RFC 9728 §3.1), so /mcp's lives at /.well-known/oauth-protected-resource/mcp. A terminating slash is removed first, as §3.1 requires.

func ProtectedResourceMetadataURL

func ProtectedResourceMetadataURL(resource string) string

ProtectedResourceMetadataURL turns a resource URL into its metadata URL (RFC 9728 §3.1). The fragment is dropped; the query, if any, is kept.

func RefuseBrowserOrigin

func RefuseBrowserOrigin(next http.Handler) http.Handler

RefuseBrowserOrigin answers 403 to any request carrying an Origin header.

The MCP transport requires a server to validate Origin, against DNS rebinding. A service with no configured origin has nothing to compare it with — and comparing with Host does not stop rebinding, which is the attack that controls Host — while no browser client of an MCP endpoint exists. So the header's presence is the refusal (docs/55 D6, docs/56 D9). Wrap it outside authentication: a refused origin never reaches token validation.

func RequestResourceURL

func RequestResourceURL(path string) func(*http.Request) string

RequestResourceURL returns a function deriving the absolute URL of the resource at path from the request that reached it: scheme, Host, path.

The scheme is the first value of X-Forwarded-Proto when that names http or https, else whether the connection itself is TLS. A TLS-terminating Ingress proxies plain HTTP to the pod, so without the header a client that called https://…/mcp would be told the resource is http://…/mcp — and RFC 9728 §3.3 has it discard a document whose `resource` differs from the URL it called. Trusting the header is safe for the same reason deriving from Host is: the document's only authority-bearing field is the configured issuer, and the client checks the echoed `resource` against its own URL.

func SecurityHeaders

func SecurityHeaders(issuerURL string) func(http.Handler) http.Handler

SecurityHeaders returns middleware that stamps docs/42 §4.8's headers onto every response. Wrap the whole mux with it: the SPA, /auth/config, /healthz and /api/v1 all need them, and only a mux-level wrap can promise "every response".

issuerURL is the configured OIDC issuer. Its origin — and only its origin — is added to connect-src, because the SPA runs the code+PKCE flow against the IdP directly (§4.8). Everything else stays 'self': with no cookies, the residual browser risk is XSS against the in-memory access token, and a strict CSP plus the embedded-assets rule are the mitigation (§5).

Types

type Config

type Config struct {
	// Issuer is the OIDC issuer URL. Discovery is fetched from it, and a
	// discovery document whose own `issuer` differs is refused.
	Issuer string
	// Audience is the value a token's `aud` must carry — the resource server
	// the token was minted for, which for an access token is not the SPA's
	// client ID (docs/42 §4.12).
	Audience string
	// RolesClaim is the dot-path to the token's roles array, with
	// oidcroles.Placeholder substituted by Audience per segment.
	RolesClaim string
	// Role is the deployment's required role. New refuses it blank — with no
	// required role every valid token would be an operator — and Role()
	// returns it for a consumer's RequireRole wiring; Middleware itself
	// authorizes nothing.
	Role string
	// ClientID is the public SPA client ID that ConfigHandler publishes. New
	// does not require it, because a pure resource server (the relay) has no
	// browser client; a consumer that serves ConfigHandler must validate it
	// itself, and ConfigHandler panics on a blank one.
	ClientID string
}

Config is what a deployment configures. Issuer, Audience, RolesClaim and Role are required: each blank one would accept tokens it should not.

type Identity

type Identity struct {
	// Subject is the token's `sub` claim: the stable, provider-scoped user ID.
	Subject string
	// Email is the `email` claim when the provider issues one. It is what
	// audit rows and webhook payloads render as the actor, so it is
	// informational — authorization never keys on it.
	Email string
	// Roles is the string array read from the configured roles claim. Empty
	// when that claim is missing or malformed: a token that cannot prove a
	// role does not have it.
	Roles []string
	// Expiry is the token's validated `exp`. Authorization is decided per
	// request, so a consumer that holds one response open beyond the request
	// that authorized it — telemetry's live stream (docs/55 D4) — must end
	// that response here, or the stream outlives the revocation horizon.
	Expiry time.Time
}

Identity is the authenticated caller, projected from validated JWT claims. Roles are the IdP-managed authorization state (docs/42 D17) — never a config-file allowlist.

It is derived fresh from the bearer token on every request: there is no session and no cookie anywhere behind this package, which is what keeps its consumers stateless enough to run more than one replica (docs/42 D16).

func FromContext

func FromContext(ctx context.Context) (Identity, bool)

FromContext returns the identity Middleware attached. The false case is a programming error on an authenticated route (Middleware refuses the request long before a handler runs) — handlers should treat it as a 500, not as an anonymous caller.

func (Identity) Actor

func (i Identity) Actor() string

Actor is what an audit row or an event records for this caller. Email when the provider issued one, subject otherwise — an audit trail with a blank actor is worse than one with an opaque ID.

func (Identity) HasRole

func (i Identity) HasRole(role string) bool

HasRole reports whether the token carried role. Comparison is exact and case-sensitive: OIDC role names are opaque strings and folding case here would silently widen access.

type Options

type Options struct {
	// Logger receives Debug-level rejection detail and Warn-level discovery and
	// priming failures. Defaults to slog.Default(). Rejections carry the
	// client IP and the validation error, which is why they are Debug-only:
	// IPs must not appear in logs above Debug (docs/42 §5).
	Logger *slog.Logger
	// HTTPClient talks to the IdP — discovery at startup, JWKS afterwards.
	// Nil means a bounded-timeout default.
	HTTPClient *http.Client
	// Now defaults to time.Now. It drives token expiry checks, the JWKS fetch
	// bucket and the failure limiter.
	Now func() time.Time
	// JWKSFetchInterval and JWKSFetchBurst size the JWKS fetch bucket: one
	// token accrues per interval, the bucket holds burst of them and starts
	// full. Zero means the default (three fetches per minute). Only a
	// verification that no cached key satisfies ever spends one.
	JWKSFetchInterval time.Duration
	JWKSFetchBurst    int
	// ResolveRetryInterval is the delay before the first retry of OIDC
	// discovery, and of key-set priming, doubling up to ResolveRetryMax.
	// Defaults to one second.
	ResolveRetryInterval time.Duration
	// ResolveRetryMax caps that backoff; it is never below
	// ResolveRetryInterval. Defaults to 30 seconds.
	ResolveRetryMax time.Duration
	// FailureRate and FailureBurst size Middleware's per-IP invalid-credential
	// bucket. Zero means the defaults (ten, then one per second).
	FailureRate  float64
	FailureBurst int
	// SigningAlgorithms, when non-nil, is the exact JWS algorithm list a token
	// may use, instead of the provider's advertised
	// id_token_signing_alg_values_supported. Either way the list is narrowed
	// to AsymmetricSigningAlgs, so neither the provider nor a caller can widen
	// it to "none" or the HMAC family.
	SigningAlgorithms []string
}

Options tunes the verifier. The zero value is production's configuration; each field exists because a test must drive it (clock, HTTP client) or a consumer must tune it.

type Verifier

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

Verifier validates tokens and authorizes roles. Construct it with New; it owns a background goroutine (issuer resolution, key-set priming, limiter sweep) that Close — or the end of New's ctx — stops.

func New

func New(ctx context.Context, cfg Config, opts Options) (*Verifier, error)

New validates the configuration and starts the background worker that resolves the provider (OIDC discovery), retrying until it succeeds.

It fails ONLY on a configuration that could never be safe — a blank issuer, audience, roles-claim path or role. That is docs/42 D7's actual concern, and it is decided without touching the network. An IdP that is merely unreachable is a transient condition: New succeeds, Ready reports false, Verify answers ErrNotReady, and the process stays up (docs/42 §6).

ctx bounds the background worker, so it must be the process context, not a request's.

func (*Verifier) Close

func (v *Verifier) Close() error

Close stops the background worker and waits for it. Idempotent.

func (*Verifier) ConfigHandler

func (v *Verifier) ConfigHandler() http.Handler

ConfigHandler serves GET /auth/config, unauthenticated (docs/42 §4.8): the configured issuer, Config.ClientID and audience.

It panics when Config.ClientID is blank: routes are wired at startup, and a bootstrap that hands the SPA no client ID is a configuration that can never log anybody in.

func (*Verifier) JWKSFetchTokensLeft

func (v *Verifier) JWKSFetchTokensLeft() float64

JWKSFetchTokensLeft reports the JWKS fetch bucket's contents WITHOUT refilling or spending. It is diagnostic: "this verification did not touch the IdP" is the guarantee docs/42 §4.5 and §4.8 rest on, and an unchanged, non-empty bucket is direct evidence that the fetch path was not consulted.

func (*Verifier) Middleware

func (v *Verifier) Middleware(next http.Handler) http.Handler

Middleware authenticates the request and puts the caller's identity on the context (NewContext). It authorizes nothing: a token whose roles claim is missing or malformed authenticates with an empty role set, and RequireRole then refuses it with 403.

Any invalid credential is answered 401 — or 429 once this client IP has spent its failure budget. While discovery is unresolved every request is answered 401 `idp_unavailable` without spending that budget.

func (*Verifier) Primed

func (v *Verifier) Primed() <-chan struct{}

Primed is closed once the key set holds keys, which is strictly later than Resolved. Nothing gates on it: a ready verifier whose key set is not primed yet fetches on the first verification instead.

func (*Verifier) Ready

func (v *Verifier) Ready() bool

Ready reports whether the provider has been resolved: OIDC discovery answered and the verifier exists. Until it does, every token is refused, so a consumer folds this into /readyz — an unready pod should not take authenticated traffic.

It never goes back to false, and it deliberately does NOT wait for the key set: startup must not be able to hang on the IdP twice (docs/42 §6, D16). The key set is instead primed right after resolution, in the background and with retries (primeKeys), so a ready pod can normally verify offline without that ever having been a precondition for going ready.

func (*Verifier) RequireAnyRole

func (v *Verifier) RequireAnyRole(roles ...string) func(http.Handler) http.Handler

RequireAnyRole refuses a valid token that carries none of roles (403).

The role model is one role per capability, not a hierarchy (docs/50 D1): a route a second role may call names both, rather than one role implying the other. It panics on an empty list or an empty entry for RequireRole's reason — either would quietly admit every valid token.

func (*Verifier) RequireRole

func (v *Verifier) RequireRole(role string) func(http.Handler) http.Handler

RequireRole refuses a valid token that does not carry role (403). It must be wrapped by Middleware.

The role is a parameter rather than Config.Role because a service can authorize more than one — gawk-admin's content-flag route authorizes the flagger role held by a client-credentials service identity (docs/42 §4.11) — and because rights must stay bound to a role, never to a merely-valid token.

An empty role panics rather than returning a middleware: routes are wired at startup, so this is the same "refuse to boot" the config validation performs (docs/42 §4.8) — a RequireRole("") that quietly authorized everyone is precisely the failure that rule exists to prevent.

func (*Verifier) ResolveError

func (v *Verifier) ResolveError() error

ResolveError returns why the provider is not resolved yet, or nil once it is (and before the first attempt has failed). It exists so /readyz can say *what* is wrong rather than just "not ready".

func (*Verifier) Resolved

func (v *Verifier) Resolved() <-chan struct{}

Resolved is closed once discovery has resolved — the moment Ready turns true. Nothing in the request path waits on it; it lets a test or a startup probe wait without polling.

func (*Verifier) Role

func (v *Verifier) Role() string

Role is the deployment's required role (Config.Role).

func (*Verifier) Verify

func (v *Verifier) Verify(ctx context.Context, rawJWT string) (Identity, error)

Verify validates rawJWT — signature, `iss`, `aud`, `exp`, `nbf`, algorithm — and projects it onto an Identity. It authorizes nothing: a token whose roles claim is missing or malformed verifies with an empty role set, so a role check then refuses it (403, never a 500 — a claim shape we do not recognise is the IdP's configuration talking, not a bug in this process).

It returns ErrNotReady while discovery has not resolved, and any other error for a credential that is not good. In the steady state it is offline: the key that signed the token is already cached and the check is pure CPU.

Directories

Path Synopsis
Package oidcauthtest is the fake OIDC issuer every oidcauth consumer tests against (R53, docs/55 D2): a real HTTP server serving /.well-known/openid-configuration and a JWKS, with locally generated keys that tokens are minted against.
Package oidcauthtest is the fake OIDC issuer every oidcauth consumer tests against (R53, docs/55 D2): a real HTTP server serving /.well-known/openid-configuration and a JWKS, with locally generated keys that tokens are minted against.

Jump to

Keyboard shortcuts

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