diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 331c3cc..15a0556 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -37,9 +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: | - tar -xzf artifacts/proofline-x86_64-pc-windows-msvc.tar.gz -C artifacts + $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." } + } + 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.' + } & ./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 5b900cc..647dfd3 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -82,6 +82,18 @@ jobs: fi fi python3 scripts/archive.py "$TARGET" + - name: Validate packaged Windows release with both PowerShell engines + if: matrix.target == 'x86_64-pc-windows-msvc' + shell: pwsh + run: | + $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." } + } - 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 new file mode 100644 index 0000000..86d3896 --- /dev/null +++ b/.github/workflows/windows-installer.yml @@ -0,0 +1,134 @@ +name: Windows installer tests + +on: + pull_request: + paths: + - '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' + - 'src/**' + - '.github/workflows/ci.yml' + - '.github/workflows/release.yml' + - '.github/workflows/windows-installer.yml' + workflow_dispatch: + +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 + 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_syntax_windows.ps1', + '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" } + } + + + 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, + # download/setup time, and test-runner overhead can exceed 30 minutes. + timeout-minutes: 60 + 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 twelve 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" } + + 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. + 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 18c4903..7e6122c 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,41 @@ 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. 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 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: + +```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 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. 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. + +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. + +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 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 new file mode 100644 index 0000000..0438258 --- /dev/null +++ b/install.ps1 @@ -0,0 +1,1264 @@ +# 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. Tested on Windows PowerShell 5.1 and PowerShell 7. +# .\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 { + # 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() + 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) { + $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.' + } + $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 - 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 +} + +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, + [Microsoft.Win32.RegistryValueKind]$Kind = [Microsoft.Win32.RegistryValueKind]::ExpandString +) { + if ($null -eq $Current) { $Current = '' } + $normalized = $Directory.TrimEnd([char[]]@('\', '/')) + foreach ($entry in ($Current -split ';')) { + $candidate = $entry.Trim() + # 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) { + 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 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) { + # 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 + # HKCU Path is shared between sessions for this SID. + $mutexName = 'Global\Proofline-UserPath-' + $sid + $mutex = [Threading.Mutex]::new($false, $mutexName) + $locked = $false + $changed = $false + try { + try { + $locked = $mutex.WaitOne(30000) + } + catch [Threading.AbandonedMutexException] { + $locked = $true + } + 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.' + 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.' + } +} + + +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 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 +} + +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, [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 { + $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.' + } + + # 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 + } + finally { $process.Dispose() } + } + finally { $lockedImage.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 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.' } + $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) { + 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 + } + 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.' + } + $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-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 -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 ($record.schema -ne 2 -or $null -ne $current)) -or + ($State -ceq 'passed' -and $current -cne 'checking')) { + throw 'Invalid installation postcheck state transition.' + } + $record | Add-Member -NotePropertyName postcheck -NotePropertyValue $State -Force + $temporary = $Pending + '.' + [guid]::NewGuid().ToString('N') + '.tmp' + $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, + [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 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)) { + 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)" } + } + 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.' } + 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, + [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) { + 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]) } + } + Clear-ProoflineJournalBackup $Pending + [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') + Restore-ProoflinePendingBackup $pending + $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 (-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)) { + 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) } + } + Clear-ProoflineJournalBackup $pending + [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.' + } + # 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) } + Clear-ProoflineJournalBackup $pending + [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 + } + else { Write-ProoflineReceipt $receipt $record.version $record.sha256 } + 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 + } + + $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 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'] + $postcheckVerified = ($null -ne $postcheck -and $postcheck.Value -ceq 'passed') + if ($activeHash -ceq $record.newSha256 -and $postcheckVerified) { + # 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 { + 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 { + 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) { + 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." + return + } + + $source = $null + foreach ($candidate in @($paths.old, $paths.api)) { + 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) { + 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.' + } + # 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) + } + if ((Get-ProoflineSha256 $destination) -cne $record.oldSha256) { + throw 'Restored executable digest differs from previous release.' + } + # Recovery copy was checked against the recorded hash; do not execute + # a pre-existing local image during repair. + Ensure-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 + if (-not [IO.Directory]::Exists($directory)) { return } + $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) { + # 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 + $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') + 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) -or [IO.File]::Exists($pending + '.postcheck.bak')) { + 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.' + } + # 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 executable and receipt already match; PATH handling still follows this invocation's options." + 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) { + $record = ConvertTo-Json -Compress -InputObject ([ordered]@{ + schema = 3 + id = $id + version = $ReleaseVersion + sha256 = $hash + postcheck = 'checking' + }) + } + 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) + try { + $stream.Write($binary, 0, $binary.Length) + $stream.Flush($true) + } + finally { $stream.Dispose() } + Assert-ProoflineExeVersion $stage $ReleaseVersion $hash + + if ($null -eq $oldReceipt) { + [IO.File]::Move($stage, $destination) + if ((Get-ProoflineSha256 $destination) -cne $hash) { + throw 'Installed executable digest differs after relocation.' + } + try { + Assert-ProoflineExeVersion $destination $ReleaseVersion $hash + 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. + $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.' + } + 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-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 $hash + 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)" } + 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() } + } + finally { foreach ($guard in $guards) { $guard.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 + } +} diff --git a/scripts/check_windows_release_archive.ps1 b/scripts/check_windows_release_archive.ps1 new file mode 100644 index 0000000..1411fab --- /dev/null +++ b/scripts/check_windows_release_archive.ps1 @@ -0,0 +1,44 @@ +#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 +# 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 + } +} +finally { $stream.Dispose() } +$payload = Get-ProoflineTarExecutable $compressed +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/generate_windows_installer_fixtures.py b/scripts/generate_windows_installer_fixtures.py new file mode 100644 index 0000000..05dd5cb --- /dev/null +++ b/scripts/generate_windows_installer_fixtures.py @@ -0,0 +1,105 @@ +"""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" + image[0x84:0x86] = (0x8664).to_bytes(2, "little") # AMD64 COFF Machine + 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)) + ) + 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( + 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() + (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"{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. + with tarfile.open(fileobj=io.BytesIO(base), mode="r:gz") as tar: + names = tar.getnames() + assert names == ["proofline.exe"], names + 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}") + + +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_concurrency_windows.ps1 b/scripts/test_install_concurrency_windows.ps1 new file mode 100644 index 0000000..8beab56 --- /dev/null +++ b/scripts/test_install_concurrency_windows.ps1 @@ -0,0 +1,224 @@ +#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]$HoldToken, + [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) + $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.' + } + # 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.' } + $validatedClaim = $false + try { + if ([IO.File]::ReadAllText($claimed) -cne "DISPOSABLE_LOCK_TEST:$HoldToken") { + # 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 ($validatedClaim -and [IO.File]::Exists($claimed)) { [IO.File]::Delete($claimed) } + } + # 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. + . (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($script:holderRelease)) { + Start-Sleep -Milliseconds 100 + } + if (-not [IO.File]::Exists($script:holderRelease)) { + throw 'Holder timed out waiting for parent release signal.' + } + return (& $script:holderOriginalReceipt $Path) + } + $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 +} + +$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 +$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' +$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, [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" + } + } + + $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 + '" -HoldToken "' + $holdToken + '"' + $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.' + + $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) + } + 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.' + $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.' } + 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..a5543ac --- /dev/null +++ b/scripts/test_install_interruption_real_windows.ps1 @@ -0,0 +1,568 @@ +#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, + [string]$DriverRoot, + [string]$TestToken, + [switch]$LatestOutage, + [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, [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) { + $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() + $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." + } + finally { $child.Dispose() } +} +function Assert-Installed( + [string]$Directory, + [string]$Version, + [ValidateSet('none', 'corrupt', 'unchecked')][string]$DamagedEvidence = 'none', + [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' + 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.' + 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' + $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. + $damaged = @(Get-ChildItem -LiteralPath $Directory -Force | + Where-Object { $_.Name -match '\A\.proofline-damaged-[0-9a-f]{32}\.exe\z' }) + 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 -ceq $script:pinnedExeHashes['0.5.2']) 'Quarantine does not match the pinned rejected new release.' + } + } + else { + Require ($damaged.Count -eq 0) 'Unexpected damaged executable remains.' + } + return $hash +} + +if ($Mode -eq 'Worker' -or $Mode -eq 'Recover') { + 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.' + } + $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') { + 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 + } + 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() + $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." + } + $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() + 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 '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' + + "`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-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 }' + $replacement = ' Write-ProoflineReceipt $receipt $ReleaseVersion $hash' + + "`n" + ' ' + $abort + + "`n" + ' try { Clear-ProoflineUpgradeFiles $paths $pending $hash }' + } + elseif ($Checkpoint -eq 'fresh-after-journal') { + $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 $hash' + + "`n`n" + ' if ($null -eq $oldReceipt) {' + $replacement = ' Assert-ProoflineExeVersion $stage $ReleaseVersion $hash' + + "`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" + ' 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." + 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)) +} + +$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', '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 +$cleanup = $false + +try { + . $originalInstaller + $script:pinnedExeHashes = @{} + 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 + $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) + } + $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:$testToken") + $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 + + '" -DriverRoot "' + $root + '" -TestToken ' + $testToken + $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." + $onDiskJournal = ConvertFrom-Json -InputObject ([IO.File]::ReadAllText($journal)) + 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')) { + 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)) { + $activeDigest = (Get-FileHash -LiteralPath $activeFile -Algorithm SHA256).Hash + } + 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-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')) { + Require ($activeDigest -ceq $oldDigest) 'Journal checkpoint unexpectedly changed old executable.' + } + elseif ($checkpoint -eq 'corrupt-after-switch') { + Require ([IO.File]::ReadAllText($activeFile) -ceq 'INTENTIONALLY_CORRUPTED') 'Corruption checkpoint did not install injected corruption.' + } + else { + Require ($activeDigest -ceq $script:pinnedExeHashes['0.5.2']) 'Replacement checkpoint did not publish pinned new 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 + + '" -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 + 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.' + 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.' + if ($checkpoint -eq 'fresh-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 first-install bytes were not preserved.' + } + $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' + if ($checkpoint -eq 'corrupt-after-switch') { $damagedMode = 'corrupt' } + elseif ($checkpoint -eq 'after-switch') { $damagedMode = 'unchecked' } + $digest = Assert-Installed $directory $expected[$checkpoint] ` + $damagedMode ` + ($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.' + + } + 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_syntax_windows.ps1 b/scripts/test_install_syntax_windows.ps1 new file mode 100644 index 0000000..8c95a5c --- /dev/null +++ b/scripts/test_install_syntax_windows.ps1 @@ -0,0 +1,27 @@ +#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'), + (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) { + $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)." diff --git a/scripts/test_install_upgrade_real_windows.ps1 b/scripts/test_install_upgrade_real_windows.ps1 new file mode 100644 index 0000000..1a99ba4 --- /dev/null +++ b/scripts/test_install_upgrade_real_windows.ps1 @@ -0,0 +1,178 @@ +#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 +# 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..." + $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) { + $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 + 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) { + 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." + } + # 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)')." + } + 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)" + + # 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) { + 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 +} diff --git a/scripts/test_install_upgrade_windows.ps1 b/scripts/test_install_upgrade_windows.ps1 new file mode 100644 index 0000000..753ff52 --- /dev/null +++ b/scripts/test_install_upgrade_windows.ps1 @@ -0,0 +1,733 @@ +#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) + + 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 + $script:failInstalledPostcheckPath = $null + $script:failInstalledPostcheckVersion = '0.5.2' + function Assert-ProoflineExeVersion([string]$Path, [string]$Version, [string]$ExpectedSha256) { + $script:smokeCount++ + $expected = switch ($Version) { + '0.5.1' { $script:oldHash; break } + '0.5.2' { $script:newHash; break } + default { throw "Unexpected test-only version $Version" } + } + 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 + $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 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') + $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 + })) + 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 '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; 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)) '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) 'Verified first-install image was lost.' + } + 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 '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-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 + 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-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 } + 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-ProoflinePendingPostcheck (Pending 'passed-before-receipt') 'checking' + [IO.File]::WriteAllBytes((Active 'passed-before-receipt'), (Get-ProoflineTarExecutable $script:newArchive)) + 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 (-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.' + [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 '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 '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 '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) + $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) + $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 '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 '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) + 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) + $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' + 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) + $before = $script:smokeCount + # 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 + } + 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 '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) + 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 + 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.' + 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 '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) + 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 { + 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 + [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_user_path_ci_windows.ps1 b/scripts/test_install_user_path_ci_windows.ps1 new file mode 100644 index 0000000..853a682 --- /dev/null +++ b/scripts/test_install_user_path_ci_windows.ps1 @@ -0,0 +1,155 @@ +#requires -Version 5.1 +<# +.SYNOPSIS + Verify raw current-user PATH persistence and expandable registry types. +.DESCRIPTION + 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') + +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 + $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 { + $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') { + $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 = 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 +# 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 +$ok = $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() } + + # 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.' + } + if (-not $after.value.Contains($token)) { + throw 'Installer expanded or removed the existing %VARIABLE% token.' + } + if ($null -ne (Get-ProoflineUpdatedUserPath $after.value $directory)) { + throw 'PATH duplicate-detection unexpectedly added a second entry.' + } + + Add-ProoflineUserPath $directory + $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 + $encoded = @(& $engine -NoProfile -NonInteractive -File $PSCommandPath -Mode ReadUserPath) + if ($LASTEXITCODE -ne 0) { + throw "Fresh PowerShell process failed to read User PATH: $LASTEXITCODE" + } + $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 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 { + if ($seeded) { + $current = Get-RawUserPath + # Restore only the exact test values; do not overwrite other edits. + if ($current.kind -in @('ExpandString', 'String') -and + $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') + 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 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) { + throw 'CI User PATH persistence failed or original raw PATH was not restored.' +} +Write-Host 'CI User PATH persistence, expandability and restore: PASS' diff --git a/scripts/test_install_windows.ps1 b/scripts/test_install_windows.ps1 new file mode 100644 index 0000000..c0b10ff --- /dev/null +++ b/scripts/test_install_windows.ps1 @@ -0,0 +1,213 @@ +#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 + # 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 + $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]) { + throw "Extracted executable payload differs from independent fixture at byte $i." + } + } + } + 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" { + 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 '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 '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 } + } + 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 '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.' } + # 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 ($expanded -cne ($token + ';' + $directory)) { + throw 'Variable-dependent PATH entry incorrectly suppressed stable installed directory.' + } + } + 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 '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)) { + 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 }