Repository navigation
feat: refresh tokens in the background before they expire, with backoff after a failure #1989
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
coderdan
wants to merge
19
commits into
next
Choose a base branch
from
feat/stack-auth-background-refresh
base: next
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+3,773
−255
Open
Changes from all commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
7e17515
test: callers must not wait for or start the refresh of a token that …
coderdan 04c2f63
feat(stack-auth): refresh a token ahead of its expiry in the backgrou…
coderdan d088161
feat(golang): refresh access-key and device-session tokens from a gor…
coderdan ad7a731
test(stack-auth): pin the refresh-ahead rule and its task against eve…
coderdan 5a8df6b
test(golang): write the device session just before its first use
coderdan 3b5847c
test(stack-auth): gate the call-driven test helpers on the http feature
coderdan 1f1fb77
test(stack-auth): fail, not hang, when a caller never starts its refresh
coderdan 65fa82b
fix(stack-auth): refresh an OIDC user's token from their calls, not a…
coderdan 242d872
fix(stack-auth): replay a failed refresh's error as the same error
coderdan d147e11
fix(golang): keep a device session's refresh error and refresh token …
coderdan d66a3f6
refactor(golang): one helper for a device session refresh under its lock
coderdan ea1f057
test(stack-auth): a refresh that fails as the token expires reports i…
coderdan 1e83957
refactor(stack-auth): split AuthError::replay so each part is tested
coderdan d94fbd9
refactor(stack-auth): drop DeviceSessionStrategy's drive_refresh and …
coderdan f6e1953
feat(stack-auth): refresh a token under a floor in the call that gets it
coderdan 97e8de6
test(stack-auth): make the refresh floor tests fail fast, not hang
coderdan c1a881c
test(stack-auth): bound the waits that hang under a mutant of the plan
coderdan fd3eed2
test(stack-auth): seed the refresh-ahead test at both ends of its window
coderdan 2c14afe
Merge next into feat/stack-auth-background-refresh
coderdan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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) | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
minor
LockPath("auth.json")→withRefreshLock→withRefresh(ctx)duplicatesstrategy.go:~412-431, so the lock order can drift between the two. Extract a helper taking the guest call, after each caller has takenrefreshingits own way.Source: standards review · claude-opus-5-5
Generated by Claude Code
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fixed in d66a3f6.
Strategy.refreshDeviceSession(strategy.go) now has the three steps: it gets the auth.json lock path, takes the lock for the refresh, and marks the refresh context.tokenandrefreshAheadboth call it, after each takesrefreshingits own way. Nothing else changed. The Go auth tests pass, with-racetoo.