Repository navigation
Description
Summary
Upstream refresh tokens are orphaned when a user re-authorizes. Two independent mechanisms cause this: (1) storage is keyed by an ephemeral session ID that is freshly generated on every /authorize call, and (2) the callback stores the new IDP response verbatim, overwriting a previously-stored refresh token with the empty string when the provider does not re-issue one.
The second mechanism is most visible with providers that only return refresh_token on first consent or when prompt=consent is explicitly passed (Google OAuth 2.0 is a prominent example). After any re-authorization, the stored refresh token is effectively lost, and subsequent refresh attempts fail with ErrNoRefreshToken.
Root cause A — session-keyed storage
pkg/authserver/server/handlers/authorize.go:91 generates a fresh session ID on every /authorize:
pending := &storage.PendingAuthorization{
...
SessionID: rand.Text(), // ← fresh random on every /authorize
CreatedAt: time.Now(),
}pkg/authserver/server/handlers/callback.go:142 stores upstream tokens keyed by that session. The session ID is then embedded as the tsid claim in the issued JWT (pkg/authserver/server/session/session.go:120-123), and downstream read paths look up by tsid/session ID (pkg/auth/token.go:1189-1196, pkg/authserver/storage/types.go:222-240).
UserID (the internal ToolHive user subject) is stored as a field on UpstreamTokens (callback.go:138) but no read path uses it as a lookup key. It is only used for cleanup/metadata.
Consequence: any re-authorization mints a new session; the old session's tokens become unreachable through the normal read path.
Root cause B — callback clobbers prior refresh token
pkg/authserver/server/handlers/callback.go:131-142 stores idpTokens.RefreshToken verbatim, with no preservation of a previously-stored refresh token:
storageTokens := &storage.UpstreamTokens{
ProviderID: providerID,
AccessToken: idpTokens.AccessToken,
RefreshToken: idpTokens.RefreshToken, // empty if provider didn't re-issue
...
}
if err := h.storage.StoreUpstreamTokens(ctx, sessionID, providerID, storageTokens); err != nil {pkg/authserver/refresher.go:73-75 already has the correct pattern for the refresh path (preserve prior refresh token when provider omits a new one). The callback path does not mirror this.
Even if root cause A is fixed (e.g., switching to UserID-keyed storage), root cause B will still overwrite a good refresh token with the empty string on every re-auth where the provider does not re-issue a refresh token.
pkg/auth/upstreamtoken/service.go:135-136 then returns ErrNoRefreshToken:
if expired.RefreshToken == "" {
return nil, ErrNoRefreshToken
}Failure mode
- Initial consent completes. Upstream tokens, including a
refresh_token, are stored under sessionS1with key(S1, providerID). - Some time later, a new
/authorizecall is made (any reason — including the compound effect of Non-expiring upstream tokens incorrectly marked as 1h-expiring #5046 causing spurious refresh/reauth cycles). - Authorize handler mints a new session
S2. The new JWT'stsidclaim points atS2. - Callback completes. If the provider does not re-issue
refresh_token(e.g., Google withoutprompt=consent—pkg/authserver/upstream/oidc.go:367-369showsprompt=consentis optional, not default), the callback stores{AccessToken: new, RefreshToken: ""}at(S2, providerID). - When the new access token expires, the refresher reads from
(S2, providerID), findsRefreshToken == "", and returnsErrNoRefreshToken. The provider is then omitted from downstream responses with the log lineomitting provider with unrefreshable expired token(pkg/auth/upstreamtoken/service.go:114). - The user is forced to re-authorize. The cycle repeats.
Proposed fix
Two independent changes — neither alone is sufficient.
-
Key upstream tokens by
UserID, not session ID.- Add a
(user_id, provider_id) → tokensindex in both memory and Redis storage backends. - Update the downstream read path (
pkg/auth/token.go:1189-1196and friends) to resolvetsid → user_idvia the session store, then read upstream tokens byuser_id. - This is net-new index work;
UserIDis currently only metadata.
- Add a
-
Preserve prior refresh token in the callback. Before calling
StoreUpstreamTokens, load any existing record for(user_id, provider_id)and, ifidpTokens.RefreshToken == "", carry forward the existingRefreshToken. Mirror the pattern already used atpkg/authserver/refresher.go:73-75.
Related
Compounds with #5046. The fake 1h expiry described there triggers the re-authorization cascade that exposes this bug.
Reproduction
Assumes a Google OAuth client (OIDC) is configured as a ToolHive upstream with the default config (no prompt=consent set).
-
Start ToolHive with Google configured as an upstream OIDC provider.
-
As a user, complete the initial
/authorizeflow. Accept Google's consent screen. -
Verify the stored upstream tokens include a non-empty
RefreshToken. For the in-memory backend this can be inspected via the authserver's storage; for Redis, read theupstream_tokens:<session_id>:googlekey. -
Trigger a second
/authorizefor the same Google account, without the initial session being invalidated. This can be done by:- Calling the OAuth endpoint again from a fresh client registration, or
- Signing out of the ToolHive client and signing back in, or
- Any path that causes the client to restart the authorization flow.
-
Complete the flow. Google returns a new access token but no
refresh_token(this is Google's documented behavior withoutprompt=consent). -
Inspect the stored tokens under the new session's key:
RefreshTokenis now"". The previous session's tokens (with the good refresh token) still exist under the old session key but are unreachable via the new JWT'stsid. -
Wait for the new access token to expire (~1 hour with Google's default).
-
Trigger a downstream request that causes
InProcessService.GetAccessTokensto run. Observe the log line:omitting provider with unrefreshable expired token provider=google -
The Google upstream is now omitted from downstream responses until the user re-authorizes — which will reproduce the same failure.
Caveats
The claim "Google does not re-issue refresh tokens without prompt=consent" reflects Google's documented OAuth 2.0 behavior. The repo only shows prompt=consent is optional (pkg/authserver/upstream/oidc.go:367-369).
Activity
tgrunnagle commentedon Apr 28, 2026
Plan — Root Cause A: User-Keyed Upstream Token Storage
Context
Upstream OAuth tokens are stored at the composite key
(sessionID, providerID), wheresessionIDis freshly generated on every/authorize(pkg/authserver/server/handlers/authorize.go:91). The samesessionIDis embedded as thetsidJWT claim (pkg/authserver/server/session/session.go:120-123), and the downstream read path looks tokens up bytsid(pkg/auth/token.go:1189-1196). Re-authorization mints a new session, so previous tokens become unreachable.UserIDis already onUpstreamTokens(callback.go:138) but no read path uses it as a key.This plan rekeys upstream-token storage by
(userID, providerID). Root Cause B is not addressed here — it lands in a separate PR.Design Decisions
subclaim directly (not a session-store lookup).subis already populated as the ToolHive userID bysession.New(line 143). The JWT signature authenticates the claim — no separate storage round-trip needed.DeleteUpstreamTokens(userID)would wipe a user's good tokens on a re-auth that fails midway through a multi-upstream chain.redis_migrate.gorewrites legacyupstream:{sessionID}:{providerID}keys underupstream:{userID}:{providerID}using the embeddedUserIDfield.Files to Modify
Storage layer
pkg/authserver/storage/types.go:217-255— changeUpstreamTokenStorageandUpstreamTokenRefresherparameter names fromsessionIDtouserID. AddDeleteUpstreamTokensByProvider(ctx, userID, providerID) error. Update interface doc comment.pkg/authserver/storage/memory.go:36-39, 693-833— rename theupstreamKeyfield fromsessionIDtouserID; rename method parameters; addDeleteUpstreamTokensByProvider.pkg/authserver/storage/redis_keys.go— change primary key format toupstream:{userID}:{providerID}. The existinguser:upstream:{userID}SET is repurposed as the per-user provider index. Theupstream:idx:{sessionID}SET is dropped.pkg/authserver/storage/redis.go:818-1068— update thestoreUpstreamTokensScriptLua script to maintainuser:upstream:{userID}directly. UpdateGet/GetAll/Deleteand addDeleteUpstreamTokensByProvider.GetAllusesSMEMBERSonuser:upstream:{userID}thenMGET.pkg/authserver/storage/redis_migrate.go— addmigrateUpstreamTokensToUserKey(ctx, client, prefix)following the existingmigrateSingleUpstreamTokenpattern (lines 136-230).SCANforupstream:*:*keys (excludingidx:anduser:upstream:*), parse stored token, re-SETunderupstream:{UserID}:{ProviderID},SADDtouser:upstream:{UserID},DELlegacy key + legacyupstream:idx:{sessionID}set. Idempotent. Wire into the migration entrypoint at storage init.Callback handler
pkg/authserver/server/handlers/callback.go:142— passsubject(resolved userID) instead ofsessionIDtoStoreUpstreamTokens.pkg/authserver/server/handlers/callback.go:147, 286, 322, 335, 346, 355, 390, 404, 412— replace each bulkDeleteUpstreamTokens(ctx, sessionID)cleanup withDeleteUpstreamTokensByProvider(ctx, subject, providerID)for the providers actually stored in this in-flight chain. Where rolling back a chain, iterate the chain's stored providers (track locally as it progresses) and delete each.pkg/authserver/server/handlers/callback.go:332-340— the defense-in-depth identity-consistency check viaGetAllUpstreamTokens(sessionID)becomes a tautology under user-keyed storage. Drop theUserIDcomparison; keep the bulk read only if needed for chain accounting.Refresher
pkg/authserver/refresher.go:31-94—RefreshAndStoreno longer needs thesessionIDparameter; useexpired.UserIDfor both logging andStoreUpstreamTokens. Update interface signature inpkg/authserver/storage/types.go:250-255.Service layer
pkg/auth/upstreamtoken/service.go:51-174— rename thesessionIDparameter touserIDthroughout (GetValidTokens,GetAllValidTokens,refreshOrFail). Update the singleflight key (line 147) to use userID. Update log fields (session_id→user_id). Drop the now-unused sessionID parameter onRefreshAndStore(line 153).pkg/auth/upstreamtoken/types.go— update theServiceandTokenReaderinterface signatures.Read path (token validator)
pkg/auth/token.go:1184-1200—loadUpstreamTokensextractssubinstead oftsid:tsidclaim itself stays in the JWT (no JWT-structure change) — it's just no longer the upstream-token lookup key.Tests
Mechanical updates — change
sessionIDliterals/parameter values to userID in:pkg/authserver/storage/memory_test.go—TestMemoryStorage_UpstreamTokens(lines 429-580).pkg/authserver/storage/redis_test.go—TestRedisStorage_UpstreamTokens(lines 572-687).pkg/authserver/storage/redis_integration_test.go—TestIntegration_UpstreamTokens,TestIntegration_MigrateLegacyUpstreamData. Add a new integration test exercisingmigrateUpstreamTokensToUserKeyagainst legacy data.pkg/auth/upstreamtoken/service_test.go—TestGetValidTokens,TestGetAllValidTokens.pkg/auth/token_test.go—TestTokenValidator_loadUpstreamTokens,TestTokenValidator_Middleware. Update fixtures to put userID insuband assert lookup bysub.pkg/authserver/refresher_test.go— drop sessionID parameter fromRefreshAndStorecalls.pkg/authserver/integration_test.go—TestAuthorizeWithUpstreamTokenRefresh,TestUpstreamTokenRefreshForwardedToProxyMiddleware,TestSessionIDPreservedAcrossAuthorizationCodeRefresh,TestMultiUpstreamAuthorizationChain.pkg/vmcp/auth/factory/incoming_upstream_test.go—TestNewIncomingAuthMiddleware_OIDC_UpstreamTokens.pkg/authserver/server/handlers/callback_test.go— assertions that read by sessionID.task genafter interface signatures change.New regression test: in
integration_test.go, addTestReAuthorizationPreservesAccessToUpstreamTokensthat:/authorizefor user U with provider P; asserts tokens accessible./authorizefor U (mints a new sessionID/JWT).This guards Root Cause A and should fail on
main.What This Plan Does NOT Change
tsidclaim stays for now (used elsewhere for session correlation/logs); just no longer the lookup key. Removingtsidwould be a separate cleanup PR.RefreshTokenwith whatever the IdP returned. After this fix, re-auth where the IdP omitsrefresh_tokenwill overwrite a good refresh token in the user-keyed slot — same orphaning end-state, different mechanism. Must be followed by a Root Cause B PR.tsid-based revocation mechanism, if/when added, is a separate concern from upstream-token keying.Verification
Risks / Open Items
tgrunnagle commentedon Apr 28, 2026
Plan — Root cause B: Callback clobbers prior refresh token
Context
Per issue #5047, upstream refresh tokens are orphaned on re-authorization. Two independent root causes are described; this plan addresses root cause B only: the OAuth callback at pkg/authserver/server/handlers/callback.go:131-142 stores
idpTokens.RefreshTokenverbatim. When the upstream IDP omitsrefresh_tokenon a re-authorization (e.g., Google withoutprompt=consent), the new record is written withRefreshToken: "", overwriting the previously-stored good refresh token. Subsequent refresh attempts then fail withErrNoRefreshTokenand the user is forced to re-authorize again.The refresher already has the correct preservation pattern at pkg/authserver/refresher.go:73-75 — the callback must mirror it. The catch: the callback's
sessionIDis freshly generated on every/authorize(root cause A), so a same-keyGetUpstreamTokens(sessionID, providerID)lookup will not find the prior record. The fix needs a(userID, providerID)-keyed lookup.This is a partial-but-valuable fix on its own: even with root cause A unresolved, carrying the refresh token forward to the new sessionID lets the refresher succeed when the new access token expires, ending the re-auth cycle.
Approach
(userID, providerID)across any session.idpTokens.RefreshToken == "", load the prior record and copy itsRefreshTokeninto the newstorage.UpstreamTokensbefore storing.refresher.go— only fall back when the new value is empty.The new method also lays usable groundwork for a future root cause A fix (user-keyed read path) without committing the design.
Files to change
1. pkg/authserver/storage/types.go
Add a new method on
UpstreamTokenStorage:2. pkg/authserver/storage/memory.go
Implement via linear scan of
s.upstreamTokensfiltered byUserID == userID && ProviderID == providerID, returning the entry with the latestcreatedAt. This mirrors the existing scan pattern at memory.go:1012-1015. ReturnErrNotFoundwhen no match. Uses.mu.RLock().3. pkg/authserver/storage/redis.go
Leverage the existing
KeyTypeUserUpstream:{userID}set (already populated byStoreUpstreamTokensat redis.go:925):SMEMBERSonredisSetKey(s.keyPrefix, KeyTypeUserUpstream, userID)to get all provider keys for the user.:{providerID}(key format is{prefix}upstream:{sessionID}:{providerName}).MGETthe matching keys; unmarshal via existingunmarshalUpstreamTokens(tolerateErrExpired— we still want the refresh token).ExpiresAtas a stable proxy for "most recent" (no createdAt is persisted in Redis).ErrNotFoundwhen no match.Tolerate stale entries in the index per the warnOnCleanupErr contract at redis.go:35-50.
4. pkg/authserver/storage/mocks/mock_storage.go
Regenerate via
task genafter the interface change.5. pkg/authserver/server/handlers/callback.go
Insert preservation logic between callback.go:128 and callback.go:131 (after
subjectis resolved, beforestorageTokensis built):Then use
refreshTokenin thestorage.UpstreamTokensliteral. The defensiveprior.UpstreamSubject == providerSubjectcheck guards against carrying a refresh token across distinct IDP identities — a no-op today (userResolver.ResolveUsermakessubjectalready implyupstreamSubject) but it costs nothing and matches the binding-validation pattern in types.go:66-76.A
slog.Debugline on successful carry-forward helps diagnose this in the field. Noslog.Warnon the lookup error: a missing prior record is the common case (first-ever auth), not a problem.6. pkg/authserver/server/handlers/helpers_test.go
Wire up the new method in the handler test storage mock (add a
DoAndReturnclause that scansstorState.upstreamTokensbyUserID/ProviderID).7. Tests
GetLatestUpstreamTokensForUser: empty, one match, multiple matches across sessions (assert latest), userID/providerID mismatch returnsErrNotFound.miniredisfixture.TestCallbackHandler_PreservesPriorRefreshToken:storState.upstreamTokenswith(oldSession, providerID)carryingRefreshToken: "rt-prior"and matchingUserID/UpstreamSubject.mockUpstream.exchangeResult.Tokens.RefreshToken = "".pending.SessionIDfor the callback.(newSession, providerID)record hasRefreshToken == "rt-prior".UpstreamSubjectdiffers — assert we do NOT carry forward.Out of scope
tsidlookup path — but the new session's record now has a usable refresh token, so the refresh path succeeds.prompt=consentto Google upstream config — separate decision.Verification
task lint-fixtask gen(regenerate mocks after interface change)task test— full unit suite, in particular:go test ./pkg/authserver/storage/...(memory + redis)go test ./pkg/authserver/server/handlers/...(callback)RefreshTokenis the carried-forward value rather than"", and that step 8'somitting provider with unrefreshable expired tokenlog line no longer appears.jhrozek commentedon Apr 29, 2026
There must have been a bad linking, this is not completely fixed.
Add GetLatestUpstreamTokensForUser to storage
Implement GetLatestUpstreamTokensForUser for memory
Implement GetLatestUpstreamTokensForUser for redis
Carry forward upstream refresh token on callback
Add integration test for re-auth refresh token carry-forward
Carry forward upstream refresh token on re-authorization (#5132)
AndrewHannigan commentedon May 5, 2026
@jhrozek @tgrunnagle did the session-keyed-storage -> user-keyed-storage fix ship as well for root cause A?
jhrozek commentedon May 5, 2026
No, let me file a separate issue for it. It's something we should do, just separately and with care.