Skip to content

fix(auth): send a stored CLI session only to the cloud that issued it - #4921

Merged
thymikee merged 11 commits into
mainfrom
fix/cloud-login-origin
Nov 22, 2026
Merged

thymikee merged 11 commits into
mainfrom
fix/cloud-login-origin

Conversation

@thymikee

@thymikee thymikee commented Nov 21, 2026 •

Copy link
Copy Markdown
Member

Summary

A stored CLI session credential goes only to the cloud that issued it, and no auth request carries a credential or device code to another origin.

  • A refresh runs at the stored URL. An AGENT_DEVICE_CLOUD_BASE_URL with another origin fails with cloud_login_origin_mismatch before any request. A rotation is stored only over a record with the same cloudBaseUrl.
  • The session file moves to format version 2, which only the origin-checked login writes. A version 1 record fails with cli_session_issuer_unverified and the hint Run agent-device auth login.
  • Device-auth start, poll and refresh follow at most three redirects on the original origin. A 307 or 308 resends the POST; a 301, 302 or 303 continues as a GET without the body. Any other redirect fails with cloud_auth_redirect_refused before a request reaches its target.

auth status wording for a version 1 session is tracked in #4849.

Before / after

version 1 session, refresh:         base: POSTs the credential        head: cli_session_issuer_unverified, no request
override at another origin:         base: POSTs the credential there  head: cloud_login_origin_mismatch, no request
poll answered 308 to another origin: base: resends the device code    head: cloud_auth_redirect_refused, one request

Validation

At 23803c95fd: cloud-auth-request.test.ts and auth-session-cloud-origin.test.ts (22 passed), typecheck, lint and format pass. The src/cli suite, check:command-docs and check:fallow last passed at 1abd533d63 (1579 tests); CI covers them at this head. cloud-auth-request.test.ts uses Node's fetch on loopback servers; removing the credential, origin, hop-limit or GET-switch check, using redirect: 'follow', or treating an empty Location as missing fails it. No real cloud exercised.


Run Proof on this PR
Open in [code]smith · Need help on this PR? Tag @codesmith-bot with what you need.

View guided diff Turn on auto-fix

@github-actions

github-actions Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Size Report

Metric Base Current Diff
Installed (including dependencies) 6.51 MB 6.51 MB +2.1 kB
Package (unpacked) 6.51 MB 6.51 MB +2.1 kB
Package (download) 1.98 MB 1.98 MB +554 B

Startup median (7 runs, lower is better):

Scenario Base Current Diff
CLI --version 21.7 ms 23.6 ms +1.9 ms
CLI --help 49.3 ms 49.8 ms +0.6 ms

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

The change binds a stored CLI session to its issuing cloud as intended, but five problems remain at af2a887. A second independent pass found them.

A second independent pass found that existing version-1 session records can still name an origin that did not issue the credential (auth-session.ts:434). Before this change, a login for origin A could follow a device-auth poll redirect to origin B and store B's credential under A's URL (base a9750b5, src/cli/auth-session.ts lines 252-274 and 575-581). The base could also save B's rotated credential under A when the environment override was set. This head accepts those records and posts the credential to A when the override is unset. Please separate records created with a verified issuer binding from legacy version-1 records. A legacy record whose issuer cannot be established from persisted state should require a fresh login before any refresh.

A second independent pass found that a late rotation can replace the credential of a different origin (auth-session.ts:483). Two origins backed by a cloned session store can return the same session ID and initial credential. If a refresh at A is in flight while a login at B replaces the record, the lock-protected comparison accepts B's record and stores A's replacement under B's URL. The next refresh then sends it to B. The saved origin must be part of the lock-protected comparison before a rotation is applied.

A second independent pass found that same-origin auth redirects now fail (auth-session.ts:599). If a cloud answers a device-auth start, device-auth poll, or CLI-session refresh POST with a 307 or 308 to its canonical path, the base follows it. This head fails at the first redirect, even when the stored issuer and the requested origin match. A cross-origin redirect also gives a generic fetch failure instead of the origin-mismatch reason. The rule should be: every redirect target is resolved and its origin checked against the original request origin before it is followed, within a bounded chain. A cross-origin target should return a typed refusal before it is followed.

A second independent pass found that a same-origin override changes the identity of an existing cloud connection (auth-session.ts:461). Take a login at https://cloud.example and a named connection created on the base with AGENT_DEVICE_CLOUD_BASE_URL=https://cloud.example/path. If the profile leaves clientId or runId for the CLI to supply, repeating the same connect now hashes the stored URL instead of the override (cloud-profile.ts:43-56). The profile and its path change, and the existing connection is rejected unless the caller passes --force (connection.ts:162-171). The stored URL should stay the refresh destination, and the validated same-origin override should stay the connection identity input.

A second independent pass found that the cloud connect docs no longer match behavior (commands.md:2686). They say connect refreshes a stored CLI session into a short-lived token. With a different cloud API origin set and a valid stored session, connect now stops with cloud_login_origin_mismatch before it fetches the profile. Please qualify the refresh description with the stored-origin rule, and say the caller can log in at the new origin or unset the override.

Not blocking, and these can be taken or left: add one sentence to the AGENT_DEVICE_CLOUD_BASE_URL row in configuration.md that, with a stored login, the variable must name the same origin or the user must run auth login with it; catch the redirect failure in postJson and rethrow a typed AppError with a hint naming the cloud base URL (the default cloud answers the refresh POST with a 307 to /unlock today, and it was already broken at base); compare the stored origin with the origin of the override only when it is set, so a hand-edited malformed stored URL is not reported as an invalid override (also true at base); open a follow-up issue to bind use of the minted access token to a daemonBaseUrl allowed for the issuing cloud, since with both settings it goes to flags.daemonBaseUrl while the refresh credential itself stays home; and split the origin test into two tests with the temp dir removed in a finally, as the sibling tests do.

CI is green: all 17 checks pass or skip at af2a887, and Body rules failed at packet time but passes on rerun. There are no conflicts. The five items above must be fixed before merge.

Not verified here: the new test and the src/cli suite were not run locally, so the claim that the test fails on base comes from reading the base path. No real cloud was exercised; a request to the default cloud showed a same-origin 307 to /unlock on the refresh path, and what a working cloud answers was not tested. The error-reasons.md page appears to be generated from ReasonTable comments, and the generator was not rerun.

@thymikee

Copy link
Copy Markdown
Member Author

Reply to #4921 (comment), at 727d73c:

  • Rotation compares the stored origin (:483): fixed. The locked re-read also requires the same cloudBaseUrl; new test a rotation is not stored over a session that a login moved to another cloud.
  • Refresh destination vs. connection identity (:461, cloud-profile.ts:43-56): fixed. The refresh goes to the stored URL; a validated same-origin override is returned as the connection base URL, as before this PR.
  • Docs (commands.md:2686): fixed; the refresh description states the stored-origin rule, cloud_login_origin_mismatch, and no redirects.
  • Legacy version-1 records (:434): not changed. cloudBaseUrl is a required field of every version-1 record (readCliSession rejects a record without it), and it is the URL the login ran against, so every stored record carries its issuer. A version bump would force every user to log in again for no gain.
  • Bounded same-origin redirects (:599): not changed. The cloud auth endpoints are POST APIs that do not redirect; refusing every redirect is the smaller and safer rule, and a cloud that needs one can serve the final URL. A same-origin redirect chain can be added if a cloud ever needs it.

src/cli tests, typecheck, lint, check:command-docs and check:layering pass.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

At 727d73c, three items from the earlier review are fixed, and two remain open on the code. The two declined items are outside the scope that blocks this PR. CI shows 16 checks with none failing, and there are no conflicts.

