Skip to content

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

Merged
thymikee merged 5 commits into
feat/cli-session-refresh-rotationfrom
fix/cli-session-refresh-followups
Nov 22, 2026
Merged

thymikee merged 5 commits into
feat/cli-session-refresh-rotationfrom
fix/cli-session-refresh-followups

Conversation

@thymikee

@thymikee thymikee commented Nov 21, 2026 •

Copy link
Copy Markdown
Member

Summary

Stacked on #4833 (#4849). Retarget to main once #4833 merges.

  • The session lock covers the whole refresh: reading the stored credential, the refresh request, and the replacement write. A command no longer sends a credential it read without the lock, closing the post-grace reuse that could invalidate a replacement another process had saved.
  • An approved login saves its session and exchanges an already-expired approval token under one lock acquisition, on the record it just wrote, and returns that snapshot with the refresh response's own token expiry. Once the session is saved, explicit auth login succeeds through a transient exchange failure; only callers that spend the token (connect) propagate it. A revoked answer refuses both.
  • A refresh response reporting revoked is refused even when it also carries tokens, and every refresh refusal publishes cli_session_revoked with no response-supplied text in message or details.
  • A session store that cannot be written fails with cli_session_store_unwritable and a chmod hint naming the directory.
  • Only an approved login's save waits out a lock timeout; a refresh read fails with the lock's typed reason. Device approval polling stays outside the lock.

Before / after

$ agent-device auth login --json   # approved token expired, refresh answers 503
before: exit 1, while `auth status` shows the saved session
after:  exit 0, the saved session, no token expiry, and a warning

Validation

  • 11ea3a7c11: pnpm check:affected --run --head HEAD passed (exactCommit: true) — format, lint, typecheck, layering, fallow, build, unit, command-docs, docs-links, docs-prose; replay and web lanes are CI-owned.
  • Each new test fails when its own fix is reverted; the behavior tests fail at base a9750b54bf.
  • The unwritable-store test uses a real 0500 directory, skipped on Windows. No device run: CLI auth only.

@github-actions

github-actions Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Size Report

Metric Base Current Diff
Installed (including dependencies) 6.49 MB 6.49 MB +2.2 kB
Package (unpacked) 6.49 MB 6.49 MB +2.2 kB
Package (download) 1.98 MB 1.98 MB +783 B

Startup median (7 runs, lower is better):

Scenario Base Current Diff
CLI --version 18.4 ms 18.4 ms +0.0 ms
CLI --help 40.2 ms 38.9 ms -1.3 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: 2 new findings on 0c266fb. 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

Five problems in 0c266fb need fixes before this lands. The lock now covers the refresh, but it can hang a command, fail an approved login, return or report the wrong credentials, and expose a stored credential in an error.

A second independent pass found that a stored-session command can wait forever for a lock it cannot get. When the cloud returns a live access token without rotating, a dead process may have left a lock claim with no owner record, or a live holder may be stopped (see process-lock.ts). At base this refresh took no lock and finished. At head, auth-session.ts:389-398 discards every typed timeout and waits again, so the command keeps warning and never shows the lock recovery hint. Use the bounded acquisition for stored-session refreshes and let the typed timeout reach the caller. Keep retrying only for the already-approved login write.

A second independent pass found that an approved auth login can fail after its session is saved (auth-session.ts:291). If the approval access token expires during the lock wait and the new refresh returns HTTP 503, auth.ts:19-35 exits with an error, while auth status shows the saved session. Base returned success here. Return success to explicit login when the access-token exchange fails transiently. Keep failure propagation for connect, which needs a usable token, and keep refusing revoked responses.

A second independent pass found that login can return another login's access token (auth-session.ts:320). Login A saves its session and releases the lock. Login B saves a different session before A takes the lock again. If A's token expired, A exchanges B's credential at lines 463-468 and returns B's token with A's session (lines 298-301). Implicit connect then pairs that token with A's cloud URL (lines 200-209). Keep the login's save and any immediate exchange in one lock acquisition, reuse the refresh routine inside it with the just-saved record, and leave device approval polling before the acquisition.

A second independent pass found that auth login --json can report expiry values for credentials it replaced (auth-session.ts:300). When the exchange rotates the session, the file gets the new session expiry (lines 523-526) but auth.ts:25-33 prints the old one. If the fresh access token has no expiry, line 300 reports the expired approval token's timestamp. Return the resulting session record from the exchange, use the refresh response's access-token expiry, and leave it absent when the response omits it.

