Skip to content

Add device authorization for Railgrid CLI login - #1095

Merged
cwilhit merged 4 commits into
mainfrom
codex/device-login
Nov 14, 2026
Merged

cwilhit merged 4 commits into
mainfrom
codex/device-login

Conversation

@cwilhit

@cwilhit cwilhit commented Nov 14, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • Add railgrid login --device so an operator can sign in from a browser on another machine. The remote CLI polls the hub over HTTPS and saves the kubeconfig and refresh credentials locally.
  • Share device login state across hub replicas, encrypt each result to the requesting CLI, and keep it available until an acknowledgment proves decryption or the request expires.
  • Give device traffic a separate rate limit. Scope new OIDC cache entries to the account and write the kubeconfig atomically.

Validation

  • go test -count=1 ./pkg/apiurl ./pkg/server/auth ./pkg/cli/auth ./pkg/cli/cmd ./pkg/hub ./pkg/hub/sharedstore
  • make fix-lint and make lint
  • make build-hub docs-cli GOFLAGS=-buildvcs=false

Live device sign-in against console-dev remains unverified. It requires the updated CLI and an updated OIDC-enabled hub backed by kcp.

@cwilhit
cwilhit requested a review from mjudeikis as a code owner November 14, 2026 15:07
@railgrid-prow

railgrid-prow Bot commented Nov 14, 2026

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by:
Once this PR has been reviewed and has the lgtm label, please assign mjudeikis for approval. For more information see the Code Review Process.

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@cwilhit

cwilhit commented Nov 14, 2026

Copy link
Copy Markdown
Collaborator Author

@mjudeikis-bot review

@cwilhit
cwilhit removed the request for review from mjudeikis November 14, 2026 15:08

@mjudeikis mjudeikis left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Three findings, none Critical. The hub-side crypto and binding design holds up: the result is HPKE-sealed to a CLI-held key, the browser cookie is checked before the state is consumed, and the ack nonce is verified before deletion.

Not anchored

Warning: kubeconfigs downloaded from the hub carry no --oidc-account, so they read a cache the new login no longer writes.
pkg/hub/restapi/kubeconfig.go:144 builds the exec args get-token --oidc-issuer-url=... --oidc-client-id=... for the /kubeconfig download. This PR moves every new login's cache to the account-scoped key. saveOIDCLogin sets Account: resp.UserID and mergeKubeconfig appends --oidc-account= (login.go:310). get-token therefore looks up the legacy key for a downloaded kubeconfig, finds nothing, and fails with "no valid token found; please run 'railgrid login' first". The same user, issuer and client worked before this PR through the shared key. buildWorkspaceKubeconfig already receives userID, so the fix is small: args = append(args, "--oidc-account="+userID) in the OIDC branch, plus a test in pkg/hub/restapi that the arg is present. I did not run this end to end. I traced it from the caller at kubeconfig.go:91 and from cacheKey in token_cache.go.

