Skip to content

Commit 05aa8aa

Browse files
committed
fix(sdk/go): always request the openid scope in interactive oidc flows
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ß <[email protected]>
1 parent b2f982e commit 05aa8aa

7 files changed

Lines changed: 329 additions & 31 deletions

File tree

‎sdk/go/openshell/v1/oidc/credentials_test.go‎

Lines changed: 73 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -308,38 +308,82 @@ func TestClientCredentialsAuthLateFlightReusesCachedToken(t *testing.T) {
308308
assert.Equal(t, "cached-token", accessToken)
309309
}
310310

311-
// A zero timeout means "no deadline". The exchange context must not be born
312-
// expired, so the token exchange should still succeed.
313-
func TestClientCredentialsAuthZeroTimeoutHasNoDeadline(t *testing.T) {
314-
resetDiscoveryCache()
315-
var server *httptest.Server
316-
server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
317-
if r.URL.Path == "/.well-known/openid-configuration" {
318-
_ = json.NewEncoder(w).Encode(map[string]string{
319-
"issuer": server.URL,
320-
"authorization_endpoint": server.URL + "/authorize",
321-
"token_endpoint": server.URL + "/token",
322-
})
323-
return
324-
}
325-
_, _ = w.Write([]byte(tokenResponseJSON("token", "", 3600)))
326-
}))
327-
t.Cleanup(server.Close)
311+
// A non-positive timeout means "no deadline". The exchange context must not be
312+
// born expired, so the token exchange should still succeed.
313+
func TestClientCredentialsAuthNonPositiveTimeoutHasNoDeadline(t *testing.T) {
314+
for _, timeout := range []time.Duration{0, -1 * time.Second} {
315+
t.Run(timeout.String(), func(t *testing.T) {
316+
resetDiscoveryCache()
317+
var server *httptest.Server
318+
server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
319+
if r.URL.Path == "/.well-known/openid-configuration" {
320+
_ = json.NewEncoder(w).Encode(map[string]string{
321+
"issuer": server.URL,
322+
"authorization_endpoint": server.URL + "/authorize",
323+
"token_endpoint": server.URL + "/token",
324+
})
325+
return
326+
}
327+
_, _ = w.Write([]byte(tokenResponseJSON("token", "", 3600)))
328+
}))
329+
t.Cleanup(server.Close)
328330

329-
auth, err := NewClientCredentialsAuth(
330-
WithIssuer(server.URL),
331-
WithClientID("client"),
332-
WithClientSecret("secret"),
333-
WithTimeout(0), // explicitly no timeout
334-
)
335-
require.NoError(t, err)
331+
auth, err := NewClientCredentialsAuth(
332+
WithIssuer(server.URL),
333+
WithClientID("client"),
334+
WithClientSecret("secret"),
335+
WithTimeout(timeout), // explicitly no timeout
336+
)
337+
require.NoError(t, err)
336338

337-
// The explicit zero timeout must be preserved (not replaced by the default).
338-
require.Zero(t, auth.(*clientCredentialsAuth).cfg.timeout)
339+
// The explicit timeout must be preserved (not replaced by the default).
340+
require.Equal(t, timeout, auth.(*clientCredentialsAuth).cfg.timeout)
339341

340-
metadata, err := auth.GetRequestMetadata(context.Background())
341-
require.NoError(t, err)
342-
assert.Equal(t, "Bearer token", metadata["authorization"])
342+
metadata, err := auth.GetRequestMetadata(context.Background())
343+
require.NoError(t, err)
344+
assert.Equal(t, "Bearer token", metadata["authorization"])
345+
})
346+
}
347+
}
348+
349+
// The client credentials grant has no user and no ID token, so "openid" must
350+
// never be forced onto it the way the interactive flows force it.
351+
func TestClientCredentialsScopesAreNotNormalized(t *testing.T) {
352+
tests := []struct {
353+
name string
354+
opts []LoginOption
355+
want []string
356+
}{
357+
{
358+
name: "unset sends no scopes",
359+
opts: nil,
360+
want: nil,
361+
},
362+
{
363+
name: "explicit empty sends no scopes",
364+
opts: []LoginOption{WithScopes()},
365+
want: []string{},
366+
},
367+
{
368+
name: "application scopes are sent verbatim",
369+
opts: []LoginOption{WithScopes("sandbox:read", "sandbox:write")},
370+
want: []string{"sandbox:read", "sandbox:write"},
371+
},
372+
}
373+
374+
for _, tt := range tests {
375+
t.Run(tt.name, func(t *testing.T) {
376+
opts := append([]LoginOption{
377+
WithIssuer("https://issuer.example.com"),
378+
WithClientID("client"),
379+
WithClientSecret("secret"),
380+
}, tt.opts...)
381+
382+
cfg, err := resolveClientCredentialsConfig(opts...)
383+
require.NoError(t, err)
384+
assert.Equal(t, tt.want, cfg.scopes)
385+
})
386+
}
343387
}
344388

