Skip to content

Wire user-keyed upstream storage into the auth server - #7332

Merged
jhrozek merged 13 commits into
mainfrom
user-keyed-storage-v2-3-server
Nov 26, 2026
Merged

jhrozek merged 13 commits into
mainfrom
user-keyed-storage-v2-3-server

Conversation

@jhrozek

@jhrozek jhrozek commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

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

  • Opt-in. Config.UserKeyedUpstreamStorage (off by default) and runner.WithUserKeyedUpstreamStorage() for NewEmbeddedAuthServerWithStorage. authserver.New applies the wrapper as the outermost storage layer, and each component (refresher, guard, sign-in handlers, token reader) detects it with storage.IsUserKeyed on 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: NewEmbeddedAuthServer refuses the option.
  • Refresher. It takes the canonical user from the row when the context has none, and refuses a different user (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.
  • Refresh grant guard. A user-keyed variant checks only the identity provider's row (the first upstream) and deletes no row. It grants a live, owned row without calling the provider. It refuses on a missing, empty or expired row without a refresh token, a rejection, another user's row, or no canonical user. It revokes the presented grant when a new sign-in would fix the cause, and after a confirmed rejection it clears the rejected refresh token from the shared row with a compare-and-swap.
  • Sign-in carry-forward. When the provider returns no refresh token, the browser callback and the device flow read the prior token from the shared row itself and write with compare-and-swap, so a sign-in never puts an obsolete token on the row or erases one another client stored. Losing to a concurrent write of the same upstream account merges the sign-in's new access and ID tokens with the winner's refresh token. Losing to a different account keeps that row and fails the sign-in with a server error.
  • ID-token refresh suppression is keyed by the storage row, so the session path and the per-user path no longer refresh the same row twice.
  • Startup checks. NewTokenValidator refuses to start when its upstream token reader reports user-keyed storage (new optional upstreamtoken.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.New refuses storage that already contains the user-keyed layer, with the option on or off, and Config.Validate refuses the option together with UpstreamFilter.
  • Docs. A "User-keyed upstream storage" section in docs/arch/11-auth-server-storage.md covers 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)

Requirement Where Proved by
Guard runs a user-keyed variant: subject as canonical user, only the identity provider's row, never DeleteUpstreamTokens, revokes on a confirmed rejection refresh_grant_guard_user_keyed.go, chosen in refreshGrantValidatorChain TestUserKeyedUpstreamRefreshGuard, TestIntegration_UpstreamRefreshGuard_UserKeyed
Refuses on ErrNoCanonicalUser; other read failures grant with one WARN same TestUserKeyedUpstreamRefreshGuard_Storage
Refresher sets the canonical user from the row when absent refresher.go withCanonicalUser TestUpstreamTokenRefresher_UserKeyed_ContextUser
Callback and device verification set the user before writing; token exchange touches no upstream row callback.go, device_verification.go TestUserKeyedStorage_DeviceFlow, TestUserKeyedStorage_TwoClientsShareConnections; the JWT bearer grant runs over the wrapper in TestUserKeyedStorage_JWTBearerReplayRefused
Wrapper applied outermost inside authserver.New, after the runner's DCRCredentialStore check server_impl.go TestUserKeyedStorage_ServerWiring, TestUserKeyedStorage_RememberedConsentAndDCR
Disconnect and user deletion Left to the embedder (see notes) TestUserKeyedStorage_DisconnectThroughIDPTokenStorage, TestUserKeyedStorage_ReferenceEmbedder

Type of change

  • New feature

Test plan

  • Unit tests, scoped to the touched packages (pkg/auth, pkg/auth/upstreamtoken/..., pkg/authserver/..., pkg/authz/authorizers/cedar/) with -race
  • Linting (golangci-lint and go vet on the touched packages)

TestUserKeyedStorage_ReferenceEmbedder wires 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, DeleteUser removes 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

File Change
pkg/authserver/config.go, server_impl.go, server.go Option, wrapping, startup refusals, accessor GoDoc
pkg/authserver/refresher.go Canonical user; with user-keyed storage, clear the dead refresh token by compare-and-swap instead of deleting the row
pkg/authserver/refresh_grant_guard.go, refresh_grant_guard_user_keyed.go User-keyed guard
pkg/authserver/server/handlers/callback.go, device_verification.go, handler.go Compare-and-swap carry-forward; user-keyed mode derived from the storage
pkg/authserver/runner/embeddedauthserver.go WithUserKeyedUpstreamStorage
pkg/authserver/storage/user_keyed_upstream.go IsUserKeyed, used by every component to detect the layer
pkg/auth/token.go, pkg/auth/upstreamtoken/service.go, types.go UserKeyedReader, validator startup check, suppression keyed by row
docs/arch/11-auth-server-storage.md, 17-token-exchange-delegation.md, README.md, docs/middleware.md, docs/redis-storage.md Docs

Does this introduce a user-facing change?

Only for Go embedders that turn the option on, plus two changes that apply without it:

  • ID-token refresh suppression. Before, it was keyed by session and provider. After, it is keyed by the storage row, so storage that maps several sessions to one row suppresses repeat ID-token refreshes across them. Nothing changes for the in-tree session-keyed storage.
  • Storage that is already user-keyed. Before, an embedder could pass storage it had wrapped with 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.New refuses 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:

  • Failed save of a rotated refresh token. The row is kept and its refresh token cleared, so the user authorizes again once the access token expires; a token a sign-in stored in the meantime is kept. With the option off the row is deleted, as on main.
  • Refresh grants. Every client of a user shares that user's upstream tokens. A refresh grant is checked against the identity provider's row only. After a confirmed rejection, the client's grant is revoked (400 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.
  • Sign-in. A sign-in that races a sign-in of a different upstream account for the same user fails with server_error (HTTP 500 on the device confirmation page).
  • Turning the option on or off. Switch every replica at once. Existing session-keyed rows are not read, so each user signs in once more. A client that refreshes before its user has signed in again has its refresh token revoked, not just refused; clients that refresh after that sign-in carry on. On a mixed fleet users lose their sessions as they move between replicas. Turning it off leaves the user-keyed rows and indexes in Redis (rows for tokens that never expire have no TTL); the storage docs give the cleanup step.
  • Startup. These configurations now fail at startup instead of misbehaving at request time:
    • a validator that is unbound or has no audience or in-process key provider, given a reader over user-keyed storage;
    • storage that already contains the user-keyed layer;
    • the option together with UpstreamFilter.

Special notes for reviewers

  • Deliberate differences from the option-off guard.
    • It revokes the presented grant by cause (when a new sign-in would fix it) instead of deleting the session's rows, because rows are shared.
    • It logs an uncertain check (transient provider failure, timeout, unreadable row) once at WARN per refresh grant where the option-off guard logs 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.
    • An unreadable Redis row grants with that WARN where the option-off guard skips the row and refuses.
  • Accepted races, documented at the site.
    • The guard's rejection recheck compares the row with a snapshot taken before the refresh. A sign-in that installs a new token in between, which the provider then rejects, is taken for a successor and granted once; the next refresh is refused and revoked.
    • The guard's clear compares only the refresh token. A sign-in that carries the same token forward between the recheck and the clear loses its new access token, and the user signs in once more.
    • The refresher's clear after a failed save also compares only the refresh token. A sign-in that carried the same dead token forward just before the swap loses its fresh access token, and the user signs in once more.
    • Closing these needs a storage method that compares more than the refresh token. That would change the storage interface every embedder implements, so it is not in this PR.
  • Synthetic providers have no stable subject, so a refresh token is carried forward without an account check, as it is today with the option off. The docs state this limit.
  • Disconnect and user deletion are the embedder's job. A row for a token that never expires has no storage lifetime, and with the option on neither the refresher nor the guard deletes a row (the callback's teardown after a confirmed identity mismatch remains, which the user-keyed layer makes unreachable in practice). WithUserKeyedUpstreamStorage and the adoption checklist name the calls: DeleteUpstreamTokensForProvider on IDPTokenStorage() with the canonical user on the context, and DeleteUser. Mecatl's sign-out and revocation work (Sign-out and revocation mecatl#2568) is the first consumer.
  • Known limits, documented:
    • GetLatestUpstreamTokensForUser can still return session-keyed rows written before the switch.
    • Concurrent refreshes across replicas are serialized only by compare-and-swap ("Handle multi-pod refresh token rotation race condition" (Handle multi-pod refresh token rotation race condition #4122)).
    • When an upstream is removed or renamed, its rows make clients get 401 while the guard grants, until the embedder deletes them.
  • New import: pkg/authserver now imports pkg/auth/upstreamtoken for the guard's per-user reader. There is no cycle: upstreamtoken imports only the auth server's storage, identity and upstream packages, and no MCP-specific code crosses it.
  • Size. 14 non-test files and about 925 production lines, over the usual guidance. It is one logical change, though: each part only makes sense once the option can be turned on, and the commits are ordered so each one can be reviewed alone; the commits after the reference embedder test answer review comments.
  • The follow-up parts of User-keyed upstream storage behind the embedder option #7263 (loading only configured providers, and the vMCP startup cross-check) are stacked on this branch.

jhrozek and others added 8 commits November 26, 2026 15:24
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]>
@jhrozek
jhrozek requested a review from ChrisJBurns as a code owner November 26, 2026 14:29
@github-actions github-actions Bot added the size/XL Extra large PR: 1000+ lines changed label Nov 26, 2026
Codespell reads failSaves as a misspelling of "failsafes". Rename the
field to failStores.

Co-authored-by: Mecatl <[email protected]>
@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 26, 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.

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

  1. pkg/authserver/refresher.go, cleanupAfterRotatedPersistFailure / replacedByNewerToken: the "don't delete a row a sign-in just replaced" check is a read followed by an unconditional DeleteUpstreamTokensForProvider. 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.

  2. pkg/authserver/refresher.go: replacedByNewerToken and checkRowOwner run with the option off, so "behaves as on main" is not true. checkRowOwner returns ErrInvalidBinding for any re-read row whose UserID differs from (or is empty versus) the canonical user in the context; a session-keyed row with an empty UserID that refreshed fine before would now be refused. I could not confirm such rows exist, so please check MigrateLegacyUpstreamData and older rows. Fix: gate both on r.userKeyed, or state the change in the PR body and show old rows are unaffected.

  3. 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: call storage.IsUserKeyed(stor) where it is needed and delete handlers.WithUserKeyedUpstreamStorage, the bool parameters, the guard-selection switch and the one-line isUserKeyed wrapper.

  4. 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 the Config / 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 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.

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: NewEmbeddedAuthServer refuses it, and pkg/runner/runner.go and pkg/vmcp/cli/serve.go build 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, …) in callback.go).
  • Token exchange and ID-JAG sessions carry no tsid, so the guard skips them; the JWT bearer grant's ConsumeAssertionJWT passes 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

