From e6dfe684034b3724ec5b790569ac00b645f18753 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Tue, 27 Oct 2026 17:10:51 +0000 Subject: [PATCH 1/9] chore: prepare develop for next prerelease --- project.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/project.json b/project.json index 3458a2b..9238e36 100644 --- a/project.json +++ b/project.json @@ -1,7 +1,7 @@ { "ProjectName": "PSModuleUpdate", "Description": "Generic self-update functionality for PowerShell modules.", - "Version": "0.2.0", + "Version": "0.2.1-preview", "Preamble": [ "Set-StrictMode -Version Latest", "$ErrorActionPreference = 'Stop'" From 668bb77df6b3c5b4d11748fe686e1203c6064867 Mon Sep 17 00:00:00 2001 From: Stiwi Gabriel Courage Date: Sun, 15 Nov 2026 18:56:57 +0100 Subject: [PATCH 2/9] Add target manifest inspection, unmanaged installation opt-in, and package-not-found handling (#6) * feat: implement Get-ProviderDiscoveryParameter function and associated tests * feat: normalize PackageNotFound error handling and update related tests * feat: Add PMU testing helpers and integration tests for manifest inspection - Introduced Initialize-PMULocalProviderStart and Initialize-PMUManifestFixture functions for setting up local provider and manifest fixtures. - Created Invoke-PMUManifestFixture to streamline the invocation of manifest fixtures. - Implemented various tests for manifest inspection, including Assert-InspectedManifest, Assert-ManifestReadHash, and Assert-ManifestWorkerResult. - Added tests for handling manifest inspection errors and ensuring proper cleanup of resources. - Developed integration tests for Get-PSModuleUpdateTargetManifest, validating the behavior of the module update process under various conditions. - Ensured that all tests adhere to the expected error handling and state management for PMU operations. * fix: add tests for exact-target inspection native fixture and update skip policy * feat: Add support for replacing unmanaged installations with explicit consent - Introduced `Install-PSModuleUpdate -ReplaceUnmanagedInstallation` to allow updates for manually copied installations lacking root `PSGetModuleInfo.xml`. - Enhanced documentation in CHANGELOG.md, README.md, and RELEASE_NOTE.md to reflect new functionality. - Updated cmdlet parameters and examples in Install-PSModuleUpdate.md to include the new switch. - Implemented new helper functions: Get-NativeSnapshotPath, Get-NativeInstallParameter, Get-NativeSelectedSource, and Test-UnmanagedInstallation to support the new feature. - Added tests to ensure correct behavior for unmanaged installations and consent handling. * fix: update CodeScene exception comment for clarity on parameter handling --- CHANGELOG.md | 21 +- README.md | 96 +++++++- RELEASE_NOTE.md | 18 +- .../en-US/Get-PSModuleUpdate.md | 35 ++- .../en-US/Get-PSModuleUpdateTargetManifest.md | 187 ++++++++++++++ .../en-US/Install-PSModuleUpdate.md | 69 +++++- docs/architecture/ARCHITECTURE.md | 24 +- scripts/build/ci/CiSkipPolicy.json | 6 + .../inspection/Assert-InspectedManifest.ps1 | 10 + .../inspection/Assert-ManifestReadHash.ps1 | 10 + .../Assert-ManifestWorkerResult.ps1 | 11 + .../inspection/Clear-ManifestInspection.ps1 | 13 + .../ConvertTo-ManifestInspectionOperation.ps1 | 12 + .../ConvertTo-ManifestWorkerContext.ps1 | 15 ++ .../inspection/ConvertTo-TargetManifest.ps1 | 14 ++ .../inspection/Get-BoundTargetManifest.ps1 | 7 + .../Get-InspectedTargetManifest.ps1 | 13 + .../Initialize-ManifestInspection.ps1 | 14 ++ .../inspection/Invoke-ManifestAcquisition.ps1 | 9 + .../Invoke-ManifestWorkerProcess.ps1 | 14 ++ .../Invoke-RepositoryManifestInspection.ps1 | 14 ++ .../Invoke-TargetManifestInspection.ps1 | 12 + .../Write-ManifestInspectionError.ps1 | 7 + .../inspection/Write-ManifestWorkerError.ps1 | 8 + .../Assert-NativeInstallationSnapshot.ps1 | 4 +- .../Assert-NativeSelectedInstallation.ps1 | 2 +- .../ConvertTo-NativeWorkerOperation.ps1 | 8 +- .../Get-NativeSelectedSnapshot.ps1 | 7 +- .../installation/Get-NativeSnapshotPath.ps1 | 7 + .../installation/Invoke-NativeWorker.ps1 | 4 +- .../Invoke-NativeWorkerAction.ps1 | 13 + .../provider/ConvertTo-NativePlanRecord.ps1 | 10 + .../ConvertTo-NativeProviderContext.ps1 | 8 + .../provider/Find-ProviderResource.ps1 | 12 +- .../provider/Get-NativeInstallParameter.ps1 | 10 + .../provider/Get-NativeSelectedSource.ps1 | 12 + .../Get-ProviderDiscoveryParameter.ps1 | 16 ++ .../provider/Install-ProviderResource.ps1 | 9 +- .../provider/Test-UnmanagedInstallation.ps1 | 10 + .../staging/Get-ValidatedStagedTree.ps1 | 12 + .../staging/Initialize-StagedPackage.ps1 | 9 +- .../Get-PSModuleUpdateTargetManifest.ps1 | 35 +++ src/public/Install-PSModuleUpdate.ps1 | 23 +- tests/ModuleArchitecture.Tests.ps1 | 14 +- .../Assert-PMUManifestInspection.ps1 | 49 ++++ .../Assert-PMUManifestRepublish.ps1 | 40 +++ .../Get-PMUTestProviderFailure.ps1 | 10 + .../Initialize-PMUInspectionMock.ps1 | 14 ++ .../Initialize-PMULocalProviderStart.ps1 | 39 +++ .../Initialize-PMUManifestFixture.ps1 | 53 ++++ .../Invoke-PMULocalProviderProcess.ps1 | 24 +- .../TestHelpers/Invoke-PMUManifestFixture.ps1 | 39 +++ .../Assert-InspectedManifest.Tests.ps1 | 25 ++ .../Assert-ManifestReadHash.Tests.ps1 | 17 ++ .../Assert-ManifestWorkerResult.Tests.ps1 | 42 ++++ .../Clear-ManifestInspection.Tests.ps1 | 25 ++ ...rtTo-ManifestInspectionOperation.Tests.ps1 | 18 ++ .../ConvertTo-ManifestWorkerContext.Tests.ps1 | 17 ++ .../ConvertTo-TargetManifest.Tests.ps1 | 19 ++ .../Get-BoundTargetManifest.Tests.ps1 | 19 ++ .../Get-InspectedTargetManifest.Tests.ps1 | 22 ++ .../Initialize-ManifestInspection.Tests.ps1 | 22 ++ .../Invoke-ManifestAcquisition.Tests.ps1 | 46 ++++ .../Invoke-ManifestWorkerProcess.Tests.ps1 | 49 ++++ ...oke-RepositoryManifestInspection.Tests.ps1 | 41 ++++ .../Invoke-TargetManifestInspection.Tests.ps1 | 21 ++ .../Write-ManifestInspectionError.Tests.ps1 | 30 +++ .../Write-ManifestWorkerError.Tests.ps1 | 13 + .../installation/Assert-ExactTarget.Tests.ps1 | 15 +- ...ssert-NativeInstallationSnapshot.Tests.ps1 | 11 +- ...ssert-NativeSelectedInstallation.Tests.ps1 | 10 + .../ConvertTo-NativeWorkerOperation.Tests.ps1 | 15 ++ .../Get-NativeSelectedSnapshot.Tests.ps1 | 9 + .../Get-NativeSnapshotPath.Tests.ps1 | 9 + .../Initialize-Replacement.Tests.ps1 | 16 ++ .../Invoke-NativeWorker.Tests.ps1 | 12 + .../Invoke-NativeWorkerAction.Tests.ps1 | 28 +++ .../ConvertTo-NativePlanRecord.Tests.ps1 | 18 ++ .../ConvertTo-NativeProviderContext.Tests.ps1 | 18 ++ .../provider/Find-ProviderResource.Tests.ps1 | 49 ++++ .../Get-NativeInstallParameter.Tests.ps1 | 32 +++ .../Get-NativeSelectedSource.Tests.ps1 | 40 +++ .../Get-ProviderDiscoveryParameter.Tests.ps1 | 49 ++++ .../Install-ProviderResource.Tests.ps1 | 42 ++++ .../Test-UnmanagedInstallation.Tests.ps1 | 18 ++ .../staging/Get-ValidatedStagedTree.Tests.ps1 | 12 + .../Initialize-StagedPackage.Tests.ps1 | 14 ++ .../Get-PSModuleUpdate.Integration.Tests.ps1 | 4 +- tests/public/Get-PSModuleUpdate.Tests.ps1 | 44 +++- ...UpdateTargetManifest.Integration.Tests.ps1 | 28 +++ ...Get-PSModuleUpdateTargetManifest.Tests.ps1 | 229 ++++++++++++++++++ ...stall-PSModuleUpdate.Integration.Tests.ps1 | 7 + tests/public/Install-PSModuleUpdate.Tests.ps1 | 16 ++ tests/scripts/build/ci/CiTestDetail.Tests.ps1 | 36 +++ 94 files changed, 2258 insertions(+), 81 deletions(-) create mode 100644 docs/PSModuleUpdate/en-US/Get-PSModuleUpdateTargetManifest.md create mode 100644 src/private/inspection/Assert-InspectedManifest.ps1 create mode 100644 src/private/inspection/Assert-ManifestReadHash.ps1 create mode 100644 src/private/inspection/Assert-ManifestWorkerResult.ps1 create mode 100644 src/private/inspection/Clear-ManifestInspection.ps1 create mode 100644 src/private/inspection/ConvertTo-ManifestInspectionOperation.ps1 create mode 100644 src/private/inspection/ConvertTo-ManifestWorkerContext.ps1 create mode 100644 src/private/inspection/ConvertTo-TargetManifest.ps1 create mode 100644 src/private/inspection/Get-BoundTargetManifest.ps1 create mode 100644 src/private/inspection/Get-InspectedTargetManifest.ps1 create mode 100644 src/private/inspection/Initialize-ManifestInspection.ps1 create mode 100644 src/private/inspection/Invoke-ManifestAcquisition.ps1 create mode 100644 src/private/inspection/Invoke-ManifestWorkerProcess.ps1 create mode 100644 src/private/inspection/Invoke-RepositoryManifestInspection.ps1 create mode 100644 src/private/inspection/Invoke-TargetManifestInspection.ps1 create mode 100644 src/private/inspection/Write-ManifestInspectionError.ps1 create mode 100644 src/private/inspection/Write-ManifestWorkerError.ps1 create mode 100644 src/private/installation/Get-NativeSnapshotPath.ps1 create mode 100644 src/private/installation/Invoke-NativeWorkerAction.ps1 create mode 100644 src/private/provider/ConvertTo-NativePlanRecord.ps1 create mode 100644 src/private/provider/ConvertTo-NativeProviderContext.ps1 create mode 100644 src/private/provider/Get-NativeInstallParameter.ps1 create mode 100644 src/private/provider/Get-NativeSelectedSource.ps1 create mode 100644 src/private/provider/Get-ProviderDiscoveryParameter.ps1 create mode 100644 src/private/provider/Test-UnmanagedInstallation.ps1 create mode 100644 src/private/staging/Get-ValidatedStagedTree.ps1 create mode 100644 src/public/Get-PSModuleUpdateTargetManifest.ps1 create mode 100644 tests/TestHelpers/Assert-PMUManifestInspection.ps1 create mode 100644 tests/TestHelpers/Assert-PMUManifestRepublish.ps1 create mode 100644 tests/TestHelpers/Get-PMUTestProviderFailure.ps1 create mode 100644 tests/TestHelpers/Initialize-PMUInspectionMock.ps1 create mode 100644 tests/TestHelpers/Initialize-PMULocalProviderStart.ps1 create mode 100644 tests/TestHelpers/Initialize-PMUManifestFixture.ps1 create mode 100644 tests/TestHelpers/Invoke-PMUManifestFixture.ps1 create mode 100644 tests/private/inspection/Assert-InspectedManifest.Tests.ps1 create mode 100644 tests/private/inspection/Assert-ManifestReadHash.Tests.ps1 create mode 100644 tests/private/inspection/Assert-ManifestWorkerResult.Tests.ps1 create mode 100644 tests/private/inspection/Clear-ManifestInspection.Tests.ps1 create mode 100644 tests/private/inspection/ConvertTo-ManifestInspectionOperation.Tests.ps1 create mode 100644 tests/private/inspection/ConvertTo-ManifestWorkerContext.Tests.ps1 create mode 100644 tests/private/inspection/ConvertTo-TargetManifest.Tests.ps1 create mode 100644 tests/private/inspection/Get-BoundTargetManifest.Tests.ps1 create mode 100644 tests/private/inspection/Get-InspectedTargetManifest.Tests.ps1 create mode 100644 tests/private/inspection/Initialize-ManifestInspection.Tests.ps1 create mode 100644 tests/private/inspection/Invoke-ManifestAcquisition.Tests.ps1 create mode 100644 tests/private/inspection/Invoke-ManifestWorkerProcess.Tests.ps1 create mode 100644 tests/private/inspection/Invoke-RepositoryManifestInspection.Tests.ps1 create mode 100644 tests/private/inspection/Invoke-TargetManifestInspection.Tests.ps1 create mode 100644 tests/private/inspection/Write-ManifestInspectionError.Tests.ps1 create mode 100644 tests/private/inspection/Write-ManifestWorkerError.Tests.ps1 create mode 100644 tests/private/installation/Get-NativeSnapshotPath.Tests.ps1 create mode 100644 tests/private/installation/Invoke-NativeWorkerAction.Tests.ps1 create mode 100644 tests/private/provider/ConvertTo-NativePlanRecord.Tests.ps1 create mode 100644 tests/private/provider/ConvertTo-NativeProviderContext.Tests.ps1 create mode 100644 tests/private/provider/Get-NativeInstallParameter.Tests.ps1 create mode 100644 tests/private/provider/Get-NativeSelectedSource.Tests.ps1 create mode 100644 tests/private/provider/Get-ProviderDiscoveryParameter.Tests.ps1 create mode 100644 tests/private/provider/Test-UnmanagedInstallation.Tests.ps1 create mode 100644 tests/private/staging/Get-ValidatedStagedTree.Tests.ps1 create mode 100644 tests/public/Get-PSModuleUpdateTargetManifest.Integration.Tests.ps1 create mode 100644 tests/public/Get-PSModuleUpdateTargetManifest.Tests.ps1 diff --git a/CHANGELOG.md b/CHANGELOG.md index 4f3bdc5..33c826f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,20 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), ### Added +- Add `Install-PSModuleUpdate -ReplaceUnmanagedInstallation` as an explicit, + default-off opt-in for manually copied installations lacking root + `PSGetModuleInfo.xml`. Install the exact planned target through the native + provider, using Force only for a target-directory collision. Present unreadable + or mismatching metadata still fails; identity, repository, scope, verification, + backup, journal and rollback safeguards remain enforced. +- Add `Get-PSModuleUpdateTargetManifest` for exact-candidate manifest inspection + from an unmodified live plan, using owned staging without installation or + target import. Complete manifest PrivateData is returned as data only. + An internal manifest binding rejects changed content during later install + staging, including same-version republishing, before installed-file mutation. + Per-call credentials, trust/license consent, source binding and cleanup remain + enforced. Planning and install WhatIf remain acquisition-free. + ### Changed ### Deprecated @@ -16,6 +30,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), ### Fixed +- Normalize PSResourceGet's structured `PackageNotFound` discovery error to + terminating `PMU.PackageNotFound`, including command-suffixed provider IDs. + Missing packages produce no update plan or fallback query; provider + diagnostics remain withheld. Unrelated discovery, authentication and + permission failures retain their existing error contracts. + ### Security ## [0.2.0] - 2026-10-27 @@ -104,4 +124,3 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), - Pass the owned temporary dependency root between `Run Tests` workflow steps so NovaModuleTools is discoverable for CI and changelog validation, with ownership-validated cleanup even after a failed consumer step. - diff --git a/README.md b/README.md index 5e5597d..54f3965 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,9 @@ installation. It targets PowerShell 7.4+ and uses `Microsoft.PowerShell.PSResourceGet` 1.2.0 for discovery and declares that exact version as a module dependency. The unreleased update implementation uses PowerShellGet 2.2.5 and PackageManagement 1.4.8.1 for staging and native -`Update-Module`, without Force or an `Install-Module` fallback. It never +`Update-Module` for managed installations. An explicit unmanaged-installation +opt-in uses exact-version `Install-Module`, with Force only for a target-directory +collision. It never persistently configures consumer repositories, stores credentials, elevates privileges, or reloads the updated module. @@ -23,7 +25,7 @@ privileges, or reloads the updated module. or `preview03`, matching the Gerber/NovaModuleTools release workflow. PowerShellGet 2.2.5 rejects dotted labels such as `preview.2`; those labels remain valid for PMU's semantic comparison but are outside this native update scope. -No Force, beta provider or alternate installer is introduced to bypass that +No beta provider or alternate installer is introduced to bypass that limitation. See [current qualification](docs/architecture/TESTING.md#native-update-transition) for successful Gallery evidence and the remaining gates. Historical G-4A3 @@ -47,6 +49,53 @@ After reviewing the plan, install it: $update | Install-PSModuleUpdate ``` +For a manually copied development installation with no root +`PSGetModuleInfo.xml`, explicitly opt in after reviewing the plan: + +```powershell +$update | Install-PSModuleUpdate -ReplaceUnmanagedInstallation +``` + +The switch defaults to off; without it, missing native metadata still fails +with `PMU.UnsupportedInstallation`. Present-but-unreadable or mismatching +metadata is never treated as unmanaged. The opt-in installs only the exact +planned version from the bound repository into the selected scope. Native +Force is used only if the target directory already exists, after the existing +GUID checks and verified backup. Tree verification, journaling, and best-effort +rollback remain in effect, including same-base replacement. Planning does not +require the switch, and `-WhatIf` never installs or replaces files. + +### Inspect the exact target manifest + +Consumers that must examine candidate metadata before approval can use the same +unmodified live plan: + +```powershell +$target = $update | Get-PSModuleUpdateTargetManifest +$target.Manifest.PrivateData +$update | Install-PSModuleUpdate -WhatIf +``` + +Inspection downloads only the exact planned version from its bound repository. +It safely imports manifest **data**, not the module, into a hashtable; it never +executes the target's RootModule or scripts, installs it, or interprets +consumer-specific metadata. The result exposes `Manifest` (including complete +`PrivateData`), `ModuleName`, `ModuleGuid`, exact semantic `Version`, and sanitized +`RepositoryUri`. + +The public plan is unchanged. PMU privately binds the inspected manifest bytes +to that live plan. Installation stages again and rejects differing manifest +content with `PMU.TargetManifestChanged` before changing installed files, +including same-version republishing. Editing the returned hashtable cannot +change the binding. Obtain a fresh plan to approve changed content; even +whitespace changes require reinspection. Uninspected plans retain their existing +installation behavior. Planning and install `-WhatIf` remain download-free. + +Pass `-Credential`, `-TrustRepository`, and `-AcceptLicense` independently when +needed for inspection, with the same meanings as installation. No credential or +consent is retained for a later call. Owned temporary registrations and the +inspection workspace are cleaned on success and failure. + Installation uses native PowerShell confirmation. For automation, `-Confirm:$false` suppresses that confirmation only; it does not accept a license, trust a repository, provide credentials, or grant filesystem access. @@ -119,6 +168,49 @@ does not read a particular environment variable or install credential providers. Plans are live in-process objects, not portable authorization records; obtain a new plan after restarting the shell or changing installation/repository state. +### Public installation identity and scope + +| Public field | Meaning | +|---|---| +| `Plan.ModuleName`, `Plan.ModuleGuid` | Validated module identity | +| `Plan.Scope` | Explicitly selected `CurrentUser` or `AllUsers` scope | +| `Plan.DestinationRoot` | Selected scope's Modules root | +| `Plan.InstalledManifestPath` | Selected existing manifest file | +| `Plan.InstalledVersion` | Complete existing version in that scope | +| `Plan.TargetVersion`, `Plan.TargetNumericVersion` | Exact semantic target and numeric directory version | +| `Plan.TargetInstalledPath` | Exact target **directory** | +| `Result.InstalledPath` | Verified target directory when `VerificationStatus` is `Verified`; otherwise the existing selected directory | +| `Result.ModuleName`, `Result.ModuleGuid`, `Result.Scope` | The same selected identity and scope | +| `Result.InstalledVersion`, `Result.TargetVersion` | Observed installed and approved target complete versions | + +After verified installation, the exact manifest file is +`Join-Path $result.InstalledPath "$($result.ModuleName).psd1"`. +There is no `Result.InstalledManifestPath` property. A later name-only module +search does not preserve this exact identity. + +`Plan.ObservedInstalledVersions` entries expose `Scope`, `Root`, `ManifestPath`, +`Guid`, `FullVersion`, `NumericVersion`, and `Prerelease` for discovered copies +in both supported scopes. These observations are returned only after successful +planning in a scope with an existing installation. PMU does not publicly infer +scope from a supplied module reference or silently choose the reference's scope: +`Policy.Scope` defaults to CurrentUser. Consumers preserving an existing scope +must classify the reference against the supported standard roots and explicitly +pass the correct scope. Unknown/nonstandard layouts must fail closed. + +Supported roots are `MyDocuments/PowerShell/Modules` and +`ProgramFiles/PowerShell/Modules` on Windows, and +`$HOME/.local/share/powershell/Modules` and +`/usr/local/share/powershell/Modules` on Linux/macOS, for CurrentUser and AllUsers +respectively. Windows MyDocuments is obtained through +`[Environment]::GetFolderPath('MyDocuments')`, not a guessed profile path. +Supported manifests use `///.psd1`. + +Missing per-call credentials and provider authentication failures use +`PMU.AuthenticationFailed`; there is no separate credential-required error ID. +Trust, license, and filesystem permission errors remain +`PMU.RepositoryTrustRequired`, `PMU.LicenseAcceptanceRequired`, and +`PMU.PermissionDenied`. + Repository selection is always caller-owned and source-bound. PMU never searches another feed just because it contains the same package name. PSGallery, public NuGet v3 repositories such as NuGet.org, and authenticated private diff --git a/RELEASE_NOTE.md b/RELEASE_NOTE.md index fd26a4f..93348f2 100644 --- a/RELEASE_NOTE.md +++ b/RELEASE_NOTE.md @@ -7,6 +7,15 @@ This file summarizes public cmdlet, CLI, configuration, and migration changes fo ### Added +- Use `Install-PSModuleUpdate -ReplaceUnmanagedInstallation` to explicitly + update a manually copied installation with no root `PSGetModuleInfo.xml`. + The default remains fail-closed. Unreadable or mismatching existing metadata + is never bypassed, and exact-target verification and recovery remain enabled. +- Inspect an approved exact target with `Get-PSModuleUpdateTargetManifest` + before deciding to install. Its `Manifest` hashtable includes full + PrivateData without loading or running the target. Installation rejects + manifest content changed after inspection, even under the same version; + obtain a fresh plan to approve different content. - Plan module updates with `Get-PSModuleUpdate`, preview them with `Install-PSModuleUpdate -WhatIf`, and explicitly approve installation. - Update independent installed modules without embedding PMU or requiring a PMU @@ -22,8 +31,10 @@ This file summarizes public cmdlet, CLI, configuration, and migration changes fo ### Changed -- Existing-module updates now use native `Update-Module` without Force or an - install fallback. Exact target/source, consent and restart requirements stay +- Managed-module updates use native `Update-Module` without Force or an + automatic install fallback. The unmanaged opt-in uses exact-version native + `Install-Module`, with Force only for a target-directory collision. + Exact target/source, consent and restart requirements stay in effect. Prerelease updates use native-compatible labels such as `preview03`; dotted labels such as `preview.3` are not supported by the native installer. Temporary repository setup also handles automatically registered defaults @@ -35,6 +46,9 @@ This file summarizes public cmdlet, CLI, configuration, and migration changes fo ### Fixed +- Update checks now report `PMU.PackageNotFound` when the selected repository + has no matching package. No update plan is returned, and PMU does not try + another feed or expose raw provider diagnostics. - PMU now declares its qualified PSResourceGet 1.2.0 runtime dependency. - Linux updates no longer falsely reject a live approving process. Legacy Linux repository receipts require diff --git a/docs/PSModuleUpdate/en-US/Get-PSModuleUpdate.md b/docs/PSModuleUpdate/en-US/Get-PSModuleUpdate.md index b7dc698..83803ea 100644 --- a/docs/PSModuleUpdate/en-US/Get-PSModuleUpdate.md +++ b/docs/PSModuleUpdate/en-US/Get-PSModuleUpdate.md @@ -4,7 +4,7 @@ external help file: PSModuleUpdate-Help.xml HelpUri: '' Locale: en-US Module Name: PSModuleUpdate -ms.date: 10.23.2026 +ms.date: 10.31.2026 PlatyPS schema version: 2024-05-01 title: Get-PSModuleUpdate --- @@ -211,6 +211,16 @@ Cannot be combined with `Repository`. PMU reuses a unique existing registration or creates a temporary owned registration; ambiguous consumer registrations are rejected. Credentials, query strings, and fragments must not be embedded in the URI. +One absolute repository endpoint. +Cannot be combined with `Repository`. +PMU reuses a unique existing registration or creates a temporary owned +registration; ambiguous consumer registrations are rejected. +Credentials, query strings, and fragments must not be embedded in the URI. +One absolute repository endpoint. +Cannot be combined with `Repository`. +PMU reuses a unique existing registration or creates a temporary owned +registration; ambiguous consumer registrations are rejected. +Credentials, query strings, and fragments must not be embedded in the URI. ```yaml Type: System.Uri @@ -246,12 +256,35 @@ A live schema-1, data-only plan with active and selected-scope installation identity, repository snapshot, exact target, policy, disposition, and prerequisites. It contains no credential and is not a durable authorization token. +`ModuleName` and `ModuleGuid` identify the target. `Scope` and `DestinationRoot` +identify the selected installation scope and its Modules root. +`InstalledManifestPath` is the selected existing manifest **file**; +`InstalledVersion` is its complete version. `TargetVersion` is the exact semantic +target, `TargetNumericVersion` is its numeric directory version, and +`TargetInstalledPath` is the exact target **directory**. + +`ObservedInstalledVersions` contains validated discovered copies from both +supported scopes, with `Scope`, `Root`, `ManifestPath`, `Guid`, `FullVersion`, +`NumericVersion`, and `Prerelease`. Planning must first succeed in an explicitly +selected scope with an existing installation. The CurrentUser default is not +automatic scope inference from the supplied reference. + ## NOTES Requires PowerShell 7.4 or later and the qualified PSResourceGet 1.2.0 baseline. Missing provider setup, unavailable packages, authentication failures, unsafe paths, and identity mismatches are terminating structured PMU errors, not UpToDate results. Credentials must be supplied independently to installation. +They must also be supplied independently to `Get-PSModuleUpdateTargetManifest` +when candidate metadata inspection is needed. Inspection does not alter this +plan or cause ordinary planning to stage/download packages. + +When no eligible package exists in the explicitly selected repository, +discovery terminates with the stable error ID `PMU.PackageNotFound` and returns +no update plan. This includes the provider's structured `PackageNotFound` +failure. PMU does not query another feed or substitute another version. +Other discovery, authentication and permission failures retain their distinct +PMU errors; raw provider diagnostics are withheld to protect credentials. PSResourceGet 1.2.0 Find/Save/Install expose repository names, not a direct URI parameter. PMU serializes its own registration changes with a per-user diff --git a/docs/PSModuleUpdate/en-US/Get-PSModuleUpdateTargetManifest.md b/docs/PSModuleUpdate/en-US/Get-PSModuleUpdateTargetManifest.md new file mode 100644 index 0000000..e165f7b --- /dev/null +++ b/docs/PSModuleUpdate/en-US/Get-PSModuleUpdateTargetManifest.md @@ -0,0 +1,187 @@ +--- +document type: cmdlet +external help file: PSModuleUpdate-Help.xml +HelpUri: '' +Locale: en-US +Module Name: PSModuleUpdate +ms.date: 10.31.2026 +PlatyPS schema version: 2024-05-01 +title: Get-PSModuleUpdateTargetManifest +--- + +# Get-PSModuleUpdateTargetManifest + +## SYNOPSIS + +Downloads and safely reads the exact target manifest of one live update plan. + +## SYNTAX + +### __AllParameterSets + +``` +Get-PSModuleUpdateTargetManifest [-Plan] [[-Credential] ] [-TrustRepository] + [-AcceptLicense] [] +``` + +## ALIASES + +None. + + +## DESCRIPTION + +Inspects only the bound repository and exact planned candidate in an owned temporary +workspace. +Does not install, import, or execute the target. +Binds the manifest internally +to the unmodified live plan; installation rejects a differing staged manifest. + +## EXAMPLES + +### EXAMPLE 1 + +```powershell +$target = $plan | Get-PSModuleUpdateTargetManifest -TrustRepository -AcceptLicense +$target.Manifest.PrivateData +``` + +Inspect the candidate metadata before independently approving installation with +`Install-PSModuleUpdate`. Credentials and consent must be supplied again to that +separate operation. + +## PARAMETERS + +### -AcceptLicense + +Explicit acceptance of declared or undisclosed package license requirements. + +```yaml +Type: System.Management.Automation.SwitchParameter +DefaultValue: False +SupportsWildcards: false +Aliases: [] +ParameterSets: +- Name: (All) + Position: Named + IsRequired: false + ValueFromPipeline: false + ValueFromPipelineByPropertyName: false + ValueFromRemainingArguments: false +DontShow: false +AcceptedValues: [] +HelpMessage: '' +``` + +### -Credential + +Optional per-call provider credential. +Never retained; supply it again to installation. + +```yaml +Type: System.Management.Automation.PSCredential +DefaultValue: '' +SupportsWildcards: false +Aliases: [] +ParameterSets: +- Name: (All) + Position: 1 + IsRequired: false + ValueFromPipeline: false + ValueFromPipelineByPropertyName: false + ValueFromRemainingArguments: false +DontShow: false +AcceptedValues: [] +HelpMessage: '' +``` + +### -Plan + +An unmodified live plan from Get-PSModuleUpdate in this same module instance. + +```yaml +Type: System.Object +DefaultValue: '' +SupportsWildcards: false +Aliases: [] +ParameterSets: +- Name: (All) + Position: 0 + IsRequired: true + ValueFromPipeline: true + ValueFromPipelineByPropertyName: false + ValueFromRemainingArguments: false +DontShow: false +AcceptedValues: [] +HelpMessage: '' +``` + +### -TrustRepository + +Explicit operation-scoped approval of an untrusted repository. + +```yaml +Type: System.Management.Automation.SwitchParameter +DefaultValue: False +SupportsWildcards: false +Aliases: [] +ParameterSets: +- Name: (All) + Position: Named + IsRequired: false + ValueFromPipeline: false + ValueFromPipelineByPropertyName: false + ValueFromRemainingArguments: false +DontShow: false +AcceptedValues: [] +HelpMessage: '' +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, +-InformationAction, -InformationVariable, -OutBuffer, -OutVariable, -PipelineVariable, +-ProgressAction, -Verbose, -WarningAction, and -WarningVariable. For more information, see +[about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### System.Object + +An unmodified live `PSModuleUpdate.UpdatePlan` from this same module instance. +Cloned, deserialized, edited, and other-instance plans are rejected. + +## OUTPUTS + +### PSModuleUpdate.TargetManifest + +A data-only object with `Manifest` (the safely imported manifest hashtable, +including GUID, ModuleVersion, and complete PrivateData), `ModuleName`, +`ModuleGuid`, `Version` (the exact semantic target identity, including prerelease), +and sanitized `RepositoryUri`. + +## NOTES + +Only the exact planned version and bound endpoint are queried. Inspection uses +the same native acquisition and package validation adapters as installation, +in an operation-owned temporary workspace under CurrentUser PMU data. It does +not import the target, execute its RootModule or scripts, mutate installed +files, or interpret consumer-specific PrivateData. + +The public plan remains unchanged. PMU privately binds the inspected manifest +bytes to the original live plan. Installation compares its newly staged +manifest before installed-file mutation and terminates with +`PMU.TargetManifestChanged` if the content differs, even if name, GUID and version +still match. Editing this result cannot change that binding. Reinspection of +changed content requires a fresh plan; changes to whitespace alone also require +fresh approval. Plans that have not been inspected retain their existing behavior. + +Repository trust and license acceptance have the same opt-in meanings as +installation. Inspection does not transfer consent or retain credentials. +Owned transport registrations and the inspection workspace are cleaned on +success and failure; unsafe cleanup fails closed. Planning and installation +`-WhatIf` remain acquisition-free. + +## RELATED LINKS + +- [about_Modules](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_modules) diff --git a/docs/PSModuleUpdate/en-US/Install-PSModuleUpdate.md b/docs/PSModuleUpdate/en-US/Install-PSModuleUpdate.md index 646ced3..735a891 100644 --- a/docs/PSModuleUpdate/en-US/Install-PSModuleUpdate.md +++ b/docs/PSModuleUpdate/en-US/Install-PSModuleUpdate.md @@ -4,7 +4,7 @@ external help file: PSModuleUpdate-Help.xml HelpUri: '' Locale: en-US Module Name: PSModuleUpdate -ms.date: 10.23.2026 +ms.date: 11.09.2026 PlatyPS schema version: 2024-05-01 title: Install-PSModuleUpdate --- @@ -21,7 +21,7 @@ Applies one live exact-version module update plan. ``` Install-PSModuleUpdate -Update [-Credential ] [-AcceptLicense] - [-TrustRepository] [-WhatIf] [-Confirm] [] + [-TrustRepository] [-ReplaceUnmanagedInstallation] [-WhatIf] [-Confirm] [] ``` ## ALIASES @@ -58,6 +58,15 @@ $plan | Install-PSModuleUpdate -AcceptLicense -TrustRepository Requests native confirmation before applying the exact approved target and scope. +### EXAMPLE 3 + +```powershell +$plan | Install-PSModuleUpdate -ReplaceUnmanagedInstallation +``` + +Explicitly replaces a manually copied installation without root PSGetModuleInfo.xml. +The exact planned target, repository and selected scope remain unchanged. + ## PARAMETERS ### -AcceptLicense @@ -125,6 +134,32 @@ AcceptedValues: [] HelpMessage: '' ``` +### -ReplaceUnmanagedInstallation + +Explicitly allows replacing the selected manually copied installation only when +its root PSGetModuleInfo.xml is absent. Defaults to off. Present-but-unreadable or +mismatching metadata still fails. Uses native Install-Module for the exact planned +target, with Force only when its target directory collides. Existing identity, +repository, scope, backup, journal, tree verification and rollback checks remain. +This consent is per call and independent of AcceptLicense and TrustRepository. + +```yaml +Type: System.Management.Automation.SwitchParameter +DefaultValue: False +SupportsWildcards: false +Aliases: [] +ParameterSets: +- Name: ByUpdatePlan + Position: Named + IsRequired: false + ValueFromPipeline: false + ValueFromPipelineByPropertyName: false + ValueFromRemainingArguments: false +DontShow: false +AcceptedValues: [] +HelpMessage: '' +``` + ### -TrustRepository Allows this operation against an untrusted repository without changing its registration. @@ -214,6 +249,25 @@ and WhatIf. Provider success alone never produces Installed. ## NOTES +An optional prior `Get-PSModuleUpdateTargetManifest` call privately binds the +inspected manifest to this same live plan. Staging compares the complete +manifest content before installed-file mutation and rejects a difference with +`PMU.TargetManifestChanged`, including same-version republishing. Obtain a fresh +plan and inspect again before approving different content. Editing the returned +manifest hashtable cannot change that binding. Without prior inspection, +installation retains its existing behavior; `-WhatIf` does not stage/download. + +After `VerificationStatus` is `Verified`, `InstalledPath` is the exact installed +target **directory**. `ModuleName`, `ModuleGuid`, `Scope`, `InstalledVersion`, +and `TargetVersion` identify its verified module, selected scope, observed +version and approved target. Construct the exact manifest path with +`Join-Path $result.InstalledPath "$($result.ModuleName).psd1"`. +There is no `InstalledManifestPath` property on installation results. + +Credentials must be supplied again for each operation. Missing required +credentials and provider authentication failures use `PMU.AuthenticationFailed`; +repository trust and license opt-ins remain separate prerequisites. + Planning and WhatIf never perform recovery writes. After native approval, an exclusive OS handle lock covers revalidation, staging, backup, replacement, verification, rollback, and journal completion. Lock acquisition is bounded. @@ -225,8 +279,15 @@ repointed or silently replaced by aliases. An initially unregistered URI uses a fresh operation-owned temporary registration after approval, with checked cleanup. `-WhatIf` never creates one. Existing registrations are never modified. -Same-numeric-version prerelease progression uses exact Save-PSResource staging -and internal Install-PSResource -Reinstall only for a validated collision. +Same-numeric-version prerelease progression uses exact native Save-Module staging. +Managed originals use Update-Module. ReplaceUnmanagedInstallation permits native +Install-Module only when the selected original lacks root PSGetModuleInfo.xml. +Without this opt-in, missing metadata still raises PMU.UnsupportedInstallation; +unreadable or mismatching existing metadata remains an error with the switch. +Planning needs no opt-in. WhatIf does not mutate files or acquire packages. +Native Force is used only for an unmanaged target-directory collision after GUID +validation and a verified backup. An already installed target still requires its +native metadata; the opt-in waives requirements only for the old installation. Backups are outside Modules. Journals use flushed temporary files and atomic file replacement; PMU does not claim atomic installation or guaranteed power-loss recovery. Interrupted state and journal paths are untrusted and diff --git a/docs/architecture/ARCHITECTURE.md b/docs/architecture/ARCHITECTURE.md index 918fd29..286f71c 100644 --- a/docs/architecture/ARCHITECTURE.md +++ b/docs/architecture/ARCHITECTURE.md @@ -59,9 +59,31 @@ repository: ## Product boundary +### Exact-target manifest inspection + +`Get-PSModuleUpdateTargetManifest` accepts only an unmodified live plan in the +same loaded PMU instance. It rechecks the exact repository/candidate and current +installation identity, then uses the existing native acquisition and staged +package validation adapters in a unique CurrentUser-owned inspection workspace. +Its isolated worker stages only: it does not enter the native mutation lease, +install the package, import the target, or execute target scripts. Credentials +travel over the existing stdin transport and are not retained in the live plan. +Owned repository registrations and workspace files are cleaned on success/failure. + +The output wraps the safely imported manifest hashtable and sanitized exact +identity fields. PMU does not interpret consumer-specific PrivateData. +The live-plan registry privately stores a SHA256 binding of the inspected +manifest bytes, separately from the unchanged public plan. That binding is +copied into the native installation worker's private record and checked during +staged identity validation before provider mutation. Different content is +rejected even when name, GUID and semantic version are unchanged; reinspection +of changed content requires a fresh plan. Uninspected plans and acquisition-free +planning/install WhatIf retain their existing contracts. + PMU owns: -- the `Get-PSModuleUpdate` and `Install-PSModuleUpdate` public cmdlets +- the `Get-PSModuleUpdate`, `Get-PSModuleUpdateTargetManifest`, and + `Install-PSModuleUpdate` public cmdlets - full-version identity, release selection, plan validation, and stale-plan detection - explicit CurrentUser and AllUsers scope handling diff --git a/scripts/build/ci/CiSkipPolicy.json b/scripts/build/ci/CiSkipPolicy.json index 5bcd024..d20d958 100644 --- a/scripts/build/ci/CiSkipPolicy.json +++ b/scripts/build/ci/CiSkipPolicy.json @@ -5,6 +5,12 @@ "operatingSystems": ["Windows", "Linux"], "reason": "The licensed offline provider fixture is currently qualified only on macOS; non-macOS qualification remains open." }, + { + "file": "tests/public/Get-PSModuleUpdateTargetManifest.Integration.Tests.ps1", + "name": "inspects an offline exact package, rejects changed MinimumGerberVersion, then installs unchanged content", + "operatingSystems": ["Windows", "Linux"], + "reason": "Exact-target inspection uses the same macOS-qualified offline native provider fixture; Windows/Linux native-fixture qualification remains open." + }, { "file": "tests/private/locking/Get-WindowsDirectoryDescriptor.Tests.ps1", "name": "reads current-user ACL metadata from a disposable directory", diff --git a/src/private/inspection/Assert-InspectedManifest.ps1 b/src/private/inspection/Assert-InspectedManifest.ps1 new file mode 100644 index 0000000..c6395a2 --- /dev/null +++ b/src/private/inspection/Assert-InspectedManifest.ps1 @@ -0,0 +1,10 @@ +function Assert-InspectedManifest { + param( + [object]$Record, + [string]$Hash + ) + $binding = $Record.PSObject.Properties['InspectedManifestHash'] + if ($binding -and $binding.Value -cne $Hash) { + Write-PMUError 'PMU.TargetManifestChanged' 'The exact target manifest differs from the inspected manifest.' 'Obtain a fresh plan and inspect it again before approving installation.' + } +} diff --git a/src/private/inspection/Assert-ManifestReadHash.ps1 b/src/private/inspection/Assert-ManifestReadHash.ps1 new file mode 100644 index 0000000..689bf38 --- /dev/null +++ b/src/private/inspection/Assert-ManifestReadHash.ps1 @@ -0,0 +1,10 @@ +function Assert-ManifestReadHash { + param( + [string]$Path, + [string]$Hash + ) + $current = (Get-FileHash -LiteralPath $Path -Algorithm SHA256 -ErrorAction Stop).Hash + if ($current -cne $Hash) { + Write-PMUError 'PMU.TargetManifestChanged' 'The target manifest changed while being inspected.' 'Obtain a fresh plan and inspect it again.' + } +} diff --git a/src/private/inspection/Assert-ManifestWorkerResult.ps1 b/src/private/inspection/Assert-ManifestWorkerResult.ps1 new file mode 100644 index 0000000..ec26376 --- /dev/null +++ b/src/private/inspection/Assert-ManifestWorkerResult.ps1 @@ -0,0 +1,11 @@ +function Assert-ManifestWorkerResult { + param( + [object]$Result, + [int]$ExitCode + ) + $complete = $ExitCode -eq 0 -and $Result.Phase -ceq 'RESULT' + if ($complete -and $Result.Success) { + return + } + Write-ManifestWorkerError $Result +} diff --git a/src/private/inspection/Clear-ManifestInspection.ps1 b/src/private/inspection/Clear-ManifestInspection.ps1 new file mode 100644 index 0000000..70ca86c --- /dev/null +++ b/src/private/inspection/Clear-ManifestInspection.ps1 @@ -0,0 +1,13 @@ +function Clear-ManifestInspection { + param([object]$Operation) + $Operation.Credential = $null + $expected = Join-Path $Operation.DataRoot "inspection-$($Operation.Journal.TransactionId)" + if ($Operation.WorkRoot -cne $expected) { + Write-PMUError 'PMU.RecoveryRequired' 'Refusing to remove an unexpected inspection workspace.' + } + $null = Assert-SafePath $expected + if (Test-Path -LiteralPath $expected) { + $null = @(Get-FileTreeInventory $expected) + Remove-Item -LiteralPath $expected -Recurse -Force -ErrorAction Stop + } +} diff --git a/src/private/inspection/ConvertTo-ManifestInspectionOperation.ps1 b/src/private/inspection/ConvertTo-ManifestInspectionOperation.ps1 new file mode 100644 index 0000000..4812e6e --- /dev/null +++ b/src/private/inspection/ConvertTo-ManifestInspectionOperation.ps1 @@ -0,0 +1,12 @@ +function ConvertTo-ManifestInspectionOperation { + param([object]$Operation) + $nonce = [guid]::NewGuid().ToString('N') + $Operation.DataRoot = Resolve-PMUDataRoot 'CurrentUser' + $root = Join-Path $Operation.DataRoot "inspection-$nonce" + $workspace = ConvertTo-InstallationWorkspace $Operation.Plan $Operation.DataRoot $root + $Operation | Add-Member -NotePropertyMembers $workspace -Force + $Operation.Journal = [pscustomobject]@{ + TransactionId = $nonce + } + $Operation +} diff --git a/src/private/inspection/ConvertTo-ManifestWorkerContext.ps1 b/src/private/inspection/ConvertTo-ManifestWorkerContext.ps1 new file mode 100644 index 0000000..a4b91a7 --- /dev/null +++ b/src/private/inspection/ConvertTo-ManifestWorkerContext.ps1 @@ -0,0 +1,15 @@ +function ConvertTo-ManifestWorkerContext { + param( + [object]$Operation, + [string]$ModulePath + ) + [pscustomobject]@{ + Operation = ConvertTo-NativeWorkerOperation $Operation ([pscustomobject]@{ + Source = [pscustomobject]@{ + Name = $Operation.RepositoryName + } + }) + ModulePath = $ModulePath + InspectManifest = $true + } +} diff --git a/src/private/inspection/ConvertTo-TargetManifest.ps1 b/src/private/inspection/ConvertTo-TargetManifest.ps1 new file mode 100644 index 0000000..2e86060 --- /dev/null +++ b/src/private/inspection/ConvertTo-TargetManifest.ps1 @@ -0,0 +1,14 @@ +function ConvertTo-TargetManifest { + param( + [object]$Plan, + [hashtable]$Manifest + ) + [pscustomobject]@{ + PSTypeName = 'PSModuleUpdate.TargetManifest' + Manifest = $Manifest + ModuleName = $Plan.ModuleName + ModuleGuid = $Plan.ModuleGuid + Version = $Plan.TargetVersion + RepositoryUri = $Plan.RepositoryUri + } +} diff --git a/src/private/inspection/Get-BoundTargetManifest.ps1 b/src/private/inspection/Get-BoundTargetManifest.ps1 new file mode 100644 index 0000000..31ddc80 --- /dev/null +++ b/src/private/inspection/Get-BoundTargetManifest.ps1 @@ -0,0 +1,7 @@ +function Get-BoundTargetManifest { + param([object]$Operation) + Assert-ExactTarget $Operation + Assert-InstallationConsent $Operation + Invoke-ManifestAcquisition $Operation + Get-InspectedTargetManifest $Operation +} diff --git a/src/private/inspection/Get-InspectedTargetManifest.ps1 b/src/private/inspection/Get-InspectedTargetManifest.ps1 new file mode 100644 index 0000000..c775017 --- /dev/null +++ b/src/private/inspection/Get-InspectedTargetManifest.ps1 @@ -0,0 +1,13 @@ +function Get-InspectedTargetManifest { + param([object]$Operation) + Assert-PlanEnvironment $Operation + $null = Test-InstalledPlanState $Operation + $path = Join-Path $Operation.StagedPath "$($Operation.Plan.ModuleName).psd1" + $hash = (Get-FileHash -LiteralPath $path -Algorithm SHA256 -ErrorAction Stop).Hash + Assert-PackageIdentity (Get-ManifestIdentity $path) $Operation.Plan + $manifest = Read-ManifestDefinition $path + Assert-ManifestReadHash $path $hash + Assert-InspectedManifest $Operation.Record $hash + $Operation.Record | Add-Member InspectedManifestHash $hash -Force + ConvertTo-TargetManifest $Operation.Plan $manifest +} diff --git a/src/private/inspection/Initialize-ManifestInspection.ps1 b/src/private/inspection/Initialize-ManifestInspection.ps1 new file mode 100644 index 0000000..a47e7e8 --- /dev/null +++ b/src/private/inspection/Initialize-ManifestInspection.ps1 @@ -0,0 +1,14 @@ +function Initialize-ManifestInspection { + param( + [object]$Plan, + [pscredential]$Credential, + [bool]$AcceptLicense, + [bool]$TrustRepository + ) + $operation = Initialize-InstallationRequest $Plan $Credential @{ + AcceptLicense = $AcceptLicense + TrustRepository = $TrustRepository + } + Assert-InstallationConsent $operation + ConvertTo-ManifestInspectionOperation $operation +} diff --git a/src/private/inspection/Invoke-ManifestAcquisition.ps1 b/src/private/inspection/Invoke-ManifestAcquisition.ps1 new file mode 100644 index 0000000..87345ca --- /dev/null +++ b/src/private/inspection/Invoke-ManifestAcquisition.ps1 @@ -0,0 +1,9 @@ +function Invoke-ManifestAcquisition { + param([object]$Operation) + $module = @(Get-Module -Name PSModuleUpdate) + if ($module.Count -ne 1) { + Write-PMUError 'PMU.UnsupportedProviderBehavior' 'Manifest acquisition requires the current built PMU module instance.' + } + $context = ConvertTo-ManifestWorkerContext $Operation $module[0].Path + Invoke-ManifestWorkerProcess $Operation $context +} diff --git a/src/private/inspection/Invoke-ManifestWorkerProcess.ps1 b/src/private/inspection/Invoke-ManifestWorkerProcess.ps1 new file mode 100644 index 0000000..d79f45e --- /dev/null +++ b/src/private/inspection/Invoke-ManifestWorkerProcess.ps1 @@ -0,0 +1,14 @@ +function Invoke-ManifestWorkerProcess { + param( + [object]$Operation, + [object]$Context + ) + $worker = Invoke-NativeWorkerStart $Operation $Context + try { + $result = Read-NativeWorkerMessage $worker.Process.StandardOutput + } finally { + Wait-NativeWorkerStop $worker + $worker.Process.Dispose() + } + Assert-ManifestWorkerResult $result $worker.ExitCode +} diff --git a/src/private/inspection/Invoke-RepositoryManifestInspection.ps1 b/src/private/inspection/Invoke-RepositoryManifestInspection.ps1 new file mode 100644 index 0000000..8fd1514 --- /dev/null +++ b/src/private/inspection/Invoke-RepositoryManifestInspection.ps1 @@ -0,0 +1,14 @@ +function Invoke-RepositoryManifestInspection { + param([object]$Operation) + $lease = Open-RepositoryTransport (ConvertTo-PlanRepositorySource $Operation.Plan) + $Operation.RepositoryName = $lease.Name + $failure = $null + try { + Get-BoundTargetManifest $Operation + } catch { + $failure = $_ + Write-ManifestInspectionError $failure + } finally { + Close-RepositoryTransport $lease $failure + } +} diff --git a/src/private/inspection/Invoke-TargetManifestInspection.ps1 b/src/private/inspection/Invoke-TargetManifestInspection.ps1 new file mode 100644 index 0000000..bf0485d --- /dev/null +++ b/src/private/inspection/Invoke-TargetManifestInspection.ps1 @@ -0,0 +1,12 @@ +function Invoke-TargetManifestInspection { + param([object]$Operation) + Initialize-ControlledDirectory $Operation.WorkRoot + Write-InstallationPhase $Operation.Plan 'Checking' + try { + $result = Invoke-RepositoryManifestInspection $Operation + } finally { + Clear-ManifestInspection $Operation + Write-InstallationPhase $Operation.Plan 'Completed' + } + $result +} diff --git a/src/private/inspection/Write-ManifestInspectionError.ps1 b/src/private/inspection/Write-ManifestInspectionError.ps1 new file mode 100644 index 0000000..f05e4d0 --- /dev/null +++ b/src/private/inspection/Write-ManifestInspectionError.ps1 @@ -0,0 +1,7 @@ +function Write-ManifestInspectionError { + param([Management.Automation.ErrorRecord]$Failure) + if ($Failure.FullyQualifiedErrorId -match '^PMU\.[A-Za-z]+$') { + throw $Failure + } + Write-ProviderError $Failure 'PMU.InstallationFailed' +} diff --git a/src/private/inspection/Write-ManifestWorkerError.ps1 b/src/private/inspection/Write-ManifestWorkerError.ps1 new file mode 100644 index 0000000..f3f86e0 --- /dev/null +++ b/src/private/inspection/Write-ManifestWorkerError.ps1 @@ -0,0 +1,8 @@ +function Write-ManifestWorkerError { + param([object]$Result) + $id = 'PMU.InstallationFailed' + if ($Result.ErrorId -match '^PMU\.[A-Za-z]+$') { + $id = $Result.ErrorId + } + Write-PMUError $id 'The target manifest could not be inspected. Provider diagnostics were withheld to protect credentials.' 'Check the source and prerequisites, then obtain a fresh plan.' +} diff --git a/src/private/installation/Assert-NativeInstallationSnapshot.ps1 b/src/private/installation/Assert-NativeInstallationSnapshot.ps1 index 91999d0..1dad1a7 100644 --- a/src/private/installation/Assert-NativeInstallationSnapshot.ps1 +++ b/src/private/installation/Assert-NativeInstallationSnapshot.ps1 @@ -9,6 +9,6 @@ function Assert-NativeInstallationSnapshot { } Assert-PackageIdentity (Get-ManifestIdentity (Join-Path $Context.Snapshot.Path "$($operation.Plan.ModuleName).psd1")) $expected Assert-FileTreeEqual @($Context.Snapshot.Tree) @(Get-FileTreeInventory $Context.Snapshot.Path) 'PMU.InstalledStateChanged' - $source = Get-NativeInstalledSource $operation $Context.Snapshot.Path - Assert-MatchingProperty $source $Context.Snapshot.Source @('Name', 'Uri') 'PMU.InstalledStateChanged' + $source = Get-NativeSelectedSource $operation $Context.Snapshot.Path $Context.Snapshot.Source.Unmanaged + Assert-MatchingProperty $source $Context.Snapshot.Source @('Name', 'Uri', 'Unmanaged') 'PMU.InstalledStateChanged' } diff --git a/src/private/installation/Assert-NativeSelectedInstallation.ps1 b/src/private/installation/Assert-NativeSelectedInstallation.ps1 index efb33ce..4b06890 100644 --- a/src/private/installation/Assert-NativeSelectedInstallation.ps1 +++ b/src/private/installation/Assert-NativeSelectedInstallation.ps1 @@ -6,7 +6,7 @@ function Assert-NativeSelectedInstallation { Write-PMUError 'PMU.InstalledStateChanged' 'The selected installation changed during handoff.' } Assert-NativeInstallationSnapshot $Context - if ($Context.AlreadyInstalled) { + if ($Context.AlreadyInstalled -or (Test-UnmanagedInstallation $operation $Context.Snapshot.Path)) { return } $parameters = Get-NativeUpdateParameter $operation diff --git a/src/private/installation/ConvertTo-NativeWorkerOperation.ps1 b/src/private/installation/ConvertTo-NativeWorkerOperation.ps1 index e02f156..354672c 100644 --- a/src/private/installation/ConvertTo-NativeWorkerOperation.ps1 +++ b/src/private/installation/ConvertTo-NativeWorkerOperation.ps1 @@ -7,11 +7,7 @@ function ConvertTo-NativeWorkerOperation { $fields = 'Plan Consent Credential DataRoot WorkRoot LockPath JournalPath StageRoot BackupPath StagedPath Reinstall Journal RecoveryStatus RequiresLicenseAcceptance'.Split(' ') $copy = $Operation | Select-Object -Property $fields $copy | Add-Member RepositoryName $Snapshot.Source.Name - $copy | Add-Member Record ([pscustomobject]@{ InstalledTree = @($Operation.Record.InstalledTree) }) - $copy | Add-Member NativeContext ([pscustomobject]@{ - Root = Get-NativeProviderRoot $Operation - Paths = $null - CurrentUserRoot = Resolve-ModuleInstallationRoot 'CurrentUser' - }) + $copy | Add-Member Record (ConvertTo-NativePlanRecord $Operation.Record) + $copy | Add-Member NativeContext (ConvertTo-NativeProviderContext $Operation) $copy } diff --git a/src/private/installation/Get-NativeSelectedSnapshot.ps1 b/src/private/installation/Get-NativeSelectedSnapshot.ps1 index df3d669..f1f9455 100644 --- a/src/private/installation/Get-NativeSelectedSnapshot.ps1 +++ b/src/private/installation/Get-NativeSelectedSnapshot.ps1 @@ -4,11 +4,8 @@ function Get-NativeSelectedSnapshot { [bool]$AlreadyInstalled ) - $path = Split-Path -Parent $Operation.Plan.InstalledManifestPath - if ($AlreadyInstalled) { - $path = $Operation.Plan.TargetInstalledPath - } - $source = Get-NativeInstalledSource $Operation $path + $path = Get-NativeSnapshotPath $Operation $AlreadyInstalled + $source = Get-NativeSelectedSource $Operation $path (-not $AlreadyInstalled) [pscustomobject]@{ Path = $path Source = $source diff --git a/src/private/installation/Get-NativeSnapshotPath.ps1 b/src/private/installation/Get-NativeSnapshotPath.ps1 new file mode 100644 index 0000000..73a10b3 --- /dev/null +++ b/src/private/installation/Get-NativeSnapshotPath.ps1 @@ -0,0 +1,7 @@ +function Get-NativeSnapshotPath { + param([object]$Operation, [bool]$AlreadyInstalled) + if ($AlreadyInstalled) { + return $Operation.Plan.TargetInstalledPath + } + Split-Path -Parent $Operation.Plan.InstalledManifestPath +} diff --git a/src/private/installation/Invoke-NativeWorker.ps1 b/src/private/installation/Invoke-NativeWorker.ps1 index 93aeaeb..6386d3b 100644 --- a/src/private/installation/Invoke-NativeWorker.ps1 +++ b/src/private/installation/Invoke-NativeWorker.ps1 @@ -2,9 +2,7 @@ function Invoke-NativeWorker { param([object]$Context) try { Initialize-NativeProvider $Context.Operation - Write-NativeWorkerMessage ([pscustomobject]@{ Phase = 'READY' }) - Assert-NativeWorkerGo ([Console]::In) - Invoke-NativeWorkerLease $Context + Invoke-NativeWorkerAction $Context } catch { Write-NativeWorkerMessage (ConvertTo-NativeWorkerResult $null $_) } diff --git a/src/private/installation/Invoke-NativeWorkerAction.ps1 b/src/private/installation/Invoke-NativeWorkerAction.ps1 new file mode 100644 index 0000000..90430f2 --- /dev/null +++ b/src/private/installation/Invoke-NativeWorkerAction.ps1 @@ -0,0 +1,13 @@ +function Invoke-NativeWorkerAction { + param([object]$Context) + if ($Context.PSObject.Properties['InspectManifest']) { + $null = @(Initialize-StagedPackage $Context.Operation) + Write-NativeWorkerMessage (ConvertTo-NativeWorkerResult $null $null) + return + } + Write-NativeWorkerMessage ([pscustomobject]@{ + Phase = 'READY' + }) + Assert-NativeWorkerGo ([Console]::In) + Invoke-NativeWorkerLease $Context +} diff --git a/src/private/provider/ConvertTo-NativePlanRecord.ps1 b/src/private/provider/ConvertTo-NativePlanRecord.ps1 new file mode 100644 index 0000000..283c34a --- /dev/null +++ b/src/private/provider/ConvertTo-NativePlanRecord.ps1 @@ -0,0 +1,10 @@ +function ConvertTo-NativePlanRecord { + param([object]$Record) + $copy = [pscustomobject]@{ + InstalledTree = @($Record.InstalledTree) + } + if ($Record.PSObject.Properties['InspectedManifestHash']) { + $copy | Add-Member InspectedManifestHash $Record.InspectedManifestHash + } + $copy +} diff --git a/src/private/provider/ConvertTo-NativeProviderContext.ps1 b/src/private/provider/ConvertTo-NativeProviderContext.ps1 new file mode 100644 index 0000000..6db9cd3 --- /dev/null +++ b/src/private/provider/ConvertTo-NativeProviderContext.ps1 @@ -0,0 +1,8 @@ +function ConvertTo-NativeProviderContext { + param([object]$Operation) + [pscustomobject]@{ + Root = Get-NativeProviderRoot $Operation + Paths = $null + CurrentUserRoot = Resolve-ModuleInstallationRoot 'CurrentUser' + } +} diff --git a/src/private/provider/Find-ProviderResource.ps1 b/src/private/provider/Find-ProviderResource.ps1 index b451bf4..ff43d7a 100644 --- a/src/private/provider/Find-ProviderResource.ps1 +++ b/src/private/provider/Find-ProviderResource.ps1 @@ -4,17 +4,13 @@ function Find-ProviderResource { [pscredential]$Credential ) - $parameters = Get-ProviderInvocationParameter - $parameters.Name = $Request.Name - $parameters.Repository = $Request.Repository - $parameters.Prerelease = $Request.Prerelease - $parameters.Version = $Request.Version ? $Request.Version : '*' - if ($Credential) { - $parameters.Credential = $Credential - } + $parameters = Get-ProviderDiscoveryParameter $Request $Credential try { Microsoft.PowerShell.PSResourceGet\Find-PSResource @parameters } catch { + if (($_.FullyQualifiedErrorId -split ',', 2)[0] -ceq 'PackageNotFound') { + Write-PMUError 'PMU.PackageNotFound' 'The requested package was not found in the selected repository.' + } Write-ProviderError $_ 'PMU.DiscoveryFailed' } } diff --git a/src/private/provider/Get-NativeInstallParameter.ps1 b/src/private/provider/Get-NativeInstallParameter.ps1 new file mode 100644 index 0000000..bb6da56 --- /dev/null +++ b/src/private/provider/Get-NativeInstallParameter.ps1 @@ -0,0 +1,10 @@ +function Get-NativeInstallParameter { + param([object]$Operation) + $parameters = Get-ProviderMutationParameter $Operation + $parameters.Repository = Get-OperationRepositoryName $Operation + $parameters.Scope = $Operation.Plan.Scope + if (Test-Path -LiteralPath $Operation.Plan.TargetInstalledPath) { + $parameters.Force = $true + } + $parameters +} diff --git a/src/private/provider/Get-NativeSelectedSource.ps1 b/src/private/provider/Get-NativeSelectedSource.ps1 new file mode 100644 index 0000000..3992a93 --- /dev/null +++ b/src/private/provider/Get-NativeSelectedSource.ps1 @@ -0,0 +1,12 @@ +function Get-NativeSelectedSource { + param([object]$Operation, [string]$SelectedPath, [bool]$AllowUnmanaged) + if ($AllowUnmanaged -and (Test-UnmanagedInstallation $Operation $SelectedPath)) { + return [pscustomobject]@{ + Name = Get-OperationRepositoryName $Operation + Uri = $Operation.Plan.RepositoryUri + Unmanaged = $true + } + } + $source = Get-NativeInstalledSource $Operation $SelectedPath + $source | Select-Object Name, Uri, @{ Name = 'Unmanaged'; Expression = { $false } } +} diff --git a/src/private/provider/Get-ProviderDiscoveryParameter.ps1 b/src/private/provider/Get-ProviderDiscoveryParameter.ps1 new file mode 100644 index 0000000..f8e7050 --- /dev/null +++ b/src/private/provider/Get-ProviderDiscoveryParameter.ps1 @@ -0,0 +1,16 @@ +function Get-ProviderDiscoveryParameter { + param( + [hashtable]$Request, + [pscredential]$Credential + ) + + $parameters = Get-ProviderInvocationParameter + $parameters.Name = $Request.Name + $parameters.Repository = $Request.Repository + $parameters.Prerelease = $Request.Prerelease + $parameters.Version = $Request.Version ? $Request.Version : '*' + if ($Credential) { + $parameters.Credential = $Credential + } + return $parameters +} diff --git a/src/private/provider/Install-ProviderResource.ps1 b/src/private/provider/Install-ProviderResource.ps1 index 4895c75..5887b66 100644 --- a/src/private/provider/Install-ProviderResource.ps1 +++ b/src/private/provider/Install-ProviderResource.ps1 @@ -1,9 +1,14 @@ function Install-ProviderResource { param([object]$Operation) Assert-NativeProviderContext $Operation - $parameters = Get-NativeUpdateParameter $Operation try { - $null = PowerShellGet\Update-Module @parameters + if (Test-UnmanagedInstallation $Operation (Split-Path -Parent $Operation.Plan.InstalledManifestPath)) { + $parameters = Get-NativeInstallParameter $Operation + $null = PowerShellGet\Install-Module @parameters + } else { + $parameters = Get-NativeUpdateParameter $Operation + $null = PowerShellGet\Update-Module @parameters + } } catch { Write-ProviderError $_ 'PMU.InstallationFailed' } diff --git a/src/private/provider/Test-UnmanagedInstallation.ps1 b/src/private/provider/Test-UnmanagedInstallation.ps1 new file mode 100644 index 0000000..d8d99a2 --- /dev/null +++ b/src/private/provider/Test-UnmanagedInstallation.ps1 @@ -0,0 +1,10 @@ +function Test-UnmanagedInstallation { + param([object]$Operation, [string]$SelectedPath) + if (-not $Operation.Consent['ReplaceUnmanagedInstallation']) { + return $false + } + if ($SelectedPath -cne (Split-Path -Parent $Operation.Plan.InstalledManifestPath)) { + return $false + } + -not (Test-Path -LiteralPath (Join-Path $SelectedPath 'PSGetModuleInfo.xml')) +} diff --git a/src/private/staging/Get-ValidatedStagedTree.ps1 b/src/private/staging/Get-ValidatedStagedTree.ps1 new file mode 100644 index 0000000..afd1dcd --- /dev/null +++ b/src/private/staging/Get-ValidatedStagedTree.ps1 @@ -0,0 +1,12 @@ +function Get-ValidatedStagedTree { + param([object]$Operation) + $manifest = Join-Path $Operation.StagedPath "$($Operation.Plan.ModuleName).psd1" + Assert-PackageIdentity (Get-ManifestIdentity $manifest) $Operation.Plan + Assert-InspectedManifest $Operation.Record (Get-FileHash -LiteralPath $manifest -Algorithm SHA256 -ErrorAction Stop).Hash + $tree = @(Get-FileTreeInventory $Operation.StagedPath) + if ($tree.Count -lt 2) { + Write-PMUError 'PMU.VerificationFailed' 'The extracted module tree is incomplete.' + } + Assert-PackageSource $Operation.StagedPath $Operation.Plan + $tree +} diff --git a/src/private/staging/Initialize-StagedPackage.ps1 b/src/private/staging/Initialize-StagedPackage.ps1 index 0c6f276..f319052 100644 --- a/src/private/staging/Initialize-StagedPackage.ps1 +++ b/src/private/staging/Initialize-StagedPackage.ps1 @@ -5,12 +5,5 @@ function Initialize-StagedPackage { Initialize-ControlledDirectory $Operation.StageRoot Assert-NativeRepositoryBinding $Operation Save-ProviderResource $Operation - $manifest = Join-Path $Operation.StagedPath "$($Operation.Plan.ModuleName).psd1" - Assert-PackageIdentity (Get-ManifestIdentity $manifest) $Operation.Plan - $tree = @(Get-FileTreeInventory $Operation.StagedPath) - if ($tree.Count -lt 2) { - Write-PMUError 'PMU.VerificationFailed' 'The extracted module tree is incomplete.' - } - Assert-PackageSource $Operation.StagedPath $Operation.Plan - $tree + Get-ValidatedStagedTree $Operation } diff --git a/src/public/Get-PSModuleUpdateTargetManifest.ps1 b/src/public/Get-PSModuleUpdateTargetManifest.ps1 new file mode 100644 index 0000000..86f7b76 --- /dev/null +++ b/src/public/Get-PSModuleUpdateTargetManifest.ps1 @@ -0,0 +1,35 @@ +function Get-PSModuleUpdateTargetManifest { + <# + .EXTERNALHELP PSModuleUpdate-Help.xml + .SYNOPSIS + Downloads and safely reads the exact target manifest of one live update plan. + .DESCRIPTION + Inspects only the bound repository and exact planned candidate in an owned temporary + workspace. Does not install, import, or execute the target. Binds the manifest internally + to the unmodified live plan; installation rejects a differing staged manifest. + .PARAMETER Plan + An unmodified live plan from Get-PSModuleUpdate in this same module instance. + .PARAMETER Credential + Optional per-call provider credential. Never retained; supply it again to installation. + .PARAMETER TrustRepository + Explicit operation-scoped approval of an untrusted repository. + .PARAMETER AcceptLicense + Explicit acceptance of declared or undisclosed package license requirements. + .EXAMPLE + $target = $plan | Get-PSModuleUpdateTargetManifest -TrustRepository -AcceptLicense + Inspect $target.Manifest.PrivateData before independently approving installation. + .OUTPUTS + PSModuleUpdate.TargetManifest + #> + [CmdletBinding()] + param( + [Parameter(Mandatory, ValueFromPipeline)][ValidateNotNull()][object]$Plan, + [pscredential]$Credential, + [switch]$TrustRepository, + [switch]$AcceptLicense + ) + process { + $operation = Initialize-ManifestInspection $Plan $Credential $AcceptLicense.IsPresent $TrustRepository.IsPresent + Invoke-TargetManifestInspection $operation + } +} diff --git a/src/public/Install-PSModuleUpdate.ps1 b/src/public/Install-PSModuleUpdate.ps1 index a0eb281..988758d 100644 --- a/src/public/Install-PSModuleUpdate.ps1 +++ b/src/public/Install-PSModuleUpdate.ps1 @@ -1,3 +1,11 @@ +<# Intentional CodeScene exception (5 parameters, limit is 4). Each parameter is an independent, +explicit opt-in on the public API: Credential, AcceptLicense, TrustRepository and +ReplaceUnmanagedInstallation. Keeping them separate makes every risky consent visible and +auditable at the call site and avoids a breaking change for existing callers. Bundling them +into an options object would hide those consents and move complexity elsewhere without +reducing it. Reconsider if further parameters are added. +@CodeScene(disable:"Excess Number of Function Arguments") +#> function Install-PSModuleUpdate { <# .EXTERNALHELP PSModuleUpdate-Help.xml @@ -16,6 +24,10 @@ function Install-PSModuleUpdate { Explicitly accepts provider package license requirements for this operation. .PARAMETER TrustRepository Allows this operation against an untrusted repository without changing its registration. + .PARAMETER ReplaceUnmanagedInstallation + Explicitly allows replacing a manually copied installation only when its root + PSGetModuleInfo.xml is absent. Installs the exact planned target through the provider; + unreadable or mismatching metadata still fails. Backup and rollback safeguards remain. .EXAMPLE $plan | Install-PSModuleUpdate -WhatIf Revalidates read-only without locking, staging, installing, or repairing recovery state. @@ -30,17 +42,20 @@ function Install-PSModuleUpdate { [Parameter(Mandatory, ValueFromPipeline, ParameterSetName = 'ByUpdatePlan')][ValidateNotNull()][object]$Update, [Parameter(ParameterSetName = 'ByUpdatePlan')][pscredential]$Credential, [Parameter(ParameterSetName = 'ByUpdatePlan')][switch]$AcceptLicense, - [Parameter(ParameterSetName = 'ByUpdatePlan')][switch]$TrustRepository + [Parameter(ParameterSetName = 'ByUpdatePlan')][switch]$TrustRepository, + [Parameter(ParameterSetName = 'ByUpdatePlan')][switch]$ReplaceUnmanagedInstallation ) process { $operation = Initialize-InstallationRequest $Update $Credential @{ - AcceptLicense = [bool]$AcceptLicense - TrustRepository = [bool]$TrustRepository + AcceptLicense = [bool]$AcceptLicense + TrustRepository = [bool]$TrustRepository + ReplaceUnmanagedInstallation = [bool]$ReplaceUnmanagedInstallation } $target = "$($Update.ModuleName) $($Update.TargetVersion) from $($Update.RepositoryName ?? $Update.RepositoryUri) into $($Update.Scope)" if ($PSCmdlet.ShouldProcess($target, 'Install exact module update')) { Invoke-UpdateInstallation $operation - } else { + } + else { ConvertTo-DeclinedUpdateResult $Update } } diff --git a/tests/ModuleArchitecture.Tests.ps1 b/tests/ModuleArchitecture.Tests.ps1 index 5624027..a063290 100644 --- a/tests/ModuleArchitecture.Tests.ps1 +++ b/tests/ModuleArchitecture.Tests.ps1 @@ -5,7 +5,7 @@ Describe 'PMU architecture' -Tag 'PMU' { } It 'has exactly the approved public command files' { @(Get-ChildItem "$root/src/public" -Filter '*.ps1').BaseName | - Sort-Object | Should -Be @('Get-PSModuleUpdate', 'Install-PSModuleUpdate') + Sort-Object | Should -Be @('Get-PSModuleUpdate', 'Get-PSModuleUpdateTargetManifest', 'Install-PSModuleUpdate') } It 'uses one matching top-level function per source file and no nested functions' { $files.Count | Should -BeGreaterThan 0 @@ -22,12 +22,12 @@ Describe 'PMU architecture' -Tag 'PMU' { It 'does not bootstrap or hot reload and confines registration writes to owned transport adapters' { foreach ($file in $files) { $text = Get-Content $file.FullName -Raw - $text | Should -Not -Match '(?i)\b(Set-PSResourceRepository|Remove-Module|Install-Module)\b' - if ($text -match '\bUpdate-Module\b') { + $text | Should -Not -Match '(?i)\b(Set-PSResourceRepository|Remove-Module)\b' + if ($text -match '\b(Update-Module|Install-Module)\b') { $file.BaseName | Should -Be 'Install-ProviderResource' } - if ($file.Directory.Name -eq 'provider') { - $text | Should -Not -Match '(?i)\bForce\b' + if ($file.Directory.Name -eq 'provider' -and $text -match '(?i)\bForce\b') { + $file.BaseName | Should -Be 'Get-NativeInstallParameter' } if ($text -match '\bRegister-PSResourceRepository\b') { $file.BaseName | Should -Be 'Register-OwnedRepository' @@ -38,9 +38,11 @@ Describe 'PMU architecture' -Tag 'PMU' { } } } - It 'applies updates only through the native Update-Module adapter' -Tag 'PMUNativeAdapter' { + It 'applies updates only through the native adapter with an explicit unmanaged gate' -Tag 'PMUNativeAdapter' { $adapter = Get-Content "$root/src/private/provider/Install-ProviderResource.ps1" -Raw $adapter | Should -Match 'PowerShellGet\\Update-Module' + $adapter | Should -Match 'PowerShellGet\\Install-Module' + $adapter | Should -Match 'Test-UnmanagedInstallation' $adapter | Should -Not -Match '\bInstall-PSResource\b' } It 'has a source-mirrored test for every production helper and public command' { diff --git a/tests/TestHelpers/Assert-PMUManifestInspection.ps1 b/tests/TestHelpers/Assert-PMUManifestInspection.ps1 new file mode 100644 index 0000000..c5041bb --- /dev/null +++ b/tests/TestHelpers/Assert-PMUManifestInspection.ps1 @@ -0,0 +1,49 @@ +function Assert-PMUManifestInspection { + param( + [object]$Plan, + [object]$Fixture + ) + $snapshot = ConvertTo-Json $Plan -Depth 12 -Compress + $target = Get-PSModuleUpdateTargetManifest -Plan $Plan -TrustRepository -AcceptLicense + Assert-PMUManifestCandidate $target $Plan $Fixture $snapshot + $result = Install-PSModuleUpdate -Update $Plan -TrustRepository -AcceptLicense -Confirm:$false + Assert-PMUManifestInstallation $result $target.Version + Assert-PMUManifestRepublish $Fixture + Write-PMUManifestFixtureResult $target.Version $result.Outcome +} + +function Write-PMUManifestFixtureResult { + param( + [string]$Version, + [string]$Outcome + ) + [pscustomobject]@{ + Version = $Version + Outcome = $Outcome + } | ConvertTo-Json -Compress +} + +function Assert-PMUManifestCandidate { + param( + [object]$Target, + [object]$Plan, + [object]$Fixture, + [string]$Snapshot + ) + if ($Target.Version -cne '2.0.0-preview2' -or $Target.Manifest.PrivateData.Gerber.MinimumGerberVersion -cne '7.0.0') { + throw 'The public inspection substituted a different manifest.' + } + if ($snapshot -cne (ConvertTo-Json $Plan -Depth 12 -Compress) -or (Get-Module -Name $Fixture.Name)) { + throw 'Inspection modified the plan or loaded the target.' + } +} + +function Assert-PMUManifestInstallation { + param( + [object]$Result, + [string]$Version + ) + if ($Result.VerificationStatus -cne 'Verified' -or $Result.InstalledVersion -cne $Version) { + throw 'Unchanged inspected native installation did not verify.' + } +} diff --git a/tests/TestHelpers/Assert-PMUManifestRepublish.ps1 b/tests/TestHelpers/Assert-PMUManifestRepublish.ps1 new file mode 100644 index 0000000..09012dc --- /dev/null +++ b/tests/TestHelpers/Assert-PMUManifestRepublish.ps1 @@ -0,0 +1,40 @@ +function Assert-PMUManifestRepublish { + param([object]$Fixture) + $plan = Get-PMURepublishPlan $Fixture + $null = Get-PSModuleUpdateTargetManifest -Plan $plan -TrustRepository -AcceptLicense + Initialize-PMUManifestFixture $Fixture '8.0.0' $plan.TargetVersion + $failure = try { + $null = Install-PSModuleUpdate -Update $plan -TrustRepository -AcceptLicense -Confirm:$false + } catch { + $_ + } + Assert-PMUManifestRepublishFailure $plan $failure +} + +function Get-PMURepublishPlan { + param([object]$Fixture) + $version = '2.0.0-preview3' + Initialize-PMULocalPackage $Fixture $version + Initialize-PMUManifestFixture $Fixture '7.0.0' $version + $path = Join-Path $Fixture.Module.ModuleBase "$($Fixture.Name).psd1" + $module = Get-Module -ListAvailable $path + $uri = [uri]::new([IO.Path]::GetFullPath($Fixture.Feed), [UriKind]::Absolute) + Get-PSModuleUpdate -Module $module -RepositoryUri $uri -Policy @{ + Channel = 'IncludePrerelease' + } +} + +function Assert-PMUManifestRepublishFailure { + param( + [object]$Plan, + [object]$Failure + ) + if (-not $Failure -or $Failure.FullyQualifiedErrorId -cne 'PMU.TargetManifestChanged') { + throw 'A republished manifest was not rejected by the built installer.' + } + $installed = Import-PowerShellDataFile -LiteralPath $Plan.InstalledManifestPath + $version = "$($installed.ModuleVersion)-$($installed.PrivateData.PSData.Prerelease)" + if ($version -cne $Plan.InstalledVersion) { + throw 'Rejected inspected content mutated the installed target.' + } +} diff --git a/tests/TestHelpers/Get-PMUTestProviderFailure.ps1 b/tests/TestHelpers/Get-PMUTestProviderFailure.ps1 new file mode 100644 index 0000000..c614966 --- /dev/null +++ b/tests/TestHelpers/Get-PMUTestProviderFailure.ps1 @@ -0,0 +1,10 @@ +function Get-PMUTestProviderFailure { + param( + [string]$Id = 'PackageNotFound', + [string]$Message = 'provider-secret-fixture credential-user-fixture', + [System.Management.Automation.ErrorCategory]$Category = 'ObjectNotFound' + ) + + $exception = [InvalidOperationException]::new($Message) + return [System.Management.Automation.ErrorRecord]::new($exception, $Id, $Category, $null) +} diff --git a/tests/TestHelpers/Initialize-PMUInspectionMock.ps1 b/tests/TestHelpers/Initialize-PMUInspectionMock.ps1 new file mode 100644 index 0000000..60dcf24 --- /dev/null +++ b/tests/TestHelpers/Initialize-PMUInspectionMock.ps1 @@ -0,0 +1,14 @@ +function Initialize-PMUInspectionMock { + Initialize-PMURepositoryMock + Initialize-PMUProviderMock + Mock Invoke-ManifestAcquisition { + $null = @(Initialize-StagedPackage $Operation) + } + Mock Save-ProviderResource { + $path = Initialize-PMUTestPackage $Operation.StageRoot $Operation.Plan.TargetVersion $Operation.Plan.ModuleGuid $Operation.Plan.ModuleName + $manifest = Join-Path $path "$($Operation.Plan.ModuleName).psd1" + $data = [IO.File]::ReadAllText($manifest).Replace("PSData = @{", "Gerber = @{ MinimumGerberVersion = '7.0.0'; Extra = @('a', 'b') }; PSData = @{") + [IO.File]::WriteAllText($manifest, $data) + $script:inspectionRoot = $Operation.WorkRoot + } +} diff --git a/tests/TestHelpers/Initialize-PMULocalProviderStart.ps1 b/tests/TestHelpers/Initialize-PMULocalProviderStart.ps1 new file mode 100644 index 0000000..bbb80f2 --- /dev/null +++ b/tests/TestHelpers/Initialize-PMULocalProviderStart.ps1 @@ -0,0 +1,39 @@ +function Initialize-PMULocalProviderStart { + param( + [string]$Root, + [string]$ModulePath, + [string]$FixtureScript + ) + $start = [Diagnostics.ProcessStartInfo]::new((Get-Process -Id $PID).Path) + foreach ($argument in @('-NoLogo', '-NoProfile', '-NonInteractive', '-File', $FixtureScript, '-Root', $Root, '-ModulePath', $ModulePath)) { + $start.ArgumentList.Add($argument) + } + Initialize-PMUFixtureHome $start $Root + $start.RedirectStandardOutput = $true + $start.RedirectStandardError = $true + $start +} + +function Initialize-PMUFixtureHome { + param( + [Diagnostics.ProcessStartInfo]$Start, + [string]$Root + ) + $homePath = Join-Path $Root 'home' + $null = New-Item $homePath -ItemType Directory -Force + $Start.Environment['HOME'] = $homePath + foreach ($entry in (Get-PMUFixtureHomeMap).GetEnumerator()) { + $path = Join-Path $homePath $entry.Value + $null = New-Item $path -ItemType Directory -Force + $Start.Environment[$entry.Key] = $path + } +} + +function Get-PMUFixtureHomeMap { + @{ + XDG_CONFIG_HOME = '.config' + XDG_CACHE_HOME = '.cache' + XDG_DATA_HOME = '.local/share' + TMPDIR = 'tmp' + } +} diff --git a/tests/TestHelpers/Initialize-PMUManifestFixture.ps1 b/tests/TestHelpers/Initialize-PMUManifestFixture.ps1 new file mode 100644 index 0000000..48e801a --- /dev/null +++ b/tests/TestHelpers/Initialize-PMUManifestFixture.ps1 @@ -0,0 +1,53 @@ +function Initialize-PMUManifestFixture { + param( + [object]$Fixture, + [string]$MinimumVersion, + [string]$Version = '2.0.0-preview2' + ) + $path = Join-Path $Fixture.Feed "$($Fixture.Name).$Version.nupkg" + $archive = [IO.Compression.ZipFile]::Open($path, [IO.Compression.ZipArchiveMode]::Update) + try { + Initialize-PMUArchiveManifest $archive "$($Fixture.Name).psd1" $MinimumVersion + } finally { + $archive.Dispose() + } +} + +function Initialize-PMUArchiveManifest { + param( + [object]$Archive, + [string]$Name, + [string]$MinimumVersion + ) + $text = Read-PMUFixtureArchiveManifest $Archive $Name + $text = $text -replace "Gerber = @\{ MinimumGerberVersion = '[^']+' \}; ", '' + Write-PMUFixtureArchiveManifest $Archive $Name ($text.Replace('PrivateData = @{', "PrivateData = @{ Gerber = @{ MinimumGerberVersion = '$MinimumVersion' };")) +} + +function Read-PMUFixtureArchiveManifest { + param( + [object]$Archive, + [string]$Name + ) + $reader = [IO.StreamReader]::new($Archive.GetEntry($Name).Open()) + try { + $reader.ReadToEnd() + } finally { + $reader.Dispose() + } +} + +function Write-PMUFixtureArchiveManifest { + param( + [object]$Archive, + [string]$Name, + [string]$Text + ) + $Archive.GetEntry($Name).Delete() + $writer = [IO.StreamWriter]::new($Archive.CreateEntry($Name).Open()) + try { + $writer.Write($Text) + } finally { + $writer.Dispose() + } +} diff --git a/tests/TestHelpers/Invoke-PMULocalProviderProcess.ps1 b/tests/TestHelpers/Invoke-PMULocalProviderProcess.ps1 index 3efeb3d..8fb4bfd 100644 --- a/tests/TestHelpers/Invoke-PMULocalProviderProcess.ps1 +++ b/tests/TestHelpers/Invoke-PMULocalProviderProcess.ps1 @@ -1,28 +1,12 @@ +. "$PSScriptRoot/Initialize-PMULocalProviderStart.ps1" function Invoke-PMULocalProviderProcess { param( [string]$Root, - [string]$ModulePath + [string]$ModulePath, + [string]$FixtureScript = "$PSScriptRoot/Invoke-PMULocalProviderFixture.ps1" ) - $homePath = Join-Path $Root 'home' - $null = New-Item $homePath -ItemType Directory -Force - $start = [Diagnostics.ProcessStartInfo]::new((Get-Process -Id $PID).Path) - foreach ($argument in @('-NoLogo', '-NoProfile', '-NonInteractive', '-File', "$PSScriptRoot/Invoke-PMULocalProviderFixture.ps1", '-Root', $Root, '-ModulePath', $ModulePath)) { - $start.ArgumentList.Add($argument) - } - $start.Environment['HOME'] = $homePath - foreach ($entry in @{ - XDG_CONFIG_HOME = '.config' - XDG_CACHE_HOME = '.cache' - XDG_DATA_HOME = '.local/share' - TMPDIR = 'tmp' - }.GetEnumerator()) { - $path = Join-Path $homePath $entry.Value - $null = New-Item $path -ItemType Directory -Force - $start.Environment[$entry.Key] = $path - } - $start.RedirectStandardOutput = $true - $start.RedirectStandardError = $true + $start = Initialize-PMULocalProviderStart $Root $ModulePath $FixtureScript # This fixture performs five sequential native updates, not one process probe. Receive-PMUChildProcess ([Diagnostics.Process]::Start($start)) -TimeoutMilliseconds 150000 } diff --git a/tests/TestHelpers/Invoke-PMUManifestFixture.ps1 b/tests/TestHelpers/Invoke-PMUManifestFixture.ps1 new file mode 100644 index 0000000..bbe33dd --- /dev/null +++ b/tests/TestHelpers/Invoke-PMUManifestFixture.ps1 @@ -0,0 +1,39 @@ +param( + [string]$Root, + [string]$ModulePath +) +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' +foreach ($helper in @( + 'Initialize-PMUTestPackage', 'Initialize-PMULocalPackage', 'Assert-PMUNativeFixtureStore', + 'Initialize-PMUNativeLocalInstallation', 'Get-PMUFixtureProviderRoot', 'Initialize-PMULocalFixture', + 'Get-PMURegistrationSnapshot', 'Clear-PMUOwnedRegistration', 'Assert-PMUManifestInspection', + 'Initialize-PMUManifestFixture', 'Assert-PMUManifestRepublish' + )) { + . (Join-Path $PSScriptRoot "$helper.ps1") +} +Import-Module Microsoft.PowerShell.PSResourceGet -RequiredVersion 1.2.0 +Import-Module $ModulePath -Force +function Invoke-PMUManifestFixture { + param([string]$Root) + $fixture = Initialize-PMULocalFixture $Root + $before = Get-PMURegistrationSnapshot + try { + $plan = Get-PMUManifestFixturePlan $fixture + Assert-PMUManifestInspection $plan $fixture + } finally { + Clear-PMUOwnedRegistration $fixture $before + } +} +function Get-PMUManifestFixturePlan { + param([object]$Fixture) + Initialize-PMULocalPackage $Fixture '2.0.0-preview2' + Initialize-PMUManifestFixture $Fixture '7.0.0' + $selection = @{ + RepositoryUri = [uri]::new([IO.Path]::GetFullPath($Fixture.Feed), [UriKind]::Absolute) + } + Get-PSModuleUpdate -Module $Fixture.Module @selection -Policy @{ + Channel = 'IncludePrerelease' + } +} +Invoke-PMUManifestFixture $Root diff --git a/tests/private/inspection/Assert-InspectedManifest.Tests.ps1 b/tests/private/inspection/Assert-InspectedManifest.Tests.ps1 new file mode 100644 index 0000000..5e6d912 --- /dev/null +++ b/tests/private/inspection/Assert-InspectedManifest.Tests.ps1 @@ -0,0 +1,25 @@ +BeforeAll { + . "$PSScriptRoot/../../TestHelpers/Import-PMUTestSource.ps1" +} +Describe 'Assert-InspectedManifest' -Tag 'PMU', 'PMUTargetManifest' { + It 'leaves an uninspected plan and an unchanged binding valid' { + { + Assert-InspectedManifest ([pscustomobject]@{ + }) 'first' + } | Should -Not -Throw + { + Assert-InspectedManifest ([pscustomobject]@{ + InspectedManifestHash = 'first' + }) 'first' + } | Should -Not -Throw + } + It 'rejects differing manifest bytes without changing the existing binding' { + $record = [pscustomobject]@{ + InspectedManifestHash = 'first' + } + { + Assert-InspectedManifest $record 'second' + } | Should -Throw -ErrorId PMU.TargetManifestChanged + $record.InspectedManifestHash | Should -BeExactly first + } +} diff --git a/tests/private/inspection/Assert-ManifestReadHash.Tests.ps1 b/tests/private/inspection/Assert-ManifestReadHash.Tests.ps1 new file mode 100644 index 0000000..cfed11f --- /dev/null +++ b/tests/private/inspection/Assert-ManifestReadHash.Tests.ps1 @@ -0,0 +1,17 @@ +BeforeAll { + . "$PSScriptRoot/../../TestHelpers/Import-PMUTestSource.ps1" +} +Describe 'Assert-ManifestReadHash' -Tag 'PMU', 'PMUTargetManifest' { + It 'detects content changes while a manifest is being read' { + $path = Join-Path $TestDrive 'manifest.psd1' + [IO.File]::WriteAllText($path, '@{ One = 1 }') + $hash = (Get-FileHash $path -Algorithm SHA256).Hash + { + Assert-ManifestReadHash $path $hash + } | Should -Not -Throw + [IO.File]::WriteAllText($path, '@{ One = 2 }') + { + Assert-ManifestReadHash $path $hash + } | Should -Throw -ErrorId PMU.TargetManifestChanged + } +} diff --git a/tests/private/inspection/Assert-ManifestWorkerResult.Tests.ps1 b/tests/private/inspection/Assert-ManifestWorkerResult.Tests.ps1 new file mode 100644 index 0000000..d499faf --- /dev/null +++ b/tests/private/inspection/Assert-ManifestWorkerResult.Tests.ps1 @@ -0,0 +1,42 @@ +BeforeAll { + . "$PSScriptRoot/../../TestHelpers/Import-PMUTestSource.ps1" +} +Describe 'Assert-ManifestWorkerResult' -Tag 'PMU', 'PMUTargetManifest' { + It 'accepts only a successful complete response from a successful child' { + { + Assert-ManifestWorkerResult ([pscustomobject]@{ + Phase = 'RESULT' + Success = $true + }) 0 + } | Should -Not -Throw + } + It 'rejects with a safe structured error' -ForEach @( + @{ + Kind = 'failed child' + Phase = 'RESULT' + Success = $true + ExitCode = 1 + } + @{ + Kind = 'unexpected phase' + Phase = 'READY' + Success = $true + ExitCode = 0 + } + @{ + Kind = 'failed operation' + Phase = 'RESULT' + Success = $false + ExitCode = 0 + } + ) { + $result = [pscustomobject]@{ + Phase = $Phase + Success = $Success + ErrorId = 'unsafe fixture-secret' + } + { + Assert-ManifestWorkerResult $result $ExitCode + } | Should -Throw -ErrorId PMU.InstallationFailed -ExpectedMessage '*diagnostics were withheld*' + } +} diff --git a/tests/private/inspection/Clear-ManifestInspection.Tests.ps1 b/tests/private/inspection/Clear-ManifestInspection.Tests.ps1 new file mode 100644 index 0000000..842ae69 --- /dev/null +++ b/tests/private/inspection/Clear-ManifestInspection.Tests.ps1 @@ -0,0 +1,25 @@ +BeforeAll { + . "$PSScriptRoot/../../TestHelpers/Import-PMUTestSource.ps1" +} +Describe 'Clear-ManifestInspection' -Tag 'PMU', 'PMUTargetManifest' { + It 'clears owned files and drops the per-call credential' { + $operation = ConvertTo-ManifestInspectionOperation (Initialize-PMUTestOperation $TestDrive) + Initialize-ControlledDirectory $operation.WorkRoot + [IO.File]::WriteAllText((Join-Path $operation.WorkRoot 'owned.txt'), 'fixture') + $operation.Credential = [pscredential]::new('fixture', [securestring]::new()) + Clear-ManifestInspection $operation + Test-Path $operation.WorkRoot | Should -BeFalse + $operation.Credential | Should -BeNullOrEmpty + { + Clear-ManifestInspection $operation + } | Should -Not -Throw + } + It 'fails closed rather than removing an unexpected workspace' { + $operation = ConvertTo-ManifestInspectionOperation (Initialize-PMUTestOperation $TestDrive) + $operation.WorkRoot = $TestDrive + { + Clear-ManifestInspection $operation + } | Should -Throw -ErrorId PMU.RecoveryRequired + Test-Path $TestDrive | Should -BeTrue + } +} diff --git a/tests/private/inspection/ConvertTo-ManifestInspectionOperation.Tests.ps1 b/tests/private/inspection/ConvertTo-ManifestInspectionOperation.Tests.ps1 new file mode 100644 index 0000000..22f8f85 --- /dev/null +++ b/tests/private/inspection/ConvertTo-ManifestInspectionOperation.Tests.ps1 @@ -0,0 +1,18 @@ +BeforeAll { + . "$PSScriptRoot/../../TestHelpers/Import-PMUTestSource.ps1" +} +Describe 'ConvertTo-ManifestInspectionOperation' -Tag 'PMU', 'PMUTargetManifest' { + It 'uses a unique user-owned workspace even when inspecting an AllUsers plan' { + $operation = Initialize-PMUTestOperation $TestDrive + $operation.Plan.Scope = 'AllUsers' + $snapshot = ConvertTo-Json $operation.Plan -Depth 12 + $result = ConvertTo-ManifestInspectionOperation $operation + $result.WorkRoot | Should -BeExactly (Join-Path $result.DataRoot "inspection-$($result.Journal.TransactionId)") + $result.StageRoot | Should -BeExactly (Join-Path $result.WorkRoot 'stage') + (ConvertTo-Json $operation.Plan -Depth 12) | Should -BeExactly $snapshot + Test-Path $result.WorkRoot | Should -BeFalse + Should -Invoke Resolve-PMUDataRoot -ParameterFilter { + $Scope -eq 'CurrentUser' + } + } +} diff --git a/tests/private/inspection/ConvertTo-ManifestWorkerContext.Tests.ps1 b/tests/private/inspection/ConvertTo-ManifestWorkerContext.Tests.ps1 new file mode 100644 index 0000000..50b6932 --- /dev/null +++ b/tests/private/inspection/ConvertTo-ManifestWorkerContext.Tests.ps1 @@ -0,0 +1,17 @@ +BeforeAll { + . "$PSScriptRoot/../../TestHelpers/Import-PMUTestSource.ps1" +} +Describe 'ConvertTo-ManifestWorkerContext' -Tag 'PMU', 'PMUTargetManifest' { + It 'binds the inspection worker to the exact operation transport without transferring a mutation lock' { + $operation = ConvertTo-ManifestInspectionOperation (Initialize-PMUTestOperation $TestDrive) + $operation.RepositoryName = 'owned-transport' + Mock Resolve-ModuleInstallationRoot { + 'fixture-root' + } + $context = ConvertTo-ManifestWorkerContext $operation 'built-module.psm1' + $context.ModulePath | Should -BeExactly 'built-module.psm1' + $context.Operation.RepositoryName | Should -BeExactly 'owned-transport' + $context.InspectManifest | Should -BeTrue + $context.Operation.PSObject.Properties.Name | Should -Not -Contain Lock + } +} diff --git a/tests/private/inspection/ConvertTo-TargetManifest.Tests.ps1 b/tests/private/inspection/ConvertTo-TargetManifest.Tests.ps1 new file mode 100644 index 0000000..8bd868c --- /dev/null +++ b/tests/private/inspection/ConvertTo-TargetManifest.Tests.ps1 @@ -0,0 +1,19 @@ +BeforeAll { + . "$PSScriptRoot/../../TestHelpers/Import-PMUTestSource.ps1" +} +Describe 'ConvertTo-TargetManifest' -Tag 'PMU', 'PMUTargetManifest' { + It 'exposes only the documented identity and data-only manifest fields' { + $operation = Initialize-PMUTestOperation $TestDrive + $manifest = @{ + PrivateData = @{ + Application = @{ + MinimumVersion = '7.0.0' + } + } + } + $result = ConvertTo-TargetManifest $operation.Plan $manifest + $result.PSObject.Properties.Name | Sort-Object | Should -Be @('Manifest', 'ModuleGuid', 'ModuleName', 'RepositoryUri', 'Version') + $result.Manifest.PrivateData.Application.MinimumVersion | Should -Be '7.0.0' + $result.Version | Should -BeExactly $operation.Plan.TargetVersion + } +} diff --git a/tests/private/inspection/Get-BoundTargetManifest.Tests.ps1 b/tests/private/inspection/Get-BoundTargetManifest.Tests.ps1 new file mode 100644 index 0000000..8369e1f --- /dev/null +++ b/tests/private/inspection/Get-BoundTargetManifest.Tests.ps1 @@ -0,0 +1,19 @@ +BeforeAll { + . "$PSScriptRoot/../../TestHelpers/Import-PMUTestSource.ps1" +} +Describe 'Get-BoundTargetManifest' -Tag 'PMU', 'PMUTargetManifest' { + It 'does not acquire an exact target without rechecked license consent' { + Mock Assert-ExactTarget { + } + Mock Assert-InstallationConsent { + Write-PMUError 'PMU.LicenseAcceptanceRequired' 'Acceptance required.' + } + Mock Invoke-ManifestAcquisition { + } + { + Get-BoundTargetManifest ([pscustomobject]@{ + }) + } | Should -Throw -ErrorId PMU.LicenseAcceptanceRequired + Should -Invoke Invoke-ManifestAcquisition -Times 0 + } +} diff --git a/tests/private/inspection/Get-InspectedTargetManifest.Tests.ps1 b/tests/private/inspection/Get-InspectedTargetManifest.Tests.ps1 new file mode 100644 index 0000000..6e9f45b --- /dev/null +++ b/tests/private/inspection/Get-InspectedTargetManifest.Tests.ps1 @@ -0,0 +1,22 @@ +BeforeAll { + . "$PSScriptRoot/../../TestHelpers/Import-PMUTestSource.ps1" +} +Describe 'Get-InspectedTargetManifest' -Tag 'PMU', 'PMUTargetManifest' { + It 'keeps the original private binding when reinspection content differs' { + $operation = Initialize-PMUTestOperation $TestDrive + Mock Assert-PlanEnvironment { + } + Mock Test-InstalledPlanState { + } + $path = Initialize-PMUTestPackage $operation.StageRoot $operation.Plan.TargetVersion $operation.Plan.ModuleGuid + $first = Get-InspectedTargetManifest $operation + $hash = $operation.Record.InspectedManifestHash + $manifest = Join-Path $path 'FixtureModule.psd1' + [IO.File]::AppendAllText($manifest, "`n") + { + Get-InspectedTargetManifest $operation + } | Should -Throw -ErrorId PMU.TargetManifestChanged + $operation.Record.InspectedManifestHash | Should -BeExactly $hash + $first.Version | Should -BeExactly $operation.Plan.TargetVersion + } +} diff --git a/tests/private/inspection/Initialize-ManifestInspection.Tests.ps1 b/tests/private/inspection/Initialize-ManifestInspection.Tests.ps1 new file mode 100644 index 0000000..e48d056 --- /dev/null +++ b/tests/private/inspection/Initialize-ManifestInspection.Tests.ps1 @@ -0,0 +1,22 @@ +BeforeAll { + . "$PSScriptRoot/../../TestHelpers/Import-PMUTestSource.ps1" +} +Describe 'Initialize-ManifestInspection' -Tag 'PMU', 'PMUTargetManifest' { + It 'checks consent before creating an inspection workspace' { + Mock Initialize-InstallationRequest { + [pscustomobject]@{ + Consent = $Consent + } + } + Mock Assert-InstallationConsent { + Write-PMUError 'PMU.RepositoryTrustRequired' 'Approval required.' + } + Mock ConvertTo-ManifestInspectionOperation { + } + { + Initialize-ManifestInspection ([pscustomobject]@{ + }) $null $false $false + } | Should -Throw -ErrorId PMU.RepositoryTrustRequired + Should -Invoke ConvertTo-ManifestInspectionOperation -Times 0 + } +} diff --git a/tests/private/inspection/Invoke-ManifestAcquisition.Tests.ps1 b/tests/private/inspection/Invoke-ManifestAcquisition.Tests.ps1 new file mode 100644 index 0000000..6108c02 --- /dev/null +++ b/tests/private/inspection/Invoke-ManifestAcquisition.Tests.ps1 @@ -0,0 +1,46 @@ +BeforeAll { + . "$PSScriptRoot/../../TestHelpers/Import-PMUTestSource.ps1" +} +Describe 'Invoke-ManifestAcquisition' -Tag 'PMU', 'PMUTargetManifest' { + It 'rejects built module instances' -ForEach @( + @{ + Instances = 0 + } + @{ + Instances = 2 + } + ) { + Mock Invoke-ManifestWorkerProcess { + } + Mock Get-Module { + @(@([pscustomobject]@{ + Path = 'a' + }, [pscustomobject]@{ + Path = 'b' + }) | Select-Object -First $Instances) + } + { + Invoke-ManifestAcquisition ([pscustomobject]@{ + }) + } | Should -Throw -ErrorId PMU.UnsupportedProviderBehavior + Should -Invoke Invoke-ManifestWorkerProcess -Times 0 + } + It 'transfers only an inspection context to the isolated worker' { + $operation = ConvertTo-ManifestInspectionOperation (Initialize-PMUTestOperation $TestDrive) + $operation.RepositoryName = 'owned' + Mock Get-Module { + [pscustomobject]@{ + Path = 'built.psm1' + } + } + Mock Resolve-ModuleInstallationRoot { + 'fixture-root' + } + Mock Invoke-ManifestWorkerProcess { + } + Invoke-ManifestAcquisition $operation + Should -Invoke Invoke-ManifestWorkerProcess -Times 1 -ParameterFilter { + $Context.InspectManifest -and $Context.ModulePath -eq 'built.psm1' -and $Context.Operation.RepositoryName -eq 'owned' + } + } +} diff --git a/tests/private/inspection/Invoke-ManifestWorkerProcess.Tests.ps1 b/tests/private/inspection/Invoke-ManifestWorkerProcess.Tests.ps1 new file mode 100644 index 0000000..5a30142 --- /dev/null +++ b/tests/private/inspection/Invoke-ManifestWorkerProcess.Tests.ps1 @@ -0,0 +1,49 @@ +BeforeAll { + . "$PSScriptRoot/../../TestHelpers/Import-PMUTestSource.ps1" +} +Describe 'Invoke-ManifestWorkerProcess' -Tag 'PMU', 'PMUTargetManifest' { + It 'waits for the child and disposes it on a response' -ForEach @( + @{ + Kind = 'complete' + Text = 'PMU_NATIVE:{"Phase":"RESULT","Success":true}' + ErrorId = $null + } + @{ + Kind = 'missing' + Text = '' + ErrorId = 'PMU.RecoveryRequired' + } + ) { + $script:disposed = $false + $process = [pscustomobject]@{ + StandardOutput = [IO.StringReader]::new($Text) + } + $process | Add-Member ScriptMethod Dispose { + $script:disposed = $true + } + $script:worker = [pscustomobject]@{ + Process = $process + ExitCode = 0 + } + Mock Invoke-NativeWorkerStart { + $script:worker + } + Mock Wait-NativeWorkerStop { + } + if ($ErrorId) { + { + Invoke-ManifestWorkerProcess ([pscustomobject]@{ + }) ([pscustomobject]@{ + }) + } | Should -Throw -ErrorId $ErrorId + } else { + { + Invoke-ManifestWorkerProcess ([pscustomobject]@{ + }) ([pscustomobject]@{ + }) + } | Should -Not -Throw + } + $disposed | Should -BeTrue + Should -Invoke Wait-NativeWorkerStop -Times 1 -Exactly + } +} diff --git a/tests/private/inspection/Invoke-RepositoryManifestInspection.Tests.ps1 b/tests/private/inspection/Invoke-RepositoryManifestInspection.Tests.ps1 new file mode 100644 index 0000000..30fff47 --- /dev/null +++ b/tests/private/inspection/Invoke-RepositoryManifestInspection.Tests.ps1 @@ -0,0 +1,41 @@ +BeforeAll { + . "$PSScriptRoot/../../TestHelpers/Import-PMUTestSource.ps1" +} +Describe 'Invoke-RepositoryManifestInspection' -Tag 'PMU', 'PMUTargetManifest' { + It 'closes the exact temporary transport on ' -ForEach @( + @{ + Outcome = 'success' + } + @{ + Outcome = 'failure' + } + ) { + $operation = Initialize-PMUTestOperation $TestDrive + $script:lease = [pscustomobject]@{ + Name = 'owned' + ReceiptPath = 'fixture' + } + Mock Open-RepositoryTransport { + $script:lease + } + Mock Get-BoundTargetManifest { + if ($Outcome -eq 'failure') { + Write-PMUError 'PMU.PackageNotFound' 'Missing candidate.' + } + 'candidate' + } + Mock Close-RepositoryTransport { + } + if ($Outcome -eq 'failure') { + { + Invoke-RepositoryManifestInspection $operation + } | Should -Throw -ErrorId PMU.PackageNotFound + } else { + Invoke-RepositoryManifestInspection $operation | Should -Be candidate + } + $operation.RepositoryName | Should -Be owned + Should -Invoke Close-RepositoryTransport -Times 1 -Exactly -ParameterFilter { + [object]::ReferenceEquals($Lease, $script:lease) + } + } +} diff --git a/tests/private/inspection/Invoke-TargetManifestInspection.Tests.ps1 b/tests/private/inspection/Invoke-TargetManifestInspection.Tests.ps1 new file mode 100644 index 0000000..7f98017 --- /dev/null +++ b/tests/private/inspection/Invoke-TargetManifestInspection.Tests.ps1 @@ -0,0 +1,21 @@ +BeforeAll { + . "$PSScriptRoot/../../TestHelpers/Import-PMUTestSource.ps1" +} +Describe 'Invoke-TargetManifestInspection' -Tag 'PMU', 'PMUTargetManifest' { + It 'does not publish a success result when workspace cleanup fails' { + $operation = ConvertTo-ManifestInspectionOperation (Initialize-PMUTestOperation $TestDrive) + Mock Invoke-RepositoryManifestInspection { + 'candidate' + } + Mock Clear-ManifestInspection { + Write-PMUError 'PMU.RecoveryRequired' 'Cleanup failed.' + } + $output = [Collections.Generic.List[object]]::new() + { + Invoke-TargetManifestInspection $operation | ForEach-Object { + $output.Add($_) + } + } | Should -Throw -ErrorId PMU.RecoveryRequired + $output.Count | Should -Be 0 + } +} diff --git a/tests/private/inspection/Write-ManifestInspectionError.Tests.ps1 b/tests/private/inspection/Write-ManifestInspectionError.Tests.ps1 new file mode 100644 index 0000000..cc3b7b2 --- /dev/null +++ b/tests/private/inspection/Write-ManifestInspectionError.Tests.ps1 @@ -0,0 +1,30 @@ +BeforeAll { + . "$PSScriptRoot/../../TestHelpers/Import-PMUTestSource.ps1" +} +Describe 'Write-ManifestInspectionError' -Tag 'PMU', 'PMUTargetManifest' { + It 'withholds arbitrary diagnostics including inner exceptions' { + try { + throw [InvalidOperationException]::new('fixture-secret') + } catch { + $failure = $_ + } + try { + Write-ManifestInspectionError $failure + } catch { + $safe = $_ + } + $safe.FullyQualifiedErrorId | Should -Be PMU.InstallationFailed + ($safe | Out-String) | Should -Not -Match fixture-secret + $safe.Exception.InnerException | Should -BeNullOrEmpty + } + It 'preserves a safe PMU error without replacing its identifier' { + try { + Write-PMUError 'PMU.RepositoryTrustRequired' 'Explicit approval required.' + } catch { + $failure = $_ + } + { + Write-ManifestInspectionError $failure + } | Should -Throw -ErrorId PMU.RepositoryTrustRequired + } +} diff --git a/tests/private/inspection/Write-ManifestWorkerError.Tests.ps1 b/tests/private/inspection/Write-ManifestWorkerError.Tests.ps1 new file mode 100644 index 0000000..ad85613 --- /dev/null +++ b/tests/private/inspection/Write-ManifestWorkerError.Tests.ps1 @@ -0,0 +1,13 @@ +BeforeAll { + . "$PSScriptRoot/../../TestHelpers/Import-PMUTestSource.ps1" +} +Describe 'Write-ManifestWorkerError' -Tag 'PMU', 'PMUTargetManifest' { + It 'preserves only a validated structured PMU identifier' { + { + Write-ManifestWorkerError ([pscustomobject]@{ + ErrorId = 'PMU.GuidMismatch' + }) + } | + Should -Throw -ErrorId PMU.GuidMismatch -ExpectedMessage '*diagnostics were withheld*' + } +} diff --git a/tests/private/installation/Assert-ExactTarget.Tests.ps1 b/tests/private/installation/Assert-ExactTarget.Tests.ps1 index 9f6eb9b..5a17218 100644 --- a/tests/private/installation/Assert-ExactTarget.Tests.ps1 +++ b/tests/private/installation/Assert-ExactTarget.Tests.ps1 @@ -1,4 +1,7 @@ -BeforeAll { . "$PSScriptRoot/../../TestHelpers/Import-PMUTestSource.ps1" } +BeforeAll { + . "$PSScriptRoot/../../TestHelpers/Import-PMUTestSource.ps1" + Import-Module Microsoft.PowerShell.PSResourceGet -RequiredVersion 1.2.0 +} Describe 'Assert-ExactTarget' -Tag 'PMU' { It 'never substitutes latest when the approved target disappears' { $operation = Initialize-PMUTestOperation $TestDrive @@ -7,4 +10,14 @@ Describe 'Assert-ExactTarget' -Tag 'PMU' { { Assert-ExactTarget $operation } | Should -Throw -ErrorId 'PMU.PackageNotFound' Should -Invoke Find-ProviderResource -Times 1 -ParameterFilter { $Request.Version -eq '[2.0.0-preview.2]' } } + It 'fails closed without retry or substitution for provider ID ' -Tag 'PMUPackageNotFound' -ForEach @( + @{ ProviderId = 'PackageNotFound' } + @{ ProviderId = 'PackageNotFound,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource' } + ) { + $operation = Initialize-PMUTestOperation $TestDrive + Mock Assert-RepositoryBinding {} + Mock Find-PSResource { throw (Get-PMUTestProviderFailure $ProviderId) } + { Assert-ExactTarget $operation } | Should -Throw -ErrorId 'PMU.PackageNotFound' + Should -Invoke Find-PSResource -Times 1 -Exactly -ParameterFilter { $Version -eq '[2.0.0-preview.2]' -and $ErrorAction -eq 'Stop' } + } } diff --git a/tests/private/installation/Assert-NativeInstallationSnapshot.Tests.ps1 b/tests/private/installation/Assert-NativeInstallationSnapshot.Tests.ps1 index c80dcc1..97ae79f 100644 --- a/tests/private/installation/Assert-NativeInstallationSnapshot.Tests.ps1 +++ b/tests/private/installation/Assert-NativeInstallationSnapshot.Tests.ps1 @@ -6,7 +6,7 @@ Describe 'Assert-NativeInstallationSnapshot' -Tag 'PMUNativeHandoff' { BeforeEach { $operation = Initialize-PMUTestOperation $TestDrive $path = Split-Path -Parent $operation.Plan.InstalledManifestPath - $script:snapshotSource = [pscustomobject]@{ Name = 'ApprovedFeed'; Uri = $operation.Plan.RepositoryUri } + $script:snapshotSource = [pscustomobject]@{ Name = 'ApprovedFeed'; Uri = $operation.Plan.RepositoryUri; Unmanaged = $false } $script:snapshotContext = [pscustomobject]@{ Operation = $operation Snapshot = [pscustomobject]@{ @@ -41,4 +41,13 @@ Describe 'Assert-NativeInstallationSnapshot' -Tag 'PMUNativeHandoff' { { Assert-NativeInstallationSnapshot $snapshotContext } | Should -Throw -ErrorId 'PMU.InstalledStateChanged' } + It 'revalidates unmanaged absence while retaining tree and identity checks' { + $snapshotContext.Operation.Consent.ReplaceUnmanagedInstallation = $true + $snapshotContext.Operation.RepositoryName = 'ApprovedFeed' + $snapshotContext.Snapshot.Source.Unmanaged = $true + @(Assert-NativeInstallationSnapshot $snapshotContext).Count | Should -Be 0 + Should -Invoke Get-NativeInstalledSource -Times 0 + [IO.File]::WriteAllText((Join-Path $snapshotContext.Snapshot.Path 'PSGetModuleInfo.xml'), 'appeared') + { Assert-NativeInstallationSnapshot $snapshotContext } | Should -Throw -ErrorId 'PMU.InstalledStateChanged' + } } diff --git a/tests/private/installation/Assert-NativeSelectedInstallation.Tests.ps1 b/tests/private/installation/Assert-NativeSelectedInstallation.Tests.ps1 index b8a5a9f..ff1f59d 100644 --- a/tests/private/installation/Assert-NativeSelectedInstallation.Tests.ps1 +++ b/tests/private/installation/Assert-NativeSelectedInstallation.Tests.ps1 @@ -27,6 +27,7 @@ Describe 'Assert-NativeSelectedInstallation' -Tag 'PMU', 'PMUNativeHandoff' { Source = [pscustomobject]@{ Name = $operation.RepositoryName Uri = $operation.Plan.RepositoryUri + Unmanaged = $false } } } @@ -40,6 +41,15 @@ Describe 'Assert-NativeSelectedInstallation' -Tag 'PMU', 'PMUNativeHandoff' { It 'accepts an unchanged selected tree and approved native source in the same scope' { Assert-NativeSelectedInstallation $selectionContext } + It 'skips native candidate lookup only for an opted-in unmanaged original' { + $selectionContext.Operation.Consent.ReplaceUnmanagedInstallation = $true + Remove-Item (Join-Path $selectionContext.Snapshot.Path 'PSGetModuleInfo.xml') + $selectionContext.Snapshot.Source.Unmanaged = $true + Assert-NativeSelectedInstallation $selectionContext + Should -Invoke Get-InstalledModule -Times 0 + [IO.File]::AppendAllText((Join-Path $selectionContext.Snapshot.Path 'FixtureModule.psm1'), 'changed') + { Assert-NativeSelectedInstallation $selectionContext } | Should -Throw -ErrorId 'PMU.InstalledStateChanged' + } It 'rejects native selection of a path outside the observed selected-scope installations' { $nativeCandidate.InstalledLocation = Join-Path $TestDrive 'other-scope' { Assert-NativeSelectedInstallation $selectionContext } | Should -Throw -ErrorId 'PMU.UnsupportedInstallation' diff --git a/tests/private/installation/ConvertTo-NativeWorkerOperation.Tests.ps1 b/tests/private/installation/ConvertTo-NativeWorkerOperation.Tests.ps1 index c8f15c8..dc2f56e 100644 --- a/tests/private/installation/ConvertTo-NativeWorkerOperation.Tests.ps1 +++ b/tests/private/installation/ConvertTo-NativeWorkerOperation.Tests.ps1 @@ -7,6 +7,7 @@ Describe 'ConvertTo-NativeWorkerOperation' -Tag 'PMU', 'PMUWorkerContracts' { $operation = Initialize-PMURecoveryFixture $TestDrive $credential = [pscredential]::new('fixture-user', [securestring]::new()) $operation.Credential = $credential + $operation.Record | Add-Member InspectedManifestHash ('a' * 64) $snapshot = [pscustomobject]@{ Source = [pscustomobject]@{ Name = 'ApprovedFeed' } } Mock Get-NativeProviderRoot { 'owned-root' } Mock Resolve-ModuleInstallationRoot { 'module-root' } @@ -17,6 +18,7 @@ Describe 'ConvertTo-NativeWorkerOperation' -Tag 'PMU', 'PMUWorkerContracts' { [object]::ReferenceEquals($copy.Plan, $operation.Plan) | Should -BeTrue [object]::ReferenceEquals($copy.Record, $operation.Record) | Should -BeFalse @($copy.Record.InstalledTree) | Should -Be @($operation.Record.InstalledTree) + $copy.Record.InspectedManifestHash | Should -BeExactly ('a' * 64) $copy.PSObject.Properties.Name | Should -Not -Contain 'Lock' $operation.PSObject.Properties.Name | Should -Not -Contain 'NativeContext' $copy.RepositoryName | Should -BeExactly 'ApprovedFeed' @@ -24,4 +26,17 @@ Describe 'ConvertTo-NativeWorkerOperation' -Tag 'PMU', 'PMUWorkerContracts' { $copy.NativeContext.CurrentUserRoot | Should -BeExactly 'module-root' $copy.NativeContext.Paths | Should -BeNullOrEmpty } + It 'preserves unmanaged consent through the actual native payload serialization' { + $operation = Initialize-PMUTestOperation $TestDrive + $operation.Consent.ReplaceUnmanagedInstallation = $true + $snapshot = [pscustomobject]@{ Source = [pscustomobject]@{ Name = 'ApprovedFeed' } } + Mock Get-NativeProviderRoot { 'owned-root' } + Mock Resolve-ModuleInstallationRoot { 'module-root' } + $copy = ConvertTo-NativeWorkerOperation $operation $snapshot + $payload = ConvertTo-NativeWorkerPayload ([pscustomobject]@{ Operation = $copy }) + $xml = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($payload)) + $worker = [Management.Automation.PSSerializer]::Deserialize($xml) + $worker.Operation.Consent['ReplaceUnmanagedInstallation'] | Should -BeTrue + Test-UnmanagedInstallation $worker.Operation (Split-Path -Parent $operation.Plan.InstalledManifestPath) | Should -BeTrue + } } diff --git a/tests/private/installation/Get-NativeSelectedSnapshot.Tests.ps1 b/tests/private/installation/Get-NativeSelectedSnapshot.Tests.ps1 index fe7130b..a76a9bf 100644 --- a/tests/private/installation/Get-NativeSelectedSnapshot.Tests.ps1 +++ b/tests/private/installation/Get-NativeSelectedSnapshot.Tests.ps1 @@ -46,4 +46,13 @@ Describe 'Get-NativeSelectedSnapshot' -Tag 'PMU', 'PMUWorkerContracts' { Should -Throw -ErrorId 'PMU.SourceMismatch' Should -Invoke Get-FileTreeInventory -Times 0 } + It 'snapshots an opted-in unmanaged original without reading native metadata' { + $operation.Consent.ReplaceUnmanagedInstallation = $true + $operation.RepositoryName = 'ApprovedFeed' + $snapshot = Get-NativeSelectedSnapshot $operation $false + $snapshot.Source.Unmanaged | Should -BeTrue + $snapshot.Version | Should -BeExactly $operation.Plan.InstalledVersion + $snapshot.Tree.Count | Should -BeGreaterThan 0 + Should -Invoke Get-NativeInstalledSource -Times 0 + } } diff --git a/tests/private/installation/Get-NativeSnapshotPath.Tests.ps1 b/tests/private/installation/Get-NativeSnapshotPath.Tests.ps1 new file mode 100644 index 0000000..73a2799 --- /dev/null +++ b/tests/private/installation/Get-NativeSnapshotPath.Tests.ps1 @@ -0,0 +1,9 @@ +BeforeAll { . "$PSScriptRoot/../../TestHelpers/Import-PMUTestSource.ps1" } +Describe 'Get-NativeSnapshotPath' -Tag 'PMU' { + It 'selects only the original or already installed planned target' { + $operation = Initialize-PMUTestOperation $TestDrive + $operation.Plan.TargetInstalledPath = Join-Path $TestDrive 'target' + Get-NativeSnapshotPath $operation $false | Should -BeExactly (Split-Path -Parent $operation.Plan.InstalledManifestPath) + Get-NativeSnapshotPath $operation $true | Should -BeExactly $operation.Plan.TargetInstalledPath + } +} diff --git a/tests/private/installation/Initialize-Replacement.Tests.ps1 b/tests/private/installation/Initialize-Replacement.Tests.ps1 index 65e46b1..6789eeb 100644 --- a/tests/private/installation/Initialize-Replacement.Tests.ps1 +++ b/tests/private/installation/Initialize-Replacement.Tests.ps1 @@ -14,4 +14,20 @@ Describe 'Initialize-Replacement' -Tag 'PMU' { $null = Initialize-PMUTestPackage $operation.Plan.DestinationRoot '2.0.0-preview.2' ([guid]::NewGuid()) { Initialize-Replacement $operation @() } | Should -Throw -ErrorId 'PMU.GuidMismatch' } + It 'backs up an unmanaged same-base original and restores it after failed replacement' -Tag 'PMUBackupCharacterization' { + $operation = Initialize-PMUTestOperation $TestDrive + $operation.Consent.ReplaceUnmanagedInstallation = $true + $path = Split-Path -Parent $operation.Plan.InstalledManifestPath + $operation.Plan.TargetInstalledPath | Should -BeExactly $path + Initialize-ControlledDirectory $operation.WorkRoot + Initialize-Replacement $operation @() + $operation.Reinstall | Should -BeTrue + Test-Path $operation.BackupPath | Should -BeTrue + $operation.Journal.State | Should -BeExactly 'BackupReady' + [IO.File]::AppendAllText((Join-Path $path 'FixtureModule.psm1'), 'replacement') + Restore-InstallationBackup $operation.Journal $operation + Assert-FileTreeEqual $operation.Journal.BackupTree @(Get-FileTreeInventory $path) + $operation.Journal.State | Should -BeExactly 'RecoveryCompleted' + Test-Path (Join-Path $path 'PSGetModuleInfo.xml') | Should -BeFalse + } } diff --git a/tests/private/installation/Invoke-NativeWorker.Tests.ps1 b/tests/private/installation/Invoke-NativeWorker.Tests.ps1 index 9955379..06fa694 100644 --- a/tests/private/installation/Invoke-NativeWorker.Tests.ps1 +++ b/tests/private/installation/Invoke-NativeWorker.Tests.ps1 @@ -46,4 +46,16 @@ Describe 'Invoke-NativeWorker' -Tag 'PMU', 'PMUWorkerProtocol' { $messages[1].ErrorId | Should -BeExactly 'PMU.PlanStale' $leaseEntered | Should -BeFalse } + + It 'reports inspection staging failure without entering the installation handshake' -Tag 'PMUTargetManifest' { + $context | Add-Member InspectManifest $true + Mock Initialize-StagedPackage { + Write-PMUError 'PMU.GuidMismatch' 'Wrong target.' + } + Invoke-NativeWorker $context + $messages.Count | Should -Be 1 + $messages[0].ErrorId | Should -Be PMU.GuidMismatch + $leaseEntered | Should -BeFalse + Should -Invoke Assert-NativeWorkerGo -Times 0 + } } diff --git a/tests/private/installation/Invoke-NativeWorkerAction.Tests.ps1 b/tests/private/installation/Invoke-NativeWorkerAction.Tests.ps1 new file mode 100644 index 0000000..d40d962 --- /dev/null +++ b/tests/private/installation/Invoke-NativeWorkerAction.Tests.ps1 @@ -0,0 +1,28 @@ +# Invoke-NativeWorker.Tests.ps1 also preserves the complete native READY/GO protocol. +BeforeAll { + . "$PSScriptRoot/../../TestHelpers/Import-PMUTestSource.ps1" +} +Describe 'Invoke-NativeWorkerAction' -Tag 'PMU', 'PMUTargetManifest' { + It 'stages inspection without requesting installation permission or entering its lease' { + $script:result = $null + Mock Initialize-StagedPackage { + 'inventory' + } + Mock Write-NativeWorkerMessage { + $script:result = $Message + } + Mock Assert-NativeWorkerGo { + } + Mock Invoke-NativeWorkerLease { + } + Invoke-NativeWorkerAction ([pscustomobject]@{ + InspectManifest = $true + Operation = [pscustomobject]@{ + } + }) + $result.Phase | Should -Be RESULT + $result.Success | Should -BeTrue + Should -Invoke Assert-NativeWorkerGo -Times 0 + Should -Invoke Invoke-NativeWorkerLease -Times 0 + } +} diff --git a/tests/private/provider/ConvertTo-NativePlanRecord.Tests.ps1 b/tests/private/provider/ConvertTo-NativePlanRecord.Tests.ps1 new file mode 100644 index 0000000..05adb59 --- /dev/null +++ b/tests/private/provider/ConvertTo-NativePlanRecord.Tests.ps1 @@ -0,0 +1,18 @@ +BeforeAll { + . "$PSScriptRoot/../../TestHelpers/Import-PMUTestSource.ps1" +} +Describe 'ConvertTo-NativePlanRecord' -Tag 'PMU', 'PMUTargetManifest' { + It 'copies the private manifest binding without exposing or sharing the original record' { + $record = [pscustomobject]@{ + InstalledTree = @('fixture') + InspectedManifestHash = 'first' + Snapshot = 'private' + } + $copy = ConvertTo-NativePlanRecord $record + $copy.InspectedManifestHash | Should -Be first + $copy.InstalledTree | Should -Be @('fixture') + $copy.PSObject.Properties.Name | Should -Not -Contain Snapshot + $copy.InspectedManifestHash = 'second' + $record.InspectedManifestHash | Should -Be first + } +} diff --git a/tests/private/provider/ConvertTo-NativeProviderContext.Tests.ps1 b/tests/private/provider/ConvertTo-NativeProviderContext.Tests.ps1 new file mode 100644 index 0000000..a84c03f --- /dev/null +++ b/tests/private/provider/ConvertTo-NativeProviderContext.Tests.ps1 @@ -0,0 +1,18 @@ +BeforeAll { + . "$PSScriptRoot/../../TestHelpers/Import-PMUTestSource.ps1" +} +Describe 'ConvertTo-NativeProviderContext' -Tag 'PMU', 'PMUTargetManifest' { + It 'retains owned provider root and original CurrentUser destination' { + Mock Get-NativeProviderRoot { + 'owned' + } + Mock Resolve-ModuleInstallationRoot { + 'original-user-modules' + } + $result = ConvertTo-NativeProviderContext ([pscustomobject]@{ + }) + $result.Root | Should -Be owned + $result.CurrentUserRoot | Should -Be original-user-modules + $result.Paths | Should -BeNullOrEmpty + } +} diff --git a/tests/private/provider/Find-ProviderResource.Tests.ps1 b/tests/private/provider/Find-ProviderResource.Tests.ps1 index e922c85..b27e6fd 100644 --- a/tests/private/provider/Find-ProviderResource.Tests.ps1 +++ b/tests/private/provider/Find-ProviderResource.Tests.ps1 @@ -49,4 +49,53 @@ Describe 'Find-ProviderResource' -Tag 'PMU' { Prerelease = $false } $null } | Should -Throw -ErrorId 'PMU.DiscoveryFailed' } + Context 'provider boundary outcomes' { + BeforeEach { + $script:discoveryRequest = @{ + Name = 'FixtureModule' + Repository = 'OwnedFeed' + Version = $null + Prerelease = $false + } + } + It 'returns the original provider objects in order' { + $resources = @([pscustomobject]@{ Version = '1.0.0' }, [pscustomobject]@{ Version = '2.0.0' }) + Mock Find-PSResource { $resources } + $actual = @(Find-ProviderResource $script:discoveryRequest $null) + $actual.Count | Should -Be 2 + [object]::ReferenceEquals($actual[0], $resources[0]) | Should -BeTrue + [object]::ReferenceEquals($actual[1], $resources[1]) | Should -BeTrue + } + It 'preserves an empty successful provider result' { + Mock Find-PSResource { @() } + @(Find-ProviderResource $script:discoveryRequest $null).Count | Should -Be 0 + } + It 'normalizes structured without exposing provider diagnostics' -Tag 'PMUPackageNotFound' -ForEach @( + @{ ProviderId = 'PackageNotFound' } + @{ ProviderId = 'PackageNotFound,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource' } + ) { + Mock Find-PSResource { throw (Get-PMUTestProviderFailure $ProviderId) } + $failure = { Find-ProviderResource $script:discoveryRequest $null } | + Should -Throw -ErrorId 'PMU.PackageNotFound' -PassThru + ($failure | Out-String) | Should -Not -Match 'provider-secret-fixture|credential-user-fixture' + ($failure.TargetObject | ConvertTo-Json) | Should -Not -Match 'provider-secret-fixture|credential-user-fixture' + Should -Invoke Find-PSResource -Times 1 -Exactly -ParameterFilter { $ErrorAction -eq 'Stop' -and $Repository[0] -eq 'OwnedFeed' } + } + It 'retains for unrelated structured ID ' -Tag 'PMUPackageNotFound' -ForEach @( + @{ ProviderId = 'OtherMissingResource'; Category = 'ObjectNotFound'; Message = 'PackageNotFound: no package found'; ExpectedId = 'PMU.DiscoveryFailed' } + @{ ProviderId = 'PrefixPackageNotFound'; Category = 'ObjectNotFound'; Message = 'no package found'; ExpectedId = 'PMU.DiscoveryFailed' } + @{ ProviderId = 'PackageNotFoundExtra'; Category = 'ObjectNotFound'; Message = 'no package found'; ExpectedId = 'PMU.DiscoveryFailed' } + @{ ProviderId = 'packagenotfound'; Category = 'ObjectNotFound'; Message = 'no package found'; ExpectedId = 'PMU.DiscoveryFailed' } + @{ ProviderId = 'OtherError,PackageNotFound'; Category = 'ObjectNotFound'; Message = 'no package found'; ExpectedId = 'PMU.DiscoveryFailed' } + @{ ProviderId = 'NetworkFailure'; Category = 'ConnectionError'; Message = 'feed offline'; ExpectedId = 'PMU.DiscoveryFailed' } + @{ ProviderId = 'AuthenticationFailure'; Category = 'SecurityError'; Message = '401 authentication failed'; ExpectedId = 'PMU.AuthenticationFailed' } + @{ ProviderId = 'PermissionFailure'; Category = 'PermissionDenied'; Message = 'permission denied'; ExpectedId = 'PMU.PermissionDenied' } + ) { + Mock Find-PSResource { throw (Get-PMUTestProviderFailure $ProviderId "$Message provider-secret-fixture" $Category) } + $failure = { Find-ProviderResource $script:discoveryRequest $null } | + Should -Throw -ErrorId $ExpectedId -PassThru + ($failure | Out-String) | Should -Not -Match 'provider-secret-fixture' + Should -Invoke Find-PSResource -Times 1 -Exactly -ParameterFilter { $ErrorAction -eq 'Stop' } + } + } } diff --git a/tests/private/provider/Get-NativeInstallParameter.Tests.ps1 b/tests/private/provider/Get-NativeInstallParameter.Tests.ps1 new file mode 100644 index 0000000..3a1d021 --- /dev/null +++ b/tests/private/provider/Get-NativeInstallParameter.Tests.ps1 @@ -0,0 +1,32 @@ +BeforeAll { . "$PSScriptRoot/../../TestHelpers/Import-PMUTestSource.ps1" } +Describe 'Get-NativeInstallParameter' -Tag 'PMU', 'PMUUnmanaged' { + It 'retains exact prerelease version, scope, source and credential for Collision=' -ForEach @( + @{ Collision = $false } + @{ Collision = $true } + ) { + $operation = Initialize-PMUTestOperation $TestDrive + $operation.RepositoryName = 'ApprovedFeed' + $operation.Credential = [pscredential]::new('fixture', [securestring]::new()) + if (-not $Collision) { + $operation.Plan.TargetInstalledPath = Join-Path $TestDrive 'absent' + } + $parameters = Get-NativeInstallParameter $operation + $parameters.Name | Should -BeExactly $operation.Plan.ModuleName + $parameters.RequiredVersion | Should -BeExactly $operation.Plan.TargetVersion + $parameters.AllowPrerelease | Should -BeTrue + $parameters.AcceptLicense | Should -BeTrue + $parameters.Repository | Should -BeExactly 'ApprovedFeed' + $parameters.Scope | Should -BeExactly 'CurrentUser' + $parameters.Credential | Should -Be $operation.Credential + $parameters.ContainsKey('Force') | Should -Be $Collision + } + It 'keeps the exact stable target for a same-base promotion' { + $operation = Initialize-PMUTestOperation $TestDrive + $operation.Plan.TargetVersion = '2.0.0' + $operation.Plan.TargetIsPrerelease = $false + $parameters = Get-NativeInstallParameter $operation + $parameters.RequiredVersion | Should -BeExactly '2.0.0' + $parameters.AllowPrerelease | Should -BeFalse + $parameters.ContainsKey('MaximumVersion') | Should -BeFalse + } +} diff --git a/tests/private/provider/Get-NativeSelectedSource.Tests.ps1 b/tests/private/provider/Get-NativeSelectedSource.Tests.ps1 new file mode 100644 index 0000000..774f718 --- /dev/null +++ b/tests/private/provider/Get-NativeSelectedSource.Tests.ps1 @@ -0,0 +1,40 @@ +BeforeAll { . "$PSScriptRoot/../../TestHelpers/Import-PMUTestSource.ps1" } +Describe 'Get-NativeSelectedSource' -Tag 'PMU', 'PMUUnmanaged' { + BeforeEach { + $operation = Initialize-PMUTestOperation $TestDrive + $operation.RepositoryName = 'ApprovedFeed' + $script:selectedPath = Split-Path -Parent $operation.Plan.InstalledManifestPath + } + It 'preserves the unsupported installation error without consent' { + { Get-NativeSelectedSource $operation $selectedPath $true } | Should -Throw -ErrorId 'PMU.UnsupportedInstallation' + } + It 'uses only the approved target source for an opted-in unmanaged original' { + $operation.Consent.ReplaceUnmanagedInstallation = $true + $source = Get-NativeSelectedSource $operation $selectedPath $true + $source.Name | Should -BeExactly 'ApprovedFeed' + $source.Uri | Should -BeExactly $operation.Plan.RepositoryUri + $source.Unmanaged | Should -BeTrue + } + It 'does not waive metadata for an already installed target' { + $operation.Consent.ReplaceUnmanagedInstallation = $true + { Get-NativeSelectedSource $operation $selectedPath $false } | Should -Throw -ErrorId 'PMU.UnsupportedInstallation' + } + It 'rejects present unreadable metadata even with consent' { + $operation.Consent.ReplaceUnmanagedInstallation = $true + [IO.File]::WriteAllText((Join-Path $selectedPath 'PSGetModuleInfo.xml'), 'not XML') + { Get-NativeSelectedSource $operation $selectedPath $true } | Should -Throw -ErrorId 'PMU.UnsupportedInstallation' + } + It 'retains native metadata identity and repository checks with consent' -ForEach @( + @{ Field = 'InstalledLocation'; Value = 'other'; ErrorId = 'PMU.UnsupportedInstallation' } + @{ Field = 'RepositorySourceLocation'; Value = 'https://other.invalid'; ErrorId = 'PMU.SourceMismatch' } + ) { + $operation.Consent.ReplaceUnmanagedInstallation = $true + $metadata = [pscustomobject]@{ + Name = $operation.Plan.ModuleName; InstalledLocation = $selectedPath + Repository = 'ApprovedFeed'; RepositorySourceLocation = $operation.Plan.RepositoryUri + } + $metadata.$Field = $Value + $metadata | Export-Clixml (Join-Path $selectedPath 'PSGetModuleInfo.xml') + { Get-NativeSelectedSource $operation $selectedPath $true } | Should -Throw -ErrorId $ErrorId + } +} diff --git a/tests/private/provider/Get-ProviderDiscoveryParameter.Tests.ps1 b/tests/private/provider/Get-ProviderDiscoveryParameter.Tests.ps1 new file mode 100644 index 0000000..e2dfd27 --- /dev/null +++ b/tests/private/provider/Get-ProviderDiscoveryParameter.Tests.ps1 @@ -0,0 +1,49 @@ +BeforeAll { + . "$PSScriptRoot/../../TestHelpers/Import-PMUTestSource.ps1" +} +Describe 'Get-ProviderDiscoveryParameter' -Tag 'PMU' { + BeforeEach { + $script:discoveryRequest = @{ + Name = 'FixtureModule' + Repository = 'OwnedFeed' + Version = $null + Prerelease = $true + } + } + It 'preserves the literal discovery query and omits an absent credential' { + $parameters = Get-ProviderDiscoveryParameter $script:discoveryRequest $null + $parameters.Name | Should -BeExactly 'FixtureModule' + $parameters.Repository | Should -BeExactly 'OwnedFeed' + $parameters.Prerelease | Should -BeTrue + $parameters.ContainsKey('Credential') | Should -BeFalse + } + It 'defaults a false or empty requested version to all versions' -ForEach @( + @{ RequestedVersion = $null } + @{ RequestedVersion = '' } + @{ RequestedVersion = $false } + ) { + $script:discoveryRequest.Version = $RequestedVersion + (Get-ProviderDiscoveryParameter $script:discoveryRequest $null).Version | Should -BeExactly '*' + } + It 'preserves an explicit version, declined prereleases and credential identity' { + $script:discoveryRequest.Version = '[1.0.0]' + $script:discoveryRequest.Prerelease = $false + $credential = [pscredential]::new('user', [securestring]::new()) + $parameters = Get-ProviderDiscoveryParameter $script:discoveryRequest $credential + $parameters.Version | Should -BeExactly '[1.0.0]' + $parameters.Prerelease | Should -BeFalse + [object]::ReferenceEquals($parameters.Credential, $credential) | Should -BeTrue + } + It 'returns independent maps with the existing provider diagnostic policy' { + $first = Get-ProviderDiscoveryParameter $script:discoveryRequest $null + $second = Get-ProviderDiscoveryParameter $script:discoveryRequest $null + $first | Should -BeOfType [hashtable] + $first.ErrorAction | Should -BeExactly 'Stop' + $first.WarningAction | Should -BeExactly 'SilentlyContinue' + $first.Verbose | Should -BeFalse + $first.Debug | Should -BeFalse + $first.Name = 'CallerChanged' + $second.Name | Should -BeExactly 'FixtureModule' + [object]::ReferenceEquals($first, $second) | Should -BeFalse + } +} diff --git a/tests/private/provider/Install-ProviderResource.Tests.ps1 b/tests/private/provider/Install-ProviderResource.Tests.ps1 index 8003c29..5d1caa1 100644 --- a/tests/private/provider/Install-ProviderResource.Tests.ps1 +++ b/tests/private/provider/Install-ProviderResource.Tests.ps1 @@ -25,4 +25,46 @@ Describe 'Install-ProviderResource' -Tag 'PMU', 'PMUNativeAdapter' { Mock Update-Module { throw 'disk failure' } { Install-ProviderResource (Initialize-PMUTestOperation $TestDrive) } | Should -Throw -ErrorId 'PMU.InstallationFailed' } + It 'installs an opted-in unmanaged original via the exact provider install path' { + $operation = Initialize-PMUTestOperation $TestDrive + $operation.Consent.ReplaceUnmanagedInstallation = $true + $operation.RepositoryName = 'ApprovedFeed' + Mock Install-Module {} + Mock Update-Module {} + Install-ProviderResource $operation + Should -Invoke Install-Module -Times 1 -ParameterFilter { + $Name -ceq 'FixtureModule' -and $RequiredVersion -ceq '2.0.0-preview.2' -and + $Repository -ceq 'ApprovedFeed' -and $Scope -ceq 'CurrentUser' -and + $AllowPrerelease -and $AcceptLicense -and $Force -and -not $Confirm + } + Should -Invoke Update-Module -Times 0 + } + It 'does not use the install path for a managed original even with consent' { + $operation = Initialize-PMUTestOperation $TestDrive + $operation.Consent.ReplaceUnmanagedInstallation = $true + $path = Split-Path -Parent $operation.Plan.InstalledManifestPath + [IO.File]::WriteAllText((Join-Path $path 'PSGetModuleInfo.xml'), 'present') + Mock Install-Module {} + Mock Update-Module {} + Install-ProviderResource $operation + Should -Invoke Update-Module -Times 1 + Should -Invoke Install-Module -Times 0 + } + It 'installs a different-base unmanaged target without Force' { + $operation = Initialize-PMUTestOperation $TestDrive + $operation.Consent.ReplaceUnmanagedInstallation = $true + $operation.Plan.TargetVersion = '3.0.0-preview1' + $operation.Plan.TargetInstalledPath = Join-Path $TestDrive '3.0.0' + Mock Install-Module {} + Mock Update-Module {} + Install-ProviderResource $operation + Should -Invoke Install-Module -Times 1 -ParameterFilter { $RequiredVersion -ceq '3.0.0-preview1' -and -not $Force } + Should -Invoke Update-Module -Times 0 + } + It 'translates unmanaged provider install failures' { + $operation = Initialize-PMUTestOperation $TestDrive + $operation.Consent.ReplaceUnmanagedInstallation = $true + Mock Install-Module { throw 'disk failure' } + { Install-ProviderResource $operation } | Should -Throw -ErrorId 'PMU.InstallationFailed' + } } diff --git a/tests/private/provider/Test-UnmanagedInstallation.Tests.ps1 b/tests/private/provider/Test-UnmanagedInstallation.Tests.ps1 new file mode 100644 index 0000000..07121d2 --- /dev/null +++ b/tests/private/provider/Test-UnmanagedInstallation.Tests.ps1 @@ -0,0 +1,18 @@ +BeforeAll { . "$PSScriptRoot/../../TestHelpers/Import-PMUTestSource.ps1" } +Describe 'Test-UnmanagedInstallation' -Tag 'PMU', 'PMUUnmanaged' { + BeforeEach { + $operation = Initialize-PMUTestOperation $TestDrive + $script:selectedPath = Split-Path -Parent $operation.Plan.InstalledManifestPath + } + It 'requires explicit consent for the selected original path with no record' { + Test-UnmanagedInstallation $operation $selectedPath | Should -BeFalse + $operation.Consent.ReplaceUnmanagedInstallation = $true + Test-UnmanagedInstallation $operation $selectedPath | Should -BeTrue + Test-UnmanagedInstallation $operation (Join-Path $TestDrive 'other') | Should -BeFalse + } + It 'never classifies a present unreadable record as unmanaged' { + $operation.Consent.ReplaceUnmanagedInstallation = $true + [IO.File]::WriteAllText((Join-Path $selectedPath 'PSGetModuleInfo.xml'), 'not XML') + Test-UnmanagedInstallation $operation $selectedPath | Should -BeFalse + } +} diff --git a/tests/private/staging/Get-ValidatedStagedTree.Tests.ps1 b/tests/private/staging/Get-ValidatedStagedTree.Tests.ps1 new file mode 100644 index 0000000..5988c4d --- /dev/null +++ b/tests/private/staging/Get-ValidatedStagedTree.Tests.ps1 @@ -0,0 +1,12 @@ +BeforeAll { + . "$PSScriptRoot/../../TestHelpers/Import-PMUTestSource.ps1" +} +Describe 'Get-ValidatedStagedTree' -Tag 'PMU', 'PMUTargetManifest' { + It 'returns the validated exact package inventory without importing its throwing root module' { + $operation = Initialize-PMUTestOperation $TestDrive + $null = Initialize-PMUTestPackage $operation.StageRoot $operation.Plan.TargetVersion + $tree = @(Get-ValidatedStagedTree $operation) + $tree.Count | Should -Be 2 + @(Get-Module FixtureModule).Count | Should -Be 0 + } +} diff --git a/tests/private/staging/Initialize-StagedPackage.Tests.ps1 b/tests/private/staging/Initialize-StagedPackage.Tests.ps1 index 6962705..df53a77 100644 --- a/tests/private/staging/Initialize-StagedPackage.Tests.ps1 +++ b/tests/private/staging/Initialize-StagedPackage.Tests.ps1 @@ -44,4 +44,18 @@ Describe 'Initialize-StagedPackage' -Tag 'PMU', 'PMUCoverageFollowUp' { $null = Initialize-StagedPackage $operation Test-Path "$($operation.StageRoot)/leftover.txt" | Should -BeFalse } + + It 'rejects an inspected manifest change before provider installation' -Tag 'PMUTargetManifest' { + $operation = Initialize-PMUTestOperation $TestDrive + $operation.Record | Add-Member InspectedManifestHash ('0' * 64) + Mock Save-ProviderResource { + $null = Initialize-PMUTestPackage $Operation.StageRoot '2.0.0-preview.2' + } + Mock Install-ProviderResource { + } + { + Initialize-StagedPackage $operation + } | Should -Throw -ErrorId 'PMU.TargetManifestChanged' + Should -Invoke Install-ProviderResource -Times 0 + } } diff --git a/tests/public/Get-PSModuleUpdate.Integration.Tests.ps1 b/tests/public/Get-PSModuleUpdate.Integration.Tests.ps1 index 086fe7e..71feccf 100644 --- a/tests/public/Get-PSModuleUpdate.Integration.Tests.ps1 +++ b/tests/public/Get-PSModuleUpdate.Integration.Tests.ps1 @@ -3,8 +3,8 @@ BeforeAll { Import-Module "$root/dist/PSModuleUpdate/PSModuleUpdate.psd1" -Force } Describe 'Get-PSModuleUpdate built surface' -Tag 'Integration', 'PMUHelp' { - It 'exports only the two approved commands and preserves the planning parameter set' { - @(Get-Command -Module PSModuleUpdate).Name | Sort-Object | Should -Be @('Get-PSModuleUpdate', 'Install-PSModuleUpdate') + It 'exports only the approved commands and preserves the planning parameter set' { + @(Get-Command -Module PSModuleUpdate).Name | Sort-Object | Should -Be @('Get-PSModuleUpdate', 'Get-PSModuleUpdateTargetManifest', 'Install-PSModuleUpdate') $command = Get-Command Get-PSModuleUpdate -Module PSModuleUpdate $command.ParameterSets.Name | Sort-Object | Should -Be @('ByModule', 'ByRepositoryUri') $command.Parameters['Module'].ParameterType | Should -Be ([System.Management.Automation.PSModuleInfo]) diff --git a/tests/public/Get-PSModuleUpdate.Tests.ps1 b/tests/public/Get-PSModuleUpdate.Tests.ps1 index 9705ba1..1ab0539 100644 --- a/tests/public/Get-PSModuleUpdate.Tests.ps1 +++ b/tests/public/Get-PSModuleUpdate.Tests.ps1 @@ -1,4 +1,7 @@ -BeforeAll { . "$PSScriptRoot/../TestHelpers/Import-PMUTestSource.ps1" } +BeforeAll { + . "$PSScriptRoot/../TestHelpers/Import-PMUTestSource.ps1" + Import-Module Microsoft.PowerShell.PSResourceGet -RequiredVersion 1.2.0 +} Describe 'Get-PSModuleUpdate' -Tag 'PMU' { It 'supports mutually exclusive name and URI parameter sets with shared policy and credential inputs' { $command = Get-Command Get-PSModuleUpdate @@ -18,4 +21,43 @@ Describe 'Get-PSModuleUpdate' -Tag 'PMU' { $command.Parameters.Keys | Should -Not -Contain 'Scope' $command.Parameters.Keys | Should -Not -Contain 'WhatIf' } + It 'plans an unmanaged installed copy without native metadata requirements' { + $script:repositoryFixture = Initialize-PMURepositoryFixture $TestDrive + Initialize-PMURepositoryMock + Initialize-PMUProviderMock + $path = Split-Path -Parent $repositoryFixture.Module.Path + Test-Path (Join-Path $path 'PSGetModuleInfo.xml') | Should -BeFalse + Mock Read-NativeInstallationRecord { throw 'Planning must not require native metadata.' } + $plan = Get-PSModuleUpdate -Module $repositoryFixture.Module -Repository PublicFixture -Policy @{ Channel = 'IncludePrerelease' } + $plan.InstalledVersion | Should -BeExactly '2.0.0-preview.1' + $plan.TargetVersion | Should -BeExactly '2.0.0-preview.2' + $plan.Scope | Should -BeExactly 'CurrentUser' + Should -Invoke Read-NativeInstallationRecord -Times 0 + } + Context 'missing package public boundary' -Tag 'PMUPackageNotFound' { + BeforeEach { + $script:repositoryFixture = Initialize-PMURepositoryFixture $TestDrive + Initialize-PMURepositoryMock + Mock Find-PSResource { throw (Get-PMUTestProviderFailure $ProviderId) } + Mock Register-UpdatePlan {} + Mock Save-ProviderResource { throw 'Package acquisition must not start.' } + Mock Install-ProviderResource { throw 'Installation must not start.' } + } + It 'terminates without producing or registering a plan for ' -ForEach @( + @{ ProviderId = 'PackageNotFound' } + @{ ProviderId = 'PackageNotFound,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource' } + ) { + $plans = [Collections.Generic.List[object]]::new() + $invoke = { + Get-PSModuleUpdate -Module $script:repositoryFixture.Module -Repository PublicFixture | + ForEach-Object { $plans.Add($_) } + } + $invoke | Should -Throw -ErrorId 'PMU.PackageNotFound' + $plans.Count | Should -Be 0 + Should -Invoke Register-UpdatePlan -Times 0 -Exactly + Should -Invoke Save-ProviderResource -Times 0 -Exactly + Should -Invoke Install-ProviderResource -Times 0 -Exactly + Should -Invoke Find-PSResource -Times 1 -Exactly -ParameterFilter { $ErrorAction -eq 'Stop' -and $Repository[0] -eq 'PublicFixture' } + } + } } diff --git a/tests/public/Get-PSModuleUpdateTargetManifest.Integration.Tests.ps1 b/tests/public/Get-PSModuleUpdateTargetManifest.Integration.Tests.ps1 new file mode 100644 index 0000000..0e02b84 --- /dev/null +++ b/tests/public/Get-PSModuleUpdateTargetManifest.Integration.Tests.ps1 @@ -0,0 +1,28 @@ +# The offline native provider fixture owns its HOME, package feed and install destination. +BeforeAll { + . "$PSScriptRoot/../TestHelpers/Receive-PMUChildProcess.ps1" + . "$PSScriptRoot/../TestHelpers/Invoke-PMULocalProviderProcess.ps1" + $root = Split-Path -Parent (Split-Path -Parent $PSScriptRoot) + $script:modulePath = Join-Path $root 'dist/PSModuleUpdate/PSModuleUpdate.psd1' + Import-Module $modulePath -Force +} +Describe 'Get-PSModuleUpdateTargetManifest built surface' -Tag 'Integration', 'PMUTargetManifestIntegration' { + It 'exports the exact four inputs and safely rejects serialized authorization' { + $command = Get-Command Get-PSModuleUpdateTargetManifest -Module PSModuleUpdate + @($command.Parameters.Keys | Where-Object { + $_ -in @('Plan', 'Credential', 'TrustRepository', 'AcceptLicense') + }).Count | Should -Be 4 + { + Get-PSModuleUpdateTargetManifest -Plan ([pscustomobject]@{ + SchemaVersion = 1 + }) + } | Should -Throw -ErrorId PMU.InvalidPlan + ((Get-Help Get-PSModuleUpdateTargetManifest -Full).Description.Text -join "`n") | Should -Match 'exact planned candidate' + } + It 'inspects an offline exact package, rejects changed MinimumGerberVersion, then installs unchanged content' -Skip:(-not $IsMacOS) { + $fixtureScript = Join-Path $PSScriptRoot '../TestHelpers/Invoke-PMUManifestFixture.ps1' + $result = Invoke-PMULocalProviderProcess (Join-Path $TestDrive 'inspection-provider') $modulePath $fixtureScript + $result.ExitCode | Should -Be 0 -Because $result.Error + $result.Output | Should -Match '"Version":"2.0.0-preview2","Outcome":"Installed"' + } +} diff --git a/tests/public/Get-PSModuleUpdateTargetManifest.Tests.ps1 b/tests/public/Get-PSModuleUpdateTargetManifest.Tests.ps1 new file mode 100644 index 0000000..12865d9 --- /dev/null +++ b/tests/public/Get-PSModuleUpdateTargetManifest.Tests.ps1 @@ -0,0 +1,229 @@ +# Acquisition is mocked; all public plan, consent, identity, staging and cleanup collaborators are real. +BeforeAll { + . "$PSScriptRoot/../TestHelpers/Import-PMUTestSource.ps1" + Import-Module Microsoft.PowerShell.PSResourceGet -RequiredVersion 1.2.0 + function Invoke-ManifestAcquisition { + param($Operation) + throw "An acquisition double is required for $($Operation.Plan.ModuleName)." + } +} +Describe 'Get-PSModuleUpdateTargetManifest' -Tag 'PMU', 'PMUTargetManifest' { + BeforeEach { + $script:repositoryFixture = Initialize-PMURepositoryFixture $TestDrive + $script:inspectionRoot = $null + Initialize-PMUInspectionMock + $script:plan = Get-PSModuleUpdate -Module $repositoryFixture.Module -Repository PublicFixture -Policy @{ + Channel = 'IncludePrerelease' + } + } + It 'exposes the four-parameter API with live plan pipeline binding' { + $command = Get-Command Get-PSModuleUpdateTargetManifest -ErrorAction Stop + $command.Parameters['Plan'].ParameterType | Should -Be ([object]) + $binding = $command.Parameters['Plan'].Attributes | Where-Object { + $_ -is [Management.Automation.ParameterAttribute] + } + $binding.ValueFromPipeline | Should -BeTrue + $command.Parameters.Keys | Should -Not -Contain Force + $command.Parameters.Keys | Should -Not -Contain WhatIf + } + It 'returns exact identity and complete safely imported PrivateData without changing the live plan or installed files' { + $snapshot = ConvertTo-Json $plan -Depth 12 -Compress + $before = @(Get-FileTreeInventory $repositoryFixture.Modules) | ConvertTo-Json -Depth 6 + $result = $plan | Get-PSModuleUpdateTargetManifest + $result.Manifest | Should -BeOfType hashtable + $result.ModuleName | Should -BeExactly $plan.ModuleName + $result.ModuleGuid | Should -Be $plan.ModuleGuid + $result.Version | Should -BeExactly '2.0.0-preview.2' + $result.RepositoryUri | Should -BeExactly $plan.RepositoryUri + $result.Manifest.GUID | Should -Be $plan.ModuleGuid + $result.Manifest.PrivateData.PSData.Prerelease | Should -Be 'preview.2' + $result.Manifest.PrivateData.Gerber.MinimumGerberVersion | Should -Be '7.0.0' + $result.Manifest.PrivateData.Gerber.Extra | Should -Be @('a', 'b') + (ConvertTo-Json $plan -Depth 12 -Compress) | Should -BeExactly $snapshot + (@(Get-FileTreeInventory $repositoryFixture.Modules) | ConvertTo-Json -Depth 6) | Should -BeExactly $before + Test-Path -LiteralPath $inspectionRoot | Should -BeFalse + @(Get-Module -Name $plan.ModuleName).Count | Should -Be 0 + Should -Invoke Install-ProviderResource -Times 0 + } + It 'rejects a plan before acquisition' -ForEach @( + @{ + Kind = 'manufactured' + } + @{ + Kind = 'deserialized' + } + @{ + Kind = 'tampered' + } + @{ + Kind = 'other module instance' + } + ) { + $inputPlan = $plan + switch ($Kind) { + manufactured { + $inputPlan = [pscustomobject]@{ + PSTypeName = 'PSModuleUpdate.UpdatePlan' + } + } + deserialized { + $inputPlan = [Management.Automation.PSSerializer]::Deserialize([Management.Automation.PSSerializer]::Serialize($plan)) + } + tampered { + $inputPlan.TargetVersion = '9.0.0' + } + 'other module instance' { + $script:PmuLivePlans = [Runtime.CompilerServices.ConditionalWeakTable[object, object]]::new() + } + } + { + Get-PSModuleUpdateTargetManifest -Plan $inputPlan + } | Should -Throw -ErrorId 'PMU.InvalidPlan' + Should -Invoke Invoke-ManifestAcquisition -Times 0 + } + It 'rejects a changed repository endpoint before acquisition' { + $repositoryFixture.Repositories.Public.Uri = [uri]'https://different.invalid/v3/index.json' + { + Get-PSModuleUpdateTargetManifest -Plan $plan + } | Should -Throw -ErrorId 'PMU.RepositoryChanged' + Should -Invoke Invoke-ManifestAcquisition -Times 0 + } + It 'rejects a missing exact candidate without selecting latest or downloading' { + Mock Find-ProviderResource { + @() + } + { + Get-PSModuleUpdateTargetManifest -Plan $plan + } | Should -Throw -ErrorId 'PMU.PackageNotFound' + Should -Invoke Invoke-ManifestAcquisition -Times 0 + Should -Invoke Find-ProviderResource -ParameterFilter { + $Request.Version -eq '[2.0.0-preview.2]' -and $Request.Repository -eq 'PublicFixture' + } + } + It 'rejects a stale installed tree before acquisition' { + [IO.File]::AppendAllText((Join-Path $repositoryFixture.Module.ModuleBase "$($plan.ModuleName).psm1"), "`n# changed") + { + Get-PSModuleUpdateTargetManifest -Plan $plan + } | Should -Throw -ErrorId PMU.InstalledStateChanged + Should -Invoke Invoke-ManifestAcquisition -Times 0 + } + It 'rejects package identity without importing it' -ForEach @( + @{ + Kind = 'different GUID' + Pattern = 'a^' + Replacement = '' + ErrorId = 'PMU.GuidMismatch' + } + @{ + Kind = 'different version' + Pattern = "ModuleVersion = '2.0.0'" + Replacement = "ModuleVersion = '3.0.0'" + ErrorId = 'PMU.VerificationFailed' + } + @{ + Kind = 'escaping RootModule' + Pattern = "RootModule = '[^']+'" + Replacement = "RootModule = '../outside.psm1'" + ErrorId = 'PMU.ModuleIdentityMismatch' + } + @{ + Kind = 'executable manifest' + Pattern = "ModuleVersion = '2.0.0'" + Replacement = "ModuleVersion = (throw 'must not execute')" + ErrorId = 'PMU.ModuleIdentityMismatch' + } + ) { + Mock Save-ProviderResource { + $guid = $Operation.Plan.ModuleGuid + if ($Kind -eq 'different GUID') { + $guid = [guid]::NewGuid() + } + $path = Initialize-PMUTestPackage $Operation.StageRoot $Operation.Plan.TargetVersion $guid $Operation.Plan.ModuleName + $manifest = Join-Path $path "$($Operation.Plan.ModuleName).psd1" + [IO.File]::WriteAllText($manifest, ([IO.File]::ReadAllText($manifest) -replace $Pattern, $Replacement)) + } + { + Get-PSModuleUpdateTargetManifest -Plan $plan + } | Should -Throw -ErrorId $ErrorId + @(Get-Module -Name $plan.ModuleName).Count | Should -Be 0 + Should -Invoke Install-ProviderResource -Times 0 + } + It 'requires independent repository trust before acquisition' { + $plan = Get-PSModuleUpdate -Module $repositoryFixture.Module -Repository PrivateFixture -Policy @{ + Channel = 'IncludePrerelease' + } + { + Get-PSModuleUpdateTargetManifest -Plan $plan + } | Should -Throw -ErrorId 'PMU.RepositoryTrustRequired' + $result = Get-PSModuleUpdateTargetManifest -Plan $plan -TrustRepository + $result.Version | Should -Be $plan.TargetVersion + $repositoryFixture.Repositories.Private.Trusted | Should -BeFalse + } + It 'rechecks license prerequisites without treating inspection as acceptance' { + Mock Find-ProviderResource { + [pscustomobject]@{ + Name = $Request.Name + Version = [version]'2.0.0' + Prerelease = 'preview.2' + AdditionalMetadata = @{ + RequireLicenseAcceptance = 'true' + } + Dependencies = @() + } + } + { + Get-PSModuleUpdateTargetManifest -Plan $plan + } | Should -Throw -ErrorId 'PMU.LicenseAcceptanceRequired' + (Get-PSModuleUpdateTargetManifest -Plan $plan -AcceptLicense).Version | Should -Be $plan.TargetVersion + { + Install-PSModuleUpdate -Update $plan -Confirm:$false + } | Should -Throw -ErrorId 'PMU.LicenseAcceptanceRequired' + } + It 'requires credentials per call without retaining or returning them' { + $credential = [pscredential]::new('private-fixture-user', [securestring]::new()) + $plan = Get-PSModuleUpdate -Module $repositoryFixture.Module -Repository PublicFixture -Credential $credential -Policy @{ + Channel = 'IncludePrerelease' + } + { + Get-PSModuleUpdateTargetManifest -Plan $plan + } | Should -Throw -ErrorId 'PMU.AuthenticationFailed' + $result = Get-PSModuleUpdateTargetManifest -Plan $plan -Credential $credential + (ConvertTo-Json $result -Depth 12) | Should -Not -Match 'fixture-secret|private-fixture-user|Credential' + (ConvertTo-Json (Test-UpdatePlan $plan) -Depth 12 -WarningAction SilentlyContinue) | Should -Not -Match 'fixture-secret|private-fixture-user' + Should -Invoke Find-ProviderResource -ParameterFilter { + [object]::ReferenceEquals($Credential, $credential) -and $Request.Version -eq '[2.0.0-preview.2]' + } + } + It 'cleans the owned workspace and redacts provider errors on acquisition failure' { + Mock Save-ProviderResource { + throw [InvalidOperationException]::new('provider fixture-secret private-fixture-user') + } + $failure = { + Get-PSModuleUpdateTargetManifest -Plan $plan + } + $failure | Should -Throw -ErrorId 'PMU.InstallationFailed' -ExpectedMessage '*diagnostics were withheld*' + @(Get-ChildItem $repositoryFixture.Data -Directory -Filter 'inspection-*').Count | Should -Be 0 + Should -Invoke Install-ProviderResource -Times 0 + } + It 'rejects a changed same-version manifest before install mutation even when the returned DTO was edited' { + $result = Get-PSModuleUpdateTargetManifest -Plan $plan + $result.Manifest.PrivateData.Gerber.MinimumGerberVersion = '0.0.0' + Mock Save-ProviderResource { + $null = Initialize-PMUTestPackage $Operation.StageRoot $Operation.Plan.TargetVersion $Operation.Plan.ModuleGuid $Operation.Plan.ModuleName + } + { + Install-PSModuleUpdate -Update $plan -Confirm:$false + } | Should -Throw -ErrorId 'PMU.TargetManifestChanged' + Should -Invoke Install-ProviderResource -Times 0 + (Get-ManifestIdentity $plan.InstalledManifestPath).Version.FullVersion | Should -Be '2.0.0-preview.1' + } + It 'installs an unchanged inspected package and keeps planning and WhatIf acquisition-free' { + Should -Invoke Save-ProviderResource -Times 0 + $null = Install-PSModuleUpdate -Update $plan -WhatIf + Should -Invoke Save-ProviderResource -Times 0 + $null = Get-PSModuleUpdateTargetManifest -Plan $plan + $result = Install-PSModuleUpdate -Update $plan -Confirm:$false + $result.InstalledVersion | Should -Be '2.0.0-preview.2' + $result.VerificationStatus | Should -Be Verified + } +} diff --git a/tests/public/Install-PSModuleUpdate.Integration.Tests.ps1 b/tests/public/Install-PSModuleUpdate.Integration.Tests.ps1 index 314be44..b1de16e 100644 --- a/tests/public/Install-PSModuleUpdate.Integration.Tests.ps1 +++ b/tests/public/Install-PSModuleUpdate.Integration.Tests.ps1 @@ -14,4 +14,11 @@ Describe 'Install-PSModuleUpdate built surface' -Tag 'Integration', 'PMUHelp' { $parameter = (Get-Help Install-PSModuleUpdate -Full).Parameters.Parameter | Where-Object Name -eq AcceptLicense ($parameter.Description.Text -join "`n") | Should -Match 'does not disclose' } + It 'exports the unmanaged opt-in and loads its generated external help' { + $command = Get-Command Install-PSModuleUpdate -Module PSModuleUpdate + $command.Parameters['ReplaceUnmanagedInstallation'].ParameterType | Should -Be ([switch]) + $parameter = (Get-Help Install-PSModuleUpdate -Full).Parameters.Parameter | Where-Object Name -eq ReplaceUnmanagedInstallation + ($parameter.Description.Text -join "`n") | Should -Match 'absent' + ($parameter.Description.Text -join "`n") | Should -Match 'unreadable' + } } diff --git a/tests/public/Install-PSModuleUpdate.Tests.ps1 b/tests/public/Install-PSModuleUpdate.Tests.ps1 index 3fe08e9..02a296c 100644 --- a/tests/public/Install-PSModuleUpdate.Tests.ps1 +++ b/tests/public/Install-PSModuleUpdate.Tests.ps1 @@ -19,4 +19,20 @@ Describe 'Install-PSModuleUpdate' -Tag 'PMU' { $binding.ValueFromPipeline | Should -BeTrue $binding.ValueFromPipelineByPropertyName | Should -BeFalse } + It 'forwards explicit unmanaged replacement consent without bypassing WhatIf' { + $operation = Initialize-PMUTestOperation $TestDrive + Mock Initialize-InstallationRequest { $script:requestedConsent = $Consent; $operation } + Mock Invoke-UpdateInstallation {} + $operation.Plan | Install-PSModuleUpdate -ReplaceUnmanagedInstallation -WhatIf + $requestedConsent.ReplaceUnmanagedInstallation | Should -BeTrue + Should -Invoke Invoke-UpdateInstallation -Times 0 + } + It 'leaves unmanaged replacement consent off by default' { + $operation = Initialize-PMUTestOperation $TestDrive + Mock Initialize-InstallationRequest { $script:requestedConsent = $Consent; $operation } + Mock Invoke-UpdateInstallation {} + $operation.Plan | Install-PSModuleUpdate -Confirm:$false + $requestedConsent.ReplaceUnmanagedInstallation | Should -BeFalse + Should -Invoke Invoke-UpdateInstallation -Times 1 + } } diff --git a/tests/scripts/build/ci/CiTestDetail.Tests.ps1 b/tests/scripts/build/ci/CiTestDetail.Tests.ps1 index bc8268d..e8c592c 100644 --- a/tests/scripts/build/ci/CiTestDetail.Tests.ps1 +++ b/tests/scripts/build/ci/CiTestDetail.Tests.ps1 @@ -45,4 +45,40 @@ Describe 'Nova detailed output evidence' -Tag 'BuildTooling' { }) { Assert-CiTestDetail -Summary $summary -Detail $detail -OperatingSystem 'macOS' } | Should -Throw '*skip*' } + + Context 'Exact-target inspection native fixture' { + BeforeEach { + $script:skipSummary = @{ + Total = 1 + Passed = 0 + Failed = 0 + Skipped = 1 + } + $script:skipDetail = @(@{ + File = 'tests/public/Get-PSModuleUpdateTargetManifest.Integration.Tests.ps1' + Name = 'inspects an offline exact package, rejects changed MinimumGerberVersion, then installs unchanged content' + Result = 'Skipped' + }) + } + + It 'accepts the classified native-fixture skip on <_>' -ForEach @('Windows', 'Linux') { + $operatingSystem = $_ + { + Assert-CiTestDetail -Summary $script:skipSummary -Detail $script:skipDetail -OperatingSystem $operatingSystem + } | Should -Not -Throw + } + + It 'rejects the same skip on the qualified macOS platform' { + { + Assert-CiTestDetail -Summary $script:skipSummary -Detail $script:skipDetail -OperatingSystem 'macOS' + } | Should -Throw '*Unexpected skip*' + } + + It 'rejects a different <_> identity even on an excluded platform' -ForEach @('File', 'Name') { + $script:skipDetail[0][$_] = 'unclassified' + { + Assert-CiTestDetail -Summary $script:skipSummary -Detail $script:skipDetail -OperatingSystem 'Windows' + } | Should -Throw '*Unexpected skip*' + } + } } From 2134f252c6201a51e39d9b23c05504769c25f7fa Mon Sep 17 00:00:00 2001 From: Stiwi Gabriel Courage Date: Sun, 15 Nov 2026 21:06:04 +0100 Subject: [PATCH 3/9] feat: Migrate to shared workflows and enhance CI processes - Implement shared `powershell-ci` workflows for contributor tests, security checks, and publishing. - Update `Run-Platform-Matrix.yml` to manage platform-specific CI lanes. - Remove legacy scripts for CodeScene analysis and NovaModuleTools CI. - Introduce `Security.yml` for unified security checks and dependency reviews. - Add `dependabot.yml` for automated dependency updates on a weekly schedule. - Enhance documentation on security models and workflow maps. - Update tests to validate new workflow structures and shared contracts. --- .github/actions/check-coverage/action.yml | 49 ----- .../actions/create-annotated-tag/action.yml | 68 ------- .../actions/create-verified-commit/action.yml | 134 ------------- .../ensure-psresource-repository/action.yml | 26 --- .github/actions/update-git-ref/action.yml | 39 ---- .github/dependabot.yml | 12 ++ .../repository-conventions.instructions.md | 2 +- .github/skills/codescene-quality/SKILL.md | 5 +- .github/workflows/Publish.yml | 177 +----------------- .../{ci.yml => Run-Platform-Matrix.yml} | 2 +- .github/workflows/Security.yml | 37 ++++ .github/workflows/Tests.yml | 166 +--------------- .github/workflows/codeql.yml | 99 ---------- .github/workflows/dependency-review.yml | 39 ---- .github/workflows/powershell.yml | 49 ----- CHANGELOG.md | 11 ++ CONTRIBUTING.md | 40 +++- README.md | 21 +++ RELEASE_NOTE.md | 6 + docs/architecture/G4A4/SECURITY_MODEL.md | 36 ++++ docs/architecture/G4A4/WORKFLOW_MAP.md | 44 ++++- docs/architecture/TESTING.md | 4 +- scripts/build/ci/Invoke-CodeSceneAnalysis.ps1 | 150 --------------- scripts/build/ci/Invoke-NovaModuleToolsCI.ps1 | 89 --------- .../ci/Repair-CodeSceneJaCoCoCoverage.ps1 | 64 ------- tests/repository/CiWorkflow.Tests.ps1 | 12 +- .../repository/RunTestsDependencies.Tests.ps1 | 121 ------------ tests/repository/SharedCiContracts.Tests.ps1 | 73 ++++++++ .../ci/Invoke-NovaModuleToolsCI.Tests.ps1 | 69 ------- 29 files changed, 301 insertions(+), 1343 deletions(-) delete mode 100644 .github/actions/check-coverage/action.yml delete mode 100644 .github/actions/create-annotated-tag/action.yml delete mode 100644 .github/actions/create-verified-commit/action.yml delete mode 100644 .github/actions/ensure-psresource-repository/action.yml delete mode 100644 .github/actions/update-git-ref/action.yml create mode 100644 .github/dependabot.yml rename .github/workflows/{ci.yml => Run-Platform-Matrix.yml} (99%) create mode 100644 .github/workflows/Security.yml delete mode 100644 .github/workflows/codeql.yml delete mode 100644 .github/workflows/dependency-review.yml delete mode 100644 .github/workflows/powershell.yml delete mode 100644 scripts/build/ci/Invoke-CodeSceneAnalysis.ps1 delete mode 100644 scripts/build/ci/Invoke-NovaModuleToolsCI.ps1 delete mode 100644 scripts/build/ci/Repair-CodeSceneJaCoCoCoverage.ps1 delete mode 100644 tests/repository/RunTestsDependencies.Tests.ps1 create mode 100644 tests/repository/SharedCiContracts.Tests.ps1 delete mode 100644 tests/scripts/build/ci/Invoke-NovaModuleToolsCI.Tests.ps1 diff --git a/.github/actions/check-coverage/action.yml b/.github/actions/check-coverage/action.yml deleted file mode 100644 index f34f3e3..0000000 --- a/.github/actions/check-coverage/action.yml +++ /dev/null @@ -1,49 +0,0 @@ -name: Check Coverage -description: Run CodeScene coverage gates against uploaded coverage artifacts. - -inputs: - access-token: - description: CodeScene REST API access token. - required: true - project-url: - description: Full CodeScene project API URL, for example https://codescene.io/v2/projects/12345. - required: true - coverage-files: - description: Glob pattern matching coverage reports to check. - required: true - -runs: - using: composite - steps: - - name: Download cs-coverage binary - shell: bash - run: | - set -euo pipefail - curl -fsSL -o "$(pwd)/cs-coverage.zip" https://downloads.codescene.io/enterprise/cli/cs-coverage-linux-amd64-latest.zip - unzip -oq "$(pwd)/cs-coverage.zip" - chmod +x "$(pwd)/cs-coverage" - - - name: Normalize JaCoCo coverage paths - shell: bash - run: | - set -euo pipefail - shopt -s globstar nullglob - files=( ${{ inputs.coverage-files }} ) - if [ ${#files[@]} -eq 0 ]; then - echo "No coverage files matched '${{ inputs.coverage-files }}' for normalization." - exit 0 - fi - - for file in "${files[@]}"; do - pwsh -NoLogo -NoProfile -File ./scripts/build/ci/Repair-CodeSceneJaCoCoCoverage.ps1 -Path "$file" - done - - - name: Run CodeScene coverage gate check - shell: bash - env: - CS_PROJECT_URL: ${{ inputs.project-url }} - CS_ACCESS_TOKEN: ${{ inputs.access-token }} - run: | - set -euo pipefail - find "$(pwd)" -name 'coverage.xml' -print - "$(pwd)/cs-coverage" check --verbose --coverage-files "${{ inputs.coverage-files }}" diff --git a/.github/actions/create-annotated-tag/action.yml b/.github/actions/create-annotated-tag/action.yml deleted file mode 100644 index da1a3b3..0000000 --- a/.github/actions/create-annotated-tag/action.yml +++ /dev/null @@ -1,68 +0,0 @@ -name: Create annotated tag -description: Create an annotated git tag for a commit SHA. - -inputs: - tag-name: - description: Tag name to create. - required: true - target-sha: - description: Commit SHA that the tag should reference. - required: true - message: - description: Annotated tag message. - required: true - -outputs: - tag-object-sha: - description: SHA of the created tag object. - value: ${{ steps.create.outputs.tag-object-sha }} - -runs: - using: composite - steps: - - id: create - uses: actions/github-script@v7 - env: - TAG_NAME: ${{ inputs.tag-name }} - TARGET_SHA: ${{ inputs.target-sha }} - TAG_MESSAGE: ${{ inputs.message }} - with: - script: | - const owner = context.repo.owner - const repo = context.repo.repo - const tagName = process.env.TAG_NAME - const targetSha = process.env.TARGET_SHA - const message = process.env.TAG_MESSAGE - - try { - await github.rest.git.getRef({ - owner, - repo, - ref: `tags/${tagName}` - }) - - core.setFailed(`Tag '${tagName}' already exists.`) - return - } catch (error) { - if (error.status !== 404) { - throw error - } - } - - const tagObject = await github.rest.git.createTag({ - owner, - repo, - tag: tagName, - message, - object: targetSha, - type: 'commit' - }) - - await github.rest.git.createRef({ - owner, - repo, - ref: `refs/tags/${tagName}`, - sha: tagObject.data.sha - }) - - core.setOutput('tag-object-sha', tagObject.data.sha) diff --git a/.github/actions/create-verified-commit/action.yml b/.github/actions/create-verified-commit/action.yml deleted file mode 100644 index ad75344..0000000 --- a/.github/actions/create-verified-commit/action.yml +++ /dev/null @@ -1,134 +0,0 @@ -name: Create verified commit -description: Create a GitHub-verified commit from local workspace changes. - -inputs: - base-ref: - description: Branch name or refs/heads reference used as the commit parent and base tree. - required: true - commit-message: - description: Commit message for the new commit. - required: true - -outputs: - has-changes: - description: Whether there were local changes to commit. - value: ${{ steps.create.outputs.has-changes }} - commit-sha: - description: SHA of the created commit. - value: ${{ steps.create.outputs.commit-sha }} - parent-sha: - description: SHA of the parent commit used for the new commit. - value: ${{ steps.create.outputs.parent-sha }} - -runs: - using: composite - steps: - - id: create - uses: actions/github-script@v7 - env: - BASE_REF: ${{ inputs.base-ref }} - COMMIT_MESSAGE: ${{ inputs.commit-message }} - with: - script: | - const fs = require('fs') - const { execSync } = require('child_process') - - const owner = context.repo.owner - const repo = context.repo.repo - const baseRefInput = process.env.BASE_REF - const baseRef = baseRefInput.replace(/^refs\/heads\//, '') - const commitMessage = process.env.COMMIT_MESSAGE - - const statusLines = execSync('git status --porcelain=v1 --untracked-files=all', { - encoding: 'utf-8' - }) - .split('\n') - .filter(Boolean) - - if (statusLines.length === 0) { - core.info('No changes to commit.') - core.setOutput('has-changes', 'false') - return - } - - const baseRefResponse = await github.rest.git.getRef({ - owner, - repo, - ref: `heads/${baseRef}` - }) - - const parentSha = baseRefResponse.data.object.sha - const baseCommit = await github.rest.git.getCommit({ - owner, - repo, - commit_sha: parentSha - }) - - async function createBlobEntry(filePath) { - const content = fs.readFileSync(filePath, 'utf8') - const blob = await github.rest.git.createBlob({ - owner, - repo, - content, - encoding: 'utf-8' - }) - - return { - path: filePath, - mode: '100644', - type: 'blob', - sha: blob.data.sha - } - } - - const tree = [] - - for (const line of statusLines) { - const status = line.slice(0, 2) - const rawPath = line.slice(3) - - if (status.includes('R') && rawPath.includes(' -> ')) { - const [oldPath, newPath] = rawPath.split(' -> ') - - tree.push({ - path: oldPath, - mode: '100644', - type: 'blob', - sha: null - }) - - tree.push(await createBlobEntry(newPath)) - continue - } - - if (status.includes('D')) { - tree.push({ - path: rawPath, - mode: '100644', - type: 'blob', - sha: null - }) - continue - } - - tree.push(await createBlobEntry(rawPath)) - } - - const newTree = await github.rest.git.createTree({ - owner, - repo, - base_tree: baseCommit.data.tree.sha, - tree - }) - - const newCommit = await github.rest.git.createCommit({ - owner, - repo, - message: commitMessage, - tree: newTree.data.sha, - parents: [parentSha] - }) - - core.setOutput('has-changes', 'true') - core.setOutput('commit-sha', newCommit.data.sha) - core.setOutput('parent-sha', parentSha) diff --git a/.github/actions/ensure-psresource-repository/action.yml b/.github/actions/ensure-psresource-repository/action.yml deleted file mode 100644 index 416bc04..0000000 --- a/.github/actions/ensure-psresource-repository/action.yml +++ /dev/null @@ -1,26 +0,0 @@ -name: Ensure PSResource repository -description: Ensure the local PSResourceGet store exists and the requested repository is registered. - -inputs: - repository-name: - description: PSResource repository name to ensure. - required: false - default: PSGallery - -runs: - using: composite - steps: - - shell: pwsh - run: | - $repositoryName = '${{ inputs.repository-name }}' - $psResourcePath = Join-Path $HOME '.local/share/PSResourceGet' - New-Item -ItemType Directory -Path $psResourcePath -Force | Out-Null - - if (-not (Get-PSResourceRepository -Name $repositoryName -ErrorAction SilentlyContinue)) { - if ($repositoryName -eq 'PSGallery') { - Register-PSResourceRepository -PSGallery - } - else { - throw "PSResource repository '$repositoryName' is not registered." - } - } diff --git a/.github/actions/update-git-ref/action.yml b/.github/actions/update-git-ref/action.yml deleted file mode 100644 index 6eb2843..0000000 --- a/.github/actions/update-git-ref/action.yml +++ /dev/null @@ -1,39 +0,0 @@ -name: Update git ref -description: Update an existing branch ref to a specific SHA. - -inputs: - ref: - description: Full git ref, for example refs/heads/main. - required: true - sha: - description: Commit SHA the ref should point to. - required: true - force: - description: Whether to force-update the ref. - required: false - default: 'false' - -runs: - using: composite - steps: - - uses: actions/github-script@v7 - env: - TARGET_REF: ${{ inputs.ref }} - TARGET_SHA: ${{ inputs.sha }} - FORCE_UPDATE: ${{ inputs.force }} - with: - script: | - const owner = context.repo.owner - const repo = context.repo.repo - const refInput = process.env.TARGET_REF - const ref = refInput.replace(/^refs\//, '') - const sha = process.env.TARGET_SHA - const force = process.env.FORCE_UPDATE === 'true' - - await github.rest.git.updateRef({ - owner, - repo, - ref, - sha, - force - }) diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..459f2b2 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,12 @@ +version: 2 +updates: + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + commit-message: + prefix: chore + groups: + powershell-ci: + patterns: + - "stiwicourage/powershell-ci*" diff --git a/.github/instructions/repository-conventions.instructions.md b/.github/instructions/repository-conventions.instructions.md index 2de1dca..22e81af 100644 --- a/.github/instructions/repository-conventions.instructions.md +++ b/.github/instructions/repository-conventions.instructions.md @@ -55,7 +55,7 @@ If the only files changed are `.md` files and none of those files contain embedd - Inspect every required hosted job and the aggregate gate for the exact revision and run attempt before claiming CI or PR readiness. An earlier revision's green run, a green quality job or four passing lanes cannot qualify a failing six-lane matrix. Uncommitted fixes remain pending hosted verification; a local handoff must say so. - Trace failures to the first failing assertion or provisioning step before changing code. Keep regression assertions and thresholds intact; do not skip Windows tests, weaken comparisons, retry until green without diagnosis, or treat downstream missing-phase/artifact errors as the primary defect. -For PSModuleUpdate, `.github/workflows/ci.yml` and `scripts/build/ci/CiLanes.json` +For PSModuleUpdate, `.github/workflows/Run-Platform-Matrix.yml` and `scripts/build/ci/CiLanes.json` define six required platform/runtime lanes. Reproduce applicable local lanes with the absolute selected PowerShell executable and `./scripts/build/ci/Invoke-PlatformLane.ps1 -LaneId ` on a matching host. diff --git a/.github/skills/codescene-quality/SKILL.md b/.github/skills/codescene-quality/SKILL.md index d059b7e..fcd6f50 100644 --- a/.github/skills/codescene-quality/SKILL.md +++ b/.github/skills/codescene-quality/SKILL.md @@ -18,8 +18,9 @@ Use the narrower sibling skills when the task is more specific: - `tests/ArchitectureGuardrails.Tests.ps1` - `tests/*TestSupport.ps1` -- `.github/actions/check-coverage/action.yml` -- `scripts/build/ci/Invoke-NovaModuleToolsCI.ps1` +- `.github/workflows/Tests.yml` (shared test/coverage caller) +- `powershell-ci/actions/check-coverage/action.yml` (upstream coverage gate) +- `powershell-ci/actions/nova-test/Invoke-NovaTestCI.ps1` (upstream Nova orchestration) - CodeScene review / safeguard tooling ## Expected practices diff --git a/.github/workflows/Publish.yml b/.github/workflows/Publish.yml index cd73564..1b6c404 100644 --- a/.github/workflows/Publish.yml +++ b/.github/workflows/Publish.yml @@ -1,180 +1,21 @@ -name: Publish module +name: Publish Module on: push: branches: - main - workflow_dispatch: permissions: contents: write actions: write -defaults: - run: - shell: pwsh - jobs: - Publish: - if: >- - ${{ - github.event_name != 'push' || - !startsWith(github.event.head_commit.message || '', 'chore(release): ') - }} - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - - name: Install required modules from PSGallery - id: modules - run: ./scripts/build/ci/Install-CiPowerShellModules.ps1 - - - name: Expose isolated modules to later steps - env: - CI_MODULE_ROOT: ${{ steps.modules.outputs.moduleRoot }} - run: | - . ./scripts/build/ci/CiDependencyRoot.ps1 - "PSModulePath=$(Get-CiIsolatedModulePath -ModuleRoot $env:CI_MODULE_ROOT)" >> $env:GITHUB_ENV - - - name: Build Module - run: Invoke-NovaBuild -ContinuousIntegration - - - name: Run Pester Tests - run: Test-NovaBuild - - - name: Generate Report - continue-on-error: true - run: | - $reportLines = @('## Output Files', '') - $files = Get-ChildItem -Path ./dist -Recurse -ErrorAction SilentlyContinue | Sort-Object FullName - - if ($files) { - $reportLines += '| Name | Directory |' - $reportLines += '| --- | --- |' - $reportLines += $files | ForEach-Object { - $name = ('' + $_.Name).Replace('|', '\|') - $directory = ('' + $_.Directory).Replace('|', '\|') - "| $name | $directory |" - } - } - else { - $reportLines += 'No files found in `./dist`.' - } - - $report = $reportLines -join [Environment]::NewLine - Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY -Value $report - Write-Output $report - - - name: Ensure PSGallery repository registration - if: github.ref_name == 'main' - uses: ./.github/actions/ensure-psresource-repository - - - name: Run release with NovaRelease - id: semantic_release - if: github.ref_name == 'main' - run: | - Invoke-NovaRelease -Repository PSGallery -ApiKey $env:PSGALLERY_API -SkipTests -ContinuousIntegration - $version = Get-NovaProjectInfo -Version - $result = Move-UnreleasedChangelog -Version $version - - "release_version=$version" >> $env:GITHUB_OUTPUT - - $delimiter = [guid]::NewGuid().Guid - "tag_message<<$delimiter" >> $env:GITHUB_OUTPUT - $result.TagMessageText >> $env:GITHUB_OUTPUT - "$delimiter" >> $env:GITHUB_OUTPUT - env: - PSGALLERY_API: ${{ secrets.PSGALLERY_API }} - - - name: Create verified release commit - id: commit_release - if: github.ref_name == 'main' - uses: ./.github/actions/create-verified-commit - with: - base-ref: main - commit-message: 'chore(release): ${{ steps.semantic_release.outputs.release_version }}' - - - name: Push verified release commit - if: github.ref_name == 'main' && steps.commit_release.outputs.has-changes == 'true' - uses: ./.github/actions/update-git-ref - with: - ref: refs/heads/main - sha: ${{ steps.commit_release.outputs.commit-sha }} - - - name: Create annotated release tag - if: github.ref_name == 'main' && steps.commit_release.outputs.has-changes == 'true' - uses: ./.github/actions/create-annotated-tag - with: - tag-name: ${{ steps.semantic_release.outputs.release_version }} - target-sha: ${{ steps.commit_release.outputs.commit-sha }} - message: ${{ steps.semantic_release.outputs.tag_message }} - - - name: Prepare next prerelease version on main -> develop - if: github.ref_name == 'main' && steps.commit_release.outputs.has-changes == 'true' - run: | - git fetch origin main - git fetch origin develop - - git checkout develop - git reset --hard origin/main - - Update-NovaModuleVersion -Preview -ContinuousIntegration - - - name: Create verified develop prerelease commit - id: commit_develop_from_main - if: github.ref_name == 'main' && steps.commit_release.outputs.has-changes == 'true' - uses: ./.github/actions/create-verified-commit - with: - base-ref: main - commit-message: 'chore: prepare develop for next prerelease' - - - name: Push verified develop prerelease commit - if: github.ref_name == 'main' && steps.commit_develop_from_main.outputs.has-changes == 'true' - uses: ./.github/actions/update-git-ref - with: - ref: refs/heads/develop - sha: ${{ steps.commit_develop_from_main.outputs.commit-sha }} - force: 'true' - - - name: Prepare next prerelease version on develop - if: github.ref_name == 'develop' - run: | - $ErrorActionPreference = 'Stop' - - git fetch origin develop - git checkout develop - - - name: Ensure PSGallery repository registration - if: github.ref_name == 'develop' - uses: ./.github/actions/ensure-psresource-repository - - - name: Publish develop prerelease to PSGallery - if: github.ref_name == 'develop' - run: | - Publish-NovaModule -Repository PSGallery -ApiKey $env:PSGALLERY_API -SkipTests -ContinuousIntegration - env: - PSGALLERY_API: ${{ secrets.PSGALLERY_API }} - - - name: Bump next prerelease version on develop - if: github.ref_name == 'develop' - run: | - Update-NovaModuleVersion -Preview -ContinuousIntegration - - - name: Create verified develop commit - id: commit_develop - if: github.ref_name == 'develop' - uses: ./.github/actions/create-verified-commit - with: - base-ref: develop - commit-message: 'chore: prepare next prerelease version' - - - name: Push verified develop commit - if: github.ref_name == 'develop' && steps.commit_develop.outputs.has-changes == 'true' - uses: ./.github/actions/update-git-ref - with: - ref: refs/heads/develop - sha: ${{ steps.commit_develop.outputs.commit-sha }} + publish: + uses: stiwicourage/powershell-ci/.github/workflows/publish.yml@develop + with: + dependency-mode: isolated + pester-required-version: '5.7.1' + test-command: Test-NovaBuild + release-continuous-integration: true + secrets: inherit diff --git a/.github/workflows/ci.yml b/.github/workflows/Run-Platform-Matrix.yml similarity index 99% rename from .github/workflows/ci.yml rename to .github/workflows/Run-Platform-Matrix.yml index 5179272..6549d60 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/Run-Platform-Matrix.yml @@ -1,4 +1,4 @@ -name: Test platform matrix +name: Run platform matrix on: push: diff --git a/.github/workflows/Security.yml b/.github/workflows/Security.yml new file mode 100644 index 0000000..21a6be9 --- /dev/null +++ b/.github/workflows/Security.yml @@ -0,0 +1,37 @@ +name: Security + +on: + push: + branches: + - develop + pull_request: + branches: + - develop + schedule: + - cron: '34 3 * * 1' + +permissions: + contents: read + +jobs: + codeql: + uses: stiwicourage/powershell-ci/.github/workflows/codeql.yml@develop + permissions: + security-events: write + packages: read + actions: read + contents: read + + analyzer: + uses: stiwicourage/powershell-ci/.github/workflows/powershell-analyzer.yml@develop + permissions: + security-events: write + actions: read + contents: read + + dependency-review: + if: ${{ github.event_name == 'pull_request' }} + uses: stiwicourage/powershell-ci/.github/workflows/dependency-review.yml@develop + permissions: + contents: read + pull-requests: write diff --git a/.github/workflows/Tests.yml b/.github/workflows/Tests.yml index 7ae469b..0ebd3be 100644 --- a/.github/workflows/Tests.yml +++ b/.github/workflows/Tests.yml @@ -1,4 +1,4 @@ -name: Test module +name: Run Tests on: push: @@ -16,160 +16,12 @@ permissions: contents: read actions: read -defaults: - run: - shell: pwsh - jobs: - test-and-coverage: - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v4 - - - name: Install required CI PowerShell modules - id: modules - run: ./scripts/build/ci/Install-CiPowerShellModules.ps1 - - - name: Run NovaModuleTools CI test and coverage workflow - env: - CI_MODULE_ROOT: ${{ steps.modules.outputs.moduleRoot }} - run: | - . ./scripts/build/ci/CiDependencyRoot.ps1 - $env:PSModulePath = Get-CiIsolatedModulePath -ModuleRoot $env:CI_MODULE_ROOT - ./scripts/build/ci/Invoke-NovaModuleToolsCI.ps1 -OutputDirectory ./artifacts - - - name: Validate repository changelog with Test-KeepAChangelogFile - env: - CI_MODULE_ROOT: ${{ steps.modules.outputs.moduleRoot }} - run: | - . ./scripts/build/ci/CiDependencyRoot.ps1 - $env:PSModulePath = Get-CiIsolatedModulePath -ModuleRoot $env:CI_MODULE_ROOT - Import-Module NovaModuleTools -ErrorAction Stop - $result = Test-KeepAChangelogFile -Path ./CHANGELOG.md - if (-not $result.IsValid) { - throw ($result.Errors -join [Environment]::NewLine) - } - - - name: Clean owned CI dependencies - if: ${{ always() && steps.modules.outputs.moduleRoot != '' }} - env: - CI_MODULE_ROOT: ${{ steps.modules.outputs.moduleRoot }} - run: | - . ./scripts/build/ci/CiDependencyRoot.ps1 - Remove-CiDependencyRoot -Owner (Get-CiDependencyOwner -Path $env:CI_MODULE_ROOT) - - - name: Upload CI artifacts - if: always() - uses: actions/upload-artifact@v4 - with: - name: nova-ci-artifacts - if-no-files-found: warn - path: | - artifacts/ - dist/ - - - name: Generate Report - if: always() - run: | - $reportLines = @( - '## CI Output Files', - '', - '### artifacts/', - '' - ) - - $artifactFiles = Get-ChildItem -Path ./artifacts -Recurse -File -ErrorAction SilentlyContinue | Sort-Object FullName - if ($artifactFiles) { - $reportLines += '| Name | Directory |' - $reportLines += '| --- | --- |' - $reportLines += $artifactFiles | ForEach-Object { - $name = ('' + $_.Name).Replace('|', '\|') - $directory = ('' + $_.Directory).Replace('|', '\|') - "| $name | $directory |" - } - } - else { - $reportLines += 'No files found in `./artifacts`.' - } - - $reportLines += @('', '### dist/', '') - $files = Get-ChildItem -Path ./dist -Recurse -ErrorAction SilentlyContinue | Sort-Object FullName - - if ($files) { - $reportLines += '| Name | Directory |' - $reportLines += '| --- | --- |' - $reportLines += $files | ForEach-Object { - $name = ('' + $_.Name).Replace('|', '\|') - $directory = ('' + $_.Directory).Replace('|', '\|') - "| $name | $directory |" - } - } - else { - $reportLines += 'No files found in `./dist`.' - } - - $report = $reportLines -join [Environment]::NewLine - Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY -Value $report - Write-Output $report - - - name: Upload results to Codecov - uses: codecov/codecov-action@v5 - with: - token: ${{ secrets.CODECOV_TOKEN }} - - codescene-coverage-gates: - runs-on: ubuntu-latest - needs: - - test-and-coverage - if: ${{ needs.test-and-coverage.result == 'success' && github.event_name == 'pull_request' }} - steps: - - name: Checkout - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - - name: Download CI artifacts - uses: actions/download-artifact@v4 - with: - name: nova-ci-artifacts - path: coverage/ - - - name: Check coverage gates in CodeScene - uses: ./.github/actions/check-coverage - with: - access-token: ${{ secrets.CS_ACCESS_TOKEN }} - project-url: ${{ format('{0}/v2/projects/{1}', vars.CS_URL, vars.CS_PROJECT_ID) }} - coverage-files: '**/coverage.xml' - - codescene-analysis: - runs-on: ubuntu-latest - needs: - - test-and-coverage - if: ${{ needs.test-and-coverage.result == 'success' && (github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref_name == 'develop')) }} - steps: - - name: Checkout - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - - name: Download CI artifacts - uses: actions/download-artifact@v4 - with: - name: nova-ci-artifacts - path: . - - - name: Install CodeScene coverage CLI - shell: bash - run: | - set -euo pipefail - curl -fsSL -o install-cs-coverage-tool.sh https://downloads.codescene.io/enterprise/cli/install-cs-coverage-tool.sh - bash install-cs-coverage-tool.sh -y - echo "$HOME/.local/bin" >> "$GITHUB_PATH" - - - name: Upload coverage to CodeScene and trigger analysis - env: - CS_URL: ${{ vars.CS_URL }} - CS_PROJECT_ID: ${{ vars.CS_PROJECT_ID }} - CS_ACCESS_TOKEN: ${{ secrets.CS_ACCESS_TOKEN }} - run: ./scripts/build/ci/Invoke-CodeSceneAnalysis.ps1 -UploadCoverage -TriggerAnalysis + tests: + uses: stiwicourage/powershell-ci/.github/workflows/tests.yml@develop + with: + dependency-mode: isolated + pester-required-version: '5.7.1' + script-analyzer-required-version: '1.25.0' + changelog-files: ./CHANGELOG.md ./RELEASE_NOTE.md + secrets: inherit diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml deleted file mode 100644 index bddef11..0000000 --- a/.github/workflows/codeql.yml +++ /dev/null @@ -1,99 +0,0 @@ -# For most projects, this workflow file will not need changing; you simply need -# to commit it to your repository. -# -# You may wish to alter this file to override the set of languages analyzed, -# or to provide custom queries or build logic. -# -# ******** NOTE ******** -# We have attempted to detect the languages in your repository. Please check -# the `language` matrix defined below to confirm you have the correct set of -# supported CodeQL languages. -# -name: "CodeQL Advanced" - -on: - push: - branches: [ "develop" ] - pull_request: - branches: [ "develop" ] - schedule: - - cron: '34 3 * * 1' - -jobs: - analyze: - name: Analyze (${{ matrix.language }}) - # Runner size impacts CodeQL analysis time. To learn more, please see: - # - https://gh.io/recommended-hardware-resources-for-running-codeql - # - https://gh.io/supported-runners-and-hardware-resources - # - https://gh.io/using-larger-runners (GitHub.com only) - # Consider using larger runners or machines with greater resources for possible analysis time improvements. - runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-latest' }} - permissions: - # required for all workflows - security-events: write - - # required to fetch internal or private CodeQL packs - packages: read - - # only required for workflows in private repositories - actions: read - contents: read - - strategy: - fail-fast: false - matrix: - include: - - language: actions - build-mode: none - # CodeQL supports the following values keywords for 'language': 'actions', 'c-cpp', 'csharp', 'go', 'java-kotlin', 'javascript-typescript', 'python', 'ruby', 'rust', 'swift' - # Use `c-cpp` to analyze code written in C, C++ or both - # Use 'java-kotlin' to analyze code written in Java, Kotlin or both - # Use 'javascript-typescript' to analyze code written in JavaScript, TypeScript or both - # To learn more about changing the languages that are analyzed or customizing the build mode for your analysis, - # see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/customizing-your-advanced-setup-for-code-scanning. - # If you are analyzing a compiled language, you can modify the 'build-mode' for that language to customize how - # your codebase is analyzed, see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/codeql-code-scanning-for-compiled-languages - steps: - - name: Checkout repository - uses: actions/checkout@v4 - - # Add any setup steps before running the `github/codeql-action/init` action. - # This includes steps like installing compilers or runtimes (`actions/setup-node` - # or others). This is typically only required for manual builds. - # - name: Setup runtime (example) - # uses: actions/setup-example@v1 - - # Initializes the CodeQL tools for scanning. - - name: Initialize CodeQL - uses: github/codeql-action/init@v4 - with: - languages: ${{ matrix.language }} - build-mode: ${{ matrix.build-mode }} - # If you wish to specify custom queries, you can do so here or in a config file. - # By default, queries listed here will override any specified in a config file. - # Prefix the list here with "+" to use these queries and those in the config file. - - # For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs - # queries: security-extended,security-and-quality - - # If the analyze step fails for one of the languages you are analyzing with - # "We were unable to automatically build your code", modify the matrix above - # to set the build mode to "manual" for that language. Then modify this step - # to build your code. - # ℹ️ Command-line programs to run using the OS shell. - # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun - - name: Run manual build steps - if: matrix.build-mode == 'manual' - shell: bash - run: | - echo 'If you are using a "manual" build mode for one or more of the' \ - 'languages you are analyzing, replace this with the commands to build' \ - 'your code, for example:' - echo ' make bootstrap' - echo ' make release' - exit 1 - - - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v4 - with: - category: "/language:${{matrix.language}}" diff --git a/.github/workflows/dependency-review.yml b/.github/workflows/dependency-review.yml deleted file mode 100644 index 1d9b368..0000000 --- a/.github/workflows/dependency-review.yml +++ /dev/null @@ -1,39 +0,0 @@ -# Dependency Review Action -# -# This Action will scan dependency manifest files that change as part of a Pull Request, -# surfacing known-vulnerable versions of the packages declared or updated in the PR. -# Once installed, if the workflow run is marked as required, PRs introducing known-vulnerable -# packages will be blocked from merging. -# -# Source repository: https://github.com/actions/dependency-review-action -# Public documentation: https://docs.github.com/en/code-security/supply-chain-security/understanding-your-software-supply-chain/about-dependency-review#dependency-review-enforcement -name: 'Dependency review' -on: - pull_request: - branches: [ "develop" ] - -# If using a dependency submission action in this workflow this permission will need to be set to: -# -# permissions: -# contents: write -# -# https://docs.github.com/en/enterprise-cloud@latest/code-security/supply-chain-security/understanding-your-software-supply-chain/using-the-dependency-submission-api -permissions: - contents: read - # Write permissions for pull-requests are required for using the `comment-summary-in-pr` option, comment out if you aren't using this option - pull-requests: write - -jobs: - dependency-review: - runs-on: ubuntu-latest - steps: - - name: 'Checkout repository' - uses: actions/checkout@v4 - - name: 'Dependency Review' - uses: actions/dependency-review-action@v4 - # Commonly enabled options, see https://github.com/actions/dependency-review-action#configuration-options for all available options. - with: - comment-summary-in-pr: always - fail-on-severity: moderate - # deny-licenses: GPL-1.0-or-later, LGPL-2.0-or-later - retry-on-snapshot-warnings: true diff --git a/.github/workflows/powershell.yml b/.github/workflows/powershell.yml deleted file mode 100644 index 78462f0..0000000 --- a/.github/workflows/powershell.yml +++ /dev/null @@ -1,49 +0,0 @@ -# This workflow uses actions that are not certified by GitHub. -# They are provided by a third-party and are governed by -# separate terms of service, privacy policy, and support -# documentation. -# -# https://github.com/microsoft/action-psscriptanalyzer -# For more information on PSScriptAnalyzer in general, see -# https://github.com/PowerShell/PSScriptAnalyzer - -name: Run PSScriptAnalyzer - -on: - push: - branches: [ "develop" ] - pull_request: - branches: [ "develop" ] - schedule: - - cron: '24 13 * * 1' - -permissions: - contents: read - -jobs: - build: - permissions: - contents: read # for actions/checkout to fetch code - security-events: write # for github/codeql-action/upload-sarif to upload SARIF results - actions: read # only required for a private repository by github/codeql-action/upload-sarif to get the Action run status - name: PSScriptAnalyzer - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - - name: Run PSScriptAnalyzer - uses: microsoft/psscriptanalyzer-action@6b2948b1944407914a58661c49941824d149734f - with: - # Check https://github.com/microsoft/action-psscriptanalyzer for more info about the options. - # The below set up runs PSScriptAnalyzer to your entire repository and runs some basic security rules. - path: .\ - recurse: true - # Include your own basic security rules. Removing this option will run all the rules - includeRule: '"PSAvoidGlobalAliases", "PSAvoidUsingConvertToSecureStringWithPlainText"' - output: results.sarif - - # Upload the SARIF file generated in the previous step - - name: Upload SARIF results file - uses: github/codeql-action/upload-sarif@v3 - with: - sarif_file: results.sarif diff --git a/CHANGELOG.md b/CHANGELOG.md index 33c826f..d23b9cb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,17 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), ### Changed +- Reuse `powershell-ci` for test/coverage, security, and publish workflows while + retaining the six local platform/runtime lanes, their SHA pins, dependency + isolation, skip classification, artifact checks, and 95% source-coverage gate. + Shared callers follow the common module convention with PSScriptAnalyzer + 1.25.0, both release documents, daily tests, weekly security checks, and grouped + weekly GitHub Actions dependency updates. PMU adds isolated dependencies and + exact Pester 5.7.1 while shared defaults own JaCoCo artifacts and analysis. Publishing follows the + GerberCore workflow and moves `CHANGELOG.md` and `RELEASE_NOTE.md` together. + PSModuleUpdate references use `develop` for qualification before moving + to a separately released shared-workflow tag. + ### Deprecated ### Removed diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3c26385..3e1f8e8 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -58,7 +58,7 @@ Recommended flow: - Use `/agent release-manager`, `.github/agents/release-manager.agent.md`, and `.github/prompts/prepare-release.prompt.md` when release-facing files change. The [G-4A4 plan](docs/architecture/G4A4/README.md) designs the GitHub Actions matrix and release gating. Phase 1 -(`.github/workflows/ci.yml`, `scripts/build/ci/`) has executed on GitHub: both macOS lanes passed, while +(`.github/workflows/Run-Platform-Matrix.yml`, formerly `ci.yml`, and `scripts/build/ci/`) has executed on GitHub: both macOS lanes passed, while Windows/Linux fixes still require a successful rerun; see [PHASE1_IMPLEMENTATION.md](docs/architecture/G4A4/PHASE1_IMPLEMENTATION.md) for triggers, lanes, the `ci-gate`, artifacts and local validation. To reproduce a lane locally, run @@ -80,18 +80,40 @@ source, version selection and owned destination. Exhausted retries or a failed isolated import probe still fail provisioning and remove its owned dependency directory. -The separate `Run Tests` workflow also saves dependencies to an owned temporary -root. Each PowerShell consumer step uses the install step's `moduleRoot` output -to set an isolated `PSModulePath`; installed modules and imports do not carry -over automatically between steps. An always-run cleanup step validates ownership -before removing that root, including when tests or changelog validation fail. -Its CI script runs `Invoke-NovaTest` before `Test-NovaBuild`: unit tests generate +The separate `Run Tests` workflow calls the shared +[`powershell-ci` test workflow](https://github.com/stiwicourage/powershell-ci). +Its `dependency-mode: isolated` opt-in saves dependencies to an owned temporary +root and passes the isolated `PSModulePath` into every consumer process. +Installed modules and imports do not carry over automatically between steps. +Shared cleanup validates ownership even when tests or changelog validation fail. +The shared Nova action runs `Invoke-NovaTest` before `Test-NovaBuild`: unit tests generate `artifacts/coverage.xml` from the enabled `project.json` JaCoCo configuration, -and the uploaded artifact supplies CodeScene and Codecov. Integration results +and the uploaded artifact supplies CodeScene. Integration results alone are not coverage evidence. +`Tests.yml`, `Publish.yml`, and `Security.yml` are thin shared-workflow callers; +`Run-Platform-Matrix.yml` and its lane/gate tooling remain local. Tests request +Pester 5.7.1 and the common PSScriptAnalyzer 1.25.0, validate both release documents, and preserve +the 95% source-coverage threshold. Publish uses `Test-NovaBuild` and Nova's CI +release mode, matching GerberCore. + +The four shared-CI module consumers use one caller convention: daily tests, +weekly shared security checks, and grouped weekly GitHub Actions dependency +updates. Only PMU's isolation/Pester requirements and Gerber.AzureDevOps' +existing build-validation and publisher exceptions differ. Shared defaults +control analyzer rules, analysis, coverage artifact names, and review severity. +The existing settings file still belongs to local `run.ps1` validation. + +During validation only PSModuleUpdate uses `@develop`. GerberCore and +SemanticRelease retain `@0.1.1`, including GerberCore's direct install-action +reference; Gerber.AzureDevOps retains its existing `@0.1.0`. Record the resolved +shared commit alongside each tested consumer revision. After a separately +authorized upstream release, +switch PSModuleUpdate to its actual tag and requalify; an outer tag does not +freeze shared actions that still reference `@develop`. + Workflow policy tests distinguish the platform matrix from the other workflows. -`ci.yml` retains full-SHA action pins, fixed runner labels, read-only permissions, +`Run-Platform-Matrix.yml` retains full-SHA action pins, fixed runner labels, read-only permissions, and no secrets or publishing. Separate test/coverage, analysis, dependency-review, and publish workflows may use version-tagged actions, moving runner labels, and their purpose-specific permissions and secrets. All workflows reject diff --git a/README.md b/README.md index 54f3965..c646f22 100644 --- a/README.md +++ b/README.md @@ -277,6 +277,27 @@ Follow this workflow when working with Copilot in this repository. ## Nova project expectations +Tests, coverage, security analysis, and publishing reuse +[powershell-ci](https://github.com/stiwicourage/powershell-ci). The callers request +isolated dependencies and exact Pester 5.7.1; `project.json` continues to require +PSResourceGet 1.2.0 and source coverage of at least 95%. Local validation still +uses `run.ps1`; the six-lane platform matrix and its evidence gate remain owned +by this repository. + +All four shared-CI module consumers use the same test, publish, security, and +weekly Dependabot convention, with PSScriptAnalyzer pinned to 1.25.0 and both +release documents validated. PMU adds only its isolated-dependency and Pester +requirements. Shared defaults own analysis and coverage artifact configuration. + +PSModuleUpdate's shared workflow references temporarily use `@develop` during +testing. GerberCore and SemanticRelease retain `@0.1.1`; Gerber.AzureDevOps +retains its existing `@0.1.0`. +The shared changes must remain compatible with those tagged callers. +PSModuleUpdate moves to a released version tag only after it exists and the +shared changes are qualified. +Publishing follows GerberCore's stable/prerelease flow and moves both release +documents; CI migration does not itself authorize publishing or branch mutation. + - Use Nova commands and `project.json` for build, test, package, and release behavior. - Treat `project.json` `Manifest.PowerShellHostVersion` as the compatibility target for PowerShell code, tests, and examples. If it is `5.1`, do not introduce PowerShell 7.x-only features. - Keep local quality checks ordered as ScriptAnalyzer first, then `Invoke-NovaBuild`, then `Invoke-NovaTest`, then `Test-NovaBuild` when your project defines both test flows. diff --git a/RELEASE_NOTE.md b/RELEASE_NOTE.md index 93348f2..4b6a69b 100644 --- a/RELEASE_NOTE.md +++ b/RELEASE_NOTE.md @@ -31,6 +31,12 @@ This file summarizes public cmdlet, CLI, configuration, and migration changes fo ### Changed +- Contributor tests, security checks, and publishing now use shared + `powershell-ci` workflows with the same caller convention as the reference + modules, including weekly grouped dependency updates. Local `run.ps1` and the six-platform/runtime CI + lanes remain in place. Stable publishing moves both changelog and release + notes. PSModuleUpdate references temporarily use `develop` during qualification; + public module commands and installation behavior are unchanged. - Managed-module updates use native `Update-Module` without Force or an automatic install fallback. The unmanaged opt-in uses exact-version native `Install-Module`, with Force only for a target-directory collision. diff --git a/docs/architecture/G4A4/SECURITY_MODEL.md b/docs/architecture/G4A4/SECURITY_MODEL.md index 6103186..8c42df3 100644 --- a/docs/architecture/G4A4/SECURITY_MODEL.md +++ b/docs/architecture/G4A4/SECURITY_MODEL.md @@ -1,5 +1,41 @@ # Security and credential model +## Current implementation boundary + +The local `Run-Platform-Matrix.yml` remains read-only, secret-free, full-SHA +pinned, and restricted to owned fixtures and evidence. Its isolation, cleanup, +runtime guards, and skip policy are unchanged. + +`Tests.yml` opts into isolated shared dependencies with owned cleanup and exact +provider/Pester imports. It retains the existing coverage services' secret +contract; it is not a blanket secret-free workflow. Fork PRs do not receive +repository secrets, and unavailable service verification must not be reported +as passed. + +`Security.yml` grants security-event/package read or PR-comment permissions +only to the job that requires them. Dependency review is PR-only; CodeQL and +SARIF use the common weekly schedule across the four module consumers. No workflow uses +`pull_request_target`. + +`Publish.yml` calls the same shared publisher as GerberCore with isolated +dependencies. It retains write permissions and an API key for main/manual +publication, including existing commit/tag and develop force-update behavior. +There is no new environment approval, branch protection, or dependency on the +platform workflow. Those protections require separate configuration and cannot +be inferred from this migration. + +Only PSModuleUpdate's shared refs temporarily follow `develop` and later move +to an actual release tag. Reference projects retain their existing tags. +The platform matrix's stricter SHA-pin policy does not change. Validate the +resolved upstream revision as well as the caller; older shared tags already +use internal develop-action references. + +## Historical G-4A4 proposal + +The remaining sections are the earlier proposed qualification/security design. +Proposed environments and release-gate workflows below are not implemented by +the shared-workflow migration. + ## TL;DR Pull-request jobs are secret-free and read-only. Cross-platform jobs use only diff --git a/docs/architecture/G4A4/WORKFLOW_MAP.md b/docs/architecture/G4A4/WORKFLOW_MAP.md index ee1d4d0..e7f064b 100644 --- a/docs/architecture/G4A4/WORKFLOW_MAP.md +++ b/docs/architecture/G4A4/WORKFLOW_MAP.md @@ -1,4 +1,46 @@ -# Existing GitHub Actions workflow map +# GitHub Actions workflow ownership + +## Current shared-workflow migration + +PSModuleUpdate keeps `.github/workflows/Run-Platform-Matrix.yml` and `scripts/build/ci/` lane +qualification locally. Six Windows/Linux x64 and macOS ARM64 lanes cover +PowerShell 7.4 and stable, with unchanged provisioning, exact skip policy, +full-SHA action pins, artifact validation, and aggregate `ci-gate`. + +| Caller | Shared owner | Project-specific contract | +| --- | --- | --- | +| `Tests.yml` | `powershell-ci/.github/workflows/tests.yml` | Common analyzer 1.25.0 and both release files; PMU isolation/Pester 5.7.1 exceptions; JaCoCo 95%; shared analysis/artifact defaults | +| `Publish.yml` | `powershell-ci/.github/workflows/publish.yml` | Main push/manual dispatch, Test-NovaBuild, CI-release mode, isolated dependencies | +| `Security.yml` | Shared CodeQL, SARIF analyzer, dependency-review workflows | Common develop push/PR and weekly Monday schedule; PR-only dependency review with shared default severity | +| `.github/dependabot.yml` | GitHub Dependabot | Common weekly GitHub Actions updates and powershell-ci group | + +The shared test workflow owns generic Nova orchestration and coverage uploads. +Each isolated job owns its dependency root and cleanup; imports do not survive +fresh PowerShell steps. `run.ps1` and the local analyzer wrapper remain valid +developer entrypoints. Consumer tests cover caller contracts, not upstream +dependency implementation. + +Only PSModuleUpdate uses `@develop` for qualification. GerberCore and +SemanticRelease retain `@0.1.1`, including GerberCore's direct install-action +ref; Gerber.AzureDevOps retains its existing `@0.1.0`. PSModuleUpdate moves to a +real release tag only after upstream qualification and a separately authorized +release. Record the +resolved upstream commit for every run; a local sibling change is not +automatically available to GitHub. + +Publish follows GerberCore: stable release publishes and updates main, then +prepares/force-updates develop; dispatch on develop publishes a prerelease and +bumps the next version. Both release documents are moved during stable release. +There is no newly introduced cross-workflow dependency or environment-approval +gate. Successful publisher build/tests are not evidence that all six matrix +jobs passed; hosted branch-protection settings are configured separately. + +## Historical discovery snapshot + +The sections below preserve the original G-4A4 investigation. Statements about +missing PMU workflows, remotes, or copied actions describe that historical +checkout and are superseded by the current ownership map above. They are not +claims about current hosted qualification. ## TL;DR diff --git a/docs/architecture/TESTING.md b/docs/architecture/TESTING.md index 687329e..48b62a3 100644 --- a/docs/architecture/TESTING.md +++ b/docs/architecture/TESTING.md @@ -10,7 +10,7 @@ defined by `project.json`; the module root and manifest are generated under pwsh -NoLogo -NoProfile -File ./run.ps1 ``` -GitHub Actions (`.github/workflows/ci.yml`) runs the same Nova build, unit and +GitHub Actions (`.github/workflows/Run-Platform-Matrix.yml`) runs the same Nova build, unit and integration phases per platform lane through `./scripts/build/ci/Invoke-PlatformLane.ps1 -LaneId `; see [G4A4/PHASE1_IMPLEMENTATION.md](G4A4/PHASE1_IMPLEMENTATION.md). @@ -44,7 +44,7 @@ enabled in `project.json`, targets the authored source paths, and writes JaCoCo to `artifacts/coverage.xml` with the configured 95 percent target. Integration tests remain a separate phase and do not generate the unit coverage report. The test/coverage workflow runs `Invoke-NovaTest` before `Test-NovaBuild` and -uploads that report for CodeScene and Codecov; test counts alone do not +uploads that report for CodeScene; test counts alone do not establish a measured coverage percentage. ### Native update transition diff --git a/scripts/build/ci/Invoke-CodeSceneAnalysis.ps1 b/scripts/build/ci/Invoke-CodeSceneAnalysis.ps1 deleted file mode 100644 index 1c1cba1..0000000 --- a/scripts/build/ci/Invoke-CodeSceneAnalysis.ps1 +++ /dev/null @@ -1,150 +0,0 @@ -param( - [string]$CoveragePath, - [switch]$UploadCoverage, - [switch]$TriggerAnalysis -) - -Set-StrictMode -Version Latest - -function Get-RequiredCodeSceneValue { - param([Parameter(Mandatory)][string]$Name) - - $value = [Environment]::GetEnvironmentVariable($Name) - if ( [string]::IsNullOrWhiteSpace($value)) { - throw "Missing required CodeScene configuration value '$Name'. Configure it as a CI secret or environment variable before running the analysis step." - } - - return $value -} - -function Test-CodeSceneRateLimitResponse { - param([string]$Body) - - return $Body -match 'rate limit for daily analysis jobs' -} - -function Test-CodeSceneInvalidProjectOwnerTokenResponse { - param([string]$Body) - - return $Body -match 'OAuth token of project owner invalid' -} - -function Get-CodeSceneAnalysisTriggerFailureMessage { - param( - [int]$StatusCode, - [string]$Body - ) - - if (Test-CodeSceneInvalidProjectOwnerTokenResponse -Body $Body) { - return "CodeScene rejected the analysis trigger because the project owner's repository OAuth token is invalid. Re-authorize the repository connection for the CodeScene project owner, then rerun the workflow. This is separate from CS_ACCESS_TOKEN, so coverage upload can still succeed while run-analysis fails." - } - - return "CodeScene API call failed with HTTP $StatusCode. Review the response above for details." -} - -function Test-CodeSceneCoverageUploadRequested { - param( - [string]$CoveragePath, - [switch]$UploadCoverage - ) - - return $UploadCoverage.IsPresent -or -not [string]::IsNullOrWhiteSpace($CoveragePath) -} - -function Resolve-CodeSceneCoveragePath { - param([string]$CoveragePath) - - if (-not [string]::IsNullOrWhiteSpace($CoveragePath)) { - return (Resolve-Path -LiteralPath $CoveragePath -ErrorAction Stop).Path - } - - $defaultPath = Join-Path (Get-Location) 'artifacts' 'coverage.xml' - if (-not (Test-Path -LiteralPath $defaultPath)) { - throw "No JaCoCo coverage file was found at '$defaultPath'. Provide -CoveragePath explicitly or run the CI coverage workflow first." - } - - return $defaultPath -} - -function Invoke-CodeSceneAnalysisTrigger { - param( - [Parameter(Mandatory)][string]$CodeSceneUrl, - [Parameter(Mandatory)][string]$ProjectId, - [Parameter(Mandatory)][string]$AccessToken - ) - - $endpoint = '{0}/v2/projects/{1}/run-analysis' -f $CodeSceneUrl.TrimEnd('/'), $ProjectId - Write-Host "Triggering CodeScene analysis: $endpoint" - - $response = Invoke-WebRequest -Uri $endpoint -Method Post -Headers @{ - Accept = 'application/json' - Authorization = "Bearer $AccessToken" - } -SkipHttpErrorCheck -ErrorAction Stop - - $statusCode = [int]$response.StatusCode - $body = '' + $response.Content - Write-Host "CodeScene HTTP status: $statusCode" - if (-not [string]::IsNullOrWhiteSpace($body)) { - Write-Host 'CodeScene response:' - Write-Host $body - } - - if ($statusCode -lt 200 -or $statusCode -ge 300) { - if (Test-CodeSceneRateLimitResponse -Body $body) { - Write-Warning "CodeScene analysis rate limit reached; skipping analysis trigger (HTTP $statusCode)." - return - } - - throw (Get-CodeSceneAnalysisTriggerFailureMessage -StatusCode $statusCode -Body $body) - } - - if ($body -match '"error"') { - throw 'CodeScene API returned an error payload despite a successful HTTP status.' - } -} - -function Test-JaCoCoBranchCoverageAvailable { - param([Parameter(Mandatory)][string]$Path) - - [xml]$document = Get-Content -LiteralPath $Path -Raw - return $null -ne $document.SelectSingleNode('//counter[@type="BRANCH"]') -} - -$shouldUploadCoverage = Test-CodeSceneCoverageUploadRequested -CoveragePath $CoveragePath -UploadCoverage:$UploadCoverage -$shouldRunAnalysis = $TriggerAnalysis.IsPresent - -if (-not ($shouldUploadCoverage -or $shouldRunAnalysis)) { - Write-Host 'No CodeScene action requested. Provide -CoveragePath to upload coverage and/or -TriggerAnalysis to trigger analysis.' - return -} - -$codeSceneUrl = Get-RequiredCodeSceneValue -Name 'CS_URL' -$projectId = Get-RequiredCodeSceneValue -Name 'CS_PROJECT_ID' -$accessToken = Get-RequiredCodeSceneValue -Name 'CS_ACCESS_TOKEN' - -if ($shouldUploadCoverage) { - $resolvedCoveragePath = Resolve-CodeSceneCoveragePath -CoveragePath $CoveragePath - & (Join-Path $PSScriptRoot 'Repair-CodeSceneJaCoCoCoverage.ps1') -Path $resolvedCoveragePath - - if (-not (Get-Command -Name 'cs-coverage' -ErrorAction SilentlyContinue)) { - throw "The 'cs-coverage' CLI was not found on PATH. Install the CodeScene coverage upload tool before running this script." - } - - & cs-coverage upload --format 'jacoco' --metric 'line-coverage' $resolvedCoveragePath - if ($LASTEXITCODE -ne 0) { - throw "CodeScene line-coverage upload failed with exit code $LASTEXITCODE." - } - - if (Test-JaCoCoBranchCoverageAvailable -Path $resolvedCoveragePath) { - & cs-coverage upload --format 'jacoco' --metric 'branch-coverage' $resolvedCoveragePath - if ($LASTEXITCODE -ne 0) { - throw "CodeScene branch-coverage upload failed with exit code $LASTEXITCODE." - } - } else { - Write-Host "Skipping branch-coverage upload: '$resolvedCoveragePath' does not contain entries." - } -} - -if ($shouldRunAnalysis) { - Invoke-CodeSceneAnalysisTrigger -CodeSceneUrl $codeSceneUrl -ProjectId $projectId -AccessToken $accessToken -} diff --git a/scripts/build/ci/Invoke-NovaModuleToolsCI.ps1 b/scripts/build/ci/Invoke-NovaModuleToolsCI.ps1 deleted file mode 100644 index b06049d..0000000 --- a/scripts/build/ci/Invoke-NovaModuleToolsCI.ps1 +++ /dev/null @@ -1,89 +0,0 @@ -param( - [string]$OutputDirectory = './artifacts', - [string[]]$ExcludeTag = @() -) - -Set-StrictMode -Version Latest - -function Get-CiNUnitArtifactPath { - param( - [Parameter(Mandatory)][string]$ArtifactsDirectory, - [Parameter(Mandatory)][string]$ProjectName - ) - - return (Join-Path $ArtifactsDirectory "$($ProjectName.ToLowerInvariant())-nunit.xml") -} - -function Copy-CiArtifactIfPresent { - param( - [Parameter(Mandatory)][string]$SourcePath, - [Parameter(Mandatory)][string]$DestinationPath - ) - - if (-not (Test-Path -LiteralPath $SourcePath)) { - return - } - - $resolvedSourcePath = (Resolve-Path -LiteralPath $SourcePath).Path - $destinationDirectory = Split-Path -Parent $DestinationPath - if (-not [string]::IsNullOrWhiteSpace($destinationDirectory)) { - New-Item -ItemType Directory -Path $destinationDirectory -Force | Out-Null - } - - $resolvedDestinationPath = [System.IO.Path]::GetFullPath($DestinationPath) - if ($resolvedSourcePath -eq $resolvedDestinationPath) { - return - } - - Copy-Item -LiteralPath $resolvedSourcePath -Destination $resolvedDestinationPath -Force -} - -function Copy-CiArtifactsIfPresent { - param( - [Parameter(Mandatory)][string]$ProjectRoot, - [Parameter(Mandatory)][string]$ArtifactsDirectory, - [Parameter(Mandatory)][string]$ProjectName - ) - - $sourceArtifactsDirectory = Join-Path $ProjectRoot 'artifacts' - Copy-CiArtifactIfPresent ` - -SourcePath (Join-Path $sourceArtifactsDirectory 'TestResults.xml') ` - -DestinationPath (Get-CiNUnitArtifactPath -ArtifactsDirectory $ArtifactsDirectory -ProjectName $ProjectName) - Copy-CiArtifactIfPresent ` - -SourcePath (Join-Path $sourceArtifactsDirectory 'coverage.xml') ` - -DestinationPath (Join-Path $ArtifactsDirectory 'coverage.xml') -} - -$repoRoot = (Resolve-Path -LiteralPath (Join-Path $PSScriptRoot '..' '..' '..')).Path -Set-Location $repoRoot -New-Item -ItemType Directory -Path $OutputDirectory -Force | Out-Null - -Import-Module NovaModuleTools -ErrorAction Stop - -Invoke-NovaBuild - -$projectInfo = Get-NovaProjectInfo -$builtModulePath = $projectInfo.OutputModuleDir -Remove-Module $projectInfo.ProjectName -ErrorAction SilentlyContinue -Import-Module $builtModulePath -Force -$projectInfo = Get-NovaProjectInfo - -$testFailed = $false -try { - if (@($ExcludeTag).Count -gt 0) { - Invoke-NovaTest -ExcludeTagFilter $ExcludeTag - Test-NovaBuild -ExcludeTagFilter $ExcludeTag - } else { - Invoke-NovaTest - Test-NovaBuild - } -} catch { - $testFailed = $true - Write-Warning "CI tests failed: $( $_.Exception.Message )" -} finally { - Copy-CiArtifactsIfPresent -ProjectRoot $projectInfo.ProjectRoot -ArtifactsDirectory $OutputDirectory -ProjectName $projectInfo.ProjectName -} - -if ($testFailed) { - exit 1 -} diff --git a/scripts/build/ci/Repair-CodeSceneJaCoCoCoverage.ps1 b/scripts/build/ci/Repair-CodeSceneJaCoCoCoverage.ps1 deleted file mode 100644 index 4fc885c..0000000 --- a/scripts/build/ci/Repair-CodeSceneJaCoCoCoverage.ps1 +++ /dev/null @@ -1,64 +0,0 @@ -param( - [Parameter(Mandatory)][string[]]$Path -) - -Set-StrictMode -Version Latest -$ErrorActionPreference = 'Stop' - -function Repair-CodeSceneJaCoCoNodePathAttribute { - param( - [Parameter(Mandatory)]$Nodes, - [Parameter(Mandatory)][string]$AttributeName - ) - - $changed = $false - foreach ($node in $Nodes) { - $changed = (Repair-CodeSceneJaCoCoNodeFileName -Node $node -AttributeName $AttributeName) -or $changed - } - - return $changed -} - -function Repair-CodeSceneJaCoCoNodeFileName { - param( - [Parameter(Mandatory)]$Node, - [Parameter(Mandatory)][string]$AttributeName - ) - - $original = $Node.GetAttribute($AttributeName) - $normalized = [System.IO.Path]::GetFileName($original) - if ($normalized -eq $original) { - return $false - } - - $Node.SetAttribute($AttributeName, $normalized) - return $true -} - -function Repair-CodeSceneJaCoCoCoverageFile { - param([Parameter(Mandatory)][string]$Path) - - [xml]$document = Get-Content -LiteralPath $Path -Raw - $changed = Repair-CodeSceneJaCoCoNodePathAttribute -Nodes $document.SelectNodes('//class[@sourcefilename]') -AttributeName 'sourcefilename' - $changed = (Repair-CodeSceneJaCoCoNodePathAttribute -Nodes $document.SelectNodes('//sourcefile[@name]') -AttributeName 'name') -or $changed - - if ($changed) { - $settings = New-Object System.Xml.XmlWriterSettings - $settings.Encoding = New-Object System.Text.UTF8Encoding($false) - $settings.Indent = $false - $settings.NewLineHandling = [System.Xml.NewLineHandling]::None - $writer = [System.Xml.XmlWriter]::Create($Path, $settings) - try { - $document.Save($writer) - } finally { - $writer.Dispose() - } - - Write-Host "Normalized JaCoCo sourcefile paths in '$Path' so package + sourcefile resolve to repo files." - } -} - -foreach ($item in $Path) { - $resolvedPath = (Resolve-Path -LiteralPath $item -ErrorAction Stop).Path - Repair-CodeSceneJaCoCoCoverageFile -Path $resolvedPath -} diff --git a/tests/repository/CiWorkflow.Tests.ps1 b/tests/repository/CiWorkflow.Tests.ps1 index e451c3a..76c2ca2 100644 --- a/tests/repository/CiWorkflow.Tests.ps1 +++ b/tests/repository/CiWorkflow.Tests.ps1 @@ -2,7 +2,7 @@ BeforeAll { $root = Split-Path -Parent (Split-Path -Parent $PSScriptRoot) $workflowDirectory = Join-Path $root '.github/workflows' $script:workflowFile = @(Get-ChildItem -LiteralPath $workflowDirectory -Filter '*.yml' -File) - $script:ci = Get-Content -LiteralPath (Join-Path $workflowDirectory 'ci.yml') -Raw + $script:ci = Get-Content -LiteralPath (Join-Path $workflowDirectory 'Run-Platform-Matrix.yml') -Raw $script:publish = Get-Content -LiteralPath (Join-Path $workflowDirectory 'Publish.yml') -Raw } @@ -16,7 +16,7 @@ Describe 'CI workflow security and gate policy' -Tag 'BuildTooling', 'WorkflowPo It 'pins every external platform-matrix action to a full commit SHA' { $uses = @([regex]::Matches($script:ci, '(?m)^\s*(?:-\s*)?uses:\s*(\S+)') | ForEach-Object { $_.Groups[1].Value }) foreach ($reference in $uses | Where-Object { -not $_.StartsWith('./') }) { - $reference | Should -Match '@[0-9a-f]{40}$' -Because "ci.yml must pin '$reference'" + $reference | Should -Match '@[0-9a-f]{40}$' -Because "Run-Platform-Matrix.yml must pin '$reference'" } } @@ -38,10 +38,10 @@ Describe 'CI workflow security and gate policy' -Tag 'BuildTooling', 'WorkflowPo $script:publish | Should -Not -Match '(?m)^ pull_request(?:_target)?:' } - It 'exposes the isolated CI modules to later publish steps through PSModulePath' { - $script:publish | Should -Match '(?s)id:\s*modules\s*\r?\n\s+run:\s*\./scripts/build/ci/Install-CiPowerShellModules\.ps1' - $script:publish | Should -Match 'Get-CiIsolatedModulePath -ModuleRoot \$env:CI_MODULE_ROOT' - $script:publish | Should -Match 'PSModulePath=.*>> \$env:GITHUB_ENV' + It 'requires the shared publisher to isolate dependencies instead of using an ambient install command' { + $script:publish | Should -Match 'uses: stiwicourage/powershell-ci/.github/workflows/publish.yml@develop' + $script:publish | Should -Match 'dependency-mode: isolated' + $script:publish | Should -Not -Match 'install-command:' } It 'supports pull requests into develop and main, pushes outside main, plus reuse' { diff --git a/tests/repository/RunTestsDependencies.Tests.ps1 b/tests/repository/RunTestsDependencies.Tests.ps1 deleted file mode 100644 index 4092708..0000000 --- a/tests/repository/RunTestsDependencies.Tests.ps1 +++ /dev/null @@ -1,121 +0,0 @@ -# Cross-cutting contract: Tests.yml hands one owned dependency root across fresh pwsh steps. -BeforeAll { - $script:root = Split-Path -Parent (Split-Path -Parent $PSScriptRoot) - $script:workflow = Get-Content -LiteralPath (Join-Path $script:root '.github/workflows/Tests.yml') -Raw - . (Join-Path $script:root 'scripts/build/ci/CiDependencyRoot.ps1') - - function Get-DependencyWorkflowStep { - param([string]$Name) - $pattern = '(?ms)^ - name: ' + [regex]::Escape($Name) + '\r?\n.*?(?=^ - name:|^ [a-z]|\z)' - return [regex]::Match($script:workflow, $pattern).Value - } - - function Get-DependencyWorkflowCommand { - param([string]$Step) - $block = [regex]::Match($Step, '(?ms)^ run: \|\r?\n(.*)').Groups[1].Value - return ($block -replace '(?m)^ ', '').TrimEnd() - } - - function Invoke-DependencyWorkflowChild { - param( - [string]$Command, - [string]$ModuleRoot - ) - - $location = $script:root.Replace("'", "''") - $path = $ModuleRoot.Replace("'", "''") - $preamble = "`$ErrorActionPreference = 'Stop'; Set-Location '$location'; `$env:CI_MODULE_ROOT = '$path';" - $output = & (Get-Process -Id $PID).Path -NoLogo -NoProfile -Command ($preamble + $Command) 2>&1 - return @{ - ExitCode = $LASTEXITCODE - Output = ($output -join "`n") - } - } -} - -Describe 'Run Tests dependency lifecycle' -Tag 'BuildTooling', 'RunTestsDependencies' { - It 'exposes the saved root through a named install step with line endings' -ForEach @( - @{ - LineEnding = 'LF' - NewLine = "`n" - } - @{ - LineEnding = 'CRLF' - NewLine = "`r`n" - } - ) { - $step = (Get-DependencyWorkflowStep 'Install required CI PowerShell modules') -replace '\r?\n', $NewLine - $step | Should -Match '(?m)^ id: modules\r?$' - $step | Should -Match 'run: ./scripts/build/ci/Install-CiPowerShellModules.ps1' - } - - It 'isolates dependencies before in a fresh process' -ForEach @( - @{ - Name = 'Run NovaModuleTools CI test and coverage workflow' - Boundary = './scripts/build/ci/Invoke-NovaModuleToolsCI.ps1' - } - @{ - Name = 'Validate repository changelog with Test-KeepAChangelogFile' - Boundary = '$result = Test-KeepAChangelogFile' - } - ) { - $step = Get-DependencyWorkflowStep $Name - $step | Should -Match 'CI_MODULE_ROOT: \$\{\{ steps\.modules\.outputs\.moduleRoot \}\}' - $command = Get-DependencyWorkflowCommand $step - $setup = ($command -split [regex]::Escape($Boundary), 2)[0] - $setup | Should -Match '\$env:PSModulePath = Get-CiIsolatedModulePath -ModuleRoot \$env:CI_MODULE_ROOT' - $owner = New-CiDependencyRoot -Path (Join-Path $TestDrive "pmu-ci-modules-$([guid]::NewGuid().ToString('N'))") - $module = New-Item -ItemType Directory -Path (Join-Path $owner.Path 'NovaModuleTools') - Set-Content -LiteralPath (Join-Path $module.FullName 'NovaModuleTools.psm1') -Value '# disposable discovery fixture' - $probe = 'Import-Module NovaModuleTools -ErrorAction Stop; (Get-Module NovaModuleTools).ModuleBase; $env:PSModulePath' - $result = Invoke-DependencyWorkflowChild -Command ($setup + "`n" + $probe) -ModuleRoot $owner.Path - $result.ExitCode | Should -Be 0 -Because $result.Output - $result.Output | Should -BeExactly ($module.FullName + "`n" + (Get-CiIsolatedModulePath -ModuleRoot $owner.Path)) - } - - It 'fails closed for an unowned dependency root before running CI' { - $step = Get-DependencyWorkflowStep 'Run NovaModuleTools CI test and coverage workflow' - $setup = (Get-DependencyWorkflowCommand $step) -split [regex]::Escape('./scripts/build/ci/Invoke-NovaModuleToolsCI.ps1'), 2 - $result = Invoke-DependencyWorkflowChild -Command ($setup[0] + "`n'consumer reached'") -ModuleRoot $TestDrive - $result.ExitCode | Should -Not -Be 0 - $result.Output | Should -Not -Match 'consumer reached' - } - - It 'imports Nova explicitly for changelog validation' { - $command = Get-DependencyWorkflowCommand (Get-DependencyWorkflowStep 'Validate repository changelog with Test-KeepAChangelogFile') - $command | Should -Match '(?s)Import-Module NovaModuleTools -ErrorAction Stop.*\$result = Test-KeepAChangelogFile' - } - - It 'always schedules owned cleanup after both consumers when installation produced a root' { - $step = Get-DependencyWorkflowStep 'Clean owned CI dependencies' - $step | Should -Match 'if: \$\{\{ always\(\) && steps\.modules\.outputs\.moduleRoot != '''' \}\}' - $step | Should -Match 'CI_MODULE_ROOT: \$\{\{ steps\.modules\.outputs\.moduleRoot \}\}' - $script:workflow.IndexOf($step) | Should -BeGreaterThan $script:workflow.IndexOf('Validate repository changelog') - $step | Should -Not -Match 'Remove-Item' - } - - It 'executes validated cleanup in a fresh process and refuses ownership' -ForEach @( - @{ - Kind = 'valid' - Tamper = $false - ExitCode = 0 - Remains = $false - } - @{ - Kind = 'invalid' - Tamper = $true - ExitCode = 1 - Remains = $true - } - ) { - $owner = New-CiDependencyRoot -Path (Join-Path $TestDrive "pmu-ci-modules-$([guid]::NewGuid().ToString('N'))") - if ($Tamper) { - Set-Content -LiteralPath (Join-Path $owner.Path '.pmu-dependencies.json') -Value '{}' - } - $command = Get-DependencyWorkflowCommand (Get-DependencyWorkflowStep 'Clean owned CI dependencies') - $command | Should -Match 'Remove-CiDependencyRoot -Owner \(Get-CiDependencyOwner -Path \$env:CI_MODULE_ROOT\)' - $result = Invoke-DependencyWorkflowChild -Command $command -ModuleRoot $owner.Path - $result.ExitCode | Should -Be $ExitCode -Because $result.Output - Test-Path -LiteralPath $owner.Path | Should -Be $Remains - } -} diff --git a/tests/repository/SharedCiContracts.Tests.ps1 b/tests/repository/SharedCiContracts.Tests.ps1 new file mode 100644 index 0000000..825779d --- /dev/null +++ b/tests/repository/SharedCiContracts.Tests.ps1 @@ -0,0 +1,73 @@ +BeforeAll { + $root = Split-Path -Parent (Split-Path -Parent $PSScriptRoot) + $directory = Join-Path $root '.github/workflows' + $script:testsWorkflow = Get-Content (Join-Path $directory 'Tests.yml') -Raw + $script:publishWorkflow = Get-Content (Join-Path $directory 'Publish.yml') -Raw + $securityPath = Join-Path $directory 'Security.yml' + $script:securityWorkflow = if (Test-Path $securityPath) { Get-Content $securityPath -Raw } else { '' } + $dependabotPath = Join-Path $root '.github/dependabot.yml' + $script:dependabot = if (Test-Path $dependabotPath) { Get-Content $dependabotPath -Raw } else { '' } +} + +Describe 'Shared CI consumer contracts' -Tag 'SharedCi', 'WorkflowPolicy', 'BuildTooling' { + It 'uses the shared test workflow without replacing its test command' { + $script:testsWorkflow | Should -Match 'uses: stiwicourage/powershell-ci/.github/workflows/tests.yml@develop' + $script:testsWorkflow | Should -Not -Match 'test-command:' + $script:testsWorkflow | Should -Not -Match 'runs-on:' + } + + It 'requests isolated exact-version test dependencies' { + $script:testsWorkflow | Should -Match 'dependency-mode: isolated' + $script:testsWorkflow | Should -Match "pester-required-version: '5.7.1'" + $script:testsWorkflow | Should -Not -Match 'install-command:' + } + + It 'uses the common analyzer version and validates both release documents' { + $script:testsWorkflow | Should -Match "script-analyzer-required-version: '1.25.0'" + $script:testsWorkflow | Should -Not -Match 'script-analyzer-settings-file:|script-analyzer-enabled:' + $script:testsWorkflow | Should -Match 'changelog-files: ./CHANGELOG.md ./RELEASE_NOTE.md' + } + + It 'preserves coverage artifacts and analysis without enabling Codecov' { + $script:testsWorkflow | Should -Not -Match 'codecov' + $script:testsWorkflow | Should -Not -Match 'codescene-enabled:|artifact-name:' + $script:testsWorkflow | Should -Match 'secrets: inherit' + } + + It 'keeps test scheduling and pull requests to both release branches' { + $script:testsWorkflow | Should -Match '(?s)branches-ignore:\s+- main' + $script:testsWorkflow | Should -Match '(?s)pull_request:\s+branches:\s+- main\s+- develop' + $script:testsWorkflow | Should -Match "cron: '0 3 \* \* \*'" + $script:testsWorkflow | Should -Match 'workflow_dispatch:' + } + + It 'uses the shared publisher with GerberCore release semantics and isolated dependencies' { + $script:publishWorkflow | Should -Match 'uses: stiwicourage/powershell-ci/.github/workflows/publish.yml@develop' + $script:publishWorkflow | Should -Match 'test-command: Test-NovaBuild' + $script:publishWorkflow | Should -Match 'release-continuous-integration: true' + $script:publishWorkflow | Should -Match 'dependency-mode: isolated' + } + + It 'delegates all three security checks and keeps dependency review PR-only' { + $script:securityWorkflow | Should -Match 'codeql.yml@develop' + $script:securityWorkflow | Should -Match 'powershell-analyzer.yml@develop' + $script:securityWorkflow | Should -Match 'dependency-review.yml@develop' + $script:securityWorkflow | Should -Match "github.event_name == 'pull_request'" + $script:securityWorkflow | Should -Not -Match 'fail-on-severity:' + } + + It 'uses the common weekly security schedule without per-job schedule routing' { + @([regex]::Matches($script:securityWorkflow, '(?m)^\s+- cron:')).Count | Should -Be 1 + $script:securityWorkflow | Should -Match "cron: '34 3 \* \* 1'" + $script:securityWorkflow | Should -Not -Match 'github.event.schedule' + } + + It 'groups shared workflow dependency updates on the common weekly schedule' { + $script:dependabot | Should -Match 'package-ecosystem: github-actions' + $script:dependabot | Should -Match 'directory: /' + $script:dependabot | Should -Match 'interval: weekly' + $script:dependabot | Should -Match 'prefix: chore' + $script:dependabot | Should -Match 'powershell-ci:' + $script:dependabot | Should -Match 'stiwicourage/powershell-ci\*' + } +} diff --git a/tests/scripts/build/ci/Invoke-NovaModuleToolsCI.Tests.ps1 b/tests/scripts/build/ci/Invoke-NovaModuleToolsCI.Tests.ps1 deleted file mode 100644 index f347f75..0000000 --- a/tests/scripts/build/ci/Invoke-NovaModuleToolsCI.Tests.ps1 +++ /dev/null @@ -1,69 +0,0 @@ -BeforeAll { - Import-Module NovaModuleTools - $root = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $PSScriptRoot))) - $script:runnerSource = Join-Path $root 'scripts/build/ci/Invoke-NovaModuleToolsCI.ps1' - - function Initialize-CiCoverageFixture { - param( - [string]$Source, - [string]$Root - ) - - $scripts = Join-Path $Root 'scripts/build/ci' - $artifacts = Join-Path $Root 'artifacts' - New-Item -ItemType Directory -Path @($scripts, $artifacts) -Force | Out-Null - $runner = Copy-Item -LiteralPath $Source -Destination $scripts -PassThru - return @{ - ProjectRoot = $Root - ProjectName = 'CoverageFixture' - OutputModuleDir = 'unused' - Runner = $runner.FullName - } - } -} - -Describe 'CI unit coverage production' -Tag 'BuildTooling', 'CiCoverage' { - BeforeEach { - $script:fixture = Initialize-CiCoverageFixture -Source $script:runnerSource -Root (Join-Path $TestDrive 'project') - $script:location = (Get-Location).Path - Mock Import-Module { } - Mock Invoke-NovaBuild { 'build' } - Mock Invoke-NovaTest { 'unit' } - Mock Test-NovaBuild { - Set-Content -LiteralPath './artifacts/TestResults.xml' -Value '' - 'integration' - } - Set-Location -LiteralPath $script:fixture.ProjectRoot - Mock Get-NovaProjectInfo { - [pscustomobject]@{ - ProjectRoot = (Get-Location).Path - ProjectName = 'CoverageFixture' - OutputModuleDir = 'unused' - } - } - } - - AfterEach { - Set-Location -LiteralPath $script:location - } - - It 'runs unit coverage before integration and retains its report in the output directory' { - Mock Invoke-NovaTest { - Set-Content -LiteralPath './artifacts/coverage.xml' -Value '' - 'unit' - } - $outputDirectory = Join-Path $script:fixture.ProjectRoot 'published' - $output = @(& $script:fixture.Runner -OutputDirectory $outputDirectory) - - $output -join ',' | Should -BeExactly 'build,unit,integration' - (Get-Content -LiteralPath (Join-Path $outputDirectory 'coverage.xml') -Raw).Trim() | Should -BeExactly '' - Test-Path -LiteralPath (Join-Path $outputDirectory 'coveragefixture-nunit.xml') | Should -BeTrue - } - - It 'applies the requested exclusions to both test phases' { - & $script:fixture.Runner -OutputDirectory (Join-Path $script:fixture.ProjectRoot 'published') -ExcludeTag RepositoryLive - - Should -Invoke Invoke-NovaTest -Times 1 -Exactly -ParameterFilter { $ExcludeTagFilter -contains 'RepositoryLive' } - Should -Invoke Test-NovaBuild -Times 1 -Exactly -ParameterFilter { $ExcludeTagFilter -contains 'RepositoryLive' } - } -} From 3633d1fdaf08db4313bf93380de8141823dfac08 Mon Sep 17 00:00:00 2001 From: Stiwi Gabriel Courage Date: Sun, 15 Nov 2026 21:09:41 +0100 Subject: [PATCH 4/9] feat: update workflow references to use version 0.2.0 --- .github/workflows/Publish.yml | 2 +- .github/workflows/Security.yml | 6 +++--- .github/workflows/Tests.yml | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/Publish.yml b/.github/workflows/Publish.yml index 1b6c404..0819b03 100644 --- a/.github/workflows/Publish.yml +++ b/.github/workflows/Publish.yml @@ -12,7 +12,7 @@ permissions: jobs: publish: - uses: stiwicourage/powershell-ci/.github/workflows/publish.yml@develop + uses: stiwicourage/powershell-ci/.github/workflows/publish.yml@0.2.0 with: dependency-mode: isolated pester-required-version: '5.7.1' diff --git a/.github/workflows/Security.yml b/.github/workflows/Security.yml index 21a6be9..f0ab00c 100644 --- a/.github/workflows/Security.yml +++ b/.github/workflows/Security.yml @@ -15,7 +15,7 @@ permissions: jobs: codeql: - uses: stiwicourage/powershell-ci/.github/workflows/codeql.yml@develop + uses: stiwicourage/powershell-ci/.github/workflows/codeql.yml@0.2.0 permissions: security-events: write packages: read @@ -23,7 +23,7 @@ jobs: contents: read analyzer: - uses: stiwicourage/powershell-ci/.github/workflows/powershell-analyzer.yml@develop + uses: stiwicourage/powershell-ci/.github/workflows/powershell-analyzer.yml@0.2.0 permissions: security-events: write actions: read @@ -31,7 +31,7 @@ jobs: dependency-review: if: ${{ github.event_name == 'pull_request' }} - uses: stiwicourage/powershell-ci/.github/workflows/dependency-review.yml@develop + uses: stiwicourage/powershell-ci/.github/workflows/dependency-review.yml@0.2.0 permissions: contents: read pull-requests: write diff --git a/.github/workflows/Tests.yml b/.github/workflows/Tests.yml index 0ebd3be..70f0525 100644 --- a/.github/workflows/Tests.yml +++ b/.github/workflows/Tests.yml @@ -18,7 +18,7 @@ permissions: jobs: tests: - uses: stiwicourage/powershell-ci/.github/workflows/tests.yml@develop + uses: stiwicourage/powershell-ci/.github/workflows/tests.yml@0.2.0 with: dependency-mode: isolated pester-required-version: '5.7.1' From 7a4101929200822e6b129cb95f7bbde54bce1c60 Mon Sep 17 00:00:00 2001 From: Stiwi Gabriel Courage Date: Sun, 15 Nov 2026 21:41:18 +0100 Subject: [PATCH 5/9] fix: Refactor CI lane execution and qualification scripts - Updated Invoke-PlatformLane.ps1 to streamline phase invocation by using hashtables for phase parameters. - Introduced new functions for initializing phase launch and handling child processes. - Enhanced error handling and logging for CI phases. - Refactored QualificationProcess.ps1 to improve child process initialization and result handling. - Simplified QualificationScenario.ps1 by modularizing plan installation and validation. - Improved test scripts to validate CI workflows and ensure proper dependency isolation. - Updated tests to reflect changes in the CI lane manifest structure and phase invocation. --- scripts/build/ci/Assert-CiGate.ps1 | 99 ++-- scripts/build/ci/CiDependencyRoot.ps1 | 17 +- scripts/build/ci/CiLaneEnvironment.ps1 | 31 +- scripts/build/ci/CiLaneManifest.ps1 | 47 +- scripts/build/ci/Install-CiPowerShell.ps1 | 126 +++-- scripts/build/ci/Invoke-PlatformLane.ps1 | 436 ++++++++++++------ .../qualification/QualificationProcess.ps1 | 37 +- .../qualification/QualificationScenario.ps1 | 137 ++++-- tests/repository/CiWorkflow.Tests.ps1 | 2 +- tests/repository/SharedCiContracts.Tests.ps1 | 10 +- .../scripts/build/ci/CiLaneManifest.Tests.ps1 | 22 +- .../build/ci/Invoke-PlatformLane.Tests.ps1 | 24 +- 12 files changed, 698 insertions(+), 290 deletions(-) diff --git a/scripts/build/ci/Assert-CiGate.ps1 b/scripts/build/ci/Assert-CiGate.ps1 index 8a32641..9f15e66 100644 --- a/scripts/build/ci/Assert-CiGate.ps1 +++ b/scripts/build/ci/Assert-CiGate.ps1 @@ -48,19 +48,29 @@ function Read-CiLaneManifest { } foreach ($file in Get-ChildItem -LiteralPath $Directory -Recurse -File -Filter 'lane-manifest.json') { - try { - $entry = Get-Content -LiteralPath $file.FullName -Raw -ErrorAction Stop | ConvertFrom-Json -AsHashtable -ErrorAction Stop - if ($entry -isnot [System.Collections.IDictionary]) { - throw 'Manifest must be a JSON object.' - } - $entry['_artifactDirectory'] = $file.Directory.FullName - $entry - } catch { - @{ - laneId = '' - readError = $_.Exception.Message - } + Read-CiLaneManifestFile -File $file + } +} + +function Read-CiLaneManifestFile { + param($File) + try { + $entry = Get-Content -LiteralPath $File.FullName -Raw -ErrorAction Stop | ConvertFrom-Json -AsHashtable -ErrorAction Stop + if ($entry -isnot [System.Collections.IDictionary]) { + throw 'Manifest must be a JSON object.' } + $entry['_artifactDirectory'] = $File.Directory.FullName + $entry + } catch { + Get-CiInvalidManifest -Message $_.Exception.Message + } +} + +function Get-CiInvalidManifest { + param([string]$Message) + return @{ + laneId = '' + readError = $Message } } @@ -77,28 +87,37 @@ function Get-CiLaneManifestFailure { if ($own.Count -ne 1) { return "Lane '$LaneId' produced $( if ($own.Count -eq 0) {'no manifest'} else {"$( $own.Count ) manifests"} )." } - if ($own[0].status -ne 'passed') { - "Lane '$LaneId' manifest status is '$( $own[0].status )'." + Get-CiLaneEntryFailure -Entry $own[0] -LaneId $LaneId -CommitSha $CommitSha -RunContext $RunContext +} + +function Get-CiLaneEntryFailure { + param($Entry, [string]$LaneId, [string]$CommitSha, $RunContext) + if ($Entry.status -ne 'passed') { + "Lane '$LaneId' manifest status is '$( $Entry.status )'." } - if ($own[0].commitSha -ne $CommitSha) { - "Lane '$LaneId' manifest belongs to commit '$( $own[0].commitSha )', not '$CommitSha'." + if ($Entry.commitSha -ne $CommitSha) { + "Lane '$LaneId' manifest belongs to commit '$( $Entry.commitSha )', not '$CommitSha'." } try { - $entry = $own[0] - $expected = @($RunContext.lanes | Where-Object id -eq $LaneId) - if ($expected.Count -ne 1) { - throw 'Lane has no unique expected configuration.' - } - $artifactName = "pmu-ci-lane-$($RunContext.runId)-$($RunContext.runAttempt)-$LaneId" - if ((Split-Path -Leaf $entry._artifactDirectory) -cne $artifactName) { - throw 'Manifest is not in its current-run named artifact directory.' - } - Assert-CiGateManifestEvidence -Manifest $entry -Expected $expected[0] -RunContext $RunContext -Directory $entry._artifactDirectory + Assert-CiLaneEntryEvidence -Entry $Entry -LaneId $LaneId -RunContext $RunContext } catch { "Lane '$LaneId' evidence is invalid: $($_.Exception.Message)" } } +function Assert-CiLaneEntryEvidence { + param($Entry, [string]$LaneId, $RunContext) + $expected = @($RunContext.lanes | Where-Object id -eq $LaneId) + if ($expected.Count -ne 1) { + throw 'Lane has no unique expected configuration.' + } + $artifactName = "pmu-ci-lane-$($RunContext.runId)-$($RunContext.runAttempt)-$LaneId" + if ((Split-Path -Leaf $Entry._artifactDirectory) -cne $artifactName) { + throw 'Manifest is not in its current-run named artifact directory.' + } + Assert-CiGateManifestEvidence -Manifest $Entry -Expected $expected[0] -RunContext $RunContext -Directory $Entry._artifactDirectory +} + function Test-CiGateResult { [CmdletBinding()] param( @@ -111,17 +130,35 @@ function Test-CiGateResult { if (-not $RunContext) { $RunContext = Get-CiGateRunContext -LanePath $LanePath } - foreach ($name in 'commitSha', 'runId', 'runAttempt') { - if ([string]::IsNullOrWhiteSpace($RunContext.$name)) { - return 'Gate requires nonempty current commit, run id and attempt.' - } + Get-CiGateResultFailure -JobResult $JobResult -ExpectedLaneId $ExpectedLaneId -ManifestDirectory $ManifestDirectory -RunContext $RunContext +} + +function Get-CiGateResultFailure { + param([hashtable]$JobResult, [string[]]$ExpectedLaneId, [string]$ManifestDirectory, $RunContext) + if (-not (Test-CiGateRunIdentity -RunContext $RunContext)) { + return 'Gate requires nonempty current commit, run id and attempt.' } $manifest = @(Read-CiLaneManifest -Directory $ManifestDirectory) Get-CiGateJobFailure -JobResult $JobResult foreach ($laneId in $ExpectedLaneId) { Get-CiLaneManifestFailure -LaneId $laneId -Manifest $manifest -CommitSha $RunContext.commitSha -RunContext $RunContext } - foreach ($entry in $manifest | Where-Object { $_.laneId -notin $ExpectedLaneId }) { + Get-CiUnexpectedManifestFailure -Manifest $manifest -ExpectedLaneId $ExpectedLaneId +} + +function Test-CiGateRunIdentity { + param($RunContext) + foreach ($name in 'commitSha', 'runId', 'runAttempt') { + if ([string]::IsNullOrWhiteSpace($RunContext.$name)) { + return $false + } + } + return $true +} + +function Get-CiUnexpectedManifestFailure { + param([object[]]$Manifest, [string[]]$ExpectedLaneId) + foreach ($entry in $Manifest | Where-Object { $_.laneId -notin $ExpectedLaneId }) { "Unexpected lane manifest '$( $entry.laneId )'." } } diff --git a/scripts/build/ci/CiDependencyRoot.ps1 b/scripts/build/ci/CiDependencyRoot.ps1 index c2cc5ee..89e7725 100644 --- a/scripts/build/ci/CiDependencyRoot.ps1 +++ b/scripts/build/ci/CiDependencyRoot.ps1 @@ -2,12 +2,7 @@ function New-CiDependencyRoot { [CmdletBinding(SupportsShouldProcess)] param([Parameter(Mandatory)][string]$Path) - if (Test-Path -LiteralPath $Path) { - throw "Dependency root already exists: '$Path'." - } - if ((Split-Path -Leaf $Path) -notlike 'pmu-ci-modules-*') { - throw 'Dependency roots must use the pmu-ci-modules- prefix.' - } + Assert-CiDependencyRootAvailable -Path $Path if (-not $PSCmdlet.ShouldProcess($Path, 'Create disposable CI dependency root')) { return } @@ -20,6 +15,16 @@ function New-CiDependencyRoot { return $owner } +function Assert-CiDependencyRootAvailable { + param([string]$Path) + if (Test-Path -LiteralPath $Path) { + throw "Dependency root already exists: '$Path'." + } + if ((Split-Path -Leaf $Path) -notlike 'pmu-ci-modules-*') { + throw 'Dependency roots must use the pmu-ci-modules- prefix.' + } +} + function Get-CiDependencyOwner { param([Parameter(Mandatory)][string]$Path) diff --git a/scripts/build/ci/CiLaneEnvironment.ps1 b/scripts/build/ci/CiLaneEnvironment.ps1 index 6689d55..be38f55 100644 --- a/scripts/build/ci/CiLaneEnvironment.ps1 +++ b/scripts/build/ci/CiLaneEnvironment.ps1 @@ -13,13 +13,28 @@ function Get-CiLaneEnvironment { [CmdletBinding()] param() + $environment = Get-CiRuntimeEnvironment + foreach ($entry in (Get-CiRunnerEnvironment).GetEnumerator()) { + $environment[$entry.Key] = $entry.Value + } + return [pscustomobject]$environment +} + +function Get-CiRuntimeEnvironment { + param() $runtime = [System.Runtime.InteropServices.RuntimeInformation] - return [pscustomobject][ordered]@{ + return [ordered]@{ OperatingSystem = Get-CiLaneOperatingSystem OsArchitecture = $runtime::OSArchitecture.ToString() ProcessArchitecture = $runtime::ProcessArchitecture.ToString() PowerShellVersion = $PSVersionTable.PSVersion.ToString() PowerShellEdition = $PSVersionTable.PSEdition + } +} + +function Get-CiRunnerEnvironment { + param() + return [ordered]@{ RunnerOs = $env:RUNNER_OS RunnerArch = $env:RUNNER_ARCH RunnerEnvironment = $env:RUNNER_ENVIRONMENT @@ -76,12 +91,22 @@ function Test-CiLaneEnvironment { [switch]$RequireGitHubHosted ) + Get-CiRuntimeMismatch -Expected $Expected -Actual $Actual + Get-CiChannelMismatch -Channel $Expected.PowerShellChannel -Version $Actual.PowerShellVersion + Get-CiRunnerMismatch -Expected $Expected -Actual $Actual + Get-CiHostMismatch -Actual $Actual -RequireGitHubHosted:$RequireGitHubHosted +} + +function Get-CiRuntimeMismatch { + param($Expected, $Actual) Get-CiEqualityMismatch -Label 'Operating system' -Actual $Actual.OperatingSystem -Expected $Expected.OperatingSystem Get-CiEqualityMismatch -Label 'OS architecture' -Actual $Actual.OsArchitecture -Expected $Expected.Architecture Get-CiEqualityMismatch -Label 'Process architecture' -Actual $Actual.ProcessArchitecture -Expected $Expected.Architecture Get-CiEqualityMismatch -Label 'PowerShell version' -Actual $Actual.PowerShellVersion -Expected $Expected.PowerShellVersion - Get-CiChannelMismatch -Channel $Expected.PowerShellChannel -Version $Actual.PowerShellVersion - Get-CiRunnerMismatch -Expected $Expected -Actual $Actual +} + +function Get-CiHostMismatch { + param($Actual, [switch]$RequireGitHubHosted) if ($Actual.PowerShellEdition -ne 'Core') { "PowerShell edition is '$( $Actual.PowerShellEdition )' but 'Core' is required." } diff --git a/scripts/build/ci/CiLaneManifest.ps1 b/scripts/build/ci/CiLaneManifest.ps1 index 41ad47d..ed1d2c8 100644 --- a/scripts/build/ci/CiLaneManifest.ps1 +++ b/scripts/build/ci/CiLaneManifest.ps1 @@ -34,40 +34,47 @@ function Get-CiLaneStatus { [Parameter(Mandatory)][hashtable]$Summary ) + $check = @(Get-CiLaneHealthCheck -Mismatch $Mismatch -Phase $Phase -Summary $Summary) + if ($check -notcontains $false) { + return 'passed' + } + + return 'failed' +} + +function Get-CiLaneHealthCheck { + param([string[]]$Mismatch, [object[]]$Phase, [hashtable]$Summary) $phaseHealthy = @('build', 'unit', 'integration' | Where-Object { -not (Test-CiPhaseSucceeded -Phase $Phase -Name $_) }).Count -eq 0 $summaryHealthy = (Test-CiSummaryHealthy -Summary $Summary -Key 'unit') -and (Test-CiSummaryHealthy -Summary $Summary -Key 'integration') - $check = @( + return @( @($Mismatch).Count -eq 0 $phaseHealthy $summaryHealthy ) - if ($check -notcontains $false) { - return 'passed' - } - - return 'failed' } function Build-CiLaneManifest { [CmdletBinding()] param( - [Parameter(Mandatory)][string]$LaneId, - [Parameter(Mandatory)][string]$CommitSha, - [Parameter(Mandatory)]$Environment, - [string[]]$Mismatch = @(), - [Parameter(Mandatory)][AllowEmptyCollection()][object[]]$Phase, - [Parameter(Mandatory)][hashtable]$Summary, + [Parameter(Mandatory)][hashtable]$Run, [Parameter(Mandatory)][hashtable]$Module ) + $manifest = Get-CiLaneManifestIdentity -Run $Run + $manifest['mismatches'] = @($Run.Mismatch) + $manifest['phases'] = @($Run.Phase) + $manifest['tests'] = $Run.Summary + $manifest['modules'] = $Module + return $manifest +} + +function Get-CiLaneManifestIdentity { + # Run is the existing lane execution record: Lane, Identity, Actual, Mismatch, Phase and Summary. + param([hashtable]$Run) return [ordered]@{ - laneId = $LaneId - commitSha = $CommitSha - status = Get-CiLaneStatus -Mismatch $Mismatch -Phase $Phase -Summary $Summary - environment = $Environment - mismatches = @($Mismatch) - phases = @($Phase) - tests = $Summary - modules = $Module + laneId = $Run.Lane.id + commitSha = $Run.Identity.commitSha + status = Get-CiLaneStatus -Mismatch $Run.Mismatch -Phase $Run.Phase -Summary $Run.Summary + environment = $Run.Actual } } diff --git a/scripts/build/ci/Install-CiPowerShell.ps1 b/scripts/build/ci/Install-CiPowerShell.ps1 index f9302b0..dbb8298 100644 --- a/scripts/build/ci/Install-CiPowerShell.ps1 +++ b/scripts/build/ci/Install-CiPowerShell.ps1 @@ -18,10 +18,15 @@ function Get-CiPowerShellAssetName { [Parameter(Mandatory)][string]$RuntimeIdentifier ) + if ($RuntimeIdentifier -eq 'win-x64') { + return "PowerShell-$Version-win-x64.zip" + } + return Get-CiUnixPowerShellAssetName -Version $Version -RuntimeIdentifier $RuntimeIdentifier +} + +function Get-CiUnixPowerShellAssetName { + param([string]$Version, [string]$RuntimeIdentifier) switch ($RuntimeIdentifier) { - 'win-x64' { - return "PowerShell-$Version-win-x64.zip" - } 'linux-x64' { return "powershell-$Version-linux-x64.tar.gz" } @@ -42,18 +47,23 @@ function Get-CiPinnedPowerShellRelease { [Parameter(Mandatory)][string]$RuntimeIdentifier ) + $pin = Get-CiPowerShellPin -PinPath $PinPath -Channel $Channel + return [pscustomobject]@{ + Version = $pin.version + FileName = Get-CiPowerShellAssetName -Version $pin.version -RuntimeIdentifier $RuntimeIdentifier + Sha256 = $pin.sha256[$RuntimeIdentifier] + HashSource = 'pinned in repository' + } +} + +function Get-CiPowerShellPin { + param([string]$PinPath, [string]$Channel) $pin = (Get-Content -LiteralPath $PinPath -Raw | ConvertFrom-Json -AsHashtable).channels if (-not $pin.ContainsKey($Channel)) { throw "PowerShell channel '$Channel' is not pinned in '$PinPath'." } - $version = $pin[$Channel].version - return [pscustomobject]@{ - Version = $version - FileName = Get-CiPowerShellAssetName -Version $version -RuntimeIdentifier $RuntimeIdentifier - Sha256 = $pin[$Channel].sha256[$RuntimeIdentifier] - HashSource = 'pinned in repository' - } + return $pin[$Channel] } function Get-CiExpectedSha256 { @@ -105,16 +115,27 @@ function Get-CiStablePowerShellRelease { [Parameter(Mandatory)][string]$WorkDirectory ) + $release = Get-CiStableReleaseInfo -RuntimeIdentifier $RuntimeIdentifier -WorkDirectory $WorkDirectory + return [pscustomobject]@{ + Version = $release.Version + FileName = $release.FileName + Sha256 = Get-CiExpectedSha256 -HashLine $release.HashLine -FileName $release.FileName + HashSource = $release.HashSource + } +} + +function Get-CiStableReleaseInfo { + param([string]$RuntimeIdentifier, [string]$WorkDirectory) $tag = (Invoke-RestMethod -Uri $script:PowerShellMetadataUri).StableReleaseTag $version = Resolve-CiPowerShellVersionTag -Tag $tag $hashFile = Join-Path $WorkDirectory 'hashes.sha256' Invoke-WebRequest -Uri "$script:PowerShellReleaseBase/$tag/hashes.sha256" -OutFile $hashFile $fileName = Get-CiPowerShellAssetName -Version $version -RuntimeIdentifier $RuntimeIdentifier - return [pscustomobject]@{ + return @{ Version = $version FileName = $fileName - Sha256 = Get-CiExpectedSha256 -HashLine @(Get-Content -LiteralPath $hashFile) -FileName $fileName + HashLine = @(Get-Content -LiteralPath $hashFile) HashSource = "hashes.sha256 of release $tag" } } @@ -132,6 +153,11 @@ function Expand-CiPowerShellArchive { return } + Invoke-CiTarExtraction -Archive $Archive -Destination $Destination +} + +function Invoke-CiTarExtraction { + param([string]$Archive, [string]$Destination) & tar -xzf $Archive -C $Destination if ($LASTEXITCODE -ne 0) { throw "Extracting '$Archive' failed with exit code $LASTEXITCODE." @@ -149,26 +175,41 @@ function Install-CiPowerShell { ) New-Item -ItemType Directory -Path $InstallRoot -Force | Out-Null - $release = if ($Channel -eq 'stable') { + $release = Resolve-CiPowerShellRelease -Channel $Channel -RuntimeIdentifier $RuntimeIdentifier -InstallRoot $InstallRoot -PinPath $PinPath + $directory = Save-CiPowerShellArchive -Release $release -InstallRoot $InstallRoot + return Get-CiPowerShellInstallationRecord -Channel $Channel -RuntimeIdentifier $RuntimeIdentifier -Release $release -Directory $directory +} + +function Resolve-CiPowerShellRelease { + param([string]$Channel, [string]$RuntimeIdentifier, [string]$InstallRoot, [string]$PinPath) + if ($Channel -eq 'stable') { Get-CiStablePowerShellRelease -RuntimeIdentifier $RuntimeIdentifier -WorkDirectory $InstallRoot } else { Get-CiPinnedPowerShellRelease -PinPath $PinPath -Channel $Channel -RuntimeIdentifier $RuntimeIdentifier } - $archive = Join-Path $InstallRoot $release.FileName - Invoke-WebRequest -Uri "$script:PowerShellReleaseBase/v$( $release.Version )/$( $release.FileName )" -OutFile $archive - Assert-CiFileHash -Path $archive -ExpectedSha256 $release.Sha256 - $directory = Join-Path $InstallRoot "powershell-$( $release.Version )" +} + +function Save-CiPowerShellArchive { + param($Release, [string]$InstallRoot) + $archive = Join-Path $InstallRoot $Release.FileName + Invoke-WebRequest -Uri "$script:PowerShellReleaseBase/v$( $Release.Version )/$( $Release.FileName )" -OutFile $archive + Assert-CiFileHash -Path $archive -ExpectedSha256 $Release.Sha256 + $directory = Join-Path $InstallRoot "powershell-$( $Release.Version )" Expand-CiPowerShellArchive -Archive $archive -Destination $directory + return $directory +} +function Get-CiPowerShellInstallationRecord { + param([string]$Channel, [string]$RuntimeIdentifier, $Release, [string]$Directory) return [pscustomobject][ordered]@{ channel = $Channel - version = $release.Version + version = $Release.Version runtimeIdentifier = $RuntimeIdentifier - fileName = $release.FileName - sha256 = $release.Sha256 - hashSource = $release.HashSource - directory = $directory + fileName = $Release.FileName + sha256 = $Release.Sha256 + hashSource = $Release.HashSource + directory = $Directory } } @@ -178,31 +219,47 @@ function Assert-CiInstalledPowerShell { [Parameter(Mandatory)]$Installation ) + $record = Read-CiRuntimeProbe -Executable (Get-CiInstalledPowerShellExecutable -Installation $Installation) + $expected = Get-CiInstalledPowerShellExpectation -Installation $Installation -Record $record + Assert-CiRuntimeRecord -Record $record -Expected $expected + $Installation | Add-Member -NotePropertyName executable -NotePropertyValue $record.Executable -Force + $Installation | Add-Member -NotePropertyName runtime -NotePropertyValue $record -Force +} + +function Get-CiInstalledPowerShellExecutable { + param($Installation) $name = if ($Installation.runtimeIdentifier -like 'win-*') { 'pwsh.exe' } else { 'pwsh' } - $record = Read-CiRuntimeProbe -Executable (Join-Path $Installation.directory $name) + return Join-Path $Installation.directory $name +} + +function Get-CiProvisioningPlatform { + param([string]$RuntimeIdentifier) $runtime = @{ 'win-x64' = @('Windows', 'X64') 'linux-x64' = @('Linux', 'X64') 'osx-arm64' = @('macOS', 'Arm64') } - $platform = $runtime[$Installation.runtimeIdentifier] + $platform = $runtime[$RuntimeIdentifier] if (-not $platform) { throw 'Unsupported provisioning runtime.' } - $expected = @{ + return $platform +} + +function Get-CiInstalledPowerShellExpectation { + param($Installation, $Record) + $platform = Get-CiProvisioningPlatform -RuntimeIdentifier $Installation.runtimeIdentifier + return @{ OperatingSystem = $platform[0] Architecture = $platform[1] PowerShellVersion = $Installation.version PowerShellChannel = $Installation.channel - Executable = $record.Executable + Executable = $Record.Executable } - Assert-CiRuntimeRecord -Record $record -Expected $expected - $Installation | Add-Member -NotePropertyName executable -NotePropertyValue $record.Executable -Force - $Installation | Add-Member -NotePropertyName runtime -NotePropertyValue $record -Force } function Publish-CiPowerShellInstallation { @@ -212,6 +269,14 @@ function Publish-CiPowerShellInstallation { [string]$ProvisioningFile ) + Publish-CiPowerShellEnvironment -Installation $Installation + if ($ProvisioningFile) { + $Installation | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath $ProvisioningFile + } +} + +function Publish-CiPowerShellEnvironment { + param($Installation) if ($env:GITHUB_PATH) { Add-Content -LiteralPath $env:GITHUB_PATH -Value $Installation.directory } @@ -219,9 +284,6 @@ function Publish-CiPowerShellInstallation { Add-Content -LiteralPath $env:GITHUB_OUTPUT -Value "version=$( $Installation.version )" Add-Content -LiteralPath $env:GITHUB_OUTPUT -Value "executable=$( $Installation.executable )" } - if ($ProvisioningFile) { - $Installation | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath $ProvisioningFile - } } if ($MyInvocation.InvocationName -ne '.') { diff --git a/scripts/build/ci/Invoke-PlatformLane.ps1 b/scripts/build/ci/Invoke-PlatformLane.ps1 index 07c203c..d8dd4be 100644 --- a/scripts/build/ci/Invoke-PlatformLane.ps1 +++ b/scripts/build/ci/Invoke-PlatformLane.ps1 @@ -32,39 +32,69 @@ function Get-CiLaneDefinition { function Invoke-CiLanePhase { [CmdletBinding()] param( - [Parameter(Mandatory)][string]$Name, - [Parameter(Mandatory)][string]$Command, - [Parameter(Mandatory)][string]$LogPath, - [Parameter(Mandatory)][string]$WorkingDirectory, + [Parameter(Mandatory)][hashtable]$Phase, $Context ) $watch = [System.Diagnostics.Stopwatch]::StartNew() - $launch = Get-CiPhaseContext -Name $Name -LogPath $LogPath -Context $Context - $launch.WorkingDirectory = $WorkingDirectory - $launch.Command = $Command - $contextFile = "$LogPath.context.json" + $launch = Initialize-CiPhaseLaunch -Phase $Phase -Context $Context + $exitCode = Invoke-CiPhaseChild -Launch $launch -LogPath $Phase.LogPath + return Get-CiPhaseResult -Phase $Phase -Launch $launch -Watch $watch -ExitCode $exitCode +} + +function Initialize-CiPhaseLaunch { + # Phase contains Name, Command, LogPath and WorkingDirectory for one child process. + param([hashtable]$Phase, $Context) + $launch = Get-CiPhaseContext -Name $Phase.Name -LogPath $Phase.LogPath -Context $Context + $launch.WorkingDirectory = $Phase.WorkingDirectory + $launch.Command = $Phase.Command + $contextFile = "$($Phase.LogPath).context.json" $launch | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $contextFile - & $launch.Expected.Executable -NoLogo -NoProfile -File (Join-Path $PSScriptRoot 'Invoke-CiPhaseProcess.ps1') -ContextFile $contextFile 2>&1 | + return $launch +} + +function Invoke-CiPhaseChild { + param($Launch, [string]$LogPath) + $contextFile = "$LogPath.context.json" + & $Launch.Expected.Executable -NoLogo -NoProfile -File (Join-Path $PSScriptRoot 'Invoke-CiPhaseProcess.ps1') -ContextFile $contextFile 2>&1 | Tee-Object -FilePath $LogPath | Out-Host - $exitCode = $LASTEXITCODE - $runtime = if (Test-Path -LiteralPath $launch.RuntimePath) { - Get-Content -LiteralPath $launch.RuntimePath -Raw | ConvertFrom-Json - } + return $LASTEXITCODE +} - return [pscustomobject][ordered]@{ - Name = $Name - ExitCode = $exitCode - DurationSeconds = [math]::Round($watch.Elapsed.TotalSeconds, 1) - LogFile = Split-Path -Leaf $LogPath - RuntimeFile = Split-Path -Leaf $launch.RuntimePath - TestRuntimeFile = Split-Path -Leaf $launch.TestRuntimePath +function Get-CiPhaseProcessEvidence { + param($Launch) + $runtime = if (Test-Path -LiteralPath $Launch.RuntimePath) { + Get-Content -LiteralPath $Launch.RuntimePath -Raw | ConvertFrom-Json + } + return [ordered]@{ Environment = $runtime.Environment Executable = $runtime.Executable ProcessId = $runtime.ProcessId } } +function Get-CiPhaseResult { + param([hashtable]$Phase, $Launch, $Watch, [int]$ExitCode) + $evidence = Get-CiPhaseProcessEvidence -Launch $Launch + $result = [ordered]@{ + Name = $Phase.Name + ExitCode = $ExitCode + DurationSeconds = [math]::Round($Watch.Elapsed.TotalSeconds, 1) + LogFile = Split-Path -Leaf $Phase.LogPath + RuntimeFile = Split-Path -Leaf $Launch.RuntimePath + TestRuntimeFile = Split-Path -Leaf $Launch.TestRuntimePath + } + return ConvertTo-CiPhaseResultObject -Result $result -Evidence $evidence +} + +function ConvertTo-CiPhaseResultObject { + param([System.Collections.Specialized.OrderedDictionary]$Result, $Evidence) + foreach ($entry in $Evidence.GetEnumerator()) { + $Result[$entry.Key] = $entry.Value + } + return [pscustomobject]$Result +} + function Get-CiPhaseContext { param( [string]$Name, @@ -73,23 +103,33 @@ function Get-CiPhaseContext { ) if (-not $Context) { - $actual = Get-CiRuntimeRecord - $Context = @{ - Expected = @{ - OperatingSystem = $actual.Environment.OperatingSystem - Architecture = $actual.Environment.ProcessArchitecture - PowerShellVersion = $actual.Environment.PowerShellVersion - PowerShellChannel = 'stable' - Executable = $actual.Executable - } - Identity = @{} - } + $Context = Get-CiDefaultPhaseContext } $identity = @{} + $Context.Identity $identity.phase = $Name + return Get-CiPhaseLaunchRecord -Expected $Context.Expected -Identity $identity -LogPath $LogPath +} + +function Get-CiDefaultPhaseContext { + param() + $actual = Get-CiRuntimeRecord return @{ - Expected = $Context.Expected - Identity = $identity + Expected = @{ + OperatingSystem = $actual.Environment.OperatingSystem + Architecture = $actual.Environment.ProcessArchitecture + PowerShellVersion = $actual.Environment.PowerShellVersion + PowerShellChannel = 'stable' + Executable = $actual.Executable + } + Identity = @{} + } +} + +function Get-CiPhaseLaunchRecord { + param($Expected, $Identity, [string]$LogPath) + return @{ + Expected = $Expected + Identity = $Identity RuntimePath = "$LogPath.runtime.json" TestRuntimePath = "$LogPath.test-runtime.json" } @@ -113,21 +153,20 @@ function Get-CiLanePhaseDefinition { param() return @( - @{ - Name = 'build' - Command = 'Import-Module Pester -RequiredVersion 5.7.1; Import-Module NovaModuleTools -ErrorAction Stop; Invoke-NovaBuild' - } - @{ - Name = 'unit' - Command = 'Import-Module Pester -RequiredVersion 5.7.1; Import-Module NovaModuleTools -ErrorAction Stop; Invoke-NovaTest -OutputVerbosity Detailed -OutputRenderMode Ansi' - } - @{ - Name = 'integration' - Command = 'Import-Module Pester -RequiredVersion 5.7.1; Import-Module NovaModuleTools -ErrorAction Stop; Test-NovaBuild -OutputVerbosity Detailed -OutputRenderMode Ansi' - } + Get-CiPhaseDefinition -Name 'build' -Command 'Import-Module Pester -RequiredVersion 5.7.1; Import-Module NovaModuleTools -ErrorAction Stop; Invoke-NovaBuild' + Get-CiPhaseDefinition -Name 'unit' -Command 'Import-Module Pester -RequiredVersion 5.7.1; Import-Module NovaModuleTools -ErrorAction Stop; Invoke-NovaTest -OutputVerbosity Detailed -OutputRenderMode Ansi' + Get-CiPhaseDefinition -Name 'integration' -Command 'Import-Module Pester -RequiredVersion 5.7.1; Import-Module NovaModuleTools -ErrorAction Stop; Test-NovaBuild -OutputVerbosity Detailed -OutputRenderMode Ansi' ) } +function Get-CiPhaseDefinition { + param([string]$Name, [string]$Command) + return @{ + Name = $Name + Command = $Command + } +} + function Invoke-CiLanePhaseSet { [CmdletBinding()] param( @@ -136,10 +175,15 @@ function Invoke-CiLanePhaseSet { [Parameter(Mandatory)]$Context ) + return Invoke-CiLanePhaseSequence -RepositoryRoot $RepositoryRoot -LogDirectory $LogDirectory -Context $Context +} + +function Invoke-CiLanePhaseSequence { + param([string]$RepositoryRoot, [string]$LogDirectory, $Context) $result = @() foreach ($definition in Get-CiLanePhaseDefinition) { - $log = Join-Path $LogDirectory "$( $definition.Name ).log" - $result += Invoke-CiLanePhase -Name $definition.Name -Command $definition.Command -LogPath $log -WorkingDirectory $RepositoryRoot -Context $Context + $phase = Get-CiPhaseInvocation -Definition $definition -RepositoryRoot $RepositoryRoot -LogDirectory $LogDirectory + $result += Invoke-CiLanePhase -Phase $phase -Context $Context if ($result[-1].ExitCode -ne 0) { break } @@ -148,6 +192,16 @@ function Invoke-CiLanePhaseSet { return $result } +function Get-CiPhaseInvocation { + param($Definition, [string]$RepositoryRoot, [string]$LogDirectory) + return @{ + Name = $Definition.Name + Command = $Definition.Command + LogPath = Join-Path $LogDirectory "$( $Definition.Name ).log" + WorkingDirectory = $RepositoryRoot + } +} + function Copy-CiTestResult { [CmdletBinding()] param( @@ -156,24 +210,47 @@ function Copy-CiTestResult { ) $summary = @{} - $source = [ordered]@{ + $source = Get-CiTestResultSource + $paths = Get-CiTestResultLocation -RepositoryRoot $RepositoryRoot -OutputDirectory $OutputDirectory + foreach ($key in $source.Keys) { + Copy-CiTestResultEntry -Key $key -Source $source[$key] -Summary $summary -Paths $paths + } + return $summary +} + +function Get-CiTestResultSource { + param() + return [ordered]@{ unit = @('artifacts/UnitTestResults.xml', 'unit-nunit.xml') integration = @('artifacts/TestResults.xml', 'integration-nunit.xml') } - foreach ($key in $source.Keys) { - $path = Join-Path $RepositoryRoot $source[$key][0] - if (Test-Path -LiteralPath $path) { - Copy-Item -LiteralPath $path -Destination (Join-Path $OutputDirectory $source[$key][1]) - $summary[$key] = Get-CiTestResultSummary -Path $path - $log = Join-Path $OutputDirectory "logs/$key.log" - $detail = @(Read-CiTestDetail -Path $log) - Assert-CiTestDetail -Summary $summary[$key] -Detail $detail -OperatingSystem (Get-CiLaneOperatingSystem) - $detail | ConvertTo-Json -Depth 4 -AsArray | Set-Content -LiteralPath (Join-Path $OutputDirectory "$key-details.json") - $summary[$key].SkippedName = @($detail | Where-Object Result -eq 'Skipped' | ForEach-Object { "$($_.File): $($_.Name)" }) - } +} + +function Get-CiTestResultLocation { + param([string]$RepositoryRoot, [string]$OutputDirectory) + return @{ + RepositoryRoot = $RepositoryRoot + OutputDirectory = $OutputDirectory } +} - return $summary +function Copy-CiTestResultEntry { + param([string]$Key, [string[]]$Source, [hashtable]$Summary, [hashtable]$Paths) + $path = Join-Path $Paths.RepositoryRoot $Source[0] + if (Test-Path -LiteralPath $path) { + Copy-Item -LiteralPath $path -Destination (Join-Path $Paths.OutputDirectory $Source[1]) + $Summary[$Key] = Get-CiTestResultSummary -Path $path + Save-CiTestResultDetail -Summary $Summary[$Key] -Key $Key -OutputDirectory $Paths.OutputDirectory + } +} + +function Save-CiTestResultDetail { + param($Summary, [string]$Key, [string]$OutputDirectory) + $log = Join-Path $OutputDirectory "logs/$Key.log" + $detail = @(Read-CiTestDetail -Path $log) + Assert-CiTestDetail -Summary $Summary -Detail $detail -OperatingSystem (Get-CiLaneOperatingSystem) + $detail | ConvertTo-Json -Depth 4 -AsArray | Set-Content -LiteralPath (Join-Path $OutputDirectory "$Key-details.json") + $Summary.SkippedName = @($detail | Where-Object Result -eq 'Skipped' | ForEach-Object { "$($_.File): $($_.Name)" }) } function Write-CiLaneSummary { @@ -182,21 +259,31 @@ function Write-CiLaneSummary { [Parameter(Mandatory)]$Manifest ) + $line = @(Get-CiLaneSummaryLine -Manifest $Manifest) + if ($env:GITHUB_STEP_SUMMARY) { + Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY -Value $line + } + $line | Out-Host +} + +function Get-CiLaneSummaryLine { + param($Manifest) $line = @("### $( $Manifest.laneId ): $( $Manifest.status )", '') $line += $Manifest.mismatches | ForEach-Object { "- Environment mismatch: $_" } $line += $Manifest.phases | ForEach-Object { "- $( $_.Name ): exit code $( $_.ExitCode ), $( $_.DurationSeconds )s" } foreach ($key in $Manifest.tests.Keys) { - $test = $Manifest.tests[$key] - $line += "- $key tests: $( $test.Passed ) passed, $( $test.Failed ) failed, $( $test.Skipped ) skipped" - $line += $test.SkippedName | ForEach-Object { " - skipped (see test source and logs for the reason): $_" } - if ($test.Skipped -gt 0 -and @($test.SkippedName).Count -eq 0) { - $line += " - skipped tests are not named in the report; see logs/*.log ([!] lines) and the test source for the reason" - } + $line += Get-CiLaneTestSummaryLine -Key $key -Test $Manifest.tests[$key] } - if ($env:GITHUB_STEP_SUMMARY) { - Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY -Value $line + return $line +} + +function Get-CiLaneTestSummaryLine { + param([string]$Key, $Test) + "- $Key tests: $( $Test.Passed ) passed, $( $Test.Failed ) failed, $( $Test.Skipped ) skipped" + $Test.SkippedName | ForEach-Object { " - skipped (see test source and logs for the reason): $_" } + if ($Test.Skipped -gt 0 -and @($Test.SkippedName).Count -eq 0) { + " - skipped tests are not named in the report; see logs/*.log ([!] lines) and the test source for the reason" } - $line | Out-Host } function Get-CiLaneIdentity { @@ -206,20 +293,29 @@ function Get-CiLaneIdentity { laneId = $LaneId executionId = [guid]::NewGuid().ToString('N') } - $defaults = @{ + $defaults = Get-CiLaneIdentityDefault + foreach ($name in $defaults.Keys) { + $identity[$name] = Get-CiLaneIdentityValue -Name $defaults[$name][0] -Default $defaults[$name][1] + } + return $identity +} + +function Get-CiLaneIdentityDefault { + param() + return @{ commitSha = @('GITHUB_SHA', 'local') runId = @('GITHUB_RUN_ID', 'local') runAttempt = @('GITHUB_RUN_ATTEMPT', '1') } - foreach ($name in $defaults.Keys) { - $value = [Environment]::GetEnvironmentVariable($defaults[$name][0]) - $identity[$name] = if ($value) { - $value - } else { - $defaults[$name][1] - } +} + +function Get-CiLaneIdentityValue { + param([string]$Name, [string]$Default) + $value = [Environment]::GetEnvironmentVariable($Name) + if ($value) { + return $value } - return $identity + return $Default } function Get-CiLaneRun { @@ -232,33 +328,49 @@ function Get-CiLaneRun { $lane = Get-CiLaneDefinition -LaneId $LaneId $actual = Get-CiLaneEnvironment + $expected = Get-CiLaneExpectation -Lane $lane -Actual $actual -Version $Version + $run = Get-CiLaneRunIdentity -Lane $lane -Actual $actual -Expected $expected -LaneId $LaneId + Initialize-CiLaneRunLocation -Run $run -RepositoryRoot $RepositoryRoot -ProvisioningFile $ProvisioningFile + return $run +} + +function Get-CiLaneExpectation { + param($Lane, $Actual, [string]$Version) if (-not $Version) { - $Version = $actual.PowerShellVersion + $Version = $Actual.PowerShellVersion } - $expected = @{ - OperatingSystem = $lane.os - Architecture = $lane.architecture - PowerShellChannel = $lane.powershell + return @{ + OperatingSystem = $Lane.os + Architecture = $Lane.architecture + PowerShellChannel = $Lane.powershell PowerShellVersion = $Version Executable = (Get-Process -Id $PID).Path } - $output = Join-Path $RepositoryRoot "artifacts/ci/$LaneId" +} + +function Get-CiLaneRunIdentity { + param($Lane, $Actual, $Expected, [string]$LaneId) return @{ - Lane = $lane - Actual = $actual - Expected = $expected + Lane = $Lane + Actual = $Actual + Expected = $Expected Identity = Get-CiLaneIdentity -LaneId $LaneId - RepositoryRoot = $RepositoryRoot - Output = $output - Logs = Join-Path $output 'logs' - ProvisioningFile = $ProvisioningFile - Provisioning = $null - Phase = @() - Summary = @() - Mismatch = @() } } +function Initialize-CiLaneRunLocation { + param([hashtable]$Run, [string]$RepositoryRoot, [string]$ProvisioningFile) + $output = Join-Path $RepositoryRoot "artifacts/ci/$($Run.Identity.laneId)" + $Run.RepositoryRoot = $RepositoryRoot + $Run.Output = $output + $Run.Logs = Join-Path $output 'logs' + $Run.ProvisioningFile = $ProvisioningFile + $Run.Provisioning = $null + $Run.Phase = @() + $Run.Summary = @() + $Run.Mismatch = @() +} + function Initialize-CiLaneArtifact { param([Parameter(Mandatory)][hashtable]$Run) @@ -297,22 +409,27 @@ function Invoke-CiLaneExecution { return } try { - Assert-CiLaneProvisioning -Run $Run - $Run.Phase = Invoke-CiLanePhaseSet -RepositoryRoot $Run.RepositoryRoot -LogDirectory $Run.Logs -Context @{ - Expected = $Run.Expected - Identity = $Run.Identity - } - $Run.Summary = Copy-CiTestResult -RepositoryRoot $Run.RepositoryRoot -OutputDirectory $Run.Output - Assert-CiLaneRuntimeEvidence -Directory $Run.Logs -Phase $Run.Phase -Expected $Run.Expected -Identity $Run.Identity + Invoke-CiLaneValidatedPhaseSet -Run $Run } catch { $Run.Mismatch += $_.Exception.Message } } +function Invoke-CiLaneValidatedPhaseSet { + param([hashtable]$Run) + Assert-CiLaneProvisioning -Run $Run + $Run.Phase = Invoke-CiLanePhaseSet -RepositoryRoot $Run.RepositoryRoot -LogDirectory $Run.Logs -Context @{ + Expected = $Run.Expected + Identity = $Run.Identity + } + $Run.Summary = Copy-CiTestResult -RepositoryRoot $Run.RepositoryRoot -OutputDirectory $Run.Output + Assert-CiLaneRuntimeEvidence -Directory $Run.Logs -Phase $Run.Phase -Expected $Run.Expected -Identity $Run.Identity +} + function Write-CiLaneManifest { param([Parameter(Mandatory)][hashtable]$Run) - $manifest = Build-CiLaneManifest -LaneId $Run.Lane.id -CommitSha $Run.Identity.commitSha -Environment $Run.Actual -Mismatch $Run.Mismatch -Phase $Run.Phase -Summary $Run.Summary -Module (Get-CiModuleVersion) + $manifest = Build-CiLaneManifest -Run $Run -Module (Get-CiModuleVersion) $manifest.schemaVersion = 1 $manifest.configuration = $Run.Lane $manifest.selectedRuntime = $Run.Expected @@ -338,45 +455,98 @@ function Invoke-CiLane { return Write-CiLaneManifest -Run $run } -if ($MyInvocation.InvocationName -ne '.') { +function Initialize-CiLaneScratch { + param() $scratch = Join-Path ([System.IO.Path]::GetTempPath()) "pmu-lane-$( [guid]::NewGuid().ToString('N') )" New-Item -ItemType Directory -Path $scratch | Out-Null + $saved = Get-CiLaneSavedEnvironment + $env:TMPDIR = $env:TEMP = $env:TMP = $scratch + Remove-Item Env:PMU_QUALIFICATION_LIVE -ErrorAction SilentlyContinue + return @{ + Path = $scratch + Saved = $saved + } +} + +function Get-CiLaneSavedEnvironment { + param() $saved = @{} foreach ($key in 'TMPDIR', 'TEMP', 'TMP', 'PATH', 'PSModulePath', 'PMU_QUALIFICATION_LIVE', 'PMU_CI_TEST_RUNTIME_PATH', 'PMU_CI_RUNTIME_CONTEXT') { $saved[$key] = [Environment]::GetEnvironmentVariable($key) } - $env:TMPDIR = $env:TEMP = $env:TMP = $scratch - Remove-Item Env:PMU_QUALIFICATION_LIVE -ErrorAction SilentlyContinue + return $saved +} + +function Invoke-CiPlatformLane { + param([hashtable]$Options) + $scratch = Initialize-CiLaneScratch try { - if (-not $ModuleRoot) { - $ModuleRoot = Join-Path $scratch "pmu-ci-modules-$([guid]::NewGuid().ToString('N'))" - & (Get-Process -Id $PID).Path -NoLogo -NoProfile -File (Join-Path $PSScriptRoot 'Install-CiPowerShellModules.ps1') -ModuleRoot $ModuleRoot - if ($LASTEXITCODE -ne 0) { - throw 'Disposable dependency provisioning failed.' - } - } - $owner = Get-CiDependencyOwner -Path $ModuleRoot - $env:PSModulePath = Get-CiIsolatedModulePath -ModuleRoot $owner.Path - $env:PATH = (Split-Path -Parent (Get-Process -Id $PID).Path) + [IO.Path]::PathSeparator + $saved.PATH - $resolved = (Get-Command pwsh -CommandType Application -ErrorAction Stop | Select-Object -First 1).Source - if ($resolved -ne (Get-Process -Id $PID).Path) { - throw 'pwsh command resolution does not match the selected executable.' - } - & (Get-Process -Id $PID).Path -NoLogo -NoProfile -File (Join-Path $PSScriptRoot 'CiDependencyProbe.ps1') -ModuleRoot $owner.Path - if ($LASTEXITCODE -ne 0) { - throw 'Dependency validation failed.' - } - $status = Invoke-CiLane -LaneId $LaneId -ExpectedPowerShellVersion $ExpectedPowerShellVersion -ProvisioningFile $ProvisioningFile -RepositoryRoot $RepositoryRoot + Initialize-CiLaneModuleOwner -Options $Options -Scratch $scratch + $owner = $Options.Owner + Initialize-CiLaneProcessEnvironment -Owner $owner -Saved $scratch.Saved + Assert-CiLaneDependencyProbe -ModuleRoot $owner.Path + $Options.Status = Invoke-CiLane -LaneId $Options.LaneId -ExpectedPowerShellVersion $Options.ExpectedPowerShellVersion -ProvisioningFile $Options.ProvisioningFile -RepositoryRoot $Options.RepositoryRoot } finally { - foreach ($key in $saved.Keys) { - [Environment]::SetEnvironmentVariable($key, $saved[$key]) - } - if ($owner) { - Remove-CiDependencyRoot -Owner $owner - } - Remove-Item -LiteralPath $scratch -Recurse -Force -ErrorAction Stop + Restore-CiLaneScratch -Scratch $scratch -Owner $owner + } +} + +function Initialize-CiLaneModuleOwner { + param([hashtable]$Options, $Scratch) + if (-not $Options.ModuleRoot) { + $Options.ModuleRoot = Join-Path $Scratch.Path "pmu-ci-modules-$([guid]::NewGuid().ToString('N'))" + Invoke-CiLaneDependencyProvision -ModuleRoot $Options.ModuleRoot + } + $Options.Owner = Get-CiDependencyOwner -Path $Options.ModuleRoot +} + +function Invoke-CiLaneDependencyProvision { + param([string]$ModuleRoot) + & (Get-Process -Id $PID).Path -NoLogo -NoProfile -File (Join-Path $PSScriptRoot 'Install-CiPowerShellModules.ps1') -ModuleRoot $ModuleRoot + if ($LASTEXITCODE -ne 0) { + throw 'Disposable dependency provisioning failed.' + } +} + +function Initialize-CiLaneProcessEnvironment { + param([hashtable]$Owner, [hashtable]$Saved) + $env:PSModulePath = Get-CiIsolatedModulePath -ModuleRoot $Owner.Path + $env:PATH = (Split-Path -Parent (Get-Process -Id $PID).Path) + [IO.Path]::PathSeparator + $Saved.PATH + $resolved = (Get-Command pwsh -CommandType Application -ErrorAction Stop | Select-Object -First 1).Source + if ($resolved -ne (Get-Process -Id $PID).Path) { + throw 'pwsh command resolution does not match the selected executable.' + } +} + +function Assert-CiLaneDependencyProbe { + param([string]$ModuleRoot) + & (Get-Process -Id $PID).Path -NoLogo -NoProfile -File (Join-Path $PSScriptRoot 'CiDependencyProbe.ps1') -ModuleRoot $ModuleRoot + if ($LASTEXITCODE -ne 0) { + throw 'Dependency validation failed.' + } +} + +function Restore-CiLaneScratch { + param($Scratch, $Owner) + foreach ($key in $Scratch.Saved.Keys) { + [Environment]::SetEnvironmentVariable($key, $Scratch.Saved[$key]) + } + if ($Owner) { + Remove-CiDependencyRoot -Owner $Owner + } + Remove-Item -LiteralPath $Scratch.Path -Recurse -Force -ErrorAction Stop +} + +if ($MyInvocation.InvocationName -ne '.') { + $options = @{ + LaneId = $LaneId + ExpectedPowerShellVersion = $ExpectedPowerShellVersion + ProvisioningFile = $ProvisioningFile + ModuleRoot = $ModuleRoot + RepositoryRoot = $RepositoryRoot } - if ($status -ne 'passed') { + Invoke-CiPlatformLane -Options $options + if ($options.Status -ne 'passed') { exit 1 } } diff --git a/scripts/qualification/QualificationProcess.ps1 b/scripts/qualification/QualificationProcess.ps1 index 8c2aba6..15c70be 100644 --- a/scripts/qualification/QualificationProcess.ps1 +++ b/scripts/qualification/QualificationProcess.ps1 @@ -5,6 +5,16 @@ function Initialize-QualificationProcessInfo { [pscredential]$Credential ) + $info = Get-QualificationChildStartInfo + Initialize-QualificationChildEnvironment $info $Options $Root + if ($Credential) { + Initialize-QualificationChildCredential $info $Credential + } + $info +} + +function Get-QualificationChildStartInfo { + param() $info = [Diagnostics.ProcessStartInfo]::new((Join-Path $PSHOME 'pwsh')) foreach ($argument in @('-NoLogo', '-NoProfile', '-NonInteractive', '-File', "$PSScriptRoot/Invoke-QualificationChild.ps1")) { $info.ArgumentList.Add($argument) @@ -12,10 +22,6 @@ function Initialize-QualificationProcessInfo { $info.UseShellExecute = $false $info.RedirectStandardOutput = $true $info.RedirectStandardError = $true - Initialize-QualificationChildEnvironment $info $Options $Root - if ($Credential) { - Initialize-QualificationChildCredential $info $Credential - } $info } @@ -56,20 +62,25 @@ function Invoke-QualificationChild { $process.StartInfo = Initialize-QualificationProcessInfo $Options $Root $Credential try { [void]$process.Start() - $outputTask = $process.StandardOutput.ReadToEndAsync() - $errorTask = $process.StandardError.ReadToEndAsync() - Wait-QualificationChild $process - [void]$errorTask.GetAwaiter().GetResult() - if ($process.ExitCode -ne 0) { - throw 'Qualification child failed; raw provider errors withheld.' - } - $text = $outputTask.GetAwaiter().GetResult() - [regex]::Match($text, '(?m)^\{.+\}\s*$').Value | ConvertFrom-Json -Depth 30 + Get-QualificationChildResult -Process $process } finally { $process.Dispose() } } +function Get-QualificationChildResult { + param([Diagnostics.Process]$Process) + $outputTask = $Process.StandardOutput.ReadToEndAsync() + $errorTask = $Process.StandardError.ReadToEndAsync() + Wait-QualificationChild $Process + [void]$errorTask.GetAwaiter().GetResult() + if ($Process.ExitCode -ne 0) { + throw 'Qualification child failed; raw provider errors withheld.' + } + $text = $outputTask.GetAwaiter().GetResult() + [regex]::Match($text, '(?m)^\{.+\}\s*$').Value | ConvertFrom-Json -Depth 30 +} + function Wait-QualificationChild { param([Diagnostics.Process]$Process) if ($Process.WaitForExit(300000)) { diff --git a/scripts/qualification/QualificationScenario.ps1 b/scripts/qualification/QualificationScenario.ps1 index 5295519..bb77c9d 100644 --- a/scripts/qualification/QualificationScenario.ps1 +++ b/scripts/qualification/QualificationScenario.ps1 @@ -10,10 +10,15 @@ function Invoke-QualificationScenario { $Session.Evidence.Phase = 'PMUPlanning' Test-QualificationSourcePolicy $Session $module $plan = Get-QualificationPlan $Session $module + Install-QualificationPlan -Session $Session -Plan $plan +} + +function Install-QualificationPlan { + param([object]$Session, [object]$Plan) $Session.Evidence.Phase = 'PMUInstallation' - Test-QualificationWhatIf $Session $plan - $result = Install-PSModuleUpdate -Update $plan -Credential $Session.Credential -AcceptLicense -TrustRepository -Confirm:$false - Assert-QualificationInstalledResult $Session $plan $result + Test-QualificationWhatIf $Session $Plan + $result = Install-PSModuleUpdate -Update $Plan -Credential $Session.Credential -AcceptLicense -TrustRepository -Confirm:$false + Assert-QualificationInstalledResult $Session $Plan $result $Session.Evidence.Outcome = 'Passed' } @@ -54,14 +59,19 @@ function Assert-QualificationSeed { if (-not $Module) { throw 'The downloaded seed is not an available PowerShell module.' } + Assert-QualificationSeedUnloaded -Module $Module + $Session.Evidence.SeedHasPmuDependency = $false + $Session.Evidence.SeedWasLoaded = $false +} + +function Assert-QualificationSeedUnloaded { + param([System.Management.Automation.PSModuleInfo]$Module) if (@($Module.RequiredModules | Where-Object Name -EQ 'PSModuleUpdate').Count) { throw 'Fixture unexpectedly depends on PMU.' } if (Get-Module -Name $Module.Name) { throw 'The seed fixture must remain unloaded.' } - $Session.Evidence.SeedHasPmuDependency = $false - $Session.Evidence.SeedWasLoaded = $false } function Get-QualificationPlan { @@ -70,6 +80,17 @@ function Get-QualificationPlan { [System.Management.Automation.PSModuleInfo]$Module ) + $parameters = Get-QualificationPlanParameter -Session $Session -Module $Module + $plan = Get-PSModuleUpdate @parameters + Assert-QualificationPublicObject $plan + Assert-QualificationSelectedTarget -Session $Session -Plan $plan + Assert-QualificationPlanIdentity $Session $Module $plan + $Session.Evidence.Plan = $plan + $plan +} + +function Get-QualificationPlanParameter { + param([object]$Session, [System.Management.Automation.PSModuleInfo]$Module) $parameters = @{ Module = $Module Policy = (Get-QualificationPolicy $Session) @@ -77,22 +98,27 @@ function Get-QualificationPlan { if ($Session.Credential) { $parameters.Credential = $Session.Credential } + Initialize-QualificationPlanSource -Session $Session -Parameters $parameters + return $parameters +} + +function Initialize-QualificationPlanSource { + param([object]$Session, [hashtable]$Parameters) if ($Session.Options.Scenario -eq 'Gallery') { - $parameters.Repository = $Session.RepositoryName + $Parameters.Repository = $Session.RepositoryName } else { - $parameters.RepositoryUri = [uri]$Session.Options.RepositoryUri + $Parameters.RepositoryUri = [uri]$Session.Options.RepositoryUri } - $plan = Get-PSModuleUpdate @parameters - Assert-QualificationPublicObject $plan - if ($plan.TargetVersion -cne $Session.Options.TargetVersion) { +} + +function Assert-QualificationSelectedTarget { + param([object]$Session, [object]$Plan) + if ($Plan.TargetVersion -cne $Session.Options.TargetVersion) { throw 'PMU selected a different exact version.' } - if ($plan.RepositoryUri -cne $Session.Options.RepositoryUri) { + if ($Plan.RepositoryUri -cne $Session.Options.RepositoryUri) { throw 'PMU changed the selected source.' } - Assert-QualificationPlanIdentity $Session $Module $plan - $Session.Evidence.Plan = $plan - $plan } function Test-QualificationWhatIf { @@ -116,6 +142,15 @@ function Assert-QualificationInstalledResult { ) Assert-QualificationPublicObject $Result + Assert-QualificationInstallationIdentity -Plan $Plan -Result $Result + Assert-QualificationResultStatus $Result + Assert-QualificationDestination $Result.InstalledPath "$($Session.Root)/home" + $Session.Evidence.Result = $Result + $Session.Evidence.CredentialFree = $true +} + +function Assert-QualificationInstallationIdentity { + param([object]$Plan, [object]$Result) foreach ($field in @('ModuleName', 'ModuleGuid', 'RepositoryUri', 'Scope', 'ActiveVersion', 'TargetVersion')) { if ($Result.$field -cne $Plan.$field) { throw 'Installation result does not match the source-bound plan.' @@ -127,10 +162,6 @@ function Assert-QualificationInstalledResult { if ($Result.VerificationStatus -ne 'Verified') { throw 'The installed package was not verified.' } - Assert-QualificationResultStatus $Result - Assert-QualificationDestination $Result.InstalledPath "$($Session.Root)/home" - $Session.Evidence.Result = $Result - $Session.Evidence.CredentialFree = $true } function Assert-QualificationPlanIdentity { @@ -140,12 +171,7 @@ function Assert-QualificationPlanIdentity { [object]$Plan ) - if ($Plan.ModuleGuid -ne $Module.Guid) { - throw 'Plan identity differs from the independent installed module.' - } - if ($Plan.InstalledVersion -cne $Session.Options.SeedVersion) { - throw 'Plan observed a different installed version.' - } + Assert-QualificationPlanSeed -Session $Session -Module $Module -Plan $Plan Assert-QualificationUnloadedState $Plan if ($Plan.Scope -ne 'CurrentUser') { throw 'Plan changed the approved isolated scope.' @@ -155,14 +181,19 @@ function Assert-QualificationPlanIdentity { } } -function Assert-QualificationResultStatus { - param([object]$Result) - if ($Result.SchemaVersion -ne 1) { - throw 'Unexpected public result schema.' +function Assert-QualificationPlanSeed { + param([object]$Session, [System.Management.Automation.PSModuleInfo]$Module, [object]$Plan) + if ($Plan.ModuleGuid -ne $Module.Guid) { + throw 'Plan identity differs from the independent installed module.' } - if ($Result.Outcome -ne 'Installed') { - throw 'Expected a verified new installation.' + if ($Plan.InstalledVersion -cne $Session.Options.SeedVersion) { + throw 'Plan observed a different installed version.' } +} + +function Assert-QualificationResultStatus { + param([object]$Result) + Assert-QualificationResultSchema -Result $Result if ($Result.RestartRequired) { throw 'An unloaded module should not require restart.' } @@ -172,6 +203,16 @@ function Assert-QualificationResultStatus { } } +function Assert-QualificationResultSchema { + param([object]$Result) + if ($Result.SchemaVersion -ne 1) { + throw 'Unexpected public result schema.' + } + if ($Result.Outcome -ne 'Installed') { + throw 'Expected a verified new installation.' + } +} + function Assert-QualificationUnloadedState { param([object]$Value) foreach ($field in @('ActiveVersion', 'ActivePath', 'ActiveScope')) { @@ -193,15 +234,20 @@ function Test-QualificationSourcePolicy { try { Get-PSModuleUpdate -Module $Module -Repository $Session.RepositoryName -Policy $policy -Credential $Session.Credential | Out-Null } catch { - if ($_.FullyQualifiedErrorId -notmatch 'PMU\.RepositoryChanged') { - throw 'Unexpected source-policy rejection.' - } - $Session.Evidence.SourcePolicyMismatchRejected = $true + Assert-QualificationSourceRejection -Session $Session -Failure $_ return } throw 'PMU accepted a mismatched source policy.' } +function Assert-QualificationSourceRejection { + param([object]$Session, [System.Management.Automation.ErrorRecord]$Failure) + if ($Failure.FullyQualifiedErrorId -notmatch 'PMU\.RepositoryChanged') { + throw 'Unexpected source-policy rejection.' + } + $Session.Evidence.SourcePolicyMismatchRejected = $true +} + function Invoke-QualificationNonModule { param([object]$Session) $Session.Evidence.Phase = 'ProviderExactDownload' @@ -211,15 +257,20 @@ function Invoke-QualificationNonModule { $module = Initialize-QualificationNonModuleSeed $Session $before = @(Get-QualificationModuleTree $Session.Destination) $Session.Evidence.Phase = 'PMUNonModuleValidation' + Install-QualificationNonModule -Session $Session -Module $module + Assert-QualificationRepositoryState $before @(Get-QualificationModuleTree $Session.Destination) + $Session.Evidence.InstallationUnchanged = $true +} + +function Install-QualificationNonModule { + param([object]$Session, [System.Management.Automation.PSModuleInfo]$Module) try { - $plan = Get-QualificationPlan $Session $module + $plan = Get-QualificationPlan $Session $Module Install-PSModuleUpdate -Update $plan -Credential $Session.Credential -AcceptLicense -TrustRepository -Confirm:$false | Out-Null throw 'PMU did not reject the nonmodule package.' } catch { Resolve-QualificationNonModuleRejection $Session $_ } - Assert-QualificationRepositoryState $before @(Get-QualificationModuleTree $Session.Destination) - $Session.Evidence.InstallationUnchanged = $true } function Save-QualificationNonModuleArchive { @@ -258,10 +309,18 @@ function Resolve-QualificationNonModuleRejection { $Session.Evidence.RejectionId = $Matches[0] return } + if (Test-QualificationProviderRejection -Session $Session -Failure $Failure) { + return + } + throw 'Unexpected PMU nonmodule outcome; diagnostics withheld.' +} + +function Test-QualificationProviderRejection { + param([object]$Session, [System.Management.Automation.ErrorRecord]$Failure) if ($Failure.FullyQualifiedErrorId -match 'PMU\.(DownloadFailed|DiscoveryFailed)') { $Session.Evidence.Outcome = 'ProviderLimitation' $Session.Evidence.PmuNonModuleValidation = 'NOT TESTED: provider rejected the package before PMU manifest validation.' - return + return $true } - throw 'Unexpected PMU nonmodule outcome; diagnostics withheld.' + return $false } diff --git a/tests/repository/CiWorkflow.Tests.ps1 b/tests/repository/CiWorkflow.Tests.ps1 index 76c2ca2..21da68f 100644 --- a/tests/repository/CiWorkflow.Tests.ps1 +++ b/tests/repository/CiWorkflow.Tests.ps1 @@ -39,7 +39,7 @@ Describe 'CI workflow security and gate policy' -Tag 'BuildTooling', 'WorkflowPo } It 'requires the shared publisher to isolate dependencies instead of using an ambient install command' { - $script:publish | Should -Match 'uses: stiwicourage/powershell-ci/.github/workflows/publish.yml@develop' + $script:publish | Should -Match 'uses: stiwicourage/powershell-ci/\.github/workflows/publish\.yml@\S+' $script:publish | Should -Match 'dependency-mode: isolated' $script:publish | Should -Not -Match 'install-command:' } diff --git a/tests/repository/SharedCiContracts.Tests.ps1 b/tests/repository/SharedCiContracts.Tests.ps1 index 825779d..1848d1a 100644 --- a/tests/repository/SharedCiContracts.Tests.ps1 +++ b/tests/repository/SharedCiContracts.Tests.ps1 @@ -11,7 +11,7 @@ BeforeAll { Describe 'Shared CI consumer contracts' -Tag 'SharedCi', 'WorkflowPolicy', 'BuildTooling' { It 'uses the shared test workflow without replacing its test command' { - $script:testsWorkflow | Should -Match 'uses: stiwicourage/powershell-ci/.github/workflows/tests.yml@develop' + $script:testsWorkflow | Should -Match 'uses: stiwicourage/powershell-ci/\.github/workflows/tests\.yml@\S+' $script:testsWorkflow | Should -Not -Match 'test-command:' $script:testsWorkflow | Should -Not -Match 'runs-on:' } @@ -42,16 +42,16 @@ Describe 'Shared CI consumer contracts' -Tag 'SharedCi', 'WorkflowPolicy', 'Buil } It 'uses the shared publisher with GerberCore release semantics and isolated dependencies' { - $script:publishWorkflow | Should -Match 'uses: stiwicourage/powershell-ci/.github/workflows/publish.yml@develop' + $script:publishWorkflow | Should -Match 'uses: stiwicourage/powershell-ci/\.github/workflows/publish\.yml@\S+' $script:publishWorkflow | Should -Match 'test-command: Test-NovaBuild' $script:publishWorkflow | Should -Match 'release-continuous-integration: true' $script:publishWorkflow | Should -Match 'dependency-mode: isolated' } It 'delegates all three security checks and keeps dependency review PR-only' { - $script:securityWorkflow | Should -Match 'codeql.yml@develop' - $script:securityWorkflow | Should -Match 'powershell-analyzer.yml@develop' - $script:securityWorkflow | Should -Match 'dependency-review.yml@develop' + $script:securityWorkflow | Should -Match 'uses: stiwicourage/powershell-ci/\.github/workflows/codeql\.yml@\S+' + $script:securityWorkflow | Should -Match 'uses: stiwicourage/powershell-ci/\.github/workflows/powershell-analyzer\.yml@\S+' + $script:securityWorkflow | Should -Match 'uses: stiwicourage/powershell-ci/\.github/workflows/dependency-review\.yml@\S+' $script:securityWorkflow | Should -Match "github.event_name == 'pull_request'" $script:securityWorkflow | Should -Not -Match 'fail-on-severity:' } diff --git a/tests/scripts/build/ci/CiLaneManifest.Tests.ps1 b/tests/scripts/build/ci/CiLaneManifest.Tests.ps1 index 7e73559..1a1a33e 100644 --- a/tests/scripts/build/ci/CiLaneManifest.Tests.ps1 +++ b/tests/scripts/build/ci/CiLaneManifest.Tests.ps1 @@ -101,8 +101,15 @@ Describe 'Build-CiLaneManifest' -Tag 'BuildTooling' { OperatingSystem = 'Linux' PowerShellVersion = '7.4.21' } - $manifest = Build-CiLaneManifest -LaneId 'linux-x64-ps74' -CommitSha 'abc123' -Environment $environment -Mismatch @() ` - -Phase (Build-PhaseList) -Summary (Build-SummaryMap) -Module @{ Pester = '5.7.1' } + $run = @{ + Lane = @{ id = 'linux-x64-ps74' } + Identity = @{ commitSha = 'abc123' } + Actual = $environment + Mismatch = @() + Phase = (Build-PhaseList) + Summary = (Build-SummaryMap) + } + $manifest = Build-CiLaneManifest -Run $run -Module @{ Pester = '5.7.1' } $manifest.laneId | Should -Be 'linux-x64-ps74' $manifest.commitSha | Should -Be 'abc123' @@ -114,8 +121,15 @@ Describe 'Build-CiLaneManifest' -Tag 'BuildTooling' { } It 'survives a JSON round trip with the status intact' { - $manifest = Build-CiLaneManifest -LaneId 'x' -CommitSha 'y' -Environment ([pscustomobject]@{}) -Mismatch @('bad') ` - -Phase (Build-PhaseList) -Summary (Build-SummaryMap) -Module @{} + $run = @{ + Lane = @{ id = 'x' } + Identity = @{ commitSha = 'y' } + Actual = [pscustomobject]@{} + Mismatch = @('bad') + Phase = (Build-PhaseList) + Summary = (Build-SummaryMap) + } + $manifest = Build-CiLaneManifest -Run $run -Module @{} ($manifest | ConvertTo-Json -Depth 6 | ConvertFrom-Json).status | Should -Be 'failed' } diff --git a/tests/scripts/build/ci/Invoke-PlatformLane.Tests.ps1 b/tests/scripts/build/ci/Invoke-PlatformLane.Tests.ps1 index 0df3b77..b80403a 100644 --- a/tests/scripts/build/ci/Invoke-PlatformLane.Tests.ps1 +++ b/tests/scripts/build/ci/Invoke-PlatformLane.Tests.ps1 @@ -7,7 +7,13 @@ Describe 'Invoke-CiLanePhase' -Tag 'BuildTooling' { It 'runs the command in a fresh PowerShell process and records a zero exit code' { $log = Join-Path $TestDrive 'ok.log' - $phase = Invoke-CiLanePhase -Name 'ok' -Command 'Write-Output ''hello from child''' -LogPath $log -WorkingDirectory $TestDrive + $request = @{ + Name = 'ok' + Command = 'Write-Output ''hello from child''' + LogPath = $log + WorkingDirectory = $TestDrive + } + $phase = Invoke-CiLanePhase -Phase $request $phase.Name | Should -Be 'ok' $phase.ExitCode | Should -Be 0 @@ -21,7 +27,13 @@ Describe 'Invoke-CiLanePhase' -Tag 'BuildTooling' { It 'preserves a nonzero exit code so test failures fail the lane' { $log = Join-Path $TestDrive 'fail.log' - $phase = Invoke-CiLanePhase -Name 'fail' -Command 'Write-Output ''boom''; exit 3' -LogPath $log -WorkingDirectory $TestDrive + $request = @{ + Name = 'fail' + Command = 'Write-Output ''boom''; exit 3' + LogPath = $log + WorkingDirectory = $TestDrive + } + $phase = Invoke-CiLanePhase -Phase $request $phase.ExitCode | Should -Be 3 Get-Content -LiteralPath $log -Raw | Should -Match 'boom' @@ -30,7 +42,13 @@ Describe 'Invoke-CiLanePhase' -Tag 'BuildTooling' { It 'treats a terminating error as a failed phase' { $log = Join-Path $TestDrive 'throw.log' - $phase = Invoke-CiLanePhase -Name 'throw' -Command 'throw ''bad''' -LogPath $log -WorkingDirectory $TestDrive + $request = @{ + Name = 'throw' + Command = 'throw ''bad''' + LogPath = $log + WorkingDirectory = $TestDrive + } + $phase = Invoke-CiLanePhase -Phase $request $phase.ExitCode | Should -Not -Be 0 } From 45d1ec3b6c19459661b0b3041a03963abd8f8fa2 Mon Sep 17 00:00:00 2001 From: Stiwi Gabriel Courage Date: Sun, 15 Nov 2026 22:00:10 +0100 Subject: [PATCH 6/9] feat: Add OutputType attributes to functions for improved type safety and clarity --- scripts/build/ci/Assert-CiGate.ps1 | 5 ++ scripts/build/ci/CiDependencyRoot.ps1 | 14 ++++-- scripts/build/ci/CiLaneEnvironment.ps1 | 3 ++ scripts/build/ci/CiLaneManifest.ps1 | 4 ++ scripts/build/ci/Install-CiPowerShell.ps1 | 1 + scripts/build/ci/Invoke-PlatformLane.ps1 | 4 ++ .../qualification/QualificationProcess.ps1 | 4 +- .../qualification/QualificationScenario.ps1 | 4 +- .../Assert-PMUManifestInspection.ps1 | 2 +- .../Initialize-PMUManifestFixture.ps1 | 4 +- .../scripts/build/ci/CiLaneManifest.Tests.ps1 | 50 +++++++++---------- 11 files changed, 58 insertions(+), 37 deletions(-) diff --git a/scripts/build/ci/Assert-CiGate.ps1 b/scripts/build/ci/Assert-CiGate.ps1 index 9f15e66..c3161cd 100644 --- a/scripts/build/ci/Assert-CiGate.ps1 +++ b/scripts/build/ci/Assert-CiGate.ps1 @@ -8,6 +8,7 @@ $script:RequiredJob = @('plan', 'quality', 'platform') . (Join-Path $PSScriptRoot 'CiGateEvidence.ps1') function ConvertTo-CiGateJobResult { + [OutputType([hashtable])] [CmdletBinding()] param( [Parameter(Mandatory)][string]$NeedsJson @@ -23,6 +24,7 @@ function ConvertTo-CiGateJobResult { } function Get-CiGateJobFailure { + [OutputType([string])] [CmdletBinding()] param( [Parameter(Mandatory)][hashtable]$JobResult @@ -38,6 +40,7 @@ function Get-CiGateJobFailure { } function Read-CiLaneManifest { + [OutputType([hashtable])] [CmdletBinding()] param( [Parameter(Mandatory)][string]$Directory @@ -75,6 +78,7 @@ function Get-CiInvalidManifest { } function Get-CiLaneManifestFailure { + [OutputType([string])] [CmdletBinding()] param( [Parameter(Mandatory)][string]$LaneId, @@ -119,6 +123,7 @@ function Assert-CiLaneEntryEvidence { } function Test-CiGateResult { + [OutputType([string])] [CmdletBinding()] param( [Parameter(Mandatory)][hashtable]$JobResult, diff --git a/scripts/build/ci/CiDependencyRoot.ps1 b/scripts/build/ci/CiDependencyRoot.ps1 index 89e7725..1909edd 100644 --- a/scripts/build/ci/CiDependencyRoot.ps1 +++ b/scripts/build/ci/CiDependencyRoot.ps1 @@ -1,4 +1,5 @@ function New-CiDependencyRoot { + [OutputType([hashtable])] [CmdletBinding(SupportsShouldProcess)] param([Parameter(Mandatory)][string]$Path) @@ -7,14 +8,19 @@ function New-CiDependencyRoot { return } $directory = New-Item -ItemType Directory -Path $Path -ErrorAction Stop - $owner = @{ - Path = $directory.FullName - Token = [guid]::NewGuid().ToString('N') - } + $owner = Get-CiDependencyCreationRecord -Directory $directory $owner | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $owner.Path '.pmu-dependencies.json') return $owner } +function Get-CiDependencyCreationRecord { + param($Directory) + return @{ + Path = $Directory.FullName + Token = [guid]::NewGuid().ToString('N') + } +} + function Assert-CiDependencyRootAvailable { param([string]$Path) if (Test-Path -LiteralPath $Path) { diff --git a/scripts/build/ci/CiLaneEnvironment.ps1 b/scripts/build/ci/CiLaneEnvironment.ps1 index be38f55..c5c3430 100644 --- a/scripts/build/ci/CiLaneEnvironment.ps1 +++ b/scripts/build/ci/CiLaneEnvironment.ps1 @@ -44,6 +44,7 @@ function Get-CiRunnerEnvironment { } function Get-CiEqualityMismatch { + [OutputType([string])] [CmdletBinding()] param( [Parameter(Mandatory)][string]$Label, @@ -57,6 +58,7 @@ function Get-CiEqualityMismatch { } function Get-CiChannelMismatch { + [OutputType([string])] [CmdletBinding()] param( [Parameter(Mandatory)][string]$Channel, @@ -84,6 +86,7 @@ function Get-CiRunnerMismatch { } function Test-CiLaneEnvironment { + [OutputType([string])] [CmdletBinding()] param( [Parameter(Mandatory)]$Expected, diff --git a/scripts/build/ci/CiLaneManifest.ps1 b/scripts/build/ci/CiLaneManifest.ps1 index ed1d2c8..a21a448 100644 --- a/scripts/build/ci/CiLaneManifest.ps1 +++ b/scripts/build/ci/CiLaneManifest.ps1 @@ -1,4 +1,5 @@ function Test-CiPhaseSucceeded { + [OutputType([bool])] [CmdletBinding()] param( [Parameter(Mandatory)][AllowEmptyCollection()][object[]]$Phase, @@ -10,6 +11,7 @@ function Test-CiPhaseSucceeded { } function Test-CiSummaryHealthy { + [OutputType([bool])] [CmdletBinding()] param( [Parameter(Mandatory)][hashtable]$Summary, @@ -27,6 +29,7 @@ function Test-CiSummaryHealthy { } function Get-CiLaneStatus { + [OutputType([string])] [CmdletBinding()] param( [string[]]$Mismatch = @(), @@ -54,6 +57,7 @@ function Get-CiLaneHealthCheck { } function Build-CiLaneManifest { + [OutputType([System.Collections.Specialized.OrderedDictionary])] [CmdletBinding()] param( [Parameter(Mandatory)][hashtable]$Run, diff --git a/scripts/build/ci/Install-CiPowerShell.ps1 b/scripts/build/ci/Install-CiPowerShell.ps1 index dbb8298..72f2482 100644 --- a/scripts/build/ci/Install-CiPowerShell.ps1 +++ b/scripts/build/ci/Install-CiPowerShell.ps1 @@ -12,6 +12,7 @@ $script:PowerShellMetadataUri = 'https://raw.githubusercontent.com/PowerShell/Po . (Join-Path $PSScriptRoot 'CiRuntimeEvidence.ps1') function Get-CiPowerShellAssetName { + [OutputType([string])] [CmdletBinding()] param( [Parameter(Mandatory)][string]$Version, diff --git a/scripts/build/ci/Invoke-PlatformLane.ps1 b/scripts/build/ci/Invoke-PlatformLane.ps1 index d8dd4be..7cf1acc 100644 --- a/scripts/build/ci/Invoke-PlatformLane.ps1 +++ b/scripts/build/ci/Invoke-PlatformLane.ps1 @@ -136,6 +136,7 @@ function Get-CiPhaseLaunchRecord { } function Get-CiModuleVersion { + [OutputType([hashtable])] [CmdletBinding()] param() @@ -149,6 +150,7 @@ function Get-CiModuleVersion { } function Get-CiLanePhaseDefinition { + [OutputType([object[]])] [CmdletBinding()] param() @@ -168,6 +170,7 @@ function Get-CiPhaseDefinition { } function Invoke-CiLanePhaseSet { + [OutputType([object[]])] [CmdletBinding()] param( [Parameter(Mandatory)][string]$RepositoryRoot, @@ -203,6 +206,7 @@ function Get-CiPhaseInvocation { } function Copy-CiTestResult { + [OutputType([hashtable])] [CmdletBinding()] param( [Parameter(Mandatory)][string]$RepositoryRoot, diff --git a/scripts/qualification/QualificationProcess.ps1 b/scripts/qualification/QualificationProcess.ps1 index 15c70be..bd9bbf5 100644 --- a/scripts/qualification/QualificationProcess.ps1 +++ b/scripts/qualification/QualificationProcess.ps1 @@ -6,7 +6,7 @@ function Initialize-QualificationProcessInfo { ) $info = Get-QualificationChildStartInfo - Initialize-QualificationChildEnvironment $info $Options $Root + Initialize-QualificationChildEnvironment -Info $info -Options $Options -Root $Root if ($Credential) { Initialize-QualificationChildCredential $info $Credential } @@ -59,7 +59,7 @@ function Invoke-QualificationChild { ) $process = [Diagnostics.Process]::new() - $process.StartInfo = Initialize-QualificationProcessInfo $Options $Root $Credential + $process.StartInfo = Initialize-QualificationProcessInfo -Options $Options -Root $Root -Credential $Credential try { [void]$process.Start() Get-QualificationChildResult -Process $process diff --git a/scripts/qualification/QualificationScenario.ps1 b/scripts/qualification/QualificationScenario.ps1 index bb77c9d..47f4e07 100644 --- a/scripts/qualification/QualificationScenario.ps1 +++ b/scripts/qualification/QualificationScenario.ps1 @@ -18,7 +18,7 @@ function Install-QualificationPlan { $Session.Evidence.Phase = 'PMUInstallation' Test-QualificationWhatIf $Session $Plan $result = Install-PSModuleUpdate -Update $Plan -Credential $Session.Credential -AcceptLicense -TrustRepository -Confirm:$false - Assert-QualificationInstalledResult $Session $Plan $result + Assert-QualificationInstalledResult -Session $Session -Plan $Plan -Result $result $Session.Evidence.Outcome = 'Passed' } @@ -84,7 +84,7 @@ function Get-QualificationPlan { $plan = Get-PSModuleUpdate @parameters Assert-QualificationPublicObject $plan Assert-QualificationSelectedTarget -Session $Session -Plan $plan - Assert-QualificationPlanIdentity $Session $Module $plan + Assert-QualificationPlanIdentity -Session $Session -Module $Module -Plan $plan $Session.Evidence.Plan = $plan $plan } diff --git a/tests/TestHelpers/Assert-PMUManifestInspection.ps1 b/tests/TestHelpers/Assert-PMUManifestInspection.ps1 index c5041bb..c2d7467 100644 --- a/tests/TestHelpers/Assert-PMUManifestInspection.ps1 +++ b/tests/TestHelpers/Assert-PMUManifestInspection.ps1 @@ -5,7 +5,7 @@ function Assert-PMUManifestInspection { ) $snapshot = ConvertTo-Json $Plan -Depth 12 -Compress $target = Get-PSModuleUpdateTargetManifest -Plan $Plan -TrustRepository -AcceptLicense - Assert-PMUManifestCandidate $target $Plan $Fixture $snapshot + Assert-PMUManifestCandidate -Target $target -Plan $Plan -Fixture $Fixture -Snapshot $snapshot $result = Install-PSModuleUpdate -Update $Plan -TrustRepository -AcceptLicense -Confirm:$false Assert-PMUManifestInstallation $result $target.Version Assert-PMUManifestRepublish $Fixture diff --git a/tests/TestHelpers/Initialize-PMUManifestFixture.ps1 b/tests/TestHelpers/Initialize-PMUManifestFixture.ps1 index 48e801a..dfd611c 100644 --- a/tests/TestHelpers/Initialize-PMUManifestFixture.ps1 +++ b/tests/TestHelpers/Initialize-PMUManifestFixture.ps1 @@ -7,7 +7,7 @@ function Initialize-PMUManifestFixture { $path = Join-Path $Fixture.Feed "$($Fixture.Name).$Version.nupkg" $archive = [IO.Compression.ZipFile]::Open($path, [IO.Compression.ZipArchiveMode]::Update) try { - Initialize-PMUArchiveManifest $archive "$($Fixture.Name).psd1" $MinimumVersion + Initialize-PMUArchiveManifest -Archive $archive -Name "$($Fixture.Name).psd1" -MinimumVersion $MinimumVersion } finally { $archive.Dispose() } @@ -21,7 +21,7 @@ function Initialize-PMUArchiveManifest { ) $text = Read-PMUFixtureArchiveManifest $Archive $Name $text = $text -replace "Gerber = @\{ MinimumGerberVersion = '[^']+' \}; ", '' - Write-PMUFixtureArchiveManifest $Archive $Name ($text.Replace('PrivateData = @{', "PrivateData = @{ Gerber = @{ MinimumGerberVersion = '$MinimumVersion' };")) + Write-PMUFixtureArchiveManifest -Archive $Archive -Name $Name -Text ($text.Replace('PrivateData = @{', "PrivateData = @{ Gerber = @{ MinimumGerberVersion = '$MinimumVersion' };")) } function Read-PMUFixtureArchiveManifest { diff --git a/tests/scripts/build/ci/CiLaneManifest.Tests.ps1 b/tests/scripts/build/ci/CiLaneManifest.Tests.ps1 index 1a1a33e..6bdb76f 100644 --- a/tests/scripts/build/ci/CiLaneManifest.Tests.ps1 +++ b/tests/scripts/build/ci/CiLaneManifest.Tests.ps1 @@ -10,21 +10,20 @@ BeforeAll { ) @( - [pscustomobject]@{ - Name = 'build' - ExitCode = $Build - } - [pscustomobject]@{ - Name = 'unit' - ExitCode = $Unit - } - [pscustomobject]@{ - Name = 'integration' - ExitCode = $Integration - } + Get-TestPhaseEntry -Name 'build' -ExitCode $Build + Get-TestPhaseEntry -Name 'unit' -ExitCode $Unit + Get-TestPhaseEntry -Name 'integration' -ExitCode $Integration ) } + function Get-TestPhaseEntry { + param([string]$Name, [int]$ExitCode) + [pscustomobject]@{ + Name = $Name + ExitCode = $ExitCode + } + } + function Build-SummaryMap { param( [int]$UnitTotal = 10, @@ -33,20 +32,19 @@ BeforeAll { ) @{ - unit = [pscustomobject]@{ - Total = $UnitTotal - Passed = $UnitTotal - $UnitFailed - Failed = $UnitFailed - Skipped = 0 - SkippedName = @() - } - integration = [pscustomobject]@{ - Total = 2 - Passed = 2 - $IntegrationFailed - Failed = $IntegrationFailed - Skipped = 0 - SkippedName = @() - } + unit = Get-TestSummaryEntry -Total $UnitTotal -Failed $UnitFailed + integration = Get-TestSummaryEntry -Total 2 -Failed $IntegrationFailed + } + } + + function Get-TestSummaryEntry { + param([int]$Total, [int]$Failed) + [pscustomobject]@{ + Total = $Total + Passed = $Total - $Failed + Failed = $Failed + Skipped = 0 + SkippedName = @() } } } From 8da39da750e7296900c58b9be98afa23b55f307f Mon Sep 17 00:00:00 2001 From: Stiwi Gabriel Courage Date: Mon, 16 Nov 2026 00:13:12 +0100 Subject: [PATCH 7/9] feat: Add comprehensive tests and new functions for installation progress and Linux clock frequency - Implemented `Get-InstallationProgressHost` to retrieve host state information regarding output redirection and interactivity. - Created `Write-InstallationProgress` to manage progress reporting during installation phases. - Introduced `Get-LinuxClockTickFrequency` to fetch the Linux process clock frequency, with error handling for command failures. - Added tests for the new functions to ensure correct behavior and error handling. - Enhanced existing tests across various modules to improve coverage and validate edge cases, including: - Validating directory requests and handling of empty required fields in metadata. - Ensuring correct behavior when dealing with repository receipts and package sources. - Testing for proper handling of staging and recovery processes. --- CHANGELOG.md | 3 ++ RELEASE_NOTE.md | 2 + scripts/build/ci/Invoke-PlatformLane.ps1 | 4 +- .../Get-InstallationProgressHost.ps1 | 6 +++ .../installation/Write-InstallationPhase.ps1 | 14 ++---- .../Write-InstallationProgress.ps1 | 13 ++++++ .../locking/Get-LinuxClockTickFrequency.ps1 | 8 ++++ .../Get-LinuxRepositoryProcessStart.ps1 | 14 +++--- .../Import-PMUTestSource.Tests.ps1 | 43 +++++++++++++++++++ tests/TestHelpers/Import-PMUTestSource.ps1 | 16 ++++++- .../Resolve-ModuleInstallationRoot.Tests.ps1 | 19 ++++++++ .../Get-BoundTargetManifest.Tests.ps1 | 15 +++++++ .../Initialize-ManifestInspection.Tests.ps1 | 16 +++++++ .../Invoke-TargetManifestInspection.Tests.ps1 | 24 +++++++++++ .../Get-InstallationProgressHost.Tests.ps1 | 13 ++++++ .../Write-InstallationPhase.Tests.ps1 | 21 +++++++++ .../Write-InstallationProgress.Tests.ps1 | 21 +++++++++ .../locking/Enter-InstallationLock.Tests.ps1 | 9 ++++ .../Get-LinuxClockTickFrequency.Tests.ps1 | 30 +++++++++++++ .../Get-LinuxRepositoryProcessStart.Tests.ps1 | 40 +++++++++++++++++ .../Get-WindowsDirectoryDescriptor.Tests.ps1 | 35 ++++++++++++--- .../Initialize-ControlledDirectory.Tests.ps1 | 16 +++++++ .../planning/Select-UpdateTarget.Tests.ps1 | 8 ++++ .../Assert-NativeInstallationRecord.Tests.ps1 | 12 ++++++ .../Assert-NativeRecordField.Tests.ps1 | 16 +++++++ .../ConvertTo-ProviderRelease.Tests.ps1 | 14 ++++++ .../provider/Get-NativeProviderRoot.Tests.ps1 | 9 ++++ .../Get-ProviderLicenseRequirement.Tests.ps1 | 10 +++++ .../provider/Write-ProviderError.Tests.ps1 | 11 +++++ .../recovery/Assert-RecoveryJournal.Tests.ps1 | 7 +++ .../Get-SurvivingManifestData.Tests.ps1 | 13 ++++++ .../Get-VerifiedRecoveryBackup.Tests.ps1 | 12 ++++++ .../Invoke-RecoveryRestoration.Tests.ps1 | 12 ++++++ .../Assert-RepositoryReceipt.Tests.ps1 | 20 +++++++++ ...Assert-RepositoryReceiptIdentity.Tests.ps1 | 16 +++++++ .../Close-OwnedRepositoryTransport.Tests.ps1 | 16 +++++++ .../Get-OwnedRepositoryName.Tests.ps1 | 27 ++++++++++++ .../Get-RepositoryReceiptEntry.Tests.ps1 | 22 ++++++++++ .../Get-SelectedRepository.Tests.ps1 | 12 ++++++ .../Read-RepositoryReceipt.Tests.ps1 | 11 +++++ .../Repair-RepositoryReceipt.Tests.ps1 | 13 ++++++ .../Write-BoundRepositoryReceipt.Tests.ps1 | 11 +++++ .../staging/Clear-StagingRoot.Tests.ps1 | 20 +++++++++ .../staging/Get-ValidatedStagedTree.Tests.ps1 | 9 ++++ .../Assert-PackageSource.Tests.ps1 | 11 +++++ .../Get-PackageSourceProperty.Tests.ps1 | 25 ++++++++++- .../build/ci/Invoke-PlatformLane.Tests.ps1 | 26 +++++++++++ 47 files changed, 716 insertions(+), 29 deletions(-) create mode 100644 src/private/installation/Get-InstallationProgressHost.ps1 create mode 100644 src/private/installation/Write-InstallationProgress.ps1 create mode 100644 src/private/locking/Get-LinuxClockTickFrequency.ps1 create mode 100644 tests/TestHelpers/Import-PMUTestSource.Tests.ps1 create mode 100644 tests/private/installation/Get-InstallationProgressHost.Tests.ps1 create mode 100644 tests/private/installation/Write-InstallationProgress.Tests.ps1 create mode 100644 tests/private/locking/Get-LinuxClockTickFrequency.Tests.ps1 diff --git a/CHANGELOG.md b/CHANGELOG.md index d23b9cb..0cf7deb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,6 +41,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), ### Fixed +- Record the qualified PSResourceGet 1.2.0 availability in CI lane manifests + even when the selected PowerShell runtime bundles a newer provider, so the + aggregate gate does not reject an available required dependency. - Normalize PSResourceGet's structured `PackageNotFound` discovery error to terminating `PMU.PackageNotFound`, including command-suffixed provider IDs. Missing packages produce no update plan or fallback query; provider diff --git a/RELEASE_NOTE.md b/RELEASE_NOTE.md index 4b6a69b..c045c14 100644 --- a/RELEASE_NOTE.md +++ b/RELEASE_NOTE.md @@ -52,6 +52,8 @@ This file summarizes public cmdlet, CLI, configuration, and migration changes fo ### Fixed +- Contributor CI no longer rejects the required provider merely because + PowerShell also bundles a newer PSResourceGet version. - Update checks now report `PMU.PackageNotFound` when the selected repository has no matching package. No update plan is returned, and PMU does not try another feed or expose raw provider diagnostics. diff --git a/scripts/build/ci/Invoke-PlatformLane.ps1 b/scripts/build/ci/Invoke-PlatformLane.ps1 index 7cf1acc..9d17c80 100644 --- a/scripts/build/ci/Invoke-PlatformLane.ps1 +++ b/scripts/build/ci/Invoke-PlatformLane.ps1 @@ -142,7 +142,9 @@ function Get-CiModuleVersion { $module = @{} foreach ($name in 'Pester', 'NovaModuleTools', 'PSScriptAnalyzer', 'Microsoft.PowerShell.PSResourceGet', 'Microsoft.PowerShell.PlatyPS') { - $module[$name] = @(Get-Module -ListAvailable -Name $name | Sort-Object Version -Descending | + $module[$name] = @(Get-Module -ListAvailable -Name $name | + Where-Object { $name -ne 'Microsoft.PowerShell.PSResourceGet' -or $_.Version -eq [version]'1.2.0' } | + Sort-Object Version -Descending | Select-Object -First 1 | ForEach-Object { $_.Version.ToString() }) } diff --git a/src/private/installation/Get-InstallationProgressHost.ps1 b/src/private/installation/Get-InstallationProgressHost.ps1 new file mode 100644 index 0000000..1418229 --- /dev/null +++ b/src/private/installation/Get-InstallationProgressHost.ps1 @@ -0,0 +1,6 @@ +function Get-InstallationProgressHost { + [pscustomobject]@{ + OutputRedirected = [Console]::IsOutputRedirected + NonInteractive = [Environment]::GetCommandLineArgs() -contains '-NonInteractive' + } +} diff --git a/src/private/installation/Write-InstallationPhase.ps1 b/src/private/installation/Write-InstallationPhase.ps1 index 7052de6..8b07abf 100644 --- a/src/private/installation/Write-InstallationPhase.ps1 +++ b/src/private/installation/Write-InstallationPhase.ps1 @@ -4,17 +4,9 @@ function Write-InstallationPhase { [string]$Phase ) - if ([Console]::IsOutputRedirected) { + $hostState = Get-InstallationProgressHost + if ($hostState.OutputRedirected -or $hostState.NonInteractive) { return } - if ([Environment]::GetCommandLineArgs() -contains '-NonInteractive') { - return - } - $progressId = 17330 # Stable native progress activity for the single-module workflow. - $activity = "Updating $($Plan.ModuleName)" - if ($Phase -eq 'Completed') { - Write-Progress -Id $progressId -Activity $activity -Completed - return - } - Write-Progress -Id $progressId -Activity $activity -Status $Phase + Write-InstallationProgress $Plan $Phase } diff --git a/src/private/installation/Write-InstallationProgress.ps1 b/src/private/installation/Write-InstallationProgress.ps1 new file mode 100644 index 0000000..e3d8aea --- /dev/null +++ b/src/private/installation/Write-InstallationProgress.ps1 @@ -0,0 +1,13 @@ +function Write-InstallationProgress { + param( + [object]$Plan, + [string]$Phase + ) + $progressId = 17330 # Stable native progress activity for the single-module workflow. + $activity = "Updating $($Plan.ModuleName)" + if ($Phase -eq 'Completed') { + Write-Progress -Id $progressId -Activity $activity -Completed + return + } + Write-Progress -Id $progressId -Activity $activity -Status $Phase +} diff --git a/src/private/locking/Get-LinuxClockTickFrequency.ps1 b/src/private/locking/Get-LinuxClockTickFrequency.ps1 new file mode 100644 index 0000000..4404e37 --- /dev/null +++ b/src/private/locking/Get-LinuxClockTickFrequency.ps1 @@ -0,0 +1,8 @@ +function Get-LinuxClockTickFrequency { + param([string]$CommandPath = '/usr/bin/getconf') + $frequency = & $CommandPath CLK_TCK + if ($LASTEXITCODE -ne 0) { + throw [IO.InvalidDataException]::new('Cannot read the Linux process clock frequency.') + } + $frequency +} diff --git a/src/private/locking/Get-LinuxRepositoryProcessStart.ps1 b/src/private/locking/Get-LinuxRepositoryProcessStart.ps1 index 71958e6..53aec61 100644 --- a/src/private/locking/Get-LinuxRepositoryProcessStart.ps1 +++ b/src/private/locking/Get-LinuxRepositoryProcessStart.ps1 @@ -1,13 +1,13 @@ function Get-LinuxRepositoryProcessStart { - param([int]$ProcessId) + param( + [int]$ProcessId, + [string]$ProcRoot = '/proc' + ) try { - $stat = [IO.File]::ReadAllText("/proc/$ProcessId/stat") + $stat = [IO.File]::ReadAllText([IO.Path]::Combine($ProcRoot, "$ProcessId", 'stat')) } catch [IO.FileNotFoundException], [IO.DirectoryNotFoundException] { return $null } - $frequency = & '/usr/bin/getconf' CLK_TCK - if ($LASTEXITCODE -ne 0) { - throw [IO.InvalidDataException]::new('Cannot read the Linux process clock frequency.') - } - ConvertTo-LinuxProcessStartIdentity $stat ([IO.File]::ReadAllText('/proc/stat')) $frequency + $frequency = Get-LinuxClockTickFrequency + ConvertTo-LinuxProcessStartIdentity $stat ([IO.File]::ReadAllText([IO.Path]::Combine($ProcRoot, 'stat'))) $frequency } diff --git a/tests/TestHelpers/Import-PMUTestSource.Tests.ps1 b/tests/TestHelpers/Import-PMUTestSource.Tests.ps1 new file mode 100644 index 0000000..feac534 --- /dev/null +++ b/tests/TestHelpers/Import-PMUTestSource.Tests.ps1 @@ -0,0 +1,43 @@ +BeforeAll { + $script:pmuTestImportSource = Join-Path $PSScriptRoot 'Import-PMUTestSource.ps1' +} + +Describe 'Test source loading' -Tag 'PMUTestSourceLoading' { + BeforeEach { + $fixtureRoot = Join-Path $TestDrive ([guid]::NewGuid().ToString('N')) + $null = New-Item -ItemType Directory -Path $fixtureRoot + $fixture = Join-Path $fixtureRoot 'Invoke-PMUTestLoadingProbe.ps1' + $script:pmuTestLoadMarker = Join-Path $fixtureRoot 'loads.txt' + Set-Content -LiteralPath $fixture -Value @' +Add-Content -LiteralPath (Join-Path $PSScriptRoot 'loads.txt') -Value 'loaded' +function Invoke-PMUTestLoadingProbe { + return 'expected source' +} +'@ + Mock Get-ChildItem { Get-Item -LiteralPath $fixture } -ParameterFilter { + $Filter -eq '*.ps1' -and $Recurse + } + } + + It 'does not reload a function already imported from the same source file' { + . $script:pmuTestImportSource + Invoke-PMUTestLoadingProbe | Should -Be 'expected source' + . $script:pmuTestImportSource + Invoke-PMUTestLoadingProbe | Should -Be 'expected source' + @(Get-Content -LiteralPath $script:pmuTestLoadMarker) | Should -HaveCount 1 + } + + It 'replaces a same-named function imported from a different source file' { + $foreignSource = Join-Path $TestDrive 'foreign.ps1' + Set-Content -LiteralPath $foreignSource -Value @' +function Invoke-PMUTestLoadingProbe { + return 'foreign source' +} +'@ + . $foreignSource + Invoke-PMUTestLoadingProbe | Should -Be 'foreign source' + . $script:pmuTestImportSource + Invoke-PMUTestLoadingProbe | Should -Be 'expected source' + @(Get-Content -LiteralPath $script:pmuTestLoadMarker) | Should -HaveCount 1 + } +} diff --git a/tests/TestHelpers/Import-PMUTestSource.ps1 b/tests/TestHelpers/Import-PMUTestSource.ps1 index 2bad548..f201a00 100644 --- a/tests/TestHelpers/Import-PMUTestSource.ps1 +++ b/tests/TestHelpers/Import-PMUTestSource.ps1 @@ -1,6 +1,18 @@ Set-StrictMode -Version Latest . "$PSScriptRoot/Get-PMUTestCommandReference.ps1" . "$PSScriptRoot/Get-PMUTestSourcePath.ps1" -foreach ($sourceFile in Get-PMUTestSourcePath $MyInvocation.ScriptName) { - . $sourceFile + +function Import-PMUTestSource { + param([string]$PmuTestSourceCaller) + + foreach ($pmuTestSourceFile in Get-PMUTestSourcePath $PmuTestSourceCaller) { + $pmuTestSourceName = [IO.Path]::GetFileNameWithoutExtension($pmuTestSourceFile) + $pmuTestSourceCommand = Microsoft.PowerShell.Core\Get-Command -Name $pmuTestSourceName -CommandType Function -ErrorAction SilentlyContinue + if ($pmuTestSourceCommand -and $pmuTestSourceCommand.ScriptBlock.File -eq $pmuTestSourceFile) { + continue + } + . $pmuTestSourceFile + } } + +. Import-PMUTestSource -PmuTestSourceCaller $MyInvocation.ScriptName diff --git a/tests/private/identity/Resolve-ModuleInstallationRoot.Tests.ps1 b/tests/private/identity/Resolve-ModuleInstallationRoot.Tests.ps1 index 678ab43..6a49b8c 100644 --- a/tests/private/identity/Resolve-ModuleInstallationRoot.Tests.ps1 +++ b/tests/private/identity/Resolve-ModuleInstallationRoot.Tests.ps1 @@ -24,4 +24,23 @@ Describe 'Resolve-ModuleInstallationRoot' -Tag 'PMU', 'PMUCoverageFollowUp' { $env:ProgramFiles = $originalProgramFiles } } + It 'routes Windows CurrentUser modules through the native Documents folder and path safety validation' { + # Unit routing only: the controlled Join-Path result is not Windows filesystem qualification. + $originalWindows = $IsWindows + $nativeDocuments = [Environment]::GetFolderPath('MyDocuments') + $expectedRoot = Join-Path $TestDrive 'Documents/PowerShell/Modules' + Mock Join-Path { $expectedRoot } -ParameterFilter { + $Path -ceq $nativeDocuments -and $ChildPath -ceq 'PowerShell/Modules' + } + try { + Set-Variable IsWindows $true -Force + Resolve-ModuleInstallationRoot 'CurrentUser' | Should -BeExactly $expectedRoot + Should -Invoke Join-Path -Times 1 -Exactly -ParameterFilter { + $Path -ceq $nativeDocuments -and $ChildPath -ceq 'PowerShell/Modules' + } + Test-Path -LiteralPath $expectedRoot | Should -BeFalse + } finally { + Set-Variable IsWindows $originalWindows -Force + } + } } diff --git a/tests/private/inspection/Get-BoundTargetManifest.Tests.ps1 b/tests/private/inspection/Get-BoundTargetManifest.Tests.ps1 index 8369e1f..bb25d84 100644 --- a/tests/private/inspection/Get-BoundTargetManifest.Tests.ps1 +++ b/tests/private/inspection/Get-BoundTargetManifest.Tests.ps1 @@ -16,4 +16,19 @@ Describe 'Get-BoundTargetManifest' -Tag 'PMU', 'PMUTargetManifest' { } | Should -Throw -ErrorId PMU.LicenseAcceptanceRequired Should -Invoke Invoke-ManifestAcquisition -Times 0 } + It 'returns the inspected manifest only after exact target and consent checks precede acquisition' { + $expectedOperation = [pscustomobject]@{ Id = 'inspection' } + $manifest = [pscustomobject]@{ Version = '2.0.0'; Name = 'FixtureModule' } + $events = [Collections.Generic.List[string]]::new() + Mock Assert-ExactTarget { $events.Add('target') } + Mock Assert-InstallationConsent { $events.Add('consent') } + Mock Invoke-ManifestAcquisition { $events.Add('acquire') } + Mock Get-InspectedTargetManifest { $events.Add('inspect'); $manifest } + $result = Get-BoundTargetManifest $expectedOperation + [object]::ReferenceEquals($result, $manifest) | Should -BeTrue + @($events) | Should -Be @('target', 'consent', 'acquire', 'inspect') + Should -Invoke Get-InspectedTargetManifest -Times 1 -Exactly -ParameterFilter { + [object]::ReferenceEquals($Operation, $expectedOperation) + } + } } diff --git a/tests/private/inspection/Initialize-ManifestInspection.Tests.ps1 b/tests/private/inspection/Initialize-ManifestInspection.Tests.ps1 index e48d056..5479f85 100644 --- a/tests/private/inspection/Initialize-ManifestInspection.Tests.ps1 +++ b/tests/private/inspection/Initialize-ManifestInspection.Tests.ps1 @@ -19,4 +19,20 @@ Describe 'Initialize-ManifestInspection' -Tag 'PMU', 'PMUTargetManifest' { } | Should -Throw -ErrorId PMU.RepositoryTrustRequired Should -Invoke ConvertTo-ManifestInspectionOperation -Times 0 } + It 'creates an isolated inspection operation after forwarding explicitly accepted consent' { + $request = Initialize-PMUTestOperation $TestDrive + $expectedCredential = [pscredential]::new('fixture', [securestring]::new()) + Mock Initialize-InstallationRequest { $request } + Mock Assert-InstallationConsent {} + $inspection = Initialize-ManifestInspection $request.Plan $expectedCredential $true $true + [object]::ReferenceEquals($inspection, $request) | Should -BeTrue + $inspection.Journal.TransactionId | Should -Match '^[a-f0-9]{32}$' + $inspection.WorkRoot | Should -BeExactly (Join-Path $inspection.DataRoot "inspection-$($inspection.Journal.TransactionId)") + Test-Path -LiteralPath $inspection.WorkRoot | Should -BeFalse + Should -Invoke Initialize-InstallationRequest -Times 1 -Exactly -ParameterFilter { + $Consent.AcceptLicense -and $Consent.TrustRepository -and + [object]::ReferenceEquals($Credential, $expectedCredential) + } + Should -Invoke Assert-InstallationConsent -Times 1 -Exactly + } } diff --git a/tests/private/inspection/Invoke-TargetManifestInspection.Tests.ps1 b/tests/private/inspection/Invoke-TargetManifestInspection.Tests.ps1 index 7f98017..82c079b 100644 --- a/tests/private/inspection/Invoke-TargetManifestInspection.Tests.ps1 +++ b/tests/private/inspection/Invoke-TargetManifestInspection.Tests.ps1 @@ -18,4 +18,28 @@ Describe 'Invoke-TargetManifestInspection' -Tag 'PMU', 'PMUTargetManifest' { } | Should -Throw -ErrorId PMU.RecoveryRequired $output.Count | Should -Be 0 } + Context 'Workspace lifetime' { + BeforeEach { + $operation = ConvertTo-ManifestInspectionOperation (Initialize-PMUTestOperation $TestDrive) + $operation.Credential = [pscredential]::new('fixture', [securestring]::new()) + $phases = [Collections.Generic.List[string]]::new() + Mock Write-InstallationPhase { $phases.Add($Phase) } + } + It 'publishes the candidate after removing the owned inspection workspace and credential' { + $candidate = [pscustomobject]@{ Version = '2.0.0' } + Mock Invoke-RepositoryManifestInspection { $candidate } + $result = Invoke-TargetManifestInspection $operation + [object]::ReferenceEquals($result, $candidate) | Should -BeTrue + Test-Path -LiteralPath $operation.WorkRoot | Should -BeFalse + $operation.Credential | Should -BeNullOrEmpty + @($phases) | Should -Be @('Checking', 'Completed') + } + It 'preserves an inspection failure while cleaning the workspace and credential' { + Mock Invoke-RepositoryManifestInspection { throw [IO.IOException]::new('Inspection failed.') } + { Invoke-TargetManifestInspection $operation } | Should -Throw -ExpectedMessage 'Inspection failed.' + Test-Path -LiteralPath $operation.WorkRoot | Should -BeFalse + $operation.Credential | Should -BeNullOrEmpty + @($phases) | Should -Be @('Checking', 'Completed') + } + } } diff --git a/tests/private/installation/Get-InstallationProgressHost.Tests.ps1 b/tests/private/installation/Get-InstallationProgressHost.Tests.ps1 new file mode 100644 index 0000000..cac2a2d --- /dev/null +++ b/tests/private/installation/Get-InstallationProgressHost.Tests.ps1 @@ -0,0 +1,13 @@ +BeforeAll { . "$PSScriptRoot/../../TestHelpers/Import-PMUTestSource.ps1" } +Describe 'Get-InstallationProgressHost' -Tag 'PMU', 'PMUProgress' { + Context 'Native host facts' { + It 'reports native redirection and command-line interactivity without changing either' { + $expectedRedirection = [Console]::IsOutputRedirected + $expectedInteractivity = [Environment]::GetCommandLineArgs() -contains '-NonInteractive' + $hostState = Get-InstallationProgressHost + $hostState.OutputRedirected | Should -Be $expectedRedirection + $hostState.NonInteractive | Should -Be $expectedInteractivity + [Console]::IsOutputRedirected | Should -Be $expectedRedirection + } + } +} diff --git a/tests/private/installation/Write-InstallationPhase.Tests.ps1 b/tests/private/installation/Write-InstallationPhase.Tests.ps1 index ab4d91b..3013bf6 100644 --- a/tests/private/installation/Write-InstallationPhase.Tests.ps1 +++ b/tests/private/installation/Write-InstallationPhase.Tests.ps1 @@ -5,4 +5,25 @@ Describe 'Write-InstallationPhase' -Tag 'PMU', 'PMUProgress' { @(Write-InstallationPhase @{ ModuleName = 'FixtureModule' } 'Staging').Count | Should -Be 0 } } + Context 'Host policy' { + BeforeEach { + Mock Write-InstallationProgress {} + } + It 'suppresses progress for a host' -ForEach @( + @{ HostKind = 'redirected'; OutputRedirected = $true; NonInteractive = $false } + @{ HostKind = 'noninteractive'; OutputRedirected = $false; NonInteractive = $true } + ) { + Mock Get-InstallationProgressHost { @{ OutputRedirected = $OutputRedirected; NonInteractive = $NonInteractive } } + @(Write-InstallationPhase @{ ModuleName = 'FixtureModule' } 'Staging').Count | Should -Be 0 + Should -Invoke Write-InstallationProgress -Times 0 -Exactly + } + It 'forwards the original plan and phase only when the host permits native progress' { + $expectedPlan = [pscustomobject]@{ ModuleName = 'FixtureModule' } + Mock Get-InstallationProgressHost { @{ OutputRedirected = $false; NonInteractive = $false } } + @(Write-InstallationPhase $expectedPlan 'Staging').Count | Should -Be 0 + Should -Invoke Write-InstallationProgress -Times 1 -Exactly -ParameterFilter { + [object]::ReferenceEquals($Plan, $expectedPlan) -and $Phase -ceq 'Staging' + } + } + } } diff --git a/tests/private/installation/Write-InstallationProgress.Tests.ps1 b/tests/private/installation/Write-InstallationProgress.Tests.ps1 new file mode 100644 index 0000000..5e49d07 --- /dev/null +++ b/tests/private/installation/Write-InstallationProgress.Tests.ps1 @@ -0,0 +1,21 @@ +BeforeAll { . "$PSScriptRoot/../../TestHelpers/Import-PMUTestSource.ps1" } +Describe 'Write-InstallationProgress' -Tag 'PMU', 'PMUProgress' { + Context 'Native progress records' { + BeforeEach { + Mock Write-Progress {} + } + It 'emits native status for an interactive update without structured success output' { + @(Write-InstallationProgress @{ ModuleName = 'FixtureModule' } 'Staging').Count | Should -Be 0 + Should -Invoke Write-Progress -Times 1 -Exactly -ParameterFilter { + $Id -eq 17330 -and $Activity -ceq 'Updating FixtureModule' -and + $Status -ceq 'Staging' -and -not $Completed + } + } + It 'completes the same native activity rather than emitting another status update' { + @(Write-InstallationProgress @{ ModuleName = 'FixtureModule' } 'Completed').Count | Should -Be 0 + Should -Invoke Write-Progress -Times 1 -Exactly -ParameterFilter { + $Id -eq 17330 -and $Activity -ceq 'Updating FixtureModule' -and $Completed + } + } + } +} diff --git a/tests/private/locking/Enter-InstallationLock.Tests.ps1 b/tests/private/locking/Enter-InstallationLock.Tests.ps1 index 1cf001b..9db4258 100644 --- a/tests/private/locking/Enter-InstallationLock.Tests.ps1 +++ b/tests/private/locking/Enter-InstallationLock.Tests.ps1 @@ -15,4 +15,13 @@ Describe 'Enter-InstallationLock' -Tag 'PMU' { $second.Dispose() Test-Path $path | Should -BeTrue } + It 'reports permission denial for a directory lock path without deleting its existing contents' { + $path = Join-Path $TestDrive 'directory-lock' + $null = New-Item -ItemType Directory -Path $path + $sentinel = Join-Path $path 'retain.txt' + [IO.File]::WriteAllText($sentinel, 'preserved lock-path contents') + { Enter-InstallationLock $path 100 } | + Should -Throw -ErrorId 'PMU.PermissionDenied' -ExpectedMessage 'Cannot open the scope-specific PMU lock.' + Get-Content -LiteralPath $sentinel -Raw | Should -BeExactly 'preserved lock-path contents' + } } diff --git a/tests/private/locking/Get-LinuxClockTickFrequency.Tests.ps1 b/tests/private/locking/Get-LinuxClockTickFrequency.Tests.ps1 new file mode 100644 index 0000000..ef794b3 --- /dev/null +++ b/tests/private/locking/Get-LinuxClockTickFrequency.Tests.ps1 @@ -0,0 +1,30 @@ +BeforeAll { . "$PSScriptRoot/../../TestHelpers/Import-PMUTestSource.ps1" } +Describe 'Get-LinuxClockTickFrequency' -Tag 'PMUUriBridge' { + Context 'Clock command protocol' { + BeforeEach { + $previousExitCode = Get-Variable LASTEXITCODE -Scope Global -ErrorAction SilentlyContinue + $script:clockExitState = @{ + Present = [bool]$previousExitCode + Value = if ($previousExitCode) { $previousExitCode.Value } else { $null } + } + } + AfterEach { + if ($script:clockExitState.Present) { + Set-Variable LASTEXITCODE $script:clockExitState.Value -Scope Global + } else { + Remove-Variable LASTEXITCODE -Scope Global -ErrorAction SilentlyContinue + } + } + It 'returns the clock command output only after a successful exit' { + $command = Join-Path $TestDrive 'clock-success.ps1' + [IO.File]::WriteAllText($command, "param([string]`$Name); if (`$Name -ne 'CLK_TCK') { exit 2 }; '100'; exit 0") + Get-LinuxClockTickFrequency $command | Should -BeExactly '100' + } + It 'rejects a failed clock command instead of using its plausible numeric output' { + $command = Join-Path $TestDrive 'clock-failure.ps1' + [IO.File]::WriteAllText($command, "'100'; exit 2") + { Get-LinuxClockTickFrequency $command } | + Should -Throw -ExceptionType ([IO.InvalidDataException]) -ExpectedMessage 'Cannot read the Linux process clock frequency.' + } + } +} diff --git a/tests/private/locking/Get-LinuxRepositoryProcessStart.Tests.ps1 b/tests/private/locking/Get-LinuxRepositoryProcessStart.Tests.ps1 index 9333cb7..6f9d267 100644 --- a/tests/private/locking/Get-LinuxRepositoryProcessStart.Tests.ps1 +++ b/tests/private/locking/Get-LinuxRepositoryProcessStart.Tests.ps1 @@ -11,4 +11,44 @@ Describe 'Get-LinuxRepositoryProcessStart' -Tag 'PMUUriBridge' { Should -Invoke Get-LinuxRepositoryProcessStart -Times 0 } } + It 'returns no kernel identity for a nonexistent PID on every supported host' { + Get-LinuxRepositoryProcessStart ([int]::MaxValue) | Should -BeNullOrEmpty + } + Context 'Isolated proc snapshot' { + BeforeEach { + $procRoot = Join-Path $TestDrive ([guid]::NewGuid().ToString('N')) + $processRoot = Join-Path $procRoot '7' + $null = New-Item -ItemType Directory -Path $processRoot -Force + $processStat = Join-Path $processRoot 'stat' + $bootStat = Join-Path $procRoot 'stat' + [IO.File]::WriteAllText($processStat, ('7 (worker ) with spaces) S ' + ('0 ' * 18) + '12345 0 0')) + [IO.File]::WriteAllText($bootStat, "cpu 0`nbtime 1790000000`n") + Mock Get-LinuxClockTickFrequency { '100' } + } + It 'derives the receipt identity from the selected proc snapshot without rewriting it' { + $hash = (Get-FileHash -LiteralPath $processStat).Hash + Get-LinuxRepositoryProcessStart 7 $procRoot | Should -BeExactly '117900001234500000' + (Get-FileHash -LiteralPath $processStat).Hash | Should -BeExactly $hash + } + It 'returns no owner when the selected process disappears before its stat is read' { + Remove-Item -LiteralPath $processStat + Get-LinuxRepositoryProcessStart 7 $procRoot | Should -BeNullOrEmpty + Test-Path -LiteralPath $bootStat | Should -BeTrue + Should -Invoke Get-LinuxClockTickFrequency -Times 0 -Exactly + } + It 'refuses a snapshot whose boot metadata disappeared instead of synthesizing a live owner' { + Remove-Item -LiteralPath $bootStat + $failure = { Get-LinuxRepositoryProcessStart 7 $procRoot } | + Should -Throw -ExceptionType ([Management.Automation.MethodInvocationException]) -PassThru + $failure.Exception.GetBaseException() | Should -BeOfType ([IO.FileNotFoundException]) + Test-Path -LiteralPath $processStat | Should -BeTrue + } + It 'preserves process evidence when the clock command fails' { + Mock Get-LinuxClockTickFrequency { throw [IO.InvalidDataException]::new('Clock frequency unavailable.') } + { Get-LinuxRepositoryProcessStart 7 $procRoot } | + Should -Throw -ExceptionType ([IO.InvalidDataException]) -ExpectedMessage 'Clock frequency unavailable.' + Test-Path -LiteralPath $processStat | Should -BeTrue + Test-Path -LiteralPath $bootStat | Should -BeTrue + } + } } diff --git a/tests/private/locking/Get-WindowsDirectoryDescriptor.Tests.ps1 b/tests/private/locking/Get-WindowsDirectoryDescriptor.Tests.ps1 index bb05dd3..c2cf083 100644 --- a/tests/private/locking/Get-WindowsDirectoryDescriptor.Tests.ps1 +++ b/tests/private/locking/Get-WindowsDirectoryDescriptor.Tests.ps1 @@ -35,6 +35,14 @@ AfterAll { } } Describe 'Get-WindowsDirectoryDescriptor' -Tag 'PMU', 'PMUCoverage' { + BeforeEach { + $identity = [pscustomobject]@{ + User = [pscustomobject]@{ Value = 'S-1-5-21-1234' } + Disposed = $false + } + $identity | Add-Member ScriptMethod Dispose { $this.Disposed = $true } + [PMUTestWindowsIdentity]::Current = $identity + } Context 'Native Windows descriptor' { It 'reads current-user ACL metadata from a disposable directory' -Skip:(-not $IsWindows) { $descriptor = Get-WindowsDirectoryDescriptor $TestDrive @@ -43,12 +51,6 @@ Describe 'Get-WindowsDirectoryDescriptor' -Tag 'PMU', 'PMUCoverage' { } It 'propagates ACL read failures after releasing the current Windows identity' { - $identity = [pscustomobject]@{ - User = [pscustomobject]@{ Value = 'S-1-5-21-1234' } - Disposed = $false - } - $identity | Add-Member ScriptMethod Dispose { $this.Disposed = $true } - [PMUTestWindowsIdentity]::Current = $identity Mock Get-Acl { if (-not $IsWindows) { [PMUTestWindowsIdentity]::Current.Disposed | Should -BeTrue @@ -58,4 +60,25 @@ Describe 'Get-WindowsDirectoryDescriptor' -Tag 'PMU', 'PMUCoverage' { { Get-WindowsDirectoryDescriptor $TestDrive } | Should -Throw -ExpectedMessage 'ACL read failed.' Should -Invoke Get-Acl -Times 1 -Exactly -ParameterFilter { $LiteralPath -eq $TestDrive -and $ErrorAction -eq 'Stop' } } + It 'maps ACL owner and access decisions while retaining the trusted system identities' { + $rules = @( + [pscustomobject]@{ IdentityReference = @{ Value = 'S-1-5-18' }; AccessControlType = 'Allow'; FileSystemRights = [Security.AccessControl.FileSystemRights]::Write } + [pscustomobject]@{ IdentityReference = @{ Value = 'S-1-5-32-545' }; AccessControlType = 'Deny'; FileSystemRights = [Security.AccessControl.FileSystemRights]::Read } + ) + $acl = [pscustomobject]@{ Rules = $rules } + $acl | Add-Member ScriptMethod GetOwner { [pscustomobject]@{ Value = 'S-1-5-18' } } + $acl | Add-Member ScriptMethod GetAccessRules { $this.Rules } + Mock Get-Acl { $acl } + $descriptor = Get-WindowsDirectoryDescriptor $TestDrive + $descriptor.Owner | Should -BeExactly 'S-1-5-18' + $descriptor.Trusted | Should -Contain 'S-1-5-32-544' + $descriptor.Access.Count | Should -Be 2 + $descriptor.Access[0].Identity | Should -BeExactly 'S-1-5-18' + $descriptor.Access[0].Allowed | Should -BeTrue + $descriptor.Access[0].CanWrite | Should -BeTrue + $descriptor.Access[1].Identity | Should -BeExactly 'S-1-5-32-545' + $descriptor.Access[1].Allowed | Should -BeFalse + $descriptor.Access[1].CanWrite | Should -BeFalse + Should -Invoke Get-Acl -Times 1 -Exactly -ParameterFilter { $LiteralPath -ceq $TestDrive -and $ErrorAction -eq 'Stop' } + } } diff --git a/tests/private/locking/Initialize-ControlledDirectory.Tests.ps1 b/tests/private/locking/Initialize-ControlledDirectory.Tests.ps1 index ca6a8bf..461d909 100644 --- a/tests/private/locking/Initialize-ControlledDirectory.Tests.ps1 +++ b/tests/private/locking/Initialize-ControlledDirectory.Tests.ps1 @@ -9,4 +9,20 @@ Describe 'Initialize-ControlledDirectory' -Tag 'PMU' { { Initialize-ControlledDirectory $path } | Should -Throw -ErrorId 'PMU.PermissionDenied' } } + It 'routes a validated Windows directory request to its native adapter without Unix creation' { + # The adapter is isolated; this proves dispatch, not native Windows permissions. + $originalWindows = $IsWindows + $expectedPath = Join-Path $TestDrive 'windows-dispatch' + Mock Initialize-WindowsControlledDirectory {} + try { + Set-Variable IsWindows $true -Force + Initialize-ControlledDirectory $expectedPath + Should -Invoke Initialize-WindowsControlledDirectory -Times 1 -Exactly -ParameterFilter { + $Path -ceq $expectedPath + } + Test-Path -LiteralPath $expectedPath | Should -BeFalse + } finally { + Set-Variable IsWindows $originalWindows -Force + } + } } diff --git a/tests/private/planning/Select-UpdateTarget.Tests.ps1 b/tests/private/planning/Select-UpdateTarget.Tests.ps1 index 06e90a1..c70618b 100644 --- a/tests/private/planning/Select-UpdateTarget.Tests.ps1 +++ b/tests/private/planning/Select-UpdateTarget.Tests.ps1 @@ -11,4 +11,12 @@ Describe 'Select-UpdateTarget' -Tag 'PMU' { It 'fails discovery rather than manufacturing UpToDate on an empty feed' { { Select-UpdateTarget @() 'Stable' } | Should -Throw -ErrorId 'PMU.PackageNotFound' } + It 'retains the newest eligible original release when later entries are older or ineligible' { + $releases = @('2.0.0', '3.0.0', '1.0.0', '9.0.0-preview.1') | ForEach-Object { + [pscustomobject]@{ Version = ConvertTo-CompleteModuleVersion $_ } + } + $target = Select-UpdateTarget $releases 'Stable' + [object]::ReferenceEquals($target, $releases[1]) | Should -BeTrue + $target.Version.FullVersion | Should -BeExactly '3.0.0' + } } diff --git a/tests/private/provider/Assert-NativeInstallationRecord.Tests.ps1 b/tests/private/provider/Assert-NativeInstallationRecord.Tests.ps1 index 762fd0b..e2305d9 100644 --- a/tests/private/provider/Assert-NativeInstallationRecord.Tests.ps1 +++ b/tests/private/provider/Assert-NativeInstallationRecord.Tests.ps1 @@ -11,4 +11,16 @@ Describe 'Assert-NativeInstallationRecord' -Tag 'PMU', 'PMUNativeAdapter' { } { Assert-NativeInstallationRecord $metadata $operation $TestDrive } | Should -Throw -ErrorId 'PMU.UnsupportedInstallation' } + It 'accepts case-insensitive provider module identity without rewriting its native spelling' { + $metadata = [pscustomobject]@{ + Name = 'fIxTuReMoDuLe' + InstalledLocation = $TestDrive + Repository = 'LiteralFeed' + RepositorySourceLocation = 'https://feed.invalid' + } + $operation = @{ Plan = @{ ModuleName = 'FixtureModule' } } + $before = ConvertTo-Json $metadata -Compress + @(Assert-NativeInstallationRecord $metadata $operation $TestDrive).Count | Should -Be 0 + ConvertTo-Json $metadata -Compress | Should -BeExactly $before + } } diff --git a/tests/private/provider/Assert-NativeRecordField.Tests.ps1 b/tests/private/provider/Assert-NativeRecordField.Tests.ps1 index ddd5d61..2d1f63e 100644 --- a/tests/private/provider/Assert-NativeRecordField.Tests.ps1 +++ b/tests/private/provider/Assert-NativeRecordField.Tests.ps1 @@ -4,4 +4,20 @@ Describe 'Assert-NativeRecordField' -Tag 'PMU', 'PMUNativeAdapter' { { Assert-NativeRecordField ([pscustomobject]@{ Name = 'FixtureModule' }) } | Should -Throw -ErrorId 'PMU.UnsupportedInstallation' } + It 'rejects an empty required native metadata value in ' -ForEach @( + @{ Field = 'Name' } + @{ Field = 'Repository' } + @{ Field = 'RepositorySourceLocation' } + @{ Field = 'InstalledLocation' } + ) { + $metadata = [pscustomobject]@{ + Name = 'FixtureModule' + Repository = 'LiteralFeed' + RepositorySourceLocation = 'https://feed.invalid' + InstalledLocation = $TestDrive + } + $metadata.$Field = '' + { Assert-NativeRecordField $metadata } | Should -Throw -ErrorId 'PMU.UnsupportedInstallation' + $metadata.$Field | Should -BeExactly '' + } } diff --git a/tests/private/provider/ConvertTo-ProviderRelease.Tests.ps1 b/tests/private/provider/ConvertTo-ProviderRelease.Tests.ps1 index a91c868..6a08588 100644 --- a/tests/private/provider/ConvertTo-ProviderRelease.Tests.ps1 +++ b/tests/private/provider/ConvertTo-ProviderRelease.Tests.ps1 @@ -12,4 +12,18 @@ Describe 'ConvertTo-ProviderRelease' -Tag 'PMU' { $release.Version.FullVersion | Should -Be '2.0.0.4-preview.3' $release.RequiresLicenseAcceptance | Should -BeTrue } + It 'projects stable release identity and dependency names without provider objects leaking through' { + $resource = [pscustomobject]@{ + Name = 'Fixture' + Version = [version]'2.1.0' + Prerelease = '' + AdditionalMetadata = @{ RequireLicenseAcceptance = 'false' } + Dependencies = @([pscustomobject]@{ Name = 'First' }, [pscustomobject]@{ Name = 'Second' }) + } + $release = ConvertTo-ProviderRelease $resource + $release.Name | Should -BeExactly 'Fixture' + $release.Version.FullVersion | Should -BeExactly '2.1.0' + $release.RequiresLicenseAcceptance | Should -BeFalse + $release.Dependencies | Should -Be @('First', 'Second') + } } diff --git a/tests/private/provider/Get-NativeProviderRoot.Tests.ps1 b/tests/private/provider/Get-NativeProviderRoot.Tests.ps1 index 743997d..8a9eb55 100644 --- a/tests/private/provider/Get-NativeProviderRoot.Tests.ps1 +++ b/tests/private/provider/Get-NativeProviderRoot.Tests.ps1 @@ -6,4 +6,13 @@ Describe 'Get-NativeProviderRoot' -Tag 'PMU', 'PMUNativeAdapter' { Join-Path $operation.WorkRoot "native-$($operation.Journal.TransactionId)" ) } + It 'refuses to invent a native provider nonce when the journal is ' -ForEach @( + @{ State = 'absent'; Journal = $null } + @{ State = 'legacy'; Journal = [pscustomobject]@{ State = 'Completed' } } + ) { + $root = Join-Path $TestDrive "missing-nonce-$State" + $operation = [pscustomobject]@{ WorkRoot = $root; Journal = $Journal } + { Get-NativeProviderRoot $operation } | Should -Throw -ErrorId 'PMU.UnsupportedProviderBehavior' + Test-Path -LiteralPath $root | Should -BeFalse + } } diff --git a/tests/private/provider/Get-ProviderLicenseRequirement.Tests.ps1 b/tests/private/provider/Get-ProviderLicenseRequirement.Tests.ps1 index 43d1bbd..02db72f 100644 --- a/tests/private/provider/Get-ProviderLicenseRequirement.Tests.ps1 +++ b/tests/private/provider/Get-ProviderLicenseRequirement.Tests.ps1 @@ -23,4 +23,14 @@ Describe 'Get-ProviderLicenseRequirement' -Tag 'PMU', 'PMULicense' { Get-ProviderLicenseRequirement @{ AdditionalMetadata = @{ RequireLicenseAcceptance = 'unknown' } } | Should -BeTrue } } + It 'requires consent when nonempty metadata has no license key' { + Get-ProviderLicenseRequirement @{ AdditionalMetadata = @{ Description = 'Fixture' } } | Should -BeTrue + } + It 'requires consent for conflicting key spellings even when both values claim no license requirement' { + $metadata = [Collections.Generic.Dictionary[string, object]]::new([StringComparer]::Ordinal) + $metadata.Add('RequireLicenseAcceptance', $false) + $metadata.Add('requirelicenseacceptance', 'false') + Get-ProviderLicenseRequirement @{ AdditionalMetadata = $metadata } | Should -BeTrue + $metadata.Count | Should -Be 2 + } } diff --git a/tests/private/provider/Write-ProviderError.Tests.ps1 b/tests/private/provider/Write-ProviderError.Tests.ps1 index f585098..dd8ae42 100644 --- a/tests/private/provider/Write-ProviderError.Tests.ps1 +++ b/tests/private/provider/Write-ProviderError.Tests.ps1 @@ -17,4 +17,15 @@ Describe 'Write-ProviderError' -Tag 'PMU' { ($_ | Out-String) | Should -Not -Match 'secret-token-fixture' } } + It 'prioritizes authentication over simultaneous access-denial hints without exposing provider details' { + $failure = [Management.Automation.ErrorRecord]::new( + [UnauthorizedAccessException]::new('401 provider-secret-fixture'), + 'PrivateProviderFailure', + [Management.Automation.ErrorCategory]::PermissionDenied, + $null + ) + $caught = { Write-ProviderError $failure 'PMU.DiscoveryFailed' } | + Should -Throw -ErrorId 'PMU.AuthenticationFailed' -PassThru + "$caught" | Should -Not -Match 'provider-secret-fixture' + } } diff --git a/tests/private/recovery/Assert-RecoveryJournal.Tests.ps1 b/tests/private/recovery/Assert-RecoveryJournal.Tests.ps1 index b0cb379..9975468 100644 --- a/tests/private/recovery/Assert-RecoveryJournal.Tests.ps1 +++ b/tests/private/recovery/Assert-RecoveryJournal.Tests.ps1 @@ -43,4 +43,11 @@ Describe 'Assert-RecoveryJournal' -Tag 'PMU' { $journal.State = 'invalid' { Assert-RecoveryJournal $journal $operation } | Should -Throw -ExpectedMessage 'Recovery paths are not the expected PMU-controlled paths.' } + It 'rejects an unknown state after valid schema identity and paths' { + $operation = Initialize-PMUTestOperation $TestDrive + $journal = ConvertTo-RecoveryJournal $operation @() + $journal.State = 'UnexpectedState' + { Assert-RecoveryJournal $journal $operation } | + Should -Throw -ErrorId 'PMU.RecoveryRequired' -ExpectedMessage 'Recovery journal state is invalid.' + } } diff --git a/tests/private/recovery/Get-SurvivingManifestData.Tests.ps1 b/tests/private/recovery/Get-SurvivingManifestData.Tests.ps1 index f181941..1aeedd2 100644 --- a/tests/private/recovery/Get-SurvivingManifestData.Tests.ps1 +++ b/tests/private/recovery/Get-SurvivingManifestData.Tests.ps1 @@ -4,5 +4,18 @@ Describe 'Get-SurvivingManifestData' -Tag 'PMU' { It 'returns no identity for a missing manifest rather than executing anything' { (Get-SurvivingManifestData "$TestDrive/absent.psd1").Count | Should -Be 0 } + It 'tolerates a truncated journal-owned manifest without executing its contents' { + $path = Join-Path $TestDrive 'Fixture.psd1' + [IO.File]::WriteAllText($path, '@{ ModuleVersion = ') + (Get-SurvivingManifestData $path).Count | Should -Be 0 + Get-Content -LiteralPath $path -Raw | Should -BeExactly '@{ ModuleVersion = ' + } + It 'returns surviving literal identity data from a readable manifest' { + $path = Join-Path $TestDrive 'Fixture.psd1' + [IO.File]::WriteAllText($path, "@{ ModuleVersion = '2.0.0'; GUID = '11111111-1111-1111-1111-111111111111' }") + $manifest = Get-SurvivingManifestData $path + $manifest.ModuleVersion | Should -BeExactly '2.0.0' + $manifest.GUID | Should -BeExactly '11111111-1111-1111-1111-111111111111' + } } } diff --git a/tests/private/recovery/Get-VerifiedRecoveryBackup.Tests.ps1 b/tests/private/recovery/Get-VerifiedRecoveryBackup.Tests.ps1 index 12666d9..f81869e 100644 --- a/tests/private/recovery/Get-VerifiedRecoveryBackup.Tests.ps1 +++ b/tests/private/recovery/Get-VerifiedRecoveryBackup.Tests.ps1 @@ -6,4 +6,16 @@ Describe 'Get-VerifiedRecoveryBackup' -Tag 'PMU' { (Get-VerifiedRecoveryBackup $operation.Journal).Version.FullVersion | Should -Be '2.0.0-preview.1' } } + It 'preserves the surviving backup when its differs from the recovery journal' -ForEach @( + @{ Field = 'ModuleGuid'; Value = '22222222-2222-2222-2222-222222222222' } + @{ Field = 'PreviousVersion'; Value = '2.0.0-preview.9' } + ) { + $operation = Initialize-PMURecoveryFixture $TestDrive + $manifest = Join-Path $operation.BackupPath 'FixtureModule.psd1' + $hash = (Get-FileHash -LiteralPath $manifest).Hash + $operation.Journal.$Field = $Value + { Get-VerifiedRecoveryBackup $operation.Journal 'PMU.RecoveryRequired' } | + Should -Throw -ErrorId 'PMU.RecoveryRequired' -ExpectedMessage 'The surviving backup does not match the previous identity.' + (Get-FileHash -LiteralPath $manifest).Hash | Should -BeExactly $hash + } } diff --git a/tests/private/recovery/Invoke-RecoveryRestoration.Tests.ps1 b/tests/private/recovery/Invoke-RecoveryRestoration.Tests.ps1 index 1d6c646..4592618 100644 --- a/tests/private/recovery/Invoke-RecoveryRestoration.Tests.ps1 +++ b/tests/private/recovery/Invoke-RecoveryRestoration.Tests.ps1 @@ -7,4 +7,16 @@ Describe 'Invoke-RecoveryRestoration' -Tag 'PMU' { $operation.Journal.State | Should -Be 'RecoveryCompleted' } } + It 'preserves the journal and surviving backup when restoration fails' { + $operation = Initialize-PMURecoveryFixture $TestDrive + $manifest = Join-Path $operation.BackupPath 'FixtureModule.psd1' + $hash = (Get-FileHash -LiteralPath $manifest).Hash + Mock Restore-InstallationBackup { throw [IO.IOException]::new('Private restoration details.') } + $failure = { Invoke-RecoveryRestoration $operation.Journal $operation } | + Should -Throw -ErrorId 'PMU.RecoveryFailed' -PassThru + "$failure" | Should -Not -Match 'Private restoration details' + $operation.Journal.State | Should -BeExactly 'ReplacementInProgress' + Test-Path -LiteralPath $operation.Journal.JournalPath | Should -BeTrue + (Get-FileHash -LiteralPath $manifest).Hash | Should -BeExactly $hash + } } diff --git a/tests/private/repository/Assert-RepositoryReceipt.Tests.ps1 b/tests/private/repository/Assert-RepositoryReceipt.Tests.ps1 index 8c971eb..c68d378 100644 --- a/tests/private/repository/Assert-RepositoryReceipt.Tests.ps1 +++ b/tests/private/repository/Assert-RepositoryReceipt.Tests.ps1 @@ -8,4 +8,24 @@ Describe 'Assert-RepositoryReceipt' -Tag 'PMUUriBridge' { { Assert-RepositoryReceipt $receipt } | Should -Throw -ErrorId 'PMU.RepositoryRecoveryRequired*' } } + It 'rejects a missing required receipt field before identity validation' -ForEach @( + @{ Field = 'ApiVersion' } + @{ Field = 'OwnerPid' } + @{ Field = 'UriHash' } + ) { + $receipt = ConvertTo-RepositoryReceipt (Initialize-PMUUriFixture $TestDrive).Source + $receipt.PSObject.Properties.Remove($Field) + { Assert-RepositoryReceipt $receipt } | + Should -Throw -ErrorId 'PMU.RepositoryRecoveryRequired' -ExpectedMessage 'Repository receipt schema is invalid.' + } + It 'rejects altered ownership policy without changing the receipt' -ForEach @( + @{ Field = 'Trusted'; Value = $true } + @{ Field = 'Priority'; Value = 1 } + ) { + $receipt = ConvertTo-RepositoryReceipt (Initialize-PMUUriFixture $TestDrive).Source + $receipt.$Field = $Value + $before = ConvertTo-Json $receipt -Compress + { Assert-RepositoryReceipt $receipt } | Should -Throw -ErrorId 'PMU.RepositoryRecoveryRequired' + ConvertTo-Json $receipt -Compress | Should -BeExactly $before + } } diff --git a/tests/private/repository/Assert-RepositoryReceiptIdentity.Tests.ps1 b/tests/private/repository/Assert-RepositoryReceiptIdentity.Tests.ps1 index f510657..bfef86d 100644 --- a/tests/private/repository/Assert-RepositoryReceiptIdentity.Tests.ps1 +++ b/tests/private/repository/Assert-RepositoryReceiptIdentity.Tests.ps1 @@ -7,4 +7,20 @@ Describe 'Assert-RepositoryReceiptIdentity' -Tag 'PMUUriBridge' { { Assert-RepositoryReceiptIdentity $receipt } | Should -Throw -ErrorId 'PMU.RepositoryRecoveryRequired*' } } + It 'rejects an otherwise valid receipt with invalid ' -ForEach @( + @{ Field = 'SchemaVersion'; Value = 2 } + @{ Field = 'OperationId'; Value = 'ABCDEF0123456789ABCDEF0123456789' } + @{ Field = 'OwnerPid'; Value = '01234' } + @{ Field = 'OwnerStartedUtcTicks'; Value = '12345678901234567' } + @{ Field = 'UriHash'; Value = ('a' * 64) } + @{ Field = 'ApiVersion'; Value = 'v3' } + ) { + $receipt = ConvertTo-RepositoryReceipt (Initialize-PMUUriFixture $TestDrive).Source + if ($Field -eq 'OperationId') { + $receipt.RegistrationName = "pmu-uri-$Value" + } + $receipt.$Field = $Value + { Assert-RepositoryReceiptIdentity $receipt } | + Should -Throw -ErrorId 'PMU.RepositoryRecoveryRequired' -ExpectedMessage 'Repository receipt identity is invalid.' + } } diff --git a/tests/private/repository/Close-OwnedRepositoryTransport.Tests.ps1 b/tests/private/repository/Close-OwnedRepositoryTransport.Tests.ps1 index 9283860..9de277a 100644 --- a/tests/private/repository/Close-OwnedRepositoryTransport.Tests.ps1 +++ b/tests/private/repository/Close-OwnedRepositoryTransport.Tests.ps1 @@ -14,4 +14,20 @@ Describe 'Close-OwnedRepositoryTransport' -Tag 'PMUUriBridge' { Test-Path $path | Should -BeTrue } } + It 'refuses a self-consistent receipt owned by a different process and releases the registry lock' { + Mock Resolve-RepositoryTransportRoot { $TestDrive } + $receipt = ConvertTo-RepositoryReceipt (Initialize-PMUUriFixture $TestDrive).Source + $receipt.OwnerPid = [int]::MaxValue + $path = Write-RepositoryReceipt $receipt $TestDrive + $lease = [pscustomobject]@{ ReceiptPath = $path; Receipt = $receipt } + { Close-OwnedRepositoryTransport $lease } | + Should -Throw -ErrorId 'PMU.RepositoryRecoveryRequired' -ExpectedMessage 'A different operation owns this registration.' + Test-Path -LiteralPath $path | Should -BeTrue + $lock = Enter-RepositoryRegistryLock $TestDrive 50 + try { + $lock.CanWrite | Should -BeTrue + } finally { + $lock.Dispose() + } + } } diff --git a/tests/private/repository/Get-OwnedRepositoryName.Tests.ps1 b/tests/private/repository/Get-OwnedRepositoryName.Tests.ps1 index 1dbf6a9..c11e43e 100644 --- a/tests/private/repository/Get-OwnedRepositoryName.Tests.ps1 +++ b/tests/private/repository/Get-OwnedRepositoryName.Tests.ps1 @@ -6,5 +6,32 @@ Describe 'Get-OwnedRepositoryName' -Tag 'PMUUriBridge' { Mock Get-RepositoryReceiptEntry { } @(Get-OwnedRepositoryName).Count | Should -Be 0 } + Context 'Validated receipt ownership' { + BeforeEach { + $script:ownedSource = (Initialize-PMUUriFixture $TestDrive).Source + $script:ownedReceipt = ConvertTo-RepositoryReceipt $ownedSource + $script:ownedRegistration = [pscustomobject]@{ + Name = $ownedReceipt.RegistrationName + Uri = $ownedSource.Uri + ApiVersion = $ownedReceipt.ApiVersion + Trusted = $false + Priority = 50 + } + Mock Resolve-RepositoryTransportRoot { $TestDrive } + Mock Get-RepositoryReceiptEntry { [pscustomobject]@{ Receipt = $ownedReceipt } } + Mock Get-RepositoryRegistration { $ownedRegistration } + } + It 'returns only the name whose registration matches the durable ownership identity' { + @(Get-OwnedRepositoryName) | Should -Be @($ownedReceipt.RegistrationName) + } + It 'ignores a receipt whose registration no longer exists' { + Mock Get-RepositoryRegistration {} + @(Get-OwnedRepositoryName).Count | Should -Be 0 + } + It 'rejects a reused name with a changed repository endpoint' { + $ownedRegistration.Uri = 'https://other.invalid/v3/index.json' + { Get-OwnedRepositoryName } | Should -Throw -ErrorId 'PMU.RepositoryRecoveryRequired' + } + } } } diff --git a/tests/private/repository/Get-RepositoryReceiptEntry.Tests.ps1 b/tests/private/repository/Get-RepositoryReceiptEntry.Tests.ps1 index 3abe6c0..fa210ac 100644 --- a/tests/private/repository/Get-RepositoryReceiptEntry.Tests.ps1 +++ b/tests/private/repository/Get-RepositoryReceiptEntry.Tests.ps1 @@ -6,5 +6,27 @@ Describe 'Get-RepositoryReceiptEntry' -Tag 'PMUUriBridge' { @(Get-RepositoryReceiptEntry $root).Count | Should -Be 0 Test-Path $root | Should -BeFalse } + It 'reads durable JSON receipts but leaves unrelated files and directories alone' { + $receipt = ConvertTo-RepositoryReceipt (Initialize-PMUUriFixture $TestDrive).Source + Initialize-ControlledDirectory $TestDrive + $path = Write-RepositoryReceipt $receipt $TestDrive + $unrelated = Join-Path $TestDrive 'notes.txt' + [IO.File]::WriteAllText($unrelated, 'retain') + $directory = Join-Path $TestDrive 'directory.json' + $null = New-Item -ItemType Directory -Path $directory + $entries = @(Get-RepositoryReceiptEntry $TestDrive) + $entries.Count | Should -Be 1 + $entries[0].Path | Should -BeExactly $path + $entries[0].Receipt.OperationId | Should -BeExactly $receipt.OperationId + Get-Content -LiteralPath $unrelated -Raw | Should -BeExactly 'retain' + Test-Path -LiteralPath $directory -PathType Container | Should -BeTrue + } + It 'fails closed when an existing receipt catalog contains corrupt JSON' { + Initialize-ControlledDirectory $TestDrive + $path = Join-Path $TestDrive "$([guid]::NewGuid().ToString('N')).json" + [IO.File]::WriteAllText($path, '{"SchemaVersion":') + { Get-RepositoryReceiptEntry $TestDrive } | Should -Throw -ErrorId 'PMU.RepositoryRecoveryRequired' + Test-Path -LiteralPath $path | Should -BeTrue + } } } diff --git a/tests/private/repository/Get-SelectedRepository.Tests.ps1 b/tests/private/repository/Get-SelectedRepository.Tests.ps1 index 0bd69f6..ef8233f 100644 --- a/tests/private/repository/Get-SelectedRepository.Tests.ps1 +++ b/tests/private/repository/Get-SelectedRepository.Tests.ps1 @@ -18,4 +18,16 @@ Describe 'Get-SelectedRepository' -Tag 'PMU', 'PMURepositoryUri' { }).Name | Should -Be 'NamedFixture' } } + It 'preserves a literal string selector and expected endpoint without URI fallback' { + $endpoint = [uri]'https://feed.invalid/v3/index.json' + $snapshot = [pscustomobject]@{ Name = 'LiteralFeed'; Uri = $endpoint.AbsoluteUri } + Mock Get-RepositorySnapshot { $snapshot } + Mock Get-RepositorySnapshotByUri { throw 'URI fallback is prohibited.' } + $result = Get-SelectedRepository 'LiteralFeed' $endpoint + [object]::ReferenceEquals($result, $snapshot) | Should -BeTrue + Should -Invoke Get-RepositorySnapshot -Times 1 -Exactly -ParameterFilter { + $Name -ceq 'LiteralFeed' -and $ExpectedUri -eq $endpoint + } + Should -Invoke Get-RepositorySnapshotByUri -Times 0 -Exactly + } } diff --git a/tests/private/repository/Read-RepositoryReceipt.Tests.ps1 b/tests/private/repository/Read-RepositoryReceipt.Tests.ps1 index 6cee84b..f2424d1 100644 --- a/tests/private/repository/Read-RepositoryReceipt.Tests.ps1 +++ b/tests/private/repository/Read-RepositoryReceipt.Tests.ps1 @@ -27,4 +27,15 @@ Describe 'Read-RepositoryReceipt' -Tag 'PMUUriBridge' { [IO.File]::WriteAllText($path, ('x' * 9000)) { Read-RepositoryReceipt $path $TestDrive } | Should -Throw -ErrorId 'PMU.RepositoryRecoveryRequired*' } + It 'rejects a valid receipt stored under another operation nonce without rewriting either identity' { + $receipt = ConvertTo-RepositoryReceipt (Initialize-PMUUriFixture $TestDrive).Source + $path = Write-RepositoryReceipt $receipt $TestDrive + $renamed = Join-Path $TestDrive "$([guid]::NewGuid().ToString('N')).json" + Move-Item -LiteralPath $path -Destination $renamed + $hash = (Get-FileHash -LiteralPath $renamed).Hash + { Read-RepositoryReceipt $renamed $TestDrive } | + Should -Throw -ErrorId 'PMU.RepositoryRecoveryRequired' -ExpectedMessage 'Repository receipt name does not match its operation.' + (Get-FileHash -LiteralPath $renamed).Hash | Should -BeExactly $hash + Test-Path -LiteralPath $path | Should -BeFalse + } } diff --git a/tests/private/repository/Repair-RepositoryReceipt.Tests.ps1 b/tests/private/repository/Repair-RepositoryReceipt.Tests.ps1 index 508469c..d319bed 100644 --- a/tests/private/repository/Repair-RepositoryReceipt.Tests.ps1 +++ b/tests/private/repository/Repair-RepositoryReceipt.Tests.ps1 @@ -8,5 +8,18 @@ Describe 'Repair-RepositoryReceipt' -Tag 'PMUUriBridge' { Repair-RepositoryReceipt $TestDrive Should -Invoke Clear-OwnedRepositoryReceipt -Times 0 } + It 'removes an abandoned durable receipt only after confirming its owner and registration are absent' { + Initialize-ControlledDirectory $TestDrive + $receipt = ConvertTo-RepositoryReceipt (Initialize-PMUUriFixture $TestDrive).Source + $path = Write-RepositoryReceipt $receipt $TestDrive + Mock Get-RepositoryProcessStart { $null } + Mock Get-RepositoryRegistration {} + Repair-RepositoryReceipt $TestDrive + Test-Path -LiteralPath $path | Should -BeFalse + Test-Path -LiteralPath $TestDrive -PathType Container | Should -BeTrue + Should -Invoke Get-RepositoryRegistration -Times 1 -Exactly -ParameterFilter { + $Name -ceq $receipt.RegistrationName + } + } } } diff --git a/tests/private/repository/Write-BoundRepositoryReceipt.Tests.ps1 b/tests/private/repository/Write-BoundRepositoryReceipt.Tests.ps1 index e93bd04..4528c1f 100644 --- a/tests/private/repository/Write-BoundRepositoryReceipt.Tests.ps1 +++ b/tests/private/repository/Write-BoundRepositoryReceipt.Tests.ps1 @@ -13,5 +13,16 @@ Describe 'Write-BoundRepositoryReceipt' -Tag 'PMUUriBridge' { (Read-RepositoryReceipt $path $TestDrive).ApiVersion | Should -Be Local Test-Path "$path.binding" | Should -BeFalse } + It 'removes the temporary binding after replacement fails without deleting the destination' { + $receipt = ConvertTo-RepositoryReceipt (Initialize-PMUUriFixture $TestDrive).Source + $path = Join-Path $TestDrive "$($receipt.OperationId).json" + $null = New-Item -ItemType Directory -Path $path + $sentinel = Join-Path $path 'retain.txt' + [IO.File]::WriteAllText($sentinel, 'retained destination') + $lease = [pscustomobject]@{ Receipt = $receipt; ReceiptPath = $path; Root = $TestDrive } + { Write-BoundRepositoryReceipt $lease } | Should -Throw + Test-Path -LiteralPath "$path.binding" | Should -BeFalse + Get-Content -LiteralPath $sentinel -Raw | Should -BeExactly 'retained destination' + } } } diff --git a/tests/private/staging/Clear-StagingRoot.Tests.ps1 b/tests/private/staging/Clear-StagingRoot.Tests.ps1 index 1e06a03..a462b2a 100644 --- a/tests/private/staging/Clear-StagingRoot.Tests.ps1 +++ b/tests/private/staging/Clear-StagingRoot.Tests.ps1 @@ -6,4 +6,24 @@ Describe 'Clear-StagingRoot' -Tag 'PMU' { { Clear-StagingRoot $operation } | Should -Throw -ErrorId 'PMU.RecoveryRequired' Test-Path $operation.Plan.InstalledManifestPath | Should -BeTrue } + It 'removes an inventoried staging tree without touching the installed module' { + $operation = Initialize-PMUTestOperation $TestDrive + $null = Initialize-PMUTestPackage $operation.StageRoot $operation.Plan.TargetVersion + Clear-StagingRoot $operation + Test-Path -LiteralPath $operation.StageRoot | Should -BeFalse + Test-Path -LiteralPath $operation.Plan.InstalledManifestPath | Should -BeTrue + } + It 'leaves staging intact when safe inventory validation rejects the tree' { + $operation = Initialize-PMUTestOperation $TestDrive + $null = Initialize-PMUTestPackage $operation.StageRoot $operation.Plan.TargetVersion + Mock Get-FileTreeInventory { throw [IO.IOException]::new('Unsafe staged inventory.') } + { Clear-StagingRoot $operation } | Should -Throw -ExpectedMessage 'Unsafe staged inventory.' + Test-Path -LiteralPath $operation.StagedPath -PathType Container | Should -BeTrue + Test-Path -LiteralPath $operation.Plan.InstalledManifestPath | Should -BeTrue + } + It 'does not create staging when the expected directory is absent' { + $operation = Initialize-PMUTestOperation $TestDrive + Clear-StagingRoot $operation + Test-Path -LiteralPath $operation.StageRoot | Should -BeFalse + } } diff --git a/tests/private/staging/Get-ValidatedStagedTree.Tests.ps1 b/tests/private/staging/Get-ValidatedStagedTree.Tests.ps1 index 5988c4d..fa05c89 100644 --- a/tests/private/staging/Get-ValidatedStagedTree.Tests.ps1 +++ b/tests/private/staging/Get-ValidatedStagedTree.Tests.ps1 @@ -9,4 +9,13 @@ Describe 'Get-ValidatedStagedTree' -Tag 'PMU', 'PMUTargetManifest' { $tree.Count | Should -Be 2 @(Get-Module FixtureModule).Count | Should -Be 0 } + It 'rejects a manifest-only extraction without publishing an incomplete inventory' { + $operation = Initialize-PMUTestOperation $TestDrive + $null = Initialize-PMUTestPackage $operation.StageRoot $operation.Plan.TargetVersion + $manifest = Join-Path $operation.StagedPath 'FixtureModule.psd1' + $definition = [IO.File]::ReadAllText($manifest).Replace("RootModule = 'FixtureModule.psm1';", '') + [IO.File]::WriteAllText($manifest, $definition) + Remove-Item -LiteralPath (Join-Path $operation.StagedPath 'FixtureModule.psm1') + { Get-ValidatedStagedTree $operation } | Should -Throw -ErrorId 'PMU.VerificationFailed' -ExpectedMessage 'The extracted module tree is incomplete.' + } } diff --git a/tests/private/verification/Assert-PackageSource.Tests.ps1 b/tests/private/verification/Assert-PackageSource.Tests.ps1 index ec78010..c5015b4 100644 --- a/tests/private/verification/Assert-PackageSource.Tests.ps1 +++ b/tests/private/verification/Assert-PackageSource.Tests.ps1 @@ -19,4 +19,15 @@ Describe 'Assert-PackageSource' -Tag 'PMU' { [pscustomobject]@{ RepositorySourceLocation = 'https://other.invalid/feed' } | Export-Clixml "$directory/PSGetModuleInfo.xml" { Assert-PackageSource $directory $operation.Plan } | Should -Throw -ErrorId 'PMU.VerificationFailed' } + It 'accepts absent optional source metadata without creating it' { + { Assert-PackageSource $TestDrive @{ RepositoryUri = 'https://feed.invalid' } } | Should -Not -Throw + Test-Path -LiteralPath (Join-Path $TestDrive 'PSGetModuleInfo.xml') | Should -BeFalse + } + It 'does not interpret an empty source property as a conflicting repository' { + $path = Join-Path $TestDrive 'PSGetModuleInfo.xml' + [pscustomobject]@{ RepositorySourceLocation = '' } | Export-Clixml $path + $hash = (Get-FileHash -LiteralPath $path).Hash + { Assert-PackageSource $TestDrive @{ RepositoryUri = 'https://feed.invalid' } } | Should -Not -Throw + (Get-FileHash -LiteralPath $path).Hash | Should -BeExactly $hash + } } diff --git a/tests/private/verification/Get-PackageSourceProperty.Tests.ps1 b/tests/private/verification/Get-PackageSourceProperty.Tests.ps1 index ca24762..b617a66 100644 --- a/tests/private/verification/Get-PackageSourceProperty.Tests.ps1 +++ b/tests/private/verification/Get-PackageSourceProperty.Tests.ps1 @@ -1,9 +1,30 @@ BeforeAll { . "$PSScriptRoot/../../TestHelpers/Import-PMUTestSource.ps1" } Describe 'Get-PackageSourceProperty' -Tag 'PMU' { Context 'Optional independently available metadata' { + BeforeEach { + $packageRoot = Join-Path $TestDrive ([guid]::NewGuid().ToString('N')) + $null = New-Item -ItemType Directory -Path $packageRoot + } It 'reports corrupt metadata rather than treating it as valid provenance' { - [IO.File]::WriteAllText("$TestDrive/PSGetModuleInfo.xml", 'corrupt') - { Get-PackageSourceProperty $TestDrive } | Should -Throw -ErrorId 'PMU.VerificationFailed' + [IO.File]::WriteAllText((Join-Path $packageRoot 'PSGetModuleInfo.xml'), 'corrupt') + { Get-PackageSourceProperty $packageRoot } | Should -Throw -ErrorId 'PMU.VerificationFailed' + } + It 'returns no provenance when optional metadata is missing' { + Get-PackageSourceProperty $packageRoot | Should -BeNullOrEmpty + Test-Path -LiteralPath (Join-Path $packageRoot 'PSGetModuleInfo.xml') | Should -BeFalse + } + It 'returns the available provenance property without modifying provider metadata' { + $path = Join-Path $packageRoot 'PSGetModuleInfo.xml' + [pscustomobject]@{ RepositorySourceLocation = 'https://feed.invalid/v3/index.json' } | Export-Clixml $path + $hash = (Get-FileHash -LiteralPath $path).Hash + $property = Get-PackageSourceProperty $packageRoot + $property.Name | Should -BeExactly 'RepositorySourceLocation' + $property.Value | Should -BeExactly 'https://feed.invalid/v3/index.json' + (Get-FileHash -LiteralPath $path).Hash | Should -BeExactly $hash + } + It 'returns no provenance when readable metadata has no source property' { + [pscustomobject]@{ Name = 'Fixture' } | Export-Clixml (Join-Path $packageRoot 'PSGetModuleInfo.xml') + Get-PackageSourceProperty $packageRoot | Should -BeNullOrEmpty } } } diff --git a/tests/scripts/build/ci/Invoke-PlatformLane.Tests.ps1 b/tests/scripts/build/ci/Invoke-PlatformLane.Tests.ps1 index b80403a..4adb059 100644 --- a/tests/scripts/build/ci/Invoke-PlatformLane.Tests.ps1 +++ b/tests/scripts/build/ci/Invoke-PlatformLane.Tests.ps1 @@ -65,3 +65,29 @@ Describe 'Get-CiLaneDefinition' -Tag 'BuildTooling' { { Get-CiLaneDefinition -LaneId 'nope' } | Should -Throw '*Unknown lane*' } } + +Describe 'Get-CiModuleVersion' -Tag 'BuildTooling', 'CiModuleInventory' { + BeforeEach { + Mock Get-Module { + [pscustomobject]@{ Version = [version]'1.0.0' } + } + } + + It 'reports the qualified provider even when the runtime bundles a newer version' { + Mock Get-Module { + [pscustomobject]@{ Version = [version]'1.3.1' } + [pscustomobject]@{ Version = [version]'1.2.0' } + } -ParameterFilter { $Name -eq 'Microsoft.PowerShell.PSResourceGet' } + $modules = Get-CiModuleVersion + $modules['Microsoft.PowerShell.PSResourceGet'] | Should -BeExactly @('1.2.0') + $modules.Pester | Should -BeExactly @('1.0.0') + } + + It 'does not report an unqualified provider as available when the required version is absent' { + Mock Get-Module { + [pscustomobject]@{ Version = [version]'1.3.1' } + } -ParameterFilter { $Name -eq 'Microsoft.PowerShell.PSResourceGet' } + $modules = Get-CiModuleVersion + $modules['Microsoft.PowerShell.PSResourceGet'].Count | Should -Be 0 + } +} From 6f44b7bf81f7eff64769b34eac9bc878341f706d Mon Sep 17 00:00:00 2001 From: Stiwi Gabriel Courage Date: Mon, 16 Nov 2026 00:34:06 +0100 Subject: [PATCH 8/9] feat: Introduce Get-WindowsDocumentsPath function and update Resolve-ModuleInstallationRoot for improved path resolution --- .../identity/Get-WindowsDocumentsPath.ps1 | 3 ++ .../Resolve-ModuleInstallationRoot.ps1 | 2 +- .../Get-WindowsDocumentsPath.Tests.ps1 | 28 +++++++++++++++++++ .../Resolve-ModuleInstallationRoot.Tests.ps1 | 26 +++++++++++++++-- 4 files changed, 55 insertions(+), 4 deletions(-) create mode 100644 src/private/identity/Get-WindowsDocumentsPath.ps1 create mode 100644 tests/private/identity/Get-WindowsDocumentsPath.Tests.ps1 diff --git a/src/private/identity/Get-WindowsDocumentsPath.ps1 b/src/private/identity/Get-WindowsDocumentsPath.ps1 new file mode 100644 index 0000000..868542e --- /dev/null +++ b/src/private/identity/Get-WindowsDocumentsPath.ps1 @@ -0,0 +1,3 @@ +function Get-WindowsDocumentsPath { + [Environment]::GetFolderPath('MyDocuments') +} diff --git a/src/private/identity/Resolve-ModuleInstallationRoot.ps1 b/src/private/identity/Resolve-ModuleInstallationRoot.ps1 index 5c518b8..2174963 100644 --- a/src/private/identity/Resolve-ModuleInstallationRoot.ps1 +++ b/src/private/identity/Resolve-ModuleInstallationRoot.ps1 @@ -4,7 +4,7 @@ function Resolve-ModuleInstallationRoot { if ($Scope -eq 'AllUsers') { return Assert-SafePath (Join-Path $env:ProgramFiles 'PowerShell/Modules') } - return Assert-SafePath (Join-Path ([Environment]::GetFolderPath('MyDocuments')) 'PowerShell/Modules') + return Assert-SafePath (Join-Path (Get-WindowsDocumentsPath) 'PowerShell/Modules') } if ($Scope -eq 'AllUsers') { return Assert-SafePath '/usr/local/share/powershell/Modules' diff --git a/tests/private/identity/Get-WindowsDocumentsPath.Tests.ps1 b/tests/private/identity/Get-WindowsDocumentsPath.Tests.ps1 new file mode 100644 index 0000000..f383dc3 --- /dev/null +++ b/tests/private/identity/Get-WindowsDocumentsPath.Tests.ps1 @@ -0,0 +1,28 @@ +BeforeAll { . "$PSScriptRoot/../../TestHelpers/Import-PMUTestSource.ps1" } +Describe 'Get-WindowsDocumentsPath' -Tag 'PMU', 'PMUInstallationRoot' { + Context 'Installation-root integration' { + It 'supplies its native fact to Windows CurrentUser routing without filesystem writes' { + $nativeDocuments = Get-WindowsDocumentsPath + $expectedRoot = Join-Path $TestDrive 'native-documents/PowerShell/Modules' + $originalWindows = $IsWindows + Mock Join-Path { $expectedRoot } -ParameterFilter { + $Path -ceq $nativeDocuments -and $ChildPath -ceq 'PowerShell/Modules' + } + try { + Set-Variable IsWindows $true -Force + if ([string]::IsNullOrEmpty($nativeDocuments)) { + { Resolve-ModuleInstallationRoot 'CurrentUser' } | + Should -Throw -ExceptionType ([System.Management.Automation.ParameterBindingException]) + } else { + Resolve-ModuleInstallationRoot 'CurrentUser' | Should -BeExactly $expectedRoot + Should -Invoke Join-Path -Times 1 -Exactly -ParameterFilter { + $Path -ceq $nativeDocuments -and $ChildPath -ceq 'PowerShell/Modules' + } + } + Test-Path -LiteralPath $expectedRoot | Should -BeFalse + } finally { + Set-Variable IsWindows $originalWindows -Force + } + } + } +} diff --git a/tests/private/identity/Resolve-ModuleInstallationRoot.Tests.ps1 b/tests/private/identity/Resolve-ModuleInstallationRoot.Tests.ps1 index 6a49b8c..6f10b81 100644 --- a/tests/private/identity/Resolve-ModuleInstallationRoot.Tests.ps1 +++ b/tests/private/identity/Resolve-ModuleInstallationRoot.Tests.ps1 @@ -1,5 +1,5 @@ BeforeAll { . "$PSScriptRoot/../../TestHelpers/Import-PMUTestSource.ps1" } -Describe 'Resolve-ModuleInstallationRoot' -Tag 'PMU', 'PMUCoverageFollowUp' { +Describe 'Resolve-ModuleInstallationRoot' -Tag 'PMU', 'PMUCoverageFollowUp', 'PMUInstallationRoot' { It 'resolves distinct scope destinations without writing either root' { $user = Resolve-ModuleInstallationRoot 'CurrentUser' $all = Resolve-ModuleInstallationRoot 'AllUsers' @@ -27,8 +27,11 @@ Describe 'Resolve-ModuleInstallationRoot' -Tag 'PMU', 'PMUCoverageFollowUp' { It 'routes Windows CurrentUser modules through the native Documents folder and path safety validation' { # Unit routing only: the controlled Join-Path result is not Windows filesystem qualification. $originalWindows = $IsWindows - $nativeDocuments = [Environment]::GetFolderPath('MyDocuments') - $expectedRoot = Join-Path $TestDrive 'Documents/PowerShell/Modules' + $nativeDocuments = Join-Path $TestDrive 'Documents' + $expectedRoot = Join-Path $nativeDocuments 'PowerShell/Modules' + $safePathCommand = (Get-Command Assert-SafePath).ScriptBlock + Mock Get-WindowsDocumentsPath { $nativeDocuments } + Mock Assert-SafePath { & $safePathCommand $Path } Mock Join-Path { $expectedRoot } -ParameterFilter { $Path -ceq $nativeDocuments -and $ChildPath -ceq 'PowerShell/Modules' } @@ -38,9 +41,26 @@ Describe 'Resolve-ModuleInstallationRoot' -Tag 'PMU', 'PMUCoverageFollowUp' { Should -Invoke Join-Path -Times 1 -Exactly -ParameterFilter { $Path -ceq $nativeDocuments -and $ChildPath -ceq 'PowerShell/Modules' } + Should -Invoke Assert-SafePath -Times 1 -Exactly -ParameterFilter { $Path -ceq $expectedRoot } + Should -Invoke Get-WindowsDocumentsPath -Times 1 -Exactly Test-Path -LiteralPath $expectedRoot | Should -BeFalse } finally { Set-Variable IsWindows $originalWindows -Force } } + It 'rejects an empty Windows Documents fact before path safety instead of selecting another root' { + $originalWindows = $IsWindows + Mock Get-WindowsDocumentsPath { '' } + Mock Assert-SafePath { throw 'An unbound path must not reach path safety validation.' } + try { + Set-Variable IsWindows $true -Force + $failure = { Resolve-ModuleInstallationRoot 'CurrentUser' } | + Should -Throw -ExceptionType ([System.Management.Automation.ParameterBindingException]) -PassThru + $failure.Exception.GetType().FullName | Should -BeExactly 'System.Management.Automation.ParameterBindingValidationException' + $failure.FullyQualifiedErrorId | Should -BeExactly 'ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.JoinPathCommand' + Should -Invoke Assert-SafePath -Times 0 -Exactly + } finally { + Set-Variable IsWindows $originalWindows -Force + } + } } From a0fc08d7ae528f213b698b3d6179e6894cc06735 Mon Sep 17 00:00:00 2001 From: Stiwi Gabriel Courage Date: Mon, 16 Nov 2026 02:48:19 +0100 Subject: [PATCH 9/9] fix: qualify native provider in CI runtimes Provision exact PSGallery PowerShellGet 2.2.5 only inside owned runtime extractions and verify its actual child-process import. Preserve engine checksums, runtime identity, the original test topology and the 95% coverage target. Require native-provider provenance at the aggregate CI gate and cover provisioning, rejection and cleanup contracts. --- CHANGELOG.md | 7 + CONTRIBUTING.md | 3 + RELEASE_NOTE.md | 4 + docs/architecture/TESTING.md | 14 ++ scripts/build/ci/CiGateEvidence.ps1 | 131 ++++++++++++---- scripts/build/ci/CiGateSchema.ps1 | 63 +++++--- scripts/build/ci/Install-CiNativeProvider.ps1 | 138 +++++++++++++++++ scripts/build/ci/Install-CiPowerShell.ps1 | 43 +++++- .../build/ci/Install-CiPowerShellModules.ps1 | 10 +- .../scripts/build/ci/Assert-CiGate.Tests.ps1 | 126 +++++++++++++++- tests/scripts/build/ci/CiGate.TestSupport.ps1 | 120 +++++++++++---- .../ci/Install-CiNativeProvider.Tests.ps1 | 141 ++++++++++++++++++ .../build/ci/Install-CiPowerShell.Tests.ps1 | 56 +++++++ .../ci/Install-CiPowerShellModules.Tests.ps1 | 12 ++ 14 files changed, 784 insertions(+), 84 deletions(-) create mode 100644 scripts/build/ci/Install-CiNativeProvider.ps1 create mode 100644 tests/scripts/build/ci/Install-CiNativeProvider.Tests.ps1 diff --git a/CHANGELOG.md b/CHANGELOG.md index 0cf7deb..fd492a3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,6 +41,13 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), ### Fixed +- Provision exact qualified PowerShellGet 2.2.5 inside owned CI runtimes and + verify its origin, loaded version and manifest path in the aggregate gate. + This preserves PMU's native provider requirement when newer PowerShell + archives bundle an unqualified version; ambient installations are unchanged. +- Isolate the Windows Documents-folder fact in installation-root tests so + Linux runners do not depend on a host Documents folder. Native path + selection, path-safety validation and no-write assertions are unchanged. - Record the qualified PSResourceGet 1.2.0 availability in CI lane manifests even when the selected PowerShell runtime bundles a newer provider, so the aggregate gate does not reject an available required dependency. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3e1f8e8..ba8b185 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -71,6 +71,9 @@ it does not install dependencies in CurrentUser or AllUsers. Existing PSResourceGet repository state is preserved by the provider fixtures, not by assuming that `HOME` or `PSModulePath` redirects registrations. Unexpected skips and incomplete XML/log/runtime evidence fail the lane. +The owned PowerShell runtime also receives exact qualified PowerShellGet 2.2.5; +see [native provider composition](docs/architecture/TESTING.md#qualified-native-provider-in-ci). +This does not change or qualify the native provider in an ambient installation. Dependency provisioning checks that PSGallery points to its official endpoint. If explicit native default registration is needed, it is removed afterward only diff --git a/RELEASE_NOTE.md b/RELEASE_NOTE.md index c045c14..a37d5f3 100644 --- a/RELEASE_NOTE.md +++ b/RELEASE_NOTE.md @@ -52,6 +52,10 @@ This file summarizes public cmdlet, CLI, configuration, and migration changes fo ### Fixed +- Platform CI uses the already-qualified native PowerShellGet 2.2.5 in its + owned runtimes; public commands and ambient installations are unchanged. +- Contributor tests for Windows installation roots no longer fail on Linux + runners without a Documents folder. - Contributor CI no longer rejects the required provider merely because PowerShell also bundles a newer PSResourceGet version. - Update checks now report `PMU.PackageNotFound` when the selected repository diff --git a/docs/architecture/TESTING.md b/docs/architecture/TESTING.md index 48b62a3..b9a0e51 100644 --- a/docs/architecture/TESTING.md +++ b/docs/architecture/TESTING.md @@ -47,6 +47,20 @@ The test/coverage workflow runs `Invoke-NovaTest` before `Test-NovaBuild` and uploads that report for CodeScene; test counts alone do not establish a measured coverage percentage. +### Qualified native provider in CI + +The platform provisioner composes an owned runtime from the checksum-verified +official PowerShell archive and exact PSGallery PowerShellGet 2.2.5. The +qualified provider occupies that runtime's flat `Modules/PowerShellGet` +directory; ambient PowerShell installations and user module stores are not +changed. Provisioning and the aggregate gate retain the archive identity and +check the native provider's source, requested/actual version and manifest path. + +This tests the selected PowerShell engine with PMU's already-qualified native +provider. It does not qualify stock PowerShell 7.7's bundled PowerShellGet 2.2.6. +Production still rejects unqualified provider versions, and native store, +temporary-path and approved-destination safeguards remain unchanged. + ### Native update transition Current local functional evidence on macOS ARM64 / PowerShell 7.4.21 passes. diff --git a/scripts/build/ci/CiGateEvidence.ps1 b/scripts/build/ci/CiGateEvidence.ps1 index cf70e02..635e610 100644 --- a/scripts/build/ci/CiGateEvidence.ps1 +++ b/scripts/build/ci/CiGateEvidence.ps1 @@ -10,11 +10,7 @@ function Assert-CiGateConfiguration { [Parameter(Mandatory)]$Expected ) - foreach ($field in 'id', 'name', 'runner', 'os', 'architecture', 'runtimeIdentifier', 'powershell') { - if ($Manifest.configuration.$field -cne $Expected.$field) { - throw "Lane configuration differs at '$field'." - } - } + Assert-CiGateLaneConfiguration -Actual $Manifest.configuration -Expected $Expected Assert-CiGateSelectedRuntime -Manifest $Manifest -Expected $Expected Assert-CiRuntimeRecord -Record @{ Environment = $Manifest.environment @@ -23,6 +19,16 @@ function Assert-CiGateConfiguration { Assert-CiGateRunnerIdentity -Environment $Manifest.environment } +function Assert-CiGateLaneConfiguration { + param($Actual, $Expected) + + foreach ($field in 'id', 'name', 'runner', 'os', 'architecture', 'runtimeIdentifier', 'powershell') { + if ($Actual.$field -cne $Expected.$field) { + throw "Lane configuration differs at '$field'." + } + } +} + function Assert-CiGateRunnerIdentity { param([Parameter(Mandatory)]$Environment) @@ -47,16 +53,28 @@ function Assert-CiGateSelectedRuntime { OperatingSystem = $Expected.os Architecture = $Expected.architecture } - if ($runtime.PowerShellChannel -cne $Expected.powershell) { + Assert-CiGateRuntimeSelection -Runtime $runtime -Expected $Expected + Assert-CiGateExecutablePath -Executable $runtime.Executable -OperatingSystem $Expected.os +} + +function Assert-CiGateRuntimeSelection { + param($Runtime, $Expected) + + if ($Runtime.PowerShellChannel -cne $Expected.powershell) { throw 'Selected runtime channel differs from lane configuration.' } - if ($runtime.PowerShellVersion -notmatch '^\d+\.\d+\.\d+$') { + if ($Runtime.PowerShellVersion -notmatch '^\d+\.\d+\.\d+$') { throw 'Invalid selected runtime version.' } - Assert-CiGateRuntimeVersion -Runtime $runtime - $absolute = $runtime.Executable -match '^/' - if ($Expected.os -eq 'Windows') { - $absolute = $runtime.Executable -match '^[A-Za-z]:[\\/]' + Assert-CiGateRuntimeVersion -Runtime $Runtime +} + +function Assert-CiGateExecutablePath { + param($Executable, $OperatingSystem) + + $absolute = $Executable -match '^/' + if ($OperatingSystem -eq 'Windows') { + $absolute = $Executable -match '^[A-Za-z]:[\\/]' } if (-not $absolute) { throw 'Selected executable path is not absolute.' @@ -95,12 +113,8 @@ function Assert-CiGateProvisioning { param([Parameter(Mandatory)]$Manifest) $provision = $Manifest.provisioning - if ($provision.sha256 -notmatch '^[a-fA-F0-9]{64}$') { - throw 'Missing verified provisioning checksum.' - } - if (-not $provision.fileName -or -not $provision.hashSource) { - throw 'Incomplete provisioning provenance.' - } + Assert-CiGateNativeProvider -Provisioning $provision + Assert-CiGateArchiveProvenance -Provisioning $provision $expected = @{ channel = $Manifest.configuration.powershell runtimeIdentifier = $Manifest.configuration.runtimeIdentifier @@ -111,6 +125,49 @@ function Assert-CiGateProvisioning { Assert-CiRuntimeRecord -Record $provision.runtime -Expected $Manifest.selectedRuntime } +function Assert-CiGateArchiveProvenance { + param($Provisioning) + + if ($Provisioning.sha256 -notmatch '^[a-fA-F0-9]{64}$') { + throw 'Missing verified provisioning checksum.' + } + if (-not $Provisioning.fileName -or -not $Provisioning.hashSource) { + throw 'Incomplete provisioning provenance.' + } +} + +function Assert-CiGateNativeProvider { + param($Provisioning) + foreach ($field in @{ + name = 'PowerShellGet' + sourceRepository = 'PSGallery' + sourceUri = 'https://www.powershellgallery.com/api/v2' + requestedVersion = '2.2.5' + actualVersion = '2.2.5' + }.GetEnumerator()) { + if ($Provisioning.nativeProvider[$field.Key] -cne $field.Value) { + throw "Native provider provenance differs at '$($field.Key)'." + } + } + Assert-CiGateNativePath -Provisioning $Provisioning +} + +function Assert-CiGateNativePath { + param($Provisioning) + $directory = $Provisioning.directory.Replace('\', '/').TrimEnd('/') + if ($directory -notmatch '^(?:/|[A-Za-z]:/).+' -or $directory -match '(^|/)\.\.?(/|$)') { + throw 'Invalid owned runtime directory.' + } + $manifest = $Provisioning.nativeProvider.manifestPath.Replace('\', '/') + $executable = $Provisioning.executable.Replace('\', '/') + if ($manifest -cne "$directory/Modules/PowerShellGet/PowerShellGet.psd1") { + throw 'Native provider manifest is not the owned runtime flat manifest.' + } + if ($executable.Substring(0, $executable.LastIndexOf('/')) -cne $directory) { + throw 'Native provider runtime differs from the selected executable.' + } +} + function Assert-CiGateTestEvidence { param( [Parameter(Mandatory)]$Manifest, @@ -153,10 +210,16 @@ function Assert-CiSerializedDetail { throw 'Serialized test detail count differs from retained log.' } for ($index = 0; $index -lt $Actual.Count; $index++) { - foreach ($name in 'File', 'Name', 'Result') { - if ($Actual[$index].$name -cne $Serialized[$index].$name) { - throw 'Serialized test detail differs from retained log.' - } + Assert-CiSerializedTestEntry -Actual $Actual[$index] -Serialized $Serialized[$index] + } +} + +function Assert-CiSerializedTestEntry { + param($Actual, $Serialized) + + foreach ($name in 'File', 'Name', 'Result') { + if ($Actual.$name -cne $Serialized.$name) { + throw 'Serialized test detail differs from retained log.' } } } @@ -172,6 +235,12 @@ function Assert-CiGateManifestIdentity { throw "Manifest belongs to another '$name'." } } + Assert-CiGateIdentityConsistency -Manifest $Manifest +} + +function Assert-CiGateIdentityConsistency { + param($Manifest) + if ($Manifest.identity.commitSha -cne $Manifest.commitSha -or $Manifest.identity.laneId -cne $Manifest.laneId) { throw 'Manifest and execution identity differ.' } @@ -188,15 +257,27 @@ function Assert-CiGateManifestEvidence { [Parameter(Mandatory)][string]$Directory ) - Assert-CiGateManifestSchema -Manifest $Manifest - if ($Manifest.schemaVersion -ne 1) { - throw 'Unsupported or missing manifest schema.' - } + Assert-CiGateSupportedSchema -Manifest $Manifest Assert-CiGateManifestIdentity -Manifest $Manifest -RunContext $RunContext Assert-CiGateConfiguration -Manifest $Manifest -Expected $Expected Assert-CiGateProvisioning -Manifest $Manifest Assert-CiLaneRuntimeEvidence -Directory (Join-Path $Directory 'logs') -Phase $Manifest.phases -Expected $Manifest.selectedRuntime -Identity $Manifest.identity Assert-CiGateTestEvidence -Manifest $Manifest -Directory $Directory + Assert-CiGatePassedEvidence -Manifest $Manifest +} + +function Assert-CiGateSupportedSchema { + param($Manifest) + + Assert-CiGateManifestSchema -Manifest $Manifest + if ($Manifest.schemaVersion -ne 1) { + throw 'Unsupported or missing manifest schema.' + } +} + +function Assert-CiGatePassedEvidence { + param($Manifest) + if ((Get-CiLaneStatus -Mismatch $Manifest.mismatches -Phase $Manifest.phases -Summary $Manifest.tests) -ne 'passed') { throw 'Manifest evidence does not establish a passed lane.' } diff --git a/scripts/build/ci/CiGateSchema.ps1 b/scripts/build/ci/CiGateSchema.ps1 index 1ba4632..4f35874 100644 --- a/scripts/build/ci/CiGateSchema.ps1 +++ b/scripts/build/ci/CiGateSchema.ps1 @@ -43,21 +43,33 @@ function Assert-CiGatePhaseSchema { Assert-CiRequiredField -Object $Phase -Name @('Name', 'ExitCode', 'ProcessId', 'Environment', 'Executable', 'DurationSeconds', 'LogFile', 'RuntimeFile', 'TestRuntimeFile') Assert-CiNonnegativeInteger -Value $Phase.ExitCode Assert-CiNonnegativeInteger -Value $Phase.ProcessId - $number = $Phase.DurationSeconds - if ($number.GetType().Name -notin 'Int32', 'Int64', 'Double', 'Decimal') { + Assert-CiGatePhaseDuration -Value $Phase.DurationSeconds + Assert-CiGatePhaseFile -Phase $Phase -Field LogFile -Suffix '.log' -Description 'phase log' + Assert-CiGatePhaseFile -Phase $Phase -Field RuntimeFile -Suffix '.log.runtime.json' -Description 'phase runtime' + Assert-CiGatePhaseFile -Phase $Phase -Field TestRuntimeFile -Suffix '.log.test-runtime.json' -Description 'test runtime' +} + +function Assert-CiGatePhaseDuration { + param($Value) + + if ($Value.GetType().Name -notin 'Int32', 'Int64', 'Double', 'Decimal') { throw 'Invalid phase duration.' } - if (-not [double]::IsFinite($number) -or $number -lt 0) { + if (-not [double]::IsFinite($Value) -or $Value -lt 0) { throw 'Invalid phase duration.' } - if ($Phase.LogFile -cne "$($Phase.Name).log") { - throw 'Unexpected phase log file.' - } - if ($Phase.RuntimeFile -cne "$($Phase.Name).log.runtime.json") { - throw 'Unexpected phase runtime file.' - } - if ($Phase.TestRuntimeFile -cne "$($Phase.Name).log.test-runtime.json") { - throw 'Unexpected test runtime file.' +} + +function Assert-CiGatePhaseFile { + param( + $Phase, + [string]$Field, + [string]$Suffix, + [string]$Description + ) + + if ($Phase.$Field -cne "$($Phase.Name)$Suffix") { + throw "Unexpected $Description file." } } @@ -67,18 +79,24 @@ function Assert-CiGateModuleSchema { $required = @('Pester', 'NovaModuleTools', 'PSScriptAnalyzer', 'Microsoft.PowerShell.PSResourceGet', 'Microsoft.PowerShell.PlatyPS') Assert-CiRequiredField -Object $Module -Name $required foreach ($name in $required) { - if (@($Module[$name]).Count -ne 1) { - throw "Missing selected module availability '$name'." - } - if ($Module[$name][0] -notmatch '^\d+\.\d+\.\d+(?:\.\d+)?$') { - throw "Invalid module version '$name'." - } + Assert-CiGateModuleAvailability -Module $Module -Name $name } if ($Module['Microsoft.PowerShell.PSResourceGet'][0] -cne '1.2.0') { throw 'PSResourceGet 1.2.0 availability is required.' } } +function Assert-CiGateModuleAvailability { + param($Module, [string]$Name) + + if (@($Module[$Name]).Count -ne 1) { + throw "Missing selected module availability '$Name'." + } + if ($Module[$Name][0] -notmatch '^\d+\.\d+\.\d+(?:\.\d+)?$') { + throw "Invalid module version '$Name'." + } +} + function Assert-CiGateManifestSchema { param([Parameter(Mandatory)]$Manifest) @@ -86,10 +104,21 @@ function Assert-CiGateManifestSchema { Assert-CiNonnegativeInteger -Value $Manifest.schemaVersion Assert-CiRequiredField -Object $Manifest.identity -Name @('laneId', 'commitSha', 'runId', 'runAttempt', 'executionId') Assert-CiGateModuleSchema -Module $Manifest.modules + Assert-CiGateNativeSchema -Provisioning $Manifest.provisioning foreach ($phase in $Manifest.phases) { Assert-CiGatePhaseSchema -Phase $phase } + foreach ($name in 'unit', 'integration') { Assert-CiGateSummarySchema -Summary $Manifest.tests[$name] } } + +function Assert-CiGateNativeSchema { + param($Provisioning) + Assert-CiRequiredField -Object $Provisioning -Name @('directory', 'nativeProvider') + Assert-CiRequiredField -Object $Provisioning.nativeProvider -Name @('name', 'sourceRepository', 'sourceUri', 'requestedVersion', 'actualVersion', 'manifestPath', 'archiveBundledVersion') + if ($Provisioning.nativeProvider.archiveBundledVersion -notmatch '^\d+\.\d+\.\d+$') { + throw 'Missing archive-bundled native provider version.' + } +} diff --git a/scripts/build/ci/Install-CiNativeProvider.ps1 b/scripts/build/ci/Install-CiNativeProvider.ps1 new file mode 100644 index 0000000..aefa75c --- /dev/null +++ b/scripts/build/ci/Install-CiNativeProvider.ps1 @@ -0,0 +1,138 @@ +. (Join-Path $PSScriptRoot 'Install-CiPowerShellModules.ps1') + +function Install-CiNativeProvider { + param($Installation) + $owner = Get-CiNativeRuntimeOwner -Path $Installation.directory + $manifest = Join-Path $owner.Path 'Modules/PowerShellGet/PowerShellGet.psd1' + Assert-CiNativeTree -Root $owner.Path -Path $manifest + $bundled = (Import-PowerShellDataFile -LiteralPath $manifest -ErrorAction Stop).ModuleVersion + $stage = Save-CiNativeProviderStage + try { + return Complete-CiNativeProviderOverlay -Installation $Installation -Stage $stage -RuntimeOwner $owner -BundledVersion $bundled + } finally { + Remove-CiDependencyRoot -Owner $stage + } +} + +function Complete-CiNativeProviderOverlay { + param($Installation, [hashtable]$Stage, [hashtable]$RuntimeOwner, [string]$BundledVersion) + $manifest = Join-Path $RuntimeOwner.Path 'Modules/PowerShellGet/PowerShellGet.psd1' + Move-CiNativeProvider -Stage $Stage -RuntimeOwner $RuntimeOwner -ManifestPath $manifest + $probe = Read-CiNativeProviderProbe -Executable (Get-CiInstalledPowerShellExecutable -Installation $Installation) -ManifestPath $manifest + Assert-CiNativeProbe -Probe $probe -ManifestPath $manifest + return Get-CiNativeProviderRecord -Probe $probe -BundledVersion $BundledVersion +} + +function Get-CiNativeRuntimeOwner { + param([string]$Path) + $owner = Get-CiDependencyOwner -Path $Path + if ($owner.Path -eq $PSHOME) { + throw 'The ambient PSHOME cannot receive a native provider overlay.' + } + return $owner +} + +function Save-CiNativeProviderStage { + param() + $path = Join-Path ([IO.Path]::GetTempPath()) "pmu-ci-modules-$([guid]::NewGuid().ToString('N'))" + return Save-CiPowerShellModule -Name PowerShellGet -ModuleRoot $path -Validation { + param($Root) + Assert-CiNativeTree -Root $Root -Path (Join-Path $Root 'PowerShellGet/2.2.5') + Assert-CiNativePayload -Path (Join-Path $Root 'PowerShellGet/2.2.5') + } +} + +function Assert-CiNativeTree { + param([string]$Root, [string]$Path) + $rootPath = [IO.Path]::GetFullPath($Root) + $current = [IO.Path]::GetFullPath($Path) + if (-not $current.StartsWith($rootPath + [IO.Path]::DirectorySeparatorChar)) { + throw 'Native provider path is outside the owned runtime.' + } + Assert-CiNativeAncestry -Path $current -Root $rootPath +} + +function Assert-CiNativeAncestry { + param([string]$Path, [string]$Root) + while ($Path) { + $item = Get-Item -LiteralPath $Path -Force -ErrorAction SilentlyContinue + if ($item -and $item.LinkType) { + throw "Native provider path contains a filesystem link: '$Path'." + } + if ($Path -eq $Root) { return } + $Path = Split-Path -Parent $Path + } +} + +function Move-CiNativeProvider { + param([hashtable]$Stage, [hashtable]$RuntimeOwner, [string]$ManifestPath) + $null = Get-CiDependencyOwner -Path $Stage.Path + $source = Join-Path $Stage.Path 'PowerShellGet/2.2.5' + Assert-CiNativeTree -Root $Stage.Path -Path $source + Assert-CiNativePayload -Path $source + $actual = Get-CiDependencyOwner -Path $RuntimeOwner.Path + if ($actual.Token -cne $RuntimeOwner.Token) { throw 'Runtime ownership changed.' } + Assert-CiNativeTree -Root $RuntimeOwner.Path -Path $ManifestPath + $destination = Split-Path -Parent $ManifestPath + Remove-Item -LiteralPath $destination -Recurse -Force -ErrorAction Stop + Move-Item -LiteralPath $source -Destination $destination -ErrorAction Stop +} + +function Assert-CiNativePayload { + param([string]$Path) + $manifest = Join-Path $Path 'PowerShellGet.psd1' + $items = @(Get-Item -LiteralPath $manifest -Force -ErrorAction Stop) + $items += @(Get-ChildItem -LiteralPath $Path -Recurse -Force -ErrorAction Stop) + if (@($items | Where-Object LinkType).Count) { + throw 'Staged native provider contains a filesystem link.' + } + if ((Import-PowerShellDataFile -LiteralPath $manifest -ErrorAction Stop).ModuleVersion -cne '2.2.5') { + throw 'Staged native provider must be PowerShellGet 2.2.5.' + } +} + +function Get-CiNativeProviderProbeCommand { + param([string]$ManifestPath) + return @" +`$ErrorActionPreference = 'Stop' +`$env:PSModulePath = Join-Path `$PSHOME 'Modules' +Import-Module '__MANIFEST__' -RequiredVersion 2.2.5 -ErrorAction Stop +`$module = Get-Module PowerShellGet -ErrorAction Stop +@{ + name = `$module.Name + actualVersion = `$module.Version.ToString() + manifestPath = Join-Path `$module.ModuleBase 'PowerShellGet.psd1' + runtimeDirectory = `$PSHOME +} | ConvertTo-Json -Compress +"@.Replace('__MANIFEST__', $ManifestPath.Replace("'", "''")) +} + +function Read-CiNativeProviderProbe { + param([string]$Executable, [string]$ManifestPath) + $command = Get-CiNativeProviderProbeCommand -ManifestPath $ManifestPath + $encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($command)) + $output = & $Executable -NoLogo -NoProfile -NonInteractive -EncodedCommand $encoded + if ($LASTEXITCODE -ne 0) { + throw 'Selected runtime native provider import probe failed.' + } + return ($output -join "`n" | ConvertFrom-Json -AsHashtable -ErrorAction Stop) +} + +function Assert-CiNativeProbe { + param($Probe, [string]$ManifestPath) + $runtime = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $ManifestPath)) + foreach ($field in @{ name = 'PowerShellGet'; actualVersion = '2.2.5'; manifestPath = $ManifestPath; runtimeDirectory = $runtime }.GetEnumerator()) { + if ($Probe[$field.Key] -cne $field.Value) { + throw "Selected runtime native provider probe differs at '$($field.Key)'." + } + } +} + +function Get-CiNativeProviderRecord { + param([hashtable]$Probe, [string]$BundledVersion) + $Probe.sourceRepository = 'PSGallery' + $Probe.sourceUri = 'https://www.powershellgallery.com/api/v2' + $Probe.requestedVersion = '2.2.5' + $Probe.archiveBundledVersion = $BundledVersion + return $Probe +} diff --git a/scripts/build/ci/Install-CiPowerShell.ps1 b/scripts/build/ci/Install-CiPowerShell.ps1 index 72f2482..f070203 100644 --- a/scripts/build/ci/Install-CiPowerShell.ps1 +++ b/scripts/build/ci/Install-CiPowerShell.ps1 @@ -10,6 +10,7 @@ param( $script:PowerShellReleaseBase = 'https://github.com/PowerShell/PowerShell/releases/download' $script:PowerShellMetadataUri = 'https://raw.githubusercontent.com/PowerShell/PowerShell/master/tools/metadata.json' . (Join-Path $PSScriptRoot 'CiRuntimeEvidence.ps1') +. (Join-Path $PSScriptRoot 'Install-CiNativeProvider.ps1') function Get-CiPowerShellAssetName { [OutputType([string])] @@ -178,7 +179,21 @@ function Install-CiPowerShell { New-Item -ItemType Directory -Path $InstallRoot -Force | Out-Null $release = Resolve-CiPowerShellRelease -Channel $Channel -RuntimeIdentifier $RuntimeIdentifier -InstallRoot $InstallRoot -PinPath $PinPath $directory = Save-CiPowerShellArchive -Release $release -InstallRoot $InstallRoot - return Get-CiPowerShellInstallationRecord -Channel $Channel -RuntimeIdentifier $RuntimeIdentifier -Release $release -Directory $directory + $installation = Get-CiPowerShellInstallationRecord -Channel $Channel -RuntimeIdentifier $RuntimeIdentifier -Release $release -Directory $directory + return Complete-CiPowerShellInstallation -Installation $installation +} + +function Complete-CiPowerShellInstallation { + param($Installation) + $owner = Get-CiDependencyOwner -Path $Installation.directory + try { + $Installation | Add-Member -NotePropertyName nativeProvider -NotePropertyValue (Install-CiNativeProvider -Installation $Installation) + Assert-CiInstalledPowerShell -Installation $Installation + return $Installation + } catch { + Remove-CiDependencyRoot -Owner $owner + throw + } } function Resolve-CiPowerShellRelease { @@ -196,9 +211,28 @@ function Save-CiPowerShellArchive { $archive = Join-Path $InstallRoot $Release.FileName Invoke-WebRequest -Uri "$script:PowerShellReleaseBase/v$( $Release.Version )/$( $Release.FileName )" -OutFile $archive Assert-CiFileHash -Path $archive -ExpectedSha256 $Release.Sha256 - $directory = Join-Path $InstallRoot "powershell-$( $Release.Version )" - Expand-CiPowerShellArchive -Archive $archive -Destination $directory - return $directory + $root = Resolve-CiInstallRootPath -Path $InstallRoot + $owner = New-CiDependencyRoot -Path (Join-Path $root "pmu-ci-modules-runtime-$([guid]::NewGuid().ToString('N'))") + try { + Expand-CiPowerShellArchive -Archive $archive -Destination $owner.Path + return $owner.Path + } catch { + Remove-CiDependencyRoot -Owner $owner + throw + } +} + +function Resolve-CiInstallRootPath { + param([string]$Path) + $item = Get-Item -LiteralPath $Path -ErrorAction Stop + $resolved = $item.FullName + while ($item) { + if ($item.LinkType) { + $resolved = $item.ResolveLinkTarget($true).FullName + $resolved.Substring($item.FullName.Length) + } + $item = $item.Parent + } + return $resolved } function Get-CiPowerShellInstallationRecord { @@ -289,7 +323,6 @@ function Publish-CiPowerShellEnvironment { if ($MyInvocation.InvocationName -ne '.') { $installation = Install-CiPowerShell -Channel $Channel -RuntimeIdentifier $RuntimeIdentifier -InstallRoot $InstallRoot -PinPath $PinPath - Assert-CiInstalledPowerShell -Installation $installation Publish-CiPowerShellInstallation -Installation $installation -ProvisioningFile $ProvisioningFile Write-Information "Provisioned PowerShell $( $installation.version ) ($( $installation.channel ), $( $installation.hashSource )) at $( $installation.directory )." -InformationAction Continue } diff --git a/scripts/build/ci/Install-CiPowerShellModules.ps1 b/scripts/build/ci/Install-CiPowerShellModules.ps1 index 981fc0d..fbf56c6 100644 --- a/scripts/build/ci/Install-CiPowerShellModules.ps1 +++ b/scripts/build/ci/Install-CiPowerShellModules.ps1 @@ -7,6 +7,7 @@ param( . (Join-Path $PSScriptRoot 'CiDependencyRoot.ps1') $script:PinnedVersion = @{ + PowerShellGet = '2.2.5' Pester = '5.7.1' 'Microsoft.PowerShell.PSResourceGet' = '1.2.0' } @@ -42,12 +43,13 @@ function Get-CiModuleSaveParameter { function Save-CiPowerShellModule { param( [string[]]$Name, - [Parameter(Mandatory)][string]$ModuleRoot + [Parameter(Mandatory)][string]$ModuleRoot, + [scriptblock]$Validation = { param($Path) Assert-CiDependencyClosure -ModuleRoot $Path } ) $owner = New-CiDependencyRoot -Path $ModuleRoot try { - Save-CiModuleSet -Name $Name -ModuleRoot $owner.Path + Save-CiModuleSet -Name $Name -ModuleRoot $owner.Path -Validation $Validation return $owner } catch { Remove-CiDependencyRoot -Owner $owner @@ -56,14 +58,14 @@ function Save-CiPowerShellModule { } function Save-CiModuleSet { - param([string[]]$Name, [string]$ModuleRoot) + param([string[]]$Name, [string]$ModuleRoot, [scriptblock]$Validation) $registered = Open-CiGallery try { $null = Assert-CiGallery foreach ($moduleName in $Name) { Save-CiModuleDownload (Get-CiModuleInstallParameter -Name $moduleName -ModuleRoot $ModuleRoot) } - Assert-CiDependencyClosure -ModuleRoot $ModuleRoot + & $Validation $ModuleRoot } finally { Close-CiGallery -Registered $registered } diff --git a/tests/scripts/build/ci/Assert-CiGate.Tests.ps1 b/tests/scripts/build/ci/Assert-CiGate.Tests.ps1 index 5a86b69..07e9d4e 100644 --- a/tests/scripts/build/ci/Assert-CiGate.Tests.ps1 +++ b/tests/scripts/build/ci/Assert-CiGate.Tests.ps1 @@ -26,16 +26,21 @@ BeforeAll { $directory = Join-Path $TestDrive $Name New-Item -ItemType Directory -Path $directory -Force | Out-Null foreach ($id in $lane) { - $laneStatus = if ($Status.ContainsKey($id)) { - $Status[$id] - } else { - 'passed' - } + $laneStatus = Get-LaneManifestStatus -LaneId $id -Status $Status Write-LaneManifest -Directory $directory -LaneId $id -Status $laneStatus } $directory } + function Get-LaneManifestStatus { + param([string]$LaneId, [hashtable]$Status) + + if ($Status.ContainsKey($LaneId)) { + return $Status[$LaneId] + } + return 'passed' + } + $script:allSuccess = @{ plan = 'success' quality = 'success' @@ -62,6 +67,77 @@ BeforeAll { } Describe 'Test-CiGateResult' -Tag 'BuildTooling' { + Context 'Foreign Windows native provenance' -Tag 'CiNativePortability' { + BeforeAll { + function Write-WindowsLaneManifest { + param([string]$Directory) + + $folder = Join-Path $Directory 'pmu-ci-lane-test-run-1-lane-a' + $path = Join-Path $folder 'lane-manifest.json' + $manifest = Get-Content -LiteralPath $path -Raw | ConvertFrom-Json -AsHashtable + Initialize-WindowsLaneConfiguration -Manifest $manifest + $runtime = Get-CiGateTestRuntime -Identity $manifest.identity + Initialize-WindowsLaneRuntime -Record $runtime + $manifest.environment = $runtime.Environment + $manifest.provisioning.runtime = $runtime + $manifest.phases = @('build', 'unit', 'integration' | ForEach-Object { Write-CiGateTestPhase -Directory $folder -Name $_ -Record $runtime }) + $manifest | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $path + return $manifest.configuration + } + + function Initialize-WindowsLaneConfiguration { + param([hashtable]$Manifest) + + $Manifest.configuration.runner = 'windows-2025' + $Manifest.configuration.os = 'Windows' + $Manifest.configuration.runtimeIdentifier = 'win-x64' + $Manifest.selectedRuntime.OperatingSystem = 'Windows' + $Manifest.selectedRuntime.Executable = 'C:\owned-runtime\pwsh.exe' + $Manifest.provisioning.runtimeIdentifier = 'win-x64' + $Manifest.provisioning.executable = $Manifest.selectedRuntime.Executable + $Manifest.provisioning.directory = 'C:\owned-runtime' + $Manifest.provisioning.nativeProvider.manifestPath = 'C:\owned-runtime\Modules\PowerShellGet\PowerShellGet.psd1' + } + + function Initialize-WindowsLaneRuntime { + param([hashtable]$Record) + + $Record.Executable = 'C:\owned-runtime\pwsh.exe' + $Record.Environment.OperatingSystem = 'Windows' + $Record.Environment.RunnerOs = 'Windows' + $Record.Environment.ImageOs = 'win25' + } + + function Invoke-WindowsTestGate { + param([string]$Directory, [hashtable]$Configuration) + + $context = $script:gateContext.Clone() + $context.commitSha = $sha + $context.lanes = @($Configuration, (Get-CiGateTestConfiguration lane-b)) + Test-CiGateResult -JobResult $script:allSuccess -ExpectedLaneId $lane -ManifestDirectory $Directory -RunContext $context + } + } + + It 'accepts a Windows lane flat native manifest from a non-Windows aggregate host' { + $directory = Build-ManifestDirectory -Name 'windows-flat' + $configuration = Write-WindowsLaneManifest -Directory $directory + @(Invoke-WindowsTestGate -Directory $directory -Configuration $configuration).Count | Should -Be 0 + } + + It 'rejects a Windows lane native manifest with from a non-Windows aggregate host' -ForEach @( + @{ Name = 'outside-root path'; ManifestPath = 'C:\shared\PowerShellGet.psd1' } + @{ Name = 'versioned path'; ManifestPath = 'C:\owned-runtime\Modules\PowerShellGet\2.2.5\PowerShellGet.psd1' } + ) { + $directory = Build-ManifestDirectory -Name $Name + $configuration = Write-WindowsLaneManifest -Directory $directory + $path = Join-Path $directory 'pmu-ci-lane-test-run-1-lane-a/lane-manifest.json' + $manifest = Get-Content -LiteralPath $path -Raw | ConvertFrom-Json -AsHashtable + $manifest.provisioning.nativeProvider.manifestPath = $ManifestPath + $manifest | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $path + @(Invoke-WindowsTestGate -Directory $directory -Configuration $configuration).Count | Should -BeGreaterThan 0 + } + } + It 'passes only when every required job succeeded and every expected lane manifest passed for the commit' { $directory = Build-ManifestDirectory -Name 'ok' @(Invoke-TestGate -JobResult $script:allSuccess ` @@ -146,6 +222,46 @@ Describe 'Test-CiGateResult' -Tag 'BuildTooling' { } It 'rejects invalid lane evidence: ' -ForEach @( + @{ + Name = 'missing native provider' + Field = 'provisioning.nativeProvider' + Value = $null + } + @{ + Name = 'wrong native name' + Field = 'provisioning.nativeProvider.name' + Value = 'Other' + } + @{ + Name = 'wrong requested native version' + Field = 'provisioning.nativeProvider.requestedVersion' + Value = '2.2.6' + } + @{ + Name = 'wrong actual native version' + Field = 'provisioning.nativeProvider.actualVersion' + Value = '2.2.6' + } + @{ + Name = 'untrusted native repository' + Field = 'provisioning.nativeProvider.sourceRepository' + Value = 'Other' + } + @{ + Name = 'untrusted native endpoint' + Field = 'provisioning.nativeProvider.sourceUri' + Value = 'https://unexpected.invalid/api/v2' + } + @{ + Name = 'native manifest outside runtime' + Field = 'provisioning.nativeProvider.manifestPath' + Value = '/shared/PowerShellGet.psd1' + } + @{ + Name = 'versioned native layout' + Field = 'provisioning.nativeProvider.manifestPath' + Value = '/owned-runtime/Modules/PowerShellGet/2.2.5/PowerShellGet.psd1' + } @{ Name = 'wrong run' Field = 'identity.runId' diff --git a/tests/scripts/build/ci/CiGate.TestSupport.ps1 b/tests/scripts/build/ci/CiGate.TestSupport.ps1 index 750cea9..fde06ab 100644 --- a/tests/scripts/build/ci/CiGate.TestSupport.ps1 +++ b/tests/scripts/build/ci/CiGate.TestSupport.ps1 @@ -21,11 +21,23 @@ function Write-CiGateTestPhase { $log = Join-Path $Directory "logs/$Name.log" $Record.Context.phase = $Name - $Record | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath "$log.runtime.json" + Write-CiGateTestPhaseEvidence -Log $log -Name $Name -Record $Record + return Get-CiGateTestPhaseRecord -Name $Name -Record $Record +} + +function Write-CiGateTestPhaseEvidence { + param([string]$Log, [string]$Name, [hashtable]$Record) + + $Record | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath "$Log.runtime.json" if ($Name -ne 'build') { - $Record | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath "$log.test-runtime.json" + $Record | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath "$Log.test-runtime.json" } - @("Running tests from '/fixture/tests/example.Tests.ps1'", 'Describing fixture', ' [+] one 1ms (1ms|0ms)', ' [+] two 1ms (1ms|0ms)') | Set-Content -LiteralPath $log + @("Running tests from '/fixture/tests/example.Tests.ps1'", 'Describing fixture', ' [+] one 1ms (1ms|0ms)', ' [+] two 1ms (1ms|0ms)') | Set-Content -LiteralPath $Log +} + +function Get-CiGateTestPhaseRecord { + param([string]$Name, [hashtable]$Record) + return @{ Name = $Name ExitCode = 0 @@ -47,12 +59,22 @@ function Write-CiGateTestReport { '' | Set-Content -LiteralPath (Join-Path $Directory "$Name-nunit.xml") + Write-CiGateTestDetail -Directory $Directory -Name $Name + return Get-CiGateTestSummary +} + +function Write-CiGateTestDetail { + param([string]$Directory, [string]$Name) + $detail = @('one', 'two' | ForEach-Object { @{ File = 'tests/example.Tests.ps1' Name = $_ Result = 'Passed' } }) $detail | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $Directory "$Name-details.json") +} + +function Get-CiGateTestSummary { return @{ Total = 2 Passed = 2 @@ -81,7 +103,7 @@ function Get-CiGateTestRuntime { param([hashtable]$Identity) return @{ - Executable = '/pwsh' + Executable = '/owned-runtime/pwsh' ProcessId = 123 Environment = (Get-CiGateTestEnvironment) Context = $Identity.Clone() @@ -99,56 +121,98 @@ function Write-CiGateTestManifest { $folder = Join-Path $Directory "pmu-ci-lane-test-run-1-$LaneId" New-Item -ItemType Directory -Path (Join-Path $folder 'logs') -Force | Out-Null - $identity = @{ + $identity = Get-CiGateTestIdentity -LaneId $LaneId -CommitSha $CommitSha + $manifest = Get-CiGateTestManifest -Identity $identity -Status $Status + Complete-CiGateTestManifest -Manifest $manifest -Folder $folder + $manifest | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath (Join-Path $folder 'lane-manifest.json') +} + +function Get-CiGateTestIdentity { + param([string]$LaneId, [string]$CommitSha) + + return @{ laneId = $LaneId commitSha = $CommitSha runId = 'test-run' runAttempt = '1' executionId = 'a' * 32 } - $runtime = Get-CiGateTestRuntime -Identity $identity - $expected = @{ +} + +function Get-CiGateTestSelectedRuntime { + return @{ OperatingSystem = 'Linux' Architecture = 'X64' PowerShellVersion = '7.4.21' PowerShellChannel = '7.4' - Executable = '/pwsh' + Executable = '/owned-runtime/pwsh' } - $phases = @('build', 'unit', 'integration' | ForEach-Object { Write-CiGateTestPhase -Directory $folder -Name $_ -Record $runtime }) - $summary = @{ - unit = (Write-CiGateTestReport -Directory $folder -Name unit) - integration = (Write-CiGateTestReport -Directory $folder -Name integration) - } - $manifest = @{ +} + +function Get-CiGateTestManifest { + param([hashtable]$Identity, [string]$Status) + + return @{ schemaVersion = 1 - laneId = $LaneId - commitSha = $CommitSha + laneId = $Identity.laneId + commitSha = $Identity.commitSha status = $Status - identity = $identity - environment = $runtime.Environment - configuration = (Get-CiGateTestConfiguration $LaneId) - selectedRuntime = $expected - phases = $phases - tests = $summary + identity = $Identity + configuration = (Get-CiGateTestConfiguration $Identity.laneId) mismatches = @() - modules = @{} } - $manifest.provisioning = @{ +} + +function Complete-CiGateTestManifest { + param([hashtable]$Manifest, [string]$Folder) + + $runtime = Get-CiGateTestRuntime -Identity $Manifest.identity + $Manifest.environment = $runtime.Environment + $Manifest.selectedRuntime = Get-CiGateTestSelectedRuntime + $Manifest.phases = @('build', 'unit', 'integration' | ForEach-Object { Write-CiGateTestPhase -Directory $Folder -Name $_ -Record $runtime }) + $Manifest.tests = @{ + unit = (Write-CiGateTestReport -Directory $Folder -Name unit) + integration = (Write-CiGateTestReport -Directory $Folder -Name integration) + } + $Manifest.provisioning = Get-CiGateTestProvisioning -Runtime $runtime + $Manifest.modules = Get-CiGateTestModuleVersion +} + +function Get-CiGateTestProvisioning { + param([hashtable]$Runtime) + + return @{ sha256 = 'a' * 64 fileName = 'archive' hashSource = 'pinned' channel = '7.4' version = '7.4.21' runtimeIdentifier = 'linux-x64' - executable = '/pwsh' - runtime = $runtime + executable = '/owned-runtime/pwsh' + directory = '/owned-runtime' + nativeProvider = Get-CiGateTestNativeProvider + runtime = $Runtime } - $manifest.modules = @{ +} + +function Get-CiGateTestModuleVersion { + return @{ Pester = @('5.9.1') NovaModuleTools = @('3.4.2') PSScriptAnalyzer = @('1.25.0') 'Microsoft.PowerShell.PSResourceGet' = @('1.2.0') 'Microsoft.PowerShell.PlatyPS' = @('1.0.3') } - $manifest | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath (Join-Path $folder 'lane-manifest.json') +} + +function Get-CiGateTestNativeProvider { + return @{ + name = 'PowerShellGet' + sourceRepository = 'PSGallery' + sourceUri = 'https://www.powershellgallery.com/api/v2' + requestedVersion = '2.2.5' + actualVersion = '2.2.5' + manifestPath = '/owned-runtime/Modules/PowerShellGet/PowerShellGet.psd1' + archiveBundledVersion = '2.2.6' + } } diff --git a/tests/scripts/build/ci/Install-CiNativeProvider.Tests.ps1 b/tests/scripts/build/ci/Install-CiNativeProvider.Tests.ps1 new file mode 100644 index 0000000..c376986 --- /dev/null +++ b/tests/scripts/build/ci/Install-CiNativeProvider.Tests.ps1 @@ -0,0 +1,141 @@ +BeforeAll { + $root = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $PSScriptRoot))) + . (Join-Path $root 'scripts/build/ci/Install-CiPowerShell.ps1') + + function Initialize-NativeOverlayFixture { + param([string]$Path, [string]$Version = '2.2.6') + $owner = New-CiDependencyRoot -Path $Path + $manifest = Join-Path $Path 'Modules/PowerShellGet/PowerShellGet.psd1' + New-Item -ItemType Directory -Path (Split-Path $manifest) -Force | Out-Null + "@{ ModuleVersion = '$Version' }" | Set-Content -LiteralPath $manifest + return @{ directory = $owner.Path; runtimeIdentifier = 'osx-arm64'; Owner = $owner } + } + + function Write-NativeOverlayPayload { + param([string]$Path, [string]$Version) + $directory = Join-Path $Path 'PowerShellGet/2.2.5' + New-Item -ItemType Directory -Path $directory -Force | Out-Null + "@{ ModuleVersion = '$Version' }" | Set-Content -LiteralPath (Join-Path $directory 'PowerShellGet.psd1') + } +} + +Describe 'Owned qualified native overlay' -Tag 'CiNativeOverlay' { + BeforeEach { + $script:stagePath = $null + Mock Get-PSRepository { @{ SourceLocation = 'https://www.powershellgallery.com/api/v2'; InstallationPolicy = 'Untrusted' } } + Mock Assert-CiDependencyClosure {} + Mock Save-Module { + $script:stagePath = $Path + Write-NativeOverlayPayload -Path $Path -Version '2.2.5' + } + Mock Read-CiNativeProviderProbe { + @{ + name = 'PowerShellGet' + actualVersion = '2.2.5' + manifestPath = $ManifestPath + runtimeDirectory = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $ManifestPath)) + } + } + } + + It 'installs the trusted exact payload into only the owned flat runtime and observes the selected probe' { + $installation = Initialize-NativeOverlayFixture -Path (Join-Path $TestDrive 'pmu-ci-modules-runtime-flat') + $record = Install-CiNativeProvider -Installation $installation + $record.archiveBundledVersion | Should -Be '2.2.6' + $record.actualVersion | Should -Be '2.2.5' + $record.sourceUri | Should -BeExactly 'https://www.powershellgallery.com/api/v2' + $record.manifestPath | Should -Be (Join-Path $installation.directory 'Modules/PowerShellGet/PowerShellGet.psd1') + (Import-PowerShellDataFile $record.manifestPath).ModuleVersion | Should -Be '2.2.5' + Test-Path (Join-Path $installation.directory 'Modules/PowerShellGet/2.2.5') | Should -BeFalse + Test-Path $script:stagePath | Should -BeFalse + Should -Invoke Save-Module -Times 1 -Exactly -ParameterFilter { $Name -eq 'PowerShellGet' -and $RequiredVersion -eq '2.2.5' -and $Repository -eq 'PSGallery' } + Should -Invoke Read-CiNativeProviderProbe -Times 1 -Exactly -ParameterFilter { $Executable -eq (Join-Path $installation.directory 'pwsh') } + } + + It 'rejects a wrong staged manifest and always cleans staging without touching the bundled provider' { + Mock Save-Module { $script:stagePath = $Path; Write-NativeOverlayPayload -Path $Path -Version '2.2.6' } + $installation = Initialize-NativeOverlayFixture -Path (Join-Path $TestDrive 'pmu-ci-modules-runtime-wrong') + { Install-CiNativeProvider -Installation $installation } | Should -Throw '*2.2.5*' + Test-Path $script:stagePath | Should -BeFalse + (Import-PowerShellDataFile (Join-Path $installation.directory 'Modules/PowerShellGet/PowerShellGet.psd1')).ModuleVersion | Should -Be '2.2.6' + Should -Invoke Read-CiNativeProviderProbe -Times 0 + } + + It 'rejects a linked destination or ancestor: ' -ForEach @( + @{ RelativePath = 'Modules/PowerShellGet' } + @{ RelativePath = 'Modules' } + ) { + $installation = Initialize-NativeOverlayFixture -Path (Join-Path $TestDrive ('pmu-ci-modules-runtime-link-' + $RelativePath.Replace('/', '-'))) + $outside = Join-Path $TestDrive ('shared-' + $RelativePath.Replace('/', '-')) + New-Item -ItemType Directory -Path $outside | Out-Null + $destination = Join-Path $installation.directory $RelativePath + Remove-Item -LiteralPath $destination -Recurse + New-Item -ItemType SymbolicLink -Path $destination -Target $outside | Out-Null + { Install-CiNativeProvider -Installation $installation } | Should -Throw '*link*' + Test-Path $outside | Should -BeTrue + Should -Invoke Save-Module -Times 0 + } + + It 'refuses an ambient runtime without ownership before downloading' { + { Install-CiNativeProvider -Installation @{ directory = $PSHOME; runtimeIdentifier = 'osx-arm64' } } | Should -Throw + Should -Invoke Save-Module -Times 0 + } + + It 'rejects a linked staged manifest and removes its owned staging root' { + $outside = Join-Path $TestDrive 'shared-native.psd1' + "@{ ModuleVersion = '2.2.5' }" | Set-Content -LiteralPath $outside + Mock Save-Module { + $script:stagePath = $Path + Write-NativeOverlayPayload -Path $Path -Version '2.2.5' + $manifest = Join-Path $Path 'PowerShellGet/2.2.5/PowerShellGet.psd1' + Remove-Item -LiteralPath $manifest + New-Item -ItemType SymbolicLink -Path $manifest -Target $outside | Out-Null + } + $installation = Initialize-NativeOverlayFixture -Path (Join-Path $TestDrive 'pmu-ci-modules-runtime-staged-link') + { Install-CiNativeProvider -Installation $installation } | Should -Throw '*link*' + Test-Path $script:stagePath | Should -BeFalse + Test-Path $outside | Should -BeTrue + } + + It 'rejects incorrect observed probe evidence: ' -ForEach @( + @{ Field = 'actualVersion'; Value = '2.2.6' } + @{ Field = 'manifestPath'; Value = '/shared/PowerShellGet.psd1' } + @{ Field = 'name'; Value = 'Other' } + @{ Field = 'runtimeDirectory'; Value = '/shared' } + ) { + Mock Read-CiNativeProviderProbe { + $record = @{ + name = 'PowerShellGet' + actualVersion = '2.2.5' + manifestPath = $ManifestPath + runtimeDirectory = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $ManifestPath)) + } + + $record[$Field] = $Value + return $record + } + $installation = Initialize-NativeOverlayFixture -Path (Join-Path $TestDrive "pmu-ci-modules-runtime-probe-$Field") + { Install-CiNativeProvider -Installation $installation } | Should -Throw '*probe*' + Test-Path $script:stagePath | Should -BeFalse + } +} + +Describe 'Selected native import probe protocol' -Tag 'CiNativeOverlay' { + It 'requests the exact flat manifest and qualified import version in the selected child command' { + $command = Get-CiNativeProviderProbeCommand -ManifestPath "/owned/runtime's/Modules/PowerShellGet/PowerShellGet.psd1" + $command | Should -Match "Import-Module '/owned/runtime''s/Modules/PowerShellGet/PowerShellGet.psd1' -RequiredVersion 2.2.5" + $command | Should -Match '\$module.Version.ToString\(\)' + $command | Should -Match '\$module.ModuleBase' + $command | Should -Match 'runtimeDirectory = \$PSHOME' + } + + It 'propagates the selected child import failure rather than publishing assumed metadata' { + Mock Get-CiNativeProviderProbeCommand { 'exit 7' } + { Read-CiNativeProviderProbe -Executable (Get-Process -Id $PID).Path -ManifestPath '/unused' } | Should -Throw '*import probe failed*' + } + + It 'rejects malformed selected child evidence' { + Mock Get-CiNativeProviderProbeCommand { "'not json'" } + { Read-CiNativeProviderProbe -Executable (Get-Process -Id $PID).Path -ManifestPath '/unused' } | Should -Throw + } +} diff --git a/tests/scripts/build/ci/Install-CiPowerShell.Tests.ps1 b/tests/scripts/build/ci/Install-CiPowerShell.Tests.ps1 index 621b3b3..53ea2c0 100644 --- a/tests/scripts/build/ci/Install-CiPowerShell.Tests.ps1 +++ b/tests/scripts/build/ci/Install-CiPowerShell.Tests.ps1 @@ -4,6 +4,62 @@ BeforeAll { $script:pinPath = Join-Path $root 'scripts/build/ci/PowerShellVersions.json' } +Describe 'Qualified runtime installation transaction' -Tag 'CiNativeOverlay' { + BeforeEach { + $script:installRoot = Join-Path $TestDrive ([guid]::NewGuid().ToString('N')) + New-Item -ItemType Directory -Path $script:installRoot | Out-Null + Mock Resolve-CiPowerShellRelease { + @{ Version = '7.7.0'; FileName = 'archive.tar.gz'; Sha256 = ('a' * 64); HashSource = 'official hashes' } + } + Mock Invoke-WebRequest {} + Mock Assert-CiFileHash {} + Mock Expand-CiPowerShellArchive {} + Mock Install-CiNativeProvider { @{ actualVersion = '2.2.5' } } + Mock Assert-CiInstalledPowerShell {} + } + + It 'overlays before returning the unchanged checksum and runtime identity' { + $installation = Install-CiPowerShell -Channel stable -RuntimeIdentifier osx-arm64 -InstallRoot $script:installRoot -PinPath $script:pinPath + $installation.nativeProvider.actualVersion | Should -Be '2.2.5' + $installation.sha256 | Should -Be ('a' * 64) + $installation.version | Should -Be '7.7.0' + $installation.channel | Should -Be 'stable' + Should -Invoke Assert-CiFileHash -Times 1 -Exactly -ParameterFilter { $ExpectedSha256 -eq ('a' * 64) } + Should -Invoke Install-CiNativeProvider -Times 1 -Exactly + } + + It 'cleans only the newly extracted owned runtime when the overlay or probe fails' { + Mock Install-CiNativeProvider { throw 'native probe failed' } + $sentinel = Join-Path $script:installRoot 'shared.txt' + Set-Content $sentinel 'preserve' + { Install-CiPowerShell -Channel stable -RuntimeIdentifier osx-arm64 -InstallRoot $script:installRoot -PinPath $script:pinPath } | Should -Throw '*native probe failed*' + Test-Path $sentinel | Should -BeTrue + @(Get-ChildItem $script:installRoot -Directory -Filter 'pmu-ci-modules-*').Count | Should -Be 0 + } + + It 'does not extract or overlay a checksum failure' { + Mock Assert-CiFileHash { throw 'checksum mismatch' } + { Install-CiPowerShell -Channel stable -RuntimeIdentifier osx-arm64 -InstallRoot $script:installRoot -PinPath $script:pinPath } | Should -Throw '*checksum mismatch*' + Should -Invoke Expand-CiPowerShellArchive -Times 0 + Should -Invoke Install-CiNativeProvider -Times 0 + } + + It 'cleans only its fresh runtime when extraction fails' { + Mock Expand-CiPowerShellArchive { throw 'extraction failed' } + { Install-CiPowerShell -Channel stable -RuntimeIdentifier osx-arm64 -InstallRoot $script:installRoot -PinPath $script:pinPath } | Should -Throw '*extraction failed*' + Test-Path $script:installRoot | Should -BeTrue + @(Get-ChildItem $script:installRoot -Directory -Filter 'pmu-ci-modules-*').Count | Should -Be 0 + Should -Invoke Install-CiNativeProvider -Times 0 + } + + It 'cleans only its fresh runtime when the original runtime identity probe fails' { + Mock Assert-CiInstalledPowerShell { throw 'runtime identity differs' } + { Install-CiPowerShell -Channel stable -RuntimeIdentifier osx-arm64 -InstallRoot $script:installRoot -PinPath $script:pinPath } | Should -Throw '*runtime identity differs*' + Test-Path $script:installRoot | Should -BeTrue + @(Get-ChildItem $script:installRoot -Directory -Filter 'pmu-ci-modules-*').Count | Should -Be 0 + } +} + Describe 'Get-CiPowerShellAssetName' -Tag 'BuildTooling' { It 'names the official archive for ' -ForEach @( @{ diff --git a/tests/scripts/build/ci/Install-CiPowerShellModules.Tests.ps1 b/tests/scripts/build/ci/Install-CiPowerShellModules.Tests.ps1 index 66805b9..0617295 100644 --- a/tests/scripts/build/ci/Install-CiPowerShellModules.Tests.ps1 +++ b/tests/scripts/build/ci/Install-CiPowerShellModules.Tests.ps1 @@ -4,6 +4,18 @@ BeforeAll { } Describe 'Get-CiModuleInstallParameter' -Tag 'BuildTooling' { + It 'explicitly acquires only qualified PowerShellGet 2.2.5 from PSGallery' { + $parameter = Get-CiModuleInstallParameter -Name PowerShellGet -ModuleRoot $TestDrive + $parameter.RequiredVersion | Should -Be '2.2.5' + $parameter.Repository | Should -BeExactly 'PSGallery' + $parameter.Path | Should -Be $TestDrive + } + + It 'does not add the native overlay to the default dependency list' { + $command = Get-Command (Join-Path $root 'scripts/build/ci/Install-CiPowerShellModules.ps1') + $command.ScriptBlock.Ast.ParamBlock.Parameters[0].DefaultValue.SafeGetValue() | Should -Not -Contain 'PowerShellGet' + } + It 'pins Pester to the version used by the repository quality pipeline' { $parameter = Get-CiModuleInstallParameter -Name 'Pester' $parameter.RequiredVersion | Should -Be '5.7.1'