A second independent pass found that a version-1 record can already hold cloud A's URL with a credential issued by cloud B. The old login could follow a cross-origin poll redirect and save the response credential under its original login URL. The old refresh could also run against cloud B through the environment override and store B's replacement under A's URL. Both records pass the version-1 parser at auth-session.ts#L296-L310. With the override unset, either refresh path then sends B's credential to A, as in auth-session.ts#L435. This breaks the rule that a credential goes only to the cloud that issued it, even though the request matches the stored URL. The rule to enforce: a stored session is used only when its issuer is established from persisted state. Please version the session format so a fresh login through the origin-checked flow records the issuer. Please also require a fresh login before refreshing any legacy record whose issuer cannot be established.

A second independent pass also found a regression for clouds that serve an auth POST through a 307 or 308 to a working path on the same origin. Before this PR, fetch followed the redirect and kept the POST. Now the shared transport at auth-session.ts#L605 rejects the first response. A redirect at device-auth start stops login from starting. A redirect at device-auth poll stops login from finishing. A redirect at refresh stops a valid stored session from refreshing. The rule to enforce: every auth request, in the shared transport that all three call, follows a bounded redirect chain only when each resolved target has the original request origin. Accepted hops keep Fetch redirect semantics, and cross-origin targets are rejected before anything is resent. Please update the command documentation to describe this behavior.

Not verified here: the new tests and the src/cli suite were not run locally, so regression validity comes from reading the earlier code at a9750b5. Not verified here: any real cloud, since the redirect: 'error' setting is asserted only as the value passed to an injected fetch, not against Node's fetch on a live 307 or 308. The same-origin path override used as the connection identity input was checked by reading auth-session.ts#L461 and cloud-profile.ts, and no test asserts it. For validation, please add a test for each redirect route above that reaches the shared transport with a same-origin 307 or 308 and a cross-origin one. The same-origin case should complete the request, and the cross-origin case should fail without sending a second request. Retarget to main after #4833 merges.

@thymikee
thymikee added this pull request to stack #4951 November 22, 2026 09:06
@thymikee

Copy link
Copy Markdown
Member Author

727d73c now conflicts with main after the latest merges. Please rebase onto main, regenerate any generated docs blocks, and include the two open items from the last review in the same push. The code verdict on 727d73c is unchanged until then.

@thymikee
thymikee force-pushed the fix/cloud-login-origin branch from 727d73c to 6c2535a Compare November 22, 2026 12:10
@thymikee

Copy link
Copy Markdown
Member Author

Rebased onto #4833 (18b6276) at 6c2535a. Both open items are in:

  • Versioned session format: a record is now version 2 with issuerOrigin. A version 1 record, or one whose origin does not match, fails with cli_session_issuer_unverified and a hint to run auth login.
  • Same-origin redirects: auth requests follow up to 3 same-origin 307 or 308 redirects with the same body. A cross-origin redirect, a fourth hop, or a 301, 302 or 303 fails before a second request, each with a typed reason.

Generated docs are regenerated. All 654 src/cli tests pass.

@apex-sentinel-staging

This comment has been minimized.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Apex Sentinel: 1 new finding on c888fd9. The verdict and the full list are in the summary comment.

Comment thread src/cli/auth-session.ts Resolved
@thymikee

Copy link
Copy Markdown
Member Author

At c888fd9 two auth-redirect defects remain, and both need a fix before merge. The conflict from the earlier review is gone, there are no conflicts, and all 21 checks pass.

A second independent pass found that cloud-auth-request.ts:101 can print the stored refresh credential. On the first refresh with a verified session, the issuing cloud can answer with a 307 or 308 and a same-origin Location whose username or password echoes the credential it received. URL.origin excludes user information, so the target passes the origin check and reaches the next fetch at line 45. Node rejects the URL and puts the full URL in its TypeError message. The error normalizer keeps that message (errors.ts:513-538) and cli.ts:665-698 prints it in JSON or on stderr. The normalized message was reproduced with a synthetic credential and this transport. The same route can print a device code echoed in a poll redirect (auth-session.ts:810-815). Please reject any redirect target that carries a username or password before calling fetch. Use the existing unsupported-redirect refusal with a fixed message, and leave out the raw Location and the fetch error.

