Skip to content

feat(oidc): CLI login via device authorization grant + PKCE - #22889

Draft
harry-anderson wants to merge 18 commits into
developfrom
feature/oidc-cli-device-flow
Draft

harry-anderson wants to merge 18 commits into
developfrom
feature/oidc-cli-device-flow

Conversation

@harry-anderson

@harry-anderson harry-anderson commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Extends the existing OIDC operator-UI auth to the CLI using the OAuth 2.0 device authorization grant (RFC 8628), and hardens the existing authorization-code flow with PKCE (RFC 7636).

Today, on a node with AuthenticationMethod = 'oidc', the operator UI authenticates against the IdP but the CLI can only use the local email/password fallback (the users table). This adds a real OIDC login path for the headless CLI without standing up a second identity app.

What changed

  • Device flow, node-brokered. New POST /oidc-device/start and POST /oidc-device/poll endpoints. The node calls the provider's device authorization endpoint, hands the user code and verification URI back to the CLI, and polls the provider on the CLI's behalf. The provider device_code never leaves the node; the CLI only holds an opaque, single-use 256-bit handle. The node's poll to the provider runs in one background goroutine driven by oauth2.DeviceAccessToken (which honours interval/slow_down), so the CLI's poll cadence cannot amplify load on the IdP. Browser login state and device-flow results are stored in Postgres so any replica can finish a login. The provider device code stays in memory on the replica that started the flow. If that replica stops during the provider poll, the login fails.
  • Device login is off unless a network allow-list is set. WebServer.OIDC.DeviceFlowAllowedCIDRs lists the client networks (for example the operator VPN or bastion range) that may use the device routes. It defaults to empty, which turns device login off. Requests from outside the list get 403 before any rate limiter, database write or IdP call. Only CLI operators need these routes, and keeping them off the public internet is what stops a stranger from starting a flow and phishing an approval (RFC 8628 section 5.4). Browser login is not affected.
  • Client address through trusted proxies only. 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: the header is walked from the right, trusted hops are skipped, and the first address outside them is the client. A zero-length prefix is rejected. With the default empty list the socket peer is the client. A device request that carries X-Forwarded-For, X-Real-IP or Forwarded from a peer outside the list gets 403, so a proxy left out of the list cannot pass its own address off as every client behind it. The global RemoteIPHeaders setting is unchanged.
  • No one-click approval links. The node no longer passes the provider's verification_uri_complete to the CLI. The operator types the user code at the identity provider. A verification URI is returned only when its host matches the configured provider host, and http is accepted only for a loopback address or localhost.
  • PKCE, always on. handleSignIn generates a PKCE verifier and an OIDC nonce, stores both server-side keyed by state, and puts only state in the session cookie. It sends the S256 challenge. handleTokenExchange takes the verifier and nonce from that store, single-use, and binds the verifier on exchange. The OIDC ClientSecret is now optional: confidential clients still send it, public clients (required for device flow) rely on PKCE. Existing confidential deployments are unaffected and get PKCE as additive hardening.
  • Single verification path. Extracted issueSessionFromIDToken so the browser exchange and the device flow share one verify, claim-extract, role-map and session-create path. Groups the node does not know are ignored; the highest configured role group picks the role.
  • CLI authenticator. New device-flow CookieAuthenticator in core/cmd. RemoteLogin uses it when the node reports OIDC and no -file is given, and keeps the local email/password path as break-glass. The CLI refuses device login unless --remote-node-url uses https (plain http only for loopback) and TLS verification is on, and refuses to show a verification URI that is not https. The CLI does not check the verification URI host itself; the node checks it against the configured provider. A 403 from the allow-list tells the operator to connect through the VPN or bastion, or use a credentials file.
  • Abuse limits. Dedicated pre-auth rate limits on /oidc-device/start (5 per 20s) and /oidc-device/poll (60 per minute), keyed per IPv4 address or IPv6 /64, and on /oidc-login (20 per minute), keyed per IPv4 address or IPv6 /48, since that route is open to the internet and one home or cloud IPv6 allocation is often a /56 or /48. Device flows are capped at 5 per client and 100 per node, with a five-minute lifetime even when the provider returns a longer expiry. A device flow the CLI stops polling for 30 seconds (or three poll intervals, if longer) frees its slot, stops polling the identity provider, and drops any session it minted. Pending browser sign-ins are capped at 50 per client and 10,000 in total; past either cap /oidc-login answers 503 with Retry-After.
  • Login events. New AUTH_DEVICE_FLOW_STARTED event with the client IP, User-Agent and a handle fingerprint (first 8 bytes of SHA-256; the handle itself is never logged). 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, the signature of a forwarded or phished approval. Denied device flows are recorded as AUTH_LOGIN_FAILED_DEVICE with a reason, and the poll response carries that reason (no_role, denied, expired, abandoned, failed) so the CLI can print its own message. OIDC role-mapping failures are recorded as AUTH_LOGIN_FAILED_OIDC with the claim set, not under the 2FA event.
  • Request log redaction. Debug request logs redact the OIDC authorization code and state and the device handle.
  • OIDC API tokens stay off. FindUserByAPIToken and SetAuthToken return an error even if UserAPITokenEnabled is true.