codecov Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.38188% with 5 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.51%. Comparing base (829427b) to head (99e74a4).
⚠️ Report is 7 commits behind head on main.

Files with missing lines Patch % Lines
pkg/authserver/refresh_grant_guard_user_keyed.go 97.18% 2 Missing ⚠️
pkg/authserver/server/handlers/callback.go 98.64% 1 Missing ⚠️
pkg/authserver/server_impl.go 92.30% 1 Missing ⚠️
pkg/authserver/storage/user_keyed_upstream.go 90.90% 1 Missing ⚠️
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.
📢 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.

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]>
@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 26, 2026
@jhrozek

jhrozek commented Nov 26, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, all three code points were right and are fixed in the last two commits.

  1. The cleanup after a failed save no longer deletes anything with user-keyed storage. It clears the dead refresh token with a compare-and-swap on that token, like the guard does, and keeps the row. A token a sign-in stored in the meantime makes the swap lose and survives, and a row a disconnect removed isn't recreated. On success the error still wraps ErrNotFound, so an expired connection is still reported as needing authorization. With the option off the row is deleted exactly as on main. The one window left is a sign-in that carries the same dead token forward just before the swap; it loses its fresh access token and the user signs in once more, same shape as the guard's race. It's documented at the site.

  2. Option off is now the same as main in the refresher. I dropped checkRowOwner altogether rather than gating it. With the option on, every refresher read goes through the wrapper after withCanonicalUser has set the user, and the wrapper already returns ErrInvalidBinding for another user's row, so the check never fired there. With the option off it was the only place it acted, and that's the empty-UserID regression you spotted (MigrateLegacyUpstreamData does copy UserID as-is). withCanonicalUser stays, since it still refuses a caller passing another user's row. The two remaining option-off differences, suppression keyed by row and the startup refusal of storage that's already user-keyed, are in the PR body.

  3. Done. The refresher, sign-in handlers, guard selection and token reader all call storage.IsUserKeyed on the storage they get. handlers.WithUserKeyedUpstreamStorage, the refresher bool and the isUserKeyed wrapper are gone. This turned up one test decorator that hid the wrapper because it had no Unwrap, exactly the silent fallback you described.

  4. I'd like to keep this as one PR. Each piece only does anything once the wrapper is applied, the commits are ordered so you can review them one at a time, and the last two commits are the changes for this review if you want to look at just those.