A second independent pass found that a refresh error can expose a stored credential (auth-session.ts:573). An HTTP 200 response with a revoked status or error, an access token, and an echoed opaque refresh credential in the other field gets copied into AppError.details. Redaction does not recognize a bare opaque credential under those keys, so --json prints it. The tokenless refusal at lines 589-593 copies the same fields. Build both refusal errors with a constant typed reason for revocation and leave untrusted status and error values out of the details.

Of the earlier inline threads, the login-failure thread still applies, and it is covered by the second fix above. The two-login race thread is not the race as stated, because the login that waited writes last, so the author can resolve it; the third-writer case is covered by the third fix above.

Not blocking, and each can be taken or left: the expired-token retry loop in resolveCliSessionAccess and the stored cliSession.expiresAt go beyond the issue, and under clock skew every command can send two refresh requests; the test 'a rotated credential does not replace a session that changed during the refresh' now writes inside the lock, so its name or a comment should say it covers an unlocked older CLI; the comment at auth-session-refresh.test.ts:303 says the fake cloud refuses a replaced credential, but the fake never refuses; and every stored-session command now creates the auth directory and takes the lock, so a read-only state directory fails where base worked, which is fine if the store is documented as writable.

Not verified here: test results, since this review only read the code, and whether each new test fails at base, which was judged by reading base. Also not verified here: how the same-process parallel test behaves in host-kit's process lock, how the cloud handles a second exchange with a just-rotated credential, and whether read-only session stores are supported.

The only two checks not passing are cancelled 'Body rules' runs, and a later 'Body rules' run passes on this commit, so they look unrelated to the diff. There are no conflicts.

@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 finding moved to a new line on 2d67cec. 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