345389
func TestClientCredentialsAuthCancellationDoesNotPoisonSharedExchange(t *testing.T) {

‎sdk/go/openshell/v1/oidc/device.go‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,9 @@ func DeviceLogin(ctx context.Context, opts ...LoginOption) (*oauth2.Token, error
4949
cfg := &loginConfig{}
5050
options.Apply(cfg, opts)
5151
cfg.applyDefaults()
52+
// DeviceLogin authenticates a user, so the request must be an OIDC one even
53+
// when the caller supplied its own scopes.
54+
cfg.requireOpenIDScope()
5255
if _, hasDeadline := ctx.Deadline(); !hasDeadline && cfg.timeout > 0 {
5356
var cancel context.CancelFunc
5457
ctx, cancel = context.WithTimeout(ctx, cfg.timeout)

‎sdk/go/openshell/v1/oidc/device_test.go‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,84 @@ func TestDeviceLogin_Success(t *testing.T) {
120120

121121
// TestDeviceLogin_MissingIssuer verifies that DeviceLogin returns
122122
// ErrOIDCConfig when the issuer is not provided.
123+
// DeviceLogin authenticates a user, so the device authorization request must
124+
// carry "openid" on the wire even when the caller supplied its own scopes.
125+
func TestDeviceLogin_AlwaysRequestsOpenIDScope(t *testing.T) {
126+
tests := []struct {
127+
name string
128+
opts []LoginOption
129+
want string
130+
}{
131+
{
132+
name: "unset scopes send the defaults",
133+
opts: nil,
134+
want: "openid profile email",
135+
},
136+
{
137+
name: "explicit empty still sends openid",
138+
opts: []LoginOption{WithScopes()},
139+
want: "openid",
140+
},
141+
{
142+
name: "application scopes gain openid",
143+
opts: []LoginOption{WithScopes("sandbox:read")},
144+
want: "openid sandbox:read",
145+
},
146+
}
147+
148+
for _, tt := range tests {
149+
t.Run(tt.name, func(t *testing.T) {
150+
resetDiscoveryCache()
151+
152+
var requestedScope string
153+
var scopeSeen atomic.Bool
154+
mux := http.NewServeMux()
155+
var srv *httptest.Server
156+
157+
mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, _ *http.Request) {
158+
_ = json.NewEncoder(w).Encode(map[string]any{
159+
"issuer": srv.URL,
160+
"authorization_endpoint": srv.URL + "/authorize",
161+
"token_endpoint": srv.URL + "/token",
162+
"device_authorization_endpoint": srv.URL + "/device",
163+
})
164+
})
165+
mux.HandleFunc("/device", func(w http.ResponseWriter, r *http.Request) {
166+
_ = r.ParseForm()
167+
requestedScope = r.Form.Get("scope")
168+
scopeSeen.Store(true)
169+
_ = json.NewEncoder(w).Encode(map[string]any{
170+
"device_code": "test-device-code",
171+
"user_code": "ABCD-1234",
172+
"verification_uri": "https://example.com/activate",
173+
"expires_in": 300,
174+
"interval": 1,
175+
})
176+
})
177+
mux.HandleFunc("/token", func(w http.ResponseWriter, _ *http.Request) {
178+
_, _ = w.Write([]byte(tokenResponseJSON("device-access-token", "", 3600)))
179+
})
180+
181+
srv = httptest.NewServer(mux)
182+
t.Cleanup(srv.Close)
183+
184+
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
185+
defer cancel()
186+
187+
opts := append([]LoginOption{
188+
WithIssuer(srv.URL),
189+
WithClientID("device-client"),
190+
WithDisplayFunc(func(_, _ string) {}),
191+
}, tt.opts...)
192+
193+
_, err := DeviceLogin(ctx, opts...)
194+
require.NoError(t, err)
195+
require.True(t, scopeSeen.Load(), "device authorization endpoint was not called")
196+
assert.Equal(t, tt.want, requestedScope)
197+
})
198+
}
199+
}
200+
123201
func TestDeviceLogin_MissingIssuer(t *testing.T) {
124202
resetDiscoveryCache()
125203

‎sdk/go/openshell/v1/oidc/oidc.go‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,9 @@ func Login(ctx context.Context, gatewayName string, opts ...LoginOption) (*oauth
3636
cfg := &loginConfig{}
3737
options.Apply(cfg, opts)
3838
cfg.applyDefaults()
39+
// Login authenticates a user, so the request must be an OIDC one even when
40+
// the caller supplied its own scopes.
41+
cfg.requireOpenIDScope()
3942

4043
// Apply configured timeout if the caller's context has no deadline.
4144
if _, hasDeadline := ctx.Deadline(); !hasDeadline && cfg.timeout > 0 {

‎sdk/go/openshell/v1/oidc/oidc_test.go‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import (
1111
"net"
1212
"net/http"
1313
"net/http/httptest"
14+
"net/url"
1415
"os"
1516
"path/filepath"
1617
"strings"
@@ -190,6 +191,72 @@ func TestLogin_KeyboardFlow(t *testing.T) {
190191
assert.Equal(t, "login-access-token", diskTok.AccessToken)
191192
}
192193

194+
// Login authenticates a user, so the authorization URL must carry "openid"
195+
// even when the caller supplied its own scopes. An explicitly-empty scope
196+
// list must never produce a bare "scope=" parameter.
197+
func TestLogin_AlwaysRequestsOpenIDScope(t *testing.T) {
198+
tests := []struct {
199+
name string
200+
opts []LoginOption
201+
want string
202+
}{
203+
{
204+
name: "unset scopes send the defaults",
205+
opts: nil,
206+
want: "openid profile email",
207+
},
208+
{
209+
name: "explicit empty still sends openid",
210+
opts: []LoginOption{WithScopes()},
211+
want: "openid",
212+
},
213+
{
214+
name: "application scopes gain openid",
215+
opts: []LoginOption{WithScopes("sandbox:read")},
216+
want: "openid sandbox:read",
217+
},
218+
}
219+
220+
for _, tt := range tests {
221+
t.Run(tt.name, func(t *testing.T) {
222+
resetDiscoveryCache()
223+
224+
provider := setupMockProvider(t)
225+
var prompt strings.Builder
226+
227+
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
228+
defer cancel()
229+
230+
opts := append([]LoginOption{
231+
WithIssuer(provider.URL),
232+
WithClientID("test-client"),
233+
WithInMemory(),
234+
WithKeyboardFlow(),
235+
withInput(strings.NewReader("keyboard-auth-code\n")),
236+
withOutput(&prompt),
237+
}, tt.opts...)
238+
239+
_, err := Login(ctx, "", opts...)
240+
require.NoError(t, err)
241+
242+
// The keyboard flow prints the authorization URL it would open.
243+
authURL := extractAuthURL(t, prompt.String())
244+
assert.Equal(t, tt.want, authURL.Query().Get("scope"))
245+
})
246+
}
247+
}
248+
249+
// extractAuthURL pulls the authorization URL out of the keyboard-flow prompt.
250+
func extractAuthURL(t *testing.T, prompt string) *url.URL {
251+
t.Helper()
252+
start := strings.Index(prompt, "http")
253+
require.GreaterOrEqual(t, start, 0, "no authorization URL in prompt: %q", prompt)
254+
raw := strings.Fields(prompt[start:])[0]
255+
parsed, err := url.Parse(raw)
256+
require.NoError(t, err)
257+
return parsed
258+
}
259+
193260
// TestLogin_InMemorySkipsPersistence verifies that WithInMemory()
194261
// returns a token without writing to disk.
195262
func TestLogin_InMemorySkipsPersistence(t *testing.T) {

‎sdk/go/openshell/v1/oidc/options.go‎

Lines changed: 44 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,13 @@ import (
1111
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/gateway"
1212
)
1313

14+
// scopeOpenID is the scope that turns an OAuth2 authorization request into
15+
// an OpenID Connect one. Interactive flows always request it.
16+
const scopeOpenID = "openid"
17+
1418
// defaultScopes are the OIDC scopes requested when no custom scopes
1519
// are specified via [WithScopes].
16-
var defaultScopes = []string{"openid", "profile", "email"}
20+
var defaultScopes = []string{scopeOpenID, "profile", "email"}
1721

1822
// defaultTimeout is the maximum duration for interactive login flows
1923
// (browser, keyboard, device code) when no custom timeout is set.
@@ -61,6 +65,27 @@ func (c *loginConfig) applyDefaults() {
6165
}
6266
}
6367

68+
// requireOpenIDScope normalizes the scopes for an interactive flow so the
69+
// request is always an OpenID Connect one. "openid" is placed first and any
70+
// caller-supplied duplicate is dropped; the remaining scopes keep their order.
71+
//
72+
// Interactive flows authenticate a user, and the gateway requires a "sub"
73+
// claim on the resulting token, so "openid" is not optional there. Callers
74+
// remain free to request application scopes such as "sandbox:read". The
75+
// client credentials grant has no user and is left untouched.
76+
//
77+
// This mirrors build_scopes in crates/openshell-cli/src/oidc_auth.rs.
78+
func (c *loginConfig) requireOpenIDScope() {
79+
normalized := make([]string, 0, len(c.scopes)+1)
80+
normalized = append(normalized, scopeOpenID)
81+
for _, scope := range c.scopes {
82+
if scope != scopeOpenID {
83+
normalized = append(normalized, scope)
84+
}
85+
}
86+
c.scopes = normalized
87+
}
88+
6489
// LoginOption configures a login attempt. Use the With* functions to
6590
// create option values.
6691
type LoginOption func(*loginConfig)
@@ -107,6 +132,12 @@ func WithAudience(audience string) LoginOption {
107132

108133
// WithScopes overrides the default scopes (openid, profile, email).
109134
// The provided scopes replace the defaults entirely.
135+
//
136+
// [Login] and [DeviceLogin] always request "openid" in addition to the
137+
// provided scopes, so WithScopes("sandbox:read") sends "openid sandbox:read".
138+
// [ClientCredentials] and [NewClientCredentialsAuth] send exactly what is
139+
// provided, since that grant has no user and no ID token; calling
140+
// WithScopes with no arguments there sends no scope parameter at all.
110141
func WithScopes(scopes ...string) LoginOption {
111142
return func(c *loginConfig) {
112143
c.scopes = make([]string, len(scopes))
@@ -123,8 +154,12 @@ func WithCallbackPort(port int) LoginOption {
123154
}
124155
}
125156

126-
// WithTimeout sets the maximum duration for interactive login flows.
157+
// WithTimeout sets the maximum duration for a login flow.
127158
// The default is 2 minutes.
159+
//
160+
// A non-positive duration (d <= 0) means "no deadline": the flow runs until
161+
// it completes or the caller's context is cancelled. A caller-supplied
162+
// context that already carries a deadline always takes precedence.
128163
func WithTimeout(d time.Duration) LoginOption {
129164
return func(c *loginConfig) {
130165
c.timeout = d
@@ -183,6 +218,13 @@ func withInput(r io.Reader) LoginOption {
183218
}
184219
}
185220

221+
// withOutput overrides the output writer for keyboard flow testing.
222+
func withOutput(w io.Writer) LoginOption {
223+
return func(c *loginConfig) {
224+
c.output = w
225+
}
226+
}
227+
186228
// withGatewayResolver overrides the gateway.LoadConfig function for
187229
// testing. This allows tests to inject a fake gateway resolver
188230
// without filesystem setup.

0 commit comments

Comments
 (0)