Skip to content

Add reason codes to redemption refusals - #7193

Merged
jhrozek merged 6 commits into
mainfrom
as2-redemption-hardening-2-reason-codes
Nov 19, 2026
Merged

jhrozek merged 6 commits into
mainfrom
as2-redemption-hardening-2-reason-codes

Conversation

@jhrozek

@jhrozek jhrozek commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary

A client could not tell apart the refusals of a JWT-bearer or ID-JAG redemption: nearly every one was invalid_grant with free text. Mecatl's broker retries a reasonless invalid_grant once with a new ID-JAG, which is wasted work for refusals a new ID-JAG cannot fix. A JWKS outage was also indistinguishable from a bad assertion. This gives each refusal a reason at the start of error_description, so a client can act on it without parsing prose.

  • error_description now starts with a reason and matches ^[a-z_]+(: .*)?$: the reason, optionally followed by : and a fixed hint. It never contains a claim value. The handlers build the error as a literal (redemptionRefusal) because fosite's WithHint puts its own default text first.
  • An assertion that fails a validation rule is invalid_grant with invalid_assertion: <hint>, on both the plain JWT-bearer and the ID-JAG grant. invalid_assertion is only ever used with invalid_grant.
  • On the ID-JAG grant, a valid ID-JAG that this server's allowlist does not permit is access_denied with subject_unknown or resource_denied, because a re-issued ID-JAG will not help.
  • If the issuer's signing keys cannot be obtained, both grants answer 503 temporarily_unavailable with issuer_unavailable. The assertion was never judged, so the same request may succeed once the issuer is reachable. A request that ends while the keys are being fetched, and a validator called with no default audiences, are 500 server_error: neither is the issuer's fault or the assertion's.
  • issueBoundedAccessToken builds its "bound lifetime elapsed" error lazily, so successful issuance no longer captures a stack trace for an error it never returns.
  • docs/arch/17-token-exchange-delegation.md gets a "Redemption refusal reasons" section with the table of refusals per grant.

Refs #7030 ("Authorization server: reason codes in error_description for ID-JAG redemption refusals")

Type of change

  • Bug fix
  • New feature
  • Refactoring (no behavior change)
  • Dependency update
  • Documentation
  • Other (describe): Client-visible error contract for JWT-bearer and ID-JAG redemption refusals

Test plan

  • Unit tests (task test)
  • E2E tests (task test-e2e)
  • Linting (task lint-fix)
  • Manual testing (describe below)

Unit tests ran with the race detector on the two packages this PR touches, pkg/authserver and pkg/authserver/server/tokenexchange, and golangci-lint reports no issues on both. The in-process delegated-agent flow test in pkg/authserver checks the new descriptions over HTTP, through the real token endpoint.

Changes

File Change
pkg/authserver/server/tokenexchange/redemption_refusal.go New: reason constants, redemptionRefusal, invalidAssertion, issuerUnavailable, and the mapping from a validation failure to its refusal
pkg/authserver/server/tokenexchange/jwt_bearer_handler.go Validation refusals carry invalid_assertion; checkSubjectBinding returns sentinels that each handler maps to its own response
pkg/authserver/server/tokenexchange/id_jag_handler.go subject_unknown / resource_denied for a valid ID-JAG the allowlist or client audiences refuse; bad resource claim is invalid_assertion
pkg/authserver/server/tokenexchange/multi_issuer_validator.go Marks "no usable key set" failures so the handlers can answer 503; a cancelled request is not counted as an unreachable issuer
pkg/authserver/server/tokenexchange/handler.go Lazy "bound lifetime elapsed" error
docs/arch/17-token-exchange-delegation.md Redemption refusal reasons section
*_test.go Tests for each refusal, the description grammar, and the 503 key-availability cases

Does this introduce a user-facing change?

Yes. A client of the JWT-bearer or ID-JAG grant sees different error_description values, and in some cases a different error code or status.

  • Before: every refusal from assertion validation was 400 invalid_grant with fosite's default text followed by the hint.
  • After: 400 invalid_grant with invalid_assertion: <the same hint>. The error code is unchanged.

