From 927b59e13817166be45db56ea8d8f91d4d5580c8 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Fri, 25 Sep 2026 18:26:12 +0800 Subject: [PATCH] fix(sandbox-windows-acl): make diagnosis repairs safe and observable --- apps/desktop/tests/acl-skill.built.e2e.ts | 77 +++ packages/sandbox/sandbox-local/src/index.ts | 2 +- .../sandbox-windows-acl/README.i18n.yaml | 8 +- .../sandbox/sandbox-windows-acl/README.md | 10 +- .../sandbox/sandbox-windows-acl/README.zh.md | 10 +- .../diagnose-windows-sandbox-acl/SKILL.md | 32 +- .../scripts/diagnose-windows-sandbox-acl.ps1 | 534 ++++++++++++------ .../sandbox-windows-acl/src/acl-skill.ts | 70 ++- .../sandbox/sandbox-windows-acl/src/index.ts | 3 +- .../tests/acl-skill.spec.ts | 32 +- .../tests/diagnose-script.spec.ts | 330 ++++++++++- .../tests/expected/denied-grant-report.txt | 8 + .../expected/parent-package-report.jsonl | 5 + .../build-exe-for-python-sdk-assets.spec.ts | 1 + scripts/build-exe-for-python-sdk.ts | 2 + scripts/run-gates.spec.ts | 1 + scripts/run-gates.ts | 1 + snapshots/session/headless.snapshot.ts | 5 + .../windows-acl-skill/session.v4.jsonl | 23 + .../session/windows-acl-skill/snapshot.yml | 9 + .../.dsh/skills/model-only-skill/SKILL.md | 7 + .../.dsh/skills/snapshot-skill/SKILL.md | 7 + .../.dsh/skills/user-only-skill/SKILL.md | 7 + 23 files changed, 951 insertions(+), 233 deletions(-) create mode 100644 apps/desktop/tests/acl-skill.built.e2e.ts create mode 100644 packages/sandbox/sandbox-windows-acl/tests/expected/denied-grant-report.txt create mode 100644 packages/sandbox/sandbox-windows-acl/tests/expected/parent-package-report.jsonl create mode 100644 snapshots/session/windows-acl-skill/session.v4.jsonl create mode 100644 snapshots/session/windows-acl-skill/snapshot.yml create mode 100644 snapshots/session/windows-acl-skill/workspace/.dsh/skills/model-only-skill/SKILL.md create mode 100644 snapshots/session/windows-acl-skill/workspace/.dsh/skills/snapshot-skill/SKILL.md create mode 100644 snapshots/session/windows-acl-skill/workspace/.dsh/skills/user-only-skill/SKILL.md diff --git a/apps/desktop/tests/acl-skill.built.e2e.ts b/apps/desktop/tests/acl-skill.built.e2e.ts new file mode 100644 index 0000000000..8b7b566f6d --- /dev/null +++ b/apps/desktop/tests/acl-skill.built.e2e.ts @@ -0,0 +1,77 @@ +/** External PowerShell must execute skill resources carried inside the Desktop archive. */ +import { spawnSync } from 'node:child_process' +import { cp, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { createRequire } from 'node:module' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { finished } from 'node:stream/promises' +import type { WriteStream } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { expect, it } from 'vitest' + +const require = createRequire(import.meta.url) +const builderRequire = createRequire(require.resolve('app-builder-lib/package.json')) +const { createPackageWithOptions } = builderRequire('@electron/asar') as { + createPackageWithOptions: (source: string, destination: string, options: object) => Promise +} +const packageDirectory = fileURLToPath(new URL('../../../packages/sandbox/sandbox-windows-acl/', import.meta.url)) + +it.skipIf(process.platform !== 'win32' || process.env.DSH_EXAMPLE_MODE !== 'lib')('executes the archived ACL skill through external PowerShell and disposes its copy', { retry: 0 }, async () => { + const root = await mkdtemp(join(tmpdir(), 'dsh-acl-asar-')) + try { + const source = join(root, 'package') + await mkdir(source) + for (const path of ['lib', 'assets', 'package.json']) await cp(join(packageDirectory, path), join(source, path), { recursive: true }) + const archive = join(root, 'app.asar') + await finished(await createPackageWithOptions(source, archive, {})) + const entry = join(root, 'probe.mjs') + await writeFile(entry, ` +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { existsSync } from 'node:fs'; +import { createRequire, registerHooks } from 'node:module'; +import { join } from 'node:path'; +import { pathToFileURL } from 'node:url'; +const [packageDirectory, archive, root] = process.argv.slice(2); +const require = createRequire(join(packageDirectory, 'package.json')); +// Only the package under test is archived; resolve its real dependencies from the built workspace. +const archiveUrl = pathToFileURL(archive).href; +registerHooks({ resolve(specifier, context, next) { + if (context.parentURL?.startsWith(archiveUrl) && !specifier.startsWith('.') && !specifier.startsWith('node:')) { + return next(pathToFileURL(require.resolve(specifier)).href, context); + } + return next(specifier, context); +} }); +const { Context } = await import(pathToFileURL(require.resolve('@deepseek-ai/cordis'))); +const { default: SkillRegistry } = await import(pathToFileURL(require.resolve('@deepseek-ai/dsh-skill'))); +const { registerAclDiagnosisSkill, ACL_DIAGNOSIS_SKILL } = await import(pathToFileURL(join(archive, 'lib/index.js'))); +const ctx = new Context(); +try { + await ctx.plugin(SkillRegistry); + const fiber = await ctx.plugin({ name: 'acl-skill-archive-probe', inject: ['skills'], apply: registerAclDiagnosisSkill }); + const skill = await ctx.skills.get(ACL_DIAGNOSIS_SKILL); + assert.equal(skill.resourceBase.kind, 'directory'); + const directory = skill.resourceBase.path; + assert.ok(!directory.includes('.asar')); + const output = execFileSync('pwsh', ['-NoProfile', '-NonInteractive', '-File', + join(directory, 'scripts/diagnose-windows-sandbox-acl.ps1'), '-Path', root], + { encoding: 'utf8', timeout: 30000, windowsHide: true }); + assert.ok(output.includes('READABLE=True')); + await fiber.dispose(); + assert.ok(!existsSync(directory)); + assert.deepEqual(await ctx.skills.list(), []); + process.stdout.write('ACL_SKILL_ASAR_OK'); +} finally { await ctx.fiber.dispose(); } +`) + const electron = require('electron') as string + const result = spawnSync(electron, [entry, packageDirectory, archive, root], { + env: { ...process.env, ELECTRON_RUN_AS_NODE: '1', TEMP: root, TMP: root }, encoding: 'utf8', timeout: 60_000, windowsHide: true, + }) + expect(result.error).toBeUndefined() + expect(result.signal).toBeNull() + expect(result.status, result.stderr).toBe(0) + expect(result.stdout).toBe('ACL_SKILL_ASAR_OK') + } finally { + await rm(root, { recursive: true, force: true }) + } +}) diff --git a/packages/sandbox/sandbox-local/src/index.ts b/packages/sandbox/sandbox-local/src/index.ts index 52718771b2..07c4a42f38 100644 --- a/packages/sandbox/sandbox-local/src/index.ts +++ b/packages/sandbox/sandbox-local/src/index.ts @@ -300,7 +300,7 @@ export class LocalSandboxProvider extends SandboxProvider { // optional: the sandbox must not require the skill registry. /* v8 ignore next 3 -- Windows-only registration; the Linux coverage lane cannot take this branch */ if (process.platform === 'win32') { - ctx.inject(['skills'], skillsCtx => registerAclDiagnosisSkill(skillsCtx)) + ctx.inject(['skills'], (skillsCtx) => { registerAclDiagnosisSkill(skillsCtx) }) } // The temp grants are revoked with the provider: a clean server // shutdown leaves no temp ACEs behind (workspace ACEs stand by design — diff --git a/packages/sandbox/sandbox-windows-acl/README.i18n.yaml b/packages/sandbox/sandbox-windows-acl/README.i18n.yaml index 0813beda01..896ea14a9f 100644 --- a/packages/sandbox/sandbox-windows-acl/README.i18n.yaml +++ b/packages/sandbox/sandbox-windows-acl/README.i18n.yaml @@ -27,8 +27,8 @@ en: 289e65bddf20dd79 zh: 44b9fcedf944546a /deepseek-ai-dsh-sandbox-windows-acl/use-this-package/failures-and-recovery: - en: bd847a7890748b9d - zh: 25ef02776687d8c3 + en: 966f167031348e70 + zh: 5bb476df9aee0e3a /deepseek-ai-dsh-sandbox-windows-acl/understand-the-implementation: en: c2cde86c85c2c619 zh: a29a114e591f9d3f @@ -54,8 +54,8 @@ en: bbb19594a2c2e4d4 zh: 075a65d9b9182aad /deepseek-ai-dsh-sandbox-windows-acl/model-experience/kv-cache-effect: - en: 8dc637e4c015ff15 - zh: 10db9e10111108cc + en: 817eb1b7de13872e + zh: 06fe175e41e7459b /deepseek-ai-dsh-sandbox-windows-acl/known-limitations-and-deferred-work: en: 2311808c0ded8564 zh: 845ddb2408c861fd diff --git a/packages/sandbox/sandbox-windows-acl/README.md b/packages/sandbox/sandbox-windows-acl/README.md index fa905a51bc..c513b5cd87 100644 --- a/packages/sandbox/sandbox-windows-acl/README.md +++ b/packages/sandbox/sandbox-windows-acl/README.md @@ -75,7 +75,13 @@ Temp isolation is per live session/workspace pair: sessions sharing a workspace `init()` throws on any Win32 failure — the child is never spawned unrestricted. A runner that fails before executing the command prints `windows-acl-run: ` to stderr and exits 127, which the seam's runner-failure rules classify as a broken sandbox rather than a denial. Cleanup is best-effort by design: `dispose()` attempts every temp revocation and aggregates failures into an `AggregateError`. -A denial this backend cannot explain — the child cannot open an object it was granted, or the provisioning call itself fails — is diagnosed by the `diagnose-windows-sandbox-acl` skill bundled in `assets/`, whose script reads unless a repair switch is passed and classifies the failing path and its ancestors before anything changes. `registerAclDiagnosisSkill` contributes it to the session catalog wherever `dsh-sandbox-local` composes on Windows, and the script's `-Fix` and `-GrantFullControl` modes are the only supported repairs: both require `-AllowRoot`, refuse any target outside it, never change an owner, and need an unconfined caller because a confined child can neither open an object carrying a package SID nor write a DACL. +A denial this backend cannot explain — the child cannot open an object it was granted, or the provisioning call itself fails — is diagnosed by the `diagnose-windows-sandbox-acl` skill bundled in `assets/`. `registerAclDiagnosisSkill` contributes it wherever `dsh-sandbox-local` composes with a skill registry on Windows. Registration copies the resources into a private temporary directory readable by external PowerShell, including in ASAR and SEA deployments; fiber disposal unregisters the provider and removes its copy. Missing packaged assets fail registration. + +The script diagnoses without changing files or ACLs; effective `WRITE_DAC` and `WRITE_OWNER` checks open existing objects without modifying contents. `-Fix` removes package allow ACEs and `-GrantFullControl` adds the caller's missing rights, including when a package ACE is present. Both require an unconfined caller and `WRITE_DAC`, enforce a containing `-AllowRoot`, reject every reparse point in the target's ancestor chain, preserve ownership and save recovery files under `-Out` before mutation. The emitted `-Restore` command writes only the saved DACL and its inheritance protection, preserves the SACL, enforces the same path restrictions and remains usable after the session ends. Apply rollback commands in reverse repair order. Refused or failed mutations exit nonzero. + +Every run emits `REPORT` JSON lines describing observations, decisions, operation attempts and results with their reasons, followed by verification and summary records. ACL observations include allow and deny ACEs with SID, rights and inheritance, native listings, effective access and read errors; unknown values remain distinct from absent permissions. Mutations report their start before executing, so a caught exception retains prior results and recovery commands. Operation completion does not imply successful verification or automatic rollback. The [bundled skill](assets/diagnose-windows-sandbox-acl/SKILL.md) defines how the model interprets these records and reports remaining uncertainty. + +Inspection visits the requested object and each ancestor through the filesystem root. Each ACL observation's `path` identifies the inspected object; the classification's `details.packageObjects` lists objects carrying package allow ACEs without establishing the cause of the original failure. The [parent-package example](tests/expected/parent-package-report.jsonl) retains the fixture paths and shows selected fields, with `fixturePackageAces` projecting only the synthetic test SID from `aces`; host-owned ACEs and ancestors are omitted. The [failed-grant example](tests/expected/denied-grant-report.txt) retains operation paths and reasons. ----- @@ -162,7 +168,7 @@ Indirectly, through [`dsh-bash-sandbox`](../../shell/bash-sandbox/README.md), [` #### KV Cache effect -One extra catalog entry on Windows: the skill's `description` (500 characters) rides in the catalog, while its body and script load only when the model invokes it. The denial surface itself stays in the tool layer. +One extra catalog entry on Windows: the skill's description enters context with the catalog, and the body enters only when invoked. Resource extraction happens at registration and does not add script contents to model context. The denial surface itself stays in the tool layer. ## Known Limitations and Deferred Work diff --git a/packages/sandbox/sandbox-windows-acl/README.zh.md b/packages/sandbox/sandbox-windows-acl/README.zh.md index feda48e15e..7ebc10bcad 100644 --- a/packages/sandbox/sandbox-windows-acl/README.zh.md +++ b/packages/sandbox/sandbox-windows-acl/README.zh.md @@ -75,7 +75,13 @@ rmSync(tempDir, { recursive: true, force: true }) `init()` 在任何 Win32 失败时抛出——子进程绝不会不受限制地 spawn。执行命令前失败的 runner 会向 stderr 打印 `windows-acl-run: ` 并以 127 退出,seam 的 runner 失败规则将其归类为损坏的沙箱,而非拒绝。清理按设计尽力而为:`dispose()` 会尝试全部临时撤销并把失败聚合为 `AggregateError`。 -此后端无法解释的拒绝——子进程打不开本已授权的对象,或授权调用本身失败——交给 `assets/` 中随包发布的 `diagnose-windows-sandbox-acl` 技能诊断:该脚本除非传入修复开关,否则只读,并先对待查路径及其祖先做出分类,再动任何东西。只要 `dsh-sandbox-local` 在 Windows 上被组合,`registerAclDiagnosisSkill` 就会把它注册进会话目录;脚本的 `-Fix` 与 `-GrantFullControl` 是唯一受支持的修复,两者都要求 `-AllowRoot`、拒绝其外的任何目标、绝不更改所有者,并且需要不受限的调用者——受限子进程既打不开带包 SID 的对象,也写不了 DACL。 +此后端无法解释的拒绝——子进程打不开本已授权的对象,或授权调用本身失败——交给 `assets/` 中随包发布的 `diagnose-windows-sandbox-acl` 技能诊断。只要 `dsh-sandbox-local` 在 Windows 上与技能注册表一起组合,`registerAclDiagnosisSkill` 就会注册它。注册时会把资源复制到外部 PowerShell 可读取的私有临时目录,ASAR 和 SEA 部署也适用;fiber 释放时注销提供者并删除副本。缺少打包资源会导致注册失败。 + +脚本诊断时不修改文件或 ACL;有效 `WRITE_DAC` 和 `WRITE_OWNER` 检查只打开已有对象,不修改内容。`-Fix` 删除包 SID 的允许 ACE,`-GrantFullControl` 补充调用者缺少的权限,即使包 ACE 同时存在也可执行。两者都要求不受限的调用者及 `WRITE_DAC`,强制目标位于 `-AllowRoot` 内,拒绝目标祖先链上的所有重解析点,保持所有者不变,并在修改前将恢复文件保存到 `-Out`。输出的 `-Restore` 命令只写回原 DACL 及其继承保护状态,保留 SACL,执行相同的路径限制,且在会话结束后仍可使用。多次修复应按相反顺序回滚。被拒绝或失败的修改均以非零状态退出。 + +每次执行都会输出 `REPORT` JSON 行,说明观察、决策、操作尝试及结果和各自原因,并记录验证结果与最终摘要。ACL 观察包含允许和拒绝 ACE 的 SID、权限与继承信息、原生列表、有效权限及读取错误;未知值与权限缺失明确区分。修改在执行前报告开始状态,捕获异常后仍保留此前结果和恢复命令。操作完成不代表验证成功或已经自动回滚。[内置技能](assets/diagnose-windows-sandbox-acl/SKILL.md) 规定模型如何解读这些记录并报告尚未确认的事项。 + +检查会从请求对象逐级访问祖先,直到文件系统根目录。每条 ACL 观察的 `path` 标识实际检查的对象;分类结果的 `details.packageObjects` 列出包含包允许 ACE 的对象,但不能据此确认原始失败的原因。[父目录包 SID 示例](tests/expected/parent-package-report.jsonl) 保留测试目录路径并展示选定字段,其中 `fixturePackageAces` 只从 `aces` 提取合成测试 SID,省略机器自带的 ACE 和祖先目录。[授权失败示例](tests/expected/denied-grant-report.txt) 保留操作路径和原因。 ----- @@ -162,7 +168,7 @@ seam 先把确定性工作区 SID 的 ACE 常驻物化(每个工作区每服 #### KV Cache 影响 -Windows 上多一个目录条目:技能的 `description`(500 字符)随目录进入上下文,其正文与脚本仅在模型调用该技能时加载。拒绝面本身仍属于工具层。 +Windows 上多一个目录条目:技能描述随目录进入上下文,正文只在调用时进入。资源在注册时提取,不会把脚本内容加入模型上下文。拒绝面本身仍属于工具层。 ## 已知限制与延期工作 diff --git a/packages/sandbox/sandbox-windows-acl/assets/diagnose-windows-sandbox-acl/SKILL.md b/packages/sandbox/sandbox-windows-acl/assets/diagnose-windows-sandbox-acl/SKILL.md index 08c19e17d0..97acd07a53 100644 --- a/packages/sandbox/sandbox-windows-acl/assets/diagnose-windows-sandbox-acl/SKILL.md +++ b/packages/sandbox/sandbox-windows-acl/assets/diagnose-windows-sandbox-acl/SKILL.md @@ -42,7 +42,9 @@ Run the bundled script over the failing path. It reads ACLs with .NET and native pwsh -File scripts/diagnose-windows-sandbox-acl.ps1 -Path ``` -It reports, for the target and every ancestor: any AppContainer package SID (`S-1-15-2-*`) as explicit or inherited, other `S-1-15-*` SIDs (reported but inert), the owner, whether the current user holds `WRITE_DAC` and `WRITE_OWNER`, whether the ACL could be read at all, and the caller's integrity level plus any sandbox markers in the environment. +It reports every observed allow and deny ACE on the target and its ancestors, including SID, rights, inheritance and propagation flags, plus the native ACL listing, owner, effective `WRITE_DAC` and `WRITE_OWNER`, caller integrity and sandbox marker names. Well-known groups `S-1-15-2-1` and `S-1-15-2-2` are reported but are not individual package ACEs eligible for removal. Access checks open existing objects without changing contents; Windows accounts for group membership, deny ACEs and inheritance. An unreadable or unrecognized value is unknown, not absent. + +Every `REPORT` line contains a JSON record with `kind`, `operation`, `path`, `status`, `reason` and `details`. Read observations and reasons alongside the verdict: a deny ACE's presence alone does not prove that it caused the failure. Decisions explain skips and refusals. Actions report `started` before execution and `completed` or `failed` afterward; completion means the operation ran, while a separate verification reports whether the intended result was observed. A final summary lists attempted operations, outcomes and available recovery commands, including after a caught exception. If execution ends before a completion or summary record, treat the result as unconfirmed. The failing API names the family. DSH's fail-closed errors carry the API and the exact Win32 code, so read the error rather than guessing: @@ -56,13 +58,15 @@ The script needs a caller that can open the object. `read-only` pwsh cannot run ## Step 2 — Read the verdict -| Package SID present | Owner is the current user | Verdict | Action | +For `UNREADABLE` or `INCOMPLETE`, report the failed observation and its error; do not treat missing evidence as missing permissions or proceed with a repair. `NOT_THIS_CLASS` only rules out the conditions the script inspected, not every cause of the original failure. + +| Package SID present | Effective permissions | Verdict | Action | |---|---|---|---| -| yes | yes | a foreign AppContainer ACE is the blocker | remove the ACE (Step 4) | -| yes | no | both problems at once | grant full control first, then remove the ACE; the grant needs Windows elevation | -| no | yes, and the DACL lacks `WRITE_OWNER` | a precondition DSH documents is unmet | grant full control (Step 4); ownership already carries `WRITE_DAC`, so no elevation is needed | -| no | no | a precondition this caller cannot repair | hand the user the single command to run from an elevated terminal (Step 4) | -| no | yes and the DACL is complete | not this class | say so and stop; report what was actually found | +| yes | the target has both rights and every affected object has `WRITE_DAC` | package ACE found | remove the ACE (Step 4), then verify the original failure | +| yes | either condition above is unmet | both problems at once | grant full control on the affected object first, then remove the ACE; if `WRITE_DAC` is missing, the user must run the grant from an elevated terminal | +| no | `WRITE_DAC` present, `WRITE_OWNER` missing | a provisioning precondition is unmet | grant full control (Step 4) | +| no | `WRITE_DAC` missing | this caller cannot repair the DACL | hand the user the single command to run from an elevated terminal (Step 4) | +| no | both rights present | not this class | say so and stop; report what was actually found | ## Step 3 — Explain, and apologize @@ -79,7 +83,7 @@ Two things must reach the user either way: Two repairs exist, and both run through the same script so that no ACL is edited by hand. -**Remove a foreign package-SID ACE.** It grants nothing to anyone yet blocks every reader below Medium: +**Remove a conflicting package-SID ACE.** This also removes that package's access, so explain which SID and permissions will be removed: ```powershell pwsh -File scripts/diagnose-windows-sandbox-acl.ps1 -Path -AllowRoot -Out -Fix @@ -93,11 +97,13 @@ pwsh -File scripts/diagnose-windows-sandbox-acl.ps1 -Path -AllowRoot (buffer).Label.Sid; byte count = Marshal.ReadByte(GetSidSubAuthorityCount(sid)); return Marshal.ReadInt32(GetSidSubAuthority(sid, (uint)(count - 1))); @@ -119,6 +190,10 @@ public static int Level(IntPtr token) { } '@ } +} + +function Get-IntegritySid { + try { $level = [Dsh.TokenInfo]::Level([System.Security.Principal.WindowsIdentity]::GetCurrent().Token) switch ($level) { 0 { return 'S-1-16-0 (Untrusted)' } @@ -126,9 +201,10 @@ public static int Level(IntPtr token) { 8192 { return 'S-1-16-8192 (Medium)' } 12288 { return 'S-1-16-12288 (High)' } 16384 { return 'S-1-16-16384 (System)' } - default { return 'unknown' } + default { return "S-1-16-$level (unrecognized level)" } } } catch { + Write-Report observation integrity '' unknown 'The token integrity level could not be read; do not infer that the caller is elevated or confined.' @{ error = (Get-HResultChain $_.Exception) } return 'unknown' } } @@ -158,8 +234,53 @@ function Test-UnderRoot { return $c.StartsWith($r + '\', [System.StringComparison]::OrdinalIgnoreCase) } +function Get-RepairRefusal { + param([string]$FullPath, [string]$Root) + if (-not (Test-UnderRoot -FullPath $FullPath -Root $Root)) { return "$FullPath is outside -AllowRoot" } + $danger = Test-DangerousRoot -FullPath $FullPath + if ($danger) { return "$FullPath is a $danger" } + # Checking every component also covers a junction used as AllowRoot itself. + foreach ($component in (Get-Ancestors -FullPath $FullPath)) { + $item = Get-Item -LiteralPath $component -Force + if (($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0) { + return "$FullPath traverses a reparse point: $component" + } + } + return $null +} + +function Save-AclBackup { + param([string]$FullPath, [string]$Directory, [string]$Root) + $fullDirectory = [System.IO.Path]::GetFullPath($Directory) + if (-not (Test-Path -LiteralPath $fullDirectory)) { + Invoke-ReportedOperation create_backup_directory $fullDirectory 'The requested recovery directory does not exist; create it before writing backup files.' files { + New-Item -ItemType Directory -Path $fullDirectory | Out-Null + } + } + $backup = Join-Path $fullDirectory ('acl-backup-{0}.txt' -f ([guid]::NewGuid().ToString('N'))) + $record = $backup + '.json' + # The skill's extracted directory expires with its registration. Recovery must + # remain runnable from the backup directory after that registration is gone. + $restoreScript = $backup + '.ps1' + $command = "pwsh -NoProfile -File '{0}' -Path '{1}' -AllowRoot '{2}' -Restore '{3}'" -f + $restoreScript.Replace("'", "''"), $FullPath.Replace("'", "''"), ([System.IO.Path]::GetFullPath($Root)).Replace("'", "''"), $record.Replace("'", "''") + Write-Report decision backup $FullPath selected 'All recovery files must be written successfully before attempting the ACL change.' @{ files = @($backup, $record, $restoreScript, ($backup + '.rollback.txt')) } + Invoke-ReportedOperation backup $FullPath 'Save the original DACL and an independent recovery command before changing permissions.' files { + $output = @(icacls $FullPath /save $backup 2>&1) + if ($LASTEXITCODE -ne 0) { throw "Could not back up the DACL (icacls exit $LASTEXITCODE): $($output -join "`n")" } + @{ Path = $FullPath; Dacl = (Get-Acl -LiteralPath $FullPath).GetSecurityDescriptorSddlForm([System.Security.AccessControl.AccessControlSections]::Access) } | + ConvertTo-Json | Set-Content -LiteralPath $record -Encoding utf8 + Copy-Item -LiteralPath $PSCommandPath -Destination $restoreScript + $command | Set-Content -LiteralPath ($backup + '.rollback.txt') + } + $script:recoveries.Add(@{ path = $FullPath; backup = $backup; record = $record; script = $restoreScript; command = $command }) + Write-Report observation recovery $FullPath available 'These files can restore the saved DACL; no rollback has been executed.' $script:recoveries[-1] + Write-Line ('BACKUP {0} -> {1}' -f $FullPath, $backup) + Write-Line ('ROLLBACK {0}' -f $command) +} + function Get-ObjectFacts { - param([string]$FullPath, [System.Security.Principal.WindowsIdentity]$Identity, [string]$MeSid) + param([string]$FullPath, [string]$MeSid) $facts = [ordered]@{ Object = $FullPath Readable = $false @@ -169,9 +290,11 @@ function Get-ObjectFacts { Owner = '' OwnerIsMe = $false MyRights = '' - HasWriteDac = $false - HasWriteOwner = $false - LowLabel = $false + HasWriteDac = $null + HasWriteOwner = $null + Aces = @() + Errors = @() + LowLabel = $null AclLines = @() } try { @@ -182,14 +305,15 @@ function Get-ObjectFacts { $facts.Readable = $true } catch { $facts.Error = Get-HResultChain -Exception $_.Exception + Write-Report observation inspect_acl $FullPath unreadable 'The ACL read failed; permissions and the cause of denial remain unknown.' @{ error = $facts.Error } return $facts } - foreach ($rule in $acl.Access) { - # Orphaned and capability SIDs have no NTAccount form and Translate throws on - # them, so fall back to the reference's own text. - $reference = $rule.IdentityReference - $sid = if ($reference -is [System.Security.Principal.SecurityIdentifier]) { $reference.Value } - else { try { $reference.Translate([System.Security.Principal.SecurityIdentifier]).Value } catch { $reference.Value } } + foreach ($rule in $acl.GetAccessRules($true, $true, [System.Security.Principal.SecurityIdentifier])) { + $sid = $rule.IdentityReference.Value + $facts.Aces += [ordered]@{ + sid = $sid; type = [string]$rule.AccessControlType; rights = [string]$rule.FileSystemRights + inherited = $rule.IsInherited; inheritance = [string]$rule.InheritanceFlags; propagation = [string]$rule.PropagationFlags + } if ($sid -match $PACKAGE_SID -and $rule.AccessControlType -eq 'Allow') { $facts.PackageAces += ('SID={0} INHERITED={1} INHERITABLE={2} RIGHTS={3}' -f $sid, $rule.IsInherited, $rule.InheritanceFlags, $rule.FileSystemRights) } elseif ($sid -match '^S-1-15-' -and $sid -notmatch $PACKAGE_SID) { @@ -197,30 +321,34 @@ function Get-ObjectFacts { } if ($sid -eq $MeSid -and $rule.AccessControlType -eq 'Allow') { $facts.MyRights = ($facts.MyRights + ';' + [string]$rule.FileSystemRights).Trim(';') - # FileSystemRights names these ChangePermissions (WRITE_DAC) and - # TakeOwnership (WRITE_OWNER); there is no WriteDac/WriteOwner member. - if (($rule.FileSystemRights -band [System.Security.AccessControl.FileSystemRights]::ChangePermissions) -ne 0) { $facts.HasWriteDac = $true } - if (($rule.FileSystemRights -band [System.Security.AccessControl.FileSystemRights]::TakeOwnership) -ne 0) { $facts.HasWriteOwner = $true } } } try { $facts.Owner = $acl.GetOwner([System.Security.Principal.SecurityIdentifier]).Value $facts.OwnerIsMe = ($facts.Owner -eq $MeSid) - # Ownership carries an implicit READ_CONTROL and WRITE_DAC: a target the caller - # owns stays writable even when no ACE names the caller with WriteDac. - if ($facts.OwnerIsMe) { $facts.HasWriteDac = $true } } catch { $facts.Owner = 'unreadable' + $facts.Errors += @{ operation = 'read_owner'; error = (Get-HResultChain $_.Exception) } + } + foreach ($check in @(@{ field = 'HasWriteDac'; mask = 0x40000 }, @{ field = 'HasWriteOwner'; mask = 0x80000 })) { + try { $facts[$check.field] = [Dsh.TokenInfo]::HasAccess($FullPath, $check.mask) } + catch { $facts.Errors += @{ operation = $check.field; error = (Get-HResultChain $_.Exception) } } } # The mandatory label lives in the SACL. Reading the SACL needs a privilege while # icacls prints the label without one, but icacls renders it by name, which is # localized: try the integrity SID first and keep the English name as a fallback. try { - $facts.AclLines = @(icacls $FullPath) + $facts.AclLines = @(icacls $FullPath 2>&1 | ForEach-Object { [string]$_ }) + if ($LASTEXITCODE -ne 0) { throw "icacls exit ${LASTEXITCODE}: $($facts.AclLines -join "`n")" } $text = $facts.AclLines -join "`n" - $facts.LowLabel = ($text -match $LOW_LABEL_SID) -or ($text -match 'Mandatory Label') + # An unrecognized localized label is unknown, not evidence of a Low label. + if ($text -match $LOW_LABEL_SID -or $text -match 'Mandatory Label\\Low Mandatory Level') { $facts.LowLabel = $true } } catch { - $facts.LowLabel = $false + $facts.Errors += @{ operation = 'icacls'; error = (Get-HResultChain $_.Exception) } + } + Write-Report observation inspect_acl $FullPath $(if ($facts.Errors.Count) { 'partial' } else { 'read' }) 'Read the ACL and check effective WRITE_DAC and WRITE_OWNER; observed ACEs alone do not identify which rule caused a denial.' @{ + owner = $facts.Owner; writeDac = $facts.HasWriteDac; writeOwner = $facts.HasWriteOwner + aces = $facts.Aces; nativeListing = @($facts.AclLines | ForEach-Object { $_.Trim() } | Where-Object { $_ }); lowLabel = $facts.LowLabel; errors = $facts.Errors } return $facts } @@ -240,153 +368,229 @@ function Get-Ancestors { # --- main --------------------------------------------------------------- -$identity = Get-CurrentIdentity -$meSid = $identity.User.Value -$caller = Get-CallerFacts -Write-Line ('CALLER SID={0} INTEGRITY={1} SANDBOX_MARKERS={2}' -f $meSid, $caller.Integrity, (($caller.Markers | Sort-Object) -join ',')) - -if ($Fix -and $GrantFullControl) { - Write-Line 'REFUSED -Fix and -GrantFullControl are separate repairs; run one at a time' - exit 2 -} -if ($Fix -or $GrantFullControl) { - foreach ($required in @('AllowRoot', 'Out')) { - if (-not (Get-Variable -Name $required -ValueOnly)) { - Write-Line ('REFUSED the requested repair requires -{0}' -f $required) - exit 2 - } - } - if (-not (Test-Path -LiteralPath $Out)) { New-Item -ItemType Directory -Path $Out | Out-Null } -} - +$operations = [System.Collections.Generic.List[object]]::new() +$recoveries = [System.Collections.Generic.List[object]]::new() $fixed = 0 $granted = 0 $refused = 0 +$restored = 0 +$exitCode = 0 +$observationFailures = 0 +$currentPath = '' +$mode = if ($Restore) { 'restore' } elseif ($GrantFullControl) { 'grant' } elseif ($Fix) { 'fix' } else { 'diagnose' } -foreach ($requested in $Path) { - $full = [System.IO.Path]::GetFullPath($requested) - Write-Line ('PATH={0}' -f $full) - if (-not (Test-Path -LiteralPath $full)) { - Write-Line ' MISSING' - Write-Line 'VERDICT=NOT_THIS_CLASS' - continue +try { + Write-Report invocation $mode '' started 'Inspect the requested paths before deciding whether the requested operation can run.' @{ + paths = $Path; allowRoot = $AllowRoot; outputDirectory = $Out; recoveryRecord = $Restore; fix = $Fix.IsPresent; grantFullControl = $GrantFullControl.IsPresent } + $identity = Get-CurrentIdentity + $meSid = $identity.User.Value + Invoke-ReportedOperation initialize '' 'Load read-only access checks and DACL-only writes before inspecting permissions.' none { Initialize-NativeApi } + $caller = Get-CallerFacts + Write-Line ('CALLER SID={0} INTEGRITY={1} SANDBOX_MARKERS={2}' -f $meSid, $caller.Integrity, (($caller.Markers | Sort-Object) -join ',')) + Write-Report observation caller '' read 'The caller token determines effective access; sandbox marker names do not prove token permissions.' @{ sid = $meSid; integrity = $caller.Integrity; sandboxMarkers = $caller.Markers } - $packageTargets = @() - foreach ($ancestor in (Get-Ancestors -FullPath $full)) { - if (-not (Test-Path -LiteralPath $ancestor)) { continue } - $f = Get-ObjectFacts -FullPath $ancestor -Identity $identity -MeSid $meSid - Write-Line (' OBJECT={0} READABLE={1}{2}' -f $f.Object, $f.Readable, $(if ($f.Readable) { '' } else { ' ERROR=' + $f.Error })) - if ($f.Readable) { - Write-Line (' OWNER={0} IS_CURRENT_USER={1} MY_RIGHTS=[{2}] WRITE_DAC={3} WRITE_OWNER={4} LOW_LABEL={5}' -f $f.Owner, $f.OwnerIsMe, $f.MyRights, $f.HasWriteDac, $f.HasWriteOwner, $f.LowLabel) - foreach ($ace in $f.PackageAces) { Write-Line (' PACKAGE_ACE {0}' -f $ace) } - foreach ($sid in ($f.OtherAppContainerSids | Sort-Object -Unique)) { Write-Line (' OTHER_S1_15 SID={0} (reported only)' -f $sid) } + if (@(@($Fix.IsPresent, $GrantFullControl.IsPresent, [bool]$Restore) | Where-Object { $_ }).Count -gt 1) { + throw [System.ArgumentException]::new('-Fix, -GrantFullControl and -Restore are separate operations; run one at a time') + } + if ($Fix -or $GrantFullControl -or $Restore) { + $requiredArguments = if ($Restore) { @('AllowRoot') } else { @('AllowRoot', 'Out') } + foreach ($required in $requiredArguments) { + if (-not (Get-Variable -Name $required -ValueOnly)) { + throw [System.ArgumentException]::new("The requested repair requires -$required") + } } - if ($f.PackageAces.Count -gt 0) { $packageTargets += $f } + if ($Restore -and $Path.Count -ne 1) { throw [System.ArgumentException]::new('-Restore requires exactly one -Path') } } - # Verdict: a confirmed package ACE is the blocker; otherwise an unmet - # precondition; otherwise this is not the class of failure this skill owns. - # The precondition is judged on the requested path itself. Ancestors above the - # tree DSH grants are not part of that grant, so their ownership and rights would - # otherwise mark every healthy path as a precondition failure. - $targetFacts = Get-ObjectFacts -FullPath $full -Identity $identity -MeSid $meSid - $unreadable = -not $targetFacts.Readable - $needsPrecondition = (-not $unreadable) -and $targetFacts.PackageAces.Count -eq 0 -and - ((-not $targetFacts.OwnerIsMe) -or (-not $targetFacts.HasWriteDac) -or (-not $targetFacts.HasWriteOwner)) + foreach ($requested in $Path) { + $currentPath = $requested + $full = [System.IO.Path]::GetFullPath($requested) + $currentPath = $full + Write-Line ('PATH={0}' -f $full) + if (-not (Test-Path -LiteralPath $full)) { + Write-Line ' MISSING' + Write-Line 'VERDICT=NOT_THIS_CLASS' + Write-Decision $mode $full skipped 'The requested path does not exist; no ACL was read or changed for it.' + if ($mode -ne 'diagnose') { $refused++ } + continue + } - if ($packageTargets.Count -gt 0) { - $blocked = @($packageTargets | Where-Object { (-not $_.OwnerIsMe) -or (-not $_.HasWriteDac) }) - Write-Line ('VERDICT={0}' -f $(if ($blocked.Count -gt 0) { 'BOTH' } else { 'CULPRIT' })) - } elseif ($unreadable) { - Write-Line 'VERDICT=UNREADABLE' - } elseif ($needsPrecondition) { - Write-Line 'VERDICT=PRECONDITION' - } else { - Write-Line 'VERDICT=NOT_THIS_CLASS' - } + $packageTargets = @() + $targetFacts = $null + foreach ($ancestor in (Get-Ancestors -FullPath $full)) { + if (-not (Test-Path -LiteralPath $ancestor)) { continue } + $f = Get-ObjectFacts -FullPath $ancestor -MeSid $meSid + if ($ancestor -eq $full) { $targetFacts = $f } + Write-Line (' OBJECT={0} READABLE={1}{2}' -f $f.Object, $f.Readable, $(if ($f.Readable) { '' } else { ' ERROR=' + $f.Error })) + if ($f.Readable) { + Write-Line (' OWNER={0} IS_CURRENT_USER={1} MY_RIGHTS=[{2}] WRITE_DAC={3} WRITE_OWNER={4} LOW_LABEL={5}' -f $f.Owner, $f.OwnerIsMe, $f.MyRights, $f.HasWriteDac, $f.HasWriteOwner, $f.LowLabel) + foreach ($ace in $f.PackageAces) { Write-Line (' PACKAGE_ACE {0}' -f $ace) } + foreach ($sid in ($f.OtherAppContainerSids | Sort-Object -Unique)) { Write-Line (' OTHER_S1_15 SID={0} (reported only)' -f $sid) } + } + if ($f.PackageAces.Count -gt 0) { $packageTargets += $f } + } - if ($GrantFullControl) { - if ($unreadable) { Write-Line 'GRANT_REFUSED the object could not be read; the grant needs an unconfined caller'; $refused++; continue } - if ($targetFacts.PackageAces.Count -gt 0) { Write-Line 'GRANT_REFUSED remove the package SID ACE first with -Fix'; $refused++; continue } - if ($targetFacts.HasWriteDac -and $targetFacts.HasWriteOwner) { Write-Line ('GRANT_SKIPPED {0} already carries WRITE_DAC and WRITE_OWNER' -f $full); continue } - if (-not (Test-UnderRoot -FullPath $full -Root $AllowRoot)) { Write-Line ('GRANT_REFUSED {0} is outside -AllowRoot' -f $full); $refused++; continue } - $danger = Test-DangerousRoot -FullPath $full - if ($danger) { Write-Line ('GRANT_REFUSED {0} is a {1}' -f $full, $danger); $refused++; continue } - $item = Get-Item -LiteralPath $full -Force - if ($item.LinkType) { Write-Line ('GRANT_REFUSED {0} is a reparse point ({1})' -f $full, $item.LinkType); $refused++; continue } - $backup = Join-Path $Out ('acl-backup-{0}.txt' -f ([guid]::NewGuid().ToString('N'))) - $before = @(icacls $full) - $before | Set-Content -LiteralPath $backup - Write-Line ('BACKUP {0} -> {1}' -f $full, $backup) - # Address the grant by SID so no account name has to resolve, and leave the - # owner alone: ownership transfer reaches far beyond this fault. - icacls $full /grant "*${meSid}:(F)" | Out-Null - $code = $LASTEXITCODE - $after = Get-ObjectFacts -FullPath $full -Identity $identity -MeSid $meSid - if ($code -eq 0 -and $after.HasWriteDac -and $after.HasWriteOwner) { - Write-Line ('GRANTED {0} SID={1}' -f $full, $meSid); $granted++ - Write-Line ('ROLLBACK icacls "{0}" /remove:g "*{1}"' -f $full, $meSid) + # The precondition is judged on the requested path itself. Ancestors above the + # tree DSH grants are not part of that grant, so their ownership and rights would + # otherwise mark every healthy path as a precondition failure. + if ($null -eq $targetFacts) { throw "The requested path disappeared before its ACL could be inspected: $full" } + $unreadable = -not $targetFacts.Readable + $needsPrecondition = (-not $unreadable) -and + ((-not $targetFacts.HasWriteDac) -or (-not $targetFacts.HasWriteOwner)) + + if ($targetFacts.Errors.Count -gt 0) { + $verdict = 'INCOMPLETE' + $reason = 'Some observations failed; missing evidence is not evidence that a right is absent or a repair is safe.' + } elseif ($packageTargets.Count -gt 0) { + $blocked = @($packageTargets | Where-Object { -not $_.HasWriteDac }) + $verdict = if ($needsPrecondition -or $blocked.Count -gt 0) { 'BOTH' } else { 'CULPRIT' } + $reason = 'Package allow ACEs were observed. Required access checks determine whether the caller can perform the requested repair; other causes remain possible.' + } elseif ($unreadable) { + $verdict = 'UNREADABLE' + $reason = 'The requested ACL could not be read; its entries and the cause of denial are unknown.' + } elseif ($needsPrecondition) { + $verdict = 'PRECONDITION' + $reason = 'The caller cannot open the requested object with both WRITE_DAC and WRITE_OWNER. The reported allow and deny ACEs are evidence, not an attribution to one rule.' } else { - Write-Line ('GRANT_FAILED {0} exit={1}; an unelevated caller cannot grant WRITE_DAC on a directory it does not own, so one elevated run of this command is required' -f $full, $code) - $refused++ + $verdict = 'NOT_THIS_CLASS' + $reason = 'No package allow ACE was observed and both required rights are available. Other ACL restrictions and causes of the original failure are not ruled out.' } - continue - } + Write-Line ('VERDICT={0}' -f $verdict) + Write-Report decision classify $full $verdict $reason @{ writeDac = $targetFacts.HasWriteDac; writeOwner = $targetFacts.HasWriteOwner; packageObjects = @($packageTargets | ForEach-Object { $_.Object }) } - if (-not $Fix) { continue } - - if ($unreadable) { - Write-Line 'FIX_REFUSED the object could not be read; repair needs an unconfined caller' - $refused++ - continue - } - foreach ($target in $packageTargets) { - if (-not (Test-UnderRoot -FullPath $target.Object -Root $AllowRoot)) { - Write-Line ('FIX_REFUSED {0} is outside -AllowRoot' -f $target.Object); $refused++; continue + if ($mode -eq 'diagnose') { + Write-Decision diagnose $full skipped 'No mutation mode was requested; all reported ACLs were left unchanged.' + continue } - $danger = Test-DangerousRoot -FullPath $target.Object - if ($danger) { Write-Line ('FIX_REFUSED {0} is a {1}' -f $target.Object, $danger); $refused++; continue } - $item = Get-Item -LiteralPath $target.Object -Force - if ($item.LinkType) { Write-Line ('FIX_REFUSED {0} is a reparse point ({1})' -f $target.Object, $item.LinkType); $refused++; continue } - if (-not ($target.OwnerIsMe -and $target.HasWriteDac)) { - Write-Line ('FIX_REFUSED {0} needs WRITE_DAC first: grant the current user full control (WRITE_DAC and WRITE_OWNER); taking ownership alone is not enough' -f $target.Object) + if ($targetFacts.Errors.Count -gt 0) { + Write-Decision $mode $full refused 'Required observations are incomplete; no repair was attempted for this path.' + $refused++; continue + } + + if ($Restore) { + $refusal = Get-RepairRefusal -FullPath $full -Root $AllowRoot + if ($refusal) { Write-Line ('RESTORE_REFUSED {0}' -f $refusal); Write-Decision restore $full refused $refusal; $refused++; continue } + $saved = Invoke-ReportedOperation read_recovery $Restore 'Read the recovery record and verify it belongs to the requested path before restoring its DACL.' none { + Get-Content -LiteralPath $Restore -Raw | ConvertFrom-Json + } + if ($saved.Path -isnot [string] -or $saved.Path -ine $full -or $saved.Dacl -isnot [string]) { + Write-Line 'RESTORE_REFUSED backup does not describe the requested path' + Write-Decision restore $full refused 'The backup does not describe the requested path; no DACL write was attempted.' + $refused++; continue + } + if (-not $targetFacts.HasWriteDac) { Write-Line 'RESTORE_REFUSED the caller lacks WRITE_DAC'; Write-Decision restore $full refused 'Effective WRITE_DAC is absent; the saved DACL cannot be written by this caller.'; $refused++; continue } + Invoke-ReportedOperation restore_dacl $full 'Restore the requested backup DACL and inheritance protection, preserving owner and SACL.' acl { + [Dsh.TokenInfo]::SetDacl($full, $saved.Dacl) + } + $actual = Invoke-ReportedOperation read_restored_dacl $full 'Read the restored DACL to compare it with the saved record.' none { + (Get-Acl -LiteralPath $full).GetSecurityDescriptorSddlForm([System.Security.AccessControl.AccessControlSections]::Access) + } + Write-Report verification restore $full $(if ($actual -eq $saved.Dacl) { 'verified' } else { 'failed' }) 'Compare the observed DACL with the recovery record after writing it.' @{ expectedDacl = $saved.Dacl; actualDacl = $actual } + if ($actual -ne $saved.Dacl) { Write-Line 'RESTORE_FAILED the restored DACL differs from the backup'; $refused++; continue } + Write-Line ('RESTORED {0}' -f $full); $restored++ + continue + } + + if ($GrantFullControl) { + if ($unreadable) { Write-Line 'GRANT_REFUSED the object could not be read; the grant needs an unconfined caller'; Write-Decision grant $full refused 'The ACL is unreadable, so a preserving grant cannot be constructed.'; $refused++; continue } + $refusal = Get-RepairRefusal -FullPath $full -Root $AllowRoot + if ($refusal) { Write-Line ('GRANT_REFUSED {0}' -f $refusal); Write-Decision grant $full refused $refusal; $refused++; continue } + if ($targetFacts.HasWriteDac -and $targetFacts.HasWriteOwner) { Write-Line ('GRANT_SKIPPED {0} already carries WRITE_DAC and WRITE_OWNER' -f $full); Write-Decision grant $full skipped 'Effective WRITE_DAC and WRITE_OWNER are already available; no grant or backup is needed.'; continue } + if (-not $targetFacts.HasWriteDac) { Write-Line 'GRANT_REFUSED the caller lacks WRITE_DAC; ask the user to run this command from an elevated terminal'; Write-Decision grant $full refused 'Effective WRITE_DAC is absent; this caller cannot change the DACL. Elevation may still be blocked by a deny ACE.'; $refused++; continue } + Save-AclBackup -FullPath $full -Directory $Out -Root $AllowRoot + # AddAccessRule preserves explicit denies; icacls /grant can remove a deny + # for the same principal. Write only the DACL, leaving owner and SACL intact. + $grantAcl = Get-Acl -LiteralPath $full + $grantAcl.AddAccessRule([System.Security.AccessControl.FileSystemAccessRule]::new( + [System.Security.Principal.SecurityIdentifier]::new($meSid), + [System.Security.AccessControl.FileSystemRights]::FullControl, + [System.Security.AccessControl.AccessControlType]::Allow)) + Invoke-ReportedOperation grant_dacl $full "WRITE_OWNER is missing and WRITE_DAC is available; add a FullControl allow ACE for $meSid while preserving deny ACEs, owner and SACL." acl { + [Dsh.TokenInfo]::SetDacl($full, $grantAcl.GetSecurityDescriptorSddlForm([System.Security.AccessControl.AccessControlSections]::Access)) + } + $after = Get-ObjectFacts -FullPath $full -MeSid $meSid + $verified = $after.Readable -and $after.Errors.Count -eq 0 -and $after.HasWriteDac -and $after.HasWriteOwner + Write-Report verification grant $full $(if ($verified) { 'verified' } else { 'failed' }) 'The DACL write completed; recheck effective access before claiming that provisioning can succeed. No automatic rollback is performed.' @{ + before = @{ writeDac = $targetFacts.HasWriteDac; writeOwner = $targetFacts.HasWriteOwner } + after = @{ writeDac = $after.HasWriteDac; writeOwner = $after.HasWriteOwner } + recovery = $recoveries[-1].command + } + if ($verified) { + Write-Line ('GRANTED {0} SID={1}' -f $full, $meSid); $granted++ + } else { + Write-Line ('GRANT_FAILED {0}; effective WRITE_DAC and WRITE_OWNER were not both confirmed; use the saved rollback and report the error' -f $full) + $refused++ + } + continue + } + + if (-not $Fix) { continue } + + if ($unreadable) { + Write-Line 'FIX_REFUSED the object could not be read; repair needs an unconfined caller' + Write-Decision fix $full refused 'The requested ACL could not be read; no package removal was attempted.' $refused++ continue } - $backup = Join-Path $Out ('acl-backup-{0}.txt' -f ([guid]::NewGuid().ToString('N'))) - $before = @(icacls $target.Object) - $before | Set-Content -LiteralPath $backup - Write-Line ('BACKUP {0} -> {1}' -f $target.Object, $backup) - foreach ($ace in $target.PackageAces) { - if ($ace -notmatch 'SID=(S-1-15-2-[\d-]+)') { continue } - $sid = $Matches[1] - icacls $target.Object /remove:g "*$sid" | Out-Null - $code = $LASTEXITCODE - $after = Get-ObjectFacts -FullPath $target.Object -Identity $identity -MeSid $meSid - # Prove the removal was surgical. icacls prints the object's first ACE on the - # same line as the path, so strip the path first: otherwise removing an ACE - # that led that line reads as a change to every following line. - $keepBefore = @($before | ForEach-Object { - $line = $_.Trim() - if ($line.StartsWith($target.Object, [System.StringComparison]::OrdinalIgnoreCase)) { $line = $line.Substring($target.Object.Length).Trim() } - $line - } | Where-Object { $_ -notmatch $PACKAGE_SID }) - $keepAfter = @($after.AclLines | ForEach-Object { - $line = $_.Trim() - if ($line.StartsWith($target.Object, [System.StringComparison]::OrdinalIgnoreCase)) { $line = $line.Substring($target.Object.Length).Trim() } - $line - } | Where-Object { $_ -notmatch $PACKAGE_SID }) - $collateral = (($keepBefore -join "`n") -eq ($keepAfter -join "`n")) - if ($code -eq 0 -and $after.PackageAces.Count -eq 0 -and $collateral) { - Write-Line ('FIXED {0} SID={1}' -f $target.Object, $sid); $fixed++ - Write-Line ('ROLLBACK icacls "{0}" /grant "*{1}:(X,RA)"' -f $target.Object, $sid) - } else { - Write-Line ('FIX_FAILED {0} SID={1} exit={2} collateral_change={3}' -f $target.Object, $sid, $code, (-not $collateral)) + if ($packageTargets.Count -eq 0) { Write-Decision fix $full skipped 'No package allow ACE was observed on the inspected objects; no ACL change or backup is needed.' } + foreach ($target in $packageTargets) { + $refusal = Get-RepairRefusal -FullPath $target.Object -Root $AllowRoot + if ($refusal) { Write-Line ('FIX_REFUSED {0}' -f $refusal); Write-Decision fix $target.Object refused $refusal; $refused++; continue } + if ($target.Errors.Count -gt 0) { Write-Decision fix $target.Object refused 'The ACL observations are incomplete; collateral changes could not be verified.'; $refused++; continue } + if (-not $target.HasWriteDac) { + Write-Line ('FIX_REFUSED {0} needs WRITE_DAC; ask the user to run the full-control grant from an elevated terminal first' -f $target.Object) + Write-Decision fix $target.Object refused 'Effective WRITE_DAC is absent; removing a package allow ACE requires that right.' $refused++ + continue + } + $before = $target.AclLines + Save-AclBackup -FullPath $target.Object -Directory $Out -Root $AllowRoot + foreach ($ace in $target.PackageAces) { + if ($ace -notmatch 'SID=(S-1-15-2-[\d-]+)') { continue } + $sid = $Matches[1] + $repairPath = $target.Object + Invoke-ReportedOperation remove_package_allow $repairPath "Remove the observed package allow ACE for $sid as requested by -Fix; preserve deny ACEs and all other principals." acl { + $output = @(icacls $repairPath /remove:g "*$sid" 2>&1) + if ($LASTEXITCODE -ne 0) { throw "icacls removal exit ${LASTEXITCODE}: $($output -join "`n")" } + } + $after = Get-ObjectFacts -FullPath $target.Object -MeSid $meSid + # icacls prefixes only the first ACE with the path, so compare entries + # without that prefix when checking for collateral changes. + $keepBefore = @($before | ForEach-Object { + $line = $_.Trim() + if ($line.StartsWith($target.Object, [System.StringComparison]::OrdinalIgnoreCase)) { $line = $line.Substring($target.Object.Length).Trim() } + $line + } | Where-Object { $_ -notmatch $PACKAGE_SID }) + $keepAfter = @($after.AclLines | ForEach-Object { + $line = $_.Trim() + if ($line.StartsWith($target.Object, [System.StringComparison]::OrdinalIgnoreCase)) { $line = $line.Substring($target.Object.Length).Trim() } + $line + } | Where-Object { $_ -notmatch $PACKAGE_SID }) + $collateral = (($keepBefore -join "`n") -eq ($keepAfter -join "`n")) + $verified = $after.Readable -and $after.Errors.Count -eq 0 -and $after.PackageAces.Count -eq 0 -and $collateral + Write-Report verification fix $target.Object $(if ($verified) { 'verified' } else { 'failed' }) 'The removal command completed; verify that package allow ACEs disappeared and other ACL listing entries remained unchanged. No automatic rollback is performed.' @{ + removedSid = $sid; remainingPackageAces = $after.PackageAces; otherEntriesUnchanged = $collateral; recovery = $recoveries[-1].command + } + if ($verified) { + Write-Line ('FIXED {0} SID={1}' -f $target.Object, $sid); $fixed++ + } else { + Write-Line ('FIX_FAILED {0} SID={1} collateral_change={2}' -f $target.Object, $sid, (-not $collateral)) + $refused++ + } } } } +} catch { + $exitCode = if ($_.Exception -is [System.ArgumentException]) { 2 } else { 1 } + Write-Report error $mode $currentPath stopped 'Execution stopped after an exception. Completed operations remain completed; an interrupted write may have changed state. No automatic rollback was performed.' @{ error = (Get-HResultChain $_.Exception); location = $_.InvocationInfo.PositionMessage } +} finally { + if ($refused -gt 0 -and $exitCode -eq 0) { $exitCode = 2 } + Write-Line ('SUMMARY FIXED={0} GRANTED={1} REFUSED={2} RESTORED={3}' -f $fixed, $granted, $refused, $restored) + $status = if ($exitCode -ne 0) { 'failed' } elseif ($observationFailures -gt 0) { 'partial' } else { 'completed' } + Write-Report summary $mode $currentPath $status 'Operation completion records API execution; verification records the observed result. Only rerunning the original confined operation can confirm its failure is resolved.' @{ + exitCode = $exitCode; fixed = $fixed; granted = $granted; refused = $refused; restored = $restored + operations = @($operations.ToArray()); recoveries = @($recoveries.ToArray()); automaticRollback = $false; observationFailures = $observationFailures + } } - -if ($Fix -or $GrantFullControl) { Write-Line ('SUMMARY FIXED={0} GRANTED={1} REFUSED={2}' -f $fixed, $granted, $refused) } +exit $exitCode diff --git a/packages/sandbox/sandbox-windows-acl/src/acl-skill.ts b/packages/sandbox/sandbox-windows-acl/src/acl-skill.ts index 201cc51e91..67c5475ca7 100644 --- a/packages/sandbox/sandbox-windows-acl/src/acl-skill.ts +++ b/packages/sandbox/sandbox-windows-acl/src/acl-skill.ts @@ -1,17 +1,16 @@ /** * Registers the bundled Windows sandbox ACL diagnosis skill. * - * The skill ships beside the backend whose failures it explains, so the assets - * resolve relative to this module exactly as `skill-office` resolves its own. The - * command-line side of the ACL backend never imports it: only the always-composed - * local sandbox provider calls {@link registerAclDiagnosisSkill}, and only where - * this backend can be the active one. + * The provider owns a private filesystem copy of its resources so external + * PowerShell can execute them even when the package lives inside ASAR or SEA. + * Disposing the registration removes both the provider and its resource copy. * * @module @deepseek-ai/dsh-sandbox-windows-acl */ -import { readFileSync } from 'node:fs' -import { readFile } from 'node:fs/promises' +import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs' +import { readFile, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' import { join } from 'node:path' import { fileURLToPath } from 'node:url' import type { Context } from '@deepseek-ai/cordis' @@ -38,31 +37,40 @@ function parseSkill(raw: string, path: string): { description: string; content: } /** - * Register the bundled diagnosis skill on a session's skill registry. + * Register the bundled diagnosis skill with a private resource directory owned by this fiber. + * Missing or invalid packaged assets fail registration; disposal removes the directory. * @param ctx - Context carrying the skill registry. */ export function registerAclDiagnosisSkill(ctx: Context): void { - const directory = fileURLToPath(new URL(`../assets/${ACL_DIAGNOSIS_SKILL}/`, import.meta.url)) - const locator = join(directory, 'SKILL.md') - const { description } = parseSkill(readFileSync(locator, 'utf8'), locator) - const candidate: SkillCandidate = { - name: ACL_DIAGNOSIS_SKILL, - description, - invocation: { modelInvocable: true, userInvocable: true }, - provider: PROVIDER, - source: 'bundled', - rank: BUNDLED_SKILL_RANK, - resourceBase: { kind: 'directory', path: directory }, - locator, - } - const provider: SkillProvider = { - name: PROVIDER, - list: () => Promise.resolve([candidate]), - async get(entry, options) { - const { rank: _rank, locator: entryPath, ...summary } = entry - const raw = await readFile(entryPath as string, { encoding: 'utf8', signal: options.signal }) - return { ...summary, content: parseSkill(raw, entryPath as string).content } - }, - } - ctx.skills.registerProvider(() => provider) + const packaged = fileURLToPath(new URL(`../assets/${ACL_DIAGNOSIS_SKILL}/`, import.meta.url)) + ctx.effect(function* () { + const directory = mkdtempSync(join(tmpdir(), 'dsh-acl-skill-')) + yield async () => { await rm(directory, { recursive: true, force: true }) } + mkdirSync(join(directory, 'scripts')) + for (const path of ['SKILL.md', 'scripts/diagnose-windows-sandbox-acl.ps1']) { + writeFileSync(join(directory, path), readFileSync(join(packaged, path)), { flag: 'wx', mode: 0o600 }) + } + const locator = join(directory, 'SKILL.md') + const { description } = parseSkill(readFileSync(locator, 'utf8'), locator) + const candidate: SkillCandidate = { + name: ACL_DIAGNOSIS_SKILL, + description, + invocation: { modelInvocable: true, userInvocable: true }, + provider: PROVIDER, + source: 'bundled', + rank: BUNDLED_SKILL_RANK, + resourceBase: { kind: 'directory', path: directory }, + locator, + } + const provider: SkillProvider = { + name: PROVIDER, + list: () => Promise.resolve([candidate]), + async get(entry, options) { + const { rank: _rank, locator: entryPath, ...summary } = entry + const raw = await readFile(entryPath as string, { encoding: 'utf8', signal: options.signal }) + return { ...summary, content: parseSkill(raw, entryPath as string).content } + }, + } + yield ctx.skills.registerProvider(() => provider) + }, 'Windows ACL diagnosis skill resources') } diff --git a/packages/sandbox/sandbox-windows-acl/src/index.ts b/packages/sandbox/sandbox-windows-acl/src/index.ts index efda04a854..5de5d47b72 100644 --- a/packages/sandbox/sandbox-windows-acl/src/index.ts +++ b/packages/sandbox/sandbox-windows-acl/src/index.ts @@ -58,6 +58,7 @@ import * as abi from './win32-abi.ts' export { AclWriteGrant } from './grant.ts' export { assertTempRootOutsideWorkspace } from './path-boundary.ts' export { tempWriteSid, workspaceWriteSid } from './workspace-sid.ts' +export { ACL_DIAGNOSIS_SKILL, registerAclDiagnosisSkill } from './acl-skill.ts' /** Construction options: the workspace/temp allowlists and their distinct SID identities. */ export interface AclSandboxOptions { /** Directories the confined child may write into (must exist and be caller-owned). */ @@ -159,8 +160,6 @@ function freeSidBestEffort( * `manageDacls: false` the caller owns the grants (the sandbox seam's grant * reuse): init() applies none and dispose() revokes none. */ -export { ACL_DIAGNOSIS_SKILL, registerAclDiagnosisSkill } from './acl-skill.ts' - export class AclSandbox { /** Absolute writable directories (constructor-validated). */ readonly writableDirs: string[] diff --git a/packages/sandbox/sandbox-windows-acl/tests/acl-skill.spec.ts b/packages/sandbox/sandbox-windows-acl/tests/acl-skill.spec.ts index 8ff7b6cdf3..e5cf2173cc 100644 --- a/packages/sandbox/sandbox-windows-acl/tests/acl-skill.spec.ts +++ b/packages/sandbox/sandbox-windows-acl/tests/acl-skill.spec.ts @@ -1,11 +1,8 @@ -/** - * The Windows ACL diagnosis skill ships as assets, so its catalog entry and the - * body the registry hands a model are asserted here rather than through a session. - * The registration is exercised on a real skill registry fiber, which is also what - * proves disposal removes the candidate. - */ +/** The bundled skill owns its registry candidate and extracted resource directory. */ import { Context } from '@deepseek-ai/cordis' +import { existsSync, readFileSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' import SkillRegistry from '@deepseek-ai/dsh-skill' import { describe, expect, it } from 'vitest' import { ACL_DIAGNOSIS_SKILL, registerAclDiagnosisSkill } from '../src/acl-skill.ts' @@ -34,6 +31,10 @@ describe('bundled Windows ACL diagnosis skill', () => { const loaded = await ctx.skills.get(ACL_DIAGNOSIS_SKILL) expect(loaded?.resourceBase).toMatchObject({ kind: 'directory' }) + if (loaded?.resourceBase?.kind !== 'directory') throw new Error('Missing physical skill resource directory') + const resourceDirectory = loaded.resourceBase.path + expect(readFileSync(join(resourceDirectory, 'scripts/diagnose-windows-sandbox-acl.ps1'), 'utf8')) + .toBe(readFileSync(new URL('../assets/diagnose-windows-sandbox-acl/scripts/diagnose-windows-sandbox-acl.ps1', import.meta.url), 'utf8')) // The body names the bundled script — the repair path the model must use // instead of editing ACLs by hand. expect(loaded?.content).toContain('scripts/diagnose-windows-sandbox-acl.ps1') @@ -41,6 +42,25 @@ describe('bundled Windows ACL diagnosis skill', () => { await fiber.dispose() expect(await ctx.skills.list()).toEqual([]) + expect(existsSync(resourceDirectory)).toBe(false) + } finally { + await ctx.fiber.dispose() + } + }) + + it.each([ + ['missing frontmatter', '# Invalid skill', 'has no YAML frontmatter'], + ['non-object metadata', '---\nnull\n---\nBody', 'has no description'], + ['empty description', '---\ndescription: ""\n---\nBody', 'has no description'], + ])('rejects an extracted skill with %s', async (_name, raw, message) => { + const ctx = new Context() + try { + await ctx.plugin(SkillRegistry) + await ctx.plugin({ name: 'acl-skill-invalid-resource', inject: ['skills'], apply: registerAclDiagnosisSkill }) + const skill = await ctx.skills.get(ACL_DIAGNOSIS_SKILL) + if (skill?.resourceBase?.kind !== 'directory') throw new Error('Missing physical skill resource directory') + writeFileSync(join(skill.resourceBase.path, 'SKILL.md'), raw) + await expect(ctx.skills.get(ACL_DIAGNOSIS_SKILL)).rejects.toThrow(message) } finally { await ctx.fiber.dispose() } diff --git a/packages/sandbox/sandbox-windows-acl/tests/diagnose-script.spec.ts b/packages/sandbox/sandbox-windows-acl/tests/diagnose-script.spec.ts index 6559969e55..8c682c22e3 100644 --- a/packages/sandbox/sandbox-windows-acl/tests/diagnose-script.spec.ts +++ b/packages/sandbox/sandbox-windows-acl/tests/diagnose-script.spec.ts @@ -10,15 +10,13 @@ * written with `icacls` and the `*SID` spelling, which no account name has to * resolve. * - * Cleanup restores full control before deleting: the grant case leaves the caller - * with `WRITE_DAC` but not `WRITE_OWNER`, and a directory that stripped its own - * `WRITE_OWNER` cannot be removed by the same unelevated caller. + * Cleanup restores full control on the fixture directories before removing them. */ import { execFileSync } from 'node:child_process' -import { mkdirSync, mkdtempSync, rmSync } from 'node:fs' +import { mkdirSync, mkdtempSync, readdirSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' -import { join } from 'node:path' +import { dirname, join } from 'node:path' import { fileURLToPath } from 'node:url' import { afterAll, beforeAll, describe, expect, it } from 'vitest' @@ -42,13 +40,35 @@ interface ScriptRun { readonly output: string } +interface ScriptReport { + readonly kind: string + readonly operation: string + readonly path: string + readonly status: string + readonly reason: string + readonly details: Record +} + +function reports(run: ScriptRun): ScriptReport[] { + const result = run.output.split(/\r?\n/u).filter(line => line.startsWith('REPORT ')) + .map(line => JSON.parse(line.slice('REPORT '.length)) as ScriptReport) + expect(result.length).toBeGreaterThan(0) + for (const entry of result) expect(entry.reason.length).toBeGreaterThan(0) + expect(result.at(-1)).toMatchObject({ kind: 'summary', details: { exitCode: run.code } }) + return result +} + function pwsh(command: string): string { return execFileSync('pwsh', ['/NoLogo', '/NonInteractive', '/NoProfile', '-Command', command], { encoding: 'utf8' }) } function runScript(args: readonly string[]): ScriptRun { + return runPowerShell(['-File', script, ...args]) +} + +function runPowerShell(args: readonly string[]): ScriptRun { try { - const stdout = execFileSync('pwsh', ['/NoLogo', '/NonInteractive', '/NoProfile', '-File', script, ...args], { + const stdout = execFileSync('pwsh', ['/NoLogo', '/NonInteractive', '/NoProfile', ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], }) @@ -60,7 +80,11 @@ function runScript(args: readonly string[]): ScriptRun { } function icacls(path: string, ...args: readonly string[]): string { - return pwsh(`(icacls '${path}' ${args.map(argument => `"${argument}"`).join(' ')}) -join "\`n"`) + return execFileSync('icacls', [path, ...args], { encoding: 'utf8', windowsHide: true }) +} + +function sddlOf(path: string): string { + return pwsh(`(Get-Acl -LiteralPath '${path.replaceAll("'", "''")}').Sddl`).trim() } function aclLines(path: string): string[] { @@ -122,6 +146,11 @@ describe.skipIf(!isWin32 || !pwshAvailable())('diagnose-windows-sandbox-acl scri const repair = runScript(['-Path', target, '-AllowRoot', scratch, '-Out', outDir, '-Fix']) expect(repair.output, repair.output).toContain(`FIXED ${target} SID=${PACKAGE_SID}`) expect(repair.output, repair.output).toContain('SUMMARY FIXED=1 GRANTED=0 REFUSED=0') + expect(reports(repair)).toEqual(expect.arrayContaining([ + expect.objectContaining({ kind: 'action', operation: 'remove_package_allow', path: target, status: 'started' }), + expect.objectContaining({ kind: 'action', operation: 'remove_package_allow', path: target, status: 'completed' }), + expect.objectContaining({ kind: 'verification', operation: 'fix', path: target, status: 'verified' }), + ])) // Exactly the foreign ACE disappears; every other line survives unchanged. expect(normalized(target, aclLines(target))).toEqual(before.filter(line => !line.includes(PACKAGE_SID))) @@ -134,12 +163,64 @@ describe.skipIf(!isWin32 || !pwshAvailable())('diagnose-windows-sandbox-acl scri const diagnosis = runScript(['-Path', target]) expect(diagnosis.output, diagnosis.output).toContain('VERDICT=NOT_THIS_CLASS') expect(diagnosis.output, diagnosis.output).not.toContain('PACKAGE_ACE') + expect(reports(diagnosis)).toContainEqual(expect.objectContaining({ kind: 'decision', operation: 'diagnose', path: target, status: 'skipped' })) const repair = runScript(['-Path', target, '-AllowRoot', scratch, '-Out', outDir, '-Fix']) expect(repair.output, repair.output).toContain('SUMMARY FIXED=0 GRANTED=0 REFUSED=0') + expect(reports(repair)).toContainEqual(expect.objectContaining({ kind: 'decision', operation: 'fix', path: target, status: 'skipped' })) expect(normalized(target, aclLines(target))).toEqual(before) }, 60_000) + it('reports every inspected ancestor and locates a package ACE present only on the parent', async () => { + const parent = makeDir('parent-package-report') + const target = join(parent, 'child') + mkdirSync(target) + stamp(parent, PACKAGE_SID) + const before = [sddlOf(parent), sddlOf(target)] + + const diagnosis = runScript(['-Path', target]) + expect(diagnosis.code, diagnosis.output).toBe(0) + const entries = reports(diagnosis) + const inspected = entries.filter(entry => entry.kind === 'observation' && entry.operation === 'inspect_acl') + const expectedPaths = [target] + for (let ancestor = dirname(target); ; ancestor = dirname(ancestor)) { + expectedPaths.push(ancestor) + if (dirname(ancestor) === ancestor) break + } + expect(inspected.map(entry => entry.path)).toEqual(expectedPaths) + expect(inspected[0]).toMatchObject({ + path: target, status: 'read', + details: { aces: expect.not.arrayContaining([expect.objectContaining({ sid: PACKAGE_SID })]) }, + }) + expect(inspected[1]).toMatchObject({ + path: parent, status: 'read', + details: { aces: expect.arrayContaining([expect.objectContaining({ sid: PACKAGE_SID, type: 'Allow', inherited: false })]) }, + }) + expect(entries).toContainEqual(expect.objectContaining({ + kind: 'decision', operation: 'classify', path: target, status: 'CULPRIT', + details: expect.objectContaining({ packageObjects: [parent] }), + })) + expect(entries.filter(entry => entry.kind === 'action' && entry.details.effect !== 'none')).toEqual([]) + expect([sddlOf(parent), sddlOf(target)]).toEqual(before) + + // The example retains both fixture paths and the fixture SID. Host-owned ACEs + // and ancestors remain covered by the assertions above instead of the snapshot. + const transcript = entries.filter(entry => entry.path === parent || entry.path === target).map((entry) => { + let details: Record = {} + if (entry.operation === 'inspect_acl') { + details = { fixturePackageAces: (entry.details.aces as { readonly sid: string }[]).filter(ace => ace.sid === PACKAGE_SID) } + } else if (entry.operation === 'classify') { + details = { packageObjects: entry.details.packageObjects } + } else if (entry.kind === 'summary') { + details = { + exitCode: entry.details.exitCode, operations: entry.details.operations, automaticRollback: entry.details.automaticRollback, + } + } + return JSON.stringify({ ...entry, details }) + }).join('\n').replaceAll(JSON.stringify(parent).slice(1, -1), '{{parent}}') + '\n' + await expect(transcript).toMatchFileSnapshot(fileURLToPath(new URL('./expected/parent-package-report.jsonl', import.meta.url))) + }, 60_000) + it('reports an inert capability SID and an inert DENY ACE without touching either', () => { const capability = makeDir('capability') stamp(capability, CAPABILITY_SID) @@ -158,6 +239,10 @@ describe.skipIf(!isWin32 || !pwshAvailable())('diagnose-windows-sandbox-acl scri const denyDiagnosis = runScript(['-Path', deny]) expect(denyDiagnosis.output, denyDiagnosis.output).not.toContain('PACKAGE_ACE') expect(denyDiagnosis.output, denyDiagnosis.output).not.toContain('VERDICT=CULPRIT') + expect(reports(denyDiagnosis)).toContainEqual(expect.objectContaining({ + kind: 'observation', operation: 'inspect_acl', path: deny, + details: expect.objectContaining({ aces: expect.arrayContaining([expect.objectContaining({ sid: PACKAGE_SID, type: 'Deny', inherited: false })]) }), + })) // `pwsh -File` passes `-Path a,b` literally, so each object is diagnosed on its own. for (const path of [capability, deny]) { @@ -195,5 +280,236 @@ describe.skipIf(!isWin32 || !pwshAvailable())('diagnose-windows-sandbox-acl scri const contradictory = runScript(['-Path', target, '-AllowRoot', scratch, '-Out', outDir, '-Fix', '-GrantFullControl']) expect(contradictory.code).toBe(2) expect(contradictory.output, contradictory.output).toContain('run one at a time') + expect(reports(contradictory)).toContainEqual(expect.objectContaining({ kind: 'error', status: 'stopped' })) }, 60_000) + + it.each(['-Fix', '-GrantFullControl'])('refuses ancestor junctions for %s without changing their destination', (repairSwitch) => { + const allowed = makeDir(`junction-${repairSwitch}`) + const outside = makeDir(`outside-${repairSwitch}`) + const target = join(outside, 'target') + mkdirSync(target) + icacls(target, '/inheritance:r', '/grant:r', `*${meSid}:(M)`) + stamp(target, PACKAGE_SID) + const before = sddlOf(target) + const link = join(allowed, 'link') + symlinkSync(outside, link, 'junction') + try { + for (const allowRoot of [allowed, link]) { + const repair = runScript(['-Path', join(link, 'target'), '-AllowRoot', allowRoot, '-Out', outDir, repairSwitch]) + expect(repair.output, repair.output).toContain('reparse point') + expect(repair.code).not.toBe(0) + expect(reports(repair)).toContainEqual(expect.objectContaining({ kind: 'decision', status: 'refused', reason: expect.stringContaining('reparse point') })) + expect(sddlOf(target)).toBe(before) + } + } finally { + unlinkSync(link) + } + }) + + it.each(['-Fix', '-GrantFullControl'])('restores the original DACL with the rollback emitted by %s', (repairSwitch) => { + const target = makeDir(`rollback-${repairSwitch}'s-directory`) + icacls(target, '/setintegritylevel', 'L') + if (repairSwitch === '-GrantFullControl') icacls(target, '/inheritance:r', '/grant:r', `*${meSid}:(M)`) + else icacls(target, '/grant', `*${PACKAGE_SID}:(OI)(CI)(RX)`) + icacls(target, '/grant', `*${CAPABILITY_SID}:(OI)(CI)(RX)`) + const before = sddlOf(target) + const linesBefore = normalized(target, aclLines(target)).sort() + const repair = runScript(['-Path', target, '-AllowRoot', scratch, '-Out', outDir, repairSwitch]) + expect(repair.code, repair.output).toBe(0) + expect(sddlOf(target)).not.toBe(before) + const rollback = repair.output.split(/\r?\n/u).find(line => line.startsWith('ROLLBACK ')) + expect(rollback, repair.output).toBeDefined() + const restored = pwsh(rollback!.slice('ROLLBACK '.length)) + expect(reports({ code: 0, output: restored })).toContainEqual(expect.objectContaining({ kind: 'verification', operation: 'restore', status: 'verified' })) + expect(sddlOf(target)).toBe(before) + expect(normalized(target, aclLines(target)).sort()).toEqual(linesBefore) + }, 60_000) + + it('repairs a directory whose full-control ACE only applies to children', () => { + const target = makeDir('inherit-only-full-control') + icacls(target, '/inheritance:r', '/grant:r', `*${meSid}:(M)`) + icacls(target, '/grant', `*${meSid}:(OI)(CI)(IO)(F)`) + const diagnosis = runScript(['-Path', target]) + expect(diagnosis.output, diagnosis.output).toContain('VERDICT=PRECONDITION') + const repair = runScript(['-Path', target, '-AllowRoot', scratch, '-Out', outDir, '-GrantFullControl']) + expect(repair.output, repair.output).toContain('SUMMARY FIXED=0 GRANTED=1 REFUSED=0') + icacls(target, '/setintegritylevel', 'L') + }) + + it('refuses a recovery record for another path or a path outside the allowed root', () => { + const target = makeDir('restore-guards') + const other = makeDir('restore-other') + const backups = makeDir('restore-backups') + icacls(target, '/inheritance:r', '/grant:r', `*${meSid}:(M)`) + const repair = runScript(['-Path', target, '-AllowRoot', scratch, '-Out', backups, '-GrantFullControl']) + expect(repair.code, repair.output).toBe(0) + const record = join(backups, readdirSync(backups).find(file => file.endsWith('.json'))!) + const before = sddlOf(target) + const otherBefore = sddlOf(other) + const mismatch = runScript(['-Path', other, '-AllowRoot', scratch, '-Restore', record]) + expect(mismatch.code).toBe(2) + expect(mismatch.output).toContain('backup does not describe the requested path') + expect(sddlOf(other)).toBe(otherBefore) + const outside = runScript(['-Path', target, '-AllowRoot', other, '-Restore', record]) + expect(outside.code).toBe(2) + expect(outside.output).toContain('outside -AllowRoot') + expect(sddlOf(target)).toBe(before) + const link = join(other, 'link') + symlinkSync(target, link, 'junction') + try { + const throughLink = runScript(['-Path', link, '-AllowRoot', other, '-Restore', record]) + expect(throughLink.code).toBe(2) + expect(throughLink.output).toContain('reparse point') + expect(sddlOf(target)).toBe(before) + } finally { + unlinkSync(link) + } + }, 60_000) + + it('does not report a successful grant when a deny ACE blocks WRITE_OWNER', async () => { + const target = makeDir('denied-write-owner') + icacls(target, '/deny', `*${meSid}:(WO)`) + try { + const diagnosis = runScript(['-Path', target]) + expect(diagnosis.output, diagnosis.output).toContain('VERDICT=PRECONDITION') + expect(reports(diagnosis)).toContainEqual(expect.objectContaining({ + kind: 'observation', operation: 'inspect_acl', path: target, + details: expect.objectContaining({ + writeOwner: false, + aces: expect.arrayContaining([expect.objectContaining({ sid: meSid, type: 'Deny', rights: 'TakeOwnership', inherited: false })]), + }), + })) + const grant = runScript(['-Path', target, '-AllowRoot', scratch, '-Out', outDir, '-GrantFullControl']) + expect(grant.code, `${grant.output}\n${aclLines(target).join('\n')}`).toBe(2) + expect(grant.output, grant.output).toContain('GRANT_FAILED') + expect(grant.output).toContain('GRANTED=0 REFUSED=1') + expect(aclLines(target).join('\n')).toContain('(DENY)(WO)') + expect(reports(grant)).toEqual(expect.arrayContaining([ + expect.objectContaining({ kind: 'action', operation: 'grant_dacl', status: 'completed' }), + expect.objectContaining({ kind: 'verification', operation: 'grant', status: 'failed', details: expect.objectContaining({ recovery: expect.stringContaining('-Restore') }) }), + expect.objectContaining({ kind: 'summary', details: expect.objectContaining({ automaticRollback: false, granted: 0 }) }), + ])) + const transcript = reports(grant) + .filter(entry => entry.path === target && entry.kind !== 'observation') + .map(entry => `${entry.kind} ${entry.operation} ${entry.status} path={{target}}: ${entry.reason.replaceAll(meSid, '{{caller_sid}}')}`) + .join('\n') + '\n' + await expect(transcript).toMatchFileSnapshot(fileURLToPath(new URL('./expected/denied-grant-report.txt', import.meta.url))) + } finally { + icacls(target, '/remove:d', `*${meSid}`) + } + }) + + it('reports backup errors and no ACL write when the output path is a file', () => { + const target = makeDir('backup-failure') + icacls(target, '/inheritance:r', '/grant:r', `*${meSid}:(M)`) + const outputFile = join(scratch, 'not-a-directory') + writeFileSync(outputFile, 'Existing contents') + const before = sddlOf(target) + const run = runScript(['-Path', target, '-AllowRoot', scratch, '-Out', outputFile, '-GrantFullControl']) + expect(run.code).toBe(1) + const entries = reports(run) + expect(entries).toContainEqual(expect.objectContaining({ kind: 'action', operation: 'backup', status: 'failed', details: expect.objectContaining({ error: expect.any(String) }) })) + expect(entries.filter(entry => entry.kind === 'action' && entry.details.effect === 'acl')).toEqual([]) + expect(sddlOf(target)).toBe(before) + }) + + it('reports unreadable ACLs as missing observations without inventing permissions', () => { + const target = makeDir('unreadable-observation') + const before = sddlOf(target) + const run = runPowerShell(['-Command', ` +function Get-Acl { param([string]$LiteralPath); throw [System.IO.IOException]::new('ACL observation unavailable') } +& '${script.replaceAll("'", "''")}' -Path '${target.replaceAll("'", "''")}' +exit $LASTEXITCODE +`]) + expect(run.code).toBe(0) + expect(run.output).toContain('VERDICT=UNREADABLE') + const entries = reports(run) + expect(entries).toContainEqual(expect.objectContaining({ + kind: 'observation', path: target, status: 'unreadable', + details: { error: expect.stringContaining('ACL observation unavailable') }, + })) + expect(entries.at(-1)).toMatchObject({ status: 'partial', details: { observationFailures: expect.any(Number) } }) + expect(entries.filter(entry => entry.kind === 'action' && entry.details.effect !== 'none')).toEqual([]) + expect(sddlOf(target)).toBe(before) + }) + + it('reports the completed write and recovery command when the verification ACL read throws', () => { + const target = makeDir('post-write-read-failure') + icacls(target, '/inheritance:r', '/grant:r', `*${meSid}:(M)`) + const before = sddlOf(target) + const quote = (value: string): string => `'${value.replaceAll("'", "''")}'` + const wrapper = join(scratch, 'fail-verification.ps1') + // The real grant runs; only its subsequent observation fails in this child. + writeFileSync(wrapper, ` +$global:targetReads = 0 +function Get-Acl { + param([string]$LiteralPath) + if ($LiteralPath -eq ${quote(target)}) { + $global:targetReads++ + if ($global:targetReads -eq 4) { throw [System.IO.IOException]::new('verification read unavailable') } + } + Microsoft.PowerShell.Security\\Get-Acl -LiteralPath $LiteralPath +} +& ${quote(script)} -Path ${quote(target)} -AllowRoot ${quote(scratch)} -Out ${quote(outDir)} -GrantFullControl +exit $LASTEXITCODE +`) + const run = runPowerShell(['-File', wrapper]) + expect(run.code).toBe(2) + const entries = reports(run) + expect(entries).toEqual(expect.arrayContaining([ + expect.objectContaining({ kind: 'action', operation: 'grant_dacl', status: 'completed' }), + expect.objectContaining({ kind: 'observation', operation: 'inspect_acl', path: target, status: 'unreadable', details: expect.objectContaining({ error: expect.stringContaining('verification read unavailable') }) }), + expect.objectContaining({ kind: 'verification', operation: 'grant', status: 'failed', details: expect.objectContaining({ recovery: expect.stringContaining('-Restore') }) }), + ])) + expect(sddlOf(target)).not.toBe(before) + const rollback = run.output.split(/\r?\n/u).find(line => line.startsWith('ROLLBACK '))! + pwsh(rollback.slice('ROLLBACK '.length)) + expect(sddlOf(target)).toBe(before) + }, 60_000) + + it('reports a missing path and an already-satisfied grant without mutating either', () => { + const missing = join(scratch, 'missing') + const run = runScript(['-Path', missing, '-AllowRoot', scratch, '-Out', outDir, '-GrantFullControl']) + expect(run.code).toBe(2) + expect(reports(run)).toContainEqual(expect.objectContaining({ kind: 'decision', path: missing, status: 'skipped', reason: expect.stringContaining('does not exist') })) + const healthy = makeDir('already-satisfied') + const before = sddlOf(healthy) + const grant = runScript(['-Path', healthy, '-AllowRoot', scratch, '-Out', outDir, '-GrantFullControl']) + expect(grant.code, grant.output).toBe(0) + expect(reports(grant)).toContainEqual(expect.objectContaining({ kind: 'decision', operation: 'grant', status: 'skipped', reason: expect.stringContaining('already available') })) + expect(sddlOf(healthy)).toBe(before) + }) + + it('reports well-known package groups without treating them as a removable package ACE', () => { + const target = makeDir('well-known-package-groups') + for (const sid of ['S-1-15-2-1', 'S-1-15-2-2']) stamp(target, sid) + const before = sddlOf(target) + const run = runScript(['-Path', target, '-AllowRoot', scratch, '-Out', outDir, '-Fix']) + expect(run.code, run.output).toBe(0) + expect(run.output).toContain('VERDICT=NOT_THIS_CLASS') + expect(reports(run)).toContainEqual(expect.objectContaining({ + kind: 'observation', operation: 'inspect_acl', path: target, + details: expect.objectContaining({ aces: expect.arrayContaining([ + expect.objectContaining({ sid: 'S-1-15-2-1', type: 'Allow' }), + expect.objectContaining({ sid: 'S-1-15-2-2', type: 'Allow' }), + ]) }), + })) + expect(sddlOf(target)).toBe(before) + }) + + it('grants missing rights before removing a package ACE when both problems are present', () => { + const target = makeDir('both') + icacls(target, '/inheritance:r', '/grant:r', `*${meSid}:(M)`) + stamp(target, PACKAGE_SID) + const ownerBefore = ownerOf(target) + const diagnosis = runScript(['-Path', target]) + expect(diagnosis.output, diagnosis.output).toContain('VERDICT=BOTH') + const grant = runScript(['-Path', target, '-AllowRoot', scratch, '-Out', outDir, '-GrantFullControl']) + expect(grant.output, grant.output).toContain('SUMMARY FIXED=0 GRANTED=1 REFUSED=0') + expect(aclLines(target).join('\n')).toContain(PACKAGE_SID) + const fix = runScript(['-Path', target, '-AllowRoot', scratch, '-Out', outDir, '-Fix']) + expect(fix.output, fix.output).toContain('SUMMARY FIXED=1 GRANTED=0 REFUSED=0') + expect(aclLines(target).join('\n')).not.toContain(PACKAGE_SID) + expect(ownerOf(target)).toBe(ownerBefore) + }) }) diff --git a/packages/sandbox/sandbox-windows-acl/tests/expected/denied-grant-report.txt b/packages/sandbox/sandbox-windows-acl/tests/expected/denied-grant-report.txt new file mode 100644 index 0000000000..1d0dbbb0f0 --- /dev/null +++ b/packages/sandbox/sandbox-windows-acl/tests/expected/denied-grant-report.txt @@ -0,0 +1,8 @@ +decision classify PRECONDITION path={{target}}: The caller cannot open the requested object with both WRITE_DAC and WRITE_OWNER. The reported allow and deny ACEs are evidence, not an attribution to one rule. +decision backup selected path={{target}}: All recovery files must be written successfully before attempting the ACL change. +action backup started path={{target}}: Save the original DACL and an independent recovery command before changing permissions. +action backup completed path={{target}}: Save the original DACL and an independent recovery command before changing permissions. +action grant_dacl started path={{target}}: WRITE_OWNER is missing and WRITE_DAC is available; add a FullControl allow ACE for {{caller_sid}} while preserving deny ACEs, owner and SACL. +action grant_dacl completed path={{target}}: WRITE_OWNER is missing and WRITE_DAC is available; add a FullControl allow ACE for {{caller_sid}} while preserving deny ACEs, owner and SACL. +verification grant failed path={{target}}: The DACL write completed; recheck effective access before claiming that provisioning can succeed. No automatic rollback is performed. +summary grant failed path={{target}}: Operation completion records API execution; verification records the observed result. Only rerunning the original confined operation can confirm its failure is resolved. diff --git a/packages/sandbox/sandbox-windows-acl/tests/expected/parent-package-report.jsonl b/packages/sandbox/sandbox-windows-acl/tests/expected/parent-package-report.jsonl new file mode 100644 index 0000000000..5d692e3919 --- /dev/null +++ b/packages/sandbox/sandbox-windows-acl/tests/expected/parent-package-report.jsonl @@ -0,0 +1,5 @@ +{"kind":"observation","operation":"inspect_acl","path":"{{parent}}\\child","status":"read","reason":"Read the ACL and check effective WRITE_DAC and WRITE_OWNER; observed ACEs alone do not identify which rule caused a denial.","details":{"fixturePackageAces":[]}} +{"kind":"observation","operation":"inspect_acl","path":"{{parent}}","status":"read","reason":"Read the ACL and check effective WRITE_DAC and WRITE_OWNER; observed ACEs alone do not identify which rule caused a denial.","details":{"fixturePackageAces":[{"sid":"S-1-15-2-1-2-3-4","type":"Allow","rights":"ReadAndExecute, Synchronize","inherited":false,"inheritance":"None","propagation":"None"}]}} +{"kind":"decision","operation":"classify","path":"{{parent}}\\child","status":"CULPRIT","reason":"Package allow ACEs were observed. Required access checks determine whether the caller can perform the requested repair; other causes remain possible.","details":{"packageObjects":["{{parent}}"]}} +{"kind":"decision","operation":"diagnose","path":"{{parent}}\\child","status":"skipped","reason":"No mutation mode was requested; all reported ACLs were left unchanged.","details":{}} +{"kind":"summary","operation":"diagnose","path":"{{parent}}\\child","status":"completed","reason":"Operation completion records API execution; verification records the observed result. Only rerunning the original confined operation can confirm its failure is resolved.","details":{"exitCode":0,"operations":[{"id":1,"operation":"initialize","path":"","effect":"none","status":"completed"}],"automaticRollback":false}} diff --git a/scripts/build-exe-for-python-sdk-assets.spec.ts b/scripts/build-exe-for-python-sdk-assets.spec.ts index 4debf6fdc5..0a963f3f1e 100644 --- a/scripts/build-exe-for-python-sdk-assets.spec.ts +++ b/scripts/build-exe-for-python-sdk-assets.spec.ts @@ -23,6 +23,7 @@ describe('Python runtime executable assets', () => { expect(result.status).toBe(0) expect(result.stdout).toContain('node_modules/@deepseek-ai/dsh-web-frontend/dist/**/*') expect(result.stdout).toContain('node_modules/@deepseek-ai/dsh-skill-badge/assets/**/*') + expect(result.stdout).toContain('node_modules/@deepseek-ai/dsh-sandbox-windows-acl/assets/**/*') expect(result.stdout).not.toContain('node_modules/**/*.py') }) }) diff --git a/scripts/build-exe-for-python-sdk.ts b/scripts/build-exe-for-python-sdk.ts index ba4f2bc726..e2000c960b 100644 --- a/scripts/build-exe-for-python-sdk.ts +++ b/scripts/build-exe-for-python-sdk.ts @@ -62,6 +62,8 @@ const ASSET_GLOBS = [ 'node_modules/@deepseek-ai/dsh-web-frontend/dist/**/*', // skill-badge resolves both Markdown and image resources through import.meta.url. 'node_modules/@deepseek-ai/dsh-skill-badge/assets/**/*', + // The diagnosis provider extracts its PowerShell script for an external interpreter. + 'node_modules/@deepseek-ai/dsh-sandbox-windows-acl/assets/**/*', ] const PLATFORMS = ['linux', 'macos', 'win'] as const diff --git a/scripts/run-gates.spec.ts b/scripts/run-gates.spec.ts index 9d7a929446..4631258c16 100644 --- a/scripts/run-gates.spec.ts +++ b/scripts/run-gates.spec.ts @@ -770,6 +770,7 @@ describe('Node 24 lane ownership', () => { expect(subject.find(item => item.id === 'built-bin-smoke')?.args).toEqual( expect.arrayContaining([ 'apps/cli/tests/profiles/headless/tests/source-tool.built.e2e.ts', + 'apps/desktop/tests/acl-skill.built.e2e.ts', 'packages/subprocess/subprocess-local/tests/spawn-runner-built.e2e.ts', 'packages/subagent/subagent-codex/tests/loader-composition.e2e.ts', 'packages/subagent/subagent-claude-code/tests/loader-composition.e2e.ts', diff --git a/scripts/run-gates.ts b/scripts/run-gates.ts index d0c4773c66..e1e2de9c21 100644 --- a/scripts/run-gates.ts +++ b/scripts/run-gates.ts @@ -855,6 +855,7 @@ function builtBinSmokeGate(needs: string[] = ['build']): Gate { 'apps/cli/tests/profiles/headless/tests/keyless-smoke.e2e.ts', 'apps/cli/tests/profiles/headless/tests/source-tool.built.e2e.ts', 'apps/cli/tests/built-bin.e2e.ts', + 'apps/desktop/tests/acl-skill.built.e2e.ts', 'packages/host/directory-picker-native/tests/built-worker.e2e.ts', 'packages/sdk/server/tests/built-scope-carrier.e2e.ts', 'packages/deliverables/tool-present/tests/built-errors.e2e.ts', diff --git a/snapshots/session/headless.snapshot.ts b/snapshots/session/headless.snapshot.ts index 5135ae4748..c5524284ac 100644 --- a/snapshots/session/headless.snapshot.ts +++ b/snapshots/session/headless.snapshot.ts @@ -475,6 +475,11 @@ async function seedWorkspace(scenario: HeadlessScenario, cwd: string): Promise Promise> = { + async 'windows-acl-skill'(cwd) { + const target = join(cwd, '.dsh', 'skills', 'diagnose-windows-sandbox-acl', 'SKILL.md') + await mkdir(dirname(target), { recursive: true }) + await copyFile(join(repoRoot, 'packages/sandbox/sandbox-windows-acl/assets/diagnose-windows-sandbox-acl/SKILL.md'), target) + }, async 'office-skills'(cwd) { await cp(join(repoRoot, 'packages/skill/skill-office/assets'), join(cwd, 'office-skills'), { recursive: true }) await symlink(process.execPath, join(cwd, 'office-node')) diff --git a/snapshots/session/windows-acl-skill/session.v4.jsonl b/snapshots/session/windows-acl-skill/session.v4.jsonl new file mode 100644 index 0000000000..ddf043ce64 --- /dev/null +++ b/snapshots/session/windows-acl-skill/session.v4.jsonl @@ -0,0 +1,23 @@ +{"type":"session","version":4,"id":"{{session:1}}","createdAt":1783654655599,"cwd":"{{cwd}}","isSeeded":false,"delegationDepth":0} +{"type":"permission/preset","data":{"preset":"danger-full-access"}} +{"type":"sandbox/mode","data":{"mode":"danger-full-access"}} +{"type":"approval/policy","data":{"policy":"never"}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Load the diagnose-windows-sandbox-acl skill with the skill tool, then reply DONE."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"}]}} +{"type":"turn/start","data":{"turn":1}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} +{"type":"step/start","data":{"turn":1,"step":1}} +{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Load the diagnose-windows-sandbox-acl skill with the skill tool, then reply DONE."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `diagnose-windows-sandbox-acl`: Use on Windows when the DSH sandbox denies something it promised: cannot write or list in the workspace, or read a path the user should be able to read. Run the bundled script over the failing path and its ancestors; it only reads without a repair switch. It separates an AppContainer package-SID ACE, which it removes under an explicit root, from an unmet ownership or permission precondition, which it repairs with a full-control grant. Never change an owner or edit ACLs outside the script.\n- `model-only-skill`: Prove user-disabled skills remain available to the model.\n- `snapshot-skill`: Exercise project skill discovery and loading in snapshot tests.\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"diagnose-windows-sandbox-acl","description":"Use on Windows when the DSH sandbox denies something it promised: cannot write or list in the workspace, or read a path the user should be able to read. Run the bundled script over the failing path and its ancestors; it only reads without a repair switch. It separates an AppContainer package-SID ACE, which it removes under an explicit root, from an unmet ownership or permission precondition, which it repairs with a full-control grant. Never change an owner or edit ACLs outside the script."},{"name":"model-only-skill","description":"Prove user-disabled skills remain available to the model."},{"name":"snapshot-skill","description":"Exercise project skill discovery and loading in snapshot tests."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} +{"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} +{"type":"session/title","data":{"title":"Load the diagnose-windows-sandbox-acl sk","messageSeqs":[8],"source":{"kind":"fallback"}}} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"Load the requested skill."},{"type":"tool-call","id":"call_skill_load","name":"skill","arguments":"{\"name\":\"diagnose-windows-sandbox-acl\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:5}}"},"usage":{"inputTokens":100,"outputTokens":20,"cacheReadTokens":0,"reasoningTokens":5},"stream":[{"type":"chunk","time":1788699430688,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1788699430688,"index":0,"dt":[],"texts":["Load the requested skill."]},{"type":"chunk","time":1788699430688,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1788699430688,"index":1,"dt":[],"id":"call_skill_load","name":"skill","args":["{\"name\":\"diagnose-windows-sandbox-acl\"}"]},{"type":"chunk","time":1788699430688,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"Load the requested skill."}}},{"type":"chunk","time":1788699430688,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_skill_load","name":"skill","arguments":"{\"name\":\"diagnose-windows-sandbox-acl\"}"}}},{"type":"chunk","time":1788699430688,"chunk":{"type":"usage","usage":{"inputTokens":100,"outputTokens":20,"cacheReadTokens":0,"reasoningTokens":5}}},{"type":"chunk","time":1788699430688,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_skill_load","name":"skill","arguments":"{\"name\":\"diagnose-windows-sandbox-acl\"}"}} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_skill_load"},"toolCallId":"call_skill_load","content":[{"type":"text","text":"\n\nBase directory for this skill: {{cwd}}/.dsh/skills/diagnose-windows-sandbox-acl\nResolve relative paths mentioned by this skill against the base directory before using them. Load referenced resources only as needed.\n\n\n\n# Diagnose Windows sandbox ACL failures\n\nA denial is only worth diagnosing when it contradicts what the active mode promises. Establish that first: repairing a denial the sandbox is supposed to produce means weakening confinement for nothing.\n\n## Step 0 — Decide whether this denial is unexpected\n\nEnter the diagnosis only for these:\n\n| Symptom | Why it contradicts the promise |\n|---|---|\n| Cannot write inside the workspace (root or any subdirectory) | `workspace-write` promises writes there |\n| Cannot enumerate inside the workspace (`dir` prints nothing for a directory that has entries) | same |\n| Anything the signed-in user should plainly be able to read cannot be read | reads are never confined in either restricted mode |\n| Only the workspace **root** is denied while its subdirectories work normally | points at one object, not at the whole tree |\n\nStrong but not required corroboration: `Test-Path` returns true while reads fail; `dir` reports an empty directory that is not empty; `cmd` cannot read a file that .NET reads fine.\n\nStop and explain instead of repairing for these — they are the confinement working as documented:\n\n| Symptom | Why it is expected | What to do instead |\n|---|---|---|\n| Writing or deleting **outside** the workspace under `workspace-write` | the fence is doing its job | escalate that one call, or write inside the workspace |\n| Any write under `read-only` | the mode itself | escalate that one call, or switch mode |\n| `spawn EPERM` when a confined command captures a grandchild's output through piped stdio | named-pipe opens are denied in both restricted modes (a Win32 default-SD property, not a permission mistake); anonymous pipes and inherited stdio still work | escalate that one call, or restructure the command to avoid piping |\n| `Add-Type`, `[System.IO.*]::`, COM, or reflection failing with \"only core types\" | `read-only` pwsh runs in ConstrainedLanguage | not a permission problem; escalate or use `workspace-write` |\n\nThen split \"cannot write in the workspace\" by shape, because the two shapes have different causes:\n\n- **Uniformly denied** — the root and every subdirectory fail together: the sandbox could not provision its grant.\n- **Only the root denied** — subdirectories are fine: one object carries something that blocks it.\n\n## Step 1 — Diagnose read-only before changing anything\n\nRun the bundled script over the failing path. It reads ACLs with .NET and native `icacls`, changes nothing, and prints machine-parseable lines:\n\n```powershell\npwsh -File scripts/diagnose-windows-sandbox-acl.ps1 -Path \n```\n\nIt reports every observed allow and deny ACE on the target and its ancestors, including SID, rights, inheritance and propagation flags, plus the native ACL listing, owner, effective `WRITE_DAC` and `WRITE_OWNER`, caller integrity and sandbox marker names. Well-known groups `S-1-15-2-1` and `S-1-15-2-2` are reported but are not individual package ACEs eligible for removal. Access checks open existing objects without changing contents; Windows accounts for group membership, deny ACEs and inheritance. An unreadable or unrecognized value is unknown, not absent.\n\nEvery `REPORT` line contains a JSON record with `kind`, `operation`, `path`, `status`, `reason` and `details`. Read observations and reasons alongside the verdict: a deny ACE's presence alone does not prove that it caused the failure. Decisions explain skips and refusals. Actions report `started` before execution and `completed` or `failed` afterward; completion means the operation ran, while a separate verification reports whether the intended result was observed. A final summary lists attempted operations, outcomes and available recovery commands, including after a caught exception. If execution ends before a completion or summary record, treat the result as unconfirmed.\n\nThe failing API names the family. DSH's fail-closed errors carry the API and the exact Win32 code, so read the error rather than guessing:\n\n| Error | Meaning |\n|---|---|\n| `GetNamedSecurityInfoW` … (Win32 5) | the object could not be **read** — either it carries a package SID and the caller is below Medium, or the caller has no access to it at all |\n| `SetNamedSecurityInfoW` … (Win32 5) | the object was read but not written — the caller lacks `WRITE_DAC`, `WRITE_OWNER`, or both |\n| `grantWrite` succeeded, yet the confined child still cannot use the directory | the grant landed but the child cannot open the object |\n\nThe script needs a caller that can open the object. `read-only` pwsh cannot run it at all, because ConstrainedLanguage blocks the .NET calls it needs; under `workspace-write` the confined child cannot open an object carrying a package SID, so the diagnosis comes back `READABLE=False` for the very object that caused the problem. In both modes the diagnosis needs an unconfined caller, so escalate once and run the diagnosis together with any repair in that same call (Step 4) — rather than concluding that the path is unreadable or that the failure is something else.\n\n## Step 2 — Read the verdict\n\nFor `UNREADABLE` or `INCOMPLETE`, report the failed observation and its error; do not treat missing evidence as missing permissions or proceed with a repair. `NOT_THIS_CLASS` only rules out the conditions the script inspected, not every cause of the original failure.\n\n| Package SID present | Effective permissions | Verdict | Action |\n|---|---|---|---|\n| yes | the target has both rights and every affected object has `WRITE_DAC` | package ACE found | remove the ACE (Step 4), then verify the original failure |\n| yes | either condition above is unmet | both problems at once | grant full control on the affected object first, then remove the ACE; if `WRITE_DAC` is missing, the user must run the grant from an elevated terminal |\n| no | `WRITE_DAC` present, `WRITE_OWNER` missing | a provisioning precondition is unmet | grant full control (Step 4) |\n| no | `WRITE_DAC` missing | this caller cannot repair the DACL | hand the user the single command to run from an elevated terminal (Step 4) |\n| no | both rights present | not this class | say so and stop; report what was actually found |\n\n## Step 3 — Explain, and apologize\n\nSay what the finding is and what it will cost before doing anything.\n\nApologize on the harness's behalf, in the language the user is writing in, in one or two sentences, then move to the technical explanation. The gap being owned is ours: the harness neither notices the conflict when it provisions the grant nor gives any direction when the denial surfaces, so the user only sees a bare \"Access is denied\" and has to guess. Do not apologize before the cause is confirmed, do not repeat it, do not blame another tool in the apology (the cause belongs in the explanation), and do not let it replace the explanation.\n\nTwo things must reach the user either way:\n\n- **Which shape this is** — one object carrying a foreign ACE, or a directory whose ownership/DACL does not satisfy DSH's documented precondition.\n- **That removing a foreign ACE may be undone** — if whatever tool placed it runs again with this directory as its root, it will place it again. The repair is not a permanent fix.\n\n## Step 4 — Repair, or hand over steps\n\nTwo repairs exist, and both run through the same script so that no ACL is edited by hand.\n\n**Remove a conflicting package-SID ACE.** This also removes that package's access, so explain which SID and permissions will be removed:\n\n```powershell\npwsh -File scripts/diagnose-windows-sandbox-acl.ps1 -Path -AllowRoot -Out -Fix\n```\n\n**Grant the current user full control when the precondition is unmet:**\n\n```powershell\npwsh -File scripts/diagnose-windows-sandbox-acl.ps1 -Path -AllowRoot -Out -GrantFullControl\n```\n\nFull control carries both rights this needs: `WRITE_DAC` for the DACL and `WRITE_OWNER` for the mandatory label DSH writes in the same call. **Taking ownership alone does not work** — it yields only `WRITE_DAC`, so the label write still fails. Never change an object's owner, and never \"replace permissions on all child objects\": that erases deny ACEs somebody set deliberately.\n\nBoth modes require `-AllowRoot` to be a containing directory and reject the target or any ancestor if it is a reparse point, including a junction used as `-AllowRoot`. Before mutation they save the native `icacls` listing format, a DACL recovery record, a standalone recovery script and its exact command under `-Out`. The recovery command uses `-Restore` to restore only the original DACL and inheritance protection; it never changes ownership or the mandatory label and remains usable after the session ends. It requires `WRITE_DAC` and enforces the same path restrictions. Run multiple rollback commands in reverse repair order.\n\nAfter a grant, the script rechecks effective `WRITE_DAC` and `WRITE_OWNER`; after removal it checks that package ACEs disappeared and other `icacls` lines stayed unchanged. Refused or failed repairs exit nonzero. A failed verification does not undo a completed DACL write. Report which operation ran, its reason, what verification observed and the recovery command; the script never rolls back automatically. If the requested repair failed after a write, use its emitted recovery command before trying another repair, and report the recovery result. Both repairs write a DACL, which the confined child cannot do, so run the diagnosis and the repair inside one escalated call rather than spending two approvals on the same directory.\n\nThe caller needs effective `WRITE_DAC` to repair the DACL. Ownership often supplies it, but an explicit grant or group grant can also supply it to a non-owner. Follow the script's access result rather than inferring permissions from the owner's name. If the caller lacks `WRITE_DAC`, ask the user to run the exact grant command from an elevated terminal. Elevation does not override every deny or system policy; verify the result.\n\nDo not reach for `sandbox_permissions` to solve a Windows-token permission failure. Escalation gives the script an unconfined caller (Step 1); it does not elevate the Windows token. If the unconfined caller still lacks `WRITE_DAC`, another sandbox escalation cannot supply it.\n\nDo not make the harness trigger UAC either. An agent-initiated `runas` is a privilege-escalation path, the elevated child would run outside both the sandbox and the approval ledger the session log is built from, and a UAC prompt cannot be routed through this harness's approval channel. Hand the user the single exact command to run from an elevated terminal, and say plainly what it changes.\n\nNever recommend running the whole agent elevated instead: that is a downgrade, and the community habit of \"just run it as administrator\" trades the isolation away for a working prompt.\n\nAlso stop short when the directory cannot be repaired this way at all, and say which applies: the owner is a system principal such as `TrustedInstaller`, the path is one the user has no business owning, or the volume is not ACL-capable. Moving the workspace is then the honest answer.\n\n## Step 5 — Verify against the original failure\n\nRe-run the operation that failed, from the same confined context. The repair is only done when that operation succeeds. Whether diagnosis, repair or verification succeeds or fails, tell the user what the script observed, what it changed or left untouched, why it took those actions, and what remains unverified. Keep observations separate from suspected causes. If the original operation still fails, report the new error verbatim rather than starting another round of changes.\n\n## Step 6 — Report recurrence\n\nTell the user the condition that brings it back, so they can recognize it instead of re-diagnosing it.\n\n## Never\n\n- Never write, create, or delete a file to *test* permissions. Writing to probe is how an existing file gets clobbered, and it answers nothing the read-only diagnosis does not. (This has already happened once in this repository: a probe overwrote a workspace-root `AGENTS.md` that no version control could restore.)\n- Never edit ACLs by hand — use the bundled repairs or their generated recovery command. The recovery script writes only the saved DACL; do not replace it with a security-descriptor write that also attempts to change the SACL.\n- Never repair anything outside the directory being diagnosed, and never widen `-AllowRoot` beyond the tree that legitimately contains the failing path — its purpose is to keep a repair from reaching a neighbour of the thing that failed.\n\n"}],"isError":false,"id":"{{message:6}}"}},"sourceEventSeqs":[15],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":1}} +{"type":"step/start","data":{"turn":1,"step":2}} +{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The skill is loaded."},{"type":"text","text":"DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:7}}"},"usage":{"inputTokens":180,"outputTokens":10,"cacheReadTokens":0,"reasoningTokens":4},"stream":[{"type":"chunk","time":1788699430709,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1788699430709,"index":0,"dt":[],"texts":["The skill is loaded."]},{"type":"chunk","time":1788699430709,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1788699430709,"index":1,"dt":[],"texts":["DONE"]},{"type":"chunk","time":1788699430709,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The skill is loaded."}}},{"type":"chunk","time":1788699430709,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"DONE"}}},{"type":"chunk","time":1788699430709,"chunk":{"type":"usage","usage":{"inputTokens":180,"outputTokens":10,"cacheReadTokens":0,"reasoningTokens":4}}},{"type":"chunk","time":1788699430709,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":2}} +{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/snapshots/session/windows-acl-skill/snapshot.yml b/snapshots/session/windows-acl-skill/snapshot.yml new file mode 100644 index 0000000000..fd9c8d4202 --- /dev/null +++ b/snapshots/session/windows-acl-skill/snapshot.yml @@ -0,0 +1,9 @@ +version: 1 +scenario: windows-acl-skill +profile: headless +composition: default +recording: authored +header: + class: skill +workspace: + setup: windows-acl-skill diff --git a/snapshots/session/windows-acl-skill/workspace/.dsh/skills/model-only-skill/SKILL.md b/snapshots/session/windows-acl-skill/workspace/.dsh/skills/model-only-skill/SKILL.md new file mode 100644 index 0000000000..ac7c02e29f --- /dev/null +++ b/snapshots/session/windows-acl-skill/workspace/.dsh/skills/model-only-skill/SKILL.md @@ -0,0 +1,7 @@ +--- +name: model-only-skill +description: Prove user-disabled skills remain available to the model. +user-invocable: false +--- + +Follow these model-only snapshot instructions. diff --git a/snapshots/session/windows-acl-skill/workspace/.dsh/skills/snapshot-skill/SKILL.md b/snapshots/session/windows-acl-skill/workspace/.dsh/skills/snapshot-skill/SKILL.md new file mode 100644 index 0000000000..b0816d6bee --- /dev/null +++ b/snapshots/session/windows-acl-skill/workspace/.dsh/skills/snapshot-skill/SKILL.md @@ -0,0 +1,7 @@ +--- +name: snapshot-skill +description: Exercise project skill discovery and loading in snapshot tests. +--- + +Follow these snapshot-only instructions. +Resolve referenced resources relative to this skill directory. diff --git a/snapshots/session/windows-acl-skill/workspace/.dsh/skills/user-only-skill/SKILL.md b/snapshots/session/windows-acl-skill/workspace/.dsh/skills/user-only-skill/SKILL.md new file mode 100644 index 0000000000..4b02550d15 --- /dev/null +++ b/snapshots/session/windows-acl-skill/workspace/.dsh/skills/user-only-skill/SKILL.md @@ -0,0 +1,7 @@ +--- +name: user-only-skill +description: Prove model-disabled skills stay outside the model catalog. +disable-model-invocation: true +--- + +Follow these user-only snapshot instructions.