From 854f38818ee8fa3b664724ce020f2cac3b0cfad5 Mon Sep 17 00:00:00 2001 From: hellouz818 Date: Tue, 3 Nov 2026 14:16:21 +0900 Subject: [PATCH 1/8] Serialize upstream refresh across replicas 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: #4122 Signed-off-by: hellouz818 --- docs/arch/11-auth-server-storage.md | 86 ++++- pkg/authserver/refresher.go | 228 ++++++++++-- pkg/authserver/refresher_lock_test.go | 329 ++++++++++++++++++ pkg/authserver/server_impl.go | 13 + pkg/authserver/storage/memory.go | 88 +++++ pkg/authserver/storage/mocks/mock_storage.go | 79 ++++- pkg/authserver/storage/redis.go | 83 +++++ pkg/authserver/storage/redis_keys.go | 23 ++ pkg/authserver/storage/types.go | 86 ++++- pkg/authserver/storage/unwrap.go | 20 ++ .../storage/upstream_refresh_lock_test.go | 235 +++++++++++++ 11 files changed, 1220 insertions(+), 50 deletions(-) create mode 100644 pkg/authserver/refresher_lock_test.go create mode 100644 pkg/authserver/storage/upstream_refresh_lock_test.go diff --git a/docs/arch/11-auth-server-storage.md b/docs/arch/11-auth-server-storage.md index a1015799a2..2469777181 100644 --- a/docs/arch/11-auth-server-storage.md +++ b/docs/arch/11-auth-server-storage.md @@ -410,6 +410,13 @@ thv:auth:{default:my-server}:reqid:access:{request-id} → {sig1, sig2} thv:auth:{default:my-server}:user:upstream:{user-id} → {session1, session2} ``` +The upstream refresh lease is a plain string key, not an index, holding the +current holder's random owner token for the lease TTL: + +``` +thv:auth:{default:my-server}:upstream-lock:{row-id} → {owner-token} +``` + ### Exchange grant storage `ExchangeGrantStorage` keeps one record per refresh token issued through token exchange, found by the token's HMAC signature. Time decisions for records (live, expired, revoked) are made in Go against the store clock; the record's Redis TTL is only garbage collection. The replay marker is different: its window follows Redis's own TTL. The create script checks whether the marker key exists, and Go only skips the marker once its window has already passed. `ExchangeGrantMarkerMargin` absorbs clock skew and the time between reading the clock and running the script. Both effects can only lengthen the window, which is the safe direction. @@ -443,16 +450,18 @@ Redis, that representation is its row-key format, so two `(sessionID, providerName)` pairs that happen to produce the same Redis key resolve to the same identity — that's safe because they're the same physical row. What's not allowed is aliasing two pairs that are genuinely different rows: the -auth server uses this identity only as the key for its in-process -`singleflight` group, then its leader re-reads the row before redeeming its -refresh token, and it reads/writes under its own sessionID — aliasing -distinct rows would cross credentials between sessions. This prevents -duplicate redemption from stale concurrent callers served by the same -process; the identity is not persisted, logged, or exposed. +auth server uses this identity as the key for its in-process `singleflight` +group and for the cross-process redemption lease described below, then its +leader re-reads the row before redeeming its refresh token, and it +reads/writes under its own sessionID — aliasing distinct rows would cross +credentials between sessions. This prevents duplicate redemption from stale +concurrent callers served by the same process; the identity is never logged +or returned to a client, and the only place it is written is the lease key a +backend derives from it, which lives no longer than the lease. This is deliberately narrower than #4122's original in-process-only scope: it -does not by itself provide distributed coordination across replicas. That -coordination now exists as a second, independent layer: +does not by itself provide distributed coordination across replicas. Two +further layers do. The first: `UpstreamTokenStorage.CompareAndSwapUpstreamTokens` conditions a refresh write on the refresh token currently stored still matching the value the caller redeemed with, failing the write (`ErrConcurrentRefresh`) instead of @@ -472,17 +481,56 @@ redemption is safe at the upstream provider. Both replicas still call provider enforcing strict single-use rotation (RFC 9700 §4.14.2 replay detection), two concurrent redemptions of the same refresh token can still be indistinguishable from a replay at the IdP, which may revoke the grant -regardless of which replica's write wins here. CAS is fully sufficient only -where the provider tolerates a short grace/leeway window in which more than -one redeemed child stays valid (e.g. Read.ai's stated behavior) — outside -that window, closing the gap requires serializing the *redemption* itself -(a distributed lock around the read-redeem-write sequence), not just the -write. That lock is a deliberate follow-up, not implemented here: this layer -only prevents storage corruption from a lost write race, and its own log -distinguishes a genuine lost race (an unexpired row on re-read) from a row -that is simply gone (deleted by logout or evicted by TTL, `ErrNotFound` on -re-read) — the latter is expected behavior, not a race, and refuses to -resurrect the deleted row. +regardless of which replica's write wins. CAS alone is therefore sufficient +only where the provider tolerates a grace/leeway window in which more than +one redeemed child stays valid (e.g. Read.ai's stated behavior). Closing the +gap outside that window requires serializing the *redemption*, which is the +third layer below. + +#### Redemption lease (`UpstreamRefreshLocker`) + +`UpstreamRefreshLocker` is an optional capability of an +`UpstreamTokenStorage` backend — segregated from the interface for the same +reason as `DeviceCodeStorage` and `ExchangeGrantStorage` — that hands out a +mutual-exclusion lease over one upstream token row, honoured by every process +sharing the backend. `upstreamTokenRefresher` resolves it once at +construction via `storage.UpstreamRefreshLockerFrom`, which peels the storage +decorators (they embed `Storage` and so do not carry the backend's optional +capabilities), and holds that lease across the whole read-redeem-write +sequence. Only the holder calls `provider.RefreshTokens`. + +A replica that cannot take the lease never falls through to the provider. It +waits on a capped exponential backoff, re-reading the row after each wait, and +returns the holder's row as soon as that row satisfies the same test the +leader uses on its own re-read: unexpired *and* different from the row the +caller arrived with. If the lease becomes free while the row is unchanged — +the holder crashed, or its lease expired — the waiter takes over as leader. If +`refreshTimeout` runs out first, the refresh fails; running out of time is not +a licence to redeem uncoordinated. An acquisition that fails for any reason +other than "held by someone else" also fails closed, because a replica that +cannot reach the backend cannot know whether another one is redeeming. + +The lease is advisory and bounded by a TTL set above `refreshTimeout`, so a +holder that dies mid-refresh blocks the row for at most that long. It does not +replace CAS: both layers run, and the CAS write is what stays correct if a +lease expires early under load. Redis implements acquisition as `SET NX PX` of +a random owner token under `{prefix}upstream-lock:{rowID}` — the same row +identity the in-process `singleflight` group is keyed by, so the two layers +cover exactly the same set of rows by construction — and release as a Lua +compare-and-delete on that owner token, so a stale holder can never delete the +lease a later holder legitimately acquired. The key name deliberately does not +match the `upstream:*` scan pattern walked by the legacy-key migration. +`MemoryStorage` implements the same semantics in-process under its existing +mutex; it is reachable from one process only, where `singleflight` already +deduplicates, but implementing it for real keeps a caller's behaviour +independent of which backend it was wired against. A backend providing +neither leaves `locker` nil and degrades to the CAS-only coordination +described above. + +The storage layer's own log distinguishes a genuine lost race (an unexpired +row on re-read) from a row that is simply gone (deleted by logout or evicted +by TTL, `ErrNotFound` on re-read) — the latter is expected behavior, not a +race, and the row is not resurrected. ### Upstream Refresh Rejections and the Refresh Grant diff --git a/pkg/authserver/refresher.go b/pkg/authserver/refresher.go index 3674e892fd..283c197718 100644 --- a/pkg/authserver/refresher.go +++ b/pkg/authserver/refresher.go @@ -33,6 +33,35 @@ const upstreamStoreRetryBackoff = 50 * time.Millisecond // attempts does not also kill the delete, which would leave the stale row behind. const upstreamDeleteTimeout = 5 * time.Second +// upstreamRefreshLeaseTTL bounds a distributed refresh lease (see +// storage.UpstreamRefreshLocker). It must outlast the holder's whole +// read-redeem-write sequence, which refreshCtx caps at refreshTimeout, or the +// lease could expire mid-redemption and let a waiter redeem the same refresh +// token — the exact race the lease exists to prevent. The margin above +// refreshTimeout covers the gap between acquiring the lease and the holder's +// CAS write landing. It is also the longest a crashed holder can block the +// row, which is why it is not set far higher. +const upstreamRefreshLeaseTTL = refreshTimeout + 15*time.Second + +// upstreamRefreshLeaseReleaseTimeout bounds the release of a refresh lease. A +// fresh detached context is used because the refresh context is usually +// already at or past its deadline by the time the holder unwinds, and a +// release skipped on that account would make every waiter sit out the full +// upstreamRefreshLeaseTTL. +const upstreamRefreshLeaseReleaseTimeout = 5 * time.Second + +// upstreamRefreshLockPollInitial and upstreamRefreshLockPollMax bound the +// backoff a replica waits between attempts while another holder has the lease. +// Each attempt costs one acquisition and one row read, and the wait can run to +// refreshTimeout, so a fixed short interval would put hundreds of round-trips +// per waiting request on the storage backend. Starting small keeps the common +// case — the holder finishes in well under a second — responsive, and the cap +// keeps a long wait cheap. +const ( + upstreamRefreshLockPollInitial = 25 * time.Millisecond + upstreamRefreshLockPollMax = 500 * time.Millisecond +) + // upstreamConflictReadTimeout bounds the single re-read resolveConcurrentRefreshConflict // performs after a CAS conflict. It is deliberately much shorter than refreshTimeout: // the caller of RefreshAndStore is already blocked on refreshTimeout (30s) via the @@ -53,6 +82,14 @@ const upstreamConflictReadTimeout = 5 * time.Second // identity returned by UpstreamTokenStorage, but only WITHIN THIS PROCESS // — it saves redundant upstream calls and redis round-trips when this // process alone receives several concurrent requests for the same row. +// - locker, when the storage backend provides one, serializes the whole +// read-redeem-write sequence ACROSS PROCESSES with a lease over the same +// row identity singleflight uses, so only the lease holder calls the +// upstream provider. This is what keeps a strict single-use-rotation IdP +// from seeing two replicas redeem one refresh token as a replay. A +// backend that does not provide the capability leaves it nil, and the +// refresher falls back to the layer below, which orders the stored row +// but cannot prevent the duplicate redemption. // - CompareAndSwapUpstreamTokens (see refreshAndStore) makes the STORED row // deterministic ACROSS PROCESSES: every write is conditioned on the refresh // token this call redeemed still being the one stored, so a replica whose @@ -67,8 +104,15 @@ const upstreamConflictReadTimeout = 5 * time.Second // the provider-behavior-dependent discussion. singleflight is an // optimization layered on top of the CAS guarantee, not a substitute for it. type upstreamTokenRefresher struct { - providers map[string]upstream.OAuth2Provider - storage storage.UpstreamTokenStorage + providers map[string]upstream.OAuth2Provider + storage storage.UpstreamTokenStorage + + // locker is the storage backend's optional cross-process refresh lease, + // resolved once at construction. It is nil for a backend that does not + // provide one, which is harmless for a single-process backend and degrades + // to CAS-only coordination for any other. + locker storage.UpstreamRefreshLocker + refreshTokenLifespan time.Duration sfGroup singleflight.Group } @@ -77,7 +121,10 @@ type upstreamTokenRefresher struct { var _ storage.UpstreamTokenRefresher = (*upstreamTokenRefresher)(nil) // RefreshAndStore validates deterministic input errors before resolving the -// opaque storage-row identity used to deduplicate a refresh within this process. +// opaque storage-row identity used to deduplicate a refresh within this process +// and, when the backend supports it, to take that row's cross-process refresh +// lease (see coordinatedRefresh). +// // The leader re-reads that row under a detached timeout so it never redeems a // stale refresh token supplied by a caller. It only short-circuits on that // re-read when the row is unexpired AND differs from the caller's row, i.e. @@ -112,27 +159,7 @@ func (r *upstreamTokenRefresher) RefreshAndStore( refreshCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), refreshTimeout) defer cancel() - authoritative, readErr := r.storage.GetUpstreamTokens(refreshCtx, sessionID, expired.ProviderID) - if readErr == nil { - // Some storage implementations may return tokens without checking - // access-token expiry (the interface does not require it; see - // storage.UpstreamTokenStorage.GetUpstreamTokens). Only short-circuit - // when the re-read row is actually unexpired; otherwise fall through - // and refresh using it as the authoritative row. - if authoritative == nil { - return nil, fmt.Errorf( - "upstream token row missing on re-read for provider %q", expired.ProviderID, - ) - } - if !authoritative.IsExpired(time.Now()) && rowChanged(expired, authoritative) { - return authoritative, nil - } - return r.refreshAndStore(refreshCtx, sessionID, authoritative) - } - if !errors.Is(readErr, storage.ErrExpired) || authoritative == nil { - return nil, readErr - } - return r.refreshAndStore(refreshCtx, sessionID, authoritative) + return r.coordinatedRefresh(refreshCtx, sessionID, rowID, expired) }) if err != nil { return nil, err @@ -145,6 +172,154 @@ func (r *upstreamTokenRefresher) RefreshAndStore( return &refreshedCopy, nil } +// coordinatedRefresh runs the leader half of RefreshAndStore under the storage +// backend's cross-process refresh lease, when it provides one. +// +// Holding the lease is what stops two replicas redeeming the same single-use +// refresh token. A replica that cannot take it must therefore never fall +// through to the upstream provider: it waits, re-reading the row, until either +// the holder's refreshed row appears — which is the result it was waiting for — +// or the lease becomes free, in which case the holder died or its lease expired +// and this replica takes over as leader. Running out of refreshCtx while +// waiting is a failure, not a licence to redeem uncoordinated. +// +// A backend without the capability (locker nil) refreshes directly, exactly as +// before this layer existed: correct for a single-process backend, and +// CAS-only coordination for any other. +func (r *upstreamTokenRefresher) coordinatedRefresh( + ctx context.Context, + sessionID string, + rowID storage.UpstreamTokenRowID, + caller *storage.UpstreamTokens, +) (*storage.UpstreamTokens, error) { + if r.locker == nil { + return r.refreshAuthoritativeRow(ctx, sessionID, caller) + } + + wait := upstreamRefreshLockPollInitial + for { + // Checked before each attempt so an expiry that coincides with a wait + // is reported as the timeout it is, rather than as whatever error the + // backend returns for an already-cancelled context. + if err := ctx.Err(); err != nil { + return nil, fmt.Errorf( + "timed out waiting for another replica to refresh upstream tokens for provider %q: %w", + caller.ProviderID, err, + ) + } + + lease, err := r.locker.AcquireUpstreamRefreshLock(ctx, rowID, upstreamRefreshLeaseTTL) + if err == nil { + return r.refreshHoldingLease(ctx, sessionID, lease, caller) + } + if !errors.Is(err, storage.ErrUpstreamRefreshLockHeld) { + // The backend could not be consulted, so this replica cannot know + // whether another one is redeeming right now. Fail closed rather + // than redeem and risk the IdP seeing a replay. + return nil, fmt.Errorf( + "could not acquire upstream refresh lock for provider %q: %w", caller.ProviderID, err, + ) + } + + select { + case <-ctx.Done(): + return nil, fmt.Errorf( + "timed out waiting for another replica to refresh upstream tokens for provider %q: %w", + caller.ProviderID, ctx.Err(), + ) + case <-time.After(wait): + } + wait = min(wait*2, upstreamRefreshLockPollMax) + + if winner := r.refreshedByLeaseHolder(ctx, sessionID, caller); winner != nil { + slog.Debug("another replica refreshed the upstream token row while this one waited", + "provider_id", caller.ProviderID, + ) + return winner, nil + } + } +} + +// refreshHoldingLease runs the leader half and gives the lease back, so a +// waiter can proceed without sitting out upstreamRefreshLeaseTTL. The release +// runs on every exit path, including the short-circuit where no upstream call +// was made at all. +func (r *upstreamTokenRefresher) refreshHoldingLease( + ctx context.Context, + sessionID string, + lease storage.UpstreamRefreshLease, + caller *storage.UpstreamTokens, +) (*storage.UpstreamTokens, error) { + defer func() { + releaseCtx, cancel := context.WithTimeout( + context.WithoutCancel(ctx), upstreamRefreshLeaseReleaseTimeout, + ) + defer cancel() + if err := lease.Release(releaseCtx); err != nil { + // Not a correctness failure: the lease expires on its own, so this + // only delays the next waiter by at most upstreamRefreshLeaseTTL. + slog.Warn("failed to release upstream refresh lock; it expires on its own", + "provider_id", caller.ProviderID, + "error", err, + ) + } + }() + + return r.refreshAuthoritativeRow(ctx, sessionID, caller) +} + +// refreshedByLeaseHolder reports the row a lease holder stored while this +// caller waited, or nil when there is nothing usable to return yet. +// +// The test is deliberately the same one refreshAuthoritativeRow short-circuits +// on — unexpired AND different from the row the caller arrived with — so a +// waiter accepts exactly what a leader would have accepted on its own re-read. +// Anything else (the row unchanged, still expired, or a read failure) means +// the holder has not finished, so the caller keeps waiting rather than +// treating a transient read as a refusal. +func (r *upstreamTokenRefresher) refreshedByLeaseHolder( + ctx context.Context, sessionID string, caller *storage.UpstreamTokens, +) *storage.UpstreamTokens { + stored, err := r.storage.GetUpstreamTokens(ctx, sessionID, caller.ProviderID) + if err != nil || stored == nil { + return nil + } + if stored.IsExpired(time.Now()) || !rowChanged(caller, stored) { + return nil + } + return stored +} + +// refreshAuthoritativeRow re-reads the row the caller is refreshing and either +// returns a row another caller already refreshed or redeems the refresh token +// itself. It is the leader half of RefreshAndStore, and with a locker present +// it only ever runs while this process holds that row's lease. +func (r *upstreamTokenRefresher) refreshAuthoritativeRow( + ctx context.Context, sessionID string, caller *storage.UpstreamTokens, +) (*storage.UpstreamTokens, error) { + authoritative, readErr := r.storage.GetUpstreamTokens(ctx, sessionID, caller.ProviderID) + if readErr == nil { + // Some storage implementations may return tokens without checking + // access-token expiry (the interface does not require it; see + // storage.UpstreamTokenStorage.GetUpstreamTokens). Only short-circuit + // when the re-read row is actually unexpired; otherwise fall through + // and refresh using it as the authoritative row. + if authoritative == nil { + return nil, fmt.Errorf( + "upstream token row missing on re-read for provider %q", caller.ProviderID, + ) + } + if !authoritative.IsExpired(time.Now()) && rowChanged(caller, authoritative) { + return authoritative, nil + } + return r.refreshAndStore(ctx, sessionID, authoritative) + } + if !errors.Is(readErr, storage.ErrExpired) || authoritative == nil { + return nil, readErr + } + return r.refreshAndStore(ctx, sessionID, authoritative) +} + // refreshAndStore performs the actual token refresh and storage write. func (r *upstreamTokenRefresher) refreshAndStore( ctx context.Context, @@ -359,7 +534,10 @@ func (r *upstreamTokenRefresher) resolveConcurrentRefreshConflict( // call's refresh token with invalid_grant. A rotating provider answers that // way to the replica that loses a cross-process refresh race (singleflight // only deduplicates within this process), even though the winner has already -// stored a valid row. If the stored row now holds a different refresh token +// stored a valid row. The refresh lease (see coordinatedRefresh) is what +// normally stops two replicas reaching the provider at all, so this path now +// covers the cases it cannot: a backend that provides no lease, and a lease +// that expired under a holder slow enough for a waiter to take over. If the stored row now holds a different refresh token // and an unexpired access token, that row is the result to use, so a lost race // is not reported as a dead upstream credential. // diff --git a/pkg/authserver/refresher_lock_test.go b/pkg/authserver/refresher_lock_test.go new file mode 100644 index 0000000000..a55286bcae --- /dev/null +++ b/pkg/authserver/refresher_lock_test.go @@ -0,0 +1,329 @@ +// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package authserver + +import ( + "context" + "errors" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/mock/gomock" + + "github.com/stacklok/toolhive/pkg/authserver/storage" + storagemocks "github.com/stacklok/toolhive/pkg/authserver/storage/mocks" + "github.com/stacklok/toolhive/pkg/authserver/upstream" + upstreammocks "github.com/stacklok/toolhive/pkg/authserver/upstream/mocks" +) + +// fakeLocker stands in for a storage backend's UpstreamRefreshLocker. It is +// hand-written rather than generated because every case here turns on how the +// lease behaves over successive attempts — held, then free, then held by the +// caller — which reads far more clearly as a scripted sequence than as +// per-call mock expectations. +type fakeLocker struct { + // results is consumed one entry per acquisition attempt; the last entry + // repeats once exhausted, so a waiting caller can spin as long as it + // likes against a lease that never frees. + results []error + + attempts atomic.Int32 + released atomic.Int32 + releaseErr error + lastRowID atomic.Value // storage.UpstreamTokenRowID + lastLeaseTTL atomic.Int64 +} + +func (f *fakeLocker) AcquireUpstreamRefreshLock( + _ context.Context, rowID storage.UpstreamTokenRowID, ttl time.Duration, +) (storage.UpstreamRefreshLease, error) { + f.lastRowID.Store(rowID) + f.lastLeaseTTL.Store(int64(ttl)) + n := int(f.attempts.Add(1)) - 1 + if n >= len(f.results) { + n = len(f.results) - 1 + } + if err := f.results[n]; err != nil { + return nil, err + } + return &fakeLease{locker: f}, nil +} + +type fakeLease struct{ locker *fakeLocker } + +func (l *fakeLease) Release(context.Context) error { + l.locker.released.Add(1) + return l.locker.releaseErr +} + +// unexpiredRow is the row a lease holder is taken to have stored: unexpired, +// and carrying a refresh token the waiting caller has not seen. +func unexpiredRow() *storage.UpstreamTokens { + return &storage.UpstreamTokens{ + ProviderID: "github", + AccessToken: "access-rotated-refresh", + RefreshToken: "rotated-refresh", + ExpiresAt: time.Now().Add(time.Hour), + } +} + +func expiredRow(refreshToken string) *storage.UpstreamTokens { + return &storage.UpstreamTokens{ + ProviderID: "github", + AccessToken: "access-" + refreshToken, + RefreshToken: refreshToken, + UpstreamSubject: "subject", + ExpiresAt: time.Now().Add(-time.Hour), + } +} + +// TestCoordinatedRefresh_WaiterNeverRedeems is the core of issue #4122: a +// replica that does not hold the row's lease must not call the upstream +// provider, whatever happens while it waits. A provider mock with no +// RefreshTokens expectation fails the test if it is called. +func TestCoordinatedRefresh_WaiterNeverRedeems(t *testing.T) { + t.Parallel() + + held := storage.ErrUpstreamRefreshLockHeld + caller := expiredRow("old-refresh") + + t.Run("returns the holder's row once it appears", func(t *testing.T) { + t.Parallel() + ctrl := gomock.NewController(t) + store := storagemocks.NewMockUpstreamTokenStorage(ctrl) + winner := unexpiredRow() + + // First re-read still shows the caller's own row: the holder has not + // finished. The second shows the rotated row it stored. + gomock.InOrder( + store.EXPECT().GetUpstreamTokens(gomock.Any(), "session", "github").Return(caller, nil), + store.EXPECT().GetUpstreamTokens(gomock.Any(), "session", "github").Return(winner, nil), + ) + + locker := &fakeLocker{results: []error{held}} + r := newLockTestRefresher(t, ctrl, store, locker) + + got, err := r.coordinatedRefresh(t.Context(), "session", "row", caller) + require.NoError(t, err) + assert.Equal(t, winner, got, "the waiter must hand back what the holder stored") + assert.Zero(t, locker.released.Load(), "a waiter holds nothing, so it releases nothing") + }) + + t.Run("fails when the wait runs out", func(t *testing.T) { + t.Parallel() + ctrl := gomock.NewController(t) + store := storagemocks.NewMockUpstreamTokenStorage(ctrl) + // The holder never finishes, so every re-read keeps showing the + // caller's own row. + store.EXPECT().GetUpstreamTokens(gomock.Any(), "session", "github"). + AnyTimes().Return(caller, nil) + + locker := &fakeLocker{results: []error{held}} + r := newLockTestRefresher(t, ctrl, store, locker) + + ctx, cancel := context.WithTimeout(t.Context(), 120*time.Millisecond) + defer cancel() + + got, err := r.coordinatedRefresh(ctx, "session", "row", caller) + require.Error(t, err) + assert.Nil(t, got) + assert.ErrorIs(t, err, context.DeadlineExceeded, + "running out of time is a failure, not a licence to redeem uncoordinated") + assert.Greater(t, locker.attempts.Load(), int32(1), "the waiter should retry the lease") + }) + + t.Run("fails closed when the lock backend errors", func(t *testing.T) { + t.Parallel() + ctrl := gomock.NewController(t) + store := storagemocks.NewMockUpstreamTokenStorage(ctrl) + backendDown := errors.New("redis: connection refused") + + locker := &fakeLocker{results: []error{backendDown}} + r := newLockTestRefresher(t, ctrl, store, locker) + + got, err := r.coordinatedRefresh(t.Context(), "session", "row", caller) + require.Error(t, err) + assert.Nil(t, got) + assert.ErrorIs(t, err, backendDown) + assert.Equal(t, int32(1), locker.attempts.Load(), + "a backend fault is not retried; the caller cannot know whether another replica is redeeming") + }) + + t.Run("ignores a row that changed but is still expired", func(t *testing.T) { + t.Parallel() + ctrl := gomock.NewController(t) + store := storagemocks.NewMockUpstreamTokenStorage(ctrl) + // A different row, but expired: the holder has not produced anything + // usable, so the waiter must keep waiting rather than return it. + store.EXPECT().GetUpstreamTokens(gomock.Any(), "session", "github"). + AnyTimes().Return(expiredRow("some-other-refresh"), nil) + + locker := &fakeLocker{results: []error{held}} + r := newLockTestRefresher(t, ctrl, store, locker) + + ctx, cancel := context.WithTimeout(t.Context(), 120*time.Millisecond) + defer cancel() + + _, err := r.coordinatedRefresh(ctx, "session", "row", caller) + assert.ErrorIs(t, err, context.DeadlineExceeded) + }) +} + +// TestCoordinatedRefresh_TakesOverFreedLease covers the holder that crashed or +// whose lease expired: the row is unchanged, so the waiter must stop waiting +// and become the leader rather than sit out the TTL. +func TestCoordinatedRefresh_TakesOverFreedLease(t *testing.T) { + t.Parallel() + + ctrl := gomock.NewController(t) + store := storagemocks.NewMockUpstreamTokenStorage(ctrl) + caller := expiredRow("old-refresh") + + // Re-read after the first failed attempt: unchanged, so no winner. Then + // the leader's own authoritative re-read. + store.EXPECT().GetUpstreamTokens(gomock.Any(), "session", "github"). + Times(2).Return(caller, storage.ErrExpired) + store.EXPECT().CompareAndSwapUpstreamTokens( + gomock.Any(), "session", "github", "old-refresh", gomock.Any(), + ).Return(nil) + + provider := upstreammocks.NewMockOAuth2Provider(ctrl) + provider.EXPECT().RefreshTokens(gomock.Any(), "old-refresh", "subject"). + Return(&upstream.Tokens{ + AccessToken: "new-access", + RefreshToken: "new-refresh", + ExpiresAt: time.Now().Add(time.Hour), + }, nil) + + locker := &fakeLocker{results: []error{storage.ErrUpstreamRefreshLockHeld, nil}} + r := &upstreamTokenRefresher{ + providers: map[string]upstream.OAuth2Provider{"github": provider}, + storage: store, + locker: locker, + refreshTokenLifespan: 24 * time.Hour, + } + + got, err := r.coordinatedRefresh(t.Context(), "session", "row", caller) + require.NoError(t, err) + require.NotNil(t, got) + assert.Equal(t, "new-refresh", got.RefreshToken) + assert.Equal(t, int32(1), locker.released.Load(), "the new leader must give the lease back") +} + +// TestCoordinatedRefresh_LeaderReleases checks the lease is given back on +// every leader exit path, including the short-circuit where the row turned out +// to be fresh and no upstream call happened at all. A lease left behind would +// stall every other replica for its full TTL. +func TestCoordinatedRefresh_LeaderReleases(t *testing.T) { + t.Parallel() + + t.Run("after a short-circuit on the authoritative re-read", func(t *testing.T) { + t.Parallel() + ctrl := gomock.NewController(t) + store := storagemocks.NewMockUpstreamTokenStorage(ctrl) + winner := unexpiredRow() + store.EXPECT().GetUpstreamTokens(gomock.Any(), "session", "github").Return(winner, nil) + + locker := &fakeLocker{results: []error{nil}} + r := newLockTestRefresher(t, ctrl, store, locker) + + got, err := r.coordinatedRefresh(t.Context(), "session", "row", expiredRow("old-refresh")) + require.NoError(t, err) + assert.Equal(t, winner, got) + assert.Equal(t, int32(1), locker.released.Load()) + }) + + t.Run("after the refresh fails", func(t *testing.T) { + t.Parallel() + ctrl := gomock.NewController(t) + store := storagemocks.NewMockUpstreamTokenStorage(ctrl) + store.EXPECT().GetUpstreamTokens(gomock.Any(), "session", "github"). + Return(nil, errors.New("storage unavailable")) + + locker := &fakeLocker{results: []error{nil}} + r := newLockTestRefresher(t, ctrl, store, locker) + + _, err := r.coordinatedRefresh(t.Context(), "session", "row", expiredRow("old-refresh")) + require.Error(t, err) + assert.Equal(t, int32(1), locker.released.Load()) + }) + + t.Run("a failed release does not fail the refresh", func(t *testing.T) { + t.Parallel() + ctrl := gomock.NewController(t) + store := storagemocks.NewMockUpstreamTokenStorage(ctrl) + winner := unexpiredRow() + store.EXPECT().GetUpstreamTokens(gomock.Any(), "session", "github").Return(winner, nil) + + locker := &fakeLocker{results: []error{nil}, releaseErr: errors.New("redis: timeout")} + r := newLockTestRefresher(t, ctrl, store, locker) + + got, err := r.coordinatedRefresh(t.Context(), "session", "row", expiredRow("old-refresh")) + require.NoError(t, err, "the lease expires on its own; a failed release is only a delay") + assert.Equal(t, winner, got) + }) +} + +// TestCoordinatedRefresh_NoLocker checks a backend without the capability +// still refreshes, with the CAS write as its only cross-process coordination. +func TestCoordinatedRefresh_NoLocker(t *testing.T) { + t.Parallel() + + ctrl := gomock.NewController(t) + store := storagemocks.NewMockUpstreamTokenStorage(ctrl) + winner := unexpiredRow() + store.EXPECT().GetUpstreamTokens(gomock.Any(), "session", "github").Return(winner, nil) + + r := newLockTestRefresher(t, ctrl, store, nil) + + got, err := r.coordinatedRefresh(t.Context(), "session", "row", expiredRow("old-refresh")) + require.NoError(t, err) + assert.Equal(t, winner, got) +} + +// TestRefreshAndStore_TakesLeaseForResolvedRow checks the lease is taken for +// the same row identity the in-process singleflight group is keyed by, and for +// longer than the refresh deadline — if it could expire mid-redemption, a +// waiter would take over and redeem the same refresh token. +func TestRefreshAndStore_TakesLeaseForResolvedRow(t *testing.T) { + t.Parallel() + + ctrl := gomock.NewController(t) + store := storagemocks.NewMockUpstreamTokenStorage(ctrl) + rowID := storage.UpstreamTokenRowID("resolved-row-id") + store.EXPECT().ResolveUpstreamTokenRowID(gomock.Any(), "session", "github").Return(rowID, nil) + store.EXPECT().GetUpstreamTokens(gomock.Any(), "session", "github"). + Return(unexpiredRow(), nil) + + locker := &fakeLocker{results: []error{nil}} + r := newLockTestRefresher(t, ctrl, store, locker) + + _, err := r.RefreshAndStore(t.Context(), "session", expiredRow("old-refresh")) + require.NoError(t, err) + + assert.Equal(t, rowID, locker.lastRowID.Load(), + "the lease must cover the same row singleflight deduplicates") + assert.Greater(t, time.Duration(locker.lastLeaseTTL.Load()), refreshTimeout, + "the lease must outlast the holder's whole read-redeem-write sequence") +} + +// newLockTestRefresher builds a refresher whose provider mock has no +// RefreshTokens expectation, so any upstream redemption fails the test. +func newLockTestRefresher( + t *testing.T, + ctrl *gomock.Controller, + store storage.UpstreamTokenStorage, + locker storage.UpstreamRefreshLocker, +) *upstreamTokenRefresher { + t.Helper() + return &upstreamTokenRefresher{ + providers: map[string]upstream.OAuth2Provider{"github": upstreammocks.NewMockOAuth2Provider(ctrl)}, + storage: store, + locker: locker, + refreshTokenLifespan: 24 * time.Hour, + } +} diff --git a/pkg/authserver/server_impl.go b/pkg/authserver/server_impl.go index c15277af36..1a4d113bdd 100644 --- a/pkg/authserver/server_impl.go +++ b/pkg/authserver/server_impl.go @@ -1077,6 +1077,8 @@ func (s *server) UpstreamTokenRefresher() storage.UpstreamTokenRefresher { // newUpstreamTokenRefresher builds a refresher over the given upstreams, or nil // when there are none. Called once during newServer so the returned instance // can be shared between the handler and the UpstreamTokenRefresher() accessor. +// It also resolves the storage backend's optional cross-process refresh lease +// so every refresh path shares one, see upstreamTokenRefresher's doc. func newUpstreamTokenRefresher( upstreams []handlers.NamedUpstream, stor storage.UpstreamTokenStorage, @@ -1089,9 +1091,20 @@ func newUpstreamTokenRefresher( for _, u := range upstreams { providers[u.Name] = u.Provider } + // Resolve the backend's cross-process refresh lease once, here, rather + // 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) + if locker == nil { + slog.Debug("upstream token storage provides no cross-process refresh lock; " + + "concurrent refreshes are coordinated by compare-and-swap on the stored row only") + } + return &upstreamTokenRefresher{ providers: providers, storage: stor, + locker: locker, refreshTokenLifespan: refreshTokenLifespan, } } diff --git a/pkg/authserver/storage/memory.go b/pkg/authserver/storage/memory.go index 598d9941f6..6e83b24217 100644 --- a/pkg/authserver/storage/memory.go +++ b/pkg/authserver/storage/memory.go @@ -150,6 +150,14 @@ type MemoryStorage struct { // upstreamTokens maps (sessionID, providerName) -> timedEntry for multi-provider support. upstreamTokens map[upstreamKey]*timedEntry[*UpstreamTokens] + // upstreamRefreshLeases holds the live UpstreamRefreshLocker leases, keyed + // by the row identity ResolveUpstreamTokenRowID returns. An entry is + // removed when its holder releases it, so in the normal path the map holds + // only rows being refreshed right now; a holder that never releases is + // bounded by the lease's own expiry, which both AcquireUpstreamRefreshLock + // and cleanupExpired treat as absent. + upstreamRefreshLeases map[UpstreamTokenRowID]*memoryUpstreamRefreshLease + // pendingAuthorizations tracks authorization requests awaiting upstream IDP callback pendingAuthorizations map[string]*timedEntry[*PendingAuthorization] consentSessions map[string]*timedEntry[*ConsentSession] @@ -288,6 +296,7 @@ func NewMemoryStorage(opts ...MemoryStorageOption) *MemoryStorage { refreshTokens: make(map[string]*timedEntry[fosite.Requester]), pkceRequests: make(map[string]*timedEntry[fosite.Requester]), upstreamTokens: make(map[upstreamKey]*timedEntry[*UpstreamTokens]), + upstreamRefreshLeases: make(map[UpstreamTokenRowID]*memoryUpstreamRefreshLease), pendingAuthorizations: make(map[string]*timedEntry[*PendingAuthorization]), consentSessions: make(map[string]*timedEntry[*ConsentSession]), clientApprovals: make(map[[2]string]*timedEntry[*ClientApproval]), @@ -411,6 +420,13 @@ func (s *MemoryStorage) cleanupExpired() { } } + var expiredRefreshLeases []UpstreamTokenRowID + for k, v := range s.upstreamRefreshLeases { + if now.After(v.expiresAt) { + expiredRefreshLeases = append(expiredRefreshLeases, k) + } + } + var expiredPendingAuthorizations []string for k, v := range s.pendingAuthorizations { if now.After(v.expiresAt) { @@ -501,6 +517,7 @@ func (s *MemoryStorage) cleanupExpired() { len(expiredRefreshTokens) == 0 && len(expiredPKCERequests) == 0 && len(expiredUpstreamTokens) == 0 && + len(expiredRefreshLeases) == 0 && len(expiredPendingAuthorizations) == 0 && len(expiredConsentSessions) == 0 && len(expiredClientApprovals) == 0 && @@ -549,6 +566,15 @@ func (s *MemoryStorage) cleanupExpired() { delete(s.pkceRequests, k) } + for _, k := range expiredRefreshLeases { + // Re-check under the write lock: a lease collected as expired above may + // have been released and re-acquired by a new holder in between, and + // deleting that live lease would let a second refresh start alongside it. + if lease, ok := s.upstreamRefreshLeases[k]; ok && now.After(lease.expiresAt) { + delete(s.upstreamRefreshLeases, k) + } + } + for _, k := range expiredUpstreamTokens { delete(s.upstreamTokens, k) } @@ -1461,6 +1487,67 @@ func (s *MemoryStorage) StoreUpstreamTokens(_ context.Context, sessionID, provid return nil } +// memoryUpstreamRefreshLease is a held lease from AcquireUpstreamRefreshLock. +// It keeps a pointer back to the storage so Release can drop the entry, and +// its own expiry so a holder that outlives the lease cannot release a lease a +// later holder now owns. +type memoryUpstreamRefreshLease struct { + storage *MemoryStorage + rowID UpstreamTokenRowID + expiresAt time.Time +} + +// Release implements UpstreamRefreshLease. It deletes the entry only when this +// lease is still the one stored, so a holder whose lease already expired and +// was taken over cannot free the new holder's lease. It never returns an +// error; the write it performs cannot fail. +func (l *memoryUpstreamRefreshLease) Release(_ context.Context) error { + l.storage.mu.Lock() + defer l.storage.mu.Unlock() + + if current, ok := l.storage.upstreamRefreshLeases[l.rowID]; ok && current == l { + delete(l.storage.upstreamRefreshLeases, l.rowID) + } + return nil +} + +// AcquireUpstreamRefreshLock implements UpstreamRefreshLocker for the +// in-memory backend. See the interface doc for the coordination contract. +// +// This backend is reachable from exactly one process, so the cross-replica +// race the capability exists to prevent cannot occur here and the auth +// server's own singleflight group already deduplicates concurrent refreshes +// of one row. Rather than always granting the lease, this implements it for +// real — mutual exclusion over the row within this process, with the same +// expiry and ownership rules — so that the behaviour a caller relies on does +// not silently depend on which backend it was wired against, and so the same +// tests can cover both backends. The cost is one map operation under the +// mutex the backend already holds for every other write. +func (s *MemoryStorage) AcquireUpstreamRefreshLock( + _ context.Context, rowID UpstreamTokenRowID, ttl time.Duration, +) (UpstreamRefreshLease, error) { + if rowID == "" { + return nil, fosite.ErrInvalidRequest.WithHint("upstream token row ID cannot be empty") + } + if ttl <= 0 { + return nil, fosite.ErrInvalidRequest.WithHint("upstream refresh lock TTL must be positive") + } + + s.mu.Lock() + defer s.mu.Unlock() + + now := time.Now() + if held, ok := s.upstreamRefreshLeases[rowID]; ok && !now.After(held.expiresAt) { + return nil, ErrUpstreamRefreshLockHeld + } + + // Either no lease exists or the stored one expired; take it over. The + // previous holder's Release compares identity, so it cannot delete this one. + lease := &memoryUpstreamRefreshLease{storage: s, rowID: rowID, expiresAt: now.Add(ttl)} + s.upstreamRefreshLeases[rowID] = lease + return lease, nil +} + // CompareAndSwapUpstreamTokens stores tokens for (sessionID, providerName) // only if the refresh token currently held there equals expectedRefreshToken. // See the interface doc (UpstreamTokenStorage.CompareAndSwapUpstreamTokens) @@ -2541,6 +2628,7 @@ var ( _ PendingDeviceConfirmationStorage = (*MemoryStorage)(nil) _ ClientRegistry = (*MemoryStorage)(nil) _ UpstreamTokenStorage = (*MemoryStorage)(nil) + _ UpstreamRefreshLocker = (*MemoryStorage)(nil) _ UserStorage = (*MemoryStorage)(nil) _ DCRCredentialStore = (*MemoryStorage)(nil) _ AssertionJWTConsumer = (*MemoryStorage)(nil) diff --git a/pkg/authserver/storage/mocks/mock_storage.go b/pkg/authserver/storage/mocks/mock_storage.go index 8179b03131..bed303bd9e 100644 --- a/pkg/authserver/storage/mocks/mock_storage.go +++ b/pkg/authserver/storage/mocks/mock_storage.go @@ -3,7 +3,7 @@ // // Generated by this command: // -// mockgen -destination=mocks/mock_storage.go -package=mocks -source=types.go Storage,PendingAuthorizationStorage,DeviceCodeStorage,PendingDeviceLoginStorage,PendingDeviceConfirmationStorage,RememberedConsentStorage,AssertionJWTConsumer,ClientRegistry,UpstreamTokenStorage,UpstreamTokenRefresher,UserStorage,ExchangeGrantStorage +// mockgen -destination=mocks/mock_storage.go -package=mocks -source=types.go Storage,PendingAuthorizationStorage,DeviceCodeStorage,PendingDeviceLoginStorage,PendingDeviceConfirmationStorage,RememberedConsentStorage,AssertionJWTConsumer,ClientRegistry,UpstreamTokenStorage,UpstreamRefreshLocker,UpstreamRefreshLease,UpstreamTokenRefresher,UserStorage,ExchangeGrantStorage // // Package mocks is a generated GoMock package. @@ -808,6 +808,83 @@ func (mr *MockUpstreamTokenStorageMockRecorder) StoreUpstreamTokens(ctx, session return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StoreUpstreamTokens", reflect.TypeOf((*MockUpstreamTokenStorage)(nil).StoreUpstreamTokens), ctx, sessionID, providerName, tokens) } +// MockUpstreamRefreshLocker is a mock of UpstreamRefreshLocker interface. +type MockUpstreamRefreshLocker struct { + ctrl *gomock.Controller + recorder *MockUpstreamRefreshLockerMockRecorder + isgomock struct{} +} + +// MockUpstreamRefreshLockerMockRecorder is the mock recorder for MockUpstreamRefreshLocker. +type MockUpstreamRefreshLockerMockRecorder struct { + mock *MockUpstreamRefreshLocker +} + +// NewMockUpstreamRefreshLocker creates a new mock instance. +func NewMockUpstreamRefreshLocker(ctrl *gomock.Controller) *MockUpstreamRefreshLocker { + mock := &MockUpstreamRefreshLocker{ctrl: ctrl} + mock.recorder = &MockUpstreamRefreshLockerMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockUpstreamRefreshLocker) EXPECT() *MockUpstreamRefreshLockerMockRecorder { + return m.recorder +} + +// AcquireUpstreamRefreshLock mocks base method. +func (m *MockUpstreamRefreshLocker) AcquireUpstreamRefreshLock(ctx context.Context, rowID storage.UpstreamTokenRowID, ttl time.Duration) (storage.UpstreamRefreshLease, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "AcquireUpstreamRefreshLock", ctx, rowID, ttl) + ret0, _ := ret[0].(storage.UpstreamRefreshLease) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// AcquireUpstreamRefreshLock indicates an expected call of AcquireUpstreamRefreshLock. +func (mr *MockUpstreamRefreshLockerMockRecorder) AcquireUpstreamRefreshLock(ctx, rowID, ttl any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AcquireUpstreamRefreshLock", reflect.TypeOf((*MockUpstreamRefreshLocker)(nil).AcquireUpstreamRefreshLock), ctx, rowID, ttl) +} + +// MockUpstreamRefreshLease is a mock of UpstreamRefreshLease interface. +type MockUpstreamRefreshLease struct { + ctrl *gomock.Controller + recorder *MockUpstreamRefreshLeaseMockRecorder + isgomock struct{} +} + +// MockUpstreamRefreshLeaseMockRecorder is the mock recorder for MockUpstreamRefreshLease. +type MockUpstreamRefreshLeaseMockRecorder struct { + mock *MockUpstreamRefreshLease +} + +// NewMockUpstreamRefreshLease creates a new mock instance. +func NewMockUpstreamRefreshLease(ctrl *gomock.Controller) *MockUpstreamRefreshLease { + mock := &MockUpstreamRefreshLease{ctrl: ctrl} + mock.recorder = &MockUpstreamRefreshLeaseMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockUpstreamRefreshLease) EXPECT() *MockUpstreamRefreshLeaseMockRecorder { + return m.recorder +} + +// Release mocks base method. +func (m *MockUpstreamRefreshLease) Release(ctx context.Context) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Release", ctx) + ret0, _ := ret[0].(error) + return ret0 +} + +// Release indicates an expected call of Release. +func (mr *MockUpstreamRefreshLeaseMockRecorder) Release(ctx any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Release", reflect.TypeOf((*MockUpstreamRefreshLease)(nil).Release), ctx) +} + // MockUpstreamTokenRefresher is a mock of UpstreamTokenRefresher interface. type MockUpstreamTokenRefresher struct { ctrl *gomock.Controller diff --git a/pkg/authserver/storage/redis.go b/pkg/authserver/storage/redis.go index 33336e1556..84492ca2e3 100644 --- a/pkg/authserver/storage/redis.go +++ b/pkg/authserver/storage/redis.go @@ -5,6 +5,8 @@ package storage import ( "context" + "crypto/rand" + "encoding/hex" "encoding/json" "errors" "fmt" @@ -1813,6 +1815,86 @@ func (s *RedisStorage) ResolveUpstreamTokenRowID(_ context.Context, sessionID, p return upstreamTokenRowID(redisUpstreamKey(s.keyPrefix, sessionID, providerName)), nil } +// releaseUpstreamRefreshLockScript gives up a refresh lease only when the +// caller still owns it. The owner token is compared inside the script so the +// read and the delete cannot interleave with another replica's acquisition: +// without it, a holder whose lease had already expired could delete the lease +// a second replica legitimately took in the meantime, and both would then +// redeem the same refresh token — precisely the race the lease exists to +// prevent. +// +// KEYS[1] = lease key +// ARGV[1] = owner token this holder wrote on acquisition +// +// Returns 1 when this holder's lease was deleted, 0 when the stored lease +// belongs to someone else or has already expired. +var releaseUpstreamRefreshLockScript = redis.NewScript(` +if redis.call('GET', KEYS[1]) == ARGV[1] then + return redis.call('DEL', KEYS[1]) +end +return 0 +`) + +// redisUpstreamRefreshLease is a held lease from AcquireUpstreamRefreshLock. +type redisUpstreamRefreshLease struct { + client redis.UniversalClient + key string + owner string +} + +// Release implements UpstreamRefreshLease. It is idempotent: releasing a lease +// that already expired, or that a later holder now owns, deletes nothing and +// reports no error, because in both cases this holder no longer has anything +// to give up. +func (l *redisUpstreamRefreshLease) Release(ctx context.Context) error { + if _, err := releaseUpstreamRefreshLockScript.Run(ctx, l.client, []string{l.key}, l.owner).Result(); err != nil { + return fmt.Errorf("failed to release upstream refresh lock: %w", err) + } + return nil +} + +// AcquireUpstreamRefreshLock implements UpstreamRefreshLocker over Redis with +// a SET NX PX of a random owner token. See the interface doc for the +// coordination contract and for why this layer exists on top of +// CompareAndSwapUpstreamTokens. +// +// The TTL is what bounds a crashed holder's lease, so it must outlast the +// whole read-redeem-write sequence the caller runs while holding it; +// the caller supplies it (pkg/authserver sets it from its own refresh +// deadline). An acquisition that cannot reach Redis returns the error rather +// than a lease, so the caller fails closed instead of redeeming +// uncoordinated. +func (s *RedisStorage) AcquireUpstreamRefreshLock( + ctx context.Context, rowID UpstreamTokenRowID, ttl time.Duration, +) (UpstreamRefreshLease, error) { + if rowID == "" { + return nil, fosite.ErrInvalidRequest.WithHint("upstream token row ID cannot be empty") + } + if ttl <= 0 { + return nil, fosite.ErrInvalidRequest.WithHint("upstream refresh lock TTL must be positive") + } + + // The owner token only has to be unpredictable enough that no other holder + // writes the same value, so a losing release can never delete a winner's + // lease. It is never persisted beyond the lease's own TTL. + ownerBytes := make([]byte, 16) + if _, err := rand.Read(ownerBytes); err != nil { + return nil, fmt.Errorf("failed to generate upstream refresh lock owner: %w", err) + } + owner := hex.EncodeToString(ownerBytes) + + key := redisUpstreamRefreshLockKey(s.keyPrefix, rowID) + acquired, err := s.client.SetNX(ctx, key, owner, ttl).Result() + if err != nil { + return nil, fmt.Errorf("failed to acquire upstream refresh lock: %w", err) + } + if !acquired { + return nil, ErrUpstreamRefreshLockHeld + } + + return &redisUpstreamRefreshLease{client: s.client, key: key, owner: owner}, nil +} + // GetUpstreamTokens retrieves the upstream IDP tokens for a session and provider. // Returns a new UpstreamTokens struct deserialized from Redis, which acts as // a defensive copy - callers cannot modify the stored data by mutating the return value. @@ -3745,6 +3827,7 @@ var ( _ PendingDeviceConfirmationStorage = (*RedisStorage)(nil) _ ClientRegistry = (*RedisStorage)(nil) _ UpstreamTokenStorage = (*RedisStorage)(nil) + _ UpstreamRefreshLocker = (*RedisStorage)(nil) _ UserStorage = (*RedisStorage)(nil) _ DCRCredentialStore = (*RedisStorage)(nil) _ AssertionJWTConsumer = (*RedisStorage)(nil) diff --git a/pkg/authserver/storage/redis_keys.go b/pkg/authserver/storage/redis_keys.go index 6fa346d230..e91314dd47 100644 --- a/pkg/authserver/storage/redis_keys.go +++ b/pkg/authserver/storage/redis_keys.go @@ -80,6 +80,14 @@ const ( // Used by GetAllUpstreamTokens (bulk read) and DeleteUpstreamTokens (bulk delete). KeyTypeUpstreamIdx = "upstream:idx" + // KeyTypeUpstreamRefreshLock is the key type for the mutual-exclusion lease + // an auth server replica takes over one upstream token row before redeeming + // its refresh token upstream (see UpstreamRefreshLocker). Like + // KeyTypeDCRClientIdx, the name deliberately does not match the "upstream:*" + // scan pattern walked by migrateUpstreamTokenKeys, so a live lease can never + // be mistaken for a token row by the legacy-key migration. + KeyTypeUpstreamRefreshLock = "upstream-lock" + // KeyTypeUserUpstream is the key type for user to upstream token reverse lookups. KeyTypeUserUpstream = "user:upstream" @@ -208,3 +216,18 @@ func redisUpstreamKey(prefix, sessionID, providerName string) string { func redisSetKey(prefix, keyType, id string) string { return fmt.Sprintf("%s%s:%s", prefix, keyType, id) } + +// redisUpstreamRefreshLockKey generates a Redis key for the refresh lease over +// one upstream token row. Format: "{prefix}upstream-lock:{rowID}". +// +// The row identity is UpstreamTokenRowID, the same value the auth server's +// in-process singleflight group is keyed by, so the two coordination layers +// cover exactly the same set of rows by construction: whatever +// ResolveUpstreamTokenRowID considers one row holds one lease. It is a +// SHA-256 hex digest, so it contains no colon and needs no length prefix, and +// it keeps the session ID out of the key name. The key shares the prefix's +// {ns:name} hash tag, so it lands in the same Redis Cluster slot as the row it +// guards. +func redisUpstreamRefreshLockKey(prefix string, rowID UpstreamTokenRowID) string { + return fmt.Sprintf("%s%s:%s", prefix, KeyTypeUpstreamRefreshLock, rowID) +} diff --git a/pkg/authserver/storage/types.go b/pkg/authserver/storage/types.go index c1c9612a7b..0dbca328da 100644 --- a/pkg/authserver/storage/types.go +++ b/pkg/authserver/storage/types.go @@ -16,7 +16,7 @@ // OAuth authorization server. package storage -//go:generate mockgen -destination=mocks/mock_storage.go -package=mocks -source=types.go Storage,PendingAuthorizationStorage,DeviceCodeStorage,PendingDeviceLoginStorage,PendingDeviceConfirmationStorage,RememberedConsentStorage,AssertionJWTConsumer,ClientRegistry,UpstreamTokenStorage,UpstreamTokenRefresher,UserStorage,ExchangeGrantStorage +//go:generate mockgen -destination=mocks/mock_storage.go -package=mocks -source=types.go Storage,PendingAuthorizationStorage,DeviceCodeStorage,PendingDeviceLoginStorage,PendingDeviceConfirmationStorage,RememberedConsentStorage,AssertionJWTConsumer,ClientRegistry,UpstreamTokenStorage,UpstreamRefreshLocker,UpstreamRefreshLease,UpstreamTokenRefresher,UserStorage,ExchangeGrantStorage //go:generate mockgen -destination=mocks/mock_dcr_store.go -package=mocks github.com/stacklok/toolhive/pkg/authserver/storage DCRCredentialStore @@ -99,6 +99,16 @@ var ( // CompareAndSwapUpstreamTokens for the full coordination contract). ErrConcurrentRefresh = errors.New("storage: upstream token row changed concurrently") + // ErrUpstreamRefreshLockHeld is returned by + // UpstreamRefreshLocker.AcquireUpstreamRefreshLock when another holder — in + // this process or in another replica sharing the backend — already holds + // the lease for that row. It means "someone else is refreshing right now", + // which is an ordinary outcome, not a fault: the caller must wait and + // re-read the row rather than redeem the refresh token itself. Every other + // error from AcquireUpstreamRefreshLock is a backend fault, and the caller + // must fail closed rather than redeem without coordination. + ErrUpstreamRefreshLockHeld = errors.New("storage: upstream refresh lock held by another holder") + // ErrDCRCredentialsChanged is returned by // DCRCredentialStore.UpdateDCRCredentialsIfUnchanged when the stored row // no longer equals the caller's expected value: another writer replaced it @@ -1232,8 +1242,11 @@ type ClientRegistry interface { RenewClientTTL(ctx context.Context, client fosite.Client) error } -// UpstreamTokenRowID is an opaque, process-local coordination key for one -// logical upstream token row. Callers must not persist, log, or expose it. +// UpstreamTokenRowID is an opaque coordination key for one logical upstream +// token row. Callers must not log it or expose it outside the refresh +// coordination path. The only place it may be written is a backend's own +// UpstreamRefreshLocker lease key, which is derived from it and lives no +// longer than the lease. type UpstreamTokenRowID string // upstreamTokenRowID returns a SHA-256 digest of the supplied row-key components. @@ -1272,8 +1285,9 @@ type UpstreamTokenStorage interface { // Resolution must be local and side-effect-free (no I/O): it is called // before the singleflight joins, so any I/O here gives every concurrent // caller its own round-trip and partially defeats the deduplication. This - // ID is solely for process-local refresh coordination: callers must not - // persist, log, or expose it. + // ID is solely for refresh coordination — the in-process singleflight + // group and the UpstreamRefreshLocker lease over the same row — and must + // not be logged or exposed outside it. ResolveUpstreamTokenRowID(ctx context.Context, sessionID, providerName string) (UpstreamTokenRowID, error) // StoreUpstreamTokens stores the upstream IDP tokens for a session and provider. @@ -1395,6 +1409,68 @@ type UpstreamTokenStorage interface { GetLatestUpstreamTokensForUser(ctx context.Context, userID, providerID string) (*UpstreamTokens, error) } +// UpstreamRefreshLocker is an OPTIONAL capability of an UpstreamTokenStorage +// backend: a mutual-exclusion lease over one logical upstream token row, +// honoured by every process sharing that backend. +// +// # Why this exists on top of CompareAndSwapUpstreamTokens +// +// CompareAndSwapUpstreamTokens makes the STORED row deterministic across +// replicas: a losing writer fails instead of clobbering the winner. It does +// not stop the losing replica from CALLING the upstream provider, because +// both replicas redeem before either one writes. An IdP enforcing strict +// single-use refresh token rotation (RFC 9700 §4.14.2 replay detection) sees +// those two redemptions of one refresh token as a replay and may revoke the +// whole grant — regardless of which write won. Closing that gap requires +// serializing the read-redeem-write sequence itself, which is what this lease +// provides. +// +// # Contract +// +// Acquisition is non-blocking: it either takes the lease or reports +// ErrUpstreamRefreshLockHeld immediately. Waiting, re-reading the row and +// retrying are the caller's job, so a caller can abandon the wait as soon as +// the row it is waiting for has been refreshed by the holder. +// +// The lease is advisory and bounded by ttl: it expires on its own so a holder +// that crashes mid-refresh cannot block the row forever. A caller must +// therefore treat holding the lease as a strong hint, not a hard guarantee, +// and still write through CompareAndSwapUpstreamTokens — the two layers are +// complementary. Implementations must make expiry and release safe against a +// stale holder: releasing must only delete the caller's own lease, never one +// a later holder acquired after this one expired. +// +// # Detection +// +// This capability is deliberately NOT embedded in UpstreamTokenStorage, +// following the same segregation as DeviceCodeStorage and ExchangeGrantStorage: +// a single-process backend does not need it, and embedding it would force +// every future implementation to provide it. Obtain it with +// UpstreamRefreshLockerFrom, which also peels storage decorators. A backend +// without it degrades to CAS-only coordination. +type UpstreamRefreshLocker interface { + // AcquireUpstreamRefreshLock tries to take the lease for rowID for at most + // ttl. It returns the lease on success, ErrUpstreamRefreshLockHeld when + // another holder has it, and any other error when the backend could not be + // consulted at all. + AcquireUpstreamRefreshLock( + ctx context.Context, rowID UpstreamTokenRowID, ttl time.Duration, + ) (UpstreamRefreshLease, error) +} + +// UpstreamRefreshLease is a held lock from +// UpstreamRefreshLocker.AcquireUpstreamRefreshLock. +type UpstreamRefreshLease interface { + // Release gives up the lease so a waiter can proceed without waiting out + // the TTL. It must be idempotent, and must not release a lease that a + // later holder acquired after this one expired. Release takes its own + // context because the context that governed the refresh is typically + // already cancelled by the time the caller unwinds. An error means the + // lease may still be held until its TTL expires; that is not a correctness + // failure, only a delay for the next waiter. + Release(ctx context.Context) error +} + // UpstreamTokenRefresher can refresh expired upstream tokens using their stored refresh token. // This is implemented by the auth server and used by the upstreamswap middleware to // transparently refresh tokens without forcing re-authentication. diff --git a/pkg/authserver/storage/unwrap.go b/pkg/authserver/storage/unwrap.go index 77b05e402a..adeac11f0d 100644 --- a/pkg/authserver/storage/unwrap.go +++ b/pkg/authserver/storage/unwrap.go @@ -15,3 +15,23 @@ func Unwrap(stor Storage) Storage { stor = unwrapper.Unwrap() } } + +// UpstreamRefreshLockerFrom returns the UpstreamRefreshLocker capability of +// stor, peeling any storage decorators that expose Unwrap, and nil when no +// layer in the chain provides it. Decorators embed the Storage interface and +// so do not carry optional capabilities of the backend they wrap, which is why +// the type assertion alone is not enough — mirrors the Unwrap use at the +// ExchangeGrantStorage discovery boundary. +func UpstreamRefreshLockerFrom(stor UpstreamTokenStorage) UpstreamRefreshLocker { + for stor != nil { + if locker, ok := stor.(UpstreamRefreshLocker); ok { + return locker + } + unwrapper, ok := stor.(interface{ Unwrap() Storage }) + if !ok { + return nil + } + stor = unwrapper.Unwrap() + } + return nil +} diff --git a/pkg/authserver/storage/upstream_refresh_lock_test.go b/pkg/authserver/storage/upstream_refresh_lock_test.go new file mode 100644 index 0000000000..3f612b68cd --- /dev/null +++ b/pkg/authserver/storage/upstream_refresh_lock_test.go @@ -0,0 +1,235 @@ +// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package storage + +import ( + "context" + "testing" + "time" + + "github.com/ory/fosite" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// lockerBackend names one UpstreamRefreshLocker implementation and supplies a +// fresh instance plus a way to push its leases past their TTL. Both backends +// run the same cases so the contract (non-blocking acquisition, takeover after +// expiry, ownership-checked release) cannot drift between them. +type lockerBackend struct { + name string + // with runs fn against a fresh backend. expire advances that backend past + // d so an already-acquired lease is seen as expired, without the test + // sleeping for a real TTL. + with func(t *testing.T, fn func(ctx context.Context, locker UpstreamRefreshLocker, expire func(d time.Duration))) +} + +func lockerBackends() []lockerBackend { + return []lockerBackend{ + { + name: "memory", + with: func(t *testing.T, fn func(context.Context, UpstreamRefreshLocker, func(time.Duration))) { + t.Helper() + s := NewMemoryStorage() + t.Cleanup(func() { _ = s.Close() }) + // MemoryStorage stamps leases from the wall clock, so the only + // way to pass their expiry is to wait it out. Every caller + // below asks for a TTL small enough that this is a few + // milliseconds. + fn(t.Context(), s, func(d time.Duration) { time.Sleep(d) }) + }, + }, + { + name: "redis", + with: func(t *testing.T, fn func(context.Context, UpstreamRefreshLocker, func(time.Duration))) { + t.Helper() + s, mr := newTestRedisStorage(t) + t.Cleanup(func() { + _ = s.Close() + mr.Close() + }) + fn(t.Context(), s, mr.FastForward) + }, + }, + } +} + +const testRowID = UpstreamTokenRowID("row-under-test") + +// TestAcquireUpstreamRefreshLock covers the capability that keeps two replicas +// from redeeming the same single-use upstream refresh token: only one of them +// may hold a row's lease at a time, and a holder that never releases must not +// block the row beyond the lease TTL. +func TestAcquireUpstreamRefreshLock(t *testing.T) { + t.Parallel() + + for _, backend := range lockerBackends() { + t.Run(backend.name, func(t *testing.T) { + t.Parallel() + + t.Run("second acquisition of a held row reports ErrUpstreamRefreshLockHeld", func(t *testing.T) { + t.Parallel() + backend.with(t, func(ctx context.Context, locker UpstreamRefreshLocker, _ func(time.Duration)) { + lease, err := locker.AcquireUpstreamRefreshLock(ctx, testRowID, time.Minute) + require.NoError(t, err) + require.NotNil(t, lease) + + second, err := locker.AcquireUpstreamRefreshLock(ctx, testRowID, time.Minute) + assert.Nil(t, second) + assert.ErrorIs(t, err, ErrUpstreamRefreshLockHeld, + "a waiter must be told to wait, not handed a second lease") + }) + }) + + t.Run("a different row is unaffected by a held lease", func(t *testing.T) { + t.Parallel() + backend.with(t, func(ctx context.Context, locker UpstreamRefreshLocker, _ func(time.Duration)) { + _, err := locker.AcquireUpstreamRefreshLock(ctx, testRowID, time.Minute) + require.NoError(t, err) + + other, err := locker.AcquireUpstreamRefreshLock(ctx, "another-row", time.Minute) + require.NoError(t, err, "the lease is per row, not global") + assert.NotNil(t, other) + }) + }) + + t.Run("release lets the next caller take the lease", func(t *testing.T) { + t.Parallel() + backend.with(t, func(ctx context.Context, locker UpstreamRefreshLocker, _ func(time.Duration)) { + lease, err := locker.AcquireUpstreamRefreshLock(ctx, testRowID, time.Minute) + require.NoError(t, err) + require.NoError(t, lease.Release(ctx)) + + next, err := locker.AcquireUpstreamRefreshLock(ctx, testRowID, time.Minute) + require.NoError(t, err, "a released lease must not make a waiter sit out the TTL") + assert.NotNil(t, next) + }) + }) + + t.Run("releasing twice is a no-op", func(t *testing.T) { + t.Parallel() + backend.with(t, func(ctx context.Context, locker UpstreamRefreshLocker, _ func(time.Duration)) { + lease, err := locker.AcquireUpstreamRefreshLock(ctx, testRowID, time.Minute) + require.NoError(t, err) + require.NoError(t, lease.Release(ctx)) + assert.NoError(t, lease.Release(ctx)) + }) + }) + + t.Run("a lease that expires can be taken over", func(t *testing.T) { + t.Parallel() + backend.with(t, func(ctx context.Context, locker UpstreamRefreshLocker, expire func(time.Duration)) { + _, err := locker.AcquireUpstreamRefreshLock(ctx, testRowID, 20*time.Millisecond) + require.NoError(t, err) + + expire(40 * time.Millisecond) + + takenOver, err := locker.AcquireUpstreamRefreshLock(ctx, testRowID, time.Minute) + require.NoError(t, err, "a crashed holder must not block the row past its TTL") + assert.NotNil(t, takenOver) + }) + }) + + t.Run("an expired holder's release does not free the new holder's lease", func(t *testing.T) { + t.Parallel() + backend.with(t, func(ctx context.Context, locker UpstreamRefreshLocker, expire func(time.Duration)) { + stale, err := locker.AcquireUpstreamRefreshLock(ctx, testRowID, 20*time.Millisecond) + require.NoError(t, err) + + expire(40 * time.Millisecond) + + _, err = locker.AcquireUpstreamRefreshLock(ctx, testRowID, time.Minute) + require.NoError(t, err) + + // The stale holder unwinds late and releases. If that + // deleted the new holder's lease, a third replica could + // start redeeming alongside it. + require.NoError(t, stale.Release(ctx)) + + third, err := locker.AcquireUpstreamRefreshLock(ctx, testRowID, time.Minute) + assert.Nil(t, third) + assert.ErrorIs(t, err, ErrUpstreamRefreshLockHeld, + "the live holder's lease must survive a stale holder's release") + }) + }) + + t.Run("rejects an empty row ID and a non-positive TTL", func(t *testing.T) { + t.Parallel() + backend.with(t, func(ctx context.Context, locker UpstreamRefreshLocker, _ func(time.Duration)) { + _, err := locker.AcquireUpstreamRefreshLock(ctx, "", time.Minute) + assert.ErrorIs(t, err, fosite.ErrInvalidRequest) + + _, err = locker.AcquireUpstreamRefreshLock(ctx, testRowID, 0) + assert.ErrorIs(t, err, fosite.ErrInvalidRequest) + }) + }) + }) + } +} + +// TestMemoryStorage_cleanupExpiredRefreshLeases checks that a lease nobody +// releases does not accumulate in the in-memory backend, and that the sweep +// cannot take a live lease with it. +func TestMemoryStorage_cleanupExpiredRefreshLeases(t *testing.T) { + t.Parallel() + + // withStorage calls t.Parallel on the subtest. + t.Run("sweeps an expired lease and keeps a live one", func(t *testing.T) { + withStorage(t, func(ctx context.Context, s *MemoryStorage) { + _, err := s.AcquireUpstreamRefreshLock(ctx, "expiring-row", 10*time.Millisecond) + require.NoError(t, err) + _, err = s.AcquireUpstreamRefreshLock(ctx, "live-row", time.Hour) + require.NoError(t, err) + + time.Sleep(30 * time.Millisecond) + s.cleanupExpired() + + s.mu.RLock() + _, expiredPresent := s.upstreamRefreshLeases["expiring-row"] + _, livePresent := s.upstreamRefreshLeases["live-row"] + s.mu.RUnlock() + + assert.False(t, expiredPresent, "an expired lease should be swept") + assert.True(t, livePresent, "a live lease must survive the sweep") + }) + }) +} + +// TestUpstreamRefreshLockerFrom covers capability discovery. Decorators embed +// the Storage interface, so they do not carry the backend's optional +// capabilities; the helper has to peel them or the refresher would silently +// lose cross-process coordination whenever a decorator is installed. +func TestUpstreamRefreshLockerFrom(t *testing.T) { + t.Parallel() + + t.Run("finds the capability on a bare backend", func(t *testing.T) { + t.Parallel() + s := NewMemoryStorage() + t.Cleanup(func() { _ = s.Close() }) + assert.NotNil(t, UpstreamRefreshLockerFrom(s)) + }) + + t.Run("finds the capability through a decorator", func(t *testing.T) { + t.Parallel() + s := NewMemoryStorage() + t.Cleanup(func() { _ = s.Close() }) + assert.NotNil(t, UpstreamRefreshLockerFrom(NewCIMDShapeGuardStorage(s))) + }) + + t.Run("returns nil for a backend without the capability", func(t *testing.T) { + t.Parallel() + assert.Nil(t, UpstreamRefreshLockerFrom(lockerlessStorage{})) + }) + + t.Run("returns nil for a nil storage", func(t *testing.T) { + t.Parallel() + assert.Nil(t, UpstreamRefreshLockerFrom(nil)) + }) +} + +// lockerlessStorage is an UpstreamTokenStorage that provides neither the lock +// capability nor Unwrap, standing in for a third-party backend. +type lockerlessStorage struct { + UpstreamTokenStorage +} From 5f075c45bf3adc0f00d2673ba32df5f87c076f9e Mon Sep 17 00:00:00 2001 From: hellouz818 Date: Tue, 3 Nov 2026 15:08:14 +0900 Subject: [PATCH 2/8] Correct how the lease waiter retries acquisition 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: #4122 Signed-off-by: hellouz818 --- docs/arch/11-auth-server-storage.md | 9 +++++---- pkg/authserver/refresher.go | 28 +++++++++++++++++----------- 2 files changed, 22 insertions(+), 15 deletions(-) diff --git a/docs/arch/11-auth-server-storage.md b/docs/arch/11-auth-server-storage.md index 2469777181..95bc5e7c73 100644 --- a/docs/arch/11-auth-server-storage.md +++ b/docs/arch/11-auth-server-storage.md @@ -503,10 +503,11 @@ A replica that cannot take the lease never falls through to the provider. It waits on a capped exponential backoff, re-reading the row after each wait, and returns the holder's row as soon as that row satisfies the same test the leader uses on its own re-read: unexpired *and* different from the row the -caller arrived with. If the lease becomes free while the row is unchanged — -the holder crashed, or its lease expired — the waiter takes over as leader. If -`refreshTimeout` runs out first, the refresh fails; running out of time is not -a licence to redeem uncoordinated. An acquisition that fails for any reason +caller arrived with. If no usable updated row is available, the waiter retries +lease acquisition. After acquiring the lease, it re-reads the row before +deciding whether an upstream refresh is still needed. If `refreshTimeout` runs +out first, the refresh fails; running out of time is not a licence to redeem +uncoordinated. An acquisition that fails for any reason other than "held by someone else" also fails closed, because a replica that cannot reach the backend cannot know whether another one is redeeming. diff --git a/pkg/authserver/refresher.go b/pkg/authserver/refresher.go index 283c197718..a30ff49f62 100644 --- a/pkg/authserver/refresher.go +++ b/pkg/authserver/refresher.go @@ -177,11 +177,14 @@ func (r *upstreamTokenRefresher) RefreshAndStore( // // Holding the lease is what stops two replicas redeeming the same single-use // refresh token. A replica that cannot take it must therefore never fall -// through to the upstream provider: it waits, re-reading the row, until either -// the holder's refreshed row appears — which is the result it was waiting for — -// or the lease becomes free, in which case the holder died or its lease expired -// and this replica takes over as leader. Running out of refreshCtx while -// waiting is a failure, not a licence to redeem uncoordinated. +// through to the upstream provider: it waits, re-reading the row, and returns +// the row a holder stored as soon as that row is usable. When no usable row +// has appeared it retries acquisition, and whichever attempt succeeds re-reads +// the row before deciding whether an upstream refresh is still needed. A free +// lease is not by itself evidence that anything went wrong — the holder +// releases it on its normal success path too — so taking it is not a licence +// to redeem without looking. Running out of refreshCtx while waiting is a +// failure, not a licence to redeem uncoordinated. // // A backend without the capability (locker nil) refreshes directly, exactly as // before this layer existed: correct for a single-process backend, and @@ -274,9 +277,11 @@ func (r *upstreamTokenRefresher) refreshHoldingLease( // The test is deliberately the same one refreshAuthoritativeRow short-circuits // on — unexpired AND different from the row the caller arrived with — so a // waiter accepts exactly what a leader would have accepted on its own re-read. -// Anything else (the row unchanged, still expired, or a read failure) means -// the holder has not finished, so the caller keeps waiting rather than -// treating a transient read as a refusal. +// Anything else (the row unchanged, still expired, or a read failure) is not +// a result, so the caller goes back to contending for the lease rather than +// treating a transient read as a refusal. It is deliberately silent about WHY +// there is nothing to return: the holder may still be working, or it may have +// died — the caller's next move is the same either way. func (r *upstreamTokenRefresher) refreshedByLeaseHolder( ctx context.Context, sessionID string, caller *storage.UpstreamTokens, ) *storage.UpstreamTokens { @@ -537,9 +542,10 @@ func (r *upstreamTokenRefresher) resolveConcurrentRefreshConflict( // stored a valid row. The refresh lease (see coordinatedRefresh) is what // normally stops two replicas reaching the provider at all, so this path now // covers the cases it cannot: a backend that provides no lease, and a lease -// that expired under a holder slow enough for a waiter to take over. If the stored row now holds a different refresh token -// and an unexpired access token, that row is the result to use, so a lost race -// is not reported as a dead upstream credential. +// that expired under a holder slow enough for a waiter to take over. If the +// stored row now holds a different refresh token and an unexpired access +// token, that row is the result to use, so a lost race is not reported as a +// dead upstream credential. // // "Another process refreshed" is tested by refresh-token inequality, unlike // rowChanged, which also compares the access token, ID token and expiry. The From 2b71fd0756be479d270582b017460b509dbba689 Mon Sep 17 00:00:00 2001 From: hellouz818 Date: Tue, 3 Nov 2026 15:08:24 +0900 Subject: [PATCH 3/8] Test two replicas redeem a refresh token once 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: #4122 Signed-off-by: hellouz818 --- pkg/authserver/refresher_contention_test.go | 206 ++++++++++++++++++++ 1 file changed, 206 insertions(+) create mode 100644 pkg/authserver/refresher_contention_test.go diff --git a/pkg/authserver/refresher_contention_test.go b/pkg/authserver/refresher_contention_test.go new file mode 100644 index 0000000000..85e9f5d215 --- /dev/null +++ b/pkg/authserver/refresher_contention_test.go @@ -0,0 +1,206 @@ +// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package authserver + +import ( + "context" + "errors" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/alicebob/miniredis/v2" + "github.com/redis/go-redis/v9" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/stacklok/toolhive/pkg/authserver/storage" + "github.com/stacklok/toolhive/pkg/authserver/upstream" +) + +// blockingProvider parks inside RefreshTokens until the test releases it, so a +// second replica can be observed while the first is mid-redemption. It counts +// its calls, which is the assertion this whole test exists for: one upstream +// redemption, however many replicas wanted one. +// +// Only RefreshTokens is reachable here, so the rest of the interface is left +// embedded and nil — a call to any other method would panic rather than pass +// silently. +type blockingProvider struct { + upstream.OAuth2Provider + + calls atomic.Int32 + + // entered is closed when the first call reaches the provider. + entered chan struct{} + // release is closed by the test to let that call finish. + release chan struct{} + + enteredOnce sync.Once +} + +func (p *blockingProvider) RefreshTokens(_ context.Context, _, _ string) (*upstream.Tokens, error) { + p.calls.Add(1) + p.enteredOnce.Do(func() { close(p.entered) }) + <-p.release + return &upstream.Tokens{ + AccessToken: "new-access", + RefreshToken: "new-refresh", + ExpiresAt: time.Now().Add(time.Hour), + }, nil +} + +// refusalSignallingLocker reports, on a channel, that an acquisition was +// refused because another holder has the lease. It makes the "the waiter did +// not call the provider" assertion deterministic: the test can wait for the +// refusal instead of sleeping and hoping the waiter got far enough to +// misbehave. +type refusalSignallingLocker struct { + storage.UpstreamRefreshLocker + refused chan struct{} +} + +func (l *refusalSignallingLocker) AcquireUpstreamRefreshLock( + ctx context.Context, rowID storage.UpstreamTokenRowID, ttl time.Duration, +) (storage.UpstreamRefreshLease, error) { + lease, err := l.UpstreamRefreshLocker.AcquireUpstreamRefreshLock(ctx, rowID, ttl) + if errors.Is(err, storage.ErrUpstreamRefreshLockHeld) { + select { + case l.refused <- struct{}{}: + default: + } + } + return lease, err +} + +// TestRefreshAndStore_TwoReplicasRedeemOnce is the end-to-end claim of #4122: +// two auth server processes sharing one Redis, each with its own singleflight +// group, concurrently find the same expired upstream row, and the upstream +// provider is asked to redeem the refresh token exactly once. +// +// Everything below the refresher is real — Redis (miniredis) storage, the +// Lua-scripted lease and CAS write, the row encoding — because the failure +// this guards against lives in the interaction between those layers, not in +// any one of them. The only test doubles are the provider (which has to park +// mid-redemption for the race to be observable at all) and a passthrough +// wrapper that reports lease refusals. +func TestRefreshAndStore_TwoReplicasRedeemOnce(t *testing.T) { + t.Parallel() + + mr := miniredis.RunT(t) + client := redis.NewClient(&redis.Options{Addr: mr.Addr()}) + stor := storage.NewRedisStorageWithClient(client, "test:auth:") + t.Cleanup(func() { + _ = stor.Close() + mr.Close() + }) + + ctx := t.Context() + expired := &storage.UpstreamTokens{ + ProviderID: "github", + AccessToken: "old-access", + RefreshToken: "old-refresh", + UpstreamSubject: "subject", + ExpiresAt: time.Now().Add(-time.Hour), + SessionExpiresAt: time.Now().Add(24 * time.Hour), + } + require.NoError(t, stor.StoreUpstreamTokens(ctx, "session", "github", expired)) + + locker := storage.UpstreamRefreshLockerFrom(stor) + require.NotNil(t, locker, "the Redis backend must provide the lease capability") + + provider := &blockingProvider{ + entered: make(chan struct{}), + release: make(chan struct{}), + } + refused := make(chan struct{}, 1) + + // Two refreshers, as two processes would have: separate singleflight + // groups (the zero value of the field), one shared storage backend. If + // coordination lived only in singleflight, both would redeem. + leader := newContendingRefresher(provider, stor, locker) + waiter := newContendingRefresher(provider, stor, + &refusalSignallingLocker{UpstreamRefreshLocker: locker, refused: refused}) + + var ( + leaderRow, waiterRow *storage.UpstreamTokens + leaderErr, waiterErr error + wg sync.WaitGroup + ) + + wg.Add(1) + go func() { + defer wg.Done() + leaderRow, leaderErr = leader.RefreshAndStore(ctx, "session", expired) + }() + + // The leader is now inside the provider, holding the lease. + select { + case <-provider.entered: + case <-time.After(10 * time.Second): + t.Fatal("the first refresher never reached the upstream provider") + } + + wg.Add(1) + go func() { + defer wg.Done() + waiterRow, waiterErr = waiter.RefreshAndStore(ctx, "session", expired) + }() + + // The second refresher has tried for the lease and been refused. The + // leader still holds it (it is parked in the provider until released + // below), so every further attempt is refused too: from here until the + // release, the waiter cannot legitimately reach the provider. + select { + case <-refused: + case <-time.After(10 * time.Second): + // Getting here means the second replica never asked for the lease at + // all. The interesting number is then how many redemptions the + // provider has seen: uncoordinated, the waiter walks straight past it + // into a second redemption of the same refresh token, which is the + // regression this test exists to catch. + t.Fatalf("the second refresher never contended for the lease; upstream redemptions so far: %d", + provider.calls.Load()) + } + assert.Equal(t, int32(1), provider.calls.Load(), + "the waiter must not redeem the refresh token while another replica holds the lease") + + close(provider.release) + wg.Wait() + + require.NoError(t, leaderErr) + require.NoError(t, waiterErr) + assert.Equal(t, int32(1), provider.calls.Load(), + "the refresh token must be redeemed upstream exactly once across both replicas") + + // Both callers end up with the leader's rotated tokens: the waiter either + // re-read the stored row, or took the freed lease and found on its own + // re-read that no refresh was needed any more. + require.NotNil(t, leaderRow) + require.NotNil(t, waiterRow) + assert.Equal(t, "new-refresh", leaderRow.RefreshToken) + assert.Equal(t, "new-refresh", waiterRow.RefreshToken) + assert.Equal(t, "new-access", waiterRow.AccessToken) + + stored, err := stor.GetUpstreamTokens(ctx, "session", "github") + require.NoError(t, err) + assert.Equal(t, "new-refresh", stored.RefreshToken, "the rotated row must be what is persisted") +} + +// newContendingRefresher builds one replica's refresher. Each call produces an +// independent singleflight group, which is what makes two of them stand in for +// two processes. +func newContendingRefresher( + provider upstream.OAuth2Provider, + stor storage.UpstreamTokenStorage, + locker storage.UpstreamRefreshLocker, +) *upstreamTokenRefresher { + return &upstreamTokenRefresher{ + providers: map[string]upstream.OAuth2Provider{"github": provider}, + storage: stor, + locker: locker, + refreshTokenLifespan: 24 * time.Hour, + } +} From cd29229b4473c7f31d689cfc988394be3a6531c7 Mon Sep 17 00:00:00 2001 From: hellouz818 Date: Tue, 3 Nov 2026 15:15:41 +0900 Subject: [PATCH 4/8] Drain the parked provider call on test teardown 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: #4122 Signed-off-by: hellouz818 --- pkg/authserver/refresher_contention_test.go | 33 ++++++++++++++++++--- 1 file changed, 29 insertions(+), 4 deletions(-) diff --git a/pkg/authserver/refresher_contention_test.go b/pkg/authserver/refresher_contention_test.go index 85e9f5d215..fc538d632f 100644 --- a/pkg/authserver/refresher_contention_test.go +++ b/pkg/authserver/refresher_contention_test.go @@ -35,16 +35,32 @@ type blockingProvider struct { // entered is closed when the first call reaches the provider. entered chan struct{} - // release is closed by the test to let that call finish. + // release is closed to let a parked call finish, by the test on its happy + // path and by releaseAll on teardown. release chan struct{} enteredOnce sync.Once + releaseOnce sync.Once } -func (p *blockingProvider) RefreshTokens(_ context.Context, _, _ string) (*upstream.Tokens, error) { +// releaseAll unparks every call still waiting. It is idempotent so the test's +// own release and the teardown release cannot double-close. +func (p *blockingProvider) releaseAll() { + p.releaseOnce.Do(func() { close(p.release) }) +} + +func (p *blockingProvider) RefreshTokens(ctx context.Context, _, _ string) (*upstream.Tokens, error) { p.calls.Add(1) p.enteredOnce.Do(func() { close(p.entered) }) - <-p.release + // ctx is a backstop only. RefreshAndStore detaches its refresh context + // (context.WithoutCancel), so cancelling the test's context does not reach + // here; what actually unparks this call when the test fails early is the + // teardown releaseAll below. + select { + case <-p.release: + case <-ctx.Done(): + return nil, ctx.Err() + } return &upstream.Tokens{ AccessToken: "new-access", RefreshToken: "new-refresh", @@ -130,6 +146,15 @@ func TestRefreshAndStore_TwoReplicasRedeemOnce(t *testing.T) { wg sync.WaitGroup ) + // Registered after the storage cleanup, so it runs BEFORE it (cleanups are + // LIFO): any goroutine still parked in the provider is unparked and + // drained while Redis is still up. Without this, a t.Fatal before the + // release below would leave a refresher blocked for the rest of the run. + t.Cleanup(func() { + provider.releaseAll() + wg.Wait() + }) + wg.Add(1) go func() { defer wg.Done() @@ -167,7 +192,7 @@ func TestRefreshAndStore_TwoReplicasRedeemOnce(t *testing.T) { assert.Equal(t, int32(1), provider.calls.Load(), "the waiter must not redeem the refresh token while another replica holds the lease") - close(provider.release) + provider.releaseAll() wg.Wait() require.NoError(t, leaderErr) From 2ec03608a4651ffa5d1aeef05e9861020a55cda6 Mon Sep 17 00:00:00 2001 From: hellouz818 Date: Mon, 23 Nov 2026 11:39:12 +0900 Subject: [PATCH 5/8] Bound the redemption by the lease, not the caller 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: #4122 Signed-off-by: hellouz818 --- pkg/authserver/refresher.go | 118 ++++++++++++++++----------- pkg/authserver/server_impl.go | 8 +- pkg/authserver/storage/memory.go | 46 ++++++----- pkg/authserver/storage/redis.go | 43 ++++++++-- pkg/authserver/storage/redis_keys.go | 17 ++-- pkg/authserver/storage/types.go | 77 +++++++---------- pkg/authserver/storage/unwrap.go | 17 ++-- 7 files changed, 186 insertions(+), 140 deletions(-) diff --git a/pkg/authserver/refresher.go b/pkg/authserver/refresher.go index a30ff49f62..8d4e24227b 100644 --- a/pkg/authserver/refresher.go +++ b/pkg/authserver/refresher.go @@ -35,28 +35,26 @@ const upstreamDeleteTimeout = 5 * time.Second // upstreamRefreshLeaseTTL bounds a distributed refresh lease (see // storage.UpstreamRefreshLocker). It must outlast the holder's whole -// read-redeem-write sequence, which refreshCtx caps at refreshTimeout, or the -// lease could expire mid-redemption and let a waiter redeem the same refresh -// token — the exact race the lease exists to prevent. The margin above -// refreshTimeout covers the gap between acquiring the lease and the holder's -// CAS write landing. It is also the longest a crashed holder can block the +// read-redeem-write sequence, or the lease could expire mid-redemption and +// let a waiter redeem the same refresh token. refreshHoldingLease caps that +// sequence at refreshTimeout from the same moment this TTL starts, so the +// margin covers the best-effort delete that may follow +// (upstreamDeleteTimeout). It is also the longest a crashed holder blocks the // row, which is why it is not set far higher. const upstreamRefreshLeaseTTL = refreshTimeout + 15*time.Second -// upstreamRefreshLeaseReleaseTimeout bounds the release of a refresh lease. A -// fresh detached context is used because the refresh context is usually -// already at or past its deadline by the time the holder unwinds, and a -// release skipped on that account would make every waiter sit out the full -// upstreamRefreshLeaseTTL. +// upstreamRefreshLeaseReleaseTimeout bounds the release of a refresh lease, on +// a detached context: the refresh context is usually already at its deadline +// by the time the holder unwinds, and a release skipped on that account would +// make every waiter sit out the full upstreamRefreshLeaseTTL. const upstreamRefreshLeaseReleaseTimeout = 5 * time.Second // upstreamRefreshLockPollInitial and upstreamRefreshLockPollMax bound the -// backoff a replica waits between attempts while another holder has the lease. -// Each attempt costs one acquisition and one row read, and the wait can run to -// refreshTimeout, so a fixed short interval would put hundreds of round-trips -// per waiting request on the storage backend. Starting small keeps the common -// case — the holder finishes in well under a second — responsive, and the cap -// keeps a long wait cheap. +// backoff a replica waits between attempts while another holder has the +// lease. Each attempt costs one acquisition and one row read, and the wait can +// run to refreshTimeout, so a fixed short interval would put hundreds of +// round-trips per waiting request on the backend. Starting small keeps the +// common case — the holder finishes in well under a second — responsive. const ( upstreamRefreshLockPollInitial = 25 * time.Millisecond upstreamRefreshLockPollMax = 500 * time.Millisecond @@ -86,10 +84,11 @@ const upstreamConflictReadTimeout = 5 * time.Second // read-redeem-write sequence ACROSS PROCESSES with a lease over the same // row identity singleflight uses, so only the lease holder calls the // upstream provider. This is what keeps a strict single-use-rotation IdP -// from seeing two replicas redeem one refresh token as a replay. A -// backend that does not provide the capability leaves it nil, and the -// refresher falls back to the layer below, which orders the stored row -// but cannot prevent the duplicate redemption. +// from seeing two replicas redeem one refresh token as a replay. The +// lease is advisory, so two residual gaps remain: one lost in a Redis +// failover that promoted a replica before the acquisition replicated, and +// a holder the host paused past the TTL. Those, and a backend that +// provides no lease at all, end at the layer below. // - CompareAndSwapUpstreamTokens (see refreshAndStore) makes the STORED row // deterministic ACROSS PROCESSES: every write is conditioned on the refresh // token this call redeemed still being the one stored, so a replica whose @@ -176,19 +175,34 @@ func (r *upstreamTokenRefresher) RefreshAndStore( // backend's cross-process refresh lease, when it provides one. // // Holding the lease is what stops two replicas redeeming the same single-use -// refresh token. A replica that cannot take it must therefore never fall -// through to the upstream provider: it waits, re-reading the row, and returns -// the row a holder stored as soon as that row is usable. When no usable row -// has appeared it retries acquisition, and whichever attempt succeeds re-reads -// the row before deciding whether an upstream refresh is still needed. A free -// lease is not by itself evidence that anything went wrong — the holder -// releases it on its normal success path too — so taking it is not a licence -// to redeem without looking. Running out of refreshCtx while waiting is a -// failure, not a licence to redeem uncoordinated. +// refresh token, so a replica that cannot take it must never fall through to +// the provider: it waits, re-reading the row, and returns the row a holder +// stored as soon as that row is usable. When no usable row has appeared it +// retries acquisition, and whichever attempt succeeds re-reads the row before +// deciding whether a refresh is still needed — a free lease is not evidence +// that anything went wrong, since the holder releases it on its success path +// too. Running out of refreshCtx while waiting is a failure, not a licence to +// redeem uncoordinated. // -// A backend without the capability (locker nil) refreshes directly, exactly as -// before this layer existed: correct for a single-process backend, and -// CAS-only coordination for any other. +// A backend without the capability (locker nil) refreshes directly: correct +// for a single-process backend, and CAS-only coordination for any other. +// nextUpstreamRefreshPoll returns the interval a waiter sleeps after an +// attempt that found the lease held, doubling until upstreamRefreshLockPollMax. +func nextUpstreamRefreshPoll(current time.Duration) time.Duration { + return min(current*2, upstreamRefreshLockPollMax) +} + +// upstreamRefreshWaitTimeout reports that the wait for another replica's +// refresh ran out of the caller's budget. It is a failure rather than a +// licence to redeem: a replica that never saw the holder finish cannot know +// whether the refresh token has already been redeemed. +func upstreamRefreshWaitTimeout(providerID string, cause error) error { + return fmt.Errorf( + "timed out waiting for another replica to refresh upstream tokens for provider %q: %w", + providerID, cause, + ) +} + func (r *upstreamTokenRefresher) coordinatedRefresh( ctx context.Context, sessionID string, @@ -205,10 +219,7 @@ func (r *upstreamTokenRefresher) coordinatedRefresh( // is reported as the timeout it is, rather than as whatever error the // backend returns for an already-cancelled context. if err := ctx.Err(); err != nil { - return nil, fmt.Errorf( - "timed out waiting for another replica to refresh upstream tokens for provider %q: %w", - caller.ProviderID, err, - ) + return nil, upstreamRefreshWaitTimeout(caller.ProviderID, err) } lease, err := r.locker.AcquireUpstreamRefreshLock(ctx, rowID, upstreamRefreshLeaseTTL) @@ -226,13 +237,10 @@ func (r *upstreamTokenRefresher) coordinatedRefresh( select { case <-ctx.Done(): - return nil, fmt.Errorf( - "timed out waiting for another replica to refresh upstream tokens for provider %q: %w", - caller.ProviderID, ctx.Err(), - ) + return nil, upstreamRefreshWaitTimeout(caller.ProviderID, ctx.Err()) case <-time.After(wait): } - wait = min(wait*2, upstreamRefreshLockPollMax) + wait = nextUpstreamRefreshPoll(wait) if winner := r.refreshedByLeaseHolder(ctx, sessionID, caller); winner != nil { slog.Debug("another replica refreshed the upstream token row while this one waited", @@ -247,6 +255,14 @@ func (r *upstreamTokenRefresher) coordinatedRefresh( // waiter can proceed without sitting out upstreamRefreshLeaseTTL. The release // runs on every exit path, including the short-circuit where no upstream call // was made at all. +// +// The redemption runs on its own refreshTimeout budget, measured from the +// acquisition rather than inherited from the caller: a waiter that wins the +// lease late would otherwise redeem on whatever is left of a deadline it +// mostly spent waiting, and a deadline that cuts a rotation off between the +// provider accepting it and the CAS write landing leaves a refresh token the +// IdP has already rotated away stored as the live one. The fresh budget +// starts when upstreamRefreshLeaseTTL does, so it still fits inside the lease. func (r *upstreamTokenRefresher) refreshHoldingLease( ctx context.Context, sessionID string, @@ -268,7 +284,10 @@ func (r *upstreamTokenRefresher) refreshHoldingLease( } }() - return r.refreshAuthoritativeRow(ctx, sessionID, caller) + refreshCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), refreshTimeout) + defer cancel() + + return r.refreshAuthoritativeRow(refreshCtx, sessionID, caller) } // refreshedByLeaseHolder reports the row a lease holder stored while this @@ -277,11 +296,10 @@ func (r *upstreamTokenRefresher) refreshHoldingLease( // The test is deliberately the same one refreshAuthoritativeRow short-circuits // on — unexpired AND different from the row the caller arrived with — so a // waiter accepts exactly what a leader would have accepted on its own re-read. -// Anything else (the row unchanged, still expired, or a read failure) is not -// a result, so the caller goes back to contending for the lease rather than -// treating a transient read as a refusal. It is deliberately silent about WHY -// there is nothing to return: the holder may still be working, or it may have -// died — the caller's next move is the same either way. +// Anything else (unchanged, still expired, or a read failure) is not a result, +// so the caller goes back to contending rather than treating a transient read +// as a refusal. Why there is nothing to return does not matter: the holder may +// still be working or may have died, and the caller's next move is the same. func (r *upstreamTokenRefresher) refreshedByLeaseHolder( ctx context.Context, sessionID string, caller *storage.UpstreamTokens, ) *storage.UpstreamTokens { @@ -540,9 +558,11 @@ func (r *upstreamTokenRefresher) resolveConcurrentRefreshConflict( // way to the replica that loses a cross-process refresh race (singleflight // only deduplicates within this process), even though the winner has already // stored a valid row. The refresh lease (see coordinatedRefresh) is what -// normally stops two replicas reaching the provider at all, so this path now +// normally stops two replicas reaching the provider at all, so this path // covers the cases it cannot: a backend that provides no lease, and a lease -// that expired under a holder slow enough for a waiter to take over. If the +// that stopped holding — lost in a Redis failover that promoted a replica +// before the acquisition replicated, or expired under a holder the host +// paused past the TTL. If the // stored row now holds a different refresh token and an unexpired access // token, that row is the result to use, so a lost race is not reported as a // dead upstream credential. diff --git a/pkg/authserver/server_impl.go b/pkg/authserver/server_impl.go index 1a4d113bdd..d1c28db08c 100644 --- a/pkg/authserver/server_impl.go +++ b/pkg/authserver/server_impl.go @@ -1078,7 +1078,7 @@ func (s *server) UpstreamTokenRefresher() storage.UpstreamTokenRefresher { // when there are none. Called once during newServer so the returned instance // can be shared between the handler and the UpstreamTokenRefresher() accessor. // It also resolves the storage backend's optional cross-process refresh lease -// so every refresh path shares one, see upstreamTokenRefresher's doc. +// (see upstreamTokenRefresher's doc) so every refresh path shares one. func newUpstreamTokenRefresher( upstreams []handlers.NamedUpstream, stor storage.UpstreamTokenStorage, @@ -1091,10 +1091,8 @@ func newUpstreamTokenRefresher( for _, u := range upstreams { providers[u.Name] = u.Provider } - // Resolve the backend's cross-process refresh lease once, here, rather - // 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. + // Resolved once here rather than per refresh: by this point stor is + // wrapped in the decorators UpstreamRefreshLockerFrom has to peel. locker := storage.UpstreamRefreshLockerFrom(stor) if locker == nil { slog.Debug("upstream token storage provides no cross-process refresh lock; " + diff --git a/pkg/authserver/storage/memory.go b/pkg/authserver/storage/memory.go index 6e83b24217..4f07412204 100644 --- a/pkg/authserver/storage/memory.go +++ b/pkg/authserver/storage/memory.go @@ -566,14 +566,7 @@ func (s *MemoryStorage) cleanupExpired() { delete(s.pkceRequests, k) } - for _, k := range expiredRefreshLeases { - // Re-check under the write lock: a lease collected as expired above may - // have been released and re-acquired by a new holder in between, and - // deleting that live lease would let a second refresh start alongside it. - if lease, ok := s.upstreamRefreshLeases[k]; ok && now.After(lease.expiresAt) { - delete(s.upstreamRefreshLeases, k) - } - } + s.deleteExpiredRefreshLeasesLocked(now, expiredRefreshLeases) for _, k := range expiredUpstreamTokens { delete(s.upstreamTokens, k) @@ -1458,8 +1451,10 @@ func (s *MemoryStorage) DeletePKCERequestSession(_ context.Context, signature st // Upstream Token Storage // ----------------------- -// ResolveUpstreamTokenRowID returns an opaque ID for process-local refresh -// coordination of a logical upstream-token row. +// ResolveUpstreamTokenRowID returns an opaque ID identifying one logical +// upstream-token row, used to coordinate refreshes of it: the auth server's +// in-process singleflight group and the cross-process UpstreamRefreshLocker +// lease are both keyed by it. See UpstreamTokenStorage for the contract. func (*MemoryStorage) ResolveUpstreamTokenRowID(_ context.Context, sessionID, providerName string) (UpstreamTokenRowID, error) { if sessionID == "" { return "", fosite.ErrInvalidRequest.WithHint("session ID cannot be empty") @@ -1487,6 +1482,21 @@ func (s *MemoryStorage) StoreUpstreamTokens(_ context.Context, sessionID, provid return nil } +// deleteExpiredRefreshLeasesLocked drops the leases cleanupExpired collected as +// expired. It must be called with s.mu held for writing. +// +// Each one is re-checked against the map, because the collection ran under the +// read lock: a lease that expired then may since have been released and +// re-acquired by a new holder, and deleting that live lease would let a second +// replica start redeeming alongside it — the race the lease exists to prevent. +func (s *MemoryStorage) deleteExpiredRefreshLeasesLocked(now time.Time, expired []UpstreamTokenRowID) { + for _, k := range expired { + if lease, ok := s.upstreamRefreshLeases[k]; ok && now.After(lease.expiresAt) { + delete(s.upstreamRefreshLeases, k) + } + } +} + // memoryUpstreamRefreshLease is a held lease from AcquireUpstreamRefreshLock. // It keeps a pointer back to the storage so Release can drop the entry, and // its own expiry so a holder that outlives the lease cannot release a lease a @@ -1514,15 +1524,13 @@ func (l *memoryUpstreamRefreshLease) Release(_ context.Context) error { // AcquireUpstreamRefreshLock implements UpstreamRefreshLocker for the // in-memory backend. See the interface doc for the coordination contract. // -// This backend is reachable from exactly one process, so the cross-replica -// race the capability exists to prevent cannot occur here and the auth -// server's own singleflight group already deduplicates concurrent refreshes -// of one row. Rather than always granting the lease, this implements it for -// real — mutual exclusion over the row within this process, with the same -// expiry and ownership rules — so that the behaviour a caller relies on does -// not silently depend on which backend it was wired against, and so the same -// tests can cover both backends. The cost is one map operation under the -// mutex the backend already holds for every other write. +// This backend is reachable from exactly one process, where the auth server's +// singleflight group already deduplicates concurrent refreshes of one row, so +// the lease could simply always be granted. It is implemented for real +// instead — mutual exclusion with the same expiry and ownership rules — so +// that what a caller relies on does not depend on which backend it was wired +// against, and so one contract test covers both. The cost is a map operation +// under the mutex every other write already takes. func (s *MemoryStorage) AcquireUpstreamRefreshLock( _ context.Context, rowID UpstreamTokenRowID, ttl time.Duration, ) (UpstreamRefreshLease, error) { diff --git a/pkg/authserver/storage/redis.go b/pkg/authserver/storage/redis.go index 84492ca2e3..3b0f07a2c6 100644 --- a/pkg/authserver/storage/redis.go +++ b/pkg/authserver/storage/redis.go @@ -1803,8 +1803,10 @@ func (s *RedisStorage) CompareAndSwapUpstreamTokens( return nil } -// ResolveUpstreamTokenRowID returns an opaque ID for process-local refresh -// coordination of a logical upstream-token row. +// ResolveUpstreamTokenRowID returns an opaque ID identifying one logical +// upstream-token row, used to coordinate refreshes of it: the auth server's +// in-process singleflight group and the cross-process UpstreamRefreshLocker +// lease are both keyed by it. See UpstreamTokenStorage for the contract. func (s *RedisStorage) ResolveUpstreamTokenRowID(_ context.Context, sessionID, providerName string) (UpstreamTokenRowID, error) { if sessionID == "" { return "", fosite.ErrInvalidRequest.WithHint("session ID cannot be empty") @@ -1819,9 +1821,8 @@ func (s *RedisStorage) ResolveUpstreamTokenRowID(_ context.Context, sessionID, p // caller still owns it. The owner token is compared inside the script so the // read and the delete cannot interleave with another replica's acquisition: // without it, a holder whose lease had already expired could delete the lease -// a second replica legitimately took in the meantime, and both would then -// redeem the same refresh token — precisely the race the lease exists to -// prevent. +// a second replica legitimately took in the meantime (see +// UpstreamRefreshLease.Release). // // KEYS[1] = lease key // ARGV[1] = owner token this holder wrote on acquisition @@ -1835,6 +1836,11 @@ end return 0 `) +// upstreamRefreshLockCleanupTimeout bounds the best-effort delete of a lease +// whose acquisition reply never came back. It runs on a detached context +// because the context that failed the acquisition is usually already done. +const upstreamRefreshLockCleanupTimeout = 2 * time.Second + // redisUpstreamRefreshLease is a held lease from AcquireUpstreamRefreshLock. type redisUpstreamRefreshLease struct { client redis.UniversalClient @@ -1886,6 +1892,13 @@ func (s *RedisStorage) AcquireUpstreamRefreshLock( key := redisUpstreamRefreshLockKey(s.keyPrefix, rowID) acquired, err := s.client.SetNX(ctx, key, owner, ttl).Result() if err != nil { + // The reply can be lost after Redis applied the SET — a timeout, a + // dropped connection. The lease would then be held by a holder that + // never got a handle to release it, blocking the row for the whole + // TTL. Deleting it compares the owner token generated above, so it + // clears exactly that case and does nothing when the SET never landed + // or another holder owns the key. + s.clearUnreleasableUpstreamRefreshLock(ctx, key, owner) return nil, fmt.Errorf("failed to acquire upstream refresh lock: %w", err) } if !acquired { @@ -1895,6 +1908,26 @@ func (s *RedisStorage) AcquireUpstreamRefreshLock( return &redisUpstreamRefreshLease{client: s.client, key: key, owner: owner}, nil } +// clearUnreleasableUpstreamRefreshLock is the best-effort cleanup for an +// acquisition that failed without telling the caller whether the lease was +// written. Failing to clear it is not an error worth propagating: the caller +// is already failing the refresh, and the lease expires on its own. +func (s *RedisStorage) clearUnreleasableUpstreamRefreshLock(ctx context.Context, key, owner string) { + cleanupCtx, cancel := context.WithTimeout( + context.WithoutCancel(ctx), upstreamRefreshLockCleanupTimeout, + ) + defer cancel() + + if _, err := releaseUpstreamRefreshLockScript.Run( + cleanupCtx, s.client, []string{key}, owner, + ).Result(); err != nil { + slog.Debug("could not clear an upstream refresh lock after a failed acquisition; "+ + "it expires on its own", + "error", err, + ) + } +} + // GetUpstreamTokens retrieves the upstream IDP tokens for a session and provider. // Returns a new UpstreamTokens struct deserialized from Redis, which acts as // a defensive copy - callers cannot modify the stored data by mutating the return value. diff --git a/pkg/authserver/storage/redis_keys.go b/pkg/authserver/storage/redis_keys.go index e91314dd47..bd2fe85117 100644 --- a/pkg/authserver/storage/redis_keys.go +++ b/pkg/authserver/storage/redis_keys.go @@ -84,8 +84,8 @@ const ( // an auth server replica takes over one upstream token row before redeeming // its refresh token upstream (see UpstreamRefreshLocker). Like // KeyTypeDCRClientIdx, the name deliberately does not match the "upstream:*" - // scan pattern walked by migrateUpstreamTokenKeys, so a live lease can never - // be mistaken for a token row by the legacy-key migration. + // scan pattern walked by migrateUpstreamTokenKeys, so a live lease is never + // mistaken for a token row by the legacy-key migration. KeyTypeUpstreamRefreshLock = "upstream-lock" // KeyTypeUserUpstream is the key type for user to upstream token reverse lookups. @@ -220,14 +220,11 @@ func redisSetKey(prefix, keyType, id string) string { // redisUpstreamRefreshLockKey generates a Redis key for the refresh lease over // one upstream token row. Format: "{prefix}upstream-lock:{rowID}". // -// The row identity is UpstreamTokenRowID, the same value the auth server's -// in-process singleflight group is keyed by, so the two coordination layers -// cover exactly the same set of rows by construction: whatever -// ResolveUpstreamTokenRowID considers one row holds one lease. It is a -// SHA-256 hex digest, so it contains no colon and needs no length prefix, and -// it keeps the session ID out of the key name. The key shares the prefix's -// {ns:name} hash tag, so it lands in the same Redis Cluster slot as the row it -// guards. +// rowID is an UpstreamTokenRowID (see ResolveUpstreamTokenRowID for what it +// identifies): a SHA-256 hex digest, so it contains no colon and needs no +// length prefix, and it keeps the session ID out of the key name. The key +// shares the prefix's {ns:name} hash tag, so it lands in the same Redis +// Cluster slot as the row it guards. func redisUpstreamRefreshLockKey(prefix string, rowID UpstreamTokenRowID) string { return fmt.Sprintf("%s%s:%s", prefix, KeyTypeUpstreamRefreshLock, rowID) } diff --git a/pkg/authserver/storage/types.go b/pkg/authserver/storage/types.go index 0dbca328da..7dc14bd76e 100644 --- a/pkg/authserver/storage/types.go +++ b/pkg/authserver/storage/types.go @@ -100,13 +100,11 @@ var ( ErrConcurrentRefresh = errors.New("storage: upstream token row changed concurrently") // ErrUpstreamRefreshLockHeld is returned by - // UpstreamRefreshLocker.AcquireUpstreamRefreshLock when another holder — in - // this process or in another replica sharing the backend — already holds - // the lease for that row. It means "someone else is refreshing right now", - // which is an ordinary outcome, not a fault: the caller must wait and - // re-read the row rather than redeem the refresh token itself. Every other - // error from AcquireUpstreamRefreshLock is a backend fault, and the caller - // must fail closed rather than redeem without coordination. + // UpstreamRefreshLocker.AcquireUpstreamRefreshLock when another holder + // already holds the lease for that row. It is an ordinary outcome, not a + // fault: the caller waits and re-reads the row rather than redeeming the + // refresh token itself. Every other error from that method is a backend + // fault, where the caller must fail closed instead. ErrUpstreamRefreshLockHeld = errors.New("storage: upstream refresh lock held by another holder") // ErrDCRCredentialsChanged is returned by @@ -1244,9 +1242,8 @@ type ClientRegistry interface { // UpstreamTokenRowID is an opaque coordination key for one logical upstream // token row. Callers must not log it or expose it outside the refresh -// coordination path. The only place it may be written is a backend's own -// UpstreamRefreshLocker lease key, which is derived from it and lives no -// longer than the lease. +// coordination path; the only place it may be written is a backend's own +// UpstreamRefreshLocker lease key, which lives no longer than the lease. type UpstreamTokenRowID string // upstreamTokenRowID returns a SHA-256 digest of the supplied row-key components. @@ -1413,40 +1410,27 @@ type UpstreamTokenStorage interface { // backend: a mutual-exclusion lease over one logical upstream token row, // honoured by every process sharing that backend. // -// # Why this exists on top of CompareAndSwapUpstreamTokens -// -// CompareAndSwapUpstreamTokens makes the STORED row deterministic across -// replicas: a losing writer fails instead of clobbering the winner. It does -// not stop the losing replica from CALLING the upstream provider, because -// both replicas redeem before either one writes. An IdP enforcing strict -// single-use refresh token rotation (RFC 9700 §4.14.2 replay detection) sees -// those two redemptions of one refresh token as a replay and may revoke the -// whole grant — regardless of which write won. Closing that gap requires -// serializing the read-redeem-write sequence itself, which is what this lease -// provides. -// -// # Contract +// It exists on top of CompareAndSwapUpstreamTokens because CAS only makes the +// STORED row deterministic; both replicas still CALL the upstream provider +// before either one writes, which an IdP enforcing strict single-use rotation +// can read as a replay. Closing that gap means serializing the whole +// read-redeem-write sequence, which is what this lease provides. See +// docs/arch/11-auth-server-storage.md's "Refresh Coordination Scope". // // Acquisition is non-blocking: it either takes the lease or reports -// ErrUpstreamRefreshLockHeld immediately. Waiting, re-reading the row and -// retrying are the caller's job, so a caller can abandon the wait as soon as -// the row it is waiting for has been refreshed by the holder. -// -// The lease is advisory and bounded by ttl: it expires on its own so a holder -// that crashes mid-refresh cannot block the row forever. A caller must -// therefore treat holding the lease as a strong hint, not a hard guarantee, -// and still write through CompareAndSwapUpstreamTokens — the two layers are -// complementary. Implementations must make expiry and release safe against a -// stale holder: releasing must only delete the caller's own lease, never one -// a later holder acquired after this one expired. -// -// # Detection +// ErrUpstreamRefreshLockHeld immediately, leaving waiting and re-reading to +// the caller, which can therefore stop as soon as the holder has refreshed +// the row it wanted. The lease is advisory and bounded by ttl, so a holder +// that crashes cannot block the row forever and a caller must still write +// through CompareAndSwapUpstreamTokens. Implementations must make expiry and +// release safe against a stale holder: releasing must only delete the +// caller's own lease, never one a later holder acquired after this one +// expired. // -// This capability is deliberately NOT embedded in UpstreamTokenStorage, -// following the same segregation as DeviceCodeStorage and ExchangeGrantStorage: -// a single-process backend does not need it, and embedding it would force -// every future implementation to provide it. Obtain it with -// UpstreamRefreshLockerFrom, which also peels storage decorators. A backend +// Like DeviceCodeStorage and ExchangeGrantStorage, it is deliberately not +// embedded in UpstreamTokenStorage, so a backend that cannot be shared +// between processes need not provide it. Obtain it with +// UpstreamRefreshLockerFrom, which also peels storage decorators; a backend // without it degrades to CAS-only coordination. type UpstreamRefreshLocker interface { // AcquireUpstreamRefreshLock tries to take the lease for rowID for at most @@ -1462,12 +1446,11 @@ type UpstreamRefreshLocker interface { // UpstreamRefreshLocker.AcquireUpstreamRefreshLock. type UpstreamRefreshLease interface { // Release gives up the lease so a waiter can proceed without waiting out - // the TTL. It must be idempotent, and must not release a lease that a - // later holder acquired after this one expired. Release takes its own - // context because the context that governed the refresh is typically - // already cancelled by the time the caller unwinds. An error means the - // lease may still be held until its TTL expires; that is not a correctness - // failure, only a delay for the next waiter. + // the TTL. It must be idempotent, and must not release a lease a later + // holder acquired after this one expired. It takes its own context, + // because the one that governed the refresh is typically already cancelled + // by the time the caller unwinds. An error only delays the next waiter + // until the TTL expires; it is not a correctness failure. Release(ctx context.Context) error } diff --git a/pkg/authserver/storage/unwrap.go b/pkg/authserver/storage/unwrap.go index adeac11f0d..dd0c1faf2b 100644 --- a/pkg/authserver/storage/unwrap.go +++ b/pkg/authserver/storage/unwrap.go @@ -17,11 +17,18 @@ func Unwrap(stor Storage) Storage { } // UpstreamRefreshLockerFrom returns the UpstreamRefreshLocker capability of -// stor, peeling any storage decorators that expose Unwrap, and nil when no -// layer in the chain provides it. Decorators embed the Storage interface and -// so do not carry optional capabilities of the backend they wrap, which is why -// the type assertion alone is not enough — mirrors the Unwrap use at the -// ExchangeGrantStorage discovery boundary. +// stor, and nil when no layer in the chain provides it. Decorators embed the +// Storage interface and so do not carry optional capabilities of the backend +// they wrap, which is why a type assertion on stor alone is not enough; the +// ExchangeGrantStorage and DeviceCodeStorage boundaries assert on Unwrap(stor) +// for the same reason. +// +// Unlike those, this walks the chain and asserts at every layer rather than +// only at the base. A decorator that implements the capability itself — to +// coordinate against something the base backend does not know about — is then +// honoured, and a chain whose decorator does not expose Unwrap still resolves +// whatever the outer layers provide instead of silently returning nil. The +// cost is a type assertion per layer, once at construction. func UpstreamRefreshLockerFrom(stor UpstreamTokenStorage) UpstreamRefreshLocker { for stor != nil { if locker, ok := stor.(UpstreamRefreshLocker); ok { From b254e99821c1a54ea96aa5d6c6de7edd28ce665d Mon Sep 17 00:00:00 2001 From: hellouz818 Date: Mon, 23 Nov 2026 11:39:22 +0900 Subject: [PATCH 6/8] Cover the lease wiring and its failure paths MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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: #4122 Signed-off-by: hellouz818 --- pkg/authserver/refresher_contention_test.go | 33 +- pkg/authserver/refresher_lock_test.go | 295 +++++++++++++----- .../storage/upstream_refresh_lock_test.go | 172 ++++++++-- 3 files changed, 394 insertions(+), 106 deletions(-) diff --git a/pkg/authserver/refresher_contention_test.go b/pkg/authserver/refresher_contention_test.go index fc538d632f..129f286242 100644 --- a/pkg/authserver/refresher_contention_test.go +++ b/pkg/authserver/refresher_contention_test.go @@ -20,6 +20,11 @@ import ( "github.com/stacklok/toolhive/pkg/authserver/upstream" ) +// contentionWaitTimeout bounds every barrier in this test. It is far longer +// than anything the test legitimately waits for, so it only ever fires on a +// deadlock or a panicking goroutine. +const contentionWaitTimeout = 10 * time.Second + // blockingProvider parks inside RefreshTokens until the test releases it, so a // second replica can be observed while the first is mid-redemption. It counts // its calls, which is the assertion this whole test exists for: one upstream @@ -152,7 +157,9 @@ func TestRefreshAndStore_TwoReplicasRedeemOnce(t *testing.T) { // release below would leave a refresher blocked for the rest of the run. t.Cleanup(func() { provider.releaseAll() - wg.Wait() + // Teardown, so a hang here is reported rather than left to run out the + // package's test timeout with no indication of which test stuck. + waitWithTimeout(t, &wg, "refreshers still running at teardown") }) wg.Add(1) @@ -164,7 +171,7 @@ func TestRefreshAndStore_TwoReplicasRedeemOnce(t *testing.T) { // The leader is now inside the provider, holding the lease. select { case <-provider.entered: - case <-time.After(10 * time.Second): + case <-time.After(contentionWaitTimeout): t.Fatal("the first refresher never reached the upstream provider") } @@ -180,7 +187,7 @@ func TestRefreshAndStore_TwoReplicasRedeemOnce(t *testing.T) { // release, the waiter cannot legitimately reach the provider. select { case <-refused: - case <-time.After(10 * time.Second): + case <-time.After(contentionWaitTimeout): // Getting here means the second replica never asked for the lease at // all. The interesting number is then how many redemptions the // provider has seen: uncoordinated, the waiter walks straight past it @@ -193,7 +200,7 @@ func TestRefreshAndStore_TwoReplicasRedeemOnce(t *testing.T) { "the waiter must not redeem the refresh token while another replica holds the lease") provider.releaseAll() - wg.Wait() + waitWithTimeout(t, &wg, "both refreshers should finish once the provider is released") require.NoError(t, leaderErr) require.NoError(t, waiterErr) @@ -214,6 +221,24 @@ func TestRefreshAndStore_TwoReplicasRedeemOnce(t *testing.T) { assert.Equal(t, "new-refresh", stored.RefreshToken, "the rotated row must be what is persisted") } +// waitWithTimeout waits for wg with a fail-fast path, so a refresher that +// deadlocks on the lease is reported here rather than hanging the package +// until the global test timeout. +func waitWithTimeout(t *testing.T, wg *sync.WaitGroup, msg string) { + t.Helper() + + done := make(chan struct{}) + go func() { + wg.Wait() + close(done) + }() + select { + case <-done: + case <-time.After(contentionWaitTimeout): + t.Fatal(msg) + } +} + // newContendingRefresher builds one replica's refresher. Each call produces an // independent singleflight group, which is what makes two of them stand in for // two processes. diff --git a/pkg/authserver/refresher_lock_test.go b/pkg/authserver/refresher_lock_test.go index a55286bcae..226866e218 100644 --- a/pkg/authserver/refresher_lock_test.go +++ b/pkg/authserver/refresher_lock_test.go @@ -6,7 +6,6 @@ package authserver import ( "context" "errors" - "sync/atomic" "testing" "time" @@ -14,52 +13,13 @@ import ( "github.com/stretchr/testify/require" "go.uber.org/mock/gomock" + "github.com/stacklok/toolhive/pkg/authserver/server/handlers" "github.com/stacklok/toolhive/pkg/authserver/storage" storagemocks "github.com/stacklok/toolhive/pkg/authserver/storage/mocks" "github.com/stacklok/toolhive/pkg/authserver/upstream" upstreammocks "github.com/stacklok/toolhive/pkg/authserver/upstream/mocks" ) -// fakeLocker stands in for a storage backend's UpstreamRefreshLocker. It is -// hand-written rather than generated because every case here turns on how the -// lease behaves over successive attempts — held, then free, then held by the -// caller — which reads far more clearly as a scripted sequence than as -// per-call mock expectations. -type fakeLocker struct { - // results is consumed one entry per acquisition attempt; the last entry - // repeats once exhausted, so a waiting caller can spin as long as it - // likes against a lease that never frees. - results []error - - attempts atomic.Int32 - released atomic.Int32 - releaseErr error - lastRowID atomic.Value // storage.UpstreamTokenRowID - lastLeaseTTL atomic.Int64 -} - -func (f *fakeLocker) AcquireUpstreamRefreshLock( - _ context.Context, rowID storage.UpstreamTokenRowID, ttl time.Duration, -) (storage.UpstreamRefreshLease, error) { - f.lastRowID.Store(rowID) - f.lastLeaseTTL.Store(int64(ttl)) - n := int(f.attempts.Add(1)) - 1 - if n >= len(f.results) { - n = len(f.results) - 1 - } - if err := f.results[n]; err != nil { - return nil, err - } - return &fakeLease{locker: f}, nil -} - -type fakeLease struct{ locker *fakeLocker } - -func (l *fakeLease) Release(context.Context) error { - l.locker.released.Add(1) - return l.locker.releaseErr -} - // unexpiredRow is the row a lease holder is taken to have stored: unexpired, // and carrying a refresh token the waiting caller has not seen. func unexpiredRow() *storage.UpstreamTokens { @@ -81,106 +41,158 @@ func expiredRow(refreshToken string) *storage.UpstreamTokens { } } +// expectAcquireHeld expects one acquisition that finds the lease held by +// someone else, which is what sends the caller into the waiting path. +func expectAcquireHeld(locker *storagemocks.MockUpstreamRefreshLocker) *gomock.Call { + return locker.EXPECT(). + AcquireUpstreamRefreshLock(gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil, storage.ErrUpstreamRefreshLockHeld) +} + +// expectAcquireGranted expects one acquisition that takes the lease, and one +// matching Release returning releaseErr. Expecting the Release here is the +// assertion that the leader gives the lease back: gomock fails the test if it +// is not called, and the leases this helper hands out are the only ones in +// these tests, so a lease left behind cannot pass unnoticed. +func expectAcquireGranted( + ctrl *gomock.Controller, locker *storagemocks.MockUpstreamRefreshLocker, releaseErr error, +) *gomock.Call { + lease := storagemocks.NewMockUpstreamRefreshLease(ctrl) + lease.EXPECT().Release(gomock.Any()).Return(releaseErr) + return locker.EXPECT(). + AcquireUpstreamRefreshLock(gomock.Any(), gomock.Any(), gomock.Any()). + Return(lease, nil) +} + // TestCoordinatedRefresh_WaiterNeverRedeems is the core of issue #4122: a // replica that does not hold the row's lease must not call the upstream -// provider, whatever happens while it waits. A provider mock with no -// RefreshTokens expectation fails the test if it is called. +// provider, whatever happens while it waits. The provider mock these cases run +// against has no RefreshTokens expectation, so any upstream redemption fails +// the test, and no lease is ever handed out, so there is nothing to release. func TestCoordinatedRefresh_WaiterNeverRedeems(t *testing.T) { t.Parallel() - held := storage.ErrUpstreamRefreshLockHeld caller := expiredRow("old-refresh") t.Run("returns the holder's row once it appears", func(t *testing.T) { t.Parallel() ctrl := gomock.NewController(t) store := storagemocks.NewMockUpstreamTokenStorage(ctrl) + locker := storagemocks.NewMockUpstreamRefreshLocker(ctrl) winner := unexpiredRow() - // First re-read still shows the caller's own row: the holder has not - // finished. The second shows the rotated row it stored. + // One acquisition per re-read: the first re-read still shows the + // caller's own row, because the holder has not finished, and the + // second shows the rotated row it stored. + expectAcquireHeld(locker).Times(2) gomock.InOrder( store.EXPECT().GetUpstreamTokens(gomock.Any(), "session", "github").Return(caller, nil), store.EXPECT().GetUpstreamTokens(gomock.Any(), "session", "github").Return(winner, nil), ) - locker := &fakeLocker{results: []error{held}} r := newLockTestRefresher(t, ctrl, store, locker) got, err := r.coordinatedRefresh(t.Context(), "session", "row", caller) require.NoError(t, err) assert.Equal(t, winner, got, "the waiter must hand back what the holder stored") - assert.Zero(t, locker.released.Load(), "a waiter holds nothing, so it releases nothing") }) - t.Run("fails when the wait runs out", func(t *testing.T) { + t.Run("fails when the caller's budget runs out", func(t *testing.T) { t.Parallel() ctrl := gomock.NewController(t) store := storagemocks.NewMockUpstreamTokenStorage(ctrl) - // The holder never finishes, so every re-read keeps showing the - // caller's own row. - store.EXPECT().GetUpstreamTokens(gomock.Any(), "session", "github"). - AnyTimes().Return(caller, nil) + locker := storagemocks.NewMockUpstreamRefreshLocker(ctrl) - locker := &fakeLocker{results: []error{held}} - r := newLockTestRefresher(t, ctrl, store, locker) + // The holder never finishes, so the re-read keeps showing the caller's + // own row. + store.EXPECT().GetUpstreamTokens(gomock.Any(), "session", "github").Return(caller, nil) - ctx, cancel := context.WithTimeout(t.Context(), 120*time.Millisecond) + // The budget is spent from inside the second attempt rather than by a + // wall-clock deadline, so the test pins the retry without racing the + // scheduler: exactly two attempts, the second of which runs out. + ctx, cancel := context.WithCancel(t.Context()) defer cancel() + gomock.InOrder( + expectAcquireHeld(locker), + locker.EXPECT().AcquireUpstreamRefreshLock(gomock.Any(), gomock.Any(), gomock.Any()). + DoAndReturn(func( + context.Context, storage.UpstreamTokenRowID, time.Duration, + ) (storage.UpstreamRefreshLease, error) { + cancel() + return nil, storage.ErrUpstreamRefreshLockHeld + }), + ) + + r := newLockTestRefresher(t, ctrl, store, locker) got, err := r.coordinatedRefresh(ctx, "session", "row", caller) require.Error(t, err) assert.Nil(t, got) - assert.ErrorIs(t, err, context.DeadlineExceeded, - "running out of time is a failure, not a licence to redeem uncoordinated") - assert.Greater(t, locker.attempts.Load(), int32(1), "the waiter should retry the lease") + assert.ErrorIs(t, err, context.Canceled, + "running out of budget is a failure, not a licence to redeem uncoordinated") }) t.Run("fails closed when the lock backend errors", func(t *testing.T) { t.Parallel() ctrl := gomock.NewController(t) store := storagemocks.NewMockUpstreamTokenStorage(ctrl) + locker := storagemocks.NewMockUpstreamRefreshLocker(ctrl) backendDown := errors.New("redis: connection refused") - locker := &fakeLocker{results: []error{backendDown}} + // Exactly one attempt, and no re-read: a backend fault is not retried, + // because the caller cannot know whether another replica is redeeming. + locker.EXPECT().AcquireUpstreamRefreshLock(gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil, backendDown) + r := newLockTestRefresher(t, ctrl, store, locker) got, err := r.coordinatedRefresh(t.Context(), "session", "row", caller) require.Error(t, err) assert.Nil(t, got) assert.ErrorIs(t, err, backendDown) - assert.Equal(t, int32(1), locker.attempts.Load(), - "a backend fault is not retried; the caller cannot know whether another replica is redeeming") }) t.Run("ignores a row that changed but is still expired", func(t *testing.T) { t.Parallel() ctrl := gomock.NewController(t) store := storagemocks.NewMockUpstreamTokenStorage(ctrl) + locker := storagemocks.NewMockUpstreamRefreshLocker(ctrl) + // A different row, but expired: the holder has not produced anything - // usable, so the waiter must keep waiting rather than return it. + // usable, so the waiter must keep contending rather than return it. store.EXPECT().GetUpstreamTokens(gomock.Any(), "session", "github"). - AnyTimes().Return(expiredRow("some-other-refresh"), nil) - - locker := &fakeLocker{results: []error{held}} - r := newLockTestRefresher(t, ctrl, store, locker) + Return(expiredRow("some-other-refresh"), nil) - ctx, cancel := context.WithTimeout(t.Context(), 120*time.Millisecond) + ctx, cancel := context.WithCancel(t.Context()) defer cancel() + gomock.InOrder( + expectAcquireHeld(locker), + locker.EXPECT().AcquireUpstreamRefreshLock(gomock.Any(), gomock.Any(), gomock.Any()). + DoAndReturn(func( + context.Context, storage.UpstreamTokenRowID, time.Duration, + ) (storage.UpstreamRefreshLease, error) { + cancel() + return nil, storage.ErrUpstreamRefreshLockHeld + }), + ) + + r := newLockTestRefresher(t, ctrl, store, locker) _, err := r.coordinatedRefresh(ctx, "session", "row", caller) - assert.ErrorIs(t, err, context.DeadlineExceeded) + assert.ErrorIs(t, err, context.Canceled) }) } -// TestCoordinatedRefresh_TakesOverFreedLease covers the holder that crashed or -// whose lease expired: the row is unchanged, so the waiter must stop waiting -// and become the leader rather than sit out the TTL. -func TestCoordinatedRefresh_TakesOverFreedLease(t *testing.T) { +// TestCoordinatedRefresh_WinsLeaseOnRetry covers the waiter whose next +// acquisition succeeds: the row it re-read was unchanged, so there was nothing +// to hand back, and the attempt that wins the lease re-reads the row and +// redeems it rather than treating the free lease as permission to skip ahead. +func TestCoordinatedRefresh_WinsLeaseOnRetry(t *testing.T) { t.Parallel() ctrl := gomock.NewController(t) store := storagemocks.NewMockUpstreamTokenStorage(ctrl) + locker := storagemocks.NewMockUpstreamRefreshLocker(ctrl) caller := expiredRow("old-refresh") // Re-read after the first failed attempt: unchanged, so no winner. Then @@ -199,7 +211,11 @@ func TestCoordinatedRefresh_TakesOverFreedLease(t *testing.T) { ExpiresAt: time.Now().Add(time.Hour), }, nil) - locker := &fakeLocker{results: []error{storage.ErrUpstreamRefreshLockHeld, nil}} + gomock.InOrder( + expectAcquireHeld(locker), + expectAcquireGranted(ctrl, locker, nil), + ) + r := &upstreamTokenRefresher{ providers: map[string]upstream.OAuth2Provider{"github": provider}, storage: store, @@ -211,13 +227,13 @@ func TestCoordinatedRefresh_TakesOverFreedLease(t *testing.T) { require.NoError(t, err) require.NotNil(t, got) assert.Equal(t, "new-refresh", got.RefreshToken) - assert.Equal(t, int32(1), locker.released.Load(), "the new leader must give the lease back") } // TestCoordinatedRefresh_LeaderReleases checks the lease is given back on // every leader exit path, including the short-circuit where the row turned out // to be fresh and no upstream call happened at all. A lease left behind would -// stall every other replica for its full TTL. +// stall every other replica for its full TTL. The Release expectation lives in +// expectAcquireGranted, so each case fails if its lease is not released. func TestCoordinatedRefresh_LeaderReleases(t *testing.T) { t.Parallel() @@ -225,41 +241,42 @@ func TestCoordinatedRefresh_LeaderReleases(t *testing.T) { t.Parallel() ctrl := gomock.NewController(t) store := storagemocks.NewMockUpstreamTokenStorage(ctrl) + locker := storagemocks.NewMockUpstreamRefreshLocker(ctrl) winner := unexpiredRow() store.EXPECT().GetUpstreamTokens(gomock.Any(), "session", "github").Return(winner, nil) + expectAcquireGranted(ctrl, locker, nil) - locker := &fakeLocker{results: []error{nil}} r := newLockTestRefresher(t, ctrl, store, locker) got, err := r.coordinatedRefresh(t.Context(), "session", "row", expiredRow("old-refresh")) require.NoError(t, err) assert.Equal(t, winner, got) - assert.Equal(t, int32(1), locker.released.Load()) }) t.Run("after the refresh fails", func(t *testing.T) { t.Parallel() ctrl := gomock.NewController(t) store := storagemocks.NewMockUpstreamTokenStorage(ctrl) + locker := storagemocks.NewMockUpstreamRefreshLocker(ctrl) store.EXPECT().GetUpstreamTokens(gomock.Any(), "session", "github"). Return(nil, errors.New("storage unavailable")) + expectAcquireGranted(ctrl, locker, nil) - locker := &fakeLocker{results: []error{nil}} r := newLockTestRefresher(t, ctrl, store, locker) _, err := r.coordinatedRefresh(t.Context(), "session", "row", expiredRow("old-refresh")) require.Error(t, err) - assert.Equal(t, int32(1), locker.released.Load()) }) t.Run("a failed release does not fail the refresh", func(t *testing.T) { t.Parallel() ctrl := gomock.NewController(t) store := storagemocks.NewMockUpstreamTokenStorage(ctrl) + locker := storagemocks.NewMockUpstreamRefreshLocker(ctrl) winner := unexpiredRow() store.EXPECT().GetUpstreamTokens(gomock.Any(), "session", "github").Return(winner, nil) + expectAcquireGranted(ctrl, locker, errors.New("redis: timeout")) - locker := &fakeLocker{results: []error{nil}, releaseErr: errors.New("redis: timeout")} r := newLockTestRefresher(t, ctrl, store, locker) got, err := r.coordinatedRefresh(t.Context(), "session", "row", expiredRow("old-refresh")) @@ -294,23 +311,133 @@ func TestRefreshAndStore_TakesLeaseForResolvedRow(t *testing.T) { ctrl := gomock.NewController(t) store := storagemocks.NewMockUpstreamTokenStorage(ctrl) + locker := storagemocks.NewMockUpstreamRefreshLocker(ctrl) rowID := storage.UpstreamTokenRowID("resolved-row-id") store.EXPECT().ResolveUpstreamTokenRowID(gomock.Any(), "session", "github").Return(rowID, nil) store.EXPECT().GetUpstreamTokens(gomock.Any(), "session", "github"). Return(unexpiredRow(), nil) - locker := &fakeLocker{results: []error{nil}} + var gotRowID storage.UpstreamTokenRowID + var gotTTL time.Duration + lease := storagemocks.NewMockUpstreamRefreshLease(ctrl) + lease.EXPECT().Release(gomock.Any()).Return(nil) + locker.EXPECT().AcquireUpstreamRefreshLock(gomock.Any(), gomock.Any(), gomock.Any()). + DoAndReturn(func( + _ context.Context, rowID storage.UpstreamTokenRowID, ttl time.Duration, + ) (storage.UpstreamRefreshLease, error) { + gotRowID, gotTTL = rowID, ttl + return lease, nil + }) + r := newLockTestRefresher(t, ctrl, store, locker) _, err := r.RefreshAndStore(t.Context(), "session", expiredRow("old-refresh")) require.NoError(t, err) - assert.Equal(t, rowID, locker.lastRowID.Load(), + assert.Equal(t, rowID, gotRowID, "the lease must cover the same row singleflight deduplicates") - assert.Greater(t, time.Duration(locker.lastLeaseTTL.Load()), refreshTimeout, + assert.Greater(t, gotTTL, refreshTimeout, "the lease must outlast the holder's whole read-redeem-write sequence") } +// TestNextUpstreamRefreshPoll pins the waiter's backoff. Each attempt costs an +// acquisition and a row read on a backend several replicas share, so a poll +// that stayed at its initial interval would put hundreds of round-trips per +// waiting request on it; one that grew without a cap would make a waiter miss +// a completed refresh for far longer than the refresh itself took. +func TestNextUpstreamRefreshPoll(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + current time.Duration + want time.Duration + }{ + {"doubles from the initial interval", upstreamRefreshLockPollInitial, 50 * time.Millisecond}, + {"keeps doubling below the cap", 100 * time.Millisecond, 200 * time.Millisecond}, + {"clamps a double that would overshoot", 300 * time.Millisecond, upstreamRefreshLockPollMax}, + {"stays at the cap", upstreamRefreshLockPollMax, upstreamRefreshLockPollMax}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tt.want, nextUpstreamRefreshPoll(tt.current)) + }) + } +} + +// TestNewUpstreamTokenRefresher_ResolvesLocker covers the one production site +// that resolves the lease capability. Without it, dropping that resolution — +// or a storage decorator that stops exposing Unwrap — would silently degrade +// every multi-replica deployment to CAS-only coordination with the rest of the +// suite still green, since every other test supplies the locker directly. +func TestNewUpstreamTokenRefresher_ResolvesLocker(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + storage func(t *testing.T) storage.UpstreamTokenStorage + wantLocker bool + }{ + { + name: "backend providing the capability", + storage: func(t *testing.T) storage.UpstreamTokenStorage { + t.Helper() + return newLockTestMemoryStorage(t) + }, + wantLocker: true, + }, + { + name: "backend behind the decorators newServer applies", + storage: func(t *testing.T) storage.UpstreamTokenStorage { + t.Helper() + decorated, err := storage.NewClientAdmissionStorage(newLockTestMemoryStorage(t), nil) + require.NoError(t, err) + return decorated + }, + wantLocker: true, + }, + { + name: "backend without the capability", + storage: func(t *testing.T) storage.UpstreamTokenStorage { + t.Helper() + return storagemocks.NewMockUpstreamTokenStorage(gomock.NewController(t)) + }, + wantLocker: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + provider := upstreammocks.NewMockOAuth2Provider(gomock.NewController(t)) + refresher := newUpstreamTokenRefresher( + []handlers.NamedUpstream{{Name: "github", Provider: provider}}, + tt.storage(t), + 24*time.Hour, + ) + require.NotNil(t, refresher) + + impl, ok := refresher.(*upstreamTokenRefresher) + require.True(t, ok) + if tt.wantLocker { + assert.NotNil(t, impl.locker, + "a backend providing the lease must be coordinated across replicas") + return + } + assert.Nil(t, impl.locker) + }) + } +} + +func newLockTestMemoryStorage(t *testing.T) *storage.MemoryStorage { + t.Helper() + stor := storage.NewMemoryStorage() + t.Cleanup(func() { _ = stor.Close() }) + return stor +} + // newLockTestRefresher builds a refresher whose provider mock has no // RefreshTokens expectation, so any upstream redemption fails the test. func newLockTestRefresher( diff --git a/pkg/authserver/storage/upstream_refresh_lock_test.go b/pkg/authserver/storage/upstream_refresh_lock_test.go index 3f612b68cd..3df8bd8826 100644 --- a/pkg/authserver/storage/upstream_refresh_lock_test.go +++ b/pkg/authserver/storage/upstream_refresh_lock_test.go @@ -168,34 +168,148 @@ func TestAcquireUpstreamRefreshLock(t *testing.T) { } } +// TestRedisUpstreamRefreshLock_BackendFailures covers what the Redis backend +// reports when it cannot be reached. The distinction matters: the refresher +// treats ErrUpstreamRefreshLockHeld as "wait for the holder" and anything else +// as "fail closed", so a fault reported as a refusal would park a request that +// should have errored, and a refusal reported as a fault would fail a request +// that only needed to wait. +func TestRedisUpstreamRefreshLock_BackendFailures(t *testing.T) { + t.Parallel() + + t.Run("an unreachable backend is a fault, not a refusal", func(t *testing.T) { + t.Parallel() + s, mr := newTestRedisStorage(t) + t.Cleanup(func() { _ = s.Close() }) + mr.Close() + + lease, err := s.AcquireUpstreamRefreshLock(t.Context(), testRowID, time.Minute) + assert.Nil(t, lease) + require.Error(t, err) + assert.NotErrorIs(t, err, ErrUpstreamRefreshLockHeld, + "a caller must fail closed here, not wait for a holder that does not exist") + }) + + t.Run("release reports a backend that went away", func(t *testing.T) { + t.Parallel() + s, mr := newTestRedisStorage(t) + t.Cleanup(func() { _ = s.Close() }) + + lease, err := s.AcquireUpstreamRefreshLock(t.Context(), testRowID, time.Minute) + require.NoError(t, err) + + mr.Close() + // Reported rather than swallowed, so the caller can log that the row + // stays locked until the TTL runs out. + assert.Error(t, lease.Release(t.Context())) + }) + + t.Run("a lease whose acquisition reply was lost does not block the row", func(t *testing.T) { + t.Parallel() + s, mr := newTestRedisStorage(t) + t.Cleanup(func() { + _ = s.Close() + mr.Close() + }) + + // Stand in for the reply that never came back: the SET landed, so the + // key is there, but no caller holds a lease over it. Clearing it is + // best-effort, and the owner token is the one the failed acquisition + // generated, so only that key is affected. + key := redisUpstreamRefreshLockKey(s.keyPrefix, testRowID) + require.NoError(t, s.client.Set(t.Context(), key, "orphaned-owner", time.Hour).Err()) + s.clearUnreleasableUpstreamRefreshLock(t.Context(), key, "orphaned-owner") + + lease, err := s.AcquireUpstreamRefreshLock(t.Context(), testRowID, time.Minute) + require.NoError(t, err, "a lease nobody holds must not block the row for its whole TTL") + assert.NotNil(t, lease) + }) + + t.Run("clearing leaves a lease another holder owns alone", func(t *testing.T) { + t.Parallel() + s, mr := newTestRedisStorage(t) + t.Cleanup(func() { + _ = s.Close() + mr.Close() + }) + + held, err := s.AcquireUpstreamRefreshLock(t.Context(), testRowID, time.Minute) + require.NoError(t, err) + require.NotNil(t, held) + + // The cleanup runs with the owner token of an acquisition that failed, + // which is not the one stored, so the live lease must survive. + key := redisUpstreamRefreshLockKey(s.keyPrefix, testRowID) + s.clearUnreleasableUpstreamRefreshLock(t.Context(), key, "some-other-owner") + + _, err = s.AcquireUpstreamRefreshLock(t.Context(), testRowID, time.Minute) + assert.ErrorIs(t, err, ErrUpstreamRefreshLockHeld) + }) +} + // TestMemoryStorage_cleanupExpiredRefreshLeases checks that a lease nobody // releases does not accumulate in the in-memory backend, and that the sweep // cannot take a live lease with it. func TestMemoryStorage_cleanupExpiredRefreshLeases(t *testing.T) { t.Parallel() - // withStorage calls t.Parallel on the subtest. t.Run("sweeps an expired lease and keeps a live one", func(t *testing.T) { - withStorage(t, func(ctx context.Context, s *MemoryStorage) { - _, err := s.AcquireUpstreamRefreshLock(ctx, "expiring-row", 10*time.Millisecond) - require.NoError(t, err) - _, err = s.AcquireUpstreamRefreshLock(ctx, "live-row", time.Hour) - require.NoError(t, err) - - time.Sleep(30 * time.Millisecond) - s.cleanupExpired() - - s.mu.RLock() - _, expiredPresent := s.upstreamRefreshLeases["expiring-row"] - _, livePresent := s.upstreamRefreshLeases["live-row"] - s.mu.RUnlock() - - assert.False(t, expiredPresent, "an expired lease should be swept") - assert.True(t, livePresent, "a live lease must survive the sweep") - }) + t.Parallel() + ctx, s := newLeaseSweepStorage(t) + + _, err := s.AcquireUpstreamRefreshLock(ctx, "expiring-row", 10*time.Millisecond) + require.NoError(t, err) + _, err = s.AcquireUpstreamRefreshLock(ctx, "live-row", time.Hour) + require.NoError(t, err) + + time.Sleep(30 * time.Millisecond) + s.cleanupExpired() + + s.mu.RLock() + _, expiredPresent := s.upstreamRefreshLeases["expiring-row"] + _, livePresent := s.upstreamRefreshLeases["live-row"] + s.mu.RUnlock() + + assert.False(t, expiredPresent, "an expired lease should be swept") + assert.True(t, livePresent, "a live lease must survive the sweep") + }) + + // cleanupExpired collects under the read lock and deletes under the write + // lock, so a lease it collected may have been released and re-acquired by + // the time the delete runs. The delete is driven directly here because + // nothing can interleave with it from outside. + t.Run("keeps a lease re-acquired since it was collected", func(t *testing.T) { + t.Parallel() + ctx, s := newLeaseSweepStorage(t) + + expiring, err := s.AcquireUpstreamRefreshLock(ctx, "contended-row", 10*time.Millisecond) + require.NoError(t, err) + + time.Sleep(30 * time.Millisecond) + collected := []UpstreamTokenRowID{"contended-row"} + + // The holder gives up its expired lease and a new one takes the row. + require.NoError(t, expiring.Release(ctx)) + _, err = s.AcquireUpstreamRefreshLock(ctx, "contended-row", time.Hour) + require.NoError(t, err) + + s.mu.Lock() + s.deleteExpiredRefreshLeasesLocked(time.Now(), collected) + _, present := s.upstreamRefreshLeases["contended-row"] + s.mu.Unlock() + + assert.True(t, present, + "deleting the new holder's lease would let a second replica redeem alongside it") }) } +func newLeaseSweepStorage(t *testing.T) (context.Context, *MemoryStorage) { + t.Helper() + s := NewMemoryStorage() + t.Cleanup(func() { _ = s.Close() }) + return t.Context(), s +} + // TestUpstreamRefreshLockerFrom covers capability discovery. Decorators embed // the Storage interface, so they do not carry the backend's optional // capabilities; the helper has to peel them or the refresher would silently @@ -222,12 +336,34 @@ func TestUpstreamRefreshLockerFrom(t *testing.T) { assert.Nil(t, UpstreamRefreshLockerFrom(lockerlessStorage{})) }) + t.Run("finds the capability through a chain of decorators", func(t *testing.T) { + t.Parallel() + s := NewMemoryStorage() + t.Cleanup(func() { _ = s.Close() }) + assert.NotNil(t, UpstreamRefreshLockerFrom( + NewCIMDShapeGuardStorage(NewCIMDShapeGuardStorage(s)), + )) + }) + + t.Run("returns nil for a decorator over a backend without the capability", func(t *testing.T) { + t.Parallel() + assert.Nil(t, UpstreamRefreshLockerFrom(unwrappingStorage{})) + }) + t.Run("returns nil for a nil storage", func(t *testing.T) { t.Parallel() assert.Nil(t, UpstreamRefreshLockerFrom(nil)) }) } +// unwrappingStorage is a decorator whose Unwrap returns nothing, standing in +// for a chain that ends before any backend provides the capability. +type unwrappingStorage struct { + UpstreamTokenStorage +} + +func (unwrappingStorage) Unwrap() Storage { return nil } + // lockerlessStorage is an UpstreamTokenStorage that provides neither the lock // capability nor Unwrap, standing in for a third-party backend. type lockerlessStorage struct { From abd72ffdc39987e8a3a10d216821429eac480876 Mon Sep 17 00:00:00 2001 From: hellouz818 Date: Mon, 23 Nov 2026 11:39:29 +0900 Subject: [PATCH 7/8] Document the upstream refresh lease for operators 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: #4122 Signed-off-by: hellouz818 --- docs/arch/11-auth-server-storage.md | 48 +++++++++++++++++------------ docs/redis-storage.md | 20 ++++++++++++ 2 files changed, 48 insertions(+), 20 deletions(-) diff --git a/docs/arch/11-auth-server-storage.md b/docs/arch/11-auth-server-storage.md index 95bc5e7c73..61ec512688 100644 --- a/docs/arch/11-auth-server-storage.md +++ b/docs/arch/11-auth-server-storage.md @@ -90,6 +90,7 @@ The storage layer implements multiple interfaces from the [fosite](https://githu - `DCRCredentialStore` — DCR client metadata and credential persistence; intentionally NOT embedded in `Storage` (each backend implements it separately and call sites reach it via an explicit `stor.(DCRCredentialStore)` type assertion). Secret-based clients store hashed secrets; `private_key_jwt` clients store their inline public JWKS and signing algorithm. Outbound (upstream) registrations resolved by `pkg/auth/dcr` are keyed by `(Issuer, UpstreamID, RedirectURI, ScopesHash)` plus the optional operator-set `dcrConfig.rotationKey`. `dcrConfig.clientName` sets the RFC 7591 `client_name` sent at registration; when empty, ToolHive registers as "ToolHive MCP Client". It is display-only metadata shown on the upstream's authorization screen and is never part of the registration's cache key, so changing it does not rename an already-registered client: the new value applies only the next time ToolHive registers a fresh client, for example after rotating via `rotationKey`. It is capped at 256 characters. Names with leading or trailing whitespace, or containing control or format characters, are rejected. Changing the rotation key addresses a new row, so the next start registers a fresh upstream client; the previous row stays in place and carries no TTL unless the upstream asserted `client_secret_expires_at`. The client registers with the token endpoint auth method the resolver prefers among those the upstream advertises (`client_secret_basic`, then `client_secret_post`, then `none`), or with the OAuth2 upstream's `tokenEndpointAuthMethod` when it is set, for an upstream whose token endpoint does not accept the preferred method. A registration response that names another method than the configured one is refused, and so is a resolution that still names one, such as a row a replica on an older configuration stored first; the next start or recheck replaces that row. On a cache hit the resolver also checks the cached client against the upstream and replaces the row when the upstream rejects it, or when the row was registered with another method than the configured `tokenEndpointAuthMethod`, provided the store implements `dcr.Replacer`. `dcrConfig.registrationProbe` selects the check: `tokenEndpoint` (default) redeems a random authorization code and reads `invalid_client` as "gone"; `authorizationEndpoint` sends an authorization request without following redirects and reads a direct 400/401/403 carrying an RFC 6749 JSON error object with `error` `invalid_client`, `unauthorized_client` or `invalid_request` as "gone" (RFC 6749 §4.1.2.1); `none` skips the upstream check but not the method check above. Each setting has a blind spot the rotation key covers: `tokenEndpoint` misses an upstream that validates the grant before authenticating a public client (it then answers `invalid_grant` for any client_id) and skips `private_key_jwt` clients, which it cannot sign for; `authorizationEndpoint` misses an upstream that renders its unknown-client error with 200, a redirect, or a page rather than a JSON error object; with `none` only the rotation key, or a change of the configured method, retires a registration. A false rejection by either probe re-registers at every start and, when registration also fails, fails startup. The check runs at start; `dcrConfig.registrationProbeInterval` (a Go duration of at least `1m`) repeats it while the server runs. Each tick re-runs the resolution against the stored row: a rejected registration is replaced, a missing one is registered, and when the result names a different client than the one in use, including a row another replica replaced, the upstream provider switches to it in place (`upstream.ClientCredentialsUpdater`; OIDC providers also replace their ID token verifier). A failed tick is logged and leaves the provider on its current client. An authorization started under the previous client and completed after the switch redeems its code with the new client, and upstream refresh tokens bound to the previous client stop refreshing, as with a restart. Each tick sends at most one probe request to the upstream from every replica (none with `registrationProbe: none`), plus a registration request when the probe rejects the client; the `tokenEndpoint` probe appears in upstream logs as a failed code redemption, so an interval of 5m to 15m suits most upstreams. Endpoints the run config leaves to discovery follow the new registration, and each replica waits a random part of the interval before its first tick and the interval ±10% after that. - `AssertionJWTConsumer` — atomic single-use consumption for validated JWT assertions. It is deliberately separate from `Storage`, so only assertion-grant composition requires replay protection. - `ExchangeGrantStorage` — optional server-side records behind refresh tokens issued through RFC 8693 token exchange. A callable discovers it with `storage.Unwrap(stor).(ExchangeGrantStorage)`. Memory and Redis implement it. See [Exchange grant storage](#exchange-grant-storage). +- `UpstreamRefreshLocker` — optional mutual-exclusion lease over one upstream token row, so only one replica redeems a single-use upstream refresh token. A callable discovers it with `storage.UpstreamRefreshLockerFrom(stor)`. Memory and Redis implement it; a backend without it falls back to compare-and-swap ordering alone. See [Redemption lease](#redemption-lease-upstreamrefreshlocker). **Implementation:** - Interface definitions: `pkg/authserver/storage/types.go` @@ -461,7 +462,7 @@ backend derives from it, which lives no longer than the lease. This is deliberately narrower than #4122's original in-process-only scope: it does not by itself provide distributed coordination across replicas. Two -further layers do. The first: +further layers do, and both run. The first: `UpstreamTokenStorage.CompareAndSwapUpstreamTokens` conditions a refresh write on the refresh token currently stored still matching the value the caller redeemed with, failing the write (`ErrConcurrentRefresh`) instead of @@ -476,16 +477,21 @@ across processes: whichever replica's write lands first wins, and every losing replica's write fails instead of silently clobbering it. This is a storage-ordering guarantee, not a guarantee that concurrent -redemption is safe at the upstream provider. Both replicas still call -`provider.RefreshTokens` before either one's CAS write runs, so for a -provider enforcing strict single-use rotation (RFC 9700 §4.14.2 replay -detection), two concurrent redemptions of the same refresh token can still -be indistinguishable from a replay at the IdP, which may revoke the grant -regardless of which replica's write wins. CAS alone is therefore sufficient -only where the provider tolerates a grace/leeway window in which more than -one redeemed child stays valid (e.g. Read.ai's stated behavior). Closing the -gap outside that window requires serializing the *redemption*, which is the -third layer below. +redemption is safe at the upstream provider. Without the second layer below, +both replicas call `provider.RefreshTokens` before either one's CAS write +runs, so for a provider enforcing strict single-use rotation (RFC 9700 +§4.14.2 replay detection), two concurrent redemptions of the same refresh +token can be indistinguishable from a replay at the IdP, which may revoke the +grant regardless of which replica's write wins. CAS alone is therefore +sufficient only where the provider tolerates a grace/leeway window in which +more than one redeemed child stays valid (e.g. Read.ai's stated behavior). +Closing the gap outside that window requires serializing the *redemption*, +which is the second layer. + +The refresher's `resolveConcurrentRefreshConflict` distinguishes a genuine +lost race (an unexpired row on re-read) from a row that is simply gone +(deleted by logout or evicted by TTL, `ErrNotFound` on re-read) — the latter +is expected behavior, not a race, and the row is not resurrected. #### Redemption lease (`UpstreamRefreshLocker`) @@ -512,7 +518,12 @@ other than "held by someone else" also fails closed, because a replica that cannot reach the backend cannot know whether another one is redeeming. The lease is advisory and bounded by a TTL set above `refreshTimeout`, so a -holder that dies mid-refresh blocks the row for at most that long. It does not +holder that dies mid-refresh blocks the row for at most that long. The holder +redeems on a fresh `refreshTimeout` budget starting at acquisition rather than +on whatever the caller had left, so a waiter that wins the lease late does not +run a rotation on a deadline that could cut it off between the IdP accepting +the redemption and the CAS write landing; the TTL margin covers the +best-effort per-provider delete that may follow. It does not replace CAS: both layers run, and the CAS write is what stays correct if a lease expires early under load. Redis implements acquisition as `SET NX PX` of a random owner token under `{prefix}upstream-lock:{rowID}` — the same row @@ -524,14 +535,10 @@ match the `upstream:*` scan pattern walked by the legacy-key migration. `MemoryStorage` implements the same semantics in-process under its existing mutex; it is reachable from one process only, where `singleflight` already deduplicates, but implementing it for real keeps a caller's behaviour -independent of which backend it was wired against. A backend providing -neither leaves `locker` nil and degrades to the CAS-only coordination -described above. - -The storage layer's own log distinguishes a genuine lost race (an unexpired -row on re-read) from a row that is simply gone (deleted by logout or evicted -by TTL, `ErrNotFound` on re-read) — the latter is expected behavior, not a -race, and the row is not resurrected. +independent of which backend it was wired against. A backend that does not +provide the capability degrades to the CAS-only coordination described above, +which is also what happens across a rolling upgrade while replicas on the +older version are still running. ### Upstream Refresh Rejections and the Refresh Grant @@ -1161,6 +1168,7 @@ The storage decorators (`CIMDStorageDecorator`, the CIMD shape guard, `SPIFFESto - **`RedisStorage` migration** (`runLegacyMigration`): A type assertion to `*storage.RedisStorage` is needed to run a one-shot data migration. - **`DeviceCodeStorage` assertion** (`buildDeviceFlowFactory` and `handlers.NewHandler`): The device flow reaches the device-code store on the concrete backend. - **`RememberedConsentStorage` assertion** (`handlers.NewHandler`): Remembered consent is only offered when the concrete backend implements it. +- **`UpstreamRefreshLocker` discovery** (`newUpstreamTokenRefresher`): `storage.UpstreamRefreshLockerFrom` resolves the optional redemption lease once at construction. Unlike the assertions above it walks the chain and tests every layer, not only the base, so a decorator that provides the capability itself is honoured; it returns nil when no layer does. - **Continuation fallback** (`handlers.NewHandler`, used by `callbackClient` in `handlers/callback.go`): deliberately bypasses the CIMD decorator. When the CIMD fetch limiter refuses a lookup during callback, consent, or device verification, it reads the persisted client row through the admitted below-CIMD view (`storage.ClientStoreBelowCIMD`, which stops at `ClientAdmissionStorage`). That view is selected once by `NewHandler` and kept on the handler, not found by walking the decorators during the request, so the fallback still passes client admission and never reaches the raw backend. The `AssertionJWTConsumer` capability is separate: `CIMDStorageDecorator` implements `ConsumeAssertionJWT` and forwards it to a capable backend. If the backend lacks the capability, the decorator returns an error instead of accepting an assertion with unknown replay status; replay protection therefore fails closed. diff --git a/docs/redis-storage.md b/docs/redis-storage.md index f2e3431300..19bcdef577 100644 --- a/docs/redis-storage.md +++ b/docs/redis-storage.md @@ -358,6 +358,7 @@ All keys use the prefix `thv:auth:{namespace:name}:` where `{namespace:name}` is | `{prefix}user:{user_id}` | User account | None | | `{prefix}provider:{len}:{provider_id}:{subject}` | Provider identity linkage | None | | `{prefix}upstream:{session_id}` | Upstream IDP tokens | Matches token lifetime | +| `{prefix}upstream-lock:{row_id}` | Mutual-exclusion lease held by the one replica refreshing an upstream token row. Value is a random owner token; `row_id` is a SHA-256 digest that carries no session ID | 45 seconds; deleted when the holder finishes | | `{prefix}pending:{handle_or_state}` | Browser-bound consent handle or upstream callback state | Remaining time until the initial `CreatedAt` + 10 minutes; deadline checked before consent/callback consumption | | `{prefix}consent:session:{digest}` | SHA-256 digest of the browser session cookie secret (never the raw secret) | Remaining fixed lifetime, at most 7 days | | `{prefix}consent:approval:{pair_hash}` | One approval per user/client; `pair_hash` is SHA-256 of the JSON-encoded `[userID, clientID]` pair | Remaining fixed lifetime, at most 30 days | @@ -411,6 +412,25 @@ The storage implementation uses different strategies depending on the consistenc Secondary index cleanup is best-effort: stale entries may remain temporarily but are cleaned up on the next write or by TTL expiration. +### Upstream Refresh Serialization + +Upstream refresh tokens are usually single-use: redeeming one returns a replacement and invalidates it. With more than one auth server replica sharing this Redis, two replicas can find the same expired upstream access token at the same time. Both would redeem the same refresh token, and an IdP that enforces strict rotation can treat the second redemption as a replay and revoke the whole grant. + +To prevent that, a replica takes `{prefix}upstream-lock:{row_id}` before refreshing one row and holds it until the refreshed tokens are stored. Only the holder calls the upstream provider. This changes how refresh requests behave: + +- **A replica that is not the holder waits.** It polls the row while the holder works and returns the refreshed tokens as soon as they are stored, so the request succeeds — it is just slower, typically by the length of one upstream refresh. Waiting is bounded at 30 seconds, after which the request fails rather than redeeming on its own. +- **A Redis fault during the refresh fails the request.** A replica that cannot reach Redis cannot tell whether another replica is redeeming, so it fails closed with `could not acquire upstream refresh lock` instead of risking the replay. This is the same dependency the stored row already has; it does not affect requests that need no refresh. +- **A replica that crashes mid-refresh blocks its row for up to 45 seconds**, the lease TTL. Only that one session's upstream refreshes are affected, and only until the lease expires. Requests arriving in the first 15 seconds of that window wait out their 30 seconds and fail; later ones take the lease over and refresh normally. +- **During a rolling upgrade**, replicas still on the older version do not take the lease, so for the length of the rollout two replicas can still redeem the same refresh token, exactly as before the upgrade. No migration is needed, and rolling back simply removes the coordination; `upstream-lock:*` keys expire on their own. + +The lease is advisory. A Redis failover that promotes a replica before the acquisition replicated, or a holder whose host paused it past the TTL, can leave two holders. The compare-and-swap on the stored row still orders their writes, which is the behavior described in [Auth Server Storage](arch/11-auth-server-storage.md#refresh-coordination-scope). + +To see the lease while a refresh is in flight: + +```bash +redis-cli --scan --pattern '*upstream-lock*' +``` + ## Troubleshooting ### Connection Failures From 03dfb7dd1a8245b5fdadc588834182b936d0ebc5 Mon Sep 17 00:00:00 2001 From: hellouz818 Date: Mon, 23 Nov 2026 13:14:51 +0900 Subject: [PATCH 8/8] Keep the lease rationale at its owner 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: #4122 Signed-off-by: hellouz818 --- pkg/authserver/refresher.go | 12 ++++++------ pkg/authserver/storage/memory.go | 6 ++---- pkg/authserver/storage/redis.go | 6 ++---- pkg/authserver/storage/upstream_refresh_lock_test.go | 11 +++++++++++ 4 files changed, 21 insertions(+), 14 deletions(-) diff --git a/pkg/authserver/refresher.go b/pkg/authserver/refresher.go index 8d4e24227b..3d616cff3d 100644 --- a/pkg/authserver/refresher.go +++ b/pkg/authserver/refresher.go @@ -83,12 +83,12 @@ const upstreamConflictReadTimeout = 5 * time.Second // - locker, when the storage backend provides one, serializes the whole // read-redeem-write sequence ACROSS PROCESSES with a lease over the same // row identity singleflight uses, so only the lease holder calls the -// upstream provider. This is what keeps a strict single-use-rotation IdP -// from seeing two replicas redeem one refresh token as a replay. The -// lease is advisory, so two residual gaps remain: one lost in a Redis -// failover that promoted a replica before the acquisition replicated, and -// a holder the host paused past the TTL. Those, and a backend that -// provides no lease at all, end at the layer below. +// upstream provider — see storage.UpstreamRefreshLocker for why that is +// needed on top of the layer below. The lease is advisory, so two +// residual gaps remain: one lost in a Redis failover that promoted a +// replica before the acquisition replicated, and a holder the host paused +// past the TTL. Those, and a backend that provides no lease at all, end +// at the layer below. // - CompareAndSwapUpstreamTokens (see refreshAndStore) makes the STORED row // deterministic ACROSS PROCESSES: every write is conditioned on the refresh // token this call redeemed still being the one stored, so a replica whose diff --git a/pkg/authserver/storage/memory.go b/pkg/authserver/storage/memory.go index 4f07412204..8b13bf7cd0 100644 --- a/pkg/authserver/storage/memory.go +++ b/pkg/authserver/storage/memory.go @@ -1451,10 +1451,8 @@ func (s *MemoryStorage) DeletePKCERequestSession(_ context.Context, signature st // Upstream Token Storage // ----------------------- -// ResolveUpstreamTokenRowID returns an opaque ID identifying one logical -// upstream-token row, used to coordinate refreshes of it: the auth server's -// in-process singleflight group and the cross-process UpstreamRefreshLocker -// lease are both keyed by it. See UpstreamTokenStorage for the contract. +// ResolveUpstreamTokenRowID implements UpstreamTokenStorage, which defines +// what the ID identifies and what may be done with it. func (*MemoryStorage) ResolveUpstreamTokenRowID(_ context.Context, sessionID, providerName string) (UpstreamTokenRowID, error) { if sessionID == "" { return "", fosite.ErrInvalidRequest.WithHint("session ID cannot be empty") diff --git a/pkg/authserver/storage/redis.go b/pkg/authserver/storage/redis.go index 3b0f07a2c6..013943c6ad 100644 --- a/pkg/authserver/storage/redis.go +++ b/pkg/authserver/storage/redis.go @@ -1803,10 +1803,8 @@ func (s *RedisStorage) CompareAndSwapUpstreamTokens( return nil } -// ResolveUpstreamTokenRowID returns an opaque ID identifying one logical -// upstream-token row, used to coordinate refreshes of it: the auth server's -// in-process singleflight group and the cross-process UpstreamRefreshLocker -// lease are both keyed by it. See UpstreamTokenStorage for the contract. +// ResolveUpstreamTokenRowID implements UpstreamTokenStorage, which defines +// what the ID identifies and what may be done with it. func (s *RedisStorage) ResolveUpstreamTokenRowID(_ context.Context, sessionID, providerName string) (UpstreamTokenRowID, error) { if sessionID == "" { return "", fosite.ErrInvalidRequest.WithHint("session ID cannot be empty") diff --git a/pkg/authserver/storage/upstream_refresh_lock_test.go b/pkg/authserver/storage/upstream_refresh_lock_test.go index 3df8bd8826..c0affdcc3e 100644 --- a/pkg/authserver/storage/upstream_refresh_lock_test.go +++ b/pkg/authserver/storage/upstream_refresh_lock_test.go @@ -346,6 +346,11 @@ func TestUpstreamRefreshLockerFrom(t *testing.T) { }) t.Run("returns nil for a decorator over a backend without the capability", func(t *testing.T) { + t.Parallel() + assert.Nil(t, UpstreamRefreshLockerFrom(NewCIMDShapeGuardStorage(lockerlessBackend{}))) + }) + + t.Run("returns nil when the chain ends in an Unwrap that returns nothing", func(t *testing.T) { t.Parallel() assert.Nil(t, UpstreamRefreshLockerFrom(unwrappingStorage{})) }) @@ -364,6 +369,12 @@ type unwrappingStorage struct { func (unwrappingStorage) Unwrap() Storage { return nil } +// lockerlessBackend is a full Storage that provides no lease, so a real +// decorator can be put over it. +type lockerlessBackend struct { + Storage +} + // lockerlessStorage is an UpstreamTokenStorage that provides neither the lock // capability nor Unwrap, standing in for a third-party backend. type lockerlessStorage struct {