Repository navigation
Add device authorization for Railgrid CLI login - #1095
Conversation
|
[APPROVALNOTIFIER] This PR is NOT APPROVED This pull-request has been approved by: The full list of commands accepted by this bot can be found here. DetailsNeeds approval from an approver in each of these files:Approvers can indicate their approval by writing |
|
@mjudeikis-bot review |
mjudeikis
left a comment
There was a problem hiding this comment.
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,HandleCallbackin full,NewHandler,RegisterRoutes, andSetTrustedProxiesinhandler.go. Alsosharedstore(CreateIfAbsent,Take,expired,objectName,RunGC), theget_token.gorefresh and persist path,token.go,logout.go,whoami.goexecOIDCArgs,restapi/kubeconfig.go, and the sharedstore wiring inhub/server.go. - Correctness: the refresh path keeps
cache.Accountbecause it is loaded from JSON, so rotated tokens are saved under the right key. TheSaveLoginTokenCacherollback is sound. One Note is below. - Concurrency:
AllowIntervaluses resourceVersion conflicts as the cross-replica gate, and a conflict maps toslow_down, which is acceptable.TakeafterGetintakeDeviceBrowserStateis 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. TheLoginResponsetype is unchanged and the token cache gains an optionalaccountfield. Legacy cache files still decode and keep the legacy key whenAccountis empty. - Security: one Warning inline (no confirmation step before the IdP redirect). User code is 40 bits and
Takeis 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 thelogin_device_test.goandtoken_cache_test.goadditions 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 veton 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(noapis/change) and./pkg/hubtests. 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.
| 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) |
There was a problem hiding this comment.
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.| return | ||
| } | ||
| pendingKey := "pending:" + request.PollKey | ||
| ok, err := h.deviceStore.CreateIfAbsent(ctx, pendingKey, nil, request.ExpiresAt) |
There was a problem hiding this comment.
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.
| ClientID: h.oidcConfig.ClientID, | ||
| } | ||
| if isDevice { | ||
| deviceFinished = true |
There was a problem hiding this comment.
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|
@mjudeikis-bot PTAL |
mjudeikis
left a comment
There was a problem hiding this comment.
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.buildWorkspaceKubeconfignow appends--oidc-account=+userID(kubeconfig.go:146).userIDistc.User, the User CR name. That is the same valueseedUserreturns andresp.UserIDcarries (handler.go:419), so the cache key matches whatloginwrites.TestDownloadKubeconfig_InstallVariantnow asserts the arg. - Resolved: no confirmation before the IdP redirect.
approveDeviceLoginnow renders a confirm page with the network prefix and request time. TheconfirmPOST needs a per-code__Host-cookie that matches the form'sconfirmationvalue, and only then doesTakeconsume the code. The page is served withframe-ancestors 'none', anddocs/security.mddocuments the residual risk. - Resolved: a failed result write left the CLI polling.
completeDeviceLoginnow returns whether the result was stored, so theserver_errorfallback runs. The fallback uses a detached 5s context and ignoresErrNotFound. The test injects a result-write failure and checks that the CLI pollsserver_error. - Resolved: unbounded unauthenticated start.
startnow has its own limiter at 6/min per IP, and an incomplete start deletes itspending: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,deviceFinisheduse).RegisterRoutesandSetTrustedProxies, including both call orders againstregisterDeviceLoginLimits.proxy.ClientIPandnewRateLimiter.requireTenantContext,tenant.TenantContext.UserandseedUser.buildWorkspaceKubeconfigand its caller.generateKubeconfig(it writes no account arg, butmergeKubeconfigadds one for CLI logins).cacheKey,LoadTokenCacheandSaveLoginTokenCache.execOIDCArgsinwhoami.go, andget_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:
Takeis single-winner, so concurrent confirm POSTs race safely. The new limiter'strustedProxiesis written bySetTrustedProxiesthe same way the existingdeviceLimiteris.go test -race ./pkg/server/authis 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.mdis 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 byCrossOriginProtection. 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 veton 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/apiurlall pass.go test -race ./pkg/server/authpasses.make lintreports 0 issues.make verify-boilerplateok.make docs-clileaves no diff. - Not run:
make verify-codegen(noapis/change),./pkg/hubtests, and any e2e. No §7 suite covers device login without a live OIDC hub, and the PR body says live sign-in is unverified.
| return | ||
| } | ||
|
|
||
| issued := false |
There was a problem hiding this comment.
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| now := time.Now() | ||
| request := deviceRequest{ | ||
| PollKey: deviceDigest(deviceCode), StartedAt: now, ExpiresAt: now.Add(deviceLoginTTL), RecipientKey: key, | ||
| Network: deviceRequesterNetwork(proxy.ClientIP(r, h.deviceStartLimiter.trustedProxies)), |
There was a problem hiding this comment.
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))
}| _ = deviceCodePage.Execute(w, "Enter the code again to review the sign-in request.") | ||
| return | ||
| } | ||
| load = h.deviceStore.Take |
There was a problem hiding this comment.
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"})
}|
/test |
|
/test all |
Summary
railgrid login --deviceso 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.Validation
go test -count=1 ./pkg/apiurl ./pkg/server/auth ./pkg/cli/auth ./pkg/cli/cmd ./pkg/hub ./pkg/hub/sharedstoremake fix-lintandmake lintmake build-hub docs-cli GOFLAGS=-buildvcs=falseLive device sign-in against console-dev remains unverified. It requires the updated CLI and an updated OIDC-enabled hub backed by kcp.