diff --git a/.github/workflows/test-runtimes.yml b/.github/workflows/test-runtimes.yml index dbfd810f..9f7794da 100644 --- a/.github/workflows/test-runtimes.yml +++ b/.github/workflows/test-runtimes.yml @@ -25,10 +25,10 @@ jobs: os: windows-latest shell: powershell version: '5.1' - - name: windows-powershell-7.0 + - name: windows-powershell-7.4 os: windows-latest shell: pwsh - version: '7.0' + version: '7.4' - name: windows-powershell-7 os: windows-latest shell: pwsh @@ -49,12 +49,12 @@ jobs: ref: ${{ inputs.ref }} - name: Install minimum supported PowerShell - if: matrix.version == '7.0' + if: matrix.version == '7.4' shell: pwsh run: | - $Path = Join-Path -Path $env:RUNNER_TEMP -ChildPath "powershell-7.0.13" + $Path = Join-Path -Path $env:RUNNER_TEMP -ChildPath "powershell-7.4.0" $Archive = "$Path.zip" - Invoke-WebRequest -Uri "https://github.com/PowerShell/PowerShell/releases/download/v7.0.13/PowerShell-7.0.13-win-x64.zip" -OutFile $Archive -ErrorAction Stop + Invoke-WebRequest -Uri "https://github.com/PowerShell/PowerShell/releases/download/v7.4.0/PowerShell-7.4.0-win-x64.zip" -OutFile $Archive -ErrorAction Stop Expand-Archive -LiteralPath $Archive -DestinationPath $Path $Path | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append diff --git a/.rules/PSScriptAnalyzerSettings.psd1 b/.rules/PSScriptAnalyzerSettings.psd1 index 7f70ee67..a5930ec1 100644 --- a/.rules/PSScriptAnalyzerSettings.psd1 +++ b/.rules/PSScriptAnalyzerSettings.psd1 @@ -17,7 +17,7 @@ PSUseCompatibleSyntax = @{ Enable = $true TargetVersions = @( - '7.0' + '7.4' '5.1' ) } diff --git a/.vscode/PSScriptAnalyzerSettings.psd1 b/.vscode/PSScriptAnalyzerSettings.psd1 index a1cb2ca6..f977eb49 100644 --- a/.vscode/PSScriptAnalyzerSettings.psd1 +++ b/.vscode/PSScriptAnalyzerSettings.psd1 @@ -12,7 +12,7 @@ } PSUseCompatibleSyntax = @{ TargetedVersions = @( - '7.0' + '7.4' '6.0' '5.1' ) diff --git a/CHANGELOG.md b/CHANGELOG.md index d90e923f..8e7e8a03 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,14 +2,21 @@ ## VERSION +> [!WARNING] +> The module now requires Windows PowerShell 5.1 or PowerShell 7.4 or later on Windows, macOS, or Linux; PowerShell 4.0 or PowerShell 6/7.0-7.3 are no longer supported. + This version strengthens download and library reliability, improves validation and error reporting across public cmdlets, and refreshes help documentation. +- **Supported runtimes:** Raise the minimum supported PowerShell 7 version to 7.4 while retaining Windows PowerShell 5.1 support. Update the CI runtime matrix, syntax checks, test setup, and support documentation. - **Downloads — `Save-EvergreenApp`:** Add optional `-VerifyChecksum` support for SHA-1, SHA-256, and SHA-512 hashes. Add bounded retries with exponential backoff and `Retry-After` handling, plus configurable connection and operation timeouts. Validate destination paths and filenames, support pipeline-bound paths, honor `-WhatIf` and custom user agents, publish only completed downloads, clean up partial files, and restore TLS settings. - **App lookup and API queries — `Get-EvergreenApp`, `Find-EvergreenApp`, `Get-EvergreenAppFromApi`, `Get-EvergreenEndpointFromApi`:** Validate app names and API inputs, encode names for requests, preserve API error details, and reuse output filtering for local and API results. Improve literal-name matching and not-found diagnostics; clean up proxy and certificate state on completion or terminating errors. `Get-EvergreenApp` diagnostics now include exception and location details while preserving the original error. - **Exports — `Export-EvergreenApp`, `Export-EvergreenManifest`:** Support pipeline input and improve validation and error reporting. `Export-EvergreenApp` batches pipeline records into a single write, respects `-WhatIf`, and preserves arrays, nested data, and nonstandard versions when merging and sorting. - **Library operations — `Start-EvergreenLibraryUpdate`, `Get-EvergreenLibrary`, `Get-EvergreenAppFromLibrary`, `Remove-EvergreenLibraryAppVersion`:** Improve mixed-version sorting and isolate per-app state. Export only entries with matching installer files; stage manifest updates before deleting files; and reject unsafe paths and reparse points. Clarify pruning behavior and correct installer-path handling for retained entries. - **Validation and compatibility — `Test-EvergreenApp`, `ConvertTo-DotNetVersionClass`, `Convert-Segment`, `Expand-CabArchive`:** Add HEAD-to-ranged-GET fallback, configurable timeouts, and HTTP status results to `Test-EvergreenApp`. Harden version conversion and make CAB extraction preserve original filenames and extensions. Support the insecure-redirect option on Windows PowerShell 5.1 while retaining compatibility checks for PowerShell Core. - **Module initialization and help:** Handle GitHub rate limits and invalid cache versions in `Evergreen.psm1`; update `Import.ps1`; and refresh cmdlet and module help, including German, Spanish, French, and Japanese documentation. +- **Confirmation and preview — `Update-Evergreen`, `Remove-ProxyEnv`:** Add `-WhatIf` and `-Confirm` support. Guard the entire cache update before downloads or cache changes, and guard each proxy variable removal. Add regression coverage and document cache update confirmation behavior. +- **Analyzer compliance and compatibility:** Resolve configured PSScriptAnalyzer findings with targeted compatibility suppressions for platform-guarded code, naming and keyword corrections, and encoding fixes. Preserve default automatic date detection without a default-enabled switch parameter, and use Unicode escapes in CAB path validation. +- **Diagnostics — `Save-EvergreenApp`, `Update-Evergreen`:** Warn when retry-response status codes or `Retry-After` headers cannot be parsed, and route cache hash-validation failures through `Write-Message` with the appropriate message type. ## 2610.2862.0 diff --git a/CLAUDE.md b/CLAUDE.md index 08872582..e8636b0f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -92,7 +92,7 @@ Module version follows `YYmm.Build` (e.g., `2511.2826.0`). The `update-module.ym ## Code Conventions - **One function per file**, filename must exactly match the function name (enforced by `Main.Tests.ps1`). -- Supports Windows PowerShell 5.1 and PowerShell 7.0+. Avoid PS6-only APIs. +- Supports Windows PowerShell 5.1 and PowerShell 7.4+. Avoid PS6-only APIs. - PSScriptAnalyzer is run at `Error` and `Warning` severity. `PSAvoidUsingWriteHost` is excluded (use `Write-Message` instead). - GitHub API calls check for `GITHUB_TOKEN` or `GH_TOKEN` environment variables to avoid rate limits. - App functions are dot-sourced lazily (at invocation time, not module import) to reduce memory footprint. diff --git a/Evergreen/Evergreen.psm1 b/Evergreen/Evergreen.psm1 index 40215460..9ec09be2 100644 --- a/Evergreen/Evergreen.psm1 +++ b/Evergreen/Evergreen.psm1 @@ -3,6 +3,7 @@ Evergreen script to initiate the module #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSReviewUnusedParameter", "", Justification = "Required for argument completion.")] +[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCommands", "", Justification = "Not reachable on Ubuntu: Get-CimInstance")] [CmdletBinding(SupportsShouldProcess = $false)] param () diff --git a/Evergreen/Private/ConvertFrom-Jwt.ps1 b/Evergreen/Private/ConvertFrom-Jwt.ps1 index ffdc3534..ea94d116 100644 --- a/Evergreen/Private/ConvertFrom-Jwt.ps1 +++ b/Evergreen/Private/ConvertFrom-Jwt.ps1 @@ -19,7 +19,7 @@ function ConvertFrom-Jwt { } # Helper: Convert Base64URL to Base64 and decode to JSON - function Decode-Part([System.String]$Part, [System.String]$Name) { + function Convert-Part ([System.String]$Part, [System.String]$Name) { # Fix Base64URL encoding (replace - and _) $replaced = $Part.Replace('-', '+').Replace('_', '/') # Pad string length to multiple of 4 @@ -42,8 +42,8 @@ function ConvertFrom-Jwt { # Return the decoded header and payload as a custom object [PSCustomObject]@{ - Header = Decode-Part -Part $parts[0] -Name "Header" - Payload = Decode-Part -Part $parts[1] -Name "Payload" + Header = Convert-Part -Part $parts[0] -Name "Header" + Payload = Convert-Part -Part $parts[1] -Name "Payload" Signature = if ($parts.Count -gt 2) { $parts[2] } else { $null } } | Write-Output } diff --git a/Evergreen/Private/ConvertTo-DateTime.ps1 b/Evergreen/Private/ConvertTo-DateTime.ps1 index 30e860ca..9496a167 100644 --- a/Evergreen/Private/ConvertTo-DateTime.ps1 +++ b/Evergreen/Private/ConvertTo-DateTime.ps1 @@ -28,12 +28,13 @@ function ConvertTo-DateTime { [System.String] $Pattern = "M/d/yyyy", [Parameter()] - [System.Management.Automation.SwitchParameter] $AutoDetect = $true + [System.Management.Automation.SwitchParameter] $AutoDetect ) Write-Verbose -Message "$($MyInvocation.MyCommand): Converting: [$DateTime]." $Parsed = $false - if ($AutoDetect) { + $UseAutoDetect = -not $PSBoundParameters.ContainsKey('AutoDetect') -or $AutoDetect + if ($UseAutoDetect) { [System.String[]] $KnownFormats = @( "M/d/yyyy" "MM/dd/yyyy HH:mm:ss" diff --git a/Evergreen/Private/Expand-CabArchive.ps1 b/Evergreen/Private/Expand-CabArchive.ps1 index f0c76264..6e9654fd 100644 --- a/Evergreen/Private/Expand-CabArchive.ps1 +++ b/Evergreen/Private/Expand-CabArchive.ps1 @@ -1,5 +1,6 @@ function Expand-CabArchive { [CmdletBinding(SupportsShouldProcess = $false)] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCommands", "", Justification = "Not reachable on Ubuntu: New-Object -ComObject")] param ( [Parameter(Mandatory = $true, Position = 0)] [ValidateNotNullOrEmpty()] @@ -66,7 +67,7 @@ function Expand-CabArchive { if ($Segment.IndexOfAny($InvalidCharacters) -ge 0 -or $Segment -match '[<>:"/\\|?*\x00-\x1F]' -or $Segment -match '[ .]$' -or - $Segment -match '^(CON|PRN|AUX|NUL|COM[1-9¹²³]|LPT[1-9¹²³])(?:\.|$)') { + $Segment -match '^(CON|PRN|AUX|NUL|COM[1-9\u00B9\u00B2\u00B3]|LPT[1-9\u00B9\u00B2\u00B3])(?:\.|$)') { throw "CAB item path '$Name' contains an invalid file name." } } diff --git a/Evergreen/Private/Get-FilteredData.ps1 b/Evergreen/Private/Get-FilteredData.ps1 index b9835c31..99cb9c18 100644 --- a/Evergreen/Private/Get-FilteredData.ps1 +++ b/Evergreen/Private/Get-FilteredData.ps1 @@ -35,7 +35,7 @@ function Get-FilteredData { System.Object[] (an array of PSObjects or any objects with properties) .OUTPUTS - System.Object[] — the subset of InputObject that match the provided filter configuration. + System.Object[] - the subset of InputObject that match the provided filter configuration. .EXAMPLE # filters.json (example) diff --git a/Evergreen/Private/Get-FunctionResource.ps1 b/Evergreen/Private/Get-FunctionResource.ps1 index eb7c8ade..66c4a5fe 100644 --- a/Evergreen/Private/Get-FunctionResource.ps1 +++ b/Evergreen/Private/Get-FunctionResource.ps1 @@ -4,6 +4,7 @@ function Get-FunctionResource { Reads an application manifest from JSON and returns a hashtable. #> [OutputType([System.Collections.IDictionary])] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCommands", "", Justification = "Not reachable on PS5.1: ConvertFrom-Json -AsHashtable")] [CmdletBinding(SupportsShouldProcess = $false)] param ( [Parameter(Mandatory = $true, Position = 0)] diff --git a/Evergreen/Private/Get-ModuleResource.ps1 b/Evergreen/Private/Get-ModuleResource.ps1 index 741a1711..a89a62eb 100644 --- a/Evergreen/Private/Get-ModuleResource.ps1 +++ b/Evergreen/Private/Get-ModuleResource.ps1 @@ -4,6 +4,7 @@ function Get-ModuleResource { Reads the module strings from the JSON file and returns a hashtable. #> [OutputType([System.Collections.IDictionary])] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCommands", "", Justification = "Not reachable on PS5.1: ConvertFrom-Json -AsHashtable")] [CmdletBinding(SupportsShouldProcess = $false)] param ( [Parameter(Mandatory = $false, Position = 0)] diff --git a/Evergreen/Private/Invoke-EvergreenRestMethod.ps1 b/Evergreen/Private/Invoke-EvergreenRestMethod.ps1 index 2737f040..b1f5e629 100644 --- a/Evergreen/Private/Invoke-EvergreenRestMethod.ps1 +++ b/Evergreen/Private/Invoke-EvergreenRestMethod.ps1 @@ -49,7 +49,7 @@ function Invoke-EvergreenRestMethod { $ErrorActionPreference = $ErrorAction } else { - $ErrorActionPreference = [System.Management.Automation.ActionPreference]::Continue + $ErrorActionPreference = [System.Management.Automation.ActionPreference]::continue } $SkipCertificateCheckEnabled = ($script:SkipCertificateCheck -eq $true -or $SkipCertificateCheck.IsPresent) diff --git a/Evergreen/Private/Invoke-EvergreenWebRequest.ps1 b/Evergreen/Private/Invoke-EvergreenWebRequest.ps1 index 01864c10..71db8b98 100644 --- a/Evergreen/Private/Invoke-EvergreenWebRequest.ps1 +++ b/Evergreen/Private/Invoke-EvergreenWebRequest.ps1 @@ -47,7 +47,7 @@ function Invoke-EvergreenWebRequest { # Disable the Invoke-WebRequest progress bar for faster downloads if ($PSBoundParameters.ContainsKey("Verbose")) { - $ProgressPreference = [System.Management.Automation.ActionPreference]::Continue + $ProgressPreference = [System.Management.Automation.ActionPreference]::continue } else { $ProgressPreference = [System.Management.Automation.ActionPreference]::SilentlyContinue diff --git a/Evergreen/Private/Remove-ProxyEnv.ps1 b/Evergreen/Private/Remove-ProxyEnv.ps1 index e863c710..221d2002 100644 --- a/Evergreen/Private/Remove-ProxyEnv.ps1 +++ b/Evergreen/Private/Remove-ProxyEnv.ps1 @@ -5,10 +5,16 @@ function Remove-ProxyEnv { .DESCRIPTION This function removes the Evergreen proxy server and credentials information from the script-scoped environment variables. + Supports WhatIf and Confirm when removing each variable. #> + [CmdletBinding(SupportsShouldProcess = $true)] + param () + foreach ($VariableName in @("EvergreenProxy", "EvergreenProxyCreds")) { if ($null -ne (Get-Variable -Name $VariableName -Scope "Script" -ErrorAction "SilentlyContinue")) { - Remove-Variable -Name $VariableName -Scope "Script" -Force -ErrorAction "Stop" + if ($PSCmdlet.ShouldProcess("Script-scoped variable '$VariableName'", "Remove proxy configuration")) { + Remove-Variable -Name $VariableName -Scope "Script" -Force -Confirm:$false -ErrorAction "Stop" + } } } } diff --git a/Evergreen/Private/Resolve-DnsNameWrapper.ps1 b/Evergreen/Private/Resolve-DnsNameWrapper.ps1 index 2417b3ef..39e5bb74 100644 --- a/Evergreen/Private/Resolve-DnsNameWrapper.ps1 +++ b/Evergreen/Private/Resolve-DnsNameWrapper.ps1 @@ -4,6 +4,7 @@ function Resolve-DnsNameWrapper { Wrap DNS resolvers and return textual record data. #> [CmdletBinding()] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCommands", "", Justification = "Not reachable on PS5.1: ConvertFrom-Json -AsHashtable")] param ( [Parameter(Mandatory = $true, Position = 0)] [ValidateNotNullOrEmpty()] diff --git a/Evergreen/Public/Save-EvergreenApp.ps1 b/Evergreen/Public/Save-EvergreenApp.ps1 index c35ce6a2..55ed7b3f 100644 --- a/Evergreen/Public/Save-EvergreenApp.ps1 +++ b/Evergreen/Public/Save-EvergreenApp.ps1 @@ -270,8 +270,8 @@ function Save-EvergreenApp { $statusCode = $null $retryAfterHeader = $null if ($null -ne $response) { - try { $statusCode = [System.Int32]$response.StatusCode } catch { } - try { $retryAfterHeader = [System.String]$response.Headers["Retry-After"] } catch { } + try { $statusCode = [System.Int32]$response.StatusCode } catch { Write-Warning -Message "Failed to parse status code from response." } + try { $retryAfterHeader = [System.String]$response.Headers["Retry-After"] } catch { Write-Warning -Message "Failed to parse Retry-After header from response." } } $retryableStatusCodes = @(408, 429, 500, 502, 503, 504) diff --git a/Evergreen/Public/Update-Evergreen.ps1 b/Evergreen/Public/Update-Evergreen.ps1 index ea9b48ce..6663b6f4 100644 --- a/Evergreen/Public/Update-Evergreen.ps1 +++ b/Evergreen/Public/Update-Evergreen.ps1 @@ -1,8 +1,8 @@ function Update-Evergreen { <# - .EXTERNALHELP Evergreen-help.xml + .EXTERNALHELP Evergreen-help.xml #> - [CmdletBinding(SupportsShouldProcess = $false)] + [CmdletBinding(SupportsShouldProcess = $true)] param( [Parameter()] [System.Management.Automation.SwitchParameter] $Force, @@ -20,8 +20,21 @@ function Update-Evergreen { [System.String] $Release ) + # Validate Force parameter requirement when Release is specified + if ($PSBoundParameters['Release'] -and -not $PSBoundParameters['Force']) { + throw "-Force parameter required when specifying a release version." + } + + $AppsPath = Get-EvergreenAppsPath + if (-not $PSCmdlet.ShouldProcess($AppsPath, "Download, validate, and synchronize Evergreen apps cache")) { + return + } + + # Approval covers the entire cache operation, including nested commands. + $ConfirmPreference = [System.Management.Automation.ConfirmImpact]::None + # Account for changing the EVERGREEN_APPS_PATH variable at runtime - $Script:AppsPath = Get-EvergreenAppsPath + $Script:AppsPath = $AppsPath $script:VersionFile = Join-Path -Path $script:AppsPath -ChildPath ".evergreen_version" Write-Message -Message "Evergreen apps cache path: $($script:AppsPath)." @@ -38,11 +51,6 @@ function Update-Evergreen { $LocalVersion = $null } - # Validate Force parameter requirement when Release is specified - if ($PSBoundParameters['Release'] -and -not $PSBoundParameters['Force']) { - throw "-Force parameter required when specifying a release version." - } - try { # Get the latest version from the remote repository if ($PSBoundParameters['Release']) { @@ -190,7 +198,7 @@ function Update-Evergreen { if (Test-Path -Path $ExtractPath) { Remove-Item -Path $ExtractPath -Recurse -Force -ErrorAction "SilentlyContinue" } $global:ProgressPreference = [System.Management.Automation.ActionPreference]::SilentlyContinue Expand-Archive -Path $ZipFile -DestinationPath $ExtractPath -Force - $global:ProgressPreference = [System.Management.Automation.ActionPreference]::Continue + $global:ProgressPreference = [System.Management.Automation.ActionPreference]::continue Remove-Item -Path $ZipFile -Force -ErrorAction "SilentlyContinue" Write-Message -Message "Validating extracted files against SHA256 hashes." @@ -200,7 +208,7 @@ function Update-Evergreen { if (Test-Path -Path $FilePath) { $LocalHash = (Get-FileHash -Path $FilePath -Algorithm "SHA256").Hash.ToLower() if ($LocalHash -ne $File.sha256.ToLower()) { - Write-Warning -Message "SHA256 mismatch for file '$($File.file_path)'." -MessageType "Fail" + Write-Message -Message "SHA256 mismatch for file '$($File.file_path)'." -MessageType "Fail" $DoReplace = $false } else { @@ -208,7 +216,7 @@ function Update-Evergreen { } } else { - Write-Warning -Message "Expected file '$($File.file_path)' not found in extracted release." -MessageType "Fail" + Write-Message -Message "Expected file '$($File.file_path)' not found in extracted release." -MessageType "Fail" $DoReplace = $false } } diff --git a/README.md b/README.md index dcccbd65..a4500118 100644 --- a/README.md +++ b/README.md @@ -55,7 +55,7 @@ Documentation for Evergreen, including usage examples, is located here: [https:/ ## Testing -The [Validate module workflow](.github/workflows/validate-module.yml) runs deterministic Pester tests on Windows PowerShell 5.1, PowerShell 7.0.13 (the minimum supported 7.0 line) on Windows, and the runner-provided PowerShell 7 on Windows, Linux, and macOS. Each runtime uploads a separate test report. Failed tests, discovery/setup failures, an empty run, an unexpected skip, inconclusive tests, or a required suite with no passing tests fail validation. Code coverage remains in the live Windows PowerShell job, avoiding debugger instrumentation in the compatibility matrix. +The [Validate module workflow](.github/workflows/validate-module.yml) runs deterministic Pester tests on Windows PowerShell 5.1, PowerShell 7.4.0 (the minimum supported 7.4 line) on Windows, and the runner-provided PowerShell 7 on Windows, Linux, and macOS. Each runtime uploads a separate test report. Failed tests, discovery/setup failures, an empty run, an unexpected skip, inconclusive tests, or a required suite with no passing tests fail validation. Code coverage remains in the live Windows PowerShell job, avoiding debugger instrumentation in the compatibility matrix. The [release workflow](.github/workflows/update-module.yml) calls the same [runtime matrix](.github/workflows/test-runtimes.yml) against the release commit before publishing to the PowerShell Gallery. Every runtime must pass; a compatibility failure or the 20-minute job timeout blocks publication. @@ -71,7 +71,7 @@ The runner installs Pester 5.7.1 if needed and writes reports to `tests/Results` ### Analysis and coverage gates -The [analyzer workflow](.github/workflows/psscriptanalyzer.yml) runs default rules, the custom lowercase-keyword rule, and explicit PowerShell 5.1/7.0 syntax and command-compatibility rules. Errors and Warnings fail validation; `PSAvoidUsingWriteHost` remains excluded. SARIF is uploaded even when findings fail the job. The bundled command profiles cover Windows PowerShell 5.1 and Windows/Linux PowerShell 7.0; macOS compatibility is exercised by the runtime matrix. Existing findings are blockers, not grandfathered exceptions. +The [analyzer workflow](.github/workflows/psscriptanalyzer.yml) runs default rules, the custom lowercase-keyword rule, explicit PowerShell 5.1/7.4 syntax checks, and command-compatibility checks against the bundled profiles for Windows PowerShell 5.1 and Windows/Linux PowerShell 7.0. Errors and Warnings fail validation; `PSAvoidUsingWriteHost` remains excluded. SARIF is uploaded even when findings fail the job. The runtime matrix separately tests the PowerShell 7.4 minimum on Windows and runner-provided PowerShell 7 on Windows, Linux, and macOS. Existing findings are blockers, not grandfathered exceptions. The runtime matrix parses module and CI `.ps1`, `.psm1`, and `.psd1` files under each engine. The [release-gates workflow](.github/workflows/validate-release.yml) also validates workflow YAML with actionlint and parses embedded PowerShell. @@ -112,7 +112,7 @@ The module uses a version notation that follows: YearMonth.Build. It is expected ### PowerShell Support -Evergreen supports Windows PowerShell 5.1 and PowerShell 7.0+. Evergreen should work on PowerShell Core 6.x; however, we are not actively testing on that version of PowerShell, so support cannot be guaranteed. +Evergreen supports Windows PowerShell 5.1 and PowerShell 7.4+. Evergreen should work on PowerShell Core 6.x and PowerShell 7.0 to 7.3; however, we are not actively testing on those versions of PowerShell, so support cannot be guaranteed. ### Install from the PowerShell Gallery diff --git a/help/en-US/Update-Evergreen.md b/help/en-US/Update-Evergreen.md index 5b171c46..427c809a 100644 --- a/help/en-US/Update-Evergreen.md +++ b/help/en-US/Update-Evergreen.md @@ -14,13 +14,15 @@ Downloads and synchronizes the Evergreen Apps functions and Manifests from the e ## SYNTAX ``` -Update-Evergreen [-Force] [-Release ] [] +Update-Evergreen [-Force] [-Release ] [-WhatIf] [-Confirm] [] ``` ## DESCRIPTION Enables separation of the core Evergreen module from app-specific code and manifests. Downloads the latest versions of /Apps and /Manifests from a specified GitHub repository to a user-writable location (no admin required). By default, the local cache is downloaded to %LocalAppData%\Evergreen on Windows, and ~/.evergreen on macOS and Linux. +Use `-WhatIf` to show the intended cache operation without contacting GitHub, downloading files, or changing the cache. Use `-Confirm` to approve the entire operation before it starts, including hash-file downloads and cache synchronization. `-Force` does not bypass confirmation or `-WhatIf`. + ## EXAMPLES ### EXAMPLE 1 @@ -80,6 +82,38 @@ Accept pipeline input: False Accept wildcard characters: False ``` +### -WhatIf + +Shows the intended cache operation without downloading files or changing the cache. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm + +Prompts for confirmation before starting the entire cache operation. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). diff --git a/tests/Install-Pester.ps1 b/tests/Install-Pester.ps1 index 2bd86cf0..9105fd4a 100644 --- a/tests/Install-Pester.ps1 +++ b/tests/Install-Pester.ps1 @@ -1,5 +1,5 @@ <# - Install the Pester version used by CI, including on PowerShell 7.0. + Install the Pester version used by CI, including on PowerShell 7.4. #> $PesterVersion = (Import-PowerShellDataFile -Path (Join-Path $PSScriptRoot "..\ci\ValidationTools.psd1")).Pester diff --git a/tests/Invoke-Tests.ps1 b/tests/Invoke-Tests.ps1 index 6f08c63f..a88695f3 100644 --- a/tests/Invoke-Tests.ps1 +++ b/tests/Invoke-Tests.ps1 @@ -47,7 +47,6 @@ try { "Public\Export-EvergreenManifest.Tests.ps1" "Public\Get-EvergreenApp.Tests.ps1" "Public\Test-EvergreenLibrary.Tests.ps1" - "Public\Update-Evergreen.Tests.ps1" ) | ForEach-Object { Join-Path -Path $PSScriptRoot -ChildPath $_ } } $Config.CodeCoverage.Enabled = $IncludeIntegration.IsPresent -or $CollectCoverage.IsPresent diff --git a/tests/Private/Expand-CabArchive.Tests.ps1 b/tests/Private/Expand-CabArchive.Tests.ps1 index dea67173..f813e20d 100644 --- a/tests/Private/Expand-CabArchive.Tests.ps1 +++ b/tests/Private/Expand-CabArchive.Tests.ps1 @@ -85,8 +85,15 @@ Set-Content -Path (Join-Path -Path $Destination -ChildPath "expanded.txt") -Valu param ($Items, $Options) $this.Copied = $true foreach ($Item in $Items) { - $FileName = if ($Item.Path) { Split-Path -Path $Item.Path -Leaf } else { $Item.Name } - Set-Content -LiteralPath (Join-Path -Path $this.Path -ChildPath $FileName) -Value "shell" + $RelativePath = if ($Item.Path) { + $Item.Path.Substring($script:CabPath.Length + 1) + } + else { + $Item.Name + } + $FilePath = Join-Path -Path $this.Path -ChildPath $RelativePath + $null = [System.IO.Directory]::CreateDirectory([System.IO.Path]::GetDirectoryName($FilePath)) + Set-Content -LiteralPath $FilePath -Value "shell" } } $script:Shell = [PSCustomObject]@{ @@ -164,6 +171,33 @@ Set-Content -Path (Join-Path -Path $Destination -ChildPath "expanded.txt") -Valu } } + It "Should promote nested CAB entries and create their destination directories" { + InModuleScope -ModuleName "Evergreen" { + $script:SourceCab.Entries = @([PSCustomObject]@{ + Name = "nested" + Path = "$script:CabPath\nested\child\file.txt" + }) + + $Items = Expand-CabArchive -Path $script:CabPath -DestinationPath $script:CabDestination + + $Items | Should -Be (Join-Path -Path $script:CabDestination -ChildPath "nested\child\file.txt") + Test-Path -LiteralPath $Items -PathType Leaf | Should -BeTrue + (Get-Content -LiteralPath $Items -Raw).Trim() | Should -Be "shell" + } + } + + It "Should not replace an existing destination directory with a CAB file" { + InModuleScope -ModuleName "Evergreen" { + $script:SourceCab.Entries = @([PSCustomObject]@{ Name = "existing" }) + $ExistingDirectory = Join-Path -Path $script:CabDestination -ChildPath "existing" + $null = New-Item -Path $ExistingDirectory -ItemType Directory + + { Expand-CabArchive -Path $script:CabPath -DestinationPath $script:CabDestination } | + Should -Throw "*Cannot replace destination directory*" + Test-Path -LiteralPath $ExistingDirectory -PathType Container | Should -BeTrue + } + } + It "Should reject unsafe CAB entry paths without invoking the fallback" { InModuleScope -ModuleName "Evergreen" { $script:SourceCab.Entries = @([PSCustomObject]@{ Name = "..\escaped.txt" }) @@ -258,6 +292,40 @@ Set-Content -Path (Join-Path -Path $Destination -ChildPath "expanded.txt") -Valu } } + It "Should retain staging and report errors when rollback cannot restore a backup" { + InModuleScope -ModuleName "Evergreen" { + $script:SourceCab.Entries = @( + [PSCustomObject]@{ Name = "first.txt" } + [PSCustomObject]@{ Name = "second.txt" } + ) + $FirstDestination = Join-Path -Path $script:CabDestination -ChildPath "first.txt" + $SecondDestination = Join-Path -Path $script:CabDestination -ChildPath "second.txt" + Set-Content -LiteralPath $FirstDestination -Value "original" + Mock Move-Item { + & (Get-Command -Name "Microsoft.PowerShell.Management\Move-Item" -CommandType Cmdlet) ` + -LiteralPath $LiteralPath -Destination $Destination -Force -ErrorAction Stop + } + Mock Move-Item { throw "Simulated promotion failure" } -ParameterFilter { + $Destination -eq $SecondDestination + } + Mock Move-Item { throw "Simulated rollback failure" } -ParameterFilter { + $LiteralPath -like "*\Backup\first.txt" -and $Destination -eq $FirstDestination + } + + $ErrorMessage = try { + Expand-CabArchive -Path $script:CabPath -DestinationPath $script:CabDestination + } + catch { + $_.Exception.Message + } + + $ErrorMessage | Should -Match "Rollback was incomplete: Simulated rollback failure" + $ErrorMessage | Should -Match "Backups/staging retained at" + $StageRoot = [regex]::Match($ErrorMessage, "retained at '(.*?)'\.").Groups[1].Value + Test-Path -LiteralPath $StageRoot -PathType Container | Should -BeTrue + } + } + It "Should throw when neither extraction approach returns items" { InModuleScope -ModuleName "Evergreen" { Set-Content -Path $script:ExpandStub -Value @' diff --git a/tests/Private/Invoke-RestMethodWrapper.Tests.ps1 b/tests/Private/Invoke-RestMethodWrapper.Tests.ps1 index 2fd16d8a..b8d230fe 100644 --- a/tests/Private/Invoke-RestMethodWrapper.Tests.ps1 +++ b/tests/Private/Invoke-RestMethodWrapper.Tests.ps1 @@ -14,6 +14,11 @@ BeforeAll { InModuleScope -ModuleName "Evergreen" { Describe -Name "Invoke-EvergreenRestMethod" { + AfterEach { + # Module-scoped proxy settings outlive Pester's per-test mocks. + Remove-ProxyEnv + } + Context "Ensure Invoke-EvergreenRestMethod works as expected" { It "Allows insecure redirects on Windows PowerShell without an unsupported parameter" { Mock Test-PSCore { $false } @@ -62,13 +67,126 @@ InModuleScope -ModuleName "Evergreen" { It "Does not disable certificate validation when explicitly passed false" { Mock Invoke-RestMethod { "mock response" } - Invoke-EvergreenRestMethod -Uri "https://example.com" -SkipCertificateCheck:$false | + Invoke-EvergreenRestMethod -Uri "https://example.com" -SkipCertificateCheck:$false ` + -ErrorAction SilentlyContinue | Should -Be "mock response" Should -Invoke Invoke-RestMethod -ParameterFilter { $PSBoundParameters.ContainsKey("SkipCertificateCheck") } -Times 0 -Exactly } + It "Passes request options, proxy settings, and credentials to PowerShell Core" { + $script:EvergreenProxy = "http://proxy.example.com" + $script:EvergreenProxyCreds = [System.Management.Automation.PSCredential]::new( + "proxy-user", + (ConvertTo-SecureString "proxy-password" -AsPlainText -Force) + ) + $headers = @{ Authorization = "Bearer token" } + $body = @{ name = "test" } + function script:Invoke-RestMethod { + param ( + [System.String] $Uri, + [System.String] $ContentType, + [System.Collections.Hashtable] $Headers, + [System.Object] $Body, + [System.String] $Method, + [System.Int32] $MaximumRedirection, + [System.Boolean] $UseBasicParsing, + [System.String] $UserAgent, + [System.Management.Automation.SwitchParameter] $SkipCertificateCheck, + [System.String] $SslProtocol, + [System.Management.Automation.SwitchParameter] $AllowInsecureRedirect, + [System.String] $Proxy, + [System.Management.Automation.PSCredential] $ProxyCredential + ) + $script:CapturedRestParams = $PSBoundParameters + "mock response" + } + Mock Test-PSCore { $true } + Mock Test-ProxyEnv { $true } + try { + Invoke-EvergreenRestMethod -Uri "https://example.com" -Headers $headers -Body $body ` + -SkipCertificateCheck -SslProtocol Tls12 -AllowInsecureRedirect -ErrorAction SilentlyContinue | + Should -Be "mock response" + + $script:CapturedRestParams.Headers.Authorization | Should -Be "Bearer token" + $script:CapturedRestParams.Body.name | Should -Be "test" + $script:CapturedRestParams.SkipCertificateCheck | Should -BeTrue + $script:CapturedRestParams.SslProtocol | Should -Be "Tls12" + $script:CapturedRestParams.AllowInsecureRedirect | Should -BeTrue + $script:CapturedRestParams.Proxy | Should -Be "http://proxy.example.com" + $script:CapturedRestParams.ProxyCredential.UserName | Should -Be "proxy-user" + } + finally { + Remove-Item -Path "Function:Invoke-RestMethod" -Force + Remove-Variable -Name CapturedRestParams -Scope Script -ErrorAction SilentlyContinue + } + } + + It "Does not leak proxy settings or credentials into subsequent requests" { + Test-ProxyEnv | Should -BeFalse + Test-ProxyEnv -Creds | Should -BeFalse + Mock Invoke-RestMethod { "mock response" } + + Invoke-EvergreenRestMethod -Uri "https://example.com" | Should -Be "mock response" + + Should -Invoke Invoke-RestMethod -Times 1 -Exactly -ParameterFilter { + -not $PSBoundParameters.ContainsKey("Proxy") -and + -not $PSBoundParameters.ContainsKey("ProxyCredential") + } + } + + It "Applies and restores the requested legacy TLS protocol" { + $originalProtocol = [System.Net.ServicePointManager]::SecurityProtocol + Mock Test-PSCore { $false } + Mock Invoke-RestMethod { "mock response" } + try { + Invoke-EvergreenRestMethod -Uri "https://example.com" -SslProtocol Tls | + Should -Be "mock response" + [System.Net.ServicePointManager]::SecurityProtocol | Should -Be $originalProtocol + } + finally { + [System.Net.ServicePointManager]::SecurityProtocol = $originalProtocol + } + } + + if ($PSVersionTable.PSVersion.Major -lt 6) { + It "Temporarily trusts certificates in Windows PowerShell and restores the prior policy" { + $originalPolicy = [System.Net.ServicePointManager]::CertificatePolicy + Mock Test-PSCore { $false } + Mock Invoke-RestMethod { "mock response" } + try { + Invoke-EvergreenRestMethod -Uri "https://example.com" -SkipCertificateCheck | + Should -Be "mock response" + [System.Net.ServicePointManager]::CertificatePolicy | Should -Be $originalPolicy + } + finally { + [System.Net.ServicePointManager]::CertificatePolicy = $originalPolicy + } + } + } + + It "Rejects TLS 1.3 on Windows PowerShell and restores the prior protocol" { + $originalProtocol = [System.Net.ServicePointManager]::SecurityProtocol + Mock Test-PSCore { $false } + + try { + { Invoke-EvergreenRestMethod -Uri "https://example.com" -SslProtocol Tls13 } | + Should -Throw "*TLS 1.3 is not supported*" + [System.Net.ServicePointManager]::SecurityProtocol | Should -Be $originalProtocol + } + finally { + [System.Net.ServicePointManager]::SecurityProtocol = $originalProtocol + } + } + + It "Warns and rethrows request failures" { + Mock Invoke-RestMethod { throw "request failed" } + + { Invoke-EvergreenRestMethod -Uri "https://example.com" -WarningAction SilentlyContinue } | + Should -Throw "*request failed*" + } + It "Returns data from a proper URL" -Tag "Integration" { $params = @{ ContentType = "application/vnd.github.v3+json" diff --git a/tests/Private/Invoke-WebRequestWrapper.Tests.ps1 b/tests/Private/Invoke-WebRequestWrapper.Tests.ps1 index 98c5399e..87e5290e 100644 --- a/tests/Private/Invoke-WebRequestWrapper.Tests.ps1 +++ b/tests/Private/Invoke-WebRequestWrapper.Tests.ps1 @@ -15,6 +15,11 @@ BeforeAll { InModuleScope -ModuleName "Evergreen" { Describe -Name "Invoke-EvergreenWebRequest" { + AfterEach { + # Module-scoped proxy settings outlive Pester's per-test mocks. + Remove-ProxyEnv + } + Context "Ensure Invoke-EvergreenWebRequest works as expected" { It "Does not disable certificate validation when explicitly passed false" { Mock Invoke-WebRequest { @@ -51,6 +56,183 @@ InModuleScope -ModuleName "Evergreen" { Test-Path -LiteralPath $script:RawResponseFile | Should -BeFalse } + It "Returns requested response objects" -TestCases @( + @{ ReturnObject = "Headers"; Expected = "text/plain" } + @{ ReturnObject = "RawContent"; Expected = "HTTP/1.1 200 OK`r`n`r`nmock response" } + @{ ReturnObject = "All"; Expected = "response" } + ) { + param ($ReturnObject, $Expected) + + $response = [PSCustomObject]@{ + StatusCode = 200 + Headers = @{ "Content-Type" = "text/plain" } + Content = "mock response" + RawContent = "HTTP/1.1 200 OK`r`n`r`nmock response" + Marker = "response" + } + Mock Invoke-WebRequest { $response } + + $result = Invoke-EvergreenWebRequest -Uri "https://example.com" -ReturnObject $ReturnObject + + if ($ReturnObject -eq "Headers") { + $result["Content-Type"] | Should -Be $Expected + } + elseif ($ReturnObject -eq "RawContent") { + $result | Should -Be $Expected + } + else { + $result.Marker | Should -Be $Expected + } + } + + It "Passes optional request and proxy settings to PowerShell Core" { + $script:EvergreenProxy = "http://proxy.example.com" + $script:EvergreenProxyCreds = [System.Management.Automation.PSCredential]::new( + "proxy-user", + (ConvertTo-SecureString "proxy-password" -AsPlainText -Force) + ) + function script:Invoke-WebRequest { + param ( + [System.String] $Uri, + [System.String] $Method, + [System.String] $UserAgent, + [System.Boolean] $UseBasicParsing, + [System.String] $ContentType, + [System.Collections.Hashtable] $Headers, + [System.Management.Automation.SwitchParameter] $SkipCertificateCheck, + [System.String] $SslProtocol, + [System.String] $OutFile, + [System.Management.Automation.SwitchParameter] $PassThru, + [System.String] $Proxy, + [System.Management.Automation.PSCredential] $ProxyCredential + ) + $script:CapturedWebParams = $PSBoundParameters + [PSCustomObject]@{ + StatusCode = 200 + Headers = @{ "Content-Type" = "text/plain" } + Content = "mock response" + RawContent = "HTTP/1.1 200 OK`r`n`r`nmock response" + } + } + Mock Test-PSCore { $true } + Mock Test-ProxyEnv { $true } + try { + Invoke-EvergreenWebRequest -Uri "https://example.com" -ContentType "text/plain" ` + -Headers @{ Accept = "text/plain" } -SkipCertificateCheck -SslProtocol Tls12 -Verbose | + Should -Be "mock response" + + $script:CapturedWebParams.ContentType | Should -Be "text/plain" + $script:CapturedWebParams.Headers.Accept | Should -Be "text/plain" + $script:CapturedWebParams.SkipCertificateCheck | Should -BeTrue + $script:CapturedWebParams.SslProtocol | Should -Be "Tls12" + $script:CapturedWebParams.Proxy | Should -Be "http://proxy.example.com" + $script:CapturedWebParams.ProxyCredential.UserName | Should -Be "proxy-user" + } + finally { + Remove-Item -Path "Function:Invoke-WebRequest" -Force + Remove-Variable -Name CapturedWebParams -Scope Script -ErrorAction SilentlyContinue + } + } + + It "Does not leak proxy settings or credentials into subsequent requests" { + Test-ProxyEnv | Should -BeFalse + Test-ProxyEnv -Creds | Should -BeFalse + Mock Invoke-WebRequest { + [PSCustomObject]@{ + StatusCode = 200 + Headers = @{ "Content-Type" = "text/plain" } + Content = "mock response" + RawContent = "HTTP/1.1 200 OK`r`n`r`nmock response" + } + } + + Invoke-EvergreenWebRequest -Uri "https://example.com" | Should -Be "mock response" + + Should -Invoke Invoke-WebRequest -Times 1 -Exactly -ParameterFilter { + -not $PSBoundParameters.ContainsKey("Proxy") -and + -not $PSBoundParameters.ContainsKey("ProxyCredential") + } + } + + It "Honors WhatIf without issuing a request" { + Mock Invoke-WebRequest {} + + Invoke-EvergreenWebRequest -Uri "https://example.com" -WhatIf | Should -BeNullOrEmpty + + Should -Invoke Invoke-WebRequest -Times 0 -Exactly + } + + It "Returns no content for an empty response" { + Mock Invoke-WebRequest { $null } + + Invoke-EvergreenWebRequest -Uri "https://example.com" | Should -BeNullOrEmpty + } + + It "Applies and restores an explicit legacy TLS protocol" { + $originalProtocol = [System.Net.ServicePointManager]::SecurityProtocol + Mock Test-PSCore { $false } + Mock Invoke-WebRequest { + [PSCustomObject]@{ + StatusCode = 200 + Headers = @{ "Content-Type" = "text/plain" } + Content = "mock response" + RawContent = "HTTP/1.1 200 OK`r`n`r`nmock response" + } + } + try { + Invoke-EvergreenWebRequest -Uri "https://example.com" -SslProtocol Tls | + Should -Be "mock response" + [System.Net.ServicePointManager]::SecurityProtocol | Should -Be $originalProtocol + } + finally { + [System.Net.ServicePointManager]::SecurityProtocol = $originalProtocol + } + } + + It "Warns and rethrows request failures" { + Mock Invoke-WebRequest { throw "request failed" } + + { Invoke-EvergreenWebRequest -Uri "https://example.com" -WarningAction SilentlyContinue } | + Should -Throw "*request failed*" + } + + It "Rejects TLS 1.3 on Windows PowerShell and restores the prior protocol" { + $originalProtocol = [System.Net.ServicePointManager]::SecurityProtocol + Mock Test-PSCore { $false } + + try { + { Invoke-EvergreenWebRequest -Uri "https://example.com" -SslProtocol Tls13 } | + Should -Throw "*TLS 1.3 is not supported*" + [System.Net.ServicePointManager]::SecurityProtocol | Should -Be $originalProtocol + } + finally { + [System.Net.ServicePointManager]::SecurityProtocol = $originalProtocol + } + } + + if ($PSVersionTable.PSVersion.Major -lt 6) { + It "Temporarily trusts certificates in Windows PowerShell and restores the prior policy" { + $originalPolicy = [System.Net.ServicePointManager]::CertificatePolicy + Mock Test-PSCore { $false } + Mock Invoke-WebRequest { + [PSCustomObject]@{ + StatusCode = 200 + Headers = @{ "Content-Type" = "text/plain" } + Content = "mock response" + RawContent = "HTTP/1.1 200 OK`r`n`r`nmock response" + } + } + try { + Invoke-EvergreenWebRequest -Uri "https://example.com" -SkipCertificateCheck | + Should -Be "mock response" + [System.Net.ServicePointManager]::CertificatePolicy | Should -Be $originalPolicy + } + finally { + [System.Net.ServicePointManager]::CertificatePolicy = $originalPolicy + } + } + } + It "Returns data from a URL" -Tag "Integration" { $params = @{ ContentType = "text/html" diff --git a/tests/Private/Remove-ProxyEnv.Tests.ps1 b/tests/Private/Remove-ProxyEnv.Tests.ps1 index 4421ee9a..a88f7523 100644 --- a/tests/Private/Remove-ProxyEnv.Tests.ps1 +++ b/tests/Private/Remove-ProxyEnv.Tests.ps1 @@ -36,6 +36,32 @@ Describe -Name "Remove-ProxyEnv" { { Remove-ProxyEnv } | Should -Not -Throw } } + + It "Preserves proxy and credential state when WhatIf is specified" { + InModuleScope -ModuleName "Evergreen" { + $Credential = [System.Management.Automation.PSCredential]::new( + "proxy-user", + [System.Security.SecureString]::new() + ) + Set-ProxyEnv -Proxy "proxyserver" -ProxyCredential $Credential + + Remove-ProxyEnv -WhatIf + + $script:EvergreenProxy | Should -Be "proxyserver" + $script:EvergreenProxyCreds | Should -Be $Credential + } + } + + It "Removes proxy state when confirmation is explicitly disabled" { + InModuleScope -ModuleName "Evergreen" { + Set-ProxyEnv -Proxy "proxyserver" + + Remove-ProxyEnv -Confirm:$false + + Test-ProxyEnv | Should -BeFalse + Test-ProxyEnv -Creds | Should -BeFalse + } + } } AfterAll { diff --git a/tests/Public/Save-EvergreenApp.Tests.ps1 b/tests/Public/Save-EvergreenApp.Tests.ps1 index 14de17a2..44bda190 100644 --- a/tests/Public/Save-EvergreenApp.Tests.ps1 +++ b/tests/Public/Save-EvergreenApp.Tests.ps1 @@ -100,6 +100,47 @@ InModuleScope -ModuleName "Evergreen" { } } + It "Uses the URI filename and forwards proxy credentials" { + $testPath = Join-Path -Path ([System.IO.Path]::GetTempPath()) -ChildPath "Evergreen-Save-$([guid]::NewGuid().ToString('N'))" + $uriFilenameApp = [PSCustomObject]@{ URI = "https://example.com/from-uri.msi" } + $proxyCredential = [System.Management.Automation.PSCredential]::new( + "proxy-user", + (ConvertTo-SecureString "proxy-password" -AsPlainText -Force) + ) + try { + Mock Invoke-WebRequest { + param ($Uri, $OutFile) + [System.IO.File]::WriteAllText($OutFile, "installer") + } + + $result = Save-EvergreenApp -InputObject $uriFilenameApp -CustomPath $testPath ` + -Proxy "http://proxy.example.com" -ProxyCredential $proxyCredential + + $result.Name | Should -Be "from-uri.msi" + Should -Invoke Invoke-WebRequest -Times 1 -Exactly -ParameterFilter { + $Proxy -eq "http://proxy.example.com" -and + $ProxyCredential.UserName -eq "proxy-user" + } + } + finally { + Remove-Item -LiteralPath $testPath -Recurse -Force -ErrorAction "SilentlyContinue" + } + } + + It "Throws when a successful request does not create its temporary download" { + $testPath = Join-Path -Path ([System.IO.Path]::GetTempPath()) -ChildPath "Evergreen-Save-$([guid]::NewGuid().ToString('N'))" + try { + Mock Invoke-WebRequest {} + + { Save-EvergreenApp -InputObject $testApp -CustomPath $testPath -RetryCount 0 } | + Should -Throw "*completed without creating a file*" + @(Get-ChildItem -LiteralPath $testPath -Force) | Should -BeNullOrEmpty + } + finally { + Remove-Item -LiteralPath $testPath -Recurse -Force -ErrorAction "SilentlyContinue" + } + } + It "Does not create directories or download under WhatIf" { $testPath = Join-Path -Path ([System.IO.Path]::GetTempPath()) -ChildPath "Evergreen-Save-$([guid]::NewGuid().ToString('N'))" try { @@ -226,25 +267,28 @@ InModuleScope -ModuleName "Evergreen" { It "Passes timeout settings supported by the current PowerShell version" { $testPath = Join-Path -Path ([System.IO.Path]::GetTempPath()) -ChildPath "Evergreen-Save-$([guid]::NewGuid().ToString('N'))" + $script:requestedTimeouts = $null try { Mock Invoke-WebRequest { - param ($Uri, $OutFile) + param ($Uri, $OutFile, $TimeoutSec, $ConnectionTimeoutSeconds, $OperationTimeoutSeconds) + $script:requestedTimeouts = $PSBoundParameters [System.IO.File]::WriteAllText($OutFile, "installer") } if ($PSVersionTable.PSVersion -ge [System.Version]"7.4") { Save-EvergreenApp -InputObject $testApp -CustomPath $testPath -ConnectionTimeoutSeconds 17 -OperationTimeoutSeconds 121 | Out-Null - Should -Invoke Invoke-WebRequest -Times 1 -Exactly -ParameterFilter { - $ConnectionTimeoutSeconds -eq 17 -and $OperationTimeoutSeconds -eq 121 - } + $script:requestedTimeouts.ConnectionTimeoutSeconds | Should -Be 17 + $script:requestedTimeouts.OperationTimeoutSeconds | Should -Be 121 } else { Save-EvergreenApp -InputObject $testApp -CustomPath $testPath -ConnectionTimeoutSeconds 17 | Out-Null - Should -Invoke Invoke-WebRequest -Times 1 -Exactly -ParameterFilter { $TimeoutSec -eq 17 } + $script:requestedTimeouts.TimeoutSec | Should -Be 17 } + Should -Invoke Invoke-WebRequest -Times 1 -Exactly } finally { Remove-Item -LiteralPath $testPath -Recurse -Force -ErrorAction "SilentlyContinue" + Remove-Variable -Name requestedTimeouts -Scope Script -ErrorAction "SilentlyContinue" } } diff --git a/tests/Public/Update-Evergreen.Tests.ps1 b/tests/Public/Update-Evergreen.Tests.ps1 index a24e25d4..12a8030c 100644 --- a/tests/Public/Update-Evergreen.Tests.ps1 +++ b/tests/Public/Update-Evergreen.Tests.ps1 @@ -26,6 +26,108 @@ BeforeAll { } } +Describe -Tag "Update" -Name "Update-Evergreen ShouldProcess" { + It "Leaves cache state unchanged with WhatIf (existing: , force: , release: )" -TestCases @( + @{ CacheExists = $false; Force = $false; Release = $null } + @{ CacheExists = $true; Force = $false; Release = $null } + @{ CacheExists = $false; Force = $true; Release = $null } + @{ CacheExists = $true; Force = $true; Release = $null } + @{ CacheExists = $false; Force = $true; Release = "v26.11.04.1" } + @{ CacheExists = $true; Force = $true; Release = "v26.11.04.1" } + ) { + param ($CacheExists, $Force, $Release) + + $CachePath = Join-Path -Path $TestDrive -ChildPath ([System.Guid]::NewGuid().ToString()) + if ($CacheExists) { + New-Item -Path (Join-Path -Path $CachePath -ChildPath "Apps") -ItemType "Directory" -Force | Out-Null + Set-Content -Path (Join-Path -Path $CachePath -ChildPath ".evergreen_version") -Value "26.11.03.1" + } + + InModuleScope -ModuleName "Evergreen" -Parameters @{ + CachePath = $CachePath; CacheExists = $CacheExists; Force = $Force; Release = $Release + } { + Mock Get-EvergreenAppsPath { $CachePath } + Mock Get-GitHubRepoRelease { throw "Unexpected network request." } + Mock Save-EvergreenApp { throw "Unexpected download." } + $OriginalAppsPath = $script:AppsPath + $OriginalVersionFile = $script:VersionFile + $Options = @{ WhatIf = $true; Force = $Force } + if ($Release) { $Options.Release = $Release } + + Update-Evergreen @Options + + $script:AppsPath | Should -Be $OriginalAppsPath + $script:VersionFile | Should -Be $OriginalVersionFile + Test-Path -Path $CachePath | Should -Be $CacheExists + if ($CacheExists) { + @(Get-ChildItem -Path $CachePath -Recurse -Force).Count | Should -Be 2 + (Get-Content -Path (Join-Path -Path $CachePath -ChildPath ".evergreen_version") -Raw).Trim() | + Should -Be "26.11.03.1" + } + Should -Invoke Get-GitHubRepoRelease -Times 0 -Exactly + Should -Invoke Save-EvergreenApp -Times 0 -Exactly + } + } + + It "Validates the Release and Force requirement even with WhatIf" { + { Update-Evergreen -Release "v26.11.04.1" -WhatIf } | Should -Throw "*Force parameter required*" + } + + It "Completes an update using a local release archive (explicit confirmation disabled: )" -TestCases @( + @{ SuppressConfirmation = $false } + @{ SuppressConfirmation = $true } + ) { + param ($SuppressConfirmation) + + $RootPath = Join-Path -Path $TestDrive -ChildPath ([System.Guid]::NewGuid().ToString()) + $SourcePath = Join-Path -Path $RootPath -ChildPath "Source" + New-Item -Path (Join-Path -Path $SourcePath -ChildPath "Apps") -ItemType "Directory" -Force | Out-Null + New-Item -Path (Join-Path -Path $SourcePath -ChildPath "Manifests") -ItemType "Directory" -Force | Out-Null + Set-Content -Path (Join-Path -Path $SourcePath -ChildPath "Apps\Get-TestApp.ps1") -Value "function Get-TestApp {}" + Set-Content -Path (Join-Path -Path $SourcePath -ChildPath "Manifests\TestApp.json") -Value "{}" + $ZipPath = Join-Path -Path $RootPath -ChildPath "Release.zip" + Compress-Archive -Path (Join-Path -Path $SourcePath -ChildPath "*") -DestinationPath $ZipPath + $CachePath = Join-Path -Path $RootPath -ChildPath "ApprovedCache" + + InModuleScope -ModuleName "Evergreen" -Parameters @{ + CachePath = $CachePath; ZipPath = $ZipPath; SuppressConfirmation = $SuppressConfirmation + } { + Mock Get-EvergreenAppsPath { $CachePath } + Mock Get-GitHubRepoRelease { + [PSCustomObject]@{ + Type = "zip" + Version = "26.11.04.1" + Uri = "https://example.invalid/release.zip" + Sha256 = (Get-FileHash -Path $ZipPath -Algorithm "SHA256").Hash + } + } + Mock Save-EvergreenApp { $ZipPath } + $OriginalAppsPath = $script:AppsPath + $OriginalVersionFile = $script:VersionFile + $OriginalProgressPreference = $global:ProgressPreference + try { + if ($SuppressConfirmation) { + Update-Evergreen -Force -Confirm:$false + } + else { + Update-Evergreen + } + + Test-Path -Path (Join-Path -Path $CachePath -ChildPath "Apps\Get-TestApp.ps1") | Should -BeTrue + Test-Path -Path (Join-Path -Path $CachePath -ChildPath "Manifests\TestApp.json") | Should -BeTrue + (Get-Content -Path (Join-Path -Path $CachePath -ChildPath ".evergreen_version") -Raw).Trim() | + Should -Be "26.11.04.1" + Should -Invoke Save-EvergreenApp -Times 1 -Exactly + } + finally { + $script:AppsPath = $OriginalAppsPath + $script:VersionFile = $OriginalVersionFile + $global:ProgressPreference = $OriginalProgressPreference + } + } + } +} + Describe -Tag "Update" -Name "Update-Evergreen Parameter Validation" { Context "Validate Release parameter format" { It "Should throw with invalid Release format - missing 'v' prefix" { @@ -55,135 +157,293 @@ Describe -Tag "Update" -Name "Update-Evergreen Parameter Validation" { } It "Should not throw parameter validation error when Release is specified with Force" { - # Note: This may throw other errors related to network/file operations, - # but should not throw the Force parameter validation error - try { - Update-Evergreen -Release "v24.01.01.12345" -Force -ErrorAction Stop - } - catch { - $_.Exception.Message | Should -Not -Match "Force parameter required" + InModuleScope -ModuleName "Evergreen" -Parameters @{ CachePath = $TestDrive } { + param ($CachePath) + + Mock Get-EvergreenAppsPath { $CachePath } + Mock Get-GitHubRepoRelease { throw "offline test" } + + { Update-Evergreen -Release "v24.01.01.12345" -Force } | + Should -Throw "*Could not retrieve remote version*" } } } } -Describe -Tag "Update" -Name "Update-Evergreen Function Behavior" { +Describe -Tag "Update" -Name "Update-Evergreen deterministic cache behavior" { BeforeAll { - # Set custom test path for this test suite - $env:EVERGREEN_APPS_PATH = $script:TestPath - New-Item -Path $script:TestPath -ItemType "Directory" -Force -ErrorAction "SilentlyContinue" | Out-Null - } + $script:CreateFixture = { + param ($Root) - AfterAll { - # Clean up test directory - if (Test-Path -Path $script:TestPath) { - Remove-Item -Path $script:TestPath -Recurse -Force -ErrorAction "SilentlyContinue" - } - # Restore original EVERGREEN_APPS_PATH - if ($script:OriginalAppsPath) { - $env:EVERGREEN_APPS_PATH = $script:OriginalAppsPath - } - else { - Remove-Item Env:\EVERGREEN_APPS_PATH -ErrorAction "SilentlyContinue" + $zipPath = Join-Path -Path $Root -ChildPath "release.zip" + $csvPath = Join-Path -Path $Root -ChildPath "hashes.csv" + $appSource = Join-Path -Path $Root -ChildPath "Get-TestApp.ps1" + [System.IO.File]::WriteAllText($appSource, "function Get-TestApp {}") + $appHash = (Get-FileHash -LiteralPath $appSource -Algorithm SHA256).Hash + [System.IO.File]::WriteAllText($zipPath, "release archive") + [System.IO.File]::WriteAllText($csvPath, "file_path,sha256`nApps/Get-TestApp.ps1,$appHash`n") + + [PSCustomObject]@{ + CachePath = Join-Path -Path $Root -ChildPath "cache" + ZipPath = $zipPath + CsvPath = $csvPath + Zip = [PSCustomObject]@{ + Type = "zip" + Version = "26.11.04.1" + Uri = "https://example.invalid/release.zip" + Sha256 = (Get-FileHash -LiteralPath $zipPath -Algorithm SHA256).Hash + } + Csv = [PSCustomObject]@{ + Type = "csv" + Uri = "https://example.invalid/hashes.csv" + Sha256 = (Get-FileHash -LiteralPath $csvPath -Algorithm SHA256).Hash + } + } } } - Context "Validate Update-Evergreen basic execution" { - It "Should not throw when called without parameters" { - { Update-Evergreen -ErrorAction Stop } | Should -Not -Throw - } + BeforeEach { + $script:FixtureRoot = Join-Path -Path $TestDrive -ChildPath ([System.Guid]::NewGuid().ToString("N")) + $null = New-Item -Path $script:FixtureRoot -ItemType Directory -Force + $script:Fixture = & $script:CreateFixture $script:FixtureRoot + } - It "Should not throw when called with -Force parameter" { - { Update-Evergreen -Force -ErrorAction Stop } | Should -Not -Throw - } + It "Fails clearly when the GitHub request fails or returns no release" { + $fixture = $script:Fixture + InModuleScope -ModuleName "Evergreen" -Parameters @{ Fixture = $fixture } { + param ($Fixture) - It "Should create Apps directory after successful update" { - $AppsDir = Join-Path -Path $script:TestPath -ChildPath "Apps" - Test-Path -Path $AppsDir -PathType "Container" | Should -Be $true - } + Mock Get-EvergreenAppsPath { $Fixture.CachePath } + Mock Get-GitHubRepoRelease { throw "offline test" } - It "Should create Manifests directory after successful update" { - $ManifestsDir = Join-Path -Path $script:TestPath -ChildPath "Manifests" - Test-Path -Path $ManifestsDir -PathType "Container" | Should -Be $true + { Update-Evergreen } | Should -Throw "*Could not retrieve remote version*" } + } + + It "Stops immediately when the GitHub API reports a rate limit" { + $fixture = $script:Fixture + InModuleScope -ModuleName "Evergreen" -Parameters @{ Fixture = $fixture } { + param ($Fixture) - It "Should create version file after successful update" { - $VersionFile = Join-Path -Path $script:TestPath -ChildPath ".evergreen_version" - Test-Path -Path $VersionFile -PathType "Leaf" | Should -Be $true + Mock Get-EvergreenAppsPath { $Fixture.CachePath } + Mock Get-GitHubRepoRelease { + [PSCustomObject]@{ Type = "zip"; Version = "RateLimited" } + } + + { Update-Evergreen } | Should -Throw "*GitHub API rate limit exceeded*" + Test-Path -LiteralPath $Fixture.CachePath | Should -BeFalse } + } - It "Version file should contain valid version format" { - $VersionFile = Join-Path -Path $script:TestPath -ChildPath ".evergreen_version" - if (Test-Path -Path $VersionFile) { - $Version = Get-Content -Path $VersionFile -Raw -ErrorAction "SilentlyContinue" - $Version = $Version.Trim() - $Version | Should -Match "^v?\d{2}\.\d{2}\.\d{2}\.\d+" + It "Uses the specified release URL and synchronizes a verified archive" { + $fixture = $script:Fixture + InModuleScope -ModuleName "Evergreen" -Parameters @{ Fixture = $fixture } { + param ($Fixture) + + Mock Get-EvergreenAppsPath { $Fixture.CachePath } + Mock Get-GitHubRepoRelease { @($Fixture.Zip, $Fixture.Csv) } + Mock Save-EvergreenApp { + if ($InputObject.Type -eq "csv") { + Get-Item -LiteralPath $Fixture.CsvPath + } + else { + $Fixture.ZipPath + } + } + Mock Expand-Archive { + $appsPath = Join-Path -Path $DestinationPath -ChildPath "Apps" + $manifestsPath = Join-Path -Path $DestinationPath -ChildPath "Manifests" + $null = New-Item -Path $appsPath -ItemType Directory -Force + $null = New-Item -Path $manifestsPath -ItemType Directory -Force + [System.IO.File]::WriteAllText((Join-Path $appsPath "Get-TestApp.ps1"), "function Get-TestApp {}") + [System.IO.File]::WriteAllText((Join-Path $manifestsPath "TestApp.json"), "{}") + } + $previousProgressPreference = $global:ProgressPreference + try { + Update-Evergreen -Force -Release "v26.11.04.1" + + Test-Path -LiteralPath (Join-Path $Fixture.CachePath "Apps\Get-TestApp.ps1") | Should -BeTrue + Test-Path -LiteralPath (Join-Path $Fixture.CachePath "Manifests\TestApp.json") | Should -BeTrue + (Get-Content -LiteralPath (Join-Path $Fixture.CachePath ".evergreen_version") -Raw).Trim() | + Should -Be "26.11.04.1" + Should -Invoke Get-GitHubRepoRelease -Times 1 -Exactly -ParameterFilter { + $Uri -like "*/releases/tags/v26.11.04.1" + } + Should -Invoke Save-EvergreenApp -Times 1 -Exactly + } + finally { + $global:ProgressPreference = $previousProgressPreference } } } - Context "Validate Update-Evergreen with custom path" { - BeforeAll { - $script:CustomTestPath = Join-Path -Path $script:TestPath -ChildPath "CustomCache" - $env:EVERGREEN_APPS_PATH = $script:CustomTestPath + It "Skips downloading when cache versions match and every local hash matches" { + $fixture = $script:Fixture + New-Item -Path (Join-Path $fixture.CachePath "Apps") -ItemType Directory -Force | Out-Null + New-Item -Path (Join-Path $fixture.CachePath "Manifests") -ItemType Directory -Force | Out-Null + Set-Content -LiteralPath (Join-Path $fixture.CachePath "Apps\Get-TestApp.ps1") -Value "function Get-TestApp {}" + Set-Content -LiteralPath (Join-Path $fixture.CachePath ".evergreen_version") -Value $fixture.Zip.Version + + InModuleScope -ModuleName "Evergreen" -Parameters @{ Fixture = $fixture } { + param ($Fixture) + + Mock Get-EvergreenAppsPath { $Fixture.CachePath } + Mock Get-GitHubRepoRelease { @($Fixture.Zip, $Fixture.Csv) } + Mock Save-EvergreenApp { Get-Item -LiteralPath $Fixture.CsvPath } + Mock Expand-Archive { throw "Unexpected archive extraction." } + + Update-Evergreen + + Should -Invoke Save-EvergreenApp -Times 1 -Exactly + Should -Invoke Expand-Archive -Times 0 -Exactly } + } + + It "Reports local hash mismatches and leaves the current cache in place" { + $fixture = $script:Fixture + New-Item -Path (Join-Path $fixture.CachePath "Apps") -ItemType Directory -Force | Out-Null + New-Item -Path (Join-Path $fixture.CachePath "Manifests") -ItemType Directory -Force | Out-Null + Set-Content -LiteralPath (Join-Path $fixture.CachePath "Apps\Get-TestApp.ps1") -Value "modified" + Set-Content -LiteralPath (Join-Path $fixture.CachePath ".evergreen_version") -Value $fixture.Zip.Version + + InModuleScope -ModuleName "Evergreen" -Parameters @{ Fixture = $fixture } { + param ($Fixture) + + Mock Get-EvergreenAppsPath { $Fixture.CachePath } + Mock Get-GitHubRepoRelease { @($Fixture.Zip, $Fixture.Csv) } + Mock Save-EvergreenApp { Get-Item -LiteralPath $Fixture.CsvPath } + Mock Expand-Archive { throw "Unexpected archive extraction." } + + $messages = @(Update-Evergreen 6>&1) - It "Should use custom EVERGREEN_APPS_PATH when set" { - Update-Evergreen -ErrorAction Stop - Test-Path -Path $script:CustomTestPath -PathType "Container" | Should -Be $true + Should -Invoke Expand-Archive -Times 0 -Exactly + ($messages | ForEach-Object MessageData | Out-String) | Should -Match "SHA256 mismatch found" } + } + + It "Rejects a downloaded release zip with an invalid SHA256" { + $fixture = $script:Fixture + $fixture.Zip.Sha256 = [System.String]::new("0", 64) + InModuleScope -ModuleName "Evergreen" -Parameters @{ Fixture = $fixture } { + param ($Fixture) + + Mock Get-EvergreenAppsPath { $Fixture.CachePath } + Mock Get-GitHubRepoRelease { @($Fixture.Zip, $Fixture.Csv) } + Mock Save-EvergreenApp { $Fixture.ZipPath } + Mock Expand-Archive {} - It "Should create Apps directory in custom path" { - $AppsDir = Join-Path -Path $script:CustomTestPath -ChildPath "Apps" - Test-Path -Path $AppsDir -PathType "Container" | Should -Be $true + { Update-Evergreen -Force } | Should -Throw "*SHA256 mismatch for downloaded release zip file*" + Should -Invoke Expand-Archive -Times 0 -Exactly } + } + + It "Does not replace the cache when extracted content fails hash validation" { + $fixture = $script:Fixture + New-Item -Path (Join-Path $fixture.CachePath "Apps") -ItemType Directory -Force | Out-Null + New-Item -Path (Join-Path $fixture.CachePath "Manifests") -ItemType Directory -Force | Out-Null + Set-Content -LiteralPath (Join-Path $fixture.CachePath "Apps\Get-TestApp.ps1") -Value "old version" + Set-Content -LiteralPath (Join-Path $fixture.CachePath ".evergreen_version") -Value "26.11.03.1" - AfterAll { - if (Test-Path -Path $script:CustomTestPath) { - Remove-Item -Path $script:CustomTestPath -Recurse -Force -ErrorAction "SilentlyContinue" + InModuleScope -ModuleName "Evergreen" -Parameters @{ Fixture = $fixture } { + param ($Fixture) + + Mock Get-EvergreenAppsPath { $Fixture.CachePath } + Mock Get-GitHubRepoRelease { @($Fixture.Zip, $Fixture.Csv) } + Mock Save-EvergreenApp { + if ($InputObject.Type -eq "csv") { + Get-Item -LiteralPath $Fixture.CsvPath + } + else { + $Fixture.ZipPath + } + } + Mock Expand-Archive { + $appsPath = Join-Path -Path $DestinationPath -ChildPath "Apps" + $manifestsPath = Join-Path -Path $DestinationPath -ChildPath "Manifests" + $null = New-Item -Path $appsPath -ItemType Directory -Force + $null = New-Item -Path $manifestsPath -ItemType Directory -Force + [System.IO.File]::WriteAllText((Join-Path $appsPath "Get-TestApp.ps1"), "bad content") } + + Update-Evergreen -Force -WarningAction SilentlyContinue + + (Get-Content -LiteralPath (Join-Path $Fixture.CachePath "Apps\Get-TestApp.ps1") -Raw).Trim() | + Should -Be "old version" + (Get-Content -LiteralPath (Join-Path $Fixture.CachePath ".evergreen_version") -Raw).Trim() | + Should -Be "26.11.03.1" } } -} -Describe -Tag "Update" -Name "Update-Evergreen Idempotency" { - BeforeAll { - # Set custom test path for this test suite - $script:IdempotencyTestPath = Join-Path -Path $script:TestPath -ChildPath "IdempotencyTest" - $env:EVERGREEN_APPS_PATH = $script:IdempotencyTestPath - New-Item -Path $script:IdempotencyTestPath -ItemType "Directory" -Force -ErrorAction "SilentlyContinue" | Out-Null - } + It "Leaves the cache unchanged when a listed extracted file is missing" { + $fixture = $script:Fixture + $missingHash = [System.String]::new("0", 64) + [System.IO.File]::WriteAllText($fixture.CsvPath, "file_path,sha256`nApps/Missing.ps1,$missingHash`n") + $fixture.Csv.Sha256 = (Get-FileHash -LiteralPath $fixture.CsvPath -Algorithm SHA256).Hash + New-Item -Path (Join-Path $fixture.CachePath "Apps") -ItemType Directory -Force | Out-Null + New-Item -Path (Join-Path $fixture.CachePath "Manifests") -ItemType Directory -Force | Out-Null + Set-Content -LiteralPath (Join-Path $fixture.CachePath "Apps\Get-TestApp.ps1") -Value "old version" + Set-Content -LiteralPath (Join-Path $fixture.CachePath ".evergreen_version") -Value "26.11.03.1" - AfterAll { - # Clean up test directory - if (Test-Path -Path $script:IdempotencyTestPath) { - Remove-Item -Path $script:IdempotencyTestPath -Recurse -Force -ErrorAction "SilentlyContinue" - } - # Restore original EVERGREEN_APPS_PATH - if ($script:OriginalAppsPath) { - $env:EVERGREEN_APPS_PATH = $script:OriginalAppsPath - } - else { - Remove-Item Env:\EVERGREEN_APPS_PATH -ErrorAction "SilentlyContinue" + InModuleScope -ModuleName "Evergreen" -Parameters @{ Fixture = $fixture } { + param ($Fixture) + + Mock Get-EvergreenAppsPath { $Fixture.CachePath } + Mock Get-GitHubRepoRelease { @($Fixture.Zip, $Fixture.Csv) } + Mock Save-EvergreenApp { + if ($InputObject.Type -eq "csv") { + Get-Item -LiteralPath $Fixture.CsvPath + } + else { + $Fixture.ZipPath + } + } + Mock Expand-Archive { + $appsPath = Join-Path -Path $DestinationPath -ChildPath "Apps" + $manifestsPath = Join-Path -Path $DestinationPath -ChildPath "Manifests" + $null = New-Item -Path $appsPath -ItemType Directory -Force + $null = New-Item -Path $manifestsPath -ItemType Directory -Force + [System.IO.File]::WriteAllText((Join-Path $appsPath "Get-TestApp.ps1"), "function Get-TestApp {}") + } + + Update-Evergreen -Force -WarningAction SilentlyContinue + + (Get-Content -LiteralPath (Join-Path $Fixture.CachePath "Apps\Get-TestApp.ps1") -Raw).Trim() | + Should -Be "old version" + (Get-Content -LiteralPath (Join-Path $Fixture.CachePath ".evergreen_version") -Raw).Trim() | + Should -Be "26.11.03.1" } } - Context "Validate multiple runs of Update-Evergreen" { - It "First run should not throw" { - { Update-Evergreen -ErrorAction Stop } | Should -Not -Throw - } + It "Continues without hash verification when the downloaded hashes file is invalid" { + $fixture = $script:Fixture + $fixture.Csv.Sha256 = [System.String]::new("0", 64) + New-Item -Path (Join-Path $fixture.CachePath "Apps") -ItemType Directory -Force | Out-Null + New-Item -Path (Join-Path $fixture.CachePath "Manifests") -ItemType Directory -Force | Out-Null + Set-Content -LiteralPath (Join-Path $fixture.CachePath ".evergreen_version") -Value $fixture.Zip.Version - It "Second run without Force should not throw" { - { Update-Evergreen -ErrorAction Stop } | Should -Not -Throw - } + InModuleScope -ModuleName "Evergreen" -Parameters @{ Fixture = $fixture } { + param ($Fixture) + + Mock Get-EvergreenAppsPath { $Fixture.CachePath } + Mock Get-GitHubRepoRelease { @($Fixture.Zip, $Fixture.Csv) } + Mock Save-EvergreenApp { Get-Item -LiteralPath $Fixture.CsvPath } + Mock Expand-Archive { throw "Unexpected archive extraction." } - It "Run with Force should not throw" { - { Update-Evergreen -Force -ErrorAction Stop } | Should -Not -Throw + { Update-Evergreen -WarningAction SilentlyContinue } | Should -Not -Throw + Should -Invoke Expand-Archive -Times 0 -Exactly } + } + + It "Fails when a requested download does not produce an archive" { + $fixture = $script:Fixture + InModuleScope -ModuleName "Evergreen" -Parameters @{ Fixture = $fixture } { + param ($Fixture) + + Mock Get-EvergreenAppsPath { $Fixture.CachePath } + Mock Get-GitHubRepoRelease { $Fixture.Zip } + Mock Save-EvergreenApp { Join-Path $Fixture.CachePath "missing.zip" } - It "Version file should still exist after multiple runs" { - $VersionFile = Join-Path -Path $script:IdempotencyTestPath -ChildPath ".evergreen_version" - Test-Path -Path $VersionFile -PathType "Leaf" | Should -Be $true + { Update-Evergreen -Force } | Should -Throw "*Failed to download Evergreen apps release*" } } }