diff --git a/.changeset/oidc-cli-device-flow.md b/.changeset/oidc-cli-device-flow.md new file mode 100644 index 00000000000..57c6b566d03 --- /dev/null +++ b/.changeset/oidc-cli-device-flow.md @@ -0,0 +1,21 @@ +--- +"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. + +#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. 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. + +#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` 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/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..a9faec63be8 --- /dev/null +++ b/core/cmd/oidc_device_auth.go @@ -0,0 +1,275 @@ +package cmd + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net" + "net/http" + "net/url" + "strings" + "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. 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"` + ExpiresIn int64 `json:"expires_in"` + Interval int64 `json:"interval"` +} + +// 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. +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. 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" + 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() + 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 +// 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") + } + 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) + + 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, reason, 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 deviceDeniedError(reason) + 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(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)) + } + 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 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 + } + 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(io.LimitReader(resp.Body, maxDeviceResponseBytes)) + if resp.StatusCode == http.StatusNotFound { + return nil, "denied", "unknown", 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, pr.Reason, nil +} + +func (o *OIDCDeviceCookieAuthenticator) promptUser(start *oidcDeviceStartResponse) { + 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", 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 new file mode 100644 index 00000000000..74f714b7559 --- /dev/null +++ b/core/cmd/oidc_device_auth_test.go @@ -0,0 +1,249 @@ +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 + 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 { + mux := http.NewServeMux() + mux.HandleFunc("/oidc-enabled", func(w http.ResponseWriter, r *http.Request) { + if !m.oidcEnabled { + w.WriteHeader(http.StatusNotFound) + return + } + 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 + // 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": uri, + "verification_uri_complete": uri + "?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 + 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 { + _ = json.NewEncoder(w).Encode(map[string]string{"status": "pending"}) + return + } + if m.denyAfter { + _ = json.NewEncoder(w).Encode(map[string]string{"status": "denied", "reason": m.denyReason, "message": "node text"}) + return + } + 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 +} + +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)) + + // 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) { + 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, 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.") + // 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) { + 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) { + t.Parallel() + 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/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/config/docs/core.toml b/core/config/docs/core.toml index 5273289460b..326046c0422 100644 --- a/core/config/docs/core.toml +++ b/core/config/docs/core.toml @@ -231,6 +231,17 @@ 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. 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 +# 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 0f5b2f1523a..3f03e7136ca 100644 --- a/core/logger/audit/audit_types.go +++ b/core/logger/audit/audit_types.go @@ -7,6 +7,9 @@ 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" + 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 new file mode 100644 index 00000000000..5620e5c1c7a --- /dev/null +++ b/core/sessions/oidcauth/device_flow.go @@ -0,0 +1,622 @@ +package oidcauth + +import ( + "context" + "crypto/rand" + "encoding/base64" + "errors" + "io" + "net/http" + "net/netip" + "sync" + "time" + + "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" + clsessions "github.com/smartcontractkit/chainlink/v2/core/sessions" + 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. +// +// 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 + // 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 + + // 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 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 + role clsessions.UserRole + 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 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() + s.sweepLocked(time.Now()) + if len(s.flows) >= maxConcurrentDeviceFlows { + return errTooManyDeviceFlows + } + n := 0 + for _, existing := range s.flows { + if existing.bucket == f.bucket { + n++ + } + } + if n >= maxDeviceFlowsPerIP { + return errTooManyDeviceFlowsPerIP + } + 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 +} + +// 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() + 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, terminal bool, known bool, flowErr error) { + s.mu.Lock() + defer s.mu.Unlock() + f, ok := s.flows[handle] + if !ok { + return "", "", "", false, false, nil + } + f.mu.Lock() + defer f.mu.Unlock() + if !f.done { + return "", "", "", false, true, nil + } + delete(s.flows, handle) + return f.sessionID, f.email, f.role, true, true, f.err +} + +// 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. 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"` + 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 "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"` +} + +// preAuthRateLimit builds a dedicated limiter for a pre-auth OIDC route. +// 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, bucket func(netip.Addr) string) gin.HandlerFunc { + store := memory.NewStore() + rate := limiter.Rate{ + Period: period, + Limit: limit, + } + 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) { + 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 + } + // 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. + 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) { + 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 + } + + // 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. + 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, 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 + } + c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to start device authorization"}) + return + } + 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", bucket, addErr) + c.JSON(http.StatusTooManyRequests, gin.H{"error": addErr.Error()}) + return + } + + 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 := 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) { + _ = 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 := 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, + // and cut short if the CLI stops polling. + go oi.pollDeviceToken(handle, state, da) + + c.JSON(http.StatusOK, DeviceStartResponse{ + 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) { + 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 + } + + rawIDToken, ok := token.Extra("id_token").(string) + if !ok { + 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.deviceHandleLive(ctx, handle) { + oi.lggr.Warnf("device flow handle gone before token completion; abandoning without session") + 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, handle, "", "", "", err) + return + } + + // 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.deviceHandleLive(ctx, handle) { + oi.lggr.Warnf("device flow handle gone after session insert; deleting orphan session") + oi.deleteOIDCSession(ctx, sessionID) + oi.finishDeviceFlow(state, handle, "", "", "", errDeviceFlowAbandoned) + return + } + + 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) + 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 + 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) + 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 { + oi.lggr.Errorf("failed to record device flow result: %v", werr) + } + } +} + +// 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. +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 + } + + // 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. + 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 !res.known { + c.JSON(http.StatusNotFound, DevicePollResponse{Status: "denied", Message: errUnknownDeviceFlow.Error()}) + return + } + + if !res.terminal { + c.JSON(http.StatusOK, DevicePollResponse{Status: "pending"}) + return + } + + 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 := res.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 + } + + // 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, 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(), res.sessionID) + c.JSON(http.StatusInternalServerError, DevicePollResponse{Status: "denied", Message: "Failed to establish session"}) + return + } + + // 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 new file mode 100644 index 00000000000..886f6b911cd --- /dev/null +++ b/core/sessions/oidcauth/device_flow_test.go @@ -0,0 +1,292 @@ +package oidcauth + +import ( + "errors" + "strconv" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smartcontractkit/chainlink-common/pkg/logger" + clsessions "github.com/smartcontractkit/chainlink/v2/core/sessions" +) + +func TestDeviceFlowStore_AddGetRemove(t *testing.T) { + t.Parallel() + 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") +} + +// 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() + for i := range maxConcurrentDeviceFlows { + 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), bucket: "fresh"}) + 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), + bucket: ip, + })) + } + err := s.add("overflow-ip", &deviceFlowState{ + expiresAt: time.Now().Add(time.Minute), + 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), + bucket: "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() + // Fill with already-expired flows. + 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. + 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) { + t.Parallel() + oi := &oidcAuthenticator{} + seen := make(map[string]struct{}) + for range 1000 { + 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) { + t.Parallel() + oi := &oidcAuthenticator{lggr: logger.TestSugared(t)} + + okState := &deviceFlowState{expiresAt: time.Now().Add(time.Minute)} + 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) + assert.Equal(t, "user@example.com", okState.email) + require.NoError(t, okState.err) + okState.mu.Unlock() + + errState := &deviceFlowState{expiresAt: time.Now().Add(time.Minute)} + wantErr := errors.New("denied") + oi.finishDeviceFlow(errState, "handle-err", "", "", "", wantErr) + errState.mu.Lock() + assert.True(t, errState.done) + assert.Empty(t, errState.sessionID) + 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.TestSugared(t)} + state := &deviceFlowState{expiresAt: time.Now().Add(time.Minute)} + + var wg sync.WaitGroup + wg.Add(2) + go func() { + defer wg.Done() + oi.finishDeviceFlow(state, "handle-conc", "s", "e", clsessions.UserRoleView, nil) + }() + go func() { + defer wg.Done() + for range 100 { + state.mu.Lock() + _ = state.done + state.mu.Unlock() + } + }() + 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) +} + +// 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) { + t.Parallel() + 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/device_http_test.go b/core/sessions/oidcauth/device_http_test.go new file mode 100644 index 00000000000..b7438b1cbd3 --- /dev/null +++ b/core/sessions/oidcauth/device_http_test.go @@ -0,0 +1,249 @@ +package oidcauth + +import ( + "bytes" + "encoding/json" + "fmt" + "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. + +// 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 +} + +// 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")} + + 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") +} + +// 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/helpers_test.go b/core/sessions/oidcauth/helpers_test.go index 8d246304ee9..d82f49e62f9 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 @@ -131,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 new file mode 100644 index 00000000000..2aa510dd0dd --- /dev/null +++ b/core/sessions/oidcauth/login_guards.go @@ -0,0 +1,247 @@ +package oidcauth + +import ( + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "net" + "net/netip" + "net/url" + "slices" + "strings" + "time" + + "github.com/gin-gonic/gin" +) + +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. +func capDeviceExpiry(expiry, now time.Time) time.Time { + if !expiry.IsZero() && !expiry.After(now) { + return expiry + } + deadline := now.Add(maxDeviceFlowLifetime) + if expiry.IsZero() || expiry.After(deadline) { + return deadline + } + 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" +} + +// 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) + } + out = append(out, p.Masked()) + } + return out, nil +} + +func prefixesContain(list []netip.Prefix, addr netip.Addr) bool { + if !addr.IsValid() { + return false + } + 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 + } + } + // Every hop was a trusted proxy, so the leftmost one is the client. + 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 == "" { + return netip.Addr{} + } + if a, err := netip.ParseAddr(s); err == nil { + return a.Unmap().WithZone("") + } + if ap, err := netip.ParseAddrPort(s); err == nil { + return ap.Addr().Unmap().WithZone("") + } + return netip.Addr{} +} + +// 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, v6Bits).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]) +} + +// 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 { + if err == nil { + return "" + } + if errors.Is(err, errNoMatchingRole) { + return deviceReasonNoRole + } + 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 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..2ca2590f80b --- /dev/null +++ b/core/sessions/oidcauth/login_guards_test.go @@ -0,0 +1,227 @@ +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) { + 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 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) + + // 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()) + + // 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()) + + // 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()) + + // 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{})) +} + +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 "}) + 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, 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) }) + req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/oidc-device/start", nil) + req.RemoteAddr = remote + 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 + } + 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")) + + // 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 { + t.Helper() + p, err := parseCIDRs("test", list) + require.NoError(t, err) + return p +} + +func TestDeviceFailureReason(t *testing.T) { + t.Parallel() + require.Empty(t, deviceFailureReason(nil)) + assert.Equal(t, "failed", deviceFailureReason(assert.AnError)) + 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 + +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.NewRequestWithContext(t.Context(), 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..9987575ff66 --- /dev/null +++ b/core/sessions/oidcauth/login_state_store.go @@ -0,0 +1,233 @@ +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 + +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 + }) +} + +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 +} + +// 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, sweepDeviceFlows); 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 + } + 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, 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() AND poll_deadline > 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 +} + +// 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 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 + ClientIP string `db:"client_ip"` + } + err := ds.GetContext(ctx, &row, ` + DELETE FROM oidc_device_flows + 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 { + res := deviceFlowResult{ + known: true, + terminal: true, + sessionID: row.SessionID, + email: row.Email, + role: clsessions.UserRole(row.Role), + startIP: row.ClientIP, + } + if row.Err != "" { + res.flowErr = errors.New(row.Err) + } + return res, nil + } + if !errors.Is(err, sql.ErrNoRows) { + return deviceFlowResult{}, 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 + } + n, err := res.RowsAffected() + if err != nil { + return deviceFlowResult{}, err + } + 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 new file mode 100644 index 00000000000..d43c87c1b78 --- /dev/null +++ b/core/sessions/oidcauth/login_state_store_test.go @@ -0,0 +1,197 @@ +package oidcauth + +import ( + "strconv" + "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", "203.0.113.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", "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) + 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.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, testReservation("overflow", "2001:db8::ffff", exp)) + require.ErrorIs(t, err, errTooManyDeviceFlowsPerIP) +} + +// 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) { + t.Parallel() + db := pgtest.NewSqlxDB(t) + ctx := t.Context() + exp := time.Now().Add(time.Minute) + 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, 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), "")) + + res, err = consumeDeviceFlow(ctx, db, "shared-handle") + require.NoError(t, err) + 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, 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 new file mode 100644 index 00000000000..56cc9137c0e --- /dev/null +++ b/core/sessions/oidcauth/mock_idp_test.go @@ -0,0 +1,177 @@ +package oidcauth + +import ( + "context" + "crypto/rand" + "crypto/rsa" + "encoding/json" + "net/http" + "net/http/httptest" + "sync/atomic" + "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/logger" + "github.com/smartcontractkit/chainlink-common/pkg/sqlutil" + "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 + 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 +} + +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", + // 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{ + "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(), + } + if m.nonce != "" { + claims["nonce"] = m.nonce + } + 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.TestSugared(t), + auditLogger: &audit.AuditLoggerService{}, + deviceFlows: newDeviceFlowStore(), + } +} diff --git a/core/sessions/oidcauth/oidc.go b/core/sessions/oidcauth/oidc.go index cc7dd40eefb..e1c333422e5 100644 --- a/core/sessions/oidcauth/oidc.go +++ b/core/sessions/oidcauth/oidc.go @@ -15,8 +15,12 @@ import ( "io" "log" "net/http" + "net/mail" + "net/netip" "slices" "strings" + "sync" + "time" "github.com/coreos/go-oidc/v3/oidc" "github.com/gin-contrib/sessions" @@ -49,6 +53,17 @@ type oidcAuthenticator struct { oauth2Config *oauth2.Config 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 + // 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 @@ -66,32 +81,52 @@ 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") + } + 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 +} + +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 @@ -117,16 +152,31 @@ 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, - } + 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 + // 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 } @@ -145,18 +195,44 @@ func (oi *oidcAuthenticator) handleCheckEnabled(c *gin.Context) { } func (oi *oidcAuthenticator) handleSignIn(c *gin.Context) { - // generate state and store on session + // 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() + 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) + 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 + } + 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 { + _, _, _, _ = takePendingAuth(c.Request.Context(), oi.ds, state) c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save session"}) return } - // redirect to provider - url := oi.oauth2Config.AuthCodeURL(state, oauth2.AccessTypeOffline) + url := oi.oauth2Config.AuthCodeURL( + state, + oauth2.AccessTypeOffline, + oauth2.S256ChallengeOption(verifier), + oidc.Nonce(nonce), + ) c.Redirect(http.StatusFound, url) } @@ -171,21 +247,41 @@ 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") - // Begin token exchange to retrieve attested claims of authenticated user + // 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, + Message: "Missing or expired authorization state", + }) + 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{ @@ -198,39 +294,79 @@ 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 } - // Verify claim and retrieve attested user id claims - idToken, err := oi.provider.Verifier(oi.oidcConfig).Verify(ctx, rawIDToken) + sessionID, email, role, err := oi.issueSessionFromIDToken(ctx, rawIDToken, expectedNonce) + 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) + oi.deleteOIDCSession(ctx, sessionID) + c.String(http.StatusInternalServerError, "Authentication failed") return } + oi.auditLogger.Audit(audit.AuthLoginSuccessNo2FA, map[string]any{"email": email, "role": role, "method": "oidc_exchange"}) + + 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, 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. +// +// 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 { - 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") + + email, err := normalizeEmailClaim(claims) + if err != nil { + return "", "", "", err } 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 +375,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.AuthLoginFailedOIDC, map[string]any{"email": email, "reason": deviceReasonNoRole, "groups": idClaims}) + return "", "", "", fmt.Errorf("%w: %w", 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 +390,42 @@ 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}) + return clSession.ID, email, role, 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") - return +// 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 +} - c.JSON(http.StatusOK, ExchangeTokenResponse{ - Success: true, - }) +// 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 + } + 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 @@ -294,47 +447,15 @@ 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") - } +// 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") - 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 - 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. See errOIDCAPITokensDisabled. +func (oi *oidcAuthenticator) FindUserByAPIToken(context.Context, string) (clsessions.User, error) { + 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 @@ -433,7 +554,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 } @@ -497,54 +618,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 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 errOIDCAPITokensDisabled. +func (oi *oidcAuthenticator) SetAuthToken(context.Context, *clsessions.User, *auth.Token) error { + return errOIDCAPITokensDisabled } // DeleteAuthToken clears and disables the users Authentication Token. @@ -657,8 +738,30 @@ 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, signInBucket), + 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. 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", + oi.deviceNetworkGuard(), + oi.preAuthRateLimit(deviceStartRatePeriod, deviceStartRateLimit, clientBucket), + oi.handleDeviceStart, + ) + api.POST("/oidc-device/poll", + oi.deviceNetworkGuard(), + oi.preAuthRateLimit(devicePollRatePeriod, devicePollRateLimit, clientBucket), + oi.handleDevicePoll, + ) + return nil } diff --git a/core/sessions/oidcauth/oidc_test.go b/core/sessions/oidcauth/oidc_test.go index ccfbc4c81f0..3baf1537ae4 100644 --- a/core/sessions/oidcauth/oidc_test.go +++ b/core/sessions/oidcauth/oidc_test.go @@ -65,9 +65,9 @@ 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) { + t.Parallel() ctx := t.Context() - // Init OIDC authenticator db, oidcAuthProvider := setupAuthenticationProvider(t) testEmail := "test@test.com" @@ -75,16 +75,16 @@ 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) { + t.Parallel() ctx := t.Context() - // Init OIDC authenticator cfg := oidcauth.TestConfig{} db, oidcAuthProvider := setupAuthenticationProvider(t) @@ -94,35 +94,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 new file mode 100644 index 00000000000..7b595b97788 --- /dev/null +++ b/core/sessions/oidcauth/pending_auth.go @@ -0,0 +1,64 @@ +package oidcauth + +import ( + "sync" + "time" +) + +// 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 + 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/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 new file mode 100644 index 00000000000..9dacc9d9489 --- /dev/null +++ b/core/sessions/oidcauth/verify_flow_test.go @@ -0,0 +1,250 @@ +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" + clsessions "github.com/smartcontractkit/chainlink/v2/core/sessions" +) + +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) { + t.Parallel() + 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) { + t.Parallel() + 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) { + t.Parallel() + 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_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{"Contractors", RunnerClaim, "Everyone"} + oi := newAuthenticatorForIDP(t, idp, db) + + _, _, 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 +// 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" + 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) { + t.Parallel() + 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) { + t.Parallel() + 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) { + t.Parallel() + 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. 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), clientIP: "127.0.0.1"} + 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) + + 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")) +} + +// 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) { + t.Parallel() + 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) + + 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, testReservation(handle, state.clientIP, state.expiresAt))) + require.NoError(t, oi.deviceFlows.add(handle, state)) + oi.pollDeviceToken(handle, 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")) +} diff --git a/core/store/migrate/migrations/0310_oidc_login_state.sql b/core/store/migrate/migrations/0310_oidc_login_state.sql new file mode 100644 index 00000000000..86492fb167b --- /dev/null +++ b/core/store/migrate/migrations/0310_oidc_login_state.sql @@ -0,0 +1,39 @@ +-- +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, 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, + 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 '', + role text NOT NULL DEFAULT '', + err text NOT NULL DEFAULT '' +); + +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; +DROP TABLE IF EXISTS oidc_pending_auth; 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/core/web/router.go b/core/web/router.go index 0be1fa20d2a..0e7f494f942 100644 --- a/core/web/router.go +++ b/core/web/router.go @@ -646,6 +646,10 @@ var blacklist = map[string]struct{}{ "oldpassword": {}, "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"`) + }) +} 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/docs/CONFIG.md b/docs/CONFIG.md index 9c75807c44e..48792cb2369 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,25 @@ 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. 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 +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/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 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 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 = ''