Repository navigation
fix(daemon): refuse an unsafe state directory before first use - #4783
Conversation
Size Report
Startup median (7 runs, lower is better):
|
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
Apex Sentinel: 1 new finding on dddd24d. The verdict and the full list are in the summary comment.
|
Thanks for this. At dddd24d the daemon now refuses an existing state root that is not exactly 0700, and it cannot create the root on Windows, so it is not ready yet. CI shows the first problem: Android Smoke Tests fail at the first CLI step with "Refusing to use the daemon state directory ... is open to accounts besides its owner". Integration Tests and the iOS smoke lane use the same launch route and likely fail the same way. There are no conflicts. An existing root that this user owns, that is a real directory with safe ancestry, but has mode 0755 used to be repaired to 0700. Now establish refuses it with On win32, admitDaemonStateRoot returns after the shape check and creates nothing. This PR also deleted the launcher's The docs say that every command that starts, attaches to, stops or reports on the daemon checks the root before it reads or writes anything there. That is not true yet. In src/cli.ts:411-421, Not blocking, take or leave: the admission tests build roots with mkdtemp or through admission itself, so none covers the production order where a CLI writer creates the root under umask 022 and Could the PR be smaller? Keeping the walker reuse, admission could be asked where an operation resolves its The change touches daemon startup on every device lane, so it needs green Android and iOS smoke runs at the fixed head. It also needs a live first run with the root pre-created at 0755 by a non-admitting writer, for example Before merge, the daemon must repair an existing owned 0755 root instead of refusing it, and it must create the root on Windows. The CLI should also admit the root before its first state-directory read. |
2608978 to
de71e29
Compare
|
All five items are fixed at this head, and the two blockers are proved live. 1. 0755 roots. The repair is in one place: 2. Windows. 3. Seams. Took the simpler design: three call sites, one per route, each where it resolves its 4. Also fixed: the three exports are module-private ( 5. Complexity. One design consequence worth your eye. Admission creates the root and nothing below it. Size: production net +149 versus |
This comment has been minimized.
This comment has been minimized.
|
Thanks for the update. At de71e29 the earlier findings are fixed, but one gap remains: the MCP, AI SDK and Node clients no longer admit the state root before first use. The delta removes the inspect admission from Because this is security code, please also fix these: script-destination.ts:550 repairs the root's own bits before it judges the ancestry, and On the open threads: the one on CI is green: 21 checks, none failing at de71e29, including Android and iOS Smoke, which exercise the CLI repair route and the launch establish route. There are no conflicts. The live 0755 to 0700 run comes from the PR body, and the win32 test mocks the platform on POSIX and calls |
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
Apex Sentinel: 2 new findings on d68ca19. The verdict and the full list are in the summary comment.
… walk Adds `admitPrivateRoot` to the module that already walks a physical path one level at a time: it judges the root's own name before the walk resolves it, judges each ancestor, and creates what is missing at 0700 in establish mode, or answers the route as absent and creates nothing in inspect mode. A root that arrives beside the call is judged by the bits the walk lands on, not adopted for passing through. Co-Authored-By: Callstack Apex <noreply@callstack.com>
`admitDaemonStateRoot` asks the host-kit walk once per operation, before the first state-directory I/O: the launcher before it opens the log, the runtime before it locks or recovers (which also covers embedded mode), and the client's attach, status and stop routes in inspect mode, where an absent root stays absent. An unsafe root refuses with `daemon_state_root_unsafe`, the offending component and one concrete step; there is no degraded mode, no enrollment and no repair of an existing tree. Windows judges the path shape only, because multi-account protection is a mode-bits question POSIX alone answers. Deletes the launch-time `repairStateMode` repairs, the log reset's reopen route, the `chmodSync` calls that only repeated a mode `publishFileSync` or admission had already set, and the duplicate recursive `mkdirSync` calls for directories admission now creates. Co-Authored-By: Callstack Apex <noreply@callstack.com>
The fallback reported any unmapped walk verdict as a group-or-other-writable ancestor. The mapping is now total over the walker's exposures, with 'unavailable' for a route that could not be checked or created. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… use An owned state root that the host's umask left at 0755 refused every local command, because admission answered `not_private` where the old launcher answered `chmod`. Nothing else creates that directory either: the update-check cache, the process lock and the log path each `mkdir` it with the umask, and every root an older build left behind qualifies. #4649 asks for the opposite: an owned level is repaired to 0700 on a best-effort basis, and the repair never decides whether the daemon starts. So the mode question is now asked in one place, `admitPrivateRoot`, and it is repaired rather than refused: an owned real directory judged with `lstat`, with safe ancestry, is closed with one `chmod` by both modes, and only a `chmod` the host refuses becomes `not_private`. A link, a foreign owner, an unsafe ancestor, a `..` step and a non-directory still refuse. Establish also creates the root on Windows, where the launcher's `openSync(logPath, 'a')` had nothing to open, and it creates nothing below the root: the daemon makes `sessions/` and `sessions/remote-scripts/` itself, so an empty state directory stays empty. The seams shrink to three, one per route, each where it resolves its `DaemonPaths`: `src/cli.ts` in repair mode before the connection defaults and the upgrade notifier read the root, `launchDaemonProcess` in establish mode, and `daemon-runtime.ts` in establish mode for an embedded or foreign-build daemon. The client-side inspects go away, so no route asks the same question twice and none asks it per write. ADR 0016 carries the rules that differ for the daemon's own root, and `configuration.md` tells an operator what the check does on each platform. Co-Authored-By: Callstack Apex <noreply@callstack.com>
The MCP server, the AI SDK tools and `createAgentDeviceClient` never pass the CLI's admission, so their first state-directory read trusted a record behind a planted link. Every client route reaches that read in one place now, and it follows a repair admission. - `observeLocalDaemon` admits `settings.paths` before `readRegisteredDaemon`, and a passed repair is remembered per base directory for the process, so repeated requests walk once. - The root's ancestry is judged to its parent BEFORE its own bits are closed. `chmod` follows links, so that order is what keeps a planted link's target out of the mode change. - A state-dir spelling sheds only the host's own trailing separators: on POSIX `\` is a file-name character, so `state\` is judged as the name it is. - `shared_parent` joins the writable-ancestor problem, and the exposure-to-problem mapping is a total `Record`, so a future exposure cannot fall through to `unavailable`. - `src/cli.ts` keeps its own admission: the connection defaults read, and the upgrade notifier writes, the root before any client exists. Co-Authored-By: Callstack Apex <noreply@callstack.com>
|
At d68ca19 the earlier findings from de71e29 are fixed: client routes admit the state root again, the repair walks the ancestry first, and the backslash and reason-mapping fixes are in. Three things remain before the label. The Repo Guards & Compatibility job fails at "Check import-direction DAG" with one R89 violation, and it looks related to this PR. daemon-resolution.ts:177 now publishes 'daemon_state_root_unsafe' as an untyped literal, and main declares no such reason. R89 (#4779) landed after your merge-base and also resolves module-scope consts, so the old const form would fail too. Please publish the reason from an owning typed reason table (an Because this is the state-directory trust boundary, please also fix these two: the planted-link client test in daemon-client-startup-state-root.test.ts asserts on the target path while the client reads the spelled stateDir path, and the net.createConnection spy likely misses the http transport, so the test may pass on pre-fix code; repairedStateRoots.add(baseDir) in daemon-resolution.ts also runs when the repair judged an absent root, so a root planted later under a sticky parent such as /tmp would skip the walk, and a root should be remembered only when it existed and was admitted. Please assert on the path the client actually reads and on every transport, and check the test fails on de71e29. And remember a root only when it existed and was admitted. Separately, not blocking: the session-script-writer.ts comment says admission owns that directory's mode, while the mkdir with mode 0o700 does, so the earlier wording and PR body items 3 and 5 are worth restoring. The earlier inline thread on win32 root creation (#4783 (comment)) no longer applies, because establish mode creates the root recursively before the launcher opens daemon.log, so you can resolve it. |
…n the one client reader (#4649) R89 measures wire-published reasons: `daemon_state_root_unsafe` is now a member of `DAEMON_STATE_ROOT_REASONS` and `configuration.md` words it. - `readRegisteredDaemon` is the client's ONE reader of the lock and `daemon.json`, and a public export in its own right, so it admits the root itself. `observeLocalDaemon` no longer does. - Nothing about a passed repair is remembered: an absent root is admitted and can become a planted link before the next read, so every call walks. A regression test covers both. - The planted-link client test now asserts the SPELLED state-dir paths the client reads, and covers the socket and HTTP transports. It fails on the pre-fix code. - A refused mode change names both ways out: `chmod 700 <dir>`, or a move if that is refused. Co-Authored-By: Callstack Apex <noreply@callstack.com>
d68ca19 to
f7644b8
Compare
|
All four items are in f7644b8, pushed and re-measured. 1 — R89, and the two steps CI skipped. const DAEMON_STATE_ROOT_REASONS = {
unsafe: 'daemon_state_root_unsafe',
} as const satisfies Record<string, string>;
Both skipped steps now run locally. 2 — the memo. Deleted outright, as instructed: neither an admitted absent root nor a passed repair is remembered, so every call walks. The PR body records the ~10 µs cost as accepted. Two regressions cover it: 3 — the planted-link test. Rewritten to watch the route the client walks, not the planter's path. It spies Proved failing without the fix, by removing only The client admission also moved, per the other thread: it is now the first statement of 4 — the two non-blocking points. Re-measured at this head: full |
This comment has been minimized.
This comment has been minimized.
|
This PR is ready at f7644b8. The Repo Guards & Compatibility job that failed at d68ca19 now passes, and all 21 checks pass at this head. The reason is published from a typed table, no repair is remembered between calls, so a root planted after an earlier admission is refused at the next read, and the client tests pin that through the public reader. The 0755 to 0700 run and the planted-link refusal come from the PR body. This is a daemon-only change, so no device run is needed. No conflicts. The earlier findings are fixed: the win32 branch creates the root before the launcher opens daemon.log, the session script writer calls chmod on its directory again, and the chmod failure message now points to moving AGENT_DEVICE_STATE_DIR. Those three inline threads can be resolved: #4783 (comment), #4783 (comment) and #4783 (comment). Not blocking, and you can take it or leave it: daemon-resolution.ts:172 passes the path to |
A directory name holding $$ or $& was read as a replacement pattern. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Apex Sentinel · ✅ Approve · review of
|
| 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.
|
Still ready at 5043120. The fix text now passes the path to |
* origin/main: (70 commits) refactor(apple-runner): one RUNNER_ERROR_CODES row per runner error code with parity/docs gates (callstack#4774) fix(android): require acknowledgements for test IME typing (callstack#4722) feat(scroll): add scroll refresh for pull-to-refresh (callstack#4770) refactor(host-kit): add request Scope and use it for the wait capture deadline (callstack#4794) fix(android): let permission all change nothing on an app that declares no permissions (callstack#4796) fix(cli): replace the CLI session and generated remote config instead of rewriting them in place (callstack#4797) fix(host-kit): accept a group-writable script directory the user owns (callstack#4799) fix(cli): escape control characters at the CLI's stdout and stderr writes (callstack#4778) fix(audit): do not report rows under a persistent bar that scrolling reveals (callstack#4775) fix(daemon): refuse an unsafe state directory before first use (callstack#4783) refactor: settle remaining single-deadline races through settleWithin (callstack#4788) refactor(host-kit): settle deadline races via settleWithin with R87 race ratchet (callstack#4766) fix(android): authenticate and bound persistent snapshot helper sessions (callstack#4729) fix(daemon): bound upload ingress and finalization (callstack#4721) chore(gates): ratchet wire-published reason literals by value (R89) (callstack#4779) feat(audit): evaluate role-less clickable views on Android (callstack#4780) fix(mutation): keep umask-setting tests out of Stryker's thread pool (callstack#4785) feat(audit): report controls that share one accessible name (callstack#4771) fix(contracts): pair open runtime hints with their apply operation (callstack#4754) refactor(daemon): report startup progress over the launch channel instead of marker files (callstack#4777) ...
fix(daemon): admit the state root, repairing an owned one the umask left open
Summary
Every state-directory write used to trust the directory it was handed: the launcher
chmod'd a loose root into place at launch, andsession-script-writerandprovider-lease-expiryre-created or re-chmod'd their directories per write. An account that could plant a name on that route steered where the daemon's record, log and recordings went (#4649).One rule now answers every question about that directory:
admitPrivateRootinpackages/host-kit/src/internal/script-destination.ts— the walker that already judges a caller-named script destination (one walker, not two) — asked byadmitDaemonStateRootinpackages/daemon-contracts/src/daemon-resolution.ts. Four call sites, one per route that reaches the root:readRegisteredDaemoninpackages/daemon-client/src/daemon-client-metadata.ts, in repair mode, as its first statement. That function is the client's ONE reader ofdaemon.lockanddaemon.json, and a public export ofpackages/daemon-client/src/index.ts: the ensured transport the CLI and the MCP server use, the AI SDK tools,createAgentDeviceClient,ensureDaemonand an attach client all reach it, and none of them passsrc/cli.ts.src/cli.ts, in repair mode, where the invocation resolves itsDaemonPaths— kept because the connection defaults read, and the upgrade notifier writes, that directory before any client exists, and because a refusal must land with the command's own exit handling rather than inside a client.launchDaemonProcess, in establish mode, before it opensdaemon.log.daemon-runtime.ts, in establish mode, which is also the entry an embeddedstartAgentDeviceand a foreign-build daemon take.Nothing is memoized. An absent root is admitted (a repair creates nothing), so a verdict cannot be carried to the next read: a long-lived MCP server whose root sits under a shared sticky parent must not skip the walk after an outside account plants a link there.
An owned root is repaired, not refused. A root this user owns that is a real directory with safe ancestry, but open through its own group or other bits, is brought to
0700by onechmodand admitted, in both modes and judged withlstat. The update-check cache, the process lock, the log directory and every root an older build left behind create it under the host's umask, so amkdirunder a wide umask cannot decide whether a command runs (#4649). Only achmodthe host refuses ends it, asnot-private. A symbolic link at the root, a foreign owner, a shared or world-writable ancestor, a..step and a non-directory still refuse, in both modes, withdetails.reason: "daemon_state_root_unsafe"and{ stateDir, component, problem, fix }. The reason is a member ofDAEMON_STATE_ROOT_REASONS(as const satisfies Record<string, string>), not a literal at the throw site, so R89 sees a published vocabulary andwebsite/docs/docs/configuration.mdwords every member.Establish creates the root on every platform, Windows included, where it creates it recursively after the shape rule and asks no privacy question. Nothing is created below the root:
sessions/andsessions/remote-scripts/are judged where they stand (link and owner) and the daemon makes each of its own names when it first needs it, so an empty state directory stays empty and a report-only command leaves it absent.Deletions:
repairStateModeandMODE_REPAIR_SKIPPED_CODES; the Windows log-reset reopen route (now one'w'handle); the launcher'smkdirSyncand its per-pathchmodSync;chmodSync(filePath, 0o600)afterpublishFileSyncinprovider-lease-expiry(which now asksexactMode); the lease writer's recursivemkdirSync; the duplicate inspect calls indaemon-client-attach.ts,daemon-client-lifecycle.tsandsrc/cli/commands/daemon.ts.Reverted as scope creep, suggested follow-up:
publishFileSyncinsrc/cli/auth-session.tsandsrc/cli/connection/generated-config.tsstill writes a sensitive file in place.Review round 1
admitDirectorycloses an owned real directory's own group/other bits with onechmodbefore it can be a refusal, inadmitPrivateRoot, the one place the rule lives. Covered bya root a plain mkdir leaves at the umask default is repaired by the next establish(amkdirSyncunderumask 022— the production order CI hit),an owned root at mode 0755 or 0770 is repaired to 0700, and nothing is created below it, and the live run below.repairmode never creates, and neither mode refuses an owned open root.admitDaemonStateRootcreates the root recursively on win32 after the shape check, in establish mode, which covers both the launcher'sopenSync(logPath, 'a')anddaemon-runtime.ts.on a Windows host establish creates a missing root recursively and repair creates nothingruns on a mocked win32 host with an absent root and then opensdaemon.logat the absolute name the launcher uses, so the test fails on ENOENT if the create is dropped.daemon-client-attach.ts,daemon-client-lifecycle.tsandsrc/cli/commands/daemon.tsare back tomain.DaemonStateRootProblemand the problem/exposure tables are module-private;resolveStateDirsplits on/on POSIX and on both separators on win32, so a POSIX directory nameda\bis a name, not a traversal;connect,authandconnection-runtimeare covered by thesrc/cli.tsadmission (proved live:auth statuson a planted link refuses withproblem: "symlink"before reading the connection state).admitPrivateRootis split intoadmitDirectoryandverdictForAncestryFaultand is inside the thresholds; no Fallow allowlist or baseline entry was added.Review round 2
R89 — the reason is published from its table.
DAEMON_STATE_ROOT_REASONS.unsafereplaces the literal inunsafeStateRoot, so the throw site reads a declared table and R89 defers it. The layering scan is clean:Fallow, and the two steps CI skipped.
fallow audit --base origin/mainandcheck:production-exportsboth pass at this head — the unused-exports gate reports✓ No issues foundover 720 entry points. The one number the report shows,parseCliInputOrExitcognitive 16, is inherited frommainand is not introduced here:main's ownsrc/cli.ts:256reports13 cyclomatic · 16 ! cognitivefor the same function, andgit diff origin/main -- src/cli.tschanges only the two-line admission and one collapsed local. The audit gate exits 0 and names it an inherited finding; no baseline row was added. Round 1's extraction tosrc/cli/help-request.tswas reverted, because it paid 19 net lines for a finding this branch does not own;src/cli.tsstays at themax-lineslimit of 1000.No verdict is remembered.
repairedStateRootsis gone, in both directions: an absent root no longer banks a pass, and no passed root does either, because the ground under a name can change between two reads of it. Two regressions cover it —a repair re-judges the root on every call, so a link planted after one cannot be read(contract) anda client that admitted an absent root refuses a link planted at it before its next read(the publicreadRegisteredDaemon). ADR 0016 now states the rule as "asks it again at the next one: a verdict is never remembered". The walk costs ~10 µs, so nothing needed memoizing.The client admission moved to
readRegisteredDaemon. It is now the first statement, beforeinspectProcessLock, andobserveLocalDaemonno longer admits. Audit of the remaining client-side state reads, all of which follow an admission on every route:daemon-client-metadata.ts—inspectProcessLockandreadDaemonRecordare insidereadRegisteredDaemon, after the admission.readDaemonInfoand thegetDaemonMetadataStateexists-checks indaemon-lifecycle-errors.tstake an already-resolved path.daemon-client-startup.ts— the threeinspectProcessLockcalls,readDaemonInfoand the log tail all sit on the startup path: afterreadReusableLocalDaemon(admitted), or afterstartDaemon→launchDaemonProcess, which admits in establish mode before it opensdaemon.log.daemon-client-attach.ts,daemon-client-lifecycle.ts,src/cli/commands/daemon.ts,src/mcp— no direct state-directory reads at all.The planted-link client test now measures the route the client walks. It watches the SPELLED paths (
<stateDir>/daemon.jsonand<stateDir>/daemon.lock) acrossreadFileSync,openSync,lstatSync,statSync,existsSyncandreaddirSync, and it watches both transports:net.createConnectionfor the socket andhttp.requestfor HTTP (loadNodeHttpRequesterresolves that same module object, so the probe goes through the spy). It runs once per transport.Failing-before evidence, from the same test file with only
admitDaemonStateRoot({ paths, mode: 'repair' })removed fromreadRegisteredDaemon. The client reached the planted record on the spelled path in both transports, and the planted pid/port were in hand:A refused
chmodno longer recommends the step that just failed.not-privatekeeps its refusal and its problem kind; itsfixis one string naming both ways out:Run `chmod 700 <dir>`, or point AGENT_DEVICE_STATE_DIR at a private directory you own if that is refused.configuration.mdwords the same two steps.remoteScriptPathkeeps itschmod. Restored as it stands onmain, withmain's comment: that call createssessions/remote-scriptsitself,mkdir's mode is masked by the umask, and admission only ever judges names — it creates none of them. So an owner-bit umask such as0o200still leaves a usable directory.Validation
Android Smoke and iOS Smoke are green at this head — see the checks on this PR.
pnpm typecheck,pnpm lint,pnpm format, the eager-closure gate (913), the layering scan,check:production-exportsandfallow audit --base origin/mainpass.ls -Aprinted nothing: the repair created nothing below it.daemon status,devicesandauth status, on the CLI route and on the client route.on a Windows host establish creates a missing root recursively and repair creates nothing—repaircreates nothing,establishcreates the nested root, and the launcher'sopenSync(…'daemon.log', 'a')then succeeds.--project unit-core— 2091 files, 20149 tests, 0 failures.--project provider-integration test/integration/provider-scenarios/session-close-leak-oracle.test.tspasses; the leak oracle sees no straysessions/residue, because admission creates nothing below the root.srcandpackages/*/src) +215 / −66, net +149, within the +150 budget for the whole PR.readRegisteredDaemon, and the no-memo rule;website/docs/docs/configuration.md,commands.md,installation.mdandagent-setup.mdmatch;docs/agents/security.mdsays the daemon admits its state directory.Unresolved risks: the check reads owner and mode bits, not ACLs or mount provenance (ADR 0016 says so); historical exposure of files already inside an admitted root is out of scope by design.
Part of #4649. Follows #4777 (merged).