Skip to content

Commit 5cd8228

Browse files
committed
fix(oidc): honor context at the refresh lock, retry replace on Windows
A Login waiting for another refresh of the same token file now returns ErrTimeout when its own context ends. writeToken retries the final rename on Windows for about 250 ms on access-denied and sharing-violation errors, as the Python SDK does, so a brief lock on the file by another process does not lose a token the provider has just rotated. Refresh errors now carry the provider's error code or the HTTP status. The Login docs now say when it returns an error instead of prompting. New tests cover the file read under the lock, a response without expires_in, peer tokens without a refresh token, and the replace retry schedule; two timing-based Login tests are replaced by direct ones. Part of NVIDIA/OpenShell#4514. Signed-off-by: shvma <[email protected]>
1 parent 5825bb5 commit 5cd8228

5 files changed

Lines changed: 471 additions & 84 deletions

File tree

‎docs/src/api/oidc.md‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -43,10 +43,11 @@ Tokens are persisted to the gateway's config directory as
4343
commands against that gateway can use them. Subsequent calls reuse the stored
4444
token only when it is valid and was issued for the gateway's issuer and client
4545
ID. If that token has expired but carries a refresh token, `Login` refreshes it
46-
and rewrites the file. Otherwise, or when the refresh fails, `Login` runs the
47-
flow again and, unless `WithInMemory` is set, rewrites the file.
48-
`WithInMemory` skips the refresh, because a rotated refresh token would not be
49-
written back.
46+
and rewrites the file. If the context ends, discovery fails, or the file cannot
47+
be written, `Login` returns the error. If there is no refresh token or the
48+
refresh fails for any other reason, `Login` runs the flow again and, unless
49+
`WithInMemory` is set, rewrites the file. `WithInMemory` skips the refresh,
50+
because a rotated refresh token would not be written back.
5051

5152
For standalone use (no gateway), pass an empty `gatewayName` with
5253
`WithIssuer` and `WithClientID`. Combine with `WithInMemory` to skip

‎openshell/v1/oidc/doc.go‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,8 @@
2626
// use them. A later Login reuses the stored token only when it is valid
2727
// and was issued for the gateway's issuer and client ID. If that token has
2828
// expired but carries a refresh token, Login refreshes it and rewrites the
29-
// file without prompting.
29+
// file without prompting; see [Login] for what happens when the refresh
30+
// fails.
3031
//
3132
// # Standalone Login
3233
//

‎openshell/v1/oidc/refresh.go‎

Lines changed: 34 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -27,22 +27,37 @@ var (
2727
// flow.
2828
errTokenRefresh = errors.New("oidc: token refresh failed")
2929

30-
// errInvalidGrant marks a refresh rejected with invalid_grant, which
31-
// usually means another process already used the refresh token.
30+
// errInvalidGrant marks a refresh rejected with invalid_grant. The
31+
// refresh token has expired or been revoked, or another process has
32+
// already used it.
3233
errInvalidGrant = errors.New("oidc: invalid_grant")
3334
)
3435

3536
// refreshLocks serializes refreshes of one token file within the process,
36-
// keyed by the cleaned token directory, so concurrent Login calls do not
37-
// spend the same refresh token twice. It holds one mutex per directory
38-
// ever refreshed, which is a handful of gateways in practice.
37+
// so concurrent Login calls do not spend the same refresh token twice. It
38+
// maps each absolute token directory to a one-slot semaphore and keeps one
39+
// entry per directory ever refreshed, which is a handful of gateways in
40+
// practice.
3941
var refreshLocks sync.Map
4042

41-
func lockTokenDir(dir string) func() {
42-
mu, _ := refreshLocks.LoadOrStore(filepath.Clean(dir), &sync.Mutex{})
43-
m := mu.(*sync.Mutex)
44-
m.Lock()
45-
return m.Unlock
43+
// lockTokenDir waits for the refresh lock of dir until ctx ends, and
44+
// returns the function that releases it.
45+
func lockTokenDir(ctx context.Context, dir string) (func(), error) {
46+
key := filepath.Clean(dir)
47+
if abs, err := filepath.Abs(key); err == nil {
48+
key = abs
49+
}
50+
slot, _ := refreshLocks.LoadOrStore(key, make(chan struct{}, 1))
51+
sem := slot.(chan struct{})
52+
if err := ctx.Err(); err != nil {
53+
return nil, fmt.Errorf("%w: %w", ErrTimeout, err)
54+
}
55+
select {
56+
case sem <- struct{}{}:
57+
return func() { <-sem }, nil
58+
case <-ctx.Done():
59+
return nil, fmt.Errorf("%w: %w", ErrTimeout, ctx.Err())
60+
}
4661
}
4762

4863
// refreshStoredToken renews an expired stored token with its refresh token
@@ -71,7 +86,10 @@ func refreshStoredToken(ctx context.Context, cfg *loginConfig, tokenDir string,
7186
return nil, nil
7287
}
7388

74-
unlock := lockTokenDir(tokenDir)
89+
unlock, err := lockTokenDir(ctx, tokenDir)
90+
if err != nil {
91+
return nil, err
92+
}
7593
defer unlock()
7694

7795
current, err := readToken(tokenDir)
@@ -187,12 +205,11 @@ func refreshToken(ctx context.Context, tokenEndpoint, clientID, refresh string,
187205
if tokResp.Error == "invalid_grant" {
188206
return nil, fmt.Errorf("%w: %w", errTokenRefresh, errInvalidGrant)
189207
}
190-
if resp.StatusCode != http.StatusOK || tokResp.Error != "" {
191-
msg := "token refresh failed"
192-
if tokResp.Error != "" {
193-
msg = fmt.Sprintf("token refresh failed: %s", tokResp.Error)
194-
}
195-
return nil, fmt.Errorf("%w: %s", errTokenRefresh, msg)
208+
if tokResp.Error != "" {
209+
return nil, fmt.Errorf("%w: %s", errTokenRefresh, tokResp.Error)
210+
}
211+
if resp.StatusCode != http.StatusOK {
212+
return nil, fmt.Errorf("%w: HTTP %d", errTokenRefresh, resp.StatusCode)
196213
}
197214
if tokResp.AccessToken == "" {
198215
return nil, fmt.Errorf("%w: token response has no access_token", errTokenRefresh)

0 commit comments

Comments
 (0)