New configuration

[WebServer.OIDC]
# Client networks that may use the CLI device login. Empty (default) turns it off.
DeviceFlowAllowedCIDRs = ['10.8.0.0/16']
# Proxies in front of the node whose X-Forwarded-For entries are believed. Empty (default) uses the socket peer.
TrustedProxyCIDRs = ['10.0.0.0/24']

Do not put the address of a proxy that adds no forwarding header (an L4 load balancer without client IP preservation, kubectl port-forward, a sidecar) inside DeviceFlowAllowedCIDRs: every caller behind it would arrive from that address.

Why the IdP app must be public/native

Okta only offers the Device Authorization grant on Native (public client) app types, not the Web (confidential) app type the UI flow uses today. A single Native app can carry both Authorization Code (with PKCE) and Device grants, so the UI and CLI share one app and one verified audience. Making the secret optional and PKCE always on is what lets one public client serve both flows.

Test plan

  • go test -race ./core/sessions/oidcauth/... (full suite, against Postgres), including the shared pending-auth round trip, per-client caps, single-winner consume, and the abandoned-flow release
  • go test ./core/cmd/ OIDC/device/login tests, including plaintext node URL, non-https verification URI, skip-verify and 403-from-allow-list refusals
  • Signed-JWT mock IdP (discovery, JWKS, device and token endpoints) exercises the real go-oidc verifier end to end: valid token issues a session, wrong-audience token rejected with no session, expired token rejected, unmatched group rejected with errNoMatchingRole, per-group RBAC role mapping, full device-flow poll path, wrong-audience device token rejected
  • Router tests through the real ExtendRouter: outside the allow-list refused on start and poll with no database write, empty allow-list disables the routes, forwarding headers from an untrusted peer refused, start and redemption events join on the fingerprint with client_ip_mismatch, sign-in limiter per client and per IPv6 /48
  • Config validation and docs tests (core/config/docs, core/services/chainlink), request-log redaction test
  • Manual end to end against Okta (sso.smartcontract.com, Native app) on a local node: chainlink admin login device flow approved in the browser with a groups claim that also carries unrelated groups, chainlink jobs list on the issued session, UI login with PKCE. A scripted run checked each limit above against the live node: plaintext node URL refused, no verification_uri_complete, a non-allow-listed client and forwarded headers from an untrusted peer refused with 403, per-client cap and limiter, abandoned flows released, /oidc-login limiter per IPv4 and per IPv6 /48, and the start/success events joined on the fingerprint

Notes

  • Rebased onto develop at f0e305c49d06 on 29 October 2026. Head c2468e864. The OIDC login-state migration is 0310_oidc_login_state.sql. It was edited in place on this branch, so a database that ran an earlier revision of it must drop oidc_device_flows and oidc_pending_auth and delete goose row 310 before starting this build.
  • Requires the IdP app to enable the Device Authorization grant and register the per-node sign-in redirect URIs (Native app). Give the app a distinctive, environment-specific name and, where the IdP supports it, require step-up MFA for device approvals, so the approval screen clearly identifies the node.
  • The local email/password CLI path is unchanged and remains as break-glass for OIDC nodes.

@github-actions

github-actions Bot commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

✅ No conflicts with other open PRs targeting develop

@trunk-io

