Repository navigation
Serialize upstream refresh across replicas - #7031
hellouz818 wants to merge 8 commits into
Conversation
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #7031 +/- ##
==========================================
+ Coverage 81.64% 81.66% +0.02%
==========================================
Files 898 898
Lines 91621 91739 +118
==========================================
+ Hits 74805 74922 +117
- Misses 16811 16812 +1
Partials 5 5 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
@tgrunnagle this is more your area of expertise could you take a look please? |
tgrunnagle
left a comment
There was a problem hiding this comment.
Review
This is a bug fix that adds a coordination layer. It introduces an optional UpstreamRefreshLocker storage capability (Redis SET NX PX with a random owner token and a Lua compare-and-delete release; MemoryStorage gets the same semantics under its mutex) and holds that lease around the read-redeem-write sequence in upstreamTokenRefresher. Only one replica redeems a given upstream refresh token. The others poll the row with capped backoff and return the holder's result. The design is sound and matches the Tier 2 approach agreed on #4122. The lease is keyed by the same UpstreamTokenRowID as the in-process singleflight. The TTL (45s) outlasts the holder's longest possible run (30s refreshCtx plus one 5s detached step). Waiters accept exactly what a leader's own re-read would accept. A free lease is never treated as a licence to redeem without re-reading. CAS stays underneath as the write-ordering backstop. Release is safe against stale holders, the key shares the prefix's cluster hash tag, and it stays out of the legacy upstream:* migration scan. The trade-off reviewers should weigh is availability for correctness. A replica now fails closed when Redis cannot be consulted, and when its wait runs out. A crashed holder stalls that one session's refreshes for up to 45s. Neither is new exposure for a deployment that already depends on Redis for the row itself.
Cross-cutting:
- Guarantee boundaries. The lease is advisory. It does not survive a Redis primary failover before replication, or a holder paused past the TTL. The code comments name a different residual gap, a slow live holder, which cannot happen. The one code-level gap is the redemption deadline: a waiter that wins the lease late redeems with whatever is left of its 30s budget. A fresh redemption timeout after acquisition would close that cheaply.
- Rolling upgrade. While old and new replicas run side by side, old replicas ignore the lease and the behaviour is the same as today. No migration is needed, and rolling back simply removes the layer.
upstream-lock:*keys expire on their own. - Observability. The new failure modes surface as wrapped errors from the refresher. A waiter that returns the holder's row logs only at DEBUG. If waits time out frequently, there is no metric to show it.
None of the findings below block merging. Each can be addressed in this PR or in a follow-up, whichever you prefer.
Medium
- Locker wiring in
newUpstreamTokenRefresheris untested (pkg/authserver/server_impl.go:987, see inline comment). Raised by: tests. - Operator Redis docs not updated for the new lease (
docs/redis-storage.md). The Key Schema table (lines 348-365) has no row for{prefix}upstream-lock:{row_id}(string, owner token, 45s TTL), and the page doesn't describe the new failure modes: a waiter can block up to 30s, a Redis fault during acquisition fails the refresh withcould not acquire upstream refresh lock, a wait timeout fails it, and replicas on the old version ignore the lease during a rolling upgrade. CLAUDE.md asks for the subsystem's page underdocs/to be updated when a request succeeds or fails differently. Raised by: documentation.
Low and info
- [LOW]
pkg/authserver/refresher.go:216: A waiter that wins the lease late redeems with whatever is left of the shared 30srefreshCtx; a deadline that cuts off a rotation mid-request can leave a dead refresh token stored. A freshcontext.WithTimeout(context.WithoutCancel(ctx), refreshTimeout)inrefreshHoldingLeasefits inside the 45s TTL. - [LOW]
pkg/authserver/refresher.go:85-92: Comments say only the lease holder calls the provider and name a slow live holder as the residual gap, which cannot happen (holder ≤ ~35s vs 45s TTL). The real gaps are a lease lost on Redis failover before replication and a holder paused past the TTL. - [LOW]
pkg/authserver/storage/redis.go:1888: On aSetNXerror the owner token is discarded; if the reply timed out after Redis applied theSET, the lease is unreleasable and blocks the row for 45s. A best-effort compare-and-delete with the generated owner before returning would clear it. - [LOW]
pkg/authserver/storage/redis.go:1803,pkg/authserver/storage/memory.go:1457:ResolveUpstreamTokenRowIDdoc comments still say "process-local refresh coordination"; the ID now also keys the cross-process lease. - [LOW]
pkg/authserver/storage/unwrap.go:25:UpstreamRefreshLockerFromasserts at every layer, outermost first, while the sibling lookups (server_impl.go:720,:906) assert only onUnwrap(stor); its doc says it "mirrors" them. - [LOW]
pkg/authserver/storage/types.go:1711: The "why a lease on top of CAS" and "same row identity as singleflight" rationales are each restated in four or five places (types.go, refresher.go, redis.go, redis_keys.go, memory.go, docs/arch); keeping one copy at the owner with pointers elsewhere would prevent drift and cut the line count. - [LOW]
pkg/authserver/refresher.go:189-190, 543: Comments narrate the change ("exactly as before this layer existed", "this path now covers") rather than the final state. - [LOW]
pkg/authserver/refresher.go:208-211, 229-232: The "timed out waiting for another replica" error is built twice in a ~53-line loop; a small helper would tidy it. - [LOW]
pkg/authserver/server_impl.go:969-970: Added doc sentence is a comma splice and overlaps the inline comment at 983-986. - [LOW]
pkg/authserver/refresher.go:235: Backoff doubling and the 500ms cap are not pinned by a test; a fixed 25ms poll would pass. - [LOW]
pkg/authserver/refresher_lock_test.go:29-67: Hand-writtenfakeLocker/fakeLease(and similar stubs) while the PR generatesMockUpstreamRefreshLocker/MockUpstreamRefreshLease, which go unused; testing.md says to use gomock and never hand-write mocks. - [LOW]
pkg/authserver/refresher_lock_test.go:116-143: "Fails when the wait runs out" assertsattempts > 1under a 120ms real-time deadline; a ~95ms scheduling stall would fail it. - [LOW]
pkg/authserver/refresher_lock_test.go:176-179: Test doc still describes a crashed/expired holder; the test scripts one refusal then a grant, andcoordinatedRefreshno longer frames a free lease that way. - [LOW]
pkg/authserver/refresher_contention_test.go:155, 196:wg.Wait()calls have no fail-fast timeout, which testing.md requires for blocking barriers. - [LOW]
pkg/authserver/storage/memory.go:572: The re-check under the write lock incleanupExpiredis never exercised; removing it fails no test. - [LOW]
pkg/authserver/storage/upstream_refresh_lock_test.go:64: RedisSetNXerror andReleaseerror paths are not exercised (e.g. acquire,mr.Close(), assert errors that are notErrUpstreamRefreshLockHeld). - [LOW]
docs/arch/11-auth-server-storage.md:426-431: Layer numbering: "Two further layers do. The first:" vs. "the third layer below"; the CAS caveat that both replicas call the provider now holds only without the lease. - [LOW]
docs/arch/11-auth-server-storage.md:495-498: The lost-race log paragraph now sits under the Redemption lease heading and attributes the log to the storage layer; it comes fromresolveConcurrentRefreshConflictin the refresher. - [LOW]
docs/arch/11-auth-server-storage.md:491-493: "A backend providing neither" has no referent and names the privatelockerfield. - [LOW]
docs/arch/11-auth-server-storage.md:59-67, 1090-1096: The ToolHive extensions list and the Unwrap pattern section don't mentionUpstreamRefreshLocker/UpstreamRefreshLockerFrom. - [LOW] PR size: Production Go changes total ~551 lines against the 400-line guideline in CLAUDE.md; trimming duplicated comments would close most of the gap.
- [LOW] PR body: #6831 is cited for the conditional delete after a failed rotation persist; per #4122 that is the reauthorization-chain issue.
- [INFO]
pkg/authserver/refresher.go:44: A crashed holder blocks its row for up to 45s; requests in the first ~15s wait 30s then fail. Documented fail-closed trade-off, scoped to one session — worth stating in the user-facing docs. - [INFO]
pkg/authserver/storage/upstream_refresh_lock_test.go:203:UpstreamRefreshLockerFromtable could add: decorator over a store without the capability, a multi-decorator chain, and anUnwrapreturning nil (the code handles all three today).
How to test
task test(the newrefresher_lock_test.go,refresher_contention_test.go,storage/upstream_refresh_lock_test.go), andtask lint-fix.- Deliberately break it: in
newUpstreamTokenRefresher, setlocker: nil. Every test still passes, which is the wiring-test gap. Then inrefresher_contention_test.go, construct the second refresher without a locker and confirm the test reports two provider redemptions. - Remove the
now.After(lease.expiresAt)re-check inMemoryStorage.cleanupExpiredand confirm no test fails, which is the coverage gap. - Manual, two replicas: run two auth-server or vMCP replicas against one Redis, with an upstream whose access token expires quickly. Fire concurrent requests for the same session through both replicas. Expect exactly one upstream refresh per expiry in the IdP or provider logs, no
lost concurrent upstream token refresh racelog, and a short-lived{prefix}upstream-lock:<hex>key in Redis during the refresh (redis-cli --scan --pattern '*upstream-lock*'). Stop Redis mid-run and confirm refreshes fail withcould not acquire upstream refresh lockrather than redeeming. - What should not change: single-replica and memory-backed deployments behave as before, apart from one uncontended map operation per refresh.
Reviewed by dev:pr-review (finders: correctness, readability, security, tests, API design, documentation). Generated with Claude Code.
| // than per refresh: it peels the storage decorators stor is wrapped in by | ||
| // this point, which embed the Storage interface and so do not carry the | ||
| // backend's optional capabilities. | ||
| locker := storage.UpstreamRefreshLockerFrom(stor) |
There was a problem hiding this comment.
[MEDIUM] Locker wiring in newUpstreamTokenRefresher is untested
Every new test builds upstreamTokenRefresher by struct literal or calls storage.UpstreamRefreshLockerFrom directly. newUpstreamTokenRefresher is the only production site that resolves the locker over the decorated storage, and no test looks at the locker it sets: the existing constructor tests never inspect it, and server_test.go:909 passes no upstreams, so it returns before this line. Dropping this line, or a decorator losing Unwrap, would silently degrade every multi-replica deployment to CAS-only coordination with every test still green. The no-locker slog.Debug branch is also uncovered (testing.md rule 7).
Recommendation: Add a small table test in package authserver: newUpstreamTokenRefresher over MemoryStorage, over MemoryStorage wrapped in the decorators newServer applies, and over a storage without the capability; assert locker is non-nil, non-nil, and nil.
Raised by: tests.
There was a problem hiding this comment.
Added TestNewUpstreamTokenRefresher_ResolvesLocker in 03dfb7d with the three cases you suggested: bare MemoryStorage, MemoryStorage wrapped in ClientAdmissionStorage, and a backend without the locker capability. The first two assert that the locker is set. The third asserts that it’s nil and exercises the no-locker debug branch.
I ran your break check by setting the constructor’s locker to nil. The first two cases failed as expected.
Two replicas sharing one Redis could both detect the same expired upstream access token and redeem the same single-use refresh token. CompareAndSwapUpstreamTokens, added earlier for this issue, orders the resulting writes so the loser cannot clobber the winner, but both replicas have already called the provider by then. An IdP enforcing strict single-use rotation (RFC 9700 4.14.2 replay detection) can read those two redemptions as a replay and revoke the grant, whichever write won. SessionAffinity does not cover rolling deployments, client IP changes, or L7 load balancers that mask the client IP. Add UpstreamRefreshLocker, an optional storage capability handing out a mutual-exclusion lease over one upstream token row, and hold it across the whole read-redeem-write sequence so only the lease holder calls the provider. A replica that cannot take the lease waits on a capped backoff, re-reading the row, and returns the holder's row once it satisfies the test the leader applies to its own re-read; it takes over as leader only if the lease frees while the row is unchanged. Running out of time, or any acquisition failure other than "held by someone else", fails closed rather than redeeming uncoordinated. Redis acquires with SET NX PX of a random owner token and releases with a Lua compare-and-delete, so a stale holder cannot free a later holder's lease. MemoryStorage implements the same semantics under its existing mutex. A backend providing neither degrades to the CAS-only coordination that exists today. Refs: stacklok#4122 Signed-off-by: hellouz818 <hellouz818@gmail.com>
The waiter's description said it takes over as leader when the lease becomes free while the row is unchanged, and attributed a free lease to a holder that crashed or whose lease expired. Both are narrower than the code: the waiter retries acquisition on every pass once no usable row has appeared, and a lease also becomes free on the holder's normal success path, which releases it. Say what the loop does instead, and drop the claim that a free lease means something went wrong. Whichever attempt wins re-reads the row before deciding whether an upstream refresh is still needed, so taking the lease is not a licence to redeem without looking. Refs: stacklok#4122 Signed-off-by: hellouz818 <hellouz818@gmail.com>
The lease tests so far drive a fake locker and mock storage, so they cover the waiter's decisions but never the claim the lease exists for: that two processes sharing one Redis ask the upstream provider to redeem a given refresh token exactly once. Contend two refreshers with independent singleflight groups on one miniredis-backed storage, over the same expired row. The provider parks mid-redemption so the second replica is observed while the first holds the lease, and a passthrough locker reports the refusal so the "it did not call the provider" assertion needs no sleep. Everything below the refresher is real, including the Lua lease and compare-and-swap write. Removing the lease from the test makes it report two redemptions. Refs: stacklok#4122 Signed-off-by: hellouz818 <hellouz818@gmail.com>
The contention test parks a refresher inside the provider on purpose. A t.Fatal before the release left that goroutine blocked for the rest of the run, holding a storage client the test had already torn down. Close the release channel and wait for both refreshers from a cleanup registered after the storage one, so it runs first and drains them while Redis is still up. The provider also selects on its context, but that is only a backstop: RefreshAndStore detaches its refresh context, so cancelling the test's context never reaches the parked call. Refs: stacklok#4122 Signed-off-by: hellouz818 <hellouz818@gmail.com>
A waiter that won the lease late redeemed on whatever was left of the caller's shared 30s budget. A deadline firing between the IdP accepting the rotation and the CAS write landing leaves a refresh token the IdP has already rotated away stored as the live one. Give the holder its own refreshTimeout, measured from the acquisition that also starts the lease TTL, so the redemption still fits inside the lease. Clear a lock whose SET reply was lost after Redis applied it, which would otherwise block the row for a full TTL with no holder. Extract the waiter's backoff and the in-memory expiry sweep so a test can reach them, and name the residual gaps the lease really leaves: a Redis failover that promoted a replica before the acquisition replicated, and a holder paused past the TTL. A slow live holder is not one of them. Refs: stacklok#4122 Signed-off-by: hellouz818 <hellouz818@gmail.com>
newUpstreamTokenRefresher is the only production site that resolves the lease capability, and nothing looked at what it resolved: dropping that line, or a decorator losing Unwrap, would degrade every multi-replica deployment to CAS-only coordination with the suite still green. The in-memory sweep's re-check under the write lock was unexercised too, and removing it failed no test. Assert the resolved locker over a bare backend, a decorated one and a backend without the capability. Drive the sweep's delete directly, so the case it guards — a lease re-acquired since it was collected — is covered. Add the Redis acquire and release faults, and pin the waiter's backoff. Replace the hand-written locker and lease stubs with the generated gomock ones, and spend the waiter's budget from inside the second acquisition rather than racing a 120ms wall-clock deadline. Give every blocking barrier a fail-fast timeout. Refs: stacklok#4122 Signed-off-by: hellouz818 <hellouz818@gmail.com>
The lease changes what an operator sees: a replica that is not the holder waits, a Redis fault during a refresh fails the request rather than redeeming, and a crashed holder blocks one row until the TTL expires. None of that was written down, and the Redis page's key schema had no row for the lease key. Describe the key and those failure modes, including what a rolling upgrade does while older replicas ignore the lease. In the architecture page, fix the layer numbering the lease broke, attribute the lost-race log to the refresher that emits it, and add the capability to the extensions list and the Unwrap section. Refs: stacklok#4122 Signed-off-by: hellouz818 <hellouz818@gmail.com>
The "why a lease on top of CAS" and "same row identity as singleflight" arguments were each restated at several call sites, where they can drift from the interface that defines them. Leave one copy on storage.UpstreamRefreshLocker and UpstreamTokenStorage, and point the refresher and both backends at it. Cover the last discovery case the capability lookup handles: a real decorator over a backend that provides no lease. Refs: stacklok#4122 Signed-off-by: hellouz818 <hellouz818@gmail.com>
7cbf4d2 to
03dfb7d
Compare
|
@tgrunnagle Thanks for the review. I rebased onto I added the locker wiring test and updated the Redis operator docs. You were right about the redemption deadline. That was a real bug: a waiter that acquired the lease late could start a token rotation with too little time left to persist the new token. The lease holder now gets a fresh 30-second budget after acquisition. I also added best-effort, owner-checked cleanup when I’d prefer to add the wait timeout metric in a follow-up PR, since it requires separate meter-provider wiring. I’m happy to include it here if you’d prefer. The production Go diff still exceeds the 400-line guideline at roughly 565 lines across seven files, including 313 lines of comments. If a smaller diff would help with review, I’m happy to split the storage changes from the refresher wiring. Could you take another look when you have a chance? |
Summary
Two auth server replicas sharing one Redis can both detect the same expired upstream access token and redeem the same single-use refresh token.
CompareAndSwapUpstreamTokens(#6548) orders the resulting writes so the loser cannot clobber the winner, but by then both replicas have already called the provider. An IdP enforcing strict single-use rotation (RFC 9700 §4.14.2 replay detection) can interpret those two redemptions as a replay and revoke the grant, regardless of which write won.SessionAffinity: ClientIPdoes not cover rolling deployments, client IP changes, or an L7 load balancer / ingress that routes to endpoints directly. This is Tier 2 from the issue; Tiers 1 and 3 are already on main, anddocs/arch/11-auth-server-storage.mdcurrently records this lock as a deliberate follow-up.storage.UpstreamRefreshLocker/UpstreamRefreshLease, an optional storage capability providing a mutual-exclusion lease over one upstream token row, keyed by the sameUpstreamTokenRowIDthe in-processsingleflightgroup uses.upstreamTokenRefresher, so only the lease holder callsprovider.RefreshTokens.refreshTimeoutwhile waiting, or any acquisition failure other than "held by another holder", returns an error rather than redeeming uncoordinated. A replica that cannot reach the backend cannot know whether another one is redeeming.SET NX PXof a random owner token under{prefix}upstream-lock:{rowID}and releases with a Lua compare-and-delete, so a holder whose lease already expired cannot free a later holder's lease.MemoryStorageimplements the same semantics under its existing mutex. Backends without the optional lease capability retain today's CAS-only coordination.We hit this in production: vMCP with 2 replicas, Redis storage and
mcp.atlassian.comupstream, behind an ingress that bypasses the Service's session affinity. Over ~1 day of logs, 8 sessions had both replicas refresh within ~1s (the loser logginglost concurrent upstream token refresh race, which only happens after a successful upstream refresh, so both redemptions were accepted). Two of those sessions have refreshed since; both failed withinvalid_grant - Invalid refresh token15–21 hours later. Sessions refreshed by a single replica succeeded on their next refresh (4/4). The sample is small and does not establish why Atlassian later rejected those tokens, but it is consistent with the concurrent-refresh failure mode.Refs: #4122
Type of change
Test plan
task test)task test-e2e)task lint-fix)New coverage:
pkg/authserver/storage/upstream_refresh_lock_test.goruns one table against both backends: a second acquisition of a held row reportsErrUpstreamRefreshLockHeld, a different row is unaffected, release frees the row immediately, release is idempotent, an expired lease can be taken over, and an expired holder's late release does not free the new holder's lease. Also covers the in-memory expiry sweep and capability discovery through a storage decorator.pkg/authserver/refresher_lock_test.gocovers the waiter paths with a provider mock that has noRefreshTokensexpectation, so any upstream redemption fails the test: returning the holder's row, failing when the wait runs out, failing closed on a backend fault without retrying, and ignoring a row that changed but is still expired. Also covers leader takeover of a freed lease, release on every leader exit path (including the short-circuit and the error path), a failed release not failing the refresh, and the lease covering the resolved row ID with a TTL aboverefreshTimeout.pkg/authserver/refresher_contention_test.goputs two refreshers with independent singleflight groups on one miniredis-backed storage and contends them on the same expired row: while the first is refreshing, the second waits without calling the provider. Both return the same refreshed tokens, with exactly one upstream refresh call. Removing the lease from that test makes it report two redemptions.Does this introduce a user-facing change?
Yes. Before: two replicas sharing one Redis could each redeem the same upstream refresh token, and an IdP enforcing strict rotation could revoke the grant. After: only the lease holder redeems; a concurrent request waits for it and returns the refreshed tokens, so it succeeds but is slower by roughly one upstream refresh. A wait that exceeds 30s, or a Redis fault during acquisition, now fails the request with
could not acquire upstream refresh lockrather than redeeming uncoordinated, and a replica that crashes mid-refresh blocks that one row until the 45s lease TTL expires. Backends without the optional lease capability, and older replicas during a rolling upgrade, behave exactly as before.docs/redis-storage.mddocuments the new key and these failure modes for operators.Special notes for reviewers
refreshTimeoutbudget measured from the acquisition that starts the TTL, so a waiter that wins the lease late does not run a rotation on a deadline it mostly spent waiting; the 15s margin covers the best-effort per-provider delete that may follow. This relies on the refresh path honoring cancellation.MemoryStorage. It implements the same lease semantics to keep the optional capability consistent across backends and allow shared contract tests. Production refreshes within one process are already deduplicated bysingleflight.Refs:rather thanFixes:, because one item from the issue is deliberately out of scope here: the operator setting explicitSessionAffinityConfig.ClientIP.TimeoutSeconds: 1800on VirtualMCPServer services (the issue's "Additional Note" — a separate layer). Happy to follow up in a separate PR.Review follow-up
Rebased onto
main(the branch had fallen 134 commits behind and was conflicting; the only conflicts were thego:generateline that #7096 split, and the mocks regenerated from it).Addressed from @tgrunnagle's review: the redemption deadline, the lost
SET NXreply, the untested locker wiring and in-memory sweep re-check, the Redis acquire/release fault paths, the unpinned backoff, the hand-written locker stubs (now the generated gomock ones), the wall-clock-dependent wait assertion, the missing fail-fast barriers, the operator docs, and the comment and architecture-page corrections. Both "deliberately break it" steps now fail: dropping the locker resolution innewUpstreamTokenRefresherfails the wiring test, and removing the sweep's re-check fails the sweep test.Generated with Claude Code