Repository navigation
feat(oidc): CLI login via device authorization grant + PKCE - #22889
Draft
harry-anderson wants to merge 18 commits into
Draft
harry-anderson wants to merge 18 commits into
harry-anderson wants to merge 18 commits into
Conversation
Contributor
|
✅ No conflicts with other open PRs targeting |
harry-anderson
marked this pull request as ready for review
June 19, 2026 03:34
product-security-plaid-production
Bot
requested review from
bolekk and
pavel-raykov
June 19, 2026 03:34
harry-anderson
force-pushed
the
feature/oidc-cli-device-flow
branch
2 times, most recently
from
July 11, 2026 08:45
6d2bffb to
4851cc5
Compare
|
Contributor
|
This PR is stale because it has been open 60 days with no activity. |
Contributor
|
HI, can we close this one? It's pinging people via the DX bot. |
Contributor
|
Closing due to inactivity (It's pinging people via the DX bot.). cc @harry-anderson |
harry-anderson
marked this pull request as draft
October 6, 2026 02:59
harry-anderson
force-pushed
the
feature/oidc-cli-device-flow
branch
2 times, most recently
from
October 6, 2026 04:02
6eddb92 to
8f757b6
Compare
|
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
force-pushed
the
feature/oidc-cli-device-flow
branch
from
October 29, 2026 02:23
8f757b6 to
381d795
Compare
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.
…n parallel router tests
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.




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 (theuserstable). This adds a real OIDC login path for the headless CLI without standing up a second identity app.What changed
POST /oidc-device/startandPOST /oidc-device/pollendpoints. 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 providerdevice_codenever 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 byoauth2.DeviceAccessToken(which honoursinterval/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.WebServer.OIDC.DeviceFlowAllowedCIDRslists 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.WebServer.OIDC.TrustedProxyCIDRslists the load balancers and proxies in front of the node. The OIDC login routes believeX-Forwarded-Foronly 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 carriesX-Forwarded-For,X-Real-IPorForwardedfrom 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 globalRemoteIPHeaderssetting is unchanged.verification_uri_completeto 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, andhttpis accepted only for a loopback address orlocalhost.handleSignIngenerates a PKCE verifier and an OIDC nonce, stores both server-side keyed bystate, and puts onlystatein the session cookie. It sends the S256 challenge.handleTokenExchangetakes the verifier and nonce from that store, single-use, and binds the verifier on exchange. The OIDCClientSecretis 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.issueSessionFromIDTokenso 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.CookieAuthenticatorincore/cmd.RemoteLoginuses it when the node reports OIDC and no-fileis given, and keeps the local email/password path as break-glass. The CLI refuses device login unless--remote-node-urluses 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./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-loginanswers 503 withRetry-After.AUTH_DEVICE_FLOW_STARTEDevent 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 andclient_ip_mismatch, the signature of a forwarded or phished approval. Denied device flows are recorded asAUTH_LOGIN_FAILED_DEVICEwith 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 asAUTH_LOGIN_FAILED_OIDCwith the claim set, not under the 2FA event.codeandstateand the device handle.FindUserByAPITokenandSetAuthTokenreturn an error even ifUserAPITokenEnabledis true.New configuration
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) insideDeviceFlowAllowedCIDRs: 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 releasego test ./core/cmd/OIDC/device/login tests, including plaintext node URL, non-https verification URI, skip-verify and 403-from-allow-list refusalserrNoMatchingRole, per-group RBAC role mapping, full device-flow poll path, wrong-audience device token rejectedExtendRouter: 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 withclient_ip_mismatch, sign-in limiter per client and per IPv6 /48core/config/docs,core/services/chainlink), request-log redaction testsso.smartcontract.com, Native app) on a local node:chainlink admin logindevice flow approved in the browser with a groups claim that also carries unrelated groups,chainlink jobs liston the issued session, UI login with PKCE. A scripted run checked each limit above against the live node: plaintext node URL refused, noverification_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-loginlimiter per IPv4 and per IPv6 /48, and the start/success events joined on the fingerprintNotes
f0e305c49d06on 29 October 2026. Headc2468e864. The OIDC login-state migration is0310_oidc_login_state.sql. It was edited in place on this branch, so a database that ran an earlier revision of it must dropoidc_device_flowsandoidc_pending_authand delete goose row 310 before starting this build.