Skip to content

fix(cli): create connection state root privately before locking - #5148

Closed
MilindChatrabhuji wants to merge 4 commits into
callstack:0.22from
MilindChatrabhuji:fix/cloud-state-dir-umask-5137
Closed

MilindChatrabhuji wants to merge 4 commits into
callstack:0.22from
MilindChatrabhuji:fix/cloud-state-dir-umask-5137

Conversation

@MilindChatrabhuji

@MilindChatrabhuji MilindChatrabhuji commented Nov 27, 2026 •

Copy link
Copy Markdown

Summary

Fixes #5137.

Invariant: Connection admission repairs owned group/other-writable state roots (0o775/0o777 -> 0o700), preserves owned non-writable roots (0o750/0o755) on connect/disconnect, creates missing roots/subdirectories privately via physical-parent walks and O_DIRECTORY | O_NOFOLLOW descriptor fchmodSync, waits on 0o500 init under umask 0200, keeps admitted (dev, ino) handles open across locks/writes, and keeps update-check active without creating stateDir.

Before / after

# Prior head (2f6490bec):
# - refused owned 0o775 roots on CLI/connect; mutated 0o750/0o755; skipped update-check without stateDir
# - locked/wrote via pathname re-resolution; alias /tmp under umask 0700 left 0o000; broke linked config dirs

# Current head:
# - removed refuseWritableRoot; preserveNonWritableRoot only skips tightening owned 0o750/0o755 on connect/disconnect
# - physical parent verified before mkdir; fchmod via descriptor; 0o500 wait returns retriable PrivateDirectoryInitializingError
# - VerifiedDirectoryHandle stays open across process-lock & cloud record/attachment writes
# - update-check uses XDG/HOME cache when stateDir is absent; generated-config & remote-connection-state set allowOwnedSymlinks

Validation

Validated on Windows 11 (Node v22.14.0):

  • oxfmt --check (19 files), pnpm typecheck, scripts/layering/check.ts (2080 files), oxlint . --deny-warnings (5614 files), tsdown --config-loader native (553 files): passed.
  • Vitest (--project unit-core): non-POSIX cases passed in file.test.ts, daemon-resolution-state-root.test.ts, remote-connection-state.test.ts, cloud-connection-record.test.ts, command-connection.test.ts (at --testTimeout=60000), and -t filtered cli-state-root-admission.test.ts / update-check.test.ts. POSIX umask 002/0200/0700, symlink, and cli-cloud-session.test.ts suites require Linux/macOS CI approval.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

All reported issues were addressed across 5 files

Reply with feedback, questions, or to request a fix.

View guided diff | Re-trigger cubic

@thymikee

Copy link
Copy Markdown
Member

Thanks for working on the umask 002 failure. The review of f7d8f47 found that some routes can still leave the state root unusable, unsafe, or changed.

In cli.ts:200, a second independent pass found that the update notifier can still create a fresh root at 0o775. In a non-JSON interactive connect with a fresh state directory and umask 002, the detached update worker can finish before command dispatch, and its cache writer uses a recursive mkdir with no mode. The new helper then sees an existing directory and skips it, so connect still fails with cloud_credential_store_unsafe. On connect, the notifier must never create the state root: run it after the root is initialized, or skip the cache write while the root is absent.

At command-connection.ts:51, a second independent pass found that connect and disconnect change a caller-owned 0o775 or 0o777 root under a trusted parent before cloud admission sees it. The root check repairs the mode to 0o700, so admission passes. The base does the same, but it breaks the promise to preserve and refuse such a root. Every affected connection command must admit the root without changing it, keep the ancestry, type and owner checks, and refuse group- or other-writable roots before any repair or lock.

At cloud-connection-record.ts:163, a second independent pass found that recursive creation can fail before the chmod runs. For a non-root POSIX user with umask 0200 and a missing parent, the parent is created at 0o500 and creating the root inside it fails with EACCES. Both lock wrappers and standalone credential creation use this helper. Each missing level must be created on its own and get its exact mode before the next level, and existing directories must stay untouched.

At cloud-connection-record.ts:167, a second independent pass found that the chmod can hit a directory this call did not create. If this call creates a missing parent and a concurrent process creates the root, mkdir returns the parent path, and the other process's 0o775 root becomes 0o700 and passes admission. If the root can be replaced by a symlink between mkdir and chmod, the target's mode changes and later writes can follow the link. The subdirectory chmod also depends on a stable parent. A mode change must apply only to a directory this call created exclusively (EEXIST means existing), under a parent that prevents replacement or through a verified directory handle. A substituted root must be refused before any lock or write.

