Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
bef27fa
feat(oidc): add CLI login via device authorization grant + PKCE
harry-anderson Jun 18, 2026
f7f73eb
test(oidc): add signed-JWT mock IdP and verification tests
harry-anderson Jun 18, 2026
63487af
fix(oidc): satisfy lint and go mod tidy for CI
harry-anderson Jun 18, 2026
1de3437
fix(oidc): harden device flow polling, auditing, and logging
harry-anderson Jun 23, 2026
96abafb
test(oidc): update issueSessionFromIDToken callers for role return value
harry-anderson Jun 23, 2026
b5f98ef
fix(oidc): move error to last return value in consumeIfDone (revive)
harry-anderson Jun 23, 2026
cacf25a
fix(oidc): harden device flow and auth-code security controls
harry-anderson Jul 11, 2026
6f5300c
fix(oidc): fix device-flow e2e test and govet shadow
harry-anderson Jul 11, 2026
d6b46b4
fix(oidc): tidy limiter dep into dependent go.mod files
harry-anderson Jul 11, 2026
e55b6f1
fix(oidc): adapt rebased device flow to current logger and HTTP client
harry-anderson Oct 6, 2026
2f7c73d
fix(oidc): share login state and tighten device-flow checks
harry-anderson Oct 6, 2026
25cfe6d
fix(oidc): satisfy lint on device-flow guards
harry-anderson Oct 6, 2026
381d795
fix(oidc): move login-state migration to 0310
harry-anderson Oct 29, 2026
fc4f44b
feat(oidc): allow extra IdP groups and give device login denial reasons
harry-anderson Nov 10, 2026
3a9d5fd
feat(oidc): redact authorization code and state in request logs
harry-anderson Nov 13, 2026
f08c4c5
feat(oidc): limit device login to allowed networks and trusted proxies
harry-anderson Nov 14, 2026
5ecd4c6
feat(oidc): refuse forwarded device logins from unlisted proxies, gro…
harry-anderson Nov 18, 2026
c2468e8
test(oidc): set gin test mode once per package to avoid a race betwee…
harry-anderson Nov 19, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions .changeset/oidc-cli-device-flow.md
Original file line number Diff line number Diff line change
@@ -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.
5 changes: 4 additions & 1 deletion core/cmd/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -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") {
Expand Down
275 changes: 275 additions & 0 deletions core/cmd/oidc_device_auth.go
Original file line number Diff line number Diff line change
@@ -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)
}
Loading
Loading