Skip to content

feat(authn): inbound OIDC/JWT bearer-token validation for resource servers - #224

Merged
jhrozek merged 10 commits into
mainfrom
authn
Aug 10, 2026
Merged

jhrozek merged 10 commits into
mainfrom
authn

Conversation

@jhrozek

@jhrozek jhrozek commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

Closes #222. Depends on #221, which has landed, so this is no longer stacked — it applies directly to main.

Adds authn: verification of inbound JWT bearer tokens at a resource server, against a configured issuer/audience policy and the issuer's JWKS. It performs no OAuth flows and issues nothing — no token endpoint, no code exchange, no signing. Token-exchange client behaviour and SVID handling remain out of scope per the issue.

10 commits, each building and passing -race independently.

What it does

  • Validate / ParseBearer / Principal, with a typed *Error carrying a client-safe Code (RFC 6750) and a finer-grained Reason, plus log-only detail.
  • OIDC discovery when no JWKS URL is configured, with the document's issuer asserted byte-exact against the configured value (OIDC Discovery §4.3 / RFC 8414 §3.3). Without that, a poisoned well-known repoints jwks_uri at an attacker JWKS and every downstream check still passes.
  • JWKS retrieval with a pinned refresh cadence, a 1 MiB body cap, an explicit URL allowlist, and unknown-kid recovery with a bounded negative cache.
  • A KeyProvider seam for embedded issuers, which also relaxes construction — see below.
  • PossiblyOpaque(err), the supported way for a consumer to layer RFC 7662 introspection above Validate.

Hardening worth reviewing specifically

Ordered by how much they'd hurt if wrong:

  • Default-deny SSRF on discovery and JWKS fetches. A jwks_uri resolving to a private, loopback or link-local address is refused unless AllowPrivateIP is set. The check runs on the resolved address at dial time, so it also defends DNS rebinding, and installing it forces keep-alives off so a pooled connection cannot skip it on a later refresh.
  • Algorithm gate before any key material is touched (RFC 8725 §3.1). none and all HMAC algs excluded — HMAC against a public JWKS is the algorithm-confusion attack. crit rejected outright. Candidate keys filtered on use/key_ops/declared alg with a kty-and-curve backstop, so an EC key can never reach an RSA verify path.
  • No credential ever reaches an error string. Error() is documented as log-safe, and a malformed header routinely still carries a live token, so ParseBearer reports only a structural category and a length (RFC 6750 §5).
  • RSA strength floor of 2048 bits (RFC 7518 §3.3), applied to both JWKS and provider keys.
  • Optional MaxJWKSStaleness, MaxTokenLifetime, AcceptedTokenTypes (typ gate), DisableLeeway — all off by default, because each can reject tokens ToolHive accepts today.

ToolHive compatibility

Three requirements were deliberately relaxed after diffing against ToolHive's pkg/auth, because each would otherwise have failed deployments at startup rather than per-request:

ToolHive today Here
Issuer required only if no JWKS URL same — empty is legal with an explicit JWKSURL, and disables iss verification
aud entries any string, check skipped when unset bounded strings (RFC 7519 StringOrURI, so Entra GUIDs and bare client_ids work); empty list only behind explicit AllowAnyAudience
token lifetime no bound MaxTokenLifetime defaults to disabled

Also loosened relative to ToolHive: kid is no longer required, and PS256/384/512 now work.

Behaviour changes a consumer must know about

  • Discovery issuer must byte-match — trailing-slash differences are the likely break, and the slash is deliberately not folded, because folding accepts a non-conformant document.
  • Redirects are refused on discovery and JWKS; ToolHive follows them to any host today.
  • iat in the future is now rejected; ToolHive does not examine iat.
  • The default is 60s of leeway where ToolHive has none. DisableLeeway restores exact-exp behaviour, but also tightens nbf and iat, so neither setting is exact parity — documented on the field.
  • Sub-2048-bit RSA keys are dropped. This reports ReasonKeyUnsupported naming the strength problem rather than implying an unknown kid.
  • A KeyProvider miss falls through to the JWKS; a provider rejection does not and fails immediately.

Verification

task clean (lint + race tests), task license-check clean, authn coverage 92.3%. Every commit verified to build and pass -race on its own, and the package survives repeated -race -count=2 runs.

Reviewed three times before opening: two independent external reviews plus an integration review from the session writing the ToolHive-side port. That last one confirmed the reason-threading and the log-safe boundary by reading the diff. Findings from all three are closed except the deliberate deferrals below.

