From a0b0ba8961078c1a6e53869981cbecc052855b42 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roland=20Hu=C3=9F?= Date: Wed, 9 Sep 2026 11:35:46 +0200 Subject: [PATCH 1/9] fix(sdk/go): honor explicitly-set zero option values in oidc defaults MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `loginConfig.applyDefaults()` keyed off the zero value rather than set-ness, so it could not distinguish an unset field from one a caller explicitly set to its zero value: - `WithTimeout(0)` was silently replaced by the 2m default. - `WithScopes()` (explicit empty) was replaced by the default scopes, even though `WithScopes` already records `scopesSet`. Switch `applyDefaults` to consult the `*Set` sentinels, add a `timeoutSet` sentinel set by `WithTimeout`, and guard the client-credentials exchange so a zero timeout means "no deadline" instead of creating an already-expired context (matching Login and DeviceFlow). `WithTimeout(0)` now means "no timeout". Unset fields still receive their defaults; non-zero explicit values are unaffected. Signed-off-by: Roland Huß --- openshell/v1/oidc/credentials_auth.go | 8 ++++++- openshell/v1/oidc/credentials_test.go | 34 +++++++++++++++++++++++++++ openshell/v1/oidc/options.go | 8 +++++-- openshell/v1/oidc/options_test.go | 20 ++++++++++++++++ 4 files changed, 67 insertions(+), 3 deletions(-) diff --git a/openshell/v1/oidc/credentials_auth.go b/openshell/v1/oidc/credentials_auth.go index b662cd5..585f7fd 100644 --- a/openshell/v1/oidc/credentials_auth.go +++ b/openshell/v1/oidc/credentials_auth.go @@ -71,7 +71,13 @@ func (a *clientCredentialsAuth) accessTokenForExchange() (string, error) { return accessToken, nil } - exchangeCtx, cancel := context.WithTimeout(context.Background(), a.cfg.timeout) + // A zero timeout means "no deadline"; only bound the exchange when a + // positive timeout was configured (mirrors Login and DeviceFlow). + exchangeCtx := context.Background() + cancel := context.CancelFunc(func() {}) + if a.cfg.timeout > 0 { + exchangeCtx, cancel = context.WithTimeout(exchangeCtx, a.cfg.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..b8394f7 100644 --- a/openshell/v1/oidc/credentials_test.go +++ b/openshell/v1/oidc/credentials_test.go @@ -308,6 +308,40 @@ func TestClientCredentialsAuthLateFlightReusesCachedToken(t *testing.T) { assert.Equal(t, "cached-token", accessToken) } +// A zero timeout means "no deadline". The exchange context must not be born +// expired, so the token exchange should still succeed. +func TestClientCredentialsAuthZeroTimeoutHasNoDeadline(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) + + auth, err := NewClientCredentialsAuth( + WithIssuer(server.URL), + WithClientID("client"), + WithClientSecret("secret"), + WithTimeout(0), // explicitly no timeout + ) + require.NoError(t, err) + + // The explicit zero timeout must be preserved (not replaced by the default). + require.Zero(t, auth.(*clientCredentialsAuth).cfg.timeout) + + metadata, err := auth.GetRequestMetadata(context.Background()) + require.NoError(t, err) + assert.Equal(t, "Bearer token", metadata["authorization"]) +} + func TestClientCredentialsAuthCancellationDoesNotPoisonSharedExchange(t *testing.T) { resetDiscoveryCache() var server *httptest.Server diff --git a/openshell/v1/oidc/options.go b/openshell/v1/oidc/options.go index 3b7a128..8c7f64a 100644 --- a/openshell/v1/oidc/options.go +++ b/openshell/v1/oidc/options.go @@ -33,6 +33,7 @@ type loginConfig struct { scopesSet bool callbackPort int timeout time.Duration + timeoutSet bool keyboardFlow bool inMemory bool displayFunc func(verificationURL, userCode string) @@ -48,12 +49,14 @@ 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 } } @@ -125,6 +128,7 @@ func WithCallbackPort(port int) LoginOption { func WithTimeout(d time.Duration) LoginOption { return func(c *loginConfig) { c.timeout = d + c.timeoutSet = true } } diff --git a/openshell/v1/oidc/options_test.go b/openshell/v1/oidc/options_test.go index 28d17c0..8af2df7 100644 --- a/openshell/v1/oidc/options_test.go +++ b/openshell/v1/oidc/options_test.go @@ -82,6 +82,26 @@ 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 TestWithKeyboardFlow(t *testing.T) { var cfg loginConfig WithKeyboardFlow()(&cfg) From 17d562d1e6ede94241b074961dc05f1bf02efb8a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roland=20Hu=C3=9F?= Date: Fri, 11 Sep 2026 15:29:44 +0200 Subject: [PATCH 2/9] fix(sdk/go): always request the openid scope in interactive oidc flows MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Login and DeviceLogin authenticate a user, so their requests must be OpenID Connect ones. Both passed the caller's scopes through verbatim, so WithScopes("profile") produced an authorization request without "openid", and buildAuthURL set the parameter unconditionally, so an explicitly-empty list emitted a bare "scope=". Normalize the scopes for both interactive flows: "openid" is placed first and a caller-supplied duplicate is dropped, with the remaining scopes keeping their order. This mirrors build_scopes in crates/openshell-cli/src/oidc_auth.rs, which the Go SDK did not follow. The client credentials grant is left untouched. It has no user and no ID token, so it keeps sending exactly what the caller asked for, matching build_ci_scopes. Also document the WithTimeout contract: the flows all gate on timeout > 0, so any non-positive duration means "no deadline". Signed-off-by: Roland Huß --- openshell/v1/oidc/credentials_test.go | 102 ++++++++++++++++++-------- openshell/v1/oidc/device.go | 3 + openshell/v1/oidc/device_test.go | 78 ++++++++++++++++++++ openshell/v1/oidc/oidc.go | 3 + openshell/v1/oidc/oidc_test.go | 67 +++++++++++++++++ openshell/v1/oidc/options.go | 46 +++++++++++- openshell/v1/oidc/options_test.go | 61 +++++++++++++++ 7 files changed, 329 insertions(+), 31 deletions(-) diff --git a/openshell/v1/oidc/credentials_test.go b/openshell/v1/oidc/credentials_test.go index b8394f7..176d9a4 100644 --- a/openshell/v1/oidc/credentials_test.go +++ b/openshell/v1/oidc/credentials_test.go @@ -308,38 +308,82 @@ func TestClientCredentialsAuthLateFlightReusesCachedToken(t *testing.T) { assert.Equal(t, "cached-token", accessToken) } -// A zero timeout means "no deadline". The exchange context must not be born -// expired, so the token exchange should still succeed. -func TestClientCredentialsAuthZeroTimeoutHasNoDeadline(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) +// A non-positive timeout means "no deadline". The exchange context must not be +// born expired, so the token exchange should still succeed. +func TestClientCredentialsAuthNonPositiveTimeoutHasNoDeadline(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) - auth, err := NewClientCredentialsAuth( - WithIssuer(server.URL), - WithClientID("client"), - WithClientSecret("secret"), - WithTimeout(0), // explicitly no timeout - ) - require.NoError(t, err) + auth, err := NewClientCredentialsAuth( + WithIssuer(server.URL), + WithClientID("client"), + WithClientSecret("secret"), + WithTimeout(timeout), // explicitly no timeout + ) + require.NoError(t, err) - // The explicit zero timeout must be preserved (not replaced by the default). - require.Zero(t, auth.(*clientCredentialsAuth).cfg.timeout) + // The explicit timeout must be preserved (not replaced by the default). + require.Equal(t, timeout, auth.(*clientCredentialsAuth).cfg.timeout) - metadata, err := auth.GetRequestMetadata(context.Background()) - require.NoError(t, err) - assert.Equal(t, "Bearer token", metadata["authorization"]) + metadata, err := auth.GetRequestMetadata(context.Background()) + require.NoError(t, err) + assert.Equal(t, "Bearer token", metadata["authorization"]) + }) + } +} + +// 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) + }) + } } func TestClientCredentialsAuthCancellationDoesNotPoisonSharedExchange(t *testing.T) { diff --git a/openshell/v1/oidc/device.go b/openshell/v1/oidc/device.go index f00ca80..fac85a4 100644 --- a/openshell/v1/oidc/device.go +++ b/openshell/v1/oidc/device.go @@ -49,6 +49,9 @@ func DeviceLogin(ctx context.Context, opts ...LoginOption) (*oauth2.Token, error cfg := &loginConfig{} options.Apply(cfg, opts) cfg.applyDefaults() + // DeviceLogin authenticates a user, so the request must be an OIDC one even + // when the caller supplied its own scopes. + cfg.requireOpenIDScope() if _, hasDeadline := ctx.Deadline(); !hasDeadline && cfg.timeout > 0 { var cancel context.CancelFunc ctx, cancel = context.WithTimeout(ctx, cfg.timeout) diff --git a/openshell/v1/oidc/device_test.go b/openshell/v1/oidc/device_test.go index cb10191..dcd9ecb 100644 --- a/openshell/v1/oidc/device_test.go +++ b/openshell/v1/oidc/device_test.go @@ -120,6 +120,84 @@ func TestDeviceLogin_Success(t *testing.T) { // TestDeviceLogin_MissingIssuer verifies that DeviceLogin returns // ErrOIDCConfig when the issuer is not provided. +// 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() + + var requestedScope string + var scopeSeen atomic.Bool + 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() + requestedScope = r.Form.Get("scope") + scopeSeen.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) + + 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) + require.True(t, scopeSeen.Load(), "device authorization endpoint was not called") + assert.Equal(t, tt.want, requestedScope) + }) + } +} + func TestDeviceLogin_MissingIssuer(t *testing.T) { resetDiscoveryCache() diff --git a/openshell/v1/oidc/oidc.go b/openshell/v1/oidc/oidc.go index d5ed3bf..87d644a 100644 --- a/openshell/v1/oidc/oidc.go +++ b/openshell/v1/oidc/oidc.go @@ -39,6 +39,9 @@ func Login(ctx context.Context, gatewayName string, opts ...LoginOption) (*oauth cfg := &loginConfig{} options.Apply(cfg, opts) cfg.applyDefaults() + // Login authenticates a user, so the request must be an OIDC one even when + // the caller supplied its own scopes. + cfg.requireOpenIDScope() // Apply configured timeout if the caller's context has no deadline. if _, hasDeadline := ctx.Deadline(); !hasDeadline && cfg.timeout > 0 { diff --git a/openshell/v1/oidc/oidc_test.go b/openshell/v1/oidc/oidc_test.go index af717a6..e9ec3b1 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,72 @@ 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")) + }) + } +} + +// 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 8c7f64a..c226e49 100644 --- a/openshell/v1/oidc/options.go +++ b/openshell/v1/oidc/options.go @@ -11,9 +11,13 @@ import ( "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. @@ -61,6 +65,27 @@ func (c *loginConfig) applyDefaults() { } } +// 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) @@ -107,6 +132,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)) @@ -123,8 +154,12 @@ func WithCallbackPort(port int) LoginOption { } } -// WithTimeout sets the maximum duration for interactive login flows. +// WithTimeout sets the maximum duration for a login flow. // The default is 2 minutes. +// +// A non-positive duration (d <= 0) means "no deadline": the flow runs until +// it completes or the caller's context is cancelled. A caller-supplied +// context that already carries a deadline always takes precedence. func WithTimeout(d time.Duration) LoginOption { return func(c *loginConfig) { c.timeout = d @@ -183,6 +218,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 8af2df7..af23b9c 100644 --- a/openshell/v1/oidc/options_test.go +++ b/openshell/v1/oidc/options_test.go @@ -102,6 +102,67 @@ func TestWithTimeout_ExplicitZeroNotOverridden(t *testing.T) { 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) From 951cf8b20142106a7b984dccea36f73d95d6f592 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roland=20Hu=C3=9F?= Date: Fri, 11 Sep 2026 15:55:02 +0200 Subject: [PATCH 3/9] fix(sdk/go): honor gateway-configured oidc scopes in interactive flows MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A gateway's metadata.json carries oidc_scopes, and the Rust CLI feeds it into every flow it starts (commands/gateway.rs passes metadata.oidc_scopes to both the interactive and the client-credentials paths). The Go SDK read the field in resolveClientCredentialsConfig only, so Login and DeviceLogin silently ignored it and always used the built-in defaults. Resolve gateway scopes in both interactive flows using the same rule the client-credentials path already applies: they fill only genuinely-unset scopes, so an explicit WithScopes still wins. The openid normalization now runs after gateway resolution, so scopes coming from metadata.json are normalized too. Behavior change: a gateway with oidc_scopes set in metadata.json now affects Login and DeviceLogin from the Go SDK, matching the CLI. Signed-off-by: Roland Huß --- openshell/v1/oidc/device.go | 14 ++- openshell/v1/oidc/device_test.go | 151 ++++++++++++++++++++++++------- openshell/v1/oidc/oidc.go | 17 +++- openshell/v1/oidc/oidc_test.go | 71 +++++++++++++++ 4 files changed, 212 insertions(+), 41 deletions(-) diff --git a/openshell/v1/oidc/device.go b/openshell/v1/oidc/device.go index fac85a4..905d624 100644 --- a/openshell/v1/oidc/device.go +++ b/openshell/v1/oidc/device.go @@ -49,9 +49,6 @@ func DeviceLogin(ctx context.Context, opts ...LoginOption) (*oauth2.Token, error cfg := &loginConfig{} options.Apply(cfg, opts) cfg.applyDefaults() - // DeviceLogin authenticates a user, so the request must be an OIDC one even - // when the caller supplied its own scopes. - cfg.requireOpenIDScope() if _, hasDeadline := ctx.Deadline(); !hasDeadline && cfg.timeout > 0 { var cancel context.CancelFunc ctx, cancel = context.WithTimeout(ctx, cfg.timeout) @@ -76,8 +73,19 @@ func DeviceLogin(ctx context.Context, opts ...LoginOption) (*oauth2.Token, error } cfg.issuer = gwCfg.OIDCIssuer cfg.clientID = gwCfg.OIDCClientID + // Gateway-configured scopes fill only genuinely-unset scopes, so an + // explicit WithScopes always wins. + if !cfg.scopesSet && gwCfg.OIDCScopes != "" { + cfg.scopes = strings.Fields(gwCfg.OIDCScopes) + cfg.scopesSet = true + } } + // 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 dcd9ecb..505c5d5 100644 --- a/openshell/v1/oidc/device_test.go +++ b/openshell/v1/oidc/device_test.go @@ -149,37 +149,8 @@ func TestDeviceLogin_AlwaysRequestsOpenIDScope(t *testing.T) { t.Run(tt.name, func(t *testing.T) { resetDiscoveryCache() - var requestedScope string - var scopeSeen atomic.Bool - 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() - requestedScope = r.Form.Get("scope") - scopeSeen.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) + scope := &capturedScope{} + srv := setupScopeCapturingDeviceProvider(t, scope) ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() @@ -192,12 +163,126 @@ func TestDeviceLogin_AlwaysRequestsOpenIDScope(t *testing.T) { _, err := DeviceLogin(ctx, opts...) require.NoError(t, err) - require.True(t, scopeSeen.Load(), "device authorization endpoint was not called") - assert.Equal(t, tt.want, requestedScope) + 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 +} + func TestDeviceLogin_MissingIssuer(t *testing.T) { resetDiscoveryCache() diff --git a/openshell/v1/oidc/oidc.go b/openshell/v1/oidc/oidc.go index 87d644a..05c62c1 100644 --- a/openshell/v1/oidc/oidc.go +++ b/openshell/v1/oidc/oidc.go @@ -9,6 +9,7 @@ import ( "io" "os" "slices" + "strings" "golang.org/x/oauth2" @@ -39,9 +40,6 @@ func Login(ctx context.Context, gatewayName string, opts ...LoginOption) (*oauth cfg := &loginConfig{} options.Apply(cfg, opts) cfg.applyDefaults() - // Login authenticates a user, so the request must be an OIDC one even when - // the caller supplied its own scopes. - cfg.requireOpenIDScope() // Apply configured timeout if the caller's context has no deadline. if _, hasDeadline := ctx.Deadline(); !hasDeadline && cfg.timeout > 0 { @@ -55,6 +53,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. @@ -123,8 +124,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 @@ -144,6 +145,12 @@ func resolveOIDCConfig(cfg *loginConfig, gatewayName string) (string, error) { } cfg.issuer = gwCfg.OIDCIssuer cfg.clientID = gwCfg.OIDCClientID + // Gateway-configured scopes fill only genuinely-unset scopes, so an + // explicit WithScopes always wins. + if !cfg.scopesSet && gwCfg.OIDCScopes != "" { + cfg.scopes = strings.Fields(gwCfg.OIDCScopes) + cfg.scopesSet = true + } if tokenDir == "" { tokenDir = gwCfg.Dir } diff --git a/openshell/v1/oidc/oidc_test.go b/openshell/v1/oidc/oidc_test.go index e9ec3b1..491e4f1 100644 --- a/openshell/v1/oidc/oidc_test.go +++ b/openshell/v1/oidc/oidc_test.go @@ -295,6 +295,77 @@ func TestLogin_AlwaysRequestsOpenIDScope(t *testing.T) { } } +// 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() From 24af02612fed0c22b147ce12e0fd91a285912499 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roland=20Hu=C3=9F?= Date: Fri, 6 Nov 2026 08:31:01 +0100 Subject: [PATCH 4/9] fix(oidc): bound background exchanges and apply WithTimeout everywhere MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit NewClientCredentialsAuth runs each token exchange on a context detached from all callers. With WithTimeout(0) or a negative timeout, that exchange had no deadline at all, so a secret provider that blocks on its context would hold the singleflight key forever and every later GetRequestMetadata call would fail with its own context error. Always bound the background exchange, falling back to the 2 minute default when the timeout is not positive. ClientCredentials ignored WithTimeout entirely. Apply it with the same rule as Login and DeviceLogin: a caller deadline wins, and a non-positive timeout means no deadline. Document which entry points honor WithTimeout and how, and fix the comments that named a non-existent DeviceFlow and claimed only a zero timeout means no deadline. Signed-off-by: Roland Huß --- openshell/v1/oidc/credentials.go | 7 +++++ openshell/v1/oidc/credentials_auth.go | 15 ++++++---- openshell/v1/oidc/credentials_test.go | 43 ++++++++++++++++++++++----- openshell/v1/oidc/options.go | 20 ++++++++----- 4 files changed, 64 insertions(+), 21 deletions(-) diff --git a/openshell/v1/oidc/credentials.go b/openshell/v1/oidc/credentials.go index 7f658c1..03b0964 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) } diff --git a/openshell/v1/oidc/credentials_auth.go b/openshell/v1/oidc/credentials_auth.go index 585f7fd..c523986 100644 --- a/openshell/v1/oidc/credentials_auth.go +++ b/openshell/v1/oidc/credentials_auth.go @@ -71,13 +71,16 @@ func (a *clientCredentialsAuth) accessTokenForExchange() (string, error) { return accessToken, nil } - // A zero timeout means "no deadline"; only bound the exchange when a - // positive timeout was configured (mirrors Login and DeviceFlow). - exchangeCtx := context.Background() - cancel := context.CancelFunc(func() {}) - if a.cfg.timeout > 0 { - exchangeCtx, cancel = context.WithTimeout(exchangeCtx, 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 176d9a4..385ca53 100644 --- a/openshell/v1/oidc/credentials_test.go +++ b/openshell/v1/oidc/credentials_test.go @@ -308,9 +308,10 @@ func TestClientCredentialsAuthLateFlightReusesCachedToken(t *testing.T) { assert.Equal(t, "cached-token", accessToken) } -// A non-positive timeout means "no deadline". The exchange context must not be -// born expired, so the token exchange should still succeed. -func TestClientCredentialsAuthNonPositiveTimeoutHasNoDeadline(t *testing.T) { +// 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() @@ -328,20 +329,29 @@ func TestClientCredentialsAuthNonPositiveTimeoutHasNoDeadline(t *testing.T) { })) 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"), - WithClientSecret("secret"), - WithTimeout(timeout), // explicitly no timeout + 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) - // The explicit timeout must be preserved (not replaced by the default). - require.Equal(t, timeout, auth.(*clientCredentialsAuth).cfg.timeout) - 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) }) } } @@ -386,6 +396,23 @@ func TestClientCredentialsScopesAreNotNormalized(t *testing.T) { } } +// 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.Less(t, time.Since(start), 5*time.Second) +} + func TestClientCredentialsAuthCancellationDoesNotPoisonSharedExchange(t *testing.T) { resetDiscoveryCache() var server *httptest.Server diff --git a/openshell/v1/oidc/options.go b/openshell/v1/oidc/options.go index c226e49..7c2d850 100644 --- a/openshell/v1/oidc/options.go +++ b/openshell/v1/oidc/options.go @@ -19,8 +19,10 @@ const scopeOpenID = "openid" // are specified via [WithScopes]. 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 @@ -154,12 +156,16 @@ func WithCallbackPort(port int) LoginOption { } } -// WithTimeout sets the maximum duration for a login flow. -// The default is 2 minutes. +// WithTimeout sets the maximum duration for a flow. The default is 2 minutes. // -// A non-positive duration (d <= 0) means "no deadline": the flow runs until -// it completes or the caller's context is cancelled. A caller-supplied -// context that already carries a deadline always takes precedence. +// [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 From 8e7ae8194735811926023fb398f5678f9b9c56f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roland=20Hu=C3=9F?= Date: Fri, 6 Nov 2026 08:31:11 +0100 Subject: [PATCH 5/9] refactor(oidc): resolve gateway scopes in one place MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Login, DeviceLogin and the client credentials path each carried the same block that fills unset scopes from the gateway's oidc_scopes. Move it into loginConfig.applyGatewayScopes so a change to how oidc_scopes is parsed lands in every flow at once. Signed-off-by: Roland Huß --- openshell/v1/oidc/credentials.go | 5 +---- openshell/v1/oidc/device.go | 7 +------ openshell/v1/oidc/oidc.go | 8 +------- openshell/v1/oidc/options.go | 12 ++++++++++++ 4 files changed, 15 insertions(+), 17 deletions(-) diff --git a/openshell/v1/oidc/credentials.go b/openshell/v1/oidc/credentials.go index 03b0964..a17ab21 100644 --- a/openshell/v1/oidc/credentials.go +++ b/openshell/v1/oidc/credentials.go @@ -73,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. diff --git a/openshell/v1/oidc/device.go b/openshell/v1/oidc/device.go index 905d624..2c35819 100644 --- a/openshell/v1/oidc/device.go +++ b/openshell/v1/oidc/device.go @@ -73,12 +73,7 @@ func DeviceLogin(ctx context.Context, opts ...LoginOption) (*oauth2.Token, error } cfg.issuer = gwCfg.OIDCIssuer cfg.clientID = gwCfg.OIDCClientID - // Gateway-configured scopes fill only genuinely-unset scopes, so an - // explicit WithScopes always wins. - if !cfg.scopesSet && gwCfg.OIDCScopes != "" { - cfg.scopes = strings.Fields(gwCfg.OIDCScopes) - cfg.scopesSet = true - } + cfg.applyGatewayScopes(gwCfg) } // DeviceLogin authenticates a user, so the request must be an OIDC one diff --git a/openshell/v1/oidc/oidc.go b/openshell/v1/oidc/oidc.go index 05c62c1..7cec821 100644 --- a/openshell/v1/oidc/oidc.go +++ b/openshell/v1/oidc/oidc.go @@ -9,7 +9,6 @@ import ( "io" "os" "slices" - "strings" "golang.org/x/oauth2" @@ -145,12 +144,7 @@ func resolveOIDCConfig(cfg *loginConfig, gatewayName string) (string, error) { } cfg.issuer = gwCfg.OIDCIssuer cfg.clientID = gwCfg.OIDCClientID - // Gateway-configured scopes fill only genuinely-unset scopes, so an - // explicit WithScopes always wins. - if !cfg.scopesSet && gwCfg.OIDCScopes != "" { - cfg.scopes = strings.Fields(gwCfg.OIDCScopes) - cfg.scopesSet = true - } + cfg.applyGatewayScopes(gwCfg) if tokenDir == "" { tokenDir = gwCfg.Dir } diff --git a/openshell/v1/oidc/options.go b/openshell/v1/oidc/options.go index 7c2d850..e4f64f5 100644 --- a/openshell/v1/oidc/options.go +++ b/openshell/v1/oidc/options.go @@ -6,6 +6,7 @@ package oidc import ( "context" "io" + "strings" "time" "github.com/ai-openshell/sdk-go/openshell/v1/gateway" @@ -67,6 +68,17 @@ func (c *loginConfig) applyDefaults() { } } +// 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. From 27b075b1d8687acc6063e6db4562d79c21059d90 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roland=20Hu=C3=9F?= Date: Fri, 6 Nov 2026 08:31:11 +0100 Subject: [PATCH 6/9] test(oidc): check the client credentials scope parameter on the wire MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit WithScopes() with no arguments promises that the client credentials grant sends no scope parameter, but only the resolved config was checked. Assert on the token request itself, for unset and explicitly empty scopes, through both ClientCredentials and NewClientCredentialsAuth. Also move the TestDeviceLogin_MissingIssuer doc comment back onto its test; the new scope tests had been inserted between the two. Signed-off-by: Roland Huß --- openshell/v1/oidc/credentials_test.go | 56 +++++++++++++++++++++++++++ openshell/v1/oidc/device_test.go | 4 +- 2 files changed, 58 insertions(+), 2 deletions(-) diff --git a/openshell/v1/oidc/credentials_test.go b/openshell/v1/oidc/credentials_test.go index 385ca53..1945225 100644 --- a/openshell/v1/oidc/credentials_test.go +++ b/openshell/v1/oidc/credentials_test.go @@ -396,6 +396,62 @@ func TestClientCredentialsScopesAreNotNormalized(t *testing.T) { } } +// 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) { diff --git a/openshell/v1/oidc/device_test.go b/openshell/v1/oidc/device_test.go index 505c5d5..9e8cdd8 100644 --- a/openshell/v1/oidc/device_test.go +++ b/openshell/v1/oidc/device_test.go @@ -118,8 +118,6 @@ func TestDeviceLogin_Success(t *testing.T) { assert.Equal(t, "ABCD-1234", displayedCode) } -// TestDeviceLogin_MissingIssuer verifies that DeviceLogin returns -// ErrOIDCConfig when the issuer is not provided. // 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) { @@ -283,6 +281,8 @@ func setupScopeCapturingDeviceProvider(t *testing.T, scope *capturedScope) *http return srv } +// TestDeviceLogin_MissingIssuer verifies that DeviceLogin returns +// ErrOIDCConfig when the issuer is not provided. func TestDeviceLogin_MissingIssuer(t *testing.T) { resetDiscoveryCache() From 62ca0cbeff471761a819d44a10e274edbd44655d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roland=20Hu=C3=9F?= Date: Fri, 6 Nov 2026 08:31:12 +0100 Subject: [PATCH 7/9] docs(oidc): describe the scope and timeout rules MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The options table still described WithTimeout as a plain 2 minute flow timeout and did not say that interactive flows always request openid or that gateway oidc_scopes are honored. Add short Scopes and Timeouts sections that match the doc comments in options.go. Signed-off-by: Roland Huß --- docs/src/api/oidc.md | 33 ++++++++++++++++++++++++++++++--- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/docs/src/api/oidc.md b/docs/src/api/oidc.md index eb40fab..a22ccd3 100644 --- a/docs/src/api/oidc.md +++ b/docs/src/api/oidc.md @@ -92,14 +92,39 @@ 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. + ## Error Handling The package defines sentinel errors for `errors.Is()` matching: @@ -129,7 +154,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 From 0968e55a3710780367890999309ef0350e7a1747 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roland=20Hu=C3=9F?= Date: Wed, 11 Nov 2026 07:43:25 +0100 Subject: [PATCH 8/9] test(oidc): cover the ClientCredentials deadline rules MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The docs promise two more WithTimeout rules for ClientCredentials than the existing bound test checks: a context deadline wins over WithTimeout, and a zero or negative timeout means no deadline. Record the deadline the secret provider sees, as the NewClientCredentialsAuth test does, and assert both. Signed-off-by: Roland Huß --- openshell/v1/oidc/credentials_test.go | 48 +++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/openshell/v1/oidc/credentials_test.go b/openshell/v1/oidc/credentials_test.go index 1945225..5c0ac1a 100644 --- a/openshell/v1/oidc/credentials_test.go +++ b/openshell/v1/oidc/credentials_test.go @@ -469,6 +469,54 @@ func TestClientCredentials_WithTimeoutBoundsExchange(t *testing.T) { assert.Less(t, time.Since(start), 5*time.Second) } +// 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 From 36b32114db2dd1290d2b6af0ee3a15119cf8745b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roland=20Hu=C3=9F?= Date: Wed, 11 Nov 2026 07:43:26 +0100 Subject: [PATCH 9/9] fix(oidc): let client credentials errors match the context error MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Now that ClientCredentials applies WithTimeout, a timeout came back as "token request failed", the same text as a refused connection, and errors.Is(err, context.DeadlineExceeded) was false. Wrap the context error when the context has ended, for the secret provider, the token request and the response read. The underlying cause stays out of the message, so nothing secret leaks. ErrTimeout still covers only the interactive flows; say so in the sentinel table and in the Timeouts section. Signed-off-by: Roland Huß --- docs/src/api/oidc.md | 8 +++++- openshell/v1/oidc/credentials.go | 17 +++++++++--- openshell/v1/oidc/credentials_test.go | 38 +++++++++++++++++++++++++++ 3 files changed, 59 insertions(+), 4 deletions(-) diff --git a/docs/src/api/oidc.md b/docs/src/api/oidc.md index a22ccd3..6e68532 100644 --- a/docs/src/api/oidc.md +++ b/docs/src/api/oidc.md @@ -125,6 +125,12 @@ runs until it completes or the context is cancelled. 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: @@ -135,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 | diff --git a/openshell/v1/oidc/credentials.go b/openshell/v1/oidc/credentials.go index a17ab21..a895d81 100644 --- a/openshell/v1/oidc/credentials.go +++ b/openshell/v1/oidc/credentials.go @@ -92,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 } @@ -139,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_test.go b/openshell/v1/oidc/credentials_test.go index 5c0ac1a..616d02d 100644 --- a/openshell/v1/oidc/credentials_test.go +++ b/openshell/v1/oidc/credentials_test.go @@ -466,9 +466,47 @@ func TestClientCredentials_WithTimeoutBoundsExchange(t *testing.T) { 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) {