Skip to content

Stop re-sending upstream refresh tokens the IdP rejected - #7307

Merged
jhrozek merged 16 commits into
mainfrom
upstream-dead-refresh-token
Nov 25, 2026
Merged

jhrozek merged 16 commits into
mainfrom
upstream-dead-refresh-token

Conversation

@jhrozek

@jhrozek jhrozek commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary

When the upstream identity provider rejects a refresh with invalid_grant, the auth server leaves the row as it is: an expired access token and a dead refresh token. Until something replaces or removes that row, every request that reads it refreshes again. That means another IdP call, another invalid_grant, more WARN lines, and another 401. A client that keeps retrying its bearer token costs one IdP call per request. With session-keyed storage this lasts until the refresh grant guard drops the session. With user-keyed storage (opt-in, see "User-keyed upstream storage behind the embedder option" (#7263)) it lasts until the user signs in again.

This PR gives each auth server process a short memory of refresh tokens its IdP rejected, so it does not send the same rejected refresh token again.

  • Memory. A small LRU in pkg/authserver (10,000 entries, 5 minutes, constants rather than configuration). Only a definitive upstream.ErrGrantRejected is remembered: invalid_grant with a non-5xx, non-429 status, after the refresher found no row rotated by another replica. Transient failures, other OAuth error codes, network and storage errors are retried as before.
  • Key. The storage row ID, a counter that the server bumps after UpdateUpstreamClientCredentials swaps a client registration, and a SHA-256 digest of the row's refresh token, access token and access token expiry. An entry stops matching as soon as:
    • another replica or a new sign-in stores different tokens in the row;
    • another replica refreshes without rotating the refresh token;
    • the upstream's client registration is replaced. This matters because RFC 6749 §5.2 lets an IdP answer invalid_grant for a refresh token issued to another client.
  • Value. Only the OAuth error code and HTTP status are kept, never the IdP's error text or the tokens. Each hit builds a new error that still matches upstream.ErrGrantRejected and still carries an *oauth2.RetrieveError with that code and status. Its message says the rejection was remembered and the provider was not called.
  • No storage writes. The memory never writes to storage, so a replica that wins a refresh race after this one's rejection always lands its write.
  • Refresh grant guard. It refreshes through the same refresher but skips the memory: before it can delete a session's upstream rows, it always asks the IdP. A rejection it receives is still recorded, so the bearer path benefits. The guard runs on refresh grants, not on every request, so this costs little.
  • Guard recheck. Before deleting, the recheck now refuses only if the row is entirely unchanged: same refresh token, access token, ID token and expiry. Before, it compared the refresh token only. A non-rotating refresh by another replica during the recheck therefore makes the guard grant instead of deleting the winner's fresh row.

Relates to "Re-authorization walks the full upstream chain instead of evaluating existing credentials" (#6831).

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 count requests to a fake IdP and use a fake clock. They cover:

  • a remembered rejection makes no second IdP call;
  • the row is not written;
  • a successor refresh token reaches the IdP;
  • transient and non-invalid_grant failures are not remembered;
  • expiry after the TTL;
  • separate rows;
  • both refresher paths;
  • the service and the guard;
  • a client registration switch, including one that happens while an IdP call is in flight;
  • a non-rotating refresh elsewhere, with a new access token or the same access token with a new expiry;
  • the guard asking the IdP despite a remembered rejection, picking up an IdP-side fix, and recording a rejection it receives;
  • the guard granting when the row changes during its recheck;
  • a server built through New bumping the refresher's counter on a client registration switch.

Each test for a review fix was checked to fail with that fix removed.

Changes

File Change
pkg/authserver/rejected_refreshes.go The memory: key, record, lookup building a new error, add.
pkg/authserver/refresher.go redeem consults and fills the memory around refreshAndStore; client registration counter.
pkg/authserver/server_impl.go Keeps the concrete refresher; bumps its counter after a successful client registration switch.
pkg/authserver/refresh_grant_guard.go Skips the memory when it refreshes; recheck confirms only an unchanged row.
pkg/authserver/config.go RefreshGrantHandlers doc: handlers can see a remembered rejection.
docs/arch/11-auth-server-storage.md, docs/middleware.md Remembered rejections, trade-offs, guard behaviour, recovery after a 401.

Does this introduce a user-facing change?

Yes. Responses keep the same shape, but timing and IdP traffic change:

  • Before: after the IdP rejected an upstream refresh token, every bearer request for that session called the IdP again and got a 401. After: the same process answers from memory for up to 5 minutes. The request still gets the same 401, with no IdP call. Another replica, a new sign-in, a client registration switch, or a successful refresh grant ends this early.
  • Before: if the IdP's invalid_grant was about account or policy state, such as a disabled account, a lockout, or a Conditional Access block or missing consent on Microsoft Entra, bearer requests recovered on the first request after an administrator fixed it. After: a client that answers the 401 with a refresh grant recovers just as soon, because the guard asks the IdP again. A client that only retries its bearer token can keep getting 401 on the same replica for up to 5 minutes.
  • Logs: each bearer request in this state still logs the same three WARN lines. The two from the token service now say the rejection was remembered and the provider was not called. A DEBUG line marks each memory hit.

Embedders see no exported API changes. A rejection can now come from the memory without an IdP call; only the built-in refresh grant guard skips the memory, so embedder RefreshGrantHandlers that call the shared refresher can see a remembered rejection. It is a new error value each time, still matches upstream.ErrGrantRejected, and still unwraps to an *oauth2.RetrieveError with the original error code and HTTP status, but without the IdP's error description. Tests that count IdP calls after a rejection will see fewer calls: a second refresh of the same rejected token within 5 minutes in the same process makes no call. Client registration switches must go through UpdateUpstreamClientCredentials for the memory to forget earlier rejections. Calling a provider's UpdateClientCredentials directly bypasses it.

Special notes for reviewers

  • Why not clear the dead refresh token in storage instead?
    • A replica that lost a refresh race re-reads immediately, so its clear can land before the winning replica's write. The winner's compare-and-swap then fails and its freshly rotated refresh token is lost. Today that race costs one request; clearing would make it cost the session.
    • Clearing would also change what the guard sees (a row with no refresh token instead of a rejected one), and with it the guard's outcome.
  • How the guard skips the memory. An unexported context marker that redeem checks; a parameter would have meant changing storage.UpstreamTokenRefresher, which embedders wrap. A guard call that joins an in-flight bearer refresh of the same row (singleflight) gets that call's result, which may come from the memory. A remembered answer is recognisable inside the package, so the guard then retries once; if that answer is remembered too, it grants and deletes nothing. The guard only drops a session after a rejection the IdP just gave. The singleflight key stays shared, so the same refresh token is never redeemed twice at once.
  • Guard and client disconnects. If the client disconnects during the guard's 500ms recheck, the guard grants and deletes nothing, and each such attempt costs an IdP call. That is how main behaves too; it is tracked separately in "Refresh grant guard skips its recheck when the client disconnects" (Refresh grant guard skips its recheck when the client disconnects #7312).
  • TTL. 5 minutes, as a constant. It only bounds how long a client that never sends a refresh grant keeps getting 401 after an IdP-side fix; compliant clients recover through the guard. One IdP call per row per 5 minutes still absorbs a retry storm.
  • Guard recheck versus rotatedElsewhere. The guard's recheck and rotatedElsewhere deliberately treat a same-refresh-token row differently. rotatedElsewhere decides what the refresher returns, and a row still holding the rejected refresh token is just as dead to it. The guard decides whether to delete the session's rows. In ToolHive, any change to a session's row under the same refresh token comes from a successful IdP refresh, so the guard treats it as live. Granting there costs at most one more round before the guard refuses.
  • One counter for all providers. Switches are rare, and a switch costs the other providers one IdP call each. The counter is bumped after the provider swaps, and redeem reads it before calling the IdP, so a rejection from the old client is never filed under the new value.
  • GitHub saves nothing here. It answers a dead refresh token with HTTP 200 and error=bad_refresh_token, which is not ErrGrantRejected, so nothing is remembered for it.
  • Possible follow-up. The two token-service WARN lines per bearer request in this state could move to DEBUG for remembered rejections. They are left as they are here.
  • Conflict. "Serialize upstream refresh across replicas" (Serialize upstream refresh across replicas #7031) also edits refresher.go. The change here is kept in redeem and the new file so a rebase stays small.

jhrozek and others added 10 commits November 25, 2026 14:21
A row holding an expired access token and a refresh token the IdP has
already rejected costs one IdP call on every request that reads it.
Add a small bounded LRU that can remember such a rejection, keyed on the
storage row ID and a SHA-256 digest of the refresh token, with a short
TTL checked on lookup against an injectable clock.

The nil and zero values miss on lookup and ignore adds, so tests that
build refreshers as struct literals are unaffected. Nothing uses it yet.

Co-authored-by: Mecatl <[email protected]>
When the IdP rejects a refresh with invalid_grant and no other process
has rotated the row, the refresher left the row alone and every later
read refreshed again, called the IdP again and got the same rejection.

Route both refresh paths in RefreshAndStore through a helper that
returns the remembered rejection for a row and refresh token it has seen
rejected, and remembers new ErrGrantRejected results. Transient and
non-invalid_grant failures are never remembered. The row is not written,
so a replica that wins a later refresh race still lands its write, and a
successor refresh token no longer matches the entry.

The refresh grant guard refreshes through the same refresher, so it can
now act on a rejection up to 10 minutes old.

Co-authored-by: Mecatl <[email protected]>
Describe the per-process memory of rejected refreshes in the auth server
storage architecture doc, with its trade-offs: an admin-fixable
invalid_grant stays failed for up to the TTL, entries lost to eviction
cost one more IdP call, and the per-request WARN lines remain. Record
the same effect on the refresh grant guard in the doc and in the guard's
comment.

Co-authored-by: Mecatl <[email protected]>
Correct the architecture doc: both per-request WARN lines come from the
token service, and it is the refresh failures behind the lines, not the
lines, that the memory answers. Name the rejectedRefreshes constants in
the constructor's panic comment, document add, and tighten the tests:
check the scrubbed RetrieveError after the TTL expiry instead of in a
duplicate subtest, add a network failure case that must not be
remembered, and make the memory type's small tests table-driven.

Co-authored-by: Mecatl <[email protected]>
A remembered refresh rejection could outlive its cause while the
refresh token string stayed the same: the IdP may answer invalid_grant
for a token issued to another client (RFC 6749 section 5.2), and another
replica's non-rotating refresh keeps the refresh token but stores a new
access token. The entry also kept the full provider error and handed the
same instance to every caller.

Key each entry on a client registration generation, which the server
bumps after a provider has swapped its client, and on a length-prefixed
digest of the refresh and access tokens. Keep only the OAuth error code
and HTTP status, and build a new error on every hit whose message says
the rejection was remembered. A rejection with no RetrieveError to take
those from is not remembered.

Co-authored-by: Mecatl <[email protected]>
Describe what a remembered upstream refresh rejection is keyed on, what
ends it, what it retains, and how its error reads in logs. Correct the
claims that an invalid_grant token never works again and that a retry of
the refresh grant repeats an upstream call, note the three WARN lines a
bearer request logs, and tell operators that a cleared IdP-side block can
take up to 10 minutes to show on the same replica.

Co-authored-by: Mecatl <[email protected]>
With remembered upstream rejections, the refresh grant guard can be
answered with a rejection up to ten minutes old without an IdP call.
Its recheck then confirmed the rejection whenever the stored row still
held the same refresh token. If another replica refreshed successfully
during the recheck without rotating the refresh token (for example once
an administrator cleared an IdP-side block), the row had the same
refresh token and a new access token, and the guard deleted the
winner's fresh row and sent the client to sign in again.

The recheck now confirms only when the row still holds both the
rejected refresh token and the guard's snapshot access token. A changed
access token means the IdP accepted a refresh, so the guard grants.
This deliberately differs from rotatedElsewhere, which decides what the
refresher returns rather than whether to delete the session's rows.

Co-authored-by: Mecatl <[email protected]>
The in-flight client switch test blocked on bare channel operations,
so a regression would hang until the global test timeout. Every wait
and send there, including the fake IdP's, now fails after five seconds.

UpdateUpstreamClientCredentials bumped the refresher's client
generation through a type assertion on the interface field, which
would silently stop working if the refresher were wrapped. The server
now also holds the concrete refresher in its own field and bumps
through that. The interface field stays, so a server without upstreams
still has a true nil refresher.

The architecture doc now notes that a retry reaching another replica
calls the IdP straight away, because the memory is per process.

Co-authored-by: Mecatl <[email protected]>
The guard's recheck confirmed a rejection when the stored row still
held the rejected refresh token and access token. A non-rotating IdP
can answer a refresh with the same access token string and a new
expiry, so the recheck still confirmed and dropped the winner's fresh
row. The recheck now takes the guard's snapshot row and confirms only
when rowChanged reports no change (refresh token, access token, ID
token, expiry). Every write to a session's row is a successful IdP
refresh, so any change means the IdP accepted the refresh token.

The remembered-rejection key had the same gap. It now also covers the
access token expiry, so a non-rotating refresh elsewhere ends the match
even when the access token string is unchanged.

The guard test no longer races a timer against the recheck read: a
refresher wrapper stores the winner row after the memory answers and
before the guard re-reads, and covers both a new access token and the
same access token with a new expiry. Comments and architecture docs
are corrected to match.

Co-authored-by: Mecatl <[email protected]>
Rewrap an over-long line in the refresh grant guard's doc comment and
drop the parameters of a test helper that every caller passed the same
values to.

Co-authored-by: Mecatl <[email protected]>
@jhrozek
jhrozek requested a review from ChrisJBurns as a code owner November 25, 2026 15:23
@github-actions github-actions Bot added the size/XL Extra large PR: 1000+ lines changed label Nov 25, 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.

One finding to settle before merge: the new rejection memory lets the refresh-grant guard delete a session on a stale answer.

Design: Remembering invalid_grant inside upstreamTokenRefresher is the right place. All callers of RefreshAndStore (token service, refresh-grant guard, chain re-evaluation) go through it, so all of them stop hammering the IdP. Keying on the row plus a digest of its token state means a refresh won by another replica changes the key and misses the memory, which is correct. No flag, API, CRD or persisted-state change on upgrade. The cost is a 10-minute window in which an IdP-side fix is not noticed.

  1. pkg/authserver/refresh_grant_guard.go checkRow (~266-284): the guard's refresh now goes through the memory. Scenario: the IdP rejects with invalid_grant because of a policy block (e.g. Conditional Access) and a bearer request fills the memory at t=0. An admin clears the block at t=1m. The client does a refresh grant at t=5m. The guard's refresh is answered from memory with no IdP call, the row is unchanged, rejectionConfirmed returns true and dropSession deletes all of the session's upstream rows, forcing a re-login. Before this PR that call would have reached the IdP and succeeded. A transient 401 becomes an irreversible delete. Suggested fix: let the guard bypass the memory lookup before it deletes (a context marker or a redeem parameter), while still recording fresh rejections. The guard runs at most once per session, so the extra IdP call is cheap, and the rejectionConfirmed change and the trade-off doc paragraph mostly go away.

  2. pkg/authserver/server_impl.go (~352): upstreamRefresherImpl plus refresher.(*upstreamTokenRefresher) is redundant, and the comment's reason is backwards. If the interface value were ever wrapped, the assertion fails silently, the field stays nil, and UpdateUpstreamClientCredentials skips the generation bump, so stale rejections keep replaying. No test goes through newServer to catch this (refresher_rejected_test.go builds &server{upstreamRefresherImpl: ...} by hand). Suggested fix: keep one concrete-typed field from newUpstreamTokenRefresher and derive the interface from it, or fail loudly if the assertion does not hold.

  3. Open question: rejectedRefreshesTTL is hardcoded at 10 minutes, so an operator cannot shorten it. 1-2 minutes would still absorb a retry storm with much less staleness. Fine to keep if deliberate, but say so.

Simpler alternative: bypass the memory in the guard (finding 1) instead of rewriting rejectionConfirmed; the rest of the PR can stay as is.

🤖 Reviewed with Claude Code

@codecov

codecov Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.65217% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.10%. Comparing base (1082992) to head (3e55e3d).
⚠️ Report is 13 commits behind head on main.

Files with missing lines Patch % Lines
pkg/authserver/rejected_refreshes.go 96.07% 2 Missing ⚠️
pkg/authserver/refresher.go 94.11% 1 Missing ⚠️
pkg/authserver/server_impl.go 92.85% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #7307      +/-   ##
==========================================
+ Coverage   81.95%   82.10%   +0.14%     
==========================================
  Files         922      929       +7     
  Lines       93367    94212     +845     
==========================================
+ Hits        76521    77352     +831     
- Misses      16841    16855      +14     
  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.

@ChrisJBurns ChrisJBurns left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

See the inline comments.

Comment thread pkg/authserver/refresh_grant_guard.go Resolved
jhrozek and others added 4 commits November 25, 2026 19:58
The refresh grant guard refreshed through the shared refresher, so it
could be answered from the memory of rejected refresh tokens. A
confirmed rejection then deleted the session's upstream rows. If an
administrator had fixed an IdP-side account or policy block in the
meantime, the client was sent to sign in again where a fresh IdP call
would have succeeded.

Mark the context the guard passes to RefreshAndStore so that redeem
skips the lookup and asks the IdP. A fresh rejection is still added to
the memory, so bearer requests benefit. The marker is unexported and no
interface changes. A guard call that joins a refresh already in flight
for the same row gets that call's result, which may come from the
memory; that window is accepted rather than giving the guard its own
singleflight key, which would allow two concurrent redemptions of one
refresh token.

Co-authored-by: Mecatl <[email protected]>
The server held the refresher twice: as the interface and, since the
last change, as a concrete pointer set through a comma-ok assertion.
That only moved the silent failure, because a wrapped or mistyped value
would leave the pointer nil and skip the generation bump.

newUpstreamTokenRefresher now returns *upstreamTokenRefresher, and the
server keeps that single field. Every consumer of the interface gets a
value from refresherInterface, which returns a nil interface for a nil
pointer so no typed nil reaches an `== nil` check. A new test builds a
server through newServer and checks that replacing an upstream's client
registration bumps the refresher's generation.

Co-authored-by: Mecatl <[email protected]>
Ten minutes kept bearer requests failing for too long after an
administrator fixed an IdP-side block for a client that never sends a
refresh grant. A compliant client recovers through the refresh grant
guard, which skips the memory, so the memory only needs to absorb a
retry storm. One IdP call per row every 5 minutes still does that.

The TTL stays a constant because nothing has asked to tune it. Update
the code comments and the docs to say 5 minutes, and gofmt the server
literal in a test.

Co-authored-by: Mecatl <[email protected]>
A guard call that joins an in-flight refresh of the same row can inherit
a remembered rejection for the leader's re-read of the row plus the
memory lookup, not only the lookup, so say so, and stop saying the guard
always asks the IdP. The architecture doc now carries the same hedge as
the guard's recheck comment about storage layers that share rows across
sessions. A test closure that runs on the guard's goroutine uses assert
instead of require, so a failure is reported instead of hanging.

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

jhrozek commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, all three were fair.

  1. Agreed, and the guard now skips the memory. It sets an unexported context marker on its refresh, redeem skips the lookup when it sees it, and a rejection the guard gets is still recorded so the bearer path keeps the benefit. I went with the marker rather than a redeem parameter because a parameter would have had to go through storage.UpstreamTokenRefresher, which embedders wrap. One edge I left as is and documented: if the guard's call joins an in-flight bearer refresh of the same row through singleflight, it gets that call's answer, which can come from the memory. That window is the leader's re-read of the row plus a map lookup, and giving the guard its own singleflight key would allow two concurrent redemptions of the same refresh token, which is worse. I kept the rowChanged recheck, since it still covers another replica refreshing without rotation during the 500ms wait, but its comment and the docs now describe it following a fresh IdP answer, and the trade-off paragraph is gone. Your scenario is now a test: rejection remembered, IdP starts accepting, refresh grant is granted and the bearer path works again without waiting out the TTL.

  2. You're right, the comma-ok just moved the silent failure. newUpstreamTokenRefresher now returns the concrete type, the server keeps that one field, and the interface value for the guard, handler and accessor is derived from it with an explicit nil when there are no upstreams. There's a test that goes through newServer and checks a client registration switch bumps the counter.

  3. It was deliberate to keep it a constant, but 10 minutes was more than it needs to be. With the guard skipping the memory, the TTL only matters for a client that keeps retrying its bearer token without ever sending a refresh grant, so I dropped it to 5 minutes and wrote that reasoning next to the constant.

@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 25, 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 5d7d1e0: the three earlier findings are fixed; two edges in the new guard bypass are still open, and neither is a design problem.

  1. Guard deletes a session on a stale remembered rejection: resolved. The guard's context now carries withoutRememberedRejections, redeem skips the memory lookup when it sees it, and the marker survives WithoutCancel/WithTimeout. Tests cover the guard asking the IdP despite a remembered rejection.
  2. Redundant upstreamRefresherImpl / silent comma-ok: resolved. The server holds one concrete refresher and refresherInterface() avoids a typed-nil interface.
  3. Hardcoded 10-minute TTL: resolved. It is now 5 minutes, and the constant's comment gives the reason it is not configurable.

New findings:

  1. pkg/authserver/refresh_grant_guard.go:308 with refresher.go:192-204: the marker is lost when the guard joins a singleflight call led by an unmarked bearer request. singleflight runs on the leader's context, so the guard gets the leader's answer, which may come from the memory. rejectionConfirmed then sees an unchanged row and dropSession deletes the session. This is the original finding 1 outcome with a smaller trigger: an admin fixes the IdP side, then the client sends a refresh grant while retry-storm bearer traffic keeps a leader in flight. A separate singleflight key would allow two redemptions of the same refresh token, so keep the shared key. Instead, have lookup return a typed error (or set a flag) meaning "answered from memory". When the guard gets that, it calls RefreshAndStore once more with the marked context, so it leads or joins a live call. There is no test for the join path.
  2. refresh_grant_guard.go:306-311: with the bypass, the guard always calls the IdP, so repeated refresh grants on a dead upstream token are no longer absorbed by the memory. The only limit left is the recheck, and rejectionConfirmed returns false on ctx.Done, so checkRow treats the row as transient and grants. The refresher goroutine is detached, so the IdP call still completes. Scenario: a token holder with a dead upstream token sends a refresh grant and disconnects within the 500ms recheck window, repeatedly. Each attempt costs one IdP call and nothing is dropped. I read this path but did not run it. Suggested fix: throttle the bypass by recording a last-probe time on the rejection entry (skip the memory only if the last probe is older than 10–30s), or drop the session when the recheck is cancelled after a fresh IdP rejection.

Design is unchanged: the memory stays in redeem. I would approve once 4 is closed, or as a follow-up if you'd rather land it now. Say which.

🤖 Reviewed with Claude Code

jhrozek and others added 2 commits November 25, 2026 22:04
The refresh grant guard skips the memory of rejected refresh tokens,
but a guard call that joins a singleflight call led by an ordinary
bearer request gets that leader's result, which can be a remembered
rejection. The guard then saw an unchanged row and deleted the session,
the stale-rejection delete the skip exists to prevent.

Remembered rejections are now recognisable inside the package without
changing the error text or its ErrGrantRejected and RetrieveError
behaviour. When the guard gets one, it refreshes once more with the
same marked context. If that answer is also remembered, the outcome is
uncertain and the grant goes through. The guard deletes rows only after
a rejection the IdP just gave.

Co-authored-by: Mecatl <[email protected]>
The "Remembered rejections" section still said the refresh grant guard
always calls the IdP. A guard call that joins a refresh already in
flight can be answered from the memory, which the guard section now
describes, so point there instead.

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

jhrozek commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the second pass.

  1. Fixed in 52ebcb8. A rejection answered from the memory is now recognisable inside the package (same error text, same errors.Is/errors.As behaviour for everyone else). When the guard gets one, which is what happens when it joins an unmarked bearer request's singleflight call, it retries once with its marked context, so it either leads a call that reaches the IdP or joins one. If that second answer also came from the memory, it grants and deletes nothing, so the guard only drops a session after a rejection the IdP just gave. The singleflight key stays shared. The join is covered by tests with a mocked refresher whose first answer comes from an unmarked call: IdP still rejects (refused, rows deleted, one IdP call), IdP now accepts (granted, row updated), and both answers remembered (granted, nothing deleted).

  2. This one predates the PR: on main the guard calls the IdP on every refresh grant and also returns false from rejectionConfirmed when the context ends, so a client that disconnects inside the recheck window costs an IdP call each time and is never dropped. The memory hid that for a while and skipping it in the guard brings main's behaviour back. Since fixing it means changing the rule that a disconnect never refuses a session that may be live, I filed it separately as "Refresh grant guard skips its recheck when the client disconnects" (Refresh grant guard skips its recheck when the client disconnects #7312).

@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 25, 2026
@github-actions github-actions Bot added the size/XL Extra large PR: 1000+ lines changed label Nov 25, 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 3e55e3d: approve. Both open findings are settled.

  1. Guard drops a session after joining an unmarked singleflight leader: resolved. checkRow now retries once with the marked context when the first answer was served from the memory. The retry is bounded (two calls, never concurrent). If the second answer is also remembered, the guard grants, so dropSession is only reachable after a live IdP rejection. The sentinel is unexported and errors.Is/errors.As on ErrGrantRejected and *oauth2.RetrieveError behave as before, so the token service and chain re-evaluation are unaffected. Tests cover "IdP still rejects", "IdP now accepts" and "two remembered answers". They simulate the join with a mock refresher; a test with a real concurrent marked and unmarked RefreshAndStore call would be a nice addition but is not blocking.

  2. Guard bypass costs one IdP call per refresh grant on a dead token: withdrawn. The guard already called the IdP on every refresh grant on main, and rejectionConfirmed already returned false on ctx.Done there. So this restores the existing behaviour rather than adding exposure. The follow-up is tracked in #7312.

No new findings. Design is unchanged.

🤖 Reviewed with Claude Code

@jhrozek
jhrozek merged commit 991ada6 into main Nov 25, 2026
50 checks passed
@jhrozek
jhrozek deleted the upstream-dead-refresh-token branch November 25, 2026 21:53
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.

3 participants