Checked

  • Read beyond the diff: HandleAuthorize, HandleCallback in full, NewHandler, RegisterRoutes, and SetTrustedProxies in handler.go. Also sharedstore (CreateIfAbsent, Take, expired, objectName, RunGC), the get_token.go refresh and persist path, token.go, logout.go, whoami.go execOIDCArgs, restapi/kubeconfig.go, and the sharedstore wiring in hub/server.go.
  • Correctness: the refresh path keeps cache.Account because it is loaded from JSON, so rotated tokens are saved under the right key. The SaveLoginTokenCache rollback is sound. One Note is below.
  • Concurrency: AllowInterval uses resourceVersion conflicts as the cross-replica gate, and a conflict maps to slow_down, which is acceptable. Take after Get in takeDeviceBrowserState is single-winner. No finding.
  • Tenancy/kcp: the device store is the hub-system namespace via the controllers config. There are no workspace-scoped calls and no provider paths. Not applicable beyond that.
  • Provider contract: not applicable, no provider, manifest or chart change.
  • API/codegen: no apis/ change. The LoginResponse type is unchanged and the token cache gains an optional account field. Legacy cache files still decode and keep the legacy key when Account is empty.
  • Security: one Warning inline (no confirmation step before the IdP redirect). User code is 40 bits and Take is single-use. Poll and ack are rate-limited per IP. Browser-state binding is checked before consume. The CLI refuses redirects and non-HTTPS verification URLs. One Note on unauthenticated store writes.
  • Portal: not applicable, no portal change.
  • Tests: TestDeviceLoginAcrossHubReplicas, TestDeviceRateLimitDoesNotExhaustBrowserSessionBudget, TestAllowIntervalAcrossReplicas, and the login_device_test.go and token_cache_test.go additions cover the new paths. I did not mutate the code to check that they fail without it. No test covers the hub-generated kubeconfig args.
  • Commands run:
    • go build ./pkg/... ./cmd/...: ok.
    • go vet on the changed packages: clean.
    • go test -count=1 ./pkg/apiurl ./pkg/server/auth ./pkg/cli/auth ./pkg/cli/cmd ./pkg/hub/sharedstore: all pass.
    • make lint: 0 issues.
    • make verify-boilerplate: ok.
  • Not run: make verify-codegen (no apis/ change) and ./pkg/hub tests. The PR body says live device sign-in against console-dev is unverified, and I did not run it either. I ran no e2e suite because none of §7's suites covers CLI device login without a live OIDC-enabled hub.

Comment thread pkg/server/auth/device.go
return
}
http.SetCookie(w, deviceBrowserCookie(state, browserSecret, int(time.Until(request.ExpiresAt).Seconds())+1))
http.Redirect(w, r, h.oauth2Config.AuthCodeURL(state, oauth2.S256ChallengeOption(record.Verifier)), http.StatusSeeOther)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warning: approving a user code redirects straight to the IdP, so a phished code hands the attacker the victim's credentials.
An attacker runs railgrid login --device on their own machine and gets a code. They tell the victim it is a support or verification step. The victim opens the genuine hub URL, enters the code, and signs in with their own IdP account. The hub then seals the victim's ID token, refresh token and kubeconfig to the attacker's key (RFC 8628 §5.4). Nothing on the approval path tells the victim what they are approving: approveDeviceLogin calls authorizeDeviceBrowser and redirects immediately. Add an interstitial before the redirect that shows the requester's coarse IP and time and asks for an explicit confirm. This needs the request context stored in deviceRequest at start. If the maintainers accept the standard device-flow risk, say so in docs/security.md.

// startDeviceLogin: record request context
request.RequesterIP = clientIP(r)
// approveDeviceLogin: render a confirm page naming request.RequesterIP and the
// time, and only call authorizeDeviceBrowser on a second POST with confirm=1.

Comment thread pkg/server/auth/device.go
return
}
pendingKey := "pending:" + request.PollKey
ok, err := h.deviceStore.CreateIfAbsent(ctx, pendingKey, nil, request.ExpiresAt)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note: the unauthenticated start endpoint writes Secrets into the hub-system namespace.
Each POST /auth/device/start creates two Secrets (pending: and user:) that live for 10 minutes. The 120/min limiter is per replica and per IP, held in memory (registerDeviceLoginLimits). One client behind many addresses, or a limiter bypass via spoofed forwarding headers when the trusted-proxy list is misconfigured, can grow that namespace until the 10-minute expiry, and RunGC only sweeps on its own interval. Consider a global cap, for example counting live entries in startDeviceLogin, or a much lower per-IP budget for start than for poll.