Deliberately not done

  • Lazy/tolerant construction for an unreachable issuer. A Config.Lazy knob means porting back the mutex-and-latch plus per-request retry this package exists to delete, and discovery tolerance is the hard half — on a failed discovery there is no jwksURL, so nothing is registered and nothing can be retried. The availability property is being preserved consumer-side instead, by constructing in a background goroutine with backoff and serving 503 until it succeeds. NewValidator cancels its context before returning an error so that retry loop cannot leak the jwx cache goroutines, and there is a regression test pinning it.
  • An iat opt-out, until a deployment actually needs exp parity without the iat tightening.
  • maxKeyCandidates truncation stays undiagnosable for a kid-less token against a JWKS of more than 8 keys. Unreachable when a kid is present, and the alternative is the amplification the bound exists to prevent.

Per the issue, done means merged and released — downstream pins by version.

🤖 Generated with Claude Code

jhrozek and others added 10 commits August 10, 2026 16:46
Adds the authn package: verification of inbound JWT bearer tokens at a resource
server, against a configured issuer/audience policy and the issuer's JWKS. It
performs NO OAuth flows and issues nothing — there is no token endpoint, no
code exchange, and no signing.

Error model. A single *Error type carries a client-safe Code (the RFC 6750
error value) and a finer-grained Reason, plus wrapped detail that is log-only
and may contain key ids, JWKS URLs and transport errors. CodeUnavailable is an
internal 503 discriminator, not an RFC 6750 registered value, and must not be
emitted on the wire. PossiblyOpaque exposes the one contract a consumer needs
to layer RFC 7662 introspection above Validate: a token that could not be
parsed as a JWT at all may be opaque and worth introspecting.

Construction is fail-closed and validated eagerly, so a typo is a startup
failure rather than a 401 on every request. When no JWKS URL is configured the
issuer's OIDC discovery document supplies one, and the document's issuer is
asserted BYTE-EXACT against the configured value (OIDC Discovery 4.3 / RFC 8414
3.3): without that, a poisoned well-known repoints jwks_uri at an attacker JWKS
and every downstream check still passes.

The JWKS fetch is hardened at the transport: response bodies are capped at
1 MiB because jwx reads the body itself and would otherwise accept ~1GB;
redirects are refused, since a jwks_uri that 302s to an internal host must not
defeat the scheme check; the httprc client is restricted to an explicit URL
allowlist, because its default permits every URL; and the refresh cadence is
pinned so the issuer's Cache-Control cannot decide how long key material stays
trusted locally. A caller-supplied client keeps the body cap, and its unset
CheckRedirect/Timeout are filled in so a bare &http.Client{} cannot silently
drop them.

Verification order is fixed so nothing touching key material runs before the
algorithm gate (RFC 8725 3.1) and nothing expensive runs before the cheap
structural rejects. The algorithm allowlist admits only RSA and ECDSA families:
`none` and HMAC are excluded, since HMAC against a public JWKS IS the
algorithm-confusion attack. A `crit` header is rejected outright because this
package understands no extensions. Candidate keys are filtered on
use/key_ops/alg with a kty-and-curve backstop, so an EC key can never reach an
RSA verification path, and are bounded in count so a kid-less token cannot turn
a large JWKS into a DoS amplifier. An unknown kid triggers one serialized
refresh with a bounded negative cache, so key rotation recovers without letting
sprayed random kids drive unbounded fetches.

Failures are mapped from golang-jwt's sentinels to Reasons deliberately: the
default arm reports invalid claims rather than malformed, because by then the
token HAS parsed as a JWT and routing it to introspection would be wrong.

Coverage 92%.

Co-Authored-By: Claude Opus 5 <[email protected]>
…arity

Three config requirements rejected deployments that ToolHive's validator accepts
today, two of them at startup rather than per request -- so a resource server
would fail to come up rather than 401 a request.

Issuer is no longer mandatory on its own: at least one of Issuer or JWKSURL is
now required, matching ToolHive, which requires only one of the two and skips
the iss check when the issuer is unset. An empty Issuer disables iss
verification, so it is documented as only appropriate when the JWKS endpoint
itself is the trust boundary. Principal.Issuer now reports the VERIFIED iss
claim rather than Config.Issuer -- with the check enabled the parser has already
proven they are byte-equal, and with it disabled the claim is the only thing
that says who issued the token.

