authn

package
v0.0.62 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: Apache-2.0 Imports: 25 Imported by: 1 module, 1 package

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 authn validates INBOUND JWT bearer tokens at a resource server.

It performs NO OAuth flows and issues nothing: there is no token endpoint, no authorization-code exchange, and no signing of tokens. The package only verifies the bearer tokens that clients present.

Validate, Verify and ParseBearer return failures as *Error. An *Error has a Code and a Reason that are safe to send to a client. Its Error method also returns detail for your logs. Do not send that detail to a client. NewValidator and NewTrustSet report construction problems as ordinary errors.

Overview

A Validator checks tokens from one issuer. Build it with NewValidator from a Config. Call ParseBearer on the Authorization header, then call Validator.Validate on the token. Validate returns a Principal.

A TrustSet checks tokens from several issuers. It holds one Trust for each issuer. Build it with NewTrustSet. Call TrustSet.Verify on the token. Verify returns a Principal whose Trust field names the trust that verified the token.

ValidateConfig checks a Config and does no network I/O. Use it to reject a bad Config at startup when you build the Validator later.

Defaults

These defaults differ from a verifier that you write by hand.

  • The token must have exp, and sub must not be empty.
  • The iss claim must equal Config.Issuer byte for byte.
  • Config needs Audiences. To skip the audience check, set AllowAnyAudience. An empty Audiences list alone is an error.
  • Only RS, PS and ES algorithms are accepted (256, 384 and 512). The algorithm none and the HMAC algorithms are refused. Config.Algs can narrow the list.
  • RSA keys under 2048 bits are refused. A token with a crit header is refused.
  • The clock-skew tolerance is 60 seconds. The maximum is 2 minutes.
  • A token with a cnf claim is refused. Set AllowCNF to accept it.
  • A token whose typ is an ID-JAG, logout, security event, DPoP or token introspection type is refused with ReasonTokenKind.
  • The default HTTP client refuses private addresses and redirects. It stops after 15 seconds and reads at most 1 MiB. A client that you supply in Config.HTTPClient does not get the private-address check.
  • Construction fails if discovery or the first JWKS fetch fails. With a KeyProvider, a failed fetch is not fatal. With ProviderOnly, nothing is fetched.
  • MaxTokenLifetime and MaxJWKSStaleness are off. Turn them on if you need them. MaxJWKSStaleness turns an issuer outage into CodeUnavailable.

What the caller must still do

A valid token is not yet an allowed request. You must still do these things.

  • Check scopes. Call Principal.RequireScopes. It checks only the scope claim, or scp when scope is absent. It does not read roles. A token with no scopes fails every RequireScopes call that names a scope.
  • Choose your own identity claim. Principal.Subject is the sub claim. It is unique only within one issuer, and some issuers need another claim.
  • Qualify every claim by Principal.Trust. A claim such as email or groups means something only for the issuer that signed it. Never compare a claim from one trust with a claim from another.
  • Read Principal.Claims as JSON types. A number is a float64. An array is a []any. An object is a map[string]any.
  • Map errors to responses. Use (*Error).HTTPStatus, not Code.HTTPStatus: only the method on *Error answers missing credentials with 401. When (*Error).MissingCredentials reports true, send a bare "WWW-Authenticate: Bearer" challenge with no error, error_description or scope parameter (RFC 6750 §3.1). CodeUnavailable is not an OAuth2 error value: return a plain 503. Use PossiblyOpaque to find a token that may be opaque and need introspection.
  • Add rules with Config.Checks when the built-in rules are not enough.

Several issuers

TrustSet.Verify reads iss from the token before it checks the signature. It uses iss only to choose a trust. The match is exact. Then it verifies the token with the Config of that trust alone. It never tries another trust. If no trust has that issuer, the error is ReasonUnknownIssuer, and no key is tried. You can then pass the token to another verifier.

Each Trust needs an ID that is unique in the set and a Config.Issuer that is unique in the set. Two trusts that differ only by a trailing slash in the issuer are both refused. Trust.Tag comes back unchanged in Principal.Trust.

A TrustSet cannot change. To change the trusts, build a new set, swap it in with an atomic.Pointer, and call Close on the old set. NewTrustSet returns the set and a []TrustError. The set holds every trust that built. A trust that failed to build is not in the set, and its tokens fail with ReasonUnknownIssuer.

Set Trust.NotAfter to the time when the data of a trust goes stale. After that time, its tokens fail with CodeUnavailable and ReasonTrustStale.

A set whose trusts are all ProviderOnly makes no network requests and holds no goroutines. It needs no Close.

The next example uses two sets. The first holds the human identity providers. It is built once at startup, and a TrustError is fatal. The second holds issuers from a directory service. It is rebuilt on a timer. WithProviderOnly makes sure that no trust in it fetches keys. WithReservedIssuers makes sure that it cannot take over an issuer of the first set.

humans, errs := authn.NewTrustSet(ctx, humanTrusts)
if len(errs) > 0 {
	log.Fatal(errs[0])
}

var machines atomic.Pointer[authn.TrustSet]
rebuild := func() {
	next, errs := authn.NewTrustSet(ctx, trustsFromDirectory(),
		authn.WithProviderOnly(),
		authn.WithReservedIssuers(humanIssuers...))
	for _, e := range errs {
		log.Print(e)
	}
	if old := machines.Swap(next); old != nil {
		old.Close()
	}
}
rebuild() // before the server accepts requests, then on a timer

verify := func(ctx context.Context, token string) (authn.Principal, error) {
	p, err := humans.Verify(ctx, token)
	var ae *authn.Error
	if errors.As(err, &ae) && ae.Reason == authn.ReasonUnknownIssuer {
		return machines.Load().Verify(ctx, token)
	}
	return p, err
}

Identity providers

