Repository navigation
fix(security): apply the Windows path-hardening ACL that never ran - #17884
Conversation
`buildWindowsRestrictAclArgs` invoked the hardening script as `powershell.exe -Command <script> <path> <sid> <isDir>`. `-Command` does not populate `$args`; it appends the trailing tokens to the command text. The script therefore read `$args[1]` as `$null`, threw `NullArrayIndex` at `$allowedSids[$sidText] = $true` under `$ErrorActionPreference = 'Stop'`, and exited 1. Both callers swallowed that: the async callback was empty and `applySecurePathRestriction` returned `true` regardless, while the sync `catch` returned `false` and nobody logged. Every Windows secure path has been left on its inherited ACL since the ACL was introduced (#5006), and nothing said so. Replace PowerShell with `icacls.exe`, which takes plain argv. That removes the quoting surface entirely rather than escaping it: interpolating a path into the command text would have turned a dead no-op into arbitrary PowerShell on a filesystem path, since `-Command` executes what it appends. It also drops the execution-policy dependency and the `powershell.exe` spawn an EDR flags, and runs ~25x faster than the PowerShell cold start. Hardening is now three passes: `/reset` to purge explicit ACEs that `/inheritance:r` leaves behind, `/inheritance:r` plus a `/grant:r` per allowed SID, then a read-back that checks the DACL is protected and grants only the intended rights. The predecessor's verification block was equally dead, and an apply that is never read back is only half a control. Failures stay non-fatal — non-NTFS volumes, network paths and restricted tokens fail legitimately and must not break startup — but they are no longer invisible: every failure is logged, and a failed async apply now evicts its cache entry so the next call retries instead of trusting a success that never happened. Routing through `runProcess`/`runProcessSync` also retires this file's `node:child_process` allowlist entry.
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Team Run ID: 📒 Files selected for processing (2)
Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review. 📝 WalkthroughWalkthroughWindows ACL hardening now uses Merge Risk: 🟡 Moderate · up to The change replaces a nonfunctional Windows hardening path with verified ACL enforcement, but credential files can still be published before ACL success and failed ACL transitions can temporarily leave inherited permissions in place; merge should wait for these guarantees or obtain explicit security-owner acceptance. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Docstring CoverageExplanation Docstring coverage is 38.89% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 54 functions across 11 files. (1 skipped: 1 unsupported.) Full details: Description checkExplanation The description gives extensive technical detail about the problem, implementation, risks, and testing. However, it does not follow the required template fully: it lacks an issue reference after "Fixes #", does not provide the required Visual Proof section with an explicit N/A justification, and leaves required checklist and review items incomplete. Resolution Add a valid linked issue after "Fixes #". Add the Visual Proof section with exactly "N/A" and a brief reason if there is no UI or interaction change. Complete the Testing, AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist sections, including the applicable checkboxes and CI status. ✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: 0dc85d08-24e9-4899-9187-8e473b5cec81
📒 Files selected for processing (6)
src/main/artifacts/artifact-create-intent-store.test.tssrc/shared/child-process/__fixtures__/child-process-import-allowlist.txtsrc/shared/secure-file.test.tssrc/shared/secure-file.tssrc/shared/secure-path-windows-acl.tssrc/shared/secure-path-windows-acl.win32.test.ts
💤 Files with no reviewable changes (1)
- src/shared/child-process/fixtures/child-process-import-allowlist.txt
Included review availability: Your plan provides up to 10 included reviews per hour; 1 remains after this review.
There was a problem hiding this comment.
Important
The rewritten secure-file.test.ts fails on Linux/macOS — the SID-lookup mock compares against hardcoded backslash paths while windowsSystem32Binary builds the program path with the host node:path (forward slashes on POSIX), so the lookup returns null and every Windows hardening test short-circuits at sid-lookup. I reproduced 17 assertion failures by running the file here. Production code only executes this path on win32, so this is a test/CI regression, not a runtime bug — but it must be fixed before merge or non-Windows CI goes red.
Reviewed changes
secure-path-windows-acl.ts— replaces the PowerShell ACL script with threeicacls.exepasses (/reset,/inheritance:r+/grant:r, verify), with a verify pass that parses the read-back DACL and fails on inherited or unexpected ACEs.secure-file.ts— the async apply now reports its real outcome through anonAsyncFailurecallback that evicts the hardening cache entry, so a failed apply is retried instead of recorded as success.secure-file.test.ts/artifact-create-intent-store.test.ts— tests rewritten aroundrunProcess/runProcessSyncinstead of rawchild_process.secure-path-windows-acl.win32.test.ts— new real-filesystem regression test asserting on the resulting ACL (skipped on non-win32).child-process-import-allowlist.txt—secure-path-windows-acl.tsremoved from the directchild_processallowlist now that it routes throughrunProcess.
ℹ️ Nitpicks
secure-path-windows-acl.win32.test.ts(the "no permission to modify" case): on an elevated runnerrestrictWindowsPathSyncactually rewrites the realdrivers\etc\hostsDACL, and the follow-upicacls /resetrestores only inherited ACEs — any explicit (non-inherited) ACEs an elevated host had onhostsare not put back. Consider skipping the test entirely when elevated, or targeting a file the test itself creates.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
Review found the bug class this PR fixes surviving inside the fix. The verify pass checked rule count, absence of the inherited marker, and exact rights — never *who* the rules named. Granting Everyone full control satisfies all three, so hardening reported success on a DACL that handed the credential to every local account, and most of the real-filesystem tests still passed. Verification now reads the descriptor back with `icacls /save`, which emits SDDL with raw SIDs, and compares the principal set exactly. That is also locale-independent by construction: the previous parse read localized account names out of icacls' OEM-codepage stdout, where a non-ASCII path survived by accident rather than by the documented mechanism. SDDL parsing moves to `windows-security-descriptor.ts`. Two further self-inflicted problems, both measured: The post-rename re-harden led with `/reset`, which re-widened a DACL that was already correct — the staged file's protected DACL survives the rename, so the pass had nothing to do but open a window. Polling an external process during a write into a relocated root caught it: the e2ee keypair dropped to `BUILTIN\Users:(RX)` plus `Authenticated Users:(M)` — read *and* write — before tightening again. Hardening now verifies first and returns early when the DACL already reads back correct, which closes the window and cuts the steady state from three spawns to one. Re-measured: 158 samples, one DACL state, zero broad. Evicting the cache on every failed async apply reintroduced #4901. The env store re-hardens on the read path at ~2/s, so on a host where hardening cannot work (FAT32, network path, restricted token) that was two icacls spawns and two warnings a second, forever. Async retries now take a retry floor and a hard per-path attempt cap. The write path keeps retrying unthrottled — it is user-driven, and a failed credential ACL must still be retried on the next write. Also: failures route through a reporter hook that the main process points at the diagnostic tracer, because `console.warn` reaches nothing in a packaged GUI-subsystem build; `writeSecureFile` returns whether hardening took, and the async branch reports `pending` rather than claiming `applied`; a transient `whoami` failure no longer disables hardening for the process lifetime, and the SID is shape-validated; the `/c` guard now covers the synchronous runner too.
…lure The per-process attempt cap added for the read-path storm was a permanent latch: one AV scan, momentary lock or %TEMP% blip and every later credential write in that session went unhardened, silently, on a host where hardening would now succeed. Same defect class as #17858's computer-use host, and worse here because what stops happening is security hardening on credential files and nothing said so. The retry budget now bounds the *rate*, not the lifetime: at most three attempts per path per minute, re-probing in every later window, forever. The transition is announced in both directions — `throttled` once per window on entry, `recovered` when a rate-limited path hardens again — so a host stuck in the degraded state is diagnosable rather than merely quiet. The reporter type covers both, and the main process ends the `recovered` span successfully rather than failing it. Extracted to secure-path-hardening-retry-budget.ts, which keeps secure-file.ts under its line cap without a max-lines disable. Also confirms the second flagged risk rather than assuming it: a real unwritable %TEMP% is now covered by a test proving verification fails closed, reports at the `verify` stage, and still leaves the ACL applied — so that path loses proof, not protection, and with the lifetime cap gone it can no longer combine into a permanent-off state.
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: 163f569b-cd2e-4c00-85bf-65dfdac3e382
📒 Files selected for processing (7)
src/main/observability/index.tssrc/shared/secure-file.test.tssrc/shared/secure-file.tssrc/shared/secure-path-windows-acl.tssrc/shared/secure-path-windows-acl.win32.test.tssrc/shared/windows-security-descriptor.test.tssrc/shared/windows-security-descriptor.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/shared/secure-path-windows-acl.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.
| const dacl = /D:([A-Z]*)((?:\([^()]*\))*)/.exec(sddl) | ||
| if (!dacl) { | ||
| return null | ||
| } | ||
| const aces: WindowsAce[] = [] | ||
| for (const group of dacl[2]!.matchAll(/\(([^()]*)\)/g)) { | ||
| const fields = group[1]!.split(';') | ||
| if (fields.length < 6) { | ||
| return null | ||
| } | ||
| aces.push({ | ||
| type: fields[0]!.toUpperCase(), | ||
| flags: splitAceFlags(fields[1]!), | ||
| rights: fields[2]!.toUpperCase(), | ||
| sid: resolveSddlSid(fields[5]!) | ||
| }) | ||
| } | ||
| return { isProtected: dacl[1]!.includes('P'), aces } |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟠 Major | ⚡ Quick win
Other (CWE-20): Improper Input Validation
Exploitability: Difficult
Reject malformed SDDL before validating the DACL.
parseSddlDacl can return only the complete ACE prefix when the DACL contains an unterminated ACE. validateHardenedDacl then validates that partial result. Require complete DACL consumption and add a regression test for a malformed suffix. Also reject odd-length ACE flag runs.
🧰 Tools
🪛 OpenGrep (1.27.1)
[ERROR] 43-43: Dynamic command passed to child_process.exec/execSync. Use child_process.execFile or spawn with an argument array instead.
(coderabbit.command-injection.exec-js)
The flag check tested only that `OI` was present — never that `CI` was, nor
that nothing else was. That was harmless while `/reset` + `/grant` ran on
every pass and repaired whatever was there. The verify-first short-circuit
made it load-bearing: what verification accepts is now left alone, so a
latent under-check went live because a different fix started depending on
it.
Two directory DACLs passed while being wrong — both protected, three
non-inherited full-control rules, correct SIDs, differing from correct only
in their flags:
(OI)(F) - no CI, so subdirectories are left unprotected
(OI)(CI)(IO) - inherit-only, so the directory object itself grants
nobody anything; the next writeFileSync into it fails
with EPERM, on a directory just cached as hardened
Verification now compares the whole flag set, which also rejects IO and NP,
and names the offending flags in the failure. Both shapes are planted in
real-filesystem regression tests, including an assertion that a write into
the repaired directory succeeds and its child inherits. Confirmed both tests
fail against the old check and pass against this one.
The fixed one-minute window bounded the retry rate but left a standing floor of three attempts per path per minute on a host where hardening can never succeed — FAT32/exFAT, a network path, a redirected profile. That budget is per path and there are several secure files, so the floor multiplied into tens of thousands of icacls spawns a day for work guaranteed to fail. The delay now doubles after each consecutive failure, from a one-minute floor to a thirty-minute ceiling, and the attempt cap is gone entirely: once the backoff elapses the path is re-probed however long it has been failing. A permanently incapable host settles at ~2 attempts/hour. Slowing the backstop costs almost nothing, because it is not the recovery mechanism: the synchronous write path is deliberately unthrottled, so a host that recovers hardens on its very next credential write regardless of what the read-path budget says. The `throttled`/`recovered` reports are unchanged and matter more here, since the quiet periods between probes are now much longer. The curve is pinned in a new unit test against the exported delay function rather than a copy of its constants, covering the doubling, the ceiling holding at 5000 consecutive failures, a 30-day failing path still re-probing, one announcement per degraded episode, and per-path isolation. The integration tests keep only what they uniquely prove: that the read path is wired to the budget, and that a day of failures still re-probes. Confirmed four of these fail against a reinstated lifetime cap.
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: d08218a6-e60d-48d5-b0d8-ccb3d7ea3b3f
📒 Files selected for processing (6)
src/main/observability/index.tssrc/shared/secure-file.test.tssrc/shared/secure-file.tssrc/shared/secure-path-hardening-retry-budget.tssrc/shared/secure-path-windows-acl.tssrc/shared/secure-path-windows-acl.win32.test.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 1 remains after this review.
| failures().set(targetPath, { | ||
| windowStartedAt: staleWindow ? now : previous.windowStartedAt, | ||
| attempts | ||
| }) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Retain retry state for every supported extended path.
SecurePathHardeningCache.set() rejects keys larger than the 64 KiB default limit, and this result is ignored. A failing extended path with enough non-ASCII characters then has no failure record. Each later read passes mayAttemptHardening() and starts icacls.exe again instead of stopping after three attempts per minute.
Use a fixed-size path identity, such as a cryptographic hash, for retry-budget keys.
There was a problem hiding this comment.
Important
The new icacls /save verify mis-parses paths on a D: drive — the unanchored D: regex matches the path line's drive letter instead of the SDDL record, so a correctly hardened file is reported as failed and /reset re-runs on every write (see inline comment).
Reviewed changes
- Replaced the shape-only verify pass with an identity check:
icacls <path> /saveplus SDDL parsing (windows-security-descriptor.ts) compares the granted SIDs as an exact set, so a substituted principal such asEveryoneis now rejected. - Added a verify-first short-circuit so an already-correct DACL is left untouched instead of
/resetreopening the inheritance window on every write. - Added a retry floor and per-path attempt cap on the async read path, replacing unconditional cache eviction that re-stormed the main thread (#4901).
- Routed hardening failures into the diagnostic trace through a reporter installed in
initObservability(and cleared on shutdown); SID-lookup failures now expire instead of caching forever; the/cguard now covers bothrunProcessandrunProcessSync.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
|
|
||
| export function parseSddlDacl(sddl: string): WindowsDacl | null { | ||
| // ACE bodies never contain parentheses, so the group stops cleanly at a following `S:` SACL. | ||
| const dacl = /D:([A-Z]*)((?:\([^()]*\))*)/.exec(sddl) |
There was a problem hiding this comment.
icacls <path> /save writes the object's full path as the first line of the save file, then the SDDL on the next line. This unanchored D: search therefore matches the drive letter when the path is on D: (e.g. D:\orca-data\…) — the path line's D: matches first, yielding an empty unprotected DACL, so the verify pass reports a false failure even after the ACL was applied correctly.
Technical details
# `parseSddlDacl` matches the path line on a `D:` drive
## Affected sites
- src/shared/windows-security-descriptor.ts:43 — unanchored `D:` regex
- src/shared/secure-path-windows-acl.ts:70-85 — `evaluateSavedAcl` feeds the whole file into the parser
## Required outcome
- Verification must parse the SDDL record, not the first line's path, regardless of drive letter.
## Suggested approach (optional)
- Strip the leading object-name line before parsing (a single `/save` writes exactly one `name`/SDDL pair), or match the `D:` that is immediately followed by flags and at least one ACE group. Note a plain `(^|\r?\n)D:` anchor does not help: on `D:` the path line itself also starts with `D:` at position 0.| return { ...ok, stdout: '"USER","S-1-5-21-1000"' } | ||
| } | ||
| const args = spec.args ?? [] | ||
| if (args.length > 1) { |
There was a problem hiding this comment.
This mock still models the pre-delta stdout verify (icacls <path> readback). After the delta, the verify pass is icacls <path> /save <savePath> /q plus an SDDL file read, so the args.length > 1 branch swallows the save call, no SDDL file is written, and evaluateSavedAcl reports icacls saved no security descriptor. The test still passes because it only asserts /reset and /grant:r, but it now logs a spurious hardening failure and never exercises the verify-success path — update the fake to write the save file, as fakeIcacls in secure-file.test.ts does.
There was a problem hiding this comment.
ℹ️ No new issues found in this delta. The retry-budget rework, whole-flag-set verification, and reporter changes are correct. This is not an approval — the findings raised on the earlier commits remain open and are not re-stated here.
Reviewed changes
- Replaced the per-process retry cap with an exponential backoff budget (
secure-path-hardening-retry-budget.ts) that bounds the retry rate without ever latching a transient failure — it re-probes at a 30-minute ceiling and announcesthrottled/recoveredtransitions. - Tightened directory verification to compare the whole inheritance flag set (
OI+CIexactly), so(OI)-only and inherit-only(IO)DACLs that the verify-first short-circuit would otherwise leave alone are now rejected and repaired. - Renamed the report type to
SecurePathHardeningReportwiththrottled/recoveredstages;initObservabilityends a success span (and logsconsole.info) on recovery instead of failing. - Added real-filesystem coverage for the two wrong-flag directory DACLs (including a post-repair write into the repaired directory) and for an unwritable
%TEMP%that fails verification closed while the ACL itself still lands.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
The win32 suite only self-skips off Windows, so it passed vacuously in every lane. Register it the way the cmd-shim suite is registered.
There was a problem hiding this comment.
ℹ️ No new issues in this delta. The commit wires the real-filesystem win32 suite into the Windows package job, and the wiring is correct: the test runs only on Windows (
describeOnWindowsskips elsewhere), thepackage_windowsjob runs onwindows-2022where a realicacls.exeexists, and adding the file toWINDOWS_PACKAGE_TESTSis what makes a change to the test file itself trigger the job (a baresrc/test file is excluded byisProductBundlePath). Prior open findings are unchanged by this commit and remain open.
Reviewed changes
- CI now executes the real-filesystem DACL suite — added
src/shared/secure-path-windows-acl.win32.test.tsto thepackage_windows"Test Windows-specific boundaries" step and toWINDOWS_PACKAGE_TESTS, closing the gap where the regression test that actually reads the resulting ACL back off disk never ran in CI.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
Both cache comments still justified themselves with PowerShell -- "~1-1.5s" and "a PowerShell spawn every read" -- in the same file whose PR removed PowerShell from this path. The caches are still right, but for different numbers, and the old ones are the kind an engineer would reasonably delete a cache over. The real shape: hardening verifies first and returns early, so an already-correct DACL costs one synchronous icacls spawn and a rewrite costs four (verify, reset, grant, verify). Still worth caching on the read path, which polls at ~2/s.
Registering this spec in the Windows lane put it under two rules it had never been measured against. Teardown now goes through `removeTreeSync`, which the lane's boundary test requires, and repairs the DACLs the suite plants on purpose first: those retries only cover transient locks, so a regressed `(OI)(CI)(IO)` repair leaves the root un-removable and `afterAll` throws EPERM. And the no-permission case decides by elevation before it writes anything. `windows-2022` runs elevated, where hardening succeeds: the old branch asserted nothing about denial and instead replaced the `hosts` DACL, then `icacls /reset` -- which is not a restore, it drops the explicit `SYSTEM:(F)` that file ships with. Ephemeral in CI; permanent for a developer running the lane from an elevated shell. Now it asserts or it skips. The probe reads the token integrity SID rather than `icacls /save`, which succeeds unelevated (`BUILTIN\Users:(RX)` carries READ_CONTROL) and would have skipped the case on every machine.
…o backwards `mayAttemptHardening` compared wall-clock times, so any backwards step -- an NTP correction, a VM snapshot restore, a user changing the clock -- made the elapsed time negative and held every failing path below its delay until the clock caught up. Measured at the 30-minute ceiling with the clock stepped back a year, the path was refused at +0d, +1d, +30d, +180d and +364d, and re-probed only at +366d. That is the permanent latch the exponential backoff was added to remove, and it contradicts the module's own "bounds the rate without ever bounding the lifetime". The SID lookup's own one-minute window had the identical shape and is worse: a failed lookup makes `planFor` return null, which disables the synchronous *write* path too, so the write-path exemption that recovers the read-path budget cannot recover it. Both now measure elapsed monotonic time, following the repo's existing `monotonicNowMs` spelling. Two things the write path was not doing, both found in the same pass: - A successful synchronous apply now records the outcome. It is exempt from the budget, but it was also invisible to it, so a host that had demonstrably recovered kept the read path backing off for up to 30 minutes and no `recovered` transition ever came from that lane. Only success is recorded; recording failure would put the exempt lane back under the budget. - `writeSecureFile`'s JSDoc now says its boolean covers the file only. The directory harden is fire-and-forget and answers `pending` on Windows regardless, so a `true` says nothing about the directory's ACL.
There was a problem hiding this comment.
ℹ️ No new issues in this delta. The monotonic-clock change and the DACL-suite scheduling hardening are correct, and the new tests pin the behavior they claim to. This is not an approval — the findings raised on the earlier commits (the POSIX
whoamimock mismatch, the staleartifact-create-intent-storeverify mock, and the unanchoredD:SDDL regex) remain open and are not re-stated here.
Reviewed changes
- Measured both hardening latches on a monotonic clock —
secure-path-hardening-retry-budget.tsand the SID-lookup latch insecure-path-windows-acl.tsnow useperformance.now()instead ofDate.now(), so a backwards wall-clock step (NTP correction, VM snapshot restore, manual clock change) can no longer hold a path below its backoff for the length of the step.sidLookupFailedAtbecamenumber | nullaccordingly. - Let the write path clear the read-path backoff — a successful synchronous harden now records
recordHardeningOutcome(targetPath, true), so a recovered host reportsrecoveredand stops backing off instead of waiting out the ceiling. - Made the DACL suite safe to schedule — the real-filesystem win32 test detects elevation from the token's mandatory integrity level and skips the
hostsdenial case when elevated (instead of rewriting a real system file's DACL), andafterAllrestores inheritance (icacls /reset /t) beforeremoveTreeSyncso a regressed(OI)(CI)(IO)grant cannot leave%TEMP%undeletable.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
Three CI failures on this branch, one failure shape: hardening silently does nothing and the check that should have caught it agrees. The auth critical-path test hand-rolled a `node:child_process` factory with `execFileSync`/`execFile`. The rewritten ACL path goes through `runProcessSync`, i.e. `spawnSync`, which the factory never returned — so every spawn threw into the SID lookup's bare catch, `planFor` returned null, and hardening no-opped. It mocks `child-process/run-process` now, the boundary production code actually calls and the one sibling ACL tests already mock: an export missing there fails loudly by name instead of returning undefined. Its fake icacls writes a real UTF-16LE SDDL file, so the pinned spawn count per write is a property of the ACL path rather than of the double. The test forces `platform='win32'`, so this failed on every platform, Linux CI included. `windowsSystem32Binary` is a production bug, not a test bug: it builds a Windows path with the host `join`, which off-platform yields the mixed `C:\Windows/System32/whoami.exe`. On Windows the two joins agree, which is why it survived; on Linux the SID lookup's whoami match missed and 27 of secure-file's 32 tests exercised a lane that never ran. These are always Windows paths, so `path.win32.join` is what it should have been. The import-boundary pin still read 160 after this branch migrated secure-path-windows-acl.ts off `node:child_process`; the ratchet correctly refuses a pin left above reality.
There was a problem hiding this comment.
ℹ️ No critical issues — one minor comment nit inline.
Reviewed changes
- Rewrote the auth critical-path test double to mock
run-processinstead ofnode:child_process— the fake icacls now writes a real UTF-16LE SDDL file, so the pinned spawn count per write is a property of the ACL path rather than of the double. - Switched
windowsSystem32Binary/windowsPowerShellPathtopath.win32.join— Windows binary paths now render backslash-separated on every host, fixing the mixedC:\Windows/System32/whoami.exethat made the whoami match miss on Linux (closes the earlier POSIX CI blocker). - Lowered the
child_processimport-boundary pin 160 → 159 — aligning the ratchet with the earliersecure-path-windows-acl.tsmigration.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
| vi.mocked(runProcessSync).mockReset() | ||
| vi.mocked(runProcess).mockReset() | ||
| vi.mocked(runProcessSync).mockImplementation((spec) => { | ||
| // Matched by suffix, not by the whole path: `windowsSystem32Binary` joins with the host |
There was a problem hiding this comment.
This rationale is now stale: this same commit switched windowsSystem32Binary to path.win32.join, which yields backslashes on every host, so a full-path literal would now match on Linux too. The suffix match is harmless but the comment describes behavior this commit removed.
The start-failure cooldown was a wall-clock deadline, so a backwards step — an NTP correction, a VM snapshot restore, a user changing the clock — left `remainingCooldown()` returning the cooldown plus the whole step. A one-hour step measured 3,660,000ms, and ten real minutes later still 3,060,000ms. Nothing shortens it from there. Only `recordSuccess()` clears the cooldown on a non-dispose path, and no request can reach a helper to succeed while it holds, so every `send()` throws `runtime_host_unavailable` first. The host is built with no `now` override and its lifecycle is a module-level singleton that shuts down at process exit, so the latch held for the sidecar's life — computer use kept working via the one-shot bridge while the per-click powershell.exe burst this host exists to remove came back silently. Store the instant the cooldown began and compare elapsed monotonic time, following the two fixes in #17884. The field is `number | null` rather than sentinel 0 because `performance.now()` legitimately returns 0. Both new tests leave `now` unset, because the bug was in the default the host picks and a test that injects a clock cannot see it.
…nied read destroying the file Path hardening verified the DACL it wrote by comparing the SIDs `icacls /save` reports. SDDL substitutes two-letter aliases for well-known SIDs, and the resolution table could only hold constants -- but `LA` and `LG` name an account by RID inside the *machine's own* SID, so on a box whose user is the built-in Administrator (a CI runner, an Administrator-only install) the current user read back as `LA`, matched nothing, and hardening reported failure for every path. Resolve those two against the machine authority derived from the user SID; without one they stay unresolved and the comparison still fails closed. Three secret stores treated any read failure as "malformed -- regenerate" and overwrote. A hardened file granting a SID this process does not hold reads as EPERM while its directory stays writable, so the overwrite succeeds: renaming over an unreadable file needs FILE_DELETE_CHILD on the parent, not DELETE on the file. That destroyed the E2EE secret key, every paired device's bearer token, and the plugin vault. Distinguish EPERM/EACCES from a parse failure and refuse. Also close the async lane's unhandled rejection: `void p.then(onSettled)` turned a throw from `onSettled` into a dead main process, and the retry budget it calls threw whenever nothing had configured it -- a contract held only by import order. The budget now defaults its own bounds.
`toHaveLength` reports only a count and vitest elides the array, so three preconditions failing on the CI runner said "expected 3, got 6" and nothing about what the sixth entry was. Name the entries in the failure.
There was a problem hiding this comment.
ℹ️ No new issues in this delta. The machine-relative SDDL alias resolution and the permission-denied read handling are correct and well-tested. This is not an approval — the two must-address findings from the earlier review (the unanchored
D:regex inwindows-security-descriptor.tsand the stale verify mock inartifact-create-intent-store.test.ts) remain open and unaddressed by these commits, so they are not re-stated here.
Reviewed changes
- Resolved the machine-relative SDDL aliases —
icacls /saveemitsLA/LGfor the built-in Administrator/Guest instead of a raw SID, so a box whose interactive user is that account (a CI runner) read back an ACE no fixed table could match and hardening reported failure forever.localDomainSidOfderives the machine authority from the user SID andresolveSddlSidnow resolvesLA→-500,LG→-501against it, failing closed when the SID is not domain-relative. - Stopped a denied read from destroying the credential file — added
isPermissionDeniedError(EPERM/EACCES) and wired it intoloadOrCreateE2EEKeypair,DeviceRegistry.load(), andPluginSecretsStore.read(), so a read that fails on an ACL now refuses to regenerate/overwrite (whichrenameSyncwould succeed at) instead of silently un-pairing every device. The startup callers already catch these and surfacepairingUnavailable, so the failure degrades rather than crashes. - Extracted the hardening reporter into
secure-path-hardening-report.ts— the report type plussetSecurePathHardeningReporter/reportSecurePathHardeningmoved out of the ACL module so the retry budget can announcethrottled/recoveredwithout importing the Windows lane;initObservabilityimports the same hook. - Defaulted the retry budget instead of throwing —
failures()now lazily initializes fromDEFAULT_HARDENING_CACHE_BOUNDS(moved intosecure-path-hardening-cache.ts), so a second importer no longer turns an unconfigured budget into an unhandled rejection that killed the main process. - Guarded the async settlement callback —
bestEffortRestrictWindowsPathnow runs.then(onSettled, () => onSettled?.(false)).catch(...), so a throw from the caller's callback (or a rejected apply) reports asettlediagnostic instead of becoming an unhandled rejection. - Added a win32 real-filesystem regression suite —
unreadable-secret-store-preservation.win32.test.tsplants a foreign-SID DACL and asserts the original bytes survive each store's read path.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
Same swallow-default-overwrite shape as the readers already fixed, found by
sweeping every store that reads under a hardened root.
- plugin-storage-store.ts returned `{}` on any read failure and set()/delete()
wrote it back, losing the plugin KV store. It is the secrets store's shape
line for line, so the two now behave identically.
- relay-revoke-outbox.ts returned [] and save() wrote it, dropping revocations
that never reached the relay -- a revoked device stays live.
- profile-cloud-session-store.ts mapped an EPERM read onto `decrypt-failed`,
which fails the `status === 'found'` guard in clearCloudSessionIfUnchanged and
falls through to an rmSync of the account session. A denied read now reports
`unreadable`, which licenses nothing; the refresh path bails on it and the
auth status surfaces it rather than reporting a bare reconnect.
All reuse isPermissionDeniedError. The predicate stays an EPERM/EACCES allow
list rather than "ENOENT defaults, everything else throws": these stores are
meant to self-heal a truncated or malformed file, and inverting it would turn a
corrupt keypair into an app that cannot start. The distinction that matters is
"could not read it" versus "read it and it was garbage".
…not plant %TEMP% grants [SYSTEM, Administrators, <user>] (OI)(CI)(F) by default, and those propagate into every fixture. Three preconditions read back 4 and 6 ACEs where 3 were planted, and the extras looked like Orca's own hardening because the shape is identical -- on a runner whose user is the built-in Administrator, the inherited trio IS the trio production grants. Combining /inheritance:r with /grant:r leaves the argument order to icacls, and that combined form drops the inherited ACEs on Windows 11 but keeps them as explicit ones on the Windows Server runner. Removing inheritance in its own invocation makes the grant the whole DACL on either host, and the fixture root is de-inherited once up front so nothing propagates in. Rooting the fixtures outside %TEMP% would not have fixed this: any directory inherits from wherever it lives. The fix is to stop inheriting, not to move. No assertion is relaxed -- the counts stay exact.
There was a problem hiding this comment.
ℹ️ One minor finding inline — the shipped behavior is correct, but the new account-session test doesn't exercise the code it claims to cover.
Reviewed changes
- Extended the "refuse to overwrite an unreadable credential" protection to three more stores — the Orca Cloud account session now surfaces a distinct
unreadablestatus (and the refresh path refuses tormSyncit), the per-plugin KV/settings store refusesset/deletewhen its file could not be read, and the relay revoke outbox throws instead of writing[]over pending revocations. - Surfaced
unreadableas acredentialErrorin the cloud auth-status projection, matching the existingdecrypt-failedhandling. - Added win32 real-filesystem tests for the plugin KV store, the relay revoke outbox, and the account-session read status.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
| } | ||
| // A session we were denied is not a session we may delete: the token we would be clearing might | ||
| // not even be the one that failed, and `clearOrcaCloudSession` unlinks the file outright. | ||
| if (current.status === 'unreadable') { |
There was a problem hiding this comment.
This unreadable guard is the production fix, but the test that names it never reaches it. does not delete the account session it could not read (unreadable-secret-store-preservation.win32.test.ts:198) only asserts readOrcaCloudSession(...).status === 'unreadable'; it never calls clearCloudSessionIfUnchanged, so removing this guard leaves the whole suite green — the one test that cannot fail, in the one PR whose thesis is that every test must.
Technical details
# Account-session delete guard is untested (and possibly unreachable)
## Affected sites
- src/main/orca-profiles/profile-cloud-session-refresh.ts:77 — the `current.status === 'unreadable'` early return
- src/main/runtime/unreadable-secret-store-preservation.win32.test.ts:198 — the test that names this path but only asserts the read status
## Required outcome
- A test that fails when this guard is removed: drive `clearCloudSessionIfUnchanged` (via `readFreshOrcaCloudSession`/`forceRefreshOrcaCloudSession` with a mocked 401 and an unreadable session file) and assert the file's bytes survive, mirroring the sibling tests that invoke the mutating method.
## Open questions for the human
- Is the guard even reachable? `readOrcaCloudSession` serves `found` sessions from the process-lifetime `memorySessions` cache, so the re-read inside `clearCloudSessionIfUnchanged` always returns `found` for a session that was just read `found`; `unreadable` is only returned on a fresh process, where `readFreshOrcaCloudSession` returns `reconnect-required` before ever reaching the refresh path. If the cache makes this dead code, it is worth keeping as defense-in-depth, but then the test should either exercise the path it names or be retitled to what it actually asserts.…unner `S-1-5-32-544` is only foreign to a token that is not an administrator. The CI runner is elevated AND logged in as the built-in Administrator, so granting Administrators granted the reader full control: the file stayed readable, and all six preservation assertions went vacuous rather than proving anything. BUILTIN\Guests is resolvable everywhere and no interactive token is a member, so the read is denied on an unelevated developer box and on the runner alike. An unresolvable SID would have been the stronger choice but icacls rejects one with ERROR_NONE_MAPPED (1332). The premise guard is what caught this -- it asserted the file was actually unreadable instead of trusting the grant, and named elevation as the suspect.
There was a problem hiding this comment.
ℹ️ No new issues in this delta. The fixture-SID switch is correct and keeps the unreadable-secret suite meaningful on an elevated CI runner. This is not an approval — the four findings raised on earlier commits (the unanchored
D:SDDL regex, the staleartifact-create-intent-storeverify mock, the stale mobile-auth comment, and the untested account-session delete guard) remain open and are not re-stated here.
Reviewed changes
- Switched the unreadable-secret fixture SID from Administrators to Guests —
S-1-5-32-544is the Administrators group, which an elevated admin token holds enabled, so on an elevated CI runner the planted full-control grant became readable and the suite's "file is unreadable" premise failed.S-1-5-32-546(Guests) is a well-known, always-resolvable SID no CI token is a member of, restoring the premise without theERROR_NONE_MAPPEDfailure an unresolvable SID would cause.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
…t just a denied one isPermissionDeniedError becomes isUnreadableError, because "permission denied" was never the concept -- "could not read it", as opposed to "read it and it was garbage", is. EBUSY, EMFILE, ENFILE and EIO say exactly as little about a file's contents as EACCES does, and they fell into the branch that regenerates and overwrites. On Windows EBUSY is the likelier of the two: antivirus holding a credential open at the moment of a startup read produces it, which makes it a commoner path to the same permanent loss than the ACL case that motivated the original fix. Still an allow list, deliberately: ENOENT keeps licensing a create, and a parse failure keeps self-healing. The stores are built to recover from a truncated write, and turning that into a refusal would trade a recoverable state for an unrecoverable one on the startup path. Also fixes the regression suite's own premise on an elevated runner: makeUnreadable combined /inheritance:r with /grant:r, and that form keeps %TEMP%'s inherited [SYSTEM, Administrators, user] as explicit ACEs on Windows Server -- so the file stayed readable and all six assertions were vacuous. Same split-the-invocation fix as the ACL suite's planter.
There was a problem hiding this comment.
ℹ️ No new issues in this delta. This is not an approval — the findings raised on the earlier commits (the unanchored
D:SDDL regex inwindows-security-descriptor.ts, the staleartifact-create-intent-store.test.tsverify mock, and the untested account-session delete guard) remain open and are not re-stated here.
Reviewed changes
- Widened the refuse-to-overwrite predicate —
isPermissionDeniedErrorbecameisUnreadableError, now treatingEBUSY/EMFILE/ENFILE/EIOas "the contents were never seen" alongsideEPERM/EACCES. An antivirus-held or transiently-unreadable credential is now refused regeneration instead of silently overwritten (whichrenameSyncwould succeed at), and the allow-list rationale (still excludingENOENTand parse failures) is documented in both the docstring and commit message. - Updated the stores' wording — all seven credential stores and their
unreadable-secret-store-preservation.win32.test.tsassertions now say "the read failed" rather than "permission denied", matching the broadened predicate. - Fixed the regression suite's own premise —
makeUnreadablenow splits/inheritance:rfrom/grant:r, so a planted foreign-SID DACL cannot keep%TEMP%'s inherited ACEs as explicit on Windows Server and leave every assertion vacuous.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
An elevated token logged in as the built-in Administrator reads straight through a DACL that grants it nothing -- confirmed on the CI runner against both BUILTIN\Administrators and BUILTIN\Guests, and with the grant split into its own icacls invocation so the DACL really was the planted one. On such a host the premise these tests rest on does not hold, and every assertion would pass while proving nothing. So probe once at module scope and skip rather than assert vacuously -- the same trade the ACL suite already makes for its unelevated-only case. The gate stays in the compound `<win32 check> && <flag>` form the win32 lane ratchet detects, so the file stays registered in both lane lists. Coverage is not lost where it counts: isUnreadableError has unit tests that run on every platform and every host, and the stores' refusal is exercised in full on any machine where a denial is reproducible -- which is every developer box.
There was a problem hiding this comment.
ℹ️ No new issues in this delta. This is not an approval — the findings raised on the earlier commits (the unanchored
D:SDDL regex, the staleartifact-create-intent-storeverify mock, the mobile-auth comment nit, and the untested account-session delete guard) remain open and are not re-stated here.
Reviewed changes
- Skip the preservation suite where a read cannot be denied —
unreadable-secret-store-preservation.win32.test.tsnow probes once at collection time (canDenyReads) by planting a foreign-SID DACL and confirming a realEPERM/EACCESdenial before running, so an elevated token (built-in Administrator) that reads straight through the DACL skips the suite instead of passing vacuously.makeUnreadablereuses the sharedreadDenied()predicate for the same check.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
…17858) * fix(computer-use): run the Windows runtime as one persistent helper Microsoft Defender for Endpoint raised multi-stage Execution + Collection incidents against Orca on Windows ("Screenshots were taken unexpectedly on this device... Screen capture code was found in a script launched by powershell.exe", factor "Executes suspicious MSIL code"). The desktop script provider spawned a fresh powershell.exe per operation, so a single computer-use session produced a burst of short-lived PIDs and re-emitted runtime.ps1's inline Add-Type P/Invoke assembly on every click. runtime.ps1 gains a -Serve mode that loads its assemblies once and then reads NDJSON requests from stdin, and a new DesktopScriptRuntimeHost owns one long-lived child: lazy spawn, strict serialization, a 30s per-request timeout, restart on crash, a 120s idle shutdown, and dispose() on provider teardown. The one-shot -OperationPath path stays as the fallback, and Linux keeps its python3 bridge unchanged. Both Windows spawn sites now use -ExecutionPolicy RemoteSigned instead of Bypass, falling back once to Bypass (and logging) when a Restricted host refuses the unsigned script. * fix(computer-use): recover the runtime host instead of latching it off Review follow-up on the persistent Windows computer-use helper. A helper that died before producing a line set an unavailable flag nothing ever cleared, and the client then dropped the host for the life of the session. One transient bad spawn — a Defender scan, a locked CSC temp directory — silently restored the per-click powershell.exe burst and per-operation MSIL emission this work exists to remove, with computer use still working so nothing looked wrong. Start failures are now retried, then cool down for 60s, then re-probed; the client keeps the host so it can come back. Repeated post-answer crashes cool down too, and a single reply no longer clears the failure count. The one-shot bridge decided its execution-policy retry from a message that fell back to stdout, so a window title containing "SecurityError" could replay a non-idempotent operation — a double click, keystroke or paste — and stick the session on Bypass. The retry now requires empty stdout and a matching stderr. Serve-mode replies carry an echoed request id. Without one a single stray stdout line would make every later response answer the previous request, acting on stale element indexes with no error raised; a mismatch now kills the child. Non-JSON noise is ignored rather than counted as the helper having answered. Also: warnings reach the main process over the sidecar's IPC channel rather than its piped, unread stdio; the child is watched on close rather than exit; dispose latches so a queued request cannot respawn during teardown; and the host is split into a serve channel and an availability policy to stay under max-lines. * fix(computer-use): prove a helper never started before replaying its request The retry that replaced the permanent-latch bug could deliver unrequested input. send() re-sent the same request whenever the helper died without replying, but "no reply came back" is not "the operation did not run": runtime.ps1 synthesizes the click and only then builds the snapshot, which allocates a full-window bitmap and walks the UIA tree — a native GDI+/UIA fault there is uncatchable, and leaves the click already delivered. A deterministic fault meant three clicks from the host plus a fourth from the one-shot bridge, surfaced as a single failed operation. -Serve now writes one {"ready":true} line after its Add-Type work and before its first read, so "never started" is a fact rather than an inference. A request is replayed only when the helper died before announcing. A runtime.ps1 that predates the announcement — reachable through the provider path override — is covered by an observation-tool allowlist until a ready line proves otherwise. Host-detected aborts (timeout, desynchronised reply, oversized line) suppress the exit handler, so they were bypassing failure accounting entirely and a helper failing that way was respawned once per operation forever. They now count and are logged. Also stop charging twice for one outage: entering the cooldown resets the failure count, so the first death after recovery no longer re-enters a full cooldown and an interleaved workload cannot be stranded on the one-shot bridge. * fix(computer-use): ignore a stdin write callback from a torn-down helper stop() destroys stdin, so a write still queued at teardown calls back with ERR_STREAM_DESTROYED. The callback carried no channel or request identity and write() had no closed guard, so it ran abortChannel a second time: stopChannel no-opped but recordFailure and the warning did not, charging two failures for one operation and reaching the 3-strike cooldown at half the intended rate. That feeds the same accounting that keeps a persistently broken helper from respawning once per operation. The same root also allowed a late callback landing after a replacement channel existed to stop that channel and reject a different request with the previous one's error. Node fires the destroyed-stream callback on the next tick, well before a new request arrives, so the double-count is the reachable effect; binding the callback closes both. write() now drops payloads and error reports once closed, and the host ignores any report whose channel or request id is no longer current. * test(computer-use): pin each stale-write guard independently The channel's closed guard and the host's request-identity check are redundant by design, and the existing tests only failed when both were absent. Someone deleting one, believing the other was the covered one, would have got a green suite and a live regression — the same shape as a test that passes without the fix it was written for. Each is now pinned on its own. The channel's half is tested against the channel directly: after stop() it takes no writes and reports no error from one already queued, which the host cannot observe because it drops the channel at the same moment. The host's half is pinned by the case the channel cannot see — a live channel whose request was already answered, where backpressure delivers a write callback for a request that is no longer pending. Removing either guard alone now fails a test. Both carry a comment saying they are deliberately redundant and separately pinned, so the next reader does not have to rediscover this from the diff. * ci(windows): run the computer-use runtime host suite in CI The win32 suite only self-skips off Windows, so it passed vacuously in every lane. Register it the way the cmd-shim suite is registered. * fix(computer-use): time the runtime host cooldown on a monotonic clock The start-failure cooldown was a wall-clock deadline, so a backwards step — an NTP correction, a VM snapshot restore, a user changing the clock — left `remainingCooldown()` returning the cooldown plus the whole step. A one-hour step measured 3,660,000ms, and ten real minutes later still 3,060,000ms. Nothing shortens it from there. Only `recordSuccess()` clears the cooldown on a non-dispose path, and no request can reach a helper to succeed while it holds, so every `send()` throws `runtime_host_unavailable` first. The host is built with no `now` override and its lifecycle is a module-level singleton that shuts down at process exit, so the latch held for the sidecar's life — computer use kept working via the one-shot bridge while the per-click powershell.exe burst this host exists to remove came back silently. Store the instant the cooldown began and compare elapsed monotonic time, following the two fixes in #17884. The field is `number | null` rather than sentinel 0 because `performance.now()` legitimately returns 0. Both new tests leave `now` unset, because the bug was in the default the host picks and a test that injects a clock cannot see it. * fix(computer-use): give a queued request its own deadline The 30s request timeout was armed only in `sendOnce`, once a request reached a helper. A request behind N timing-out ones therefore waited roughly N times that with no deadline of its own: bounded, but the caller sees an `await` that looks hung for minutes and gets no error to act on. Move the serialization tail into its own class and arm a deadline at enqueue time. Only the wait is bounded — a request that reaches a helper still gets its full execution budget, so nothing that used to succeed now fails. An expired request is dropped rather than sent late: the caller has already been told it failed, and a click delivered after that is worse than no click. The tail keeps its never-rejecting shape and chains on the turn rather than on the raced promise, so a caller giving up early cannot release the next request while its predecessor is still in flight. * fix(computer-use): stop reading a locked file as an execution policy block `UnauthorizedAccess` is the FullyQualifiedErrorId PowerShell reports for a policy block, and it is also a strict prefix of `UnauthorizedAccessException`, which .NET raises for any ordinary locked or ACL-denied file. The predicate matched the token unanchored, so an AV scan holding runtime.ps1 or a locked CSC temp directory was read as a policy block. Two consequences, both bad. `escalateExecutionPolicy()` has no path back, so one false match spent the rest of the session on `-ExecutionPolicy Bypass` — the exact command line token this stack exists to stop emitting. And on the one-shot path `isPolicyBlockedStart` re-runs the operation: one-shot mode writes stdout only after the operation returns, so a crash partway through an action is indistinguishable from a helper that never started, and the click lands twice. Measured on Windows against all three records, which the test carries verbatim as fixtures: policy/Restricted FullyQualifiedErrorId: UnauthorizedAccess policy/RemoteSigned FullyQualifiedErrorId: UnauthorizedAccess genuine access denied FullyQualifiedErrorId: UnauthorizedAccessException `\b` is the whole discriminator: between `s` and `E` both sides are word characters, so no boundary exists there and the exception cannot match. Dropped two alternatives that measurement showed were wrong. `PSSecurityException` never appears — the record surfaces through a native-command wrapper and reports `ParentContainsErrorRecordException`. The prose is wrong three times over: it differs by policy, it is localized, and PowerShell hard-wraps it mid-sentence. Anchoring on the `FullyQualifiedErrorId:`/`CategoryInfo:` labels would be more precise again, but those labels are localized where the values are not, so it would lose a real block on a non-English host and strand it with no fallback. Matching the values with word boundaries keeps both directions; a fixture with translated labels pins it. The escalation stays sticky. With the predicate correct, it only fires on a machine that really does block, where re-probing the preferred policy would buy a guaranteed failed spawn per operation. * fix(computer-use): route a malformed request back to the request that caused it `ConvertFrom-Json` throws before `$requestId` is read, so the serve loop answered an unparseable request with an untagged error. On the client that is not an error at all: `deliver()` sees no matching id, calls `abortChannel`, kills the helper and charges a failure — and the helper's own message is discarded. A parse failure was reported as a stream desync with no trace of the real cause, and three of them walked into the 60s cooldown behind three misleading "did not match" messages. Recover the id from the raw line when the parse fails. No wire change: the response shape is untouched and `BridgeResponse.requestId` already documents this echo. It is the same shape the helper already returns for `not_a_tool`, where the id survives because it is read before the operation runs. Both mixed pairings degrade safely — a new script with an old client resolves the error normally, and an old script with a new client still aborts, but now reports what the helper said. When the line is mangled past recovering an id, the desync abort is the honest outcome, so keep it and carry the helper's text into it rather than replacing it. A line the helper could not tag is usually the only account of the cause. Proven against the real `runtime.ps1 -Serve`: the host can only write well-formed JSON, so the parse-failure branch is unreachable through it and the test drives the channel directly. * fix(computer-use): keep the Bypass escalation only when Bypass actually works AppLocker and WDAC constrained language mode raise PSSecurityException under the same SecurityError category a real execution-policy block uses, so the predicate matches them - correctly, on the evidence available. But those block the script at parse time, which `-ExecutionPolicy Bypass` cannot lift. The escalation was sticky unconditionally, so on a WDAC host we misdiagnosed, retried, failed again, and then latched: every later command line carried the most heavily weighted MDE token there is, on exactly the hardened, monitored enterprise machine that is watching for it. Treat the escalation as the diagnosis it is. A fallback that cannot start a helper either disproves it - the policy was not what stopped the first attempt - so revert to RemoteSigned instead of latching. When Bypass does start a helper the diagnosis is confirmed and it stays sticky exactly as before, so a genuinely Restricted machine still never pays a re-probe per operation. The revert lands inside the outage rather than only at its end, so a misdiagnosis costs one Bypass command line instead of one per attempt, and an escalation that never proved itself does not outlive the cooldown that ends the outage. Deliberately not a permanent "fallback is useless" flag: a Bypass attempt that failed for a transient reason would then disable the fallback for the session, which is the same latch in the other direction. Only `runtime_host_unavailable` proves no helper started, so only that reverts; a helper that started and then died proves Bypass works. That also makes the policy branch reachable on a final attempt for the first time, so it now rejects as unavailable rather than a generic error - that code is what routes the operation to the one-shot bridge, which carries its own policy fallback, and without it an all-blocked host would fail operations outright instead of degrading. The pre-existing "reports itself unavailable when Bypass is also refused" test pins that. --------- Co-authored-by: Orca Worker <orca-worker@localhost>
The ACL hunks are obsolete: #17884 replaced the PowerShell ACL path with icacls, so there is no ACL PowerShell left to strip a switch from. Took main's side there; system-fonts.ts is the remaining live site.
…tablyai#17858) * fix(computer-use): run the Windows runtime as one persistent helper Microsoft Defender for Endpoint raised multi-stage Execution + Collection incidents against Orca on Windows ("Screenshots were taken unexpectedly on this device... Screen capture code was found in a script launched by powershell.exe", factor "Executes suspicious MSIL code"). The desktop script provider spawned a fresh powershell.exe per operation, so a single computer-use session produced a burst of short-lived PIDs and re-emitted runtime.ps1's inline Add-Type P/Invoke assembly on every click. runtime.ps1 gains a -Serve mode that loads its assemblies once and then reads NDJSON requests from stdin, and a new DesktopScriptRuntimeHost owns one long-lived child: lazy spawn, strict serialization, a 30s per-request timeout, restart on crash, a 120s idle shutdown, and dispose() on provider teardown. The one-shot -OperationPath path stays as the fallback, and Linux keeps its python3 bridge unchanged. Both Windows spawn sites now use -ExecutionPolicy RemoteSigned instead of Bypass, falling back once to Bypass (and logging) when a Restricted host refuses the unsigned script. * fix(computer-use): recover the runtime host instead of latching it off Review follow-up on the persistent Windows computer-use helper. A helper that died before producing a line set an unavailable flag nothing ever cleared, and the client then dropped the host for the life of the session. One transient bad spawn — a Defender scan, a locked CSC temp directory — silently restored the per-click powershell.exe burst and per-operation MSIL emission this work exists to remove, with computer use still working so nothing looked wrong. Start failures are now retried, then cool down for 60s, then re-probed; the client keeps the host so it can come back. Repeated post-answer crashes cool down too, and a single reply no longer clears the failure count. The one-shot bridge decided its execution-policy retry from a message that fell back to stdout, so a window title containing "SecurityError" could replay a non-idempotent operation — a double click, keystroke or paste — and stick the session on Bypass. The retry now requires empty stdout and a matching stderr. Serve-mode replies carry an echoed request id. Without one a single stray stdout line would make every later response answer the previous request, acting on stale element indexes with no error raised; a mismatch now kills the child. Non-JSON noise is ignored rather than counted as the helper having answered. Also: warnings reach the main process over the sidecar's IPC channel rather than its piped, unread stdio; the child is watched on close rather than exit; dispose latches so a queued request cannot respawn during teardown; and the host is split into a serve channel and an availability policy to stay under max-lines. * fix(computer-use): prove a helper never started before replaying its request The retry that replaced the permanent-latch bug could deliver unrequested input. send() re-sent the same request whenever the helper died without replying, but "no reply came back" is not "the operation did not run": runtime.ps1 synthesizes the click and only then builds the snapshot, which allocates a full-window bitmap and walks the UIA tree — a native GDI+/UIA fault there is uncatchable, and leaves the click already delivered. A deterministic fault meant three clicks from the host plus a fourth from the one-shot bridge, surfaced as a single failed operation. -Serve now writes one {"ready":true} line after its Add-Type work and before its first read, so "never started" is a fact rather than an inference. A request is replayed only when the helper died before announcing. A runtime.ps1 that predates the announcement — reachable through the provider path override — is covered by an observation-tool allowlist until a ready line proves otherwise. Host-detected aborts (timeout, desynchronised reply, oversized line) suppress the exit handler, so they were bypassing failure accounting entirely and a helper failing that way was respawned once per operation forever. They now count and are logged. Also stop charging twice for one outage: entering the cooldown resets the failure count, so the first death after recovery no longer re-enters a full cooldown and an interleaved workload cannot be stranded on the one-shot bridge. * fix(computer-use): ignore a stdin write callback from a torn-down helper stop() destroys stdin, so a write still queued at teardown calls back with ERR_STREAM_DESTROYED. The callback carried no channel or request identity and write() had no closed guard, so it ran abortChannel a second time: stopChannel no-opped but recordFailure and the warning did not, charging two failures for one operation and reaching the 3-strike cooldown at half the intended rate. That feeds the same accounting that keeps a persistently broken helper from respawning once per operation. The same root also allowed a late callback landing after a replacement channel existed to stop that channel and reject a different request with the previous one's error. Node fires the destroyed-stream callback on the next tick, well before a new request arrives, so the double-count is the reachable effect; binding the callback closes both. write() now drops payloads and error reports once closed, and the host ignores any report whose channel or request id is no longer current. * test(computer-use): pin each stale-write guard independently The channel's closed guard and the host's request-identity check are redundant by design, and the existing tests only failed when both were absent. Someone deleting one, believing the other was the covered one, would have got a green suite and a live regression — the same shape as a test that passes without the fix it was written for. Each is now pinned on its own. The channel's half is tested against the channel directly: after stop() it takes no writes and reports no error from one already queued, which the host cannot observe because it drops the channel at the same moment. The host's half is pinned by the case the channel cannot see — a live channel whose request was already answered, where backpressure delivers a write callback for a request that is no longer pending. Removing either guard alone now fails a test. Both carry a comment saying they are deliberately redundant and separately pinned, so the next reader does not have to rediscover this from the diff. * ci(windows): run the computer-use runtime host suite in CI The win32 suite only self-skips off Windows, so it passed vacuously in every lane. Register it the way the cmd-shim suite is registered. * fix(computer-use): time the runtime host cooldown on a monotonic clock The start-failure cooldown was a wall-clock deadline, so a backwards step — an NTP correction, a VM snapshot restore, a user changing the clock — left `remainingCooldown()` returning the cooldown plus the whole step. A one-hour step measured 3,660,000ms, and ten real minutes later still 3,060,000ms. Nothing shortens it from there. Only `recordSuccess()` clears the cooldown on a non-dispose path, and no request can reach a helper to succeed while it holds, so every `send()` throws `runtime_host_unavailable` first. The host is built with no `now` override and its lifecycle is a module-level singleton that shuts down at process exit, so the latch held for the sidecar's life — computer use kept working via the one-shot bridge while the per-click powershell.exe burst this host exists to remove came back silently. Store the instant the cooldown began and compare elapsed monotonic time, following the two fixes in stablyai#17884. The field is `number | null` rather than sentinel 0 because `performance.now()` legitimately returns 0. Both new tests leave `now` unset, because the bug was in the default the host picks and a test that injects a clock cannot see it. * fix(computer-use): give a queued request its own deadline The 30s request timeout was armed only in `sendOnce`, once a request reached a helper. A request behind N timing-out ones therefore waited roughly N times that with no deadline of its own: bounded, but the caller sees an `await` that looks hung for minutes and gets no error to act on. Move the serialization tail into its own class and arm a deadline at enqueue time. Only the wait is bounded — a request that reaches a helper still gets its full execution budget, so nothing that used to succeed now fails. An expired request is dropped rather than sent late: the caller has already been told it failed, and a click delivered after that is worse than no click. The tail keeps its never-rejecting shape and chains on the turn rather than on the raced promise, so a caller giving up early cannot release the next request while its predecessor is still in flight. * fix(computer-use): stop reading a locked file as an execution policy block `UnauthorizedAccess` is the FullyQualifiedErrorId PowerShell reports for a policy block, and it is also a strict prefix of `UnauthorizedAccessException`, which .NET raises for any ordinary locked or ACL-denied file. The predicate matched the token unanchored, so an AV scan holding runtime.ps1 or a locked CSC temp directory was read as a policy block. Two consequences, both bad. `escalateExecutionPolicy()` has no path back, so one false match spent the rest of the session on `-ExecutionPolicy Bypass` — the exact command line token this stack exists to stop emitting. And on the one-shot path `isPolicyBlockedStart` re-runs the operation: one-shot mode writes stdout only after the operation returns, so a crash partway through an action is indistinguishable from a helper that never started, and the click lands twice. Measured on Windows against all three records, which the test carries verbatim as fixtures: policy/Restricted FullyQualifiedErrorId: UnauthorizedAccess policy/RemoteSigned FullyQualifiedErrorId: UnauthorizedAccess genuine access denied FullyQualifiedErrorId: UnauthorizedAccessException `\b` is the whole discriminator: between `s` and `E` both sides are word characters, so no boundary exists there and the exception cannot match. Dropped two alternatives that measurement showed were wrong. `PSSecurityException` never appears — the record surfaces through a native-command wrapper and reports `ParentContainsErrorRecordException`. The prose is wrong three times over: it differs by policy, it is localized, and PowerShell hard-wraps it mid-sentence. Anchoring on the `FullyQualifiedErrorId:`/`CategoryInfo:` labels would be more precise again, but those labels are localized where the values are not, so it would lose a real block on a non-English host and strand it with no fallback. Matching the values with word boundaries keeps both directions; a fixture with translated labels pins it. The escalation stays sticky. With the predicate correct, it only fires on a machine that really does block, where re-probing the preferred policy would buy a guaranteed failed spawn per operation. * fix(computer-use): route a malformed request back to the request that caused it `ConvertFrom-Json` throws before `$requestId` is read, so the serve loop answered an unparseable request with an untagged error. On the client that is not an error at all: `deliver()` sees no matching id, calls `abortChannel`, kills the helper and charges a failure — and the helper's own message is discarded. A parse failure was reported as a stream desync with no trace of the real cause, and three of them walked into the 60s cooldown behind three misleading "did not match" messages. Recover the id from the raw line when the parse fails. No wire change: the response shape is untouched and `BridgeResponse.requestId` already documents this echo. It is the same shape the helper already returns for `not_a_tool`, where the id survives because it is read before the operation runs. Both mixed pairings degrade safely — a new script with an old client resolves the error normally, and an old script with a new client still aborts, but now reports what the helper said. When the line is mangled past recovering an id, the desync abort is the honest outcome, so keep it and carry the helper's text into it rather than replacing it. A line the helper could not tag is usually the only account of the cause. Proven against the real `runtime.ps1 -Serve`: the host can only write well-formed JSON, so the parse-failure branch is unreachable through it and the test drives the channel directly. * fix(computer-use): keep the Bypass escalation only when Bypass actually works AppLocker and WDAC constrained language mode raise PSSecurityException under the same SecurityError category a real execution-policy block uses, so the predicate matches them - correctly, on the evidence available. But those block the script at parse time, which `-ExecutionPolicy Bypass` cannot lift. The escalation was sticky unconditionally, so on a WDAC host we misdiagnosed, retried, failed again, and then latched: every later command line carried the most heavily weighted MDE token there is, on exactly the hardened, monitored enterprise machine that is watching for it. Treat the escalation as the diagnosis it is. A fallback that cannot start a helper either disproves it - the policy was not what stopped the first attempt - so revert to RemoteSigned instead of latching. When Bypass does start a helper the diagnosis is confirmed and it stays sticky exactly as before, so a genuinely Restricted machine still never pays a re-probe per operation. The revert lands inside the outage rather than only at its end, so a misdiagnosis costs one Bypass command line instead of one per attempt, and an escalation that never proved itself does not outlive the cooldown that ends the outage. Deliberately not a permanent "fallback is useless" flag: a Bypass attempt that failed for a transient reason would then disable the fallback for the session, which is the same latch in the other direction. Only `runtime_host_unavailable` proves no helper started, so only that reverts; a helper that started and then died proves Bypass works. That also makes the policy branch reachable on a final attempt for the first time, so it now rejects as unavailable rather than a generic error - that code is what routes the operation to the one-shot bridge, which carries its own policy fallback, and without it an all-blocked host would fail operations outright instead of degrading. The pre-existing "reports itself unavailable when Bypass is also refused" test pins that. --------- Co-authored-by: Orca Worker <orca-worker@localhost>
…tablyai#17884) * fix(security): apply the Windows path-hardening ACL that never ran `buildWindowsRestrictAclArgs` invoked the hardening script as `powershell.exe -Command <script> <path> <sid> <isDir>`. `-Command` does not populate `$args`; it appends the trailing tokens to the command text. The script therefore read `$args[1]` as `$null`, threw `NullArrayIndex` at `$allowedSids[$sidText] = $true` under `$ErrorActionPreference = 'Stop'`, and exited 1. Both callers swallowed that: the async callback was empty and `applySecurePathRestriction` returned `true` regardless, while the sync `catch` returned `false` and nobody logged. Every Windows secure path has been left on its inherited ACL since the ACL was introduced (stablyai#5006), and nothing said so. Replace PowerShell with `icacls.exe`, which takes plain argv. That removes the quoting surface entirely rather than escaping it: interpolating a path into the command text would have turned a dead no-op into arbitrary PowerShell on a filesystem path, since `-Command` executes what it appends. It also drops the execution-policy dependency and the `powershell.exe` spawn an EDR flags, and runs ~25x faster than the PowerShell cold start. Hardening is now three passes: `/reset` to purge explicit ACEs that `/inheritance:r` leaves behind, `/inheritance:r` plus a `/grant:r` per allowed SID, then a read-back that checks the DACL is protected and grants only the intended rights. The predecessor's verification block was equally dead, and an apply that is never read back is only half a control. Failures stay non-fatal — non-NTFS volumes, network paths and restricted tokens fail legitimately and must not break startup — but they are no longer invisible: every failure is logged, and a failed async apply now evicts its cache entry so the next call retries instead of trusting a success that never happened. Routing through `runProcess`/`runProcessSync` also retires this file's `node:child_process` allowlist entry. * fix(security): verify the hardened ACL by identity, not by shape Review found the bug class this PR fixes surviving inside the fix. The verify pass checked rule count, absence of the inherited marker, and exact rights — never *who* the rules named. Granting Everyone full control satisfies all three, so hardening reported success on a DACL that handed the credential to every local account, and most of the real-filesystem tests still passed. Verification now reads the descriptor back with `icacls /save`, which emits SDDL with raw SIDs, and compares the principal set exactly. That is also locale-independent by construction: the previous parse read localized account names out of icacls' OEM-codepage stdout, where a non-ASCII path survived by accident rather than by the documented mechanism. SDDL parsing moves to `windows-security-descriptor.ts`. Two further self-inflicted problems, both measured: The post-rename re-harden led with `/reset`, which re-widened a DACL that was already correct — the staged file's protected DACL survives the rename, so the pass had nothing to do but open a window. Polling an external process during a write into a relocated root caught it: the e2ee keypair dropped to `BUILTIN\Users:(RX)` plus `Authenticated Users:(M)` — read *and* write — before tightening again. Hardening now verifies first and returns early when the DACL already reads back correct, which closes the window and cuts the steady state from three spawns to one. Re-measured: 158 samples, one DACL state, zero broad. Evicting the cache on every failed async apply reintroduced stablyai#4901. The env store re-hardens on the read path at ~2/s, so on a host where hardening cannot work (FAT32, network path, restricted token) that was two icacls spawns and two warnings a second, forever. Async retries now take a retry floor and a hard per-path attempt cap. The write path keeps retrying unthrottled — it is user-driven, and a failed credential ACL must still be retried on the next write. Also: failures route through a reporter hook that the main process points at the diagnostic tracer, because `console.warn` reaches nothing in a packaged GUI-subsystem build; `writeSecureFile` returns whether hardening took, and the async branch reports `pending` rather than claiming `applied`; a transient `whoami` failure no longer disables hardening for the process lifetime, and the SID is shape-validated; the `/c` guard now covers the synchronous runner too. * fix(security): re-probe hardening instead of latching a transient failure The per-process attempt cap added for the read-path storm was a permanent latch: one AV scan, momentary lock or %TEMP% blip and every later credential write in that session went unhardened, silently, on a host where hardening would now succeed. Same defect class as stablyai#17858's computer-use host, and worse here because what stops happening is security hardening on credential files and nothing said so. The retry budget now bounds the *rate*, not the lifetime: at most three attempts per path per minute, re-probing in every later window, forever. The transition is announced in both directions — `throttled` once per window on entry, `recovered` when a rate-limited path hardens again — so a host stuck in the degraded state is diagnosable rather than merely quiet. The reporter type covers both, and the main process ends the `recovered` span successfully rather than failing it. Extracted to secure-path-hardening-retry-budget.ts, which keeps secure-file.ts under its line cap without a max-lines disable. Also confirms the second flagged risk rather than assuming it: a real unwritable %TEMP% is now covered by a test proving verification fails closed, reports at the `verify` stage, and still leaves the ACL applied — so that path loses proof, not protection, and with the lifetime cap gone it can no longer combine into a permanent-off state. * fix(security): verify a directory's whole inheritance flag set The flag check tested only that `OI` was present — never that `CI` was, nor that nothing else was. That was harmless while `/reset` + `/grant` ran on every pass and repaired whatever was there. The verify-first short-circuit made it load-bearing: what verification accepts is now left alone, so a latent under-check went live because a different fix started depending on it. Two directory DACLs passed while being wrong — both protected, three non-inherited full-control rules, correct SIDs, differing from correct only in their flags: (OI)(F) - no CI, so subdirectories are left unprotected (OI)(CI)(IO) - inherit-only, so the directory object itself grants nobody anything; the next writeFileSync into it fails with EPERM, on a directory just cached as hardened Verification now compares the whole flag set, which also rejects IO and NP, and names the offending flags in the failure. Both shapes are planted in real-filesystem regression tests, including an assertion that a write into the repaired directory succeeds and its child inherits. Confirmed both tests fail against the old check and pass against this one. * fix(security): back the hardening retry off exponentially The fixed one-minute window bounded the retry rate but left a standing floor of three attempts per path per minute on a host where hardening can never succeed — FAT32/exFAT, a network path, a redirected profile. That budget is per path and there are several secure files, so the floor multiplied into tens of thousands of icacls spawns a day for work guaranteed to fail. The delay now doubles after each consecutive failure, from a one-minute floor to a thirty-minute ceiling, and the attempt cap is gone entirely: once the backoff elapses the path is re-probed however long it has been failing. A permanently incapable host settles at ~2 attempts/hour. Slowing the backstop costs almost nothing, because it is not the recovery mechanism: the synchronous write path is deliberately unthrottled, so a host that recovers hardens on its very next credential write regardless of what the read-path budget says. The `throttled`/`recovered` reports are unchanged and matter more here, since the quiet periods between probes are now much longer. The curve is pinned in a new unit test against the exported delay function rather than a copy of its constants, covering the doubling, the ceiling holding at 5000 consecutive failures, a 30-day failing path still re-probing, one announcement per degraded episode, and per-path isolation. The integration tests keep only what they uniquely prove: that the read path is wired to the budget, and that a day of failures still re-probes. Confirmed four of these fail against a reinstated lifetime cap. * ci(windows): run the real-icacls DACL suite in CI The win32 suite only self-skips off Windows, so it passed vacuously in every lane. Register it the way the cmd-shim suite is registered. * fix(security): describe the cache's real cost, which is icacls now Both cache comments still justified themselves with PowerShell -- "~1-1.5s" and "a PowerShell spawn every read" -- in the same file whose PR removed PowerShell from this path. The caches are still right, but for different numbers, and the old ones are the kind an engineer would reasonably delete a cache over. The real shape: hardening verifies first and returns early, so an already-correct DACL costs one synchronous icacls spawn and a rewrite costs four (verify, reset, grant, verify). Still worth caching on the read path, which polls at ~2/s. * test(security): make the DACL suite safe to schedule Registering this spec in the Windows lane put it under two rules it had never been measured against. Teardown now goes through `removeTreeSync`, which the lane's boundary test requires, and repairs the DACLs the suite plants on purpose first: those retries only cover transient locks, so a regressed `(OI)(CI)(IO)` repair leaves the root un-removable and `afterAll` throws EPERM. And the no-permission case decides by elevation before it writes anything. `windows-2022` runs elevated, where hardening succeeds: the old branch asserted nothing about denial and instead replaced the `hosts` DACL, then `icacls /reset` -- which is not a restore, it drops the explicit `SYSTEM:(F)` that file ships with. Ephemeral in CI; permanent for a developer running the lane from an elevated shell. Now it asserts or it skips. The probe reads the token integrity SID rather than `icacls /save`, which succeeds unelevated (`BUILTIN\Users:(RX)` carries READ_CONTROL) and would have skipped the case on every machine. * fix(security): measure the hardening latches on a clock that cannot go backwards `mayAttemptHardening` compared wall-clock times, so any backwards step -- an NTP correction, a VM snapshot restore, a user changing the clock -- made the elapsed time negative and held every failing path below its delay until the clock caught up. Measured at the 30-minute ceiling with the clock stepped back a year, the path was refused at +0d, +1d, +30d, +180d and +364d, and re-probed only at +366d. That is the permanent latch the exponential backoff was added to remove, and it contradicts the module's own "bounds the rate without ever bounding the lifetime". The SID lookup's own one-minute window had the identical shape and is worse: a failed lookup makes `planFor` return null, which disables the synchronous *write* path too, so the write-path exemption that recovers the read-path budget cannot recover it. Both now measure elapsed monotonic time, following the repo's existing `monotonicNowMs` spelling. Two things the write path was not doing, both found in the same pass: - A successful synchronous apply now records the outcome. It is exempt from the budget, but it was also invisible to it, so a host that had demonstrably recovered kept the read path backing off for up to 30 minutes and no `recovered` transition ever came from that lane. Only success is recorded; recording failure would put the exempt lane back under the budget. - `writeSecureFile`'s JSDoc now says its boolean covers the file only. The directory harden is fire-and-forget and answers `pending` on Windows regardless, so a `true` says nothing about the directory's ACL. * fix(security): stop the hardening test doubles from faking a no-op Three CI failures on this branch, one failure shape: hardening silently does nothing and the check that should have caught it agrees. The auth critical-path test hand-rolled a `node:child_process` factory with `execFileSync`/`execFile`. The rewritten ACL path goes through `runProcessSync`, i.e. `spawnSync`, which the factory never returned — so every spawn threw into the SID lookup's bare catch, `planFor` returned null, and hardening no-opped. It mocks `child-process/run-process` now, the boundary production code actually calls and the one sibling ACL tests already mock: an export missing there fails loudly by name instead of returning undefined. Its fake icacls writes a real UTF-16LE SDDL file, so the pinned spawn count per write is a property of the ACL path rather than of the double. The test forces `platform='win32'`, so this failed on every platform, Linux CI included. `windowsSystem32Binary` is a production bug, not a test bug: it builds a Windows path with the host `join`, which off-platform yields the mixed `C:\Windows/System32/whoami.exe`. On Windows the two joins agree, which is why it survived; on Linux the SID lookup's whoami match missed and 27 of secure-file's 32 tests exercised a lane that never ran. These are always Windows paths, so `path.win32.join` is what it should have been. The import-boundary pin still read 160 after this branch migrated secure-path-windows-acl.ts off `node:child_process`; the ratchet correctly refuses a pin left above reality. * fix(security): resolve the machine-relative SDDL alias, and stop a denied read destroying the file Path hardening verified the DACL it wrote by comparing the SIDs `icacls /save` reports. SDDL substitutes two-letter aliases for well-known SIDs, and the resolution table could only hold constants -- but `LA` and `LG` name an account by RID inside the *machine's own* SID, so on a box whose user is the built-in Administrator (a CI runner, an Administrator-only install) the current user read back as `LA`, matched nothing, and hardening reported failure for every path. Resolve those two against the machine authority derived from the user SID; without one they stay unresolved and the comparison still fails closed. Three secret stores treated any read failure as "malformed -- regenerate" and overwrote. A hardened file granting a SID this process does not hold reads as EPERM while its directory stays writable, so the overwrite succeeds: renaming over an unreadable file needs FILE_DELETE_CHILD on the parent, not DELETE on the file. That destroyed the E2EE secret key, every paired device's bearer token, and the plugin vault. Distinguish EPERM/EACCES from a parse failure and refuse. Also close the async lane's unhandled rejection: `void p.then(onSettled)` turned a throw from `onSettled` into a dead main process, and the retry budget it calls threw whenever nothing had configured it -- a contract held only by import order. The budget now defaults its own bounds. * test(windows): say which ACEs icacls listed when a planted DACL fails `toHaveLength` reports only a count and vitest elides the array, so three preconditions failing on the CI runner said "expected 3, got 6" and nothing about what the sixth entry was. Name the entries in the failure. * fix(security): stop three more stores overwriting what they were denied Same swallow-default-overwrite shape as the readers already fixed, found by sweeping every store that reads under a hardened root. - plugin-storage-store.ts returned `{}` on any read failure and set()/delete() wrote it back, losing the plugin KV store. It is the secrets store's shape line for line, so the two now behave identically. - relay-revoke-outbox.ts returned [] and save() wrote it, dropping revocations that never reached the relay -- a revoked device stays live. - profile-cloud-session-store.ts mapped an EPERM read onto `decrypt-failed`, which fails the `status === 'found'` guard in clearCloudSessionIfUnchanged and falls through to an rmSync of the account session. A denied read now reports `unreadable`, which licenses nothing; the refresh path bails on it and the auth status surfaces it rather than reporting a bare reconnect. All reuse isPermissionDeniedError. The predicate stays an EPERM/EACCES allow list rather than "ENOENT defaults, everything else throws": these stores are meant to self-heal a truncated or malformed file, and inverting it would turn a corrupt keypair into an app that cannot start. The distinction that matters is "could not read it" versus "read it and it was garbage". * test(windows): plant fixture DACLs that cannot inherit what they did not plant %TEMP% grants [SYSTEM, Administrators, <user>] (OI)(CI)(F) by default, and those propagate into every fixture. Three preconditions read back 4 and 6 ACEs where 3 were planted, and the extras looked like Orca's own hardening because the shape is identical -- on a runner whose user is the built-in Administrator, the inherited trio IS the trio production grants. Combining /inheritance:r with /grant:r leaves the argument order to icacls, and that combined form drops the inherited ACEs on Windows 11 but keeps them as explicit ones on the Windows Server runner. Removing inheritance in its own invocation makes the grant the whole DACL on either host, and the fixture root is de-inherited once up front so nothing propagates in. Rooting the fixtures outside %TEMP% would not have fixed this: any directory inherits from wherever it lives. The fix is to stop inheriting, not to move. No assertion is relaxed -- the counts stay exact. * test(windows): pick a foreign SID that stays foreign on an elevated runner `S-1-5-32-544` is only foreign to a token that is not an administrator. The CI runner is elevated AND logged in as the built-in Administrator, so granting Administrators granted the reader full control: the file stayed readable, and all six preservation assertions went vacuous rather than proving anything. BUILTIN\Guests is resolvable everywhere and no interactive token is a member, so the read is denied on an unelevated developer box and on the runner alike. An unresolvable SID would have been the stronger choice but icacls rejects one with ERROR_NONE_MAPPED (1332). The premise guard is what caught this -- it asserted the file was actually unreadable instead of trusting the grant, and named elevation as the suspect. * fix(security): refuse on any read that never reached the contents, not just a denied one isPermissionDeniedError becomes isUnreadableError, because "permission denied" was never the concept -- "could not read it", as opposed to "read it and it was garbage", is. EBUSY, EMFILE, ENFILE and EIO say exactly as little about a file's contents as EACCES does, and they fell into the branch that regenerates and overwrites. On Windows EBUSY is the likelier of the two: antivirus holding a credential open at the moment of a startup read produces it, which makes it a commoner path to the same permanent loss than the ACL case that motivated the original fix. Still an allow list, deliberately: ENOENT keeps licensing a create, and a parse failure keeps self-healing. The stores are built to recover from a truncated write, and turning that into a refusal would trade a recoverable state for an unrecoverable one on the startup path. Also fixes the regression suite's own premise on an elevated runner: makeUnreadable combined /inheritance:r with /grant:r, and that form keeps %TEMP%'s inherited [SYSTEM, Administrators, user] as explicit ACEs on Windows Server -- so the file stayed readable and all six assertions were vacuous. Same split-the-invocation fix as the ACL suite's planter. * test(windows): skip the preservation suite where a read cannot be denied An elevated token logged in as the built-in Administrator reads straight through a DACL that grants it nothing -- confirmed on the CI runner against both BUILTIN\Administrators and BUILTIN\Guests, and with the grant split into its own icacls invocation so the DACL really was the planted one. On such a host the premise these tests rest on does not hold, and every assertion would pass while proving nothing. So probe once at module scope and skip rather than assert vacuously -- the same trade the ACL suite already makes for its unelevated-only case. The gate stays in the compound `<win32 check> && <flag>` form the win32 lane ratchet detects, so the file stays registered in both lane lists. Coverage is not lost where it counts: isUnreadableError has unit tests that run on every platform and every host, and the stores' refusal is exercised in full on any machine where a denial is reproducible -- which is every developer box. --------- Co-authored-by: Orca Worker <orca-worker@localhost> Co-authored-by: Neil <[email protected]>
…took (stablyai#19009) stablyai#17861 and stablyai#17884 each migrated one file off node:child_process and each lowered the pin 158 -> 157 independently. Together they took two, so the true count is 156 and the two-sided assertion fails on main. Co-authored-by: Orca Worker <orca-worker@localhost>

Impact: the Windows path-hardening ACL has never applied
bestEffortRestrictWindowsPath/restrictWindowsPathSyncare the only enforcement mechanism Orca has on Windows —mkdirSync({mode: 0o700})andwriteFileSync({mode: 0o600})are no-ops there, assecure-file.tsitself notes. POSIX gets a realchmod. Windows has been getting nothing since the ACL was introduced in #5006 (8f40ddf328, later reverted/re-landed viaaab112933e/879aad7dd6).Confirmed on a live install:
Severity: Medium
This is not "world-readable" on a default install. On a stock single-user box the inherited
%APPDATA%ACL is{current user, SYSTEM, BUILTIN\Administrators}— byte-for-byte the principal set the script would have granted. The correct framing is a live security-hardening gap: the control that is supposed to guarantee that set has never run, so nothing has been enforcing it and nothing would have detected it being loosened.Not remotely exploitable. No elevation to SYSTEM or Administrator — but cross-user lateral movement is possible on a relocated root, because
orca-runtime.jsonholds the local RPCauthToken. A second local account that reads it acts as the victim user inside Orca. All exposure cases need a second local principal or a non-default data root:ORCA_USER_DATA_PATH(src/cli/runtime/metadata.ts,src/main/codex/codex-home-paths.ts) — the unambiguous one.C:\grantsBUILTIN\Users:(OI)(CI)(RX), so a data root at e.g.C:\orca-datainherits read access for every local account, and — measured below —Authenticated Users:(M), i.e. write access.%APPDATA%— stripping inherited ACEs from a share-backed parent is exactly whatSetAccessRuleProtection($true, $false)exists for.What was left on inherited ACLs
Everything written through
writeSecureFile/hardenExistingSecureFile. Credential-grade:<userData>\orca-e2ee-keypair.jsonAuthenticated Users:(M), so on a relocated root this is writable, not merely readable. Write access to an identity key is key substitution: a local attacker replaces the keypair and MITMs the E2EE channel. That is a different and worse failure than disclosure.<userData>\orca-devices.jsonruntimescope grants CLI-level powers<userData>\orca-runtime.jsonauthTokenin plaintext — full local RPC control, and the lateral-movement path noted above<userData>\orca-environments.jsondeviceToken+ peer public keys (the codebase redacts these before they leave the process)<userData>\profiles\<id>\account-session.json.encdev-plaintext-v1cleartext when safeStorage is unavailable<userData>\plugins-data\<pub>.<id>\secrets.json.enc%USERPROFILE%\.orca\minimax-session-cookie.enc<userData>\orca-ephemeral-vm-runtimes.json<userData>\profiles\<id>\artifact-shares.jsoneditTokensThe safeStorage-encrypted entries are DPAPI user-scoped on Windows, so the ACL is the boundary separating them from another process running as the same user.
<userData>\profiles\<id>\artifact-create-intents\is the sharpest case: its child files are written with barewriteFileSync(mode: 0o600)and are only protected by inheritance from the once-hardened directory.Reproduction
-Commanddoes not populate$args. Worse, it appends the trailing tokens to the command text, where they execute as statements —AAAandBBBabove were run, not passed. Feeding the real script its real arguments:$ErrorActionPreference = 'Stop'turns that into exit 1 beforeSet-Aclis ever reached. The async caller's callback was empty;applySecurePathRestrictionreturnedtruefor the async path regardless of outcome; the synccatchreturnedfalseand logged nothing.Independent of the
-ExecutionPolicy Bypassflag that #17873 removes — it fails identically with or without it.Fix:
icacls.exeChosen:
icacls.exe. A plain executable taking plain argv, so there is no quoting layer at all — not an escaped one, an absent one. It also drops the execution-policy dependency, removes thepowershell.exespawn that EDR flags, and is far faster (5.7 ms vs 148 ms warm; the code comments cite a 1–1.5 s cold start, which caused the #4901 main-thread storm).Rejected — interpolating into the
-Commandtext. Because-Commandexecutes what it appends, populating the values in that spelling would have converted a dead no-op into arbitrary PowerShell execution on a filesystem path. Strictly worse than the bug being fixed, in a security control, on attacker-influenceable input.Rejected —
-Filewith a real.ps1. Populates$args, but reintroduces the execution-policy dependency the sibling work is removing.Rejected — env vars +
$env:. Genuinely sound, but keeps the PowerShell spawn and its cost for no benefit overicacls. The right answer ificaclsever proves insufficient.Two measured
icaclsfindings drove the design:/inheritance:rdoes not remove explicit ACEs. A plantedEveryone:(R)survives the grant pass, so hardening leads with/reset. The two cannot be combined in one invocation./cmakesicaclsexit 0 while printing "Failed processing 1 files" — the same silent-no-op failure mode by another route. It is never passed, and a test asserts it never appears in either runner's argv.Long paths use the
\\?\prefix past MAX_PATH.Review round 2 — three blocking fixes
The verify pass checked shape, not identity
The first version of this PR verified rule count, absence of the
(I)inherited marker, and exact rights — but never who the rules named. A reviewer mutated the granted SID list toS-1-1-0and ran the real path:restrictWindowsPathSyncreturnedtruewithEveryone:(F)on the credential file, and 11 of 13 real-filesystem tests still passed. The bug class this PR exists to fix, alive inside the fix.Verification now reads the descriptor back with
icacls <path> /save, which emits SDDL carrying raw SIDs:Pgives protection,FAgives rights, and the SIDs give identity, compared as an exact set. That is also locale-independent by construction rather than by luck: the previous parse read localized account names out of icacls' OEM-codepage stdout, where a non-ASCII path survived vialastIndexOf(':(')rather than the mechanism its comment claimed. SDDL parsing lives inwindows-security-descriptor.tswith its own unit tests.The post-rename re-harden re-widened an already-correct DACL
/resetran unconditionally, including on the pass afterrenameSync— where the staged file's protected DACL has already survived the rename, so the pass had nothing to do but open a window. Measured by polling from an external process during writes into a relocated root, before the fix:Windows checks access at open, so a handle acquired in that window survives the tightening. Hardening now verifies first and returns early when the DACL already reads back correct. Same harness, after:
This also cuts the steady state from three spawns to one.
Eviction-on-failure reintroduced #4901 — and the first fix for it latched
Dropping the cache entry on every failed async apply meant the env store's read-path re-harden — ~2/s — would respawn icacls and re-log on every read, forever, on any host where hardening legitimately cannot work (FAT32/exFAT have no ACLs; network paths, redirected profiles and restricted tokens refuse).
The first fix was a retry floor plus a per-process attempt cap, and review caught that this is its own defect: a permanent latch on a transient failure. One AV scan, momentary lock or
%TEMP%blip, and every later credential write in that session is unhardened — silently, on a host where hardening would now succeed. Same class as #17858's computer-use host permanently reverting to its degraded path.The budget now bounds the rate, not the lifetime: at most three attempts per path per minute, re-probing in every later window, forever. Both directions of the transition are announced —
throttledonce per window on entry,recoveredwhen a rate-limited path hardens again — so a host stuck in the degraded state is diagnosable rather than merely quiet. Lives insecure-path-hardening-retry-budget.ts.The write path deliberately keeps retrying unthrottled: it is user-driven rather than polled, and a failed credential ACL must still be retried on the next write.
The short-circuit made a latent under-check load-bearing
Verification tested that
OIwas present on a directory's rules — never thatCIwas, nor that nothing else was. That cost nothing while/reset+/grantran on every pass and repaired whatever was there. Verify-first made it load-bearing: whatever validation accepts is now left alone, so a latent weakness went live because a different fix started depending on it. Worth stating plainly, because it is the general hazard in adding a short-circuit to a security control.Two directory DACLs passed while being wrong — each protected, three non-inherited full-control rules, correct SIDs, differing from correct only in flags:
(OI)(F)CI: subdirectories are left unprotected(OI)(CI)(IO)writeFileSyncinto it fails with EPERM, on a directoryhardenSecurePathOncehad just cached as hardenedVerification now compares the whole flag set, which also rejects
IOandNP, and names the offending flags. Both shapes are planted in real-filesystem regression tests, one of which asserts a write into the repaired directory succeeds and its child inherits. Both were confirmed to fail against the old check and pass against the new one.Also addressed
console.warnis invisible in a packaged build — the main process is GUI-subsystem and owns no console, andsrc/main/observability/collects only the NDJSON trace sink and the daemon log. Failures now go through a reporter hook thatinitObservabilitypoints at the tracer, so a failed credential ACL lands in the diagnostic bundle. Console stays as the dev/CLI default.writeSecureFile(and the JSON wrappers) return whether hardening took, and the staged-file result is no longer discarded.applySecurePathRestrictionreturnsapplied | pending | failed— the async branch reportspendingrather than claimingapplied, which is the shape of the original bug.getCurrentWindowsUserSidno longer caches a failure for the process lifetime (one transientwhoamihiccup disabled hardening until restart); failures expire, and the SID is shape-validated./cguard now coversrunProcessSyncas well asrunProcess.Hardening remains non-fatal. No caller was made fatal;
writeSecureFilewriting the e2ee keypair is where that would be defensible, but it is a startup-risk decision and belongs in its own change.Evidence: before/after on a relocated data root
BEFORE — inherited from
C:\:Running the shipped code path — the no-op:
Unchanged.
restrictWindowsPathSyncreturnedfalse; nothing was logged.AFTER the fix:
No
(I)on any ACE — the DACL is protected.BUILTIN\UsersandAuthenticated Usersare gone. A file created afterwards inherits the hardened directory ACL:Tests
src/shared/secure-path-windows-acl.win32.test.tsruns against a real filesystem — the regression test that would have caught the original bug, because it asserts on the resulting ACL, not the constructed argv. A mocked-argv test passed happily throughout.Covered: a real file (plants an explicit
Everyone:(R)first and asserts it is purged with all inherited ACEs); a real directory including a child created afterwards; a protected three-rule DACL that grants Everyone — the shape-only-valid case that defeated the first verifier, asserted to be repaired; idempotence; a hostile-path corpus (spaces,',$, backtick,[],;/&,,,(),^/%); a path past MAX_PATH; a non-existent path; and a path the process cannot modify. Two wrong-flags directory DACLs —(OI)without(CI), and(OI)(CI)(IO)— planted and asserted repaired, the second including a real write into the repaired directory. An unwritable%TEMP%is exercised for real, asserting verification fails closed and reports while the ACL itself still lands.Unit tests cover the SDDL parser directly (alias resolution, two-letter flag tokenization so
OICIIDis not read as containing a stray token, SACL truncation, an owner alias ending inD, malformed input), the verifier rejecting each way a DACL can be wrong (Everyone, deny rule, unprotected, surviving inherited rule, read-only rights), the verify-first short-circuit, the retry budget (throttling under a read-path poll, re-probing in every later window rather than giving up, and therecoveredreport), and the/cguard across both runners.Results
tsc --noEmit× 3 projectsoxlint(changed files)src/shared/secure-*,src/shared/windows-security-descriptor*,src/shared/child-process/,src/main/artifacts,src/main/observabilityPre-existing failures, unrelated to this change and independently confirmed on
main:src/shared/agent-hook-listener-relay-dependency.test.ts(1) andsrc/main/persistence/loading-store/(7).One failure shape, three mechanisms
Everything fixed on this PR is the same bug wearing different clothes: hardening silently does nothing, and the thing that should have noticed agrees it is fine.
powershell.exe -Commanddoes not populate$args, so the ACL script ran with no target and hardened nothing. Argv-asserting tests passed.node:child_processwithexecFileSync/execFile; the rewritten path callsrunProcessSync(spawnSync), which the factory never returned. Every spawn threw into the SID lookup's barecatch,planForreturnednull, hardening no-opped, and the test reported a plain length mismatch.windowsSystem32Binarybuilt a Windows path with the hostjoin, so off-platform it producedC:\Windows/System32/whoami.exe. On Linux the whoami match missed, the SID lookup failed, and 27 ofsecure-file.test.ts's 32 tests exercised a lane that never ran. Identical on Windows, which is why it survived.Three different mechanisms, all invisible until something actually executed, all landing on
planForreturningnull— the one place a failure turns into a silent skip. Anyone touching this module should assume a green ACL test proves nothing unless it can show the spawn happened.Risks for a reviewer
%TEMP%, random name, unlinked infinally). It holds SIDs, no secrets. An unwritable%TEMP%is now covered by a real-filesystem test: verification fails closed, reports at theverifystage, and the assertion confirms the ACL was still applied — so that path loses proof, not protection. It no longer combines into a permanent-off state, because the lifetime cap is gone./resetstill runs when a DACL is not already correct, briefly restoring the inherited ACL. That path is only taken when the DACL was wrong anyway; the already-correct case, which is the common one, no longer touches it at all.throttledreport per window. That is deliberate: the alternative latches transient failures. On a genuinely incapable host (FAT32) this is a standing low-rate cost, traded for never silently abandoning hardening on a host that recovers.initObservabilitynow installs the reporter, a new edge fromsrc/main/observability/intosrc/shared/. The lane-isolation rule it must respect is telemetry↔observability, which is untouched; the architecture test passes.child-process-import-allowlist.txt) is a ratchet improvement; this module now inheritsrunProcess's spawn policy.icacls /savethat passesvalidateHardenedDacl. On POSIX it still can:applySecurePathRestrictionreturnsappliedunconditionally afterchmodSyncwith no read-back (secure-file.ts), so the guarantee there is "chmod did not throw", not "the mode is 0600". Recorded, not fixed.