Skip to content
Open
Show file tree
Hide file tree
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 Nov 27, 2026
04c2f63
feat(stack-auth): refresh a token ahead of its expiry in the backgrou…
coderdan Nov 27, 2026
d088161
feat(golang): refresh access-key and device-session tokens from a gor…
coderdan Nov 27, 2026
ad7a731
test(stack-auth): pin the refresh-ahead rule and its task against eve…
coderdan Nov 27, 2026
5a8df6b
test(golang): write the device session just before its first use
coderdan Nov 27, 2026
3b5847c
test(stack-auth): gate the call-driven test helpers on the http feature
coderdan Nov 27, 2026
1f1fb77
test(stack-auth): fail, not hang, when a caller never starts its refresh
coderdan Nov 27, 2026
65fa82b
fix(stack-auth): refresh an OIDC user's token from their calls, not a…
coderdan Nov 27, 2026
242d872
fix(stack-auth): replay a failed refresh's error as the same error
coderdan Nov 28, 2026
d147e11
fix(golang): keep a device session's refresh error and refresh token …
coderdan Nov 28, 2026
d66a3f6
refactor(golang): one helper for a device session refresh under its lock
coderdan Nov 28, 2026
ea1f057
test(stack-auth): a refresh that fails as the token expires reports i…
coderdan Nov 28, 2026
1e83957
refactor(stack-auth): split AuthError::replay so each part is tested
coderdan Nov 28, 2026
d94fbd9
refactor(stack-auth): drop DeviceSessionStrategy's drive_refresh and …
coderdan Nov 29, 2026
f6e1953
feat(stack-auth): refresh a token under a floor in the call that gets it
coderdan Nov 29, 2026
97e8de6
test(stack-auth): make the refresh floor tests fail fast, not hang
coderdan Nov 29, 2026
c1a881c
test(stack-auth): bound the waits that hang under a mutant of the plan
coderdan Nov 29, 2026
fd3eed2
test(stack-auth): seed the refresh-ahead test at both ends of its window
coderdan Nov 29, 2026
2c14afe
Merge next into feat/stack-auth-background-refresh
coderdan Nov 29, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions .changeset/auth-background-refresh.md
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.
26 changes: 26 additions & 0 deletions languages/golang/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 13 additions & 0 deletions languages/golang/auth/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
170 changes: 170 additions & 0 deletions languages/golang/auth/background.go
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() {

Copy link
Copy Markdown
Contributor

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) duplicates strategy.go:~412-431, so the lock order can drift between the two. Extract a helper taking the guest call, after each caller has taken refreshing its own way.

Source: standards review · claude-opus-5-5


Generated by Claude Code

Copy link
Copy Markdown
Contributor Author

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. token and refreshAhead both call it, after each takes refreshing its own way. Nothing else changed. The Go auth tests pass, with -race too.

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)
}
Loading
Loading