Repository navigation
Add reason codes to redemption refusals - #7193
Conversation
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]>
rdimitrov
left a comment
There was a problem hiding this comment.
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:
pkg/authserver/server/tokenexchange/id_jag_handler.go:206-213:errors.Is(err, server.ErrInvalidTarget)turns everyinvalid_targetfromValidateIDJAGClientAudienceintoaccess_denied/resource_denied. That includes the case where the client itself sent aresourceparameter its audiences don't allow (idJAGResourcereturns the form value whenever the parameter is present). Before this PR that client got RFC 8707invalid_target. Afterwards it gets the code meant for "valid ID-JAG, refused by policy", and a client that treatsaccess_deniedas 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 keepinvalid_targetwhen it came from the form. Or state in the docs that the remap is deliberate for both sources.docs/arch/17-token-exchange-delegation.md(the 503 paragraph):ensureRegisteredfailures (discovery failure, issuer-URL mismatch) also returnissuer_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
left a comment
There was a problem hiding this comment.
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.
Codecov Report❌ Patch coverage is
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. 🚀 New features to boost your workflow:
|
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]>
|
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. |
rdimitrov
left a comment
There was a problem hiding this comment.
Re-review of abdff49: one earlier finding is withdrawn, one is only partly fixed, and there is one new finding.
id_jag_handler.goinvalid_targetremap: withdrawn. The subject-binding check already returnsaccess_deniedfor 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.- Permanent 503s and ERROR logging: partly resolved. The docs now say discovery and
jwks_urifailures 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 inensureRegistered, so it covers only part of what returns the 503 (new finding 3).
New findings:
multi_issuer_validator.go:1041-1062(lookupJWKS) with:739-751: everylookupJWKSerror becomeserrIssuerKeysUnavailableand so a 503issuer_unavailable. AfterensureRegisteredsucceeds,jwksCache.Lookupcan fail,bridgeJWKSetcan fail or drop every key as unsupported ("JWKS contains no keys"), or the set can exceedmaxJWKSKeys. None of these log at any level now, because this push removed the cause from the Debug field. Oncefetchedis true,ensureRegisteredreturns early and never logs again. Scenario: an issuer rotates to a key setbridgeJWKSetstrips (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 thefetchFailedAtwindow works), or keep the cause on the refusal's debug field.- 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.
TestLogAccessErroronly covers the Debug downgrade. A capturingsloghandler 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
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]>
|
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. |
rdimitrov
left a comment
There was a problem hiding this comment.
Re-review of 55cc340: approve. All earlier findings are resolved or withdrawn, and the new commits add no significant finding.
invalid_targetremap: withdrawn (earlier).- 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.
- Silent post-fetch 503s: resolved.
lookupJWKSnow logs throughlogKeySetUnusablefor everyusableJWKSfailure (cache lookup error,bridgeJWKSeterror, empty set, more thanmaxJWKSKeys), rate-limited per issuer on its own timestamp underissuerConfig.mu. Its only callers are the two sites inverifyExternalSignature, so both the redemption and RFC 8693 paths are covered. - Missing test for the logging contract: resolved.
TestIssuerKeysUnavailableLogsOncePerWindowchecks 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
Summary
A client could not tell apart the refusals of a JWT-bearer or ID-JAG redemption: nearly every one was
invalid_grantwith free text. Mecatl's broker retries a reasonlessinvalid_grantonce 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 oferror_description, so a client can act on it without parsing prose.error_descriptionnow 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'sWithHintputs its own default text first.invalid_grantwithinvalid_assertion: <hint>, on both the plain JWT-bearer and the ID-JAG grant.invalid_assertionis only ever used withinvalid_grant.access_deniedwithsubject_unknownorresource_denied, because a re-issued ID-JAG will not help.temporarily_unavailablewithissuer_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 500server_error: neither is the issuer's fault or the assertion's.issueBoundedAccessTokenbuilds 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.mdgets 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
Test plan
task test)task test-e2e)task lint-fix)Unit tests ran with the race detector on the two packages this PR touches,
pkg/authserverandpkg/authserver/server/tokenexchange, andgolangci-lintreports no issues on both. The in-process delegated-agent flow test inpkg/authserverchecks the new descriptions over HTTP, through the real token endpoint.Changes
pkg/authserver/server/tokenexchange/redemption_refusal.goredemptionRefusal,invalidAssertion,issuerUnavailable, and the mapping from a validation failure to its refusalpkg/authserver/server/tokenexchange/jwt_bearer_handler.goinvalid_assertion;checkSubjectBindingreturns sentinels that each handler maps to its own responsepkg/authserver/server/tokenexchange/id_jag_handler.gosubject_unknown/resource_deniedfor a valid ID-JAG the allowlist or client audiences refuse; bad resource claim isinvalid_assertionpkg/authserver/server/tokenexchange/multi_issuer_validator.gopkg/authserver/server/tokenexchange/handler.godocs/arch/17-token-exchange-delegation.md*_test.goDoes this introduce a user-facing change?
Yes. A client of the JWT-bearer or ID-JAG grant sees different
error_descriptionvalues, and in some cases a different error code or status.400 invalid_grantwith fosite's default text followed by the hint.400 invalid_grantwithinvalid_assertion: <the same hint>. The error code is unchanged.ID-JAG grant only:
subject_bindingsinvalid_grantaccess_denied,subject_unknownallowed_resourcesinvalid_targetaccess_denied,resource_deniedinvalid_target, text naming the resourceaccess_denied,resource_deniedresourceclaim that is not a valid URI, noresourceparameter in the requestinvalid_target, text that could quote the claiminvalid_grant,invalid_assertion: The ID-JAG assertion resource claim is not a valid resource URI.Both grants:
invalid_granttemporarily_unavailable,issuer_unavailableinvalid_grantserver_error, generic textA client that retries a reasonless
invalid_grantwith a new ID-JAG, as Mecatl's broker does, stops retryinginvalid_assertionand the twoaccess_deniedrefusals.issuer_unavailableis the retryable one. The 503 has noRetry-Afterheader.docs/arch/17-token-exchange-delegation.mddescribes each case.Special notes for reviewers
subject_bindingsrefusals (invalid_grantwith fosite's text for an unlisted subject, a bareinvalid_targetfor a resource that is not allowed). It is outside the ID-JAG profile, so only the ID-JAG handler maps them toaccess_denied.checkSubjectBindingreturns two sentinels and each handler maps them.kidis not among them, even after the refresh, the refusal staysinvalid_assertion. A freshly rotatedkidthat arrives while the issuer's key endpoint is down therefore getsinvalid_assertionuntil the keys are reachable. There is a comment at the site inverifyExternalSignature.invalid_request.issuer_unavailable. The cause stays wrapped forerrors.Is.handler.gois a separate small change in a function this PR touches anyway. The error is now built only on the path that returns it.