Skip to content

Let embedders refuse refresh grants on dead upstreams - #6902

Merged
tgrunnagle merged 4 commits into
mainfrom
enchanted-run
Oct 22, 2026
Merged

tgrunnagle merged 4 commits into
mainfrom
enchanted-run

Conversation

@tgrunnagle

@tgrunnagle tgrunnagle commented Oct 21, 2026 •

Copy link
Copy Markdown
Collaborator

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's refresh_token grant 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 new tsid, 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:

  • Refresh-grant validation seam. A new authserver.Config.RefreshGrantHandlers field takes extra fosite.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 the refresh_token grant, 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. Returning fosite.ErrInvalidGrant answers HTTP 400 invalid_grant, which sends the client to a full authorization. The server only calls the handler to validate the grant. See the reviewer notes.
  • Typed upstream refresh rejection. Before this PR, callers could not tell an IdP's invalid_grant from a network failure. formatOAuth2Error now wraps a new exported sentinel, upstream.ErrGrantRejected, when oautherr.IsRejectedRefreshGrant (the classifier the client-side token source already uses) reports an invalid_grant rejection. A 5xx or 429, a response without a status, a network error or any other error code does not wrap it. The refresher and upstreamtoken.ErrRefreshFailed carry the sentinel through, so errors.Is finds it on errors from GetValidTokens and on the per-provider errors from GetAllUpstreamCredentials.
  • Lost-race handling in the refresher. A rotating IdP also answers invalid_grant to 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. docs/arch/11-auth-server-storage.md gains 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

  • Bug fix
  • New feature
  • Refactoring (no behavior change)
  • Dependency update
  • Documentation
  • Other (describe):

Test plan

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

New tests:

  • TestIntegration_RefreshGrantHandlers: with two registered handlers, a refusal from the second with fosite.ErrInvalidGrant produces 400 invalid_grant and a plain error produces 500; neither issues tokens or rotates the refresh token. Handlers see the stored session's tsid and do not run on authorization_code grants.
  • TestRefreshGrantValidators_* (gate checks): the validator runs only on the refresh_token grant, never skips client authentication, never delegates PopulateTokenEndpointResponse, and is not registered as a revocation, introspection or authorize handler.
  • TestUpstreamRefreshRejection_ReachesServiceCallers: an IdP invalid_grant is reachable with errors.Is(err, upstream.ErrGrantRejected) from GetValidTokens and GetAllUpstreamCredentials. A 5xx or network failure is not.
  • TestFormatOAuth2Error_GrantRejected: the sentinel is wrapped for invalid_grant except on 5xx, 429 or a missing response.
  • TestRefreshGrantValidators_GrantTypes / TestRefreshGrantValidators_HandlerChain: the grant-type gate, handler ordering, first-refusal-wins, and ErrUnknownRequest as 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

File Change
pkg/authserver/config.go Add RefreshGrantHandlers and reject nil entries in Validate
pkg/authserver/refresh_grant_handlers.go New refreshGrantOnlyHandler wrapper and factory helper
pkg/authserver/server_impl.go Register embedder handlers after the built-in factories
pkg/authserver/upstream/oauth2.go Add the ErrGrantRejected sentinel, classified by oautherr.IsRejectedRefreshGrant
pkg/authserver/refresher.go Re-read storage on invalid_grant to resolve a lost cross-replica race
pkg/auth/upstreamtoken/{types,service,errors}.go GetAllUpstreamCredentials returns failed map[string]error. Update the docs
pkg/auth/upstreamtoken/mocks/mock_token_reader.go Regenerate the mock
pkg/auth/token.go, pkg/vmcp/server/server.go Adapt callers to the map
docs/arch/11-auth-server-storage.md Document the refresh rejections and the seam

Does 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.RefreshGrantHandlers option and the upstream.ErrGrantRejected sentinel, and must adapt to one interface change (see below).

Special notes for reviewers

  • Breaking Go API change. upstreamtoken.TokenReader.GetAllUpstreamCredentials now returns failed map[string]error instead of failed []string. The map is keyed by provider name, and each value is that provider's refresh error. This lets errors.Is reach upstream.ErrGrantRejected for each provider. I chose this over adding a second, near-duplicate method. Migration:

    • Callers that need only the provider names can use slices.Sorted(maps.Keys(failed)).
    • Implementers of TokenReader must change the signature and regenerate their mocks.
  • The seam only validates. The wrapper delegates only CanHandleTokenEndpointRequest and HandleTokenEndpointRequest. It never calls the embedder handler's PopulateTokenEndpointResponse or CanSkipClientAuth, for two reasons:

    • By the time the response is populated, the refresh token has already been rotated. An error at that point would leave the client with no tokens and a dead refresh token.
    • Client authentication must always apply.

    A fosite RFC 6749 error keeps its own status and code; a plain Go error is answered as HTTP 500 with fosite's generic error code.

  • 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, so ErrGrantRejected can 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. ErrGrantRejected is also wrapped on authorization code exchange failures, because both paths share formatOAuth2Error. Only the refresh path is relevant to this change.

🤖 Generated with Claude Code

tgrunnagle and others added 2 commits October 21, 2026 11:34
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]>
@github-actions github-actions Bot added the size/L Large PR: 600-999 lines changed label Oct 21, 2026

@tgrunnagle tgrunnagle left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

Comment thread pkg/authserver/upstream/oauth2.go Resolved
Comment thread pkg/authserver/refresher_test.go Resolved
Comment thread pkg/authserver/config.go Resolved
Comment thread pkg/authserver/refresher.go Resolved
Comment thread pkg/authserver/upstream/oauth2.go Resolved
@codecov

codecov Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 79.78%. Comparing base (0ea7c4f) to head (2e31000).
⚠️ Report is 5 commits behind head on main.

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

tgrunnagle and others added 2 commits October 21, 2026 12:17
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]>
@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 Oct 21, 2026
@tgrunnagle
tgrunnagle marked this pull request as ready for review October 21, 2026 20:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/L Large PR: 600-999 lines changed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

authserver: let embedders validate refresh-token grants, and type upstream refresh rejections

2 participants