Repository navigation
Stop re-sending upstream refresh tokens the IdP rejected - #7307
Conversation
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]>
rdimitrov
left a comment
There was a problem hiding this comment.
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.
-
pkg/authserver/refresh_grant_guard.gocheckRow(~266-284): the guard's refresh now goes through the memory. Scenario: the IdP rejects withinvalid_grantbecause 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,rejectionConfirmedreturns true anddropSessiondeletes 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 aredeemparameter), while still recording fresh rejections. The guard runs at most once per session, so the extra IdP call is cheap, and therejectionConfirmedchange and the trade-off doc paragraph mostly go away. -
pkg/authserver/server_impl.go(~352):upstreamRefresherImplplusrefresher.(*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, andUpdateUpstreamClientCredentialsskips the generation bump, so stale rejections keep replaying. No test goes throughnewServerto catch this (refresher_rejected_test.gobuilds&server{upstreamRefresherImpl: ...}by hand). Suggested fix: keep one concrete-typed field fromnewUpstreamTokenRefresherand derive the interface from it, or fail loudly if the assertion does not hold. -
Open question:
rejectedRefreshesTTLis 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 Report❌ Patch coverage is
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. 🚀 New features to boost your workflow:
|
ChrisJBurns
left a comment
There was a problem hiding this comment.
See the inline comments.
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]>
|
Thanks, all three were fair.
|
rdimitrov
left a comment
There was a problem hiding this comment.
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.
- Guard deletes a session on a stale remembered rejection: resolved. The guard's context now carries
withoutRememberedRejections,redeemskips the memory lookup when it sees it, and the marker survivesWithoutCancel/WithTimeout. Tests cover the guard asking the IdP despite a remembered rejection. - Redundant
upstreamRefresherImpl/ silent comma-ok: resolved. The server holds one concrete refresher andrefresherInterface()avoids a typed-nil interface. - Hardcoded 10-minute TTL: resolved. It is now 5 minutes, and the constant's comment gives the reason it is not configurable.
New findings:
pkg/authserver/refresh_grant_guard.go:308withrefresher.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.rejectionConfirmedthen sees an unchanged row anddropSessiondeletes 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, havelookupreturn a typed error (or set a flag) meaning "answered from memory". When the guard gets that, it callsRefreshAndStoreonce more with the marked context, so it leads or joins a live call. There is no test for the join path.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, andrejectionConfirmedreturns false onctx.Done, socheckRowtreats 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
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]>
|
Thanks for the second pass.
|
rdimitrov
left a comment
There was a problem hiding this comment.
Re-review of 3e55e3d: approve. Both open findings are settled.
-
Guard drops a session after joining an unmarked singleflight leader: resolved.
checkRownow 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, sodropSessionis only reachable after a live IdP rejection. The sentinel is unexported anderrors.Is/errors.AsonErrGrantRejectedand*oauth2.RetrieveErrorbehave 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 unmarkedRefreshAndStorecall would be a nice addition but is not blocking. -
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, andrejectionConfirmedalready returned false onctx.Donethere. 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
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, anotherinvalid_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.
pkg/authserver(10,000 entries, 5 minutes, constants rather than configuration). Only a definitiveupstream.ErrGrantRejectedis remembered:invalid_grantwith 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.UpdateUpstreamClientCredentialsswaps 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:invalid_grantfor a refresh token issued to another client.upstream.ErrGrantRejectedand still carries an*oauth2.RetrieveErrorwith that code and status. Its message says the rejection was remembered and the provider was not called.Relates to "Re-authorization walks the full upstream chain instead of evaluating existing credentials" (#6831).
Type of change
Test plan
task test)task test-e2e)task lint-fix)New tests count requests to a fake IdP and use a fake clock. They cover:
invalid_grantfailures are not remembered;Newbumping the refresher's counter on a client registration switch.Each test for a review fix was checked to fail with that fix removed.
Changes
pkg/authserver/rejected_refreshes.gopkg/authserver/refresher.goredeemconsults and fills the memory aroundrefreshAndStore; client registration counter.pkg/authserver/server_impl.gopkg/authserver/refresh_grant_guard.gopkg/authserver/config.goRefreshGrantHandlersdoc: handlers can see a remembered rejection.docs/arch/11-auth-server-storage.md,docs/middleware.mdDoes this introduce a user-facing change?
Yes. Responses keep the same shape, but timing and IdP traffic change:
invalid_grantwas 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.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
RefreshGrantHandlersthat call the shared refresher can see a remembered rejection. It is a new error value each time, still matchesupstream.ErrGrantRejected, and still unwraps to an*oauth2.RetrieveErrorwith 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 throughUpdateUpstreamClientCredentialsfor the memory to forget earlier rejections. Calling a provider'sUpdateClientCredentialsdirectly bypasses it.Special notes for reviewers
redeemchecks; a parameter would have meant changingstorage.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.mainbehaves 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).rotatedElsewhere. The guard's recheck androtatedElsewheredeliberately treat a same-refresh-token row differently.rotatedElsewheredecides 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.redeemreads it before calling the IdP, so a rejection from the old client is never filed under the new value.error=bad_refresh_token, which is notErrGrantRejected, so nothing is remembered for it.refresher.go. The change here is kept inredeemand the new file so a rebase stays small.