Audience entries are validated as bounded, control-character-free strings
instead of absolute URIs. RFC 7519 section 4.1.3 types aud as StringOrURI, so
Entra ID's opaque GUID audiences and bare client_id audiences are conformant;
requiring a URI rejected valid tokens. An empty audience list is allowed only
behind the new AllowAnyAudience, and setting both is an error -- disabling the
audience check should be a deliberate, visible act, since a silently absent one
is how confused-deputy bugs reach production.

MaxTokenLifetime now defaults to disabled rather than 24h. ToolHive enforces no
exp-iat bound at all, so a default cap would start rejecting the long-lived
service-account tokens it accepts today. The field remains for callers who want
the bound.

Co-Authored-By: Claude Opus 5 <[email protected]>
…tches

ToolHive blocks a jwks_uri that resolves to a private, loopback, or link-local
address BY DEFAULT: its JWKS client is built with WithPrivateIPs(AllowPrivateIP)
and --jwks-allow-private-ip defaults to false. authn had no address-level check
at all, so adopting it would silently drop that protection -- the worst shape of
regression, because it hits deployments that changed nothing.

The https scheme check and redirect refusal do not help here: neither classifies
the address a name resolves to, so a jwks_uri of https://169.254.169.254/... was
fetched without complaint.

The default client is now built by toolhive-core/networking, which installs a
net.Dialer.Control guard that rejects those ranges after DNS resolution (so it
also defends DNS rebinding) and forces keep-alives off so a pooled connection
cannot skip the per-dial check on a later refresh -- which matters here
specifically, since the JWKS is refreshed every 15 minutes over a long-lived
client. AllowPrivateIP and CACertPath are added to Config, named to match
ToolHive's fields so its migration is parameter-preserving.

authn keeps refusing redirects outright rather than adopting networking's
tolerance of them: ToolHive is looser here (its builder never sets
CheckRedirect, so redirects are followed to any host today), and parity must not
mean weakening the stricter side.

A supplied HTTPClient necessarily opts out of the dial guard, since a
DialContext cannot be retrofitted onto someone else's transport. That is now
documented explicitly, along with the recipe for attaching a bearer token to the
outbound JWKS request.

Test fixtures gain AllowPrivateIP because httptest listens on loopback -- which
is the point: any localhost issuer now needs that opt-out, exactly as under
ToolHive.
…ded issuers

ToolHive supports an in-process key provider so a resource server can verify
tokens from an authorization server running in the same pod. authn's
fail-closed construction is incompatible with that topology, and the feature is
not vestigial: it is CRD-driven (MCPExternalAuthConfig type embeddedAuthServer),
un-gated unlike its sibling OBO type, covered by integration tests that stand up
real OAuth flows, and used by both thv vmcp serve and the plain proxy runner.

Two distinct failure modes had to be handled, and only the first is a race:

  - Startup ordering. The embedded issuer's JWKS route is mounted on the very
    listener that has not started yet when the validator is constructed, so a
    fetch connection-refuses.
  - Permanent unreachability. ToolHive tolerates DISCOVERY failure when a key
    provider is present because the issuer's advertised URL may not be routable
    from inside the cluster at all. Lazy retry alone does not cover this; the
    local key path has to work with no HTTP whatsoever.

KeyProvider is consulted before the JWKS cache, matching ToolHive's order, and
its keys go through the same kid/alg filtering, maxKeyCandidates bound, and
kty/curve backstop as JWKS keys -- without that backstop an ECDSA key could be
handed to an RS256 verification path.

Construction relaxes ONLY when a provider is configured: discovery failure
becomes non-fatal and the first JWKS fetch is no longer required. With no
provider, fail-closed behavior is unchanged, and there is a test for each
direction. Note the fetch is still ATTEMPTED with a provider, not skipped:
skipping it left a reachable JWKS unpopulated, so a provider miss failed with
ErrNotReady instead of falling through to working key material.

Discovery now retries transient failures three times with exponential backoff,
mirroring ToolHive, since a resource server commonly loses a startup race with
its issuer. A poisoned document -- issuer mismatch, missing or non-https
jwks_uri -- is marked non-transient and fails on the first attempt, because
retrying only re-fetches the same unacceptable answer.

Co-Authored-By: Claude Opus 5 <[email protected]>
… iat:0

Five findings from an external review of an earlier revision of this branch that
survive the ToolHive-compatibility work.

Credential disclosure (the serious one). ParseBearer echoed the whole
Authorization value via %q, and Error() is documented as log-safe, so any
slightly malformed header put a live replayable token into the logs --
"Bearer <token> junk", or a token sent with no scheme at all. RFC 6750 section 5
names token disclosure as a primary threat. No ParseBearer error now contains
any byte of the header, not even the scheme position, since a header with no
separator puts the whole credential there. Errors report the structural
category and, where useful, a length.

Shutdown hang. The jwx cache's controller goroutines are bound to the
validator's lifetime context, so a Lookup carrying only the request context
would, after Close, send on a channel with no remaining receiver and block
forever. Measured: Validate after Close blocked past a 3s timeout. Cache
operations are now bound to both contexts via context.AfterFunc, and Validate
fails fast with CodeUnavailable when the validator is already closed. Covered
from both sides: after Close, and a Close racing an in-flight Validate.

iat:0 bypassed MaxTokenLifetime. 0 is a valid NumericDate (the Unix epoch), but
jwt.MapClaims.GetIssuedAt returns nil for it, so the lifetime check read the
claim as absent and skipped -- measured: a token with iat:0 and exp 24h out was
ACCEPTED under MaxTokenLifetime=1h. The check now tests claim PRESENCE on the
raw map. Narrower than when reported, since the bound is now opt-in, but it
silently defeated the check for anyone who opted in.

Audiences aliased caller memory. Config is copied by value, but the slice shared
its backing array, so mutating it after construction rewrote the trusted policy
and raced Validate. It is cloned at construction.

RFC 7235 separator. `credentials = auth-scheme 1*SP token68` permits more than
one space, but "Bearer  <token>" was rejected. Additional separator spaces are
now trimmed; token68 still forbids internal whitespace.

Also adds the missing authn and networking rows to README.md's package table.

Deliberately not addressed here, as they change what gets rejected and are
policy calls: maximum JWKS staleness (a revoked key stays trusted while
refreshes fail), a minimum RSA modulus, configurable algorithm pinning, and a
typ/token-use discriminator against ID-token substitution.

Co-Authored-By: Claude Opus 5 <[email protected]>
Three hardening policies from the external review. None is a ToolHive
regression -- ToolHive enforces none of them either -- so each is net-new
tightening, and the two that could reject tokens accepted today are opt-in with
a zero/empty default.

RSA strength floor, on by default and not configurable. A 1024-bit key
validated cleanly before this; RFC 7518 section 3.3 requires at least 2048 bits
for every RS*/PS* algorithm. A short key is now filtered out as a verification
candidate rather than used. Applied to both key sources: a KeyProvider is
trusted, but not trusted to be correctly configured. This one is on by default
because it is a spec requirement rather than a policy preference, and the only
realistic casualty is a test fixture.

MaxJWKSStaleness, zero (disabled) by default. The cache keeps serving its last
good key set after every failed refresh, so a key revoked at the IdP stayed
trusted for as long as the endpoint was unreachable -- measured: three
consecutive validations of a revoked key succeeded after the JWKS started
returning 500. Enabling the bound trades availability for that window, which is
why it is opt-in: a prolonged issuer outage becomes an authentication outage
instead of an invisible one.

Freshness is deliberately self-correcting rather than schedule-based. httprc
exposes no last-success accessor and this package cannot observe the cache's
BACKGROUND refreshes, so a purely timestamp-based check would reject keys that
were in fact fresh. Instead, exceeding the bound triggers a refresh attempt
before anything is rejected: a healthy endpoint therefore never trips it, and
the refreshFloor rate limit caps the cost. lastSuccess is tracked separately
from lastRefresh, since only a success proves the cached set reflects the
issuer.

AcceptedTokenTypes, empty (accept anything) by default. Every typ was accepted
before this, including a token explicitly labelled id_token+jwt carrying nonce
and auth_time. Comparison is case-insensitive with an optional application/
prefix per RFC 7515 section 4.1.9, and a missing or non-string typ fails a
configured gate, since the point is to require a positive statement of token
kind. It cannot default to RFC 9068's at+jwt: that is a SHOULD, and many IdPs
emit JWT or omit the header.

Worth recording why this gate is lower value than it first appears: the AUDIENCE
check is the primary defence against ID-token substitution, because an ID
token's aud is the client_id rather than the resource. The gate matters mainly
when AllowAnyAudience is set or a deployment uses its client_id as the resource
audience -- documented on the field.

Still deferred: per-deployment algorithm pinning (additive, no demand yet), and
the two racing construction fetches, whose honest fix is an upstream
register-without-fetch option in jwx.

Co-Authored-By: Claude Opus 5 <[email protected]>
…s and log safety

Seven findings from an external review, none of which the earlier reviews or my
own passes caught. All were reproduced against the code before being fixed.

AcceptedTokenTypes was not cloned, so a caller mutating its slice after
construction rewrote the validator's trusted typ policy and raced Validate.
Audiences was already cloned for exactly this reason; AcceptedTokenTypes was
added two commits later without the same treatment.

lastSuccess was never stamped when a KeyProvider is configured: the stamp sat
after the provider's early return in init, so it was unreachable. staleness()
was therefore enormous from construction, and once MaxJWKSStaleness is set the
JWKS fallback rejects with keys_stale. The symptom is masked while the issuer is
reachable, because jwksFresh self-corrects by refreshing -- it bites during an
outage, which is the one scenario a KeyProvider exists for.

Malformed provider keys panicked validation rather than being rejected. Both
`&rsa.PublicKey{}` (nil modulus, panics in big.Int.BitLen) and
`&ecdsa.PublicKey{}` (nil Curve, panics on the nil-interface method call)
crashed the request path, and PublicKeys is called per validation. Guarded in
both branches, treating a malformed key as ineligible to match every other
filter in that file.

InsecureAllowHTTP permitted ANY scheme, not just http: the test was
`scheme != https && !insecureAllowHTTP`, so ftp://, file:// and gopher:// all
passed, and validation/http.ValidateResourceURI does not check the scheme value
either. Replaced with an explicit allowlist.

A KeyProvider swallowed non-transient discovery failures. discoverWithRetry
marks a rejected document -- issuer mismatch, missing or non-https jwks_uri --
as non-transient so it fails fast, but init's switch did not distinguish it, so
a configuration error became "abandon JWKS forever" with jwksCache nil and
unknown_kid for every token the provider does not offer. Only transport
failures are now tolerated; startup-race tolerance is not a licence to ignore a
document we rejected.

The crit header value was rendered with %v into an error whose text is
documented as log-safe, allowing control-character log injection from an
unverified attacker-controlled header. The value is no longer rendered at all.
Note this was the ONLY such site: alg, kid and typ all use %q, which escapes
control characters, so no package-wide sweep was warranted.

A JWKS key declaring a `use` other than sig stayed eligible, since only an
exact `enc` match was rejected. Now only an absent use or sig is accepted.

ParseBearer accepted CR/LF, NUL, ESC and DEL, rejecting only spaces and tabs,
so a token carrying CRLF flowed on to consumers that may place it in an HTTP
header. Now rejects anything outside printable ASCII. Deliberately NOT strict
RFC 7235 token68: that alphabet could forbid characters real IdPs use in OPAQUE
tokens, which this package passes through on purpose so a consumer can
introspect them.

Also from the integration review:

AuthTokenFile is now a Config field wired through networking's WithTokenFromFile,
resolving a contradiction: attaching a bearer token to the outbound JWKS request
previously required a caller-supplied HTTPClient, which opts out of the
private-IP dial guard -- so a port had to drop the flag or drop the SSRF
protection added two commits earlier.

DisableLeeway makes zero clock skew expressible. Leeway == 0 defaulted to 60s,
so the package newly accepted tokens up to a minute past expiry with no opt-out
-- the same defaulting anti-pattern deliberately avoided for MaxTokenLifetime
and MaxJWKSStaleness.

Refused redirects now return a real error naming the target instead of
http.ErrUseLastResponse, which is not an error: it handed the 3xx back, so an
IdP behind a redirecting load balancer surfaced "returned status 302" or a parse
failure rather than anything mentioning redirects.

Deliberately not addressed, as agreed: lazy/tolerant construction for an
unreachable issuer, a distinct reason for keys dropped by the RSA strength
floor, and two items where the current behaviour is the lesser evil -- the 30s
negative-cache window is the kid-spraying guard working as designed, and
maxKeyCandidates truncation has no clean fix, since trying every key is the
amplification the bound prevents.

Co-Authored-By: Claude Opus 5 <[email protected]>
…efore scanning

Two one-liners from the second pass of the integration review.

keyTypeMatchesAlg's EC branch called raw.Curve.Params().Name with no nil-Curve
guard, while the three sibling sites -- the RSA branch beside it, and both
branches in keyprovider.go -- gained guards in the previous commit. It is very
likely unreachable, since jwk.Export should reject an unknown crv, but that is
exactly the status assigned to the RSA guard that WAS added: leaving one of four
sites unguarded is the defect, not the reachability. The Curve check must
precede Params(), because the promoted raw.Params() is raw.Curve.Params() and
panics identically on a nil Curve.

ParseBearer scanned the whole credential for printable ASCII before applying the
length bound, so work was proportional to attacker-chosen input. The O(1) bound
now runs first. net/http's MaxHeaderBytes already caps this, so it is hygiene
rather than a fix -- and the reordering is free.

Both paths still return CodeInvalidRequest/ReasonMalformed, so the wire contract
is unchanged; only the log-side detail message differs for a credential that is
both oversized and non-printable. There is a test pinning that ordering, since
the message is the only observable difference.

No test for the nil-Curve guard: constructing a jwk.Key with a stripped crv
needs disproportionate machinery, the same reason the RSA guard beside it has
none. Both are defence-in-depth on paths jwk.Export should already refuse.

Co-Authored-By: Claude Opus 5 <[email protected]>
…nown kid

Closes the diagnosability gap from the integration review. A key filtered out of
the candidate set was indistinguishable from a kid that is not in the JWKS at
all, so an operator with a legacy 1024-bit key got unknown_kid -- a message
pointing at the wrong problem entirely.

The cause was structural, not cosmetic: the eligibility functions were bool
predicates and candidateKeys filtered silently, so by the time verificationKeys
saw an empty set it could no longer tell "nothing carries that kid" from "the key
is here and unusable". A new keyRejection type is threaded out of both filter
chains -- the JWKS path and the KeyProvider path -- and an empty set caused by a
rejection is now reported as ReasonKeyUnsupported.

It covers every silent-ineligibility path, since they all had the same failure
shape: a `use` that is not sig, `key_ops` without verify, a declared `alg` that
disagrees with the token, a key type or curve inconsistent with the alg, a
sub-2048-bit RSA modulus, and a key that fails to decode.

Two consequences beyond the message.

An unusable key no longer triggers the unknown-kid recovery. That path exists for
a rotated kid the cache has not seen; a key that is present and unusable is
PERMANENT, so refreshing cannot help. Previously every request for such a token
spent a JWKS fetch and then a negative-cache entry. There is a test asserting the
fetch count does not move.

A kid-less token whose alg matches nothing now reports key_unsupported rather
than ReasonSignature. It previously fell through to an empty VerificationKeySet
and golang-jwt reported ErrTokenUnverifiable, which mapped to a signature failure
for a token whose signature had never been checked against anything.

On the log-safe boundary, which is the part this change could have widened by
accident: the cause strings name a PROPERTY of the key and never key material or
JWKS contents. Key sizes and use/alg declarations are public -- a JWKS is a
public document -- but the bytes are not, and nothing renders them. Three tests
hold that line: the detail must not contain the modulus or any control
character, every enum value must be non-empty and control-character-free, and
the reason must still be specific enough to be useful.

Also from the handover:

The DisableLeeway doc now states that it applies to nbf and iat as well as exp,
and that this package checks iat where ToolHive does not -- so NEITHER setting is
exact parity: set, and iat becomes zero-tolerance where ToolHive ignores it;
unset, and exp gains 60s of slack ToolHive does not give. A separate iat opt-out
is deliberately not added before a deployment needs it.

The discovery issuer-mismatch error now names the byte-identity requirement
(RFC 8414 section 3.3) and trailing-slash as the usual cause, and says
explicitly that the slash is NOT folded, because folding would silently accept a
non-conformant document.

Finally, a regression test that failed construction does not leak goroutines.
NewValidator already cancels its lifetime context before returning an error, but
that is one line in an error path, and a consumer tolerating an unreachable
issuer by retrying construction in a loop depends on it. Losing it would leak
silently and surface only as slow memory growth.

Co-Authored-By: Claude Opus 5 <[email protected]>
The field doc said a provider miss "falls through to JWKS when one is
configured", which was true before ReasonKeyUnsupported and is now only true of a
MISS. A provider REJECTION short-circuits and never consults the JWKS, so the doc
overstated the fallback -- and the field doc is what a caller reads, whereas the
reasoning only existed as an inline comment at the branch.

Also records the consequence explicitly rather than leaving it to be discovered
from behaviour: an unusable provider key shadows a usable JWKS key under the same
kid. Accepted, because 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.

Caught in review of 86c0645 by the session writing the ToolHive-side port.

Co-Authored-By: Claude Opus 5 <[email protected]>
@jhrozek
jhrozek merged commit f0b065e into main Aug 10, 2026
5 checks passed
@jhrozek
jhrozek deleted the authn branch August 10, 2026 18:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add inbound OIDC/JWT bearer-token validation (authn) to core

2 participants