refactor(sandbox): derive the private temp dir; drop the acl-session record

The durable sandbox/acl-session event carried a workspace binding that
always equals the session cwd and a random temp path that only needed
to be stable per session. Both are now derived: the temp subdirectory
is sha256(session id + workspace), created exclusively and removed on
provider dispose, so fork/resume semantics fall out of the derivation
and the record, its fold/provision/tamper validation, the immediate
flush kick, and the session-store dependency all disappear.
This commit is contained in:
Huanqi Cao
2026-08-10 01:03:29 +08:00
parent a29966b71f
commit 976020f2bb
12 changed files with 257 additions and 487 deletions
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-08-08-windows-acl-restricted-token-sandbox.md
2026-08-08-windows-acl-restricted-token-sandbox.md: d6915cadb5817679749474c1046d1c715adc2b9b
2026-08-08-windows-acl-restricted-token-sandbox.zh.md: 1533e39bf5c239730b6e027e5f0b345d4c6c42e4
2026-08-08-windows-acl-restricted-token-sandbox.md: 7e8f229269233d9ac9baa65241ca02a4cf4c3f7c
2026-08-08-windows-acl-restricted-token-sandbox.zh.md: eeb346b228b3559f487448e5d4ec525b7bb89525
@@ -10,7 +10,7 @@ The [sandbox decision](2026-07-06-sandbox.md) leaves `PLATFORM_CHAINS.win32` emp
## Decision
Implement the rung directly on the raw ACL mechanism: duplicate the caller's token into a `WRITE_RESTRICTED` token (`CreateRestrictedToken` with `WRITE_RESTRICTED` + `DISABLE_MAX_PRIVILEGE` + `LUA_TOKEN`) whose restricting SIDs include a write SID (`S-1-4-x-y`); the write SID's Write ACEs on the workspace and temp roots are the entire write allowlist, because `WRITE_RESTRICTED` intersects write accesses only and reads keep the caller's full ambient access. The mechanism is the one huoyaoyuan/windows-acl-restrict-poc (`10e4dfb`) demonstrates; this port checks every API call and fails closed (the POC fail-opened on every ignored return value). The write SID is the PER-WORKSPACE identity, derived deterministically from the canonical workspace path (`workspaceWriteSid` — sha256 → `S-1-4-x-y`) and stored NOWHERE: the workspace-root ACE therefore materializes once per workspace per machine — the standing ACE is the cross-session reuse cache, and every later provision hits the exact-ACE skip (idempotent re-grant skips the eager full-tree re-propagation — no garbage collection) — instead of once per session, which is what the earlier per-session random SID paid a full tree propagation per session for. The seam still provisions one log-only `sandbox/acl-session` event per session (fork mints a fresh one; resume replays the same one) carrying the session's workspace binding and PRIVATE temp subdirectory — no SID, so the record's old SID-tamper surface does not exist; a fresh provision kicks an immediate persistence flush right after the append (no write-behind debounce), so the record is durable within the flush latency — a crash inside that window can strand the private temp directory unrecorded, the one documented self-healing gap. The seam materializes the workspace ACE STANDING (never revoked — the cache) and the temp ACE REVOCABLY (revoked on provider dispose, so an inheritable ACE never outlives its session's temp directory on the ambient temp root); the record is BOUND to its owning session id and validated at the fold (workspace/temp shape): a fork's copied parent record never provisions the child, and a tampered record fails loud instead of materializing grants. The token's restricting list is the keep-alive group plus the write SID only under workspace-write: read-only = [logon SID, Everyone] and workspace-write = [logon SID, Everyone, write SID]. The keep-alive invariants are logon SID + Everyone (early DLL init dies with 0xC0000142 and CNG crashes pwsh with 0xE0434352 without them). Read-only carries no write SID: a standing grant ACE from an earlier workspace-write period stays INERT (the pass-2 check grants only what the list carries, so read-only remains strictly zero-grant across a `/permission` downgrade or a crash-resumed session, while the standing ACE keeps the re-upgrade free). Authenticated Users is absent from BOTH lists — the WMI namespace security check fails (0x80041003), so CIM is unavailable in every confined mode, and the C:\-root tree-creation escape (standing `AU:(AD)` + `AU:(OI)(CI)(IO)(M)` ACEs) is closed in both; INTERACTIVE/LOCAL are likewise absent from both (the Public tree writes are denied — pinned by the runner's Public-probe regression). Workspace-write children see a PRIVATE per-session temp subdirectory (`<temp>\dsh-<16 random hex>` — unguessable, created exclusively, reparse points rejected — TMP/TEMP rewritten by the runner — bwrap `--tmpfs /tmp` semantics). The restricted token's DEFAULT DACL is extended with a full-access write-SID ACE (`SetTokenInformation(TokenDefaultDacl)`): new objects created without an explicit security descriptor (anonymous pipes — CreatePipe, sync objects) then carry a restricting-SID ACE and pass the write pass-2 check at creation; NAMED pipes are exempt — their default security descriptor is the kernel's PUBLIC template (owner/SYSTEM/Admins full, Everyone read-only), which the token cannot influence, so piped stdio capture stays denied for confined grandchildren (the POC-documented boundary, pinned by the runner suite). It ships as [`@deepseek-ai/dsh-sandbox-windows-acl`](../../../../packages/sandbox/sandbox-windows-acl/README.md) (backend plus the `./runner` argv-prefix entry), the `win32` chain rung of [`dsh-sandbox-local`](../../../../packages/sandbox/sandbox-local/README.md), and [`@deepseek-ai/dsh-pwsh-sandbox`](../../../../packages/bash/pwsh-sandbox/README.md) as the confining executor; the Windows platform layer re-enables the full permission surface (sandbox/sandbox-policy/permission/approval/fs-sandbox) over the confined pwsh stack.
Implement the rung directly on the raw ACL mechanism: duplicate the caller's token into a `WRITE_RESTRICTED` token (`CreateRestrictedToken` with `WRITE_RESTRICTED` + `DISABLE_MAX_PRIVILEGE` + `LUA_TOKEN`) whose restricting SIDs include a write SID (`S-1-4-x-y`); the write SID's Write ACEs on the workspace and temp roots are the entire write allowlist, because `WRITE_RESTRICTED` intersects write accesses only and reads keep the caller's full ambient access. The mechanism is the one huoyaoyuan/windows-acl-restrict-poc (`10e4dfb`) demonstrates; this port checks every API call and fails closed (the POC fail-opened on every ignored return value). The write SID is the PER-WORKSPACE identity, derived deterministically from the canonical workspace path (`workspaceWriteSid` — sha256 → `S-1-4-x-y`) and stored NOWHERE: the workspace-root ACE therefore materializes once per workspace per machine — the standing ACE is the cross-session reuse cache, and every later provision hits the exact-ACE skip (idempotent re-grant skips the eager full-tree re-propagation — no garbage collection) — instead of once per session, which is what the earlier per-session random SID paid a full tree propagation per session for. The seam derives the session's PRIVATE temp subdirectory from the session id + workspace (sha256, 16 hex — stored nowhere, so no tamper surface exists) and creates it exclusively; it is removed on provider dispose, and a crash leaves it as `%TEMP%` litter whose next resume fails loudly at the exclusive creation until temp hygiene reclaims it. The seam materializes the workspace ACE STANDING (never revoked — the cache) and the temp ACE REVOCABLY (revoked on provider dispose, so an inheritable ACE never outlives its session's temp directory on the ambient temp root). The token's restricting list is the keep-alive group plus the write SID only under workspace-write: read-only = [logon SID, Everyone] and workspace-write = [logon SID, Everyone, write SID]. The keep-alive invariants are logon SID + Everyone (early DLL init dies with 0xC0000142 and CNG crashes pwsh with 0xE0434352 without them). Read-only carries no write SID: a standing grant ACE from an earlier workspace-write period stays INERT (the pass-2 check grants only what the list carries, so read-only remains strictly zero-grant across a `/permission` downgrade or a crash-resumed session, while the standing ACE keeps the re-upgrade free). Authenticated Users is absent from BOTH lists — the WMI namespace security check fails (0x80041003), so CIM is unavailable in every confined mode, and the C:\-root tree-creation escape (standing `AU:(AD)` + `AU:(OI)(CI)(IO)(M)` ACEs) is closed in both; INTERACTIVE/LOCAL are likewise absent from both (the Public tree writes are denied — pinned by the runner's Public-probe regression). Workspace-write children see a PRIVATE per-session temp subdirectory (`<temp>\dsh-<16 hex>` derived from the session id + workspace — created exclusively, reparse points rejected, removed on provider dispose — TMP/TEMP rewritten by the runner — bwrap `--tmpfs /tmp` semantics). The restricted token's DEFAULT DACL is extended with a full-access write-SID ACE (`SetTokenInformation(TokenDefaultDacl)`): new objects created without an explicit security descriptor (anonymous pipes — CreatePipe, sync objects) then carry a restricting-SID ACE and pass the write pass-2 check at creation; NAMED pipes are exempt — their default security descriptor is the Win32 layer's user-mode default SD template (built by KernelBase — owner/SYSTEM/Admins full, Everyone/ANONYMOUS read-only), which the token cannot influence, so piped stdio capture stays denied for confined grandchildren (the POC-documented boundary, pinned by the runner suite). It ships as [`@deepseek-ai/dsh-sandbox-windows-acl`](../../../../packages/sandbox/sandbox-windows-acl/README.md) (backend plus the `./runner` argv-prefix entry), the `win32` chain rung of [`dsh-sandbox-local`](../../../../packages/sandbox/sandbox-local/README.md), and [`@deepseek-ai/dsh-pwsh-sandbox`](../../../../packages/bash/pwsh-sandbox/README.md) as the confining executor; the Windows platform layer re-enables the full permission surface (sandbox/sandbox-policy/permission/approval/fs-sandbox) over the confined pwsh stack.
## How the restriction works (why no new identity)
@@ -32,11 +32,11 @@ The [landstrip evaluation](../../rejected/feature/2026-07-26-evaluate-landstrip-
## Consequences
Bought: write-only confinement with no new OS floor (`CreateRestrictedToken` predates the mxc releases by two decades), reads/network/process visibility untouched exactly as the mode vocabulary requires, and fail-closed errors carrying the API name and the exact Win32 code. Cost: no read-side or network isolation; console isolation unavailable (hidden-console children die with `STATUS_DLL_INIT_FAILED`; children share the host console); standing ACE mutations on the granted roots (caller-owned directories; workspace ACEs stand forever by design — the reuse cache, invisible residue when a workspace is renamed — temp ACEs revoked by provider dispose, self-healing across restarts via the durable per-session recordwhose immediate flush precedes the ACEs, within the flush latency); grant materialization is an EAGER full-tree propagation (`SetNamedSecurityInfoW` walks every descendant immediately — tens of seconds on large workspaces), paid once per workspace per machine by the per-workspace identity; CIM is unavailable in BOTH confined modes (AuthUsers dropped from both lists — the WMI namespace security check fails, and `Get-ComputerInfo` silently returns incomplete results) as the price of closing the C:\-root tree-creation escape in both; FAT-class (non-ACL) targets outside the granted roots remain writable under both modes (no security descriptors to intersect — a legacy residue treated as unsupported, warn-only, documented in the README); NULL-DACL directories are not identity-preserving under a grant+revoke round-trip (documented edge, the POC shares it); `whoami` and token-inspection cmdlets fail under the restricted token (diagnostic noise, documented); and BOTH confined modes run `pwsh` in ConstrainedLanguage mode — the restricted token trips PowerShell's lockdown detection, so `Add-Type`, non-core .NET statics (`[System.IO.*]::`, `[math]::`), COM objects, and reflection fail with "only core types" errors while `-f` formatting, property access, and core cmdlets/types keep working, and the language mode cannot be lifted back to FullLanguage from inside — taught to the model in the pwsh tool description and documented in the package README's Known Limitations; BOTH confined modes also deny named-pipe opens — libuv's piped-stdio spawns fail with EPERM (the POC-documented "no output redirection" boundary; inherited/ignored stdio and anonymous pipes work) — documented in the package README's Known Limitations and taught to the model in the pwsh tool description.
Bought: write-only confinement with no new OS floor (`CreateRestrictedToken` predates the mxc releases by two decades), reads/network/process visibility untouched exactly as the mode vocabulary requires, and fail-closed errors carrying the API name and the exact Win32 code. Cost: no read-side or network isolation; console isolation unavailable (hidden-console children die with `STATUS_DLL_INIT_FAILED`; children share the host console); standing ACE mutations on the granted roots (caller-owned directories; workspace ACEs stand forever by design — the reuse cache, invisible residue when a workspace is renamed — temp ACEs revoked by provider dispose together with the derived private temp directorya crash leaves both behind and the next resume fails loudly at the exclusive creation until temp hygiene reclaims the directory); grant materialization is an EAGER full-tree propagation (`SetNamedSecurityInfoW` walks every descendant immediately — tens of seconds on large workspaces), paid once per workspace per machine by the per-workspace identity; CIM is unavailable in BOTH confined modes (AuthUsers dropped from both lists — the WMI namespace security check fails, and `Get-ComputerInfo` silently returns incomplete results) as the price of closing the C:\-root tree-creation escape in both; FAT-class (non-ACL) targets outside the granted roots remain writable under both modes (no security descriptors to intersect — a legacy residue treated as unsupported, warn-only, documented in the README); NULL-DACL directories are not identity-preserving under a grant+revoke round-trip (documented edge, the POC shares it); `whoami` and token-inspection cmdlets fail under the restricted token (diagnostic noise, documented); and BOTH confined modes run `pwsh` in ConstrainedLanguage mode — the restricted token trips PowerShell's lockdown detection, so `Add-Type`, non-core .NET statics (`[System.IO.*]::`, `[math]::`), COM objects, and reflection fail with "only core types" errors while `-f` formatting, property access, and core cmdlets/types keep working, and the language mode cannot be lifted back to FullLanguage from inside — taught to the model in the pwsh tool description and documented in the package README's Known Limitations; BOTH confined modes also deny named-pipe opens — libuv's piped-stdio spawns fail with EPERM (the POC-documented "no output redirection" boundary; inherited/ignored stdio and anonymous pipes work) — documented in the package README's Known Limitations and taught to the model in the pwsh tool description.
## Testing
The product-visible Windows roster flip is win32-only, so the keyless snapshot fixtures — which must replay on macOS/Linux — cannot cover it; the bundle composition specs ([`base.spec.ts`](../../../../packages/bundle/base/tests/base.spec.ts), [`windows-shell.spec.ts`](../../../../apps/cli/tests/windows-shell.spec.ts)) plus the win32 real-runner suites (`packages/sandbox/sandbox-windows-acl/tests/`, `packages/bash/pwsh-sandbox/tests/`) are the substitute evidence, and the CI Windows lane owns the assembled signal. The grant machinery is pinned cross-platform by `packages/sandbox/sandbox-local/tests/acl-session.spec.ts` (record fold/provision with the ownership binding — a fork's copied parent record never provisions the child — tamper validation on the workspace/temp paths, one-shot materialization with the immediate-flush kick, exclusive temp creation with reparse-point rejection, fork/resume temp reuse, the standing-vs-revocable lifecycle across dispose and the mode-switch cycle, and the derived-SID argv contract — with the Win32 surface mocked) and on win32 by `workspace-sid.spec.ts` (derivation determinism/shape/distinctness), `grant.spec.ts` (real-DACL materialization: revocable paths revoke on dispose, standing paths survive it), the `acl.spec.ts` idempotent-grant fast-path and standing-ACE-after-dispose contract, the `failure-paths.spec.ts` suspension-orphan regression (AssignProcessToJobObject failure terminates the child), and the `runner.spec.ts` `--write-sid` contract (caller-owned grants, private temp subdir through TMP/TEMP, both-mode CIM-denial probes, the mode-downgrade regression — a standing grant ACE is inert under read-only and effective again on re-upgrade — the ambient-writable Public-probe regression (a C:\Users\Public subdirectory write is denied under both modes), and the ConstrainedLanguage pins in both modes, plus the grandchild-stdio matrix pins — inherited/ignored stdio spawns succeed while piped capture is DENIED in both modes). The runner-failure classification is exit-gated on 127 (a confined command that merely prints the `windows-acl-run:` signature on a non-127 exit is never misclassified as "the command did not run" — pinned in the pwsh-sandbox helper suite).
The product-visible Windows roster flip is win32-only, so the keyless snapshot fixtures — which must replay on macOS/Linux — cannot cover it; the bundle composition specs ([`base.spec.ts`](../../../../packages/bundle/base/tests/base.spec.ts), [`windows-shell.spec.ts`](../../../../apps/cli/tests/windows-shell.spec.ts)) plus the win32 real-runner suites (`packages/sandbox/sandbox-windows-acl/tests/`, `packages/bash/pwsh-sandbox/tests/`) are the substitute evidence, and the CI Windows lane owns the assembled signal. The grant machinery is pinned cross-platform by `packages/sandbox/sandbox-local/tests/acl-grants.spec.ts` (the derived private-temp identity — deterministic per session + workspace, distinct across sessions — one-shot materialization, exclusive temp creation with reparse-point rejection and self-cleanup on failure, clean-restart re-grant of the same derived directory, the standing-vs-revocable lifecycle across dispose and the mode-switch cycle, and the derived-SID argv contract — with the Win32 surface mocked) and on win32 by `workspace-sid.spec.ts` (derivation determinism/shape/distinctness), `grant.spec.ts` (real-DACL materialization: revocable paths revoke on dispose, standing paths survive it), the `acl.spec.ts` idempotent-grant fast-path and standing-ACE-after-dispose contract, the `failure-paths.spec.ts` suspension-orphan regression (AssignProcessToJobObject failure terminates the child), and the `runner.spec.ts` `--write-sid` contract (caller-owned grants, private temp subdir through TMP/TEMP, both-mode CIM-denial probes, the mode-downgrade regression — a standing grant ACE is inert under read-only and effective again on re-upgrade — the ambient-writable Public-probe regression (a C:\Users\Public subdirectory write is denied under both modes), and the ConstrainedLanguage pins in both modes, plus the grandchild-stdio matrix pins — inherited/ignored stdio spawns succeed while piped capture is DENIED in both modes). The runner-failure classification is exit-gated on 127 (a confined command that merely prints the `windows-acl-run:` signature on a non-127 exit is never misclassified as "the command did not run" — pinned in the pwsh-sandbox helper suite).
## Related
@@ -10,7 +10,7 @@ Status: implemented
## Decision
直接基于原始 ACL 机制实现该档:把调用者令牌复制为 `WRITE_RESTRICTED` 受限令牌(`CreateRestrictedToken``WRITE_RESTRICTED` + `DISABLE_MAX_PRIVILEGE` + `LUA_TOKEN`),其 restricting SIDs 中包含写入 SID`S-1-4-x-y`);工作区与临时目录上写入 SID 的 Write ACE 就是全部写入白名单,因为 `WRITE_RESTRICTED` 只对写访问做交集检查,读保持调用者的完整环境访问。该机制来自 huoyaoyuan/windows-acl-restrict-poc`10e4dfb`)的演示;本移植检查每一个 API 调用并 fail-closedPOC 因忽略返回值而 fail-open)。写入 SID 是**按工作区**的身份,由规范工作区路径确定性派生(`workspaceWriteSid`——sha256 → `S-1-4-x-y`),且**任何地方都不存储**:工作区根目录 ACE 因此每台机器每个工作区只物化一次——常驻 ACE 就是跨会话复用缓存,此后每次供给都命中精确 ACE 跳过(幂等重授权跳过急切的全树重传播——不做垃圾回收)——而不是每会话一次,这正是先前每会话随机 SID 每个会话都要付一次全树传播的代价。seam 仍为每个会话供给一条 log-only 的 `sandbox/acl-session` 事件(fork 铸出新记录;恢复回放同一条),携带会话的工作区绑定与**私有**临时子目录——不含 SID,因此记录原先的 SID 篡改面已不存在;新供给在追加之后立即触发一次即时持久化 flush(无 write-behind 去抖),因此记录在 flush 延迟内即持久化——在该窗口内崩溃可能遗留未记录的私有临时目录,这是唯一记录在案的自愈缺口。seam 把工作区 ACE **常驻**物化(绝不撤销——就是缓存),把临时 ACE **可回收**物化(提供方 dispose(资源释放)时撤销,因此可继承 ACE 不会在环境临时根目录上比其会话的临时目录活得更久);记录被**绑定**到其所属会话 id 并在 fold 处校验(工作区/临时路径形态):fork 复制的父记录绝不会为子会话供给记录,被篡改的记录会响亮失败而非物化授权。令牌的 restricting list 是保活组加上仅 workspace-write 下的写入 SIDread-only = [登录 SID、Everyone]workspace-write = [登录 SID、Everyone、写入 SID]。保活不变式是登录 SID + Everyone(没有它们,早期 DLL init 会以 0xC0000142 死亡,CNG 会让 pwsh 以 0xE0434352 崩溃)。Read-only 不含写入 SID:先前 workspace-write 时期留下的常驻授权 ACE 保持**失效**(pass-2 检查只授予列表所携带的内容,因此 read-only 在 `/permission` 降级或崩溃后恢复的会话中始终保持严格零授权,而常驻 ACE 让重新升级保持零成本)。Authenticated Users 在**两种**列表中都缺席——WMI namespace 安全校验失败(0x80041003),因此 CIM 在每一种受限模式下都不可用,且 C:\-root 建树逃逸(驻留的 `AU:(AD)` + `AU:(OI)(CI)(IO)(M)` ACE)在两种模式下都被关闭;INTERACTIVE/LOCAL 同样在两种列表中都缺席(Public 树的写入被拒绝——由 runner 的 Public-probe 回归钉住)。Workspace-write 子进程看到的是私有的每会话临时子目录(`<temp>\dsh-<16 random hex>`——不可猜测、独占创建、拒绝 reparse point——TMP/TEMP 由 runner 重写——bwrap `--tmpfs /tmp` 语义)。受限令牌的**默认 DACL** 被扩展一条写入 SID 全权 ACE(`SetTokenInformation(TokenDefaultDacl)`):此后不带显式安全描述符创建的新对象(匿名管道——CreatePipe、同步对象)自带 restricting SID ACE,创建时的写 pass-2 检查通过;**named pipe 例外**——其默认安全描述符是内核的**公共模板**owner/SYSTEM/Admins 全权、Everyone 只读),令牌无法影响,因此受限孙进程的管道 stdio 捕获保持拒绝(POC 记载的边界,由 runner 套件钉住)。它以 [`@deepseek-ai/dsh-sandbox-windows-acl`](../../../../packages/sandbox/sandbox-windows-acl/README.md)(后端加 `./runner` argv 前缀入口)、[`dsh-sandbox-local`](../../../../packages/sandbox/sandbox-local/README.md) 的 `win32` 链档、以及作为隔离执行器的 [`@deepseek-ai/dsh-pwsh-sandbox`](../../../../packages/bash/pwsh-sandbox/README.md) 交付;Windows 平台层在受限 pwsh 栈之上重新启用完整权限面(sandbox/sandbox-policy/permission/approval/fs-sandbox)。
直接基于原始 ACL 机制实现该档:把调用者令牌复制为 `WRITE_RESTRICTED` 受限令牌(`CreateRestrictedToken``WRITE_RESTRICTED` + `DISABLE_MAX_PRIVILEGE` + `LUA_TOKEN`),其 restricting SIDs 中包含写入 SID`S-1-4-x-y`);工作区与临时目录上写入 SID 的 Write ACE 就是全部写入白名单,因为 `WRITE_RESTRICTED` 只对写访问做交集检查,读保持调用者的完整环境访问。该机制来自 huoyaoyuan/windows-acl-restrict-poc`10e4dfb`)的演示;本移植检查每一个 API 调用并 fail-closedPOC 因忽略返回值而 fail-open)。写入 SID 是**按工作区**的身份,由规范工作区路径确定性派生(`workspaceWriteSid`——sha256 → `S-1-4-x-y`),且**任何地方都不存储**:工作区根目录 ACE 因此每台机器每个工作区只物化一次——常驻 ACE 就是跨会话复用缓存,此后每次供给都命中精确 ACE 跳过(幂等重授权跳过急切的全树重传播——不做垃圾回收)——而不是每会话一次,这正是先前每会话随机 SID 每个会话都要付一次全树传播的代价。seam 从会话 id + 工作区派生会话的**私有**临时子目录(sha256、16 位 hex——任何地方都不存储,因此不存在篡改面)并独占创建;它在提供方 dispose 时移除,崩溃则把它留作 `%TEMP%` 垃圾,其下一次恢复会在独占创建处大声失败,直到临时目录卫生机制将其回收。seam 把工作区 ACE **常驻**物化(绝不撤销——就是缓存),把临时 ACE **可回收**物化(提供方 dispose(资源释放)时撤销,因此可继承 ACE 不会在环境临时根目录上比其会话的临时目录活得更久)。令牌的 restricting list 是保活组加上仅 workspace-write 下的写入 SIDread-only = [登录 SID、Everyone]workspace-write = [登录 SID、Everyone、写入 SID]。保活不变式是登录 SID + Everyone(没有它们,早期 DLL init 会以 0xC0000142 死亡,CNG 会让 pwsh 以 0xE0434352 崩溃)。Read-only 不含写入 SID:先前 workspace-write 时期留下的常驻授权 ACE 保持**失效**(pass-2 检查只授予列表所携带的内容,因此 read-only 在 `/permission` 降级或崩溃后恢复的会话中始终保持严格零授权,而常驻 ACE 让重新升级保持零成本)。Authenticated Users 在**两种**列表中都缺席——WMI namespace 安全校验失败(0x80041003),因此 CIM 在每一种受限模式下都不可用,且 C:\-root 建树逃逸(驻留的 `AU:(AD)` + `AU:(OI)(CI)(IO)(M)` ACE)在两种模式下都被关闭;INTERACTIVE/LOCAL 同样在两种列表中都缺席(Public 树的写入被拒绝——由 runner 的 Public-probe 回归钉住)。Workspace-write 子进程看到的是私有的每会话临时子目录(`<temp>\dsh-<16 hex>`——由会话 id + 工作区派生、独占创建、拒绝 reparse point、提供方 dispose 时移除——TMP/TEMP 由 runner 重写——bwrap `--tmpfs /tmp` 语义)。受限令牌的**默认 DACL** 被扩展一条写入 SID 全权 ACE(`SetTokenInformation(TokenDefaultDacl)`):此后不带显式安全描述符创建的新对象(匿名管道——CreatePipe、同步对象)自带 restricting SID ACE,创建时的写 pass-2 检查通过;**named pipe 例外**——其默认安全描述符是 Win32 层在用户态安装的默认 SD 模板(由 KernelBase 构建——owner/SYSTEM/Admins 全权、Everyone/ANONYMOUS 只读),令牌无法影响,因此受限孙进程的管道 stdio 捕获保持拒绝(POC 记载的边界,由 runner 套件钉住)。它以 [`@deepseek-ai/dsh-sandbox-windows-acl`](../../../../packages/sandbox/sandbox-windows-acl/README.md)(后端加 `./runner` argv 前缀入口)、[`dsh-sandbox-local`](../../../../packages/sandbox/sandbox-local/README.md) 的 `win32` 链档、以及作为隔离执行器的 [`@deepseek-ai/dsh-pwsh-sandbox`](../../../../packages/bash/pwsh-sandbox/README.md) 交付;Windows 平台层在受限 pwsh 栈之上重新启用完整权限面(sandbox/sandbox-policy/permission/approval/fs-sandbox)。
## How the restriction works (why no new identity)
@@ -32,11 +32,11 @@ AppContainer 令牌没有环境读访问:每个可读路径都必须预先通
## Consequences
所得:仅写隔离、不引入新的 OS 版本下限(`CreateRestrictedToken` 比 mxc 的版本早二十年)、读/网络/进程可见性完全不受影响(与模式词汇表一致)、fail-closed 错误携带 API 名与精确 Win32 错误码。所失:无读侧或网络隔离;控制台隔离不可用(隐藏控制台子进程以 `STATUS_DLL_INIT_FAILED` 死亡;子进程共享宿主控制台);被授权根目录上有驻留 ACE 改动(目录须为调用者所有;工作区 ACE 按设计永久常驻——复用缓存,工作区改名时成为不可见残留——临时 ACE 由提供方 dispose 回收,借助持久化的每会话记录跨重启自愈——其即时 flush 先于 ACE(flush 延迟内));授权物化是急切的全树传播(`SetNamedSecurityInfoW` 立即遍历每个后代——在大型工作区上耗时数十秒),因按工作区身份,每台机器每个工作区只付一次;CIM 在**两种**受限模式下都不可用(AuthUsers 从两种列表中被移除——WMI namespace 安全校验失败,`Get-ComputerInfo` 静默返回不完整结果),作为关闭两种模式下 C:\-root 建树逃逸的代价;位于被授权根目录之外的 FAT 类(无 ACL)目标在两种模式下仍可写(没有可做交集的安全描述符——作为历史残留处理:不支持、仅警告、已在 README 中记录);NULL DACL 目录在 grant+revoke 往返下不保持身份(记录在案的边角,POC 亦有此行为);`whoami` 与令牌检查 cmdlet 在受限令牌下失败(诊断噪音,已记录);且**两种**受限模式都以 ConstrainedLanguage 模式运行 `pwsh`——受限令牌触发 PowerShell 的锁定检测,因此 `Add-Type`、非核心 .NET 静态调用(`[System.IO.*]::``[math]::`)、COM 对象与反射都会以“only core types”错误失败,而 `-f` 格式化、属性访问与核心 cmdlet/类型继续工作,语言模式也无法从内部提升回 FullLanguage——已在 pwsh 工具描述中教给模型,并记录在包 README 的 Known Limitations 中;**两种**受限模式同样拒绝 named-pipe 打开——libuv 的管道 stdio spawn 以 EPERM 失败(POC 记载的“无法重定向输出”边界;继承/忽略的 stdio 与匿名管道可用)——记录在包 README 的 Known Limitations 中,并在 pwsh 工具描述中教给模型。
所得:仅写隔离、不引入新的 OS 版本下限(`CreateRestrictedToken` 比 mxc 的版本早二十年)、读/网络/进程可见性完全不受影响(与模式词汇表一致)、fail-closed 错误携带 API 名与精确 Win32 错误码。所失:无读侧或网络隔离;控制台隔离不可用(隐藏控制台子进程以 `STATUS_DLL_INIT_FAILED` 死亡;子进程共享宿主控制台);被授权根目录上有驻留 ACE 改动(目录须为调用者所有;工作区 ACE 按设计永久常驻——复用缓存,工作区改名时成为不可见残留——临时 ACE 由提供方 dispose 连同派生的私有临时目录一起回收——崩溃会把两者都留下,下一次恢复会在独占创建处大声失败,直到临时目录卫生回收该目录);授权物化是急切的全树传播(`SetNamedSecurityInfoW` 立即遍历每个后代——在大型工作区上耗时数十秒),因按工作区身份,每台机器每个工作区只付一次;CIM 在**两种**受限模式下都不可用(AuthUsers 从两种列表中被移除——WMI namespace 安全校验失败,`Get-ComputerInfo` 静默返回不完整结果),作为关闭两种模式下 C:\-root 建树逃逸的代价;位于被授权根目录之外的 FAT 类(无 ACL)目标在两种模式下仍可写(没有可做交集的安全描述符——作为历史残留处理:不支持、仅警告、已在 README 中记录);NULL DACL 目录在 grant+revoke 往返下不保持身份(记录在案的边角,POC 亦有此行为);`whoami` 与令牌检查 cmdlet 在受限令牌下失败(诊断噪音,已记录);且**两种**受限模式都以 ConstrainedLanguage 模式运行 `pwsh`——受限令牌触发 PowerShell 的锁定检测,因此 `Add-Type`、非核心 .NET 静态调用(`[System.IO.*]::``[math]::`)、COM 对象与反射都会以“only core types”错误失败,而 `-f` 格式化、属性访问与核心 cmdlet/类型继续工作,语言模式也无法从内部提升回 FullLanguage——已在 pwsh 工具描述中教给模型,并记录在包 README 的 Known Limitations 中;**两种**受限模式同样拒绝 named-pipe 打开——libuv 的管道 stdio spawn 以 EPERM 失败(POC 记载的“无法重定向输出”边界;继承/忽略的 stdio 与匿名管道可用)——记录在包 README 的 Known Limitations 中,并在 pwsh 工具描述中教给模型。
## Testing
产品可见的 Windows 阵容切换仅存在于 win32,而 keyless 快照夹具必须在 macOS/Linux 上可重放,因此无法覆盖它;替代证据是 bundle 组合 spec[`base.spec.ts`](../../../../packages/bundle/base/tests/base.spec.ts)、[`windows-shell.spec.ts`](../../../../apps/cli/tests/windows-shell.spec.ts))加上 win32 真实 runner 套件(`packages/sandbox/sandbox-windows-acl/tests/``packages/bash/pwsh-sandbox/tests/`),组装态信号由 CI 的 Windows lane 负责。授权机制在跨平台侧由 `packages/sandbox/sandbox-local/tests/acl-session.spec.ts` 钉住(带归属绑定的记录 fold/供给——fork 复制的父记录绝不会为子会话供给记录——工作区/临时路径的篡改校验、带即时 flush 触发的一次性物化、独占临时目录创建并拒绝 reparse point、fork/恢复临时目录复用、dispose 与模式切换循环中的常驻/可回收生命周期,以及派生 SID 的 argv 契约——mock 掉 Win32 表面),win32 侧由 `workspace-sid.spec.ts`(派生的确定性/形态/相异性)、`grant.spec.ts`(真实 DACL 物化:可回收路径在 dispose 时撤销、常驻路径存活)、`acl.spec.ts` 的幂等授权快速路径与 dispose 后常驻 ACE 契约、`failure-paths.spec.ts` 的 suspension-orphan 回归(AssignProcessToJobObject 失败会终止子进程)与 `runner.spec.ts``--write-sid` 契约(调用者所有目录的授权、经 TMP/TEMP 的私有临时子目录、两种模式下的 CIM 拒绝探针、模式降级回归——驻留授权 ACE 在 read-only 下失效并在重新升级后再度生效——环境可写 Public-probe 回归(对 C:\Users\Public 子目录的写入在两种模式下都会被拒绝),以及两种模式下对 ConstrainedLanguage 的钉定,加上孙进程 stdio 矩阵钉定——继承/忽略的 stdio spawn 成功,而管道捕获在两种模式下都被**拒绝**)钉住。runner 失败分类以 127 退出码为门槛(受限命令仅仅在非 127 退出时打印 `windows-acl-run:` 签名,也绝不会被误分类为"命令未运行"——由 pwsh-sandbox helper 套件钉住)。
产品可见的 Windows 阵容切换仅存在于 win32,而 keyless 快照夹具必须在 macOS/Linux 上可重放,因此无法覆盖它;替代证据是 bundle 组合 spec[`base.spec.ts`](../../../../packages/bundle/base/tests/base.spec.ts)、[`windows-shell.spec.ts`](../../../../apps/cli/tests/windows-shell.spec.ts))加上 win32 真实 runner 套件(`packages/sandbox/sandbox-windows-acl/tests/``packages/bash/pwsh-sandbox/tests/`),组装态信号由 CI 的 Windows lane 负责。授权机制在跨平台侧由 `packages/sandbox/sandbox-local/tests/acl-grants.spec.ts` 钉住(派生的私有临时身份——按会话 + 工作区确定性、跨会话相异——一次性物化、独占临时目录创建并拒绝 reparse point、失败时自我清理、干净重启时对同一派生目录的重新授权、dispose 与模式切换循环中的常驻/可回收生命周期,以及派生 SID 的 argv 契约——mock 掉 Win32 表面),win32 侧由 `workspace-sid.spec.ts`(派生的确定性/形态/相异性)、`grant.spec.ts`(真实 DACL 物化:可回收路径在 dispose 时撤销、常驻路径存活)、`acl.spec.ts` 的幂等授权快速路径与 dispose 后常驻 ACE 契约、`failure-paths.spec.ts` 的 suspension-orphan 回归(AssignProcessToJobObject 失败会终止子进程)与 `runner.spec.ts``--write-sid` 契约(调用者所有目录的授权、经 TMP/TEMP 的私有临时子目录、两种模式下的 CIM 拒绝探针、模式降级回归——驻留授权 ACE 在 read-only 下失效并在重新升级后再度生效——环境可写 Public-probe 回归(对 C:\Users\Public 子目录的写入在两种模式下都会被拒绝),以及两种模式下对 ConstrainedLanguage 的钉定,加上孙进程 stdio 矩阵钉定——继承/忽略的 stdio spawn 成功,而管道捕获在两种模式下都被**拒绝**)钉住。runner 失败分类以 127 退出码为门槛(受限命令仅仅在非 127 退出时打印 `windows-acl-run:` 签名,也绝不会被误分类为"命令未运行"——由 pwsh-sandbox helper 套件钉住)。
## Related
+2 -2
View File
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write docs/persistence-catalog.md
persistence-catalog.md: b07a02fcfca093c08acd206235e009d4d5fb9664
persistence-catalog.zh.md: 6f75e4ae522b75fc48bf95df707a0bd0a990ea5c
persistence-catalog.md: a17cae015eaa107a900069de916dddb216b87ec7
persistence-catalog.zh.md: 3aef073dedcff0b6addb99d7c287f4e5f372c402
-25
View File
@@ -488,31 +488,6 @@ Source: [`packages/core/session/src/types.ts:276`](../packages/core/session/src/
### `sandbox/*`
#### `sandbox/acl-session` — log-only
```ts persistence-catalog
/**
* The session's windows-acl write record was provisioned — log-only
* (like `sandbox/mode`; NOT a surface event, carries no `surfaceOp`):
* durable and replayable, never in the model transcript. The LAST such
* event owned by the session is its record ({@link sessionAclRecord});
* the provider appends exactly one on the session's first Windows
* confined execution. The write SID itself is NOT stored — it is the
* per-workspace identity derived from `workspace`
* (`workspaceWriteSid`).
*/
'sandbox/acl-session': {
/** The owning session — the binding a fork's copied event cannot satisfy. */
sessionId: SessionId
/** The workspace root the grant applies to (the session's immutable cwd, as resolved). */
workspace: string
/** The session's private temp subdirectory under the host temp root. */
tempDir: string
}
```
Source: [`packages/sandbox/sandbox-local/src/acl-session.ts:43`](../packages/sandbox/sandbox-local/src/acl-session.ts)
#### `sandbox/mode` — log-only
```ts persistence-catalog
-25
View File
@@ -490,31 +490,6 @@ export type SessionEvent<T extends SessionEventType = SessionEventType> = {
### `sandbox/*`
#### `sandbox/acl-session` — log-only
```ts persistence-catalog
/**
* The session's windows-acl write record was provisioned — log-only
* (like `sandbox/mode`; NOT a surface event, carries no `surfaceOp`):
* durable and replayable, never in the model transcript. The LAST such
* event owned by the session is its record ({@link sessionAclRecord});
* the provider appends exactly one on the session's first Windows
* confined execution. The write SID itself is NOT stored — it is the
* per-workspace identity derived from `workspace`
* (`workspaceWriteSid`).
*/
'sandbox/acl-session': {
/** The owning session — the binding a fork's copied event cannot satisfy. */
sessionId: SessionId
/** The workspace root the grant applies to (the session's immutable cwd, as resolved). */
workspace: string
/** The session's private temp subdirectory under the host temp root. */
tempDir: string
}
```
来源:[`packages/sandbox/sandbox-local/src/acl-session.ts:43`](../packages/sandbox/sandbox-local/src/acl-session.ts)
#### `sandbox/mode` — log-only
```ts persistence-catalog
@@ -1,126 +0,0 @@
/**
* The windows-acl session write record — the DURABLE half of the seam's
* grant lifecycle. Each session owns exactly one record (its workspace
* binding plus one private temp subdirectory), stored as a log-only
* `sandbox/acl-session` event on the session log (the `sandbox/mode`
* precedent): replayable, never in the model transcript, and no external
* config store. The record carries NO SID: the write SID is the
* per-WORKSPACE identity derived from the workspace path
* (`workspaceWriteSid`) — deterministic across sessions and server
* restarts, so the workspace-root ACE materializes once per workspace per
* machine (the grant's exact-ACE skip makes every later provision O(1))
* instead of once per session. The ACE half is server-lifetime state owned
* by the provider ({@link AclWriteGrant}: workspace ACEs standing, temp ACEs
* revocable); the record survives restarts so a resumed session reuses the
* SAME private temp subdirectory and the same derived SID — re-granting
* idempotently merges into (or skips) the standing ACEs. The record is
* BOUND to its owning session id, so a fork (which copies the parent's
* events, record included) never inherits the parent's temp identity — it
* provisions a fresh one. The record's payload is durable input and is
* validated at the fold (well-formed workspace/temp paths); a
* matching-but-tampered record fails loud.
*
* @module dsh-sandbox-local/acl-session
*/
import { randomBytes } from 'node:crypto'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import type { Session, SessionEvent, SessionId } from '@deepseek-ai/dsh-session'
declare module '@deepseek-ai/dsh-session/types' {
interface SessionEventMap {
/**
* The session's windows-acl write record was provisioned — log-only
* (like `sandbox/mode`; NOT a surface event, carries no `surfaceOp`):
* durable and replayable, never in the model transcript. The LAST such
* event owned by the session is its record ({@link sessionAclRecord});
* the provider appends exactly one on the session's first Windows
* confined execution. The write SID itself is NOT stored — it is the
* per-workspace identity derived from `workspace`
* (`workspaceWriteSid`).
*/
'sandbox/acl-session': {
/** The owning session — the binding a fork's copied event cannot satisfy. */
sessionId: SessionId
/** The workspace root the grant applies to (the session's immutable cwd, as resolved). */
workspace: string
/** The session's private temp subdirectory under the host temp root. */
tempDir: string
}
}
}
/** The durable per-session record carried by one `sandbox/acl-session` event. */
export interface AclSessionRecord {
/** The owning session id (binds the record against fork inheritance). */
sessionId: SessionId
/** The workspace root the record was provisioned for (the write SID derives from it). */
workspace: string
/** The session's private temp subdirectory. */
tempDir: string
}
/**
* The session's record: the last `sandbox/acl-session` event owned by it, or
* undefined (never confined / a fork). Durable-input validation: tampered
* workspace or temp path fails loud. @param events/@param sessionId/@returns
* as below.
* @param events - session events (other types skipped).
* @param sessionId - owning session (fork binding).
* @returns the last owned record, or undefined without one.
*/
export function sessionAclRecord(events: readonly SessionEvent[], sessionId: SessionId): AclSessionRecord | undefined {
for (let index = events.length - 1; index >= 0; index -= 1) {
const event = events[index] as SessionEvent
if (event.type !== 'sandbox/acl-session') continue
const data = event.data
// Fork copies the parent's record: skip non-owned records (fork mints fresh).
if (data.sessionId !== sessionId) continue
if (typeof data.workspace !== 'string' || data.workspace.length === 0) {
throw new Error(`sandbox-local: session "${sessionId}" acl record carries an empty workspace`)
}
if (typeof data.tempDir !== 'string' || dirname(data.tempDir) !== tmpdir()) {
throw new Error(
`sandbox-local: session "${sessionId}" acl record carries a temp path outside the host temp root: ${JSON.stringify(data.tempDir)}`,
)
}
return data
}
return undefined
}
/**
* The session's private temp subdirectory name: `<tmpdir>\dsh-<16 random hex>`.
* The name is RANDOM and persisted in the record — convergence across server
* restarts comes from the record (the same SID re-grants the same directory),
* not from any derivation an attacker (who knows the session id through
* `DSH_SESSION_ID`) could predict and pre-place. The provider creates it
* exclusively and rejects reparse points; OS temp hygiene may reclaim it —
* deliberately no GC here.
* @returns the private temp subdirectory path.
*/
export function sessionTempDir(): string {
return join(tmpdir(), `dsh-${randomBytes(8).toString('hex')}`)
}
/**
* Provision the record for a session that has none (its first Windows
* confined execution): the workspace binding plus the private temp
* subdirectory, appended as exactly one log-only `sandbox/acl-session`
* event — the provision IS its event, nothing mutates record state out of
* band. Fork (whose copied parent record is not its own) provisions a fresh
* record; resume replays the stored one.
* @param session - the session the record belongs to.
* @param workspaceRoot - the resolved policy root (the session's immutable cwd).
* @returns the provisioned record.
*/
export function provisionAclSession(session: Session, workspaceRoot: string): AclSessionRecord {
const record: AclSessionRecord = {
sessionId: session.id,
workspace: workspaceRoot,
tempDir: sessionTempDir(),
}
session.append('sandbox/acl-session', record)
return record
}
+84 -88
View File
@@ -7,8 +7,8 @@
*
* The windows-acl rung additionally owns the write grants: the write SID is
* the per-WORKSPACE identity derived from the canonical workspace path
* (`workspaceWriteSid`), and one private temp subdirectory per session
* (durable record in the session log — see `./acl-session.ts`). The
* (`workspaceWriteSid`), and the private temp subdirectory is DERIVED per
* session (session id + workspace — nothing stored). The
* workspace-root ACE materializes once per workspace per server lifetime
* and STANDS (the cross-session reuse cache — the exact-ACE skip makes
* every later provision O(1) instead of re-propagating the tree per
@@ -19,8 +19,10 @@
*/
import { spawnSync } from 'node:child_process'
import { existsSync, mkdirSync } from 'node:fs'
import { createHash } from 'node:crypto'
import { existsSync, mkdirSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import {
LAUNCHER_BIN,
@@ -35,8 +37,6 @@ import { SandboxProvider, SandboxUnavailableError } from '@deepseek-ai/dsh-sandb
import type { ConfinedArgv, ConfinedSandboxMode, RunnerFailureRule, SandboxEnforcement, SandboxPolicy } from '@deepseek-ai/dsh-sandbox'
import type { SessionId } from '@deepseek-ai/dsh-session'
import { AclWriteGrant, workspaceWriteSid } from '@deepseek-ai/dsh-sandbox-windows-acl'
import { provisionAclSession, sessionAclRecord } from './acl-session.ts'
import type { AclSessionRecord } from './acl-session.ts'
import { bwrapProfileArgs, landlockProfileArgs, seatbeltProfileArgs } from './profiles.ts'
/** Plugin config. All optional — `static Config` supplies the defaults. */
@@ -110,6 +110,25 @@ function defaultProbeWindowsAcl(runnerInvocation: string[], timeoutMs: number):
return probe.status === 0
}
/**
* The session's private temp subdirectory: `<tmpdir>\dsh-<16 hex>`, derived
* from the session id and its workspace instead of stored. The same session
* and workspace always name the same directory — a resumed session
* re-grants it (the exact-ACE skip keeps that O(1)) — while a fork's
* different session id names a fresh one. The name is predictable to anyone
* who knows the session id (the confined command sees it as
* `DSH_SESSION_ID`), so the provider creates the directory EXCLUSIVELY and
* rejects reparse points: a pre-placed entry fails the first confined run
* loudly, and cannot redirect the grant onto a foreign object.
* @param sessionId - the policy's calling-session identity.
* @param workspaceRoot - the resolved policy root.
* @returns the session's private temp subdirectory path.
*/
export function sessionTempDir(sessionId: SessionId, workspaceRoot: string): string {
const digest = createHash('sha256').update(String(sessionId)).update('\0').update(workspaceRoot).digest('hex')
return join(tmpdir(), `dsh-${digest.slice(0, 16)}`)
}
/** Test hook: inject probe verdicts / a fake launcher / a platform without real runners. */
export interface SandboxInternals {
/** Replaces `process.platform` for chain selection (exercise any platform's chain from any host). */
@@ -132,6 +151,8 @@ export interface SandboxInternals {
windowsAclRunnerEntry?: string
/** Replaces the functional windows-acl probe (the win32 chain's sole rung — only consulted if that chain ever grows). */
probeWindowsAcl?: () => boolean
/** Replaces the private-temp-directory removal at provider dispose (a throwing fake exercises the cleanup-failure path). */
rmTempDir?: (path: string) => void
}
/** The chain's verdict: which runner confines, and how completely it enforces. */
@@ -257,12 +278,12 @@ export class LocalSandboxProvider extends SandboxProvider {
* Server-lifetime write grants (windows-acl rung): the STANDING
* workspace-root grant per workspace (its ACE is the cross-session reuse
* cache and outlives the provider — never revoked) and the REVOCABLE
* private-temp grant per session (revoked on provider dispose); the
* durable half (workspace binding + private temp dir) lives in the
* session log (`./acl-session.ts`).
* private-temp grant per session (revoked on provider dispose).
*/
private readonly workspaceGrants = new Map<string, AclWriteGrant>()
private readonly tempGrants = new Map<string, AclWriteGrant>()
/** Session id → the private temp directory this provider created (removed on dispose). */
private readonly tempDirs = new Map<string, string>()
constructor(ctx: Context, config: Config) {
super(ctx)
@@ -335,18 +356,15 @@ export class LocalSandboxProvider extends SandboxProvider {
}
/**
* The windows-acl runner argv for one policy. With a calling session
* (the policy's `sessionId`), the session's durable record is folded from
* the session log (provisioned on first use), its ACEs materialized once
* per server lifetime, and the runner receives `--write-sid` plus the
* session's PRIVATE temp subdirectory — it grants nothing and revokes
* nothing. A fresh provision kicks an IMMEDIATE persistence flush right
* after the append (no write-behind debounce delay), narrowing the
* crash-and-lose-record window to the flush latency itself — the residual
* is documented in the README (the spawn seams are synchronous, so no
* await barrier exists between record and ACEs). Agentless calls (no
* session) pass no SID: the runner self-manages per-call grants on the
* ambient temp root.
* The windows-acl runner argv for one policy. With a calling session (the
* policy's `sessionId`), the write grants are materialized once per server
* lifetime — the standing workspace-root grant per workspace and the
* revocable private-temp grant per session — and the runner receives
* `--write-sid` (the workspace-derived identity; its presence marks the
* seam-managed DACL contract) plus, under workspace-write, the session's
* PRIVATE temp subdirectory (derived from session id + workspace) — it
* grants nothing and revokes nothing. Agentless calls pass the ambient
* temp root and no `--write-sid`: the runner self-manages its DACLs.
* @param policy - the resolved per-call policy.
* @returns the runner invocation.
*/
@@ -360,8 +378,7 @@ export class LocalSandboxProvider extends SandboxProvider {
'--mode', policy.mode,
]
}
const record = this.aclSessionRecord(sessionId, policy.workspaceRoot)
this.materializeAclGrant(record, policy.mode)
this.materializeAclGrant(sessionId, policy.workspaceRoot, policy.mode)
return [
...this.windowsAclRunnerInvocation(),
'--workspace', policy.workspaceRoot,
@@ -370,79 +387,40 @@ export class LocalSandboxProvider extends SandboxProvider {
// runs pass the ambient temp root — the runner validates it exists
// but grants nothing. The derived write SID is the per-workspace
// identity; the flag's presence marks the seam-managed DACL contract.
'--temp', policy.mode === 'workspace-write' ? record.tempDir : tmpdir(),
'--temp', policy.mode === 'workspace-write' ? sessionTempDir(sessionId, policy.workspaceRoot) : tmpdir(),
'--mode', policy.mode,
'--write-sid', workspaceWriteSid(record.workspace),
'--write-sid', workspaceWriteSid(policy.workspaceRoot),
]
}
/**
* Fold (or provision) the calling session's durable windows-acl record.
* The provision appends exactly one log-only `sandbox/acl-session` event
* to the session log and kicks an immediate persistence flush (the
* write-behind coordinator's bounded window would otherwise delay the
* record's durability past its ACE materialization); the record's
* workspace must equal the policy root — both derive from the session's
* immutable cwd, so a mismatch is a corrupted composition and fails loud.
* @param sessionId - the policy's calling-session identity.
* @param workspaceRoot - the resolved policy root.
* @returns the session's record.
*/
private aclSessionRecord(sessionId: SessionId, workspaceRoot: string): AclSessionRecord {
const store = this.ctx.get('sessions')
if (store === undefined) {
throw new Error('sandbox-local: per-session windows-acl confinement requires the session store (ctx.sessions)')
}
const session = store.get(sessionId)
if (session === undefined) {
throw new Error(`sandbox-local: windows-acl policy carries session "${sessionId}" but ctx.sessions has no such session`)
}
const existing = sessionAclRecord(session.events, sessionId)
if (existing !== undefined) {
if (existing.workspace !== workspaceRoot) {
throw new Error(
`sandbox-local: session "${sessionId}" acl record workspace ${JSON.stringify(existing.workspace)} `
+ `does not match the resolved policy root ${JSON.stringify(workspaceRoot)} (session cwd is immutable)`,
)
}
return existing
}
const record = provisionAclSession(session, workspaceRoot)
// Immediate durability kick: the append is write-behind (bounded
// coordinator window); flush now so the record is durable as close to
// its ACE materialization as the synchronous confine seam allows. The
// residual window (a crash inside the flush latency) strands the
// private temp directory unrecorded — documented in the README.
void store.flush(session)
return record
}
/**
* Materialize the record's ACEs once per server lifetime: lazily at the
* session's first confined execution, reused for every later call (the map
* hits are the whole call). The write SID is the per-workspace identity
* derived from the record's workspace. Workspace-write grants the
* workspace root STANDING (the ACE outlives every session — the reuse
* cache) and the private temp subdirectory REVOCABLY — created here
* EXCLUSIVELY (the name is random and unguessable, a pre-existing entry
* throws EEXIST, and a reparse point is rejected, so the grant never
* lands on an attacker-placed object); read-only materializes NOTHING —
* its token alone restricts every write, and the standing grant from an
* Materialize the session's ACEs once per server lifetime: lazily at its
* first confined execution, reused for every later call (the map hits are
* the whole call). The write SID is the per-workspace identity derived
* from the workspace. Workspace-write grants the workspace root STANDING
* (the ACE outlives every session — the reuse cache) and the session's
* private temp subdirectory REVOCABLY — the directory is derived from
* session id + workspace, created here EXCLUSIVELY (a pre-existing entry
* or a reparse point fails the first confined run loudly, so the grant
* never lands on a foreign object); read-only materializes NOTHING — its
* token alone restricts every write, and the standing grant from an
* earlier workspace-write period is KEPT through a downgrade (never
* revoked): the read-only restricted token carries no write SID (the
* read-only list), so the ACE is inert there, while the map hit keeps the
* re-upgrade free of re-propagation. Fail-closed: a half-materialized
* temp grant is revoked before the error propagates.
* @param record - the session's durable record.
* @param sessionId - the policy's calling-session identity.
* @param workspaceRoot - the resolved policy root.
* @param mode - the policy mode (grants exist only under workspace-write).
*/
private materializeAclGrant(record: AclSessionRecord, mode: ConfinedSandboxMode): void {
private materializeAclGrant(sessionId: SessionId, workspaceRoot: string, mode: ConfinedSandboxMode): void {
if (mode === 'read-only') return
const writeSid = workspaceWriteSid(record.workspace)
if (!this.workspaceGrants.has(record.workspace)) {
const writeSid = workspaceWriteSid(workspaceRoot)
const tempDir = sessionTempDir(sessionId, workspaceRoot)
if (!this.workspaceGrants.has(workspaceRoot)) {
const grant = AclWriteGrant.create(writeSid)
try {
grant.add(record.workspace, true)
grant.add(workspaceRoot, true)
} catch (error) {
// Free the SID; a standing ACE (if the apply succeeded before a
// post-apply throw) is the intended end state, not an error
@@ -454,17 +432,23 @@ export class LocalSandboxProvider extends SandboxProvider {
}
throw error
}
this.workspaceGrants.set(record.workspace, grant)
this.workspaceGrants.set(workspaceRoot, grant)
}
if (this.tempGrants.has(record.sessionId)) return
if (this.tempGrants.has(sessionId)) return
const grant = AclWriteGrant.create(writeSid)
// The directory is removed again in the catch only when THIS confine
// created it — a pre-existing entry (EEXIST) is a foreign object and is
// never deleted.
let created = false
try {
// Exclusive creation (no `recursive`): a pre-existing entry OR a
// reparse point both fail EEXIST — the grant never lands on a foreign
// object.
mkdirSync(record.tempDir)
grant.add(record.tempDir)
mkdirSync(tempDir)
created = true
grant.add(tempDir)
} catch (error) {
if (created) rmSync(tempDir, { recursive: true, force: true })
// Revoke whatever stands and free the SID — never leave a half-grant
// behind a failed confine (the runner never runs).
try {
@@ -474,15 +458,18 @@ export class LocalSandboxProvider extends SandboxProvider {
}
throw error
}
this.tempGrants.set(record.sessionId, grant)
this.tempGrants.set(sessionId, grant)
this.tempDirs.set(sessionId, tempDir)
}
/**
* Dispose every write grant (provider dispose): the revocable temp ACEs
* are revoked and every SID allocation freed; the standing workspace ACEs
* are revoked, the private temp directories this provider created are
* removed, and every SID allocation is freed; the standing workspace ACEs
* stay (the reuse cache). Cleanup failures are reported, not thrown:
* cordis teardown must not be aborted by grant cleanup, and the durable
* records make a missed revocation self-healing on the next resume.
* cordis teardown must not be aborted by grant cleanup. A crash skips all
* of it — the next resume then fails loudly at the exclusive creation and
* OS temp hygiene (or manual removal) recovers.
*/
private revokeAclGrants(): void {
if (this.workspaceGrants.size === 0 && this.tempGrants.size === 0) return
@@ -494,8 +481,17 @@ export class LocalSandboxProvider extends SandboxProvider {
failures.push(error)
}
}
const rmTempDir = this.internals.rmTempDir ?? ((dir: string) => rmSync(dir, { recursive: true, force: true }))
for (const dir of this.tempDirs.values()) {
try {
rmTempDir(dir)
} catch (error) {
failures.push(error)
}
}
this.workspaceGrants.clear()
this.tempGrants.clear()
this.tempDirs.clear()
if (failures.length > 0) {
this.ctx.logger.warn(`sandbox-local: windows-acl grant cleanup completed with ${failures.length} failure(s)`)
for (const error of failures) this.ctx.logger.warn(error)
@@ -1,11 +1,10 @@
/**
* windows-acl write grants: the DURABLE record (log-event fold/provision with
* ownership binding + tamper validation) plus the SERVER-LIFETIME ACE
* materialization (standing workspace grant per workspace, revocable temp
* grant per session), through the REAL LocalSandboxProvider.confine() with a
* real session store. Win32 surface mocked at the package boundary (the
* workspace-derived SID mocked to a constant); the real-FFI grant behavior
* lives in sandbox-windows-acl's win32 tests.
* windows-acl write grants: the SERVER-LIFETIME ACE materialization
* (standing workspace grant per workspace, revocable private-temp grant per
* session) plus the derived private-temp identity, through the REAL
* LocalSandboxProvider.confine(). Win32 surface mocked at the package
* boundary (the workspace-derived SID mocked to a constant); the real-FFI
* grant behavior lives in sandbox-windows-acl's win32 tests.
*/
import { existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync } from 'node:fs'
@@ -14,15 +13,15 @@ import { basename, join } from 'node:path'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { Context } from 'cordis'
import type { SandboxPolicy } from '@deepseek-ai/dsh-sandbox'
import { SessionId, SessionStore } from '@deepseek-ai/dsh-session'
import type { SessionEvent, SessionId as SessionIdType } from '@deepseek-ai/dsh-session'
import { LocalSandboxProvider } from '@deepseek-ai/dsh-sandbox-local'
import { sessionTempDir } from '../src/acl-session.ts'
import { SessionId } from '@deepseek-ai/dsh-session'
import { LocalSandboxProvider, sessionTempDir } from '@deepseek-ai/dsh-sandbox-local'
/** Cross-file state shared with the vi.mock factory (hoisting contract). */
const mockState = vi.hoisted(() => ({
grants: [] as Array<{ writeSid: string; added: Array<{ path: string; standing: boolean }>; disposed: boolean }>,
addFailure: undefined as Error | undefined,
/** Restricts {@link addFailure} to this path (undefined = every add throws). */
addFailurePath: undefined as string | undefined,
disposeFailure: undefined as Error | undefined,
}))
@@ -39,7 +38,9 @@ vi.mock('@deepseek-ai/dsh-sandbox-windows-acl', () => {
return new MockAclWriteGrant(writeSid)
}
add(path: string, standing = false): void {
if (mockState.addFailure !== undefined) throw mockState.addFailure
if (mockState.addFailure !== undefined && (mockState.addFailurePath === undefined || mockState.addFailurePath === path)) {
throw mockState.addFailure
}
this.added.push({ path, standing })
}
dispose(): void {
@@ -53,28 +54,17 @@ vi.mock('@deepseek-ai/dsh-sandbox-windows-acl', () => {
/** The workspace-derived write SID the mock pins for every workspace. */
const DERIVED_SID = 'S-1-4-42-42'
/** One provisioned record event, shaped like the live log's envelope. */
function recordEvent(record: { sessionId: SessionIdType; workspace: string; tempDir: string }): SessionEvent {
return { type: 'sandbox/acl-session', seq: 0, time: 0, data: record }
}
async function setup() {
const ctx = new Context()
await ctx.plugin(SessionStore)
const fiber = await ctx.plugin(LocalSandboxProvider, {})
const sandbox = ctx.sandbox as LocalSandboxProvider
sandbox.internals = { platform: 'win32', windowsAclRunnerArgs: ['node', 'windows-acl-runner.js'] }
return { ctx, sandbox, fiber }
}
/** A workspace root the policy, the record, and the session cwd all share. */
/** A workspace root the policy carries. */
function workspaceRoot(): string {
return mkdtempSync(join(tmpdir(), 'dsh-acl-session-ws-'))
}
/** A well-shaped private temp path under the host temp root (never created). */
function shapedTempPath(): string {
return join(tmpdir(), `dsh-${'ab'.repeat(8)}`)
return mkdtempSync(join(tmpdir(), 'dsh-acl-grants-ws-'))
}
describe('windows-acl write grants (LocalSandboxProvider)', () => {
@@ -83,6 +73,7 @@ describe('windows-acl write grants (LocalSandboxProvider)', () => {
beforeEach(() => {
mockState.grants = []
mockState.addFailure = undefined
mockState.addFailurePath = undefined
mockState.disposeFailure = undefined
})
@@ -90,21 +81,26 @@ describe('windows-acl write grants (LocalSandboxProvider)', () => {
for (const dir of scratch.splice(0)) rmSync(dir, { recursive: true, force: true })
}
it('workspace-write: first confine provisions the record and materializes ONCE (standing workspace + revocable private temp)', async () => {
it('workspace-write: first confine materializes ONCE (standing workspace + revocable private temp), the derived temp dir rides the argv', async () => {
try {
const { ctx, sandbox, fiber } = await setup()
const { sandbox, fiber } = await setup()
const ws = workspaceRoot()
scratch.push(ws)
const session = ctx.sessions.create(SessionId('sess-1'), { meta: { cwd: ws } })
const tempDir = sessionTempDir(SessionId('sess-1'), ws)
scratch.push(tempDir)
const policy: SandboxPolicy = { mode: 'workspace-write', workspaceRoot: ws, sessionId: SessionId('sess-1') }
const confined = sandbox.confine(['pwsh', '/Command', 'x'], policy)
expect(confined.argv).toContain('--write-sid')
expect(confined.argv).toContain(DERIVED_SID)
expect(confined.argv).toContain('workspace-write')
expect(confined.argv).toEqual([
'node', 'windows-acl-runner.js',
'--workspace', ws,
'--temp', tempDir,
'--mode', 'workspace-write',
'--write-sid', DERIVED_SID,
'--',
'pwsh', '/Command', 'x',
])
expect(mockState.grants).toHaveLength(2)
const tempDir = (session.events.at(-1)!.data as { tempDir: string }).tempDir
scratch.push(tempDir)
expect(mockState.grants[0]).toMatchObject({
writeSid: DERIVED_SID,
added: [{ path: ws, standing: true }], // standing: the reuse cache, never revoked
@@ -116,12 +112,10 @@ describe('windows-acl write grants (LocalSandboxProvider)', () => {
disposed: false,
})
expect(existsSync(tempDir)).toBe(true) // created exclusively
expect(session.events.filter(event => event.type === 'sandbox/acl-session')).toHaveLength(1)
// Reuse: the second confine is the map hits.
sandbox.confine(['pwsh', '/Command', 'x'], policy)
expect(mockState.grants).toHaveLength(2)
expect(session.events).toHaveLength(1)
await fiber.dispose()
// dispose() runs on BOTH grants: the standing workspace ACE is left in
@@ -135,66 +129,17 @@ describe('windows-acl write grants (LocalSandboxProvider)', () => {
it('mode switch: read-only materializes nothing, the upgrade materializes ONCE with the derived SID, the downgrade keeps the standing grant', async () => {
try {
const { ctx, sandbox } = await setup()
const { sandbox } = await setup()
const ws = workspaceRoot()
scratch.push(ws)
const session = ctx.sessions.create(SessionId('sess-switch'), { meta: { cwd: ws } })
const tempDir = sessionTempDir(SessionId('sess-switch'), ws)
scratch.push(tempDir)
const readOnly: SandboxPolicy = { mode: 'read-only', workspaceRoot: ws, sessionId: SessionId('sess-switch') }
const workspaceWrite: SandboxPolicy = { mode: 'workspace-write', workspaceRoot: ws, sessionId: SessionId('sess-switch') }
// read-only first: record rides along, nothing materialized, ambient temp.
// read-only first: nothing materialized, ambient temp.
const confinedRo = sandbox.confine(['true'], readOnly)
expect(confinedRo.argv).toContain('--write-sid')
expect(confinedRo.argv).toContain(tmpdir())
expect(mockState.grants).toHaveLength(0)
const record = session.events.filter(event => event.type === 'sandbox/acl-session')[0]!.data as { tempDir: string }
scratch.push(record.tempDir)
expect(existsSync(record.tempDir)).toBe(false)
// Upgrade: first workspace-write materializes with the derived SID.
const upgraded = sandbox.confine(['true'], workspaceWrite)
expect(upgraded.argv).toEqual([
'node', 'windows-acl-runner.js',
'--workspace', ws,
'--temp', record.tempDir,
'--mode', 'workspace-write',
'--write-sid', DERIVED_SID,
'--',
'true',
])
expect(mockState.grants).toHaveLength(2)
expect(mockState.grants[0]).toMatchObject({ writeSid: DERIVED_SID, added: [{ path: ws, standing: true }], disposed: false })
expect(mockState.grants[1]).toMatchObject({
writeSid: DERIVED_SID,
added: [{ path: record.tempDir, standing: false }],
disposed: false,
})
expect(existsSync(record.tempDir)).toBe(true)
// Reuse: map hits.
sandbox.confine(['true'], workspaceWrite)
expect(mockState.grants).toHaveLength(2)
// Downgrade: standing grant KEPT (inert under read-only, free re-upgrade).
sandbox.confine(['true'], readOnly)
expect(mockState.grants).toHaveLength(2)
expect(mockState.grants[0]!.disposed).toBe(false)
expect(session.events.filter(event => event.type === 'sandbox/acl-session')).toHaveLength(1)
} finally {
cleanup()
}
})
it('read-only: the record rides along (--write-sid, one event) but NOTHING is materialized and the ambient temp root is passed', async () => {
try {
const { ctx, sandbox } = await setup()
const ws = workspaceRoot()
scratch.push(ws)
const session = ctx.sessions.create(SessionId('sess-ro'), { meta: { cwd: ws } })
const policy: SandboxPolicy = { mode: 'read-only', workspaceRoot: ws, sessionId: SessionId('sess-ro') }
const confined = sandbox.confine(['true'], policy)
expect(confined.argv).toEqual([
expect(confinedRo.argv).toEqual([
'node', 'windows-acl-runner.js',
'--workspace', ws,
'--temp', tmpdir(), // NOT the private subdir: read-only grants nothing
@@ -204,90 +149,89 @@ describe('windows-acl write grants (LocalSandboxProvider)', () => {
'true',
])
expect(mockState.grants).toHaveLength(0)
expect(session.events.filter(event => event.type === 'sandbox/acl-session')).toHaveLength(1)
expect(existsSync(tempDir)).toBe(false)
// Upgrade: first workspace-write materializes with the derived SID.
const upgraded = sandbox.confine(['true'], workspaceWrite)
expect(upgraded.argv).toEqual([
'node', 'windows-acl-runner.js',
'--workspace', ws,
'--temp', tempDir,
'--mode', 'workspace-write',
'--write-sid', DERIVED_SID,
'--',
'true',
])
expect(mockState.grants).toHaveLength(2)
expect(mockState.grants[0]).toMatchObject({ writeSid: DERIVED_SID, added: [{ path: ws, standing: true }], disposed: false })
expect(mockState.grants[1]).toMatchObject({
writeSid: DERIVED_SID,
added: [{ path: tempDir, standing: false }],
disposed: false,
})
expect(existsSync(tempDir)).toBe(true)
// Reuse: map hits.
sandbox.confine(['true'], workspaceWrite)
expect(mockState.grants).toHaveLength(2)
// Downgrade: standing grant KEPT (inert under read-only, free re-upgrade).
sandbox.confine(['true'], readOnly)
expect(mockState.grants).toHaveLength(2)
expect(mockState.grants[0]!.disposed).toBe(false)
} finally {
cleanup()
}
})
it('resume: a seeded record replays the same derived SID and temp dir with no second event appended', async () => {
it('resume: a fresh provider derives the SAME temp dir for the same session and workspace and re-grants it', async () => {
try {
const ws = workspaceRoot()
scratch.push(ws)
const tempDir = shapedTempPath()
const record = { sessionId: SessionId('resumed'), workspace: ws, tempDir }
scratch.push(tempDir)
const first = await setup()
const session = first.ctx.sessions.create(SessionId('resumed'), { seed: [recordEvent(record)], meta: { cwd: ws } })
expect(session.events.filter(event => event.type === 'sandbox/acl-session')).toHaveLength(1)
const policy: SandboxPolicy = { mode: 'workspace-write', workspaceRoot: ws, sessionId: SessionId('resumed') }
const confined = first.sandbox.confine(['true'], policy)
expect(confined.argv).toContain(DERIVED_SID) // re-derived from the record's workspace
const firstConfined = first.sandbox.confine(['true'], policy)
expect(mockState.grants).toHaveLength(2)
expect(mockState.grants[1]).toMatchObject({ writeSid: DERIVED_SID, added: [{ path: tempDir, standing: false }] })
// Replay IS the state: nothing appended.
expect(session.events.filter(event => event.type === 'sandbox/acl-session')).toHaveLength(1)
expect(session.events).toHaveLength(2)
// Clean restart: dispose revokes the temp ACE and removes the private
// temp directory, so the fresh provider's exclusive creation succeeds.
await first.fiber.dispose()
mockState.grants = []
const second = await setup()
const secondConfined = second.sandbox.confine(['true'], policy)
expect(secondConfined.argv).toEqual(firstConfined.argv)
expect(mockState.grants).toHaveLength(2)
expect(mockState.grants[1]).toMatchObject({
writeSid: DERIVED_SID,
added: [{ path: sessionTempDir(SessionId('resumed'), ws), standing: false }],
})
await second.fiber.dispose()
} finally {
cleanup()
}
})
it('fork: a child seeded with the PARENT\'s events ignores the parent record and provisions a fresh temp identity (sessionId binding)', async () => {
it('fork: a different session id derives a DIFFERENT private temp identity over the same workspace', async () => {
try {
const { ctx, sandbox } = await setup()
const { sandbox } = await setup()
const ws = workspaceRoot()
scratch.push(ws)
const parentTemp = shapedTempPath()
const parentRecord = { sessionId: SessionId('parent'), workspace: ws, tempDir: parentTemp }
const parentPolicy: SandboxPolicy = { mode: 'workspace-write', workspaceRoot: ws, sessionId: SessionId('parent') }
const childPolicy: SandboxPolicy = { mode: 'workspace-write', workspaceRoot: ws, sessionId: SessionId('child') }
sandbox.confine(['true'], parentPolicy)
const parentTemp = sessionTempDir(SessionId('parent'), ws)
scratch.push(parentTemp)
// SessionStore.fork copies the parent's events verbatim — the child must NOT inherit the record.
const child = ctx.sessions.create(SessionId('child'), { seed: [recordEvent(parentRecord)], meta: { cwd: ws } })
sandbox.confine(['true'], childPolicy)
const childTemp = sessionTempDir(SessionId('child'), ws)
scratch.push(childTemp)
const policy: SandboxPolicy = { mode: 'workspace-write', workspaceRoot: ws, sessionId: SessionId('child') }
sandbox.confine(['true'], policy)
expect(mockState.grants).toHaveLength(2)
// Fresh temp identity, NOT the parent's (the workspace SID is shared by
// derivation — the workspace is the same).
const childTemp = (child.events.at(-1)!.data as { tempDir: string }).tempDir
// derivation — the workspace is the same, so the standing grant is the
// map hit and only the child's temp grant joins).
expect(childTemp).not.toBe(parentTemp)
expect(mockState.grants[1]).toMatchObject({ added: [{ path: childTemp, standing: false }] })
expect(child.events.filter(event => event.type === 'sandbox/acl-session')).toHaveLength(2) // parent's copied + child's fresh
} finally {
cleanup()
}
})
it('fails loud on a matching-but-tampered record: foreign temp path, empty workspace, and non-string fields never materialize', async () => {
try {
const { ctx, sandbox } = await setup()
const ws = workspaceRoot()
scratch.push(ws)
// tempDir outside the host temp root.
const foreignTemp = { sessionId: SessionId('tampered-temp'), workspace: ws, tempDir: '/attacker/path' }
ctx.sessions.create(SessionId('tampered-temp'), { seed: [recordEvent(foreignTemp)], meta: { cwd: ws } })
const tempPolicy: SandboxPolicy = { mode: 'workspace-write', workspaceRoot: ws, sessionId: SessionId('tampered-temp') }
expect(() => sandbox.confine(['true'], tempPolicy)).toThrow(/outside the host temp root/)
// Non-string durable fields (a corrupted/tampered JSONL payload): the
// typeof guards fail loud before any string operation runs. There is
// NO stored SID to tamper with — the write SID is derived from the
// workspace path, so the old "SID rewritten to Everyone" attack
// surface does not exist.
const cases: Array<{ id: string; record: Record<string, unknown>; expect: RegExp }> = [
{ id: 'tampered-type-ws-null', record: { sessionId: SessionId('tampered-type-ws-null'), workspace: null, tempDir: shapedTempPath() }, expect: /empty workspace/ },
{ id: 'tampered-type-ws-empty', record: { sessionId: SessionId('tampered-type-ws-empty'), workspace: '', tempDir: shapedTempPath() }, expect: /empty workspace/ },
{ id: 'tampered-type-temp', record: { sessionId: SessionId('tampered-type-temp'), workspace: ws, tempDir: 123 }, expect: /outside the host temp root/ },
]
for (const c of cases) {
ctx.sessions.create(SessionId(c.id), { seed: [recordEvent(c.record as never)], meta: { cwd: ws } })
const policy: SandboxPolicy = { mode: 'workspace-write', workspaceRoot: ws, sessionId: SessionId(c.id) }
expect(() => sandbox.confine(['true'], policy), c.id).toThrow(c.expect)
}
expect(mockState.grants).toHaveLength(0)
expect(mockState.grants).toHaveLength(3)
expect(mockState.grants[2]).toMatchObject({ added: [{ path: childTemp, standing: false }] })
} finally {
cleanup()
}
@@ -295,16 +239,14 @@ describe('windows-acl write grants (LocalSandboxProvider)', () => {
it('creates the private temp dir EXCLUSIVELY: a pre-existing entry or a reparse point fails EEXIST, never receiving the temp grant', async () => {
try {
const { ctx, sandbox } = await setup()
const { sandbox } = await setup()
const ws = workspaceRoot()
scratch.push(ws)
// Pre-existing entry: exclusive mkdir throws EEXIST instead of adopting it.
const preexisting = shapedTempPath()
const preexisting = sessionTempDir(SessionId('preexisting'), ws)
mkdirSync(preexisting)
scratch.push(preexisting)
const preRecord = { sessionId: SessionId('preexisting'), workspace: ws, tempDir: preexisting }
ctx.sessions.create(SessionId('preexisting'), { seed: [recordEvent(preRecord)], meta: { cwd: ws } })
const prePolicy: SandboxPolicy = { mode: 'workspace-write', workspaceRoot: ws, sessionId: SessionId('preexisting') }
expect(() => sandbox.confine(['true'], prePolicy)).toThrow(/EEXIST/)
// The standing workspace grant is the intended end state and stays; the
@@ -316,11 +258,9 @@ describe('windows-acl write grants (LocalSandboxProvider)', () => {
// Reparse point: same EEXIST (exclusive mkdir never follows links).
const target = mkdtempSync(join(tmpdir(), 'dsh-acl-junction-target-'))
scratch.push(target)
const linkPath = shapedTempPath().replace(/abab$/, 'cdcd') // distinct well-shaped name
const linkPath = sessionTempDir(SessionId('reparse'), ws)
symlinkSync(target, linkPath)
scratch.push(linkPath)
const linkRecord = { sessionId: SessionId('reparse'), workspace: ws, tempDir: linkPath }
ctx.sessions.create(SessionId('reparse'), { seed: [recordEvent(linkRecord)], meta: { cwd: ws } })
const linkPolicy: SandboxPolicy = { mode: 'workspace-write', workspaceRoot: ws, sessionId: SessionId('reparse') }
expect(() => sandbox.confine(['true'], linkPolicy)).toThrow(/EEXIST/)
// Same workspace as the preexisting case: the standing workspace grant
@@ -333,11 +273,9 @@ describe('windows-acl write grants (LocalSandboxProvider)', () => {
// fails — the temp cleanup AggregateError propagates.
mockState.grants = []
mockState.disposeFailure = new Error('temp cleanup exploded')
const dupTemp = shapedTempPath().replace(/abab$/, 'efef')
const dupTemp = sessionTempDir(SessionId('temp-cleanup-fail'), ws)
mkdirSync(dupTemp)
scratch.push(dupTemp)
const dupRecord = { sessionId: SessionId('temp-cleanup-fail'), workspace: ws, tempDir: dupTemp }
ctx.sessions.create(SessionId('temp-cleanup-fail'), { seed: [recordEvent(dupRecord)], meta: { cwd: ws } })
const dupPolicy: SandboxPolicy = { mode: 'workspace-write', workspaceRoot: ws, sessionId: SessionId('temp-cleanup-fail') }
expect(() => sandbox.confine(['true'], dupPolicy)).toThrow(/temp grant materialization failed and its cleanup also failed/)
expect(mockState.grants).toHaveLength(1) // only the failed temp grant (the workspace grant was the map hit)
@@ -346,49 +284,17 @@ describe('windows-acl write grants (LocalSandboxProvider)', () => {
}
})
it('fails loud when the durable record\'s workspace does not match the resolved policy root', async () => {
try {
const { ctx, sandbox } = await setup()
const ws = workspaceRoot()
scratch.push(ws)
const mismatched = { sessionId: SessionId('stale'), workspace: '/somewhere-else', tempDir: shapedTempPath() }
ctx.sessions.create(SessionId('stale'), { seed: [recordEvent(mismatched)], meta: { cwd: ws } })
const policy: SandboxPolicy = { mode: 'workspace-write', workspaceRoot: ws, sessionId: SessionId('stale') }
expect(() => sandbox.confine(['true'], policy)).toThrow(/does not match the resolved policy root/)
expect(mockState.grants).toHaveLength(0)
} finally {
cleanup()
}
})
it('fails loud without the session store, and when the policy names a session the store does not hold', async () => {
try {
const bare = new Context()
await bare.plugin(LocalSandboxProvider, {})
const sandbox = bare.sandbox as LocalSandboxProvider
sandbox.internals = { platform: 'win32', windowsAclRunnerArgs: ['node', 'windows-acl-runner.js'] }
const policy: SandboxPolicy = { mode: 'read-only', workspaceRoot: '/ws', sessionId: SessionId('sess-none') }
expect(() => sandbox.confine(['true'], policy)).toThrow(/requires the session store/)
const { sandbox: withStore } = await setup()
expect(() => withStore.confine(['true'], policy)).toThrow(/no such session/)
} finally {
cleanup()
}
})
it('a grant failure mid-materialization disposes the failed grant and rethrows (AggregateError when the cleanup also fails)', async () => {
try {
const { ctx, sandbox } = await setup()
const { sandbox } = await setup()
const ws = workspaceRoot()
scratch.push(ws)
const session = ctx.sessions.create(SessionId('sess-add-fail'), { meta: { cwd: ws } })
scratch.push(sessionTempDir(SessionId('sess-add-fail'), ws))
const policy: SandboxPolicy = { mode: 'workspace-write', workspaceRoot: ws, sessionId: SessionId('sess-add-fail') }
// add() throws on the FIRST (workspace) grant: cleanup dispose() runs, original error propagates.
mockState.addFailure = new Error('grant exploded')
expect(() => sandbox.confine(['true'], policy)).toThrow('grant exploded')
scratch.push((session.events.at(-1)!.data as { tempDir: string }).tempDir)
expect(mockState.grants).toHaveLength(1)
expect(mockState.grants[0]!.disposed).toBe(true)
@@ -402,7 +308,29 @@ describe('windows-acl write grants (LocalSandboxProvider)', () => {
}
})
it('agentless calls stay self-managed: no --write-sid, the ambient temp root, no session store involved', async () => {
it('a temp add failure after the exclusive mkdir removed the half-created directory again', async () => {
try {
const { sandbox } = await setup()
const ws = workspaceRoot()
scratch.push(ws)
const tempDir = sessionTempDir(SessionId('sess-temp-add-fail'), ws)
const policy: SandboxPolicy = { mode: 'workspace-write', workspaceRoot: ws, sessionId: SessionId('sess-temp-add-fail') }
// The workspace grant succeeds; only the TEMP grant's add throws (the
// path-targeted failure keeps the workspace branch intact).
mockState.addFailurePath = tempDir
mockState.addFailure = new Error('temp add exploded')
expect(() => sandbox.confine(['true'], policy)).toThrow('temp add exploded')
expect(existsSync(tempDir)).toBe(false) // the half-created directory is removed again
expect(mockState.grants).toHaveLength(2)
expect(mockState.grants[0]!.disposed).toBe(false) // the standing workspace grant stays
expect(mockState.grants[1]!.disposed).toBe(true) // the failed temp grant self-disposes
} finally {
cleanup()
}
})
it('agentless calls stay self-managed: no --write-sid, the ambient temp root, no grants', async () => {
try {
const { sandbox, fiber } = await setup()
const policy: SandboxPolicy = { mode: 'workspace-write', workspaceRoot: '/ws' }
@@ -427,10 +355,9 @@ describe('windows-acl write grants (LocalSandboxProvider)', () => {
const { ctx, sandbox, fiber } = await setup()
const ws = workspaceRoot()
scratch.push(ws)
const session = ctx.sessions.create(SessionId('sess-dispose'), { meta: { cwd: ws } })
scratch.push(sessionTempDir(SessionId('sess-dispose'), ws))
const policy: SandboxPolicy = { mode: 'workspace-write', workspaceRoot: ws, sessionId: SessionId('sess-dispose') }
sandbox.confine(['true'], policy)
scratch.push((session.events.at(-1)!.data as { tempDir: string }).tempDir)
expect(mockState.grants).toHaveLength(2)
mockState.disposeFailure = new Error('revoke exploded')
@@ -444,11 +371,34 @@ describe('windows-acl write grants (LocalSandboxProvider)', () => {
}
})
it('sessionTempDir names are random and well-shaped (unpredictable, never derivable from the session id)', () => {
const a = basename(sessionTempDir())
const b = basename(sessionTempDir())
expect(a).not.toBe(b)
expect(a).toMatch(/^dsh-[0-9a-f]{16}$/)
expect(b).toMatch(/^dsh-[0-9a-f]{16}$/)
it('a failing private-temp removal at provider teardown is reported via ctx.logger.warn and never thrown into teardown', async () => {
try {
const { ctx, sandbox, fiber } = await setup()
const ws = workspaceRoot()
scratch.push(ws)
scratch.push(sessionTempDir(SessionId('sess-rm-fail'), ws))
const policy: SandboxPolicy = { mode: 'workspace-write', workspaceRoot: ws, sessionId: SessionId('sess-rm-fail') }
sandbox.confine(['true'], policy)
expect(mockState.grants).toHaveLength(2)
sandbox.internals.rmTempDir = () => { throw new Error('rm exploded') }
const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => undefined)
await fiber.dispose()
// Both grants dispose cleanly; only the directory removal fails.
expect(warn).toHaveBeenCalledWith(expect.stringContaining('cleanup completed with 1 failure(s)'))
expect(warn).toHaveBeenCalledWith(expect.objectContaining({ message: 'rm exploded' }))
} finally {
cleanup()
}
})
it('sessionTempDir derives the same well-shaped name for the same session and workspace, distinct otherwise', () => {
const base = sessionTempDir(SessionId('sess-a'), '/ws/a')
expect(basename(base)).toMatch(/^dsh-[0-9a-f]{16}$/)
expect(sessionTempDir(SessionId('sess-a'), '/ws/a')).toBe(base)
expect(sessionTempDir(SessionId('sess-b'), '/ws/a')).not.toBe(base) // different session
expect(sessionTempDir(SessionId('sess-a'), '/ws/b')).not.toBe(base) // different workspace
// The separator prevents id/workspace collisions from merging inputs.
expect(sessionTempDir(SessionId('ab'), '/ws/c')).not.toBe(sessionTempDir(SessionId('a'), '/ws/bc'))
})
})
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/sandbox/sandbox-windows-acl/README.md
README.md: 6f649f5dcc4ecf5c2cbbe90a687af25e0c6ecc9d
README.zh.md: 11c0fdd4b7431a280ff656ae4d2bd63b81e9dd06
README.md: b13160f7490878143c719ca617936b74ffd298af
README.zh.md: 9895449f6f416ad971bbbfff700c9fd62ad99c44
@@ -39,7 +39,7 @@ node runner.js --workspace <dir> --temp <dir> --mode <read-only|workspace-write>
The runner creates the restricted token, spawns the wrapped argv under it with the caller's stdio passed straight through (the caller's pipes, made inheritable around the spawn — Node clears stdio inheritability at startup, which raw spawns must compensate for), wraps the child in a `KILL_ON_JOB_CLOSE` job (a dead runner kills the child), ignores its own console Ctrl+C so the child handles its own, mirrors the child's exit code, and revokes its temp grant on exit (workspace ACEs stand). Every runner-side failure prints `windows-acl-run: <detail>` to stderr and exits 127 — the seam's `RUNNER_FAILURE_RULES` match that signature, so a runner refusal is never mistaken for a denial.
**Workspace grant reuse** (`--write-sid`): the write SID is DERIVED from the workspace path — no SID is stored anywhere (the previous per-session random SID and its tamper surface are gone). The seam still provisions ONE log-only `sandbox/acl-session` event per session (bound to the owning session id, validated at the fold) carrying the session's workspace binding and PRIVATE temp subdirectory: a resumed session replays the same temp dir, a fork mints a fresh one. The seam materializes the workspace ACE STANDING (once per workspace per server lifetime, never revoked — it is the reuse cache) and the temp ACE revocably (revoked on provider dispose), both lazily at the session's first confined execution. A fresh provision kicks an IMMEDIATE persistence flush right after the append (no write-behind debounce), so the record is durable within the flush latency — a crash inside that window can strand the private temp directory unrecorded, the one documented self-healing gap (the spawn seams are synchronous, so no await barrier exists between record and ACEs). Under `--write-sid` the runner neither grants nor revokes (`manageDacls: false`) — the flag's presence marks the seam-managed contract, its value is the derived SID; without it (standalone use) the runner self-manages with the SAME derived SID (workspace ACEs standing, temp ACE revocable per call). Re-granting after a restart is idempotent: `grantWrite` reads the current DACL and SKIPS the `SetNamedSecurityInfoW` apply when the exact ACE already stands (that apply eagerly re-propagates the identical ACE across the whole tree — minutes on large workspaces). Standing ACEs from an unclean shutdown need no garbage collection — they ARE the cache; the same derived SID re-hits them forever. Known cost: materializing the grant on a big workspace tree blocks for the full eager propagation once per workspace per machine (the first confined write ever on this host).
**Workspace grant reuse** (`--write-sid`): the write SID is DERIVED from the workspace path — no SID or temp-dir state is stored anywhere (the previous per-session random SID and its tamper surface are gone). The seam materializes the workspace ACE STANDING (once per workspace per server lifetime, never revoked — it is the reuse cache) and the temp ACE revocably (revoked on provider dispose), both lazily at the session's first confined execution. The session's private temp subdirectory is DERIVED from the session id + workspace (sha256, 16 hex) instead of stored: a resumed session derives the same directory and re-grants it (the exact-ACE skip keeps that O(1)), while a fork's different session id derives a fresh one. The directory is created EXCLUSIVELY — a pre-existing entry or a reparse point fails the first confined run loudly, so the grant never lands on a foreign object — and removed again on provider dispose. Under `--write-sid` the runner neither grants nor revokes (`manageDacls: false`) — the flag's presence marks the seam-managed contract, its value is the derived SID; without it (standalone use) the runner self-manages with the SAME derived SID (workspace ACEs standing, temp ACE revocable per call). Re-granting after a restart is idempotent: `grantWrite` reads the current DACL and SKIPS the `SetNamedSecurityInfoW` apply when the exact ACE already stands (that apply eagerly re-propagates the identical ACE across the whole tree — minutes on large workspaces). Standing ACEs from an unclean shutdown need no garbage collection — they ARE the cache; the same derived SID re-hits them forever. Known cost: materializing the grant on a big workspace tree blocks for the full eager propagation once per workspace per machine (the first confined write ever on this host).
Modes (the token's restricting-SID list follows the mode; the keep-alive group is logon SID + Everyone in BOTH modes — early DLL init dies with `0xC0000142` and CNG crashes pwsh with `0xE0434352` without them):
- `workspace-write` (logon SID, Everyone, write SID): the workspace and the session's PRIVATE temp subdirectory carry the write-SID Write grant; every other write is denied by the token intersection.
@@ -65,8 +65,8 @@ The koffi struct definitions assert their sizes against the probe at module load
- **Console isolation is unavailable.** Under the restricted token, children created with `CREATE_NO_WINDOW` / `CREATE_NEW_CONSOLE` die during DLL initialization with `STATUS_DLL_INIT_FAILED` (`0xC0000142`). The POC tried to fix this by adding the console logon SID (`S-1-2-1`) to the restricting list; on Windows 11 26200 `CreateWellKnownSid(WinLocalLogonSid)` fails with `ERROR_INVALID_PARAMETER` (87), the correct `WinConsoleLogonSid` yields a valid `S-1-2-1` but the child still dies, and the POC's final revision removed both the SID and console isolation. Children therefore share the host console; stdio redirection is pipe-based and unaffected.
- **ACL grants are standing directory mutations.** They persist if the process dies mid-run; workspace ACEs are standing BY DESIGN (never revoked — the reuse cache), temp ACEs are revoked by `dispose()` (`init()` also revokes an already-applied temp grant when a later step fails). The POC's documented manual cleanup (`icacls <dir> /remove '*S-1-4-…'`) fails on this platform with `ERROR_NONE_MAPPED` (1332) — revoke through this module instead. An unclean shutdown needs no self-healing for the workspace ACE: the derived SID re-hits the standing ACE on the next provision (skipping the apply); the write-SID ACE never accumulates a second identity per restart because the identity IS the workspace.
- **Granted directories must be caller-owned.** The owner's implicit `WRITE_DAC` is what lets the sandbox edit the DACL without elevation.
- **The temp grant follows `GetTempPathW`** — pass `tempDir` explicitly whenever possible. `GetTempPathW` reads the NATIVE environment block, which host runtimes that manage `process.env` through worker pools may not keep in sync (verified with vitest: a worker-side `process.env.TMP` change never reached the native block). The seam passes the session's PRIVATE subdirectory (`<temp>\dsh-<16 random hex>`, created exclusively — a pre-existing entry or reparse point fails loudly); a defaulted grant landing on the real temp dir inherits `(OI)(CI)` over every subdirectory of temp, silently widening the allowlist — point it at a per-sandbox directory instead.
- **The confined child's temp root is private per session** (workspace-write + `--write-sid`): the runner rewrites TMP/TEMP via `SetEnvironmentVariableW` to the session's private subdirectory before the spawn and the child inherits the rewritten block (bwrap `--tmpfs /tmp` semantics). Read-only leaves the ambient temp entries untouched — writes there are denied anyway. The subdirectory itself is plain `%TEMP%` litter with no garbage collection: OS temp hygiene reclaims it, and the record's determinism lets a later resume reuse it.
- **The temp grant follows `GetTempPathW`** — pass `tempDir` explicitly whenever possible. `GetTempPathW` reads the NATIVE environment block, which host runtimes that manage `process.env` through worker pools may not keep in sync (verified with vitest: a worker-side `process.env.TMP` change never reached the native block). The seam passes the session's PRIVATE subdirectory (`<temp>\dsh-<16 hex>` derived from the session id + workspace, created exclusively — a pre-existing entry or reparse point fails loudly); a defaulted grant landing on the real temp dir inherits `(OI)(CI)` over every subdirectory of temp, silently widening the allowlist — point it at a per-sandbox directory instead.
- **The confined child's temp root is private per session** (workspace-write + `--write-sid`): the runner rewrites TMP/TEMP via `SetEnvironmentVariableW` to the session's private subdirectory before the spawn and the child inherits the rewritten block (bwrap `--tmpfs /tmp` semantics). Read-only leaves the ambient temp entries untouched — writes there are denied anyway. The subdirectory is removed on provider dispose; after a crash it may survive as plain `%TEMP%` litter until OS temp hygiene (or manual removal) reclaims it — a later resume then fails loudly at the exclusive creation.
- **`whoami` and token-inspection cmdlets fail under the restricted token.** `GetTokenInformation` on the duplicate is partially unavailable to the child, so `whoami /all` reports errors — diagnostic noise of the restriction scheme, not an operational failure; the denial surfaces that matter (file writes) are unaffected.
## Model Experience
@@ -85,7 +85,7 @@ None directly; the denial surface belongs to the tool layer.
- **NULL-DACL directories are not identity-preserving under grant+revoke.** A directory with a NULL DACL (rare — Windows-created directories carry real DACLs) means "everyone full control"; `grantWrite` builds the new ACL from that null, and the revoke round-trip leaves an EMPTY (deny-all) DACL rather than the original NULL DACL. The POC shares the behavior; real workspace and temp directories carry real DACLs, so this stays a documented edge rather than a guarded path.
- **Piped stdio capture is impossible for confined grandchildren (the named-pipe default SD template).** libuv's pipe stdio uses NAMED pipes; `CreateNamedPipeW` without security attributes installs the Win32 layer's user-mode default SD template (built by KernelBase — owner/SYSTEM/Admins full, Everyone/ANONYMOUS read-only, the fixed template [MS documents](https://learn.microsoft.com/en-us/windows/win32/ipc/named-pipe-security-and-access-rights)) — NOT the token default DACL, which is what the kernel applies to a raw SD-null create — so the client-end open requests write access no restricting SID is granted: `spawn(..., { stdio: 'pipe' })` inside a confined process fails with EPERM, the POC-documented "no output redirection" boundary of WRITE_RESTRICTED tokens. Inherited (`inherit`/fd) and ignored (`ignore`) stdio spawns work, and anonymous pipes (CreatePipe — a token-default-DACL consumer, e.g. PowerShell pipelines) work because the restricted token's default DACL carries a full-access restricting-SID ACE (set at init). A confined process therefore cannot capture a grandchild's output through a pipe; tools that must capture output cannot run confined.
- **Grant materialization is an eager full-tree propagation.** `SetNamedSecurityInfoW` on a directory with inheritable ACEs walks every descendant immediately (NOT lazily per access — measured at tens of seconds on large workspace trees plus the real temp root). The per-workspace identity pays it once per workspace per machine (lazily at the first confined execution ever, skipped entirely on every later provision when the exact ACE stands). If a workspace is huge, the first confined write on this host is correspondingly slow.
- **Resuming one session concurrently in two server processes races the record.** The durable record lives in the session log; both processes read or provision it independently — the derived write SID is identical, the per-path lock keeps the DACL merges consistent, and the private temp dir race resolves by the last-written record winning for future resumes. Single-writer session usage (the normal deployment) never sees this.
- **Resuming one session concurrently in two server processes fails the second at its first confined write.** Both processes derive the same private temp directory; the second one's exclusive creation hits the first one's directory and fails loudly. Single-writer session usage (the normal deployment) never sees this.
- **Read-side confinement and network policy are out of scope** — `WRITE_RESTRICTED` intersects write accesses only; pair this backend with a read-side policy for stronger confinement.
- **Wide-directory and FAT-volume warnings are deferred; FAT-class targets stay writable.** The UI-side warnings for granting unusually wide directories or FAT-class (non-ACL) volumes are not yet implemented, and a FAT volume as a grant ROOT simply fails the grant loudly (no ACL support). A FAT-class target OUTSIDE the granted roots is different: it has no security descriptors, so the restricted token's write check passes (Everyone sits in both lists) and such targets are writable under BOTH confined modes. FAT is treated as a legacy residue — unsupported and not engineered around; this warn-only posture is documented here rather than mitigated.
- **Both confined modes run `pwsh` in ConstrainedLanguage.** The restricted token trips PowerShell's lockdown detection, so under `read-only` AND `workspace-write` the language mode is ConstrainedLanguage: `Add-Type` (C# compile, P/Invoke), non-core .NET static calls (`[System.IO.*]::`, `[math]::`, `[Environment]::`), COM objects, and reflection fail with `Cannot create type` / `Cannot invoke method` ("only core types") errors, and `$ExecutionContext.SessionState.LanguageMode = 'FullLanguage'` is refused. Core cmdlets, core types (`[string]`, `[datetime]`, `[regex]`, `[guid]`), `-f` formatting, and property access keep working. The `pwsh` tool description teaches this contract to the model; `danger-full-access` calls run unconfined at FullLanguage.
@@ -41,7 +41,7 @@ node runner.js --workspace <dir> --temp <dir> --mode <read-only|workspace-write>
runner 创建受限令牌,在它之下 spawn 包装后的 argv,调用者的 stdio 直接透传(调用者的管道在 spawn 前后被设为可继承——Node 在启动时清除 stdio 可继承性,裸 spawn 必须补偿这一点),把子进程包进 `KILL_ON_JOB_CLOSE` job(runner 死亡则子进程死亡),忽略自身的控制台 Ctrl+C 让子进程自行处理,镜像子进程的退出码,并在退出时撤销其临时授权(工作区 ACE 常驻)。每个 runner 侧失败都会向 stderr 打印 `windows-acl-run: <detail>` 并以 127 退出——seam 的 `RUNNER_FAILURE_RULES` 匹配该签名,因此 runner 拒绝永远不会被误判为拒绝授权。
**按工作区授权复用**`--write-sid`):写入 SID 从工作区路径**派生**——任何地方都不存储 SID(先前每会话随机 SID 及其篡改面已移除)。seam 仍会为每个会话只供给一条仅作日志记录的 `sandbox/acl-session` 事件(绑定其所属会话 id,在 fold 处校验),携带会话的工作区绑定与**私有**临时子目录:恢复的会话回放同一个临时目录,fork 则铸造一个新的。seam 把工作区 ACE **常驻**物化(每个工作区每服务器生命周期一次,绝不撤销——它就是复用缓存),把临时 ACE **可回收**物化(提供方 dispose 时撤销),两者都在会话首次受限执行时惰性进行。新供给在追加之后立即触发一次**即时**持久化 flush(无 write-behind 去抖),因此记录在 flush 延迟内即持久化——在该窗口内崩溃可能遗留未记录的私有临时目录,这是唯一记录在案的自愈缺口(spawn seam 是同步的,因此记录与 ACE 之间不存在 await 屏障)。传入 `--write-sid` 时 runner 既不授权也不回收(`manageDacls: false`)——该标志的存在标记 seam 管理的契约,其值即派生 SID;不传它(独立使用)时 runner 用**同一个**派生 SID 自行管理(工作区 ACE 常驻,临时 ACE 每次调用可回收)。重启后重新授权是幂等的:`grantWrite` 读取当前 DACL,当完全相同的 ACE 已存在时跳过 `SetNamedSecurityInfoW` 的应用(该应用会把相同的 ACE 急切地重新传播到整棵树——大型工作区上以分钟计)。异常关闭遗留的 ACE 无需垃圾回收——它们**就是**缓存;同一个派生 SID 永远重新命中它们。已知代价:在大型工作区树上物化授权会阻塞整次急切传播,每台机器每个工作区一次(该主机上的第一次受限写入)。
**按工作区授权复用**`--write-sid`):写入 SID 从工作区路径**派生**——任何地方都不存储 SID 或临时目录状态(先前每会话随机 SID 及其篡改面已移除)。seam 把工作区 ACE **常驻**物化(每个工作区每服务器生命周期一次,绝不撤销——它就是复用缓存),把临时 ACE **可回收**物化(提供方 dispose 时撤销),两者都在会话首次受限执行时惰性进行。会话的私有临时子目录由会话 id + 工作区**派生**sha256、16 位 hex)而非存储:恢复的会话派生同一个目录并重新授权(精确 ACE 跳过使这一步保持 O(1)),而 fork 的不同会话 id 会派生出一个全新的目录。该目录以**独占**方式创建——已存在条目或重解析点会让首次受限运行大声失败,因此授权永远不会落到外部对象上——并在提供方 dispose 时再次移除。传入 `--write-sid` 时 runner 既不授权也不回收(`manageDacls: false`)——该标志的存在标记 seam 管理的契约,其值即派生 SID;不传它(独立使用)时 runner 用**同一个**派生 SID 自行管理(工作区 ACE 常驻,临时 ACE 每次调用可回收)。重启后重新授权是幂等的:`grantWrite` 读取当前 DACL,当完全相同的 ACE 已存在时跳过 `SetNamedSecurityInfoW` 的应用(该应用会把相同的 ACE 急切地重新传播到整棵树——大型工作区上以分钟计)。异常关闭遗留的 ACE 无需垃圾回收——它们**就是**缓存;同一个派生 SID 永远重新命中它们。已知代价:在大型工作区树上物化授权会阻塞整次急切传播,每台机器每个工作区一次(该主机上的第一次受限写入)。
模式(令牌的 restricting-SID 列表随模式而变;保活组登录 SID + Everyone 在**两种**模式下都存在——没有它们早期 DLL 初始化会以 `0xC0000142` 死亡、CNG 会让 pwsh 以 `0xE0434352` 崩溃):
- `workspace-write`(登录 SID、Everyone、写入 SID):工作区与会话的**私有**临时子目录携带写入 SID 的 Write 授权;其余写全部被令牌交集拒绝。
@@ -67,8 +67,8 @@ koffi 结构体定义在模块加载时对照探针断言其大小,因此头
- **控制台隔离不可用。** 在受限令牌下,以 `CREATE_NO_WINDOW` / `CREATE_NEW_CONSOLE` 创建的子进程在 DLL 初始化期间以 `STATUS_DLL_INIT_FAILED``0xC0000142`)死亡。POC 尝试把控制台登录 SID(`S-1-2-1`)加入 restricting 列表来修复;在 Windows 11 26200 上 `CreateWellKnownSid(WinLocalLogonSid)``ERROR_INVALID_PARAMETER`87)失败,正确的 `WinConsoleLogonSid` 能产出合法 `S-1-2-1` 但子进程仍然死亡,POC 的最终修订同时移除了该 SID 与控制台隔离。子进程因此共享宿主控制台;stdio 重定向走管道,不受影响。
- **ACL 授权是对真实目录的驻留改动。** 进程中途死亡会留下授权;工作区 ACE **按设计**常驻(绝不撤销——复用缓存),临时 ACE 由 `dispose()` 撤销(后续步骤失败时 `init()` 也会撤销已应用的临时授权)。POC 注释里的手工清理命令(`icacls <dir> /remove '*S-1-4-…'`)在本平台实测失败(`ERROR_NONE_MAPPED` 1332)——请通过本模块回收。工作区 ACE 在异常关闭后无需自愈:派生 SID 在下一次供给时重新命中常驻 ACE(跳过应用);写入 SID ACE 不会因每次重启而累积第二个身份,因为身份**就是**工作区。
- **被授权目录必须由调用者拥有。** 所有者的隐式 `WRITE_DAC` 是沙盒无需提权即可编辑 DACL 的原因。
- **临时授权跟随 `GetTempPathW`**——尽可能显式传 `tempDir``GetTempPathW` 读取**原生**环境块,而通过 worker 池管理 `process.env` 的宿主运行时可能没有与之保持同步(vitest 实测:worker 侧的 `process.env.TMP` 变更从未到达原生块)。seam 传入会话的**私有**子目录(`<temp>\dsh-<16 位随机 hex>`,独占创建——已存在条目或重解析点会大声失败);默认授权落在真实临时目录上会让 `(OI)(CI)` 继承到临时目录的每个子目录,静默扩大白名单——请改指向每个沙盒的目录。
- **受限子进程的临时根目录按会话私有**workspace-write + `--write-sid`):runner 在 spawn 之前用 `SetEnvironmentVariableW` 把 TMP/TEMP 改写为会话的私有子目录,子进程继承改写后的环境块(bwrap `--tmpfs /tmp` 的语义)。read-only 保持环境中的临时目录条目不动——那里的写入反正会被拒绝。子目录本身只是 `%TEMP%` 下的普通垃圾、没有垃圾回收:OS 临时目录的日常清理会回收它,记录的确定性让之后的恢复可以复用它
- **临时授权跟随 `GetTempPathW`**——尽可能显式传 `tempDir``GetTempPathW` 读取**原生**环境块,而通过 worker 池管理 `process.env` 的宿主运行时可能没有与之保持同步(vitest 实测:worker 侧的 `process.env.TMP` 变更从未到达原生块)。seam 传入会话的**私有**子目录(`<temp>\dsh-<16 hex>`由会话 id + 工作区派生、独占创建——已存在条目或重解析点会大声失败);默认授权落在真实临时目录上会让 `(OI)(CI)` 继承到临时目录的每个子目录,静默扩大白名单——请改指向每个沙盒的目录。
- **受限子进程的临时根目录按会话私有**workspace-write + `--write-sid`):runner 在 spawn 之前用 `SetEnvironmentVariableW` 把 TMP/TEMP 改写为会话的私有子目录,子进程继承改写后的环境块(bwrap `--tmpfs /tmp` 的语义)。read-only 保持环境中的临时目录条目不动——那里的写入反正会被拒绝。子目录在提供方 dispose 时移除;崩溃后它可能作为普通 `%TEMP%` 垃圾存活,直到 OS 临时目录卫生(或手动删除)将其回收——之后的恢复会在独占创建处大声失败
- **受限令牌下 `whoami` 与令牌检查 cmdlet 会失败。** 子进程对复制令牌的 `GetTokenInformation` 部分不可用,因此 `whoami /all` 报错——这是限制方案的诊断噪音,不是运行故障;真正重要的拒绝面(文件写入)不受影响。
## Model Experience
@@ -87,7 +87,7 @@ koffi 结构体定义在模块加载时对照探针断言其大小,因此头
- **NULL-DACL 目录在 grant+revoke 往返下不保持身份。** 带 NULL DACL 的目录(罕见——Windows 创建的目录都带真实 DACL)意味着「所有人完全控制」;`grantWrite` 从该 null 构建新 ACL,撤销往返后留下的是 EMPTY(全部拒绝)DACL 而非原始 NULL DACL。POC 行为相同;真实工作区与临时目录都带真实 DACL,因此这仍是记录在案的边界情形而非守护路径。
- **受限孙进程的管道 stdio 捕获不可用(named pipe 的默认 SD 模板)。** libuv 的管道 stdio 用的是 NAMED pipe;不带安全属性调用 `CreateNamedPipeW` 时,其默认安全描述符不是内核的模板,而是 Win32 层在用户态安装的默认 SD 模板(由 KernelBase 构建——owner/SYSTEM/Admins 全权,Everyone/ANONYMOUS 只读,即 [MS 文档](https://learn.microsoft.com/en-us/windows/win32/ipc/named-pipe-security-and-access-rights)记载的固定模板)——**不是**令牌默认 DACL(后者才是内核在原始 SD-null 创建时应用的)——因此 client 端打开所请求的写访问没有任何 restricting SID 被授予:受限进程内 `spawn(..., { stdio: 'pipe' })` 以 EPERM 失败,这是 POC 记载的 WRITE_RESTRICTED「无法重定向输出」边界。继承(`inherit`/fd)与忽略(`ignore`stdio 的 spawn 可用;匿名管道(CreatePipe——令牌默认 DACL 的消费者,例如 PowerShell 的管道)因受限令牌默认 DACL 携带 restricting SID 全权 ACEinit 时写入)而可用。受限进程因此无法用管道捕获孙进程输出;必须捕获输出的工具无法在受限下运行。
- **授权物化是急切的全树传播。** 在带可继承 ACE 的目录上调用 `SetNamedSecurityInfoW` 会立即遍历每个后代(**不是**按访问惰性进行——大型工作区树上实测数十秒,加上真实临时根目录)。按工作区身份每台机器每个工作区只付一次(在首次受限执行时惰性进行,之后每次供给在精确 ACE 常驻时完全跳过)。如果工作区巨大,该主机上的第一次受限写入相应变慢。
- **两个服务器进程并发恢复同一会话会竞争记录。** 持久记录在会话日志中;两个进程独立读取或供给它——派生出的写入 SID 相同,每路径锁保持 DACL 合并一致,私有临时目录的竞争以后写记录对后续恢复生效而解决。单写者会话用法(常规部署)永远不会遇到。
- **两个服务器进程并发恢复同一会话时,第二个会在其首次受限写入处失败。** 两个进程派生同一个私有临时目录;第二个的独占创建撞上第一个的目录并大声失败。单写者会话用法(常规部署)永远不会遇到。
- **读侧隔离与网络策略不在范围内** —— `WRITE_RESTRICTED` 只交叉检查写访问;将此后端与读侧策略配对以获得更强隔离。
- **宽目录与 FAT 卷警告已推迟;FAT 类目标保持可写。** 对异常宽的目录或 FAT 类(非 ACL)卷的 UI 侧警告尚未实现,且 FAT 卷作为授权**根**只会大声失败(无 ACL 支持)。授权根**之外**的 FAT 类目标则不同:它没有安全描述符,因此受限令牌的写检查通过(Everyone 在两种列表中都在)——此类目标在**两种**受限模式下都可写。FAT 被视为遗留残留——不受支持、不围绕它设计;此处记录的是这种仅警告的立场,而非缓解措施。
- **两种受限模式都运行 ConstrainedLanguage 的 `pwsh`。** 受限令牌会触发 PowerShell 的锁定检测,因此在 `read-only` **和** `workspace-write` 下语言模式都是 ConstrainedLanguage`Add-Type`C# 编译、P/Invoke)、非核心 .NET 静态调用(`[System.IO.*]::``[math]::``[Environment]::`)、COM 对象与反射以 `Cannot create type` / `Cannot invoke method`(「only core types」)错误失败,且 `$ExecutionContext.SessionState.LanguageMode = 'FullLanguage'` 被拒绝。核心 cmdlet、核心类型(`[string]``[datetime]``[regex]``[guid]`)、`-f` 格式化与属性访问保持可用。`pwsh` 工具描述向模型传授该契约;`danger-full-access` 调用不受限地在 FullLanguage 下运行。