Skip to content
Merged
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
82 changes: 82 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -668,6 +668,88 @@ jobs:
throw 'mise-path-ownership.ps1 must print duplicate owners before the plan-only exit.'
}

- name: Validate Tailscale fail-closed and User PATH convergence
shell: pwsh
run: |
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

# setup-tailscale.ps1 must fail closed when `tailscale status --json`
# cannot be parsed: the old code treated parse failure as "not
# running" and fell into `tailscale up --auth-key`, re-registering an
# already-enrolled node. And both scripts must decode the native JSON
# as UTF-8, because Windows PowerShell 5.1 uses the OEM code page and
# mojibake breaks ConvertFrom-Json on Japanese Windows.
$setup = Get-Content -LiteralPath ./platforms/windows-11/setup-tailscale.ps1 -Raw
foreach ($needle in 'Invoke-Utf8Native', 'Get-TailscaleStatus', 'UTF8', 'fail closed') {
if (-not $setup.Contains($needle)) { throw "setup-tailscale.ps1 is missing: $needle" }
}
$statusCall = $setup.IndexOf('$status = Get-TailscaleStatus')
$nullGuard = $setup.IndexOf('refusing to touch node registration')
$register = $setup.IndexOf("'up'")
if ($statusCall -lt 0 -or $nullGuard -lt 0 -or $register -lt 0) {
throw 'setup-tailscale.ps1 must read status through Get-TailscaleStatus and guard registration behind the fail-closed check.'
}
if (-not ($statusCall -lt $nullGuard -and $nullGuard -lt $register)) {
throw 'setup-tailscale.ps1 must throw on unknown status BEFORE reaching tailscale up.'
}

$verify = Get-Content -LiteralPath ./platforms/windows-11/verify.ps1 -Raw
foreach ($needle in 'Invoke-NativeUtf8', 'Microsoft.PowerShell', 'user-path.ps1', 'legacy .cargo\bin') {
if (-not $verify.Contains($needle)) { throw "verify.ps1 is missing: $needle" }
}

# user-path.ps1 edits HKCU\Environment\Path. Plan mode must be
# read-only; -Apply must back up the unexpanded value first and write
# through the registry with the original value kind preserved.
$up = './platforms/windows-11/user-path.ps1'
$tokens = $null; $parseErrors = $null
[void][System.Management.Automation.Language.Parser]::ParseFile((Resolve-Path $up).Path, [ref]$tokens, [ref]$parseErrors)
if ($parseErrors.Count -gt 0) { throw "user-path.ps1 does not parse: $($parseErrors[0].Message)" }
$upText = Get-Content -LiteralPath $up -Raw
foreach ($needle in 'param(', '[switch]$Apply', '[string]$Restore', 'HKCU', 'user-path-backup', 'DoNotExpandEnvironmentNames', '.cargo\bin', 'mise\shims') {
if (-not $upText.Contains($needle)) { throw "user-path.ps1 is missing: $needle" }
}
$backupIndex = $upText.IndexOf('user-path-backup')
$setValueIndex = $upText.IndexOf("SetValue('Path'")
if ($backupIndex -lt 0 -or $setValueIndex -lt 0 -or $setValueIndex -lt $backupIndex) {
throw 'user-path.ps1 must save the previous User PATH before writing it.'
}

# Plan mode on the CI runner must not write.
$userKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $false)
try { $before = $userKey.GetValue('Path', '', 'DoNotExpandEnvironmentNames') } finally { $userKey.Close() }
& $up *>&1 | Out-Null
if ($LASTEXITCODE -ne 0) { throw "user-path.ps1 plan mode exited $LASTEXITCODE" }
$userKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $false)
try { $after = $userKey.GetValue('Path', '', 'DoNotExpandEnvironmentNames') } finally { $userKey.Close() }
if ($before -ne $after) { throw 'user-path.ps1 changed the User PATH without -Apply.' }

# -Apply on the ephemeral runner must converge and be restorable:
# apply, confirm a second plan reports converged, restore the backup,
# confirm the original value is back.
$applyOut = (& $up -Apply *>&1 | Out-String)
if ($LASTEXITCODE -ne 0) { throw "user-path.ps1 -Apply exited $LASTEXITCODE`n$applyOut" }
$backupLine = [regex]::Match($applyOut, 'backup\s+(\S+\.txt)')
if (-not $backupLine.Success) { throw "user-path.ps1 -Apply printed no backup path`n$applyOut" }
$backupFile = $backupLine.Groups[1].Value
$converged = (& $up *>&1 | Out-String)
if ($converged -notmatch 'already converged') { throw "user-path.ps1 did not converge after -Apply`n$converged" }
& $up -Restore $backupFile *>&1 | Out-Null
if ($LASTEXITCODE -ne 0) { throw "user-path.ps1 -Restore exited $LASTEXITCODE" }
$userKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $false)
try { $restored = $userKey.GetValue('Path', '', 'DoNotExpandEnvironmentNames') } finally { $userKey.Close() }
if ($restored -ne $before) { throw 'user-path.ps1 -Restore did not put the original User PATH back.' }