@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 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; clearDeadRefreshToken does 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 ErrInvalidBinding for a foreign row, so the check only ever acted on option-off rows. The option-off delete path now matches main.
  • R1-3 flag threaded through four components: resolved. Mode is derived with storage.IsUserKeyed from the final stor; 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-1054 still 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 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 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:

  1. Delete after failed rotation save races a sign-in: resolved. clearDeadRefreshToken now 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.
  2. Option-off behaviour change in the refresher: resolved. checkRowOwner and replacedByNewerToken are gone, and the option-off path is equivalent to main's delete.
  3. 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.
  4. 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.
  5. Rollout order, rollback cleanup, "revoked" wording (second review): not resolved. docs/arch/11-auth-server-storage.md still 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 leftover upstream:user:* rows and indexes.
  6. 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.
  7. #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

jhrozek and others added 2 commits November 26, 2026 20:15
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]>
@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 26, 2026
@jhrozek

jhrozek commented Nov 26, 2026

Copy link
Copy Markdown
Contributor Author

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 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 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 ExpiresAt plus an expired ID token): resolved. clearDeadRefreshToken now also sets ExpiresAt to now, and refreshForIDToken returns the ErrNotFound-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 of DefaultRefreshTokenTTL instead of none. The option-off path is unchanged.
  • Test for that path: resolved. TestUserKeyedClearedRowNeedsAuthorization runs the real refresher, the wrapper over memory storage and InProcessService. 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.md says to switch every replica at once, describes both mixed-fleet directions as measured (including revocation), and gives the rollback cleanup: delete upstream:user:* and upstream: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

@jhrozek
jhrozek merged commit 9a27ec4 into main Nov 26, 2026
47 of 49 checks passed
@jhrozek
jhrozek deleted the user-keyed-storage-v2-3-server branch November 26, 2026 19:49
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.

2 participants