diff --git a/cc.ps1 b/cc.ps1 index 86a9b6f..f4c11b1 100644 --- a/cc.ps1 +++ b/cc.ps1 @@ -1,6 +1,6 @@ [CmdletBinding()] param( - [Parameter(Position = 0)][ValidateSet('doctor', 'plan', 'apply', 'sync', 'status', 'configs', 'capture', 'restore', 'schedule', 'unschedule', 'menu')][string]$Command = 'menu', + [Parameter(Position = 0)][ValidateSet('doctor', 'plan', 'apply', 'sync', 'update-software', 'status', 'configs', 'capture', 'restore', 'schedule', 'unschedule', 'menu')][string]$Command = 'menu', [string]$Machine, [string]$Config, [string]$OutputPath, diff --git a/src/Core.psm1 b/src/Core.psm1 index 7933690..0a82b70 100644 --- a/src/Core.psm1 +++ b/src/Core.psm1 @@ -21,6 +21,29 @@ function Get-OperationPlan { [pscustomobject]@{ effective = $effective; packages = $packagePlan; configs = $configPlan; state = $state; settings = $settings } } +function Get-SoftwareUpdatePlan { + param([string]$Machine, [string]$RepositoryRoot, $Paths) + $state = Read-JsonState -Path $Paths.State -Default ([ordered]@{ schemaVersion = 1; configs = [ordered]@{} }) + if (-not $state.Contains('configs')) { $state.configs = [ordered]@{} } + $effective = Resolve-MachineManifest -RepositoryRoot $RepositoryRoot -Machine $Machine + $wingetPackages = @($effective.packages | Where-Object { -not $_.PSObject.Properties['provider'] -or $_.provider -eq 'winget' }) + $inventory = if ($wingetPackages.Count) { Get-WingetInventory } else { @{} } + $packagePlan = [System.Collections.Generic.List[object]]::new() + foreach ($package in $effective.packages) { + try { + $selected = if ($package.PSObject.Properties['provider'] -and $package.provider -eq 'portable') { + Resolve-PackageRelease -Package $package + } + else { $package } + foreach ($operation in @(Get-PackagePlan -Packages @($selected) -Inventory $inventory -DataRoot $Paths.Root)) { $packagePlan.Add($operation) } + } + catch { + $packagePlan.Add([pscustomobject]@{ kind = 'package'; name = $package.id; action = 'Failed'; reason = "Release lookup failed: $($_.Exception.Message)"; package = $package }) + } + } + [pscustomobject]@{ effective = $effective; packages = @($packagePlan); configs = @(); state = $state } +} + function Invoke-Doctor { param([string]$Machine, [string]$RepositoryRoot, $Paths) $checks = [System.Collections.Generic.List[object]]::new() @@ -55,14 +78,14 @@ function Invoke-Doctor { } function Invoke-ApplyPlan { - param($Plan, [string]$Machine, [string]$RepositoryRoot, $Paths, [string]$Revision, [switch]$ForceConfigs) - $result = New-BaseResult 'apply' + param($Plan, [string]$Machine, [string]$RepositoryRoot, $Paths, [string]$Revision, [switch]$ForceConfigs, [string]$Command = 'apply') + $result = New-BaseResult $Command $result.revision = $Revision $lock = $null try { $lock = Enter-ApplyLock -Paths $Paths } catch { $result.succeeded = $false; $result.exitCode = 10; $result.warnings = @($_.Exception.Message); return [pscustomobject]$result } - $run = New-RunContext -Paths $Paths -Command 'apply' -Revision $Revision + $run = New-RunContext -Paths $Paths -Command $Command -Revision $Revision $failedPackages = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) $rebootRequired = $false try { @@ -107,7 +130,7 @@ function Invoke-ApplyPlan { $failures = @($run.results | Where-Object status -in @('Failed', 'Conflict', 'Skipped')) $result.succeeded = $failures.Count -eq 0 $result.exitCode = if (-not $result.succeeded) { 5 } elseif ($rebootRequired) { 6 } else { 0 } - $Plan.state.lastAppliedRevision = $Revision + if ($Command -eq 'apply') { $Plan.state.lastAppliedRevision = $Revision } Complete-Run -Run $run -Paths $Paths -State $Plan.state -Succeeded $result.succeeded return [pscustomobject]$result } @@ -170,6 +193,14 @@ function Invoke-ConfigCentral { return Invoke-SnapshotApply -Snapshot $snapshot -Machine $Machine -Paths $Paths -Revision $remoteRevision -ConfigsOnly:$ConfigsOnly -ForceConfigs:$ForceConfigs } + if ($Command -eq 'update-software') { + if ($ConfigsOnly -or $ForceConfigs) { throw 'update-software does not accept config options.' } + if ($FromSnapshot) { throw 'update-software cannot run as a snapshot child.' } + if ([string]::IsNullOrWhiteSpace($Revision)) { $Revision = Get-RepositoryRevision -RepositoryRoot $RepositoryRoot } + $softwarePlan = Get-SoftwareUpdatePlan -Machine $Machine -RepositoryRoot $RepositoryRoot -Paths $Paths + return Invoke-ApplyPlan -Plan $softwarePlan -Machine $Machine -RepositoryRoot $RepositoryRoot -Paths $Paths -Revision $Revision -Command 'update-software' + } + if ([string]::IsNullOrWhiteSpace($Revision)) { $Revision = Get-RepositoryRevision -RepositoryRoot $RepositoryRoot } $plan = Get-OperationPlan -Machine $Machine -RepositoryRoot $RepositoryRoot -Paths $Paths -ConfigsOnly:$ConfigsOnly if ($Command -eq 'apply') { return Invoke-ApplyPlan -Plan $plan -Machine $Machine -RepositoryRoot $RepositoryRoot -Paths $Paths -Revision $Revision -ForceConfigs:$ForceConfigs } @@ -221,13 +252,13 @@ function Write-ConfigCentralResult { function Show-ConfigCentralMenu { param([string]$Machine, [string]$DataRoot, [string]$RepositoryRoot) Write-Host 'Config Central' - Write-Host '1. Plan 2. Sync 3. Status 4. Doctor 5. Schedule 6. Config paths 7. Capture configs Q. Quit' + Write-Host '1. Plan 2. Update software 3. Sync 4. Status 5. Doctor 6. Schedule 7. Config paths 8. Capture configs Q. Quit' $choice = Read-Host 'Select' - $command = switch ($choice.ToUpperInvariant()) { '1' { 'plan' } '2' { 'sync' } '3' { 'status' } '4' { 'doctor' } '5' { 'schedule' } '6' { 'configs' } '7' { 'capture' } 'Q' { return } default { throw "Unknown menu choice '$choice'." } } + $command = switch ($choice.ToUpperInvariant()) { '1' { 'plan' } '2' { 'update-software' } '3' { 'sync' } '4' { 'status' } '5' { 'doctor' } '6' { 'schedule' } '7' { 'configs' } '8' { 'capture' } 'Q' { return } default { throw "Unknown menu choice '$choice'." } } $arguments = @($command, '-RepositoryRoot', $RepositoryRoot) if ($Machine) { $arguments += @('-Machine', $Machine) } if ($DataRoot) { $arguments += @('-DataRoot', $DataRoot) } & (Join-Path $RepositoryRoot 'cc.ps1') @arguments } -Export-ModuleMember -Function Get-OperationPlan, Invoke-ConfigCentral, Write-ConfigCentralResult, Show-ConfigCentralMenu +Export-ModuleMember -Function Get-OperationPlan, Get-SoftwareUpdatePlan, Invoke-ConfigCentral, Write-ConfigCentralResult, Show-ConfigCentralMenu diff --git a/src/Packages.psm1 b/src/Packages.psm1 index 5ee3a41..4322328 100644 --- a/src/Packages.psm1 +++ b/src/Packages.psm1 @@ -91,8 +91,19 @@ function Get-PackagePlan { return @($plan) } +function Resolve-PackageRelease { + param([Parameter(Mandatory)]$Package) + if ($Package.PSObject.Properties['provider'] -and $Package.provider -eq 'portable') { + return Resolve-PortablePackageRelease -Package $Package + } + return $Package +} + function Invoke-PackageOperation { param([Parameter(Mandatory)]$Operation, [string]$LogPath) + if ($Operation.action -eq 'Failed') { + return [pscustomobject]@{ name = $Operation.name; status = 'Failed'; exitCode = 1; rebootRequired = $false; message = $Operation.reason } + } if ($Operation.package.PSObject.Properties['provider'] -and $Operation.package.provider -eq 'portable') { return Invoke-PortablePackageOperation -Operation $Operation } @@ -132,4 +143,4 @@ function Invoke-PackagePlan { return @($results) } -Export-ModuleMember -Function Get-WingetInventory, Get-PackagePlan, Invoke-PackageOperation, Invoke-PackagePlan +Export-ModuleMember -Function Get-WingetInventory, Get-PackagePlan, Resolve-PackageRelease, Invoke-PackageOperation, Invoke-PackagePlan diff --git a/src/PortablePackages.psm1 b/src/PortablePackages.psm1 index 4a6839a..260e8e9 100644 --- a/src/PortablePackages.psm1 +++ b/src/PortablePackages.psm1 @@ -44,6 +44,84 @@ function Get-PortableLauncherContent { Get-Content -LiteralPath (Join-Path $PSScriptRoot 'portable-launcher.ps1') -Raw } +function Invoke-PortableReleaseRequest { + param([Parameter(Mandatory)][string]$Uri, [Parameter(Mandatory)][ValidateSet('Json', 'Text')][string]$Kind) + try { $response = Invoke-WebRequest -Uri $Uri -MaximumRedirection 5 -ErrorAction Stop } + catch { throw "Portable release request failed for '$Uri': $($_.Exception.Message)" } + if ($null -eq $response -or $null -eq $response.PSObject.Properties['Content']) { throw "Portable release request returned no content for '$Uri'." } + $content = [string]$response.Content + $limit = if ($Kind -eq 'Json') { 4MB } else { 1MB } + if ([Text.Encoding]::UTF8.GetByteCount($content) -gt $limit) { throw "Portable release $($Kind.ToLowerInvariant()) response is too large." } + if ($Kind -eq 'Text') { return $content } + try { return $content | ConvertFrom-Json -Depth 32 } + catch { throw "Portable release API returned invalid JSON: $($_.Exception.Message)" } +} + +function Assert-PortableReleaseUrl { + param([Parameter(Mandatory)][string]$Url, [Parameter(Mandatory)][uri]$ApiUri, [Parameter(Mandatory)][string]$Description) + $uri = $null + if (-not [uri]::TryCreate($Url, [UriKind]::Absolute, [ref]$uri) -or + $uri.Scheme -ne 'https' -or $uri.UserInfo -or $uri.Fragment -or + -not [string]::Equals($uri.Authority, $ApiUri.Authority, [StringComparison]::OrdinalIgnoreCase)) { + throw "$Description URL must use HTTPS on the release API host." + } + return $uri +} + +function Resolve-PortablePackageRelease { + param([Parameter(Mandatory)]$Package) + if (-not $Package.PSObject.Properties['releaseApi']) { return $Package } + + $apiUri = [uri]$Package.releaseApi + $response = Invoke-PortableReleaseRequest -Uri $Package.releaseApi -Kind Json + $candidates = [System.Collections.Generic.List[object]]::new() + foreach ($release in @($response)) { + if ($release.draft) { continue } + if ($Package.releaseChannel -eq 'stable' -and $release.prerelease) { continue } + $match = [regex]::Match([string]$release.tag_name, '^v?(\d+\.\d+(?:\.\d+){0,2})$') + if (-not $match.Success) { continue } + $version = $null + if (-not [version]::TryParse($match.Groups[1].Value, [ref]$version)) { continue } + if ($version -lt [version]$Package.version) { continue } + $candidates.Add([pscustomobject]@{ release = $release; version = $version; versionText = $match.Groups[1].Value }) + } + if ($candidates.Count -eq 0) { throw "No eligible $($Package.releaseChannel) release at or above $($Package.version) was found for '$($Package.id)'." } + $ordered = @($candidates | Sort-Object version -Descending) + if ($ordered.Count -gt 1 -and $ordered[0].version -eq $ordered[1].version) { throw "Release API returned duplicate version '$($ordered[0].versionText)' for '$($Package.id)'." } + $selected = $ordered[0] + $assetName = $Package.assetTemplate.Replace('{version}', $selected.versionText) + $checksumName = if ($Package.PSObject.Properties['checksumAsset']) { [string]$Package.checksumAsset } else { 'SHA256SUMS' } + $assets = @($selected.release.assets) + $archiveAssets = @($assets | Where-Object { [string]::Equals([string]$_.name, $assetName, [StringComparison]::Ordinal) }) + $checksumAssets = @($assets | Where-Object { [string]::Equals([string]$_.name, $checksumName, [StringComparison]::Ordinal) }) + if ($archiveAssets.Count -ne 1) { throw "Release '$($selected.release.tag_name)' must contain exactly one '$assetName' asset." } + if ($checksumAssets.Count -ne 1) { throw "Release '$($selected.release.tag_name)' must contain exactly one '$checksumName' asset." } + + $archiveUri = Assert-PortableReleaseUrl -Url ([string]$archiveAssets[0].browser_download_url) -ApiUri $apiUri -Description 'Portable archive' + $checksumUri = Assert-PortableReleaseUrl -Url ([string]$checksumAssets[0].browser_download_url) -ApiUri $apiUri -Description 'Portable checksum' + if ($archiveUri.AbsolutePath -notlike '*.zip') { throw 'Portable release archive URL must identify a ZIP file.' } + $checksumText = Invoke-PortableReleaseRequest -Uri $checksumUri.AbsoluteUri -Kind Text + $matches = [System.Collections.Generic.List[string]]::new() + foreach ($line in $checksumText -split '\r?\n') { + $checksumMatch = [regex]::Match($line, '^([a-fA-F0-9]{64})\s+\*?(.+)$') + if ($checksumMatch.Success -and [string]::Equals($checksumMatch.Groups[2].Value, $assetName, [StringComparison]::Ordinal)) { + $matches.Add($checksumMatch.Groups[1].Value.ToLowerInvariant()) + } + } + if ($matches.Count -ne 1) { throw "Checksum asset must contain exactly one SHA-256 entry for '$assetName'." } + if ($selected.versionText -eq $Package.version -and $matches[0] -ne $Package.sha256.ToLowerInvariant()) { + throw "Published checksum for pinned version $($Package.version) differs from the manifest; review the release before updating." + } + + $resolved = [ordered]@{} + foreach ($property in $Package.PSObject.Properties) { $resolved[$property.Name] = $property.Value } + $resolved.version = $selected.versionText + $resolved.url = $archiveUri.AbsoluteUri + $resolved.sha256 = $matches[0] + $resolved.executable = $Package.executableTemplate.Replace('{version}', $selected.versionText) + return [pscustomobject]$resolved +} + function Get-PortablePackagePlan { param($Package, [string]$DataRoot) $ErrorActionPreference = 'Stop' @@ -197,4 +275,4 @@ function Invoke-PortablePackageOperation { } } -Export-ModuleMember -Function Get-PortablePackagePlan, Invoke-PortablePackageOperation +Export-ModuleMember -Function Get-PortablePackagePlan, Resolve-PortablePackageRelease, Invoke-PortablePackageOperation diff --git a/tests/Cli.Tests.ps1 b/tests/Cli.Tests.ps1 index 1f5042a..1baf64e 100644 --- a/tests/Cli.Tests.ps1 +++ b/tests/Cli.Tests.ps1 @@ -15,3 +15,12 @@ Describe 'CLI error reporting' { $result.error | Should -Not -BeNullOrEmpty } } + +Describe 'Software update CLI' { + It 'recognizes update-software as a command' { + $output = & (Join-Path $PSHOME $(if ($IsWindows) { 'pwsh.exe' } else { 'pwsh' })) -NoProfile -File "$PSScriptRoot/../cc.ps1" update-software -Machine missing-test-machine -DataRoot "$TestDrive/software-data" 2>&1 + $LASTEXITCODE | Should -Be 2 + ($output | Out-String) | Should -Match 'Missing machine manifest' + ($output | Out-String) | Should -Not -Match 'ValidateSet|Cannot validate argument' + } +} diff --git a/tests/Core.Tests.ps1 b/tests/Core.Tests.ps1 index 8169f01..045f74b 100644 --- a/tests/Core.Tests.ps1 +++ b/tests/Core.Tests.ps1 @@ -116,3 +116,70 @@ Describe 'Portable workflow integration' { } } } + +Describe 'Software update command' { + It 'resolves portable releases, plans WinGet once, and skips configs' { + InModuleScope Core -Parameters @{ Working = $TestDrive } { + Mock Read-JsonState { @{ schemaVersion = 1; configs = @{} } } + Mock Resolve-MachineManifest { [pscustomobject]@{ packages = @( + [pscustomobject]@{ id = 'Portable.App'; provider = 'portable'; source = 'owner'; version = '1.0'; update = 'pinned'; releaseApi = 'https://example.org/api/v1/repos/a/b/releases' }, + [pscustomobject]@{ id = 'Winget.App'; source = 'winget'; update = 'latest' } + ); configs = @([pscustomobject]@{ name = 'never-plan-config' }) } } + Mock Resolve-PackageRelease { [pscustomobject]@{ id = 'Portable.App'; provider = 'portable'; source = 'owner'; version = '2.0'; update = 'pinned' } } + Mock Get-WingetInventory { @{} } + Mock Get-PackagePlan { + [pscustomobject]@{ kind = 'package'; name = $Packages[0].id; action = 'Install'; reason = 'Missing'; package = $Packages[0] } + } + Mock Get-ConfigPlan { throw 'Configs must not be planned' } + $paths = Get-ConfigCentralPaths -DataRoot "$Working/software-plan" + $plan = Get-SoftwareUpdatePlan -Machine test -RepositoryRoot $Working -Paths $paths + $plan.packages.name | Should -Be @('Portable.App', 'Winget.App') + $plan.configs.Count | Should -Be 0 + Should -Invoke Resolve-PackageRelease -Times 1 -Exactly + Should -Invoke Get-WingetInventory -Times 1 -Exactly + Should -Invoke Get-PackagePlan -Times 2 -Exactly + Should -Invoke Get-ConfigPlan -Times 0 + } + } + + It 'continues planning after an independent release lookup failure' { + InModuleScope Core -Parameters @{ Working = $TestDrive } { + Mock Read-JsonState { @{ schemaVersion = 1; configs = @{} } } + Mock Resolve-MachineManifest { [pscustomobject]@{ packages = @( + [pscustomobject]@{ id = 'Bad.Portable'; provider = 'portable'; source = 'owner'; version = '1.0'; update = 'pinned' }, + [pscustomobject]@{ id = 'Good.Portable'; provider = 'portable'; source = 'owner'; version = '1.0'; update = 'pinned' } + ); configs = @() } } + Mock Resolve-PackageRelease { if ($Package.id -eq 'Bad.Portable') { throw 'API unavailable' }; $Package } + Mock Get-PackagePlan { [pscustomobject]@{ kind = 'package'; name = $Packages[0].id; action = 'None'; reason = 'Current'; package = $Packages[0] } } + $paths = Get-ConfigCentralPaths -DataRoot "$Working/release-failure" + $plan = Get-SoftwareUpdatePlan -Machine test -RepositoryRoot $Working -Paths $paths + $plan.packages.action | Should -Be @('Failed', 'None') + $plan.packages[0].reason | Should -Match 'API unavailable' + } + } + + It 'runs package-only work under the update-software command name' { + InModuleScope Core -Parameters @{ Working = $TestDrive } { + Mock Get-RepositoryRevision { 'abc' } + Mock Get-SoftwareUpdatePlan { [pscustomobject]@{ packages = @(); configs = @(); state = @{ schemaVersion = 1; configs = @{} } } } + Mock Invoke-ApplyPlan { [pscustomobject]@{ command = $Command; succeeded = $true; exitCode = 0 } } + $paths = Get-ConfigCentralPaths -DataRoot "$Working/software-command" + $result = Invoke-ConfigCentral -Command update-software -Machine test -Paths $paths -RepositoryRoot $Working + $result.command | Should -Be 'update-software' + Should -Invoke Invoke-ApplyPlan -Times 1 -Exactly -ParameterFilter { $Command -eq 'update-software' } + } + } + + It 'records the software run without claiming configs used that revision' { + InModuleScope Core -Parameters @{ Working = $TestDrive } { + $paths = Get-ConfigCentralPaths -DataRoot "$Working/software-state" + $plan = [pscustomobject]@{ packages = @(); configs = @(); state = @{ schemaVersion = 1; configs = @{}; lastAppliedRevision = 'previous' } } + $result = Invoke-ApplyPlan -Plan $plan -Machine test -RepositoryRoot $Working -Paths $paths -Revision newer -Command update-software + $result.command | Should -Be 'update-software' + $state = Read-JsonState $paths.State @{} + $state.lastAppliedRevision | Should -Be 'previous' + $state.lastRun.command | Should -Be 'update-software' + $state.lastRun.revision | Should -Be 'newer' + } + } +} diff --git a/tests/Packages.Tests.ps1 b/tests/Packages.Tests.ps1 index a19f63d..685b11b 100644 --- a/tests/Packages.Tests.ps1 +++ b/tests/Packages.Tests.ps1 @@ -35,6 +35,21 @@ Describe 'Package planning' { } } +Describe 'Release lookup failures' { + It 'returns a structured failure without invoking either package provider' { + InModuleScope Packages { + Mock Invoke-WingetCapture { throw 'WinGet must not run' } + Mock Invoke-PortablePackageOperation { throw 'Portable install must not run' } + $operation = [pscustomobject]@{ action = 'Failed'; name = 'broken'; reason = 'Release API unavailable'; package = [pscustomobject]@{ provider = 'portable' } } + $result = Invoke-PackageOperation $operation + $result.status | Should -Be 'Failed' + $result.message | Should -Be 'Release API unavailable' + Should -Invoke Invoke-WingetCapture -Times 0 + Should -Invoke Invoke-PortablePackageOperation -Times 0 + } + } +} + Describe 'WinGet signed process exit codes' { It 'preserves the HRESULT bits and diagnostics for a negative exit code' { InModuleScope Packages { diff --git a/tests/PortablePackages.Tests.ps1 b/tests/PortablePackages.Tests.ps1 index 34849b2..271e0e7 100644 --- a/tests/PortablePackages.Tests.ps1 +++ b/tests/PortablePackages.Tests.ps1 @@ -164,3 +164,80 @@ Describe 'Portable launcher process status' { $output | Should -Be 'document with spaces.pdf' } } + +Describe 'Portable release discovery' { + InModuleScope PortablePackages { + BeforeEach { + $package = [pscustomobject]@{ + id = 'presenter'; provider = 'portable'; source = 'gitea'; version = '1.2.3'; update = 'pinned' + url = 'https://example.org/download/v1.2.3/presenter-1.2.3.zip'; sha256 = ('a' * 64); executable = 'presenter-1.2.3/app.exe' + releaseApi = 'https://example.org/api/v1/repos/owner/project/releases'; releaseChannel = 'prerelease' + assetTemplate = 'presenter-{version}.zip'; executableTemplate = 'presenter-{version}/app.exe'; checksumAsset = 'SHA256SUMS' + } + $script:releases = @( + [pscustomobject]@{ tag_name = 'v2.0.0'; draft = $false; prerelease = $true; assets = @( + [pscustomobject]@{ name = 'presenter-2.0.0.zip'; browser_download_url = 'https://example.org/download/v2.0.0/presenter-2.0.0.zip' }, + [pscustomobject]@{ name = 'SHA256SUMS'; browser_download_url = 'https://example.org/download/v2.0.0/SHA256SUMS' } + ) }, + [pscustomobject]@{ tag_name = 'v1.5.0'; draft = $false; prerelease = $false; assets = @( + [pscustomobject]@{ name = 'presenter-1.5.0.zip'; browser_download_url = 'https://example.org/download/v1.5.0/presenter-1.5.0.zip' }, + [pscustomobject]@{ name = 'SHA256SUMS'; browser_download_url = 'https://example.org/download/v1.5.0/SHA256SUMS' } + ) } + ) + Mock Invoke-PortableReleaseRequest { + if ($Kind -eq 'Json') { return $script:releases } + return ('b' * 64) + ' presenter-2.0.0.zip' + } + } + + It 'selects the newest eligible release and resolves exact install fields' { + $resolved = Resolve-PortablePackageRelease $package + $resolved.version | Should -Be '2.0.0' + $resolved.url | Should -Be 'https://example.org/download/v2.0.0/presenter-2.0.0.zip' + $resolved.sha256 | Should -Be ('b' * 64) + $resolved.executable | Should -Be 'presenter-2.0.0/app.exe' + $package.version | Should -Be '1.2.3' + Should -Invoke Invoke-PortableReleaseRequest -Times 2 -Exactly + } + + It 'ignores prereleases on the stable channel' { + $package.releaseChannel = 'stable' + Mock Invoke-PortableReleaseRequest { + if ($Kind -eq 'Json') { return $script:releases } + return ('c' * 64) + ' presenter-1.5.0.zip' + } + (Resolve-PortablePackageRelease $package).version | Should -Be '1.5.0' + } + + It 'rejects cross-host assets and ambiguous checksums' { + $script:releases[0].assets[0].browser_download_url = 'https://attacker.invalid/presenter-2.0.0.zip' + { Resolve-PortablePackageRelease $package } | Should -Throw '*release API host*' + $script:releases[0].assets[0].browser_download_url = 'https://example.org/download/v2.0.0/presenter-2.0.0.zip' + Mock Invoke-PortableReleaseRequest { + if ($Kind -eq 'Json') { return $script:releases } + return (('b' * 64) + " presenter-2.0.0.zip`n" + ('c' * 64) + ' presenter-2.0.0.zip') + } + { Resolve-PortablePackageRelease $package } | Should -Throw '*exactly one SHA-256*' + } + + It 'rejects a changed checksum for the pinned release' { + $script:releases = @([pscustomobject]@{ tag_name = 'v1.2.3'; draft = $false; prerelease = $true; assets = @( + [pscustomobject]@{ name = 'presenter-1.2.3.zip'; browser_download_url = 'https://example.org/download/v1.2.3/presenter-1.2.3.zip' }, + [pscustomobject]@{ name = 'SHA256SUMS'; browser_download_url = 'https://example.org/download/v1.2.3/SHA256SUMS' } + ) }) + Mock Invoke-PortableReleaseRequest { + if ($Kind -eq 'Json') { return $script:releases } + return ('b' * 64) + ' presenter-1.2.3.zip' + } + { Resolve-PortablePackageRelease $package } | Should -Throw '*differs from the manifest*' + } + + It 'rejects duplicate release versions and missing exact assets' { + $script:releases += $script:releases[0].PSObject.Copy() + { Resolve-PortablePackageRelease $package } | Should -Throw '*duplicate version*' + $script:releases = @($script:releases[0]) + $script:releases[0].assets[0].name = 'wrong.zip' + { Resolve-PortablePackageRelease $package } | Should -Throw '*exactly one*' + } + } +}