Repository navigation
Description
Scope update (2026-11-24). The fix is storing connections per user
instead of per login. It lands in two parts:
- for Go embedders, behind an option: "User-keyed upstream storage behind
the embedder option" (User-keyed upstream storage behind the embedder option #7263); - for runner-built and operator-managed deployments: this issue.
This issue now covers: user keying for runner-built storage, with existing
tsid rows migrated on first read (copied with store-if-absent, then
deleted); the refresher deleting a row only if it still holds the refresh
token it redeemed; one account per provider (a new connection for a
provider replaces the existing row, and a concurrent refresh never
overwrites the replacement); a dead provider dropping out of an
interactive request (except the identity provider) instead of a 401; the
kind test harness (every backend call recorded, login through a second
upstream) and an upgrade test. It ships after "Serialize upstream refresh
across replicas" (PR #7031), and its release needs that PR's test of two
refreshers contending for one row to pass. The stable-session-ID approach
and the opt-in setting are replaced. The connect entry point, the
reconnect trigger and their tests move to "vMCP: answer a call for an
unconnected provider with a URL elicitation carrying the connect link"
(#7188).
Summary
Upstream tokens are stored under a session ID that is freshly generated on every /oauth/authorize. nextMissingUpstream, which decides which chain legs still need an upstream authorization, only reads tokens for the current session. Credentials collected by an earlier authorization for the same user remain in storage, but the path that would evaluate whether they can be reused never runs. As a result, every re-authorization redirects through every upstream in the chain again.
This is the "Root cause A" of #5047. That issue was closed after root cause B (the callback clobbering a prior refresh token) was fixed; the session-keyed storage was left in place, with a note that it deserved its own issue:
did the session-keyed-storage -> user-keyed-storage fix ship as well for root cause A?
No, let me file a separate issue for it. It's something we should do, just separately and with care.
I could not find that follow-up issue, so this is it. It is distinct from #6406 / #6407, which cover credential reads for session-less delegated agents; this issue is about reusing existing connections during interactive browser re-authorization.
Root cause
pkg/authserver/server/handlers/authorize.go mints a fresh session on every authorize request:
pending := &storage.PendingAuthorization{
...
SessionID: rand.Text(), CreatedAt: time.Now(),
}pkg/authserver/server/handlers/handler.go then resolves the next chain leg against that session alone:
func (h *Handler) nextMissingUpstream(ctx context.Context, sessionID string, chain []string) (string, error) {
stored, err := h.storage.GetAllUpstreamTokens(ctx, sessionID)
...
for _, name := range chain {
tokens, ok := stored[name]
if !ok || tokens == nil {
return name, nil // no token stored for this leg
}
if tokens.ExpiresAt.IsZero() || !tokens.IsExpired(time.Now()) {
continue // live token satisfies the leg
}
if !h.refreshExpiredLeg(ctx, sessionID, name, tokens) {
return name, nil
}
}
return "", nil
}The skip-and-refresh logic exists, but it only sees tokens collected under the newly generated session ID. Credentials from earlier sessions are not considered, so subsequent upstream legs are visited again. In practice the function only helps within one in-flight authorization.
A user-keyed lookup already exists in storage and is already called: maybeCarryForwardRefreshToken uses it in callback.go to preserve a prior refresh token, which is the root-cause-B fix from #5047:
prior, err := h.storage.GetLatestUpstreamTokensForUser(ctx, subject, providerID)So the storage capability is present; the chain-walk path does not consult it.
beginIfRemembered does not help here. It skips the consent page, not the upstream chain.
Verified against main at 9adad0a.
Production observation
Deployment: a vMCP gateway with an embedded auth server, Redis session and auth storage, fixed signing/HMAC keys, and five upstream providers (okta as the mandatory identity leg, plus atlassian, slack, salesforce, and an internal API's provider, called internal below). It runs a fork carrying the group-based upstream filter from #6675 and additional upstream-error logging with a reordered pending-authorization lookup in callback.go; neither changes the chain-walk or carry-forward logic above.
We added a new backend to a group, which added its provider (internal) to the upstream chain for everyone in that group. The first visible symptom was a failing backend call with ErrUpstreamTokenNotFound (pkg/vmcp/auth/strategies/upstream_inject.go), because the live session had no row for the new provider. Our client surfaced this as a permissions problem, and reconnecting (a fresh authorization) was the only way through. When users reconnected, they reported being redirected through the login chain from the start, not only to the new internal provider.
Storage is consistent with that: across 251 upstream:<session>:<provider> rows (74 sessions, 24 users, five days), every session holding an internal token also holds a row under the new session ID for each other provider in its effective chain, while the earlier sessions for the same users remain in storage:
sessions with internal |
providers held |
|---|---|
| 21 | atlassian, internal, okta, slack |
| 5 | atlassian, internal, okta, salesforce, slack |
The table supports the code path above but does not by itself prove that each provider was re-authorized, and I did not compare token values or issuance timestamps. Likewise, the fact that earlier rows carry refresh tokens does not mean they would have been usable (they may have expired, been revoked, or been affected by #6508). The point is that the reuse evaluation never runs.
Impact
Adding one backend that needs its own upstream provider sends every user in the matching group back through every upstream they had already connected, not only the new one. The same happens on any ordinary re-authorization. Each additional upstream adds one more leg to every re-authorization, and one more point at which an interrupted flow has to restart (see also #5162).
Proposed direction
The question this issue is asking:
Once the identity leg has established the canonical platform user, could subsequent legs reuse an existing credential for that user and provider, subject to explicit ownership, account-binding, client-scope, and revocation rules?
One possible approach is to let nextMissingUpstream fall back to GetLatestUpstreamTokensForUser for legs after the identity leg. This is not just a matter of adding a user-keyed lookup. The guard maybeCarryForwardRefreshToken uses does not transfer to that path: it compares the providerSubject the current provider's callback just returned against the stored row, and a path whose purpose is to skip that provider's callback has no such value to compare. It also skips the comparison entirely for synthetic providers. The account-binding rules would have to be defined for this path on their own terms.
This also overlaps with work already in flight:
- Redis user-keyed upstream token read does not verify row ownership #6273 reports that the Redis user-keyed read does not verify row ownership. Any new consumer of that read depends on this being resolved.
- Delegated client access to a user's connections #6406 / Add upstreamCredentialScope opt-in and enforce its issuer trust #6403 / Add a delegated-access marker that gates credential lookup for approved delegated tokens #6404 / Ownership-checked credential read for delegated tokens, keyed by user and routed provider #6407 build
upstreamCredentialScope: platformUser, a user-keyed credential read with a write-time one-row-per-(user, provider) invariant and explicit trust gates, for session-less delegated agent tokens. Ownership-checked credential read for delegated tokens, keyed by user and routed provider #6407 states that existing session-based deployments should see zero behavior change. Whether the chain walk should reuse that machinery, and whether a credential connected under one client may be adopted by another authorization at all, is a design call. Stored rows carryclient_id, so the information to scope it either way is present. - Embedded auth runtime DCR does not bind upstream refresh tokens to the DCR client generation #6508 raises a related constraint on safely reusing a prior credential: binding upstream refresh tokens to a DCR client generation.
A larger alternative is the original #5047 proposal: key upstream token storage by user rather than session outright, which touches tsid semantics, the downstream read paths, and revocation.
Related
- Upstream refresh tokens orphaned on re-authorization #5047: closed; this is its deferred root cause A
- vMCP: graceful degradation when one upstream IdP fails in multi-upstream auth #5162: the same "restart the whole chain from scratch" pain, triggered by an upstream failing mid-chain rather than by one being added
- vMCP: backend health/set changes are not propagated to live sessions (stale tool catalog until reconnect; no tools/list_changed) #5786: companion symptom when a backend is added; live sessions keep a stale tool catalog until the client reconnects
- Redis user-keyed upstream token read does not verify row ownership #6273, Add upstreamCredentialScope opt-in and enforce its issuer trust #6403, Add a delegated-access marker that gates credential lookup for approved delegated tokens #6404, Delegated client access to a user's connections #6406, Ownership-checked credential read for delegated tokens, keyed by user and routed provider #6407, Embedded auth runtime DCR does not bind upstream refresh tokens to the DCR client generation #6508: user-keyed credential reads and credential-reuse constraints already under design
Reproduction
- Configure an embedded auth server with an identity upstream followed by at least two additional upstreams, with persistent storage and fixed signing keys.
- Complete an authorization and confirm rows exist for every upstream under one session ID.
- Start a second authorization for the same user, with stored credentials for every upstream still present.
- Observe that the flow redirects through every upstream again and writes a second set of rows under a new session ID. The first set remains in storage, but the newly issued token's
tsidpoints only to the second session.
Adding a provider to the chain between steps 2 and 3 makes this visible at scale, but it is not required to reproduce it.
Activity
hellouz818 commentedon Oct 15, 2026
I'd like to take this on. Could you assign it to me? I'd start by proposing the credential-reuse design here—covering ownership, account binding, client scope, and revocation—and coordinating with #6406 / #6407 to avoid duplicating work. Once we agree on the direction, I'd move on to implementation.
JAORMX commentedon Oct 15, 2026
@hellouz818 assigned! Thanks for all the work!
hellouz818 commentedon Oct 16, 2026
Design proposal: credential reuse during re-authorization
@JAORMX Thanks for assigning this! As planned, I've outlined a proposed reuse model below, with three design questions I'd appreciate your guidance on, particularly around the overlap with #6406/#6407.
All code references below are against
mainat87ed79d94.Proposed direction
After the identity leg establishes the canonical platform user, later legs could reuse that user's existing provider credentials.
The key requirement is that the chain walk and subsequent MCP requests resolve to the same credential row and refresh coordination. A user-keyed lookup in
nextMissingUpstreamalone would skip the redirect, but the newly issued token'stsidwould still point to a session without that provider's credential. Copying credentials into separate session rows introduces a different problem: those rows could independently redeem the same rotating refresh token.I'd therefore propose sharing the credential row rather than copying it. A storage decorator using
CanonicalUserFromContextlooks like one possible approach; linking sessions to an existing row is another.Three decisions before implementation
Shared storage model and ownership. Should this reuse the durable-user storage model from Ownership-checked credential read for delegated tokens, keyed by user and routed provider #6407, with this issue owning interactive chain-walk behavior? The existing context accessors and callback comments appear to anticipate a
(gateway, user)-keyed storage decorator, but I'd like to confirm that interpretation before building on it.Downstream client scope. Should a credential connected through client A be reusable through client B for the same user?
UpstreamTokens.ClientIDdocuments same-client access, but I could not find a read-time check enforcing it. With one row per(user, provider), checking only the last writer'sClientIDcould make two clients repeatedly force each other through re-authorization. My preference is user-scoped credentials, subject to each client's authorization and consent requirements, withClientIDtreated as provenance. If client isolation is intended, we need either client-scoped rows or explicit client grants on the shared row.Opt-in. Should interactive reuse be enabled only under
upstreamCredentialScope: platformUserfrom Add upstreamCredentialScope opt-in and enforce its issuer trust #6403? That seems consistent with its permanentsessiondefault and compatibility contract, but I'd like to confirm whether interactive reuse belongs under the same switch.Suggested implementation boundary
Before enabling reuse, I'd include:
verifyChainIdentityand the relevant cleanup paths under shared-row semantics.I'd keep #6508's upstream-client generation binding and the reconnect/refresh races already deferred by #6407 as coordinated follow-ups, rather than expanding this issue to cover all of them.
Code analysis and lifecycle considerations
Why a lookup or copy alone is insufficient
The MCP-request path reads credentials through:
loadUpstreamTokens→GetAllUpstreamCredentials(ctx, tsid)→GetUpstreamTokens(ctx, sessionID, provider)See
pkg/auth/token.go:1253-1258andpkg/auth/upstreamtoken/service.go:117.A reused credential therefore needs to remain reachable from the new authorization's request path.
Copying a prior credential into a new session row solves reachability but creates independent refresh state:
ResolveUpstreamTokenRowIDmust distinguish physically different rows (pkg/authserver/storage/types.go:1231-1246), so process-local singleflight does not coordinate those copies.CompareAndSwapUpstreamTokensorders writes against the refresh token stored at each individual row; it does not coordinate redemption across separate rows.Two sessions could consequently redeem the same refresh token independently. Sharing a physical row avoids that additional source of duplication, although it does not itself eliminate the cross-replica refresh limitations documented in
docs/arch/11-auth-server-storage.md.The existing
maybeCarryForwardRefreshTokenis not proof that copying is safe for rotating providers. It checks whether the authorization-code exchange omitted a refresh token, not whether the provider rotates tokens on refresh (callback.go:411-450).Existing storage seams
WithPlatformUserandCanonicalUserFromContextdistinguish a canonical user used for storage keying from a validated request principal (pkg/auth/context.go:124-176).The callback attaches the resolved canonical user before storage operations (
callback.go:293-300), and the request-serving path supplies the validated identity during credential loading (pkg/auth/token.go:1330-1337).Several callback comments explicitly discuss a
(gateway, user)-keyed storage decorator, including preserving existing connector credentials on failed or canceled authorization attempts and deleting by provider rather than deleting every connector.These look like useful integration points, but I am treating the intended implementation as an open question.
Ownership and account binding
Reuse would apply only after the identity leg has established
principal.PlatformUserID. The identity leg itself would still be walked.The account comparison in
maybeCarryForwardRefreshTokencannot be applied directly: it compares the subject returned by the current provider callback, whereas reuse deliberately skips that callback.The write-time invariant proposed in #6407 — one upstream subject per
(canonical user, provider), replacing the existing connection on account change — appears to provide the corresponding model for reuse, subject to the client-scope decision above.Synthetic identities need explicit treatment:
Reconnection and revocation
Reuse needs an explicit bypass for replacing an existing connection. Two possible entry points are:
prompt=consent, although downstream consent and upstream reconnection are different operations, so overloading it would need justification.PendingAuthorization.SingleLeg, which already bypasses chain continuation but would also need a secure binding between the authenticated canonical user and the provider being reconnected.Provider-scoped revocation should likewise identify the canonical user and provider explicitly.
Effects of sharing rows
verifyChainIdentitycurrently compares the first provider's storedUserIDwith the user carried through the flow. If storage already selects and validates rows by canonical user, that check may become redundant. Its remaining protection should be documented before retaining or replacing it.refresher.go:255-275).Does this direction fit the intended model? Once those three decisions are settled, I can work on the chain-walk integration or the reconnect/replace path, coordinating the shared storage work with #6407.
jhrozek commentedon Oct 16, 2026
Hey @hellouz818 thanks for the detailed write-up and the production data. Both made this much easier to reason about. We went through the code paths and agree with your analysis. It's not just extra redirects. Because every reconnect walks every provider, it also:
This is a fair amount of delicate work and the authserver is a piece that also our other projects build on so we'd like to proceed with care and split this into two workstreams
There's a fairly small change that fixes what you hit in production, using today's storage schema. When the identity leg resolves a real (non-synthetic) user and a new opt-in setting is on, the callback replaces the random session ID with a stable one derived from the user. The chain walk then sees the rows the user already has and only redirects for providers that are missing or broken. In your case, adding the internal backend would mean one redirect to that provider instead of the whole chain. All of the user's clients share one row per provider, nothing is copied, and the request path still reads by tsid, so delegated tokens still can't reach upstream credentials.
On your three questions, briefly:
It does need a few things around it to be safe:
I think we could write the proposal either here or in a small scoped RFC - this could be something that would be implemented fairly quickly and would solve the issues you encountered.
The broader question, how upstream credentials should be owned by users or agents working on behalf of users rather than sessions, overlaps heavily with the work we have planned for agents reading a user's credentials (#6403, #6404, #6407: an opt-in setting, a token claim marking a real user, and the user-keyed read itself). Your proposal already covers much of the same ground: shared rows instead of copies, account binding, client scope, revocation. We'd rather settle those decisions once, in an RFC, than piece by piece across issues.
We'd be happy to have you work on that with us: write the RFC with us so that we can reason about the storage changes and consequences of them on one place rather than in disjoint issues and PRs. The way we do it is to submit a proposal against the stacklok rfc repo, discuss is there, then split the RFC into issues and work on those.
Would you be interested in working with us on either of those?
hellouz818 commentedon Oct 20, 2026
@jhrozek Thanks for going through this so carefully — I'd be happy to work on both!
1. Scoped fix
The stable-session-ID approach sounds right to me. It addresses the production issue with the current schema, keeps the request path reading by
tsid, and avoids copying credential rows and introducing separate refresh state. I'd like to take this on.Agreed on giving interactive reuse its own opt-in setting, separate from
platformUser, and on sharing credentials across a user's clients withClientIDrecording provenance.I'll write up the scoped proposal here first, then open an implementation PR once we've agreed on the approach. We can reference the agreed design from the broader RFC.
I'd cover:
verifyChainIdentityunder the new session ID scheme.2. User-keyed storage RFC
I'd like to work on the broader RFC with you. I agree that ownership, account binding, client scope, and revocation should be settled together rather than separately across issues.
I can put together an initial draft in
stacklok/rfcscovering storage and credential ownership based on the analysis above, and would appreciate your input on the delegated-agent requirements from #6403/#6404/#6407. If you already have a draft underway, I can contribute to that instead.I'll start with the scoped proposal so we can address the production problem without waiting for the broader storage work. The two efforts should stay aligned on shared credential semantics, while keeping interactive reuse independent from delegated-agent access.
hellouz818 commentedon Oct 20, 2026
Scoped proposal: interactive credential reuse with a stable credential session ID
@jhrozek Following up on the scoped fix, here's the proposed approach. It preserves session-keyed storage and does not introduce user-keyed reads for delegated agents. References are against
mainat89b1bd28f.1. Opt-in and stable ID selection
Introduce a separate opt-in setting, disabled by default and independent of
upstreamCredentialScope: platformUser.After the identity leg resolves a real, non-synthetic canonical user, select a stable credential session ID before storing that leg's credential. The chain walk, subsequent writes, and issued token's
tsidall use that ID, sharing existing records rather than copying them.I'd derive it with HMAC-SHA256 over a versioned domain, auth-server namespace, and canonical ToolHive user ID (
user.ID), using length-prefixed inputs. I'd omit the identity provider so linked identities resolving to the same canonical user share one credential session.My preference is a dedicated persistent key shared across replicas, with configuration validation failing if reuse is enabled without it. Rotation would require an explicit migration or fallback strategy for new authorizations to reuse old records.
Synthetic identity legs retain today's behavior. Later callbacks preserve the ID selected by the first leg. The ID is visible through
tsid; it does not replace authenticated-user binding or ownership checks.2. Chain walk and unusable credentials
The identity leg still runs. For each subsequent required provider:
I'd reuse
pkg/auth/oautherr.IsRejectedRefreshGrant. Registration errors such asinvalid_clientand transient provider/storage failures would remain distinct and would not automatically trigger re-login or deletion.Revoked-but-unexpired access tokens need an explicit scope decision: provider-specific validation during the walk, or failure at use followed by reconnection. We cannot assume every provider offers a generic validation endpoint.
3. Explicit reconnect
I'd add a provider-specific reconnect flow, using
PendingAuthorization.SingleLegwhere appropriate. At89b1bd28f, it has no non-test producer, so this would add the entry point that initiates such a flow rather than only reuse the callback's existing bypass branch. I'd keep this separate from downstreamprompt=consent.The flow must bind the authenticated canonical user to the selected provider. It would preserve the existing credential until a successful exchange and account-binding validation, then replace it. Cancellation or exchange failure would leave the existing connection intact.
4. Shared-record lifecycle and identity checks
Credentials are shared across the user's clients, with
ClientIDrecording provenance. Revoking one downstream client's token should not delete shared upstream credentials.I'd review callback cleanup on confirmed identity mismatch, refresher deletion after rotation-persistence failure, and expiry/index behavior under shared records. Refresh and reconnect writes must also prevent stale refresh work from overwriting a replacement connection.
I'd retain ownership checks and document what
verifyChainIdentitystill protects before changing it.Points for review
Does this boundary look right? Once we agree on the derivation and lifecycle semantics, I'll start with session-ID selection and chain-walk integration, followed by reconnect.
Validation plan
tsidand the chain walk resolve to the same records.Code references — main at 89b1bd2
pkg/authserver/server/handlers/callback.go:256-335.pkg/authserver/server/handlers/handler.go,nextMissingUpstream.callback.go:707-725.callback.go:752-765;verifyChainIdentityat:886.pkg/auth/oautherr/oautherr.go,IsRejectedRefreshGrant.pkg/authserver/refresher.go:264.pkg/authserver/storage/memory.goandredis.go.pkg/authserver/storage/redis_keys.go,DeriveKeyPrefix.pkg/authserver/config.go.tsidlookup:pkg/auth/token.go,loadUpstreamTokens.jhrozek commentedon Oct 20, 2026
Thanks, this looks right to me. Two requests from the scheduled-tasks side:
sub), with the same key and version. The stamping itself is separate work behind its own setting; this issue only needs the derivation to be reusable.tsidis visible to clients, so it can't be the only thing standing between a token and a row.On your review points: derivation as proposed works for us. For reconnect, please keep the stable ID when a credential is replaced, so long-lived grants pick up the new credential. For revoked tokens, "fail at use" is fine, as long as a request with no browser gets a clear "needs authorization" answer rather than a redirect or a 403.
jhrozek commentedon Oct 21, 2026
Two more points on the scoped proposal, both from rows now being shared across a user's clients, plus an update to my earlier request.
1. Rows for providers whose tokens never expire disappear about 37 days after they were connected. A row's storage lifetime is
ExpiresAt + 30d, orSessionExpiresAt + 30dwhen the token has no expiry (pkg/authserver/storage/redis.go~1409-1426,memory.go~1246).SessionExpiresAtis set only when the callback writes a row (callback.go~315), and the refresher carries it forward unchanged (refresher.go~185-202). With stable IDs the chain walk skips live rows (handler.go~439-441), so a later sign-in never rewrites a GitHub OAuth App or Slack row. The row then expires about 37 days after the first connection, however often the user signs in. Suggestion: when the chain walk reuses a stored row during an interactive sign-in, extend its storage lifetime (a CAS touch). Non-interactive reads should not extend it.2. The refresher's delete after a failed rotation should be conditional. When persisting a rotated refresh token fails, the refresher deletes the row unconditionally (
refresher.go~255-275). With one row per user and provider shared by all clients, that can delete a replacement credential the user connected in the meantime. Suggestion: delete only if the row still holds the refresh token that was redeemed (compare-and-delete), otherwise leave it.3. Update to my request 1. We dropped the plan to stamp the stable ID onto tokens issued by token exchange. The derivation still needs to be a reusable function, but the new caller is the credential read for delegated tokens (#6407): it derives the stable ID from the token's user at read time, inside the upstream token service, and never puts it in a token. Same key, version and namespace as the callback. Request 2 (reads by the stable ID rely on the owner comparison from #6176) stands.
hellouz818 commentedon Nov 2, 2026
@jhrozek Thanks, these all make sense. I'll incorporate them into the scoped fix.
tsidremains as proposed.Proposed PR order:
Does that ordering work for you?
jhrozek commentedon Nov 24, 2026
Hi, a heads-up on scope. We ended up fixing this by keying stored
connections by user rather than by a stable session ID, and it's split in
two: the embedder path goes into a new issue, "User-keyed upstream storage behind the embedder option" (#7263), so Mecatl isn't waiting on
the runner work, and this issue keeps the runner-built side, the refresher
fix, and the rule that a new connection replaces the old row. The part that
starts a reconnect (the connect entry point and its tests) moved to "vMCP:
answer a call for an unconnected provider with a URL elicitation carrying
the connect link" (#7188), since that's the issue that hands users the link. I've updated the
description at the top. Sorry for the churn after the plan we'd agreed.