diff --git a/docs/src/api/gateway.md b/docs/src/api/gateway.md index d2e870b..a98ad41 100644 --- a/docs/src/api/gateway.md +++ b/docs/src/api/gateway.md @@ -124,11 +124,23 @@ type Info struct { | `""` or `"none"` | `AuthModeNone` | `v1.NoAuth()` | | `"plaintext"` | `AuthModePlaintext` | `v1.NoAuth()` + insecure TLS | | `"cloudflare_jwt"` | `AuthModeCloudflareJWT` | Lazy edge token auth | -| `"oidc"` | `AuthModeOIDC` | `v1.RefreshableToken` that reads `oidc_token.json` near expiry and fails once the token has expired | +| `"oidc"` | `AuthModeOIDC` | `v1.RefreshableToken` that reads `oidc_token.json` near expiry and renews the token with its refresh token | | `"mtls"` | `AuthModeMTLS` | Unsupported (use `WithAuth`) | With `AuthModeCloudflareJWT`, the SDK rereads the edge token file on each request, so a token refreshed by `openshell gateway login` takes effect without a restart. Keep the token file readable. +With `AuthModeOIDC`, the SDK renews the token in `oidc_token.json` with its refresh token when the token is within 30 seconds of expiry, as the CLI does, and rewrites the file in the CLI's format (owner-only on Unix), so the CLI and other SDKs pick up a rotated refresh token. For tokens valid for less than a minute, renewal starts at half the token's lifetime once the client has renewed one. Renewal needs `oidc_issuer` and `oidc_client_id` in `metadata.json` and a token issued for them; tokens without a refresh token or an expiry are not renewed. The SDK sends `oidc_scopes` with `openid` first, or no scope when `oidc_scopes` is not set. + +RPCs that find the token due while it has not expired wait for the renewal until 2 seconds after it started, then send the current token and let the renewal finish in the background. An RPC with a deadline waits at most half the time it has left and then sends the token the client already holds; if the client holds none yet, the RPC fails with DeadlineExceeded when its deadline ends first. If renewal fails while the token is still usable, the source returns that token to the client and waits at least 5 seconds before trying again. Returning a usable token resets the client's backoff. + +An RPC that finds the token expired, or sees it expire while waiting, waits for the renewal, at most 30 seconds for the lock and discovery and then for each token request. If the renewal fails, the RPC fails as described in [Error Handling](#error-handling), with the reason in the message, such as the provider's error code or HTTP status, and later RPCs retry with the client's backoff of 1 second, doubling up to 30 seconds; in between, they fail at once with the last error. Every failed renewal also goes to the logger set with `gateway.WithLogger`. + +If a renewed token cannot be written, for example on a full disk, the client keeps it in memory and uses it, since a provider that rotates refresh tokens has already revoked the one in the file, and the write error goes to the logger. The next renewal writes it first. While that write fails and the refresh token was rotated, renewals send no token request, because a provider may end the session when it sees a revoked refresh token; the client then works until the token expires. A login or a token written by another process replaces it. + +A renewal is not tied to the client: closing the client does not stop it, and a renewal still running when the process exits is cut off. With a provider that rotates refresh tokens, the stored refresh token may then no longer work. A process killed while it writes the file can leave a `.oidc-token-*` temporary file in the gateway directory. + +The SDK does not lock `oidc_token.json` against other processes, as the CLI and the Python SDK do not. With a provider that rotates refresh tokens, two processes that renew at the same moment spend the same refresh token, and one gets `invalid_grant`. It uses the token the other wrote if that is already in the file, and otherwise fails that renewal and picks the token up on a later one. A provider that revokes all tokens of a session on refresh token reuse ends the session instead. + The SDK tries `edge_token` first and falls back to the legacy `cf_token` only when `edge_token` is absent. Logout takes effect for a running client once neither token file remains. Removing only `edge_token` still permits authentication if a legacy `cf_token` remains. ### ClientOption @@ -153,15 +165,17 @@ if errors.Is(err, gateway.ErrGatewayNotFound) { ``` Tokens load lazily, so `NewClient` does not return `ErrTokenLoad`. For `oidc` -gateways, a missing, malformed, or expired `oidc_token.json` surfaces on RPCs as +gateways, a missing, malformed, or expired `oidc_token.json`, or a failed renewal +of an expired token, surfaces on RPCs as an error for which `v1.IsUnauthenticated(err)` is true, and its message includes -``run `openshell gateway login ` ``. +``run `openshell gateway login ` ``. An RPC whose context ends while it +waits for the renewal fails with DeadlineExceeded or Canceled instead. | Error | Meaning | |-------|---------| | `ErrGatewayNotFound` | No gateway directory in user or system paths | | `ErrConfigParse` | metadata.json missing or malformed | -| `ErrTokenLoad` | Token file missing, unreadable, malformed, or expired; RPCs report it as Unauthenticated | +| `ErrTokenLoad` | Token file missing, unreadable, malformed, or expired, or an expired OIDC token could not be renewed; RPCs report it as Unauthenticated | | `ErrUnsupportedAuthMode` | Unrecognized auth_mode value | | `ErrInvalidGatewayName` | Name fails validation | | `ErrNoActiveGateway` | No active gateway configured | diff --git a/openshell/v1/auth_refresh.go b/openshell/v1/auth_refresh.go index e2bd84b..3177112 100644 --- a/openshell/v1/auth_refresh.go +++ b/openshell/v1/auth_refresh.go @@ -11,7 +11,9 @@ import ( "golang.org/x/oauth2" "golang.org/x/sync/singleflight" + "google.golang.org/grpc/status" + "github.com/ai-openshell/sdk-go/openshell/v1/internal/oidctoken" "github.com/ai-openshell/sdk-go/openshell/v1/internal/options" "github.com/ai-openshell/sdk-go/openshell/v1/types" ) @@ -69,6 +71,33 @@ type refreshableAuth struct { lastErr error } +// refreshWaitError is returned when a call's context ends while it waits for +// a refresh and no cached token is usable. It wraps the context's error +// and carries the matching gRPC status, so the call fails with +// DeadlineExceeded or Canceled rather than Unauthenticated. +type refreshWaitError struct{ err error } + +func (e refreshWaitError) Error() string { + return "openshell: waiting for a token refresh: " + e.err.Error() +} + +func (e refreshWaitError) Unwrap() error { return e.err } + +func (e refreshWaitError) GRPCStatus() *status.Status { + return status.New(status.FromContextError(e.err).Code(), e.Error()) +} + +// cached returns the authorization metadata for the cached token if it +// has not expired. +func (r *refreshableAuth) cached() (map[string]string, bool) { + r.mu.Lock() + defer r.mu.Unlock() + if !r.usableCached() { + return nil, false + } + return map[string]string{"authorization": "Bearer " + r.tok.AccessToken}, true +} + // usableCached reports whether the cached token has not yet expired. // Callers must hold r.mu. func (r *refreshableAuth) usableCached() bool { @@ -82,7 +111,13 @@ func (r *refreshableAuth) isTokenValid() bool { if r.tok.Expiry.IsZero() { return true } - return time.Now().Before(r.tok.Expiry.Add(-r.leeway)) + leeway := r.leeway + if source, ok := r.source.(interface { + RefreshWindow() oidctoken.RefreshWindow + }); ok { + leeway = time.Duration(source.RefreshWindow()) + } + return time.Now().Before(r.tok.Expiry.Add(-leeway)) } func (r *refreshableAuth) GetRequestMetadata(ctx context.Context, _ ...string) (map[string]string, error) { @@ -103,58 +138,98 @@ func (r *refreshableAuth) GetRequestMetadata(ctx context.Context, _ ...string) ( r.mu.Unlock() return nil, err } + usable := r.usableCached() r.mu.Unlock() resultCh := r.group.DoChan("refresh", func() (any, error) { - return r.source.Token() + tok, err := r.source.Token() + if err == nil && tok == nil { + err = errNilToken + } + // Record the outcome here rather than in the callers: with a + // deadline, every caller may have stopped waiting for it. + r.record(tok, err) + return tok, err }) + + // A cached token that has not expired is still good for this call, so + // a call with a deadline waits for the refresh for at most half the + // time it has left and keeps the rest for the call itself. The refresh + // keeps running, and its outcome is recorded for later calls. + var giveUp <-chan time.Time + if deadline, ok := ctx.Deadline(); ok && usable { + timer := time.NewTimer(time.Until(deadline) / 2) + defer timer.Stop() + giveUp = timer.C + } var val any var err error - select { - case <-ctx.Done(): - return nil, ctx.Err() - case result := <-resultCh: - val = result.Val - err = result.Err +wait: + for { + select { + case <-ctx.Done(): + if md, ok := r.cached(); ok { + return md, nil + } + return nil, refreshWaitError{ctx.Err()} + case <-giveUp: + if md, ok := r.cached(); ok { + return md, nil + } + giveUp = nil + case result := <-resultCh: + val = result.Val + err = result.Err + break wait + } } - r.mu.Lock() - defer r.mu.Unlock() - if err != nil { - if r.nextRetry.IsZero() || !time.Now().Before(r.nextRetry) { - bo := r.backoff - if bo == 0 { - bo = initialBackoff - } else { - bo *= 2 - if bo > maxBackoff { - bo = maxBackoff - } - } - r.backoff = bo - r.nextRetry = time.Now().Add(bo) + if md, ok := r.cached(); ok { + return md, nil } - r.lastErr = err + return nil, err + } + return map[string]string{"authorization": "Bearer " + val.(*oauth2.Token).AccessToken}, nil +} - if r.usableCached() { - if r.logger != nil { - r.logger.Error(err, "token refresh failed, using cached token") +// errNilToken is recorded when the source returns neither a token nor an +// error. +var errNilToken = errors.New("openshell: token source returned nil token without error") + +// record stores a token or advances backoff on failure. A source that +// returns a still-valid token with no error resets this backoff and owns +// any cooldown for retries it makes. A failure with a usable cached token +// is logged once. +func (r *refreshableAuth) record(tok *oauth2.Token, err error) { + r.mu.Lock() + if err == nil { + r.tok = tok + r.backoff = 0 + r.nextRetry = time.Time{} + r.lastErr = nil + r.mu.Unlock() + return + } + if r.nextRetry.IsZero() || !time.Now().Before(r.nextRetry) { + bo := r.backoff + if bo == 0 { + bo = initialBackoff + } else { + bo *= 2 + if bo > maxBackoff { + bo = maxBackoff } - return map[string]string{"authorization": "Bearer " + r.tok.AccessToken}, nil } - return nil, err + r.backoff = bo + r.nextRetry = time.Now().Add(bo) } - - tok, ok := val.(*oauth2.Token) - if !ok || tok == nil { - return nil, errors.New("openshell: token source returned nil token without error") + r.lastErr = err + logIt := r.logger != nil && r.usableCached() + r.mu.Unlock() + if logIt { + r.logger.Error(err, "token refresh failed, using cached token") } - r.tok = tok - r.backoff = 0 - r.nextRetry = time.Time{} - r.lastErr = nil - return map[string]string{"authorization": "Bearer " + r.tok.AccessToken}, nil } func (r *refreshableAuth) RequireTransportSecurity() bool { @@ -166,7 +241,14 @@ func (r *refreshableAuth) RequireTransportSecurity() bool { // in-flight refresh via singleflight. Failed refreshes trigger exponential // backoff (1s, 2s, 4s, ..., 30s cap) to avoid amplifying token endpoint outages. // After a failed refresh, the cached token is used only until it expires; -// after that, requests fail with the last refresh error. +// after that, requests fail with the last refresh error. A source that +// returns neither a token nor an error is treated as a failed refresh. +// While a refresh runs and the cached token has not expired, a request with a deadline +// waits for the refresh for at most half the time it has left, then uses +// the cached token. A request whose context ends while it waits uses the +// cached token if it has not expired, and otherwise fails with an error +// that wraps the context's error and that gRPC reports as DeadlineExceeded +// or Canceled. func RefreshableToken(src oauth2.TokenSource, opts ...RefreshOption) (AuthProvider, error) { if src == nil { return nil, errNilTokenSource diff --git a/openshell/v1/auth_refresh_test.go b/openshell/v1/auth_refresh_test.go index 69fde8b..bf07cd1 100644 --- a/openshell/v1/auth_refresh_test.go +++ b/openshell/v1/auth_refresh_test.go @@ -15,6 +15,8 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "golang.org/x/oauth2" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) // mockTokenSource implements oauth2.TokenSource for testing. @@ -72,9 +74,137 @@ func TestGetRequestMetadata_ReturnsWhenContextCanceledDuringRefresh(t *testing.T _, err = provider.GetRequestMetadata(ctx) require.ErrorIs(t, err, context.Canceled) + assert.Equal(t, codes.Canceled, status.Code(err), "gRPC reports the cancellation, not Unauthenticated") assert.Less(t, time.Since(started), time.Second) } +// TestGetRequestMetadata_UsesCachedTokenDuringSlowRefresh verifies that +// while a refresh is slow and the cached token has not expired, a request +// with a deadline gets the cached token at half its deadline, a canceled +// request gets it too, and once the cached token has expired the request +// fails with the context's error. +func TestGetRequestMetadata_UsesCachedTokenDuringSlowRefresh(t *testing.T) { + release := make(chan struct{}) + t.Cleanup(func() { close(release) }) + var calls atomic.Int32 + expiry := time.Now().Add(3 * time.Second) + src := &mockTokenSource{tokenFunc: func() (*oauth2.Token, error) { + if calls.Add(1) == 1 { + // Inside the default 10 s leeway, so the next call refreshes. + return &oauth2.Token{AccessToken: "cached-token", Expiry: expiry}, nil + } + <-release + return &oauth2.Token{AccessToken: "late-token"}, nil + }} + provider, err := RefreshableToken(src) + require.NoError(t, err) + _, err = provider.GetRequestMetadata(context.Background()) + require.NoError(t, err) + + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + start := time.Now() + md, err := provider.GetRequestMetadata(ctx) + require.NoError(t, err) + assert.Equal(t, "Bearer cached-token", md["authorization"]) + elapsed := time.Since(start) + assert.Greater(t, elapsed, 800*time.Millisecond, "it waited about half the deadline") + assert.Less(t, elapsed, 1500*time.Millisecond, "it gave up at half the deadline") + + canceled, cancelNow := context.WithCancel(context.Background()) + go func() { + time.Sleep(20 * time.Millisecond) + cancelNow() + }() + md, err = provider.GetRequestMetadata(canceled) + require.NoError(t, err) + assert.Equal(t, "Bearer cached-token", md["authorization"]) + + time.Sleep(time.Until(expiry) + 100*time.Millisecond) + ctx, cancel = context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + _, err = provider.GetRequestMetadata(ctx) + require.ErrorIs(t, err, context.DeadlineExceeded) + assert.Equal(t, codes.DeadlineExceeded, status.Code(err)) + assert.Contains(t, err.Error(), "waiting for a token refresh") +} + +// TestGetRequestMetadata_KeepsWaitingWhenCacheExpiresFirst verifies that a +// request that reaches half its deadline after the cached token expired +// keeps waiting for the refresh instead of sending the expired token. +func TestGetRequestMetadata_KeepsWaitingWhenCacheExpiresFirst(t *testing.T) { + var calls atomic.Int32 + src := &mockTokenSource{tokenFunc: func() (*oauth2.Token, error) { + if calls.Add(1) == 1 { + return &oauth2.Token{AccessToken: "cached-token", Expiry: time.Now().Add(200 * time.Millisecond)}, nil + } + time.Sleep(time.Second) + return &oauth2.Token{AccessToken: "late-token", Expiry: time.Now().Add(time.Hour)}, nil + }} + provider, err := RefreshableToken(src) + require.NoError(t, err) + _, err = provider.GetRequestMetadata(context.Background()) + require.NoError(t, err) + + // Half the deadline is 600 ms, after the cached token expired at 200 ms. + ctx, cancel := context.WithTimeout(context.Background(), 1200*time.Millisecond) + defer cancel() + md, err := provider.GetRequestMetadata(ctx) + require.NoError(t, err) + assert.Equal(t, "Bearer late-token", md["authorization"]) +} + +// TestGetRequestMetadata_RecordsRefreshNobodyWaitedFor verifies that the +// outcome of a refresh is kept even when every request stopped waiting for +// it: a failure starts the backoff, so the source is not asked on every +// request, and a new token is used without asking the source again. +func TestGetRequestMetadata_RecordsRefreshNobodyWaitedFor(t *testing.T) { + newProvider := func(t *testing.T, refresh func() (*oauth2.Token, error)) (AuthProvider, *atomic.Int32) { + t.Helper() + var calls atomic.Int32 + src := &mockTokenSource{tokenFunc: func() (*oauth2.Token, error) { + if calls.Add(1) == 1 { + return &oauth2.Token{AccessToken: "cached-token", Expiry: time.Now().Add(5 * time.Second)}, nil + } + time.Sleep(150 * time.Millisecond) + return refresh() + }} + provider, err := RefreshableToken(src) + require.NoError(t, err) + _, err = provider.GetRequestMetadata(context.Background()) + require.NoError(t, err) + return provider, &calls + } + call := func(t *testing.T, provider AuthProvider) string { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel() + md, err := provider.GetRequestMetadata(ctx) + require.NoError(t, err) + return md["authorization"] + } + + t.Run("failure starts the backoff", func(t *testing.T) { + provider, calls := newProvider(t, func() (*oauth2.Token, error) { return nil, errors.New("provider down") }) + for range 10 { + assert.Equal(t, "Bearer cached-token", call(t, provider)) + time.Sleep(100 * time.Millisecond) + } + // One initial fetch, the first refresh, and at most one more after + // the 1 s backoff. + assert.LessOrEqual(t, calls.Load(), int32(3)) + }) + t.Run("new token is used", func(t *testing.T) { + provider, calls := newProvider(t, func() (*oauth2.Token, error) { + return &oauth2.Token{AccessToken: "new-token", Expiry: time.Now().Add(time.Hour)}, nil + }) + assert.Equal(t, "Bearer cached-token", call(t, provider)) + time.Sleep(300 * time.Millisecond) + assert.Equal(t, "Bearer new-token", call(t, provider)) + assert.Equal(t, int32(2), calls.Load()) + }) +} + // --- Phase 3 / US1 tests: automatic token refresh --- func TestGetRequestMetadata_FirstCallFetchesToken(t *testing.T) { @@ -424,6 +554,46 @@ func TestGetRequestMetadata_BackoffWithoutCachedTokenReturnsLastError(t *testing assert.Equal(t, 1, src.calls(), "should not call Token() during backoff window") } +func TestGetRequestMetadata_NilTokenStartsBackoff(t *testing.T) { + t.Run("no cached token", func(t *testing.T) { + src := &mockTokenSource{ + tokenFunc: func() (*oauth2.Token, error) { return nil, nil }, + } + provider, err := RefreshableToken(src) + require.NoError(t, err) + + _, err = provider.GetRequestMetadata(context.Background()) + require.ErrorIs(t, err, errNilToken) + + _, err = provider.GetRequestMetadata(context.Background()) + require.ErrorIs(t, err, errNilToken) + assert.Equal(t, 1, src.calls(), "a nil token must start the backoff") + }) + + t.Run("cached token", func(t *testing.T) { + var callNum atomic.Int32 + src := &mockTokenSource{ + tokenFunc: func() (*oauth2.Token, error) { + if callNum.Add(1) == 1 { + return &oauth2.Token{AccessToken: "stale", Expiry: time.Now().Add(5 * time.Second)}, nil + } + return nil, nil + }, + } + provider, err := RefreshableToken(src) // default 10s leeway + require.NoError(t, err) + + _, err = provider.GetRequestMetadata(context.Background()) + require.NoError(t, err) + for range 2 { + md, err := provider.GetRequestMetadata(context.Background()) + require.NoError(t, err) + assert.Equal(t, "Bearer stale", md["authorization"]) + } + assert.Equal(t, 2, src.calls(), "a nil token must start the backoff") + }) +} + func TestGetRequestMetadata_BackoffResetsOnSuccess(t *testing.T) { var callNum atomic.Int32 src := &mockTokenSource{ diff --git a/openshell/v1/gateway/doc.go b/openshell/v1/gateway/doc.go index 8516941..d3d0782 100644 --- a/openshell/v1/gateway/doc.go +++ b/openshell/v1/gateway/doc.go @@ -52,10 +52,18 @@ // $XDG_CONFIG_HOME/openshell/gateways//metadata.json (user) // /etc/openshell/gateways//metadata.json (system) // -// Token files (edge_token, cf_token, oidc_token.json) sit alongside -// metadata.json and are read on each authentication attempt, so tokens -// refreshed by the CLI are picked up. A missing or empty file surfaces as -// [ErrTokenLoad] on the RPC that needs it. +// Token files sit alongside metadata.json. Edge authentication reads +// edge_token or cf_token on each request. OIDC authentication reads +// oidc_token.json when it needs a token or the cached token is due for +// renewal, picking up tokens refreshed by the CLI. When the file holds a refresh +// token and was issued for the OIDC issuer and client ID that metadata.json +// names, the client also renews the token itself within 30 seconds of +// expiry, or at half the token's lifetime for tokens valid for less than a +// minute once it has renewed one, and rewrites the file in the CLI's +// format. A missing or empty file, or a failed renewal of an expired +// token, fails the RPC that needs it as Unauthenticated with the +// [ErrTokenLoad] message; an RPC whose deadline ends while it waits for the +// renewal fails with DeadlineExceeded or Canceled instead. // // # Error Handling // @@ -63,7 +71,7 @@ // // - [ErrGatewayNotFound]: no gateway directory found // - [ErrConfigParse]: metadata.json missing or malformed -// - [ErrTokenLoad]: token file missing, unreadable, malformed, or expired; RPCs report it as Unauthenticated +// - [ErrTokenLoad]: token file missing, unreadable, malformed, or expired, or an expired OIDC token could not be renewed; RPCs report it as Unauthenticated // - [ErrUnsupportedAuthMode]: unrecognized auth_mode value // - [ErrInvalidGatewayName]: name fails validation // - [ErrNoActiveGateway]: no active gateway configured diff --git a/openshell/v1/gateway/errors.go b/openshell/v1/gateway/errors.go index b2e09bf..85609ad 100644 --- a/openshell/v1/gateway/errors.go +++ b/openshell/v1/gateway/errors.go @@ -17,7 +17,9 @@ var ( ErrConfigParse = errors.New("gateway: config parse error") // ErrTokenLoad is returned when a token file (edge_token, - // oidc_token.json) is missing, unreadable, malformed, or expired. + // oidc_token.json) is missing, unreadable, malformed, or expired, or + // when an expired OIDC token cannot be renewed. The message names the + // reason, such as the provider's error code or HTTP status. ErrTokenLoad = errors.New("gateway: token load error") // ErrUnsupportedAuthMode is returned when the auth_mode value in diff --git a/openshell/v1/gateway/gateway.go b/openshell/v1/gateway/gateway.go index a7adfdc..3e5df30 100644 --- a/openshell/v1/gateway/gateway.go +++ b/openshell/v1/gateway/gateway.go @@ -33,7 +33,7 @@ func NewClient(name string, opts ...ClientOption) (*v1.Client, error) { // Resolve auth provider: caller override takes precedence. auth := cc.auth if auth == nil { - auth, err = resolveAuthProvider(cfg) + auth, err = resolveAuthProvider(cfg, cc.logger) if err != nil { return nil, err } @@ -154,8 +154,9 @@ func ListGateways() ([]Info, error) { } // resolveAuthProvider maps a Config's AuthMode to an SDK AuthProvider. -// Tokens are loaded lazily where possible. -func resolveAuthProvider(cfg *Config) (types.AuthProvider, error) { +// Tokens are loaded lazily where possible. logger, which may be nil, +// receives OIDC refresh failures that do not fail an RPC. +func resolveAuthProvider(cfg *Config, logger types.Logger) (types.AuthProvider, error) { switch cfg.AuthMode { case AuthModeNone: return v1.NoAuth(), nil @@ -171,8 +172,11 @@ func resolveAuthProvider(cfg *Config) (types.AuthProvider, error) { return &lazyEdgeAuth{dir: cfg.Dir}, nil case AuthModeOIDC: - src := newDiskTokenSource(cfg.Dir, cfg.Name) - return v1.RefreshableToken(src) + var opts []v1.RefreshOption + if logger != nil { + opts = append(opts, v1.WithLogger(logger)) + } + return v1.RefreshableToken(newOIDCTokenSource(cfg, logger), opts...) case AuthModeMTLS: return nil, fmt.Errorf("%w: mtls is not yet supported; use WithAuth() to provide a custom auth provider", ErrUnsupportedAuthMode) diff --git a/openshell/v1/gateway/gateway_test.go b/openshell/v1/gateway/gateway_test.go index d52c6a3..49c1bd6 100644 --- a/openshell/v1/gateway/gateway_test.go +++ b/openshell/v1/gateway/gateway_test.go @@ -190,7 +190,7 @@ func TestNewClient_NoCredentialLeaks(t *testing.T) { AuthMode: AuthModeCloudflareJWT, Dir: filepath.Join(os.Getenv("XDG_CONFIG_HOME"), "openshell", "gateways", "no-edge-gw"), } - auth, authErr := resolveAuthProvider(cfg) + auth, authErr := resolveAuthProvider(cfg, nil) require.NoError(t, authErr) _, err = auth.GetRequestMetadata(context.Background()) require.Error(t, err) @@ -209,7 +209,7 @@ func TestNewClient_NoCredentialLeaks(t *testing.T) { AuthMode: AuthModeCloudflareJWT, Dir: filepath.Join(os.Getenv("XDG_CONFIG_HOME"), "openshell", "gateways", "leak-gw"), } - auth, err = resolveAuthProvider(cfg) + auth, err = resolveAuthProvider(cfg, nil) require.NoError(t, err) // The provider should not expose the token in its string form. @@ -236,7 +236,7 @@ func TestResolveAuthProvider_NoTokenLeaks(t *testing.T) { Dir: gwDir, } - auth, err := resolveAuthProvider(cfg) + auth, err := resolveAuthProvider(cfg, nil) require.NoError(t, err) // The auth provider should work but the token value should not @@ -314,7 +314,7 @@ func TestLoadConfig_FrozenSnapshot(t *testing.T) { func TestResolveAuthProvider_None(t *testing.T) { cfg := &Config{AuthMode: AuthModeNone} - auth, err := resolveAuthProvider(cfg) + auth, err := resolveAuthProvider(cfg, nil) require.NoError(t, err) require.NotNil(t, auth) assert.False(t, auth.RequireTransportSecurity()) @@ -322,7 +322,7 @@ func TestResolveAuthProvider_None(t *testing.T) { func TestResolveAuthProvider_Plaintext(t *testing.T) { cfg := &Config{AuthMode: AuthModePlaintext} - auth, err := resolveAuthProvider(cfg) + auth, err := resolveAuthProvider(cfg, nil) require.NoError(t, err) require.NotNil(t, auth) assert.False(t, auth.RequireTransportSecurity()) @@ -333,7 +333,7 @@ func TestResolveAuthProvider_CloudflareJWT(t *testing.T) { writeFile(t, dir, edgeTokenFile, "cf-jwt-token") cfg := &Config{AuthMode: AuthModeCloudflareJWT, Dir: dir} - auth, err := resolveAuthProvider(cfg) + auth, err := resolveAuthProvider(cfg, nil) require.NoError(t, err) require.NotNil(t, auth) @@ -347,7 +347,7 @@ func TestResolveAuthProvider_OIDC(t *testing.T) { writeFile(t, dir, oidctoken.FileName, oidcBundleJSON("oidc-access-token", "")) cfg := &Config{AuthMode: AuthModeOIDC, Dir: dir, Name: "prod"} - auth, err := resolveAuthProvider(cfg) + auth, err := resolveAuthProvider(cfg, nil) require.NoError(t, err) require.NotNil(t, auth) @@ -358,10 +358,10 @@ func TestResolveAuthProvider_OIDC(t *testing.T) { func TestResolveAuthProvider_OIDCPicksUpReplacedTokenNearExpiry(t *testing.T) { dir := t.TempDir() - // Within the default 10s refresh leeway, so the next call re-reads the file. + // Within the 30 s refresh leeway, so the next call re-reads the file. writeFile(t, dir, oidctoken.FileName, oidcBundleJSON("token-a", fmt.Sprint(time.Now().Add(5*time.Second).Unix()))) - auth, err := resolveAuthProvider(&Config{AuthMode: AuthModeOIDC, Dir: dir, Name: "prod"}) + auth, err := resolveAuthProvider(&Config{AuthMode: AuthModeOIDC, Dir: dir, Name: "prod"}, nil) require.NoError(t, err) md, err := auth.GetRequestMetadata(context.Background()) @@ -379,7 +379,7 @@ func TestResolveAuthProvider_OIDCLegacyFileReturnsLoginHint(t *testing.T) { dir := t.TempDir() writeFile(t, dir, oidctoken.FileName, `{"access_token": "legacy-token", "expiry": "2099-01-01T00:00:00Z"}`) - auth, err := resolveAuthProvider(&Config{AuthMode: AuthModeOIDC, Dir: dir, Name: "prod"}) + auth, err := resolveAuthProvider(&Config{AuthMode: AuthModeOIDC, Dir: dir, Name: "prod"}, nil) require.NoError(t, err) // The second call is answered from the refresh backoff. @@ -392,7 +392,7 @@ func TestResolveAuthProvider_OIDCLegacyFileReturnsLoginHint(t *testing.T) { func TestResolveAuthProvider_MTLS(t *testing.T) { cfg := &Config{AuthMode: AuthModeMTLS} - _, err := resolveAuthProvider(cfg) + _, err := resolveAuthProvider(cfg, nil) require.Error(t, err) assert.ErrorIs(t, err, ErrUnsupportedAuthMode) assert.Contains(t, err.Error(), "mtls") @@ -401,7 +401,7 @@ func TestResolveAuthProvider_MTLS(t *testing.T) { func TestResolveAuthProvider_UnknownMode(t *testing.T) { cfg := &Config{AuthMode: "alien_auth"} - _, err := resolveAuthProvider(cfg) + _, err := resolveAuthProvider(cfg, nil) require.Error(t, err) assert.ErrorIs(t, err, ErrUnsupportedAuthMode) } diff --git a/openshell/v1/gateway/options.go b/openshell/v1/gateway/options.go index 6485201..c4c3bb2 100644 --- a/openshell/v1/gateway/options.go +++ b/openshell/v1/gateway/options.go @@ -24,7 +24,9 @@ type clientConfig struct { // underlying SDK client is created. type ClientOption func(*clientConfig) -// WithLogger sets the logger on the SDK client configuration. +// WithLogger sets the logger on the SDK client configuration. For OIDC +// gateways it also receives failed token renewals, including those that +// do not fail an RPC. func WithLogger(l types.Logger) ClientOption { return func(c *clientConfig) { c.logger = l diff --git a/openshell/v1/gateway/refresh_rpc_test.go b/openshell/v1/gateway/refresh_rpc_test.go new file mode 100644 index 0000000..e789204 --- /dev/null +++ b/openshell/v1/gateway/refresh_rpc_test.go @@ -0,0 +1,356 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package gateway + +import ( + "context" + "fmt" + "net" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" + + v1 "github.com/ai-openshell/sdk-go/openshell/v1" + "github.com/ai-openshell/sdk-go/openshell/v1/internal/oidctoken" + "github.com/ai-openshell/sdk-go/openshell/v1/types" +) + +// authRecorder is a TLS gRPC server that records the authorization header +// of every call and answers each with Unimplemented. It listens on TCP +// rather than bufconn because NewClient dials the endpoint in +// metadata.json and takes no dialer. +type authRecorder struct { + addr string + mu sync.Mutex + seen []string +} + +func newAuthRecorder(t *testing.T) *authRecorder { + t.Helper() + // Borrow httptest's self-signed certificate for the gRPC listener. + certSrv := httptest.NewTLSServer(http.NotFoundHandler()) + cert := certSrv.TLS.Certificates[0] + certSrv.Close() + + lis, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + r := &authRecorder{addr: lis.Addr().String()} + srv := grpc.NewServer( + grpc.Creds(credentials.NewServerTLSFromCert(&cert)), + grpc.UnknownServiceHandler(func(_ any, stream grpc.ServerStream) error { + md, _ := metadata.FromIncomingContext(stream.Context()) + r.mu.Lock() + r.seen = append(r.seen, md.Get("authorization")...) + r.mu.Unlock() + return status.Error(codes.Unimplemented, "recorded") + }), + ) + go func() { _ = srv.Serve(lis) }() + t.Cleanup(srv.Stop) + return r +} + +func (r *authRecorder) headers() []string { + r.mu.Lock() + defer r.mu.Unlock() + return append([]string(nil), r.seen...) +} + +// settle lets a held-up provider answer and waits until the renewal has +// written the file, so no renewal touches the directory after the test. +func settle(t *testing.T, answer func(), dir string) { + t.Helper() + answer() + require.Eventually(t, func() bool { + return readBundle(t, dir).RefreshToken == "rotated-refresh" + }, 10*time.Second, 10*time.Millisecond) +} + +// newOIDCGatewayClient registers an OIDC gateway "rpc-gw" at addr whose +// metadata names issuer, stores access with a refresh token and the given +// expiry relative to now, and returns a client from NewClient with its +// gateway directory. +func newOIDCGatewayClient(t *testing.T, addr, issuer, access string, expiresIn time.Duration) (*v1.Client, string) { + t.Helper() + tmp := setupGateway(t, "rpc-gw", fmt.Sprintf( + `{"gateway_endpoint":%q,"auth_mode":"oidc","oidc_issuer":%q,"oidc_client_id":"openshell-cli"}`, addr, issuer)) + dir := filepath.Join(tmp, "openshell", "gateways", "rpc-gw") + storeToken(t, dir, issuer, access, "stored-refresh", expiresIn) + + client, err := NewClient("rpc-gw", WithTLS(&types.TLSConfig{Insecure: true})) + require.NoError(t, err) + t.Cleanup(func() { _ = client.Close() }) + return client, dir +} + +// TestNewClient_OIDCRenewsExpiredToken checks the issue's acceptance +// criterion end to end: a client from NewClient, holding only an expired +// token and a refresh token, renews the token and sends the new one. +func TestNewClient_OIDCRenewsExpiredToken(t *testing.T) { + rec := newAuthRecorder(t) + p := newTokenProvider(t, rotating) + client, dir := newOIDCGatewayClient(t, rec.addr, p.URL, "expired-access", -time.Minute) + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + _, err := client.Health().Check(ctx) + require.Equal(t, codes.Unimplemented, status.Code(err), "the call reached the server: %v", err) + + assert.Equal(t, []string{"Bearer refreshed-access"}, rec.headers()) + assert.Len(t, p.requests(), 1) + assert.Equal(t, "rotated-refresh", readBundle(t, dir).RefreshToken) +} + +func TestNewClient_OIDCCachesShortLivedToken(t *testing.T) { + rec := newAuthRecorder(t) + p := newTokenProvider(t, func(url.Values) (int, string) { + return http.StatusOK, `{"access_token":"short-access","refresh_token":"rotated-refresh","expires_in":20}` + }) + client, dir := newOIDCGatewayClient(t, rec.addr, p.URL, "expired-access", -time.Minute) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + _, err := client.Health().Check(ctx) + require.Equal(t, codes.Unimplemented, status.Code(err)) + storeToken(t, dir, p.URL, "peer-access", "peer-refresh", time.Hour) + _, err = client.Health().Check(ctx) + require.Equal(t, codes.Unimplemented, status.Code(err)) + + assert.Equal(t, []string{"Bearer short-access", "Bearer short-access"}, rec.headers()) + assert.Len(t, p.requests(), 1) +} + +// TestNewClient_OIDCRenewalFailureIsUnauthenticated checks that a failed +// renewal reaches the caller as Unauthenticated, naming the provider's +// error and the login command, and that no call goes out. +func TestNewClient_OIDCRenewalFailureIsUnauthenticated(t *testing.T) { + rec := newAuthRecorder(t) + p := newTokenProvider(t, func(url.Values) (int, string) { + return http.StatusBadRequest, `{"error":"invalid_grant"}` + }) + client, _ := newOIDCGatewayClient(t, rec.addr, p.URL, "expired-access", -time.Minute) + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + _, err := client.Health().Check(ctx) + require.Error(t, err) + assert.True(t, v1.IsUnauthenticated(err), "got %v", err) + assert.Contains(t, err.Error(), "invalid_grant") + assert.Contains(t, err.Error(), "run `openshell gateway login rpc-gw`") + assert.NotContains(t, err.Error(), "stored-refresh") + assert.Empty(t, rec.headers()) +} + +// TestNewClient_OIDCUsesCachedTokenOutsideWindow checks that the client +// keeps sending its cached token until it is within the 30 s refresh +// window: a token with 45 s left is neither refreshed nor read again. +func TestNewClient_OIDCUsesCachedTokenOutsideWindow(t *testing.T) { + rec := newAuthRecorder(t) + p := newTokenProvider(t, rotating) + client, dir := newOIDCGatewayClient(t, rec.addr, p.URL, "first-access", 45*time.Second) + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + _, err := client.Health().Check(ctx) + require.Equal(t, codes.Unimplemented, status.Code(err), "the call reached the server: %v", err) + + // A token written now is not picked up until the cached one is due. + storeToken(t, dir, p.URL, "second-access", "stored-refresh", time.Hour) + _, err = client.Health().Check(ctx) + require.Equal(t, codes.Unimplemented, status.Code(err), "the call reached the server: %v", err) + + assert.Equal(t, []string{"Bearer first-access", "Bearer first-access"}, rec.headers()) + assert.Empty(t, p.requests()) +} + +// TestNewClient_OIDCRenewsInBackground checks that a client holding a +// token inside the refresh window keeps sending it while a slow renewal +// runs in the background, and sends the renewed token once it is stored. +func TestNewClient_OIDCRenewsInBackground(t *testing.T) { + rec := newAuthRecorder(t) + release := make(chan struct{}) + p := newTokenProvider(t, func(form url.Values) (int, string) { + <-release + return rotating(form) + }) + // Released on every path, or closing the provider waits forever. + answer := sync.OnceFunc(func() { close(release) }) + defer answer() + setRefreshWait(t, 100*time.Millisecond) + client, dir := newOIDCGatewayClient(t, rec.addr, p.URL, "expiring-access", 20*time.Second) + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + _, err := client.Health().Check(ctx) + require.Equal(t, codes.Unimplemented, status.Code(err), "the call reached the server: %v", err) + assert.Equal(t, []string{"Bearer expiring-access"}, rec.headers(), "the call waited for the slow renewal") + + answer() + require.Eventually(t, func() bool { + _, err := client.Health().Check(ctx) + h := rec.headers() + return status.Code(err) == codes.Unimplemented && h[len(h)-1] == "Bearer refreshed-access" + }, 5*time.Second, 20*time.Millisecond) + assert.Equal(t, "rotated-refresh", readBundle(t, dir).RefreshToken) + assert.Len(t, p.requests(), 1) +} + +// TestNewClient_OIDCLogsFailureWithCachedToken checks that the logger +// given to NewClient hears about a token failure the client covers with +// its cached token: here the token file is removed while the cached token +// is inside the refresh window. +func TestNewClient_OIDCLogsFailureWithCachedToken(t *testing.T) { + rec := newAuthRecorder(t) + p := newTokenProvider(t, rotating) + tmp := setupGateway(t, "rpc-gw", fmt.Sprintf( + `{"gateway_endpoint":%q,"auth_mode":"oidc","oidc_issuer":%q,"oidc_client_id":"openshell-cli"}`, rec.addr, p.URL)) + dir := filepath.Join(tmp, "openshell", "gateways", "rpc-gw") + // No refresh token, so nothing renews it. + storeToken(t, dir, p.URL, "cached-access", "", 20*time.Second) + logger := &recordingLogger{} + client, err := NewClient("rpc-gw", WithTLS(&types.TLSConfig{Insecure: true}), WithLogger(logger)) + require.NoError(t, err) + t.Cleanup(func() { _ = client.Close() }) + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + _, err = client.Health().Check(ctx) + require.Equal(t, codes.Unimplemented, status.Code(err), "the call reached the server: %v", err) + + require.NoError(t, os.Remove(filepath.Join(dir, oidctoken.FileName))) + _, err = client.Health().Check(ctx) + require.Equal(t, codes.Unimplemented, status.Code(err), "the call reached the server: %v", err) + + assert.Equal(t, []string{"Bearer cached-access", "Bearer cached-access"}, rec.headers()) + errs := logger.errors() + require.Len(t, errs, 1) + assert.ErrorIs(t, errs[0], ErrTokenLoad) +} + +// TestNewClient_OIDCLogsFailedRenewal checks that a renewal that fails +// while the token is still usable leaves the call working and reaches the +// logger given to NewClient. +func TestNewClient_OIDCLogsFailedRenewal(t *testing.T) { + rec := newAuthRecorder(t) + p := newTokenProvider(t, unavailable) + tmp := setupGateway(t, "rpc-gw", fmt.Sprintf( + `{"gateway_endpoint":%q,"auth_mode":"oidc","oidc_issuer":%q,"oidc_client_id":"openshell-cli"}`, rec.addr, p.URL)) + dir := filepath.Join(tmp, "openshell", "gateways", "rpc-gw") + storeToken(t, dir, p.URL, "usable-access", "stored-refresh", 20*time.Second) + logger := &recordingLogger{} + client, err := NewClient("rpc-gw", WithTLS(&types.TLSConfig{Insecure: true}), WithLogger(logger)) + require.NoError(t, err) + t.Cleanup(func() { _ = client.Close() }) + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + _, err = client.Health().Check(ctx) + require.Equal(t, codes.Unimplemented, status.Code(err), "the call reached the server: %v", err) + assert.Equal(t, []string{"Bearer usable-access"}, rec.headers()) + + require.Eventually(t, func() bool { return len(logger.errors()) > 0 }, 5*time.Second, 10*time.Millisecond) + errs := logger.errors() + require.Len(t, errs, 1) + assert.ErrorIs(t, errs[0], ErrTokenLoad) + assert.Contains(t, errs[0].Error(), "HTTP 503") +} + +// TestNewClient_OIDCHungRenewalDelaysOneCall checks that while a renewal +// hangs, the first call waits refreshWait and later calls are not held up. +func TestNewClient_OIDCHungRenewalDelaysOneCall(t *testing.T) { + rec := newAuthRecorder(t) + release := make(chan struct{}) + p := newTokenProvider(t, func(form url.Values) (int, string) { + <-release + return rotating(form) + }) + answer := sync.OnceFunc(func() { close(release) }) + defer answer() + setRefreshWait(t, time.Second) + client, dir := newOIDCGatewayClient(t, rec.addr, p.URL, "usable-access", 25*time.Second) + + for i := range 4 { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + start := time.Now() + _, err := client.Health().Check(ctx) + cancel() + require.Equal(t, codes.Unimplemented, status.Code(err), "call %d reached the server: %v", i, err) + if i > 0 { + assert.Less(t, time.Since(start), 500*time.Millisecond, "call %d waited for the hung renewal", i) + } + } + assert.Equal(t, []string{"Bearer usable-access", "Bearer usable-access", "Bearer usable-access", "Bearer usable-access"}, rec.headers()) + settle(t, answer, dir) +} + +// TestNewClient_OIDCShortDeadlineUsesCachedToken checks that a call with +// a deadline shorter than refreshWait, made while a renewal hangs, goes out +// with the client's cached token that has not expired. +func TestNewClient_OIDCShortDeadlineUsesCachedToken(t *testing.T) { + rec := newAuthRecorder(t) + release := make(chan struct{}) + p := newTokenProvider(t, func(form url.Values) (int, string) { + <-release + return rotating(form) + }) + answer := sync.OnceFunc(func() { close(release) }) + defer answer() + setRefreshWait(t, 2*time.Second) + // Outside the 30 s window, so the first call caches it. The file keeps + // whole seconds, so this leaves 4 to 5 s. + client, dir := newOIDCGatewayClient(t, rec.addr, p.URL, "cached-access", 35*time.Second) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + _, err := client.Health().Check(ctx) + require.Equal(t, codes.Unimplemented, status.Code(err), "the call reached the server: %v", err) + require.Empty(t, p.requests()) + + // Now inside the window: the next call starts a renewal that hangs. + time.Sleep(5500 * time.Millisecond) + short, cancelShort := context.WithTimeout(context.Background(), 500*time.Millisecond) + defer cancelShort() + _, err = client.Health().Check(short) + require.Equal(t, codes.Unimplemented, status.Code(err), "the call reached the server: %v", err) + assert.Equal(t, []string{"Bearer cached-access", "Bearer cached-access"}, rec.headers()) + settle(t, answer, dir) +} + +// TestNewClient_OIDCFirstCallDeadlineIsNotUnauthenticated checks that the +// first call of a client, which has no cached token yet, fails with its +// own deadline, not as Unauthenticated, when the deadline ends while it +// waits for a slow renewal. +func TestNewClient_OIDCFirstCallDeadlineIsNotUnauthenticated(t *testing.T) { + rec := newAuthRecorder(t) + release := make(chan struct{}) + p := newTokenProvider(t, func(form url.Values) (int, string) { + <-release + return rotating(form) + }) + answer := sync.OnceFunc(func() { close(release) }) + defer answer() + setRefreshWait(t, 2*time.Second) + client, dir := newOIDCGatewayClient(t, rec.addr, p.URL, "usable-access", 20*time.Second) + + ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond) + defer cancel() + _, err := client.Health().Check(ctx) + require.Error(t, err) + assert.Equal(t, codes.DeadlineExceeded, status.Code(err), "got %v", err) + assert.False(t, v1.IsUnauthenticated(err), "got %v", err) + assert.Empty(t, rec.headers()) + settle(t, answer, dir) +} diff --git a/openshell/v1/gateway/refresh_test.go b/openshell/v1/gateway/refresh_test.go new file mode 100644 index 0000000..f7680a5 --- /dev/null +++ b/openshell/v1/gateway/refresh_test.go @@ -0,0 +1,1429 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package gateway + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "runtime" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "golang.org/x/oauth2" + + "github.com/ai-openshell/sdk-go/openshell/v1/internal/oidcclient" + "github.com/ai-openshell/sdk-go/openshell/v1/internal/oidctoken" + "github.com/ai-openshell/sdk-go/openshell/v1/types" +) + +// tokenProvider is a fake OIDC provider. Its token endpoint records each +// request form and answers through respond. +type tokenProvider struct { + *httptest.Server + mu sync.Mutex + forms []url.Values + respond func(form url.Values) (int, string) +} + +func newTokenProvider(t *testing.T, respond func(form url.Values) (int, string)) *tokenProvider { + t.Helper() + oidcclient.ResetDiscoveryCache() + p := &tokenProvider{respond: respond} + mux := http.NewServeMux() + mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "issuer": p.URL, + "authorization_endpoint": p.URL + "/authorize", + "token_endpoint": p.URL + "/token", + }) + }) + mux.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) { + if err := r.ParseForm(); err != nil { + t.Errorf("parse token request: %v", err) + } + p.mu.Lock() + p.forms = append(p.forms, r.PostForm) + p.mu.Unlock() + status, body := p.respond(r.PostForm) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _, _ = w.Write([]byte(body)) + }) + p.Server = httptest.NewServer(mux) + t.Cleanup(p.Close) + return p +} + +// requests returns the forms of all token requests so far. +func (p *tokenProvider) requests() []url.Values { + p.mu.Lock() + defer p.mu.Unlock() + return append([]url.Values(nil), p.forms...) +} + +// rotating answers every refresh with a new access token valid for an hour +// and a rotated refresh token. +func rotating(url.Values) (int, string) { + return http.StatusOK, `{"access_token":"refreshed-access","refresh_token":"rotated-refresh","token_type":"Bearer","expires_in":3600}` +} + +// unavailable answers every refresh with HTTP 503. +func unavailable(url.Values) (int, string) { + return http.StatusServiceUnavailable, `{}` +} + +// bundleFor returns a token file for issuer and client "openshell-cli" +// with the given refresh token and expiry relative to now. +func bundleFor(issuer, access, refresh string, expiresIn time.Duration) oidctoken.Bundle { + return oidctoken.FromToken(&oauth2.Token{ + AccessToken: access, + RefreshToken: refresh, + Expiry: time.Now().Add(expiresIn), + }, issuer, "openshell-cli") +} + +// storeToken writes oidc_token.json for issuer and client "openshell-cli". +func storeToken(t *testing.T, dir, issuer, access, refresh string, expiresIn time.Duration) { + t.Helper() + require.NoError(t, oidcclient.WriteToken(dir, bundleFor(issuer, access, refresh, expiresIn))) +} + +// storeTokenFromHandler is storeToken for a provider's handler goroutine, +// where the test must not be stopped. +func storeTokenFromHandler(t *testing.T, dir, issuer, access, refresh string, expiresIn time.Duration) { + if err := oidcclient.WriteToken(dir, bundleFor(issuer, access, refresh, expiresIn)); err != nil { + t.Errorf("store token: %v", err) + } +} + +func readBundle(t *testing.T, dir string) oidctoken.Bundle { + t.Helper() + data, err := os.ReadFile(filepath.Join(dir, oidctoken.FileName)) + require.NoError(t, err) + var b oidctoken.Bundle + require.NoError(t, json.Unmarshal(data, &b)) + return b +} + +// oidcConfig is an OIDC gateway "prod" in dir whose metadata names issuer, +// client "openshell-cli" and scopes. +func oidcConfig(dir, issuer, scopes string) *Config { + return &Config{ + AuthMode: AuthModeOIDC, Dir: dir, Name: "prod", + OIDCIssuer: issuer, OIDCClientID: "openshell-cli", OIDCScopes: scopes, + } +} + +// oidcSource returns the token source NewClient builds for oidcConfig. The +// test waits for its background refreshes before its directories go away. +func oidcSource(t *testing.T, dir, issuer string, logger types.Logger) *diskTokenSource { + t.Helper() + src := newOIDCTokenSource(oidcConfig(dir, issuer, ""), logger) + t.Cleanup(src.background.Wait) + return src +} + +// oidcAuth returns the auth provider NewClient builds for oidcConfig. Use +// it only with tokens that do not start a background refresh: expired, or +// outside the window. +func oidcAuth(t *testing.T, dir, issuer, scopes string) types.AuthProvider { + t.Helper() + auth, err := resolveAuthProvider(oidcConfig(dir, issuer, scopes), nil) + require.NoError(t, err) + return auth +} + +// setRefreshWait shortens refreshWait for the test. +func setRefreshWait(t *testing.T, d time.Duration) { + old := refreshWait + refreshWait = d + t.Cleanup(func() { refreshWait = old }) +} + +// setRefreshRetryDelay changes refreshRetryDelay for the test. +func setRefreshRetryDelay(t *testing.T, d time.Duration) { + old := refreshRetryDelay + refreshRetryDelay = d + t.Cleanup(func() { refreshRetryDelay = old }) +} + +// setRefreshWaitTimeout shortens refreshWaitTimeout for the test. +func setRefreshWaitTimeout(t *testing.T, d time.Duration) { + old := refreshWaitTimeout + refreshWaitTimeout = d + t.Cleanup(func() { refreshWaitTimeout = old }) +} + +// recordingLogger records the errors it is given. +type recordingLogger struct { + mu sync.Mutex + errs []error + msgs []string + kvs []any +} + +func (l *recordingLogger) Debug(string, ...any) {} +func (l *recordingLogger) Info(string, ...any) {} +func (l *recordingLogger) Error(err error, msg string, keysAndValues ...any) { + l.mu.Lock() + defer l.mu.Unlock() + l.errs = append(l.errs, err) + l.msgs = append(l.msgs, msg) + l.kvs = keysAndValues +} + +func (l *recordingLogger) messages() []string { + l.mu.Lock() + defer l.mu.Unlock() + return append([]string(nil), l.msgs...) +} + +func (l *recordingLogger) lastKeysAndValues() []any { + l.mu.Lock() + defer l.mu.Unlock() + return l.kvs +} + +func (l *recordingLogger) errors() []error { + l.mu.Lock() + defer l.mu.Unlock() + return append([]error(nil), l.errs...) +} + +// tokenWithin calls src.Token and fails the test if it takes longer than +// limit, which shows that Token did not wait for the provider or the lock. +func tokenWithin(t *testing.T, src *diskTokenSource, limit time.Duration) (*oauth2.Token, error) { + t.Helper() + type result struct { + tok *oauth2.Token + err error + } + done := make(chan result, 1) + go func() { + tok, err := src.Token() + done <- result{tok, err} + }() + select { + case res := <-done: + return res.tok, res.err + case <-time.After(limit): + t.Fatalf("Token took longer than %v", limit) + return nil, nil + } +} + +func TestOIDCAuth_RefreshesExpiredToken(t *testing.T) { + p := newTokenProvider(t, rotating) + dir := t.TempDir() + storeToken(t, dir, p.URL, "expired-access", "stored-refresh", -time.Minute) + + md, err := oidcAuth(t, dir, p.URL, "").GetRequestMetadata(context.Background()) + require.NoError(t, err) + assert.Equal(t, "Bearer refreshed-access", md["authorization"]) + + reqs := p.requests() + require.Len(t, reqs, 1) + assert.Equal(t, "refresh_token", reqs[0].Get("grant_type")) + assert.Equal(t, "stored-refresh", reqs[0].Get("refresh_token")) + assert.Equal(t, "openshell-cli", reqs[0].Get("client_id")) + assert.False(t, reqs[0].Has("scope"), "no scope without oidc_scopes") + + b := readBundle(t, dir) + assert.Equal(t, "refreshed-access", b.AccessToken) + assert.Equal(t, "rotated-refresh", b.RefreshToken) + assert.Equal(t, p.URL, b.Issuer) + assert.Equal(t, "openshell-cli", b.ClientID) + require.NotNil(t, b.ExpiresAt) + assert.InDelta(t, time.Now().Add(time.Hour).Unix(), int64(*b.ExpiresAt), 5) + if runtime.GOOS != "windows" { + info, err := os.Stat(filepath.Join(dir, oidctoken.FileName)) + require.NoError(t, err) + assert.Equal(t, os.FileMode(0o600), info.Mode().Perm()) + } +} + +// TestDiskTokenSource_RenewsBeforeExpiry verifies that a token inside the +// 30 s window is renewed before Token returns when the provider answers +// within refreshWait. +func TestDiskTokenSource_RenewsBeforeExpiry(t *testing.T) { + p := newTokenProvider(t, rotating) + dir := t.TempDir() + storeToken(t, dir, p.URL, "expiring-access", "stored-refresh", 20*time.Second) + + tok, err := oidcSource(t, dir, p.URL, nil).Token() + require.NoError(t, err) + assert.Equal(t, "refreshed-access", tok.AccessToken) + assert.Equal(t, "rotated-refresh", readBundle(t, dir).RefreshToken) + assert.Len(t, p.requests(), 1) +} + +// TestDiskTokenSource_SlowRenewalFinishesInBackground verifies that when +// the provider takes longer than refreshWait, Token returns the current +// token and the renewal still finishes and is used by the next call. +func TestDiskTokenSource_SlowRenewalFinishesInBackground(t *testing.T) { + setRefreshWait(t, 100*time.Millisecond) + release := make(chan struct{}) + p := newTokenProvider(t, func(form url.Values) (int, string) { + <-release + return rotating(form) + }) + answer := sync.OnceFunc(func() { close(release) }) + defer answer() + dir := t.TempDir() + storeToken(t, dir, p.URL, "expiring-access", "stored-refresh", 20*time.Second) + src := oidcSource(t, dir, p.URL, nil) + + tok, err := tokenWithin(t, src, 2*time.Second) + require.NoError(t, err) + assert.Equal(t, "expiring-access", tok.AccessToken) + + answer() + src.background.Wait() + tok, err = src.Token() + require.NoError(t, err) + assert.Equal(t, "refreshed-access", tok.AccessToken) + assert.Len(t, p.requests(), 1) +} + +func TestOIDCAuth_DoesNotRefreshOutsideWindow(t *testing.T) { + p := newTokenProvider(t, rotating) + dir := t.TempDir() + // Well outside the window: the file keeps whole seconds, so a margin + // of a second could fall inside it. + storeToken(t, dir, p.URL, "valid-access", "stored-refresh", refreshWindow+time.Minute) + + md, err := oidcAuth(t, dir, p.URL, "").GetRequestMetadata(context.Background()) + require.NoError(t, err) + assert.Equal(t, "Bearer valid-access", md["authorization"]) + assert.Empty(t, p.requests()) +} + +func TestDiskTokenSource_NoRefreshWithoutRefreshTokenOrExpiry(t *testing.T) { + p := newTokenProvider(t, rotating) + + t.Run("expired, no refresh token", func(t *testing.T) { + dir := t.TempDir() + storeToken(t, dir, p.URL, "expired-access", "", -time.Minute) + _, err := oidcSource(t, dir, p.URL, nil).Token() + require.ErrorIs(t, err, ErrTokenLoad) + assert.Contains(t, err.Error(), "expired at") + assert.Contains(t, err.Error(), loginHint) + }) + t.Run("expiring, no refresh token", func(t *testing.T) { + dir := t.TempDir() + storeToken(t, dir, p.URL, "expiring-access", "", 5*time.Second) + tok, err := oidcSource(t, dir, p.URL, nil).Token() + require.NoError(t, err) + assert.Equal(t, "expiring-access", tok.AccessToken) + }) + t.Run("no expiry", func(t *testing.T) { + dir := t.TempDir() + b := oidctoken.Bundle{AccessToken: "forever", RefreshToken: "stored-refresh", Issuer: p.URL, ClientID: "openshell-cli"} + require.NoError(t, oidcclient.WriteToken(dir, b)) + tok, err := oidcSource(t, dir, p.URL, nil).Token() + require.NoError(t, err) + assert.Equal(t, "forever", tok.AccessToken) + }) + assert.Empty(t, p.requests()) +} + +// TestDiskTokenSource_NoRefreshWithoutMetadataClient verifies that a +// gateway whose metadata.json names no issuer or client ID does not +// refresh, as Login refuses to: the refresh token would go to whatever +// issuer the token file names. +func TestDiskTokenSource_NoRefreshWithoutMetadataClient(t *testing.T) { + p := newTokenProvider(t, rotating) + for name, cfg := range map[string]func(dir string) *Config{ + "no issuer": func(dir string) *Config { + c := oidcConfig(dir, p.URL, "") + c.OIDCIssuer = "" + return c + }, + "no client ID": func(dir string) *Config { + c := oidcConfig(dir, p.URL, "") + c.OIDCClientID = "" + return c + }, + } { + t.Run(name, func(t *testing.T) { + dir := t.TempDir() + storeToken(t, dir, p.URL, "expired-access", "stored-refresh", -time.Minute) + src := newOIDCTokenSource(cfg(dir), nil) + t.Cleanup(src.background.Wait) + + _, err := src.Token() + require.ErrorIs(t, err, ErrTokenLoad) + assert.Contains(t, err.Error(), "expired at") + + storeToken(t, dir, p.URL, "expiring-access", "stored-refresh", 5*time.Second) + tok, err := src.Token() + require.NoError(t, err) + assert.Equal(t, "expiring-access", tok.AccessToken) + }) + } + assert.Empty(t, p.requests()) +} + +func TestOIDCAuth_RefreshSendsGatewayScopes(t *testing.T) { + p := newTokenProvider(t, rotating) + dir := t.TempDir() + storeToken(t, dir, p.URL, "expired-access", "stored-refresh", -time.Minute) + + _, err := oidcAuth(t, dir, p.URL, "sandbox:read openid offline_access").GetRequestMetadata(context.Background()) + require.NoError(t, err) + reqs := p.requests() + require.Len(t, reqs, 1) + assert.Equal(t, "openid sandbox:read offline_access", reqs[0].Get("scope")) +} + +func TestDiskTokenSource_RefreshKeepsRefreshTokenWhenNotRotated(t *testing.T) { + p := newTokenProvider(t, func(url.Values) (int, string) { + return http.StatusOK, `{"access_token":"refreshed-access","token_type":"Bearer","expires_in":3600}` + }) + dir := t.TempDir() + storeToken(t, dir, p.URL, "expired-access", "stored-refresh", -time.Minute) + + tok, err := oidcSource(t, dir, p.URL, nil).Token() + require.NoError(t, err) + assert.Equal(t, "refreshed-access", tok.AccessToken) + assert.Equal(t, "stored-refresh", readBundle(t, dir).RefreshToken) +} + +func TestDiskTokenSource_RefreshFailureReportsReason(t *testing.T) { + for name, tc := range map[string]struct { + status int + body string + want string + wantIs error + }{ + "invalid_grant": { + status: http.StatusBadRequest, + body: `{"error":"invalid_grant","error_description":"Token is not active"}`, + want: "invalid_grant", + wantIs: oidcclient.ErrInvalidGrant, + }, + "provider error code": { + status: http.StatusUnauthorized, + body: `{"error":"invalid_client","error_description":"stored-refresh leaked?"}`, + want: `"invalid_client"`, + wantIs: oidcclient.ErrRefresh, + }, + "server error": { + status: http.StatusInternalServerError, + body: `{}`, + want: "HTTP 500", + wantIs: oidcclient.ErrRefresh, + }, + "proxy error page": { + status: http.StatusBadGateway, + body: `502 Bad Gateway`, + want: "HTTP 502", + wantIs: oidcclient.ErrRefresh, + }, + } { + t.Run(name, func(t *testing.T) { + p := newTokenProvider(t, func(url.Values) (int, string) { return tc.status, tc.body }) + dir := t.TempDir() + storeToken(t, dir, p.URL, "expired-access", "stored-refresh", -time.Minute) + + _, err := oidcSource(t, dir, p.URL, nil).Token() + require.ErrorIs(t, err, ErrTokenLoad) + require.ErrorIs(t, err, tc.wantIs) + assert.Contains(t, err.Error(), tc.want) + assert.Contains(t, err.Error(), loginHint) + assert.NotContains(t, err.Error(), "stored-refresh") + assert.NotContains(t, err.Error(), "Token is not active", "error_description is left out") + assert.Equal(t, "stored-refresh", readBundle(t, dir).RefreshToken, "the file is unchanged") + }) + } +} + +func TestDiskTokenSource_DiscoveryFailureIsReported(t *testing.T) { + srv := httptest.NewServer(http.NotFoundHandler()) + t.Cleanup(srv.Close) + oidcclient.ResetDiscoveryCache() + dir := t.TempDir() + storeToken(t, dir, srv.URL, "expired-access", "stored-refresh", -time.Minute) + + _, err := oidcSource(t, dir, srv.URL, nil).Token() + require.ErrorIs(t, err, ErrTokenLoad) + require.ErrorIs(t, err, oidcclient.ErrDiscovery) + assert.Contains(t, err.Error(), "HTTP 404") +} + +// TestDiskTokenSource_DiscoveryWaitIsBounded verifies that a discovery +// endpoint that does not answer delays Token by refreshWaitTimeout, not +// by the HTTP client's timeout. +func TestDiskTokenSource_DiscoveryWaitIsBounded(t *testing.T) { + setRefreshWaitTimeout(t, 100*time.Millisecond) + + release := make(chan struct{}) + srv := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { <-release })) + t.Cleanup(srv.Close) + t.Cleanup(func() { close(release) }) + oidcclient.ResetDiscoveryCache() + dir := t.TempDir() + storeToken(t, dir, srv.URL, "expired-access", "stored-refresh", -time.Minute) + + _, err := tokenWithin(t, oidcSource(t, dir, srv.URL, nil), 5*time.Second) + require.ErrorIs(t, err, ErrTokenLoad) + require.ErrorIs(t, err, oidcclient.ErrDiscovery) +} + +func TestDiskTokenSource_InvalidGrantUsesPeerToken(t *testing.T) { + dir := t.TempDir() + var p *tokenProvider + p = newTokenProvider(t, func(url.Values) (int, string) { + // Another process refreshed with the same refresh token first. + storeTokenFromHandler(t, dir, p.URL, "peer-access", "peer-refresh", time.Hour) + return http.StatusBadRequest, `{"error":"invalid_grant"}` + }) + storeToken(t, dir, p.URL, "expired-access", "stored-refresh", -time.Minute) + + tok, err := oidcSource(t, dir, p.URL, nil).Token() + require.NoError(t, err) + assert.Equal(t, "peer-access", tok.AccessToken) + assert.Len(t, p.requests(), 1) +} + +func TestOIDCAuth_ConcurrentRequestsRefreshOnce(t *testing.T) { + p := newTokenProvider(t, rotating) + dir := t.TempDir() + storeToken(t, dir, p.URL, "expired-access", "stored-refresh", -time.Minute) + + // Two clients for the same gateway, as two NewClient calls make, each + // with eight concurrent RPCs. Each client shares one refresh between + // its RPCs; the clients share the per-directory lock, so the second + // finds the token the first wrote. + auths := []types.AuthProvider{oidcAuth(t, dir, p.URL, ""), oidcAuth(t, dir, p.URL, "")} + var wg sync.WaitGroup + errs := make(chan error, 16) + for i := range 16 { + wg.Go(func() { + md, err := auths[i%2].GetRequestMetadata(context.Background()) + if err == nil && md["authorization"] != "Bearer refreshed-access" { + err = fmt.Errorf("unexpected token %q", md["authorization"]) + } + errs <- err + }) + } + wg.Wait() + close(errs) + for err := range errs { + require.NoError(t, err) + } + assert.Len(t, p.requests(), 1) +} + +func TestOIDCAuth_CanceledRequestStillStoresRotatedToken(t *testing.T) { + release := make(chan struct{}) + p := newTokenProvider(t, func(form url.Values) (int, string) { + <-release + return rotating(form) + }) + answer := sync.OnceFunc(func() { close(release) }) + defer answer() + dir := t.TempDir() + storeToken(t, dir, p.URL, "expired-access", "stored-refresh", -time.Minute) + auth := oidcAuth(t, dir, p.URL, "") + + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel() + _, err := auth.GetRequestMetadata(ctx) + require.ErrorIs(t, err, context.DeadlineExceeded) + + // The provider answers after the RPC gave up. RefreshableToken runs + // Token apart from the RPC, so the refresh still finishes and stores + // the rotated token. + answer() + require.Eventually(t, func() bool { + return readBundle(t, dir).RefreshToken == "rotated-refresh" + }, 5*time.Second, 10*time.Millisecond) + + md, err := auth.GetRequestMetadata(context.Background()) + require.NoError(t, err) + assert.Equal(t, "Bearer refreshed-access", md["authorization"]) + assert.Len(t, p.requests(), 1) +} + +func TestOIDCAuth_OtherIssuerOrClientDoesNotRefresh(t *testing.T) { + p := newTokenProvider(t, rotating) + other := newTokenProvider(t, rotating) + + t.Run("expired, other issuer", func(t *testing.T) { + dir := t.TempDir() + storeToken(t, dir, other.URL, "expired-access", "stored-refresh", -time.Minute) + _, err := oidcAuth(t, dir, p.URL, "").GetRequestMetadata(context.Background()) + require.ErrorIs(t, err, ErrTokenLoad) + assert.Contains(t, err.Error(), "another issuer or client than metadata.json names") + assert.Contains(t, err.Error(), loginHint) + }) + t.Run("expired, other client", func(t *testing.T) { + dir := t.TempDir() + storeToken(t, dir, p.URL, "expired-access", "stored-refresh", -time.Minute) + cfg := oidcConfig(dir, p.URL, "") + cfg.OIDCClientID = "other-client" + auth, err := resolveAuthProvider(cfg, nil) + require.NoError(t, err) + _, err = auth.GetRequestMetadata(context.Background()) + require.ErrorIs(t, err, ErrTokenLoad) + assert.Contains(t, err.Error(), "another issuer or client than metadata.json names") + }) + t.Run("expiring, other issuer", func(t *testing.T) { + dir := t.TempDir() + storeToken(t, dir, other.URL, "expiring-access", "stored-refresh", 5*time.Second) + md, err := oidcAuth(t, dir, p.URL, "").GetRequestMetadata(context.Background()) + require.NoError(t, err) + assert.Equal(t, "Bearer expiring-access", md["authorization"]) + }) + t.Run("trailing slash is the same issuer", func(t *testing.T) { + dir := t.TempDir() + storeToken(t, dir, p.URL, "expired-access", "stored-refresh", -time.Minute) + md, err := oidcAuth(t, dir, p.URL+"/", "").GetRequestMetadata(context.Background()) + require.NoError(t, err) + assert.Equal(t, "Bearer refreshed-access", md["authorization"]) + }) + assert.Len(t, p.requests(), 1) + assert.Empty(t, other.requests()) +} + +func TestDiskTokenSource_ShortLivedTokensAreNotRefreshedOnEveryCall(t *testing.T) { + // Tokens valid for less than the 30 s window: without the cap at half + // their lifetime, every call would refresh. + for _, lifetime := range []int{4, 20} { + t.Run(fmt.Sprintf("%d s", lifetime), func(t *testing.T) { + p := newTokenProvider(t, func(url.Values) (int, string) { + return http.StatusOK, fmt.Sprintf(`{"access_token":"short-access","refresh_token":"rotated-refresh","token_type":"Bearer","expires_in":%d}`, lifetime) + }) + dir := t.TempDir() + storeToken(t, dir, p.URL, "expired-access", "stored-refresh", -time.Minute) + src := oidcSource(t, dir, p.URL, nil) + + tok, err := src.Token() + require.NoError(t, err) + assert.Equal(t, "short-access", tok.AccessToken) + for range 5 { + tok, err = src.Token() + require.NoError(t, err) + assert.Equal(t, "short-access", tok.AccessToken) + } + assert.Len(t, p.requests(), 1) + }) + } +} + +// TestDiskTokenSource_WindowFollowsGrantedLifetime verifies that the +// window is half the lifetime of the last granted token when that is +// under 60 s, twice the window, and the full 30 s otherwise. +func TestDiskTokenSource_WindowFollowsGrantedLifetime(t *testing.T) { + for lifetime, want := range map[int]time.Duration{ + 4: 2 * time.Second, + 20: 10 * time.Second, + 45: 22500 * time.Millisecond, + 61: refreshWindow, + 3600: refreshWindow, + } { + t.Run(fmt.Sprintf("%d s", lifetime), func(t *testing.T) { + p := newTokenProvider(t, func(url.Values) (int, string) { + return http.StatusOK, fmt.Sprintf(`{"access_token":"a","refresh_token":"r","expires_in":%d}`, lifetime) + }) + dir := t.TempDir() + storeToken(t, dir, p.URL, "expired-access", "stored-refresh", -time.Minute) + src := oidcSource(t, dir, p.URL, nil) + assert.Equal(t, refreshWindow, time.Duration(src.RefreshWindow()), "before any grant") + + _, err := src.Token() + require.NoError(t, err) + assert.InDelta(t, want.Seconds(), time.Duration(src.RefreshWindow()).Seconds(), 0.5) + }) + } +} + +// TestDiskTokenSource_WindowIgnoresPeerTokens verifies that the window is +// sized by tokens from this source's own token requests, not by the time +// left on a token another caller stored. +func TestDiskTokenSource_WindowIgnoresPeerTokens(t *testing.T) { + setRefreshWaitTimeout(t, 5*time.Second) + + p := newTokenProvider(t, rotating) + dir := t.TempDir() + storeToken(t, dir, p.URL, "expired-access", "stored-refresh", -time.Minute) + unlock, err := oidcclient.LockDir(context.Background(), dir) + require.NoError(t, err) + go func() { + // A peer stores a token with 40 s left while Token waits. + time.Sleep(20 * time.Millisecond) + storeTokenFromHandler(t, dir, p.URL, "peer-access", "peer-refresh", 40*time.Second) + unlock() + }() + src := oidcSource(t, dir, p.URL, nil) + + tok, err := src.Token() + require.NoError(t, err) + assert.Equal(t, "peer-access", tok.AccessToken) + assert.Equal(t, refreshWindow, time.Duration(src.RefreshWindow())) + assert.Empty(t, p.requests()) +} + +// TestDiskTokenSource_UnwritableDirSpendsNoRefreshToken verifies that a +// token directory the process cannot write to is reported before the +// token request, so a rotating provider does not revoke the stored +// refresh token for a response that could not be kept. +func TestDiskTokenSource_UnwritableDirSpendsNoRefreshToken(t *testing.T) { + if runtime.GOOS == "windows" || os.Geteuid() == 0 { + t.Skip("needs a directory the process cannot write to") + } + p := newTokenProvider(t, rotating) + dir := t.TempDir() + storeToken(t, dir, p.URL, "expired-access", "stored-refresh", -time.Minute) + require.NoError(t, os.Chmod(dir, 0o500)) + t.Cleanup(func() { _ = os.Chmod(dir, 0o700) }) + + _, err := oidcSource(t, dir, p.URL, nil).Token() + require.ErrorIs(t, err, ErrTokenLoad) + require.ErrorIs(t, err, oidcclient.ErrTokenPersist) + assert.Empty(t, p.requests()) + assert.Equal(t, "stored-refresh", readBundle(t, dir).RefreshToken) +} + +// TestOIDCAuth_WriteFailureKeepsRenewedToken verifies that a token the +// provider issued is used, and logged, when it cannot be written: the +// provider has already revoked the refresh token in the file. +func TestOIDCAuth_WriteFailureKeepsRenewedToken(t *testing.T) { + if runtime.GOOS == "windows" || os.Geteuid() == 0 { + t.Skip("needs a directory the process cannot write to") + } + dir := t.TempDir() + p := newTokenProvider(t, func(form url.Values) (int, string) { + // The directory becomes read-only while the request is in flight. + if err := os.Chmod(dir, 0o500); err != nil { + t.Errorf("chmod: %v", err) + } + return rotating(form) + }) + storeToken(t, dir, p.URL, "expired-access", "stored-refresh", -time.Minute) + t.Cleanup(func() { _ = os.Chmod(dir, 0o700) }) + logger := &recordingLogger{} + auth, err := resolveAuthProvider(oidcConfig(dir, p.URL, ""), logger) + require.NoError(t, err) + + for range 3 { + md, err := auth.GetRequestMetadata(context.Background()) + require.NoError(t, err) + assert.Equal(t, "Bearer refreshed-access", md["authorization"]) + } + assert.Len(t, p.requests(), 1) + assert.Equal(t, "stored-refresh", readBundle(t, dir).RefreshToken) + errs := logger.errors() + require.Len(t, errs, 1) + assert.ErrorIs(t, errs[0], oidcclient.ErrTokenPersist) +} + +// TestDiskTokenSource_UnsavedTokenOutlivesWaiters verifies that a renewed +// token that could not be written is kept after every caller stopped +// waiting for it: the provider has revoked the refresh token in the file. +// Token uses it, a renewal does not send the revoked refresh token while +// it still cannot be written, and once the directory is writable again +// the next renewal writes it and refreshes with its refresh token. +func TestDiskTokenSource_UnsavedTokenOutlivesWaiters(t *testing.T) { + if runtime.GOOS == "windows" || os.Geteuid() == 0 { + t.Skip("needs a directory the process cannot write to") + } + setRefreshWait(t, 50*time.Millisecond) + setRefreshRetryDelay(t, 10*time.Millisecond) + dir := t.TempDir() + t.Cleanup(func() { _ = os.Chmod(dir, 0o700) }) + var calls atomic.Int32 + p := newTokenProvider(t, func(url.Values) (int, string) { + if calls.Add(1) == 1 { + // Slower than refreshWait, and the directory becomes read-only + // before the response arrives. + time.Sleep(200 * time.Millisecond) + if err := os.Chmod(dir, 0o500); err != nil { + t.Errorf("chmod: %v", err) + } + // Due in 3 s: the window is half of its 6 s lifetime. + return http.StatusOK, `{"access_token":"renewed-1","refresh_token":"rt-1","token_type":"Bearer","expires_in":6}` + } + return http.StatusOK, `{"access_token":"renewed-2","refresh_token":"rt-2","token_type":"Bearer","expires_in":3600}` + }) + storeToken(t, dir, p.URL, "usable-access", "stored-refresh", 8*time.Second) + logger := &recordingLogger{} + src := oidcSource(t, dir, p.URL, logger) + + tok, err := tokenWithin(t, src, 2*time.Second) + require.NoError(t, err) + assert.Equal(t, "usable-access", tok.AccessToken, "the caller stopped waiting") + src.background.Wait() + assert.Contains(t, logger.messages(), "cannot store the renewed OIDC token") + + tok, err = src.Token() + require.NoError(t, err) + assert.Equal(t, "renewed-1", tok.AccessToken, "the unwritten token is used") + assert.Equal(t, "stored-refresh", readBundle(t, dir).RefreshToken) + require.Len(t, p.requests(), 1) + + // Once renewed-1 is due, renewals cannot write it and send nothing. + deadline := time.Now().Add(4 * time.Second) + for len(logger.messages()) < 2 && time.Now().Before(deadline) { + tok, err = src.Token() + require.NoError(t, err) + assert.Equal(t, "renewed-1", tok.AccessToken) + src.background.Wait() + time.Sleep(20 * time.Millisecond) + } + msgs := logger.messages() + require.Len(t, msgs, 2, "no renewal of the due token was attempted") + assert.Equal(t, "OIDC token renewal failed", msgs[1]) + assert.ErrorIs(t, logger.errors()[1], ErrTokenLoad) + require.Len(t, p.requests(), 1, "the revoked refresh token was sent") + + require.NoError(t, os.Chmod(dir, 0o700)) + time.Sleep(20 * time.Millisecond) // past the retry delay + _, err = src.Token() + require.NoError(t, err) + // renewed-1 is still valid, so on a loaded machine the call may return + // it after refreshWait while the renewal goes on. + src.background.Wait() + tok, err = src.Token() + require.NoError(t, err) + assert.Equal(t, "renewed-2", tok.AccessToken) + reqs := p.requests() + require.Len(t, reqs, 2) + assert.Equal(t, "rt-1", reqs[1].Get("refresh_token"), "the refresh used the unwritten token's refresh token") + b := readBundle(t, dir) + assert.Equal(t, "renewed-2", b.AccessToken) + assert.Equal(t, "rt-2", b.RefreshToken) +} + +// TestDiskTokenSource_UnsavedTokenYieldsToFileChanges verifies that an +// unwritten renewed token is dropped when the file changes, as after a +// login, and is not served after a logout removed the file. +func TestDiskTokenSource_UnsavedTokenYieldsToFileChanges(t *testing.T) { + if runtime.GOOS == "windows" || os.Geteuid() == 0 { + t.Skip("needs a directory the process cannot write to") + } + for _, change := range []string{"login", "logout"} { + t.Run(change, func(t *testing.T) { + dir := t.TempDir() + t.Cleanup(func() { _ = os.Chmod(dir, 0o700) }) + p := newTokenProvider(t, func(form url.Values) (int, string) { + if err := os.Chmod(dir, 0o500); err != nil { + t.Errorf("chmod: %v", err) + } + return rotating(form) + }) + storeToken(t, dir, p.URL, "expired-access", "stored-refresh", -time.Minute) + src := oidcSource(t, dir, p.URL, nil) + + tok, err := src.Token() + require.NoError(t, err) + assert.Equal(t, "refreshed-access", tok.AccessToken) + src.background.Wait() + src.mu.Lock() + require.NotNil(t, src.unsaved, "the unwritten token was not kept") + src.mu.Unlock() + require.NoError(t, os.Chmod(dir, 0o700)) + + if change == "login" { + storeToken(t, dir, p.URL, "login-access", "login-refresh", time.Hour) + for range 2 { + tok, err = src.Token() + require.NoError(t, err) + assert.Equal(t, "login-access", tok.AccessToken) + } + } else { + require.NoError(t, os.Remove(filepath.Join(dir, oidctoken.FileName))) + _, err = src.Token() + require.ErrorIs(t, err, ErrTokenLoad) + } + assert.Len(t, p.requests(), 1) + src.mu.Lock() + defer src.mu.Unlock() + if change == "login" { + assert.Nil(t, src.unsaved) + } + }) + } +} + +// TestDiskTokenSource_SaveUnsaved verifies how a renewal writes an +// unwritten renewed token first: under the refresh lock, only over the +// token it replaced, keeping the file's other fields, and not at all when +// the file cannot be read. +func TestDiskTokenSource_SaveUnsaved(t *testing.T) { + const issuer = "https://issuer.example" + unsavedFor := func(src *diskTokenSource, over string) *unsavedToken { + b := bundleFor(issuer, "unsaved-access", "unsaved-refresh", time.Hour) + b.ClientCredentials = true + u := &unsavedToken{bundle: b, over: over, rotated: true} + src.mu.Lock() + src.unsaved = u + src.mu.Unlock() + return u + } + unsaved := func(src *diskTokenSource) *unsavedToken { + src.mu.Lock() + defer src.mu.Unlock() + return src.unsaved + } + + t.Run("writes over the token it replaced", func(t *testing.T) { + dir := t.TempDir() + storeToken(t, dir, issuer, "old-access", "old-refresh", time.Minute) + src := oidcSource(t, dir, issuer, nil) + unsavedFor(src, "old-access") + _, err := src.saveUnsaved(context.Background()) + require.NoError(t, err) + b := readBundle(t, dir) + assert.Equal(t, "unsaved-access", b.AccessToken) + assert.Equal(t, "unsaved-refresh", b.RefreshToken) + assert.True(t, b.ClientCredentials) + assert.Nil(t, unsaved(src)) + }) + t.Run("file changed since", func(t *testing.T) { + dir := t.TempDir() + storeToken(t, dir, issuer, "newer-access", "newer-refresh", time.Hour) + src := oidcSource(t, dir, issuer, nil) + unsavedFor(src, "old-access") + _, err := src.saveUnsaved(context.Background()) + require.NoError(t, err) + assert.Equal(t, "newer-access", readBundle(t, dir).AccessToken, "the newer token was overwritten") + assert.Nil(t, unsaved(src)) + }) + t.Run("file removed since", func(t *testing.T) { + dir := t.TempDir() + src := oidcSource(t, dir, issuer, nil) + unsavedFor(src, "old-access") + _, err := src.saveUnsaved(context.Background()) + require.NoError(t, err) + _, err = os.Stat(filepath.Join(dir, oidctoken.FileName)) + assert.ErrorIs(t, err, os.ErrNotExist, "the logout was undone") + assert.Nil(t, unsaved(src)) + }) + t.Run("file unreadable", func(t *testing.T) { + dir := t.TempDir() + writeFile(t, dir, oidctoken.FileName, "{not json") + src := oidcSource(t, dir, issuer, nil) + u := unsavedFor(src, "old-access") + rotated, err := src.saveUnsaved(context.Background()) + require.Error(t, err) + assert.True(t, rotated) + data, err := os.ReadFile(filepath.Join(dir, oidctoken.FileName)) + require.NoError(t, err) + assert.Equal(t, "{not json", string(data)) + assert.Same(t, u, unsaved(src)) + }) + t.Run("waits for the refresh lock", func(t *testing.T) { + dir := t.TempDir() + storeToken(t, dir, issuer, "old-access", "old-refresh", time.Minute) + src := oidcSource(t, dir, issuer, nil) + u := unsavedFor(src, "old-access") + unlock, err := oidcclient.LockDir(context.Background(), dir) + require.NoError(t, err) + defer unlock() + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) + defer cancel() + _, err = src.saveUnsaved(ctx) + require.ErrorIs(t, err, context.DeadlineExceeded) + assert.Equal(t, "old-access", readBundle(t, dir).AccessToken) + assert.Same(t, u, unsaved(src)) + }) + t.Run("keepUnsaved", func(t *testing.T) { + src := oidcSource(t, t.TempDir(), issuer, nil) + file := bundleFor(issuer, "file-access", "file-refresh", time.Minute) + renewed := bundleFor(issuer, "new-access", "new-refresh", time.Hour) + renewed.ClientCredentials = true + src.keepUnsaved(oidcclient.Result{Granted: true, Unwritten: &renewed, Replaced: &file}) + u := unsaved(src) + require.NotNil(t, u) + assert.Equal(t, "file-access", u.over) + assert.Equal(t, renewed, u.bundle) + assert.True(t, u.rotated) + + same := bundleFor(issuer, "same-access", "file-refresh", time.Hour) + src.keepUnsaved(oidcclient.Result{Granted: true, Unwritten: &same, Replaced: &file}) + require.NotNil(t, unsaved(src)) + assert.Equal(t, "same-access", unsaved(src).bundle.AccessToken) + assert.False(t, unsaved(src).rotated, "the refresh token was not rotated") + + src.keepUnsaved(oidcclient.Result{Granted: true}) + assert.Equal(t, "same-access", unsaved(src).bundle.AccessToken, "a result without Unwritten replaced the kept token") + }) +} + +// TestDiskTokenSource_UnsavedTokenLosesToLoginDuringFailedWrite verifies +// that a login that lands right after a failed write, while the renewal +// still reports it, wins over the unwritten token and is not overwritten. +func TestDiskTokenSource_UnsavedTokenLosesToLoginDuringFailedWrite(t *testing.T) { + if runtime.GOOS == "windows" || os.Geteuid() == 0 { + t.Skip("needs a directory the process cannot write to") + } + dir := t.TempDir() + t.Cleanup(func() { _ = os.Chmod(dir, 0o700) }) + p := newTokenProvider(t, func(form url.Values) (int, string) { + if err := os.Chmod(dir, 0o500); err != nil { + t.Errorf("chmod: %v", err) + } + return rotating(form) + }) + storeToken(t, dir, p.URL, "expired-access", "stored-refresh", -time.Minute) + // The login happens while the renewal reports the failed write. + logger := &hookLogger{onError: func(msg string) { + if msg != "cannot store the renewed OIDC token" { + return + } + if err := os.Chmod(dir, 0o700); err != nil { + t.Errorf("chmod: %v", err) + } + storeTokenFromHandler(t, dir, p.URL, "login-access", "login-refresh", time.Hour) + }} + src := oidcSource(t, dir, p.URL, logger) + + tok, err := src.Token() + require.NoError(t, err) + assert.Equal(t, "refreshed-access", tok.AccessToken) + tok, err = src.Token() + require.NoError(t, err) + assert.Equal(t, "login-access", tok.AccessToken) + _, err = src.saveUnsaved(context.Background()) + require.NoError(t, err) + assert.Equal(t, "login-refresh", readBundle(t, dir).RefreshToken) +} + +// TestDiskTokenSource_UnsavedTokenWithoutRotation verifies that a failed +// write of an unwritten token stops token requests only when the refresh +// token was rotated: otherwise the one in the file still works. +func TestDiskTokenSource_UnsavedTokenWithoutRotation(t *testing.T) { + old := writeUnsaved + writeUnsaved = func(context.Context, string, oidctoken.Bundle, string) error { return errors.New("disk full") } + t.Cleanup(func() { writeUnsaved = old }) + for _, rotated := range []bool{false, true} { + t.Run(fmt.Sprint("rotated=", rotated), func(t *testing.T) { + p := newTokenProvider(t, rotating) + dir := t.TempDir() + storeToken(t, dir, p.URL, "file-access", "file-refresh", -time.Minute) + src := oidcSource(t, dir, p.URL, nil) + // An unwritten token that has expired, issued in place of the + // file's token. + rt := "file-refresh" + if rotated { + rt = "unwritten-refresh" + } + b := bundleFor(p.URL, "unwritten-access", rt, -time.Second) + src.mu.Lock() + src.unsaved = &unsavedToken{bundle: b, over: "file-access", rotated: rotated} + src.mu.Unlock() + + tok, err := src.Token() + if rotated { + require.ErrorIs(t, err, ErrTokenLoad) + assert.ErrorContains(t, err, "disk full") + assert.Empty(t, p.requests(), "the revoked refresh token was sent") + return + } + require.NoError(t, err) + assert.Equal(t, "refreshed-access", tok.AccessToken) + reqs := p.requests() + require.Len(t, reqs, 1) + assert.Equal(t, "file-refresh", reqs[0].Get("refresh_token")) + }) + } +} + +// hookLogger calls onError with the message of each error it is given. +type hookLogger struct{ onError func(msg string) } + +func (l *hookLogger) Debug(string, ...any) {} +func (l *hookLogger) Info(string, ...any) {} +func (l *hookLogger) Error(_ error, msg string, _ ...any) { l.onError(msg) } + +// TestDiskTokenSource_UsableTokenWaitsBriefly verifies that a token that +// is due but has not expired is returned within refreshWait, whatever the +// renewal does: the provider fails, hangs, or another renewal holds the +// lock. +func TestDiskTokenSource_UsableTokenWaitsBriefly(t *testing.T) { + setRefreshWait(t, 100*time.Millisecond) + + t.Run("provider fails", func(t *testing.T) { + p := newTokenProvider(t, unavailable) + dir := t.TempDir() + storeToken(t, dir, p.URL, "usable-access", "stored-refresh", 8*time.Second) + logger := &recordingLogger{} + src := oidcSource(t, dir, p.URL, logger) + + tok, err := tokenWithin(t, src, 2*time.Second) + require.NoError(t, err) + assert.Equal(t, "usable-access", tok.AccessToken) + src.background.Wait() + + // The failure is logged, and the next calls within + // refreshRetryDelay neither fail nor ask the provider again. + errs := logger.errors() + require.Len(t, errs, 1) + assert.ErrorIs(t, errs[0], ErrTokenLoad) + assert.Contains(t, errs[0].Error(), "HTTP 503") + assert.Equal(t, []string{"OIDC token renewal failed"}, logger.messages()) + assert.Equal(t, []any{"gateway", "prod"}, logger.lastKeysAndValues()) + for range 3 { + tok, err = src.Token() + require.NoError(t, err) + assert.Equal(t, "usable-access", tok.AccessToken) + } + src.background.Wait() + assert.Len(t, p.requests(), 1) + }) + t.Run("provider hangs", func(t *testing.T) { + release := make(chan struct{}) + p := newTokenProvider(t, func(form url.Values) (int, string) { + <-release + return rotating(form) + }) + answer := sync.OnceFunc(func() { close(release) }) + defer answer() + dir := t.TempDir() + storeToken(t, dir, p.URL, "usable-access", "stored-refresh", 8*time.Second) + src := oidcSource(t, dir, p.URL, nil) + + // Both calls return the current token; the second joins the + // renewal the first started. + for range 2 { + tok, err := tokenWithin(t, src, 2*time.Second) + require.NoError(t, err) + assert.Equal(t, "usable-access", tok.AccessToken) + } + answer() + src.background.Wait() + assert.Len(t, p.requests(), 1) + }) + t.Run("another renewal holds the lock", func(t *testing.T) { + p := newTokenProvider(t, rotating) + dir := t.TempDir() + storeToken(t, dir, p.URL, "usable-access", "stored-refresh", 8*time.Second) + unlock, err := oidcclient.LockDir(context.Background(), dir) + require.NoError(t, err) + src := oidcSource(t, dir, p.URL, nil) + defer unlock() + + tok, err := tokenWithin(t, src, 2*time.Second) + require.NoError(t, err) + assert.Equal(t, "usable-access", tok.AccessToken) + }) +} + +func TestDiskTokenSource_LockWaitTimeout(t *testing.T) { + hold := func(t *testing.T, dir string) { + t.Helper() + unlock, err := oidcclient.LockDir(context.Background(), dir) + require.NoError(t, err) + t.Cleanup(unlock) + } + // writeLater writes b while Token waits for the lock: well after Token + // has started waiting, well before refreshWaitTimeout ends. + writeLater := func(dir string, b oidctoken.Bundle) <-chan error { + written := make(chan error, 1) + go func() { + time.Sleep(100 * time.Millisecond) + written <- oidcclient.WriteToken(dir, b) + }() + return written + } + + t.Run("reports the timeout", func(t *testing.T) { + setRefreshWaitTimeout(t, 50*time.Millisecond) + p := newTokenProvider(t, rotating) + dir := t.TempDir() + storeToken(t, dir, p.URL, "expired-access", "stored-refresh", -time.Minute) + hold(t, dir) + + _, err := tokenWithin(t, oidcSource(t, dir, p.URL, nil), 5*time.Second) + require.ErrorIs(t, err, ErrTokenLoad) + require.ErrorIs(t, err, context.DeadlineExceeded) + assert.Contains(t, err.Error(), "waiting for another refresh of "+oidctoken.FileName) + assert.Empty(t, p.requests()) + }) + + t.Run("uses a token written meanwhile", func(t *testing.T) { + setRefreshWaitTimeout(t, time.Second) + p := newTokenProvider(t, rotating) + dir := t.TempDir() + storeToken(t, dir, p.URL, "expired-access", "stored-refresh", -time.Minute) + hold(t, dir) + // The CLI keeps the issuer as the user typed it. + written := writeLater(dir, bundleFor(p.URL+"/", "written-meanwhile", "peer-refresh", time.Hour)) + + tok, err := tokenWithin(t, oidcSource(t, dir, p.URL, nil), 5*time.Second) + require.NoError(t, <-written) + require.NoError(t, err) + assert.Equal(t, "written-meanwhile", tok.AccessToken) + assert.Empty(t, p.requests()) + }) + + t.Run("ignores a token written meanwhile for another client", func(t *testing.T) { + setRefreshWaitTimeout(t, time.Second) + p := newTokenProvider(t, rotating) + dir := t.TempDir() + storeToken(t, dir, p.URL, "expired-access", "stored-refresh", -time.Minute) + hold(t, dir) + b := bundleFor(p.URL, "other-access", "other-refresh", time.Hour) + b.ClientID = "other-client" + written := writeLater(dir, b) + + _, err := tokenWithin(t, oidcSource(t, dir, p.URL, nil), 5*time.Second) + require.NoError(t, <-written) + require.ErrorIs(t, err, ErrTokenLoad) + // The lock wait timed out and the fallback rejected the token; + // a write that came first would fail on the client check instead. + assert.Contains(t, err.Error(), "waiting for another refresh") + }) +} + +// TestDiskTokenSource_ValidTokenSkipsRefreshLock verifies that a token +// outside the refresh window is returned without waiting for a refresh of +// the same directory that is in progress. +func TestDiskTokenSource_ValidTokenSkipsRefreshLock(t *testing.T) { + p := newTokenProvider(t, rotating) + dir := t.TempDir() + storeToken(t, dir, p.URL, "valid-access", "stored-refresh", time.Hour) + unlock, err := oidcclient.LockDir(context.Background(), dir) + require.NoError(t, err) + t.Cleanup(unlock) + + tok, err := tokenWithin(t, oidcSource(t, dir, p.URL, nil), 2*time.Second) + require.NoError(t, err) + assert.Equal(t, "valid-access", tok.AccessToken) + assert.Empty(t, p.requests()) +} + +// TestDiskTokenSource_GrantOutlivesWaitTimeout verifies that a token +// request already sent is not cut off by refreshWaitTimeout: the response +// is used and the rotated refresh token is stored. +func TestDiskTokenSource_GrantOutlivesWaitTimeout(t *testing.T) { + setRefreshWaitTimeout(t, 100*time.Millisecond) + + p := newTokenProvider(t, func(form url.Values) (int, string) { + time.Sleep(3 * refreshWaitTimeout) + return rotating(form) + }) + // Discover now, so that refreshWaitTimeout covers only the lock wait. + _, err := oidcclient.Discover(context.Background(), p.URL) + require.NoError(t, err) + dir := t.TempDir() + storeToken(t, dir, p.URL, "expired-access", "stored-refresh", -time.Minute) + + tok, err := oidcSource(t, dir, p.URL, nil).Token() + require.NoError(t, err) + assert.Equal(t, "refreshed-access", tok.AccessToken) + assert.Equal(t, "rotated-refresh", readBundle(t, dir).RefreshToken) + assert.Len(t, p.requests(), 1) +} + +// TestDiskTokenSource_RefreshWithoutExpiresIn verifies that a refreshed +// token without expires_in is stored without an expiry and is then used +// as is, without another refresh. +func TestDiskTokenSource_RefreshWithoutExpiresIn(t *testing.T) { + p := newTokenProvider(t, func(url.Values) (int, string) { + return http.StatusOK, `{"access_token":"no-expiry-access","refresh_token":"rotated-refresh","token_type":"Bearer"}` + }) + dir := t.TempDir() + storeToken(t, dir, p.URL, "expired-access", "stored-refresh", -time.Minute) + src := oidcSource(t, dir, p.URL, nil) + + tok, err := src.Token() + require.NoError(t, err) + assert.Equal(t, "no-expiry-access", tok.AccessToken) + assert.True(t, tok.Expiry.IsZero()) + assert.Nil(t, readBundle(t, dir).ExpiresAt) + + tok, err = src.Token() + require.NoError(t, err) + assert.Equal(t, "no-expiry-access", tok.AccessToken) + assert.Len(t, p.requests(), 1) +} + +// TestDiskTokenSource_WaitIsPerRenewal verifies that while one renewal +// hangs, only the calls within refreshWait of its start wait for it; later +// calls return the current token at once. +func TestDiskTokenSource_WaitIsPerRenewal(t *testing.T) { + setRefreshWait(t, time.Second) + release := make(chan struct{}) + p := newTokenProvider(t, func(form url.Values) (int, string) { + <-release + return rotating(form) + }) + answer := sync.OnceFunc(func() { close(release) }) + defer answer() + dir := t.TempDir() + storeToken(t, dir, p.URL, "usable-access", "stored-refresh", 20*time.Second) + src := oidcSource(t, dir, p.URL, nil) + + start := time.Now() + tok, err := tokenWithin(t, src, 5*time.Second) + require.NoError(t, err) + assert.Equal(t, "usable-access", tok.AccessToken) + assert.GreaterOrEqual(t, time.Since(start), 900*time.Millisecond, "the first call waits for the renewal") + for range 3 { + tok, err := tokenWithin(t, src, 500*time.Millisecond) + require.NoError(t, err) + assert.Equal(t, "usable-access", tok.AccessToken) + } + answer() + src.background.Wait() + assert.Len(t, p.requests(), 1) +} + +// TestDiskTokenSource_TokenExpiringDuringWaitIsRenewed verifies that a +// token that expires while Token waits for its renewal is not returned: +// Token waits for the renewal instead. +func TestDiskTokenSource_TokenExpiringDuringWaitIsRenewed(t *testing.T) { + setRefreshWait(t, 10*time.Second) + p := newTokenProvider(t, func(form url.Values) (int, string) { + // Answer only after the stored token has expired. + time.Sleep(1600 * time.Millisecond) + return rotating(form) + }) + dir := t.TempDir() + // The file keeps whole seconds, so this expires 0.5 to 1.5 s from now. + storeToken(t, dir, p.URL, "expiring-access", "stored-refresh", 1500*time.Millisecond) + + tok, err := tokenWithin(t, oidcSource(t, dir, p.URL, nil), 5*time.Second) + require.NoError(t, err) + assert.Equal(t, "refreshed-access", tok.AccessToken) +} + +// TestDiskTokenSource_ExpiredTokenUsesPeerRenewal verifies that when the +// renewal of an expired token fails because another process renewed the +// file meanwhile, the token it wrote is used while it has not expired, +// even if it is already inside the window. +func TestDiskTokenSource_ExpiredTokenUsesPeerRenewal(t *testing.T) { + dir := t.TempDir() + var p *tokenProvider + p = newTokenProvider(t, func(form url.Values) (int, string) { + // A peer stores a 20 s token while this request is in flight. + storeTokenFromHandler(t, dir, p.URL, "peer-access", "peer-refresh", 20*time.Second) + return rotating(form) + }) + storeToken(t, dir, p.URL, "expired-access", "stored-refresh", -time.Minute) + + tok, err := oidcSource(t, dir, p.URL, nil).Token() + require.NoError(t, err) + assert.Equal(t, "peer-access", tok.AccessToken) + assert.Equal(t, "peer-refresh", readBundle(t, dir).RefreshToken, "the peer's token stands") +} + +// TestDiskTokenSource_RetryDelay verifies that after a failed renewal of a +// usable token no renewal starts within refreshRetryDelay, that an expired +// token is renewed regardless, and that a successful renewal ends the +// delay. +func TestDiskTokenSource_RetryDelay(t *testing.T) { + setRefreshRetryDelay(t, time.Hour) + var failing atomic.Bool + failing.Store(true) + p := newTokenProvider(t, func(form url.Values) (int, string) { + if failing.Load() { + return unavailable(form) + } + return rotating(form) + }) + dir := t.TempDir() + storeToken(t, dir, p.URL, "usable-access", "stored-refresh", 8*time.Second) + src := oidcSource(t, dir, p.URL, nil) + + for range 2 { + tok, err := src.Token() + require.NoError(t, err) + assert.Equal(t, "usable-access", tok.AccessToken) + src.background.Wait() + } + require.Len(t, p.requests(), 1, "a renewal started within the retry delay") + + failing.Store(false) + storeToken(t, dir, p.URL, "expired-access", "second-refresh", -time.Minute) + tok, err := src.Token() + require.NoError(t, err) + assert.Equal(t, "refreshed-access", tok.AccessToken, "an expired token waits out no delay") + require.Len(t, p.requests(), 2) + + storeToken(t, dir, p.URL, "usable-access-2", "third-refresh", 8*time.Second) + tok, err = src.Token() + require.NoError(t, err) + assert.Equal(t, "refreshed-access", tok.AccessToken, "the successful renewal ended the delay") + assert.Len(t, p.requests(), 3) +} + +// TestDiskTokenSource_ExpiredTokenUsesPeerTokenWithoutRotation verifies +// that the token another process wrote is used after a failed renewal even +// when the provider does not rotate refresh tokens, so the file keeps the +// same refresh token. +func TestDiskTokenSource_ExpiredTokenUsesPeerTokenWithoutRotation(t *testing.T) { + dir := t.TempDir() + var p *tokenProvider + p = newTokenProvider(t, func(url.Values) (int, string) { + // A peer renews with the same refresh token, then the provider + // fails this request. + storeTokenFromHandler(t, dir, p.URL, "peer-access", "stored-refresh", 20*time.Second) + return http.StatusServiceUnavailable, `{}` + }) + storeToken(t, dir, p.URL, "expired-access", "stored-refresh", -time.Minute) + + tok, err := oidcSource(t, dir, p.URL, nil).Token() + require.NoError(t, err) + assert.Equal(t, "peer-access", tok.AccessToken) +} + +// TestRefreshDefaults pins the values the documentation states. +func TestRefreshDefaults(t *testing.T) { + assert.Equal(t, 30*time.Second, refreshWindow, "renewal window") + assert.Equal(t, 2*time.Second, refreshWait, "wait for a renewal while the token is usable") + assert.Equal(t, 5*time.Second, refreshRetryDelay, "delay after a failed renewal of a usable token") + assert.Equal(t, 30*time.Second, refreshWaitTimeout, "bound on the lock wait and discovery") +} + +// TestDiskTokenSource_ExpiredRenewalFallback verifies what an expired +// token's failed renewal falls back to: an expired token another process +// wrote is not used, and a logout during the renewal leaves an error, not +// a token. +func TestDiskTokenSource_ExpiredRenewalFallback(t *testing.T) { + t.Run("expired peer token", func(t *testing.T) { + dir := t.TempDir() + var p *tokenProvider + p = newTokenProvider(t, func(url.Values) (int, string) { + storeTokenFromHandler(t, dir, p.URL, "peer-expired-access", "peer-refresh", -time.Second) + return http.StatusServiceUnavailable, `{}` + }) + storeToken(t, dir, p.URL, "expired-access", "stored-refresh", -time.Minute) + + tok, err := oidcSource(t, dir, p.URL, nil).Token() + require.ErrorIs(t, err, ErrTokenLoad, "got token %v", tok) + assert.Contains(t, err.Error(), loginHint) + }) + t.Run("logout during the renewal", func(t *testing.T) { + dir := t.TempDir() + p := newTokenProvider(t, func(form url.Values) (int, string) { + if err := os.Remove(filepath.Join(dir, oidctoken.FileName)); err != nil { + t.Errorf("remove: %v", err) + } + return rotating(form) + }) + storeToken(t, dir, p.URL, "expired-access", "stored-refresh", -time.Minute) + + tok, err := oidcSource(t, dir, p.URL, nil).Token() + require.ErrorIs(t, err, ErrTokenLoad, "got token %v", tok) + assert.Contains(t, err.Error(), "changed during the refresh") + _, statErr := os.Stat(filepath.Join(dir, oidctoken.FileName)) + assert.True(t, os.IsNotExist(statErr), "the logout was undone") + }) +} diff --git a/openshell/v1/gateway/token.go b/openshell/v1/gateway/token.go index a37a0cb..aacbaf3 100644 --- a/openshell/v1/gateway/token.go +++ b/openshell/v1/gateway/token.go @@ -10,11 +10,14 @@ import ( "os" "path/filepath" "strings" + "sync" "time" "golang.org/x/oauth2" + "github.com/ai-openshell/sdk-go/openshell/v1/internal/oidcclient" "github.com/ai-openshell/sdk-go/openshell/v1/internal/oidctoken" + "github.com/ai-openshell/sdk-go/openshell/v1/types" ) const ( @@ -59,24 +62,336 @@ func readEdgeToken(dir string) (string, error) { return token, nil } +// refreshWindow is the gateway's default renewal window before expiry, +// matching the CLI and Python SDK. +const refreshWindow = 30 * time.Second + +// refreshRetryDelay is how long the source waits after a failed renewal +// of a token that has not expired before it starts another. Sources copy +// it when they are made; tests change it first. +var refreshRetryDelay = 5 * time.Second + +// refreshWait is how long RPCs that hold a token that has not expired wait +// for a renewal, counted from its start, before they use that token and +// let the renewal finish in the background. When the provider answers +// within it, and RefreshableToken has not stopped waiting at half the +// RPC's deadline, the RPC returns only after the new token is written, so +// a program that exits right after the RPC does not cut the token request +// off. Sources copy it when they are made; tests shorten it first. +var refreshWait = 2 * time.Second + +// refreshWaitTimeout bounds how long a refresh waits for the refresh lock +// and for discovery. The token requests themselves run to the end, bounded +// by the HTTP client's timeout. Sources copy it when they are made; tests +// shorten it first. +var refreshWaitTimeout = 30 * time.Second + +// writeUnsaved writes a renewed token that an earlier write could not +// store. Tests replace it to make the write fail. +var writeUnsaved = oidcclient.SavePendingToken + // diskTokenSource implements oauth2.TokenSource by reading oidc_token.json // from disk on every Token() call. This allows the source to pick up -// tokens refreshed by the Rust CLI without process restart. +// tokens refreshed by the CLI or another SDK without a process restart. +// When metadata.json names the issuer and client ID, it refreshes tokens +// that are due and rewrites the file in the CLI's format. type diskTokenSource struct { dir string name string + + // issuer and clientID come from metadata.json. A token is refreshed + // only when both are set and the file was issued for them, as Login + // requires. + issuer string + clientID string + + // scopes are sent with the refresh request; nil sends none. + scopes []string + + // logger, when set, receives every failed renewal, and renewed tokens + // that could not be written. + logger types.Logger + + // wait, waitTimeout and retryDelay are refreshWait, + // refreshWaitTimeout and refreshRetryDelay. + wait, waitTimeout, retryDelay time.Duration + + mu sync.Mutex + // lifetime is how long the last token this source got from a token + // request was valid for, or zero before the first one. + lifetime time.Duration + // renewal is the renewal in progress, if any, and retryAt the + // earliest time to start one after a renewal failed while the token + // was still usable. + renewal *renewal + retryAt time.Time + // unsaved is a renewed token that could not be written; see Token. + unsaved *unsavedToken + // background counts running renewals, for tests. + background sync.WaitGroup } -// newDiskTokenSource returns an oauth2.TokenSource that reads -// oidc_token.json from the directory of the named gateway on each -// Token() call. -func newDiskTokenSource(dir, name string) oauth2.TokenSource { - return &diskTokenSource{dir: dir, name: name} +// unsavedToken is a renewed token that could not be written, as the file +// would hold it, and the access token the file held instead. rotated +// reports that its refresh token differs from the file's, which a +// provider that rotates refresh tokens has then revoked. +type unsavedToken struct { + bundle oidctoken.Bundle + over string + rotated bool } -// Token reads and parses oidc_token.json, returning an oauth2.Token. -// The file is read on every call to pick up CLI-refreshed tokens. +// renewal is one run of refresh that callers of Token share. +type renewal struct { + done chan struct{} + // waitUntil is when callers that hold a token that has not expired + // stop waiting for this renewal. + waitUntil time.Time + tok *oauth2.Token + err error +} + +// newDiskTokenSource returns a diskTokenSource for the gateway directory +// dir. Without metadata it reads the file and never refreshes. +func newDiskTokenSource(dir, name string) *diskTokenSource { + return &diskTokenSource{dir: dir, name: name, wait: refreshWait, waitTimeout: refreshWaitTimeout, retryDelay: refreshRetryDelay} +} + +// newOIDCTokenSource returns a diskTokenSource for the OIDC gateway cfg, +// which refreshes with the issuer, client ID and scopes in its +// metadata.json and reports failures that do not fail an RPC to logger. +func newOIDCTokenSource(cfg *Config, logger types.Logger) *diskTokenSource { + src := newDiskTokenSource(cfg.Dir, cfg.Name) + src.issuer = cfg.OIDCIssuer + src.clientID = cfg.OIDCClientID + if scopes := strings.Fields(cfg.OIDCScopes); len(scopes) > 0 { + src.scopes = oidcclient.ScopesWithOpenID(scopes) + } + src.logger = logger + return src +} + +// Token reads and parses oidc_token.json, returning an oauth2.Token. The +// file is read on every call to pick up tokens refreshed elsewhere. +// +// A token that expires within the refresh window is renewed when the file +// has a refresh token and was issued for the issuer and client ID in +// metadata.json. Concurrent calls share one renewal. While the token has +// not expired, Token waits for the renewal until refreshWait after it +// started, then returns the current token and leaves the renewal to finish +// in the background; after a failed renewal, the next one starts no sooner +// than refreshRetryDelay later. An expired token, including one that +// expires during that wait, is renewed before Token returns. If that fails +// and no usable token has appeared in the file meanwhile, Token returns +// ErrTokenLoad with the reason, such as the provider's error code or HTTP +// status. +// +// A renewed token that cannot be written stays in memory: a provider that +// rotates refresh tokens has already revoked the one in the file. While +// the file still holds the token it replaced, Token uses it in place of +// the file's, and the next renewal writes it before anything else. While +// that write fails, a renewal sends no token request if the refresh token +// was rotated, since the provider may end the session when it sees the +// revoked one; the client then works until the token expires. A change to +// the file, such as a login or a token written by another process, +// discards it; a removed file fails as before. +// +// A renewal is not tied to the client: closing the client does not stop +// it, and a renewal still running when the process exits is cut off. func (d *diskTokenSource) Token() (*oauth2.Token, error) { + bundle, err := d.read() + if err != nil { + return nil, err + } + bundle = d.withUnsaved(bundle) + + tok := bundle.Token() + window := time.Duration(d.RefreshWindow()) + if bundle.RefreshToken == "" || oidcclient.Fresh(tok, window) || d.issuer == "" || d.clientID == "" { + return d.unexpired(tok) + } + if !oidcclient.SameClient(bundle, d.issuer, d.clientID) { + if _, err := d.unexpired(tok); err != nil { + return nil, d.loadError("OIDC token for gateway %q was issued by another issuer or client than metadata.json names", d.name) + } + return tok, nil + } + + if _, err := d.unexpired(tok); err != nil { + r := d.renew(window, bundle.AccessToken, true) + <-r.done + return r.tok, r.err + } + + // The token is still usable, so an RPC waits only briefly for the + // provider. + r := d.renew(window, bundle.AccessToken, false) + if r == nil { + return tok, nil + } + // The wait ends at r.waitUntil, or when the token expires if that is + // sooner; a wait cut short by expiry goes on until the renewal ends. + // That case is decided by which bound was used, not by reading the + // clock again, which a timer may beat by a little. + end, expires := r.waitUntil, false + if !tok.Expiry.After(end) { + end, expires = tok.Expiry, true + } + timer := time.NewTimer(time.Until(end)) + defer timer.Stop() + select { + case <-r.done: + if r.err == nil { + return r.tok, nil + } + if time.Now().Before(tok.Expiry) { + return tok, nil + } + return r.tok, r.err + case <-timer.C: + if !expires && time.Now().Before(tok.Expiry) { + return tok, nil + } + } + <-r.done + return r.tok, r.err +} + +// renew returns the renewal in progress or starts one. seen is the access +// token the caller read from the file. Unless force is set, it starts none +// within refreshRetryDelay of a failed renewal and returns nil. +func (d *diskTokenSource) renew(window time.Duration, seen string, force bool) *renewal { + d.mu.Lock() + defer d.mu.Unlock() + if d.renewal != nil { + return d.renewal + } + if !force && time.Now().Before(d.retryAt) { + return nil + } + r := &renewal{done: make(chan struct{}), waitUntil: time.Now().Add(d.wait)} + d.renewal = r + d.background.Add(1) + go func() { + defer d.background.Done() + r.tok, r.err = d.refresh(window, seen) + d.mu.Lock() + d.renewal = nil + d.retryAt = time.Time{} + if r.err != nil { + d.retryAt = time.Now().Add(d.retryDelay) + } + d.mu.Unlock() + close(r.done) + if r.err != nil { + d.logError(r.err, "OIDC token renewal failed") + } + }() + return r +} + +// refresh renews the stored token; seen is the access token read before +// the renewal started. A renewed token that could not be written is +// returned all the same and kept as d.unsaved. +func (d *diskTokenSource) refresh(window time.Duration, seen string) (*oauth2.Token, error) { + ctx, cancel := context.WithTimeout(context.Background(), d.waitTimeout) + defer cancel() + if rotated, err := d.saveUnsaved(ctx); err != nil && rotated { + // The file's refresh token is revoked; sending it could make the + // provider end the session. + return nil, fmt.Errorf("%w: cannot store the renewed OIDC token for gateway %q: %w", ErrTokenLoad, d.name, err) + } + res, err := oidcclient.Refresh(ctx, oidcclient.Request{ + Dir: d.dir, + Issuer: d.issuer, + ClientID: d.clientID, + Scopes: d.scopes, + Window: window, + FinishGrant: true, + }) + if res.Granted { + d.observe(res.Token) + } + switch { + case err == nil: + return res.Token, nil + case res.Granted: + // The provider may have revoked the refresh token in the file, so + // this token may be the only one that works. + d.keepUnsaved(res) + d.logError(err, "cannot store the renewed OIDC token") + return res.Token, nil + } + + // Another process may have refreshed the file meanwhile, for example + // while this call waited for the lock. Its token is used if it is not + // the one this renewal started from and has not expired, even inside + // the window: with tokens shorter than the window, a just-renewed token + // is already inside it. + if current, readErr := d.read(); readErr == nil && oidcclient.SameClient(current, d.issuer, d.clientID) { + t := current.Token() + if _, expiredErr := d.unexpired(t); current.AccessToken != seen && expiredErr == nil { + return t, nil + } + } + return nil, fmt.Errorf("%w: cannot refresh the OIDC token for gateway %q: %w; run `openshell gateway login %s`", + ErrTokenLoad, d.name, err, d.name) +} + +// keepUnsaved keeps the token that res says could not be written. +func (d *diskTokenSource) keepUnsaved(res oidcclient.Result) { + if res.Unwritten == nil || res.Replaced == nil { + return + } + d.mu.Lock() + d.unsaved = &unsavedToken{ + bundle: *res.Unwritten, + over: res.Replaced.AccessToken, + rotated: res.Unwritten.RefreshToken != res.Replaced.RefreshToken, + } + d.mu.Unlock() +} + +// withUnsaved returns the unsaved token in place of bundle while the file +// still holds the token it replaced, and otherwise drops it. +func (d *diskTokenSource) withUnsaved(bundle *oidctoken.Bundle) *oidctoken.Bundle { + d.mu.Lock() + defer d.mu.Unlock() + if d.unsaved == nil { + return bundle + } + if bundle.AccessToken != d.unsaved.over { + d.unsaved = nil + return bundle + } + b := d.unsaved.bundle + return &b +} + +// saveUnsaved writes the unsaved token, if any, under the refresh lock, +// unless the file no longer holds the token it replaced. On failure it +// also reports whether that token's refresh token was rotated. +func (d *diskTokenSource) saveUnsaved(ctx context.Context) (rotated bool, err error) { + d.mu.Lock() + u := d.unsaved + d.mu.Unlock() + if u == nil { + return false, nil + } + if err := writeUnsaved(ctx, d.dir, u.bundle, u.over); err != nil { + return u.rotated, err + } + d.mu.Lock() + if d.unsaved == u { + d.unsaved = nil + } + d.mu.Unlock() + return false, nil +} + +// read reads oidc_token.json and checks that it has an access token, an +// issuer and a client ID. +func (d *diskTokenSource) read() (*oidctoken.Bundle, error) { data, err := os.ReadFile(filepath.Join(d.dir, oidctoken.FileName)) if err != nil { return nil, d.loadError("cannot read %s: %v", oidctoken.FileName, err) @@ -95,16 +410,46 @@ func (d *diskTokenSource) Token() (*oauth2.Token, error) { if bundle.Issuer == "" || bundle.ClientID == "" { return nil, d.loadError("OIDC token for gateway %q is missing issuer or client_id", d.name) } + return &bundle, nil +} - tok := bundle.Token() +// unexpired returns tok, or ErrTokenLoad if it has expired. +func (d *diskTokenSource) unexpired(tok *oauth2.Token) (*oauth2.Token, error) { if !tok.Expiry.IsZero() && !time.Now().Before(tok.Expiry) { return nil, d.loadError("OIDC token for gateway %q expired at %s", d.name, tok.Expiry.UTC().Format(time.RFC3339)) } - return tok, nil } +// RefreshWindow is shared by the SDK cache and Token. It uses half the +// last observed token lifetime when that is shorter than refreshWindow. +func (d *diskTokenSource) RefreshWindow() oidctoken.RefreshWindow { + d.mu.Lock() + defer d.mu.Unlock() + if half := d.lifetime / 2; half > 0 && half < refreshWindow { + return oidctoken.RefreshWindow(half) + } + return oidctoken.RefreshWindow(refreshWindow) +} + +// observe records how long a token from a token request is valid for. +func (d *diskTokenSource) observe(tok *oauth2.Token) { + if tok.Expiry.IsZero() { + return + } + d.mu.Lock() + defer d.mu.Unlock() + d.lifetime = time.Until(tok.Expiry) +} + +// logError reports err to the logger, if there is one. +func (d *diskTokenSource) logError(err error, msg string) { + if d.logger != nil { + d.logger.Error(err, msg, "gateway", d.name) + } +} + // loadError wraps ErrTokenLoad with the CLI login command that repairs // the token file. func (d *diskTokenSource) loadError(format string, args ...any) error { diff --git a/openshell/v1/oidc/discovery.go b/openshell/v1/internal/oidcclient/discovery.go similarity index 79% rename from openshell/v1/oidc/discovery.go rename to openshell/v1/internal/oidcclient/discovery.go index 1c1dcef..ba8073b 100644 --- a/openshell/v1/oidc/discovery.go +++ b/openshell/v1/internal/oidcclient/discovery.go @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -package oidc +package oidcclient import ( "context" @@ -16,16 +16,19 @@ import ( "time" ) -var oidcHTTPClient = &http.Client{ +// HTTPClient is the HTTP client for discovery and token requests. It does +// not follow redirects, so a 3xx response cannot steer a request, or the +// refresh token it carries, to another host. +var HTTPClient = &http.Client{ Timeout: 30 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, } -// providerConfig holds parsed fields from an OIDC discovery document +// ProviderConfig holds parsed fields from an OIDC discovery document // (.well-known/openid-configuration). -type providerConfig struct { +type ProviderConfig struct { Issuer string `json:"issuer"` AuthorizationEndpoint string `json:"authorization_endpoint"` TokenEndpoint string `json:"token_endpoint"` @@ -37,7 +40,7 @@ type providerConfig struct { const discoveryCacheTTL = 10 * time.Minute type discoveryCacheEntry struct { - config *providerConfig + config *ProviderConfig fetchedAt time.Time } @@ -51,26 +54,26 @@ var ( discoveryCache = make(map[string]*discoveryCacheEntry) ) -// resetDiscoveryCache clears the in-memory discovery cache. This is +// ResetDiscoveryCache clears the in-memory discovery cache. This is // only used by tests to avoid interference between test cases. -func resetDiscoveryCache() { +func ResetDiscoveryCache() { discoveryCacheMu.Lock() defer discoveryCacheMu.Unlock() discoveryCache = make(map[string]*discoveryCacheEntry) } -// normalizeIssuer strips a trailing slash from the issuer URL so that +// NormalizeIssuer strips a trailing slash from the issuer URL so that // "https://auth.example.com" and "https://auth.example.com/" resolve // to the same cache key. -func normalizeIssuer(issuer string) string { +func NormalizeIssuer(issuer string) string { return strings.TrimRight(issuer, "/") } -// discover fetches and caches the OIDC discovery document for the +// Discover fetches and caches the OIDC discovery document for the // given issuer URL. Only successful results are cached; failed // fetches are retried on the next call. -func discover(ctx context.Context, issuer string) (*providerConfig, error) { - key := normalizeIssuer(issuer) +func Discover(ctx context.Context, issuer string) (*ProviderConfig, error) { + key := NormalizeIssuer(issuer) now := time.Now() discoveryCacheMu.Lock() @@ -98,8 +101,8 @@ func discover(ctx context.Context, issuer string) (*providerConfig, error) { // fetchDiscovery performs the actual HTTP GET to the OIDC discovery // endpoint and parses the response. -func fetchDiscovery(ctx context.Context, issuer string) (*providerConfig, error) { - if err := validateSecureURL("issuer", issuer); err != nil { +func fetchDiscovery(ctx context.Context, issuer string) (*ProviderConfig, error) { + if err := ValidateSecureURL("issuer", issuer); err != nil { return nil, err } url := issuer + "/.well-known/openid-configuration" @@ -109,7 +112,7 @@ func fetchDiscovery(ctx context.Context, issuer string) (*providerConfig, error) return nil, fmt.Errorf("%w: %v", ErrDiscovery, err) } - resp, err := oidcHTTPClient.Do(req) + resp, err := HTTPClient.Do(req) if err != nil { return nil, fmt.Errorf("%w: %v", ErrDiscovery, err) } @@ -128,11 +131,11 @@ func fetchDiscovery(ctx context.Context, issuer string) (*providerConfig, error) return nil, fmt.Errorf("%w: discovery response is too large", ErrDiscovery) } - var cfg providerConfig + var cfg ProviderConfig if err := json.Unmarshal(body, &cfg); err != nil { return nil, fmt.Errorf("%w: invalid discovery JSON: %v", ErrDiscovery, err) } - if normalizeIssuer(cfg.Issuer) != normalizeIssuer(issuer) { + if NormalizeIssuer(cfg.Issuer) != NormalizeIssuer(issuer) { return nil, fmt.Errorf("%w: discovery issuer does not match configured issuer", ErrDiscovery) } @@ -149,7 +152,7 @@ func fetchDiscovery(ctx context.Context, issuer string) (*providerConfig, error) "device_authorization_endpoint": cfg.DeviceAuthorizationEndpoint, } { if endpoint != "" { - if err := validateSecureURL(name, endpoint); err != nil { + if err := ValidateSecureURL(name, endpoint); err != nil { return nil, err } } @@ -158,7 +161,9 @@ func fetchDiscovery(ctx context.Context, issuer string) (*providerConfig, error) return &cfg, nil } -func validateSecureURL(name, raw string) error { +// ValidateSecureURL checks that raw is an absolute URL without userinfo or a +// fragment, and that it uses HTTPS, or HTTP for a loopback host. +func ValidateSecureURL(name, raw string) error { u, err := url.Parse(raw) if err != nil || u.Host == "" { return fmt.Errorf("%w: invalid %s URL", ErrDiscovery, name) diff --git a/openshell/v1/internal/oidcclient/discovery_test.go b/openshell/v1/internal/oidcclient/discovery_test.go new file mode 100644 index 0000000..db3a1c7 --- /dev/null +++ b/openshell/v1/internal/oidcclient/discovery_test.go @@ -0,0 +1,85 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package oidcclient + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// TestDiscover_Errors covers the discovery failures that the oidc package +// tests do not reach. Each is reported as ErrDiscovery, which is what +// Login stops on and what the gateway reports. +func TestDiscover_Errors(t *testing.T) { + serve := func(t *testing.T, handler func(srv *httptest.Server, w http.ResponseWriter)) string { + t.Helper() + var srv *httptest.Server + srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { handler(srv, w) })) + t.Cleanup(srv.Close) + return srv.URL + } + doc := func(srv *httptest.Server, authorize, token string) string { + return fmt.Sprintf(`{"issuer":%q,"authorization_endpoint":%q,"token_endpoint":%q}`, srv.URL, authorize, token) + } + + for name, tc := range map[string]struct { + issuer func(t *testing.T) string + want string + }{ + "plain HTTP to a remote issuer": { + issuer: func(*testing.T) string { return "http://idp.example.com" }, + want: "issuer URL must use HTTPS", + }, + "issuer without a host": { + issuer: func(*testing.T) string { return "https://" }, + want: "invalid issuer URL", + }, + "provider not listening": { + issuer: func(*testing.T) string { + srv := httptest.NewServer(http.NotFoundHandler()) + srv.Close() + return srv.URL + }, + want: "dial tcp", + }, + "truncated response": { + issuer: func(t *testing.T) string { + return serve(t, func(_ *httptest.Server, w http.ResponseWriter) { + w.Header().Set("Content-Length", "100") + _, _ = w.Write([]byte(`{"issuer":`)) + }) + }, + want: "failed to read discovery response", + }, + "missing authorization_endpoint": { + issuer: func(t *testing.T) string { + return serve(t, func(srv *httptest.Server, w http.ResponseWriter) { + _, _ = w.Write([]byte(doc(srv, "", srv.URL+"/token"))) + }) + }, + want: "missing authorization_endpoint", + }, + "token endpoint that is not a URL": { + issuer: func(t *testing.T) string { + return serve(t, func(srv *httptest.Server, w http.ResponseWriter) { + _, _ = w.Write([]byte(doc(srv, srv.URL+"/authorize", "/token"))) + }) + }, + want: "invalid token_endpoint URL", + }, + } { + t.Run(name, func(t *testing.T) { + ResetDiscoveryCache() + _, err := Discover(context.Background(), tc.issuer(t)) + require.ErrorIs(t, err, ErrDiscovery) + assert.Contains(t, err.Error(), tc.want) + }) + } +} diff --git a/openshell/v1/internal/oidcclient/errors.go b/openshell/v1/internal/oidcclient/errors.go new file mode 100644 index 0000000..d95bf13 --- /dev/null +++ b/openshell/v1/internal/oidcclient/errors.go @@ -0,0 +1,34 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +// Package oidcclient holds the OIDC code that both the oidc and gateway +// packages need: discovery, the refresh_token grant, and reading and +// writing oidc_token.json. The oidc package imports gateway, so this code +// cannot live in oidc if gateway is to use it. +package oidcclient + +import "errors" + +var ( + // ErrDiscovery is returned when the OIDC discovery document cannot be + // fetched or parsed. The oidc package exports it as oidc.ErrDiscovery. + ErrDiscovery = errors.New("oidc: discovery failed") + + // ErrTokenPersist is returned when oidc_token.json cannot be read or + // written. The oidc package exports it as oidc.ErrTokenPersist. + ErrTokenPersist = errors.New("oidc: token persistence failed") + + // ErrRefresh is returned when a refresh_token grant fails. + ErrRefresh = errors.New("oidc: token refresh failed") + + // ErrInvalidGrant marks a refresh rejected with invalid_grant. The + // refresh token has expired or been revoked, or another process has + // already used it. + ErrInvalidGrant = errors.New("oidc: invalid_grant") + + // ErrNotRefreshable is returned when the stored token cannot be + // refreshed: the file is missing or unreadable, was issued for another + // issuer or client, has no refresh token, or holds a refresh token the + // provider rejected with no newer one to retry with. + ErrNotRefreshable = errors.New("oidc: stored token cannot be refreshed") +) diff --git a/openshell/v1/internal/oidcclient/lock_test.go b/openshell/v1/internal/oidcclient/lock_test.go new file mode 100644 index 0000000..64e3f59 --- /dev/null +++ b/openshell/v1/internal/oidcclient/lock_test.go @@ -0,0 +1,147 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package oidcclient + +import ( + "context" + "os" + "path/filepath" + "runtime" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +// TestLockDir verifies that a done context never takes the lock, even when +// it is free, and that one directory is one lock however its path is +// written. +func TestLockDir(t *testing.T) { + t.Run("done context", func(t *testing.T) { + dir := t.TempDir() + ctx, cancel := context.WithCancel(context.Background()) + cancel() + // With the lock free, a bare select would pick either case. + for range 64 { + unlock, err := LockDir(ctx, dir) + require.ErrorIs(t, err, context.Canceled) + require.Nil(t, unlock) + } + unlock, err := LockDir(context.Background(), dir) + require.NoError(t, err, "a failed attempt left the lock taken") + unlock() + }) + t.Run("relative and absolute path", func(t *testing.T) { + parent := t.TempDir() + require.NoError(t, os.Mkdir(filepath.Join(parent, "gw"), 0o700)) + t.Chdir(parent) + unlock, err := LockDir(context.Background(), "gw") + require.NoError(t, err) + defer unlock() + + for _, path := range []string{filepath.Join(parent, "gw"), filepath.Join("gw", "..", "gw")} { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) + _, err := LockDir(ctx, path) + cancel() + require.ErrorIs(t, err, context.DeadlineExceeded, "%s did not wait for the lock on gw", path) + } + }) + // Spellings a file system may treat as one directory: macOS and + // Windows ignore case, and APFS also ignores Unicode normalization and + // folds the Greek final sigma. Each pair runs only where the two names + // are one directory. + for name, pair := range map[string][2]string{ + "case": {"gw", "GW"}, + "NFC and NFD": {"caf\u00e9", "cafe\u0301"}, + "NFD and NFC": {"cafe\u0301", "caf\u00e9"}, + "final sigma": {"\u03c2", "\u03c3"}, + "capital sigma": {"\u03c2", "\u03a3"}, + "sharp s and capital": {"\u00df", "\u1e9e"}, + } { + t.Run(name, func(t *testing.T) { + parent := t.TempDir() + created := filepath.Join(parent, pair[0]) + require.NoError(t, os.Mkdir(created, 0o700)) + other := filepath.Join(parent, pair[1]) + if !sameDir(created, other) { + t.Skipf("%q and %q are different directories here", pair[0], pair[1]) + } + requireSharedLock(t, created, other) + }) + } + t.Run("firmlink", func(t *testing.T) { + if runtime.GOOS != "darwin" { + t.Skip("macOS firmlinks") + } + dir, err := filepath.EvalSymlinks(t.TempDir()) + require.NoError(t, err) + alias := filepath.Join("/System/Volumes/Data", dir) + if !sameDir(dir, alias) { + t.Skip("no firmlink alias here") + } + requireSharedLock(t, dir, alias) + }) + t.Run("different directories", func(t *testing.T) { + parent := t.TempDir() + a, b := filepath.Join(parent, "a"), filepath.Join(parent, "b") + require.NoError(t, os.Mkdir(a, 0o700)) + require.NoError(t, os.Mkdir(b, 0o700)) + unlock, err := LockDir(context.Background(), a) + require.NoError(t, err) + defer unlock() + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + unlockB, err := LockDir(ctx, b) + require.NoError(t, err, "b waited for the lock on a") + unlockB() + }) + t.Run("missing directory", func(t *testing.T) { + parent := t.TempDir() + missing := filepath.Join(parent, "missing") + requireSharedLock(t, missing, filepath.Join(missing, "..", "missing")) + t.Chdir(parent) + requireSharedLock(t, "missing", missing) + }) + t.Run("symlink", func(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("creating symlinks needs privileges on Windows") + } + parent := t.TempDir() + target := filepath.Join(parent, "real") + require.NoError(t, os.Mkdir(target, 0o700)) + link := filepath.Join(parent, "link") + require.NoError(t, os.Symlink(target, link)) + unlock, err := LockDir(context.Background(), target) + require.NoError(t, err) + defer unlock() + + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) + defer cancel() + _, err = LockDir(ctx, link) + require.ErrorIs(t, err, context.DeadlineExceeded, "the symlink did not wait for the lock on its target") + }) +} + +// sameDir reports whether a and b name one existing directory. +func sameDir(a, b string) bool { + ia, errA := os.Stat(a) + ib, errB := os.Stat(b) + return errA == nil && errB == nil && os.SameFile(ia, ib) +} + +// requireSharedLock fails the test unless other waits for the lock taken +// on held. +func requireSharedLock(t *testing.T, held, other string) { + t.Helper() + unlock, err := LockDir(context.Background(), held) + require.NoError(t, err) + defer unlock() + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) + defer cancel() + unlockOther, err := LockDir(ctx, other) + if err == nil { + unlockOther() + } + require.ErrorIs(t, err, context.DeadlineExceeded, "%q did not wait for the lock on %q", other, held) +} diff --git a/openshell/v1/internal/oidcclient/refresh.go b/openshell/v1/internal/oidcclient/refresh.go new file mode 100644 index 0000000..f379772 --- /dev/null +++ b/openshell/v1/internal/oidcclient/refresh.go @@ -0,0 +1,456 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package oidcclient + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "math" + "net/http" + "net/url" + "os" + "path/filepath" + "strings" + "sync" + "time" + + "golang.org/x/oauth2" + + "github.com/ai-openshell/sdk-go/openshell/v1/internal/oidctoken" +) + +// LoginRefreshWindow is how long before expiry Login treats a stored token as +// due for refresh: the expiry margin of oauth2.Token.Valid. +const LoginRefreshWindow = 10 * time.Second + +// now is the clock used to decide whether a token is fresh. Tests replace +// it. +var now = time.Now + +// refreshLocks serializes refreshes of one token file within the process, +// so concurrent callers do not spend the same refresh token twice. It +// holds a one-slot semaphore for each token directory ever refreshed, +// which is a handful of gateways in practice. +var refreshLocks struct { + mu sync.Mutex + // dirs identifies directories by os.SameFile, so every spelling of a + // directory shares one lock: a relative path, a symlink, another case + // or Unicode normalization on a file system that ignores them, a + // macOS firmlink. + dirs []dirLock + // paths holds the locks of directories that could not be stat'ed, by + // absolute path. + paths map[string]chan struct{} +} + +type dirLock struct { + info os.FileInfo + sem chan struct{} +} + +// dirSemaphore returns the refresh semaphore of dir. +func dirSemaphore(dir string) chan struct{} { + // Stat outside the mutex: a slow file system then holds up only this + // caller. SameFile(info, info) loads the file ID now on Windows, where + // os.Stat leaves it for the first comparison, so a stored entry still + // identifies its directory after the directory is gone. + info, err := os.Stat(dir) + if err == nil && !os.SameFile(info, info) { + err = errors.New("no file identity") + } + refreshLocks.mu.Lock() + defer refreshLocks.mu.Unlock() + if err != nil { + key := filepath.Clean(dir) + if abs, err := filepath.Abs(key); err == nil { + key = abs + } + if refreshLocks.paths == nil { + refreshLocks.paths = make(map[string]chan struct{}) + } + sem, ok := refreshLocks.paths[key] + if !ok { + sem = make(chan struct{}, 1) + refreshLocks.paths[key] = sem + } + return sem + } + for _, l := range refreshLocks.dirs { + if os.SameFile(l.info, info) { + return l.sem + } + } + sem := make(chan struct{}, 1) + refreshLocks.dirs = append(refreshLocks.dirs, dirLock{info: info, sem: sem}) + return sem +} + +// LockDir waits for the refresh lock of dir until ctx ends, and returns +// the function that releases it. When ctx ends first, it returns ctx's +// error. All spellings of one directory share its lock. +func LockDir(ctx context.Context, dir string) (func(), error) { + sem := dirSemaphore(dir) + if err := ctx.Err(); err != nil { + return nil, err + } + select { + case sem <- struct{}{}: + return func() { <-sem }, nil + case <-ctx.Done(): + return nil, ctx.Err() + } +} + +// Fresh reports whether tok has an access token that does not expire +// within window. A token without an expiry is fresh. With a 10 second +// window it is the same test as oauth2.Token.Valid. +func Fresh(tok *oauth2.Token, window time.Duration) bool { + if tok == nil || tok.AccessToken == "" { + return false + } + return tok.Expiry.IsZero() || !tok.Expiry.Round(0).Add(-window).Before(now()) +} + +// Request describes a refresh of the token stored in a directory. +type Request struct { + // Dir is the directory that holds oidc_token.json. + Dir string + + // Issuer and ClientID identify the provider and client the stored + // token must belong to. A file written for another issuer or client is + // not refreshed. + Issuer string + ClientID string + + // Scopes are sent as scope when not empty. + Scopes []string + + // Window is how close to expiry the stored token may be and still be + // returned without a refresh. + Window time.Duration + + // FinishGrant lets the token requests, and the write of the result, + // run to the end when ctx ends after discovery; the retry after + // invalid_grant is then still sent. A provider that rotates refresh + // tokens revokes the stored one once it accepts a request, so a request + // cut off before the response arrives loses the new tokens. + // HTTPClient's timeout still bounds each request. + FinishGrant bool +} + +// Result is the token Refresh returns. +type Result struct { + // Token is the token to use. + Token *oauth2.Token + + // Granted reports that Token comes from a token request this call + // made, not from the file. + Granted bool + + // When the write after a granted token request fails, Unwritten is the + // token file Refresh tried to write and Replaced the one it was to + // replace, which the file still holds. + Unwritten, Replaced *oidctoken.Bundle +} + +// Refresh renews the token stored in req.Dir with its refresh token and +// rewrites the file. +// +// The file is shared with the CLI, and providers that rotate refresh +// tokens revoke the old one on use. Under a per-directory lock the file is +// read again first, so a token another process or goroutine has just +// refreshed is returned as is. When the refresh is rejected with +// invalid_grant, the file is read once more: a fresh token another process +// wrote for the same issuer and client is returned as is, and one that is +// due, with a different refresh token, is refreshed once with that token. +// Like the Python SDK, it takes no file lock across processes. If the +// response has no refresh token, the stored one is kept. +// +// Before the token request, Refresh checks that it can create a file in +// req.Dir, so a directory without write permission does not cost the +// refresh token. The write can still fail after the token request, for +// example on a full disk; the Result then carries the new token. Before +// writing, it reads the file again: if the file was removed, +// as `openshell gateway logout` does, or now holds another refresh token, +// as after a login in another process, or is for another client, the new +// token is not written, so the logout or the newer login stands. A file it +// cannot read at that point is written over. +// +// ctx bounds the lock wait, discovery and, unless req.FinishGrant is set, +// the token requests. The errors wrap ctx's error while waiting for the +// lock, ErrNotRefreshable when there is nothing to refresh or the file +// changed during the refresh, ErrDiscovery, ErrRefresh, and +// ErrTokenPersist when the new token cannot be written. When the write +// fails after a successful token request, the Result still holds the new +// token, which the file does not; the file keeps the old refresh token, as +// with the CLI. +func Refresh(ctx context.Context, req Request) (Result, error) { + unlock, err := LockDir(ctx, req.Dir) + if err != nil { + return Result{}, fmt.Errorf("waiting for another refresh of %s: %w", oidctoken.FileName, err) + } + defer unlock() + + current, err := ReadToken(req.Dir) + switch { + case err != nil: + return Result{}, fmt.Errorf("%w: %v", ErrNotRefreshable, err) + case current == nil: + return Result{}, fmt.Errorf("%w: %s does not exist", ErrNotRefreshable, oidctoken.FileName) + case !sameClient(current, req): + return Result{}, fmt.Errorf("%w: it was issued for another issuer or client", ErrNotRefreshable) + } + if tok := current.Token(); Fresh(tok, req.Window) { + return Result{Token: tok}, nil + } + if current.RefreshToken == "" { + return Result{}, fmt.Errorf("%w: it has no refresh token", ErrNotRefreshable) + } + stored := *current + + if err := checkWritable(req.Dir); err != nil { + return Result{}, err + } + + provider, err := Discover(ctx, req.Issuer) + if err != nil { + return Result{}, err + } + + grantCtx := ctx + if req.FinishGrant { + grantCtx = context.WithoutCancel(ctx) + } + tok, err := refreshToken(grantCtx, provider.TokenEndpoint, req.ClientID, stored.RefreshToken, req.Scopes) + if errors.Is(err, ErrInvalidGrant) { + peer, readErr := ReadToken(req.Dir) + if readErr != nil || peer == nil || !sameClient(peer, req) { + return Result{}, fmt.Errorf("%w: %w", ErrNotRefreshable, err) + } + if peerTok := peer.Token(); Fresh(peerTok, req.Window) { + return Result{Token: peerTok}, nil + } + if peer.RefreshToken == "" || peer.RefreshToken == stored.RefreshToken { + return Result{}, fmt.Errorf("%w: %w", ErrNotRefreshable, err) + } + stored = *peer + tok, err = refreshToken(grantCtx, provider.TokenEndpoint, req.ClientID, stored.RefreshToken, req.Scopes) + } + if err != nil { + return Result{}, err + } + + // Providers that do not rotate refresh tokens omit one from the + // response; keep the stored token so the next refresh still works. + if tok.RefreshToken == "" { + tok.RefreshToken = stored.RefreshToken + } + + // Without a file lock across processes this narrows, but does not + // close, the gap in which a logout or login can be overwritten. A file + // that cannot be read now, for example while the CLI rewrites it in + // place, is written over: the new token is the only one known to work. + b := oidctoken.FromToken(tok, stored.Issuer, stored.ClientID) + b.ClientCredentials = stored.ClientCredentials + latest, attempted, err := replaceTokenIfCurrent(req.Dir, b, func(current *oidctoken.Bundle) bool { + return sameClient(current, req) && current.RefreshToken == stored.RefreshToken + }, true) + if !attempted { + if latest != nil && sameClient(latest, req) && Fresh(latest.Token(), req.Window) { + return Result{Token: latest.Token()}, nil + } + return Result{}, fmt.Errorf("%w: %s changed during the refresh", ErrNotRefreshable, oidctoken.FileName) + } + + granted := Result{Token: tok, Granted: true} + if err != nil { + granted.Unwritten, granted.Replaced = &b, &stored + if latest != nil { + granted.Replaced = latest + } + return granted, err + } + return granted, nil +} + +// ScopesWithOpenID returns scopes with openid first and only once, as the +// authorization request sends them. It mirrors build_scopes in +// crates/openshell-cli/src/oidc_auth.rs. +func ScopesWithOpenID(scopes []string) []string { + normalized := make([]string, 0, len(scopes)+1) + normalized = append(normalized, scopeOpenID) + for _, scope := range scopes { + if scope != scopeOpenID { + normalized = append(normalized, scope) + } + } + return normalized +} + +const scopeOpenID = "openid" + +// SameClient reports whether a stored bundle was issued for issuer +// (ignoring a trailing slash) and clientID. +func SameClient(b *oidctoken.Bundle, issuer, clientID string) bool { + return NormalizeIssuer(b.Issuer) == NormalizeIssuer(issuer) && b.ClientID == clientID +} + +func sameClient(b *oidctoken.Bundle, req Request) bool { + return SameClient(b, req.Issuer, req.ClientID) +} + +// maxErrorCode is how much of a provider's error code goes into an error +// message. RFC 6749 error codes are short ASCII words. +const maxErrorCode = 64 + +// holdsSecret reports whether s contains secret as is or after undoing +// up to four rounds of percent-encoding, in either hex case. +func holdsSecret(s, secret string) bool { + for range 4 { + if strings.Contains(s, secret) { + return true + } + decoded := percentDecode(s) + if decoded == s { + return false + } + s = decoded + } + return strings.Contains(s, secret) +} + +// percentDecode decodes every valid %XX escape in s and leaves the rest, +// including malformed escapes, as is. +func percentDecode(s string) string { + var b strings.Builder + for i := 0; i < len(s); i++ { + if s[i] == '%' && i+2 < len(s) { + if hi, lo := unhex(s[i+1]), unhex(s[i+2]); hi >= 0 && lo >= 0 { + b.WriteByte(byte(hi<<4 | lo)) + i += 2 + continue + } + } + b.WriteByte(s[i]) + } + return b.String() +} + +func unhex(c byte) int { + switch { + case '0' <= c && c <= '9': + return int(c - '0') + case 'a' <= c && c <= 'f': + return int(c - 'a' + 10) + case 'A' <= c && c <= 'F': + return int(c - 'A' + 10) + } + return -1 +} + +// grantResponse is the token endpoint's JSON response. +type grantResponse struct { + AccessToken string `json:"access_token"` + RefreshToken string `json:"refresh_token"` + TokenType string `json:"token_type"` + ExpiresIn int64 `json:"expires_in"` + Error string `json:"error"` +} + +// refreshToken exchanges a refresh token for new tokens at the token +// endpoint (RFC 6749 Section 6). Like the CLI, it sends grant_type, +// refresh_token and client_id as a public client, plus scope when scopes +// are given. +// +// The refresh token is never included in error messages, even when the +// provider echoes it in its error code. The error code is quoted and cut +// to maxErrorCode bytes, and error_description is left out, since the +// provider controls that text. A response that is not JSON is reported by +// its HTTP status. +func refreshToken(ctx context.Context, tokenEndpoint, clientID, refresh string, scopes []string) (*oauth2.Token, error) { + data := url.Values{ + "grant_type": {"refresh_token"}, + "refresh_token": {refresh}, + "client_id": {clientID}, + } + if len(scopes) > 0 { + data.Set("scope", strings.Join(scopes, " ")) + } + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, tokenEndpoint, strings.NewReader(data.Encode())) + if err != nil { + return nil, fmt.Errorf("%w: failed to create token request: %v", ErrRefresh, err) + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + + resp, err := HTTPClient.Do(req) + if err != nil { + return nil, fmt.Errorf("%w: token request failed: %v", ErrRefresh, err) + } + defer func() { _ = resp.Body.Close() }() + + const maxResponseBytes = 1 << 20 + body, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBytes)) + if err != nil { + return nil, fmt.Errorf("%w: failed to read token response: %v", ErrRefresh, err) + } + + // An error page from a proxy is not JSON; its status still says what + // happened. So an error code is reported whatever the status, and a + // body that is not JSON only for a 200 response. + var tokResp grantResponse + jsonErr := json.Unmarshal(body, &tokResp) + if tokResp.Error == "invalid_grant" { + return nil, fmt.Errorf("%w: %w", ErrRefresh, ErrInvalidGrant) + } + if code := tokResp.Error; code != "" { + if refresh != "" { + code = strings.ReplaceAll(code, refresh, "[refresh token]") + code = strings.ReplaceAll(code, url.QueryEscape(refresh), "[refresh token]") + if holdsSecret(code, refresh) { + // Encoded some other way, such as with lowercase hex. + code = "[error code containing the refresh token]" + } + } + if len(code) > maxErrorCode { + code = strings.ToValidUTF8(code[:maxErrorCode], "") + "..." + } + return nil, fmt.Errorf("%w: %q", ErrRefresh, code) + } + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("%w: HTTP %d", ErrRefresh, resp.StatusCode) + } + if jsonErr != nil { + // Decoder errors can quote values from the response. + return nil, fmt.Errorf("%w: invalid token response JSON", ErrRefresh) + } + if tokResp.AccessToken == "" { + return nil, fmt.Errorf("%w: token response has no access_token", ErrRefresh) + } + + // An absent or null expires_in leaves the token without an expiry, as + // the code exchange and the CLI's oauth2 crate do. A present expires_in + // must be positive; zero or a negative value is rejected as malformed. + var fields map[string]json.RawMessage + _ = json.Unmarshal(body, &fields) + if raw, present := fields["expires_in"]; present && string(raw) != "null" && tokResp.ExpiresIn <= 0 { + return nil, fmt.Errorf("%w: token response requires a positive expires_in", ErrRefresh) + } + + tok := &oauth2.Token{ + AccessToken: tokResp.AccessToken, + RefreshToken: tokResp.RefreshToken, + TokenType: tokResp.TokenType, + } + if tokResp.ExpiresIn > 0 { + // Capped at 2^31-1 seconds as golang.org/x/oauth2 does: above about + // 9.2e9 seconds the multiplication overflows time.Duration and can + // put the expiry in the past. + tok.Expiry = time.Now().Add(time.Duration(min(tokResp.ExpiresIn, math.MaxInt32)) * time.Second) + } + return tok, nil +} diff --git a/openshell/v1/internal/oidcclient/refresh_errors_test.go b/openshell/v1/internal/oidcclient/refresh_errors_test.go new file mode 100644 index 0000000..42c0b13 --- /dev/null +++ b/openshell/v1/internal/oidcclient/refresh_errors_test.go @@ -0,0 +1,362 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package oidcclient + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "runtime" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "golang.org/x/oauth2" + + "github.com/ai-openshell/sdk-go/openshell/v1/internal/oidctoken" +) + +// newRefreshServer starts a provider whose token endpoint calls onToken +// before answering with respond, and returns its URL and a counter of +// token requests. +func newRefreshServer(t *testing.T, onToken func(), respond func() (int, string)) (string, *atomic.Int32) { + t.Helper() + ResetDiscoveryCache() + var calls atomic.Int32 + var srv *httptest.Server + srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if r.URL.Path == "/.well-known/openid-configuration" { + _, _ = fmt.Fprintf(w, `{"issuer":%q,"authorization_endpoint":%q,"token_endpoint":%q}`, + srv.URL, srv.URL+"/authorize", srv.URL+"/token") + return + } + calls.Add(1) + onToken() + status, body := respond() + w.WriteHeader(status) + _, _ = w.Write([]byte(body)) + })) + t.Cleanup(srv.Close) + return srv.URL, &calls +} + +// TestRefresh_NotRefreshable verifies which failures Refresh reports as +// ErrNotRefreshable: those where the file under the lock gives it nothing +// to refresh with, before the grant or after invalid_grant. A failed retry +// with a peer's refresh token is a refresh error, not one of these. +func TestRefresh_NotRefreshable(t *testing.T) { + expired := func(issuer, clientID, refresh string) oidctoken.Bundle { + return oidctoken.FromToken(&oauth2.Token{ + AccessToken: "old-access", RefreshToken: refresh, Expiry: time.Now().Add(-time.Minute), + }, issuer, clientID) + } + invalidGrant := func() (int, string) { return http.StatusBadRequest, `{"error":"invalid_grant"}` } + + for name, tc := range map[string]struct { + file func(t *testing.T, dir, issuer string) // the file under the lock + peer func(dir, issuer string) // what a peer leaves before the provider answers + want string + calls int32 + notRefreshable bool + }{ + "no file": { + file: func(*testing.T, string, string) {}, + want: "does not exist", + notRefreshable: true, + }, + "unreadable file": { + file: func(t *testing.T, dir, _ string) { + require.NoError(t, os.WriteFile(filepath.Join(dir, oidctoken.FileName), []byte("{"), 0o600)) + }, + want: "invalid JSON", + notRefreshable: true, + }, + "another client": { + file: func(t *testing.T, dir, issuer string) { + require.NoError(t, WriteToken(dir, expired(issuer, "other-client", "old-refresh"))) + }, + want: "another issuer or client", + notRefreshable: true, + }, + "another issuer": { + file: func(t *testing.T, dir, _ string) { + require.NoError(t, WriteToken(dir, expired("https://other.example", "client", "old-refresh"))) + }, + want: "another issuer or client", + notRefreshable: true, + }, + "no refresh token": { + file: func(t *testing.T, dir, issuer string) { + require.NoError(t, WriteToken(dir, expired(issuer, "client", ""))) + }, + want: "no refresh token", + notRefreshable: true, + }, + "invalid_grant, peer removed the file": { + peer: func(dir, _ string) { + if err := os.Remove(filepath.Join(dir, oidctoken.FileName)); err != nil { + t.Errorf("remove: %v", err) + } + }, + want: "invalid_grant", calls: 1, notRefreshable: true, + }, + "invalid_grant, peer token for another client": { + peer: func(dir, issuer string) { + if err := WriteToken(dir, expired(issuer, "other-client", "peer-refresh")); err != nil { + t.Errorf("write: %v", err) + } + }, + want: "invalid_grant", calls: 1, notRefreshable: true, + }, + "invalid_grant, same refresh token": { + peer: func(string, string) {}, + want: "invalid_grant", calls: 1, notRefreshable: true, + }, + "invalid_grant, peer without refresh token": { + peer: func(dir, issuer string) { + if err := WriteToken(dir, expired(issuer, "client", "")); err != nil { + t.Errorf("write: %v", err) + } + }, + want: "invalid_grant", calls: 1, notRefreshable: true, + }, + "invalid_grant again with the peer's refresh token": { + peer: func(dir, issuer string) { + if err := WriteToken(dir, expired(issuer, "client", "peer-refresh")); err != nil { + t.Errorf("write: %v", err) + } + }, + want: "invalid_grant", calls: 2, + }, + } { + t.Run(name, func(t *testing.T) { + dir := t.TempDir() + var issuer string + peered := false + issuer, calls := newRefreshServer(t, func() { + if tc.peer != nil && !peered { + peered = true + tc.peer(dir, issuer) + } + }, invalidGrant) + if tc.file != nil { + tc.file(t, dir, issuer) + } else { + require.NoError(t, WriteToken(dir, expired(issuer, "client", "old-refresh"))) + } + + res, err := Refresh(context.Background(), Request{Dir: dir, Issuer: issuer, ClientID: "client", Window: LoginRefreshWindow}) + require.Error(t, err) + assert.Equal(t, Result{}, res) + assert.Contains(t, err.Error(), tc.want) + assert.Equal(t, tc.notRefreshable, errors.Is(err, ErrNotRefreshable), "ErrNotRefreshable in %v", err) + assert.NotErrorIs(t, err, ErrTokenPersist) + if tc.calls > 0 { + require.ErrorIs(t, err, ErrInvalidGrant) + } + assert.Equal(t, tc.calls, calls.Load()) + }) + } +} + +// TestRefresh_FileChangedDuringGrant verifies that Refresh does not write +// the new token over a file that changed while the token request was in +// flight: removed by a logout, or replaced by a login elsewhere. A file it +// cannot read at that point is written over. +func TestRefresh_FileChangedDuringGrant(t *testing.T) { + expired := func(issuer, refresh string) oidctoken.Bundle { + return oidctoken.FromToken(&oauth2.Token{ + AccessToken: "old-access", RefreshToken: refresh, Expiry: time.Now().Add(-time.Minute), + }, issuer, "client") + } + rotated := func() (int, string) { + return http.StatusOK, `{"access_token":"new-access","refresh_token":"rotated","expires_in":3600}` + } + + for name, tc := range map[string]struct { + change func(t *testing.T, dir, issuer string) + wantToken string // empty: ErrNotRefreshable + wantFile string // refresh token left in the file; empty: no file + granted bool + unix bool // needs file modes that keep the owner out + }{ + "logout removed the file": { + change: func(t *testing.T, dir, _ string) { + if err := os.Remove(filepath.Join(dir, oidctoken.FileName)); err != nil { + t.Errorf("remove: %v", err) + } + }, + }, + "a login wrote a fresh token": { + change: func(t *testing.T, dir, issuer string) { + if err := WriteToken(dir, oidctoken.FromToken(&oauth2.Token{ + AccessToken: "login-access", RefreshToken: "login-refresh", Expiry: time.Now().Add(time.Hour), + }, issuer, "client")); err != nil { + t.Errorf("write: %v", err) + } + }, + wantToken: "login-access", + wantFile: "login-refresh", + }, + "another refresh token, expired": { + change: func(t *testing.T, dir, issuer string) { + if err := WriteToken(dir, expired(issuer, "other-refresh")); err != nil { + t.Errorf("write: %v", err) + } + }, + wantFile: "other-refresh", + }, + "unreadable while the request runs": { + // For example the CLI rewriting the file in place. The new + // token is the only one known to work, so it is written. + unix: true, + change: func(t *testing.T, dir, _ string) { + if err := os.Chmod(filepath.Join(dir, oidctoken.FileName), 0o000); err != nil { + t.Errorf("chmod: %v", err) + } + }, + wantToken: "new-access", + wantFile: "rotated", + granted: true, + }, + "a token for another client with the same refresh token": { + change: func(t *testing.T, dir, issuer string) { + if err := WriteToken(dir, oidctoken.FromToken(&oauth2.Token{ + AccessToken: "other-access", RefreshToken: "old-refresh", Expiry: time.Now().Add(-time.Minute), + }, issuer, "other-client")); err != nil { + t.Errorf("write: %v", err) + } + }, + wantFile: "old-refresh", + }, + "a token for another client": { + change: func(t *testing.T, dir, issuer string) { + if err := WriteToken(dir, oidctoken.FromToken(&oauth2.Token{ + AccessToken: "other-access", RefreshToken: "other-refresh", Expiry: time.Now().Add(time.Hour), + }, issuer, "other-client")); err != nil { + t.Errorf("write: %v", err) + } + }, + wantFile: "other-refresh", + }, + } { + t.Run(name, func(t *testing.T) { + if tc.unix && (runtime.GOOS == "windows" || os.Geteuid() == 0) { + t.Skip("needs a file the process cannot read") + } + dir := t.TempDir() + var issuer string + issuer, calls := newRefreshServer(t, func() { tc.change(t, dir, issuer) }, rotated) + require.NoError(t, WriteToken(dir, expired(issuer, "old-refresh"))) + + res, err := Refresh(context.Background(), Request{Dir: dir, Issuer: issuer, ClientID: "client", Window: LoginRefreshWindow}) + assert.Equal(t, int32(1), calls.Load()) + assert.Equal(t, tc.granted, res.Granted) + if tc.wantToken == "" { + require.ErrorIs(t, err, ErrNotRefreshable) + assert.Contains(t, err.Error(), "changed during the refresh") + assert.Nil(t, res.Token) + } else { + require.NoError(t, err) + assert.Equal(t, tc.wantToken, res.Token.AccessToken) + } + got, readErr := ReadToken(dir) + require.NoError(t, readErr) + if tc.wantFile == "" { + assert.Nil(t, got, "the removed file came back") + } else { + require.NotNil(t, got) + assert.Equal(t, tc.wantFile, got.RefreshToken) + } + }) + } +} + +// TestRefresh_WriteFailure verifies that a directory Refresh cannot write +// to is reported before the token request, so the refresh token is not +// spent, and that a write failing after the request still returns the +// new token. +func TestRefresh_WriteFailure(t *testing.T) { + if runtime.GOOS == "windows" || os.Geteuid() == 0 { + t.Skip("needs a directory the process cannot write to") + } + stored := func(issuer string) oidctoken.Bundle { + return oidctoken.FromToken(&oauth2.Token{ + AccessToken: "old-access", RefreshToken: "old-refresh", Expiry: time.Now().Add(-time.Minute), + }, issuer, "client") + } + rotated := func() (int, string) { + return http.StatusOK, `{"access_token":"new-access","refresh_token":"rotated","expires_in":3600}` + } + + t.Run("before the token request", func(t *testing.T) { + dir := t.TempDir() + issuer, calls := newRefreshServer(t, func() {}, rotated) + require.NoError(t, WriteToken(dir, stored(issuer))) + require.NoError(t, os.Chmod(dir, 0o500)) + t.Cleanup(func() { _ = os.Chmod(dir, 0o700) }) + + res, err := Refresh(context.Background(), Request{Dir: dir, Issuer: issuer, ClientID: "client", Window: LoginRefreshWindow}) + require.ErrorIs(t, err, ErrTokenPersist) + assert.Equal(t, Result{}, res) + assert.Equal(t, int32(0), calls.Load(), "the refresh token was spent") + }) + for _, accessToken := range []string{"old-access", "peer-access"} { + t.Run("after the token request/"+accessToken, func(t *testing.T) { + dir := t.TempDir() + var issuer string + issuer, calls := newRefreshServer(t, func() { + if accessToken != "old-access" { + peer := stored(issuer) + peer.AccessToken = accessToken + if err := WriteToken(dir, peer); err != nil { + t.Errorf("write peer token: %v", err) + } + } + if err := os.Chmod(dir, 0o500); err != nil { + t.Errorf("chmod: %v", err) + } + }, rotated) + require.NoError(t, WriteToken(dir, stored(issuer))) + t.Cleanup(func() { _ = os.Chmod(dir, 0o700) }) + + res, err := Refresh(context.Background(), Request{Dir: dir, Issuer: issuer, ClientID: "client", Window: LoginRefreshWindow}) + require.ErrorIs(t, err, ErrTokenPersist) + assert.True(t, res.Granted) + require.NotNil(t, res.Token) + assert.Equal(t, "new-access", res.Token.AccessToken) + assert.Equal(t, "rotated", res.Token.RefreshToken) + require.NotNil(t, res.Unwritten) + assert.Equal(t, "rotated", res.Unwritten.RefreshToken) + require.NotNil(t, res.Replaced) + assert.Equal(t, accessToken, res.Replaced.AccessToken) + assert.Equal(t, int32(1), calls.Load()) + got, readErr := ReadToken(dir) + require.NoError(t, readErr) + assert.Equal(t, "old-refresh", got.RefreshToken) + }) + } +} + +// TestRefresh_LockWaitError verifies that a lock wait cut off by ctx says +// what it was waiting for and wraps ctx's error. +func TestRefresh_LockWaitError(t *testing.T) { + dir := t.TempDir() + unlock, err := LockDir(context.Background(), dir) + require.NoError(t, err) + defer unlock() + + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) + defer cancel() + _, err = Refresh(ctx, Request{Dir: dir, Issuer: "https://idp.example.com", ClientID: "client", Window: LoginRefreshWindow}) + require.ErrorIs(t, err, context.DeadlineExceeded) + assert.Contains(t, err.Error(), "waiting for another refresh of "+oidctoken.FileName) +} diff --git a/openshell/v1/internal/oidcclient/refresh_test.go b/openshell/v1/internal/oidcclient/refresh_test.go new file mode 100644 index 0000000..41477f2 --- /dev/null +++ b/openshell/v1/internal/oidcclient/refresh_test.go @@ -0,0 +1,328 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package oidcclient + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "os" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "golang.org/x/oauth2" + + "github.com/ai-openshell/sdk-go/openshell/v1/internal/oidctoken" +) + +// respondWith starts a token endpoint that answers every request with +// status and body, and returns its URL. +func respondWith(t *testing.T, status int, body string) string { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _, _ = w.Write([]byte(body)) + })) + t.Cleanup(srv.Close) + return srv.URL + "/token" +} + +// TestRefreshToken_Errors verifies that every failure of the refresh +// request is reported as ErrRefresh, is not mistaken for +// invalid_grant, and never includes the refresh token. +func TestRefreshToken_Errors(t *testing.T) { + closed := httptest.NewServer(http.NotFoundHandler()) + closedURL := closed.URL + "/token" + closed.Close() + + for name, tc := range map[string]struct { + endpoint func(t *testing.T) string + refresh string // default "secret-refresh-token" + want string + }{ + "invalid endpoint URL": { + endpoint: func(*testing.T) string { return "http://[::1]:namedport/token" }, + want: "failed to create token request", + }, + "transport failure": { + endpoint: func(*testing.T) string { return closedURL }, + want: "token request failed", + }, + "truncated response body": { + endpoint: func(t *testing.T) string { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + conn, buf, err := http.NewResponseController(w).Hijack() + if err != nil { + t.Errorf("hijack: %v", err) + return + } + _, _ = buf.WriteString("HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\n{\"access") + _ = buf.Flush() + _ = conn.Close() + })) + t.Cleanup(srv.Close) + return srv.URL + "/token" + }, + want: "failed to read token response", + }, + "invalid JSON": { + endpoint: func(t *testing.T) string { + return respondWith(t, http.StatusOK, "not json") + }, + want: "invalid token response JSON", + }, + "invalid expiry echoes the refresh token": { + endpoint: func(t *testing.T) string { + return respondWith(t, http.StatusOK, `{"access_token":"a","expires_in":123456789012345678901234567890}`) + }, + refresh: "123456789012345678901234567890", + want: "invalid token response JSON", + }, + "server error without error code": { + endpoint: func(t *testing.T) string { + return respondWith(t, http.StatusInternalServerError, `{"access_token":"a"}`) + }, + want: "HTTP 500", + }, + "error code with status 401": { + endpoint: func(t *testing.T) string { + return respondWith(t, http.StatusUnauthorized, `{"error":"invalid_client"}`) + }, + want: `: "invalid_client"`, + }, + "proxy error page": { + endpoint: func(t *testing.T) string { + return respondWith(t, http.StatusBadGateway, "502 Bad Gateway") + }, + want: "HTTP 502", + }, + "long error code": { + endpoint: func(t *testing.T) string { + return respondWith(t, http.StatusBadRequest, `{"error":"`+strings.Repeat("x", 1000)+`"}`) + }, + want: `: "` + strings.Repeat("x", maxErrorCode) + `..."`, + }, + "error code that echoes the refresh token": { + endpoint: func(t *testing.T) string { + return respondWith(t, http.StatusBadRequest, `{"error":"bad secret-refresh-token"}`) + }, + want: `: "bad [refresh token]"`, + }, + "error code that echoes the form-encoded refresh token": { + endpoint: func(t *testing.T) string { + return respondWith(t, http.StatusBadRequest, `{"error":"bad secret%2Frefresh"}`) + }, + refresh: "secret/refresh", + want: `: "bad [refresh token]"`, + }, + "error code that echoes a refresh token with special characters": { + endpoint: func(t *testing.T) string { + return respondWith(t, http.StatusBadRequest, `{"error":"bad secret/refresh"}`) + }, + refresh: "secret/refresh", + want: `: "bad [refresh token]"`, + }, + "error code that echoes the refresh token with lowercase hex": { + endpoint: func(t *testing.T) string { + return respondWith(t, http.StatusBadRequest, `{"error":"bad rt%2fab%2bcd%3def"}`) + }, + refresh: "rt/ab+cd=ef", + want: `: "[error code containing the refresh token]"`, + }, + "error code that echoes the path-escaped refresh token": { + endpoint: func(t *testing.T) string { + return respondWith(t, http.StatusBadRequest, `{"error":"bad rt%2Fab+cd=ef"}`) + }, + refresh: "rt/ab+cd=ef", + want: `: "[error code containing the refresh token]"`, + }, + "error code that echoes the fully percent-encoded refresh token": { + endpoint: func(t *testing.T) string { + return respondWith(t, http.StatusBadRequest, `{"error":"bad %72%74%2F%61%62%2B%63%64%3D%65%66"}`) + }, + refresh: "rt/ab+cd=ef", + want: `: "[error code containing the refresh token]"`, + }, + "error code that echoes the twice-encoded refresh token": { + endpoint: func(t *testing.T) string { + return respondWith(t, http.StatusBadRequest, `{"error":"bad rt%252Fab%252Bcd%253Def"}`) + }, + refresh: "rt/ab+cd=ef", + want: `: "[error code containing the refresh token]"`, + }, + "error code that echoes the refresh token encoded four times": { + endpoint: func(t *testing.T) string { + return respondWith(t, http.StatusBadRequest, `{"error":"bad rt%2525252Fab"}`) + }, + refresh: "rt/ab", + want: `: "[error code containing the refresh token]"`, + }, + "error code with a malformed escape": { + endpoint: func(t *testing.T) string { + return respondWith(t, http.StatusBadRequest, `{"error":"bad%zz %2"}`) + }, + want: `: "bad%zz %2"`, + }, + "long error code cut inside a character": { + endpoint: func(t *testing.T) string { + return respondWith(t, http.StatusBadRequest, `{"error":"`+strings.Repeat("x", maxErrorCode-1)+`é"}`) + }, + want: `: "` + strings.Repeat("x", maxErrorCode-1) + `..."`, + }, + "error code with status 200": { + endpoint: func(t *testing.T) string { + return respondWith(t, http.StatusOK, `{"error":"temporarily_unavailable","access_token":"a"}`) + }, + want: `: "temporarily_unavailable"`, + }, + } { + t.Run(name, func(t *testing.T) { + refresh := tc.refresh + if refresh == "" { + refresh = "secret-refresh-token" + } + _, err := refreshToken(context.Background(), tc.endpoint(t), "test-client", refresh, nil) + require.ErrorIs(t, err, ErrRefresh) + assert.NotErrorIs(t, err, ErrInvalidGrant) + assert.Contains(t, err.Error(), tc.want) + assert.NotContains(t, err.Error(), refresh) + assert.NotContains(t, err.Error(), url.QueryEscape(refresh)) + assert.False(t, holdsSecret(err.Error(), refresh), "refresh token recoverable from %q", err) + assert.Less(t, len(err.Error()), 200) + }) + } +} + +// TestPercentDecode verifies that every hex digit in either case decodes, +// and that malformed or cut-off escapes stay as they are. +func TestPercentDecode(t *testing.T) { + for in, want := range map[string]string{ + "%00%09%0a%0A": "\x00\t\n\n", + "%20%30%90%a0%A0%f0": " 0\x90\xa0\xa0\xf0", + "%af%AF%Fa%fF": "\xaf\xaf\xfa\xff", + "rt%2Fab": "rt/ab", + "%g0%0g%%41": "%g0%0g%A", + "a%4": "a%4", + "%": "%", + } { + assert.Equal(t, want, percentDecode(in), "percentDecode(%q)", in) + } +} + +// TestRefreshToken_ExpiresIn verifies that an absent or null expires_in +// gives a token without an expiry, and that a present one sets it. +func TestRefreshToken_ExpiresIn(t *testing.T) { + for name, tc := range map[string]struct { + body string + noExpiry bool + }{ + "absent": {body: `{"access_token":"a"}`, noExpiry: true}, + "null": {body: `{"access_token":"a","expires_in":null}`, noExpiry: true}, + "set": {body: `{"access_token":"a","expires_in":60}`}, + // Larger than time.Duration can hold; capped as golang.org/x/oauth2 does. + "huge": {body: `{"access_token":"a","expires_in":10000000000}`}, + } { + t.Run(name, func(t *testing.T) { + tok, err := refreshToken(context.Background(), respondWith(t, http.StatusOK, tc.body), "test-client", "r", nil) + require.NoError(t, err) + assert.Equal(t, tc.noExpiry, tok.Expiry.IsZero()) + if !tc.noExpiry { + assert.True(t, tok.Expiry.After(time.Now().Add(59*time.Second)), "expiry %v", tok.Expiry) + } + if name == "set" { + assert.WithinDuration(t, time.Now().Add(time.Minute), tok.Expiry, 5*time.Second) + } + }) + } +} + +// TestFresh verifies the freshness test at the window boundary. With the +// 10 second LoginRefreshWindow it is oauth2.Token.Valid: a token that expires +// exactly one window from now is still fresh, one nanosecond less is not. +func TestFresh(t *testing.T) { + base := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) + now = func() time.Time { return base } + t.Cleanup(func() { now = time.Now }) + + at := func(d time.Duration) *oauth2.Token { + return &oauth2.Token{AccessToken: "a", Expiry: base.Add(d)} + } + w := LoginRefreshWindow + assert.True(t, Fresh(at(w), w), "expires exactly one window from now") + assert.False(t, Fresh(at(w-time.Nanosecond), w), "expires just inside the window") + assert.True(t, Fresh(at(time.Hour), w)) + assert.False(t, Fresh(at(-time.Second), w), "already expired") + assert.True(t, Fresh(&oauth2.Token{AccessToken: "a"}, w), "no expiry") + assert.False(t, Fresh(&oauth2.Token{Expiry: base.Add(time.Hour)}, w), "no access token") + assert.False(t, Fresh(nil, w)) + assert.True(t, Fresh(at(30*time.Second), 30*time.Second)) + assert.False(t, Fresh(at(30*time.Second-time.Nanosecond), 30*time.Second)) +} + +// TestFreshMatchesOAuth2Valid verifies that with LoginRefreshWindow, Fresh +// agrees with oauth2.Token.Valid, which Login used before the refresh code +// moved here. The expiries stay a second away from the boundary so the +// two clocks cannot disagree. +func TestFreshMatchesOAuth2Valid(t *testing.T) { + for _, d := range []time.Duration{-time.Hour, -time.Second, 0, 5 * time.Second, 9 * time.Second, 11 * time.Second, time.Hour} { + tok := &oauth2.Token{AccessToken: "a", Expiry: time.Now().Add(d)} + assert.Equal(t, tok.Valid(), Fresh(tok, LoginRefreshWindow), "expiry in %v", d) + } + for _, tok := range []*oauth2.Token{{AccessToken: "a"}, {}, {Expiry: time.Now().Add(time.Hour)}} { + assert.Equal(t, tok.Valid(), Fresh(tok, LoginRefreshWindow), "%+v", tok) + } +} + +// TestRefresh_FinishGrant verifies that with FinishGrant a token request +// already sent completes and is stored when ctx ends, and that without it +// the request is abandoned and the file keeps the old token. +func TestRefresh_FinishGrant(t *testing.T) { + for _, finish := range []bool{true, false} { + t.Run(fmt.Sprintf("FinishGrant=%v", finish), func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + issuer, _ := newRefreshServer(t, func() { + // The provider has accepted the refresh when the caller + // gives up. + cancel() + time.Sleep(50 * time.Millisecond) + }, func() (int, string) { + return http.StatusOK, `{"access_token":"new-access","refresh_token":"rotated","expires_in":3600}` + }) + dir := t.TempDir() + require.NoError(t, WriteToken(dir, oidctoken.FromToken(&oauth2.Token{ + AccessToken: "old-access", RefreshToken: "old-refresh", Expiry: time.Now().Add(-time.Minute), + }, issuer, "client"))) + + res, err := Refresh(ctx, Request{Dir: dir, Issuer: issuer, ClientID: "client", Window: LoginRefreshWindow, FinishGrant: finish}) + stored, readErr := ReadToken(dir) + require.NoError(t, readErr) + entries, dirErr := os.ReadDir(dir) + require.NoError(t, dirErr) + assert.Len(t, entries, 1, "only %s is left in the directory", oidctoken.FileName) + if finish { + require.NoError(t, err) + assert.True(t, res.Granted) + assert.Equal(t, "new-access", res.Token.AccessToken) + assert.Equal(t, "rotated", stored.RefreshToken) + return + } + require.ErrorIs(t, err, ErrRefresh) + assert.Contains(t, err.Error(), "context canceled") + assert.Equal(t, "old-refresh", stored.RefreshToken) + }) + } +} + +func TestScopesWithOpenID(t *testing.T) { + assert.Equal(t, []string{"openid"}, ScopesWithOpenID(nil)) + assert.Equal(t, []string{"openid", "a", "b"}, ScopesWithOpenID([]string{"a", "openid", "b", "openid"})) + assert.Equal(t, []string{"openid", "a"}, ScopesWithOpenID([]string{"openid", "a"})) +} diff --git a/openshell/v1/oidc/token.go b/openshell/v1/internal/oidcclient/token.go similarity index 64% rename from openshell/v1/oidc/token.go rename to openshell/v1/internal/oidcclient/token.go index 8c3f780..d85d13b 100644 --- a/openshell/v1/oidc/token.go +++ b/openshell/v1/internal/oidcclient/token.go @@ -1,9 +1,10 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -package oidc +package oidcclient import ( + "context" "encoding/json" "errors" "fmt" @@ -16,11 +17,11 @@ import ( "github.com/ai-openshell/sdk-go/openshell/v1/internal/oidctoken" ) -// writeToken persists an OIDC token bundle to disk as oidc_token.json in +// WriteToken persists an OIDC token bundle to disk as oidc_token.json in // the given directory, in the CLI's format. The file is written with 0600 -// permissions (owner-only) to protect credentials, and on Windows the final +// permissions (owner-only on Unix) to protect credentials, and on Windows the final // replace is retried briefly while another process has the file open. -func writeToken(dir string, b oidctoken.Bundle) error { +func WriteToken(dir string, b oidctoken.Bundle) error { data, err := json.Marshal(b) if err != nil { return fmt.Errorf("%w: failed to marshal token: %v", ErrTokenPersist, err) @@ -101,12 +102,26 @@ func isTransientReplaceError(goos string, err error) bool { (errno == errorAccessDenied || errno == errorSharingViolation) } -// readToken reads an existing oidc_token.json from the given +// checkWritable returns ErrTokenPersist if a file cannot be created in dir. +// It catches a missing write permission, not every later write failure, +// such as a full disk. +func checkWritable(dir string) error { + f, err := os.CreateTemp(dir, ".oidc-token-*") + if err != nil { + return fmt.Errorf("%w: cannot write to the token directory: %v", ErrTokenPersist, err) + } + name := f.Name() + _ = f.Close() + _ = os.Remove(name) + return nil +} + +// ReadToken reads an existing oidc_token.json from the given // directory. It returns: // - (bundle, nil) if the file exists and parses // - (nil, nil) if the file does not exist // - (nil, error) if the file exists but cannot be read or parsed -func readToken(dir string) (*oidctoken.Bundle, error) { +func ReadToken(dir string) (*oidctoken.Bundle, error) { path := filepath.Join(dir, oidctoken.FileName) data, err := os.ReadFile(path) @@ -119,8 +134,38 @@ func readToken(dir string) (*oidctoken.Bundle, error) { var bundle oidctoken.Bundle if err := json.Unmarshal(data, &bundle); err != nil { - return nil, fmt.Errorf("%w: invalid JSON in %s: %v", ErrTokenPersist, oidctoken.FileName, err) + // Decoder errors can quote values from the token file. + return nil, fmt.Errorf("%w: invalid JSON in %s", ErrTokenPersist, oidctoken.FileName) } return &bundle, nil } + +// SavePendingToken retries a write while the file still contains the +// access token that the pending token replaced. +func SavePendingToken(ctx context.Context, dir string, bundle oidctoken.Bundle, replacedAccessToken string) error { + unlock, err := LockDir(ctx, dir) + if err != nil { + return fmt.Errorf("waiting for another refresh of %s: %w", oidctoken.FileName, err) + } + defer unlock() + + _, _, err = replaceTokenIfCurrent(dir, bundle, func(current *oidctoken.Bundle) bool { + return current.AccessToken == replacedAccessToken + }, false) + return err +} + +// replaceTokenIfCurrent rereads the file under the caller's refresh lock. +// It returns the observed bundle and whether a write was attempted. +func replaceTokenIfCurrent(dir string, bundle oidctoken.Bundle, matches func(*oidctoken.Bundle) bool, replaceUnreadable bool) (*oidctoken.Bundle, bool, error) { + current, err := ReadToken(dir) + if err != nil { + if !replaceUnreadable { + return nil, false, err + } + } else if current == nil || !matches(current) { + return current, false, nil + } + return current, true, WriteToken(dir, bundle) +} diff --git a/openshell/v1/internal/oidcclient/token_test.go b/openshell/v1/internal/oidcclient/token_test.go new file mode 100644 index 0000000..ac4a227 --- /dev/null +++ b/openshell/v1/internal/oidcclient/token_test.go @@ -0,0 +1,119 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package oidcclient + +import ( + "errors" + "os" + "path/filepath" + "syscall" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/ai-openshell/sdk-go/openshell/v1/internal/oidctoken" +) + +// TestRetryReplace verifies the replace retry schedule: transient errors +// are retried with delays doubling from 5 ms up to 50 ms until they add +// up to 250 ms, and any other error is returned at once. +func TestRetryReplace(t *testing.T) { + errTransient := errors.New("transient") + errOther := errors.New("other") + transient := func(err error) bool { return errors.Is(err, errTransient) } + + t.Run("succeeds after transient failures", func(t *testing.T) { + var slept []time.Duration + calls := 0 + err := retryReplace(func() error { + calls++ + if calls < 3 { + return errTransient + } + return nil + }, transient, func(d time.Duration) { slept = append(slept, d) }) + require.NoError(t, err) + assert.Equal(t, 3, calls) + assert.Equal(t, []time.Duration{5 * time.Millisecond, 10 * time.Millisecond}, slept) + }) + + t.Run("returns other errors at once", func(t *testing.T) { + var slept []time.Duration + err := retryReplace(func() error { return errOther }, transient, + func(d time.Duration) { slept = append(slept, d) }) + require.ErrorIs(t, err, errOther) + assert.Empty(t, slept) + }) + + t.Run("gives up after 250 ms of delays", func(t *testing.T) { + var slept []time.Duration + calls := 0 + err := retryReplace(func() error { calls++; return errTransient }, transient, + func(d time.Duration) { slept = append(slept, d) }) + require.ErrorIs(t, err, errTransient) + ms := time.Millisecond + assert.Equal(t, []time.Duration{5 * ms, 10 * ms, 20 * ms, 40 * ms, 50 * ms, 50 * ms, 50 * ms, 50 * ms}, slept) + assert.Equal(t, len(slept)+1, calls) + }) +} + +// TestIsTransientReplaceError verifies that only access denied and sharing +// violation on Windows are retried. +func TestIsTransientReplaceError(t *testing.T) { + link := func(errno syscall.Errno) error { + return &os.LinkError{Op: "rename", Old: "a", New: "b", Err: errno} + } + assert.True(t, isTransientReplaceError("windows", link(5))) + assert.True(t, isTransientReplaceError("windows", link(32))) + assert.False(t, isTransientReplaceError("windows", link(2))) + assert.False(t, isTransientReplaceError("windows", errors.New("rename failed"))) + assert.False(t, isTransientReplaceError("linux", link(5))) + assert.False(t, isTransientReplaceError("darwin", link(32))) +} + +// TestTokenFile_Errors verifies that failures to read or replace +// oidc_token.json are reported as ErrTokenPersist with the step that +// failed, and that a failed write leaves no temporary file behind. +func TestTokenFile_Errors(t *testing.T) { + b := oidctoken.Bundle{AccessToken: "access", Issuer: "https://idp.example.com", ClientID: "client"} + + t.Run("token path is a directory", func(t *testing.T) { + dir := t.TempDir() + require.NoError(t, os.Mkdir(filepath.Join(dir, oidctoken.FileName), 0o700)) + + _, err := ReadToken(dir) + require.ErrorIs(t, err, ErrTokenPersist) + assert.Contains(t, err.Error(), "cannot read") + + err = WriteToken(dir, b) + require.ErrorIs(t, err, ErrTokenPersist) + assert.Contains(t, err.Error(), "failed to replace") + entries, readErr := os.ReadDir(dir) + require.NoError(t, readErr) + assert.Len(t, entries, 1, "only the directory is left") + }) + t.Run("missing directory", func(t *testing.T) { + err := WriteToken(filepath.Join(t.TempDir(), "absent"), b) + require.ErrorIs(t, err, ErrTokenPersist) + assert.Contains(t, err.Error(), "failed to create temporary token file") + }) + t.Run("missing file", func(t *testing.T) { + got, err := ReadToken(t.TempDir()) + require.NoError(t, err) + assert.Nil(t, got) + }) + t.Run("malformed expiry hides its value", func(t *testing.T) { + dir := t.TempDir() + const invalidExpiry = "123456789012345678901234567890" + data := []byte(`{"access_token":"access","expires_at":` + invalidExpiry + `}`) + require.NoError(t, os.WriteFile(filepath.Join(dir, oidctoken.FileName), data, 0o600)) + + _, err := ReadToken(dir) + require.ErrorIs(t, err, ErrTokenPersist) + assert.ErrorContains(t, err, "invalid JSON in "+oidctoken.FileName) + assert.NotContains(t, err.Error(), invalidExpiry) + }) +} diff --git a/openshell/v1/internal/oidctoken/oidctoken.go b/openshell/v1/internal/oidctoken/oidctoken.go index 306e9ee..9be4c4c 100644 --- a/openshell/v1/internal/oidctoken/oidctoken.go +++ b/openshell/v1/internal/oidctoken/oidctoken.go @@ -14,6 +14,10 @@ import ( // FileName is the OIDC token bundle in a gateway directory. const FileName = "oidc_token.json" +// RefreshWindow lets the gateway's token source share its renewal window +// with the SDK cache without changing the contract for other token sources. +type RefreshWindow time.Duration + // Bundle is the CLI's on-disk OIDC token bundle (openshell-bootstrap OidcTokenBundle). type Bundle struct { AccessToken string `json:"access_token"` diff --git a/openshell/v1/oidc/authcode.go b/openshell/v1/oidc/authcode.go index 0bde13d..d9a068c 100644 --- a/openshell/v1/oidc/authcode.go +++ b/openshell/v1/oidc/authcode.go @@ -19,6 +19,8 @@ import ( "time" "golang.org/x/oauth2" + + "github.com/ai-openshell/sdk-go/openshell/v1/internal/oidcclient" ) // generateCodeVerifier creates a PKCE code verifier per RFC 7636. @@ -195,7 +197,7 @@ func exchangeCode(ctx context.Context, tokenEndpoint, clientID, code, redirectUR } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - resp, err := oidcHTTPClient.Do(req) + resp, err := oidcclient.HTTPClient.Do(req) if err != nil { return nil, fmt.Errorf("%w: token request failed: %v", ErrAuthCode, err) } diff --git a/openshell/v1/oidc/credentials.go b/openshell/v1/oidc/credentials.go index a895d81..ee5a4f7 100644 --- a/openshell/v1/oidc/credentials.go +++ b/openshell/v1/oidc/credentials.go @@ -17,6 +17,8 @@ import ( "github.com/ai-openshell/sdk-go/openshell/v1/gateway" "github.com/ai-openshell/sdk-go/openshell/v1/internal/options" + + "github.com/ai-openshell/sdk-go/openshell/v1/internal/oidcclient" ) // ClientCredentials performs a non-interactive OAuth2 client credentials @@ -117,7 +119,7 @@ func exchangeClientCredentials(ctx context.Context, cfg *loginConfig, requirePos } // Discover provider endpoints. - provider, err := discover(ctx, cfg.issuer) + provider, err := oidcclient.Discover(ctx, cfg.issuer) if err != nil { return nil, err } @@ -144,7 +146,7 @@ func exchangeClientCredentials(ctx context.Context, cfg *loginConfig, requirePos // Use a no-redirect client for token requests that carry client_secret // in the POST body. A 307/308 redirect would replay the body (including // the secret) to the redirect target. - noRedirectClient := *oidcHTTPClient + noRedirectClient := *oidcclient.HTTPClient noRedirectClient.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } diff --git a/openshell/v1/oidc/credentials_test.go b/openshell/v1/oidc/credentials_test.go index 616d02d..87a4eef 100644 --- a/openshell/v1/oidc/credentials_test.go +++ b/openshell/v1/oidc/credentials_test.go @@ -24,6 +24,7 @@ import ( "github.com/stretchr/testify/require" "github.com/ai-openshell/sdk-go/openshell/v1/gateway" + "github.com/ai-openshell/sdk-go/openshell/v1/internal/oidcclient" ) type clientCredentialsFixture struct { @@ -68,10 +69,10 @@ func TestClientCredentialsConformanceFixture(t *testing.T) { fixture := loadClientCredentialsFixture(t) assert.Equal(t, int(clientCredentialsLeeway/time.Second), fixture.Expiry.LeewaySeconds) for _, raw := range fixture.URLs.Allowed { - assert.NoError(t, validateSecureURL("issuer", raw), raw) + assert.NoError(t, oidcclient.ValidateSecureURL("issuer", raw), raw) } for _, raw := range fixture.URLs.Rejected { - assert.Error(t, validateSecureURL("issuer", raw), raw) + assert.Error(t, oidcclient.ValidateSecureURL("issuer", raw), raw) } } @@ -80,7 +81,7 @@ func TestClientCredentialsRejectsInvalidExpiryConformance(t *testing.T) { for _, raw := range fixture.Expiry.InvalidExpiresIn { raw := raw t.Run(string(raw), func(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() var server *httptest.Server server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/.well-known/openid-configuration" { @@ -108,7 +109,7 @@ func TestClientCredentialsRejectsInvalidExpiryConformance(t *testing.T) { } func TestClientCredentialsMissingExpiryCompatibility(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() var server *httptest.Server server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/.well-known/openid-configuration" { @@ -147,7 +148,7 @@ func TestClientCredentialsRefusesRedirectsConformance(t *testing.T) { for _, endpoint := range []string{"discovery", "token"} { endpoint := endpoint t.Run(fmt.Sprintf("%s_%d", endpoint, status), func(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() var server *httptest.Server var redirected atomic.Bool server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -186,7 +187,7 @@ func TestClientCredentialsRefusesRedirectsConformance(t *testing.T) { } func TestClientCredentialsRejectsMismatchedIssuerConformance(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() fixture := loadClientCredentialsFixture(t) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _ = json.NewEncoder(w).Encode(map[string]string{ @@ -208,7 +209,7 @@ func TestClientCredentialsRejectsMismatchedIssuerConformance(t *testing.T) { } func TestClientCredentialsRejectsOversizedResponseConformance(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() fixture := loadClientCredentialsFixture(t) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write(make([]byte, fixture.Limits.MaxResponseBytes+1)) @@ -226,7 +227,7 @@ func TestClientCredentialsRejectsOversizedResponseConformance(t *testing.T) { } func TestClientCredentialsAuthSingleFlightRenewalAndFields(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() fixture := loadClientCredentialsFixture(t) var server *httptest.Server var calls atomic.Int32 @@ -314,7 +315,7 @@ func TestClientCredentialsAuthLateFlightReusesCachedToken(t *testing.T) { func TestClientCredentialsAuthNonPositiveTimeoutUsesDefaultBound(t *testing.T) { for _, timeout := range []time.Duration{0, -1 * time.Second} { t.Run(timeout.String(), func(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() var server *httptest.Server server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/.well-known/openid-configuration" { @@ -421,7 +422,7 @@ func TestClientCredentialsSendNoScopeParameterWithoutScopes(t *testing.T) { for entryName, run := range entryPoints { for scopeName, scopeOpts := range scopeOptions { t.Run(entryName+"/"+scopeName, func(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() var form url.Values var srv *httptest.Server srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -474,7 +475,7 @@ func TestClientCredentials_WithTimeoutBoundsExchange(t *testing.T) { // context.DeadlineExceeded, so callers can tell a timeout from a provider // failure. func TestClientCredentials_TokenRequestTimeoutWrapsContextError(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() release := make(chan struct{}) var srv *httptest.Server srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -493,7 +494,7 @@ func TestClientCredentials_TokenRequestTimeoutWrapsContextError(t *testing.T) { t.Cleanup(func() { close(release) }) // runs before srv.Close // Fetch discovery first, so the timeout hits the token request. - _, err := discover(context.Background(), srv.URL) + _, err := oidcclient.Discover(context.Background(), srv.URL) require.NoError(t, err) _, err = ClientCredentials(context.Background(), @@ -523,7 +524,7 @@ func TestClientCredentials_TimeoutDeadlineRules(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() provider := setupCredentialsMockProvider(t, "client", "secret") ctx := context.Background() @@ -556,7 +557,7 @@ func TestClientCredentials_TimeoutDeadlineRules(t *testing.T) { } func TestClientCredentialsAuthCancellationDoesNotPoisonSharedExchange(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() var server *httptest.Server started := make(chan struct{}) release := make(chan struct{}) @@ -612,7 +613,7 @@ func TestClientCredentialsAuthRedactsSecretProviderError(t *testing.T) { } func TestClientCredentialsAuthFailsClosedOnRenewalError(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() var server *httptest.Server var fail atomic.Bool server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -717,7 +718,7 @@ func setupCredentialsMockProvider(t *testing.T, expectedClientID, expectedSecret // TestClientCredentials_Success verifies the happy path: valid client // ID, secret, and issuer produce a valid access token. func TestClientCredentials_Success(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() provider := setupCredentialsMockProvider(t, "my-client", "my-secret") @@ -737,7 +738,7 @@ func TestClientCredentials_Success(t *testing.T) { // TestClientCredentials_MissingIssuer verifies that ClientCredentials // returns ErrOIDCConfig when the issuer is not set. func TestClientCredentials_MissingIssuer(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() _, err := ClientCredentials(context.Background(), WithClientID("my-client"), @@ -750,7 +751,7 @@ func TestClientCredentials_MissingIssuer(t *testing.T) { // TestClientCredentials_MissingClientID verifies that ClientCredentials // returns ErrOIDCConfig when the client ID is not set. func TestClientCredentials_MissingClientID(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() _, err := ClientCredentials(context.Background(), WithIssuer("https://example.com"), @@ -764,7 +765,7 @@ func TestClientCredentials_MissingClientID(t *testing.T) { // ClientCredentials returns ErrClientCredentials when the secret is // missing. func TestClientCredentials_MissingClientSecret(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() _, err := ClientCredentials(context.Background(), WithIssuer("https://example.com"), @@ -779,7 +780,7 @@ func TestClientCredentials_MissingClientSecret(t *testing.T) { // rejects the credentials, and that the secret is not leaked in the // error message. func TestClientCredentials_InvalidCredentials(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() provider := setupCredentialsMockProvider(t, "good-client", "good-secret") @@ -803,7 +804,7 @@ func TestClientCredentials_InvalidCredentials(t *testing.T) { // ClientCredentials returns ErrDiscovery when the provider is // unreachable. func TestClientCredentials_DiscoveryFailure(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() @@ -820,7 +821,7 @@ func TestClientCredentials_DiscoveryFailure(t *testing.T) { // TestClientCredentials_WithGateway verifies that ClientCredentials // resolves OIDC config from gateway metadata when WithGateway is set. func TestClientCredentials_WithGateway(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() provider := setupCredentialsMockProvider(t, "gw-client", "gw-secret") @@ -850,7 +851,7 @@ func TestClientCredentials_WithGateway(t *testing.T) { // TestClientCredentials_CustomScopes verifies that WithScopes overrides // default scopes in the client credentials request. func TestClientCredentials_CustomScopes(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() var receivedScope string mux := http.NewServeMux() @@ -893,7 +894,7 @@ func TestClientCredentials_CustomScopes(t *testing.T) { // TestClientCredentials_ContextCancellation verifies that // ClientCredentials respects context cancellation. func TestClientCredentials_ContextCancellation(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() provider := setupCredentialsMockProvider(t, "my-client", "my-secret") diff --git a/openshell/v1/oidc/device.go b/openshell/v1/oidc/device.go index 2c35819..511294d 100644 --- a/openshell/v1/oidc/device.go +++ b/openshell/v1/oidc/device.go @@ -17,6 +17,8 @@ import ( "github.com/ai-openshell/sdk-go/openshell/v1/gateway" "github.com/ai-openshell/sdk-go/openshell/v1/internal/options" + + "github.com/ai-openshell/sdk-go/openshell/v1/internal/oidcclient" ) // deviceAuthResponse holds the parsed response from the device @@ -90,7 +92,7 @@ func DeviceLogin(ctx context.Context, opts ...LoginOption) (*oauth2.Token, error } // Discover provider endpoints. - provider, err := discover(ctx, cfg.issuer) + provider, err := oidcclient.Discover(ctx, cfg.issuer) if err != nil { return nil, err } @@ -155,7 +157,7 @@ func requestDeviceCode(ctx context.Context, endpoint, clientID string, scopes [] } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - resp, err := oidcHTTPClient.Do(req) + resp, err := oidcclient.HTTPClient.Do(req) if err != nil { return nil, fmt.Errorf("%w: device authorization request failed", ErrDeviceCode) } @@ -232,7 +234,7 @@ func tryDeviceTokenExchange(ctx context.Context, tokenEndpoint, clientID, device } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - resp, err := oidcHTTPClient.Do(req) + resp, err := oidcclient.HTTPClient.Do(req) if err != nil { // If the context was cancelled or timed out, surface that as // ErrTimeout so callers can distinguish "user/caller cancelled" diff --git a/openshell/v1/oidc/device_test.go b/openshell/v1/oidc/device_test.go index 9e8cdd8..24e0c5a 100644 --- a/openshell/v1/oidc/device_test.go +++ b/openshell/v1/oidc/device_test.go @@ -17,6 +17,8 @@ import ( "github.com/stretchr/testify/require" "github.com/ai-openshell/sdk-go/openshell/v1/gateway" + + "github.com/ai-openshell/sdk-go/openshell/v1/internal/oidcclient" ) // --- T025: Device code flow tests --- @@ -90,7 +92,7 @@ func setupDeviceMockProvider(t *testing.T, pendingPolls int) *httptest.Server { // requests a device code, displays it, polls until authorized, and // returns a valid token. func TestDeviceLogin_Success(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() // Provider returns "authorization_pending" for the first 2 polls, // then returns a token on the 3rd poll. @@ -145,7 +147,7 @@ func TestDeviceLogin_AlwaysRequestsOpenIDScope(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() scope := &capturedScope{} srv := setupScopeCapturingDeviceProvider(t, scope) @@ -201,7 +203,7 @@ func TestDeviceLogin_GatewayScopes(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() scope := &capturedScope{} srv := setupScopeCapturingDeviceProvider(t, scope) @@ -284,7 +286,7 @@ func setupScopeCapturingDeviceProvider(t *testing.T, scope *capturedScope) *http // TestDeviceLogin_MissingIssuer verifies that DeviceLogin returns // ErrOIDCConfig when the issuer is not provided. func TestDeviceLogin_MissingIssuer(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() _, err := DeviceLogin(context.Background(), WithClientID("device-client"), @@ -296,7 +298,7 @@ func TestDeviceLogin_MissingIssuer(t *testing.T) { // TestDeviceLogin_MissingClientID verifies that DeviceLogin returns // ErrOIDCConfig when the client ID is not provided. func TestDeviceLogin_MissingClientID(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() _, err := DeviceLogin(context.Background(), WithIssuer("https://example.com"), @@ -308,7 +310,7 @@ func TestDeviceLogin_MissingClientID(t *testing.T) { // TestDeviceLogin_DiscoveryFailure verifies that DeviceLogin returns // ErrDiscovery when the OIDC provider is unreachable. func TestDeviceLogin_DiscoveryFailure(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() @@ -324,7 +326,7 @@ func TestDeviceLogin_DiscoveryFailure(t *testing.T) { // TestDeviceLogin_SlowDown verifies that the polling loop respects the // "slow_down" response by increasing the polling interval. func TestDeviceLogin_SlowDown(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() mux := http.NewServeMux() var srv *httptest.Server @@ -391,7 +393,7 @@ func TestDeviceLogin_SlowDown(t *testing.T) { // TestDeviceLogin_ExpiredDeviceCode verifies that DeviceLogin returns // ErrDeviceCode when the device code expires before authorization. func TestDeviceLogin_ExpiredDeviceCode(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() mux := http.NewServeMux() var srv *httptest.Server @@ -443,7 +445,7 @@ func TestDeviceLogin_ExpiredDeviceCode(t *testing.T) { // TestDeviceLogin_CustomDisplayFunc verifies that WithDisplayFunc is // invoked with the verification URL and user code. func TestDeviceLogin_CustomDisplayFunc(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() // Provider that immediately returns a token (0 pending polls). provider := setupDeviceMockProvider(t, 0) @@ -473,7 +475,7 @@ func TestDeviceLogin_CustomDisplayFunc(t *testing.T) { // TestDeviceLogin_WithGateway verifies that DeviceLogin resolves OIDC // config from gateway metadata when WithGateway is set. func TestDeviceLogin_WithGateway(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() provider := setupDeviceMockProvider(t, 0) @@ -503,7 +505,7 @@ func TestDeviceLogin_WithGateway(t *testing.T) { // TestDeviceLogin_ContextCancellation verifies that DeviceLogin // respects context cancellation during polling. func TestDeviceLogin_ContextCancellation(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() // Provider that always returns "authorization_pending" so // the polling loop never succeeds on its own. @@ -526,7 +528,7 @@ func TestDeviceLogin_ContextCancellation(t *testing.T) { } func TestDeviceLogin_WithTimeoutBoundsPolling(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() provider := setupDeviceMockProvider(t, 1000) started := time.Now() @@ -544,7 +546,7 @@ func TestDeviceLogin_WithTimeoutBoundsPolling(t *testing.T) { // TestDeviceLogin_AccessDenied verifies that DeviceLogin returns // ErrDeviceCode when the user denies authorization. func TestDeviceLogin_AccessDenied(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() mux := http.NewServeMux() var srv *httptest.Server @@ -597,7 +599,7 @@ func TestDeviceLogin_AccessDenied(t *testing.T) { // TestDeviceLogin_UnknownError verifies that DeviceLogin returns // ErrDeviceCode with the error description for unknown error codes. func TestDeviceLogin_UnknownError(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() mux := http.NewServeMux() var srv *httptest.Server @@ -652,7 +654,7 @@ func TestDeviceLogin_UnknownError(t *testing.T) { // returns ErrDeviceCode when the device authorization endpoint returns // a non-200 HTTP status. func TestDeviceLogin_DeviceEndpointHTTPError(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() mux := http.NewServeMux() var srv *httptest.Server @@ -691,7 +693,7 @@ func TestDeviceLogin_DeviceEndpointHTTPError(t *testing.T) { // TestDeviceLogin_DeviceEndpointInvalidJSON verifies that DeviceLogin // returns ErrDeviceCode when the device endpoint returns invalid JSON. func TestDeviceLogin_DeviceEndpointInvalidJSON(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() mux := http.NewServeMux() var srv *httptest.Server @@ -730,7 +732,7 @@ func TestDeviceLogin_DeviceEndpointInvalidJSON(t *testing.T) { // TestDeviceLogin_MissingUserCode verifies that DeviceLogin returns // ErrDeviceCode when the device endpoint returns an empty user_code. func TestDeviceLogin_MissingUserCode(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() mux := http.NewServeMux() var srv *httptest.Server @@ -777,7 +779,7 @@ func TestDeviceLogin_MissingUserCode(t *testing.T) { // returns ErrDeviceCode when the token endpoint returns invalid JSON // during polling. func TestDeviceLogin_TokenEndpointInvalidJSON(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() mux := http.NewServeMux() var srv *httptest.Server @@ -829,7 +831,7 @@ func TestDeviceLogin_TokenEndpointInvalidJSON(t *testing.T) { // ErrDeviceCode when the provider does not advertise a device // authorization endpoint. func TestDeviceLogin_NoDeviceEndpoint(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() mux := http.NewServeMux() var srv *httptest.Server diff --git a/openshell/v1/oidc/discovery_test.go b/openshell/v1/oidc/discovery_test.go index ede7218..bc8b6e7 100644 --- a/openshell/v1/oidc/discovery_test.go +++ b/openshell/v1/oidc/discovery_test.go @@ -13,6 +13,8 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/ai-openshell/sdk-go/openshell/v1/internal/oidcclient" ) // wellKnownJSON returns a valid OIDC discovery document JSON string @@ -37,9 +39,9 @@ func TestDiscover_ValidDocument(t *testing.T) { defer srv.Close() // Clear cache to avoid interference from other tests. - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() - cfg, err := discover(context.Background(), srv.URL) + cfg, err := oidcclient.Discover(context.Background(), srv.URL) require.NoError(t, err) assert.Equal(t, srv.URL, cfg.Issuer) @@ -60,12 +62,12 @@ func TestDiscover_CachesResult(t *testing.T) { })) defer srv.Close() - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() - cfg1, err := discover(context.Background(), srv.URL) + cfg1, err := oidcclient.Discover(context.Background(), srv.URL) require.NoError(t, err) - cfg2, err := discover(context.Background(), srv.URL) + cfg2, err := oidcclient.Discover(context.Background(), srv.URL) require.NoError(t, err) // Same pointer should be returned from cache. @@ -85,12 +87,12 @@ func TestDiscover_DifferentIssuersNotCached(t *testing.T) { srv2 := httptest.NewServer(handler) defer srv2.Close() - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() - cfg1, err := discover(context.Background(), srv1.URL) + cfg1, err := oidcclient.Discover(context.Background(), srv1.URL) require.NoError(t, err) - cfg2, err := discover(context.Background(), srv2.URL) + cfg2, err := oidcclient.Discover(context.Background(), srv2.URL) require.NoError(t, err) // Different issuers should yield different cached entries. @@ -103,9 +105,9 @@ func TestDiscover_HTTPError(t *testing.T) { })) defer srv.Close() - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() - _, err := discover(context.Background(), srv.URL) + _, err := oidcclient.Discover(context.Background(), srv.URL) require.Error(t, err) assert.True(t, errors.Is(err, ErrDiscovery)) } @@ -117,9 +119,9 @@ func TestDiscover_InvalidJSON(t *testing.T) { })) defer srv.Close() - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() - _, err := discover(context.Background(), srv.URL) + _, err := oidcclient.Discover(context.Background(), srv.URL) require.Error(t, err) assert.True(t, errors.Is(err, ErrDiscovery)) } @@ -132,9 +134,9 @@ func TestDiscover_MissingTokenEndpoint(t *testing.T) { })) defer srv.Close() - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() - _, err := discover(context.Background(), srv.URL) + _, err := oidcclient.Discover(context.Background(), srv.URL) require.Error(t, err) assert.True(t, errors.Is(err, ErrDiscovery)) assert.Contains(t, err.Error(), "token_endpoint") @@ -148,12 +150,12 @@ func TestDiscover_ContextCancelled(t *testing.T) { })) defer srv.Close() - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() ctx, cancel := context.WithCancel(context.Background()) cancel() // Cancel immediately. - _, err := discover(ctx, srv.URL) + _, err := oidcclient.Discover(ctx, srv.URL) require.Error(t, err) assert.True(t, errors.Is(err, ErrDiscovery)) } @@ -170,17 +172,17 @@ func TestDiscover_ConcurrentAccess(t *testing.T) { })) defer srv.Close() - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() var wg sync.WaitGroup - results := make([]*providerConfig, 10) + results := make([]*oidcclient.ProviderConfig, 10) errs := make([]error, 10) for i := range 10 { wg.Add(1) go func(idx int) { defer wg.Done() - results[idx], errs[idx] = discover(context.Background(), srv.URL) + results[idx], errs[idx] = oidcclient.Discover(context.Background(), srv.URL) }(i) } wg.Wait() @@ -208,9 +210,9 @@ func TestDiscover_NoDeviceEndpointIsOK(t *testing.T) { })) defer srv.Close() - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() - cfg, err := discover(context.Background(), srv.URL) + cfg, err := oidcclient.Discover(context.Background(), srv.URL) require.NoError(t, err) assert.Empty(t, cfg.DeviceAuthorizationEndpoint) } @@ -225,13 +227,13 @@ func TestDiscover_TrailingSlashNormalized(t *testing.T) { })) defer srv.Close() - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() // Call with trailing slash and without; should be same cache entry. - _, err := discover(context.Background(), srv.URL) + _, err := oidcclient.Discover(context.Background(), srv.URL) require.NoError(t, err) - _, err = discover(context.Background(), srv.URL+"/") + _, err = oidcclient.Discover(context.Background(), srv.URL+"/") require.NoError(t, err) assert.Equal(t, 1, callCount, "trailing slash should be normalized for caching") @@ -242,9 +244,9 @@ func TestDiscover_RejectsIssuerMismatch(t *testing.T) { _, _ = w.Write([]byte(wellKnownJSON("https://attacker.example"))) })) defer srv.Close() - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() - _, err := discover(context.Background(), srv.URL) + _, err := oidcclient.Discover(context.Background(), srv.URL) require.Error(t, err) assert.Contains(t, err.Error(), "issuer") } @@ -255,9 +257,9 @@ func TestDiscover_RejectsInsecureRemoteEndpoint(t *testing.T) { _, _ = w.Write([]byte(`{"issuer":"` + srv.URL + `","authorization_endpoint":"http://example.com/authorize","token_endpoint":"` + srv.URL + `/token"}`)) })) defer srv.Close() - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() - _, err := discover(context.Background(), srv.URL) + _, err := oidcclient.Discover(context.Background(), srv.URL) require.Error(t, err) assert.Contains(t, err.Error(), "authorization_endpoint") } diff --git a/openshell/v1/oidc/errors.go b/openshell/v1/oidc/errors.go index ffdc150..76d74f1 100644 --- a/openshell/v1/oidc/errors.go +++ b/openshell/v1/oidc/errors.go @@ -3,14 +3,18 @@ package oidc -import "errors" +import ( + "errors" + + "github.com/ai-openshell/sdk-go/openshell/v1/internal/oidcclient" +) // Sentinel errors for OIDC authentication failures. All wrapped errors // returned by this package support classification via [errors.Is]. var ( // ErrDiscovery is returned when the OIDC discovery document // (.well-known/openid-configuration) cannot be fetched or parsed. - ErrDiscovery = errors.New("oidc: discovery failed") + ErrDiscovery = oidcclient.ErrDiscovery // ErrAuthCode is returned when the authorization code exchange // fails (invalid code, expired code, provider error). @@ -28,7 +32,9 @@ var ( // ErrTimeout is returned when an interactive login flow // (browser, keyboard, or device code) exceeds its deadline, or when // the context ends while Login refreshes a stored token. In the - // refresh case the error also wraps the context's error. + // refresh case the error also wraps the context's error, and if the + // token request had reached a provider that rotates refresh tokens, + // the stored refresh token may no longer work. ErrTimeout = errors.New("oidc: login timed out") // ErrCallbackServer is returned when the localhost HTTP server @@ -37,7 +43,7 @@ var ( // ErrTokenPersist is returned when the token cannot be written // to disk (permission error, invalid path). - ErrTokenPersist = errors.New("oidc: token persistence failed") + ErrTokenPersist = oidcclient.ErrTokenPersist // ErrOIDCConfig is returned when gateway metadata is missing // the required oidc_issuer or oidc_client_id fields. diff --git a/openshell/v1/oidc/oidc.go b/openshell/v1/oidc/oidc.go index f281ca1..4177a34 100644 --- a/openshell/v1/oidc/oidc.go +++ b/openshell/v1/oidc/oidc.go @@ -15,6 +15,8 @@ import ( "github.com/ai-openshell/sdk-go/openshell/v1/gateway" "github.com/ai-openshell/sdk-go/openshell/v1/internal/oidctoken" "github.com/ai-openshell/sdk-go/openshell/v1/internal/options" + + "github.com/ai-openshell/sdk-go/openshell/v1/internal/oidcclient" ) // Login performs an interactive OIDC authorization code login. @@ -34,6 +36,9 @@ import ( // exchanges the refresh token for a new one and rewrites the file. If the // context ends, discovery fails, or the file cannot be written, Login // returns the error; if the refresh fails for any other reason, it runs +// the interactive flow. If ctx ends after the token request reached the +// provider, a provider that rotates refresh tokens may already have +// revoked the stored one; the next Login then gets invalid_grant and runs // the interactive flow. [WithInMemory] skips the refresh, because a // rotated refresh token would not be written back. // @@ -64,7 +69,7 @@ func Login(ctx context.Context, gatewayName string, opts ...LoginOption) (*oauth // FR-019: Check for existing valid token on disk before starting // an interactive flow. if tokenDir != "" { - stored, readErr := readToken(tokenDir) + stored, readErr := oidcclient.ReadToken(tokenDir) if readErr == nil && stored != nil && sameClient(stored, cfg) { if tok := stored.Token(); tok.Valid() { return tok, nil @@ -83,7 +88,7 @@ func Login(ctx context.Context, gatewayName string, opts ...LoginOption) (*oauth } // Run OIDC discovery to get provider endpoints. - provider, err := discover(ctx, cfg.issuer) + provider, err := oidcclient.Discover(ctx, cfg.issuer) if err != nil { return nil, err } @@ -126,7 +131,7 @@ func Login(ctx context.Context, gatewayName string, opts ...LoginOption) (*oauth // Persist token to disk unless in-memory mode is requested. if !cfg.inMemory && tokenDir != "" { - if writeErr := writeToken(tokenDir, oidctoken.FromToken(tok, cfg.issuer, cfg.clientID)); writeErr != nil { + if writeErr := oidcclient.WriteToken(tokenDir, oidctoken.FromToken(tok, cfg.issuer, cfg.clientID)); writeErr != nil { return nil, writeErr } } @@ -170,13 +175,13 @@ func resolveOIDCConfig(cfg *loginConfig, gatewayName string) (string, error) { } // supportsS256 checks if the OIDC provider advertises S256 PKCE support. -func supportsS256(provider *providerConfig) bool { +func supportsS256(provider *oidcclient.ProviderConfig) bool { return slices.Contains(provider.CodeChallengeMethodsSupported, "S256") } // loginKeyboard performs the keyboard flow: builds the auth URL, shows // it to the user, and reads the pasted authorization code. -func loginKeyboard(ctx context.Context, cfg *loginConfig, provider *providerConfig, state, challenge string) (string, error) { +func loginKeyboard(ctx context.Context, cfg *loginConfig, provider *oidcclient.ProviderConfig, state, challenge string) (string, error) { redirectURI := "urn:ietf:wg:oauth:2.0:oob" authURL := buildAuthURL(provider.AuthorizationEndpoint, cfg.clientID, redirectURI, state, challenge, cfg.scopes) @@ -200,7 +205,7 @@ func loginKeyboard(ctx context.Context, cfg *loginConfig, provider *providerConf // exchangeCode so that it exactly matches the URI used in the auth // request. When the function falls back to keyboard flow, the returned // redirectURI is the keyboard placeholder ("urn:ietf:wg:oauth:2.0:oob"). -func loginBrowser(ctx context.Context, cfg *loginConfig, provider *providerConfig, state, challenge string) (string, string, error) { +func loginBrowser(ctx context.Context, cfg *loginConfig, provider *oidcclient.ProviderConfig, state, challenge string) (string, string, error) { port := cfg.callbackPort if port == 0 { port = 8000 diff --git a/openshell/v1/oidc/oidc_test.go b/openshell/v1/oidc/oidc_test.go index 55aca8a..e07bfcc 100644 --- a/openshell/v1/oidc/oidc_test.go +++ b/openshell/v1/oidc/oidc_test.go @@ -24,6 +24,8 @@ import ( "github.com/ai-openshell/sdk-go/openshell/v1/gateway" "github.com/ai-openshell/sdk-go/openshell/v1/internal/oidctoken" + + "github.com/ai-openshell/sdk-go/openshell/v1/internal/oidcclient" ) // --- T021: Login entry point tests --- @@ -63,7 +65,7 @@ func setupMockProvider(t *testing.T) *httptest.Server { // TestLogin_MissingOIDCConfig verifies that Login returns ErrOIDCConfig // when called without a gateway name and without WithIssuer/WithClientID. func TestLogin_MissingOIDCConfig(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() _, err := Login(context.Background(), "") require.Error(t, err) @@ -73,7 +75,7 @@ func TestLogin_MissingOIDCConfig(t *testing.T) { // TestLogin_MissingIssuer verifies that Login returns ErrOIDCConfig // when only WithClientID is provided (missing issuer). func TestLogin_MissingIssuer(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() _, err := Login(context.Background(), "", WithClientID("test-client")) require.Error(t, err) @@ -83,7 +85,7 @@ func TestLogin_MissingIssuer(t *testing.T) { // TestLogin_MissingClientID verifies that Login returns ErrOIDCConfig // when only WithIssuer is provided (missing client ID). func TestLogin_MissingClientID(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() _, err := Login(context.Background(), "", WithIssuer("https://example.com")) require.Error(t, err) @@ -94,7 +96,7 @@ func TestLogin_MissingClientID(t *testing.T) { // same issuer (ignoring a trailing slash) and client ID exists on disk, // Login returns it without starting an interactive flow. func TestLogin_ReusesValidToken(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() // Create a temp dir with a valid, non-expired token file. tokenDir := t.TempDir() @@ -104,7 +106,7 @@ func TestLogin_ReusesValidToken(t *testing.T) { TokenType: "Bearer", Expiry: time.Now().Add(1 * time.Hour), } - err := writeToken(tokenDir, oidctoken.FromToken(existingToken, + err := oidcclient.WriteToken(tokenDir, oidctoken.FromToken(existingToken, "https://issuer-should-not-be-called.example.com/", "test-client")) require.NoError(t, err) @@ -126,7 +128,7 @@ func TestLogin_ReusesValidToken(t *testing.T) { // the interactive flow. Since we use keyboard flow (no browser), we feed // it a code and verify a new token is returned. func TestLogin_ExpiredTokenTriggersFlow(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() provider := setupMockProvider(t) tokenDir := t.TempDir() @@ -137,7 +139,7 @@ func TestLogin_ExpiredTokenTriggersFlow(t *testing.T) { TokenType: "Bearer", Expiry: time.Now().Add(-1 * time.Hour), // expired } - err := writeToken(tokenDir, oidctoken.FromToken(expiredToken, provider.URL, "test-client")) + err := oidcclient.WriteToken(tokenDir, oidctoken.FromToken(expiredToken, provider.URL, "test-client")) require.NoError(t, err) // Start a callback server ourselves to simulate the auth code callback. @@ -166,7 +168,7 @@ func TestLogin_ExpiredTokenTriggersFlow(t *testing.T) { // SDK build, is not reused: Login runs the flow and rewrites the file in // the CLI format. func TestLogin_ReplacesMismatchedStoredToken(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() provider := setupMockProvider(t) expiresAt := fmt.Sprint(time.Now().Add(time.Hour).Unix()) @@ -198,7 +200,7 @@ func TestLogin_ReplacesMismatchedStoredToken(t *testing.T) { require.NoError(t, err) assert.Equal(t, "login-access-token", tok.AccessToken) - diskTok, err := readToken(tokenDir) + diskTok, err := oidcclient.ReadToken(tokenDir) require.NoError(t, err) require.NotNil(t, diskTok) assert.Equal(t, "login-access-token", diskTok.AccessToken) @@ -212,7 +214,7 @@ func TestLogin_ReplacesMismatchedStoredToken(t *testing.T) { // keyboard flow when WithKeyboardFlow() is set. The test provides a // mock OIDC provider and feeds an auth code through a reader. func TestLogin_KeyboardFlow(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() provider := setupMockProvider(t) tokenDir := t.TempDir() @@ -233,7 +235,7 @@ func TestLogin_KeyboardFlow(t *testing.T) { assert.Equal(t, "login-access-token", tok.AccessToken) // Verify token was persisted to disk. - diskTok, err := readToken(tokenDir) + diskTok, err := oidcclient.ReadToken(tokenDir) require.NoError(t, err) require.NotNil(t, diskTok) assert.Equal(t, "login-access-token", diskTok.AccessToken) @@ -267,7 +269,7 @@ func TestLogin_AlwaysRequestsOpenIDScope(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() provider := setupMockProvider(t) var prompt strings.Builder @@ -329,7 +331,7 @@ func TestLogin_GatewayScopes(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() provider := setupMockProvider(t) var prompt strings.Builder @@ -379,7 +381,7 @@ func extractAuthURL(t *testing.T, prompt string) *url.URL { // TestLogin_InMemorySkipsPersistence verifies that WithInMemory() // returns a token without writing to disk. func TestLogin_InMemorySkipsPersistence(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() provider := setupMockProvider(t) tokenDir := t.TempDir() @@ -408,7 +410,7 @@ func TestLogin_InMemorySkipsPersistence(t *testing.T) { // TestLogin_DiscoveryFailure verifies that Login returns ErrDiscovery // when the OIDC provider is unreachable. func TestLogin_DiscoveryFailure(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() // Point to a server that doesn't exist. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) @@ -427,7 +429,7 @@ func TestLogin_DiscoveryFailure(t *testing.T) { // from gateway metadata when a gateway name is provided. We use the // withGatewayResolver option to inject a fake gateway loader. func TestLogin_GatewayResolution(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() provider := setupMockProvider(t) tokenDir := t.TempDir() @@ -457,7 +459,7 @@ func TestLogin_GatewayResolution(t *testing.T) { assert.Equal(t, "login-access-token", tok.AccessToken) // Verify token was persisted in the gateway dir. - diskTok, err := readToken(tokenDir) + diskTok, err := oidcclient.ReadToken(tokenDir) require.NoError(t, err) require.NotNil(t, diskTok) assert.Equal(t, "login-access-token", diskTok.AccessToken) @@ -468,7 +470,7 @@ func TestLogin_GatewayResolution(t *testing.T) { // TestLogin_GatewayMissingOIDCFields verifies that Login returns // ErrOIDCConfig when the gateway config has empty OIDC fields. func TestLogin_GatewayMissingOIDCFields(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() fakeConfig := &gateway.Config{ Name: "no-oidc-gw", @@ -489,7 +491,7 @@ func TestLogin_GatewayMissingOIDCFields(t *testing.T) { // TestLogin_GatewayResolutionError verifies that Login propagates // errors from gateway resolution. func TestLogin_GatewayResolutionError(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() gwErr := fmt.Errorf("gateway not found: no-such-gateway") @@ -505,7 +507,7 @@ func TestLogin_GatewayResolutionError(t *testing.T) { // TestLogin_NoPKCESupport verifies that Login proceeds without PKCE // when the OIDC provider does not advertise S256 support. func TestLogin_NoPKCESupport(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() // Create a provider that does NOT list S256 in supported methods. mux := http.NewServeMux() @@ -556,7 +558,7 @@ func TestLogin_NoPKCESupport(t *testing.T) { // TestLogin_ContextCancellation verifies that Login respects context // cancellation during the interactive flow. func TestLogin_ContextCancellation(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() provider := setupMockProvider(t) @@ -580,7 +582,7 @@ func TestLogin_ContextCancellation(t *testing.T) { // TestLogin_CustomScopes verifies that WithScopes overrides the // default scopes sent in the authorization request. func TestLogin_CustomScopes(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() // Provider that captures the auth URL scope parameter. mux := http.NewServeMux() @@ -627,7 +629,7 @@ func TestLogin_CustomScopes(t *testing.T) { // loginBrowser falls back to keyboard flow when the callback server // port is already occupied and no custom port is set. func TestLoginBrowser_PortBusy_FallbackToKeyboard(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() provider := setupMockProvider(t) @@ -666,7 +668,7 @@ func TestLoginBrowser_PortBusy_FallbackToKeyboard(t *testing.T) { // TestLogin_ContextTimeout verifies that a Login with a very short // timeout returns a timeout-related error. func TestLogin_ContextTimeout(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() provider := setupMockProvider(t) diff --git a/openshell/v1/oidc/oidcclient.go b/openshell/v1/oidc/oidcclient.go new file mode 100644 index 0000000..7821ea0 --- /dev/null +++ b/openshell/v1/oidc/oidcclient.go @@ -0,0 +1,78 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package oidc + +import ( + "context" + "errors" + "fmt" + + "golang.org/x/oauth2" + + "github.com/ai-openshell/sdk-go/openshell/v1/internal/oidcclient" + "github.com/ai-openshell/sdk-go/openshell/v1/internal/oidctoken" +) + +// refreshStoredToken renews an expired stored token with its refresh token +// and rewrites the file (see [oidcclient.Refresh]). It returns a nil token +// and nil error when Login should run the interactive flow instead, and an +// error when Login should stop: the context is done, discovery failed, or +// the new token could not be written. The stored argument only decides +// whether to try; the file read under the lock is what gets refreshed. +// +// In-memory mode does not refresh, since a rotated refresh token that is +// not written back would leave the file holding a revoked one. +func refreshStoredToken(ctx context.Context, cfg *loginConfig, tokenDir string, stored oidctoken.Bundle) (*oauth2.Token, error) { + if cfg.inMemory || stored.RefreshToken == "" { + return nil, nil + } + + // Refresh with the scopes the authorization request uses (openid + // first) when they were set explicitly or by the gateway's + // oidc_scopes; with the built-in defaults, omit scope so the provider + // keeps the original grant. + var scopes []string + if cfg.scopesSet { + scopes = cfg.scopes + } + + res, err := oidcclient.Refresh(ctx, oidcclient.Request{ + Dir: tokenDir, + Issuer: cfg.issuer, + ClientID: cfg.clientID, + Scopes: scopes, + Window: oidcclient.LoginRefreshWindow, + }) + if err != nil { + return nil, loginRefreshError(ctx, err) + } + return res.Token, nil +} + +// loginRefreshError decides what Login does with a failed refresh. It +// returns nil when Login should run the interactive flow: there was +// nothing to refresh, or the refresh failed while ctx was still live. +// Otherwise it returns the error Login reports: the write error, even if +// ctx has also ended; ErrTimeout wrapping ctx's error; or the discovery +// error. +func loginRefreshError(ctx context.Context, err error) error { + switch { + case errors.Is(err, oidcclient.ErrNotRefreshable): + return nil + case errors.Is(err, ErrTokenPersist): + return err + case ctx.Err() != nil: + return fmt.Errorf("%w: %w", ErrTimeout, ctx.Err()) + case errors.Is(err, ErrDiscovery): + return err + default: + return nil + } +} + +// sameClient reports whether a stored bundle was issued for the configured +// issuer (ignoring a trailing slash) and client ID. +func sameClient(b *oidctoken.Bundle, cfg *loginConfig) bool { + return oidcclient.SameClient(b, cfg.issuer, cfg.clientID) +} diff --git a/openshell/v1/oidc/options.go b/openshell/v1/oidc/options.go index e4f64f5..4b8b72f 100644 --- a/openshell/v1/oidc/options.go +++ b/openshell/v1/oidc/options.go @@ -10,6 +10,7 @@ import ( "time" "github.com/ai-openshell/sdk-go/openshell/v1/gateway" + "github.com/ai-openshell/sdk-go/openshell/v1/internal/oidcclient" ) // scopeOpenID is the scope that turns an OAuth2 authorization request into @@ -90,14 +91,7 @@ func (c *loginConfig) applyGatewayScopes(gw *gateway.Config) { // // This mirrors build_scopes in crates/openshell-cli/src/oidc_auth.rs. func (c *loginConfig) requireOpenIDScope() { - normalized := make([]string, 0, len(c.scopes)+1) - normalized = append(normalized, scopeOpenID) - for _, scope := range c.scopes { - if scope != scopeOpenID { - normalized = append(normalized, scope) - } - } - c.scopes = normalized + c.scopes = oidcclient.ScopesWithOpenID(c.scopes) } // LoginOption configures a login attempt. Use the With* functions to diff --git a/openshell/v1/oidc/refresh.go b/openshell/v1/oidc/refresh.go deleted file mode 100644 index 59e56de..0000000 --- a/openshell/v1/oidc/refresh.go +++ /dev/null @@ -1,236 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -package oidc - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "io" - "net/http" - "net/url" - "path/filepath" - "strings" - "sync" - "time" - - "golang.org/x/oauth2" - - "github.com/ai-openshell/sdk-go/openshell/v1/internal/oidctoken" -) - -var ( - // errTokenRefresh is returned when a refresh_token grant fails. Login - // does not surface it: a failed refresh falls back to the interactive - // flow. - errTokenRefresh = errors.New("oidc: token refresh failed") - - // errInvalidGrant marks a refresh rejected with invalid_grant. The - // refresh token has expired or been revoked, or another process has - // already used it. - errInvalidGrant = errors.New("oidc: invalid_grant") -) - -// refreshLocks serializes refreshes of one token file within the process, -// so concurrent Login calls do not spend the same refresh token twice. It -// maps each absolute token directory to a one-slot semaphore and keeps one -// entry per directory ever refreshed, which is a handful of gateways in -// practice. -var refreshLocks sync.Map - -// lockTokenDir waits for the refresh lock of dir until ctx ends, and -// returns the function that releases it. -func lockTokenDir(ctx context.Context, dir string) (func(), error) { - key := filepath.Clean(dir) - if abs, err := filepath.Abs(key); err == nil { - key = abs - } - slot, _ := refreshLocks.LoadOrStore(key, make(chan struct{}, 1)) - sem := slot.(chan struct{}) - if err := ctx.Err(); err != nil { - return nil, fmt.Errorf("%w: %w", ErrTimeout, err) - } - select { - case sem <- struct{}{}: - return func() { <-sem }, nil - case <-ctx.Done(): - return nil, fmt.Errorf("%w: %w", ErrTimeout, ctx.Err()) - } -} - -// refreshStoredToken renews an expired stored token with its refresh token -// and rewrites the file. It returns a nil token and nil error when Login -// should run the interactive flow instead, and an error when Login should -// stop: the context is done, discovery failed, or the new token could not -// be written. -// -// The file is shared with the CLI, and providers that rotate refresh -// tokens revoke the old one on use. Under a per-directory lock the file is -// read again first, so a token another process or goroutine has just -// refreshed is used as is. When the refresh is rejected with invalid_grant, -// the file is read once more: a valid token another process wrote for the -// same issuer and client is used as is, and an expired one with a -// different refresh token is refreshed once with that token. Like the -// Python SDK, it takes no file lock across processes. The stored argument -// only decides whether to try; the file read under the lock is what gets -// refreshed. -// -// In-memory mode does not refresh, since a rotated refresh token that is -// not written back would leave the file holding a revoked one. If the -// write fails after a rotation, the error is returned and the file keeps -// the old refresh token, as with the CLI. -func refreshStoredToken(ctx context.Context, cfg *loginConfig, tokenDir string, stored oidctoken.Bundle) (*oauth2.Token, error) { - if cfg.inMemory || stored.RefreshToken == "" { - return nil, nil - } - - unlock, err := lockTokenDir(ctx, tokenDir) - if err != nil { - return nil, err - } - defer unlock() - - current, err := readToken(tokenDir) - if err != nil || current == nil || !sameClient(current, cfg) { - return nil, nil - } - if tok := current.Token(); tok.Valid() { - return tok, nil - } - if current.RefreshToken == "" { - return nil, nil - } - stored = *current - - provider, err := discover(ctx, cfg.issuer) - if err != nil { - if ctxErr := ctx.Err(); ctxErr != nil { - return nil, fmt.Errorf("%w: %w", ErrTimeout, ctxErr) - } - return nil, err - } - - // Refresh with the scopes the authorization request uses (openid - // first) when they were set explicitly or by the gateway's - // oidc_scopes; with the built-in defaults, omit scope so the provider - // keeps the original grant. - var scopes []string - if cfg.scopesSet { - scopes = cfg.scopes - } - - tok, err := refreshToken(ctx, provider.TokenEndpoint, cfg.clientID, stored.RefreshToken, scopes) - if errors.Is(err, errInvalidGrant) { - peer, readErr := readToken(tokenDir) - if readErr != nil || peer == nil || !sameClient(peer, cfg) { - return nil, nil - } - if peerTok := peer.Token(); peerTok.Valid() { - return peerTok, nil - } - if peer.RefreshToken == "" || peer.RefreshToken == stored.RefreshToken { - return nil, nil - } - stored = *peer - tok, err = refreshToken(ctx, provider.TokenEndpoint, cfg.clientID, stored.RefreshToken, scopes) - } - if err != nil { - if ctxErr := ctx.Err(); ctxErr != nil { - return nil, fmt.Errorf("%w: %w", ErrTimeout, ctxErr) - } - return nil, nil - } - - // Providers that do not rotate refresh tokens omit one from the - // response; keep the stored token so the next refresh still works. - if tok.RefreshToken == "" { - tok.RefreshToken = stored.RefreshToken - } - - b := oidctoken.FromToken(tok, stored.Issuer, stored.ClientID) - b.ClientCredentials = stored.ClientCredentials - if err := writeToken(tokenDir, b); err != nil { - return nil, err - } - return tok, nil -} - -// sameClient reports whether a stored bundle was issued for the configured -// issuer (ignoring a trailing slash) and client ID. -func sameClient(b *oidctoken.Bundle, cfg *loginConfig) bool { - return normalizeIssuer(b.Issuer) == normalizeIssuer(cfg.issuer) && b.ClientID == cfg.clientID -} - -// refreshToken exchanges a refresh token for new tokens at the token -// endpoint (RFC 6749 Section 6). Like the CLI, it sends grant_type, -// refresh_token and client_id as a public client, plus scope when scopes -// are given. -// -// The refresh token is never included in error messages. -func refreshToken(ctx context.Context, tokenEndpoint, clientID, refresh string, scopes []string) (*oauth2.Token, error) { - data := url.Values{ - "grant_type": {"refresh_token"}, - "refresh_token": {refresh}, - "client_id": {clientID}, - } - if len(scopes) > 0 { - data.Set("scope", strings.Join(scopes, " ")) - } - - req, err := http.NewRequestWithContext(ctx, http.MethodPost, tokenEndpoint, strings.NewReader(data.Encode())) - if err != nil { - return nil, fmt.Errorf("%w: failed to create token request: %v", errTokenRefresh, err) - } - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - - resp, err := oidcHTTPClient.Do(req) - if err != nil { - return nil, fmt.Errorf("%w: token request failed: %v", errTokenRefresh, err) - } - defer func() { _ = resp.Body.Close() }() - - const maxResponseBytes = 1 << 20 - body, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBytes)) - if err != nil { - return nil, fmt.Errorf("%w: failed to read token response: %v", errTokenRefresh, err) - } - - var tokResp tokenResponse - if err := json.Unmarshal(body, &tokResp); err != nil { - return nil, fmt.Errorf("%w: invalid token response JSON: %v", errTokenRefresh, err) - } - - if tokResp.Error == "invalid_grant" { - return nil, fmt.Errorf("%w: %w", errTokenRefresh, errInvalidGrant) - } - if tokResp.Error != "" { - return nil, fmt.Errorf("%w: %s", errTokenRefresh, tokResp.Error) - } - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("%w: HTTP %d", errTokenRefresh, resp.StatusCode) - } - if tokResp.AccessToken == "" { - return nil, fmt.Errorf("%w: token response has no access_token", errTokenRefresh) - } - - // An absent expires_in leaves the token without an expiry, as the code - // exchange does. A present expires_in must be positive; zero or a - // negative value is rejected as malformed. - var fields map[string]json.RawMessage - _ = json.Unmarshal(body, &fields) - if _, present := fields["expires_in"]; present && tokResp.ExpiresIn <= 0 { - return nil, fmt.Errorf("%w: token response requires a positive expires_in", errTokenRefresh) - } - - tok := &oauth2.Token{ - AccessToken: tokResp.AccessToken, - RefreshToken: tokResp.RefreshToken, - TokenType: tokResp.TokenType, - } - if tokResp.ExpiresIn > 0 { - tok.Expiry = time.Now().Add(time.Duration(tokResp.ExpiresIn) * time.Second) - } - return tok, nil -} diff --git a/openshell/v1/oidc/refresh_test.go b/openshell/v1/oidc/refresh_test.go index 255dbc9..cd884d0 100644 --- a/openshell/v1/oidc/refresh_test.go +++ b/openshell/v1/oidc/refresh_test.go @@ -7,7 +7,7 @@ import ( "bytes" "context" "encoding/json" - "errors" + "fmt" "net/http" "net/http/httptest" "net/url" @@ -16,7 +16,6 @@ import ( "runtime" "strings" "sync" - "syscall" "testing" "time" @@ -25,6 +24,7 @@ import ( "golang.org/x/oauth2" "github.com/ai-openshell/sdk-go/openshell/v1/gateway" + "github.com/ai-openshell/sdk-go/openshell/v1/internal/oidcclient" "github.com/ai-openshell/sdk-go/openshell/v1/internal/oidctoken" ) @@ -93,14 +93,14 @@ const invalidGrantJSON = `{"error":"invalid_grant","error_description":"refresh func writeStoredToken(t *testing.T, dir, issuer string, tok *oauth2.Token) { t.Helper() - require.NoError(t, writeToken(dir, oidctoken.FromToken(tok, issuer, "test-client"))) + require.NoError(t, oidcclient.WriteToken(dir, oidctoken.FromToken(tok, issuer, "test-client"))) } // writeStoredTokenFromHandler writes a token from an HTTP handler, where // require must not be used. func writeStoredTokenFromHandler(t *testing.T, dir, issuer string, tok *oauth2.Token) { t.Helper() - if err := writeToken(dir, oidctoken.FromToken(tok, issuer, "test-client")); err != nil { + if err := oidcclient.WriteToken(dir, oidctoken.FromToken(tok, issuer, "test-client")); err != nil { t.Errorf("write peer token: %v", err) } } @@ -150,7 +150,7 @@ func loginNoPromptCtx(ctx context.Context, issuer, dir string, opts ...LoginOpti // stored token with its refresh token, without prompting, and rewrites the // file in the CLI format (NVIDIA/OpenShell#4514). func TestLogin_RefreshesExpiredToken(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() provider := newRefreshProvider(t, refreshed) dir := t.TempDir() writeStoredToken(t, dir, provider.URL, expiredToken("still-good")) @@ -179,7 +179,7 @@ func TestLogin_RefreshesExpiredToken(t *testing.T) { // TestLogin_RefreshKeepsRefreshTokenWhenNotRotated verifies that a // provider response without a refresh token keeps the stored one. func TestLogin_RefreshKeepsRefreshTokenWhenNotRotated(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() provider := newRefreshProvider(t, func(url.Values) (int, string) { return http.StatusOK, `{"access_token":"refreshed-access-token","token_type":"Bearer","expires_in":3600}` }) @@ -196,7 +196,7 @@ func TestLogin_RefreshKeepsRefreshTokenWhenNotRotated(t *testing.T) { // WithScopes are sent on refresh, normalized with openid first as in the // authorization request. func TestLogin_RefreshSendsConfiguredScopes(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() provider := newRefreshProvider(t, refreshed) dir := t.TempDir() writeStoredToken(t, dir, provider.URL, expiredToken("still-good")) @@ -210,7 +210,7 @@ func TestLogin_RefreshSendsConfiguredScopes(t *testing.T) { // refresh token was already used by another process, Login re-reads the // file and returns the peer's valid token without a second request. func TestLogin_RefreshInvalidGrantUsesPeerToken(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() dir := t.TempDir() var provider *refreshProvider provider = newRefreshProvider(t, func(url.Values) (int, string) { @@ -236,7 +236,7 @@ func TestLogin_RefreshInvalidGrantUsesPeerToken(t *testing.T) { // Login retries once with a different refresh token found on disk when // the peer's access token has also expired. func TestLogin_RefreshInvalidGrantRetriesWithPeerRefreshToken(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() dir := t.TempDir() var provider *refreshProvider provider = newRefreshProvider(t, func(form url.Values) (int, string) { @@ -260,7 +260,7 @@ func TestLogin_RefreshInvalidGrantRetriesWithPeerRefreshToken(t *testing.T) { // TestLogin_RefreshFailureFallsBackToFlow verifies that a rejected refresh // with no newer token on disk falls back to the interactive flow. func TestLogin_RefreshFailureFallsBackToFlow(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() provider := newRefreshProvider(t, func(form url.Values) (int, string) { if form.Get("grant_type") == "refresh_token" { return http.StatusBadRequest, invalidGrantJSON @@ -290,7 +290,7 @@ func TestLogin_RefreshFailureFallsBackToFlow(t *testing.T) { // interactive flow without refreshing: a rotated refresh token would not be // written back, and the file would keep a revoked one. func TestLogin_InMemoryDoesNotRefresh(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() provider := newRefreshProvider(t, refreshed) dir := t.TempDir() writeStoredToken(t, dir, provider.URL, expiredToken("still-good")) @@ -315,12 +315,12 @@ func TestLogin_InMemoryDoesNotRefresh(t *testing.T) { // TestLogin_RefreshKeepsClientCredentialsMarker verifies that rewriting the // file after a refresh keeps the CLI's client_credentials marker. func TestLogin_RefreshKeepsClientCredentialsMarker(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() provider := newRefreshProvider(t, refreshed) dir := t.TempDir() b := oidctoken.FromToken(expiredToken("still-good"), provider.URL, "test-client") b.ClientCredentials = true - require.NoError(t, writeToken(dir, b)) + require.NoError(t, oidcclient.WriteToken(dir, b)) _, _, err := loginNoPrompt(t, provider.URL, dir) require.NoError(t, err) @@ -335,7 +335,7 @@ func TestLogin_RefreshPersistFailure(t *testing.T) { if runtime.GOOS == "windows" || os.Geteuid() == 0 { t.Skip("needs a read-only directory") } - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() provider := newRefreshProvider(t, refreshed) dir := t.TempDir() writeStoredToken(t, dir, provider.URL, expiredToken("still-good")) @@ -345,13 +345,14 @@ func TestLogin_RefreshPersistFailure(t *testing.T) { tok, _, err := loginNoPrompt(t, provider.URL, dir) require.ErrorIs(t, err, ErrTokenPersist) assert.Nil(t, tok) + assert.Empty(t, provider.grants(), "the refresh token is not spent when it cannot be stored") assert.Equal(t, "still-good", readStoredBundle(t, dir).RefreshToken) } // TestLogin_RefreshUsesGatewayScopes verifies that the gateway's // oidc_scopes from metadata.json are sent on refresh. func TestLogin_RefreshUsesGatewayScopes(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() provider := newRefreshProvider(t, refreshed) dir := t.TempDir() writeStoredToken(t, dir, provider.URL, expiredToken("still-good")) @@ -380,7 +381,7 @@ func TestLogin_RefreshUsesGatewayScopes(t *testing.T) { // TestLogin_RefreshInvalidGrantIgnoresPeerForOtherClient verifies that a // token written for another client is never returned or refreshed. func TestLogin_RefreshInvalidGrantIgnoresPeerForOtherClient(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() dir := t.TempDir() var provider *refreshProvider provider = newRefreshProvider(t, func(form url.Values) (int, string) { @@ -392,7 +393,7 @@ func TestLogin_RefreshInvalidGrantIgnoresPeerForOtherClient(t *testing.T) { RefreshToken: "other-client-refresh-token", Expiry: time.Now().Add(time.Hour), }, provider.URL, "other-client") - if err := writeToken(dir, peer); err != nil { + if err := oidcclient.WriteToken(dir, peer); err != nil { t.Errorf("write peer token: %v", err) } return http.StatusBadRequest, invalidGrantJSON @@ -424,7 +425,7 @@ func TestLogin_RefreshRejectsUnusableResponses(t *testing.T) { "negative lifetime": `{"access_token":"a","token_type":"Bearer","expires_in":-5}`, } { t.Run(name, func(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() provider := newRefreshProvider(t, func(form url.Values) (int, string) { if form.Get("grant_type") == "refresh_token" { return http.StatusOK, body @@ -455,7 +456,7 @@ func TestLogin_RefreshRejectsUnusableResponses(t *testing.T) { // keeps the issuer exactly as stored, so a trailing slash written by the // CLI survives. func TestLogin_RefreshKeepsStoredIssuerForm(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() provider := newRefreshProvider(t, refreshed) dir := t.TempDir() writeStoredToken(t, dir, provider.URL+"/", expiredToken("still-good")) @@ -468,7 +469,7 @@ func TestLogin_RefreshKeepsStoredIssuerForm(t *testing.T) { // TestLogin_RefreshDiscoveryFailure verifies that Login reports a discovery // failure after a single discovery request and without prompting. func TestLogin_RefreshDiscoveryFailure(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() var discoveries sync.Mutex calls := 0 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { @@ -492,7 +493,7 @@ func TestLogin_RefreshDiscoveryFailure(t *testing.T) { // TestLogin_RefreshContextDeadline verifies that a refresh cut short by the // caller's deadline returns ErrTimeout and does not start the flow. func TestLogin_RefreshContextDeadline(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() provider := newRefreshProvider(t, func(form url.Values) (int, string) { time.Sleep(300 * time.Millisecond) return refreshed(form) @@ -500,7 +501,7 @@ func TestLogin_RefreshContextDeadline(t *testing.T) { dir := t.TempDir() writeStoredToken(t, dir, provider.URL, expiredToken("still-good")) // Warm the discovery cache so the deadline falls inside the refresh. - _, err := discover(context.Background(), provider.URL) + _, err := oidcclient.Discover(context.Background(), provider.URL) require.NoError(t, err) ctx, cancel := context.WithTimeout(context.Background(), 150*time.Millisecond) @@ -516,7 +517,7 @@ func TestLogin_RefreshContextDeadline(t *testing.T) { // re-read the file and use the token the first one wrote. The mock // provider rejects a reused refresh token, as a rotating provider does. func TestLogin_ConcurrentRefreshSpendsRefreshTokenOnce(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() var used sync.Map provider := newRefreshProvider(t, func(form url.Values) (int, string) { if _, spent := used.LoadOrStore(form.Get("refresh_token"), true); spent { @@ -554,7 +555,7 @@ func TestLogin_ConcurrentRefreshSpendsRefreshTokenOnce(t *testing.T) { // TestLogin_RefreshDiscoveryDeadline verifies that a deadline reached // during discovery for the refresh returns ErrTimeout without prompting. func TestLogin_RefreshDiscoveryDeadline(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { select { case <-time.After(300 * time.Millisecond): @@ -578,7 +579,7 @@ func TestLogin_RefreshDiscoveryDeadline(t *testing.T) { // that a valid token another process wrote is used even when it carries no // refresh token. func TestLogin_RefreshInvalidGrantUsesPeerTokenWithoutRefreshToken(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() dir := t.TempDir() var provider *refreshProvider provider = newRefreshProvider(t, func(url.Values) (int, string) { @@ -601,7 +602,7 @@ func TestLogin_RefreshInvalidGrantUsesPeerTokenWithoutRefreshToken(t *testing.T) // context gets ErrTimeout wrapping context.Canceled, with no prompt and no // change to the file. func TestLogin_RefreshCanceledContext(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() provider := newRefreshProvider(t, refreshed) dir := t.TempDir() writeStoredToken(t, dir, provider.URL, expiredToken("still-good")) @@ -616,86 +617,6 @@ func TestLogin_RefreshCanceledContext(t *testing.T) { assert.Equal(t, "still-good", readStoredBundle(t, dir).RefreshToken) } -// TestRefreshToken_Errors verifies that every failure of the refresh -// request is reported as errTokenRefresh, is not mistaken for -// invalid_grant, and never includes the refresh token. -func TestRefreshToken_Errors(t *testing.T) { - closed := httptest.NewServer(http.NotFoundHandler()) - closedURL := closed.URL + "/token" - closed.Close() - - for name, tc := range map[string]struct { - endpoint func(t *testing.T) string - want string - }{ - "invalid endpoint URL": { - endpoint: func(*testing.T) string { return "http://[::1]:namedport/token" }, - want: "failed to create token request", - }, - "transport failure": { - endpoint: func(*testing.T) string { return closedURL }, - want: "token request failed", - }, - "truncated response body": { - endpoint: func(t *testing.T) string { - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - conn, buf, err := http.NewResponseController(w).Hijack() - if err != nil { - t.Errorf("hijack: %v", err) - return - } - _, _ = buf.WriteString("HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\n{\"access") - _ = buf.Flush() - _ = conn.Close() - })) - t.Cleanup(srv.Close) - return srv.URL + "/token" - }, - want: "failed to read token response", - }, - "invalid JSON": { - endpoint: func(t *testing.T) string { - return newRefreshProvider(t, func(url.Values) (int, string) { - return http.StatusOK, "not json" - }).URL + "/token" - }, - want: "invalid token response JSON", - }, - "server error without error code": { - endpoint: func(t *testing.T) string { - return newRefreshProvider(t, func(url.Values) (int, string) { - return http.StatusInternalServerError, `{"access_token":"a"}` - }).URL + "/token" - }, - want: "HTTP 500", - }, - "error code with status 401": { - endpoint: func(t *testing.T) string { - return newRefreshProvider(t, func(url.Values) (int, string) { - return http.StatusUnauthorized, `{"error":"invalid_client"}` - }).URL + "/token" - }, - want: ": invalid_client", - }, - "error code with status 200": { - endpoint: func(t *testing.T) string { - return newRefreshProvider(t, func(url.Values) (int, string) { - return http.StatusOK, `{"error":"temporarily_unavailable","access_token":"a"}` - }).URL + "/token" - }, - want: ": temporarily_unavailable", - }, - } { - t.Run(name, func(t *testing.T) { - _, err := refreshToken(context.Background(), tc.endpoint(t), "test-client", "secret-refresh-token", nil) - require.ErrorIs(t, err, errTokenRefresh) - assert.NotErrorIs(t, err, errInvalidGrant) - assert.Contains(t, err.Error(), tc.want) - assert.NotContains(t, err.Error(), "secret-refresh-token") - }) - } -} - // TestRefreshStoredToken_RereadsFileUnderLock verifies that // refreshStoredToken decides from the file it reads under the refresh // lock. The bundle Login read before waiting for the lock only decides @@ -721,6 +642,18 @@ func TestRefreshStoredToken_RereadsFileUnderLock(t *testing.T) { }, wantToken: "fresh-access-token", }, + "token refreshed by another caller, 20 s left": { + // Outside Login's 10 s refresh window, so it is used as is. + file: func(issuer string) *oidctoken.Bundle { + b := oidctoken.FromToken(&oauth2.Token{ + AccessToken: "fresh-access-token", + RefreshToken: "fresh-refresh-token", + Expiry: time.Now().Add(20 * time.Second), + }, issuer, "test-client") + return &b + }, + wantToken: "fresh-access-token", + }, "newer refresh token on disk": { file: func(issuer string) *oidctoken.Bundle { b := oidctoken.FromToken(expiredToken("newer-refresh-token"), issuer, "test-client") @@ -747,11 +680,11 @@ func TestRefreshStoredToken_RereadsFileUnderLock(t *testing.T) { }, } { t.Run(name, func(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() provider := newRefreshProvider(t, refreshed) dir := t.TempDir() if b := tc.file(provider.URL); b != nil { - require.NoError(t, writeToken(dir, *b)) + require.NoError(t, oidcclient.WriteToken(dir, *b)) } cfg := &loginConfig{issuer: provider.URL, clientID: "test-client"} // Login read this bundle before it waited for the lock. @@ -781,11 +714,11 @@ func TestRefreshStoredToken_RereadsFileUnderLock(t *testing.T) { // another refresh of the same file returns ErrTimeout when its own context // ends, without prompting. func TestLogin_RefreshLockWaitHonorsContext(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() provider := newRefreshProvider(t, refreshed) dir := t.TempDir() writeStoredToken(t, dir, provider.URL, expiredToken("still-good")) - unlock, err := lockTokenDir(context.Background(), dir) + unlock, err := oidcclient.LockDir(context.Background(), dir) require.NoError(t, err) defer unlock() @@ -815,7 +748,7 @@ func TestLogin_RefreshLockWaitHonorsContext(t *testing.T) { // without expires_in is accepted and stored without an expiry, as the code // exchange does. func TestLogin_RefreshWithoutExpiresIn(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() provider := newRefreshProvider(t, func(url.Values) (int, string) { return http.StatusOK, `{"access_token":"refreshed-access-token","refresh_token":"rotated","token_type":"Bearer"}` }) @@ -836,7 +769,7 @@ func TestLogin_RefreshWithoutExpiresIn(t *testing.T) { // that an expired peer token with no refresh token leads to the // interactive flow without a second refresh request. func TestLogin_RefreshInvalidGrantPeerWithoutRefreshTokenRunsFlow(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() dir := t.TempDir() var provider *refreshProvider provider = newRefreshProvider(t, func(form url.Values) (int, string) { @@ -868,7 +801,7 @@ func TestLogin_RefreshInvalidGrantPeerWithoutRefreshTokenRunsFlow(t *testing.T) // file keeps the peer's refresh token. The provider has already rejected // the original one. func TestLogin_RefreshPeerRetryKeepsPeerRefreshToken(t *testing.T) { - resetDiscoveryCache() + oidcclient.ResetDiscoveryCache() dir := t.TempDir() var provider *refreshProvider provider = newRefreshProvider(t, func(form url.Values) (int, string) { @@ -886,59 +819,144 @@ func TestLogin_RefreshPeerRetryKeepsPeerRefreshToken(t *testing.T) { assert.Equal(t, "peer-refresh-token", readStoredBundle(t, dir).RefreshToken) } -// TestRetryReplace verifies the replace retry schedule: transient errors -// are retried with delays doubling from 5 ms up to 50 ms until they add -// up to 250 ms, and any other error is returned at once. -func TestRetryReplace(t *testing.T) { - errTransient := errors.New("transient") - errOther := errors.New("other") - transient := func(err error) bool { return errors.Is(err, errTransient) } - - t.Run("succeeds after transient failures", func(t *testing.T) { - var slept []time.Duration - calls := 0 - err := retryReplace(func() error { - calls++ - if calls < 3 { - return errTransient +// TestLoginRefreshError verifies how Login treats each refresh error: run +// the interactive flow, or stop with the error. A write error is reported +// even when the context has also ended, and nothing to refresh means the +// interactive flow even when it has. +func TestLoginRefreshError(t *testing.T) { + live := context.Background() + ended, cancel := context.WithCancel(context.Background()) + cancel() + notRefreshable := fmt.Errorf("%w: it has no refresh token", oidcclient.ErrNotRefreshable) + invalidGrant := fmt.Errorf("%w: %w", oidcclient.ErrRefresh, oidcclient.ErrInvalidGrant) + persist := fmt.Errorf("%w: failed to replace", ErrTokenPersist) + discovery := fmt.Errorf("%w: HTTP 500", ErrDiscovery) + grant := fmt.Errorf("%w: HTTP 500", oidcclient.ErrRefresh) + + for name, tc := range map[string]struct { + ctx context.Context + err error + wantNil bool + wantIs []error + wantNotIs error + }{ + "nothing to refresh": {ctx: live, err: notRefreshable, wantNil: true}, + "nothing to refresh, context ended": {ctx: ended, err: notRefreshable, wantNil: true}, + "rejected with no newer token": {ctx: live, err: fmt.Errorf("%w: %w", oidcclient.ErrNotRefreshable, invalidGrant), wantNil: true}, + "write failed": {ctx: live, err: persist, wantIs: []error{ErrTokenPersist}}, + "write failed, context ended": {ctx: ended, err: persist, wantIs: []error{ErrTokenPersist}, wantNotIs: ErrTimeout}, + "discovery failed": {ctx: live, err: discovery, wantIs: []error{ErrDiscovery}}, + "discovery failed, context ended": {ctx: ended, err: discovery, wantIs: []error{ErrTimeout, context.Canceled}}, + "grant failed": {ctx: live, err: grant, wantNil: true}, + "grant failed, context ended": {ctx: ended, err: grant, wantIs: []error{ErrTimeout, context.Canceled}}, + "lock wait ended": {ctx: ended, err: context.Canceled, wantIs: []error{ErrTimeout, context.Canceled}}, + "invalid_grant on retry, context ended": {ctx: ended, err: invalidGrant, wantIs: []error{ErrTimeout}}, + } { + t.Run(name, func(t *testing.T) { + err := loginRefreshError(tc.ctx, tc.err) + if tc.wantNil { + assert.NoError(t, err) + return } - return nil - }, transient, func(d time.Duration) { slept = append(slept, d) }) + require.Error(t, err) + for _, want := range tc.wantIs { + assert.ErrorIs(t, err, want) + } + if tc.wantNotIs != nil { + assert.NotErrorIs(t, err, tc.wantNotIs) + } + }) + } +} + +// TestRefreshStoredToken_UnreadableFileRunsFlow verifies that Login runs +// the interactive flow when oidc_token.json cannot be parsed, whether it is +// read under the refresh lock or after invalid_grant, although a failed +// read is a token persistence error. +func TestRefreshStoredToken_UnreadableFileRunsFlow(t *testing.T) { + // corrupt runs in the provider's handler too, so it reports with + // t.Errorf instead of stopping the test from another goroutine. + corrupt := func(t *testing.T, dir string) { + t.Helper() + if err := os.WriteFile(filepath.Join(dir, oidctoken.FileName), []byte("{not json"), 0o600); err != nil { + t.Errorf("corrupt %s: %v", oidctoken.FileName, err) + } + } + + t.Run("under the lock", func(t *testing.T) { + oidcclient.ResetDiscoveryCache() + provider := newRefreshProvider(t, refreshed) + dir := t.TempDir() + corrupt(t, dir) + cfg := &loginConfig{issuer: provider.URL, clientID: "test-client"} + before := oidctoken.FromToken(expiredToken("older-refresh-token"), provider.URL, "test-client") + + tok, err := refreshStoredToken(context.Background(), cfg, dir, before) require.NoError(t, err) - assert.Equal(t, 3, calls) - assert.Equal(t, []time.Duration{5 * time.Millisecond, 10 * time.Millisecond}, slept) + assert.Nil(t, tok) + assert.Empty(t, provider.grants()) }) - t.Run("returns other errors at once", func(t *testing.T) { - var slept []time.Duration - err := retryReplace(func() error { return errOther }, transient, - func(d time.Duration) { slept = append(slept, d) }) - require.ErrorIs(t, err, errOther) - assert.Empty(t, slept) + t.Run("after invalid_grant", func(t *testing.T) { + oidcclient.ResetDiscoveryCache() + dir := t.TempDir() + provider := newRefreshProvider(t, func(url.Values) (int, string) { + corrupt(t, dir) + return http.StatusBadRequest, invalidGrantJSON + }) + writeStoredToken(t, dir, provider.URL, expiredToken("already-used")) + cfg := &loginConfig{issuer: provider.URL, clientID: "test-client"} + stored := readStoredBundle(t, dir) + + tok, err := refreshStoredToken(context.Background(), cfg, dir, stored) + require.NoError(t, err) + assert.Nil(t, tok) + assert.Equal(t, []string{"refresh_token"}, provider.grants()) }) +} - t.Run("gives up after 250 ms of delays", func(t *testing.T) { - var slept []time.Duration - calls := 0 - err := retryReplace(func() error { calls++; return errTransient }, transient, - func(d time.Duration) { slept = append(slept, d) }) - require.ErrorIs(t, err, errTransient) - ms := time.Millisecond - assert.Equal(t, []time.Duration{5 * ms, 10 * ms, 20 * ms, 40 * ms, 50 * ms, 50 * ms, 50 * ms, 50 * ms}, slept) - assert.Equal(t, len(slept)+1, calls) +// TestLogin_RefreshFileRemovedDuringRefreshRunsFlow verifies that a token +// file removed while the refresh request is in flight, as a logout does, +// is not written back: Login runs the interactive flow instead. +func TestLogin_RefreshFileRemovedDuringRefreshRunsFlow(t *testing.T) { + oidcclient.ResetDiscoveryCache() + dir := t.TempDir() + provider := newRefreshProvider(t, func(form url.Values) (int, string) { + if form.Get("grant_type") == "refresh_token" { + if err := os.Remove(filepath.Join(dir, oidctoken.FileName)); err != nil { + t.Errorf("remove: %v", err) + } + } + return refreshed(form) }) + writeStoredToken(t, dir, provider.URL, expiredToken("still-good")) + + tok, prompt, err := loginNoPrompt(t, provider.URL, dir) + require.Error(t, err, "the interactive flow cannot finish in the test") + assert.Nil(t, tok) + assert.NotEmpty(t, prompt, "Login ran the interactive flow") + _, statErr := os.Stat(filepath.Join(dir, oidctoken.FileName)) + assert.True(t, os.IsNotExist(statErr), "the refreshed token was written back") } -// TestIsTransientReplaceError verifies that only access denied and sharing -// violation on Windows are retried. -func TestIsTransientReplaceError(t *testing.T) { - link := func(errno syscall.Errno) error { - return &os.LinkError{Op: "rename", Old: "a", New: "b", Err: errno} - } - assert.True(t, isTransientReplaceError("windows", link(5))) - assert.True(t, isTransientReplaceError("windows", link(32))) - assert.False(t, isTransientReplaceError("windows", link(2))) - assert.False(t, isTransientReplaceError("windows", errors.New("rename failed"))) - assert.False(t, isTransientReplaceError("linux", link(5))) - assert.False(t, isTransientReplaceError("darwin", link(32))) +// TestLogin_RefreshNullExpiresIn verifies that a refresh response with a +// null expires_in gives a token without an expiry, stored without +// expires_at, as the CLI's oauth2 crate reads it. +func TestLogin_RefreshNullExpiresIn(t *testing.T) { + oidcclient.ResetDiscoveryCache() + provider := newRefreshProvider(t, func(form url.Values) (int, string) { + if form.Get("grant_type") == "refresh_token" { + return http.StatusOK, `{"access_token":"refreshed-access-token","refresh_token":"rotated","token_type":"Bearer","expires_in":null}` + } + return refreshed(form) + }) + dir := t.TempDir() + writeStoredToken(t, dir, provider.URL, expiredToken("still-good")) + + tok, prompt, err := loginNoPrompt(t, provider.URL, dir) + require.NoError(t, err) + assert.Empty(t, prompt) + assert.Equal(t, "refreshed-access-token", tok.AccessToken) + assert.True(t, tok.Expiry.IsZero()) + assert.Nil(t, readStoredBundle(t, dir).ExpiresAt) } diff --git a/openshell/v1/oidc/token_test.go b/openshell/v1/oidc/token_test.go index 09064a6..b984949 100644 --- a/openshell/v1/oidc/token_test.go +++ b/openshell/v1/oidc/token_test.go @@ -16,6 +16,8 @@ import ( "golang.org/x/oauth2" "github.com/ai-openshell/sdk-go/openshell/v1/internal/oidctoken" + + "github.com/ai-openshell/sdk-go/openshell/v1/internal/oidcclient" ) func loadOIDCTokenFixture(t *testing.T) []byte { @@ -29,7 +31,7 @@ func TestReadToken_ConformanceFixture(t *testing.T) { dir := t.TempDir() require.NoError(t, os.WriteFile(filepath.Join(dir, oidctoken.FileName), loadOIDCTokenFixture(t), 0o600)) - b, err := readToken(dir) + b, err := oidcclient.ReadToken(dir) require.NoError(t, err) require.NotNil(t, b) assert.Equal(t, "conformance-access-token", b.AccessToken) @@ -48,7 +50,7 @@ func TestWriteToken_MatchesConformanceFixture(t *testing.T) { Expiry: time.Unix(4102444800, 0), } - require.NoError(t, writeToken(dir, oidctoken.FromToken(tok, "https://issuer.example.com", "openshell-cli"))) + require.NoError(t, oidcclient.WriteToken(dir, oidctoken.FromToken(tok, "https://issuer.example.com", "openshell-cli"))) data, err := os.ReadFile(filepath.Join(dir, oidctoken.FileName)) require.NoError(t, err) @@ -59,7 +61,7 @@ func TestWriteToken_OmitsEmptyOptionalFields(t *testing.T) { dir := t.TempDir() tok := &oauth2.Token{AccessToken: "access-only"} - require.NoError(t, writeToken(dir, oidctoken.FromToken(tok, "https://issuer.example.com", "openshell-cli"))) + require.NoError(t, oidcclient.WriteToken(dir, oidctoken.FromToken(tok, "https://issuer.example.com", "openshell-cli"))) data, err := os.ReadFile(filepath.Join(dir, oidctoken.FileName)) require.NoError(t, err) @@ -73,13 +75,13 @@ func TestWriteToken_ReplacesInsecureExistingFileWithOwnerOnlyFile(t *testing.T) path := filepath.Join(dir, oidctoken.FileName) require.NoError(t, os.WriteFile(path, []byte("old"), 0o644)) - require.NoError(t, writeToken(dir, oidctoken.Bundle{AccessToken: "secret"})) + require.NoError(t, oidcclient.WriteToken(dir, oidctoken.Bundle{AccessToken: "secret"})) assertOwnerOnlyFilePermissions(t, path) } func TestWriteToken_InvalidDirectory(t *testing.T) { - err := writeToken("/nonexistent/path/that/does/not/exist", oidctoken.Bundle{AccessToken: "test"}) + err := oidcclient.WriteToken("/nonexistent/path/that/does/not/exist", oidctoken.Bundle{AccessToken: "test"}) require.Error(t, err) assert.True(t, errors.Is(err, ErrTokenPersist)) } @@ -87,7 +89,7 @@ func TestWriteToken_InvalidDirectory(t *testing.T) { func TestReadToken_MissingFile(t *testing.T) { dir := t.TempDir() - tok, err := readToken(dir) + tok, err := oidcclient.ReadToken(dir) assert.Nil(t, tok) assert.NoError(t, err, "missing file should return nil token, no error") } @@ -97,7 +99,7 @@ func TestReadToken_InvalidJSON(t *testing.T) { err := os.WriteFile(filepath.Join(dir, "oidc_token.json"), []byte(`{invalid`), 0o600) require.NoError(t, err) - _, err = readToken(dir) + _, err = oidcclient.ReadToken(dir) require.Error(t, err) assert.True(t, errors.Is(err, ErrTokenPersist)) } @@ -105,7 +107,7 @@ func TestReadToken_InvalidJSON(t *testing.T) { func TestWriteToken_FilePermissions(t *testing.T) { dir := t.TempDir() - err := writeToken(dir, oidctoken.Bundle{AccessToken: "perm-check"}) + err := oidcclient.WriteToken(dir, oidctoken.Bundle{AccessToken: "perm-check"}) require.NoError(t, err) assertOwnerOnlyFilePermissions(t, filepath.Join(dir, "oidc_token.json"))