Round 1 (0c266fb, #4927 (comment)) is only partly fixed at 2d67cec. The lock now covers the refresh, but explicit auth login can still fail after the approval is saved, and one revoked-refresh path still copies response text into error details.

Explicit login still fails after a successful save: auth-session.ts:291. When the approved access token is already expired, loginWithDeviceAuth calls refreshExpiredLoginToken and then resolveCliSessionAccess (line 333). Any throw there reaches auth login (commands/auth.ts:19-24): an HTTP 503 or network error from postJson, and now also the bounded process_lock_timeout, because this change removed keepWaiting from resolveCliSessionAccess (line 505). Base a9750b5 returned success with the approved pair. At this head, auth login exits non-zero while auth status shows the saved session. The new commands.md sentence says an approved login keeps waiting through the timeout, but the command still fails on the exchange's own timeout. Explicit login does not use the access token; it prints only expiry and session fields. The rule: once the approved session is saved, explicit auth login reports success. A transient exchange failure (non-revoked HTTP or network error, or process_lock_timeout) returns the approved pair without the stale expiry, and a revoked answer still refuses. Implicit login (resolveRemoteAuth, resolveCloudAccessForConnect) keeps propagating the failure, because it needs a usable token. The simplest fix is to run the exchange only in those two implicit callers. Please add a test where the exchange answers 503 and auth login --json exits 0. A second independent pass reached the same failure, and the earlier thread #4927 (comment) still holds at this head.

A second independent pass found that the exchange can return a sibling login's token: auth-session.ts:333. Login A saves its approved session and releases the lock (lines 286-290). A's access token is expired. If login B saves a different session before A's refresh re-reads the file (line 477), A sends B's stored credential (line 486) and returns B's access token (line 303). Implicit connect then uses that token (lines 149-157, 200-209). Base returned only the approved token and record. Please keep the session write and the immediate exchange in one acquisition of the existing lock, and run the exchange on A's just-saved record. Approval polling stays outside the lock.

A second independent pass found that the post-exchange read can pair a token with a different session or a stale expiry: auth-session.ts:305. A's refresh rotates its session, then releases the lock (lines 421-424) before line 305 reads the record. If B logs in during that gap, A returns A's token and expiry with B's session metadata, and cloud connect uses that record's URL with A's token (lines 200-209). If a logout removes the file in the gap, the fallback reports the pre-rotation expiry. Explicit login prints these fields (commands/auth.ts:25-33). Please return the session snapshot and token pair produced by the exchange while the lock is held, and use that for login output.

A second independent pass found that a revoked refresh response can expose untrusted text: auth-session.ts:604. When a 200 response carries tokens and one of status or error equals revoked, the refusal is correct. But it copies both fields into AppError.details (lines 606-607). An opaque echoed value in the other field is not recognized by redaction (packages/kernel/src/redaction.ts:66-89), so it can appear in --json output. Base returned the token for this response, so this route is new. The rule: refresh refusals never carry response-supplied strings. Keep the revocation check before token acceptance, and return a fixed reason (for example details.reason cli_session_revoked) with the existing recovery hint. Please add a test that the details of a revoked-with-token response do not contain the echoed value. The tokenless refusal at line 622 copies the same fields and should get the same fix while here, although that route already exists at base.

A second independent pass found a regression for a readable but unwritable auth directory: auth-session.ts:474. State-root admission checks the root and the managed sessions directories (packages/daemon-contracts/src/daemon-resolution.ts:154-164), not the auth subdirectory. Base sent the refresh and accepted a live token, and the existing test covers a 0500 auth directory (auth-session.test.ts:320-336). At this head, the lock state must be written beside the session (lines 392-401), so the call fails before any refresh is sent, even if the cloud would make no rotation. A readable store with an unwritable auth directory can no longer authenticate remote commands. Please keep the lock mandatory and either repair the owner-owned directory's write permission through state admission, or, if that case is intentionally unsupported, document the change and return a typed storage error with a repair hint.

Not blocking, and fine to take or leave: re-reading the file at line 305 after the lock is released could be replaced by returning the record from resolveCliSessionAccess (which also makes the try/catch in readStoredSession removable, since readCliSession never throws), and the new login-exchange test at auth.test.ts:153 passes at 0c266fb, so a case with a refresh response that has no expiresAt and rotates cliSession.expiresAt would pin the round-1 expiry fix.

Does the extra machinery in this change need to be in this PR? Round 1 marked the in-command second exchange and the stored cliSession.expiresAt as beyond the issue, and this update adds more around exactly those parts: the file/asked split with three store outcomes, the readable() expiry guard, and readStoredSession. A smaller shape: (1) loginWithDeviceAuth saves under keepWaiting and returns the approved pair, as at base; (2) the two implicit callers (lines 127-158 and 183-210) call resolveCliSessionAccess once when the approved token is expired; (3) with one exchange, storeRotatedCredential is a single compare-and-write against the record read under the lock, and the file/asked tracker goes away; (4) leave cliSession.expiresAt storage out, or read it only through isExpired's own parse. Issue #4849 does not ask for the second exchange or a sliding session expiry, so the author may decide to drop them.

For a follow-up issue, not for this PR: refresh refusals should never carry response-supplied strings (the revoked and tokenless cases above, auth-session.ts:603), if the author prefers to fix that separately from the revoked-with-token route that this change newly reaches.

Of the two earlier inline threads, #4927 (comment) still applies (login failing after a post-save 503 or lock timeout), and #4927 (comment) no longer applies, because the login that waited writes last (lines 286-290) and line 305 now returns the stored session with the exchanged token, so only the narrow gap above remains. Please resolve the second thread.

The code needs the fixes above before merge, starting with the explicit-login failure at line 291. Required evidence is present. CI looks unrelated to this change: the diff touches only src/cli/auth-session.ts, CLI auth tests and one docs line, the iOS and macOS smoke tests are still running and do not exercise cloud login, and the cancelled Body rules run matches a superseded run seen on 0c266fb. There are no conflicts. Not verified here: tests and check:affected were not run, whether each new test fails at base or at 0c266fb was judged by reading the code, how redaction treats every echoed value in details.status and details.error was not checked, and the cloud's real access-token lifetime was not measured, so how often the expired-approval path is reached is estimated.

@apex-sentinel-staging

This comment has been minimized.

…se 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.
@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

Round 2 items addressed in 11ea3a7. Each answer names the commit and the test that pins it.

1. Explicit auth login succeeds once the session is saved. loginWithDeviceAuth now takes
requiresLiveToken. The explicit auth login path leaves it off, so once the approved session is
written, a transient exchange failure (non-revoked HTTP, network error, or process_lock_timeout)
warns and returns the approved pair; auth login --json exits 0. resolveRemoteAuth and
resolveCloudAccessForConnect pass requiresLiveToken: true and keep propagating, because they
send the token themselves. A revoked answer still refuses both. Tests: auth login succeeds when the exchange of its expired approval token gets 503 (commands/tests/auth.test.ts, the requested 503
case, asserting exit 0, the saved session, and no reported token expiry) and
an expired approval token whose exchange fails transiently keeps the login and fails the caller that spends the token (auth-session-refresh.test.ts, 503 through both callers). The round-1 thread
#4927 (comment) is fixed by this; I
resolved it.

2. One lock acquisition, reusing the refresh routine, returning the snapshot. The save and the
immediate exchange now run inside a single withCliSessionLock(..., keepWaiting: true) task, and the
exchange is the same exchangeCliSessionAccess the commands use, run on the record just written. It
returns the session snapshot and token pair it produced, so login output no longer re-reads the file
after the lock is released, and neither a sibling login nor a logout in that gap can pair another
session or a pre-rotation expiry with this token. The reported expiresAt is the refresh response's
access-token expiry, absent when the response omits it. Approval polling stays outside the lock.
Tests: a login that exchanges an expired approval token does it under the acquisition that saved the session (asserts one acquire, the refresh inside it, then release, and that the credential sent
is the one just saved) and the existing expiry-pairing test in commands/tests/auth.test.ts.

3. Revoked and tokenless refusals carry one constant reason and no response text. Both refusals
now publish details.reason: 'cli_session_revoked' from a CLI_SESSION_REASONS
ReasonTable<'auth'> and drop status and error from the details, so nothing the response
supplied reaches the message, the details, or --json. pnpm generate:reasons regenerated
website/docs/docs/error-reasons.md. Test: a refused refresh carries its reason and no text from the response (auth-session-refusal.test.ts) runs the revoked-with-token case in both fields and the
tokenless case in both fields, and asserts an echoed opaque credential appears nowhere in the
serialized error.

4. Unwritable auth directory. I took the typed-error option: the store stays lock-mandatory, and
a write refusal (EACCES, EPERM, EROFS) while preparing the lock answers
COMMAND_FAILED with details.reason: 'cli_session_store_unwritable', details.authDir, and a
chmod 700 <dir> hint naming that directory, instead of a bare filesystem error. The case is
documented in commands.md. Test: a session store that cannot be written refuses with the directory to repair (a real 0500 auth directory; asserts no credential is sent and the session is unchanged).

5. Bounded refresh lock acquisition. Confirmed still true at this head: resolveCliSessionAccess
acquires without keepWaiting, so a timed-out wait fails with process_lock_timeout and sends no
request; only the approved login's save keeps waiting. Covered by a timed-out session lock wait keeps a login waiting and fails a refresh read with its reason.

Took the non-blocking suggestions that overlapped these: the post-exchange file re-read is gone,
replaced by the returned record, and readStoredSession and the approval-token expiry fallback went
with it. Left cliSession.expiresAt storage and the bounded second exchange as they were; both are
already covered and dropping them now would widen this round's diff.

Validation at 11ea3a7: pnpm format, pnpm typecheck, pnpm lint, pnpm check:layering and
npx vitest run src/cli pass, plus the reason-table and command-doc guards. Each new test fails when
its own fix is reverted. No device run: CLI auth only.

@thymikee

Copy link
Copy Markdown
Member Author

This follow-up covers 11ea3a7. The two earlier findings from the previous review are fixed: a non-revoked exchange failure after the save now returns the approved pair for explicit login, and the exchange runs on the record just written, inside the same lock acquisition. Six issues remain in the new code, and they must be fixed before merge.

A second independent pass found that explicit auth login can save an approved session with an expired access token and then treat a tokenless refresh as a confirmed revocation (auth-session.ts#L691). A 200 response with an empty body, or one with no access token, sets cli_session_revoked. The catch at line 329 then exits with an error although the session is saved and the cloud never reported revocation. The rule: a missing access token gets its own fixed failure reason, and only an explicit revocation marker produces cli_session_revoked. Explicit login then keeps the saved session on a tokenless response, and implicit callers still fail.

A second independent pass found that a refresh that answers HTTP 401 with a JSON body reporting revoked is never classified as revoked (auth-session.ts#L652). cloud-response.ts#L11 rejects the HTTP status before the refresh classifier at line 673 sees the marker. The catch at line 329 treats it as transient, so auth login prints success. The same branch contradicts the blanket cli_session_revoked claim at commands.md#L2686. The rule: classify the exact revocation markers on refresh responses before generic HTTP handling, copy no body text into errors, keep generic status handling for other HTTP errors, and limit the documented reason to confirmed revocation.

A second independent pass found that device approval can abort explicit login after its save (auth-session.ts#L307). If the approval returns an expiresAt object with a string-valued toString, the response is cast without runtime validation. After the save at line 306, Date.parse at line 920 throws a TypeError before the recovery catch. Base a9750b5 returned the approved result after the save without coercing the expiry (base lines 277-285). The rule: only a nonempty string counts as the approval's access-token expiry before isExpired runs, and any other type is omitted.

A second independent pass found that a failed second exchange makes auth login --json report the pre-rotation session (auth-session.ts#L335). The first exchange of an expired approval token rotates the credential and saves a new session expiry, but it still returns an expired access token. The second exchange gets HTTP 503, and the fallback returns the original approved session. Login then prints an expiresAt that differs from auth status for the same session ID. The rule: while the same lock is held, the explicit-login fallback uses the last successfully saved session snapshot, and omits the token expiry when the exchange yielded no usable token.

A second independent pass found a related case where a failed rotation write makes login report an expiry it did not save (auth-session.ts#L572). The exchange returns a fresh token, a replacement credential and a new session expiry, but the write fails before rename. storeRotatedCredential then returns the in-memory record at line 633 while the disk still holds the approval record, and auth login --json prints the unsaved expiry through commands/auth.ts#L32. Base reported the same expiry as the record it saved. The rule: keep the next exchange's credential separate from the session snapshot returned for login output, report the last successfully saved record, and keep the returned access token's own expiry.

A second independent pass found that a normal remote command can now fail where base succeeded (auth-session.ts#L563). The cloud returns an access token its daemon would still accept, but the CLI clock is ahead of that token's expiry. Base (a9750b5 lines 425-442) forwards the token. Head makes a second refresh and aborts before dispatch if that request hits HTTP 503 or a transport failure. The rule: an existing session uses one locked exchange, or keeps the first token when an optional second exchange fails transiently, and a confirmed revocation still fails.

Not blocking: the transient-failure fallback at auth-session.ts#L335 can print the pre-rotation expiresAt when the first exchange rotates and the second fails, which the fourth finding above covers, and cli_session_revoked at auth-session.ts#L30 also labels a malformed 200 response and is declared only for connect although every remote command that refreshes can publish it, so a follow-up issue could give the tokenless refusal its own reason; both can be taken or left.

Could the shape be smaller? loginWithDeviceAuth could save under keepWaiting and return the approved pair, as at base, so explicit auth login never exchanges. The two implicit callers (resolveRemoteAuth at line 157 and resolveCloudAccessForConnect at line 210) would then run withCliSessionLock(() => exchangeCliSessionAccess({ session: login.session, ... })) when isExpired(login.expiresAt). Passing the returned record, not rereading the file, sends this login's own credential and returns this login's token. storeRotatedCredential already skips the write if a sibling replaced the file, so the earlier sibling-token fix holds without the shared acquisition. This would delete requiresLiveToken, isCliSessionRevoked and the warn-and-fallback branch, and it would also remove the default-false flag that gives a future caller an expired token silently. This is not required for merge, and the earlier round did ask for save and exchange in one acquisition, so the call is yours.

The two open inline threads from the earlier round no longer apply, and both are safe to resolve: the 503 after save is fixed at 11ea3a7 and covered by the test 'auth login succeeds when the exchange of its expired approval token gets 503', and the exchange on the saved record now runs inside the acquisition that wrote it, with no file read in between.

All 14 checks were queued or in progress when this was written, so CI has no result yet. The diff overlaps Lint/Typecheck, Coverage, Integration and Repo Guards & Compatibility, because the new reason table feeds the generated error-reasons.md that test/repo-guards/reason-tables.test.ts checks. Not verified here: the tests, check:affected and pnpm generate:reasons were not run, and that the new tests fail at 2d67cec was judged by reading the code. Not verified here: the unwritable-directory test relies on chmod 0500 and would not refuse under a root runner, and the runner identity was not checked. Not verified here: the cloud's real behavior for a rotation that answers with an expired token. There are no conflicts. After the six fixes and a green CI run, nothing else stops the merge.

…ssion

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

Copy link
Copy Markdown
Member Author

All six findings from this round are fixed in 8469cdf. Each was reproduced as a test first, and each test was then checked against a revert of its fix.

1. A tokenless refresh answer gets its own reason. The reason table declares cli_session_refresh_unanswered beside the existing rows, and pnpm generate:reasons publishes it. cli_session_revoked is reserved for an explicit revocation marker, so explicit login keeps the saved session on a tokenless answer, while a caller that spends the token itself still fails. Pinned by 'a refused refresh carries its reason and no text from the response' and 'a tokenless refresh keeps the session an explicit login saved and a revoked one fails it' (src/cli/tests/auth-session-refusal.test.ts).

2. Exact revocation markers are classified before the generic HTTP rejection. readCloudJsonResponse takes a classifyRejectedBody hook and calls it on the parsed body before it rejects a status, so a 401 or 503 whose JSON body reports revoked is answered as confirmed revocation. Any other body keeps the generic status refusal, including a body that is not JSON, which is read as carrying no marker. The refusal is built in auth-session.ts, so no body text is copied. website/docs/docs/commands.md now documents cli_session_revoked only for the exact marker and names the new reason for the tokenless answer. Pinned by 'an approval that reports revocation over HTTP is refused and never echoes its body', 'a rejected refresh without the revocation marker keeps the generic status refusal' and 'a rejected response is offered to the classifier before its status is rejected'.

3. The approval's access-token expiry must be a nonempty string. Anything else is omitted before isExpired runs, so a foreign value cannot reach Date.parse after the session is saved. Pinned by 'an approval whose access-token expiry is not a string is reported without an expiry'.

4. and 5. The login's output is the last successfully saved session, and its next credential is kept separate. exchangeCliSessionAccess now carries saved, the last record known written, apart from asked, the credential the next exchange asks with. A rotation whose write failed is asked with again and never reported, and the fallback for an expired approval token returns the approved pair without the expiry of a token whose exchange never answered, so auth login --json and auth status agree for one session ID. Pinned by 'a login whose rotation could not be saved reports the record on disk and its own token expiry' (src/cli/tests/auth-session-exchange.test.ts).

6. An existing session uses one locked exchange, or keeps the first token. When the optional second exchange fails with a transport failure or a retriable status, the token the cloud already answered with is kept, paired with the record as last stored, so a command base dispatches is not aborted. A confirmed revocation is never treated as transient and still fails. Pinned by 'an optional second exchange that fails transiently keeps the token already answered' and 'a login whose second exchange fails reports the session its first exchange stored'.

Each revert makes exactly the test that pins it fail: relabelling the tokenless reason, removing the classifier hook, trusting a non-string expiry, reporting an unsaved rotation, and aborting on the failed optional exchange.

Validation from this worktree: pnpm format, pnpm typecheck, pnpm lint, pnpm check:layering, pnpm generate:reasons and npx vitest run src/cli test/repo-guards pass (825 tests). On the smaller shape: I kept the single save-and-exchange acquisition the earlier round asked for rather than moving the exchange to the two implicit callers, so one acquisition continues to own the approval.

This is the last round for this PR. Further hardening goes to issue #4849: giving the reasons a refreshing remote command publishes an owner that matches how they are reached, and refusing the unwritable-directory test under a root runner.

@apex-sentinel-staging

Copy link
Copy Markdown

Apex Sentinel · ✅ Approve · review of 8469cdf

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

No open findings.

1 finding below minor hidden (user_settings.min_severity).

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

💬 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 follow-up on the earlier review (#4927 (comment)) covers 8469cdf. The earlier findings are fixed, but a second independent pass found five problems that remain. CI is green: 16 checks, none failing, including the guards that check the generated error-reasons.md against the new reason row. There are no conflicts. No tests were run here, and the author's local validation was not reproduced. Not verified here: whether the real cloud sends the revoked marker on a non-2xx status, or how its daemon handles a token the CLI clock calls expired.

A second independent pass found that a refresh can return a valid access token with an expiresAt object whose toString is a string (auth-session.ts:716). Head passes that object to Date.parse at lines 606 and 976, which throws outside the optional-exchange catch. A stored-session command then aborts before dispatch, although base a9750b5 forwards the token. During an explicit login, the catch at lines 331-344 can also report the old approval snapshot while auth status reads the newer expiry. Please apply the same nonempty-string guard used for the approval expiry at line 297 to the refresh expiry before the exchange loop uses it.

A second independent pass found that a stored-session connect can lose a usable first token (auth-session.ts:713). The service accepts the first token while the CLI clock calls it expired. The optional second refresh then returns a nonblank token with an internal newline, and head replaces the first token with it at lines 602-607. Building the profile request in cloud-profile.ts:74 throws a Node header error that includes the response-supplied value. That message is published through errors.ts:508 and cli.ts:665. Please reject access tokens that cannot be sent safely in a Bearer header at the refresh boundary, with a fixed error and no raw value or cause. The existing second-exchange fallback can then keep the first token.

A second independent pass found that a later-arriving token can replace a better one (auth-session.ts:602). Say the CLI clock reads 01:00 while the cloud and daemon read 00:20. The first refresh returns a token that expires at 00:30. A second response, for example from a stale cache, returns one that expired at 00:10. Head replaces the first token unconditionally and sends the second, and the daemon rejects it. Base a9750b5 sends the first token and dispatch succeeds. When both responses have known expiries and the second is already expired locally, please keep the first token and its own expiry if its deadline is later. The saved session snapshot should be kept independently.

A second independent pass found that a successful refresh with the JSON body null bypasses the new tokenless reason (auth-session.ts:713). The revocation guard at lines 740-743 handles null, but the accessToken read then throws a TypeError. A remote command or connect reports UNKNOWN instead of cli_session_refresh_unanswered, which contradicts commands.md:2686. The bare error also exists at base, before the reason was documented. Please treat a null success body as a tokenless refresh after the revocation check, and keep the generic HTTP refusal for rejected responses without a marker.

A second independent pass found that the command docs promise more than the code does (commands.md:2686). A stored-session command can get a first token that is already expired on the CLI clock, then an HTTP 200 with an empty object on the optional second refresh. The exchange keeps the first token and dispatches (auth-session.ts:578), yet the docs say a tokenless response fails with cli_session_refresh_unanswered. The docs also promise a warning when exchanging an already-expired approval token fails transiently, while the tested second-exchange 503 path produces none (auth-session-exchange.test.ts:295). Please scope the refusal and warning to an exchange that obtained no usable answer to return, and say that the optional second attempt can keep the first token silently. Generic unmarked HTTP errors should stay distinct from successful tokenless responses.

Not blocking, take or leave: the docs sentence at commands.md:2686 should say "a successful refresh response that carries neither a token nor that marker", since other HTTP errors keep their status refusal; the comments at cloud-response.ts:8 and :21 say the opposite of the code (line 8 should read "a response whose status is not OK", line 21 "Only a body that parses can hold a marker"); and the test at auth-session-refusal.test.ts:123 should be renamed "a refresh that reports revocation over HTTP …", since it drives a refresh, not an approval.

Of the earlier inline threads, the two on a 503 after the approved save (#4927 (comment)) and on exchanging the expired token inside one lock (#4927 (comment)) are fixed at head and can be resolved. No other earlier thread still applies.

Once the five items above are fixed, nothing else stands between this PR and merge. The non-blocking notes can go to follow-up issue #4849.

@thymikee

Copy link
Copy Markdown
Member Author

Thanks for the round-4 review. As said in round 3, this PR takes no more hardening. I moved all five items to #4849: #4849

@thymikee

Copy link
Copy Markdown
Member Author

Acknowledged: the five round-4 items now live in #4849, so they no longer block this PR. The earlier findings are fixed at 8469cdf, CI is green, and there are no conflicts.

@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 1b90bcd into feat/cli-session-refresh-rotation Nov 22, 2026
16 checks passed
@thymikee
thymikee deleted the fix/cli-session-refresh-followups branch November 22, 2026 10:14
thymikee added a commit that referenced this pull request Nov 22, 2026
…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 added a commit that referenced this pull request Nov 22, 2026
…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 added a commit that referenced this pull request Nov 22, 2026
… code (#4833)

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

* fix(auth): state the rotation contract and name the flag for what the CLI accepts

* fix(auth): serialize CLI session file changes under one process lock

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.

* fix(auth): keep an approved login or rotated credential through session 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.

* fix(auth): keep a committed session change when the lock warning cannot 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.

* test(auth): cover a failed session lock release and a throwing stderr after a stored rotation

* fix(auth): write the unsaved-rotation warning best effort too

* fix(auth): never drop an approved login or a rotated credential on a 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.

* fix(auth): absorb late stderr write errors with one listener per stream

* fix(auth): hold the CLI session lock across a refresh and keep its access 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.
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