Repository navigation
Wire user-keyed upstream storage into the auth server - #7332
Conversation
Add Config.UserKeyedUpstreamStorage, off by default. When set, authserver.New wraps the storage in the user-keyed layer as the outermost decorator, so the refresher, handlers, guard and ID-JAG subject resolver all see rows keyed by user, while client, consent and device-code lookups keep reaching the inner layers through Unwrap. authserver.New refuses storage that already contains the user-keyed layer, with the setting on or off. With it on, the layer would be applied twice. With it off, the session-keyed refresh guard would read the rows without a canonical user and never refuse a refresh. storage.IsUserKeyed finds the layer through either Unwrap() Storage or Unwrap() UpstreamTokenStorage. The device flow now puts the resolved user in the context before it stores upstream tokens, as the browser callback already does; the user-keyed layer refuses writes without one. With the setting on, the refresher, the refresh-grant guard and the sign-in carry-forward still treat rows as per session. The following commits in this series make them user-aware, so this commit is not meant to land on its own. Co-authored-by: Mecatl <[email protected]>
With user-keyed storage every refresher storage call needs the canonical user in the context. Callers that hand the refresher a row without one, such as an embedder calling UpstreamTokenRefresher() directly, would otherwise fail with ErrNoCanonicalUser. With the setting on, the refresher takes the user from the row it refreshes when the context has none. It refuses with ErrInvalidBinding when the context holds a different user, and with ErrNoCanonicalUser when it holds an explicitly empty one, so a caller cannot act on another user's row by passing it in. With the setting off the context is left as it is. The Server interface doc for UpstreamTokenRefresher and IDPTokenStorage says callers must pass only rows they read for that user and put the canonical user in the context. The refresher then re-reads the row and may redeem that row's refresh token, or return it. The user-keyed layer refuses a foreign row on that read, but storage that is not user-keyed does not, for example under the per-user credential reader. So whenever the context carries a canonical user, the refresher also refuses a re-read row owned by someone else with ErrInvalidBinding, before it calls the provider or writes anything. The same check covers the row it reads after losing a concurrent refresh, and the row it reads to see whether a rejected token was rotated elsewhere, which is not taken for a successor when it belongs to someone else. A context without a canonical user is not checked. When a rotated refresh token cannot be saved, the refresher deletes the row so the dead token is not redeemed again. A shared row can meanwhile hold a token a new sign-in stored, so the refresher now re-reads the row first and keeps it when it holds a different refresh token; the error then does not report the row as deleted. A failed re-read still deletes. A small window between the re-read and the delete remains; closing it would need a conditional delete in the storage interface. This applies with the setting on or off. Co-authored-by: Mecatl <[email protected]>
With user-keyed storage a user's rows are shared by all their clients, so the refresh-grant guard can no longer judge one session by every row and delete them on failure. With the setting on, the guard checks only the identity provider's row, through its own credential reader on the shared refresher, and deletes no row. A row with a live access token owned by the user is granted without calling the reader, as the field-off guard does, so a refresh grant does not ask the provider for a new ID token while the access token is valid. It refuses when that row is absent, a placeholder, empty, has expired without a refresh token, belongs to another user, or the identity provider rejects the refresh, and also when there is no canonical user. A transient failure or timeout grants with one WARN, and the tests check it is the only WARN; a cancelled request logs at DEBUG. That WARN comes once per refresh grant, where the field-off guard logs the same case at DEBUG: on the per-user read the reader's own refresh WARN is off, so this line is the only sign that the guard let a grant through unchecked. Sessions without a tsid are still not checked, and with the setting off the guard is unchanged. Refusing a refresh token with invalid_grant makes a compliant client discard it, so an unrevoked refused token would work again once the user signs in on any client, where reuse detection cannot catch a stolen copy. The guard therefore revokes the presented grant when the identity provider row is missing, a placeholder, empty or deleted during the refresh (including by the refresher after it could not save a rotated refresh token), when a refresh leaves no access token, or when the provider rejected the refresh. It keeps the grant for a foreign row, no canonical user and an unconfigured identity provider, which a new sign-in does not fix. After a confirmed rejection the guard also clears the rejected refresh token from the shared row with a compare-and-swap on that token, so the next sign-in that gets no refresh token from the provider does not carry the dead one forward. A token stored since is left alone. The row stays. Like the field-off guard, it asks the IdP instead of the refresher's memory of rejected refresh tokens: it marks the read's context, retries once when it joined a refresh that answered from memory, and grants at DEBUG if that answer is remembered too. Otherwise a client whose IdP-side block an administrator had cleared could lose a token the IdP would now accept. A rejection is confirmed by re-reading the row and comparing it with the refresh token read before the refresh; an empty snapshot token is never confirmed. Two races are accepted and noted at the site. If another sign-in installs a new token before the refresh and the provider rejects it, the recheck takes it for a successor and grants once, and the next refresh is refused and revoked; fixing it would need the refresher to report the token it redeemed. If a sign-in carries the same refresh token forward between the recheck and the clear, the clear also replaces that sign-in's new access token and the user signs in once more; fixing it would need a swap that compares more than the refresh token. Co-authored-by: Mecatl <[email protected]>
When an upstream returns no refresh token at login, the callback and the device flow copy one forward from the user's latest stored row. With user-keyed storage that row is shared by all the user's clients, and the latest row across the user's index can be an old session row, so the copy could put an obsolete refresh token on the shared row or overwrite one a concurrent refresh just rotated. With the setting on, the prior token is read from the shared row itself and written back with compare-and-swap. A login that read no row, or a row without a refresh token, swaps on an empty refresh token, so a token another client stored in between is not erased. If the prior read fails, the login writes only over a row without a refresh token, so a storage error cannot strip the token from the user's other clients. A prior row of a different upstream account is replaced, also with a swap on the token that was read. A row owned by another user is replaced and logged at ERROR; the user-keyed layer already refuses such writes, so this is a fallback. Every lost write re-reads the winning row and compares its upstream account with the sign-in's. A winner of the same account (or a synthetic subject) gets the sign-in's access token, ID token and expiry together with its own refresh token, in one more swap; if that swap loses as well, the newer row is kept. Either way the sign-in succeeds, and new scopes a re-consent granted are not lost to a concurrent refresh. A winner of a different account is kept, and the sign-in fails with a server error, logged once at WARN, so requests do not silently use another account. If the row is gone at the re-read, the sign-in's tokens are written into the empty slot. A winner that cannot be read fails the sign-in. A retry replaces the row as before. The handler works on a copy of the sign-in's tokens and does not change the caller's. The new WARN and ERROR lines leave the user ID out; it is logged at DEBUG. The server passes the setting to the handlers with a new handler option. With the setting off the carry-forward is unchanged. Co-authored-by: Mecatl <[email protected]>
After a refresh leaves the ID token expired (the provider omitted id_token), the credential service stops the ID-token trigger for that row until the access token expires. The per-user reader GetValidTokensForUser kept that state under "user:"+userID and the session paths under the tsid. Under user-keyed storage both address the same row, so a switch between the paths missed the suppression and called the provider again. Key the suppression by the row ID that storage resolves, on every path, and fall back to the old session-and-provider key when no row ID resolves. Distinct rows keep separate entries. Co-authored-by: Mecatl <[email protected]>
An embedder that builds the authorization server in Go with its own storage needs a way to opt in to user-keyed upstream storage. Add the WithUserKeyedUpstreamStorage option for NewEmbeddedAuthServerWithStorage, which sets Config.UserKeyedUpstreamStorage. Runner-built storage stays session-keyed until it gets a migration, so NewEmbeddedAuthServer refuses the option instead of ignoring it. The option is not on RunConfig. Config.Validate refuses the option together with UpstreamFilter. The filter only narrows which upstream legs a sign-in walks, while the bearer validator loads every row the user has, so a user who loses a group would keep sending that group's upstream tokens until the embedder deletes the rows. The combination is refused until the read side applies the filter per user. Under user-keyed storage the bearer validator names the user only for a token it classifies as an interactive session, which needs the validator bound to the embedded issuer, verifying with the in-process key provider, and configured with an audience. Without all three no token is interactive: a bound validator serves every request without upstream tokens, an unbound one answers 503, and a client that signs in again gets the same answer. NewTokenValidator therefore refuses to start in that case when its upstream token reader reports user-keyed storage, and names the missing settings; the message also says that a validator for another issuer should not get this reader. The report is a new optional capability, upstreamtoken.UserKeyedReader; InProcessService implements it by checking whether its storage is the user-keyed layer, directly or through Unwrap() Storage or Unwrap() UpstreamTokenStorage, so a decorator over IDPTokenStorage() can expose it. A reader that wraps another must forward it; behind one that does not, the request-time behaviour is unchanged. TokenReader itself is not changed. The end-to-end test from the per-user reads change keeps covering the request-time cases through a reader that hides the capability. The server deletes a user's row on its own only when the refresher cannot save a rotated refresh token, and a row for a token that never expires has no storage lifetime, so disconnect and user deletion are left to the embedder. The option's doc names the calls to use (DeleteUpstreamTokensForProvider on IDPTokenStorage() with the user on the context, and DeleteUser), and a test disconnects a provider that way and checks that the user's next login runs that provider's leg again. The docs of the option and the Config field also warn against storage that already keys rows by user and against reading tokens through the raw storage handle instead of IDPTokenStorage(), and point to the adoption checklist on the storage architecture page. Co-authored-by: Mecatl <[email protected]>
Embedders turning on user-keyed upstream storage need to know how rows are keyed, when the validator loads them, and how the refresher, the refresh-grant guard and sign-in behave once one row is shared by all of a user's clients. Add a "User-keyed upstream storage" section to the auth server storage architecture page. It covers the key layout, the startup refusals, and the admission route that decides whether the validator names a user (an unbound validator answers 503, a bound one without an audience or key provider loads nothing, and NewTokenValidator refuses both when it can see the user-keyed storage). It then covers how refreshes and sign-ins write the shared row, row lifetime and when the refresher deletes a row, the per-user reader, the guard's identity-provider check, when it revokes a grant and clears a rejected refresh token, how it skips remembered rejections, the accepted races and loops, and what DeleteUser leaves behind. Most mistakes in adopting the option do not fail: users look disconnected, refreshes fail, or a refresh check passes every time. The section ends with an adoption checklist for embedders, including what turning the option on and disconnecting a provider cost. On the middleware page, the 401 for a tsid session with no upstream access token holds under user-keyed storage only for an interactive session of the embedded auth server, and a confirmed rejection keeps the shared row; say so. On the token exchange page, qualify how an unmarked token that fits no route is served. Link the section from the architecture index, the token exchange page and the middleware page, and describe the user-keyed row keys in the Redis storage page's key and secondary index tables. Co-authored-by: Mecatl <[email protected]>
Embedders adopt user-keyed upstream storage by following the checklist in docs/arch/11-auth-server-storage.md. Nothing exercised that wiring end to end, so a change to the validator or the reader contract could break an embedder without failing a test. The test wires the server the way an embedder does: a storage decorator below the user-keyed layer, a TokenReader wrapper over IDPTokenStorage() that forwards UserKeyed, a validator bound to the embedded issuer with the key provider and an audience, and a handler behind the validator middleware. It runs over memory and Redis. Two clients share one user's connections, a refresh grant keeps working, a disconnect shows up on the next request, DeleteUser removes the rows, and the decorator only sees user-keyed session IDs. Miswired variants pin the symptom of each mistake: a reader below the layer (401), a wrapper that hides the capability behind an unbound validator (503), a missing audience (startup error), and a disconnect without a canonical user (ErrNoCanonicalUser, row kept). It cannot cover the per-server key prefix, migrating rows written before the option was on, or zero expiry fields; those depend on deployment state a single test server does not have. Co-authored-by: Mecatl <[email protected]>
Codespell reads failSaves as a misspelling of "failsafes". Rename the field to failStores. Co-authored-by: Mecatl <[email protected]>
rdimitrov
left a comment
There was a problem hiding this comment.
Comment: the design is right (wrapper outermost, each consumer fixed at its own owner, fail-closed startup checks), but there is one real race, an unstated behaviour change on the default path, and the PR is too big to review as one.
Design: the keying lives in the UserKeyedUpstreamStorage wrapper, and the refresher, refresh-grant guard, callback/device carry-forward and ID-token suppression are each fixed where they touch the shared row. I found no uncovered path that writes upstream rows, and the option is embedder-only, so there is no CRD, RunConfig or HTTP change. The weak spot is how "user-keyed" reaches those components (finding 3), and the PR bundles four separable changes (finding 4).
-
pkg/authserver/refresher.go,cleanupAfterRotatedPersistFailure/replacedByNewerToken: the "don't delete a row a sign-in just replaced" check is a read followed by an unconditionalDeleteUpstreamTokensForProvider. Scenario: the IdP rotates and the persist fails; a sign-in's CAS lands between the read and the delete, and the delete removes the fresh shared row, so every client of that user loses the upstream connection. The check also compares only refresh tokens, so a sign-in that carried the old refresh token forward (same token, new access token) is seen as "not replaced" and its row is deleted; a read error has the same effect. Fix: make the removal conditional on the refresh token you read (CAS that clears the refresh token, as the guard does) instead of deleting the row. -
pkg/authserver/refresher.go:replacedByNewerTokenandcheckRowOwnerrun with the option off, so "behaves as on main" is not true.checkRowOwnerreturnsErrInvalidBindingfor any re-read row whoseUserIDdiffers from (or is empty versus) the canonical user in the context; a session-keyed row with an emptyUserIDthat refreshed fine before would now be refused. I could not confirm such rows exist, so please checkMigrateLegacyUpstreamDataand older rows. Fix: gate both onr.userKeyed, or state the change in the PR body and show old rows are unaffected. -
pkg/authserver/server_impl.go(newUpstreamTokenRefresher,buildHandlerOptions,refreshGrantValidatorChain),pkg/authserver/server/handlers,pkg/auth/upstreamtoken/service.go(isUserKeyed): the same fact is passed as a bool or option into four components, although each already receives the outermost storage. Constructing one with the wrapped store but without the flag silently gives session-keyed behaviour. Fix: callstorage.IsUserKeyed(stor)where it is needed and deletehandlers.WithUserKeyedUpstreamStorage, the bool parameters, the guard-selection switch and the one-lineisUserKeyedwrapper. -
Size: about 4.9k added lines, roughly 14 non-test files and about 750 lines of source, against the repo's 400-line / 10-file limit. Separable pieces: the user-keyed guard, the CAS carry-forward in the callback and device flows, the refresher owner checks and persist-failure change, and the validator startup check in
pkg/auth(token.go,types.go, which depends on nothing else here). Please split (see/split-pr), with theConfig/ runner option wiring landing last.
Simpler alternative: derive user-keyed once from storage (finding 3) and ship the four pieces as separate PRs.
🤖 Reviewed with Claude Code
rdimitrov
left a comment
There was a problem hiding this comment.
Reviewed locally at c932c2d6c: pkg/auth/..., pkg/authserver/..., pkg/authz/... and pkg/vmcp/... pass with -race. I also ran a throwaway two-replica test (two servers on one miniredis with shared keys, one with UserKeyedUpstreamStorage on and one off) and traced every upstream-row read and write to check the canonical user is set first. The design follows #7263 closely, and option-off deployments are safe. Four things worth addressing:
1. Enabling or disabling the option on a multi-replica fleet logs users out, and the docs give no rollout order
From the two-replica test:
| Login on | Refresh on | Result |
|---|---|---|
| option off | option on | 400 invalid_grant, and the refresh token is revoked: retrying it on the option-off replica also gets 400 |
| option on | option off | 400 invalid_grant (not revoked, but a compliant client discards it); bearer requests on the option-off replica get 401 |
So during a rolling restart, users bounce between replicas and lose their sessions. The user-facing section says refresh grants "are refused" until users sign in again. They are revoked, so that client's refresh token stays dead even after the user signs in elsewhere.
Turning the option off leaves the upstream:user:* rows and upstream:idx:user:* indexes in Redis. Rows for tokens that never expire (a GitHub OAuth App) have no TTL, so live third-party credentials stay at rest with nothing reading or deleting them. "Turning it off later does the same in reverse" understates that.
docs/arch/11-auth-server-storage.md gives a rollout and rollback order for the other cross-version settings (subject-identifier disclosure, non-fatal secondary legs). This option needs one too, e.g.: switch every replica at once (no mixed fleet), expect one forced sign-in per user, and on rollback delete the user-keyed rows and indexes.
2. Behaviour changes with the option off, contrary to #7263's acceptance criteria
#7263 says: "With the field off, over storage that reads the canonical user, the guard, the refresher and the callback behave exactly as today", and "With the field off, none of these run". This PR changes three things for every deployment, including thv, the operator and vMCP:
- the refresher's owner check on re-read rows (
checkRowOwner) - the re-read before the delete after a failed rotation persist (
replacedByNewerToken) - ID-token suppression keyed by row ID
The PR body says so in the user-facing section, but the summary says "With the option off, the server behaves as on main", which contradicts it. The practical risk looks low: in-tree writers always store the session subject as UserID, and the field has existed since January 2026, so existing rows should not trip the owner check.
I'd either split these three into their own PR, which also brings this one closer to the 400-line / 10-file guideline, or update #7263 so the issue and the code agree.
3. Shared rows make the cross-replica rotation race (#4122) much more likely
Before, one row belonged to one client session. Now every client of a user, on every replica, refreshes the same row, and across replicas only compare-and-swap coordinates them. With an IdP that rotates refresh tokens and detects reuse (Okta, Entra ID, Auth0), one lost race can make the IdP revoke the whole token family. The guard then refuses and revokes every client of that user at the next refresh grant: one race logs the user out of all clients.
The known-limits note mentions #4122, but the adoption checklist doesn't. Please add an item for embedders running more than one replica against a rotating IdP: user-affine routing, or a single replica until #4122 lands.
4. Parts of #7263 not in this PR
#7263 also lists pkg/vmcp/cli/serve.go calling ValidateAuthServerIntegration, which nothing calls today, and vMCP loading only its configured providers. The description says both are stacked follow-ups, and the PR is "Part of #7263", so the issue won't auto-close. Just noting it so the issue stays open until those land.
Checked and fine
- The option can't be turned on from
RunConfig,thv, the operator or vMCP:NewEmbeddedAuthServerrefuses it, andpkg/runner/runner.goandpkg/vmcp/cli/serve.gobuild their reader over storage that is never user-keyed. - Every server-side read and write of an upstream row sets the canonical user first: the browser callback, a skipped chain leg, device confirmation, the guard, the refresher (from the row) and
GetValidTokensForUser. - The guard's user (the session subject) is the ID the callback stores rows under (
session.New(subject, …)incallback.go). - Token exchange and ID-JAG sessions carry no
tsid, so the guard skips them; the JWT bearer grant'sConsumeAssertionJWTpasses through the wrapper. - I agree with the reasoning for the disclosed deviations: the guard clears the refresh token instead of deleting the shared row, and the three accepted races are documented at their sites.
🤖 Generated with Claude Code
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #7332 +/- ##
==========================================
+ Coverage 82.41% 82.51% +0.10%
==========================================
Files 937 938 +1
Lines 95821 96113 +292
==========================================
+ Hits 78967 79309 +342
+ Misses 16849 16799 -50
Partials 5 5 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
The refresher, the sign-in handlers, the refresh grant guard and the token reader each took the user-keyed setting as a flag or option, although each already receives the outermost storage. A component built over the user-keyed layer without the flag silently behaved as if rows were per session. Each component now asks storage.IsUserKeyed on the storage it is given. handlers.WithUserKeyedUpstreamStorage and the refresher's flag are removed. Config.UserKeyedUpstreamStorage still decides whether authserver.New applies the layer. Co-authored-by: Mecatl <[email protected]>
When the provider rotates a refresh token and the refresher cannot save the new one, it deleted the row so the dead token is not redeemed again. With user-keyed storage the row is shared, and a re-read before the delete still left a window in which a sign-in's fresh row could be deleted for every client of the user. With user-keyed storage the refresher now clears the dead token with a compare-and-swap on it and keeps the row. A token stored in the meantime makes the swap lose and is kept, and a row a disconnect removed is not recreated. On success the error still wraps ErrNotFound, so an expired connection is reported as needing authorization as before; on the ID-token path the stored access token is served until it expires. With the setting off the row is deleted exactly as before. The owner check on rows the refresher re-reads is removed. With the setting on every refresher read goes through the user-keyed layer, which already refuses another user's row once withCanonicalUser has set the user; with it off the check refused old rows without a user ID that refreshed before. The refresher is now unchanged with the setting off. Co-authored-by: Mecatl <[email protected]>
|
Thanks, all three code points were right and are fixed in the last two commits.
|
rdimitrov
left a comment
There was a problem hiding this comment.
Re-review of 164363b: the code findings are fixed and the design is better, but one new edge case, a missing test and some doc items are still open.
Earlier findings (first review = R1, second = R2):
- R1-1 delete-after-read race in
replacedByNewerToken: resolved. The re-read is gone;clearDeadRefreshTokendoes a compare-and-swap on the redeemed token and keeps the row, and a read error no longer deletes anything. The one remaining window (a sign-in that carried the same dead token forward just before the swap) is documented and would need a storage-interface change; accepted. - R1-2 owner check and re-read running with the option off: withdrawn. The wrapper already returns
ErrInvalidBindingfor a foreign row, so the check only ever acted on option-off rows. The option-off delete path now matchesmain. - R1-3 flag threaded through four components: resolved. Mode is derived with
storage.IsUserKeyedfrom the finalstor; the wrapper is applied last, so detection sees it everywhere. - R1-4 PR size: not resolved, but net lines dropped by 127. Still above the 10-file limit; maintainer call.
- R2-1 rollout order, revocation and rollback of stale
upstream:user:*rows: not resolved.docs/arch/11-auth-server-storage.md:1053-1054still says "Turning it off later does the same in reverse" with no order and no revocation or orphaned-row note. - R2-2 option-off behaviour changes: partly resolved. The code differences are gone except ID-token suppression keyed by row and startup refusal of already user-keyed storage. The Summary still says "With the option off, the server behaves as on main"; fix the sentence or list these two.
- R2-3 #4122 cross-replica rotation race missing from the adoption checklist (items 1-10, lines ~1287-1360): not resolved.
- R2-4 follow-ups for the rest of #7263: no action.
New findings:
9. pkg/authserver/refresher.go (clearDeadRefreshToken) with pkg/auth/upstreamtoken/service.go (refreshForIDToken, shouldRefreshForIDToken): the cleared row can be served forever. Scenario: an upstream returns no expires_in but an expiring ID token. A persist failure clears the refresh token and keeps the row; the wrapper's userRowForWrite drops SessionExpiresAt for a real user, so the row has no TTL. refreshForIDToken re-reads and serves the kept row, then shouldRefreshForIDToken is false (empty refresh token) and ExpiresAt is zero, so the row never counts as expired. Every read serves an expired ID token and the user is never sent to re-authorize. On main the delete forced a re-login. Fix: keep the row only when ExpiresAt is non-zero, otherwise delete it or set ExpiresAt to now; or make the per-user reader treat an empty refresh token plus an expired ID token as needing authorization.
10. No test for this path (an ID-token-only refresh where the save fails and the CAS clear succeeds). The only refreshForIDToken test is service_test.go:847. Add one service-level test over the user-keyed wrapper with a failing save, asserting the stored credential is served, the row is kept with an empty refresh token, and a read after the access token expires needs authorization; it would cover finding 9.
Design: user-keyed mode is now derived from the storage where it is consumed instead of a flag passed through four components, and the persist-failure cleanup is split by mode (delete without the option, CAS-clear with it). That is the right owner, and I found no break on the option-off or upgrade path.
🤖 Reviewed with Claude Code
rdimitrov
left a comment
There was a problem hiding this comment.
Re-review of 164363b: the code findings are fixed and the author's pushback was right; three docs/PR-text items are still open, so I'm leaving this as a comment.
Earlier findings:
- Delete after failed rotation save races a sign-in: resolved.
clearDeadRefreshTokennow clears with a compare-and-swap on the token it redeemed, so a newer token from a sign-in wins and a concurrently removed row is not recreated (checked in both memory and Redis). The remaining same-token carry-forward window only costs that sign-in's fresh access token, and it is documented. - Option-off behaviour change in the refresher: resolved.
checkRowOwnerandreplacedByNewerTokenare gone, and the option-off path is equivalent to main's delete. - Derive user-keyed mode once: resolved. It is now derived from the storage in each consumer, and the flag threading is removed. Every in-tree decorator has
Unwrap(), and the user-keyed layer is outermost. - PR size: withdrawn. Splitting is the maintainers' call, and the author's argument (each piece is inert without the wrapper, commits are ordered) is reasonable.
- Rollout order, rollback cleanup, "revoked" wording (second review): not resolved.
docs/arch/11-auth-server-storage.mdstill only says "turning it off later does the same in reverse". It needs a no-mixed-fleet rollout order and a rollback step for the leftoverupstream:user:*rows and indexes. - Option-off differences vs #7263: partly resolved. The refresher parts are gone and the PR body now discloses the rest. The summary line "behaves as on main" should say "except ID-token suppression keyed by row and the startup refusal of already user-keyed storage". Embedders that pre-wrapped their storage with the option off now fail at startup (
server_impl.go:371), and the release notes should say so. - #4122 in the adoption checklist: not resolved. The checklist has no item for a multi-replica fleet against an IdP that rotates refresh tokens. It is only in the PR body's known limits.
New findings:
8. pkg/auth/upstreamtoken/service.go:316: the log "upstream token row removed by failed refresh" is wrong for user-keyed mode, where the row is kept and only its refresh token is cleared. Reword it.
9. pkg/authserver/refresher_test.go:1373-1450: the new clear behaviour is only tested against a gomock store. Add one test over storage.NewMemoryStorage plus NewUserKeyedUpstreamStorage covering: failed rotated save, then the row is kept with an empty refresh token, then GetValidTokensForUser asks for re-authorization, then a sign-in on the same row works. This would also catch an Unwrap or keying regression.
Design: unchanged. The wrapper is outermost and fail-closed, mode is derived where it is consumed, and a failed rotated save clears the refresh token by CAS rather than deleting the shared row. Settling 5 to 7 (and fixing 8 and 9) would make this approvable.
🤖 Reviewed with Claude Code
After the refresher cleared a dead refresh token from a shared row, a row with no access-token expiry and an expiring ID token could be served for ever: the ID-token refresh path re-read the kept row and returned it, and later reads neither saw it expired nor could refresh it without a refresh token. Deleting the row, as the server does with the setting off, forced a new sign-in instead. With user-keyed storage the refresher now also sets the cleared row's access-token expiry to now, and the ID-token refresh path returns the refresh error when it reports the row removed or cleared instead of serving the stored credential. Either path then needs authorization right away, as with the setting off, while the row stays so a sign-in that raced the clear is not lost. The reader's log line for that case no longer says the row was removed. Co-authored-by: Mecatl <[email protected]>
Switching the option on a fleet changes which rows a refresh grant and a bearer request read, so replicas that disagree sign users out, and a client that refreshes before its user signs in again has its refresh token revoked rather than refused. Turning the option off leaves the user-keyed rows and indexes in Redis, rows for tokens that never expire without a TTL, and a later sign-in can carry a token forward from them. Add a rollout and rollback section: switch every replica at once, expect one sign-in per user, and on rollback delete the user-keyed row and index keys. Add an adoption checklist item for fleets of several replicas against an identity provider that rotates refresh tokens, where shared rows make the cross-replica rotation race far more likely. Co-authored-by: Mecatl <[email protected]>
|
Thanks for the two-replica test and the re-reviews. Everything still open is addressed in the last two commits. The cleared row served forever (your finding 9) was a real regression from the clear. With user-keyed storage the clear now also sets the row's ExpiresAt to now, and refreshForIDToken returns the error when the refresh reports the row removed or cleared instead of re-reading and serving it. Both paths need authorization right away, like the delete on main, and the row still stays so a sign-in that raced the clear isn't lost. There's a test over the real refresher, the wrapper on memory storage and InProcessService for both the expired access token case and the zero-expiry, expired-ID-token case. It checks that the row is kept with an empty refresh token, that the first and later reads need authorization, and that a new sign-in is served afterwards. The log line in credentialFor no longer says the row was removed. Rollout: docs/arch/11 has a rollout and rollback section now. Switch every replica at once, and expect one sign-in per user. A client that refreshes before its user signs in again is revoked, not just refused, and clients that refresh after that sign-in carry on. Both mixed-fleet directions are described as you measured them. On rollback, the user-keyed rows and indexes stay in Redis, and rows for tokens that never expire have no TTL. Until they're deleted, an option-off sign-in that gets no refresh token from the IdP can copy one forward from a leftover row, because GetLatestUpstreamTokensForUser still finds them through the user's index. The section says to delete both key patterns; leftover index members are then skipped as dangling. The adoption checklist has an item for #4122: with several replicas against an IdP that rotates refresh tokens and detects reuse, use user-affine routing or a single replica until #4122 is fixed. The PR body summary now names the two remaining option-off differences, row-keyed ID-token suppression and the startup refusal of storage that's already user-keyed. It also has a release-notes line for embedders who wrapped their own storage, and uses "revoked" rather than "refused" for the switch. And yes, #7263 stays open until the provider filter and the vMCP startup check land; both are stacked on this branch. |
rdimitrov
left a comment
There was a problem hiding this comment.
Re-review of 99e74a4: every open finding is resolved, and I found nothing new. pkg/auth/... and pkg/authserver/... pass locally with -race.
Open findings from the earlier reviews:
- Cleared row served forever (zero
ExpiresAtplus an expired ID token): resolved.clearDeadRefreshTokennow also setsExpiresAtto now, andrefreshForIDTokenreturns theErrNotFound-wrapped error before the re-read in user-keyed mode, so both the expired-access-token and the ID-token-only paths need authorization at once. On Redis the cleared row now gets a TTL ofDefaultRefreshTokenTTLinstead of none. The option-off path is unchanged. - Test for that path: resolved.
TestUserKeyedClearedRowNeedsAuthorizationruns the real refresher, the wrapper over memory storage andInProcessService. It checks both cases, that the row is kept with an empty refresh token, that a later read also needs authorization, and that a new sign-in is served afterwards. - Log line in
credentialFor: resolved. - Rollout and rollback: resolved. The new section in
docs/arch/11-auth-server-storage.mdsays to switch every replica at once, describes both mixed-fleet directions as measured (including revocation), and gives the rollback cleanup: deleteupstream:user:*andupstream:idx:user:*, with the copy-forward risk from leftover rows spelled out. - #4122 in the adoption checklist: resolved as item 11.
- Option-off differences in the summary and release notes: resolved in the PR body.
- Rest of #7263: tracked as stacked follow-ups; the issue stays open.
Design: unchanged. The wrapper is outermost, mode is derived from the storage where it is used, and a failed rotated save now leaves the shared row in the same "authorize again" state that a delete gives on main, without losing a sign-in that raced it.
🤖 Generated with Claude Code
Summary
"User-keyed upstream storage behind the embedder option" (#7263) moves upstream tokens from one row per login session to one row per user and provider, so all of a user's clients share the user's connections. #7308 added the storage wrapper and #7323 the per-user reads. This PR turns it on: a Go embedder can now opt in, and every part of the auth server that reads or writes upstream rows works correctly when one row is shared by several clients. With the option off, the server behaves as on main, except that ID-token refresh suppression is keyed by storage row and storage that is already user-keyed is refused at startup (see the user-facing section).
Config.UserKeyedUpstreamStorage(off by default) andrunner.WithUserKeyedUpstreamStorage()forNewEmbeddedAuthServerWithStorage.authserver.Newapplies the wrapper as the outermost storage layer, and each component (refresher, guard, sign-in handlers, token reader) detects it withstorage.IsUserKeyedon the storage it is given, so no component can run session-keyed logic over the shared rows. Runner-built storage,RunConfig,thv, the operator and vMCP cannot turn it on:NewEmbeddedAuthServerrefuses the option.ErrInvalidBinding) or an explicitly empty one (ErrNoCanonicalUser). Its reads go through the user-keyed layer, which refuses another user's row. When a rotated refresh token cannot be saved, it clears the dead token from the shared row with a compare-and-swap instead of deleting the row, so a token a sign-in stored in the meantime is kept.NewTokenValidatorrefuses to start when its upstream token reader reports user-keyed storage (new optionalupstreamtoken.UserKeyedReader) and the validator is unbound or lacks an audience or the in-process key provider. In that setup no token could load upstream tokens.authserver.Newrefuses storage that already contains the user-keyed layer, with the option on or off, andConfig.Validaterefuses the option together withUpstreamFilter.docs/arch/11-auth-server-storage.mdcovers key layout, admission, refresh and sign-in behaviour, row lifetime, accepted races, and an adoption checklist for embedders. Related pages are updated.Part of #7263.
Required by the wrapper PR (#7308)
DeleteUpstreamTokens, revokes on a confirmed rejectionrefresh_grant_guard_user_keyed.go, chosen inrefreshGrantValidatorChainTestUserKeyedUpstreamRefreshGuard,TestIntegration_UpstreamRefreshGuard_UserKeyedErrNoCanonicalUser; other read failures grant with one WARNTestUserKeyedUpstreamRefreshGuard_Storagerefresher.gowithCanonicalUserTestUpstreamTokenRefresher_UserKeyed_ContextUsercallback.go,device_verification.goTestUserKeyedStorage_DeviceFlow,TestUserKeyedStorage_TwoClientsShareConnections; the JWT bearer grant runs over the wrapper inTestUserKeyedStorage_JWTBearerReplayRefusedauthserver.New, after the runner'sDCRCredentialStorecheckserver_impl.goTestUserKeyedStorage_ServerWiring,TestUserKeyedStorage_RememberedConsentAndDCRTestUserKeyedStorage_DisconnectThroughIDPTokenStorage,TestUserKeyedStorage_ReferenceEmbedderType of change
Test plan
pkg/auth,pkg/auth/upstreamtoken/...,pkg/authserver/...,pkg/authz/authorizers/cedar/) with-racegolangci-lintandgo veton the touched packages)TestUserKeyedStorage_ReferenceEmbedderwires the server the way the adoption checklist tells an embedder to, over memory and Redis. Two clients share one user's connections, a refresh grant keeps working, a disconnect shows up on the next request,DeleteUserremoves the rows, and each miswiring from the checklist produces its documented symptom. The guard, refresher and carry-forward tests drive each race named below through storage hooks, without sleeps.Changes
pkg/authserver/config.go,server_impl.go,server.gopkg/authserver/refresher.gopkg/authserver/refresh_grant_guard.go,refresh_grant_guard_user_keyed.gopkg/authserver/server/handlers/callback.go,device_verification.go,handler.gopkg/authserver/runner/embeddedauthserver.goWithUserKeyedUpstreamStoragepkg/authserver/storage/user_keyed_upstream.goIsUserKeyed, used by every component to detect the layerpkg/auth/token.go,pkg/auth/upstreamtoken/service.go,types.goUserKeyedReader, validator startup check, suppression keyed by rowdocs/arch/11-auth-server-storage.md,17-token-exchange-delegation.md,README.md,docs/middleware.md,docs/redis-storage.mdDoes this introduce a user-facing change?
Only for Go embedders that turn the option on, plus two changes that apply without it:
storage.NewUserKeyedUpstreamStorage(from Add user-keyed upstream token storage #7308) without the option, and the session-keyed guard then never refused a refresh. After,authserver.Newrefuses it at startup. Release notes: an embedder that wrapped its own storage this way must remove the wrapping and set the option instead.With the option on:
invalid_grant) and the row is kept with its refresh token cleared, so the user's other clients have to sign in again once their access token expires.server_error(HTTP 500 on the device confirmation page).UpstreamFilter.Special notes for reviewers
WithUserKeyedUpstreamStorageand the adoption checklist name the calls:DeleteUpstreamTokensForProvideronIDPTokenStorage()with the canonical user on the context, andDeleteUser. Mecatl's sign-out and revocation work (Sign-out and revocation mecatl#2568) is the first consumer.GetLatestUpstreamTokensForUsercan still return session-keyed rows written before the switch.pkg/authservernow importspkg/auth/upstreamtokenfor the guard's per-user reader. There is no cycle:upstreamtokenimports only the auth server's storage, identity and upstream packages, and no MCP-specific code crosses it.