Repository navigation
Add user-keyed upstream token storage - #7308
Conversation
The storage docs described the Redis upstream token rows as one key per session and the user reverse index as a set of session IDs. Since upstream tokens are stored per provider, each row key carries the provider name and the per-user index holds full row keys, not session IDs. Fix the key table and secondary index table in the Redis storage page, the example index entry, and the two reverse-index notes in the auth server storage architecture page. These errors predate the user-keyed storage work, so they are corrected on their own first. Co-authored-by: Mecatl <[email protected]>
Upstream connections are stored per login session, so a token without a tsid, or a user's second client, finds none of the user's connections. This is the first part of "User-keyed upstream storage behind the embedder option" (#7263). Add a storage wrapper that keys upstream rows by the canonical user from the authorization server's own context key and ignores the session ID. Every read checks the row's owner before the expiry check; a bulk read skips another user's row and logs it at ERROR. Writes need a canonical user that matches tokens.UserID. A token without expiry gets no storage TTL, except for synthetic users, whose subject changes on every login. DeleteUpstreamTokens returns an error matching errors.ErrUnsupported, because a delete by session cannot be answered once rows are keyed by user. The constructor refuses a nil inner storage instead of building a wrapper that panics on first use. DeleteUser also removes the per-user Redis index after the backend has deleted the user's rows, so an index left without a TTL by a token that never expires does not outlive the user; a failed cleanup is logged and does not fail the delete. A resolver test checks that the ID-JAG subject resolver still reads users and provider identities through the wrapper without a canonical user, and the JWT-bearer handler doc lists the wrapper among the decorators that forward ConsumeAssertionJWT. The wrapper is not applied anywhere yet; the auth server will apply it around its own storage, never the embedder. Co-authored-by: Mecatl <[email protected]>
rdimitrov
left a comment
There was a problem hiding this comment.
Design is right, but one behaviour in this PR needs a decision before the wiring lands: real-user rows are stored with no expiry.
Design: A decorator over the existing backends that re-keys upstream rows to (canonical user, provider) is the right place. It matches the CIMD/SPIFFE/client-admission decorators and needs no backend or interface change. Nothing constructs it yet, so there is no upgrade impact today. The key escaping is injective, owner checks happen before expiry is reported, and writes are bound to the context user.
-
pkg/authserver/storage/user_keyed_upstream.go:240-250(userRowForWrite): for a real user whose upstream token has noExpiresAt,SessionExpiresAtis cleared. Redis then writes the row with TTL 0 (and PERSISTs the index), and the memory backend never sweeps it. Before this, such a row died with the login session. Scenario: an IdP that issues non-expiring or refreshable tokens, user stops using ToolHive, access and refresh tokens stay stored indefinitely; onlyDeleteUserremoves them, and that does nothing for synthetic users. Fix: keep a session bound or a long fixed cap for real users too, or state where the wiring PR adds GC/logout cleanup viaDeleteUpstreamTokensForProviderand add a test for it. -
Wiring hazards the PR body should list as required in the follow-up (nothing breaks today, since nothing constructs the wrapper):
pkg/authserver/refresh_grant_guard.go:200-205treats anyGetAllUpstreamTokenserror as "grant" (DEBUG log). With the wrapper and no canonical user on the refresh-grant context this returnsErrNoCanonicalUser, so the guard silently stops protecting.dropSession(:352) callsDeleteUpstreamTokens, which now always returnsErrUnsupported, so dead rows stay. The wiring PR must set the canonical user on the guard/refresher/token-exchange contexts and delete per provider; please add a guard test with the wrapper on.pkg/authserver/runner/embeddedauthserver.go:436assertsstor.(storage.DCRCredentialStore)withoutstorage.Unwrap(others useUnwrap, e.g.server_impl.go:383). If the wrapper is applied before that point, startup fails. Wrap after it or useUnwrap.
-
Trust-model note for the PR body: reads no longer see
ClientID, so a second client's login overwrites the first client's row. That is the point of the feature, but theUpstreamTokens.ClientIDdoc ("only accessible to the same client") should be updated, and the PR should say wiring is opt-in.
🤖 Reviewed with Claude Code
The UpstreamTokens.ClientID doc still said tokens are only accessible to the client that obtained them, which contradicts the user-keyed note right after it: under UserKeyedUpstreamStorage every client of a user shares one row per provider. Co-authored-by: Mecatl <[email protected]>
|
Thanks for the review!
|
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #7308 +/- ##
==========================================
+ Coverage 81.98% 82.08% +0.10%
==========================================
Files 923 929 +6
Lines 93575 94203 +628
==========================================
+ Hits 76717 77327 +610
- Misses 16853 16871 +18
Partials 5 5 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
CodeQL flags the context user ID in the ERROR line logged when a bulk read skips a row owned by another user (clear-text logging of data from request headers). The caller's identity is already in the request logs, so keep only the row's owner and the provider. Co-authored-by: Mecatl <[email protected]>
rdimitrov
left a comment
There was a problem hiding this comment.
Re-review of 4be6ed0: still approve. All three earlier findings are settled, and the two new commits only change a doc comment, one log field and the matching test.
- Real-user rows have no expiry: withdrawn. The author is right that a session-bound TTL would drop a live connector (e.g. a GitHub OAuth App token) once the original session lapsed, since those rows aren't rewritten on later logins. Synthetic
tk-rows keep the session bound, and the PR body now documents the rule. - Wiring hazards: resolved for this PR. The PR body lists them as requirements for the wiring PR (user-keyed refresh guard that never deletes on
ErrNoCanonicalUser, refresher setting the canonical user, callback/device verification setting it before writes, wrapper applied outermost after the DCR check). Nothing constructs the wrapper here, so nothing is affected today. Please hold the wiring PR to that list. ClientIDtrust-model doc: resolved.types.gonow scopes the same-client rule to session-keyed storage and says user-keyed reads ignoreClientID.
No new findings. Dropping expected_user_id from the foreign-row log is fine; got_user_id and provider are enough to diagnose.
One thing to track in the wiring PR, not a blocker here: a user whose IdP token never expires and who stops using ToolHive keeps tokens in storage until DeleteUser or DeleteUpstreamTokensForProvider is called, so the wiring PR needs a disconnect or user-deletion path that calls them.
CI: the only failure is TestIntegration_RunConfigUpstreamFilter_MissingClaimFails (CloseIdleConnections called), the known httptest DefaultTransport flake in code this PR doesn't touch. Please re-run it.
🤖 Reviewed with Claude Code
Summary
Upstream tokens are stored per login session (
tsid). A token without atsid, or a second client of the same user, therefore finds none of the user's upstream connections, and the user has to connect every provider again. "User-keyed upstream storage behind the embedder option" (#7263) moves these rows to one row per user and provider. This PR is the first part: the storage wrapper on its own, not yet applied anywhere.storage.UserKeyedUpstreamStorage, a decorator that keys upstream token rows by the canonical user from the auth server's own context key (identity.CanonicalUserFromContext) and ignores the session ID. It never reads the user from an authenticatedIdentity. With no user in the context, every keyed method returns the newstorage.ErrNoCanonicalUser.GetUpstreamTokensreturnsErrInvalidBindingfor another user's row;GetAllUpstreamTokensskips it and logs one ERROR.UserIDmatches the context user. A token that never expires gets no storage lifetime, except for synthetic users (tk-…), whose subject changes on every login.upstream:user:{escaped}:{provider}in Redis), so no user ID can address another user's row. No backend change is needed.DeleteUpstreamTokens(delete by session) returns an error matchingerrors.ErrUnsupported, because a delete by session cannot be answered once rows are keyed by user.DeleteUseralso removes the per-user Redis index after the backend has deleted the user's rows.docs/redis-storage.mdanddocs/arch/11-auth-server-storage.md. Those errors predate this work: the docs described one key per session and an index of session IDs, while rows are per provider and the indexes hold full keys.Part of #7263.
Type of change
Test plan
pkg/authserver/storage,pkg/authserver/subjectresolver,pkg/authserver/server/tokenexchange) with-racegolangci-lintandgo veton the touched packages)The wrapper has a contract suite that runs against both the memory backend and miniredis. It covers owner checks on single and bulk reads, expired foreign rows, placeholder rows, write refusals, storage lifetime (including synthetic users), key escaping,
DeleteUsercleanup, and the missing-user cases. A resolver test checks that the ID-JAG subject resolver still reads users and provider identities through the wrapper without a canonical user.Changes
pkg/authserver/storage/user_keyed_upstream.gopkg/authserver/storage/types.goErrNoCanonicalUser; contract notes onUpstreamTokenStorageandUpstreamTokens.ClientIDpkg/authserver/server/tokenexchange/jwt_bearer_handler.goConsumeAssertionJWTpkg/authserver/README.mddocs/redis-storage.md,docs/arch/11-auth-server-storage.mdpkg/authserver/storage/*_test.go,pkg/authserver/subjectresolver/resolver_user_keyed_test.goDoes this introduce a user-facing change?
No. Nothing applies the wrapper yet; a later part of #7263 enables it through the auth server's configuration.
Special notes for reviewers
DeleteUseris overridden, not passed through. After the backend deletes the user, the wrapper callsDeleteUpstreamTokenson the user's row key in the wrapped store. In Redis that removes theupstream:idx:user:{escaped}set, which can otherwise stay forever: a token that never expires leaves the index without a TTL, and the index can name providers that are no longer configured. A failed cleanup is logged at WARN and does not fail the delete. When the user record does not exist (always the case for synthetic users), both backends returnErrNotFoundbefore deleting anything; those rows expire by their TTL.errors.ErrUnsupportedinstead of exporting a new sentinel. A caller can tell the case apart witherrors.Is, and the storage package gets no new exported error.ConsumeAssertionJWTis forwarded the same way the CIMD, SPIFFE and client-admission decorators do it: embeddingStoragewould hide it, and the JWT-bearer handler deliberately does not unwrap past decorators.ClientID, so every client of a user shares one row per provider, and a second client's login overwrites the first client's row. That is the point of the feature. Turning it on is opt-in: nothing applies the wrapper unless an embedder asks for it.DeleteUpstreamTokensForProvider, a reconnect that replaces the row, orDeleteUser. A user-facing disconnect is up to the embedder. Synthetic users (tk-…) keep the session bound, because their subject changes on every login and nothing would ever reconnect or disconnect those rows.DeleteUpstreamTokens(on a confirmed rejection it revokes the presented refresh token and its access tokens instead). It never treats a missing canonical user as a grant: it refuses onErrNoCanonicalUser. Other read failures still grant, with one WARN, as today. The refresher sets the canonical user from the expired row'sUserIDwhen the context has none. The callback and device verification set the user before writing; token exchange does not touch upstream rows. The wrapper is applied insideauthserver.Newas the outermost layer, after the runner'sDCRCredentialStorecheck on the raw storage, so startup is unaffected.GetLatestUpstreamTokensForUserpasses through and can still return session-keyed rows written before the switch. Concurrent refreshes across replicas are serialized only by compare-and-swap, so a shared row makes the existing multi-replica rotation race ("Handle multi-pod refresh token rotation race condition" (Handle multi-pod refresh token rotation race condition #4122)) easier to hit.