At cloud-connection-record.ts:74, a second independent pass found that the lock can see an unfinished root or recreate a vanished one. Under umask 0200, a second process can see the 0o500 root between mkdir and chmod, return early, and fail to create its lock. If the root vanishes before locking, the lock helper (also here) recreates it with default permissions, which gives 0o775 under umask 002. No caller may use the root before it is ready. Both connection lock paths must require the prepared root, and refuse or repeat private initialization if it is gone.

At cloud-connection-record.ts:135, a second independent pass found that a credential write can rebuild the root after the lock was taken. If the state directory is reset while connect waits for its provider, the pending record rewrite recreates the root and publishes into it, and a second lock for the same session becomes possible. The base refuses this rewrite. Writes made under a lock must require the root admitted for that lock and refuse if it disappears or changes. Only the initial or standalone write path may create it.

At remote-connection-state.ts:412, a second independent pass found that under umask 0200 a missing remote-connections directory is created at 0o500 and the record write fails. A missing state root passed to this writer gets the same mask. Every level this writer creates must get its exact mode before anything is created or written inside it, without changing existing directories.

Could connect call admitDaemonStateRoot({ paths: resolveDaemonPaths(flags.stateDir, host), mode: 'establish' }) once in connectCommand before withConnectionLock, or could resolveCommandConnection pass 'establish' for connect? Then ensurePrivateStateRoot and its three call sites could be deleted. This is about 3 production lines, reuses the rule from #4649, and keeps the symlink and ancestry checks.

On the open threads, the Windows ownership one does not apply: Windows admission checks only the path shape by design (ADR 0016), the base had no ACL privacy either, and this change claims none. The remote-state mode one does not apply to the umask 002 case in #5137: the base fails the same way under an owner-bit mask, and current production routes create the root first. The stricter owner-bit case is still requested above for remote-connection-state.ts.

CI is pending. The main Linux and macOS jobs are waiting for fork approval, so none of the new POSIX umask and ownership tests has run. The reported validation ran on Windows, where these tests are skipped.

Not verified here: no test was run locally, and the claim that the CLI regression test fails on the base comes only from reading the code. Not verified here: whether an older concurrent agent-device process can create the root at 0o775 between the helper's lstat and mkdir.

Before merge, the problems above need fixes, and the umask tests must run and pass in fork-approved CI.

@thymikee

Copy link
Copy Markdown
Member

Thanks for the update. At 114e208, parent directory creation under umask 0200 and the Windows handling raised earlier are fixed, but the problems below still need changes in the code.

The first open problem from the earlier review remains on a non-JSON interactive connect with a fresh state directory and umask 002. The upgrade notifier runs before dispatch, and its update worker or prompt writer creates the state root with a recursive mkdir and no mode. The root is then 0775, private setup accepts the existing root, and cloud admission refuses it, so connect likely still fails with cloud_credential_store_unsafe, as reported in #5137. No writer may create the state root on a connect route before private setup. The smallest fix is to establish the root in resolveCommandConnection for connect (admitDaemonStateRoot in establish mode), which runs before the notifier. Skipping the cache write while the root is absent is an alternative. Please validate this exact route and show that the root is private and connect succeeds. Not verified here: the timing of the detached update worker was not reproduced.

The second earlier problem also remains, and it is a regression against the base. writeCloudConnection now creates the state root before writing. If the root is removed while connect waits for its provider, the pending-record rewrite likely recreates it and publishes without the connection lock that lived in the old root, so a second connect for the same session can take a lock while the first still writes. The base refused this rewrite. Only the initial or standalone write path may create the root. Every write made under a connection lock must require the root admitted for that lock and refuse if it is absent. Creating the root once before the lock, and removing root creation from admitCloudCredentialDirectory, achieves this. Not verified here: this was confirmed by reading the code, not by a run.

