From 8b0f9364550b13b67291331a6f3292f81aed2104 Mon Sep 17 00:00:00 2001 From: rebuildup Date: Mon, 30 Nov 2026 14:36:10 +0900 Subject: [PATCH] =?UTF-8?q?fix(#281):=20machine-global=20mise=20config=20?= =?UTF-8?q?=E3=82=92=E5=8E=9F=E5=AD=90=E7=9A=84=E3=81=AB=E6=9B=B8=E3=81=8D?= =?UTF-8?q?=E3=80=81=E7=A9=BA=E3=83=95=E3=82=A1=E3=82=A4=E3=83=AB=E3=81=A8?= =?UTF-8?q?=20backup=20=E4=B8=8A=E9=99=90=E3=82=92=E6=89=B1=E3=81=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Windows の machine-global mise config (`~/.config/mise/config.toml`) が 0 bytes になると、managed marker の guard が「unmanaged」と判定して以後すべての apply を 拒否する。結果は mise shim が全滅し (No version is set for shim: ...)、旧 `%USERPROFILE%\.rustup` / `.cargo` が再生成される。実機では毎時 converge が `LastTaskResult = 1` のまま provision できない状態が続いていた。 - 書き込みを atomic 化 (一時ファイルへ書いてから置換)。WriteAllText の truncate 後に中断されると truncated config が残るため。 - 0 bytes の config は user content を持たないので採用する。空でない unmanaged config は従来どおり拒否する。 - backup (`config.toml.pc-setup-backup-*`) を直近 5 件に制限し、無制限増加を 止める。 - 保護ルールを副作用のない `scripts/mise-config-target.ps1` に切り出し、 `scripts/test-mise-config-target.ps1` で直接検証する。CI (ci.sh / ci.yml) にも追加。 Co-Authored-By: Claude Code --- .github/workflows/ci.yml | 53 ++++++++ scripts/apply-global-mise.ps1 | 40 ++++-- scripts/ci.sh | 2 + scripts/mise-config-target.ps1 | 190 ++++++++++++++++++++++++++++ scripts/test-mise-config-target.ps1 | 117 +++++++++++++++++ 5 files changed, 393 insertions(+), 9 deletions(-) create mode 100644 scripts/mise-config-target.ps1 create mode 100644 scripts/test-mise-config-target.ps1 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 07241e15..6b68bcd9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -956,6 +956,14 @@ jobs: shell: pwsh run: ./scripts/test-windows-mise-config.ps1 + # scripts/test-mise-config-target.ps1 exercises the protection rules for + # the machine-global mise config target (scripts/mise-config-target.ps1): + # an empty config has to be adoptable, an unmanaged one has to be + # refused, and the write has to replace the target as a whole. + - name: Validate machine-global mise config target rules + shell: pwsh + run: ./scripts/test-mise-config-target.ps1 + - name: Validate the apply keeps the committed lock read-only shell: pwsh run: | @@ -1014,6 +1022,51 @@ jobs: Remove-Item -LiteralPath $root -Recurse -Force -ErrorAction SilentlyContinue } + # Regression: an interrupted apply left the machine-global config at zero + # bytes, and the managed-marker guard then refused to overwrite it, so + # every later apply failed and every mise shim stayed broken + # ("No version is set for shim: gh"). The apply has to adopt a zero-length + # config and write the rendered one. + - name: Validate the apply recovers an empty machine-global config + shell: pwsh + run: | + Set-StrictMode -Version Latest + $ErrorActionPreference = 'Stop' + + $root = Join-Path ([System.IO.Path]::GetTempPath()) "pc-setup-emptyconfig-$([guid]::NewGuid())" + $fakeBin = Join-Path $root 'bin' + $target = Join-Path $root 'config.toml' + New-Item -ItemType Directory -Path $fakeBin -Force | Out-Null + $oldPath = $env:PATH + + try { + $fakeMise = @( + '@echo off', + 'exit /b 0' + ) -join "`r`n" + Set-Content -LiteralPath (Join-Path $fakeBin 'mise.cmd') -Value $fakeMise + $env:PATH = "$fakeBin;$oldPath" + $env:MISE_GLOBAL_CONFIG_FILE = $target + $env:MISE_GITHUB_TOKEN = 'ci-placeholder' + + # The state an interrupted write leaves behind. + [System.IO.File]::WriteAllText($target, '') + + & ./scripts/apply-global-mise.ps1 | Out-Null + if ($LASTEXITCODE -ne 0) { throw "apply-global-mise.ps1 exited $LASTEXITCODE" } + + $content = [System.IO.File]::ReadAllText($target) + if ($content.Length -eq 0) { throw 'the apply left the machine-global config empty' } + if (-not $content.StartsWith('# Managed by rebuildup/pc-setup.')) { + throw 'the apply did not write a managed config' + } + } + finally { + $env:PATH = $oldPath + Remove-Item Env:MISE_GLOBAL_CONFIG_FILE, Env:MISE_GITHUB_TOKEN, Env:MISE_LOCKED -ErrorAction SilentlyContinue + Remove-Item -LiteralPath $root -Recurse -Force -ErrorAction SilentlyContinue + } + - name: Validate the apply aligns the rustup default toolchain shell: pwsh run: | diff --git a/scripts/apply-global-mise.ps1 b/scripts/apply-global-mise.ps1 index 7fff9718..41a22729 100644 --- a/scripts/apply-global-mise.ps1 +++ b/scripts/apply-global-mise.ps1 @@ -48,12 +48,16 @@ if (-not (Test-Path -LiteralPath $SourceConfig)) { $targetDir = Split-Path -Parent $TargetConfig New-Item -ItemType Directory -Path $targetDir -Force | Out-Null -if (Test-Path -LiteralPath $TargetConfig) { - $firstLine = Get-Content -LiteralPath $TargetConfig -TotalCount 1 - if ($firstLine -ne $ManagedMarker) { - throw "refusing to overwrite unmanaged mise global config: $TargetConfig" - } -} +# The protection rules for the config target live in mise-config-target.ps1 so +# they can be exercised directly (scripts/test-mise-config-target.ps1). +. (Join-Path $PSScriptRoot 'mise-config-target.ps1') + +# A config that already holds content is only overwritten when this repository +# wrote it (the managed marker). A zero-length file holds no user content at +# all: it is the residue of an interrupted write, and refusing to touch it +# would leave the machine without any machine-global config and without a way +# to get one back, because every later run would refuse as well (issue #281). +Assert-MiseConfigOverwritable -Path $TargetConfig -ManagedMarker $ManagedMarker | Out-Null # Windows-only rewrites of the shared machine-global config live in # scripts/windows-mise-config.ps1 so CI can exercise them directly. @@ -68,16 +72,34 @@ if (Test-Path -LiteralPath $TargetConfig) { $existingContent = [System.IO.File]::ReadAllText($TargetConfig) if ($existingContent -ne $targetContent) { $backup = "$TargetConfig.pc-setup-backup-$(Get-Date -Format 'yyyyMMdd-HHmmss')" - Copy-Item -LiteralPath $TargetConfig -Destination $backup + Copy-Item -LiteralPath $TargetConfig -Destination $backup -Force Write-Host "backup $backup" } } -[System.IO.File]::WriteAllText($TargetConfig, $targetContent, (New-Object System.Text.UTF8Encoding($false))) +# Write atomically. WriteAllText truncates before it writes, so an interrupted +# run (scheduled task killed, machine suspended, power loss) leaves a +# zero-length machine-global config behind. Every mise shim then fails with +# "No version is set for shim: ..." and the marker guard above refuses to +# repair the file, which is how this machine ended up without any +# machine-global config at all (issue #281). Writing a sibling file first and +# replacing the target as a whole leaves the target either the old content or +# the new content, never a partial write. +Write-MiseConfigAtomic -Path $TargetConfig -Content $targetContent Write-Host "synced $TargetConfig <- $SourceConfig" +# The backup files above are kept per content change, which made the config +# directory grow without bound (26 files in one month on the audited machine). +# Keep the most recent ones and drop the rest, so the residue does not +# accumulate again (issue #281). +foreach ($pruned in (Remove-StaleMiseConfigBackups -Path $TargetConfig -Keep 5)) { + Write-Host "pruned $pruned" +} + if (Test-Path -LiteralPath $SourceLock) { - Copy-Item -LiteralPath $SourceLock -Destination $TargetLock -Force + # Copy atomically for the same reason the config is written atomically: a + # truncated lock breaks `mise install --locked` for every tool it covers. + Copy-MiseFileAtomic -Source $SourceLock -Destination $TargetLock Write-Host "synced $TargetLock <- $SourceLock" # The lock references its dependency sidecars by a path relative to the diff --git a/scripts/ci.sh b/scripts/ci.sh index 31f0e080..aa171470 100755 --- a/scripts/ci.sh +++ b/scripts/ci.sh @@ -509,6 +509,8 @@ grep -Fq 'windows-mise-config.ps1' scripts/apply-global-mise.ps1 if command -v pwsh >/dev/null 2>&1; then printf 'Running Windows mise config renderer checks...\n' pwsh -NoProfile -NonInteractive -File scripts/test-windows-mise-config.ps1 + printf 'Running machine-global mise config target checks...\n' + pwsh -NoProfile -NonInteractive -File scripts/test-mise-config-target.ps1 fi # Both CI steps that run apply-global-mise.sh under a strict fake mise have to diff --git a/scripts/mise-config-target.ps1 b/scripts/mise-config-target.ps1 new file mode 100644 index 00000000..1c6541c8 --- /dev/null +++ b/scripts/mise-config-target.ps1 @@ -0,0 +1,190 @@ +# Protection rules for the machine-global mise config target. +# +# The machine-global config (`~/.config/mise/config.toml`) is the file that +# decides which tools every shell on the machine can run. Writing it is the one +# operation on this machine that can take the whole toolchain down, so the +# rules live here, in a file with no side effects, and are exercised directly by +# scripts/test-mise-config-target.ps1. +# +# Rules: +# +# * A config that holds content is only overwritten when this repository wrote +# it (the managed marker). A user's own config is never replaced. +# * A zero-length config holds no user content. It is the residue of an +# interrupted write, and refusing to touch it would leave the machine +# without a machine-global config and without a way to get one back, +# because every later run would refuse as well. (rebuildup/pc-setup#281) +# * The write is atomic: the target is replaced as a whole, never truncated +# in place, so an interrupted run cannot leave a half-written config. +# * The backup copies made on every content change are bounded, so the +# config directory cannot grow without limit. (rebuildup/pc-setup#281) + +Set-StrictMode -Version Latest + +function Get-MiseConfigState { + <# + .SYNOPSIS + Classify the machine-global mise config target. + .DESCRIPTION + Returns one of: + missing - the file does not exist + empty - the file exists and has zero length + managed - the file exists, is not empty, and starts with the managed marker + unmanaged - the file exists, is not empty, and was not written by this repository + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [string]$Path, + + [Parameter(Mandatory)] + [string]$ManagedMarker + ) + + if (-not (Test-Path -LiteralPath $Path)) { return 'missing' } + if ((Get-Item -LiteralPath $Path).Length -eq 0) { return 'empty' } + + $firstLine = Get-Content -LiteralPath $Path -TotalCount 1 + if ($firstLine -eq $ManagedMarker) { return 'managed' } + return 'unmanaged' +} + +function Assert-MiseConfigOverwritable { + <# + .SYNOPSIS + Refuse to overwrite a config this repository did not write. + .DESCRIPTION + Throws for an unmanaged config. An empty config is accepted: it carries no + user content and is the only state a machine can still recover from. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [string]$Path, + + [Parameter(Mandatory)] + [string]$ManagedMarker + ) + + $state = Get-MiseConfigState -Path $Path -ManagedMarker $ManagedMarker + if ($state -eq 'unmanaged') { + throw "refusing to overwrite unmanaged mise global config: $Path" + } + return $state +} + +function Write-MiseConfigAtomic { + <# + .SYNOPSIS + Replace a file with new content without ever truncating it in place. + .DESCRIPTION + The content is written to a sibling temporary file first and then moved + over the target. A reader therefore sees either the previous content or the + new content, never a partial file. When the target exists it is replaced + with the atomic NTFS replace operation; the fallback (remove, then move) + can lose the file for the duration of the move, which the next run repairs + because a missing config is not an unmanaged config. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [string]$Path, + + [Parameter(Mandatory)] + [string]$Content + ) + + $tempPath = "$Path.pc-setup-tmp-$PID" + try { + [System.IO.File]::WriteAllText($tempPath, $Content, (New-Object System.Text.UTF8Encoding($false))) + if ([System.IO.File]::Exists($Path)) { + try { + [System.IO.File]::Replace($tempPath, $Path, $null, $true) + } + catch { + Remove-Item -LiteralPath $Path -Force + [System.IO.File]::Move($tempPath, $Path) + } + } + else { + [System.IO.File]::Move($tempPath, $Path) + } + } + finally { + Remove-Item -LiteralPath $tempPath -Force -ErrorAction SilentlyContinue + } +} + +function Copy-MiseFileAtomic { + <# + .SYNOPSIS + Replace a file with the byte content of another file, atomically. + .DESCRIPTION + The lock file is read by `mise install --locked`, so a truncated lock + breaks every tool it covers. The copy therefore replaces the target as a + whole instead of writing into it. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [string]$Source, + + [Parameter(Mandatory)] + [string]$Destination + ) + + $tempPath = "$Destination.pc-setup-tmp-$PID" + try { + Copy-Item -LiteralPath $Source -Destination $tempPath -Force + if ([System.IO.File]::Exists($Destination)) { + try { + [System.IO.File]::Replace($tempPath, $Destination, $null, $true) + } + catch { + Remove-Item -LiteralPath $Destination -Force + [System.IO.File]::Move($tempPath, $Destination) + } + } + else { + [System.IO.File]::Move($tempPath, $Destination) + } + } + finally { + Remove-Item -LiteralPath $tempPath -Force -ErrorAction SilentlyContinue + } +} + +function Remove-StaleMiseConfigBackups { + <# + .SYNOPSIS + Keep only the most recent backup copies of the machine-global config. + .DESCRIPTION + Every content change writes a timestamped backup next to the config. The + backup is the only record of a local edit that the overwrite discarded, so + the most recent ones are kept and the rest are removed. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [string]$Path, + + [int]$Keep = 5 + ) + + $directory = Split-Path -Parent $Path + if (-not (Test-Path -LiteralPath $directory)) { return @() } + + $pattern = (Split-Path -Leaf $Path) + '.pc-setup-backup-*' + $backups = @( + Get-ChildItem -Path $directory -Filter $pattern -File -ErrorAction SilentlyContinue | + Sort-Object -Property LastWriteTime -Descending + ) + if ($backups.Count -le $Keep) { return @() } + + $removed = @() + foreach ($stale in @($backups[$Keep..($backups.Count - 1)])) { + Remove-Item -LiteralPath $stale.FullName -Force + $removed += $stale.Name + } + return $removed +} diff --git a/scripts/test-mise-config-target.ps1 b/scripts/test-mise-config-target.ps1 new file mode 100644 index 00000000..a1de9412 --- /dev/null +++ b/scripts/test-mise-config-target.ps1 @@ -0,0 +1,117 @@ +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' + +. (Join-Path $PSScriptRoot 'mise-config-target.ps1') + +$marker = '# Managed by rebuildup/pc-setup.' +$root = Join-Path ([System.IO.Path]::GetTempPath()) "pc-setup-config-target-$([guid]::NewGuid())" +New-Item -ItemType Directory -Force -Path $root | Out-Null + +try { + $target = Join-Path $root 'config.toml' + + # A missing config is the normal fresh-machine state. + if ((Get-MiseConfigState -Path $target -ManagedMarker $marker) -ne 'missing') { + throw 'a missing config must be reported as missing' + } + Write-Host 'ok missing config detected' + + # A zero-length config is the residue of an interrupted write. It must be + # adoptable, otherwise the machine can never recover (pc-setup#281). + [System.IO.File]::WriteAllText($target, '') + if ((Get-MiseConfigState -Path $target -ManagedMarker $marker) -ne 'empty') { + throw 'a zero-length config must be reported as empty' + } + $state = Assert-MiseConfigOverwritable -Path $target -ManagedMarker $marker + if ($state -ne 'empty') { + throw "an empty config must be adoptable, got: $state" + } + Write-Host 'ok empty config is adoptable' + + # A config this repository wrote is overwritten. + [System.IO.File]::WriteAllText($target, "$marker`nvalue = 1`n") + if ((Get-MiseConfigState -Path $target -ManagedMarker $marker) -ne 'managed') { + throw 'a config with the managed marker must be reported as managed' + } + Assert-MiseConfigOverwritable -Path $target -ManagedMarker $marker | Out-Null + Write-Host 'ok managed config is overwritable' + + # A config the user wrote is never replaced. + [System.IO.File]::WriteAllText($target, "# user config`nvalue = 2`n") + if ((Get-MiseConfigState -Path $target -ManagedMarker $marker) -ne 'unmanaged') { + throw 'a config without the managed marker must be reported as unmanaged' + } + $refused = $false + try { + Assert-MiseConfigOverwritable -Path $target -ManagedMarker $marker | Out-Null + } + catch { + $refused = $true + } + if (-not $refused) { + throw 'an unmanaged config must be refused' + } + if ([System.IO.File]::ReadAllText($target) -notmatch 'user config') { + throw 'the refused config was modified' + } + Write-Host 'ok unmanaged config is refused and left untouched' + + # The write replaces the target as a whole: no leftover temporary file, + # and the content is exactly what was requested. + Write-MiseConfigAtomic -Path $target -Content "$marker`nvalue = 3`n" + if ([System.IO.File]::ReadAllText($target) -ne "$marker`nvalue = 3`n") { + throw 'atomic write did not produce the requested content' + } + $leftovers = @(Get-ChildItem -Path $root -Filter '*.pc-setup-tmp-*' -File -ErrorAction SilentlyContinue) + if ($leftovers.Count -ne 0) { + throw "atomic write left temporary files: $($leftovers.Name -join ', ')" + } + Write-Host 'ok atomic write replaces the target and leaves no temporary file' + + # An atomic write over a missing target creates it. + $fresh = Join-Path $root 'fresh.toml' + Write-MiseConfigAtomic -Path $fresh -Content "$marker`nfresh`n" + if (-not [System.IO.File]::Exists($fresh)) { + throw 'atomic write did not create a missing target' + } + Write-Host 'ok atomic write creates a missing target' + + # The atomic copy behaves the same way for the lock. + $source = Join-Path $root 'source.lock' + [System.IO.File]::WriteAllText($source, "lockfile_version = 3`n") + $lockTarget = Join-Path $root 'mise.lock' + Copy-MiseFileAtomic -Source $source -Destination $lockTarget + if ([System.IO.File]::ReadAllText($lockTarget) -ne "lockfile_version = 3`n") { + throw 'atomic copy did not produce the requested content' + } + Copy-MiseFileAtomic -Source $source -Destination $lockTarget + Write-Host 'ok atomic copy replaces an existing target' + + # Backups are bounded: the newest ones are kept, the rest are removed. + $backupDir = Join-Path $root 'backups' + New-Item -ItemType Directory -Force -Path $backupDir | Out-Null + $backupTarget = Join-Path $backupDir 'config.toml' + for ($i = 0; $i -lt 9; $i++) { + $backup = "$backupTarget.pc-setup-backup-2026010$('{0:d2}' -f $i)-000000" + [System.IO.File]::WriteAllText($backup, "backup $i") + (Get-Item -LiteralPath $backup).LastWriteTime = (Get-Date).AddMinutes(-$i) + } + $removed = Remove-StaleMiseConfigBackups -Path $backupTarget -Keep 3 + $remaining = @(Get-ChildItem -Path $backupDir -Filter 'config.toml.pc-setup-backup-*' -File) + if ($remaining.Count -ne 3) { + throw "expected 3 backups to remain, got $($remaining.Count)" + } + if ($removed.Count -ne 6) { + throw "expected 6 backups to be pruned, got $($removed.Count)" + } + $newest = ($remaining | Sort-Object -Property LastWriteTime -Descending | Select-Object -First 1).Name + if ($newest -notmatch '2026010[01]') { + throw "the newest backup was not kept: $newest" + } + Write-Host 'ok backups are bounded and the newest ones survive' +} +finally { + Remove-Item -LiteralPath $root -Recurse -Force -ErrorAction SilentlyContinue +} + +Write-Host 'ok mise config target rules verified'