# bootstrap.ps1 and converge.ps1 must both reach the same script so a
# fresh install and the hourly converge stay on one code path.
$bootstrap = Get-Content -LiteralPath ./bootstrap.ps1 -Raw
if (-not $bootstrap.Contains('user-path.ps1')) { throw 'bootstrap.ps1 must invoke user-path.ps1.' }
$converge = Get-Content -LiteralPath ./platforms/windows-11/converge.ps1 -Raw
if (-not $converge.Contains('user-path.ps1') -or -not $converge.Contains("Invoke-Step 'user-path'")) {
throw 'converge.ps1 must run user-path.ps1 as a named step.'
}

- name: Validate converge survives a step error and always reports
shell: pwsh
run: |
Expand Down
10 changes: 10 additions & 0 deletions bootstrap.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,16 @@ finally {
Install-NotionMsix
Install-StoreApps

# User PATH convergence (ADR-0021): drop the legacy .cargo\bin rustup proxy
# entry and guarantee the mise shims entry. HKCU only with a backup; a failure
# must not stop bootstrap — verify.ps1 reports the resulting state.
try {
& (Join-Path $applyDir 'platforms\windows-11\user-path.ps1') -Apply
}
catch {
Write-Warning "User PATH convergence failed: $($_.Exception.Message)"
}

# Rex is in public beta and its Windows server still requires tester
# enrollment, so a failed install or `rex server install --user` must not stop
# the rest of the machine bootstrap. platforms/windows-11/verify.ps1 reports
Expand Down
6 changes: 5 additions & 1 deletion docs/adr/ADR-0021.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,11 @@ orphan shim は上の「Rust CLI は mise の cargo backend で宣言する」

- mise 管理のツールは、`mise activate` された shell で mise が先頭に差し込む install dir / shim で解決される。activation が無い経路 (Scheduled Task / IDE / GUI / `pwsh -NoProfile`) では、registry PATH 上の同名 binary が勝つ。
- registry (User/Machine) PATH には mise shim dir だけを mise 由来の最小集合として置く。`%USERPROFILE%\.cargoin` のような mise の data dir 外の Rust home は registry PATH に置かない。
- 同名の重複 (Program Files / npm global / bun / chocolatey) は、その管理者が自己更新する GUI・vendor 経路を壊しうるため、自動では削除しない。`verify.ps1` は非 activation 経路で mise 外に解決されるものを WARN として列挙する。
- 同名の重複 (Program Files / npm global / bun / chocolatey) は、その管理者が自己更新する GUI・vendor 経路を壊しうるため、自動では削除しない。`verify.ps1` は Tool ownership で非 activation 経路の mise 外解決を FAIL として報告し、`mise-path-ownership.ps1` が Machine PATH の冗長 entry を除去する。

## Addendum (#174, 2026-11-23): User PATH の収束は user-path.ps1 が担う

「`%USERPROFILE%\.cargo\bin` は User PATH から外す」の実施手段として `platforms/windows-11/user-path.ps1` を追加した。HKCU の User PATH だけを対象に、展開後の完全一致で legacy `.cargo\bin` entry を除去し、`%LOCALAPPDATA%\mise\shims` の存在を保証する。既定は plan のみで、`-Apply` は書き込み前に生値を state dir へ backup し、`-Restore` で復元できる。`bootstrap.ps1` と `converge.ps1` の双方から呼ばれ、`verify.ps1` は未収束を FAIL として報告する。

## Consequences

Expand Down
21 changes: 21 additions & 0 deletions platforms/windows-11/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,8 @@ pwsh -NoProfile -File platforms/windows-11/powershell-path.ps1 -Apply # 管理

並び順だけを変更し、PATH entry も PowerShell 本体も削除しない。変更前の PATH は `%LOCALAPPDATA%\pc-setup` に保存する。

`winget:Microsoft.PowerShell` は MSI と MSIX のどちらの package も同じ正本として導入されうる。MSIX の場合 `pwsh` は `%LOCALAPPDATA%\Microsoft\WindowsApps\Microsoft.PowerShell_<ver>_x64__<publisher>\pwsh.exe` の per-user 実行エイリアスに解決される。`verify.ps1` は MSI path・MSIX `InstallLocation`・実行エイリアスのいずれにも一致すれば正本として受理する。

### Herdr

実機の Herdr は GitHub backend (`github:herdrdev/herdr`、aqua registry より新しい)。Windows だけこの宣言を `mise.global.toml` に置き、Linux/macOS は従来の registry entry のまま。`mise.global.lock` には Windows の GitHub backend entry を追加している。
Expand Down Expand Up @@ -180,6 +182,10 @@ infisical login --domain=https://secrets.rebuildup.dev

setup script は Infisical から OAuth secret を runtime injectionし、未接続の host だけを persistent / preauthorized node として登録する。既に Tailscale backend が `Running` の host は既存 node identity を維持し、再登録しない。

`tailscale status --json` の出力は UTF-8 で decode する。Windows PowerShell 5.1 が console の OEM code page で decode すると、日本語 Windows では Health 文字列が文字化けして `ConvertFrom-Json` が失敗するため、status / serve の呼び出しは一時的に UTF-8 へ切り替えて実行する。

status が取得・parse できない場合は **fail closed** とし、node 登録 (`tailscale up --auth-key`) へ進まない。状態不明を「未接続」と誤認して既存 node を再登録する経路はない。`BackendState` が判明して `Running` 以外 (`NeedsLogin` / `Stopped` など) の場合だけ登録処理へ進む。

その後 Tailscale Serve を idempotent に収束させるため、WSL 側の SSH endpoint は従来どおり Windows localhost にだけ bind したままでよい。LAN interfaceへ `2222` / `2223` を直接公開しない。

詳細な authority / recovery boundary は [ADR-0011](../../docs/adr/ADR-0011.md) を参照。
Expand Down Expand Up @@ -306,6 +312,21 @@ pwsh -NoProfile -File platforms/windows-11/mise-path-ownership.ps1 -Restore <bac
- 管理者権限が無い場合、`-Apply` は変更せず終了する。
- 変更は新規プロセスにのみ効く。既に起動済みの shell は古い PATH を保持し続けるため、PATH から外したコピーを解決しようとして失敗することがある。`-Apply` 後は新しいターミナルを開く。

### User PATH の収束 (`user-path.ps1`)

ADR-0021 は registry User PATH に置く mise 由来の entry を `%LOCALAPPDATA%\mise\shims` だけとし、旧 Rust home の `%USERPROFILE%\.cargo\bin` を外すことを要求する。`platforms/windows-11/user-path.ps1` がその収束を行う。

```powershell
pwsh -NoProfile -File platforms/windows-11/user-path.ps1 # plan のみ (書き込みなし)
pwsh -NoProfile -File platforms/windows-11/user-path.ps1 -Apply # HKCU のみ、昇格不要
pwsh -NoProfile -File platforms/windows-11/user-path.ps1 -Restore <backup-file>
```

- 変更するのは **User PATH (HKCU) のみ**。展開後の完全一致で `.cargo\bin` entry を除去し、mise shims entry が無ければ末尾へ追加する。並び順は変えず、他の entry・ファイル・ディレクトリは触らない。
- Machine PATH は `mise-path-ownership.ps1` の担当であり、この script は触らない。
- 書き込み前に展開前の生値を `%LOCALAPPDATA%\pc-setup\user-path-backup\user-path-<timestamp>.txt` に保存する。registry の値 kind (REG_SZ / REG_EXPAND_SZ) は保持する。
- `bootstrap.ps1` と `converge.ps1` の両方から呼ばれ、再実行は冪等。`verify.ps1` は `.cargo\bin` 残存と shims entry 欠落を FAIL として報告する。

### 宣言済みツールの実行確認

`verify.ps1` は `Get-Command` による**解決**だけでなく、宣言済みツールを**実際に起動**して確認する。存在確認では検出できない破損があるため。
Expand Down
23 changes: 23 additions & 0 deletions platforms/windows-11/converge.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,28 @@ function Invoke-MiseApply {
}
}