Also, a second independent pass found that the helper applies chmod by pathname under a parent that may permit replacement. If the new entry is replaced before chmod, chmod likely follows a symbolic link and changes the substituted target. This race remains for the cloud root at both lock wrappers (also line 91) and the credential write, and this change adds it to the remote state writer. Cloud admission uses stat, so a link to an otherwise acceptable directory can also redirect a later credential write. Each missing level must be created inside an admitted, stable parent. The mode must apply only to the directory this process created. A changed root must be refused before locking or writing, and those operations must use the verified directory identity.

In addition, a second independent pass found that a concurrent caller can likely use a directory before it has its final mode. On POSIX with umask 0200, one caller creates the root as 0500 and pauses before chmod, while another sees it as existing or gets EEXIST and continues. The lock wrappers, standalone credential subdirectory creation and the remote state writer can then reach a directory without owner write access. Initialization must return only when the directory is ready. If another caller owns initialization, wait for it or return a retriable refusal, and leave that caller's directory mode untouched.

Related to this, a second independent pass found that both connection lock wrappers can recreate a vanished root with default permissions. If the prepared root disappears before the lock starts, generic lock parent creation (process-lock.ts lines 180 and 397) can recreate it as 0775 under umask 002 and write the lock before cloud admission refuses the root. Every lock path must require the initialized root, disable generic parent creation, and refuse or restart private initialization if the root disappears before acquisition.

Finally, a second independent pass found the same rewrite risk at the credential write when the root is reset during the provider wait. The pending-record rewrite and the attachment writes in cloud-attachment.ts can create a new root and publish without a lock in it, while a second process acquires the same session lock there. Root creation must be limited to standalone initialization. The session lock must pass the admitted root identity to all record and attachment writes, which must refuse if that root is absent or changed.

The two earlier inline threads no longer apply and can be resolved: Windows ACL privacy is not claimed now, because chmod is skipped on Windows, the doc says so, and Windows admission checks only the path shape by design; remote state modes are fixed because each created level gets mode 0700 before the next one is created.

CI is still pending: one reported check passes, and the main Linux and macOS jobs wait for fork approval. The new POSIX umask tests in file.test.ts, remote-connection-state.test.ts, cloud-connection-record.test.ts and cli-cloud-session.test.ts cover the changed paths, but they have not run in CI and are skipped in the reported Windows run. Not verified here: no test was run locally.

Before merge, please fix the problems above, starting with the two earlier ones (establishing the root once with admitDaemonStateRoot in establish mode on the connect route is the starting point for both), and then get the POSIX umask tests passing in CI after fork approval.

@MilindChatrabhuji

Copy link
Copy Markdown
Author

@thymikee Thank you for the detailed review on 114e208! Addressed every remaining item in 2f6490bec9bdb392372d4d219f5cb16eb25a61af:

  1. Update notifier on interactive connect (src/cli/update-check.ts): maybeRunUpgradeNotifier and writeUpdateCheckCache now skip initialization/writes when stateDir does not yet exist, so connect remains the sole path establishing a fresh root privately.
  2. Preserve and refuse writable caller-owned roots (src/cli.ts, src/cli/connect-preflight.ts, src/cli/connection/command-connection.ts, packages/daemon-contracts/src/daemon-resolution.ts, packages/host-kit/src/internal/script-destination.ts): Added refuseWritableRoot?: boolean to admitPrivateRoot/admitDaemonStateRoot and passed establishRoot: base.command === 'connect' + refuseWritableRoot: true so connect creates missing roots via establish while connect/disconnect refuse pre-existing group/other-writable ((mode & 0o022) !== 0) roots unchanged before repair or lock acquisition.
  3. Per-level creation under umask 0200, concurrent init, and symlink-safe descriptor fchmod (packages/host-kit/src/file.ts, packages/host-kit/src/internal/script-destination.ts, src/cli/connection/generated-config.ts): ensurePrivateDirectorySync and createMissingLevel now create each missing level step-by-step inside a verified parent, open via O_DIRECTORY | O_NOFOLLOW + fstatSync identity, apply fchmodSync only on descriptors created by this process, and bound-wait (Atomics.wait / PrivateDirectoryInitializingError) when another caller is still finishing a 0o500 init under umask 0200 without mutating existing directory modes. generated-config.ts now uses ensurePrivateDirectorySync.
  4. Lock parent creation and locked state root identity across writes (packages/host-kit/src/internal/process-lock.ts, src/cli/connection/cloud-connection-record.ts): Added ensureParentDir?: boolean (false in withConnectionLock / tryWithConnectionLock), verified (dev, ino) with verifyDirectoryIdentityNoFollow, and propagated the locked state root via AsyncLocalStorage (assertLockedCloudStateRoot) so credential/attachment writes refuse (cloud_credential_store_unsafe) instead of recreating a vanished or replaced state root during provider waits.