trunk-io Bot commented Jun 18, 2026 •

Copy link
Copy Markdown

Static Badge   Static Badge   Static Badge

View Full Report ↗︎ ⋅ Docs

@harry-anderson
harry-anderson marked this pull request as ready for review June 19, 2026 03:34
@harry-anderson
harry-anderson requested review from a team as code owners June 19, 2026 03:34
@harry-anderson
harry-anderson force-pushed the feature/oidc-cli-device-flow branch 2 times, most recently from 6d2bffb to 4851cc5 Compare July 11, 2026 08:45
@cl-sonarqube-production

Copy link
Copy Markdown

@harry-anderson
harry-anderson requested a review from a team as a code owner July 11, 2026 09:21
@github-actions

Copy link
Copy Markdown
Contributor

This PR is stale because it has been open 60 days with no activity.
Remove the stale label, comment, or update this PR to prevent this PR from being closed in 7 days.

@github-actions github-actions Bot added the Stale label Sep 10, 2026
@bolekk

bolekk commented Sep 14, 2026

Copy link
Copy Markdown
Contributor

HI, can we close this one? It's pinging people via the DX bot.

@github-actions github-actions Bot removed the Stale label Sep 15, 2026
@bolekk

bolekk commented Sep 28, 2026

Copy link
Copy Markdown
Contributor