Comment thread pkg/server/auth/handler.go Outdated
ClientID: h.oidcConfig.ClientID,
}
if isDevice {
deviceFinished = true

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note: a failed result write after the callback leaves the CLI polling until expiry.
deviceFinished is set to true before completeDeviceLogin runs. If storeDeviceResult fails with a store error (a 503 to the browser), the deferred server_error fallback does not run, so the CLI keeps getting authorization_pending for up to 10 minutes. The browser state was already consumed, so the user cannot retry this sign-in. Set the flag only after a successful store, or have completeDeviceLogin return an error and let the defer record server_error.

err := h.completeDeviceLogin(w, r, device, deviceResult{LoginResponse: resp})
deviceFinished = err == nil

@cwilhit

cwilhit commented Nov 14, 2026

Copy link
Copy Markdown
Collaborator Author

@mjudeikis-bot PTAL

@mjudeikis mjudeikis left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review of aaeb7e2. All three earlier findings are resolved, and I found no Critical issues. One Warning and two Notes remain, on code the fix commit added.

Earlier findings

  • Resolved: the downloaded kubeconfig had no --oidc-account. buildWorkspaceKubeconfig now appends --oidc-account= + userID (kubeconfig.go:146). userID is tc.User, the User CR name. That is the same value seedUser returns and resp.UserID carries (handler.go:419), so the cache key matches what login writes. TestDownloadKubeconfig_InstallVariant now asserts the arg.
  • Resolved: no confirmation before the IdP redirect. approveDeviceLogin now renders a confirm page with the network prefix and request time. The confirm POST needs a per-code __Host- cookie that matches the form's confirmation value, and only then does Take consume the code. The page is served with frame-ancestors 'none', and docs/security.md documents the residual risk.
  • Resolved: a failed result write left the CLI polling. completeDeviceLogin now returns whether the result was stored, so the server_error fallback runs. The fallback uses a detached 5s context and ignores ErrNotFound. The test injects a result-write failure and checks that the CLI polls server_error.
  • Resolved: unbounded unauthenticated start. start now has its own limiter at 6/min per IP, and an incomplete start deletes its pending: key.

Not anchored
Note: kubeconfigs downloaded before this PR keep reading the legacy cache key. A kubeconfig downloaded earlier has no --oidc-account, so get-token loads the unscoped key (token_cache.go:62). After this PR, railgrid login writes only the account-scoped key and never refreshes the legacy file. Once that legacy refresh token expires or rotates elsewhere, the old kubeconfig fails with "run 'railgrid login' first" until the user re-downloads it. This is the intended scoping, so I am not asking for code. Please add a release note or a line in the CLI docs saying to re-download hub kubeconfigs.

Checked

  • Read beyond the diff: the whole of device.go (start, approve, authorize, take-state, complete, store-result, poll, ack). HandleCallback (device branch, deferred fallback, deviceFinished use). RegisterRoutes and SetTrustedProxies, including both call orders against registerDeviceLoginLimits. proxy.ClientIP and newRateLimiter. requireTenantContext, tenant.TenantContext.User and seedUser. buildWorkspaceKubeconfig and its caller. generateKubeconfig (it writes no account arg, but mergeKubeconfig adds one for CLI logins). cacheKey, LoadTokenCache and SaveLoginTokenCache. execOIDCArgs in whoami.go, and get_token.go.
  • Correctness: the confirm flow is Get on step 1 and Take on step 2. The wrong-cookie, short-confirmation and expired-code paths all return 400 with the code form. The fallback skips ErrNotFound. Two findings below.
  • Concurrency: Take is single-winner, so concurrent confirm POSTs race safely. The new limiter's trustedProxies is written by SetTrustedProxies the same way the existing deviceLimiter is. go test -race ./pkg/server/auth is clean.
  • Tenancy/kcp: not applicable. The change touches the hub-system store and the CLI, with no workspace-scoped calls.
  • Provider contract: not applicable.
  • API/codegen: no apis/ change. docs/cli/railgrid_login.md is regenerated.
  • Security: the code-phishing path now has a confirmation step. The cookie is bound to the code and is __Host-, Secure, HttpOnly and Lax. Cross-origin POSTs are blocked by CrossOriginProtection. Template output is auto-escaped. No credential reaches a page or a log. One Note on the displayed network (inline).
  • Portal: not applicable. The hub-rendered HTML pages carry no rendered evidence, but the PR makes no portal change.
  • Tests: the confirm flow, the store-failure fallback and the start limiter are exercised, and each would fail without the change. The start-failure cleanup defer and deviceRequesterNetwork (IPv6, v4-mapped, unparseable input) have no test (inline).
  • Commands: go build ./pkg/... ./cmd/... ok. go vet on auth, restapi, cli and sharedstore is clean. go test -count=1 ./pkg/server/auth ./pkg/hub/restapi ./pkg/cli/auth ./pkg/cli/cmd ./pkg/hub/sharedstore ./pkg/apiurl all pass. go test -race ./pkg/server/auth passes. make lint reports 0 issues. make verify-boilerplate ok. make docs-cli leaves no diff.
  • Not run: make verify-codegen (no apis/ change), ./pkg/hub tests, and any e2e. No §7 suite covers device login without a live OIDC hub, and the PR body says live sign-in is unverified.

Comment thread pkg/server/auth/device.go
return
}