# Converges the per-user PATH (ADR-0021): drops the legacy .cargo\bin rustup
# proxy entry and guarantees the mise shims entry. HKCU only, exact-match
# removal, backup before write — user-path.ps1 is idempotent by design.
function Invoke-UserPath {
if (-not $script:DeployOk) {
Add-Step 'user-path' 'skipped' 'deploy checkout not converged in this run'
return
}
$userPath = Join-Path (Join-Path (Join-Path $DeployDir 'platforms') 'windows-11') 'user-path.ps1'
if (-not (Test-Path -LiteralPath $userPath)) {
Add-Step 'user-path' 'skipped' 'no user-path.ps1 in the deploy checkout'
return
}
& powershell.exe -NoProfile -ExecutionPolicy Bypass -File $userPath -Apply *>&1 | ForEach-Object { Write-Log ([string]$_) }
$code = $LASTEXITCODE
if ($code -eq 0) {
Add-Step 'user-path' 'ok' 'User PATH converged'
} else {
Add-Step 'user-path' 'error' ('user-path.ps1 -Apply exited ' + $code + '; see ' + $script:LogFile)
}
}

# Derived from current state, not from a previous run: dsh is pending when
# `npm:@deepseek-ai/dsh` is installed on this machine but the deployed
# mise.global.toml does not declare it (it exists only in an unmerged PR; ADR-0016).
Expand Down Expand Up @@ -531,6 +553,7 @@ function Invoke-Main {

Invoke-Step 'deploy-sync' { Sync-Deploy }
Invoke-Step 'mise-apply' { Invoke-MiseApply }
Invoke-Step 'user-path' { Invoke-UserPath }
Invoke-Step 'dsh-declaration' { Test-DshDeclaration }
Invoke-Step 'dotfiles-sync' { Invoke-DotfilesSync }
Invoke-Step 'devices-sync' { Sync-Devices }
Expand Down
79 changes: 66 additions & 13 deletions platforms/windows-11/setup-tailscale.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,58 @@ function Invoke-Checked {
}
}

# `tailscale status --json` emits UTF-8. Windows PowerShell 5.1 on a Japanese
# (or any non-UTF-8) console decodes native output with the OEM code page, so
# the Health strings arrive as mojibake and ConvertFrom-Json fails on
# 'Path 'Health[0]''. Decode as UTF-8 for the duration of the call and restore
# the previous encoding afterwards; a failure to set it must not stop the
# script, because the parse below still fails closed on bad output.
function Invoke-Utf8Native {
param(
[Parameter(Mandatory)][string]$Command,
[Parameter(Mandatory)][string[]]$Arguments
)

$previousEncoding = $null
try {
$previousEncoding = [Console]::OutputEncoding
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
}
catch { }

try {
$output = @(& $Command @Arguments 2>$null)
$exitCode = $LASTEXITCODE
}
finally {
if ($null -ne $previousEncoding) {
try { [Console]::OutputEncoding = $previousEncoding } catch { }
}
}

return [pscustomobject]@{ Output = $output; ExitCode = $exitCode }
}

# Returns the parsed `tailscale status --json` object, or $null when the state
# cannot be determined. Callers MUST treat $null as "unknown" and fail closed:
# an unparseable status once fell through to the `tailscale up --auth-key`
# path and re-registered a node that was already enrolled.
function Get-TailscaleStatus {
param([Parameter(Mandatory)]$TailscaleCommand)

$result = Invoke-Utf8Native -Command $TailscaleCommand -Arguments @('status', '--json')
if ($result.ExitCode -ne 0 -or $result.Output.Count -eq 0) {
return $null
}

try {
return (($result.Output -join [Environment]::NewLine) | ConvertFrom-Json)
}
catch {
return $null
}
}

if ([System.Environment]::OSVersion.Platform -ne [System.PlatformID]::Win32NT) {
throw 'This setup targets Windows.'
}
Expand Down Expand Up @@ -107,18 +159,18 @@ if ([string]::IsNullOrWhiteSpace($oauthSecret)) {
throw "Required Infisical secret is not injected: $secretName"
}

$status = $null
$statusOutput = @(& $tailscale status --json 2>$null)
if ($LASTEXITCODE -eq 0 -and $statusOutput.Count -gt 0) {
try {
$status = ($statusOutput -join [Environment]::NewLine) | ConvertFrom-Json
}
catch {
$status = $null
}
$status = Get-TailscaleStatus -TailscaleCommand $tailscale

if ($null -eq $status -or $null -eq $status.BackendState) {
# Fail closed: the backend state is unknown, so this script cannot tell a
# fresh machine (NeedsLogin) from an already-enrolled node whose status
# output failed to decode. Re-registering here once replaced a healthy
# node identity; refuse instead and let the operator re-run once the
# status command works.
throw 'tailscale status --json is unavailable or unparseable; refusing to touch node registration (fail closed). Re-run after Tailscale is responsive.'
}

if (-not $status -or $status.BackendState -ne 'Running') {
if ($status.BackendState -ne 'Running') {
Write-Host 'Registering Windows host with Tailscale'
$authKey = "${oauthSecret}?$($config.Tailscale.AuthKeyParameters)"
try {
Expand Down Expand Up @@ -147,9 +199,10 @@ foreach ($mapping in $config.Tailscale.Serve) {
) -Description "Tailscale Serve $($mapping.ListenPort)"
}

$serveStatus = @(& $tailscale serve status 2>$null) -join [Environment]::NewLine
if ($LASTEXITCODE -ne 0) {
throw "Tailscale Serve status failed with exit code $LASTEXITCODE"
$serveResult = Invoke-Utf8Native -Command $tailscale -Arguments @('serve', 'status')
$serveStatus = ($serveResult.Output -join [Environment]::NewLine)
if ($serveResult.ExitCode -ne 0) {
throw "Tailscale Serve status failed with exit code $($serveResult.ExitCode)"
}

foreach ($mapping in $config.Tailscale.Serve) {
Expand Down
Loading