Skip to content

Reject authn issuers with a template placeholder - #516

Merged
rdimitrov merged 1 commit into
tsm-03-trustset-guardsfrom
tsm-04-issuer-form
Nov 20, 2026
Merged

rdimitrov merged 1 commit into
tsm-03-trustset-guardsfrom
tsm-04-issuer-form

Conversation

@jhrozek

@jhrozek jhrozek commented Nov 12, 2026

Copy link
Copy Markdown
Contributor

Summary

  • An issuer copied from a multi-tenant discovery document has a template placeholder in it, such as https://login.microsoftonline.com/{tenantid}/v2.0. No token carries that form in its iss. Before this change, such a Config or trust was accepted, then matched nothing and failed discovery with a confusing error.
  • ValidateConfig now rejects an issuer that contains a brace, raw or percent-encoded (%7B/%7D). This covers both Config and NewTrustSet, which refuses the trust with a TrustError. The error says to configure one issuer per tenant.
  • The check is provider-neutral: no host table, and no Entra common/organizations/consumers check. That vendor knowledge stays out of the library. The shared validation/http checks are unchanged.
  • Behaviour change: a config with such an issuer used to construct and now fails validation. It could never verify a token.

Stack: #506 (jose, errors) → #507 (verify/accept) → #508 (checks) → #509 (scopes, algs) → #510 (JWKS close race) → #511 (ProviderOnly) → #514 (TrustSet) → #515 (guards) → this PR

Test plan

  • TestValidateIssuerForm: raw braces, a lone closing brace, upper- and lower-case percent-encoded braces rejected with a "template placeholder" error; tenant and generic issuers accepted
  • TestValidateConfigAgreesWithNewValidator and TestNewTrustSetRefusesTrusts: templated issuers refused through ValidateConfig, NewValidator and NewTrustSet
  • go test -race ./authn/, golangci-lint run ./authn/...: 0 issues, task license-check passes

🤖 Generated with Claude Code

An issuer copied from a multi-tenant discovery document has a template
placeholder in it, such as https://login.microsoftonline.com/{tenantid}/v2.0.
No token carries that form in its iss. A trust or Config with one was
accepted, then matched nothing and failed discovery with a confusing error.

ValidateConfig now rejects an issuer that contains a brace, raw or
percent-encoded, so both Config and a TrustSet trust (refused by
NewTrustSet with a TrustError) refuse it. The error says to configure one
issuer per tenant. The check knows nothing about any provider, and the
shared validation/http checks are not changed.

Behaviour change: a configuration with such an issuer used to construct and
now fails validation. It could never verify a token.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@jhrozek jhrozek mentioned this pull request Nov 12, 2026
1 task done

@rdimitrov rdimitrov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. Cheap, provider-neutral, and it turns a confusing discovery failure into a clear config error.

@rdimitrov
rdimitrov merged commit 437d32a into tsm-03-trustset-guards Nov 20, 2026
@rdimitrov
rdimitrov deleted the tsm-04-issuer-form branch November 20, 2026 09:20
rdimitrov pushed a commit that referenced this pull request Nov 20, 2026
* Add TrustSet guards for sets built from external data

A Directory-fed workload set is rebuilt from Directory data every 30
seconds. Its keys are fetched elsewhere and passed in as ProviderOnly
trusts. Two things must hold for that set however the data looks: no
trust may capture an issuer that a human IdP set already serves, and no
trust may make the library do discovery or a JWKS fetch. NewTrustSet
checked neither, so a Directory trust for https://idp/ could shadow the
static https://idp, and one trust without ProviderOnly would turn a
rebuild into network requests to a URL that came from Directory data.

WithReservedIssuers refuses a trust whose issuer equals a reserved one,
ignoring trailing slashes and otherwise exact. Calls accumulate. The
workload set is given the gateway's human issuer list. WithProviderOnly
refuses every trust whose Config.ProviderOnly is false, as defence in
depth for the same set.

Both checks run in the validation phase, after validateTrust and before
the shared ID and issuer check. A refused trust therefore does not take
part in that check and cannot cause the refusal of another trust.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Reject authn issuers with a template placeholder (#516)

An issuer copied from a multi-tenant discovery document has a template
placeholder in it, such as https://login.microsoftonline.com/{tenantid}/v2.0.
No token carries that form in its iss. A trust or Config with one was
accepted, then matched nothing and failed discovery with a confusing error.

ValidateConfig now rejects an issuer that contains a brace, raw or
percent-encoded, so both Config and a TrustSet trust (refused by
NewTrustSet with a TrustError) refuse it. The error says to configure one
issuer per tenant. The check knows nothing about any provider, and the
shared validation/http checks are not changed.

Behaviour change: a configuration with such an issuer used to construct and
now fails validation. It could never verify a token.

Co-authored-by: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
rdimitrov pushed a commit that referenced this pull request Nov 20, 2026
* Add an immutable TrustSet that routes tokens by issuer

A server that accepts tokens from several issuers has to pick the right
keys and policy for a token before verifying it. The only hint is the
token's unverified iss. The AI gateway and the connector gateway each do
this by hand today, with two different JWT parsers.

TrustSet does it once. A Trust is an ID, an ordinary Config (Issuer
required), an optional NotAfter and an opaque Tag. NewTrustSet validates
the trusts, builds one Validator per trust in parallel, and returns a set
with every trust that built plus a TrustError for each one that did not.
Verify reads the unverified iss as an exact string, picks the trust whose
Config.Issuer equals it, and verifies and accepts the token with that
trust's Validator alone. The validator checks that the verified iss equals
the issuer, so a wrong peek cannot pass. There is no fallthrough to another
trust.

The set is immutable. To change trusts, a caller builds a new set, swaps
it in and closes the old one. There is no Replace, no partitions and no
reuse: static issuers are built once at startup, and Directory-fed trusts
are ProviderOnly, so a rebuild does no I/O and the old set holds no
goroutines. The lifetime of the background JWKS refresh is the set, not
ctx, so a set built per poll does not register a child on a long-lived
context. ctx bounds construction only.

A trust whose ID or issuer (trailing slashes ignored) is shared with
another is refused, together with the other one, since there is no rule
for which is meant. That keeps https://idp and https://idp/ from both
routing. The cost is that whoever can add a trust with a colliding issuer
can deny service to another trust, so a feed must reject collisions when
trusts are registered.

Errors: a token that is not a JWT stays ReasonMalformed, so PossiblyOpaque
works. A JWT that no trust routes is ReasonUnknownIssuer and no key is
tried, so the caller can pass it to its other verifier. A trust past its
NotAfter is CodeUnavailable with ReasonTrustStale rather than an unknown
issuer, so its tokens are not passed on. A trust that failed to build is
absent from the set, so its tokens are ReasonUnknownIssuer; a caller for
whom that hand-off is unsafe treats the returned TrustErrors as fatal.

TrustRef now carries the trust's ID, Issuer and Tag. The caller's own
identifiers (for a Directory trust: authority, revision, profile) travel
in Tag. The Revision, Partition and Route fields, which nothing set, are
removed.

NewValidator gains an internal variant whose construction I/O is also
bounded by a second context. NewValidator itself does not change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Add TrustSet guards for sets built from external data (#515)

* Add TrustSet guards for sets built from external data

A Directory-fed workload set is rebuilt from Directory data every 30
seconds. Its keys are fetched elsewhere and passed in as ProviderOnly
trusts. Two things must hold for that set however the data looks: no
trust may capture an issuer that a human IdP set already serves, and no
trust may make the library do discovery or a JWKS fetch. NewTrustSet
checked neither, so a Directory trust for https://idp/ could shadow the
static https://idp, and one trust without ProviderOnly would turn a
rebuild into network requests to a URL that came from Directory data.

WithReservedIssuers refuses a trust whose issuer equals a reserved one,
ignoring trailing slashes and otherwise exact. Calls accumulate. The
workload set is given the gateway's human issuer list. WithProviderOnly
refuses every trust whose Config.ProviderOnly is false, as defence in
depth for the same set.

Both checks run in the validation phase, after validateTrust and before
the shared ID and issuer check. A refused trust therefore does not take
part in that check and cannot cause the refusal of another trust.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Reject authn issuers with a template placeholder (#516)

An issuer copied from a multi-tenant discovery document has a template
placeholder in it, such as https://login.microsoftonline.com/{tenantid}/v2.0.
No token carries that form in its iss. A trust or Config with one was
accepted, then matched nothing and failed discovery with a confusing error.

ValidateConfig now rejects an issuer that contains a brace, raw or
percent-encoded, so both Config and a TrustSet trust (refused by
NewTrustSet with a TrustError) refuse it. The error says to configure one
issuer per tenant. The check knows nothing about any provider, and the
shared validation/http checks are not changed.

Behaviour change: a configuration with such an issuer used to construct and
now fails validation. It could never verify a token.

Co-authored-by: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
rdimitrov pushed a commit that referenced this pull request Nov 20, 2026
* Add Config.ProviderOnly for keys that are fetched elsewhere

A Directory-fed workload trust gets its keys from the workloadtrust
adapter, which fetches and caches them with its own egress rules. A
Config with an Issuer and a KeyProvider still ran OIDC discovery against
the issuer, and fetched the JWKS it found, as a fallback for an embedded
issuer whose endpoint is not up yet. For Directory trusts that would
mean network requests to issuer URLs that came from Directory data, on
every rebuild.

ProviderOnly makes the KeyProvider the only key source. There is no
discovery and no JWKS, so the validator makes no requests and starts no
background refresh. A kid the provider does not offer is unknown_kid.
Issuer is still required and still verified.

It requires a KeyProvider and an Issuer, and these are checked before
the generic "issuer or jwks_url" rule so the error never suggests
setting jwks_url. JWKSURL, HTTPClient, CACertPath, AuthTokenFile,
AllowPrivateIP and MaxJWKSStaleness only configure fetching, so setting
one of them together with ProviderOnly is an error instead of being
silently ignored. ValidateConfig and NewValidator agree.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Add an immutable TrustSet that routes tokens by issuer (#514)

* Add an immutable TrustSet that routes tokens by issuer

A server that accepts tokens from several issuers has to pick the right
keys and policy for a token before verifying it. The only hint is the
token's unverified iss. The AI gateway and the connector gateway each do
this by hand today, with two different JWT parsers.

TrustSet does it once. A Trust is an ID, an ordinary Config (Issuer
required), an optional NotAfter and an opaque Tag. NewTrustSet validates
the trusts, builds one Validator per trust in parallel, and returns a set
with every trust that built plus a TrustError for each one that did not.
Verify reads the unverified iss as an exact string, picks the trust whose
Config.Issuer equals it, and verifies and accepts the token with that
trust's Validator alone. The validator checks that the verified iss equals
the issuer, so a wrong peek cannot pass. There is no fallthrough to another
trust.

The set is immutable. To change trusts, a caller builds a new set, swaps
it in and closes the old one. There is no Replace, no partitions and no
reuse: static issuers are built once at startup, and Directory-fed trusts
are ProviderOnly, so a rebuild does no I/O and the old set holds no
goroutines. The lifetime of the background JWKS refresh is the set, not
ctx, so a set built per poll does not register a child on a long-lived
context. ctx bounds construction only.

A trust whose ID or issuer (trailing slashes ignored) is shared with
another is refused, together with the other one, since there is no rule
for which is meant. That keeps https://idp and https://idp/ from both
routing. The cost is that whoever can add a trust with a colliding issuer
can deny service to another trust, so a feed must reject collisions when
trusts are registered.

Errors: a token that is not a JWT stays ReasonMalformed, so PossiblyOpaque
works. A JWT that no trust routes is ReasonUnknownIssuer and no key is
tried, so the caller can pass it to its other verifier. A trust past its
NotAfter is CodeUnavailable with ReasonTrustStale rather than an unknown
issuer, so its tokens are not passed on. A trust that failed to build is
absent from the set, so its tokens are ReasonUnknownIssuer; a caller for
whom that hand-off is unsafe treats the returned TrustErrors as fatal.

TrustRef now carries the trust's ID, Issuer and Tag. The caller's own
identifiers (for a Directory trust: authority, revision, profile) travel
in Tag. The Revision, Partition and Route fields, which nothing set, are
removed.

NewValidator gains an internal variant whose construction I/O is also
bounded by a second context. NewValidator itself does not change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Add TrustSet guards for sets built from external data (#515)

* Add TrustSet guards for sets built from external data

A Directory-fed workload set is rebuilt from Directory data every 30
seconds. Its keys are fetched elsewhere and passed in as ProviderOnly
trusts. Two things must hold for that set however the data looks: no
trust may capture an issuer that a human IdP set already serves, and no
trust may make the library do discovery or a JWKS fetch. NewTrustSet
checked neither, so a Directory trust for https://idp/ could shadow the
static https://idp, and one trust without ProviderOnly would turn a
rebuild into network requests to a URL that came from Directory data.

WithReservedIssuers refuses a trust whose issuer equals a reserved one,
ignoring trailing slashes and otherwise exact. Calls accumulate. The
workload set is given the gateway's human issuer list. WithProviderOnly
refuses every trust whose Config.ProviderOnly is false, as defence in
depth for the same set.

Both checks run in the validation phase, after validateTrust and before
the shared ID and issuer check. A refused trust therefore does not take
part in that check and cannot cause the refusal of another trust.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Reject authn issuers with a template placeholder (#516)

An issuer copied from a multi-tenant discovery document has a template
placeholder in it, such as https://login.microsoftonline.com/{tenantid}/v2.0.
No token carries that form in its iss. A trust or Config with one was
accepted, then matched nothing and failed discovery with a confusing error.

ValidateConfig now rejects an issuer that contains a brace, raw or
percent-encoded, so both Config and a TrustSet trust (refused by
NewTrustSet with a TrustError) refuse it. The error says to configure one
issuer per tenant. The check knows nothing about any provider, and the
shared validation/http checks are not changed.

Behaviour change: a configuration with such an issuer used to construct and
now fails validation. It could never verify a token.

Co-authored-by: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
rdimitrov pushed a commit that referenced this pull request Nov 20, 2026
* Fix Validate panicking when Close lands during a JWKS lookup

Validate reads keys through jwkfetch.Cache.Lookup. The cache's controller
goroutines are bound to the validator's lifetime context, so Close stops
them. A Lookup that is in flight at that moment can get a nil resource
back from the stopped controller, and jwkfetch type-asserts it without a
check. The result is a panic in the library, in the caller's goroutine:
an interface conversion of a nil httprc.Resource. That is upstream
behaviour. A server that closes its validator on shutdown while requests
are still arriving can crash instead of answering them.

Add lookupJWKS and make lookupCandidates call it. It recovers the panic
and returns an error only when the validator is closed. A panic on a
validator that is still open is not this race and is raised again. The
error then takes the existing lookupCandidates path and reaches the
caller as CodeUnavailable with ReasonKeysUnavailable, the same as any
other lookup failure.

Cache.Refresh finishes with the same Lookup, so refreshOnce, which
runs on the request path for an unknown kid and for the staleness check,
has the same exposure. It and the two construction-time calls in init
now go through the same guard (refreshJWKS and lookupJWKS). Register is
not affected: it only adds the resource and never type-asserts.

TestValidateSurvivesCloseRace runs many callers against a validator and
closes it once calls are in flight, repeated over fresh validators. Each
call must return a principal or a CodeUnavailable error. It panics
without the guard.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Add Config.ProviderOnly for keys that are fetched elsewhere (#511)

* Add Config.ProviderOnly for keys that are fetched elsewhere

A Directory-fed workload trust gets its keys from the workloadtrust
adapter, which fetches and caches them with its own egress rules. A
Config with an Issuer and a KeyProvider still ran OIDC discovery against
the issuer, and fetched the JWKS it found, as a fallback for an embedded
issuer whose endpoint is not up yet. For Directory trusts that would
mean network requests to issuer URLs that came from Directory data, on
every rebuild.

ProviderOnly makes the KeyProvider the only key source. There is no
discovery and no JWKS, so the validator makes no requests and starts no
background refresh. A kid the provider does not offer is unknown_kid.
Issuer is still required and still verified.

It requires a KeyProvider and an Issuer, and these are checked before
the generic "issuer or jwks_url" rule so the error never suggests
setting jwks_url. JWKSURL, HTTPClient, CACertPath, AuthTokenFile,
AllowPrivateIP and MaxJWKSStaleness only configure fetching, so setting
one of them together with ProviderOnly is an error instead of being
silently ignored. ValidateConfig and NewValidator agree.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Add an immutable TrustSet that routes tokens by issuer (#514)

* Add an immutable TrustSet that routes tokens by issuer

A server that accepts tokens from several issuers has to pick the right
keys and policy for a token before verifying it. The only hint is the
token's unverified iss. The AI gateway and the connector gateway each do
this by hand today, with two different JWT parsers.

TrustSet does it once. A Trust is an ID, an ordinary Config (Issuer
required), an optional NotAfter and an opaque Tag. NewTrustSet validates
the trusts, builds one Validator per trust in parallel, and returns a set
with every trust that built plus a TrustError for each one that did not.
Verify reads the unverified iss as an exact string, picks the trust whose
Config.Issuer equals it, and verifies and accepts the token with that
trust's Validator alone. The validator checks that the verified iss equals
the issuer, so a wrong peek cannot pass. There is no fallthrough to another
trust.

The set is immutable. To change trusts, a caller builds a new set, swaps
it in and closes the old one. There is no Replace, no partitions and no
reuse: static issuers are built once at startup, and Directory-fed trusts
are ProviderOnly, so a rebuild does no I/O and the old set holds no
goroutines. The lifetime of the background JWKS refresh is the set, not
ctx, so a set built per poll does not register a child on a long-lived
context. ctx bounds construction only.

A trust whose ID or issuer (trailing slashes ignored) is shared with
another is refused, together with the other one, since there is no rule
for which is meant. That keeps https://idp and https://idp/ from both
routing. The cost is that whoever can add a trust with a colliding issuer
can deny service to another trust, so a feed must reject collisions when
trusts are registered.

Errors: a token that is not a JWT stays ReasonMalformed, so PossiblyOpaque
works. A JWT that no trust routes is ReasonUnknownIssuer and no key is
tried, so the caller can pass it to its other verifier. A trust past its
NotAfter is CodeUnavailable with ReasonTrustStale rather than an unknown
issuer, so its tokens are not passed on. A trust that failed to build is
absent from the set, so its tokens are ReasonUnknownIssuer; a caller for
whom that hand-off is unsafe treats the returned TrustErrors as fatal.

TrustRef now carries the trust's ID, Issuer and Tag. The caller's own
identifiers (for a Directory trust: authority, revision, profile) travel
in Tag. The Revision, Partition and Route fields, which nothing set, are
removed.

NewValidator gains an internal variant whose construction I/O is also
bounded by a second context. NewValidator itself does not change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Add TrustSet guards for sets built from external data (#515)

* Add TrustSet guards for sets built from external data

A Directory-fed workload set is rebuilt from Directory data every 30
seconds. Its keys are fetched elsewhere and passed in as ProviderOnly
trusts. Two things must hold for that set however the data looks: no
trust may capture an issuer that a human IdP set already serves, and no
trust may make the library do discovery or a JWKS fetch. NewTrustSet
checked neither, so a Directory trust for https://idp/ could shadow the
static https://idp, and one trust without ProviderOnly would turn a
rebuild into network requests to a URL that came from Directory data.

WithReservedIssuers refuses a trust whose issuer equals a reserved one,
ignoring trailing slashes and otherwise exact. Calls accumulate. The
workload set is given the gateway's human issuer list. WithProviderOnly
refuses every trust whose Config.ProviderOnly is false, as defence in
depth for the same set.

Both checks run in the validation phase, after validateTrust and before
the shared ID and issuer check. A refused trust therefore does not take
part in that check and cannot cause the refusal of another trust.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Reject authn issuers with a template placeholder (#516)

An issuer copied from a multi-tenant discovery document has a template
placeholder in it, such as https://login.microsoftonline.com/{tenantid}/v2.0.
No token carries that form in its iss. A trust or Config with one was
accepted, then matched nothing and failed discovery with a confusing error.

ValidateConfig now rejects an issuer that contains a brace, raw or
percent-encoded, so both Config and a TrustSet trust (refused by
NewTrustSet with a TrustError) refuse it. The error says to configure one
issuer per tenant. The check knows nothing about any provider, and the
shared validation/http checks are not changed.

Behaviour change: a configuration with such an issuer used to construct and
now fails validation. It could never verify a token.

Co-authored-by: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
rdimitrov pushed a commit that referenced this pull request Nov 20, 2026
* Add Principal scopes, trust reference and Config.Algs

TrustSet, added later in this stack, serves tokens from several issuers.
Before it can do that, a caller needs three things from authn that the
single-issuer Validator does not yet expose.

Scopes: an endpoint decides access from the token's scopes, and a 403
must name the scopes it wanted. Principal.Scopes reads the scope claim,
falling back to scp. A non-string element yields nil rather than a
partial list. RequireScopes returns an insufficient_scope Error, which
Code.HTTPStatus maps to 403.

Trust reference: a caller must know which trust accepted a token, to log
it and to pick policy. Principal.Trust is a TrustRef, which is zero for a
plain Validator. TrustSet, later in this series, fills it in.

Config.Algs: lets an operator restrict signature algorithms to a subset
of the default allowlist, instead of accepting all of it. Entries outside
the allowlist, or repeated, are configuration errors.

Principal.Claims is now a deep copy. Checks (the Check commit earlier in
this series) run on their own copies, and a Principal given to a caller
must not share memory with the validator. This is a behaviour change:
Claims no longer aliases the parsed map.

Scope strings are split on SP only (RFC 6749 §3.3), not on any whitespace: a
tab or no-break space is part of a scope-token, so such a value fails closed.
RequireScopes and Principal.Scopes document that Entra app-only tokens carry
roles, not scp, so they never satisfy a scope requirement.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Fix Validate panicking when Close lands during a JWKS lookup (#510)

* Fix Validate panicking when Close lands during a JWKS lookup

Validate reads keys through jwkfetch.Cache.Lookup. The cache's controller
goroutines are bound to the validator's lifetime context, so Close stops
them. A Lookup that is in flight at that moment can get a nil resource
back from the stopped controller, and jwkfetch type-asserts it without a
check. The result is a panic in the library, in the caller's goroutine:
an interface conversion of a nil httprc.Resource. That is upstream
behaviour. A server that closes its validator on shutdown while requests
are still arriving can crash instead of answering them.

Add lookupJWKS and make lookupCandidates call it. It recovers the panic
and returns an error only when the validator is closed. A panic on a
validator that is still open is not this race and is raised again. The
error then takes the existing lookupCandidates path and reaches the
caller as CodeUnavailable with ReasonKeysUnavailable, the same as any
other lookup failure.

Cache.Refresh finishes with the same Lookup, so refreshOnce, which
runs on the request path for an unknown kid and for the staleness check,
has the same exposure. It and the two construction-time calls in init
now go through the same guard (refreshJWKS and lookupJWKS). Register is
not affected: it only adds the resource and never type-asserts.

TestValidateSurvivesCloseRace runs many callers against a validator and
closes it once calls are in flight, repeated over fresh validators. Each
call must return a principal or a CodeUnavailable error. It panics
without the guard.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Add Config.ProviderOnly for keys that are fetched elsewhere (#511)

* Add Config.ProviderOnly for keys that are fetched elsewhere

A Directory-fed workload trust gets its keys from the workloadtrust
adapter, which fetches and caches them with its own egress rules. A
Config with an Issuer and a KeyProvider still ran OIDC discovery against
the issuer, and fetched the JWKS it found, as a fallback for an embedded
issuer whose endpoint is not up yet. For Directory trusts that would
mean network requests to issuer URLs that came from Directory data, on
every rebuild.

ProviderOnly makes the KeyProvider the only key source. There is no
discovery and no JWKS, so the validator makes no requests and starts no
background refresh. A kid the provider does not offer is unknown_kid.
Issuer is still required and still verified.

It requires a KeyProvider and an Issuer, and these are checked before
the generic "issuer or jwks_url" rule so the error never suggests
setting jwks_url. JWKSURL, HTTPClient, CACertPath, AuthTokenFile,
AllowPrivateIP and MaxJWKSStaleness only configure fetching, so setting
one of them together with ProviderOnly is an error instead of being
silently ignored. ValidateConfig and NewValidator agree.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Add an immutable TrustSet that routes tokens by issuer (#514)

* Add an immutable TrustSet that routes tokens by issuer

A server that accepts tokens from several issuers has to pick the right
keys and policy for a token before verifying it. The only hint is the
token's unverified iss. The AI gateway and the connector gateway each do
this by hand today, with two different JWT parsers.

TrustSet does it once. A Trust is an ID, an ordinary Config (Issuer
required), an optional NotAfter and an opaque Tag. NewTrustSet validates
the trusts, builds one Validator per trust in parallel, and returns a set
with every trust that built plus a TrustError for each one that did not.
Verify reads the unverified iss as an exact string, picks the trust whose
Config.Issuer equals it, and verifies and accepts the token with that
trust's Validator alone. The validator checks that the verified iss equals
the issuer, so a wrong peek cannot pass. There is no fallthrough to another
trust.

The set is immutable. To change trusts, a caller builds a new set, swaps
it in and closes the old one. There is no Replace, no partitions and no
reuse: static issuers are built once at startup, and Directory-fed trusts
are ProviderOnly, so a rebuild does no I/O and the old set holds no
goroutines. The lifetime of the background JWKS refresh is the set, not
ctx, so a set built per poll does not register a child on a long-lived
context. ctx bounds construction only.

A trust whose ID or issuer (trailing slashes ignored) is shared with
another is refused, together with the other one, since there is no rule
for which is meant. That keeps https://idp and https://idp/ from both
routing. The cost is that whoever can add a trust with a colliding issuer
can deny service to another trust, so a feed must reject collisions when
trusts are registered.

Errors: a token that is not a JWT stays ReasonMalformed, so PossiblyOpaque
works. A JWT that no trust routes is ReasonUnknownIssuer and no key is
tried, so the caller can pass it to its other verifier. A trust past its
NotAfter is CodeUnavailable with ReasonTrustStale rather than an unknown
issuer, so its tokens are not passed on. A trust that failed to build is
absent from the set, so its tokens are ReasonUnknownIssuer; a caller for
whom that hand-off is unsafe treats the returned TrustErrors as fatal.

TrustRef now carries the trust's ID, Issuer and Tag. The caller's own
identifiers (for a Directory trust: authority, revision, profile) travel
in Tag. The Revision, Partition and Route fields, which nothing set, are
removed.

NewValidator gains an internal variant whose construction I/O is also
bounded by a second context. NewValidator itself does not change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Add TrustSet guards for sets built from external data (#515)

* Add TrustSet guards for sets built from external data

A Directory-fed workload set is rebuilt from Directory data every 30
seconds. Its keys are fetched elsewhere and passed in as ProviderOnly
trusts. Two things must hold for that set however the data looks: no
trust may capture an issuer that a human IdP set already serves, and no
trust may make the library do discovery or a JWKS fetch. NewTrustSet
checked neither, so a Directory trust for https://idp/ could shadow the
static https://idp, and one trust without ProviderOnly would turn a
rebuild into network requests to a URL that came from Directory data.

WithReservedIssuers refuses a trust whose issuer equals a reserved one,
ignoring trailing slashes and otherwise exact. Calls accumulate. The
workload set is given the gateway's human issuer list. WithProviderOnly
refuses every trust whose Config.ProviderOnly is false, as defence in
depth for the same set.

Both checks run in the validation phase, after validateTrust and before
the shared ID and issuer check. A refused trust therefore does not take
part in that check and cannot cause the refusal of another trust.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Reject authn issuers with a template placeholder (#516)

An issuer copied from a multi-tenant discovery document has a template
placeholder in it, such as https://login.microsoftonline.com/{tenantid}/v2.0.
No token carries that form in its iss. A trust or Config with one was
accepted, then matched nothing and failed discovery with a confusing error.

ValidateConfig now rejects an issuer that contains a brace, raw or
percent-encoded, so both Config and a TrustSet trust (refused by
NewTrustSet with a TrustError) refuse it. The error says to configure one
issuer per tenant. The check knows nothing about any provider, and the
shared validation/http checks are not changed.

Behaviour change: a configuration with such an issuer used to construct and
now fails validation. It could never verify a token.

Co-authored-by: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
jhrozek added a commit that referenced this pull request Nov 21, 2026
* Add Principal scopes, trust reference and Config.Algs

TrustSet, added later in this stack, serves tokens from several issuers.
Before it can do that, a caller needs three things from authn that the
single-issuer Validator does not yet expose.

Scopes: an endpoint decides access from the token's scopes, and a 403
must name the scopes it wanted. Principal.Scopes reads the scope claim,
falling back to scp. A non-string element yields nil rather than a
partial list. RequireScopes returns an insufficient_scope Error, which
Code.HTTPStatus maps to 403.

Trust reference: a caller must know which trust accepted a token, to log
it and to pick policy. Principal.Trust is a TrustRef, which is zero for a
plain Validator. TrustSet, later in this series, fills it in.

Config.Algs: lets an operator restrict signature algorithms to a subset
of the default allowlist, instead of accepting all of it. Entries outside
the allowlist, or repeated, are configuration errors.

Principal.Claims is now a deep copy. Checks (the Check commit earlier in
this series) run on their own copies, and a Principal given to a caller
must not share memory with the validator. This is a behaviour change:
Claims no longer aliases the parsed map.

Scope strings are split on SP only (RFC 6749 §3.3), not on any whitespace: a
tab or no-break space is part of a scope-token, so such a value fails closed.
RequireScopes and Principal.Scopes document that Entra app-only tokens carry
roles, not scp, so they never satisfy a scope requirement.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Fix Validate panicking when Close lands during a JWKS lookup (#510)

* Fix Validate panicking when Close lands during a JWKS lookup

Validate reads keys through jwkfetch.Cache.Lookup. The cache's controller
goroutines are bound to the validator's lifetime context, so Close stops
them. A Lookup that is in flight at that moment can get a nil resource
back from the stopped controller, and jwkfetch type-asserts it without a
check. The result is a panic in the library, in the caller's goroutine:
an interface conversion of a nil httprc.Resource. That is upstream
behaviour. A server that closes its validator on shutdown while requests
are still arriving can crash instead of answering them.

Add lookupJWKS and make lookupCandidates call it. It recovers the panic
and returns an error only when the validator is closed. A panic on a
validator that is still open is not this race and is raised again. The
error then takes the existing lookupCandidates path and reaches the
caller as CodeUnavailable with ReasonKeysUnavailable, the same as any
other lookup failure.

Cache.Refresh finishes with the same Lookup, so refreshOnce, which
runs on the request path for an unknown kid and for the staleness check,
has the same exposure. It and the two construction-time calls in init
now go through the same guard (refreshJWKS and lookupJWKS). Register is
not affected: it only adds the resource and never type-asserts.

TestValidateSurvivesCloseRace runs many callers against a validator and
closes it once calls are in flight, repeated over fresh validators. Each
call must return a principal or a CodeUnavailable error. It panics
without the guard.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Add Config.ProviderOnly for keys that are fetched elsewhere (#511)

* Add Config.ProviderOnly for keys that are fetched elsewhere

A Directory-fed workload trust gets its keys from the workloadtrust
adapter, which fetches and caches them with its own egress rules. A
Config with an Issuer and a KeyProvider still ran OIDC discovery against
the issuer, and fetched the JWKS it found, as a fallback for an embedded
issuer whose endpoint is not up yet. For Directory trusts that would
mean network requests to issuer URLs that came from Directory data, on
every rebuild.

ProviderOnly makes the KeyProvider the only key source. There is no
discovery and no JWKS, so the validator makes no requests and starts no
background refresh. A kid the provider does not offer is unknown_kid.
Issuer is still required and still verified.

It requires a KeyProvider and an Issuer, and these are checked before
the generic "issuer or jwks_url" rule so the error never suggests
setting jwks_url. JWKSURL, HTTPClient, CACertPath, AuthTokenFile,
AllowPrivateIP and MaxJWKSStaleness only configure fetching, so setting
one of them together with ProviderOnly is an error instead of being
silently ignored. ValidateConfig and NewValidator agree.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Add an immutable TrustSet that routes tokens by issuer (#514)

* Add an immutable TrustSet that routes tokens by issuer

A server that accepts tokens from several issuers has to pick the right
keys and policy for a token before verifying it. The only hint is the
token's unverified iss. The AI gateway and the connector gateway each do
this by hand today, with two different JWT parsers.

TrustSet does it once. A Trust is an ID, an ordinary Config (Issuer
required), an optional NotAfter and an opaque Tag. NewTrustSet validates
the trusts, builds one Validator per trust in parallel, and returns a set
with every trust that built plus a TrustError for each one that did not.
Verify reads the unverified iss as an exact string, picks the trust whose
Config.Issuer equals it, and verifies and accepts the token with that
trust's Validator alone. The validator checks that the verified iss equals
the issuer, so a wrong peek cannot pass. There is no fallthrough to another
trust.

The set is immutable. To change trusts, a caller builds a new set, swaps
it in and closes the old one. There is no Replace, no partitions and no
reuse: static issuers are built once at startup, and Directory-fed trusts
are ProviderOnly, so a rebuild does no I/O and the old set holds no
goroutines. The lifetime of the background JWKS refresh is the set, not
ctx, so a set built per poll does not register a child on a long-lived
context. ctx bounds construction only.

A trust whose ID or issuer (trailing slashes ignored) is shared with
another is refused, together with the other one, since there is no rule
for which is meant. That keeps https://idp and https://idp/ from both
routing. The cost is that whoever can add a trust with a colliding issuer
can deny service to another trust, so a feed must reject collisions when
trusts are registered.

Errors: a token that is not a JWT stays ReasonMalformed, so PossiblyOpaque
works. A JWT that no trust routes is ReasonUnknownIssuer and no key is
tried, so the caller can pass it to its other verifier. A trust past its
NotAfter is CodeUnavailable with ReasonTrustStale rather than an unknown
issuer, so its tokens are not passed on. A trust that failed to build is
absent from the set, so its tokens are ReasonUnknownIssuer; a caller for
whom that hand-off is unsafe treats the returned TrustErrors as fatal.

TrustRef now carries the trust's ID, Issuer and Tag. The caller's own
identifiers (for a Directory trust: authority, revision, profile) travel
in Tag. The Revision, Partition and Route fields, which nothing set, are
removed.

NewValidator gains an internal variant whose construction I/O is also
bounded by a second context. NewValidator itself does not change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Add TrustSet guards for sets built from external data (#515)

* Add TrustSet guards for sets built from external data

A Directory-fed workload set is rebuilt from Directory data every 30
seconds. Its keys are fetched elsewhere and passed in as ProviderOnly
trusts. Two things must hold for that set however the data looks: no
trust may capture an issuer that a human IdP set already serves, and no
trust may make the library do discovery or a JWKS fetch. NewTrustSet
checked neither, so a Directory trust for https://idp/ could shadow the
static https://idp, and one trust without ProviderOnly would turn a
rebuild into network requests to a URL that came from Directory data.

WithReservedIssuers refuses a trust whose issuer equals a reserved one,
ignoring trailing slashes and otherwise exact. Calls accumulate. The
workload set is given the gateway's human issuer list. WithProviderOnly
refuses every trust whose Config.ProviderOnly is false, as defence in
depth for the same set.

Both checks run in the validation phase, after validateTrust and before
the shared ID and issuer check. A refused trust therefore does not take
part in that check and cannot cause the refusal of another trust.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Reject authn issuers with a template placeholder (#516)

An issuer copied from a multi-tenant discovery document has a template
placeholder in it, such as https://login.microsoftonline.com/{tenantid}/v2.0.
No token carries that form in its iss. A trust or Config with one was
accepted, then matched nothing and failed discovery with a confusing error.

ValidateConfig now rejects an issuer that contains a brace, raw or
percent-encoded, so both Config and a TrustSet trust (refused by
NewTrustSet with a TrustError) refuse it. The error says to configure one
issuer per tenant. The check knows nothing about any provider, and the
shared validation/http checks are not changed.

Behaviour change: a configuration with such an issuer used to construct and
now fails validation. It could never verify a token.

Co-authored-by: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
jhrozek added a commit that referenced this pull request Nov 21, 2026
* Add Principal scopes, trust reference and Config.Algs

TrustSet, added later in this stack, serves tokens from several issuers.
Before it can do that, a caller needs three things from authn that the
single-issuer Validator does not yet expose.

Scopes: an endpoint decides access from the token's scopes, and a 403
must name the scopes it wanted. Principal.Scopes reads the scope claim,
falling back to scp. A non-string element yields nil rather than a
partial list. RequireScopes returns an insufficient_scope Error, which
Code.HTTPStatus maps to 403.

Trust reference: a caller must know which trust accepted a token, to log
it and to pick policy. Principal.Trust is a TrustRef, which is zero for a
plain Validator. TrustSet, later in this series, fills it in.

Config.Algs: lets an operator restrict signature algorithms to a subset
of the default allowlist, instead of accepting all of it. Entries outside
the allowlist, or repeated, are configuration errors.

Principal.Claims is now a deep copy. Checks (the Check commit earlier in
this series) run on their own copies, and a Principal given to a caller
must not share memory with the validator. This is a behaviour change:
Claims no longer aliases the parsed map.

Scope strings are split on SP only (RFC 6749 §3.3), not on any whitespace: a
tab or no-break space is part of a scope-token, so such a value fails closed.
RequireScopes and Principal.Scopes document that Entra app-only tokens carry
roles, not scp, so they never satisfy a scope requirement.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Fix Validate panicking when Close lands during a JWKS lookup (#510)

* Fix Validate panicking when Close lands during a JWKS lookup

Validate reads keys through jwkfetch.Cache.Lookup. The cache's controller
goroutines are bound to the validator's lifetime context, so Close stops
them. A Lookup that is in flight at that moment can get a nil resource
back from the stopped controller, and jwkfetch type-asserts it without a
check. The result is a panic in the library, in the caller's goroutine:
an interface conversion of a nil httprc.Resource. That is upstream
behaviour. A server that closes its validator on shutdown while requests
are still arriving can crash instead of answering them.

Add lookupJWKS and make lookupCandidates call it. It recovers the panic
and returns an error only when the validator is closed. A panic on a
validator that is still open is not this race and is raised again. The
error then takes the existing lookupCandidates path and reaches the
caller as CodeUnavailable with ReasonKeysUnavailable, the same as any
other lookup failure.

Cache.Refresh finishes with the same Lookup, so refreshOnce, which
runs on the request path for an unknown kid and for the staleness check,
has the same exposure. It and the two construction-time calls in init
now go through the same guard (refreshJWKS and lookupJWKS). Register is
not affected: it only adds the resource and never type-asserts.

TestValidateSurvivesCloseRace runs many callers against a validator and
closes it once calls are in flight, repeated over fresh validators. Each
call must return a principal or a CodeUnavailable error. It panics
without the guard.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Add Config.ProviderOnly for keys that are fetched elsewhere (#511)

* Add Config.ProviderOnly for keys that are fetched elsewhere

A Directory-fed workload trust gets its keys from the workloadtrust
adapter, which fetches and caches them with its own egress rules. A
Config with an Issuer and a KeyProvider still ran OIDC discovery against
the issuer, and fetched the JWKS it found, as a fallback for an embedded
issuer whose endpoint is not up yet. For Directory trusts that would
mean network requests to issuer URLs that came from Directory data, on
every rebuild.

ProviderOnly makes the KeyProvider the only key source. There is no
discovery and no JWKS, so the validator makes no requests and starts no
background refresh. A kid the provider does not offer is unknown_kid.
Issuer is still required and still verified.

It requires a KeyProvider and an Issuer, and these are checked before
the generic "issuer or jwks_url" rule so the error never suggests
setting jwks_url. JWKSURL, HTTPClient, CACertPath, AuthTokenFile,
AllowPrivateIP and MaxJWKSStaleness only configure fetching, so setting
one of them together with ProviderOnly is an error instead of being
silently ignored. ValidateConfig and NewValidator agree.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Add an immutable TrustSet that routes tokens by issuer (#514)

* Add an immutable TrustSet that routes tokens by issuer

A server that accepts tokens from several issuers has to pick the right
keys and policy for a token before verifying it. The only hint is the
token's unverified iss. The AI gateway and the connector gateway each do
this by hand today, with two different JWT parsers.

TrustSet does it once. A Trust is an ID, an ordinary Config (Issuer
required), an optional NotAfter and an opaque Tag. NewTrustSet validates
the trusts, builds one Validator per trust in parallel, and returns a set
with every trust that built plus a TrustError for each one that did not.
Verify reads the unverified iss as an exact string, picks the trust whose
Config.Issuer equals it, and verifies and accepts the token with that
trust's Validator alone. The validator checks that the verified iss equals
the issuer, so a wrong peek cannot pass. There is no fallthrough to another
trust.

The set is immutable. To change trusts, a caller builds a new set, swaps
it in and closes the old one. There is no Replace, no partitions and no
reuse: static issuers are built once at startup, and Directory-fed trusts
are ProviderOnly, so a rebuild does no I/O and the old set holds no
goroutines. The lifetime of the background JWKS refresh is the set, not
ctx, so a set built per poll does not register a child on a long-lived
context. ctx bounds construction only.

A trust whose ID or issuer (trailing slashes ignored) is shared with
another is refused, together with the other one, since there is no rule
for which is meant. That keeps https://idp and https://idp/ from both
routing. The cost is that whoever can add a trust with a colliding issuer
can deny service to another trust, so a feed must reject collisions when
trusts are registered.

Errors: a token that is not a JWT stays ReasonMalformed, so PossiblyOpaque
works. A JWT that no trust routes is ReasonUnknownIssuer and no key is
tried, so the caller can pass it to its other verifier. A trust past its
NotAfter is CodeUnavailable with ReasonTrustStale rather than an unknown
issuer, so its tokens are not passed on. A trust that failed to build is
absent from the set, so its tokens are ReasonUnknownIssuer; a caller for
whom that hand-off is unsafe treats the returned TrustErrors as fatal.

TrustRef now carries the trust's ID, Issuer and Tag. The caller's own
identifiers (for a Directory trust: authority, revision, profile) travel
in Tag. The Revision, Partition and Route fields, which nothing set, are
removed.

NewValidator gains an internal variant whose construction I/O is also
bounded by a second context. NewValidator itself does not change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Add TrustSet guards for sets built from external data (#515)

* Add TrustSet guards for sets built from external data

A Directory-fed workload set is rebuilt from Directory data every 30
seconds. Its keys are fetched elsewhere and passed in as ProviderOnly
trusts. Two things must hold for that set however the data looks: no
trust may capture an issuer that a human IdP set already serves, and no
trust may make the library do discovery or a JWKS fetch. NewTrustSet
checked neither, so a Directory trust for https://idp/ could shadow the
static https://idp, and one trust without ProviderOnly would turn a
rebuild into network requests to a URL that came from Directory data.

WithReservedIssuers refuses a trust whose issuer equals a reserved one,
ignoring trailing slashes and otherwise exact. Calls accumulate. The
workload set is given the gateway's human issuer list. WithProviderOnly
refuses every trust whose Config.ProviderOnly is false, as defence in
depth for the same set.

Both checks run in the validation phase, after validateTrust and before
the shared ID and issuer check. A refused trust therefore does not take
part in that check and cannot cause the refusal of another trust.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Reject authn issuers with a template placeholder (#516)

An issuer copied from a multi-tenant discovery document has a template
placeholder in it, such as https://login.microsoftonline.com/{tenantid}/v2.0.
No token carries that form in its iss. A trust or Config with one was
accepted, then matched nothing and failed discovery with a confusing error.

ValidateConfig now rejects an issuer that contains a brace, raw or
percent-encoded, so both Config and a TrustSet trust (refused by
NewTrustSet with a TrustError) refuse it. The error says to configure one
issuer per tenant. The check knows nothing about any provider, and the
shared validation/http checks are not changed.

Behaviour change: a configuration with such an issuer used to construct and
now fails validation. It could never verify a token.

Co-authored-by: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
jhrozek added a commit that referenced this pull request Nov 21, 2026
… stack (#508)

* Add MaxRemainingLifetime to authn acceptance

Add Config.MaxRemainingLifetime: a token whose exp is more than this far
after the validation instant is refused with ReasonLifetime. It is a
ceiling on how long a token stays usable, which matters because a bearer
token cannot be revoked before exp.

The existing MaxTokenLifetime caps exp-iat, but it needs iat, and some
issuers omit it. This bound is measured from the validator's own clock,
so it works without iat.

The check runs in accept, after audience, typ and cnf. It uses the same
instant verify used for its temporal checks, so expiry and the ceiling
are measured from one clock reading. accept now takes that instant
instead of ignoring it.

TestAcceptMaxRemainingLifetime covers a token within the ceiling, above
it, and with the ceiling disabled.

Co-Authored-By: Claude Haiku 5.5 <[email protected]>

* Add Check extension point to authn acceptance

Some rules are specific to one deployment and cannot be built into the
library. The Kubernetes projected service-account rules are an example:
the token must name a namespace and a bound pod that match the workload.
Add a Check interface so a caller can add such a rule over the verified
claims without changing the package.

Config.Checks holds the rules. They run in accept, after every built-in
check, in order, and all must pass. A check can only add restrictions.

Each check gets its own deep copy of the claims, so a check that changes
its map cannot change Principal.Claims or what the next check sees. A
panic is recovered and counts as a rejection. A check error is never
wrapped or returned, so a buggy or hostile check cannot leak detail to a
client. The failure is CodeInvalidToken with ReasonCheck and a fixed
detail that names the check index, the profile and the trust ID.

RejectIDTokens is a ready-made check that refuses at_hash and c_hash,
which only OpenID Connect ID tokens carry. It is weak alone, because an
authorization-code ID token may carry neither, so it is a helper and not
a default.

The profile and trust ID in that detail are empty for a Validator.

k8s_checks_test.go expresses the projected service-account rules as
Checks. It is the first real consumer and shows the intended use.

Co-Authored-By: Claude Haiku 5.5 <[email protected]>

* Add Principal scopes, trust reference and Config.Algs (#509)

* Add Principal scopes, trust reference and Config.Algs

TrustSet, added later in this stack, serves tokens from several issuers.
Before it can do that, a caller needs three things from authn that the
single-issuer Validator does not yet expose.

Scopes: an endpoint decides access from the token's scopes, and a 403
must name the scopes it wanted. Principal.Scopes reads the scope claim,
falling back to scp. A non-string element yields nil rather than a
partial list. RequireScopes returns an insufficient_scope Error, which
Code.HTTPStatus maps to 403.

Trust reference: a caller must know which trust accepted a token, to log
it and to pick policy. Principal.Trust is a TrustRef, which is zero for a
plain Validator. TrustSet, later in this series, fills it in.

Config.Algs: lets an operator restrict signature algorithms to a subset
of the default allowlist, instead of accepting all of it. Entries outside
the allowlist, or repeated, are configuration errors.

Principal.Claims is now a deep copy. Checks (the Check commit earlier in
this series) run on their own copies, and a Principal given to a caller
must not share memory with the validator. This is a behaviour change:
Claims no longer aliases the parsed map.

Scope strings are split on SP only (RFC 6749 §3.3), not on any whitespace: a
tab or no-break space is part of a scope-token, so such a value fails closed.
RequireScopes and Principal.Scopes document that Entra app-only tokens carry
roles, not scp, so they never satisfy a scope requirement.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Fix Validate panicking when Close lands during a JWKS lookup (#510)

* Fix Validate panicking when Close lands during a JWKS lookup

Validate reads keys through jwkfetch.Cache.Lookup. The cache's controller
goroutines are bound to the validator's lifetime context, so Close stops
them. A Lookup that is in flight at that moment can get a nil resource
back from the stopped controller, and jwkfetch type-asserts it without a
check. The result is a panic in the library, in the caller's goroutine:
an interface conversion of a nil httprc.Resource. That is upstream
behaviour. A server that closes its validator on shutdown while requests
are still arriving can crash instead of answering them.

Add lookupJWKS and make lookupCandidates call it. It recovers the panic
and returns an error only when the validator is closed. A panic on a
validator that is still open is not this race and is raised again. The
error then takes the existing lookupCandidates path and reaches the
caller as CodeUnavailable with ReasonKeysUnavailable, the same as any
other lookup failure.

Cache.Refresh finishes with the same Lookup, so refreshOnce, which
runs on the request path for an unknown kid and for the staleness check,
has the same exposure. It and the two construction-time calls in init
now go through the same guard (refreshJWKS and lookupJWKS). Register is
not affected: it only adds the resource and never type-asserts.

TestValidateSurvivesCloseRace runs many callers against a validator and
closes it once calls are in flight, repeated over fresh validators. Each
call must return a principal or a CodeUnavailable error. It panics
without the guard.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Add Config.ProviderOnly for keys that are fetched elsewhere (#511)

* Add Config.ProviderOnly for keys that are fetched elsewhere

A Directory-fed workload trust gets its keys from the workloadtrust
adapter, which fetches and caches them with its own egress rules. A
Config with an Issuer and a KeyProvider still ran OIDC discovery against
the issuer, and fetched the JWKS it found, as a fallback for an embedded
issuer whose endpoint is not up yet. For Directory trusts that would
mean network requests to issuer URLs that came from Directory data, on
every rebuild.

ProviderOnly makes the KeyProvider the only key source. There is no
discovery and no JWKS, so the validator makes no requests and starts no
background refresh. A kid the provider does not offer is unknown_kid.
Issuer is still required and still verified.

It requires a KeyProvider and an Issuer, and these are checked before
the generic "issuer or jwks_url" rule so the error never suggests
setting jwks_url. JWKSURL, HTTPClient, CACertPath, AuthTokenFile,
AllowPrivateIP and MaxJWKSStaleness only configure fetching, so setting
one of them together with ProviderOnly is an error instead of being
silently ignored. ValidateConfig and NewValidator agree.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Add an immutable TrustSet that routes tokens by issuer (#514)

* Add an immutable TrustSet that routes tokens by issuer

A server that accepts tokens from several issuers has to pick the right
keys and policy for a token before verifying it. The only hint is the
token's unverified iss. The AI gateway and the connector gateway each do
this by hand today, with two different JWT parsers.

TrustSet does it once. A Trust is an ID, an ordinary Config (Issuer
required), an optional NotAfter and an opaque Tag. NewTrustSet validates
the trusts, builds one Validator per trust in parallel, and returns a set
with every trust that built plus a TrustError for each one that did not.
Verify reads the unverified iss as an exact string, picks the trust whose
Config.Issuer equals it, and verifies and accepts the token with that
trust's Validator alone. The validator checks that the verified iss equals
the issuer, so a wrong peek cannot pass. There is no fallthrough to another
trust.

The set is immutable. To change trusts, a caller builds a new set, swaps
it in and closes the old one. There is no Replace, no partitions and no
reuse: static issuers are built once at startup, and Directory-fed trusts
are ProviderOnly, so a rebuild does no I/O and the old set holds no
goroutines. The lifetime of the background JWKS refresh is the set, not
ctx, so a set built per poll does not register a child on a long-lived
context. ctx bounds construction only.

A trust whose ID or issuer (trailing slashes ignored) is shared with
another is refused, together with the other one, since there is no rule
for which is meant. That keeps https://idp and https://idp/ from both
routing. The cost is that whoever can add a trust with a colliding issuer
can deny service to another trust, so a feed must reject collisions when
trusts are registered.

Errors: a token that is not a JWT stays ReasonMalformed, so PossiblyOpaque
works. A JWT that no trust routes is ReasonUnknownIssuer and no key is
tried, so the caller can pass it to its other verifier. A trust past its
NotAfter is CodeUnavailable with ReasonTrustStale rather than an unknown
issuer, so its tokens are not passed on. A trust that failed to build is
absent from the set, so its tokens are ReasonUnknownIssuer; a caller for
whom that hand-off is unsafe treats the returned TrustErrors as fatal.

TrustRef now carries the trust's ID, Issuer and Tag. The caller's own
identifiers (for a Directory trust: authority, revision, profile) travel
in Tag. The Revision, Partition and Route fields, which nothing set, are
removed.

NewValidator gains an internal variant whose construction I/O is also
bounded by a second context. NewValidator itself does not change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Add TrustSet guards for sets built from external data (#515)

* Add TrustSet guards for sets built from external data

A Directory-fed workload set is rebuilt from Directory data every 30
seconds. Its keys are fetched elsewhere and passed in as ProviderOnly
trusts. Two things must hold for that set however the data looks: no
trust may capture an issuer that a human IdP set already serves, and no
trust may make the library do discovery or a JWKS fetch. NewTrustSet
checked neither, so a Directory trust for https://idp/ could shadow the
static https://idp, and one trust without ProviderOnly would turn a
rebuild into network requests to a URL that came from Directory data.

WithReservedIssuers refuses a trust whose issuer equals a reserved one,
ignoring trailing slashes and otherwise exact. Calls accumulate. The
workload set is given the gateway's human issuer list. WithProviderOnly
refuses every trust whose Config.ProviderOnly is false, as defence in
depth for the same set.

Both checks run in the validation phase, after validateTrust and before
the shared ID and issuer check. A refused trust therefore does not take
part in that check and cannot cause the refusal of another trust.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Reject authn issuers with a template placeholder (#516)

An issuer copied from a multi-tenant discovery document has a template
placeholder in it, such as https://login.microsoftonline.com/{tenantid}/v2.0.
No token carries that form in its iss. A trust or Config with one was
accepted, then matched nothing and failed discovery with a confusing error.

ValidateConfig now rejects an issuer that contains a brace, raw or
percent-encoded, so both Config and a TrustSet trust (refused by
NewTrustSet with a TrustError) refuse it. The error says to configure one
issuer per tenant. The check knows nothing about any provider, and the
shared validation/http checks are not changed.

Behaviour change: a configuration with such an issuer used to construct and
now fails validation. It could never verify a token.

Co-authored-by: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>

* Name the trust and wrap the error in authn Check failures

acceptPolicy carried profile and trustID fields to label Check failures,
but nothing in the stack set them, so every failure read
(profile "", trust ""). Drop profile, which only meant something with
the per-trust bindings this series no longer has, and have NewTrustSet
set trustID on each trust's validator. A plain Validator leaves it
empty and the label omits it.

The check's own error was discarded, so an operator only saw
"check 2 rejected the token" and had to guess which rule fired. Wrap it
with %w in the *Error detail instead. That detail is already the
log-only channel and never reaches a response. The Check doc now says
so. A panic value is still not recorded.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Haiku 5.5 <[email protected]>
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.

2 participants