Local Verification (2f6490bec, Windows 11 / Node v22.14.0)

  • oxfmt --check (16 files): passed
  • pnpm typecheck, scripts/layering/check.ts (2080 files), oxlint . --deny-warnings (5614 files, 0 warnings/errors), tsdown --config-loader native (553 files): all passed
  • Vitest (excluding win32-skipped POSIX umask/chmod cases): file.test.ts (2 passed, 4 skipped), process-lock.test.ts (42 passed, 1 skipped), daemon-resolution-state-root.test.ts (1 passed, 29 skipped), remote-connection-state.test.ts (9 passed, 4 skipped), command-connection.test.ts (5 passed), cloud-connection-record.test.ts (4 passed, 5 skipped)
  • Targeted new tests (-t filter with an external Windows junction shim for @agent-device/maestro/replay workspace links): update-check.test.ts (notifier and update worker skip creating a missing state root passed) and cli-state-root-admission.test.ts (interactive non-JSON connect establishes a fresh state root privately before the upgrade notifier and pending rewrite during connect provider wait refuses if the locked state root disappears passed). Unfiltered update-check.test.ts, cli-state-root-admission.test.ts, and cli-cloud-* hit Windows platform issues (\ vs / regex, process.umask, unprivileged symlinkSync, and verified-file.ts lstat vs fstat dev mismatch).

Linux/macOS CI approval after this push will run the POSIX umask 002/0200/0700, symlink, and full CLI cloud suites directly.

@thymikee

Copy link
Copy Markdown
Member

Thanks for the update.

At 2f6490b, connect now establishes the state root before locking and skips the early update notice, and new directory levels are set to 0700 one at a time, but problems remain after the earlier review.

command-connection.ts:53, line 175 and connect-preflight.ts:54 pass refuseWritableRoot: true on every CLI call, so script-destination.ts:601 and line 638 refuse an owned root, sessions or sessions/remote-scripts directory with group or other write bits (daemon_state_root_unsafe / not-private). The base changes it to 0700 and continues. A user or CI job with a 0775 state directory (umask 002, or left by the failed connect in #5137) can then run no command until a manual chmod 700, and #5137 asks to create the root privately or accept an owned group-writable one. The rule: no CLI route refuses an owned state root or managed directory that it can repair to 0700. Please remove refuseWritableRoot from admitPrivateRoot, admitDirectory, admitDaemonStateRoot and every caller, keep establishRoot for connect, and remove the refusal tests or make them assert that the root ends at 0700 and connect proceeds. The existing repair already closes an open root before cloud admission reads it.

A second independent pass found that an owned 0755 or 0750 root under a safe parent is still changed to 0700 by connect and disconnect at script-destination.ts:638, so the earlier request to preserve an existing root looks unmet. Can connection admission check ownership and type, then return for a root without group or other write bits before the repair chmod, while writable roots are still repaired as described above?

A second independent pass found that the option at command-connection.ts:53 also stops daemon status, connection status and profile-redirected roots on an owned 0775 root, and daemon-resolution.ts:162 applies it to the managed directory names, so even connect fails on a 0700 root with a 0775 sessions directory. ADR 0016 describes repair for these callers. Does every one of these routes repair again once the option is removed?

A second independent pass found that connect-preflight.ts:54 makes connect cloud list with a bound API key fail on an owned 0775 root, although this path takes no connection lock and writes no credential. Can this listing path keep the base admission?

A second independent pass found that a root moved aside and replaced after admission can receive lock files before cloud-connection-record.ts:92 leads to an identity check: both the awaited and the try path lock by pathname, so the guard and claim can be written into the replacement. Can lock and guard creation and removal stay bound to the admitted root identity, since a check after acquisition is too late?

A second independent pass found that verification closes the directory handle, so a root replaced after the check can receive record or attachment bytes through cloud-connection-record.ts:189, the record publisher and the attachment writer, which resolve the original path again. Can the admitted identity stay live through publication, with subdirectory creation and both credential writes resolved inside that directory?

A second independent pass found that file.ts:271, and the daemon establish path at script-destination.ts:560, still chmod by pathname after the last lstat, so a swapped entry can be changed; the immediate-parent check can also miss an unsafe shared ancestor or accept another user's sticky directory, and a directory swapped in before the first lstat after mkdir can pass as the created one. Can one creation path verify a stable parent before each level and set the mode, without following links, only on the entry it created?

A second independent pass found that on macOS with umask 0700, a missing root directly under /tmp is created, then file.ts:253 rejects the /tmp alias parent and leaves the root at 0000. Can creation and mode setting both use the admitted physical parent, checked before mkdir?

A second independent pass found that with umask 0200 a second writer can see an unfinished 0500 directory and return it at cloud-connection-record.ts:214, then fail with EACCES; the CLI establish route can likewise descend into or admit an unfinished level. Can observed entries get the same readiness check as EEXIST ones, ending in a wait on the same directory or a typed retriable refusal?

A second independent pass found that generated-config.ts:32 now rejects a remote-connections/generated link to an owned private directory, and remote-connection-state.ts:412 rejects a linked remote-connections; both worked on the base. Can the new link policy apply only to the state root and credential store, while missing directories are still created privately?

A second independent pass found that read-only commands such as daemon status on a fresh state directory no longer schedule the update check at update-check.ts:42, because nothing creates the root. Can these commands keep the update notice, with its cache stored independently of the root if the notifier must not create it?

These earlier threads do not apply at this commit and can be resolved: Windows privacy claim is settled because the doc names a POSIX-only privacy model, and per-level private creation is addressed because each level is set to 0700 before the next one is created.

CI is pending. One reported check passes. The Linux and macOS jobs wait for fork approval and have not run at this commit.

Not verified here: no tests were run locally. The refusal of 0775 directories comes from reading the code. It was not traced which writer creates sessions/ or with what mode; a plain mkdir under umask 002 would also cause a freshly established root to be refused. The effect of the script-destination.ts level changes on script saving was not traced. The interactive connect test would pass with either establishment or the notifier skip alone, so it does not show which one is needed.

Before merge, first make an owned group-writable root get repaired to 0700 instead of refused. The umask 002, 0200 and 0700 tests in file.test.ts, remote-connection-state.test.ts, cloud-connection-record.test.ts, cli-cloud-session.test.ts and cli-state-root-admission.test.ts must also pass on Linux and macOS after fork approval; the reported author run was on Windows only, where they are skipped. No device run is needed.

@MilindChatrabhuji

Copy link
Copy Markdown
Author

@thymikee Thank you for the second-pass review on 2f6490b — every point was spot-on and is addressed in e8c3a0057a506d6d834674c55ca83d520badd751:

  1. Repair owned 0o775/0o777 roots; preserve 0o750/0o755 on connect/disconnect (script-destination.ts, daemon-resolution.ts, command-connection.ts, connect-preflight.ts):
    • Removed refuseWritableRoot everywhere (admitPrivateRoot, admitDirectory, admitDaemonStateRoot, command-connection.ts, connect-preflight.ts). daemon status, connection status, connect cloud list, redirected roots, sessions/, and sessions/remote-scripts/ now all repair owned writable modes (0o775/0o777 -> 0o700) via the base admission path.
    • Added preserveNonWritableRoot?: boolean (set only for connect/disconnect via establishRoot || claimForDisconnect), returning early for owned directories without group/other write bits ((mode & 0o022) === 0) under safe parents while still repairing 0o775/0o777.
  2. Physical-parent creation, descriptor fchmod, /tmp alias handling, 0o500 waits, and symlink policy (script-destination.ts, file.ts, generated-config.ts, remote-connection-state.ts):
    • Consolidated ensurePrivateDirectoryWithAncestrySync / ensurePrivateChildWithAncestrySync on one physical-parent creation path (walkSpelledParent + verifyPhysicalParent resolving /tmp aliases BEFORE mkdir under umask 0700).
    • Checks (seen.mode & 0o077) === 0 before opening O_RDONLY | O_DIRECTORY | O_NOFOLLOW and fchmodSync(fd, 0o700); waits on observed unfinished 0o500 directories (both pre-existing and EEXIST) and throws typed retriable PrivateDirectoryInitializingError.
    • Kept the no-symlink policy on state root and credential store while passing { allowOwnedSymlinks: true } in generated-config.ts and remote-connection-state.ts.
  3. Live root identity across locks & credential writes (process-lock.ts, cloud-connection-record.ts, cloud-attachment.ts):
    • Added assertParentIntact + resolveEntryPath hooks to acquireProcessLock / tryAcquireProcessLock (withConnectionLock / tryWithConnectionLock) so lock dir, guard, claim, and release operate through the admitted VerifiedDirectoryHandle (/proc/self/fd/<fd> on Linux + pre/post assertDirectoryHandleIntact on POSIX).
    • withCloudCredentialFileTarget keeps rootHandle, cloudHandle, and connHandle open through both writeCloudConnection and writeCloudAttachment, and openOrCreateVerifiedSubdir waits on 0o500 subdirs and throws PrivateDirectoryInitializingError when still unready.
  4. Update notifier on read-only commands (src/cli.ts, src/cli/update-check.ts):
    • maybeRunUpgradeNotifier still shows notices and schedules background checks when stateDir is absent by caching under $XDG_CACHE_HOME (or $HOME/.cache) /agent-device/update-check/<hash>.json without creating stateDir; once stateDir exists, it uses stateDir/update-check.json.

Validation (e8c3a0057a506d6d834674c55ca83d520badd751, Windows 11 / Node v22.14.0)

  • oxfmt --check (19 files), pnpm typecheck, scripts/layering/check.ts (2080 files), oxlint . --deny-warnings (5614 files, 0 warnings/errors), tsdown --config-loader native (553 files): passed.
  • Vitest (--project unit-core --maxWorkers=1, external Windows junction shim):
    • file.test.ts (2 passed, 4 win32-skipped), daemon-resolution-state-root.test.ts (1 passed, 29 win32-skipped), remote-connection-state.test.ts (9 passed, 4 win32-skipped), cloud-connection-record.test.ts (6 passed, 6 win32-skipped)
    • command-connection.test.ts: 5/5 passed with --testTimeout=60000 (slow-test gate triggered locally by Windows PowerShell CIM probes in process-lock/owner-identity)
    • Filtered (-t): cli-state-root-admission.test.ts (2 passed: interactive non-JSON connect and pending rewrite during connect provider wait) and update-check.test.ts (1 passed: notifier uses an independent cache when state root is absent)
  • Linux/macOS CI approval after this push is still needed to run the win32-skipped POSIX umask 002/0200/0700, 0o750/0o755 preservation, 0o775 repair, symlink, and full cli-cloud-session.test.ts / cli-state-root-admission.test.ts suites.

@thymikee

Copy link
Copy Markdown
Member

Thanks for the follow-up.

At e8c3a00, several problems from the earlier review are fixed: owned 0775 and 0777 roots and managed directories are repaired to 0700 again, connect and disconnect keep an owned 0750 or 0755 root, the /tmp alias parent is resolved before mkdir, owned links under remote-connections are allowed again, and read-only commands on a fresh state directory run the update check. Problems remain in the new waits, in the root identity handling and in the new update cache.

The new readiness wait at script-destination.ts:810 catches any owned directory without group or other write bits and without full owner access, such as a state root or sessions directory at 0555, 0550, 0510 or 0500. It waits about 150 ms and throws PrivateDirectoryInitializingError before the repair chmod, so every command keeps failing with an error that says to retry but never clears. The base repairs 0555 and 0550 to 0700 and continues, and a mode the owner can change should not decide whether a command runs (#4649). The same wait applies to every existing owned ancestor in the walk, so saving a script under an owned 0555 ancestor now fails too. In repair or establish admission, an owned directory that is not 0700 must be changed to 0700, unless the preserve rule first returns for an owner-accessible root without group or other write bits. Keep the wait only for readers that never repair (the cloud subdirectory readers), and in the walk only for levels that walk created.

A second independent pass found that the wait at script-destination.ts:810 also refuses an owned state root, sessions or sessions/remote-scripts directory at 0550 or 0500 under safe ancestry, which affects connect, disconnect, daemon status, connection status, connect cloud list and profile-redirected roots. The existing owned-directory repair must run before any initialization wait. Read admission must stay mode-compatible, and waits belong only on creation paths that need the directory writable.

A second independent pass found that the walk at script-destination.ts:373 now waits for owner write permission on an owned 0555 ancestor that it only traverses. Creating a state root, generated config, remote state or a script under an existing 0700 child worked on the base and now reports an initialization failure. Traversal must follow the existing ancestry rule, with a wait only on a directory that the operation needs to change and has reason to treat as still being created.

A second independent pass found that cloud record reads at cloud-connection-record.ts:497 now wait on, then reject, a private 0500 cloud-connections or per-session directory even when create is false, so a normal session command can fail before dispatch. Read admission must use the base type, owner and exposure checks, and readiness is required only for the write or child creation that needs it.

A second independent pass found that on macOS, lock work at cloud-connection-record.ts:183 still resolves the state root by pathname. A root moved and replaced after the last check can receive the guard or claim, release has the same gap, and the identity error comes after the change. Every guard, claim and cleanup operation must be bound to the already open root with descriptor-relative operations, as the Linux route does through its descriptor path.

A second independent pass found the same gap for writes at cloud-connection-record.ts:508: on macOS, a root replaced after the directory checks can receive record files or attachment credential bytes, and the later check cannot undo them. Every subdirectory creation and file publish must be descriptor-relative, with the root, cloud and session handles open until the final publish.

A second independent pass found that when umask removes owner read, script-destination.ts:627 changes the mode by pathname after checking the entry, so a replacement made in between can be changed. New cloud and session directories do the same at cloud-connection-record.ts:453-471, and the physical parent check does not compare the parent with the walked inode. Every creation must keep the checked parent identity, and set the mode with an inode-bound or no-follow operation, only on the directory it created.

A second independent pass found that the waits at script-destination.ts:571 can accept a different directory that takes the name during the wait, and the walk or root admission then continues on it. The cloud subdirectory wait at cloud-connection-record.ts:365-375 does the same and reopens the path at cloud-connection-record.ts:498. Every wait must compare each observation with the first device and inode, carry that identity through the open, refuse a changed one, and return the retriable error if the original stays unready.

A second independent pass found that on Linux without /proc/self/fd, a fresh uncontended connect or disconnect that could lock by pathname on the base now fails at cloud-connection-record.ts:180 with ENOENT, reported as cloud_credential_store_unsafe, and standalone credential writes use the same missing path. Every lock and credential operation must be descriptor-relative in a way that also works without procfs, while diagnostics keep the logical state path.

A second independent pass found that with an absent state root, the update worker can write through a symlink in an existing shared XDG fallback cache and overwrite its target (update-check.ts:168). Setup errors are ignored, and the directory kind check and mode 0600 do not prevent this. The fallback cache directory must be admitted before the worker gets it, and cache data must be published through an exclusive temporary file and an atomic rename that does not follow the final entry.

These earlier threads do not apply at this commit and can be resolved: Windows privacy claim is settled because the POSIX-only privacy model is documented and Windows behavior is unchanged since the previous review, and per-level private creation is fixed because each created level is set to exactly 0700.

CI is pending. One reported check passes. The Linux and macOS jobs, which run the tests on the changed paths, wait for fork approval and have not run at this commit.

Not verified here: no tests were run locally, and the 0555 failure comes from comparing the base and new admission code, not from a reproduction. The /proc/self/fd lock and credential paths were not run on Linux. It was not traced whether a caller outside the CLI (Node API or MCP) writes remote connection state under a state directory that was never admitted, which would now meet the walk's ancestry refusals instead of a plain recursive mkdir. It could not be confirmed that the regression tests fail on the base, because they are POSIX-only.

Before merge, first restore the 0700 repair for owned directories that lack full owner access, such as 0555 and 0550, and limit the walk's wait to levels it created. Then the umask 002, 0200 and 0700, 0750 and 0755 preservation, 0775 repair and owned-symlink tests in file.test.ts, daemon-resolution-state-root.test.ts, remote-connection-state.test.ts, cloud-connection-record.test.ts, cli-cloud-session.test.ts, cli-state-root-admission.test.ts and update-check.test.ts must pass on Linux and macOS after fork approval; the reported author run was on Windows only. No device run is needed.

Could the later hardening that drives most of the +828 lines be moved out of this change? That is a maintainer decision.

@thymikee

Copy link
Copy Markdown
Member

Thanks for digging into #5137 and for the detailed iterations here. The fix is landing through #5157, which takes the smaller route suggested in the review: connect and disconnect establish the state root privately during connection resolution, before the lock. Closing this one in favour of it.

@thymikee thymikee closed this Nov 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants