From fea495944141a02c397b6e8f936c788e5d6d74a5 Mon Sep 17 00:00:00 2001 From: Ayan Khan Date: Mon, 23 Nov 2026 08:13:17 +0530 Subject: [PATCH 01/21] feat(windows): add verified CLI installer with journaled recovery --- install.ps1 | 813 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 813 insertions(+) create mode 100644 install.ps1 diff --git a/install.ps1 b/install.ps1 new file mode 100644 index 0000000..c02ed6f --- /dev/null +++ b/install.ps1 @@ -0,0 +1,813 @@ +# Install the official Proofline Windows x64 CLI release for the current user. +# Installer-managed upgrades use a verified previous image, a pending journal, +# and postcheck/rollback. Installer-managed upgrades have Windows 5.1 test coverage. +# .\install.ps1 [-Version 0.5.2] [-InstallDir C:\path\to\bin] [-NoModifyPath] +[CmdletBinding()] +param( + [string]$Version, + [string]$InstallDir, + [switch]$NoModifyPath +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' + +$script:ProoflineArchiveName = 'proofline-x86_64-pc-windows-msvc.tar.gz' +$script:ProoflineOrigin = 'https://proofline.sh' +$script:MaxArchiveBytes = 64 * 1024 * 1024 +$script:MaxExecutableBytes = 128 * 1024 * 1024 + +function Assert-ProoflinePlatform { + if ([Environment]::OSVersion.Platform -ne [PlatformID]::Win32NT) { + throw 'The Windows installer can run only on Windows.' + } + $architecture = [Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString() + if ($architecture -ne 'X64') { + throw "No official Windows release is available for architecture '$architecture' (expected X64)." + } +} + +function Assert-ProoflineVersion([string]$Value) { + if ($Value.Length -gt 32 -or $Value -cnotmatch '\A(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\z') { + throw 'Expected a release version of the form X.Y.Z, containing only digits and dots.' + } + return $Value +} + +function Get-ProoflineOfficialBytes([string]$RelativePath, [int]$MaximumLength) { + # The relative path is assembled exclusively from constant strings and a + # validated version. Do not expose arbitrary URLs to installer arguments. + if ($RelativePath -notmatch '\A/cli/(latest|download/[0-9]+\.[0-9]+\.[0-9]+/(SHA256SUMS|proofline-x86_64-pc-windows-msvc\.tar\.gz))\z') { + throw 'Invalid official release request.' + } + Add-Type -AssemblyName System.Net.Http + $handler = [Net.Http.HttpClientHandler]::new() + $handler.AllowAutoRedirect = $false + # PowerShell 5.1 uses .NET Framework, where HttpClientHandler.SslProtocols + # may not be implemented. Scope TLS 1.2 to this download and restore the + # process policy afterward. PowerShell 7 retains the system TLS defaults. + $originalProtocol = $null + if ($PSVersionTable.PSVersion.Major -eq 5) { + $originalProtocol = [Net.ServicePointManager]::SecurityProtocol + [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 + } + $client = [Net.Http.HttpClient]::new($handler) + $client.Timeout = [TimeSpan]::FromSeconds(120) + $cancellation = [Threading.CancellationTokenSource]::new() + $cancellation.CancelAfter(120000) + try { + $uri = [Uri]($script:ProoflineOrigin + $RelativePath) + for ($redirect = 0; $redirect -le 3; $redirect++) { + $response = $client.GetAsync($uri, [Net.Http.HttpCompletionOption]::ResponseHeadersRead, $cancellation.Token).GetAwaiter().GetResult() + try { + $status = [int]$response.StatusCode + if ($status -in @(301, 302, 303, 307, 308)) { + if ($redirect -eq 3 -or $null -eq $response.Headers.Location) { + throw 'Too many redirects or a redirect without a Location header.' + } + $nextUri = [Uri]::new($uri, $response.Headers.Location) + if ($nextUri.Scheme -cne 'https' -or $nextUri.Host -cne 'proofline.sh' -or + -not $nextUri.IsDefaultPort -or $nextUri.UserInfo -ne '' -or + $nextUri.AbsolutePath -cne $uri.AbsolutePath -or $nextUri.Query -ne '') { + throw "The release endpoint redirected outside its approved HTTPS path: $nextUri" + } + $uri = $nextUri + continue + } + if ($status -ne 200) { throw "Official release download failed (HTTP $status): $uri" } + if ($response.Content.Headers.ContentLength -gt $MaximumLength) { + throw 'Release download exceeds the permitted size.' + } + $inputStream = $response.Content.ReadAsStreamAsync().GetAwaiter().GetResult() + $outputStream = [IO.MemoryStream]::new() + try { + $buffer = [byte[]]::new(65536) + while ($true) { + $count = $inputStream.ReadAsync($buffer, 0, $buffer.Length, $cancellation.Token).GetAwaiter().GetResult() + if ($count -eq 0) { break } + if ($outputStream.Length + $count -gt $MaximumLength) { + throw 'Release download exceeds the permitted size.' + } + $outputStream.Write($buffer, 0, $count) + } + return ,($outputStream.ToArray()) + } + finally { + $inputStream.Dispose() + $outputStream.Dispose() + } + } + finally { $response.Dispose() } + } + throw 'Release download exhausted the redirect limit.' + } + finally { + $cancellation.Dispose() + $client.Dispose() + $handler.Dispose() + if ($null -ne $originalProtocol) { + [Net.ServicePointManager]::SecurityProtocol = $originalProtocol + } + } +} + +function Get-ProoflineLatestVersion { + $bytes = Get-ProoflineOfficialBytes '/cli/latest' 128 + $value = ([Text.UTF8Encoding]::new($false, $true)).GetString($bytes) + if ($value -notmatch '\A([0-9]+\.[0-9]+\.[0-9]+)\r?\n?\z') { + throw 'The official latest-version pointer is malformed.' + } + return (Assert-ProoflineVersion $Matches[1]) +} + +function Assert-ProoflineChecksum([byte[]]$ArchiveBytes, [byte[]]$ManifestBytes) { + if ($ArchiveBytes.Length -eq 0 -or $ArchiveBytes.Length -gt $script:MaxArchiveBytes) { + throw 'Release archive is empty or too large.' + } + if ($ManifestBytes.Length -eq 0 -or $ManifestBytes.Length -gt 8192) { + throw 'Release checksum manifest is empty or too large.' + } + $manifest = ([Text.UTF8Encoding]::new($false, $true)).GetString($ManifestBytes) + $expected = $null + $seen = @{} + foreach ($line in ($manifest -split "`n")) { + $line = $line.TrimEnd("`r") + if ($line.Length -eq 0) { continue } + if ($line -cnotmatch '\A([0-9a-fA-F]{64}) [ *](proofline-[a-zA-Z0-9_.-]+\.tar\.gz)\z') { + throw 'The checksum manifest contains a malformed line.' + } + $digest = $Matches[1] + $name = $Matches[2] + if ($seen.ContainsKey($name)) { throw "Duplicate checksum entry: $name" } + $seen[$name] = $true + if ($name -ceq $script:ProoflineArchiveName) { $expected = $digest } + } + if ($null -eq $expected) { throw "SHA256SUMS does not list $script:ProoflineArchiveName" } + $hash = [Security.Cryptography.SHA256]::Create() + try { $actual = [BitConverter]::ToString($hash.ComputeHash($ArchiveBytes)).Replace('-', '') } + finally { $hash.Dispose() } + if ($actual -cne $expected.ToUpperInvariant()) { + throw 'Release checksum mismatch; no executable has been installed.' + } +} + +function Get-ProoflineTarOctal([byte[]]$Bytes, [int]$Offset, [int]$Width) { + $field = ([Text.Encoding]::ASCII).GetString($Bytes, $Offset, $Width) + if ($field -cnotmatch '\A[ \x00]*([0-7]+)[ \x00]*\z') { + throw 'Invalid tar numeric field.' + } + return [Convert]::ToInt64($Matches[1], 8) +} + +function Get-ProoflineTarName([byte[]]$Bytes, [int]$Offset, [int]$Width) { + $stop = $Offset + while ($stop -lt ($Offset + $Width) -and $Bytes[$stop] -ne 0) { + if ($Bytes[$stop] -lt 32 -or $Bytes[$stop] -gt 126) { + throw 'Tar path contains non-printable or non-ASCII bytes.' + } + $stop++ + } + for ($i = $stop; $i -lt ($Offset + $Width); $i++) { + if ($Bytes[$i] -ne 0) { throw 'Tar string field has data after its terminator.' } + } + return [Text.Encoding]::ASCII.GetString($Bytes, $Offset, $stop - $Offset) +} + +function Get-ProoflineTarExecutable([byte[]]$ArchiveBytes) { + # Decode into bounded memory, then independently parse a minimal, strict + # one-member ustar archive; never ask tar.exe to unpack arbitrary paths. + $source = [IO.MemoryStream]::new($ArchiveBytes, $false) + $gzip = [IO.Compression.GZipStream]::new($source, [IO.Compression.CompressionMode]::Decompress) + $output = [IO.MemoryStream]::new() + try { + $buffer = [byte[]]::new(65536) + $limit = $script:MaxExecutableBytes + 10240 + while (($count = $gzip.Read($buffer, 0, $buffer.Length)) -gt 0) { + if ($output.Length + $count -gt $limit) { throw 'Decompressed archive exceeds the permitted size.' } + $output.Write($buffer, 0, $count) + } + $tar = $output.ToArray() + } + finally { + $gzip.Dispose() + $source.Dispose() + $output.Dispose() + } + if ($tar.Length -lt 1536 -or $tar.Length % 512 -ne 0) { + throw 'Release tar archive has invalid alignment or is truncated.' + } + $sum = 0L + for ($i = 0; $i -lt 512; $i++) { + if ($i -ge 148 -and $i -lt 156) { $sum += 32 } + else { $sum += $tar[$i] } + } + if ((Get-ProoflineTarOctal $tar 148 8) -ne $sum) { throw 'Tar header checksum is invalid.' } + if ((Get-ProoflineTarName $tar 0 100) -cne 'proofline.exe' -or + (Get-ProoflineTarName $tar 345 155) -ne '' -or + (Get-ProoflineTarName $tar 157 100) -ne '' -or + $tar[156] -notin @(0, 48)) { + throw 'Release archive must contain exactly one regular proofline.exe.' + } + $size = Get-ProoflineTarOctal $tar 124 12 + if ($size -lt 2 -or $size -gt $script:MaxExecutableBytes) { + throw 'Release executable is empty or too large.' + } + $afterFile = [long]512 + $size + $afterPadding = [long]([Math]::Ceiling($afterFile / 512.0) * 512) + if ($afterPadding + 1024 -gt $tar.Length) { throw 'Release archive is truncated.' } + for ($i = $afterFile; $i -lt $tar.Length; $i++) { + if ($tar[$i] -ne 0) { throw 'Release archive has nonzero padding or an unexpected extra member.' } + } + $binary = [byte[]]::new([int]$size) + [Array]::Copy($tar, 512, $binary, 0, [int]$size) + if ($binary.Length -lt 256 -or $binary[0] -ne 77 -or $binary[1] -ne 90) { + throw 'Release executable has no valid MZ header.' + } + $peOffset = [BitConverter]::ToInt32($binary, 0x3c) + if ($peOffset -lt 64 -or $peOffset -gt ($binary.Length - 4) -or + $binary[$peOffset] -ne 80 -or $binary[$peOffset + 1] -ne 69 -or + $binary[$peOffset + 2] -ne 0 -or $binary[$peOffset + 3] -ne 0) { + throw 'Release executable has no valid PE signature.' + } + return ,$binary +} + +function Resolve-ProoflineInstallDir([string]$Requested) { + if ([string]::IsNullOrWhiteSpace($Requested)) { + if ([string]::IsNullOrWhiteSpace($env:LOCALAPPDATA)) { throw 'LOCALAPPDATA is missing.' } + $Requested = [IO.Path]::Combine($env:LOCALAPPDATA, 'Programs', 'Proofline', 'bin') + } + # Reject UNC/device paths and relative paths. An explicit path must be an + # ordinary absolute drive path with no PATH delimiter. + if ($Requested -notmatch '^[A-Za-z]:[\\/]' -or $Requested.Contains(';')) { + throw 'InstallDir must be a local absolute drive path without semicolons.' + } + return [IO.Path]::GetFullPath($Requested) +} + +function Assert-ProoflineNoReparse([string]$Path) { + if ([IO.File]::Exists($Path) -or [IO.Directory]::Exists($Path)) { + if (([IO.File]::GetAttributes($Path) -band [IO.FileAttributes]::ReparsePoint) -ne 0) { + throw "Refusing an install path that is a symbolic link or reparse point: $Path" + } + } +} + +function Get-ProoflineUpdatedUserPath([string]$Current, [string]$Directory) { + if ($null -eq $Current) { $Current = '' } + $normalized = $Directory.TrimEnd([char[]]@('\', '/')) + foreach ($entry in ($Current -split ';')) { + $expanded = [Environment]::ExpandEnvironmentVariables($entry.Trim()) + if ($expanded.TrimEnd([char[]]@('\', '/')) -ieq $normalized) { + return $null # already present; no registry write needed + } + } + $result = if ($Current.TrimEnd(';') -eq '') { $Directory } else { $Current.TrimEnd(';') + ';' + $Directory } + if ($result.Length -gt 30000) { throw 'User PATH is too long; add the directory manually.' } + return $result +} + +function Add-ProoflineUserPath([string]$Directory) { + $current = [Environment]::GetEnvironmentVariable('Path', 'User') + $result = Get-ProoflineUpdatedUserPath $current $Directory + if ($null -eq $result) { + Write-Host 'User PATH already contains the Proofline directory.' + return + } + [Environment]::SetEnvironmentVariable('Path', $result, 'User') + Write-Host 'Added Proofline to your user PATH. Open a new terminal to use it.' +} + + +function Assert-ProoflinePathTree([string]$Directory) { + # A pre-existing reparse-point ancestor can redirect writes outside the + # requested directory. Check all existing ancestors and refuse such paths. + $cursor = [IO.DirectoryInfo]::new($Directory) + while ($null -ne $cursor) { + if ($cursor.Exists -and + ($cursor.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { + throw "Refusing a directory that contains a reparse point: $($cursor.FullName)" + } + $cursor = $cursor.Parent + } +} + +function Get-ProoflineSha256([string]$Path) { + return (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash +} + +function Assert-ProoflineExeVersion([string]$Path, [string]$Version) { + # Run only a checksum-verified release, never a raw unverified download. + # Process isolation and timeout avoid hanging this installer indefinitely. + $startInfo = [Diagnostics.ProcessStartInfo]::new() + $startInfo.FileName = $Path + $startInfo.Arguments = '--version' + $startInfo.UseShellExecute = $false + $startInfo.CreateNoWindow = $true + $startInfo.RedirectStandardOutput = $true + $startInfo.RedirectStandardError = $true + $process = [Diagnostics.Process]::new() + $process.StartInfo = $startInfo + try { + if (-not $process.Start()) { throw 'Candidate executable did not start.' } + if (-not $process.WaitForExit(15000)) { + try { $process.Kill() } catch { } + throw 'Candidate executable did not exit within 15 seconds.' + } + $actual = $process.StandardOutput.ReadToEnd().Trim() + $stderr = $process.StandardError.ReadToEnd().Trim() + if ($process.ExitCode -ne 0 -or $actual -cne "proofline $Version" -or $stderr -ne '') { + throw "Executable version check failed (expected 'proofline $Version', exit $($process.ExitCode), got '$actual' '$stderr')." + } + } + finally { $process.Dispose() } +} + +function Write-ProoflineAtomicRecord([string]$Path, [string]$Content) { + # Only used for first install. Do not overwrite existing transaction files. + $temporary = $Path + '.' + [guid]::NewGuid().ToString('N') + '.tmp' + $file = [IO.File]::Open($temporary, [IO.FileMode]::CreateNew, + [IO.FileAccess]::Write, [IO.FileShare]::None) + try { + $bytes = [Text.Encoding]::UTF8.GetBytes($Content) + $file.Write($bytes, 0, $bytes.Length) + $file.Flush($true) + } + finally { $file.Dispose() } + try { [IO.File]::Move($temporary, $Path) } + finally { + if ([IO.File]::Exists($temporary)) { [IO.File]::Delete($temporary) } + } +} + +function Assert-ProoflineRecord([string]$Path, [string]$ExpectedVersion, [string]$ExpectedHash) { + $record = Read-ProoflineReceipt $Path + if ($record.version -cne $ExpectedVersion -or $record.sha256 -cne $ExpectedHash) { + throw "An existing Proofline installation record does not match this release: $Path" + } +} + +function Read-ProoflineReceipt([string]$Path) { + if (-not [IO.File]::Exists($Path)) { throw 'No installer-managed receipt exists.' } + if (([IO.FileInfo]$Path).Length -gt 4096) { throw 'Installation receipt is too large.' } + $record = ConvertFrom-Json -InputObject ([IO.File]::ReadAllText($Path)) + if ($null -eq $record -or $record.schema -ne 1 -or + $record.sha256 -cnotmatch '\A[A-F0-9]{64}\z') { + throw 'Installation receipt is invalid; refusing to modify existing executable.' + } + [void](Assert-ProoflineVersion $record.version) + return $record +} + +function Write-ProoflineReceipt([string]$Path, [string]$Version, [string]$Hash) { + $record = ConvertTo-Json -Compress -InputObject ([ordered]@{ + schema = 1 + version = $Version + sha256 = $Hash + }) + if (-not [IO.File]::Exists($Path)) { + Write-ProoflineAtomicRecord $Path $record + } + else { + $temp = $Path + '.' + [guid]::NewGuid().ToString('N') + '.tmp' + $stream = [IO.File]::Open($temp, [IO.FileMode]::CreateNew, + [IO.FileAccess]::Write, [IO.FileShare]::None) + try { + $bytes = [Text.Encoding]::UTF8.GetBytes($record) + $stream.Write($bytes, 0, $bytes.Length) + $stream.Flush($true) + } + finally { $stream.Dispose() } + # PowerShell 5.1/.NET Framework rejected a null backup path on + # receipt replacement. Give File.Replace a real, unique same-volume + # backup path. Preserve that backup if replacement/validation fails. + $backup = $Path + '.' + [guid]::NewGuid().ToString('N') + '.bak' + $verified = $false + try { + [IO.File]::Replace($temp, $Path, $backup) + Assert-ProoflineRecord $Path $Version $Hash + $verified = $true + } + finally { + if ([IO.File]::Exists($temp)) { + try { [IO.File]::Delete($temp) } + catch { Write-Warning "Receipt staging file remains at $temp" } + } + # Journaled installer recovery handles errors before this point. + # Never discard a previous receipt until the new one is verified. + if ($verified -and [IO.File]::Exists($backup)) { + try { [IO.File]::Delete($backup) } + catch { Write-Warning "Previous receipt backup remains at $backup" } + } + } + } + Assert-ProoflineRecord $Path $Version $Hash +} + +function Read-ProoflinePending([string]$Path) { + if (-not [IO.File]::Exists($Path)) { return $null } + if (([IO.FileInfo]$Path).Length -gt 4096) { throw 'Pending transaction is too large.' } + $record = ConvertFrom-Json -InputObject ([IO.File]::ReadAllText($Path)) + if ($null -eq $record) { throw 'Pending transaction is empty.' } + if ($record.schema -in @(1, 3)) { + if ($record.sha256 -cnotmatch '\A[A-F0-9]{64}\z') { + throw 'Pending first-install digest is invalid.' + } + [void](Assert-ProoflineVersion $record.version) + if ($record.schema -eq 3 -and $record.id -cnotmatch '\A[0-9a-f]{32}\z') { + throw 'Pending first-install stage ID is invalid.' + } + return $record + } + if ($record.schema -ne 2 -or + $record.id -cnotmatch '\A[0-9a-f]{32}\z' -or + $record.oldSha256 -cnotmatch '\A[A-F0-9]{64}\z' -or + $record.newSha256 -cnotmatch '\A[A-F0-9]{64}\z') { + throw 'Pending upgrade record is invalid.' + } + [void](Assert-ProoflineVersion $record.oldVersion) + [void](Assert-ProoflineVersion $record.newVersion) + if ($record.oldSha256 -ceq $record.newSha256) { + throw 'Pending upgrade has identical old and new digests.' + } + return $record +} + +function Get-ProoflineTransactionPaths([string]$Directory, [string]$Id) { + # NEVER use a path supplied directly by transaction JSON. + if ($Id -cnotmatch '\A[0-9a-f]{32}\z') { throw 'Invalid transaction ID.' } + return @{ + old = [IO.Path]::Combine($Directory, ".proofline-recovery-$Id.exe") + api = [IO.Path]::Combine($Directory, ".proofline-api-backup-$Id.exe") + damaged = [IO.Path]::Combine($Directory, ".proofline-damaged-$Id.exe") + stage = [IO.Path]::Combine($Directory, ".proofline-staged-$Id.exe") + } +} + +function Clear-ProoflineUpgradeFiles([hashtable]$Paths, [string]$Pending, [string]$NewHash) { + # Deleting every matching ".proofline-staged-*.exe" would remove files + # belonging to unrelated attempts. A schema-2 journal's validated ID + # identifies precisely one stage belonging to this transaction. + foreach ($key in @('old', 'api', 'stage')) { + Assert-ProoflineNoReparse $Paths[$key] + } + if ([IO.File]::Exists($Paths.stage) -and + (Get-ProoflineSha256 $Paths.stage) -cne $NewHash) { + throw 'Pending upgrade stage has unexpected contents; preserving transaction evidence.' + } + foreach ($key in @('old', 'api', 'stage')) { + if ([IO.File]::Exists($Paths[$key])) { [IO.File]::Delete($Paths[$key]) } + } + [IO.File]::Delete($Pending) # delete journal LAST +} + +function Recover-ProoflinePending([string]$Directory) { + # Caller MUST hold the stable installer lock during this operation. + $destination = [IO.Path]::Combine($Directory, 'proofline.exe') + $receipt = [IO.Path]::Combine($Directory, '.proofline-install.receipt.json') + $pending = [IO.Path]::Combine($Directory, '.proofline-install.pending.json') + $record = Read-ProoflinePending $pending + if ($null -eq $record) { return } + foreach ($path in @($destination, $receipt, $pending)) { + Assert-ProoflineNoReparse $path + } + + if ($record.schema -in @(1, 3)) { + # Schema 3 records the exact stage ID BEFORE any staged file is + # created. This makes a killed first install recoverable even when + # termination occurs before the executable move. Legacy schema 1 + # journal recovery remains supported without guessing stage paths. + $stage = $null + if ($record.schema -eq 3) { + $stage = [IO.Path]::Combine($Directory, ('.proofline-staged-' + $record.id + '.exe')) + Assert-ProoflineNoReparse $stage + if ([IO.File]::Exists($stage) -and + (Get-ProoflineSha256 $stage) -cne $record.sha256) { + throw 'Interrupted first-install stage differs from verified release; preserving journal.' + } + } + if (-not [IO.File]::Exists($destination)) { + if ([IO.File]::Exists($receipt)) { + throw 'Interrupted first installation has a receipt but no executable.' + } + if ($null -ne $stage -and [IO.File]::Exists($stage)) { + [IO.File]::Delete($stage) + } + [IO.File]::Delete($pending) + return + } + if ((Get-ProoflineSha256 $destination) -cne $record.sha256) { + throw 'Interrupted first install has an unrecognized executable; preserving journal.' + } + Assert-ProoflineExeVersion $destination $record.version + if ([IO.File]::Exists($receipt)) { + Assert-ProoflineRecord $receipt $record.version $record.sha256 + } + else { Write-ProoflineReceipt $receipt $record.version $record.sha256 } + if ($null -ne $stage -and [IO.File]::Exists($stage)) { + [IO.File]::Delete($stage) + } + [IO.File]::Delete($pending) + Write-Host 'Recovered interrupted first installation.' + return + } + + $paths = Get-ProoflineTransactionPaths $Directory $record.id + foreach ($path in $paths.Values) { Assert-ProoflineNoReparse $path } + $activeHash = $null + if ([IO.File]::Exists($destination)) { $activeHash = Get-ProoflineSha256 $destination } + + if ($activeHash -ceq $record.newSha256) { + try { + Assert-ProoflineExeVersion $destination $record.newVersion + Write-ProoflineReceipt $receipt $record.newVersion $record.newSha256 + Clear-ProoflineUpgradeFiles $paths $pending $record.newSha256 + Write-Host "Finalized interrupted Proofline $($record.newVersion) upgrade." + return + } catch { + Write-Warning "New executable is present but cannot be finalized: $($_.Exception.Message)" + # Try verified old copy below rather than claiming the upgrade worked. + } + } + + if ($activeHash -ceq $record.oldSha256) { + Assert-ProoflineExeVersion $destination $record.oldVersion + Write-ProoflineReceipt $receipt $record.oldVersion $record.oldSha256 + Clear-ProoflineUpgradeFiles $paths $pending $record.newSha256 + Write-Host "Previous Proofline $($record.oldVersion) installation remains usable." + return + } + + $source = $null + foreach ($candidate in @($paths.old, $paths.api)) { + if ([IO.File]::Exists($candidate) -and + (Get-ProoflineSha256 $candidate) -ceq $record.oldSha256) { + $source = $candidate + break + } + } + if ($null -eq $source) { + throw 'Neither executable is verified and no valid previous-version copy remains. Files and recovery journal preserved.' + } + + $restore = [IO.Path]::Combine($Directory, ('.proofline-restore-' + [guid]::NewGuid().ToString('N') + '.exe')) + [IO.File]::Copy($source, $restore, $false) + try { + if ((Get-ProoflineSha256 $restore) -cne $record.oldSha256) { + throw 'Verified recovery copy changed while preparing rollback.' + } + if ([IO.File]::Exists($destination)) { + if ([IO.File]::Exists($paths.damaged)) { + throw 'Damaged-file evidence path already exists; manual recovery required.' + } + [IO.File]::Replace($restore, $destination, $paths.damaged) + } else { + [IO.File]::Move($restore, $destination) + } + if ((Get-ProoflineSha256 $destination) -cne $record.oldSha256) { + throw 'Restored executable digest differs from previous release.' + } + Assert-ProoflineExeVersion $destination $record.oldVersion + Write-ProoflineReceipt $receipt $record.oldVersion $record.oldSha256 + Clear-ProoflineUpgradeFiles $paths $pending $record.newSha256 + Write-Host "Restored verified Proofline $($record.oldVersion) after interrupted upgrade." + } + finally { + if ([IO.File]::Exists($restore)) { + try { [IO.File]::Delete($restore) } + catch { Write-Warning "Recovery staging file remains: $restore" } + } + } +} + +function Invoke-ProoflinePendingRepair([string]$Directory) { + # Recover BEFORE network activity, so an outage cannot block local repair. + $directory = Resolve-ProoflineInstallDir $Directory + Assert-ProoflinePathTree $directory + if (-not [IO.Directory]::Exists($directory)) { return } + $pending = [IO.Path]::Combine($directory, '.proofline-install.pending.json') + if (-not [IO.File]::Exists($pending)) { return } + $lock = [IO.Path]::Combine($directory, '.proofline-install.lock') + Assert-ProoflineNoReparse $lock + $handle = [IO.File]::Open($lock, [IO.FileMode]::OpenOrCreate, + [IO.FileAccess]::ReadWrite, [IO.FileShare]::None) + try { Recover-ProoflinePending $directory } + finally { $handle.Dispose() } +} + +function Test-ProoflineTransientReplaceFailure([Exception]$Error) { + # Retry only Win32 sharing (32) and lock (33) violations, not + # arbitrary permission errors or partial filesystem failures. + $current = $Error + while ($null -ne $current) { + if ($current -is [IO.IOException] -and + $current.HResult -in @(-2147024864, -2147024863)) { + return $true + } + $current = $current.InnerException + } + return $false +} + +function Invoke-ProoflineReplaceWithRetry( + [string]$Candidate, + [string]$Destination, + [string]$Backup, + [string]$NewHash, + [string]$OldHash +) { + # A recently executed binary or filesystem scanner can hold a transient + # handle. Retry only after confirming BOTH files retain pre-switch bytes + # and backup path has NOT appeared. Never retry a partial replacement. + $delays = @(0, 150, 300, 600, 1200, 2400) + for ($index = 0; $index -lt $delays.Count; $index++) { + if ($index -gt 0) { + Start-Sleep -Milliseconds $delays[$index] + foreach ($path in @($Candidate, $Destination, $Backup)) { + Assert-ProoflineNoReparse $path + } + if (-not [IO.File]::Exists($Candidate) -or + -not [IO.File]::Exists($Destination) -or + [IO.File]::Exists($Backup) -or + (Get-ProoflineSha256 $Candidate) -cne $NewHash -or + (Get-ProoflineSha256 $Destination) -cne $OldHash) { + throw 'Replacement files changed after sharing failure; unsafe to retry.' + } + } + try { + [IO.File]::Replace($Candidate, $Destination, $Backup) + return + } + catch { + if (-not (Test-ProoflineTransientReplaceFailure $_.Exception) -or + $index -eq ($delays.Count - 1)) { + throw + } + Write-Warning "Executable replacement is temporarily locked; retrying verified state ($($index + 1)/$($delays.Count))." + } + } +} + +function Install-ProoflineArchive( + [byte[]]$ArchiveBytes, + [byte[]]$ChecksumBytes, + [string]$ReleaseVersion, + [string]$Directory +) { + $ReleaseVersion = Assert-ProoflineVersion $ReleaseVersion + Assert-ProoflineChecksum $ArchiveBytes $ChecksumBytes + $binary = Get-ProoflineTarExecutable $ArchiveBytes + $digest = [Security.Cryptography.SHA256]::Create() + try { $hash = [BitConverter]::ToString($digest.ComputeHash($binary)).Replace('-', '') } + finally { $digest.Dispose() } + + $directory = Resolve-ProoflineInstallDir $Directory + Assert-ProoflinePathTree $directory + [IO.Directory]::CreateDirectory($directory) | Out-Null + $destination = [IO.Path]::Combine($directory, 'proofline.exe') + $receipt = [IO.Path]::Combine($directory, '.proofline-install.receipt.json') + $pending = [IO.Path]::Combine($directory, '.proofline-install.pending.json') + $lock = [IO.Path]::Combine($directory, '.proofline-install.lock') + foreach ($path in @($destination, $receipt, $pending, $lock)) { + Assert-ProoflineNoReparse $path + } + try { + $lockHandle = [IO.File]::Open($lock, [IO.FileMode]::OpenOrCreate, + [IO.FileAccess]::ReadWrite, [IO.FileShare]::None) + } + catch { throw "Another installer may be running, or the lock file is unavailable: $($_.Exception.Message)" } + try { + # Handle a concurrent previous installer that stopped during download. + if ([IO.File]::Exists($pending)) { + Recover-ProoflinePending $directory + } + $hasDestination = [IO.File]::Exists($destination) + $hasReceipt = [IO.File]::Exists($receipt) + if ($hasDestination -ne $hasReceipt) { + throw 'Incomplete or unmanaged existing installation; refusing to overwrite it.' + } + $oldReceipt = $null + if ($hasDestination) { + $oldReceipt = Read-ProoflineReceipt $receipt + if ((Get-ProoflineSha256 $destination) -cne $oldReceipt.sha256) { + throw 'Existing Proofline executable does not match its installer-managed receipt.' + } + Assert-ProoflineExeVersion $destination $oldReceipt.version + if ($oldReceipt.version -ceq $ReleaseVersion -and + $oldReceipt.sha256 -ceq $hash) { + Write-Host "Proofline $ReleaseVersion is already installed; nothing was changed." + return $destination + } + } + # Tie the stage path to the same validated transaction ID that the + # pending journal records. Recovery can now clean ONLY its own stage. + $id = [guid]::NewGuid().ToString('N') + $stage = [IO.Path]::Combine($directory, ('.proofline-staged-' + $id + '.exe')) + Assert-ProoflineNoReparse $stage + if ($null -eq $oldReceipt) { + # Write the schema-3 journal BEFORE creating the stage. If killed + # during a write, recovery retains incomplete bytes as evidence; + # it only deletes a stage whose digest matches the verified one. + $record = ConvertTo-Json -Compress -InputObject ([ordered]@{ + schema = 3 + id = $id + version = $ReleaseVersion + sha256 = $hash + }) + Write-ProoflineAtomicRecord $pending $record + } + try { + $stream = [IO.File]::Open($stage, [IO.FileMode]::CreateNew, + [IO.FileAccess]::Write, [IO.FileShare]::None) + try { + $stream.Write($binary, 0, $binary.Length) + $stream.Flush($true) + } + finally { $stream.Dispose() } + Assert-ProoflineExeVersion $stage $ReleaseVersion + + if ($null -eq $oldReceipt) { + [IO.File]::Move($stage, $destination) + if ((Get-ProoflineSha256 $destination) -cne $hash) { + throw 'Installed executable digest differs after relocation.' + } + Assert-ProoflineExeVersion $destination $ReleaseVersion + Write-ProoflineReceipt $receipt $ReleaseVersion $hash + [IO.File]::Delete($pending) + return $destination + } + + # Upgrade: independently preserve the previous verified executable. + $paths = Get-ProoflineTransactionPaths $directory $id + foreach ($path in $paths.Values) { Assert-ProoflineNoReparse $path } + [IO.File]::Copy($destination, $paths.old, $false) + if ((Get-ProoflineSha256 $paths.old) -cne $oldReceipt.sha256) { + throw 'Could not preserve a verified previous executable; upgrade aborted.' + } + $record = ConvertTo-Json -Compress -InputObject ([ordered]@{ + schema = 2 + id = $id + oldVersion = $oldReceipt.version + oldSha256 = $oldReceipt.sha256 + newVersion = $ReleaseVersion + newSha256 = $hash + }) + Write-ProoflineAtomicRecord $pending $record + try { + Invoke-ProoflineReplaceWithRetry $stage $destination $paths.api $hash $oldReceipt.sha256 + if ((Get-ProoflineSha256 $destination) -cne $hash) { + throw 'Upgraded executable digest differs from verified candidate.' + } + Assert-ProoflineExeVersion $destination $ReleaseVersion + Write-ProoflineReceipt $receipt $ReleaseVersion $hash + Clear-ProoflineUpgradeFiles $paths $pending $hash + Write-Host "Upgraded Proofline $($oldReceipt.version) to $ReleaseVersion." + return $destination + } + catch { + $originalError = $_.Exception.Message + try { Recover-ProoflinePending $directory } + catch { + throw "Upgrade failed ($originalError). Automatic recovery also failed: $($_.Exception.Message). Transaction evidence was preserved." + } + throw "Upgrade encountered an error ($originalError); recovery was attempted. Verify the reported installed version." + } + } + finally { + if ([IO.File]::Exists($stage)) { + try { [IO.File]::Delete($stage) } + catch { Write-Warning "Staged file remains at $stage" } + } + } + } + finally { $lockHandle.Dispose() } +} + +function Invoke-ProoflineInstaller([string]$RequestedVersion, [string]$RequestedDirectory, [bool]$ModifyPath) { + Assert-ProoflinePlatform + Invoke-ProoflinePendingRepair $RequestedDirectory + $release = if ([string]::IsNullOrWhiteSpace($RequestedVersion)) { + Get-ProoflineLatestVersion + } else { Assert-ProoflineVersion $RequestedVersion } + $prefix = "/cli/download/$release" + Write-Host "Downloading Proofline $release for Windows x64..." + $archive = Get-ProoflineOfficialBytes "$prefix/$script:ProoflineArchiveName" $script:MaxArchiveBytes + $sums = Get-ProoflineOfficialBytes "$prefix/SHA256SUMS" 8192 + $installed = Install-ProoflineArchive $archive $sums $release $RequestedDirectory + Write-Host "Verified proofline $release at $installed" + if ($ModifyPath) { + try { Add-ProoflineUserPath ([IO.Path]::GetDirectoryName($installed)) } + catch { Write-Warning "Proofline installed, but PATH update failed: $($_.Exception.Message)" } + } + else { Write-Host 'PATH unchanged (-NoModifyPath was selected).' } + Write-Host 'Next: open a new terminal and run proofline login.' +} + +# Dot-sourcing allows the non-mutating validator functions to be unit tested. +if ($MyInvocation.InvocationName -ne '.') { + try { Invoke-ProoflineInstaller $Version $InstallDir (-not [bool]$NoModifyPath) } + catch { + [Console]::Error.WriteLine("proofline install: $($_.Exception.Message)") + exit 1 + } +} From aa12ba4275ae04eb5ccd3bf3181e51bffc33bd38 Mon Sep 17 00:00:00 2001 From: Ayan Khan Date: Mon, 23 Nov 2026 08:57:11 +0530 Subject: [PATCH 02/21] test(windows): cover archive validation and offline recovery --- .../generate_windows_installer_fixtures.py | 92 +++++++ scripts/test_install_upgrade_windows.ps1 | 257 ++++++++++++++++++ scripts/test_install_windows.ps1 | 88 ++++++ 3 files changed, 437 insertions(+) create mode 100644 scripts/generate_windows_installer_fixtures.py create mode 100644 scripts/test_install_upgrade_windows.ps1 create mode 100644 scripts/test_install_windows.ps1 diff --git a/scripts/generate_windows_installer_fixtures.py b/scripts/generate_windows_installer_fixtures.py new file mode 100644 index 0000000..e9b2305 --- /dev/null +++ b/scripts/generate_windows_installer_fixtures.py @@ -0,0 +1,92 @@ +"""Generate offline release fixtures for PowerShell validator tests. + +Fixtures intentionally contain a fake PE header and MUST NOT be executed. +""" + +import gzip +import hashlib +import io +from pathlib import Path +import sys +import tarfile + + +def pack(*members: tuple[str, bytes, bytes]) -> bytes: + output = io.BytesIO() + with gzip.GzipFile(fileobj=output, mode="wb", mtime=0) as gz: + with tarfile.open(fileobj=gz, mode="w", format=tarfile.USTAR_FORMAT) as tar: + for name, data, kind in members: + header = tarfile.TarInfo(name) + header.type = kind + header.size = len(data) if kind == tarfile.REGTYPE else 0 + header.mtime = 0 + tar.addfile(header, io.BytesIO(data)) + return output.getvalue() + + +def pe_fixture() -> bytes: + image = bytearray(1024) + image[:2] = b"MZ" + image[0x3C:0x40] = (0x80).to_bytes(4, "little") + image[0x80:0x84] = b"PE\0\0" + return bytes(image) + + +def main(destination: Path) -> None: + destination.mkdir(parents=True, exist_ok=True) + binary = pe_fixture() + base = pack(("proofline.exe", binary, tarfile.REGTYPE)) + (destination / "valid.tar.gz").write_bytes(base) + upgraded_binary = bytearray(binary) + upgraded_binary[512] = 0x42 # different digest, same fake PE header + upgraded = pack(("proofline.exe", bytes(upgraded_binary), tarfile.REGTYPE)) + (destination / "upgrade.tar.gz").write_bytes(upgraded) + (destination / "SHA256SUMS-upgrade").write_text( + f"{hashlib.sha256(upgraded).hexdigest()} proofline-x86_64-pc-windows-msvc.tar.gz\n", + encoding="ascii", + ) + (destination / "bad-digest.tar.gz").write_bytes(base + b"tampered") + (destination / "traversal.tar.gz").write_bytes( + pack(("../proofline.exe", binary, tarfile.REGTYPE)) + ) + (destination / "unexpected-member.tar.gz").write_bytes( + pack(("proofline.exe", binary, tarfile.REGTYPE), ("extra.txt", b"evil", tarfile.REGTYPE)) + ) + (destination / "symlink.tar.gz").write_bytes( + pack(("proofline.exe", b"", tarfile.SYMTYPE)) + ) + (destination / "not-pe.tar.gz").write_bytes( + pack(("proofline.exe", b"not a PE" * 128, tarfile.REGTYPE)) + ) + name = "proofline-x86_64-pc-windows-msvc.tar.gz" + sha = hashlib.sha256(base).hexdigest() + other = hashlib.sha256(b"other archive bytes").hexdigest() + (destination / "SHA256SUMS").write_text( + f"{sha} {name}\n{other} proofline-x86_64-unknown-linux-musl.tar.gz\n", + encoding="ascii", + ) + (destination / "SHA256SUMS-mismatch").write_text( + f"{'0'*64} {name}\n", encoding="ascii" + ) + (destination / "SHA256SUMS-duplicate").write_text( + f"{sha} {name}\n{sha} {name}\n", encoding="ascii" + ) + (destination / "SHA256SUMS-missing").write_text( + f"{other} proofline-x86_64-unknown-linux-musl.tar.gz\n", encoding="ascii" + ) + (destination / "SHA256SUMS-malformed").write_text( + f"not-a-hash {name}\n", encoding="ascii" + ) + # The release's archive format is deterministic; assert our fixture name, + # tar type and content are correct before it reaches PowerShell tests. + with tarfile.open(fileobj=io.BytesIO(base), mode="r:gz") as tar: + names = tar.getnames() + assert names == ["proofline.exe"], names + assert tar.extractfile(tar.getmembers()[0]).read() == binary + print(f"Created offline fixture files in {destination}") + + +if __name__ == "__main__": + if len(sys.argv) != 2: + raise SystemExit("usage: generate_windows_installer_fixtures.py DIRECTORY") + main(Path(sys.argv[1])) diff --git a/scripts/test_install_upgrade_windows.ps1 b/scripts/test_install_upgrade_windows.ps1 new file mode 100644 index 0000000..ecbf2c9 --- /dev/null +++ b/scripts/test_install_upgrade_windows.ps1 @@ -0,0 +1,257 @@ +#requires -Version 5.1 +<# +.SYNOPSIS + Offline installer-managed Windows upgrade/recovery tests. +.DESCRIPTION + Uses fake PE fixtures that are NEVER executed. Replaces executable version + smoke-check function with a strict digest assertion inside this test scope. + No download, user PATH modification, or real Proofline installation. +#> +[CmdletBinding()] +param([string]$Python = 'python') +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' +if ([Environment]::OSVersion.Platform -ne [PlatformID]::Win32NT) { + throw 'Run these tests on Windows.' +} + +$root = Join-Path ([IO.Path]::GetTempPath()) ('proofline-upgrade-tests-' + [guid]::NewGuid().ToString('N')) +[IO.Directory]::CreateDirectory($root) | Out-Null +$passed = 0 +$failed = 0 + +function Check([string]$Name, [scriptblock]$Case) { + try { + & $Case + $script:passed++ + Write-Host "PASS $Name" + } + catch { + $script:failed++ + Write-Warning "FAIL $Name : $($_.Exception.ToString())" + } +} +function Require([bool]$Condition, [string]$Explanation) { + if (-not $Condition) { throw $Explanation } +} +function Must-Throw([scriptblock]$Case) { + $didThrow = $false + try { & $Case | Out-Null } catch { $didThrow = $true } + if (-not $didThrow) { throw 'Expected an error, but operation succeeded.' } +} +function Fixture([string]$Name) { + return ,([IO.File]::ReadAllBytes((Join-Path $root $Name))) +} +function Active([string]$Name) { + return (Join-Path (Join-Path $root $Name) 'proofline.exe') +} +function Receipt([string]$Name) { + return (Join-Path (Join-Path $root $Name) '.proofline-install.receipt.json') +} +function Pending([string]$Name) { + return (Join-Path (Join-Path $root $Name) '.proofline-install.pending.json') +} +function Get-ProoflineSha256FileBytes([byte[]]$Value) { + $hash = [Security.Cryptography.SHA256]::Create() + try { return [BitConverter]::ToString($hash.ComputeHash($Value)).Replace('-', '') } + finally { $hash.Dispose() } +} +function PrepareOld([string]$Name) { + $directory = Join-Path $root $Name + $installed = Install-ProoflineArchive $script:oldArchive $script:oldSums '0.5.1' $directory + Require ((Get-ProoflineSha256 $installed) -ceq $script:oldHash) 'Old fixture did not install.' + return $directory +} +function MakePending([string]$Directory) { + $id = [guid]::NewGuid().ToString('N') + $paths = Get-ProoflineTransactionPaths $Directory $id + $active = Join-Path $Directory 'proofline.exe' + [IO.File]::Copy($active, $paths.old, $false) + $pendingPath = Join-Path $Directory '.proofline-install.pending.json' + $json = ConvertTo-Json -Compress -InputObject ([ordered]@{ + schema = 2 + id = $id + oldVersion = '0.5.1' + oldSha256 = $script:oldHash + newVersion = '0.5.2' + newSha256 = $script:newHash + }) + Write-ProoflineAtomicRecord $pendingPath $json + return $paths +} + +try { + $scriptDir = $PSScriptRoot + & $Python (Join-Path $scriptDir 'generate_windows_installer_fixtures.py') $root | Out-Host + if ($LASTEXITCODE -ne 0) { throw 'Fixture generation failed.' } + . (Join-Path (Split-Path -Parent $scriptDir) 'install.ps1') + $script:oldArchive = Fixture 'valid.tar.gz' + $script:oldSums = Fixture 'SHA256SUMS' + $script:newArchive = Fixture 'upgrade.tar.gz' + $script:newSums = Fixture 'SHA256SUMS-upgrade' + $script:oldHash = Get-ProoflineSha256FileBytes (Get-ProoflineTarExecutable $script:oldArchive) + $script:newHash = Get-ProoflineSha256FileBytes (Get-ProoflineTarExecutable $script:newArchive) + + # Test-only shadow function: fake PE fixtures are not runnable and must + # NEVER be started. Production installer calls the original version checker. + function Assert-ProoflineExeVersion([string]$Path, [string]$Version) { + $digest = Get-ProoflineSha256 $Path + $expected = switch ($Version) { + '0.5.1' { $script:oldHash; break } + '0.5.2' { $script:newHash; break } + default { throw "Unexpected test-only version $Version" } + } + if ($digest -cne $expected) { + throw "Test fixture for $Version has unexpected digest." + } + } + + Check 'interrupted fresh install cleans only verified matching stage' { + $dir = Join-Path $root 'fresh-stage' + [IO.Directory]::CreateDirectory($dir) | Out-Null + $id = [guid]::NewGuid().ToString('N') + $stage = Join-Path $dir ('.proofline-staged-' + $id + '.exe') + $other = Join-Path $dir ('.proofline-staged-' + [guid]::NewGuid().ToString('N') + '.exe') + [IO.File]::WriteAllBytes($stage, (Get-ProoflineTarExecutable $script:oldArchive)) + [IO.File]::WriteAllText($other, 'UNRELATED_STAGING_EVIDENCE') + Write-ProoflineAtomicRecord (Join-Path $dir '.proofline-install.pending.json') (ConvertTo-Json -Compress -InputObject ([ordered]@{ + schema = 3; id = $id; version = '0.5.1'; sha256 = $script:oldHash + })) + Invoke-ProoflinePendingRepair $dir + Require (-not [IO.File]::Exists($stage)) 'Transaction-owned verified stage survived cleanup.' + Require ([IO.File]::Exists($other)) 'Unrelated staged file was removed.' + Require (-not [IO.File]::Exists((Join-Path $dir '.proofline-install.pending.json'))) 'Fresh pending record remains.' + Require (-not [IO.File]::Exists((Join-Path $dir 'proofline.exe'))) 'Interrupted install unexpectedly published an executable.' + } + Check 'interrupted fresh install refuses an unverified stage' { + $dir = Join-Path $root 'fresh-tampered' + [IO.Directory]::CreateDirectory($dir) | Out-Null + $id = [guid]::NewGuid().ToString('N') + $stage = Join-Path $dir ('.proofline-staged-' + $id + '.exe') + [IO.File]::WriteAllText($stage, 'INCOMPLETE_DOWNLOAD') + $journal = Join-Path $dir '.proofline-install.pending.json' + Write-ProoflineAtomicRecord $journal (ConvertTo-Json -Compress -InputObject ([ordered]@{ + schema = 3; id = $id; version = '0.5.1'; sha256 = $script:oldHash + })) + Must-Throw { Invoke-ProoflinePendingRepair $dir } + Require ([IO.File]::Exists($journal)) 'Journal vanished despite unrecognized stage.' + Require ([IO.File]::Exists($stage)) 'Unverified stage was silently discarded.' + } + Check 'interrupted fresh install finalizes verified published executable' { + $dir = Join-Path $root 'fresh-published' + [IO.Directory]::CreateDirectory($dir) | Out-Null + $id = [guid]::NewGuid().ToString('N') + [IO.File]::WriteAllBytes((Join-Path $dir 'proofline.exe'), (Get-ProoflineTarExecutable $script:oldArchive)) + $journal = Join-Path $dir '.proofline-install.pending.json' + Write-ProoflineAtomicRecord $journal (ConvertTo-Json -Compress -InputObject ([ordered]@{ + schema = 3; id = $id; version = '0.5.1'; sha256 = $script:oldHash + })) + Invoke-ProoflinePendingRepair $dir + Require (-not [IO.File]::Exists($journal)) 'Journal not cleared after successful receipt recovery.' + Assert-ProoflineRecord (Join-Path $dir '.proofline-install.receipt.json') '0.5.1' $script:oldHash + Require ((Get-ProoflineSha256 (Join-Path $dir 'proofline.exe')) -ceq $script:oldHash) 'First-install recovery modified verified bytes.' + } + Check 'clean upgrade from previous verified install' { + $dir = PrepareOld 'normal' + $destination = Install-ProoflineArchive $script:newArchive $script:newSums '0.5.2' $dir + Require ((Get-ProoflineSha256 $destination) -ceq $script:newHash) 'New executable digest incorrect.' + Assert-ProoflineRecord (Receipt 'normal') '0.5.2' $script:newHash + Require (-not [IO.File]::Exists((Pending 'normal'))) 'Upgrade journal remains after success.' + Require (@(Get-ChildItem -LiteralPath $dir -Force -Filter '.proofline-recovery*').Count -eq 0) 'Old backup not cleaned.' + } + Check 'receipt replacement preserves and cleans up its backup' { + $dir = PrepareOld 'receipt-backup' + $receiptPath = Receipt 'receipt-backup' + Write-ProoflineReceipt $receiptPath '0.5.2' $script:newHash + Assert-ProoflineRecord $receiptPath '0.5.2' $script:newHash + $leftovers = @(Get-ChildItem -LiteralPath $dir -Force | + Where-Object { $_.Name -like '.proofline-install.receipt.json.*' }) + Require ($leftovers.Count -eq 0) 'Receipt replacement left temporary or backup files.' + } + Check 'only sharing/lock HRESULTs are retryable' { + $sharing = [IO.IOException]::new('temporarily held', -2147024864) + $lock = [IO.IOException]::new('range locked', -2147024863) + $denied = [UnauthorizedAccessException]::new('denied') + $other = [IO.IOException]::new('not a sharing violation') + Require (Test-ProoflineTransientReplaceFailure $sharing) 'Sharing violation not recognized.' + Require (Test-ProoflineTransientReplaceFailure $lock) 'Lock violation not recognized.' + Require (-not (Test-ProoflineTransientReplaceFailure $denied)) 'Access denial must not be retried.' + Require (-not (Test-ProoflineTransientReplaceFailure $other)) 'Unrelated IO failure must not be retried.' + } + Check 'repeat upgrade is idempotent' { + $dir = PrepareOld 'repeat' + [void](Install-ProoflineArchive $script:newArchive $script:newSums '0.5.2' $dir) + [void](Install-ProoflineArchive $script:newArchive $script:newSums '0.5.2' $dir) + Require ((Get-ProoflineSha256 (Active 'repeat')) -ceq $script:newHash) 'Repeat changed active bytes.' + Assert-ProoflineRecord (Receipt 'repeat') '0.5.2' $script:newHash + } + Check 'interrupted pre-switch stage cleaned by matching transaction ID' { + $dir = PrepareOld 'pre-switch-stage' + $paths = MakePending $dir + [IO.File]::WriteAllBytes($paths.stage, (Get-ProoflineTarExecutable $script:newArchive)) + Invoke-ProoflinePendingRepair $dir + Require (-not [IO.File]::Exists($paths.stage)) 'Verified staged executable survived completed recovery.' + Require (-not [IO.File]::Exists((Pending 'pre-switch-stage'))) 'Recovered transaction journal remains.' + Require ((Get-ProoflineSha256 (Active 'pre-switch-stage')) -ceq $script:oldHash) 'Old executable changed.' + Assert-ProoflineRecord (Receipt 'pre-switch-stage') '0.5.1' $script:oldHash + } + Check 'untrusted pre-switch stage is preserved with the journal' { + $dir = PrepareOld 'tampered-stage' + $paths = MakePending $dir + [IO.File]::WriteAllText($paths.stage, 'NOT_THE_VERIFIED_CANDIDATE', [Text.Encoding]::ASCII) + Must-Throw { Invoke-ProoflinePendingRepair $dir } + Require ([IO.File]::Exists((Pending 'tampered-stage'))) 'Unknown staged data lost its pending record.' + Require ([IO.File]::Exists($paths.stage)) 'Unknown staged data was deleted.' + Require ((Get-ProoflineSha256 (Active 'tampered-stage')) -ceq $script:oldHash) 'Old executable was changed.' + } + Check 'new active detected and finalized after restart' { + $dir = PrepareOld 'finalize' + $paths = MakePending $dir + [IO.File]::WriteAllBytes((Active 'finalize'), (Get-ProoflineTarExecutable $script:newArchive)) + Invoke-ProoflinePendingRepair $dir + Require ((Get-ProoflineSha256 (Active 'finalize')) -ceq $script:newHash) 'New active hash was lost.' + Assert-ProoflineRecord (Receipt 'finalize') '0.5.2' $script:newHash + Require (-not [IO.File]::Exists((Pending 'finalize'))) 'Pending journal not cleared.' + } + Check 'corrupt active restored from verified previous copy' { + $dir = PrepareOld 'rollback' + $paths = MakePending $dir + [IO.File]::WriteAllText((Active 'rollback'), 'BROKEN', [Text.Encoding]::ASCII) + Invoke-ProoflinePendingRepair $dir + Require ((Get-ProoflineSha256 (Active 'rollback')) -ceq $script:oldHash) 'Old binary not restored.' + Assert-ProoflineRecord (Receipt 'rollback') '0.5.1' $script:oldHash + Require (-not [IO.File]::Exists((Pending 'rollback'))) 'Pending record remains after successful recovery.' + } + Check 'ambiguous state refuses and preserves evidence' { + $dir = PrepareOld 'ambiguous' + $paths = MakePending $dir + [IO.File]::WriteAllText((Active 'ambiguous'), 'BROKEN', [Text.Encoding]::ASCII) + [IO.File]::WriteAllText($paths.old, 'BAD', [Text.Encoding]::ASCII) + Must-Throw { Invoke-ProoflinePendingRepair $dir } + Require ([IO.File]::Exists((Pending 'ambiguous'))) 'Pending journal was removed in ambiguous state.' + Require ((Get-ProoflineSha256 (Active 'ambiguous')) -cne $script:oldHash) 'Unverified bytes overwritten.' + } + Check 'exclusive lock refuses second installer without mutation' { + $dir = PrepareOld 'locked' + $lock = Join-Path $dir '.proofline-install.lock' + $stream = [IO.File]::Open($lock, [IO.FileMode]::OpenOrCreate, + [IO.FileAccess]::ReadWrite, [IO.FileShare]::None) + try { + Must-Throw { + [void](Install-ProoflineArchive $script:newArchive $script:newSums '0.5.2' $dir) + } + } + finally { $stream.Dispose() } + Require ((Get-ProoflineSha256 (Active 'locked')) -ceq $script:oldHash) 'Locked installer changed active executable.' + } +} +finally { + if ($failed -eq 0) { + Remove-Item -LiteralPath $root -Recurse -Force -ErrorAction SilentlyContinue + } +} +Write-Host "Offline Windows upgrade tests: $passed passed, $failed failed." +if ($failed -ne 0) { + Write-Warning "Failed fixtures retained at $root" + exit 1 +} diff --git a/scripts/test_install_windows.ps1 b/scripts/test_install_windows.ps1 new file mode 100644 index 0000000..5cc59fe --- /dev/null +++ b/scripts/test_install_windows.ps1 @@ -0,0 +1,88 @@ +#requires -Version 5.1 +# Offline validator tests: no network, PATH changes, installation or execution. +[CmdletBinding()] +param([string]$Python = 'python') +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' +if ([Environment]::OSVersion.Platform -ne [PlatformID]::Win32NT) { + throw 'Run these PowerShell tests on Windows.' +} + +$root = Join-Path ([IO.Path]::GetTempPath()) ('proofline-validation-tests-' + [guid]::NewGuid().ToString('N')) +[IO.Directory]::CreateDirectory($root) | Out-Null +$installer = Join-Path (Split-Path -Parent $PSScriptRoot) 'install.ps1' +$generator = Join-Path $PSScriptRoot 'generate_windows_installer_fixtures.py' +$passed = 0 +$failed = 0 + +function Test-Case([string]$Name, [scriptblock]$Check) { + try { + & $Check + $script:passed++ + Write-Host "PASS $Name" + } + catch { + $script:failed++ + Write-Warning "FAIL $Name : $($_.Exception.Message)" + } +} +function Must-Throw([scriptblock]$Action) { + $didThrow = $false + try { & $Action | Out-Null } catch { $didThrow = $true } + if (-not $didThrow) { throw 'Expected rejection, but operation succeeded.' } +} +function Bytes([string]$Filename) { + return ,([IO.File]::ReadAllBytes((Join-Path $root $Filename))) +} + +try { + & $Python $generator $root | Out-Host + if ($LASTEXITCODE -ne 0) { throw 'Python fixture generation failed.' } + . $installer + $valid = Bytes 'valid.tar.gz' + $sums = Bytes 'SHA256SUMS' + + Test-Case 'valid official-style tar and multi-target digest manifest' { + Assert-ProoflineChecksum $valid $sums + $exe = Get-ProoflineTarExecutable $valid + if ($exe.Length -ne 1024) { throw 'Unexpected fixture executable length.' } + } + foreach ($name in @('SHA256SUMS-mismatch', 'SHA256SUMS-duplicate', + 'SHA256SUMS-missing', 'SHA256SUMS-malformed')) { + $manifest = Bytes $name + Test-Case "manifest rejects $name" { + Must-Throw { Assert-ProoflineChecksum $valid $manifest } + } + } + foreach ($name in @('traversal.tar.gz', 'unexpected-member.tar.gz', + 'symlink.tar.gz', 'not-pe.tar.gz')) { + $archive = Bytes $name + Test-Case "archive rejects $name" { + Must-Throw { Get-ProoflineTarExecutable $archive } + } + } + Test-Case 'checksum rejects modified archive bytes' { + $modified = Bytes 'bad-digest.tar.gz' + Must-Throw { Assert-ProoflineChecksum $modified $sums } + } + Test-Case 'strict semantic versions' { + if ((Assert-ProoflineVersion '1.2.3') -cne '1.2.3') { throw 'Valid version rejected.' } + Must-Throw { Assert-ProoflineVersion '../1.2.3' } + Must-Throw { Assert-ProoflineVersion '01.2.3' } + Must-Throw { Assert-ProoflineVersion '1.2.3-rc1' } + } + Test-Case 'PATH change is idempotent' { + $directory = 'C:\Users\tester\AppData\Local\Programs\Proofline\bin' + if ($null -ne (Get-ProoflineUpdatedUserPath $directory $directory)) { + throw 'Duplicate PATH entry would be appended.' + } + if ((Get-ProoflineUpdatedUserPath 'C:\Other' $directory) -cne ('C:\Other;' + $directory)) { + throw 'Expected PATH entry missing.' + } + } +} +finally { + Remove-Item -LiteralPath $root -Recurse -Force -ErrorAction SilentlyContinue +} +Write-Host "Offline PowerShell validator tests: $passed passed, $failed failed." +if ($failed -ne 0) { exit 1 } From 2ab421884d35a78295c51c110c34842ec5a0b4d0 Mon Sep 17 00:00:00 2001 From: Ayan Khan Date: Mon, 23 Nov 2026 10:26:59 +0530 Subject: [PATCH 03/21] test(windows): exercise real upgrades, locking, and interruption recovery --- scripts/test_install_concurrency_windows.ps1 | 179 +++++++++ ...test_install_interruption_real_windows.ps1 | 363 ++++++++++++++++++ scripts/test_install_upgrade_real_windows.ps1 | 118 ++++++ 3 files changed, 660 insertions(+) create mode 100644 scripts/test_install_concurrency_windows.ps1 create mode 100644 scripts/test_install_interruption_real_windows.ps1 create mode 100644 scripts/test_install_upgrade_real_windows.ps1 diff --git a/scripts/test_install_concurrency_windows.ps1 b/scripts/test_install_concurrency_windows.ps1 new file mode 100644 index 0000000..98b788d --- /dev/null +++ b/scripts/test_install_concurrency_windows.ps1 @@ -0,0 +1,179 @@ +#requires -Version 5.1 +<# +.SYNOPSIS + Tests cross-process Windows installer locking with disposable local fixtures. +.DESCRIPTION + No network, admin rights, PATH changes, or real executable execution. + The main test invokes a separate PowerShell holder process, then checks that + a competing upgrade refuses to modify its verified previous installation. + The holder mode is internal to this test and requires a fresh test marker. +#> +[CmdletBinding()] +param( + [ValidateSet('Test', 'Hold')][string]$Mode = 'Test', + [string]$CaseDir, + [string]$Python = 'python' +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' +if ([Environment]::OSVersion.Platform -ne [PlatformID]::Win32NT) { + throw 'Run this test on Windows.' +} + +if ($Mode -eq 'Hold') { + if ([string]::IsNullOrWhiteSpace($CaseDir)) { throw 'Holder needs CaseDir.' } + $folder = [IO.Path]::GetFullPath($CaseDir) + $marker = Join-Path $folder '.proofline-test-only' + if (-not [IO.File]::Exists($marker) -or + [IO.File]::ReadAllText($marker) -cne 'DISPOSABLE_LOCK_TEST') { + throw 'Refusing to hold lock without disposable test marker.' + } + $lock = Join-Path $folder '.proofline-install.lock' + $ready = Join-Path $folder '.holder-ready' + $release = Join-Path $folder '.holder-release' + $stream = [IO.File]::Open($lock, [IO.FileMode]::OpenOrCreate, + [IO.FileAccess]::ReadWrite, [IO.FileShare]::None) + try { + [IO.File]::WriteAllText($ready, 'LOCK_HELD') + $expires = [DateTime]::UtcNow.AddSeconds(25) + while ([DateTime]::UtcNow -lt $expires -and -not [IO.File]::Exists($release)) { + Start-Sleep -Milliseconds 100 + } + if (-not [IO.File]::Exists($release)) { + throw 'Holder timed out waiting for parent release signal.' + } + } + finally { $stream.Dispose() } + exit 0 +} + +$root = Join-Path ([IO.Path]::GetTempPath()) ('proofline-concurrent-' + [guid]::NewGuid().ToString('N')) +[IO.Directory]::CreateDirectory($root) | Out-Null +$bin = Join-Path $root 'bin' +[IO.Directory]::CreateDirectory($bin) | Out-Null +[IO.File]::WriteAllText((Join-Path $bin '.proofline-test-only'), 'DISPOSABLE_LOCK_TEST') +$holder = $null +$passed = $false +$holderReady = Join-Path $bin '.holder-ready' +$holderRelease = Join-Path $bin '.holder-release' + +function Assert-Condition([bool]$Value, [string]$Message) { + if (-not $Value) { throw $Message } +} +function Digest-Bytes([byte[]]$Data) { + $sha = [Security.Cryptography.SHA256]::Create() + try { return [BitConverter]::ToString($sha.ComputeHash($Data)).Replace('-', '') } + finally { $sha.Dispose() } +} + +try { + & $Python (Join-Path $PSScriptRoot 'generate_windows_installer_fixtures.py') $root | Out-Host + if ($LASTEXITCODE -ne 0) { throw 'Offline fixture generator failed.' } + . (Join-Path (Split-Path -Parent $PSScriptRoot) 'install.ps1') + $oldArchive = [IO.File]::ReadAllBytes((Join-Path $root 'valid.tar.gz')) + $oldManifest = [IO.File]::ReadAllBytes((Join-Path $root 'SHA256SUMS')) + $newArchive = [IO.File]::ReadAllBytes((Join-Path $root 'upgrade.tar.gz')) + $newManifest = [IO.File]::ReadAllBytes((Join-Path $root 'SHA256SUMS-upgrade')) + $script:oldHash = Digest-Bytes (Get-ProoflineTarExecutable $oldArchive) + $script:newHash = Digest-Bytes (Get-ProoflineTarExecutable $newArchive) + + # This is test-only: artificial PE fixtures must never be executed. + function Assert-ProoflineExeVersion([string]$Path, [string]$Version) { + $expected = switch ($Version) { + '0.5.1' { $script:oldHash; break } + '0.5.2' { $script:newHash; break } + default { throw "Unexpected fixture version $Version" } + } + if ((Get-ProoflineSha256 $Path) -cne $expected) { + throw "Invalid fixture contents for $Version" + } + } + + $active = Install-ProoflineArchive $oldArchive $oldManifest '0.5.1' $bin + Assert-Condition ((Get-ProoflineSha256 $active) -ceq $script:oldHash) 'Old fixture did not install.' + $receipt = Join-Path $bin '.proofline-install.receipt.json' + Assert-ProoflineRecord $receipt '0.5.1' $script:oldHash + + $powershell = (Get-Process -Id $PID).Path + $args = '-NoProfile -NonInteractive -File "' + $PSCommandPath + + '" -Mode Hold -CaseDir "' + $bin + '"' + $start = [Diagnostics.ProcessStartInfo]::new() + $start.FileName = $powershell + $start.Arguments = $args + $start.UseShellExecute = $false + $start.CreateNoWindow = $true + $start.WindowStyle = [Diagnostics.ProcessWindowStyle]::Hidden + $holder = [Diagnostics.Process]::Start($start) + if ($null -eq $holder) { throw 'Could not start lock holder process.' } + + $deadline = [DateTime]::UtcNow.AddSeconds(12) + while (-not [IO.File]::Exists($holderReady) -and [DateTime]::UtcNow -lt $deadline) { + if ($holder.HasExited) { throw 'Lock holder exited before readiness.' } + Start-Sleep -Milliseconds 100 + } + Assert-Condition ([IO.File]::Exists($holderReady)) 'Lock holder did not signal readiness.' + Assert-Condition (-not $holder.HasExited) 'Lock holder exited before contested upgrade.' + Write-Host 'Separate PowerShell process holds installer lock.' + + $refused = $false + try { + [void](Install-ProoflineArchive $newArchive $newManifest '0.5.2' $bin) + } + catch { + if ($_.Exception.Message -match 'Another installer may be running|lock file is unavailable') { + $refused = $true + } + else { throw } + } + Assert-Condition $refused 'Competing installer was not rejected due to exclusive lock.' + Assert-Condition ((Get-ProoflineSha256 $active) -ceq $script:oldHash) 'Concurrent attempt changed active executable.' + Assert-ProoflineRecord $receipt '0.5.1' $script:oldHash + Assert-Condition (-not [IO.File]::Exists((Join-Path $bin '.proofline-install.pending.json'))) 'Concurrent attempt left a journal.' + Write-Host 'PASS competing installer refused; old executable, receipt and journal unchanged.' + + [IO.File]::WriteAllText($holderRelease, 'RELEASE') + if (-not $holder.WaitForExit(10000)) { throw 'Holder did not exit after release.' } + Assert-Condition ($holder.ExitCode -eq 0) "Lock holder exited $($holder.ExitCode)." + Write-Host 'PASS second process released lock cleanly.' + + $upgraded = Install-ProoflineArchive $newArchive $newManifest '0.5.2' $bin + Assert-Condition ((Get-ProoflineSha256 $upgraded) -ceq $script:newHash) 'Upgrade after lock release failed.' + Assert-ProoflineRecord $receipt '0.5.2' $script:newHash + Assert-Condition (-not [IO.File]::Exists((Join-Path $bin '.proofline-install.pending.json'))) 'Upgrade left a journal.' + Write-Host 'PASS upgrade succeeds after competing process releases lock.' + $passed = $true +} +catch { + Write-Warning "FAIL cross-process lock test: $($_.Exception.ToString())" +} +finally { + if ($null -ne $holder) { + try { + if (-not $holder.HasExited) { + # This child was created solely for the disposable test. + $holder.Kill() + $holder.WaitForExit(5000) | Out-Null + } + } + catch { + Write-Warning "Could not stop test lock holder process: $($_.Exception.Message)" + $passed = $false + } + $holder.Dispose() + } + if ($passed) { + try { Remove-Item -LiteralPath $root -Recurse -Force -ErrorAction Stop } + catch { + $passed = $false + Write-Warning "Could not clean test sandbox: $($_.Exception.Message)" + } + } +} +if ($passed) { + Write-Host 'Cross-process Windows lock integration: PASS; temporary files cleaned.' +} +else { + Write-Warning "Failure evidence retained at: $root" + exit 1 +} diff --git a/scripts/test_install_interruption_real_windows.ps1 b/scripts/test_install_interruption_real_windows.ps1 new file mode 100644 index 0000000..392b057 --- /dev/null +++ b/scripts/test_install_interruption_real_windows.ps1 @@ -0,0 +1,363 @@ +#requires -Version 5.1 +<# +.SYNOPSIS + End-to-end tests for forcibly interrupted Windows executable installs and upgrades. +.DESCRIPTION + Downloads two pinned official Proofline releases once, installs into + disposable GUID-named TEMP directories, and generates INSTRUMENTED COPIES + of install.ps1 in the test sandbox. A child PowerShell process runs actual + Install-ProoflineArchive and terminates itself at a chosen checkpoint. + Another fresh process calls the unmodified installer's recovery function. + NEVER changes PATH or an existing Proofline installation. + Does not simulate an OS crash, disk loss, or power failure. +#> +[CmdletBinding()] +param( + [ValidateSet('Driver', 'Worker', 'Recover')] + [string]$Mode = 'Driver', + [string]$CaseDir, + [string]$InstallerCopy, + [string]$FixtureDir, + [switch]$KeepFiles +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' +if ([Environment]::OSVersion.Platform -ne [PlatformID]::Win32NT) { + throw 'Windows is required for the interruption integration test.' +} +$originalInstaller = Join-Path (Split-Path -Parent $PSScriptRoot) 'install.ps1' + +function Require([bool]$Ok, [string]$Message) { + if (-not $Ok) { throw $Message } +} +function Get-TestBytes([string]$Directory, [string]$Name) { + return ,([IO.File]::ReadAllBytes((Join-Path $Directory $Name))) +} +function Assert-Sandbox([string]$Directory) { + if ([string]::IsNullOrWhiteSpace($Directory)) { throw 'Missing test directory.' } + $marker = Join-Path ([IO.Path]::GetFullPath($Directory)) '.proofline-test-only' + if (-not [IO.File]::Exists($marker) -or + [IO.File]::ReadAllText($marker) -cne 'DISPOSABLE_REAL_UPGRADE_TEST') { + throw 'Missing disposable test marker; refusing to touch a real installation.' + } +} +function Assert-Installed([string]$Directory, [string]$Version, [bool]$ExpectDamagedEvidence = $false) { + $exe = Join-Path $Directory 'proofline.exe' + $receipt = Join-Path $Directory '.proofline-install.receipt.json' + $pending = Join-Path $Directory '.proofline-install.pending.json' + Require ([IO.File]::Exists($exe)) 'Active executable missing.' + Require ([IO.File]::Exists($receipt)) 'Installer receipt missing.' + Require (-not [IO.File]::Exists($pending)) 'A recovery journal remains after recovery.' + $data = ConvertFrom-Json -InputObject ([IO.File]::ReadAllText($receipt)) + $hash = (Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash + Require ($data.schema -eq 1 -and $data.version -ceq $Version -and + $data.sha256 -ceq $hash) 'Receipt does not match installed executable.' + $output = @(& $exe --version) + $exitCode = $LASTEXITCODE + Require ($exitCode -eq 0 -and ($output -join '').Trim() -ceq "proofline $Version") "Executable version check failed for $Version." + $debris = @(Get-ChildItem -LiteralPath $Directory -Force | + Where-Object { $_.Name -match '\A\.proofline-(recovery|api-backup|staged|restore)-' }) + Require ($debris.Count -eq 0) 'A recovery or staging executable remains after successful repair.' + # A corrupted active executable is intentionally kept in a quarantine + # path following successful rollback. Don't conceal that evidence merely + # to make this test green; verify exactly what was preserved. + $damaged = @(Get-ChildItem -LiteralPath $Directory -Force | + Where-Object { $_.Name -match '\A\.proofline-damaged-[0-9a-f]{32}\.exe\z' }) + if ($ExpectDamagedEvidence) { + Require ($damaged.Count -eq 1) 'Expected one quarantined corrupted executable.' + Require ([IO.File]::ReadAllText($damaged[0].FullName) -ceq 'INTENTIONALLY_CORRUPTED') 'Quarantined contents differ from injected corruption.' + } + else { + Require ($damaged.Count -eq 0) 'Unexpected damaged executable remains.' + } + return $hash +} + +if ($Mode -eq 'Worker' -or $Mode -eq 'Recover') { + Assert-Sandbox $CaseDir + if ([string]::IsNullOrWhiteSpace($InstallerCopy) -or + -not [IO.File]::Exists($InstallerCopy)) { + throw 'Child requires its installer file.' + } + . $InstallerCopy + if ($Mode -eq 'Recover') { + Invoke-ProoflinePendingRepair $CaseDir + Write-Output 'RECOVERY_COMPLETED' + exit 0 + } + if ([string]::IsNullOrWhiteSpace($FixtureDir)) { throw 'Missing fixture directory.' } + $fresh = [IO.File]::Exists((Join-Path $CaseDir '.first-install-case')) + $name = if ($fresh) { 'old' } else { 'new' } + $version = if ($fresh) { '0.5.1' } else { '0.5.2' } + $archive = Get-TestBytes $FixtureDir "$name.tar.gz" + $manifest = Get-TestBytes $FixtureDir "$name-SHA256SUMS" + # An instrumented installer will kill ONLY THIS worker at the checkpoint. + [void](Install-ProoflineArchive $archive $manifest $version $CaseDir) + throw 'Worker unexpectedly returned: checkpoint injection did not terminate it.' +} + +function Invoke-HiddenPowerShell([string]$Arguments, [string]$Purpose) { + # A fresh console-subsystem powershell.exe normally opens another console + # when launched with Start-Process. Suppress its window while preserving + # stdout, stderr, exit status, and a finite timeout for diagnosis. + $start = [Diagnostics.ProcessStartInfo]::new() + $start.FileName = $engine + $start.Arguments = $Arguments + $start.UseShellExecute = $false + $start.CreateNoWindow = $true + $start.WindowStyle = [Diagnostics.ProcessWindowStyle]::Hidden + $start.RedirectStandardOutput = $true + $start.RedirectStandardError = $true + $child = [Diagnostics.Process]::new() + $child.StartInfo = $start + try { + if (-not $child.Start()) { throw "Could not start $Purpose." } + # Drain both pipes concurrently; waiting before reading may deadlock + # when a child writes enough data to fill a redirected pipe. + $outTask = $child.StandardOutput.ReadToEndAsync() + $errTask = $child.StandardError.ReadToEndAsync() + if (-not $child.WaitForExit(90000)) { + try { $child.Kill() } catch { } + [void]$child.WaitForExit(5000) + throw "$Purpose did not exit within 90 seconds." + } + $child.WaitForExit() + return [pscustomobject]@{ + ExitCode = $child.ExitCode + Output = $outTask.GetAwaiter().GetResult() + ErrorOutput = $errTask.GetAwaiter().GetResult() + } + } + finally { $child.Dispose() } +} + +function Make-InstrumentedInstaller([string]$Source, [string]$Destination, [string]$Checkpoint) { + # Normalize line endings, then require the exact current production + # statements. A changed installer should fail this test's setup rather + # than silently disable fault injection. + $text = [IO.File]::ReadAllText($Source).Replace("`r`n", "`n") + # The marker proves this child reached the intentional termination point. + $mark = '[IO.File]::WriteAllText(([IO.Path]::Combine($directory, ''.injected-stop'')), ''' + + $Checkpoint + ''', [Text.Encoding]::ASCII)' + $abort = $mark + "`n" + ' Stop-Process -Id $PID -Force -ErrorAction Stop' + if ($Checkpoint -eq 'after-journal') { + $target = ' Write-ProoflineAtomicRecord $pending $record' + + "`n" + ' try {' + $replacement = ' Write-ProoflineAtomicRecord $pending $record' + + "`n" + ' ' + $abort + "`n" + ' try {' + } + elseif ($Checkpoint -eq 'after-switch' -or $Checkpoint -eq 'corrupt-after-switch') { + $target = ' Invoke-ProoflineReplaceWithRetry $stage $destination $paths.api $hash $oldReceipt.sha256' + + "`n" + ' if (' + $damage = if ($Checkpoint -eq 'corrupt-after-switch') { + ' [IO.File]::WriteAllText($destination, "INTENTIONALLY_CORRUPTED", [Text.Encoding]::ASCII)' + "`n" + } + else { '' } + $replacement = ' Invoke-ProoflineReplaceWithRetry $stage $destination $paths.api $hash $oldReceipt.sha256' + + "`n" + $damage + ' ' + $abort + "`n" + ' if (' + } + elseif ($Checkpoint -eq 'after-receipt') { + $target = ' Write-ProoflineReceipt $receipt $ReleaseVersion $hash' + + "`n" + ' Clear-ProoflineUpgradeFiles $paths $pending $hash' + $replacement = ' Write-ProoflineReceipt $receipt $ReleaseVersion $hash' + + "`n" + ' ' + $abort + "`n" + ' Clear-ProoflineUpgradeFiles $paths $pending $hash' + } + elseif ($Checkpoint -eq 'fresh-after-journal') { + $target = ' Write-ProoflineAtomicRecord $pending $record' + + "`n" + ' }' + "`n" + ' try {' + $replacement = ' Write-ProoflineAtomicRecord $pending $record' + + "`n" + ' ' + $abort + "`n" + ' }' + "`n" + ' try {' + } + elseif ($Checkpoint -eq 'fresh-after-stage') { + $target = ' Assert-ProoflineExeVersion $stage $ReleaseVersion' + + "`n`n" + ' if ($null -eq $oldReceipt) {' + $replacement = ' Assert-ProoflineExeVersion $stage $ReleaseVersion' + + "`n" + ' ' + $abort + "`n`n" + ' if ($null -eq $oldReceipt) {' + } + elseif ($Checkpoint -eq 'fresh-after-move') { + $target = ' [IO.File]::Move($stage, $destination)' + + "`n" + ' if (' + $replacement = ' [IO.File]::Move($stage, $destination)' + + "`n" + ' ' + $abort + "`n" + ' if (' + } + elseif ($Checkpoint -eq 'fresh-after-receipt') { + $target = ' Write-ProoflineReceipt $receipt $ReleaseVersion $hash' + + "`n" + ' [IO.File]::Delete($pending)' + $replacement = ' Write-ProoflineReceipt $receipt $ReleaseVersion $hash' + + "`n" + ' ' + $abort + "`n" + ' [IO.File]::Delete($pending)' + } + else { throw "Unsupported injection checkpoint $Checkpoint." } + Require ($text.Contains($target)) "Production installer checkpoint '$Checkpoint' changed." + Require (($text.Split([string[]]@($target), [StringSplitOptions]::None).Count) -eq 2) "Checkpoint '$Checkpoint' is not unique." + $instrumented = $text.Replace($target, $replacement) + [IO.File]::WriteAllText($Destination, $instrumented, [Text.UTF8Encoding]::new($false)) +} + +$root = Join-Path ([IO.Path]::GetTempPath()) ('proofline-real-interruption-' + [guid]::NewGuid().ToString('N')) +[IO.Directory]::CreateDirectory($root) | Out-Null +$cache = Join-Path $root 'cache' +[IO.Directory]::CreateDirectory($cache) | Out-Null +$scenarios = @( + 'after-journal', 'after-switch', 'corrupt-after-switch', 'after-receipt', + 'fresh-after-journal', 'fresh-after-stage', 'fresh-after-move', 'fresh-after-receipt' +) +$expected = @{ + 'after-journal' = '0.5.1' + 'after-switch' = '0.5.2' + 'corrupt-after-switch' = '0.5.1' + 'after-receipt' = '0.5.2' + 'fresh-after-journal' = 'absent' + 'fresh-after-stage' = 'absent' + 'fresh-after-move' = '0.5.1' + 'fresh-after-receipt' = '0.5.1' +} +$engine = (Get-Process -Id $PID).Path +$pathBefore = [Environment]::GetEnvironmentVariable('Path', 'User') +$results = @() +$passed = $false +$cleanup = $false + +try { + . $originalInstaller + foreach ($pair in @(@('0.5.1', 'old'), @('0.5.2', 'new'))) { + $v = $pair[0] + $kind = $pair[1] + $prefix = "/cli/download/$v" + Write-Host "Downloading pinned official v$v fixture..." + $archive = Get-ProoflineOfficialBytes "$prefix/$script:ProoflineArchiveName" $script:MaxArchiveBytes + $manifest = Get-ProoflineOfficialBytes "$prefix/SHA256SUMS" 8192 + Assert-ProoflineChecksum $archive $manifest + [void](Get-ProoflineTarExecutable $archive) + [IO.File]::WriteAllBytes((Join-Path $cache "$kind.tar.gz"), $archive) + [IO.File]::WriteAllBytes((Join-Path $cache "$kind-SHA256SUMS"), $manifest) + } + $oldArchive = Get-TestBytes $cache 'old.tar.gz' + $oldManifest = Get-TestBytes $cache 'old-SHA256SUMS' + + foreach ($checkpoint in $scenarios) { + $directory = Join-Path $root $checkpoint + [IO.Directory]::CreateDirectory($directory) | Out-Null + [IO.File]::WriteAllText((Join-Path $directory '.proofline-test-only'), 'DISPOSABLE_REAL_UPGRADE_TEST') + $isFresh = $checkpoint -like 'fresh-*' + $oldDigest = $null + if ($isFresh) { + [IO.File]::WriteAllText((Join-Path $directory '.first-install-case'), 'DISPOSABLE') + Write-Host "Vacant first-install sandbox prepared for $checkpoint." + } + else { + [void](Install-ProoflineArchive $oldArchive $oldManifest '0.5.1' $directory) + $oldDigest = Assert-Installed $directory '0.5.1' + Write-Host "Initial v0.5.1 installation validated for $checkpoint." + } + + $copy = Join-Path $root ("instrumented-$checkpoint.ps1") + Make-InstrumentedInstaller $originalInstaller $copy $checkpoint + $stdout = Join-Path $root ("worker-$checkpoint.stdout.txt") + $stderr = Join-Path $root ("worker-$checkpoint.stderr.txt") + $arguments = '-NoProfile -NonInteractive -File "' + $PSCommandPath + + '" -Mode Worker -CaseDir "' + $directory + + '" -FixtureDir "' + $cache + '" -InstallerCopy "' + $copy + '"' + $worker = Invoke-HiddenPowerShell $arguments "upgrade worker ($checkpoint)" + $workerExit = $worker.ExitCode + [IO.File]::WriteAllText($stdout, $worker.Output) + [IO.File]::WriteAllText($stderr, $worker.ErrorOutput) + $workerOutput = $worker.Output + $worker.ErrorOutput + $marker = Join-Path $directory '.injected-stop' + Require ([IO.File]::Exists($marker)) "Worker failed before reaching $checkpoint; exit $workerExit; output: $workerOutput" + Require ([IO.File]::ReadAllText($marker) -ceq $checkpoint) "Wrong checkpoint marker for $checkpoint." + Require ($workerExit -eq -1) "Worker did not terminate as expected at $checkpoint; exit $workerExit; output: $workerOutput" + $journal = Join-Path $directory '.proofline-install.pending.json' + Require ([IO.File]::Exists($journal)) "No pending journal existed after forced termination at $checkpoint." + $activeFile = Join-Path $directory 'proofline.exe' + $activeDigest = $null + if ([IO.File]::Exists($activeFile)) { + $activeDigest = (Get-FileHash -LiteralPath $activeFile -Algorithm SHA256).Hash + } + if ($checkpoint -in @('fresh-after-journal', 'fresh-after-stage')) { + Require ($null -eq $activeDigest) 'Fresh install published executable before intended checkpoint.' + } + elseif ($checkpoint -in @('fresh-after-move', 'fresh-after-receipt')) { + Require ($null -ne $activeDigest) 'Fresh install did not publish executable before checkpoint.' + } + elseif ($checkpoint -eq 'after-journal') { + Require ($activeDigest -ceq $oldDigest) 'Journal checkpoint unexpectedly changed old executable.' + } + elseif ($checkpoint -eq 'corrupt-after-switch') { + Require ($activeDigest -cne $oldDigest) 'Corruption checkpoint did not change the active file.' + } + else { + Require ($activeDigest -cne $oldDigest) 'Replacement checkpoint did not change executable.' + } + + $recoverStdout = Join-Path $root ("recovery-$checkpoint.stdout.txt") + $recoverStderr = Join-Path $root ("recovery-$checkpoint.stderr.txt") + $recoverArgs = '-NoProfile -NonInteractive -File "' + $PSCommandPath + + '" -Mode Recover -CaseDir "' + $directory + + '" -InstallerCopy "' + $originalInstaller + '"' + $recovery = Invoke-HiddenPowerShell $recoverArgs "recovery worker ($checkpoint)" + $recoverExit = $recovery.ExitCode + [IO.File]::WriteAllText($recoverStdout, $recovery.Output) + [IO.File]::WriteAllText($recoverStderr, $recovery.ErrorOutput) + $recoverOutput = $recovery.Output + $recovery.ErrorOutput + Require ($recoverExit -eq 0) "Fresh recovery process failed for $checkpoint; output: $recoverOutput" + $digest = $null + if ($expected[$checkpoint] -eq 'absent') { + Require (-not [IO.File]::Exists($activeFile)) 'Interrupted fresh install unexpectedly published an executable.' + Require (-not [IO.File]::Exists((Join-Path $directory '.proofline-install.receipt.json'))) 'Interrupted fresh install incorrectly wrote a receipt.' + Require (-not [IO.File]::Exists($journal)) 'Interrupted fresh install left a pending journal.' + $unclaimed = @(Get-ChildItem -LiteralPath $directory -Force | + Where-Object { $_.Name -match '^\.proofline-staged-[a-f0-9]{32}\.exe$' }) + Require ($unclaimed.Count -eq 0) 'Fresh-install recovery left a staged executable.' + Write-Host "PASS $checkpoint; fresh process removed interrupted first-install files." + } + else { + $digest = Assert-Installed $directory $expected[$checkpoint] ($checkpoint -eq 'corrupt-after-switch') + if ($isFresh) { + Require ($null -ne $digest) 'First-install recovery failed to finalize new executable.' + } + elseif ($expected[$checkpoint] -eq '0.5.1') { + Require ($digest -ceq $oldDigest) 'Rollback did not preserve original executable bytes.' + } + else { + Require ($digest -cne $oldDigest) 'Recovery did not install the different new executable.' + } + Write-Host "PASS $checkpoint; fresh process recovered to v$($expected[$checkpoint])." + } + $results += [pscustomobject]@{ + checkpoint = $checkpoint + workerExitCode = $workerExit + recoveryExitCode = $recoverExit + recoveredVersion = $expected[$checkpoint] + recoveredSha256 = $digest + } + } + + Require ([Environment]::GetEnvironmentVariable('Path', 'User') -ceq $pathBefore) 'User PATH was modified.' + $passed = $true +} +catch { + Write-Warning "FAIL real installer interruption test: $($_.Exception.ToString())" +} +finally { + if ($passed -and -not $KeepFiles) { + try { + Remove-Item -LiteralPath $root -Recurse -Force -ErrorAction Stop + $cleanup = $true + } + catch { + Write-Warning "Could not delete disposable test directory: $($_.Exception.Message)" + $passed = $false + } + } +} +Write-Host "Completed $($results.Count) of $($scenarios.Count) interruption scenarios." +if ($passed) { + Write-Host 'Real Windows installer interruption integration: PASS' + if ($KeepFiles) { Write-Host "Retained test evidence at $root" } + else { Write-Host "Cleaned isolated test directory: $cleanup" } +} +else { + Write-Warning "Failure evidence preserved at: $root" + exit 1 +} diff --git a/scripts/test_install_upgrade_real_windows.ps1 b/scripts/test_install_upgrade_real_windows.ps1 new file mode 100644 index 0000000..d3c3430 --- /dev/null +++ b/scripts/test_install_upgrade_real_windows.ps1 @@ -0,0 +1,118 @@ +#requires -Version 5.1 +<# +.SYNOPSIS + Tests an actual Windows upgrade using two pinned official Proofline releases. +.DESCRIPTION + Uses a fresh GUID-named TEMP directory only. No user PATH modifications, + authentication, existing Proofline installation or admin access. + Executes install.ps1 under the same PowerShell edition that launched the + test. Deletes the test directory on success unless -KeepFiles is provided. + Preserves it on failure for debugging. Requires network access. +#> +[CmdletBinding()] +param([switch]$KeepFiles) + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' +if ([Environment]::OSVersion.Platform -ne [PlatformID]::Win32NT) { + throw 'Run this integration test on Windows.' +} + +$installer = Join-Path (Split-Path -Parent $PSScriptRoot) 'install.ps1' +if (-not [IO.File]::Exists($installer)) { throw 'Cannot find install.ps1.' } +$root = Join-Path ([IO.Path]::GetTempPath()) ('proofline-real-upgrade-' + [guid]::NewGuid().ToString('N')) +[IO.Directory]::CreateDirectory($root) | Out-Null +$bin = Join-Path $root 'bin' +$oldUserPath = [Environment]::GetEnvironmentVariable('Path', 'User') +$script:TestEngine = (Get-Process -Id $PID).Path # Test whichever PowerShell edition invoked this script. +$passed = $false + +function Install-Release([string]$Version) { + Write-Host "Installing official Proofline $Version..." + & $script:TestEngine -NoProfile -NonInteractive -File $installer -Version $Version -InstallDir $bin -NoModifyPath + if ($LASTEXITCODE -ne 0) { + throw "Installer $Version exited with code $LASTEXITCODE." + } +} +function Check-Release([string]$Version) { + $exe = Join-Path $bin 'proofline.exe' + $receipt = Join-Path $bin '.proofline-install.receipt.json' + $pending = Join-Path $bin '.proofline-install.pending.json' + if (-not [IO.File]::Exists($exe) -or -not [IO.File]::Exists($receipt)) { + throw "Managed installation missing executable or receipt for $Version." + } + $hash = (Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash + $receiptHash = (Get-FileHash -LiteralPath $receipt -Algorithm SHA256).Hash + $record = ConvertFrom-Json -InputObject ([IO.File]::ReadAllText($receipt)) + if ($record.schema -ne 1 -or $record.version -cne $Version -or $record.sha256 -cne $hash) { + throw "Receipt verification failed for $Version." + } + if ([IO.File]::Exists($pending)) { + throw "Pending journal remains after successful installation of $Version." + } + $debris = @(Get-ChildItem -LiteralPath $bin -Force | Where-Object { + $_.Name -match '\A\.proofline-(staged|recovery|api-backup|restore|damaged)-' + }) + if ($debris.Count -ne 0) { + throw "Unexpected staged or recovery artifacts remain after $Version." + } + $output = @(& $exe '--version') + $exitCode = $LASTEXITCODE + if ($exitCode -ne 0 -or ($output -join [Environment]::NewLine).Trim() -cne "proofline $Version") { + throw "Executable version check failed for $Version (exit $exitCode)." + } + return [pscustomobject]@{ + BinarySha256 = $hash + ReceiptSha256 = $receiptHash + } +} + +try { + Install-Release '0.5.1' + $before = Check-Release '0.5.1' + Write-Host "PASS fresh v0.5.1 install; hash $($before.BinarySha256)" + + Install-Release '0.5.2' + $after = Check-Release '0.5.2' + if ($before.BinarySha256 -ceq $after.BinarySha256) { + throw 'Old and new executable hashes unexpectedly match.' + } + Write-Host "PASS upgrade to v0.5.2; hash $($after.BinarySha256)" + + Install-Release '0.5.2' + $repeat = Check-Release '0.5.2' + if ($repeat.BinarySha256 -cne $after.BinarySha256 -or + $repeat.ReceiptSha256 -cne $after.ReceiptSha256) { + throw 'Repeated installation modified executable or receipt.' + } + Write-Host 'PASS v0.5.2 reinstallation is a no-op' + + if ([Environment]::GetEnvironmentVariable('Path', 'User') -cne $oldUserPath) { + throw 'User PATH changed despite -NoModifyPath.' + } + Write-Host 'PASS user PATH unchanged' + $passed = $true +} +catch { + Write-Warning "FAIL real-release integration: $($_.Exception.ToString())" +} +finally { + if ($passed -and -not $KeepFiles) { + try { + Remove-Item -LiteralPath $root -Force -Recurse -ErrorAction Stop + } + catch { + Write-Warning "Could not clean disposable test directory: $($_.Exception.Message)" + $passed = $false + } + } +} +if ($passed) { + Write-Host 'Real Windows release upgrade test: PASS' + if ($KeepFiles) { Write-Host "Retained test installation: $bin" } + else { Write-Host 'Cleaned temporary test directory.' } +} +else { + Write-Warning "Test evidence retained at: $root" + exit 1 +} From d40ef39601a80219d254ebc1f66b1d5d797bc207 Mon Sep 17 00:00:00 2001 From: Ayan Khan Date: Mon, 23 Nov 2026 11:07:12 +0530 Subject: [PATCH 04/21] ci(windows): test both PowerShell editions and User PATH persistence --- .github/workflows/windows-installer.yml | 56 ++++++++++++ scripts/test_install_user_path_ci_windows.ps1 | 89 +++++++++++++++++++ 2 files changed, 145 insertions(+) create mode 100644 .github/workflows/windows-installer.yml create mode 100644 scripts/test_install_user_path_ci_windows.ps1 diff --git a/.github/workflows/windows-installer.yml b/.github/workflows/windows-installer.yml new file mode 100644 index 0000000..c3513fe --- /dev/null +++ b/.github/workflows/windows-installer.yml @@ -0,0 +1,56 @@ +name: Windows installer tests + +on: + pull_request: + paths: + - 'install.ps1' + - 'scripts/test_install*windows.ps1' + - 'scripts/generate_windows_installer_fixtures.py' + - '.github/workflows/windows-installer.yml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + offline-validation: + name: Installer offline tests (${{ matrix.engine }}) + runs-on: windows-2025 + timeout-minutes: 20 + strategy: + fail-fast: false + matrix: + engine: ['powershell.exe', 'pwsh.exe'] + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Check fixture generator + shell: pwsh + run: | + python -m py_compile scripts/generate_windows_installer_fixtures.py + if ($LASTEXITCODE -ne 0) { throw 'Fixture generator did not compile.' } + + - name: Run validator and recovery fixtures + shell: pwsh + env: + TEST_ENGINE: ${{ matrix.engine }} + run: | + foreach ($script in @( + 'scripts/test_install_windows.ps1', + 'scripts/test_install_upgrade_windows.ps1', + 'scripts/test_install_concurrency_windows.ps1' + )) { + Write-Host "Running $script with $env:TEST_ENGINE" + & $env:TEST_ENGINE -NoProfile -NonInteractive -File $script + if ($LASTEXITCODE -ne 0) { throw "$script failed with exit code $LASTEXITCODE" } + } + + - name: Verify User PATH persistence on disposable CI runner + shell: pwsh + env: + TEST_ENGINE: ${{ matrix.engine }} + run: | + & $env:TEST_ENGINE -NoProfile -NonInteractive -File scripts/test_install_user_path_ci_windows.ps1 + if ($LASTEXITCODE -ne 0) { throw "User PATH persistence test failed: $LASTEXITCODE" } diff --git a/scripts/test_install_user_path_ci_windows.ps1 b/scripts/test_install_user_path_ci_windows.ps1 new file mode 100644 index 0000000..c8cf2a0 --- /dev/null +++ b/scripts/test_install_user_path_ci_windows.ps1 @@ -0,0 +1,89 @@ +#requires -Version 5.1 +<# +.SYNOPSIS + Verify current-user PATH registry updates only in a disposable CI runner. +.DESCRIPTION + Writes a unique temporary Proofline-style PATH entry to the CI runner's + User PATH, checks a fresh PowerShell process can read it, checks idempotence, + and restores the original value in finally. Refuses non-CI execution. + Never run this test on a personal Windows profile. +#> +[CmdletBinding()] +param([ValidateSet('Check','ReadUserPath')][string]$Mode = 'Check') + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' +if ([Environment]::OSVersion.Platform -ne [PlatformID]::Win32NT) { + throw 'Windows CI runner required.' +} +if ($env:GITHUB_ACTIONS -cne 'true' -or [string]::IsNullOrWhiteSpace($env:RUNNER_TEMP)) { + throw 'Refusing PATH registry test outside GitHub Actions Windows runner.' +} + +if ($Mode -eq 'ReadUserPath') { + $freshPath = [Environment]::GetEnvironmentVariable('Path', 'User') + if ($null -eq $freshPath) { $freshPath = '' } + [Console]::Out.Write([Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($freshPath))) + exit 0 +} + +. (Join-Path (Split-Path -Parent $PSScriptRoot) 'install.ps1') +$original = [Environment]::GetEnvironmentVariable('Path', 'User') +$directory = Join-Path $env:RUNNER_TEMP ('proofline-path-ci-' + [guid]::NewGuid().ToString('N')) +$expected = Get-ProoflineUpdatedUserPath $original $directory +if ($null -eq $expected) { + throw 'Fresh randomized CI directory was already in User PATH.' +} +[IO.Directory]::CreateDirectory($directory) | Out-Null +$ok = $false +$restoreOk = $false +try { + Add-ProoflineUserPath $directory + $after = [Environment]::GetEnvironmentVariable('Path', 'User') + if ($after -cne $expected) { + throw 'User PATH did not persist expected entry.' + } + if ($null -ne (Get-ProoflineUpdatedUserPath $after $directory)) { + throw 'User PATH idempotence function returned a duplicate entry.' + } + Add-ProoflineUserPath $directory + if ([Environment]::GetEnvironmentVariable('Path', 'User') -cne $expected) { + throw 'Second PATH update mutated the registry value.' + } + + $engine = (Get-Process -Id $PID).Path + $encoded = @(& $engine -NoProfile -NonInteractive -File $PSCommandPath -Mode ReadUserPath) + if ($LASTEXITCODE -ne 0) { + throw "Fresh PowerShell process failed to read User PATH: $LASTEXITCODE" + } + $fresh = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String(($encoded -join '').Trim())) + if ($fresh -cne $expected) { + throw 'Fresh PowerShell process observed a different User PATH.' + } + Write-Host 'PASS new PowerShell process sees persistent User PATH entry.' + Write-Host 'PASS repeated PATH update does not duplicate entry.' + $ok = $true +} +finally { + # Restore only if the test's exact value is still present. In case of an + # unexpected concurrent edit, do not overwrite it with an older snapshot. + $current = [Environment]::GetEnvironmentVariable('Path', 'User') + if ($current -ceq $expected) { + [Environment]::SetEnvironmentVariable('Path', $original, 'User') + $restored = [Environment]::GetEnvironmentVariable('Path', 'User') + $normalizedOriginal = if ($null -eq $original) { '' } else { $original } + $normalizedRestored = if ($null -eq $restored) { '' } else { $restored } + $restoreOk = ($normalizedRestored -ceq $normalizedOriginal) + if (-not $restoreOk) { + Write-Warning 'Could not verify original CI User PATH value was restored.' + } + } + else { + Write-Warning 'User PATH changed unexpectedly during CI; refusing to overwrite concurrent edits.' + } + Remove-Item -LiteralPath $directory -Recurse -Force -ErrorAction SilentlyContinue +} +if (-not $ok -or -not $restoreOk) { + throw 'CI User PATH persistence check failed or did not restore original value.' +} +Write-Host 'CI User PATH persistence and restore: PASS' From ef91fbf7c69cb7ca2e1e2e3ee100afdec8f73eb8 Mon Sep 17 00:00:00 2001 From: Ayan Khan Date: Mon, 23 Nov 2026 11:07:57 +0530 Subject: [PATCH 05/21] docs(windows): document installation, tests, and safety boundaries --- README.md | 36 ++++++++++++++++++++++++++++++++++-- install.ps1 | 2 +- 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 18c4903..93ae37f 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ The command-line client for the [Proofline review API](https://proofline.sh/docs/). See the [CLI documentation](https://proofline.sh/docs/cli/) for commands. -This repository is the published distribution of the Proofline CLI. `openapi.public.json` is the generated public API contract pinned for this revision. During the build, `build.rs` generates request URLs for the operations it declares. [Open an issue](https://github.com/prooflinedev/cli/issues) for changes to `openapi.public.json`, generated code, or workflows. Pull requests are welcome for the hand-written installer in `install.sh`, commands in `src/`, release scripts in `scripts/`, and tests in `tests/`. +This repository is the published distribution of the Proofline CLI. `openapi.public.json` is the generated public API contract pinned for this revision. During the build, `build.rs` generates request URLs for the operations it declares. [Open an issue](https://github.com/prooflinedev/cli/issues) for changes to `openapi.public.json`, generated code, or workflows. Pull requests are welcome for the hand-written installers in `install.sh` and `install.ps1`, commands in `src/`, release scripts in `scripts/`, and tests in `tests/`. ## Installation and setup @@ -12,7 +12,39 @@ On Linux and macOS, install the CLI with `curl -fsSL https://proofline.sh/cli | ### Windows installation -Official releases include `proofline-x86_64-pc-windows-msvc.tar.gz` with `proofline.exe`. Download the archive and `SHA256SUMS` from the same GitHub release, and compare its SHA-256 hash using `Get-FileHash -Algorithm SHA256`. Extract the archive with `tar -xzf` and put `proofline.exe` in a directory on `PATH`. Run `proofline login` to store credentials in Windows Credential Manager. To update, close running Proofline processes and replace the executable from a verified release. The Unix shell installer and self-update command do not install Windows binaries. +On **Windows x64**, run the PowerShell installer from a checked-out copy of this repository: + +```powershell +powershell.exe -NoProfile -File .\install.ps1 +``` + +It downloads the official release and `SHA256SUMS` from `https://proofline.sh`, validates the archive, verifies `proofline.exe --version`, and installs for the **current user** in `%LOCALAPPDATA%\Programs\Proofline\bin` without administrator rights. By default it adds that directory to the user PATH; open a new terminal to run `proofline login`. It does not handle login or credentials. + +To pin a version or install in a disposable folder without updating PATH: + +```powershell +powershell.exe -NoProfile -File .\install.ps1 -Version 0.5.2 -InstallDir "$env:TEMP\proofline-test-bin" -NoModifyPath +``` + +Re-running the installer with the same verified version is a no-op. Upgrading an installer-managed version preserves the previous executable and uses a pending recovery record; an unmanaged or inconsistent existing installation is not overwritten. No administrator privileges or machine-level PATH changes are required. + +The installer script is currently distributed **in this repository**, not via a verified Windows one-liner on `proofline.sh`. Alternatively, manually download `proofline-x86_64-pc-windows-msvc.tar.gz` and its `SHA256SUMS` from the same official release, verify the SHA-256 with `Get-FileHash`, extract `proofline.exe` and place it on PATH. + +Windows `proofline update` (self-update invoked from the CLI) remains unsupported; re-run `install.ps1` to upgrade an installer-managed installation. + +The installer verifies the archive against the official SHA-256 manifest. Because both are fetched from the same HTTPS release origin, this establishes download consistency rather than independent cryptographic publisher authentication. + +To verify the installer on Windows x64, run the following from the repository root (Python 3 is required for the offline fixtures): + +```powershell +powershell.exe -NoProfile -File .\scripts\test_install_windows.ps1 +powershell.exe -NoProfile -File .\scripts\test_install_upgrade_windows.ps1 +powershell.exe -NoProfile -File .\scripts\test_install_concurrency_windows.ps1 +powershell.exe -NoProfile -File .\scripts\test_install_upgrade_real_windows.ps1 +powershell.exe -NoProfile -File .\scripts\test_install_interruption_real_windows.ps1 +``` + +Run the same commands with `pwsh.exe` to verify PowerShell 7. The last two tests download pinned official releases; all test installations use disposable paths and do not modify User PATH. The separate `scripts/test_install_user_path_ci_windows.ps1` test intentionally runs **only on GitHub Actions Windows runners**, where it verifies registry persistence and restores the original User PATH value. On Linux, coding agents that omit `DBUS_SESSION_BUS_ADDRESS` and `XDG_RUNTIME_DIR` can still use the stored sign-in when the standard `/run/user//bus` socket diff --git a/install.ps1 b/install.ps1 index c02ed6f..bcab68a 100644 --- a/install.ps1 +++ b/install.ps1 @@ -1,6 +1,6 @@ # Install the official Proofline Windows x64 CLI release for the current user. # Installer-managed upgrades use a verified previous image, a pending journal, -# and postcheck/rollback. Installer-managed upgrades have Windows 5.1 test coverage. +# and postcheck/rollback. Tested on Windows PowerShell 5.1 and PowerShell 7. # .\install.ps1 [-Version 0.5.2] [-InstallDir C:\path\to\bin] [-NoModifyPath] [CmdletBinding()] param( From 55624bb55ee565ce3b90ed3fc6665f975a50f19d Mon Sep 17 00:00:00 2001 From: Ayan Khan Date: Mon, 23 Nov 2026 11:43:34 +0530 Subject: [PATCH 06/21] fix(windows): harden upgrade recovery, PATH integrity, and timeouts --- README.md | 10 +- install.ps1 | 184 ++++++++++++++---- ...test_install_interruption_real_windows.ps1 | 95 +++++++-- scripts/test_install_upgrade_windows.ps1 | 76 +++++++- scripts/test_install_user_path_ci_windows.ps1 | 125 +++++++----- 5 files changed, 381 insertions(+), 109 deletions(-) diff --git a/README.md b/README.md index 93ae37f..7416aa6 100644 --- a/README.md +++ b/README.md @@ -12,13 +12,13 @@ On Linux and macOS, install the CLI with `curl -fsSL https://proofline.sh/cli | ### Windows installation -On **Windows x64**, run the PowerShell installer from a checked-out copy of this repository: +On **Windows x64**, run the PowerShell installer from a checked-out copy of this repository. The effective PowerShell execution policy must permit local scripts; inspect it with `Get-ExecutionPolicy -List`. If your organization permits a per-process change, use `Set-ExecutionPolicy -Scope Process RemoteSigned` in the terminal running these commands. Do not override an organization-enforced policy: consult your administrator instead. ```powershell powershell.exe -NoProfile -File .\install.ps1 ``` -It downloads the official release and `SHA256SUMS` from `https://proofline.sh`, validates the archive, verifies `proofline.exe --version`, and installs for the **current user** in `%LOCALAPPDATA%\Programs\Proofline\bin` without administrator rights. By default it adds that directory to the user PATH; open a new terminal to run `proofline login`. It does not handle login or credentials. +It downloads the official release and `SHA256SUMS` from `https://proofline.sh`, validates the archive, verifies `proofline.exe --version`, and installs for the **current user** in `%LOCALAPPDATA%\Programs\Proofline\bin` without administrator rights. By default it appends that directory to the user PATH while preserving expandable registry entries. Open a new terminal and run `Get-Command proofline -All` to check which executable has precedence. If an older copy is found first, run the new executable using its absolute path (for example, `& "$env:LOCALAPPDATA\Programs\Proofline\bin\proofline.exe" login`) or correct the stale PATH entry. The installer does not handle login or credentials. To pin a version or install in a disposable folder without updating PATH: @@ -26,11 +26,11 @@ To pin a version or install in a disposable folder without updating PATH: powershell.exe -NoProfile -File .\install.ps1 -Version 0.5.2 -InstallDir "$env:TEMP\proofline-test-bin" -NoModifyPath ``` -Re-running the installer with the same verified version is a no-op. Upgrading an installer-managed version preserves the previous executable and uses a pending recovery record; an unmanaged or inconsistent existing installation is not overwritten. No administrator privileges or machine-level PATH changes are required. +Re-running the installer with the same verified version does not replace the executable or receipt, but User PATH may still be updated unless `-NoModifyPath` is selected. Upgrading an installer-managed version preserves the previous executable and uses a pending recovery record; an unmanaged or inconsistent existing installation is not overwritten. No administrator privileges or machine-level PATH changes are required. The installer script is currently distributed **in this repository**, not via a verified Windows one-liner on `proofline.sh`. Alternatively, manually download `proofline-x86_64-pc-windows-msvc.tar.gz` and its `SHA256SUMS` from the same official release, verify the SHA-256 with `Get-FileHash`, extract `proofline.exe` and place it on PATH. -Windows `proofline update` (self-update invoked from the CLI) remains unsupported; re-run `install.ps1` to upgrade an installer-managed installation. +Windows `proofline update` (self-update invoked from the CLI) remains unsupported; re-run `install.ps1` to upgrade an installer-managed installation. After a process interruption, a later installer run uses a pending journal to complete or recover a recognized transaction. A partial first-install or pre-switch stage can be retained with an `.incomplete` suffix for diagnostics without blocking a new attempt. Errors that cannot be safely classified preserve evidence and may require manual recovery. The installer verifies the archive against the official SHA-256 manifest. Because both are fetched from the same HTTPS release origin, this establishes download consistency rather than independent cryptographic publisher authentication. @@ -44,7 +44,7 @@ powershell.exe -NoProfile -File .\scripts\test_install_upgrade_real_windows.ps1 powershell.exe -NoProfile -File .\scripts\test_install_interruption_real_windows.ps1 ``` -Run the same commands with `pwsh.exe` to verify PowerShell 7. The last two tests download pinned official releases; all test installations use disposable paths and do not modify User PATH. The separate `scripts/test_install_user_path_ci_windows.ps1` test intentionally runs **only on GitHub Actions Windows runners**, where it verifies registry persistence and restores the original User PATH value. +Run the same commands with `pwsh.exe` to verify PowerShell 7. The interruption test additionally covers hard termination during partially written stages. The last two tests download pinned official releases; all test installations use disposable paths and do not modify User PATH. The separate `scripts/test_install_user_path_ci_windows.ps1` test intentionally runs **only on GitHub Actions Windows runners**, where it verifies registry persistence and restores the original User PATH value. On Linux, coding agents that omit `DBUS_SESSION_BUS_ADDRESS` and `XDG_RUNTIME_DIR` can still use the stored sign-in when the standard `/run/user//bus` socket diff --git a/install.ps1 b/install.ps1 index bcab68a..7da9b98 100644 --- a/install.ps1 +++ b/install.ps1 @@ -56,6 +56,8 @@ function Get-ProoflineOfficialBytes([string]$RelativePath, [int]$MaximumLength) $cancellation = [Threading.CancellationTokenSource]::new() $cancellation.CancelAfter(120000) try { + # Bound the complete response, including any stalled body reads. + $downloadClock = [Diagnostics.Stopwatch]::StartNew() $uri = [Uri]($script:ProoflineOrigin + $RelativePath) for ($redirect = 0; $redirect -le 3; $redirect++) { $response = $client.GetAsync($uri, [Net.Http.HttpCompletionOption]::ResponseHeadersRead, $cancellation.Token).GetAwaiter().GetResult() @@ -83,7 +85,20 @@ function Get-ProoflineOfficialBytes([string]$RelativePath, [int]$MaximumLength) try { $buffer = [byte[]]::new(65536) while ($true) { - $count = $inputStream.ReadAsync($buffer, 0, $buffer.Length, $cancellation.Token).GetAwaiter().GetResult() + $remaining = [int][Math]::Max(0, 120000 - $downloadClock.ElapsedMilliseconds) + if ($remaining -eq 0) { + $response.Dispose() + throw 'Release download exceeded its 120-second deadline.' + } + $read = $inputStream.ReadAsync($buffer, 0, $buffer.Length, $cancellation.Token) + # HttpClient.Timeout stops after headers with ResponseHeadersRead. + # On .NET Framework, stream cancellation may be ignored; bound + # the actual wait and close the response on timeout. + if (-not $read.Wait($remaining)) { + $response.Dispose() + throw 'Release download exceeded its 120-second deadline.' + } + $count = $read.GetAwaiter().GetResult() if ($count -eq 0) { break } if ($outputStream.Length + $count -gt $MaximumLength) { throw 'Release download exceeds the permitted size.' @@ -267,14 +282,71 @@ function Get-ProoflineUpdatedUserPath([string]$Current, [string]$Directory) { return $result } +function Get-ProoflineUserPathRecord { + # Environment.GetEnvironmentVariable('Path', 'User') expands REG_EXPAND_SZ. + # Read raw text and the registry kind to avoid flattening %VARIABLE% entries. + $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $false) + if ($null -eq $key) { + return @{ value = ''; kind = [Microsoft.Win32.RegistryValueKind]::ExpandString; exists = $false } + } + try { + if ('Path' -notin @($key.GetValueNames())) { + return @{ value = ''; kind = [Microsoft.Win32.RegistryValueKind]::ExpandString; exists = $false } + } + $kind = $key.GetValueKind('Path') + if ($kind -notin @([Microsoft.Win32.RegistryValueKind]::String, + [Microsoft.Win32.RegistryValueKind]::ExpandString)) { + throw 'User PATH registry value has an unsupported type; change it manually.' + } + $value = $key.GetValue('Path', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames) + if ($value -isnot [string]) { throw 'User PATH registry value is not text.' } + return @{ value = $value; kind = $kind; exists = $true } + } + finally { $key.Dispose() } +} + +function Send-ProoflineEnvironmentChange { + # RegistryKey.SetValue retains REG_EXPAND_SZ but does not notify other + # processes. Notify the shell as Environment.SetEnvironmentVariable does. + if (-not ('ProoflineEnvironmentNotifier' -as [type])) { + Add-Type -TypeDefinition @' +using System; +using System.Runtime.InteropServices; +public static class ProoflineEnvironmentNotifier { + [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + public static extern IntPtr SendMessageTimeout(IntPtr hwnd, uint msg, + IntPtr wParam, string lParam, uint flags, uint timeout, out IntPtr result); +} +'@ + } + $result = [IntPtr]::Zero + $sent = [ProoflineEnvironmentNotifier]::SendMessageTimeout( + [IntPtr]65535, 0x1a, [IntPtr]::Zero, 'Environment', 0x2, 5000, [ref]$result) + if ($sent -eq [IntPtr]::Zero) { + Write-Warning 'User PATH was saved, but the environment-change notification was not acknowledged. Open a new terminal.' + } +} + function Add-ProoflineUserPath([string]$Directory) { - $current = [Environment]::GetEnvironmentVariable('Path', 'User') - $result = Get-ProoflineUpdatedUserPath $current $Directory + $previous = Get-ProoflineUserPathRecord + $result = Get-ProoflineUpdatedUserPath $previous.value $Directory if ($null -eq $result) { Write-Host 'User PATH already contains the Proofline directory.' return } - [Environment]::SetEnvironmentVariable('Path', $result, 'User') + $key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Environment') + try { + # Avoid an obvious lost update if another process changed PATH since + # our read. This is not a cross-process atomic registry compare/swap. + $fresh = Get-ProoflineUserPathRecord + if ($fresh.value -cne $previous.value -or + $fresh.kind -ne $previous.kind -or $fresh.exists -ne $previous.exists) { + throw 'User PATH changed concurrently; retry the installer or add the directory manually.' + } + $key.SetValue('Path', $result, $previous.kind) + } + finally { $key.Dispose() } + Send-ProoflineEnvironmentChange Write-Host 'Added Proofline to your user PATH. Open a new terminal to use it.' } @@ -444,16 +516,28 @@ function Get-ProoflineTransactionPaths([string]$Directory, [string]$Id) { } } -function Clear-ProoflineUpgradeFiles([hashtable]$Paths, [string]$Pending, [string]$NewHash) { - # Deleting every matching ".proofline-staged-*.exe" would remove files - # belonging to unrelated attempts. A schema-2 journal's validated ID - # identifies precisely one stage belonging to this transaction. +function Clear-ProoflineUpgradeFiles( + [hashtable]$Paths, [string]$Pending, [string]$NewHash, + [switch]$PreserveIncompleteStage +) { + # Only delete transaction-owned artifacts derived from a validated ID. foreach ($key in @('old', 'api', 'stage')) { Assert-ProoflineNoReparse $Paths[$key] } if ([IO.File]::Exists($Paths.stage) -and (Get-ProoflineSha256 $Paths.stage) -cne $NewHash) { - throw 'Pending upgrade stage has unexpected contents; preserving transaction evidence.' + if (-not $PreserveIncompleteStage) { + throw 'Pending upgrade stage has unexpected contents; preserving transaction evidence.' + } + # Before switching, the installed old executable is still intact. + # Quarantine an incomplete stage instead of permanently blocking retry. + $evidence = $Paths.stage + '.incomplete' + Assert-ProoflineNoReparse $evidence + if ([IO.File]::Exists($evidence)) { + throw 'Incomplete-stage evidence path already exists; preserving the journal.' + } + [IO.File]::Move($Paths.stage, $evidence) + Write-Warning "Unverified interrupted upgrade stage preserved at $evidence" } foreach ($key in @('old', 'api', 'stage')) { if ([IO.File]::Exists($Paths[$key])) { [IO.File]::Delete($Paths[$key]) } @@ -481,25 +565,37 @@ function Recover-ProoflinePending([string]$Directory) { if ($record.schema -eq 3) { $stage = [IO.Path]::Combine($Directory, ('.proofline-staged-' + $record.id + '.exe')) Assert-ProoflineNoReparse $stage - if ([IO.File]::Exists($stage) -and - (Get-ProoflineSha256 $stage) -cne $record.sha256) { - throw 'Interrupted first-install stage differs from verified release; preserving journal.' - } } if (-not [IO.File]::Exists($destination)) { if ([IO.File]::Exists($receipt)) { throw 'Interrupted first installation has a receipt but no executable.' } if ($null -ne $stage -and [IO.File]::Exists($stage)) { - [IO.File]::Delete($stage) + if ((Get-ProoflineSha256 $stage) -cne $record.sha256) { + # No executable was published. Keep incomplete bytes for + # diagnosis, but remove the transaction's blocking journal. + $evidence = $stage + '.incomplete' + Assert-ProoflineNoReparse $evidence + if ([IO.File]::Exists($evidence)) { + throw 'Incomplete-stage evidence path already exists; preserving journal.' + } + [IO.File]::Move($stage, $evidence) + Write-Warning "Unverified first-install stage preserved at $evidence" + } + else { [IO.File]::Delete($stage) } } [IO.File]::Delete($pending) return } + if ($null -ne $stage -and [IO.File]::Exists($stage) -and + (Get-ProoflineSha256 $stage) -cne $record.sha256) { + throw 'Published first-install executable has an unverified stage; preserving journal.' + } if ((Get-ProoflineSha256 $destination) -cne $record.sha256) { throw 'Interrupted first install has an unrecognized executable; preserving journal.' } - Assert-ProoflineExeVersion $destination $record.version + # Do not execute an existing image whose hash is trusted only against + # mutable local metadata. Smoke tests run on verified download stages. if ([IO.File]::Exists($receipt)) { Assert-ProoflineRecord $receipt $record.version $record.sha256 } @@ -518,22 +614,30 @@ function Recover-ProoflinePending([string]$Directory) { if ([IO.File]::Exists($destination)) { $activeHash = Get-ProoflineSha256 $destination } if ($activeHash -ceq $record.newSha256) { + $finalized = $false try { - Assert-ProoflineExeVersion $destination $record.newVersion + # A local journal hash is not sufficient authority to execute + # an existing image. Validate bytes and write the matching receipt. Write-ProoflineReceipt $receipt $record.newVersion $record.newSha256 - Clear-ProoflineUpgradeFiles $paths $pending $record.newSha256 + $finalized = $true + } + catch { + Write-Warning "New executable is present but cannot be finalized: $($_.Exception.Message)" + } + if ($finalized) { + # Cleaning old files is not part of the successful version switch. + # Preserve the new executable and journal if cleanup must be retried. + try { Clear-ProoflineUpgradeFiles $paths $pending $record.newSha256 } + catch { Write-Warning "Upgrade finalized; cleanup will be retried: $($_.Exception.Message)" } Write-Host "Finalized interrupted Proofline $($record.newVersion) upgrade." return - } catch { - Write-Warning "New executable is present but cannot be finalized: $($_.Exception.Message)" - # Try verified old copy below rather than claiming the upgrade worked. } } if ($activeHash -ceq $record.oldSha256) { - Assert-ProoflineExeVersion $destination $record.oldVersion Write-ProoflineReceipt $receipt $record.oldVersion $record.oldSha256 - Clear-ProoflineUpgradeFiles $paths $pending $record.newSha256 + try { Clear-ProoflineUpgradeFiles $paths $pending $record.newSha256 -PreserveIncompleteStage } + catch { Write-Warning "Verified previous installation retained; cleanup will be retried: $($_.Exception.Message)" } Write-Host "Previous Proofline $($record.oldVersion) installation remains usable." return } @@ -567,7 +671,8 @@ function Recover-ProoflinePending([string]$Directory) { if ((Get-ProoflineSha256 $destination) -cne $record.oldSha256) { throw 'Restored executable digest differs from previous release.' } - Assert-ProoflineExeVersion $destination $record.oldVersion + # Recovery copy was checked against the recorded hash; do not execute + # a pre-existing local image during repair. Write-ProoflineReceipt $receipt $record.oldVersion $record.oldSha256 Clear-ProoflineUpgradeFiles $paths $pending $record.newSha256 Write-Host "Restored verified Proofline $($record.oldVersion) after interrupted upgrade." @@ -692,7 +797,8 @@ function Install-ProoflineArchive( if ((Get-ProoflineSha256 $destination) -cne $oldReceipt.sha256) { throw 'Existing Proofline executable does not match its installer-managed receipt.' } - Assert-ProoflineExeVersion $destination $oldReceipt.version + # Existing binaries are not executed merely because a local + # receipt contains a matching hash. Only verified downloads run. if ($oldReceipt.version -ceq $ReleaseVersion -and $oldReceipt.sha256 -ceq $hash) { Write-Host "Proofline $ReleaseVersion is already installed; nothing was changed." @@ -705,17 +811,27 @@ function Install-ProoflineArchive( $stage = [IO.Path]::Combine($directory, ('.proofline-staged-' + $id + '.exe')) Assert-ProoflineNoReparse $stage if ($null -eq $oldReceipt) { - # Write the schema-3 journal BEFORE creating the stage. If killed - # during a write, recovery retains incomplete bytes as evidence; - # it only deletes a stage whose digest matches the verified one. $record = ConvertTo-Json -Compress -InputObject ([ordered]@{ schema = 3 id = $id version = $ReleaseVersion sha256 = $hash }) - Write-ProoflineAtomicRecord $pending $record } + else { + # Journal BEFORE creating the staged image or previous-version + # copy. A killed preparation then has an exact transaction ID + # with which to clean up owned artifacts. + $record = ConvertTo-Json -Compress -InputObject ([ordered]@{ + schema = 2 + id = $id + oldVersion = $oldReceipt.version + oldSha256 = $oldReceipt.sha256 + newVersion = $ReleaseVersion + newSha256 = $hash + }) + } + Write-ProoflineAtomicRecord $pending $record try { $stream = [IO.File]::Open($stage, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::None) @@ -744,15 +860,6 @@ function Install-ProoflineArchive( if ((Get-ProoflineSha256 $paths.old) -cne $oldReceipt.sha256) { throw 'Could not preserve a verified previous executable; upgrade aborted.' } - $record = ConvertTo-Json -Compress -InputObject ([ordered]@{ - schema = 2 - id = $id - oldVersion = $oldReceipt.version - oldSha256 = $oldReceipt.sha256 - newVersion = $ReleaseVersion - newSha256 = $hash - }) - Write-ProoflineAtomicRecord $pending $record try { Invoke-ProoflineReplaceWithRetry $stage $destination $paths.api $hash $oldReceipt.sha256 if ((Get-ProoflineSha256 $destination) -cne $hash) { @@ -760,7 +867,8 @@ function Install-ProoflineArchive( } Assert-ProoflineExeVersion $destination $ReleaseVersion Write-ProoflineReceipt $receipt $ReleaseVersion $hash - Clear-ProoflineUpgradeFiles $paths $pending $hash + try { Clear-ProoflineUpgradeFiles $paths $pending $hash } + catch { Write-Warning "Verified upgrade retained; cleanup will be retried: $($_.Exception.Message)" } Write-Host "Upgraded Proofline $($oldReceipt.version) to $ReleaseVersion." return $destination } diff --git a/scripts/test_install_interruption_real_windows.ps1 b/scripts/test_install_interruption_real_windows.ps1 index 392b057..b0804ab 100644 --- a/scripts/test_install_interruption_real_windows.ps1 +++ b/scripts/test_install_interruption_real_windows.ps1 @@ -142,10 +142,17 @@ function Make-InstrumentedInstaller([string]$Source, [string]$Destination, [stri $Checkpoint + ''', [Text.Encoding]::ASCII)' $abort = $mark + "`n" + ' Stop-Process -Id $PID -Force -ErrorAction Stop' if ($Checkpoint -eq 'after-journal') { - $target = ' Write-ProoflineAtomicRecord $pending $record' + - "`n" + ' try {' - $replacement = ' Write-ProoflineAtomicRecord $pending $record' + - "`n" + ' ' + $abort + "`n" + ' try {' + $target = ' Write-ProoflineAtomicRecord $pending $record' + + "`n" + ' try {' + $replacement = ' Write-ProoflineAtomicRecord $pending $record' + + "`n" + ' ' + $abort + "`n" + ' try {' + } + elseif ($Checkpoint -eq 'fresh-partial-stage' -or $Checkpoint -eq 'upgrade-partial-stage') { + $target = ' $stream.Write($binary, 0, $binary.Length)' + + "`n" + ' $stream.Flush($true)' + $replacement = ' $stream.Write($binary, 0, [Math]::Min(32, $binary.Length))' + + "`n" + ' $stream.Flush($true)' + + "`n" + ' ' + $abort } elseif ($Checkpoint -eq 'after-switch' -or $Checkpoint -eq 'corrupt-after-switch') { $target = ' Invoke-ProoflineReplaceWithRetry $stage $destination $paths.api $hash $oldReceipt.sha256' + @@ -159,15 +166,16 @@ function Make-InstrumentedInstaller([string]$Source, [string]$Destination, [stri } elseif ($Checkpoint -eq 'after-receipt') { $target = ' Write-ProoflineReceipt $receipt $ReleaseVersion $hash' + - "`n" + ' Clear-ProoflineUpgradeFiles $paths $pending $hash' + "`n" + ' try { Clear-ProoflineUpgradeFiles $paths $pending $hash }' $replacement = ' Write-ProoflineReceipt $receipt $ReleaseVersion $hash' + - "`n" + ' ' + $abort + "`n" + ' Clear-ProoflineUpgradeFiles $paths $pending $hash' + "`n" + ' ' + $abort + + "`n" + ' try { Clear-ProoflineUpgradeFiles $paths $pending $hash }' } elseif ($Checkpoint -eq 'fresh-after-journal') { - $target = ' Write-ProoflineAtomicRecord $pending $record' + - "`n" + ' }' + "`n" + ' try {' - $replacement = ' Write-ProoflineAtomicRecord $pending $record' + - "`n" + ' ' + $abort + "`n" + ' }' + "`n" + ' try {' + $target = ' Write-ProoflineAtomicRecord $pending $record' + + "`n" + ' try {' + $replacement = ' Write-ProoflineAtomicRecord $pending $record' + + "`n" + ' ' + $abort + "`n" + ' try {' } elseif ($Checkpoint -eq 'fresh-after-stage') { $target = ' Assert-ProoflineExeVersion $stage $ReleaseVersion' + @@ -199,15 +207,17 @@ $root = Join-Path ([IO.Path]::GetTempPath()) ('proofline-real-interruption-' + [ $cache = Join-Path $root 'cache' [IO.Directory]::CreateDirectory($cache) | Out-Null $scenarios = @( - 'after-journal', 'after-switch', 'corrupt-after-switch', 'after-receipt', - 'fresh-after-journal', 'fresh-after-stage', 'fresh-after-move', 'fresh-after-receipt' + 'after-journal', 'upgrade-partial-stage', 'after-switch', 'corrupt-after-switch', 'after-receipt', + 'fresh-after-journal', 'fresh-partial-stage', 'fresh-after-stage', 'fresh-after-move', 'fresh-after-receipt' ) $expected = @{ 'after-journal' = '0.5.1' + 'upgrade-partial-stage' = '0.5.1' 'after-switch' = '0.5.2' 'corrupt-after-switch' = '0.5.1' 'after-receipt' = '0.5.2' 'fresh-after-journal' = 'absent' + 'fresh-partial-stage' = 'absent' 'fresh-after-stage' = 'absent' 'fresh-after-move' = '0.5.1' 'fresh-after-receipt' = '0.5.1' @@ -274,13 +284,13 @@ try { if ([IO.File]::Exists($activeFile)) { $activeDigest = (Get-FileHash -LiteralPath $activeFile -Algorithm SHA256).Hash } - if ($checkpoint -in @('fresh-after-journal', 'fresh-after-stage')) { + if ($checkpoint -in @('fresh-after-journal', 'fresh-partial-stage', 'fresh-after-stage')) { Require ($null -eq $activeDigest) 'Fresh install published executable before intended checkpoint.' } elseif ($checkpoint -in @('fresh-after-move', 'fresh-after-receipt')) { Require ($null -ne $activeDigest) 'Fresh install did not publish executable before checkpoint.' } - elseif ($checkpoint -eq 'after-journal') { + elseif ($checkpoint -in @('after-journal', 'upgrade-partial-stage')) { Require ($activeDigest -ceq $oldDigest) 'Journal checkpoint unexpectedly changed old executable.' } elseif ($checkpoint -eq 'corrupt-after-switch') { @@ -309,6 +319,63 @@ try { $unclaimed = @(Get-ChildItem -LiteralPath $directory -Force | Where-Object { $_.Name -match '^\.proofline-staged-[a-f0-9]{32}\.exe$' }) Require ($unclaimed.Count -eq 0) 'Fresh-install recovery left a staged executable.' + if ($checkpoint -eq 'fresh-partial-stage') { + $evidence = @(Get-ChildItem -LiteralPath $directory -Force | + Where-Object { $_.Name -match '^\.proofline-staged-[a-f0-9]{32}\.exe\.incomplete + } + else { + $digest = Assert-Installed $directory $expected[$checkpoint] ($checkpoint -eq 'corrupt-after-switch') + if ($isFresh) { + Require ($null -ne $digest) 'First-install recovery failed to finalize new executable.' + } + elseif ($expected[$checkpoint] -eq '0.5.1') { + Require ($digest -ceq $oldDigest) 'Rollback did not preserve original executable bytes.' + } + else { + Require ($digest -cne $oldDigest) 'Recovery did not install the different new executable.' + } + Write-Host "PASS $checkpoint; fresh process recovered to v$($expected[$checkpoint])." + } + $results += [pscustomobject]@{ + checkpoint = $checkpoint + workerExitCode = $workerExit + recoveryExitCode = $recoverExit + recoveredVersion = $expected[$checkpoint] + recoveredSha256 = $digest + } + } + + Require ([Environment]::GetEnvironmentVariable('Path', 'User') -ceq $pathBefore) 'User PATH was modified.' + $passed = $true +} +catch { + Write-Warning "FAIL real installer interruption test: $($_.Exception.ToString())" +} +finally { + if ($passed -and -not $KeepFiles) { + try { + Remove-Item -LiteralPath $root -Recurse -Force -ErrorAction Stop + $cleanup = $true + } + catch { + Write-Warning "Could not delete disposable test directory: $($_.Exception.Message)" + $passed = $false + } + } +} +Write-Host "Completed $($results.Count) of $($scenarios.Count) interruption scenarios." +if ($passed) { + Write-Host 'Real Windows installer interruption integration: PASS' + if ($KeepFiles) { Write-Host "Retained test evidence at $root" } + else { Write-Host "Cleaned isolated test directory: $cleanup" } +} +else { + Write-Warning "Failure evidence preserved at: $root" + exit 1 +} + }) + Require ($evidence.Count -eq 1) 'Incomplete first-install bytes were not preserved.' + } Write-Host "PASS $checkpoint; fresh process removed interrupted first-install files." } else { diff --git a/scripts/test_install_upgrade_windows.ps1 b/scripts/test_install_upgrade_windows.ps1 index ecbf2c9..b683123 100644 --- a/scripts/test_install_upgrade_windows.ps1 +++ b/scripts/test_install_upgrade_windows.ps1 @@ -94,7 +94,9 @@ try { # Test-only shadow function: fake PE fixtures are not runnable and must # NEVER be started. Production installer calls the original version checker. + $script:smokeCount = 0 function Assert-ProoflineExeVersion([string]$Path, [string]$Version) { + $script:smokeCount++ $digest = Get-ProoflineSha256 $Path $expected = switch ($Version) { '0.5.1' { $script:oldHash; break } @@ -123,7 +125,7 @@ try { Require (-not [IO.File]::Exists((Join-Path $dir '.proofline-install.pending.json'))) 'Fresh pending record remains.' Require (-not [IO.File]::Exists((Join-Path $dir 'proofline.exe'))) 'Interrupted install unexpectedly published an executable.' } - Check 'interrupted fresh install refuses an unverified stage' { + Check 'interrupted first-install stage is quarantined and retry can proceed' { $dir = Join-Path $root 'fresh-tampered' [IO.Directory]::CreateDirectory($dir) | Out-Null $id = [guid]::NewGuid().ToString('N') @@ -133,9 +135,13 @@ try { Write-ProoflineAtomicRecord $journal (ConvertTo-Json -Compress -InputObject ([ordered]@{ schema = 3; id = $id; version = '0.5.1'; sha256 = $script:oldHash })) - Must-Throw { Invoke-ProoflinePendingRepair $dir } - Require ([IO.File]::Exists($journal)) 'Journal vanished despite unrecognized stage.' - Require ([IO.File]::Exists($stage)) 'Unverified stage was silently discarded.' + Invoke-ProoflinePendingRepair $dir + Require (-not [IO.File]::Exists($journal)) 'Incomplete first install blocked further attempts.' + Require (-not [IO.File]::Exists($stage)) 'Incomplete bytes remained at executable stage path.' + Require ([IO.File]::ReadAllText($stage + '.incomplete') -ceq 'INCOMPLETE_DOWNLOAD') 'Untrusted bytes not retained for diagnosis.' + Require (-not [IO.File]::Exists((Join-Path $dir 'proofline.exe'))) 'Untrusted stage was installed.' + [void](Install-ProoflineArchive $script:oldArchive $script:oldSums '0.5.1' $dir) + Assert-ProoflineRecord (Join-Path $dir '.proofline-install.receipt.json') '0.5.1' $script:oldHash } Check 'interrupted fresh install finalizes verified published executable' { $dir = Join-Path $root 'fresh-published' @@ -181,7 +187,9 @@ try { Check 'repeat upgrade is idempotent' { $dir = PrepareOld 'repeat' [void](Install-ProoflineArchive $script:newArchive $script:newSums '0.5.2' $dir) + $before = $script:smokeCount [void](Install-ProoflineArchive $script:newArchive $script:newSums '0.5.2' $dir) + Require ($script:smokeCount -eq $before) 'No-op installation executed the pre-existing local executable.' Require ((Get-ProoflineSha256 (Active 'repeat')) -ceq $script:newHash) 'Repeat changed active bytes.' Assert-ProoflineRecord (Receipt 'repeat') '0.5.2' $script:newHash } @@ -195,20 +203,25 @@ try { Require ((Get-ProoflineSha256 (Active 'pre-switch-stage')) -ceq $script:oldHash) 'Old executable changed.' Assert-ProoflineRecord (Receipt 'pre-switch-stage') '0.5.1' $script:oldHash } - Check 'untrusted pre-switch stage is preserved with the journal' { + Check 'interrupted upgrade stage is quarantined without blocking retry' { $dir = PrepareOld 'tampered-stage' $paths = MakePending $dir [IO.File]::WriteAllText($paths.stage, 'NOT_THE_VERIFIED_CANDIDATE', [Text.Encoding]::ASCII) - Must-Throw { Invoke-ProoflinePendingRepair $dir } - Require ([IO.File]::Exists((Pending 'tampered-stage'))) 'Unknown staged data lost its pending record.' - Require ([IO.File]::Exists($paths.stage)) 'Unknown staged data was deleted.' + Invoke-ProoflinePendingRepair $dir + Require (-not [IO.File]::Exists((Pending 'tampered-stage'))) 'Pre-switch retry is still blocked.' + Require (-not [IO.File]::Exists($paths.stage)) 'Unverified stage remained available for execution.' + Require ([IO.File]::ReadAllText($paths.stage + '.incomplete') -ceq 'NOT_THE_VERIFIED_CANDIDATE') 'Quarantined evidence is missing.' Require ((Get-ProoflineSha256 (Active 'tampered-stage')) -ceq $script:oldHash) 'Old executable was changed.' + [void](Install-ProoflineArchive $script:newArchive $script:newSums '0.5.2' $dir) + Assert-ProoflineRecord (Receipt 'tampered-stage') '0.5.2' $script:newHash } Check 'new active detected and finalized after restart' { $dir = PrepareOld 'finalize' $paths = MakePending $dir [IO.File]::WriteAllBytes((Active 'finalize'), (Get-ProoflineTarExecutable $script:newArchive)) + $before = $script:smokeCount Invoke-ProoflinePendingRepair $dir + Require ($script:smokeCount -eq $before) 'Recovery executed pre-existing executable verified only by local journal.' Require ((Get-ProoflineSha256 (Active 'finalize')) -ceq $script:newHash) 'New active hash was lost.' Assert-ProoflineRecord (Receipt 'finalize') '0.5.2' $script:newHash Require (-not [IO.File]::Exists((Pending 'finalize'))) 'Pending journal not cleared.' @@ -222,6 +235,53 @@ try { Assert-ProoflineRecord (Receipt 'rollback') '0.5.1' $script:oldHash Require (-not [IO.File]::Exists((Pending 'rollback'))) 'Pending record remains after successful recovery.' } + Check 'crash before upgrade stage creation has a recoverable journal' { + $dir = PrepareOld 'preparation' + $paths = MakePending $dir + [IO.File]::Delete($paths.old) + # The upgrade can now be killed after journaling but before creating + # a stage or a verified old backup. + Invoke-ProoflinePendingRepair $dir + Require (-not [IO.File]::Exists((Pending 'preparation'))) 'Upgrade preparation record blocked retry.' + Require ((Get-ProoflineSha256 (Active 'preparation')) -ceq $script:oldHash) 'Previous executable changed.' + [void](Install-ProoflineArchive $script:newArchive $script:newSums '0.5.2' $dir) + Require ((Get-ProoflineSha256 (Active 'preparation')) -ceq $script:newHash) 'Upgrade could not retry.' + } + Check 'verified normal upgrade is never undone by cleanup failure' { + $dir = PrepareOld 'cleanup-normal' + $originalCleanup = (Get-Item Function:\Clear-ProoflineUpgradeFiles).ScriptBlock + try { + Set-Item Function:\Clear-ProoflineUpgradeFiles -Value { + throw 'Simulated cleanup deletion failure after verified upgrade.' + } + [void](Install-ProoflineArchive $script:newArchive $script:newSums '0.5.2' $dir) + } + finally { Set-Item Function:\Clear-ProoflineUpgradeFiles -Value $originalCleanup } + Require ((Get-ProoflineSha256 (Active 'cleanup-normal')) -ceq $script:newHash) 'Cleanup failure rolled back a verified upgrade.' + Assert-ProoflineRecord (Receipt 'cleanup-normal') '0.5.2' $script:newHash + Require ([IO.File]::Exists((Pending 'cleanup-normal'))) 'Cleanup failure lost retry journal.' + Invoke-ProoflinePendingRepair $dir + Require (-not [IO.File]::Exists((Pending 'cleanup-normal'))) 'Retried cleanup did not clear the journal.' + Require ((Get-ProoflineSha256 (Active 'cleanup-normal')) -ceq $script:newHash) 'Retried cleanup changed the verified executable.' + } + Check 'verified recovered upgrade is never undone by cleanup failure' { + $dir = PrepareOld 'cleanup-recovery' + [void](MakePending $dir) + [IO.File]::WriteAllBytes((Active 'cleanup-recovery'), (Get-ProoflineTarExecutable $script:newArchive)) + $originalCleanup = (Get-Item Function:\Clear-ProoflineUpgradeFiles).ScriptBlock + try { + Set-Item Function:\Clear-ProoflineUpgradeFiles -Value { + throw 'Simulated cleanup deletion failure during recovery.' + } + Invoke-ProoflinePendingRepair $dir + } + finally { Set-Item Function:\Clear-ProoflineUpgradeFiles -Value $originalCleanup } + Assert-ProoflineRecord (Receipt 'cleanup-recovery') '0.5.2' $script:newHash + Require ((Get-ProoflineSha256 (Active 'cleanup-recovery')) -ceq $script:newHash) 'Cleanup failure restored old executable.' + Require ([IO.File]::Exists((Pending 'cleanup-recovery'))) 'Recovery cleanup failure lost its journal.' + Invoke-ProoflinePendingRepair $dir + Require (-not [IO.File]::Exists((Pending 'cleanup-recovery'))) 'Recovery cleanup did not finish on retry.' + } Check 'ambiguous state refuses and preserves evidence' { $dir = PrepareOld 'ambiguous' $paths = MakePending $dir diff --git a/scripts/test_install_user_path_ci_windows.ps1 b/scripts/test_install_user_path_ci_windows.ps1 index c8cf2a0..c89c277 100644 --- a/scripts/test_install_user_path_ci_windows.ps1 +++ b/scripts/test_install_user_path_ci_windows.ps1 @@ -1,15 +1,14 @@ #requires -Version 5.1 <# .SYNOPSIS - Verify current-user PATH registry updates only in a disposable CI runner. + Verify raw current-user PATH persistence and expandable registry types. .DESCRIPTION - Writes a unique temporary Proofline-style PATH entry to the CI runner's - User PATH, checks a fresh PowerShell process can read it, checks idempotence, - and restores the original value in finally. Refuses non-CI execution. - Never run this test on a personal Windows profile. + CI-only test: insert a unique expandable PATH entry, append Proofline path, + assert idempotence and fresh-process visibility, restore exact raw registry + value and value kind. Refuses execution outside GitHub Actions Windows. #> [CmdletBinding()] -param([ValidateSet('Check','ReadUserPath')][string]$Mode = 'Check') +param([ValidateSet('Check', 'ReadUserPath')][string]$Mode = 'Check') Set-StrictMode -Version Latest $ErrorActionPreference = 'Stop' @@ -20,35 +19,65 @@ if ($env:GITHUB_ACTIONS -cne 'true' -or [string]::IsNullOrWhiteSpace($env:RUNNER throw 'Refusing PATH registry test outside GitHub Actions Windows runner.' } +function Get-RawUserPath { + $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $false) + if ($null -eq $key) { return @{ exists = $false; value = ''; kind = 'ExpandString' } } + try { + if ('Path' -notin @($key.GetValueNames())) { + return @{ exists = $false; value = ''; kind = 'ExpandString' } + } + $kind = $key.GetValueKind('Path') + $raw = $key.GetValue('Path', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames) + if ($raw -isnot [string]) { throw 'User PATH has an unexpected registry type.' } + return @{ exists = $true; value = $raw; kind = $kind.ToString() } + } + finally { $key.Dispose() } +} + if ($Mode -eq 'ReadUserPath') { - $freshPath = [Environment]::GetEnvironmentVariable('Path', 'User') - if ($null -eq $freshPath) { $freshPath = '' } - [Console]::Out.Write([Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($freshPath))) + $fresh = Get-RawUserPath + $data = ConvertTo-Json -Compress -InputObject $fresh + [Console]::Out.Write([Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($data))) exit 0 } . (Join-Path (Split-Path -Parent $PSScriptRoot) 'install.ps1') -$original = [Environment]::GetEnvironmentVariable('Path', 'User') +$original = Get-RawUserPath $directory = Join-Path $env:RUNNER_TEMP ('proofline-path-ci-' + [guid]::NewGuid().ToString('N')) -$expected = Get-ProoflineUpdatedUserPath $original $directory -if ($null -eq $expected) { - throw 'Fresh randomized CI directory was already in User PATH.' -} +$token = '%PROOFLINE_CI_TEST_ROOT%\bin' +$seed = if ([string]::IsNullOrEmpty($original.value)) { $token } +else { $original.value.TrimEnd(';') + ';' + $token } +$expected = Get-ProoflineUpdatedUserPath $seed $directory +if ($null -eq $expected) { throw 'Fresh randomized CI directory was already in User PATH.' } [IO.Directory]::CreateDirectory($directory) | Out-Null + +$seeded = $false $ok = $false -$restoreOk = $false +$restored = $false try { + $key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Environment') + try { + $key.SetValue('Path', $seed, [Microsoft.Win32.RegistryValueKind]::ExpandString) + $seeded = $true + } + finally { $key.Dispose() } + Add-ProoflineUserPath $directory - $after = [Environment]::GetEnvironmentVariable('Path', 'User') - if ($after -cne $expected) { - throw 'User PATH did not persist expected entry.' + $after = Get-RawUserPath + if ($after.value -cne $expected -or $after.kind -cne 'ExpandString') { + throw 'Installer did not preserve expandable PATH entry and its type.' + } + if (-not $after.value.Contains($token)) { + throw 'Installer expanded or removed the existing %VARIABLE% token.' } - if ($null -ne (Get-ProoflineUpdatedUserPath $after $directory)) { - throw 'User PATH idempotence function returned a duplicate entry.' + if ($null -ne (Get-ProoflineUpdatedUserPath $after.value $directory)) { + throw 'PATH duplicate-detection unexpectedly added a second entry.' } + Add-ProoflineUserPath $directory - if ([Environment]::GetEnvironmentVariable('Path', 'User') -cne $expected) { - throw 'Second PATH update mutated the registry value.' + $repeat = Get-RawUserPath + if ($repeat.value -cne $expected -or $repeat.kind -cne 'ExpandString') { + throw 'Second PATH update mutated the raw registry value or its type.' } $engine = (Get-Process -Id $PID).Path @@ -56,34 +85,42 @@ try { if ($LASTEXITCODE -ne 0) { throw "Fresh PowerShell process failed to read User PATH: $LASTEXITCODE" } - $fresh = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String(($encoded -join '').Trim())) - if ($fresh -cne $expected) { - throw 'Fresh PowerShell process observed a different User PATH.' + $json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String(($encoded -join '').Trim())) + $fresh = ConvertFrom-Json -InputObject $json + if ($fresh.value -cne $expected -or $fresh.kind -cne 'ExpandString') { + throw 'Fresh process did not see the correct raw User PATH and registry kind.' } - Write-Host 'PASS new PowerShell process sees persistent User PATH entry.' - Write-Host 'PASS repeated PATH update does not duplicate entry.' + + Write-Host 'PASS raw expandable PATH text and REG_EXPAND_SZ preserved.' + Write-Host 'PASS repeated PATH update did not create duplicates.' + Write-Host 'PASS fresh PowerShell process observed persisted User PATH.' $ok = $true } finally { - # Restore only if the test's exact value is still present. In case of an - # unexpected concurrent edit, do not overwrite it with an older snapshot. - $current = [Environment]::GetEnvironmentVariable('Path', 'User') - if ($current -ceq $expected) { - [Environment]::SetEnvironmentVariable('Path', $original, 'User') - $restored = [Environment]::GetEnvironmentVariable('Path', 'User') - $normalizedOriginal = if ($null -eq $original) { '' } else { $original } - $normalizedRestored = if ($null -eq $restored) { '' } else { $restored } - $restoreOk = ($normalizedRestored -ceq $normalizedOriginal) - if (-not $restoreOk) { - Write-Warning 'Could not verify original CI User PATH value was restored.' + if ($seeded) { + $current = Get-RawUserPath + # Restore only the exact test values; do not overwrite other edits. + if ($current.kind -ceq 'ExpandString' -and + $current.value -in @($seed, $expected)) { + $key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Environment') + try { + if ($original.exists) { + $originalKind = [Enum]::Parse([Microsoft.Win32.RegistryValueKind], $original.kind) + $key.SetValue('Path', $original.value, $originalKind) + } + else { $key.DeleteValue('Path', $false) } + } + finally { $key.Dispose() } + Send-ProoflineEnvironmentChange + $check = Get-RawUserPath + $restored = ($check.exists -eq $original.exists -and + $check.value -ceq $original.value -and $check.kind -ceq $original.kind) } - } - else { - Write-Warning 'User PATH changed unexpectedly during CI; refusing to overwrite concurrent edits.' + else { Write-Warning 'User PATH changed concurrently; refusing to overwrite it.' } } Remove-Item -LiteralPath $directory -Recurse -Force -ErrorAction SilentlyContinue } -if (-not $ok -or -not $restoreOk) { - throw 'CI User PATH persistence check failed or did not restore original value.' +if (-not $ok -or -not $restored) { + throw 'CI User PATH persistence failed or original raw PATH was not restored.' } -Write-Host 'CI User PATH persistence and restore: PASS' +Write-Host 'CI User PATH persistence, expandability and restore: PASS' From 6202c617f314dd01a1bd9652b561d7a9fcc72c3f Mon Sep 17 00:00:00 2001 From: Ayan Khan Date: Mon, 23 Nov 2026 12:03:49 +0530 Subject: [PATCH 07/21] test(windows): repair interruption harness and enforce syntax checks --- .github/workflows/windows-installer.yml | 1 + ...test_install_interruption_real_windows.ps1 | 59 ++----------------- scripts/test_install_syntax_windows.ps1 | 26 ++++++++ 3 files changed, 33 insertions(+), 53 deletions(-) create mode 100644 scripts/test_install_syntax_windows.ps1 diff --git a/.github/workflows/windows-installer.yml b/.github/workflows/windows-installer.yml index c3513fe..8707509 100644 --- a/.github/workflows/windows-installer.yml +++ b/.github/workflows/windows-installer.yml @@ -38,6 +38,7 @@ jobs: TEST_ENGINE: ${{ matrix.engine }} run: | foreach ($script in @( + 'scripts/test_install_syntax_windows.ps1', 'scripts/test_install_windows.ps1', 'scripts/test_install_upgrade_windows.ps1', 'scripts/test_install_concurrency_windows.ps1' diff --git a/scripts/test_install_interruption_real_windows.ps1 b/scripts/test_install_interruption_real_windows.ps1 index b0804ab..77a8bd3 100644 --- a/scripts/test_install_interruption_real_windows.ps1 +++ b/scripts/test_install_interruption_real_windows.ps1 @@ -321,59 +321,7 @@ try { Require ($unclaimed.Count -eq 0) 'Fresh-install recovery left a staged executable.' if ($checkpoint -eq 'fresh-partial-stage') { $evidence = @(Get-ChildItem -LiteralPath $directory -Force | - Where-Object { $_.Name -match '^\.proofline-staged-[a-f0-9]{32}\.exe\.incomplete - } - else { - $digest = Assert-Installed $directory $expected[$checkpoint] ($checkpoint -eq 'corrupt-after-switch') - if ($isFresh) { - Require ($null -ne $digest) 'First-install recovery failed to finalize new executable.' - } - elseif ($expected[$checkpoint] -eq '0.5.1') { - Require ($digest -ceq $oldDigest) 'Rollback did not preserve original executable bytes.' - } - else { - Require ($digest -cne $oldDigest) 'Recovery did not install the different new executable.' - } - Write-Host "PASS $checkpoint; fresh process recovered to v$($expected[$checkpoint])." - } - $results += [pscustomobject]@{ - checkpoint = $checkpoint - workerExitCode = $workerExit - recoveryExitCode = $recoverExit - recoveredVersion = $expected[$checkpoint] - recoveredSha256 = $digest - } - } - - Require ([Environment]::GetEnvironmentVariable('Path', 'User') -ceq $pathBefore) 'User PATH was modified.' - $passed = $true -} -catch { - Write-Warning "FAIL real installer interruption test: $($_.Exception.ToString())" -} -finally { - if ($passed -and -not $KeepFiles) { - try { - Remove-Item -LiteralPath $root -Recurse -Force -ErrorAction Stop - $cleanup = $true - } - catch { - Write-Warning "Could not delete disposable test directory: $($_.Exception.Message)" - $passed = $false - } - } -} -Write-Host "Completed $($results.Count) of $($scenarios.Count) interruption scenarios." -if ($passed) { - Write-Host 'Real Windows installer interruption integration: PASS' - if ($KeepFiles) { Write-Host "Retained test evidence at $root" } - else { Write-Host "Cleaned isolated test directory: $cleanup" } -} -else { - Write-Warning "Failure evidence preserved at: $root" - exit 1 -} - }) + Where-Object { $_.Name -match '^\.proofline-staged-[a-f0-9]{32}\.exe\.incomplete$' }) Require ($evidence.Count -eq 1) 'Incomplete first-install bytes were not preserved.' } Write-Host "PASS $checkpoint; fresh process removed interrupted first-install files." @@ -385,6 +333,11 @@ else { } elseif ($expected[$checkpoint] -eq '0.5.1') { Require ($digest -ceq $oldDigest) 'Rollback did not preserve original executable bytes.' + if ($checkpoint -eq 'upgrade-partial-stage') { + $evidence = @(Get-ChildItem -LiteralPath $directory -Force | + Where-Object { $_.Name -match '^\.proofline-staged-[a-f0-9]{32}\.exe\.incomplete$' }) + Require ($evidence.Count -eq 1) 'Incomplete upgrade stage was not preserved.' + } } else { Require ($digest -cne $oldDigest) 'Recovery did not install the different new executable.' diff --git a/scripts/test_install_syntax_windows.ps1 b/scripts/test_install_syntax_windows.ps1 new file mode 100644 index 0000000..2c62592 --- /dev/null +++ b/scripts/test_install_syntax_windows.ps1 @@ -0,0 +1,26 @@ +#requires -Version 5.1 +# Parse installer scripts and tests without executing network/process tests. +[CmdletBinding()] +param() +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' +$root = Split-Path -Parent $PSScriptRoot +$paths = @((Join-Path $root 'install.ps1')) +$paths += @(Get-ChildItem -LiteralPath $PSScriptRoot -File -Filter 'test_install*windows.ps1' | + ForEach-Object { $_.FullName }) +foreach ($path in $paths) { + $tokens = $null + $parseErrors = $null + [void][System.Management.Automation.Language.Parser]::ParseFile( + $path, [ref]$tokens, [ref]$parseErrors) + if ($parseErrors.Count -gt 0) { + foreach ($parseError in $parseErrors) { + Write-Host ("{0}:{1}:{2}: {3}" -f $path, + $parseError.Extent.StartLineNumber, + $parseError.Extent.StartColumnNumber, + $parseError.Message) + } + throw "PowerShell syntax validation failed for $path." + } +} +Write-Host "PowerShell syntax validation: PASS ($($paths.Count) scripts parsed)." From 5c3cf205b847b9034f4cb9623220208cf40fa064 Mon Sep 17 00:00:00 2001 From: Ayan Khan Date: Mon, 23 Nov 2026 12:07:44 +0530 Subject: [PATCH 08/21] test(windows): recognize quarantined partial-stage evidence --- ...test_install_interruption_real_windows.ps1 | 35 ++++++++++++++----- 1 file changed, 26 insertions(+), 9 deletions(-) diff --git a/scripts/test_install_interruption_real_windows.ps1 b/scripts/test_install_interruption_real_windows.ps1 index 77a8bd3..25819ca 100644 --- a/scripts/test_install_interruption_real_windows.ps1 +++ b/scripts/test_install_interruption_real_windows.ps1 @@ -42,7 +42,12 @@ function Assert-Sandbox([string]$Directory) { throw 'Missing disposable test marker; refusing to touch a real installation.' } } -function Assert-Installed([string]$Directory, [string]$Version, [bool]$ExpectDamagedEvidence = $false) { +function Assert-Installed( + [string]$Directory, + [string]$Version, + [bool]$ExpectDamagedEvidence = $false, + [bool]$ExpectIncompleteStageEvidence = $false +) { $exe = Join-Path $Directory 'proofline.exe' $receipt = Join-Path $Directory '.proofline-install.receipt.json' $pending = Join-Path $Directory '.proofline-install.pending.json' @@ -56,9 +61,23 @@ function Assert-Installed([string]$Directory, [string]$Version, [bool]$ExpectDam $output = @(& $exe --version) $exitCode = $LASTEXITCODE Require ($exitCode -eq 0 -and ($output -join '').Trim() -ceq "proofline $Version") "Executable version check failed for $Version." - $debris = @(Get-ChildItem -LiteralPath $Directory -Force | - Where-Object { $_.Name -match '\A\.proofline-(recovery|api-backup|staged|restore)-' }) + # A partial, untrusted stage is deliberately retained as .exe.incomplete + # evidence. This is not an executable eligible for install or recovery. + $incompletePattern = '\A\.proofline-staged-[0-9a-f]{32}\.exe\.incomplete\z' + $files = @(Get-ChildItem -LiteralPath $Directory -Force) + $debris = @($files | Where-Object { + $_.Name -match '\A\.proofline-(recovery|api-backup|staged|restore)-' -and + $_.Name -notmatch $incompletePattern + }) Require ($debris.Count -eq 0) 'A recovery or staging executable remains after successful repair.' + $incomplete = @($files | Where-Object { $_.Name -match $incompletePattern }) + if ($ExpectIncompleteStageEvidence) { + Require ($incomplete.Count -eq 1) 'Exactly one incomplete staged-file evidence copy was expected.' + Require ($incomplete[0].Length -eq 32) 'Incomplete stage does not contain the expected injected prefix.' + } + else { + Require ($incomplete.Count -eq 0) 'Unexpected incomplete staged-file evidence remains.' + } # A corrupted active executable is intentionally kept in a quarantine # path following successful rollback. Don't conceal that evidence merely # to make this test green; verify exactly what was preserved. @@ -327,17 +346,15 @@ try { Write-Host "PASS $checkpoint; fresh process removed interrupted first-install files." } else { - $digest = Assert-Installed $directory $expected[$checkpoint] ($checkpoint -eq 'corrupt-after-switch') + $digest = Assert-Installed $directory $expected[$checkpoint] ` + ($checkpoint -eq 'corrupt-after-switch') ` + ($checkpoint -eq 'upgrade-partial-stage') if ($isFresh) { Require ($null -ne $digest) 'First-install recovery failed to finalize new executable.' } elseif ($expected[$checkpoint] -eq '0.5.1') { Require ($digest -ceq $oldDigest) 'Rollback did not preserve original executable bytes.' - if ($checkpoint -eq 'upgrade-partial-stage') { - $evidence = @(Get-ChildItem -LiteralPath $directory -Force | - Where-Object { $_.Name -match '^\.proofline-staged-[a-f0-9]{32}\.exe\.incomplete$' }) - Require ($evidence.Count -eq 1) 'Incomplete upgrade stage was not preserved.' - } + } else { Require ($digest -cne $oldDigest) 'Recovery did not install the different new executable.' From af6e9e2ec6de51bb7bef4ec74c1460f493165a17 Mon Sep 17 00:00:00 2001 From: Ayan Khan Date: Mon, 23 Nov 2026 12:50:06 +0530 Subject: [PATCH 09/21] fix(windows): roll back upgrades when installed postcheck fails --- install.ps1 | 63 ++++++++++++++++++- ...test_install_interruption_real_windows.ps1 | 20 ++++-- scripts/test_install_upgrade_windows.ps1 | 62 ++++++++++++++++++ 3 files changed, 138 insertions(+), 7 deletions(-) diff --git a/install.ps1 b/install.ps1 index 7da9b98..5114ca2 100644 --- a/install.ps1 +++ b/install.ps1 @@ -502,9 +502,60 @@ function Read-ProoflinePending([string]$Path) { if ($record.oldSha256 -ceq $record.newSha256) { throw 'Pending upgrade has identical old and new digests.' } + $postcheck = $record.PSObject.Properties['postcheck'] + if ($null -ne $postcheck -and $postcheck.Value -cnotin @('checking', 'passed')) { + throw 'Pending upgrade postcheck state is invalid.' + } return $record } +function Set-ProoflineUpgradePostcheck([string]$Pending, [ValidateSet('checking', 'passed')][string]$State) { + # Record the post-replacement validation phase durably before switching. + # A failed or interrupted postcheck must never be finalized by hash alone. + $record = Read-ProoflinePending $Pending + if ($null -eq $record -or $record.schema -ne 2) { + throw 'Cannot update postcheck state without a valid upgrade journal.' + } + $currentProperty = $record.PSObject.Properties['postcheck'] + $current = if ($null -eq $currentProperty) { $null } else { $currentProperty.Value } + if (($State -ceq 'checking' -and $null -ne $current) -or + ($State -ceq 'passed' -and $current -cne 'checking')) { + throw 'Invalid upgrade postcheck state transition.' + } + $record | Add-Member -NotePropertyName postcheck -NotePropertyValue $State -Force + $temporary = $Pending + '.' + [guid]::NewGuid().ToString('N') + '.tmp' + $backup = $Pending + '.' + [guid]::NewGuid().ToString('N') + '.bak' + foreach ($path in @($Pending, $temporary, $backup)) { Assert-ProoflineNoReparse $path } + $verified = $false + try { + $stream = [IO.File]::Open($temporary, [IO.FileMode]::CreateNew, + [IO.FileAccess]::Write, [IO.FileShare]::None) + try { + $json = ConvertTo-Json -Compress -InputObject $record + $bytes = [Text.Encoding]::UTF8.GetBytes($json) + $stream.Write($bytes, 0, $bytes.Length) + $stream.Flush($true) + } + finally { $stream.Dispose() } + [IO.File]::Replace($temporary, $Pending, $backup) + $updated = Read-ProoflinePending $Pending + if ($updated.id -cne $record.id -or $updated.postcheck -cne $State) { + throw 'Could not verify the persisted upgrade postcheck state.' + } + $verified = $true + } + finally { + if ([IO.File]::Exists($temporary)) { + try { [IO.File]::Delete($temporary) } + catch { Write-Warning "Postcheck journal staging file remains at $temporary" } + } + if ($verified -and [IO.File]::Exists($backup)) { + try { [IO.File]::Delete($backup) } + catch { Write-Warning "Previous postcheck journal copy remains at $backup" } + } + } +} + function Get-ProoflineTransactionPaths([string]$Directory, [string]$Id) { # NEVER use a path supplied directly by transaction JSON. if ($Id -cnotmatch '\A[0-9a-f]{32}\z') { throw 'Invalid transaction ID.' } @@ -613,7 +664,12 @@ function Recover-ProoflinePending([string]$Directory) { $activeHash = $null if ([IO.File]::Exists($destination)) { $activeHash = Get-ProoflineSha256 $destination } - if ($activeHash -ceq $record.newSha256) { + # If post-replacement validation was in progress at interruption, or + # explicitly failed, keep the previous verified version. A matching SHA + # does not establish that the new executable can start successfully. + $postcheck = $record.PSObject.Properties['postcheck'] + $postcheckUnverified = ($null -ne $postcheck -and $postcheck.Value -ceq 'checking') + if ($activeHash -ceq $record.newSha256 -and -not $postcheckUnverified) { $finalized = $false try { # A local journal hash is not sufficient authority to execute @@ -861,11 +917,16 @@ function Install-ProoflineArchive( throw 'Could not preserve a verified previous executable; upgrade aborted.' } try { + # Mark validation in-progress BEFORE switching the image. + # A crash after switch but before postcheck will conservatively + # restore the previous executable instead of adopting untested bytes. + Set-ProoflineUpgradePostcheck $pending 'checking' Invoke-ProoflineReplaceWithRetry $stage $destination $paths.api $hash $oldReceipt.sha256 if ((Get-ProoflineSha256 $destination) -cne $hash) { throw 'Upgraded executable digest differs from verified candidate.' } Assert-ProoflineExeVersion $destination $ReleaseVersion + Set-ProoflineUpgradePostcheck $pending 'passed' Write-ProoflineReceipt $receipt $ReleaseVersion $hash try { Clear-ProoflineUpgradeFiles $paths $pending $hash } catch { Write-Warning "Verified upgrade retained; cleanup will be retried: $($_.Exception.Message)" } diff --git a/scripts/test_install_interruption_real_windows.ps1 b/scripts/test_install_interruption_real_windows.ps1 index 25819ca..ee7b26b 100644 --- a/scripts/test_install_interruption_real_windows.ps1 +++ b/scripts/test_install_interruption_real_windows.ps1 @@ -45,7 +45,7 @@ function Assert-Sandbox([string]$Directory) { function Assert-Installed( [string]$Directory, [string]$Version, - [bool]$ExpectDamagedEvidence = $false, + [ValidateSet('none', 'corrupt', 'unchecked')][string]$DamagedEvidence = 'none', [bool]$ExpectIncompleteStageEvidence = $false ) { $exe = Join-Path $Directory 'proofline.exe' @@ -83,9 +83,14 @@ function Assert-Installed( # to make this test green; verify exactly what was preserved. $damaged = @(Get-ChildItem -LiteralPath $Directory -Force | Where-Object { $_.Name -match '\A\.proofline-damaged-[0-9a-f]{32}\.exe\z' }) - if ($ExpectDamagedEvidence) { - Require ($damaged.Count -eq 1) 'Expected one quarantined corrupted executable.' - Require ([IO.File]::ReadAllText($damaged[0].FullName) -ceq 'INTENTIONALLY_CORRUPTED') 'Quarantined contents differ from injected corruption.' + if ($DamagedEvidence -cne 'none') { + Require ($damaged.Count -eq 1) 'Expected one quarantined failed or unverified executable.' + if ($DamagedEvidence -ceq 'corrupt') { + Require ([IO.File]::ReadAllText($damaged[0].FullName) -ceq 'INTENTIONALLY_CORRUPTED') 'Quarantined contents differ from injected corruption.' + } + else { + Require ((Get-FileHash -LiteralPath $damaged[0].FullName -Algorithm SHA256).Hash -cne $hash) 'Rejected new release was not quarantined.' + } } else { Require ($damaged.Count -eq 0) 'Unexpected damaged executable remains.' @@ -232,7 +237,7 @@ $scenarios = @( $expected = @{ 'after-journal' = '0.5.1' 'upgrade-partial-stage' = '0.5.1' - 'after-switch' = '0.5.2' + 'after-switch' = '0.5.1' 'corrupt-after-switch' = '0.5.1' 'after-receipt' = '0.5.2' 'fresh-after-journal' = 'absent' @@ -346,8 +351,11 @@ try { Write-Host "PASS $checkpoint; fresh process removed interrupted first-install files." } else { + $damagedMode = 'none' + if ($checkpoint -eq 'corrupt-after-switch') { $damagedMode = 'corrupt' } + elseif ($checkpoint -eq 'after-switch') { $damagedMode = 'unchecked' } $digest = Assert-Installed $directory $expected[$checkpoint] ` - ($checkpoint -eq 'corrupt-after-switch') ` + $damagedMode ` ($checkpoint -eq 'upgrade-partial-stage') if ($isFresh) { Require ($null -ne $digest) 'First-install recovery failed to finalize new executable.' diff --git a/scripts/test_install_upgrade_windows.ps1 b/scripts/test_install_upgrade_windows.ps1 index b683123..7f74a5e 100644 --- a/scripts/test_install_upgrade_windows.ps1 +++ b/scripts/test_install_upgrade_windows.ps1 @@ -95,8 +95,15 @@ try { # Test-only shadow function: fake PE fixtures are not runnable and must # NEVER be started. Production installer calls the original version checker. $script:smokeCount = 0 + $script:failInstalledPostcheckPath = $null function Assert-ProoflineExeVersion([string]$Path, [string]$Version) { $script:smokeCount++ + if ($null -ne $script:failInstalledPostcheckPath -and + $Path -ieq $script:failInstalledPostcheckPath -and + $Version -ceq '0.5.2') { + # Only the installed copy fails, never the staged verified image. + throw 'Simulated installed executable postcheck failure.' + } $digest = Get-ProoflineSha256 $Path $expected = switch ($Version) { '0.5.1' { $script:oldHash; break } @@ -165,6 +172,61 @@ try { Require (-not [IO.File]::Exists((Pending 'normal'))) 'Upgrade journal remains after success.' Require (@(Get-ChildItem -LiteralPath $dir -Force -Filter '.proofline-recovery*').Count -eq 0) 'Old backup not cleaned.' } + Check 'failed installed-executable postcheck restores verified old release' { + $dir = PrepareOld 'failed-postcheck' + $script:failInstalledPostcheckPath = Active 'failed-postcheck' + try { + Must-Throw { [void](Install-ProoflineArchive $script:newArchive $script:newSums '0.5.2' $dir) } + } + finally { $script:failInstalledPostcheckPath = $null } + Require ((Get-ProoflineSha256 (Active 'failed-postcheck')) -ceq $script:oldHash) 'Failed postcheck left the rejected new image active.' + Assert-ProoflineRecord (Receipt 'failed-postcheck') '0.5.1' $script:oldHash + Require (-not [IO.File]::Exists((Pending 'failed-postcheck'))) 'Successful rollback did not clear its journal.' + $damaged = @(Get-ChildItem -LiteralPath $dir -Force | + Where-Object { $_.Name -match '\A\.proofline-damaged-[0-9a-f]{32}\.exe\z' }) + Require ($damaged.Count -eq 1) 'Failed replacement was not quarantined.' + Require ((Get-ProoflineSha256 $damaged[0].FullName) -ceq $script:newHash) 'Quarantined bytes do not match rejected release.' + $debris = @(Get-ChildItem -LiteralPath $dir -Force | + Where-Object { $_.Name -match '\A\.proofline-(recovery|api-backup|staged)-' }) + Require ($debris.Count -eq 0) 'Successful rollback left executable transaction files.' + [void](Install-ProoflineArchive $script:newArchive $script:newSums '0.5.2' $dir) + Assert-ProoflineRecord (Receipt 'failed-postcheck') '0.5.2' $script:newHash + } + Check 'interrupted in-progress postcheck restores old release' { + $dir = PrepareOld 'checking-interrupted' + [void](MakePending $dir) + Set-ProoflineUpgradePostcheck (Pending 'checking-interrupted') 'checking' + [IO.File]::WriteAllBytes((Active 'checking-interrupted'), (Get-ProoflineTarExecutable $script:newArchive)) + Invoke-ProoflinePendingRepair $dir + Require ((Get-ProoflineSha256 (Active 'checking-interrupted')) -ceq $script:oldHash) 'Interrupted postcheck was incorrectly treated as verified.' + Assert-ProoflineRecord (Receipt 'checking-interrupted') '0.5.1' $script:oldHash + Require (-not [IO.File]::Exists((Pending 'checking-interrupted'))) 'Interrupted postcheck rollback left its journal.' + } + Check 'missing rollback backup never silently adopts rejected executable' { + $dir = PrepareOld 'failed-postcheck-no-backup' + $paths = MakePending $dir + Set-ProoflineUpgradePostcheck (Pending 'failed-postcheck-no-backup') 'checking' + [IO.File]::WriteAllBytes((Active 'failed-postcheck-no-backup'), (Get-ProoflineTarExecutable $script:newArchive)) + [IO.File]::Delete($paths.old) + Must-Throw { Invoke-ProoflinePendingRepair $dir } + Must-Throw { Invoke-ProoflinePendingRepair $dir } + Require ([IO.File]::Exists((Pending 'failed-postcheck-no-backup'))) 'Missing-backup failure lost its pending journal.' + $record = Read-ProoflinePending (Pending 'failed-postcheck-no-backup') + Require ($record.postcheck -ceq 'checking') 'A failed postcheck lost its durable rejection marker.' + Assert-ProoflineRecord (Receipt 'failed-postcheck-no-backup') '0.5.1' $script:oldHash + Require ((Get-ProoflineSha256 (Active 'failed-postcheck-no-backup')) -ceq $script:newHash) 'Recovery modified a file without a verified rollback source.' + } + Check 'completed postcheck permits interrupted receipt finalization' { + $dir = PrepareOld 'passed-before-receipt' + [void](MakePending $dir) + Set-ProoflineUpgradePostcheck (Pending 'passed-before-receipt') 'checking' + [IO.File]::WriteAllBytes((Active 'passed-before-receipt'), (Get-ProoflineTarExecutable $script:newArchive)) + Set-ProoflineUpgradePostcheck (Pending 'passed-before-receipt') 'passed' + Invoke-ProoflinePendingRepair $dir + Require ((Get-ProoflineSha256 (Active 'passed-before-receipt')) -ceq $script:newHash) 'Recovery rolled back an explicitly passed postcheck.' + Assert-ProoflineRecord (Receipt 'passed-before-receipt') '0.5.2' $script:newHash + Require (-not [IO.File]::Exists((Pending 'passed-before-receipt'))) 'Passed-postcheck recovery left its journal.' + } Check 'receipt replacement preserves and cleans up its backup' { $dir = PrepareOld 'receipt-backup' $receiptPath = Receipt 'receipt-backup' From 08129b5400b3f8d55a84cb0e521ade41ff0922c7 Mon Sep 17 00:00:00 2001 From: Ayan Khan Date: Mon, 23 Nov 2026 21:50:21 +0530 Subject: [PATCH 10/21] fix(windows): address Proofline installer recovery review findings --- .github/workflows/windows-installer.yml | 29 ++++++ install.ps1 | 76 +++++++++++---- scripts/test_install_concurrency_windows.ps1 | 22 +++-- ...test_install_interruption_real_windows.ps1 | 54 +++++++++-- scripts/test_install_upgrade_real_windows.ps1 | 29 +++++- scripts/test_install_upgrade_windows.ps1 | 97 +++++++++++++++++-- scripts/test_install_user_path_ci_windows.ps1 | 10 +- scripts/test_install_windows.ps1 | 27 +++++- 8 files changed, 291 insertions(+), 53 deletions(-) diff --git a/.github/workflows/windows-installer.yml b/.github/workflows/windows-installer.yml index 8707509..1121124 100644 --- a/.github/workflows/windows-installer.yml +++ b/.github/workflows/windows-installer.yml @@ -55,3 +55,32 @@ jobs: run: | & $env:TEST_ENGINE -NoProfile -NonInteractive -File scripts/test_install_user_path_ci_windows.ps1 if ($LASTEXITCODE -ne 0) { throw "User PATH persistence test failed: $LASTEXITCODE" } + + real-release-integration: + name: Real Windows install and interruption recovery (${{ matrix.engine }}) + runs-on: windows-2025 + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + engine: ['powershell.exe', 'pwsh.exe'] + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Install and upgrade pinned official releases + shell: pwsh + env: + TEST_ENGINE: ${{ matrix.engine }} + run: | + & $env:TEST_ENGINE -NoProfile -NonInteractive -File scripts/test_install_upgrade_real_windows.ps1 + if ($LASTEXITCODE -ne 0) { throw "Real Windows upgrade test failed: $LASTEXITCODE" } + + - name: Recover from ten real process-termination checkpoints + shell: pwsh + env: + TEST_ENGINE: ${{ matrix.engine }} + run: | + & $env:TEST_ENGINE -NoProfile -NonInteractive -File scripts/test_install_interruption_real_windows.ps1 + if ($LASTEXITCODE -ne 0) { throw "Real interruption recovery failed: $LASTEXITCODE" } diff --git a/install.ps1 b/install.ps1 index 5114ca2..ccfa365 100644 --- a/install.ps1 +++ b/install.ps1 @@ -486,8 +486,14 @@ function Read-ProoflinePending([string]$Path) { throw 'Pending first-install digest is invalid.' } [void](Assert-ProoflineVersion $record.version) - if ($record.schema -eq 3 -and $record.id -cnotmatch '\A[0-9a-f]{32}\z') { - throw 'Pending first-install stage ID is invalid.' + if ($record.schema -eq 3) { + if ($record.id -cnotmatch '\A[0-9a-f]{32}\z') { + throw 'Pending first-install stage ID is invalid.' + } + $firstPostcheck = $record.PSObject.Properties['postcheck'] + if ($null -ne $firstPostcheck -and $firstPostcheck.Value -cnotin @('checking', 'passed')) { + throw 'Pending first-install postcheck state is invalid.' + } } return $record } @@ -509,18 +515,18 @@ function Read-ProoflinePending([string]$Path) { return $record } -function Set-ProoflineUpgradePostcheck([string]$Pending, [ValidateSet('checking', 'passed')][string]$State) { - # Record the post-replacement validation phase durably before switching. +function Set-ProoflinePendingPostcheck([string]$Pending, [ValidateSet('checking', 'passed')][string]$State) { + # Record validation progress durably before publishing an installed image. # A failed or interrupted postcheck must never be finalized by hash alone. $record = Read-ProoflinePending $Pending - if ($null -eq $record -or $record.schema -ne 2) { - throw 'Cannot update postcheck state without a valid upgrade journal.' + if ($null -eq $record -or $record.schema -notin @(2, 3)) { + throw 'Cannot update postcheck state without a valid installation journal.' } $currentProperty = $record.PSObject.Properties['postcheck'] $current = if ($null -eq $currentProperty) { $null } else { $currentProperty.Value } - if (($State -ceq 'checking' -and $null -ne $current) -or + if (($State -ceq 'checking' -and ($record.schema -ne 2 -or $null -ne $current)) -or ($State -ceq 'passed' -and $current -cne 'checking')) { - throw 'Invalid upgrade postcheck state transition.' + throw 'Invalid installation postcheck state transition.' } $record | Add-Member -NotePropertyName postcheck -NotePropertyValue $State -Force $temporary = $Pending + '.' + [guid]::NewGuid().ToString('N') + '.tmp' @@ -645,8 +651,32 @@ function Recover-ProoflinePending([string]$Directory) { if ((Get-ProoflineSha256 $destination) -cne $record.sha256) { throw 'Interrupted first install has an unrecognized executable; preserving journal.' } - # Do not execute an existing image whose hash is trusted only against - # mutable local metadata. Smoke tests run on verified download stages. + # A matching digest is not proof that the installed executable can + # start. Never execute a pre-existing image verified only against local + # mutable journal metadata. Require a persisted successful postcheck. + $firstStatus = $record.PSObject.Properties['postcheck'] + $passedFirst = ($null -ne $firstStatus -and $firstStatus.Value -ceq 'passed') + if (-not $passedFirst -and $record.schema -eq 1 -and [IO.File]::Exists($receipt)) { + # Legacy first-install journals had no postcheck state. A valid + # matching receipt is evidence the old installer completed its + # installed-path check before writing that receipt. + Assert-ProoflineRecord $receipt $record.version $record.sha256 + $passedFirst = $true + } + if (-not $passedFirst) { + if ([IO.File]::Exists($receipt)) { + throw 'An unverified first install has a receipt; preserving transaction evidence.' + } + $evidenceId = if ($record.schema -eq 3) { $record.id } else { [guid]::NewGuid().ToString('N') } + $evidence = [IO.Path]::Combine($Directory, ".proofline-unverified-first-$evidenceId.exe") + Assert-ProoflineNoReparse $evidence + if ([IO.File]::Exists($evidence)) { throw 'First-install quarantine path exists; preserving recovery journal.' } + [IO.File]::Move($destination, $evidence) + if ($null -ne $stage -and [IO.File]::Exists($stage)) { [IO.File]::Delete($stage) } + [IO.File]::Delete($pending) + Write-Warning "Unverified first-install executable quarantined at $evidence; retry installation." + return + } if ([IO.File]::Exists($receipt)) { Assert-ProoflineRecord $receipt $record.version $record.sha256 } @@ -655,7 +685,7 @@ function Recover-ProoflinePending([string]$Directory) { [IO.File]::Delete($stage) } [IO.File]::Delete($pending) - Write-Host 'Recovered interrupted first installation.' + Write-Host 'Recovered verified first installation.' return } @@ -668,8 +698,8 @@ function Recover-ProoflinePending([string]$Directory) { # explicitly failed, keep the previous verified version. A matching SHA # does not establish that the new executable can start successfully. $postcheck = $record.PSObject.Properties['postcheck'] - $postcheckUnverified = ($null -ne $postcheck -and $postcheck.Value -ceq 'checking') - if ($activeHash -ceq $record.newSha256 -and -not $postcheckUnverified) { + $postcheckVerified = ($null -ne $postcheck -and $postcheck.Value -ceq 'passed') + if ($activeHash -ceq $record.newSha256 -and $postcheckVerified) { $finalized = $false try { # A local journal hash is not sufficient authority to execute @@ -700,10 +730,16 @@ function Recover-ProoflinePending([string]$Directory) { $source = $null foreach ($candidate in @($paths.old, $paths.api)) { - if ([IO.File]::Exists($candidate) -and - (Get-ProoflineSha256 $candidate) -ceq $record.oldSha256) { - $source = $candidate - break + if (-not [IO.File]::Exists($candidate)) { continue } + try { + if ((Get-ProoflineSha256 $candidate) -ceq $record.oldSha256) { + $source = $candidate + break + } + } + catch { + # An unreadable primary copy must not mask a valid secondary. + Write-Warning "Cannot read recovery candidate $candidate; checking the next verified copy: $($_.Exception.Message)" } } if ($null -eq $source) { @@ -872,6 +908,7 @@ function Install-ProoflineArchive( id = $id version = $ReleaseVersion sha256 = $hash + postcheck = 'checking' }) } else { @@ -904,6 +941,7 @@ function Install-ProoflineArchive( throw 'Installed executable digest differs after relocation.' } Assert-ProoflineExeVersion $destination $ReleaseVersion + Set-ProoflinePendingPostcheck $pending 'passed' Write-ProoflineReceipt $receipt $ReleaseVersion $hash [IO.File]::Delete($pending) return $destination @@ -920,13 +958,13 @@ function Install-ProoflineArchive( # Mark validation in-progress BEFORE switching the image. # A crash after switch but before postcheck will conservatively # restore the previous executable instead of adopting untested bytes. - Set-ProoflineUpgradePostcheck $pending 'checking' + Set-ProoflinePendingPostcheck $pending 'checking' Invoke-ProoflineReplaceWithRetry $stage $destination $paths.api $hash $oldReceipt.sha256 if ((Get-ProoflineSha256 $destination) -cne $hash) { throw 'Upgraded executable digest differs from verified candidate.' } Assert-ProoflineExeVersion $destination $ReleaseVersion - Set-ProoflineUpgradePostcheck $pending 'passed' + Set-ProoflinePendingPostcheck $pending 'passed' Write-ProoflineReceipt $receipt $ReleaseVersion $hash try { Clear-ProoflineUpgradeFiles $paths $pending $hash } catch { Write-Warning "Verified upgrade retained; cleanup will be retried: $($_.Exception.Message)" } diff --git a/scripts/test_install_concurrency_windows.ps1 b/scripts/test_install_concurrency_windows.ps1 index 98b788d..c05ea79 100644 --- a/scripts/test_install_concurrency_windows.ps1 +++ b/scripts/test_install_concurrency_windows.ps1 @@ -12,6 +12,7 @@ param( [ValidateSet('Test', 'Hold')][string]$Mode = 'Test', [string]$CaseDir, + [string]$HoldToken, [string]$Python = 'python' ) @@ -25,10 +26,14 @@ if ($Mode -eq 'Hold') { if ([string]::IsNullOrWhiteSpace($CaseDir)) { throw 'Holder needs CaseDir.' } $folder = [IO.Path]::GetFullPath($CaseDir) $marker = Join-Path $folder '.proofline-test-only' - if (-not [IO.File]::Exists($marker) -or - [IO.File]::ReadAllText($marker) -cne 'DISPOSABLE_LOCK_TEST') { - throw 'Refusing to hold lock without disposable test marker.' + if ($HoldToken -cnotmatch '\A[0-9a-f]{32}\z' -or + -not [IO.File]::Exists($marker) -or + [IO.File]::ReadAllText($marker) -cne "DISPOSABLE_LOCK_TEST:$HoldToken") { + throw 'Refusing to hold lock without fresh matching test token.' } + # Consume the unique challenge before opening the lock. A retained marker + # cannot authorize another unrelated invocation later. + [IO.File]::Delete($marker) $lock = Join-Path $folder '.proofline-install.lock' $ready = Join-Path $folder '.holder-ready' $release = Join-Path $folder '.holder-release' @@ -52,7 +57,8 @@ $root = Join-Path ([IO.Path]::GetTempPath()) ('proofline-concurrent-' + [guid]:: [IO.Directory]::CreateDirectory($root) | Out-Null $bin = Join-Path $root 'bin' [IO.Directory]::CreateDirectory($bin) | Out-Null -[IO.File]::WriteAllText((Join-Path $bin '.proofline-test-only'), 'DISPOSABLE_LOCK_TEST') +$holdToken = [guid]::NewGuid().ToString('N') +[IO.File]::WriteAllText((Join-Path $bin '.proofline-test-only'), "DISPOSABLE_LOCK_TEST:$holdToken") $holder = $null $passed = $false $holderReady = Join-Path $bin '.holder-ready' @@ -97,7 +103,7 @@ try { $powershell = (Get-Process -Id $PID).Path $args = '-NoProfile -NonInteractive -File "' + $PSCommandPath + - '" -Mode Hold -CaseDir "' + $bin + '"' + '" -Mode Hold -CaseDir "' + $bin + '" -HoldToken "' + $holdToken + '"' $start = [Diagnostics.ProcessStartInfo]::new() $start.FileName = $powershell $start.Arguments = $args @@ -116,6 +122,8 @@ try { Assert-Condition (-not $holder.HasExited) 'Lock holder exited before contested upgrade.' Write-Host 'Separate PowerShell process holds installer lock.' + $stagesBefore = @(Get-ChildItem -LiteralPath $bin -Force -Filter '.proofline-staged-*.exe' | ForEach-Object FullName) + Assert-Condition ($stagesBefore.Count -eq 0) 'Test fixture unexpectedly contains staged executables before refusal.' $refused = $false try { [void](Install-ProoflineArchive $newArchive $newManifest '0.5.2' $bin) @@ -130,7 +138,9 @@ try { Assert-Condition ((Get-ProoflineSha256 $active) -ceq $script:oldHash) 'Concurrent attempt changed active executable.' Assert-ProoflineRecord $receipt '0.5.1' $script:oldHash Assert-Condition (-not [IO.File]::Exists((Join-Path $bin '.proofline-install.pending.json'))) 'Concurrent attempt left a journal.' - Write-Host 'PASS competing installer refused; old executable, receipt and journal unchanged.' + $stagesAfter = @(Get-ChildItem -LiteralPath $bin -Force -Filter '.proofline-staged-*.exe' | ForEach-Object FullName) + Assert-Condition ($stagesAfter.Count -eq $stagesBefore.Count) 'Competing installer staged executable bytes before acquiring lock.' + Write-Host 'PASS competing installer refused; old executable, receipt, stage and journal unchanged.' [IO.File]::WriteAllText($holderRelease, 'RELEASE') if (-not $holder.WaitForExit(10000)) { throw 'Holder did not exit after release.' } diff --git a/scripts/test_install_interruption_real_windows.ps1 b/scripts/test_install_interruption_real_windows.ps1 index ee7b26b..bf39a5c 100644 --- a/scripts/test_install_interruption_real_windows.ps1 +++ b/scripts/test_install_interruption_real_windows.ps1 @@ -42,6 +42,30 @@ function Assert-Sandbox([string]$Directory) { throw 'Missing disposable test marker; refusing to touch a real installation.' } } +function Assert-TestExecutableVersion([string]$Exe, [string]$Version) { + $start = [Diagnostics.ProcessStartInfo]::new() + $start.FileName = $Exe + $start.Arguments = '--version' + $start.UseShellExecute = $false + $start.CreateNoWindow = $true + $start.RedirectStandardOutput = $true + $start.RedirectStandardError = $true + $child = [Diagnostics.Process]::new() + $child.StartInfo = $start + try { + if (-not $child.Start()) { throw "Could not start recovered version $Version." } + $stdout = $child.StandardOutput.ReadToEndAsync() + $stderr = $child.StandardError.ReadToEndAsync() + if (-not $child.WaitForExit(15000)) { + try { $child.Kill() } catch { } + [void]$child.WaitForExit(5000) + throw "Version check timed out for recovered $Version." + } + Require ($child.ExitCode -eq 0 -and $stdout.GetAwaiter().GetResult().Trim() -ceq "proofline $Version" -and + $stderr.GetAwaiter().GetResult().Trim() -eq '') "Executable version check failed for $Version." + } + finally { $child.Dispose() } +} function Assert-Installed( [string]$Directory, [string]$Version, @@ -58,9 +82,8 @@ function Assert-Installed( $hash = (Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash Require ($data.schema -eq 1 -and $data.version -ceq $Version -and $data.sha256 -ceq $hash) 'Receipt does not match installed executable.' - $output = @(& $exe --version) - $exitCode = $LASTEXITCODE - Require ($exitCode -eq 0 -and ($output -join '').Trim() -ceq "proofline $Version") "Executable version check failed for $Version." + Require ($hash -ceq $script:pinnedExeHashes[$Version]) 'Recovered executable does not match pinned official fixture bytes.' + Assert-TestExecutableVersion $exe $Version # A partial, untrusted stage is deliberately retained as .exe.incomplete # evidence. This is not an executable eligible for install or recovery. $incompletePattern = '\A\.proofline-staged-[0-9a-f]{32}\.exe\.incomplete\z' @@ -89,7 +112,7 @@ function Assert-Installed( Require ([IO.File]::ReadAllText($damaged[0].FullName) -ceq 'INTENTIONALLY_CORRUPTED') 'Quarantined contents differ from injected corruption.' } else { - Require ((Get-FileHash -LiteralPath $damaged[0].FullName -Algorithm SHA256).Hash -cne $hash) 'Rejected new release was not quarantined.' + Require ((Get-FileHash -LiteralPath $damaged[0].FullName -Algorithm SHA256).Hash -ceq $script:pinnedExeHashes['0.5.2']) 'Quarantine does not match the pinned rejected new release.' } } else { @@ -243,7 +266,7 @@ $expected = @{ 'fresh-after-journal' = 'absent' 'fresh-partial-stage' = 'absent' 'fresh-after-stage' = 'absent' - 'fresh-after-move' = '0.5.1' + 'fresh-after-move' = 'absent' 'fresh-after-receipt' = '0.5.1' } $engine = (Get-Process -Id $PID).Path @@ -254,6 +277,7 @@ $cleanup = $false try { . $originalInstaller + $script:pinnedExeHashes = @{} foreach ($pair in @(@('0.5.1', 'old'), @('0.5.2', 'new'))) { $v = $pair[0] $kind = $pair[1] @@ -262,7 +286,10 @@ try { $archive = Get-ProoflineOfficialBytes "$prefix/$script:ProoflineArchiveName" $script:MaxArchiveBytes $manifest = Get-ProoflineOfficialBytes "$prefix/SHA256SUMS" 8192 Assert-ProoflineChecksum $archive $manifest - [void](Get-ProoflineTarExecutable $archive) + $verifiedBinary = Get-ProoflineTarExecutable $archive + $sha = [Security.Cryptography.SHA256]::Create() + try { $script:pinnedExeHashes[$v] = [BitConverter]::ToString($sha.ComputeHash($verifiedBinary)).Replace('-', '') } + finally { $sha.Dispose() } [IO.File]::WriteAllBytes((Join-Path $cache "$kind.tar.gz"), $archive) [IO.File]::WriteAllBytes((Join-Path $cache "$kind-SHA256SUMS"), $manifest) } @@ -312,16 +339,16 @@ try { Require ($null -eq $activeDigest) 'Fresh install published executable before intended checkpoint.' } elseif ($checkpoint -in @('fresh-after-move', 'fresh-after-receipt')) { - Require ($null -ne $activeDigest) 'Fresh install did not publish executable before checkpoint.' + Require ($activeDigest -ceq $script:pinnedExeHashes['0.5.1']) 'Fresh install did not publish the pinned executable before checkpoint.' } elseif ($checkpoint -in @('after-journal', 'upgrade-partial-stage')) { Require ($activeDigest -ceq $oldDigest) 'Journal checkpoint unexpectedly changed old executable.' } elseif ($checkpoint -eq 'corrupt-after-switch') { - Require ($activeDigest -cne $oldDigest) 'Corruption checkpoint did not change the active file.' + Require ([IO.File]::ReadAllText($activeFile) -ceq 'INTENTIONALLY_CORRUPTED') 'Corruption checkpoint did not install injected corruption.' } else { - Require ($activeDigest -cne $oldDigest) 'Replacement checkpoint did not change executable.' + Require ($activeDigest -ceq $script:pinnedExeHashes['0.5.2']) 'Replacement checkpoint did not publish pinned new executable.' } $recoverStdout = Join-Path $root ("recovery-$checkpoint.stdout.txt") @@ -348,7 +375,14 @@ try { Where-Object { $_.Name -match '^\.proofline-staged-[a-f0-9]{32}\.exe\.incomplete$' }) Require ($evidence.Count -eq 1) 'Incomplete first-install bytes were not preserved.' } - Write-Host "PASS $checkpoint; fresh process removed interrupted first-install files." + $unverified = @(Get-ChildItem -LiteralPath $directory -Force | + Where-Object { $_.Name -match '^\.proofline-unverified-first-[a-f0-9]{32}\.exe$' }) + if ($checkpoint -eq 'fresh-after-move') { + Require ($unverified.Count -eq 1) 'Unverified published first-install executable was not quarantined.' + Require ((Get-FileHash -LiteralPath $unverified[0].FullName -Algorithm SHA256).Hash -ceq $script:pinnedExeHashes['0.5.1']) 'First-install quarantine does not match pinned executable.' + } + else { Require ($unverified.Count -eq 0) 'Unexpected first-install quarantine remains.' } + Write-Host "PASS $checkpoint; fresh process recovered without accepting an unverified executable." } else { $damagedMode = 'none' diff --git a/scripts/test_install_upgrade_real_windows.ps1 b/scripts/test_install_upgrade_real_windows.ps1 index d3c3430..2bafc05 100644 --- a/scripts/test_install_upgrade_real_windows.ps1 +++ b/scripts/test_install_upgrade_real_windows.ps1 @@ -56,11 +56,32 @@ function Check-Release([string]$Version) { if ($debris.Count -ne 0) { throw "Unexpected staged or recovery artifacts remain after $Version." } - $output = @(& $exe '--version') - $exitCode = $LASTEXITCODE - if ($exitCode -ne 0 -or ($output -join [Environment]::NewLine).Trim() -cne "proofline $Version") { - throw "Executable version check failed for $Version (exit $exitCode)." + # Always bound real executable execution, including stalled version probes. + $start = [Diagnostics.ProcessStartInfo]::new() + $start.FileName = $exe + $start.Arguments = '--version' + $start.UseShellExecute = $false + $start.CreateNoWindow = $true + $start.RedirectStandardOutput = $true + $start.RedirectStandardError = $true + $child = [Diagnostics.Process]::new() + $child.StartInfo = $start + try { + if (-not $child.Start()) { throw "Could not launch official Proofline $Version." } + $outTask = $child.StandardOutput.ReadToEndAsync() + $errTask = $child.StandardError.ReadToEndAsync() + if (-not $child.WaitForExit(15000)) { + try { $child.Kill() } catch { } + [void]$child.WaitForExit(5000) + throw "Executable version check timed out for $Version after 15 seconds." + } + $output = $outTask.GetAwaiter().GetResult().Trim() + $errors = $errTask.GetAwaiter().GetResult().Trim() + if ($child.ExitCode -ne 0 -or $output -cne "proofline $Version" -or $errors -ne '') { + throw "Executable version check failed for $Version (exit $($child.ExitCode), output '$output', stderr '$errors')." + } } + finally { $child.Dispose() } return [pscustomobject]@{ BinarySha256 = $hash ReceiptSha256 = $receiptHash diff --git a/scripts/test_install_upgrade_windows.ps1 b/scripts/test_install_upgrade_windows.ps1 index 7f74a5e..7655a2d 100644 --- a/scripts/test_install_upgrade_windows.ps1 +++ b/scripts/test_install_upgrade_windows.ps1 @@ -96,11 +96,12 @@ try { # NEVER be started. Production installer calls the original version checker. $script:smokeCount = 0 $script:failInstalledPostcheckPath = $null + $script:failInstalledPostcheckVersion = '0.5.2' function Assert-ProoflineExeVersion([string]$Path, [string]$Version) { $script:smokeCount++ if ($null -ne $script:failInstalledPostcheckPath -and $Path -ieq $script:failInstalledPostcheckPath -and - $Version -ceq '0.5.2') { + $Version -ceq $script:failInstalledPostcheckVersion) { # Only the installed copy fails, never the staged verified image. throw 'Simulated installed executable postcheck failure.' } @@ -150,19 +151,38 @@ try { [void](Install-ProoflineArchive $script:oldArchive $script:oldSums '0.5.1' $dir) Assert-ProoflineRecord (Join-Path $dir '.proofline-install.receipt.json') '0.5.1' $script:oldHash } - Check 'interrupted fresh install finalizes verified published executable' { + Check 'first install with no passed postcheck quarantines instead of finalizing' { $dir = Join-Path $root 'fresh-published' [IO.Directory]::CreateDirectory($dir) | Out-Null $id = [guid]::NewGuid().ToString('N') [IO.File]::WriteAllBytes((Join-Path $dir 'proofline.exe'), (Get-ProoflineTarExecutable $script:oldArchive)) $journal = Join-Path $dir '.proofline-install.pending.json' Write-ProoflineAtomicRecord $journal (ConvertTo-Json -Compress -InputObject ([ordered]@{ - schema = 3; id = $id; version = '0.5.1'; sha256 = $script:oldHash + schema = 3; id = $id; version = '0.5.1'; sha256 = $script:oldHash; postcheck = 'checking' + })) + Invoke-ProoflinePendingRepair $dir + Require (-not [IO.File]::Exists($journal)) 'Quarantine did not clear the first-install journal.' + Require (-not [IO.File]::Exists((Join-Path $dir 'proofline.exe'))) 'Unverified first-install image became active.' + Require (-not [IO.File]::Exists((Join-Path $dir '.proofline-install.receipt.json'))) 'Unverified first install received a receipt.' + $evidence = Join-Path $dir ".proofline-unverified-first-$id.exe" + Require ((Get-ProoflineSha256 $evidence) -ceq $script:oldHash) 'First-install quarantine lost the rejected candidate.' + [void](Install-ProoflineArchive $script:oldArchive $script:oldSums '0.5.1' $dir) + Assert-ProoflineRecord (Join-Path $dir '.proofline-install.receipt.json') '0.5.1' $script:oldHash + } + Check 'passed first-install postcheck allows finalization after crash' { + $dir = Join-Path $root 'fresh-passed' + [IO.Directory]::CreateDirectory($dir) | Out-Null + $id = [guid]::NewGuid().ToString('N') + [IO.File]::WriteAllBytes((Join-Path $dir 'proofline.exe'), (Get-ProoflineTarExecutable $script:oldArchive)) + $journal = Join-Path $dir '.proofline-install.pending.json' + Write-ProoflineAtomicRecord $journal (ConvertTo-Json -Compress -InputObject ([ordered]@{ + schema = 3; id = $id; version = '0.5.1'; sha256 = $script:oldHash; postcheck = 'checking' })) + Set-ProoflinePendingPostcheck $journal 'passed' Invoke-ProoflinePendingRepair $dir - Require (-not [IO.File]::Exists($journal)) 'Journal not cleared after successful receipt recovery.' + Require (-not [IO.File]::Exists($journal)) 'Passed first-install journal remains.' Assert-ProoflineRecord (Join-Path $dir '.proofline-install.receipt.json') '0.5.1' $script:oldHash - Require ((Get-ProoflineSha256 (Join-Path $dir 'proofline.exe')) -ceq $script:oldHash) 'First-install recovery modified verified bytes.' + Require ((Get-ProoflineSha256 (Join-Path $dir 'proofline.exe')) -ceq $script:oldHash) 'Verified first-install image was lost.' } Check 'clean upgrade from previous verified install' { $dir = PrepareOld 'normal' @@ -195,7 +215,7 @@ try { Check 'interrupted in-progress postcheck restores old release' { $dir = PrepareOld 'checking-interrupted' [void](MakePending $dir) - Set-ProoflineUpgradePostcheck (Pending 'checking-interrupted') 'checking' + Set-ProoflinePendingPostcheck (Pending 'checking-interrupted') 'checking' [IO.File]::WriteAllBytes((Active 'checking-interrupted'), (Get-ProoflineTarExecutable $script:newArchive)) Invoke-ProoflinePendingRepair $dir Require ((Get-ProoflineSha256 (Active 'checking-interrupted')) -ceq $script:oldHash) 'Interrupted postcheck was incorrectly treated as verified.' @@ -205,7 +225,7 @@ try { Check 'missing rollback backup never silently adopts rejected executable' { $dir = PrepareOld 'failed-postcheck-no-backup' $paths = MakePending $dir - Set-ProoflineUpgradePostcheck (Pending 'failed-postcheck-no-backup') 'checking' + Set-ProoflinePendingPostcheck (Pending 'failed-postcheck-no-backup') 'checking' [IO.File]::WriteAllBytes((Active 'failed-postcheck-no-backup'), (Get-ProoflineTarExecutable $script:newArchive)) [IO.File]::Delete($paths.old) Must-Throw { Invoke-ProoflinePendingRepair $dir } @@ -219,14 +239,69 @@ try { Check 'completed postcheck permits interrupted receipt finalization' { $dir = PrepareOld 'passed-before-receipt' [void](MakePending $dir) - Set-ProoflineUpgradePostcheck (Pending 'passed-before-receipt') 'checking' + Set-ProoflinePendingPostcheck (Pending 'passed-before-receipt') 'checking' [IO.File]::WriteAllBytes((Active 'passed-before-receipt'), (Get-ProoflineTarExecutable $script:newArchive)) - Set-ProoflineUpgradePostcheck (Pending 'passed-before-receipt') 'passed' + Set-ProoflinePendingPostcheck (Pending 'passed-before-receipt') 'passed' Invoke-ProoflinePendingRepair $dir Require ((Get-ProoflineSha256 (Active 'passed-before-receipt')) -ceq $script:newHash) 'Recovery rolled back an explicitly passed postcheck.' Assert-ProoflineRecord (Receipt 'passed-before-receipt') '0.5.2' $script:newHash Require (-not [IO.File]::Exists((Pending 'passed-before-receipt'))) 'Passed-postcheck recovery left its journal.' } + Check 'failed first-install postcheck quarantines on next recovery' { + $dir = Join-Path $root 'fresh-failed-installed-check' + $script:failInstalledPostcheckPath = Join-Path $dir 'proofline.exe' + $script:failInstalledPostcheckVersion = '0.5.1' + try { + Must-Throw { [void](Install-ProoflineArchive $script:oldArchive $script:oldSums '0.5.1' $dir) } + } + finally { + $script:failInstalledPostcheckPath = $null + $script:failInstalledPostcheckVersion = '0.5.2' + } + Require ([IO.File]::Exists((Pending 'fresh-failed-installed-check'))) 'Failed first install did not retain journal.' + Invoke-ProoflinePendingRepair $dir + Require (-not [IO.File]::Exists((Active 'fresh-failed-installed-check'))) 'Rejected first-install executable remained active.' + $evidence = @(Get-ChildItem -LiteralPath $dir -Filter '.proofline-unverified-first-*.exe') + Require ($evidence.Count -eq 1) 'Rejected first-install image was not quarantined.' + Require ((Get-ProoflineSha256 $evidence[0].FullName) -ceq $script:oldHash) 'Quarantined first-install bytes changed.' + [void](Install-ProoflineArchive $script:oldArchive $script:oldSums '0.5.1' $dir) + Assert-ProoflineRecord (Receipt 'fresh-failed-installed-check') '0.5.1' $script:oldHash + } + Check 'upgrade without postcheck marker rolls back matching new image' { + $dir = PrepareOld 'legacy-unchecked-upgrade' + [void](MakePending $dir) + [IO.File]::WriteAllBytes((Active 'legacy-unchecked-upgrade'), (Get-ProoflineTarExecutable $script:newArchive)) + Invoke-ProoflinePendingRepair $dir + Require ((Get-ProoflineSha256 (Active 'legacy-unchecked-upgrade')) -ceq $script:oldHash) 'Markerless upgrade was finalized by hash alone.' + Assert-ProoflineRecord (Receipt 'legacy-unchecked-upgrade') '0.5.1' $script:oldHash + Require (-not [IO.File]::Exists((Pending 'legacy-unchecked-upgrade'))) 'Rollback journal remains.' + } + Check 'unreadable primary backup falls back to verified secondary copy' { + $dir = PrepareOld 'backup-fallback' + $paths = MakePending $dir + [IO.File]::Copy($paths.old, $paths.api, $false) + [IO.File]::WriteAllBytes((Active 'backup-fallback'), (Get-ProoflineTarExecutable $script:newArchive)) + Set-ProoflinePendingPostcheck (Pending 'backup-fallback') 'checking' + $originalDigest = (Get-Item Function:\Get-ProoflineSha256).ScriptBlock + $script:blockedBackup = $paths.old + $script:realDigest = $originalDigest + try { + Set-Item Function:\Get-ProoflineSha256 -Value { + param([string]$Path) + if ($Path -ieq $script:blockedBackup) { throw [IO.IOException]::new('Simulated unreadable primary backup.') } + & $script:realDigest $Path + } + Invoke-ProoflinePendingRepair $dir + } + finally { + Set-Item Function:\Get-ProoflineSha256 -Value $originalDigest + $script:blockedBackup = $null + $script:realDigest = $null + } + Require ((Get-ProoflineSha256 (Active 'backup-fallback')) -ceq $script:oldHash) 'Verified secondary backup did not restore old release.' + Assert-ProoflineRecord (Receipt 'backup-fallback') '0.5.1' $script:oldHash + Require (-not [IO.File]::Exists((Pending 'backup-fallback'))) 'Fallback recovery left pending journal.' + } Check 'receipt replacement preserves and cleans up its backup' { $dir = PrepareOld 'receipt-backup' $receiptPath = Receipt 'receipt-backup' @@ -280,7 +355,9 @@ try { Check 'new active detected and finalized after restart' { $dir = PrepareOld 'finalize' $paths = MakePending $dir + Set-ProoflinePendingPostcheck (Pending 'finalize') 'checking' [IO.File]::WriteAllBytes((Active 'finalize'), (Get-ProoflineTarExecutable $script:newArchive)) + Set-ProoflinePendingPostcheck (Pending 'finalize') 'passed' $before = $script:smokeCount Invoke-ProoflinePendingRepair $dir Require ($script:smokeCount -eq $before) 'Recovery executed pre-existing executable verified only by local journal.' @@ -329,7 +406,9 @@ try { Check 'verified recovered upgrade is never undone by cleanup failure' { $dir = PrepareOld 'cleanup-recovery' [void](MakePending $dir) + Set-ProoflinePendingPostcheck (Pending 'cleanup-recovery') 'checking' [IO.File]::WriteAllBytes((Active 'cleanup-recovery'), (Get-ProoflineTarExecutable $script:newArchive)) + Set-ProoflinePendingPostcheck (Pending 'cleanup-recovery') 'passed' $originalCleanup = (Get-Item Function:\Clear-ProoflineUpgradeFiles).ScriptBlock try { Set-Item Function:\Clear-ProoflineUpgradeFiles -Value { diff --git a/scripts/test_install_user_path_ci_windows.ps1 b/scripts/test_install_user_path_ci_windows.ps1 index c89c277..b0708f4 100644 --- a/scripts/test_install_user_path_ci_windows.ps1 +++ b/scripts/test_install_user_path_ci_windows.ps1 @@ -47,8 +47,10 @@ $directory = Join-Path $env:RUNNER_TEMP ('proofline-path-ci-' + [guid]::NewGuid( $token = '%PROOFLINE_CI_TEST_ROOT%\bin' $seed = if ([string]::IsNullOrEmpty($original.value)) { $token } else { $original.value.TrimEnd(';') + ';' + $token } -$expected = Get-ProoflineUpdatedUserPath $seed $directory -if ($null -eq $expected) { throw 'Fresh randomized CI directory was already in User PATH.' } +# Independent oracle: do not use the same helper under test to construct +# expected output, or truncation before $token could go undetected. +$expected = $seed.TrimEnd(';') + ';' + $directory +if ($seed -match [regex]::Escape($directory)) { throw 'Fresh randomized CI directory was already in User PATH.' } [IO.Directory]::CreateDirectory($directory) | Out-Null $seeded = $false @@ -100,8 +102,10 @@ finally { if ($seeded) { $current = Get-RawUserPath # Restore only the exact test values; do not overwrite other edits. - if ($current.kind -ceq 'ExpandString' -and + if ($current.kind -in @('ExpandString', 'String') -and $current.value -in @($seed, $expected)) { + # Even if a registry-kind regression occurred, restore the exact + # seeded text instead of leaving the disposable PATH entries behind. $key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Environment') try { if ($original.exists) { diff --git a/scripts/test_install_windows.ps1 b/scripts/test_install_windows.ps1 index 5cc59fe..366b08d 100644 --- a/scripts/test_install_windows.ps1 +++ b/scripts/test_install_windows.ps1 @@ -45,7 +45,19 @@ try { Test-Case 'valid official-style tar and multi-target digest manifest' { Assert-ProoflineChecksum $valid $sums $exe = Get-ProoflineTarExecutable $valid - if ($exe.Length -ne 1024) { throw 'Unexpected fixture executable length.' } + # Verify every payload byte, not just the archive layout and length. + $expected = [byte[]]::new(1024) + $expected[0] = 77 + $expected[1] = 90 + $expected[0x3c] = 0x80 + $expected[0x80] = 80 + $expected[0x81] = 69 + if ($exe.Length -ne $expected.Length) { throw 'Unexpected fixture executable length.' } + for ($i = 0; $i -lt $expected.Length; $i++) { + if ($exe[$i] -ne $expected[$i]) { + throw "Extracted executable payload differs from independent fixture at byte $i." + } + } } foreach ($name in @('SHA256SUMS-mismatch', 'SHA256SUMS-duplicate', 'SHA256SUMS-missing', 'SHA256SUMS-malformed')) { @@ -58,7 +70,18 @@ try { 'symlink.tar.gz', 'not-pe.tar.gz')) { $archive = Bytes $name Test-Case "archive rejects $name" { - Must-Throw { Get-ProoflineTarExecutable $archive } + if ($name -eq 'symlink.tar.gz') { + $rejectedForType = $false + try { [void](Get-ProoflineTarExecutable $archive) } + catch { + if ($_.Exception.Message -notlike '*exactly one regular proofline.exe*') { + throw "Symlink rejected for the wrong reason: $($_.Exception.Message)" + } + $rejectedForType = $true + } + if (-not $rejectedForType) { throw 'Symlink tar member was accepted.' } + } + else { Must-Throw { Get-ProoflineTarExecutable $archive } } } } Test-Case 'checksum rejects modified archive bytes' { From e5d1e411a5282ab124079a0b5191020800adc50a Mon Sep 17 00:00:00 2001 From: Ayan Khan Date: Mon, 23 Nov 2026 22:19:08 +0530 Subject: [PATCH 11/21] fix(windows): harden recovery and CI against Proofline review findings --- .github/workflows/windows-installer.yml | 30 +++- README.md | 4 +- install.ps1 | 129 +++++++++++++----- .../generate_windows_installer_fixtures.py | 11 +- scripts/test_install_concurrency_windows.ps1 | 21 ++- ...test_install_interruption_real_windows.ps1 | 124 ++++++++++++++--- scripts/test_install_upgrade_real_windows.ps1 | 81 +++++++---- scripts/test_install_upgrade_windows.ps1 | 82 ++++++++++- scripts/test_install_user_path_ci_windows.ps1 | 33 ++++- scripts/test_install_windows.ps1 | 26 ++++ 10 files changed, 437 insertions(+), 104 deletions(-) diff --git a/.github/workflows/windows-installer.yml b/.github/workflows/windows-installer.yml index 1121124..9f89503 100644 --- a/.github/workflows/windows-installer.yml +++ b/.github/workflows/windows-installer.yml @@ -48,13 +48,6 @@ jobs: if ($LASTEXITCODE -ne 0) { throw "$script failed with exit code $LASTEXITCODE" } } - - name: Verify User PATH persistence on disposable CI runner - shell: pwsh - env: - TEST_ENGINE: ${{ matrix.engine }} - run: | - & $env:TEST_ENGINE -NoProfile -NonInteractive -File scripts/test_install_user_path_ci_windows.ps1 - if ($LASTEXITCODE -ne 0) { throw "User PATH persistence test failed: $LASTEXITCODE" } real-release-integration: name: Real Windows install and interruption recovery (${{ matrix.engine }}) @@ -84,3 +77,26 @@ jobs: run: | & $env:TEST_ENGINE -NoProfile -NonInteractive -File scripts/test_install_interruption_real_windows.ps1 if ($LASTEXITCODE -ne 0) { throw "Real interruption recovery failed: $LASTEXITCODE" } + + isolated-user-path: + name: Default installer PATH persistence (${{ matrix.engine }}) + # A separate GitHub-hosted VM provides a disposable Windows user profile. + # No other job or test in this workflow shares its HKCU registry hive. + runs-on: windows-2025 + timeout-minutes: 15 + strategy: + fail-fast: false + matrix: + engine: ['powershell.exe', 'pwsh.exe'] + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Check full installer default user PATH integration in isolated profile + shell: pwsh + env: + TEST_ENGINE: ${{ matrix.engine }} + run: | + & $env:TEST_ENGINE -NoProfile -NonInteractive -File scripts/test_install_user_path_ci_windows.ps1 + if ($LASTEXITCODE -ne 0) { throw "Isolated installer PATH test failed: $LASTEXITCODE" } diff --git a/README.md b/README.md index 7416aa6..aa30296 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ On **Windows x64**, run the PowerShell installer from a checked-out copy of this powershell.exe -NoProfile -File .\install.ps1 ``` -It downloads the official release and `SHA256SUMS` from `https://proofline.sh`, validates the archive, verifies `proofline.exe --version`, and installs for the **current user** in `%LOCALAPPDATA%\Programs\Proofline\bin` without administrator rights. By default it appends that directory to the user PATH while preserving expandable registry entries. Open a new terminal and run `Get-Command proofline -All` to check which executable has precedence. If an older copy is found first, run the new executable using its absolute path (for example, `& "$env:LOCALAPPDATA\Programs\Proofline\bin\proofline.exe" login`) or correct the stale PATH entry. The installer does not handle login or credentials. +It downloads the official release and `SHA256SUMS` from `https://proofline.sh`, validates the archive, verifies `proofline.exe --version`, and installs for the **current user** in `%LOCALAPPDATA%\Programs\Proofline\bin` without administrator rights. By default it attempts to append that directory to the user PATH while preserving expandable registry entries; this is best-effort and may warn if registry permissions or concurrent changes prevent an update. If warned, open **Windows Environment Variables → User variables → Path → Edit → New** and add `%LOCALAPPDATA%\Programs\Proofline\bin` manually (or your custom `-InstallDir`). Open a new terminal and run `Get-Command proofline -All` to check which executable has precedence. If an older copy is found first, run the new executable using its absolute path (for example, `& "$env:LOCALAPPDATA\Programs\Proofline\bin\proofline.exe" login`) or correct the stale PATH entry. The installer does not handle login or credentials. To pin a version or install in a disposable folder without updating PATH: @@ -44,7 +44,7 @@ powershell.exe -NoProfile -File .\scripts\test_install_upgrade_real_windows.ps1 powershell.exe -NoProfile -File .\scripts\test_install_interruption_real_windows.ps1 ``` -Run the same commands with `pwsh.exe` to verify PowerShell 7. The interruption test additionally covers hard termination during partially written stages. The last two tests download pinned official releases; all test installations use disposable paths and do not modify User PATH. The separate `scripts/test_install_user_path_ci_windows.ps1` test intentionally runs **only on GitHub Actions Windows runners**, where it verifies registry persistence and restores the original User PATH value. +Run the same commands with `pwsh.exe` to verify PowerShell 7. The interruption test covers 12 hard-termination checkpoints, including checkpoints before receipt publication. The last two tests download pinned official releases; their installations use disposable directories and do not modify User PATH. The separate `scripts/test_install_user_path_ci_windows.ps1` test intentionally runs **only on disposable GitHub-hosted Windows runners** in its own isolated CI job, where it exercises the default PATH update and restores the prior raw registry value in `finally`. On Linux, coding agents that omit `DBUS_SESSION_BUS_ADDRESS` and `XDG_RUNTIME_DIR` can still use the stored sign-in when the standard `/run/user//bus` socket diff --git a/install.ps1 b/install.ps1 index ccfa365..e053e79 100644 --- a/install.ps1 +++ b/install.ps1 @@ -268,12 +268,18 @@ function Assert-ProoflineNoReparse([string]$Path) { } } -function Get-ProoflineUpdatedUserPath([string]$Current, [string]$Directory) { +function Get-ProoflineUpdatedUserPath( + [string]$Current, [string]$Directory, + [Microsoft.Win32.RegistryValueKind]$Kind = [Microsoft.Win32.RegistryValueKind]::ExpandString +) { if ($null -eq $Current) { $Current = '' } $normalized = $Directory.TrimEnd([char[]]@('\', '/')) foreach ($entry in ($Current -split ';')) { - $expanded = [Environment]::ExpandEnvironmentVariables($entry.Trim()) - if ($expanded.TrimEnd([char[]]@('\', '/')) -ieq $normalized) { + $candidate = $entry.Trim() + if ($Kind -eq [Microsoft.Win32.RegistryValueKind]::ExpandString) { + $candidate = [Environment]::ExpandEnvironmentVariables($candidate) + } + if ($candidate.TrimEnd([char[]]@('\', '/')) -ieq $normalized) { return $null # already present; no registry write needed } } @@ -329,7 +335,7 @@ public static class ProoflineEnvironmentNotifier { function Add-ProoflineUserPath([string]$Directory) { $previous = Get-ProoflineUserPathRecord - $result = Get-ProoflineUpdatedUserPath $previous.value $Directory + $result = Get-ProoflineUpdatedUserPath $previous.value $Directory $previous.kind if ($null -eq $result) { Write-Host 'User PATH already contains the Proofline directory.' return @@ -368,9 +374,19 @@ function Get-ProoflineSha256([string]$Path) { return (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash } +function Assert-ProoflineVersionResult( + [int]$ExitCode, [string]$Stdout, [string]$Stderr, [string]$Version +) { + $actual = $Stdout.Trim() + $errors = $Stderr.Trim() + if ($ExitCode -ne 0 -or $actual -cne "proofline $Version" -or $errors -ne '') { + throw "Executable version check failed (expected 'proofline $Version', exit $ExitCode, got '$actual' '$errors')." + } +} + function Assert-ProoflineExeVersion([string]$Path, [string]$Version) { - # Run only a checksum-verified release, never a raw unverified download. - # Process isolation and timeout avoid hanging this installer indefinitely. + # Run only checksum-verified images; bound both process termination + # and redirected output collection so descendants cannot hang the check. $startInfo = [Diagnostics.ProcessStartInfo]::new() $startInfo.FileName = $Path $startInfo.Arguments = '--version' @@ -380,17 +396,21 @@ function Assert-ProoflineExeVersion([string]$Path, [string]$Version) { $startInfo.RedirectStandardError = $true $process = [Diagnostics.Process]::new() $process.StartInfo = $startInfo + $clock = [Diagnostics.Stopwatch]::StartNew() try { if (-not $process.Start()) { throw 'Candidate executable did not start.' } + $outTask = $process.StandardOutput.ReadToEndAsync() + $errTask = $process.StandardError.ReadToEndAsync() if (-not $process.WaitForExit(15000)) { try { $process.Kill() } catch { } + [void]$process.WaitForExit(5000) throw 'Candidate executable did not exit within 15 seconds.' } - $actual = $process.StandardOutput.ReadToEnd().Trim() - $stderr = $process.StandardError.ReadToEnd().Trim() - if ($process.ExitCode -ne 0 -or $actual -cne "proofline $Version" -or $stderr -ne '') { - throw "Executable version check failed (expected 'proofline $Version', exit $($process.ExitCode), got '$actual' '$stderr')." + $remaining = [int][Math]::Max(0, 15000 - $clock.ElapsedMilliseconds) + if (-not [Threading.Tasks.Task]::WaitAll([Threading.Tasks.Task[]]@($outTask, $errTask), $remaining)) { + throw 'Candidate version check exited but output streams remained open beyond 15 seconds.' } + Assert-ProoflineVersionResult $process.ExitCode ($outTask.GetAwaiter().GetResult()) ($errTask.GetAwaiter().GetResult()) $Version } finally { $process.Dispose() } } @@ -530,8 +550,9 @@ function Set-ProoflinePendingPostcheck([string]$Pending, [ValidateSet('checking' } $record | Add-Member -NotePropertyName postcheck -NotePropertyValue $State -Force $temporary = $Pending + '.' + [guid]::NewGuid().ToString('N') + '.tmp' - $backup = $Pending + '.' + [guid]::NewGuid().ToString('N') + '.bak' + $backup = $Pending + '.postcheck.bak' foreach ($path in @($Pending, $temporary, $backup)) { Assert-ProoflineNoReparse $path } + if ([IO.File]::Exists($backup)) { throw 'A previous postcheck journal backup needs recovery before another update.' } $verified = $false try { $stream = [IO.File]::Open($temporary, [IO.FileMode]::CreateNew, @@ -562,6 +583,28 @@ function Set-ProoflinePendingPostcheck([string]$Pending, [ValidateSet('checking' } } +function Restore-ProoflinePendingBackup([string]$Pending) { + # Caller holds the installer lock. File.Replace may have moved the only + # readable journal into its backup when the process was interrupted. + $backup = $Pending + '.postcheck.bak' + foreach ($path in @($Pending, $backup)) { Assert-ProoflineNoReparse $path } + if (-not [IO.File]::Exists($backup)) { return } + if ([IO.File]::Exists($Pending)) { + [void](Read-ProoflinePending $Pending) + [IO.File]::Delete($backup) + } + else { + [void](Read-ProoflinePending $backup) + [IO.File]::Move($backup, $Pending) + } +} + +function Clear-ProoflineJournalBackup([string]$Pending) { + $backup = $Pending + '.postcheck.bak' + Assert-ProoflineNoReparse $backup + if ([IO.File]::Exists($backup)) { [IO.File]::Delete($backup) } +} + function Get-ProoflineTransactionPaths([string]$Directory, [string]$Id) { # NEVER use a path supplied directly by transaction JSON. if ($Id -cnotmatch '\A[0-9a-f]{32}\z') { throw 'Invalid transaction ID.' } @@ -599,6 +642,7 @@ function Clear-ProoflineUpgradeFiles( foreach ($key in @('old', 'api', 'stage')) { if ([IO.File]::Exists($Paths[$key])) { [IO.File]::Delete($Paths[$key]) } } + Clear-ProoflineJournalBackup $Pending [IO.File]::Delete($Pending) # delete journal LAST } @@ -607,6 +651,7 @@ function Recover-ProoflinePending([string]$Directory) { $destination = [IO.Path]::Combine($Directory, 'proofline.exe') $receipt = [IO.Path]::Combine($Directory, '.proofline-install.receipt.json') $pending = [IO.Path]::Combine($Directory, '.proofline-install.pending.json') + Restore-ProoflinePendingBackup $pending $record = Read-ProoflinePending $pending if ($null -eq $record) { return } foreach ($path in @($destination, $receipt, $pending)) { @@ -641,6 +686,7 @@ function Recover-ProoflinePending([string]$Directory) { } else { [IO.File]::Delete($stage) } } + Clear-ProoflineJournalBackup $pending [IO.File]::Delete($pending) return } @@ -673,6 +719,7 @@ function Recover-ProoflinePending([string]$Directory) { if ([IO.File]::Exists($evidence)) { throw 'First-install quarantine path exists; preserving recovery journal.' } [IO.File]::Move($destination, $evidence) if ($null -ne $stage -and [IO.File]::Exists($stage)) { [IO.File]::Delete($stage) } + Clear-ProoflineJournalBackup $pending [IO.File]::Delete($pending) Write-Warning "Unverified first-install executable quarantined at $evidence; retry installation." return @@ -684,6 +731,7 @@ function Recover-ProoflinePending([string]$Directory) { if ($null -ne $stage -and [IO.File]::Exists($stage)) { [IO.File]::Delete($stage) } + Clear-ProoflineJournalBackup $pending [IO.File]::Delete($pending) Write-Host 'Recovered verified first installation.' return @@ -700,24 +748,29 @@ function Recover-ProoflinePending([string]$Directory) { $postcheck = $record.PSObject.Properties['postcheck'] $postcheckVerified = ($null -ne $postcheck -and $postcheck.Value -ceq 'passed') if ($activeHash -ceq $record.newSha256 -and $postcheckVerified) { - $finalized = $false + # A passed postcheck is a commit decision. If receipt replacement is + # blocked, retain the new executable and journal; NEVER fall through + # to the old-version rollback path. try { - # A local journal hash is not sufficient authority to execute - # an existing image. Validate bytes and write the matching receipt. - Write-ProoflineReceipt $receipt $record.newVersion $record.newSha256 - $finalized = $true + if ([IO.File]::Exists($receipt)) { + $current = Read-ProoflineReceipt $receipt + if ($current.version -cne $record.newVersion -or + $current.sha256 -cne $record.newSha256) { + Write-ProoflineReceipt $receipt $record.newVersion $record.newSha256 + } + } + else { Write-ProoflineReceipt $receipt $record.newVersion $record.newSha256 } + Assert-ProoflineRecord $receipt $record.newVersion $record.newSha256 } catch { - Write-Warning "New executable is present but cannot be finalized: $($_.Exception.Message)" - } - if ($finalized) { - # Cleaning old files is not part of the successful version switch. - # Preserve the new executable and journal if cleanup must be retried. - try { Clear-ProoflineUpgradeFiles $paths $pending $record.newSha256 } - catch { Write-Warning "Upgrade finalized; cleanup will be retried: $($_.Exception.Message)" } - Write-Host "Finalized interrupted Proofline $($record.newVersion) upgrade." - return + throw "Postcheck passed but the receipt cannot be finalized; new executable and journal retained: $($_.Exception.Message)" } + # A matching receipt may already be open with deny-delete sharing: + # do not attempt to replace it again merely to retry cleanup. + try { Clear-ProoflineUpgradeFiles $paths $pending $record.newSha256 } + catch { Write-Warning "Upgrade finalized; cleanup will be retried: $($_.Exception.Message)" } + Write-Host "Finalized interrupted Proofline $($record.newVersion) upgrade." + return } if ($activeHash -ceq $record.oldSha256) { @@ -783,7 +836,8 @@ function Invoke-ProoflinePendingRepair([string]$Directory) { Assert-ProoflinePathTree $directory if (-not [IO.Directory]::Exists($directory)) { return } $pending = [IO.Path]::Combine($directory, '.proofline-install.pending.json') - if (-not [IO.File]::Exists($pending)) { return } + if (-not [IO.File]::Exists($pending) -and + -not [IO.File]::Exists($pending + '.postcheck.bak')) { return } $lock = [IO.Path]::Combine($directory, '.proofline-install.lock') Assert-ProoflineNoReparse $lock $handle = [IO.File]::Open($lock, [IO.FileMode]::OpenOrCreate, @@ -875,7 +929,7 @@ function Install-ProoflineArchive( catch { throw "Another installer may be running, or the lock file is unavailable: $($_.Exception.Message)" } try { # Handle a concurrent previous installer that stopped during download. - if ([IO.File]::Exists($pending)) { + if ([IO.File]::Exists($pending) -or [IO.File]::Exists($pending + '.postcheck.bak')) { Recover-ProoflinePending $directory } $hasDestination = [IO.File]::Exists($destination) @@ -893,7 +947,7 @@ function Install-ProoflineArchive( # receipt contains a matching hash. Only verified downloads run. if ($oldReceipt.version -ceq $ReleaseVersion -and $oldReceipt.sha256 -ceq $hash) { - Write-Host "Proofline $ReleaseVersion is already installed; nothing was changed." + Write-Host "Proofline $ReleaseVersion executable and receipt already match; PATH handling still follows this invocation's options." return $destination } } @@ -940,11 +994,20 @@ function Install-ProoflineArchive( if ((Get-ProoflineSha256 $destination) -cne $hash) { throw 'Installed executable digest differs after relocation.' } - Assert-ProoflineExeVersion $destination $ReleaseVersion - Set-ProoflinePendingPostcheck $pending 'passed' - Write-ProoflineReceipt $receipt $ReleaseVersion $hash - [IO.File]::Delete($pending) - return $destination + try { + Assert-ProoflineExeVersion $destination $ReleaseVersion + Set-ProoflinePendingPostcheck $pending 'passed' + Write-ProoflineReceipt $receipt $ReleaseVersion $hash + Clear-ProoflineJournalBackup $pending + [IO.File]::Delete($pending) + return $destination + } + catch { + $originalError = $_.Exception.Message + try { Recover-ProoflinePending $directory } + catch { throw "First-install validation failed ($originalError); recovery failed: $($_.Exception.Message)" } + throw "First installation failed ($originalError); recovery completed or retained evidence." + } } # Upgrade: independently preserve the previous verified executable. diff --git a/scripts/generate_windows_installer_fixtures.py b/scripts/generate_windows_installer_fixtures.py index e9b2305..429be50 100644 --- a/scripts/generate_windows_installer_fixtures.py +++ b/scripts/generate_windows_installer_fixtures.py @@ -58,6 +58,11 @@ def main(destination: Path) -> None: (destination / "not-pe.tar.gz").write_bytes( pack(("proofline.exe", b"not a PE" * 128, tarfile.REGTYPE)) ) + wrong_signature = bytearray(binary) + wrong_signature[0x80:0x84] = b"NOPE" + (destination / "bad-pe-signature.tar.gz").write_bytes( + pack(("proofline.exe", bytes(wrong_signature), tarfile.REGTYPE)) + ) name = "proofline-x86_64-pc-windows-msvc.tar.gz" sha = hashlib.sha256(base).hexdigest() other = hashlib.sha256(b"other archive bytes").hexdigest() @@ -75,14 +80,16 @@ def main(destination: Path) -> None: f"{other} proofline-x86_64-unknown-linux-musl.tar.gz\n", encoding="ascii" ) (destination / "SHA256SUMS-malformed").write_text( - f"not-a-hash {name}\n", encoding="ascii" + f"{sha} {name}\nnot-a-hash another-release.tar.gz\n", encoding="ascii" ) # The release's archive format is deterministic; assert our fixture name, # tar type and content are correct before it reaches PowerShell tests. with tarfile.open(fileobj=io.BytesIO(base), mode="r:gz") as tar: names = tar.getnames() assert names == ["proofline.exe"], names - assert tar.extractfile(tar.getmembers()[0]).read() == binary + member = tar.getmembers()[0] + assert member.type == tarfile.REGTYPE, member.type + assert tar.extractfile(member).read() == binary print(f"Created offline fixture files in {destination}") diff --git a/scripts/test_install_concurrency_windows.ps1 b/scripts/test_install_concurrency_windows.ps1 index c05ea79..c3a12ee 100644 --- a/scripts/test_install_concurrency_windows.ps1 +++ b/scripts/test_install_concurrency_windows.ps1 @@ -26,14 +26,21 @@ if ($Mode -eq 'Hold') { if ([string]::IsNullOrWhiteSpace($CaseDir)) { throw 'Holder needs CaseDir.' } $folder = [IO.Path]::GetFullPath($CaseDir) $marker = Join-Path $folder '.proofline-test-only' - if ($HoldToken -cnotmatch '\A[0-9a-f]{32}\z' -or - -not [IO.File]::Exists($marker) -or - [IO.File]::ReadAllText($marker) -cne "DISPOSABLE_LOCK_TEST:$HoldToken") { - throw 'Refusing to hold lock without fresh matching test token.' + if ($HoldToken -cnotmatch '\A[0-9a-f]{32}\z') { + throw 'Refusing to hold lock without a valid test token.' } - # Consume the unique challenge before opening the lock. A retained marker - # cannot authorize another unrelated invocation later. - [IO.File]::Delete($marker) + # The rename is an atomic, exclusive claim: only one competing holder + # can move this single-use marker. Validate after claiming it. + $claimed = Join-Path $folder ('.proofline-test-claimed-' + $HoldToken) + if ([IO.File]::Exists($claimed)) { throw 'Test marker was already claimed.' } + try { [IO.File]::Move($marker, $claimed) } + catch { throw 'Refusing to hold lock: fresh disposable test marker is unavailable or already claimed.' } + try { + if ([IO.File]::ReadAllText($claimed) -cne "DISPOSABLE_LOCK_TEST:$HoldToken") { + throw 'Refusing to hold lock: claimed marker has unexpected contents.' + } + } + finally { [IO.File]::Delete($claimed) } $lock = Join-Path $folder '.proofline-install.lock' $ready = Join-Path $folder '.holder-ready' $release = Join-Path $folder '.holder-release' diff --git a/scripts/test_install_interruption_real_windows.ps1 b/scripts/test_install_interruption_real_windows.ps1 index bf39a5c..5fb219c 100644 --- a/scripts/test_install_interruption_real_windows.ps1 +++ b/scripts/test_install_interruption_real_windows.ps1 @@ -18,6 +18,8 @@ param( [string]$CaseDir, [string]$InstallerCopy, [string]$FixtureDir, + [string]$DriverRoot, + [string]$TestToken, [switch]$KeepFiles ) @@ -34,12 +36,39 @@ function Require([bool]$Ok, [string]$Message) { function Get-TestBytes([string]$Directory, [string]$Name) { return ,([IO.File]::ReadAllBytes((Join-Path $Directory $Name))) } -function Assert-Sandbox([string]$Directory) { - if ([string]::IsNullOrWhiteSpace($Directory)) { throw 'Missing test directory.' } - $marker = Join-Path ([IO.Path]::GetFullPath($Directory)) '.proofline-test-only' - if (-not [IO.File]::Exists($marker) -or - [IO.File]::ReadAllText($marker) -cne 'DISPOSABLE_REAL_UPGRADE_TEST') { - throw 'Missing disposable test marker; refusing to touch a real installation.' +function Assert-Sandbox([string]$Directory, [string]$RunRoot, [string]$Token) { + if ([string]::IsNullOrWhiteSpace($Directory) -or + [string]::IsNullOrWhiteSpace($RunRoot) -or + $Token -cnotmatch '\A[0-9a-f]{32}\z') { + throw 'Missing validated interruption-test sandbox identity.' + } + $temp = [IO.Path]::GetFullPath([IO.Path]::GetTempPath()).TrimEnd([char]'\') + $root = [IO.Path]::GetFullPath($RunRoot).TrimEnd([char]'\') + $case = [IO.Path]::GetFullPath($Directory).TrimEnd([char]'\') + if ([IO.Path]::GetDirectoryName($root) -ine $temp -or + [IO.Path]::GetFileName($root) -cnotmatch '\Aproofline-real-interruption-[0-9a-f]{32}\z' -or + [IO.Path]::GetDirectoryName($case) -ine $root -or + [IO.Path]::GetFileName($case) -notin @( + 'after-journal', 'upgrade-partial-stage', 'after-switch', 'corrupt-after-switch', + 'after-upgrade-passed', 'after-receipt', 'fresh-after-journal', + 'fresh-partial-stage', 'fresh-after-stage', 'fresh-after-move', + 'fresh-after-passed', 'fresh-after-receipt' + )) { + throw 'Interruption test child refused a directory outside the driver-created TEMP sandbox.' + } + foreach ($path in @($root, $case)) { + if (-not [IO.Directory]::Exists($path) -or + (([IO.File]::GetAttributes($path) -band [IO.FileAttributes]::ReparsePoint) -ne 0)) { + throw 'Interruption test sandbox directory does not exist or is a reparse point.' + } + } + $runMarker = Join-Path $root '.proofline-run-token' + $caseMarker = Join-Path $case '.proofline-test-only' + if (-not [IO.File]::Exists($runMarker) -or + [IO.File]::ReadAllText($runMarker) -cne $Token -or + -not [IO.File]::Exists($caseMarker) -or + [IO.File]::ReadAllText($caseMarker) -cne "DISPOSABLE_REAL_UPGRADE_TEST:$Token") { + throw 'Interruption test driver identity does not match the disposable sandbox.' } } function Assert-TestExecutableVersion([string]$Exe, [string]$Version) { @@ -56,11 +85,16 @@ function Assert-TestExecutableVersion([string]$Exe, [string]$Version) { if (-not $child.Start()) { throw "Could not start recovered version $Version." } $stdout = $child.StandardOutput.ReadToEndAsync() $stderr = $child.StandardError.ReadToEndAsync() + $clock = [Diagnostics.Stopwatch]::StartNew() if (-not $child.WaitForExit(15000)) { try { $child.Kill() } catch { } [void]$child.WaitForExit(5000) throw "Version check timed out for recovered $Version." } + $remaining = [int][Math]::Max(0, 15000 - $clock.ElapsedMilliseconds) + if (-not [Threading.Tasks.Task]::WaitAll([Threading.Tasks.Task[]]@($stdout, $stderr), $remaining)) { + throw "Recovered $Version version probe exited but output pipes remained open after deadline." + } Require ($child.ExitCode -eq 0 -and $stdout.GetAwaiter().GetResult().Trim() -ceq "proofline $Version" -and $stderr.GetAwaiter().GetResult().Trim() -eq '') "Executable version check failed for $Version." } @@ -122,7 +156,20 @@ function Assert-Installed( } if ($Mode -eq 'Worker' -or $Mode -eq 'Recover') { - Assert-Sandbox $CaseDir + Assert-Sandbox $CaseDir $DriverRoot $TestToken + if ($Mode -eq 'Worker') { + if ([IO.Path]::GetFullPath($FixtureDir) -ine ([IO.Path]::Combine([IO.Path]::GetFullPath($DriverRoot), 'cache'))) { + throw 'Worker fixture directory is not inside its driver sandbox.' + } + $expectedCopy = [IO.Path]::Combine([IO.Path]::GetFullPath($DriverRoot), + ('instrumented-' + [IO.Path]::GetFileName([IO.Path]::GetFullPath($CaseDir)) + '.ps1')) + if ([IO.Path]::GetFullPath($InstallerCopy) -ine $expectedCopy) { + throw 'Worker installer copy does not match driver-owned instrumented file.' + } + } + elseif ([IO.Path]::GetFullPath($InstallerCopy) -ine [IO.Path]::GetFullPath($originalInstaller)) { + throw 'Recovery worker must use the unmodified repository installer.' + } if ([string]::IsNullOrWhiteSpace($InstallerCopy) -or -not [IO.File]::Exists($InstallerCopy)) { throw 'Child requires its installer file.' @@ -164,12 +211,16 @@ function Invoke-HiddenPowerShell([string]$Arguments, [string]$Purpose) { # when a child writes enough data to fill a redirected pipe. $outTask = $child.StandardOutput.ReadToEndAsync() $errTask = $child.StandardError.ReadToEndAsync() + $clock = [Diagnostics.Stopwatch]::StartNew() if (-not $child.WaitForExit(90000)) { try { $child.Kill() } catch { } [void]$child.WaitForExit(5000) throw "$Purpose did not exit within 90 seconds." } - $child.WaitForExit() + $remaining = [int][Math]::Max(0, 90000 - $clock.ElapsedMilliseconds) + if (-not [Threading.Tasks.Task]::WaitAll([Threading.Tasks.Task[]]@($outTask, $errTask), $remaining)) { + throw "$Purpose exited but output pipes remained open after the 90-second deadline." + } return [pscustomobject]@{ ExitCode = $child.ExitCode Output = $outTask.GetAwaiter().GetResult() @@ -211,6 +262,20 @@ function Make-InstrumentedInstaller([string]$Source, [string]$Destination, [stri $replacement = ' Invoke-ProoflineReplaceWithRetry $stage $destination $paths.api $hash $oldReceipt.sha256' + "`n" + $damage + ' ' + $abort + "`n" + ' if (' } + elseif ($Checkpoint -eq 'after-upgrade-passed') { + $target = " Set-ProoflinePendingPostcheck "+'$pending '+ "'passed'" + + "`n" + ' Write-ProoflineReceipt $receipt $ReleaseVersion $hash' + $replacement = " Set-ProoflinePendingPostcheck "+'$pending '+ "'passed'" + + "`n" + ' ' + $abort + + "`n" + ' Write-ProoflineReceipt $receipt $ReleaseVersion $hash' + } + elseif ($Checkpoint -eq 'fresh-after-passed') { + $target = " Set-ProoflinePendingPostcheck "+'$pending '+ "'passed'" + + "`n" + ' Write-ProoflineReceipt $receipt $ReleaseVersion $hash' + $replacement = " Set-ProoflinePendingPostcheck "+'$pending '+ "'passed'" + + "`n" + ' ' + $abort + + "`n" + ' Write-ProoflineReceipt $receipt $ReleaseVersion $hash' + } elseif ($Checkpoint -eq 'after-receipt') { $target = ' Write-ProoflineReceipt $receipt $ReleaseVersion $hash' + "`n" + ' try { Clear-ProoflineUpgradeFiles $paths $pending $hash }' @@ -237,10 +302,10 @@ function Make-InstrumentedInstaller([string]$Source, [string]$Destination, [stri "`n" + ' ' + $abort + "`n" + ' if (' } elseif ($Checkpoint -eq 'fresh-after-receipt') { - $target = ' Write-ProoflineReceipt $receipt $ReleaseVersion $hash' + - "`n" + ' [IO.File]::Delete($pending)' - $replacement = ' Write-ProoflineReceipt $receipt $ReleaseVersion $hash' + - "`n" + ' ' + $abort + "`n" + ' [IO.File]::Delete($pending)' + $target = ' Write-ProoflineReceipt $receipt $ReleaseVersion $hash' + + "`n" + ' Clear-ProoflineJournalBackup $pending' + $replacement = ' Write-ProoflineReceipt $receipt $ReleaseVersion $hash' + + "`n" + ' ' + $abort + "`n" + ' Clear-ProoflineJournalBackup $pending' } else { throw "Unsupported injection checkpoint $Checkpoint." } Require ($text.Contains($target)) "Production installer checkpoint '$Checkpoint' changed." @@ -254,22 +319,28 @@ $root = Join-Path ([IO.Path]::GetTempPath()) ('proofline-real-interruption-' + [ $cache = Join-Path $root 'cache' [IO.Directory]::CreateDirectory($cache) | Out-Null $scenarios = @( - 'after-journal', 'upgrade-partial-stage', 'after-switch', 'corrupt-after-switch', 'after-receipt', - 'fresh-after-journal', 'fresh-partial-stage', 'fresh-after-stage', 'fresh-after-move', 'fresh-after-receipt' + 'after-journal', 'upgrade-partial-stage', 'after-switch', 'corrupt-after-switch', + 'after-upgrade-passed', 'after-receipt', + 'fresh-after-journal', 'fresh-partial-stage', 'fresh-after-stage', 'fresh-after-move', + 'fresh-after-passed', 'fresh-after-receipt' ) $expected = @{ 'after-journal' = '0.5.1' 'upgrade-partial-stage' = '0.5.1' 'after-switch' = '0.5.1' 'corrupt-after-switch' = '0.5.1' + 'after-upgrade-passed' = '0.5.2' 'after-receipt' = '0.5.2' 'fresh-after-journal' = 'absent' 'fresh-partial-stage' = 'absent' 'fresh-after-stage' = 'absent' 'fresh-after-move' = 'absent' + 'fresh-after-passed' = '0.5.1' 'fresh-after-receipt' = '0.5.1' } $engine = (Get-Process -Id $PID).Path +$testToken = [guid]::NewGuid().ToString('N') +[IO.File]::WriteAllText((Join-Path $root '.proofline-run-token'), $testToken) $pathBefore = [Environment]::GetEnvironmentVariable('Path', 'User') $results = @() $passed = $false @@ -299,7 +370,7 @@ try { foreach ($checkpoint in $scenarios) { $directory = Join-Path $root $checkpoint [IO.Directory]::CreateDirectory($directory) | Out-Null - [IO.File]::WriteAllText((Join-Path $directory '.proofline-test-only'), 'DISPOSABLE_REAL_UPGRADE_TEST') + [IO.File]::WriteAllText((Join-Path $directory '.proofline-test-only'), "DISPOSABLE_REAL_UPGRADE_TEST:$testToken") $isFresh = $checkpoint -like 'fresh-*' $oldDigest = $null if ($isFresh) { @@ -318,7 +389,8 @@ try { $stderr = Join-Path $root ("worker-$checkpoint.stderr.txt") $arguments = '-NoProfile -NonInteractive -File "' + $PSCommandPath + '" -Mode Worker -CaseDir "' + $directory + - '" -FixtureDir "' + $cache + '" -InstallerCopy "' + $copy + '"' + '" -FixtureDir "' + $cache + '" -InstallerCopy "' + $copy + + '" -DriverRoot "' + $root + '" -TestToken ' + $testToken $worker = Invoke-HiddenPowerShell $arguments "upgrade worker ($checkpoint)" $workerExit = $worker.ExitCode [IO.File]::WriteAllText($stdout, $worker.Output) @@ -330,6 +402,21 @@ try { Require ($workerExit -eq -1) "Worker did not terminate as expected at $checkpoint; exit $workerExit; output: $workerOutput" $journal = Join-Path $directory '.proofline-install.pending.json' Require ([IO.File]::Exists($journal)) "No pending journal existed after forced termination at $checkpoint." + $onDiskJournal = ConvertFrom-Json -InputObject ([IO.File]::ReadAllText($journal)) + if ($checkpoint -in @('after-switch', 'corrupt-after-switch')) { + Require ($onDiskJournal.postcheck -ceq 'checking') 'Switch happened without durable checking state.' + } + if ($checkpoint -in @('after-upgrade-passed', 'fresh-after-passed')) { + Require ($onDiskJournal.postcheck -ceq 'passed') 'Passed checkpoint did not persist postcheck before receipt.' + $receiptBefore = Join-Path $directory '.proofline-install.receipt.json' + if ($checkpoint -eq 'fresh-after-passed') { + Require (-not [IO.File]::Exists($receiptBefore)) 'First-install receipt was prematurely published before persisted passed checkpoint.' + } + else { + $oldReceipt = ConvertFrom-Json -InputObject ([IO.File]::ReadAllText($receiptBefore)) + Require ($oldReceipt.version -ceq '0.5.1') 'Upgrade receipt was prematurely published before persisted passed checkpoint.' + } + } $activeFile = Join-Path $directory 'proofline.exe' $activeDigest = $null if ([IO.File]::Exists($activeFile)) { @@ -338,7 +425,7 @@ try { if ($checkpoint -in @('fresh-after-journal', 'fresh-partial-stage', 'fresh-after-stage')) { Require ($null -eq $activeDigest) 'Fresh install published executable before intended checkpoint.' } - elseif ($checkpoint -in @('fresh-after-move', 'fresh-after-receipt')) { + elseif ($checkpoint -in @('fresh-after-move', 'fresh-after-passed', 'fresh-after-receipt')) { Require ($activeDigest -ceq $script:pinnedExeHashes['0.5.1']) 'Fresh install did not publish the pinned executable before checkpoint.' } elseif ($checkpoint -in @('after-journal', 'upgrade-partial-stage')) { @@ -355,7 +442,8 @@ try { $recoverStderr = Join-Path $root ("recovery-$checkpoint.stderr.txt") $recoverArgs = '-NoProfile -NonInteractive -File "' + $PSCommandPath + '" -Mode Recover -CaseDir "' + $directory + - '" -InstallerCopy "' + $originalInstaller + '"' + '" -InstallerCopy "' + $originalInstaller + + '" -DriverRoot "' + $root + '" -TestToken ' + $testToken $recovery = Invoke-HiddenPowerShell $recoverArgs "recovery worker ($checkpoint)" $recoverExit = $recovery.ExitCode [IO.File]::WriteAllText($recoverStdout, $recovery.Output) diff --git a/scripts/test_install_upgrade_real_windows.ps1 b/scripts/test_install_upgrade_real_windows.ps1 index 2bafc05..7392e1a 100644 --- a/scripts/test_install_upgrade_real_windows.ps1 +++ b/scripts/test_install_upgrade_real_windows.ps1 @@ -26,12 +26,54 @@ $bin = Join-Path $root 'bin' $oldUserPath = [Environment]::GetEnvironmentVariable('Path', 'User') $script:TestEngine = (Get-Process -Id $PID).Path # Test whichever PowerShell edition invoked this script. $passed = $false +# Stable official Windows x64 executable digests recorded from previously +# checksum-validated real-release integration runs. These are intentionally +# independent of the installer receipt and newly downloaded manifest. +$script:TrustedReleaseDigests = @{ + '0.5.1' = '442D14583870A4E44291BD0AD118DFC536AA9D1096FA6E669BCD01B29BCEF379' + '0.5.2' = '7B93F8FE807AAB90133FF19908921079E5A91A51A705118BC3063DC74BD9CCB5' +} + +function Invoke-TestChild([string]$FileName, [string]$Arguments, [string]$Purpose, [int]$TimeoutMs) { + $start = [Diagnostics.ProcessStartInfo]::new() + $start.FileName = $FileName + $start.Arguments = $Arguments + $start.UseShellExecute = $false + $start.CreateNoWindow = $true + $start.RedirectStandardOutput = $true + $start.RedirectStandardError = $true + $child = [Diagnostics.Process]::new() + $child.StartInfo = $start + $clock = [Diagnostics.Stopwatch]::StartNew() + try { + if (-not $child.Start()) { throw "Could not start $Purpose." } + $stdout = $child.StandardOutput.ReadToEndAsync() + $stderr = $child.StandardError.ReadToEndAsync() + if (-not $child.WaitForExit($TimeoutMs)) { + try { $child.Kill() } catch { } + [void]$child.WaitForExit(5000) + throw "$Purpose exceeded its $TimeoutMs ms process deadline." + } + $remaining = [int][Math]::Max(0, $TimeoutMs - $clock.ElapsedMilliseconds) + if (-not [Threading.Tasks.Task]::WaitAll([Threading.Tasks.Task[]]@($stdout, $stderr), $remaining)) { + throw "$Purpose exited but its redirected output streams did not close before the deadline." + } + return [pscustomobject]@{ + ExitCode = $child.ExitCode + Output = $stdout.GetAwaiter().GetResult() + ErrorOutput = $stderr.GetAwaiter().GetResult() + } + } + finally { $child.Dispose() } +} function Install-Release([string]$Version) { Write-Host "Installing official Proofline $Version..." - & $script:TestEngine -NoProfile -NonInteractive -File $installer -Version $Version -InstallDir $bin -NoModifyPath - if ($LASTEXITCODE -ne 0) { - throw "Installer $Version exited with code $LASTEXITCODE." + $args = '-NoProfile -NonInteractive -File "' + $installer + '" -Version ' + $Version + + ' -InstallDir "' + $bin + '" -NoModifyPath' + $result = Invoke-TestChild $script:TestEngine $args "Installer $Version" 120000 + if ($result.ExitCode -ne 0) { + throw "Installer $Version exited $($result.ExitCode); stdout: $($result.Output); stderr: $($result.ErrorOutput)" } } function Check-Release([string]$Version) { @@ -42,6 +84,9 @@ function Check-Release([string]$Version) { throw "Managed installation missing executable or receipt for $Version." } $hash = (Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash + if ($hash -cne $script:TrustedReleaseDigests[$Version]) { + throw "Installed $Version executable does not match the pinned official release digest." + } $receiptHash = (Get-FileHash -LiteralPath $receipt -Algorithm SHA256).Hash $record = ConvertFrom-Json -InputObject ([IO.File]::ReadAllText($receipt)) if ($record.schema -ne 1 -or $record.version -cne $Version -or $record.sha256 -cne $hash) { @@ -56,32 +101,12 @@ function Check-Release([string]$Version) { if ($debris.Count -ne 0) { throw "Unexpected staged or recovery artifacts remain after $Version." } - # Always bound real executable execution, including stalled version probes. - $start = [Diagnostics.ProcessStartInfo]::new() - $start.FileName = $exe - $start.Arguments = '--version' - $start.UseShellExecute = $false - $start.CreateNoWindow = $true - $start.RedirectStandardOutput = $true - $start.RedirectStandardError = $true - $child = [Diagnostics.Process]::new() - $child.StartInfo = $start - try { - if (-not $child.Start()) { throw "Could not launch official Proofline $Version." } - $outTask = $child.StandardOutput.ReadToEndAsync() - $errTask = $child.StandardError.ReadToEndAsync() - if (-not $child.WaitForExit(15000)) { - try { $child.Kill() } catch { } - [void]$child.WaitForExit(5000) - throw "Executable version check timed out for $Version after 15 seconds." - } - $output = $outTask.GetAwaiter().GetResult().Trim() - $errors = $errTask.GetAwaiter().GetResult().Trim() - if ($child.ExitCode -ne 0 -or $output -cne "proofline $Version" -or $errors -ne '') { - throw "Executable version check failed for $Version (exit $($child.ExitCode), output '$output', stderr '$errors')." - } + # Apply one deadline to process exit AND both redirected output reads. + $probe = Invoke-TestChild $exe '--version' "Version check $Version" 15000 + if ($probe.ExitCode -ne 0 -or $probe.Output.Trim() -cne "proofline $Version" -or + $probe.ErrorOutput.Trim() -ne '') { + throw "Executable version check failed for $Version (exit $($probe.ExitCode), output '$($probe.Output)', stderr '$($probe.ErrorOutput)')." } - finally { $child.Dispose() } return [pscustomobject]@{ BinarySha256 = $hash ReceiptSha256 = $receiptHash diff --git a/scripts/test_install_upgrade_windows.ps1 b/scripts/test_install_upgrade_windows.ps1 index 7655a2d..719b1c6 100644 --- a/scripts/test_install_upgrade_windows.ps1 +++ b/scripts/test_install_upgrade_windows.ps1 @@ -92,6 +92,14 @@ try { $script:oldHash = Get-ProoflineSha256FileBytes (Get-ProoflineTarExecutable $script:oldArchive) $script:newHash = Get-ProoflineSha256FileBytes (Get-ProoflineTarExecutable $script:newArchive) + Check 'version checker rejects correct output from a failed process' { + # Tests the actual production checker result contract without launching + # the intentionally unexecutable fake PE fixture. + Must-Throw { Assert-ProoflineVersionResult 7 'proofline 0.5.1' '' '0.5.1' } + Must-Throw { Assert-ProoflineVersionResult 0 'proofline 0.5.1' 'unexpected stderr' '0.5.1' } + Assert-ProoflineVersionResult 0 'proofline 0.5.1' '' '0.5.1' + } + # Test-only shadow function: fake PE fixtures are not runnable and must # NEVER be started. Production installer calls the original version checker. $script:smokeCount = 0 @@ -217,6 +225,8 @@ try { [void](MakePending $dir) Set-ProoflinePendingPostcheck (Pending 'checking-interrupted') 'checking' [IO.File]::WriteAllBytes((Active 'checking-interrupted'), (Get-ProoflineTarExecutable $script:newArchive)) + # Destroy the original receipt, so rollback MUST regenerate it. + [IO.File]::Delete((Receipt 'checking-interrupted')) Invoke-ProoflinePendingRepair $dir Require ((Get-ProoflineSha256 (Active 'checking-interrupted')) -ceq $script:oldHash) 'Interrupted postcheck was incorrectly treated as verified.' Assert-ProoflineRecord (Receipt 'checking-interrupted') '0.5.1' $script:oldHash @@ -258,9 +268,8 @@ try { $script:failInstalledPostcheckPath = $null $script:failInstalledPostcheckVersion = '0.5.2' } - Require ([IO.File]::Exists((Pending 'fresh-failed-installed-check'))) 'Failed first install did not retain journal.' - Invoke-ProoflinePendingRepair $dir - Require (-not [IO.File]::Exists((Active 'fresh-failed-installed-check'))) 'Rejected first-install executable remained active.' + Require (-not [IO.File]::Exists((Pending 'fresh-failed-installed-check'))) 'Failed first install retained a blocking journal.' + Require (-not [IO.File]::Exists((Active 'fresh-failed-installed-check'))) 'Rejected first-install executable remained active after error.' $evidence = @(Get-ChildItem -LiteralPath $dir -Filter '.proofline-unverified-first-*.exe') Require ($evidence.Count -eq 1) 'Rejected first-install image was not quarantined.' Require ((Get-ProoflineSha256 $evidence[0].FullName) -ceq $script:oldHash) 'Quarantined first-install bytes changed.' @@ -302,6 +311,73 @@ try { Assert-ProoflineRecord (Receipt 'backup-fallback') '0.5.1' $script:oldHash Require (-not [IO.File]::Exists((Pending 'backup-fallback'))) 'Fallback recovery left pending journal.' } + + Check 'markerless schema 3 first install must not finalize by matching digest' { + $dir = Join-Path $root 'fresh-markerless' + [IO.Directory]::CreateDirectory($dir) | Out-Null + $id = [guid]::NewGuid().ToString('N') + [IO.File]::WriteAllBytes((Active 'fresh-markerless'), (Get-ProoflineTarExecutable $script:oldArchive)) + Write-ProoflineAtomicRecord (Pending 'fresh-markerless') (ConvertTo-Json -Compress -InputObject ([ordered]@{ + schema = 3; id = $id; version = '0.5.1'; sha256 = $script:oldHash + })) + Invoke-ProoflinePendingRepair $dir + Require (-not [IO.File]::Exists((Active 'fresh-markerless'))) 'Markerless first install became active from digest alone.' + Require (-not [IO.File]::Exists((Receipt 'fresh-markerless'))) 'Markerless first install received a receipt.' + Require ((Get-ProoflineSha256 (Join-Path $dir ".proofline-unverified-first-$id.exe")) -ceq $script:oldHash) 'Markerless quarantine was corrupted.' + Require (-not [IO.File]::Exists((Pending 'fresh-markerless'))) 'Markerless first install left a blocking journal.' + } + Check 'missing canonical postcheck journal restores validated backup before recovery' { + $dir = PrepareOld 'journal-backup-only' + [void](MakePending $dir) + $pendingPath = Pending 'journal-backup-only' + Set-ProoflinePendingPostcheck $pendingPath 'checking' + Set-ProoflinePendingPostcheck $pendingPath 'passed' + [IO.File]::Copy($pendingPath, $pendingPath + '.postcheck.bak', $false) + [IO.File]::Delete($pendingPath) + [IO.File]::WriteAllBytes((Active 'journal-backup-only'), (Get-ProoflineTarExecutable $script:newArchive)) + Invoke-ProoflinePendingRepair $dir + Require ((Get-ProoflineSha256 (Active 'journal-backup-only')) -ceq $script:newHash) 'Journal backup recovery lost passed image.' + Assert-ProoflineRecord (Receipt 'journal-backup-only') '0.5.2' $script:newHash + Require (-not [IO.File]::Exists($pendingPath + '.postcheck.bak')) 'Backup was not cleaned after recovery.' + Require (-not [IO.File]::Exists($pendingPath)) 'Restored journal was not cleared.' + } + Check 'matching receipt is not rewritten when retrying completed upgrade cleanup' { + $dir = PrepareOld 'matched-locked-receipt' + [void](MakePending $dir) + $pendingPath = Pending 'matched-locked-receipt' + Set-ProoflinePendingPostcheck $pendingPath 'checking' + [IO.File]::WriteAllBytes((Active 'matched-locked-receipt'), (Get-ProoflineTarExecutable $script:newArchive)) + Set-ProoflinePendingPostcheck $pendingPath 'passed' + Write-ProoflineReceipt (Receipt 'matched-locked-receipt') '0.5.2' $script:newHash + $realWrite = (Get-Item Function:\Write-ProoflineReceipt).ScriptBlock + try { + Set-Item Function:\Write-ProoflineReceipt -Value { throw 'Simulated receipt replacement lock.' } + Invoke-ProoflinePendingRepair $dir + } + finally { Set-Item Function:\Write-ProoflineReceipt -Value $realWrite } + Require ((Get-ProoflineSha256 (Active 'matched-locked-receipt')) -ceq $script:newHash) 'Cleanup rolled back passed executable.' + Assert-ProoflineRecord (Receipt 'matched-locked-receipt') '0.5.2' $script:newHash + Require (-not [IO.File]::Exists($pendingPath)) 'Matching receipt cleanup retained journal.' + } + Check 'failed receipt publication after passed postcheck keeps new binary' { + $dir = PrepareOld 'locked-stale-receipt' + [void](MakePending $dir) + $pendingPath = Pending 'locked-stale-receipt' + Set-ProoflinePendingPostcheck $pendingPath 'checking' + [IO.File]::WriteAllBytes((Active 'locked-stale-receipt'), (Get-ProoflineTarExecutable $script:newArchive)) + Set-ProoflinePendingPostcheck $pendingPath 'passed' + $realWrite = (Get-Item Function:\Write-ProoflineReceipt).ScriptBlock + try { + Set-Item Function:\Write-ProoflineReceipt -Value { throw 'Simulated receipt replacement lock.' } + Must-Throw { Invoke-ProoflinePendingRepair $dir } + } + finally { Set-Item Function:\Write-ProoflineReceipt -Value $realWrite } + Require ((Get-ProoflineSha256 (Active 'locked-stale-receipt')) -ceq $script:newHash) 'Receipt lock rolled back passed executable.' + Require ([IO.File]::Exists($pendingPath)) 'Receipt lock discarded recoverable journal.' + Assert-ProoflineRecord (Receipt 'locked-stale-receipt') '0.5.1' $script:oldHash + Invoke-ProoflinePendingRepair $dir + Assert-ProoflineRecord (Receipt 'locked-stale-receipt') '0.5.2' $script:newHash + } Check 'receipt replacement preserves and cleans up its backup' { $dir = PrepareOld 'receipt-backup' $receiptPath = Receipt 'receipt-backup' diff --git a/scripts/test_install_user_path_ci_windows.ps1 b/scripts/test_install_user_path_ci_windows.ps1 index b0708f4..853a682 100644 --- a/scripts/test_install_user_path_ci_windows.ps1 +++ b/scripts/test_install_user_path_ci_windows.ps1 @@ -15,8 +15,10 @@ $ErrorActionPreference = 'Stop' if ([Environment]::OSVersion.Platform -ne [PlatformID]::Win32NT) { throw 'Windows CI runner required.' } -if ($env:GITHUB_ACTIONS -cne 'true' -or [string]::IsNullOrWhiteSpace($env:RUNNER_TEMP)) { - throw 'Refusing PATH registry test outside GitHub Actions Windows runner.' +if ($env:GITHUB_ACTIONS -cne 'true' -or + $env:RUNNER_ENVIRONMENT -cne 'github-hosted' -or + [string]::IsNullOrWhiteSpace($env:RUNNER_TEMP)) { + throw 'Refusing PATH mutation outside a disposable GitHub-hosted Windows runner profile.' } function Get-RawUserPath { @@ -45,6 +47,8 @@ if ($Mode -eq 'ReadUserPath') { $original = Get-RawUserPath $directory = Join-Path $env:RUNNER_TEMP ('proofline-path-ci-' + [guid]::NewGuid().ToString('N')) $token = '%PROOFLINE_CI_TEST_ROOT%\bin' +$originalToken = [Environment]::GetEnvironmentVariable('PROOFLINE_CI_TEST_ROOT', 'Process') +[Environment]::SetEnvironmentVariable('PROOFLINE_CI_TEST_ROOT', (Join-Path $env:RUNNER_TEMP 'proofline-expanded-token'), 'Process') $seed = if ([string]::IsNullOrEmpty($original.value)) { $token } else { $original.value.TrimEnd(';') + ';' + $token } # Independent oracle: do not use the same helper under test to construct @@ -64,7 +68,27 @@ try { } finally { $key.Dispose() } - Add-ProoflineUserPath $directory + # Exercise the default installer entrypoint without -NoModifyPath, not + # merely its PATH helper. The disposable runner owns this user profile. + $installer = Join-Path (Split-Path -Parent $PSScriptRoot) 'install.ps1' + $engine = (Get-Process -Id $PID).Path + $start = [Diagnostics.ProcessStartInfo]::new() + $start.FileName = $engine + $start.Arguments = '-NoProfile -NonInteractive -File "' + $installer + '" -Version 0.5.1 -InstallDir "' + $directory + '"' + $start.UseShellExecute = $false + $start.CreateNoWindow = $true + $child = [Diagnostics.Process]::new() + $child.StartInfo = $start + try { + if (-not $child.Start()) { throw 'Could not start full installer for User PATH test.' } + if (-not $child.WaitForExit(120000)) { + try { $child.Kill() } catch { } + [void]$child.WaitForExit(5000) + throw 'Full installer exceeded the 120-second PATH integration deadline.' + } + if ($child.ExitCode -ne 0) { throw "Default installer exited $($child.ExitCode)." } + } + finally { $child.Dispose() } $after = Get-RawUserPath if ($after.value -cne $expected -or $after.kind -cne 'ExpandString') { throw 'Installer did not preserve expandable PATH entry and its type.' @@ -103,7 +127,7 @@ finally { $current = Get-RawUserPath # Restore only the exact test values; do not overwrite other edits. if ($current.kind -in @('ExpandString', 'String') -and - $current.value -in @($seed, $expected)) { + $current.value -cin @($seed, $expected)) { # Even if a registry-kind regression occurred, restore the exact # seeded text instead of leaving the disposable PATH entries behind. $key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Environment') @@ -122,6 +146,7 @@ finally { } else { Write-Warning 'User PATH changed concurrently; refusing to overwrite it.' } } + [Environment]::SetEnvironmentVariable('PROOFLINE_CI_TEST_ROOT', $originalToken, 'Process') Remove-Item -LiteralPath $directory -Recurse -Force -ErrorAction SilentlyContinue } if (-not $ok -or -not $restored) { diff --git a/scripts/test_install_windows.ps1 b/scripts/test_install_windows.ps1 index 366b08d..4be9a7f 100644 --- a/scripts/test_install_windows.ps1 +++ b/scripts/test_install_windows.ps1 @@ -84,6 +84,18 @@ try { else { Must-Throw { Get-ProoflineTarExecutable $archive } } } } + Test-Case 'invalid PE signature is rejected at a valid offset' { + $badSignature = Bytes 'bad-pe-signature.tar.gz' + $specificRejection = $false + try { [void](Get-ProoflineTarExecutable $badSignature) } + catch { + if ($_.Exception.Message -notlike '*no valid PE signature*') { + throw "Invalid PE signature rejected for wrong reason: $($_.Exception.Message)" + } + $specificRejection = $true + } + if (-not $specificRejection) { throw 'Corrupt PE signature was accepted.' } + } Test-Case 'checksum rejects modified archive bytes' { $modified = Bytes 'bad-digest.tar.gz' Must-Throw { Assert-ProoflineChecksum $modified $sums } @@ -94,6 +106,20 @@ try { Must-Throw { Assert-ProoflineVersion '01.2.3' } Must-Throw { Assert-ProoflineVersion '1.2.3-rc1' } } + Test-Case 'literal REG_SZ PATH tokens are not expanded during duplicate detection' { + $variable = 'PROOFLINE_DUPLICATE_KIND_TEST' + $previous = [Environment]::GetEnvironmentVariable($variable, 'Process') + $directory = 'C:\ProoflineTest\bin' + [Environment]::SetEnvironmentVariable($variable, 'C:\ProoflineTest', 'Process') + try { + $token = '%' + $variable + '%\bin' + $literal = Get-ProoflineUpdatedUserPath $token $directory ([Microsoft.Win32.RegistryValueKind]::String) + if ($literal -cne ($token + ';' + $directory)) { throw 'REG_SZ token incorrectly treated as expanded directory.' } + $expanded = Get-ProoflineUpdatedUserPath $token $directory ([Microsoft.Win32.RegistryValueKind]::ExpandString) + if ($null -ne $expanded) { throw 'REG_EXPAND_SZ duplicate token was not recognized.' } + } + finally { [Environment]::SetEnvironmentVariable($variable, $previous, 'Process') } + } Test-Case 'PATH change is idempotent' { $directory = 'C:\Users\tester\AppData\Local\Programs\Proofline\bin' if ($null -ne (Get-ProoflineUpdatedUserPath $directory $directory)) { From b1d042429ee8100be7decc8bbb9b5f6cfcaf501f Mon Sep 17 00:00:00 2001 From: Ayan Khan Date: Mon, 23 Nov 2026 22:51:23 +0530 Subject: [PATCH 12/21] fix(windows): close reviewed recovery and PATH concurrency gaps --- .github/workflows/ci.yml | 7 ++ .github/workflows/windows-installer.yml | 7 +- README.md | 2 +- install.ps1 | 78 ++++++++++++++----- .../generate_windows_installer_fixtures.py | 2 +- scripts/test_install_concurrency_windows.ps1 | 7 +- ...test_install_interruption_real_windows.ps1 | 8 +- scripts/test_install_upgrade_windows.ps1 | 59 ++++++++++++++ scripts/test_install_windows.ps1 | 7 +- 9 files changed, 150 insertions(+), 27 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 331c3cc..4360052 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -39,6 +39,13 @@ jobs: - run: python scripts/archive.py x86_64-pc-windows-msvc - shell: pwsh run: | + # Reject a packaged archive that the proposed installer cannot read. + # The normal tar smoke test alone does not reject extra members. + . ./install.ps1 + $archivePath = 'artifacts/proofline-x86_64-pc-windows-msvc.tar.gz' + $binary = Get-ProoflineTarExecutable ([IO.File]::ReadAllBytes((Resolve-Path $archivePath).Path)) + if ($binary.Length -le 0) { throw 'PR-built Windows archive contains no supported Proofline executable.' } + Write-Host "Installer-compatible PR-built Windows archive validated ($($binary.Length) bytes)." tar -xzf artifacts/proofline-x86_64-pc-windows-msvc.tar.gz -C artifacts & ./artifacts/proofline.exe --version if ($LASTEXITCODE -ne 0) { throw "Windows executable failed" } diff --git a/.github/workflows/windows-installer.yml b/.github/workflows/windows-installer.yml index 9f89503..a5557a8 100644 --- a/.github/workflows/windows-installer.yml +++ b/.github/workflows/windows-installer.yml @@ -6,6 +6,11 @@ on: - 'install.ps1' - 'scripts/test_install*windows.ps1' - 'scripts/generate_windows_installer_fixtures.py' + - 'scripts/archive.py' + - 'Cargo.toml' + - 'Cargo.lock' + - 'src/**' + - '.github/workflows/ci.yml' - '.github/workflows/windows-installer.yml' workflow_dispatch: @@ -70,7 +75,7 @@ jobs: & $env:TEST_ENGINE -NoProfile -NonInteractive -File scripts/test_install_upgrade_real_windows.ps1 if ($LASTEXITCODE -ne 0) { throw "Real Windows upgrade test failed: $LASTEXITCODE" } - - name: Recover from ten real process-termination checkpoints + - name: Recover from twelve real process-termination checkpoints shell: pwsh env: TEST_ENGINE: ${{ matrix.engine }} diff --git a/README.md b/README.md index aa30296..f3ad09c 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ On **Windows x64**, run the PowerShell installer from a checked-out copy of this powershell.exe -NoProfile -File .\install.ps1 ``` -It downloads the official release and `SHA256SUMS` from `https://proofline.sh`, validates the archive, verifies `proofline.exe --version`, and installs for the **current user** in `%LOCALAPPDATA%\Programs\Proofline\bin` without administrator rights. By default it attempts to append that directory to the user PATH while preserving expandable registry entries; this is best-effort and may warn if registry permissions or concurrent changes prevent an update. If warned, open **Windows Environment Variables → User variables → Path → Edit → New** and add `%LOCALAPPDATA%\Programs\Proofline\bin` manually (or your custom `-InstallDir`). Open a new terminal and run `Get-Command proofline -All` to check which executable has precedence. If an older copy is found first, run the new executable using its absolute path (for example, `& "$env:LOCALAPPDATA\Programs\Proofline\bin\proofline.exe" login`) or correct the stale PATH entry. The installer does not handle login or credentials. +It downloads the official release and `SHA256SUMS` from `https://proofline.sh`, validates the archive, verifies `proofline.exe --version`, and installs for the **current user** in `%LOCALAPPDATA%\Programs\Proofline\bin` without administrator rights. By default it attempts to append that directory to the user PATH while preserving expandable registry entries; this is best-effort and may warn if registry permissions or concurrent changes prevent an update. Cooperating Proofline installer processes serialize PATH updates with a per-user mutex, but unrelated registry editors do not share that lock. If the installer warns, first check **Windows Environment Variables → User variables → Path**. Add `%LOCALAPPDATA%\Programs\Proofline\bin` (or your custom `-InstallDir`) **only if it is missing**; a notification warning does not necessarily mean the registry update failed. Open a new terminal and run `Get-Command proofline -All` to check which executable has precedence. If an older copy is found first, run the new executable using its absolute path (for example, `& "$env:LOCALAPPDATA\Programs\Proofline\bin\proofline.exe" login`) or correct the stale PATH entry. The installer does not handle login or credentials. To pin a version or install in a disposable folder without updating PATH: diff --git a/install.ps1 b/install.ps1 index e053e79..ccc3d9f 100644 --- a/install.ps1 +++ b/install.ps1 @@ -276,7 +276,11 @@ function Get-ProoflineUpdatedUserPath( $normalized = $Directory.TrimEnd([char[]]@('\', '/')) foreach ($entry in ($Current -split ';')) { $candidate = $entry.Trim() - if ($Kind -eq [Microsoft.Win32.RegistryValueKind]::ExpandString) { + # A variable-containing entry can expand to the install directory + # today but move when the variable changes. Do not treat it as a + # durable duplicate of the literal installed directory. + if ($Kind -eq [Microsoft.Win32.RegistryValueKind]::ExpandString -and + $candidate -notmatch '%[^%]+%') { $candidate = [Environment]::ExpandEnvironmentVariables($candidate) } if ($candidate.TrimEnd([char[]]@('\', '/')) -ieq $normalized) { @@ -334,26 +338,50 @@ public static class ProoflineEnvironmentNotifier { } function Add-ProoflineUserPath([string]$Directory) { - $previous = Get-ProoflineUserPathRecord - $result = Get-ProoflineUpdatedUserPath $previous.value $Directory $previous.kind - if ($null -eq $result) { - Write-Host 'User PATH already contains the Proofline directory.' - return - } - $key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Environment') + # Serialize cooperating installer processes for the same Windows user. + # Other PATH editors are not obligated to acquire this mutex; their edits + # can still race with RegistryKey.SetValue (no registry compare-and-swap). + $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value + $mutexName = 'Local\Proofline-UserPath-' + $sid + $mutex = [Threading.Mutex]::new($false, $mutexName) + $locked = $false + $changed = $false try { - # Avoid an obvious lost update if another process changed PATH since - # our read. This is not a cross-process atomic registry compare/swap. - $fresh = Get-ProoflineUserPathRecord - if ($fresh.value -cne $previous.value -or - $fresh.kind -ne $previous.kind -or $fresh.exists -ne $previous.exists) { - throw 'User PATH changed concurrently; retry the installer or add the directory manually.' + try { + $locked = $mutex.WaitOne(30000) + } + catch [Threading.AbandonedMutexException] { + $locked = $true } - $key.SetValue('Path', $result, $previous.kind) + if (-not $locked) { throw 'Another Proofline installer is updating user PATH; retry after it completes.' } + $previous = Get-ProoflineUserPathRecord + $result = Get-ProoflineUpdatedUserPath $previous.value $Directory $previous.kind + if ($null -eq $result) { + Write-Host 'User PATH already contains the Proofline directory.' + return + } + $key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Environment') + try { + # Detect external changes before writing where possible. This + # check cannot make unrelated registry editors atomic. + $fresh = Get-ProoflineUserPathRecord + if ($fresh.value -cne $previous.value -or + $fresh.kind -ne $previous.kind -or $fresh.exists -ne $previous.exists) { + throw 'User PATH changed concurrently; retry the installer or add the directory manually.' + } + $key.SetValue('Path', $result, $previous.kind) + $changed = $true + } + finally { $key.Dispose() } + } + finally { + if ($locked) { $mutex.ReleaseMutex() } + $mutex.Dispose() + } + if ($changed) { + Send-ProoflineEnvironmentChange + Write-Host 'Added Proofline to your user PATH. Open a new terminal to use it.' } - finally { $key.Dispose() } - Send-ProoflineEnvironmentChange - Write-Host 'Added Proofline to your user PATH. Open a new terminal to use it.' } @@ -439,6 +467,16 @@ function Assert-ProoflineRecord([string]$Path, [string]$ExpectedVersion, [string } } +function Ensure-ProoflineReceipt([string]$Path, [string]$Version, [string]$Hash) { + # A matching receipt may be held open without delete sharing. No need + # to replace it just to complete cleanup of an already verified release. + if ([IO.File]::Exists($Path)) { + $current = Read-ProoflineReceipt $Path + if ($current.version -ceq $Version -and $current.sha256 -ceq $Hash) { return } + } + Write-ProoflineReceipt $Path $Version $Hash +} + function Read-ProoflineReceipt([string]$Path) { if (-not [IO.File]::Exists($Path)) { throw 'No installer-managed receipt exists.' } if (([IO.FileInfo]$Path).Length -gt 4096) { throw 'Installation receipt is too large.' } @@ -774,7 +812,7 @@ function Recover-ProoflinePending([string]$Directory) { } if ($activeHash -ceq $record.oldSha256) { - Write-ProoflineReceipt $receipt $record.oldVersion $record.oldSha256 + Ensure-ProoflineReceipt $receipt $record.oldVersion $record.oldSha256 try { Clear-ProoflineUpgradeFiles $paths $pending $record.newSha256 -PreserveIncompleteStage } catch { Write-Warning "Verified previous installation retained; cleanup will be retried: $($_.Exception.Message)" } Write-Host "Previous Proofline $($record.oldVersion) installation remains usable." @@ -818,7 +856,7 @@ function Recover-ProoflinePending([string]$Directory) { } # Recovery copy was checked against the recorded hash; do not execute # a pre-existing local image during repair. - Write-ProoflineReceipt $receipt $record.oldVersion $record.oldSha256 + Ensure-ProoflineReceipt $receipt $record.oldVersion $record.oldSha256 Clear-ProoflineUpgradeFiles $paths $pending $record.newSha256 Write-Host "Restored verified Proofline $($record.oldVersion) after interrupted upgrade." } diff --git a/scripts/generate_windows_installer_fixtures.py b/scripts/generate_windows_installer_fixtures.py index 429be50..28c3691 100644 --- a/scripts/generate_windows_installer_fixtures.py +++ b/scripts/generate_windows_installer_fixtures.py @@ -80,7 +80,7 @@ def main(destination: Path) -> None: f"{other} proofline-x86_64-unknown-linux-musl.tar.gz\n", encoding="ascii" ) (destination / "SHA256SUMS-malformed").write_text( - f"{sha} {name}\nnot-a-hash another-release.tar.gz\n", encoding="ascii" + f"{sha} {name}\nnot-a-hash proofline-x86_64-unknown-linux-musl.tar.gz\n", encoding="ascii" ) # The release's archive format is deterministic; assert our fixture name, # tar type and content are correct before it reaches PowerShell tests. diff --git a/scripts/test_install_concurrency_windows.ps1 b/scripts/test_install_concurrency_windows.ps1 index c3a12ee..e2d7aff 100644 --- a/scripts/test_install_concurrency_windows.ps1 +++ b/scripts/test_install_concurrency_windows.ps1 @@ -37,10 +37,15 @@ if ($Mode -eq 'Hold') { catch { throw 'Refusing to hold lock: fresh disposable test marker is unavailable or already claimed.' } try { if ([IO.File]::ReadAllText($claimed) -cne "DISPOSABLE_LOCK_TEST:$HoldToken") { + # Invalid invocations must not consume another holder's valid + # marker. Atomic move back only if no new marker was created. + if (-not [IO.File]::Exists($marker)) { [IO.File]::Move($claimed, $marker) } throw 'Refusing to hold lock: claimed marker has unexpected contents.' } } - finally { [IO.File]::Delete($claimed) } + finally { + if ([IO.File]::Exists($claimed)) { [IO.File]::Delete($claimed) } + } $lock = Join-Path $folder '.proofline-install.lock' $ready = Join-Path $folder '.holder-ready' $release = Join-Path $folder '.holder-release' diff --git a/scripts/test_install_interruption_real_windows.ps1 b/scripts/test_install_interruption_real_windows.ps1 index 5fb219c..1cfe44b 100644 --- a/scripts/test_install_interruption_real_windows.ps1 +++ b/scripts/test_install_interruption_real_windows.ps1 @@ -174,7 +174,11 @@ if ($Mode -eq 'Worker' -or $Mode -eq 'Recover') { -not [IO.File]::Exists($InstallerCopy)) { throw 'Child requires its installer file.' } - . $InstallerCopy + $validatedCopy = [IO.Path]::GetFullPath($InstallerCopy) + if (([IO.File]::GetAttributes($validatedCopy) -band [IO.FileAttributes]::ReparsePoint) -ne 0) { + throw 'Refusing to dot-source an installer copy that is a reparse point.' + } + . $validatedCopy if ($Mode -eq 'Recover') { Invoke-ProoflinePendingRepair $CaseDir Write-Output 'RECOVERY_COMPLETED' @@ -403,7 +407,7 @@ try { $journal = Join-Path $directory '.proofline-install.pending.json' Require ([IO.File]::Exists($journal)) "No pending journal existed after forced termination at $checkpoint." $onDiskJournal = ConvertFrom-Json -InputObject ([IO.File]::ReadAllText($journal)) - if ($checkpoint -in @('after-switch', 'corrupt-after-switch')) { + if ($checkpoint -in @('after-switch', 'corrupt-after-switch', 'fresh-after-move')) { Require ($onDiskJournal.postcheck -ceq 'checking') 'Switch happened without durable checking state.' } if ($checkpoint -in @('after-upgrade-passed', 'fresh-after-passed')) { diff --git a/scripts/test_install_upgrade_windows.ps1 b/scripts/test_install_upgrade_windows.ps1 index 719b1c6..ebfe69e 100644 --- a/scripts/test_install_upgrade_windows.ps1 +++ b/scripts/test_install_upgrade_windows.ps1 @@ -341,6 +341,65 @@ try { Require (-not [IO.File]::Exists($pendingPath + '.postcheck.bak')) 'Backup was not cleaned after recovery.' Require (-not [IO.File]::Exists($pendingPath)) 'Restored journal was not cleared.' } + Check 'pre-switch repair does not rewrite matching locked old receipt' { + $dir = PrepareOld 'pre-switch-matching-receipt' + [void](MakePending $dir) + $realWrite = (Get-Item Function:\Write-ProoflineReceipt).ScriptBlock + try { + Set-Item Function:\Write-ProoflineReceipt -Value { throw 'Simulated locked old receipt.' } + Invoke-ProoflinePendingRepair $dir + } + finally { Set-Item Function:\Write-ProoflineReceipt -Value $realWrite } + Require ((Get-ProoflineSha256 (Active 'pre-switch-matching-receipt')) -ceq $script:oldHash) 'Pre-switch repair changed the old image.' + Assert-ProoflineRecord (Receipt 'pre-switch-matching-receipt') '0.5.1' $script:oldHash + Require (-not [IO.File]::Exists((Pending 'pre-switch-matching-receipt'))) 'Pre-switch repair left journal.' + } + Check 'rollback preserves matching locked old receipt' { + $dir = PrepareOld 'rollback-matching-receipt' + [void](MakePending $dir) + Set-ProoflinePendingPostcheck (Pending 'rollback-matching-receipt') 'checking' + [IO.File]::WriteAllBytes((Active 'rollback-matching-receipt'), (Get-ProoflineTarExecutable $script:newArchive)) + $realWrite = (Get-Item Function:\Write-ProoflineReceipt).ScriptBlock + try { + Set-Item Function:\Write-ProoflineReceipt -Value { throw 'Simulated locked old receipt.' } + Invoke-ProoflinePendingRepair $dir + } + finally { Set-Item Function:\Write-ProoflineReceipt -Value $realWrite } + Require ((Get-ProoflineSha256 (Active 'rollback-matching-receipt')) -ceq $script:oldHash) 'Rollback did not restore old image.' + Assert-ProoflineRecord (Receipt 'rollback-matching-receipt') '0.5.1' $script:oldHash + Require (-not [IO.File]::Exists((Pending 'rollback-matching-receipt'))) 'Rollback left journal.' + } + Check 'pre-download installer repairs interrupted upgrade despite download outage' { + $dir = PrepareOld 'predownload-outage' + [void](MakePending $dir) + Set-ProoflinePendingPostcheck (Pending 'predownload-outage') 'checking' + [IO.File]::WriteAllBytes((Active 'predownload-outage'), (Get-ProoflineTarExecutable $script:newArchive)) + $realDownload = (Get-Item Function:\Get-ProoflineOfficialBytes).ScriptBlock + try { + Set-Item Function:\Get-ProoflineOfficialBytes -Value { + param([string]$RelativePath, [int]$MaximumLength) + throw 'INTENTIONAL_DOWNLOAD_UNAVAILABLE' + } + Must-Throw { Invoke-ProoflineInstaller '0.5.2' $dir $false } + } + finally { Set-Item Function:\Get-ProoflineOfficialBytes -Value $realDownload } + Require ((Get-ProoflineSha256 (Active 'predownload-outage')) -ceq $script:oldHash) 'Installer did not roll back before failing download.' + Assert-ProoflineRecord (Receipt 'predownload-outage') '0.5.1' $script:oldHash + Require (-not [IO.File]::Exists((Pending 'predownload-outage'))) 'Installer left pre-download journal.' + } + Check 'orphaned checking-state backup conservatively restores old release' { + $dir = PrepareOld 'orphan-checking' + [void](MakePending $dir) + $journal = Pending 'orphan-checking' + Set-ProoflinePendingPostcheck $journal 'checking' + [IO.File]::Move($journal, $journal + '.postcheck.bak') + [IO.File]::WriteAllBytes((Active 'orphan-checking'), (Get-ProoflineTarExecutable $script:newArchive)) + Invoke-ProoflinePendingRepair $dir + Require ((Get-ProoflineSha256 (Active 'orphan-checking')) -ceq $script:oldHash) 'Interrupted checking journal was accepted as passed.' + Assert-ProoflineRecord (Receipt 'orphan-checking') '0.5.1' $script:oldHash + Require (-not [IO.File]::Exists($journal + '.postcheck.bak')) 'Orphaned backup remains.' + Require (-not [IO.File]::Exists($journal)) 'Recovered checking journal remains.' + } Check 'matching receipt is not rewritten when retrying completed upgrade cleanup' { $dir = PrepareOld 'matched-locked-receipt' [void](MakePending $dir) diff --git a/scripts/test_install_windows.ps1 b/scripts/test_install_windows.ps1 index 4be9a7f..fcde69f 100644 --- a/scripts/test_install_windows.ps1 +++ b/scripts/test_install_windows.ps1 @@ -115,8 +115,13 @@ try { $token = '%' + $variable + '%\bin' $literal = Get-ProoflineUpdatedUserPath $token $directory ([Microsoft.Win32.RegistryValueKind]::String) if ($literal -cne ($token + ';' + $directory)) { throw 'REG_SZ token incorrectly treated as expanded directory.' } + # An expandable entry can move when the variable changes. + # Preserve the literal installed directory even when the token + # happens to expand to it at this moment. $expanded = Get-ProoflineUpdatedUserPath $token $directory ([Microsoft.Win32.RegistryValueKind]::ExpandString) - if ($null -ne $expanded) { throw 'REG_EXPAND_SZ duplicate token was not recognized.' } + if ($expanded -cne ($token + ';' + $directory)) { + throw 'Variable-dependent PATH entry incorrectly suppressed stable installed directory.' + } } finally { [Environment]::SetEnvironmentVariable($variable, $previous, 'Process') } } From 6025759d40fe32477988da8553f3a29cf5a3c616 Mon Sep 17 00:00:00 2001 From: Ayan Khan Date: Mon, 23 Nov 2026 23:37:20 +0530 Subject: [PATCH 13/21] fix(windows): harden release validation and recoverable postchecks --- .github/workflows/ci.yml | 7 +- .github/workflows/release.yml | 19 ++++ .github/workflows/windows-installer.yml | 4 +- install.ps1 | 86 ++++++++++++------- .../generate_windows_installer_fixtures.py | 6 ++ scripts/test_install_windows.ps1 | 14 +++ 6 files changed, 104 insertions(+), 32 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4360052..9748271 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -43,7 +43,12 @@ jobs: # The normal tar smoke test alone does not reject extra members. . ./install.ps1 $archivePath = 'artifacts/proofline-x86_64-pc-windows-msvc.tar.gz' - $binary = Get-ProoflineTarExecutable ([IO.File]::ReadAllBytes((Resolve-Path $archivePath).Path)) + $archiveFile = (Resolve-Path $archivePath).Path + $archiveLength = ([IO.FileInfo]::new($archiveFile)).Length + if ($archiveLength -le 0 -or $archiveLength -gt $script:MaxArchiveBytes) { + throw "PR-built Windows archive exceeds the installer size limit: $archiveLength bytes." + } + $binary = Get-ProoflineTarExecutable ([IO.File]::ReadAllBytes($archiveFile)) if ($binary.Length -le 0) { throw 'PR-built Windows archive contains no supported Proofline executable.' } Write-Host "Installer-compatible PR-built Windows archive validated ($($binary.Length) bytes)." tar -xzf artifacts/proofline-x86_64-pc-windows-msvc.tar.gz -C artifacts diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 5b900cc..0f082ad 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -82,6 +82,25 @@ jobs: fi fi python3 scripts/archive.py "$TARGET" + - name: Validate exact Windows release archive with installer rules + if: matrix.target == 'x86_64-pc-windows-msvc' + shell: pwsh + run: | + . ./install.ps1 + $archiveFile = (Resolve-Path 'artifacts/proofline-x86_64-pc-windows-msvc.tar.gz').Path + $archiveLength = ([IO.FileInfo]::new($archiveFile)).Length + if ($archiveLength -le 0 -or $archiveLength -gt $script:MaxArchiveBytes) { + throw "Windows release archive exceeds installer size limit: $archiveLength bytes." + } + $payload = Get-ProoflineTarExecutable ([IO.File]::ReadAllBytes($archiveFile)) + $built = (Resolve-Path 'target/x86_64-pc-windows-msvc/release/proofline.exe').Path + $sha = [Security.Cryptography.SHA256]::Create() + try { $packedDigest = [BitConverter]::ToString($sha.ComputeHash($payload)).Replace('-', '') } + finally { $sha.Dispose() } + if ($packedDigest -cne (Get-FileHash -LiteralPath $built -Algorithm SHA256).Hash) { + throw 'Packaged Windows executable differs from tested release build.' + } + Write-Host 'Published Windows archive passed installer compatibility checks.' - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: cli-${{ matrix.target }} diff --git a/.github/workflows/windows-installer.yml b/.github/workflows/windows-installer.yml index a5557a8..f9e04df 100644 --- a/.github/workflows/windows-installer.yml +++ b/.github/workflows/windows-installer.yml @@ -57,7 +57,9 @@ jobs: real-release-integration: name: Real Windows install and interruption recovery (${{ matrix.engine }}) runs-on: windows-2025 - timeout-minutes: 30 + # Up to 24 forced-termination workers x 90 seconds plus real upgrades, + # download/setup time, and test-runner overhead can exceed 30 minutes. + timeout-minutes: 60 strategy: fail-fast: false matrix: diff --git a/install.ps1 b/install.ps1 index ccc3d9f..8eb5f5a 100644 --- a/install.ps1 +++ b/install.ps1 @@ -239,11 +239,16 @@ function Get-ProoflineTarExecutable([byte[]]$ArchiveBytes) { throw 'Release executable has no valid MZ header.' } $peOffset = [BitConverter]::ToInt32($binary, 0x3c) - if ($peOffset -lt 64 -or $peOffset -gt ($binary.Length - 4) -or + if ($peOffset -lt 64 -or $peOffset -gt ($binary.Length - 6) -or $binary[$peOffset] -ne 80 -or $binary[$peOffset + 1] -ne 69 -or $binary[$peOffset + 2] -ne 0 -or $binary[$peOffset + 3] -ne 0) { throw 'Release executable has no valid PE signature.' } + # The archive name promises x86_64. A valid PE signature alone also + # accepts x86 images, which can run under WOW64 and pass --version. + if ([BitConverter]::ToUInt16($binary, $peOffset + 4) -ne 0x8664) { + throw 'Release executable has no AMD64 (x64) COFF machine type.' + } return ,$binary } @@ -412,35 +417,54 @@ function Assert-ProoflineVersionResult( } } -function Assert-ProoflineExeVersion([string]$Path, [string]$Version) { - # Run only checksum-verified images; bound both process termination - # and redirected output collection so descendants cannot hang the check. - $startInfo = [Diagnostics.ProcessStartInfo]::new() - $startInfo.FileName = $Path - $startInfo.Arguments = '--version' - $startInfo.UseShellExecute = $false - $startInfo.CreateNoWindow = $true - $startInfo.RedirectStandardOutput = $true - $startInfo.RedirectStandardError = $true - $process = [Diagnostics.Process]::new() - $process.StartInfo = $startInfo - $clock = [Diagnostics.Stopwatch]::StartNew() +function Assert-ProoflineExeVersion([string]$Path, [string]$Version, [string]$ExpectedSha256) { + # Keep a read-only handle that denies writes and deletes from the hash + # through process creation and the --version check. This closes the gap + # between a standalone Get-FileHash and launching the executable. + if ($ExpectedSha256 -cnotmatch '\A[0-9A-Fa-f]{64}\z') { + throw 'Executable version check requires an expected SHA-256 digest.' + } + Assert-ProoflineNoReparse $Path + $lockedImage = [IO.File]::Open($Path, [IO.FileMode]::Open, + [IO.FileAccess]::Read, [IO.FileShare]::Read) try { - if (-not $process.Start()) { throw 'Candidate executable did not start.' } - $outTask = $process.StandardOutput.ReadToEndAsync() - $errTask = $process.StandardError.ReadToEndAsync() - if (-not $process.WaitForExit(15000)) { - try { $process.Kill() } catch { } - [void]$process.WaitForExit(5000) - throw 'Candidate executable did not exit within 15 seconds.' + $digest = [Security.Cryptography.SHA256]::Create() + try { $actualHash = [BitConverter]::ToString($digest.ComputeHash($lockedImage)).Replace('-', '') } + finally { $digest.Dispose() } + if ($actualHash -cne $ExpectedSha256.ToUpperInvariant()) { + throw 'Executable changed before its protected version check.' } - $remaining = [int][Math]::Max(0, 15000 - $clock.ElapsedMilliseconds) - if (-not [Threading.Tasks.Task]::WaitAll([Threading.Tasks.Task[]]@($outTask, $errTask), $remaining)) { - throw 'Candidate version check exited but output streams remained open beyond 15 seconds.' + + # Bound both process termination and redirected output collection so + # descendants cannot hang the check. + $startInfo = [Diagnostics.ProcessStartInfo]::new() + $startInfo.FileName = $Path + $startInfo.Arguments = '--version' + $startInfo.UseShellExecute = $false + $startInfo.CreateNoWindow = $true + $startInfo.RedirectStandardOutput = $true + $startInfo.RedirectStandardError = $true + $process = [Diagnostics.Process]::new() + $process.StartInfo = $startInfo + $clock = [Diagnostics.Stopwatch]::StartNew() + try { + if (-not $process.Start()) { throw 'Candidate executable did not start.' } + $outTask = $process.StandardOutput.ReadToEndAsync() + $errTask = $process.StandardError.ReadToEndAsync() + if (-not $process.WaitForExit(15000)) { + try { $process.Kill() } catch { } + [void]$process.WaitForExit(5000) + throw 'Candidate executable did not exit within 15 seconds.' + } + $remaining = [int][Math]::Max(0, 15000 - $clock.ElapsedMilliseconds) + if (-not [Threading.Tasks.Task]::WaitAll([Threading.Tasks.Task[]]@($outTask, $errTask), $remaining)) { + throw 'Candidate version check exited but output streams remained open beyond 15 seconds.' + } + Assert-ProoflineVersionResult $process.ExitCode ($outTask.GetAwaiter().GetResult()) ($errTask.GetAwaiter().GetResult()) $Version } - Assert-ProoflineVersionResult $process.ExitCode ($outTask.GetAwaiter().GetResult()) ($errTask.GetAwaiter().GetResult()) $Version + finally { $process.Dispose() } } - finally { $process.Dispose() } + finally { $lockedImage.Dispose() } } function Write-ProoflineAtomicRecord([string]$Path, [string]$Content) { @@ -847,7 +871,9 @@ function Recover-ProoflinePending([string]$Directory) { if ([IO.File]::Exists($paths.damaged)) { throw 'Damaged-file evidence path already exists; manual recovery required.' } - [IO.File]::Replace($restore, $destination, $paths.damaged) + # Reuse bounded transient-lock retries without ever retrying a + # partially completed replacement or losing rejected-image evidence. + Invoke-ProoflineReplaceWithRetry $restore $destination $paths.damaged $record.oldSha256 $activeHash } else { [IO.File]::Move($restore, $destination) } @@ -1025,7 +1051,7 @@ function Install-ProoflineArchive( $stream.Flush($true) } finally { $stream.Dispose() } - Assert-ProoflineExeVersion $stage $ReleaseVersion + Assert-ProoflineExeVersion $stage $ReleaseVersion $hash if ($null -eq $oldReceipt) { [IO.File]::Move($stage, $destination) @@ -1033,7 +1059,7 @@ function Install-ProoflineArchive( throw 'Installed executable digest differs after relocation.' } try { - Assert-ProoflineExeVersion $destination $ReleaseVersion + Assert-ProoflineExeVersion $destination $ReleaseVersion $hash Set-ProoflinePendingPostcheck $pending 'passed' Write-ProoflineReceipt $receipt $ReleaseVersion $hash Clear-ProoflineJournalBackup $pending @@ -1064,7 +1090,7 @@ function Install-ProoflineArchive( if ((Get-ProoflineSha256 $destination) -cne $hash) { throw 'Upgraded executable digest differs from verified candidate.' } - Assert-ProoflineExeVersion $destination $ReleaseVersion + Assert-ProoflineExeVersion $destination $ReleaseVersion $hash Set-ProoflinePendingPostcheck $pending 'passed' Write-ProoflineReceipt $receipt $ReleaseVersion $hash try { Clear-ProoflineUpgradeFiles $paths $pending $hash } diff --git a/scripts/generate_windows_installer_fixtures.py b/scripts/generate_windows_installer_fixtures.py index 28c3691..05dd5cb 100644 --- a/scripts/generate_windows_installer_fixtures.py +++ b/scripts/generate_windows_installer_fixtures.py @@ -29,6 +29,7 @@ def pe_fixture() -> bytes: image[:2] = b"MZ" image[0x3C:0x40] = (0x80).to_bytes(4, "little") image[0x80:0x84] = b"PE\0\0" + image[0x84:0x86] = (0x8664).to_bytes(2, "little") # AMD64 COFF Machine return bytes(image) @@ -58,6 +59,11 @@ def main(destination: Path) -> None: (destination / "not-pe.tar.gz").write_bytes( pack(("proofline.exe", b"not a PE" * 128, tarfile.REGTYPE)) ) + x86_binary = bytearray(binary) + x86_binary[0x84:0x86] = (0x014C).to_bytes(2, "little") + (destination / "x86-machine.tar.gz").write_bytes( + pack(("proofline.exe", bytes(x86_binary), tarfile.REGTYPE)) + ) wrong_signature = bytearray(binary) wrong_signature[0x80:0x84] = b"NOPE" (destination / "bad-pe-signature.tar.gz").write_bytes( diff --git a/scripts/test_install_windows.ps1 b/scripts/test_install_windows.ps1 index fcde69f..2592fca 100644 --- a/scripts/test_install_windows.ps1 +++ b/scripts/test_install_windows.ps1 @@ -52,6 +52,8 @@ try { $expected[0x3c] = 0x80 $expected[0x80] = 80 $expected[0x81] = 69 + $expected[0x84] = 0x64 + $expected[0x85] = 0x86 if ($exe.Length -ne $expected.Length) { throw 'Unexpected fixture executable length.' } for ($i = 0; $i -lt $expected.Length; $i++) { if ($exe[$i] -ne $expected[$i]) { @@ -96,6 +98,18 @@ try { } if (-not $specificRejection) { throw 'Corrupt PE signature was accepted.' } } + Test-Case 'valid PE with x86 COFF Machine is rejected as non-AMD64' { + $x86 = Bytes 'x86-machine.tar.gz' + $rejectedArchitecture = $false + try { [void](Get-ProoflineTarExecutable $x86) } + catch { + if ($_.Exception.Message -notlike '*AMD64 (x64) COFF machine type*') { + throw "x86 fixture rejected for wrong reason: $($_.Exception.Message)" + } + $rejectedArchitecture = $true + } + if (-not $rejectedArchitecture) { throw 'Mislabeled x86 release was accepted.' } + } Test-Case 'checksum rejects modified archive bytes' { $modified = Bytes 'bad-digest.tar.gz' Must-Throw { Assert-ProoflineChecksum $modified $sums } From 949567260f5a8bdc418af5538e28a881bcccc606 Mon Sep 17 00:00:00 2001 From: Ayan Khan Date: Mon, 23 Nov 2026 23:54:37 +0530 Subject: [PATCH 14/21] fix(windows): repair interruption CI and address review findings --- .github/workflows/ci.yml | 11 ++++++++++- .github/workflows/windows-installer.yml | 1 + README.md | 2 ++ install.ps1 | 14 ++++++++++++-- scripts/test_install_concurrency_windows.ps1 | 8 +++++--- scripts/test_install_interruption_real_windows.ps1 | 4 ++-- 6 files changed, 32 insertions(+), 8 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9748271..f3b1e4b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -50,8 +50,17 @@ jobs: } $binary = Get-ProoflineTarExecutable ([IO.File]::ReadAllBytes($archiveFile)) if ($binary.Length -le 0) { throw 'PR-built Windows archive contains no supported Proofline executable.' } - Write-Host "Installer-compatible PR-built Windows archive validated ($($binary.Length) bytes)." tar -xzf artifacts/proofline-x86_64-pc-windows-msvc.tar.gz -C artifacts + # Require the installer parser and the smoke-tested executable to + # agree byte-for-byte by independent SHA-256 comparison. + $sha = [Security.Cryptography.SHA256]::Create() + try { $parsedDigest = [BitConverter]::ToString($sha.ComputeHash($binary)).Replace('-', '') } + finally { $sha.Dispose() } + $extractedDigest = (Get-FileHash -LiteralPath './artifacts/proofline.exe' -Algorithm SHA256).Hash + if ($parsedDigest -cne $extractedDigest) { + throw 'Installer parser output differs from the Windows executable tested by CI.' + } + Write-Host "Installer-compatible PR-built archive validated ($($binary.Length) bytes)." & ./artifacts/proofline.exe --version if ($LASTEXITCODE -ne 0) { throw "Windows executable failed" } & ./artifacts/proofline.exe setup --print diff --git a/.github/workflows/windows-installer.yml b/.github/workflows/windows-installer.yml index f9e04df..c2757f0 100644 --- a/.github/workflows/windows-installer.yml +++ b/.github/workflows/windows-installer.yml @@ -11,6 +11,7 @@ on: - 'Cargo.lock' - 'src/**' - '.github/workflows/ci.yml' + - '.github/workflows/release.yml' - '.github/workflows/windows-installer.yml' workflow_dispatch: diff --git a/README.md b/README.md index f3ad09c..c765be1 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,8 @@ powershell.exe -NoProfile -File .\install.ps1 -Version 0.5.2 -InstallDir "$env:T Re-running the installer with the same verified version does not replace the executable or receipt, but User PATH may still be updated unless `-NoModifyPath` is selected. Upgrading an installer-managed version preserves the previous executable and uses a pending recovery record; an unmanaged or inconsistent existing installation is not overwritten. No administrator privileges or machine-level PATH changes are required. +User PATH updates use a cross-session per-user mutex to serialize cooperating installers. Unrelated registry editors that do not take the mutex can still race because Windows does not offer an atomic registry compare-and-swap for this value; verify PATH after simultaneous unrelated edits. An existing oversized PATH or expandable PATH that would reinterpret percent-delimited text in the installation directory is left unchanged with a warning (the executable remains installed). + The installer script is currently distributed **in this repository**, not via a verified Windows one-liner on `proofline.sh`. Alternatively, manually download `proofline-x86_64-pc-windows-msvc.tar.gz` and its `SHA256SUMS` from the same official release, verify the SHA-256 with `Get-FileHash`, extract `proofline.exe` and place it on PATH. Windows `proofline update` (self-update invoked from the CLI) remains unsupported; re-run `install.ps1` to upgrade an installer-managed installation. After a process interruption, a later installer run uses a pending journal to complete or recover a recognized transaction. A partial first-install or pre-switch stage can be retained with an `.incomplete` suffix for diagnostics without blocking a new attempt. Errors that cannot be safely classified preserve evidence and may require manual recovery. diff --git a/install.ps1 b/install.ps1 index 8eb5f5a..bdec661 100644 --- a/install.ps1 +++ b/install.ps1 @@ -347,7 +347,8 @@ function Add-ProoflineUserPath([string]$Directory) { # Other PATH editors are not obligated to acquire this mutex; their edits # can still race with RegistryKey.SetValue (no registry compare-and-swap). $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value - $mutexName = 'Local\Proofline-UserPath-' + $sid + # HKCU Path is shared between sessions for this SID. + $mutexName = 'Global\Proofline-UserPath-' + $sid $mutex = [Threading.Mutex]::new($false, $mutexName) $locked = $false $changed = $false @@ -360,6 +361,12 @@ function Add-ProoflineUserPath([string]$Directory) { } if (-not $locked) { throw 'Another Proofline installer is updating user PATH; retry after it completes.' } $previous = Get-ProoflineUserPathRecord + # An expandable Path interprets %NAME% inside the appended directory. + # Refuse a misleading PATH write while retaining the installed binary. + if ($previous.kind -eq [Microsoft.Win32.RegistryValueKind]::ExpandString -and + $Directory -match '%[^%]+%') { + throw 'Install directory contains %VARIABLE% syntax that would expand in User PATH; use -NoModifyPath and add a safe directory manually.' + } $result = Get-ProoflineUpdatedUserPath $previous.value $Directory $previous.kind if ($null -eq $result) { Write-Host 'User PATH already contains the Proofline directory.' @@ -653,7 +660,10 @@ function Restore-ProoflinePendingBackup([string]$Pending) { if (-not [IO.File]::Exists($backup)) { return } if ([IO.File]::Exists($Pending)) { [void](Read-ProoflinePending $Pending) - [IO.File]::Delete($backup) + # The canonical journal is verified. A transiently locked backup + # must not prevent rollback; leave it for transaction cleanup. + try { [IO.File]::Delete($backup) } + catch { Write-Warning "Journal backup is locked; recovery will retain it until cleanup: $($_.Exception.Message)" } } else { [void](Read-ProoflinePending $backup) diff --git a/scripts/test_install_concurrency_windows.ps1 b/scripts/test_install_concurrency_windows.ps1 index e2d7aff..dcbf3c3 100644 --- a/scripts/test_install_concurrency_windows.ps1 +++ b/scripts/test_install_concurrency_windows.ps1 @@ -35,16 +35,18 @@ if ($Mode -eq 'Hold') { if ([IO.File]::Exists($claimed)) { throw 'Test marker was already claimed.' } try { [IO.File]::Move($marker, $claimed) } catch { throw 'Refusing to hold lock: fresh disposable test marker is unavailable or already claimed.' } + $validatedClaim = $false try { if ([IO.File]::ReadAllText($claimed) -cne "DISPOSABLE_LOCK_TEST:$HoldToken") { - # Invalid invocations must not consume another holder's valid - # marker. Atomic move back only if no new marker was created. + # Preserve an unrecognized claim if restoration fails or a + # replacement marker appeared. Never delete another test's token. if (-not [IO.File]::Exists($marker)) { [IO.File]::Move($claimed, $marker) } throw 'Refusing to hold lock: claimed marker has unexpected contents.' } + $validatedClaim = $true } finally { - if ([IO.File]::Exists($claimed)) { [IO.File]::Delete($claimed) } + if ($validatedClaim -and [IO.File]::Exists($claimed)) { [IO.File]::Delete($claimed) } } $lock = Join-Path $folder '.proofline-install.lock' $ready = Join-Path $folder '.holder-ready' diff --git a/scripts/test_install_interruption_real_windows.ps1 b/scripts/test_install_interruption_real_windows.ps1 index 1cfe44b..eaf5442 100644 --- a/scripts/test_install_interruption_real_windows.ps1 +++ b/scripts/test_install_interruption_real_windows.ps1 @@ -294,9 +294,9 @@ function Make-InstrumentedInstaller([string]$Source, [string]$Destination, [stri "`n" + ' ' + $abort + "`n" + ' try {' } elseif ($Checkpoint -eq 'fresh-after-stage') { - $target = ' Assert-ProoflineExeVersion $stage $ReleaseVersion' + + $target = ' Assert-ProoflineExeVersion $stage $ReleaseVersion $hash' + "`n`n" + ' if ($null -eq $oldReceipt) {' - $replacement = ' Assert-ProoflineExeVersion $stage $ReleaseVersion' + + $replacement = ' Assert-ProoflineExeVersion $stage $ReleaseVersion $hash' + "`n" + ' ' + $abort + "`n`n" + ' if ($null -eq $oldReceipt) {' } elseif ($Checkpoint -eq 'fresh-after-move') { From 1544f3016f988fdba6df5de6c1d4730f45fcb2bd Mon Sep 17 00:00:00 2001 From: Ayan Khan Date: Mon, 23 Nov 2026 23:57:42 +0530 Subject: [PATCH 15/21] test(windows): exercise production lock and locked-journal rollback --- scripts/test_install_concurrency_windows.ps1 | 38 ++++++++++++++------ scripts/test_install_upgrade_windows.ps1 | 24 +++++++++++++ 2 files changed, 52 insertions(+), 10 deletions(-) diff --git a/scripts/test_install_concurrency_windows.ps1 b/scripts/test_install_concurrency_windows.ps1 index dcbf3c3..0259746 100644 --- a/scripts/test_install_concurrency_windows.ps1 +++ b/scripts/test_install_concurrency_windows.ps1 @@ -48,22 +48,40 @@ if ($Mode -eq 'Hold') { finally { if ($validatedClaim -and [IO.File]::Exists($claimed)) { [IO.File]::Delete($claimed) } } - $lock = Join-Path $folder '.proofline-install.lock' - $ready = Join-Path $folder '.holder-ready' - $release = Join-Path $folder '.holder-release' - $stream = [IO.File]::Open($lock, [IO.FileMode]::OpenOrCreate, - [IO.FileAccess]::ReadWrite, [IO.FileShare]::None) - try { - [IO.File]::WriteAllText($ready, 'LOCK_HELD') + # Hold the *production* installer lock, not a separately manufactured + # FileShare.None handle. Otherwise the test passes even if the installer + # accidentally weakens its own lock sharing policy. + $driver = Split-Path -Parent $folder + if ([IO.Path]::GetDirectoryName($driver) -ine [IO.Path]::GetFullPath([IO.Path]::GetTempPath()).TrimEnd([char]'\') -or + [IO.Path]::GetFileName($driver) -cnotmatch '\Aproofline-concurrent-[0-9a-f]{32}\z' -or + [IO.Path]::GetFileName($folder) -cne 'bin') { + throw 'Holder refused a directory outside the disposable test sandbox.' + } + foreach ($path in @($driver, $folder)) { + if (([IO.File]::GetAttributes($path) -band [IO.FileAttributes]::ReparsePoint) -ne 0) { + throw 'Holder refused a reparse-point test directory.' + } + } + . (Join-Path (Split-Path -Parent $PSScriptRoot) 'install.ps1') + $script:holderOriginalReceipt = (Get-Item Function:\Read-ProoflineReceipt).ScriptBlock + $script:holderReady = Join-Path $folder '.holder-ready' + $script:holderRelease = Join-Path $folder '.holder-release' + function Read-ProoflineReceipt([string]$Path) { + # Install-ProoflineArchive reaches this function only after opening + # the production lock, so parent contention exercises that lock. + [IO.File]::WriteAllText($script:holderReady, 'LOCK_HELD') $expires = [DateTime]::UtcNow.AddSeconds(25) - while ([DateTime]::UtcNow -lt $expires -and -not [IO.File]::Exists($release)) { + while ([DateTime]::UtcNow -lt $expires -and -not [IO.File]::Exists($script:holderRelease)) { Start-Sleep -Milliseconds 100 } - if (-not [IO.File]::Exists($release)) { + if (-not [IO.File]::Exists($script:holderRelease)) { throw 'Holder timed out waiting for parent release signal.' } + return (& $script:holderOriginalReceipt $Path) } - finally { $stream.Dispose() } + $archive = [IO.File]::ReadAllBytes((Join-Path $driver 'valid.tar.gz')) + $sums = [IO.File]::ReadAllBytes((Join-Path $driver 'SHA256SUMS')) + [void](Install-ProoflineArchive $archive $sums '0.5.1' $folder) exit 0 } diff --git a/scripts/test_install_upgrade_windows.ps1 b/scripts/test_install_upgrade_windows.ps1 index ebfe69e..4c77781 100644 --- a/scripts/test_install_upgrade_windows.ps1 +++ b/scripts/test_install_upgrade_windows.ps1 @@ -341,6 +341,30 @@ try { Require (-not [IO.File]::Exists($pendingPath + '.postcheck.bak')) 'Backup was not cleaned after recovery.' Require (-not [IO.File]::Exists($pendingPath)) 'Restored journal was not cleared.' } + Check 'backup deletion lock does not block rollback from validated canonical journal' { + $dir = PrepareOld 'locked-journal-backup' + [void](MakePending $dir) + $journal = Pending 'locked-journal-backup' + Set-ProoflinePendingPostcheck $journal 'checking' + # The redundant backup can be held by an antivirus/reader. Recovery + # must restore the verified previous executable before cleanup retries. + [IO.File]::Copy($journal, $journal + '.postcheck.bak', $false) + [IO.File]::WriteAllBytes((Active 'locked-journal-backup'), (Get-ProoflineTarExecutable $script:newArchive)) + $handle = [IO.File]::Open($journal + '.postcheck.bak', [IO.FileMode]::Open, + [IO.FileAccess]::Read, [IO.FileShare]::Read) + try { + # Cleanup may fail because backup is locked, but rollback must + # already have restored the correct previous bytes. + try { Invoke-ProoflinePendingRepair $dir } catch { } + Require ((Get-ProoflineSha256 (Active 'locked-journal-backup')) -ceq $script:oldHash) 'Backup lock prevented rollback.' + Assert-ProoflineRecord (Receipt 'locked-journal-backup') '0.5.1' $script:oldHash + Require ([IO.File]::Exists($journal)) 'Locked backup cleanup discarded the canonical recovery record.' + } + finally { $handle.Dispose() } + Invoke-ProoflinePendingRepair $dir + Require (-not [IO.File]::Exists($journal)) 'Unlocked backup cleanup did not complete.' + Require (-not [IO.File]::Exists($journal + '.postcheck.bak')) 'Unlocked backup remains.' + } Check 'pre-switch repair does not rewrite matching locked old receipt' { $dir = PrepareOld 'pre-switch-matching-receipt' [void](MakePending $dir) From 5a56c542331485d1209c23081be8a157f4274267 Mon Sep 17 00:00:00 2001 From: Ayan Khan Date: Mon, 23 Nov 2026 23:59:36 +0530 Subject: [PATCH 16/21] test(windows): cover latest-release entrypoint and expandable PATH refusal --- scripts/test_install_upgrade_windows.ps1 | 24 +++++++++++++++++++++++ scripts/test_install_windows.ps1 | 25 ++++++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/scripts/test_install_upgrade_windows.ps1 b/scripts/test_install_upgrade_windows.ps1 index 4c77781..9ad228f 100644 --- a/scripts/test_install_upgrade_windows.ps1 +++ b/scripts/test_install_upgrade_windows.ps1 @@ -393,6 +393,30 @@ try { Assert-ProoflineRecord (Receipt 'rollback-matching-receipt') '0.5.1' $script:oldHash Require (-not [IO.File]::Exists((Pending 'rollback-matching-receipt'))) 'Rollback left journal.' } + Check 'latest release invocation uses pinned offline archive and passes installer postchecks' { + $dir = Join-Path $root 'latest-release-entrypoint' + $realDownload = (Get-Item Function:\Get-ProoflineOfficialBytes).ScriptBlock + try { + Set-Item Function:\Get-ProoflineOfficialBytes -Value { + param([string]$RelativePath, [int]$MaximumLength) + if ($RelativePath -ceq '/cli/latest') { + return ,([Text.Encoding]::UTF8.GetBytes("0.5.1`n")) + } + if ($RelativePath -ceq '/cli/download/0.5.1/proofline-x86_64-pc-windows-msvc.tar.gz') { + return ,$script:oldArchive + } + if ($RelativePath -ceq '/cli/download/0.5.1/SHA256SUMS') { + return ,$script:oldSums + } + throw "Unexpected official endpoint $RelativePath" + } + Invoke-ProoflineInstaller $null $dir $false + } + finally { Set-Item Function:\Get-ProoflineOfficialBytes -Value $realDownload } + Require ((Get-ProoflineSha256 (Active 'latest-release-entrypoint')) -ceq $script:oldHash) 'Latest release entrypoint installed the wrong executable.' + Assert-ProoflineRecord (Receipt 'latest-release-entrypoint') '0.5.1' $script:oldHash + Require (-not [IO.File]::Exists((Pending 'latest-release-entrypoint'))) 'Latest release entrypoint left a recovery journal.' + } Check 'pre-download installer repairs interrupted upgrade despite download outage' { $dir = PrepareOld 'predownload-outage' [void](MakePending $dir) diff --git a/scripts/test_install_windows.ps1 b/scripts/test_install_windows.ps1 index 2592fca..d826642 100644 --- a/scripts/test_install_windows.ps1 +++ b/scripts/test_install_windows.ps1 @@ -139,6 +139,31 @@ try { } finally { [Environment]::SetEnvironmentVariable($variable, $previous, 'Process') } } + Test-Case 'REG_EXPAND_SZ refuses an installation path whose percent tokens would expand' { + # Stubs make this non-mutating even if the installer regresses: the + # helper throws before any registry write can be attempted. + $realReader = (Get-Item Function:\Get-ProoflineUserPathRecord).ScriptBlock + $realCalculator = (Get-Item Function:\Get-ProoflineUpdatedUserPath).ScriptBlock + try { + Set-Item Function:\Get-ProoflineUserPathRecord -Value { + return @{ value = 'C:\safe'; kind = [Microsoft.Win32.RegistryValueKind]::ExpandString; exists = $true } + } + Set-Item Function:\Get-ProoflineUpdatedUserPath -Value { + throw 'PATH calculator reached after invalid expandable install directory.' + } + $rejected = $false + try { Add-ProoflineUserPath 'C:\literal\%PROOFLINE_UNSAFE_EXPANSION%\bin' } + catch { + if ($_.Exception.Message -notlike '*contains %VARIABLE% syntax*') { throw } + $rejected = $true + } + if (-not $rejected) { throw 'Unsafe expandable installation path was accepted.' } + } + finally { + Set-Item Function:\Get-ProoflineUpdatedUserPath -Value $realCalculator + Set-Item Function:\Get-ProoflineUserPathRecord -Value $realReader + } + } Test-Case 'PATH change is idempotent' { $directory = 'C:\Users\tester\AppData\Local\Programs\Proofline\bin' if ($null -ne (Get-ProoflineUpdatedUserPath $directory $directory)) { From bfac24adfd92e0a33b5818445ab6b26f6d62db03 Mon Sep 17 00:00:00 2001 From: Ayan Khan Date: Tue, 24 Nov 2026 00:01:18 +0530 Subject: [PATCH 17/21] fix(windows): pin install directory chain across filesystem transactions --- install.ps1 | 101 +++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 92 insertions(+), 9 deletions(-) diff --git a/install.ps1 b/install.ps1 index bdec661..33c6e02 100644 --- a/install.ps1 +++ b/install.ps1 @@ -410,6 +410,83 @@ function Assert-ProoflinePathTree([string]$Directory) { } } +function Protect-ProoflineDirectoryTree([string]$Directory, [bool]$CreateMissing) { + # Pin every ancestor (root first), denying FILE_SHARE_DELETE for the entire + # transaction. A checked directory cannot be renamed or swapped for a + # junction between validation and a later lock/open by its pathname. + # Open the reparse point itself and verify handle attributes, never the + # attributes of a separately resolved pathname. + if (-not ('ProoflineDirectoryPin' -as [type])) { + Add-Type -TypeDefinition @' +using System; +using System.ComponentModel; +using System.Runtime.InteropServices; +using Microsoft.Win32.SafeHandles; +public static class ProoflineDirectoryPin { + [StructLayout(LayoutKind.Sequential)] + private struct FileInfo { + public uint Attributes, CreationLow, CreationHigh, AccessLow, AccessHigh; + public uint WriteLow, WriteHigh, VolumeSerial, SizeHigh, SizeLow; + public uint Links, FileIndexHigh, FileIndexLow; + } + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern SafeFileHandle CreateFile(string name, uint access, + uint share, IntPtr security, uint disposition, uint flags, IntPtr template); + [DllImport("kernel32.dll", SetLastError = true)] + private static extern bool GetFileInformationByHandle(SafeFileHandle file, + out FileInfo info); + public static SafeFileHandle Open(string path) { + // FILE_READ_ATTRIBUTES; FILE_SHARE_READ | FILE_SHARE_WRITE (no delete); + // OPEN_EXISTING; BACKUP_SEMANTICS | OPEN_REPARSE_POINT. + var handle = CreateFile(path, 0x80, 0x03, IntPtr.Zero, 3, 0x02200000, IntPtr.Zero); + if (handle.IsInvalid) { + int error = Marshal.GetLastWin32Error(); + handle.Dispose(); + throw new Win32Exception(error, "Unable to pin install directory: " + path); + } + return handle; + } + public static uint Attributes(SafeFileHandle handle) { + FileInfo info; + if (!GetFileInformationByHandle(handle, out info)) + throw new Win32Exception(Marshal.GetLastWin32Error(), + "Unable to inspect pinned directory handle"); + return info.Attributes; + } +} +'@ + } + $ancestors = [Collections.Generic.List[string]]::new() + $cursor = [IO.DirectoryInfo]::new($Directory) + while ($null -ne $cursor) { + $ancestors.Add($cursor.FullName) + $cursor = $cursor.Parent + } + $guards = [Collections.Generic.List[Microsoft.Win32.SafeHandles.SafeFileHandle]]::new() + try { + for ($i = $ancestors.Count - 1; $i -ge 0; $i--) { + $path = $ancestors[$i] + if (-not [IO.Directory]::Exists($path)) { + if (-not $CreateMissing) { throw "Missing install directory: $path" } + # Parent is already pinned, so creating a missing child cannot + # be redirected through an ancestor swapped concurrently. + [IO.Directory]::CreateDirectory($path) | Out-Null + } + $handle = [ProoflineDirectoryPin]::Open($path) + $guards.Add($handle) + $attributes = [ProoflineDirectoryPin]::Attributes($handle) + if (($attributes -band 0x400) -ne 0 -or ($attributes -band 0x10) -eq 0) { + throw "Refusing reparse point or non-directory in install path: $path" + } + } + return ,$guards + } + catch { + foreach ($guard in $guards) { $guard.Dispose() } + throw + } +} + function Get-ProoflineSha256([string]$Path) { return (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash } @@ -907,17 +984,20 @@ function Recover-ProoflinePending([string]$Directory) { function Invoke-ProoflinePendingRepair([string]$Directory) { # Recover BEFORE network activity, so an outage cannot block local repair. $directory = Resolve-ProoflineInstallDir $Directory - Assert-ProoflinePathTree $directory if (-not [IO.Directory]::Exists($directory)) { return } $pending = [IO.Path]::Combine($directory, '.proofline-install.pending.json') if (-not [IO.File]::Exists($pending) -and -not [IO.File]::Exists($pending + '.postcheck.bak')) { return } - $lock = [IO.Path]::Combine($directory, '.proofline-install.lock') - Assert-ProoflineNoReparse $lock - $handle = [IO.File]::Open($lock, [IO.FileMode]::OpenOrCreate, - [IO.FileAccess]::ReadWrite, [IO.FileShare]::None) - try { Recover-ProoflinePending $directory } - finally { $handle.Dispose() } + $guards = Protect-ProoflineDirectoryTree $directory $false + try { + $lock = [IO.Path]::Combine($directory, '.proofline-install.lock') + Assert-ProoflineNoReparse $lock + $handle = [IO.File]::Open($lock, [IO.FileMode]::OpenOrCreate, + [IO.FileAccess]::ReadWrite, [IO.FileShare]::None) + try { Recover-ProoflinePending $directory } + finally { $handle.Dispose() } + } + finally { foreach ($guard in $guards) { $guard.Dispose() } } } function Test-ProoflineTransientReplaceFailure([Exception]$Error) { @@ -987,8 +1067,9 @@ function Install-ProoflineArchive( finally { $digest.Dispose() } $directory = Resolve-ProoflineInstallDir $Directory - Assert-ProoflinePathTree $directory - [IO.Directory]::CreateDirectory($directory) | Out-Null + # Pin the entire path through the lock, journal, replacement and cleanup. + $guards = Protect-ProoflineDirectoryTree $directory $true + try { $destination = [IO.Path]::Combine($directory, 'proofline.exe') $receipt = [IO.Path]::Combine($directory, '.proofline-install.receipt.json') $pending = [IO.Path]::Combine($directory, '.proofline-install.pending.json') @@ -1125,6 +1206,8 @@ function Install-ProoflineArchive( } } finally { $lockHandle.Dispose() } + } + finally { foreach ($guard in $guards) { $guard.Dispose() } } } function Invoke-ProoflineInstaller([string]$RequestedVersion, [string]$RequestedDirectory, [bool]$ModifyPath) { From c7db95e296569b69df7a65b44e215e114155c1f8 Mon Sep 17 00:00:00 2001 From: Ayan Khan Date: Tue, 24 Nov 2026 00:02:37 +0530 Subject: [PATCH 18/21] test(windows): prove pinned install directory denies rename --- scripts/test_install_windows.ps1 | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/scripts/test_install_windows.ps1 b/scripts/test_install_windows.ps1 index d826642..1be0c70 100644 --- a/scripts/test_install_windows.ps1 +++ b/scripts/test_install_windows.ps1 @@ -164,6 +164,24 @@ try { Set-Item Function:\Get-ProoflineUserPathRecord -Value $realReader } } + Test-Case 'pinned install directory cannot be renamed before releasing handles' { + $probe = Join-Path $root 'unlocked-directory-probe' + [IO.Directory]::CreateDirectory($probe) | Out-Null + [IO.Directory]::Move($probe, $probe + '-moved') + [IO.Directory]::Move($probe + '-moved', $probe) + $dir = Join-Path $root 'pinned-directory' + $guards = Protect-ProoflineDirectoryTree $dir $true + try { + $blocked = $false + try { [IO.Directory]::Move($dir, $dir + '-moved') } + catch [IO.IOException] { $blocked = $true } + if (-not $blocked) { + throw 'Pinned directory was renamed despite share-delete protection.' + } + if (-not [IO.Directory]::Exists($dir)) { throw 'Pinned directory disappeared.' } + } + finally { foreach ($guard in $guards) { $guard.Dispose() } } + } Test-Case 'PATH change is idempotent' { $directory = 'C:\Users\tester\AppData\Local\Programs\Proofline\bin' if ($null -ne (Get-ProoflineUpdatedUserPath $directory $directory)) { From 107c4da9c3dca7ba98ed9b720881115b5e666564 Mon Sep 17 00:00:00 2001 From: Ayan Khan Date: Tue, 24 Nov 2026 00:04:35 +0530 Subject: [PATCH 19/21] revert(windows): avoid unproven directory pinning semantics --- install.ps1 | 101 +++---------------------------- scripts/test_install_windows.ps1 | 18 ------ 2 files changed, 9 insertions(+), 110 deletions(-) diff --git a/install.ps1 b/install.ps1 index 33c6e02..bdec661 100644 --- a/install.ps1 +++ b/install.ps1 @@ -410,83 +410,6 @@ function Assert-ProoflinePathTree([string]$Directory) { } } -function Protect-ProoflineDirectoryTree([string]$Directory, [bool]$CreateMissing) { - # Pin every ancestor (root first), denying FILE_SHARE_DELETE for the entire - # transaction. A checked directory cannot be renamed or swapped for a - # junction between validation and a later lock/open by its pathname. - # Open the reparse point itself and verify handle attributes, never the - # attributes of a separately resolved pathname. - if (-not ('ProoflineDirectoryPin' -as [type])) { - Add-Type -TypeDefinition @' -using System; -using System.ComponentModel; -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; -public static class ProoflineDirectoryPin { - [StructLayout(LayoutKind.Sequential)] - private struct FileInfo { - public uint Attributes, CreationLow, CreationHigh, AccessLow, AccessHigh; - public uint WriteLow, WriteHigh, VolumeSerial, SizeHigh, SizeLow; - public uint Links, FileIndexHigh, FileIndexLow; - } - [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] - private static extern SafeFileHandle CreateFile(string name, uint access, - uint share, IntPtr security, uint disposition, uint flags, IntPtr template); - [DllImport("kernel32.dll", SetLastError = true)] - private static extern bool GetFileInformationByHandle(SafeFileHandle file, - out FileInfo info); - public static SafeFileHandle Open(string path) { - // FILE_READ_ATTRIBUTES; FILE_SHARE_READ | FILE_SHARE_WRITE (no delete); - // OPEN_EXISTING; BACKUP_SEMANTICS | OPEN_REPARSE_POINT. - var handle = CreateFile(path, 0x80, 0x03, IntPtr.Zero, 3, 0x02200000, IntPtr.Zero); - if (handle.IsInvalid) { - int error = Marshal.GetLastWin32Error(); - handle.Dispose(); - throw new Win32Exception(error, "Unable to pin install directory: " + path); - } - return handle; - } - public static uint Attributes(SafeFileHandle handle) { - FileInfo info; - if (!GetFileInformationByHandle(handle, out info)) - throw new Win32Exception(Marshal.GetLastWin32Error(), - "Unable to inspect pinned directory handle"); - return info.Attributes; - } -} -'@ - } - $ancestors = [Collections.Generic.List[string]]::new() - $cursor = [IO.DirectoryInfo]::new($Directory) - while ($null -ne $cursor) { - $ancestors.Add($cursor.FullName) - $cursor = $cursor.Parent - } - $guards = [Collections.Generic.List[Microsoft.Win32.SafeHandles.SafeFileHandle]]::new() - try { - for ($i = $ancestors.Count - 1; $i -ge 0; $i--) { - $path = $ancestors[$i] - if (-not [IO.Directory]::Exists($path)) { - if (-not $CreateMissing) { throw "Missing install directory: $path" } - # Parent is already pinned, so creating a missing child cannot - # be redirected through an ancestor swapped concurrently. - [IO.Directory]::CreateDirectory($path) | Out-Null - } - $handle = [ProoflineDirectoryPin]::Open($path) - $guards.Add($handle) - $attributes = [ProoflineDirectoryPin]::Attributes($handle) - if (($attributes -band 0x400) -ne 0 -or ($attributes -band 0x10) -eq 0) { - throw "Refusing reparse point or non-directory in install path: $path" - } - } - return ,$guards - } - catch { - foreach ($guard in $guards) { $guard.Dispose() } - throw - } -} - function Get-ProoflineSha256([string]$Path) { return (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash } @@ -984,20 +907,17 @@ function Recover-ProoflinePending([string]$Directory) { function Invoke-ProoflinePendingRepair([string]$Directory) { # Recover BEFORE network activity, so an outage cannot block local repair. $directory = Resolve-ProoflineInstallDir $Directory + Assert-ProoflinePathTree $directory if (-not [IO.Directory]::Exists($directory)) { return } $pending = [IO.Path]::Combine($directory, '.proofline-install.pending.json') if (-not [IO.File]::Exists($pending) -and -not [IO.File]::Exists($pending + '.postcheck.bak')) { return } - $guards = Protect-ProoflineDirectoryTree $directory $false - try { - $lock = [IO.Path]::Combine($directory, '.proofline-install.lock') - Assert-ProoflineNoReparse $lock - $handle = [IO.File]::Open($lock, [IO.FileMode]::OpenOrCreate, - [IO.FileAccess]::ReadWrite, [IO.FileShare]::None) - try { Recover-ProoflinePending $directory } - finally { $handle.Dispose() } - } - finally { foreach ($guard in $guards) { $guard.Dispose() } } + $lock = [IO.Path]::Combine($directory, '.proofline-install.lock') + Assert-ProoflineNoReparse $lock + $handle = [IO.File]::Open($lock, [IO.FileMode]::OpenOrCreate, + [IO.FileAccess]::ReadWrite, [IO.FileShare]::None) + try { Recover-ProoflinePending $directory } + finally { $handle.Dispose() } } function Test-ProoflineTransientReplaceFailure([Exception]$Error) { @@ -1067,9 +987,8 @@ function Install-ProoflineArchive( finally { $digest.Dispose() } $directory = Resolve-ProoflineInstallDir $Directory - # Pin the entire path through the lock, journal, replacement and cleanup. - $guards = Protect-ProoflineDirectoryTree $directory $true - try { + Assert-ProoflinePathTree $directory + [IO.Directory]::CreateDirectory($directory) | Out-Null $destination = [IO.Path]::Combine($directory, 'proofline.exe') $receipt = [IO.Path]::Combine($directory, '.proofline-install.receipt.json') $pending = [IO.Path]::Combine($directory, '.proofline-install.pending.json') @@ -1206,8 +1125,6 @@ function Install-ProoflineArchive( } } finally { $lockHandle.Dispose() } - } - finally { foreach ($guard in $guards) { $guard.Dispose() } } } function Invoke-ProoflineInstaller([string]$RequestedVersion, [string]$RequestedDirectory, [bool]$ModifyPath) { diff --git a/scripts/test_install_windows.ps1 b/scripts/test_install_windows.ps1 index 1be0c70..d826642 100644 --- a/scripts/test_install_windows.ps1 +++ b/scripts/test_install_windows.ps1 @@ -164,24 +164,6 @@ try { Set-Item Function:\Get-ProoflineUserPathRecord -Value $realReader } } - Test-Case 'pinned install directory cannot be renamed before releasing handles' { - $probe = Join-Path $root 'unlocked-directory-probe' - [IO.Directory]::CreateDirectory($probe) | Out-Null - [IO.Directory]::Move($probe, $probe + '-moved') - [IO.Directory]::Move($probe + '-moved', $probe) - $dir = Join-Path $root 'pinned-directory' - $guards = Protect-ProoflineDirectoryTree $dir $true - try { - $blocked = $false - try { [IO.Directory]::Move($dir, $dir + '-moved') } - catch [IO.IOException] { $blocked = $true } - if (-not $blocked) { - throw 'Pinned directory was renamed despite share-delete protection.' - } - if (-not [IO.Directory]::Exists($dir)) { throw 'Pinned directory disappeared.' } - } - finally { foreach ($guard in $guards) { $guard.Dispose() } } - } Test-Case 'PATH change is idempotent' { $directory = 'C:\Users\tester\AppData\Local\Programs\Proofline\bin' if ($null -ne (Get-ProoflineUpdatedUserPath $directory $directory)) { From 9a007f28268968aea9890fe598ea3a910650b37a Mon Sep 17 00:00:00 2001 From: Ayan Khan Date: Tue, 24 Nov 2026 00:30:05 +0530 Subject: [PATCH 20/21] fix(windows): close outstanding installer security and review regressions --- .github/workflows/ci.yml | 32 ++--- .github/workflows/release.yml | 23 ++-- .github/workflows/windows-installer.yml | 1 + README.md | 2 +- install.ps1 | 111 ++++++++++++++++-- scripts/check_windows_release_archive.ps1 | 30 +++++ scripts/test_install_concurrency_windows.ps1 | 5 +- scripts/test_install_syntax_windows.ps1 | 3 +- scripts/test_install_upgrade_real_windows.ps1 | 16 ++- scripts/test_install_upgrade_windows.ps1 | 57 +++++++-- scripts/test_install_windows.ps1 | 32 +++++ 11 files changed, 249 insertions(+), 63 deletions(-) create mode 100644 scripts/check_windows_release_archive.ps1 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f3b1e4b..15a0556 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -37,30 +37,20 @@ jobs: persist-credentials: false - run: cargo build --release --locked --target x86_64-pc-windows-msvc - run: python scripts/archive.py x86_64-pc-windows-msvc - - shell: pwsh + - name: Check packaged archive with PowerShell 5.1 and PowerShell 7 + shell: pwsh run: | - # Reject a packaged archive that the proposed installer cannot read. - # The normal tar smoke test alone does not reject extra members. - . ./install.ps1 - $archivePath = 'artifacts/proofline-x86_64-pc-windows-msvc.tar.gz' - $archiveFile = (Resolve-Path $archivePath).Path - $archiveLength = ([IO.FileInfo]::new($archiveFile)).Length - if ($archiveLength -le 0 -or $archiveLength -gt $script:MaxArchiveBytes) { - throw "PR-built Windows archive exceeds the installer size limit: $archiveLength bytes." + $archive = 'artifacts/proofline-x86_64-pc-windows-msvc.tar.gz' + $built = 'target/x86_64-pc-windows-msvc/release/proofline.exe' + foreach ($engine in @('powershell.exe', 'pwsh.exe')) { + & $engine -NoProfile -NonInteractive -File scripts/check_windows_release_archive.ps1 -ArchivePath $archive -ExecutablePath $built + if ($LASTEXITCODE -ne 0) { throw "$engine rejected the packaged Windows executable." } } - $binary = Get-ProoflineTarExecutable ([IO.File]::ReadAllBytes($archiveFile)) - if ($binary.Length -le 0) { throw 'PR-built Windows archive contains no supported Proofline executable.' } - tar -xzf artifacts/proofline-x86_64-pc-windows-msvc.tar.gz -C artifacts - # Require the installer parser and the smoke-tested executable to - # agree byte-for-byte by independent SHA-256 comparison. - $sha = [Security.Cryptography.SHA256]::Create() - try { $parsedDigest = [BitConverter]::ToString($sha.ComputeHash($binary)).Replace('-', '') } - finally { $sha.Dispose() } - $extractedDigest = (Get-FileHash -LiteralPath './artifacts/proofline.exe' -Algorithm SHA256).Hash - if ($parsedDigest -cne $extractedDigest) { - throw 'Installer parser output differs from the Windows executable tested by CI.' + tar -xzf $archive -C artifacts + if ((Get-FileHash -LiteralPath './artifacts/proofline.exe' -Algorithm SHA256).Hash -cne + (Get-FileHash -LiteralPath $built -Algorithm SHA256).Hash) { + throw 'Smoke-tested Windows executable differs from installer-validated archive.' } - Write-Host "Installer-compatible PR-built archive validated ($($binary.Length) bytes)." & ./artifacts/proofline.exe --version if ($LASTEXITCODE -ne 0) { throw "Windows executable failed" } & ./artifacts/proofline.exe setup --print diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 0f082ad..647dfd3 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -82,25 +82,18 @@ jobs: fi fi python3 scripts/archive.py "$TARGET" - - name: Validate exact Windows release archive with installer rules + - name: Validate packaged Windows release with both PowerShell engines if: matrix.target == 'x86_64-pc-windows-msvc' shell: pwsh run: | - . ./install.ps1 - $archiveFile = (Resolve-Path 'artifacts/proofline-x86_64-pc-windows-msvc.tar.gz').Path - $archiveLength = ([IO.FileInfo]::new($archiveFile)).Length - if ($archiveLength -le 0 -or $archiveLength -gt $script:MaxArchiveBytes) { - throw "Windows release archive exceeds installer size limit: $archiveLength bytes." + $archive = 'artifacts/proofline-x86_64-pc-windows-msvc.tar.gz' + $built = 'target/x86_64-pc-windows-msvc/release/proofline.exe' + # Validate exactly the archive being uploaded, not the separate + # Checks workflow build. Both engines must accept its gzip stream. + foreach ($engine in @('powershell.exe', 'pwsh.exe')) { + & $engine -NoProfile -NonInteractive -File scripts/check_windows_release_archive.ps1 -ArchivePath $archive -ExecutablePath $built + if ($LASTEXITCODE -ne 0) { throw "$engine rejected the release archive." } } - $payload = Get-ProoflineTarExecutable ([IO.File]::ReadAllBytes($archiveFile)) - $built = (Resolve-Path 'target/x86_64-pc-windows-msvc/release/proofline.exe').Path - $sha = [Security.Cryptography.SHA256]::Create() - try { $packedDigest = [BitConverter]::ToString($sha.ComputeHash($payload)).Replace('-', '') } - finally { $sha.Dispose() } - if ($packedDigest -cne (Get-FileHash -LiteralPath $built -Algorithm SHA256).Hash) { - throw 'Packaged Windows executable differs from tested release build.' - } - Write-Host 'Published Windows archive passed installer compatibility checks.' - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: cli-${{ matrix.target }} diff --git a/.github/workflows/windows-installer.yml b/.github/workflows/windows-installer.yml index c2757f0..91a64cb 100644 --- a/.github/workflows/windows-installer.yml +++ b/.github/workflows/windows-installer.yml @@ -6,6 +6,7 @@ on: - 'install.ps1' - 'scripts/test_install*windows.ps1' - 'scripts/generate_windows_installer_fixtures.py' + - 'scripts/check_windows_release_archive.ps1' - 'scripts/archive.py' - 'Cargo.toml' - 'Cargo.lock' diff --git a/README.md b/README.md index c765be1..7e6122c 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ powershell.exe -NoProfile -File .\install.ps1 -Version 0.5.2 -InstallDir "$env:T Re-running the installer with the same verified version does not replace the executable or receipt, but User PATH may still be updated unless `-NoModifyPath` is selected. Upgrading an installer-managed version preserves the previous executable and uses a pending recovery record; an unmanaged or inconsistent existing installation is not overwritten. No administrator privileges or machine-level PATH changes are required. -User PATH updates use a cross-session per-user mutex to serialize cooperating installers. Unrelated registry editors that do not take the mutex can still race because Windows does not offer an atomic registry compare-and-swap for this value; verify PATH after simultaneous unrelated edits. An existing oversized PATH or expandable PATH that would reinterpret percent-delimited text in the installation directory is left unchanged with a warning (the executable remains installed). +User PATH updates use a cross-session per-user mutex to serialize cooperating installers. Unrelated registry editors that do not take the mutex can still race because Windows does not offer an atomic registry compare-and-swap for this value; verify PATH after simultaneous unrelated edits. If appending the directory would exceed the 30,000-character User PATH safety threshold, or REG_EXPAND_SZ would reinterpret percent-delimited tokens in the literal installation directory, the installer leaves PATH unchanged and warns rather than claiming that `proofline` is discoverable by name (the verified executable remains installed). The installer script is currently distributed **in this repository**, not via a verified Windows one-liner on `proofline.sh`. Alternatively, manually download `proofline-x86_64-pc-windows-msvc.tar.gz` and its `SHA256SUMS` from the same official release, verify the SHA-256 with `Get-FileHash`, extract `proofline.exe` and place it on PATH. diff --git a/install.ps1 b/install.ps1 index bdec661..ce6d6ef 100644 --- a/install.ps1 +++ b/install.ps1 @@ -410,6 +410,86 @@ function Assert-ProoflinePathTree([string]$Directory) { } } +function Protect-ProoflineDirectoryTree([string]$Directory, [bool]$CreateMissing) { + # Retain handles for all existing ancestors for the entire install/repair + # transaction, not merely a path-string check. FILE_LIST_DIRECTORY is + # essential: metadata-only 0x80 handles do NOT prevent directory renames. + # Denying FILE_SHARE_DELETE then prevents a checked ancestor from being + # replaced with a junction while child paths are being opened. + if (-not ('ProoflinePinnedDirectory' -as [type])) { + Add-Type -TypeDefinition @' +using System; +using System.ComponentModel; +using System.Runtime.InteropServices; +using Microsoft.Win32.SafeHandles; +public static class ProoflinePinnedDirectory { + [StructLayout(LayoutKind.Sequential)] + private struct Info { + public uint Attributes, CreationLow, CreationHigh, AccessLow, AccessHigh; + public uint WriteLow, WriteHigh, VolumeSerial, SizeHigh, SizeLow; + public uint Links, IndexHigh, IndexLow; + } + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern SafeFileHandle CreateFile(string path, uint access, + uint share, IntPtr security, uint disposition, uint flags, IntPtr template); + [DllImport("kernel32.dll", SetLastError = true)] + private static extern bool GetFileInformationByHandle(SafeFileHandle file, out Info info); + public static SafeFileHandle Open(string path) { + // SYNCHRONIZE | FILE_READ_ATTRIBUTES | FILE_LIST_DIRECTORY: + // list-directory access makes the no-FILE_SHARE_DELETE lock effective. + // BACKUP_SEMANTICS permits directory handles; OPEN_REPARSE_POINT ensures + // the handle identifies the link itself, not a redirected target. + SafeFileHandle h = CreateFile(path, 0x00100081u, 0x03u, IntPtr.Zero, + 3u, 0x02200000u, IntPtr.Zero); + if (h.IsInvalid) { + int error = Marshal.GetLastWin32Error(); + h.Dispose(); + throw new Win32Exception(error, "Unable to pin installation directory: " + path); + } + return h; + } + public static uint GetAttributes(SafeFileHandle h) { + Info info; + if (!GetFileInformationByHandle(h, out info)) + throw new Win32Exception(Marshal.GetLastWin32Error(), + "Unable to inspect pinned directory"); + return info.Attributes; + } +} +'@ + } + $parents = [Collections.Generic.List[string]]::new() + $cursor = [IO.DirectoryInfo]::new($Directory) + while ($null -ne $cursor) { + $parents.Add($cursor.FullName) + $cursor = $cursor.Parent + } + $handles = [Collections.Generic.List[Microsoft.Win32.SafeHandles.SafeFileHandle]]::new() + try { + for ($i = $parents.Count - 1; $i -ge 0; $i--) { + $path = $parents[$i] + if (-not [IO.Directory]::Exists($path)) { + if (-not $CreateMissing) { throw "Installation directory is missing: $path" } + # All already-existing ancestors are pinned, so an attacker + # cannot swap a parent for a junction during this creation. + [IO.Directory]::CreateDirectory($path) | Out-Null + } + $handle = [ProoflinePinnedDirectory]::Open($path) + $handles.Add($handle) + $attributes = [ProoflinePinnedDirectory]::GetAttributes($handle) + if (($attributes -band 0x400) -ne 0 -or + ($attributes -band 0x10) -eq 0) { + throw "Refusing a reparse point or non-directory in installation path: $path" + } + } + return ,$handles + } + catch { + foreach ($handle in $handles) { $handle.Dispose() } + throw + } +} + function Get-ProoflineSha256([string]$Path) { return (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash } @@ -907,17 +987,20 @@ function Recover-ProoflinePending([string]$Directory) { function Invoke-ProoflinePendingRepair([string]$Directory) { # Recover BEFORE network activity, so an outage cannot block local repair. $directory = Resolve-ProoflineInstallDir $Directory - Assert-ProoflinePathTree $directory if (-not [IO.Directory]::Exists($directory)) { return } - $pending = [IO.Path]::Combine($directory, '.proofline-install.pending.json') - if (-not [IO.File]::Exists($pending) -and - -not [IO.File]::Exists($pending + '.postcheck.bak')) { return } - $lock = [IO.Path]::Combine($directory, '.proofline-install.lock') - Assert-ProoflineNoReparse $lock - $handle = [IO.File]::Open($lock, [IO.FileMode]::OpenOrCreate, - [IO.FileAccess]::ReadWrite, [IO.FileShare]::None) - try { Recover-ProoflinePending $directory } - finally { $handle.Dispose() } + $guards = Protect-ProoflineDirectoryTree $directory $false + try { + $pending = [IO.Path]::Combine($directory, '.proofline-install.pending.json') + if (-not [IO.File]::Exists($pending) -and + -not [IO.File]::Exists($pending + '.postcheck.bak')) { return } + $lock = [IO.Path]::Combine($directory, '.proofline-install.lock') + Assert-ProoflineNoReparse $lock + $handle = [IO.File]::Open($lock, [IO.FileMode]::OpenOrCreate, + [IO.FileAccess]::ReadWrite, [IO.FileShare]::None) + try { Recover-ProoflinePending $directory } + finally { $handle.Dispose() } + } + finally { foreach ($guard in $guards) { $guard.Dispose() } } } function Test-ProoflineTransientReplaceFailure([Exception]$Error) { @@ -987,9 +1070,9 @@ function Install-ProoflineArchive( finally { $digest.Dispose() } $directory = Resolve-ProoflineInstallDir $Directory - Assert-ProoflinePathTree $directory - [IO.Directory]::CreateDirectory($directory) | Out-Null - $destination = [IO.Path]::Combine($directory, 'proofline.exe') + $guards = Protect-ProoflineDirectoryTree $directory $true + try { + $destination = [IO.Path]::Combine($directory, 'proofline.exe') $receipt = [IO.Path]::Combine($directory, '.proofline-install.receipt.json') $pending = [IO.Path]::Combine($directory, '.proofline-install.pending.json') $lock = [IO.Path]::Combine($directory, '.proofline-install.lock') @@ -1125,6 +1208,8 @@ function Install-ProoflineArchive( } } finally { $lockHandle.Dispose() } + } + finally { foreach ($guard in $guards) { $guard.Dispose() } } } function Invoke-ProoflineInstaller([string]$RequestedVersion, [string]$RequestedDirectory, [bool]$ModifyPath) { diff --git a/scripts/check_windows_release_archive.ps1 b/scripts/check_windows_release_archive.ps1 new file mode 100644 index 0000000..ae420fe --- /dev/null +++ b/scripts/check_windows_release_archive.ps1 @@ -0,0 +1,30 @@ +#requires -Version 5.1 +# Validate the exact Windows release archive using the same parser and limits +# as install.ps1. Invoked under BOTH Windows PowerShell 5.1 and PowerShell 7. +[CmdletBinding()] +param( + [Parameter(Mandatory = $true)][string]$ArchivePath, + [Parameter(Mandatory = $true)][string]$ExecutablePath +) +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' + +. (Join-Path (Split-Path -Parent $PSScriptRoot) 'install.ps1') +$archive = (Resolve-Path -LiteralPath $ArchivePath).Path +$executable = (Resolve-Path -LiteralPath $ExecutablePath).Path +$archiveLength = ([IO.FileInfo]::new($archive)).Length +if ($archiveLength -le 0 -or $archiveLength -gt $script:MaxArchiveBytes) { + throw "Packaged Windows archive violates installer compressed-size limit: $archiveLength bytes." +} +$payload = Get-ProoflineTarExecutable ([IO.File]::ReadAllBytes($archive)) +if ($payload.Length -le 0) { + throw 'Packaged Windows archive has no installable executable.' +} +$sha = [Security.Cryptography.SHA256]::Create() +try { $payloadHash = [BitConverter]::ToString($sha.ComputeHash($payload)).Replace('-', '') } +finally { $sha.Dispose() } +$expectedHash = (Get-FileHash -LiteralPath $executable -Algorithm SHA256).Hash +if ($payloadHash -cne $expectedHash) { + throw 'Windows installer-extracted payload differs from the version-tested build.' +} +Write-Host "Windows archive compatible with PowerShell $($PSVersionTable.PSVersion): $payloadHash" diff --git a/scripts/test_install_concurrency_windows.ps1 b/scripts/test_install_concurrency_windows.ps1 index 0259746..cc92a85 100644 --- a/scripts/test_install_concurrency_windows.ps1 +++ b/scripts/test_install_concurrency_windows.ps1 @@ -117,12 +117,15 @@ try { $script:newHash = Digest-Bytes (Get-ProoflineTarExecutable $newArchive) # This is test-only: artificial PE fixtures must never be executed. - function Assert-ProoflineExeVersion([string]$Path, [string]$Version) { + function Assert-ProoflineExeVersion([string]$Path, [string]$Version, [string]$ExpectedSha256) { $expected = switch ($Version) { '0.5.1' { $script:oldHash; break } '0.5.2' { $script:newHash; break } default { throw "Unexpected fixture version $Version" } } + if ($ExpectedSha256 -cne $expected) { + throw "Version check for $Version omitted or supplied an incorrect digest." + } if ((Get-ProoflineSha256 $Path) -cne $expected) { throw "Invalid fixture contents for $Version" } diff --git a/scripts/test_install_syntax_windows.ps1 b/scripts/test_install_syntax_windows.ps1 index 2c62592..8c95a5c 100644 --- a/scripts/test_install_syntax_windows.ps1 +++ b/scripts/test_install_syntax_windows.ps1 @@ -5,7 +5,8 @@ param() Set-StrictMode -Version Latest $ErrorActionPreference = 'Stop' $root = Split-Path -Parent $PSScriptRoot -$paths = @((Join-Path $root 'install.ps1')) +$paths = @((Join-Path $root 'install.ps1'), + (Join-Path $PSScriptRoot 'check_windows_release_archive.ps1')) $paths += @(Get-ChildItem -LiteralPath $PSScriptRoot -File -Filter 'test_install*windows.ps1' | ForEach-Object { $_.FullName }) foreach ($path in $paths) { diff --git a/scripts/test_install_upgrade_real_windows.ps1 b/scripts/test_install_upgrade_real_windows.ps1 index 7392e1a..1a99ba4 100644 --- a/scripts/test_install_upgrade_real_windows.ps1 +++ b/scripts/test_install_upgrade_real_windows.ps1 @@ -125,7 +125,21 @@ try { } Write-Host "PASS upgrade to v0.5.2; hash $($after.BinarySha256)" - Install-Release '0.5.2' + # Hold both published files read-only with deny-write/delete sharing + # while the same-version installer runs in a fresh process. Hash-only + # checks would miss a byte-identical rewrite. + $heldExe = [IO.File]::Open((Join-Path $bin 'proofline.exe'), [IO.FileMode]::Open, + [IO.FileAccess]::Read, [IO.FileShare]::Read) + $heldReceipt = $null + try { + $heldReceipt = [IO.File]::Open((Join-Path $bin '.proofline-install.receipt.json'), + [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::Read) + Install-Release '0.5.2' + } + finally { + if ($null -ne $heldReceipt) { $heldReceipt.Dispose() } + $heldExe.Dispose() + } $repeat = Check-Release '0.5.2' if ($repeat.BinarySha256 -cne $after.BinarySha256 -or $repeat.ReceiptSha256 -cne $after.ReceiptSha256) { diff --git a/scripts/test_install_upgrade_windows.ps1 b/scripts/test_install_upgrade_windows.ps1 index 9ad228f..84a383f 100644 --- a/scripts/test_install_upgrade_windows.ps1 +++ b/scripts/test_install_upgrade_windows.ps1 @@ -105,25 +105,33 @@ try { $script:smokeCount = 0 $script:failInstalledPostcheckPath = $null $script:failInstalledPostcheckVersion = '0.5.2' - function Assert-ProoflineExeVersion([string]$Path, [string]$Version) { + function Assert-ProoflineExeVersion([string]$Path, [string]$Version, [string]$ExpectedSha256) { $script:smokeCount++ - if ($null -ne $script:failInstalledPostcheckPath -and - $Path -ieq $script:failInstalledPostcheckPath -and - $Version -ceq $script:failInstalledPostcheckVersion) { - # Only the installed copy fails, never the staged verified image. - throw 'Simulated installed executable postcheck failure.' - } - $digest = Get-ProoflineSha256 $Path $expected = switch ($Version) { '0.5.1' { $script:oldHash; break } '0.5.2' { $script:newHash; break } default { throw "Unexpected test-only version $Version" } } - if ($digest -cne $expected) { + if ($ExpectedSha256 -cne $expected) { + throw "Version checker for $Version received a missing or wrong verified digest." + } + if ((Get-ProoflineSha256 $Path) -cne $expected) { throw "Test fixture for $Version has unexpected digest." } + if ($null -ne $script:failInstalledPostcheckPath -and + $Path -ieq $script:failInstalledPostcheckPath -and + $Version -ceq $script:failInstalledPostcheckVersion) { + # Only the installed copy fails, never the staged verified image. + throw 'Simulated installed executable postcheck failure.' + } } + Check 'offline version checker enforces caller supplied SHA-256' { + $dir = PrepareOld 'version-digest-contract' + Must-Throw { Assert-ProoflineExeVersion (Active 'version-digest-contract') '0.5.1' $null } + Must-Throw { Assert-ProoflineExeVersion (Active 'version-digest-contract') '0.5.1' $script:newHash } + Assert-ProoflineExeVersion (Active 'version-digest-contract') '0.5.1' $script:oldHash + } Check 'interrupted fresh install cleans only verified matching stage' { $dir = Join-Path $root 'fresh-stage' [IO.Directory]::CreateDirectory($dir) | Out-Null @@ -341,6 +349,22 @@ try { Require (-not [IO.File]::Exists($pendingPath + '.postcheck.bak')) 'Backup was not cleaned after recovery.' Require (-not [IO.File]::Exists($pendingPath)) 'Restored journal was not cleared.' } + Check 'canonical passed postcheck takes precedence over stale checking backup' { + $dir = PrepareOld 'passed-plus-stale-checking' + [void](MakePending $dir) + $journal = Pending 'passed-plus-stale-checking' + Set-ProoflinePendingPostcheck $journal 'checking' + $checkingCopy = [IO.File]::ReadAllBytes($journal) + Set-ProoflinePendingPostcheck $journal 'passed' + [IO.File]::WriteAllBytes($journal + '.postcheck.bak', $checkingCopy) + [IO.File]::WriteAllBytes((Active 'passed-plus-stale-checking'), + (Get-ProoflineTarExecutable $script:newArchive)) + Invoke-ProoflinePendingRepair $dir + Require ((Get-ProoflineSha256 (Active 'passed-plus-stale-checking')) -ceq $script:newHash) 'Stale checking backup rolled back a passed image.' + Assert-ProoflineRecord (Receipt 'passed-plus-stale-checking') '0.5.2' $script:newHash + Require (-not [IO.File]::Exists($journal)) 'Canonical passed journal remains after recovery.' + Require (-not [IO.File]::Exists($journal + '.postcheck.bak')) 'Stale checking backup remains after recovery.' + } Check 'backup deletion lock does not block rollback from validated canonical journal' { $dir = PrepareOld 'locked-journal-backup' [void](MakePending $dir) @@ -508,7 +532,20 @@ try { $dir = PrepareOld 'repeat' [void](Install-ProoflineArchive $script:newArchive $script:newSums '0.5.2' $dir) $before = $script:smokeCount - [void](Install-ProoflineArchive $script:newArchive $script:newSums '0.5.2' $dir) + # Read-only deny-write handles ensure a byte-identical rewrite cannot + # pass the test just because the final digests still match. + $heldExe = [IO.File]::Open((Active 'repeat'), [IO.FileMode]::Open, + [IO.FileAccess]::Read, [IO.FileShare]::Read) + $heldReceipt = $null + try { + $heldReceipt = [IO.File]::Open((Receipt 'repeat'), [IO.FileMode]::Open, + [IO.FileAccess]::Read, [IO.FileShare]::Read) + [void](Install-ProoflineArchive $script:newArchive $script:newSums '0.5.2' $dir) + } + finally { + if ($null -ne $heldReceipt) { $heldReceipt.Dispose() } + $heldExe.Dispose() + } Require ($script:smokeCount -eq $before) 'No-op installation executed the pre-existing local executable.' Require ((Get-ProoflineSha256 (Active 'repeat')) -ceq $script:newHash) 'Repeat changed active bytes.' Assert-ProoflineRecord (Receipt 'repeat') '0.5.2' $script:newHash diff --git a/scripts/test_install_windows.ps1 b/scripts/test_install_windows.ps1 index d826642..c0b10ff 100644 --- a/scripts/test_install_windows.ps1 +++ b/scripts/test_install_windows.ps1 @@ -164,6 +164,38 @@ try { Set-Item Function:\Get-ProoflineUserPathRecord -Value $realReader } } + Test-Case 'pinned installation directory and ancestor resist rename' { + # A plain directory is renameable; pinning must make it unavailable + # for rename until the entire installer transaction completes. + $probe = Join-Path $root 'unpinned-control' + [IO.Directory]::CreateDirectory($probe) | Out-Null + [IO.Directory]::Move($probe, $probe + '-moved') + [IO.Directory]::Move($probe + '-moved', $probe) + + $parent = Join-Path $root 'pin-parent' + $child = Join-Path $parent 'bin' + $guards = Protect-ProoflineDirectoryTree $child $true + try { + if ($guards.Count -lt 2) { throw 'Directory pinning returned too few handles.' } + foreach ($guard in $guards) { + if ($guard.IsClosed -or $guard.IsInvalid) { + throw 'Directory guard handle was closed before the transaction.' + } + } + foreach ($testPath in @($child, $parent)) { + $blocked = $false + try { [IO.Directory]::Move($testPath, $testPath + '-moved') } + catch [IO.IOException] { $blocked = $true } + if (-not $blocked) { + throw "Pinned directory was renamed while its guard was held: $testPath" + } + if (-not [IO.Directory]::Exists($testPath)) { + throw "Pinned directory disappeared: $testPath" + } + } + } + finally { foreach ($guard in $guards) { $guard.Dispose() } } + } Test-Case 'PATH change is idempotent' { $directory = 'C:\Users\tester\AppData\Local\Programs\Proofline\bin' if ($null -ne (Get-ProoflineUpdatedUserPath $directory $directory)) { From efa6fedef57ae017598bb060420b6bf334913a91 Mon Sep 17 00:00:00 2001 From: Ayan Khan Date: Tue, 24 Nov 2026 11:48:39 +0530 Subject: [PATCH 21/21] fix(windows): recover corrupt journals and verify recovery ordering --- .github/workflows/windows-installer.yml | 23 ++++++++ install.ps1 | 28 +++++++++- scripts/check_windows_release_archive.ps1 | 22 ++++++-- scripts/test_install_concurrency_windows.ps1 | 22 ++++---- ...test_install_interruption_real_windows.ps1 | 36 +++++++++++- scripts/test_install_upgrade_windows.ps1 | 55 +++++++++++++++++++ 6 files changed, 167 insertions(+), 19 deletions(-) diff --git a/.github/workflows/windows-installer.yml b/.github/workflows/windows-installer.yml index 91a64cb..86d3896 100644 --- a/.github/workflows/windows-installer.yml +++ b/.github/workflows/windows-installer.yml @@ -20,7 +20,28 @@ permissions: contents: read jobs: + syntax-preflight: + name: Installer syntax (${{ matrix.engine }}) + runs-on: windows-2025 + timeout-minutes: 10 + strategy: + fail-fast: false + matrix: + engine: ['powershell.exe', 'pwsh.exe'] + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Parse Windows installer and test scripts + shell: pwsh + env: + TEST_ENGINE: ${{ matrix.engine }} + run: | + & $env:TEST_ENGINE -NoProfile -NonInteractive -File scripts/test_install_syntax_windows.ps1 + if ($LASTEXITCODE -ne 0) { throw "Installer syntax preflight failed: $env:TEST_ENGINE" } + offline-validation: + needs: syntax-preflight name: Installer offline tests (${{ matrix.engine }}) runs-on: windows-2025 timeout-minutes: 20 @@ -57,6 +78,7 @@ jobs: real-release-integration: + needs: syntax-preflight name: Real Windows install and interruption recovery (${{ matrix.engine }}) runs-on: windows-2025 # Up to 24 forced-termination workers x 90 seconds plus real upgrades, @@ -88,6 +110,7 @@ jobs: if ($LASTEXITCODE -ne 0) { throw "Real interruption recovery failed: $LASTEXITCODE" } isolated-user-path: + needs: syntax-preflight name: Default installer PATH persistence (${{ matrix.engine }}) # A separate GitHub-hosted VM provides a disposable Windows user profile. # No other job or test in this workflow shares its HKCU registry hive. diff --git a/install.ps1 b/install.ps1 index ce6d6ef..0438258 100644 --- a/install.ps1 +++ b/install.ps1 @@ -739,9 +739,31 @@ function Restore-ProoflinePendingBackup([string]$Pending) { foreach ($path in @($Pending, $backup)) { Assert-ProoflineNoReparse $path } if (-not [IO.File]::Exists($backup)) { return } if ([IO.File]::Exists($Pending)) { - [void](Read-ProoflinePending $Pending) - # The canonical journal is verified. A transiently locked backup - # must not prevent rollback; leave it for transaction cleanup. + try { + # A valid canonical journal is authoritative, including 'passed'. + [void](Read-ProoflinePending $Pending) + } + catch { + # Fall back only after validating the backup, preserve corrupt + # canonical evidence, and use normal digest-checked recovery. + $failure = $_.Exception.Message + [void](Read-ProoflinePending $backup) + $evidence = $Pending + '.invalid-' + [guid]::NewGuid().ToString('N') + '.json' + Assert-ProoflineNoReparse $evidence + if ([IO.File]::Exists($evidence)) { throw 'Invalid journal evidence path occupied.' } + [IO.File]::Move($Pending, $evidence) + try { [IO.File]::Move($backup, $Pending) } + catch { + if (-not [IO.File]::Exists($Pending)) { + try { [IO.File]::Move($evidence, $Pending) } catch { } + } + throw + } + Write-Warning "Malformed journal preserved at $evidence ($failure); recovering from validated backup." + return + } + # Do not block rollback when an unrelated reader temporarily locks the + # redundant backup. Cleanup keeps the journal until deletion succeeds. try { [IO.File]::Delete($backup) } catch { Write-Warning "Journal backup is locked; recovery will retain it until cleanup: $($_.Exception.Message)" } } diff --git a/scripts/check_windows_release_archive.ps1 b/scripts/check_windows_release_archive.ps1 index ae420fe..1411fab 100644 --- a/scripts/check_windows_release_archive.ps1 +++ b/scripts/check_windows_release_archive.ps1 @@ -12,11 +12,25 @@ $ErrorActionPreference = 'Stop' . (Join-Path (Split-Path -Parent $PSScriptRoot) 'install.ps1') $archive = (Resolve-Path -LiteralPath $ArchivePath).Path $executable = (Resolve-Path -LiteralPath $ExecutablePath).Path -$archiveLength = ([IO.FileInfo]::new($archive)).Length -if ($archiveLength -le 0 -or $archiveLength -gt $script:MaxArchiveBytes) { - throw "Packaged Windows archive violates installer compressed-size limit: $archiveLength bytes." +# Open the archive just once and deny replacement, ensuring the size bound +# applies to precisely the stream whose bytes the parser will consume. +$stream = [IO.File]::Open($archive, [IO.FileMode]::Open, + [IO.FileAccess]::Read, [IO.FileShare]::Read) +try { + $length = $stream.Length + if ($length -le 0 -or $length -gt $script:MaxArchiveBytes) { + throw "Packaged Windows archive violates installer compressed-size limit: $length bytes." + } + $compressed = [byte[]]::new([int]$length) + $offset = 0 + while ($offset -lt $compressed.Length) { + $count = $stream.Read($compressed, $offset, $compressed.Length - $offset) + if ($count -le 0) { throw 'Packaged Windows archive truncated during read.' } + $offset += $count + } } -$payload = Get-ProoflineTarExecutable ([IO.File]::ReadAllBytes($archive)) +finally { $stream.Dispose() } +$payload = Get-ProoflineTarExecutable $compressed if ($payload.Length -le 0) { throw 'Packaged Windows archive has no installable executable.' } diff --git a/scripts/test_install_concurrency_windows.ps1 b/scripts/test_install_concurrency_windows.ps1 index cc92a85..8beab56 100644 --- a/scripts/test_install_concurrency_windows.ps1 +++ b/scripts/test_install_concurrency_windows.ps1 @@ -25,6 +25,17 @@ if ([Environment]::OSVersion.Platform -ne [PlatformID]::Win32NT) { if ($Mode -eq 'Hold') { if ([string]::IsNullOrWhiteSpace($CaseDir)) { throw 'Holder needs CaseDir.' } $folder = [IO.Path]::GetFullPath($CaseDir) + $driver = Split-Path -Parent $folder + if ([IO.Path]::GetDirectoryName($driver) -ine [IO.Path]::GetFullPath([IO.Path]::GetTempPath()).TrimEnd([char]'\') -or + [IO.Path]::GetFileName($driver) -cnotmatch '\Aproofline-concurrent-[0-9a-f]{32}\z' -or + [IO.Path]::GetFileName($folder) -cne 'bin') { + throw 'Holder refused a directory outside the disposable test sandbox.' + } + foreach ($path in @($driver, $folder)) { + if (([IO.File]::GetAttributes($path) -band [IO.FileAttributes]::ReparsePoint) -ne 0) { + throw 'Holder refused a reparse-point test directory.' + } + } $marker = Join-Path $folder '.proofline-test-only' if ($HoldToken -cnotmatch '\A[0-9a-f]{32}\z') { throw 'Refusing to hold lock without a valid test token.' @@ -51,17 +62,6 @@ if ($Mode -eq 'Hold') { # Hold the *production* installer lock, not a separately manufactured # FileShare.None handle. Otherwise the test passes even if the installer # accidentally weakens its own lock sharing policy. - $driver = Split-Path -Parent $folder - if ([IO.Path]::GetDirectoryName($driver) -ine [IO.Path]::GetFullPath([IO.Path]::GetTempPath()).TrimEnd([char]'\') -or - [IO.Path]::GetFileName($driver) -cnotmatch '\Aproofline-concurrent-[0-9a-f]{32}\z' -or - [IO.Path]::GetFileName($folder) -cne 'bin') { - throw 'Holder refused a directory outside the disposable test sandbox.' - } - foreach ($path in @($driver, $folder)) { - if (([IO.File]::GetAttributes($path) -band [IO.FileAttributes]::ReparsePoint) -ne 0) { - throw 'Holder refused a reparse-point test directory.' - } - } . (Join-Path (Split-Path -Parent $PSScriptRoot) 'install.ps1') $script:holderOriginalReceipt = (Get-Item Function:\Read-ProoflineReceipt).ScriptBlock $script:holderReady = Join-Path $folder '.holder-ready' diff --git a/scripts/test_install_interruption_real_windows.ps1 b/scripts/test_install_interruption_real_windows.ps1 index eaf5442..a5543ac 100644 --- a/scripts/test_install_interruption_real_windows.ps1 +++ b/scripts/test_install_interruption_real_windows.ps1 @@ -20,6 +20,7 @@ param( [string]$FixtureDir, [string]$DriverRoot, [string]$TestToken, + [switch]$LatestOutage, [switch]$KeepFiles ) @@ -180,6 +181,20 @@ if ($Mode -eq 'Worker' -or $Mode -eq 'Recover') { } . $validatedCopy if ($Mode -eq 'Recover') { + if ($LatestOutage) { + # Invoke the real entrypoint so moving repair after /cli/latest + # fails the test even if standalone repair remains correct. + function Get-ProoflineLatestVersion { + throw 'INTENTIONAL_LATEST_LOOKUP_UNAVAILABLE' + } + try { Invoke-ProoflineInstaller $null $CaseDir $false } + catch { + if ($_.Exception.Message -cne 'INTENTIONAL_LATEST_LOOKUP_UNAVAILABLE') { throw } + Write-Output 'LATEST_LOOKUP_FAILED_AFTER_RECOVERY' + exit 17 + } + throw 'Latest lookup outage unexpectedly completed.' + } Invoke-ProoflinePendingRepair $CaseDir Write-Output 'RECOVERY_COMPLETED' exit 0 @@ -315,6 +330,18 @@ function Make-InstrumentedInstaller([string]$Source, [string]$Destination, [stri Require ($text.Contains($target)) "Production installer checkpoint '$Checkpoint' changed." Require (($text.Split([string[]]@($target), [StringSplitOptions]::None).Count) -eq 2) "Checkpoint '$Checkpoint' is not unique." $instrumented = $text.Replace($target, $replacement) + # Parse generated scripts before starting any worker. Source-only + # validation cannot catch malformed injection templates. + $tokens = $null + $parseErrors = $null + [void][System.Management.Automation.Language.Parser]::ParseInput( + $instrumented, [ref]$tokens, [ref]$parseErrors) + if ($parseErrors.Count -gt 0) { + $details = @($parseErrors | ForEach-Object { + "line $($_.Extent.StartLineNumber): $($_.Message)" + }) -join '; ' + throw "Generated $Checkpoint installer failed syntax preflight: $details" + } [IO.File]::WriteAllText($Destination, $instrumented, [Text.UTF8Encoding]::new($false)) } @@ -448,12 +475,19 @@ try { '" -Mode Recover -CaseDir "' + $directory + '" -InstallerCopy "' + $originalInstaller + '" -DriverRoot "' + $root + '" -TestToken ' + $testToken + if ($checkpoint -eq 'after-switch') { $recoverArgs += ' -LatestOutage' } $recovery = Invoke-HiddenPowerShell $recoverArgs "recovery worker ($checkpoint)" $recoverExit = $recovery.ExitCode [IO.File]::WriteAllText($recoverStdout, $recovery.Output) [IO.File]::WriteAllText($recoverStderr, $recovery.ErrorOutput) $recoverOutput = $recovery.Output + $recovery.ErrorOutput - Require ($recoverExit -eq 0) "Fresh recovery process failed for $checkpoint; output: $recoverOutput" + if ($checkpoint -eq 'after-switch') { + Require ($recoverExit -eq 17 -and + $recoverOutput.Contains('LATEST_LOOKUP_FAILED_AFTER_RECOVERY')) "Unpinned latest-outage recovery failed at $checkpoint; exit $recoverExit; output: $recoverOutput" + } + else { + Require ($recoverExit -eq 0) "Fresh recovery process failed for $checkpoint; output: $recoverOutput" + } $digest = $null if ($expected[$checkpoint] -eq 'absent') { Require (-not [IO.File]::Exists($activeFile)) 'Interrupted fresh install unexpectedly published an executable.' diff --git a/scripts/test_install_upgrade_windows.ps1 b/scripts/test_install_upgrade_windows.ps1 index 84a383f..753ff52 100644 --- a/scripts/test_install_upgrade_windows.ps1 +++ b/scripts/test_install_upgrade_windows.ps1 @@ -365,6 +365,36 @@ try { Require (-not [IO.File]::Exists($journal)) 'Canonical passed journal remains after recovery.' Require (-not [IO.File]::Exists($journal + '.postcheck.bak')) 'Stale checking backup remains after recovery.' } + Check 'malformed canonical journal recovers using validated checking backup' { + $dir = PrepareOld 'corrupt-canonical' + [void](MakePending $dir) + $pending = Pending 'corrupt-canonical' + Set-ProoflinePendingPostcheck $pending 'checking' + [IO.File]::Copy($pending, $pending + '.postcheck.bak', $false) + [IO.File]::WriteAllText($pending, 'BROKEN_JSON{') + [IO.File]::WriteAllBytes((Active 'corrupt-canonical'), + (Get-ProoflineTarExecutable $script:newArchive)) + Invoke-ProoflinePendingRepair $dir + Require ((Get-ProoflineSha256 (Active 'corrupt-canonical')) -ceq $script:oldHash) 'Backup did not restore previous verified image.' + Assert-ProoflineRecord (Receipt 'corrupt-canonical') '0.5.1' $script:oldHash + Require (-not [IO.File]::Exists($pending)) 'Recovered transaction journal was retained.' + Require (-not [IO.File]::Exists($pending + '.postcheck.bak')) 'Recovered journal backup was retained.' + $evidence = @(Get-ChildItem -LiteralPath $dir -File -Force | + Where-Object { $_.Name -match '\A\.proofline-install\.pending\.json\.invalid-[0-9a-f]{32}\.json\z' }) + Require ($evidence.Count -eq 1) 'Malformed journal evidence is missing.' + Require ([IO.File]::ReadAllText($evidence[0].FullName) -ceq 'BROKEN_JSON{') 'Malformed journal evidence was modified.' + } + Check 'invalid backup does not displace invalid canonical journal' { + $dir = PrepareOld 'invalid-both-journals' + [void](MakePending $dir) + $pending = Pending 'invalid-both-journals' + [IO.File]::WriteAllText($pending, 'BROKEN_CANONICAL{') + [IO.File]::WriteAllText($pending + '.postcheck.bak', 'BROKEN_BACKUP{') + Must-Throw { Invoke-ProoflinePendingRepair $dir } + Require ([IO.File]::ReadAllText($pending) -ceq 'BROKEN_CANONICAL{') 'Invalid canonical journal was discarded.' + Require ([IO.File]::ReadAllText($pending + '.postcheck.bak') -ceq 'BROKEN_BACKUP{') 'Invalid backup was discarded.' + Require ((Get-ProoflineSha256 (Active 'invalid-both-journals')) -ceq $script:oldHash) 'Invalid backup changed the installed executable.' + } Check 'backup deletion lock does not block rollback from validated canonical journal' { $dir = PrepareOld 'locked-journal-backup' [void](MakePending $dir) @@ -441,6 +471,31 @@ try { Assert-ProoflineRecord (Receipt 'latest-release-entrypoint') '0.5.1' $script:oldHash Require (-not [IO.File]::Exists((Pending 'latest-release-entrypoint'))) 'Latest release entrypoint left a recovery journal.' } + Check 'unpinned latest outage recovers interrupted upgrade before lookup' { + $dir = PrepareOld 'latest-failure-repair' + [void](MakePending $dir) + $pending = Pending 'latest-failure-repair' + Set-ProoflinePendingPostcheck $pending 'checking' + [IO.File]::WriteAllBytes((Active 'latest-failure-repair'), + (Get-ProoflineTarExecutable $script:newArchive)) + $real = (Get-Item Function:\Get-ProoflineLatestVersion).ScriptBlock + try { + Set-Item Function:\Get-ProoflineLatestVersion -Value { + throw 'INTENTIONAL_LATEST_LOOKUP_UNAVAILABLE' + } + $failed = $false + try { Invoke-ProoflineInstaller $null $dir $false } + catch { + if ($_.Exception.Message -cne 'INTENTIONAL_LATEST_LOOKUP_UNAVAILABLE') { throw } + $failed = $true + } + Require $failed 'Latest pointer failure was not observed.' + } + finally { Set-Item Function:\Get-ProoflineLatestVersion -Value $real } + Require ((Get-ProoflineSha256 (Active 'latest-failure-repair')) -ceq $script:oldHash) 'Latest pointer failure prevented rollback.' + Assert-ProoflineRecord (Receipt 'latest-failure-repair') '0.5.1' $script:oldHash + Require (-not [IO.File]::Exists($pending)) 'Latest lookup failure left a pending journal.' + } Check 'pre-download installer repairs interrupted upgrade despite download outage' { $dir = PrepareOld 'predownload-outage' [void](MakePending $dir)