diff --git a/.changeset/auth-background-refresh.md b/.changeset/auth-background-refresh.md new file mode 100644 index 0000000000..2adbc0ae3c --- /dev/null +++ b/.changeset/auth-background-refresh.md @@ -0,0 +1,29 @@ +--- +'@cipherstash/auth': patch +--- + +Access-key and device-session tokens are now refreshed before they expire, +in the background. In Node, such a strategy refreshes its token on a task of +its own. The refresh is due between 90 seconds and two minutes before the +token expires. So +`getToken` returns the current token at once while it has more than 30 +seconds left. Before, the first call in the last 90 seconds started the +refresh and waited for it. + +A call whose token has less than 30 seconds left still refreshes it, or +waits for the refresh already running. It does not get back a token that may +expire before it is used. The refresh runs only while the strategy is in use, +so an idle process stops asking the token service. + +`OidcFederationStrategy` has no background task: each user's token is still +refreshed by that user's calls, in the last 90 seconds before it expires. The +30-second rule above does not apply to it. + +After a refresh fails, the next attempt waits about a second, doubling up to +30 seconds. Meanwhile a call whose token still works gets it. A call whose +token has expired fails at once with that refresh's error, rather than every +call asking the token service again. This backoff also applies to the WASM +build. That build has no background task, and still refreshes in the last 90 +seconds. + +The JavaScript API is unchanged. diff --git a/.github/workflows/test-eql.yml b/.github/workflows/test-eql.yml index 69ee76f0f0..c6ea81eec1 100644 --- a/.github/workflows/test-eql.yml +++ b/.github/workflows/test-eql.yml @@ -540,18 +540,8 @@ jobs: postgres-version: ${{ fromJSON(needs.setup.outputs.pg-versions) }} services: encryption-postgres: - image: postgres:${{ matrix.postgres-version }} - # Docker Hub refuses pulls without a login after too many from one - # address, and RunsOn machines reach that limit. One expression, not - # `username:` and `password:` keys: GitHub rejects an empty value for - # either key ("Unexpected value ''"), which fails the job on a fork's - # pull request. With either secret empty this gives `{}`, and the - # runner then pulls without a login. - credentials: >- - ${{ secrets.DOCKER_HUB_USERNAME != '' && secrets.DOCKER_HUB_PASSWORD != '' - && fromJSON(format('{{"username":{0},"password":{1}}}', - toJSON(secrets.DOCKER_HUB_USERNAME), toJSON(secrets.DOCKER_HUB_PASSWORD))) - || fromJSON('{}') }} + # Docker's public ECR mirror avoids Docker Hub's anonymous pull limit. + image: public.ecr.aws/docker/library/postgres:${{ matrix.postgres-version }} env: POSTGRES_PASSWORD: postgres # Container port only: Docker picks the host port, and the test step diff --git a/.github/workflows/tests-golang.yml b/.github/workflows/tests-golang.yml index f03d30b25d..5d797f2208 100644 --- a/.github/workflows/tests-golang.yml +++ b/.github/workflows/tests-golang.yml @@ -483,18 +483,8 @@ jobs: timeout-minutes: 30 services: postgres: - image: postgres:17 - # Docker Hub refuses pulls without a login after too many from one - # address, and RunsOn machines reach that limit. One expression, not - # `username:` and `password:` keys: GitHub rejects an empty value for - # either key ("Unexpected value ''"), which fails the job on a fork's - # pull request. With either secret empty this gives `{}`, and the - # runner then pulls without a login. - credentials: >- - ${{ secrets.DOCKER_HUB_USERNAME != '' && secrets.DOCKER_HUB_PASSWORD != '' - && fromJSON(format('{{"username":{0},"password":{1}}}', - toJSON(secrets.DOCKER_HUB_USERNAME), toJSON(secrets.DOCKER_HUB_PASSWORD))) - || fromJSON('{}') }} + # Docker's public ECR mirror avoids Docker Hub's anonymous pull limit. + image: public.ecr.aws/docker/library/postgres:17 env: POSTGRES_PASSWORD: postgres # Container port only: Docker picks the host port, and the test step diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 564723c70c..126b1dc00d 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -752,7 +752,7 @@ jobs: run: | docker run -d --name pg18-upgrade -e POSTGRES_PASSWORD=password \ -p 127.0.0.1::5432 \ - postgres:18@sha256:e3d24f6906d0760bf4da0dae872415391ededefad23fd471c47dc53b0ddf3c42 + public.ecr.aws/docker/library/postgres:18@sha256:e3d24f6906d0760bf4da0dae872415391ededefad23fd471c47dc53b0ddf3c42 # Probe over TCP: the init-time server listens on the socket only. for _ in $(seq 1 60); do docker exec pg18-upgrade pg_isready -h 127.0.0.1 -U postgres -q && break diff --git a/e2e/migration-harness/isolation/Dockerfile b/e2e/migration-harness/isolation/Dockerfile index 61e9a0b60e..7ecbeba2c8 100644 --- a/e2e/migration-harness/isolation/Dockerfile +++ b/e2e/migration-harness/isolation/Dockerfile @@ -1,4 +1,4 @@ -FROM node:22-bookworm-slim +FROM public.ecr.aws/docker/library/node:22-bookworm-slim RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates strace socat python3 util-linux git && rm -rf /var/lib/apt/lists/* # A bind mount's root can appear root-owned (Colima virtiofs on macOS) while the # actor runs as the host uid; Git would then refuse /workspace as dubious ownership. diff --git a/e2e/migration-harness/run/real-stores.mjs b/e2e/migration-harness/run/real-stores.mjs index 7e48b1425b..94e1c2e834 100644 --- a/e2e/migration-harness/run/real-stores.mjs +++ b/e2e/migration-harness/run/real-stores.mjs @@ -45,7 +45,7 @@ async function publishAdminPort(target, port, network, resources) { '64m', '-p', `127.0.0.1::${port}`, - 'node:22-bookworm-slim', + 'public.ecr.aws/docker/library/node:22-bookworm-slim', 'node', '-e', `const net = require('node:net'); @@ -121,7 +121,7 @@ async function initializePostgres(actor, eqlBundle, postgresV2) { `POSTGRES_PASSWORD=${password}`, '--tmpfs', '/var/lib/postgresql/data:rw,nosuid,nodev,size=512m', - 'postgres:17-alpine', + 'public.ecr.aws/docker/library/postgres:17-alpine', ]) resources.push(pg) const pgPort = await publishAdminPort(pg, 5432, network, resources) diff --git a/languages/golang/CHANGELOG.md b/languages/golang/CHANGELOG.md index e4b3a369ab..691fbf6784 100644 --- a/languages/golang/CHANGELOG.md +++ b/languages/golang/CHANGELOG.md @@ -13,6 +13,32 @@ and `languages/golang/encrypt/encrypttest/vX.Y.Z` on the same commit. ## [Unreleased] +### Changed + +- **Tokens are refreshed in the background, before they expire** (#1962). + An access-key or device-session `auth.Strategy` now runs a goroutine that + refreshes its token between 90 seconds and two minutes before the token + expires. So no call waits for the token service while its token has more + than 30 seconds left. That includes the call that used to start the + refresh. + - The refresh runs only while the strategy is in use. A strategy no call + has used since its last refresh is left alone, so an idle process does + not keep calling the service. + - After a refresh fails, the next attempt waits about a second, doubling + with each failure up to 30 seconds. Meanwhile a call whose token still + works gets it. A call whose token has expired fails at once with the + failed refresh's error, rather than each call asking the service again. + - `Strategy.Close` and `ProfileStore.Close` stop the goroutine, as does + the strategy being garbage collected. + - A call whose token has less than 30 seconds left refreshes it, or + waits for the refresh already running. It does not get back a token + that may expire before it is used. `auth.WithRefreshFloor` sets this + refresh floor for an access-key or device-session strategy. For + short-lived tokens, keep it at or below half the token's lifetime. + - An OIDC strategy has no such goroutine. Its provider is asked for a JWT + on every call. A timer cannot ask for one. The refresh floor does not + apply to it: a call inside the 90 seconds before expiry refreshes. + ### Added - `gensupport.UUID`, the kind `"uuid"`: a field the engine seals and diff --git a/languages/golang/auth/README.md b/languages/golang/auth/README.md index 8dd083f33e..392eac89c3 100644 --- a/languages/golang/auth/README.md +++ b/languages/golang/auth/README.md @@ -121,6 +121,19 @@ exchanged, other callers of the same strategy get its current token at once, and a caller with no usable token waits for that exchange rather than starting its own. +An access-key or device-session strategy refreshes its token ahead of its +expiry from a goroutine of its own, by stack-auth's rule +(`RefreshSchedule`): between 90 seconds and two minutes before expiry, +only while the strategy is in use, and with backoff after a failure. A +call whose token has less than the refresh floor left (30 seconds, or +`WithRefreshFloor`) refreshes it first, as for an expired token. The +floor does not apply to an OIDC strategy. The guest keeps the +rule; Go keeps the timer. It asks the guest when the next refresh is due +(`sa_auth_next_refresh`), sleeps until then, and calls +`sa_auth_refresh_ahead`, both step operations like a token fetch. The +goroutine holds the strategy only weakly, and never holds the profile's +lock while it sleeps. + The crypto guest behind `encrypt` is not widened by this package existing: it still has no filesystem and no environment. diff --git a/languages/golang/auth/background.go b/languages/golang/auth/background.go new file mode 100644 index 0000000000..5428abf62b --- /dev/null +++ b/languages/golang/auth/background.go @@ -0,0 +1,170 @@ +package auth + +import ( + "context" + "errors" + "runtime" + "strconv" + "sync/atomic" + "time" + "weak" + + "github.com/cipherstash/stack/languages/golang/internal/guest" + "github.com/tetratelabs/wazero/api" +) + +// refreshLoops counts the refresh loops running. The tests read it to +// prove that none outlives its strategy. +var refreshLoops atomic.Int32 + +// minRefreshGap is the least time between two refresh attempts of one +// loop, so a plan that stays due (a caller's refresh still in flight, say) +// cannot spin it. +const minRefreshGap = time.Second + +// startRefreshLoop starts the goroutine that refreshes the strategy's +// token ahead of its expiry, by stack-auth's rule (the guest's +// sa_auth_next_refresh): only while the token is in use, and with backoff +// after a failure. Close stops it, as does closing the profile. +// +// The loop holds the strategy weakly, and only while it talks to the +// guest: a strategy its application forgets to close is still collected, +// and its cleanup stops the loop. +func (s *Strategy) startRefreshLoop() { + ctx, cancel := context.WithCancel(context.Background()) + s.stopLoop = cancel + s.used = make(chan struct{}, 1) + s.loopDone = make(chan struct{}) + runtime.AddCleanup(s, func(cancel context.CancelFunc) { cancel() }, cancel) + refreshLoops.Add(1) + go refreshLoop(ctx, weak.Make(s), s.used, s.store.root.done, s.loopDone) +} + +// signalUse wakes the refresh loop if it is idle: the token was used, so +// its refresh ahead of expiry is due again. +func (s *Strategy) signalUse() { + select { + case s.used <- struct{}{}: + default: + } +} + +func refreshLoop(ctx context.Context, strategy weak.Pointer[Strategy], used <-chan struct{}, closing <-chan struct{}, done chan<- struct{}) { + defer refreshLoops.Add(-1) + defer close(done) + // Nothing to refresh before the first token: wait for a call to get + // one, rather than ask while that call's exchange holds the strategy. + if waitFor(ctx, 0, used, closing) == stop { + return + } + var lastAttempt time.Time + for { + s := strategy.Value() + if s == nil { + return + } + at, idle, err := s.nextRefresh(ctx) + s = nil + switch { + case ctx.Err() != nil, errors.Is(err, ErrState): + return + case err != nil: + // Nothing to act on: look again in a minute, or when the token + // is next used. + at, idle = time.Now().Add(time.Minute), false + } + var wake <-chan struct{} + var wait time.Duration + if idle { + wake = used + } else { + wait = max(time.Until(at), minRefreshGap-time.Since(lastAttempt)) + } + switch waitFor(ctx, wait, wake, closing) { + case stop: + return + case woken: + continue + case elapsed: + } + if s = strategy.Value(); s == nil { + return + } + lastAttempt = time.Now() + s.refreshAhead(ctx) + s = nil + } +} + +type waited int + +const ( + stop waited = iota + woken + elapsed +) + +// waitFor waits until wait has passed (when wake is nil), or until wake +// fires (when it is not), unless ctx ends or the profile closes first. +func waitFor(ctx context.Context, wait time.Duration, wake <-chan struct{}, closing <-chan struct{}) waited { + var due <-chan time.Time + if wake == nil { + timer := time.NewTimer(wait) + defer timer.Stop() + due = timer.C + } + select { + case <-ctx.Done(): + return stop + case <-closing: + return stop + case <-wake: + return woken + case <-due: + return elapsed + } +} + +// nextRefresh asks the guest when the token's next refresh ahead of +// expiry is due. idle means not until the token is used again. +func (s *Strategy) nextRefresh(ctx context.Context) (at time.Time, idle bool, err error) { + out, err := s.store.run(ctx, func(i *instance) api.Function { return i.authNextRefresh }, guest.BufArg([]byte(s.handle))) + if err != nil { + return time.Time{}, false, err + } + if len(out) == 0 { + return time.Time{}, true, nil + } + secs, err := strconv.ParseInt(string(out), 10, 64) + if err != nil { + return time.Time{}, false, errMalformedNextRefresh + } + return time.Unix(secs, 0), false, nil +} + +var errMalformedNextRefresh = errors.New("auth: the guest's next refresh time is not a number") + +// refreshAhead refreshes the token if its refresh is still due. Its +// outcome is the guest's to record: a failure backs the next attempt off, +// and a caller whose token has expired meanwhile gets that failure's +// error. A device session refreshes as Token does, one at a time in the +// process and under the cross-process lock; a caller already refreshing +// one inline is left to it. +func (s *Strategy) refreshAhead(ctx context.Context) { + refresh := func(ctx context.Context) error { + out, err := s.store.run(ctx, func(i *instance) api.Function { return i.authRefreshAhead }, guest.BufArg([]byte(s.handle))) + guest.Wipe(out) + return err + } + if !s.device { + _ = refresh(ctx) + return + } + if !s.refreshing.TryLock() { + return + } + defer s.refreshing.Unlock() + // The one request that rotates a credential runs on after Close + // cancels the loop, for the grace (see refreshGrace). + _ = s.refreshDeviceSession(ctx, refresh) +} diff --git a/languages/golang/auth/background_test.go b/languages/golang/auth/background_test.go new file mode 100644 index 0000000000..5d26c6ce5e --- /dev/null +++ b/languages/golang/auth/background_test.go @@ -0,0 +1,426 @@ +package auth + +import ( + "context" + "errors" + "fmt" + "io" + "math" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "runtime" + "sync/atomic" + "testing" + "time" +) + +// A strategy's token is refreshed in the background, ahead of its expiry, +// so no caller with a token that still works waits for the token service. + +// shortTokenServer answers access-key exchanges with tokens that last +// lifetime, named by the exchange's number ("1", "2", ...). Every exchange +// after the first is announced on refreshing and answered after delay. +func shortTokenServer(t *testing.T, lifetime, delay time.Duration) (server *httptest.Server, requests *atomic.Int32, refreshing chan struct{}) { + t.Helper() + requests = new(atomic.Int32) + refreshing = make(chan struct{}, 64) + var issuer string + server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + n := requests.Add(1) + if n > 1 { + select { + case refreshing <- struct{}{}: + default: + } + select { + case <-time.After(delay): + case <-r.Context().Done(): + return + } + } + fmt.Fprintf(w, `{"accessToken":%q,"expiry":%d}`, testJWTFor(t, issuer, fmt.Sprint(n)), time.Now().Add(lifetime).Unix()) + })) + issuer = server.URL + t.Cleanup(server.Close) + return server, requests, refreshing +} + +// A token inside the 90-second refresh window still works: the caller +// gets it at once, and neither starts nor waits for its refresh. +func TestACallerWithAValidTokenDoesNotWaitForItsRefresh(t *testing.T) { + guestOrSkip(t) + const delay = time.Second + server, _, _ := shortTokenServer(t, 60*time.Second, delay) + profile, err := Open(context.Background(), t.TempDir()) + if err != nil { + t.Fatal(err) + } + defer profile.Close() + strategy, err := profile.AccessKey(context.Background(), testCRN, "CSAKtestKeyId.testKeySecret", WithBaseURL(server.URL)) + if err != nil { + t.Fatal(err) + } + defer strategy.Close() + + if token, err := strategy.Token(context.Background()); err != nil || jwtSubject(t, token) != "1" { + t.Fatalf("the first Token: %q, %v", token, err) + } + start := time.Now() + token, err := strategy.Token(context.Background()) + if waited := time.Since(start); waited > delay/4 { + t.Errorf("the caller waited %v for a refresh its valid token did not need", waited) + } + if err != nil || jwtSubject(t, token) != "1" { + t.Errorf("got %q, %v, want the current token, %q", jwtSubject(t, token), err, "1") + } +} + +// A token in use is refreshed before it expires, with no caller asking. +func TestATokenInUseIsRefreshedBeforeItExpires(t *testing.T) { + guestOrSkip(t) + const lifetime = 4 * time.Second + server, requests, refreshing := shortTokenServer(t, lifetime, 0) + profile, err := Open(context.Background(), t.TempDir()) + if err != nil { + t.Fatal(err) + } + defer profile.Close() + // The floor is off. The token lasts less than the default floor, and + // this test is about the refresh no caller makes. + strategy, err := profile.AccessKey(context.Background(), testCRN, "CSAKtestKeyId.testKeySecret", WithBaseURL(server.URL), WithRefreshFloor(0)) + if err != nil { + t.Fatal(err) + } + defer strategy.Close() + + // The first Token exchanges. The second uses the token, so it is due a + // refresh ahead of its expiry, which no caller makes: the token still + // works. + if _, err := strategy.Token(context.Background()); err != nil { + t.Fatal(err) + } + if token, err := strategy.Token(context.Background()); err != nil || jwtSubject(t, token) != "1" { + t.Fatalf("the second Token: %q, %v: a caller refreshed a token that still worked", jwtSubject(t, token), err) + } + select { + case <-refreshing: + case <-time.After(lifetime): + t.Fatalf("no refresh before the token expired: %d exchanges", requests.Load()) + } + deadline := time.Now().Add(5 * time.Second) + for { + token, err := strategy.Token(context.Background()) + if err != nil { + t.Fatal(err) + } + if jwtSubject(t, token) == "2" { + break + } + if time.Now().After(deadline) { + t.Fatalf("the refreshed token was never handed out: still %q", jwtSubject(t, token)) + } + time.Sleep(10 * time.Millisecond) + } +} + +// loopEnded reports whether a refresh loop has returned. +func loopEnded(done <-chan struct{}) bool { + select { + case <-done: + return true + default: + return false + } +} + +// Close ends the strategy's refresh loop before it returns. +func TestClosingAStrategyEndsItsRefreshLoop(t *testing.T) { + guestOrSkip(t) + server, _, _ := shortTokenServer(t, time.Hour, 0) + profile, err := Open(context.Background(), t.TempDir()) + if err != nil { + t.Fatal(err) + } + defer profile.Close() + strategy, err := profile.AccessKey(context.Background(), testCRN, "CSAKtestKeyId.testKeySecret", WithBaseURL(server.URL)) + if err != nil { + t.Fatal(err) + } + // Used twice, so the loop sleeps until the refresh ahead is due. + for range 2 { + if _, err := strategy.Token(context.Background()); err != nil { + t.Fatal(err) + } + } + done := strategy.loopDone + if err := strategy.Close(); err != nil { + t.Fatal(err) + } + if !loopEnded(done) { + t.Fatal("Close returned with the refresh loop still running") + } +} + +// Closing the profile ends the refresh loops of its strategies, which +// their own Close then finds ended. +func TestClosingTheProfileEndsItsStrategiesRefreshLoops(t *testing.T) { + _, store := profile(t) + server, _, _ := shortTokenServer(t, time.Hour, 0) + key, err := store.AccessKey(context.Background(), testCRN, "CSAKtestKeyId.testKeySecret", WithBaseURL(server.URL)) + if err != nil { + t.Fatal(err) + } + if _, err := key.Token(context.Background()); err != nil { + t.Fatal(err) + } + ws, err := store.WorkspaceStore(context.Background(), wsA) + if err != nil { + t.Fatal(err) + } + device, err := ws.DeviceSession(context.Background()) + if err != nil { + t.Fatal(err) + } + if err := store.Close(); err != nil { + t.Fatal(err) + } + for _, s := range []*Strategy{key, device} { + eventually(t, "the refresh loop ended", func() bool { return loopEnded(s.loopDone) }) + if err := s.Close(); err != nil { + t.Fatal(err) + } + } +} + +// A strategy its application never closes is still collected: its refresh +// loop holds it only weakly, and ends when it goes. +func TestAForgottenStrategysRefreshLoopEnds(t *testing.T) { + guestOrSkip(t) + server, _, _ := shortTokenServer(t, time.Hour, 0) + profile, err := Open(context.Background(), t.TempDir()) + if err != nil { + t.Fatal(err) + } + defer profile.Close() + done := func() <-chan struct{} { + strategy, err := profile.AccessKey(context.Background(), testCRN, "CSAKtestKeyId.testKeySecret", WithBaseURL(server.URL)) + if err != nil { + t.Fatal(err) + } + for range 2 { + if _, err := strategy.Token(context.Background()); err != nil { + t.Fatal(err) + } + } + return strategy.loopDone + }() + eventually(t, "the forgotten strategy's loop ended", func() bool { + runtime.GC() + return loopEnded(done) + }) +} + +// Every refresh loop a test started has ended once its strategies and +// profiles are closed. +func TestNoRefreshLoopOutlivesItsStrategies(t *testing.T) { + guestOrSkip(t) + server, _, _ := shortTokenServer(t, time.Hour, 0) + before := refreshLoops.Load() + profile, err := Open(context.Background(), t.TempDir()) + if err != nil { + t.Fatal(err) + } + var strategies []*Strategy + for range 4 { + s, err := profile.AccessKey(context.Background(), testCRN, "CSAKtestKeyId.testKeySecret", WithBaseURL(server.URL)) + if err != nil { + t.Fatal(err) + } + if _, err := s.Token(context.Background()); err != nil { + t.Fatal(err) + } + strategies = append(strategies, s) + } + if n := refreshLoops.Load() - before; n < 4 { + t.Fatalf("%d refresh loops started for 4 strategies", n) + } + for _, s := range strategies { + if err := s.Close(); err != nil { + t.Fatal(err) + } + } + if err := profile.Close(); err != nil { + t.Fatal(err) + } + eventually(t, "every refresh loop this test started ended", func() bool { return refreshLoops.Load() <= before }) +} + +// deviceSessionWith opens a profile whose workspace holds the session in +// auth.json, and that workspace's device session strategy against +// baseURL. +func deviceSessionWith(t *testing.T, authJSON, baseURL string, opts ...StrategyOption) *Strategy { + t.Helper() + guestOrSkip(t) + dir := t.TempDir() + workspaceDir := filepath.Join(dir, "workspaces", wsA) + if err := os.MkdirAll(workspaceDir, 0o700); err != nil { + t.Fatal(err) + } + write(t, filepath.Join(workspaceDir, "auth.json"), authJSON) + profile, err := Open(context.Background(), dir) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = profile.Close() }) + ws, err := profile.WorkspaceStore(context.Background(), wsA) + if err != nil { + t.Fatal(err) + } + strategy, err := ws.DeviceSession(context.Background(), append([]StrategyOption{WithBaseURL(baseURL)}, opts...)...) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = strategy.Close() }) + return strategy +} + +// While a device session's failed refresh backs off, a caller with an +// expired token gets that refresh's error again. The status is the same: +// a transport failure is still ErrTransport. +func TestADeviceSessionsReplayedRefreshErrorKeepsItsKind(t *testing.T) { + unreachable := httptest.NewServer(http.NotFoundHandler()) + unreachable.Close() + strategy := deviceSessionWith(t, fmt.Sprintf( + `{"access_token":"old","refresh_token":"refresh-1","token_type":"Bearer","expires_at":%d,"region":"ap-southeast-2.aws","client_id":"client-1"}`, + time.Now().Add(-time.Minute).Unix()), unreachable.URL) + + // The first call refreshes and fails; the calls after it, during the + // backoff, get that failure again. + for i := range 10 { + if _, err := strategy.Token(context.Background()); !errors.Is(err, ErrTransport) { + t.Fatalf("call %d: %v, want ErrTransport", i, err) + } + } +} + +// A device session token with no refresh token cannot be refreshed, so no +// refresh is ever due for it. The refresh loop never takes the auth.json +// lock for a refresh that cannot happen. +func TestADeviceSessionWithNoRefreshTokenIsNeverDueARefresh(t *testing.T) { + strategy := deviceSessionWith(t, fmt.Sprintf( + `{"access_token":"only","token_type":"Bearer","expires_at":%d,"region":"ap-southeast-2.aws","client_id":"client-1"}`, + time.Now().Add(time.Hour).Unix()), "https://cts.invalid/") + + if token, err := strategy.Token(context.Background()); err != nil || token != "only" { + t.Fatalf("Token: %q, %v", token, err) + } + if _, idle, err := strategy.nextRefresh(context.Background()); err != nil || !idle { + t.Fatalf("a refresh is due (idle %v, %v): the token has no refresh token", idle, err) + } +} + +// refreshingServer answers a device session's refresh with a fresh token +// and counts the refreshes. +func refreshingServer(t *testing.T) (*httptest.Server, *atomic.Int32) { + t.Helper() + var requests atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + requests.Add(1) + fmt.Fprint(w, `{"access_token":"fresh","token_type":"Bearer","expires_in":3600,"refresh_token":"refresh-2"}`) + })) + t.Cleanup(server.Close) + return server, &requests +} + +// deviceSessionExpiringIn is auth.json for a device session whose token +// expires in left. +func deviceSessionExpiringIn(left time.Duration) string { + return fmt.Sprintf( + `{"access_token":"old","refresh_token":"refresh-1","token_type":"Bearer","expires_at":%d,"region":"ap-southeast-2.aws","client_id":"client-1"}`, + time.Now().Add(left).Unix()) +} + +// A device session token with less than the refresh floor left is +// refreshed before the caller gets a token. Above the floor the caller +// gets the token at once. +func TestADeviceSessionTokenUnderTheFloorIsRefreshedFirst(t *testing.T) { + server, requests := refreshingServer(t) + under := deviceSessionWith(t, deviceSessionExpiringIn(15*time.Second), server.URL) + if token, err := under.Token(context.Background()); err != nil || token != "fresh" { + t.Fatalf("under the default floor: %q, %v, want the refreshed token", token, err) + } + + above := deviceSessionWith(t, deviceSessionExpiringIn(60*time.Second), server.URL) + before := requests.Load() + if token, err := above.Token(context.Background()); err != nil || token != "old" { + t.Fatalf("above the floor: %q, %v, want the current token", token, err) + } + if requests.Load() != before { + t.Fatal("a caller above the floor refreshed") + } +} + +// WithRefreshFloor sets the floor. Under a 5-second floor, a token with 15 +// seconds left is handed out at once. Under a 70-second floor, a token +// with 60 seconds left is refreshed first. A negative floor is ErrConfig. +func TestWithRefreshFloorSetsTheFloor(t *testing.T) { + server, _ := refreshingServer(t) + lower := deviceSessionWith(t, deviceSessionExpiringIn(15*time.Second), server.URL, WithRefreshFloor(5*time.Second)) + if token, err := lower.Token(context.Background()); err != nil || token != "old" { + t.Fatalf("under a 5 s floor: %q, %v, want the current token", token, err) + } + higher := deviceSessionWith(t, deviceSessionExpiringIn(60*time.Second), server.URL, WithRefreshFloor(70*time.Second)) + if token, err := higher.Token(context.Background()); err != nil || token != "fresh" { + t.Fatalf("under a 70 s floor: %q, %v, want the refreshed token", token, err) + } + + tokens, _, _ := shortTokenServer(t, time.Hour, 0) + profile, err := Open(context.Background(), t.TempDir()) + if err != nil { + t.Fatal(err) + } + defer profile.Close() + if _, err := profile.AccessKey(context.Background(), testCRN, "CSAKtestKeyId.testKeySecret", WithBaseURL(tokens.URL), WithRefreshFloor(-time.Second)); !errors.Is(err, ErrConfig) { + t.Fatalf("a negative floor: %v, want ErrConfig", err) + } +} + +// An access key's token with less than the floor left is refreshed by the +// call that gets it. +func TestAnAccessKeyTokenUnderTheFloorIsRefreshedFirst(t *testing.T) { + guestOrSkip(t) + server, _, _ := shortTokenServer(t, 60*time.Second, 0) + profile, err := Open(context.Background(), t.TempDir()) + if err != nil { + t.Fatal(err) + } + defer profile.Close() + strategy, err := profile.AccessKey(context.Background(), testCRN, "CSAKtestKeyId.testKeySecret", WithBaseURL(server.URL), WithRefreshFloor(70*time.Second)) + if err != nil { + t.Fatal(err) + } + defer strategy.Close() + if _, err := strategy.Token(context.Background()); err != nil { + t.Fatal(err) + } + if token, err := strategy.Token(context.Background()); err != nil || jwtSubject(t, token) != "2" { + t.Fatalf("the second Token: %q, %v, want the refreshed token", jwtSubject(t, token), err) + } +} + +func TestRefreshFloorSecsRoundsUp(t *testing.T) { + for _, c := range []struct { + floor time.Duration + want uint64 + }{{0, 0}, {time.Millisecond, 1}, {30 * time.Second, 30}, {30*time.Second + 1, 31}, {math.MaxInt64, uint64(math.MaxInt64/time.Second) + 1}} { + floor := c.floor + got, err := strategyOptions{refreshFloor: &floor}.refreshFloorSecs() + if err != nil || got == nil || *got != c.want { + t.Errorf("%v: %v, %v, want %d", c.floor, got, err, c.want) + } + } +} diff --git a/languages/golang/auth/doc.go b/languages/golang/auth/doc.go index 395c99088a..4167226a93 100644 --- a/languages/golang/auth/doc.go +++ b/languages/golang/auth/doc.go @@ -47,6 +47,24 @@ // token still works gets it at once, and one with no usable token waits // for that exchange rather than starting a second. // +// An access-key or device-session strategy refreshes its token in the +// background, from a goroutine of its own, between 90 seconds and two +// minutes before the token expires, so no call waits for the token service +// while its token has more than 30 seconds left. A call whose token has +// less left refreshes it, or waits for the refresh already running; +// [WithRefreshFloor] sets that refresh floor. It refreshes only while the +// strategy is in use: a strategy no call has used since its last refresh +// is left alone. +// After a refresh fails, the next attempt waits about a second, doubling +// with each failure up to 30 seconds. Meanwhile a call whose token still works gets it, and +// one whose token has expired fails at once with the failed refresh's +// error rather than asking the service itself. [Strategy.Close] and +// [ProfileStore.Close] stop the goroutine, as does the strategy being +// garbage collected. An OIDC strategy has none: its [OIDCProvider] is asked +// for a JWT on every call, and a timer cannot ask for one. The refresh +// floor does not apply to it: a call inside the 90 seconds before expiry +// refreshes. +// // A call whose context ends, [Strategy.Token] included, fails with the // context's error and leaves the store and its strategies open: a request // cancelled while its token is exchanged or refreshed does not stop the diff --git a/languages/golang/auth/guest.go b/languages/golang/auth/guest.go index fea766ee4d..c843ad34f2 100644 --- a/languages/golang/auth/guest.go +++ b/languages/golang/auth/guest.go @@ -73,6 +73,7 @@ type instance struct { listWorkspaces, workspaceDir, lockPath api.Function secretKey, token, hasToken, sessionCRN, deviceIdentity api.Function authNew, authValidateCRN, authToken, authRefresh, authFree api.Function + authNextRefresh, authRefreshAhead api.Function // The step exports of the token operations (see step.go). authIO, authResume, authAbort, authRunnable api.Function } @@ -174,6 +175,8 @@ func newInstance(ctx context.Context, wasm []byte, hostDir string, policy guest. "sa_auth_validate_crn": &inst.authValidateCRN, "sa_auth_token": &inst.authToken, "sa_auth_refresh": &inst.authRefresh, + "sa_auth_next_refresh": &inst.authNextRefresh, + "sa_auth_refresh_ahead": &inst.authRefreshAhead, "sa_auth_free": &inst.authFree, "sa_auth_io": &inst.authIO, "sa_auth_resume": &inst.authResume, diff --git a/languages/golang/auth/guest/src/abi.rs b/languages/golang/auth/guest/src/abi.rs index 043aa4e3ce..36487dfe4f 100644 --- a/languages/golang/auth/guest/src/abi.rs +++ b/languages/golang/auth/guest/src/abi.rs @@ -283,10 +283,15 @@ pub unsafe extern "C" fn sa_auth_validate_crn(ptr: *const u8, len: u32) -> u64 { /// ``` /// /// `refresh_required` is true once the token is inside stack-auth's -/// refresh window, while it still works: the host refreshes it with +/// refresh window, while it still works, unless the strategy was created +/// with `refresh_ahead` (the host refreshes ahead of expiry): the host refreshes it with /// [`sa_auth_refresh`] under its lock, and may hand the token to other /// callers until that refresh is done. A token past its expiry, which -/// nothing can use, is `STATUS_AUTH_REFRESH_REQUIRED` instead. The frame +/// nothing can use, is `STATUS_AUTH_REFRESH_REQUIRED` instead, or, while +/// a failed refresh backs off, that refresh's error. A strategy created +/// with `refresh_ahead` reports a token under its refresh floor the same +/// way, unless a failed refresh is backing off. Every caller then waits +/// for the refresh. The frame /// carries the token: the host releases it with `se_dealloc`, which wipes /// it. /// # Safety @@ -306,6 +311,31 @@ pub unsafe extern "C" fn sa_auth_refresh(ptr: *const u8, len: u32) -> u64 { start1(ptr, len, auth::refresh) } +/// When a strategy's next refresh ahead of expiry is due, as a step +/// operation: empty output while it is idle (nothing is due until a call +/// uses the token again), else the time in decimal seconds since the Unix +/// epoch. The host calls [`sa_auth_refresh_ahead`] when the time comes; a +/// strategy created with `refresh_ahead` leaves that to it, so a call for +/// a token that still works never refreshes it. See +/// [`auth::next_refresh`]. +/// # Safety +/// The input pair is validated against guest linear memory. +#[no_mangle] +pub unsafe extern "C" fn sa_auth_next_refresh(ptr: *const u8, len: u32) -> u64 { + start1(ptr, len, auth::next_refresh) +} + +/// Refresh a strategy's token ahead of its expiry if a refresh is due, as a +/// step operation with empty output. For a device session the Go host must +/// hold the workspace's auth.json lock across every step, as for +/// [`sa_auth_refresh`]. See [`auth::refresh_ahead`]. +/// # Safety +/// The input pair is validated against guest linear memory. +#[no_mangle] +pub unsafe extern "C" fn sa_auth_refresh_ahead(ptr: *const u8, len: u32) -> u64 { + start1(ptr, len, auth::refresh_ahead) +} + /// The step a paused token export left: its handle, whether it is parked, /// and the requests it waits on, as a packed buffer ([`crate::io`]), handed /// over once: a second call returns zero, as does a call with no step diff --git a/languages/golang/auth/guest/src/auth.rs b/languages/golang/auth/guest/src/auth.rs index 0f2fbbc7ae..4347dec880 100644 --- a/languages/golang/auth/guest/src/auth.rs +++ b/languages/golang/auth/guest/src/auth.rs @@ -24,8 +24,8 @@ use std::rc::Rc; use serde::Deserialize; use stack_auth::Crn; use stack_auth::{ - AccessKey, AccessKeyStrategy, AuthStrategy, DeviceSessionStrategy, OidcFederationStrategy, - Token, + AccessKey, AccessKeyStrategy, AuthStrategy, DeviceSessionStrategy, NextRefresh, + OidcFederationStrategy, RefreshDriver, RefreshSchedule, Token, REFRESH_FLOOR_SECS, }; use stack_profile::ProfileStore; use zeroize::Zeroizing; @@ -45,6 +45,16 @@ enum Config { crn: String, access_key: String, base_url: Option, + /// The host refreshes ahead of expiry ([`next_refresh`], + /// [`refresh_ahead`]), so a call with a token that still works + /// never does. Absent, calls refresh in the 90 seconds before + /// expiry. + #[serde(default)] + refresh_ahead: bool, + /// The refresh floor in seconds, while the host refreshes ahead. A + /// call whose token has less left refreshes it first. Absent, it is + /// stack-auth's default. See `auth.WithRefreshFloor`. + refresh_floor_secs: Option, }, Oidc { crn: String, @@ -57,11 +67,21 @@ enum Config { DeviceSession { workspace_dir: String, base_url: Option, + /// As for an access key. + #[serde(default)] + refresh_ahead: bool, + /// As for an access key. + refresh_floor_secs: Option, }, } enum Strategy { - AccessKey(AccessKeyStrategy), + AccessKey { + strategy: AccessKeyStrategy, + /// Held when the host refreshes ahead of expiry: a call with a + /// token that still works then never does. + _driver: Option, + }, Oidc(OidcFederationStrategy), // A device session is rebuilt for refresh only after Go has acquired the // cross-process lock. A fresh token can be read without the lock; keeping @@ -69,9 +89,44 @@ enum Strategy { DeviceSession { workspace_dir: String, base_url: Option, + /// stack-auth's refresh rule for the token in auth.json. Only the + /// plan is kept, never the token. + plan: RefCell, }, } +/// A device session's refresh plan, and the last refresh's error, replayed +/// to a caller whose token has expired while the refresh backs off. +#[derive(Default)] +struct DevicePlan { + schedule: RefreshSchedule, + /// Whether the host refreshes ahead of expiry. + driven: bool, + /// The refresh floor in seconds, while the host refreshes ahead. + floor: u64, + /// The error itself, so a replay reports the same status and detail. + last_error: Option, +} + +impl DevicePlan { + /// Plan for the token in auth.json at `now`. A token with no refresh + /// token cannot be refreshed, so no refresh is due for it. + fn observe(&mut self, token: &Token, now: u64) { + self.schedule.observe(token, now); + if token.refresh_token().is_none() { + self.schedule.cannot_refresh(); + } + } +} + +/// The time now, in seconds since the Unix epoch: the host's clock. +fn now_secs() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or_default() +} + thread_local! { /// Each strategy, shared with the operations paused on it: freeing one /// removes it here, and it is dropped, with its access key and cached @@ -110,6 +165,8 @@ pub fn create(config: &[u8]) -> Result, u32> { crn, access_key, base_url, + refresh_ahead, + refresh_floor_secs, } => { let access_key = Zeroizing::new(access_key); let crn: Crn = crn.parse().map_err(|e| fail_auth(&AuthError::from(e)))?; @@ -120,7 +177,14 @@ pub fn create(config: &[u8]) -> Result, u32> { if let Some(url) = parse_base_url(base_url)? { builder = builder.base_url(url); } - Strategy::AccessKey(builder.build().map_err(|e| fail_auth(&e))?) + if let Some(secs) = refresh_floor_secs { + builder = builder.refresh_floor(std::time::Duration::from_secs(secs)); + } + let strategy = builder.build().map_err(|e| fail_auth(&e))?; + Strategy::AccessKey { + _driver: refresh_ahead.then(|| strategy.drive_refresh()), + strategy, + } } Config::Oidc { crn, @@ -142,6 +206,8 @@ pub fn create(config: &[u8]) -> Result, u32> { Config::DeviceSession { workspace_dir, base_url, + refresh_ahead, + refresh_floor_secs, } => { if workspace_dir.is_empty() { return Err(malformed("the strategy config's workspace_dir is empty")); @@ -149,6 +215,11 @@ pub fn create(config: &[u8]) -> Result, u32> { Strategy::DeviceSession { workspace_dir, base_url: parse_base_url(base_url)?, + plan: RefCell::new(DevicePlan { + driven: refresh_ahead, + floor: refresh_floor_secs.unwrap_or(REFRESH_FLOOR_SECS), + ..DevicePlan::default() + }), } } }; @@ -185,7 +256,7 @@ pub fn token(handle: &[u8]) -> Result { let strategy = strategy(handle)?; Ok(Box::pin(async move { match &*strategy { - Strategy::AccessKey(strategy) => strategy + Strategy::AccessKey { strategy, .. } => strategy .get_token() .await .map(|token| token.as_str().as_bytes().to_vec()) @@ -198,14 +269,52 @@ pub fn token(handle: &[u8]) -> Result { Strategy::DeviceSession { workspace_dir, base_url, - } => cached_device_token(workspace_dir, base_url), + plan, + } => cached_device_token(workspace_dir, base_url, plan), } })) } -/// A fresh token needs only a profile read. The 90-second refresh window is -/// decided by stack-auth's Token, so Go does not duplicate that rule. -fn cached_device_token(workspace_dir: &str, base_url: &Option) -> Result, u32> { +/// A fresh token needs only a profile read. The 90-second refresh window and +/// the backoff after a failed refresh are decided by stack-auth, so Go does +/// not duplicate those rules. +fn cached_device_token( + workspace_dir: &str, + base_url: &Option, + plan: &RefCell, +) -> Result, u32> { + let token = load_device_token(workspace_dir, base_url)?; + let now = now_secs(); + let mut plan = plan.borrow_mut(); + plan.observe(&token, now); + let _ = plan.schedule.used(); + // Past its expiry nothing can use the token. While a failed refresh + // backs off, the caller gets that refresh's error at once rather than + // refreshing again itself. + if !token.is_usable() { + if plan.schedule.backing_off(now) { + if let Some(error) = &plan.last_error { + return Err(fail_auth(error)); + } + } + return Err(STATUS_AUTH_REFRESH_REQUIRED); + } + // Inside the refresh window the token still works. With no host + // refreshing ahead, it goes to the host with the flag set, so one + // caller refreshes while the others keep using it. With a host + // refreshing ahead, a token under the floor is refreshed before any + // caller gets it, as an expired one is. The exception is a failed + // refresh that is backing off. + let left = token.expires_at().saturating_sub(now); + if plan.driven && token.is_expired() && left < plan.floor && !plan.schedule.backing_off(now) { + return Err(STATUS_AUTH_REFRESH_REQUIRED); + } + device_token_frame(&token, token.is_expired() && !plan.driven) +} + +/// The device session's token in auth.json, checked as every read checks +/// it. +fn load_device_token(workspace_dir: &str, base_url: &Option) -> Result { let token: Token = ProfileStore::new(workspace_dir) .load_profile() .map_err(|e| fail_profile(&e))?; @@ -215,13 +324,7 @@ fn cached_device_token(workspace_dir: &str, base_url: &Option) -> Resu if base_url.is_none() { let _ = token.issuer().map_err(|e| fail_auth(&e))?; } - // Inside the refresh window the token still works: it goes to the - // host with the flag set, so callers keep using it while one of them - // refreshes. Past its expiry nothing can use it. - if token.is_expired() && !token.is_usable() { - return Err(STATUS_AUTH_REFRESH_REQUIRED); - } - device_token_frame(&token, token.is_expired()) + Ok(token) } /// A device session's token read, as the frame `sa_auth_token` returns: @@ -250,10 +353,35 @@ fn device_token_frame(token: &Token, refresh_required: bool) -> Result, /// saved before the operation finishes. pub fn refresh(handle: &[u8]) -> Result { let strategy = strategy(handle)?; + let session = device_session(&strategy)?; + Ok(Box::pin(async move { + let Strategy::DeviceSession { + workspace_dir, + plan, + .. + } = &*strategy + else { + unreachable!("device_session accepted it"); + }; + plan.borrow_mut().schedule.attempt_started(); + match session.get_token().await { + Ok(token) => { + device_refreshed(workspace_dir, plan); + Ok(token.as_str().as_bytes().to_vec()) + } + Err(error) => Err(device_refresh_failed(plan, error)), + } + })) +} + +/// The device session in auth.json, rebuilt so it re-reads the token +/// another process may have rotated while the host waited for its lock. +fn device_session(strategy: &Strategy) -> Result { let Strategy::DeviceSession { workspace_dir, base_url, - } = &*strategy + .. + } = strategy else { return Err(out_of_order("only a device session strategy refreshes")); }; @@ -263,10 +391,113 @@ pub fn refresh(handle: &[u8]) -> Result { if let Some(url) = base_url { builder = builder.base_url(url.clone()); } - let session = builder.build().map_err(|e| fail_auth(&e))?; + builder.build().map_err(|e| fail_auth(&e)) +} + +/// Record a device session refresh that succeeded: plan for the token it +/// saved. +fn device_refreshed(workspace_dir: &str, plan: &RefCell) { + let mut plan = plan.borrow_mut(); + plan.last_error = None; + if let Ok(token) = ProfileStore::new(workspace_dir).load_profile::() { + plan.observe(&token, now_secs()); + } +} + +/// Record a device session refresh that failed: start or extend the +/// backoff, and keep the error to report again while it lasts. Returns +/// the error's status. +fn device_refresh_failed(plan: &RefCell, error: AuthError) -> u32 { + let status = fail_auth(&error); + let mut plan = plan.borrow_mut(); + plan.schedule.refresh_failed(&error, now_secs()); + plan.last_error = Some(error); + status +} + +/// When the strategy's next refresh ahead of expiry is due, as a step +/// operation: empty output while nothing is due until the token is used +/// again, else the time, in decimal seconds since the Unix epoch. The host +/// calls [`refresh_ahead`] when the time comes. An OIDC strategy is always +/// idle: its provider is asked for a JWT on each call, which a timer +/// cannot do. +pub fn next_refresh(handle: &[u8]) -> Result { + let strategy = strategy(handle)?; + Ok(Box::pin(async move { + let next = match &*strategy { + Strategy::AccessKey { strategy, .. } => strategy.next_refresh().await, + Strategy::Oidc(_) => NextRefresh::Idle, + Strategy::DeviceSession { + workspace_dir, + base_url, + plan, + } => { + let mut plan = plan.borrow_mut(); + // No readable token is nothing to refresh ahead: the next + // call reports why. + match load_device_token(workspace_dir, base_url) { + Ok(token) => { + plan.observe(&token, now_secs()); + plan.schedule.next() + } + Err(_) => { + stack_guest_abi::last_error::clear(); + NextRefresh::Idle + } + } + } + }; + Ok(match next { + NextRefresh::Idle => Vec::new(), + NextRefresh::At(at) => at.to_string().into_bytes(), + }) + })) +} + +/// Refresh ahead of expiry if a refresh is due, as a step operation, with +/// empty output. Nothing happens when the plan has moved on since the host +/// asked: a caller refreshed meanwhile, or another process rotated a device +/// session's token. For a device session the host holds the workspace's +/// auth.json lock across every step, as for [`refresh`]. +pub fn refresh_ahead(handle: &[u8]) -> Result { + let strategy = strategy(handle)?; + let session = match &*strategy { + Strategy::DeviceSession { .. } => Some(device_session(&strategy)?), + _ => None, + }; Ok(Box::pin(async move { - let token = session.get_token().await.map_err(|e| fail_auth(&e))?; - Ok(token.as_str().as_bytes().to_vec()) + let due = |next: NextRefresh| matches!(next, NextRefresh::At(at) if at <= now_secs()); + match &*strategy { + Strategy::AccessKey { strategy, .. } => { + if due(strategy.next_refresh().await) { + strategy.refresh_now().await.map_err(|e| fail_auth(&e))?; + } + } + Strategy::Oidc(_) => {} + Strategy::DeviceSession { + workspace_dir, + base_url, + plan, + } => { + let token = load_device_token(workspace_dir, base_url)?; + let next = { + let mut plan = plan.borrow_mut(); + plan.observe(&token, now_secs()); + plan.schedule.next() + }; + if due(next) { + let Some(session) = session else { + unreachable!("built for a device session"); + }; + plan.borrow_mut().schedule.attempt_started(); + match session.refresh_now().await { + Ok(()) => device_refreshed(workspace_dir, plan), + Err(error) => return Err(device_refresh_failed(plan, error)), + } + } + } + } + Ok(Vec::new()) })) } diff --git a/languages/golang/auth/refresh_test.go b/languages/golang/auth/refresh_test.go index 05cc48c303..9feac32cdb 100644 --- a/languages/golang/auth/refresh_test.go +++ b/languages/golang/auth/refresh_test.go @@ -20,35 +20,6 @@ import ( // token service, which can take a second or more, must not hold up the // others while they have a token that still works (#1958). -// slowRefreshServer answers the first access-key exchange at once with a -// token inside the guest's 90-second refresh window (so the next Token -// refreshes it), named "old". Every later exchange is announced on -// refreshing and answered after delay, with a token named "new" that lasts -// an hour. -func slowRefreshServer(t *testing.T, delay time.Duration) (server *httptest.Server, requests *atomic.Int32, refreshing chan struct{}) { - t.Helper() - requests = new(atomic.Int32) - refreshing = make(chan struct{}, 16) - var issuer string - server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - _, _ = io.Copy(io.Discard, r.Body) - if requests.Add(1) == 1 { - fmt.Fprintf(w, `{"accessToken":%q,"expiry":%d}`, testJWTFor(t, issuer, "old"), time.Now().Add(60*time.Second).Unix()) - return - } - refreshing <- struct{}{} - select { - case <-time.After(delay): - case <-r.Context().Done(): - return - } - fmt.Fprintf(w, `{"accessToken":%q,"expiry":%d}`, testJWTFor(t, issuer, "new"), time.Now().Add(time.Hour).Unix()) - })) - issuer = server.URL - t.Cleanup(server.Close) - return server, requests, refreshing -} - // subject is a test token's sub claim, its name here, or "" for anything // else. Safe off the test's goroutine, unlike jwtSubject. func subject(token string) string { @@ -66,35 +37,33 @@ func subject(token string) string { return claims.Sub } -// While one caller refreshes a token that is still valid, every other +// While a token that is still valid is refreshed in the background, every // caller gets that token at once, rather than waiting for the token // service to answer. func TestCallersDoNotWaitBehindARefreshOfAValidToken(t *testing.T) { guestOrSkip(t) const delay = time.Second - server, requests, refreshing := slowRefreshServer(t, delay) + server, requests, refreshing := shortTokenServer(t, 4*time.Second, delay) profile, err := Open(context.Background(), t.TempDir()) if err != nil { t.Fatal(err) } defer profile.Close() - strategy, err := profile.AccessKey(context.Background(), testCRN, "CSAKtestKeyId.testKeySecret", WithBaseURL(server.URL)) + // The floor is off. The token lasts less than the default floor, and + // this test is about callers above it. + strategy, err := profile.AccessKey(context.Background(), testCRN, "CSAKtestKeyId.testKeySecret", WithBaseURL(server.URL), WithRefreshFloor(0)) if err != nil { t.Fatal(err) } defer strategy.Close() - if token, err := strategy.Token(context.Background()); err != nil || jwtSubject(t, token) != "old" { - t.Fatalf("the first Token: %q, %v", token, err) - } - refreshed := make(chan string, 1) - go func() { - token, err := strategy.Token(context.Background()) - if err != nil { - t.Errorf("the refreshing Token: %v", err) + // The first Token exchanges; the second uses the token, so its + // refresh ahead of expiry is due half way through its life. + for range 2 { + if token, err := strategy.Token(context.Background()); err != nil || jwtSubject(t, token) != "1" { + t.Fatalf("Token: %q, %v", token, err) } - refreshed <- token - }() + } select { case <-refreshing: case <-time.After(5 * time.Second): @@ -110,22 +79,19 @@ func TestCallersDoNotWaitBehindARefreshOfAValidToken(t *testing.T) { if waited := time.Since(start); waited > delay/4 { t.Errorf("caller %d waited %v behind the refresh", i, waited) } - if err != nil || subject(token) != "old" { - t.Errorf("caller %d got token %q, %v, want the current token, %q", i, subject(token), err, "old") + if err != nil || subject(token) != "1" { + t.Errorf("caller %d got token %q, %v, want the current token, %q", i, subject(token), err, "1") } }) } wg.Wait() - - if token := <-refreshed; jwtSubject(t, token) != "new" { - t.Fatalf("the refreshing Token got %q, want the new token", jwtSubject(t, token)) - } - if token, err := strategy.Token(context.Background()); err != nil || jwtSubject(t, token) != "new" { - t.Fatalf("a Token after the refresh: %q, %v", token, err) - } if n := requests.Load(); n != 2 { t.Fatalf("%d exchanges, want 2: the first, and one refresh", n) } + eventually(t, "the refreshed token", func() bool { + token, err := strategy.Token(context.Background()) + return err == nil && subject(token) == "2" + }) } // heldServer answers access-key exchanges with an hour-long token named by @@ -207,7 +173,13 @@ func TestManyCallersWithNoTokenYetShareOneExchange(t *testing.T) { t.Fatalf("%d exchanges, want 1", n) } wantProfileOpen(t, profile) - wantNoneOpen(t, profile) + // The strategy's refresh loop may hold an operation open for a moment, + // asking when the next refresh is due. + eventually(t, "no operation open", func() bool { + profile.root.mu.Lock() + defer profile.root.mu.Unlock() + return profile.root.open == 0 + }) } // A caller waiting for another's exchange that gives up returns at its diff --git a/languages/golang/auth/steps_test.go b/languages/golang/auth/steps_test.go index 344f34668e..21ed6199c5 100644 --- a/languages/golang/auth/steps_test.go +++ b/languages/golang/auth/steps_test.go @@ -128,8 +128,8 @@ func TestClosingTheProfileDuringARefreshKeepsTheRotatedRefreshToken(t *testing.T } } -// F3: a device session's token inside the 90-second refresh window still -// works. While one caller refreshes it, every other caller gets it at +// A device session's token inside the 90-second refresh window still +// works. While it is refreshed in the background, every caller gets it at // once, as for the other strategies. func TestDeviceSessionCallersDoNotWaitBehindARefreshOfAValidToken(t *testing.T) { guestOrSkip(t) @@ -139,9 +139,12 @@ func TestDeviceSessionCallersDoNotWaitBehindARefreshOfAValidToken(t *testing.T) if err := os.MkdirAll(workspaceDir, 0o700); err != nil { t.Fatal(err) } - write(t, filepath.Join(workspaceDir, "auth.json"), fmt.Sprintf( - `{"access_token":"old","refresh_token":"refresh-1","token_type":"Bearer","expires_at":%d,"region":"ap-southeast-2.aws","client_id":"client-1"}`, - time.Now().Add(60*time.Second).Unix())) + session := func() { + write(t, filepath.Join(workspaceDir, "auth.json"), fmt.Sprintf( + `{"access_token":"old","refresh_token":"refresh-1","token_type":"Bearer","expires_at":%d,"region":"ap-southeast-2.aws","client_id":"client-1"}`, + time.Now().Add(4*time.Second).Unix())) + } + session() refreshing := make(chan struct{}, 16) var requests atomic.Int32 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -161,20 +164,22 @@ func TestDeviceSessionCallersDoNotWaitBehindARefreshOfAValidToken(t *testing.T) if err != nil { t.Fatal(err) } - strategy, err := ws.DeviceSession(context.Background(), WithBaseURL(server.URL)) + // The floor is off. The token lasts less than the default floor, and + // this test is about callers above it. + strategy, err := ws.DeviceSession(context.Background(), WithBaseURL(server.URL), WithRefreshFloor(0)) if err != nil { t.Fatal(err) } defer strategy.Close() - refreshed := make(chan string, 1) - go func() { - token, err := strategy.Token(context.Background()) - if err != nil { - t.Errorf("the refreshing Token: %v", err) - } - refreshed <- token - }() + // The first Token uses the token, so its refresh ahead of expiry is due + // half way through its life, and no caller makes it. The session is + // written again now: opening the profile can take seconds under the + // race detector, longer than the token lasts. + session() + if token, err := strategy.Token(context.Background()); err != nil || token != "old" { + t.Fatalf("the first Token: %q, %v", token, err) + } select { case <-refreshing: case <-time.After(5 * time.Second): @@ -195,9 +200,10 @@ func TestDeviceSessionCallersDoNotWaitBehindARefreshOfAValidToken(t *testing.T) }) } wg.Wait() - if token := <-refreshed; token != "fresh" { - t.Fatalf("the refreshing Token got %q, want the refreshed one", token) - } + eventually(t, "the refreshed token", func() bool { + token, err := strategy.Token(context.Background()) + return err == nil && token == "fresh" + }) if n := requests.Load(); n != 1 { t.Fatalf("%d refresh requests, want 1", n) } diff --git a/languages/golang/auth/store.go b/languages/golang/auth/store.go index 29e71bb286..f5b85c46cf 100644 --- a/languages/golang/auth/store.go +++ b/languages/golang/auth/store.go @@ -103,6 +103,9 @@ type root struct { // ops counts the token operations running (run), each from its start // to its last step. Close waits for them. ops sync.WaitGroup + // done is closed by Close, with closing set: the strategies' refresh + // loops end. + done chan struct{} } // Resolve opens the profile directory the Rust crate would: CS_CONFIG_PATH @@ -170,6 +173,7 @@ func open(ctx context.Context, hostDir string, opts []Option) (*ProfileStore, er r := &root{ inst: inst, hostDir: hostDir, stuck: guest.StuckAfter, freed: make(chan struct{}), parked: make(map[uint64]chan struct{}), + done: make(chan struct{}), } // The cleanup takes the instance, not the root: a cleanup whose // argument reaches its object keeps that object alive forever. @@ -242,6 +246,7 @@ func (s *ProfileStore) Close() error { } if !r.closing { r.closing = true + close(r.done) r.cleanup.Stop() // A parked token operation wakes and aborts, rather than waiting // for an exchange that may not finish before the profile closes. diff --git a/languages/golang/auth/strategy.go b/languages/golang/auth/strategy.go index e94d005712..4a789b0332 100644 --- a/languages/golang/auth/strategy.go +++ b/languages/golang/auth/strategy.go @@ -8,6 +8,7 @@ import ( "os" "strconv" "sync" + "time" "github.com/cipherstash/stack/languages/golang/internal/guest" "github.com/cipherstash/vitaminc/bindings/go/vcffi" @@ -21,6 +22,7 @@ type StrategyOption func(*strategyOptions) type strategyOptions struct { baseURL string cacheCapacity *uint32 + refreshFloor *time.Duration } // WithBaseURL overrides CTS service discovery for one strategy. @@ -38,6 +40,42 @@ func WithCacheCapacity(n uint32) StrategyOption { return func(o *strategyOptions) { o.cacheCapacity = &n } } +// WithRefreshFloor sets the refresh floor of an access-key or +// device-session strategy, 30 seconds unless set. When a Token call's +// token has less than the floor left, the call refreshes it, or waits for +// the refresh already running. So it does not get back a token that may +// expire before the request using it is sent. Above the floor, Token +// returns the token at once while the strategy's goroutine refreshes it. +// +// The floor is whole seconds, rounded up. Zero turns it off: Token then +// never waits while the token still works. A floor longer than the +// 90-second refresh window acts as the window. A negative floor is +// [ErrConfig]. +// +// For short-lived tokens, keep the floor at or below half the token's +// lifetime: such a token's background refresh is due half way through its +// life. [ProfileStore.OIDC] does not read the floor. An OIDC strategy +// refreshes on the calls inside the refresh window. +func WithRefreshFloor(floor time.Duration) StrategyOption { + return func(o *strategyOptions) { o.refreshFloor = &floor } +} + +// refreshFloorSecs is the floor the guest is given: nil for its default, +// else whole seconds, rounded up. +func (o strategyOptions) refreshFloorSecs() (*uint64, error) { + if o.refreshFloor == nil { + return nil, nil + } + if *o.refreshFloor < 0 { + return nil, ErrConfig + } + secs := uint64(*o.refreshFloor / time.Second) + if *o.refreshFloor%time.Second != 0 { + secs++ + } + return &secs, nil +} + func strategyConfig(opts []StrategyOption) strategyOptions { var o strategyOptions for _, opt := range opts { @@ -77,6 +115,12 @@ type Strategy struct { // refreshing takes a device session's refreshes in this process one at // a time, before the cross-process lock does across processes. refreshing guest.Lock + // The refresh loop of an access-key or device-session strategy (see + // background.go): stopLoop ends it, loopDone is closed when it has, + // and used wakes it when it is idle. All nil for OIDC. + stopLoop context.CancelFunc + loopDone chan struct{} + used chan struct{} } func (s *ProfileStore) newStrategy(ctx context.Context, config any, device bool) (*Strategy, error) { @@ -102,12 +146,23 @@ func (s *ProfileStore) AccessKey(ctx context.Context, crn, key string, opts ...S return nil, ErrConfig } o := strategyConfig(opts) - return s.newStrategy(ctx, struct { - Kind string `json:"kind"` - CRN string `json:"crn"` - Key string `json:"access_key"` - BaseURL string `json:"base_url,omitempty"` - }{"access_key", crn, key, o.baseURL}, false) + floor, err := o.refreshFloorSecs() + if err != nil { + return nil, err + } + strategy, err := s.newStrategy(ctx, struct { + Kind string `json:"kind"` + CRN string `json:"crn"` + Key string `json:"access_key"` + BaseURL string `json:"base_url,omitempty"` + RefreshAhead bool `json:"refresh_ahead"` + RefreshFloor *uint64 `json:"refresh_floor_secs,omitempty"` + }{"access_key", crn, key, o.baseURL, true, floor}, false) + if err != nil { + return nil, err + } + strategy.startRefreshLoop() + return strategy, nil } // OIDC constructs stack-auth's federation strategy. provider is called on @@ -216,11 +271,22 @@ func (s *ProfileStore) DeviceSession(ctx context.Context, opts ...StrategyOption return nil, ErrConfig } o := strategyConfig(opts) - return s.newStrategy(ctx, struct { - Kind string `json:"kind"` - Dir string `json:"workspace_dir"` - BaseURL string `json:"base_url,omitempty"` - }{"device_session", s.dir, o.baseURL}, true) + floor, err := o.refreshFloorSecs() + if err != nil { + return nil, err + } + strategy, err := s.newStrategy(ctx, struct { + Kind string `json:"kind"` + Dir string `json:"workspace_dir"` + BaseURL string `json:"base_url,omitempty"` + RefreshAhead bool `json:"refresh_ahead"` + RefreshFloor *uint64 `json:"refresh_floor_secs,omitempty"` + }{"device_session", s.dir, o.baseURL, true, floor}, true) + if err != nil { + return nil, err + } + strategy.startRefreshLoop() + return strategy, nil } // Auto follows stack-auth's detection order against the Go host's @@ -317,6 +383,12 @@ func (s *Strategy) Token(ctx context.Context) (string, error) { ctx, status := withAuthHTTPStatus(ctx) r.token, r.err = s.token(ctx) r.err = status.wrap(r.err) + if s.used != nil && r.err == nil { + // The token was used: its refresh ahead of expiry is due again. + // Only after a success, when no exchange holds the strategy, so + // the loop's question does not wait behind one. + s.signalUse() + } panicked.raise(nil) }() select { @@ -371,7 +443,8 @@ func (s *Strategy) token(ctx context.Context) (string, error) { out, err := run(ctx, func(i *instance) api.Function { return i.authToken }) switch { case errors.Is(err, guest.ErrAuthRefreshRequired): - // Past its expiry: every caller waits for the refresh. + // Past its expiry, or under the refresh floor: every caller waits + // for the refresh. if err := s.refreshing.Acquire(ctx); err != nil { return "", err } @@ -390,24 +463,31 @@ func (s *Strategy) token(ctx context.Context) (string, error) { } } defer s.refreshing.Unlock() - path, err := s.store.LockPath(ctx, "auth.json") - if err != nil { - return "", err - } - // The lock is held across every step of the refresh. A refresh that - // waited here behind another finds the token that one saved: the - // guest re-reads auth.json before it asks the service. + // A refresh that waited for the lock behind another finds the token + // that one saved: the guest re-reads auth.json before it asks the + // service. var token string - err = withRefreshLock(ctx, path, func() error { + err = s.refreshDeviceSession(ctx, func(ctx context.Context) error { var err error - // The one request that rotates a credential: it runs on after its - // caller leaves (see refreshGrace). - token, err = text(run(withRefresh(ctx), func(i *instance) api.Function { return i.authRefresh })) + token, err = text(run(ctx, func(i *instance) api.Function { return i.authRefresh })) return err }) return token, err } +// refreshDeviceSession runs refresh, a device session's refresh through +// the guest, holding the workspace's auth.json lock across every step of +// it. The caller holds s.refreshing. The context given to refresh marks +// the one request that rotates a credential. That request runs on after +// its caller leaves (see refreshGrace). +func (s *Strategy) refreshDeviceSession(ctx context.Context, refresh func(context.Context) error) error { + path, err := s.store.LockPath(ctx, "auth.json") + if err != nil { + return err + } + return withRefreshLock(ctx, path, func() error { return refresh(withRefresh(ctx)) }) +} + // decodeDeviceToken reads a device session's token read: // `{"access_token": text, "refresh_required": bool}`. The error never // quotes the frame: it carries the token. @@ -473,6 +553,12 @@ func (s *Strategy) Close() error { s.closeDone = make(chan struct{}) s.mu.Unlock() defer close(s.closeDone) + if s.stopLoop != nil { + // A device session refresh the loop has sent runs on for the + // grace, as a cancelled Token's does. + s.stopLoop() + <-s.loopDone + } s.inflight.Wait() if s.providerID != 0 { s.store.root.inst.transport.unregister(s.providerID) diff --git a/languages/typescript/examples/prisma/docker-compose.yml b/languages/typescript/examples/prisma/docker-compose.yml index 0ec2f00de6..e99e187aaf 100644 --- a/languages/typescript/examples/prisma/docker-compose.yml +++ b/languages/typescript/examples/prisma/docker-compose.yml @@ -12,7 +12,7 @@ services: postgres: - image: postgres:16 + image: public.ecr.aws/docker/library/postgres:16 container_name: cipherstash-prisma-example-pg restart: unless-stopped environment: diff --git a/languages/typescript/packages/protect-ffi/integration-tests/docker-compose.yml b/languages/typescript/packages/protect-ffi/integration-tests/docker-compose.yml index db35fb5d0f..5fe0f7d221 100644 --- a/languages/typescript/packages/protect-ffi/integration-tests/docker-compose.yml +++ b/languages/typescript/packages/protect-ffi/integration-tests/docker-compose.yml @@ -1,6 +1,6 @@ services: postgres: - image: postgres:latest + image: public.ecr.aws/docker/library/postgres:latest container_name: protect-ffi-postgres environment: - POSTGRES_DB=${PGDATABASE:-cipherstash} diff --git a/local/docker-compose.supabase.yml b/local/docker-compose.supabase.yml index 9274106a13..96c3694e3b 100644 --- a/local/docker-compose.supabase.yml +++ b/local/docker-compose.supabase.yml @@ -30,7 +30,7 @@ name: cs-integration-supabase services: db: - image: supabase/postgres:17.4.1.048@sha256:68f90b9a227f56b583d2c1aef2fc683c4dc693a3c5ebf5191903e966318d87ee + image: public.ecr.aws/supabase/postgres:17.4.1.048@sha256:68f90b9a227f56b583d2c1aef2fc683c4dc693a3c5ebf5191903e966318d87ee environment: POSTGRES_PASSWORD: password ports: @@ -65,7 +65,7 @@ services: retries: 60 postgrest: - image: postgrest/postgrest:v12.2.12@sha256:be3b6ab31a94e3e89f08edad40be0234ae0951e3297f2043d797c219165f5afa + image: public.ecr.aws/supabase/postgrest:v12.2.12@sha256:be3b6ab31a94e3e89f08edad40be0234ae0951e3297f2043d797c219165f5afa depends_on: db: condition: service_healthy diff --git a/packages/eql/tests/docker-compose.yml b/packages/eql/tests/docker-compose.yml index 7089551a29..c97e58dc6b 100644 --- a/packages/eql/tests/docker-compose.yml +++ b/packages/eql/tests/docker-compose.yml @@ -1,7 +1,7 @@ services: postgres: &postgres container_name: postgres - image: postgres:17 + image: public.ecr.aws/docker/library/postgres:17 # max_locks_per_transaction is NOT a per-transaction cap — it sizes the # CLUSTER-WIDE shared lock table as max_locks_per_transaction * # max_connections. The shipped uninstaller drops both eql_v3 schemas with @@ -44,24 +44,24 @@ services: postgres-17: <<: *postgres - image: postgres:17 + image: public.ecr.aws/docker/library/postgres:17 container_name: postgres-17 #volumes: # uncomment if you need to inspect the container contents #- ./pg/data-17:/var/lib/postgresql/data postgres-16: <<: *postgres - image: postgres:16 + image: public.ecr.aws/docker/library/postgres:16 container_name: postgres-16 postgres-15: <<: *postgres - image: postgres:15 + image: public.ecr.aws/docker/library/postgres:15 container_name: postgres-15 postgres-14: <<: *postgres - image: postgres:14 + image: public.ecr.aws/docker/library/postgres:14 container_name: postgres-14 networks: diff --git a/packages/stack-auth/src/access_key_refresher.rs b/packages/stack-auth/src/access_key_refresher.rs index f33880515d..393e800daa 100644 --- a/packages/stack-auth/src/access_key_refresher.rs +++ b/packages/stack-auth/src/access_key_refresher.rs @@ -901,12 +901,14 @@ mod tests { /// stick. Treating a transient failure as permanent locks a client out of /// a service that has since recovered — the worse of the two mistakes. #[tokio::test] - async fn a_server_fault_is_retried_on_the_next_call() { + async fn a_server_fault_is_retried_after_its_backoff() { let (url, calls) = start_counting_server( axum::http::StatusCode::INTERNAL_SERVER_ERROR, serde_json::json!({}), ) .await; + let start = now_secs(); + let clock = crate::clock::TestClock::new(start); let refresher = AccessKeyRefresher::new( SecretToken::new("test-access-key"), @@ -914,16 +916,24 @@ mod tests { None, default_transport(), ); - let strategy = AutoRefresh::with_token(refresher, make_expired_token("old-token")); + let strategy = AutoRefresh::with_token_and_clock( + refresher, + make_token_expiring_at("old-token", start - 1), + clock.shared(), + ); - for _ in 0..3 { + for attempt in 1..=3 { strategy.get_token().await.unwrap_err(); + // A caller during the backoff gets the same error, without a + // request of its own. + strategy.get_token().await.unwrap_err(); + assert_eq!(calls.load(Ordering::SeqCst), attempt); + clock.advance(crate::BACKOFF_CAP_SECS); } - assert_eq!( calls.load(Ordering::SeqCst), 3, - "a server fault must be retried; only settled refusals stick", + "a server fault must be retried once its backoff ends; only settled refusals stick", ); } @@ -1286,20 +1296,16 @@ mod tests { ); } - // At least N-1 callers should be fast (non-blocking). + // Every caller is fast: the token still works, so the refresh is + // the background task's, and no caller starts or waits for it. let fast_callers = results .iter() .filter(|(_, dur)| *dur < Duration::from_millis(100)) .count(); - assert!( - fast_callers >= CONCURRENCY - 1, - "expected at least {} fast callers, got {}", - CONCURRENCY - 1, - fast_callers, - ); + assert_eq!(fast_callers, CONCURRENCY, "every caller should be fast"); - assert_eq!(stats.peak(), 1, "peak concurrency to auth endpoint"); - assert_eq!(stats.total(), 1, "total auth requests"); + assert!(stats.peak() <= 1, "peak concurrency to auth endpoint"); + assert!(stats.total() <= 1, "total auth requests"); } #[tokio::test(flavor = "multi_thread", worker_threads = 4)] diff --git a/packages/stack-auth/src/access_key_strategy.rs b/packages/stack-auth/src/access_key_strategy.rs index 86a8b1a5b2..ebb18f80f6 100644 --- a/packages/stack-auth/src/access_key_strategy.rs +++ b/packages/stack-auth/src/access_key_strategy.rs @@ -6,7 +6,10 @@ use crate::auto_refresh::AutoRefresh; use crate::token_store::{NoStore, TokenStore}; use crate::transport::{self, SharedTransport}; use crate::HttpTransport; -use crate::{ensure_trailing_slash, AuthError, AuthStrategy, SecretToken, ServiceToken}; +use crate::{ + ensure_trailing_slash, AuthError, AuthStrategy, NextRefresh, RefreshDriver, SecretToken, + ServiceToken, +}; /// An [`AuthStrategy`] that uses a static access key to authenticate against /// a specific workspace. @@ -90,10 +93,40 @@ impl AccessKeyStrategy { base_url_override: None, token_store: NoStore, transport: None, + refresh_floor: std::time::Duration::from_secs(crate::REFRESH_FLOOR_SECS), } } } +impl AccessKeyStrategy { + /// Hand refreshing this strategy's token ahead of its expiry to the + /// caller's own timer, for a host with no background task of its own, + /// such as a WebAssembly host. See [`RefreshDriver`] for the contract, + /// and [`next_refresh`](Self::next_refresh) and + /// [`refresh_now`](Self::refresh_now) for the two calls a driver makes. + /// + /// A native strategy refreshes ahead from a Tokio task of its own, and + /// needs no driver. + pub fn drive_refresh(&self) -> RefreshDriver { + self.inner.drive_refresh() + } + + /// When the token's next refresh ahead of its expiry is due, by the + /// rule in [`RefreshSchedule`](crate::RefreshSchedule): idle until a + /// call uses the token, and later after a failed refresh. + pub async fn next_refresh(&self) -> NextRefresh { + self.inner.next_refresh().await + } + + /// Refresh the token now. A refresh already in flight is not repeated. + /// Returns this attempt's error, which a caller of `get_token` does not + /// see while the cached token still works; the next attempt then backs + /// off. + pub async fn refresh_now(&self) -> Result<(), AuthError> { + self.inner.refresh_now().await.map_err(AuthError::from) + } +} + impl AuthStrategy for &AccessKeyStrategy { async fn get_token(self) -> Result { self.inner @@ -113,9 +146,34 @@ pub struct AccessKeyStrategyBuilder { base_url_override: Option, token_store: S, transport: Option, + refresh_floor: std::time::Duration, } impl AccessKeyStrategyBuilder { + /// Set the refresh floor: once the token has less than `floor` left, + /// the call that gets it refreshes it first. So the call does not get + /// back a token that may expire before the request using it is sent. + /// Defaults to [`REFRESH_FLOOR_SECS`](crate::REFRESH_FLOOR_SECS), 30 + /// seconds. + /// + /// Above the floor, a call gets the token at once while the background + /// task refreshes it. Below it, the call refreshes the token itself, or + /// waits for the refresh already running. + /// + /// The floor is whole seconds, rounded up. Zero turns it off: a call + /// never waits while its token still works. A floor longer than the + /// 90-second refresh window acts as the window. + /// + /// For short-lived tokens, keep the floor at or below half the token's + /// lifetime. The background refresh of a short-lived token is due half + /// way through its life, so with a larger floor calls start waiting + /// before it runs. Raise the floor if the requests that use a token can + /// take longer than 30 seconds to reach the server. + pub fn refresh_floor(mut self, floor: std::time::Duration) -> Self { + self.refresh_floor = floor; + self + } + /// Send this strategy's requests through `transport` instead of the /// bundled `reqwest` client. /// @@ -174,6 +232,7 @@ impl AccessKeyStrategyBuilder { base_url_override: self.base_url_override, token_store: store, transport: self.transport, + refresh_floor: self.refresh_floor, } } } @@ -201,8 +260,10 @@ impl AccessKeyStrategyBuilder { self.audience, transport::resolve(self.transport)?, ); + let inner = AutoRefresh::with_store(refresher, self.token_store); + inner.set_refresh_floor(self.refresh_floor); Ok(AccessKeyStrategy { - inner: AutoRefresh::with_store(refresher, self.token_store), + inner, expected_workspace, }) } @@ -416,3 +477,131 @@ mod workspace_verification_tests { } } } + +/// The calls a host with no background task makes to refresh ahead of +/// expiry. +#[cfg(test)] +#[cfg(feature = "http")] +mod host_refresh_tests { + use super::*; + use crate::test_support::{crn_with_workspace, jwt_with_workspace}; + use mocktail::prelude::*; + + const WS: &str = "ZVATKW3VHMFG27DY"; + + /// An auth server that issues an hour-long token, or refuses with a + /// server fault. + async fn server(issues: bool) -> MockServer { + let mut mocks = MockSet::new(); + let jwt = jwt_with_workspace(WS); + mocks.mock(move |when, then| { + when.post().path("/api/authorise"); + if issues { + then.json(serde_json::json!({ "accessToken": jwt, "expiry": now() + 3_600 })); + } else { + then.internal_server_error(); + } + }); + let server = MockServer::new_http("access-key-host-refresh").with_mocks(mocks); + #[allow(clippy::expect_used)] + server.start().await.expect("mock server start"); + server + } + + fn strategy(server: &MockServer) -> AccessKeyStrategy { + #[allow(clippy::expect_used)] + AccessKeyStrategy::builder( + crn_with_workspace(WS), + "CSAKtestKeyId.testKeySecret".parse().expect("access key"), + ) + .base_url(server.url("")) + .build() + .expect("builder") + } + + /// The builder's refresh floor reaches the engine: the default, a + /// configured one, and one longer than the refresh window, bounded. + #[tokio::test] + #[allow(clippy::expect_used)] + async fn the_builder_sets_the_refresh_floor() { + let server = server(true).await; + let build = |floor: Option| { + let mut builder = AccessKeyStrategy::builder( + crn_with_workspace(WS), + "CSAKtestKeyId.testKeySecret".parse().expect("access key"), + ) + .base_url(server.url("")); + if let Some(secs) = floor { + builder = builder.refresh_floor(std::time::Duration::from_secs(secs)); + } + builder.build().expect("builder") + }; + assert_eq!(build(None).inner.refresh_floor(), crate::REFRESH_FLOOR_SECS); + assert_eq!(build(Some(45)).inner.refresh_floor(), 45); + assert_eq!(build(Some(600)).inner.refresh_floor(), 90); + } + + fn now() -> u64 { + web_time::SystemTime::now() + .duration_since(web_time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or_default() + } + + #[tokio::test] + #[allow(clippy::expect_used)] + async fn a_used_tokens_refresh_is_due_ahead_of_its_expiry() { + let server = server(true).await; + let strategy = strategy(&server); + assert_eq!( + strategy.next_refresh().await, + NextRefresh::Idle, + "no token yet" + ); + + // The first call exchanges, which is a refresh attempt; the second + // uses the token. + let _ = (&strategy).get_token().await.expect("get_token"); + assert_eq!( + strategy.next_refresh().await, + NextRefresh::Idle, + "not used since" + ); + let _ = (&strategy).get_token().await.expect("get_token"); + let NextRefresh::At(at) = strategy.next_refresh().await else { + panic!("a used token has a refresh due"); + }; + let now = now(); + assert!( + at > now + 3_000 && at < now + 3_600, + "due {} s from now, not ahead of an hour-long token's expiry", + at.saturating_sub(now) + ); + } + + #[tokio::test] + #[allow(clippy::expect_used)] + async fn refresh_now_exchanges_and_reports_a_failure() { + let ok = server(true).await; + strategy(&ok) + .refresh_now() + .await + .expect("an exchange that succeeds"); + + let refusing = server(false).await; + let strategy = strategy(&refusing); + let err = strategy.refresh_now().await.expect_err("a server fault"); + assert!(matches!(err, AuthError::Server(_)), "{err:?}"); + } + + #[tokio::test] + #[allow(clippy::expect_used)] + async fn a_host_driver_is_attached_while_it_lives() { + let server = server(true).await; + let strategy = strategy(&server); + let driver = strategy.drive_refresh(); + assert_eq!(strategy.inner.drivers_attached(), 1); + drop(driver); + assert_eq!(strategy.inner.drivers_attached(), 0); + } +} diff --git a/packages/stack-auth/src/auto_refresh.rs b/packages/stack-auth/src/auto_refresh.rs index 1e336a42bd..5748311f25 100644 --- a/packages/stack-auth/src/auto_refresh.rs +++ b/packages/stack-auth/src/auto_refresh.rs @@ -1,9 +1,10 @@ -use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; use std::sync::Arc; use tokio::sync::{Mutex, Notify, OwnedMutexGuard}; use crate::clock::{system_clock, SharedClock}; +use crate::refresh_schedule::{NextRefresh, RefreshSchedule}; use crate::refresher::Refresher; use crate::token_store::{NoStore, TokenStore}; use crate::{ServiceToken, Token}; @@ -62,6 +63,96 @@ struct RefreshState { /// Source of "now" for token-expiry checks. [`SystemClock`](crate::clock::SystemClock) /// in production; an injected clock in tests so expiry is deterministic. clock: SharedClock, + /// Who refreshes the token ahead of its expiry, if anyone. + driver: Arc, + /// The refresh floor, in seconds. While a driver is attached, a call + /// whose token has less than this left refreshes it, or waits for the + /// refresh in flight. See [`refresh_floor_secs`]. + refresh_floor: AtomicU64, +} + +/// The refresh floor `floor` in whole seconds, rounded up, as the engine +/// applies it. A floor longer than the 90-second refresh window acts as the +/// window, since a call outside it never refreshes. Zero turns the floor +/// off: a call never waits while its token still works. +pub(crate) fn refresh_floor_secs(floor: std::time::Duration) -> u64 { + let secs = floor + .as_secs() + .saturating_add(u64::from(floor.subsec_nanos() > 0)); + secs.min(crate::token::EXPIRY_LEEWAY_SECS) +} + +/// Who refreshes a token ahead of its expiry: the background task on a +/// native target, or a host holding a [`RefreshDriver`]. While one is +/// attached, a call with a token that still works never starts a refresh. +#[derive(Default)] +struct DriverControl { + /// The drivers attached: the background task, and each live + /// [`RefreshDriver`]. + attached: AtomicUsize, + /// Whether the background task has been started and has not ended. + #[cfg(not(target_arch = "wasm32"))] + task: AtomicBool, + /// Set when the strategy is dropped, so its background task ends. + stopped: AtomicBool, + /// Wakes the background task: an idle plan was used, or the strategy + /// was dropped. + wake: Notify, +} + +/// A driver's place in [`DriverControl::attached`], given up on drop. +struct Attachment(Arc); + +impl Attachment { + fn new(control: &Arc) -> Self { + let _ = control.attached.fetch_add(1, Ordering::AcqRel); + Self(Arc::clone(control)) + } +} + +impl Drop for Attachment { + fn drop(&mut self) { + let _ = self.0.attached.fetch_sub(1, Ordering::AcqRel); + } +} + +/// The background task's attachment. When the task ends, or its runtime +/// drops it, the next call may start another. +#[cfg(not(target_arch = "wasm32"))] +struct TaskAttachment(Attachment); + +#[cfg(not(target_arch = "wasm32"))] +impl Drop for TaskAttachment { + fn drop(&mut self) { + (self.0).0.task.store(false, Ordering::Release); + } +} + +/// A host's hold on refreshing one strategy's token ahead of its expiry. +/// +/// A WebAssembly host has no background task in the strategy, so it keeps +/// the timer itself: it asks the strategy when the next refresh is due +/// (`next_refresh`), waits until then, and calls `refresh_now`. While a +/// `RefreshDriver` lives, a call for a token that still works does not +/// start a refresh: the host does. The one exception is a token with less +/// than the refresh floor left +/// ([`AccessKeyStrategyBuilder::refresh_floor`](crate::AccessKeyStrategyBuilder::refresh_floor)). +/// The call refreshes that token itself. Drop the driver when the host stops +/// driving; calls then refresh in the 90 seconds before expiry, as they do +/// with no driver. +/// +/// A host that holds a driver and never refreshes loses nothing but time: +/// once the token expires, the next call exchanges it, as at startup. +/// +/// A native strategy refreshes ahead from a task of its own and needs no +/// driver. +#[must_use = "dropping the driver hands refreshing back to the calls"] +pub struct RefreshDriver(#[allow(dead_code, reason = "held for its drop")] Attachment); + +impl std::fmt::Debug for RefreshDriver { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("RefreshDriver").finish_non_exhaustive() + } } /// How long a cached refusal is replayed before the server is asked again. @@ -92,7 +183,10 @@ struct State { /// sees the *same* outcome as whoever actually performed the refresh it /// was waiting on, instead of a generic `Expired` that discards why the /// wait ended in failure. - last_refresh_error: Option<(&'static str, String)>, + last_refresh_error: Option, + /// When the token is refreshed ahead of its expiry, and the backoff + /// after a failed refresh. + schedule: RefreshSchedule, } /// A non-retryable refusal, held in a form that can be handed to more than one @@ -134,6 +228,29 @@ impl StickyDenial { } } +/// A refresh attempt that failed: its error, and the cached token when the +/// caller may go on using it. +struct Failed { + error: AutoRefreshError, + usable: Option, +} + +impl Failed { + /// A failure with no token to fall back on. + fn with(error: impl Into) -> Self { + Self { + error: error.into(), + usable: None, + } + } + + /// For a call to get a token: the cached token if it still works, else + /// the error. + fn into_token(self) -> Result { + self.usable.ok_or(self.error) + } +} + /// Whether a failed [`Refresher::refresh`] spent its credential. /// /// A store error means the upstream exchange succeeded and only persisting @@ -182,6 +299,14 @@ impl State { token, denial: None, last_refresh_error: None, + schedule: RefreshSchedule::new(), + } + } + + /// Plan for the cached token, if there is one, as of `now`. + fn observe_token(&mut self, now: u64) { + if let Some(token) = &self.token { + self.schedule.observe(token, now); } } @@ -206,15 +331,17 @@ impl State { if err.is_account_refusal() { self.denial = Some(StickyDenial::new(err, now)); } - self.last_refresh_error = Some((err.error_code(), err.to_string())); + self.last_refresh_error = Some(err.replay()); + self.schedule.refresh_failed(err, now); } /// The error from the most recently completed refresh attempt, if it - /// failed and no success has happened since. + /// failed and no success has happened since: the same kind of error, + /// with the same code and message. fn last_refresh_error(&self) -> Option { - self.last_refresh_error.as_ref().map(|(code, message)| { - crate::AuthError::from_error_code(code, message, &serde_json::Map::new()) - }) + self.last_refresh_error + .as_ref() + .map(crate::AuthError::replay) } /// The recorded refusal if it is still within its window, discarding it if @@ -297,6 +424,8 @@ impl AutoRefresh { refresh_in_progress: AtomicBool::new(false), refresh_notify: Notify::new(), clock, + driver: Arc::default(), + refresh_floor: AtomicU64::new(crate::REFRESH_FLOOR_SECS), }), } } @@ -316,12 +445,77 @@ impl AutoRefresh { pub(crate) fn refresher(&self) -> &R { &self.shared.refresher } + + /// How many drivers are attached: the background task and each live + /// [`RefreshDriver`]. + #[cfg(test)] + #[cfg(feature = "http")] + pub(crate) fn drivers_attached(&self) -> usize { + self.shared.driver.attached.load(Ordering::Acquire) + } + + /// No background task: a call in the 90 seconds before expiry starts + /// the refresh, as on wasm32 with no host driving it. + /// + /// For an engine whose refresh only a call should start: an OIDC + /// engine re-exchanges one user's JWT, which a timer has no business + /// renewing once that user's requests stop, and which may expire + /// before the token it was exchanged for. + pub(crate) fn refreshed_by_calls(self) -> Self { + // The task's flag, set for good: no call starts one. + #[cfg(not(target_arch = "wasm32"))] + self.shared.driver.task.store(true, Ordering::Release); + self + } + + /// The refresh floor in effect, in seconds. + #[cfg(test)] + #[cfg(feature = "http")] + pub(crate) fn refresh_floor(&self) -> u64 { + self.shared.refresh_floor.load(Ordering::Relaxed) + } + + /// Set the refresh floor. See [`refresh_floor_secs`]. + pub(crate) fn set_refresh_floor(&self, floor: std::time::Duration) { + self.shared + .refresh_floor + .store(refresh_floor_secs(floor), Ordering::Relaxed); + } + + /// Hand refreshing ahead of expiry to the caller's timer. See + /// [`RefreshDriver`]. + pub(crate) fn drive_refresh(&self) -> RefreshDriver { + RefreshDriver(Attachment::new(&self.shared.driver)) + } +} + +impl Drop for AutoRefresh { + /// The background task holds only a weak reference; this wakes it so it + /// sees the strategy is gone and ends now rather than at its next + /// refresh. + fn drop(&mut self) { + self.shared.driver.stopped.store(true, Ordering::Release); + self.shared.driver.wake.notify_one(); + } } impl AutoRefresh { pub(crate) async fn get_token(&self) -> Result { self.shared.get_token().await } + + /// When the token's next refresh ahead of expiry is due. + pub(crate) async fn next_refresh(&self) -> NextRefresh { + let mut state = self.shared.state.lock().await; + state.observe_token(self.shared.clock.now_unix_secs()); + state.schedule.next() + } + + /// Refresh the token now, whether or not it is due, and report how the + /// attempt went. A refresh already in flight is not joined or repeated. + pub(crate) async fn refresh_now(&self) -> Result<(), AutoRefreshError> { + self.shared.refresh_now().await + } } impl RefreshState { @@ -354,6 +548,14 @@ impl RefreshState { // the checks are mutually consistent and deterministic under test. let now = self.clock.now_unix_secs(); + // This call uses the token, so it is due a refresh ahead of expiry. + state.observe_token(now); + if state.schedule.used() { + self.driver.wake.notify_one(); + } + #[cfg(not(target_arch = "wasm32"))] + self.ensure_driver(); + if state.token.is_none() { if let Some(err) = state.fresh_denial(now) { return Err(AutoRefreshError::Auth(err)); @@ -361,7 +563,10 @@ impl RefreshState { let Some(credential) = self.refresher.try_credential(None) else { return Err(AutoRefreshError::NotFound); }; - return self.start_refresh(state, credential).await; + return self + .start_refresh(state, credential) + .await + .or_else(Failed::into_token); } if !state.token.as_ref().is_some_and(|t| t.is_expired_at(now)) { @@ -383,11 +588,150 @@ impl RefreshState { }; } + // A token that still works is the driver's to refresh. The + // exception is a token with less than the floor left: the call + // refreshes it rather than get back a token about to expire. + // While a failed refresh backs off, nobody starts another. A token + // that has expired meanwhile fails at once with that refresh's + // error, rather than every call making an exchange of its own. + let usable = state.token.as_ref().is_some_and(|t| t.is_usable_at(now)); + let driven = self.driver.attached.load(Ordering::Acquire) > 0; + let above_floor = state + .token + .as_ref() + .is_some_and(|t| self.above_floor(t, now)); + if usable && ((driven && above_floor) || state.schedule.backing_off(now)) { + return state.service_token(); + } + if !usable && state.schedule.backing_off(now) { + return Err(state + .last_refresh_error() + .map_or(AutoRefreshError::Expired, AutoRefreshError::Auth)); + } + let Some(credential) = self.refresher.try_credential(state.token.as_mut()) else { return state.require_usable_token(now); }; - self.start_refresh(state, credential).await + self.start_refresh(state, credential) + .await + .or_else(Failed::into_token) + } + + /// Refresh now, unless a refresh is in flight. Loads a stored token + /// first if none is cached. The result is this attempt's: a failure + /// is reported even when the cached token still works. + async fn refresh_now(self: &Arc) -> Result<(), AutoRefreshError> { + let mut state = self.state.clone().lock_owned().await; + if state.token.is_none() { + drop(state); + let loaded = self.store.load().await; + state = self.state.clone().lock_owned().await; + if state.token.is_none() { + state.token = loaded.map(|t| distrust_overlong(t, self.clock.now_unix_secs())); + } + } + let now = self.clock.now_unix_secs(); + state.observe_token(now); + if self.refresh_in_progress.load(Ordering::Acquire) { + return Ok(()); + } + if let Some(err) = state.fresh_denial(now) { + return Err(AutoRefreshError::Auth(err)); + } + // With no token yet this is the first exchange, for a strategy + // that can make one. + let Some(credential) = self.refresher.try_credential(state.token.as_mut()) else { + if state.token.is_none() { + return Err(AutoRefreshError::NotFound); + } + state.schedule.cannot_refresh(); + return Ok(()); + }; + self.start_refresh(state, credential) + .await + .map(|_| ()) + .map_err(|failed| failed.error) + } + + /// Refresh if the plan says one is due: it may have moved on since the + /// background task read it. + #[cfg(not(target_arch = "wasm32"))] + async fn refresh_if_due(self: &Arc) { + let due = { + let mut state = self.state.lock().await; + let now = self.clock.now_unix_secs(); + state.observe_token(now); + matches!(state.schedule.next(), NextRefresh::At(at) if at <= now) + }; + if due { + // The outcome is recorded in the plan; there is no caller to + // tell. A refresh already in flight is left to finish. + let _ = self.refresh_now().await; + } + } + + /// Start the background task that refreshes ahead of expiry, once, on + /// the current Tokio runtime. Outside a runtime there is none, and + /// calls refresh in the 90 seconds before expiry instead. + #[cfg(not(target_arch = "wasm32"))] + fn ensure_driver(self: &Arc) { + let control = &self.driver; + if control.task.swap(true, Ordering::AcqRel) { + return; + } + let Ok(runtime) = tokio::runtime::Handle::try_current() else { + control.task.store(false, Ordering::Release); + return; + }; + // Attached before the task runs, so a call right after this one + // already leaves the refresh to it. A runtime that drops the task + // unrun drops the attachment too, and the next call starts another. + let attachment = TaskAttachment(Attachment::new(control)); + let _task = runtime.spawn(Self::drive(Arc::downgrade(self), attachment)); + } + + /// The background task: wait until the plan says a refresh is due, run + /// it, and repeat, until the strategy is dropped. Holds the strategy + /// only while it refreshes. + #[cfg(not(target_arch = "wasm32"))] + async fn drive(strategy: std::sync::Weak, attachment: TaskAttachment) { + use std::time::Duration; + let control = Arc::clone(&(attachment.0).0); + loop { + let mut wake = std::pin::pin!(control.wake.notified()); + // Listed before the plan is read, so a use or a drop between + // the read and the wait still wakes it. + let _ = wake.as_mut().enable(); + if control.stopped.load(Ordering::Acquire) { + return; + } + let (next, now) = { + let Some(strategy) = strategy.upgrade() else { + return; + }; + let next = strategy.state.lock().await.schedule.next(); + (next, strategy.clock.now_unix_secs()) + }; + let NextRefresh::At(at) = next else { + wake.await; + continue; + }; + // Until the refresh is due, unless a use or the drop of the + // strategy wakes the task to read the plan again. + tokio::select! { + () = tokio::time::sleep(Duration::from_secs(at.saturating_sub(now))) => {} + () = wake => continue, + } + let Some(strategy) = strategy.upgrade() else { + return; + }; + strategy.refresh_if_due().await; + drop(strategy); + // At least a second between attempts, so a plan that stays due + // (a caller's refresh still in flight, say) cannot spin. + tokio::time::sleep(Duration::from_secs(1)).await; + } } /// There is no suspension between extracting the credential and spawning @@ -395,9 +739,10 @@ impl RefreshState { /// the exchange, persistence, state installation, or waiter notification. async fn start_refresh( self: &Arc, - state: OwnedMutexGuard, + mut state: OwnedMutexGuard, credential: R::Credential, - ) -> Result { + ) -> Result { + state.schedule.attempt_started(); self.refresh_in_progress.store(true, Ordering::Release); #[cfg(not(target_arch = "wasm32"))] { @@ -405,9 +750,9 @@ impl RefreshState { tokio::spawn(async move { shared.run_refresh(state, credential).await }) .await .map_err(|_| { - crate::AuthError::Internal(crate::error::InternalError( + Failed::with(crate::AuthError::Internal(crate::error::InternalError( "token refresh task terminated before completion".into(), - )) + ))) })? } // WASI hosts drive the export to completion with block_on; browser @@ -420,7 +765,7 @@ impl RefreshState { &self, mut state: OwnedMutexGuard, credential: R::Credential, - ) -> Result { + ) -> Result { if state .token .as_ref() @@ -448,7 +793,10 @@ impl RefreshState { /// [`save_refreshed_token`](Self::save_refreshed_token). fn install_refreshed_token(&self, state: &mut State, new_token: Token) -> ServiceToken { let service_token = ServiceToken::new(new_token.access_token().clone()); - state.token = Some(capped(new_token, self.clock.now_unix_secs())); + let now = self.clock.now_unix_secs(); + let new_token = capped(new_token, now); + state.schedule.observe(&new_token, now); + state.token = Some(new_token); // A success proves whatever previously refused us has changed its mind. state.denial = None; state.last_refresh_error = None; @@ -456,8 +804,22 @@ impl RefreshState { service_token } - /// Another caller is already refreshing — return the current token if still - /// usable, otherwise wait for the in-flight refresh to complete via `Notify`. + /// Whether `token` has at least the refresh floor left at `now`. The + /// floor applies only while a driver is attached. With none, as for an + /// OIDC engine, every call in the 90-second window refreshes anyway. A + /// call during that refresh gets the token while it still works. + fn above_floor(&self, token: &Token, now: u64) -> bool { + let floor = if self.driver.attached.load(Ordering::Acquire) > 0 { + self.refresh_floor.load(Ordering::Relaxed) + } else { + 0 + }; + token.expires_at().saturating_sub(now) >= floor + } + + /// Another caller is already refreshing. Return the current token if it + /// has at least the refresh floor left. Otherwise wait for the in-flight + /// refresh to complete via `Notify`. /// /// Takes `MutexGuard` by value because the lock is dropped before awaiting /// the notification. @@ -467,12 +829,17 @@ impl RefreshState { now: u64, ) -> Result { if let Ok(token) = state.service_token() { - if state.token.as_ref().is_some_and(|t| t.is_usable_at(now)) { + if state + .token + .as_ref() + .is_some_and(|t| t.is_usable_at(now) && self.above_floor(t, now)) + { return Ok(token); } } - // Token crossed real expiry during in-flight refresh. Wait for the - // refresh to complete rather than returning Expired. + // The token is under the floor, or crossed real expiry, during the + // in-flight refresh. Wait for the refresh to complete rather than + // hand back a token about to expire, or return Expired. // // `Notified` does not join the notify list until it is first polled, // and `notify_waiters` stores no permit for futures that are not yet @@ -542,8 +909,8 @@ impl RefreshState { &self, state: OwnedMutexGuard, credential: R::Credential, - ) -> Result { - let current_service_token = state.service_token()?; + ) -> Result { + let current_service_token = state.service_token().map_err(Failed::with)?; let current_expires_at = state.token.as_ref().map_or(0, Token::expires_at); drop(state); @@ -591,15 +958,16 @@ impl RefreshState { // refresh actually got (regardless of its class). state.record_refusal(&err, self.clock.now_unix_secs()); guard.defuse(); - // An ordinary failure leaves the cached token usable, so this - // call still succeeds. A consumed credential does not: the - // rotation happened upstream but was lost, and succeeding - // would hide that until the cached token expires. - if consumed || self.clock.now_unix_secs() >= current_expires_at { - Err(AutoRefreshError::Auth(err)) - } else { - Ok(current_service_token) - } + // An ordinary failure leaves the cached token usable, so a + // call for a token still gets one. A consumed credential + // does not. The rotation happened upstream but was lost. + // Handing out the cached token would hide that until it + // expires. + let usable = !consumed && self.clock.now_unix_secs() < current_expires_at; + Err(Failed { + error: AutoRefreshError::Auth(err), + usable: usable.then_some(current_service_token), + }) } }; @@ -613,7 +981,7 @@ impl RefreshState { &self, state: &mut State, credential: R::Credential, - ) -> Result { + ) -> Result { let mut guard = CancelGuard { in_progress: &self.refresh_in_progress, notify: &self.refresh_notify, @@ -639,7 +1007,7 @@ impl RefreshState { // Propagate the refuser's own answer. Flattening to `Expired` // here would tell a caller who is over their usage limit that // their token expired, and send them round the same loop. - Err(AutoRefreshError::Auth(err)) + Err(Failed::with(err)) } } } @@ -754,6 +1122,25 @@ mod tests { server } + /// Wait, on the wall clock, until a failed refresh's backoff has ended, + /// so the next call may refresh again. + async fn wait_out_backoff(strategy: &AutoRefresh) { + // The tests that wait here fail once or twice: a backoff of a + // couple of seconds. One that never ends fails the test rather + // than hang it. + tokio::time::timeout(std::time::Duration::from_secs(5), async { + loop { + let now = strategy.shared.clock.now_unix_secs(); + if !strategy.shared.state.lock().await.schedule.backing_off(now) { + return; + } + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + } + }) + .await + .expect("the backoff did not end"); + } + fn auto_refresh_with_token( dir: &tempfile::TempDir, server: &MockServer, @@ -771,7 +1158,7 @@ mod tests { None, crate::transport::default_transport(), ); - AutoRefresh::with_token(refresher, token) + AutoRefresh::with_token(refresher, token).refreshed_by_calls() } mod given_no_cached_token { @@ -789,7 +1176,7 @@ mod tests { None, crate::transport::default_transport(), ); - let strategy = AutoRefresh::with_store(refresher, NoStore); + let strategy = AutoRefresh::with_store(refresher, NoStore).refreshed_by_calls(); let err = strategy.get_token().await.unwrap_err(); @@ -856,7 +1243,8 @@ mod tests { let store = CountingStore { load_calls: Arc::clone(&load_calls), }; - let strategy = AutoRefresh::with_store(AlwaysOverLimitRefresher, store); + let strategy = + AutoRefresh::with_store(AlwaysOverLimitRefresher, store).refreshed_by_calls(); let first = strategy.get_token().await; assert!( @@ -1103,6 +1491,7 @@ mod tests { }); // Second call: refresh token is available → retry succeeds. + wait_out_backoff(&strategy).await; let token = strategy.get_token().await.unwrap(); assert_eq!( token.as_str(), @@ -1260,6 +1649,7 @@ mod tests { }); // Second call: refresh token was restored, so the retry succeeds. + wait_out_backoff(&strategy).await; let token = strategy.get_token().await.unwrap(); assert!( token.as_str() == "still-usable" || token.as_str() == "refreshed-token", @@ -1574,7 +1964,7 @@ mod stress_tests { None, crate::transport::default_transport(), ); - AutoRefresh::with_token(refresher, token) + AutoRefresh::with_token(refresher, token).refreshed_by_calls() } const CONCURRENCY: usize = 50; @@ -2117,16 +2507,19 @@ mod expiry_crossing_regression { let started = Arc::new(Notify::new()); let gate = Arc::new(Notify::new()); let calls = Arc::new(AtomicUsize::new(0)); - let strategy = Arc::new(AutoRefresh::with_token_and_clock( - GatedRefresher { - started: Arc::clone(&started), - gate: Arc::clone(&gate), - calls: Arc::clone(&calls), - refreshed_expires_at: clock.now() + 3600, - }, - make_token("expiring-soon", clock.now() + 10), - clock.shared(), - )); + let strategy = Arc::new( + AutoRefresh::with_token_and_clock( + GatedRefresher { + started: Arc::clone(&started), + gate: Arc::clone(&gate), + calls: Arc::clone(&calls), + refreshed_expires_at: clock.now() + 3600, + }, + make_token("expiring-soon", clock.now() + 10), + clock.shared(), + ) + .refreshed_by_calls(), + ); let caller = tokio::spawn({ let strategy = Arc::clone(&strategy); async move { strategy.get_token().await } @@ -2156,6 +2549,39 @@ mod expiry_crossing_regression { } } + /// With no driver attached, the caller that finds its token inside the + /// refresh window starts the refresh itself. Bounded, so a strategy that + /// wrongly believes a driver is attached fails here rather than hanging. + #[tokio::test] + async fn with_no_driver_a_caller_starts_the_refresh() { + let clock = TestClock::new(1_000_000); + let started = Arc::new(Notify::new()); + let gate = Arc::new(Notify::new()); + let calls = Arc::new(AtomicUsize::new(0)); + let refresher = GatedRefresher { + started: Arc::clone(&started), + gate: Arc::clone(&gate), + calls: Arc::clone(&calls), + refreshed_expires_at: clock.now() + 3600, + }; + let token = make_token("expiring-soon", clock.now() + 10); + let strategy = Arc::new( + AutoRefresh::with_token_and_clock(refresher, token, clock.shared()) + .refreshed_by_calls(), + ); + + let caller = { + let s = Arc::clone(&strategy); + tokio::spawn(async move { s.get_token().await }) + }; + tokio::time::timeout(std::time::Duration::from_secs(5), started.notified()) + .await + .expect("no caller started the refresh, although nothing drives it"); + gate.notify_one(); + caller.await.unwrap().unwrap(); + assert_eq!(calls.load(Ordering::SeqCst), 1); + } + #[tokio::test] async fn waiters_wait_for_refresh_when_token_crosses_expiry() { let clock = TestClock::new(1_000_000); @@ -2174,11 +2600,10 @@ mod expiry_crossing_regression { // the current clock value (so the first caller takes the non-blocking // path and gets the old token). let token = make_token("expiring-soon", clock.now() + 10); - let strategy = Arc::new(AutoRefresh::with_token_and_clock( - refresher, - token, - clock.shared(), - )); + let strategy = Arc::new( + AutoRefresh::with_token_and_clock(refresher, token, clock.shared()) + .refreshed_by_calls(), + ); // 1. First caller starts the non-blocking refresh. let first = { @@ -2186,7 +2611,9 @@ mod expiry_crossing_regression { tokio::spawn(async move { s.get_token().await }) }; // Wait until the refresh is actually in flight (gated; won't complete yet). - started.notified().await; + tokio::time::timeout(std::time::Duration::from_secs(5), started.notified()) + .await + .expect("the first caller did not start the refresh"); // 2. Advance the clock past real expiry while the refresh is still gated. // The token is now both expired and unusable. @@ -2313,18 +2740,19 @@ mod expiry_crossing_regression { // Within the 90s leeway (triggers a refresh) but still usable now, so the // first caller takes the non-blocking path and captures the old token. let token = make_token("expiring-soon", clock.now() + 10); - let strategy = Arc::new(AutoRefresh::with_token_and_clock( - refresher, - token, - clock.shared(), - )); + let strategy = Arc::new( + AutoRefresh::with_token_and_clock(refresher, token, clock.shared()) + .refreshed_by_calls(), + ); // 1. First caller starts the (gated) non-blocking refresh. let first = { let s = Arc::clone(&strategy); tokio::spawn(async move { s.get_token().await }) }; - started.notified().await; + tokio::time::timeout(std::time::Duration::from_secs(5), started.notified()) + .await + .expect("the first caller did not start the refresh"); // 2. Advance the clock past real expiry while the refresh is still gated. // The cached token is now both expired and unusable. @@ -2403,17 +2831,18 @@ mod expiry_crossing_regression { // Inside the leeway (so a refresh starts) but still usable, so the // first caller takes the non-blocking path. let token = make_token("expiring-soon", clock.now() + 10); - let strategy = Arc::new(AutoRefresh::with_token_and_clock( - refresher, - token, - clock.shared(), - )); + let strategy = Arc::new( + AutoRefresh::with_token_and_clock(refresher, token, clock.shared()) + .refreshed_by_calls(), + ); let first = { let s = Arc::clone(&strategy); tokio::spawn(async move { s.get_token().await }) }; - started.notified().await; + tokio::time::timeout(std::time::Duration::from_secs(5), started.notified()) + .await + .expect("the first caller did not start the refresh"); // Cross real expiry while the refresh is gated, so the waiters park in // `wait_for_in_flight_refresh` instead of being served the cached token. @@ -2519,17 +2948,18 @@ mod expiry_crossing_regression { // Inside the leeway (so a refresh starts) but still usable, so the // first caller takes the non-blocking path. let token = make_token("expiring-soon", clock.now() + 10); - let strategy = Arc::new(AutoRefresh::with_token_and_clock( - refresher, - token, - clock.shared(), - )); + let strategy = Arc::new( + AutoRefresh::with_token_and_clock(refresher, token, clock.shared()) + .refreshed_by_calls(), + ); let first = { let s = Arc::clone(&strategy); tokio::spawn(async move { s.get_token().await }) }; - started.notified().await; + tokio::time::timeout(std::time::Duration::from_secs(5), started.notified()) + .await + .expect("the first caller did not start the refresh"); // Cross real expiry while the refresh is gated, so the waiters park in // `wait_for_in_flight_refresh` instead of being served the cached token. @@ -2584,7 +3014,8 @@ mod expiry_crossing_regression { let clock = TestClock::new(1_000_000); // Fresh token: expires well beyond the 90s leeway. let token = make_token("fresh", clock.now() + 3600); - let strategy = AutoRefresh::with_token_and_clock(NeverRefresher, token, clock.shared()); + let strategy = AutoRefresh::with_token_and_clock(NeverRefresher, token, clock.shared()) + .refreshed_by_calls(); // Forward reading returns the cached token without refreshing. assert_eq!(strategy.get_token().await.unwrap().as_str(), "fresh"); @@ -2608,3 +3039,8 @@ mod cancellation_tests; #[cfg(all(feature = "http", not(target_arch = "wasm32")))] #[path = "auto_refresh/tests/soak.rs"] mod cancellation_soak; + +#[cfg(test)] +#[cfg(all(feature = "http", not(target_arch = "wasm32")))] +#[path = "auto_refresh/tests/background.rs"] +mod background_tests; diff --git a/packages/stack-auth/src/auto_refresh/tests/background.rs b/packages/stack-auth/src/auto_refresh/tests/background.rs new file mode 100644 index 0000000000..29f649ba3e --- /dev/null +++ b/packages/stack-auth/src/auto_refresh/tests/background.rs @@ -0,0 +1,839 @@ +//! Refresh ahead of expiry, off the caller's path, and backoff after a +//! failure. Time is Tokio's paused clock, so every wait is virtual. +#![allow(clippy::unwrap_used)] + +use super::*; +use crate::clock::Clock; +use crate::{AuthError, SecretToken}; +use std::sync::atomic::AtomicUsize; +use std::sync::Mutex as StdMutex; +use std::time::Duration; +use tokio::sync::Semaphore; +use tokio::time::{sleep, timeout, Instant}; + +/// "Now" from Tokio's clock, so a paused runtime moves the engine's time +/// with every virtual sleep. +struct TokioClock(Instant); + +impl Clock for TokioClock { + fn now_unix_secs(&self) -> u64 { + 1_000_000 + self.0.elapsed().as_secs() + } +} + +fn clock() -> SharedClock { + Arc::new(TokioClock(Instant::now())) +} + +fn token(access: &str, expires_at: u64) -> Token { + Token { + access_token: SecretToken::new(access), + refresh_token: None, + token_type: "Bearer".into(), + expires_at, + region: None, + client_id: None, + device_instance_id: None, + federated_from: None, + } +} + +/// An issuer that answers with a new token valid for `lifetime` seconds, +/// fails the first `failures` exchanges, and holds each exchange until the +/// test opens `gate` (when `gated`). +struct Issuer { + calls: AtomicUsize, + failures: AtomicUsize, + gated: bool, + gate: Semaphore, + lifetime: u64, + attempts: StdMutex>, +} + +impl Issuer { + fn new(failures: usize, gated: bool) -> Arc { + Arc::new(Self { + calls: AtomicUsize::new(0), + failures: AtomicUsize::new(failures), + gated, + gate: Semaphore::new(0), + lifetime: 900, + attempts: StdMutex::new(Vec::new()), + }) + } + + fn calls(&self) -> usize { + self.calls.load(Ordering::SeqCst) + } +} + +struct IssuerRefresher { + issuer: Arc, + clock: SharedClock, +} + +impl Refresher for IssuerRefresher { + type Credential = (); + + fn save(&self, _: &Token) {} + + fn try_credential(&self, _: Option<&mut Token>) -> Option<()> { + Some(()) + } + + fn restore(&self, _: &mut Token, _: ()) {} + + async fn refresh(&self, _: &()) -> Result { + let issuer = &self.issuer; + let call = issuer.calls.fetch_add(1, Ordering::SeqCst) + 1; + issuer + .attempts + .lock() + .unwrap() + .push(self.clock.now_unix_secs()); + if issuer.gated { + issuer.gate.acquire().await.unwrap().forget(); + } + if issuer + .failures + .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |n| n.checked_sub(1)) + .is_ok() + { + return Err(crate::error::ServerError("injected failure".into()).into()); + } + Ok(token( + &format!("issued-{call}"), + self.clock.now_unix_secs() + issuer.lifetime, + )) + } +} + +fn strategy( + issuer: &Arc, + clock: &SharedClock, + current: Option, +) -> AutoRefresh { + AutoRefresh::new( + IssuerRefresher { + issuer: Arc::clone(issuer), + clock: Arc::clone(clock), + }, + NoStore, + current, + Arc::clone(clock), + ) +} + +/// A token 60 seconds from expiry is inside the refresh window and still +/// works. The caller gets it at once: it neither starts nor waits for the +/// refresh, which runs in the background. +#[tokio::test(start_paused = true)] +async fn a_caller_with_a_valid_token_does_not_wait_for_its_refresh() { + let clock = clock(); + let issuer = Issuer::new(0, true); + let now = clock.now_unix_secs(); + let strategy = strategy(&issuer, &clock, Some(token("current", now + 60))); + + let got = timeout(Duration::from_secs(5), strategy.get_token()) + .await + .expect("the caller waited for a refresh its valid token did not need") + .unwrap(); + assert_eq!(got.as_str(), "current"); + + // The refresh runs without any caller waiting on it, half way through + // the token's remaining life. + issuer.gate.add_permits(1); + timeout(Duration::from_secs(35), async { + while strategy + .shared + .state + .lock() + .await + .token + .as_ref() + .unwrap() + .access_token() + .as_str() + == "current" + { + sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("the background refresh did not install a new token"); + assert_eq!(issuer.calls(), 1, "one refresh, not one per caller"); +} + +/// After a refresh fails and the token has expired, a caller fails at once +/// with that refresh's error. It does not start an exchange of its own +/// while the refresh backs off. +#[tokio::test(start_paused = true)] +async fn an_expired_token_fails_fast_while_refreshes_back_off() { + let clock = clock(); + let issuer = Issuer::new(usize::MAX, false); + let now = clock.now_unix_secs(); + let strategy = strategy(&issuer, &clock, Some(token("expired", now - 1))); + + let first = strategy.get_token().await.unwrap_err(); + assert!( + matches!(first, AutoRefreshError::Auth(AuthError::Server(_))), + "{first:?}" + ); + assert_eq!(issuer.calls(), 1); + + for _ in 0..10 { + let again = strategy.get_token().await.unwrap_err(); + assert!( + matches!(again, AutoRefreshError::Auth(AuthError::Server(_))), + "a caller during the backoff gets the last refresh error, not {again:?}" + ); + } + assert_eq!( + issuer.calls(), + 1, + "callers during the backoff started exchanges of their own" + ); +} + +/// A seed for the refresh plan of a token that expires at `expires_at`, +/// observed at `now`, whose refresh is then due `ahead` seconds before +/// expiry. +fn seed_for(expires_at: u64, now: u64, ahead: u64) -> u64 { + (0..10_000) + .find(|&seed| { + let mut plan = RefreshSchedule::with_seed(seed); + plan.observe(&token("t", expires_at), now); + let _ = plan.used(); + plan.next() == NextRefresh::At(expires_at - ahead) + }) + .expect("a seed for that jitter") +} + +/// A token in use is refreshed before it expires, with no caller asking. +/// The refresh is due 90 to 120 seconds before expiry, whatever the +/// jitter: at the latest, when the 90-second leeway starts. The plan is +/// seeded for each end of that window, so the test does not depend on +/// chance. +#[tokio::test(start_paused = true)] +async fn a_token_in_use_is_refreshed_before_it_expires() { + for ahead in [ + crate::REFRESH_AHEAD_SECS - crate::REFRESH_JITTER_SECS, + crate::REFRESH_AHEAD_SECS, + ] { + let clock = clock(); + let issuer = Issuer::new(0, false); + let now = clock.now_unix_secs(); + let strategy = strategy(&issuer, &clock, Some(token("current", now + 900))); + strategy.shared.state.try_lock().unwrap().schedule = + RefreshSchedule::with_seed(seed_for(now + 900, now, ahead)); + + assert_eq!(strategy.get_token().await.unwrap().as_str(), "current"); + sleep(Duration::from_secs(899)).await; + + assert_eq!( + issuer.calls(), + 1, + "nothing refreshed the token before it expired" + ); + let refreshed_at = issuer.attempts.lock().unwrap()[0]; + assert_eq!( + refreshed_at, + now + 900 - ahead, + "the refresh ran at {} s, not {ahead} s before expiry", + refreshed_at - now + ); + assert_eq!(strategy.get_token().await.unwrap().as_str(), "issued-1"); + } +} + +/// A token nobody has asked for since its last refresh is not refreshed +/// again, so an idle process does not call the issuer forever. +#[tokio::test(start_paused = true)] +async fn an_idle_strategy_stops_refreshing() { + let clock = clock(); + let issuer = Issuer::new(0, false); + let now = clock.now_unix_secs(); + let strategy = strategy(&issuer, &clock, Some(token("current", now + 900))); + + strategy.get_token().await.unwrap(); + sleep(Duration::from_secs(900)).await; + assert_eq!( + issuer.calls(), + 1, + "the token in use was not refreshed ahead" + ); + sleep(Duration::from_secs(10 * 900)).await; + assert_eq!(issuer.calls(), 1, "an idle strategy kept refreshing"); + + // A caller wakes it again, and its token is refreshed ahead once more. + strategy.get_token().await.unwrap(); + sleep(Duration::from_secs(900)).await; + assert_eq!(issuer.calls(), 2); +} + +/// A failed refresh is retried with growing gaps while the token is in use, +/// and a success before expiry leaves callers none the wiser. +#[tokio::test(start_paused = true)] +async fn a_failed_refresh_is_retried_with_backoff() { + let clock = clock(); + let issuer = Issuer::new(3, false); + let now = clock.now_unix_secs(); + let strategy = strategy(&issuer, &clock, Some(token("current", now + 900))); + + // A call every second keeps the token in use, so only the backoff + // spaces the retries. + for _ in 0..900 { + assert!(strategy.get_token().await.is_ok()); + sleep(Duration::from_secs(1)).await; + } + + let attempts = issuer.attempts.lock().unwrap().clone(); + assert_eq!(attempts.len(), 4, "attempts at {attempts:?}"); + let gaps: Vec = attempts.windows(2).map(|w| w[1] - w[0]).collect(); + assert!(gaps.iter().all(|&gap| gap >= 1), "no backoff: {gaps:?}"); + assert!(gaps[2] > gaps[0], "the backoff did not grow: {gaps:?}"); + assert_eq!(strategy.get_token().await.unwrap().as_str(), "issued-4"); +} + +/// Dropping the strategy stops its background refresh: nothing outlives it. +#[tokio::test(start_paused = true)] +async fn dropping_the_strategy_stops_its_background_refresh() { + let clock = clock(); + let issuer = Issuer::new(0, false); + let now = clock.now_unix_secs(); + let strategy = strategy(&issuer, &clock, Some(token("current", now + 900))); + strategy.get_token().await.unwrap(); + // Used again, so the task sleeps until the refresh is due, minutes away. + strategy.get_token().await.unwrap(); + + drop(strategy); + sleep(Duration::from_secs(1)).await; + assert_eq!( + Arc::strong_count(&issuer), + 1, + "something still holds the dropped strategy's refresher" + ); + sleep(Duration::from_secs(10 * 900)).await; + assert_eq!(issuer.calls(), 0); +} + +/// A runtime that ends takes the background task with it; a call on the +/// next runtime starts another, rather than the strategy believing one +/// still runs. +#[test] +fn a_call_on_a_new_runtime_starts_a_new_background_task() { + let runtime = || { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap() + }; + let clock: SharedClock = Arc::new(crate::clock::SystemClock); + let issuer = Issuer::new(0, false); + let now = clock.now_unix_secs(); + let strategy = strategy(&issuer, &clock, Some(token("current", now + 900))); + + let first = runtime(); + first.block_on(strategy.get_token()).unwrap(); + assert_eq!(strategy.drivers_attached(), 1); + drop(first); + assert_eq!( + strategy.drivers_attached(), + 0, + "the task ended with its runtime" + ); + + let second = runtime(); + second.block_on(strategy.get_token()).unwrap(); + assert_eq!( + strategy.drivers_attached(), + 1, + "the next call started another" + ); +} + +/// A host's driver shows nothing of the strategy it drives. +#[test] +fn a_refresh_driver_debugs_opaquely() { + let clock = Arc::new(crate::clock::SystemClock) as SharedClock; + let issuer = Issuer::new(0, false); + let strategy = strategy(&issuer, &clock, None); + assert_eq!( + format!("{:?}", strategy.drive_refresh()), + "RefreshDriver { .. }" + ); +} + +/// Dropping the strategy wakes its background task, which ends at once +/// rather than when its refresh would have been due, minutes later. On the +/// wall clock: a paused one would move to that time as soon as the test +/// waited. +#[tokio::test] +async fn dropping_the_strategy_ends_its_background_task_at_once() { + let clock: SharedClock = Arc::new(crate::clock::SystemClock); + let issuer = Issuer::new(0, false); + let now = clock.now_unix_secs(); + let strategy = strategy(&issuer, &clock, Some(token("current", now + 900))); + strategy.get_token().await.unwrap(); + strategy.get_token().await.unwrap(); + let control = Arc::clone(&strategy.shared.driver); + assert_eq!(control.attached.load(Ordering::Acquire), 1); + // Let the task run until it sleeps on the refresh's due time. + tokio::time::sleep(Duration::from_millis(50)).await; + + drop(strategy); + timeout(Duration::from_secs(5), async { + while control.attached.load(Ordering::Acquire) != 0 { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("the background task outlived its strategy"); +} + +/// The task sleeps until the refresh it read was due. A refresh made +/// meanwhile, by a host's `refresh_now` here, moves the plan on, and the +/// task does not repeat it when the old time comes. +#[tokio::test(start_paused = true)] +async fn a_refresh_made_before_the_task_wakes_is_not_repeated() { + let clock = clock(); + let issuer = Issuer::new(0, false); + let now = clock.now_unix_secs(); + let strategy = strategy(&issuer, &clock, Some(token("current", now + 900))); + strategy.get_token().await.unwrap(); + strategy.get_token().await.unwrap(); + + sleep(Duration::from_secs(600)).await; + strategy.refresh_now().await.unwrap(); + assert_eq!(issuer.calls(), 1); + + sleep(Duration::from_secs(300)).await; + assert_eq!( + issuer.calls(), + 1, + "the task refreshed again at its old time" + ); +} + +/// A refresher whose every exchange fails with the error `fail` makes. +struct FailingRefresher(fn() -> AuthError); + +impl Refresher for FailingRefresher { + type Credential = (); + + fn save(&self, _: &Token) {} + + fn try_credential(&self, _: Option<&mut Token>) -> Option<()> { + Some(()) + } + + fn restore(&self, _: &mut Token, _: ()) {} + + async fn refresh(&self, _: &()) -> Result { + Err((self.0)()) + } +} + +/// Errors a refresh can fail with, one of each kind that wraps more than +/// a fixed message. +fn refresh_failures() -> Vec AuthError> { + vec![ + || crate::error::RequestError(Box::new(std::io::Error::other("connection refused"))).into(), + || crate::error::InternalError("poisoned".into()).into(), + || crate::error::InvalidToken("malformed".into()).into(), + || { + crate::error::StoreError(stack_profile::ProfileError::Io(std::io::Error::from( + std::io::ErrorKind::PermissionDenied, + ))) + .into() + }, + || { + crate::error::WorkspaceMismatch { + expected_workspace: "ZVATKW3VHMFG27DY".parse().unwrap(), + token_workspace: "AAAAAAAAAAAAAAAA".parse().unwrap(), + } + .into() + }, + ] +} + +fn assert_same_error(replayed: &AuthError, original: &AuthError) { + use miette::Diagnostic; + assert_eq!(replayed.error_code(), original.error_code(), "{replayed:?}"); + assert_eq!(replayed.to_string(), original.to_string()); + assert_eq!( + replayed.code().map(|c| c.to_string()), + original.code().map(|c| c.to_string()) + ); + assert_eq!(replayed.is_retryable(), original.is_retryable()); +} + +/// While a failed refresh backs off, a caller with an expired token gets +/// that refresh's error again. The replay is the same kind of error: a +/// transport failure stays one, so a caller that retries on it still does. +#[tokio::test(start_paused = true)] +async fn a_replayed_refresh_error_keeps_its_kind() { + for fail in refresh_failures() { + let clock = clock(); + let now = clock.now_unix_secs(); + let strategy = AutoRefresh::new( + FailingRefresher(fail), + NoStore, + Some(token("expired", now - 1)), + Arc::clone(&clock), + ); + let original = fail(); + let Err(AutoRefreshError::Auth(first)) = strategy.get_token().await else { + panic!("the first caller did not get the refresh's error"); + }; + assert_same_error(&first, &original); + let Err(AutoRefreshError::Auth(again)) = strategy.get_token().await else { + panic!("a caller during the backoff did not get the refresh's error"); + }; + assert_same_error(&again, &original); + } +} + +/// `refresh_now` reports its own attempt's error, of the same kind, even +/// when the cached token still works. +#[tokio::test(start_paused = true)] +async fn refresh_now_reports_its_own_error() { + for fail in refresh_failures() { + let clock = clock(); + let now = clock.now_unix_secs(); + let strategy = AutoRefresh::new( + FailingRefresher(fail), + NoStore, + Some(token("current", now + 600)), + Arc::clone(&clock), + ); + let Err(AutoRefreshError::Auth(err)) = strategy.refresh_now().await else { + panic!("refresh_now did not report the failure"); + }; + assert_same_error(&err, &fail()); + } +} + +/// A failed explicit refresh must not leave an overlong stored token usable. +/// A token at the lifetime cap remains a valid fallback during the backoff. +#[tokio::test(start_paused = true)] +async fn refresh_now_distrusts_overlong_stored_tokens_after_failure() { + let clock = clock(); + let cap = clock.now_unix_secs() + crate::token::MAX_TOKEN_LIFETIME_SECS; + for expires_at in [cap, cap + 1, u64::MAX] { + let issuer = Issuer::new(1, false); + let store = crate::InMemoryTokenStore::new(); + store.save(&token("stored", expires_at)).await; + let strategy = AutoRefresh::new( + IssuerRefresher { + issuer: Arc::clone(&issuer), + clock: Arc::clone(&clock), + }, + store, + None, + Arc::clone(&clock), + ) + .refreshed_by_calls(); + + assert!(matches!( + strategy.refresh_now().await, + Err(AutoRefreshError::Auth(AuthError::Server(_))) + )); + let got = strategy.get_token().await; + if expires_at == cap { + assert_eq!(got.unwrap().as_str(), "stored"); + } else { + assert!( + matches!(got, Err(AutoRefreshError::Auth(AuthError::Server(_)))), + "an overlong token must not be returned after a failed refresh" + ); + } + assert_eq!(issuer.calls(), 1, "calls must respect the refresh backoff"); + } +} + +/// A refresher that fails with a server fault after a second of +/// (virtual) time. +struct SlowFailingRefresher; + +impl Refresher for SlowFailingRefresher { + type Credential = (); + + fn save(&self, _: &Token) {} + + fn try_credential(&self, _: Option<&mut Token>) -> Option<()> { + Some(()) + } + + fn restore(&self, _: &mut Token, _: ()) {} + + async fn refresh(&self, _: &()) -> Result { + sleep(Duration::from_secs(1)).await; + Err(crate::error::ServerError("injected failure".into()).into()) + } +} + +/// A refresh that fails just as the cached token expires leaves the caller +/// nothing to use: it gets the refresh's error, not the expired token. +#[tokio::test(start_paused = true)] +async fn a_refresh_that_fails_as_the_token_expires_reports_its_error() { + let clock = clock(); + let now = clock.now_unix_secs(); + let strategy = AutoRefresh::new( + SlowFailingRefresher, + NoStore, + Some(token("current", now + 1)), + Arc::clone(&clock), + ) + .refreshed_by_calls(); + let result = strategy.get_token().await; + assert!( + matches!(result, Err(AutoRefreshError::Auth(AuthError::Server(_)))), + "{:?}", + result.map(|token| token.as_str().to_owned()) + ); +} + +/// After a quiet period, nothing has refreshed the token. A call that finds +/// it with less than the refresh floor left refreshes it, rather than get +/// back a token with 2 seconds to live. +#[tokio::test(start_paused = true)] +async fn a_call_under_the_floor_after_a_quiet_period_refreshes() { + let clock = clock(); + let issuer = Issuer::new(0, false); + let now = clock.now_unix_secs(); + let strategy = strategy(&issuer, &clock, Some(token("current", now + 900))); + + // One use: the token is refreshed ahead once. The plan is then idle + // until the next call. + strategy.get_token().await.unwrap(); + sleep(Duration::from_secs(900)).await; + assert_eq!(issuer.calls(), 1); + let issued_1_expires = issuer.attempts.lock().unwrap()[0] + 900; + let left = issued_1_expires - clock.now_unix_secs(); + sleep(Duration::from_secs(left - 2)).await; + assert_eq!(issuer.calls(), 1, "an idle strategy refreshed"); + + let got = strategy.get_token().await.unwrap(); + assert_eq!( + got.as_str(), + "issued-2", + "the call got the token with 2 s left" + ); +} + +/// A current-thread runtime driven only by `block_on(get_token())` never +/// runs the background task: each call is ready at once. Under the floor a +/// call refreshes the token itself. +#[test] +fn a_block_on_caller_gets_a_fresh_token_under_the_floor() { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + let test_clock = crate::clock::TestClock::new(1_000_000); + let clock = test_clock.shared(); + let issuer = Issuer::new(0, false); + let strategy = strategy(&issuer, &clock, Some(token("current", 1_000_000 + 900))); + assert_eq!(strategy.refresh_floor(), crate::REFRESH_FLOOR_SECS); + + for _ in 0..3 { + let got = runtime.block_on(strategy.get_token()).unwrap(); + assert_eq!(got.as_str(), "current"); + } + // Inside the 90-second window, above the floor: the cached token. + test_clock.set(1_000_000 + 900 - 60); + let got = runtime.block_on(strategy.get_token()).unwrap(); + assert_eq!(got.as_str(), "current"); + assert_eq!(issuer.calls(), 0, "the background task never ran"); + // Under the floor: a fresh token. + test_clock.set(1_000_000 + 900 - 10); + let got = runtime.block_on(strategy.get_token()).unwrap(); + assert_eq!(got.as_str(), "issued-1"); +} + +/// A configured floor is the one applied. Under a 70-second floor, a token +/// with 60 seconds left is refreshed. Under a 10-second floor, a token with +/// 20 seconds left is not. +#[tokio::test(start_paused = true)] +async fn a_configured_floor_is_honoured() { + let clock = clock(); + let now = clock.now_unix_secs(); + + let issuer = Issuer::new(0, false); + let higher = strategy(&issuer, &clock, Some(token("current", now + 60))); + higher.set_refresh_floor(Duration::from_secs(70)); + assert_eq!(higher.get_token().await.unwrap().as_str(), "issued-1"); + + let issuer = Issuer::new(0, true); + let lower = strategy(&issuer, &clock, Some(token("current", now + 20))); + lower.set_refresh_floor(Duration::from_secs(10)); + let got = timeout(Duration::from_secs(5), lower.get_token()) + .await + .expect("the caller waited above its floor") + .unwrap(); + assert_eq!(got.as_str(), "current"); +} + +/// A floor is whole seconds, rounded up. Zero turns it off, and a floor +/// longer than the 90-second refresh window acts as the window. +#[test] +fn a_floor_out_of_range_is_bounded() { + let floor = |d| crate::auto_refresh::refresh_floor_secs(d); + assert_eq!(floor(Duration::ZERO), 0); + assert_eq!(floor(Duration::from_millis(1)), 1); + assert_eq!(floor(Duration::from_millis(30_500)), 31); + assert_eq!(floor(Duration::from_secs(90)), 90); + assert_eq!(floor(Duration::from_secs(91)), 90); + assert_eq!(floor(Duration::MAX), 90); +} + +/// With the floor off, a call never waits while its token still works, +/// even with a second left. +#[tokio::test(start_paused = true)] +async fn a_zero_floor_never_makes_a_call_wait() { + let clock = clock(); + let now = clock.now_unix_secs(); + let issuer = Issuer::new(0, true); + let strategy = strategy(&issuer, &clock, Some(token("current", now + 1))); + strategy.set_refresh_floor(Duration::ZERO); + let got = timeout(Duration::from_secs(5), strategy.get_token()) + .await + .expect("the caller waited with the floor off") + .unwrap(); + assert_eq!(got.as_str(), "current"); +} + +/// Under the floor, a call waits for the refresh already running rather +/// than get back the old token. +#[tokio::test(start_paused = true)] +async fn a_call_under_the_floor_waits_for_the_refresh_in_flight() { + let clock = clock(); + let now = clock.now_unix_secs(); + let issuer = Issuer::new(0, true); + let strategy = Arc::new(strategy(&issuer, &clock, Some(token("current", now + 10)))); + let first = tokio::spawn({ + let strategy = Arc::clone(&strategy); + async move { strategy.get_token().await.unwrap() } + }); + // Let the first call start its refresh. + refresh_started(&strategy).await; + let second = tokio::spawn({ + let strategy = Arc::clone(&strategy); + async move { strategy.get_token().await.unwrap() } + }); + sleep(Duration::from_millis(100)).await; + assert!(!second.is_finished(), "the second call got the old token"); + issuer.gate.add_permits(1); + assert_eq!(first.await.unwrap().as_str(), "issued-1"); + assert_eq!(second.await.unwrap().as_str(), "issued-1"); + assert_eq!(issuer.calls(), 1); +} + +/// A token that lasts 60 seconds, as a short-lived identity token can, is +/// inside the 90-second window from the moment it arrives. Its background +/// refresh is due half way through its life. With the default floor, that +/// is also when calls start refreshing. A call every second for ten +/// minutes never gets a token with less than the floor left. The token is +/// exchanged about once every 30 seconds, not once a call. +#[tokio::test(start_paused = true)] +async fn a_60_second_token_is_refreshed_about_once_every_30_seconds() { + let clock = clock(); + let issuer = Arc::new(Issuer { + calls: AtomicUsize::new(0), + failures: AtomicUsize::new(0), + gated: false, + gate: Semaphore::new(0), + lifetime: 60, + attempts: StdMutex::new(Vec::new()), + }); + let strategy = strategy(&issuer, &clock, None); + + for _ in 0..600 { + let got = strategy.get_token().await.unwrap(); + let n: usize = got.as_str().trim_start_matches("issued-").parse().unwrap(); + let expires_at = issuer.attempts.lock().unwrap()[n - 1] + 60; + let left = expires_at - clock.now_unix_secs(); + assert!( + left >= crate::REFRESH_FLOOR_SECS, + "a call got a token with {left} s left" + ); + sleep(Duration::from_secs(1)).await; + } + let exchanges = issuer.calls(); + assert!( + (19..=22).contains(&exchanges), + "{exchanges} exchanges in 600 s" + ); +} + +/// The floor applies only to a strategy with a background task or a host +/// driving its refresh. An engine refreshed by calls, as an OIDC engine +/// is, works as before. A call in the 90-second window refreshes, whatever +/// the floor. A call during that refresh gets the token while it still +/// works. +#[tokio::test(start_paused = true)] +async fn the_floor_does_not_change_an_engine_refreshed_by_calls() { + let clock = clock(); + let now = clock.now_unix_secs(); + let issuer = Issuer::new(0, true); + let strategy = + Arc::new(strategy(&issuer, &clock, Some(token("current", now + 60))).refreshed_by_calls()); + let first = tokio::spawn({ + let strategy = Arc::clone(&strategy); + async move { strategy.get_token().await.unwrap() } + }); + refresh_started(&strategy).await; + clock_forward_to(&clock, now + 50).await; + let second = timeout(Duration::from_secs(1), strategy.get_token()) + .await + .expect("a call during the refresh waited") + .unwrap(); + assert_eq!(second.as_str(), "current"); + issuer.gate.add_permits(1); + assert_eq!(first.await.unwrap().as_str(), "issued-1"); +} + +/// Sleep until `clock` reads `at`. +async fn clock_forward_to(clock: &SharedClock, at: u64) { + let now = clock.now_unix_secs(); + sleep(Duration::from_secs(at.saturating_sub(now))).await; +} + +/// Wait until a refresh of `strategy` is in flight. Fail after a second of +/// virtual time if none starts: a test whose call never refreshes then +/// fails rather than hangs. +async fn refresh_started(strategy: &AutoRefresh) { + timeout(Duration::from_secs(1), async { + while !strategy.shared.refresh_in_progress.load(Ordering::Acquire) { + sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("no refresh started"); +} + +/// A token with exactly the floor left is still above it: the call gets it +/// at once. One second less, and the call refreshes it. +#[tokio::test(start_paused = true)] +async fn a_token_exactly_at_the_floor_is_handed_out() { + let clock = clock(); + let now = clock.now_unix_secs(); + let floor = crate::REFRESH_FLOOR_SECS; + + let issuer = Issuer::new(0, true); + let at = strategy(&issuer, &clock, Some(token("current", now + floor))); + let got = timeout(Duration::from_secs(1), at.get_token()) + .await + .expect("the caller waited with exactly the floor left") + .unwrap(); + assert_eq!(got.as_str(), "current"); + + let issuer = Issuer::new(0, false); + let under = strategy(&issuer, &clock, Some(token("current", now + floor - 1))); + let got = timeout(Duration::from_secs(1), under.get_token()) + .await + .expect("the refresh did not finish") + .unwrap(); + assert_eq!(got.as_str(), "issued-1"); +} diff --git a/packages/stack-auth/src/auto_refresh/tests/cancellation.rs b/packages/stack-auth/src/auto_refresh/tests/cancellation.rs index 61fae44513..ad7d9a60e0 100644 --- a/packages/stack-auth/src/auto_refresh/tests/cancellation.rs +++ b/packages/stack-auth/src/auto_refresh/tests/cancellation.rs @@ -1,5 +1,9 @@ //! Cancellation must leave the rotating session usable, including after the //! issuer has spent the old credential. Gates pin each await without sleeps. +//! +//! Every engine here is call-driven: a caller starts each refresh, as on +//! wasm32 with no host driving it, so the caller's cancellation is what is +//! tested. #![allow(clippy::unwrap_used)] use super::*; @@ -9,6 +13,15 @@ use std::sync::atomic::AtomicUsize; use std::time::Duration; use tokio::sync::Semaphore; +/// A gate's wait, bounded: a refresh that never reaches the gate fails +/// the test instead of hanging it. Time is paused, so the bound passes as +/// soon as nothing else can run. +async fn within(gate: F) -> F::Output { + tokio::time::timeout(Duration::from_secs(600), gate) + .await + .expect("the refresh never reached this gate") +} + fn token(generation: usize, expires_at: u64) -> Token { Token { access_token: SecretToken::new(format!("access-{generation}")), @@ -139,24 +152,27 @@ async fn cancelled_at_unbounded(phase: Phase, usable: bool, initial: bool) { save: Semaphore::new(0), saved: AtomicUsize::new(0), }); - let strategy = Arc::new(AutoRefresh::new( - RotatingRefresher(issuer.clone()), - store.clone(), - (!initial).then(|| token(0, if usable { 1_030 } else { 999 })), - clock.shared(), - )); + let strategy = Arc::new( + AutoRefresh::new( + RotatingRefresher(issuer.clone()), + store.clone(), + (!initial).then(|| token(0, if usable { 1_030 } else { 999 })), + clock.shared(), + ) + .refreshed_by_calls(), + ); let caller = tokio::spawn({ let strategy = strategy.clone(); async move { strategy.get_token().await } }); - issuer.started.notified().await; + within(issuer.started.notified()).await; if !matches!(phase, Phase::Exchange) { issuer.exchange.add_permits(1); - issuer.answered.notified().await; + within(issuer.answered.notified()).await; } if matches!(phase, Phase::SaveStore | Phase::Install) { issuer.persist.add_permits(1); - store.entered.notified().await; + within(store.entered.notified()).await; } // Only the non-blocking path releases the state lock during the exchange. let held = if matches!(phase, Phase::Install) { @@ -242,16 +258,19 @@ async fn cancelled_failed_refresh_restores_the_credential_for_retry() { let clock = TestClock::new(1_000); let issuer = Arc::new(Issuer::new(false)); issuer.fail_once.store(true, Ordering::SeqCst); - let strategy = Arc::new(AutoRefresh::with_token_and_clock( - RotatingRefresher(issuer.clone()), - token(0, if usable { 1_030 } else { 999 }), - clock.shared(), - )); + let strategy = Arc::new( + AutoRefresh::with_token_and_clock( + RotatingRefresher(issuer.clone()), + token(0, if usable { 1_030 } else { 999 }), + clock.shared(), + ) + .refreshed_by_calls(), + ); let caller = tokio::spawn({ let strategy = strategy.clone(); async move { strategy.get_token().await } }); - issuer.started.notified().await; + within(issuer.started.notified()).await; caller.abort(); assert!(caller.await.unwrap_err().is_cancelled()); issuer.exchange.add_permits(1); @@ -270,15 +289,18 @@ async fn cancelled_failed_refresh_restores_the_credential_for_retry() { #[tokio::test(start_paused = true)] async fn rotation_is_saved_even_after_all_callers_drop_the_strategy() { let issuer = Arc::new(Issuer::new(false)); - let strategy = Arc::new(AutoRefresh::with_token_and_clock( - RotatingRefresher(issuer.clone()), - token(0, 999), - TestClock::new(1_000).shared(), - )); + let strategy = Arc::new( + AutoRefresh::with_token_and_clock( + RotatingRefresher(issuer.clone()), + token(0, 999), + TestClock::new(1_000).shared(), + ) + .refreshed_by_calls(), + ); let caller = tokio::spawn(async move { strategy.get_token().await }); - issuer.started.notified().await; + within(issuer.started.notified()).await; issuer.exchange.add_permits(1); - issuer.answered.notified().await; + within(issuer.answered.notified()).await; caller.abort(); assert!(caller.await.unwrap_err().is_cancelled()); issuer.persist.add_permits(1); @@ -296,16 +318,19 @@ async fn rotation_is_saved_even_after_all_callers_drop_the_strategy() { async fn a_panicking_refresh_reports_an_error_and_releases_waiters() { let issuer = Arc::new(Issuer::new(false)); let clock = TestClock::new(1_000); - let strategy = Arc::new(AutoRefresh::with_token_and_clock( - RotatingRefresher(issuer.clone()), - token(0, 1_030), - clock.shared(), - )); + let strategy = Arc::new( + AutoRefresh::with_token_and_clock( + RotatingRefresher(issuer.clone()), + token(0, 1_030), + clock.shared(), + ) + .refreshed_by_calls(), + ); let caller = tokio::spawn({ let strategy = strategy.clone(); async move { strategy.get_token().await } }); - issuer.started.notified().await; + within(issuer.started.notified()).await; clock.advance(31); let waiter = tokio::spawn({ let strategy = strategy.clone(); @@ -331,7 +356,8 @@ async fn guard_notification_before_waiter_registration_is_not_lost() { RotatingRefresher(Arc::new(Issuer::new(false))), token(0, 999), TestClock::new(1_000).shared(), - ); + ) + .refreshed_by_calls(); let shared = &strategy.shared; let state = shared.state.clone().lock_owned().await; shared.refresh_in_progress.store(true, Ordering::Release); diff --git a/packages/stack-auth/src/auto_refresh/tests/soak.rs b/packages/stack-auth/src/auto_refresh/tests/soak.rs index 5746f95dfb..84c8ea0b6f 100644 --- a/packages/stack-auth/src/auto_refresh/tests/soak.rs +++ b/packages/stack-auth/src/auto_refresh/tests/soak.rs @@ -1,5 +1,11 @@ //! Seeded cancellation soak. No credentials or network needed. //! +//! Each seed runs twice: with the background task that refreshes ahead of +//! expiry (the native default), and call-driven, where callers start every +//! refresh (as on wasm32 with no host driving it), so callers' cancellation +//! still reaches every phase of a refresh. Injected failures exercise the +//! backoff in both. +//! //! The seeded runs use a current-thread runtime with paused time, so a seed //! replays exactly. That cannot interleave callers across worker threads, so //! a short run on a multi-thread runtime in real time, sped up by [`Pace`], @@ -43,9 +49,11 @@ impl Pace { /// The bound within which a caller must get a token or give up. Paced /// runs share real CPUs with the rest of the suite, so they get a fixed /// real-time bound instead of a scaled one that a busy runner could miss. + /// A caller whose token expired while refreshes fail waits out their + /// backoff, so the bound allows for its cap. fn stranded_after(self) -> Duration { if self.0 == 1 { - Duration::from_secs(30) + Duration::from_secs(30 + crate::BACKOFF_CAP_SECS) } else { Duration::from_secs(10) } @@ -155,6 +163,11 @@ impl TokenStore for RotationStore { } async fn soak(seed: u64, rounds: usize, pace: Pace) { + soak_with(seed, rounds, pace, true).await; + soak_with(seed, rounds, pace, false).await; +} + +async fn soak_with(seed: u64, rounds: usize, pace: Pace, driven: bool) { let clock: SharedClock = Arc::new(PacedClock(Instant::now(), pace)); let idp = Arc::new(StdMutex::new(IdentityProvider { random: Random(seed), @@ -164,7 +177,7 @@ async fn soak(seed: u64, rounds: usize, pace: Pace) { saved: 0, errors: 0, })); - let strategy = Arc::new(AutoRefresh::new( + let strategy = AutoRefresh::new( RotatingRefresher { idp: idp.clone(), clock: clock.clone(), @@ -173,7 +186,12 @@ async fn soak(seed: u64, rounds: usize, pace: Pace) { RotationStore(idp.clone(), pace), Some(token(0, clock.now_unix_secs())), clock.clone(), - )); + ); + let strategy = Arc::new(if driven { + strategy + } else { + strategy.refreshed_by_calls() + }); let mut callers = JoinSet::new(); for caller in 1..=256 { let strategy = strategy.clone(); @@ -289,7 +307,7 @@ async fn soak(seed: u64, rounds: usize, pace: Pace) { // Test-only progress counters make the long CI run's coverage reviewable. #[allow(clippy::print_stderr)] { - eprintln!("seed={seed}, rotations={}, injected_errors={}, completed={completed}, timeouts={timed_out}, select_cancels={selected_out}", idp.generation, idp.errors); + eprintln!("seed={seed}, driven={driven}, rotations={}, injected_errors={}, completed={completed}, timeouts={timed_out}, select_cancels={selected_out}", idp.generation, idp.errors); } } @@ -303,7 +321,11 @@ async fn cancellation_soak_short() { /// floor; it exists to interleave callers in ways one thread cannot. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn cancellation_soak_multi_thread() { - soak(0x1170, 8, Pace(100)).await; + // A run takes a few seconds. One that slows past this bound fails + // rather than hang the suite. + timeout(Duration::from_secs(30), soak(0x1170, 8, Pace(100))) + .await + .expect("the soak did not finish"); } #[tokio::test(start_paused = true)] diff --git a/packages/stack-auth/src/device_session_strategy.rs b/packages/stack-auth/src/device_session_strategy.rs index eee2704a7e..4f145474f8 100644 --- a/packages/stack-auth/src/device_session_strategy.rs +++ b/packages/stack-auth/src/device_session_strategy.rs @@ -59,6 +59,7 @@ impl DeviceSessionStrategy { base_url_override: None, transport: None, expected_workspace: None, + refresh_floor: std::time::Duration::from_secs(crate::REFRESH_FLOOR_SECS), } } @@ -76,6 +77,7 @@ impl DeviceSessionStrategy { base_url_override: None, transport: None, expected_workspace: None, + refresh_floor: std::time::Duration::from_secs(crate::REFRESH_FLOOR_SECS), } } @@ -90,6 +92,7 @@ impl DeviceSessionStrategy { base_url_override: None, transport: None, expected_workspace: None, + refresh_floor: std::time::Duration::from_secs(crate::REFRESH_FLOOR_SECS), } } @@ -99,6 +102,16 @@ impl DeviceSessionStrategy { } } +impl DeviceSessionStrategy { + /// Refresh the token now, for a host that keeps the refresh timer + /// itself. A refresh already in flight is not repeated. Returns this + /// attempt's error. While the cached token still works, `get_token` + /// does not return that error. The next attempt backs off. + pub async fn refresh_now(&self) -> Result<(), AuthError> { + self.inner.refresh_now().await.map_err(AuthError::from) + } +} + impl AuthStrategy for &DeviceSessionStrategy { async fn get_token(self) -> Result { let token = self.inner.get_token().await?; @@ -130,6 +143,7 @@ pub struct DeviceSessionStrategyBuilder { base_url_override: Option, transport: Option, expected_workspace: Option, + refresh_floor: std::time::Duration, } impl DeviceSessionStrategyBuilder { @@ -178,6 +192,30 @@ impl DeviceSessionStrategyBuilder { /// CTS, or a local mock auth server in development — without relying on the /// process-wide `CS_CTS_HOST`, which would redirect every other CTS client /// sharing the process. + /// Set the refresh floor: once the token has less than `floor` left, + /// the call that gets it refreshes it first. So the call does not get + /// back a token that may expire before the request using it is sent. + /// Defaults to [`REFRESH_FLOOR_SECS`](crate::REFRESH_FLOOR_SECS), 30 + /// seconds. + /// + /// Above the floor, a call gets the token at once while the background + /// task refreshes it. Below it, the call refreshes the token itself, or + /// waits for the refresh already running. + /// + /// The floor is whole seconds, rounded up. Zero turns it off: a call + /// never waits while its token still works. A floor longer than the + /// 90-second refresh window acts as the window. + /// + /// For short-lived tokens, keep the floor at or below half the token's + /// lifetime. The background refresh of a short-lived token is due half + /// way through its life, so with a larger floor calls start waiting + /// before it runs. Raise the floor if the requests that use a token can + /// take longer than 30 seconds to reach the server. + pub fn refresh_floor(mut self, floor: std::time::Duration) -> Self { + self.refresh_floor = floor; + self + } + pub fn base_url(mut self, url: url::Url) -> Self { self.base_url_override = Some(url); self @@ -196,9 +234,10 @@ impl DeviceSessionStrategyBuilder { base_url_override, transport, expected_workspace, + refresh_floor, } = self; let transport = transport::resolve(transport)?; - match source { + let strategy = match source { OAuthTokenSource::Token { region, client_id, @@ -229,7 +268,9 @@ impl DeviceSessionStrategyBuilder { transport, expected_workspace, ), - } + }?; + strategy.inner.set_refresh_floor(refresh_floor); + Ok(strategy) } /// Build from a token supplied directly (in-memory only, no store). @@ -426,3 +467,72 @@ mod tests { .expect("matching workspace should pass"); } } + +/// The calls a host with no background task makes to refresh ahead of +/// expiry. +#[cfg(test)] +#[cfg(feature = "http")] +mod host_refresh_tests { + use super::*; + use crate::test_support::raw_token; + use mocktail::prelude::*; + + #[allow(clippy::expect_used)] + async fn session(issues: bool) -> (MockServer, DeviceSessionStrategy) { + let mut mocks = MockSet::new(); + mocks.mock(move |when, then| { + when.post().path("/oauth/token"); + if issues { + then.json(serde_json::json!({ + "access_token": "refreshed", + "token_type": "Bearer", + "expires_in": 3600, + "refresh_token": "refresh-2", + })); + } else { + then.internal_server_error(); + } + }); + let server = MockServer::new_http("device-session-host-refresh").with_mocks(mocks); + server.start().await.expect("mock server start"); + let region = Region::aws("ap-southeast-2").expect("valid region"); + let strategy = DeviceSessionStrategy::with_token(region, "my-client", raw_token("current")) + .base_url(server.url("")) + .build() + .expect("build"); + (server, strategy) + } + + /// The builder's refresh floor reaches the engine. + #[test] + #[allow(clippy::expect_used)] + fn the_builder_sets_the_refresh_floor() { + let build = |floor: Option| { + let region = Region::aws("ap-southeast-2").expect("valid region"); + let mut builder = + DeviceSessionStrategy::with_token(region, "my-client", raw_token("current")) + .base_url("https://cts.example/".parse().expect("url")); + if let Some(secs) = floor { + builder = builder.refresh_floor(std::time::Duration::from_secs(secs)); + } + builder.build().expect("build") + }; + assert_eq!(build(None).inner.refresh_floor(), crate::REFRESH_FLOOR_SECS); + assert_eq!(build(Some(10)).inner.refresh_floor(), 10); + } + + #[tokio::test] + #[allow(clippy::expect_used)] + async fn refresh_now_refreshes_and_reports_a_failure() { + let (_server, strategy) = session(true).await; + strategy + .refresh_now() + .await + .expect("a refresh that succeeds"); + let token = (&strategy).get_token().await.expect("get_token"); + assert_eq!(token.as_str(), "refreshed"); + + let (_server, strategy) = session(false).await; + assert!(strategy.refresh_now().await.is_err(), "a server fault"); + } +} diff --git a/packages/stack-auth/src/error.rs b/packages/stack-auth/src/error.rs index facf3b9384..3dc67c3c82 100644 --- a/packages/stack-auth/src/error.rs +++ b/packages/stack-auth/src/error.rs @@ -851,6 +851,199 @@ impl AuthError { } } +impl AuthError { + /// Another error equal to this one: the same variant, codes, message, + /// help and fields, for an error handed to more than one caller (a + /// failed refresh's, say). `AuthError` is not `Clone`, because some + /// variants wrap another library's error, so each is rebuilt: + /// + /// - a transport's error, the source of a [`RequestError`], comes back + /// as its text, cause by cause; + /// - an I/O error keeps its kind, and its OS error code if it had one; + /// - a profile file's JSON error keeps its kind of error, but not where + /// in the file it was. Its text is never copied: it can quote the + /// file, and a profile file contains a token. + pub(crate) fn replay(&self) -> Self { + match self { + // Variants with a fixed message, and `Custom`, rebuild exactly + // from their code and message. + Self::AccessDenied(_) + | Self::InvalidGrant(_) + | Self::InvalidClient(_) + | Self::MissingWorkspaceCrn(_) + | Self::NotAuthenticated(_) + | Self::TokenExpired(_) + | Self::AlreadyConsumed(_) + | Self::Custom(_) => self.replay_by_code(), + Self::Request(e) => RequestError(replay_transport_error(&*e.0)).into(), + Self::InvalidUrl(InvalidUrl(e)) => InvalidUrl(*e).into(), + Self::Region(UnsupportedRegion(e)) => UnsupportedRegion(replay_region(e)).into(), + Self::InvalidCrn(InvalidCrn(e)) => self.replay_crn(e), + Self::WorkspaceMismatch(e) => WorkspaceMismatch { + expected_workspace: e.expected_workspace, + token_workspace: e.token_workspace, + } + .into(), + Self::InvalidWorkspaceId(InvalidWorkspaceId(e)) => match replay_workspace_id(e) { + Some(e) => InvalidWorkspaceId(e).into(), + None => self.replay_by_code(), + }, + Self::InvalidAccessKey(InvalidAccessKeyError(e)) => { + InvalidAccessKeyError(replay_access_key(e)).into() + } + Self::InvalidToken(InvalidToken(message)) => InvalidToken(message.clone()).into(), + Self::UsageLimitExceeded(UsageLimitExceeded(message)) => { + UsageLimitExceeded(message.clone()).into() + } + Self::OrgNotProvisioned(OrgNotProvisioned(message)) => { + OrgNotProvisioned(message.clone()).into() + } + Self::Server(ServerError(message)) => ServerError(message.clone()).into(), + Self::Internal(InternalError(message)) => InternalError(message.clone()).into(), + Self::Store(StoreError(e)) => match replay_profile_error(e) { + Some(e) => StoreError(e).into(), + None => self.replay_by_code(), + }, + } + } + + /// [`replay`](Self::replay) for an `InvalidCrn` error, which wraps `e`. + fn replay_crn(&self, e: &cts_common::InvalidCrn) -> Self { + use cts_common::InvalidCrn as C; + match e { + C::InvalidFormat(input) => InvalidCrn(C::InvalidFormat(input.clone())).into(), + C::InvalidRegion(e) => InvalidCrn(C::InvalidRegion(replay_region(e))).into(), + C::InvalidWorkspaceId(e) => match replay_workspace_id(e) { + Some(e) => InvalidCrn(C::InvalidWorkspaceId(e)).into(), + None => self.replay_by_code(), + }, + } + } + + /// The error rebuilt from its code, message, and fields, for a wrapped + /// error that cannot be rebuilt itself. + fn replay_by_code(&self) -> Self { + Self::from_error_code(self.error_code(), self.to_string(), &self.payload()) + } +} + +/// A transport's error, replayed as its text: the error, then each cause. +#[derive(Debug)] +struct ReplayedCause { + message: String, + source: Option>, +} + +impl std::fmt::Display for ReplayedCause { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.message) + } +} + +impl std::error::Error for ReplayedCause { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + self.source + .as_deref() + .map(|cause| cause as &(dyn std::error::Error + 'static)) + } +} + +/// How many causes of a transport's error are replayed, after the error +/// itself. A chain this long is a loop or a bug. +const MAX_REPLAYED_CAUSES: usize = 16; + +/// The source of a [`RequestError`], rebuilt for [`AuthError::replay`]. +fn replay_transport_error( + error: &(dyn std::error::Error + Send + Sync + 'static), +) -> Box { + #[cfg(not(feature = "http"))] + if error.is::() { + return Box::new(crate::transport::NoTransport); + } + let mut causes = Vec::new(); + let mut next = error.source(); + while let Some(cause) = next { + if causes.len() == MAX_REPLAYED_CAUSES { + break; + } + causes.push(cause.to_string()); + next = cause.source(); + } + let source = causes.into_iter().rev().fold(None, |source, message| { + Some(Box::new(ReplayedCause { message, source })) + }); + Box::new(ReplayedCause { + message: error.to_string(), + source, + }) +} + +fn replay_access_key(error: &access_key::InvalidAccessKey) -> access_key::InvalidAccessKey { + use access_key::InvalidAccessKey as K; + match error { + K::MissingPrefix => K::MissingPrefix, + K::MissingDot => K::MissingDot, + K::EmptyKeyId => K::EmptyKeyId, + K::EmptySecret => K::EmptySecret, + } +} + +fn replay_region(error: &cts_common::RegionError) -> cts_common::RegionError { + match error { + cts_common::RegionError::InvalidRegion(input) => { + cts_common::RegionError::InvalidRegion(input.clone()) + } + cts_common::RegionError::InvalidHostFqdn(input) => { + cts_common::RegionError::InvalidHostFqdn(input.clone()) + } + } +} + +/// `cts_common::InvalidWorkspaceId` keeps the refused text private, and +/// shows it after a fixed prefix. Parsing that text again refuses it the +/// same way. `None` if the prefix has changed, or the text now parses. +fn replay_workspace_id( + error: &cts_common::InvalidWorkspaceId, +) -> Option { + let shown = error.to_string(); + let input = shown.strip_prefix("Invalid workspace ID: ")?; + input.parse::().err() +} + +/// A profile error rebuilt for [`AuthError::replay`], or `None` for a +/// variant added to `stack_profile` since. +fn replay_profile_error( + error: &stack_profile::ProfileError, +) -> Option { + use stack_profile::ProfileError as P; + Some(match error { + P::Io(e) => P::Io(match e.raw_os_error() { + Some(code) => std::io::Error::from_raw_os_error(code), + None => std::io::Error::from(e.kind()), + }), + P::Json(e) => P::Json(replay_json_error(e)?), + P::HomeDirNotFound => P::HomeDirNotFound, + P::NotFound { path } => P::NotFound { path: path.clone() }, + P::InvalidFilename(name) => P::InvalidFilename(name.clone()), + P::NoCurrentWorkspace => P::NoCurrentWorkspace, + P::InvalidWorkspaceId(id) => P::InvalidWorkspaceId(id.clone()), + P::WorkspaceNotFound(id) => P::WorkspaceNotFound(id.clone()), + _ => return None, + }) +} + +/// A JSON error of the same kind as `error`, at no particular position. +/// `None` only if serde_json stops refusing the two inputs below. +fn replay_json_error(error: &serde_json::Error) -> Option { + use serde_json::error::Category; + Some(match error.classify() { + Category::Io => serde_json::Error::io(std::io::Error::other("replayed")), + Category::Syntax => serde_json::from_str::("!").err()?, + Category::Eof => serde_json::from_str::("").err()?, + Category::Data => ::custom("replayed"), + }) +} + /// `message.trim()`, or `default` if that's blank — the shared fallback for /// the account-refusal codes in [`AuthError::from_error_code`], so an empty /// message never produces a blank `Display` and the two codes can't drift @@ -1655,6 +1848,147 @@ mod tests { ] } + /// Everything a caller can read from an error, for comparing an error + /// with its replay: the codes, message, help, fields, how it is + /// classified, and the text of each cause. + fn readable(error: &AuthError) -> String { + use miette::Diagnostic; + let mut causes = Vec::new(); + let mut next = std::error::Error::source(error); + while let Some(cause) = next { + causes.push(cause.to_string()); + next = cause.source(); + } + format!( + "{} {:?} {error} {:?} {:?} {} {} {} {causes:?}", + error.error_code(), + error.code().map(|c| c.to_string()), + error.help().map(|h| h.to_string()), + error.payload(), + error.is_retryable(), + error.is_credential_rejection(), + error.is_account_refusal(), + ) + } + + /// A replayed error reads exactly as the original, for every variant + /// and for each kind of profile error a store can fail with. + #[test] + fn a_replayed_error_reads_as_the_original() { + use stack_profile::ProfileError as P; + let mut errors: Vec = every_variant().into_iter().map(|row| row.0).collect(); + errors.extend( + [ + P::Io(std::io::Error::from_raw_os_error(2)), + P::Io(std::io::Error::from(std::io::ErrorKind::PermissionDenied)), + P::HomeDirNotFound, + P::InvalidFilename("../x".into()), + P::NoCurrentWorkspace, + P::InvalidWorkspaceId("short".into()), + P::WorkspaceNotFound("ZVATKW3VHMFG27DY".into()), + ] + .map(AuthError::from), + ); + let region = |host: bool| { + let input = "nowhere".to_string(); + if host { + cts_common::RegionError::InvalidHostFqdn(input) + } else { + cts_common::RegionError::InvalidRegion(input) + } + }; + let workspace_id = || "short".parse::().unwrap_err(); + for host in [false, true] { + errors.push(UnsupportedRegion(region(host)).into()); + errors.push(InvalidCrn(cts_common::InvalidCrn::InvalidRegion(region(host))).into()); + } + errors.push(InvalidCrn(cts_common::InvalidCrn::InvalidFormat("x".into())).into()); + errors.push(InvalidCrn(cts_common::InvalidCrn::InvalidWorkspaceId(workspace_id())).into()); + errors.extend( + [ + access_key::InvalidAccessKey::MissingPrefix, + access_key::InvalidAccessKey::MissingDot, + access_key::InvalidAccessKey::EmptyKeyId, + access_key::InvalidAccessKey::EmptySecret, + ] + .map(|e| AuthError::from(InvalidAccessKeyError(e))), + ); + for error in errors { + assert_eq!(readable(&error.replay()), readable(&error), "{error:?}"); + } + } + + /// A transport error and its causes, `depth` errors in all. + #[derive(Debug)] + struct Link(usize, Option>); + + impl std::fmt::Display for Link { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "link {}", self.0) + } + } + + impl std::error::Error for Link { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + self.1 + .as_deref() + .map(|link| link as &(dyn std::error::Error + 'static)) + } + } + + fn transport_error(depth: usize) -> AuthError { + let chain = (0..depth) + .rev() + .fold(None, |source, n| Some(Box::new(Link(n, source)))); + RequestError(chain.unwrap()).into() + } + + /// A transport error's causes are replayed in order, as text. + #[test] + fn a_replayed_transport_error_keeps_its_causes() { + let error = transport_error(3); + assert_eq!(readable(&error.replay()), readable(&error)); + } + + /// A chain of causes too long to be real is cut short in a replay. + #[test] + fn a_replayed_transport_error_keeps_a_bounded_chain() { + let replayed = transport_error(40).replay(); + let mut causes = 0; + let mut next = std::error::Error::source(&replayed); + while let Some(cause) = next { + causes += 1; + next = cause.source(); + } + // The transport's error, then the causes kept after it. + assert_eq!(causes, 1 + MAX_REPLAYED_CAUSES); + } + + /// A profile file's JSON error keeps its kind of error and its code in + /// a replay. Its position in the file is not kept. + #[test] + fn a_replayed_json_error_keeps_its_kind() { + use miette::Diagnostic; + let parse = |input: &str| { + serde_json::from_str::>(input).unwrap_err() + }; + let read_failure = serde_json::Error::io(std::io::Error::other("unreadable")); + for json in [parse("{"), parse("!"), parse("[1]"), read_failure] { + let category = json.classify(); + let error = AuthError::from(stack_profile::ProfileError::Json(json)); + let replayed = error.replay(); + let AuthError::Store(StoreError(stack_profile::ProfileError::Json(json))) = &replayed + else { + panic!("not a JSON error: {replayed:?}"); + }; + assert_eq!(json.classify(), category); + assert_eq!( + replayed.code().map(|c| c.to_string()), + error.code().map(|c| c.to_string()) + ); + } + } + /// The frozen codes and the miette codes are two names for one error: /// every variant carries the pair in its row, so a code changed on one /// side and not the other fails here. Every frozen code has a row. diff --git a/packages/stack-auth/src/lib.rs b/packages/stack-auth/src/lib.rs index 9bbcd3ee55..4d3c26cd99 100644 --- a/packages/stack-auth/src/lib.rs +++ b/packages/stack-auth/src/lib.rs @@ -75,6 +75,7 @@ mod device_session_refresher; mod device_session_strategy; mod oidc_federation_strategy; mod oidc_refresher; +mod refresh_schedule; mod refresher; pub use error::StoreError; @@ -115,12 +116,17 @@ mod test_support; pub use access_key::{AccessKey, InvalidAccessKey}; pub use access_key_strategy::{AccessKeyStrategy, AccessKeyStrategyBuilder}; pub use auth_strategy_fn::AuthStrategyFn; +pub use auto_refresh::RefreshDriver; pub use auto_strategy::{AutoStrategy, AutoStrategyBuilder}; pub use device_session_strategy::{DeviceSessionStrategy, DeviceSessionStrategyBuilder}; pub use oidc_federation_strategy::{ profile_workspace_crn, OidcFederationStrategy, OidcFederationStrategyBuilder, }; pub use oidc_refresher::{CredentialPerCall, OidcProvider, OidcProviderFn}; +pub use refresh_schedule::{ + NextRefresh, RefreshSchedule, BACKOFF_CAP_SECS, REFRESH_AHEAD_SECS, REFRESH_FLOOR_SECS, + REFRESH_JITTER_SECS, +}; pub use service_token::ServiceToken; #[cfg(any(test, feature = "test-utils"))] pub use static_token_strategy::StaticTokenStrategy; @@ -259,15 +265,59 @@ pub mod store { /// A token can be "expired" (in the preemptive sense) but still "usable" /// (the server will still accept it). /// -/// ## Concurrent refresh strategies -/// -/// The gap between "expired" and "unusable" enables two refresh modes: -/// -/// 1. **Expiring but still usable** — The first caller triggers a background -/// refresh. Concurrent callers receive the current (still-valid) token -/// immediately without blocking. -/// 2. **Fully expired** — The first caller blocks while refreshing. Concurrent -/// callers wait until the refresh completes, then all receive the new token. +/// ## Refreshing ahead of expiry +/// +/// A token is refreshed before it expires, off the caller's path, by the +/// rule in [`RefreshSchedule`]: its refresh is due 90 to 120 seconds before +/// it expires (later for a token with little life left), and only while +/// the strategy is in use, so an idle process stops asking the auth server. +/// After a refresh fails, the next attempt waits about a second, doubling +/// up to [`BACKOFF_CAP_SECS`], and a minute after a refusal of the account. +/// +/// On native targets an access-key or device-session strategy runs that +/// rule on a background task on the current Tokio runtime, started by the +/// first `get_token`. The task holds the strategy weakly and ends when it +/// is dropped. On wasm32 there is no task: a host can keep the timer itself +/// ([`AccessKeyStrategy::drive_refresh`]); without one, calls refresh as +/// described below. +/// +/// An [`OidcFederationStrategy`] has no task on any target. Each user's +/// token is refreshed by that user's calls, as described below, so nothing +/// renews it once their requests stop, and nothing re-exchanges a JWT that +/// may have expired by then. +/// The refresh floor described below does not apply to it: a call inside +/// the 90 seconds before expiry refreshes, as with no task. +/// +/// ## Short-lived tokens +/// +/// A token that lasts less than 90 seconds is inside the refresh window +/// from the moment it arrives. Its background refresh is due half way +/// through its life, so a 60-second token is refreshed about every 30 +/// seconds while it is in use. With the default floor, calls in the first +/// half of its life get it at once. Calls in the second half refresh it, +/// or wait for the background refresh. Keep the floor at or below half +/// the token's lifetime: with a larger floor, calls start waiting before +/// the background refresh is due. +/// +/// ## What a call does +/// +/// - **Its token still works**: it gets that token, at once. With a +/// background task or a host driving the refresh, it does not start or +/// wait for one. The exception is a token with less than the refresh +/// floor left: [`REFRESH_FLOOR_SECS`], 30 seconds unless set with +/// [`AccessKeyStrategyBuilder::refresh_floor`] or +/// [`DeviceSessionStrategyBuilder::refresh_floor`]. Under the floor, the +/// call refreshes the token itself, or waits for the refresh already +/// running. So it does not get back a token that may expire before it is +/// used. Without a task or a host, the first call within 90 seconds of +/// expiry refreshes and waits for its own refresh, while concurrent +/// callers get the current token. +/// - **The token has expired**: the first caller refreshes, and concurrent +/// callers wait for it, then all receive the new token. If a refresh has +/// failed and its backoff has not ended, the call fails at once with that +/// refresh's error instead. +/// - **There is no token yet**: the first caller authenticates, and +/// concurrent callers wait for it. /// /// Only one refresh runs at a time, regardless of how many callers request a /// token concurrently. diff --git a/packages/stack-auth/src/oidc_federation_strategy.rs b/packages/stack-auth/src/oidc_federation_strategy.rs index 68be21922d..58f79e63f0 100644 --- a/packages/stack-auth/src/oidc_federation_strategy.rs +++ b/packages/stack-auth/src/oidc_federation_strategy.rs @@ -389,13 +389,19 @@ impl OidcFederationStrategy { if let Some(err) = self.fresh_denial() { return Err(err); } - let engine = Arc::new(AutoRefresh::with_store( - JwtRefresher::new(jwt, Arc::clone(&self.federation)), - BoundStore { - inner: Arc::clone(&self.store), - digest, - }, - )); + // Refreshed by calls only: a background task would keep renewing + // this user's token after their requests stop, with a JWT that may + // have expired by then. + let engine = Arc::new( + AutoRefresh::with_store( + JwtRefresher::new(jwt, Arc::clone(&self.federation)), + BoundStore { + inner: Arc::clone(&self.store), + digest, + }, + ) + .refreshed_by_calls(), + ); let _ = engines.pending.insert(digest, Arc::clone(&engine)); Ok(engine) } @@ -1271,6 +1277,30 @@ mod tests { assert_eq!(calls.load(Ordering::SeqCst), 5); } + /// A user's token is refreshed by that user's calls, never by a task + /// that would go on renewing it once their requests stop. A call in a + /// Tokio runtime is where an access-key strategy starts its task. + #[tokio::test] + async fn a_users_token_is_refreshed_by_their_calls_not_a_background_task() { + let server = start_mock_server().await; + accept_exchange(&server, "jwt-a", "CS|a"); + let (current, _calls, provider) = switchable_provider(); + let strategy = strategy_on(&server, provider).build().expect("builder"); + + act_as(¤t, "jwt-a"); + let _ = (&strategy).get_token().await.expect("A"); + let _ = (&strategy).get_token().await.expect("A cached"); + + let engine = strategy + .engine_for(SecretToken::new("jwt-a".to_string())) + .expect("A's engine"); + assert_eq!( + engine.drivers_attached(), + 0, + "no background task refreshes a user's token" + ); + } + /// A provider that cannot say who the caller is fails the call before any /// exchange is attempted: its own error comes back, not the exchange's. #[tokio::test] diff --git a/packages/stack-auth/src/refresh_schedule.rs b/packages/stack-auth/src/refresh_schedule.rs new file mode 100644 index 0000000000..5abf8408b7 --- /dev/null +++ b/packages/stack-auth/src/refresh_schedule.rs @@ -0,0 +1,499 @@ +//! When a token is refreshed ahead of its expiry, and how long to wait +//! after a refresh fails. +//! +//! [`RefreshSchedule`] is the one rule every SDK follows. It is plain data: +//! it reads no clock and starts no task. A strategy on a native target +//! drives it from a background task of its own. A WebAssembly host drives +//! it from its own timer, through a strategy's +//! [`next_refresh`](crate::AccessKeyStrategy::next_refresh) and +//! [`refresh_now`](crate::AccessKeyStrategy::refresh_now). + +use crate::Token; + +/// How long before a token's expiry its refresh is due, at the earliest. +/// That is 30 seconds before the 90-second leeway in which a call would +/// refresh it anyway, so a failed refresh has time for retries. +pub const REFRESH_AHEAD_SECS: u64 = 120; + +/// The refresh of each token is due at a random moment in the +/// [`REFRESH_JITTER_SECS`] after [`REFRESH_AHEAD_SECS`] before its expiry, +/// so processes whose tokens were issued together do not all refresh at +/// once. +pub const REFRESH_JITTER_SECS: u64 = 30; + +/// The default refresh floor, in seconds. A call whose token has less than +/// this left refreshes it, or waits for the refresh already running. So it +/// does not get back a token that may expire before it is used. Above the +/// floor, a call gets its token at once while a background task or a host +/// refreshes it. Set it with +/// [`AccessKeyStrategyBuilder::refresh_floor`](crate::AccessKeyStrategyBuilder::refresh_floor) +/// or +/// [`DeviceSessionStrategyBuilder::refresh_floor`](crate::DeviceSessionStrategyBuilder::refresh_floor). +pub const REFRESH_FLOOR_SECS: u64 = 30; + +/// The longest wait between two attempts after refreshes fail. The first +/// wait is about a second, and each failure doubles it up to this. +pub const BACKOFF_CAP_SECS: u64 = 30; + +/// When the next refresh is due. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum NextRefresh { + /// Nothing to do until the strategy is used again: it has not been used + /// since its last refresh, it has no token yet, or its token cannot be + /// refreshed. + Idle, + /// Due at this time, in seconds since the Unix epoch. A time already + /// past means now. + At(u64), +} + +/// The refresh plan for one strategy's token. +/// +/// A token is refreshed ahead of its expiry only while the strategy is in +/// use: [`used`](Self::used) marks a call for a token, and every refresh +/// attempt clears the mark. So a process that stops asking for tokens stops +/// asking the token service too. +/// +/// After a refresh fails, the next attempt waits: about a second after the +/// first failure, doubling with each one up to [`BACKOFF_CAP_SECS`], each +/// wait chosen at random between half its length and its length. +#[derive(Debug, Clone)] +pub struct RefreshSchedule { + /// The expiry of the token the plan is for. + expires_at: Option, + /// When that token's refresh is due, or `None` when it cannot be + /// refreshed. + refresh_at: Option, + used: bool, + failures: u32, + /// When the last refresh failed, and when the next may start. + failed_at: u64, + retry_at: Option, + random: SplitMix64, +} + +impl Default for RefreshSchedule { + fn default() -> Self { + Self::new() + } +} + +impl RefreshSchedule { + /// A plan with no token yet. + pub fn new() -> Self { + Self::with_seed(SplitMix64::seed()) + } + + /// A plan whose random choices are fixed by `seed`, for tests. + pub(crate) fn with_seed(seed: u64) -> Self { + Self { + expires_at: None, + refresh_at: None, + used: false, + failures: 0, + failed_at: 0, + retry_at: None, + random: SplitMix64(seed), + } + } + + /// Plan for `token`, the strategy's token at `now`. A token the plan has + /// already seen changes nothing. A new one, from a refresh or from + /// another process, ends any backoff, and its refresh is due + /// [`REFRESH_AHEAD_SECS`] before its expiry, give or take the jitter, or + /// half way through its remaining life if that is later. + pub fn observe(&mut self, token: &Token, now: u64) { + let expires_at = token.expires_at(); + if self.expires_at == Some(expires_at) { + return; + } + self.expires_at = Some(expires_at); + self.failures = 0; + self.retry_at = None; + let jitter = self.random.below(REFRESH_JITTER_SECS + 1); + let ahead = expires_at.saturating_sub(REFRESH_AHEAD_SECS.saturating_sub(jitter)); + let half_way = now.saturating_add(expires_at.saturating_sub(now) / 2); + self.refresh_at = Some(ahead.max(half_way)); + } + + /// Mark a call for a token. Returns whether the plan was idle, so the + /// caller knows to wake whoever drives it. + pub fn used(&mut self) -> bool { + let was_idle = !self.used; + self.used = true; + was_idle && self.refresh_at.is_some() + } + + /// A refresh attempt is starting. It clears the mark of use: the next + /// refresh ahead waits for another call. + pub fn attempt_started(&mut self) { + self.used = false; + } + + /// The refresh attempt that started last failed at `now` with `error`. + /// The next one waits for the backoff, and a refusal of the account + /// (a usage limit, an organisation not yet provisioned) for at least a + /// minute: retrying sooner cannot change the answer. + pub fn refresh_failed(&mut self, error: &crate::AuthError, now: u64) { + let at_least = if error.is_account_refusal() { + crate::auto_refresh::DENIAL_TTL_SECS + } else { + 0 + }; + self.attempt_failed(now, at_least); + } + + /// [`refresh_failed`](Self::refresh_failed), with the minimum wait + /// given directly. + pub(crate) fn attempt_failed(&mut self, now: u64, at_least: u64) { + self.failures = self.failures.saturating_add(1); + let ceiling = 1u64 + .checked_shl(self.failures - 1) + .unwrap_or(u64::MAX) + .min(BACKOFF_CAP_SECS); + let floor = ceiling.div_ceil(2); + let wait = floor + self.random.below(ceiling - floor + 1); + self.failed_at = now; + self.retry_at = Some(now.saturating_add(wait.max(at_least))); + } + + /// The token cannot be refreshed: it has no refresh credential. Nothing + /// is due until a new token is observed. + pub fn cannot_refresh(&mut self) { + self.refresh_at = None; + } + + /// When the next refresh is due. + pub fn next(&self) -> NextRefresh { + match self.refresh_at { + Some(refresh_at) if self.used => { + NextRefresh::At(refresh_at.max(self.retry_at.unwrap_or(0))) + } + _ => NextRefresh::Idle, + } + } + + /// Whether a refresh failed and its backoff has not ended by `now`. A + /// call does not start a refresh of its own while it lasts. + /// + /// A clock that reads earlier than the failure (an NTP step, a restored + /// snapshot) ends the backoff: how long has passed is then unknown, and + /// asking again costs one request where waiting could lock the caller + /// out until the clock catches up. + pub fn backing_off(&self, now: u64) -> bool { + self.retry_at + .is_some_and(|retry_at| self.failed_at <= now && now < retry_at) + } +} + +/// A small, fast generator for the jitter. Not for secrets: it only spreads +/// refreshes over time. +#[derive(Debug, Clone)] +struct SplitMix64(u64); + +impl SplitMix64 { + /// A seed that differs between processes and between plans: the + /// standard library's per-process hash keys, the time, and a counter. + fn seed() -> u64 { + use std::hash::{BuildHasher, Hasher}; + use std::sync::atomic::{AtomicU64, Ordering}; + static COUNTER: AtomicU64 = AtomicU64::new(0); + let mut hasher = std::collections::hash_map::RandomState::new().build_hasher(); + hasher.write_u64(COUNTER.fetch_add(1, Ordering::Relaxed)); + let nanos = web_time::SystemTime::now() + .duration_since(web_time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or_default(); + hasher.write_u128(nanos); + hasher.finish() + } + + fn next(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } + + /// A value in `0..limit`; `limit` is small, so the bias is negligible. + fn below(&mut self, limit: u64) -> u64 { + self.next() % limit.max(1) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::SecretToken; + use proptest::prelude::*; + + fn token(expires_at: u64) -> Token { + Token { + access_token: SecretToken::new("t"), + refresh_token: None, + token_type: "Bearer".into(), + expires_at, + region: None, + client_id: None, + device_instance_id: None, + federated_from: None, + } + } + + fn due(plan: &RefreshSchedule) -> u64 { + match plan.next() { + NextRefresh::At(at) => at, + NextRefresh::Idle => panic!("idle"), + } + } + + /// The generator's values stay below their limit, and reach every value + /// under it. + #[test] + fn the_jitter_stays_below_its_limit() { + let mut random = SplitMix64(7); + for limit in [1, 2, REFRESH_JITTER_SECS + 1] { + let mut seen = std::collections::BTreeSet::new(); + for _ in 0..1_000 { + let value = random.below(limit); + assert!(value < limit, "{value} for a limit of {limit}"); + let _ = seen.insert(value); + } + assert_eq!(seen.len() as u64, limit, "values for a limit of {limit}"); + } + } + + #[test] + fn a_plan_with_no_token_is_idle() { + let mut plan = RefreshSchedule::with_seed(1); + plan.used(); + assert_eq!(plan.next(), NextRefresh::Idle); + } + + #[test] + fn an_unused_plan_is_idle_and_a_use_wakes_it() { + let mut plan = RefreshSchedule::with_seed(1); + plan.observe(&token(1_900), 1_000); + assert_eq!(plan.next(), NextRefresh::Idle); + assert!(plan.used(), "the first use reports an idle plan"); + assert!(!plan.used(), "a second use does not"); + assert!(matches!(plan.next(), NextRefresh::At(_))); + plan.attempt_started(); + assert_eq!(plan.next(), NextRefresh::Idle); + } + + #[test] + fn a_use_before_any_token_wakes_nothing() { + let mut plan = RefreshSchedule::with_seed(1); + assert!(!plan.used()); + } + + #[test] + fn a_token_that_cannot_be_refreshed_is_idle_until_a_new_one() { + let mut plan = RefreshSchedule::with_seed(1); + plan.observe(&token(1_900), 1_000); + plan.used(); + plan.cannot_refresh(); + assert_eq!(plan.next(), NextRefresh::Idle); + plan.observe(&token(1_900), 1_000); + assert_eq!(plan.next(), NextRefresh::Idle, "the same token"); + plan.observe(&token(2_800), 1_900); + assert!(matches!(plan.next(), NextRefresh::At(_)), "a new token"); + } + + #[test] + fn the_first_backoff_is_one_second() { + let mut plan = RefreshSchedule::with_seed(1); + plan.observe(&token(1_900), 1_000); + plan.used(); + plan.attempt_failed(1_790, 0); + assert_eq!(plan.retry_at, Some(1_791)); + assert!(due(&plan) >= 1_791); + assert!(plan.backing_off(1_790)); + assert!(!plan.backing_off(1_791)); + } + + #[test] + fn a_refusal_of_the_account_waits_at_least_its_minimum() { + let mut plan = RefreshSchedule::with_seed(1); + plan.observe(&token(1_900), 1_000); + plan.used(); + plan.attempt_failed(1_790, 60); + assert_eq!(due(&plan), 1_850); + } + + /// The generator is SplitMix64: its first outputs from two seeds, as + /// the reference algorithm gives them. + #[test] + fn the_jitter_generator_is_splitmix64() { + let mut zero = SplitMix64(0); + assert_eq!( + [zero.next(), zero.next(), zero.next()], + [ + 0xe220_a839_7b1d_cdaf, + 0x6e78_9e6a_a1b9_65f4, + 0x06c4_5d18_8009_454f + ] + ); + let mut other = SplitMix64(1_234_567); + assert_eq!( + [other.next(), other.next()], + [0x599e_d017_fb08_fc85, 0x2c73_f084_5854_0fa5] + ); + } + + /// Plans made with `new` draw different jitter, so processes, and + /// strategies in one process, do not refresh in step. + #[test] + fn new_plans_draw_different_jitter() { + let times: std::collections::HashSet = (0..64) + .map(|_| { + let mut plan = RefreshSchedule::new(); + plan.observe(&token(10_000), 1_000); + plan.used(); + due(&plan) + }) + .collect(); + assert!(times.len() > 8, "only {} distinct times", times.len()); + } + + /// A token with little life left is refreshed half way through it, + /// not at once. + #[test] + fn a_short_lived_token_is_due_half_way() { + for seed in 0..64 { + let mut plan = RefreshSchedule::with_seed(seed); + plan.observe(&token(1_060), 1_000); + plan.used(); + assert_eq!(due(&plan), 1_030); + } + } + + /// The jitter covers the whole window, from REFRESH_AHEAD_SECS to + /// REFRESH_AHEAD_SECS - REFRESH_JITTER_SECS before expiry. + #[test] + fn the_jitter_covers_its_whole_window() { + let offsets: std::collections::BTreeSet = (0..2_000) + .map(|seed| { + let mut plan = RefreshSchedule::with_seed(seed); + plan.observe(&token(10_000), 1_000); + plan.used(); + 10_000 - due(&plan) + }) + .collect(); + let window: std::collections::BTreeSet = + (REFRESH_AHEAD_SECS - REFRESH_JITTER_SECS..=REFRESH_AHEAD_SECS).collect(); + assert_eq!(offsets, window); + } + + /// Each wait is chosen from the whole of its range: after a third + /// failure, two to four seconds. + #[test] + fn a_backoff_wait_covers_its_whole_range() { + let waits: std::collections::BTreeSet = (0..500) + .map(|seed| { + let mut plan = RefreshSchedule::with_seed(seed); + plan.observe(&token(10_000), 1_000); + for _ in 0..3 { + plan.attempt_failed(2_000, 0); + } + plan.retry_at.unwrap() - 2_000 + }) + .collect(); + assert_eq!(waits, (2..=4).collect()); + } + + #[test] + fn a_clock_that_goes_back_ends_the_backoff() { + let mut plan = RefreshSchedule::with_seed(1); + plan.observe(&token(1_900), 1_000); + plan.attempt_failed(1_790, 60); + assert!(plan.backing_off(1_800)); + assert!(!plan.backing_off(1_789)); + } + + #[test] + fn a_new_token_ends_the_backoff() { + let mut plan = RefreshSchedule::with_seed(1); + plan.observe(&token(1_900), 1_000); + for _ in 0..10 { + plan.attempt_failed(1_790, 0); + } + assert!(plan.backing_off(1_790)); + plan.observe(&token(2_800), 1_791); + assert!(!plan.backing_off(1_791)); + plan.attempt_failed(1_791, 0); + assert_eq!(plan.retry_at, Some(1_792), "the failure count restarted"); + } + + proptest! { + /// A token's refresh is due before it expires, no earlier than + /// REFRESH_AHEAD_SECS before, and no later than the jitter allows + /// or half way through its remaining life. + #[test] + fn a_refresh_is_due_ahead_of_expiry( + seed: u64, + now in 0u64..1 << 40, + life in 1u64..100_000, + ) { + let mut plan = RefreshSchedule::with_seed(seed); + plan.observe(&token(now + life), now); + plan.used(); + let at = due(&plan); + prop_assert!(at < now + life, "due at or after expiry"); + prop_assert!(at + REFRESH_AHEAD_SECS >= now + life, "due too early"); + prop_assert!( + at <= (now + life).saturating_sub(REFRESH_AHEAD_SECS - REFRESH_JITTER_SECS) + || at == now + life / 2, + "due later than the jitter or half way" + ); + } + + /// The waits after failures stay between one second and the cap, + /// and their upper bound never shrinks as failures mount. + #[test] + fn the_backoff_grows_to_its_cap(seed: u64, failures in 1usize..64) { + let mut plan = RefreshSchedule::with_seed(seed); + plan.observe(&token(1_000_000), 0); + plan.used(); + let mut ceiling = 0; + for n in 1..=failures { + plan.attempt_failed(500, 0); + let wait = plan.retry_at.unwrap() - 500; + let this_ceiling = (1u64 << (n - 1).min(10)).min(BACKOFF_CAP_SECS); + prop_assert!((1..=BACKOFF_CAP_SECS).contains(&wait)); + prop_assert!(wait <= this_ceiling && wait >= this_ceiling.div_ceil(2)); + prop_assert!(this_ceiling >= ceiling); + ceiling = this_ceiling; + } + } + + /// A token observed again changes nothing. + #[test] + fn observing_the_same_token_again_keeps_the_plan(seed: u64, later in 0u64..1_000) { + let mut plan = RefreshSchedule::with_seed(seed); + plan.observe(&token(10_000), 1_000); + plan.used(); + plan.attempt_failed(1_000, 0); + let before = plan.clone(); + plan.observe(&token(10_000), 1_000 + later); + prop_assert_eq!(plan.next(), before.next()); + prop_assert_eq!(plan.backing_off(1_000), before.backing_off(1_000)); + } + + /// Jitter spreads the plans of tokens issued together. + #[test] + fn tokens_issued_together_refresh_at_different_times(seed in 0u64..1_000) { + let times: std::collections::HashSet = (0..64) + .map(|i| { + let mut plan = RefreshSchedule::with_seed(seed * 64 + i); + plan.observe(&token(10_000), 9_100); + plan.used(); + due(&plan) + }) + .collect(); + prop_assert!(times.len() > 8, "only {} distinct times", times.len()); + } + } +} diff --git a/packages/stack-auth/src/token.rs b/packages/stack-auth/src/token.rs index 3d90c75fcd..45220c0fb5 100644 --- a/packages/stack-auth/src/token.rs +++ b/packages/stack-auth/src/token.rs @@ -15,7 +15,7 @@ impl stack_profile::ProfileData for Token { /// This leeway triggers preemptive refresh well before the token becomes /// unusable, giving the HTTP refresh call time to complete while concurrent /// callers can still use the current token. -const EXPIRY_LEEWAY_SECS: u64 = 90; +pub(crate) const EXPIRY_LEEWAY_SECS: u64 = 90; /// The longest token lifetime this crate accepts from a server, in seconds /// (30 days). diff --git a/scripts/__tests__/workflow-docker-hub-login.test.mjs b/scripts/__tests__/workflow-docker-hub-login.test.mjs index bbe976c63e..46fbcd1088 100644 --- a/scripts/__tests__/workflow-docker-hub-login.test.mjs +++ b/scripts/__tests__/workflow-docker-hub-login.test.mjs @@ -208,7 +208,7 @@ export const HIDDEN_PULLS = { { step: 'Run README walkthrough e2e', reason: - "e2e/tests/prisma-example-readme.e2e.test.ts runs the Prisma example's README, whose `docker compose up -d` pulls postgres:16.", + "e2e/tests/prisma-example-readme.e2e.test.ts runs the Prisma example's README, whose `docker compose up -d` pulls public.ecr.aws/docker/library/postgres:16.", }, ], '.github/workflows/tests.yml#e2e-tests': [ @@ -219,7 +219,7 @@ export const HIDDEN_PULLS = { { step: 'Run the credentialed Migration Harness self-test', reason: - 'With HARNESS_LIVE=1, e2e/migration-harness runs postgres:17-alpine and node:22-bookworm-slim, and builds an image from node:22-bookworm-slim.', + 'With HARNESS_LIVE=1, e2e/migration-harness runs postgres:17-alpine and node:22-bookworm-slim from public.ecr.aws/docker/library, and builds an image from the same Node image.', }, ], }