diff --git a/docs/src/api/oidc.md b/docs/src/api/oidc.md index eb40fab..6e68532 100644 --- a/docs/src/api/oidc.md +++ b/docs/src/api/oidc.md @@ -92,14 +92,45 @@ Use `WithClientSecretProvider` when the application rotates secret material. | `WithClientSecret(secret)` | OAuth2 client secret (for client credentials) | | `WithClientSecretProvider(provider)` | Resolve the client secret for each exchange | | `WithAudience(audience)` | Optional OAuth2 resource-server audience | -| `WithScopes(scopes...)` | Custom scopes (client credentials has no implicit scopes) | +| `WithScopes(scopes...)` | Replace the default scopes (`openid profile email`); see [Scopes](#scopes) | | `WithCallbackPort(port)` | Fixed port for localhost callback (default: tries 8000, then 18000) | -| `WithTimeout(d)` | Auth flow timeout (default: 2 minutes) | +| `WithTimeout(d)` | Flow timeout (default: 2 minutes); see [Timeouts](#timeouts) | | `WithKeyboardFlow()` | Use keyboard flow instead of browser | | `WithInMemory()` | Skip token persistence to disk | | `WithDisplayFunc(fn)` | Custom display for device code flow | | `WithGateway(name)` | Resolve OIDC config from gateway metadata | +### Scopes + +Scopes come from `WithScopes` if set, then from the gateway's +`oidc_scopes` (when the flow reads gateway metadata), then from the +defaults. + +- `Login` and `DeviceLogin` authenticate a user, so they always request + `openid`: `WithScopes("sandbox:read")` sends `openid sandbox:read`, and + `WithScopes()` sends only `openid`. +- `ClientCredentials` and `NewClientCredentialsAuth` have no user, so they + send exactly the scopes set by `WithScopes` or the gateway, with no + defaults. Without scopes, the token request carries no `scope` + parameter. + +### Timeouts + +`Login`, `DeviceLogin` and `ClientCredentials` apply `WithTimeout` only +when the context has no deadline; a context deadline always wins. For +these flows, a zero or negative duration means no deadline, so the flow +runs until it completes or the context is cancelled. + +`NewClientCredentialsAuth` renews tokens in the background, where no +caller context can cancel the exchange. It always bounds each exchange: +by `WithTimeout` when positive, otherwise by the 2 minute default. + +`ErrTimeout` covers only the interactive flows. When a client credentials +exchange runs out of time or its context is cancelled, the error matches +both `ErrClientCredentials` and the context error, so +`errors.Is(err, context.DeadlineExceeded)` tells a timeout apart from a +provider failure. + ## Error Handling The package defines sentinel errors for `errors.Is()` matching: @@ -110,7 +141,7 @@ The package defines sentinel errors for `errors.Is()` matching: | `ErrAuthCode` | Authorization code exchange failed | | `ErrDeviceCode` | Device code flow failed | | `ErrClientCredentials` | Client credentials exchange failed | -| `ErrTimeout` | Authentication flow timed out | +| `ErrTimeout` | Interactive flow (browser, keyboard or device code) timed out | | `ErrCallbackServer` | Localhost callback server failed | | `ErrTokenPersist` | Token read/write failed | | `ErrOIDCConfig` | Missing or invalid OIDC configuration | @@ -129,7 +160,9 @@ if errors.Is(err, oidc.ErrTimeout) { When a gateway's `metadata.json` contains `oidc_issuer` and `oidc_client_id` fields, `Login` and `DeviceLogin` can resolve -configuration automatically: +configuration automatically. An `oidc_scopes` field (space-separated) +sets the scopes for every flow that reads the gateway, unless +`WithScopes` is set: ```go // Login reads OIDC config from the gateway diff --git a/openshell/v1/oidc/credentials.go b/openshell/v1/oidc/credentials.go index 7f658c1..a895d81 100644 --- a/openshell/v1/oidc/credentials.go +++ b/openshell/v1/oidc/credentials.go @@ -33,6 +33,13 @@ func ClientCredentials(ctx context.Context, opts ...LoginOption) (*oauth2.Token, if err != nil { return nil, err } + // Same rule as Login and DeviceLogin: a caller deadline wins, and a + // non-positive timeout means no deadline. + if _, hasDeadline := ctx.Deadline(); !hasDeadline && cfg.timeout > 0 { + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(ctx, cfg.timeout) + defer cancel() + } return exchangeClientCredentials(ctx, cfg, false) } @@ -66,10 +73,7 @@ func resolveClientCredentialsConfig(opts ...LoginOption) (*loginConfig, error) { if !cfg.audienceSet { cfg.audience = gwCfg.OIDCAudience } - if !cfg.scopesSet && gwCfg.OIDCScopes != "" { - cfg.scopes = strings.Fields(gwCfg.OIDCScopes) - cfg.scopesSet = true - } + cfg.applyGatewayScopes(gwCfg) } // Validate required configuration. @@ -88,12 +92,23 @@ func resolveClientCredentialsConfig(opts ...LoginOption) (*loginConfig, error) { return cfg, nil } +// clientCredentialsError wraps ErrClientCredentials and, once ctx has ended, +// the context error too, so callers can tell a timeout or cancellation from +// a provider failure. The underlying cause is left out on purpose: it may +// carry secret material (FR-014), the context error never does. +func clientCredentialsError(ctx context.Context, msg string) error { + if ctxErr := ctx.Err(); ctxErr != nil { + return fmt.Errorf("%w: %s: %w", ErrClientCredentials, msg, ctxErr) + } + return fmt.Errorf("%w: %s", ErrClientCredentials, msg) +} + func exchangeClientCredentials(ctx context.Context, cfg *loginConfig, requirePositiveExpiry bool) (*oauth2.Token, error) { secret := cfg.clientSecret if cfg.secretProvider != nil { value, err := cfg.secretProvider(ctx) if err != nil { - return nil, fmt.Errorf("%w: client secret provider failed", ErrClientCredentials) + return nil, clientCredentialsError(ctx, "client secret provider failed") } secret = value } @@ -135,14 +150,14 @@ func exchangeClientCredentials(ctx context.Context, cfg *loginConfig, requirePos } resp, err := noRedirectClient.Do(req) if err != nil { - return nil, fmt.Errorf("%w: token request failed", ErrClientCredentials) + return nil, clientCredentialsError(ctx, "token request failed") } defer func() { _ = resp.Body.Close() }() const maxResponseBytes = 1 << 20 body, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBytes+1)) if err != nil { - return nil, fmt.Errorf("%w: failed to read token response", ErrClientCredentials) + return nil, clientCredentialsError(ctx, "failed to read token response") } if len(body) > maxResponseBytes { return nil, fmt.Errorf("%w: token response is too large", ErrClientCredentials) diff --git a/openshell/v1/oidc/credentials_auth.go b/openshell/v1/oidc/credentials_auth.go index b662cd5..c523986 100644 --- a/openshell/v1/oidc/credentials_auth.go +++ b/openshell/v1/oidc/credentials_auth.go @@ -71,7 +71,16 @@ func (a *clientCredentialsAuth) accessTokenForExchange() (string, error) { return accessToken, nil } - exchangeCtx, cancel := context.WithTimeout(context.Background(), a.cfg.timeout) + // The exchange is detached from caller contexts on purpose, so no caller + // can cancel it. Always bound it, or a secret provider that blocks would + // hold the singleflight key forever and wedge every later request. A + // non-positive timeout falls back to the default here instead of meaning + // "no deadline" as it does for the caller-driven flows. + timeout := a.cfg.timeout + if timeout <= 0 { + timeout = defaultTimeout + } + exchangeCtx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() token, err := exchangeClientCredentials(exchangeCtx, a.cfg, true) if err != nil { diff --git a/openshell/v1/oidc/credentials_test.go b/openshell/v1/oidc/credentials_test.go index 87ba11f..616d02d 100644 --- a/openshell/v1/oidc/credentials_test.go +++ b/openshell/v1/oidc/credentials_test.go @@ -308,6 +308,253 @@ func TestClientCredentialsAuthLateFlightReusesCachedToken(t *testing.T) { assert.Equal(t, "cached-token", accessToken) } +// No caller can cancel the detached background exchange, so a non-positive +// timeout falls back to the default instead of leaving it unbounded. The +// exchange context must not be born expired either, so the exchange succeeds. +func TestClientCredentialsAuthNonPositiveTimeoutUsesDefaultBound(t *testing.T) { + for _, timeout := range []time.Duration{0, -1 * time.Second} { + t.Run(timeout.String(), func(t *testing.T) { + 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" { + _ = json.NewEncoder(w).Encode(map[string]string{ + "issuer": server.URL, + "authorization_endpoint": server.URL + "/authorize", + "token_endpoint": server.URL + "/token", + }) + return + } + _, _ = w.Write([]byte(tokenResponseJSON("token", "", 3600))) + })) + t.Cleanup(server.Close) + + // The secret provider runs on the exchange context, so it sees + // the bound the exchange runs under. + var remaining time.Duration + var hasDeadline bool + auth, err := NewClientCredentialsAuth( + WithIssuer(server.URL), + WithClientID("client"), + WithClientSecretProvider(func(ctx context.Context) (string, error) { + var deadline time.Time + deadline, hasDeadline = ctx.Deadline() + remaining = time.Until(deadline) + return "secret", nil + }), + WithTimeout(timeout), + ) + require.NoError(t, err) + + metadata, err := auth.GetRequestMetadata(context.Background()) + require.NoError(t, err) + assert.Equal(t, "Bearer token", metadata["authorization"]) + require.True(t, hasDeadline, "the background exchange must have a deadline") + assert.Greater(t, remaining, defaultTimeout-time.Minute) + assert.LessOrEqual(t, remaining, defaultTimeout) + }) + } +} + +// The client credentials grant has no user and no ID token, so "openid" must +// never be forced onto it the way the interactive flows force it. +func TestClientCredentialsScopesAreNotNormalized(t *testing.T) { + tests := []struct { + name string + opts []LoginOption + want []string + }{ + { + name: "unset sends no scopes", + opts: nil, + want: nil, + }, + { + name: "explicit empty sends no scopes", + opts: []LoginOption{WithScopes()}, + want: []string{}, + }, + { + name: "application scopes are sent verbatim", + opts: []LoginOption{WithScopes("sandbox:read", "sandbox:write")}, + want: []string{"sandbox:read", "sandbox:write"}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + opts := append([]LoginOption{ + WithIssuer("https://issuer.example.com"), + WithClientID("client"), + WithClientSecret("secret"), + }, tt.opts...) + + cfg, err := resolveClientCredentialsConfig(opts...) + require.NoError(t, err) + assert.Equal(t, tt.want, cfg.scopes) + }) + } +} + +// Without scopes (unset or WithScopes()), the token request must carry no +// scope parameter at all, not a bare "scope=", for both entry points. +func TestClientCredentialsSendNoScopeParameterWithoutScopes(t *testing.T) { + entryPoints := map[string]func(opts ...LoginOption) error{ + "ClientCredentials": func(opts ...LoginOption) error { + _, err := ClientCredentials(context.Background(), opts...) + return err + }, + "NewClientCredentialsAuth": func(opts ...LoginOption) error { + auth, err := NewClientCredentialsAuth(opts...) + if err != nil { + return err + } + _, err = auth.GetRequestMetadata(context.Background()) + return err + }, + } + scopeOptions := map[string][]LoginOption{ + "unset": nil, + "explicit empty": {WithScopes()}, + } + + for entryName, run := range entryPoints { + for scopeName, scopeOpts := range scopeOptions { + t.Run(entryName+"/"+scopeName, func(t *testing.T) { + resetDiscoveryCache() + var form url.Values + var srv *httptest.Server + srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/.well-known/openid-configuration" { + _ = json.NewEncoder(w).Encode(map[string]string{ + "issuer": srv.URL, + "authorization_endpoint": srv.URL + "/authorize", + "token_endpoint": srv.URL + "/token", + }) + return + } + _ = r.ParseForm() + form = r.Form + _, _ = w.Write([]byte(tokenResponseJSON("token", "", 3600))) + })) + t.Cleanup(srv.Close) + + opts := append([]LoginOption{ + WithIssuer(srv.URL), + WithClientID("client"), + WithClientSecret("secret"), + }, scopeOpts...) + require.NoError(t, run(opts...)) + require.NotNil(t, form, "the token request was never made") + assert.False(t, form.Has("scope"), "unexpected scope parameter %q", form.Get("scope")) + }) + } + } +} + +// ClientCredentials applies WithTimeout when the caller's context has no +// deadline, the same way Login and DeviceLogin do. +func TestClientCredentials_WithTimeoutBoundsExchange(t *testing.T) { + start := time.Now() + _, err := ClientCredentials(context.Background(), + WithIssuer("https://issuer.example.com"), + WithClientID("client"), + WithClientSecretProvider(func(ctx context.Context) (string, error) { + <-ctx.Done() + return "", ctx.Err() + }), + WithTimeout(50*time.Millisecond), + ) + require.ErrorIs(t, err, ErrClientCredentials) + assert.ErrorIs(t, err, context.DeadlineExceeded) + assert.Less(t, time.Since(start), 5*time.Second) +} + +// A token endpoint that outlives the deadline yields an error that matches +// context.DeadlineExceeded, so callers can tell a timeout from a provider +// failure. +func TestClientCredentials_TokenRequestTimeoutWrapsContextError(t *testing.T) { + resetDiscoveryCache() + release := make(chan struct{}) + var srv *httptest.Server + srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/.well-known/openid-configuration" { + _ = json.NewEncoder(w).Encode(map[string]string{ + "issuer": srv.URL, + "authorization_endpoint": srv.URL + "/authorize", + "token_endpoint": srv.URL + "/token", + }) + return + } + // Hold the token response until the test ends. + <-release + })) + t.Cleanup(srv.Close) + 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) + require.NoError(t, err) + + _, err = ClientCredentials(context.Background(), + WithIssuer(srv.URL), + WithClientID("client"), + WithClientSecret("secret"), + WithTimeout(50*time.Millisecond), + ) + require.ErrorIs(t, err, ErrClientCredentials) + assert.ErrorIs(t, err, context.DeadlineExceeded) + assert.Contains(t, err.Error(), "token request failed") +} + +// The other two WithTimeout rules for ClientCredentials: a caller deadline +// wins over WithTimeout, and a non-positive timeout means no deadline. +func TestClientCredentials_TimeoutDeadlineRules(t *testing.T) { + callerDeadline := time.Now().Add(time.Hour) + tests := []struct { + name string + ctxDeadline bool + timeout time.Duration + wantDeadline bool + }{ + {name: "caller deadline wins", ctxDeadline: true, timeout: time.Second, wantDeadline: true}, + {name: "zero timeout", timeout: 0}, + {name: "negative timeout", timeout: -time.Second}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + resetDiscoveryCache() + provider := setupCredentialsMockProvider(t, "client", "secret") + + ctx := context.Background() + if tt.ctxDeadline { + var cancel context.CancelFunc + ctx, cancel = context.WithDeadline(ctx, callerDeadline) + t.Cleanup(cancel) + } + + // The secret provider runs on the exchange context, so it sees + // the deadline the exchange runs under. + var deadline time.Time + var hasDeadline bool + _, err := ClientCredentials(ctx, + WithIssuer(provider.URL), + WithClientID("client"), + WithClientSecretProvider(func(ctx context.Context) (string, error) { + deadline, hasDeadline = ctx.Deadline() + return "secret", nil + }), + WithTimeout(tt.timeout), + ) + require.NoError(t, err) + require.Equal(t, tt.wantDeadline, hasDeadline) + if tt.wantDeadline { + assert.True(t, deadline.Equal(callerDeadline), "deadline %v, want the caller's %v", deadline, callerDeadline) + } + }) + } +} + func TestClientCredentialsAuthCancellationDoesNotPoisonSharedExchange(t *testing.T) { resetDiscoveryCache() var server *httptest.Server diff --git a/openshell/v1/oidc/device.go b/openshell/v1/oidc/device.go index f00ca80..2c35819 100644 --- a/openshell/v1/oidc/device.go +++ b/openshell/v1/oidc/device.go @@ -73,8 +73,14 @@ func DeviceLogin(ctx context.Context, opts ...LoginOption) (*oauth2.Token, error } cfg.issuer = gwCfg.OIDCIssuer cfg.clientID = gwCfg.OIDCClientID + cfg.applyGatewayScopes(gwCfg) } + // DeviceLogin authenticates a user, so the request must be an OIDC one + // whether the scopes came from the caller, the gateway metadata, or the + // defaults. + cfg.requireOpenIDScope() + // Validate required configuration. if cfg.issuer == "" || cfg.clientID == "" { return nil, fmt.Errorf( diff --git a/openshell/v1/oidc/device_test.go b/openshell/v1/oidc/device_test.go index cb10191..9e8cdd8 100644 --- a/openshell/v1/oidc/device_test.go +++ b/openshell/v1/oidc/device_test.go @@ -118,6 +118,169 @@ func TestDeviceLogin_Success(t *testing.T) { assert.Equal(t, "ABCD-1234", displayedCode) } +// DeviceLogin authenticates a user, so the device authorization request must +// carry "openid" on the wire even when the caller supplied its own scopes. +func TestDeviceLogin_AlwaysRequestsOpenIDScope(t *testing.T) { + tests := []struct { + name string + opts []LoginOption + want string + }{ + { + name: "unset scopes send the defaults", + opts: nil, + want: "openid profile email", + }, + { + name: "explicit empty still sends openid", + opts: []LoginOption{WithScopes()}, + want: "openid", + }, + { + name: "application scopes gain openid", + opts: []LoginOption{WithScopes("sandbox:read")}, + want: "openid sandbox:read", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + resetDiscoveryCache() + + scope := &capturedScope{} + srv := setupScopeCapturingDeviceProvider(t, scope) + + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + opts := append([]LoginOption{ + WithIssuer(srv.URL), + WithClientID("device-client"), + WithDisplayFunc(func(_, _ string) {}), + }, tt.opts...) + + _, err := DeviceLogin(ctx, opts...) + require.NoError(t, err) + assert.Equal(t, tt.want, scope.get(t)) + }) + } +} + +// DeviceLogin must honor the gateway's configured oidc_scopes the way the +// Rust CLI does (see build_scopes in crates/openshell-cli/src/oidc_auth.rs), +// while an explicit WithScopes still wins. +func TestDeviceLogin_GatewayScopes(t *testing.T) { + tests := []struct { + name string + gatewayScope string + opts []LoginOption + want string + }{ + { + name: "gateway scopes are used when the caller sets none", + gatewayScope: "openid sandbox:read sandbox:write", + want: "openid sandbox:read sandbox:write", + }, + { + name: "gateway scopes gain openid", + gatewayScope: "sandbox:read", + want: "openid sandbox:read", + }, + { + name: "explicit scopes win over gateway scopes", + gatewayScope: "sandbox:read", + opts: []LoginOption{WithScopes("sandbox:admin")}, + want: "openid sandbox:admin", + }, + { + name: "empty gateway scopes fall back to the defaults", + gatewayScope: "", + want: "openid profile email", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + resetDiscoveryCache() + + scope := &capturedScope{} + srv := setupScopeCapturingDeviceProvider(t, scope) + + fakeConfig := &gateway.Config{ + Name: "device-gw", + Endpoint: "gateway.example.com:443", + Dir: t.TempDir(), + OIDCIssuer: srv.URL, + OIDCClientID: "gw-device-client", + OIDCScopes: tt.gatewayScope, + } + + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + opts := append([]LoginOption{ + WithGateway("device-gw"), + WithDisplayFunc(func(_, _ string) {}), + withGatewayResolver(func(string) (*gateway.Config, error) { + return fakeConfig, nil + }), + }, tt.opts...) + + _, err := DeviceLogin(ctx, opts...) + require.NoError(t, err) + assert.Equal(t, tt.want, scope.get(t)) + }) + } +} + +// capturedScope records the scope parameter seen by a mock provider. +type capturedScope struct { + value string + seen atomic.Bool +} + +func (c *capturedScope) get(t *testing.T) string { + t.Helper() + require.True(t, c.seen.Load(), "the authorization request was never made") + return c.value +} + +// setupScopeCapturingDeviceProvider serves a device-flow provider that records +// the scope parameter sent to the device authorization endpoint. +func setupScopeCapturingDeviceProvider(t *testing.T, scope *capturedScope) *httptest.Server { + t.Helper() + mux := http.NewServeMux() + var srv *httptest.Server + + mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, _ *http.Request) { + _ = json.NewEncoder(w).Encode(map[string]any{ + "issuer": srv.URL, + "authorization_endpoint": srv.URL + "/authorize", + "token_endpoint": srv.URL + "/token", + "device_authorization_endpoint": srv.URL + "/device", + }) + }) + mux.HandleFunc("/device", func(w http.ResponseWriter, r *http.Request) { + _ = r.ParseForm() + scope.value = r.Form.Get("scope") + scope.seen.Store(true) + _ = json.NewEncoder(w).Encode(map[string]any{ + "device_code": "test-device-code", + "user_code": "ABCD-1234", + "verification_uri": "https://example.com/activate", + "expires_in": 300, + "interval": 1, + }) + }) + mux.HandleFunc("/token", func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write([]byte(tokenResponseJSON("device-access-token", "", 3600))) + }) + + srv = httptest.NewServer(mux) + t.Cleanup(srv.Close) + return srv +} + // TestDeviceLogin_MissingIssuer verifies that DeviceLogin returns // ErrOIDCConfig when the issuer is not provided. func TestDeviceLogin_MissingIssuer(t *testing.T) { diff --git a/openshell/v1/oidc/oidc.go b/openshell/v1/oidc/oidc.go index d5ed3bf..7cec821 100644 --- a/openshell/v1/oidc/oidc.go +++ b/openshell/v1/oidc/oidc.go @@ -52,6 +52,9 @@ func Login(ctx context.Context, gatewayName string, opts ...LoginOption) (*oauth if err != nil { return nil, err } + // Login authenticates a user, so the request must be an OIDC one whether the + // scopes came from the caller, the gateway metadata, or the defaults. + cfg.requireOpenIDScope() // FR-019: Check for existing valid token on disk before starting // an interactive flow. @@ -120,8 +123,8 @@ func Login(ctx context.Context, gatewayName string, opts ...LoginOption) (*oauth return tok, nil } -// resolveOIDCConfig resolves the OIDC issuer and client ID either from -// the gateway metadata or from explicit options. Returns the token +// resolveOIDCConfig resolves the OIDC issuer, client ID, and scopes either +// from the gateway metadata or from explicit options. Returns the token // directory path (empty if in-memory or no directory available). func resolveOIDCConfig(cfg *loginConfig, gatewayName string) (string, error) { tokenDir := cfg.tokenDir @@ -141,6 +144,7 @@ func resolveOIDCConfig(cfg *loginConfig, gatewayName string) (string, error) { } cfg.issuer = gwCfg.OIDCIssuer cfg.clientID = gwCfg.OIDCClientID + cfg.applyGatewayScopes(gwCfg) if tokenDir == "" { tokenDir = gwCfg.Dir } diff --git a/openshell/v1/oidc/oidc_test.go b/openshell/v1/oidc/oidc_test.go index af717a6..491e4f1 100644 --- a/openshell/v1/oidc/oidc_test.go +++ b/openshell/v1/oidc/oidc_test.go @@ -11,6 +11,7 @@ import ( "net" "net/http" "net/http/httptest" + "net/url" "os" "path/filepath" "strings" @@ -239,6 +240,143 @@ func TestLogin_KeyboardFlow(t *testing.T) { assert.Equal(t, "login-access-token", diskTok.AccessToken) } +// Login authenticates a user, so the authorization URL must carry "openid" +// even when the caller supplied its own scopes. An explicitly-empty scope +// list must never produce a bare "scope=" parameter. +func TestLogin_AlwaysRequestsOpenIDScope(t *testing.T) { + tests := []struct { + name string + opts []LoginOption + want string + }{ + { + name: "unset scopes send the defaults", + opts: nil, + want: "openid profile email", + }, + { + name: "explicit empty still sends openid", + opts: []LoginOption{WithScopes()}, + want: "openid", + }, + { + name: "application scopes gain openid", + opts: []LoginOption{WithScopes("sandbox:read")}, + want: "openid sandbox:read", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + resetDiscoveryCache() + + provider := setupMockProvider(t) + var prompt strings.Builder + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + opts := append([]LoginOption{ + WithIssuer(provider.URL), + WithClientID("test-client"), + WithInMemory(), + WithKeyboardFlow(), + withInput(strings.NewReader("keyboard-auth-code\n")), + withOutput(&prompt), + }, tt.opts...) + + _, err := Login(ctx, "", opts...) + require.NoError(t, err) + + // The keyboard flow prints the authorization URL it would open. + authURL := extractAuthURL(t, prompt.String()) + assert.Equal(t, tt.want, authURL.Query().Get("scope")) + }) + } +} + +// Login must honor the gateway's configured oidc_scopes the way the Rust CLI +// does (see commands/gateway.rs, which passes metadata.oidc_scopes into the +// interactive flow), while an explicit WithScopes still wins. +func TestLogin_GatewayScopes(t *testing.T) { + tests := []struct { + name string + gatewayScope string + opts []LoginOption + want string + }{ + { + name: "gateway scopes are used when the caller sets none", + gatewayScope: "openid sandbox:read sandbox:write", + want: "openid sandbox:read sandbox:write", + }, + { + name: "gateway scopes gain openid", + gatewayScope: "sandbox:read", + want: "openid sandbox:read", + }, + { + name: "explicit scopes win over gateway scopes", + gatewayScope: "sandbox:read", + opts: []LoginOption{WithScopes("sandbox:admin")}, + want: "openid sandbox:admin", + }, + { + name: "empty gateway scopes fall back to the defaults", + gatewayScope: "", + want: "openid profile email", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + resetDiscoveryCache() + + provider := setupMockProvider(t) + var prompt strings.Builder + + fakeConfig := &gateway.Config{ + Name: "login-gw", + Endpoint: "gateway.example.com:443", + Dir: t.TempDir(), + OIDCIssuer: provider.URL, + OIDCClientID: "gw-login-client", + OIDCScopes: tt.gatewayScope, + } + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + opts := append([]LoginOption{ + WithInMemory(), + WithKeyboardFlow(), + withInput(strings.NewReader("keyboard-auth-code\n")), + withOutput(&prompt), + withGatewayResolver(func(string) (*gateway.Config, error) { + return fakeConfig, nil + }), + }, tt.opts...) + + _, err := Login(ctx, "login-gw", opts...) + require.NoError(t, err) + + authURL := extractAuthURL(t, prompt.String()) + assert.Equal(t, tt.want, authURL.Query().Get("scope")) + }) + } +} + +// extractAuthURL pulls the authorization URL out of the keyboard-flow prompt. +func extractAuthURL(t *testing.T, prompt string) *url.URL { + t.Helper() + start := strings.Index(prompt, "http") + require.GreaterOrEqual(t, start, 0, "no authorization URL in prompt: %q", prompt) + raw := strings.Fields(prompt[start:])[0] + parsed, err := url.Parse(raw) + require.NoError(t, err) + return parsed +} + // TestLogin_InMemorySkipsPersistence verifies that WithInMemory() // returns a token without writing to disk. func TestLogin_InMemorySkipsPersistence(t *testing.T) { diff --git a/openshell/v1/oidc/options.go b/openshell/v1/oidc/options.go index 3b7a128..e4f64f5 100644 --- a/openshell/v1/oidc/options.go +++ b/openshell/v1/oidc/options.go @@ -6,17 +6,24 @@ package oidc import ( "context" "io" + "strings" "time" "github.com/ai-openshell/sdk-go/openshell/v1/gateway" ) +// scopeOpenID is the scope that turns an OAuth2 authorization request into +// an OpenID Connect one. Interactive flows always request it. +const scopeOpenID = "openid" + // defaultScopes are the OIDC scopes requested when no custom scopes // are specified via [WithScopes]. -var defaultScopes = []string{"openid", "profile", "email"} +var defaultScopes = []string{scopeOpenID, "profile", "email"} -// defaultTimeout is the maximum duration for interactive login flows -// (browser, keyboard, device code) when no custom timeout is set. +// defaultTimeout is the maximum duration of a flow (browser, keyboard, +// device code, client credentials) when no custom timeout is set. It also +// bounds every background exchange of [NewClientCredentialsAuth] that has no +// positive timeout. const defaultTimeout = 2 * time.Minute // loginConfig holds the resolved configuration for a single login @@ -33,6 +40,7 @@ type loginConfig struct { scopesSet bool callbackPort int timeout time.Duration + timeoutSet bool keyboardFlow bool inMemory bool displayFunc func(verificationURL, userCode string) @@ -48,16 +56,50 @@ type loginConfig struct { // applyDefaults fills in default values for fields that were not set // by any option function. func (c *loginConfig) applyDefaults() { - if len(c.scopes) == 0 { + // Check set-ness, not the zero value, so an explicitly-set empty scope + // list or zero timeout is honored instead of being replaced by defaults. + if !c.scopesSet { // Deep copy to avoid callers mutating the package-level slice. c.scopes = make([]string, len(defaultScopes)) copy(c.scopes, defaultScopes) } - if c.timeout == 0 { + if !c.timeoutSet { c.timeout = defaultTimeout } } +// applyGatewayScopes fills unset scopes from the gateway's oidc_scopes, a +// whitespace-separated list in metadata.json. Gateway scopes only fill +// genuinely-unset scopes, so an explicit [WithScopes] always wins. All flows +// that read gateway metadata use this one rule. +func (c *loginConfig) applyGatewayScopes(gw *gateway.Config) { + if !c.scopesSet && gw.OIDCScopes != "" { + c.scopes = strings.Fields(gw.OIDCScopes) + c.scopesSet = true + } +} + +// requireOpenIDScope normalizes the scopes for an interactive flow so the +// request is always an OpenID Connect one. "openid" is placed first and any +// caller-supplied duplicate is dropped; the remaining scopes keep their order. +// +// Interactive flows authenticate a user, and the gateway requires a "sub" +// claim on the resulting token, so "openid" is not optional there. Callers +// remain free to request application scopes such as "sandbox:read". The +// client credentials grant has no user and is left untouched. +// +// 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 +} + // LoginOption configures a login attempt. Use the With* functions to // create option values. type LoginOption func(*loginConfig) @@ -104,6 +146,12 @@ func WithAudience(audience string) LoginOption { // WithScopes overrides the default scopes (openid, profile, email). // The provided scopes replace the defaults entirely. +// +// [Login] and [DeviceLogin] always request "openid" in addition to the +// provided scopes, so WithScopes("sandbox:read") sends "openid sandbox:read". +// [ClientCredentials] and [NewClientCredentialsAuth] send exactly what is +// provided, since that grant has no user and no ID token; calling +// WithScopes with no arguments there sends no scope parameter at all. func WithScopes(scopes ...string) LoginOption { return func(c *loginConfig) { c.scopes = make([]string, len(scopes)) @@ -120,11 +168,20 @@ func WithCallbackPort(port int) LoginOption { } } -// WithTimeout sets the maximum duration for interactive login flows. -// The default is 2 minutes. +// WithTimeout sets the maximum duration for a flow. The default is 2 minutes. +// +// [Login], [DeviceLogin] and [ClientCredentials] apply it only when the +// caller's context has no deadline; a caller-supplied deadline always takes +// precedence. For them, a non-positive duration (d <= 0) means "no deadline": +// the flow runs until it completes or the caller's context is cancelled. +// +// [NewClientCredentialsAuth] runs each token exchange in the background, +// detached from any caller context, so it always bounds the exchange: by d +// when d is positive and by the 2 minute default otherwise. func WithTimeout(d time.Duration) LoginOption { return func(c *loginConfig) { c.timeout = d + c.timeoutSet = true } } @@ -179,6 +236,13 @@ func withInput(r io.Reader) LoginOption { } } +// withOutput overrides the output writer for keyboard flow testing. +func withOutput(w io.Writer) LoginOption { + return func(c *loginConfig) { + c.output = w + } +} + // withGatewayResolver overrides the gateway.LoadConfig function for // testing. This allows tests to inject a fake gateway resolver // without filesystem setup. diff --git a/openshell/v1/oidc/options_test.go b/openshell/v1/oidc/options_test.go index 28d17c0..af23b9c 100644 --- a/openshell/v1/oidc/options_test.go +++ b/openshell/v1/oidc/options_test.go @@ -82,6 +82,87 @@ func TestWithTimeout(t *testing.T) { assert.Equal(t, 5*time.Minute, cfg.timeout) } +func TestWithScopes_ExplicitEmptyNotOverridden(t *testing.T) { + var cfg loginConfig + WithScopes()(&cfg) // caller explicitly requests no scopes + cfg.applyDefaults() + + // An explicitly-set empty scope list must be honored, not replaced by defaults. + assert.True(t, cfg.scopesSet) + assert.Empty(t, cfg.scopes) +} + +func TestWithTimeout_ExplicitZeroNotOverridden(t *testing.T) { + var cfg loginConfig + WithTimeout(0)(&cfg) // caller explicitly requests no timeout + cfg.applyDefaults() + + // An explicitly-set zero timeout must be honored, not replaced by the default. + assert.True(t, cfg.timeoutSet) + assert.Zero(t, cfg.timeout) +} + +func TestWithTimeout_NegativeMeansNoDeadline(t *testing.T) { + var cfg loginConfig + WithTimeout(-1 * time.Second)(&cfg) + cfg.applyDefaults() + + // Every flow gates on timeout > 0, so a negative duration means + // "no deadline" exactly as zero does. It is not replaced by the default. + assert.True(t, cfg.timeoutSet) + assert.Negative(t, cfg.timeout) +} + +// Interactive flows authenticate a user, so the request must carry the +// "openid" scope regardless of what the caller asked for. This mirrors +// build_scopes in crates/openshell-cli/src/oidc_auth.rs. +func TestRequireOpenIDScope(t *testing.T) { + tests := []struct { + name string + opts []LoginOption + want []string + }{ + { + name: "unset scopes keep the defaults", + opts: nil, + want: []string{"openid", "profile", "email"}, + }, + { + name: "explicit empty still requests openid", + opts: []LoginOption{WithScopes()}, + want: []string{"openid"}, + }, + { + name: "application scopes gain openid", + opts: []LoginOption{WithScopes("sandbox:read", "sandbox:write")}, + want: []string{"openid", "sandbox:read", "sandbox:write"}, + }, + { + name: "existing openid is not duplicated", + opts: []LoginOption{WithScopes("openid", "profile")}, + want: []string{"openid", "profile"}, + }, + { + name: "openid is normalized to the front", + opts: []LoginOption{WithScopes("profile", "openid", "email")}, + want: []string{"openid", "profile", "email"}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var cfg loginConfig + for _, opt := range tt.opts { + opt(&cfg) + } + cfg.applyDefaults() + cfg.requireOpenIDScope() + + assert.Equal(t, tt.want, cfg.scopes) + }) + } +} + func TestWithKeyboardFlow(t *testing.T) { var cfg loginConfig WithKeyboardFlow()(&cfg)