120 lines
15 KiB
PowerShell
120 lines
15 KiB
PowerShell
[CmdletBinding()]
|
|
param(
|
|
[Parameter(Mandatory)][string]$PackagePath,
|
|
[Parameter(Mandatory)][string]$SetupDirectory,
|
|
[Parameter(Mandatory)][string]$BaselineMsi,
|
|
[Parameter(Mandatory)][string]$ReportPath
|
|
)
|
|
$ErrorActionPreference='Stop'
|
|
. (Join-Path $PSScriptRoot '..\DeveloperPackage.ps1')
|
|
$package=Test-DeveloperPackage $PackagePath
|
|
$release=Get-Content -Raw (Join-Path $PSScriptRoot 'Release.json') | ConvertFrom-Json
|
|
$evidence=Get-Content -Raw (Join-Path $SetupDirectory 'setup-evidence.json') | ConvertFrom-Json
|
|
$passed=[Collections.Generic.List[string]]::new()
|
|
function Assert-Package([bool]$condition,[string]$message){if(!$condition){throw "Package qualification failed: $message"};$passed.Add($message)}
|
|
function Invoke-Com($object,[string]$name,[object[]]$arguments){$values=@(foreach($v in $arguments){if($null -eq $v){$null}else{$v.PSObject.BaseObject}});$object.GetType().InvokeMember($name,[Reflection.BindingFlags]::InvokeMethod,$null,$object,$values)}
|
|
function Get-Com($object,[string]$name,[object[]]$arguments){$values=@(foreach($v in $arguments){$v.PSObject.BaseObject});$object.GetType().InvokeMember($name,[Reflection.BindingFlags]::GetProperty,$null,$object,$values)}
|
|
function Read-Table($database,[string]$table){
|
|
if($table -notmatch '^[A-Za-z]+$'){throw 'Unexpected table name'}
|
|
$view=Invoke-Com $database 'OpenView' @('SELECT * FROM `'+$table+'`');$null=Invoke-Com $view 'Execute' @()
|
|
$columns=Get-Com $view 'ColumnInfo' @(0);$count=Get-Com $columns 'FieldCount' @();$rows=@()
|
|
while($null -ne ($record=Invoke-Com $view 'Fetch' @())){
|
|
$row=[ordered]@{};for($i=1;$i -le $count;$i++){$row[(Get-Com $columns 'StringData' @($i))]=Get-Com $record 'StringData' @($i)}
|
|
$rows+=,[pscustomobject]$row
|
|
}
|
|
$null=Invoke-Com $view 'Close' @();return $rows
|
|
}
|
|
# These APIs read the CAB and native EXE manifest as data. No MSI action,
|
|
# executable entry point, DllMain, Word, tray activation or installer is run.
|
|
Add-Type @'
|
|
using System;using System.IO;using System.Runtime.InteropServices;using System.Text;
|
|
public static class CompanionPackageStreams {
|
|
[DllImport("msi.dll",CharSet=CharSet.Unicode)]static extern uint MsiOpenDatabase(string file,IntPtr persist,out IntPtr db);
|
|
[DllImport("msi.dll",CharSet=CharSet.Unicode)]static extern uint MsiDatabaseOpenView(IntPtr db,string sql,out IntPtr view);
|
|
[DllImport("msi.dll")]static extern uint MsiViewExecute(IntPtr view,IntPtr record);
|
|
[DllImport("msi.dll")]static extern uint MsiViewFetch(IntPtr view,out IntPtr record);
|
|
[DllImport("msi.dll")]static extern uint MsiRecordReadStream(IntPtr record,uint field,byte[] data,ref uint size);
|
|
[DllImport("msi.dll")]static extern uint MsiCloseHandle(IntPtr handle);
|
|
[DllImport("kernel32.dll",CharSet=CharSet.Unicode,SetLastError=true)]static extern IntPtr LoadLibraryEx(string file,IntPtr reserved,uint flags);
|
|
[DllImport("kernel32.dll",CharSet=CharSet.Unicode,SetLastError=true)]static extern IntPtr FindResource(IntPtr module,IntPtr name,IntPtr type);
|
|
[DllImport("kernel32.dll")]static extern IntPtr LoadResource(IntPtr module,IntPtr resource);
|
|
[DllImport("kernel32.dll")]static extern IntPtr LockResource(IntPtr resource);
|
|
[DllImport("kernel32.dll")]static extern uint SizeofResource(IntPtr module,IntPtr resource);
|
|
[DllImport("kernel32.dll")]static extern bool FreeLibrary(IntPtr module);
|
|
static void Check(uint result){if(result!=0)throw new System.ComponentModel.Win32Exception((int)result);}
|
|
public static void Cabinet(string file,string destination){IntPtr db=IntPtr.Zero,view=IntPtr.Zero,record=IntPtr.Zero;try{Check(MsiOpenDatabase(file,IntPtr.Zero,out db));Check(MsiDatabaseOpenView(db,"SELECT `Data` FROM `_Streams` WHERE `Name`='payload.cab'",out view));Check(MsiViewExecute(view,IntPtr.Zero));Check(MsiViewFetch(view,out record));using(var output=File.Create(destination)){var buffer=new byte[65536];while(true){uint size=(uint)buffer.Length;Check(MsiRecordReadStream(record,1,buffer,ref size));if(size==0)break;output.Write(buffer,0,(int)size);}}}finally{if(record!=IntPtr.Zero)MsiCloseHandle(record);if(view!=IntPtr.Zero)MsiCloseHandle(view);if(db!=IntPtr.Zero)MsiCloseHandle(db);}}
|
|
public static string Manifest(string file){var module=LoadLibraryEx(file,IntPtr.Zero,0x22);if(module==IntPtr.Zero)throw new System.ComponentModel.Win32Exception();try{var resource=FindResource(module,(IntPtr)1,(IntPtr)24);if(resource==IntPtr.Zero)throw new InvalidDataException("Missing setup execution-level manifest.");var data=LockResource(LoadResource(module,resource));var bytes=new byte[SizeofResource(module,resource)];Marshal.Copy(data,bytes,0,bytes.Length);return Encoding.UTF8.GetString(bytes);}finally{FreeLibrary(module);}}
|
|
}
|
|
'@
|
|
$verify=Join-Path $SetupDirectory 'verification'
|
|
if(Test-Path $verify){throw 'Verification output already exists; reuse the existing report instead of repeating qualification.'}
|
|
New-Item -ItemType Directory -Path $verify | Out-Null
|
|
$msi=Join-Path $SetupDirectory 'PlotDirectorCompanion.msi';$exe=Join-Path $SetupDirectory 'PlotDirectorCompanionSetup.exe'
|
|
Assert-Package ($package.version -eq $release.version -and $evidence.applicationCommit -eq $package.commit) 'Exact release payload source and setup evidence agree'
|
|
Assert-Package ((Get-FileHash $exe).Hash -eq $evidence.setupSha256 -and (Get-FileHash $msi).Hash -eq $evidence.msiSha256) 'Final EXE and MSI hashes agree with build evidence'
|
|
$assembly=[Reflection.Assembly]::Load([IO.File]::ReadAllBytes($exe))
|
|
Assert-Package ($assembly.GetName().Version.ToString() -eq $release.version -and [Diagnostics.FileVersionInfo]::GetVersionInfo($exe).FileVersion -eq $release.version) 'Bootstrapper assembly and file versions match the release'
|
|
$embedded=Join-Path $verify 'embedded.msi';$source=$assembly.GetManifestResourceStream('Companion.msi');$dest=[IO.File]::Create($embedded);try{$source.CopyTo($dest)}finally{$source.Dispose();$dest.Dispose()}
|
|
Assert-Package ((Get-FileHash $embedded).Hash -eq (Get-FileHash $msi).Hash) 'EXE embeds the exact signed MSI with no external payload dependency'
|
|
[xml]$manifest=[CompanionPackageStreams]::Manifest($exe)
|
|
Assert-Package ($manifest.SelectSingleNode('//*[local-name()="requestedExecutionLevel"]').level -eq 'asInvoker') 'Setup has an explicit asInvoker execution manifest'
|
|
$signatures=@(foreach($file in @($exe,$msi)){
|
|
$signature=Get-AuthenticodeSignature $file
|
|
Assert-Package ($signature.SignerCertificate.Thumbprint -eq $package.certificateThumbprint) "$(Split-Path $file -Leaf) uses the existing developer signer"
|
|
Assert-Package ($signature.Status -eq 'Valid' -or ($signature.Status -in @('UnknownError','NotTrusted') -and $signature.StatusMessage -match 'not trusted|untrusted')) "$(Split-Path $file -Leaf) signature is valid or limited solely by developer trust"
|
|
@{file=Split-Path $file -Leaf;status=[string]$signature.Status;message=$signature.StatusMessage;thumbprint=$signature.SignerCertificate.Thumbprint}
|
|
})
|
|
$installer=New-Object -ComObject WindowsInstaller.Installer
|
|
$database=Invoke-Com $installer 'OpenDatabase' @($msi,0);$baseline=Invoke-Com $installer 'OpenDatabase' @($BaselineMsi,0)
|
|
$tables=@{};foreach($table in @('Property','File','Component','Directory','Registry','Shortcut','Upgrade','InstallExecuteSequence','InstallUISequence','Media','RemoveFile','LaunchCondition','Feature','FeatureComponents')){$tables[$table]=@(Read-Table $database $table)}
|
|
$properties=@{};foreach($row in $tables.Property){$properties[$row.Property]=$row.Value}
|
|
$oldProperties=@{};foreach($row in @(Read-Table $baseline 'Property')){$oldProperties[$row.Property]=$row.Value}
|
|
Assert-Package ($properties.ProductVersion -eq $release.msiVersion -and $properties.COMPANIONVERSION -eq $release.version -and $properties.SOURCECOMMIT -eq $package.commit) 'MSI version and source metadata match the final application'
|
|
Assert-Package ($properties.ProductCode -eq $release.productCode -and $properties.ProductCode -ne $oldProperties.ProductCode -and $properties.UpgradeCode -eq $oldProperties.UpgradeCode) "Major upgrade changes ProductCode and preserves the baseline UpgradeCode ($($oldProperties.ProductVersion))"
|
|
Assert-Package (!$properties.ContainsKey('ALLUSERS') -and $properties.MSIINSTALLPERUSER -eq '1' -and @($tables.LaunchCondition | Where-Object Condition -eq 'NOT ALLUSERS').Count -eq 1) 'MSI is authored strictly per-user'
|
|
$summary=Get-Com $database 'SummaryInformation' @(0)
|
|
Assert-Package (([int](Get-Com $summary 'Property' @(15)) -band 10) -eq 10 -and (Get-Com $summary 'Property' @(7)) -eq 'x64;1033') 'MSI summary is compressed x64 and requires no elevated privileges'
|
|
Assert-Package (@($tables.Directory | Where-Object {$_.Directory -eq 'INSTALLDIR' -and $_.Directory_Parent -eq 'ProgramsDir' -and $_.DefaultDir -like '*PlotDirector Companion'}).Count -eq 1) 'Install root remains current-user LocalAppData Programs'
|
|
$components=@{};foreach($row in $tables.Component){$components[$row.Component]=$row}
|
|
$oldComponents=@{};foreach($row in @(Read-Table $baseline 'Component')){$oldComponents[$row.Component]=$row}
|
|
$oldPaths=@{};foreach($row in @(Read-Table $baseline 'File')){$component=$oldComponents[$row.Component_];$oldPaths[$component.Directory_+'/'+($row.FileName -split '\|')[-1]]=$component.ComponentId}
|
|
$cab=Join-Path $verify 'payload.cab';[CompanionPackageStreams]::Cabinet($msi,$cab)
|
|
$expanded=Join-Path $verify 'cab';New-Item -ItemType Directory -Path $expanded | Out-Null
|
|
Invoke-Checked expand.exe @('-F:*',$cab,$expanded)
|
|
$installed=@();$agentId=$null
|
|
foreach($file in $tables.File){
|
|
$component=$components[$file.Component_];$name=($file.FileName -split '\|')[-1]
|
|
Assert-Package ($component.Directory_ -in @('INSTALLDIR','AGENTDIR')) "Payload directory is application-only: $name"
|
|
$relative=if($component.Directory_ -eq 'AGENTDIR'){'Agent/'+$name}else{$name}
|
|
$expected=Join-Path $PackagePath $relative;$actual=Join-Path $expanded $file.File
|
|
Assert-Package ((Test-Path $expected) -and (Get-FileHash $actual).Hash -eq (Get-FileHash $expected).Hash) "Embedded CAB hash matches verified payload: $relative"
|
|
Assert-Package ((Get-Item $actual).Length -eq [long]$file.FileSize) "MSI file size matches payload: $relative"
|
|
$logical=$component.Directory_+'/'+$name
|
|
if($oldPaths.ContainsKey($logical)){Assert-Package ($component.ComponentId -eq $oldPaths[$logical]) "Component GUID remains stable from baseline $($oldProperties.ProductVersion): $relative"}
|
|
$installed+=@{path=$relative;sha256=(Get-FileHash $actual).Hash;componentId=$component.ComponentId;fileId=$file.File}
|
|
if($relative -eq 'Agent/PlotDirector.Companion.Agent.exe'){$agentId=$file.File}
|
|
}
|
|
$expectedRuntime=@($package.files | Where-Object {$_.path -notlike '*.pdb'}).Count+1
|
|
Assert-Package ($installed.Count -eq $expectedRuntime -and @(Get-ChildItem $expanded -File).Count -eq $installed.Count) 'CAB includes the complete runtime inventory plus package.json, without symbols or extra state'
|
|
$preflightFiles=$assembly.GetType('SetupRelease',$true).GetField('PayloadFiles',[Reflection.BindingFlags]'Static,NonPublic').GetValue($null)
|
|
Assert-Package (@(Compare-Object @($installed.path | ForEach-Object {$_.Replace('/','\')}) @($preflightFiles)).Count -eq 0) 'Replacement preflight inventory exactly matches every embedded MSI payload path'
|
|
$registry=$tables.Registry
|
|
Assert-Package (@($registry | Where-Object {$_.Root -ne '1' -or $_.Key -notin @('Software\Microsoft\Office\Word\Addins\PlotDirector.WordAddIn','Software\PlotDirector\Companion')}).Count -eq 0) 'All MSI registry writes are limited to exact Companion HKCU keys'
|
|
Assert-Package (@($registry | Where-Object {$_.Name -eq 'Manifest' -and $_.Value -eq 'file:///[INSTALLDIR]PlotDirector.WordAddIn.vsto|vstolocal'}).Count -eq 1 -and @($registry | Where-Object {$_.Name -eq 'LoadBehavior' -and $_.Value -eq '#3'}).Count -eq 1) 'Word registration uses signed local manifest and LoadBehavior3'
|
|
Assert-Package ($tables.Shortcut.Count -eq 2 -and @($tables.Shortcut | Where-Object {$_.Target -ne ('[#'+$agentId+']') -or $_.Directory_ -notin @('MENUFOLDER','StartupFolder')}).Count -eq 0) 'Start-menu and Startup shortcuts target the installed tray executable'
|
|
Assert-Package (@($tables.RemoveFile | Where-Object {$_.DirProperty -ne 'MENUFOLDER' -or $_.FileName -or $_.InstallMode -ne '2'}).Count -eq 0) 'Uninstall cleanup excludes user state, documents, credentials and logs'
|
|
$sequence=@{};foreach($row in $tables.InstallExecuteSequence){$sequence[$row.Action]=[int]$row.Sequence}
|
|
Assert-Package ($sequence.InstallInitialize -lt $sequence.RemoveExistingProducts -and $sequence.RemoveExistingProducts -lt $sequence.InstallFiles -and $sequence.InstallFiles -lt $sequence.InstallFinalize) 'Older MSI removal is transactional and precedes new files'
|
|
Assert-Package (@(@('RemoveFiles','RemoveRegistryValues','RemoveShortcuts','RegisterProduct','PublishProduct') | Where-Object {!$sequence.ContainsKey($_)}).Count -eq 0) 'Standard MSI installation and unified removal actions are present'
|
|
$older=@($tables.Upgrade | Where-Object ActionProperty -eq 'OLDPRODUCTS');$newer=@($tables.Upgrade | Where-Object ActionProperty -eq 'NEWERPRODUCTS')
|
|
Assert-Package ($older.Count -eq 1 -and $older[0].VersionMax -eq $release.msiVersion -and [int]$older[0].Attributes -eq 0 -and $older[0].Remove -eq 'ALL' -and [version]$oldProperties.ProductVersion -lt [version]$older[0].VersionMax) "Upgrade range includes baseline $($oldProperties.ProductVersion) without migrating advertised feature state"
|
|
Assert-Package ($newer.Count -eq 1 -and $newer[0].VersionMin -eq $release.msiVersion -and [int]$newer[0].Attributes -eq 2 -and @($tables.LaunchCondition | Where-Object Condition -eq 'Installed OR NOT NEWERPRODUCTS').Count -eq 1) 'Newer versions are detected without removal and blocked from downgrade'
|
|
$runtime=Get-Content -Raw (Join-Path $PackagePath 'Agent\PlotDirector.Companion.Agent.runtimeconfig.json') | ConvertFrom-Json
|
|
$deps=Get-Content -Raw (Join-Path $PackagePath 'Agent\PlotDirector.Companion.Agent.deps.json') | ConvertFrom-Json
|
|
Assert-Package ($runtime.runtimeOptions.tfm -eq 'net10.0' -and @($runtime.runtimeOptions.frameworks | Where-Object name -eq 'Microsoft.WindowsDesktop.App').Count -eq 1 -and $deps.runtimeTarget.name -like '*/win-x64') 'Tray depends on existing .NET10 Windows Desktop x64 runtime'
|
|
$sourceCode=Get-Content -Raw (Join-Path $PSScriptRoot 'Setup.cs')
|
|
Assert-Package ($sourceCode.Contains('GetCurrentPackageFullName') -and $sourceCode.Contains('Win32_Process') -and $sourceCode.Contains('CompanionInstallerInventory.RequireCurrentUser') -and $sourceCode.Contains('product != "PlotDirector.WordAddIn"') -and $sourceCode.Contains('if (result == -401)')) 'Bootstrapper retains normal-user escape, native context checks and exact-product stale metadata handling'
|
|
$result=@{version=$release.version;sourceCommit=$package.commit;passed=$passed;installedInventory=$installed;signatures=$signatures;msiProperties=$properties;upgrade=$tables.Upgrade;executeSequence=$tables.InstallExecuteSequence;manual='Installation, upgrade/uninstall/rollback, trust, Word restart, visual/theme/DPI/accessibility and author workflow acceptance not performed.'}
|
|
$result | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $ReportPath -Encoding UTF8
|
|
Write-Output "PASS package qualification: $($passed.Count) assertions; neither installer nor application was executed."
|