Skip to content

Add user-keyed upstream token storage - #7308

Merged
jhrozek merged 4 commits into
mainfrom
user-keyed-storage-v2-1-wrapper
Nov 25, 2026
Merged

jhrozek merged 4 commits into
mainfrom
user-keyed-storage-v2-1-wrapper

Conversation

@jhrozek

@jhrozek jhrozek commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Upstream tokens are stored per login session (tsid). A token without a tsid, 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.

  • Add 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 authenticated Identity. With no user in the context, every keyed method returns the new storage.ErrNoCanonicalUser.
  • Every read checks the row's owner before it reports expiry, because an expired row comes back together with its refresh token. GetUpstreamTokens returns ErrInvalidBinding for another user's row; GetAllUpstreamTokens skips it and logs one ERROR.
  • Writes need tokens whose UserID matches the context user. A token that never expires gets no storage lifetime, except for synthetic users (tk-…), whose subject changes on every login.
  • The user ID is escaped in the key (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 matching errors.ErrUnsupported, because a delete by session cannot be answered once rows are keyed by user.
  • DeleteUser also removes the per-user Redis index after the backend has deleted the user's rows.
  • A separate first commit fixes the Redis key layout in docs/redis-storage.md and docs/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

  • New feature

Test plan

  • Unit tests, scoped to the touched packages (pkg/authserver/storage, pkg/authserver/subjectresolver, pkg/authserver/server/tokenexchange) with -race
  • Linting (golangci-lint and go vet on 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, DeleteUser cleanup, 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

File Change
pkg/authserver/storage/user_keyed_upstream.go New wrapper
pkg/authserver/storage/types.go ErrNoCanonicalUser; contract notes on UpstreamTokenStorage and UpstreamTokens.ClientID
pkg/authserver/server/tokenexchange/jwt_bearer_handler.go Doc: the wrapper forwards ConsumeAssertionJWT
pkg/authserver/README.md List the wrapper among the built-in decorators
docs/redis-storage.md, docs/arch/11-auth-server-storage.md Correct the upstream key and index layout
pkg/authserver/storage/*_test.go, pkg/authserver/subjectresolver/resolver_user_keyed_test.go Contract suite and tests

Does 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

  • Not wired. Only the auth server is meant to apply this wrapper, around its own storage. Other callers do not set the canonical user, so wrapping a store by hand today would fail those calls. The type's GoDoc says so.
  • DeleteUser is overridden, not passed through. After the backend deletes the user, the wrapper calls DeleteUpstreamTokens on the user's row key in the wrapped store. In Redis that removes the upstream: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 return ErrNotFound before deleting anything; those rows expire by their TTL.
  • Unsupported delete. I wrapped errors.ErrUnsupported instead of exporting a new sentinel. A caller can tell the case apart with errors.Is, and the storage package gets no new exported error.
  • ConsumeAssertionJWT is forwarded the same way the CIMD, SPIFFE and client-admission decorators do it: embedding Storage would hide it, and the JWT-bearer handler deliberately does not unwrap past decorators.
  • Trust model. Reads ignore 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.
  • Tokens that never expire have no storage TTL, on purpose. Once rows are keyed by user, re-authorization skips connectors that are already connected (every upstream after the identity provider, whose row is rewritten on each login), so a connector's row is written at connect and not rewritten while the user keeps using it. A session bound would make a GitHub OAuth App connection disappear about 37 days after connect (7-day session plus 30 days), even for a user who uses it every day. Such rows are removed by an explicit action instead: a disconnect or revocation through DeleteUpstreamTokensForProvider, a reconnect that replaces the row, or DeleteUser. 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.
  • Required in the wiring PR (done in the third part of User-keyed upstream storage behind the embedder option #7263, after the per-user readers): the refresh guard runs a user-keyed variant that puts the requester's subject on the context as the canonical user, checks only the identity provider's row, and never calls 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 on ErrNoCanonicalUser. Other read failures still grant, with one WARN, as today. The refresher sets the canonical user from the expired row's UserID when 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 inside authserver.New as the outermost layer, after the runner's DCRCredentialStore check on the raw storage, so startup is unaffected.
  • Known limits once wired (handled in later parts of User-keyed upstream storage behind the embedder option #7263): GetLatestUpstreamTokensForUser passes 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.

jhrozek and others added 2 commits November 25, 2026 17:33
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]>
@jhrozek
jhrozek requested a review from ChrisJBurns as a code owner November 25, 2026 16:37
@github-actions github-actions Bot added the size/L Large PR: 600-999 lines changed label Nov 25, 2026

@rdimitrov rdimitrov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

  1. pkg/authserver/storage/user_keyed_upstream.go:240-250 (userRowForWrite): for a real user whose upstream token has no ExpiresAt, SessionExpiresAt is 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; only DeleteUser removes 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 via DeleteUpstreamTokensForProvider and add a test for it.

  2. 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-205 treats any GetAllUpstreamTokens error as "grant" (DEBUG log). With the wrapper and no canonical user on the refresh-grant context this returns ErrNoCanonicalUser, so the guard silently stops protecting. dropSession (:352) calls DeleteUpstreamTokens, which now always returns ErrUnsupported, 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:436 asserts stor.(storage.DCRCredentialStore) without storage.Unwrap (others use Unwrap, e.g. server_impl.go:383). If the wrapper is applied before that point, startup fails. Wrap after it or use Unwrap.
  3. 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 the UpstreamTokens.ClientID doc ("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]>
@jhrozek

jhrozek commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review!

  1. No TTL for tokens that never expire is on purpose. With user keying, re-authorization skips connectors that are already connected (everything after the identity provider, whose row is rewritten on each login), so a connector's row is written once at connect and isn't rewritten while the user keeps using it. If we kept the session bound, a GitHub OAuth App connection would disappear about 37 days after connect (7-day session plus 30 days), even for someone who uses it every day. These rows are removed by an explicit action instead: disconnect or revocation through DeleteUpstreamTokensForProvider, a reconnect that replaces the row, or DeleteUser. The user-facing disconnect belongs to the embedder (for Mecatl it's part of Sign-out and revocation mecatl#2568), and the option is opt-in, so nobody gets this without asking for it. I've added this to the PR body. Synthetic users keep the session bound because their subject changes on every login, so nothing would ever reconnect or disconnect those rows.

  2. All of these are handled in the server-wiring PR, the third in the stack (after the one adding the per-user readers), which is where the wrapper gets applied:

    • Guard: with the option on, authserver.New installs a user-keyed guard. It puts the requester's subject on the context as the canonical user and checks only the IdP row. A missing canonical user is refused, never granted; other read failures still grant with one WARN, as today. It never calls DeleteUpstreamTokens; on a confirmed rejection it revokes the presented refresh token and its access tokens instead of deleting rows. It has its own tests with the wrapper on.
    • Refresher: sets the canonical user from the expired row's UserID when the context has none, and returns ErrInvalidBinding on a mismatch.
    • The callback and device verification set the user before writing. Token exchange doesn't touch upstream rows.
    • DCR: the wrapper is applied inside authserver.New as the outermost layer, after the runner's DCRCredentialStore check on the raw storage, so startup isn't affected.

    I've listed these in the PR body as required in the wiring PR.

  3. Fair point on the ClientID doc. I reworded it so the same-client rule applies only to session-keyed storage, and added a trust-model note to the PR body.

@github-actions github-actions Bot added size/L Large PR: 600-999 lines changed and removed size/L Large PR: 600-999 lines changed labels Nov 25, 2026
@codecov

codecov Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 82.08%. Comparing base (10943fb) to head (4be6ed0).
⚠️ Report is 6 commits behind head on main.

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

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]>
@github-actions github-actions Bot added size/L Large PR: 600-999 lines changed and removed size/L Large PR: 600-999 lines changed labels Nov 25, 2026

@rdimitrov rdimitrov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Re-review of 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.

  1. 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.
  2. 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.
  3. ClientID trust-model doc: resolved. types.go now scopes the same-client rule to session-keyed storage and says user-keyed reads ignore ClientID.

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/L Large PR: 600-999 lines changed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants