Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 57 additions & 6 deletions bin/prepare-workspace.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,32 @@ $ErrorActionPreference = 'Stop'
if ($ExecutionContext.SessionState.LanguageMode -ne 'FullLanguage') {
throw 'DSH_OPS_CONSTRAINED_LANGUAGE: workspace ACL preparation requires PowerShell FullLanguage; no ACL preparation was completed. Keep the host security policy enabled and ask its administrator for a supported preparation path.'
}
. (Join-Path $PSScriptRoot 'workspace-acl.ps1')
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = [Security.Principal.WindowsPrincipal]::new($identity)
$item = Get-Item -LiteralPath $Workspace -Force
if (!$item.PSIsContainer) { throw 'Workspace is not a directory' }
$cursor = $item
while ($null -ne $cursor) {
if ($cursor.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Workspace ancestry contains a reparse point; refusing ACL preparation' }
$cursor = $cursor.Parent
}
# \\wsl.localhost\<distro> and \\wsl$\<distro> are the WSL 9P redirector (#669):
# the filesystem behind them exposes no NTFS security descriptor, so Get-Acl
# cannot produce one and no DACL preparation has an object to write. Authority
# there is the distribution's own uid/gid mapping. The decision runs after the
# existence/container validation above — a missing path still fails exactly like
# any other workspace — and before Get-Acl below, so a live 9P root answers
# ready instead of dying inside it. This is a prefix decision, not a catch:
# every other path keeps its existing behaviour, and a real ACL error on those
# paths still fails closed.
if ((Get-DshOpsWorkspaceNtfsState -Path $item.FullName) -eq 'wsl-redirector') { Write-Output 'ready'; exit 0 }
# No reparse walk here: a folder that is already ready answers without any
# tag inspection, so an OneDrive placeholder root is not refused merely for
# being a reparse point (#744). The tag check lives on the one branch below
# that actually writes.
$acl = Get-Acl -LiteralPath $item.FullName
. (Join-Path $PSScriptRoot 'workspace-acl.ps1')
$decision = Get-DshOpsWorkspaceDecision -Acl $acl -Identity $identity -Principal $principal
if ($decision.State -eq 'denied') { throw $decision.Reason }
if ($decision.State -eq 'ready') { Write-Output 'ready'; exit 0 }
if ($decision.State -eq 'foreign-owner') { throw $decision.Reason }
# Everything below is the preparation branch: the only code that writes, and
# therefore the only place a reparse tag is allowed to matter (#744).
$needed = [Security.AccessControl.FileSystemRights]::TakeOwnership # WRITE_OWNER, needed to set the sandbox integrity label
# Write only the root's own DACL through its handle. The added ACE is directory-only and the
# inheritable ACEs are unchanged, so no descendant needs a new ACL; path-based SetAccessControl
Expand Down Expand Up @@ -52,7 +63,47 @@ public static class DshOpsDirectoryDacl {
}
}
}
public static class DshOpsReparseTag {
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
static extern SafeFileHandle CreateFileW(string name, uint access, uint share, IntPtr security, uint disposition, uint flags, IntPtr template);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool DeviceIoControl(SafeFileHandle handle, uint control, IntPtr inBuffer, uint inSize, byte[] outBuffer, uint outSize, out uint returned, IntPtr overlapped);
public static uint Get(string path) {
// Zero access, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT:
// the query opens the point itself, never its target (#744).
using (SafeFileHandle handle = CreateFileW(path, 0u, 7u, IntPtr.Zero, 3u, 0x02000000u | 0x00200000u, IntPtr.Zero)) {
if (handle.IsInvalid) throw new Win32Exception(Marshal.GetLastWin32Error());
// FSCTL_GET_REPARSE_POINT needs a full REPARSE_DATA_BUFFER-sized output:
// a four-byte slice is rejected with ERROR_INSUFFICIENT_BUFFER.
byte[] buffer = new byte[16384];
// The first dword of the returned buffer is the tag.
// Windows PowerShell 5.1 compiles with C# 5, which has no inline out declarations.
uint returned;
if (!DeviceIoControl(handle, 0x900A8u, IntPtr.Zero, 0, buffer, (uint)buffer.Length, out returned, IntPtr.Zero) || returned < 4)
throw new Win32Exception(Marshal.GetLastWin32Error() != 0 ? Marshal.GetLastWin32Error() : unchecked((int)0x80070057));
return BitConverter.ToUInt32(buffer, 0);
}
}
}
'@
# Cloud placeholders keep a real directory entry behind the point, so the proven
# cloud-files family (the exact 0x9000?01A shape) is allowed through; every other
# tag — including the rest of the 0x9xxxxxxx band — redirects the view and fails
# closed with the tag named, and a point whose tag cannot even be read fails closed
# too (#744).
$cursor = $item
while ($null -ne $cursor) {
if ($cursor.Attributes -band [IO.FileAttributes]::ReparsePoint) {
try { $tag = [DshOpsReparseTag]::Get($cursor.FullName) } catch {
throw "Workspace ancestry contains a reparse point at $($cursor.FullName) whose tag cannot be read ($($_.Exception.Message)); refusing ACL preparation. Cloud placeholders are allowed through; an unreadable point is not."
}
$family = Get-DshOpsReparseTagDecision -Tag $tag
if ($family.State -ne 'cloud') {
throw "Workspace ancestry contains an unsupported reparse point (tag 0x$($tag.ToString('X8'))) at $($cursor.FullName); refusing ACL preparation. Cloud placeholders pass; every other reparse tag fails closed."
}
}
$cursor = $cursor.Parent
}
# Save only the DACL. Owner, SACL, existing ACEs and child ACLs are not changed.
$before = $acl.GetSecurityDescriptorSddlForm([Security.AccessControl.AccessControlSections]::Access)
[IO.Directory]::CreateDirectory($BackupDir) | Out-Null
Expand Down
46 changes: 46 additions & 0 deletions bin/workspace-acl.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,49 @@ function Get-DshOpsWorkspaceDecision {
# foreign-owner instead. Both are the pre-existing behaviour, kept unchanged.
[pscustomobject]@{ State = 'needs-preparation' }
}

<#
Classify one reparse tag for the preparation branch (#744). This is pure: it
never opens the point, it only judges the tag value the caller read.

Only the proven cloud-files family is allowed through: the placeholders
(IO_REPARSE_TAG_CLOUD 0x9000001A, CLOUD_ROOT 0x9000101A, CLOUD_ON_DEMAND
0x9000201A, and family members sharing the exact 0x9000?01A shape) keep a
real directory entry behind the point, so a directory-only WRITE_OWNER write
still targets a real object. A high nibble of 9 alone is NOT enough: the rest
of Microsoft's reserved 0x90000000-0x9FFFFFFF band is unproven here and stays
out, exactly like every other tag (mount point, symlink, dedup, ...) that
redirects or transforms the view and fails closed with the tag named. A tag
that cannot be read at all is the caller's error to surface, not a decision
to soften.
#>
function Get-DshOpsReparseTagDecision {
param(
[Parameter(Mandatory = $true)][uint32]$Tag
)
# Decimal constants on purpose: Windows PowerShell 5.1 folds in-band hex
# literals into a negative Int32, and a sign-extended Int64 mask never
# matches. 4294905855 is 0xFFFF0FFF (family mask); 2415919130 is
# 0x9000001A (IO_REPARSE_TAG_CLOUD).
if (($Tag -band 4294905855) -eq 2415919130) { return [pscustomobject]@{ State = 'cloud' } }
return [pscustomobject]@{ State = 'unsupported' }
}

<#
Classify one workspace spelling for NTFS ACL evaluation (#669). Pure.

\\wsl.localhost\<distro> and \\wsl$\<distro> are the WSL 9P redirector: the
filesystem behind it exposes no NTFS security descriptor, so Get-Acl cannot
produce one and no DACL write has an object. Authority there is the
distribution's own uid/gid mapping, so those prefixes must not be treated
as a failed preparation. This is a prefix decision, not a catch swallowing
ACL errors: everything else is evaluated as NTFS, where a real Get-Acl
failure still fails closed.
#>
function Get-DshOpsWorkspaceNtfsState {
param(
[Parameter(Mandatory = $true)][string]$Path
)
if ($Path -match '^(\\\\(\?\\UNC\\)?wsl(\.localhost|\$)\\)') { return 'wsl-redirector' }
return 'ntfs'
}
8 changes: 8 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,14 @@ this package adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
- 原生工具构造与发布拒绝队列不再向组合根挂监听或生命周期 effect:证据观察者与 result admission 改为在调用方上下文订阅并声明 global 分发,拒绝队列在 root 拒绝 effect 时回落到调用方生命周期。dsh-tui 0.20 会拒绝插件激活期内的 `root.events.on` 与 `root.effect`,而原生工具行正是插件激活,导致每次 `dsh-tui --resume` 都在 agent 挂载前报 "cannot resume session"。
- The Bash tool description now states the parse contract of `stdout`/`stderr` where the model reads it: `text` may be a partial fragment, `truncated` marks one that must not be parsed as complete structured output, and `spillPath` is optional and not a completeness guarantee. The typed output schema is unchanged: repeating the contract there would cost every PTC request without saying anything the tool text does not. Command semantics, exit codes, result values, limits, spill files, permissions and rendering are unchanged.
- Bash 工具说明现在在模型读取它的地方写明 `stdout`/`stderr` 的解析契约:文本可能只是片段,`truncated` 标记的片段不得当作完整结构化输出解析,`spillPath` 是可选项且不保证完整。输出类型 schema 保持不变:在那里重复这段契约只会让每个 PTC 请求更贵,并不会多说明什么。命令语义、退出码、结果值、上限、落盘、权限与渲染均不变。
- The promoted Bash render no longer implies a job kill stops one command: it states that `job_kill` terminates the whole process tree, including daemons the command started and left attached to it (an adb server, a dev-server watcher), and points to stopping those on their own channel, starting them detached, or beginning daemon-like work with `run_in_background`. The host's subprocess/job layer still owns the actual kill semantics; this is actionable guidance, not a host fix (#814).
- 提升为后台的 Bash 渲染不再暗示一次任务终止只停掉一条命令:现在写明 `job_kill` 会终止整棵进程树,包括该命令启动后仍挂在其上的守护进程(如 adb server、dev-server watcher),并给出指引——先在守护进程自己的通道上停止、以分离方式启动,或对守护进程类工作直接使用 `run_in_background`。宿主的 subprocess/job 层仍拥有真实的终止语义;这是可操作的指引,不是对宿主的修复(#814)。
- The workspace bootstrap no longer refuses a root for being a reparse point before the DACL decision runs: a folder that already grants effective `WRITE_OWNER` answers `ready` with no tag inspection at all, so an OneDrive placeholder root (IO_REPARSE_TAG_CLOUD, no target) stops failing every workspace-write tool (#744). The tag check now lives on the only branch that writes the DACL, and only the proven cloud-files family passes — the exact 0x9000?01A shape (IO_REPARSE_TAG_CLOUD, CLOUD_ROOT, CLOUD_ON_DEMAND), allowed because a placeholder keeps a real directory entry behind the point; the rest of the reserved 0x90000000-0x9FFFFFFF band is unproven and fails closed exactly like mount points, symlinks, and unknown or unreadable tags, naming the tag it refused. Cloud tags cannot be synthesized in a unit fixture, so the family rule is pinned on the pure decision function `Get-DshOpsReparseTagDecision` and the fail-closed walk is pinned end to end with a real junction.
- 工作区引导脚本不再在 DACL 判定之前就因为「是重解析点」而拒绝根目录:已授予有效 `WRITE_OWNER` 的文件夹在完全不检查 tag 的情况下直接回答 `ready`,OneDrive 占位符根目录(IO_REPARSE_TAG_CLOUD,无目标)不再让所有 workspace-write 工具失败(#744)。tag 检查现在只存在于唯一会写 DACL 的分支上,且只有已证实的云文件族可以通过——精确的 0x9000?01A 形状(IO_REPARSE_TAG_CLOUD、CLOUD_ROOT、CLOUD_ON_DEMAND),放行理由是占位点后面保留真实目录项;保留段 0x90000000-0x9FFFFFFF 的其余部分未经证实,与挂载点、符号链接、未知或不可读 tag 一样闭锁拒绝,并写明所拒绝的具体 tag。云 tag 无法在单元夹具中合成,因此家族规则固定在纯判定函数 `Get-DshOpsReparseTagDecision` 上,闭锁遍历则用真实 junction 做端到端验证。
- A WSL UNC workspace (`\wsl.localhost\<distro>` or `\wsl$\<distro>`) no longer dies inside the workspace bootstrap: the 9P redirector behind those prefixes exposes no NTFS security descriptor, so `Get-Acl` threw and every workspace-write `run_code` call failed. Exactly those two Microsoft-fixed spellings now answer `ready` after the existence and container validation and before `Get-Acl` is touched — a prefix decision pinned on the pure classifier `Get-DshOpsWorkspaceNtfsState`, not a catch that swallows ACL errors: a missing path fails exactly like any other missing workspace, and a real ACL failure on any other path still fails closed (#669).
- WSL UNC 工作区(`\wsl.localhost\<发行版>` 或 `\wsl$\<发行版>`)不再死在工作区引导脚本里:这两个前缀背后的 9P 重定向器不暴露 NTFS 安全描述符,`Get-Acl` 因此抛错,workspace-write 下的每次 `run_code` 调用都失败。现在恰好这两个微软固定前缀会在完成存在性与目录验证之后、触碰 `Get-Acl` 之前直接回答 `ready`——判定固定在纯分类函数 `Get-DshOpsWorkspaceNtfsState` 上,是前缀判定而不是吞错 catch:不存在的路径与其他任何缺失工作区一样失败,其他任何路径保持原有行为,真实的 ACL 故障依然闭锁失败(#669)。
- The optional WSL read pays one wsl.exe startup for preparation instead of one per drive mapping plus one for the payload digest (#576): preparation is now a single fixed `/bin/sh -c` script whose text is a constant, with every drive root and the payload path as positional arguments, so no Windows path can alter the command shape. A small delegated read drops from four wsl.exe invocations (two drive mappings, one sha256sum, one worker) to two (one merged preparation, one worker). The wslpath mappings are still resolved anew per call, the payload digest must still match the receipt, and a refused mapping (exit 9), refused digest (exit 8) or failed spawn still falls back to the Windows worker exactly as before; the distribution now needs `/bin/sh` beside `wslpath` and `sha256sum`.
- 可选 WSL 读取的准备开销从「每个盘符一次 wsl.exe 外加一次摘要校验」合并为一次 wsl.exe 启动(#576):准备现在是一次固定 `/bin/sh -c` 脚本,脚本文本是常量,所有盘符根与 worker 路径都以位置参数传递,任何 Windows 路径都无法改变命令形状。一次小的委派读取从四次 wsl.exe 调用(两次盘符映射、一次 sha256sum、一次 worker)降为两次(一次合并准备、一次 worker)。wslpath 映射仍按每次调用重新解析,载荷摘要仍须与凭据一致,映射被拒(退出码 9)、摘要被拒(退出码 8)或进程启动失败仍与从前完全一样回退到 Windows worker;发行版在 `wslpath` 与 `sha256sum` 之外现在还需要 `/bin/sh`。

- Replace the `global.forceDefaultOpsPtc` switch with one explicit action: the row's detail page carries a **Make OPS (PTC) the default** button that writes `selectedDefault: ops-ptc` once and answers `applied`/`no-update`/`unavailable`/`failed`. Apply, remount and unload no longer write the default, so a preset chosen on the settings page is not overridden on the next apply, and a saved `global.forceDefaultOpsPtc` key still loads with no effect.
- 用一次显式操作取代 `global.forceDefaultOpsPtc` 开关:行详情页有一个「设为 OPS (PTC) 默认」按钮,点一次写 `selectedDefault: ops-ptc`,并回报 `applied`/`no-update`/`unavailable`/`failed`。apply、重挂载与卸载都不再改写默认,设置页选定的预设不会在下一次 apply 被覆盖;已保存的 `global.forceDefaultOpsPtc` 键仍可加载但不再生效。
Expand Down
Loading
Loading