Skip to content

feat(auth): store a rotated CLI session credential and show the login code - #4833

Merged
thymikee merged 10 commits into
mainfrom
feat/cli-session-refresh-rotation
Nov 22, 2026
Merged

thymikee merged 10 commits into
mainfrom
feat/cli-session-refresh-rotation

Conversation

@thymikee

@thymikee thymikee commented Nov 20, 2026 •

Copy link
Copy Markdown
Member

Summary

Two hardening changes to the cloud CLI login:

  • Refresh credential rotation. The refresh request sends acceptsRotatedRefreshCredential: true. A response refreshCredential replaces the stored one. A cloud that does not rotate sees no change.
  • Login code in the terminal. Browser login prints the device-flow user code to compare with the approval page. A code with unsafe characters is not printed.

Rotation contract (written at the request in auth-session.ts): a rotating cloud issues at most one replacement per credential, answers the replaced credential with an access token and no new replacement, and keeps it valid for a grace period.

Login, logout and the store of a rotated credential run under one process lock on the session file. The store re-reads the file under the lock, so a login or logout wins. A failed lock or write keeps the access token and warns.

Before / after

$ agent-device auth login
Opening https://cloud.example/authorize...
Confirm that the browser shows this code: ABCD-EFGH   # new line

Validation

  • 0756331887: src/cli tests (621 pass), typecheck, lint, layering guard.
  • New test: a rotated credential waits for a logout that holds the lock. It fails on the previous head.
  • Other tests: rotation stored and reused; parallel commands leave one replacement; a changed session is not overwritten; failed write warns; unsafe code not printed.
  • A cloud implementation of the contract was exercised against this flag.
  • No device run: CLI auth only.

@github-actions

github-actions Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Size Report

Metric Base Current Diff
Installed (including dependencies) 6.51 MB 6.51 MB +3.9 kB
Package (unpacked) 6.51 MB 6.51 MB +3.9 kB
Package (download) 1.98 MB 1.98 MB +1.2 kB

Startup median (7 runs, lower is better):

Scenario Base Current Diff
CLI --version 21.3 ms 22.1 ms +0.8 ms
CLI --help 45.9 ms 46.7 ms +0.7 ms

@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 333f2cc. 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 333f2cc the code does what it says, CI is green and there are no conflicts. One point should be settled before a cloud turns rotation on, because it is the case this PR exists for.

