Skip to content
Draft
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
53 changes: 53 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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: |
Expand Down Expand Up @@ -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: |
Expand Down
40 changes: 31 additions & 9 deletions scripts/apply-global-mise.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand Down
2 changes: 2 additions & 0 deletions scripts/ci.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
190 changes: 190 additions & 0 deletions scripts/mise-config-target.ps1
Original file line number Diff line number Diff line change
@@ -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
}
Loading