Files
ucvl-zonghengjia-open-source/windows/build/Test-ProductionInstallationBaseline.ps1
2026-10-11 23:23:20 +00:00

207 lines
15 KiB
PowerShell

#requires -Version 7.0
# Synthetic fixture only: never execute an EXE, open the registry, or call the
# production capture/restore entry points. Evidence is retained in GUID temp dirs.
param()
$ErrorActionPreference = 'Stop'
Set-StrictMode -Version Latest
$libraryPath = Join-Path $PSScriptRoot 'ProductionInstallationBaseline.ps1'
$loadedLibraryHash = (Get-FileHash -LiteralPath $libraryPath -Algorithm SHA256).Hash
. $libraryPath
$script:checks = [ordered]@{}
$script:failures = [Collections.Generic.List[string]]::new()
$script:fixtures = [Collections.Generic.List[object]]::new()
$script:activeFixture = $null
$utf8 = [Text.UTF8Encoding]::new($false)
function Assert-Test([bool]$Condition, [string]$Message) {
if (-not $Condition) { throw $Message }
}
function Invoke-Test([string]$Name, [scriptblock]$Body) {
try { & $Body; $script:checks[$Name] = $true; Write-Host "PASS $Name" }
catch {
$script:checks[$Name] = $false
$script:failures.Add("${Name}: $($_.Exception.Message) [$($_.ScriptStackTrace)]")
Write-Host "FAIL ${Name}: $($_.Exception.Message)"
}
}
. (Join-Path $PSScriptRoot 'fixtures/production-installation-fixture.ps1')
function Assert-RefusalUnchanged($Fixture, [scriptblock]$Action) {
$before = Get-FixtureDigest $Fixture
$errorSeen = $false
try { & $Action | Out-Null } catch { $errorSeen = $true }
Assert-Test $errorSeen 'Expected refusal, but action succeeded'
Assert-Test ((Get-FixtureDigest $Fixture) -ceq $before) 'Refusal changed owned files/registration/user data'
}
function Test-TamperedBaseline($Fixture, [scriptblock]$Mutation) {
$path = Join-Path $Fixture.Job 'baseline.json'
$saved = [IO.File]::ReadAllBytes($path)
try {
$value = Get-Content -LiteralPath $path -Raw | ConvertFrom-Json
& $Mutation $value
Write-PIBJson $path $value
$hash = Get-PIBHash $path
Assert-RefusalUnchanged $Fixture { Restore-PIBFixtureBaseline -JobDirectory $Fixture.Job -BaselineSha256 $hash }
} finally { [IO.File]::WriteAllBytes($path, $saved) }
}
function Test-TamperedJournal($Fixture, [scriptblock]$Mutation) {
$path = Get-PIBDestination -Profile $Fixture.Profile -Key 'metadata:journal'
$saved = [IO.File]::ReadAllBytes($path)
try {
$value = Get-Content -LiteralPath $path -Raw | ConvertFrom-Json
& $Mutation $value
Write-PIBJson $path $value
Assert-RefusalUnchanged $Fixture { Restore-PIBFixtureBaseline -JobDirectory $Fixture.Job -BaselineSha256 $Fixture.Sha256 }
} finally { [IO.File]::WriteAllBytes($path, $saved) }
}
$started = [DateTimeOffset]::Now.ToString('O')
Invoke-Test 'synthetic_capture_shape_and_digest' {
$script:activeFixture = New-TestFixture
$f = $script:activeFixture
Assert-Test ($f.Snapshot.Schema -eq 2 -and $f.Snapshot.Mode -eq 'fixture-only') 'Wrong fixture snapshot schema/mode'
Assert-Test ($f.Snapshot.Entries.Count -eq 10 -and $f.Snapshot.CandidateComponents.Count -eq 3) 'Incomplete payload/component/metadata capture'
Assert-OldRestored $f
}
if ($null -ne $script:activeFixture) {
$f = $script:activeFixture
Invoke-Test 'unchanged_baseline_is_idempotent' { $r = Restore-TestFixture $f; Assert-Test ($r.AlreadyRestored -and $r.Writes -eq 0) 'Unchanged baseline wrote files' }
Invoke-Test 'postcommit_complete_restore_and_idempotence' {
Apply-TestCandidate $f
$r = Restore-TestFixture $f
Assert-Test (-not $r.AlreadyRestored -and $r.Writes -gt 0) 'Candidate was not restored'
$r = Restore-TestFixture $f
Assert-Test ($r.AlreadyRestored -and $r.Writes -eq 0) 'Repeated restore wrote files'
}
Invoke-Test 'pending_partial_install_restores' { Apply-TestCandidate $f -State 'pending' -Partial; $null = Restore-TestFixture $f }
Invoke-Test 'interrupted_restore_keeps_barrier_and_candidate_main_then_resumes' {
Apply-TestCandidate $f
$interrupted = $false
try { Restore-PIBFixtureBaseline -JobDirectory $f.Job -BaselineSha256 $f.Sha256 -FixtureInterruptAfter 2 | Out-Null }
catch { $interrupted = $_.Exception.Message -match 'Injected fixture interruption' }
Assert-Test $interrupted 'Interruption injection was not reached'
$journal = Get-Content -LiteralPath (Get-PIBDestination -Profile $f.Profile -Key 'metadata:journal') -Raw | ConvertFrom-Json
Assert-Test ($journal.State -eq 'external-rollback-pending') 'Mixed installation lost its launch barrier'
Assert-Test ((Get-PIBHash (Get-PIBDestination -Profile $f.Profile -Key 'payload:VPNPlus.exe')) -eq $f.Next[0].Sha256) 'Main EXE restored before dependencies/registration'
$null = Restore-TestFixture $f
}
Invoke-Test 'main_executable_waits_for_all_dependencies_and_shell' {
Apply-TestCandidate $f
$dependencyEntries = @($f.Snapshot.Entries | Where-Object { $_.Key -notin @('payload:VPNPlus.exe', 'metadata:journal', 'metadata:uninstall') })
$interrupted = $false
try { Restore-PIBFixtureBaseline -JobDirectory $f.Job -BaselineSha256 $f.Sha256 -FixtureInterruptAfter $dependencyEntries.Count | Out-Null }
catch { $interrupted = $_.Exception.Message -match 'Injected fixture interruption' }
Assert-Test $interrupted 'Last dependency interruption was not reached'
foreach ($entry in $dependencyEntries) {
Assert-Test ((Get-PIBHash (Get-PIBDestination -Profile $f.Profile -Key $entry.Key)) -eq $entry.Sha256) "Dependency/shell not restored before main: $($entry.Key)"
}
Assert-Test ((Get-PIBHash (Get-PIBDestination -Profile $f.Profile -Key 'payload:VPNPlus.exe')) -eq $f.Next[0].Sha256) 'Main EXE did not remain candidate through last dependency'
$null = Restore-TestFixture $f
}
Invoke-Test 'old_journal_is_last_after_main_and_registration_verified' {
Apply-TestCandidate $f
$beforeJournal = @($f.Snapshot.Entries | Where-Object { $_.Key -notin @('metadata:journal', 'metadata:uninstall') }).Count
$interrupted = $false
try { Restore-PIBFixtureBaseline -JobDirectory $f.Job -BaselineSha256 $f.Sha256 -FixtureInterruptAfter $beforeJournal | Out-Null }
catch { $interrupted = $_.Exception.Message -match 'Injected fixture interruption' }
Assert-Test $interrupted 'Post-main/pre-journal interruption was not reached'
foreach ($entry in $f.Snapshot.Entries | Where-Object Key -ne 'metadata:journal') {
Assert-Test ((Get-PIBHash (Get-PIBDestination -Profile $f.Profile -Key $entry.Key)) -eq $entry.Sha256) "Journal barrier reached before old bytes: $($entry.Key)"
}
Assert-Test (Test-PIBEqual (Get-PIBRegistration -Profile $f.Profile) $f.Snapshot.Registration) 'Journal barrier reached before old registry'
$journal = Get-Content -LiteralPath (Get-PIBDestination -Profile $f.Profile -Key 'metadata:journal') -Raw | ConvertFrom-Json
Assert-Test ($journal.State -eq 'external-rollback-pending') 'Original terminal journal was restored too early'
$result = Restore-TestFixture $f
Assert-Test ($result.Writes -eq 1 -and -not $result.AlreadyRestored) 'Resume did not leave original journal as only remaining file write'
}
Apply-TestCandidate $f
Invoke-Test 'wrong_baseline_digest_refuses_before_writes' { Assert-RefusalUnchanged $f { Restore-PIBFixtureBaseline -JobDirectory $f.Job -BaselineSha256 ('0' * 64) } }
Invoke-Test 'corrupt_backup_refuses_before_writes' {
$entry = $f.Snapshot.Entries | Where-Object Key -eq 'payload:README.md'
$path = Join-Path $f.Job "baseline/$($entry.Id).bin"; $saved = [IO.File]::ReadAllBytes($path)
try { Write-FixtureText $path 'broken independent backup'; Assert-RefusalUnchanged $f { Restore-PIBFixtureBaseline -JobDirectory $f.Job -BaselineSha256 $f.Sha256 } }
finally { [IO.File]::WriteAllBytes($path, $saved) }
}
Invoke-Test 'external_payload_refuses_before_writes' {
$path = Get-PIBDestination -Profile $f.Profile -Key 'payload:README.md'; $saved = [IO.File]::ReadAllBytes($path)
try { Write-FixtureText $path 'external unrelated file modification'; Assert-RefusalUnchanged $f { Restore-PIBFixtureBaseline -JobDirectory $f.Job -BaselineSha256 $f.Sha256 } }
finally { [IO.File]::WriteAllBytes($path, $saved) }
}
Invoke-Test 'external_owned_registration_refuses_before_writes' {
$saved = [IO.File]::ReadAllBytes($f.RegistrationPath)
try {
$reg = Get-Content -LiteralPath $f.RegistrationPath -Raw | ConvertFrom-Json
$reg.Values[4].Data = 'external version'; Write-PIBJson $f.RegistrationPath $reg
Assert-RefusalUnchanged $f { Restore-PIBFixtureBaseline -JobDirectory $f.Job -BaselineSha256 $f.Sha256 }
} finally { [IO.File]::WriteAllBytes($f.RegistrationPath, $saved) }
}
Invoke-Test 'locked_main_refuses_before_dependency_changes' {
$handle = [IO.File]::Open((Get-PIBDestination -Profile $f.Profile -Key 'payload:VPNPlus.exe'), [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::Read)
try { Assert-RefusalUnchanged $f { Restore-PIBFixtureBaseline -JobDirectory $f.Job -BaselineSha256 $f.Sha256 } }
finally { $handle.Dispose() }
}
Invoke-Test 'tampered_profile_target_refuses' { Test-TamperedBaseline $f { param($s) $s.Profile.Target = Join-Path $f.Root 'outside-installed' } }
Invoke-Test 'tampered_profile_desktop_refuses' { Test-TamperedBaseline $f { param($s) $s.Profile.Desktop = Join-Path $f.Root 'outside-shortcut.lnk' } }
Invoke-Test 'tampered_profile_root_refuses' { Test-TamperedBaseline $f { param($s) $s.Profile.FixtureRoot = [IO.Path]::GetTempPath() } }
Invoke-Test 'production_mode_rejected_by_fixture_entry' { Test-TamperedBaseline $f { param($s) $s.Mode = 'production-current-user'; $s.Profile.Mode = 'production-current-user' } }
Invoke-Test 'tampered_registry_mapping_refuses' { Test-TamperedBaseline $f { param($s) $s.Profile.RegistryKeys[0] = 'arbitrary-registration' } }
Invoke-Test 'wrong_user_sid_refuses' { Test-TamperedBaseline $f { param($s) $s.Profile.Sid = 'S-1-5-21-111-222-333-444' } }
Invoke-Test 'duplicate_snapshot_payload_refuses' { Test-TamperedBaseline $f { param($s) $s.Candidate = @($s.Candidate) + @($s.Candidate[0]) } }
Invoke-Test 'traversal_snapshot_payload_refuses' { Test-TamperedBaseline $f { param($s) $s.Candidate[-1].Path = 'assets/../../outside.fixture' } }
Invoke-Test 'unbound_component_hash_refuses' { Test-TamperedJournal $f { param($j) $j.Integration.Components[0].Sha256 = '9' * 64 } }
Invoke-Test 'unbound_registration_next_refuses' { Test-TamperedJournal $f { param($j) $j.Integration.Values[4].Next.Data = '"foreign-version"' } }
Invoke-Test 'unbound_registration_previous_refuses' { Test-TamperedJournal $f { param($j) $j.Integration.Values[4].Previous.Data = '"foreign-old-version"' } }
Invoke-Test 'unbound_registration_key_existence_refuses' { Test-TamperedJournal $f { param($j) $j.Integration.KeysExisted[0] = $false } }
Invoke-Test 'duplicate_journal_files_refuse' { Test-TamperedJournal $f { param($j) $j.Files[-1] = $j.Files[0] } }
Invoke-Test 'valid_fixture_recovers_after_all_refusals' { $null = Restore-TestFixture $f }
foreach ($bad in @('duplicate', 'traversal')) {
Invoke-Test "capture_${bad}_manifest_refuses_without_job_creation" {
$badPath = Join-Path $f.Root "bad-$bad.json"
$rows = @($f.Next | ConvertTo-Json -Depth 8 | ConvertFrom-Json)
if ($bad -eq 'duplicate') { $rows += $rows[0] } else { $rows[-1].Path = 'assets/../outside.fixture' }
Write-PIBJson $badPath $rows
$job = New-TestJobPath
Assert-RefusalUnchanged $f { New-PIBFixtureBaseline -JobDirectory $job -FixtureRoot $f.Root -OldManifestPath $f.OldPath -CandidateManifestPath $badPath -CandidateComponentsManifestPath $f.ComponentsPath -CandidateVersion $f.Version }
Assert-Test (-not (Test-Path -LiteralPath $job)) 'Invalid manifest created a snapshot job'
}
}
Invoke-Test 'capture_candidate_source_hash_mismatch_refuses_without_job_creation' {
$path = Join-Path ([IO.Path]::GetDirectoryName($f.NextPath)) 'README.md'
$saved = [IO.File]::ReadAllBytes($path); $job = New-TestJobPath
try {
Write-FixtureText $path 'mismatched candidate source bytes'
Assert-RefusalUnchanged $f { New-PIBFixtureBaseline -JobDirectory $job -FixtureRoot $f.Root -OldManifestPath $f.OldPath -CandidateManifestPath $f.NextPath -CandidateComponentsManifestPath $f.ComponentsPath -CandidateVersion $f.Version }
Assert-Test (-not (Test-Path -LiteralPath $job)) 'Unverified candidate bytes created a snapshot job'
} finally { [IO.File]::WriteAllBytes($path, $saved) }
}
Invoke-Test 'capture_component_source_hash_mismatch_refuses_without_job_creation' {
$path = Join-Path ([IO.Path]::GetDirectoryName($f.ComponentsPath)) 'Uninstall.exe'
$saved = [IO.File]::ReadAllBytes($path); $job = New-TestJobPath
try {
Write-FixtureText $path 'mismatched candidate component bytes'
Assert-RefusalUnchanged $f { New-PIBFixtureBaseline -JobDirectory $job -FixtureRoot $f.Root -OldManifestPath $f.OldPath -CandidateManifestPath $f.NextPath -CandidateComponentsManifestPath $f.ComponentsPath -CandidateVersion $f.Version }
Assert-Test (-not (Test-Path -LiteralPath $job)) 'Unverified component bytes created a snapshot job'
} finally { [IO.File]::WriteAllBytes($path, $saved) }
}
}
Invoke-Test 'absent_old_components_and_registration_are_restored' {
$empty = New-TestFixture -AbsentIntegration
Apply-TestCandidate $empty
$null = Restore-TestFixture $empty
Assert-Test (-not (Test-Path -LiteralPath (Get-PIBDestination -Profile $empty.Profile -Key 'component:0'))) 'New uninstaller survived rollback'
Assert-Test (-not (Test-Path -LiteralPath (Get-PIBDestination -Profile $empty.Profile -Key 'metadata:journal'))) 'New journal survived rollback'
}
Invoke-Test 'loaded_library_unchanged_during_tests' { Assert-Test ((Get-PIBHash $libraryPath) -eq $loadedLibraryHash) 'Library changed after this suite loaded it; rerun against final source' }
$report = [ordered]@{
Kind = 'production-installation-baseline-synthetic-fixtures'; StartedAt = $started
FinishedAt = [DateTimeOffset]::Now.ToString('O'); Passed = ($script:failures.Count -eq 0)
CheckCount = $script:checks.Count; Checks = $script:checks; Failures = @($script:failures)
ProductionModified = $false; RegistryOpened = $false; NetworkUsed = $false; ExecutablesStarted = $false
ReleaseAccepted = $false; FixtureRoots = @($script:fixtures | ForEach-Object Root); Jobs = @($script:fixtures | ForEach-Object Job)
LibrarySha256 = $loadedLibraryHash
TestSha256 = Get-PIBHash $PSCommandPath
}
$report | ConvertTo-Json -Depth 20
if (-not $report.Passed) { exit 1 }