Repository navigation
Description
Context
PR #4117 extracted upstream token refresh into a reusable InProcessService (pkg/auth/upstreamtoken). During review, a race condition was identified that affects multi-pod deployments with shared Redis storage and single-use refresh token rotation at the upstream IDP.
The singleflight.Group in InProcessService deduplicates concurrent refresh attempts within a single pod, but cannot coordinate across pods. When two pods simultaneously detect an expired access token and attempt to refresh using the same single-use refresh token, only one succeeds — the other gets rejected by the IDP.
The Race
Time Pod A Pod B Redis
───── ────────────────────────────── ────────────────────────────── ─────────────
t0 GetValidTokens(sid) {AT_old, RT1}
t1 storage.Get → expired + RT1 GetValidTokens(sid) {AT_old, RT1}
t2 storage.Get → expired + RT1 {AT_old, RT1}
t3 provider.RefreshTokens(RT1) provider.RefreshTokens(RT1) {AT_old, RT1}
t4 IDP returns AT2 + RT2 {AT_old, RT1}
t5 storage.Store(AT2, RT2) IDP rejects RT1 → error {AT2, RT2}
t6 → ErrRefreshFailed → 401
The race window is approximately 50–320ms (one Redis GET + one IDP round-trip + one Redis SET).
Current Mitigation
SessionAffinity (shipped in #3992) is the primary defense. With SessionAffinity: ClientIP, kube-proxy pins a client IP to the same backend pod, so the in-process singleflight handles deduplication. This eliminates the race in the common case.
SessionAffinity breaks during:
- Rolling deployments / pod evictions
- Client IP changes (mobile network switch, VPN reconnect)
- L7 load balancers that mask client IPs (Ingress, service mesh)
Risk Assessment
Current risk is low:
- MCPServer runs single-replica today with an embedded auth server
- vMCP does not use upstream token refresh yet
- SessionAffinity covers the common case
Risk increases when:
- vMCP adds upstream token injection (multi-replica is the default)
- Users deploy behind L7 load balancers without client-IP-based affinity
- IDPs with aggressive replay detection are used (see below)
IDP-Specific Behavior
Not all IDPs handle refresh token replay the same way:
| IDP | Behavior on replay of consumed RT | Severity |
|---|---|---|
| Okta | Revokes entire grant family (all ATs + RTs for that session) | Critical — both pods lose tokens |
| Auth0 | Configurable "Reuse Interval" (default: no grace) | High if interval is 0 |
| Keycloak | Configurable; no grace period when rotation enabled | High when enabled |
| Entra ID | ~10s grace period for confidential clients | Low |
| Doesn't rotate RTs by default | N/A |
Since ToolHive is IDP-agnostic, the design must assume worst-case (Okta).
Proposed Mitigation Tiers
Tier 1: Retry-with-Reread (low effort, partial fix)
After RefreshAndStore fails, re-read Redis. If another pod already stored fresh tokens, use them instead of returning 401.
- ~10 lines in
InProcessService.refreshOrFail - No interface changes, no new dependencies
- Handles the case where the IDP doesn't punish replay
- Does not prevent the duplicate IDP call (still unsafe with Okta)
Tier 2: Redis distributed lock (moderate effort, complete fix)
Acquire a SET NX EX lock on {prefix}refresh-lock:{sessionID} before calling the IDP. Only the lock holder refreshes; other pods wait and re-read.
- Prevents duplicate IDP calls entirely (safe with Okta)
- Uses existing Redis infrastructure and Lua script patterns
- Self-contained in
pkg/auth/upstreamtoken/service.go - Failure mode: lock-holder crash → other pods wait until TTL expires (use 30s to match
refreshTimeout) - Lock acquisition failure (Redis down) → fail closed (consistent with existing behavior in
27644a8e)
Tier 3: CAS on storage (optional hardening)
Add CompareAndStoreUpstreamTokens to UpstreamTokenStorage — write only succeeds if the stored RT matches what was read. Prevents stale overwrites even with non-rotating IDPs.
- Extends existing Lua script in
storeUpstreamTokensScript - New method on
UpstreamTokenStorageinterface - Complementary to Tier 2, not a replacement
Not recommended
- K8s Lease-based coordination: Wrong granularity (per-session coordination needs sub-second; Leases are per-workload with 10–15s renewal)
- Singleton refresh service: Operationally heavy, architectural mismatch with embedded auth server design
- Leader election: Concentrates all refresh work on one pod, creates single point of failure
Suggested Implementation Order
- Tier 1 (retry-with-reread) as a quick safety net
- Tier 2 (Redis lock) when vMCP adds upstream token support
- Tier 3 (CAS) as optional hardening if needed
Relevant Files
pkg/auth/upstreamtoken/service.go—InProcessService.refreshOrFail(primary change site)pkg/auth/upstreamswap/middleware.go— error-to-HTTP mappingpkg/authserver/refresher.go—RefreshAndStore(blind write, no CAS)pkg/authserver/storage/redis.go—storeUpstreamTokensScriptLua scriptpkg/authserver/storage/types.go—UpstreamTokenStorageinterface (no CAS method)cmd/thv-operator/controllers/virtualmcpserver_deployment.go— SessionAffinity config
Additional Note
The operator should set explicit SessionAffinityConfig.ClientIP.TimeoutSeconds: 1800 on VirtualMCPServer services for parity with the non-operator path (pkg/container/kubernetes/client.go:1028).
Activity
Sanskarzz commentedon Jun 19, 2026
@jhrozek I’d like to give this a try. Could you please assign this issue to me?
Deduplicate refreshes by storage row
Deduplicate refreshes by storage row
Deduplicate refreshes by storage row (#6361)
hellouz818 commentedon Nov 2, 2026
Hi @Sanskarzz, are you still planning to work on this? Have you made any progress on Tier 2 (the Redis distributed lock)?
We're running vMCP with 2 replicas, Redis storage, and Atlassian (
mcp.atlassian.com) as the upstream. Traffic reaches the pods through an ingress that routes to endpoints directly, so the Service'sSessionAffinity: ClientIPdoesn't apply. We've seen both pods attempt an upstream refresh for the same session within the same second.Atlassian sessions intermittently fail with
invalid_grant - Invalid refresh tokenon the first refresh after hours or days of idle time. We haven't observed this with other providers. We suspect this may be related to the refresh-token rotation race described here. One possibility is that Atlassian accepts concurrent redemptions of the same refresh token, but the token that ends up stored subsequently becomes invalid. We haven't yet confirmed this end to end and are collecting logs to verify it.#6361 and #6548 don't prevent duplicate redemptions at the upstream, so this looks like it needs the Tier 2 coordination described above.
I'd also be happy to help with Tier 2 if you haven't started yet or would like a hand.
Sanskarzz commentedon Nov 2, 2026
Thanks for checking, @hellouz818! I expressed interest in this a while ago, but it was never assigned to me, and I haven’t started working on it. I’m not currently working on Tier 2, so please don’t wait on me.
Thanks for offering to help. I’m assigning this to you. The cross-pod coordination gap remains despite #6361 and #6548. Please share a short approach here so we can agree on the remaining scope before implementation. The Atlassian logs you’re collecting would also help confirm whether this race explains those failures.
hellouz818 commentedon Nov 3, 2026
Thanks! Here's what the logs show so far, followed by a proposed approach.
Logs (≈1 day, 2 replicas, Redis):
lost concurrent upstream token refresh race. That only happens after a successful upstream refresh, so both redemptions succeeded.invalid_grant - Invalid refresh token, 15–21 hours later.Approach (Tier 2):
The singleflight leader in
RefreshAndStoretakes a per-row Redis lock before its re-read. The lock key uses a separate lock prefix and is derived from the sameUpstreamTokenRowIDthat singleflight uses, so different session IDs that resolve to the same row share one lock. Acquisition usesSET NX PXwith an owner token and a TTL greater thanrefreshTimeout. Release is compare-and-delete.The holder runs today's authoritative re-read and keeps its existing short-circuit condition (the row is unexpired and differs from the caller's). Otherwise it redeems, CAS-writes, and releases the lock.
A replica that doesn't get the lock polls the row:
refreshTimeoutruns out first, it fails.While it doesn't hold the lock, it never calls the upstream.
The lock goes behind an optional storage interface: a Redis implementation and a no-op for memory storage. If Redis fails while acquiring the lock, it fails closed.
CAS remains as a storage-write backstop. Lease expiry can still permit duplicate upstream redemptions.
Out of scope: the conditional delete after a failed rotation persist (Re-authorization walks the full upstream chain instead of evaluating existing credentials #6831).
Does this scope look right?
hellouz818 commentedon Nov 3, 2026
Opened #7031 with the proposed Tier 2 implementation.
It follows the approach above, with one deliberate difference:
MemoryStorageimplements the same lease semantics as Redis rather than a no-op, keeping the optional capability consistent across backends and allowing shared contract tests.Two implementation details: the lease TTL is 45s (
refreshTimeout+ 15s), and waiters use exponential backoff from 25ms to a 500ms cap.Added a concurrency test with two independent refreshers sharing Redis: while the first holds the lease, the second waits without calling the provider, and both return the same refreshed tokens with exactly one upstream refresh call. Removing the lease from that test makes it report two redemptions instead.
The PR body has the full description and reviewer notes. Happy to adjust the implementation based on the scope discussion, including splitting the storage capability/backends and refresher wiring into separate PRs if that would make review easier.
Correct how the lease waiter retries acquisition
Test two replicas redeem a refresh token once
Drain the parked provider call on test teardown
Sanskarzz commentedon Nov 3, 2026
Thanks, @hellouz818 the Tier 2 scope looks right. The production observations are helpful, and I agree with keeping the Atlassian root cause qualified while you gather more data. Implementing equivalent lease semantics in MemoryStorage makes sense, and I see the two-refresher Redis contention test is already included.
Please go ahead with the split you offered: storage capability/backends and their contract tests first, then refresher wiring, contention tests and runtime documentation on top. Keeping conditional deletion and the Service affinity timeout separate makes sense.
One small reference correction: #6831 is the reauthorization-chain issue, so please update the conditional-delete link.
Serialize upstream refresh across replicas
Correct how the lease waiter retries acquisition
Test two replicas redeem a refresh token once
Drain the parked provider call on test teardown
Bound the redemption by the lease, not the caller
Cover the lease wiring and its failure paths
Document the upstream refresh lease for operators
Keep the lease rationale at its owner