Config.Issuer must be the exact iss value of the tokens. For that reason NewValidator and NewTrustSet refuse an issuer with a template placeholder such as {tenantid}, which no token carries. The Entra multi-tenant issuers common, organizations and consumers are not refused, but no token carries them either. Configure one issuer, and so one trust, for each tenant.

Microsoft Entra:

  • Set Config.JWKSURL. The v1 issuer is https://sts.windows.net/{tenant}/, but its keys are on login.microsoftonline.com. Use https://login.microsoftonline.com/{tenant}/discovery/keys for v1 tokens and https://login.microsoftonline.com/{tenant}/discovery/v2.0/keys for v2 tokens.
  • The aud claim has a different form in v1 and v2 tokens. It can be a client ID (a GUID) or an App ID URI such as api://{id}. List every form that your clients receive in Config.Audiences. Matching is byte-exact.
  • A delegated token has scp, a space-separated string. An app-only token has roles, an array, and no scp. Principal.Scopes never holds roles. Read roles from Principal.Claims.
  • The typ header of Entra tokens is JWT. Leave AcceptedTokenTypes empty.
  • An ID token has the client ID as aud. The strongest guard against an ID token is an API audience that is not the ID of any client, together with RequireScopes for at least one scope. An ID token has no scp.
  • Roles do not separate ID tokens from access tokens. An ID token can carry roles.
  • Identify a user by the pair tid and oid from Principal.Claims. Do not use sub alone.

Okta:

  • Use a custom authorization server. The issuer is https://{org}.okta.com/oauth2/{id}. Do not use the org authorization server.
  • Scopes are in scp, an array. Principal.Scopes reads it.
  • Do not set AcceptedTokenTypes. Do not rely on typ for Okta tokens.
  • The cid claim is the ID of the client that asked for the token. Read it from Principal.Claims.
  • A client-credentials token has no user. Its sub is the client ID.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewTrustSet added in v0.0.62

func NewTrustSet(ctx context.Context, trusts []Trust, opts ...SetOption) (*TrustSet, []TrustError)

NewTrustSet validates the trusts, builds a validator for each valid one and returns a set holding every trust that built. Each trust that did not is reported in the returned errors, in input order; a caller that needs all of them treats any error as fatal. A trust that failed to build is absent from the set, so its tokens get ReasonUnknownIssuer from Verify, not CodeUnavailable. A caller that must not fall through to another verifier when a trust is missing treats the returned errors as fatal.

A trust is refused when its ID is empty, too long or has control characters; when its Config is invalid or has no Issuer; when WithReservedIssuers reserves its issuer or WithProviderOnly requires a ProviderOnly Config it lacks; and when its ID, or its issuer with trailing slashes removed, is shared with another trust that was not refused for one of these reasons. A shared ID or issuer refuses every trust that shares it, since there is no rule for which one is meant, so an invalid trust never keeps a valid one of the same issuer out.

Routing and the shared-issuer check are byte-exact apart from trailing slashes: there is no case or default-port normalisation. Because every copy of a shared issuer is refused, a feed that lets one party register a colliding issuer lets that party deny service to another trust. Such a feed must reject collisions when trusts are registered.

ctx bounds construction, including discovery and the first JWKS fetch, which run in parallel. The validators' background JWKS refresh lives until Close. A set whose trusts are all ProviderOnly holds no goroutines and needs no Close.

func ParseBearer

func ParseBearer(headerValue string) (string, error)

ParseBearer extracts the token from an Authorization header value. The scheme match is CASE-INSENSITIVE per RFC 7235 §2.1 (this fixes ToolHive's case-sensitive match at pkg/auth/utils.go:45-47).

The missing-vs-malformed split lets callers distinguish "no credentials" (a bare WWW-Authenticate challenge, RFC 6750 §3.1) from "broken credentials" (error="invalid_request", 400): an empty value yields ReasonMissingHeader; anything else malformed — not exactly `Bearer <token>`, extra whitespace segments, an empty token part, or a token longer than maxTokenLength — yields ReasonMalformed. A header whose scheme is present but not Bearer (e.g. "Basic ...") yields ReasonUnsupportedScheme, which RFC 6750 §3.1 treats as missing credentials; see (*Error).MissingCredentials and (*Error).HTTPStatus.

All ParseBearer failures use Code CodeInvalidRequest (400), including ReasonMalformed. The ReasonMalformed value here is a malformed *header*, not a possibly-opaque token, so unlike Validate's CodeInvalidToken + ReasonMalformed it must NOT feed ToolHive's introspection fallback (see errors.go).

NO error returned here contains any byte of the header value. Error() is documented as log-safe, and a malformed header routinely still carries a live credential — "Bearer <token> junk", or a token sent with no scheme at all would put a replayable token into the logs (RFC 6750 §5 names token disclosure as a primary threat). Errors therefore report only the structural category and, where useful, a length.

func PossiblyOpaque

func PossiblyOpaque(err error) bool

PossiblyOpaque reports whether err indicates the token could not be parsed as a JWT at all, and so may be an opaque token worth validating via RFC 7662 introspection.

It is true only for a Validate failure (Code == CodeInvalidToken) with Reason == ReasonMalformed; ParseBearer's CodeInvalidRequest failures are a broken request, not a possibly-opaque token, and report false. A nil err also reports false.

Verified parity note: a token that is three base64url segments whose header decodes to JSON without an "alg" member yields ReasonUnsupportedAlg, not ReasonMalformed, so PossiblyOpaque reports false for it. That matches ToolHive's existing behavior: ToolHive keys its fallback on jwt.ErrTokenMalformed, while golang-jwt reports a missing alg as jwt.ErrTokenUnverifiable. Neither implementation introspects that shape.

Types

type Check added in v0.0.62

type Check interface {
	Check(claims map[string]any, now time.Time) error
}

Check is a rule over verified claims. It runs after every built-in check, so it can only add restrictions; it must not do I/O. It returns nil to accept the token. Any error or panic rejects it with CodeInvalidToken and ReasonCheck. The returned error is wrapped in the *Error, so it appears in Error() and is reachable with errors.Is and errors.As; like every *Error detail it is for logs only and never part of a response. Do not put values in it that must not reach logs. A panic value is not recorded.

Each check receives its own deep copy of the claims, and the instant the validator used for every temporal check of this token.

var RejectIDTokens Check = CheckFunc(func(claims map[string]any, _ time.Time) error {
	for _, name := range []string{"at_hash", "c_hash"} {
		if _, present := claims[name]; present {
			return fmt.Errorf("token carries the ID token claim %q", name)
		}
	}
	return nil
})

RejectIDTokens refuses a token that carries an `at_hash` or `c_hash` claim, which only OpenID Connect ID tokens carry. It is weak on its own: an ID token from the authorization code flow may carry neither.

type CheckFunc added in v0.0.62

type CheckFunc func(claims map[string]any, now time.Time) error

CheckFunc adapts a function to the Check interface.

func (CheckFunc) Check added in v0.0.62

func (f CheckFunc) Check(claims map[string]any, now time.Time) error

Check calls f.

type Code

type Code string

Code is the OAuth2 error code, safe to send to a client.

It corresponds to the "error" parameter defined in RFC 6750 Section 3.1 and carries the coarse response semantics (the HTTP status is implied by the value).

const (
	// CodeInvalidRequest is the OAuth2 "invalid_request" code (HTTP 400).
	CodeInvalidRequest Code = "invalid_request" // 400
	// CodeInvalidToken is the OAuth2 "invalid_token" code (HTTP 401).
	CodeInvalidToken Code = "invalid_token" // 401
	// CodeUnavailable indicates key material could not be reached and maps to
	// HTTP 503. It is distinct from an invalid token: the verifier could not
	// make a determination because its inputs (e.g. the JWKS endpoint) were
	// unreachable.
	//
	// Unlike CodeInvalidRequest and CodeInvalidToken, CodeUnavailable is NOT a
	// registered RFC 6750 §3.1 error value (that section defines exactly
	// invalid_request, invalid_token, insufficient_scope). It is an internal
	// discriminator: map it to a plain HTTP 503 and do not emit it as an
	// OAuth2 error= parameter.
	CodeUnavailable Code = "unavailable" // 503 — key material unreachable
	// CodeInsufficientScope is the OAuth2 "insufficient_scope" code (HTTP 403).
	// Validate never returns it.
	CodeInsufficientScope Code = "insufficient_scope" // 403
)

func (Code) HTTPStatus added in v0.0.61

func (c Code) HTTPStatus() int

HTTPStatus returns the HTTP status for a Code; an unknown Code maps to 401.

It maps by Code alone, so it cannot tell missing credentials (which RFC 6750 §3.1 answers with 401) from a malformed request (400): both are CodeInvalidRequest. For an *Error use (*Error).HTTPStatus instead.

type Config

type Config struct {
	// Issuer is the expected iss claim value. When JWKSURL is empty it is
	// also the base for OIDC discovery ({Issuer}/.well-known/openid-configuration).
	// Must be an https URI unless InsecureAllowHTTP is set.
	//
	// At least one of Issuer or JWKSURL is required. Leaving Issuer EMPTY
	// (only legal alongside an explicit JWKSURL) DISABLES iss verification
	// entirely: any issuer that can present a key from the configured JWKS is
	// accepted. Only do this when the JWKS endpoint itself is the trust
	// boundary.
	Issuer string

	// Audiences lists acceptable aud claim values; a token is accepted when
	// ANY of its aud values matches ANY entry here.
	//
	// Each entry is compared byte-exact against the token's aud values and is
	// validated only as a bounded, control-character-free string: RFC 7519
	// §4.1.3 types aud as StringOrURI, so bare identifiers (an OAuth
	// client_id) and opaque GUIDs (Entra ID) are conformant and accepted.
	//
	// Required and non-empty unless AllowAnyAudience is set.
	Audiences []string

	// AllowAnyAudience disables audience verification. It exists so a
	// deployment with no audience policy can be expressed explicitly rather
	// than by leaving Audiences unset, since a silently absent audience check
	// is how confused-deputy bugs reach production: any token the issuer minted
	// for ANY relying party is accepted by this resource server.
	//
	// Setting it together with a non-empty Audiences is an error, so the two
	// cannot silently disagree.
	AllowAnyAudience bool

	// JWKSURL, when set, points directly at the JWKS endpoint and skips OIDC
	// discovery. Optional. Must be an https URI unless InsecureAllowHTTP is
	// set.
	JWKSURL string

	// Leeway is the clock-skew tolerance applied to exp/nbf/iat. Zero uses
	// the default of 60s; negative is an error; values above 2m are an
	// error.
	Leeway time.Duration

	// DisableLeeway sets the clock-skew tolerance to zero, so exp is enforced
	// exactly. It exists because Leeway == 0 means "use the 60s default", which
	// left no way to ask for no tolerance at all. Setting it together with a
	// non-zero Leeway is an error, so the two cannot silently disagree.
	//
	// IMPORTANT for anyone setting this for parity with a validator that has no
	// leeway: it applies to nbf and iat as well as exp, and this package checks
	// iat (a token issued in the future beyond tolerance is rejected) where many
	// validators do not check it at all. So NEITHER setting is exact parity with
	// such a validator:
	//
	//   - set     → exp and nbf match exactly, but iat becomes zero-tolerance
	//               where the other validator ignores iat entirely, so IdP clock
	//               skew that was previously invisible starts failing.
	//   - unset   → 60s of slack on exp that the other validator does not give.
	//
	// Pick based on which mismatch your deployment can absorb. There is
	// deliberately no separate iat opt-out: adding one before a concrete
	// deployment needs it would be a speculative knob.
	DisableLeeway bool

	// MaxJWKSStaleness bounds how long cached JWKS key material stays trusted
	// without a confirmed successful fetch. Negative is an error.
	//
	// Zero DISABLES the bound, and is the default. The bound exists because the
	// cache keeps serving its last good key set after every failed refresh, so a
	// key revoked at the IdP stays trusted for as long as the endpoint is
	// unreachable — the trust window equals the outage length.
	//
	// Enabling it trades availability for that bound: once exceeded, validation
	// fails with CodeUnavailable/ReasonKeysStale, so a prolonged IdP outage
	// becomes an authentication outage instead of an invisible one. Pick a value
	// that reflects how long you are willing to honour a revoked key; hours
	// rather than minutes is usually the right order of magnitude.
	//
	// Freshness is self-correcting rather than schedule-based: when the bound is
	// exceeded the validator attempts a refresh before rejecting anything, so a
	// healthy endpoint never trips it regardless of when the background refresh
	// last ran. It applies only to JWKS material — keys from a KeyProvider are
	// resolved in-process and are never considered stale.
	MaxJWKSStaleness time.Duration

	// AcceptedTokenTypes, when non-empty, requires the token's `typ` header to
	// match one of these media types. Comparison is case-insensitive and an
	// `application/` prefix is optional on both sides (RFC 7515 §4.1.9), so
	// "at+jwt" matches a token carrying "application/at+JWT". Whitespace is not
	// trimmed from either side: a padded entry is a configuration error, and a
	// padded `typ` never matches.
	//
	// Empty (the default) accepts any `typ`, including none, except ID-JAG,
	// logout, security event, DPoP and token introspection JWTs, which are
	// refused with ReasonTokenKind unless listed here. It cannot default
	// to requiring RFC 9068's "at+jwt": that is a SHOULD, and many IdPs emit
	// "JWT" or omit the header entirely, so a default would reject conformant
	// tokens.
	//
	// This guards against ID-token substitution — an ID token sharing the
	// issuer, audience, subject and expiry of an access token. Note the AUDIENCE
	// check is the primary defence there, since an ID token's aud is the
	// client_id rather than the resource: this matters most when
	// AllowAnyAudience is set, or when a deployment uses its client_id as the
	// resource audience, because in those cases the audience check cannot tell
	// the two kinds of token apart.
	AcceptedTokenTypes []string

	// AllowCNF accepts tokens that carry a `cnf` claim. By default they are
	// refused with ReasonTokenKind: they are bound to a key this package does
	// not verify.
	AllowCNF bool

	// Algs restricts the accepted signature algorithms to a subset of the
	// default allowlist (RS/PS/ES 256/384/512). Empty means all of them.
	Algs []string

	// MaxRemainingLifetime rejects a token whose exp is more than this far
	// after the time of validation, with ReasonLifetime. Unlike MaxTokenLifetime
	// it does not need iat. Zero disables it; negative is an error.
	MaxRemainingLifetime time.Duration

	// Checks are extra rules over the verified claims, run after every
	// built-in check, in order; all must pass. A nil entry is an error.
	Checks []Check

	// MaxTokenLifetime rejects tokens whose exp-iat span exceeds it, when both
	// claims are present. Negative is an error.
	//
	// Zero DISABLES the check, and is the default: a resource server that
	// accepts long-lived tokens today (service-account credentials commonly
	// outlive a day) must not start rejecting them merely by adopting this
	// package. Set it explicitly to opt into a lifetime bound.
	MaxTokenLifetime time.Duration

	// HTTPClient is used for discovery and JWKS fetches. Leave it nil unless you
	// need something the default cannot express: the default is built by
	// toolhive-core's networking package and is secure by default (private-IP
	// dial guard, 15s timeout, redirects refused, 1 MiB body cap).
	//
	// IMPORTANT — a supplied client OPTS OUT of the address-level SSRF guard.
	// That guard lives in the transport's DialContext, which this package cannot
	// retrofit onto a client it did not build; AllowPrivateIP and CACertPath are
	// likewise ignored. Build your client with
	// networking.NewHttpClientBuilder() (or install
	// networking.NewPrivateIPBlockingDialContext yourself) or you will have a
	// weaker configuration than the default.
	//
	// What IS still enforced for a supplied client: the 1 MiB response-body cap
	// (its Transport is wrapped), plus redirect refusal and the 15s timeout when
	// the caller left CheckRedirect / Timeout unset — so a bare &http.Client{}
	// cannot silently drop them. Explicit caller values are preserved.
	//
	// To attach a bearer token to the OUTBOUND JWKS/discovery request (an IdP
	// whose JWKS endpoint is itself gated), supply a client whose Transport
	// injects the Authorization header. That RoundTripper must be the innermost
	// one — this package wraps whatever it is given in its body-capping
	// transport, so set it as your client's Transport and let the wrapping
	// happen around it.
	//
	// If your IdP legitimately redirects its discovery or JWKS endpoint, set
	// JWKSURL to the final target rather than relaxing the redirect policy.
	HTTPClient *http.Client

	// InsecureAllowHTTP permits http:// Issuer and JWKSURL values. It exists
	// for development and test environments only; never set it in
	// production.
	InsecureAllowHTTP bool

	// AllowPrivateIP permits discovery and JWKS fetches to reach private,
	// loopback, and link-local addresses. It defaults to FALSE, which is what
	// blocks a jwks_uri resolving to cloud instance metadata
	// (169.254.169.254) or an in-cluster address.
	//
	// The check runs on the resolved address at dial time, so it also defends
	// against DNS rebinding and re-applies per redirect hop. Set it only for an
	// issuer that legitimately lives on a private network — an in-cluster OIDC
	// provider, or a test server on localhost.
	//
	// It applies ONLY to the default client. A caller-supplied HTTPClient brings
	// its own dial policy; see that field.
	AllowPrivateIP bool

	// CACertPath optionally points at a PEM CA bundle used to verify the
	// discovery and JWKS endpoints, for an issuer fronted by a private CA.
	//
	// It applies ONLY to the default client, for the same reason as
	// AllowPrivateIP.
	CACertPath string

	// AuthTokenFile optionally points at a file containing a bearer token to
	// attach to the OUTBOUND discovery and JWKS requests, for an IdP whose own
	// endpoints are gated behind auth (mirrors ToolHive's
	// --jwks-auth-token-file). The networking package re-reads the file per
	// request, so a rotated token is picked up without restarting the
	// validator.
	//
	// It applies ONLY to the default client, for the same reason as
	// AllowPrivateIP and CACertPath: it is implemented by networking's HTTP
	// client builder, which cannot be retrofitted onto a caller-supplied
	// HTTPClient.
	AuthTokenFile string

	// KeyProvider optionally supplies verification keys in-process, for an
	// embedded issuer. It is consulted BEFORE the JWKS cache on every
	// validation.
	//
	// A provider MISS falls through to the JWKS when one is configured. A
	// provider REJECTION does not: if the provider offers a key for the token's
	// kid but that key is unusable — a sub-2048-bit modulus, a declared alg that
	// disagrees, a malformed key — validation fails immediately with
	// ReasonKeyUnsupported and the JWKS is never consulted. An unusable key is a
	// permanent condition, so reporting it beats masking it behind a fallback
	// that would end up reporting an unknown kid instead.
	//
	// The practical effect is that an unusable provider key shadows a usable
	// JWKS key under the same kid. That is accepted: in the only topology that
	// has a provider, the provider and the JWKS are the same key source, so the
	// two disagreeing means something is wrong that a silent fallback would
	// hide.
	//
	// Setting it also relaxes construction, because an embedded issuer's JWKS
	// endpoint is characteristically not reachable at the moment the Validator
	// is built:
	//
	//   - OIDC discovery failure becomes non-fatal.
	//   - The first JWKS fetch is no longer required to succeed; key material
	//     is fetched lazily by the background refresh instead.
	//
	// Until that first fetch lands, a token whose kid the provider does not
	// offer fails with CodeUnavailable/ReasonKeysUnavailable rather than being
	// rejected as invalid — the verifier could not make a determination.
	//
	// With no KeyProvider, construction stays fail-closed: discovery and the
	// first JWKS fetch must both succeed or NewValidator returns an error.
	//
	// Set ProviderOnly to drop the discovery and JWKS fallback entirely.
	KeyProvider KeyProvider

	// ProviderOnly makes KeyProvider the only key source: there is no OIDC
	// discovery and no JWKS, so the validator makes no network requests and
	// starts no background refresh. A kid the provider does not offer is
	// ReasonUnknownKID. Issuer is still required and still verified.
	//
	// KeyProvider.PublicKeys is called on every validation, so "no network
	// requests" holds only if the provider itself serves from memory.
	//
	// Use it when another component already fetches and caches the issuer's
	// keys, for example keys taken from a directory service, so that the
	// issuer URL is never contacted. It requires KeyProvider, and the settings
	// that only configure fetching (JWKSURL, HTTPClient, CACertPath,
	// AuthTokenFile, AllowPrivateIP and MaxJWKSStaleness) must be unset.
	ProviderOnly bool
}

Config holds the trusted issuer/audience policy and fetch behavior for a Validator. A Config is validated eagerly by NewValidator so that a typo is a startup failure, not a 401 on every request.

func ValidateConfig

func ValidateConfig(cfg Config) (Config, error)

ValidateConfig validates cfg and returns a normalized copy with defaults applied. It is exactly the static policy checking and defaulting NewValidator performs before it builds anything, exposed on its own.

It exists for a caller that defers construction. A resource server whose issuer may not be reachable yet has good reason to build its Validator lazily in the background — but that also defers every error, so a plain typo in the issuer or a contradictory audience policy would stop being a startup failure and become a per-request one, discovered from a log line rather than at deploy time. ValidateConfig separates the two: static policy can be rejected synchronously while discovery and JWKS work stay asynchronous.

It performs NO I/O. No HTTP client is built, no file is read, no discovery or JWKS fetch is made, no cache or goroutine is started, and no context is required. cfg is not mutated, and every caller-owned slice is cloned, so the returned Config shares no backing array with the argument.

A successful return does NOT promise that NewValidator will succeed: everything dynamic remains unchecked. Whether CACertPath and AuthTokenFile exist and parse, whether the issuer resolves, whether its discovery document is conformant, and whether the JWKS is reachable are all still open questions — deliberately, since they are precisely the part a deferring caller wants to keep asynchronous.

On failure the zero Config is returned, so a half-defaulted value cannot be used by mistake.

type Error

type Error struct {
	// Code is the coarse, client-safe OAuth2 error code.
	Code Code
	// Reason is the finer-grained, client-safe failure cause.
	Reason Reason
	// contains filtered or unexported fields
}

Error is the only error type Validate and ParseBearer return.

Log-vs-wire split:

Code and Reason are both client-safe, but not equally wire-safe. CodeInvalidRequest and CodeInvalidToken are registered RFC 6750 §3.1 error values and may be surfaced on the wire verbatim (e.g. in the WWW-Authenticate / error response body). CodeUnavailable is not registered and must map to a plain HTTP 503 instead (see its doc comment). Error() is NOT safe to send to a client — it includes wrapped detail that can carry key ids, JWKS URLs, issuer-mismatch specifics, and underlying transport errors. Log Error(); send Code/Reason.

As a special case, a Validate failure with Code == CodeInvalidToken && Reason == ReasonMalformed means the token could not be parsed as a JWT at all, and so may be an opaque token worth validating via RFC 7662 introspection — ToolHive layers that introspection above Validate. Use PossiblyOpaque to ask this rather than comparing Code and Reason by hand: it is the stable API, and the Reason taxonomy may grow. The contract is specific to Validate: ParseBearer reports a malformed header as CodeInvalidRequest + ReasonMalformed (400, broken request), which PossiblyOpaque correctly reports as false.

func (*Error) Error

func (e *Error) Error() string

Error returns a human-readable message that combines the Reason with the wrapped detail. The output is intended for server-side logs and is NOT safe to send to a client; it may contain key ids, JWKS URLs, or issuer-mismatch specifics. It is always distinct from string(Reason) when err is non-nil and carries the wrapped detail via fmt's %v.

func (*Error) HTTPStatus added in v0.0.61

func (e *Error) HTTPStatus() int

HTTPStatus returns the HTTP status to answer with: 401 when MissingCredentials, otherwise Code.HTTPStatus. A nil *Error returns 401, as does an unknown Code. Prefer this over Code.HTTPStatus.

func (*Error) MissingCredentials added in v0.0.61

func (e *Error) MissingCredentials() bool

MissingCredentials reports whether the request carried no usable credentials: Reason is ReasonMissingHeader or ReasonUnsupportedScheme. Answer with 401 and a bare "WWW-Authenticate: Bearer" challenge, with no error, error_description or scope parameter (RFC 6750 §3.1). A nil *Error reports false.

func (*Error) RequiredScopes added in v0.0.61

func (e *Error) RequiredScopes() []string

RequiredScopes returns the scopes a CodeInsufficientScope error requires, or nil for other codes.

func (*Error) RetryAfter added in v0.0.61

func (e *Error) RetryAfter() time.Duration

RetryAfter returns how long a client should wait before retrying. It is positive only for CodeUnavailable.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the wrapped detail error (may be nil). This enables errors.Is and errors.As to traverse the wrapped chain. A nil Unwrap result simply terminates the chain for that branch.

type KeyProvider

type KeyProvider interface {
	// PublicKeys returns the currently valid verification keys. It is called
	// per validation, so an implementation that computes or reads keys should
	// cache them itself; this package deliberately does not, so that key
	// rotation inside the provider takes effect immediately.
	PublicKeys(ctx context.Context) ([]PublicKey, error)
}

KeyProvider supplies verification keys in-process, without an HTTP JWKS fetch.

It exists for an EMBEDDED issuer — an authorization server running inside the same process or pod as the resource server. Two things make an HTTP fetch unworkable in that topology, and a provider solves both:

  • Startup ordering. The embedded issuer's JWKS route is typically mounted on the same listener that serves the resource server, so at the moment the Validator is constructed that listener does not exist yet and a fetch connection-refuses.
  • Reachability. The issuer's advertised URL may be an external-facing address that is not routable from inside the cluster, so OIDC discovery against it can fail permanently rather than transiently.

Configuring a KeyProvider therefore also relaxes construction: see the Config.KeyProvider docs for exactly what becomes non-fatal.

Implementations must be safe for concurrent use: PublicKeys is called on the request path, once per token whose kid is not already resolved.

type Principal

type Principal struct {
	// Issuer is the verified `iss` claim.
	Issuer string
	// Subject is the verified `sub` claim, guaranteed non-empty.
	Subject string
	// Name is the `name` claim, may be empty.
	Name string
	// Claims is a deep copy of the verified claim set, holding only
	// encoding/json types. It shares no memory with the validator or any Check.
	Claims map[string]any
	// Scopes are the token's scopes, read from `scope` (else `scp`); nil when
	// absent or malformed.
	// It never includes `roles`: a Microsoft Entra app-only token has `roles` and
	// no `scp`, so its Scopes is nil. Read `roles` from Claims.
	Scopes []string
	// Trust identifies the trust that verified the token; zero for a Validator.
	Trust TrustRef
}

Principal is the verified identity carried by a token. It never carries the serialized token or any other credential.

func (Principal) RequireScopes added in v0.0.62

func (p Principal) RequireScopes(scopes ...string) error

RequireScopes returns nil when the principal holds every scope in scopes (and when none are given). Otherwise it returns an *Error with CodeInsufficientScope and ReasonScope that carries the requested scopes.

It checks Principal.Scopes only. A token with no `scope` or `scp` claim has no scopes, so it never satisfies a call with one or more scopes. That includes Microsoft Entra app-only (client-credentials) tokens, which carry `roles` and no `scp`, and ID tokens, which carry neither. The `roles` claim is deliberately not treated as scopes: read it from Principal.Claims.

type PublicKey

type PublicKey struct {
	// KeyID is the JWK kid this key answers to. It may be empty, in which case
	// the key is considered a candidate for any token — including one that
	// carries a kid, since an embedded issuer with a single key commonly omits
	// it on one side or the other.
	KeyID string

	// Alg optionally restricts the key to a single JWA algorithm (e.g.
	// "RS256"). When empty the key is eligible for any allow-listed algorithm
	// its type supports, subject to the same kty/curve backstop applied to
	// JWKS keys.
	Alg string

	// Key is the public key itself: *rsa.PublicKey or *ecdsa.PublicKey. Any
	// other type is rejected, since the algorithm allow-list admits only RSA
	// and ECDSA families.
	Key crypto.PublicKey
}

PublicKey is one verification key offered by a KeyProvider.

type Reason

type Reason string

Reason is a finer-grained, client-safe failure cause.

Reason refines a Code without leaking sensitive detail. Both Code and Reason are safe to transmit to a client; the human-readable detail in Error is not.

const (
	// ReasonMissingHeader indicates no Authorization header was present in the
	// request.
	ReasonMissingHeader Reason = "missing_header"
	// ReasonUnsupportedScheme indicates the Authorization header uses a scheme
	// other than Bearer. It is treated as missing credentials (RFC 6750 §3.1):
	// see (*Error).MissingCredentials.
	ReasonUnsupportedScheme Reason = "unsupported_scheme"
	// ReasonMalformed indicates the token could not be parsed as a
	// structurally valid JWT. From Validate, this pairs with CodeInvalidToken
	// and means the token may be an opaque token worth validating via RFC
	// 7662 introspection — use PossiblyOpaque to ask that, rather than
	// comparing Code and Reason by hand; the Reason taxonomy may grow.
	//
	// That opaque-token meaning applies ONLY to Validate. ParseBearer also
	// returns ReasonMalformed, but with Code == CodeInvalidRequest (400): a
	// malformed Authorization header is a broken request, not a
	// possibly-opaque token. PossiblyOpaque already accounts for this split.
	ReasonMalformed Reason = "malformed"
	// ReasonUnsupportedAlg indicates the "alg" header is missing, none, or
	// not in the configured allow-list.
	ReasonUnsupportedAlg Reason = "unsupported_alg"
	// ReasonCriticalHeader indicates a "crit" header listed a header the
	// verifier does not understand or a protected header was malformed.
	ReasonCriticalHeader Reason = "critical_header"
	// ReasonUnknownKID indicates the "kid" in the token header does not
	// match any currently known key.
	ReasonUnknownKID Reason = "unknown_kid"
	// ReasonSignature indicates the signature did not verify against the
	// selected key.
	ReasonSignature Reason = "signature"
	// ReasonExpired indicates the "exp" claim has passed.
	ReasonExpired Reason = "expired"
	// ReasonExpirationMissing indicates the "exp" claim is absent. It is
	// distinct from ReasonExpired (whose contract is "exp has passed"): the
	// parser is configured with WithExpirationRequired, so a missing exp is
	// a missing-claim failure, not a lifetime-expired one.
	ReasonExpirationMissing Reason = "expiration_missing"
	// ReasonNotYetValid indicates the "nbf" claim is in the future.
	ReasonNotYetValid Reason = "not_yet_valid"
	// ReasonIssuedInFuture indicates the "iat" claim is in the future
	// beyond the configured clock skew.
	ReasonIssuedInFuture Reason = "issued_in_future"
	// ReasonLifetime indicates the token's total lifetime (exp - iat)
	// exceeds the configured maximum.
	ReasonLifetime Reason = "lifetime"
	// ReasonIssuer indicates the "iss" claim is missing or not in the
	// trusted set.
	ReasonIssuer Reason = "issuer"
	// ReasonAudience indicates the "aud" claim is missing, has the wrong
	// type, or none of its values match a configured audience.
	ReasonAudience Reason = "audience"
	// ReasonMissingClaim indicates a required claim is absent but could not
	// be identified as iss/aud/exp (e.g. a future required claim added by a
	// custom parser option). It is deliberately NOT ReasonMalformed so it
	// does not trigger the introspection fallback.
	ReasonMissingClaim Reason = "missing_claim"
	// ReasonSubject indicates the "sub" claim is missing or rejected by
	// policy.
	ReasonSubject Reason = "subject"
	// ReasonKeysUnavailable indicates the key material source (e.g. JWKS
	// endpoint) could not be fetched; paired with CodeUnavailable.
	ReasonKeysUnavailable Reason = "keys_unavailable"
	// ReasonKeyUnsupported indicates a key matching the token WAS found, but is
	// not usable to verify it — a sub-2048-bit RSA modulus, a `use` that is not
	// `sig`, `key_ops` without `verify`, a declared `alg` that disagrees with the
	// token, or a key type/curve inconsistent with the token's alg.
	//
	// It is distinct from ReasonUnknownKID on purpose, and the distinction is
	// operational rather than cosmetic: unknown_kid says "rotate or re-check the
	// kid", while this says "the key is right there and your configuration or
	// key material is the problem". Reporting the former for the latter sends an
	// operator hunting the wrong fault. The specific cause is in the log-only
	// detail, never on the wire.
	ReasonKeyUnsupported Reason = "key_unsupported"
	// ReasonKeysStale indicates cached key material is older than the
	// configured Config.MaxJWKSStaleness and a fresh fetch did not succeed, so
	// it is no longer trusted; paired with CodeUnavailable.
	//
	// It is distinct from ReasonKeysUnavailable on purpose: keys_unavailable
	// means the verifier never had usable key material, while keys_stale means
	// it has some and is deliberately refusing to keep trusting it. For an
	// operator those point at the same root cause (the issuer is unreachable)
	// but different urgency — a revocation may already have been published.
	ReasonKeysStale Reason = "keys_stale"
	// ReasonTokenType indicates the "typ" header does not match any entry in
	// Config.AcceptedTokenTypes (e.g. an ID token presented as an access
	// token), or is present but not a string. The non-string case applies even
	// when AcceptedTokenTypes is empty.
	ReasonTokenType Reason = "token_type"
	// ReasonInvalidClaims indicates the token parsed as a structurally valid
	// JWT but its claim set was rejected by golang-jwt for a reason this
	// package does not otherwise enumerate (e.g. a claim with the wrong JSON
	// type, such as a numeric iss). It is deliberately NOT ReasonMalformed:
	// that pair is the load-bearing introspection-fallback trigger (see
	// Error), and a token that parsed as a JWT is not an opaque token worth
	// introspecting, no matter which claim check subsequently failed it.
	ReasonInvalidClaims Reason = "invalid_claims"
	// ReasonTokenKind indicates the token is not an access token for this
	// endpoint: its `typ` is on the default deny list, or it carries a `cnf`
	// claim and Config.AllowCNF is not set.
	ReasonTokenKind Reason = "token_kind"
	// ReasonCheck indicates a Check rejected the token, returned an error or
	// panicked.
	ReasonCheck Reason = "check"
	// ReasonUnknownIssuer indicates a TrustSet has no trust for the token's
	// `iss` claim, or the token carries no string `iss`. No key was tried.
	ReasonUnknownIssuer Reason = "unknown_issuer"
	// ReasonTrustStale indicates the TrustSet trust for the token's issuer is
	// past its NotAfter; paired with CodeUnavailable.
	ReasonTrustStale Reason = "trust_stale"
	// ReasonScope indicates the token is valid but lacks a required scope;
	// paired with CodeInsufficientScope.
	ReasonScope Reason = "scope"
)

type SetOption added in v0.0.62

type SetOption func(*setConfig)

SetOption configures a TrustSet.

func WithClock added in v0.0.62

func WithClock(clock func() time.Time) SetOption

WithClock sets the clock Verify reads once per token. The default is time.Now.

func WithProviderOnly added in v0.0.62

func WithProviderOnly() SetOption

WithProviderOnly refuses every trust whose Config.ProviderOnly is false. A set whose keys are fetched elsewhere uses it to guarantee that no trust in it does discovery or a JWKS fetch.

func WithReservedIssuers added in v0.0.62

func WithReservedIssuers(issuers ...string) SetOption

WithReservedIssuers refuses every trust whose Config.Issuer, with trailing slashes removed, equals one of issuers with trailing slashes removed. The comparison is otherwise exact. Calls accumulate. A set fed from external data uses it with the issuers of another set, so that a trust cannot take over one of them, for example https://idp as https://idp/.

type Trust added in v0.0.62

type Trust struct {
	// ID names the trust in errors. Required and unique within the set.
	ID string
	// Config verifies the issuer's tokens exactly as a Validator built from it
	// would: keys, algorithms, leeway and acceptance policy. Config.Issuer is
	// required; it is the value the token's `iss` must equal.
	Config Config
	// NotAfter, when set, is when the data the trust was built from goes
	// stale. From then on its tokens fail with CodeUnavailable and
	// ReasonTrustStale; they never fall through to another trust.
	NotAfter time.Time
	// Tag is returned unchanged in Principal.Trust, so a caller can attach its
	// own identifiers or policy to the trust that verified a token.
	Tag any
}

Trust is one issuer a TrustSet accepts tokens from.

type TrustError added in v0.0.62

type TrustError struct {
	ID  string
	Err error
}

TrustError reports a trust NewTrustSet did not install, and why.

func (*TrustError) Error added in v0.0.62

func (e *TrustError) Error() string

func (*TrustError) Unwrap added in v0.0.62

func (e *TrustError) Unwrap() error

Unwrap returns the cause.

type TrustRef added in v0.0.62

type TrustRef struct {
	ID     string
	Issuer string
	// Tag is Trust.Tag, returned unchanged.
	Tag any
}

TrustRef identifies the TrustSet trust that verified a token: its ID, its issuer and the Tag the caller attached to it.

type TrustSet added in v0.0.62

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

TrustSet verifies tokens from several issuers. It routes a token to the trust whose Config.Issuer equals the token's `iss`, then verifies and accepts it with that trust's Config alone. There is no fallthrough to another trust.

A TrustSet is immutable. To change the trusts, build a new set and swap it in (for example with atomic.Pointer), then Close the old one. Verify is safe for concurrent use.

func (*TrustSet) Close added in v0.0.62

func (s *TrustSet) Close()

Close stops the background JWKS refresh of every validator in the set. It does not wait for Verify calls already running; one that loses the race fails with CodeUnavailable, as does every Verify afterwards. It is idempotent.

func (*TrustSet) Verify added in v0.0.62

func (s *TrustSet) Verify(ctx context.Context, raw string) (Principal, error)

Verify verifies a bare JWT (no "Bearer " prefix; see ParseBearer) and returns the Principal, with Principal.Trust naming the trust that verified it. Every error is an *Error.

A token that is not a JWT is CodeInvalidToken with ReasonMalformed, so PossiblyOpaque works. A JWT whose `iss` no trust routes is ReasonUnknownIssuer and no key is tried, so a caller can safely pass it to another verifier. A trust past its NotAfter is CodeUnavailable with ReasonTrustStale. Otherwise the result is what the trust's Validator would return. One clock reading serves every temporal check.

type Validator

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

Validator verifies inbound JWT bearer tokens against the configured issuer and audience policy and the issuer's JWKS key material.

A Validator owns background JWKS refresh goroutines; always call Close when it is no longer needed.

func NewValidator

func NewValidator(ctx context.Context, cfg Config) (*Validator, error)

NewValidator validates cfg and constructs a Validator.

The ctx argument governs the LIFETIME of the validator's background JWKS refresh, not just construction: the refresh goroutines stop when ctx is canceled or Close is called. Pass an application-lifetime context, not a per-request context.

Construction-time network I/O (discovery and the initial JWKS fetch) is separately bounded by an internal timeout, so passing context.Background() cannot hang NewValidator indefinitely.

Errors returned here are ordinary construction errors, not the *Error type: *Error is reserved for Validate/ParseBearer runtime failures.

func (*Validator) Close

func (v *Validator) Close()

Close stops the validator's background JWKS refresh by canceling its internal context. It is idempotent and safe to call concurrently. It does not wait for in-flight fetches to finish.

Validate must not be called after Close; if it is, it fails fast with CodeUnavailable rather than blocking. A concurrent Close during an in-flight Validate is also safe: cache operations are bound to the validator lifetime, so they unblock instead of waiting on a controller that has stopped.

func (*Validator) Validate

func (v *Validator) Validate(ctx context.Context, token string) (Principal, error)

Validate verifies a bare JWT (no "Bearer " prefix — callers use ParseBearer for that) against the validator's issuer/audience policy and JWKS key material, returning the verified Principal.

Every failure is a *Error. It reads the clock once and runs verify (signature and temporal checks), then accept (audience, `typ`, `cnf`).

Jump to

Keyboard shortcuts

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