A second independent pass also found that cloud-auth-request.ts:77 breaks auth routes that worked before. A cloud can accept the auth POST and answer with a same-origin 303 to a result URL that serves the JSON on GET. The old fetch in auth-session.ts followed that redirect without resending the body. This head refuses it before the result request. Device-auth start then cannot begin, poll cannot read the approval, and refresh cannot read the token. The old fetch behavior and the new refusal were reproduced on loopback for 301, 302 and 303. Please keep the bounded origin check on every hop. For an accepted same-origin 301, 302 or 303, switch to GET, drop the body and its content headers, and continue with GET for the rest of the chain. Keep POST and the body for 307 and 308 hops that come before that switch.

Not blocking: issuerOrigin in cli-session-format.ts:10 is accepted only when it equals the origin of cloudBaseUrl, and login writes exactly that value, so the field adds nothing beyond the version 2 marker. Dropping it in a follow-up is fine, or keep it if a future flow can record a different issuer. These can be taken or left.

The one other review thread, on auth status showing a v1 session as not authenticated, no longer applies. The maintainer re-scoped that naming to #4849 and the author replied, so it can be resolved: #4921 (comment)

Not verified here: the tests and the src/cli suite were not run, so regression validity comes from reading the tests against the deleted postJson. Node's real fetch with redirect: 'manual' on a live 307 or 308 was not exercised, because the tests inject fetch. No real cloud was exercised. After the two fixes, a loopback run should show a 303 chain completing with a GET and a credential-bearing redirect failing with the fixed message and no credential in the output.

No other code issue is known. The PR should be retargeted to main after #4833 merges.

@apex-sentinel-staging

This comment has been minimized.

Base automatically changed from feat/cli-session-refresh-rotation to main November 22, 2026 13:47
@thymikee
thymikee force-pushed the fix/cloud-login-origin branch from 2fcb5e3 to 11abd8c Compare November 22, 2026 13:47
AGENT_DEVICE_CLOUD_BASE_URL overrode the cloud origin stored with the CLI session, so the stored
refresh credential went to whatever origin the variable named. A refresh now refuses an override
with another origin (UNAUTHORIZED, reason cloud_login_origin_mismatch) before any request, and
cloud auth requests no longer follow redirects, which would resend a credential or device code to
the redirect target.
… table

R89 measures wire-published reason literals against the merge-base.
Read the reason from a ReasonTable beside the origin check and regenerate
the error reasons page.
…e a rotation, and document the rule

A same-origin AGENT_DEVICE_CLOUD_BASE_URL still names the connection, while the refresh goes to the
URL stored with the session. A rotation is not stored over a session that a login moved to another
cloud. The commands docs state the stored-origin rule and the cloud_login_origin_mismatch outcome.
…w bounded same-origin auth redirects

The stored CLI session format moves to version 2, which records the origin that issued the
credential. A version 1 record, or one whose issuer is not its URL's origin, fails with
cli_session_issuer_unverified before any request, and agent-device auth login replaces it.

Cloud auth requests (device-auth start, poll and CLI session refresh) follow at most three 307 or
308 redirects whose target has the original request origin, with the same POST body. A
cross-origin target, a fourth redirect, or a 301, 302 or 303 fails with a typed reason before
anything is sent again.
@apex-sentinel-staging

This comment has been minimized.

…uth redirects with one reason

Drop issuerOrigin: login always writes the origin of cloudBaseUrl, so version 2
alone marks a session saved through the origin-checked login. Collapse the three
redirect reasons into cloud_auth_redirect_refused, drop the opaqueredirect branch
Node never returns, and make the hint name the request origin instead of an
override a refresh does not use.

Prove the transport with Node's own fetch on loopback servers, and keep one
cross-origin case per auth route to prove every route uses it.
@thymikee
thymikee force-pushed the fix/cloud-login-origin branch from 11abd8c to 1abd533 Compare November 22, 2026 13:55
@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

The earlier findings from c888fd9 are fixed at 9c9da8c, but a second independent pass found one remaining defect in the redirect handling.

A cloud can answer an auth POST with a 301, 302, 303, 307 or 308 and a present but empty Location header, then answer successfully on the second request to the same URL. The base transport uses Fetch's default redirect handling, which retries that URL as GET without a body for 301/302/303 and as POST with its body for 307/308 (auth-session.ts:806-812 on main). At cloud-auth-request.ts:65 the truthiness check treats the empty header as absent, so the request fails with cloud_auth_redirect_refused after one request. A loopback run reproduced this for all five statuses. It affects device-auth start (auth-session.ts:248), poll (auth-session.ts:808) and CLI-session refresh (auth-session.ts:724). The rule: only a null Location counts as absent, and every present value, including the empty string, goes to URL.parse(location, current). Keep the existing origin, userinfo, hop-limit and method checks. A test with an empty Location on a same-URL redirect should show the second request succeeding.

Not blocking: the same empty-Location case could instead keep the refusal and be documented in the error-reasons row as counting as missing; take or leave this, since the fix above resolves it.

Of the earlier inline threads, the two about the test server's dynamic method call are fixed at 9c9da8c, because the tests now serve canned route data from a map (#4921 (comment), #4921 (comment)). The thread on auth-session.ts:353 does not need action here, because the maintainer deferred it to #4849 (#4921 (comment)). No open thread still applies.

CI is green at 9c9da8c, with 21 checks and none failing, and there are no conflicts. Not verified here: the tests were not run locally, so regression validity comes from reading them against the pre-change code. Not verified here: no real cloud was exercised, and the redirect behavior is proven only by loopback Node fetch. After the empty-Location fix lands with its test and CI stays green, nothing else blocks merge.

@apex-sentinel-staging

Copy link
Copy Markdown

Apex Sentinel · ✅ Approve · review of 23803c9

Since the review of 9c9da8c: 0 new · 0 still open · 0 no longer raised

No open findings.

Reviewed with this repository's own Sentinel configuration (caa232e6ca2e).

💬 Talking to Sentinel

In a finding's thread, reply with:

Command What it does
@apex-sentinel-staging note <context> Adds context; Sentinel re-checks the cited code
@apex-sentinel-staging pivot <why> Says the finding is wrong; Sentinel re-checks the cited code
@apex-sentinel-staging like Marks the finding as useful
@apex-sentinel-staging dislike <why> Marks it as not useful, so it is not raised again

On this conversation, comment @apex-sentinel-staging review to run a full review once again.

@thymikee

Copy link
Copy Markdown
Member Author

An empty Location is now resolved against the current URL as Fetch does, with the origin, userinfo, hop and method checks unchanged, and the new test covers 301/302/303/307/308. This addresses the last finding; nothing else blocks 23803c9.

@thymikee thymikee added the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Nov 22, 2026
@thymikee
thymikee merged commit 2fc19f2 into main Nov 22, 2026
21 of 22 checks passed
@thymikee
thymikee deleted the fix/cloud-login-origin branch November 22, 2026 16:22
thymikee added a commit that referenced this pull request Nov 22, 2026
* origin/main:
  fix(auth): send a stored CLI session only to the cloud that issued it (#4921)
  refactor(reasons): declare the daemon reasons in ReasonTable rows (#4936)
  fix(cli): drop --remote-config from auth and skip reading it for unsupported commands (#4957)
  refactor(snapshot): deduplicate system-surface projections and warnings (#4959)
  fix(find): enforce offscreen and non-hittable guarantees on focus (#4954)
  feat(auth): store a rotated CLI session credential and show the login code (#4833)
  fix(daemon): report Windows SIGTERM daemon exits as forced (#4659)

# Conflicts:
#	packages/capture-kit/src/snapshot-quality-verdict.ts
#	packages/command-runtime/src/commands/interaction/runtime/target-visibility-stages.ts
#	packages/contracts/src/device-inventory.ts
#	packages/daemon/src/execution/interaction/internal/__tests__/find.test.ts
#	packages/daemon/src/execution/interaction/internal/find-target-capture.ts
#	packages/replay-port/src/daemon-port/session-replay-runtime-failure-response.ts
#	website/docs/docs/error-reasons.md
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-human Valid work that needs human implementation, judgment, or maintainer merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants