Repository navigation
Let embedders refuse refresh grants on dead upstreams - #6902
Conversation
The embedded auth server's refresh_token grant keeps the token session, so a client whose upstream credential is dead gets a new access token that the bearer validator rejects again, and a client that only ever refreshes loops. Embedders had no way to refuse that grant, and could not tell an IdP's invalid_grant from a transient upstream failure. Implements items 1 and 2 of #6901 (the default guard is a follow-up): - Add Config.RefreshGrantHandlers: fosite token endpoint handlers that run only on the refresh_token grant, after the built-in refresh handler and before any tokens are issued or the refresh token rotates - Wrap a new upstream.ErrInvalidGrant when the IdP answers a token request with invalid_grant and a 4xx status - Return per-provider errors from GetAllUpstreamCredentials (failed is now map[string]error) so errors.Is reaches the sentinel there too Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Never delegate the response phase to embedder handlers: it runs after the refresh token is rotated, so an error there would strand the client, and it would let an embedder rewrite the issued response - On an upstream invalid_grant, re-read the row and return it if another replica already rotated it, so a lost cross-replica race is not reported as a dead credential; document the remaining window - Document that non-OAuth handler errors answer 500, and that the code exchange also wraps ErrInvalidGrant Co-Authored-By: Claude Opus 5.5 <[email protected]>
tgrunnagle
left a comment
There was a problem hiding this comment.
Multi-Agent Consensus Review
Agents consulted: security, concurrency/error-handling, api/architecture, tests/docs, general/review-friendliness
Consensus Summary
| # | Finding | Consensus | Severity | Action |
|---|---|---|---|---|
| 1 | Multiple RefreshGrantHandlers collapse to the first (fosite dedups by type) |
9/10 | HIGH | Fix |
| 2 | isInvalidGrant duplicates oautherr.IsRejectedRefreshGrant and differs on edge cases |
8/10 | MEDIUM | Fix |
| 3 | "same refresh token stored" case doesn't reach the equal-token branch | 9/10 | MEDIUM | Fix |
| 4 | RefreshGrantHandlers doc contract overstated or incomplete |
8/10 | MEDIUM | Fix |
| 5 | "session loaded first" assertion is vacuous | 8/10 | MEDIUM | Fix |
| 6 | No test for plain error -> 500 or for 2+ handlers | 7/10 | LOW | Fix |
| 7 | rotatedElsewhere silent on read errors; differs from rowChanged |
8/10 | LOW | Fix |
| 8 | Sentinel placement and naming | 7/10 | LOW | Discuss |
| 9 | Refusals only visible at Debug | 7/10 | LOW | Discuss |
Overall
This adds a validate-only seam (Config.RefreshGrantHandlers), a typed upstream.ErrInvalidGrant, lost-race handling in the refresher, and a TokenReader signature change that carries per-provider errors. The approach is sound. The wrapper runs after the built-in refresh handler loads the session and before tokens are issued or the refresh token rotates. Client authentication is never relaxed, and the response phase is never delegated. I checked that ordering against fosite v0.49.0.
One finding should be fixed before merge. fosite deduplicates token-endpoint handlers by concrete type, so with more than one entry in RefreshGrantHandlers only the first is registered, and the rest are dropped with no error or log (finding 1). The remaining findings are polish: reuse of the existing oautherr predicate, two tests that don't pin what they claim, doc-contract gaps, and observability of refusals.
Documentation
pkg/authserver/config.go: the RefreshGrantHandlers comment says the issued response "cannot be altered", but handlers receive the live AccessRequester (finding 4). docs/arch/11-auth-server-storage.md could also note that only the request phase is delegated and that non-fosite errors answer 500.
Generated with Claude Code
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #6902 +/- ##
=======================================
Coverage 79.78% 79.78%
=======================================
Files 827 828 +1
Lines 84547 84607 +60
=======================================
+ Hits 67454 67506 +52
- Misses 17088 17096 +8
Partials 5 5 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
fosite drops a token endpoint handler whose concrete type is already registered, so wrapping each handler separately kept only the first. Addresses #6902 review comments: - HIGH pkg/authserver/refresh_grant_handlers.go (4340715142): run all handlers from one registered validator, in order, first refusal wins - MEDIUM pkg/authserver/config.go (4340715167): document the read-only requester, ErrUnknownRequest as no objection, concurrency, the lost-race caveat and the plain-error 500; reject typed-nil handlers - MEDIUM pkg/authserver/refresh_grant_handlers_test.go (4340715177): assert the handler sees the stored session's tsid - LOW pkg/authserver/refresh_grant_handlers_test.go (4340715184): test two handlers and the plain-error 500 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reuse oautherr.IsRejectedRefreshGrant instead of a second predicate that disagreed on 200, 429 and status-less responses, and rename the sentinel so it no longer reads like fosite.ErrInvalidGrant. Addresses #6902 review comments: - MEDIUM pkg/authserver/upstream/oauth2.go (4340715152): classify with oautherr.IsRejectedRefreshGrant - MEDIUM pkg/authserver/refresher_test.go (4340715156): cover the unchanged-token, nil-row and read-error branches - LOW pkg/authserver/refresher.go (4340715199): log unexpected re-read errors and explain the refresh-token comparison - LOW pkg/authserver/upstream/oauth2.go (4340715203): rename upstream.ErrInvalidGrant to upstream.ErrGrantRejected Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
When the bearer validator finds that a session's upstream credential cannot be refreshed, it answers 401
invalid_token. Most OAuth clients respond by redeeming their refresh token. The embedded auth server'srefresh_tokengrant succeeds and keeps the same token session (tsid), so the new access token points at the same dead upstream credential and gets the same 401. A client that never falls back to full authorization loops with no delay. Only a fresh authorization, which creates a newtsid, fixes the session, and the client starts one only after the refresh grant fails.This PR covers proposal items 1 and 2 from the issue. Embedders get what they need to refuse such a refresh grant themselves:
authserver.Config.RefreshGrantHandlersfield takes extrafosite.TokenEndpointHandlers, registered after the built-in refresh handler. All handlers are registered as one validator (fosite drops a second handler of the same concrete type) that runs them in order, only on therefresh_tokengrant, after fosite has authenticated the client and loaded and checked the refresh session, and before any tokens are issued or the refresh token is rotated. Returningfosite.ErrInvalidGrantanswers HTTP 400invalid_grant, which sends the client to a full authorization. The server only calls the handler to validate the grant. See the reviewer notes.invalid_grantfrom a network failure.formatOAuth2Errornow wraps a new exported sentinel,upstream.ErrGrantRejected, whenoautherr.IsRejectedRefreshGrant(the classifier the client-side token source already uses) reports aninvalid_grantrejection. A 5xx or 429, a response without a status, a network error or any other error code does not wrap it. The refresher andupstreamtoken.ErrRefreshFailedcarry the sentinel through, soerrors.Isfinds it on errors fromGetValidTokensand on the per-provider errors fromGetAllUpstreamCredentials.invalid_grantto the replica that loses a cross-replica refresh race. On that rejection the refresher re-reads storage. If the stored row now holds a different, unexpired token, the refresher returns that row, so the rejection is not reported as a dead credential.docs/arch/11-auth-server-storage.mdgains a section on upstream refresh rejections and the refresh-grant seam.Item 3 (a built-in default guard that refuses the grant and revokes the refresh token) is left for a follow-up.
Part of #6901
Type of change
Test plan
task test)task test-e2e)task lint-fix)New tests:
TestIntegration_RefreshGrantHandlers: with two registered handlers, a refusal from the second withfosite.ErrInvalidGrantproduces 400invalid_grantand a plain error produces 500; neither issues tokens or rotates the refresh token. Handlers see the stored session'stsidand do not run onauthorization_codegrants.TestRefreshGrantValidators_*(gate checks): the validator runs only on therefresh_tokengrant, never skips client authentication, never delegatesPopulateTokenEndpointResponse, and is not registered as a revocation, introspection or authorize handler.TestUpstreamRefreshRejection_ReachesServiceCallers: an IdPinvalid_grantis reachable witherrors.Is(err, upstream.ErrGrantRejected)fromGetValidTokensandGetAllUpstreamCredentials. A 5xx or network failure is not.TestFormatOAuth2Error_GrantRejected: the sentinel is wrapped forinvalid_grantexcept on 5xx, 429 or a missing response.TestRefreshGrantValidators_GrantTypes/TestRefreshGrantValidators_HandlerChain: the grant-type gate, handler ordering, first-refusal-wins, andErrUnknownRequestas no objection.TestUpstreamTokenRefresher_InvalidGrantLostRace: after a rejection, the refresher returns a row another replica already rotated, and keeps the rejection when the stored row is unchanged, expired or gone.Changes
pkg/authserver/config.goRefreshGrantHandlersand reject nil entries inValidatepkg/authserver/refresh_grant_handlers.gorefreshGrantOnlyHandlerwrapper and factory helperpkg/authserver/server_impl.gopkg/authserver/upstream/oauth2.goErrGrantRejectedsentinel, classified byoautherr.IsRejectedRefreshGrantpkg/authserver/refresher.goinvalid_grantto resolve a lost cross-replica racepkg/auth/upstreamtoken/{types,service,errors}.goGetAllUpstreamCredentialsreturnsfailed map[string]error. Update the docspkg/auth/upstreamtoken/mocks/mock_token_reader.gopkg/auth/token.go,pkg/vmcp/server/server.godocs/arch/11-auth-server-storage.mdDoes this introduce a user-facing change?
No for users and operators. No handler is registered by default, so token endpoint responses, status codes and refresh behavior stay the same. Upstream refresh error messages read as before. Go embedders get the new
Config.RefreshGrantHandlersoption and theupstream.ErrGrantRejectedsentinel, and must adapt to one interface change (see below).Special notes for reviewers
Breaking Go API change.
upstreamtoken.TokenReader.GetAllUpstreamCredentialsnow returnsfailed map[string]errorinstead offailed []string. The map is keyed by provider name, and each value is that provider's refresh error. This letserrors.Isreachupstream.ErrGrantRejectedfor each provider. I chose this over adding a second, near-duplicate method. Migration:slices.Sorted(maps.Keys(failed)).TokenReadermust change the signature and regenerate their mocks.The seam only validates. The wrapper delegates only
CanHandleTokenEndpointRequestandHandleTokenEndpointRequest. It never calls the embedder handler'sPopulateTokenEndpointResponseorCanSkipClientAuth, for two reasons:A fosite RFC 6749 error keeps its own status and code; a plain Go error is answered as HTTP 500 with fosite's generic
errorcode.Remaining cross-replica window. On an upstream
invalid_grant, the refresher re-reads storage and returns a row another replica already rotated. If that replica's write has not landed yet, the rejection still surfaces, soErrGrantRejectedcan occasionally reflect a lost race rather than a dead credential. The deferred default guard (item 3) must account for this, for example by tolerating or retrying a single rejection before revoking.Sentinel scope.
ErrGrantRejectedis also wrapped on authorization code exchange failures, because both paths shareformatOAuth2Error. Only the refresh path is relevant to this change.🤖 Generated with Claude Code