Every remote CLI command refreshes the stored session, so two commands that start together against one state directory both send the same old credential with rotatesRefreshCredential: true (auth-session.ts#L426). If the cloud issues successive replacements, the earlier response can be saved while the later one is discarded by the re-read guard (auth-session.ts#L403), and the file then holds an invalidated credential. A cloud with reuse detection can also read the second request as a replay and revoke the session. Agents run CLI commands in parallel routinely, and today (no rotation) this cannot lose a session. The rule: with rotation on, concurrent commands on one session file never leave an invalidated credential stored. Either one refresh-and-store per session file is in flight at a time (an advisory lock around read, refresh and store, also taken by login and logout), or the contract with the cloud states a grace window in which the just-rotated credential stays valid, and the PR says so. Which is intended?

Notes for a follow-up issue, not for this PR:

  • If writing the replacement fails, or the process exits before the rename, the file still holds the credential the cloud just invalidated. A recovery path needs the cloud's side of the protocol.
  • The refresh fetch follows redirects and the final response origin is not checked, so a redirect to another origin could supply the replacement credential.
  • The comment at auth-session.ts#L383 says a change during the refresh wins, but the re-read and rename are not atomic; "a change visible on re-read wins" is accurate. The open inline thread on this still applies: feat(auth): store a rotated CLI session credential and show the login code #4833 (comment)
  • rotatesRefreshCredential reads as if the client rotates; acceptsRotatedRefreshCredential may be clearer before a cloud depends on the name.
  • The failed-write test uses chmod 0500, which does not block writes when the suite runs as root.

Not verified here: the diff was read and the two concurrency outcomes were confirmed with an in-memory run of the guard; no tests were run. The cloud side was not checked: whether it honors the flag, applies reuse detection or a grace window, or shows the user code on the approval page.

@thymikee

Copy link
Copy Markdown
Member Author

Answering "which is intended": the grace-window contract, not a lock. It is now stated in the PR body and at the refresh request in auth-session.ts (735ea78).

A cloud that rotates must:

  1. issue at most one replacement for a credential;
  2. answer a request that still presents the replaced credential with an access token and no further replacement;
  3. keep the replaced credential valid for a grace period that covers commands in flight.

Under 1 and 2, two commands that start together never hold different replacements: one response carries the replacement, the other carries none and writes nothing. So the "earlier saved, later discarded" outcome needs a cloud that issues successive replacements, which the contract forbids. A new test runs two refreshes in flight against a cloud that follows the contract and checks that the one replacement is stored whichever response lands first.

Also taken in this push:

  • The comment on storeRotatedCredential now says "a change that is visible on that read wins", and that the read and write are not atomic and why that is sufficient under the contract.
  • The flag is renamed to acceptsRotatedRefreshCredential. I did it here, not in a follow-up, because the name is a wire contract and no released CLI sends it yet.

Left for a follow-up issue, as you listed: recovery when the write fails or the process exits before the rename; rejecting a refresh response from a redirected origin; the chmod-based failed-write test under root.

Cloud side, verified against one implementation: it honours the flag, rotates at most once per hour, answers the replaced credential for 5 minutes without a new one, and revokes the session when a replaced credential arrives after that.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

At 735ea78 the earlier concurrency question is answered for two refreshes: the documented contract leaves only one process holding a replacement. All checks pass and there are no conflicts. One case inside that same guarantee remains.

A second independent pass found that a rotating refresh can overwrite a completed login or recreate a logged-out session (auth-session.ts#L406). The refresh reads the original record at line 397 and passes the guard. A second process then signs in (line 273) or signs out (lines 312–316) before the rename. The refresh publishes the old session with its replacement credential. Later commands then use the old account or workspace, or auth status shows a session after logout reported success. Without rotation a refresh never writes the session file, so this is new with this PR. The rule: the refresh's re-read and publish, the login commit and the logout removal are serialized on the session file. The existing process lock (bounded acquisition, dead-owner reclamation) would do it, with device approval polling kept outside the lock.

For #4849, not for this PR:

  • A process that reads the credential, pauses past the cloud's grace window and then refreshes sends a stale credential; a cloud that revokes on post-grace reuse then invalidates the replacement another process saved (auth-session.ts#L357). The same lock covering read, request and store would also close this.
  • An HTTP 200 refresh response that reports revoked and also carries tokens is accepted, because the access-token branch returns before the revocation check (auth-session.ts#L441).
  • The request now always adds acceptsRotatedRefreshCredential; a non-rotating control plane that rejects unknown body keys would answer 400 (auth-session.ts#L433).

Not blocking, take or leave: the comment at auth-session.test.ts#L256 implies a release order, but the test passes in either order.

The open inline thread on the non-atomic compare-and-swap no longer applies as written and can be resolved; the login and logout case above is what remains of it (#4833 (comment)).

Not verified here: no tests were run; the new test was read and traced by hand. Whether the cloud enforces the rotation contract (one replacement, none for a replaced credential, the grace period) lives outside this repository.

@thymikee

Copy link
Copy Markdown
Member Author

Fixed at 0756331, and rebased on main.

The login write, the logout removal, and the rotated-credential re-read and write now run under one process lock on the session file (withCliSessionLock, the existing acquireProcessLock with a 10 s bound and dead-owner reclaim). Device approval polling stays outside the lock. A store that cannot take the lock keeps its access token and warns, as a failed write did. removeCliSession is now async.

New test: a rotated credential waits for a logout that holds the session file lock. It fails on the previous head (the store wrote while the logout held the lock) and passes now. src/cli tests: 621 passed. Typecheck, lint and the layering guard pass.

The three items for #4849 go there. The test comment at auth-session.test.ts is left as is.

@thymikee
thymikee force-pushed the feat/cli-session-refresh-rotation branch from 735ea78 to 0756331 Compare November 21, 2026 14:42
@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

At 0756331, the rotation compare-and-swap from the earlier review (#4833 (comment)) is fixed: the re-read and write now run under the session lock, and login and logout take the same lock. Five new problems remain in the locking itself.

Only the "Body rules" check fails. It grades the PR title and body, not the diff, so it is likely unrelated to these changes. Not verified here: the exact failing rule, because the job log was not read. No conflicts are known.

A second independent pass found that login throws on lock timeout after the user approved the device. If a logout holds the lock past the 10-second wait, the approved credentials are discarded and the retry starts a new approval. On base, the same approval completed without a lock wait. On a typed process_lock_timeout, keep the approved result and retry only the locked publish, so a timeout never forces a new device approval.

A second independent pass found that a refresh loses the cloud's only replacement credential on lock timeout. The rotation request runs outside the lock, so the store can time out, warn, and return the access token while R1 is never written. The cloud issues R1 once and later rejects R0, so no later refresh recovers it. Keep the returned replacement through a typed acquisition timeout and retry the locked compare and publish without requesting another rotation. If the command must exit at the first timeout, make the save resumable or make the replacement recoverable on the cloud side.

A second independent pass found that an owner-masking umask such as 0200 blocks login and logout on an existing session. The lock directory made by process-lock.ts:278 loses owner write, so the owner record at line 286 cannot be written. Base replaced or removed the session under that umask. The new umask test at 0700 writes the raw file and never creates a lock. Set exact private owner permissions on every freshly created lock directory, owner record, and guard file in the shared lock publisher, and test login and logout through the locked entry points under an owner-masking umask.

A second independent pass found that logout needs write access even when no session is stored. With a readable but non-writable empty auth directory, base prints "No stored cloud CLI session." and this head fails while creating the guard. A fresh writable state root also now gains an auth directory from what used to be a read-only no-op. Return false when the session is absent before taking any lock, then keep the second existence check and all removal under the lock.

A second independent pass found that a lock-release failure can report a completed mutation as failed. If a contender holds the mutation guard while the session-lock holder finishes, process-lock.ts:80-85 and :499-533 reject after the login, logout, or rotation already took effect. The CLI then prints a failure while auth status shows the change. Separate the committed outcome from the release failure at the auth boundary, report the committed result, and name the release problem on its own.

The earlier inline thread on the non-atomic compare-and-swap no longer applies; the locked re-read and write fix it, so it can be resolved: #4833 (comment). No other open threads were carried over.

Evidence limits: no tests were run here. Only the rotation-store lock has a test; that login and logout take the lock was checked by reading the code. Whether the cloud enforces the single-issue rotation contract lives outside this repository.

Before merge, these five problems need fixes and the "Body rules" check must pass.

@thymikee

Copy link
Copy Markdown
Member Author

Reply to #4833 (comment), fixed at c721659:

  1. Login after approval and 2. rotated credential on lock timeout: the session lock now waits up to 60 s instead of 10 s. A holder keeps it for one file operation and a dead holder is reclaimed, so only a stuck live process makes a contender wait that long. The acquisition is the only part that waits, so the approved result and the returned replacement are kept for the whole wait and no second approval or rotation is requested. The bound stays finite so a stuck live process cannot hang the command.

  2. Logout with no session: returns false before taking the lock. It needs no write access and creates no auth directory. New test: logout without a stored session takes no lock and writes nothing.

  3. Release failure after a committed change: withCliSessionLock now acquires and releases directly. A change that took effect is returned; a release failure afterwards is a warning, and the next contender reclaims the spent claim. A task failure still releases and throws.

  4. Umask 0200: not in this PR. The lock directory permissions belong to the shared host-kit lock used by every caller, so I filed it as host-kit: process lock fails under an owner-masking umask #4903.

src/cli tests 622 pass; typecheck, lint and fallow audit pass. This is the third review round on this PR, so further adjacent hardening goes to #4849.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

The five findings from the earlier review (0756331) are fixed at c721659, and all 21 checks pass. A second independent pass found four remaining problems. No conflicts are known. Merge needs these four fixed.

A second independent pass found that an approved login can still lose its credentials. If another live CLI process holds the session lock past the 60-second wait, withCliSessionLock rejects with process_lock_timeout. loginWithDeviceAuth then exits with the approved session only in memory, and the next login starts a new device approval (L222). The rule: once the cloud has approved a device, a lock timeout must not discard that session. Retain the approved session and retry only the locked publish on the typed process_lock_timeout reason.

A second independent pass found the same loss on refresh at auth-session.ts:450. If the cloud returns replacement R1 once while rotating R0, and the locked re-read times out, the catch warns and leaves R0 on disk. After the grace period the cloud rejects R0, so the user must log in again. The rule: a received replacement must not be dropped on a lock timeout. Retain R1 and retry only the locked re-read and conditional publish on process_lock_timeout. Keep the existing guard so a committed logout or a different login still wins.

A second independent pass found that the lock is not private under a permissive umask (process-lock.ts:278). With umask 000 and an existing auth directory, the lock directory is created at 0777. The owner record goes through atomic-publish.ts:29-34 without a mode, so it is 0666. Other local users can then write to the lock directory and read its metadata. The rule: every lock directory and owner record this path creates must be owner-only. That includes the record restored on release at process-lock.ts:605-609. Create the directory with owner-only permissions and write owner records at 0600.

A second independent pass found that the new release warning can fail a committed command (auth-session.ts:358). If another process holds the lock past the release wait and the caller has closed its stderr pipe, the write to process.stderr at L697-698 emits an unhandled EPIPE. In a small Node subprocess check, the CLI exited 1 even though stdout had reported success. The same warning runs after a committed login or rotation. The rule: warning delivery after a committed mutation must never change the command result. Make it best effort, handling both synchronous and asynchronous write failures.

The earlier compare-and-swap thread is fixed at this head: re-read, compare and write now run under withCliSessionLock at auth-session.ts:441-446, so that thread can be resolved.

Not verified here: no tests were run, and the new logout test's failure on 0756331 was judged from reading the code. Not verified here: the cloud's single-issue rotation contract, which lives outside this repository. After the fixes, please show the lock-timeout cases above: a timed-out login publish that succeeds on retry without a second approval, and a timed-out refresh that keeps R1 on disk.

@thymikee

Copy link
Copy Markdown
Member Author

Reply to #4833 (comment), at 69648bb:

  • Release warning can fail a committed command (auth-session.ts:358): fixed. The warning is written best effort: a synchronous throw is caught and a later EPIPE error event is absorbed by a one-shot listener. Checked with a child process whose stderr was destroyed: exit 1 without the guard, exit 0 with stdout "done" with it.
  • Lock directory and owner record modes (process-lock.ts:278, :605-609): not in this PR. The CLI creates the auth directory 0700, so other users cannot reach the lock inside it; the general rule belongs to the shared host-kit lock used by every caller. Added the permissive-umask case to host-kit: process lock fails under an owner-masking umask #4903.
  • Login and refresh on process_lock_timeout (auth-session.ts:278, :450): kept as designed. The acquisition is the retried step: it waits 60 s, a holder keeps the lock for one file operation, and a dead holder is reclaimed. The only way to time out is a live process stuck while holding the lock; retrying past that bound would hang the command on that process. The remaining case goes to CLI session rotation: lost-store recovery, refresh origin check, root-safe failure test #4849 with this note.

This was review round 4. Further hardening of the lock path is tracked in #4849 and #4903.

@blacksmith-sh

This comment has been minimized.

@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 0be628f. The verdict and the full list are in the summary comment.

Comment thread src/cli/auth-session.ts Resolved
@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

The EPIPE finding from the earlier review (#4833 (comment)) is fixed at dbea97e: both post-commit warning sites now use warnBestEffort. Three problems remain in the lock handling, and CI is green (21 checks, none failing). The earlier replay failure on suite/01-settings.ad does not touch CLI cloud auth and is not failing at this head. No conflicts.

A second independent pass found that an approved login can be lost when the session lock times out at src/cli/auth-session.ts:278. If another live CLI process holds the lock past the 60-second deadline, acquisition rejects with process_lock_timeout (process-lock.ts:371,385,441) after the cloud already approved. The session never reaches disk, and the next auth login starts a new approval. The base published the approved session directly. An in-memory check of the head confirmed the timeout propagates with no publish. Should the approved session be kept and its locked publish retried on the typed process_lock_timeout reason, with the device approval requests kept outside the lock?

A second independent pass found that a lock timeout can drop the only rotated refresh credential at src/cli/auth-session.ts:450. R0 is on disk, the cloud returns R1 once, and another process holds the lock past the deadline. The catch warns and drops R1, so R0 stays stored and stops working after the cloud's grace period. This contradicts website/docs/docs/commands.md:2320. The rule: a returned rotated credential must be retained on process_lock_timeout and the locked re-read and conditional publish retried without refreshing again. Keep the comparison at lines 444-446 so a different session or a completed logout still wins.

A second independent pass found that the lock is exposed to other accounts under a permissive umask at process-lock.ts:278. On POSIX with umask 000 and an existing auth directory reached through a symlink, which the CLI admits (src/cli.ts:412-417 and auth-session.ts:342-346,365), the lock directory is created 0777 and the owner record 0666. Initial publication and restoration pass no mode (process-lock.ts:542-546,605-609 and atomic-publish.ts:29-34). Another local account can edit the record that proves ownership, so exclusion is not guaranteed. Base login worked with this layout. The rule: the lock directory must be 0700 and every owner record 0600 at both publication sites.

No review thread still applies. These two are fixed at this head and can be resolved: the stderr write in the rotation catch now uses warnBestEffort (#4833 (comment)), and the re-read, compare and write run under withCliSessionLock (#4833 (comment)).

Not verified here: no tests were run, and the new test was judged from code to fail on c721659. The async EPIPE path of warnBestEffort is covered only by the author's child-process check, which was not rerun. The cloud's single-issue rotation contract lives outside this repository. The 60-second lock wait from the first review is not re-raised; the cases above are the specific states where approval or rotation is discarded. Please fix these three, then push and re-run the checks before merge.

@thymikee

Copy link
Copy Markdown
Member Author

Reply to #4833 (comment), fixed at f4aada0:

  1. Approved login on process_lock_timeout: the locked publish waits again on the typed timeout and prints a notice; the approved session stays in memory and no second approval starts. Device approval requests stay outside the lock.
  2. Rotated R1 on process_lock_timeout: the locked re-read and conditional publish wait again without another refresh. The comparison still lets a logout or a different login win. Logout keeps failing on a timeout, because it drops nothing.
  3. Lock modes: the lock directory is created 0700 and set exactly, and owner records (initial and restored on release) are published at exactly 0600.

Tests: a timed-out session lock wait keeps waiting and never drops a rotated credential or a login (one refresh, one approval, both credentials on disk, two notices) and acquireProcessLock keeps the lock owner-only under any umask (umask 0200 and 000). Both fail on the previous head. Tests for src/cli, host-kit, apple-runner and daemon-contracts: 2548 pass. Typecheck, lint and fallow audit pass. This also covers #4903.

@thymikee
thymikee force-pushed the feat/cli-session-refresh-rotation branch from f4aada0 to 49dfd5f Compare November 21, 2026 17:06
@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: 2 new findings on 49dfd5f. The verdict and the full list are in the summary comment.

Comment thread src/cli/auth-session.ts Resolved
Comment thread src/cli/auth-session.ts Resolved
@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

The three findings from the earlier review at dbea97e (#4833 (comment)) are fixed at a9750b5. All 21 checks pass or skip, and none fail. A second independent pass found three new problems, all from waiting on the session lock; no conflicts are known.

A second independent pass found that an interactive cloud connect without a stored session can return an expired access token. The user approves and gets a short-lived access token. If a live holder keeps the session lock past that expiry, the head saves the session afterwards and still returns the original token (auth-session.ts:198). The first profile request sends it as a bearer token (cloud-profile.ts:38) and fails authentication. The base used the token right after approval. Keep the locked write, then check the access-token expiry from the approval before returning the token, and get a fresh one from the saved session if it expired during the wait.

A second independent pass found the same problem on refresh (auth-session.ts:439). The refresh returns a new credential and a short-lived access token. If the lock is acquired after that token expires, the head saves the credential and returns the expired token to the profile request or remote command. The base used the refresh response at once. After the rotation is saved, check the returned expiry before handing the token to the caller, and refresh again through the rotation-aware path if it expired.

A second independent pass found that a refresh during a long lock wait can revoke the pending replacement (auth-session.ts:425). While process A waits to store the only new credential, the old one is still on disk. Process B starts after the cloud's grace period and sends the old credential before taking any lock. With the cloud behavior described in #4833 (comment), this post-grace replay revokes the session. A then writes a credential that is already unusable, and the user must log in again. The base did not opt in to rotation, so this sequence did not exist. Take the same session lock before reading and sending the stored credential, and hold it through any replacement write. Keep device approval polling outside the lock.

Not blocking: isProcessLockTimeout is the third inline check of the process_lock_timeout reason (also in packages/host-swift/src/swift-cache.ts:542 and packages/daemon-contracts/src/daemon-registration-owner.ts:563), so a follow-up could export one predicate from @agent-device/host-kit/file and use it at all three sites; take it or leave it.

Of the open inline threads, the one on the absorbing stream listener is fixed at this head (#4833 (comment)), and the one on copying the refresh expiry (#4833 (comment)) does not apply because that value is the access-token expiry, not the session expiry, so it can be resolved.

Not verified here: no tests were run, and the new tests were judged from the code to fail on 31afdcc. The lock-timeout test builds the error by hand, matching processLockTimeoutError in shape, so the real 60-second timeout path was not exercised. The unbounded wait while a live holder keeps the lock was also not exercised.

@thymikee

Copy link
Copy Markdown
Member Author

Reply to #4833 (comment): these three move to a follow-up PR on #4849, stacked on this branch.

  1. Login after a long lock wait (auth-session.ts:198) and 2. rotation saved after a long lock wait (:439): the access token can expire only when a live process holds the session lock longer than the token lives (about 30 minutes for the current cloud). The follow-up checks the returned token's expiry after the locked save and gets a fresh one from the saved session.
  2. Lock across the whole refresh (:425): already tracked in CLI session rotation: lost-store recovery, refresh origin check, root-safe failure test #4849. The follow-up takes the session lock before reading the stored credential and holds it through the replacement write, with device approval polling outside it.

This PR keeps its scope: rotation storage, the login code, and the session-file lock.

@thymikee

Copy link
Copy Markdown
Member Author

This head (a9750b5) now conflicts with main. Please rebase onto main and push; the rebased head gets a delta review.

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

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

The conflict reported in the earlier review (#4833 (comment)) no longer applies to the code, and the two earlier inline threads are addressed at 1b90bcd. Two defects remain in the session refresh path, and the first one must be fixed before merge. All 7 checks pass. The PR still conflicts with main in website/docs/docs/commands.md and website/docs/docs/error-reasons.md, both generated since #4919 and #4928, so CI has not run on the merged result.

A second independent pass found that a read-only session store can no longer refresh against a non-rotating cloud (auth-session.ts:535). Take an unprivileged caller with a valid session in a readable auth directory with mode 0500, where the cloud returns a valid access token and no replacement credential. Main and a9750b5 send the refresh and use the token without writing anything. At this head, lock creation fails first and the caller gets cli_session_store_unwritable. The new test at auth-session-refusal.test.ts:281-315 asserts that no request is sent for this case. The lock should live in a writable state location shared by every operation on the session. Under that lock, a non-rotating exchange should be allowed when the credential file cannot be replaced.

A second independent pass found that a bearer token can expire while the session lock is released (auth-session.ts:415). A cloud connect refreshes its stored session, and the endpoint returns an access token with two seconds left and no rotated credential. The check at auth-session.ts:606 passes. A paused contender holds the mutation guard during release, which can wait five seconds (process-lock.ts:30, :511, :809-821). The same token then reaches the profile request at cloud-profile.ts:38-41 and fails authentication. Main and a9750b5 return a non-rotating response without a lock release. The interactive connect approval has the same gap between its check at auth-session.ts:313 and delivery to the caller. Every path that hands an access token to a caller that spends it should check the token after the final awaited release. If the release used up the remaining lifetime, use the saved session for one bounded refresh and return a typed failure if there is still no live token.

Not blocking: the PR body still says "A failed lock or write keeps the access token and warns", but a failed lock now fails the command with process_lock_timeout or cli_session_store_unwritable, and only a failed rotation write warns. Update the Summary to "A failed rotation write keeps the access token and warns; a refresh that cannot take the session lock fails with its typed reason." These notes can be taken or left.

For a follow-up issue, not for this PR: the docs in commands.md:2686 and the matching error-reasons.md row say a refresh with neither a token nor the revoked marker fails with cli_session_refresh_unanswered, but the code raises it only for a 2xx body without accessToken (auth-session.ts:509-514); a non-2xx answer such as 401 invalid_grant, 429 or 503 fails earlier with the generic cloud rejection and no details.reason (cloud-response.ts:31-37). Scoping both sentences to a successful response, in the docs and in the ReasonTable comment that generates error-reasons.md, is the smaller fix.

Simplicity question: with the session lock now held across read, refresh and write, no lock-respecting writer can change the file under the holder. Could storeRotatedCredential shrink to "write {...session, ...rotation}; on failure warn and keep asking with the rotated credential in memory", without the file.holds, asked and saved bookkeeping and its re-read compare? Could the MAX_CLI_SESSION_TOKEN_EXCHANGES second-exchange loop and the login-time exchange of an already-expired approval token go too, since a cloud that issues already-expired access tokens is not part of the stated invariant? That would also remove requiresLiveToken, the transient-failure branch, its warning and the matching doc sentence. This is not blocking, and the invariant holds at this head.

No high-priority thread from other reviewers still applies, and no lower-priority one does either. These two threads can be resolved: #4833 (comment) was fixed in a9750b5 and the delta keeps that fix, and #4833 (comment) is addressed because readCredentialRotation now stores the response's cliSession.expiresAt with the rotation.

Not verified here: the new auth-session exchange, refresh and refusal tests were not run, so whether they fail without the change is unconfirmed; a real cloud implementation of the rotation contract was not exercised, although the PR body says one was; and the conflict resolution of the generated docs blocks against the generator from #4919 was not judged, so the rebased head needs a regenerate.

@thymikee

Copy link
Copy Markdown
Member Author

Rebased onto main at c8cffcd. commands.md keeps main's shorter cloud auth bullet plus the session and refresh sentences. error-reasons.md is regenerated. All 643 CLI tests pass.

The two findings in #4833 (comment) go to #4849, because this PR is closed for new hardening:

  • the lock location and the non-rotating exchange for a 0500 auth directory;
  • the access token's remaining lifetime after the final lock release.

@thymikee
thymikee force-pushed the feat/cli-session-refresh-rotation branch from 1b90bcd to c8cffcd Compare November 22, 2026 11:07
@apex-sentinel-staging

This comment has been minimized.

A rotating refresh re-read the session file and then wrote it. A login or a logout from another
process between the two steps was overwritten: later commands used the old session, or a logout
that reported success left a session. The login write, the logout removal, and the re-read and
write of a rotated credential now run under one lock on the session file. Device approval polling
stays outside the lock. A store that cannot take the lock keeps the access token and warns.
…on lock contention

The session lock waits up to 60 s instead of 10 s: a holder keeps it for one file operation and a
dead holder is reclaimed, so only a stuck live process makes a contender wait that long, and the
change that waits is one the cloud will not repeat. A change that took effect is reported as done
when the lock release fails afterwards; the release failure is a warning. Logout returns false
before taking the lock when no session is stored, so it needs no write access and creates no auth
directory.
…ot be written

The warning for a lock release failure is written best effort: a closed stderr fails the write
synchronously or with a later EPIPE error event, and neither may turn a login, logout or stored
rotation that took effect into a failed command.
…session lock timeout

A login after device approval and the store of a rotated credential keep waiting on a typed
process_lock_timeout and print a notice, so the cloud's one-time result is never discarded; device
approval stays outside the lock, and the locked re-read still lets a logout or another login win.
Logout still fails on a timeout, because it loses nothing.

The shared process lock creates its directory 0700 and writes owner records, including the record
restored on release, at exactly 0600 under any umask.
…cess token live (#4927)

* fix(auth): hold the CLI session lock across a refresh and keep its access token live

* fix(auth): fail a refresh lock wait typed and keep a login token with its own expiry

* test(auth): cover the login exchange's expiry pairing and lock timeout

* fix(auth): keep an approved login and refuse a refresh without response text

An explicit `auth login` prints its session, not its access token, so a session
that is saved already answers the command: the exchange of an already-expired
approval token now runs inside the acquisition that saved the session, on the
record just written, and only a caller that spends the token itself, such as
`connect`, propagates that exchange's failure. A refresh refusal names
`cli_session_revoked` and copies no `status` or `error` text out of the cloud's
response, which could echo a credential into `--json` output. A session store
that cannot be written answers `cli_session_store_unwritable` with the `chmod`
hint that names the directory.

* fix(auth): name confirmed revocation and keep a login's last saved session

A refresh that answers without an access token was labelled `cli_session_revoked`, so an explicit
login treated a tokenless answer as proof its saved session was gone. The reason now names only the
exact `revoked` marker; the tokenless answer gets `cli_session_refresh_unanswered` and keeps the
session. `cloud-response.ts` offers a rejected body to its caller's classifier before the generic
status refusal, so a 401 whose body reports revocation is classified as one, with no body text
copied. The approval's access-token expiry counts only as a nonempty string, an exchange keeps the
next rotation's credential apart from the session it reports, and a transient failure of the
optional second exchange keeps the token already answered.
@thymikee
thymikee force-pushed the feat/cli-session-refresh-rotation branch from c8cffcd to 18b6276 Compare November 22, 2026 11:21
@apex-sentinel-staging

Copy link
Copy Markdown

Apex Sentinel · ✅ Approve · review of 18b6276

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

No open findings.

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

💬 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

This PR is ready to merge at 18b6276. The two findings from the 1b90bcd review are re-scoped to #4849, and the delta since then is a clean rebase plus a shortened, accurate commands.md bullet. CI is green: 22 checks, 0 not passing at 18b6276, and there are no conflicts. Not verified here: the CLI tests were not run locally, and the lock location and post-release token lifetime were not re-examined (re-scoped to #4849). Not blocking, and fine to take or leave: isProcessLockTimeout compares the reason to the literal 'process_lock_timeout', while PROCESS_LOCK_REASONS.timeout from @agent-device/host-kit/file now owns that reason.

@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 caa232e into main Nov 22, 2026
22 checks passed
@thymikee
thymikee deleted the feat/cli-session-refresh-rotation branch November 22, 2026 13:47
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.

1 participant