ID-JAG grant only:

Case Before After
Subject not in subject_bindings 400 invalid_grant 400 access_denied, subject_unknown
Listed subject asks for a resource outside its allowed_resources 400 invalid_target 400 access_denied, resource_denied
Resource outside the redeeming client's audiences 400 invalid_target, text naming the resource 400 access_denied, resource_denied
Single resource claim that is not a valid URI, no resource parameter in the request 400 invalid_target, text that could quote the claim 400 invalid_grant, invalid_assertion: The ID-JAG assertion resource claim is not a valid resource URI.

Both grants:

Case Before After
Issuer's signing keys cannot be fetched 400 invalid_grant 503 temporarily_unavailable, issuer_unavailable
Request ends while the keys are being fetched, or no default audiences are configured 400 invalid_grant 500 server_error, generic text

A client that retries a reasonless invalid_grant with a new ID-JAG, as Mecatl's broker does, stops retrying invalid_assertion and the two access_denied refusals. issuer_unavailable is the retryable one. The 503 has no Retry-After header.

docs/arch/17-token-exchange-delegation.md describes each case.

Special notes for reviewers

  • The plain RFC 7523 grant keeps its codes for the two subject_bindings refusals (invalid_grant with fosite's text for an unlisted subject, a bare invalid_target for a resource that is not allowed). It is outside the ID-JAG profile, so only the ID-JAG handler maps them to access_denied. checkSubjectBinding returns two sentinels and each handler maps them.
  • Accepted trade-off on the 503. It only covers failures before a usable key set exists. When keys are in hand and the token's kid is not among them, even after the refresh, the refusal stays invalid_assertion. A freshly rotated kid that arrives while the issuer's key endpoint is down therefore gets invalid_assertion until the keys are reachable. There is a comment at the site in verifyExternalSignature.
  • The RFC 8693 token-exchange path is unchanged. It still reports an unreachable issuer as invalid_request.
  • The 503 logs its cause once per backoff window, not per request. A failed key fetch for an issuer is logged at Error once per 30 seconds per issuer, naming the issuer, and so is a fetched key set the server cannot use. Each refused request logs at Debug with no cause text, and the response carries only issuer_unavailable. The cause stays wrapped for errors.Is.
  • The lazy "elapsed" error in handler.go is a separate small change in a function this PR touches anyway. The error is now built only on the path that returns it.

A client could not tell apart the refusals of a JWT-bearer or ID-JAG
redemption: every one was invalid_grant with free text. Mecatl's broker
retries a reasonless invalid_grant once with a new ID-JAG, which is
wrong for refusals a new ID-JAG cannot fix. This implements the grammar
and the existing refusals of "Authorization server: reason codes in
error_description for ID-JAG redemption refusals" (#7030).

redemptionRefusal builds a literal error (like exactReason) so the
reason leads; fosite's WithHint would put its default text first.
error_description now matches ^[a-z_]+(: .*)?$ and carries no claim
value. invalid_assertion is used only with invalid_grant.

Client-visible changes:
- Plain JWT-bearer and ID-JAG clients: every invalid_grant from
  assertion validation now has the error_description
  "invalid_assertion: <existing hint>" instead of fosite's text. The
  error code is unchanged.
- ID-JAG only: a subject missing from subject_bindings is now 400
  access_denied "subject_unknown", and a listed subject asking for a
  resource outside its allowed_resources is 400 access_denied
  "resource_denied" (was invalid_grant and invalid_target). The plain
  RFC 7523 grant keeps its codes for both.
- ID-JAG only: a resource outside the redeeming client's audiences is
  now 400 access_denied "resource_denied" (was invalid_target "The
  client is not permitted to request resource ...").
- ID-JAG only: a single resource claim that is not a valid resource URI,
  with no resource parameter in the request, is now invalid_grant
  "invalid_assertion: The ID-JAG assertion resource claim is not a valid
  resource URI." (was invalid_target with text that could quote the
  claim value).
- A client that retries a reasonless invalid_grant with a new ID-JAG,
  as Mecatl's broker does, stops retrying these refusals.

Refs #7030

Co-authored-by: Mecatl <[email protected]>
A JWKS outage made ID-JAG and JWT-bearer redemptions fail with
invalid_grant/invalid_assertion, which tells a client its assertion is
bad when it was never judged. Wrap failures that happen before a usable
key set exists (fetch, cache lookup, conversion, empty or oversized set)
in an unexported sentinel and have both handlers answer 503
temporarily_unavailable with the bare description issuer_unavailable.
An unknown kid with keys in hand, even after the refresh, stays
invalid_assertion. The RFC 8693 path is unchanged.

The 503 carries the cause, which names the issuer, in its debug field,
so the log line says which issuer failed; clients still see only
issuer_unavailable. A request that ends while the keys are being
fetched, and a validator called with no default audiences, are 500
server_error instead: neither is the issuer's fault nor the assertion's.

Also build the "bound lifetime elapsed" error lazily in
issueBoundedAccessToken so successful issuance no longer captures a
stack trace for an error it never returns.

Co-authored-by: Mecatl <[email protected]>
@jhrozek
jhrozek requested a review from ChrisJBurns as a code owner November 19, 2026 10:56
@github-actions github-actions Bot added the size/L Large PR: 600-999 lines changed label Nov 19, 2026

@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.

Right layer and mostly right behaviour; one error-mapping gap to settle before approving.

Design: The reason codes are produced where the refusal is decided. Each token-endpoint handler builds its own error. The validator marks "no key set was available" with a sentinel, so a JWKS outage is told apart from a bad assertion. The shared subject-binding check returns sentinels that each handler maps itself, which keeps the plain JWT-bearer grant's codes while ID-JAG gets the draft's. No flags, CRDs or persisted state change. The wire change is error_description on every refusal, plus the status and code moves the PR body lists.

Findings:

  1. pkg/authserver/server/tokenexchange/id_jag_handler.go:206-213: errors.Is(err, server.ErrInvalidTarget) turns every invalid_target from ValidateIDJAGClientAudience into access_denied / resource_denied. That includes the case where the client itself sent a resource parameter its audiences don't allow (idJAGResource returns the form value whenever the parameter is present). Before this PR that client got RFC 8707 invalid_target. Afterwards it gets the code meant for "valid ID-JAG, refused by policy", and a client that treats access_denied as permanent will give up on a request it could fix. The comment says the hint "may come from the assertion", but the same path is reached with a client-supplied value. Suggested fix: remap only when the resource was defaulted from the assertion claim, and keep invalid_target when it came from the form. Or state in the docs that the remap is deliberate for both sources.
  2. docs/arch/17-token-exchange-delegation.md (the 503 paragraph): ensureRegistered failures (discovery failure, issuer-URL mismatch) also return issuer_unavailable / 503, and those are permanent operator misconfigurations. A client that retries on 503 will retry them indefinitely. Say so in the docs, and make sure the 5xx path logs the underlying cause at ERROR. The cause is only in the debug field, which is not sent to clients, so the server log is where operators will see it.

Smaller notes, no action needed: access_denied is not a registered token-endpoint error code in RFC 6749 §5.2, but the issue picked it deliberately, so just confirm the broker tolerates it. The issueBoundedAccessToken closure change in handler.go is unrelated to the PR and could go in a separate PR.

🤖 Reviewed with Claude Code

A refused assertion from an issuer whose keys are down was logged at Error
on every request, and its cause was copied into the debug field each time.
An unauthenticated caller can trigger that on every request, so an outage
could flood the log. The validator now logs the cause once per backoff
window at Error, naming the issuer. The per-request 503 logs at Debug and
carries no cause text, and the cause stays wrapped for errors.Is.

Also document the access_denied remap for ID-JAG resource refusals, and
fix the unknown-kid test, which signed with a key that was in the JWKS.

Co-authored-by: Mecatl <[email protected]>

@jhrozek jhrozek left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for the close read. I pushed 22f2494 with the changes.

On the remap: I kept access_denied for both sources. The subject-binding check already does the same for a client-supplied resource, so changing only this site would give two codes for the same refusal, and draft -06 section 4.4.1 points to access_denied in either case. I reworded the comment to say that, and the docs now say the remap covers a resource from the request and one from the assertion's claim.

On the 503s: the docs now cover discovery failures and a mismatched discovery document or jwks_uri. The cause is logged once per 30-second backoff window at Error, naming the issuer. Each refused request logs at Debug with no cause text, so an outage can't flood the log from unauthenticated callers. The cause stays wrapped for errors.Is.

I also fixed the unknown-kid test, which signed with a key that was in the served JWKS, and corrected the server_error sentence in the docs table.

@github-actions github-actions Bot added size/L Large PR: 600-999 lines changed and removed size/L Large PR: 600-999 lines changed labels Nov 19, 2026
@codecov

codecov Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.66667% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 81.56%. Comparing base (01b1d76) to head (55cc340).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...hserver/server/tokenexchange/jwt_bearer_handler.go 96.15% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #7193      +/-   ##
==========================================
- Coverage   81.60%   81.56%   -0.05%     
==========================================
  Files         896      897       +1     
  Lines       91441    91482      +41     
==========================================
- Hits        74619    74613       -6     
- Misses      16817    16864      +47     
  Partials        5        5              

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

issueBoundedAccessToken takes the elapsed error as a callback so that a
successful issuance does not capture a stack trace for an error it never
returns. Nothing pinned that, so a later change could quietly build the
error on every path again. Add a table test for the three cases: no
expiry, a future expiry, and a past expiry. Also reflow the doc comment.

Co-authored-by: Mecatl <[email protected]>
@jhrozek

jhrozek commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

Pushed abdff49. It adds a test for the lazy bound-elapsed error and reflows the doc comment on issueBoundedAccessToken.

On the closure change in 4756d52: it isn't separable from this PR. The regression comes from e45d20f. That commit changed the elapsed parameter from a hint string to a built error, which made the stack capture run on every successful issuance. On main the error is only built on the elapsed path. So the lazy change is a fix for a regression this PR introduced, and I'd keep it here. The new test pins that the error is only built when the bound has elapsed.

Nothing else changed in behaviour.

@github-actions github-actions Bot added size/XL Extra large PR: 1000+ lines changed and removed size/L Large PR: 600-999 lines changed labels Nov 19, 2026

@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.

Re-review of abdff49: one earlier finding is withdrawn, one is only partly fixed, and there is one new finding.

  1. id_jag_handler.go invalid_target remap: withdrawn. The subject-binding check already returns access_denied for a client-supplied resource, so remapping only the assertion-defaulted case would give two codes for one refusal. The comment and docs now say the remap covers both sources.
  2. Permanent 503s and ERROR logging: partly resolved. The docs now say discovery and jwks_uri failures are permanent, and the cause is logged at Error once per 30s backoff window per issuer (multi_issuer_validator.go:927-933). That log lives only in ensureRegistered, so it covers only part of what returns the 503 (new finding 3).

New findings:

  1. multi_issuer_validator.go:1041-1062 (lookupJWKS) with :739-751: every lookupJWKS error becomes errIssuerKeysUnavailable and so a 503 issuer_unavailable. After ensureRegistered succeeds, jwksCache.Lookup can fail, bridgeJWKSet can fail or drop every key as unsupported ("JWKS contains no keys"), or the set can exceed maxJWKSKeys. None of these log at any level now, because this push removed the cause from the Debug field. Once fetched is true, ensureRegistered returns early and never logs again. Scenario: an issuer rotates to a key set bridgeJWKSet strips (for example sub-2048-bit RSA). Every redemption returns 503 indefinitely and operators see nothing. Before this push the cause was at least in the debug field. Suggested fix: log these branches at Error, rate-limited per issuer (reusing the fetchFailedAt window works), or keep the cause on the refusal's debug field.
  2. Missing test for the new logging contract: nothing asserts that the Error log fires once per window and names the issuer, or that replayed errors inside the window stay quiet. TestLogAccessError only covers the Debug downgrade. A capturing slog handler with two failures in one window and one after it would cover this, and would have caught finding 3.

Design: unchanged. This push only moves where the cause is logged, from per refused request to the validator's fetch attempt.

🤖 Reviewed with Claude Code

jhrozek and others added 2 commits November 19, 2026 16:11
A fetched key set that the server cannot use (a cache lookup failure, only
unsupported keys, an empty set, or too many keys) refused assertions with
503 issuer_unavailable and logged nothing. The pre-fetch failure was logged
once per backoff window, but the post-fetch one never was, so an issuer that
rotated to keys the server could not use returned 503 with no operator
signal. Log it at Error once per window per issuer, from a separate timestamp
guarded by the issuer's mutex. Client disconnects are skipped, since they are
not an issuer fault. Document the behaviour in the token-exchange architecture
page.

Co-authored-by: Mecatl <[email protected]>
Nothing asserted the once-per-window Error line for either a pre-fetch or a
post-fetch key-set failure, so a regression could silently drop it or let it
repeat. Add a test for both, and serve a valid empty key set in the fixture:
a null key list failed to parse before the post-fetch path ran. Also cover the
two binding-refusal mappers passing unrecognised errors through unchanged.

Co-authored-by: Mecatl <[email protected]>
@jhrozek

jhrozek commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

Pushed 2188e29 and 55cc340 for the post-fetch finding.

The key sets that lookupJWKS can't use after a successful fetch now log once per 30-second window per issuer, at Error, with the message "issuer signing keys unusable". They have their own timestamp under the issuer mutex, separate from the pre-fetch retry gate, so the two lines don't interfere. Client disconnects are skipped, since they aren't an issuer fault. The docs list both cases.

The test covers the once-per-window contract for both the pre-fetch and post-fetch paths. I also found that the empty-key-set fixture was serving a null key list, which failed to parse before the post-fetch code ran, so that case never reached the new path. It now serves an empty list. The binding-refusal mappers have a passthrough test for unrecognised errors.

One coverage gap is left: the "exactly one JOSE signature" check in jwt_bearer_handler.go can't be reached, because go-jose's compact parser always yields exactly one signature. That check was already on main, so I've left it uncovered rather than write a test that can't fail.

@github-actions github-actions Bot added size/XL Extra large PR: 1000+ lines changed and removed size/XL Extra large PR: 1000+ lines changed labels Nov 19, 2026

@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.

Re-review of 55cc340: approve. All earlier findings are resolved or withdrawn, and the new commits add no significant finding.

  1. invalid_target remap: withdrawn (earlier).
  2. Permanent 503s and ERROR logging: resolved. The pre-fetch failure logs at Error once per backoff window, and the docs now list the post-fetch cases as well.
  3. Silent post-fetch 503s: resolved. lookupJWKS now logs through logKeySetUnusable for every usableJWKS failure (cache lookup error, bridgeJWKSet error, empty set, more than maxJWKSKeys), rate-limited per issuer on its own timestamp under issuerConfig.mu. Its only callers are the two sites in verifyExternalSignature, so both the redemption and RFC 8693 paths are covered.
  4. Missing test for the logging contract: resolved. TestIssuerKeysUnavailableLogsOncePerWindow checks that one Error line naming the issuer is emitted per window and that a failure after the window logs again, for both log paths.

Design: unchanged. The push only adds a second rate-limited Error log for failures after the key fetch, so operators can see why an issuer returns issuer_unavailable.

Optional, no action needed: the tests don't cover the cancelled-context skip or a non-empty-but-unusable key set. A different failure cause within the same 30s window is not logged separately.

🤖 Reviewed with Claude Code

@jhrozek
jhrozek merged commit 2d7e1d7 into main Nov 19, 2026
47 checks passed
@jhrozek
jhrozek deleted the as2-redemption-hardening-2-reason-codes branch November 19, 2026 15:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/XL Extra large PR: 1000+ lines changed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants