diff --git a/docs/arch/11-auth-server-storage.md b/docs/arch/11-auth-server-storage.md index a1015799a2..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` @@ -410,6 +411,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 +451,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, 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 @@ -467,22 +477,68 @@ 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 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. +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`) + +`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 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. + +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. 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 +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 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 @@ -1112,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 diff --git a/pkg/authserver/refresher.go b/pkg/authserver/refresher.go index 3674e892fd..3d616cff3d 100644 --- a/pkg/authserver/refresher.go +++ b/pkg/authserver/refresher.go @@ -33,6 +33,33 @@ 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, 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, 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 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 +) + // 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 +80,15 @@ 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 — 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 @@ -67,8 +103,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 +120,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 +158,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 +171,178 @@ 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, 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: 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, + 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, upstreamRefreshWaitTimeout(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, upstreamRefreshWaitTimeout(caller.ProviderID, ctx.Err()) + case <-time.After(wait): + } + 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", + "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. +// +// 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, + 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, + ) + } + }() + + 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 +// 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 (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 { + 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,9 +557,15 @@ 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 -// and an unexpired access token, that row is the result to use, so a lost race -// is not reported as a dead upstream credential. +// stored a valid row. The refresh lease (see coordinatedRefresh) is what +// 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 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. // // "Another process refreshed" is tested by refresh-token inequality, unlike // rowChanged, which also compares the access token, ID token and expiry. The diff --git a/pkg/authserver/refresher_contention_test.go b/pkg/authserver/refresher_contention_test.go new file mode 100644 index 0000000000..129f286242 --- /dev/null +++ b/pkg/authserver/refresher_contention_test.go @@ -0,0 +1,256 @@ +// 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" +) + +// 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 +// 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 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 +} + +// 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) }) + // 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", + 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 + ) + + // 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() + // 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) + 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(contentionWaitTimeout): + 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(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 + // 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") + + provider.releaseAll() + waitWithTimeout(t, &wg, "both refreshers should finish once the provider is released") + + 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") +} + +// 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. +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, + } +} diff --git a/pkg/authserver/refresher_lock_test.go b/pkg/authserver/refresher_lock_test.go new file mode 100644 index 0000000000..226866e218 --- /dev/null +++ b/pkg/authserver/refresher_lock_test.go @@ -0,0 +1,456 @@ +// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package authserver + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "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" +) + +// 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), + } +} + +// 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. 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() + + 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() + + // 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), + ) + + 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") + }) + + t.Run("fails when the caller's budget runs out", func(t *testing.T) { + t.Parallel() + ctrl := gomock.NewController(t) + store := storagemocks.NewMockUpstreamTokenStorage(ctrl) + locker := storagemocks.NewMockUpstreamRefreshLocker(ctrl) + + // 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) + + // 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.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") + + // 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) + }) + + 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 contending rather than return it. + store.EXPECT().GetUpstreamTokens(gomock.Any(), "session", "github"). + Return(expiredRow("some-other-refresh"), nil) + + 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.Canceled) + }) +} + +// 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 + // 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) + + gomock.InOrder( + expectAcquireHeld(locker), + expectAcquireGranted(ctrl, locker, 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) +} + +// 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. The Release expectation lives in +// expectAcquireGranted, so each case fails if its lease is not released. +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) + locker := storagemocks.NewMockUpstreamRefreshLocker(ctrl) + winner := unexpiredRow() + store.EXPECT().GetUpstreamTokens(gomock.Any(), "session", "github").Return(winner, nil) + expectAcquireGranted(ctrl, locker, 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) + }) + + 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) + + r := newLockTestRefresher(t, ctrl, store, locker) + + _, err := r.coordinatedRefresh(t.Context(), "session", "row", expiredRow("old-refresh")) + require.Error(t, err) + }) + + 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")) + + 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) + 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) + + 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, gotRowID, + "the lease must cover the same row singleflight deduplicates") + 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( + 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..d1c28db08c 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 +// (see upstreamTokenRefresher's doc) so every refresh path shares one. func newUpstreamTokenRefresher( upstreams []handlers.NamedUpstream, stor storage.UpstreamTokenStorage, @@ -1089,9 +1091,18 @@ func newUpstreamTokenRefresher( for _, u := range upstreams { providers[u.Name] = u.Provider } + // 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; " + + "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..8b13bf7cd0 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,8 @@ func (s *MemoryStorage) cleanupExpired() { delete(s.pkceRequests, k) } + s.deleteExpiredRefreshLeasesLocked(now, expiredRefreshLeases) + for _, k := range expiredUpstreamTokens { delete(s.upstreamTokens, k) } @@ -1432,8 +1451,8 @@ 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 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") @@ -1461,6 +1480,80 @@ 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 +// 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, 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) { + 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 +2634,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..013943c6ad 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" @@ -1801,8 +1803,8 @@ func (s *RedisStorage) CompareAndSwapUpstreamTokens( return nil } -// ResolveUpstreamTokenRowID returns an opaque ID for process-local refresh -// coordination of a logical upstream-token row. +// 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") @@ -1813,6 +1815,117 @@ 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 (see +// UpstreamRefreshLease.Release). +// +// 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 +`) + +// 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 + 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 { + // 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 { + return nil, ErrUpstreamRefreshLockHeld + } + + 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. @@ -3745,6 +3858,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..bd2fe85117 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 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. KeyTypeUserUpstream = "user:upstream" @@ -208,3 +216,15 @@ 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}". +// +// 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 c1c9612a7b..7dc14bd76e 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,14 @@ 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 + // 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 // DCRCredentialStore.UpdateDCRCredentialsIfUnchanged when the stored row // no longer equals the caller's expected value: another writer replaced it @@ -1232,8 +1240,10 @@ 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 lives no longer than the lease. type UpstreamTokenRowID string // upstreamTokenRowID returns a SHA-256 digest of the supplied row-key components. @@ -1272,8 +1282,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 +1406,54 @@ 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. +// +// 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, 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. +// +// 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 + // 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 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 +} + // 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..dd0c1faf2b 100644 --- a/pkg/authserver/storage/unwrap.go +++ b/pkg/authserver/storage/unwrap.go @@ -15,3 +15,30 @@ func Unwrap(stor Storage) Storage { stor = unwrapper.Unwrap() } } + +// UpstreamRefreshLockerFrom returns the UpstreamRefreshLocker capability of +// 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 { + 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..c0affdcc3e --- /dev/null +++ b/pkg/authserver/storage/upstream_refresh_lock_test.go @@ -0,0 +1,382 @@ +// 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) + }) + }) + }) + } +} + +// 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() + + t.Run("sweeps an expired lease and keeps a live one", func(t *testing.T) { + 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 +// 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("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(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{})) + }) + + 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 } + +// 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 { + UpstreamTokenStorage +}