Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion openshell/v1/oidc/authcode.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,11 @@ func buildAuthURL(authEndpoint, clientID, redirectURI, state, challenge string,
return u.String()
}

// loopbackHost is where the browser callback listens. The redirect URI
// uses the same host so a resolver that maps localhost to ::1 still
// reaches the IPv4 socket.
const loopbackHost = "127.0.0.1"

// callbackResult carries the authorization code (or error) from the
// callback server to the auth code flow orchestrator.
type callbackResult struct {
Expand Down Expand Up @@ -129,7 +134,7 @@ func startCallbackServer(ctx context.Context, port int, expectedState string) (*
send(callbackResult{code: code})
})

listener, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))
listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", loopbackHost, port))
if err != nil {
return nil, nil, fmt.Errorf("%w: failed to start callback server on port %d: %v", ErrCallbackServer, port, err)
}
Expand Down
8 changes: 6 additions & 2 deletions openshell/v1/oidc/oidc.go
Original file line number Diff line number Diff line change
Expand Up @@ -224,11 +224,15 @@ func loginBrowser(ctx context.Context, cfg *loginConfig, provider *providerConfi
_ = srv.Close()
}()

redirectURI := fmt.Sprintf("http://localhost:%d/callback", port)
redirectURI := fmt.Sprintf("http://%s:%d/callback", loopbackHost, port)
authURL := buildAuthURL(provider.AuthorizationEndpoint, cfg.clientID, redirectURI, state, challenge, cfg.scopes)

// Try to open the browser.
if browserErr := openBrowser(authURL); browserErr != nil {
open := openBrowser
if cfg.browserOpener != nil {
open = cfg.browserOpener
}
if browserErr := open(authURL); browserErr != nil {
// Browser failed, fall back to keyboard flow.
_ = srv.Close()
code, kbErr := loginKeyboard(ctx, cfg, provider, state, challenge)
Expand Down
80 changes: 80 additions & 0 deletions openshell/v1/oidc/oidc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -663,6 +663,86 @@ func TestLoginBrowser_PortBusy_FallbackToKeyboard(t *testing.T) {
assert.Equal(t, "login-access-token", tok.AccessToken)
}

// TestLogin_BrowserRedirectUsesLoopbackIP verifies that the authorization
// URL and the token exchange both use the IPv4 loopback host the callback
// server listens on.
func TestLogin_BrowserRedirectUsesLoopbackIP(t *testing.T) {
resetDiscoveryCache()

var tokenRedirect string
mux := http.NewServeMux()
var srv *httptest.Server
mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
doc := map[string]any{
"issuer": srv.URL,
"authorization_endpoint": srv.URL + "/authorize",
"token_endpoint": srv.URL + "/token",
"code_challenge_methods_supported": []string{"S256"},
}
_ = json.NewEncoder(w).Encode(doc)
})
mux.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) {
require.NoError(t, r.ParseForm())
tokenRedirect = r.Form.Get("redirect_uri")
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(tokenResponseJSON("login-access-token", "login-refresh-token", 3600)))
})
srv = httptest.NewServer(mux)
t.Cleanup(srv.Close)

ln, err := net.Listen("tcp", "127.0.0.1:0")
require.NoError(t, err)
port := ln.Addr().(*net.TCPAddr).Port
require.NoError(t, ln.Close())

wantRedirect := fmt.Sprintf("http://127.0.0.1:%d/callback", port)
var authURL string
opener := func(raw string) error {
authURL = raw
parsed, parseErr := url.Parse(raw)
if parseErr != nil {
return parseErr
}
callback, parseErr := url.Parse(parsed.Query().Get("redirect_uri"))
if parseErr != nil {
return parseErr
}
q := callback.Query()
q.Set("code", "browser-auth-code")
q.Set("state", parsed.Query().Get("state"))
callback.RawQuery = q.Encode()
resp, getErr := http.Get(callback.String())
if getErr != nil {
return getErr
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("callback status %s", resp.Status)
}
return nil
}

ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

tok, err := Login(ctx, "",
WithIssuer(srv.URL),
WithClientID("test-client"),
WithInMemory(),
WithCallbackPort(port),
withBrowserOpener(opener),
withInput(strings.NewReader("")),
)
require.NoError(t, err)
assert.Equal(t, "login-access-token", tok.AccessToken)

parsed, err := url.Parse(authURL)
require.NoError(t, err)
assert.Equal(t, wantRedirect, parsed.Query().Get("redirect_uri"))
assert.Equal(t, wantRedirect, tokenRedirect)
}

// TestLogin_ContextTimeout verifies that a Login with a very short
// timeout returns a timeout-related error.
func TestLogin_ContextTimeout(t *testing.T) {
Expand Down
10 changes: 10 additions & 0 deletions openshell/v1/oidc/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ type loginConfig struct {
input io.Reader // override stdin for keyboard flow
output io.Writer // override stderr for keyboard flow
gatewayResolver func(name string) (*gateway.Config, error) // override gateway.LoadConfig
browserOpener func(url string) error // override browser launch
}

// applyDefaults fills in default values for fields that were not set
Expand Down Expand Up @@ -251,3 +252,12 @@ func withGatewayResolver(fn func(name string) (*gateway.Config, error)) LoginOpt
c.gatewayResolver = fn
}
}

// withBrowserOpener overrides the browser launch used by the authorization
// code flow. Tests use it to capture the authorization URL and complete the
// callback without starting a browser.
func withBrowserOpener(fn func(url string) error) LoginOption {
return func(c *loginConfig) {
c.browserOpener = fn
}
}