From bef27fa33f48e39a4ee293c3330741f3f445a250 Mon Sep 17 00:00:00 2001 From: Harry Anderson Date: Thu, 18 Jun 2026 01:33:49 +0000 Subject: [PATCH 01/18] feat(oidc): add CLI login via device authorization grant + PKCE Extend the existing OIDC operator-UI auth to the CLI using the OAuth 2.0 device authorization grant (RFC 8628), brokered by the node so the provider device_code never reaches the CLI. - Always send PKCE (RFC 7636) on the authorization-code flow; make the OIDC ClientSecret optional so a public/native client works while confidential deployments stay unchanged. - Extract issueSessionFromIDToken so the browser exchange and the device flow share one verification + role-mapping + session-creation path. - Add /oidc-device/start and /oidc-device/poll endpoints and a CLI device-flow cookie authenticator; RemoteLogin branches on OIDC and keeps the local email/password path as break-glass. --- .changeset/oidc-cli-device-flow.md | 7 + core/cmd/app.go | 5 +- core/cmd/oidc_device_auth.go | 201 +++++++++++++++ core/cmd/oidc_device_auth_test.go | 129 ++++++++++ core/cmd/shell.go | 6 + core/cmd/shell_remote.go | 18 ++ core/sessions/oidcauth/device_flow.go | 278 +++++++++++++++++++++ core/sessions/oidcauth/device_flow_test.go | 159 ++++++++++++ core/sessions/oidcauth/helpers_test.go | 1 + core/sessions/oidcauth/oidc.go | 159 ++++++++---- 10 files changed, 911 insertions(+), 52 deletions(-) create mode 100644 .changeset/oidc-cli-device-flow.md create mode 100644 core/cmd/oidc_device_auth.go create mode 100644 core/cmd/oidc_device_auth_test.go create mode 100644 core/sessions/oidcauth/device_flow.go create mode 100644 core/sessions/oidcauth/device_flow_test.go diff --git a/.changeset/oidc-cli-device-flow.md b/.changeset/oidc-cli-device-flow.md new file mode 100644 index 00000000000..09aa9ae70e8 --- /dev/null +++ b/.changeset/oidc-cli-device-flow.md @@ -0,0 +1,7 @@ +--- +"chainlink": minor +--- + +#added Added OIDC login support to the CLI via the OAuth 2.0 device authorization grant (RFC 8628). When a node is configured with `AuthenticationMethod = 'oidc'`, `chainlink admin login` (with no credentials file) now performs a browser-based device flow against the identity provider, brokered by the node. The local email/password path is unchanged and remains available as a break-glass admin. + +#changed The OIDC authorization-code (operator UI) flow now always uses PKCE (RFC 7636). The OIDC `ClientSecret` is now optional: confidential clients still send it, while public clients (required for the device flow) rely on PKCE instead. Existing confidential-client deployments are unaffected. diff --git a/core/cmd/app.go b/core/cmd/app.go index ee0e378ecb1..97bc7b1b289 100644 --- a/core/cmd/app.go +++ b/core/cmd/app.go @@ -112,7 +112,8 @@ func NewApp(s *Shell) *cli.App { insecureSkipVerify := c.Bool("insecure-skip-verify") clientOpts := ClientOpts{RemoteNodeURL: *remoteNodeURL, InsecureSkipVerify: insecureSkipVerify} - cookieAuth := NewSessionCookieAuthenticator(clientOpts, DiskCookieStore{Config: cookieJar}, s.Logger) + cookieStore := DiskCookieStore{Config: cookieJar} + cookieAuth := NewSessionCookieAuthenticator(clientOpts, cookieStore, s.Logger) sessionRequestBuilder := NewFileSessionRequestBuilder(s.Logger) credentialsFile := c.String("admin-credentials-file") @@ -124,6 +125,8 @@ func NewApp(s *Shell) *cli.App { s.HTTP = NewAuthenticatedHTTPClient(s.Logger, clientOpts, cookieAuth, sr) s.CookieAuthenticator = cookieAuth s.FileSessionRequestBuilder = sessionRequestBuilder + s.clientOpts = clientOpts + s.cookieStore = cookieStore // Allow for initServerConfig to be called if the flag is provided. if c.Bool("applyInitServerConfig") { diff --git a/core/cmd/oidc_device_auth.go b/core/cmd/oidc_device_auth.go new file mode 100644 index 00000000000..bfda0d10162 --- /dev/null +++ b/core/cmd/oidc_device_auth.go @@ -0,0 +1,201 @@ +package cmd + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "time" + + "github.com/pkg/errors" + + "github.com/smartcontractkit/chainlink/v2/core/logger" + "github.com/smartcontractkit/chainlink/v2/core/web" +) + +// OIDC device authorization grant client for the CLI. +// +// When a node is configured with AuthenticationMethod = 'oidc', the local +// users table only holds break-glass admins; interactive operators authenticate +// through the identity provider. The CLI cannot drive a browser redirect, so it +// uses the RFC 8628 device flow the node brokers at /oidc-device/start and +// /oidc-device/poll. The CLI never talks to the identity provider directly and +// never holds any token; it receives only an opaque handle and, on success, the +// same session cookie the browser flow produces. + +// oidcDeviceStartResponse mirrors oidcauth.DeviceStartResponse. +type oidcDeviceStartResponse struct { + DeviceHandle string `json:"device_handle"` + UserCode string `json:"user_code"` + VerificationURI string `json:"verification_uri"` + VerificationURIComplete string `json:"verification_uri_complete,omitempty"` + ExpiresIn int64 `json:"expires_in"` + Interval int64 `json:"interval"` +} + +// oidcDevicePollResponse mirrors oidcauth.DevicePollResponse. +type oidcDevicePollResponse struct { + Status string `json:"status"` + Message string `json:"message,omitempty"` +} + +// OIDCDeviceCookieAuthenticator obtains a session cookie via the node-brokered +// device authorization flow and persists it to the same cookie store the +// password authenticator uses. +type OIDCDeviceCookieAuthenticator struct { + config ClientOpts + store CookieStore + lggr logger.SugaredLogger + // out is where user-facing prompts are written. Defaults to os.Stdout in + // production; overridable in tests. + out io.Writer +} + +func NewOIDCDeviceCookieAuthenticator(config ClientOpts, store CookieStore, out io.Writer, lggr logger.Logger) *OIDCDeviceCookieAuthenticator { + return &OIDCDeviceCookieAuthenticator{ + config: config, + store: store, + lggr: logger.Sugared(lggr), + out: out, + } +} + +// NodeHasOIDCEnabled probes the node's unauthenticated /oidc-enabled endpoint to +// decide whether the device flow applies. A non-OIDC node 404s the route. +func NodeHasOIDCEnabled(ctx context.Context, config ClientOpts, lggr logger.Logger) bool { + client := newHttpClient(lggr, config.InsecureSkipVerify) + u := config.RemoteNodeURL.String() + "/oidc-enabled" + req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil) + if err != nil { + return false + } + resp, err := client.Do(req) + if err != nil { + return false + } + defer resp.Body.Close() + return resp.StatusCode == http.StatusOK +} + +// Login runs the full device flow: start, prompt the operator, poll until the +// node reports completion, then save the returned session cookie. +func (o *OIDCDeviceCookieAuthenticator) Login(ctx context.Context) error { + start, err := o.start(ctx) + if err != nil { + return err + } + + o.promptUser(start) + + interval := time.Duration(start.Interval) * time.Second + if interval <= 0 { + interval = 5 * time.Second + } + deadline := time.Now().Add(time.Duration(start.ExpiresIn) * time.Second) + + ticker := time.NewTicker(interval) + defer ticker.Stop() + + for { + select { + case <-ctx.Done(): + return ctx.Err() + case <-ticker.C: + if time.Now().After(deadline) { + return errors.New("device authorization timed out before approval") + } + cookie, status, perr := o.poll(ctx, start.DeviceHandle) + if perr != nil { + return perr + } + switch status { + case "complete": + if cookie == nil { + return errors.New("node reported login complete but returned no session cookie") + } + return o.store.Save(cookie) + case "denied": + return errors.New("device authorization was denied or expired") + default: // "pending" + continue + } + } + } +} + +func (o *OIDCDeviceCookieAuthenticator) start(ctx context.Context) (*oidcDeviceStartResponse, error) { + u := o.config.RemoteNodeURL.String() + "/oidc-device/start" + req, err := http.NewRequestWithContext(ctx, http.MethodPost, u, nil) + if err != nil { + return nil, err + } + client := newHttpClient(o.lggr, o.config.InsecureSkipVerify) + resp, err := client.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + body, _ := io.ReadAll(resp.Body) + if resp.StatusCode != http.StatusOK { + return nil, errors.Errorf("failed to start device authorization (status %d): %s", resp.StatusCode, string(body)) + } + var sr oidcDeviceStartResponse + if err := json.Unmarshal(body, &sr); err != nil { + return nil, errors.Wrap(err, "failed to parse device authorization response") + } + return &sr, nil +} + +// poll asks the node for the flow status. On "complete" the node sets the +// session cookie on the response, which is extracted and returned. +func (o *OIDCDeviceCookieAuthenticator) poll(ctx context.Context, handle string) (*http.Cookie, string, error) { + b, err := json.Marshal(map[string]string{"device_handle": handle}) + if err != nil { + return nil, "", err + } + u := o.config.RemoteNodeURL.String() + "/oidc-device/poll" + req, err := http.NewRequestWithContext(ctx, http.MethodPost, u, bytes.NewReader(b)) + if err != nil { + return nil, "", err + } + req.Header.Set("Content-Type", "application/json") + client := newHttpClient(o.lggr, o.config.InsecureSkipVerify) + resp, err := client.Do(req) + if err != nil { + return nil, "", err + } + defer resp.Body.Close() + + body, _ := io.ReadAll(resp.Body) + if resp.StatusCode == http.StatusNotFound { + return nil, "denied", nil + } + if resp.StatusCode != http.StatusOK { + return nil, "", errors.Errorf("device poll failed (status %d): %s", resp.StatusCode, string(body)) + } + var pr oidcDevicePollResponse + if err := json.Unmarshal(body, &pr); err != nil { + return nil, "", errors.Wrap(err, "failed to parse device poll response") + } + if pr.Status == "complete" { + return web.FindSessionCookie(resp.Cookies()), "complete", nil + } + return nil, pr.Status, nil +} + +func (o *OIDCDeviceCookieAuthenticator) promptUser(start *oidcDeviceStartResponse) { + uri := start.VerificationURIComplete + if uri == "" { + uri = start.VerificationURI + } + fmt.Fprintln(o.out, "To log in, open the following URL in a browser and sign in with your identity provider:") + fmt.Fprintf(o.out, "\n %s\n\n", uri) + if start.VerificationURIComplete == "" { + fmt.Fprintf(o.out, "When prompted, enter the code: %s\n\n", start.UserCode) + } else { + fmt.Fprintf(o.out, "Verify the code shown matches: %s\n\n", start.UserCode) + } + fmt.Fprintln(o.out, "Waiting for approval...") +} diff --git a/core/cmd/oidc_device_auth_test.go b/core/cmd/oidc_device_auth_test.go new file mode 100644 index 00000000000..d52cf30b758 --- /dev/null +++ b/core/cmd/oidc_device_auth_test.go @@ -0,0 +1,129 @@ +package cmd_test + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "net/url" + "sync/atomic" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smartcontractkit/chainlink/v2/core/cmd" + "github.com/smartcontractkit/chainlink/v2/core/logger" +) + +// mockNode stands in for an OIDC-enabled chainlink node, serving the three +// endpoints the CLI device flow touches. +type mockNode struct { + oidcEnabled bool + pollsPending int32 // number of "pending" polls to return before "complete" + denyAfter bool // if true, return "denied" instead of completing +} + +func (m *mockNode) handler(t *testing.T) http.Handler { + mux := http.NewServeMux() + mux.HandleFunc("/oidc-enabled", func(w http.ResponseWriter, r *http.Request) { + if !m.oidcEnabled { + w.WriteHeader(http.StatusNotFound) + return + } + w.WriteHeader(http.StatusOK) + }) + mux.HandleFunc("/oidc-device/start", func(w http.ResponseWriter, r *http.Request) { + require.Equal(t, http.MethodPost, r.Method) + _ = json.NewEncoder(w).Encode(map[string]any{ + "device_handle": "test-handle", + "user_code": "WDJB-MJHT", + "verification_uri": "https://sso.example.com/activate", + "verification_uri_complete": "https://sso.example.com/activate?user_code=WDJB-MJHT", + "expires_in": 300, + "interval": 1, + }) + }) + mux.HandleFunc("/oidc-device/poll", func(w http.ResponseWriter, r *http.Request) { + var req map[string]string + require.NoError(t, json.NewDecoder(r.Body).Decode(&req)) + assert.Equal(t, "test-handle", req["device_handle"], "CLI must echo back the opaque handle") + + if atomic.AddInt32(&m.pollsPending, -1) >= 0 { + _ = json.NewEncoder(w).Encode(map[string]string{"status": "pending"}) + return + } + if m.denyAfter { + _ = json.NewEncoder(w).Encode(map[string]string{"status": "denied", "message": "expired"}) + return + } + http.SetCookie(w, &http.Cookie{Name: "clsession", Value: "abc123", Path: "/"}) + _ = json.NewEncoder(w).Encode(map[string]string{"status": "complete"}) + }) + return mux +} + +func newClientOpts(t *testing.T, srv *httptest.Server) cmd.ClientOpts { + u, err := url.Parse(srv.URL) + require.NoError(t, err) + return cmd.ClientOpts{RemoteNodeURL: *u} +} + +func TestNodeHasOIDCEnabled(t *testing.T) { + t.Parallel() + lggr := logger.TestLogger(t) + + enabled := &mockNode{oidcEnabled: true} + srv := httptest.NewServer(enabled.handler(t)) + defer srv.Close() + assert.True(t, cmd.NodeHasOIDCEnabled(context.Background(), newClientOpts(t, srv), lggr)) + + disabled := &mockNode{oidcEnabled: false} + srv2 := httptest.NewServer(disabled.handler(t)) + defer srv2.Close() + assert.False(t, cmd.NodeHasOIDCEnabled(context.Background(), newClientOpts(t, srv2), lggr)) +} + +func TestOIDCDeviceLogin_Success(t *testing.T) { + t.Parallel() + node := &mockNode{oidcEnabled: true, pollsPending: 2} + srv := httptest.NewServer(node.handler(t)) + defer srv.Close() + + store := &cmd.MemoryCookieStore{} + var out bytes.Buffer + auth := cmd.NewOIDCDeviceCookieAuthenticator(newClientOpts(t, srv), store, &out, logger.TestLogger(t)) + + require.NoError(t, auth.Login(context.Background())) + + // The session cookie produced by the node must land in the cookie jar. + cookie, err := store.Retrieve() + require.NoError(t, err) + require.NotNil(t, cookie) + assert.Equal(t, "clsession", cookie.Name) + assert.Equal(t, "abc123", cookie.Value) + + // The operator must be shown the verification URI and code. + assert.Contains(t, out.String(), "https://sso.example.com/activate") + assert.Contains(t, out.String(), "WDJB-MJHT") +} + +func TestOIDCDeviceLogin_Denied(t *testing.T) { + t.Parallel() + node := &mockNode{oidcEnabled: true, pollsPending: 1, denyAfter: true} + srv := httptest.NewServer(node.handler(t)) + defer srv.Close() + + store := &cmd.MemoryCookieStore{} + var out bytes.Buffer + auth := cmd.NewOIDCDeviceCookieAuthenticator(newClientOpts(t, srv), store, &out, logger.TestLogger(t)) + + err := auth.Login(context.Background()) + require.Error(t, err) + assert.Contains(t, err.Error(), "denied") + + // On denial nothing must be written to the cookie jar. + cookie, _ := store.Retrieve() + assert.Nil(t, cookie) +} diff --git a/core/cmd/shell.go b/core/cmd/shell.go index 9f2f36fed74..cc64419bf67 100644 --- a/core/cmd/shell.go +++ b/core/cmd/shell.go @@ -236,6 +236,12 @@ type Shell struct { ChangePasswordPrompter ChangePasswordPrompter PasswordPrompter PasswordPrompter + // clientOpts and cookieStore are retained so RemoteLogin can construct an + // OIDC device-flow authenticator on demand, reusing the same node URL and + // cookie jar as the password authenticator. + clientOpts ClientOpts + cookieStore CookieStore + configFiles []string configFilesIsSet bool secretsFiles []string diff --git a/core/cmd/shell_remote.go b/core/cmd/shell_remote.go index dcecbd7c05d..5cc61cdabdc 100644 --- a/core/cmd/shell_remote.go +++ b/core/cmd/shell_remote.go @@ -174,8 +174,26 @@ func (s *Shell) getPage(requestURI string, page int, model any) (err error) { } // RemoteLogin creates a cookie session to run remote commands. +// +// With no credentials file and an OIDC-enabled node, login runs the browser +// device authorization flow against the identity provider. A supplied +// credentials file always uses the local email/password path (the OIDC +// break-glass admin), so automation and recovery keep working unchanged. func (s *Shell) RemoteLogin(c *cli.Context) error { lggr := s.Logger.Named("RemoteLogin") + + if c.String("file") == "" && NodeHasOIDCEnabled(s.ctx(), s.clientOpts, lggr) { + auth := NewOIDCDeviceCookieAuthenticator(s.clientOpts, s.cookieStore, os.Stdout, lggr) + if err := auth.Login(s.ctx()); err != nil { + return s.errorOut(err) + } + if err := s.checkRemoteBuildCompatibility(lggr, c.Bool("bypass-version-check"), static.Version, static.Sha); err != nil { + return s.errorOut(err) + } + fmt.Println("Successfully Logged In.") + return nil + } + sessionRequest, err := s.buildSessionRequest(c.String("file")) if err != nil { return s.errorOut(err) diff --git a/core/sessions/oidcauth/device_flow.go b/core/sessions/oidcauth/device_flow.go new file mode 100644 index 00000000000..6ad20001802 --- /dev/null +++ b/core/sessions/oidcauth/device_flow.go @@ -0,0 +1,278 @@ +package oidcauth + +import ( + "context" + "crypto/rand" + "encoding/base64" + "errors" + "io" + "net/http" + "sync" + "time" + + "github.com/gin-contrib/sessions" + "github.com/gin-gonic/gin" + "golang.org/x/oauth2" + + "github.com/smartcontractkit/chainlink/v2/core/logger/audit" + webauth "github.com/smartcontractkit/chainlink/v2/core/web/auth" +) + +// Device authorization grant (RFC 8628) for headless clients (the CLI). +// +// The node brokers the flow as a confidential or public OAuth client: it calls +// the provider's device authorization endpoint, hands the user-facing code and +// verification URI back to the CLI, then polls the provider's token endpoint on +// the CLI's behalf. The raw provider device_code never leaves the node; the CLI +// only ever holds an opaque, single-use handle minted here. +// +// Polling the provider runs in one background goroutine per flow, driven by +// oauth2's DeviceAccessToken which honours the server-mandated interval and +// slow_down backoff. The CLI's poll to the node is therefore decoupled from the +// node's poll to the provider: no matter how fast the CLI asks, the node never +// exceeds the provider's cadence. + +const ( + // maxConcurrentDeviceFlows bounds the in-memory store so unauthenticated + // callers cannot exhaust memory or fan out provider load without limit. + maxConcurrentDeviceFlows = 100 + // deviceHandleBytes is the entropy of the opaque handle returned to the CLI. + deviceHandleBytes = 32 // 256 bits +) + +var ( + errTooManyDeviceFlows = errors.New("too many concurrent device authorization flows in progress") + errUnknownDeviceFlow = errors.New("unknown or expired device authorization flow") +) + +// deviceFlowState is the per-flow state held server-side while a device +// authorization is pending. Exactly one background goroutine writes the +// terminal fields (sessionID/email/err/done); readers take the mutex. +type deviceFlowState struct { + mu sync.Mutex + expiresAt time.Time + done bool + sessionID string + email string + err error +} + +// deviceFlowStore maps opaque handles to pending flows. Handles are single-use: +// a successful poll consumes the flow. Expired flows are swept lazily. +type deviceFlowStore struct { + mu sync.Mutex + flows map[string]*deviceFlowState +} + +func newDeviceFlowStore() *deviceFlowStore { + return &deviceFlowStore{flows: make(map[string]*deviceFlowState)} +} + +func (s *deviceFlowStore) sweepLocked(now time.Time) { + for h, f := range s.flows { + f.mu.Lock() + expired := now.After(f.expiresAt) + f.mu.Unlock() + if expired { + delete(s.flows, h) + } + } +} + +// add stores a flow under a fresh handle, enforcing the concurrency cap. The +// caller must not have logged or persisted the provider device_code. +func (s *deviceFlowStore) add(handle string, f *deviceFlowState) error { + s.mu.Lock() + defer s.mu.Unlock() + s.sweepLocked(time.Now()) + if len(s.flows) >= maxConcurrentDeviceFlows { + return errTooManyDeviceFlows + } + s.flows[handle] = f + return nil +} + +func (s *deviceFlowStore) get(handle string) (*deviceFlowState, bool) { + s.mu.Lock() + defer s.mu.Unlock() + f, ok := s.flows[handle] + return f, ok +} + +func (s *deviceFlowStore) remove(handle string) { + s.mu.Lock() + defer s.mu.Unlock() + delete(s.flows, handle) +} + +// generateDeviceHandle returns a URL-safe 256-bit random handle. It is the only +// device-flow identifier the CLI ever sees; the provider device_code stays +// server-side. +func (oi *oidcAuthenticator) generateDeviceHandle() (string, error) { + b := make([]byte, deviceHandleBytes) + if _, err := io.ReadFull(rand.Reader, b); err != nil { + return "", err + } + return base64.RawURLEncoding.EncodeToString(b), nil +} + +// DeviceStartResponse is the CLI-facing payload that begins a device flow. +// It deliberately omits the provider device_code. +type DeviceStartResponse struct { + DeviceHandle string `json:"device_handle"` + UserCode string `json:"user_code"` + VerificationURI string `json:"verification_uri"` + VerificationURIComplete string `json:"verification_uri_complete,omitempty"` + ExpiresIn int64 `json:"expires_in"` + Interval int64 `json:"interval"` +} + +// DevicePollRequest is the CLI's request to check on a pending flow. +type DevicePollRequest struct { + DeviceHandle string `json:"device_handle" binding:"required"` +} + +// DevicePollResponse reports flow status to the CLI. Status is one of +// "pending", "complete", or "denied". On "complete" the session cookie is set +// on the response; the body carries no token material. +type DevicePollResponse struct { + Status string `json:"status"` + Message string `json:"message,omitempty"` +} + +// handleDeviceStart begins a device authorization flow. Unauthenticated, like +// the browser /oidc-login route: it only initiates the provider handshake. +func (oi *oidcAuthenticator) handleDeviceStart(c *gin.Context) { + ctx := context.Background() + da, err := oi.oauth2Config.DeviceAuth(ctx) + if err != nil { + oi.lggr.Errorf("device authorization request failed: %v", err) + c.JSON(http.StatusBadGateway, gin.H{"error": "Failed to start device authorization"}) + return + } + + handle, err := oi.generateDeviceHandle() + if err != nil { + oi.lggr.Errorf("failed to generate device handle: %v", err) + c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to start device authorization"}) + return + } + + expiry := da.Expiry + if expiry.IsZero() { + // Per RFC 8628 the provider should send expires_in; fall back to a + // conservative default so a malformed response cannot create an + // unbounded flow. + expiry = time.Now().Add(5 * time.Minute) + } + state := &deviceFlowState{expiresAt: expiry} + + if err := oi.deviceFlows.add(handle, state); err != nil { + oi.lggr.Warnf("refusing new device flow: %v", err) + c.JSON(http.StatusTooManyRequests, gin.H{"error": err.Error()}) + return + } + + // Poll the provider in the background. DeviceAccessToken blocks until the + // user approves, denies, or the code expires, internally respecting the + // provider's interval and slow_down. Bounded by the device-code expiry. + go oi.pollDeviceToken(handle, state, da) + + interval := da.Interval + if interval == 0 { + interval = 5 // RFC 8628 default + } + c.JSON(http.StatusOK, DeviceStartResponse{ + DeviceHandle: handle, + UserCode: da.UserCode, + VerificationURI: da.VerificationURI, + VerificationURIComplete: da.VerificationURIComplete, + ExpiresIn: int64(time.Until(expiry).Seconds()), + Interval: interval, + }) +} + +// pollDeviceToken runs the blocking provider poll for one flow and records the +// terminal result. On success it verifies the id_token and creates a session +// through the same issueSessionFromIDToken path the browser flow uses. +func (oi *oidcAuthenticator) pollDeviceToken(handle string, state *deviceFlowState, da *oauth2.DeviceAuthResponse) { + ctx, cancel := context.WithDeadline(context.Background(), state.expiresAt) + defer cancel() + + token, err := oi.oauth2Config.DeviceAccessToken(ctx, da) + if err != nil { + oi.finishDeviceFlow(state, "", "", err) + return + } + + rawIDToken, ok := token.Extra("id_token").(string) + if !ok { + oi.finishDeviceFlow(state, "", "", errors.New("missing id_token in device token response")) + return + } + + sessionID, email, err := oi.issueSessionFromIDToken(ctx, rawIDToken) + oi.finishDeviceFlow(state, sessionID, email, err) +} + +func (oi *oidcAuthenticator) finishDeviceFlow(state *deviceFlowState, sessionID, email string, err error) { + state.mu.Lock() + state.done = true + state.sessionID = sessionID + state.email = email + state.err = err + state.mu.Unlock() + if err != nil { + oi.lggr.Errorf("device authorization flow failed: %v", err) + } +} + +// handleDevicePoll reports the status of a pending flow to the CLI and, once +// complete, sets the session cookie. The handle is single-use: a completed flow +// is removed after its cookie is issued or its failure reported. +func (oi *oidcAuthenticator) handleDevicePoll(c *gin.Context) { + var req DevicePollRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, DevicePollResponse{Status: "denied", Message: "Invalid request"}) + return + } + + state, ok := oi.deviceFlows.get(req.DeviceHandle) + if !ok { + c.JSON(http.StatusNotFound, DevicePollResponse{Status: "denied", Message: errUnknownDeviceFlow.Error()}) + return + } + + state.mu.Lock() + done := state.done + sessionID := state.sessionID + email := state.email + flowErr := state.err + state.mu.Unlock() + + if !done { + c.JSON(http.StatusOK, DevicePollResponse{Status: "pending"}) + return + } + + // Terminal: consume the handle regardless of outcome. + oi.deviceFlows.remove(req.DeviceHandle) + + if flowErr != nil { + c.JSON(http.StatusOK, DevicePollResponse{Status: "denied", Message: "Authorization was not completed"}) + return + } + + // Bind the session ID to the CLI's cookie jar, exactly as the browser flow + // does on a successful exchange. + ginSession := sessions.Default(c) + ginSession.Set(webauth.SessionIDKey, sessionID) + if err := ginSession.Save(); err != nil { + oi.lggr.Errorf("failed to save device flow session: %v", err) + c.JSON(http.StatusInternalServerError, DevicePollResponse{Status: "denied", Message: "Failed to establish session"}) + return + } + + oi.auditLogger.Audit(audit.AuthLoginSuccessNo2FA, map[string]any{"email": email, "method": "device_flow"}) + c.JSON(http.StatusOK, DevicePollResponse{Status: "complete"}) +} diff --git a/core/sessions/oidcauth/device_flow_test.go b/core/sessions/oidcauth/device_flow_test.go new file mode 100644 index 00000000000..5234115bd0b --- /dev/null +++ b/core/sessions/oidcauth/device_flow_test.go @@ -0,0 +1,159 @@ +package oidcauth + +import ( + "errors" + "strconv" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smartcontractkit/chainlink/v2/core/logger" +) + +func TestDeviceFlowStore_AddGetRemove(t *testing.T) { + s := newDeviceFlowStore() + + state := &deviceFlowState{expiresAt: time.Now().Add(time.Minute)} + require.NoError(t, s.add("handle-1", state)) + + got, ok := s.get("handle-1") + require.True(t, ok) + assert.Same(t, state, got) + + s.remove("handle-1") + _, ok = s.get("handle-1") + assert.False(t, ok, "handle must be single-use: gone after remove") +} + +func TestDeviceFlowStore_ConcurrencyCap(t *testing.T) { + s := newDeviceFlowStore() + for i := 0; i < maxConcurrentDeviceFlows; i++ { + require.NoError(t, s.add(handleN(i), &deviceFlowState{expiresAt: time.Now().Add(time.Minute)})) + } + // One past the cap must be refused, not silently dropped. + err := s.add("overflow", &deviceFlowState{expiresAt: time.Now().Add(time.Minute)}) + require.ErrorIs(t, err, errTooManyDeviceFlows) +} + +func TestDeviceFlowStore_ExpiredSweptOnAdd(t *testing.T) { + s := newDeviceFlowStore() + // Fill with already-expired flows. + for i := 0; i < maxConcurrentDeviceFlows; i++ { + require.NoError(t, s.add(handleN(i), &deviceFlowState{expiresAt: time.Now().Add(-time.Second)})) + } + // A fresh add sweeps the expired entries, making room rather than erroring. + require.NoError(t, s.add("fresh", &deviceFlowState{expiresAt: time.Now().Add(time.Minute)})) + _, ok := s.get("fresh") + assert.True(t, ok) +} + +func TestGenerateDeviceHandle_UniqueAndURLSafe(t *testing.T) { + oi := &oidcAuthenticator{} + seen := make(map[string]struct{}) + for i := 0; i < 1000; i++ { + h, err := oi.generateDeviceHandle() + require.NoError(t, err) + require.NotEmpty(t, h) + // RawURLEncoding of 32 bytes -> 43 chars, no padding, URL-safe alphabet. + assert.Len(t, h, 43) + assert.NotContains(t, h, "+") + assert.NotContains(t, h, "/") + assert.NotContains(t, h, "=") + _, dup := seen[h] + require.False(t, dup, "handle collision is a security failure") + seen[h] = struct{}{} + } +} + +func TestFinishDeviceFlow_RecordsTerminalState(t *testing.T) { + oi := &oidcAuthenticator{lggr: logger.TestLogger(t)} + + okState := &deviceFlowState{expiresAt: time.Now().Add(time.Minute)} + oi.finishDeviceFlow(okState, "sess-1", "user@example.com", nil) + okState.mu.Lock() + assert.True(t, okState.done) + assert.Equal(t, "sess-1", okState.sessionID) + assert.Equal(t, "user@example.com", okState.email) + assert.NoError(t, okState.err) + okState.mu.Unlock() + + errState := &deviceFlowState{expiresAt: time.Now().Add(time.Minute)} + wantErr := errors.New("denied") + oi.finishDeviceFlow(errState, "", "", wantErr) + errState.mu.Lock() + assert.True(t, errState.done) + assert.Empty(t, errState.sessionID) + assert.ErrorIs(t, errState.err, wantErr) + errState.mu.Unlock() +} + +// TestDeviceFlowState_ConcurrentAccess exercises the writer/reader lock that +// separates the background poll goroutine from the CLI poll handler. +func TestDeviceFlowState_ConcurrentAccess(t *testing.T) { + oi := &oidcAuthenticator{lggr: logger.TestLogger(t)} + state := &deviceFlowState{expiresAt: time.Now().Add(time.Minute)} + + var wg sync.WaitGroup + wg.Add(2) + go func() { + defer wg.Done() + oi.finishDeviceFlow(state, "s", "e", nil) + }() + go func() { + defer wg.Done() + for i := 0; i < 100; i++ { + state.mu.Lock() + _ = state.done + state.mu.Unlock() + } + }() + wg.Wait() +} + +func handleN(i int) string { + return "h-" + strconv.Itoa(i) +} + +// mutableConfig embeds the default *TestConfig and lets a test override the one +// field under test. TestConfig's methods use a pointer receiver, so embed the +// pointer to satisfy config.OIDC. +type mutableConfig struct { + *TestConfig + clientSecret *string + clientID *string +} + +func (m mutableConfig) ClientSecret() string { + if m.clientSecret != nil { + return *m.clientSecret + } + return m.TestConfig.ClientSecret() +} + +func (m mutableConfig) ClientID() string { + if m.clientID != nil { + return *m.clientID + } + return m.TestConfig.ClientID() +} + +func TestValidateOIDCConfig_SecretOptional(t *testing.T) { + empty := "" + base := &TestConfig{} + + // Public client: empty secret must be accepted (this is the change that + // lets a Native app + PKCE work for the CLI device flow). + require.NoError(t, validateOIDCConfig(mutableConfig{TestConfig: base, clientSecret: &empty}), + "empty ClientSecret must be allowed for public/PKCE clients") + + // Confidential client: a secret is still fine (backwards compatibility). + require.NoError(t, validateOIDCConfig(mutableConfig{TestConfig: base}), + "a populated ClientSecret must still be accepted") + + // ClientID, by contrast, remains required. + require.Error(t, validateOIDCConfig(mutableConfig{TestConfig: base, clientID: &empty}), + "empty ClientID must still be rejected") +} diff --git a/core/sessions/oidcauth/helpers_test.go b/core/sessions/oidcauth/helpers_test.go index 8d246304ee9..f5761aaa284 100644 --- a/core/sessions/oidcauth/helpers_test.go +++ b/core/sessions/oidcauth/helpers_test.go @@ -53,6 +53,7 @@ func NewTestOIDCAuthenticator( oauth2Config: oauth2Config, lggr: logger.Sugared(lggr).Named("OIDCAuthenticationProvider"), auditLogger: auditLogger, + deviceFlows: newDeviceFlowStore(), } return &oidcAuth, nil diff --git a/core/sessions/oidcauth/oidc.go b/core/sessions/oidcauth/oidc.go index cc7dd40eefb..63fd8be6334 100644 --- a/core/sessions/oidcauth/oidc.go +++ b/core/sessions/oidcauth/oidc.go @@ -49,6 +49,7 @@ type oidcAuthenticator struct { oauth2Config *oauth2.Config lggr logger.SugaredLogger auditLogger audit.Logger + deviceFlows *deviceFlowStore } // ExchangeTokenRequest represents the expected JSON payload from the frontend @@ -66,32 +67,40 @@ type ExchangeTokenResponse struct { // oidcAuthenticator implements sessions.AuthenticationProvider interface var _ clsessions.AuthenticationProvider = (*oidcAuthenticator)(nil) -func NewOIDCAuthenticator( - ds sqlutil.DataSource, - oidcCfg config.OIDC, - lggr logger.Logger, - auditLogger audit.Logger, -) (*oidcAuthenticator, error) { - // Ensure all RBAC role mappings to OIDC Id claims are defined, and required fields populated, or error on startup - lggr.Debugf("OIDC CFG:\n %#v\n", oidcCfg) +// validateOIDCConfig checks the required OIDC fields at startup. ClientSecret is +// intentionally NOT required: confidential clients (Okta "Web" apps) set it and +// it is sent on the token exchange, while public clients (Okta "Native" apps, +// which the CLI device flow needs) leave it empty and rely on PKCE instead. +func validateOIDCConfig(oidcCfg config.OIDC) error { if oidcCfg.AdminClaim() == "" || oidcCfg.EditClaim() == "" || oidcCfg.RunClaim() == "" || oidcCfg.ReadClaim() == "" { - return nil, errors.New("OIDC Group name mapping for callback group claims for all local RBAC role required. Set group names for `_Claim` fields") + return errors.New("OIDC Group name mapping for callback group claims for all local RBAC role required. Set group names for `_Claim` fields") } if oidcCfg.ClientID() == "" { - return nil, errors.New("OIDC ClientID config required") - } - if oidcCfg.ClientSecret() == "" { - return nil, errors.New("OIDC ClientSecret config required") + return errors.New("OIDC ClientID config required") } if oidcCfg.ProviderURL() == "" { - return nil, errors.New("OIDC ProviderURL config required") + return errors.New("OIDC ProviderURL config required") } if oidcCfg.RedirectURL() == "" { - return nil, errors.New("OIDC RedirectURL config required") + return errors.New("OIDC RedirectURL config required") } if oidcCfg.ClaimName() == "" { - return nil, errors.New("OIDC ClaimName config required") + return errors.New("OIDC ClaimName config required") + } + return nil +} + +func NewOIDCAuthenticator( + ds sqlutil.DataSource, + oidcCfg config.OIDC, + lggr logger.Logger, + auditLogger audit.Logger, +) (*oidcAuthenticator, error) { + // Ensure all RBAC role mappings to OIDC Id claims are defined, and required fields populated, or error on startup + lggr.Debugf("OIDC CFG:\n %#v\n", oidcCfg) + if err := validateOIDCConfig(oidcCfg); err != nil { + return nil, err } var provider *oidc.Provider @@ -126,6 +135,7 @@ func NewOIDCAuthenticator( oauth2Config: oauth2Config, lggr: logger.Sugared(lggr).Named("OIDCAuthenticationProvider"), auditLogger: auditLogger, + deviceFlows: newDeviceFlowStore(), } return &oidcAuth, nil @@ -145,10 +155,16 @@ func (oi *oidcAuthenticator) handleCheckEnabled(c *gin.Context) { } func (oi *oidcAuthenticator) handleSignIn(c *gin.Context) { - // generate state and store on session + // generate state and a PKCE verifier, store both on the session. PKCE (RFC + // 7636) is sent unconditionally: it is additive hardening for confidential + // clients and the sole proof-of-possession for public clients that carry no + // secret. The challenge derived from the verifier travels to the provider; + // the verifier stays server-side until the exchange. state := oi.generateState() + verifier := oauth2.GenerateVerifier() session := sessions.Default(c) session.Set("state", state) + session.Set("pkce_verifier", verifier) err := session.Save() if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save session"}) @@ -156,7 +172,7 @@ func (oi *oidcAuthenticator) handleSignIn(c *gin.Context) { } // redirect to provider - url := oi.oauth2Config.AuthCodeURL(state, oauth2.AccessTypeOffline) + url := oi.oauth2Config.AuthCodeURL(state, oauth2.AccessTypeOffline, oauth2.S256ChallengeOption(verifier)) c.Redirect(http.StatusFound, url) } @@ -183,9 +199,22 @@ func (oi *oidcAuthenticator) handleTokenExchange(c *gin.Context) { } ginSession.Delete("state") - // Begin token exchange to retrieve attested claims of authenticated user + // Recover the PKCE verifier stored at sign-in and bind it to this exchange. + storedVerifier, _ := ginSession.Get("pkce_verifier").(string) + ginSession.Delete("pkce_verifier") + if storedVerifier == "" { + c.JSON(http.StatusBadRequest, ExchangeTokenResponse{ + Success: false, + Message: "Missing PKCE verifier", + }) + return + } + + // Begin token exchange to retrieve attested claims of authenticated user. + // VerifierOption proves possession of the value whose challenge was sent at + // sign-in; for public clients this replaces the client secret. ctx := context.Background() - oauth2Token, err := oi.oauth2Config.Exchange(ctx, req.Code) + oauth2Token, err := oi.oauth2Config.Exchange(ctx, req.Code, oauth2.VerifierOption(storedVerifier)) if err != nil { oi.lggr.Errorf("Failed to exchange token: %v", err) c.JSON(http.StatusInternalServerError, ExchangeTokenResponse{ @@ -203,34 +232,60 @@ func (oi *oidcAuthenticator) handleTokenExchange(c *gin.Context) { return } - // Verify claim and retrieve attested user id claims - idToken, err := oi.provider.Verifier(oi.oidcConfig).Verify(ctx, rawIDToken) + sessionID, _, err := oi.issueSessionFromIDToken(ctx, rawIDToken) + if err != nil { + oi.handleIssueSessionError(c, err) + return + } + + // save session + ginSession.Set(webauth.SessionIDKey, sessionID) + err = ginSession.Save() if err != nil { - oi.lggr.Errorf("Failed to verify ID token: %v", err) - c.String(http.StatusInternalServerError, "Failed to verify ID token") + oi.lggr.Errorf("failed to saved session %v", err) + c.String(http.StatusInternalServerError, "Authentication failed") return } + c.JSON(http.StatusOK, ExchangeTokenResponse{ + Success: true, + }) +} + +// errNoMatchingRole signals that a verified token carried no group claim that +// maps to a local RBAC role. Callers translate it to a 4xx (the token was +// valid, the user simply lacks an authorised group), distinct from a 5xx for +// genuine verification or storage failures. +var errNoMatchingRole = errors.New("no matching role within attested user group claims") + +// issueSessionFromIDToken is the single trusted path that turns a raw OIDC +// id_token into an oidc_sessions row. Both the browser auth-code exchange and +// the CLI device flow funnel through here so verification, claim extraction, +// role mapping, and session creation never diverge between the two. It returns +// the new session ID and the authenticated email. +func (oi *oidcAuthenticator) issueSessionFromIDToken(ctx context.Context, rawIDToken string) (string, string, error) { + // Verify signature, issuer, expiry, and audience (pinned to ClientID). + idToken, err := oi.provider.Verifier(oi.oidcConfig).Verify(ctx, rawIDToken) + if err != nil { + return "", "", fmt.Errorf("failed to verify ID token: %w", err) + } + var claims map[string]any if err = idToken.Claims(&claims); err != nil { - oi.lggr.Errorf("Failed to parse OIDC return claims: %v", err) - c.String(http.StatusInternalServerError, "Failed to parse OIDC return claims") - return + return "", "", fmt.Errorf("failed to parse OIDC return claims: %w", err) } + idClaims, err := oi.ExtractIDClaimValues(claims, oi.config.ClaimName()) if err != nil { - oi.lggr.Errorf("Failed to extract ID claims from ID token. ClaimName: '%s': error %v", oi.config.ClaimName(), err) - c.String(http.StatusInternalServerError, "Failed to extract ID claims from claims") - return + return "", "", fmt.Errorf("failed to extract ID claims for claim name '%s': %w", oi.config.ClaimName(), err) } + email, ok := claims["email"].(string) if !ok { - oi.lggr.Errorf("Failed to get email from claims. error: %v", err) - c.String(http.StatusInternalServerError, "Failed to get email from claims") + return "", "", errors.New("failed to get email from claims") } oi.lggr.Tracef("Received and validated ID claims: %v\n", idClaims) - // Map the claims to a role and insert a newly created session paired with role mapping for user role, err := oi.IDClaimsToUserRole( idClaims, oi.config.AdminClaim(), @@ -239,13 +294,12 @@ func (oi *oidcAuthenticator) handleTokenExchange(c *gin.Context) { oi.config.ReadClaim(), ) if err != nil { - oi.lggr.Errorf("Failed to map configured RBAC role name against received list of group claims: %v", err) - c.String(http.StatusBadRequest, "No matching role within attested user group claims") - return + // Audit the full claim set so an over-broad or unexpected group grant is + // detectable after the fact. + oi.auditLogger.Audit(audit.AuthLoginFailed2FA, map[string]any{"email": email, "groups": idClaims}) + return "", "", fmt.Errorf("%w: %v", errNoMatchingRole, err) } - // Save new user authenticated clSession and role to oidc_sessions table - // Sessions are set to expire after the duration + creation date elapsed clSession := clsessions.NewSession() _, err = oi.ds.ExecContext( ctx, @@ -255,24 +309,24 @@ func (oi *oidcAuthenticator) handleTokenExchange(c *gin.Context) { role, ) if err != nil { - oi.lggr.Errorf("unable to create new session in oidc_sessions table %v", err) - c.String(http.StatusInternalServerError, "Error creating session") + return "", "", fmt.Errorf("unable to create new session in oidc_sessions table: %w", err) } - oi.auditLogger.Audit(audit.AuthLoginSuccessNo2FA, map[string]any{"email": email}) + oi.auditLogger.Audit(audit.AuthLoginSuccessNo2FA, map[string]any{"email": email, "role": role}) + return clSession.ID, email, nil +} - // save session - ginSession.Set(webauth.SessionIDKey, clSession.ID) - err = ginSession.Save() - if err != nil { - oi.lggr.Errorf("failed to saved session %v", err) - c.String(http.StatusInternalServerError, "Authentication failed") +// handleIssueSessionError maps an issueSessionFromIDToken error to the HTTP +// status the browser exchange returns: a missing/invalid role is a client-side +// 400, everything else is a 500. +func (oi *oidcAuthenticator) handleIssueSessionError(c *gin.Context, err error) { + if errors.Is(err, errNoMatchingRole) { + oi.lggr.Errorf("Failed to map configured RBAC role name against received list of group claims: %v", err) + c.String(http.StatusBadRequest, "No matching role within attested user group claims") return } - - c.JSON(http.StatusOK, ExchangeTokenResponse{ - Success: true, - }) + oi.lggr.Errorf("Failed to establish OIDC session: %v", err) + c.String(http.StatusInternalServerError, "Failed to establish OIDC session") } // FindUser in the context of the OIDC driver only supports local admin users @@ -659,6 +713,9 @@ func (oi *oidcAuthenticator) ExtendRouter(api *gin.RouterGroup) error { api.GET("/oidc-enabled", oi.handleCheckEnabled) api.GET("/oidc-login", oi.handleSignIn) api.POST("/oidc-exchange", oi.handleTokenExchange) + // Device authorization grant for headless clients (the CLI). + api.POST("/oidc-device/start", oi.handleDeviceStart) + api.POST("/oidc-device/poll", oi.handleDevicePoll) return nil } From f7f73ebceae0ece059353bd4b81339f58a826d9e Mon Sep 17 00:00:00 2001 From: Harry Anderson Date: Thu, 18 Jun 2026 01:39:21 +0000 Subject: [PATCH 02/18] test(oidc): add signed-JWT mock IdP and verification tests Add a mock OpenID Connect provider (discovery + JWKS + device + token endpoints, RSA-signed id_tokens) so the real go-oidc verifier is exercised end to end rather than stubbed. Covers issueSessionFromIDToken and the device-flow poll path: valid-token session creation, wrong-audience rejection (auth-bypass guard), expiry enforcement, unmatched-group rejection, and per-group RBAC role mapping. --- core/sessions/oidcauth/mock_idp_test.go | 158 +++++++++++++++++++ core/sessions/oidcauth/verify_flow_test.go | 168 +++++++++++++++++++++ 2 files changed, 326 insertions(+) create mode 100644 core/sessions/oidcauth/mock_idp_test.go create mode 100644 core/sessions/oidcauth/verify_flow_test.go diff --git a/core/sessions/oidcauth/mock_idp_test.go b/core/sessions/oidcauth/mock_idp_test.go new file mode 100644 index 00000000000..90538fc4e2b --- /dev/null +++ b/core/sessions/oidcauth/mock_idp_test.go @@ -0,0 +1,158 @@ +package oidcauth + +import ( + "context" + "crypto/rand" + "crypto/rsa" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + "time" + + gooidc "github.com/coreos/go-oidc/v3/oidc" + jose "github.com/go-jose/go-jose/v4" + "github.com/go-jose/go-jose/v4/jwt" + "github.com/stretchr/testify/require" + "golang.org/x/oauth2" + + "github.com/smartcontractkit/chainlink-common/pkg/sqlutil" + "github.com/smartcontractkit/chainlink/v2/core/logger" + "github.com/smartcontractkit/chainlink/v2/core/logger/audit" +) + +// mockIDP is a minimal OpenID Connect provider for tests. It serves a discovery +// document, a JWKS, a device authorization endpoint, and a token endpoint that +// returns RSA-signed id_tokens. It lets tests exercise the real go-oidc +// verifier (signature, issuer, audience, expiry) rather than stubbing it out. +type mockIDP struct { + server *httptest.Server + signer jose.Signer + key *rsa.PrivateKey + kid string + + // Knobs the tests flip to shape the id_token the token endpoint mints. + audience string // "aud" claim; default = clientID + issuerOverride string // "iss" claim; default = server URL + groups []string // groups claim + email string // email claim + lifetime time.Duration // exp relative to now; negative => already expired + + clientID string +} + +func newMockIDP(t *testing.T, clientID string) *mockIDP { + t.Helper() + key, err := rsa.GenerateKey(rand.Reader, 2048) + require.NoError(t, err) + + kid := "test-key-1" + signer, err := jose.NewSigner( + jose.SigningKey{Algorithm: jose.RS256, Key: key}, + (&jose.SignerOptions{}).WithType("JWT").WithHeader("kid", kid), + ) + require.NoError(t, err) + + m := &mockIDP{ + signer: signer, + key: key, + kid: kid, + groups: []string{AdminClaim}, + email: "user@example.com", + lifetime: time.Hour, + clientID: clientID, + } + + mux := http.NewServeMux() + mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, r *http.Request) { + base := m.server.URL + _ = json.NewEncoder(w).Encode(map[string]any{ + "issuer": base, + "authorization_endpoint": base + "/authorize", + "token_endpoint": base + "/token", + "jwks_uri": base + "/keys", + "device_authorization_endpoint": base + "/device/authorize", + "id_token_signing_alg_values_supported": []string{"RS256"}, + }) + }) + mux.HandleFunc("/keys", func(w http.ResponseWriter, r *http.Request) { + jwks := jose.JSONWebKeySet{Keys: []jose.JSONWebKey{{ + Key: key.Public(), + KeyID: kid, + Algorithm: "RS256", + Use: "sig", + }}} + _ = json.NewEncoder(w).Encode(jwks) + }) + mux.HandleFunc("/device/authorize", func(w http.ResponseWriter, r *http.Request) { + base := m.server.URL + _ = json.NewEncoder(w).Encode(map[string]any{ + "device_code": "test-device-code", + "user_code": "WDJB-MJHT", + "verification_uri": base + "/activate", + "expires_in": 300, + "interval": 1, + }) + }) + mux.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) { + idToken := m.signIDToken(t) + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "access_token": "test-access-token", + "token_type": "Bearer", + "expires_in": 3600, + "id_token": idToken, + }) + }) + + m.server = httptest.NewServer(mux) + t.Cleanup(m.server.Close) + return m +} + +// signIDToken builds and signs an id_token from the current knob values. +func (m *mockIDP) signIDToken(t *testing.T) string { + t.Helper() + aud := m.audience + if aud == "" { + aud = m.clientID + } + iss := m.issuerOverride + if iss == "" { + iss = m.server.URL + } + now := time.Now() + claims := map[string]any{ + "iss": iss, + "aud": aud, + "sub": "subject-123", + "email": m.email, + "groups": m.groups, + "iat": now.Unix(), + "exp": now.Add(m.lifetime).Unix(), + } + raw, err := jwt.Signed(m.signer).Claims(claims).Serialize() + require.NoError(t, err) + return raw +} + +// newAuthenticatorForIDP builds an oidcAuthenticator wired to the mock IdP: a +// real go-oidc provider (so the real verifier and JWKS fetch are used) and an +// oauth2 config whose endpoints point at the mock. ds is the real test DB. +func newAuthenticatorForIDP(t *testing.T, idp *mockIDP, ds sqlutil.DataSource) *oidcAuthenticator { + t.Helper() + ctx := context.Background() + provider, err := gooidc.NewProvider(ctx, idp.server.URL) + require.NoError(t, err) + + return &oidcAuthenticator{ + ds: ds, + config: &TestConfig{}, + provider: provider, + oidcConfig: &gooidc.Config{ClientID: idp.clientID}, + oauth2Config: &oauth2.Config{ClientID: idp.clientID, Endpoint: provider.Endpoint()}, + lggr: logger.TestLogger(t), + auditLogger: &audit.AuditLoggerService{}, + deviceFlows: newDeviceFlowStore(), + } +} diff --git a/core/sessions/oidcauth/verify_flow_test.go b/core/sessions/oidcauth/verify_flow_test.go new file mode 100644 index 00000000000..aa64c358dea --- /dev/null +++ b/core/sessions/oidcauth/verify_flow_test.go @@ -0,0 +1,168 @@ +package oidcauth + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest" +) + +const testClientID = "test-client-id" + +// countOIDCSessions returns the number of rows for an email in oidc_sessions. +func countOIDCSessions(t *testing.T, oi *oidcAuthenticator, email string) int { + t.Helper() + var n int + require.NoError(t, oi.ds.GetContext(context.Background(), &n, + "SELECT count(*) FROM oidc_sessions WHERE lower(user_email) = lower($1)", email)) + return n +} + +// TestIssueSessionFromIDToken_Valid runs a correctly signed, correctly +// audienced token through the real verifier and asserts a session row lands. +func TestIssueSessionFromIDToken_Valid(t *testing.T) { + db := pgtest.NewSqlxDB(t) + idp := newMockIDP(t, testClientID) + idp.email = "valid-user@example.com" + idp.groups = []string{AdminClaim} + oi := newAuthenticatorForIDP(t, idp, db) + + raw := idp.signIDToken(t) + sessionID, email, err := oi.issueSessionFromIDToken(context.Background(), raw) + require.NoError(t, err) + assert.NotEmpty(t, sessionID) + assert.Equal(t, "valid-user@example.com", email) + assert.Equal(t, 1, countOIDCSessions(t, oi, "valid-user@example.com")) +} + +// TestIssueSessionFromIDToken_WrongAudience is the critical auth-bypass guard: +// a token minted for a different client must be rejected and create no session. +func TestIssueSessionFromIDToken_WrongAudience(t *testing.T) { + db := pgtest.NewSqlxDB(t) + idp := newMockIDP(t, testClientID) + idp.email = "attacker@example.com" + idp.audience = "some-other-client" // token for a different app + oi := newAuthenticatorForIDP(t, idp, db) + + raw := idp.signIDToken(t) + _, _, err := oi.issueSessionFromIDToken(context.Background(), raw) + require.Error(t, err, "token with mismatched audience must be rejected") + assert.Contains(t, err.Error(), "verify") + assert.Equal(t, 0, countOIDCSessions(t, oi, "attacker@example.com")) +} + +// TestIssueSessionFromIDToken_Expired asserts the verifier enforces expiry. +func TestIssueSessionFromIDToken_Expired(t *testing.T) { + db := pgtest.NewSqlxDB(t) + idp := newMockIDP(t, testClientID) + idp.email = "expired-user@example.com" + idp.lifetime = -time.Hour // already expired + oi := newAuthenticatorForIDP(t, idp, db) + + raw := idp.signIDToken(t) + _, _, err := oi.issueSessionFromIDToken(context.Background(), raw) + require.Error(t, err, "expired token must be rejected") + assert.Equal(t, 0, countOIDCSessions(t, oi, "expired-user@example.com")) +} + +// TestIssueSessionFromIDToken_NoMatchingGroup asserts a validly signed token +// whose groups map to no RBAC role is rejected with errNoMatchingRole and +// creates no session. +func TestIssueSessionFromIDToken_NoMatchingGroup(t *testing.T) { + db := pgtest.NewSqlxDB(t) + idp := newMockIDP(t, testClientID) + idp.email = "nogroup-user@example.com" + idp.groups = []string{"SomeUnrelatedGroup"} + oi := newAuthenticatorForIDP(t, idp, db) + + raw := idp.signIDToken(t) + _, _, err := oi.issueSessionFromIDToken(context.Background(), raw) + require.ErrorIs(t, err, errNoMatchingRole) + assert.Equal(t, 0, countOIDCSessions(t, oi, "nogroup-user@example.com")) +} + +// TestIssueSessionFromIDToken_RoleMapping asserts each group claim maps to the +// expected RBAC role on the stored session. +func TestIssueSessionFromIDToken_RoleMapping(t *testing.T) { + cases := []struct { + group string + wantRole string + }{ + {AdminClaim, "admin"}, + {EditorClaim, "edit"}, + {RunnerClaim, "run"}, + {ReadClaim, "view"}, + } + for _, tc := range cases { + t.Run(tc.group, func(t *testing.T) { + db := pgtest.NewSqlxDB(t) + idp := newMockIDP(t, testClientID) + email := tc.group + "@example.com" + idp.email = email + idp.groups = []string{tc.group} + oi := newAuthenticatorForIDP(t, idp, db) + + _, _, err := oi.issueSessionFromIDToken(context.Background(), idp.signIDToken(t)) + require.NoError(t, err) + + var role string + require.NoError(t, oi.ds.GetContext(context.Background(), &role, + "SELECT user_role FROM oidc_sessions WHERE lower(user_email) = lower($1)", email)) + assert.Equal(t, tc.wantRole, role) + }) + } +} + +// TestDeviceFlow_EndToEnd drives the full device flow against the mock IdP: the +// node polls the mock token endpoint, verifies the returned id_token, and +// records a completed flow with a real oidc_sessions row. +func TestDeviceFlow_EndToEnd(t *testing.T) { + db := pgtest.NewSqlxDB(t) + idp := newMockIDP(t, testClientID) + idp.email = "device-user@example.com" + idp.groups = []string{EditorClaim} + oi := newAuthenticatorForIDP(t, idp, db) + + // Kick off a device authorization at the provider, then run the same + // blocking poll the node uses in production. + da, err := oi.oauth2Config.DeviceAuth(context.Background()) + require.NoError(t, err) + + state := &deviceFlowState{expiresAt: time.Now().Add(time.Minute)} + oi.pollDeviceToken("e2e-handle", state, da) + + state.mu.Lock() + defer state.mu.Unlock() + require.True(t, state.done) + require.NoError(t, state.err, "device flow should complete and issue a session") + assert.NotEmpty(t, state.sessionID) + assert.Equal(t, "device-user@example.com", state.email) + assert.Equal(t, 1, countOIDCSessions(t, oi, "device-user@example.com")) +} + +// TestDeviceFlow_WrongAudienceRejected asserts the device path uses the same +// verifier: a token for the wrong client fails the flow and creates no session. +func TestDeviceFlow_WrongAudienceRejected(t *testing.T) { + db := pgtest.NewSqlxDB(t) + idp := newMockIDP(t, testClientID) + idp.email = "device-attacker@example.com" + idp.audience = "other-client" + oi := newAuthenticatorForIDP(t, idp, db) + + da, err := oi.oauth2Config.DeviceAuth(context.Background()) + require.NoError(t, err) + + state := &deviceFlowState{expiresAt: time.Now().Add(time.Minute)} + oi.pollDeviceToken("e2e-handle-2", state, da) + + state.mu.Lock() + defer state.mu.Unlock() + require.True(t, state.done) + require.Error(t, state.err) + assert.Empty(t, state.sessionID) + assert.Equal(t, 0, countOIDCSessions(t, oi, "device-attacker@example.com")) +} From 63487af22ce098ad2285ab44d5da75a2fa698556 Mon Sep 17 00:00:00 2001 From: Harry Anderson Date: Thu, 18 Jun 2026 01:56:12 +0000 Subject: [PATCH 03/18] fix(oidc): satisfy lint and go mod tidy for CI - go mod tidy: promote go-jose/v4 to a direct dependency (used by the mock IdP test). - errorlint: wrap the role-mapping error with %w. - testifylint: use require for error assertions; assert (not require) inside the mock node's HTTP handlers. - modernize: range-over-int loops in tests. - paralleltest: add t.Parallel to the new tests. - gosec: set Secure/HttpOnly/SameSite on the mock session cookie. --- core/cmd/oidc_device_auth_test.go | 15 ++++++++++++--- core/sessions/oidcauth/device_flow_test.go | 19 +++++++++++++------ core/sessions/oidcauth/oidc.go | 2 +- core/sessions/oidcauth/verify_flow_test.go | 8 ++++++++ go.mod | 2 +- 5 files changed, 35 insertions(+), 11 deletions(-) diff --git a/core/cmd/oidc_device_auth_test.go b/core/cmd/oidc_device_auth_test.go index d52cf30b758..6179eba4b83 100644 --- a/core/cmd/oidc_device_auth_test.go +++ b/core/cmd/oidc_device_auth_test.go @@ -35,7 +35,9 @@ func (m *mockNode) handler(t *testing.T) http.Handler { w.WriteHeader(http.StatusOK) }) mux.HandleFunc("/oidc-device/start", func(w http.ResponseWriter, r *http.Request) { - require.Equal(t, http.MethodPost, r.Method) + // assert (not require) inside handler goroutines: require calls Goexit + // on the wrong goroutine. + assert.Equal(t, http.MethodPost, r.Method) _ = json.NewEncoder(w).Encode(map[string]any{ "device_handle": "test-handle", "user_code": "WDJB-MJHT", @@ -47,7 +49,7 @@ func (m *mockNode) handler(t *testing.T) http.Handler { }) mux.HandleFunc("/oidc-device/poll", func(w http.ResponseWriter, r *http.Request) { var req map[string]string - require.NoError(t, json.NewDecoder(r.Body).Decode(&req)) + assert.NoError(t, json.NewDecoder(r.Body).Decode(&req)) assert.Equal(t, "test-handle", req["device_handle"], "CLI must echo back the opaque handle") if atomic.AddInt32(&m.pollsPending, -1) >= 0 { @@ -58,7 +60,14 @@ func (m *mockNode) handler(t *testing.T) http.Handler { _ = json.NewEncoder(w).Encode(map[string]string{"status": "denied", "message": "expired"}) return } - http.SetCookie(w, &http.Cookie{Name: "clsession", Value: "abc123", Path: "/"}) + http.SetCookie(w, &http.Cookie{ + Name: "clsession", + Value: "abc123", + Path: "/", + Secure: true, + HttpOnly: true, + SameSite: http.SameSiteStrictMode, + }) _ = json.NewEncoder(w).Encode(map[string]string{"status": "complete"}) }) return mux diff --git a/core/sessions/oidcauth/device_flow_test.go b/core/sessions/oidcauth/device_flow_test.go index 5234115bd0b..6b4c50ac82e 100644 --- a/core/sessions/oidcauth/device_flow_test.go +++ b/core/sessions/oidcauth/device_flow_test.go @@ -14,6 +14,7 @@ import ( ) func TestDeviceFlowStore_AddGetRemove(t *testing.T) { + t.Parallel() s := newDeviceFlowStore() state := &deviceFlowState{expiresAt: time.Now().Add(time.Minute)} @@ -29,8 +30,9 @@ func TestDeviceFlowStore_AddGetRemove(t *testing.T) { } func TestDeviceFlowStore_ConcurrencyCap(t *testing.T) { + t.Parallel() s := newDeviceFlowStore() - for i := 0; i < maxConcurrentDeviceFlows; i++ { + for i := range maxConcurrentDeviceFlows { require.NoError(t, s.add(handleN(i), &deviceFlowState{expiresAt: time.Now().Add(time.Minute)})) } // One past the cap must be refused, not silently dropped. @@ -39,9 +41,10 @@ func TestDeviceFlowStore_ConcurrencyCap(t *testing.T) { } func TestDeviceFlowStore_ExpiredSweptOnAdd(t *testing.T) { + t.Parallel() s := newDeviceFlowStore() // Fill with already-expired flows. - for i := 0; i < maxConcurrentDeviceFlows; i++ { + for i := range maxConcurrentDeviceFlows { require.NoError(t, s.add(handleN(i), &deviceFlowState{expiresAt: time.Now().Add(-time.Second)})) } // A fresh add sweeps the expired entries, making room rather than erroring. @@ -51,9 +54,10 @@ func TestDeviceFlowStore_ExpiredSweptOnAdd(t *testing.T) { } func TestGenerateDeviceHandle_UniqueAndURLSafe(t *testing.T) { + t.Parallel() oi := &oidcAuthenticator{} seen := make(map[string]struct{}) - for i := 0; i < 1000; i++ { + for range 1000 { h, err := oi.generateDeviceHandle() require.NoError(t, err) require.NotEmpty(t, h) @@ -69,6 +73,7 @@ func TestGenerateDeviceHandle_UniqueAndURLSafe(t *testing.T) { } func TestFinishDeviceFlow_RecordsTerminalState(t *testing.T) { + t.Parallel() oi := &oidcAuthenticator{lggr: logger.TestLogger(t)} okState := &deviceFlowState{expiresAt: time.Now().Add(time.Minute)} @@ -77,7 +82,7 @@ func TestFinishDeviceFlow_RecordsTerminalState(t *testing.T) { assert.True(t, okState.done) assert.Equal(t, "sess-1", okState.sessionID) assert.Equal(t, "user@example.com", okState.email) - assert.NoError(t, okState.err) + require.NoError(t, okState.err) okState.mu.Unlock() errState := &deviceFlowState{expiresAt: time.Now().Add(time.Minute)} @@ -86,13 +91,14 @@ func TestFinishDeviceFlow_RecordsTerminalState(t *testing.T) { errState.mu.Lock() assert.True(t, errState.done) assert.Empty(t, errState.sessionID) - assert.ErrorIs(t, errState.err, wantErr) + require.ErrorIs(t, errState.err, wantErr) errState.mu.Unlock() } // TestDeviceFlowState_ConcurrentAccess exercises the writer/reader lock that // separates the background poll goroutine from the CLI poll handler. func TestDeviceFlowState_ConcurrentAccess(t *testing.T) { + t.Parallel() oi := &oidcAuthenticator{lggr: logger.TestLogger(t)} state := &deviceFlowState{expiresAt: time.Now().Add(time.Minute)} @@ -104,7 +110,7 @@ func TestDeviceFlowState_ConcurrentAccess(t *testing.T) { }() go func() { defer wg.Done() - for i := 0; i < 100; i++ { + for range 100 { state.mu.Lock() _ = state.done state.mu.Unlock() @@ -141,6 +147,7 @@ func (m mutableConfig) ClientID() string { } func TestValidateOIDCConfig_SecretOptional(t *testing.T) { + t.Parallel() empty := "" base := &TestConfig{} diff --git a/core/sessions/oidcauth/oidc.go b/core/sessions/oidcauth/oidc.go index 63fd8be6334..8f23600591c 100644 --- a/core/sessions/oidcauth/oidc.go +++ b/core/sessions/oidcauth/oidc.go @@ -297,7 +297,7 @@ func (oi *oidcAuthenticator) issueSessionFromIDToken(ctx context.Context, rawIDT // Audit the full claim set so an over-broad or unexpected group grant is // detectable after the fact. oi.auditLogger.Audit(audit.AuthLoginFailed2FA, map[string]any{"email": email, "groups": idClaims}) - return "", "", fmt.Errorf("%w: %v", errNoMatchingRole, err) + return "", "", fmt.Errorf("%w: %w", errNoMatchingRole, err) } clSession := clsessions.NewSession() diff --git a/core/sessions/oidcauth/verify_flow_test.go b/core/sessions/oidcauth/verify_flow_test.go index aa64c358dea..0d8532e1200 100644 --- a/core/sessions/oidcauth/verify_flow_test.go +++ b/core/sessions/oidcauth/verify_flow_test.go @@ -25,6 +25,7 @@ func countOIDCSessions(t *testing.T, oi *oidcAuthenticator, email string) int { // TestIssueSessionFromIDToken_Valid runs a correctly signed, correctly // audienced token through the real verifier and asserts a session row lands. func TestIssueSessionFromIDToken_Valid(t *testing.T) { + t.Parallel() db := pgtest.NewSqlxDB(t) idp := newMockIDP(t, testClientID) idp.email = "valid-user@example.com" @@ -42,6 +43,7 @@ func TestIssueSessionFromIDToken_Valid(t *testing.T) { // TestIssueSessionFromIDToken_WrongAudience is the critical auth-bypass guard: // a token minted for a different client must be rejected and create no session. func TestIssueSessionFromIDToken_WrongAudience(t *testing.T) { + t.Parallel() db := pgtest.NewSqlxDB(t) idp := newMockIDP(t, testClientID) idp.email = "attacker@example.com" @@ -57,6 +59,7 @@ func TestIssueSessionFromIDToken_WrongAudience(t *testing.T) { // TestIssueSessionFromIDToken_Expired asserts the verifier enforces expiry. func TestIssueSessionFromIDToken_Expired(t *testing.T) { + t.Parallel() db := pgtest.NewSqlxDB(t) idp := newMockIDP(t, testClientID) idp.email = "expired-user@example.com" @@ -73,6 +76,7 @@ func TestIssueSessionFromIDToken_Expired(t *testing.T) { // whose groups map to no RBAC role is rejected with errNoMatchingRole and // creates no session. func TestIssueSessionFromIDToken_NoMatchingGroup(t *testing.T) { + t.Parallel() db := pgtest.NewSqlxDB(t) idp := newMockIDP(t, testClientID) idp.email = "nogroup-user@example.com" @@ -88,6 +92,7 @@ func TestIssueSessionFromIDToken_NoMatchingGroup(t *testing.T) { // TestIssueSessionFromIDToken_RoleMapping asserts each group claim maps to the // expected RBAC role on the stored session. func TestIssueSessionFromIDToken_RoleMapping(t *testing.T) { + t.Parallel() cases := []struct { group string wantRole string @@ -99,6 +104,7 @@ func TestIssueSessionFromIDToken_RoleMapping(t *testing.T) { } for _, tc := range cases { t.Run(tc.group, func(t *testing.T) { + t.Parallel() db := pgtest.NewSqlxDB(t) idp := newMockIDP(t, testClientID) email := tc.group + "@example.com" @@ -121,6 +127,7 @@ func TestIssueSessionFromIDToken_RoleMapping(t *testing.T) { // node polls the mock token endpoint, verifies the returned id_token, and // records a completed flow with a real oidc_sessions row. func TestDeviceFlow_EndToEnd(t *testing.T) { + t.Parallel() db := pgtest.NewSqlxDB(t) idp := newMockIDP(t, testClientID) idp.email = "device-user@example.com" @@ -147,6 +154,7 @@ func TestDeviceFlow_EndToEnd(t *testing.T) { // TestDeviceFlow_WrongAudienceRejected asserts the device path uses the same // verifier: a token for the wrong client fails the flow and creates no session. func TestDeviceFlow_WrongAudienceRejected(t *testing.T) { + t.Parallel() db := pgtest.NewSqlxDB(t) idp := newMockIDP(t, testClientID) idp.email = "device-attacker@example.com" diff --git a/go.mod b/go.mod index 7e8aca189bc..2834a184ef2 100644 --- a/go.mod +++ b/go.mod @@ -30,6 +30,7 @@ require ( github.com/gin-contrib/size v0.0.0-20230212012657-e14a14094dc4 github.com/gin-gonic/gin v1.10.1 github.com/go-co-op/gocron/v2 v2.18.0 + github.com/go-jose/go-jose/v4 v4.1.6 github.com/go-json-experiment/json v0.0.0-20260505212615-e40f80bf6836 github.com/go-ldap/ldap/v3 v3.4.6 github.com/go-viper/mapstructure/v2 v2.5.0 @@ -230,7 +231,6 @@ require ( github.com/gedex/inflector v0.0.0-20170307190818-16278e9db813 // indirect github.com/gin-contrib/sse v0.1.0 // indirect github.com/go-asn1-ber/asn1-ber v1.5.5 // indirect - github.com/go-jose/go-jose/v4 v4.1.6 // indirect github.com/go-kit/kit v0.13.0 // indirect github.com/go-kit/log v0.2.1 // indirect github.com/go-logfmt/logfmt v0.6.0 // indirect From 1de3437a662d4ec1ef4ba75e6680c30fcb239015 Mon Sep 17 00:00:00 2001 From: harry-anderson <14777088+harry-anderson@users.noreply.github.com> Date: Tue, 23 Jun 2026 05:19:27 +0000 Subject: [PATCH 04/18] fix(oidc): harden device flow polling, auditing, and logging - Close a double-poll race in handleDevicePoll: add deviceFlowStore.consumeIfDone, which checks the terminal state and removes the handle in a single critical section, so two concurrent polls on a completed handle can no longer both be issued the session cookie. Add a racing-pollers test asserting a single winner. - Redact device_handle in request body logging so the live bearer handle is not written to debug logs. - Emit one method-tagged success audit event per login path (oidc_exchange, device_flow, local_admin), each carrying email and resolved role. issueSessionFromIDToken now returns the role and no longer audits success itself, removing the device path's duplicate, role-less event. - Correct the misleading oidc_user_api_tokens comment: no upstream revocation sync exists for OIDC and the mechanism must stay disabled. --- core/sessions/oidcauth/device_flow.go | 54 ++++++++++++++-------- core/sessions/oidcauth/device_flow_test.go | 50 ++++++++++++++++++-- core/sessions/oidcauth/oidc.go | 39 ++++++++++------ core/web/router.go | 1 + 4 files changed, 107 insertions(+), 37 deletions(-) diff --git a/core/sessions/oidcauth/device_flow.go b/core/sessions/oidcauth/device_flow.go index 6ad20001802..af7967842d5 100644 --- a/core/sessions/oidcauth/device_flow.go +++ b/core/sessions/oidcauth/device_flow.go @@ -15,6 +15,7 @@ import ( "golang.org/x/oauth2" "github.com/smartcontractkit/chainlink/v2/core/logger/audit" + clsessions "github.com/smartcontractkit/chainlink/v2/core/sessions" webauth "github.com/smartcontractkit/chainlink/v2/core/web/auth" ) @@ -54,6 +55,7 @@ type deviceFlowState struct { done bool sessionID string email string + role clsessions.UserRole err error } @@ -105,6 +107,27 @@ func (s *deviceFlowStore) remove(handle string) { delete(s.flows, handle) } +// consumeIfDone atomically reports whether the flow for handle has reached a +// terminal state and, if so, removes it in the same critical section. This +// closes the double-poll window: two concurrent polls on a completed handle +// cannot both observe done and both be issued the session cookie; exactly one +// sees terminal=true, the rest see (nil, false) once it is gone. +func (s *deviceFlowStore) consumeIfDone(handle string) (sessionID, email string, role clsessions.UserRole, flowErr error, terminal bool, known bool) { + s.mu.Lock() + defer s.mu.Unlock() + f, ok := s.flows[handle] + if !ok { + return "", "", "", nil, false, false + } + f.mu.Lock() + defer f.mu.Unlock() + if !f.done { + return "", "", "", nil, false, true + } + delete(s.flows, handle) + return f.sessionID, f.email, f.role, f.err, true, true +} + // generateDeviceHandle returns a URL-safe 256-bit random handle. It is the only // device-flow identifier the CLI ever sees; the provider device_code stays // server-side. @@ -201,25 +224,26 @@ func (oi *oidcAuthenticator) pollDeviceToken(handle string, state *deviceFlowSta token, err := oi.oauth2Config.DeviceAccessToken(ctx, da) if err != nil { - oi.finishDeviceFlow(state, "", "", err) + oi.finishDeviceFlow(state, "", "", "", err) return } rawIDToken, ok := token.Extra("id_token").(string) if !ok { - oi.finishDeviceFlow(state, "", "", errors.New("missing id_token in device token response")) + oi.finishDeviceFlow(state, "", "", "", errors.New("missing id_token in device token response")) return } - sessionID, email, err := oi.issueSessionFromIDToken(ctx, rawIDToken) - oi.finishDeviceFlow(state, sessionID, email, err) + sessionID, email, role, err := oi.issueSessionFromIDToken(ctx, rawIDToken) + oi.finishDeviceFlow(state, sessionID, email, role, err) } -func (oi *oidcAuthenticator) finishDeviceFlow(state *deviceFlowState, sessionID, email string, err error) { +func (oi *oidcAuthenticator) finishDeviceFlow(state *deviceFlowState, sessionID, email string, role clsessions.UserRole, err error) { state.mu.Lock() state.done = true state.sessionID = sessionID state.email = email + state.role = role state.err = err state.mu.Unlock() if err != nil { @@ -237,27 +261,19 @@ func (oi *oidcAuthenticator) handleDevicePoll(c *gin.Context) { return } - state, ok := oi.deviceFlows.get(req.DeviceHandle) - if !ok { + // Read the terminal result and consume the handle in one critical section + // so two concurrent polls cannot both be handed the session cookie. + sessionID, email, role, flowErr, terminal, known := oi.deviceFlows.consumeIfDone(req.DeviceHandle) + if !known { c.JSON(http.StatusNotFound, DevicePollResponse{Status: "denied", Message: errUnknownDeviceFlow.Error()}) return } - state.mu.Lock() - done := state.done - sessionID := state.sessionID - email := state.email - flowErr := state.err - state.mu.Unlock() - - if !done { + if !terminal { c.JSON(http.StatusOK, DevicePollResponse{Status: "pending"}) return } - // Terminal: consume the handle regardless of outcome. - oi.deviceFlows.remove(req.DeviceHandle) - if flowErr != nil { c.JSON(http.StatusOK, DevicePollResponse{Status: "denied", Message: "Authorization was not completed"}) return @@ -273,6 +289,6 @@ func (oi *oidcAuthenticator) handleDevicePoll(c *gin.Context) { return } - oi.auditLogger.Audit(audit.AuthLoginSuccessNo2FA, map[string]any{"email": email, "method": "device_flow"}) + oi.auditLogger.Audit(audit.AuthLoginSuccessNo2FA, map[string]any{"email": email, "role": role, "method": "device_flow"}) c.JSON(http.StatusOK, DevicePollResponse{Status: "complete"}) } diff --git a/core/sessions/oidcauth/device_flow_test.go b/core/sessions/oidcauth/device_flow_test.go index 6b4c50ac82e..8e89dafb5eb 100644 --- a/core/sessions/oidcauth/device_flow_test.go +++ b/core/sessions/oidcauth/device_flow_test.go @@ -11,6 +11,7 @@ import ( "github.com/stretchr/testify/require" "github.com/smartcontractkit/chainlink/v2/core/logger" + clsessions "github.com/smartcontractkit/chainlink/v2/core/sessions" ) func TestDeviceFlowStore_AddGetRemove(t *testing.T) { @@ -29,6 +30,49 @@ func TestDeviceFlowStore_AddGetRemove(t *testing.T) { assert.False(t, ok, "handle must be single-use: gone after remove") } +// TestDeviceFlowStore_ConsumeIfDoneSingleWinner asserts that when many polls +// race on one completed handle, exactly one observes the terminal result and +// consumes it. This is the double-spend guard: two polls must never both be +// handed the session cookie. +func TestDeviceFlowStore_ConsumeIfDoneSingleWinner(t *testing.T) { + t.Parallel() + s := newDeviceFlowStore() + state := &deviceFlowState{expiresAt: time.Now().Add(time.Minute)} + state.done = true + state.sessionID = "sess-winner" + require.NoError(t, s.add("race-handle", state)) + + const pollers = 50 + var ( + wg sync.WaitGroup + mu sync.Mutex + winners int + pendings int + ) + wg.Add(pollers) + for range pollers { + go func() { + defer wg.Done() + sessionID, _, _, _, terminal, known := s.consumeIfDone("race-handle") + mu.Lock() + defer mu.Unlock() + switch { + case terminal: + winners++ + assert.Equal(t, "sess-winner", sessionID) + case known: + pendings++ // saw it before it was consumed, but not terminal: impossible here + } + }() + } + wg.Wait() + + assert.Equal(t, 1, winners, "exactly one poll may consume a completed handle") + assert.Equal(t, 0, pendings, "a done flow must never report pending") + _, ok := s.get("race-handle") + assert.False(t, ok, "handle must be removed after it is consumed") +} + func TestDeviceFlowStore_ConcurrencyCap(t *testing.T) { t.Parallel() s := newDeviceFlowStore() @@ -77,7 +121,7 @@ func TestFinishDeviceFlow_RecordsTerminalState(t *testing.T) { oi := &oidcAuthenticator{lggr: logger.TestLogger(t)} okState := &deviceFlowState{expiresAt: time.Now().Add(time.Minute)} - oi.finishDeviceFlow(okState, "sess-1", "user@example.com", nil) + oi.finishDeviceFlow(okState, "sess-1", "user@example.com", clsessions.UserRoleEdit, nil) okState.mu.Lock() assert.True(t, okState.done) assert.Equal(t, "sess-1", okState.sessionID) @@ -87,7 +131,7 @@ func TestFinishDeviceFlow_RecordsTerminalState(t *testing.T) { errState := &deviceFlowState{expiresAt: time.Now().Add(time.Minute)} wantErr := errors.New("denied") - oi.finishDeviceFlow(errState, "", "", wantErr) + oi.finishDeviceFlow(errState, "", "", "", wantErr) errState.mu.Lock() assert.True(t, errState.done) assert.Empty(t, errState.sessionID) @@ -106,7 +150,7 @@ func TestDeviceFlowState_ConcurrentAccess(t *testing.T) { wg.Add(2) go func() { defer wg.Done() - oi.finishDeviceFlow(state, "s", "e", nil) + oi.finishDeviceFlow(state, "s", "e", clsessions.UserRoleView, nil) }() go func() { defer wg.Done() diff --git a/core/sessions/oidcauth/oidc.go b/core/sessions/oidcauth/oidc.go index 8f23600591c..fef23559e32 100644 --- a/core/sessions/oidcauth/oidc.go +++ b/core/sessions/oidcauth/oidc.go @@ -232,7 +232,7 @@ func (oi *oidcAuthenticator) handleTokenExchange(c *gin.Context) { return } - sessionID, _, err := oi.issueSessionFromIDToken(ctx, rawIDToken) + sessionID, email, role, err := oi.issueSessionFromIDToken(ctx, rawIDToken) if err != nil { oi.handleIssueSessionError(c, err) return @@ -247,6 +247,8 @@ func (oi *oidcAuthenticator) handleTokenExchange(c *gin.Context) { return } + oi.auditLogger.Audit(audit.AuthLoginSuccessNo2FA, map[string]any{"email": email, "role": role, "method": "oidc_exchange"}) + c.JSON(http.StatusOK, ExchangeTokenResponse{ Success: true, }) @@ -262,27 +264,29 @@ var errNoMatchingRole = errors.New("no matching role within attested user group // id_token into an oidc_sessions row. Both the browser auth-code exchange and // the CLI device flow funnel through here so verification, claim extraction, // role mapping, and session creation never diverge between the two. It returns -// the new session ID and the authenticated email. -func (oi *oidcAuthenticator) issueSessionFromIDToken(ctx context.Context, rawIDToken string) (string, string, error) { +// the new session ID, the authenticated email, and the resolved role. The +// caller emits the success audit event tagged with its login method so device +// and UI sessions are distinguishable; this function audits only failures. +func (oi *oidcAuthenticator) issueSessionFromIDToken(ctx context.Context, rawIDToken string) (string, string, clsessions.UserRole, error) { // Verify signature, issuer, expiry, and audience (pinned to ClientID). idToken, err := oi.provider.Verifier(oi.oidcConfig).Verify(ctx, rawIDToken) if err != nil { - return "", "", fmt.Errorf("failed to verify ID token: %w", err) + return "", "", "", fmt.Errorf("failed to verify ID token: %w", err) } var claims map[string]any if err = idToken.Claims(&claims); err != nil { - return "", "", fmt.Errorf("failed to parse OIDC return claims: %w", err) + return "", "", "", fmt.Errorf("failed to parse OIDC return claims: %w", err) } idClaims, err := oi.ExtractIDClaimValues(claims, oi.config.ClaimName()) if err != nil { - return "", "", fmt.Errorf("failed to extract ID claims for claim name '%s': %w", oi.config.ClaimName(), err) + return "", "", "", fmt.Errorf("failed to extract ID claims for claim name '%s': %w", oi.config.ClaimName(), err) } email, ok := claims["email"].(string) if !ok { - return "", "", errors.New("failed to get email from claims") + return "", "", "", errors.New("failed to get email from claims") } oi.lggr.Tracef("Received and validated ID claims: %v\n", idClaims) @@ -297,7 +301,7 @@ func (oi *oidcAuthenticator) issueSessionFromIDToken(ctx context.Context, rawIDT // Audit the full claim set so an over-broad or unexpected group grant is // detectable after the fact. oi.auditLogger.Audit(audit.AuthLoginFailed2FA, map[string]any{"email": email, "groups": idClaims}) - return "", "", fmt.Errorf("%w: %w", errNoMatchingRole, err) + return "", "", "", fmt.Errorf("%w: %w", errNoMatchingRole, err) } clSession := clsessions.NewSession() @@ -309,11 +313,10 @@ func (oi *oidcAuthenticator) issueSessionFromIDToken(ctx context.Context, rawIDT role, ) if err != nil { - return "", "", fmt.Errorf("unable to create new session in oidc_sessions table: %w", err) + return "", "", "", fmt.Errorf("unable to create new session in oidc_sessions table: %w", err) } - oi.auditLogger.Audit(audit.AuthLoginSuccessNo2FA, map[string]any{"email": email, "role": role}) - return clSession.ID, email, nil + return clSession.ID, email, role, nil } // handleIssueSessionError maps an issueSessionFromIDToken error to the HTTP @@ -356,9 +359,15 @@ func (oi *oidcAuthenticator) FindUserByAPIToken(ctx context.Context, apiToken st var foundUser clsessions.User err := sqlutil.TransactDataSource(ctx, oi.ds, nil, func(tx sqlutil.DataSource) error { - // Query the oidc user API token table for given token, user role and email are cached so - // no further upstream OIDC query is performed, sessions and tokens are synced against the upstream server - // via the UpstreamSyncInterval config and reaper.go sync implementation + // Query the oidc user API token table for the given token. The user role + // and email are cached on the row, so no upstream OIDC query is performed + // on lookup. NOTE: there is no upstream revocation sync for these tokens. + // The OIDC reaper (reaper.go) only deletes stale oidc_sessions, and + // UpstreamSyncInterval applies to the LDAP provider, not OIDC. A cached + // token therefore retains its role until its own UserAPITokenDuration + // expiry, even if the user's group is revoked at the identity provider. + // This mechanism must stay disabled (UserAPITokenEnabled = false) until + // that revocation gap is fixed. var foundUserToken struct { UserEmail string UserRole clsessions.UserRole @@ -487,7 +496,7 @@ func (oi *oidcAuthenticator) CreateSession(ctx context.Context, sr clsessions.Se return "", fmt.Errorf("error creating local OIDC session: %w", err) } - oi.auditLogger.Audit(audit.AuthLoginSuccessNo2FA, map[string]any{"email": sr.Email}) + oi.auditLogger.Audit(audit.AuthLoginSuccessNo2FA, map[string]any{"email": sr.Email, "role": foundUser.Role, "method": "local_admin"}) return session.ID, nil } diff --git a/core/web/router.go b/core/web/router.go index 0be1fa20d2a..d8a641b0c51 100644 --- a/core/web/router.go +++ b/core/web/router.go @@ -646,6 +646,7 @@ var blacklist = map[string]struct{}{ "oldpassword": {}, "current_password": {}, "new_account_password": {}, + "device_handle": {}, } func isBlacklisted(k string) bool { From 96abafbac7bdc049bcdfa5676e3791d5b3ba78d3 Mon Sep 17 00:00:00 2001 From: Harry Anderson Date: Tue, 23 Jun 2026 06:07:33 +0000 Subject: [PATCH 05/18] test(oidc): update issueSessionFromIDToken callers for role return value --- core/sessions/oidcauth/verify_flow_test.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/core/sessions/oidcauth/verify_flow_test.go b/core/sessions/oidcauth/verify_flow_test.go index 0d8532e1200..2adadd46bc8 100644 --- a/core/sessions/oidcauth/verify_flow_test.go +++ b/core/sessions/oidcauth/verify_flow_test.go @@ -33,7 +33,7 @@ func TestIssueSessionFromIDToken_Valid(t *testing.T) { oi := newAuthenticatorForIDP(t, idp, db) raw := idp.signIDToken(t) - sessionID, email, err := oi.issueSessionFromIDToken(context.Background(), raw) + sessionID, email, _, err := oi.issueSessionFromIDToken(context.Background(), raw) require.NoError(t, err) assert.NotEmpty(t, sessionID) assert.Equal(t, "valid-user@example.com", email) @@ -51,7 +51,7 @@ func TestIssueSessionFromIDToken_WrongAudience(t *testing.T) { oi := newAuthenticatorForIDP(t, idp, db) raw := idp.signIDToken(t) - _, _, err := oi.issueSessionFromIDToken(context.Background(), raw) + _, _, _, err := oi.issueSessionFromIDToken(context.Background(), raw) require.Error(t, err, "token with mismatched audience must be rejected") assert.Contains(t, err.Error(), "verify") assert.Equal(t, 0, countOIDCSessions(t, oi, "attacker@example.com")) @@ -67,7 +67,7 @@ func TestIssueSessionFromIDToken_Expired(t *testing.T) { oi := newAuthenticatorForIDP(t, idp, db) raw := idp.signIDToken(t) - _, _, err := oi.issueSessionFromIDToken(context.Background(), raw) + _, _, _, err := oi.issueSessionFromIDToken(context.Background(), raw) require.Error(t, err, "expired token must be rejected") assert.Equal(t, 0, countOIDCSessions(t, oi, "expired-user@example.com")) } @@ -84,7 +84,7 @@ func TestIssueSessionFromIDToken_NoMatchingGroup(t *testing.T) { oi := newAuthenticatorForIDP(t, idp, db) raw := idp.signIDToken(t) - _, _, err := oi.issueSessionFromIDToken(context.Background(), raw) + _, _, _, err := oi.issueSessionFromIDToken(context.Background(), raw) require.ErrorIs(t, err, errNoMatchingRole) assert.Equal(t, 0, countOIDCSessions(t, oi, "nogroup-user@example.com")) } @@ -112,7 +112,7 @@ func TestIssueSessionFromIDToken_RoleMapping(t *testing.T) { idp.groups = []string{tc.group} oi := newAuthenticatorForIDP(t, idp, db) - _, _, err := oi.issueSessionFromIDToken(context.Background(), idp.signIDToken(t)) + _, _, _, err := oi.issueSessionFromIDToken(context.Background(), idp.signIDToken(t)) require.NoError(t, err) var role string From b5f98ef8d1c3480a6d5a6824eb57cc6b1d4f0253 Mon Sep 17 00:00:00 2001 From: Harry Anderson Date: Tue, 23 Jun 2026 09:27:11 +0000 Subject: [PATCH 06/18] fix(oidc): move error to last return value in consumeIfDone (revive) --- core/sessions/oidcauth/device_flow.go | 10 +++++----- core/sessions/oidcauth/device_flow_test.go | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/core/sessions/oidcauth/device_flow.go b/core/sessions/oidcauth/device_flow.go index af7967842d5..964e12d8cd0 100644 --- a/core/sessions/oidcauth/device_flow.go +++ b/core/sessions/oidcauth/device_flow.go @@ -112,20 +112,20 @@ func (s *deviceFlowStore) remove(handle string) { // closes the double-poll window: two concurrent polls on a completed handle // cannot both observe done and both be issued the session cookie; exactly one // sees terminal=true, the rest see (nil, false) once it is gone. -func (s *deviceFlowStore) consumeIfDone(handle string) (sessionID, email string, role clsessions.UserRole, flowErr error, terminal bool, known bool) { +func (s *deviceFlowStore) consumeIfDone(handle string) (sessionID, email string, role clsessions.UserRole, terminal bool, known bool, flowErr error) { s.mu.Lock() defer s.mu.Unlock() f, ok := s.flows[handle] if !ok { - return "", "", "", nil, false, false + return "", "", "", false, false, nil } f.mu.Lock() defer f.mu.Unlock() if !f.done { - return "", "", "", nil, false, true + return "", "", "", false, true, nil } delete(s.flows, handle) - return f.sessionID, f.email, f.role, f.err, true, true + return f.sessionID, f.email, f.role, true, true, f.err } // generateDeviceHandle returns a URL-safe 256-bit random handle. It is the only @@ -263,7 +263,7 @@ func (oi *oidcAuthenticator) handleDevicePoll(c *gin.Context) { // Read the terminal result and consume the handle in one critical section // so two concurrent polls cannot both be handed the session cookie. - sessionID, email, role, flowErr, terminal, known := oi.deviceFlows.consumeIfDone(req.DeviceHandle) + sessionID, email, role, terminal, known, flowErr := oi.deviceFlows.consumeIfDone(req.DeviceHandle) if !known { c.JSON(http.StatusNotFound, DevicePollResponse{Status: "denied", Message: errUnknownDeviceFlow.Error()}) return diff --git a/core/sessions/oidcauth/device_flow_test.go b/core/sessions/oidcauth/device_flow_test.go index 8e89dafb5eb..e82c38a5d5c 100644 --- a/core/sessions/oidcauth/device_flow_test.go +++ b/core/sessions/oidcauth/device_flow_test.go @@ -53,7 +53,7 @@ func TestDeviceFlowStore_ConsumeIfDoneSingleWinner(t *testing.T) { for range pollers { go func() { defer wg.Done() - sessionID, _, _, _, terminal, known := s.consumeIfDone("race-handle") + sessionID, _, _, terminal, known, _ := s.consumeIfDone("race-handle") mu.Lock() defer mu.Unlock() switch { From cacf25a69067988a191b99f2844918043f8b9da8 Mon Sep 17 00:00:00 2001 From: Harry Anderson Date: Sat, 11 Jul 2026 08:45:09 +0000 Subject: [PATCH 07/18] fix(oidc): harden device flow and auth-code security controls - Dedicated pre-auth rate limits on /oidc-device/start and /poll - Per-IP concurrent device-flow cap (plus existing global cap) - Reserve store slot before outbound IdP DeviceAuth calls - Server-side PKCE verifier + OIDC nonce (not in session cookie) - Nonce verification on browser id_token path - Reject empty/invalid email claims - Delete orphan oidc_sessions if cookie Save fails or handle expires - Stricter CLI /oidc-enabled probe (require enabled:true JSON) - Document multi-replica sticky-session requirement --- .changeset/oidc-cli-device-flow.md | 2 + core/cmd/oidc_device_auth.go | 15 ++- core/cmd/oidc_device_auth_test.go | 11 +- core/sessions/oidcauth/device_flow.go | 145 ++++++++++++++++++--- core/sessions/oidcauth/device_flow_test.go | 59 +++++++++ core/sessions/oidcauth/helpers_test.go | 1 + core/sessions/oidcauth/mock_idp_test.go | 5 + core/sessions/oidcauth/oidc.go | 106 +++++++++++---- core/sessions/oidcauth/pending_auth.go | 68 ++++++++++ core/sessions/oidcauth/verify_flow_test.go | 58 ++++++++- 10 files changed, 417 insertions(+), 53 deletions(-) create mode 100644 core/sessions/oidcauth/pending_auth.go diff --git a/.changeset/oidc-cli-device-flow.md b/.changeset/oidc-cli-device-flow.md index 09aa9ae70e8..b6eb88c6738 100644 --- a/.changeset/oidc-cli-device-flow.md +++ b/.changeset/oidc-cli-device-flow.md @@ -5,3 +5,5 @@ #added Added OIDC login support to the CLI via the OAuth 2.0 device authorization grant (RFC 8628). When a node is configured with `AuthenticationMethod = 'oidc'`, `chainlink admin login` (with no credentials file) now performs a browser-based device flow against the identity provider, brokered by the node. The local email/password path is unchanged and remains available as a break-glass admin. #changed The OIDC authorization-code (operator UI) flow now always uses PKCE (RFC 7636). The OIDC `ClientSecret` is now optional: confidential clients still send it, while public clients (required for the device flow) rely on PKCE instead. Existing confidential-client deployments are unaffected. + +#changed Hardened OIDC device and auth-code flows: dedicated pre-auth rate limits and per-IP concurrency caps on device endpoints, server-side PKCE verifier and OIDC nonce (not stored in the session cookie), email claim validation, orphan-session cleanup if cookie bind fails, and a stricter CLI `/oidc-enabled` probe. diff --git a/core/cmd/oidc_device_auth.go b/core/cmd/oidc_device_auth.go index bfda0d10162..ea1547d6df4 100644 --- a/core/cmd/oidc_device_auth.go +++ b/core/cmd/oidc_device_auth.go @@ -63,7 +63,9 @@ func NewOIDCDeviceCookieAuthenticator(config ClientOpts, store CookieStore, out } // NodeHasOIDCEnabled probes the node's unauthenticated /oidc-enabled endpoint to -// decide whether the device flow applies. A non-OIDC node 404s the route. +// decide whether the device flow applies. A non-OIDC node 404s the route. The +// body must be JSON with enabled=true so a reverse-proxy 200 HTML page cannot +// accidentally trigger the device-flow path. func NodeHasOIDCEnabled(ctx context.Context, config ClientOpts, lggr logger.Logger) bool { client := newHttpClient(lggr, config.InsecureSkipVerify) u := config.RemoteNodeURL.String() + "/oidc-enabled" @@ -76,7 +78,16 @@ func NodeHasOIDCEnabled(ctx context.Context, config ClientOpts, lggr logger.Logg return false } defer resp.Body.Close() - return resp.StatusCode == http.StatusOK + if resp.StatusCode != http.StatusOK { + return false + } + var body struct { + Enabled bool `json:"enabled"` + } + if err := json.NewDecoder(resp.Body).Decode(&body); err != nil { + return false + } + return body.Enabled } // Login runs the full device flow: start, prompt the operator, poll until the diff --git a/core/cmd/oidc_device_auth_test.go b/core/cmd/oidc_device_auth_test.go index 6179eba4b83..3fd7cadedda 100644 --- a/core/cmd/oidc_device_auth_test.go +++ b/core/cmd/oidc_device_auth_test.go @@ -32,7 +32,8 @@ func (m *mockNode) handler(t *testing.T) http.Handler { w.WriteHeader(http.StatusNotFound) return } - w.WriteHeader(http.StatusOK) + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]bool{"enabled": true}) }) mux.HandleFunc("/oidc-device/start", func(w http.ResponseWriter, r *http.Request) { // assert (not require) inside handler goroutines: require calls Goexit @@ -92,6 +93,14 @@ func TestNodeHasOIDCEnabled(t *testing.T) { srv2 := httptest.NewServer(disabled.handler(t)) defer srv2.Close() assert.False(t, cmd.NodeHasOIDCEnabled(context.Background(), newClientOpts(t, srv2), lggr)) + + // HTTP 200 without {"enabled":true} must not trigger the device flow. + bare200 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte("ok")) + })) + defer bare200.Close() + assert.False(t, cmd.NodeHasOIDCEnabled(context.Background(), newClientOpts(t, bare200), lggr)) } func TestOIDCDeviceLogin_Success(t *testing.T) { diff --git a/core/sessions/oidcauth/device_flow.go b/core/sessions/oidcauth/device_flow.go index 964e12d8cd0..e82618bb1ed 100644 --- a/core/sessions/oidcauth/device_flow.go +++ b/core/sessions/oidcauth/device_flow.go @@ -12,6 +12,9 @@ import ( "github.com/gin-contrib/sessions" "github.com/gin-gonic/gin" + "github.com/ulule/limiter/v3" + mgin "github.com/ulule/limiter/v3/drivers/middleware/gin" + "github.com/ulule/limiter/v3/drivers/store/memory" "golang.org/x/oauth2" "github.com/smartcontractkit/chainlink/v2/core/logger/audit" @@ -32,18 +35,38 @@ import ( // slow_down backoff. The CLI's poll to the node is therefore decoupled from the // node's poll to the provider: no matter how fast the CLI asks, the node never // exceeds the provider's cadence. +// +// Multi-replica note: deviceFlowStore is process-local memory. Deployments with +// more than one replica behind a load balancer MUST use session affinity +// (sticky sessions) for /oidc-device/* (and preferably the whole node API), or +// replace this store with a shared short-TTL backend. Without affinity, start +// and poll can land on different replicas and the login fails closed. const ( // maxConcurrentDeviceFlows bounds the in-memory store so unauthenticated // callers cannot exhaust memory or fan out provider load without limit. maxConcurrentDeviceFlows = 100 + // maxDeviceFlowsPerIP stops a single source from consuming the entire + // global budget (fairness / DoS). + maxDeviceFlowsPerIP = 5 // deviceHandleBytes is the entropy of the opaque handle returned to the CLI. deviceHandleBytes = 32 // 256 bits + + // Dedicated pre-auth rate limits for device endpoints. These sit on top of + // the outer authenticated-tier limiter and match the unauth tier defaults + // for start (expensive: outbound IdP call + goroutine). Poll is looser so a + // legitimate CLI can tick at the provider interval. + deviceStartRateLimit = 5 + deviceStartRatePeriod = 20 * time.Second + devicePollRateLimit = 60 + devicePollRatePeriod = time.Minute ) var ( - errTooManyDeviceFlows = errors.New("too many concurrent device authorization flows in progress") - errUnknownDeviceFlow = errors.New("unknown or expired device authorization flow") + errTooManyDeviceFlows = errors.New("too many concurrent device authorization flows in progress") + errTooManyDeviceFlowsPerIP = errors.New("too many concurrent device authorization flows from this address") + errUnknownDeviceFlow = errors.New("unknown or expired device authorization flow") + errDeviceFlowAbandoned = errors.New("device authorization flow expired or abandoned before completion") ) // deviceFlowState is the per-flow state held server-side while a device @@ -52,6 +75,7 @@ var ( type deviceFlowState struct { mu sync.Mutex expiresAt time.Time + clientIP string done bool sessionID string email string @@ -81,8 +105,10 @@ func (s *deviceFlowStore) sweepLocked(now time.Time) { } } -// add stores a flow under a fresh handle, enforcing the concurrency cap. The -// caller must not have logged or persisted the provider device_code. +// add stores a flow under a fresh handle, enforcing the global and per-IP +// concurrency caps. The caller must not have logged or persisted the provider +// device_code. Prefer reserving the slot *before* calling the IdP so a refused +// flow never produces outbound provider load. func (s *deviceFlowStore) add(handle string, f *deviceFlowState) error { s.mu.Lock() defer s.mu.Unlock() @@ -90,6 +116,17 @@ func (s *deviceFlowStore) add(handle string, f *deviceFlowState) error { if len(s.flows) >= maxConcurrentDeviceFlows { return errTooManyDeviceFlows } + if f.clientIP != "" { + n := 0 + for _, existing := range s.flows { + if existing.clientIP == f.clientIP { + n++ + } + } + if n >= maxDeviceFlowsPerIP { + return errTooManyDeviceFlowsPerIP + } + } s.flows[handle] = f return nil } @@ -101,6 +138,14 @@ func (s *deviceFlowStore) get(handle string) (*deviceFlowState, bool) { return f, ok } +// contains reports whether handle is still present (not swept/consumed). +func (s *deviceFlowStore) contains(handle string) bool { + s.mu.Lock() + defer s.mu.Unlock() + _, ok := s.flows[handle] + return ok +} + func (s *deviceFlowStore) remove(handle string) { s.mu.Lock() defer s.mu.Unlock() @@ -163,21 +208,46 @@ type DevicePollResponse struct { Message string `json:"message,omitempty"` } +// deviceEndpointRateLimit builds a dedicated per-IP limiter for pre-auth device +// routes. Nested under the outer api group so both limits apply. +func deviceEndpointRateLimit(period time.Duration, limit int64) gin.HandlerFunc { + store := memory.NewStore() + rate := limiter.Rate{ + Period: period, + Limit: limit, + } + return mgin.NewMiddleware(limiter.New(store, rate)) +} + // handleDeviceStart begins a device authorization flow. Unauthenticated, like // the browser /oidc-login route: it only initiates the provider handshake. func (oi *oidcAuthenticator) handleDeviceStart(c *gin.Context) { - ctx := context.Background() - da, err := oi.oauth2Config.DeviceAuth(ctx) + handle, err := oi.generateDeviceHandle() if err != nil { - oi.lggr.Errorf("device authorization request failed: %v", err) - c.JSON(http.StatusBadGateway, gin.H{"error": "Failed to start device authorization"}) + oi.lggr.Errorf("failed to generate device handle: %v", err) + c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to start device authorization"}) return } - handle, err := oi.generateDeviceHandle() + // Reserve a concurrency slot *before* calling the IdP so a refused flow + // never produces outbound provider load, and so a flood cannot open more + // IdP device codes than the store will accept. + state := &deviceFlowState{ + expiresAt: time.Now().Add(5 * time.Minute), // provisional; refined after IdP response + clientIP: c.ClientIP(), + } + if err := oi.deviceFlows.add(handle, state); err != nil { + oi.lggr.Warnf("refusing new device flow: %v", err) + c.JSON(http.StatusTooManyRequests, gin.H{"error": err.Error()}) + return + } + + ctx := context.Background() + da, err := oi.oauth2Config.DeviceAuth(ctx) if err != nil { - oi.lggr.Errorf("failed to generate device handle: %v", err) - c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to start device authorization"}) + oi.deviceFlows.remove(handle) + oi.lggr.Errorf("device authorization request failed: %v", err) + c.JSON(http.StatusBadGateway, gin.H{"error": "Failed to start device authorization"}) return } @@ -188,13 +258,9 @@ func (oi *oidcAuthenticator) handleDeviceStart(c *gin.Context) { // unbounded flow. expiry = time.Now().Add(5 * time.Minute) } - state := &deviceFlowState{expiresAt: expiry} - - if err := oi.deviceFlows.add(handle, state); err != nil { - oi.lggr.Warnf("refusing new device flow: %v", err) - c.JSON(http.StatusTooManyRequests, gin.H{"error": err.Error()}) - return - } + state.mu.Lock() + state.expiresAt = expiry + state.mu.Unlock() // Poll the provider in the background. DeviceAccessToken blocks until the // user approves, denies, or the code expires, internally respecting the @@ -234,8 +300,31 @@ func (oi *oidcAuthenticator) pollDeviceToken(handle string, state *deviceFlowSta return } - sessionID, email, role, err := oi.issueSessionFromIDToken(ctx, rawIDToken) - oi.finishDeviceFlow(state, sessionID, email, role, err) + // If the handle was swept/expired while we waited on the IdP, do not mint a + // session nobody can claim (orphan oidc_sessions row). + if !oi.deviceFlows.contains(handle) { + oi.lggr.Warnf("device flow handle gone before token completion; abandoning without session") + oi.finishDeviceFlow(state, "", "", "", errDeviceFlowAbandoned) + return + } + + // Device flow does not use a browser nonce; pass empty expectedNonce. + sessionID, email, role, err := oi.issueSessionFromIDToken(ctx, rawIDToken, "") + if err != nil { + oi.finishDeviceFlow(state, "", "", "", err) + return + } + + // Race: handle may have been swept between contains and issue. Drop the + // orphan session rather than leave a live unclaimable row. + if !oi.deviceFlows.contains(handle) { + oi.lggr.Warnf("device flow handle gone after session insert; deleting orphan session") + oi.deleteOIDCSession(ctx, sessionID) + oi.finishDeviceFlow(state, "", "", "", errDeviceFlowAbandoned) + return + } + + oi.finishDeviceFlow(state, sessionID, email, role, nil) } func (oi *oidcAuthenticator) finishDeviceFlow(state *deviceFlowState, sessionID, email string, role clsessions.UserRole, err error) { @@ -251,6 +340,17 @@ func (oi *oidcAuthenticator) finishDeviceFlow(state *deviceFlowState, sessionID, } } +// deleteOIDCSession removes a session row that was minted but never bound to a +// client cookie (Save failure or abandoned device flow). +func (oi *oidcAuthenticator) deleteOIDCSession(ctx context.Context, sessionID string) { + if sessionID == "" { + return + } + if _, err := oi.ds.ExecContext(ctx, "DELETE FROM oidc_sessions WHERE id = $1", sessionID); err != nil { + oi.lggr.Errorf("failed to delete orphan OIDC session %s: %v", sessionID, err) + } +} + // handleDevicePoll reports the status of a pending flow to the CLI and, once // complete, sets the session cookie. The handle is single-use: a completed flow // is removed after its cookie is issued or its failure reported. @@ -275,6 +375,8 @@ func (oi *oidcAuthenticator) handleDevicePoll(c *gin.Context) { } if flowErr != nil { + // Terminal failure already consumed the handle; no session to clean up + // unless a prior success path left one (should not happen). c.JSON(http.StatusOK, DevicePollResponse{Status: "denied", Message: "Authorization was not completed"}) return } @@ -284,7 +386,10 @@ func (oi *oidcAuthenticator) handleDevicePoll(c *gin.Context) { ginSession := sessions.Default(c) ginSession.Set(webauth.SessionIDKey, sessionID) if err := ginSession.Save(); err != nil { + // Handle is already consumed (single-winner). Delete the session row so + // we do not leave a live unclaimable credential; the CLI must restart. oi.lggr.Errorf("failed to save device flow session: %v", err) + oi.deleteOIDCSession(context.Background(), sessionID) c.JSON(http.StatusInternalServerError, DevicePollResponse{Status: "denied", Message: "Failed to establish session"}) return } diff --git a/core/sessions/oidcauth/device_flow_test.go b/core/sessions/oidcauth/device_flow_test.go index e82c38a5d5c..3f4400dd02a 100644 --- a/core/sessions/oidcauth/device_flow_test.go +++ b/core/sessions/oidcauth/device_flow_test.go @@ -84,6 +84,65 @@ func TestDeviceFlowStore_ConcurrencyCap(t *testing.T) { require.ErrorIs(t, err, errTooManyDeviceFlows) } +func TestDeviceFlowStore_PerIPCap(t *testing.T) { + t.Parallel() + s := newDeviceFlowStore() + ip := "203.0.113.10" + for i := range maxDeviceFlowsPerIP { + require.NoError(t, s.add(handleN(i), &deviceFlowState{ + expiresAt: time.Now().Add(time.Minute), + clientIP: ip, + })) + } + err := s.add("overflow-ip", &deviceFlowState{ + expiresAt: time.Now().Add(time.Minute), + clientIP: ip, + }) + require.ErrorIs(t, err, errTooManyDeviceFlowsPerIP) + + // A different IP can still open a flow. + require.NoError(t, s.add("other-ip", &deviceFlowState{ + expiresAt: time.Now().Add(time.Minute), + clientIP: "198.51.100.1", + })) +} + +func TestDeviceFlowStore_Contains(t *testing.T) { + t.Parallel() + s := newDeviceFlowStore() + require.False(t, s.contains("missing")) + require.NoError(t, s.add("h1", &deviceFlowState{expiresAt: time.Now().Add(time.Minute)})) + require.True(t, s.contains("h1")) + s.remove("h1") + require.False(t, s.contains("h1")) +} + +func TestPendingAuthStore_PutTakeSingleUse(t *testing.T) { + t.Parallel() + s := newPendingAuthStore() + s.put("state-1", "verifier-1", "nonce-1") + v, n, ok := s.take("state-1") + require.True(t, ok) + assert.Equal(t, "verifier-1", v) + assert.Equal(t, "nonce-1", n) + _, _, ok = s.take("state-1") + assert.False(t, ok, "take must be single-use") +} + +func TestNormalizeEmailClaim(t *testing.T) { + t.Parallel() + email, err := normalizeEmailClaim(map[string]any{"email": " User@Example.COM "}) + require.NoError(t, err) + assert.Equal(t, "User@Example.COM", email) + + _, err = normalizeEmailClaim(map[string]any{"email": ""}) + require.Error(t, err) + _, err = normalizeEmailClaim(map[string]any{"email": "not-an-email"}) + require.Error(t, err) + _, err = normalizeEmailClaim(map[string]any{}) + require.Error(t, err) +} + func TestDeviceFlowStore_ExpiredSweptOnAdd(t *testing.T) { t.Parallel() s := newDeviceFlowStore() diff --git a/core/sessions/oidcauth/helpers_test.go b/core/sessions/oidcauth/helpers_test.go index f5761aaa284..9db09d254c8 100644 --- a/core/sessions/oidcauth/helpers_test.go +++ b/core/sessions/oidcauth/helpers_test.go @@ -54,6 +54,7 @@ func NewTestOIDCAuthenticator( lggr: logger.Sugared(lggr).Named("OIDCAuthenticationProvider"), auditLogger: auditLogger, deviceFlows: newDeviceFlowStore(), + pendingAuth: newPendingAuthStore(), } return &oidcAuth, nil diff --git a/core/sessions/oidcauth/mock_idp_test.go b/core/sessions/oidcauth/mock_idp_test.go index 90538fc4e2b..1e075edc48e 100644 --- a/core/sessions/oidcauth/mock_idp_test.go +++ b/core/sessions/oidcauth/mock_idp_test.go @@ -36,6 +36,7 @@ type mockIDP struct { issuerOverride string // "iss" claim; default = server URL groups []string // groups claim email string // email claim + nonce string // optional "nonce" claim lifetime time.Duration // exp relative to now; negative => already expired clientID string @@ -131,6 +132,9 @@ func (m *mockIDP) signIDToken(t *testing.T) string { "iat": now.Unix(), "exp": now.Add(m.lifetime).Unix(), } + if m.nonce != "" { + claims["nonce"] = m.nonce + } raw, err := jwt.Signed(m.signer).Claims(claims).Serialize() require.NoError(t, err) return raw @@ -154,5 +158,6 @@ func newAuthenticatorForIDP(t *testing.T, idp *mockIDP, ds sqlutil.DataSource) * lggr: logger.TestLogger(t), auditLogger: &audit.AuditLoggerService{}, deviceFlows: newDeviceFlowStore(), + pendingAuth: newPendingAuthStore(), } } diff --git a/core/sessions/oidcauth/oidc.go b/core/sessions/oidcauth/oidc.go index fef23559e32..16031cc5abe 100644 --- a/core/sessions/oidcauth/oidc.go +++ b/core/sessions/oidcauth/oidc.go @@ -15,6 +15,7 @@ import ( "io" "log" "net/http" + "net/mail" "slices" "strings" @@ -50,6 +51,9 @@ type oidcAuthenticator struct { lggr logger.SugaredLogger auditLogger audit.Logger deviceFlows *deviceFlowStore + // pendingAuth holds PKCE verifiers and OIDC nonces server-side for the + // browser authorization-code flow (not in the signed session cookie). + pendingAuth *pendingAuthStore } // ExchangeTokenRequest represents the expected JSON payload from the frontend @@ -136,8 +140,13 @@ func NewOIDCAuthenticator( lggr: logger.Sugared(lggr).Named("OIDCAuthenticationProvider"), auditLogger: auditLogger, deviceFlows: newDeviceFlowStore(), + pendingAuth: newPendingAuthStore(), } + // Device-flow and pending-auth state are process-local. Multi-replica nodes + // need sticky sessions for OIDC routes (see device_flow.go header comment). + oidcAuth.lggr.Infof("OIDC authenticator ready (device flow + PKCE). Multi-replica deployments require session affinity for /oidc-device/* and /oidc-login|/oidc-exchange") + return &oidcAuth, nil } @@ -155,24 +164,33 @@ func (oi *oidcAuthenticator) handleCheckEnabled(c *gin.Context) { } func (oi *oidcAuthenticator) handleSignIn(c *gin.Context) { - // generate state and a PKCE verifier, store both on the session. PKCE (RFC - // 7636) is sent unconditionally: it is additive hardening for confidential - // clients and the sole proof-of-possession for public clients that carry no - // secret. The challenge derived from the verifier travels to the provider; - // the verifier stays server-side until the exchange. + // Generate state (anti-CSRF, stored in the browser session cookie), plus a + // PKCE verifier and OIDC nonce kept server-side only. PKCE (RFC 7636) is + // sent unconditionally: additive hardening for confidential clients and the + // sole proof-of-possession for public clients. The S256 challenge travels + // to the provider; the verifier never leaves the node (not even in the + // signed session cookie, which is not encrypted). state := oi.generateState() verifier := oauth2.GenerateVerifier() + nonce := oi.generateState() + oi.pendingAuth.put(state, verifier, nonce) + session := sessions.Default(c) session.Set("state", state) - session.Set("pkce_verifier", verifier) + // Intentionally do NOT store pkce_verifier or nonce in the cookie. err := session.Save() if err != nil { + oi.pendingAuth.take(state) // best-effort cleanup c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save session"}) return } - // redirect to provider - url := oi.oauth2Config.AuthCodeURL(state, oauth2.AccessTypeOffline, oauth2.S256ChallengeOption(verifier)) + url := oi.oauth2Config.AuthCodeURL( + state, + oauth2.AccessTypeOffline, + oauth2.S256ChallengeOption(verifier), + oidc.Nonce(nonce), + ) c.Redirect(http.StatusFound, url) } @@ -187,25 +205,24 @@ func (oi *oidcAuthenticator) handleTokenExchange(c *gin.Context) { return } - // check state matches stored value on the session + // check state matches stored value on the session (constant-time compare) ginSession := sessions.Default(c) - storedState := ginSession.Get("state") - if storedState == nil || req.State != storedState.(string) { + storedState, _ := ginSession.Get("state").(string) + ginSession.Delete("state") + if storedState == "" || subtle.ConstantTimeCompare([]byte(req.State), []byte(storedState)) != 1 { c.JSON(http.StatusBadRequest, ExchangeTokenResponse{ Success: false, Message: "Invalid state parameter", }) return } - ginSession.Delete("state") - // Recover the PKCE verifier stored at sign-in and bind it to this exchange. - storedVerifier, _ := ginSession.Get("pkce_verifier").(string) - ginSession.Delete("pkce_verifier") - if storedVerifier == "" { + // Recover PKCE verifier + nonce from the server-side store (single-use). + storedVerifier, expectedNonce, ok := oi.pendingAuth.take(req.State) + if !ok || storedVerifier == "" { c.JSON(http.StatusBadRequest, ExchangeTokenResponse{ Success: false, - Message: "Missing PKCE verifier", + Message: "Missing or expired authorization state", }) return } @@ -227,12 +244,12 @@ func (oi *oidcAuthenticator) handleTokenExchange(c *gin.Context) { // Request token from provider for claims lookup and verification rawIDToken, ok := oauth2Token.Extra("id_token").(string) if !ok { - oi.lggr.Errorf("No id_token field in oauth2 token: %v", err) + oi.lggr.Errorf("No id_token field in oauth2 token") c.String(http.StatusInternalServerError, "Missing id_token field in response") return } - sessionID, email, role, err := oi.issueSessionFromIDToken(ctx, rawIDToken) + sessionID, email, role, err := oi.issueSessionFromIDToken(ctx, rawIDToken, expectedNonce) if err != nil { oi.handleIssueSessionError(c, err) return @@ -243,6 +260,7 @@ func (oi *oidcAuthenticator) handleTokenExchange(c *gin.Context) { err = ginSession.Save() if err != nil { oi.lggr.Errorf("failed to saved session %v", err) + oi.deleteOIDCSession(ctx, sessionID) c.String(http.StatusInternalServerError, "Authentication failed") return } @@ -267,13 +285,22 @@ var errNoMatchingRole = errors.New("no matching role within attested user group // the new session ID, the authenticated email, and the resolved role. The // caller emits the success audit event tagged with its login method so device // and UI sessions are distinguishable; this function audits only failures. -func (oi *oidcAuthenticator) issueSessionFromIDToken(ctx context.Context, rawIDToken string) (string, string, clsessions.UserRole, error) { +// +// expectedNonce, when non-empty, must match the id_token nonce claim (browser +// auth-code flow). Pass "" for the device flow, which does not use a nonce. +func (oi *oidcAuthenticator) issueSessionFromIDToken(ctx context.Context, rawIDToken string, expectedNonce string) (string, string, clsessions.UserRole, error) { // Verify signature, issuer, expiry, and audience (pinned to ClientID). idToken, err := oi.provider.Verifier(oi.oidcConfig).Verify(ctx, rawIDToken) if err != nil { return "", "", "", fmt.Errorf("failed to verify ID token: %w", err) } + if expectedNonce != "" { + if subtle.ConstantTimeCompare([]byte(idToken.Nonce), []byte(expectedNonce)) != 1 { + return "", "", "", errors.New("id_token nonce mismatch") + } + } + var claims map[string]any if err = idToken.Claims(&claims); err != nil { return "", "", "", fmt.Errorf("failed to parse OIDC return claims: %w", err) @@ -284,9 +311,9 @@ func (oi *oidcAuthenticator) issueSessionFromIDToken(ctx context.Context, rawIDT return "", "", "", fmt.Errorf("failed to extract ID claims for claim name '%s': %w", oi.config.ClaimName(), err) } - email, ok := claims["email"].(string) - if !ok { - return "", "", "", errors.New("failed to get email from claims") + email, err := normalizeEmailClaim(claims) + if err != nil { + return "", "", "", err } oi.lggr.Tracef("Received and validated ID claims: %v\n", idClaims) @@ -319,6 +346,25 @@ func (oi *oidcAuthenticator) issueSessionFromIDToken(ctx context.Context, rawIDT return clSession.ID, email, role, nil } +// normalizeEmailClaim extracts and validates the email claim from a verified +// id_token. Rejects missing, empty, or syntactically invalid addresses so we +// never mint a session under a blank or garbage identity. +func normalizeEmailClaim(claims map[string]any) (string, error) { + raw, ok := claims["email"].(string) + if !ok { + return "", errors.New("failed to get email from claims") + } + raw = strings.TrimSpace(raw) + if raw == "" { + return "", errors.New("email claim is empty") + } + addr, err := mail.ParseAddress(raw) + if err != nil || addr.Address == "" { + return "", errors.New("email claim is not a valid address") + } + return addr.Address, nil +} + // handleIssueSessionError maps an issueSessionFromIDToken error to the HTTP // status the browser exchange returns: a missing/invalid role is a client-side // 400, everything else is a 500. @@ -722,9 +768,19 @@ func (oi *oidcAuthenticator) ExtendRouter(api *gin.RouterGroup) error { api.GET("/oidc-enabled", oi.handleCheckEnabled) api.GET("/oidc-login", oi.handleSignIn) api.POST("/oidc-exchange", oi.handleTokenExchange) + // Device authorization grant for headless clients (the CLI). - api.POST("/oidc-device/start", oi.handleDeviceStart) - api.POST("/oidc-device/poll", oi.handleDevicePoll) + // Dedicated pre-auth rate limits: start is expensive (outbound IdP call + + // background goroutine); poll is cheaper but still unauthenticated. + // These nest under the outer api rate limiter so both apply. + api.POST("/oidc-device/start", + deviceEndpointRateLimit(deviceStartRatePeriod, deviceStartRateLimit), + oi.handleDeviceStart, + ) + api.POST("/oidc-device/poll", + deviceEndpointRateLimit(devicePollRatePeriod, devicePollRateLimit), + oi.handleDevicePoll, + ) return nil } diff --git a/core/sessions/oidcauth/pending_auth.go b/core/sessions/oidcauth/pending_auth.go new file mode 100644 index 00000000000..bae794c41b1 --- /dev/null +++ b/core/sessions/oidcauth/pending_auth.go @@ -0,0 +1,68 @@ +package oidcauth + +import ( + "sync" + "time" +) + +// pendingAuth holds server-side secrets for one browser authorization-code +// login. The PKCE verifier and OIDC nonce must not round-trip through the +// signed-but-not-encrypted session cookie (see OCD-004 / OCD-005). Only the +// anti-CSRF state value is stored client-side; the secrets stay here, keyed by +// that state, until a single successful take() at exchange time. +// +// Like deviceFlowStore this is process-local: multi-replica deployments need +// session affinity for /oidc-login → /oidc-exchange, or a shared short-TTL store. +type pendingAuth struct { + verifier string + nonce string + expiresAt time.Time +} + +type pendingAuthStore struct { + mu sync.Mutex + entries map[string]pendingAuth +} + +func newPendingAuthStore() *pendingAuthStore { + return &pendingAuthStore{entries: make(map[string]pendingAuth)} +} + +const pendingAuthTTL = 15 * time.Minute + +func (s *pendingAuthStore) sweepLocked(now time.Time) { + for k, e := range s.entries { + if now.After(e.expiresAt) { + delete(s.entries, k) + } + } +} + +// put records verifier+nonce for state. Overwrites any prior entry for the same +// state (should not happen with 256-bit state values). +func (s *pendingAuthStore) put(state, verifier, nonce string) { + s.mu.Lock() + defer s.mu.Unlock() + s.sweepLocked(time.Now()) + s.entries[state] = pendingAuth{ + verifier: verifier, + nonce: nonce, + expiresAt: time.Now().Add(pendingAuthTTL), + } +} + +// take removes and returns the entry for state. Single-use: a second take fails. +func (s *pendingAuthStore) take(state string) (verifier, nonce string, ok bool) { + s.mu.Lock() + defer s.mu.Unlock() + s.sweepLocked(time.Now()) + e, ok := s.entries[state] + if !ok { + return "", "", false + } + delete(s.entries, state) + if time.Now().After(e.expiresAt) { + return "", "", false + } + return e.verifier, e.nonce, true +} diff --git a/core/sessions/oidcauth/verify_flow_test.go b/core/sessions/oidcauth/verify_flow_test.go index 2adadd46bc8..603b18f02eb 100644 --- a/core/sessions/oidcauth/verify_flow_test.go +++ b/core/sessions/oidcauth/verify_flow_test.go @@ -33,7 +33,7 @@ func TestIssueSessionFromIDToken_Valid(t *testing.T) { oi := newAuthenticatorForIDP(t, idp, db) raw := idp.signIDToken(t) - sessionID, email, _, err := oi.issueSessionFromIDToken(context.Background(), raw) + sessionID, email, _, err := oi.issueSessionFromIDToken(context.Background(), raw, "") require.NoError(t, err) assert.NotEmpty(t, sessionID) assert.Equal(t, "valid-user@example.com", email) @@ -51,7 +51,7 @@ func TestIssueSessionFromIDToken_WrongAudience(t *testing.T) { oi := newAuthenticatorForIDP(t, idp, db) raw := idp.signIDToken(t) - _, _, _, err := oi.issueSessionFromIDToken(context.Background(), raw) + _, _, _, err := oi.issueSessionFromIDToken(context.Background(), raw, "") require.Error(t, err, "token with mismatched audience must be rejected") assert.Contains(t, err.Error(), "verify") assert.Equal(t, 0, countOIDCSessions(t, oi, "attacker@example.com")) @@ -67,7 +67,7 @@ func TestIssueSessionFromIDToken_Expired(t *testing.T) { oi := newAuthenticatorForIDP(t, idp, db) raw := idp.signIDToken(t) - _, _, _, err := oi.issueSessionFromIDToken(context.Background(), raw) + _, _, _, err := oi.issueSessionFromIDToken(context.Background(), raw, "") require.Error(t, err, "expired token must be rejected") assert.Equal(t, 0, countOIDCSessions(t, oi, "expired-user@example.com")) } @@ -84,7 +84,7 @@ func TestIssueSessionFromIDToken_NoMatchingGroup(t *testing.T) { oi := newAuthenticatorForIDP(t, idp, db) raw := idp.signIDToken(t) - _, _, _, err := oi.issueSessionFromIDToken(context.Background(), raw) + _, _, _, err := oi.issueSessionFromIDToken(context.Background(), raw, "") require.ErrorIs(t, err, errNoMatchingRole) assert.Equal(t, 0, countOIDCSessions(t, oi, "nogroup-user@example.com")) } @@ -112,7 +112,7 @@ func TestIssueSessionFromIDToken_RoleMapping(t *testing.T) { idp.groups = []string{tc.group} oi := newAuthenticatorForIDP(t, idp, db) - _, _, _, err := oi.issueSessionFromIDToken(context.Background(), idp.signIDToken(t)) + _, _, _, err := oi.issueSessionFromIDToken(context.Background(), idp.signIDToken(t), "") require.NoError(t, err) var role string @@ -151,6 +151,54 @@ func TestDeviceFlow_EndToEnd(t *testing.T) { assert.Equal(t, 1, countOIDCSessions(t, oi, "device-user@example.com")) } +// TestIssueSessionFromIDToken_EmptyEmail rejects blank or missing email claims. +func TestIssueSessionFromIDToken_EmptyEmail(t *testing.T) { + t.Parallel() + db := pgtest.NewSqlxDB(t) + idp := newMockIDP(t, testClientID) + idp.email = " " + idp.groups = []string{AdminClaim} + oi := newAuthenticatorForIDP(t, idp, db) + + _, _, _, err := oi.issueSessionFromIDToken(context.Background(), idp.signIDToken(t), "") + require.Error(t, err) + assert.Contains(t, err.Error(), "email") + assert.Equal(t, 0, countOIDCSessions(t, oi, "")) +} + +// TestIssueSessionFromIDToken_NonceMismatch rejects a browser-path token whose +// nonce does not match the value stored at sign-in. +func TestIssueSessionFromIDToken_NonceMismatch(t *testing.T) { + t.Parallel() + db := pgtest.NewSqlxDB(t) + idp := newMockIDP(t, testClientID) + idp.email = "nonce-user@example.com" + idp.groups = []string{AdminClaim} + idp.nonce = "token-nonce" + oi := newAuthenticatorForIDP(t, idp, db) + + _, _, _, err := oi.issueSessionFromIDToken(context.Background(), idp.signIDToken(t), "expected-nonce") + require.Error(t, err) + assert.Contains(t, err.Error(), "nonce") + assert.Equal(t, 0, countOIDCSessions(t, oi, "nonce-user@example.com")) +} + +// TestIssueSessionFromIDToken_NonceMatch accepts a matching nonce. +func TestIssueSessionFromIDToken_NonceMatch(t *testing.T) { + t.Parallel() + db := pgtest.NewSqlxDB(t) + idp := newMockIDP(t, testClientID) + idp.email = "nonce-ok@example.com" + idp.groups = []string{AdminClaim} + idp.nonce = "good-nonce" + oi := newAuthenticatorForIDP(t, idp, db) + + sessionID, email, _, err := oi.issueSessionFromIDToken(context.Background(), idp.signIDToken(t), "good-nonce") + require.NoError(t, err) + assert.NotEmpty(t, sessionID) + assert.Equal(t, "nonce-ok@example.com", email) +} + // TestDeviceFlow_WrongAudienceRejected asserts the device path uses the same // verifier: a token for the wrong client fails the flow and creates no session. func TestDeviceFlow_WrongAudienceRejected(t *testing.T) { From 6f5300cac52f016b428e2d9a311a87f80da42cb9 Mon Sep 17 00:00:00 2001 From: Harry Anderson Date: Sat, 11 Jul 2026 09:04:30 +0000 Subject: [PATCH 08/18] fix(oidc): fix device-flow e2e test and govet shadow Register handles in the store before calling pollDeviceToken so the orphan-session guard does not abandon intentional e2e tests. Rename the add() error binding to avoid shadowing err (govet). --- core/sessions/oidcauth/device_flow.go | 6 +++--- core/sessions/oidcauth/verify_flow_test.go | 12 +++++++++--- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/core/sessions/oidcauth/device_flow.go b/core/sessions/oidcauth/device_flow.go index e82618bb1ed..0e63d7e24ba 100644 --- a/core/sessions/oidcauth/device_flow.go +++ b/core/sessions/oidcauth/device_flow.go @@ -236,9 +236,9 @@ func (oi *oidcAuthenticator) handleDeviceStart(c *gin.Context) { expiresAt: time.Now().Add(5 * time.Minute), // provisional; refined after IdP response clientIP: c.ClientIP(), } - if err := oi.deviceFlows.add(handle, state); err != nil { - oi.lggr.Warnf("refusing new device flow: %v", err) - c.JSON(http.StatusTooManyRequests, gin.H{"error": err.Error()}) + if addErr := oi.deviceFlows.add(handle, state); addErr != nil { + oi.lggr.Warnf("refusing new device flow: %v", addErr) + c.JSON(http.StatusTooManyRequests, gin.H{"error": addErr.Error()}) return } diff --git a/core/sessions/oidcauth/verify_flow_test.go b/core/sessions/oidcauth/verify_flow_test.go index 603b18f02eb..0d573b99e0d 100644 --- a/core/sessions/oidcauth/verify_flow_test.go +++ b/core/sessions/oidcauth/verify_flow_test.go @@ -135,12 +135,16 @@ func TestDeviceFlow_EndToEnd(t *testing.T) { oi := newAuthenticatorForIDP(t, idp, db) // Kick off a device authorization at the provider, then run the same - // blocking poll the node uses in production. + // blocking poll the node uses in production. Register the handle in the + // store first — pollDeviceToken refuses to mint a session if the handle + // was swept/expired (orphan-session guard). da, err := oi.oauth2Config.DeviceAuth(context.Background()) require.NoError(t, err) + const handle = "e2e-handle" state := &deviceFlowState{expiresAt: time.Now().Add(time.Minute)} - oi.pollDeviceToken("e2e-handle", state, da) + require.NoError(t, oi.deviceFlows.add(handle, state)) + oi.pollDeviceToken(handle, state, da) state.mu.Lock() defer state.mu.Unlock() @@ -212,8 +216,10 @@ func TestDeviceFlow_WrongAudienceRejected(t *testing.T) { da, err := oi.oauth2Config.DeviceAuth(context.Background()) require.NoError(t, err) + const handle = "e2e-handle-2" state := &deviceFlowState{expiresAt: time.Now().Add(time.Minute)} - oi.pollDeviceToken("e2e-handle-2", state, da) + require.NoError(t, oi.deviceFlows.add(handle, state)) + oi.pollDeviceToken(handle, state, da) state.mu.Lock() defer state.mu.Unlock() From d6b46b45666e94268904ad36fcca087a879996bd Mon Sep 17 00:00:00 2001 From: Harry Anderson Date: Sat, 11 Jul 2026 09:21:20 +0000 Subject: [PATCH 09/18] fix(oidc): tidy limiter dep into dependent go.mod files Device-flow rate limiting pulls in github.com/ulule/limiter/v3. Submodules that replace the root module need it as an indirect require so go generate does not fail with "updates to go.mod needed". --- deployment/go.mod | 1 + integration-tests/go.mod | 1 + integration-tests/load/go.mod | 1 + system-tests/lib/go.mod | 1 + system-tests/tests/go.mod | 1 + 5 files changed, 5 insertions(+) diff --git a/deployment/go.mod b/deployment/go.mod index aad81685f37..cb6e7268cb7 100644 --- a/deployment/go.mod +++ b/deployment/go.mod @@ -482,6 +482,7 @@ require ( github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/tyler-smith/go-bip39 v1.1.0 // indirect github.com/ugorji/go/codec v1.3.2 // indirect + github.com/ulule/limiter/v3 v3.11.2 // indirect github.com/urfave/cli v1.22.16 // indirect github.com/urfave/cli/v2 v2.27.7 // indirect github.com/valyala/fastjson v1.6.10 // indirect diff --git a/integration-tests/go.mod b/integration-tests/go.mod index 9a70720706c..f26668dc1c5 100644 --- a/integration-tests/go.mod +++ b/integration-tests/go.mod @@ -469,6 +469,7 @@ require ( github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/tyler-smith/go-bip39 v1.1.0 // indirect github.com/ugorji/go/codec v1.3.2 // indirect + github.com/ulule/limiter/v3 v3.11.2 // indirect github.com/urfave/cli/v2 v2.27.7 // indirect github.com/valyala/fastjson v1.6.10 // indirect github.com/vektah/gqlparser/v2 v2.5.19 // indirect diff --git a/integration-tests/load/go.mod b/integration-tests/load/go.mod index fc6d035f840..0e33a6e41c3 100644 --- a/integration-tests/load/go.mod +++ b/integration-tests/load/go.mod @@ -556,6 +556,7 @@ require ( github.com/uber/jaeger-client-go v2.30.0+incompatible // indirect github.com/uber/jaeger-lib v2.4.1+incompatible // indirect github.com/ugorji/go/codec v1.3.2 // indirect + github.com/ulule/limiter/v3 v3.11.2 // indirect github.com/urfave/cli/v2 v2.27.7 // indirect github.com/valyala/fastjson v1.6.10 // indirect github.com/vektah/gqlparser/v2 v2.5.19 // indirect diff --git a/system-tests/lib/go.mod b/system-tests/lib/go.mod index 4c6466ddef2..d863f1df618 100644 --- a/system-tests/lib/go.mod +++ b/system-tests/lib/go.mod @@ -551,6 +551,7 @@ require ( github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/tyler-smith/go-bip39 v1.1.0 // indirect github.com/ugorji/go/codec v1.3.2 // indirect + github.com/ulule/limiter/v3 v3.11.2 // indirect github.com/urfave/cli/v2 v2.27.7 // indirect github.com/valyala/fastjson v1.6.10 // indirect github.com/vektah/gqlparser/v2 v2.5.32 // indirect diff --git a/system-tests/tests/go.mod b/system-tests/tests/go.mod index 391187922bb..dea63c14951 100644 --- a/system-tests/tests/go.mod +++ b/system-tests/tests/go.mod @@ -698,6 +698,7 @@ require ( github.com/uber/jaeger-client-go v2.30.0+incompatible // indirect github.com/uber/jaeger-lib v2.4.1+incompatible // indirect github.com/ugorji/go/codec v1.3.2 // indirect + github.com/ulule/limiter/v3 v3.11.2 // indirect github.com/urfave/cli/v2 v2.27.7 // indirect github.com/valyala/fastjson v1.6.10 // indirect github.com/vektah/gqlparser/v2 v2.5.32 // indirect From e55b6f1073547bedaa612dd682cd6fa96b7b456c Mon Sep 17 00:00:00 2001 From: Harry Anderson Date: Tue, 6 Oct 2026 02:57:02 +0000 Subject: [PATCH 10/18] fix(oidc): adapt rebased device flow to current logger and HTTP client Develop renamed newHttpClient to newHTTPClient, and the authenticator logger field is the common sugared logger. The CLI client and tests follow that. --- core/cmd/oidc_device_auth.go | 6 +++--- core/sessions/oidcauth/device_flow_test.go | 6 +++--- core/sessions/oidcauth/mock_idp_test.go | 4 ++-- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/core/cmd/oidc_device_auth.go b/core/cmd/oidc_device_auth.go index ea1547d6df4..96b20557611 100644 --- a/core/cmd/oidc_device_auth.go +++ b/core/cmd/oidc_device_auth.go @@ -67,7 +67,7 @@ func NewOIDCDeviceCookieAuthenticator(config ClientOpts, store CookieStore, out // body must be JSON with enabled=true so a reverse-proxy 200 HTML page cannot // accidentally trigger the device-flow path. func NodeHasOIDCEnabled(ctx context.Context, config ClientOpts, lggr logger.Logger) bool { - client := newHttpClient(lggr, config.InsecureSkipVerify) + client := newHTTPClient(lggr, config.InsecureSkipVerify) u := config.RemoteNodeURL.String() + "/oidc-enabled" req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil) if err != nil { @@ -142,7 +142,7 @@ func (o *OIDCDeviceCookieAuthenticator) start(ctx context.Context) (*oidcDeviceS if err != nil { return nil, err } - client := newHttpClient(o.lggr, o.config.InsecureSkipVerify) + client := newHTTPClient(o.lggr, o.config.InsecureSkipVerify) resp, err := client.Do(req) if err != nil { return nil, err @@ -172,7 +172,7 @@ func (o *OIDCDeviceCookieAuthenticator) poll(ctx context.Context, handle string) return nil, "", err } req.Header.Set("Content-Type", "application/json") - client := newHttpClient(o.lggr, o.config.InsecureSkipVerify) + client := newHTTPClient(o.lggr, o.config.InsecureSkipVerify) resp, err := client.Do(req) if err != nil { return nil, "", err diff --git a/core/sessions/oidcauth/device_flow_test.go b/core/sessions/oidcauth/device_flow_test.go index 3f4400dd02a..977d14ba4b9 100644 --- a/core/sessions/oidcauth/device_flow_test.go +++ b/core/sessions/oidcauth/device_flow_test.go @@ -10,7 +10,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/smartcontractkit/chainlink/v2/core/logger" + "github.com/smartcontractkit/chainlink-common/pkg/logger" clsessions "github.com/smartcontractkit/chainlink/v2/core/sessions" ) @@ -177,7 +177,7 @@ func TestGenerateDeviceHandle_UniqueAndURLSafe(t *testing.T) { func TestFinishDeviceFlow_RecordsTerminalState(t *testing.T) { t.Parallel() - oi := &oidcAuthenticator{lggr: logger.TestLogger(t)} + oi := &oidcAuthenticator{lggr: logger.TestSugared(t)} okState := &deviceFlowState{expiresAt: time.Now().Add(time.Minute)} oi.finishDeviceFlow(okState, "sess-1", "user@example.com", clsessions.UserRoleEdit, nil) @@ -202,7 +202,7 @@ func TestFinishDeviceFlow_RecordsTerminalState(t *testing.T) { // separates the background poll goroutine from the CLI poll handler. func TestDeviceFlowState_ConcurrentAccess(t *testing.T) { t.Parallel() - oi := &oidcAuthenticator{lggr: logger.TestLogger(t)} + oi := &oidcAuthenticator{lggr: logger.TestSugared(t)} state := &deviceFlowState{expiresAt: time.Now().Add(time.Minute)} var wg sync.WaitGroup diff --git a/core/sessions/oidcauth/mock_idp_test.go b/core/sessions/oidcauth/mock_idp_test.go index 1e075edc48e..78f33511a1d 100644 --- a/core/sessions/oidcauth/mock_idp_test.go +++ b/core/sessions/oidcauth/mock_idp_test.go @@ -16,8 +16,8 @@ import ( "github.com/stretchr/testify/require" "golang.org/x/oauth2" + "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink-common/pkg/sqlutil" - "github.com/smartcontractkit/chainlink/v2/core/logger" "github.com/smartcontractkit/chainlink/v2/core/logger/audit" ) @@ -155,7 +155,7 @@ func newAuthenticatorForIDP(t *testing.T, idp *mockIDP, ds sqlutil.DataSource) * provider: provider, oidcConfig: &gooidc.Config{ClientID: idp.clientID}, oauth2Config: &oauth2.Config{ClientID: idp.clientID, Endpoint: provider.Endpoint()}, - lggr: logger.TestLogger(t), + lggr: logger.TestSugared(t), auditLogger: &audit.AuditLoggerService{}, deviceFlows: newDeviceFlowStore(), pendingAuth: newPendingAuthStore(), From 2f7c73d9b3e6d0b78aabfe6cceadfd5b193d1368 Mon Sep 17 00:00:00 2001 From: Harry Anderson Date: Tue, 6 Oct 2026 03:30:22 +0000 Subject: [PATCH 11/18] fix(oidc): share login state and tighten device-flow checks Store browser login state and device-flow results in Postgres so any replica can finish a login. The provider device code stays on the replica that started the flow. Cap device-flow lifetime at five minutes, reject a verification URI whose host does not match the provider, and refuse CLI device login when TLS verification is disabled. When the socket peer is a private proxy, device-flow limits use the rightmost X-Forwarded-For address. Reject group claims outside the configured role groups, and disable OIDC API tokens. --- .changeset/oidc-cli-device-flow.md | 2 +- core/cmd/oidc_device_auth.go | 6 +- core/cmd/oidc_device_auth_test.go | 12 +- core/logger/audit/audit_types.go | 1 + core/sessions/oidcauth/device_flow.go | 128 ++++++++++++---- core/sessions/oidcauth/device_flow_test.go | 6 +- core/sessions/oidcauth/helpers_test.go | 1 - core/sessions/oidcauth/login_guards.go | 136 +++++++++++++++++ core/sessions/oidcauth/login_guards_test.go | 91 +++++++++++ core/sessions/oidcauth/login_state_store.go | 143 ++++++++++++++++++ .../oidcauth/login_state_store_test.go | 87 +++++++++++ core/sessions/oidcauth/mock_idp_test.go | 1 - core/sessions/oidcauth/oidc.go | 133 +++++----------- core/sessions/oidcauth/oidc_test.go | 36 ++--- core/sessions/oidcauth/pending_auth.go | 12 +- core/sessions/oidcauth/reaper.go | 8 +- core/sessions/oidcauth/verify_flow_test.go | 22 ++- .../migrations/0309_oidc_login_state.sql | 27 ++++ 18 files changed, 682 insertions(+), 170 deletions(-) create mode 100644 core/sessions/oidcauth/login_guards.go create mode 100644 core/sessions/oidcauth/login_guards_test.go create mode 100644 core/sessions/oidcauth/login_state_store.go create mode 100644 core/sessions/oidcauth/login_state_store_test.go create mode 100644 core/store/migrate/migrations/0309_oidc_login_state.sql diff --git a/.changeset/oidc-cli-device-flow.md b/.changeset/oidc-cli-device-flow.md index b6eb88c6738..9b7e6728e7f 100644 --- a/.changeset/oidc-cli-device-flow.md +++ b/.changeset/oidc-cli-device-flow.md @@ -6,4 +6,4 @@ #changed The OIDC authorization-code (operator UI) flow now always uses PKCE (RFC 7636). The OIDC `ClientSecret` is now optional: confidential clients still send it, while public clients (required for the device flow) rely on PKCE instead. Existing confidential-client deployments are unaffected. -#changed Hardened OIDC device and auth-code flows: dedicated pre-auth rate limits and per-IP concurrency caps on device endpoints, server-side PKCE verifier and OIDC nonce (not stored in the session cookie), email claim validation, orphan-session cleanup if cookie bind fails, and a stricter CLI `/oidc-enabled` probe. +#changed Hardened OIDC device and auth-code flows: dedicated pre-auth rate limits and per-IP concurrency caps on device endpoints, server-side PKCE verifier and OIDC nonce (the session cookie holds only the anti-CSRF state), email claim validation, orphan-session cleanup if cookie bind fails, and a stricter CLI `/oidc-enabled` probe. Browser login state and device-flow results are stored in Postgres so any replica can finish a login. The provider device code stays on the replica that started the flow and is not written to the database. Device-flow lifetime is capped at five minutes. A verification URI whose host does not match the configured provider is rejected. When the socket peer is a private proxy, device-flow rate limits use the rightmost X-Forwarded-For address; a public peer is used as-is. Denied device flows are audited. A groups claim that contains any value other than the configured role groups is rejected. OIDC API tokens cannot be created or used. The CLI refuses device login when TLS verification is disabled. diff --git a/core/cmd/oidc_device_auth.go b/core/cmd/oidc_device_auth.go index 96b20557611..95e4412b093 100644 --- a/core/cmd/oidc_device_auth.go +++ b/core/cmd/oidc_device_auth.go @@ -93,6 +93,9 @@ func NodeHasOIDCEnabled(ctx context.Context, config ClientOpts, lggr logger.Logg // Login runs the full device flow: start, prompt the operator, poll until the // node reports completion, then save the returned session cookie. func (o *OIDCDeviceCookieAuthenticator) Login(ctx context.Context) error { + if o.config.InsecureSkipVerify { + return errors.New("device login requires TLS verification; do not set insecure-skip-verify") + } start, err := o.start(ctx) if err != nil { return err @@ -201,7 +204,8 @@ func (o *OIDCDeviceCookieAuthenticator) promptUser(start *oidcDeviceStartRespons if uri == "" { uri = start.VerificationURI } - fmt.Fprintln(o.out, "To log in, open the following URL in a browser and sign in with your identity provider:") + fmt.Fprintln(o.out, "To log in, open the following URL in a browser and sign in with your identity provider.") + fmt.Fprintln(o.out, "Confirm the host is your identity provider before you approve. An approval you did not start is an attack.") fmt.Fprintf(o.out, "\n %s\n\n", uri) if start.VerificationURIComplete == "" { fmt.Fprintf(o.out, "When prompted, enter the code: %s\n\n", start.UserCode) diff --git a/core/cmd/oidc_device_auth_test.go b/core/cmd/oidc_device_auth_test.go index 3fd7cadedda..9ea7299fd3c 100644 --- a/core/cmd/oidc_device_auth_test.go +++ b/core/cmd/oidc_device_auth_test.go @@ -122,9 +122,19 @@ func TestOIDCDeviceLogin_Success(t *testing.T) { assert.Equal(t, "clsession", cookie.Name) assert.Equal(t, "abc123", cookie.Value) - // The operator must be shown the verification URI and code. + // The operator must be shown the verification URI, the code, and a warning + // to confirm the host before approving. assert.Contains(t, out.String(), "https://sso.example.com/activate") assert.Contains(t, out.String(), "WDJB-MJHT") + assert.Contains(t, out.String(), "An approval you did not start is an attack.") +} + +func TestOIDCDeviceLogin_RefusesInsecureSkipVerify(t *testing.T) { + t.Parallel() + opts := cmd.ClientOpts{InsecureSkipVerify: true} + auth := cmd.NewOIDCDeviceCookieAuthenticator(opts, &cmd.MemoryCookieStore{}, &bytes.Buffer{}, logger.TestLogger(t)) + err := auth.Login(context.Background()) + require.EqualError(t, err, "device login requires TLS verification; do not set insecure-skip-verify") } func TestOIDCDeviceLogin_Denied(t *testing.T) { diff --git a/core/logger/audit/audit_types.go b/core/logger/audit/audit_types.go index 0f5b2f1523a..80e9ef985fb 100644 --- a/core/logger/audit/audit_types.go +++ b/core/logger/audit/audit_types.go @@ -7,6 +7,7 @@ const ( AuthLoginFailedEmail EventID = "AUTH_LOGIN_FAILED_EMAIL" AuthLoginFailedPassword EventID = "AUTH_LOGIN_FAILED_PASSWORD" AuthLoginFailed2FA EventID = "AUTH_LOGIN_FAILED_2FA" + AuthLoginFailedDevice EventID = "AUTH_LOGIN_FAILED_DEVICE" AuthLoginSuccessWith2FA EventID = "AUTH_LOGIN_SUCCESS_WITH_2FA" AuthLoginSuccessNo2FA EventID = "AUTH_LOGIN_SUCCESS_NO_2FA" Auth2FAEnrolled EventID = "AUTH_2FA_ENROLLED" diff --git a/core/sessions/oidcauth/device_flow.go b/core/sessions/oidcauth/device_flow.go index 0e63d7e24ba..ac0ad26d464 100644 --- a/core/sessions/oidcauth/device_flow.go +++ b/core/sessions/oidcauth/device_flow.go @@ -17,6 +17,7 @@ import ( "github.com/ulule/limiter/v3/drivers/store/memory" "golang.org/x/oauth2" + "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink/v2/core/logger/audit" clsessions "github.com/smartcontractkit/chainlink/v2/core/sessions" webauth "github.com/smartcontractkit/chainlink/v2/core/web/auth" @@ -36,11 +37,10 @@ import ( // node's poll to the provider: no matter how fast the CLI asks, the node never // exceeds the provider's cadence. // -// Multi-replica note: deviceFlowStore is process-local memory. Deployments with -// more than one replica behind a load balancer MUST use session affinity -// (sticky sessions) for /oidc-device/* (and preferably the whole node API), or -// replace this store with a shared short-TTL backend. Without affinity, start -// and poll can land on different replicas and the login fails closed. +// Multi-replica: the opaque handle and its terminal result live in +// oidc_device_flows, so start and poll may land on different replicas. The +// provider device code stays in the poller process and is not written to the +// database. The in-memory map below is only the poller's local copy. const ( // maxConcurrentDeviceFlows bounds the in-memory store so unauthenticated @@ -208,15 +208,23 @@ type DevicePollResponse struct { Message string `json:"message,omitempty"` } -// deviceEndpointRateLimit builds a dedicated per-IP limiter for pre-auth device -// routes. Nested under the outer api group so both limits apply. -func deviceEndpointRateLimit(period time.Duration, limit int64) gin.HandlerFunc { +// deviceEndpointRateLimit builds a dedicated limiter for pre-auth device +// routes. The key is the operator address from deviceClientIP, not the socket +// peer, so a load balancer does not collapse every caller into one bucket. +// Nested under the outer api group so both limits apply. +func deviceEndpointRateLimit(period time.Duration, limit int64, lggr logger.Logger) gin.HandlerFunc { store := memory.NewStore() rate := limiter.Rate{ Period: period, Limit: limit, } - return mgin.NewMiddleware(limiter.New(store, rate)) + return mgin.NewMiddleware(limiter.New(store, rate), + mgin.WithKeyGetter(deviceClientIP), + mgin.WithLimitReachedHandler(func(c *gin.Context) { + lggr.Warnf("device endpoint rate limit reached path=%s client=%s", c.FullPath(), deviceClientIP(c)) + c.String(http.StatusTooManyRequests, "Limit exceeded") + }), + ) } // handleDeviceStart begins a device authorization flow. Unauthenticated, like @@ -232,12 +240,24 @@ func (oi *oidcAuthenticator) handleDeviceStart(c *gin.Context) { // Reserve a concurrency slot *before* calling the IdP so a refused flow // never produces outbound provider load, and so a flood cannot open more // IdP device codes than the store will accept. + clientIP := deviceClientIP(c) + provisional := time.Now().Add(maxDeviceFlowLifetime) state := &deviceFlowState{ - expiresAt: time.Now().Add(5 * time.Minute), // provisional; refined after IdP response - clientIP: c.ClientIP(), + expiresAt: provisional, + clientIP: clientIP, + } + if addErr := reserveDeviceFlow(c.Request.Context(), oi.ds, handle, clientIP, provisional); addErr != nil { + oi.lggr.Warnf("refusing new device flow client=%s: %v", clientIP, addErr) + if errors.Is(addErr, errTooManyDeviceFlows) || errors.Is(addErr, errTooManyDeviceFlowsPerIP) { + c.JSON(http.StatusTooManyRequests, gin.H{"error": addErr.Error()}) + return + } + c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to start device authorization"}) + return } if addErr := oi.deviceFlows.add(handle, state); addErr != nil { - oi.lggr.Warnf("refusing new device flow: %v", addErr) + _ = removeDeviceFlow(c.Request.Context(), oi.ds, handle) + oi.lggr.Warnf("refusing new device flow client=%s: %v", clientIP, addErr) c.JSON(http.StatusTooManyRequests, gin.H{"error": addErr.Error()}) return } @@ -245,22 +265,35 @@ func (oi *oidcAuthenticator) handleDeviceStart(c *gin.Context) { ctx := context.Background() da, err := oi.oauth2Config.DeviceAuth(ctx) if err != nil { + _ = removeDeviceFlow(c.Request.Context(), oi.ds, handle) oi.deviceFlows.remove(handle) oi.lggr.Errorf("device authorization request failed: %v", err) c.JSON(http.StatusBadGateway, gin.H{"error": "Failed to start device authorization"}) return } - expiry := da.Expiry - if expiry.IsZero() { - // Per RFC 8628 the provider should send expires_in; fall back to a - // conservative default so a malformed response cannot create an - // unbounded flow. - expiry = time.Now().Add(5 * time.Minute) + expiry := capDeviceExpiry(da.Expiry, time.Now()) + if !expiry.After(time.Now()) { + _ = removeDeviceFlow(c.Request.Context(), oi.ds, handle) + oi.deviceFlows.remove(handle) + oi.lggr.Errorf("device authorization expiry is already past") + c.JSON(http.StatusBadGateway, gin.H{"error": "Failed to start device authorization"}) + return + } + if !verificationURIAllowed(oi.config.ProviderURL(), da.VerificationURI) || + (da.VerificationURIComplete != "" && !verificationURIAllowed(oi.config.ProviderURL(), da.VerificationURIComplete)) { + _ = removeDeviceFlow(c.Request.Context(), oi.ds, handle) + oi.deviceFlows.remove(handle) + oi.lggr.Errorf("device authorization verification URI host does not match the configured provider") + c.JSON(http.StatusBadGateway, gin.H{"error": "Failed to start device authorization"}) + return } state.mu.Lock() state.expiresAt = expiry state.mu.Unlock() + if _, err := oi.ds.ExecContext(c.Request.Context(), `UPDATE oidc_device_flows SET expires_at = $2 WHERE handle = $1`, handle, expiry); err != nil { + oi.lggr.Errorf("failed to record device flow expiry: %v", err) + } // Poll the provider in the background. DeviceAccessToken blocks until the // user approves, denies, or the code expires, internally respecting the @@ -290,44 +323,60 @@ func (oi *oidcAuthenticator) pollDeviceToken(handle string, state *deviceFlowSta token, err := oi.oauth2Config.DeviceAccessToken(ctx, da) if err != nil { - oi.finishDeviceFlow(state, "", "", "", err) + oi.finishDeviceFlow(state, handle, "", "", "", err) return } rawIDToken, ok := token.Extra("id_token").(string) if !ok { - oi.finishDeviceFlow(state, "", "", "", errors.New("missing id_token in device token response")) + oi.finishDeviceFlow(state, handle, "", "", "", errors.New("missing id_token in device token response")) return } // If the handle was swept/expired while we waited on the IdP, do not mint a // session nobody can claim (orphan oidc_sessions row). - if !oi.deviceFlows.contains(handle) { + if !oi.deviceHandleLive(ctx, handle) { oi.lggr.Warnf("device flow handle gone before token completion; abandoning without session") - oi.finishDeviceFlow(state, "", "", "", errDeviceFlowAbandoned) + oi.finishDeviceFlow(state, handle, "", "", "", errDeviceFlowAbandoned) return } // Device flow does not use a browser nonce; pass empty expectedNonce. sessionID, email, role, err := oi.issueSessionFromIDToken(ctx, rawIDToken, "") if err != nil { - oi.finishDeviceFlow(state, "", "", "", err) + oi.finishDeviceFlow(state, handle, "", "", "", err) return } - // Race: handle may have been swept between contains and issue. Drop the + // Race: handle may have been swept between the live check and issue. Drop the // orphan session rather than leave a live unclaimable row. - if !oi.deviceFlows.contains(handle) { + if !oi.deviceHandleLive(ctx, handle) { oi.lggr.Warnf("device flow handle gone after session insert; deleting orphan session") oi.deleteOIDCSession(ctx, sessionID) - oi.finishDeviceFlow(state, "", "", "", errDeviceFlowAbandoned) + oi.finishDeviceFlow(state, handle, "", "", "", errDeviceFlowAbandoned) return } - oi.finishDeviceFlow(state, sessionID, email, role, nil) + oi.finishDeviceFlow(state, handle, sessionID, email, role, nil) } -func (oi *oidcAuthenticator) finishDeviceFlow(state *deviceFlowState, sessionID, email string, role clsessions.UserRole, err error) { +func (oi *oidcAuthenticator) deviceHandleLive(ctx context.Context, handle string) bool { + if oi.ds != nil { + live, err := deviceFlowLive(ctx, oi.ds, handle) + if err != nil { + oi.lggr.Errorf("device flow live check failed: %v", err) + return false + } + return live + } + return oi.deviceFlows.contains(handle) +} + +func (oi *oidcAuthenticator) finishDeviceFlow(state *deviceFlowState, handle, sessionID, email string, role clsessions.UserRole, err error) { + errText := "" + if err != nil { + errText = deviceFailureReason(err) + } state.mu.Lock() state.done = true state.sessionID = sessionID @@ -337,6 +386,17 @@ func (oi *oidcAuthenticator) finishDeviceFlow(state *deviceFlowState, sessionID, state.mu.Unlock() if err != nil { oi.lggr.Errorf("device authorization flow failed: %v", err) + if oi.auditLogger != nil { + oi.auditLogger.Audit(audit.AuthLoginFailedDevice, map[string]any{ + "method": "device_flow", + "reason": errText, + }) + } + } + if oi.ds != nil && handle != "" { + if werr := recordDeviceFlowResult(context.Background(), oi.ds, handle, sessionID, email, string(role), errText); werr != nil { + oi.lggr.Errorf("failed to record device flow result: %v", werr) + } } } @@ -361,9 +421,15 @@ func (oi *oidcAuthenticator) handleDevicePoll(c *gin.Context) { return } - // Read the terminal result and consume the handle in one critical section - // so two concurrent polls cannot both be handed the session cookie. - sessionID, email, role, terminal, known, flowErr := oi.deviceFlows.consumeIfDone(req.DeviceHandle) + // Read the terminal result and consume the handle in one statement so two + // polls, including polls on different replicas, cannot both be handed the + // session cookie. + sessionID, email, role, terminal, known, flowErr, err := consumeDeviceFlow(c.Request.Context(), oi.ds, req.DeviceHandle) + if err != nil { + oi.lggr.Errorf("device flow poll failed: %v", err) + c.JSON(http.StatusInternalServerError, DevicePollResponse{Status: "denied", Message: "Failed to read device authorization"}) + return + } if !known { c.JSON(http.StatusNotFound, DevicePollResponse{Status: "denied", Message: errUnknownDeviceFlow.Error()}) return diff --git a/core/sessions/oidcauth/device_flow_test.go b/core/sessions/oidcauth/device_flow_test.go index 977d14ba4b9..c5ad622cdae 100644 --- a/core/sessions/oidcauth/device_flow_test.go +++ b/core/sessions/oidcauth/device_flow_test.go @@ -180,7 +180,7 @@ func TestFinishDeviceFlow_RecordsTerminalState(t *testing.T) { oi := &oidcAuthenticator{lggr: logger.TestSugared(t)} okState := &deviceFlowState{expiresAt: time.Now().Add(time.Minute)} - oi.finishDeviceFlow(okState, "sess-1", "user@example.com", clsessions.UserRoleEdit, nil) + oi.finishDeviceFlow(okState, "handle-ok", "sess-1", "user@example.com", clsessions.UserRoleEdit, nil) okState.mu.Lock() assert.True(t, okState.done) assert.Equal(t, "sess-1", okState.sessionID) @@ -190,7 +190,7 @@ func TestFinishDeviceFlow_RecordsTerminalState(t *testing.T) { errState := &deviceFlowState{expiresAt: time.Now().Add(time.Minute)} wantErr := errors.New("denied") - oi.finishDeviceFlow(errState, "", "", "", wantErr) + oi.finishDeviceFlow(errState, "handle-err", "", "", "", wantErr) errState.mu.Lock() assert.True(t, errState.done) assert.Empty(t, errState.sessionID) @@ -209,7 +209,7 @@ func TestDeviceFlowState_ConcurrentAccess(t *testing.T) { wg.Add(2) go func() { defer wg.Done() - oi.finishDeviceFlow(state, "s", "e", clsessions.UserRoleView, nil) + oi.finishDeviceFlow(state, "handle-conc", "s", "e", clsessions.UserRoleView, nil) }() go func() { defer wg.Done() diff --git a/core/sessions/oidcauth/helpers_test.go b/core/sessions/oidcauth/helpers_test.go index 9db09d254c8..f5761aaa284 100644 --- a/core/sessions/oidcauth/helpers_test.go +++ b/core/sessions/oidcauth/helpers_test.go @@ -54,7 +54,6 @@ func NewTestOIDCAuthenticator( lggr: logger.Sugared(lggr).Named("OIDCAuthenticationProvider"), auditLogger: auditLogger, deviceFlows: newDeviceFlowStore(), - pendingAuth: newPendingAuthStore(), } return &oidcAuth, nil diff --git a/core/sessions/oidcauth/login_guards.go b/core/sessions/oidcauth/login_guards.go new file mode 100644 index 00000000000..41ed8360dbd --- /dev/null +++ b/core/sessions/oidcauth/login_guards.go @@ -0,0 +1,136 @@ +package oidcauth + +import ( + "net" + "net/url" + "strings" + "time" + + "github.com/gin-gonic/gin" +) + +const maxDeviceFlowLifetime = 5 * time.Minute + +// capDeviceExpiry bounds a provider expiry. A missing expiry, or one longer +// than maxDeviceFlowLifetime, is shortened. An already-past expiry is left +// past so the caller can fail the flow instead of extending it. +func capDeviceExpiry(expiry, now time.Time) time.Time { + if !expiry.IsZero() && !expiry.After(now) { + return expiry + } + cap := now.Add(maxDeviceFlowLifetime) + if expiry.IsZero() || expiry.After(cap) { + return cap + } + return expiry +} + +// verificationURIAllowed reports whether uri is safe to hand to an operator. +// The host must be the configured provider host, and the scheme must be https +// unless the host is loopback (local providers). +func verificationURIAllowed(providerURL, uri string) bool { + if uri == "" { + return false + } + provider, err := url.Parse(providerURL) + if err != nil || provider.Hostname() == "" { + return false + } + parsed, err := url.Parse(uri) + if err != nil || parsed.Hostname() == "" { + return false + } + if !strings.EqualFold(parsed.Hostname(), provider.Hostname()) { + return false + } + if parsed.Scheme == "https" { + return true + } + if parsed.Scheme != "http" { + return false + } + ip := net.ParseIP(parsed.Hostname()) + return (ip != nil && ip.IsLoopback()) || parsed.Hostname() == "localhost" +} + +// deviceClientIP is the address the device-flow caps use. Behind a private +// load balancer the socket peer is the balancer, so the rightmost +// X-Forwarded-For entry is the address that balancer observed. A public peer +// is used as-is. The header is ignored in that case, because the caller can +// set it. +func deviceClientIP(c *gin.Context) string { + peer := remotePeer(c) + parsed := net.ParseIP(peer) + if parsed == nil || !trustedProxyPeer(parsed) { + if peer != "" { + return peer + } + return c.ClientIP() + } + xff := c.GetHeader("X-Forwarded-For") + if xff == "" { + return peer + } + parts := strings.Split(xff, ",") + for i := len(parts) - 1; i >= 0; i-- { + ip := net.ParseIP(strings.TrimSpace(parts[i])) + if ip != nil { + return ip.String() + } + } + return peer +} + +func remotePeer(c *gin.Context) string { + if c.Request == nil { + return "" + } + host, _, err := net.SplitHostPort(c.Request.RemoteAddr) + if err != nil { + return c.Request.RemoteAddr + } + return host +} + +func trustedProxyPeer(ip net.IP) bool { + return ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() +} + +func deviceFailureReason(err error) string { + if err == nil { + return "" + } + if errorsIsDeadline(err) { + return "expired" + } + msg := strings.ToLower(err.Error()) + switch { + case strings.Contains(msg, "abandon"): + return "abandoned" + case strings.Contains(msg, "expired") || strings.Contains(msg, "timeout"): + return "expired" + case strings.Contains(msg, "denied") || strings.Contains(msg, "access_denied"): + return "denied" + default: + return "failed" + } +} + +func unexpectedGroup(claims []string, allowed ...string) string { + allow := make(map[string]struct{}, len(allowed)) + for _, name := range allowed { + if name != "" { + allow[name] = struct{}{} + } + } + for _, claim := range claims { + if _, ok := allow[claim]; !ok { + return claim + } + } + return "" +} + +func errorsIsDeadline(err error) bool { + return err != nil && (strings.Contains(err.Error(), "context deadline exceeded") || strings.Contains(err.Error(), "context canceled")) +} diff --git a/core/sessions/oidcauth/login_guards_test.go b/core/sessions/oidcauth/login_guards_test.go new file mode 100644 index 00000000000..1fedb5c328d --- /dev/null +++ b/core/sessions/oidcauth/login_guards_test.go @@ -0,0 +1,91 @@ +package oidcauth + +import ( + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestCapDeviceExpiry(t *testing.T) { + t.Parallel() + now := time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC) + + assert.Equal(t, now.Add(maxDeviceFlowLifetime), capDeviceExpiry(time.Time{}, now)) + assert.Equal(t, now.Add(maxDeviceFlowLifetime), capDeviceExpiry(now.Add(time.Hour), now)) + assert.Equal(t, now.Add(2*time.Minute), capDeviceExpiry(now.Add(2*time.Minute), now)) + past := now.Add(-time.Second) + assert.Equal(t, past, capDeviceExpiry(past, now)) +} + +func TestVerificationURIAllowed(t *testing.T) { + t.Parallel() + const provider = "https://id.example.com/oauth2/default" + + assert.True(t, verificationURIAllowed(provider, "https://id.example.com/activate")) + assert.True(t, verificationURIAllowed(provider, "https://ID.EXAMPLE.COM/activate?user_code=WDJB")) + assert.False(t, verificationURIAllowed(provider, "https://evil.example/activate")) + assert.False(t, verificationURIAllowed(provider, "http://id.example.com/activate")) + assert.False(t, verificationURIAllowed(provider, "")) + assert.False(t, verificationURIAllowed(provider, "not a url")) + + assert.True(t, verificationURIAllowed("http://127.0.0.1:8080", "http://127.0.0.1:8080/activate")) + assert.True(t, verificationURIAllowed("http://localhost:8080", "http://localhost:8080/activate")) + assert.False(t, verificationURIAllowed("http://10.0.0.1:8080", "http://10.0.0.1:8080/activate")) +} + +func TestDeviceClientIP(t *testing.T) { + t.Parallel() + + public := deviceRequest(t, "203.0.113.8:1234", "198.51.100.1, 203.0.113.9") + assert.Equal(t, "203.0.113.8", deviceClientIP(public)) + + loopback := deviceRequest(t, "127.0.0.1:1234", "198.51.100.1, 203.0.113.9") + assert.Equal(t, "203.0.113.9", deviceClientIP(loopback)) + + private := deviceRequest(t, "10.0.0.5:443", "203.0.113.4, not-an-ip") + assert.Equal(t, "203.0.113.4", deviceClientIP(private)) + + noHeader := deviceRequest(t, "10.0.0.5:443", "") + assert.Equal(t, "10.0.0.5", deviceClientIP(noHeader)) + + linkLocal := deviceRequest(t, "[fe80::1]:443", "203.0.113.7") + assert.Equal(t, "203.0.113.7", deviceClientIP(linkLocal)) +} + +func TestUnexpectedGroup(t *testing.T) { + t.Parallel() + allowed := []string{AdminClaim, EditorClaim, RunnerClaim, ReadClaim} + assert.Empty(t, unexpectedGroup([]string{AdminClaim, EditorClaim}, allowed...)) + assert.Equal(t, "Contractors", unexpectedGroup([]string{AdminClaim, "Contractors"}, allowed...)) + assert.Empty(t, unexpectedGroup(nil, allowed...)) + assert.Equal(t, "Contractors", unexpectedGroup([]string{"Contractors"}, allowed...)) +} + +func TestDeviceFailureReason(t *testing.T) { + t.Parallel() + require.Empty(t, deviceFailureReason(nil)) + assert.Equal(t, "failed", deviceFailureReason(assert.AnError)) + assert.Equal(t, "denied", deviceFailureReason(errString("access_denied"))) + assert.Equal(t, "abandoned", deviceFailureReason(errDeviceFlowAbandoned)) + assert.Equal(t, "expired", deviceFailureReason(errString("context deadline exceeded"))) +} + +type errString string + +func (e errString) Error() string { return string(e) } + +func deviceRequest(t *testing.T, remoteAddr, xff string) *gin.Context { + t.Helper() + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/oidc-device/start", nil) + c.Request.RemoteAddr = remoteAddr + if xff != "" { + c.Request.Header.Set("X-Forwarded-For", xff) + } + return c +} diff --git a/core/sessions/oidcauth/login_state_store.go b/core/sessions/oidcauth/login_state_store.go new file mode 100644 index 00000000000..523cb315953 --- /dev/null +++ b/core/sessions/oidcauth/login_state_store.go @@ -0,0 +1,143 @@ +package oidcauth + +import ( + "context" + "database/sql" + "errors" + "time" + + "github.com/smartcontractkit/chainlink-common/pkg/sqlutil" + clsessions "github.com/smartcontractkit/chainlink/v2/core/sessions" +) + +// oidcDeviceFlowLock serializes the concurrency-cap check and insert so two +// replicas cannot both pass the count and both insert. +const oidcDeviceFlowLock = 8628002 + +func putPendingAuth(ctx context.Context, ds sqlutil.DataSource, state, verifier, nonce string, expiresAt time.Time) error { + if _, err := ds.ExecContext(ctx, `DELETE FROM oidc_pending_auth WHERE expires_at <= now()`); err != nil { + return err + } + _, err := ds.ExecContext(ctx, ` + INSERT INTO oidc_pending_auth (state, verifier, nonce, expires_at) + VALUES ($1, $2, $3, $4) + ON CONFLICT (state) DO UPDATE + SET verifier = EXCLUDED.verifier, + nonce = EXCLUDED.nonce, + expires_at = EXCLUDED.expires_at`, + state, verifier, nonce, expiresAt) + return err +} + +func takePendingAuth(ctx context.Context, ds sqlutil.DataSource, state string) (verifier, nonce string, ok bool, err error) { + var row struct { + Verifier string + Nonce string + } + err = ds.GetContext(ctx, &row, ` + DELETE FROM oidc_pending_auth + WHERE state = $1 AND expires_at > now() + RETURNING verifier, nonce`, state) + if errors.Is(err, sql.ErrNoRows) { + return "", "", false, nil + } + if err != nil { + return "", "", false, err + } + return row.Verifier, row.Nonce, true, nil +} + +func reserveDeviceFlow(ctx context.Context, ds sqlutil.DataSource, handle, clientIP string, expiresAt time.Time) error { + return sqlutil.TransactDataSource(ctx, ds, nil, func(tx sqlutil.DataSource) error { + if _, err := tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock($1::bigint)`, int64(oidcDeviceFlowLock)); err != nil { + return err + } + if _, err := tx.ExecContext(ctx, `DELETE FROM oidc_device_flows WHERE expires_at <= now()`); err != nil { + return err + } + var total int + if err := tx.GetContext(ctx, &total, `SELECT count(*) FROM oidc_device_flows`); err != nil { + return err + } + if total >= maxConcurrentDeviceFlows { + return errTooManyDeviceFlows + } + if clientIP != "" { + var perIP int + if err := tx.GetContext(ctx, &perIP, `SELECT count(*) FROM oidc_device_flows WHERE client_ip = $1`, clientIP); err != nil { + return err + } + if perIP >= maxDeviceFlowsPerIP { + return errTooManyDeviceFlowsPerIP + } + } + _, err := tx.ExecContext(ctx, ` + INSERT INTO oidc_device_flows (handle, client_ip, expires_at) + VALUES ($1, $2, $3)`, handle, clientIP, expiresAt) + return err + }) +} + +func deviceFlowLive(ctx context.Context, ds sqlutil.DataSource, handle string) (bool, error) { + var n int + err := ds.GetContext(ctx, &n, ` + SELECT count(*) FROM oidc_device_flows + WHERE handle = $1 AND expires_at > now()`, handle) + if err != nil { + return false, err + } + return n == 1, nil +} + +func removeDeviceFlow(ctx context.Context, ds sqlutil.DataSource, handle string) error { + _, err := ds.ExecContext(ctx, `DELETE FROM oidc_device_flows WHERE handle = $1`, handle) + return err +} + +func recordDeviceFlowResult(ctx context.Context, ds sqlutil.DataSource, handle, sessionID, email, role, errText string) error { + _, err := ds.ExecContext(ctx, ` + UPDATE oidc_device_flows + SET done = true, session_id = $2, email = $3, role = $4, err = $5 + WHERE handle = $1`, handle, sessionID, email, role, errText) + return err +} + +// consumeDeviceFlow deletes a finished flow and returns it. A second caller +// sees unknown. A row that is not finished yet is left in place and reported +// as pending. +func consumeDeviceFlow(ctx context.Context, ds sqlutil.DataSource, handle string) (sessionID, email string, role clsessions.UserRole, terminal, known bool, flowErr error, err error) { + var row struct { + SessionID string `db:"session_id"` + Email string + Role string + Err string + ExpiresAt time.Time `db:"expires_at"` + } + err = ds.GetContext(ctx, &row, ` + DELETE FROM oidc_device_flows + WHERE handle = $1 AND done = true + RETURNING session_id, email, role, err, expires_at`, handle) + if err == nil { + if time.Now().After(row.ExpiresAt) { + return "", "", "", false, false, nil, nil + } + var storedErr error + if row.Err != "" { + storedErr = errors.New(row.Err) + } + return row.SessionID, row.Email, clsessions.UserRole(row.Role), true, true, storedErr, nil + } + if !errors.Is(err, sql.ErrNoRows) { + return "", "", "", false, false, nil, err + } + var pending int + if err = ds.GetContext(ctx, &pending, ` + SELECT count(*) FROM oidc_device_flows + WHERE handle = $1 AND expires_at > now()`, handle); err != nil { + return "", "", "", false, false, nil, err + } + if pending == 1 { + return "", "", "", false, true, nil, nil + } + return "", "", "", false, false, nil, nil +} diff --git a/core/sessions/oidcauth/login_state_store_test.go b/core/sessions/oidcauth/login_state_store_test.go new file mode 100644 index 00000000000..09100b61df0 --- /dev/null +++ b/core/sessions/oidcauth/login_state_store_test.go @@ -0,0 +1,87 @@ +package oidcauth + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest" + clsessions "github.com/smartcontractkit/chainlink/v2/core/sessions" +) + +func TestPendingAuth_SharedRoundTrip(t *testing.T) { + t.Parallel() + db := pgtest.NewSqlxDB(t) + ctx := t.Context() + exp := time.Now().Add(pendingAuthTTL) + + require.NoError(t, putPendingAuth(ctx, db, "state-1", "verifier-1", "nonce-1", exp)) + + verifier, nonce, ok, err := takePendingAuth(ctx, db, "state-1") + require.NoError(t, err) + require.True(t, ok) + assert.Equal(t, "verifier-1", verifier) + assert.Equal(t, "nonce-1", nonce) + + _, _, ok, err = takePendingAuth(ctx, db, "state-1") + require.NoError(t, err) + assert.False(t, ok) + + require.NoError(t, putPendingAuth(ctx, db, "state-expired", "verifier-2", "nonce-2", time.Now().Add(-time.Second))) + _, _, ok, err = takePendingAuth(ctx, db, "state-expired") + require.NoError(t, err) + assert.False(t, ok) +} + +func TestReserveDeviceFlow_PerIPCap(t *testing.T) { + t.Parallel() + db := pgtest.NewSqlxDB(t) + ctx := t.Context() + exp := time.Now().Add(time.Minute) + + for i := range maxDeviceFlowsPerIP { + require.NoError(t, reserveDeviceFlow(ctx, db, handleN(i), "203.0.113.10", exp)) + } + err := reserveDeviceFlow(ctx, db, "overflow", "203.0.113.10", exp) + require.ErrorIs(t, err, errTooManyDeviceFlowsPerIP) + require.NoError(t, reserveDeviceFlow(ctx, db, "other", "198.51.100.1", exp)) +} + +func TestConsumeDeviceFlow_SingleWinner(t *testing.T) { + t.Parallel() + db := pgtest.NewSqlxDB(t) + ctx := t.Context() + exp := time.Now().Add(time.Minute) + require.NoError(t, reserveDeviceFlow(ctx, db, "shared-handle", "203.0.113.9", exp)) + + var ( + sessionID, email string + role clsessions.UserRole + terminal, known bool + flowErr, err error + ) + sessionID, _, _, terminal, known, flowErr, err = consumeDeviceFlow(ctx, db, "shared-handle") + require.NoError(t, err) + assert.False(t, terminal) + assert.True(t, known, "an unfinished flow stays pending") + assert.Empty(t, sessionID) + require.NoError(t, flowErr) + + require.NoError(t, recordDeviceFlowResult(ctx, db, "shared-handle", "sess-winner", "a@example.com", string(clsessions.UserRoleEdit), "")) + + sessionID, email, role, terminal, known, flowErr, err = consumeDeviceFlow(ctx, db, "shared-handle") + require.NoError(t, err) + require.True(t, terminal) + require.True(t, known) + assert.Equal(t, "sess-winner", sessionID) + assert.Equal(t, "a@example.com", email) + assert.Equal(t, clsessions.UserRoleEdit, role) + require.NoError(t, flowErr) + + _, _, _, terminal, known, _, err = consumeDeviceFlow(ctx, db, "shared-handle") + require.NoError(t, err) + assert.False(t, terminal) + assert.False(t, known, "a second poll must not observe the completed flow") +} diff --git a/core/sessions/oidcauth/mock_idp_test.go b/core/sessions/oidcauth/mock_idp_test.go index 78f33511a1d..de9352c4dea 100644 --- a/core/sessions/oidcauth/mock_idp_test.go +++ b/core/sessions/oidcauth/mock_idp_test.go @@ -158,6 +158,5 @@ func newAuthenticatorForIDP(t *testing.T, idp *mockIDP, ds sqlutil.DataSource) * lggr: logger.TestSugared(t), auditLogger: &audit.AuditLoggerService{}, deviceFlows: newDeviceFlowStore(), - pendingAuth: newPendingAuthStore(), } } diff --git a/core/sessions/oidcauth/oidc.go b/core/sessions/oidcauth/oidc.go index 16031cc5abe..3db7442c597 100644 --- a/core/sessions/oidcauth/oidc.go +++ b/core/sessions/oidcauth/oidc.go @@ -18,6 +18,7 @@ import ( "net/mail" "slices" "strings" + "time" "github.com/coreos/go-oidc/v3/oidc" "github.com/gin-contrib/sessions" @@ -51,9 +52,6 @@ type oidcAuthenticator struct { lggr logger.SugaredLogger auditLogger audit.Logger deviceFlows *deviceFlowStore - // pendingAuth holds PKCE verifiers and OIDC nonces server-side for the - // browser authorization-code flow (not in the signed session cookie). - pendingAuth *pendingAuthStore } // ExchangeTokenRequest represents the expected JSON payload from the frontend @@ -140,12 +138,12 @@ func NewOIDCAuthenticator( lggr: logger.Sugared(lggr).Named("OIDCAuthenticationProvider"), auditLogger: auditLogger, deviceFlows: newDeviceFlowStore(), - pendingAuth: newPendingAuthStore(), } - // Device-flow and pending-auth state are process-local. Multi-replica nodes - // need sticky sessions for OIDC routes (see device_flow.go header comment). - oidcAuth.lggr.Infof("OIDC authenticator ready (device flow + PKCE). Multi-replica deployments require session affinity for /oidc-device/* and /oidc-login|/oidc-exchange") + // Browser login state and device-flow results live in Postgres, so any + // replica can finish a login. The provider device code stays in the poller + // process that called the identity provider. + oidcAuth.lggr.Infof("OIDC authenticator ready (device flow + PKCE). Login state is shared across replicas; the provider device code stays on the replica that started the flow") return &oidcAuth, nil } @@ -173,14 +171,18 @@ func (oi *oidcAuthenticator) handleSignIn(c *gin.Context) { state := oi.generateState() verifier := oauth2.GenerateVerifier() nonce := oi.generateState() - oi.pendingAuth.put(state, verifier, nonce) + if err := putPendingAuth(c.Request.Context(), oi.ds, state, verifier, nonce, time.Now().Add(pendingAuthTTL)); err != nil { + oi.lggr.Errorf("failed to store authorization state: %v", err) + c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to start login"}) + return + } session := sessions.Default(c) session.Set("state", state) // Intentionally do NOT store pkce_verifier or nonce in the cookie. err := session.Save() if err != nil { - oi.pendingAuth.take(state) // best-effort cleanup + _, _, _, _ = takePendingAuth(c.Request.Context(), oi.ds, state) c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save session"}) return } @@ -217,8 +219,16 @@ func (oi *oidcAuthenticator) handleTokenExchange(c *gin.Context) { return } - // Recover PKCE verifier + nonce from the server-side store (single-use). - storedVerifier, expectedNonce, ok := oi.pendingAuth.take(req.State) + // Recover PKCE verifier + nonce from the shared store (single-use). + storedVerifier, expectedNonce, ok, err := takePendingAuth(c.Request.Context(), oi.ds, req.State) + if err != nil { + oi.lggr.Errorf("failed to load authorization state: %v", err) + c.JSON(http.StatusInternalServerError, ExchangeTokenResponse{ + Success: false, + Message: "Failed to load authorization state", + }) + return + } if !ok || storedVerifier == "" { c.JSON(http.StatusBadRequest, ExchangeTokenResponse{ Success: false, @@ -315,6 +325,10 @@ func (oi *oidcAuthenticator) issueSessionFromIDToken(ctx context.Context, rawIDT if err != nil { return "", "", "", err } + if extra := unexpectedGroup(idClaims, oi.config.AdminClaim(), oi.config.EditClaim(), oi.config.RunClaim(), oi.config.ReadClaim()); extra != "" { + oi.auditLogger.Audit(audit.AuthLoginFailed2FA, map[string]any{"email": email, "reason": "unexpected_group", "group": extra}) + return "", "", "", fmt.Errorf("%w: groups claim is not limited to the configured role groups", errNoMatchingRole) + } oi.lggr.Tracef("Received and validated ID claims: %v\n", idClaims) role, err := oi.IDClaimsToUserRole( @@ -397,53 +411,11 @@ func (oi *oidcAuthenticator) FindUser(ctx context.Context, email string) (clsess return foundUser, nil } -// FindUserByAPIToken retrieves a possible stored user and role from the oidc_user_api_tokens table store -func (oi *oidcAuthenticator) FindUserByAPIToken(ctx context.Context, apiToken string) (clsessions.User, error) { - if !oi.config.UserAPITokenEnabled() { - return clsessions.User{}, errors.New("API token is not enabled") - } - - var foundUser clsessions.User - err := sqlutil.TransactDataSource(ctx, oi.ds, nil, func(tx sqlutil.DataSource) error { - // Query the oidc user API token table for the given token. The user role - // and email are cached on the row, so no upstream OIDC query is performed - // on lookup. NOTE: there is no upstream revocation sync for these tokens. - // The OIDC reaper (reaper.go) only deletes stale oidc_sessions, and - // UpstreamSyncInterval applies to the LDAP provider, not OIDC. A cached - // token therefore retains its role until its own UserAPITokenDuration - // expiry, even if the user's group is revoked at the identity provider. - // This mechanism must stay disabled (UserAPITokenEnabled = false) until - // that revocation gap is fixed. - var foundUserToken struct { - UserEmail string - UserRole clsessions.UserRole - Valid bool - } - if err := tx.GetContext(ctx, &foundUserToken, - "SELECT user_email, user_role, created_at + $2 >= now() as valid FROM oidc_user_api_tokens WHERE token_key = $1", - apiToken, oi.config.UserAPITokenDuration().Duration(), - ); err != nil { - return err - } - if !foundUserToken.Valid { - return clsessions.ErrUserSessionExpired - } - foundUser = clsessions.User{ - Email: foundUserToken.UserEmail, - Role: foundUserToken.UserRole, - } - return nil - }) - if err != nil { - if errors.Is(err, clsessions.ErrUserSessionExpired) { - // API Token expired, purge - if _, execErr := oi.ds.ExecContext(ctx, "DELETE FROM oidc_user_api_tokens WHERE token_key = $1", apiToken); execErr != nil { - oi.lggr.Errorf("error purging stale oidc API token session: %v", execErr) - } - } - return clsessions.User{}, err - } - return foundUser, nil +// FindUserByAPIToken refuses OIDC API tokens. The token row caches the role, +// nothing re-checks the identity provider when a group is revoked, and the +// session reaper does not touch this table. The config flag does not enable it. +func (oi *oidcAuthenticator) FindUserByAPIToken(context.Context, string) (clsessions.User, error) { + return clsessions.User{}, errors.New("OIDC API tokens are disabled") } // ListUsers in the context of the OIDC driver only supports listing the local (admin) users, we don't have an identity server to query against @@ -616,44 +588,9 @@ func (oi *oidcAuthenticator) CreateAndSetAuthToken(ctx context.Context, user *cl return newToken, nil } -// SetAuthToken updates the user to use the given Authentication Token. -func (oi *oidcAuthenticator) SetAuthToken(ctx context.Context, user *clsessions.User, token *auth.Token) error { - if !oi.config.UserAPITokenEnabled() { - return errors.New("API token is not enabled ") - } - - salt := utils.NewSecret(utils.DefaultSecretSize) - hashedSecret, err := auth.HashedSecret(token, salt) - if err != nil { - return fmt.Errorf("OIDCAuth SetAuthToken hashed secret error: %w", err) - } - - err = sqlutil.TransactDataSource(ctx, oi.ds, nil, func(tx sqlutil.DataSource) error { - // Remove any existing API tokens - if _, err = oi.ds.ExecContext(ctx, "DELETE FROM oidc_user_api_tokens WHERE user_email = $1", user.Email); err != nil { - return fmt.Errorf("error executing DELETE FROM oidc_user_api_tokens: %w", err) - } - // Create new API token for user - _, err = oi.ds.ExecContext(ctx, - "INSERT INTO oidc_user_api_tokens (user_email, user_role, token_key, token_salt, token_hashed_secret, created_at) VALUES ($1, $2, $3, $4, $5, $6, now())", - user.Email, - user.Role, - token.AccessKey, - salt, - hashedSecret, - ) - if err != nil { - return fmt.Errorf("failed insert into oidc_user_api_tokens: %w", err) - } - return nil - }) - if err != nil { - oi.lggr.Errorf("error creating API token: %v", err) - return errors.New("error creating API token") - } - - oi.auditLogger.Audit(audit.APITokenCreated, map[string]any{"user": user.Email}) - return nil +// SetAuthToken refuses OIDC API tokens. See FindUserByAPIToken. +func (oi *oidcAuthenticator) SetAuthToken(context.Context, *clsessions.User, *auth.Token) error { + return errors.New("OIDC API tokens are disabled") } // DeleteAuthToken clears and disables the users Authentication Token. @@ -774,11 +711,11 @@ func (oi *oidcAuthenticator) ExtendRouter(api *gin.RouterGroup) error { // background goroutine); poll is cheaper but still unauthenticated. // These nest under the outer api rate limiter so both apply. api.POST("/oidc-device/start", - deviceEndpointRateLimit(deviceStartRatePeriod, deviceStartRateLimit), + deviceEndpointRateLimit(deviceStartRatePeriod, deviceStartRateLimit, oi.lggr), oi.handleDeviceStart, ) api.POST("/oidc-device/poll", - deviceEndpointRateLimit(devicePollRatePeriod, devicePollRateLimit), + deviceEndpointRateLimit(devicePollRatePeriod, devicePollRateLimit, oi.lggr), oi.handleDevicePoll, ) diff --git a/core/sessions/oidcauth/oidc_test.go b/core/sessions/oidcauth/oidc_test.go index ccfbc4c81f0..2794b2aef9a 100644 --- a/core/sessions/oidcauth/oidc_test.go +++ b/core/sessions/oidcauth/oidc_test.go @@ -65,9 +65,8 @@ func TestORM_FindUser_Single(t *testing.T) { require.Equal(t, foundUser.Role, user1.Role) } -func TestORM_FindUserByAPIToken_Success(t *testing.T) { +func TestORM_FindUserByAPIToken_Disabled(t *testing.T) { ctx := t.Context() - // Init OIDC authenticator db, oidcAuthProvider := setupAuthenticationProvider(t) testEmail := "test@test.com" @@ -75,16 +74,15 @@ func TestORM_FindUserByAPIToken_Success(t *testing.T) { _, err := db.Exec("INSERT INTO oidc_user_api_tokens values ($1, 'edit', $2, '', '', now())", testEmail, apiToken) require.NoError(t, err) - // Find user - foundUser, err := oidcAuthProvider.FindUserByAPIToken(ctx, apiToken) - require.NoError(t, err) - require.Equal(t, foundUser.Email, testEmail) - require.Equal(t, sessions.UserRoleEdit, foundUser.Role) + _, err = oidcAuthProvider.FindUserByAPIToken(ctx, apiToken) + require.EqualError(t, err, "OIDC API tokens are disabled") + + _, err = oidcAuthProvider.CreateAndSetAuthToken(ctx, &sessions.User{Email: testEmail, Role: sessions.UserRoleEdit}) + require.EqualError(t, err, "OIDC API tokens are disabled") } -func TestORM_FindUserByAPIToken_Expired(t *testing.T) { +func TestORM_FindUserByAPIToken_ExpiredStillDisabled(t *testing.T) { ctx := t.Context() - // Init OIDC authenticator cfg := oidcauth.TestConfig{} db, oidcAuthProvider := setupAuthenticationProvider(t) @@ -94,35 +92,29 @@ func TestORM_FindUserByAPIToken_Expired(t *testing.T) { _, err := db.Exec("INSERT INTO oidc_user_api_tokens values ($1, 'edit', $2, '', '', $3)", testEmail, apiToken, expiredTime) require.NoError(t, err, "failed to insert expired token") - // Token found but expired. expect error _, err = oidcAuthProvider.FindUserByAPIToken(ctx, apiToken) - require.ErrorIs(t, err, sessions.ErrUserSessionExpired, "expected expired token to return ErrUserSessionExpired") + require.EqualError(t, err, "OIDC API tokens are disabled") } func TestORM_DeleteAuthToken(t *testing.T) { ctx := t.Context() - // Init OIDC authenticator db, oidcAuthProvider := setupAuthenticationProvider(t) - // Create a token for a test user testEmail := "test-delete@test.com" apiToken := "delete-test-token" _, err := db.Exec("INSERT INTO oidc_user_api_tokens values ($1, 'edit', $2, '', '', now())", testEmail, apiToken) require.NoError(t, err) - // Verify token exists by finding user - user, err := oidcAuthProvider.FindUserByAPIToken(ctx, apiToken) - require.NoError(t, err) - require.Equal(t, testEmail, user.Email) + var n int + require.NoError(t, db.Get(&n, "SELECT count(*) FROM oidc_user_api_tokens WHERE user_email = $1", testEmail)) + require.Equal(t, 1, n) - // Delete the auth token - err = oidcAuthProvider.DeleteAuthToken(ctx, &user) + err = oidcAuthProvider.DeleteAuthToken(ctx, &sessions.User{Email: testEmail}) require.NoError(t, err) - // Verify token is deleted - FindUserByAPIToken should fail - _, err = oidcAuthProvider.FindUserByAPIToken(ctx, apiToken) - require.Error(t, err) + require.NoError(t, db.Get(&n, "SELECT count(*) FROM oidc_user_api_tokens WHERE user_email = $1", testEmail)) + require.Equal(t, 0, n) } func TestORM_ListUsers(t *testing.T) { diff --git a/core/sessions/oidcauth/pending_auth.go b/core/sessions/oidcauth/pending_auth.go index bae794c41b1..7b595b97788 100644 --- a/core/sessions/oidcauth/pending_auth.go +++ b/core/sessions/oidcauth/pending_auth.go @@ -5,14 +5,10 @@ import ( "time" ) -// pendingAuth holds server-side secrets for one browser authorization-code -// login. The PKCE verifier and OIDC nonce must not round-trip through the -// signed-but-not-encrypted session cookie (see OCD-004 / OCD-005). Only the -// anti-CSRF state value is stored client-side; the secrets stay here, keyed by -// that state, until a single successful take() at exchange time. -// -// Like deviceFlowStore this is process-local: multi-replica deployments need -// session affinity for /oidc-login → /oidc-exchange, or a shared short-TTL store. +// pendingAuth is the in-memory copy used by unit tests that have no database. +// Production sign-in and exchange write oidc_pending_auth. The cookie holds +// only the anti-CSRF state. The PKCE verifier and OIDC nonce stay server-side, +// keyed by that state, until a single successful take at exchange time. type pendingAuth struct { verifier string nonce string diff --git a/core/sessions/oidcauth/reaper.go b/core/sessions/oidcauth/reaper.go index 6210e6252e1..7473042fac9 100644 --- a/core/sessions/oidcauth/reaper.go +++ b/core/sessions/oidcauth/reaper.go @@ -46,6 +46,12 @@ func (sr *sessionReaper) Work(ctx context.Context) { // DeleteStaleSessions deletes all sessions before the passed time. func (sr *sessionReaper) deleteStaleSessions(ctx context.Context, before time.Time) error { - _, err := sr.ds.ExecContext(ctx, "DELETE FROM oidc_sessions WHERE created_at < $1", before) + if _, err := sr.ds.ExecContext(ctx, "DELETE FROM oidc_sessions WHERE created_at < $1", before); err != nil { + return err + } + if _, err := sr.ds.ExecContext(ctx, "DELETE FROM oidc_pending_auth WHERE expires_at <= now()"); err != nil { + return err + } + _, err := sr.ds.ExecContext(ctx, "DELETE FROM oidc_device_flows WHERE expires_at <= now()") return err } diff --git a/core/sessions/oidcauth/verify_flow_test.go b/core/sessions/oidcauth/verify_flow_test.go index 0d573b99e0d..318e5e07a38 100644 --- a/core/sessions/oidcauth/verify_flow_test.go +++ b/core/sessions/oidcauth/verify_flow_test.go @@ -72,6 +72,22 @@ func TestIssueSessionFromIDToken_Expired(t *testing.T) { assert.Equal(t, 0, countOIDCSessions(t, oi, "expired-user@example.com")) } +// TestIssueSessionFromIDToken_UnexpectedGroup rejects a token that carries a +// configured role group plus any other group. The login fails closed. +func TestIssueSessionFromIDToken_UnexpectedGroup(t *testing.T) { + t.Parallel() + db := pgtest.NewSqlxDB(t) + idp := newMockIDP(t, testClientID) + idp.email = "extra-group@example.com" + idp.groups = []string{AdminClaim, "Contractors"} + oi := newAuthenticatorForIDP(t, idp, db) + + _, _, _, err := oi.issueSessionFromIDToken(t.Context(), idp.signIDToken(t), "") + require.ErrorIs(t, err, errNoMatchingRole) + assert.Contains(t, err.Error(), "not limited") + assert.Equal(t, 0, countOIDCSessions(t, oi, "extra-group@example.com")) +} + // TestIssueSessionFromIDToken_NoMatchingGroup asserts a validly signed token // whose groups map to no RBAC role is rejected with errNoMatchingRole and // creates no session. @@ -142,7 +158,8 @@ func TestDeviceFlow_EndToEnd(t *testing.T) { require.NoError(t, err) const handle = "e2e-handle" - state := &deviceFlowState{expiresAt: time.Now().Add(time.Minute)} + state := &deviceFlowState{expiresAt: time.Now().Add(time.Minute), clientIP: "127.0.0.1"} + require.NoError(t, reserveDeviceFlow(t.Context(), oi.ds, handle, state.clientIP, state.expiresAt)) require.NoError(t, oi.deviceFlows.add(handle, state)) oi.pollDeviceToken(handle, state, da) @@ -217,7 +234,8 @@ func TestDeviceFlow_WrongAudienceRejected(t *testing.T) { require.NoError(t, err) const handle = "e2e-handle-2" - state := &deviceFlowState{expiresAt: time.Now().Add(time.Minute)} + state := &deviceFlowState{expiresAt: time.Now().Add(time.Minute), clientIP: "127.0.0.1"} + require.NoError(t, reserveDeviceFlow(t.Context(), oi.ds, handle, state.clientIP, state.expiresAt)) require.NoError(t, oi.deviceFlows.add(handle, state)) oi.pollDeviceToken(handle, state, da) diff --git a/core/store/migrate/migrations/0309_oidc_login_state.sql b/core/store/migrate/migrations/0309_oidc_login_state.sql new file mode 100644 index 00000000000..2609e42dbbe --- /dev/null +++ b/core/store/migrate/migrations/0309_oidc_login_state.sql @@ -0,0 +1,27 @@ +-- +goose Up +-- Short-lived login state shared by every replica. The provider device code +-- is not stored here. Only the opaque handle and the browser state key are. +CREATE TABLE IF NOT EXISTS oidc_pending_auth ( + state text PRIMARY KEY, + verifier text NOT NULL, + nonce text NOT NULL, + expires_at timestamp WITH time zone NOT NULL +); + +CREATE TABLE IF NOT EXISTS oidc_device_flows ( + handle text PRIMARY KEY, + client_ip text NOT NULL DEFAULT '', + expires_at timestamp WITH time zone NOT NULL, + done boolean NOT NULL DEFAULT false, + session_id text NOT NULL DEFAULT '', + email text NOT NULL DEFAULT '', + role text NOT NULL DEFAULT '', + err text NOT NULL DEFAULT '' +); + +CREATE INDEX IF NOT EXISTS idx_oidc_device_flows_client_ip + ON oidc_device_flows (client_ip); + +-- +goose Down +DROP TABLE IF EXISTS oidc_device_flows; +DROP TABLE IF EXISTS oidc_pending_auth; From 25cfe6d1e745a597d87c0954bd209f7dc309bef3 Mon Sep 17 00:00:00 2001 From: Harry Anderson Date: Tue, 6 Oct 2026 03:52:48 +0000 Subject: [PATCH 12/18] fix(oidc): satisfy lint on device-flow guards Rename the expiry bound so it does not shadow cap, walk X-Forwarded-For from the right with slices.Backward, and return one sentinel when OIDC API tokens are refused. --- core/sessions/oidcauth/login_guards.go | 11 +++++---- core/sessions/oidcauth/login_guards_test.go | 10 ++++---- core/sessions/oidcauth/oidc.go | 27 ++++++++++----------- core/sessions/oidcauth/oidc_test.go | 2 ++ 4 files changed, 26 insertions(+), 24 deletions(-) diff --git a/core/sessions/oidcauth/login_guards.go b/core/sessions/oidcauth/login_guards.go index 41ed8360dbd..e6b09f82b22 100644 --- a/core/sessions/oidcauth/login_guards.go +++ b/core/sessions/oidcauth/login_guards.go @@ -3,6 +3,7 @@ package oidcauth import ( "net" "net/url" + "slices" "strings" "time" @@ -18,9 +19,9 @@ func capDeviceExpiry(expiry, now time.Time) time.Time { if !expiry.IsZero() && !expiry.After(now) { return expiry } - cap := now.Add(maxDeviceFlowLifetime) - if expiry.IsZero() || expiry.After(cap) { - return cap + deadline := now.Add(maxDeviceFlowLifetime) + if expiry.IsZero() || expiry.After(deadline) { + return deadline } return expiry } @@ -72,8 +73,8 @@ func deviceClientIP(c *gin.Context) string { return peer } parts := strings.Split(xff, ",") - for i := len(parts) - 1; i >= 0; i-- { - ip := net.ParseIP(strings.TrimSpace(parts[i])) + for _, part := range slices.Backward(parts) { + ip := net.ParseIP(strings.TrimSpace(part)) if ip != nil { return ip.String() } diff --git a/core/sessions/oidcauth/login_guards_test.go b/core/sessions/oidcauth/login_guards_test.go index 1fedb5c328d..acb08b2edd0 100644 --- a/core/sessions/oidcauth/login_guards_test.go +++ b/core/sessions/oidcauth/login_guards_test.go @@ -70,19 +70,19 @@ func TestDeviceFailureReason(t *testing.T) { t.Parallel() require.Empty(t, deviceFailureReason(nil)) assert.Equal(t, "failed", deviceFailureReason(assert.AnError)) - assert.Equal(t, "denied", deviceFailureReason(errString("access_denied"))) + assert.Equal(t, "denied", deviceFailureReason(stringError("access_denied"))) assert.Equal(t, "abandoned", deviceFailureReason(errDeviceFlowAbandoned)) - assert.Equal(t, "expired", deviceFailureReason(errString("context deadline exceeded"))) + assert.Equal(t, "expired", deviceFailureReason(stringError("context deadline exceeded"))) } -type errString string +type stringError string -func (e errString) Error() string { return string(e) } +func (e stringError) Error() string { return string(e) } func deviceRequest(t *testing.T, remoteAddr, xff string) *gin.Context { t.Helper() c, _ := gin.CreateTestContext(httptest.NewRecorder()) - c.Request = httptest.NewRequest(http.MethodPost, "/oidc-device/start", nil) + c.Request = httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/oidc-device/start", nil) c.Request.RemoteAddr = remoteAddr if xff != "" { c.Request.Header.Set("X-Forwarded-For", xff) diff --git a/core/sessions/oidcauth/oidc.go b/core/sessions/oidcauth/oidc.go index 3db7442c597..04567867940 100644 --- a/core/sessions/oidcauth/oidc.go +++ b/core/sessions/oidcauth/oidc.go @@ -411,11 +411,15 @@ func (oi *oidcAuthenticator) FindUser(ctx context.Context, email string) (clsess return foundUser, nil } -// FindUserByAPIToken refuses OIDC API tokens. The token row caches the role, -// nothing re-checks the identity provider when a group is revoked, and the -// session reaper does not touch this table. The config flag does not enable it. +// errOIDCAPITokensDisabled is returned for every OIDC API-token operation. +// The token row caches the role, nothing re-checks the identity provider when +// a group is revoked, and the session reaper does not touch that table. The +// config flag does not enable the path. +var errOIDCAPITokensDisabled = errors.New("OIDC API tokens are disabled") + +// FindUserByAPIToken refuses OIDC API tokens. See errOIDCAPITokensDisabled. func (oi *oidcAuthenticator) FindUserByAPIToken(context.Context, string) (clsessions.User, error) { - return clsessions.User{}, errors.New("OIDC API tokens are disabled") + return clsessions.User{}, errOIDCAPITokensDisabled } // ListUsers in the context of the OIDC driver only supports listing the local (admin) users, we don't have an identity server to query against @@ -578,19 +582,14 @@ func (oi *oidcAuthenticator) TestPassword(ctx context.Context, email, password s return nil } -// CreateAndSetAuthToken generates a new credential token with the user role -func (oi *oidcAuthenticator) CreateAndSetAuthToken(ctx context.Context, user *clsessions.User) (*auth.Token, error) { - newToken := auth.NewToken() - err := oi.SetAuthToken(ctx, user, newToken) - if err != nil { - return nil, err - } - return newToken, nil +// CreateAndSetAuthToken refuses OIDC API tokens. See errOIDCAPITokensDisabled. +func (oi *oidcAuthenticator) CreateAndSetAuthToken(context.Context, *clsessions.User) (*auth.Token, error) { + return nil, errOIDCAPITokensDisabled } -// SetAuthToken refuses OIDC API tokens. See FindUserByAPIToken. +// SetAuthToken refuses OIDC API tokens. See errOIDCAPITokensDisabled. func (oi *oidcAuthenticator) SetAuthToken(context.Context, *clsessions.User, *auth.Token) error { - return errors.New("OIDC API tokens are disabled") + return errOIDCAPITokensDisabled } // DeleteAuthToken clears and disables the users Authentication Token. diff --git a/core/sessions/oidcauth/oidc_test.go b/core/sessions/oidcauth/oidc_test.go index 2794b2aef9a..3baf1537ae4 100644 --- a/core/sessions/oidcauth/oidc_test.go +++ b/core/sessions/oidcauth/oidc_test.go @@ -66,6 +66,7 @@ func TestORM_FindUser_Single(t *testing.T) { } func TestORM_FindUserByAPIToken_Disabled(t *testing.T) { + t.Parallel() ctx := t.Context() db, oidcAuthProvider := setupAuthenticationProvider(t) @@ -82,6 +83,7 @@ func TestORM_FindUserByAPIToken_Disabled(t *testing.T) { } func TestORM_FindUserByAPIToken_ExpiredStillDisabled(t *testing.T) { + t.Parallel() ctx := t.Context() cfg := oidcauth.TestConfig{} db, oidcAuthProvider := setupAuthenticationProvider(t) From 381d7955c58f6d71a2315e8eef68f249b66bfcfe Mon Sep 17 00:00:00 2001 From: Harry Anderson Date: Thu, 29 Oct 2026 02:23:03 +0000 Subject: [PATCH 13/18] fix(oidc): move login-state migration to 0310 develop already ships 0309_relax_bhs_bhf_coordinator_constraints.sql. A second 0309 file fails goose at startup, so the OIDC login tables move to the next version. --- .../{0309_oidc_login_state.sql => 0310_oidc_login_state.sql} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename core/store/migrate/migrations/{0309_oidc_login_state.sql => 0310_oidc_login_state.sql} (100%) diff --git a/core/store/migrate/migrations/0309_oidc_login_state.sql b/core/store/migrate/migrations/0310_oidc_login_state.sql similarity index 100% rename from core/store/migrate/migrations/0309_oidc_login_state.sql rename to core/store/migrate/migrations/0310_oidc_login_state.sql From fc4f44bc5bb5c7983bab42e9deb30a9ff0f5f3ec Mon Sep 17 00:00:00 2001 From: Harry Anderson Date: Tue, 10 Nov 2026 20:22:59 +0000 Subject: [PATCH 14/18] feat(oidc): allow extra IdP groups and give device login denial reasons Drop the check that rejected any groups claim containing a group outside the four configured role groups. Real users belong to many IdP groups; role mapping already ignores unknown groups and picks the highest configured role. The device poll response now carries a reason code (no_role, denied, expired, abandoned, failed). The CLI maps it to its own text instead of "denied or expired", so a user with no matching role group is told so. OIDC role-mapping failures now log as AUTH_LOGIN_FAILED_OIDC instead of AUTH_LOGIN_FAILED_2FA. --- .changeset/oidc-cli-device-flow.md | 2 +- core/cmd/oidc_device_auth.go | 45 +++++++++++++------ core/cmd/oidc_device_auth_test.go | 49 ++++++++++++++------- core/logger/audit/audit_types.go | 1 + core/sessions/oidcauth/device_flow.go | 13 ++++-- core/sessions/oidcauth/login_guards.go | 33 +++++++------- core/sessions/oidcauth/login_guards_test.go | 14 +++--- core/sessions/oidcauth/oidc.go | 6 +-- core/sessions/oidcauth/verify_flow_test.go | 18 ++++---- 9 files changed, 111 insertions(+), 70 deletions(-) diff --git a/.changeset/oidc-cli-device-flow.md b/.changeset/oidc-cli-device-flow.md index 9b7e6728e7f..58da2587809 100644 --- a/.changeset/oidc-cli-device-flow.md +++ b/.changeset/oidc-cli-device-flow.md @@ -6,4 +6,4 @@ #changed The OIDC authorization-code (operator UI) flow now always uses PKCE (RFC 7636). The OIDC `ClientSecret` is now optional: confidential clients still send it, while public clients (required for the device flow) rely on PKCE instead. Existing confidential-client deployments are unaffected. -#changed Hardened OIDC device and auth-code flows: dedicated pre-auth rate limits and per-IP concurrency caps on device endpoints, server-side PKCE verifier and OIDC nonce (the session cookie holds only the anti-CSRF state), email claim validation, orphan-session cleanup if cookie bind fails, and a stricter CLI `/oidc-enabled` probe. Browser login state and device-flow results are stored in Postgres so any replica can finish a login. The provider device code stays on the replica that started the flow and is not written to the database. Device-flow lifetime is capped at five minutes. A verification URI whose host does not match the configured provider is rejected. When the socket peer is a private proxy, device-flow rate limits use the rightmost X-Forwarded-For address; a public peer is used as-is. Denied device flows are audited. A groups claim that contains any value other than the configured role groups is rejected. OIDC API tokens cannot be created or used. The CLI refuses device login when TLS verification is disabled. +#changed Hardened OIDC device and auth-code flows: dedicated pre-auth rate limits and per-IP concurrency caps on device endpoints, server-side PKCE verifier and OIDC nonce (the session cookie holds only the anti-CSRF state), email claim validation, orphan-session cleanup if cookie bind fails, and a stricter CLI `/oidc-enabled` probe. Browser login state and device-flow results are stored in Postgres so any replica can finish a login. The provider device code stays on the replica that started the flow and is not written to the database. Device-flow lifetime is capped at five minutes. A verification URI whose host does not match the configured provider is rejected. When the socket peer is a private proxy, device-flow rate limits use the rightmost X-Forwarded-For address; a public peer is used as-is. Denied device flows are audited. Groups the node does not know are ignored; the highest configured role group picks the role. A denied device login tells the CLI why, including when none of the user's groups map to a node role. OIDC API tokens cannot be created or used. The CLI refuses device login when TLS verification is disabled. diff --git a/core/cmd/oidc_device_auth.go b/core/cmd/oidc_device_auth.go index 95e4412b093..9dd98a6e488 100644 --- a/core/cmd/oidc_device_auth.go +++ b/core/cmd/oidc_device_auth.go @@ -38,9 +38,27 @@ type oidcDeviceStartResponse struct { // oidcDevicePollResponse mirrors oidcauth.DevicePollResponse. type oidcDevicePollResponse struct { Status string `json:"status"` + Reason string `json:"reason,omitempty"` Message string `json:"message,omitempty"` } +// deviceDeniedMessages maps a node failure reason to CLI text. The CLI uses +// its own text per reason rather than printing the node's message. +var deviceDeniedMessages = map[string]string{ + "no_role": "signed in, but none of your identity provider groups map to a node role; ask your IdP admin to add you to one of the node's configured role groups", + "denied": "device authorization was denied at the identity provider", + "expired": "device authorization expired before it was approved", + "abandoned": "device authorization was abandoned by the node; start the login again", + "unknown": "the node does not know this device login; it may have expired, start the login again", +} + +func deviceDeniedError(reason string) error { + if msg, ok := deviceDeniedMessages[reason]; ok { + return errors.New(msg) + } + return errors.New("device authorization was not completed; check the node log for the reason") +} + // OIDCDeviceCookieAuthenticator obtains a session cookie via the node-brokered // device authorization flow and persists it to the same cookie store the // password authenticator uses. @@ -120,7 +138,7 @@ func (o *OIDCDeviceCookieAuthenticator) Login(ctx context.Context) error { if time.Now().After(deadline) { return errors.New("device authorization timed out before approval") } - cookie, status, perr := o.poll(ctx, start.DeviceHandle) + cookie, status, reason, perr := o.poll(ctx, start.DeviceHandle) if perr != nil { return perr } @@ -131,7 +149,7 @@ func (o *OIDCDeviceCookieAuthenticator) Login(ctx context.Context) error { } return o.store.Save(cookie) case "denied": - return errors.New("device authorization was denied or expired") + return deviceDeniedError(reason) default: // "pending" continue } @@ -162,41 +180,42 @@ func (o *OIDCDeviceCookieAuthenticator) start(ctx context.Context) (*oidcDeviceS return &sr, nil } -// poll asks the node for the flow status. On "complete" the node sets the -// session cookie on the response, which is extracted and returned. -func (o *OIDCDeviceCookieAuthenticator) poll(ctx context.Context, handle string) (*http.Cookie, string, error) { +// poll asks the node for the flow status and, on "denied", the failure +// reason. On "complete" the node sets the session cookie on the response, +// which is extracted and returned. +func (o *OIDCDeviceCookieAuthenticator) poll(ctx context.Context, handle string) (*http.Cookie, string, string, error) { b, err := json.Marshal(map[string]string{"device_handle": handle}) if err != nil { - return nil, "", err + return nil, "", "", err } u := o.config.RemoteNodeURL.String() + "/oidc-device/poll" req, err := http.NewRequestWithContext(ctx, http.MethodPost, u, bytes.NewReader(b)) if err != nil { - return nil, "", err + return nil, "", "", err } req.Header.Set("Content-Type", "application/json") client := newHTTPClient(o.lggr, o.config.InsecureSkipVerify) resp, err := client.Do(req) if err != nil { - return nil, "", err + return nil, "", "", err } defer resp.Body.Close() body, _ := io.ReadAll(resp.Body) if resp.StatusCode == http.StatusNotFound { - return nil, "denied", nil + return nil, "denied", "unknown", nil } if resp.StatusCode != http.StatusOK { - return nil, "", errors.Errorf("device poll failed (status %d): %s", resp.StatusCode, string(body)) + return nil, "", "", errors.Errorf("device poll failed (status %d): %s", resp.StatusCode, string(body)) } var pr oidcDevicePollResponse if err := json.Unmarshal(body, &pr); err != nil { - return nil, "", errors.Wrap(err, "failed to parse device poll response") + return nil, "", "", errors.Wrap(err, "failed to parse device poll response") } if pr.Status == "complete" { - return web.FindSessionCookie(resp.Cookies()), "complete", nil + return web.FindSessionCookie(resp.Cookies()), "complete", "", nil } - return nil, pr.Status, nil + return nil, pr.Status, pr.Reason, nil } func (o *OIDCDeviceCookieAuthenticator) promptUser(start *oidcDeviceStartResponse) { diff --git a/core/cmd/oidc_device_auth_test.go b/core/cmd/oidc_device_auth_test.go index 9ea7299fd3c..d5cd204050f 100644 --- a/core/cmd/oidc_device_auth_test.go +++ b/core/cmd/oidc_device_auth_test.go @@ -23,6 +23,7 @@ type mockNode struct { oidcEnabled bool pollsPending int32 // number of "pending" polls to return before "complete" denyAfter bool // if true, return "denied" instead of completing + denyReason string } func (m *mockNode) handler(t *testing.T) http.Handler { @@ -58,7 +59,7 @@ func (m *mockNode) handler(t *testing.T) http.Handler { return } if m.denyAfter { - _ = json.NewEncoder(w).Encode(map[string]string{"status": "denied", "message": "expired"}) + _ = json.NewEncoder(w).Encode(map[string]string{"status": "denied", "reason": m.denyReason, "message": "node text"}) return } http.SetCookie(w, &http.Cookie{ @@ -139,19 +140,35 @@ func TestOIDCDeviceLogin_RefusesInsecureSkipVerify(t *testing.T) { func TestOIDCDeviceLogin_Denied(t *testing.T) { t.Parallel() - node := &mockNode{oidcEnabled: true, pollsPending: 1, denyAfter: true} - srv := httptest.NewServer(node.handler(t)) - defer srv.Close() - - store := &cmd.MemoryCookieStore{} - var out bytes.Buffer - auth := cmd.NewOIDCDeviceCookieAuthenticator(newClientOpts(t, srv), store, &out, logger.TestLogger(t)) - - err := auth.Login(context.Background()) - require.Error(t, err) - assert.Contains(t, err.Error(), "denied") - - // On denial nothing must be written to the cookie jar. - cookie, _ := store.Retrieve() - assert.Nil(t, cookie) + cases := []struct { + reason string + want string + }{ + {"denied", "denied at the identity provider"}, + {"no_role", "none of your identity provider groups map to a node role"}, + {"expired", "expired before it was approved"}, + {"", "was not completed"}, + {"something-new", "was not completed"}, + } + for _, tc := range cases { + t.Run(tc.reason, func(t *testing.T) { + t.Parallel() + node := &mockNode{oidcEnabled: true, pollsPending: 1, denyAfter: true, denyReason: tc.reason} + srv := httptest.NewServer(node.handler(t)) + defer srv.Close() + + store := &cmd.MemoryCookieStore{} + var out bytes.Buffer + auth := cmd.NewOIDCDeviceCookieAuthenticator(newClientOpts(t, srv), store, &out, logger.TestLogger(t)) + + err := auth.Login(context.Background()) + require.Error(t, err) + assert.Contains(t, err.Error(), tc.want) + assert.NotContains(t, err.Error(), "node text", "CLI must not print the node's message") + + // On denial nothing must be written to the cookie jar. + cookie, _ := store.Retrieve() + assert.Nil(t, cookie) + }) + } } diff --git a/core/logger/audit/audit_types.go b/core/logger/audit/audit_types.go index 80e9ef985fb..c8cbba33403 100644 --- a/core/logger/audit/audit_types.go +++ b/core/logger/audit/audit_types.go @@ -8,6 +8,7 @@ const ( AuthLoginFailedPassword EventID = "AUTH_LOGIN_FAILED_PASSWORD" AuthLoginFailed2FA EventID = "AUTH_LOGIN_FAILED_2FA" AuthLoginFailedDevice EventID = "AUTH_LOGIN_FAILED_DEVICE" + AuthLoginFailedOIDC EventID = "AUTH_LOGIN_FAILED_OIDC" AuthLoginSuccessWith2FA EventID = "AUTH_LOGIN_SUCCESS_WITH_2FA" AuthLoginSuccessNo2FA EventID = "AUTH_LOGIN_SUCCESS_NO_2FA" Auth2FAEnrolled EventID = "AUTH_2FA_ENROLLED" diff --git a/core/sessions/oidcauth/device_flow.go b/core/sessions/oidcauth/device_flow.go index ac0ad26d464..1683a4f16bc 100644 --- a/core/sessions/oidcauth/device_flow.go +++ b/core/sessions/oidcauth/device_flow.go @@ -201,10 +201,12 @@ type DevicePollRequest struct { } // DevicePollResponse reports flow status to the CLI. Status is one of -// "pending", "complete", or "denied". On "complete" the session cookie is set -// on the response; the body carries no token material. +// "pending", "complete", or "denied". On "denied" after a finished flow, +// Reason is one of the deviceReasonMessages keys. On "complete" the session +// cookie is set on the response; the body carries no token material. type DevicePollResponse struct { Status string `json:"status"` + Reason string `json:"reason,omitempty"` Message string `json:"message,omitempty"` } @@ -443,7 +445,12 @@ func (oi *oidcAuthenticator) handleDevicePoll(c *gin.Context) { if flowErr != nil { // Terminal failure already consumed the handle; no session to clean up // unless a prior success path left one (should not happen). - c.JSON(http.StatusOK, DevicePollResponse{Status: "denied", Message: "Authorization was not completed"}) + reason := flowErr.Error() + msg, ok := deviceReasonMessages[reason] + if !ok { + reason, msg = "failed", deviceReasonMessages["failed"] + } + c.JSON(http.StatusOK, DevicePollResponse{Status: "denied", Reason: reason, Message: msg}) return } diff --git a/core/sessions/oidcauth/login_guards.go b/core/sessions/oidcauth/login_guards.go index e6b09f82b22..0d34e834827 100644 --- a/core/sessions/oidcauth/login_guards.go +++ b/core/sessions/oidcauth/login_guards.go @@ -1,6 +1,7 @@ package oidcauth import ( + "errors" "net" "net/url" "slices" @@ -12,6 +13,20 @@ import ( const maxDeviceFlowLifetime = 5 * time.Minute +// deviceReasonNoRole is the failure reason for a verified identity whose +// groups map to no node role. +const deviceReasonNoRole = "no_role" + +// deviceReasonMessages are the operator-facing texts for each device-flow +// failure reason. The CLI keeps its own copy and never prints node text. +var deviceReasonMessages = map[string]string{ + deviceReasonNoRole: "Signed in, but none of your identity provider groups map to a node role", + "denied": "Authorization was denied at the identity provider", + "expired": "Authorization expired before it was approved", + "abandoned": "Authorization was abandoned", + "failed": "Authorization was not completed", +} + // capDeviceExpiry bounds a provider expiry. A missing expiry, or one longer // than maxDeviceFlowLifetime, is shortened. An already-past expiry is left // past so the caller can fail the flow instead of extending it. @@ -101,6 +116,9 @@ func deviceFailureReason(err error) string { if err == nil { return "" } + if errors.Is(err, errNoMatchingRole) { + return deviceReasonNoRole + } if errorsIsDeadline(err) { return "expired" } @@ -117,21 +135,6 @@ func deviceFailureReason(err error) string { } } -func unexpectedGroup(claims []string, allowed ...string) string { - allow := make(map[string]struct{}, len(allowed)) - for _, name := range allowed { - if name != "" { - allow[name] = struct{}{} - } - } - for _, claim := range claims { - if _, ok := allow[claim]; !ok { - return claim - } - } - return "" -} - func errorsIsDeadline(err error) bool { return err != nil && (strings.Contains(err.Error(), "context deadline exceeded") || strings.Contains(err.Error(), "context canceled")) } diff --git a/core/sessions/oidcauth/login_guards_test.go b/core/sessions/oidcauth/login_guards_test.go index acb08b2edd0..384bf4653c9 100644 --- a/core/sessions/oidcauth/login_guards_test.go +++ b/core/sessions/oidcauth/login_guards_test.go @@ -1,6 +1,7 @@ package oidcauth import ( + "fmt" "net/http" "net/http/httptest" "testing" @@ -57,15 +58,6 @@ func TestDeviceClientIP(t *testing.T) { assert.Equal(t, "203.0.113.7", deviceClientIP(linkLocal)) } -func TestUnexpectedGroup(t *testing.T) { - t.Parallel() - allowed := []string{AdminClaim, EditorClaim, RunnerClaim, ReadClaim} - assert.Empty(t, unexpectedGroup([]string{AdminClaim, EditorClaim}, allowed...)) - assert.Equal(t, "Contractors", unexpectedGroup([]string{AdminClaim, "Contractors"}, allowed...)) - assert.Empty(t, unexpectedGroup(nil, allowed...)) - assert.Equal(t, "Contractors", unexpectedGroup([]string{"Contractors"}, allowed...)) -} - func TestDeviceFailureReason(t *testing.T) { t.Parallel() require.Empty(t, deviceFailureReason(nil)) @@ -73,6 +65,10 @@ func TestDeviceFailureReason(t *testing.T) { assert.Equal(t, "denied", deviceFailureReason(stringError("access_denied"))) assert.Equal(t, "abandoned", deviceFailureReason(errDeviceFlowAbandoned)) assert.Equal(t, "expired", deviceFailureReason(stringError("context deadline exceeded"))) + assert.Equal(t, deviceReasonNoRole, deviceFailureReason(fmt.Errorf("%w: %w", errNoMatchingRole, ErrUserNoOIDCGroups))) + for _, reason := range []string{deviceReasonNoRole, "denied", "expired", "abandoned", "failed"} { + assert.NotEmpty(t, deviceReasonMessages[reason], reason) + } } type stringError string diff --git a/core/sessions/oidcauth/oidc.go b/core/sessions/oidcauth/oidc.go index 04567867940..c317938ec45 100644 --- a/core/sessions/oidcauth/oidc.go +++ b/core/sessions/oidcauth/oidc.go @@ -325,10 +325,6 @@ func (oi *oidcAuthenticator) issueSessionFromIDToken(ctx context.Context, rawIDT if err != nil { return "", "", "", err } - if extra := unexpectedGroup(idClaims, oi.config.AdminClaim(), oi.config.EditClaim(), oi.config.RunClaim(), oi.config.ReadClaim()); extra != "" { - oi.auditLogger.Audit(audit.AuthLoginFailed2FA, map[string]any{"email": email, "reason": "unexpected_group", "group": extra}) - return "", "", "", fmt.Errorf("%w: groups claim is not limited to the configured role groups", errNoMatchingRole) - } oi.lggr.Tracef("Received and validated ID claims: %v\n", idClaims) role, err := oi.IDClaimsToUserRole( @@ -341,7 +337,7 @@ func (oi *oidcAuthenticator) issueSessionFromIDToken(ctx context.Context, rawIDT if err != nil { // Audit the full claim set so an over-broad or unexpected group grant is // detectable after the fact. - oi.auditLogger.Audit(audit.AuthLoginFailed2FA, map[string]any{"email": email, "groups": idClaims}) + oi.auditLogger.Audit(audit.AuthLoginFailedOIDC, map[string]any{"email": email, "reason": deviceReasonNoRole, "groups": idClaims}) return "", "", "", fmt.Errorf("%w: %w", errNoMatchingRole, err) } diff --git a/core/sessions/oidcauth/verify_flow_test.go b/core/sessions/oidcauth/verify_flow_test.go index 318e5e07a38..1a1481720ab 100644 --- a/core/sessions/oidcauth/verify_flow_test.go +++ b/core/sessions/oidcauth/verify_flow_test.go @@ -9,6 +9,7 @@ import ( "github.com/stretchr/testify/require" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest" + clsessions "github.com/smartcontractkit/chainlink/v2/core/sessions" ) const testClientID = "test-client-id" @@ -72,20 +73,21 @@ func TestIssueSessionFromIDToken_Expired(t *testing.T) { assert.Equal(t, 0, countOIDCSessions(t, oi, "expired-user@example.com")) } -// TestIssueSessionFromIDToken_UnexpectedGroup rejects a token that carries a -// configured role group plus any other group. The login fails closed. -func TestIssueSessionFromIDToken_UnexpectedGroup(t *testing.T) { +// TestIssueSessionFromIDToken_ExtraGroups accepts a token that carries a +// configured role group alongside groups the node does not know. Real IdP +// users belong to many groups; only the configured ones pick the role. +func TestIssueSessionFromIDToken_ExtraGroups(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) idp := newMockIDP(t, testClientID) idp.email = "extra-group@example.com" - idp.groups = []string{AdminClaim, "Contractors"} + idp.groups = []string{"Contractors", RunnerClaim, "Everyone"} oi := newAuthenticatorForIDP(t, idp, db) - _, _, _, err := oi.issueSessionFromIDToken(t.Context(), idp.signIDToken(t), "") - require.ErrorIs(t, err, errNoMatchingRole) - assert.Contains(t, err.Error(), "not limited") - assert.Equal(t, 0, countOIDCSessions(t, oi, "extra-group@example.com")) + _, _, role, err := oi.issueSessionFromIDToken(t.Context(), idp.signIDToken(t), "") + require.NoError(t, err) + assert.Equal(t, clsessions.UserRoleRun, role) + assert.Equal(t, 1, countOIDCSessions(t, oi, "extra-group@example.com")) } // TestIssueSessionFromIDToken_NoMatchingGroup asserts a validly signed token From 3a9d5fd30c4a42208fe78bfcc9efe7195953060d Mon Sep 17 00:00:00 2001 From: Harry Anderson Date: Fri, 13 Nov 2026 02:01:25 +0000 Subject: [PATCH 15/18] feat(oidc): redact authorization code and state in request logs At debug level the request logger printed the OIDC code and state from the /signin query and the /oidc-exchange body. Add both keys to the redaction list, next to device_handle. --- .changeset/oidc-cli-device-flow.md | 2 +- core/web/router.go | 3 +++ core/web/router_redact_internal_test.go | 35 +++++++++++++++++++++++++ 3 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 core/web/router_redact_internal_test.go diff --git a/.changeset/oidc-cli-device-flow.md b/.changeset/oidc-cli-device-flow.md index 58da2587809..2badebd9e40 100644 --- a/.changeset/oidc-cli-device-flow.md +++ b/.changeset/oidc-cli-device-flow.md @@ -6,4 +6,4 @@ #changed The OIDC authorization-code (operator UI) flow now always uses PKCE (RFC 7636). The OIDC `ClientSecret` is now optional: confidential clients still send it, while public clients (required for the device flow) rely on PKCE instead. Existing confidential-client deployments are unaffected. -#changed Hardened OIDC device and auth-code flows: dedicated pre-auth rate limits and per-IP concurrency caps on device endpoints, server-side PKCE verifier and OIDC nonce (the session cookie holds only the anti-CSRF state), email claim validation, orphan-session cleanup if cookie bind fails, and a stricter CLI `/oidc-enabled` probe. Browser login state and device-flow results are stored in Postgres so any replica can finish a login. The provider device code stays on the replica that started the flow and is not written to the database. Device-flow lifetime is capped at five minutes. A verification URI whose host does not match the configured provider is rejected. When the socket peer is a private proxy, device-flow rate limits use the rightmost X-Forwarded-For address; a public peer is used as-is. Denied device flows are audited. Groups the node does not know are ignored; the highest configured role group picks the role. A denied device login tells the CLI why, including when none of the user's groups map to a node role. OIDC API tokens cannot be created or used. The CLI refuses device login when TLS verification is disabled. +#changed Hardened OIDC device and auth-code flows: dedicated pre-auth rate limits and per-IP concurrency caps on device endpoints, server-side PKCE verifier and OIDC nonce (the session cookie holds only the anti-CSRF state), email claim validation, orphan-session cleanup if cookie bind fails, and a stricter CLI `/oidc-enabled` probe. Browser login state and device-flow results are stored in Postgres so any replica can finish a login. The provider device code stays on the replica that started the flow and is not written to the database. Device-flow lifetime is capped at five minutes. A verification URI whose host does not match the configured provider is rejected. When the socket peer is a private proxy, device-flow rate limits use the rightmost X-Forwarded-For address; a public peer is used as-is. Denied device flows are audited. Groups the node does not know are ignored; the highest configured role group picks the role. A denied device login tells the CLI why, including when none of the user's groups map to a node role. OIDC API tokens cannot be created or used. The CLI refuses device login when TLS verification is disabled. Debug request logs redact the OIDC authorization code and state. diff --git a/core/web/router.go b/core/web/router.go index d8a641b0c51..0e7f494f942 100644 --- a/core/web/router.go +++ b/core/web/router.go @@ -647,6 +647,9 @@ var blacklist = map[string]struct{}{ "current_password": {}, "new_account_password": {}, "device_handle": {}, + // OIDC authorization code and state, sent to /signin and /oidc-exchange. + "code": {}, + "state": {}, } func isBlacklisted(k string) bool { diff --git a/core/web/router_redact_internal_test.go b/core/web/router_redact_internal_test.go new file mode 100644 index 00000000000..f42d958b1f5 --- /dev/null +++ b/core/web/router_redact_internal_test.go @@ -0,0 +1,35 @@ +package web + +import ( + "bytes" + "net/url" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestRequestLogRedactsOIDCSecrets(t *testing.T) { + t.Parallel() + + t.Run("signin query", func(t *testing.T) { + t.Parallel() + q, err := url.ParseQuery("code=secret-code&state=secret-state&other=kept") + require.NoError(t, err) + out := redact(q) + assert.NotContains(t, out, "secret-code") + assert.NotContains(t, out, "secret-state") + assert.Contains(t, out, "other=kept") + }) + + t.Run("exchange body", func(t *testing.T) { + t.Parallel() + body := bytes.NewBufferString(`{"code":"secret-code","state":"secret-state","device_handle":"secret-handle","other":"kept"}`) + out, err := readSanitizedJSON(body) + require.NoError(t, err) + assert.NotContains(t, out, "secret-code") + assert.NotContains(t, out, "secret-state") + assert.NotContains(t, out, "secret-handle") + assert.Contains(t, out, `"other":"kept"`) + }) +} From f08c4c5d35e208cf11b161653cdfac7b1690f2c7 Mon Sep 17 00:00:00 2001 From: Harry Anderson Date: Sat, 14 Nov 2026 03:59:06 +0000 Subject: [PATCH 16/18] feat(oidc): limit device login to allowed networks and trusted proxies Device login now needs WebServer.OIDC.DeviceFlowAllowedCIDRs. Empty turns it off and requests from outside the list get 403 before any rate limiter, database write or IdP call. The node no longer forwards verification_uri_complete, so the operator always types the user code. X-Forwarded-For is believed only from WebServer.OIDC.TrustedProxyCIDRs, walked from the right. A catch-all prefix is rejected. Rate limits and per-client caps count per IPv4 address or IPv6 /64. A device flow the CLI stops polling for max(30s, 3 intervals) frees its slot, stops polling the IdP, and drops any session it minted. /oidc-login gets its own limiter and caps pending rows at 50 per client and 10,000 total. New AUTH_DEVICE_FLOW_STARTED event with client IP, User-Agent and a handle fingerprint. Success and failure events carry the same fingerprint and start IP; success adds the redeeming IP and client_ip_mismatch. The CLI refuses device login unless the node URL is https (http only for loopback) and refuses a verification URI that is not https. --- .changeset/oidc-cli-device-flow.md | 14 +- core/cmd/oidc_device_auth.go | 78 ++++-- core/cmd/oidc_device_auth_test.go | 79 +++++- core/config/docs/core.toml | 9 + core/config/toml/types.go | 36 +++ core/config/web_config.go | 2 + core/logger/audit/audit_types.go | 1 + core/services/chainlink/config_test.go | 8 +- core/services/chainlink/config_web_server.go | 14 + .../testdata/config-empty-effective.toml | 2 + .../chainlink/testdata/config-full.toml | 2 + .../config-multi-chain-effective.toml | 2 + core/sessions/oidcauth/device_flow.go | 251 ++++++++++++++---- core/sessions/oidcauth/device_flow_test.go | 33 ++- core/sessions/oidcauth/device_http_test.go | 228 ++++++++++++++++ core/sessions/oidcauth/helpers_test.go | 8 + core/sessions/oidcauth/login_guards.go | 136 +++++++--- core/sessions/oidcauth/login_guards_test.go | 132 ++++++++- core/sessions/oidcauth/login_state_store.go | 182 +++++++++---- .../oidcauth/login_state_store_test.go | 168 ++++++++++-- core/sessions/oidcauth/mock_idp_test.go | 19 +- core/sessions/oidcauth/oidc.go | 71 ++++- core/sessions/oidcauth/verify_flow_test.go | 4 +- .../migrations/0310_oidc_login_state.sql | 15 +- .../testdata/config-empty-effective.toml | 2 + core/web/resolver/testdata/config-full.toml | 2 + .../config-multi-chain-effective.toml | 2 + docs/CONFIG.md | 19 ++ .../scripts/config/merge_raw_configs.txtar | 2 + testdata/scripts/node/validate/default.txtar | 2 + .../node/validate/defaults-override.txtar | 2 + .../disk-based-logging-disabled.txtar | 2 + .../validate/disk-based-logging-no-dir.txtar | 2 + .../node/validate/disk-based-logging.txtar | 2 + .../node/validate/fallback-override.txtar | 2 + .../node/validate/invalid-ocr-p2p.txtar | 2 + testdata/scripts/node/validate/invalid.txtar | 2 + testdata/scripts/node/validate/valid.txtar | 2 + testdata/scripts/node/validate/warnings.txtar | 2 + 39 files changed, 1320 insertions(+), 221 deletions(-) create mode 100644 core/sessions/oidcauth/device_http_test.go diff --git a/.changeset/oidc-cli-device-flow.md b/.changeset/oidc-cli-device-flow.md index 2badebd9e40..533a7f89eaf 100644 --- a/.changeset/oidc-cli-device-flow.md +++ b/.changeset/oidc-cli-device-flow.md @@ -6,4 +6,16 @@ #changed The OIDC authorization-code (operator UI) flow now always uses PKCE (RFC 7636). The OIDC `ClientSecret` is now optional: confidential clients still send it, while public clients (required for the device flow) rely on PKCE instead. Existing confidential-client deployments are unaffected. -#changed Hardened OIDC device and auth-code flows: dedicated pre-auth rate limits and per-IP concurrency caps on device endpoints, server-side PKCE verifier and OIDC nonce (the session cookie holds only the anti-CSRF state), email claim validation, orphan-session cleanup if cookie bind fails, and a stricter CLI `/oidc-enabled` probe. Browser login state and device-flow results are stored in Postgres so any replica can finish a login. The provider device code stays on the replica that started the flow and is not written to the database. Device-flow lifetime is capped at five minutes. A verification URI whose host does not match the configured provider is rejected. When the socket peer is a private proxy, device-flow rate limits use the rightmost X-Forwarded-For address; a public peer is used as-is. Denied device flows are audited. Groups the node does not know are ignored; the highest configured role group picks the role. A denied device login tells the CLI why, including when none of the user's groups map to a node role. OIDC API tokens cannot be created or used. The CLI refuses device login when TLS verification is disabled. Debug request logs redact the OIDC authorization code and state. +#changed Hardened OIDC device and auth-code flows: server-side PKCE verifier and OIDC nonce (the session cookie holds only the anti-CSRF state), email claim validation, orphan-session cleanup if cookie bind fails, and a stricter CLI `/oidc-enabled` probe. Browser login state and device-flow results are stored in Postgres so any replica can finish a login. The provider device code stays on the replica that started the flow and is not written to the database. Device-flow lifetime is capped at five minutes. A verification URI whose host does not match the configured provider is rejected. Groups the node does not know are ignored; the highest configured role group picks the role. A denied device login tells the CLI why, including when none of the user's groups map to a node role. OIDC API tokens cannot be created or used. Debug request logs redact the OIDC authorization code and state. + +#added `WebServer.OIDC.DeviceFlowAllowedCIDRs` lists the client networks (for example the operator VPN or bastion range) that may use the CLI device login. It defaults to empty, which turns the device login off; requests from outside the list get 403. Browser login is not affected. + +#added `WebServer.OIDC.TrustedProxyCIDRs` lists the load balancers and proxies in front of the node. The OIDC login routes believe `X-Forwarded-For` only from these hops and take the first address outside them as the client. It defaults to empty, which uses the socket peer and ignores the header. + +#changed The node no longer passes the identity provider's `verification_uri_complete` to the CLI, and the CLI no longer prints a pre-filled approval link. The operator types the user code at the identity provider, which removes the one-click approval a forwarded link would allow. + +#changed The CLI refuses device login unless `--remote-node-url` uses https (plain http only for localhost) and TLS verification is on, and refuses to show a verification URI that is not https. Note the CLI does not check the verification URI host itself; the node checks it against the configured provider. + +#changed Device-flow abuse limits: dedicated pre-auth rate limits on `/oidc-device/start`, `/oidc-device/poll` and `/oidc-login`, keyed per IPv4 address or IPv6 /64. A device flow the CLI stops polling for 30 seconds (or three poll intervals, if longer) releases its slot and stops polling the identity provider. `/oidc-login` caps pending sign-ins at 50 per client and 10,000 in total, and answers 503 with `Retry-After` past either. + +#added `AUTH_DEVICE_FLOW_STARTED` audit event with the client IP, User-Agent and a handle fingerprint. Device-flow success and failure events carry the same fingerprint and the starting client IP; success also records the redeeming IP and `client_ip_mismatch` when the two differ. diff --git a/core/cmd/oidc_device_auth.go b/core/cmd/oidc_device_auth.go index 9dd98a6e488..a9faec63be8 100644 --- a/core/cmd/oidc_device_auth.go +++ b/core/cmd/oidc_device_auth.go @@ -6,7 +6,10 @@ import ( "encoding/json" "fmt" "io" + "net" "net/http" + "net/url" + "strings" "time" "github.com/pkg/errors" @@ -25,14 +28,15 @@ import ( // never holds any token; it receives only an opaque handle and, on success, the // same session cookie the browser flow produces. -// oidcDeviceStartResponse mirrors oidcauth.DeviceStartResponse. +// oidcDeviceStartResponse mirrors oidcauth.DeviceStartResponse. There is no +// verification_uri_complete: the operator always types the code, and a +// pre-filled link from an older node is ignored. type oidcDeviceStartResponse struct { - DeviceHandle string `json:"device_handle"` - UserCode string `json:"user_code"` - VerificationURI string `json:"verification_uri"` - VerificationURIComplete string `json:"verification_uri_complete,omitempty"` - ExpiresIn int64 `json:"expires_in"` - Interval int64 `json:"interval"` + DeviceHandle string `json:"device_handle"` + UserCode string `json:"user_code"` + VerificationURI string `json:"verification_uri"` + ExpiresIn int64 `json:"expires_in"` + Interval int64 `json:"interval"` } // oidcDevicePollResponse mirrors oidcauth.DevicePollResponse. @@ -114,10 +118,19 @@ func (o *OIDCDeviceCookieAuthenticator) Login(ctx context.Context) error { if o.config.InsecureSkipVerify { return errors.New("device login requires TLS verification; do not set insecure-skip-verify") } + if !secureOrLoopback(&o.config.RemoteNodeURL) { + return errors.New("device login requires an https remote-node-url (plain http is allowed only for localhost)") + } start, err := o.start(ctx) if err != nil { return err } + if !secureOrLoopbackString(start.VerificationURI) { + return errors.New("node returned a verification URI that is not https; refusing to show it") + } + if start.UserCode == "" { + return errors.New("node returned no user code") + } o.promptUser(start) @@ -169,7 +182,10 @@ func (o *OIDCDeviceCookieAuthenticator) start(ctx context.Context) (*oidcDeviceS return nil, err } defer resp.Body.Close() - body, _ := io.ReadAll(resp.Body) + body, _ := io.ReadAll(io.LimitReader(resp.Body, maxDeviceResponseBytes)) + if resp.StatusCode == http.StatusForbidden { + return nil, errors.New("this node does not allow device login from your network; connect through the operator VPN or bastion, or log in with a credentials file (-f)") + } if resp.StatusCode != http.StatusOK { return nil, errors.Errorf("failed to start device authorization (status %d): %s", resp.StatusCode, string(body)) } @@ -201,7 +217,7 @@ func (o *OIDCDeviceCookieAuthenticator) poll(ctx context.Context, handle string) } defer resp.Body.Close() - body, _ := io.ReadAll(resp.Body) + body, _ := io.ReadAll(io.LimitReader(resp.Body, maxDeviceResponseBytes)) if resp.StatusCode == http.StatusNotFound { return nil, "denied", "unknown", nil } @@ -219,17 +235,41 @@ func (o *OIDCDeviceCookieAuthenticator) poll(ctx context.Context, handle string) } func (o *OIDCDeviceCookieAuthenticator) promptUser(start *oidcDeviceStartResponse) { - uri := start.VerificationURIComplete - if uri == "" { - uri = start.VerificationURI - } fmt.Fprintln(o.out, "To log in, open the following URL in a browser and sign in with your identity provider.") fmt.Fprintln(o.out, "Confirm the host is your identity provider before you approve. An approval you did not start is an attack.") - fmt.Fprintf(o.out, "\n %s\n\n", uri) - if start.VerificationURIComplete == "" { - fmt.Fprintf(o.out, "When prompted, enter the code: %s\n\n", start.UserCode) - } else { - fmt.Fprintf(o.out, "Verify the code shown matches: %s\n\n", start.UserCode) - } + fmt.Fprintf(o.out, "\n %s\n\n", start.VerificationURI) + fmt.Fprintf(o.out, "When prompted, enter the code: %s\n\n", start.UserCode) + fmt.Fprintln(o.out, "Never enter a code someone else sent you.") fmt.Fprintln(o.out, "Waiting for approval...") } + +// maxDeviceResponseBytes bounds what the CLI reads from a device endpoint. +const maxDeviceResponseBytes = 64 << 10 + +// secureOrLoopback reports whether u is https, or http to a loopback host. +func secureOrLoopback(u *url.URL) bool { + switch u.Scheme { + case "https": + return u.Hostname() != "" + case "http": + host := u.Hostname() + if strings.EqualFold(host, "localhost") { + return true + } + ip := net.ParseIP(host) + return ip != nil && ip.IsLoopback() + default: + return false + } +} + +func secureOrLoopbackString(raw string) bool { + if raw == "" { + return false + } + u, err := url.Parse(raw) + if err != nil { + return false + } + return secureOrLoopback(u) +} diff --git a/core/cmd/oidc_device_auth_test.go b/core/cmd/oidc_device_auth_test.go index d5cd204050f..74f714b7559 100644 --- a/core/cmd/oidc_device_auth_test.go +++ b/core/cmd/oidc_device_auth_test.go @@ -24,6 +24,10 @@ type mockNode struct { pollsPending int32 // number of "pending" polls to return before "complete" denyAfter bool // if true, return "denied" instead of completing denyReason string + // verificationURI overrides the URI the start endpoint returns. + verificationURI string + // startStatus, when set, is returned by the start endpoint instead of 200. + startStatus int } func (m *mockNode) handler(t *testing.T) http.Handler { @@ -40,11 +44,22 @@ func (m *mockNode) handler(t *testing.T) http.Handler { // assert (not require) inside handler goroutines: require calls Goexit // on the wrong goroutine. assert.Equal(t, http.MethodPost, r.Method) + if m.startStatus != 0 { + w.WriteHeader(m.startStatus) + _, _ = w.Write([]byte(`{"error":"node text"}`)) + return + } + uri := "https://sso.example.com/activate" + if m.verificationURI != "" { + uri = m.verificationURI + } + // An older node may still send verification_uri_complete. The CLI + // must ignore it. _ = json.NewEncoder(w).Encode(map[string]any{ "device_handle": "test-handle", "user_code": "WDJB-MJHT", - "verification_uri": "https://sso.example.com/activate", - "verification_uri_complete": "https://sso.example.com/activate?user_code=WDJB-MJHT", + "verification_uri": uri, + "verification_uri_complete": uri + "?user_code=WDJB-MJHT", "expires_in": 300, "interval": 1, }) @@ -128,6 +143,66 @@ func TestOIDCDeviceLogin_Success(t *testing.T) { assert.Contains(t, out.String(), "https://sso.example.com/activate") assert.Contains(t, out.String(), "WDJB-MJHT") assert.Contains(t, out.String(), "An approval you did not start is an attack.") + // The pre-filled one-click link must never be shown. + assert.NotContains(t, out.String(), "user_code=") + assert.Contains(t, out.String(), "When prompted, enter the code: WDJB-MJHT") +} + +func TestOIDCDeviceLogin_RefusesPlaintextNode(t *testing.T) { + t.Parallel() + for _, raw := range []string{"http://node.internal:6688", "http://10.0.0.5:6688", "ftp://node.internal", "https://"} { + t.Run(raw, func(t *testing.T) { + t.Parallel() + u, err := url.Parse(raw) + require.NoError(t, err) + auth := cmd.NewOIDCDeviceCookieAuthenticator(cmd.ClientOpts{RemoteNodeURL: *u}, &cmd.MemoryCookieStore{}, &bytes.Buffer{}, logger.TestLogger(t)) + err = auth.Login(context.Background()) + require.ErrorContains(t, err, "requires an https remote-node-url") + }) + } +} + +func TestOIDCDeviceLogin_AllowsLoopbackHTTP(t *testing.T) { + t.Parallel() + // httptest serves http://127.0.0.1, so the success test covers 127.0.0.1. + // localhost and [::1] are covered by rejecting at a later step instead of + // the scheme check. + for _, raw := range []string{"http://localhost:1", "http://[::1]:1"} { + u, err := url.Parse(raw) + require.NoError(t, err) + auth := cmd.NewOIDCDeviceCookieAuthenticator(cmd.ClientOpts{RemoteNodeURL: *u}, &cmd.MemoryCookieStore{}, &bytes.Buffer{}, logger.TestLogger(t)) + err = auth.Login(context.Background()) + require.Error(t, err) + assert.NotContains(t, err.Error(), "requires an https remote-node-url", raw) + } +} + +func TestOIDCDeviceLogin_RefusesPlaintextVerificationURI(t *testing.T) { + t.Parallel() + for _, uri := range []string{"http://sso.example.com/activate", "javascript:alert(1)", "sso.example.com/activate"} { + t.Run(uri, func(t *testing.T) { + t.Parallel() + node := &mockNode{oidcEnabled: true, verificationURI: uri} + srv := httptest.NewServer(node.handler(t)) + defer srv.Close() + var out bytes.Buffer + auth := cmd.NewOIDCDeviceCookieAuthenticator(newClientOpts(t, srv), &cmd.MemoryCookieStore{}, &out, logger.TestLogger(t)) + err := auth.Login(context.Background()) + require.ErrorContains(t, err, "verification URI that is not https") + assert.NotContains(t, out.String(), "sso.example.com", "a rejected URI must not be printed") + }) + } +} + +func TestOIDCDeviceLogin_NetworkRefused(t *testing.T) { + t.Parallel() + node := &mockNode{oidcEnabled: true, startStatus: http.StatusForbidden} + srv := httptest.NewServer(node.handler(t)) + defer srv.Close() + auth := cmd.NewOIDCDeviceCookieAuthenticator(newClientOpts(t, srv), &cmd.MemoryCookieStore{}, &bytes.Buffer{}, logger.TestLogger(t)) + err := auth.Login(context.Background()) + require.ErrorContains(t, err, "does not allow device login from your network") + assert.NotContains(t, err.Error(), "node text") } func TestOIDCDeviceLogin_RefusesInsecureSkipVerify(t *testing.T) { diff --git a/core/config/docs/core.toml b/core/config/docs/core.toml index 5273289460b..8619090b45b 100644 --- a/core/config/docs/core.toml +++ b/core/config/docs/core.toml @@ -231,6 +231,15 @@ SessionTimeout = '15m0s' # Default UserAPITokenEnabled = false # Default # UserAPITokenDuration is the duration of time an API token is active for before expiring UserAPITokenDuration = '240h0m0s' # Default +# DeviceFlowAllowedCIDRs lists the client networks, such as an operator VPN or bastion range, that may use the CLI device login +# (`/oidc-device/start` and `/oidc-device/poll`). Requests from any other address get 403. Empty turns the CLI device login off. +# Browser login is not affected. The client address is resolved through TrustedProxyCIDRs. +DeviceFlowAllowedCIDRs = [] # Default +# TrustedProxyCIDRs lists the proxies and load balancers in front of the node whose `X-Forwarded-For` entries the OIDC login +# routes believe. The node walks `X-Forwarded-For` from the right, skips entries inside these prefixes, and uses the first +# address outside them as the client. With the default empty list the socket peer is the client and the header is ignored. +# List only the proxy addresses: any host inside these ranges can claim any client address. A zero-length prefix is rejected. +TrustedProxyCIDRs = [] # Default # Optional LDAP config if WebServer.AuthenticationMethod is set to 'ldap' # LDAP queries are all parameterized to support custom LDAP 'dn', 'cn', and attributes diff --git a/core/config/toml/types.go b/core/config/toml/types.go index 53b2677f2e8..ad626762884 100644 --- a/core/config/toml/types.go +++ b/core/config/toml/types.go @@ -1247,12 +1247,36 @@ func (w *WebServer) ValidateConfig() (err error) { if w.OIDC.UserAPITokenDuration == commonconfig.MustNewDuration(0) { err = errors.Join(err, configutils.InvalidError{Name: "OIDC.UserAPITokenDuration", Msg: "OIDC UserAPITokenDuration can not be empty"}) } + err = errors.Join(err, validateCIDRList("OIDC.DeviceFlowAllowedCIDRs", w.OIDC.DeviceFlowAllowedCIDRs)) + err = errors.Join(err, validateCIDRList("OIDC.TrustedProxyCIDRs", w.OIDC.TrustedProxyCIDRs)) + if w.OIDC.TrustedProxyCIDRs != nil { + for i, v := range *w.OIDC.TrustedProxyCIDRs { + if _, n, perr := net.ParseCIDR(v); perr == nil { + if ones, _ := n.Mask.Size(); ones == 0 { + err = errors.Join(err, configutils.InvalidError{Name: fmt.Sprintf("OIDC.TrustedProxyCIDRs[%d]", i), Value: v, Msg: "trusts every address; list only the proxies in front of the node"}) + } + } + } + } return err } return err } +// validateCIDRList reports each entry of list that is not a CIDR prefix. +func validateCIDRList(name string, list *[]string) (err error) { + if list == nil { + return nil + } + for i, v := range *list { + if _, _, perr := net.ParseCIDR(v); perr != nil { + err = errors.Join(err, configutils.InvalidError{Name: fmt.Sprintf("%s[%d]", name, i), Value: v, Msg: "must be a CIDR prefix such as 10.0.0.0/8"}) + } + } + return err +} + type WebServerMFA struct { RPID *string RPOrigin *string @@ -1426,6 +1450,12 @@ type WebServerOIDC struct { SessionTimeout *commonconfig.Duration UserAPITokenEnabled *bool UserAPITokenDuration *commonconfig.Duration + // DeviceFlowAllowedCIDRs lists the client networks that may use the CLI + // device login. Empty turns the device login off. + DeviceFlowAllowedCIDRs *[]string + // TrustedProxyCIDRs lists the proxies whose X-Forwarded-For entries the + // OIDC login routes believe. + TrustedProxyCIDRs *[]string } func (w *WebServerOIDC) setFrom(f *WebServerOIDC) { @@ -1462,6 +1492,12 @@ func (w *WebServerOIDC) setFrom(f *WebServerOIDC) { if v := f.UserAPITokenDuration; v != nil { w.UserAPITokenDuration = v } + if v := f.DeviceFlowAllowedCIDRs; v != nil { + w.DeviceFlowAllowedCIDRs = v + } + if v := f.TrustedProxyCIDRs; v != nil { + w.TrustedProxyCIDRs = v + } } type WebServerOIDCSecrets struct { diff --git a/core/config/web_config.go b/core/config/web_config.go index 636e499b1e2..d577d8e6e36 100644 --- a/core/config/web_config.go +++ b/core/config/web_config.go @@ -68,6 +68,8 @@ type OIDC interface { SessionTimeout() commonconfig.Duration UserAPITokenEnabled() bool UserAPITokenDuration() commonconfig.Duration + DeviceFlowAllowedCIDRs() []string + TrustedProxyCIDRs() []string } type WebServer interface { diff --git a/core/logger/audit/audit_types.go b/core/logger/audit/audit_types.go index c8cbba33403..3f03e7136ca 100644 --- a/core/logger/audit/audit_types.go +++ b/core/logger/audit/audit_types.go @@ -9,6 +9,7 @@ const ( AuthLoginFailed2FA EventID = "AUTH_LOGIN_FAILED_2FA" AuthLoginFailedDevice EventID = "AUTH_LOGIN_FAILED_DEVICE" AuthLoginFailedOIDC EventID = "AUTH_LOGIN_FAILED_OIDC" + AuthDeviceFlowStarted EventID = "AUTH_DEVICE_FLOW_STARTED" AuthLoginSuccessWith2FA EventID = "AUTH_LOGIN_SUCCESS_WITH_2FA" AuthLoginSuccessNo2FA EventID = "AUTH_LOGIN_SUCCESS_NO_2FA" Auth2FAEnrolled EventID = "AUTH_2FA_ENROLLED" diff --git a/core/services/chainlink/config_test.go b/core/services/chainlink/config_test.go index e97a05898ff..2cfbe920c58 100644 --- a/core/services/chainlink/config_test.go +++ b/core/services/chainlink/config_test.go @@ -321,8 +321,10 @@ func TestConfig_Marshal(t *testing.T) { RunClaim: new("NodeRunners"), ReadClaim: new("NodeReadOnly"), SessionTimeout: commonconfig.MustNewDuration(15 * time.Minute), - UserAPITokenEnabled: new(false), - UserAPITokenDuration: commonconfig.MustNewDuration(240 * time.Hour), + UserAPITokenEnabled: new(false), + UserAPITokenDuration: commonconfig.MustNewDuration(240 * time.Hour), + DeviceFlowAllowedCIDRs: &[]string{"10.8.0.0/16"}, + TrustedProxyCIDRs: &[]string{"10.0.0.0/8"}, }, RateLimit: toml.WebServerRateLimit{ Authenticated: new(int64(42)), @@ -978,6 +980,8 @@ ReadClaim = 'NodeReadOnly' SessionTimeout = '15m0s' UserAPITokenEnabled = false UserAPITokenDuration = '240h0m0s' +DeviceFlowAllowedCIDRs = ['10.8.0.0/16'] +TrustedProxyCIDRs = ['10.0.0.0/8'] [WebServer.MFA] RPID = 'test-rpid' diff --git a/core/services/chainlink/config_web_server.go b/core/services/chainlink/config_web_server.go index 85e982d914b..d84182b6e40 100644 --- a/core/services/chainlink/config_web_server.go +++ b/core/services/chainlink/config_web_server.go @@ -227,6 +227,20 @@ func (l *ldapConfig) UserAPITokenDuration() commonconfig.Duration { return *l.c.UserAPITokenDuration } +func (l *oidcConfig) DeviceFlowAllowedCIDRs() []string { + if l.c.DeviceFlowAllowedCIDRs == nil { + return nil + } + return *l.c.DeviceFlowAllowedCIDRs +} + +func (l *oidcConfig) TrustedProxyCIDRs() []string { + if l.c.TrustedProxyCIDRs == nil { + return nil + } + return *l.c.TrustedProxyCIDRs +} + func (l *ldapConfig) BaseUserAttr() string { if l.c.BaseUserAttr == nil { return "" diff --git a/core/services/chainlink/testdata/config-empty-effective.toml b/core/services/chainlink/testdata/config-empty-effective.toml index 3e6fb0dd366..d1b02d4bc27 100644 --- a/core/services/chainlink/testdata/config-empty-effective.toml +++ b/core/services/chainlink/testdata/config-empty-effective.toml @@ -107,6 +107,8 @@ ReadClaim = 'NodeReadOnly' SessionTimeout = '15m0s' UserAPITokenEnabled = false UserAPITokenDuration = '240h0m0s' +DeviceFlowAllowedCIDRs = [] +TrustedProxyCIDRs = [] [WebServer.MFA] RPID = '' diff --git a/core/services/chainlink/testdata/config-full.toml b/core/services/chainlink/testdata/config-full.toml index 144b3c07271..e35ce84725f 100644 --- a/core/services/chainlink/testdata/config-full.toml +++ b/core/services/chainlink/testdata/config-full.toml @@ -113,6 +113,8 @@ ReadClaim = 'NodeReadOnly' SessionTimeout = '15m0s' UserAPITokenEnabled = false UserAPITokenDuration = '240h0m0s' +DeviceFlowAllowedCIDRs = ['10.8.0.0/16'] +TrustedProxyCIDRs = ['10.0.0.0/8'] [WebServer.MFA] RPID = 'test-rpid' diff --git a/core/services/chainlink/testdata/config-multi-chain-effective.toml b/core/services/chainlink/testdata/config-multi-chain-effective.toml index 98600eeaa73..2a8b7034ee4 100644 --- a/core/services/chainlink/testdata/config-multi-chain-effective.toml +++ b/core/services/chainlink/testdata/config-multi-chain-effective.toml @@ -107,6 +107,8 @@ ReadClaim = 'NodeReadOnly' SessionTimeout = '15m0s' UserAPITokenEnabled = false UserAPITokenDuration = '240h0m0s' +DeviceFlowAllowedCIDRs = [] +TrustedProxyCIDRs = [] [WebServer.MFA] RPID = '' diff --git a/core/sessions/oidcauth/device_flow.go b/core/sessions/oidcauth/device_flow.go index 1683a4f16bc..1b55cada841 100644 --- a/core/sessions/oidcauth/device_flow.go +++ b/core/sessions/oidcauth/device_flow.go @@ -17,7 +17,6 @@ import ( "github.com/ulule/limiter/v3/drivers/store/memory" "golang.org/x/oauth2" - "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink/v2/core/logger/audit" clsessions "github.com/smartcontractkit/chainlink/v2/core/sessions" webauth "github.com/smartcontractkit/chainlink/v2/core/web/auth" @@ -60,22 +59,43 @@ const ( deviceStartRatePeriod = 20 * time.Second devicePollRateLimit = 60 devicePollRatePeriod = time.Minute + + // Browser sign-in writes one oidc_pending_auth row per call. + signInRateLimit = 20 + signInRatePeriod = time.Minute + + // minDevicePollGrace is how long a flow may go unpolled before it stops + // holding a slot. The grace is the larger of this and three intervals. + minDevicePollGrace = 30 * time.Second + // deviceLiveCheckEvery is how often the provider poller checks that the + // CLI is still polling, so an abandoned flow stops calling the provider. + deviceLiveCheckEvery = 10 * time.Second ) var ( errTooManyDeviceFlows = errors.New("too many concurrent device authorization flows in progress") errTooManyDeviceFlowsPerIP = errors.New("too many concurrent device authorization flows from this address") errUnknownDeviceFlow = errors.New("unknown or expired device authorization flow") + errDeviceLoginDisabled = errors.New("device login is disabled on this node") + errDeviceLoginNetwork = errors.New("device login is not allowed from this network") errDeviceFlowAbandoned = errors.New("device authorization flow expired or abandoned before completion") ) +// devicePollGrace is how long a flow may go unpolled before it is dropped. +func devicePollGrace(interval int64) time.Duration { + return max(minDevicePollGrace, 3*time.Duration(interval)*time.Second) +} + // deviceFlowState is the per-flow state held server-side while a device // authorization is pending. Exactly one background goroutine writes the // terminal fields (sessionID/email/err/done); readers take the mutex. type deviceFlowState struct { mu sync.Mutex expiresAt time.Time - clientIP string + // clientIP is the address that started the flow, for audit. + clientIP string + // bucket is the rate-limit key the per-client cap counts. + bucket string done bool sessionID string email string @@ -116,17 +136,15 @@ func (s *deviceFlowStore) add(handle string, f *deviceFlowState) error { if len(s.flows) >= maxConcurrentDeviceFlows { return errTooManyDeviceFlows } - if f.clientIP != "" { - n := 0 - for _, existing := range s.flows { - if existing.clientIP == f.clientIP { - n++ - } - } - if n >= maxDeviceFlowsPerIP { - return errTooManyDeviceFlowsPerIP + n := 0 + for _, existing := range s.flows { + if existing.bucket == f.bucket { + n++ } } + if n >= maxDeviceFlowsPerIP { + return errTooManyDeviceFlowsPerIP + } s.flows[handle] = f return nil } @@ -185,14 +203,16 @@ func (oi *oidcAuthenticator) generateDeviceHandle() (string, error) { } // DeviceStartResponse is the CLI-facing payload that begins a device flow. -// It deliberately omits the provider device_code. +// It deliberately omits the provider device_code. It also omits the +// provider's verification_uri_complete: a link with the code already filled +// in turns a forwarded login into a one-click approval (RFC 8628 section +// 5.4), so the operator has to type or paste the user code. type DeviceStartResponse struct { - DeviceHandle string `json:"device_handle"` - UserCode string `json:"user_code"` - VerificationURI string `json:"verification_uri"` - VerificationURIComplete string `json:"verification_uri_complete,omitempty"` - ExpiresIn int64 `json:"expires_in"` - Interval int64 `json:"interval"` + DeviceHandle string `json:"device_handle"` + UserCode string `json:"user_code"` + VerificationURI string `json:"verification_uri"` + ExpiresIn int64 `json:"expires_in"` + Interval int64 `json:"interval"` } // DevicePollRequest is the CLI's request to check on a pending flow. @@ -210,25 +230,48 @@ type DevicePollResponse struct { Message string `json:"message,omitempty"` } -// deviceEndpointRateLimit builds a dedicated limiter for pre-auth device -// routes. The key is the operator address from deviceClientIP, not the socket -// peer, so a load balancer does not collapse every caller into one bucket. +// preAuthRateLimit builds a dedicated limiter for a pre-auth OIDC route. +// The key is the client bucket (IPv4 address or IPv6 /64) resolved through +// the trusted proxies, so a load balancer does not collapse every caller into +// one bucket and a forged X-Forwarded-For from an untrusted hop is ignored. // Nested under the outer api group so both limits apply. -func deviceEndpointRateLimit(period time.Duration, limit int64, lggr logger.Logger) gin.HandlerFunc { +func (oi *oidcAuthenticator) preAuthRateLimit(period time.Duration, limit int64) gin.HandlerFunc { store := memory.NewStore() rate := limiter.Rate{ Period: period, Limit: limit, } + key := func(c *gin.Context) string { return clientBucket(oi.clients.clientAddr(c)) } return mgin.NewMiddleware(limiter.New(store, rate), - mgin.WithKeyGetter(deviceClientIP), + mgin.WithKeyGetter(key), mgin.WithLimitReachedHandler(func(c *gin.Context) { - lggr.Warnf("device endpoint rate limit reached path=%s client=%s", c.FullPath(), deviceClientIP(c)) + oi.lggr.Warnf("OIDC pre-auth rate limit reached path=%s client=%s", c.FullPath(), key(c)) c.String(http.StatusTooManyRequests, "Limit exceeded") }), ) } +// deviceNetworkGuard refuses device-flow requests from outside +// DeviceFlowAllowedCIDRs. An empty list turns the device login off. Only CLI +// operators need these routes, and keeping them off the public internet is +// what stops a stranger from starting a flow to phish an approval. +func (oi *oidcAuthenticator) deviceNetworkGuard() gin.HandlerFunc { + return func(c *gin.Context) { + if len(oi.deviceAllowed) == 0 { + c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": errDeviceLoginDisabled.Error()}) + return + } + addr := oi.clients.clientAddr(c) + if !prefixesContain(oi.deviceAllowed, addr) { + // Debug, not Warn: anyone on the internet can trigger this. + oi.lggr.Debugf("refusing device login request from outside DeviceFlowAllowedCIDRs path=%s client=%s", c.FullPath(), addrString(addr)) + c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": errDeviceLoginNetwork.Error()}) + return + } + c.Next() + } +} + // handleDeviceStart begins a device authorization flow. Unauthenticated, like // the browser /oidc-login route: it only initiates the provider handshake. func (oi *oidcAuthenticator) handleDeviceStart(c *gin.Context) { @@ -242,14 +285,23 @@ func (oi *oidcAuthenticator) handleDeviceStart(c *gin.Context) { // Reserve a concurrency slot *before* calling the IdP so a refused flow // never produces outbound provider load, and so a flood cannot open more // IdP device codes than the store will accept. - clientIP := deviceClientIP(c) + addr := oi.clients.clientAddr(c) + clientIP := addrString(addr) + bucket := clientBucket(addr) provisional := time.Now().Add(maxDeviceFlowLifetime) state := &deviceFlowState{ expiresAt: provisional, clientIP: clientIP, + bucket: bucket, } - if addErr := reserveDeviceFlow(c.Request.Context(), oi.ds, handle, clientIP, provisional); addErr != nil { - oi.lggr.Warnf("refusing new device flow client=%s: %v", clientIP, addErr) + if addErr := reserveDeviceFlow(c.Request.Context(), oi.ds, deviceFlowReservation{ + handle: handle, + clientIP: clientIP, + ipBucket: bucket, + expiresAt: provisional, + pollGrace: minDevicePollGrace, + }); addErr != nil { + oi.lggr.Warnf("refusing new device flow client=%s: %v", bucket, addErr) if errors.Is(addErr, errTooManyDeviceFlows) || errors.Is(addErr, errTooManyDeviceFlowsPerIP) { c.JSON(http.StatusTooManyRequests, gin.H{"error": addErr.Error()}) return @@ -259,7 +311,7 @@ func (oi *oidcAuthenticator) handleDeviceStart(c *gin.Context) { } if addErr := oi.deviceFlows.add(handle, state); addErr != nil { _ = removeDeviceFlow(c.Request.Context(), oi.ds, handle) - oi.lggr.Warnf("refusing new device flow client=%s: %v", clientIP, addErr) + oi.lggr.Warnf("refusing new device flow client=%s: %v", bucket, addErr) c.JSON(http.StatusTooManyRequests, gin.H{"error": addErr.Error()}) return } @@ -282,49 +334,77 @@ func (oi *oidcAuthenticator) handleDeviceStart(c *gin.Context) { c.JSON(http.StatusBadGateway, gin.H{"error": "Failed to start device authorization"}) return } - if !verificationURIAllowed(oi.config.ProviderURL(), da.VerificationURI) || - (da.VerificationURIComplete != "" && !verificationURIAllowed(oi.config.ProviderURL(), da.VerificationURIComplete)) { + if !verificationURIAllowed(oi.config.ProviderURL(), da.VerificationURI) { _ = removeDeviceFlow(c.Request.Context(), oi.ds, handle) oi.deviceFlows.remove(handle) oi.lggr.Errorf("device authorization verification URI host does not match the configured provider") c.JSON(http.StatusBadGateway, gin.H{"error": "Failed to start device authorization"}) return } + interval := da.Interval + if interval == 0 { + interval = 5 // RFC 8628 default + } state.mu.Lock() state.expiresAt = expiry state.mu.Unlock() - if _, err := oi.ds.ExecContext(c.Request.Context(), `UPDATE oidc_device_flows SET expires_at = $2 WHERE handle = $1`, handle, expiry); err != nil { + if err := setDeviceFlowTiming(c.Request.Context(), oi.ds, handle, expiry, devicePollGrace(interval)); err != nil { oi.lggr.Errorf("failed to record device flow expiry: %v", err) } + oi.audit(audit.AuthDeviceFlowStarted, map[string]any{ + "method": "device_flow", + "handle_fp": handleFingerprint(handle), + "client_ip": clientIP, + "user_agent": truncateUserAgent(c.Request.UserAgent()), + "expires_in": int64(time.Until(expiry).Seconds()), + "remote_addr": c.Request.RemoteAddr, + }) + // Poll the provider in the background. DeviceAccessToken blocks until the // user approves, denies, or the code expires, internally respecting the - // provider's interval and slow_down. Bounded by the device-code expiry. + // provider's interval and slow_down. Bounded by the device-code expiry, + // and cut short if the CLI stops polling. go oi.pollDeviceToken(handle, state, da) - interval := da.Interval - if interval == 0 { - interval = 5 // RFC 8628 default - } c.JSON(http.StatusOK, DeviceStartResponse{ - DeviceHandle: handle, - UserCode: da.UserCode, - VerificationURI: da.VerificationURI, - VerificationURIComplete: da.VerificationURIComplete, - ExpiresIn: int64(time.Until(expiry).Seconds()), - Interval: interval, + DeviceHandle: handle, + UserCode: da.UserCode, + VerificationURI: da.VerificationURI, + ExpiresIn: int64(time.Until(expiry).Seconds()), + Interval: interval, }) } +// audit forwards to the audit logger when one is configured. +func (oi *oidcAuthenticator) audit(event audit.EventID, data map[string]any) { + if oi.auditLogger != nil { + oi.auditLogger.Audit(event, data) + } +} + // pollDeviceToken runs the blocking provider poll for one flow and records the // terminal result. On success it verifies the id_token and creates a session // through the same issueSessionFromIDToken path the browser flow uses. func (oi *oidcAuthenticator) pollDeviceToken(handle string, state *deviceFlowState, da *oauth2.DeviceAuthResponse) { - ctx, cancel := context.WithDeadline(context.Background(), state.expiresAt) + state.mu.Lock() + deadline := state.expiresAt + state.mu.Unlock() + ctx, cancel := context.WithDeadline(context.Background(), deadline) defer cancel() + // Free this replica's slot however the flow ends. + defer oi.deviceFlows.remove(handle) + + abandoned := make(chan struct{}) + go oi.watchDeviceFlow(ctx, handle, cancel, abandoned) token, err := oi.oauth2Config.DeviceAccessToken(ctx, da) if err != nil { + select { + case <-abandoned: + err = errDeviceFlowAbandoned + default: + } oi.finishDeviceFlow(state, handle, "", "", "", err) return } @@ -362,6 +442,45 @@ func (oi *oidcAuthenticator) pollDeviceToken(handle string, state *deviceFlowSta oi.finishDeviceFlow(state, handle, sessionID, email, role, nil) } +// watchDeviceFlow stops the provider poll once the flow is no longer live, +// usually because the CLI stopped polling. Without it an abandoned flow keeps +// calling the provider until the device code expires. A database error is +// not taken as abandonment, so a blip does not fail a real login. +func (oi *oidcAuthenticator) watchDeviceFlow(ctx context.Context, handle string, cancel context.CancelFunc, abandoned chan<- struct{}) { + every := oi.liveCheckEvery + if every <= 0 { + every = deviceLiveCheckEvery + } + ticker := time.NewTicker(every) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + live, err := oi.deviceHandleLiveErr(ctx, handle) + if err != nil { + if ctx.Err() == nil { + oi.lggr.Warnf("device flow live check failed: %v", err) + } + continue + } + if !live { + close(abandoned) + cancel() + return + } + } + } +} + +func (oi *oidcAuthenticator) deviceHandleLiveErr(ctx context.Context, handle string) (bool, error) { + if oi.ds != nil { + return deviceFlowLive(ctx, oi.ds, handle) + } + return oi.deviceFlows.contains(handle), nil +} + func (oi *oidcAuthenticator) deviceHandleLive(ctx context.Context, handle string) bool { if oi.ds != nil { live, err := deviceFlowLive(ctx, oi.ds, handle) @@ -385,15 +504,16 @@ func (oi *oidcAuthenticator) finishDeviceFlow(state *deviceFlowState, handle, se state.email = email state.role = role state.err = err + startIP := state.clientIP state.mu.Unlock() if err != nil { oi.lggr.Errorf("device authorization flow failed: %v", err) - if oi.auditLogger != nil { - oi.auditLogger.Audit(audit.AuthLoginFailedDevice, map[string]any{ - "method": "device_flow", - "reason": errText, - }) - } + oi.audit(audit.AuthLoginFailedDevice, map[string]any{ + "method": "device_flow", + "reason": errText, + "handle_fp": handleFingerprint(handle), + "start_client_ip": startIP, + }) } if oi.ds != nil && handle != "" { if werr := recordDeviceFlowResult(context.Background(), oi.ds, handle, sessionID, email, string(role), errText); werr != nil { @@ -426,26 +546,26 @@ func (oi *oidcAuthenticator) handleDevicePoll(c *gin.Context) { // Read the terminal result and consume the handle in one statement so two // polls, including polls on different replicas, cannot both be handed the // session cookie. - sessionID, email, role, terminal, known, flowErr, err := consumeDeviceFlow(c.Request.Context(), oi.ds, req.DeviceHandle) + res, err := consumeDeviceFlow(c.Request.Context(), oi.ds, req.DeviceHandle) if err != nil { oi.lggr.Errorf("device flow poll failed: %v", err) c.JSON(http.StatusInternalServerError, DevicePollResponse{Status: "denied", Message: "Failed to read device authorization"}) return } - if !known { + if !res.known { c.JSON(http.StatusNotFound, DevicePollResponse{Status: "denied", Message: errUnknownDeviceFlow.Error()}) return } - if !terminal { + if !res.terminal { c.JSON(http.StatusOK, DevicePollResponse{Status: "pending"}) return } - if flowErr != nil { + if res.flowErr != nil { // Terminal failure already consumed the handle; no session to clean up // unless a prior success path left one (should not happen). - reason := flowErr.Error() + reason := res.flowErr.Error() msg, ok := deviceReasonMessages[reason] if !ok { reason, msg = "failed", deviceReasonMessages["failed"] @@ -457,16 +577,33 @@ func (oi *oidcAuthenticator) handleDevicePoll(c *gin.Context) { // Bind the session ID to the CLI's cookie jar, exactly as the browser flow // does on a successful exchange. ginSession := sessions.Default(c) - ginSession.Set(webauth.SessionIDKey, sessionID) + ginSession.Set(webauth.SessionIDKey, res.sessionID) if err := ginSession.Save(); err != nil { // Handle is already consumed (single-winner). Delete the session row so // we do not leave a live unclaimable credential; the CLI must restart. oi.lggr.Errorf("failed to save device flow session: %v", err) - oi.deleteOIDCSession(context.Background(), sessionID) + oi.deleteOIDCSession(context.Background(), res.sessionID) c.JSON(http.StatusInternalServerError, DevicePollResponse{Status: "denied", Message: "Failed to establish session"}) return } - oi.auditLogger.Audit(audit.AuthLoginSuccessNo2FA, map[string]any{"email": email, "role": role, "method": "device_flow"}) + // A different address redeeming the flow than the one that started it is + // the signature of a forwarded or phished approval. It can also be an + // operator whose egress address changed, so flag it rather than refuse. + redeemIP := addrString(oi.clients.clientAddr(c)) + mismatch := redeemIP != res.startIP + if mismatch { + oi.lggr.Warnf("device flow redeemed from a different address than it was started from email=%s start=%s redeem=%s", res.email, res.startIP, redeemIP) + } + oi.audit(audit.AuthLoginSuccessNo2FA, map[string]any{ + "email": res.email, + "role": res.role, + "method": "device_flow", + "handle_fp": handleFingerprint(req.DeviceHandle), + "client_ip": redeemIP, + "start_client_ip": res.startIP, + "client_ip_mismatch": mismatch, + "user_agent": truncateUserAgent(c.Request.UserAgent()), + }) c.JSON(http.StatusOK, DevicePollResponse{Status: "complete"}) } diff --git a/core/sessions/oidcauth/device_flow_test.go b/core/sessions/oidcauth/device_flow_test.go index c5ad622cdae..886f6b911cd 100644 --- a/core/sessions/oidcauth/device_flow_test.go +++ b/core/sessions/oidcauth/device_flow_test.go @@ -77,10 +77,10 @@ func TestDeviceFlowStore_ConcurrencyCap(t *testing.T) { t.Parallel() s := newDeviceFlowStore() for i := range maxConcurrentDeviceFlows { - require.NoError(t, s.add(handleN(i), &deviceFlowState{expiresAt: time.Now().Add(time.Minute)})) + require.NoError(t, s.add(handleN(i), &deviceFlowState{expiresAt: time.Now().Add(time.Minute), bucket: handleN(i)})) } // One past the cap must be refused, not silently dropped. - err := s.add("overflow", &deviceFlowState{expiresAt: time.Now().Add(time.Minute)}) + err := s.add("overflow", &deviceFlowState{expiresAt: time.Now().Add(time.Minute), bucket: "fresh"}) require.ErrorIs(t, err, errTooManyDeviceFlows) } @@ -91,19 +91,19 @@ func TestDeviceFlowStore_PerIPCap(t *testing.T) { for i := range maxDeviceFlowsPerIP { require.NoError(t, s.add(handleN(i), &deviceFlowState{ expiresAt: time.Now().Add(time.Minute), - clientIP: ip, + bucket: ip, })) } err := s.add("overflow-ip", &deviceFlowState{ expiresAt: time.Now().Add(time.Minute), - clientIP: ip, + bucket: ip, }) require.ErrorIs(t, err, errTooManyDeviceFlowsPerIP) // A different IP can still open a flow. require.NoError(t, s.add("other-ip", &deviceFlowState{ expiresAt: time.Now().Add(time.Minute), - clientIP: "198.51.100.1", + bucket: "198.51.100.1", })) } @@ -222,6 +222,29 @@ func TestDeviceFlowState_ConcurrentAccess(t *testing.T) { wg.Wait() } +type cidrConfig struct { + *TestConfig + trusted []string +} + +func (c cidrConfig) TrustedProxyCIDRs() []string { return c.trusted } + +func TestValidateOIDCConfig_RejectsCatchAllProxy(t *testing.T) { + t.Parallel() + for _, v := range []string{"0.0.0.0/0", "::/0"} { + require.ErrorContains(t, validateOIDCConfig(cidrConfig{TestConfig: &TestConfig{}, trusted: []string{v}}), "trusts every address", v) + } + require.NoError(t, validateOIDCConfig(cidrConfig{TestConfig: &TestConfig{}, trusted: []string{"10.0.0.0/24"}})) + require.Error(t, validateOIDCConfig(cidrConfig{TestConfig: &TestConfig{}, trusted: []string{"10.0.0.1"}})) +} + +func TestDevicePollGrace(t *testing.T) { + t.Parallel() + assert.Equal(t, minDevicePollGrace, devicePollGrace(0)) + assert.Equal(t, minDevicePollGrace, devicePollGrace(5)) + assert.Equal(t, 60*time.Second, devicePollGrace(20)) +} + func handleN(i int) string { return "h-" + strconv.Itoa(i) } diff --git a/core/sessions/oidcauth/device_http_test.go b/core/sessions/oidcauth/device_http_test.go new file mode 100644 index 00000000000..aaf6ff1279a --- /dev/null +++ b/core/sessions/oidcauth/device_http_test.go @@ -0,0 +1,228 @@ +package oidcauth + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "sync" + "testing" + "time" + + "github.com/gin-contrib/sessions" + "github.com/gin-contrib/sessions/cookie" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest" + "github.com/smartcontractkit/chainlink/v2/core/logger/audit" +) + +// These tests drive the real routes from ExtendRouter against the mock IdP +// and a real database. + +type auditEvent struct { + id audit.EventID + data audit.Data +} + +// captureAudit records audit events. It embeds the no-op service for the +// services.Service half of audit.Logger. +type captureAudit struct { + audit.AuditLoggerService + mu sync.Mutex + events []auditEvent +} + +func (c *captureAudit) Audit(id audit.EventID, data audit.Data) { + c.mu.Lock() + defer c.mu.Unlock() + c.events = append(c.events, auditEvent{id: id, data: data}) +} + +func (c *captureAudit) find(id audit.EventID) (audit.Data, bool) { + c.mu.Lock() + defer c.mu.Unlock() + for _, e := range c.events { + if e.id == id { + return e.data, true + } + } + return nil, false +} + +// idpConfig points ProviderURL at the mock IdP so the node's verification URI +// host check passes. +type idpConfig struct { + *TestConfig + provider string +} + +func (c idpConfig) ProviderURL() string { return c.provider } + +type routerHarness struct { + t *testing.T + engine *gin.Engine + oi *oidcAuthenticator + idp *mockIDP + audit *captureAudit +} + +func newRouterHarness(t *testing.T) *routerHarness { + t.Helper() + db := pgtest.NewSqlxDB(t) + idp := newMockIDP(t, testClientID) + idp.email = "operator@example.com" + idp.groups = []string{EditorClaim} + oi := newAuthenticatorForIDP(t, idp, db) + capture := &captureAudit{} + oi.auditLogger = capture + oi.config = idpConfig{TestConfig: &TestConfig{}, provider: idp.server.URL} + // Operators on the VPN (10.8.0.0/16) behind one load balancer (10.0.0.0/24). + oi.deviceAllowed = mustCIDRs(t, "10.8.0.0/16") + oi.clients = clientResolver{trustedProxies: mustCIDRs(t, "10.0.0.0/24")} + + gin.SetMode(gin.TestMode) + engine := gin.New() + api := engine.Group("/", sessions.Sessions("clsession", cookie.NewStore([]byte("0123456789abcdef0123456789abcdef")))) + require.NoError(t, oi.ExtendRouter(api)) + return &routerHarness{t: t, engine: engine, oi: oi, idp: idp, audit: capture} +} + +// do sends a request as if it came through the load balancer for client. +func (h *routerHarness) do(method, path, client string, body any) *httptest.ResponseRecorder { + h.t.Helper() + var buf bytes.Buffer + if body != nil { + require.NoError(h.t, json.NewEncoder(&buf).Encode(body)) + } + req := httptest.NewRequestWithContext(h.t.Context(), method, path, &buf) + req.RemoteAddr = "10.0.0.2:40000" + req.Header.Set("X-Forwarded-For", client) + req.Header.Set("User-Agent", "chainlink-cli-test") + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + w := httptest.NewRecorder() + h.engine.ServeHTTP(w, req) + return w +} + +func (h *routerHarness) start(client string) DeviceStartResponse { + h.t.Helper() + w := h.do(http.MethodPost, "/oidc-device/start", client, nil) + require.Equal(h.t, http.StatusOK, w.Code, w.Body.String()) + assert.NotContains(h.t, w.Body.String(), "verification_uri_complete") + assert.NotContains(h.t, w.Body.String(), "user_code=") + var sr DeviceStartResponse + require.NoError(h.t, json.Unmarshal(w.Body.Bytes(), &sr)) + return sr +} + +func TestDeviceRoutes_OutsideAllowListRefused(t *testing.T) { + t.Parallel() + h := newRouterHarness(t) + + for _, path := range []string{"/oidc-device/start", "/oidc-device/poll"} { + w := h.do(http.MethodPost, path, "203.0.113.5", map[string]string{"device_handle": "x"}) + assert.Equal(t, http.StatusForbidden, w.Code, path) + } + // Nothing reached the identity provider or the database. + var n int + require.NoError(t, h.oi.ds.GetContext(t.Context(), &n, `SELECT count(*) FROM oidc_device_flows`)) + assert.Equal(t, 0, n) +} + +func TestDeviceRoutes_DisabledWhenAllowListEmpty(t *testing.T) { + t.Parallel() + h := newRouterHarness(t) + h.oi.deviceAllowed = nil + w := h.do(http.MethodPost, "/oidc-device/start", "10.8.1.1", nil) + assert.Equal(t, http.StatusForbidden, w.Code) + assert.Contains(t, w.Body.String(), "disabled") +} + +// TestDeviceRoutes_EndToEndAudit runs a full device login through the router +// and checks the audit trail can join start and redemption. +func TestDeviceRoutes_EndToEndAudit(t *testing.T) { + t.Parallel() + h := newRouterHarness(t) + + sr := h.start("10.8.1.1") + assert.Equal(t, "WDJB-MJHT", sr.UserCode) + assert.Equal(t, h.idp.server.URL+"/activate", sr.VerificationURI) + + started, ok := h.audit.find(audit.AuthDeviceFlowStarted) + require.True(t, ok, "start must be audited") + assert.Equal(t, "10.8.1.1", started["client_ip"]) + assert.Equal(t, "chainlink-cli-test", started["user_agent"]) + assert.Equal(t, handleFingerprint(sr.DeviceHandle), started["handle_fp"]) + assert.NotContains(t, started, "device_handle") + + // Redeem from a different VPN address, as a phished approval would. + var w *httptest.ResponseRecorder + require.Eventually(t, func() bool { + w = h.do(http.MethodPost, "/oidc-device/poll", "10.8.9.9", map[string]string{"device_handle": sr.DeviceHandle}) + return w.Code == http.StatusOK && bytes.Contains(w.Body.Bytes(), []byte(`"complete"`)) + }, 10*time.Second, 100*time.Millisecond) + assert.NotEmpty(t, w.Result().Cookies(), "the session cookie is set on completion") + + success, ok := h.audit.find(audit.AuthLoginSuccessNo2FA) + require.True(t, ok) + assert.Equal(t, "operator@example.com", success["email"]) + assert.Equal(t, started["handle_fp"], success["handle_fp"], "start and success join on the fingerprint") + assert.Equal(t, "10.8.1.1", success["start_client_ip"]) + assert.Equal(t, "10.8.9.9", success["client_ip"]) + assert.Equal(t, true, success["client_ip_mismatch"]) + + // Single use. + w = h.do(http.MethodPost, "/oidc-device/poll", "10.8.9.9", map[string]string{"device_handle": sr.DeviceHandle}) + assert.Equal(t, http.StatusNotFound, w.Code) +} + +// TestDeviceRoutes_AbandonedFlowStopsProviderPolling: a flow nobody polls +// gives up its slot and stops calling the identity provider. +func TestDeviceRoutes_AbandonedFlowStopsProviderPolling(t *testing.T) { + t.Parallel() + h := newRouterHarness(t) + h.oi.liveCheckEvery = 100 * time.Millisecond + h.idp.pending.Store(true) + + sr := h.start("10.8.1.1") + require.True(t, h.oi.deviceFlows.contains(sr.DeviceHandle)) + + // Simulate the poll grace running out. + _, err := h.oi.ds.ExecContext(t.Context(), `UPDATE oidc_device_flows SET poll_deadline = now() - interval '1 second' WHERE handle = $1`, sr.DeviceHandle) + require.NoError(t, err) + + require.Eventually(t, func() bool { return !h.oi.deviceFlows.contains(sr.DeviceHandle) }, 5*time.Second, 50*time.Millisecond, + "the poller must exit and free the replica slot") + failed, ok := h.audit.find(audit.AuthLoginFailedDevice) + require.True(t, ok) + assert.Equal(t, "abandoned", failed["reason"]) + assert.Equal(t, "10.8.1.1", failed["start_client_ip"]) + assert.Equal(t, handleFingerprint(sr.DeviceHandle), failed["handle_fp"]) + + calls := h.idp.tokenCalls.Load() + time.Sleep(1500 * time.Millisecond) + assert.Equal(t, calls, h.idp.tokenCalls.Load(), "no provider calls after abandonment") +} + +func TestSignInRoute_RateLimitedPerClient(t *testing.T) { + t.Parallel() + h := newRouterHarness(t) + for i := range signInRateLimit { + w := h.do(http.MethodGet, "/oidc-login", "198.51.100.7", nil) + require.Equal(t, http.StatusFound, w.Code, "request %d", i) + } + w := h.do(http.MethodGet, "/oidc-login", "198.51.100.7", nil) + assert.Equal(t, http.StatusTooManyRequests, w.Code) + // Another client is unaffected. + w = h.do(http.MethodGet, "/oidc-login", "198.51.100.8", nil) + assert.Equal(t, http.StatusFound, w.Code) + + var n int + require.NoError(t, h.oi.ds.GetContext(t.Context(), &n, `SELECT count(*) FROM oidc_pending_auth WHERE client_key = '198.51.100.7'`)) + assert.Equal(t, signInRateLimit, n, "refused sign-ins write nothing") +} diff --git a/core/sessions/oidcauth/helpers_test.go b/core/sessions/oidcauth/helpers_test.go index f5761aaa284..d82f49e62f9 100644 --- a/core/sessions/oidcauth/helpers_test.go +++ b/core/sessions/oidcauth/helpers_test.go @@ -132,3 +132,11 @@ func (t *TestConfig) UserAPITokenEnabled() bool { func (t *TestConfig) UserAPITokenDuration() commonconfig.Duration { return *commonconfig.MustNewDuration(24 * time.Hour) } + +func (t *TestConfig) DeviceFlowAllowedCIDRs() []string { + return []string{"127.0.0.0/8", "::1/128"} +} + +func (t *TestConfig) TrustedProxyCIDRs() []string { + return nil +} diff --git a/core/sessions/oidcauth/login_guards.go b/core/sessions/oidcauth/login_guards.go index 0d34e834827..8adb8bf90ad 100644 --- a/core/sessions/oidcauth/login_guards.go +++ b/core/sessions/oidcauth/login_guards.go @@ -1,8 +1,12 @@ package oidcauth import ( + "crypto/sha256" + "encoding/hex" "errors" + "fmt" "net" + "net/netip" "net/url" "slices" "strings" @@ -69,47 +73,119 @@ func verificationURIAllowed(providerURL, uri string) bool { return (ip != nil && ip.IsLoopback()) || parsed.Hostname() == "localhost" } -// deviceClientIP is the address the device-flow caps use. Behind a private -// load balancer the socket peer is the balancer, so the rightmost -// X-Forwarded-For entry is the address that balancer observed. A public peer -// is used as-is. The header is ignored in that case, because the caller can -// set it. -func deviceClientIP(c *gin.Context) string { - peer := remotePeer(c) - parsed := net.ParseIP(peer) - if parsed == nil || !trustedProxyPeer(parsed) { - if peer != "" { - return peer +// clientResolver works out the client address for the pre-authentication +// OIDC routes. X-Forwarded-For is believed only when the hop that sent it is +// inside trustedProxies. The header is walked from the right, each trusted +// hop is skipped, and the first address outside the trusted set is the +// client. With no trusted proxies the socket peer is the client. +type clientResolver struct { + trustedProxies []netip.Prefix +} + +// parseCIDRs parses config prefixes. Config validation already rejects bad +// entries, so an error here means the config bypassed validation. +func parseCIDRs(name string, list []string) ([]netip.Prefix, error) { + out := make([]netip.Prefix, 0, len(list)) + for _, v := range list { + p, err := netip.ParsePrefix(strings.TrimSpace(v)) + if err != nil { + return nil, fmt.Errorf("%s: invalid CIDR %q: %w", name, v, err) } - return c.ClientIP() + out = append(out, p.Masked()) } - xff := c.GetHeader("X-Forwarded-For") - if xff == "" { - return peer + return out, nil +} + +func prefixesContain(list []netip.Prefix, addr netip.Addr) bool { + if !addr.IsValid() { + return false } - parts := strings.Split(xff, ",") - for _, part := range slices.Backward(parts) { - ip := net.ParseIP(strings.TrimSpace(part)) - if ip != nil { - return ip.String() + return slices.ContainsFunc(list, func(p netip.Prefix) bool { return p.Contains(addr) }) +} + +// clientAddr returns the client address, or the zero Addr when it cannot be +// determined (unparseable peer, or a malformed entry in a trusted hop's +// X-Forwarded-For). Callers treat the zero Addr as untrusted. +func (r clientResolver) clientAddr(c *gin.Context) netip.Addr { + if c.Request == nil { + return netip.Addr{} + } + current := parseHostAddr(c.Request.RemoteAddr) + if !current.IsValid() || !prefixesContain(r.trustedProxies, current) { + return current + } + var entries []string + for _, line := range c.Request.Header.Values("X-Forwarded-For") { + entries = append(entries, strings.Split(line, ",")...) + } + for _, entry := range slices.Backward(entries) { + next := parseHostAddr(strings.TrimSpace(entry)) + if !next.IsValid() { + // A trusted hop passed on something that is not an address. Do not + // fall back to the proxy's own address: that would let any caller + // inherit the proxy's allow-list standing. + return netip.Addr{} + } + current = next + if !prefixesContain(r.trustedProxies, current) { + return current } } - return peer + // Every hop was a trusted proxy, so the leftmost one is the client. + return current } -func remotePeer(c *gin.Context) string { - if c.Request == nil { - return "" +// parseHostAddr accepts "ip", "ip:port" and "[ipv6]:port". +func parseHostAddr(s string) netip.Addr { + if s == "" { + return netip.Addr{} + } + if a, err := netip.ParseAddr(s); err == nil { + return a.Unmap().WithZone("") } - host, _, err := net.SplitHostPort(c.Request.RemoteAddr) - if err != nil { - return c.Request.RemoteAddr + if ap, err := netip.ParseAddrPort(s); err == nil { + return ap.Addr().Unmap().WithZone("") } - return host + return netip.Addr{} +} + +// clientBucket is the key the rate limiters and concurrency caps count +// against. IPv6 clients are grouped by /64, the smallest block an ISP or +// cloud normally hands out, so one allocation cannot mint fresh buckets. +// Unresolvable clients share one bucket. +func clientBucket(addr netip.Addr) string { + switch { + case !addr.IsValid(): + return "unknown" + case addr.Is4(): + return addr.String() + default: + return netip.PrefixFrom(addr, 64).Masked().String() + } +} + +func addrString(addr netip.Addr) string { + if !addr.IsValid() { + return "" + } + return addr.String() +} + +// handleFingerprint is a short, non-reversible id for a device handle so +// audit events for one flow can be joined without logging the handle. +func handleFingerprint(handle string) string { + sum := sha256.Sum256([]byte(handle)) + return hex.EncodeToString(sum[:8]) } -func trustedProxyPeer(ip net.IP) bool { - return ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() +// truncateUserAgent bounds an attacker-supplied header before it reaches the +// audit log. +func truncateUserAgent(ua string) string { + const maxUserAgent = 256 + if len(ua) > maxUserAgent { + return ua[:maxUserAgent] + } + return ua } func deviceFailureReason(err error) string { diff --git a/core/sessions/oidcauth/login_guards_test.go b/core/sessions/oidcauth/login_guards_test.go index 384bf4653c9..82004f1137c 100644 --- a/core/sessions/oidcauth/login_guards_test.go +++ b/core/sessions/oidcauth/login_guards_test.go @@ -2,14 +2,18 @@ package oidcauth import ( "fmt" + "net" "net/http" "net/http/httptest" + "net/netip" "testing" "time" "github.com/gin-gonic/gin" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/smartcontractkit/chainlink-common/pkg/logger" ) func TestCapDeviceExpiry(t *testing.T) { @@ -39,23 +43,129 @@ func TestVerificationURIAllowed(t *testing.T) { assert.False(t, verificationURIAllowed("http://10.0.0.1:8080", "http://10.0.0.1:8080/activate")) } -func TestDeviceClientIP(t *testing.T) { +func TestClientResolver_NoTrustedProxies(t *testing.T) { + t.Parallel() + r := clientResolver{} + + // With no trusted proxies the header is ignored, even from a private or + // loopback peer. This is the forgery Halborn showed behind an L4 hop. + for _, peer := range []string{"203.0.113.8:1234", "127.0.0.1:1234", "10.0.0.7:5555", "[fe80::1]:443"} { + c := deviceRequest(t, peer, "198.51.100.1, 203.0.113.9") + host, _, _ := net.SplitHostPort(peer) + assert.Equal(t, host, r.clientAddr(c).String(), peer) + } +} + +func TestClientResolver_TrustedProxies(t *testing.T) { t.Parallel() + r := clientResolver{trustedProxies: mustCIDRs(t, "10.0.0.0/8", "fd00::/8")} + + // One trusted hop: the rightmost entry is the client. + assert.Equal(t, "203.0.113.9", r.clientAddr(deviceRequest(t, "10.0.0.5:443", "198.51.100.1, 203.0.113.9")).String()) + + // Two trusted hops: skip the inner proxy and take the first untrusted entry. + assert.Equal(t, "203.0.113.9", r.clientAddr(deviceRequest(t, "10.0.0.5:443", "198.51.100.1, 203.0.113.9, 10.1.2.3")).String()) + + // Forging extra entries on the left changes nothing. + a := r.clientAddr(deviceRequest(t, "10.0.0.5:443", "203.0.113.1, 203.0.113.9")) + b := r.clientAddr(deviceRequest(t, "10.0.0.5:443", "203.0.113.2, 203.0.113.9")) + assert.Equal(t, a, b) - public := deviceRequest(t, "203.0.113.8:1234", "198.51.100.1, 203.0.113.9") - assert.Equal(t, "203.0.113.8", deviceClientIP(public)) + // A peer outside the trusted set is the client and its header is ignored. + assert.Equal(t, "198.51.100.9", r.clientAddr(deviceRequest(t, "198.51.100.9:1", "203.0.113.1")).String()) - loopback := deviceRequest(t, "127.0.0.1:1234", "198.51.100.1, 203.0.113.9") - assert.Equal(t, "203.0.113.9", deviceClientIP(loopback)) + // A private peer that is not a configured proxy is also not believed. + assert.Equal(t, "192.168.1.5", r.clientAddr(deviceRequest(t, "192.168.1.5:1", "203.0.113.1")).String()) - private := deviceRequest(t, "10.0.0.5:443", "203.0.113.4, not-an-ip") - assert.Equal(t, "203.0.113.4", deviceClientIP(private)) + // Trusted peer without a header: the peer is the client. + assert.Equal(t, "10.0.0.5", r.clientAddr(deviceRequest(t, "10.0.0.5:443", "")).String()) - noHeader := deviceRequest(t, "10.0.0.5:443", "") - assert.Equal(t, "10.0.0.5", deviceClientIP(noHeader)) + // Every hop trusted: the leftmost is the client. + assert.Equal(t, "10.9.9.9", r.clientAddr(deviceRequest(t, "10.0.0.5:443", "10.9.9.9, 10.1.1.1")).String()) + + // A malformed entry from a trusted hop resolves to no address, never to + // the proxy's own address. + assert.False(t, r.clientAddr(deviceRequest(t, "10.0.0.5:443", "203.0.113.4, not-an-ip")).IsValid()) + + // Several header lines are one list. + c := deviceRequest(t, "10.0.0.5:443", "198.51.100.1") + c.Request.Header.Add("X-Forwarded-For", "203.0.113.50") + assert.Equal(t, "203.0.113.50", r.clientAddr(c).String()) + + // ip:port entries and IPv4-mapped IPv6 normalize. + assert.Equal(t, "203.0.113.7", r.clientAddr(deviceRequest(t, "10.0.0.5:443", "203.0.113.7:5555")).String()) + assert.Equal(t, "203.0.113.7", r.clientAddr(deviceRequest(t, "[::ffff:10.0.0.5]:443", "::ffff:203.0.113.7")).String()) +} + +func TestClientBucket(t *testing.T) { + t.Parallel() + // Addresses in one IPv6 /64 share a bucket. + assert.Equal(t, clientBucket(netip.MustParseAddr("2001:db8::1")), clientBucket(netip.MustParseAddr("2001:db8::2"))) + assert.Equal(t, "2001:db8::/64", clientBucket(netip.MustParseAddr("2001:db8::ffff:1"))) + assert.NotEqual(t, clientBucket(netip.MustParseAddr("2001:db8:0:1::1")), clientBucket(netip.MustParseAddr("2001:db8:0:2::1"))) + // IPv4 stays per address. + assert.Equal(t, "203.0.113.1", clientBucket(netip.MustParseAddr("203.0.113.1"))) + assert.Equal(t, "unknown", clientBucket(netip.Addr{})) +} - linkLocal := deviceRequest(t, "[fe80::1]:443", "203.0.113.7") - assert.Equal(t, "203.0.113.7", deviceClientIP(linkLocal)) +func TestParseCIDRs(t *testing.T) { + t.Parallel() + got, err := parseCIDRs("x", []string{"10.1.2.3/8", " 2001:db8::/32 "}) + require.NoError(t, err) + assert.Equal(t, []netip.Prefix{netip.MustParsePrefix("10.0.0.0/8"), netip.MustParsePrefix("2001:db8::/32")}, got) + _, err = parseCIDRs("x", []string{"10.0.0.1"}) + require.Error(t, err) +} + +func TestHandleFingerprint(t *testing.T) { + t.Parallel() + fp := handleFingerprint("some-handle") + assert.Len(t, fp, 16) + assert.NotContains(t, fp, "some-handle") + assert.Equal(t, fp, handleFingerprint("some-handle")) + assert.NotEqual(t, fp, handleFingerprint("other-handle")) +} + +func TestDeviceNetworkGuard(t *testing.T) { + t.Parallel() + run := func(oi *oidcAuthenticator, remote, xff string) int { + w := httptest.NewRecorder() + _, eng := gin.CreateTestContext(w) + eng.POST("/oidc-device/start", oi.deviceNetworkGuard(), func(c *gin.Context) { c.Status(http.StatusOK) }) + req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/oidc-device/start", nil) + req.RemoteAddr = remote + if xff != "" { + req.Header.Set("X-Forwarded-For", xff) + } + eng.ServeHTTP(w, req) + return w.Code + } + lggr := logger.TestSugared(t) + + off := &oidcAuthenticator{lggr: lggr} + assert.Equal(t, http.StatusForbidden, run(off, "10.8.0.4:1", ""), "empty allow-list turns device login off") + + on := &oidcAuthenticator{ + lggr: lggr, + deviceAllowed: mustCIDRs(t, "10.8.0.0/16"), + clients: clientResolver{trustedProxies: mustCIDRs(t, "10.0.0.0/24")}, + } + assert.Equal(t, http.StatusOK, run(on, "10.8.0.4:1", "")) + assert.Equal(t, http.StatusForbidden, run(on, "203.0.113.5:1", "")) + // Through the trusted load balancer: the client decides. + assert.Equal(t, http.StatusOK, run(on, "10.0.0.2:1", "10.8.3.3")) + assert.Equal(t, http.StatusForbidden, run(on, "10.0.0.2:1", "203.0.113.5")) + // A public caller cannot claim to be inside by forging the header. + assert.Equal(t, http.StatusForbidden, run(on, "203.0.113.5:1", "10.8.3.3")) + // A malformed header from the trusted proxy is refused. + assert.Equal(t, http.StatusForbidden, run(on, "10.0.0.2:1", "garbage")) +} + +func mustCIDRs(t *testing.T, list ...string) []netip.Prefix { + t.Helper() + p, err := parseCIDRs("test", list) + require.NoError(t, err) + return p } func TestDeviceFailureReason(t *testing.T) { diff --git a/core/sessions/oidcauth/login_state_store.go b/core/sessions/oidcauth/login_state_store.go index 523cb315953..9987575ff66 100644 --- a/core/sessions/oidcauth/login_state_store.go +++ b/core/sessions/oidcauth/login_state_store.go @@ -14,19 +14,53 @@ import ( // replicas cannot both pass the count and both insert. const oidcDeviceFlowLock = 8628002 -func putPendingAuth(ctx context.Context, ds sqlutil.DataSource, state, verifier, nonce string, expiresAt time.Time) error { - if _, err := ds.ExecContext(ctx, `DELETE FROM oidc_pending_auth WHERE expires_at <= now()`); err != nil { +const ( + // maxPendingAuth bounds oidc_pending_auth so anonymous sign-in traffic + // cannot grow the table without limit. + maxPendingAuth = 10000 + // maxPendingAuthPerClient stops one client bucket from taking the whole + // table. One operator needs one row per sign-in attempt. + maxPendingAuthPerClient = 50 +) + +var ( + errTooManyPendingAuth = errors.New("too many sign-ins in progress") + errTooManyPendingAuthPerClient = errors.New("too many sign-ins in progress from this address") +) + +// putPendingAuth stores the PKCE verifier and nonce for one browser sign-in. +// The caps are soft across replicas: two concurrent inserts can each pass the +// count, which overshoots by at most the number of replicas. +func putPendingAuth(ctx context.Context, ds sqlutil.DataSource, state, verifier, nonce, clientKey string, expiresAt time.Time) error { + return sqlutil.TransactDataSource(ctx, ds, nil, func(tx sqlutil.DataSource) error { + if _, err := tx.ExecContext(ctx, `DELETE FROM oidc_pending_auth WHERE expires_at <= now()`); err != nil { + return err + } + var total int + if err := tx.GetContext(ctx, &total, `SELECT count(*) FROM oidc_pending_auth`); err != nil { + return err + } + if total >= maxPendingAuth { + return errTooManyPendingAuth + } + var perClient int + if err := tx.GetContext(ctx, &perClient, `SELECT count(*) FROM oidc_pending_auth WHERE client_key = $1`, clientKey); err != nil { + return err + } + if perClient >= maxPendingAuthPerClient { + return errTooManyPendingAuthPerClient + } + _, err := tx.ExecContext(ctx, ` + INSERT INTO oidc_pending_auth (state, verifier, nonce, client_key, expires_at) + VALUES ($1, $2, $3, $4, $5) + ON CONFLICT (state) DO UPDATE + SET verifier = EXCLUDED.verifier, + nonce = EXCLUDED.nonce, + client_key = EXCLUDED.client_key, + expires_at = EXCLUDED.expires_at`, + state, verifier, nonce, clientKey, expiresAt) return err - } - _, err := ds.ExecContext(ctx, ` - INSERT INTO oidc_pending_auth (state, verifier, nonce, expires_at) - VALUES ($1, $2, $3, $4) - ON CONFLICT (state) DO UPDATE - SET verifier = EXCLUDED.verifier, - nonce = EXCLUDED.nonce, - expires_at = EXCLUDED.expires_at`, - state, verifier, nonce, expiresAt) - return err + }) } func takePendingAuth(ctx context.Context, ds sqlutil.DataSource, state string) (verifier, nonce string, ok bool, err error) { @@ -47,12 +81,33 @@ func takePendingAuth(ctx context.Context, ds sqlutil.DataSource, state string) ( return row.Verifier, row.Nonce, true, nil } -func reserveDeviceFlow(ctx context.Context, ds sqlutil.DataSource, handle, clientIP string, expiresAt time.Time) error { +// deviceFlowReservation is the row written before the node calls the +// identity provider. +type deviceFlowReservation struct { + handle string + clientIP string + ipBucket string + expiresAt time.Time + pollGrace time.Duration +} + +// sweepDeviceFlows drops flows that expired or that nobody has polled within +// their grace period, and deletes any session such a flow minted but never +// handed out. +const sweepDeviceFlows = ` + WITH gone AS ( + DELETE FROM oidc_device_flows + WHERE expires_at <= now() OR poll_deadline <= now() + RETURNING session_id + ) + DELETE FROM oidc_sessions WHERE id IN (SELECT session_id FROM gone WHERE session_id <> '')` + +func reserveDeviceFlow(ctx context.Context, ds sqlutil.DataSource, r deviceFlowReservation) error { return sqlutil.TransactDataSource(ctx, ds, nil, func(tx sqlutil.DataSource) error { if _, err := tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock($1::bigint)`, int64(oidcDeviceFlowLock)); err != nil { return err } - if _, err := tx.ExecContext(ctx, `DELETE FROM oidc_device_flows WHERE expires_at <= now()`); err != nil { + if _, err := tx.ExecContext(ctx, sweepDeviceFlows); err != nil { return err } var total int @@ -62,27 +117,41 @@ func reserveDeviceFlow(ctx context.Context, ds sqlutil.DataSource, handle, clien if total >= maxConcurrentDeviceFlows { return errTooManyDeviceFlows } - if clientIP != "" { - var perIP int - if err := tx.GetContext(ctx, &perIP, `SELECT count(*) FROM oidc_device_flows WHERE client_ip = $1`, clientIP); err != nil { - return err - } - if perIP >= maxDeviceFlowsPerIP { - return errTooManyDeviceFlowsPerIP - } + var perBucket int + if err := tx.GetContext(ctx, &perBucket, `SELECT count(*) FROM oidc_device_flows WHERE ip_bucket = $1`, r.ipBucket); err != nil { + return err } + if perBucket >= maxDeviceFlowsPerIP { + return errTooManyDeviceFlowsPerIP + } + grace := int(r.pollGrace / time.Second) _, err := tx.ExecContext(ctx, ` - INSERT INTO oidc_device_flows (handle, client_ip, expires_at) - VALUES ($1, $2, $3)`, handle, clientIP, expiresAt) + INSERT INTO oidc_device_flows (handle, client_ip, ip_bucket, expires_at, poll_deadline, poll_grace_seconds) + VALUES ($1, $2, $3, $4, now() + make_interval(secs => $5::integer), $5::integer)`, + r.handle, r.clientIP, r.ipBucket, r.expiresAt, grace) return err }) } +// setDeviceFlowTiming records the provider expiry and the poll grace once the +// provider has answered. +func setDeviceFlowTiming(ctx context.Context, ds sqlutil.DataSource, handle string, expiresAt time.Time, pollGrace time.Duration) error { + grace := int(pollGrace / time.Second) + _, err := ds.ExecContext(ctx, ` + UPDATE oidc_device_flows + SET expires_at = $2, + poll_grace_seconds = $3::integer, + poll_deadline = now() + make_interval(secs => $3::integer) + WHERE handle = $1`, handle, expiresAt, grace) + return err +} + +// deviceFlowLive reports whether the flow is unexpired and still being polled. func deviceFlowLive(ctx context.Context, ds sqlutil.DataSource, handle string) (bool, error) { var n int err := ds.GetContext(ctx, &n, ` SELECT count(*) FROM oidc_device_flows - WHERE handle = $1 AND expires_at > now()`, handle) + WHERE handle = $1 AND expires_at > now() AND poll_deadline > now()`, handle) if err != nil { return false, err } @@ -102,42 +171,63 @@ func recordDeviceFlowResult(ctx context.Context, ds sqlutil.DataSource, handle, return err } +// deviceFlowResult is what a poll learns about a flow. +type deviceFlowResult struct { + known bool + terminal bool + sessionID string + email string + role clsessions.UserRole + flowErr error + // startIP is the client address that started the flow. + startIP string +} + // consumeDeviceFlow deletes a finished flow and returns it. A second caller -// sees unknown. A row that is not finished yet is left in place and reported -// as pending. -func consumeDeviceFlow(ctx context.Context, ds sqlutil.DataSource, handle string) (sessionID, email string, role clsessions.UserRole, terminal, known bool, flowErr error, err error) { +// sees unknown. A live row that is not finished yet has its poll deadline +// moved forward and is reported as pending. A row past its expiry or poll +// deadline is unknown. +func consumeDeviceFlow(ctx context.Context, ds sqlutil.DataSource, handle string) (deviceFlowResult, error) { var row struct { SessionID string `db:"session_id"` Email string Role string Err string - ExpiresAt time.Time `db:"expires_at"` + ClientIP string `db:"client_ip"` } - err = ds.GetContext(ctx, &row, ` + err := ds.GetContext(ctx, &row, ` DELETE FROM oidc_device_flows - WHERE handle = $1 AND done = true - RETURNING session_id, email, role, err, expires_at`, handle) + WHERE handle = $1 AND done = true AND expires_at > now() AND poll_deadline > now() + RETURNING session_id, email, role, err, client_ip`, handle) if err == nil { - if time.Now().After(row.ExpiresAt) { - return "", "", "", false, false, nil, nil + res := deviceFlowResult{ + known: true, + terminal: true, + sessionID: row.SessionID, + email: row.Email, + role: clsessions.UserRole(row.Role), + startIP: row.ClientIP, } - var storedErr error if row.Err != "" { - storedErr = errors.New(row.Err) + res.flowErr = errors.New(row.Err) } - return row.SessionID, row.Email, clsessions.UserRole(row.Role), true, true, storedErr, nil + return res, nil } if !errors.Is(err, sql.ErrNoRows) { - return "", "", "", false, false, nil, err + return deviceFlowResult{}, err } - var pending int - if err = ds.GetContext(ctx, &pending, ` - SELECT count(*) FROM oidc_device_flows - WHERE handle = $1 AND expires_at > now()`, handle); err != nil { - return "", "", "", false, false, nil, err + res, err := ds.ExecContext(ctx, ` + UPDATE oidc_device_flows + SET poll_deadline = now() + make_interval(secs => poll_grace_seconds) + WHERE handle = $1 AND expires_at > now() AND poll_deadline > now()`, handle) + // No done = false filter: if the poller finished between the DELETE and + // this UPDATE, the row is reported pending and the next poll takes it. + if err != nil { + return deviceFlowResult{}, err } - if pending == 1 { - return "", "", "", false, true, nil, nil + n, err := res.RowsAffected() + if err != nil { + return deviceFlowResult{}, err } - return "", "", "", false, false, nil, nil + return deviceFlowResult{known: n == 1}, nil } diff --git a/core/sessions/oidcauth/login_state_store_test.go b/core/sessions/oidcauth/login_state_store_test.go index 09100b61df0..d43c87c1b78 100644 --- a/core/sessions/oidcauth/login_state_store_test.go +++ b/core/sessions/oidcauth/login_state_store_test.go @@ -1,6 +1,7 @@ package oidcauth import ( + "strconv" "testing" "time" @@ -17,7 +18,7 @@ func TestPendingAuth_SharedRoundTrip(t *testing.T) { ctx := t.Context() exp := time.Now().Add(pendingAuthTTL) - require.NoError(t, putPendingAuth(ctx, db, "state-1", "verifier-1", "nonce-1", exp)) + require.NoError(t, putPendingAuth(ctx, db, "state-1", "verifier-1", "nonce-1", "203.0.113.1", exp)) verifier, nonce, ok, err := takePendingAuth(ctx, db, "state-1") require.NoError(t, err) @@ -29,12 +30,56 @@ func TestPendingAuth_SharedRoundTrip(t *testing.T) { require.NoError(t, err) assert.False(t, ok) - require.NoError(t, putPendingAuth(ctx, db, "state-expired", "verifier-2", "nonce-2", time.Now().Add(-time.Second))) + require.NoError(t, putPendingAuth(ctx, db, "state-expired", "verifier-2", "nonce-2", "203.0.113.1", time.Now().Add(-time.Second))) _, _, ok, err = takePendingAuth(ctx, db, "state-expired") require.NoError(t, err) assert.False(t, ok) } +func TestPendingAuth_PerClientCap(t *testing.T) { + t.Parallel() + db := pgtest.NewSqlxDB(t) + ctx := t.Context() + exp := time.Now().Add(pendingAuthTTL) + + for i := range maxPendingAuthPerClient { + require.NoError(t, putPendingAuth(ctx, db, "s-"+strconv.Itoa(i), "v", "n", "2001:db8::/64", exp)) + } + err := putPendingAuth(ctx, db, "s-overflow", "v", "n", "2001:db8::/64", exp) + require.ErrorIs(t, err, errTooManyPendingAuthPerClient) + require.NoError(t, putPendingAuth(ctx, db, "s-other", "v", "n", "203.0.113.1", exp)) + + // Taking a row frees its slot. + _, _, ok, err := takePendingAuth(ctx, db, "s-0") + require.NoError(t, err) + require.True(t, ok) + require.NoError(t, putPendingAuth(ctx, db, "s-overflow", "v", "n", "2001:db8::/64", exp)) +} + +func TestPendingAuth_GlobalCap(t *testing.T) { + t.Parallel() + db := pgtest.NewSqlxDB(t) + ctx := t.Context() + // Fill to the cap in one statement rather than 10k round trips. + _, err := db.ExecContext(ctx, ` + INSERT INTO oidc_pending_auth (state, verifier, nonce, client_key, expires_at) + SELECT 'bulk-' || g, 'v', 'n', 'k-' || (g % 1000), now() + interval '10 minutes' + FROM generate_series(1, $1) g`, maxPendingAuth) + require.NoError(t, err) + err = putPendingAuth(ctx, db, "one-more", "v", "n", "fresh-client", time.Now().Add(pendingAuthTTL)) + require.ErrorIs(t, err, errTooManyPendingAuth) +} + +func testReservation(handle, ip string, exp time.Time) deviceFlowReservation { + return deviceFlowReservation{ + handle: handle, + clientIP: ip, + ipBucket: clientBucket(parseHostAddr(ip)), + expiresAt: exp, + pollGrace: minDevicePollGrace, + } +} + func TestReserveDeviceFlow_PerIPCap(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) @@ -42,11 +87,81 @@ func TestReserveDeviceFlow_PerIPCap(t *testing.T) { exp := time.Now().Add(time.Minute) for i := range maxDeviceFlowsPerIP { - require.NoError(t, reserveDeviceFlow(ctx, db, handleN(i), "203.0.113.10", exp)) + require.NoError(t, reserveDeviceFlow(ctx, db, testReservation(handleN(i), "203.0.113.10", exp))) + } + err := reserveDeviceFlow(ctx, db, testReservation("overflow", "203.0.113.10", exp)) + require.ErrorIs(t, err, errTooManyDeviceFlowsPerIP) + require.NoError(t, reserveDeviceFlow(ctx, db, testReservation("other", "198.51.100.1", exp))) +} + +// TestReserveDeviceFlow_IPv6SharesSlash64 is the address-rotation case: every +// address in one /64 counts against the same five slots. +func TestReserveDeviceFlow_IPv6SharesSlash64(t *testing.T) { + t.Parallel() + db := pgtest.NewSqlxDB(t) + ctx := t.Context() + exp := time.Now().Add(time.Minute) + + for i := range maxDeviceFlowsPerIP { + require.NoError(t, reserveDeviceFlow(ctx, db, testReservation(handleN(i), "2001:db8::"+strconv.Itoa(i+1), exp))) } - err := reserveDeviceFlow(ctx, db, "overflow", "203.0.113.10", exp) + err := reserveDeviceFlow(ctx, db, testReservation("overflow", "2001:db8::ffff", exp)) require.ErrorIs(t, err, errTooManyDeviceFlowsPerIP) - require.NoError(t, reserveDeviceFlow(ctx, db, "other", "198.51.100.1", exp)) +} + +// TestReserveDeviceFlow_AbandonedReleaseSlot: flows nobody polls stop holding +// slots once their poll grace passes, so a start-and-walk-away flood cannot +// hold the pool for the full five minutes. +func TestReserveDeviceFlow_AbandonedReleaseSlot(t *testing.T) { + t.Parallel() + db := pgtest.NewSqlxDB(t) + ctx := t.Context() + exp := time.Now().Add(time.Minute) + + for i := range maxDeviceFlowsPerIP { + require.NoError(t, reserveDeviceFlow(ctx, db, testReservation(handleN(i), "203.0.113.20", exp))) + } + require.ErrorIs(t, reserveDeviceFlow(ctx, db, testReservation("blocked", "203.0.113.20", exp)), errTooManyDeviceFlowsPerIP) + + // Keep one flow alive by polling it, then age the others past the grace. + res, err := consumeDeviceFlow(ctx, db, handleN(0)) + require.NoError(t, err) + require.True(t, res.known) + _, err = db.ExecContext(ctx, `UPDATE oidc_device_flows SET poll_deadline = now() - interval '1 second' WHERE handle <> $1`, handleN(0)) + require.NoError(t, err) + + live, err := deviceFlowLive(ctx, db, handleN(1)) + require.NoError(t, err) + assert.False(t, live, "an unpolled flow is no longer live") + res, err = consumeDeviceFlow(ctx, db, handleN(1)) + require.NoError(t, err) + assert.False(t, res.known, "an unpolled flow cannot be redeemed") + + require.NoError(t, reserveDeviceFlow(ctx, db, testReservation("unblocked", "203.0.113.20", exp))) + live, err = deviceFlowLive(ctx, db, handleN(0)) + require.NoError(t, err) + assert.True(t, live, "a polled flow survives the sweep") +} + +// TestReserveDeviceFlow_SweepDeletesUnclaimedSession: a flow that finished +// but was never redeemed takes its minted session with it. +func TestReserveDeviceFlow_SweepDeletesUnclaimedSession(t *testing.T) { + t.Parallel() + db := pgtest.NewSqlxDB(t) + ctx := t.Context() + exp := time.Now().Add(time.Minute) + + require.NoError(t, reserveDeviceFlow(ctx, db, testReservation("orphan", "203.0.113.30", exp))) + _, err := db.ExecContext(ctx, `INSERT INTO oidc_sessions (id, user_email, user_role, created_at) VALUES ('orphan-sess', 'o@example.com', 'view', now())`) + require.NoError(t, err) + require.NoError(t, recordDeviceFlowResult(ctx, db, "orphan", "orphan-sess", "o@example.com", "view", "")) + _, err = db.ExecContext(ctx, `UPDATE oidc_device_flows SET poll_deadline = now() - interval '1 second' WHERE handle = 'orphan'`) + require.NoError(t, err) + + require.NoError(t, reserveDeviceFlow(ctx, db, testReservation("next", "203.0.113.31", exp))) + var n int + require.NoError(t, db.GetContext(ctx, &n, `SELECT count(*) FROM oidc_sessions WHERE id = 'orphan-sess'`)) + assert.Equal(t, 0, n) } func TestConsumeDeviceFlow_SingleWinner(t *testing.T) { @@ -54,34 +169,29 @@ func TestConsumeDeviceFlow_SingleWinner(t *testing.T) { db := pgtest.NewSqlxDB(t) ctx := t.Context() exp := time.Now().Add(time.Minute) - require.NoError(t, reserveDeviceFlow(ctx, db, "shared-handle", "203.0.113.9", exp)) - - var ( - sessionID, email string - role clsessions.UserRole - terminal, known bool - flowErr, err error - ) - sessionID, _, _, terminal, known, flowErr, err = consumeDeviceFlow(ctx, db, "shared-handle") + require.NoError(t, reserveDeviceFlow(ctx, db, testReservation("shared-handle", "203.0.113.9", exp))) + + res, err := consumeDeviceFlow(ctx, db, "shared-handle") require.NoError(t, err) - assert.False(t, terminal) - assert.True(t, known, "an unfinished flow stays pending") - assert.Empty(t, sessionID) - require.NoError(t, flowErr) + assert.False(t, res.terminal) + assert.True(t, res.known, "an unfinished flow stays pending") + assert.Empty(t, res.sessionID) + require.NoError(t, res.flowErr) require.NoError(t, recordDeviceFlowResult(ctx, db, "shared-handle", "sess-winner", "a@example.com", string(clsessions.UserRoleEdit), "")) - sessionID, email, role, terminal, known, flowErr, err = consumeDeviceFlow(ctx, db, "shared-handle") + res, err = consumeDeviceFlow(ctx, db, "shared-handle") require.NoError(t, err) - require.True(t, terminal) - require.True(t, known) - assert.Equal(t, "sess-winner", sessionID) - assert.Equal(t, "a@example.com", email) - assert.Equal(t, clsessions.UserRoleEdit, role) - require.NoError(t, flowErr) - - _, _, _, terminal, known, _, err = consumeDeviceFlow(ctx, db, "shared-handle") + require.True(t, res.terminal) + require.True(t, res.known) + assert.Equal(t, "sess-winner", res.sessionID) + assert.Equal(t, "a@example.com", res.email) + assert.Equal(t, clsessions.UserRoleEdit, res.role) + assert.Equal(t, "203.0.113.9", res.startIP) + require.NoError(t, res.flowErr) + + res, err = consumeDeviceFlow(ctx, db, "shared-handle") require.NoError(t, err) - assert.False(t, terminal) - assert.False(t, known, "a second poll must not observe the completed flow") + assert.False(t, res.terminal) + assert.False(t, res.known, "a second poll must not observe the completed flow") } diff --git a/core/sessions/oidcauth/mock_idp_test.go b/core/sessions/oidcauth/mock_idp_test.go index de9352c4dea..56cc9137c0e 100644 --- a/core/sessions/oidcauth/mock_idp_test.go +++ b/core/sessions/oidcauth/mock_idp_test.go @@ -7,6 +7,7 @@ import ( "encoding/json" "net/http" "net/http/httptest" + "sync/atomic" "testing" "time" @@ -38,6 +39,11 @@ type mockIDP struct { email string // email claim nonce string // optional "nonce" claim lifetime time.Duration // exp relative to now; negative => already expired + // pending makes the token endpoint answer authorization_pending, as if + // nobody has approved the device code yet. + pending atomic.Bool + // tokenCalls counts token endpoint hits. + tokenCalls atomic.Int32 clientID string } @@ -91,11 +97,20 @@ func newMockIDP(t *testing.T, clientID string) *mockIDP { "device_code": "test-device-code", "user_code": "WDJB-MJHT", "verification_uri": base + "/activate", - "expires_in": 300, - "interval": 1, + // The node must not pass this one-click link on. + "verification_uri_complete": base + "/activate?user_code=WDJB-MJHT", + "expires_in": 300, + "interval": 1, }) }) mux.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) { + m.tokenCalls.Add(1) + if m.pending.Load() { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + _, _ = w.Write([]byte(`{"error":"authorization_pending"}`)) + return + } idToken := m.signIDToken(t) w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(map[string]any{ diff --git a/core/sessions/oidcauth/oidc.go b/core/sessions/oidcauth/oidc.go index c317938ec45..6beb3b7f6a7 100644 --- a/core/sessions/oidcauth/oidc.go +++ b/core/sessions/oidcauth/oidc.go @@ -16,6 +16,7 @@ import ( "log" "net/http" "net/mail" + "net/netip" "slices" "strings" "time" @@ -52,6 +53,13 @@ type oidcAuthenticator struct { lggr logger.SugaredLogger auditLogger audit.Logger deviceFlows *deviceFlowStore + // clients resolves the client address on the pre-authentication routes. + clients clientResolver + // deviceAllowed lists the networks that may use the device login. Empty + // turns the device login off. + deviceAllowed []netip.Prefix + // liveCheckEvery overrides deviceLiveCheckEvery in tests. + liveCheckEvery time.Duration } // ExchangeTokenRequest represents the expected JSON payload from the frontend @@ -90,6 +98,18 @@ func validateOIDCConfig(oidcCfg config.OIDC) error { if oidcCfg.ClaimName() == "" { return errors.New("OIDC ClaimName config required") } + if _, err := parseCIDRs("DeviceFlowAllowedCIDRs", oidcCfg.DeviceFlowAllowedCIDRs()); err != nil { + return err + } + trusted, err := parseCIDRs("TrustedProxyCIDRs", oidcCfg.TrustedProxyCIDRs()) + if err != nil { + return err + } + for _, p := range trusted { + if p.Bits() == 0 { + return fmt.Errorf("TrustedProxyCIDRs: %s trusts every address, so any caller could choose its own client address", p) + } + } return nil } @@ -128,16 +148,25 @@ func NewOIDCAuthenticator( Scopes: []string{oidc.ScopeOpenID, "profile", "email", oidcCfg.ClaimName()}, } + // validateOIDCConfig has already parsed both lists. + deviceAllowed, _ := parseCIDRs("DeviceFlowAllowedCIDRs", oidcCfg.DeviceFlowAllowedCIDRs()) + trustedProxies, _ := parseCIDRs("TrustedProxyCIDRs", oidcCfg.TrustedProxyCIDRs()) + // Create Authenticator struct, with internal HTTP handlers oidcAuth := oidcAuthenticator{ - ds: ds, - config: oidcCfg, - provider: provider, - oidcConfig: oidcConfig, - oauth2Config: oauth2Config, - lggr: logger.Sugared(lggr).Named("OIDCAuthenticationProvider"), - auditLogger: auditLogger, - deviceFlows: newDeviceFlowStore(), + ds: ds, + config: oidcCfg, + provider: provider, + oidcConfig: oidcConfig, + oauth2Config: oauth2Config, + lggr: logger.Sugared(lggr).Named("OIDCAuthenticationProvider"), + auditLogger: auditLogger, + deviceFlows: newDeviceFlowStore(), + clients: clientResolver{trustedProxies: trustedProxies}, + deviceAllowed: deviceAllowed, + } + if len(deviceAllowed) == 0 { + oidcAuth.lggr.Infof("OIDC CLI device login is off: WebServer.OIDC.DeviceFlowAllowedCIDRs is empty") } // Browser login state and device-flow results live in Postgres, so any @@ -171,7 +200,14 @@ func (oi *oidcAuthenticator) handleSignIn(c *gin.Context) { state := oi.generateState() verifier := oauth2.GenerateVerifier() nonce := oi.generateState() - if err := putPendingAuth(c.Request.Context(), oi.ds, state, verifier, nonce, time.Now().Add(pendingAuthTTL)); err != nil { + bucket := clientBucket(oi.clients.clientAddr(c)) + if err := putPendingAuth(c.Request.Context(), oi.ds, state, verifier, nonce, bucket, time.Now().Add(pendingAuthTTL)); err != nil { + if errors.Is(err, errTooManyPendingAuth) || errors.Is(err, errTooManyPendingAuthPerClient) { + oi.lggr.Warnf("refusing sign-in client=%s: %v", bucket, err) + c.Header("Retry-After", "60") + c.JSON(http.StatusServiceUnavailable, gin.H{"error": "Too many sign-ins in progress, try again shortly"}) + return + } oi.lggr.Errorf("failed to store authorization state: %v", err) c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to start login"}) return @@ -698,19 +734,28 @@ func constantTimeEmailCompare(left, right string) bool { func (oi *oidcAuthenticator) ExtendRouter(api *gin.RouterGroup) error { api.GET("/oidc-enabled", oi.handleCheckEnabled) - api.GET("/oidc-login", oi.handleSignIn) + // Sign-in writes a pending-auth row, so it gets its own pre-auth limiter + // on top of the outer api limiter. + api.GET("/oidc-login", + oi.preAuthRateLimit(signInRatePeriod, signInRateLimit), + oi.handleSignIn, + ) api.POST("/oidc-exchange", oi.handleTokenExchange) // Device authorization grant for headless clients (the CLI). // Dedicated pre-auth rate limits: start is expensive (outbound IdP call + // background goroutine); poll is cheaper but still unauthenticated. - // These nest under the outer api rate limiter so both apply. + // These nest under the outer api rate limiter so both apply. The network + // allow-list runs first so callers outside it never reach the limiter, + // the database, or the identity provider. api.POST("/oidc-device/start", - deviceEndpointRateLimit(deviceStartRatePeriod, deviceStartRateLimit, oi.lggr), + oi.deviceNetworkGuard(), + oi.preAuthRateLimit(deviceStartRatePeriod, deviceStartRateLimit), oi.handleDeviceStart, ) api.POST("/oidc-device/poll", - deviceEndpointRateLimit(devicePollRatePeriod, devicePollRateLimit, oi.lggr), + oi.deviceNetworkGuard(), + oi.preAuthRateLimit(devicePollRatePeriod, devicePollRateLimit), oi.handleDevicePoll, ) diff --git a/core/sessions/oidcauth/verify_flow_test.go b/core/sessions/oidcauth/verify_flow_test.go index 1a1481720ab..9dacc9d9489 100644 --- a/core/sessions/oidcauth/verify_flow_test.go +++ b/core/sessions/oidcauth/verify_flow_test.go @@ -161,7 +161,7 @@ func TestDeviceFlow_EndToEnd(t *testing.T) { const handle = "e2e-handle" state := &deviceFlowState{expiresAt: time.Now().Add(time.Minute), clientIP: "127.0.0.1"} - require.NoError(t, reserveDeviceFlow(t.Context(), oi.ds, handle, state.clientIP, state.expiresAt)) + require.NoError(t, reserveDeviceFlow(t.Context(), oi.ds, testReservation(handle, state.clientIP, state.expiresAt))) require.NoError(t, oi.deviceFlows.add(handle, state)) oi.pollDeviceToken(handle, state, da) @@ -237,7 +237,7 @@ func TestDeviceFlow_WrongAudienceRejected(t *testing.T) { const handle = "e2e-handle-2" state := &deviceFlowState{expiresAt: time.Now().Add(time.Minute), clientIP: "127.0.0.1"} - require.NoError(t, reserveDeviceFlow(t.Context(), oi.ds, handle, state.clientIP, state.expiresAt)) + require.NoError(t, reserveDeviceFlow(t.Context(), oi.ds, testReservation(handle, state.clientIP, state.expiresAt))) require.NoError(t, oi.deviceFlows.add(handle, state)) oi.pollDeviceToken(handle, state, da) diff --git a/core/store/migrate/migrations/0310_oidc_login_state.sql b/core/store/migrate/migrations/0310_oidc_login_state.sql index 2609e42dbbe..d484c4ddfca 100644 --- a/core/store/migrate/migrations/0310_oidc_login_state.sql +++ b/core/store/migrate/migrations/0310_oidc_login_state.sql @@ -1,17 +1,28 @@ -- +goose Up -- Short-lived login state shared by every replica. The provider device code -- is not stored here. Only the opaque handle and the browser state key are. +-- client_key and ip_bucket are the rate-limit bucket for the caller (an IPv4 +-- address or an IPv6 /64), used by the per-client caps. CREATE TABLE IF NOT EXISTS oidc_pending_auth ( state text PRIMARY KEY, verifier text NOT NULL, nonce text NOT NULL, + client_key text NOT NULL DEFAULT '', expires_at timestamp WITH time zone NOT NULL ); +CREATE INDEX IF NOT EXISTS idx_oidc_pending_auth_client_key + ON oidc_pending_auth (client_key); + +-- poll_deadline moves forward each time the CLI polls. A flow nobody polls +-- for poll_grace_seconds stops counting against the caps and is dropped. CREATE TABLE IF NOT EXISTS oidc_device_flows ( handle text PRIMARY KEY, client_ip text NOT NULL DEFAULT '', + ip_bucket text NOT NULL DEFAULT '', expires_at timestamp WITH time zone NOT NULL, + poll_deadline timestamp WITH time zone NOT NULL, + poll_grace_seconds integer NOT NULL, done boolean NOT NULL DEFAULT false, session_id text NOT NULL DEFAULT '', email text NOT NULL DEFAULT '', @@ -19,8 +30,8 @@ CREATE TABLE IF NOT EXISTS oidc_device_flows ( err text NOT NULL DEFAULT '' ); -CREATE INDEX IF NOT EXISTS idx_oidc_device_flows_client_ip - ON oidc_device_flows (client_ip); +CREATE INDEX IF NOT EXISTS idx_oidc_device_flows_ip_bucket + ON oidc_device_flows (ip_bucket); -- +goose Down DROP TABLE IF EXISTS oidc_device_flows; diff --git a/core/web/resolver/testdata/config-empty-effective.toml b/core/web/resolver/testdata/config-empty-effective.toml index 3e6fb0dd366..d1b02d4bc27 100644 --- a/core/web/resolver/testdata/config-empty-effective.toml +++ b/core/web/resolver/testdata/config-empty-effective.toml @@ -107,6 +107,8 @@ ReadClaim = 'NodeReadOnly' SessionTimeout = '15m0s' UserAPITokenEnabled = false UserAPITokenDuration = '240h0m0s' +DeviceFlowAllowedCIDRs = [] +TrustedProxyCIDRs = [] [WebServer.MFA] RPID = '' diff --git a/core/web/resolver/testdata/config-full.toml b/core/web/resolver/testdata/config-full.toml index 8735192c3ca..3c8e2f4fc6a 100644 --- a/core/web/resolver/testdata/config-full.toml +++ b/core/web/resolver/testdata/config-full.toml @@ -113,6 +113,8 @@ ReadClaim = 'NodeReadOnly' SessionTimeout = '15m0s' UserAPITokenEnabled = false UserAPITokenDuration = '240h0m0s' +DeviceFlowAllowedCIDRs = ['10.8.0.0/16'] +TrustedProxyCIDRs = ['10.0.0.0/8'] [WebServer.MFA] RPID = 'test-rpid' diff --git a/core/web/resolver/testdata/config-multi-chain-effective.toml b/core/web/resolver/testdata/config-multi-chain-effective.toml index d031ee10283..90b8e9be65d 100644 --- a/core/web/resolver/testdata/config-multi-chain-effective.toml +++ b/core/web/resolver/testdata/config-multi-chain-effective.toml @@ -107,6 +107,8 @@ ReadClaim = 'NodeReadOnly' SessionTimeout = '15m0s' UserAPITokenEnabled = false UserAPITokenDuration = '240h0m0s' +DeviceFlowAllowedCIDRs = [] +TrustedProxyCIDRs = [] [WebServer.MFA] RPID = '' diff --git a/docs/CONFIG.md b/docs/CONFIG.md index 9c75807c44e..ca8cd7f172a 100644 --- a/docs/CONFIG.md +++ b/docs/CONFIG.md @@ -591,6 +591,8 @@ ReadClaim = 'NodeReadOnly' # Default SessionTimeout = '15m0s' # Default UserAPITokenEnabled = false # Default UserAPITokenDuration = '240h0m0s' # Default +DeviceFlowAllowedCIDRs = [] # Default +TrustedProxyCIDRs = [] # Default ``` Optional OIDC config if WebServer.AuthenticationMethod is set to 'oidc' @@ -660,6 +662,23 @@ UserAPITokenDuration = '240h0m0s' # Default ``` UserAPITokenDuration is the duration of time an API token is active for before expiring +### DeviceFlowAllowedCIDRs +```toml +DeviceFlowAllowedCIDRs = [] # Default +``` +DeviceFlowAllowedCIDRs lists the client networks, such as an operator VPN or bastion range, that may use the CLI device login +(`/oidc-device/start` and `/oidc-device/poll`). Requests from any other address get 403. Empty turns the CLI device login off. +Browser login is not affected. The client address is resolved through TrustedProxyCIDRs. + +### TrustedProxyCIDRs +```toml +TrustedProxyCIDRs = [] # Default +``` +TrustedProxyCIDRs lists the proxies and load balancers in front of the node whose `X-Forwarded-For` entries the OIDC login +routes believe. The node walks `X-Forwarded-For` from the right, skips entries inside these prefixes, and uses the first +address outside them as the client. With the default empty list the socket peer is the client and the header is ignored. +List only the proxy addresses: any host inside these ranges can claim any client address. A zero-length prefix is rejected. + ## WebServer.LDAP ```toml [WebServer.LDAP] diff --git a/testdata/scripts/config/merge_raw_configs.txtar b/testdata/scripts/config/merge_raw_configs.txtar index 1463970ca35..a9a20a822de 100644 --- a/testdata/scripts/config/merge_raw_configs.txtar +++ b/testdata/scripts/config/merge_raw_configs.txtar @@ -254,6 +254,8 @@ ReadClaim = 'NodeReadOnly' SessionTimeout = '15m0s' UserAPITokenEnabled = false UserAPITokenDuration = '240h0m0s' +DeviceFlowAllowedCIDRs = [] +TrustedProxyCIDRs = [] [WebServer.MFA] RPID = '' diff --git a/testdata/scripts/node/validate/default.txtar b/testdata/scripts/node/validate/default.txtar index e423ec523f9..fb7f946c865 100644 --- a/testdata/scripts/node/validate/default.txtar +++ b/testdata/scripts/node/validate/default.txtar @@ -119,6 +119,8 @@ ReadClaim = 'NodeReadOnly' SessionTimeout = '15m0s' UserAPITokenEnabled = false UserAPITokenDuration = '240h0m0s' +DeviceFlowAllowedCIDRs = [] +TrustedProxyCIDRs = [] [WebServer.MFA] RPID = '' diff --git a/testdata/scripts/node/validate/defaults-override.txtar b/testdata/scripts/node/validate/defaults-override.txtar index 20f3b565be0..d42c03a8cde 100644 --- a/testdata/scripts/node/validate/defaults-override.txtar +++ b/testdata/scripts/node/validate/defaults-override.txtar @@ -180,6 +180,8 @@ ReadClaim = 'NodeReadOnly' SessionTimeout = '15m0s' UserAPITokenEnabled = false UserAPITokenDuration = '240h0m0s' +DeviceFlowAllowedCIDRs = [] +TrustedProxyCIDRs = [] [WebServer.MFA] RPID = '' diff --git a/testdata/scripts/node/validate/disk-based-logging-disabled.txtar b/testdata/scripts/node/validate/disk-based-logging-disabled.txtar index 721d1701c82..579d023433d 100644 --- a/testdata/scripts/node/validate/disk-based-logging-disabled.txtar +++ b/testdata/scripts/node/validate/disk-based-logging-disabled.txtar @@ -163,6 +163,8 @@ ReadClaim = 'NodeReadOnly' SessionTimeout = '15m0s' UserAPITokenEnabled = false UserAPITokenDuration = '240h0m0s' +DeviceFlowAllowedCIDRs = [] +TrustedProxyCIDRs = [] [WebServer.MFA] RPID = '' diff --git a/testdata/scripts/node/validate/disk-based-logging-no-dir.txtar b/testdata/scripts/node/validate/disk-based-logging-no-dir.txtar index d5337a40c9a..a0490a46a9c 100644 --- a/testdata/scripts/node/validate/disk-based-logging-no-dir.txtar +++ b/testdata/scripts/node/validate/disk-based-logging-no-dir.txtar @@ -163,6 +163,8 @@ ReadClaim = 'NodeReadOnly' SessionTimeout = '15m0s' UserAPITokenEnabled = false UserAPITokenDuration = '240h0m0s' +DeviceFlowAllowedCIDRs = [] +TrustedProxyCIDRs = [] [WebServer.MFA] RPID = '' diff --git a/testdata/scripts/node/validate/disk-based-logging.txtar b/testdata/scripts/node/validate/disk-based-logging.txtar index 7ff4cbf59b5..1c3d8781b08 100644 --- a/testdata/scripts/node/validate/disk-based-logging.txtar +++ b/testdata/scripts/node/validate/disk-based-logging.txtar @@ -163,6 +163,8 @@ ReadClaim = 'NodeReadOnly' SessionTimeout = '15m0s' UserAPITokenEnabled = false UserAPITokenDuration = '240h0m0s' +DeviceFlowAllowedCIDRs = [] +TrustedProxyCIDRs = [] [WebServer.MFA] RPID = '' diff --git a/testdata/scripts/node/validate/fallback-override.txtar b/testdata/scripts/node/validate/fallback-override.txtar index e34c251e4de..18cd5995de0 100644 --- a/testdata/scripts/node/validate/fallback-override.txtar +++ b/testdata/scripts/node/validate/fallback-override.txtar @@ -262,6 +262,8 @@ ReadClaim = 'NodeReadOnly' SessionTimeout = '15m0s' UserAPITokenEnabled = false UserAPITokenDuration = '240h0m0s' +DeviceFlowAllowedCIDRs = [] +TrustedProxyCIDRs = [] [WebServer.MFA] RPID = '' diff --git a/testdata/scripts/node/validate/invalid-ocr-p2p.txtar b/testdata/scripts/node/validate/invalid-ocr-p2p.txtar index 3ed1117dd42..f1305d7c24e 100644 --- a/testdata/scripts/node/validate/invalid-ocr-p2p.txtar +++ b/testdata/scripts/node/validate/invalid-ocr-p2p.txtar @@ -148,6 +148,8 @@ ReadClaim = 'NodeReadOnly' SessionTimeout = '15m0s' UserAPITokenEnabled = false UserAPITokenDuration = '240h0m0s' +DeviceFlowAllowedCIDRs = [] +TrustedProxyCIDRs = [] [WebServer.MFA] RPID = '' diff --git a/testdata/scripts/node/validate/invalid.txtar b/testdata/scripts/node/validate/invalid.txtar index 1c27e505de9..e5a4042d1cc 100644 --- a/testdata/scripts/node/validate/invalid.txtar +++ b/testdata/scripts/node/validate/invalid.txtar @@ -159,6 +159,8 @@ ReadClaim = 'NodeReadOnly' SessionTimeout = '15m0s' UserAPITokenEnabled = false UserAPITokenDuration = '240h0m0s' +DeviceFlowAllowedCIDRs = [] +TrustedProxyCIDRs = [] [WebServer.MFA] RPID = '' diff --git a/testdata/scripts/node/validate/valid.txtar b/testdata/scripts/node/validate/valid.txtar index cfdb2cae79b..865dce0e389 100644 --- a/testdata/scripts/node/validate/valid.txtar +++ b/testdata/scripts/node/validate/valid.txtar @@ -160,6 +160,8 @@ ReadClaim = 'NodeReadOnly' SessionTimeout = '15m0s' UserAPITokenEnabled = false UserAPITokenDuration = '240h0m0s' +DeviceFlowAllowedCIDRs = [] +TrustedProxyCIDRs = [] [WebServer.MFA] RPID = '' diff --git a/testdata/scripts/node/validate/warnings.txtar b/testdata/scripts/node/validate/warnings.txtar index 9e15d037a5b..a5229f4e277 100644 --- a/testdata/scripts/node/validate/warnings.txtar +++ b/testdata/scripts/node/validate/warnings.txtar @@ -142,6 +142,8 @@ ReadClaim = 'NodeReadOnly' SessionTimeout = '15m0s' UserAPITokenEnabled = false UserAPITokenDuration = '240h0m0s' +DeviceFlowAllowedCIDRs = [] +TrustedProxyCIDRs = [] [WebServer.MFA] RPID = '' From 5ecd4c686811b27382f7df3ffa98ffdf68aa0573 Mon Sep 17 00:00:00 2001 From: Harry Anderson Date: Wed, 18 Nov 2026 21:11:26 +0000 Subject: [PATCH 17/18] feat(oidc): refuse forwarded device logins from unlisted proxies, group sign-in by IPv6 /48 A device login request that carries X-Forwarded-For, X-Real-IP or Forwarded from a peer outside TrustedProxyCIDRs now gets 403. Before, a node behind a load balancer that was left out of TrustedProxyCIDRs but sat inside DeviceFlowAllowedCIDRs let every caller behind it in, because each one resolved to the load balancer's address. The first refusal logs a Warn that names TrustedProxyCIDRs. The /oidc-login limiter and the oidc_pending_auth per-client cap now count an IPv6 client per /48 instead of per /64. One /56 held 256 buckets, enough for one subscriber to fill the 10,000-row cap and stop browser sign-in for everyone for 15 minutes. Device-flow routes keep /64 buckets. --- .changeset/oidc-cli-device-flow.md | 4 +- core/config/docs/core.toml | 4 +- core/sessions/oidcauth/device_flow.go | 21 ++++++++-- core/sessions/oidcauth/device_http_test.go | 18 +++++++++ core/sessions/oidcauth/login_guards.go | 39 +++++++++++++++++-- core/sessions/oidcauth/login_guards_test.go | 32 ++++++++++++++- core/sessions/oidcauth/oidc.go | 12 ++++-- .../migrations/0310_oidc_login_state.sql | 5 ++- docs/CONFIG.md | 4 +- 9 files changed, 120 insertions(+), 19 deletions(-) diff --git a/.changeset/oidc-cli-device-flow.md b/.changeset/oidc-cli-device-flow.md index 533a7f89eaf..57c6b566d03 100644 --- a/.changeset/oidc-cli-device-flow.md +++ b/.changeset/oidc-cli-device-flow.md @@ -8,7 +8,7 @@ #changed Hardened OIDC device and auth-code flows: server-side PKCE verifier and OIDC nonce (the session cookie holds only the anti-CSRF state), email claim validation, orphan-session cleanup if cookie bind fails, and a stricter CLI `/oidc-enabled` probe. Browser login state and device-flow results are stored in Postgres so any replica can finish a login. The provider device code stays on the replica that started the flow and is not written to the database. Device-flow lifetime is capped at five minutes. A verification URI whose host does not match the configured provider is rejected. Groups the node does not know are ignored; the highest configured role group picks the role. A denied device login tells the CLI why, including when none of the user's groups map to a node role. OIDC API tokens cannot be created or used. Debug request logs redact the OIDC authorization code and state. -#added `WebServer.OIDC.DeviceFlowAllowedCIDRs` lists the client networks (for example the operator VPN or bastion range) that may use the CLI device login. It defaults to empty, which turns the device login off; requests from outside the list get 403. Browser login is not affected. +#added `WebServer.OIDC.DeviceFlowAllowedCIDRs` lists the client networks (for example the operator VPN or bastion range) that may use the CLI device login. It defaults to empty, which turns the device login off; requests from outside the list get 403. Browser login is not affected. A device login request that carries `X-Forwarded-For`, `X-Real-IP` or `Forwarded` from a peer outside `TrustedProxyCIDRs` gets 403, so an unlisted proxy inside the allow-list does not let every caller behind it in. #added `WebServer.OIDC.TrustedProxyCIDRs` lists the load balancers and proxies in front of the node. The OIDC login routes believe `X-Forwarded-For` only from these hops and take the first address outside them as the client. It defaults to empty, which uses the socket peer and ignores the header. @@ -16,6 +16,6 @@ #changed The CLI refuses device login unless `--remote-node-url` uses https (plain http only for localhost) and TLS verification is on, and refuses to show a verification URI that is not https. Note the CLI does not check the verification URI host itself; the node checks it against the configured provider. -#changed Device-flow abuse limits: dedicated pre-auth rate limits on `/oidc-device/start`, `/oidc-device/poll` and `/oidc-login`, keyed per IPv4 address or IPv6 /64. A device flow the CLI stops polling for 30 seconds (or three poll intervals, if longer) releases its slot and stops polling the identity provider. `/oidc-login` caps pending sign-ins at 50 per client and 10,000 in total, and answers 503 with `Retry-After` past either. +#changed Device-flow abuse limits: dedicated pre-auth rate limits on `/oidc-device/start` and `/oidc-device/poll`, keyed per IPv4 address or IPv6 /64, and on `/oidc-login`, keyed per IPv4 address or IPv6 /48. A device flow the CLI stops polling for 30 seconds (or three poll intervals, if longer) releases its slot and stops polling the identity provider. `/oidc-login` caps pending sign-ins at 50 per client and 10,000 in total, and answers 503 with `Retry-After` past either. #added `AUTH_DEVICE_FLOW_STARTED` audit event with the client IP, User-Agent and a handle fingerprint. Device-flow success and failure events carry the same fingerprint and the starting client IP; success also records the redeeming IP and `client_ip_mismatch` when the two differ. diff --git a/core/config/docs/core.toml b/core/config/docs/core.toml index 8619090b45b..326046c0422 100644 --- a/core/config/docs/core.toml +++ b/core/config/docs/core.toml @@ -233,7 +233,9 @@ UserAPITokenEnabled = false # Default UserAPITokenDuration = '240h0m0s' # Default # DeviceFlowAllowedCIDRs lists the client networks, such as an operator VPN or bastion range, that may use the CLI device login # (`/oidc-device/start` and `/oidc-device/poll`). Requests from any other address get 403. Empty turns the CLI device login off. -# Browser login is not affected. The client address is resolved through TrustedProxyCIDRs. +# Browser login is not affected. The client address is resolved through TrustedProxyCIDRs. A device login request that carries +# `X-Forwarded-For`, `X-Real-IP` or `Forwarded` from a peer outside TrustedProxyCIDRs is refused, so a proxy left out of that list +# cannot pass its own address off as the client. Do not list the address of a proxy that adds none of those headers. DeviceFlowAllowedCIDRs = [] # Default # TrustedProxyCIDRs lists the proxies and load balancers in front of the node whose `X-Forwarded-For` entries the OIDC login # routes believe. The node walks `X-Forwarded-For` from the right, skips entries inside these prefixes, and uses the first diff --git a/core/sessions/oidcauth/device_flow.go b/core/sessions/oidcauth/device_flow.go index 1b55cada841..5620e5c1c7a 100644 --- a/core/sessions/oidcauth/device_flow.go +++ b/core/sessions/oidcauth/device_flow.go @@ -7,6 +7,7 @@ import ( "errors" "io" "net/http" + "net/netip" "sync" "time" @@ -231,17 +232,17 @@ type DevicePollResponse struct { } // preAuthRateLimit builds a dedicated limiter for a pre-auth OIDC route. -// The key is the client bucket (IPv4 address or IPv6 /64) resolved through -// the trusted proxies, so a load balancer does not collapse every caller into +// The key is bucket applied to the client address resolved through the +// trusted proxies, so a load balancer does not collapse every caller into // one bucket and a forged X-Forwarded-For from an untrusted hop is ignored. // Nested under the outer api group so both limits apply. -func (oi *oidcAuthenticator) preAuthRateLimit(period time.Duration, limit int64) gin.HandlerFunc { +func (oi *oidcAuthenticator) preAuthRateLimit(period time.Duration, limit int64, bucket func(netip.Addr) string) gin.HandlerFunc { store := memory.NewStore() rate := limiter.Rate{ Period: period, Limit: limit, } - key := func(c *gin.Context) string { return clientBucket(oi.clients.clientAddr(c)) } + key := func(c *gin.Context) string { return bucket(oi.clients.clientAddr(c)) } return mgin.NewMiddleware(limiter.New(store, rate), mgin.WithKeyGetter(key), mgin.WithLimitReachedHandler(func(c *gin.Context) { @@ -261,6 +262,18 @@ func (oi *oidcAuthenticator) deviceNetworkGuard() gin.HandlerFunc { c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": errDeviceLoginDisabled.Error()}) return } + // A forwarding header from a hop outside TrustedProxyCIDRs means a proxy + // the node does not know about. The socket peer is then the proxy, and + // if the proxy's address is inside the allow-list every caller behind it + // would pass. Refuse instead. + if oi.clients.forwardedByUntrustedHop(c) { + oi.lggr.Debugf("refusing device login request forwarded by an untrusted hop path=%s peer=%s", c.FullPath(), c.Request.RemoteAddr) + oi.warnUntrustedForward.Do(func() { + oi.lggr.Warnf("refusing device login requests that carry X-Forwarded-For, X-Real-IP or Forwarded from a peer outside WebServer.OIDC.TrustedProxyCIDRs (first seen from %s); list the node's proxies in TrustedProxyCIDRs", c.Request.RemoteAddr) + }) + c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": errDeviceLoginNetwork.Error()}) + return + } addr := oi.clients.clientAddr(c) if !prefixesContain(oi.deviceAllowed, addr) { // Debug, not Warn: anyone on the internet can trigger this. diff --git a/core/sessions/oidcauth/device_http_test.go b/core/sessions/oidcauth/device_http_test.go index aaf6ff1279a..34c93062554 100644 --- a/core/sessions/oidcauth/device_http_test.go +++ b/core/sessions/oidcauth/device_http_test.go @@ -3,6 +3,7 @@ package oidcauth import ( "bytes" "encoding/json" + "fmt" "net/http" "net/http/httptest" "sync" @@ -226,3 +227,20 @@ func TestSignInRoute_RateLimitedPerClient(t *testing.T) { require.NoError(t, h.oi.ds.GetContext(t.Context(), &n, `SELECT count(*) FROM oidc_pending_auth WHERE client_key = '198.51.100.7'`)) assert.Equal(t, signInRateLimit, n, "refused sign-ins write nothing") } + +// TestSignInRoute_IPv6AllocationIsOneClient: rotating through the /64s of one +// allocation does not buy extra sign-ins or pending-auth rows. +func TestSignInRoute_IPv6AllocationIsOneClient(t *testing.T) { + t.Parallel() + h := newRouterHarness(t) + for i := range signInRateLimit { + w := h.do(http.MethodGet, "/oidc-login", fmt.Sprintf("2001:db8:0:%x::1", i), nil) + require.Equal(t, http.StatusFound, w.Code, "request %d", i) + } + w := h.do(http.MethodGet, "/oidc-login", "2001:db8:0:ff::1", nil) + assert.Equal(t, http.StatusTooManyRequests, w.Code) + + var n int + require.NoError(t, h.oi.ds.GetContext(t.Context(), &n, `SELECT count(*) FROM oidc_pending_auth WHERE client_key = '2001:db8::/48'`)) + assert.Equal(t, signInRateLimit, n) +} diff --git a/core/sessions/oidcauth/login_guards.go b/core/sessions/oidcauth/login_guards.go index 8adb8bf90ad..2aa510dd0dd 100644 --- a/core/sessions/oidcauth/login_guards.go +++ b/core/sessions/oidcauth/login_guards.go @@ -135,6 +135,24 @@ func (r clientResolver) clientAddr(c *gin.Context) netip.Addr { return current } +// forwardingHeaders are the headers a proxy uses to pass on the client +// address. A client that talks to the node directly sends none of them. +var forwardingHeaders = []string{"X-Forwarded-For", "X-Real-IP", "Forwarded"} + +// forwardedByUntrustedHop reports whether the request carries a forwarding +// header and the socket peer is not a trusted proxy. The header is not +// believed either way; this only tells the caller a proxy it does not know +// about may sit in front of the node. +func (r clientResolver) forwardedByUntrustedHop(c *gin.Context) bool { + if c.Request == nil { + return false + } + if !slices.ContainsFunc(forwardingHeaders, func(h string) bool { return len(c.Request.Header.Values(h)) > 0 }) { + return false + } + return !prefixesContain(r.trustedProxies, parseHostAddr(c.Request.RemoteAddr)) +} + // parseHostAddr accepts "ip", "ip:port" and "[ipv6]:port". func parseHostAddr(s string) netip.Addr { if s == "" { @@ -149,18 +167,31 @@ func parseHostAddr(s string) netip.Addr { return netip.Addr{} } -// clientBucket is the key the rate limiters and concurrency caps count -// against. IPv6 clients are grouped by /64, the smallest block an ISP or -// cloud normally hands out, so one allocation cannot mint fresh buckets. +// clientBucket is the key the device-flow rate limiters and concurrency caps +// count against. IPv6 clients are grouped by /64, the smallest block an ISP +// or cloud normally hands out, so one allocation cannot mint fresh buckets. // Unresolvable clients share one bucket. func clientBucket(addr netip.Addr) string { + return bucketFor(addr, 64) +} + +// signInBucket is the key for the browser sign-in limiter and the +// oidc_pending_auth per-client cap. That route is open to the internet, and a +// single home or cloud IPv6 allocation is often a /56 (256 /64s) or a /48, so +// /64 buckets would let one subscriber fill the global pending-auth cap. +// Grouping by /48 makes that take hundreds of separate allocations. +func signInBucket(addr netip.Addr) string { + return bucketFor(addr, 48) +} + +func bucketFor(addr netip.Addr, v6Bits int) string { switch { case !addr.IsValid(): return "unknown" case addr.Is4(): return addr.String() default: - return netip.PrefixFrom(addr, 64).Masked().String() + return netip.PrefixFrom(addr, v6Bits).Masked().String() } } diff --git a/core/sessions/oidcauth/login_guards_test.go b/core/sessions/oidcauth/login_guards_test.go index 82004f1137c..2ca2590f80b 100644 --- a/core/sessions/oidcauth/login_guards_test.go +++ b/core/sessions/oidcauth/login_guards_test.go @@ -108,6 +108,19 @@ func TestClientBucket(t *testing.T) { assert.Equal(t, "unknown", clientBucket(netip.Addr{})) } +func TestSignInBucket(t *testing.T) { + t.Parallel() + // Every /64 in one /56 (a common home or cloud allocation) is one bucket. + seen := map[string]bool{} + for i := range 256 { + seen[signInBucket(netip.MustParseAddr(fmt.Sprintf("2001:db8:0:%x::1", i)))] = true + } + assert.Equal(t, map[string]bool{"2001:db8::/48": true}, seen) + assert.NotEqual(t, signInBucket(netip.MustParseAddr("2001:db8:1::1")), signInBucket(netip.MustParseAddr("2001:db8:2::1"))) + assert.Equal(t, "203.0.113.1", signInBucket(netip.MustParseAddr("203.0.113.1"))) + assert.Equal(t, "unknown", signInBucket(netip.Addr{})) +} + func TestParseCIDRs(t *testing.T) { t.Parallel() got, err := parseCIDRs("x", []string{"10.1.2.3/8", " 2001:db8::/32 "}) @@ -128,7 +141,7 @@ func TestHandleFingerprint(t *testing.T) { func TestDeviceNetworkGuard(t *testing.T) { t.Parallel() - run := func(oi *oidcAuthenticator, remote, xff string) int { + run := func(oi *oidcAuthenticator, remote, xff string, extra ...string) int { w := httptest.NewRecorder() _, eng := gin.CreateTestContext(w) eng.POST("/oidc-device/start", oi.deviceNetworkGuard(), func(c *gin.Context) { c.Status(http.StatusOK) }) @@ -137,6 +150,9 @@ func TestDeviceNetworkGuard(t *testing.T) { if xff != "" { req.Header.Set("X-Forwarded-For", xff) } + for i := 0; i+1 < len(extra); i += 2 { + req.Header.Set(extra[i], extra[i+1]) + } eng.ServeHTTP(w, req) return w.Code } @@ -159,6 +175,20 @@ func TestDeviceNetworkGuard(t *testing.T) { assert.Equal(t, http.StatusForbidden, run(on, "203.0.113.5:1", "10.8.3.3")) // A malformed header from the trusted proxy is refused. assert.Equal(t, http.StatusForbidden, run(on, "10.0.0.2:1", "garbage")) + + // An unlisted proxy inside the allow-list: every caller behind it would + // look like the proxy. A forwarding header from an untrusted hop is + // refused, whatever it says. + assert.Equal(t, http.StatusForbidden, run(on, "10.8.0.9:1", "203.0.113.5")) + assert.Equal(t, http.StatusForbidden, run(on, "10.8.0.9:1", "10.8.3.3")) + assert.Equal(t, http.StatusForbidden, run(on, "10.8.0.9:1", "", "X-Real-IP", "203.0.113.5")) + assert.Equal(t, http.StatusForbidden, run(on, "10.8.0.9:1", "", "Forwarded", "for=203.0.113.5")) + + // No trusted proxies at all, node behind an unlisted load balancer whose + // address is inside the allow-list. + open := &oidcAuthenticator{lggr: lggr, deviceAllowed: mustCIDRs(t, "10.0.0.0/16")} + assert.Equal(t, http.StatusForbidden, run(open, "10.0.1.5:443", "203.0.113.9")) + assert.Equal(t, http.StatusOK, run(open, "10.0.1.5:443", ""), "a direct caller sends no forwarding header") } func mustCIDRs(t *testing.T, list ...string) []netip.Prefix { diff --git a/core/sessions/oidcauth/oidc.go b/core/sessions/oidcauth/oidc.go index 6beb3b7f6a7..e1c333422e5 100644 --- a/core/sessions/oidcauth/oidc.go +++ b/core/sessions/oidcauth/oidc.go @@ -19,6 +19,7 @@ import ( "net/netip" "slices" "strings" + "sync" "time" "github.com/coreos/go-oidc/v3/oidc" @@ -60,6 +61,9 @@ type oidcAuthenticator struct { deviceAllowed []netip.Prefix // liveCheckEvery overrides deviceLiveCheckEvery in tests. liveCheckEvery time.Duration + // warnUntrustedForward logs the missing-TrustedProxyCIDRs hint once, so + // an internet caller cannot flood the log at Warn. + warnUntrustedForward sync.Once } // ExchangeTokenRequest represents the expected JSON payload from the frontend @@ -200,7 +204,7 @@ func (oi *oidcAuthenticator) handleSignIn(c *gin.Context) { state := oi.generateState() verifier := oauth2.GenerateVerifier() nonce := oi.generateState() - bucket := clientBucket(oi.clients.clientAddr(c)) + bucket := signInBucket(oi.clients.clientAddr(c)) if err := putPendingAuth(c.Request.Context(), oi.ds, state, verifier, nonce, bucket, time.Now().Add(pendingAuthTTL)); err != nil { if errors.Is(err, errTooManyPendingAuth) || errors.Is(err, errTooManyPendingAuthPerClient) { oi.lggr.Warnf("refusing sign-in client=%s: %v", bucket, err) @@ -737,7 +741,7 @@ func (oi *oidcAuthenticator) ExtendRouter(api *gin.RouterGroup) error { // Sign-in writes a pending-auth row, so it gets its own pre-auth limiter // on top of the outer api limiter. api.GET("/oidc-login", - oi.preAuthRateLimit(signInRatePeriod, signInRateLimit), + oi.preAuthRateLimit(signInRatePeriod, signInRateLimit, signInBucket), oi.handleSignIn, ) api.POST("/oidc-exchange", oi.handleTokenExchange) @@ -750,12 +754,12 @@ func (oi *oidcAuthenticator) ExtendRouter(api *gin.RouterGroup) error { // the database, or the identity provider. api.POST("/oidc-device/start", oi.deviceNetworkGuard(), - oi.preAuthRateLimit(deviceStartRatePeriod, deviceStartRateLimit), + oi.preAuthRateLimit(deviceStartRatePeriod, deviceStartRateLimit, clientBucket), oi.handleDeviceStart, ) api.POST("/oidc-device/poll", oi.deviceNetworkGuard(), - oi.preAuthRateLimit(devicePollRatePeriod, devicePollRateLimit), + oi.preAuthRateLimit(devicePollRatePeriod, devicePollRateLimit, clientBucket), oi.handleDevicePoll, ) diff --git a/core/store/migrate/migrations/0310_oidc_login_state.sql b/core/store/migrate/migrations/0310_oidc_login_state.sql index d484c4ddfca..86492fb167b 100644 --- a/core/store/migrate/migrations/0310_oidc_login_state.sql +++ b/core/store/migrate/migrations/0310_oidc_login_state.sql @@ -1,8 +1,9 @@ -- +goose Up -- Short-lived login state shared by every replica. The provider device code -- is not stored here. Only the opaque handle and the browser state key are. --- client_key and ip_bucket are the rate-limit bucket for the caller (an IPv4 --- address or an IPv6 /64), used by the per-client caps. +-- client_key and ip_bucket are the rate-limit bucket for the caller, used by +-- the per-client caps: an IPv4 address, or an IPv6 /48 for browser sign-in +-- (client_key) and an IPv6 /64 for the device flow (ip_bucket). CREATE TABLE IF NOT EXISTS oidc_pending_auth ( state text PRIMARY KEY, verifier text NOT NULL, diff --git a/docs/CONFIG.md b/docs/CONFIG.md index ca8cd7f172a..48792cb2369 100644 --- a/docs/CONFIG.md +++ b/docs/CONFIG.md @@ -668,7 +668,9 @@ DeviceFlowAllowedCIDRs = [] # Default ``` DeviceFlowAllowedCIDRs lists the client networks, such as an operator VPN or bastion range, that may use the CLI device login (`/oidc-device/start` and `/oidc-device/poll`). Requests from any other address get 403. Empty turns the CLI device login off. -Browser login is not affected. The client address is resolved through TrustedProxyCIDRs. +Browser login is not affected. The client address is resolved through TrustedProxyCIDRs. A device login request that carries +`X-Forwarded-For`, `X-Real-IP` or `Forwarded` from a peer outside TrustedProxyCIDRs is refused, so a proxy left out of that list +cannot pass its own address off as the client. Do not list the address of a proxy that adds none of those headers. ### TrustedProxyCIDRs ```toml From c2468e8647b342ac6e0eb5173fbd5d454db73699 Mon Sep 17 00:00:00 2001 From: Harry Anderson Date: Thu, 19 Nov 2026 04:03:39 +0000 Subject: [PATCH 18/18] test(oidc): set gin test mode once per package to avoid a race between parallel router tests --- core/sessions/oidcauth/device_http_test.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/core/sessions/oidcauth/device_http_test.go b/core/sessions/oidcauth/device_http_test.go index 34c93062554..b7438b1cbd3 100644 --- a/core/sessions/oidcauth/device_http_test.go +++ b/core/sessions/oidcauth/device_http_test.go @@ -23,6 +23,10 @@ import ( // These tests drive the real routes from ExtendRouter against the mock IdP // and a real database. +// gin's mode is a package global that route registration reads, so set it +// once here rather than from parallel tests. +func init() { gin.SetMode(gin.TestMode) } + type auditEvent struct { id audit.EventID data audit.Data @@ -84,7 +88,6 @@ func newRouterHarness(t *testing.T) *routerHarness { oi.deviceAllowed = mustCIDRs(t, "10.8.0.0/16") oi.clients = clientResolver{trustedProxies: mustCIDRs(t, "10.0.0.0/24")} - gin.SetMode(gin.TestMode) engine := gin.New() api := engine.Group("/", sessions.Sessions("clsession", cookie.NewStore([]byte("0123456789abcdef0123456789abcdef")))) require.NoError(t, oi.ExtendRouter(api))