issued := false

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warning: the new start-failure cleanup has no test.
The deferred Delete of pending: runs when CreateIfAbsent for user: errors or all three code attempts collide. It is new server-path behaviour on an unauthenticated endpoint, and nothing in device_test.go makes user: creation fail and then checks that the pending: key is gone. If the defer regressed, orphaned pending: Secrets would sit for 10 minutes and nothing would catch it. The store double already supports failure injection (failNextResultWrite), so a user: variant is small.

// testDeviceStore: fail the user-code write, then assert no pending key remains
if s.failNextUserWrite && strings.HasPrefix(key, "user:") { s.failNextUserWrite = false; return false, errors.New("injected") }
// test: start -> 503, then assert no key with prefix "pending:" remains in store.values

Comment thread pkg/server/auth/device.go Outdated
now := time.Now()
request := deviceRequest{
PollKey: deviceDigest(deviceCode), StartedAt: now, ExpiresAt: now.Add(deviceLoginTTL), RecipientKey: key,
Network: deviceRequesterNetwork(proxy.ClientIP(r, h.deviceStartLimiter.trustedProxies)),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note: the confirmation page shows the proxy's address when --trusted-proxy-cidrs is unset.
proxy.ClientIP ignores forwarding headers unless the peer is in the trusted list, and the flag help says to set it behind an ingress. On a hub behind an ingress without it, every request has the ingress as its peer, so the page tells the victim "Request network 10.0.0.0/24" for any requester. That looks like an internal, trustworthy origin and weakens the phishing defence this page exists for. Show the network only when trusted proxies are configured, or say "Unavailable" otherwise. A table test for deviceRequesterNetwork (IPv6, v4-mapped, unparseable) is also missing.

network := "Unavailable"
if len(h.deviceStartLimiter.trustedProxies) > 0 {
	network = deviceRequesterNetwork(proxy.ClientIP(r, h.deviceStartLimiter.trustedProxies))
}

Comment thread pkg/server/auth/device.go
_ = deviceCodePage.Execute(w, "Enter the code again to review the sign-in request.")
return
}
load = h.deviceStore.Take

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note: a store failure after the confirm Take loses the code and leaves the CLI polling.
On the confirm POST, Take consumes user:<code> before authorizeDeviceBrowser runs. If its CreateIfAbsent for oidc:<state> then fails, the browser gets a 503. The code cannot be re-entered, and pending: is still live, so the CLI polls authorization_pending for up to 10 minutes. The callback path now records server_error for this class of failure, but this path does not. Have authorizeDeviceBrowser report failure and record server_error for the request on that branch.

if !h.authorizeDeviceBrowser(w, r, request) {
	_ = h.storeDeviceResult(context.WithoutCancel(r.Context()), request, deviceResult{Error: "server_error"})
}

@cwilhit

cwilhit commented Nov 14, 2026

Copy link
Copy Markdown
Collaborator Author

/test

@cwilhit

cwilhit commented Nov 14, 2026

Copy link
Copy Markdown
Collaborator Author

/test all

@cwilhit
cwilhit merged commit 0729f2d into main Nov 14, 2026
10 of 18 checks passed
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