Closing due to inactivity (It's pinging people via the DX bot.). cc @harry-anderson

@bolekk bolekk closed this Sep 28, 2026
@harry-anderson harry-anderson reopened this Oct 6, 2026
@harry-anderson
harry-anderson marked this pull request as draft October 6, 2026 02:59
@harry-anderson
harry-anderson force-pushed the feature/oidc-cli-device-flow branch 2 times, most recently from 6eddb92 to 8f757b6 Compare October 6, 2026 04:02
@cl-sonarqube-production

Copy link
Copy Markdown

harry-anderson and others added 7 commits October 29, 2026 02:21
Extend the existing OIDC operator-UI auth to the CLI using the OAuth 2.0
device authorization grant (RFC 8628), brokered by the node so the
provider device_code never reaches the CLI.

- Always send PKCE (RFC 7636) on the authorization-code flow; make the
  OIDC ClientSecret optional so a public/native client works while
  confidential deployments stay unchanged.
- Extract issueSessionFromIDToken so the browser exchange and the device
  flow share one verification + role-mapping + session-creation path.
- Add /oidc-device/start and /oidc-device/poll endpoints and a CLI
  device-flow cookie authenticator; RemoteLogin branches on OIDC and
  keeps the local email/password path as break-glass.
Add a mock OpenID Connect provider (discovery + JWKS + device + token
endpoints, RSA-signed id_tokens) so the real go-oidc verifier is
exercised end to end rather than stubbed.

Covers issueSessionFromIDToken and the device-flow poll path:
valid-token session creation, wrong-audience rejection (auth-bypass
guard), expiry enforcement, unmatched-group rejection, and per-group
RBAC role mapping.
- go mod tidy: promote go-jose/v4 to a direct dependency (used by the
  mock IdP test).
- errorlint: wrap the role-mapping error with %w.
- testifylint: use require for error assertions; assert (not require)
  inside the mock node's HTTP handlers.
- modernize: range-over-int loops in tests.
- paralleltest: add t.Parallel to the new tests.
- gosec: set Secure/HttpOnly/SameSite on the mock session cookie.
- Close a double-poll race in handleDevicePoll: add
  deviceFlowStore.consumeIfDone, which checks the terminal state and
  removes the handle in a single critical section, so two concurrent
  polls on a completed handle can no longer both be issued the session
  cookie. Add a racing-pollers test asserting a single winner.
- Redact device_handle in request body logging so the live bearer
  handle is not written to debug logs.
- Emit one method-tagged success audit event per login path
  (oidc_exchange, device_flow, local_admin), each carrying email and
  resolved role. issueSessionFromIDToken now returns the role and no
  longer audits success itself, removing the device path's duplicate,
  role-less event.
- Correct the misleading oidc_user_api_tokens comment: no upstream
  revocation sync exists for OIDC and the mechanism must stay disabled.
- Dedicated pre-auth rate limits on /oidc-device/start and /poll
- Per-IP concurrent device-flow cap (plus existing global cap)
- Reserve store slot before outbound IdP DeviceAuth calls
- Server-side PKCE verifier + OIDC nonce (not in session cookie)
- Nonce verification on browser id_token path
- Reject empty/invalid email claims
- Delete orphan oidc_sessions if cookie Save fails or handle expires
- Stricter CLI /oidc-enabled probe (require enabled:true JSON)
- Document multi-replica sticky-session requirement
Register handles in the store before calling pollDeviceToken so the
orphan-session guard does not abandon intentional e2e tests. Rename
the add() error binding to avoid shadowing err (govet).
Device-flow rate limiting pulls in github.com/ulule/limiter/v3. Submodules
that replace the root module need it as an indirect require so go generate
does not fail with "updates to go.mod needed".
Develop renamed newHttpClient to newHTTPClient, and the authenticator
logger field is the common sugared logger. The CLI client and tests
follow that.
Store browser login state and device-flow results in Postgres so any replica can finish a login. The provider device code stays on the replica that started the flow. Cap device-flow lifetime at five minutes, reject a verification URI whose host does not match the provider, and refuse CLI device login when TLS verification is disabled. When the socket peer is a private proxy, device-flow limits use the rightmost X-Forwarded-For address. Reject group claims outside the configured role groups, and disable OIDC API tokens.
Rename the expiry bound so it does not shadow cap, walk X-Forwarded-For from the right with slices.Backward, and return one sentinel when OIDC API tokens are refused.
develop already ships 0309_relax_bhs_bhf_coordinator_constraints.sql.
A second 0309 file fails goose at startup, so the OIDC login tables
move to the next version.
@harry-anderson
harry-anderson force-pushed the feature/oidc-cli-device-flow branch from 8f757b6 to 381d795 Compare October 29, 2026 02:23
Drop the check that rejected any groups claim containing a group outside
the four configured role groups. Real users belong to many IdP groups;
role mapping already ignores unknown groups and picks the highest
configured role.

The device poll response now carries a reason code (no_role, denied,
expired, abandoned, failed). The CLI maps it to its own text instead of
"denied or expired", so a user with no matching role group is told so.

OIDC role-mapping failures now log as AUTH_LOGIN_FAILED_OIDC instead of
AUTH_LOGIN_FAILED_2FA.
At debug level the request logger printed the OIDC code and state from
the /signin query and the /oidc-exchange body. Add both keys to the
redaction list, next to device_handle.
Device login now needs WebServer.OIDC.DeviceFlowAllowedCIDRs. Empty turns
it off and requests from outside the list get 403 before any rate limiter,
database write or IdP call. The node no longer forwards
verification_uri_complete, so the operator always types the user code.

X-Forwarded-For is believed only from WebServer.OIDC.TrustedProxyCIDRs,
walked from the right. A catch-all prefix is rejected. Rate limits and
per-client caps count per IPv4 address or IPv6 /64.

A device flow the CLI stops polling for max(30s, 3 intervals) frees its
slot, stops polling the IdP, and drops any session it minted. /oidc-login
gets its own limiter and caps pending rows at 50 per client and 10,000
total.

New AUTH_DEVICE_FLOW_STARTED event with client IP, User-Agent and a handle
fingerprint. Success and failure events carry the same fingerprint and
start IP; success adds the redeeming IP and client_ip_mismatch.

The CLI refuses device login unless the node URL is https (http only for
loopback) and refuses a verification URI that is not https.
…up sign-in by IPv6 /48

A device login request that carries X-Forwarded-For, X-Real-IP or Forwarded
from a peer outside TrustedProxyCIDRs now gets 403. Before, a node behind a
load balancer that was left out of TrustedProxyCIDRs but sat inside
DeviceFlowAllowedCIDRs let every caller behind it in, because each one
resolved to the load balancer's address. The first refusal logs a Warn that
names TrustedProxyCIDRs.

The /oidc-login limiter and the oidc_pending_auth per-client cap now count an
IPv6 client per /48 instead of per /64. One /56 held 256 buckets, enough
for one subscriber to fill the 10,000-row cap and stop browser sign-in for
everyone for 15 minutes. Device-flow routes keep /64 buckets.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants