diff --git a/.gitattributes b/.gitattributes index 87340bb..d2012d8 100644 --- a/.gitattributes +++ b/.gitattributes @@ -104,3 +104,8 @@ package/docs/images/report-global-recover-light.png -text package/docs/images/report-phase-light.png -text package/docs/images/report-phase-warning-light.png -text CHANGELOG.md -text whitespace=blank-at-eol,space-before-tab,blank-at-eof,cr-at-eol + +# Repository CI and release tooling scripts keep LF line endings on checkout. +.github/scripts/*.ps1 text eol=lf +tools/New-Sbom.ps1 text eol=lf +tools/Compare-ReleaseSource.ps1 text eol=lf diff --git a/.github/ci-pins.json b/.github/ci-pins.json new file mode 100644 index 0000000..2bcbd94 --- /dev/null +++ b/.github/ci-pins.json @@ -0,0 +1,42 @@ +{ + "schema": 1, + "powerShell": [ + { + "role": "primary", + "line": "7.6", + "version": "7.6.10", + "dotNetRuntime": "10.0.15", + "sha256": "7D871531806EB1646264E4BBABD9F0C30C23355591BC756BB9909448C29AE166", + "source": "https://github.com/PowerShell/PowerShell/releases/tag/v7.6.10", + "hashSource": "https://github.com/PowerShell/PowerShell/releases/download/v7.6.10/hashes.sha256", + "supportEnds": "2028-11-14", + "supportSource": "https://learn.microsoft.com/powershell/scripting/install/powershell-support-lifecycle" + } + + ], + "signingCertificate": { + "thumbprint": "0F28E442889F17B5F4D251E8F96E7CC6E2C9C6D6", + "notAfter": "2027-10-13", + "warnDays": 90 + }, + "modules": [ + { + "name": "Pester", + "version": "6.1.0", + "sha256": "0207A75EA09F81B27C1DED44898B2BB3C845BAFA02045BD64A39E26A53CA41B4", + "sha512Base64": "GK3Db7arrcdZ4Z/i/VMptAzZccIpftsTOR1fgVlMETmSFZkbsD759KhlxGhlyolj0K9/7axmlFo5iozx3ikM0A==", + "size": 420319, + "source": "https://www.powershellgallery.com/packages/Pester/6.1.0", + "hashSource": "https://www.powershellgallery.com/api/v2/Packages(Id='Pester',Version='6.1.0')" + }, + { + "name": "PSScriptAnalyzer", + "version": "1.25.0", + "sha256": "14E634C828EB98EFB9F40B2918BA90F139ED5ECCDF663A2A747736D996995D60", + "sha512Base64": "5/tXMmLmBLqymRSuYpIdJLl8L4i1GbQSd7QD72zhY/FLfRs23HNEmmjlrlqNlQKJGxDCZBMf0YE63ym/ExwWYw==", + "size": 14658674, + "source": "https://www.powershellgallery.com/packages/PSScriptAnalyzer/1.25.0", + "hashSource": "https://www.powershellgallery.com/api/v2/Packages(Id='PSScriptAnalyzer',Version='1.25.0')" + } + ] +} diff --git a/.github/ci.json b/.github/ci.json index 604b2c8..ba75f1c 100644 --- a/.github/ci.json +++ b/.github/ci.json @@ -8,7 +8,8 @@ "tests/PackageIntegrity.Tests.ps1", "tests/PraReport.Tests.ps1", "tests/PraLegacyFixtures.Tests.ps1", - "tests/PraDocumentation.Tests.ps1" + "tests/PraDocumentation.Tests.ps1", + "tests/PraRepository.Tests.ps1" ], "packageBuilder": "tools/New-PraPackage.ps1", "packageEntry": "Invoke-PraRemoteMailbox.ps1" diff --git a/.github/scripts/Initialize-CIModules.ps1 b/.github/scripts/Initialize-CIModules.ps1 index 8c72c5a..a0a4602 100644 --- a/.github/scripts/Initialize-CIModules.ps1 +++ b/.github/scripts/Initialize-CIModules.ps1 @@ -1,28 +1,83 @@ #Requires -Version 5.1 +<# +.SYNOPSIS + CI only. Installs the pinned analysis and test modules from the PowerShell Gallery packages, after checking their hashes. +.DESCRIPTION + .github\ci-pins.json holds, for each module, the version and the hash of its .nupkg together. The package of that exact version is downloaded, + its SHA-256 (and its SHA-512 as published by the Gallery) must equal the pins, and only then is it extracted under \\. + A package that does not match is deleted and stops the step. The folder is put on PSModulePath of the next steps through GITHUB_ENV. +.PARAMETER Destination + The folder that receives \ for each module. +.PARAMETER PinsPath + The pin file. Default: .github\ci-pins.json. +.PARAMETER PackageDirectory + A folder that already holds ..nupkg files; nothing is downloaded. The hashes are checked all the same. +#> [CmdletBinding()] param( - [Parameter(Mandatory)][string]$Destination + [Parameter(Mandatory)][string]$Destination, + [string]$PinsPath = (Join-Path $PSScriptRoot '..\ci-pins.json'), + [string]$PackageDirectory ) +Set-StrictMode -Version Latest $ErrorActionPreference = 'Stop' -[void][IO.Directory]::CreateDirectory($Destination) -Save-Module -Name Pester -RequiredVersion 6.1.0 -Repository PSGallery -Path $Destination -Force -ErrorAction Stop -Save-Module -Name PSScriptAnalyzer -RequiredVersion 1.25.0 -Repository PSGallery -Path $Destination -Force -ErrorAction Stop +Add-Type -AssemblyName System.IO.Compression.FileSystem -foreach ($module in @( - @{ Name = 'Pester'; Version = '6.1.0' }, - @{ Name = 'PSScriptAnalyzer'; Version = '1.25.0' } -)) { - $manifest = Join-Path $Destination ('{0}\{1}\{0}.psd1' -f $module.Name, $module.Version) - if (-not (Test-Path -LiteralPath $manifest -PathType Leaf)) { - throw "The pinned module was not saved: $manifest" +function Assert-PackageHash { + param([Parameter(Mandatory)][string]$Path, [Parameter(Mandatory)]$Pin) + $sha256 = (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash + if (-not [string]::Equals($sha256, [string]$Pin.sha256, [StringComparison]::OrdinalIgnoreCase)) { + throw "The package of $($Pin.name) $($Pin.version) does not match its pinned SHA-256 ($sha256)." } - $data = Import-PowerShellDataFile -LiteralPath $manifest - if ([string]$data.ModuleVersion -cne $module.Version) { - throw "The saved module version does not match: $manifest" + $algorithm = [Security.Cryptography.SHA512]::Create() + try { $sha512 = [Convert]::ToBase64String($algorithm.ComputeHash([IO.File]::ReadAllBytes($Path))) } finally { $algorithm.Dispose() } + if (-not [string]::Equals($sha512, [string]$Pin.sha512Base64, [StringComparison]::Ordinal)) { + throw "The package of $($Pin.name) $($Pin.version) does not match its pinned SHA-512 ($sha512)." } } +$pins = Get-Content -LiteralPath $PinsPath -Raw -Encoding UTF8 | ConvertFrom-Json +$destinationFull = [IO.Path]::GetFullPath($Destination) +[void][IO.Directory]::CreateDirectory($destinationFull) +$download = Join-Path ([IO.Path]::GetTempPath()) ('ci-modules-' + [guid]::NewGuid().ToString('N')) +[void][IO.Directory]::CreateDirectory($download) +try { + foreach ($pin in @($pins.modules)) { + if ([string]$pin.name -notmatch '\A[A-Za-z][A-Za-z0-9.]*\z' -or [string]$pin.version -notmatch '\A\d+\.\d+\.\d+\z') { throw 'A module pin has an invalid name or version.' } + if ([string]$pin.sha256 -notmatch '\A[0-9A-Fa-f]{64}\z' -or [string]$pin.sha512Base64 -notmatch '\A[A-Za-z0-9+/]{86}==\z') { throw "The hash pins of $($pin.name) are not valid." } + $file = ('{0}.{1}.nupkg' -f $pin.name, $pin.version) + if ($PackageDirectory) { + $package = Join-Path $PackageDirectory $file + if (-not (Test-Path -LiteralPath $package -PathType Leaf)) { throw "The package is missing: $package" } + } + else { + $package = Join-Path $download $file + Invoke-WebRequest -Uri ('https://www.powershellgallery.com/api/v2/package/{0}/{1}' -f $pin.name, $pin.version) -OutFile $package -UseBasicParsing + } + try { Assert-PackageHash -Path $package -Pin $pin } + catch { + if (-not $PackageDirectory) { Remove-Item -LiteralPath $package -Force -ErrorAction SilentlyContinue } + throw + } + $target = Join-Path $destinationFull ('{0}\{1}' -f $pin.name, $pin.version) + if (Test-Path -LiteralPath $target) { Remove-Item -LiteralPath $target -Recurse -Force } + [IO.Compression.ZipFile]::ExtractToDirectory($package, $target) + foreach ($packaging in @('_rels', 'package', '[Content_Types].xml', ('{0}.nuspec' -f $pin.name))) { + $item = Join-Path $target $packaging + if (Test-Path -LiteralPath $item) { Remove-Item -LiteralPath $item -Recurse -Force } + } + $manifest = Join-Path $target ('{0}.psd1' -f $pin.name) + if (-not (Test-Path -LiteralPath $manifest -PathType Leaf)) { throw "The pinned module was not extracted: $manifest" } + $data = Import-PowerShellDataFile -LiteralPath $manifest + if ([string]$data.ModuleVersion -cne [string]$pin.version) { throw "The extracted module version does not match: $manifest" } + Write-Output ('{0} {1} installed from a package that matches its pinned hashes.' -f $pin.name, $pin.version) + } +} +finally { + Remove-Item -LiteralPath $download -Recurse -Force -ErrorAction SilentlyContinue +} + if (-not $env:GITHUB_ENV) { throw 'The GitHub Actions environment file is missing.' } -'CI_MODULE_PATH={0}' -f [IO.Path]::GetFullPath($Destination) | +'CI_MODULE_PATH={0}' -f $destinationFull | Out-File -LiteralPath $env:GITHUB_ENV -Encoding utf8 -Append diff --git a/.github/scripts/Install-PowerShell.ps1 b/.github/scripts/Install-PowerShell.ps1 index 382a21a..5b33df0 100644 --- a/.github/scripts/Install-PowerShell.ps1 +++ b/.github/scripts/Install-PowerShell.ps1 @@ -1,23 +1,46 @@ #Requires -Version 5.1 <# .SYNOPSIS - CI only. Makes sure that the pwsh used by the next steps is PowerShell 7.5 or later (the engine requires 7.5+). + CI only. Makes sure that the pwsh used by the next steps is exactly the pinned PowerShell release of the requested line. .DESCRIPTION - The GitHub-hosted Windows images ship PowerShell 7.4. If pwsh on PATH is older than 7.5, the pinned release below is - downloaded from the official PowerShell release page, its SHA-256 is checked against the value pinned here (the same value - appears in the hashes.sha256 asset of the release), it is extracted under RUNNER_TEMP and put first on PATH for the - following steps. A full extracted copy keeps pwsh.exe inside $PSHOME, which the engine needs to start its child processes. + The GitHub-hosted Windows images ship an older PowerShell 7. Unless pwsh on PATH already is the pinned version, the pinned release is + downloaded from the official PowerShell release page, its SHA-256 is checked against the value pinned in .github\ci-pins.json (the same + value appears in the hashes.sha256 asset of the release), it is extracted under RUNNER_TEMP and put first on PATH for the following steps. + A full extracted copy keeps pwsh.exe inside $PSHOME, which the engine needs to start its child processes. It does not connect to a lab or use publication credentials. +.PARAMETER Line + The PowerShell line to install, for example 7.6. The pinned version and hash of this line come from the pin file. +.PARAMETER PinsPath + The pin file. Default: .github\ci-pins.json. +.PARAMETER Version + Overrides the pinned version (with -Sha256). +.PARAMETER Sha256 + Overrides the pinned SHA-256 (with -Version). +.PARAMETER ArchivePath + Uses this local archive instead of downloading it; it is checked against the pinned SHA-256 all the same. #> [CmdletBinding()] param( - [string]$Version = '7.5.13', - [string]$Sha256 = '120B8F0B04F3B3F6E8C351DDBE568BF596CDCA15EEB2ECB7E724060051A36D65' + [string]$Line = '7.6', + [string]$PinsPath = (Join-Path $PSScriptRoot '..\ci-pins.json'), + [string]$Version, + [string]$Sha256, + [string]$ArchivePath ) Set-StrictMode -Version Latest $ErrorActionPreference = 'Stop' -$minimum = [version]'7.5.0' + +if ([string]::IsNullOrWhiteSpace($Version) -ne [string]::IsNullOrWhiteSpace($Sha256)) { throw 'Give both -Version and -Sha256, or neither.' } +if ([string]::IsNullOrWhiteSpace($Version)) { + $pins = Get-Content -LiteralPath $PinsPath -Raw -Encoding UTF8 | ConvertFrom-Json + $pin = @($pins.powerShell | Where-Object { [string]::Equals([string]$_.line, $Line, [StringComparison]::OrdinalIgnoreCase) }) + if ($pin.Count -ne 1) { throw "The pin file has no single PowerShell entry for the line $Line." } + $Version = [string]$pin[0].version + $Sha256 = [string]$pin[0].sha256 +} +if ($Version -notmatch '\A\d+\.\d+\.\d+\z') { throw "The PowerShell version is not a release version: $Version" } +if ($Sha256 -notmatch '\A[0-9A-Fa-f]{64}\z') { throw 'The pinned SHA-256 is not 64 hexadecimal characters.' } function Get-PwshVersion { $command = Get-Command pwsh -ErrorAction SilentlyContinue @@ -28,20 +51,25 @@ function Get-PwshVersion { } $current = Get-PwshVersion -if ($current -and $current -ge $minimum) { - Write-Output ('pwsh {0} already satisfies PowerShell 7.5+.' -f $current) +if ($current -and $current -eq [version]$Version) { + Write-Output ('pwsh {0} is the pinned version.' -f $current) return } $runnerTemp = if ($env:RUNNER_TEMP) { $env:RUNNER_TEMP } else { [IO.Path]::GetTempPath() } -$zip = Join-Path $runnerTemp ('PowerShell-{0}-win-x64.zip' -f $Version) $destination = Join-Path $runnerTemp ('pwsh-{0}' -f $Version) -$uri = 'https://github.com/PowerShell/PowerShell/releases/download/v{0}/PowerShell-{0}-win-x64.zip' -f $Version -Invoke-WebRequest -Uri $uri -OutFile $zip -UseBasicParsing +if ($ArchivePath) { + $zip = $ArchivePath +} +else { + $zip = Join-Path $runnerTemp ('PowerShell-{0}-win-x64.zip' -f $Version) + $uri = 'https://github.com/PowerShell/PowerShell/releases/download/v{0}/PowerShell-{0}-win-x64.zip' -f $Version + Invoke-WebRequest -Uri $uri -OutFile $zip -UseBasicParsing +} $actual = (Get-FileHash -LiteralPath $zip -Algorithm SHA256).Hash if (-not [string]::Equals($actual, $Sha256, [StringComparison]::OrdinalIgnoreCase)) { - Remove-Item -LiteralPath $zip -Force - throw "The downloaded PowerShell archive does not match the pinned SHA-256 ($actual)." + if (-not $ArchivePath) { Remove-Item -LiteralPath $zip -Force } + throw "The PowerShell archive does not match the pinned SHA-256 ($actual)." } if (Test-Path -LiteralPath $destination) { throw "The destination already exists and will not be overwritten: $destination" } Expand-Archive -LiteralPath $zip -DestinationPath $destination diff --git a/.github/scripts/Invoke-CI.ps1 b/.github/scripts/Invoke-CI.ps1 index fc5d169..98b04a0 100644 --- a/.github/scripts/Invoke-CI.ps1 +++ b/.github/scripts/Invoke-CI.ps1 @@ -1,4 +1,4 @@ -#Requires -Version 7.5 +#Requires -Version 7.6 [CmdletBinding()] param( [Parameter(Mandatory)][ValidateSet('Analyze', 'Test', 'Package')][string]$Stage, @@ -10,6 +10,13 @@ Set-StrictMode -Version Latest $ErrorActionPreference = 'Stop' $root = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..\..')) $configuration = Get-Content -LiteralPath (Join-Path $root '.github\ci.json') -Raw | ConvertFrom-Json +$pins = Get-Content -LiteralPath (Join-Path $root '.github\ci-pins.json') -Raw | ConvertFrom-Json +function Get-PinnedModuleVersion { + param([Parameter(Mandatory)][string]$Name) + $pin = @($pins.modules | Where-Object { [string]::Equals([string]$_.name, $Name, [StringComparison]::OrdinalIgnoreCase) }) + if ($pin.Count -ne 1) { throw "The pin file has no single entry for the module $Name." } + [string]$pin[0].version +} $OutputDirectory = [IO.Path]::GetFullPath($OutputDirectory) [void][IO.Directory]::CreateDirectory($OutputDirectory) @@ -30,7 +37,7 @@ function Resolve-RepositoryFile { switch ($Stage) { 'Analyze' { - Import-Module PSScriptAnalyzer -RequiredVersion 1.25.0 -Force -ErrorAction Stop + Import-Module PSScriptAnalyzer -RequiredVersion (Get-PinnedModuleVersion 'PSScriptAnalyzer') -Force -ErrorAction Stop $tracked = @(git -C $root ls-files -- '*.ps1' '*.psm1' '*.psd1') if ($LASTEXITCODE -ne 0) { throw 'Cannot enumerate the tracked PowerShell sources.' } $runtime = [string]$configuration.runtimeRoot @@ -65,7 +72,7 @@ switch ($Stage) { ConvertTo-Json -InputObject $parseFailures -Depth 5 | Out-File -LiteralPath (Join-Path $OutputDirectory 'syntax-errors.json') -Encoding utf8 $summary = [ordered]@{ - Files = $files.Count; RuntimeFiles = $runtimeFiles.Count; TestAndToolFiles = $supportFiles.Count; Analyzer = '1.25.0'; SyntaxErrors = $parseFailures.Count + Files = $files.Count; RuntimeFiles = $runtimeFiles.Count; TestAndToolFiles = $supportFiles.Count; Analyzer = (Get-PinnedModuleVersion 'PSScriptAnalyzer'); SyntaxErrors = $parseFailures.Count Errors = @($findings | Where-Object Severity -eq 'Error').Count Warnings = @($findings | Where-Object Severity -eq 'Warning').Count Informative = @($findings | Where-Object Severity -eq 'Information').Count @@ -77,7 +84,7 @@ switch ($Stage) { if ($parseFailures.Count) { throw 'PowerShell sources (runtime, tests or tools) contain syntax errors.' } } 'Test' { - Import-Module Pester -RequiredVersion 6.1.0 -Force -ErrorAction Stop + Import-Module Pester -RequiredVersion (Get-PinnedModuleVersion 'Pester') -Force -ErrorAction Stop if ($configuration.testMode -eq 'gate') { $gate = Resolve-RepositoryFile $configuration.testEntry $executable = Join-Path $PSHOME 'pwsh.exe' @@ -142,5 +149,23 @@ switch ($Stage) { ConvertTo-Json -InputObject $inventory -Depth 5 | Out-File -LiteralPath (Join-Path $OutputDirectory 'package-inventory.json') -Encoding utf8 Write-Output ('Existing package builder completed: {0} files.' -f $files.Count) + # The bill of materials of the built package, written and checked the way a release does it (the ZIP itself is not kept). + Add-Type -AssemblyName System.IO.Compression.FileSystem + $sbomTool = Resolve-RepositoryFile 'tools/New-Sbom.ps1' + $zipFolder = Join-Path ([IO.Path]::GetTempPath()) ('ci-zip-' + [guid]::NewGuid().ToString('N')) + [void][IO.Directory]::CreateDirectory($zipFolder) + try { + $zipPath = Join-Path $zipFolder 'PraRemoteMailbox-ci.zip' + [IO.Compression.ZipFile]::CreateFromDirectory($destination, $zipPath, [IO.Compression.CompressionLevel]::Optimal, $true) + $written = @(& $sbomTool -PackageRoot $destination -ZipPath $zipPath -RepositoryRoot $root -OutputDirectory (Join-Path $OutputDirectory 'sbom') -Unsigned) + if ($written.Count -ne 2 -or @($written | Where-Object { -not (Test-Path -LiteralPath $_ -PathType Leaf) }).Count -gt 0) { throw 'The bill of materials and the dependency declaration were not both written.' } + $document = Get-Content -LiteralPath $written[0] -Raw -Encoding UTF8 | ConvertFrom-Json + $zipSha256 = (Get-FileHash -LiteralPath $zipPath -Algorithm SHA256).Hash.ToLowerInvariant() + $rootPackage = @($document.packages | Where-Object { $_.SPDXID -ceq 'SPDXRef-Package-PraRemoteMailbox' }) + if ($rootPackage.Count -ne 1 -or $rootPackage[0].checksums[0].checksumValue -cne $zipSha256) { throw 'The bill of materials does not describe the ZIP that was built.' } + if (@($document.files).Count -ne $files.Count) { throw ('The bill of materials lists {0} files and the package holds {1}.' -f @($document.files).Count, $files.Count) } + Write-Output ('Bill of materials written and checked: {0} files, {1} packages.' -f @($document.files).Count, @($document.packages).Count) + } + finally { Remove-Item -LiteralPath $zipFolder -Recurse -Force -ErrorAction SilentlyContinue } } } diff --git a/.github/scripts/Invoke-DependencyWatch.ps1 b/.github/scripts/Invoke-DependencyWatch.ps1 new file mode 100644 index 0000000..d4fd186 --- /dev/null +++ b/.github/scripts/Invoke-DependencyWatch.ps1 @@ -0,0 +1,472 @@ +#Requires -Version 7.4 +<# +.SYNOPSIS + Monthly watch of what the repository pins and declares. It only reads public data and only reports. +.DESCRIPTION + Reads the pins of .github/ci-pins.json (CI PowerShell, Pester, PSScriptAnalyzer, the signing certificate), the `uses:` pins of the workflows and the + minimum versions the package declares, asks the public sources (GitHub releases, tags and advisories, the GitHub Advisory Database for the nuget and + actions ecosystems, the PowerShell Gallery) and writes a job summary table and a JSON result. Nothing is written to GitHub: no issue, no pull request, + no comment. + + Failure (exit code 1): a pinned version is named by a published advisory, the support of the pinned PowerShell line has ended, the signing + certificate has expired, a pinned action commit is no longer the commit of its tag, a pin is not a full commit with an exact tag comment, or every + lookup of one kind of source failed (the watch looked at nothing of that kind). + Warning: a pinned version is behind the latest release of its line, support or the certificate ends within 90 days, an advisory range cannot be read, + one lookup failed. + Information: a newer major exists, the declared minimums have newer releases, the known end of support of the floor leg. +.PARAMETER RepositoryRoot + The repository folder. Default: two levels above this script. +.PARAMETER OutputDirectory + Receives dependency-watch.json and dependency-watch.md. +.PARAMETER Today + The date used for the support dates. Default: today (UTC). +.PARAMETER LoadOnly + Defines the functions and returns (used by the tests). +#> +[CmdletBinding()] +param( + [string]$RepositoryRoot = (Join-Path $PSScriptRoot '../..'), + [string]$OutputDirectory = (Join-Path $RepositoryRoot 'artifacts/dependency-watch'), + [datetime]$Today = [datetime]::UtcNow.Date, + [switch]$LoadOnly +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' + +$script:WatchStats = @{} +$script:WatchCache = @{} + +function New-WatchFinding { + param( + [Parameter(Mandatory)][ValidateSet('Fail', 'Warn', 'Info')][string]$Level, + [Parameter(Mandatory)][string]$Component, + [Parameter(Mandatory)][string]$Message, + [string]$Url + ) + [pscustomobject][ordered]@{ Level = $Level; Component = $Component; Message = $Message; Url = $Url } +} + +function ConvertTo-WatchVersion { + <# A release version (x.y.z, an optional leading v) or $null. A pre-release or a text that is not a version gives $null. #> + param([AllowNull()][AllowEmptyString()][string]$Text) + if ([string]::IsNullOrWhiteSpace($Text)) { return $null } + $match = [regex]::Match($Text.Trim(), '\Av?(?\d+(?:\.\d+){1,3})\z') + if (-not $match.Success) { return $null } + $value = $match.Groups['n'].Value + if ($value.Split('.').Count -eq 2) { $value += '.0' } + [version]$value +} + +function ConvertTo-WatchLimit { + <# The limit of an advisory range: a version, with a flag when it is a pre-release (7.0.0-rc.1). $null when it is not a version. #> + param([AllowNull()][AllowEmptyString()][string]$Text) + if ([string]::IsNullOrWhiteSpace($Text)) { return $null } + $match = [regex]::Match($Text.Trim(), '\Av?(?\d+(?:\.\d+){1,3})(?
-[0-9A-Za-z.+-]+)?\z')
+    if (-not $match.Success) { return $null }
+    $value = $match.Groups['n'].Value
+    if ($value.Split('.').Count -eq 2) { $value += '.0' }
+    [pscustomobject]@{ Version = [version]$value; Pre = $match.Groups['pre'].Success }
+}
+
+function Get-WatchRangeState {
+    <# 'In', 'Out' or 'Unreadable' for a version against a GitHub advisory range such as ">= 7.5.0, < 7.5.12" (also "<= x", "> x", "= x"). A stable version is above its own pre-release. #>
+    param([Parameter(Mandatory)][version]$Version, [AllowNull()][AllowEmptyString()][string]$Range)
+    if ([string]::IsNullOrWhiteSpace($Range)) { return 'Unreadable' }
+    foreach ($part in $Range.Split(',')) {
+        $match = [regex]::Match($part.Trim(), '\A(?<=|>=|<|>|=)\s*(?\S+)\z')
+        if (-not $match.Success) { return 'Unreadable' }
+        $limit = ConvertTo-WatchLimit $match.Groups['v'].Value
+        if ($null -eq $limit) { return 'Unreadable' }
+        $holds = switch ($match.Groups['op'].Value) {
+            '<' { $Version -lt $limit.Version }
+            '<=' { if ($limit.Pre) { $Version -lt $limit.Version } else { $Version -le $limit.Version } }
+            '>' { if ($limit.Pre) { $Version -ge $limit.Version } else { $Version -gt $limit.Version } }
+            '>=' { $Version -ge $limit.Version }
+            default { (-not $limit.Pre) -and $Version -eq $limit.Version }
+        }
+        if (-not $holds) { return 'Out' }
+    }
+    'In'
+}
+
+function Test-WatchVersionInRange {
+    param([Parameter(Mandatory)][version]$Version, [AllowNull()][AllowEmptyString()][string]$Range)
+    (Get-WatchRangeState -Version $Version -Range $Range) -eq 'In'
+}
+
+function Get-WatchAdvisoryHit {
+    <# The published advisories (GitHub API objects) that name the version (State Hit) or whose range for the package cannot be read (State Unreadable). With -Package only the entries of those packages count. #>
+    param([Parameter(Mandatory)][version]$Version, [AllowNull()][object[]]$Advisory, [string[]]$Package = @())
+    foreach ($candidate in @($Advisory)) {
+        if ($null -eq $candidate) { continue }
+        if ($candidate.PSObject.Properties['withdrawn_at'] -and $candidate.withdrawn_at) { continue }
+        $state = ''; $range = ''
+        foreach ($vulnerability in @($candidate.vulnerabilities)) {
+            if ($null -eq $vulnerability) { continue }
+            if ($Package.Count -gt 0) {
+                $name = if ($vulnerability.PSObject.Properties['package'] -and $null -ne $vulnerability.package -and $vulnerability.package.PSObject.Properties['name']) { [string]$vulnerability.package.name } else { '' }
+                if (-not ($Package | Where-Object { [string]::Equals($_, $name, [StringComparison]::OrdinalIgnoreCase) })) { continue }
+            }
+            $text = if ($vulnerability.PSObject.Properties['vulnerable_version_range']) { [string]$vulnerability.vulnerable_version_range } else { '' }
+            $result = Get-WatchRangeState -Version $Version -Range $text
+            if ($result -eq 'In') { $state = 'Hit'; $range = $text; break }
+            if ($result -eq 'Unreadable' -and $state -eq '') { $state = 'Unreadable'; $range = $text }
+        }
+        if ($state) { [pscustomobject]@{ Advisory = $candidate; State = $state; Range = $range } }
+    }
+}
+
+function Get-WatchAdvisoryFinding {
+    param(
+        [Parameter(Mandatory)][string]$Component, [Parameter(Mandatory)][version]$Version, [AllowNull()][object[]]$Advisory,
+        [string[]]$Package = @(), [Parameter(Mandatory)][ValidateSet('Fail', 'Warn')][string]$HitLevel
+    )
+    foreach ($hit in @(Get-WatchAdvisoryHit -Version $Version -Advisory $Advisory -Package $Package)) {
+        if ($hit.State -eq 'Hit') {
+            New-WatchFinding $HitLevel $Component ('A published advisory covers this version: {0} {1}' -f $hit.Advisory.ghsa_id, $hit.Advisory.summary) $hit.Advisory.html_url
+        }
+        else {
+            New-WatchFinding Warn $Component ('The version range of advisory {0} cannot be read (''{1}''): read the advisory and decide.' -f $hit.Advisory.ghsa_id, $hit.Range) $hit.Advisory.html_url
+        }
+    }
+}
+
+function Get-WatchLatestInLine {
+    <# The highest release version with the same major (and, with -Minor, minor) as the pinned one, from a list of tags. A tag that is not a release version (codeql-bundle-v2.27.5, a pre-release) is ignored. #>
+    param([Parameter(Mandatory)][version]$Pinned, [AllowNull()][string[]]$Tag, [switch]$Minor)
+    $best = $null
+    foreach ($text in @($Tag)) {
+        $version = ConvertTo-WatchVersion $text
+        if ($null -eq $version -or $version.Major -ne $Pinned.Major) { continue }
+        if ($Minor -and $version.Minor -ne $Pinned.Minor) { continue }
+        if ($null -eq $best -or $version -gt $best) { $best = $version }
+    }
+    $best
+}
+
+function Get-WatchPowerShellFinding {
+    param(
+        [Parameter(Mandatory)]$Pin, [AllowNull()][string[]]$ReleaseTag, [AllowNull()][object[]]$Advisory, [Parameter(Mandatory)][datetime]$Today,
+        [AllowNull()][object[]]$PackageAdvisory, [AllowNull()][object[]]$RuntimeAdvisory
+    )
+    $component = 'PowerShell {0} ({1})' -f $Pin.version, $Pin.role
+    $pinned = ConvertTo-WatchVersion ([string]$Pin.version)
+    $url = [string]$Pin.source
+    $hitLevel = if ($Pin.role -eq 'primary') { 'Fail' } else { 'Warn' }
+    $ends = [datetime]::ParseExact([string]$Pin.supportEnds, 'yyyy-MM-dd', [Globalization.CultureInfo]::InvariantCulture)
+    if ($Pin.role -eq 'primary') {
+        if ($ends -lt $Today) { New-WatchFinding Fail $component ('Support of the {0} line ended on {1}.' -f $Pin.line, $Pin.supportEnds) $Pin.supportSource }
+        elseif ($ends -lt $Today.AddDays(90)) { New-WatchFinding Warn $component ('Support of the {0} line ends on {1}.' -f $Pin.line, $Pin.supportEnds) $Pin.supportSource }
+    }
+    elseif ($ends -lt $Today) {
+        New-WatchFinding Info $component ('Support of the {0} line ended on {1}; this leg only keeps the offered floor tested.' -f $Pin.line, $Pin.supportEnds) $Pin.supportSource
+    }
+    Get-WatchAdvisoryFinding -Component $component -Version $pinned -Advisory $Advisory -HitLevel $hitLevel
+    Get-WatchAdvisoryFinding -Component $component -Version $pinned -Advisory $PackageAdvisory -Package @('Microsoft.PowerShell.SDK', 'System.Management.Automation') -HitLevel $hitLevel
+    $runtime = if ($Pin.PSObject.Properties['dotNetRuntime']) { ConvertTo-WatchVersion ([string]$Pin.dotNetRuntime) } else { $null }
+    if ($null -ne $runtime) {
+        Get-WatchAdvisoryFinding -Component ('{0}, .NET runtime {1}' -f $component, $runtime) -Version $runtime -Advisory $RuntimeAdvisory -Package @('Microsoft.NETCore.App.Runtime.win-x64') -HitLevel $hitLevel
+    }
+    $latest = Get-WatchLatestInLine -Pinned $pinned -Tag $ReleaseTag -Minor
+    if ($null -ne $latest -and $latest -gt $pinned) {
+        $level = if ($Pin.role -eq 'primary') { 'Warn' } else { 'Info' }
+        New-WatchFinding $level $component ('A newer release of the {0} line exists: {1}. Move the version and the SHA-256 together in .github\ci-pins.json.' -f $Pin.line, $latest) $url
+    }
+}
+
+function Get-WatchModuleFinding {
+    param([Parameter(Mandatory)]$Pin, [AllowNull()][string]$LatestVersion, [AllowNull()][object[]]$Advisory)
+    $component = '{0} {1}' -f $Pin.name, $Pin.version
+    $pinned = ConvertTo-WatchVersion ([string]$Pin.version)
+    Get-WatchAdvisoryFinding -Component $component -Version $pinned -Advisory $Advisory -HitLevel Fail
+    $latest = ConvertTo-WatchVersion $LatestVersion
+    if ($null -ne $latest -and $latest -gt $pinned) {
+        New-WatchFinding Warn $component ('The Gallery has {0}. Read its release notes, then move the version and both hashes together in .github\ci-pins.json.' -f $latest) $Pin.source
+    }
+}
+
+function Get-WatchActionFinding {
+    param(
+        [Parameter(Mandatory)]$Pin, [AllowNull()][string[]]$ReleaseTag, [AllowNull()][string]$TagCommit,
+        [AllowNull()][object[]]$Advisory
+    )
+    $component = '{0} {1}' -f $Pin.Name, $Pin.Tag
+    $pinned = ConvertTo-WatchVersion $Pin.Tag
+    $url = 'https://github.com/{0}/releases/tag/{1}' -f $Pin.Repository, $Pin.Tag
+    if (-not [string]::IsNullOrEmpty($TagCommit) -and -not [string]::Equals($TagCommit, $Pin.Sha, [StringComparison]::OrdinalIgnoreCase)) {
+        New-WatchFinding Fail $component ('The tag no longer points at the pinned commit (the tag is {0}).' -f $TagCommit) $url
+    }
+    Get-WatchAdvisoryFinding -Component $component -Version $pinned -Advisory $Advisory -Package @($Pin.Repository) -HitLevel Fail
+    $inLine = Get-WatchLatestInLine -Pinned $pinned -Tag $ReleaseTag
+    if ($null -ne $inLine -and $inLine -gt $pinned) {
+        New-WatchFinding Warn $component ('A newer release of the major {0} exists: {1}. Read the release notes, then change the pin and its tag comment together.' -f $pinned.Major, $inLine) $url
+    }
+    $highest = $null
+    foreach ($text in @($ReleaseTag)) { $version = ConvertTo-WatchVersion $text; if ($null -ne $version -and ($null -eq $highest -or $version -gt $highest)) { $highest = $version } }
+    if ($null -ne $highest -and $highest.Major -gt $pinned.Major) {
+        New-WatchFinding Info $component ('A newer major exists: {0}.' -f $highest) $url
+    }
+}
+
+function Get-WatchCertificateFinding {
+    <# The signing certificate: expired is a failure, ending within the warning days is a warning. The thumbprint of the pin is compared with the one the signed manifest names. #>
+    param([Parameter(Mandatory)]$Certificate, [AllowNull()][string]$ManifestThumbprint, [Parameter(Mandatory)][datetime]$Today)
+    $component = 'Signing certificate {0}' -f ([string]$Certificate.thumbprint).Substring(0, 8)
+    $ends = [datetime]::ParseExact([string]$Certificate.notAfter, 'yyyy-MM-dd', [Globalization.CultureInfo]::InvariantCulture)
+    $days = [int]($ends - $Today).TotalDays
+    if ($days -lt 0) { New-WatchFinding Fail $component ('The certificate expired on {0}.' -f $Certificate.notAfter) }
+    elseif ($days -le [int]$Certificate.warnDays) { New-WatchFinding Warn $component ('The certificate expires on {0} ({1} days). Renew it, then sign every file again.' -f $Certificate.notAfter, $days) }
+    if (-not [string]::IsNullOrEmpty($ManifestThumbprint) -and -not [string]::Equals($ManifestThumbprint, [string]$Certificate.thumbprint, [StringComparison]::OrdinalIgnoreCase)) {
+        New-WatchFinding Warn $component ('The signed manifest names the thumbprint {0}: the date in the pin file may belong to another certificate.' -f $ManifestThumbprint)
+    }
+}
+
+function Get-WatchWorkflowPin {
+    <# Every `uses:` of the workflows: Name, Repository, Sha, Tag, File, Line. A `uses:` that is not a full commit with an exact tag comment gets Valid = $false. Local actions (./) are skipped. #>
+    param([Parameter(Mandatory)][string]$RepositoryRoot)
+    $folder = Join-Path $RepositoryRoot '.github/workflows'
+    foreach ($file in @(Get-ChildItem -LiteralPath $folder -File | Where-Object { $_.Extension -in '.yml', '.yaml' } | Sort-Object Name)) {
+        $number = 0
+        foreach ($line in [IO.File]::ReadAllLines($file.FullName)) {
+            $number++
+            $match = [regex]::Match($line, '\buses:\s*(?[^\s#]+)')
+            if (-not $match.Success -or $line.TrimStart().StartsWith('#')) { continue }
+            $reference = $match.Groups['ref'].Value.Trim('''"')
+            if ($reference.StartsWith('./', [StringComparison]::Ordinal)) { continue }
+            $parts = $reference.Split('@')
+            $name = $parts[0]
+            $sha = if ($parts.Count -eq 2) { $parts[1] } else { '' }
+            $tag = [regex]::Match($line, '#\s*(?v\d+\.\d+\.\d+)\s*\z').Groups['t'].Value
+            $segments = $name.Split('/')
+            [pscustomobject]@{
+                Name = $name; Repository = ($segments[0..([Math]::Min(1, $segments.Count - 1))] -join '/'); Sha = $sha; Tag = $tag
+                File = $file.Name; Line = $number; Valid = ($sha -cmatch '\A[0-9a-f]{40}\z' -and $tag -ne '')
+            }
+        }
+    }
+}
+
+function Get-WatchDeclaredMinimum {
+    <# The minimum versions the package declares, read as text from its files. #>
+    param([Parameter(Mandatory)][string]$RepositoryRoot)
+    $common = [IO.File]::ReadAllText((Join-Path $RepositoryRoot 'package/module/PRA.Common.psm1'))
+    $manifest = [IO.File]::ReadAllText((Join-Path $RepositoryRoot 'package/PraRemoteMailbox.psd1'))
+    [pscustomobject]@{
+        PowerShell = [regex]::Match($manifest, "(?m)^\s*PowerShellVersion\s*=\s*'([0-9.]+)'").Groups[1].Value
+        ExchangeOnlineManagement = [regex]::Match($common, "(?m)^\`$script:PraMinExoVersion\s*=\s*'([0-9.]+)'").Groups[1].Value
+        GraphAuthentication = [regex]::Match($common, "(?m)^\`$script:PraMinGraphVersion\s*=\s*'([0-9.]+)'").Groups[1].Value
+    }
+}
+
+function Invoke-WatchRequest {
+    <# The only function that talks to the network: an https GET of public data. The workflow token goes only to api.github.com. Returns the content text. #>
+    param([Parameter(Mandatory)][string]$Uri, [hashtable]$Headers = @{})
+    $target = [uri]$Uri
+    if ($target.Scheme -ne 'https') { throw "Not an https address: $Uri" }
+    $send = @{ 'User-Agent' = 'dependency-watch' }
+    foreach ($key in $Headers.Keys) { $send[$key] = $Headers[$key] }
+    $token = if ($env:GH_TOKEN) { $env:GH_TOKEN } else { $env:GITHUB_TOKEN }
+    if ($token -and $target.Host -ceq 'api.github.com') { $send['Authorization'] = "Bearer $token" }
+    $reason = 'no answer'
+    for ($attempt = 1; $attempt -le 3; $attempt++) {
+        try {
+            $response = Invoke-WebRequest -Uri $Uri -Headers $send -Method Get -SkipHttpErrorCheck -TimeoutSec 60 -MaximumRedirection 3
+            if ([int]$response.StatusCode -ge 200 -and [int]$response.StatusCode -lt 300) { return [string]$response.Content }
+            $reason = 'HTTP {0}' -f [int]$response.StatusCode
+        }
+        catch { $reason = $_.Exception.Message }
+        if ($attempt -lt 3) { Start-Sleep -Seconds (5 * $attempt) }
+    }
+    throw "Source unavailable: $Uri ($reason)"
+}
+
+function Get-WatchGitHubJson {
+    param([Parameter(Mandatory)][string]$Path)
+    $json = Invoke-WatchRequest -Uri ('https://api.github.com/' + $Path) -Headers @{ Accept = 'application/vnd.github+json'; 'X-GitHub-Api-Version' = '2022-11-28' }
+    $json | ConvertFrom-Json
+}
+
+function Get-WatchPagedJson {
+    <# Up to five pages of 100 of a GitHub list. #>
+    param([Parameter(Mandatory)][string]$Path)
+    $items = New-Object 'System.Collections.Generic.List[object]'
+    for ($page = 1; $page -le 5; $page++) {
+        $chunk = @(Get-WatchGitHubJson ('{0}{1}per_page=100&page={2}' -f $Path, $(if ($Path.Contains('?')) { '&' } else { '?' }), $page))
+        foreach ($item in $chunk) { $items.Add($item) }
+        if ($chunk.Count -lt 100) { break }
+    }
+    , $items.ToArray()
+}
+
+function Get-WatchReleaseTag {
+    <# The tags of the published releases (the tag, never the release name: codeql-action also publishes codeql-bundle-v... releases). #>
+    param([Parameter(Mandatory)][string]$Repository)
+    $releases = Get-WatchPagedJson ('repos/{0}/releases' -f $Repository)
+    @($releases | Where-Object { -not $_.draft -and -not $_.prerelease } | ForEach-Object { [string]$_.tag_name })
+}
+
+function Get-WatchRepositoryAdvisory {
+    param([Parameter(Mandatory)][string]$Repository)
+    @(Get-WatchGitHubJson ('repos/{0}/security-advisories?state=published&per_page=100' -f $Repository))
+}
+
+function Get-WatchDatabaseAdvisory {
+    <# The GitHub Advisory Database for one package of an ecosystem (nuget, actions). The API does not filter by version: the ranges are read here. #>
+    param([Parameter(Mandatory)][ValidateSet('nuget', 'actions')][string]$Ecosystem, [Parameter(Mandatory)][string]$Package, [Parameter(Mandatory)][string]$Version)
+    @(Get-WatchPagedJson ('advisories?ecosystem={0}&affects={1}' -f $Ecosystem, [uri]::EscapeDataString($Package + '@' + $Version)))
+}
+
+function Get-WatchTagCommit {
+    param([Parameter(Mandatory)][string]$Repository, [Parameter(Mandatory)][string]$Tag)
+    $reference = Get-WatchGitHubJson ('repos/{0}/git/ref/tags/{1}' -f $Repository, [uri]::EscapeDataString($Tag))
+    $object = $reference.object
+    if ($object.type -eq 'tag') { $object = (Get-WatchGitHubJson ('repos/{0}/git/tags/{1}' -f $Repository, $object.sha)).object }
+    [string]$object.sha
+}
+
+function Get-WatchGalleryLatest {
+    param([Parameter(Mandatory)][string]$Name)
+    $uri = 'https://www.powershellgallery.com/api/v2/Packages()?$filter=' + [uri]::EscapeDataString("Id eq '$Name' and IsLatestVersion")
+    $xml = Invoke-WatchRequest -Uri $uri
+    $match = [regex]::Match($xml, ']*>([^<]+)')
+    if (-not $match.Success) { throw "Source unavailable: the PowerShell Gallery did not answer for $Name." }
+    $match.Groups[1].Value
+}
+
+function Invoke-WatchSource {
+    <# Runs one lookup of a kind of source; a lookup that fails becomes a warning and the watch goes on. The count of tries and failures per kind is kept (Get-WatchSourceFinding). A -Key repeats nothing. #>
+    param([Parameter(Mandatory)][scriptblock]$Lookup, [Parameter(Mandatory)][string]$Component, [Parameter(Mandatory)][string]$Kind, [System.Collections.Generic.List[object]]$Findings, [string]$Key)
+    if ($Key -and $script:WatchCache.ContainsKey($Key)) { return $script:WatchCache[$Key] }
+    if (-not $script:WatchStats.ContainsKey($Kind)) { $script:WatchStats[$Kind] = [pscustomobject]@{ Attempts = 0; Failures = 0 } }
+    $script:WatchStats[$Kind].Attempts++
+    try { $value = & $Lookup }
+    catch {
+        $script:WatchStats[$Kind].Failures++
+        $Findings.Add((New-WatchFinding Warn $Component ([string]$_.Exception.Message)))
+        $value = $null
+    }
+    if ($Key) { $script:WatchCache[$Key] = $value }
+    $value
+}
+
+function Get-WatchSourceFinding {
+    <# A kind of source where every lookup failed, and a run where every lookup failed, is a failure: the watch looked at nothing. #>
+    param([Parameter(Mandatory)][hashtable]$Stats)
+    $attempts = 0; $failures = 0
+    foreach ($kind in @($Stats.Keys | Sort-Object)) {
+        $entry = $Stats[$kind]
+        $attempts += $entry.Attempts; $failures += $entry.Failures
+        if ($entry.Attempts -gt 0 -and $entry.Failures -eq $entry.Attempts) {
+            New-WatchFinding Fail ('Source: {0}' -f $kind) ('All {0} lookup(s) failed: nothing of this kind was checked.' -f $entry.Attempts)
+        }
+    }
+    if ($attempts -eq 0) { New-WatchFinding Fail 'Sources' 'No lookup was made: nothing was checked.' }
+    elseif ($failures -eq $attempts) { New-WatchFinding Fail 'Sources' ('All {0} lookup(s) failed: nothing was checked.' -f $attempts) }
+}
+
+function ConvertTo-WatchAnnotation {
+    <# The text of a workflow command (::error, ::warning): % and the line breaks are written the way GitHub reads them. #>
+    param([AllowNull()][AllowEmptyString()][string]$Text)
+    if ($null -eq $Text) { return '' }
+    $Text.Replace('%', '%25').Replace("`r", '%0D').Replace("`n", '%0A')
+}
+
+function Format-WatchSummary {
+    param([Parameter(Mandatory)][AllowEmptyCollection()][object[]]$Finding, [Parameter(Mandatory)][datetime]$Today)
+    $culture = [Globalization.CultureInfo]::InvariantCulture
+    $builder = New-Object Text.StringBuilder
+    [void]$builder.AppendLine('# Dependency watch ' + $Today.ToString('yyyy-MM-dd', $culture)).AppendLine()
+    if ($Finding.Count -eq 0) { [void]$builder.AppendLine('Nothing to act on.') }
+    else {
+        [void]$builder.AppendLine('| Level | Component | Finding |').AppendLine('| --- | --- | --- |')
+        foreach ($item in $Finding) {
+            $text = ([string]$item.Message).Replace('|', '\|').Replace("`r", ' ').Replace("`n", ' ')
+            if ($item.Url) { $text += ' ' + $item.Url }
+            [void]$builder.AppendLine(('| {0} | {1} | {2} |' -f $item.Level, ([string]$item.Component).Replace('|', '\|'), $text))
+        }
+    }
+    [void]$builder.AppendLine().AppendLine(('Run date: {0} (UTC). This run is scheduled monthly. GitHub disables scheduled workflows after 60 days without repository activity: if no run is listed after {1}, enable the workflow again in the Actions tab (a keep-alive commit is not needed).' -f $Today.ToString('yyyy-MM-dd', $culture), $Today.AddDays(40).ToString('yyyy-MM-dd', $culture)))
+    $builder.ToString()
+}
+
+if ($LoadOnly) { return }
+
+$RepositoryRoot = [IO.Path]::GetFullPath($RepositoryRoot)
+$pins = Get-Content -LiteralPath (Join-Path $RepositoryRoot '.github/ci-pins.json') -Raw -Encoding UTF8 | ConvertFrom-Json
+$findings = New-Object 'System.Collections.Generic.List[object]'
+
+foreach ($pin in @($pins.powerShell)) {
+    $component = 'PowerShell ' + $pin.version
+    $tags = Invoke-WatchSource -Kind 'GitHub releases' -Component $component -Findings $findings -Key 'releases:PowerShell/PowerShell' -Lookup { Get-WatchReleaseTag 'PowerShell/PowerShell' }
+    $advisories = Invoke-WatchSource -Kind 'GitHub advisories' -Component $component -Findings $findings -Key 'repo-advisories:PowerShell/PowerShell' -Lookup { Get-WatchRepositoryAdvisory 'PowerShell/PowerShell' }
+    $packageAdvisories = @(foreach ($package in 'Microsoft.PowerShell.SDK', 'System.Management.Automation') {
+            Invoke-WatchSource -Kind 'GitHub advisories' -Component $component -Findings $findings -Lookup { Get-WatchDatabaseAdvisory nuget $package ([string]$pin.version) }
+        })
+    $runtimeAdvisories = if ($pin.PSObject.Properties['dotNetRuntime']) {
+        Invoke-WatchSource -Kind 'GitHub advisories' -Component $component -Findings $findings -Lookup { Get-WatchDatabaseAdvisory nuget 'Microsoft.NETCore.App.Runtime.win-x64' ([string]$pin.dotNetRuntime) }
+    }
+    foreach ($item in @(Get-WatchPowerShellFinding -Pin $pin -ReleaseTag $tags -Advisory $advisories -Today $Today -PackageAdvisory $packageAdvisories -RuntimeAdvisory $runtimeAdvisories)) { $findings.Add($item) }
+}
+
+$moduleRepositories = @{ Pester = 'pester/Pester'; PSScriptAnalyzer = 'PowerShell/PSScriptAnalyzer' }
+foreach ($pin in @($pins.modules)) {
+    $component = '{0} {1}' -f $pin.name, $pin.version
+    $latest = Invoke-WatchSource -Kind 'PowerShell Gallery' -Component $component -Findings $findings -Lookup { Get-WatchGalleryLatest $pin.name }
+    $repository = $moduleRepositories[[string]$pin.name]
+    $advisories = if ($repository) { Invoke-WatchSource -Kind 'GitHub advisories' -Component $component -Findings $findings -Key ('repo-advisories:' + $repository) -Lookup { Get-WatchRepositoryAdvisory $repository } }
+    foreach ($item in @(Get-WatchModuleFinding -Pin $pin -LatestVersion $latest -Advisory $advisories)) { $findings.Add($item) }
+}
+
+$seenPins = New-Object 'System.Collections.Generic.HashSet[string]' -ArgumentList ([StringComparer]::Ordinal)
+foreach ($pin in @(Get-WatchWorkflowPin $RepositoryRoot)) {
+    if ($pin.Valid -and -not $seenPins.Add(('{0}|{1}|{2}' -f $pin.Repository, $pin.Sha, $pin.Tag))) { continue }
+    if (-not $pin.Valid) {
+        $findings.Add((New-WatchFinding Fail ('{0}:{1}' -f $pin.File, $pin.Line) ('{0} is not a full commit with an exact tag comment (# vX.Y.Z).' -f $pin.Name)))
+        continue
+    }
+    $component = '{0} {1}' -f $pin.Name, $pin.Tag
+    $tags = Invoke-WatchSource -Kind 'GitHub releases' -Component $component -Findings $findings -Key ('releases:' + $pin.Repository) -Lookup { Get-WatchReleaseTag $pin.Repository }
+    $commit = Invoke-WatchSource -Kind 'GitHub tags' -Component $component -Findings $findings -Lookup { Get-WatchTagCommit $pin.Repository $pin.Tag }
+    $advisories = Invoke-WatchSource -Kind 'GitHub advisories' -Component $component -Findings $findings -Lookup { Get-WatchDatabaseAdvisory actions $pin.Repository ([string](ConvertTo-WatchVersion $pin.Tag)) }
+    foreach ($item in @(Get-WatchActionFinding -Pin $pin -ReleaseTag $tags -TagCommit $commit -Advisory $advisories)) { $findings.Add($item) }
+}
+
+$declared = Get-WatchDeclaredMinimum $RepositoryRoot
+$galleryNames = @{ ExchangeOnlineManagement = $declared.ExchangeOnlineManagement; 'Microsoft.Graph.Authentication' = $declared.GraphAuthentication }
+foreach ($name in $galleryNames.Keys) {
+    $latest = Invoke-WatchSource -Kind 'PowerShell Gallery' -Component $name -Findings $findings -Lookup { Get-WatchGalleryLatest $name }
+    $minimum = ConvertTo-WatchVersion $galleryNames[$name]
+    $newest = ConvertTo-WatchVersion $latest
+    if ($null -ne $minimum -and $null -ne $newest -and $newest -gt $minimum) {
+        $findings.Add((New-WatchFinding Info $name ('The package requires at least {0}; the Gallery has {1}.' -f $minimum, $newest)))
+    }
+}
+$floor = ConvertTo-WatchVersion $declared.PowerShell
+$floorPin = @($pins.powerShell | Where-Object { $_.role -eq 'floor' })
+if ($null -ne $floor -and $floorPin.Count -eq 1 -and [datetime]::ParseExact([string]$floorPin[0].supportEnds, 'yyyy-MM-dd', [Globalization.CultureInfo]::InvariantCulture) -lt $Today) {
+    $findings.Add((New-WatchFinding Info ('PowerShell ' + $declared.PowerShell) ('The floor the package declares is a line whose support ended on {0}.' -f $floorPin[0].supportEnds) $floorPin[0].supportSource))
+}
+
+$manifestText = [IO.File]::ReadAllText((Join-Path $RepositoryRoot 'package/PackageIntegrity.psd1'))
+$manifestThumbprint = [regex]::Match($manifestText, "(?m)^\s*SignerThumbprint\s*=\s*'([0-9A-Fa-f]{40})'").Groups[1].Value
+foreach ($item in @(Get-WatchCertificateFinding -Certificate $pins.signingCertificate -ManifestThumbprint $manifestThumbprint -Today $Today)) { $findings.Add($item) }
+foreach ($item in @(Get-WatchSourceFinding -Stats $script:WatchStats)) { $findings.Add($item) }
+
+[void][IO.Directory]::CreateDirectory($OutputDirectory)
+$ordered = @($findings | Sort-Object @{ Expression = { switch ($_.Level) { 'Fail' { 0 } 'Warn' { 1 } default { 2 } } } }, Component)
+$summary = Format-WatchSummary -Finding $ordered -Today $Today
+[IO.File]::WriteAllText((Join-Path $OutputDirectory 'dependency-watch.md'), $summary, (New-Object Text.UTF8Encoding($false)))
+[IO.File]::WriteAllText((Join-Path $OutputDirectory 'dependency-watch.json'), (ConvertTo-Json -InputObject $ordered -Depth 5), (New-Object Text.UTF8Encoding($false)))
+if ($env:GITHUB_STEP_SUMMARY) { [IO.File]::AppendAllText($env:GITHUB_STEP_SUMMARY, $summary, (New-Object Text.UTF8Encoding($false))) }
+foreach ($item in $ordered) {
+    $text = ConvertTo-WatchAnnotation ('{0}: {1}' -f $item.Component, $item.Message)
+    switch ($item.Level) {
+        'Fail' { Write-Output ('::error title=Dependency watch::' + $text) }
+        'Warn' { Write-Output ('::warning title=Dependency watch::' + $text) }
+        default { Write-Output ('Info: ' + ('{0}: {1}' -f $item.Component, $item.Message).Replace("`r", ' ').Replace("`n", ' ')) }
+    }
+}
+$failed = @($ordered | Where-Object Level -eq 'Fail').Count
+Write-Output ('Dependency watch {0}: {1} failure(s), {2} warning(s), {3} information line(s). The scheduled run needs repository activity within 60 days to stay enabled.' -f $Today.ToString('yyyy-MM-dd', [Globalization.CultureInfo]::InvariantCulture), $failed, @($ordered | Where-Object Level -eq 'Warn').Count, @($ordered | Where-Object Level -eq 'Info').Count)
+exit $(if ($failed) { 1 } else { 0 })
diff --git a/.github/workflows/attest-release.yml b/.github/workflows/attest-release.yml
index b70a28b..e192650 100644
--- a/.github/workflows/attest-release.yml
+++ b/.github/workflows/attest-release.yml
@@ -181,7 +181,7 @@ jobs:
 
       # Binds distributed ZIP bytes to this repository/workflow; does not prove their original build.
       - name: Generate artifact attestation
-        uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4
+        uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2
         with:
           subject-path: 'dist/*.zip'
           push-to-registry: false
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index acda216..9a001d6 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -22,45 +22,48 @@ jobs:
     strategy:
       fail-fast: false
       matrix:
-        include: [{"engine":"PowerShell 7","shell":"pwsh","package":true}]
+        include: [{"engine":"PowerShell 7","line":"7.6","package":true}]
     steps:
       - name: Check out the tested revision
-        uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
+        uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
         with:
           persist-credentials: false
 
-      - name: Ensure PowerShell 7.5 or later (the engine requires it; the image ships 7.4)
+      - name: Install the pinned PowerShell ${{ matrix.line }} (the image ships an older one)
         shell: pwsh
-        run: .\.github\scripts\Install-PowerShell.ps1
+        run: .\.github\scripts\Install-PowerShell.ps1 -Line '${{ matrix.line }}'
 
       - name: Show the PowerShell that runs the next steps
         shell: pwsh
+        env:
+          POWERSHELL_LINE: ${{ matrix.line }}
         run: |
           $PSVersionTable.PSVersion.ToString()
           $PSHOME
-          if ($PSVersionTable.PSVersion -lt [version]'7.5.0') { throw 'PowerShell 7.5+ is required.' }
+          if (-not $PSVersionTable.PSVersion.ToString().StartsWith($env:POWERSHELL_LINE + '.', [StringComparison]::Ordinal)) { throw "PowerShell $env:POWERSHELL_LINE is required." }
 
       - name: Load pinned analysis and test modules
         shell: pwsh
         run: .\.github\scripts\Initialize-CIModules.ps1 -Destination "$env:RUNNER_TEMP\ci-modules"
 
-      - name: Analyze PowerShell sources (PowerShell 7.5)
+      - name: Analyze PowerShell sources (PowerShell ${{ matrix.line }})
         shell: pwsh
         run: .\.github\scripts\Invoke-CI.ps1 -Stage Analyze -OutputDirectory "$env:RUNNER_TEMP\ci-results"
 
-      - name: Run the existing project tests (PowerShell 7.5)
+      - name: Run the existing project tests (PowerShell ${{ matrix.line }})
         shell: pwsh
         run: .\.github\scripts\Invoke-CI.ps1 -Stage Test -OutputDirectory "$env:RUNNER_TEMP\ci-results"
 
-      - name: Build with the existing package tool (PowerShell 7.5)
+      - name: Build with the existing package tool (PowerShell ${{ matrix.line }})
+        if: ${{ matrix.package }}
         shell: pwsh
         run: .\.github\scripts\Invoke-CI.ps1 -Stage Package -OutputDirectory "$env:RUNNER_TEMP\ci-results"
 
       - name: Retain public CI evidence
         if: always()
-        uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
+        uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
         with:
-          name: ci-powershell-7.5
+          name: ci-powershell-${{ matrix.line }}
           path: |
             ${{ runner.temp }}/ci-results
             tests/evidence/gate
diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml
index 7e249ba..c2341e6 100644
--- a/.github/workflows/codeql.yml
+++ b/.github/workflows/codeql.yml
@@ -1,71 +1,53 @@
-{
-  "name": "CodeQL (advisory)",
-  "on": {
-    "pull_request": {
-      "branches": ["main"]
-    },
-    "push": {
-      "branches": ["main"]
-    },
-    "schedule": [
-      {
-        "cron": "41 5 * * 3"
-      }
-    ],
-    "workflow_dispatch": {}
-  },
-  "permissions": {},
-  "concurrency": {
-    "group": "codeql-${{ github.workflow }}-${{ github.ref }}",
-    "cancel-in-progress": true
-  },
-  "jobs": {
-    "analyze": {
-      "name": "CodeQL ${{ matrix.language }} (advisory)",
-      "if": "${{ contains(fromJSON('[\"Nico77600/EasOAuthMailbox\",\"Nico77600/Exchange2013-2016-to-2019-Migration\",\"Nico77600/ExchangeLogReport\",\"Nico77600/ExchangeMailboxMigration\",\"Nico77600/MailboxMessageReport\",\"Nico77600/MeetingCleanup\",\"Nico77600/MeetingCleanupOnPrem\",\"Nico77600/MessageTraceReport\",\"Nico77600/PraCloudMailbox\",\"Nico77600/PraRemoteMailbox\",\"Nico77600/PurviewDlpReport\",\"Nico77600/PurviewDlpReport-Fabric\",\"Nico77600/RecipientLimitReport\",\"Nico77600/WebServicesClient\",\"Nico77600/XTapSharingMigration\"]'), github.repository) && (github.event_name == 'pull_request' || github.ref == 'refs/heads/main') }}",
-      "runs-on": "ubuntu-latest",
-      "timeout-minutes": 25,
-      "permissions": {
-        "contents": "read",
-        "security-events": "write"
-      },
-      "strategy": {
-        "fail-fast": false,
-        "max-parallel": 2,
-        "matrix": {
-          "language": ["actions"]
-        }
-      },
-      "steps": [
-        {
-          "name": "Check out event revision",
-          "uses": "actions/checkout@11d5960a326750d5838078e36cf38b85af677262",
-          "with": {
-            "persist-credentials": false
-          }
-        },
-        {
-          "name": "Initialize source-only analysis",
-          "uses": "github/codeql-action/init@24c54180a607b1449ed407dd24f251e4e9147c8d",
-          "with": {
-            "languages": "${{ matrix.language }}",
-            "build-mode": "none",
-            "threads": 2,
-            "dependency-caching": "false",
-            "config": "{\"name\":\"GitHub Actions workflows\",\"paths\":[\".github/workflows\"]}"
-          }
-        },
-        {
-          "name": "Analyze and upload advisory results",
-          "uses": "github/codeql-action/analyze@24c54180a607b1449ed407dd24f251e4e9147c8d",
-          "with": {
-            "category": "/language:${{ matrix.language }}",
-            "upload": "always",
-            "upload-database": "false",
-            "wait-for-processing": "true"
-          }
-        }
-      ]
-    }
-  }
-}
+name: CodeQL (advisory)
+
+on:
+  pull_request:
+    branches: [main]
+  push:
+    branches: [main]
+  schedule:
+    - cron: '41 5 * * 3'
+  workflow_dispatch: {}
+
+permissions: {}
+
+concurrency:
+  group: codeql-${{ github.workflow }}-${{ github.ref }}
+  cancel-in-progress: true
+
+jobs:
+  analyze:
+    name: CodeQL ${{ matrix.language }} (advisory)
+    if: ${{ github.repository == 'Nico77600/PraRemoteMailbox' && (github.event_name == 'pull_request' || github.ref == 'refs/heads/main') }}
+    runs-on: ubuntu-latest
+    timeout-minutes: 25
+    permissions:
+      contents: read
+      security-events: write
+    strategy:
+      fail-fast: false
+      max-parallel: 2
+      matrix:
+        language: [actions]
+    steps:
+      - name: Check out event revision
+        uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+        with:
+          persist-credentials: false
+
+      - name: Initialize source-only analysis
+        uses: github/codeql-action/init@915412ff23e8b7659517e607487dbeae018f2934 # v4.39.5
+        with:
+          languages: ${{ matrix.language }}
+          build-mode: none
+          threads: 2
+          dependency-caching: false
+          config: '{"name":"GitHub Actions workflows","paths":[".github/workflows"]}'
+
+      - name: Analyze and upload advisory results
+        uses: github/codeql-action/analyze@915412ff23e8b7659517e607487dbeae018f2934 # v4.39.5
+        with:
+          category: /language:${{ matrix.language }}
+          upload: always
+          upload-database: false
+          wait-for-processing: true
diff --git a/.github/workflows/dependency-watch.yml b/.github/workflows/dependency-watch.yml
new file mode 100644
index 0000000..ea60699
--- /dev/null
+++ b/.github/workflows/dependency-watch.yml
@@ -0,0 +1,46 @@
+name: Dependency watch
+
+# Monthly, on the 16th (Patch Tuesday is never later than the 14th). The run reads public data only and reports.
+# A failed run is the alert: it notifies the account that last edited the schedule. The workflow opens no issue and no pull request.
+on:
+  schedule:
+    - cron: '23 6 16 * *'
+  workflow_dispatch:
+
+permissions:
+  contents: read
+
+concurrency:
+  group: dependency-watch-${{ github.repository }}
+  cancel-in-progress: false
+
+jobs:
+  watch:
+    name: Watch the pinned and declared dependencies
+    if: ${{ github.repository == 'Nico77600/PraRemoteMailbox' }}
+    runs-on: ubuntu-latest
+    timeout-minutes: 20
+    steps:
+      - name: Check out the revision without persistent credentials
+        uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+        with:
+          persist-credentials: false
+
+      - name: Compare the pins and the declared minimums with the public sources
+        shell: pwsh
+        env:
+          GH_TOKEN: ${{ github.token }}
+        run: |
+          & ./.github/scripts/Invoke-DependencyWatch.ps1 -OutputDirectory (Join-Path $env:RUNNER_TEMP 'dependency-watch')
+          exit $LASTEXITCODE
+
+      - name: Keep the complete result of the watch
+        if: ${{ always() }}
+        uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
+        with:
+          name: dependency-watch
+          path: |
+            ${{ runner.temp }}/dependency-watch/dependency-watch.json
+            ${{ runner.temp }}/dependency-watch/dependency-watch.md
+          if-no-files-found: warn
+          retention-days: 90
diff --git a/AGENTS.md b/AGENTS.md
index 5a2a07e..2daaea8 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -49,4 +49,8 @@ Required validation checks are enabled only after successful GitHub runs. Do not
 
 The release attestation workflow does not build or execute repository code. It attests the actual published ZIP bytes; it does not prove their original build. Manual attestation must run from the default branch with an explicit existing release tag. Missing releases or ZIPs fail explicitly; no source archive is substituted.
 
-Actions are pinned to full commit IDs. Updates require review of the action source and an explicit pin change. Repository policies may reject unpinned or unapproved actions; never relax them to merge a contribution.
+Actions are pinned to full commit IDs, each with its exact release tag in a comment on the same line. Updates require review of the action source and an explicit pin change, and the repository's allowed-actions list names the same commits. Repository policies may reject unpinned or unapproved actions; never relax them to merge a contribution.
+
+The CI PowerShell, Pester and PSScriptAnalyzer are pinned in .github/ci-pins.json: the version and the hash of the official archive or package change together, in one commit. CI runs on PowerShell 7.6, the only PowerShell 7 line the tool supports. A monthly workflow compares the pins and the declared minimum versions with the public sources and reports; it fails only when a pinned version is named by an advisory, the support of the pinned PowerShell line has ended, or a pinned action commit is no longer the commit of its tag. It opens no issue and no pull request.
+
+tools/New-Sbom.ps1 writes the bill of materials and the dependency declaration of a release ZIP at packaging time (the CI Package stage runs it on the built package and checks the result), and tools/Compare-ReleaseSource.ps1 compares a release ZIP with the source committed in git, byte for byte.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3811452..e97ca83 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,23 @@ All notable changes of PRA Remote Mailbox. Author: Nicolas Fabert. Versions foll
 a MAJOR version changes the command line or the configuration file, a MINOR version adds a feature,
 a PATCH version fixes a defect. The backup formats have their own version (see the guide, annex D).
 
+## 3.3.0 — 2026-11-27
+
+**PowerShell 7.6 is now required.** Windows PowerShell 5.1 and PowerShell 7.5 are refused before any code runs: install PowerShell 7.6 LTS before replacing the package folder. Files written by older versions are still read, every new setting is optional, and a new check warns before it refuses.
+
+### Added
+- Transfer packages: the fingerprint of a package (`-ExpectedFingerprint`), a comparison of a Finalize with the originals kept on the AD server, tenant and domain recorded in new files, and an optional shared secret (`Transfer.Authenticate`, a `.auth` file). Refusals exist only behind the `Transfer.Require...` settings or `-ExpectedFingerprint`.
+- Optional protection of backups and packages at rest (`Storage.Protect`: AES-256-GCM, with a certificate, a key file or a passphrase).
+- `-Action Cleanup`: lists the finished batches, the old logs and the reports, and deletes them only after you type a word.
+- The Preview of the AD part reads the permissions of each object and warns when your account is likely to be refused.
+- Windows events for each Apply and each safety override (`Logging.WindowsEvents`), the overrides recorded in the log, the summary and the report, the account in every journal line, and an optional hash chain of the journal (`Logging.JournalChain`).
+- A package signed by the owner starts on an isolated server, without the public root certificate, with one warning, also kept in the log and the report of the run, while the signing certificate is valid.
+- Start-up checks that warn: the versions and paths in use, who can write or read the folders of the tool (`Security.RequireProtectedFolders` makes an Apply refuse), and what the run will use.
+- Optional strict settings, off by default: `Retention.RequireLiveCheck` (a Recover never reads a retention proof; Exchange Online must answer in the run) and `Logging.RequireJournalChain` (a Recover stops when the chain of the batch journal is broken). `Console.NetworkProbes = 'Off'` stops the network tests of the Setup page, for an Active Directory server that must stay isolated.
+- The Exchange Online child process starts from its standard input, without a temporary script (`Exo.ChildStart`), and from a script file with `-ExecutionPolicy Bypass` for itself only under the `AllSigned` execution policy, after the tool checked the Microsoft signature of the installed module, with a clear error when a Group Policy enforces it; the HTML reports carry a Content-Security-Policy; an optional UTC offset in the text log (`Logging.TimestampOffset`).
+- Guides: the quick rights, then the exact list; the versions; hardening; the data the tool writes and how to keep and delete it; removal; the network connections; the events; SECURITY.md with the supported versions, the verification of a release and the renewal of the signing certificate.
+- Repository: CI on PowerShell 7.6 with pinned tools, a monthly dependency watch, a bill of materials and a source comparison for each release.
+
 ## 3.2.0 — 2026-11-22
 
 ### Added
@@ -229,7 +246,7 @@ addressed in 2.0.0. No defect of the backup/proof engine was found.
 
 ### Validation
 
-- Test gate on VMLLM (Windows PowerShell 5.1, Pester 6.0.0, PSScriptAnalyzer 1.25.0): **279 / 279 passed**,
+- Test gate on OPS01 (Windows PowerShell 5.1, Pester 6.0.0, PSScriptAnalyzer 1.25.0): **279 / 279 passed**,
   0 analyzer error (evidence `tests\evidence\gate\v2.0.0-release`). The 61 tests of the removed path options
   of 1.3.6 are replaced by tests of `-Batch` and of the confirmation (1.3.6: 325 tests).
 - Lab campaign 2026-09-30 / 2026-10-01 on a lab Active Directory domain + a Microsoft 365 test tenant (real AD, Entra Connect and
diff --git a/PROVENANCE.md b/PROVENANCE.md
index e6d4114..4443992 100644
--- a/PROVENANCE.md
+++ b/PROVENANCE.md
@@ -5,6 +5,6 @@
 - Audited revision: `8caa5cbd693d633e570f0e95d9eed6998fcf0723`
 - Audit date: 2026-10-07
 - Public commits inspected across branches and tags: 18
-- `Co-authored-by: Copilot` findings: none
+- Co-author trailers of automated tools: none
 
 This declaration records the public commit-history audit at the revision above. It is not a cryptographic signature and does not make claims about how source code was authored. Release assets are covered by the GitHub Actions workflow in `.github/workflows/attest-release.yml`; run it manually for an existing release when needed.
diff --git a/README.md b/README.md
index 1968125..e9c32ae 100644
--- a/README.md
+++ b/README.md
@@ -21,7 +21,7 @@
 

> [!TIP] -> **Download the latest release.** Open the [latest release](https://github.com/Nico77600/PraRemoteMailbox/releases/latest) and download **`PraRemoteMailbox-3.2.0.zip`** under *Assets* (its SHA-256 is in the release notes). That ZIP is the signed tool, with the HTML guides. Do not use the **Source code** archives or the green **Code** button: they are a copy of the repository, not the release package. +> **Download the latest release.** Open the [latest release](https://github.com/Nico77600/PraRemoteMailbox/releases/latest) and download **`PraRemoteMailbox-3.3.0.zip`** under *Assets* (its SHA-256 is in the release notes). That ZIP is the signed tool, with the HTML guides. Do not use the **Source code** archives or the green **Code** button: they are a copy of the repository, not the release package. > [!IMPORTANT] > Files downloaded from the Internet may be blocked by Windows and fail to run. Before using this project, unblock every file in the downloaded folder: @@ -35,7 +35,7 @@ > The `Install-Module` commands in this documentation use `-Force`, so they also update or reinstall a module that is already installed. If an older version still conflicts, close every PowerShell window, open a new one (as administrator for `-Scope AllUsers`), run `Uninstall-Module -AllVersions -Force`, then run the `Install-Module` command again. > [!IMPORTANT] -> **3.0.0 requires PowerShell 7.5 or later (`pwsh.exe`).** Windows PowerShell 5.1 is refused before any code runs. The **2.2.x releases remain the Windows PowerShell 5.1 version** for servers that cannot have PowerShell 7. Backups, proofs and Finalize packages written by 2.x restore unchanged with 3.0.0 (the formats did not change, [reference guide](package/docs/PraRemoteMailbox-Guide.md) annex D). +> **PowerShell 7.6 is required (`pwsh.exe`).** Windows PowerShell 5.1 and PowerShell 7.5 or earlier are refused before any code runs; install PowerShell 7.6 LTS first (`winget install Microsoft.PowerShell`, or the MSI from https://aka.ms/powershell). The **2.2.x releases remain the Windows PowerShell 5.1 version** for servers that cannot have PowerShell 7; 2.2.x is no longer supported and receives no fix. Backups, proofs and Finalize packages written by older versions are still read and restore unchanged (the formats did not change, [reference guide](package/docs/PraRemoteMailbox-Guide.md) annex D). ## Why @@ -48,7 +48,7 @@ In a hybrid organisation, a mailbox hosted on-premises is only a *mail user* for Done by hand, this means rewriting about ten Exchange attributes per object in Active Directory, for hundreds of objects, under stress — and keeping every original value to come back later: a wrong or lost value cannot be repaired without a backup. This tool does the conversion in a planned, verified and **reversible** way. -**Author:** Nicolas Fabert · **Version:** 3.2.0, 2026-11-22 ([changelog](CHANGELOG.md)). +**Author:** Nicolas Fabert · **Version:** 3.3.0, 2026-11-27 ([changelog](CHANGELOG.md)). > [!CAUTION] > Convert creates **new, empty** mailboxes in Exchange Online: the content of the on-premises mailboxes is not moved. A Recover deprovisions the cloud mailboxes: export first what was received in the cloud during the disaster, or protect it with a retention policy (reference guide, chapter 6). Before it removes anything, a Recover checks that the retention policy holds the mailboxes and stops when it does not (`-AcceptRetentionRisk` accepts the risk for one run). @@ -67,8 +67,8 @@ One path for everyone. Set the tool up once (**1 to 4**), then take branch **A** ```powershell # 1 · Get your rights. Give the table "Requirements" below to your administrator (minimum rights, derived from the code). -# 2 · On the server, in PowerShell 7.5+ as administrator: put the tool in its folder and unblock it. -# Download PraRemoteMailbox-3.2.0.zip from the latest release (under Assets, not Source code) and extract it to D:\PRA\PraRemoteMailbox +# 2 · On the server, in PowerShell 7.6 as administrator: put the tool in its folder and unblock it. +# Download PraRemoteMailbox-3.3.0.zip from the latest release (under Assets, not Source code) and extract it to D:\PRA\PraRemoteMailbox Get-ChildItem D:\PRA\PraRemoteMailbox -Recurse -File -Force | Unblock-File Install-Module ExchangeOnlineManagement -MinimumVersion 3.10.1 -Scope AllUsers -Force Install-Module Microsoft.Graph.Authentication -MinimumVersion 2.41.1 -Scope AllUsers -Force # one command per module: PowerShellGet refuses -MinimumVersion with several names @@ -202,7 +202,7 @@ Exchange on-premises is down, so the tool reads the permissions where Exchange k ## Console -Open the console with `pwsh -STA -File .\package\Invoke-PraRemoteMailbox.ps1 -Gui` (native Fluent theme, PowerShell 7.5+, English). It starts no operation by itself; every operation runs the existing engine in a separate **PowerShell 7.5+** process (the same `pwsh.exe`). +Open the console with `pwsh -STA -File .\package\Invoke-PraRemoteMailbox.ps1 -Gui` (native Fluent theme, PowerShell 7.6, English). It starts no operation by itself; every operation runs the existing engine in a separate **PowerShell 7.6** process (the same `pwsh.exe`). The console is a guided path of five pages: **Setup** (the environment, what this server can run, the prerequisite lights from real detection, one line of run settings), **Task** (move mailboxes, roll back, complete a rollback, check a mailbox, on what: one identity to test first, the configured scope, an OU or a CSV, or a batch or package to continue), **Verify** (the Preview in plain words, then the confirmation word in any letter case), **Run** (the steps announced by the engine, with their waits and warnings in plain words; click a step or an object) and **Next steps**. The batch lists show what is **To do** and what is **Finished**. Run settings changed in the window apply to that run only, through a guarded effective copy of the configuration: the file is never rewritten. See the [reference guide, chapter 8](package/docs/PraRemoteMailbox-Guide.md#8-everyday-use). @@ -231,11 +231,13 @@ Every run writes a log, a PowerShell transcript, a CSV and an HTML report. Exit | Item | Requirement | |---|---| | Scenario | Hybrid Exchange organisation (Exchange Server + Exchange Online) synchronised by **Entra Connect**. Exchange on-premises is not needed (it is down); Active Directory and Entra Connect must work (both lost: [PRA Cloud Mailbox](https://github.com/Nico77600/PraCloudMailbox)) | -| PowerShell | **PowerShell 7.5 or later** (`pwsh.exe`) for the operations and the window. Windows PowerShell 5.1 is refused (use the 2.2.x release there) | +| PowerShell | **PowerShell 7.6** (`pwsh.exe`) for the operations and the window. Windows PowerShell 5.1 and PowerShell 7.5 or earlier are refused (use the 2.2.x release on Windows PowerShell 5.1; 2.2.x is no longer supported and receives no fix) | | Modules | RSAT `ActiveDirectory` (native in PowerShell 7 on Windows 10 1809+ / Windows Server 2019+), `ExchangeOnlineManagement` 3.10.1 or later and `Microsoft.Graph.Authentication` / `Microsoft.Graph.Users` 2.41.1 or later (both Graph modules in one same version), installed **for PowerShell 7**; `ADSync` on the Entra Connect server (loaded through the Windows PowerShell compatibility layer when used locally) | | Licences | A licence group that gives Exchange Online to the users (shared mailboxes need no licence) | | Console | Windows Terminal for emoji and colours; the classic console shows symbols | +The supported and recommended versions (PowerShell 7.6 LTS and its patch level, the modules, RSAT, Entra Connect Sync, the browser) are listed in the [reference guide, chapter 4](package/docs/PraRemoteMailbox-Guide.md#versions). + ### Minimum permissions Derived from the code, not from habit: no Domain Admin, no Global Administrator. The exact table, with the place in the code that justifies each line and the commands to delegate, is in the [reference guide, chapter 4](package/docs/PraRemoteMailbox-Guide.md#permissions). @@ -254,11 +256,11 @@ Derived from the code, not from habit: no Domain Admin, no Global Administrator. | Exchange Online, interactive | **Exchange Recipient Administrator** (or the role group Recipient Management) | | Exchange Online, certificate | Application permission `Exchange.ManageAsApp` (admin consent) and the Entra role **Exchange Recipient Administrator** for the application; a CSP certificate in `CurrentUser\My` (reference guide, annex C) | -A few points depend on Microsoft services and are flagged for a lab check in the reference guide (*What the code cannot tell you*). +To try the tool, the guide first lists broader rights that work quickly: they are never required, and they are to be reviewed after the rehearsal; the table above is the exact list for the real day. A few points depend on Microsoft services and are flagged for a lab check in the reference guide (*What the code cannot tell you*). ## Quick start -The short version of [Get started](#get-started), once the rights and the settings file are ready. PowerShell 7.5+, as administrator, in the tool folder: +The short version of [Get started](#get-started), once the rights and the settings file are ready. PowerShell 7.6, as administrator, in the tool folder: ```powershell cd D:\PRA\PraRemoteMailbox @@ -274,18 +276,25 @@ The `package` folder of this repository holds exactly the files needed to run PR | Guide | Content | |---|---| | **[User guide](package/docs/PraRemoteMailbox-UserGuide.md)** | **The guided path in plain words**, written for someone who has never used the tool: a checklist before you start, the rights to ask for, set up once (**1 to 4**), then **A · Move mailboxes** (one test mailbox, everyone on one server, everyone on two servers) and **B · Go back** (roll back, complete the rollback). A picture for each step, what you should see and what to do if not, a table of the common messages, and a picture dictionary. | -| **[Reference guide](package/docs/PraRemoteMailbox-Guide.md)** | Everything else: the disaster scenario, what changes in Active Directory, the shared mailbox permissions, installation, the exact minimum permissions, configuration, unattended execution with a certificate, ready-to-use recipes, the reports, troubleshooting, the internals, how to modify and test the tool, and the lab test campaign. | +| **[Reference guide](package/docs/PraRemoteMailbox-Guide.md)** | Everything else: the disaster scenario, what changes in Active Directory, the shared mailbox permissions, the versions, the rights (quick, then exact), the accounts and the network connections, installation and hardening, configuration, unattended execution with a certificate, ready-to-use recipes, the Windows events and exit codes, the reports, the files and the handling of the data, removal, troubleshooting, the internals, how to modify and test the tool, and the lab test campaign. | Both guides also exist as a single HTML file with a light and a dark theme (`package/docs/PraRemoteMailbox-UserGuide.html`, `package/docs/PraRemoteMailbox-Guide.html`): download them and open them locally, or use the copies in the release zip. The pictures are generated from synthetic data by `tools\New-DocumentationImages.ps1`. ## Tests ```powershell -# PowerShell 7.5+ (pwsh), like the tool; Pester 5+ and PSScriptAnalyzer 1.25.0 installed +# PowerShell 7.6 (pwsh), like the tool; Pester 5+ and PSScriptAnalyzer 1.25.0 installed pwsh -NoProfile -File .\tests\Invoke-TestGate.ps1 # no directory, no tenant needed ``` -The gate runs the real entry script against a synthetic Active Directory, Entra Connect and Exchange Online: no write before the complete backup, stop at the first error, no write in Preview, no Apply without confirmation, memory bounds, proofs and Finalize packages. It also exercises WPF selection, Preview/Apply guards and OU/CSV targeting, and checks the documentation (pictures, names, the Graph scope documented against the one of the code). Earlier versions were validated on a real Active Directory, Entra Connect and Microsoft 365 tenant (reference guide, annex B); **3.2.0 was validated on a real lab** with two servers (Convert, Recover, the retention check before Recover, interrupted runs). Files written by the real 2.2.0 under Windows PowerShell 5.1 are replayed by the gate (`tests\PraLegacyFixtures.Tests.ps1`, fixtures frozen in `tests\fixtures\ps51-2.2.0`). `tools\Build-Documentation.ps1` and `tools\New-DocumentationImages.ps1`, which rebuild the HTML guides and the pictures on a workstation, need PowerShell 7.5+ (and Microsoft Edge for the pictures). +The gate runs the real entry script against a synthetic Active Directory, Entra Connect and Exchange Online: no write before the complete backup, stop at the first error, no write in Preview, no Apply without confirmation, memory bounds, proofs and Finalize packages. It also exercises WPF selection, Preview/Apply guards and OU/CSV targeting, and checks the documentation (pictures, names, the Graph scope documented against the one of the code). Earlier versions were validated on a real Active Directory, Entra Connect and Microsoft 365 tenant (reference guide, annex B); **3.3.0 was validated on a real lab** with two servers. Files written by the real 2.2.0 under Windows PowerShell 5.1 are replayed by the gate (`tests\PraLegacyFixtures.Tests.ps1`, fixtures frozen in `tests\fixtures\ps51-2.2.0`). `tools\Build-Documentation.ps1` and `tools\New-DocumentationImages.ps1`, which rebuild the HTML guides and the pictures on a workstation, need PowerShell 7.6 (and Microsoft Edge for the pictures). + +## Security and support + +- **Supported version.** Only the latest release receives fixes. A fix is a new version that replaces the package folder; watch the releases and the security advisories of this repository to be told. No support period is promised: this is a personal project, provided AS-IS. +- **Verify what you download.** The files in the ZIP are signed by their owner; the ZIP is attested and comes with a bill of materials. The checks, the thumbprint of the signing certificate and the renewal of the certificate are in [SECURITY.md](SECURITY.md); the commands are in the [reference guide, chapter 5](package/docs/PraRemoteMailbox-Guide.md#verify-what-you-downloaded). +- **Report a vulnerability** privately through the Security tab of this repository. Reports go to the maintainer only, and contributions (pull requests) are not accepted. +- **Your data.** The organisation that runs the tool is the controller of the data that the tool extracts and stores (a backup of every attribute of the users in scope with their security descriptors, the permission reports, the packages). Keep it protected and delete it once the rollback is verified: [reference guide, chapter 10](package/docs/PraRemoteMailbox-Guide.md#data-handling). ## License diff --git a/SECURITY.md b/SECURITY.md index 87b513c..2ccead0 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,15 +1,63 @@ # Security +## Supported versions + +Only the **latest release** receives fixes. A fix is published as a new version that replaces the package folder; the files of a published release never change. To be told of a new version or of a security advisory, watch this repository on GitHub (*Releases* and *Security advisories*). When a newer version is published, the notes of the replaced release start with a notice that it is not the latest. Older versions, the 2.2.x line included, receive no fix. + +No support period is promised: this is a personal project, provided AS-IS. PowerShell 7.6 LTS is the only PowerShell line that the tool runs on. + ## Reporting a vulnerability Use this repository's Security tab and Report a vulnerability to contact the maintainer privately. Do not publish credentials, personal data, customer configuration, or sensitive exploit details in a public issue. Include the affected version, expected and observed behavior, and minimal reproduction steps with sensitive values removed. If a credential has been exposed, revoke or rotate it immediately; deleting a commit or file is not sufficient. -## Release integrity +## How a report is handled + +The repository has one maintainer, who reads every report, checks whether it applies to the latest release and decides what to do. No response time and no fix date are promised. A confirmed vulnerability is fixed in a new release: the release notes say what changed, and a security advisory of this repository is published once the fix is available. Reports go to the maintainer only. + +## Contributions + +Contributions, pull requests included, are not accepted. A defect, a question or an idea is welcome as a report to the maintainer (through the Security tab when it is sensitive), and the maintainer decides what is changed. + +## Provenance and release integrity + +Obtain releases from the official Nico77600 repository only, from the *Assets* of the release (never from the *Source code* archives). + +- **Signing certificate.** Every PowerShell file of the package and the manifest `PackageIntegrity.psd1` carry the owner's timestamped Authenticode signature. The thumbprint of the certificate is `0F28E442889F17B5F4D251E8F96E7CC6E2C9C6D6`. The tool checks the signatures and every other file against the signed manifest at every start, and has no unsigned mode. +- **Attestation.** A workflow of this repository attests the published ZIP. +- **Bill of materials.** Each release from 3.3.0 carries a bill of materials (`PraRemoteMailbox-.zip.spdx.json`, SPDX 2.3) and a dependency declaration (`PraRemoteMailbox--dependencies.md`). No third-party code is bundled: PowerShell and the modules that the tool requires are declared as required, not shipped. +- **Immutable releases.** New immutable releases preserve their published assets and associated tag. Existing releases are not made immutable retroactively. Corrections are published as a new version rather than replacing a released file. -Obtain releases from the official Nico77600 repository. Verify available artifact attestations against the expected repository and verify any code signature against the expected publisher. +### Verify a release + +```powershell +# 1. The SHA-256 of the ZIP, to compare with the release notes. +Get-FileHash .\PraRemoteMailbox-.zip -Algorithm SHA256 + +# 2. The attestation of the ZIP (GitHub CLI). +gh attestation verify .\PraRemoteMailbox-.zip --repo Nico77600/PraRemoteMailbox + +# 3. The signature of every signed file, after extracting the ZIP: each line must show the thumbprint above. +Get-ChildItem .\PraRemoteMailbox- -Recurse -File -Include *.ps1, *.psm1, *.psd1 | + Where-Object { $_.DirectoryName -notlike '*\config' } | Get-AuthenticodeSignature | + Select-Object @{ n = 'File'; e = { $_.Path } }, Status, @{ n = 'Thumbprint'; e = { $_.SignerCertificate.Thumbprint } } +``` + +On a computer without the public root certificate the status can read `UnknownError` with the right thumbprint: the thumbprint is what counts, and the tool accepts that case on an isolated server with one warning. To compare a ZIP with the source of its tag byte for byte, run `tools\Compare-ReleaseSource.ps1` from a clone of the repository. A checksum alone does not authenticate a file if the checksum and the file can both be replaced. A valid signature or attestation proves integrity or provenance, not the absence of vulnerabilities. -New immutable releases preserve their published assets and associated tag. Existing releases are not made immutable retroactively. Corrections are published as a new version rather than replacing a released file. +## Signing certificate renewal + +The signing certificate ends on 13 October 2027. Its renewal follows this runbook: + +1. The renewal starts 90 days before the end date. A monthly check of the repository warns from that day and fails once the certificate has ended. +2. The new certificate has an RSA key of 3072 bits or more, or an ECDSA P-384 key. +3. Every signed file is signed again, with a timestamp. The manifest is generated again from the signed bytes and signed. The thumbprint is changed, in one change, in every place that holds it: the ten signed files that hold it (all eleven signed files are signed again), the pin file of the repository checks (with the end date), the package builder, the tests and the documents. +4. The next release is signed with the new certificate. Its notes and this page give the new thumbprint and the date of the change. +5. Earlier releases stay verifiable, because their signatures are timestamped, but they keep the old thumbprint and receive no fix. On a server without the publisher's root certificate, a release signed with the old certificate stops starting after the old certificate ends (the offline acceptance needs a certificate that is valid on the day): install the root certificate, or move to a release signed with the new one. + +What it changes for you: if you trust the publisher by its certificate (the `AllSigned` execution policy, an application control rule), add the new certificate before you install the first release signed with it, after comparing its thumbprint with the one given here and in the release notes. + +If a signing key is lost or suspected to be compromised, the maintainer stops signing with it, publishes a security advisory and a new release signed with a new certificate, and says which releases to stop using. diff --git a/package/Invoke-PraRemoteMailbox.ps1 b/package/Invoke-PraRemoteMailbox.ps1 index e455cf1..75bc21f 100644 --- a/package/Invoke-PraRemoteMailbox.ps1 +++ b/package/Invoke-PraRemoteMailbox.ps1 @@ -4,7 +4,7 @@ mailboxes (Exchange Online) when the on-premises Exchange servers are lost, and rolls back later. .DESCRIPTION - Four actions, all driven by config\PraRemoteMailbox.config.psd1: + Five actions, all driven by config\PraRemoteMailbox.config.psd1: Convert On-premises mailbox -> remote mailbox. AD attributes are rewritten (backup first), users are added to the licence group, Entra Connect synchronises, then the tool waits @@ -14,6 +14,8 @@ Finalize Last step of a Recover done on two servers: applies, on the AD server, the Finalize package produced by the cloud phase. Check Read-only Exchange Online check (mailbox provisioned / deprovisioned / retention). + Cleanup Lists what the tool left behind (finished batches, old logs, transcripts, reports, Preview folders, temporary files of the Exchange Online child); + -Mode Apply deletes it after you type the word CLEANUP. Never automatic. Cleanup.OlderThanDays sets the age. Every run starts in Preview: the tool reads, plans and shows the changes, and writes nothing. -Mode Apply performs the changes, after one confirmation (or none with -Force). A complete, @@ -24,7 +26,7 @@ servers (Phase AD, then Phase Cloud with a copy of the batch folder). .PARAMETER Action - Convert, Recover, Finalize or Check. The value is case-insensitive (convert, CONVERT); the entry script + Convert, Recover, Finalize, Check or Cleanup. The value is case-insensitive (convert, CONVERT); the entry script rewrites it to its official spelling right after the parameters are bound. .PARAMETER Mode @@ -99,8 +101,31 @@ this one run anyway: the run lists what is not covered in a warning, in the log, in the summary and in the report. It is not remembered. The check itself is turned off in the configuration file (Retention.CheckBeforeRecover = $false), not here. +.PARAMETER IgnoreProof + Recover, AD part only. Skips ONE retention proof, named by its file name or its full path, as if the file was not there. Use it when a proof in the Inbox, Outbox or batch folder + blocks the Recover (damaged, left by someone else, made for another run) and you do not want to delete it. Only that file is left out; the other proofs and the live check of + Exchange Online are not affected. It is recorded in the log, the summary, the report and the run settings. It is much narrower than -AcceptRetentionRisk, which drops the check for every mailbox. + +.PARAMETER ExpectedFingerprint + With a transfer package (-Batch .zip). The fingerprint that the other server printed for the package: 20 hexadecimal characters in groups of four (ABCD-EF01-2345-6789-ABCD; any case, the + dashes are optional). When the package that is read has another fingerprint, nothing is imported. Without it the tool only shows the fingerprint of the package it reads. + +.PARAMETER AuthPassphrase + Only with Transfer.Authenticate or Transfer.RequireAuthentication in the configuration, and no Transfer.KeyFile: the passphrase of the shared secret, as a SecureString, for an unattended run. + At a console the tool asks for it (nothing is shown, nothing is stored). It is never written to a log, a report or a file. Both servers must use the same passphrase. + Example: $secret = Read-Host -AsSecureString; .\Invoke-PraRemoteMailbox.ps1 -Action Finalize -Batch .\package.zip -AuthPassphrase $secret + +.PARAMETER ProtectPassphrase + Only with Storage.Protect = Passphrase and no Storage.KeyFile: the passphrase that protects the backups, proofs, phase data and transfer packages (and opens the ones already protected), as a SecureString, for an unattended run. + At a console the tool asks for it (twice when files are written; nothing is shown, nothing is stored). It is never written to a log, a report or a file. Losing the passphrase means losing the files it protects. + +.PARAMETER NewAuthKeyFile + Creates a key file at this path and ends: 32 random bytes as base64 text, in a new file that only this account, SYSTEM and Administrators can read. It never overwrites a file. The file is the key of the shared secret + (Transfer.KeyFile) or the key of the protection of the files at rest (Storage.KeyFile). Copy the file to the other server by a channel you trust and give it the same rights there. No -Action is needed. + Example: .\Invoke-PraRemoteMailbox.ps1 -NewAuthKeyFile D:\PRA\keys\pra.key + .PARAMETER Force - Apply without the confirmation prompt (scheduled or unattended runs). Never skips a safety check. + Apply without the confirmation prompt (scheduled or unattended runs). Never skips a safety check. The run records that the confirmation was skipped. The single confirmation of an Apply is also skipped when -Confirm is given explicitly, with either value: -Confirm:$false behaves like -Force for this prompt (and for the per-write prompts, which are then off), whereas a plain -Confirm replaces the single confirmation by the PowerShell confirmation of every write. @@ -114,7 +139,7 @@ log and report paths), for a script or an orchestrator. Without it, nothing is written to the pipeline. .PARAMETER Gui - Opens the WPF window (native Fluent theme). Every operation runs in its own PowerShell 7.5+ process (pwsh.exe). + Opens the WPF window (native Fluent theme). Every operation runs in its own PowerShell 7.6 process (pwsh.exe). .EXAMPLE pwsh -STA -File .\Invoke-PraRemoteMailbox.ps1 -Gui @@ -155,8 +180,8 @@ .NOTES Author : Nicolas Fabert - Version : 3.2.0 - Requires : PowerShell 7.5 or later (pwsh.exe; Windows PowerShell 5.1 is refused), RSAT ActiveDirectory, + Version : 3.3.0 + Requires : PowerShell 7.6 or later (pwsh.exe; Windows PowerShell 5.1 is refused), RSAT ActiveDirectory, ExchangeOnlineManagement 3.10.1+, Microsoft.Graph.Authentication and Microsoft.Graph.Users 2.41.1+ in one same version (cloud part), ADSync (sync; through the Windows PowerShell compatibility layer when local). Exit codes : 0 = done, 1 = failed, 2 = done but a next step is required (Pending objects: a phase AD that ends with a package for @@ -172,10 +197,10 @@ The tool changes production objects in Active Directory and creates mailboxes in Exchange Online: run the preview, review the plan, keep the backups and test in a lab before using it in a real disaster. #> -#Requires -Version 7.5 +#Requires -Version 7.6 [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High', DefaultParameterSetName = 'Run')] param( - [Parameter(ParameterSetName = 'Run')][ValidateSet('Convert','Recover','Finalize','Check')][string]$Action, + [Parameter(ParameterSetName = 'Run')][ValidateSet('Convert','Recover','Finalize','Check','Cleanup')][string]$Action, [Parameter(ParameterSetName = 'Run')][ValidateSet('Preview','Apply')][string]$Mode = 'Preview', [Parameter(ParameterSetName = 'Run')][ValidateSet('Both','AD','Cloud')][string]$Phase, [Parameter(ParameterSetName = 'Run')][string]$Batch, @@ -190,6 +215,11 @@ param( [Parameter(ParameterSetName = 'Run')][string]$BaseConfigPath, [Parameter(ParameterSetName = 'Run')][switch]$ForceAdReplication, [Parameter(ParameterSetName = 'Run')][switch]$AcceptRetentionRisk, + [Parameter(ParameterSetName = 'Run')][string]$IgnoreProof, + [Parameter(ParameterSetName = 'Run')][string]$ExpectedFingerprint, + [Parameter(ParameterSetName = 'Run')][securestring]$AuthPassphrase, + [Parameter(ParameterSetName = 'Run')][securestring]$ProtectPassphrase, + [Parameter(ParameterSetName = 'Run')][string]$NewAuthKeyFile, [Parameter(ParameterSetName = 'Run')][switch]$Force, [Parameter(ParameterSetName = 'Run')][switch]$Once, [Parameter(ParameterSetName = 'Run')][switch]$PassThru, @@ -203,18 +233,150 @@ $ProgressPreference = 'SilentlyContinue' # It authenticates module\Test-PackageIntegrity.ps1 before running it; there is no unsigned or bypass path. & { param([Parameter(Mandatory)][string]$PackageRoot) + # A reparse point is judged by its tag, not by the attribute. Accepted: the cloud files of OneDrive, data deduplication and WOF (they do not redirect); refused: every tag that + # redirects (name-surrogate bit 0x20000000: symbolic links, junctions, mount points), every unknown tag and a tag that cannot be read. The tag is read with FindFirstFileW + # (dwReserved0), declared with Reflection.Emit because this runs before the engine exists; a cloud placeholder is not downloaded. + function Get-PathReparseTag { + param([Parameter(Mandatory)][string]$Path) + $api = [AppDomain]::CurrentDomain.GetData('PRA.FindFileApi') + if ($null -eq $api) { + $module = [Reflection.Emit.AssemblyBuilder]::DefineDynamicAssembly([Reflection.AssemblyName]::new('PraReparseTag'), [Reflection.Emit.AssemblyBuilderAccess]::Run).DefineDynamicModule('PraReparseTag') + $native = $module.DefineType('Native', 'Public, Abstract, Sealed') + foreach ($call in @(@('FindFirstFileW', [IntPtr], @([string], [IntPtr])), @('FindClose', [bool], @([IntPtr])))) { + $method = $native.DefinePInvokeMethod($call[0], 'kernel32.dll', $call[0], 'Public, Static, PinvokeImpl', 'Standard', $call[1], [type[]]$call[2], 'Winapi', 'Unicode') + $method.SetImplementationFlags('PreserveSig') + } + $api = $native.CreateType() + [AppDomain]::CurrentDomain.SetData('PRA.FindFileApi', $api) + } + $full = [IO.Path]::GetFullPath($Path) + $full = if ($full.StartsWith('\\?\', [StringComparison]::Ordinal)) { $full } elseif ($full.StartsWith('\\', [StringComparison]::Ordinal)) { '\\?\UNC\' + $full.Substring(2) } else { '\\?\' + $full } + $data = [Runtime.InteropServices.Marshal]::AllocHGlobal(592) + try { + $handle = $api::FindFirstFileW($full, $data) + if ($handle -eq [IntPtr]::new(-1)) { throw "the reparse tag cannot be read (Windows error $([Runtime.InteropServices.Marshal]::GetLastSystemError()))" } + [void]$api::FindClose($handle) + if (([Runtime.InteropServices.Marshal]::ReadInt32($data, 0) -band 0x400) -eq 0) { return $null } + return [uint32]([long][Runtime.InteropServices.Marshal]::ReadInt32($data, 36) -band 0xFFFFFFFFL) + } + finally { [Runtime.InteropServices.Marshal]::FreeHGlobal($data) } + } + function Get-RefusedReparseTag { + param([Parameter(Mandatory)]$Item) + if (-not ($Item.Attributes -band [IO.FileAttributes]::ReparsePoint)) { return $null } + try { $tag = [long](Get-PathReparseTag $Item.FullName) } catch { return 'UNREADABLE' } + if (-not ($tag -band 0x20000000L) -and ((($tag -band 0xFFFF0FFFL) -eq 0x9000001AL) -or $tag -eq 0x80000013L -or $tag -eq 0x80000017L)) { return $null } + return $tag.ToString('X8') + } + # The publisher is accepted on the pinned thumbprint when only the certificate chain of the signature cannot be built here (an isolated server: no root, no revocation list). The + # signature value, the signed digest of the text, the signer and the timestamp token are checked without the chain; the chain, evaluated at the time of the timestamp, may only report an + # untrusted root, a partial chain or an unknown revocation status. The timestamp token must verify, cover the signature value and lie within the validity of the signer certificate, which must also be valid now. A changed + # text, a changed signature value, another signer, text outside the signature block, a missing or invalid timestamp or any other chain error is refused. + function Test-ChainOnlySignature { + param([Parameter(Mandatory)]$Signature, [Parameter(Mandatory)][string]$Path, [Parameter(Mandatory)][string]$Thumbprint) + $status = [string]$Signature.Status + if (-not [string]::Equals($status, 'UnknownError', [StringComparison]::Ordinal)) { return $false } + if ($null -eq $Signature.SignerCertificate -or -not [string]::Equals([string]$Signature.SignerCertificate.Thumbprint, $Thumbprint, [StringComparison]::Ordinal) -or $null -eq $Signature.TimeStamperCertificate) { return $false } + $chain = $null + try { + $source = [IO.File]::OpenRead($Path); try { $copy = New-Object IO.MemoryStream; $source.CopyTo($copy); $bytes = $copy.ToArray() } finally { $source.Dispose() } + if ($bytes.Length -lt 3 -or $bytes[0] -ne 0xEF -or $bytes[1] -ne 0xBB -or $bytes[2] -ne 0xBF) { return $false } + $text = [Text.Encoding]::UTF8.GetString($bytes) + $marker = '# SIG # Begin signature block' + $endMarker = '# SIG # End signature block' + $begin = $text.LastIndexOf($marker, [StringComparison]::Ordinal) + $end = $text.LastIndexOf($endMarker, [StringComparison]::Ordinal) + if ($begin -lt 2 -or $end -lt $begin) { return $false } + $tail = $text.Substring($end) + if (-not ([string]::Equals($tail, $endMarker, [StringComparison]::Ordinal) -or [string]::Equals($tail, $endMarker + "`r`n", [StringComparison]::Ordinal))) { return $false } + $head = $text.Substring(0, $begin) + $lineEnd = if ($head.EndsWith("`r`n", [StringComparison]::Ordinal)) { 2 } elseif ($head.EndsWith("`n", [StringComparison]::Ordinal)) { 1 } else { return $false } + $digest = [Security.Cryptography.SHA256]::HashData([Text.Encoding]::Unicode.GetBytes($head.Substring(0, $head.Length - $lineEnd))) + $lines = [string[]]($text.Substring($begin + $marker.Length, $end - $begin - $marker.Length) -split "`r?`n") + if ($lines.Count -lt 3 -or $lines[0].Length -ne 0 -or $lines[$lines.Count - 1].Length -ne 0) { return $false } + $base64 = [Text.StringBuilder]::new() + for ($i = 1; $i -lt $lines.Count - 1; $i++) { + if (-not $lines[$i].StartsWith('# ', [StringComparison]::Ordinal) -or -not [regex]::IsMatch($lines[$i].Substring(2), '^[A-Za-z0-9+/=]+$')) { return $false } + [void]$base64.Append($lines[$i].Substring(2)) + } + $cms = [Security.Cryptography.Pkcs.SignedCms]::new() + $cms.Decode([Convert]::FromBase64String($base64.ToString())) + $cms.CheckSignature($true) + if ($cms.SignerInfos.Count -ne 1 -or -not [string]::Equals($cms.ContentInfo.ContentType.Value, '1.3.6.1.4.1.311.2.1.4', [StringComparison]::Ordinal)) { return $false } + $signer = $cms.SignerInfos[0] + if (-not [string]::Equals($signer.DigestAlgorithm.Value, '2.16.840.1.101.3.4.2.1', [StringComparison]::Ordinal) -or -not [string]::Equals([string]$signer.Certificate.Thumbprint, $Thumbprint, [StringComparison]::Ordinal)) { return $false } + $content = $cms.ContentInfo.Content + if ($content.Length -lt 34 -or $content[$content.Length - 34] -ne 0x04 -or $content[$content.Length - 33] -ne 0x20) { return $false } + if (-not [Security.Cryptography.CryptographicOperations]::FixedTimeEquals([byte[]]$digest, [byte[]]$content[($content.Length - 32)..($content.Length - 1)])) { return $false } + $signatureValue = [byte[]]$signer.GetSignature() + $stamp = $null + foreach ($attribute in $signer.UnsignedAttributes) { + if ($null -ne $stamp -or -not [string]::Equals($attribute.Oid.Value, '1.3.6.1.4.1.311.3.3.1', [StringComparison]::Ordinal)) { continue } + foreach ($value in $attribute.Values) { + $token = [Security.Cryptography.Pkcs.SignedCms]::new() + $token.Decode([byte[]]$value.RawData) + $token.CheckSignature($true) + if (-not [string]::Equals($token.ContentInfo.ContentType.Value, '1.2.840.113549.1.9.16.1.4', [StringComparison]::Ordinal)) { return $false } + $info = [System.Formats.Asn1.AsnReader]::new([byte[]]$token.ContentInfo.Content, [System.Formats.Asn1.AsnEncodingRules]::DER).ReadSequence() + [void]$info.ReadInteger() + [void]$info.ReadObjectIdentifier() + $imprint = $info.ReadSequence() + $imprintAlgorithm = $imprint.ReadSequence().ReadObjectIdentifier() + $imprintHash = [byte[]]$imprint.ReadOctetString() + [void]$info.ReadInteger() + $genTime = $info.ReadGeneralizedTime() + if ([string]::Equals($imprintAlgorithm, '2.16.840.1.101.3.4.2.1', [StringComparison]::Ordinal) -and [Security.Cryptography.CryptographicOperations]::FixedTimeEquals($imprintHash, [byte[]][Security.Cryptography.SHA256]::HashData($signatureValue))) { $stamp = $genTime.UtcDateTime; break } + } + } + if ($null -eq $stamp) { + foreach ($counter in $signer.CounterSignerInfos) { + $counter.CheckSignature($true) + $counterHash = $null + if ([string]::Equals($counter.DigestAlgorithm.Value, '2.16.840.1.101.3.4.2.1', [StringComparison]::Ordinal)) { $counterHash = [byte[]][Security.Cryptography.SHA256]::HashData($signatureValue) } + elseif ([string]::Equals($counter.DigestAlgorithm.Value, '1.3.14.3.2.26', [StringComparison]::Ordinal)) { $counterHash = [byte[]][Security.Cryptography.SHA1]::HashData($signatureValue) } + if ($null -eq $counterHash) { continue } + $counterDigest = $null + $counterTime = $null + foreach ($attribute in $counter.SignedAttributes) { + if ([string]::Equals($attribute.Oid.Value, '1.2.840.113549.1.9.4', [StringComparison]::Ordinal)) { $counterDigest = [byte[]][System.Formats.Asn1.AsnReader]::new([byte[]]$attribute.Values[0].RawData, [System.Formats.Asn1.AsnEncodingRules]::DER).ReadOctetString() } + elseif ([string]::Equals($attribute.Oid.Value, '1.2.840.113549.1.9.5', [StringComparison]::Ordinal)) { $counterTime = [Security.Cryptography.Pkcs.Pkcs9SigningTime]::new([byte[]]$attribute.Values[0].RawData).SigningTime.ToUniversalTime() } + } + if ($null -ne $counterDigest -and $null -ne $counterTime -and [Security.Cryptography.CryptographicOperations]::FixedTimeEquals($counterDigest, $counterHash)) { $stamp = $counterTime; break } + } + } + if ($null -eq $stamp) { return $false } + $stamp = [DateTime]::SpecifyKind([DateTime]$stamp, [DateTimeKind]::Utc) + if ($stamp -lt $signer.Certificate.NotBefore.ToUniversalTime() -or $stamp -gt $signer.Certificate.NotAfter.ToUniversalTime()) { return $false } + if ([DateTime]::UtcNow -lt $signer.Certificate.NotBefore.ToUniversalTime() -or [DateTime]::UtcNow -gt $signer.Certificate.NotAfter.ToUniversalTime()) { return $false } + $chain = [Security.Cryptography.X509Certificates.X509Chain]::new() + $chain.ChainPolicy.RevocationMode = [Security.Cryptography.X509Certificates.X509RevocationMode]::Offline + $chain.ChainPolicy.VerificationTime = $stamp + $chain.ChainPolicy.ExtraStore.AddRange($cms.Certificates) + [void]$chain.Build($signer.Certificate) + $allowed = [Security.Cryptography.X509Certificates.X509ChainStatusFlags]::UntrustedRoot -bor [Security.Cryptography.X509Certificates.X509ChainStatusFlags]::PartialChain -bor [Security.Cryptography.X509Certificates.X509ChainStatusFlags]::OfflineRevocation -bor [Security.Cryptography.X509Certificates.X509ChainStatusFlags]::RevocationStatusUnknown + foreach ($element in $chain.ChainStatus) { if (([int]$element.Status -band (-bnot [int]$allowed)) -ne 0) { return $false } } + return $true + } + catch { return $false } + finally { if ($null -ne $chain) { $chain.Dispose() } } + } $verifier = [IO.Path]::GetFullPath([IO.Path]::Combine($PackageRoot, 'module', 'Test-PackageIntegrity.ps1')) $cursor = $verifier while ($cursor) { $item = Microsoft.PowerShell.Management\Get-Item -LiteralPath $cursor -Force -ErrorAction Stop - if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw "Package integrity: reparse point: $cursor" } + $refused = Get-RefusedReparseTag $item + if ($refused) { throw "Package integrity: reparse point that is not accepted (tag 0x$refused): $cursor" } $cursor = [IO.Path]::GetDirectoryName($cursor) } $signature = Microsoft.PowerShell.Security\Get-AuthenticodeSignature -LiteralPath $verifier -ErrorAction Stop if (-not [string]::Equals([string]$signature.Status, 'Valid', [StringComparison]::Ordinal) -or $null -eq $signature.SignerCertificate -or -not [string]::Equals([string]$signature.SignerCertificate.Thumbprint, '0F28E442889F17B5F4D251E8F96E7CC6E2C9C6D6', [StringComparison]::Ordinal) -or $null -eq $signature.TimeStamperCertificate) { - throw 'Package integrity: verifier must have the trusted, timestamped owner signature.' + if (-not (Test-ChainOnlySignature -Signature $signature -Path $verifier -Thumbprint '0F28E442889F17B5F4D251E8F96E7CC6E2C9C6D6')) { throw 'Package integrity: verifier must have the trusted, timestamped owner signature.' } + if ($null -eq [AppDomain]::CurrentDomain.GetData('PRA.ChainOnlyWarned')) { + [AppDomain]::CurrentDomain.SetData('PRA.ChainOnlyWarned', $true) + Microsoft.PowerShell.Utility\Write-Warning 'Package integrity: the certificate chain of the publisher cannot be built on this computer (no trusted root certificate or no revocation list, as on an isolated server). The signature is valid, the publisher is the expected one, the file is intact and the signature is timestamped, so the package starts. Install the publisher root certificate on this computer to remove this warning.' + } } & $verifier -Root $PackageRoot } $PSScriptRoot @@ -241,8 +403,17 @@ foreach ($parameterInfo in $MyInvocation.MyCommand.Parameters.Values) { } # -Action is not a Mandatory parameter on purpose: PowerShell would ask for it with a prompt, and a scheduled or unattended run (no console, no keyboard) would wait for # an answer forever. A missing -Action stops at once, with the usage. (A new PowerShell process started with -NonInteractive would stop too; this does not depend on it.) +if ($NewAuthKeyFile) { + try { + Import-Module (Join-Path $PSScriptRoot 'PraRemoteMailbox.psd1') -Force -ErrorAction Stop + $created = New-PraAuthKeyFile -Path $NewAuthKeyFile + Write-Host ('Key file created: {0}. Set Transfer.KeyFile (shared secret) or Storage.KeyFile (protection of the files at rest, Storage.Protect = Passphrase) to its path in the configuration file. Copy it to the other server by a channel you trust and give it the same rights there; keep another copy in a safe place: losing a key file that protects files means losing those files.' -f $created) + exit 0 + } + catch { Write-Error ('The key file was not created: {0}' -f $_.Exception.Message) -ErrorAction Continue; exit 1 } +} if (-not $Action -and -not $Gui) { - Write-Error -ErrorAction Continue -Message ('-Action is missing: nothing was done. Give the task: -Action Convert, Recover, Finalize or Check (Preview is the default mode). Example: .\Invoke-PraRemoteMailbox.ps1 -Action Convert -Mode Preview. For the window: -Gui. Help: Get-Help .\Invoke-PraRemoteMailbox.ps1 -Full.') + Write-Error -ErrorAction Continue -Message ('-Action is missing: nothing was done. Give the task: -Action Convert, Recover, Finalize, Check or Cleanup (Preview is the default mode). Example: .\Invoke-PraRemoteMailbox.ps1 -Action Convert -Mode Preview. For the window: -Gui. Help: Get-Help .\Invoke-PraRemoteMailbox.ps1 -Full.') exit 1 } if ($Gui) { @@ -295,6 +466,16 @@ $context = @{ $context.Approval = New-PraApprovalCallback $caller $context # Lets the modules write a command line of this run's own style (-ConfigPath kept) in a message; defined here because Get-PraCommandLine is a function of this script. $context.CommandLineFor = { param([string]$ActionName, [string]$PhaseName, [string]$BatchId) Get-PraCommandLine -ActionName $ActionName -PhaseName $PhaseName -BatchId $BatchId } +$context.RerunCommandFor = { + param([string]$ActionName, [string]$PhaseName, [string]$BatchId) + # The AD phase of a Recover is run again with the Convert batch that it read, not with the Recover batch that it made; the cloud phase takes the batch of its own command. + $adPart = (Test-PraOrdinalIgnoreCaseEqual $ActionName 'Recover') -and (-not $PhaseName -or (Test-PraOrdinalIn $PhaseName @('AD', 'Both') -IgnoreCase)) + $sourceBatch = [string](Get-PraValue (Get-PraValue (Get-PraValue $context 'Source' $null) 'Data' $null) 'BatchId' '') + if ($adPart -and $sourceBatch) { $BatchId = Get-PraShortId $sourceBatch } + $again = Get-PraCommandLine -ActionName $ActionName -PhaseName $PhaseName -ModeName $effectiveMode -BatchId $BatchId -KeepFilters + if ($AcceptRetentionRisk -and $adPart) { $again += ' -AcceptRetentionRisk' } + return $again +} $context.GroupCommandLineFor = { param([string]$GroupName) Get-PraCommandLine -ActionName $Action -PhaseName $effectivePhase -ModeName $effectiveMode -KeepFilters -Only Group -GroupName $GroupName } # ================================================================================================= @@ -316,9 +497,35 @@ function ConvertTo-PraLiteral { return "'" + $escaped + "'" } +function Get-PraSelectionIdentity { + <# The -Identity of this run in a form that the next phase finds in the batch: as typed when the batch holds exactly one object that it names (account name, UPN or object GUID), else the account name of the one object of the batch or of the run. '' when the run has no -Identity. #> + if (-not $Identity -or $Identity -match '[\x00-\x1f\x7f]') { return '' } + $records = @(Get-PraList (Get-PraValue (Get-PraValue $context 'Source' $null) 'Data' $null) 'Records') + $named = @($records | Where-Object { (Test-PraOrdinalIgnoreCaseEqual ([string](Get-PraValue $_ 'SamAccountName' '')) $Identity) -or (Test-PraOrdinalIgnoreCaseEqual ([string](Get-PraValue $_ 'UserPrincipalName' '')) $Identity) -or (Test-PraOrdinalIgnoreCaseEqual ([string](Get-PraValue $_ 'ObjectGuid' '')) $Identity) }) + if ($named.Count -eq 1) { return [string]$Identity } + if ($records.Count -eq 1 -and [string](Get-PraValue $records[0] 'SamAccountName' '')) { return [string]$records[0].SamAccountName } + $rows = @(Get-PraList $context 'Rows' | Where-Object { [string](Get-PraValue $_ 'SamAccountName' '') }) + if ($rows.Count -eq 1) { return [string]$rows[0].SamAccountName } + return '' +} + +function Test-PraSelectionNarrows { + <# True when the objects named by this run are a part of what the next phase reads: a Recover and the cloud phase of a Convert read a batch that holds more, and a batch of more than one object holds more than the one object named. A Convert of one object names the whole of its batch. #> + if ((Test-PraOrdinalIgnoreCaseEqual $Action 'Recover') -or ((Test-PraOrdinalIgnoreCaseEqual $Action 'Convert') -and (Test-PraOrdinalIgnoreCaseEqual $effectivePhase 'Cloud'))) { return $true } + return (@(Get-PraList (Get-PraValue (Get-PraValue $context 'Source' $null) 'Data' $null) 'Records').Count -gt 1) +} + +function Get-PraSelectionScope { + <# The -Scope of this run when the run filtered the objects of a batch by it (a Recover, the cloud phase of a Convert, a Check of a batch), so that the next phase filters the same way. '' otherwise: the AD phase of a Convert chooses its objects, and finishing a batch ignores the scope. #> + if (-not $Scope -or (Test-PraOrdinalIgnoreCaseEqual $Scope 'All')) { return '' } + $filters = (Test-PraOrdinalIgnoreCaseEqual $Action 'Recover') -or ((Test-PraOrdinalIgnoreCaseEqual $Action 'Convert') -and (Test-PraOrdinalIgnoreCaseEqual $effectivePhase 'Cloud')) -or ((Test-PraOrdinalIgnoreCaseEqual $Action 'Check') -and $Batch) + if ($filters) { return [string]$Scope } + return '' +} + function Get-PraCommandLine { <# Command line suggested in "Next step", with the options of this run that still apply. Every free-text value is quoted as data. #> - param([string]$ActionName, [string]$ModeName = 'Apply', [string]$PhaseName = '', [string]$BatchId = '', [switch]$KeepFilters, [switch]$OtherServer, + param([string]$ActionName, [string]$ModeName = 'Apply', [string]$PhaseName = '', [string]$BatchId = '', [switch]$KeepFilters, [switch]$KeepSelection, [switch]$OtherServer, [ValidateSet('', 'Identity', 'SearchBase', 'CsvPath', 'Group', 'None')][string]$Only = '', [string]$GroupName = '', [string]$CsvOverride = '') $parts = @('.\Invoke-PraRemoteMailbox.ps1', "-Action $ActionName") # With -Only, the one object selector kept (-Identity, -SearchBase, -CsvPath or -Group; None keeps no selector): the others are left out. @@ -326,6 +533,12 @@ function Get-PraCommandLine { if ($PhaseName) { $parts += "-Phase $PhaseName" } if ((Test-PraOrdinalIgnoreCaseEqual $ModeName 'Apply')) { $parts += '-Mode Apply' } if ($BatchId) { $parts += $(if ($BatchId -match '^[0-9a-fA-F]+\z') { "-Batch $BatchId" } else { '-Batch ' + (ConvertTo-PraLiteral $BatchId) }) } + # -KeepSelection: the objects of this run, for the next phase or the other server (the batch of a subset names all its objects): the account and the scope, as that phase reads them. + if ($KeepSelection -and -not $KeepFilters) { + $selected = Get-PraSelectionIdentity + if ($selected) { $parts += '-Identity ' + (ConvertTo-PraLiteral $selected) } + else { $selectedScope = Get-PraSelectionScope; if ($selectedScope) { $parts += "-Scope $selectedScope" } } + } if ($KeepFilters) { if ($Identity -and (& $keepSelector 'Identity')) { $parts += '-Identity ' + (ConvertTo-PraLiteral $Identity) } if ((-not (Test-PraOrdinalIgnoreCaseEqual $Scope 'All'))) { $parts += "-Scope $Scope" } @@ -337,6 +550,8 @@ function Get-PraCommandLine { if ($CsvPath -and -not $CsvOverride -and (& $keepSelector 'CsvPath')) { $parts += '-CsvPath ' + (ConvertTo-PraLiteral $(if ($OtherServer) { [IO.Path]::GetFileName($CsvPath) } else { $CsvPath })) } if ((Test-PraOrdinalIgnoreCaseEqual $ActionName 'Check') -and -not (Test-PraOrdinalIgnoreCaseEqual $Expect 'Provisioned')) { $parts += "-Expect $Expect" } if ($Once) { $parts += '-Once' } + if ($IgnoreProof -and -not $OtherServer -and (Test-PraOrdinalIgnoreCaseEqual $ActionName 'Recover')) { $parts += '-IgnoreProof ' + (ConvertTo-PraLiteral $IgnoreProof) } + if ($ExpectedFingerprint -and -not $OtherServer -and $BatchId.EndsWith('.zip', [StringComparison]::OrdinalIgnoreCase)) { $parts += '-ExpectedFingerprint ' + (ConvertTo-PraLiteral $ExpectedFingerprint) } } # A file made by this run for the objects that are still to convert replaces the CSV of the run. if ($CsvOverride) { $parts += '-CsvPath ' + (ConvertTo-PraLiteral $CsvOverride) } @@ -408,7 +623,7 @@ function Get-PraFallbackNext { if ((Test-PraOrdinalIgnoreCaseEqual $Action 'Convert') -and (Test-PraOrdinalIgnoreCaseEqual $effectivePhase 'AD')) { return @(('{0} Fix the problem named above, then finish the batch (Entra Connect sync and transfer package; AD is not changed again):' -f $kept), (Get-PraCommandLine -ActionName 'Convert' -PhaseName 'AD' -BatchId $batchId)) } - return @(('{0} Fix the problem named above, then run the Exchange Online part:' -f $kept), (Get-PraCommandLine -ActionName $Action -PhaseName 'Cloud' -BatchId $batchId)) + return @(('{0} Fix the problem named above, then run the Exchange Online part:' -f $kept), (Get-PraCommandLine -ActionName $Action -PhaseName 'Cloud' -BatchId $batchId -KeepSelection)) } $mayBe = @(Get-PraList $context 'MayBeChanged') if (($written -gt 0 -or $mayBe.Count) -and $batchId -and (Test-PraOrdinalIgnoreCaseEqual $Action 'Convert')) { @@ -449,14 +664,7 @@ function Get-PraJsonHeader { #> param([Parameter(Mandatory)][string]$Path, [Parameter(Mandatory)][string[]]$Name) $head = '' - try { - $stream = [IO.File]::Open($Path, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::ReadWrite) - try { - $buffer = New-Object 'byte[]' 8192 - $count = $stream.Read($buffer, 0, $buffer.Length) - $head = [Text.Encoding]::UTF8.GetString($buffer, 0, $count).TrimStart([char]0xFEFF) - } finally { $stream.Dispose() } - } catch { $head = '' } + try { $head = Read-PraFileHead -Path $Path } catch { $head = '' } $values = New-Object 'Collections.Generic.Dictionary[string,string]' ([StringComparer]::Ordinal) $open = [regex]::Match($head, '\A\s*\{') if ($open.Success) { @@ -473,7 +681,7 @@ function Get-PraJsonHeader { } $header = [ordered]@{} foreach ($field in $Name) { - if (-not $values.ContainsKey($field)) { return ([IO.File]::ReadAllText($Path) | ConvertFrom-PraJson) } + if (-not $values.ContainsKey($field)) { return (Read-PraFileText -Path $Path | ConvertFrom-PraJson) } $header[$field] = $values[$field] } return [pscustomobject]$header @@ -520,9 +728,9 @@ function Get-PraBatchFile { $found = New-Object 'Collections.Generic.List[string]' foreach ($folder in $folders) { foreach ($file in @(Get-ChildItem -LiteralPath $folder.FullName -File -Filter '*.json' -ErrorAction Stop | Where-Object { -not (Test-PraBatchSideFile $_.Name) })) { - try { $operation = [string](Get-PraJsonHeader $file.FullName @('Operation')).Operation } catch { continue } + try { $operation = [string](Get-PraJsonHeader $file.FullName @('Operation')).Operation } catch { if (([string]$_.FullyQualifiedErrorId).StartsWith('PraProtected', [StringComparison]::Ordinal)) { throw }; continue } # In a Finalize package only the manifest counts (the other JSON files are copies of the source batches). - if ((Test-PraOrdinalIn $operation $Operations) -and ($folder.Name -match '^Batch-' -or (Test-PraOrdinalEqual $operation 'RecoverFinalize'))) { $found.Add($file.FullName) } + if ((Test-PraOrdinalIn $operation $Operations) -and (($folder.Name -match '^Batch-' -and -not (Test-PraOrdinalEqual $operation 'RecoverFinalize')) -or ((Test-PraOrdinalEqual $operation 'RecoverFinalize') -and $folder.Name -match '^Finalize-'))) { $found.Add($file.FullName) } } } # The same batch folder copied twice (identical content) is not an ambiguity. @@ -637,22 +845,25 @@ function Save-PraFinalizePackage { SourceBackupFile = [IO.Path]::GetFileName($context.Source.Path); SourceBackupHash = $context.Source.Hash StateFile = [IO.Path]::GetFileName($proof.Path); StateHash = $proof.Hash; Items = $items } - Write-PraImmutableFile $path ($manifest | ConvertTo-Json -Depth 20) + $runIdentity = Get-PraRunIdentity -Context $context + foreach ($identityKey in @($runIdentity.Keys)) { $manifest[[string]$identityKey] = [string]$runIdentity[$identityKey] } + Write-PraImmutableFile $path ($manifest | ConvertTo-Json -Depth 20) -Protect Write-PraImmutableFile ($path + '.sha256') (Get-PraHash $path) $context.StateFiles.Add($path) foreach ($row in $Rows) { $row.RestoreDeferred = $true; $row.FinalStatus = 'Pending'; $row.Detail += ' | Finalize required on the AD server' } + try { Write-PraVerifiedMarker -BackupFolder ([string]$context.BackupFolder) -FolderPath $directory -Origin 'Local' } catch { Write-PraLog -Context $context -Level Detail -Message ('The marker of a verified folder could not be written: ' + $_.Exception.Message) } $short = Get-PraShortId $packageId $context.BatchId = $short Write-PraItem -Context $context -Status Ok -Icon Batch -Text ("Finalize package {0} written: {1}" -f $short, $directory) Publish-PraTransferPackage -Kind 'Finalize' -BatchId $packageId -Folders @($directory) -NextAction 'Finalize' ` - -FallbackSteps @("Copy the folder $directory to the Backups folder of the AD server, then run there:", (Get-PraCommandLine -ActionName 'Finalize' -BatchId $short -OtherServer)) + -FallbackSteps @("Copy the folder $directory to the Backups folder of the AD server, then run there:", (Get-PraCommandLine -ActionName 'Finalize' -BatchId $short -KeepSelection -OtherServer)) } function Get-PraFinalizeInput { <# Reads and checks a Finalize package; returns the objects it authorises to restore. #> $path = Get-PraBatchFile -Value $Batch -Operations @('RecoverFinalize') $context.CurrentOperation = 'Read-FinalizePackage' - $manifest = Get-Content -LiteralPath $path -Raw -Encoding UTF8 -ErrorAction Stop | ConvertFrom-PraJson + $manifest = Read-PraFileText -Path $path | ConvertFrom-PraJson if ((Get-PraValue $manifest 'SchemaVersion' 0) -ne 2 -or -not (Test-PraOrdinalEqual $manifest.Operation 'RecoverFinalize') -or -not (Test-PraOrdinalIgnoreCaseEqual $manifest.Environment $context.Config.Environment)) { throw 'Finalize package of another version or Environment: nothing restored.' } if (-not (Test-PraOrdinalIgnoreCaseEqual (Get-Content -LiteralPath ($path + '.sha256') -Raw -ErrorAction Stop).Trim() (Get-PraHash $path))) { throw 'Finalize package: SHA-256 mismatch.' } foreach ($property in @('SourceBackupFile','StateFile')) { @@ -663,6 +874,7 @@ function Get-PraFinalizeInput { if ($context.AllowMutation) { $context.PhaseWriteFolder = Split-Path $path -Parent } $context.Proof = Import-PraProof $context (Join-Path (Split-Path $path -Parent) $manifest.StateFile) $context.Source 'Recover' if (-not (Test-PraOrdinalIgnoreCaseEqual $context.Source.Hash $manifest.SourceBackupHash) -or -not (Test-PraOrdinalIgnoreCaseEqual $context.Proof.Hash $manifest.StateHash)) { throw 'Finalize package: manifest and proofs do not match.' } + Test-PraFinalizeOrigin -ManifestPath $path $records = @(Select-PraSourceRecord $context.Source); $seen = @{} $items = @($manifest.Items) if (-not $items.Count) { throw 'Finalize package is empty.' } @@ -696,6 +908,234 @@ function Format-PraByteSize { return ('{0} bytes' -f $Bytes) } +function Test-PraRunCanPrompt { + <# True when a person can type an answer in this run: no -Force (unless -IgnoreForce), a host with a user, an input that is not redirected, no -NonInteractive on the command line of the process. #> + param([switch]$IgnoreForce) + if ($Force -and -not $IgnoreForce) { return $false } + $state = Get-PraRunHostState + foreach ($argument in $state.CommandLine) { if ($argument -match '(?i)\A(--?|/|[–—])noni') { return $false } } + return ([bool]$state.UserInteractive -and -not [bool]$state.InputRedirected) +} + +function Test-PraAuthEnabled { + <# True when the shared secret is on: Transfer.Authenticate, or Transfer.RequireAuthentication (which implies it). #> + return ([bool]$context.Config.Transfer.Authenticate -or [bool]$context.Config.Transfer.RequireAuthentication) +} + +function Get-PraAuthKey { + <# + .SYNOPSIS + The key of the shared secret for this run: Transfer.KeyFile, else the passphrase given with -AuthPassphrase, else the one typed now (asked once per run, twice when a file is written). $null when there is none. + #> + param([switch]$ForWriting) + if ($null -ne $script:AuthKey) { return $script:AuthKey } + $transfer = $context.Config.Transfer + if ([string]$transfer.KeyFile) { + $exposed = @(Get-PraKeyFileExposure -Path ([string]$transfer.KeyFile)) + if ($exposed.Count) { Write-PraItem -Context $context -Status Warn -Text ('The key file {0} can be read by other accounts ({1}). Restrict it to this account, SYSTEM and Administrators: icacls "{0}" /inheritance:r /grant:r *{2}:F *S-1-5-18:F *S-1-5-32-544:F' -f (ConvertTo-PraSafeText ([string]$transfer.KeyFile)), (($exposed | ForEach-Object { '*' + $_ }) -join ', '), [Security.Principal.WindowsIdentity]::GetCurrent().User.Value) } + $script:AuthKey = [pscustomobject]@{ KeyFile = [string]$transfer.KeyFile; Passphrase = $null }; return $script:AuthKey + } + if ($null -ne $AuthPassphrase -and $AuthPassphrase.Length) { $script:AuthKey = [pscustomobject]@{ KeyFile = ''; Passphrase = $AuthPassphrase }; return $script:AuthKey } + if (-not $script:AuthPrompted -and (Test-PraRunCanPrompt)) { + $script:AuthPrompted = $true + $typed = Read-Host -AsSecureString -Prompt 'Passphrase of the shared secret of the transfer files (not shown, not stored)' + if ($typed.Length -and $ForWriting) { + $again = Read-Host -AsSecureString -Prompt 'Type it again to be sure' + if (-not (Test-PraAuthPassphraseEqual $typed $again)) { Write-PraItem -Context $context -Status Warn -Text 'The two passphrases are not the same: no authenticity file is written by this run.'; return $null } + } + if ($typed.Length) { $script:AuthKey = [pscustomobject]@{ KeyFile = ''; Passphrase = $typed }; return $script:AuthKey } + } + return $null +} + +function Invoke-PraCleanupAction { + <# + .SYNOPSIS + -Action Cleanup: lists what the tool left behind (finished batches, old logs, transcripts, reports, effective configurations, Preview folders, temporary files of the Exchange Online child) and, with -Mode Apply and the typed word, deletes it. + #> + $days = [int]$context.Config.Cleanup.OlderThanDays + $found = Get-PraCleanupCandidate -Config $context.Config -OlderThanDays $days -ExcludePath @([string]$context.LogFile, [string]$context.TranscriptPath) + foreach ($note in @($found.Notes)) { Write-PraItem -Context $context -Status Warn -Text $note } + $apply = [bool]$context.AllowMutation + if (-not @($found.Items).Count) { + Write-PraItem -Context $context -Status Ok -Icon Batch -Text ('Nothing to clean up: no finished batch, log, report or leftover older than {0} day(s) (Cleanup.OlderThanDays) was found.' -f $days) + } + else { + Write-PraItem -Context $context -Status Info -Icon Batch -Text ('{0} item(s) can be deleted, {1} in all (older than {2} day(s), Cleanup.OlderThanDays; a Preview folder and a temporary file of the Exchange Online child: 24 hours):' -f @($found.Items).Count, (Format-PraCleanupSize $found.TotalBytes), $days) + Write-PraLog -Context $context -Level Sub -Message ('{0,-16} {1,8} {2,11} {3} [{4}]' -f 'Kind', 'Age (d)', 'Size', 'Path', 'Reason') + $shown = 0 + foreach ($item in @($found.Items)) { + $shown++ + if ($shown -gt 200) { Write-PraLog -Context $context -Level Debug -Message ('{0,-16} {1,8} {2,11} {3} [{4}]' -f $item.Kind, $item.AgeDays.ToString('0.0', [Globalization.CultureInfo]::InvariantCulture), (Format-PraCleanupSize $item.SizeBytes), (ConvertTo-PraSafeText ([string]$item.Path)), $item.Reason); continue } + Write-PraLog -Context $context -Level Sub -Message ('{0,-16} {1,8} {2,11} {3} [{4}]' -f $item.Kind, $item.AgeDays.ToString('0.0', [Globalization.CultureInfo]::InvariantCulture), (Format-PraCleanupSize $item.SizeBytes), (ConvertTo-PraSafeText ([string]$item.Path)), $item.Reason) + } + if ($shown -gt 200) { Write-PraLog -Context $context -Level Sub -Message ('... and {0} more (all of them are in the log file)' -f ($shown - 200)) } + Write-PraItem -Context $context -Status Info -Icon Batch -Text ('Total: {0} item(s), {1}.' -f @($found.Items).Count, (Format-PraCleanupSize $found.TotalBytes)) + } + $keptBatches = @($found.Kept | Where-Object { $_.Path -match '[\\/](Batch|Finalize)-[0-9a-fA-F]{32}\z' }) + if ($keptBatches.Count) { + Write-PraItem -Context $context -Status Info -Icon Batch -Text ('{0} batch folder(s) stay: a batch is listed only when it is finished (rolled back and verified, or nothing was written to Active Directory) and old enough. The reasons are in the log.' -f $keptBatches.Count) + foreach ($item in $keptBatches) { Write-PraLog -Context $context -Level Detail -Message ('Cleanup kept | {0} | {1}' -f (ConvertTo-PraSafeText ([string]$item.Path)), $item.Reason) } + } + if (-not $apply) { + if (@($found.Items).Count) { $context.NextSteps = @('Nothing was deleted. To delete the items listed above, run the same command with -Mode Apply: it asks you to type the word CLEANUP first.', (Get-PraCommandLine -ActionName 'Cleanup' -ModeName 'Apply')) } + return + } + if (-not @($found.Items).Count) { return } + $word = '' + if (Test-PraRunCanPrompt -IgnoreForce) { $word = [string](Read-Host -Prompt ('Type {0} to delete the {1} item(s) listed above (anything else deletes nothing)' -f 'CLEANUP', @($found.Items).Count)) } + else { Write-PraItem -Context $context -Status Warn -Text 'This run cannot ask for the typed word (no console, redirected input or -NonInteractive; -Force does not replace it): nothing was deleted. Run the command in an interactive console.' } + if (-not (Test-PraOrdinalIgnoreCaseEqual $word.Trim() 'CLEANUP')) { + $context.NoChangeMade = $true + if ($word) { Write-PraItem -Context $context -Status Warn -Text 'The word typed is not CLEANUP: nothing was deleted.' } + $context.NextSteps = @('Nothing was deleted. To delete the items listed above, run the command again and type the word CLEANUP when asked:', (Get-PraCommandLine -ActionName 'Cleanup' -ModeName 'Apply')) + return + } + Write-PraApplyStarted -Context $context + $context.ChangesStarted = $true + $outcome = Invoke-PraCleanup -Config $context.Config -Item @($found.Items) -ConfirmationWord $word -OlderThanDays $days -ExcludePath @([string]$context.LogFile, [string]$context.TranscriptPath) -Context $context + Write-PraItem -Context $context -Status Ok -Icon Batch -Text ('{0} item(s) deleted.' -f @($outcome.Deleted).Count) + if (@($outcome.Skipped).Count) { Write-PraItem -Context $context -Status Warn -Text ('{0} item(s) were left: they are no longer candidates (changed since the list was made).' -f @($outcome.Skipped).Count) } + if (@($outcome.Failed).Count) { Write-PraItem -Context $context -Status Warn -Text ('{0} item(s) could not be deleted (in use or no right): {1}.' -f @($outcome.Failed).Count, ((@($outcome.Failed | Select-Object -First 3) | ForEach-Object { ConvertTo-PraSafeText ([string]$_) }) -join '; ')) } +} + +function Get-PraProtectPassphrase { + <# The typed passphrase of the protection of the files at rest: asked once per run at a console (twice when this run writes files). $null when nobody can type it, or when the two entries differ. #> + param([switch]$ForWriting) + if ($script:ProtectPrompted -or -not (Test-PraRunCanPrompt)) { return $null } + $script:ProtectPrompted = $true + $typed = Read-Host -AsSecureString -Prompt 'Passphrase that protects the backups, proofs and packages (not shown, not stored)' + if (-not $typed.Length) { return $null } + if ($ForWriting) { + $again = Read-Host -AsSecureString -Prompt 'Type it again to be sure' + if (-not (Test-PraAuthPassphraseEqual $typed $again)) { Write-PraItem -Context $context -Status Warn -Text 'The two passphrases are not the same: no passphrase was set for this run.'; return $null } + } + return $typed +} + +function Write-PraAuthFile { + <# Writes the .auth file of a package or a retention proof when the shared secret is on. Never stops the run: a file that cannot be written is a warning that says what to do. Returns the path, or ''. #> + param([Parameter(Mandatory)][string]$Path, [Parameter(Mandatory)][string]$FileKind, [Parameter(Mandatory)][string]$BatchId, [Parameter(Mandatory)][string]$CreatedUtc, [Parameter(Mandatory)][string]$Sha256, [Parameter(Mandatory)][string]$What) + if (-not (Test-PraAuthEnabled)) { return '' } + try { + $key = Get-PraAuthKey -ForWriting + if ($null -eq $key) { + Write-PraItem -Context $context -Status Warn -Text ('The shared secret is on (Transfer.Authenticate), but this run has no key: the {0} is written without its .auth file, and the other server will say that it cannot check it. Type the passphrase at a console, give -AuthPassphrase, or set Transfer.KeyFile (create the key file with: .\Invoke-PraRemoteMailbox.ps1 -NewAuthKeyFile ).' -f $What) + return '' + } + $parameters = @{ Path = $Path; FileKind = $FileKind; Environment = [string]$context.Config.Environment; BatchId = $BatchId; CreatedUtc = $CreatedUtc; FileSha256 = $Sha256 } + if ($key.KeyFile) { $parameters['KeyFile'] = $key.KeyFile } else { $parameters['Passphrase'] = $key.Passphrase } + $written = Write-PraAuthSidecar @parameters + Write-PraItem -Context $context -Status Ok -Icon Batch -Text ('Authenticity file written for the {0}: {1}' -f $What, $written) -Detail $written + return $written + } + catch { + Write-PraItem -Context $context -Status Warn -Text ('The authenticity file of the {0} could not be written ({1}): the {0} itself is complete. Check the key file or the passphrase, then write the file again by running the step again.' -f $What, (ConvertTo-PraSafeText ([string]$_.Exception.Message))) + return '' + } +} + +function Test-PraAuthFile { + <# The verdict on the .auth file of a package or a retention proof (Get-PraAuthVerdict) with the key of this run: Transfer.KeyFile, -AuthPassphrase or the passphrase typed at a console. #> + param([Parameter(Mandatory)][string]$Path, [Parameter(Mandatory)][string]$FileKind, [Parameter(Mandatory)][string]$BatchId, [Parameter(Mandatory)][string]$CreatedUtc, [Parameter(Mandatory)][string]$Sha256, [Parameter(Mandatory)][string]$What) + $enabled = Test-PraAuthEnabled + $key = if ($enabled) { Get-PraAuthKey } else { $null } + $parameters = @{ Path = $Path; FileKind = $FileKind; Environment = [string]$context.Config.Environment; BatchId = $BatchId; CreatedUtc = $CreatedUtc; Sha256 = $Sha256; What = $What; Enabled = $enabled; Required = [bool]$context.Config.Transfer.RequireAuthentication } + if ($null -ne $key) { if ($key.KeyFile) { $parameters['KeyFile'] = $key.KeyFile } else { $parameters['Passphrase'] = $key.Passphrase } } + return (Get-PraAuthVerdict @parameters) +} +function Write-PraBatchOrigin { + <# + .SYNOPSIS + Compares a batch with the configuration and the domain of this run, warns for each difference, and stops the run before any write when the operator turned Transfer.RequireConfigMatch or Transfer.RequireSameDomain on. + A Preview that would stop says so and puts the stop among the blockers of the Apply. + #> + param([Parameter(Mandatory)]$Source, [switch]$IdentityOnly) + $origin = Test-PraBatchOrigin -Context $context -Source $Source -IdentityOnly:$IdentityOnly -ResolveGroups:(-not $IdentityOnly) + $context.BatchOrigin = $origin + foreach ($line in @($origin.ConfigMatch) + @($origin.Identity)) { Write-PraItem -Context $context -Status Warn -Icon Config -Text $line } + $transfer = $context.Config.Transfer + $stops = New-Object 'Collections.Generic.List[string]' + if (@($origin.ConfigMatch).Count -and [bool]$transfer.RequireConfigMatch) { $stops.Add('Transfer.RequireConfigMatch is on and the batch does not match this configuration (' + $origin.ConfigMatch[0] + ')') } + if (@($origin.Identity).Count -and [bool]$transfer.RequireSameDomain) { $stops.Add('Transfer.RequireSameDomain is on and the batch comes from another tenant or domain (' + $origin.Identity[0] + ')') } + Stop-PraBatchOrigin -Stop $stops.ToArray() +} + +function Stop-PraBatchOrigin { + <# An Apply stops, before any write, for the reasons given; a Preview says that the Apply would stop and keeps the reasons among the blockers of the Apply. #> + param([string[]]$Stop = @()) + if (-not @($Stop).Count) { return } + if ($context.AllowMutation) { + $context.NoChangeMade = $true; $context.NextOnFailure = $true + $context.NextSteps = @('Fix the configuration file or use the right batch, or turn the setting off in the configuration file, then run the Preview again:', (Get-PraCommandLine -ActionName $Action -PhaseName $(if ($Phase) { $Phase } else { '' }) -ModeName 'Preview' -BatchId $(if ($script:PackageArgument) { $script:PackageArgument } else { $Batch }) -KeepFilters)) + throw ('{0}. Nothing was changed.' -f ($Stop -join '; ')) + } + Write-PraItem -Context $context -Status Warn -Icon Config -Text ('An Apply of this run would stop here, before it writes anything: {0}.' -f ($Stop -join '; ')) + $context.ApplyBlockers = @(Get-PraList $context 'ApplyBlockers') + @($Stop | ForEach-Object { 'make the batch and this configuration agree, or turn the matching setting off in the configuration file (' + $_ + ')' }) +} + +function Resolve-PraBatchServer { + <# + .SYNOPSIS + The domain controller to connect to when this run has none configured and takes the one a batch names: checked BEFORE the connection, with the rights of the operator. A name that is not a host name is not used (the run discovers a domain + controller itself); a name that the domain of this machine does not know is a warning (an Apply with Transfer.RequireConfigMatch stops before it connects). + #> + param([AllowEmptyString()][string]$Server = '') + if (-not $Server) { return '' } + $shape = Get-PraBatchServerFinding -Server $Server -InDomain 'Unknown' + $inDomain = if ($shape.Use) { Test-PraServerInDomain -Context $context -Server $Server } else { 'Unknown' } + $finding = Get-PraBatchServerFinding -Server $Server -InDomain $inDomain + foreach ($line in @($finding.Findings)) { Write-PraItem -Context $context -Status Warn -Icon Directory -Text $line } + if ($finding.Use -and (Test-PraOrdinalEqual $inDomain 'Unknown') -and [bool]$context.Config.Transfer.RequireConfigMatch) { Stop-PraBatchOrigin -Stop @('Transfer.RequireConfigMatch is on and the domain of this machine could not say whether the domain controller ' + (ConvertTo-PraSafeText $Server) + ' that the batch names is one of its domain controllers: set DomainController in the configuration file'); return '' } + if (@($finding.Findings).Count -and [bool]$context.Config.Transfer.RequireConfigMatch) { Stop-PraBatchOrigin -Stop @('Transfer.RequireConfigMatch is on and the domain controller of the batch is not acceptable (' + $finding.Findings[0] + ')') } + if ($finding.Use) { return $Server } + return '' +} +function Test-PraFinalizeOrigin { + <# + .SYNOPSIS + Where the Finalize loads its inputs: compares what the AD server wrote itself (the Convert backup, the Recover backup, the AD proof, with their checksum and raw files) with the originals kept here, by content, the same way + for a package, an extracted folder, a folder copied by hand and a console import. Then the .auth rule for a folder. Warns; stops before any restore or AD connection only with Transfer.RequireLocalOriginal or Transfer.RequireAuthentication. + #> + param([Parameter(Mandatory)][string]$ManifestPath) + $transfer = $context.Config.Transfer + $folder = Split-Path $ManifestPath -Parent + $loaded = New-Object 'Collections.Generic.List[object]' + $receipt = $context.Proof.Receipt + foreach ($pair in @(@($context.Source, 'Convert backup', [string]$context.Source.Data.BatchId), @($receipt, 'Recover backup', [string]$receipt.Data.BatchId))) { + $backup = $pair[0] + # The hashes recorded when the files were loaded and checked are the ones compared; a checksum file is hashed from disk. + $candidates = @(@([string]$backup.Path, $pair[1], [string]$backup.Hash), @(([string]$backup.Path + '.sha256'), ($pair[1] + ' checksum'), '')) + $raw = [string](Get-PraValue $backup.Data 'RawFile' '') + if ($raw -and (Test-PraOrdinalEqual ([IO.Path]::GetFileName($raw)) $raw)) { $candidates += , @((Join-Path (Split-Path ([string]$backup.Path) -Parent) $raw), ($pair[1] + ' raw capture'), [string](Get-PraValue $backup.Data 'RawHash' '')) } + foreach ($candidate in $candidates) { if ([IO.File]::Exists($candidate[0])) { $loaded.Add([pscustomobject]@{ Path = $candidate[0]; Role = $candidate[1]; BatchId = $pair[2]; Sha256 = $candidate[2] }) } } + } + foreach ($candidate in @(@([string]$context.Proof.Path, 'AD proof', [string]$context.Proof.Hash), @(([string]$context.Proof.Path + '.sha256'), 'AD proof checksum', ''))) { if ([IO.File]::Exists($candidate[0])) { $loaded.Add([pscustomobject]@{ Path = $candidate[0]; Role = $candidate[1]; BatchId = [string]$receipt.Data.BatchId; Sha256 = $candidate[2] }) } } + $comparison = Get-PraFinalizeOriginalComparison -File $loaded.ToArray() -BackupFolder ([string]$context.Config.Storage.BackupFolder) -ExcludeFolder @($folder) + $finding = Get-PraOriginalFinding -Comparison $comparison -RequireLocalOriginal:([bool]$transfer.RequireLocalOriginal) + foreach ($line in @($finding.Information)) { Write-PraItem -Context $context -Status Info -Icon Batch -Text $line } + foreach ($line in @($finding.Warnings)) { Write-PraItem -Context $context -Status Warn -Icon Batch -Text $line } + $stops = New-Object 'Collections.Generic.List[string]' + foreach ($line in @($finding.Refusals)) { $stops.Add($line) } + # A folder that this run imported from a verified package, that a verified import left here, or that this server made, has its origin checked; a folder copied by hand cannot carry a .auth file. + $verified = [bool]$script:PackageArgument + if (-not $verified) { $verified = Test-PraVerifiedMarker -BackupFolder ([string]$context.Config.Storage.BackupFolder) -FolderPath $folder -ManifestSha256 (Get-PraHash $ManifestPath) -StateSha256 ([string]$context.Proof.Hash) } + if (-not $verified) { + if ([bool]$transfer.RequireAuthentication) { $stops.Add('Transfer.RequireAuthentication is on and this Finalize folder was copied by hand: no .auth file can come with a folder. Import the package (.zip and its .auth file) written by the cloud server instead') } + elseif ([bool]$transfer.Authenticate) { Write-PraItem -Context $context -Status Warn -Icon Batch -Text 'The shared secret is on, and this Finalize folder was copied by hand: no .auth file can come with a folder, so its origin is not checked. Import the package (.zip and its .auth file) written by the cloud server to have it checked.' } + } + Stop-PraBatchOrigin -Stop $stops.ToArray() +} +function Get-PraWhereText { + <# The licence group and the domain controller that a restore will use, for the question of the confirmation. #> + $parts = @() + $groups = @(Get-PraList (Get-PraValue $context 'BatchOrigin' $null) 'Groups') + if ($groups.Count) { $parts += ('Licence group: {0}.' -f ((@($groups | ForEach-Object { ConvertTo-PraSafeText ([string]$_) })) -join '; ')) } + if ([string]$context.Server) { $parts += ('Domain controller: {0}.' -f (ConvertTo-PraSafeText ([string]$context.Server))) } + if (-not $parts.Count) { return '' } + return (' ' + ($parts -join ' ')) +} + function Publish-PraTransferPackage { <# .SYNOPSIS @@ -726,12 +1166,27 @@ function Publish-PraTransferPackage { } try { $name = Get-PraTransferPackageName -Kind $Kind -Environment $context.Config.Environment -BatchId $BatchId - $command = Get-PraCommandLine -ActionName $NextAction -PhaseName $NextPhase -BatchId $name -OtherServer + $command = Get-PraCommandLine -ActionName $NextAction -PhaseName $NextPhase -BatchId $name -KeepSelection -OtherServer + # The objects of this run travel in the package as data (the console reads them); a command longer than the limit of the manifest is printed in the next steps only. + $selectedIdentity = if (Test-PraSelectionNarrows) { Get-PraSelectionIdentity } else { '' } + if ($selectedIdentity.Length -gt 1024) { + Write-PraItem -Context $context -Status Warn -Icon Batch -Text 'The identity of this run is longer than 1024 characters: it is left out of the transfer package (the command below carries it), and the package keeps the scope when there is one.' + $selectedIdentity = '' + $selectedScope = Get-PraSelectionScope + } + else { $selectedScope = if ($selectedIdentity -or -not (Test-PraSelectionNarrows)) { '' } else { Get-PraSelectionScope } } + $selection = @{ Identity = $selectedIdentity; Scope = $selectedScope } $package = New-PraTransferPackage -Kind $Kind -Environment $context.Config.Environment -BatchId $BatchId -Folders $Folders ` - -OutboxFolder (Join-Path $context.BackupFolder 'Outbox') -NextCommand $command -ToolVersion $context.Version - $context.TransferPackage = $package.Path; $context.TransferPackageKind = $Kind + -OutboxFolder (Join-Path $context.BackupFolder 'Outbox') -NextCommand $(if ($command.Length -le 1000) { $command } else { '' }) -ToolVersion $context.Version -Identity (Get-PraRunIdentity -Context $context) -Selection $selection + $context.TransferPackage = $package.Path; $context.TransferPackageKind = $Kind; $context.TransferPackageFingerprint = [string]$package.Fingerprint + $context.TransferPackageIdentity = [string]$selection.Identity; $context.TransferPackageScope = [string]$selection.Scope Write-PraItem -Context $context -Status Ok -Icon Batch -Text ('Transfer package {0} written ({1}, checksums verified)' -f $package.Name, (Format-PraByteSize $package.SizeBytes)) -Detail $package.Path - $context.NextSteps = @(('Copy these two files, together in the same folder, to the {0} server (anywhere): {1} and {2}. Then run there:' -f $targetName, $package.Path, $package.Sidecar), $command) + Write-PraItem -Context $context -Status Info -Icon Batch -Text ('Package fingerprint {0} (the start of its SHA-256). Read it to the operator of the {1} server by another channel than the one the package travels on: there, -ExpectedFingerprint {0} makes the import refuse any other package.' -f $package.Fingerprint, $targetName) + $authFile = Write-PraAuthFile -Path $package.Path -FileKind ('Package:' + $Kind) -BatchId ([string]$package.BatchId) -CreatedUtc ([string]$package.CreatedUtc) -Sha256 ([string]$package.Sha256) -What 'transfer package' + $copyText = if ($authFile) { 'Copy these three files, together in the same folder, to the {0} server (anywhere): {1}, {2} and {3}. Then run there:' -f $targetName, $package.Path, $package.Sidecar, $authFile } + else { 'Copy these two files, together in the same folder, to the {0} server (anywhere): {1} and {2}. Then run there:' -f $targetName, $package.Path, $package.Sidecar } + $verifyText = 'The fingerprint of this package is {0}. Read it to the operator of the {1} server by another channel than the one the package travels on; there, add -ExpectedFingerprint so that the import refuses any other package:' -f $package.Fingerprint, $targetName + $context.NextSteps = @($copyText, $command, $verifyText, ($command + ' -ExpectedFingerprint ' + $package.Fingerprint)) } catch { Write-PraLog -Context $context -Message ('The transfer package could not be created ({0}). The folders are complete: copy them by hand as indicated below.' -f $_.Exception.Message) -Level Warning @@ -754,6 +1209,36 @@ function Resolve-PraTransferPackagePath { throw "Transfer package $Value not found in $(Join-Path $context.BackupFolder 'Inbox'), in the Outbox folder or in the current folder: give its full path." } +function Get-PraLeftoverFolderStep { + <# The next steps of an import refused because a folder of the same batch is already in the backup folder and is not the package: the folder, what it may be, and the command that moves it aside and runs the step again. #> + param([Parameter(Mandatory)][string]$Root, [Parameter(Mandatory)][string]$Name, [string]$Mode, [string]$Phase) + $folder = Join-Path $Root $Name + $aside = Join-Path $Root ('Refused-{0}-{1}' -f $Name, [DateTime]::UtcNow.ToString('yyyyMMddHHmmss', [Globalization.CultureInfo]::InvariantCulture)) + return @(('The folder {0} is already in the backup folder and is not the package you gave: it comes from an earlier import that was refused or stopped, from another package of the same batch, or from a copy made by hand. Nothing was changed.' -f $folder), + 'Look at it first. If you did not put it there on purpose, move it aside (nothing is deleted: keep it as evidence), then run the same command again:', + ('Move-Item -LiteralPath {0} -Destination {1}' -f (ConvertTo-PraLiteral $folder), (ConvertTo-PraLiteral $aside)), + (Get-PraCommandLine -ActionName $Action -PhaseName $(if ($Phase) { $Phase } else { '' }) -ModeName $Mode -BatchId $script:PackageArgument -KeepFilters)) +} + +function Undo-PraRunImport { + <# A package that this run extracted is taken back when the run stops before it has loaded it (checks of the proof, the originals, the backup): the files it extracted and the markers it wrote are removed while they are still as it left them; a file that another run added or changed keeps its folder in place, with a warning. #> + if ($null -eq $script:ImportUndo) { return } + $undo = $script:ImportUndo; $script:ImportUndo = $null + try { + $result = Undo-PraImport -Undo $undo + $gone = @($result.RemovedFolder) + if ($gone.Count) { + $script:ImportedFolders = @($script:ImportedFolders | Where-Object { -not (Test-PraOrdinalIn $_ $gone -IgnoreCase) }) + $inside = { param([string]$Path) foreach ($folder in $gone) { if ($Path -and (([IO.Path]::GetFullPath($Path).TrimEnd('\') + '\').StartsWith($folder.TrimEnd('\') + '\', [StringComparison]::OrdinalIgnoreCase))) { return $true } }; return $false } + if (& $inside ([string](Get-PraValue $context 'PhaseWriteFolder' ''))) { $context.PhaseWriteFolder = '' } + $context.PhaseFolders = @(@(Get-PraList $context 'PhaseFolders') | Where-Object { -not (& $inside ([string]$_)) }) + Write-PraItem -Context $context -Status Info -Icon Batch -Text ('The package was taken back: the run stopped before it loaded it, so what this run extracted ({0}) was removed and nothing of it stays in the backup folder.' -f ((@($gone | ForEach-Object { [IO.Path]::GetFileName($_) })) -join ', ')) + } + if (@($result.Kept).Count) { Write-PraItem -Context $context -Status Warn -Icon Batch -Text ('The package was not taken back completely: something other than this import added or changed these files or folders since it ran (another run on this server may use them), so they are left in place: {0}. Look at them before you import the package again.' -f ((@($result.Kept) | ForEach-Object { ConvertTo-PraSafeText $_ }) -join '; ')) } + if (@($result.Failed).Count) { Write-PraItem -Context $context -Status Warn -Icon Batch -Text ('These files or folders of the refused package could not be removed: {0}. Move them aside by hand before you import the package again.' -f ((@($result.Failed) | ForEach-Object { ConvertTo-PraSafeText $_ }) -join '; ')) } + } + catch { $null = $_ } +} function Test-PraSyncAvailable { <# .SYNOPSIS @@ -842,11 +1327,15 @@ function Save-PraRetentionProof { $outbox = Join-Path ([string]$context.Config.Storage.BackupFolder) 'Outbox' try { $guids = @([string](Get-PraValue $context 'RetentionPolicyGuid' '')) - $written = Write-PraRetentionProof -Folder $outbox -BatchId ([string]$context.Source.Data.BatchId) -SourceBackupHash ([string]$context.Source.Hash) -Environment ([string]$context.Config.Environment) -PolicyGuid $guids -Object $objects.ToArray() + $written = Write-PraRetentionProof -Folder $outbox -BatchId ([string]$context.Source.Data.BatchId) -SourceBackupHash ([string]$context.Source.Hash) -Environment ([string]$context.Config.Environment) -PolicyGuid $guids -Object $objects.ToArray() -Identity (Get-PraRunIdentity -Context $context) $withoutMailbox = @($objects | Where-Object { Test-PraOrdinalEqual $_.Verdict 'NoMailbox' }).Count Write-PraItem -Context $context -Status Ok -Icon Batch -Text ('Retention proof written: {0} of {1} object(s) covered{2} ({3})' -f $written.CoveredCount, $written.ObjectCount, $(if ($withoutMailbox) { ', {0} without a mailbox in Exchange Online (nothing to retain)' -f $withoutMailbox } else { '' }), $written.Path) -Detail $written.Path - $next = Get-PraCommandLine -ActionName 'Recover' -PhaseName 'AD' -ModeName 'Preview' -BatchId (Get-PraShortId ([string]$context.Source.Data.BatchId)) -OtherServer - $context.NextSteps = @(Get-PraList $context 'NextSteps') + @(('For the Recover on the AD server, copy these two files to its Backups\Inbox folder: {0} and {1}. The AD server accepts a proof for as many hours as its own Retention.ProofMaxAgeHours says (24 by default), so copy them soon. Then run there:' -f $written.Path, $written.Sidecar), $next) + $next = Get-PraCommandLine -ActionName 'Recover' -PhaseName 'AD' -ModeName 'Preview' -BatchId (Get-PraShortId ([string]$context.Source.Data.BatchId)) -KeepSelection -OtherServer + Write-PraItem -Context $context -Status Info -Icon Batch -Text ('Retention proof fingerprint {0} (the start of its SHA-256): the Recover on the AD server prints the fingerprint of the proof it accepts; they must be the same.' -f $written.Fingerprint) + $authFile = Write-PraAuthFile -Path $written.Path -FileKind 'RetentionProof' -BatchId ([string]$context.Source.Data.BatchId) -CreatedUtc ($written.CreatedUtc.ToUniversalTime().ToString('o', [Globalization.CultureInfo]::InvariantCulture)) -Sha256 ([string]$written.Sha256) -What 'retention proof' + $copyProof = if ($authFile) { 'For the Recover on the AD server, copy these three files to its Backups\Inbox folder: {0}, {1} and {2}. The AD server accepts a proof for as many hours as its own Retention.ProofMaxAgeHours says (24 by default), so copy them soon. Then run there:' -f $written.Path, $written.Sidecar, $authFile } + else { 'For the Recover on the AD server, copy these two files to its Backups\Inbox folder: {0} and {1}. The AD server accepts a proof for as many hours as its own Retention.ProofMaxAgeHours says (24 by default), so copy them soon. Then run there:' -f $written.Path, $written.Sidecar } + $context.NextSteps = @(Get-PraList $context 'NextSteps') + @($copyProof, $next) } catch { Write-PraItem -Context $context -Status Warn -Icon Batch -Text ('The retention proof could not be written ({0}): the check itself is not affected.' -f $_.Exception.Message) @@ -900,6 +1389,10 @@ function Invoke-PraRetentionGate { return } $context.CurrentOperation = 'Check-Retention'; $context.CurrentIdentity = '' + if ($Plans.Count -and -not @($Plans | Where-Object { Test-PraPlanChange -Plan $_ }).Count) { + Write-PraItem -Context $context -Status Info -Icon Cloud -Text ('Retention: this Recover changes nothing in Active Directory (the {0} object(s) are already in the state of the backup), so it removes no mailbox from Exchange Online and there is no retention to check. A rollback that is only partly done is checked in full.' -f $Plans.Count) + return + } $rows = New-Object 'Collections.Generic.List[object]' foreach ($plan in $Plans) { if (Test-PraOrdinalEqual $plan.Operation 'AlreadyRecovered') { continue } @@ -941,8 +1434,41 @@ function Invoke-PraRetentionGate { $viaProof = $false; $coveredCount = [int](Get-PraValue $answer 'Covered' 0); $noMailboxCount = [int](Get-PraValue $answer 'NoMailbox' 0); $proofKinds = @{ Unverified = 0; NotChecked = 0; NotListed = 0 } if ($isAd -and $couldNotAsk -and -not $notCovered.Count) { $script:RetentionProofRoute = $true - $proof = Get-PraRetentionProof -Folder (Get-PraRetentionProofFolder) -BatchId ([string]$context.Source.Data.BatchId) -Environment ([string]$context.Config.Environment) -MaxAgeHours ([int]$context.Config.Retention.ProofMaxAgeHours) -Row $rows.ToArray() -SourceBackupHash ([string]$context.Source.Hash) -PolicyGuid ([string]$context.Config.Retention.PolicyGuid) + $context.RetentionRoute = 'retention proof (this run could not ask Exchange Online)' + if ([bool]$context.Config.Retention.RequireLiveCheck) { + $proof = [pscustomobject]@{ Found = $false; Complete = $false; Refusal = 'LiveCheck'; Reason = 'Retention.RequireLiveCheck is on: only a live answer of Exchange Online is accepted, and this run could not ask it'; Path = ''; Sha256 = ''; Blocked = @(); Missing = [string[]]@(); NoMailbox = @(); PolicyGuid = [string[]]@(); RefusedPath = ''; FutureDated = $false; Duplicates = 0; Ignored = [string[]]@(); IgnoreNotApplied = ''; Candidates = 0; Proofs = @() } + } + else { + $proof = Get-PraRetentionProof -Folder (Get-PraRetentionProofFolder) -BatchId ([string]$context.Source.Data.BatchId) -Environment ([string]$context.Config.Environment) -MaxAgeHours ([int]$context.Config.Retention.ProofMaxAgeHours) -Row $rows.ToArray() -SourceBackupHash ([string]$context.Source.Hash) -PolicyGuid ([string]$context.Config.Retention.PolicyGuid) -IgnoreProof ([string]$IgnoreProof) + } + if ($IgnoreProof) { + if ([bool]$context.Config.Retention.RequireLiveCheck) { Write-PraItem -Context $context -Status Warn -Icon Cloud -Text '-IgnoreProof has no effect in this run: Retention.RequireLiveCheck is on, so no retention proof is read at all.' } + elseif (@($proof.Ignored).Count) { + $context.IgnoredProof = (@($proof.Ignored) -join '; ') + foreach ($skipped in @($proof.Ignored)) { + Write-PraItem -Context $context -Status Warn -Icon Cloud -Text ('The retention proof {0} is skipped for this run (-IgnoreProof): it is treated as if the file was not there. The other proofs and the live check are not affected; this is recorded in the log, the summary and the report.' -f (ConvertTo-PraSafeText ([string]$skipped))) + Add-PraOverride -Context $context -Id 'IgnoreProof' -Count 1 -Text ('Retention proof skipped for this run (-IgnoreProof): {0}' -f (ConvertTo-PraSafeText ([IO.Path]::GetFileName([string]$skipped)))) + } + } + elseif ([string]$proof.IgnoreNotApplied) { Write-PraItem -Context $context -Status Warn -Icon Cloud -Text ('-IgnoreProof names the retention proof {0}, which this run can use: it is not skipped. Only a proof that this run refuses (damaged, of another batch, too old, ...) can be skipped, so that an older proof never stands in for a usable newer one.' -f (ConvertTo-PraSafeText ([string]$proof.IgnoreNotApplied))) } + else { Write-PraItem -Context $context -Status Warn -Icon Cloud -Text ('-IgnoreProof {0} names no retention proof of this batch in the Inbox, Outbox or batch folders that this run refuses: nothing was skipped. Give the file name as it appears in the folder (RetentionProof--
+

With two servers, a roll-back of part of a batch (-Identity or -Scope) names the same objects in the next phase: the commands printed for the cloud server (and then for the Finalize on the AD server) carry -Identity <the object> or -Scope as the run used them, quoted as data, so that each command works as printed. The cloud phase reads the whole batch and verifies only what the AD phase verified, so without the selection it stops at Object not verified by the AD phase of this batch. An identity typed as a distinguished name is printed as the account name of the object; an identity that no object of the batch carries is not printed. The scope is printed only by a run that filtered a batch with it (a Recover, the cloud phase of a Convert, a Check of a batch): the AD phase of a Convert chose its objects, and finishing a batch (-Phase AD -Batch) ignores the scope, so neither prints it. The same goes for the commands that continue a batch after a stop.

+

The package also carries that selection (the Selection of its manifest), and the tool never applies it by itself on the command line: a run that was given neither -Identity nor -Scope for a package made for part of its batch says so in one warning and names the option to add. The console reads it when you import the package (it is kept in the verified marker of the folder of the package's own batch, with the kind of the package; the Convert batch that a Recover package only brings along gets none, and the console applies the selection only to a batch of the kind of the package, for the run that reads that batch, never to the finish of a batch): for that rollback or batch it fills and fixes the objects and the scope of the run with the ones of the package (the window's scope does not apply), says so under the list (This package was made for …), shows them in What this run will use, and its Next step after a package names them. A batch whose package named nothing is run with the window's settings, as before.

Users get their original attributes back and leave the licence group. Shared mailboxes are first removed from Exchange Online; their on-premises attributes come back when Exchange Online confirms it (up to Polling.TimeoutMinutes), in the same run. Their on-premises permissions were never changed.

The Preview also checks that the retention policy holds the mailboxes that carry the retention tag; the Apply stops before any change when it does not (see Retention in chapter 6). To go on anyway, for this one run: .\Invoke-PraRemoteMailbox.ps1 -Action Recover -Batch 1d5ac20b -Mode Apply -AcceptRetentionRisk.

Recipe 6 — Check, at any time

@@ -1623,14 +2099,14 @@

Scenario D — Recover on two servers Phase Both retains inline restoration unless DeferOnPremRestore is enabled. Finalize is only required when the result supplies a Finalize package (deferred shared attributes or retention tags).

What you see

-
The Verify page: the preview of a Convert, with the confirmation word typed
The Verify page: the preview of a Convert, with the confirmation word typed
+
The Verify page: the preview of a Convert, with the confirmation word typed
The Verify page: the preview of a Convert, with the confirmation word typed
  1. The banner: action, mode, scope, tenant, configuration and log file.
  2. Numbered steps. In a preview, the steps that write are shown as skipped.
  3. For each object: its type change (UserMailbox → RemoteUserMailbox) and only the attributes that change — green = added, yellow = changed, red = removed. For a shared mailbox, the holders that will get FullAccess, SendAs and SendOnBehalf in Exchange Online. The full before/after values and the complete lists of holders are in the log.
  4. The summary: result, batch ID, backup, report, log, duration and the next command.
-
The Next steps page at the end of a Convert
The Next steps page at the end of a Convert
+
The Next steps page at the end of a Convert
The Next steps page at the end of a Convert

Exit codes

@@ -1668,18 +2144,100 @@

Exit codes

-Action Recover -Batch <id> of a partial batch takes only the objects of the proof and the object the batch stopped on; every other object of the backup is reported Skipped ("not converted by this batch": nothing to roll back), so an object that another batch converted since is not rolled back by this one. -Action Check -Batch <id> of a partial batch reports the objects that were never converted as not as expected.

New Convert for the objects that are left. With -CsvPath, the Next steps give a command with a CSV file that lists only the objects still to convert (same columns as your file, written in the log folder); with -Identity, -SearchBase or -Group the command keeps the filters: the converted objects are not eligible any more and are skipped. On the cloud server the AD-side commands are introduced by On the AD server: and are written without this server's configuration path.

A Convert batch that a Recover rolled back, or started to roll back, cannot be resumed (-Phase AD -Batch and the cloud phase refuse it: "Convert batch X cannot be resumed: Recover batch Y already rolled back objects of it"). A Recover that stopped before its proof counts too: its journal tells which objects it had started on; a journal that is missing counts for every object. On two servers the cloud server learns of the Recover only when the Recover package has been imported there: until then it cannot refuse.

+

Windows events

+

An Apply writes one event when it starts, one when it ends or fails, and one for each safety override in the Windows Application log, source PraRemoteMailbox (Logging.WindowsEvents, chapter 6). Never one per object. A Preview and a Check write none. The text is English, made of Key=Value lines, and does not depend on the language of Windows: find the events by their number. They hold identifiers and counts only (run ID, batch ID, SID of the account, counts), never the name of a person, a mailbox or an object.

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Event IDLevelWhenFields
4100InformationAn Apply starts (after its confirmation, or at once with -Force); the events 4200 of the overrides of the run follow it, and none is written for an Apply that is not confirmedRun, Action, Phase, Batch, Account, Version, Overrides
4101InformationAn Apply ends (exit code 0 or 2)the same, and Status, ExitCode, Success, Error, Pending, Skipped, Warnings, Overrides
4102ErrorAn Apply fails (exit code 1), or stops after its start before its end could be writtenthe same as 4101, and FirstErrorSource and Issues (the number of errors)
4200WarningA safety override is used: AcceptRetentionRisk, IgnoreProof, Force, IdentityCheckOff, RetentionCheckOff or Off:<setting> (a protection of the configuration turned off for this run from the console)Override, Count (objects concerned, 0 when not counted), Origin (command line, console or file)
+

Batch is the first 8 characters of the batch of the run. A run that made a batch but ends without reporting one (an Apply that the domain controller refused before its first write, which leaves a backup folder marked NOT-APPLIED) still names it in 4101 and 4102; the field is empty only when the run knows no batch.

+

The same overrides are in the log, in the summary and in the report (Run settings changed), and the run settings of the report name the settings that steer a privileged action: the identity check, the permission source, the age limit of a retention proof, whether the retention policy is named, whether the Exchange Online child process is on, and whether the confirmation was skipped.

+

The source is registered the first time an Apply runs as administrator. On a server where nobody runs the tool as administrator, register it once from a window opened as administrator: [System.Diagnostics.EventLog]::CreateEventSource('PraRemoteMailbox', 'Application'). An event that cannot be written is one line in the log (level DETAIL) and nothing else: it never changes the result, the exit code or the errors of the run, and it is written after the log and journal lines, never before a write.

+

Where the records are, and how to forward them.

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecordWhereWritten
Windows eventsApplication log, source PraRemoteMailbox, ids 4100, 4101, 4102 and 4200by an Apply: start, end, failure, override
Log and transcriptlogs\PRA_<RunId>_<n>.log and .transcript.txtby every run, a Preview included
Journal of a batchBackups\Batch-<id>\Journal-<id>.jsonl; the Exchange Online grants of a run: Backups\<RunId>-cloud\CloudOperations.jsonlby an Apply, one line per write, with the Account (SID), the Computer, the ProcessId and the RunId
Reportsreports\PRA_<RunId>_<n>.html and .csv, and the global reportby every run
Exit code0 done, 1 failed, 2 done and a next step is required (Exit codes); with -PassThru, the result objectby every run
+

To send the events to a collector, use Windows Event Forwarding or the agent of your collector, with a filter on the source. A subscription of the Windows Event Collector takes this query (try it first on the server with Get-WinEvent -FilterHashtable @{ LogName = 'Application'; ProviderName = 'PraRemoteMailbox' }):

+
xml
<QueryList><Query Id="0"><Select Path="Application">*[System[Provider[@Name='PraRemoteMailbox'] and (EventID=4100 or EventID=4101 or EventID=4102 or EventID=4200)]]</Select></Query></QueryList>
+
+

The log, the journals and the reports are files: collect them with your file collection, and protect them as the backups (Data handling). The events hold identifiers and counts only, so they can leave the server without leaking a name.

Chapter 9

Reading the results

In short: Every run writes a report that opens in a browser. Read the result, then the warnings, then the line of each person.

The HTML report

-
HTML report of one run (synthetic example data)
HTML report of one run (synthetic example data)
-

One page per run in reports\: tiles with the counters (including Warnings), the next step, the warnings of the run, one row per object, and the run errors. It is self-contained (no external resource, no network, no telemetry).

+
HTML report of one run (synthetic example data)
HTML report of one run (synthetic example data)
+

One page per run in reports\: tiles with the counters (including Warnings), the next step, the warnings of the run, one row per object, and the run errors. It is self-contained (no external resource, no network, no telemetry), and its own Content-Security-Policy forbids everything but its own inline script and style (default-src 'none'; the scripts and the style are named by their SHA-256), so that the page cannot load or send anything even if a text of the run held markup. It opens from a file (file://) in Microsoft Edge or Google Chrome as before.

The rows are stored in the page as compressed chunks of 20,000 rows (gzip, then base64: compression, not encryption; protect the file like the CSV). When the page opens it decodes all chunks at once (eager, not lazy; about 0.3 s for 50,000 rows on the test PC), then shows only the rows in view: the Summary grid (the eight columns above) and the All 22 fields grid never hold more than 200 data rows in the page, whatever the number of rows. Scroll, or use the keyboard (arrows, Page Up/Down, Home/End, Enter for all the fields of a row). Filters (status, type, action, six yes/no flags, ten text fields and a search over the 22 fields) combine with AND, always inspect every row and show the filtered counts; Reset filters clears them. Export filtered CSV writes every matching row with the 22 fields (semicolon, UTF-8 with BOM, every field quoted, a cell starting with =, +, - or @ gets a leading '). The CSV written next to the report is unchanged and has the raw values. Warnings and run errors are listed 100 per page with their own filter; none is dropped.

Requirement: a current desktop Microsoft Edge or Google Chrome (the page needs DecompressionStream). Without it, without JavaScript, or if a chunk is missing or damaged, the page says so explicitly and displays no partial result; the run summary (tiles, next step) stays visible and the CSV with the same name holds every row. A report of 50,000 or 100,000 rows is for reading; Apply itself remains designed for the batch sizes of the guide.

The global report (two servers, one report)

-
Global report of a Convert across two servers (synthetic example data)
Global report of a Convert across two servers (synthetic example data)
-
Global report of a rollback across three phases: Recover on the AD server, Recover on the cloud server, Finalize (synthetic example data)
Global report of a rollback across three phases: Recover on the AD server, Recover on the cloud server, Finalize (synthetic example data)
+
Global report of a Convert across two servers (synthetic example data)
Global report of a Convert across two servers (synthetic example data)
+
Global report of a rollback across three phases: Recover on the AD server, Recover on the cloud server, Finalize (synthetic example data)
Global report of a rollback across three phases: Recover on the AD server, Recover on the cloud server, Finalize (synthetic example data)

With two servers, each side writes its own report (as before). The last server also writes ONE global report that follows every object from the first server to the last, for Convert (AD, then Cloud) as for Recover (AD, Cloud, then Finalize), whatever the type of the objects (users, shared mailboxes, all):

    @@ -1718,7 +2276,101 @@

    The global report (two servers

Warnings

A warning never stops the run and never changes the exit code; it says that something was left aside on purpose and should be read. Today: the permission entries of a shared mailbox that point to an account no longer in AD or that is not a user or a group, and the Deny entries that are not reproduced (chapter 2); the objects that a Recover finds changed since the batch left them, and the retention that a Recover accepted or did not check (chapter 6); and an X500 address missing in Exchange Online (chapter 2, X500 addresses). It is shown in four places: a yellow ▲ line in the console under the object, [WARN] in the log, the Warnings column of the CSV, and in the HTML report (Warnings tile, Warnings card, yellow mark on the row). The summary card of the console turns yellow and shows the last warnings.

-
Report of a run with a warning on a shared mailbox (synthetic example data)
Report of a run with a warning on a shared mailbox (synthetic example data)
+
Report of a run with a warning on a shared mailbox (synthetic example data)
Report of a run with a warning on a shared mailbox (synthetic example data)
+

Checks made at the start of a run

+

Before anything is written, the log header records the version and the path of PowerShell, ExchangeOnlineManagement, Microsoft.Graph.Authentication and Microsoft.Graph.Users; the report repeats them in its footer. A block What this run will use (Preview and Apply confirmation, and the header of the report) lists the values that steer a privileged action, each with its source (the configuration file, the command line or the console): configuration file, environment, domain controller, mailbox scope, licence group, permission source, trustee exclusions, identity check, retention check and proof age, Entra Connect, tenant, application, backup, log and report folders, and whether protected folders are required. Every check below only warns; none changes the exit code, and none refuses the run.

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
WarningWhat it says and what to do
PowerShell … is older than …, the first … release with a published security fixUpdate PowerShell.
Package integrity: the certificate chain of the publisher cannot be built on this computerAn isolated server: the package starts on the signature, the pinned signer and the timestamp, see Package integrity. The warning is also written in the log, the summary and the report of the run.
No Windows event is written in this run: the event source PraRemoteMailbox is not registeredNobody ran the tool as administrator on this computer yet. Register the source once (command in Windows events) or set Logging.WindowsEvents to Off. The run goes on.
The journal … ends a write that was cut at line …A crash or a power loss cut a line while it was written, and the next line carries on the chain. Nothing is blocked, not even with Logging.RequireJournalChain. If no run was interrupted, compare the journal with the audit logs.
The chain of the journal … is broken at line …The optional journal chain (Logging.JournalChain) finds a line that was edited, cut or removed, or that another program wrote. The journal is read as it is; compare it with the audit logs. Logging.RequireJournalChain makes a Recover stop instead.
The execution policy refused a PowerShell file of the Exchange Online module in the child process started from its standard inputWith Exo.UseSubprocess and Exo.ChildStart = Auto: the policy is AllSigned and ExchangeOnlineManagement wrote an unsigned temporary module. The child is started once more from a temporary script file with -ExecutionPolicy Bypass for that process only; nothing was sent to Exchange Online by the first start. Set Exo.ChildStart = File to skip the first start.
The Exchange Online part cannot run on this computer: the execution policy AllSigned is set by Group PolicyA Group Policy (MachinePolicy or UserPolicy) enforces AllSigned, and a process parameter cannot override it: no start mode and no in-process connection can work. Ask the administrator of the policy for an exception for this computer, or run the Exchange Online part on a computer where AllSigned is not enforced by Group Policy. Nothing was sent to Exchange Online.
Exo.ChildStart = Stdin cannot work under the execution policy …The child started from its standard input was refused by the execution policy (AllSigned, usually): set Exo.ChildStart to Auto or File. The text ends with the type and the error identifier of the original error.
ExchangeOnlineManagement … is not validly signed by MicrosoftThe execution policy is AllSigned and a file of the installed module has no valid Microsoft signature (or the module is missing or older than Exo.MinModuleVersion): nothing was started. Install the module again from the PowerShell Gallery and do not edit its files.
Exchange Online cannot be reached in process under the execution policy …Exo.UseSubprocess is off and the policy refused a PowerShell file of the Exchange Online module in this process: set Exo.UseSubprocess = $true (certificate sign-in of the Cloud section). The text ends with the type and the error identifier of the original error. A security error under another policy than AllSigned that is not a refusal by the policy is reported as it is.
The Exchange Online child process did not run from its standard inputWith Exo.UseSubprocess: the child never ran its script (no start marker): the execution policy is AllSigned or PowerShell is in Constrained Language mode. The child is started once more from a temporary script file in a private folder; nothing was sent to Exchange Online by the first start.
Folder permissions: …See Protection of the folders.
Protection of the files at rest is on (…)Information: the mode used by this run (Storage.Protect). Keep a copy of the key away from the backups: losing it means losing the files.
N object(s) are likely to be refused by Active Directory when this is appliedThe Preview of the AD part found, in the security descriptor of an object, a Deny entry for the account that runs the tool (or one of its groups, by SID) on a property that the Apply writes, an object protected by AdminSDHolder (adminCount = 1), or an object that blocks inheritance and has no entry that lets the account write. See Rights probe below. Run dsacls "<DN>" on the first object, use an account that has the right, or change the entries before the Apply.
-Verbose or -Debug is onThe transcript and the log record the output of the Microsoft modules: do not share them without reading them.
This run is started as SYSTEMSee chapter 7.
Cloud.CertificateThumbprint does not look like a certificate thumbprint, Cloud.TenantId … is not a GUID, Cloud.Organization … does not look like the domain of the tenantA value that an older version accepted looks wrong: it is used as it is, and fails later if it is wrong. Copy it again.
The backup … holds permission values of an unusual shapeA shared-permission entry of a backup is not a UPN-like text (at most 320 characters) or a right holds more than 5000 entries. The backup is used as it is.
The private key of the application certificate can be exported and The key file of the application certificate can be used by other accountsAnyone who runs as this account can copy the key, or other accounts can use it: create the certificate again with -KeyExportPolicy NonExportable (annex C), or restrict the key file with the icacls command shown.
Trustee … is a built-in account of the domainA shared mailbox gives access to a built-in account (RID 500, 516, 517, 520, 521, 526 or 527) that SharedMailbox.ExcludeTrusteeSamAccountNames does not name. That list holds names, and the name of the built-in administrator depends on the language of the domain: add the name shown if it must not receive access. The plan is unchanged.
+

Rights probe (Preview of the AD part). While it builds the plan of an object, the tool reads its security descriptor (the same read as for the backup: nothing more is asked of the directory, apart from one query of the schema for the identifiers of the properties, once per run, and one read of the licence group) and evaluates the entries in memory against the SIDs of the account and of its groups. It lists, as warnings with the object and the reason, and in the Warnings column of the report: a Deny entry that covers a property the Apply writes (for every property, for that property, or for its property set); an object protected by AdminSDHolder (adminCount = 1: SDProp resets its permissions every hour and delegated rights are not inherited); and an object that blocks inheritance and has no entry that lets the account write the property. It never stops a run and never changes anything. What it does not cover: the privileges of the account (backup and restore rights), the Self and Creator Owner entries, the entries on the parents of an object that are not inherited into it, a property set the schema does not name, claims and conditional entries, a Deny-only group in the token, and the rights of the licence group beyond its member property. Two more limits make it a hint and not a verdict: the groups of the account are the domain groups of its token, so an entry that names a local group of the computer where the tool runs (a BUILTIN SID on a member server) is not matched; and the entries are read as a set, without the order in which Windows evaluates them, so a Deny can be reported although an explicit Allow that comes first in the descriptor wins (an inherited Deny against an explicit Allow on the object, for example). A property set that the schema does not name is not matched by its entries either. A schema that cannot be read leaves out the entries that name one property (the entries that cover every property are still evaluated). An object that is not listed can still be refused.

+

The Deny entries of a shared mailbox are named in the Preview and in the Deny entries line of the report header, with the accounts that are granted access anyway.

Statuses

@@ -1774,7 +2426,7 @@

The CSV columns

Finalize-3f2c90e1....\ Finalize package (Recover on two servers) <RunId>-cloud\CloudOperations.jsonl journal of the Exchange Online grants of a run Outbox\PRA-<Env>-<Kind>-<id8>-for-<Cloud|AD>.zip transfer package written at each handover (+ .sha256) - Inbox\ packages dropped here are listed by the console + Inbox\ packages dropped here are listed by the console; an Apply creates it, private, when it is missing logs\ PRA_<RunId>_<n>.log and .transcript.txt reports\ PRA_<RunId>_<n>.csv and .html @@ -1782,7 +2434,7 @@

The CSV columns

  • Batch ID = the first 8 characters of the folder name; -Batch accepts 8 characters or more, or the path of the JSON file.
  • The State file is the proof that the AD part was done and verified: the cloud phase and Finalize refuse to write without it.
  • Carry one transfer package (the zip and its .sha256 file, below) between the servers; if you copy folders by hand instead, copy whole folders, never single files, and never rename them.
  • -
  • Keep the batches at least until the Recover is finished and checked; then archive them with the logs.
  • +
  • Keep the batches at least until the Recover is finished and checked; then archive them with the logs, or clear them with the cleanup helper (below).
  • The transfer package (one zip file, with its checksum file, from one server to the other)

    At each handover of a two-server run (Convert or Recover with -Phase AD, and the cloud phase of a Recover that needs a final AD restore), an Apply writes one zip file and its .sha256 file @@ -1817,7 +2469,7 @@

    State-*, the journal Journal-*, the report data PhaseData-* and PhaseEvents-*, and the .sha256 files) are kept as they are and are never replaced or supplied by a package; a folder with any different or missing file of the package, or any other extra file, is refused, and nothing is left half-extracted. The normal flow then continues and every proof and hash check of the engine is unchanged: the package replaces the copy of the folders, not the verifications.

    +

    A package that passes its own checks but is refused afterwards, when the run loads it (an AD proof that does not match the backup, a file that differs from the originals with Transfer.RequireLocalOriginal, a backup that cannot be read), leaves nothing in the backup folder: the run removes exactly the files it extracted (checked by their SHA-256 against the package) and the folder they were in once it is empty, and puts back the markers of Backups\Imported as they were while they still hold what the import wrote, and says so in one line (The package was taken back). A folder that was already there is never deleted or changed, and a file that another run added or changed since the import (a journal, phase data) keeps its folder in place, with a warning that names it. A run that stops later (the domain controller, the confirmation) keeps the extracted folders for the next run, as before. A folder of the same batch that is already in Backups and is not the package (a leftover of an import that an older version refused, another package of the same batch, a copy by hand) is refused with its full name, and the Next steps give a Move-Item command that moves it aside to Backups\Refused-<name>-<time> (nothing is deleted) and the command to run again.

    PowerShell
    .\Invoke-PraRemoteMailbox.ps1 -Action Convert -Phase Cloud -Mode Apply -Batch 'PRA-PROD-Convert-490cc62e-for-Cloud.zip'
     
    +

    Who made the package? Fingerprint, originals, tenant and domain. The checksums above show that a package is complete and unchanged since it was made; they cannot show who made it, because anyone who can write the folder can write a package with its checksums made again. What the tool adds is information first, and a refusal only when you ask for one:

    +
      +
    • Fingerprint. The server that writes a package prints its fingerprint (the first 20 characters of the SHA-256 of the zip, in five groups of four, for instance 3FA9-C21B-07DE-55A0-91C4), and the server that reads it prints the fingerprint of what it received. Read the first one to the other operator by another channel than the one the package travels on (a call, a ticket), and compare; or give it to the import: -ExpectedFingerprint 3fa9c21b07de55a091c4 (any letter case, the dashes are optional). A package with another fingerprint is refused before anything is written. The Next steps of the server that wrote the package repeat the fingerprint and give the command for the other server with -ExpectedFingerprint already added: read that line to the other operator, who runs it. Without -ExpectedFingerprint the fingerprint is information only. The console shows it in the run output, as the command line does.
    • +
    • The originals kept here. The Finalize compares, at the point where it loads its files and before any restore or AD connection, what the AD server wrote itself with the originals kept in Backups\Batch-*, by content (SHA-256), the same way whether the input is a package, an extracted folder, a folder copied by hand or a console import. The files are the ones the Finalize really loads: it follows the manifest to the Convert backup and to the AD proof, the proof to the Recover backup, each backup to its raw capture, and takes the batch of each backup from the parsed backup, never from a guess in the text. Written by the AD server (and compared): the Convert backup, the Recover backup and the AD proof (State-*), each with its .sha256 file and, for a backup, its raw capture. Written by the cloud server (not comparable with an original kept here): the Finalize manifest, its .sha256 file and the report data (PhaseData-*, PhaseEvents-*). An original is a .json, .clixml or .sha256 file under a Batch-* folder of the Backups folder; the folder that holds the loaded files is never an original of itself, and neither is a Batch-* folder extracted from an imported package (the run leaves a marker for it in Imported). A Batch-* folder that someone copies back into the Backups folder by hand counts as an original: guard the Backups folder as the backups themselves. A Finalize manifest is read by id only from a Finalize-* folder. Per file: an identical file under any Batch-* folder is a match; if the server holds Batch-<that batch> and no identical file is in it, the file is different; if the server holds neither, it has no original. Only when every such file matches does the run say that they are identical to the originals. A difference, or a file with no original, is a warning; Transfer.RequireLocalOriginal turns both into a refusal. What the cloud manifest asks for (the objects, the restore flags) is checked by the Finalize against the matched originals before anything is restored; the origin of the manifest itself is only proved by the shared secret when it is on. The same rule covers a Finalize folder copied by hand: no .auth file can come with a folder, so with Transfer.RequireAuthentication on it is refused, and with Transfer.Authenticate on it is a warning, unless this server made the folder or a verified import left it (the run keeps a small Imported\<id>.verified.json for that, with the full path of the folder and the SHA-256 of its manifest and of its AD proof; it counts only for that folder at that path with those hashes, and a later valid verification replaces a weaker one, never the other way). The packages of a Convert or a Recover that the AD server imports (Convert -Phase AD -Batch <zip>, Recover -Phase AD -Batch <zip>) are not compared with originals: only the Finalize is. Limit: Transfer.RequireAuthentication covers packages, retention proofs and Finalize folders; a Batch-* folder copied by hand and used by the cloud phase (Convert -Phase Cloud, Recover -Phase Cloud, Check -Batch) cannot carry a .auth file and is not checked for one: import the package to have it checked.
    • +
    • Tenant and domain. These keys are not authenticated: a forged file can leave them out or copy them, so they catch a file that comes from another environment by mistake, not an attacker (only the shared secret, below, narrows that). A new backup, a new AD proof, a new package, a new Finalize manifest and a new retention proof record TenantId (when Cloud.TenantId is set), DomainSid and DomainDnsRoot (read from the domain controller). A file that records another tenant or domain than this run knows is a prominent warning (made for another tenant / domain); Transfer.RequireSameDomain turns it into a refusal. A file of an older version records none and is accepted without a word. The keys are written by the tool.
    • +
    • What the batch will use. A Recover and a Finalize take the licence group, the retention tag and, for a Finalize on a server without DomainController, the domain controller from the stored batch. The run compares the licence group and the tag with the configuration and prints one warning per difference; the question of the confirmation names the licence group and the domain controller. The domain controller that only the batch names is checked before the run connects to it: a name that is not a host name is not used (the run discovers a domain controller itself), and a name that the domain of this machine does not list as one of its domain controllers is a warning and is not used either (another domain controller of the same domain is normal and says nothing). When the domain cannot answer, the run goes on with a warning, and stops before it connects with Transfer.RequireConfigMatch. The licence group is compared by GUID (the configured group is resolved once): a renamed group is the same group, and a record whose DN no longer belongs to its GUID is reported. Transfer.RequireConfigMatch turns these warnings into a stop before the first write. Setting DomainController in the configuration file always wins over the name in a batch.
    • +
    +

    A package that was written by the shared secret has a .auth file next to it: see Files that travel between the two servers in chapter 6.

    +

    Carrying a package or a proof between the servers

    +

    The limit, said plainly. The .sha256 file of a package, the hashes inside the zip file and the .sha256 file of a retention proof detect damage and careless edits. They do not prove who made the package or the proof: anyone who can write to the folder where the file waits can write a package with its checksums computed again. This is the same limit as for the retention proof (chapter 6). Everything the tool adds is information first (the fingerprint, the comparison with the originals, the warnings), and a refusal only for what you switch on (chapter 6). The channel is yours: the tool treats it as one that it does not control, and does not require a type of channel.

    +

    A procedure that fits any channel (recommended, never required):

    +
      +
    1. Use a channel that only the two operators can write to: a share whose write access is limited to the two operators (never Everyone or a broad group), or removable media that the two operators hand over to each other.
    2. +
    3. Keep the originals on the sending server. Leave its Backups folder as it is: the Finalize compares the package with the files that this server wrote itself.
    4. +
    5. Compare the fingerprint by another channel, a call or a ticket, whenever the channel is not trusted, and give it to the import with -ExpectedFingerprint.
    6. +
    7. Avoid carrying a proof. With phase Both, or with a certificate sign-in, the retention check asks Exchange Online itself and no proof travels (chapter 6).
    8. +
    9. Add the shared secret (Transfer.Authenticate) when you want a check of origin on top of the checksum, and the protection at rest (Storage.Protect) when the package must not be readable on the way.
    10. +
    11. Delete the copies that you no longer need once the import is done (the share, the removable media), with your own procedure for sensitive data (Data handling).
    12. +
    +

    Cleaning up

    +

    .\Invoke-PraRemoteMailbox.ps1 -Action Cleanup lists what the tool left behind, and -Mode Apply deletes it. It is never automatic: no other action, no scheduled run and no -Force deletes anything. The Preview (the default) lists only: a table with the path, the kind, the age, the size and the reason of each item, then the totals; the Apply shows the same list, asks you to type the word CLEANUP (any letter case) and deletes the items one by one, with one line in the log for each. Any other answer, no console (a scheduled run, a redirected input) or -Force alone deletes nothing.

    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    KindWhat is listedMarks that must agree with its name
    Finished batcha Convert batch rolled back and verified (the AD proof of a complete Recover batch restores every object of it), or that never wrote to Active Directory (NOT-APPLIED.txt), older than Cleanup.OlderThanDays, with the Recover batch and the Finalize folders that carry the proof; the Convert folder is deleted firstfolder Batch-<id>, its backup file naming the same batch and Environment, its journal or proof
    Log, transcriptPRA_…_<8 hex>.log and .transcript.txt older than Cleanup.OlderThanDaysthe log holds the start of an audit; the transcript names itself
    ReportPRA_… .html and .csv of the reports folder older than thatthe page names the tool; the table starts with its header
    Generated configurationlogs\gui\run-<id>\effective.config.psd1 older than thatits first line
    Preview folderlogs\preview-<id> older than 24 hoursonly the folders of a package inside
    Exchange Online childpraexo_<id> files and folder in the temporary folder of the account, older than 24 hoursthe content of each file (the folder holds only child.ps1)
    +

    A batch is finished only when it is proven: a Recover proof lists every object as restored, the phase data of the Recover records its cloud part as complete for every object, no shared mailbox or retention tag waits for its final restore (the Finalize that does it has its own proof, kept in a batch folder of the AD server), and every Finalize package of the batch has been applied. A proof or a manifest is read only when its .sha256 file matches the file as it is stored. When one of these is not proven, the batch is kept and the list says rollback not finished (cloud or Finalize pending) with what is missing. If the folder of the Convert batch cannot be deleted, the folders that carry its proof are left alone and reported.

    +

    Protected batches. A batch written with Storage.Protect can be judged only by a run that has its key (Storage.KeyFile, Storage.CertificateThumbprint, or the passphrase given with -ProtectPassphrase). Without the key the batch is kept untouched, and the table and the log say why: a protected backup (Storage.Protect) that this run cannot read without its key with what is missing and the setting to give; run the Cleanup again with the key.

    +

    Never listed: a batch that is not finished (a Convert that is still in force, a Recover that restored only some objects or whose cloud part or final restore is not proven, a partial or missing proof, a proof that cannot be read), a folder or a file that has only the name, anything outside the backup, log and report folders of the configuration (the temporary files of the Exchange Online child excepted), and anything where a reparse point that redirects (junction, symbolic link, mount point) is on the way: the tag decides, as everywhere else in the tool. Every item is checked again just before it is deleted; one that changed since the list was made is left and counted. The files of the current run are never listed. The window keeps its own logs\gui folder (30 days). The console has no Cleanup page: it is a command-line action.

    +

    Data handling

    +

    What is written, and where. The tool writes personal and access-control data about the people in scope, in clear text unless you turn on the protection of the files at rest.

    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    WhereWhat it holdsWho should read it
    Backups\Batch-* (backup, journal, proof)every attribute of every object of the batch, as Active Directory returned it, with the two security descriptors of each object (nTSecurityDescriptor, msExchMailboxSecurityDescriptor) and the lists of holders of the shared mailboxesthe operators only
    Backups\Outbox, Backups\Inbox, the transfer packages and the retention proofsthe same batches in a zip file; a proof names the objects (GUID, UPN)the operators only; the channel is yours
    logs\ (log, transcript)names, addresses, DNs and values of the objects, and the run settings; the transcript can hold more when -Verbose or -Debug was onthe operators, and the people who audit
    reports\ (HTML, CSV, global report)one row per object and the permission map of the shared mailboxes (who has FullAccess, SendAs, SendOnBehalf)the operators, and the people who decide
    logs\gui\the effective settings of the runs started from the consoledeleted by the tool after 30 days
    The Windows event logidentifiers and counts only, no namewhoever reads your event log
    +

    Protect them. Keep Backups, logs and reports on a volume that your disk encryption protects (BitLocker or your own product), with read access limited to the operators (the tool creates them private: keep that, chapter 5). Back them up with your own backup product, with its own encryption, and never copy them to a share that ordinary users can read. When you want the tool itself to protect the backups and the packages, use Storage.Protect (chapter 6).

    +

    How long to keep them. Keep a batch until the rollback is finished and verified: the backup is the only way back. Then archive it as your policy says, or delete it: -Action Cleanup lists the finished batches, the old logs and the reports, and deletes them only when you type the word (Cleaning up). The tool deletes by itself only its own temporary files (the preview folder, the temporary folder of the Exchange Online child process, and the logs\gui folder of the window after 30 days); nothing else is ever deleted without your word. Set Retention.ProofMaxAgeHours to the length of your disaster window (default 24) so that a retention proof does not outlive it.

    +
    +

    Note

    +

    Data protection. The organisation that runs the tool is the controller of the data that the tool extracts and stores: the backups, the permission reports and the packages are personal and access-control data about its staff, and the purpose and the retention are for the organisation to decide and to justify (its register of processing, its disaster recovery plan). A tool that keeps every attribute of an object is more than a log of administrative actions. The project, for its part, receives nothing: the tool has no telemetry and sends no data to its author.

    +

    Batch size

    A batch of 5,000 objects is supported. The checks that grew with the square of the batch (the backup fingerprint recomputed for every write, the searches of the whole batch for each object, the console reading every batch file at every refresh) are gone: what is done for one object costs the same in a batch of 50 and in a batch of 5,000.

      @@ -1879,7 +2646,7 @@

      Code map

      PraRemoteMailbox.psd1, PraRemoteMailbox.psm1 -Module manifest (ModuleVersion, GUID, PowerShellVersion 7.5, explicit FunctionsToExport, no wildcard) and root module (package check, then PRA.Common and PRA.Directory). PRA.Cloud stays on demand (Graph before Exchange Online in the dedicated process) and PRA.Gui is for -Gui only. +Module manifest (ModuleVersion, GUID, PowerShellVersion 7.6, explicit FunctionsToExport, no wildcard) and root module (package check, then PRA.Common and PRA.Directory). PRA.Cloud stays on demand (Graph before Exchange Online in the dedicated process) and PRA.Gui is for -Gui only. module\PRA.Common.psm1 @@ -1995,7 +2762,7 @@

      PowerShell pitfalls met during ConvertFrom-Json of PowerShell 7 turns ISO 8601 strings into [DateTime] (CapturedUtc, CreatedUtc, Utc), so the byte-exact comparisons of the proofs fail -every read goes through ConvertFrom-PraJson (-DateKind String, PowerShell 7.5+); a test refuses any other ConvertFrom-Json in package\ +every read goes through ConvertFrom-PraJson (-DateKind String, PowerShell 7.6); a test refuses any other ConvertFrom-Json in package\ [IO.Directory]::CreateDirectory(path, security) and GetAccessControl(path) do not exist on .NET @@ -2034,7 +2801,7 @@

      The gate (no directory, no tenant)

      Requirements: Pester 5 or later and PSScriptAnalyzer 1.25.0 (machine-wide modules). Every test is mandatory: a skipped or missing test fails the gate.

      Release 3.0.0 (2026-11-05, signed and timestamped, PowerShell 7.5+): 764 tests, 764 passed, 0 analyzer error, about 80 minutes under pwsh 7.6 (the analyzer lists 1263 non-error diagnostics, among them the 7.5 additions that the PowerShell 7.0 profiles do not know). The gate of 2.3.0 under Windows PowerShell 5.1 was 506 tests; the extra tests are the PowerShell 7 engine, the review fixes, the 54 tests of the ordinal comparisons (tag Ordinal), the replay of the 2.2.0 fixtures and the 25 tests of the documentation (tests\PraDocumentation.Tests.ps1: pictures, private names, permissions against the code, readability of the user guide).

      Release 2.3.0 (2026-11-03, unreleased source, working tree not yet signed): 506 tests, 506 passed, 0 analyzer error; the native-state test accepts the fail-closed state of the unsigned package. Run the gate from a Windows PowerShell whose PSModulePath does not start with the PowerShell 7 module folders (the tests start powershell.exe children that inherit it).

      -

      Release 2.0.0 (2026-10-01, VMLLM): 279 tests, 279 passed, 0 analyzer error, about 12 minutes — evidence tests\evidence\gate\v2.0.0-release. The only analyzer warnings on the delivered files are expected: Write-Host in the console module (14, by design) and ConvertFrom-Markdown in the documentation builder (6, PowerShell 7 tool). Compared with the 325 tests of 1.3.6, the 61 combinations of the removed path options (-BackupFile, -StateFile, -LogPath, -TranscriptPath, -ReportDirectory) are replaced by 9 tests of -Batch and of the confirmation.

      +

      Release 2.0.0 (2026-10-01, OPS01): 279 tests, 279 passed, 0 analyzer error, about 12 minutes — evidence tests\evidence\gate\v2.0.0-release. The only analyzer warnings on the delivered files are expected: Write-Host in the console module (14, by design) and ConvertFrom-Markdown in the documentation builder (6, PowerShell 7 tool). Compared with the 325 tests of 1.3.6, the 61 combinations of the removed path options (-BackupFile, -StateFile, -LogPath, -TranscriptPath, -ReportDirectory) are replaced by 9 tests of -Batch and of the confirmation.

      The documentation and its pictures

      Two guides: the user guide (PraRemoteMailbox-UserGuide.md, plain words, one picture per step) and this reference guide. Both are built into one HTML file each, with a light and a dark theme:

      PowerShell
      pwsh -NoProfile -File .\tools\New-DocumentationImages.ps1   # every picture, then the two HTML guides (needs Microsoft Edge)
      @@ -2065,6 +2832,60 @@ 

      The lab campaign

      +Security.RequireProtectedFolders is on and N location(s) are not protected +the option of chapter 6 is on and a folder of the tool can be changed or read by other accounts: the Apply stopped before it wrote anything +run the icacls commands of the message in a window opened as administrator, then start the same command again; or turn the option off + + + +Folder permissions: … (warning) +other accounts can change or read a folder or a file of the tool +run the icacls command of the warning (every location is in the log), or list your own administrators in Security.AcceptedWriterSids + + + +The file '…' is protected and this run cannot read it +the file was written with Storage.Protect and this run has not its key +the message says which: the certificate with the thumbprint it names and its private key (in CurrentUser\My or LocalMachine\My of this account), Storage.KeyFile set to the key file that protected it, or the passphrase (type it, or -ProtectPassphrase). A run does not need Storage.Protect to read; it needs the key + + + +The file '…' cannot be opened: the passphrase or the key file of this run is not the one that protected it / … was changed or damaged (its authentication tag does not match) +another passphrase or key file, or a file that was changed, cut or damaged +give the right key; copy the file again from its source (the .sha256 file tells whether the copy is the one that was written); a file that fails its tag is never used + + + +The file … is not readable with the current key: it is left out of the search for the batch of an object +a search of the backup folder (the batch of an object, the Recover that rolled a batch back) met a protected file and this run has not its key +give the run the key that protects it (Storage.KeyFile, the certificate with its private key, or -ProtectPassphrase) and run again: a batch that only that file proves can be missed until then + + + +The private key of the certificate … cannot be exported +a warning: the certificate works, but its private key exists only on this computer +create a certificate with an exportable key and keep a copy away from the backups (the warning gives the commands), or use a key file + + + +Storage.Protect = Certificate, but the certificate … is not in CurrentUser\My or LocalMachine\My / has no RSA key / has no private key available to this account +the certificate of the setting cannot protect or read files here +import the certificate with its private key for this account, or fix the thumbprint; an Apply stops before it writes anything + + + +N file(s) cannot be compared with the originals kept on this server: a protected file cannot be read with the key of this run +the Finalize found protected files that this run cannot decrypt: they are not known to differ +give the run the key (see above); with Transfer.RequireLocalOriginal the Finalize is refused until then + + + +Package integrity: reparse point that is not accepted (tag 0x…) +the package is behind a junction, a symbolic link or a mount point, or a type of reparse point that the tool does not know +install the package in a plain folder, or in a OneDrive folder whose files are downloaded + + + Batch <id> not found under ... the batch folder is not in Storage.BackupFolder copy the whole Batch-... / Finalize-... folder there, or give the path of the JSON file @@ -2083,6 +2904,54 @@

      The lab campaign

      +N file(s) differ from the originals kept on this server, which holds the batch they name: … or N file(s) have no original on this server … (warning) +a file that the AD server wrote itself and that the Finalize loads is not identical, by content, to the original kept in Backups\Batch-*, or this server holds no such original +compare with the Batch-* folder it came from, check the fingerprint with the other server, or copy the package again; Transfer.RequireLocalOriginal makes both a refusal + + + +The AD proof does not match this Convert backup / The AD proof does not match its backup +a backup or a package was changed after the proof was made (even with its checksums made again), or the proof belongs to another batch (when a package is being read, what the run extracted is taken back, as long as another run has not used those files, and nothing else stays in the backup folder) +do not use these files: copy the transfer package again from the server that wrote it and compare its fingerprint with the one that server printed; for a batch folder that was not read from a package, restore the folder from a copy that you trust + + + +Transfer package: the folder … already exists and is different from the package: refused +a folder of the same batch is in Backups and is not this package (an import that an older version refused, another package of the same batch, a copy by hand) +the Next steps name the folder and give the Move-Item command that moves it aside, then the command to run again + + + +The fingerprint of this package is …, not the one given with -ExpectedFingerprint +the package that was read is not the one the other server announced +copy it again from the server that wrote it; the fingerprint to expect is in its Next steps and log + + + +This … records another tenant (or domain) than this run knows (warning) +a backup, package or proof made for another tenant or domain +check the server and the configuration file; Transfer.RequireSameDomain makes it a refusal + + + +The batch changes the membership of the licence group …, and Licensing.GroupDN of this configuration is … (warning) +the batch names a licence group (or retention tag, or domain controller) that is not the one of the configuration +read the group with the command of the message; correct the configuration or use the right batch; Transfer.RequireConfigMatch makes it a stop + + + +… has no .auth file, … does NOT match (warning) +the shared secret is on and the file has no valid .auth file +copy the .auth file next to it; check that both servers use the same passphrase or key file; Transfer.RequireAuthentication makes it a refusal + + + +Retention.RequireLiveCheck is on: … +the run could not ask Exchange Online and no proof is read +set the certificate sign-in, or run at a console without -Force, or turn the setting off + + + N of the M object(s) changed since this batch left them (warning) a Recover found attributes that are neither as the Convert left them nor as they were before it (an address added during the disaster, a later Convert of the same object) read the PLANNED values of the objects named above: the saved values are put back over what is there now. Nothing is blocked @@ -2319,7 +3188,7 @@

      The lab campaign

      -Action is missing: nothing was done the command has no -Action -always give -Action Convert, Recover, Finalize or Check (the tool no longer waits for an answer at a prompt) +always give -Action Convert, Recover, Finalize, Check or Cleanup (the tool no longer waits for an answer at a prompt) @@ -2434,8 +3303,8 @@

      The lab campaign

      In short: What was tested in a lab, and what is still to replay for 3.0.0.

      -

      Lab Active Directory domain (two domain controllers DC1 and DC2, Entra Connect on AADC, Exchange servers stopped = disaster), Microsoft 365 test tenant, operator account LAB\pra-operator, certificate sign-in. Objects of OU=PRA-PILOT-OU: pra-user04, pra-user05 (user mailboxes), pra-shared02, pra-shared03 (shared mailboxes, 3 FullAccess + 3 SendAs each).

      -

      All runs were made with the real script on VMLLM (Windows PowerShell 5.1), against the real directory, the real Entra Connect server and the real tenant. Result: 28 runs: 26 PASS, and 2 runs (T17, T18) that found defects 3 and 4, fixed since and covered by the gate (list below).

      +

      Lab Active Directory domain (two domain controllers DC01 and DC02, Entra Connect on SYNC01, Exchange servers stopped = disaster), Microsoft 365 test tenant, operator account CONTOSO\pra-operator, certificate sign-in. Objects of OU=PRA-PILOT-OU: pra-user04, pra-user05 (user mailboxes), pra-shared02, pra-shared03 (shared mailboxes, 3 FullAccess + 3 SendAs each).

      +

      All runs were made with the real script on OPS01 (Windows PowerShell 5.1), against the real directory, the real Entra Connect server and the real tenant. Result: 28 runs: 26 PASS, and 2 runs (T17, T18) that found defects 3 and 4, fixed since and covered by the gate (list below).

      @@ -2608,12 +3477,12 @@

      The lab campaign

    • (transcripts of T3 and T9) Before each FullAccess grant, the normal "No permissions were found" answer appeared as a TerminatingError line in the transcript. Fix: read through -ErrorVariable; T16 and T17c: 0 such line.
    • The lab was left as before the tests: T16 test material removed (groups deleted, msExchMailboxSecurityDescriptor identical to its copy taken before the test, publicDelegates empty), pra-shared03 back on-premises.

      -

      Lab fixes made before the campaign (outside the tool): domain controller DC2 had not replicated from DC1 since 2026-09-18 (Kerberos 0x80090322, stale KDC ticket); fixed by purging the tickets of the computer account and forcing the replication. Account LAB\pra-operator and the lab application (annex C) were created for the campaign.

      +

      Lab fixes made before the campaign (outside the tool): domain controller DC02 had not replicated from DC01 since 2026-09-18 (Kerberos 0x80090322, stale KDC ticket); fixed by purging the tickets of the computer account and forcing the replication. Account CONTOSO\pra-operator and the lab application (annex C) were created for the campaign.

      Lab revalidation of the PowerShell 7 engine (3.0.0)

      -

      3.0.0 has offline validation only (the gate, which replays the files written by the real 2.2.0 under Windows PowerShell 5.1: tests\PraLegacyFixtures.Tests.ps1, 23 checks on the fixtures frozen in tests\fixtures\ps51-2.2.0). Before any use in production, replay on the lab, with PowerShell 7.5+:

      +

      3.0.0 has offline validation only (the gate, which replays the files written by the real 2.2.0 under Windows PowerShell 5.1: tests\PraLegacyFixtures.Tests.ps1, 23 checks on the fixtures frozen in tests\fixtures\ps51-2.2.0). Before any use in production, replay on the lab, with PowerShell 7.6:

        -
      1. Prerequisites on each lab server: pwsh 7.5+, RSAT ActiveDirectory (Get-Module ActiveDirectory -ListAvailable shows Core), ExchangeOnlineManagement 3.10+ and Microsoft.Graph 2.x installed for PowerShell 7, the application certificate reachable.
      2. +
      3. Prerequisites on each lab server: pwsh 7.6, RSAT ActiveDirectory (Get-Module ActiveDirectory -ListAvailable shows Core), ExchangeOnlineManagement 3.10+ and Microsoft.Graph 2.x installed for PowerShell 7, the application certificate reachable.
      4. Restoration of a real 2.2.0 history (acceptance test of the compatibility promise): Recover (AD phase, then cloud phase, then Finalize on two servers) of a Convert batch produced by 2.2.0 under Windows PowerShell 5.1 in the lab, and Check on that batch.
      5. Convert Preview and Apply, users and shared mailboxes (FullAccess, SendAs, SendOnBehalf); Recover; Retention / RestoreTag; Finalize.
      6. Entra Connect: a Delta cycle started locally on the Entra Connect server (ADSync loaded through the Windows PowerShell compatibility layer: check the Result and SyncCycleInProgress values), a cycle started remotely with EntraConnect.Server from the AD server, and EntraConnect.Sync = $false.
      7. @@ -2690,6 +3559,11 @@

        Lab revalidation of t

      + + + + + @@ -2715,7 +3589,8 @@

      Lab revalidation of t

      In short: What changed between versions and how to upgrade.

      -

      From 2.x to 3.0.0. Install PowerShell 7.5+ and the AD, Exchange Online and Graph modules for PowerShell 7 (chapter 4); replace the package folder; keep Backups\ and the configuration file (same format; nothing to change); run the commands with pwsh (and change the action of scheduled tasks from powershell.exe to pwsh.exe, chapter 7). Windows PowerShell 5.1 and PowerShell 7.4 are refused before any code runs. The 2.2.x package remains the Windows PowerShell 5.1 version and is the fallback on a server that cannot have PowerShell 7; both versions read the backups of the other.

      +

      Which versions are supported. Only the latest release receives fixes. A fix is a new version that replaces the package folder: the files of a published release never change. To be told of a new version or of a security advisory, watch the repository on GitHub (releases and security advisories); once a newer version is out, the notes of the replaced release start with a notice that it is not the latest. Older versions, the 2.2.x line included, receive no fix. No support period is promised: this is a personal project, provided AS-IS (SECURITY.md).

      +

      From 2.x to 3.0.0. Install PowerShell 7.6 and the AD, Exchange Online and Graph modules for PowerShell 7 (chapter 4); replace the package folder; keep Backups\ and the configuration file (same format; nothing to change); run the commands with pwsh (and change the action of scheduled tasks from powershell.exe to pwsh.exe, chapter 7). Windows PowerShell 5.1 and PowerShell 7.5 or earlier are refused before any code runs. The 2.2.x package remains the Windows PowerShell 5.1 version and is the fallback on a server that cannot have PowerShell 7; both versions read the backups of the other.

      • One source: $script:ToolVersion in module\PRA.Common.psm1, exported as Get-PraToolVersion. The entry script (run context, report, audit, log), the window (title) and the package builder (tools\New-PraPackage.ps1, which reads that line as text) take the version from it. Nothing else in the code carries a version literal.
      • Literals that cannot be computed (the signature and the manifest hash the exact bytes, so a comment cannot be generated at run time). Change them together with the source, in the same commit; tests\PraRemoteMailbox.Tests.ps1 fails if one differs: @@ -2728,10 +3603,11 @@

        Lab revalidation of t
      • the repository-only headers Version of tools\New-PraPackage.ps1, tools\Build-Documentation.ps1, tests\Invoke-TestGate.ps1, tests\IntegrityFixture.ps1, tests\PackageIntegrity.Tests.ps1, tests\PraRemoteMailbox.Tests.ps1, tests\PraReport.Tests.ps1.
      -
    • Release checklist: gate PASS · lab campaign (annex B) · pwsh tools\New-DocumentationImages.ps1 (PowerShell 7.5+, Microsoft Edge, documentation only: every picture of the README and the guides, then the two HTML guides) · owner signature and manifest (below) · tools\New-PraPackage.ps1 · git tag vX.Y.Z.
    • +
    • Release checklist: gate PASS · lab campaign (annex B) · pwsh tools\New-DocumentationImages.ps1 (PowerShell 7.6, Microsoft Edge, documentation only: every picture of the README and the guides, then the two HTML guides) · owner signature and manifest (below) · tools\New-PraPackage.ps1 · git tag vX.Y.Z.
    • Signature and manifest after a change. Editing a signed or hashed file invalidates its signature or hash, and the package then refuses to start (by design). The owner (1) signs, with the timestamp, every PowerShell file of the inventory (Invoke-PraRemoteMailbox.ps1, PraRemoteMailbox.psd1, PraRemoteMailbox.psm1, module\PRA.Common.psm1, PRA.Directory.psm1, PRA.Backup.psm1, PRA.Cloud.psm1, PRA.Gui.psm1, PRA.Gui.Directory.ps1, Test-PackageIntegrity.ps1); (2) regenerates PackageIntegrity.psd1 with the SHA256 of every inventory file taken from the final signed bytes (the hash of a signed script includes its signature block, so it cannot be computed before signing), then signs the manifest; (3) runs the gate and tools\New-PraPackage.ps1. The gate and the Pester suites also pass on an unsigned working tree (the native-state tests accept the fail-closed state); tools\New-PraPackage.ps1 and the CI Package stage refuse an unsigned or changed source.
    • From 3.1.x to 3.2.0. The configuration file keeps working (new optional settings: Cloud.IdentityCheck, Cloud.RetryBudgetObjectSeconds, Cloud.RetryBudgetRunMinutes, Retention.CheckBeforeRecover and Retention.ProofMaxAgeHours). A Recover now checks retention first and stops when it is not covered: see the Retention section for -AcceptRetentionRisk and the retention proof of a two-server setup. 3.2.0 reads Microsoft Graph for every object, shared mailboxes and runs without a licence check included, to confirm the account of the object and of each trustee: the permission User.Read.All (delegated, with the consent of the signing-in administrator; or application, with admin consent) must therefore be in place for every run of the cloud part, not only for the licence checks. A refusal by Graph (403, insufficient privileges) stops the object with a message that names the permission. The alternative is Cloud.IdentityCheck = 'Off', which finds the accounts by UPN only and reads nothing for this purpose (a tenant whose source anchor is neither the objectGUID nor ms-DS-ConsistencyGuid needs it). Batches and backups of 3.1.x are read as before.

      +

      From 3.2.x to 3.3.0. PowerShell 7.6 is required: Windows PowerShell 5.1 and PowerShell 7.5 are refused before any code runs, so install PowerShell 7.6 LTS (chapter 4) before you replace the package folder. Nothing else is imposed: the backups, the proofs, the packages and the configuration files of 3.2.x and of every older version are read as before, and every new setting is optional (a configuration without them behaves as 3.2.0, a new check warns first, and a refusal exists only behind a setting that you switch on). The new settings are Transfer.*, Storage.Protect, Storage.CertificateThumbprint, Storage.KeyFile, Security.*, Cleanup.OlderThanDays, Logging.WindowsEvents, Logging.JournalChain, Logging.RequireJournalChain, Logging.TimestampOffset, Retention.RequireLiveCheck, Exo.ChildStart and Console.NetworkProbes (chapter 6). What you will notice: the log header lists the versions and paths in use; an Apply run as administrator registers the Windows event source (Logging.WindowsEvents = 'Off' prevents it); a warning names a folder that other accounts can write or read, with the command that closes it; the Preview of the AD part warns of the objects that Active Directory is likely to refuse; -Action Cleanup is new; and the HTML reports carry a Content-Security-Policy.

      From 1.3.6: keep the old Backups folders; copy the values of DRP-Config.psd1 into the new file (same sections; ADConnect → EntraConnect; BackupFolder/LogFolder/ReportFolder → Storage/Logging/Report; Safety → Storage.ForbiddenBackupRoots); keep the same Environment to use the old batches. Command mapping: see CHANGELOG.md (table "Changed").

      Annex F

      Code review 2026-09-30

      @@ -2818,7 +3694,7 @@

      Lab revalidation of t

      every attribute returned by AD, closed descriptors (no native object)
      Protected file (optional, Storage.Protect)envelope version 1, any of the files above except the journalsthe 7 bytes PRAPROT, version, mode (1 certificate, 2 passphrase, 3 key file), chunk size (1 MiB), a 12-byte nonce, then the thumbprint and the RSA-OAEP-wrapped key, or the 16-byte salt (with the iteration count for a typed passphrase), then 8 bytes that tell a wrong key from a changed file (the key of the chunks and the key of that check are two keys derived from the master key with HKDF-SHA-256, one label each); then chunks of AES-256-GCM (ciphertext and 16-byte tag), each authenticating the header, its number and whether it is the last. A clear file is read as before.
      AD proof State-<id>.json schema 2 Kind = ADVerified, BackupFile + BackupHash, Records[] (ObjectGuid, Operation, VerifiedUsnChanged); a Convert batch that stopped at its first error has Partial = true and PlannedCount (the number of objects planned), and lists only the objects verified

      No defect was found in the backup, receipt and proof engine; its logic is unchanged in 2.0.0 and covered by the gate.

    -
    PRA Remote Mailbox 3.2.0 · Nicolas Fabert · generated 2026-11-22 04:54 from PraRemoteMailbox-Guide.md
    +
    PRA Remote Mailbox 3.3.0 · Nicolas Fabert · generated 2026-11-27 12:06 from PraRemoteMailbox-Guide.md
    & "q"' }) | Should -BeExactly '<script>alert("x")</script> & "q"' + (InModuleScope PRA.Common -Parameters @{ Text = "a$([char]27)[31mb$([char]0x202E)c`r`nd" } { param($Text) Get-PraSafeText $Text }) | Should -BeExactly 'a?[31mb?c??d' + } +} + +Describe 'Release 3.3.0 - an existing folder keeps the rights it has and the exposure check reports it (production Common module, synthetic folders)' -Tag 'Release330a' { + BeforeAll { Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global } + It 'leaves an Inbox that someone made before, with rights for Everyone, as it is, reports it in the exposure check, and reads a proof put in it' { + $backups = Join-Path $global:PraGate.Root ('limits-inbox-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) + $inbox = Join-Path $backups 'Inbox' + $null = New-Item -ItemType Directory -Path $inbox -Force + $info = New-Object IO.DirectoryInfo $inbox + $acl = [IO.FileSystemAclExtensions]::GetAccessControl($info) + $everyone = New-Object Security.Principal.SecurityIdentifier('S-1-1-0') + $null = $acl.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule($everyone, [Security.AccessControl.FileSystemRights]::Modify, ([Security.AccessControl.InheritanceFlags]'ContainerInherit,ObjectInherit'), [Security.AccessControl.PropagationFlags]::None, [Security.AccessControl.AccessControlType]::Allow))) + [IO.FileSystemAclExtensions]::SetAccessControl($info, $acl) + $output = @(Initialize-PraPrivateFolder -Path $inbox 3>&1 4>&1 5>&1 6>&1) + $output.Count | Should -Be 0 + $after = [IO.FileSystemAclExtensions]::GetAccessControl((New-Object IO.DirectoryInfo $inbox)) + $everyoneRules = @($after.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier]) | Where-Object { $_.IdentityReference.Value -eq 'S-1-1-0' -and $_.AccessControlType -eq 'Allow' }) + $everyoneRules.Count | Should -BeGreaterThan 0 + $after.AreAccessRulesProtected | Should -BeFalse + $exposure = Get-PraFolderExposure -Root $backups -Config @{ Storage = @{ BackupFolder = $backups }; Security = @{ AcceptedWriterSids = @() } } -Available @() -PowerShellHome (Join-Path $global:PraGate.Root 'none') + @($exposure.Findings | Where-Object { $_.Role -ceq 'Inbox folder' -and $_.Kind -ceq 'Write' -and $_.Sids -contains 'S-1-1-0' }).Count | Should -Be 1 + $batchId = 'dddddddd44444444dddddddd44444444' + $null = Write-PraRetentionProof -Folder $inbox -BatchId $batchId -SourceBackupHash '' -Environment 'PROD' -Object @([pscustomobject]@{ ObjectGuid = '00000000-0000-0000-0000-000000000001'; Upn = 'user1@contoso.invalid'; Verdict = 'Covered' }) + $answer = Get-PraRetentionProof -Folder @($inbox) -BatchId $batchId -Environment 'PROD' -MaxAgeHours 24 -Row @([pscustomobject]@{ ObjectGuid = '00000000-0000-0000-0000-000000000001'; UserPrincipalName = 'user1@contoso.invalid' }) + $answer.Found | Should -BeTrue -Because $answer.Reason + } +} + +Describe 'Release 3.3.0 - the journal and the phase events when a file is cut or written by someone else, documented as they are today (production Directory and Common modules, synthetic folders)' -Tag 'Release330a' { + BeforeAll { Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global } + It 'documents a known limit of a journal without the optional chain: a journal line that was cut by a crash and a line of garbage are the same one skipped line, and a complete line that someone inserted counts as a write of its object (the chain names them: see the journal chain tests)' { + $first = '{"RunId":"r","Utc":"u","Target":"AAAAAAAA-0000-0000-0000-000000000001","Operation":"Set-ADUser","Status":"Started","Detail":""}' + $torn = '{"RunId":"r","Utc":"u","Target":"AAAAAAAA-0000-0000-0000-000000000002","Operation":"Set-ADUser","Sta' + $inserted = '{"RunId":"forged","Utc":"u","Target":"AAAAAAAA-0000-0000-0000-000000000003","Operation":"Set-ADUser","Status":"Started","Detail":""}' + $cases = [ordered]@{ + Torn = @($first, $torn) + Garbage = @($first, 'not a journal line at all') + Inserted = @($first, $inserted) + } + $results = @{} + try { + foreach ($name in $cases.Keys) { + $path = Join-Path $global:PraGate.Root ('limits-journal-' + $name + '-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.jsonl') + [IO.File]::WriteAllText($path, (($cases[$name] -join "`r`n") + "`r`n"), (New-Object Text.UTF8Encoding($false))) + $global:PraGate.L330Journal = $path + $results[$name] = InModuleScope PRA.Directory { + $skipped = 0 + $set = Get-PraJournalTouchedObject -Path $global:PraGate.L330Journal -SkippedCount ([ref]$skipped) + @{ Set = (@($set | Sort-Object) -join ','); Skipped = $skipped } + } + } + } + finally { $global:PraGate.Remove('L330Journal') } + $results.Torn.Skipped | Should -Be 1 + $results.Garbage.Skipped | Should -Be $results.Torn.Skipped -Because 'a cut line and a line of garbage are not told apart' + $results.Torn.Set | Should -BeExactly 'AAAAAAAA-0000-0000-0000-000000000001' + $results.Inserted.Skipped | Should -Be 0 + $results.Inserted.Set | Should -BeExactly 'AAAAAAAA-0000-0000-0000-000000000001,AAAAAAAA-0000-0000-0000-000000000003' -Because 'a complete line is believed whoever wrote it' + } + It 'reads a phase record whose events file was cut without the checksums being made again as a record without steps, and documents a known limit: an events file cut at a line, with every checksum made again, is read without a word' { + $root = Join-Path $global:PraGate.Root ('limits-phase-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) + $folder = Join-Path $root 'batch'; $null = New-Item -ItemType Directory -Path $folder -Force + $context = @{ Root = $global:PraGate.Package; Version = '3.2.0'; RunId = ((Get-Date -Format 'yyyyMMdd_HHmmss') + '-' + [guid]::NewGuid().ToString('N')); StartTime = Get-Date; Action = 'Convert'; Mode = 'Apply'; Phase = 'AD' + CurrentPhase = 'Start'; CurrentOperation = ''; CurrentIdentity = ''; StepIndex = 0; StepTotal = 0; Warnings = 0; Issues = (New-Object 'Collections.Generic.List[object]'); Rows = (New-Object 'Collections.Generic.List[object]') + Server = 'dc01.contoso.invalid'; Config = @{ Environment = 'GATE' }; AllowMutation = $true; ReportFolder = (Join-Path $root 'reports'); NoReport = $true; BatchId = 'abcd1234'; LogFile = ''; NextSteps = @(); ExitCode = 0; CloudConnectFailed = $false; ResultStatus = ''; PhaseFolders = @(); ConfigOverrides = @{} } + $guid = [guid]::NewGuid().ToString() + $context.Rows.Add([pscustomobject]@{ ObjectGuid = $guid; SamAccountName = 'alice'; UserPrincipalName = 'alice@contoso.invalid'; Action = 'Convert'; IsShared = $false; ADApplied = $true; ADVerified = $true; BackupPath = 'D:\x.json'; CloudStatus = 'N/A'; CloudDetail = ''; FinalStatus = 'Pending'; Detail = 'd'; Warnings = 0 }) + Register-PraObjectName $context $guid 'alice@contoso.invalid' + $context.CurrentIdentity = $guid + Write-PraStep -Context $context -Title 'Backup and Active Directory changes' | Out-Null + foreach ($i in 1..12) { Write-PraItem -Context $context -Status Ok -Text ('step {0}' -f $i) } + $dataFile = Save-PraPhaseData -Context $context -Folder $folder + $eventsFile = Join-Path $folder (([IO.Path]::GetFileName($dataFile)) -replace '^PhaseData-', 'PhaseEvents-' -replace '\.json$', '.jsonl') + $whole = Read-PraPhaseData -Folder @($folder) -Environment 'GATE' + $whole.Problems.Count | Should -Be 0 + $stepsOf = { param($Read) @(@($Read.Phases[0].Objects)[0].Steps).Count } + $all = & $stepsOf $whole + $all | Should -BeGreaterThan 4 + $utf8 = New-Object Text.UTF8Encoding($false) + $lines = @([IO.File]::ReadAllLines($eventsFile)) + $original = [IO.File]::ReadAllBytes($eventsFile) + [IO.File]::WriteAllBytes($eventsFile, $original[0..([int]($original.Length * 0.6))]) + $cut = Read-PraPhaseData -Folder @($folder) -Environment 'GATE' + $cut.Phases.Count | Should -Be 1 + [string]$cut.Phases[0].EventsProblem | Should -Match 'checksum of the events file does not match' + $keep = [int][Math]::Floor($lines.Count / 2) + [IO.File]::WriteAllText($eventsFile, (($lines[0..($keep - 1)] -join "`n") + "`n"), $utf8) + $newHash = (Get-FileHash -LiteralPath $eventsFile -Algorithm SHA256).Hash.ToLowerInvariant() + [IO.File]::WriteAllText($eventsFile + '.sha256', $newHash, $utf8) + $header = [IO.File]::ReadAllText($dataFile) + $oldHash = [regex]::Match($header, '"Events":\{[^}]*"Sha256":"([0-9a-f]{64})"').Groups[1].Value + $oldHash.Length | Should -Be 64 + [IO.File]::WriteAllText($dataFile, $header.Replace($oldHash, $newHash), $utf8) + [IO.File]::WriteAllText($dataFile + '.sha256', (Get-FileHash -LiteralPath $dataFile -Algorithm SHA256).Hash.ToLowerInvariant(), $utf8) + $forged = Read-PraPhaseData -Folder @($folder) -Environment 'GATE' + $forged.Problems.Count | Should -Be 0 + [string]$forged.Phases[0].EventsProblem | Should -BeExactly '' + (& $stepsOf $forged) | Should -BeLessThan $all + $forged.Phases[0].EventLinesSkipped | Should -Be 0 + } +} + +Describe 'Release 3.3.0 - the command line applies the configuration of the moment and says nothing about a change since the Preview, documented as it is today (real main, synthetic AD and cloud barrier)' -Tag 'Release330a' { + It 'documents a known limit: a Preview, a change of the configuration file, then an Apply from the command line: the Apply runs with the changed file and no line says that the file changed' { + $runtime = New-GateRuntime -Name 'limits-config' + $preview = Invoke-GateProcess $runtime @{Action='Convert';Phase='AD';Mode='Preview';ConfigPath=$runtime.ConfigPath} -TimeoutSeconds 120 + $preview.ExitCode | Should -BeIn @(0, 2) + @(Get-GateWrites $runtime).Count | Should -Be 0 + Set-GateConfigText $runtime { param($text) $text.Replace("Value='Converted'", "Value='ChangedAfterPreview'") } + $apply = Invoke-GateProcess $runtime @{Action='Convert';Phase='AD';Mode='Apply';Force=$true;ConfigPath=$runtime.ConfigPath} -TimeoutSeconds 120 + $apply.ExitCode | Should -BeIn @(0, 2) + @(Get-GateWrites $runtime).Count | Should -BeGreaterThan 0 + $apply.Output | Should -Not -Match '(?i)configuration[^.]{0,60}(changed|modified)|(changed|modified)[^.]{0,60}since the preview' + (@($apply.MainResult.Issues | ForEach-Object { [string]$_.Message }) -join ' ') | Should -Not -Match '(?i)(changed|modified)' + } +} + +Describe 'Release 3.3.0 - the runtime report: versions and paths in the log and the report, one warning for an old patch level, never a refusal (production Common module)' -Tag 'Release330B' { + BeforeAll { + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global + Register-PraTestProxy PRA.Common 'Get-PraRuntimeReport' + $script:Installed = @( + [pscustomobject]@{ Name = 'ExchangeOnlineManagement'; Version = [version]'3.10.1'; ModuleBase = 'C:\Synthetic\Modules\ExchangeOnlineManagement\3.10.1' } + [pscustomobject]@{ Name = 'Microsoft.Graph.Authentication'; Version = [version]'2.41.1'; ModuleBase = 'C:\Synthetic\Modules\Microsoft.Graph.Authentication\2.41.1' } + [pscustomobject]@{ Name = 'Microsoft.Graph.Users'; Version = [version]'2.41.1'; ModuleBase = 'C:\Synthetic\Modules\Microsoft.Graph.Users\2.41.1' } + ) + $script:NewRunContext = { + param([string]$LogFile) + @{ StepIndex = 0; StepTotal = 4; Issues = (New-Object 'Collections.Generic.List[object]'); Warnings = 0; LogFile = $LogFile; Action = 'Convert'; CurrentPhase = ''; Config = @{ Exo = @{ MinModuleVersion = '3.10.1' } } } + } + } + It 'records the version and the path of PowerShell and of the three modules, and warns about nothing on a current PowerShell 7.6' { + $report = Get-PraRuntimeReport -PowerShellVersion ([version]'7.6.9') -PowerShellHome 'C:\Synthetic\PowerShell\7' -Available $script:Installed + @($report.Lines).Count | Should -Be 4 + $report.Lines[0] | Should -BeExactly 'PowerShell 7.6.9 (C:\Synthetic\PowerShell\7)' + $report.Lines[1] | Should -BeExactly 'ExchangeOnlineManagement 3.10.1 (C:\Synthetic\Modules\ExchangeOnlineManagement\3.10.1)' + $report.Lines[2] | Should -BeExactly 'Microsoft.Graph.Authentication 2.41.1 (C:\Synthetic\Modules\Microsoft.Graph.Authentication\2.41.1)' + $report.Lines[3] | Should -BeExactly 'Microsoft.Graph.Users 2.41.1 (C:\Synthetic\Modules\Microsoft.Graph.Users\2.41.1)' + @($report.Warnings).Count | Should -Be 0 + } + It 'says warning(s) for PowerShell , by version comparison against the table of the first fixed release of each line' -ForEach @( + @{ Version = '7.6.7'; Expect = 1; Match = @('older than 7.6.8, the first 7.6 release with a published security fix') } + @{ Version = '7.6.0'; Expect = 1; Match = @('older than 7.6.8') } + @{ Version = '7.6.8'; Expect = 0; Match = @() } + @{ Version = '7.6.10'; Expect = 0; Match = @() } + @{ Version = '7.7.0'; Expect = 0; Match = @() } + ) { + $report = Get-PraRuntimeReport -PowerShellVersion ([version]$Version) -PowerShellHome 'C:\Synthetic\PowerShell\7' -Available $script:Installed + @($report.Warnings).Count | Should -Be $Expect -Because (@($report.Warnings) -join ' | ') + foreach ($fragment in $Match) { (@($report.Warnings) -join ' | ') | Should -BeLike ('*' + $fragment + '*') } + (@($report.Warnings) -join ' | ') | Should -Not -BeLike '*older than 7.6 LTS*' + } + It 'names a module that is not installed and still raises no warning for it' { + $report = Get-PraRuntimeReport -PowerShellVersion ([version]'7.6.9') -PowerShellHome 'C:\Synthetic\PowerShell\7' -Available @() + $report.Lines[1] | Should -BeExactly 'ExchangeOnlineManagement: not installed' + @($report.Warnings).Count | Should -Be 0 + } + It 'keeps the thresholds in one table: the first fixed release of the supported line' { + $policy = InModuleScope PRA.Common { $script:PraRuntimePolicy } + $policy.ContainsKey('Recommended') | Should -BeFalse + $policy.ContainsKey('ExoNeedsPowerShell') | Should -BeFalse + (@($policy.Lines | ForEach-Object { $_.Line + '=' + $_.FixedFrom }) -join ',') | Should -BeExactly '7.6=7.6.8' + } + It 'gives the same texts under a French culture' { + $before = [Threading.Thread]::CurrentThread.CurrentCulture + try { + [Threading.Thread]::CurrentThread.CurrentCulture = [Globalization.CultureInfo]::GetCultureInfo('fr-FR') + $report = Get-PraRuntimeReport -PowerShellVersion ([version]'7.6.5') -PowerShellHome 'C:\Synthetic\PowerShell\7' -Available $script:Installed + @($report.Warnings).Count | Should -Be 1 + $report.Lines[0] | Should -BeExactly 'PowerShell 7.6.5 (C:\Synthetic\PowerShell\7)' + } + finally { [Threading.Thread]::CurrentThread.CurrentCulture = $before } + } + It 'writes the lines in the log header, keeps them for the report footer and raises ONE warning that does not change the exit code' { + $log = Join-Path $global:PraGate.Root ('runtime-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.log') + $context = & $script:NewRunContext $log + $null = Write-PraRuntimeReport -Context $context -Available $script:Installed 6>$null + $text = [IO.File]::ReadAllText($log) + $text | Should -Match 'Runtime: PowerShell \d+\.\d+\.\d+ \(' + $text | Should -Match 'Runtime: ExchangeOnlineManagement 3\.10\.1 \(C:\\Synthetic\\Modules\\ExchangeOnlineManagement\\3\.10\.1\)' + @($context.RuntimeLines).Count | Should -Be 4 + $context.Warnings | Should -BeLessOrEqual 1 + $context.Issues.Count | Should -Be 0 + } +} + +Describe 'Release 3.3.0 - how the run was started: -Verbose, -Debug and SYSTEM are told once, a configuration value of a doubtful shape is a warning and never a refusal (production Common module)' -Tag 'Release330B' { + BeforeAll { + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global + $script:NewRunContext = { + @{ StepIndex = 0; StepTotal = 4; Issues = (New-Object 'Collections.Generic.List[object]'); Warnings = 0; LogFile = ''; Action = 'Convert'; CurrentPhase = '' } + } + $script:WriteConfig = { + param([string]$Body) + $path = Join-Path $global:PraGate.Root ('shape-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.psd1') + [IO.File]::WriteAllText($path, "@{ Scope = @{ Mode = 'Auto' }`n $(if ($Body -notmatch 'Licensing') { 'Licensing = @{ Enabled = $false }; ' }) $Body }", (New-Object Text.UTF8Encoding($true))) + $path + } + } + It 'warns once when -Verbose or -Debug is on, and for an unattended run as SYSTEM (S-1-5-18, in any letter case)' -ForEach @( + @{ Diagnostic = $true; Sid = 'S-1-5-21-1-2-3-1001'; Expect = 1; Match = '*do not share*' } + @{ Diagnostic = $false; Sid = 'S-1-5-18'; Expect = 1; Match = '*started as SYSTEM*' } + @{ Diagnostic = $true; Sid = 's-1-5-18'; Expect = 2; Match = '*started as SYSTEM*' } + @{ Diagnostic = $false; Sid = 'S-1-5-21-1-2-3-1001'; Expect = 0; Match = '*' } + ) { + $context = & $script:NewRunContext + Write-PraRunWarning -Context $context -DiagnosticOutput $Diagnostic -AccountSid $Sid 6>$null + $context.Warnings | Should -Be $Expect + if ($Expect) { (@($context.WarningList | ForEach-Object { $_.Message }) -join ' ') | Should -BeLike $Match } + $context.Issues.Count | Should -Be 0 + } + It 'accepts the configuration of 3.2.0 as it is, and turns a doubtful tenant, organization or thumbprint into a warning' { + $good = Import-PraConfiguration -Path (& $script:WriteConfig '') -Root $global:PraGate.Package + @($good['_ShapeWarnings']).Count | Should -Be 0 + $good.Security.RequireProtectedFolders | Should -BeFalse + @($good.Security.AcceptedWriterSids).Count | Should -Be 0 + $good.Console.NetworkProbes | Should -BeExactly 'Auto' + $odd = Import-PraConfiguration -Path (& $script:WriteConfig "Cloud = @{ Organization = 'tenant'; TenantId = 'not-a-guid' }; Licensing = @{ Enabled = `$false; GroupDN = 'license group' }") -Root $global:PraGate.Package + $notes = @($odd['_ShapeWarnings']) -join ' | ' + $notes | Should -BeLike '*Cloud.Organization (tenant)*' + $notes | Should -BeLike '*Cloud.TenantId (not-a-guid) is not a GUID*' + $notes | Should -Not -BeLike '*GroupDN*' -Because 'a group can be given by its name, its GUID or its SID' + $thumb = Import-PraConfiguration -Path (& $script:WriteConfig "Cloud = @{ TenantId = '11111111-2222-3333-4444-555555555555'; Organization = 'contoso.onmicrosoft.com'; AppId = '22222222-3333-4444-5555-666666666666'; CertificateThumbprint = 'ABC' }") -Root $global:PraGate.Package + $thumb.Cloud.CertificateThumbprint | Should -BeExactly 'ABC' + @($thumb['_ShapeWarnings']).Count | Should -Be 1 + $thumb['_ShapeWarnings'][0] | Should -BeLike 'Cloud.CertificateThumbprint does not look like a certificate thumbprint*3 characters long*' + } + It 'accepts a thumbprint of 40 or 64 hexadecimal characters in any letter case, without a note' -ForEach @(@{ Value = 'abcdef0123456789ABCDEF0123456789abcdef01' }, @{ Value = ('aB' * 32) }) { + $config = Import-PraConfiguration -Path (& $script:WriteConfig "Cloud = @{ TenantId = '11111111-2222-3333-4444-555555555555'; Organization = 'contoso.onmicrosoft.com'; AppId = '22222222-3333-4444-5555-666666666666'; CertificateThumbprint = '$Value' }") -Root $global:PraGate.Package + @($config['_ShapeWarnings']).Count | Should -Be 0 + } + It 'checks the shape of the shared permissions of a stored record and rejects nothing' { + $record = [pscustomobject]@{ SharedPermissions = [pscustomobject]@{ FullAccess = @('a@contoso.invalid', 'not a upn', ('x' * 330 + '@contoso.invalid')); SendAs = @('b@contoso.invalid'); SendOnBehalf = @() } } + $notes = @(InModuleScope PRA.Directory -Parameters @{ Record = $record } { param($Record) Get-PraStoredPermissionShapeWarning -Record $Record }) + $notes.Count | Should -Be 1 + $notes[0] | Should -BeLike 'FullAccess: 2 of 3 entries do not look like a UPN*' + @(InModuleScope PRA.Directory -Parameters @{ Record = [pscustomobject]@{ UserPrincipalName = 'x' } } { param($Record) Get-PraStoredPermissionShapeWarning -Record $Record }).Count | Should -Be 0 + $many = [pscustomobject]@{ SharedPermissions = [pscustomobject]@{ FullAccess = @(1..5001 | ForEach-Object { 'u' + $_ + '@contoso.invalid' }); SendAs = @(); SendOnBehalf = @() } } + (@(InModuleScope PRA.Directory -Parameters @{ Record = $many } { param($Record) Get-PraStoredPermissionShapeWarning -Record $Record }) -join ' ') | Should -BeLike '*holds 5001 entries (more than 5000)*' + } +} + +Describe 'Release 3.3.0 - the new settings: Security and Console, in any letter case, unknown keys still refused (production Common module)' -Tag 'Release330B' { + BeforeAll { + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global + $script:Load = { + param([string]$Body) + $path = Join-Path $global:PraGate.Root ('settings-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.psd1') + [IO.File]::WriteAllText($path, "@{ Scope = @{ Mode = 'Auto' }`n $(if ($Body -notmatch 'Licensing') { 'Licensing = @{ Enabled = $false }; ' }) $Body }", (New-Object Text.UTF8Encoding($true))) + Import-PraConfiguration -Path $path -Root $global:PraGate.Package + } + } + It 'reads Console.NetworkProbes whatever the letter case and gives the official spelling' -ForEach @(@{ Value = 'off'; Expect = 'Off' }, @{ Value = 'OFF'; Expect = 'Off' }, @{ Value = 'auto'; Expect = 'Auto' }, @{ Value = 'AuTo'; Expect = 'Auto' }) { + (& $script:Load "Console = @{ NetworkProbes = '$Value' }").Console.NetworkProbes | Should -BeExactly $Expect + } + It 'refuses a Console.NetworkProbes value that is not Auto or Off, and an unknown key of the new sections' { + { & $script:Load "Console = @{ NetworkProbes = 'Never' }" } | Should -Throw '*Console.NetworkProbes must be Auto or Off*' + { & $script:Load "Console = @{ Probes = 'Off' }" } | Should -Throw '*unknown setting Console.Probes*' + { & $script:Load "Security = @{ RequireFolders = `$true }" } | Should -Throw '*unknown setting Security.RequireFolders*' + { & $script:Load "Security = @{ RequireProtectedFolders = 'yes' }" } | Should -Throw '*Security.RequireProtectedFolders must be `$true or `$false*' + } + It 'normalises the accepted SIDs and refuses a name, which would depend on the language of Windows' { + $config = & $script:Load "Security = @{ RequireProtectedFolders = `$true; AcceptedWriterSids = @('s-1-5-32-549', ' S-1-5-21-1-2-3-1105 ') }" + $config.Security.RequireProtectedFolders | Should -BeTrue + ($config.Security.AcceptedWriterSids -join ',') | Should -BeExactly 'S-1-5-32-549,S-1-5-21-1-2-3-1105' + { & $script:Load "Security = @{ AcceptedWriterSids = @('BUILTIN\Server Operators') }" } | Should -Throw '*Security.AcceptedWriterSids must be a list of SIDs*' + { & $script:Load "Security = @{ AcceptedWriterSids = 'S-1-5-32-549' }" } | Should -Throw '*Security.AcceptedWriterSids must be a list*' + } + It 'ships both sections in the configuration file, with the defaults of the code, commented' { + $shipped = Get-Content -LiteralPath (Join-Path $global:PraGate.Package 'config\PraRemoteMailbox.config.psd1') -Raw + $shipped | Should -Match '(?s)#\s+RequireProtectedFolders = \$true.*?Security = @\{\s+RequireProtectedFolders = \$false\s+AcceptedWriterSids\s+= @\(\)' + $shipped | Should -Match "(?s)#\s+NetworkProbes = Auto.*?Console = @\{\s+NetworkProbes = 'Auto'" + $defaults = InModuleScope PRA.Common { Get-PraDefaultConfiguration } + $defaults.Security.RequireProtectedFolders | Should -BeFalse + $defaults.Console.NetworkProbes | Should -BeExactly 'Auto' + } +} + +Describe 'Release 3.3.0 - who can change or read the folders of the tool: read only, by SID, one warning with the fix, never a stop unless the operator asks (production Common module, synthetic folders)' -Tag 'Release330B' { + BeforeAll { + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global + Register-PraTestProxy PRA.Common 'Get-PraPathExposure', 'Get-PraExposureFix', 'Get-PraSidDisplayName' + $script:AddAce = { + param([string]$Path, [string]$Sid, [string]$Rights = 'Modify', [string]$Type = 'Allow') + $directory = [IO.Directory]::Exists($Path) + $info = if ($directory) { New-Object IO.DirectoryInfo $Path } else { New-Object IO.FileInfo $Path } + $acl = [IO.FileSystemAclExtensions]::GetAccessControl($info) + $inherit = if ($directory) { [Security.AccessControl.InheritanceFlags]'ContainerInherit,ObjectInherit' } else { [Security.AccessControl.InheritanceFlags]::None } + $null = $acl.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($Sid)), [Security.AccessControl.FileSystemRights]$Rights, $inherit, [Security.AccessControl.PropagationFlags]::None, [Security.AccessControl.AccessControlType]$Type))) + [IO.FileSystemAclExtensions]::SetAccessControl($info, $acl) + } + $script:NewFolder = { param([string]$Prefix) $path = Join-Path $global:PraGate.Root ($Prefix + '-' + [guid]::NewGuid().ToString('N').Substring(0, 6)); Initialize-PraPrivateFolder -Path $path; $path } + $script:Me = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value + $script:NewRunContext = { param([string]$LogFile) @{ StepIndex = 0; StepTotal = 4; Issues = (New-Object 'Collections.Generic.List[object]'); Warnings = 0; LogFile = $LogFile; Action = 'Convert'; CurrentPhase = '' } } + $script:Rule = { param([string]$Sid, [int64]$Rights, [bool]$Allow = $true, [bool]$Inherited = $false, [bool]$InheritOnly = $false) [pscustomobject]@{ Sid = $Sid; Allow = $Allow; Rights = $Rights; Inherited = $Inherited; InheritOnly = $InheritOnly } } + } + It 'reports an account that can write, by SID, with the icacls command written with *SID; the name is for display only' { + $folder = & $script:NewFolder 'exposed' + & $script:AddAce $folder 'S-1-5-32-545' 'Modify' + $result = Get-PraPathExposure -Path $folder -CurrentSid $script:Me + @($result.Write | ForEach-Object { $_.Sid }) | Should -Contain 'S-1-5-32-545' + $fix = Get-PraExposureFix -Path $folder -Sid @('S-1-5-32-545') -Inherited $false + $fix | Should -BeExactly ('icacls "{0}" /remove:g *S-1-5-32-545' -f $folder) + (Get-PraExposureFix -Path $folder -Sid @('S-1-5-32-545', 'S-1-1-0') -Inherited $true) | Should -BeExactly ('icacls "{0}" /inheritance:d && icacls "{0}" /remove:g *S-1-5-32-545 && icacls "{0}" /remove:g *S-1-1-0' -f $folder) + Get-PraSidDisplayName 'S-1-5-32-545' | Should -BeExactly 'Users' + Get-PraSidDisplayName 'S-1-5-21-1-2-3-513' | Should -BeExactly 'Domain Users' + Get-PraSidDisplayName 'S-1-5-21-1-2-3-1105' | Should -BeExactly '' + } + It 'reports nothing for a folder that the tool made private, and nothing for the trusted accounts of a synthetic ACL' { + $private = Join-Path (& $script:NewFolder 'private') 'Inbox' + Initialize-PraPrivateFolder -Path $private + $result = Get-PraPathExposure -Path $private -CurrentSid $script:Me + @($result.Write).Count | Should -Be 0 + @($result.Read).Count | Should -Be 0 + $rules = @( + (& $script:Rule 'S-1-5-18' 0x1F01FF), (& $script:Rule 'S-1-5-32-544' 0x1F01FF), (& $script:Rule 'S-1-3-0' 0x1F01FF), (& $script:Rule $script:Me 0x1F01FF) + (& $script:Rule 'S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464' 0x1F01FF), (& $script:Rule 'S-1-5-21-111-222-333-512' 0x1F01FF), (& $script:Rule 'S-1-5-21-111-222-333-519' 0x1F01FF) + (& $script:Rule 'S-1-5-32-545' 0x1200A9 $true $true $true) + ) + $synthetic = Get-PraPathExposure -Path $private -CurrentSid $script:Me -ReadAcl ({ param($p) $rules }.GetNewClosure()) + @($synthetic.Write).Count | Should -Be 0 + @($synthetic.Read).Count | Should -Be 0 + } + It 'tests the access mask, not the name of a right: a write right of any kind is found, a read right alone is not a write' -ForEach @( + @{ Rights = 0x2; Write = $true }, @{ Rights = 0x4; Write = $true }, @{ Rights = 0x40; Write = $true }, @{ Rights = 0x10000; Write = $true }, @{ Rights = 0x40000; Write = $true } + @{ Rights = 0x80000; Write = $true }, @{ Rights = 0x10000000; Write = $true }, @{ Rights = 0x40000000; Write = $true }, @{ Rights = 0x1200A9; Write = $false }, @{ Rights = 0x1; Write = $false } + ) { + $path = Join-Path $global:PraGate.Root 'mask' + $rules = @(& $script:Rule 'S-1-5-11' ([int64]$Rights)) + $result = Get-PraPathExposure -Path $path -CurrentSid $script:Me -ReadAcl ({ param($p) $rules }.GetNewClosure()) + (@($result.Write).Count -gt 0) | Should -Be $Write + } + It 'lets a Deny entry of the same SID take its rights off, and lets Security.AcceptedWriterSids silence a group, in any letter case' { + $folder = & $script:NewFolder 'deny' + & $script:AddAce $folder 'S-1-5-32-549' 'Modify' 'Allow' + & $script:AddAce $folder 'S-1-5-32-549' 'Modify' 'Deny' + @((Get-PraPathExposure -Path $folder -CurrentSid $script:Me).Write).Count | Should -Be 0 + $other = & $script:NewFolder 'accepted' + & $script:AddAce $other 'S-1-5-32-550' 'Modify' + @((Get-PraPathExposure -Path $other -CurrentSid $script:Me).Write).Count | Should -Be 1 + @((Get-PraPathExposure -Path $other -CurrentSid $script:Me -Accepted @('s-1-5-32-550')).Write).Count | Should -Be 0 + } + It 'checks every location, only warns about the folders of PowerShell and of the modules, and works the same under a French culture' { + $before = [Threading.Thread]::CurrentThread.CurrentCulture + try { + [Threading.Thread]::CurrentThread.CurrentCulture = [Globalization.CultureInfo]::GetCultureInfo('fr-FR') + $package = & $script:NewFolder 'pkg' + foreach ($name in 'module', 'config') { $null = New-Item -ItemType Directory -Path (Join-Path $package $name) -Force } + $backups = Join-Path $package 'Backups' + Initialize-PraPrivateFolder -Path $backups + $inbox = Join-Path $backups 'Inbox'; $null = New-Item -ItemType Directory -Path $inbox -Force + & $script:AddAce $inbox 'S-1-5-32-545' 'Modify' + $moduleFolder = & $script:NewFolder 'mod'; & $script:AddAce $moduleFolder 'S-1-1-0' 'Modify' + $powerShellFolder = & $script:NewFolder 'pshome'; & $script:AddAce $powerShellFolder 'S-1-1-0' 'Modify' + $config = @{ Storage = @{ BackupFolder = $backups }; Logging = @{ Folder = (Join-Path $package 'logs') }; Report = @{ Folder = (Join-Path $package 'reports') }; Security = @{ AcceptedWriterSids = @() } } + $installed = @([pscustomobject]@{ Name = 'ExchangeOnlineManagement'; Version = [version]'3.10.1'; ModuleBase = $moduleFolder }) + $exposure = Get-PraFolderExposure -Root $package -Config $config -Available $installed -CurrentSid $script:Me -PowerShellHome $powerShellFolder + $exposure.Checked | Should -BeGreaterThan 4 + $roles = @($exposure.Findings | ForEach-Object { $_.Role + ':' + $_.Class + ':' + $_.Kind }) + $roles | Should -Contain 'Inbox folder:Data:Write' + $roles | Should -Contain 'PowerShell module ExchangeOnlineManagement:Module:Write' + $roles | Should -Contain 'PowerShell folder:Module:Write' + @($exposure.Blocking | ForEach-Object { $_.Role }) | Should -Be @('Inbox folder') + $exposure.Blocking[0].Sids | Should -Contain 'S-1-5-32-545' + } + finally { [Threading.Thread]::CurrentThread.CurrentCulture = $before } + } + It 'reports a data folder that other accounts can read, and not a package folder that they can only read' { + $package = & $script:NewFolder 'readers' + $backups = Join-Path $package 'Backups' + $null = New-Item -ItemType Directory -Path $backups -Force + & $script:AddAce $backups 'S-1-5-11' 'ReadAndExecute' + & $script:AddAce $package 'S-1-5-11' 'ReadAndExecute' + $config = @{ Storage = @{ BackupFolder = $backups }; Logging = @{ Folder = (Join-Path $package 'logs') }; Report = @{ Folder = (Join-Path $package 'reports') }; Security = @{ AcceptedWriterSids = @() } } + $exposure = Get-PraFolderExposure -Root $package -Config $config -Available @() -CurrentSid $script:Me -PowerShellHome (Join-Path $package 'none') + @($exposure.Findings | Where-Object { $_.Kind -ceq 'Read' } | ForEach-Object { $_.Role }) | Should -Be @('backup folder') + @($exposure.Findings | Where-Object { $_.Kind -ceq 'Write' }).Count | Should -Be 0 + } + It 'raises ONE warning with the first fix, writes every finding to the log, changes nothing and leaves the exit code alone' { + $folder = & $script:NewFolder 'warn'; & $script:AddAce $folder 'S-1-5-32-545' 'Modify' + $other = & $script:NewFolder 'warn2'; & $script:AddAce $other 'S-1-1-0' 'Modify' + $before = (Get-Acl -LiteralPath $folder).Sddl + $findings = @( + [pscustomobject]@{ Role = 'package folder'; Path = $folder; Class = 'Package'; Kind = 'Write'; Sids = [string[]]@('S-1-5-32-545'); Names = [string[]]@('Users'); Inherited = $false; Fix = (Get-PraExposureFix -Path $folder -Sid @('S-1-5-32-545') -Inherited $false) } + [pscustomobject]@{ Role = 'log folder'; Path = $other; Class = 'Data'; Kind = 'Write'; Sids = [string[]]@('S-1-1-0'); Names = [string[]]@('Everyone'); Inherited = $false; Fix = (Get-PraExposureFix -Path $other -Sid @('S-1-1-0') -Inherited $false) } + ) + $result = [pscustomobject]@{ Findings = $findings; NotAssessed = [string[]]@(); Checked = 2; Blocking = $findings } + $log = Join-Path $global:PraGate.Root ('exposure-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.log') + $context = & $script:NewRunContext $log + Write-PraFolderExposure -Context $context -Result $result 6>$null + $context.Warnings | Should -Be 1 + $context.Issues.Count | Should -Be 0 + $message = [string]$context.WarningList[0].Message + $message | Should -BeLike '*Folder permissions: 2 location(s) can be changed*package folder*S-1-5-32-545 (Users)*' + $message | Should -BeLike ('*icacls "{0}" /remove:g *S-1-5-32-545*' -f $folder) + $message | Should -BeLike '*no right was changed*Security.AcceptedWriterSids*' + $text = [IO.File]::ReadAllText($log) + ([regex]::Matches($text, 'FOLDER EXPOSURE \|')).Count | Should -Be 2 + (Get-Acl -LiteralPath $folder).Sddl | Should -BeExactly $before + $refusal = Format-PraExposureRefusal -Result $result + $refusal | Should -BeLike 'Security.RequireProtectedFolders is on and 2 location(s) are not protected*Nothing was written*/remove:g *S-1-5-32-545*' + } + It 'says once that a network share is not assessed from here' { + $result = [pscustomobject]@{ Findings = @(); NotAssessed = [string[]]@('backup folder \\files.contoso.invalid\pra: share ACL not assessable from here'); Checked = 1; Blocking = @() } + $context = & $script:NewRunContext '' + Write-PraFolderExposure -Context $context -Result $result 6>$null + $context.Warnings | Should -Be 0 + $context.Issues.Count | Should -Be 0 + } +} + +Describe 'Release 3.3.0 - the Inbox folder is created private when it is missing and an existing one is left as it is (production Common module, synthetic folders)' -Tag 'Release330B' { + BeforeAll { Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global } + It 'creates Backups and Backups\Inbox with the private ACL of the backups, and does nothing the second time' { + $backups = Join-Path $global:PraGate.Root ('inbox-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '\Backups') + $context = @{ BackupFolder = $backups; Warnings = 0; Issues = (New-Object 'Collections.Generic.List[object]'); LogFile = '' } + (Initialize-PraInboxFolder -Context $context) | Should -BeTrue + foreach ($folder in @($backups, (Join-Path $backups 'Inbox'))) { + $security = [IO.FileSystemAclExtensions]::GetAccessControl((New-Object IO.DirectoryInfo $folder)) + $security.AreAccessRulesProtected | Should -BeTrue -Because $folder + @($security.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier]) | ForEach-Object { $_.IdentityReference.Value } | Sort-Object -Unique).Count | Should -BeLessOrEqual 3 + } + (Initialize-PraInboxFolder -Context $context) | Should -BeFalse + } + It 'leaves an Inbox that exists exactly as it is' { + $backups = Join-Path $global:PraGate.Root ('inbox-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) + $inbox = Join-Path $backups 'Inbox' + $null = New-Item -ItemType Directory -Path $inbox -Force + $before = (Get-Acl -LiteralPath $inbox).Sddl + $context = @{ BackupFolder = $backups; Warnings = 0; Issues = (New-Object 'Collections.Generic.List[object]'); LogFile = '' } + (Initialize-PraInboxFolder -Context $context) | Should -BeFalse + (Get-Acl -LiteralPath $inbox).Sddl | Should -BeExactly $before + } + It 'warns and goes on when the folder cannot be created' { + $file = Join-Path $global:PraGate.Root ('inbox-file-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) + [IO.File]::WriteAllText($file, 'x') + $context = @{ BackupFolder = $file; Warnings = 0; Issues = (New-Object 'Collections.Generic.List[object]'); LogFile = '' } + (Initialize-PraInboxFolder -Context $context 6>$null) | Should -BeFalse + $context.Warnings | Should -Be 1 + $context.Issues.Count | Should -Be 0 + [string]$context.WarningList[0].Message | Should -BeLike '*cannot be created*Create it yourself*' + } +} + +Describe 'Release 3.3.0 - what this run will use, with the source of each value (production Common module)' -Tag 'Release330B' { + BeforeAll { + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global + Register-PraTestProxy PRA.Common 'Get-PraRunSetting' + $script:Config = { + param([string]$Body) + $path = Join-Path $global:PraGate.Root ('use-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.psd1') + [IO.File]::WriteAllText($path, "@{ Scope = @{ Mode = 'OU'; SearchBase = 'OU=Wave1,DC=contoso,DC=invalid' }`n $(if ($Body -notmatch 'Licensing') { 'Licensing = @{ Enabled = $false }; ' }) $Body }", (New-Object Text.UTF8Encoding($true))) + Import-PraConfiguration -Path $path -Root $global:PraGate.Package + } + } + It 'lists the values that steer a privileged action, each with its source' { + $config = & $script:Config "Licensing = @{ Enabled = `$true; GroupDN = 'CN=Licence,OU=Groups,DC=contoso,DC=invalid' }; SharedMailbox = @{ PermissionSource = 'None'; ExcludeTrusteeSamAccountNames = @('Administrateur') }; DomainController = 'dc1.contoso.invalid'" + $rows = @(Get-PraRunSetting -Config $config -Source @{ 'Scope.Mode' = 'command line'; 'Scope.SearchBase' = 'command line'; 'DomainController' = 'console' } -BaseConfigPath 'C:\Synthetic\base.psd1') + $byName = @{}; foreach ($row in $rows) { $byName[$row.Name] = $row } + foreach ($name in 'Configuration file', 'Base configuration file', 'Environment', 'Domain controller', 'Mailbox scope', 'Licence group', 'Permission source', 'Trustee exclusions', 'Identity check', 'Retention check before a Recover', 'Retention proof age limit', 'Entra Connect', 'Tenant', 'Application', 'Backup folder', 'Log folder', 'Report folder', 'Protected folders required') { + $byName.ContainsKey($name) | Should -BeTrue -Because $name + } + $byName['Mailbox scope'].Value | Should -BeExactly 'OU OU=Wave1,DC=contoso,DC=invalid' + $byName['Mailbox scope'].Source | Should -BeExactly 'command line' + $byName['Domain controller'].Value | Should -BeExactly 'dc1.contoso.invalid' + $byName['Domain controller'].Source | Should -BeExactly 'console' + $byName['Licence group'].Value | Should -BeExactly 'CN=Licence,OU=Groups,DC=contoso,DC=invalid' + $byName['Licence group'].Source | Should -BeExactly 'configuration file' + $byName['Trustee exclusions'].Value | Should -BeExactly 'Administrateur' + $byName['Retention check before a Recover'].Value | Should -BeExactly 'on' + $byName['Application'].Value | Should -BeExactly 'interactive sign-in' + $byName['Protected folders required'].Value | Should -BeExactly 'off' + } + It 'shows the application of a certificate sign-in without the thumbprint, and neutralises a control character in a value' { + $config = & $script:Config "Cloud = @{ TenantId = '11111111-2222-3333-4444-555555555555'; Organization = 'contoso.onmicrosoft.com'; AppId = '22222222-3333-4444-5555-666666666666'; CertificateThumbprint = 'ABCDEF0123456789ABCDEF0123456789ABCDEF01' }" + $config.Environment = "PROD$([char]27)[31m" + $rows = @(Get-PraRunSetting -Config $config) + (@($rows | ForEach-Object { $_.Value }) -join ' | ') | Should -Not -BeLike '*ABCDEF0123456789*' + ($rows | Where-Object Name -ceq 'Application').Value | Should -BeExactly 'certificate sign-in, application 22222222-3333-4444-5555-666666666666' + ($rows | Where-Object Name -ceq 'Environment').Value | Should -BeExactly 'PROD<0x1B>[31m' + } + It 'shows the block once per run, keeps it for the report header, and -Silent only keeps it' { + $config = & $script:Config '' + $context = @{ StepIndex = 0; StepTotal = 4; Issues = (New-Object 'Collections.Generic.List[object]'); Warnings = 0; LogFile = ''; Config = $config } + Write-PraRunSetting -Context $context -Silent 6>&1 | Should -BeNullOrEmpty + @($context.RunSettings).Count | Should -BeGreaterThan 10 + $first = @(Write-PraRunSetting -Context $context 6>&1 | ForEach-Object { [string]$_ }) + ($first -join "`n") | Should -BeLike '*What this run will use:*Mailbox scope*' + @(Write-PraRunSetting -Context $context 6>&1).Count | Should -Be 0 + $context.RunSettings[0] | Should -BeLike 'Configuration file: *' + } +} + +Describe 'Release 3.3.0 - control characters reach neither the console nor the log, a spreadsheet formula is neutralised after leading spaces (production Common module)' -Tag 'Release330B' { + BeforeAll { Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global; Register-PraTestProxy PRA.Common 'ConvertTo-PraSafeText' } + It 'replaces every control character but the tab, line breaks included, by a visible placeholder, and leaves printable text alone' { + (ConvertTo-PraSafeText "a$([char]27)[31mb") | Should -BeExactly 'a<0x1B>[31mb' + (ConvertTo-PraSafeText "bell$([char]7) null$([char]0) back$([char]8) del$([char]0x7F) cr`r lf`n c1$([char]0x85) rlo$([char]0x202E)") | Should -BeExactly 'bell<0x07> null<0x00> back<0x08> del<0x7F> cr<0x0D> lf<0x0A> c1<0x85> rlo<0x202E>' + (ConvertTo-PraSafeText "tab`tline`nfeed") | Should -BeExactly "tab`tline<0x0A>feed" + (ConvertTo-PraSafeText ('Jos' + [char]0xE9 + ' O''Brien & "x"')) | Should -Not -BeLike '*<0x*' + (ConvertTo-PraSafeText "caf$([char]0xE9) $([char]0x4E2D)$([char]0x6587)") | Should -BeExactly "caf$([char]0xE9) $([char]0x4E2D)$([char]0x6587)" + (ConvertTo-PraSafeText $null) | Should -BeExactly '' + } + It 'writes the placeholder on the console and in the log for a text from the directory, and never an escape sequence' { + $log = Join-Path $global:PraGate.Root ('safe-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.log') + $context = @{ StepIndex = 0; StepTotal = 4; Issues = (New-Object 'Collections.Generic.List[object]'); Warnings = 0; LogFile = $log; Action = 'Convert'; CurrentPhase = '' } + $hostile = "Display$([char]27)[2J name$([char]7)" + $output = @(Write-PraItem -Context $context -Status Warn -Text $hostile 6>&1 | ForEach-Object { [string]$_ }) + ($output -join '') | Should -Match ([regex]::Escape('Display<0x1B>[2J name<0x07>')) + ($output -join '').Contains([string][char]27) | Should -BeFalse + $output2 = @(Write-PraLog -Context $context -Message $hostile -Level Info 6>&1 | ForEach-Object { [string]$_ }) + ($output2 -join '').Contains([string][char]27) | Should -BeFalse + $text = [IO.File]::ReadAllText($log) + $text.Contains([string][char]27) | Should -BeFalse + $text | Should -Match ([regex]::Escape('Display<0x1B>[2J name<0x07>')) + } + It 'adds the apostrophe after leading whitespace in the CSV of a run and in the global CSV, and leaves other text alone' { + $path = Join-Path $global:PraGate.Root ('csv-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.csv') + $rows = New-Object 'Collections.Generic.List[string[]]' + $rows.Add([string[]]@('=cmd', ' +1', " `t@sum", 'a =b', ' text', '"quoted"')) + InModuleScope PRA.Common -Parameters @{ Path = $path; Rows = $rows } { param($Path, $Rows) Write-PraCsvFile -Path $Path -Fields @('A', 'B', 'C', 'D', 'E', 'F') -Rows $Rows } + $line = @([IO.File]::ReadAllLines($path))[1] + $line | Should -BeExactly "`"'=cmd`";`"' +1`";`"' `t@sum`";`"a =b`";`" text`";`"`"`"quoted`"`"`"" + } +} + +Describe 'Release 3.3.0 - the shipped report pages guard a spreadsheet formula after leading whitespace, and the report footer and header carry the runtime and the settings (runtime files)' -Tag 'Release330B' { + It 'has the same guard in both report templates as in the CSV writers' { + foreach ($name in 'Report.template.html', 'GlobalReport.template.html') { + [IO.File]::ReadAllText((Join-Path $global:PraGate.Package ('templates\' + $name))) | Should -Match ([regex]::Escape('if (/^(?:[=+\-@\t\r]|\s+[=+\-@])/.test(s)) s = "''" + s;')) + } + [IO.File]::ReadAllText((Join-Path $global:PraGate.Package 'templates\Report.template.html')) | Should -Match '\{\{RUNTIME\}\}' + } +} + +Describe 'Release 3.3.0 - a built-in account that the exclusion list does not name is a warning, the plan is unchanged (production Directory module)' -Tag 'Release330B' { + BeforeAll { + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Directory.psm1') -Force -Global + } + It 'warns once per account for the RID that the list of names does not catch, and not for an account the list names in any letter case' -ForEach @( + @{ Rid = 500; Name = 'Administrateur'; Excluded = @('Administrator'); Expect = 1 } + @{ Rid = 500; Name = 'Administrateur'; Excluded = @('ADMINISTRATEUR'); Expect = 0 } + @{ Rid = 516; Name = 'Domain Controllers'; Excluded = @(); Expect = 1 } + @{ Rid = 521; Name = 'Read-only Domain Controllers'; Excluded = @(); Expect = 1 } + @{ Rid = 527; Name = 'Enterprise Key Admins'; Excluded = @(); Expect = 1 } + @{ Rid = 1105; Name = 'user1'; Excluded = @(); Expect = 0 } + @{ Rid = 501; Name = 'Guest'; Excluded = @(); Expect = 0 } + ) { + $context = @{ Warnings = 0; Issues = (New-Object 'Collections.Generic.List[object]'); LogFile = ''; Config = @{ SharedMailbox = @{ ExcludeTrusteeSamAccountNames = $Excluded } } } + $sid = New-Object Security.Principal.SecurityIdentifier ('S-1-5-21-111-222-333-' + $Rid) + $object = [pscustomobject]@{ sAMAccountName = $Name; objectClass = 'user' } + InModuleScope PRA.Directory -Parameters @{ Context = $context; Sid = $sid; Object = $object } { param($Context, $Sid, $Object) Write-PraTrusteeRidWarning -Context $Context -Sid $Sid -Object $Object 6>$null; Write-PraTrusteeRidWarning -Context $Context -Sid $Sid -Object $Object 6>$null } + $context.Warnings | Should -Be $Expect + $context.Issues.Count | Should -Be 0 + if ($Expect) { [string]$context.WarningList[0].Message | Should -BeLike ('*is a built-in account of the domain*' + $Name + '*The plan is unchanged.') } + } + It 'never warns for a well-known group of another domain-independent SID' { + $context = @{ Warnings = 0; Issues = (New-Object 'Collections.Generic.List[object]'); LogFile = ''; Config = @{ SharedMailbox = @{ ExcludeTrusteeSamAccountNames = @() } } } + InModuleScope PRA.Directory -Parameters @{ Context = $context } { param($Context) Write-PraTrusteeRidWarning -Context $Context -Sid (New-Object Security.Principal.SecurityIdentifier 'S-1-5-32-544') -Object ([pscustomobject]@{ sAMAccountName = 'Administrators' }) 6>$null } + $context.Warnings | Should -Be 0 + } +} + +Describe 'Release 3.3.0 - the application certificate: a key that can be exported, or a key file open to other accounts, is one warning (production Common module, synthetic certificates)' -Tag 'Release330B' { + BeforeAll { + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global + Register-PraTestProxy PRA.Common 'Get-PraCertificateKeyExposure' + $script:NewCertificate = { + # A self-signed certificate made with .NET only (no PKI module), imported into CurrentUser\My with a persisted key that can be exported or not. + param([string]$Policy) + $rsa = [Security.Cryptography.RSA]::Create(2048) + try { + $request = New-Object Security.Cryptography.X509Certificates.CertificateRequest(('CN=SYNTHETIC-PRA-' + [guid]::NewGuid().ToString('N').Substring(0, 8)), $rsa, [Security.Cryptography.HashAlgorithmName]::SHA256, [Security.Cryptography.RSASignaturePadding]::Pkcs1) + $ephemeral = $request.CreateSelfSigned([DateTimeOffset]::UtcNow.AddMinutes(-5), [DateTimeOffset]::UtcNow.AddDays(2)) + $pfx = $ephemeral.Export([Security.Cryptography.X509Certificates.X509ContentType]::Pfx, 'synthetic') + $ephemeral.Dispose() + } + finally { $rsa.Dispose() } + $flags = [Security.Cryptography.X509Certificates.X509KeyStorageFlags]'UserKeySet,PersistKeySet' + if ($Policy -ceq 'Exportable') { $flags = $flags -bor [Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable } + $certificate = New-Object Security.Cryptography.X509Certificates.X509Certificate2($pfx, 'synthetic', $flags) + $store = New-Object Security.Cryptography.X509Certificates.X509Store('My', 'CurrentUser') + try { $store.Open('ReadWrite'); $store.Add($certificate) } finally { $store.Dispose() } + $certificate + } + } + It 'finds an exportable key and a key that cannot be exported, and nothing for a thumbprint that is not in the store' { + $created = @() + try { + $exportable = & $script:NewCertificate 'Exportable'; $created += $exportable + $fixed = & $script:NewCertificate 'NonExportable'; $created += $fixed + (Get-PraCertificateKeyExposure -Thumbprint $exportable.Thumbprint).Exportable | Should -BeTrue + (Get-PraCertificateKeyExposure -Thumbprint $fixed.Thumbprint.ToLowerInvariant()).Exportable | Should -BeFalse + (Get-PraCertificateKeyExposure -Thumbprint $fixed.Thumbprint).Found | Should -BeTrue + (Get-PraCertificateKeyExposure -Thumbprint ('0' * 40)).Found | Should -BeFalse + $everyone = @([pscustomobject]@{ Sid = 'S-1-1-0'; Allow = $true; Rights = 1; Inherited = $false; InheritOnly = $false }, [pscustomobject]@{ Sid = 'S-1-5-18'; Allow = $true; Rights = 1; Inherited = $false; InheritOnly = $false }) + $exposure = Get-PraCertificateKeyExposure -Thumbprint $fixed.Thumbprint -ReadAcl ({ param($p) $everyone }.GetNewClosure()) + if ($exposure.KeyFile) { @($exposure.Sids) | Should -Be @('S-1-1-0') } + } + finally { foreach ($certificate in $created) { Remove-Item -LiteralPath ('Cert:\CurrentUser\My\' + $certificate.Thumbprint) -Force -ErrorAction SilentlyContinue } } + } + It 'raises one warning for an exportable key, with the way to create the certificate again, and none for a missing certificate' { + $created = @() + try { + $exportable = & $script:NewCertificate 'Exportable'; $created += $exportable + $context = @{ StepIndex = 0; StepTotal = 4; Issues = (New-Object 'Collections.Generic.List[object]'); Warnings = 0; LogFile = ''; Action = 'Convert'; CurrentPhase = '' } + Write-PraCertificateWarning -Context $context -Thumbprint $exportable.Thumbprint 6>$null + $context.Warnings | Should -Be 1 + [string]$context.WarningList[0].Message | Should -BeLike '*can be exported*-KeyExportPolicy NonExportable*' + $none = @{ StepIndex = 0; StepTotal = 4; Issues = (New-Object 'Collections.Generic.List[object]'); Warnings = 0; LogFile = ''; Action = 'Convert'; CurrentPhase = '' } + Write-PraCertificateWarning -Context $none -Thumbprint ('0' * 40) 6>$null + $none.Warnings | Should -Be 0 + } + finally { foreach ($certificate in $created) { Remove-Item -LiteralPath ('Cert:\CurrentUser\My\' + $certificate.Thumbprint) -Force -ErrorAction SilentlyContinue } } + } +} + +Describe 'Release 3.3.0 - the entry script: folder exposure, the Inbox folder and the block of settings (real main, synthetic AD and cloud barrier)' -Tag 'Release330B' { + BeforeAll { + $script:Expose = { + param($Runtime) + # The folders of the run keep only the trusted accounts (the ACL of the temporary folder of a computer can hold other accounts), then the backup folder is opened to Users. + $private = New-Object Security.AccessControl.DirectorySecurity + $private.SetAccessRuleProtection($true, $false) + foreach ($sid in @([Security.Principal.WindowsIdentity]::GetCurrent().User.Value, 'S-1-5-18', 'S-1-5-32-544')) { + $null = $private.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($sid)), [Security.AccessControl.FileSystemRights]::FullControl, ([Security.AccessControl.InheritanceFlags]'ContainerInherit,ObjectInherit'), [Security.AccessControl.PropagationFlags]::None, [Security.AccessControl.AccessControlType]::Allow))) + } + [IO.FileSystemAclExtensions]::SetAccessControl((New-Object IO.DirectoryInfo $Runtime.Root), $private) + $folder = $Runtime.State.BackupFolder + $null = New-Item -ItemType Directory -Path $folder -Force + $info = New-Object IO.DirectoryInfo $folder + $acl = [IO.FileSystemAclExtensions]::GetAccessControl($info) + $null = $acl.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier('S-1-5-32-545')), [Security.AccessControl.FileSystemRights]::Modify, ([Security.AccessControl.InheritanceFlags]'ContainerInherit,ObjectInherit'), [Security.AccessControl.PropagationFlags]::None, [Security.AccessControl.AccessControlType]::Allow))) + [IO.FileSystemAclExtensions]::SetAccessControl($info, $acl) + } + $script:Require = { param($Runtime) Set-GateConfigText $Runtime { param($text) $text.Replace("Execution=@{Phase='Both'}", "Execution=@{Phase='Both'}`n Security=@{RequireProtectedFolders=`$true}") } } + } + It 'warns once with the fix, shows what the run will use with its sources, and creates nothing in a Preview' { + $runtime = New-GateRuntime -Name 'b-exposure-preview' + & $script:Expose $runtime + $result = Invoke-GateProcess $runtime @{ Action = 'Convert'; Phase = 'AD'; Mode = 'Preview'; ConfigPath = $runtime.ConfigPath; SearchBase = 'OU=Gate,DC=gate,DC=invalid' } -TimeoutSeconds 120 + $result.ExitCode | Should -BeIn @(0, 2) + $result.Output | Should -BeLike '*Folder permissions:*backup folder*S-1-5-32-545 (Users)*/remove:g *S-1-5-32-545*' + $result.Output | Should -BeLike '*What this run will use:*' + $result.Output | Should -Match 'Mailbox scope\s+OU OU=Gate,DC=gate,DC=invalid\s+\[command line\]' + $result.Output | Should -Match 'Environment\s+\S+\s+\[configuration file\]' + Test-Path -LiteralPath (Join-Path $runtime.State.BackupFolder 'Inbox') | Should -BeFalse + @(Get-GateWrites $runtime).Count | Should -Be 0 + } + It 'creates the Inbox folder private in an Apply, goes on with the warning when the option is off, and records the runtime in the log' { + $runtime = New-GateRuntime -Name 'b-exposure-apply' + & $script:Expose $runtime + $result = Invoke-GateProcess $runtime @{ Action = 'Convert'; Phase = 'AD'; Mode = 'Apply'; Force = $true; ConfigPath = $runtime.ConfigPath } -TimeoutSeconds 120 + $result.ExitCode | Should -BeIn @(0, 2) + @(Get-GateWrites $runtime).Count | Should -BeGreaterThan 0 + $inbox = Join-Path $runtime.State.BackupFolder 'Inbox' + Test-Path -LiteralPath $inbox -PathType Container | Should -BeTrue + [IO.FileSystemAclExtensions]::GetAccessControl((New-Object IO.DirectoryInfo $inbox)).AreAccessRulesProtected | Should -BeTrue + $result.Output | Should -BeLike '*Folder permissions:*' + $logText = [IO.File]::ReadAllText([string]$result.MainResult.LogFile) + $logText | Should -Match 'Runtime: PowerShell \d+\.\d+\.\d+ \(' + $logText | Should -Match 'FOLDER EXPOSURE \| changeable by backup folder' + $htmlPath = [string]$result.MainResult.HtmlReport + [IO.File]::ReadAllText($htmlPath) | Should -Match 'PowerShell \d+\.\d+\.\d+ \(.+?\)' + } + It 'with Security.RequireProtectedFolders, a Preview says that an Apply would stop and an Apply stops before it writes anything, with the fix' { + $runtime = New-GateRuntime -Name 'b-exposure-require' + & $script:Expose $runtime + & $script:Require $runtime + $preview = Invoke-GateProcess $runtime @{ Action = 'Convert'; Phase = 'AD'; Mode = 'Preview'; ConfigPath = $runtime.ConfigPath } -TimeoutSeconds 120 + $preview.ExitCode | Should -BeIn @(0, 2) + $preview.Output | Should -BeLike '*an Apply of this run would stop before it writes anything*' + @(Get-GateWrites $runtime).Count | Should -Be 0 + $apply = Invoke-GateProcess $runtime @{ Action = 'Convert'; Phase = 'AD'; Mode = 'Apply'; Force = $true; ConfigPath = $runtime.ConfigPath } -TimeoutSeconds 120 + $apply.ExitCode | Should -Be 1 + @(Get-GateWrites $runtime).Count | Should -Be 0 + Test-Path -LiteralPath (Join-Path $runtime.State.BackupFolder 'Inbox') | Should -BeFalse -Because 'the check comes before the first folder the run creates' + $apply.Output | Should -BeLike '*Security.RequireProtectedFolders is on and*not protected*Nothing was written*icacls*/remove:g *S-1-5-32-545*' + $apply.Output | Should -BeLike '*then start the same command again*' + @(Get-ChildItem -LiteralPath $runtime.State.BackupFolder -Filter 'Convert-*.json' -Recurse -ErrorAction SilentlyContinue).Count | Should -Be 0 + } +} + +Describe 'Release 3.3.0 - the generated folders of the package are found in any letter case, and the Active Directory calls name their module (production Common and Directory modules, runtime files)' -Tag 'Release330B' { + BeforeAll { Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global; Register-PraTestProxy PRA.Common 'Assert-PraOutputFolder' } + It 'accepts an existing backup folder written backups, LOGS or Reports at the root of the package, and still refuses another folder of the package' -ForEach @( + @{ Folder = 'backups'; Name = 'Storage.BackupFolder'; Canonical = 'Backups' } + @{ Folder = 'LOGS'; Name = 'Logging.Folder'; Canonical = 'logs' } + @{ Folder = 'Reports'; Name = 'Report.Folder'; Canonical = 'reports' } + ) { + $root = Join-Path $global:PraGate.Root ('case-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) + $null = New-Item -ItemType Directory -Path (Join-Path $root $Folder) -Force + $returned = Assert-PraOutputFolder -Path (Join-Path $root $Folder) -Name $Name -Canonical $Canonical -Root $root + $returned | Should -BeExactly (Join-Path (Get-PraPhysicalPath $root) $Folder) + $null = New-Item -ItemType Directory -Path (Join-Path $root 'Other') -Force + { Assert-PraOutputFolder -Path (Join-Path $root 'Other') -Name $Name -Canonical $Canonical -Root $root } | Should -Throw '*is not the*folder*' + } + It 'calls every Active Directory cmdlet with the name of its module, so that a function or an alias of the same name cannot answer' { + $cmdlets = 'Get-ADDomainController', 'Get-ADRootDSE', 'Get-ADUser', 'Get-ADGroup', 'Get-ADGroupMember', 'Get-ADObject', 'Get-ADOrganizationalUnit', 'Set-ADUser', 'Add-ADGroupMember', 'Remove-ADGroupMember', 'Sync-ADObject' + foreach ($relative in 'module\PRA.Directory.psm1', 'module\PRA.Gui.Directory.ps1', 'module\PRA.Backup.psm1', 'module\PRA.Common.psm1', 'module\PRA.Gui.psm1', 'Invoke-PraRemoteMailbox.ps1') { + $ast = [Management.Automation.Language.Parser]::ParseFile((Join-Path $global:PraGate.Package $relative), [ref]$null, [ref]$null) + $calls = @($ast.FindAll({ param($n) $n -is [Management.Automation.Language.CommandAst] }, $true) | ForEach-Object { [string]$_.GetCommandName() } | Where-Object { $_ }) + foreach ($cmdlet in $cmdlets) { @($calls | Where-Object { $_ -ceq $cmdlet }).Count | Should -Be 0 -Because ($relative + ' calls ' + $cmdlet + ' without its module') } + } + $directory = [IO.File]::ReadAllText((Join-Path $global:PraGate.Package 'module\PRA.Directory.psm1')) + ([regex]::Matches($directory, 'ActiveDirectory\\(Get|Set|Add|Remove|Sync)-AD\w+')).Count | Should -BeGreaterThan 20 + } +} + +Describe 'Release 3.3.0 - the folder check reads the owner, takes a Deny entry off only when it comes first, quotes a drive root, looks at the newest Finalize folders and at the base configuration file (production Common module, synthetic ACLs)' -Tag 'Release330B' { + BeforeAll { + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global + Register-PraTestProxy PRA.Common 'Get-PraPathExposure', 'Get-PraExposureFix', 'Get-PraRefusedReparseTag' + $script:Me = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value + $script:Rule = { param([string]$Sid, [int64]$Rights, [bool]$Allow = $true, [bool]$Inherited = $false) [pscustomobject]@{ Sid = $Sid; Allow = $Allow; Rights = $Rights; Inherited = $Inherited; InheritOnly = $false } } + $script:Path = Join-Path $global:PraGate.Root 'order' + } + It 'reports an owner outside the trusted set with the command that gives the folder to Administrators, unless an OWNER RIGHTS entry limits it or the SID is accepted' { + $rules = @(& $script:Rule 'S-1-5-18' 0x1F01FF) + $stranger = 'S-1-5-21-1-2-3-1105' + $owner = { param($path) 'S-1-5-21-1-2-3-1105' } + $found = Get-PraPathExposure -Path $script:Path -CurrentSid $script:Me -ReadAcl ({ param($p) $rules }.GetNewClosure()) -ReadOwner $owner + @($found.Write | ForEach-Object { $_.Sid + ':' + $_.Owner }) | Should -Be @($stranger + ':True') + (Get-PraExposureFix -Path $script:Path -Sid @($stranger) -Inherited $false -OwnerSid @($stranger)) | Should -BeLike '*/remove:g *S-1-5-21-1-2-3-1105 && icacls "*" /setowner *S-1-5-32-544' + $limited = @($rules + (& $script:Rule 'S-1-3-4' 0x20000)) + @((Get-PraPathExposure -Path $script:Path -CurrentSid $script:Me -ReadAcl ({ param($p) $limited }.GetNewClosure()) -ReadOwner $owner).Write).Count | Should -Be 0 + @((Get-PraPathExposure -Path $script:Path -CurrentSid $script:Me -ReadAcl ({ param($p) $rules }.GetNewClosure()) -ReadOwner $owner -Accepted @('s-1-5-21-1-2-3-1105')).Write).Count | Should -Be 0 + @((Get-PraPathExposure -Path $script:Path -CurrentSid $script:Me -ReadAcl ({ param($p) $rules }.GetNewClosure()) -ReadOwner { param($path) 'S-1-5-32-544' }).Write).Count | Should -Be 0 + $withEntry = @($rules + (& $script:Rule $stranger 0x1F01FF)) + @((Get-PraPathExposure -Path $script:Path -CurrentSid $script:Me -ReadAcl ({ param($p) $withEntry }.GetNewClosure()) -ReadOwner $owner).Write).Count | Should -Be 1 + } + It 'subtracts a Deny entry only from the Allow entries that come after it: ' -ForEach @( + @{ Name = 'an explicit Deny, then an explicit Allow'; Flagged = $false; Entries = @(@('S-1-5-32-550', 0x1F01FF, $false, $false), @('S-1-5-32-550', 0x1F01FF, $true, $false)) } + @{ Name = 'an explicit Allow, then an inherited Deny'; Flagged = $true; Entries = @(@('S-1-5-32-550', 0x1F01FF, $true, $false), @('S-1-5-32-550', 0x1F01FF, $false, $true)) } + @{ Name = 'an inherited Deny, then an inherited Allow'; Flagged = $false; Entries = @(@('S-1-5-32-550', 0x1F01FF, $false, $true), @('S-1-5-32-550', 0x1F01FF, $true, $true)) } + @{ Name = 'an Allow, then a Deny of the same level'; Flagged = $true; Entries = @(@('S-1-5-32-550', 0x1F01FF, $true, $true), @('S-1-5-32-550', 0x1F01FF, $false, $true)) } + @{ Name = 'a Deny of another SID'; Flagged = $true; Entries = @(@('S-1-5-32-551', 0x1F01FF, $false, $false), @('S-1-5-32-550', 0x1F01FF, $true, $false)) } + ) { + $rules = @(foreach ($entry in $Entries) { & $script:Rule $entry[0] ([int64]$entry[1]) $entry[2] $entry[3] }) + $found = Get-PraPathExposure -Path $script:Path -CurrentSid $script:Me -ReadAcl ({ param($p) $rules }.GetNewClosure()) -ReadOwner { param($path) 'S-1-5-32-544' } + (@($found.Write).Count -gt 0) | Should -Be $Flagged + } + It 'writes a drive root and a path that ends in a backslash so that the closing quote is not escaped' { + (Get-PraExposureFix -Path 'D:\' -Sid @('S-1-1-0') -Inherited $false) | Should -BeExactly 'icacls "D:\\" /remove:g *S-1-1-0' + (Get-PraExposureFix -Path 'D:\PRA\Backups' -Sid @('S-1-1-0') -Inherited $false) | Should -BeExactly 'icacls "D:\PRA\Backups" /remove:g *S-1-1-0' + } + It 'checks the 50 newest Finalize folders, and the base configuration file wherever it is' { + $package = Join-Path $global:PraGate.Root ('fin-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) + $backups = Join-Path $package 'Backups' + $null = New-Item -ItemType Directory -Path $backups -Force + for ($i = 0; $i -lt 52; $i++) { + $folder = Join-Path $backups ('Finalize-' + $i.ToString('00')) + $null = New-Item -ItemType Directory -Path $folder + [IO.Directory]::SetLastWriteTimeUtc($folder, [datetime]::UtcNow.AddHours(-$i)) + } + $base = Join-Path $global:PraGate.Root ('base-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.psd1') + [IO.File]::WriteAllText($base, '@{}') + $config = @{ Storage = @{ BackupFolder = $backups }; Logging = @{ Folder = (Join-Path $package 'logs') }; Report = @{ Folder = (Join-Path $package 'reports') }; Security = @{ AcceptedWriterSids = @() } } + $everyone = @([pscustomobject]@{ Sid = 'S-1-1-0'; Allow = $true; Rights = [int64]0x1F01FF; Inherited = $false; InheritOnly = $false }) + $exposure = Get-PraFolderExposure -Root $package -Config $config -Available @() -CurrentSid $script:Me -PowerShellHome (Join-Path $package 'none') -BaseFile @($base) -ReadAcl ({ param($p) $everyone }.GetNewClosure()) -ReadOwner { param($path) 'S-1-5-32-544' } + $names = @($exposure.Findings | Where-Object { $_.Role -ceq 'Finalize folder' } | ForEach-Object { Split-Path $_.Path -Leaf }) + $names.Count | Should -Be 50 + $names | Should -Contain 'Finalize-00' + $names | Should -Not -Contain 'Finalize-51' + $names | Should -Not -Contain 'Finalize-50' + @($exposure.Findings | Where-Object { $_.Role -ceq 'base configuration file' }).Count | Should -Be 1 + } + It 'applies the tag rule of the integrity check to the folders of the configuration: a OneDrive tag is accepted, a junction is refused ()' -ForEach @(@{ Tag = '9000001A'; Refused = $false }, @{ Tag = '80000013'; Refused = $false }, @{ Tag = 'A0000003'; Refused = $true }) { + $root = Join-Path $global:PraGate.Root ('tag-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) + $real = Join-Path $root 'Backups\real'; $link = Join-Path $root 'Backups\link' + $null = New-Item -ItemType Directory -Path $real -Force + $null = New-Item -ItemType Junction -Path $link -Target $real + try { + $answer = InModuleScope PRA.Common -Parameters @{ Root = $root; Link = $link; Tag = [Convert]::ToInt64($Tag, 16) } { + param($Root, $Link, $Tag) + Mock Get-PraReparseTag { $Tag } + try { [pscustomobject]@{ Refused = $false; Text = [string](Assert-PraOutputFolder -Path $Link -Name 'Storage.BackupFolder' -Canonical 'Backups' -Root $Root); Tag = (Get-PraRefusedReparseTag (Get-Item -LiteralPath $Link -Force)) } } + catch { [pscustomobject]@{ Refused = $true; Text = $_.Exception.Message; Tag = (Get-PraRefusedReparseTag (Get-Item -LiteralPath $Link -Force)) } } + } + $answer.Refused | Should -Be $Refused -Because $answer.Text + if ($Refused) { $answer.Text | Should -BeLike '*goes through a reparse point inside the package*' } else { $answer.Tag | Should -BeNullOrEmpty } + } + finally { [IO.Directory]::Delete($link); Remove-Item -LiteralPath $root -Recurse -Force -ErrorAction SilentlyContinue } + } +} + +Describe 'Release 3.3.0 - -Verbose:$false is not a reason to warn (real main, synthetic AD and cloud barrier)' -Tag 'Release330B' { + It 'warns when -Verbose is given and not when -Verbose:$false is given' -ForEach @(@{ Verbose = $true; Warned = $true }, @{ Verbose = $false; Warned = $false }) { + $runtime = New-GateRuntime -Name 'b-verbose' + $result = Invoke-GateProcess $runtime @{ Action = 'Convert'; Phase = 'AD'; Mode = 'Preview'; ConfigPath = $runtime.ConfigPath; Verbose = $Verbose } -TimeoutSeconds 120 + $result.ExitCode | Should -BeIn @(0, 2) + ($result.Output -match 'Verbose or -Debug is on') | Should -Be $Warned + } +} + +Describe 'Release 3.3.0 - the fingerprint of a package, the originals kept on the AD server, -ExpectedFingerprint, and the tenant and domain a file records (production Common and Directory modules, synthetic folders)' -Tag 'Release330C' { + BeforeAll { + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Directory.psm1') -Force -Global + $script:C330Root = Join-Path $global:PraGate.Root ('origin-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) + $null = New-Item -ItemType Directory -Path $script:C330Root -Force + $script:C330Counter = 0 + function script:New-C330Work { $script:C330Counter++; $path = Join-Path $script:C330Root ('w' + $script:C330Counter); $null = New-Item -ItemType Directory -Path $path -Force; $path } + function script:Use-C330Culture { + param([string]$Name, [scriptblock]$Do) + $old = [Globalization.CultureInfo]::CurrentCulture; $oldUi = [Globalization.CultureInfo]::CurrentUICulture + try { [Globalization.CultureInfo]::CurrentCulture = [Globalization.CultureInfo]::GetCultureInfo($Name); [Globalization.CultureInfo]::CurrentUICulture = [Globalization.CultureInfo]::GetCultureInfo($Name); & $Do } + finally { [Globalization.CultureInfo]::CurrentCulture = $old; [Globalization.CultureInfo]::CurrentUICulture = $oldUi } + } + # A batch folder with a JSON file, its checksum file and a raw file, as the AD server keeps them. + function script:New-C330Folder([string]$Parent, [string]$Name, [string]$Json, [string]$LeafName = 'Convert-x.json') { + $Json = '{"Operation":"Convert","BatchId":"cccccccc33333333cccccccc33333333","RawFile":"raw.clixml",' + $Json.TrimStart().Substring(1) + $folder = Join-Path $Parent $Name + $null = New-Item -ItemType Directory -Path $folder -Force + $utf8 = New-Object Text.UTF8Encoding($false) + [IO.File]::WriteAllText((Join-Path $folder $LeafName), $Json, $utf8) + [IO.File]::WriteAllText((Join-Path $folder ($LeafName + '.sha256')), (Get-FileHash -LiteralPath (Join-Path $folder $LeafName) -Algorithm SHA256).Hash.ToLowerInvariant(), $utf8) + [IO.File]::WriteAllBytes((Join-Path $folder 'raw.clixml'), [byte[]](1..200 | ForEach-Object { [byte]($_ % 251) })) + $folder + } + } + It 'shows the first 20 characters of the SHA-256 in groups of four, and accepts what the operator types in any letter case, with or without dashes and spaces ()' -ForEach @(@{ Culture = 'en-US' }, @{ Culture = 'fr-FR' }) { + Use-C330Culture $Culture { + $sha = 'abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789' + Format-PraFingerprint $sha | Should -BeExactly 'ABCD-EF01-2345-6789-ABCD' + Format-PraFingerprint 'abcdef0123456789abc' | Should -BeExactly '' + foreach ($typed in @('ABCD-EF01-2345-6789-ABCD', 'abcd-ef01-2345-6789-abcd', 'abcdef0123456789abcd', ' AbCd Ef01 2345 6789 aBcD ', $sha, $sha.ToUpperInvariant())) { Test-PraFingerprintMatch -Expected $typed -Sha256 $sha | Should -BeTrue -Because $typed } + foreach ($typed in @('', 'ABCD', 'ABCD-EF01-2345', 'abcdef012345', 'ABCD-EF01-2345-6789-ABCE', '0000-0000-0000-0000-0000', 'ABCD-EF01-2345-6789-ABCZ', ($sha + '00'))) { Test-PraFingerprintMatch -Expected $typed -Sha256 $sha | Should -BeFalse -Because $typed } + } + } + It 'reports the fingerprint of a package and the files it lists; a package written without the new keys (as 3.2.0 writes it) reports no tenant and no domain' { + $work = New-C330Work + $id = 'aaaaaaaa11111111aaaaaaaa11111111' + $folder = New-C330Folder (Join-Path $work 'src') "Batch-$id" '{"a":1}' + $package = New-PraTransferPackage -Kind Convert -Environment LAB -BatchId $id -Folders $folder -OutboxFolder (Join-Path $work 'out') -ToolVersion '3.2.0' + $info = Get-PraTransferPackage -Path $package.Path -Environment LAB + $info.Valid | Should -BeTrue -Because $info.Error + $info.Fingerprint | Should -BeExactly (Format-PraFingerprint $info.Sha256) + $info.Fingerprint | Should -Match '\A([0-9A-F]{4}-){4}[0-9A-F]{4}\z' + $package.Fingerprint | Should -BeExactly $info.Fingerprint + @($info.Entries | ForEach-Object Name) | Should -Be @("Batch-$id/Convert-x.json", "Batch-$id/Convert-x.json.sha256", "Batch-$id/raw.clixml") + $info.TenantId | Should -BeExactly ''; $info.DomainSid | Should -BeExactly ''; $info.DomainDnsRoot | Should -BeExactly '' + Get-PraIdentityDifference -Recorded $info -Current ([ordered]@{ TenantId = '11111111-2222-3333-4444-555555555555'; DomainSid = 'S-1-5-21-100-200-300'; DomainDnsRoot = 'gate.invalid' }) -What 'package' | Should -BeNullOrEmpty + $bare = Test-PraPackageOrigin -Package $info + @($bare.Refusals).Count | Should -Be 0 + $bare.Information[0] | Should -Match ('Package fingerprint ' + $info.Fingerprint) + } + It 'records the tenant and the domain in a new package, a new proof, and reads them back' { + $work = New-C330Work + $id = 'aaaaaaaa11111111aaaaaaaa11111111' + $identity = [ordered]@{ TenantId = '11111111-2222-3333-4444-555555555555'; DomainSid = 'S-1-5-21-100-200-300'; DomainDnsRoot = 'gate.invalid' } + $folder = New-C330Folder (Join-Path $work 'src') "Batch-$id" '{"a":1}' + $package = New-PraTransferPackage -Kind Convert -Environment LAB -BatchId $id -Folders $folder -OutboxFolder (Join-Path $work 'out') -Identity $identity + $info = Get-PraTransferPackage -Path $package.Path -Environment LAB + $info.TenantId | Should -BeExactly '11111111-2222-3333-4444-555555555555' + $info.DomainSid | Should -BeExactly 'S-1-5-21-100-200-300' + $info.DomainDnsRoot | Should -BeExactly 'gate.invalid' + $proofFolder = Join-Path $work 'proofs' + $written = Write-PraRetentionProof -Folder $proofFolder -BatchId $id -Environment LAB -Identity $identity -Object @([pscustomobject]@{ ObjectGuid = '00000000-0000-0000-0000-000000000001'; Upn = 'u1@contoso.invalid'; Verdict = 'Covered' }) + $written.Fingerprint | Should -BeExactly (Format-PraFingerprint $written.Sha256) + $read = Get-PraRetentionProof -Folder @($proofFolder) -BatchId $id -Environment 'lab' -MaxAgeHours 24 + $read.Found | Should -BeTrue -Because $read.Reason + $read.TenantId | Should -BeExactly '11111111-2222-3333-4444-555555555555' + $read.DomainSid | Should -BeExactly 'S-1-5-21-100-200-300' + $read.Fingerprint | Should -BeExactly $written.Fingerprint + $read.Proofs[0].Fingerprint | Should -BeExactly $written.Fingerprint + } + It 'compares what a Finalize loads and the AD server wrote with the originals kept here, by content: identical files match whatever they are called, a rewritten file is a difference, a file with no batch here has no original, and Transfer.RequireLocalOriginal refuses both ()' -ForEach @(@{ Culture = 'en-US' }, @{ Culture = 'fr-FR' }) { + Use-C330Culture $Culture { + $work = New-C330Work + $batch = 'cccccccc33333333cccccccc33333333' + $backups = Join-Path $work 'Backups' + $null = New-C330Folder $backups "batch-$batch" '{"Items":["genuine"]}' + $descriptor = { param($folder, $role, $id) @(Get-ChildItem -LiteralPath $folder -File | ForEach-Object { [pscustomobject]@{ Path = $_.FullName; Role = $role; BatchId = $id } }) } + $genuine = New-C330Folder (Join-Path $work 'g') 'Finalize-x' '{"Items":["genuine"]}' + $same = Get-PraFinalizeOriginalComparison -File (& $descriptor $genuine 'Convert backup' $batch) -BackupFolder $backups + $same.Status | Should -BeExactly 'Match' + @($same.Matched).Count | Should -Be 3 + $info = Get-PraOriginalFinding -Comparison $same -RequireLocalOriginal + @($info.Refusals).Count | Should -Be 0 + ($info.Information -join ' ') | Should -Match 'identical, by content, to the originals' + ($info.Information -join ' ') | Should -Match 'cannot be compared with an original kept here' + $renamed = New-C330Folder (Join-Path $work 'r') 'Finalize-x' '{"Items":["genuine"]}' 'Anything-else.json' + Rename-Item -LiteralPath (Join-Path $renamed 'Anything-else.json') -NewName 'Unrelated.txt' + (Get-PraFinalizeOriginalComparison -File (& $descriptor $renamed 'Convert backup' $batch) -BackupFolder $backups).Status | Should -BeExactly 'Match' -Because 'the original is found by content, whatever the files are called' + $forged = New-C330Folder (Join-Path $work 'f') 'Finalize-x' '{"Items":["rewritten"]}' + $different = Get-PraFinalizeOriginalComparison -File (& $descriptor $forged 'Convert backup' $batch) -BackupFolder $backups + $different.Status | Should -BeExactly 'Different' + @($different.Matched) | Should -Be @('raw.clixml (Convert backup)') + $finding = Get-PraOriginalFinding -Comparison $different + @($finding.Refusals).Count | Should -Be 0 + $finding.Warnings[0] | Should -Match '2 file\(s\) differ from the originals kept on this server, which holds the batch they name: Convert-x\.json \(Convert backup\), Convert-x\.json\.sha256' + $finding.Warnings[0] | Should -Match 'Transfer\.RequireLocalOriginal = \$true' + @((Get-PraOriginalFinding -Comparison $different -RequireLocalOriginal).Refusals).Count | Should -Be 1 + $foreign = Get-PraFinalizeOriginalComparison -File (& $descriptor $forged 'Recover backup' 'dddddddd44444444dddddddd44444444') -BackupFolder (Join-Path $work 'Rebuilt') + $foreign.Status | Should -BeExactly 'NoOriginal' + @((Get-PraOriginalFinding -Comparison $foreign).Warnings).Count | Should -Be 1 + @((Get-PraOriginalFinding -Comparison $foreign).Refusals).Count | Should -Be 0 + (Get-PraOriginalFinding -Comparison $foreign -RequireLocalOriginal).Refusals[0] | Should -Match 'Transfer\.RequireLocalOriginal is on: 3 file\(s\) have no original on this server' + $mixed = Get-PraFinalizeOriginalComparison -File ((& $descriptor $genuine 'Convert backup' $batch) + (& $descriptor $forged 'Recover backup' 'dddddddd44444444dddddddd44444444')) -BackupFolder $backups + $mixed.Status | Should -BeExactly 'NoOriginal' -Because 'one file of the AD server has no original: not a Match' + @($mixed.Matched).Count | Should -Be 4 -Because 'the raw file of the other backup has the same bytes, which are found' + @((Get-PraOriginalFinding -Comparison $mixed -RequireLocalOriginal).Refusals).Count | Should -Be 1 + ((Get-PraOriginalFinding -Comparison $mixed).Information -join ' ') | Should -Not -Match 'identical' + } + } + It 'finds an original by its content under any Batch-* folder, not by the name of the folder or of the file, and does not follow a folder that redirects' { + $work = New-C330Work + $backups = Join-Path $work 'Backups' + $null = New-C330Folder $backups 'Batch-eeeeeeee55555555eeeeeeee55555555' '{"Items":["genuine"]}' + $copy = New-C330Folder (Join-Path $work 'c') 'Finalize-y' '{"Items":["genuine"]}' + $files = @(Get-ChildItem -LiteralPath $copy -File | ForEach-Object { [pscustomobject]@{ Path = $_.FullName; Role = 'AD proof'; BatchId = 'ffffffff66666666ffffffff66666666' } }) + $found = Get-PraFinalizeOriginalComparison -File $files -BackupFolder $backups + $found.Status | Should -BeExactly 'Match' -Because 'the same content is in a batch folder, whatever batch the loaded file names' + $target = Join-Path $work 'elsewhere'; $null = New-C330Folder $target 'Batch-x' '{"Items":["genuine"]}' + $linked = Join-Path $work 'Linked'; $null = New-Item -ItemType Directory -Path $linked + $null = New-Item -ItemType Junction -Path (Join-Path $linked 'Batch-gggggggg77777777gggggggg77777777') -Target (Join-Path $target 'Batch-x') + try { (Get-PraFinalizeOriginalComparison -File $files -BackupFolder $linked).Status | Should -BeExactly 'NoOriginal' -Because 'a junction is not read' } + finally { [IO.Directory]::Delete((Join-Path $linked 'Batch-gggggggg77777777gggggggg77777777')) } + } + It 'refuses a package whose fingerprint is not the one typed, and accepts it in any letter case and with or without dashes ()' -ForEach @(@{ Culture = 'en-US' }, @{ Culture = 'fr-FR' }) { + Use-C330Culture $Culture { + $work = New-C330Work + $id = 'dddddddd44444444dddddddd44444444' + $package = New-PraTransferPackage -Kind Convert -Environment LAB -BatchId $id -Folders (New-C330Folder (Join-Path $work 'src') "Batch-$id" '{"a":1}') -OutboxFolder (Join-Path $work 'out') + $info = Get-PraTransferPackage -Path $package.Path -Environment LAB + foreach ($typed in @($info.Fingerprint, $info.Fingerprint.ToLowerInvariant(), $info.Fingerprint.Replace('-', '').ToLowerInvariant(), $info.Sha256.ToUpperInvariant())) { + $good = Test-PraPackageOrigin -Package $info -ExpectedFingerprint $typed + @($good.Refusals).Count | Should -Be 0 -Because $typed + ($good.Information -join ' ') | Should -Match 'is the one given with -ExpectedFingerprint' + } + $wrong = Test-PraPackageOrigin -Package $info -ExpectedFingerprint '0000-0000-0000-0000-0000' + @($wrong.Refusals).Count | Should -Be 1 + $wrong.Refusals[0] | Should -Match ('The fingerprint of this package is ' + $info.Fingerprint + ', not the one given with -ExpectedFingerprint \(0000-0000-0000-0000-0000\)') + $wrong.Refusals[0] | Should -Match 'Nothing was imported' + $backups = Join-Path $work 'Backups' + $refuse = { param($p) $o = Test-PraPackageOrigin -Package $p -ExpectedFingerprint '0000-0000-0000-0000-0000'; if (@($o.Refusals).Count) { throw $o.Refusals[0] } } + $backups = Join-Path $work 'Backups' + { Import-PraTransferPackage -Path $package.Path -BackupFolder $backups -Environment LAB -ExpectedKind Convert -BeforeExtract $refuse } | Should -Throw '*not the one given with -ExpectedFingerprint*' + Test-Path -LiteralPath (Join-Path $backups "Batch-$id") | Should -BeFalse + $malformed = Test-PraPackageOrigin -Package $info -ExpectedFingerprint 'ABCD-EF01' + $malformed.Refusals[0] | Should -Match 'is not a fingerprint: it is 20 to 64 hexadecimal characters' + $malformed.Refusals[0] | Should -Not -Match 'not the one given' + } + } + It 'compares the originals with the files of a Finalize folder written by the frozen 2.2.0 fixtures: the same files match by content' { + $fixtureRoot = Join-Path $global:PraGate.Release 'tests\fixtures\ps51-2.2.0' + $finalize = @(Get-ChildItem -LiteralPath (Join-Path $fixtureRoot '03-finalize-shared13') -Directory | Where-Object Name -Like 'Finalize-*')[0] + $work = New-C330Work + $backups = Join-Path $work 'Backups' + $null = New-Item -ItemType Directory -Path $backups -Force + $loaded = New-Object 'Collections.Generic.List[object]' + foreach ($file in @(Get-ChildItem -LiteralPath $finalize.FullName -File | Where-Object { $_.Name -match '\A(Convert|Recover|State)-' })) { + $batchId = if ($file.Name -like 'Convert-*') { 'cf72361c626a45b1929f878eecf932f5' } else { 'fbb1600986cc48e8b61bb2fba771eb8d' } + $loaded.Add([pscustomobject]@{ Path = $file.FullName; Role = 'fixture'; BatchId = $batchId }) + } + $loaded.Count | Should -BeGreaterThan 5 + (Get-PraFinalizeOriginalComparison -File $loaded.ToArray() -BackupFolder $backups).Status | Should -BeExactly 'NoOriginal' -Because 'the server holds nothing yet' + foreach ($other in @(Get-ChildItem -LiteralPath (Join-Path $fixtureRoot '04-shared13') -Directory -Filter 'Batch-*')) { Copy-Item -LiteralPath $other.FullName -Destination $backups -Recurse } + foreach ($backup in @($loaded | Where-Object { [IO.Path]::GetFileName($_.Path) -match '\A(Convert|Recover)-' })) { + Copy-Item -LiteralPath $backup.Path -Destination (Join-Path $backups $(if ([IO.Path]::GetFileName($backup.Path) -like 'Convert-*') { 'Batch-cf72361c626a45b1929f878eecf932f5' } else { 'Batch-fbb1600986cc48e8b61bb2fba771eb8d' })) + } + $found = Get-PraFinalizeOriginalComparison -File $loaded.ToArray() -BackupFolder $backups + $found.Status | Should -BeExactly 'Match' -Because ((@($found.Different) + @($found.NoOriginal)) -join ', ') + @($found.Matched).Count | Should -Be $loaded.Count + @((Get-PraOriginalFinding -Comparison $found -RequireLocalOriginal).Refusals).Count | Should -Be 0 + } + It 'reads the tenant and the domain a file records and compares them with the ones the run knows: any letter case, nothing for a file that records none ()' -ForEach @(@{ Culture = 'en-US' }, @{ Culture = 'fr-FR' }) { + Use-C330Culture $Culture { + $context = @{ Config = @{ Cloud = @{ TenantId = '11111111-2222-3333-4444-555555555555' } }; DomainSid = 's-1-5-21-100-200-300'; DomainDnsRoot = 'GATE.INVALID' } + $current = Get-PraRunIdentity -Context $context + $current['TenantId'] | Should -BeExactly '11111111-2222-3333-4444-555555555555' + $current['DomainSid'] | Should -BeExactly 'S-1-5-21-100-200-300' + $current['DomainDnsRoot'] | Should -BeExactly 'gate.invalid' + @((Get-PraRunIdentity -Context @{ Config = @{ Cloud = @{ TenantId = 'not a guid' } }; DomainSid = 'S-1-5-18' }).Keys).Count | Should -Be 0 + @((Get-PraRunIdentity -Context @{ Config = @{} }).Keys).Count | Should -Be 0 + Get-PraIdentityDifference -Recorded ([pscustomobject]@{ TenantId = '11111111-2222-3333-4444-555555555555'.ToUpperInvariant(); DomainSid = 'S-1-5-21-100-200-300'; DomainDnsRoot = 'Gate.Invalid' }) -Current $current | Should -BeNullOrEmpty + Get-PraIdentityDifference -Recorded $null -Current $current | Should -BeNullOrEmpty + Get-PraIdentityDifference -Recorded ([pscustomobject]@{ SchemaVersion = 3; Environment = 'PROD' }) -Current $current | Should -BeNullOrEmpty + $other = @(Get-PraIdentityDifference -Recorded ([pscustomobject]@{ TenantId = '99999999-2222-3333-4444-555555555555'; DomainSid = 'S-1-5-21-1-2-3' }) -Current $current -What 'backup') + $other.Count | Should -Be 2 + $other[0] | Should -Match '\AThis backup records another tenant than this run knows \(99999999-2222-3333-4444-555555555555 in the file, 11111111-2222-3333-4444-555555555555 here\): it was made for another tenant\. Check that this is the right server and the right configuration file; Transfer\.RequireSameDomain = \$true makes such a file a refusal\.\z' + $other[1] | Should -Match 'another domain than this run knows' + Get-PraIdentityDifference -Recorded ([pscustomobject]@{ TenantId = '99999999-2222-3333-4444-555555555555' }) -Current ([ordered]@{}) | Should -BeNullOrEmpty -Because 'a run that knows nothing compares nothing' + } + } + It 'compares the licence group, the retention tag and the domain controller of a batch with the configuration, and says nothing for a batch that matches ()' -ForEach @(@{ Culture = 'en-US' }, @{ Culture = 'fr-FR' }) { + Use-C330Culture $Culture { + $record = [pscustomobject]@{ ObjectGuid = '00000000-0000-0000-0000-000000000001'; Licensing = [pscustomobject]@{ Enabled = $true; GroupGuid = '10000000-0000-0000-0000-000000000001'; GroupDN = 'CN=License,OU=Tests,DC=gate,DC=invalid' }; Retention = [pscustomobject]@{ Enabled = $true; Attribute = 'extensionAttribute1'; Value = 'Converted' } } + $source = [pscustomobject]@{ Data = [pscustomobject]@{ Records = @($record); Server = 'dc01.gate.invalid' } } + $new = { param([string]$Group, [string]$Attribute, [string]$Value, [string]$Controller) @{ Config = @{ DomainController = $Controller; Licensing = @{ Enabled = $true; GroupDN = $Group }; Retention = @{ Enabled = $true; Tag = @{ Enabled = $true; Attribute = $Attribute; Value = $Value } }; Cloud = @{ TenantId = '' } } } } + $same = Test-PraBatchOrigin -Context (& $new 'cn=license, ou=Tests,DC=gate,DC=invalid' 'EXTENSIONATTRIBUTE1' 'converted' '') -Source $source + @($same.ConfigMatch).Count | Should -Be 0 + @($same.Identity).Count | Should -Be 0 + @($same.Groups) | Should -Be @('CN=License,OU=Tests,DC=gate,DC=invalid') + $group = Test-PraBatchOrigin -Context (& $new 'CN=Other,OU=Tests,DC=gate,DC=invalid' 'extensionAttribute1' 'Converted' '') -Source $source + @($group.ConfigMatch).Count | Should -Be 1 + $group.ConfigMatch[0] | Should -Match 'changes the membership of the licence group CN=License,OU=Tests,DC=gate,DC=invalid, and Licensing\.GroupDN of this configuration is CN=Other,OU=Tests,DC=gate,DC=invalid\. Read the group with: Get-ADGroup -Identity ''CN=License,OU=Tests,DC=gate,DC=invalid''' + $noLicence = Test-PraBatchOrigin -Context @{ Config = @{ DomainController = ''; Licensing = @{ Enabled = $false; GroupDN = '' }; Retention = @{ Enabled = $true; Tag = @{ Enabled = $true; Attribute = 'extensionAttribute1'; Value = 'Converted' } } } } -Source $source + $noLicence.ConfigMatch[0] | Should -Match 'names no licence group' + $tag = Test-PraBatchOrigin -Context (& $new 'CN=License,OU=Tests,DC=gate,DC=invalid' 'extensionAttribute2' 'Converted' '') -Source $source + @($tag.ConfigMatch).Count | Should -Be 1 + $tag.ConfigMatch[0] | Should -Match 'writes the retention tag extensionAttribute1 = Converted, and Retention\.Tag of this configuration is extensionAttribute2 = Converted' + $shape = Get-PraBatchServerFinding -Server 'dc01;calc' + $shape.Use | Should -BeFalse + $shape.Findings[0] | Should -Match 'is not a host name \(dc01;calc\): this run does not connect to it' + $known = Get-PraBatchServerFinding -Server 'dc02.gate.invalid' -InDomain 'Yes' + $known.Use | Should -BeTrue + @($known.Findings).Count | Should -Be 0 -Because 'another domain controller of the same domain is normal' + @((Get-PraBatchServerFinding -Server 'dc02.gate.invalid' -InDomain 'Unknown').Findings).Count | Should -Be 0 + $foreign = Get-PraBatchServerFinding -Server 'dc99.fabrikam.invalid' -InDomain 'No' + $foreign.Use | Should -BeFalse -Because 'a name that the domain does not list is never connected to' + $foreign.Findings[0] | Should -Match 'names the domain controller dc99\.fabrikam\.invalid, and the domain of this machine says that it is not one of its domain controllers: this run does not connect to it' + @((Get-PraBatchServerFinding -Server '').Findings).Count | Should -Be 0 + $identityOnly = Test-PraBatchOrigin -Context (& $new 'CN=Other,OU=Tests,DC=gate,DC=invalid' 'extensionAttribute2' 'Converted' '') -Source $source -IdentityOnly + @($identityOnly.ConfigMatch).Count | Should -Be 0 + $old = [pscustomobject]@{ Data = [pscustomobject]@{ SchemaVersion = 1; Records = @([pscustomobject]@{ ObjectGuid = '00000000-0000-0000-0000-000000000001' }) } } + $legacy = Test-PraBatchOrigin -Context (& $new 'CN=License,OU=Tests,DC=gate,DC=invalid' 'extensionAttribute1' 'Converted' '') -Source $old + @($legacy.ConfigMatch).Count | Should -Be 0 -Because 'a batch of an older version without those keys is accepted without a word' + @($legacy.Identity).Count | Should -Be 0 + } + } +} + +Describe 'Release 3.3.0 - the shared secret of the transfer files: the .auth file, the key file, the passphrase (production Common module, synthetic files)' -Tag 'Release330C' { + BeforeAll { + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global + $script:C330Auth = Join-Path $global:PraGate.Root ('auth-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) + $null = New-Item -ItemType Directory -Path $script:C330Auth -Force + function script:New-C330Secret([string]$Text) { $secure = New-Object Security.SecureString; foreach ($character in $Text.ToCharArray()) { $secure.AppendChar($character) }; $secure.MakeReadOnly(); $secure } + function script:New-C330File { + $path = Join-Path $script:C330Auth ([guid]::NewGuid().ToString('N').Substring(0, 8) + '.zip') + [IO.File]::WriteAllBytes($path, [byte[]](1..64)) + $path + } + $script:C330Parameters = @{ FileKind = 'Package:Convert'; Environment = 'LAB'; BatchId = 'aaaaaaaa11111111aaaaaaaa11111111'; CreatedUtc = '2026-11-24T10:00:00.1234567Z'; FileSha256 = ('ab' * 32) } + } + It 'writes a file that checks with the same passphrase, refuses another passphrase, and never holds the passphrase or the key ()' -ForEach @(@{ Culture = 'en-US' }, @{ Culture = 'fr-FR' }) { + $old = [Globalization.CultureInfo]::CurrentCulture + try { + [Globalization.CultureInfo]::CurrentCulture = [Globalization.CultureInfo]::GetCultureInfo($Culture) + $path = New-C330File + $parameters = $script:C330Parameters + (Test-PraAuthSidecar -Path $path @parameters).Status | Should -BeExactly 'Absent' + $written = Write-PraAuthSidecar -Path $path @parameters -Passphrase (New-C330Secret 'Correct Horse Battery') + $written | Should -BeExactly ($path + '.auth') + (Test-PraAuthSidecar -Path $path @parameters -Passphrase (New-C330Secret 'Correct Horse Battery')).Status | Should -BeExactly 'Valid' + (Test-PraAuthSidecar -Path $path @parameters -Passphrase (New-C330Secret 'correct horse battery')).Status | Should -BeExactly 'Invalid' -Because 'a secret is compared exactly' + (Test-PraAuthSidecar -Path $path @parameters).Status | Should -BeExactly 'NoKey' + $text = [IO.File]::ReadAllText($written) + $text | Should -Not -Match 'Correct Horse' + $header = $text | ConvertFrom-Json + $header.Algorithm | Should -BeExactly 'HMAC-SHA256' + $header.Kdf | Should -BeExactly 'PBKDF2-HMAC-SHA256' + [int]$header.Iterations | Should -BeGreaterOrEqual 600000 + [Convert]::FromBase64String($header.Salt).Length | Should -BeGreaterOrEqual 16 + [Convert]::FromBase64String($header.Mac).Length | Should -Be 32 + { Write-PraAuthSidecar -Path $path @parameters -Passphrase (New-C330Secret 'x') } | Should -Throw -Because 'an existing file is never overwritten' + } + finally { [Globalization.CultureInfo]::CurrentCulture = $old } + } + It 'gives the same key for a passphrase typed composed or decomposed (an accent), and a different one for another word' { + $path = New-C330File; $parameters = $script:C330Parameters + $null = Write-PraAuthSidecar -Path $path @parameters -Passphrase (New-C330Secret ("caf" + [char]0x00E9 + ' noir')) + (Test-PraAuthSidecar -Path $path @parameters -Passphrase (New-C330Secret ("cafe" + [char]0x0301 + ' noir'))).Status | Should -BeExactly 'Valid' + (Test-PraAuthSidecar -Path $path @parameters -Passphrase (New-C330Secret 'cafe noir')).Status | Should -BeExactly 'Invalid' + Test-PraAuthPassphraseEqual (New-C330Secret 'abc') (New-C330Secret 'abc') | Should -BeTrue + Test-PraAuthPassphraseEqual (New-C330Secret 'abc') (New-C330Secret 'ABC') | Should -BeFalse + } + It 'creates a key file that only this account, SYSTEM and Administrators can read, never overwrites it, and checks with it' { + $key = Join-Path $script:C330Auth ('key-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.txt') + (New-PraAuthKeyFile -Path $key) | Should -BeExactly $key + [Convert]::FromBase64String([IO.File]::ReadAllText($key).Trim()).Length | Should -Be 32 + { New-PraAuthKeyFile -Path $key } | Should -Throw + $acl = [IO.FileSystemAclExtensions]::GetAccessControl((New-Object IO.FileInfo $key)) + $acl.AreAccessRulesProtected | Should -BeTrue + $sids = @($acl.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier]) | ForEach-Object { $_.IdentityReference.Value } | Sort-Object -Unique) + $allowed = @([Security.Principal.WindowsIdentity]::GetCurrent().User.Value, 'S-1-5-18', 'S-1-5-32-544') + foreach ($sid in $sids) { $allowed | Should -Contain $sid } + $path = New-C330File; $parameters = $script:C330Parameters + $null = Write-PraAuthSidecar -Path $path @parameters -KeyFile $key + (Test-PraAuthSidecar -Path $path @parameters -KeyFile $key).Status | Should -BeExactly 'Valid' + [IO.File]::ReadAllText($path + '.auth') | Should -Not -Match ([regex]::Escape([IO.File]::ReadAllText($key).Trim())) + (Test-PraAuthSidecar -Path $path @parameters).Status | Should -BeExactly 'NoKey' + $other = Join-Path $script:C330Auth ('key-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.txt'); $null = New-PraAuthKeyFile -Path $other + (Test-PraAuthSidecar -Path $path @parameters -KeyFile $other).Status | Should -BeExactly 'Invalid' + $short = Join-Path $script:C330Auth 'short.txt'; [IO.File]::WriteAllText($short, [Convert]::ToBase64String([byte[]](1..8))) + (Test-PraAuthSidecar -Path $path @parameters -KeyFile $short).Status | Should -BeExactly 'Invalid' + (Test-PraAuthSidecar -Path $path @parameters -KeyFile (Join-Path $script:C330Auth 'missing.txt')).Status | Should -BeExactly 'Invalid' + } + It 'does not accept a file that was changed, a tag made for another file, batch, kind or time, or a weak derivation, and ignores the case of the Environment and the batch' { + $key = Join-Path $script:C330Auth ('key-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.txt'); $null = New-PraAuthKeyFile -Path $key + $path = New-C330File; $parameters = $script:C330Parameters + $null = Write-PraAuthSidecar -Path $path @parameters -KeyFile $key + $with = { param([hashtable]$Change) $copy = $parameters.Clone(); foreach ($name in $Change.Keys) { $copy[$name] = $Change[$name] }; (Test-PraAuthSidecar -Path $path @copy -KeyFile $key).Status } + & $with @{} | Should -BeExactly 'Valid' + & $with @{ Environment = 'lab' } | Should -BeExactly 'Valid' + & $with @{ BatchId = 'AAAAAAAA11111111AAAAAAAA11111111' } | Should -BeExactly 'Valid' + & $with @{ CreatedUtc = '2026-11-24T10:00:00.1234567+00:00' } | Should -BeExactly 'Valid' -Because 'the same instant written another way' + & $with @{ FileSha256 = ('cd' * 32) } | Should -BeExactly 'Invalid' + & $with @{ FileKind = 'RetentionProof' } | Should -BeExactly 'Invalid' -Because 'a tag of a proof is not a tag of a package' + & $with @{ Environment = 'PROD' } | Should -BeExactly 'Invalid' + & $with @{ BatchId = 'bbbbbbbb22222222bbbbbbbb22222222' } | Should -BeExactly 'Invalid' + & $with @{ CreatedUtc = '2026-11-24T10:00:01.0000000Z' } | Should -BeExactly 'Invalid' + $sidecar = $path + '.auth'; $original = [IO.File]::ReadAllText($sidecar) + $edit = { param([scriptblock]$Change) $data = $original | ConvertFrom-Json -AsHashtable; & $Change $data; [IO.File]::WriteAllText($sidecar, ($data | ConvertTo-Json)); (Test-PraAuthSidecar -Path $path @parameters -KeyFile $key).Status } + & $edit { param($d) $d.Mac = [Convert]::ToBase64String([byte[]](1..32)) } | Should -BeExactly 'Invalid' + & $edit { param($d) $d.Mac = 'not base64!' } | Should -BeExactly 'Invalid' + & $edit { param($d) $d.Algorithm = 'HMAC-MD5' } | Should -BeExactly 'Invalid' + & $edit { param($d) $d.KeySource = 'Magic' } | Should -BeExactly 'Invalid' + [IO.File]::WriteAllText($sidecar, 'not json'); (Test-PraAuthSidecar -Path $path @parameters -KeyFile $key).Status | Should -BeExactly 'Invalid' + [IO.File]::WriteAllText($sidecar, $original); (Test-PraAuthSidecar -Path $path @parameters -KeyFile $key).Status | Should -BeExactly 'Valid' + $weak = New-C330File + $null = Write-PraAuthSidecar -Path $weak @parameters -Passphrase (New-C330Secret 'secret') + $data = [IO.File]::ReadAllText($weak + '.auth') | ConvertFrom-Json -AsHashtable + $data.Iterations = 1000 + [IO.File]::WriteAllText($weak + '.auth', ($data | ConvertTo-Json)) + (Test-PraAuthSidecar -Path $weak @parameters -Passphrase (New-C330Secret 'secret')).Status | Should -BeExactly 'Invalid' -Because 'a derivation below 600000 iterations is not one this version writes' + } +} + +Describe 'Release 3.3.0 - the settings of the transfer checks and of the live retention check: defaults, validation, shipped file (production Common module)' -Tag 'Release330C' { + BeforeAll { Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global } + It 'a configuration without the new keys behaves as before: every Require setting and the shared secret are off, the key file is empty' { + $path = Join-Path $global:PraGate.Root ('cfg-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.psd1') + [IO.File]::WriteAllText($path, "@{ Environment='SYNTHETIC'; Scope=@{Mode='Auto'}; Licensing=@{Enabled=`$false} }", (New-Object Text.UTF8Encoding($true))) + $config = Import-PraConfiguration -Path $path -Root $global:PraGate.Source -DeferScopeCheck + foreach ($name in 'RequireLocalOriginal', 'RequireConfigMatch', 'RequireSameDomain', 'Authenticate', 'RequireAuthentication') { $config.Transfer[$name] | Should -BeFalse -Because $name } + $config.Transfer.KeyFile | Should -BeExactly '' + $config.Retention.RequireLiveCheck | Should -BeFalse + $shipped = Import-PowerShellDataFile -LiteralPath (Join-Path $global:PraGate.Source 'config\PraRemoteMailbox.config.psd1') + foreach ($name in 'RequireLocalOriginal', 'RequireConfigMatch', 'RequireSameDomain', 'Authenticate', 'RequireAuthentication') { $shipped.Transfer[$name] | Should -BeFalse -Because $name } + $shipped.Transfer.KeyFile | Should -BeExactly '' + $shipped.Retention.RequireLiveCheck | Should -BeFalse + $text = [IO.File]::ReadAllText((Join-Path $global:PraGate.Source 'config\PraRemoteMailbox.config.psd1')) + foreach ($name in 'RequireLocalOriginal', 'RequireConfigMatch', 'RequireSameDomain', 'RequireAuthentication', 'RequireLiveCheck', 'KeyFile') { $text | Should -Match ('#\s+' + $name) -Because ('the file documents ' + $name) } + } + It 'refuses an unknown key of the Transfer section, a value that is not true or false, and a key file that is not text; a relative key file is relative to the tool folder' { + $make = { param($body) $path = Join-Path $global:PraGate.Root ('cfg-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.psd1'); [IO.File]::WriteAllText($path, "@{ Environment='SYNTHETIC'; Scope=@{Mode='Auto'}; Licensing=@{Enabled=`$false}; $body }", (New-Object Text.UTF8Encoding($true))); $path } + { Import-PraConfiguration -Path (& $make 'Transfer=@{Bogus=$true}') -Root $global:PraGate.Source -DeferScopeCheck } | Should -Throw '*unknown setting Transfer.Bogus*' + { Import-PraConfiguration -Path (& $make "Transfer=@{RequireLocalOriginal='yes'}") -Root $global:PraGate.Source -DeferScopeCheck } | Should -Throw '*Transfer.RequireLocalOriginal must be $true or $false*' + { Import-PraConfiguration -Path (& $make 'Transfer=@{KeyFile=5}') -Root $global:PraGate.Source -DeferScopeCheck } | Should -Throw '*Transfer.KeyFile must be text between quotes*' + { Import-PraConfiguration -Path (& $make 'Retention=@{RequireLiveCheck=1}') -Root $global:PraGate.Source -DeferScopeCheck } | Should -Throw '*Retention.RequireLiveCheck must be $true or $false*' + $config = Import-PraConfiguration -Path (& $make "Transfer=@{RequireSameDomain=`$true;Authenticate=`$true;KeyFile='keys\pra.key'}; Retention=@{RequireLiveCheck=`$true}") -Root $global:PraGate.Source -DeferScopeCheck + $config.Transfer.RequireSameDomain | Should -BeTrue + $config.Retention.RequireLiveCheck | Should -BeTrue + $config.Transfer.KeyFile | Should -BeExactly (Join-Path $global:PraGate.Source 'keys\pra.key') + } + It 'shows the new settings in what the run will use, and the shared secret never shows a passphrase' { + $path = Join-Path $global:PraGate.Root ('cfg-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.psd1') + [IO.File]::WriteAllText($path, "@{ Environment='SYNTHETIC'; Scope=@{Mode='Auto'}; Licensing=@{Enabled=`$false}; Transfer=@{RequireAuthentication=`$true;RequireLocalOriginal=`$true} }", (New-Object Text.UTF8Encoding($true))) + $config = Import-PraConfiguration -Path $path -Root $global:PraGate.Source -DeferScopeCheck + $rows = @(& (Get-Module PRA.Common) { param($c) Get-PraRunSetting -Config $c } $config) + ($rows | Where-Object Name -EQ 'Local original required').Value | Should -BeExactly 'on' + ($rows | Where-Object Name -EQ 'Configuration match required').Value | Should -BeExactly 'off' + ($rows | Where-Object Name -EQ 'Shared secret for packages and proofs').Value | Should -BeExactly 'required, typed passphrase' + ($rows | Where-Object Name -EQ 'Live retention check required').Value | Should -BeExactly 'off' + } +} + +Describe 'Release 3.3.0 - the entry script: what a package, a backup and a proof record and show, the shared secret, the configuration match, and the retention gate that says what decided (real main, production Directory module, synthetic AD and cloud barrier)' -Tag 'Release330C' { + BeforeAll { + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global + function script:Get-C330Flat($Run) { [regex]::Replace([string]$Run.Output, '\s+', ' ') } + function script:Get-C330Why($Run) { (@(([string]$Run.Output + [string]$Run.Error) -split '\r?\n' | Where-Object { $_ -match 'Stopped at step|refused|Nothing was|cannot|failed|Error' } | Select-Object -First 8) -join ' | ') } + function script:Set-C330Converted { + param($Runtime, $Bundles) + $module = Get-Module PRA.Directory + foreach ($plan in $Bundles.Plans) { + $user = @($Runtime.State.Users | Where-Object ObjectGUID -eq $plan.Record.ObjectGuid)[0] + foreach ($key in $plan.Kinds.Keys) { $user.$key = & $module { param($state) ConvertFrom-PraStoredValue $state } $plan.Desired[$key] } + $user.uSNChanged = [long]101 + } + $Runtime.State.Group.member = @($Runtime.State.Users | ForEach-Object DistinguishedName) + [IO.File]::WriteAllText($Runtime.StatePath, [Management.Automation.PSSerializer]::Serialize($Runtime.State, 35)) + } + function script:New-C330Proof { + param($Runtime, $Bundles, [string]$Folder = '', [switch]$Tamper, [System.Collections.IDictionary]$Identity) + if (-not $Folder) { $Folder = Join-Path $Runtime.State.BackupFolder 'Inbox' } + $source = Get-Content -LiteralPath $Bundles.Source -Raw | ConvertFrom-Json + $hash = (Get-FileHash -LiteralPath $Bundles.Source -Algorithm SHA256).Hash.ToLowerInvariant() + $objects = @($source.Records | ForEach-Object { [pscustomobject]@{ ObjectGuid = [string]$_.ObjectGuid; Upn = [string]$_.UserPrincipalName; Verdict = 'Covered' } }) + $parameters = @{ Folder = $Folder; BatchId = [string]$source.BatchId; SourceBackupHash = $hash; Environment = 'SYNTHETIC_GATE'; Object = $objects } + if ($null -ne $Identity) { $parameters['Identity'] = $Identity } + $written = Write-PraRetentionProof @parameters + if ($Tamper) { [IO.File]::WriteAllText($written.Sidecar, ('0' * 64)) } + $written + } + function script:Use-C330Config { + param($Runtime, [string]$Section = '', [string]$Retention = '') + $transform = { + param($text) + if ($Section) { $text = $text.Replace("Execution=@{Phase='Both'}", "Execution=@{Phase='Both'}`r`n $Section") } + if ($Retention) { $text = $text.Replace('Retention=@{Enabled=$true;', 'Retention=@{Enabled=$true;' + $Retention + ';') } + $text + }.GetNewClosure() + Set-GateConfigText $Runtime $transform + } + } + BeforeEach { + $runtime = New-GateRuntime -Name 'origin-330c' + $env:PRA_GATE_STATE = $runtime.StatePath + $env:PSModulePath = $runtime.Modules + ';' + (Join-Path $PSHOME 'Modules') + Remove-Module PRA.Directory -Force -ErrorAction SilentlyContinue + Get-Module ActiveDirectory -All | Remove-Module -Force -ErrorAction Stop + Import-Module (Join-Path $runtime.Modules 'ActiveDirectory\ActiveDirectory.psm1') -Force -Global + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Directory.psm1') -Force -Global + } + AfterAll { Remove-Item -LiteralPath 'Function:\Set-C330Converted', 'Function:\New-C330Proof', 'Function:\Use-C330Config' -ErrorAction SilentlyContinue } + It 'records the tenant and the domain in the backup, the proof and the package of a Convert, shows the fingerprint, writes the .auth file with the key file, and records -Force' { + $key = Join-Path $runtime.Root 'secret.key'; $null = New-PraAuthKeyFile -Path $key + Use-C330Config $runtime -Section ("Cloud=@{TenantId='11111111-2222-3333-4444-555555555555';Organization='contoso.onmicrosoft.com'}`r`n Transfer=@{Authenticate=`$true;KeyFile='" + $key + "'}") + $run = Invoke-GateProcess $runtime @{Action='Convert';Phase='AD';Mode='Apply';Force=$true;ConfigPath=$runtime.ConfigPath} -TimeoutSeconds 120 + $run.ExitCode | Should -Be 2 -Because (Get-C330Why $run) + $folder = @(Get-ChildItem -LiteralPath $runtime.State.BackupFolder -Directory | Where-Object Name -Like 'Batch-*')[0].FullName + foreach ($file in @((Get-ChildItem -LiteralPath $folder -Filter 'Convert-*.json')[0], (Get-ChildItem -LiteralPath $folder -Filter 'State-*.json')[0])) { + $data = [IO.File]::ReadAllText($file.FullName) | ConvertFrom-Json + $data.TenantId | Should -BeExactly '11111111-2222-3333-4444-555555555555' -Because $file.Name + $data.DomainSid | Should -BeExactly 'S-1-5-21-100-200-300' -Because $file.Name + $data.DomainDnsRoot | Should -BeExactly 'gate.invalid' -Because $file.Name + } + $zip = [string]$run.MainResult.TransferPackage + $info = Get-PraTransferPackage -Path $zip -Environment SYNTHETIC_GATE + $info.Valid | Should -BeTrue -Because $info.Error + $info.TenantId | Should -BeExactly '11111111-2222-3333-4444-555555555555' + $info.DomainSid | Should -BeExactly 'S-1-5-21-100-200-300' + (Get-C330Flat $run) | Should -Match ('Package fingerprint ' + [regex]::Escape($info.Fingerprint) + ' \(the start of its SHA-256\)') + Test-Path -LiteralPath ($zip + '.auth') -PathType Leaf | Should -BeTrue + (Test-PraAuthSidecar -Path $zip -FileKind 'Package:Convert' -Environment SYNTHETIC_GATE -BatchId $info.BatchId -CreatedUtc $info.CreatedUtc -FileSha256 $info.Sha256 -KeyFile $key).Status | Should -BeExactly 'Valid' + ($run.MainResult.NextSteps -join "`n") | Should -Match 'Copy these three files, together in the same folder, to the cloud server \(anywhere\): .*for-Cloud\.zip, .*for-Cloud\.zip\.sha256 and .*for-Cloud\.zip\.auth\. Then run there:' + ($run.MainResult.ConfigOverrides -join '|') | Should -Match 'Confirmation skipped for this run \(-Force\)' + (Get-C330Flat $run) | Should -Not -Match ([regex]::Escape([IO.File]::ReadAllText($key).Trim())) + } + It 'imports that package on the cloud server: the fingerprint is shown, -ExpectedFingerprint decides in any letter case, and Transfer.RequireAuthentication refuses a package without its .auth file before anything is written' { + $key = Join-Path $runtime.Root 'secret.key'; $null = New-PraAuthKeyFile -Path $key + Use-C330Config $runtime -Section ("Transfer=@{Authenticate=`$true;KeyFile='" + $key + "'}") + $made = Invoke-GateProcess $runtime @{Action='Convert';Phase='AD';Mode='Apply';Force=$true;ConfigPath=$runtime.ConfigPath} -TimeoutSeconds 120 + $made.ExitCode | Should -Be 2 -Because (Get-C330Why $made) + $zip = [string]$made.MainResult.TransferPackage + $info = Get-PraTransferPackage -Path $zip -Environment SYNTHETIC_GATE + $cloud = New-GateRuntime -Name 'origin-cloud' + $drop = Join-Path $cloud.Root 'drop'; $null = New-Item -ItemType Directory -Path $drop -Force + Copy-Item -LiteralPath $zip, ($zip + '.sha256') -Destination $drop + $dropped = Join-Path $drop ([IO.Path]::GetFileName($zip)) + $arguments = @{Action='Convert';Phase='Cloud';Mode='Preview';ConfigPath=$cloud.ConfigPath;Batch=$dropped} + $plain = Invoke-GateProcess $cloud $arguments -TimeoutSeconds 120 + $plain.ExitCode | Should -Be 0 -Because (Get-C330Why $plain) + (Get-C330Flat $plain) | Should -Match ('Package fingerprint ' + [regex]::Escape($info.Fingerprint) + ' \(the start of its SHA-256\)\. To be sure that it is the package the other server wrote') + (Get-C330Flat $plain) | Should -Not -Match 'has no \.auth file' -Because 'the shared secret is off on this server' + $wrong = Invoke-GateProcess $cloud ($arguments + @{ExpectedFingerprint='0000-0000-0000-0000-0000'}) -TimeoutSeconds 120 + $wrong.ExitCode | Should -Be 1 + ($wrong.MainResult.Issues.Message -join ' ') | Should -Match 'not the one given with -ExpectedFingerprint \(0000-0000-0000-0000-0000\)' + $right = Invoke-GateProcess $cloud ($arguments + @{ExpectedFingerprint=$info.Fingerprint.Replace('-', '').ToLowerInvariant()}) -TimeoutSeconds 120 + $right.ExitCode | Should -Be 0 -Because (Get-C330Why $right) + (Get-C330Flat $right) | Should -Match 'is the one given with -ExpectedFingerprint' + Use-C330Config $cloud -Section ("Transfer=@{RequireAuthentication=`$true;KeyFile='" + $key + "'}") + $refused = Invoke-GateProcess $cloud $arguments -TimeoutSeconds 120 + $refused.ExitCode | Should -Be 1 + ($refused.MainResult.Issues.Message -join ' ') | Should -Match 'Transfer\.RequireAuthentication is on: The transfer package .* has no \.auth file' + ($refused.MainResult.Issues.Message -join ' ') | Should -Match 'Nothing was imported' + @(Get-ChildItem -LiteralPath $cloud.State.BackupFolder -Directory -ErrorAction SilentlyContinue | Where-Object Name -Like 'Batch-*').Count | Should -Be 0 + Copy-Item -LiteralPath ($zip + '.auth') -Destination $drop + $accepted = Invoke-GateProcess $cloud $arguments -TimeoutSeconds 120 + $accepted.ExitCode | Should -Be 0 -Because (Get-C330Why $accepted) + (Get-C330Flat $accepted) | Should -Match 'Authenticity file checked: the transfer package .* was made by a holder of the shared secret' + $other = Join-Path $cloud.Root 'other.key'; $null = New-PraAuthKeyFile -Path $other + $swap = { param($text) $text.Replace(('RequireAuthentication=$true;KeyFile=' + "'" + $key + "'"), ('Authenticate=$true;KeyFile=' + "'" + $other + "'")) }.GetNewClosure() + Set-GateConfigText $cloud $swap + $warned = Invoke-GateProcess $cloud $arguments -TimeoutSeconds 120 + $warned.ExitCode | Should -Be 0 -Because 'a wrong tag is a warning unless the setting that requires it is on' + (Get-C330Flat $warned) | Should -Match 'does NOT match' + } + It 'warns when the licence group of the batch is not the one of the configuration, shows the group and the domain controller, and stops before any write only with Transfer.RequireConfigMatch' { + $first = Invoke-GateProcess $runtime @{Action='Convert';Mode='Apply';Force=$true;ConfigPath=$runtime.ConfigPath} -TimeoutSeconds 120 + $first.ExitCode | Should -BeIn @(0, 2) -Because (Get-C330Why $first) + $short = [string]$first.MainResult.BatchId + $writes = @(Get-GateWrites $runtime).Count + Use-C330Config $runtime -Retention 'CheckBeforeRecover=$false' + Set-GateConfigText $runtime { param($text) $text.Replace("Attribute='extensionAttribute1'", "Attribute='extensionAttribute2'") } + $preview = Invoke-GateProcess $runtime @{Action='Recover';Mode='Preview';Phase='AD';Force=$true;ConfigPath=$runtime.ConfigPath;Batch=$short} -TimeoutSeconds 120 + (Get-C330Flat $preview) | Should -Match 'The batch writes the retention tag extensionAttribute1 = Converted, and Retention\.Tag of this configuration is extensionAttribute2 = Converted' + Use-C330Config $runtime -Section 'Transfer=@{RequireConfigMatch=$true}' + $previewRequired = Invoke-GateProcess $runtime @{Action='Recover';Mode='Preview';Phase='AD';Force=$true;ConfigPath=$runtime.ConfigPath;Batch=$short} -TimeoutSeconds 120 + (Get-C330Flat $previewRequired) | Should -Match 'An Apply of this run would stop here, before it writes anything: Transfer\.RequireConfigMatch is on' + $stopped = Invoke-GateProcess $runtime @{Action='Recover';Mode='Apply';Phase='AD';Force=$true;ConfigPath=$runtime.ConfigPath;Batch=$short} -TimeoutSeconds 120 + $stopped.ExitCode | Should -Be 1 + (Get-C330Flat $stopped) | Should -Match 'Transfer\.RequireConfigMatch is on and the batch does not match this configuration' + @(Get-GateWrites $runtime).Count | Should -Be $writes -Because 'the Apply stopped before it wrote anything' + Set-GateConfigText $runtime { param($text) $text.Replace('Transfer=@{RequireConfigMatch=$true}', 'Transfer=@{RequireConfigMatch=$false}') } + $goes = Invoke-GateProcess $runtime @{Action='Recover';Mode='Apply';Phase='AD';Force=$true;ConfigPath=$runtime.ConfigPath;Batch=$short} -TimeoutSeconds 120 + $goes.ExitCode | Should -BeIn @(0, 2) -Because (Get-C330Why $goes) + (Get-C330Flat $goes) | Should -Match 'Retention\.Tag of this configuration is extensionAttribute2' + } + It 'a Recover on the AD server says what decided the retention check: the proof, its fingerprint, its age, what it covers, the route, and the three reasons to prefer a live answer' { + $context = New-GateContext $runtime; $context.BackupFolder = $runtime.State.BackupFolder + $bundles = New-GateSourceBundles $context + Remove-Item -LiteralPath $runtime.EventPath -Force -ErrorAction SilentlyContinue + $runtime.State.Case = 'RetentionUnverified'; Set-C330Converted $runtime $bundles + $proof = New-C330Proof $runtime $bundles + $run = Invoke-GateProcess $runtime @{Action='Recover';Mode='Apply';Phase='AD';Force=$true;ConfigPath=$runtime.ConfigPath;Batch=$bundles.Source} + $run.ExitCode | Should -BeIn @(0, 2) -Because (Get-C330Why $run) + (Get-C330Flat $run) | Should -Match ('Retention proof used: ' + [regex]::Escape((Split-Path $proof.Path -Leaf)) + ', fingerprint ' + [regex]::Escape($proof.Fingerprint) + ', \d+(\.\d)? hours old, 2 of 2 object\(s\) covered in the proof, 2 object\(s\) needed by this Recover\. Route: the proof stood in for the live answer of Exchange Online\.') + (Get-C330Flat $run) | Should -Match 'stood in for a live answer because this configuration has no certificate sign-in \(Cloud\.AppId and Cloud\.CertificateThumbprint\)' + (Get-C330Flat $run) | Should -Match 'stood in for a live answer because -Force was given' + (Get-C330Flat $run) | Should -Match 'Retention\.PolicyGuid is empty, so a proof that names any retention policy is accepted' + (Get-C330Flat $run) | Should -Match 'Retention: accepted from the retention proof RetentionProof-' + ($run.MainResult.ConfigOverrides -join '|') | Should -Match 'Confirmation skipped for this run \(-Force\)' + @($run.MainResult.Issues).Count | Should -Be 0 + } + It 'skips only the one proof that -IgnoreProof names (any letter case, a file name or a full path), records it, and says so when the name matches no proof' { + $context = New-GateContext $runtime; $context.BackupFolder = $runtime.State.BackupFolder + $bundles = New-GateSourceBundles $context + Remove-Item -LiteralPath $runtime.EventPath -Force -ErrorAction SilentlyContinue + $runtime.State.Case = 'RetentionUnverified'; Set-C330Converted $runtime $bundles + $older = New-C330Proof $runtime $bundles + Start-Sleep -Milliseconds 40 + $newer = New-C330Proof $runtime $bundles -Tamper + $arguments = @{Action='Recover';Mode='Apply';Phase='AD';Force=$true;ConfigPath=$runtime.ConfigPath;Batch=$bundles.Source} + $blocked = Invoke-GateProcess $runtime $arguments + $blocked.ExitCode | Should -Be 1 + ($blocked.MainResult.NextSteps -join "`n") | Should -Match ('Before that, delete the damaged copy at ' + [regex]::Escape($newer.Path) + ' \(and its \.sha256 file\), so that it is not read again\. To leave the file where it is and skip only that proof for one run, add -IgnoreProof ''' + [regex]::Escape((Split-Path $newer.Path -Leaf)) + ''' to the command instead') + @(Get-GateWrites $runtime).Count | Should -Be 0 + $nothing = Invoke-GateProcess $runtime ($arguments + @{IgnoreProof='RetentionProof-nothing.json'}) + $nothing.ExitCode | Should -Be 1 + (Get-C330Flat $nothing) | Should -Match '-IgnoreProof ''?RetentionProof-nothing\.json''? names no retention proof of this batch' + foreach ($typed in @((Split-Path $newer.Path -Leaf).ToUpperInvariant(), $newer.Path.ToLowerInvariant())) { + $ignored = Invoke-GateProcess $runtime (@{Action='Recover';Mode='Preview';Phase='AD';Force=$true;ConfigPath=$runtime.ConfigPath;Batch=$bundles.Source;IgnoreProof=$typed}) + $ignored.ExitCode | Should -Be 0 -Because (Get-C330Why $ignored) + (Get-C330Flat $ignored) | Should -Match 'is skipped for this run \(-IgnoreProof\): it is treated as if the file was not there' + (Get-C330Flat $ignored) | Should -Match ('Retention proof used: ' + [regex]::Escape((Split-Path $older.Path -Leaf))) + ($ignored.MainResult.ConfigOverrides -join '|') | Should -Match ('Retention proof skipped for this run \(-IgnoreProof\): ' + [regex]::Escape((Split-Path $newer.Path -Leaf))) + } + $applied = Invoke-GateProcess $runtime ($arguments + @{IgnoreProof=(Split-Path $newer.Path -Leaf)}) + $applied.ExitCode | Should -BeIn @(0, 2) -Because (Get-C330Why $applied) + @(Get-GateWrites $runtime).Count | Should -BeGreaterThan 0 + ($applied.MainResult.ConfigOverrides -join '|') | Should -Match 'Retention proof named to be skipped for this run \(-IgnoreProof' + } + It 'Retention.RequireLiveCheck: a Recover never reads a proof, the Preview says what blocks the Apply, the Apply stops before any change and names the way to sign in' { + $context = New-GateContext $runtime; $context.BackupFolder = $runtime.State.BackupFolder + $bundles = New-GateSourceBundles $context + Remove-Item -LiteralPath $runtime.EventPath -Force -ErrorAction SilentlyContinue + $runtime.State.Case = 'RetentionUnverified'; Set-C330Converted $runtime $bundles + $null = New-C330Proof $runtime $bundles + Use-C330Config $runtime -Retention 'RequireLiveCheck=$true' + $preview = Invoke-GateProcess $runtime @{Action='Recover';Mode='Preview';Phase='AD';ConfigPath=$runtime.ConfigPath;Batch=$bundles.Source} + (Get-C330Flat $preview) | Should -Not -Match 'Retention proof used' + ($preview.MainResult.NextSteps -join "`n") | Should -Match 'The Apply would be refused as things stand\. First sign in to Exchange Online in this run \(set the certificate sign-in Cloud\.AppId, or run at a console without -Force\), because Retention\.RequireLiveCheck is on' + $run = Invoke-GateProcess $runtime @{Action='Recover';Mode='Apply';Phase='AD';Force=$true;ConfigPath=$runtime.ConfigPath;Batch=$bundles.Source} + $run.ExitCode | Should -Be 1 + ($run.MainResult.Issues.Message -join ' ') | Should -Match 'Recover stopped before any change' + (Get-C330Flat $run) | Should -Match 'No retention proof stands in for the check: Retention\.RequireLiveCheck is on' + ($run.MainResult.NextSteps -join "`n") | Should -Match 'Retention\.RequireLiveCheck is on: this run does not read a retention proof, and it could not ask Exchange Online itself\. Give it a way to sign in' + @(Get-GateWrites $runtime).Count | Should -Be 0 + } + It 'checks the .auth file of a retention proof: a valid one is said, a missing or wrong one is a warning, and Transfer.RequireAuthentication turns it into a stop; a proof of another tenant is a warning and a stop with Transfer.RequireSameDomain' { + $context = New-GateContext $runtime; $context.BackupFolder = $runtime.State.BackupFolder + $bundles = New-GateSourceBundles $context + Remove-Item -LiteralPath $runtime.EventPath -Force -ErrorAction SilentlyContinue + $runtime.State.Case = 'RetentionUnverified'; Set-C330Converted $runtime $bundles + $key = Join-Path $runtime.Root 'secret.key'; $null = New-PraAuthKeyFile -Path $key + $arguments = @{Action='Recover';Mode='Preview';Phase='AD';ConfigPath=$runtime.ConfigPath;Batch=$bundles.Source} + $proof = New-C330Proof $runtime $bundles + $batchId = [string]((Get-Content -LiteralPath $bundles.Source -Raw | ConvertFrom-Json).BatchId) + Use-C330Config $runtime -Section ("Transfer=@{Authenticate=`$true;KeyFile='" + $key + "'}") + $missing = Invoke-GateProcess $runtime $arguments + $missing.ExitCode | Should -Be 0 -Because (Get-C330Why $missing) + (Get-C330Flat $missing) | Should -Match 'The retention proof RetentionProof-.* has no \.auth file, so nothing shows that a holder of the shared secret made it' + $created = $proof.CreatedUtc.ToUniversalTime().ToString('o', [Globalization.CultureInfo]::InvariantCulture) + $null = Write-PraAuthSidecar -Path $proof.Path -FileKind 'RetentionProof' -Environment 'SYNTHETIC_GATE' -BatchId $batchId -CreatedUtc $created -FileSha256 $proof.Sha256 -KeyFile $key + $valid = Invoke-GateProcess $runtime $arguments + $valid.ExitCode | Should -Be 0 -Because (Get-C330Why $valid) + (Get-C330Flat $valid) | Should -Match 'Authenticity file checked: the retention proof RetentionProof-.* was made by a holder of the shared secret' + Set-GateConfigText $runtime { param($text) $text.Replace('Transfer=@{Authenticate=$true;', 'Transfer=@{RequireAuthentication=$true;') } + (Invoke-GateProcess $runtime $arguments).ExitCode | Should -Be 0 + Remove-Item -LiteralPath ($proof.Path + '.auth') -Force + $required = Invoke-GateProcess $runtime (@{Action='Recover';Mode='Apply';Phase='AD';Force=$true;ConfigPath=$runtime.ConfigPath;Batch=$bundles.Source}) + $required.ExitCode | Should -Be 1 + (Get-C330Flat $required) | Should -Match 'Transfer\.RequireAuthentication is on: The retention proof .* has no \.auth file' + @(Get-GateWrites $runtime).Count | Should -Be 0 + $null = New-C330Proof $runtime $bundles -Identity ([ordered]@{ TenantId = '99999999-2222-3333-4444-555555555555' }) + Set-GateConfigText $runtime { param($text) $text.Replace('Transfer=@{RequireAuthentication=$true;', 'Transfer=@{') } + Use-C330Config $runtime -Section "Cloud=@{TenantId='11111111-2222-3333-4444-555555555555';Organization='contoso.onmicrosoft.com'}" + $tenant = Invoke-GateProcess $runtime $arguments + (Get-C330Flat $tenant) | Should -Match 'This retention proof records another tenant than this run knows \(99999999-2222-3333-4444-555555555555 in the file, 11111111-2222-3333-4444-555555555555 here\)' + $tenant.ExitCode | Should -Be 0 -Because 'a warning, not a refusal' + Set-GateConfigText $runtime { param($text) $text.Replace('Transfer=@{KeyFile=', 'Transfer=@{RequireSameDomain=$true;KeyFile=') } + $stopped = Invoke-GateProcess $runtime (@{Action='Recover';Mode='Apply';Phase='AD';Force=$true;ConfigPath=$runtime.ConfigPath;Batch=$bundles.Source}) + $stopped.ExitCode | Should -Be 1 + (Get-C330Flat $stopped) | Should -Match 'Transfer\.RequireSameDomain is on: This retention proof records another tenant' + @(Get-GateWrites $runtime).Count | Should -Be 0 + } +} + +Describe 'Release 3.3.0 - originals found through the batch a backup names, whatever the file is called or how it arrives; a retention proof is skipped only when the run refuses it (production Common module, synthetic folders)' -Tag 'Release330C' { + BeforeAll { + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global + $script:M330Root = Join-Path $global:PraGate.Root ('more-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) + $null = New-Item -ItemType Directory -Path $script:M330Root -Force + $script:M330Counter = 0 + function script:New-M330Work { $script:M330Counter++; $path = Join-Path $script:M330Root ('w' + $script:M330Counter); $null = New-Item -ItemType Directory -Path $path -Force; $path } + function script:New-M330Backup([string]$Parent, [string]$Folder, [string]$BatchId, [string]$Leaf, [string]$Marker, [string]$Operation = 'Convert') { + $directory = Join-Path $Parent $Folder + $null = New-Item -ItemType Directory -Path $directory -Force + $utf8 = New-Object Text.UTF8Encoding($false) + [IO.File]::WriteAllText((Join-Path $directory $Leaf), ('{"Operation":"' + $Operation + '","BatchId":"' + $BatchId + '","RawFile":"raw-' + $BatchId.Substring(0, 4) + '.clixml","Marker":"' + $Marker + '"}'), $utf8) + [IO.File]::WriteAllText((Join-Path $directory ($Leaf + '.sha256')), (Get-FileHash -LiteralPath (Join-Path $directory $Leaf) -Algorithm SHA256).Hash.ToLowerInvariant(), $utf8) + [IO.File]::WriteAllBytes((Join-Path $directory ('raw-' + $BatchId.Substring(0, 4) + '.clixml')), [byte[]](1..100)) + $directory + } + $script:M330Convert = 'aaaa1111aaaa1111aaaa1111aaaa1111' + $script:M330Recover = 'bbbb2222bbbb2222bbbb2222bbbb2222' + } + It 'a package written by 3.2.0 (no identity keys, no .auth file) is imported and compared without any refusal by default' { + $work = New-M330Work + $id = 'aaaa1111aaaa1111aaaa1111aaaa1111' + $source = New-M330Backup (Join-Path $work 'src') "Finalize-$id" $id 'Convert-PROD-1.json' 'old' + $package = New-PraTransferPackage -Kind Finalize -Environment PROD -BatchId $id -Folders $source -OutboxFolder (Join-Path $work 'out') -ToolVersion '3.2.0' + $info = Get-PraTransferPackage -Path $package.Path -Environment PROD + $info.Valid | Should -BeTrue -Because $info.Error + $origin = Test-PraPackageOrigin -Package $info + @($origin.Refusals).Count | Should -Be 0 + (Import-PraTransferPackage -Path $package.Path -BackupFolder (Join-Path $work 'Backups') -Environment PROD -ExpectedKind Finalize -BeforeExtract { param($p) $null = Test-PraPackageOrigin -Package $p }).Created.Count | Should -Be 1 + @(Get-PraIdentityDifference -Recorded $info -Current ([ordered]@{ TenantId = '11111111-2222-3333-4444-555555555555' })).Count | Should -Be 0 + } + It 'a retention proof that the run can use is not skipped by -IgnoreProof, so that an older proof never decides in its place; a proof that is refused is skipped and recorded' { + $work = New-M330Work + $batch = 'abcdef0123456789abcdef0123456789' + $rows = @(1..2 | ForEach-Object { [pscustomobject]@{ ObjectGuid = ('00000000-0000-0000-0000-{0:000000000000}' -f $_); UserPrincipalName = "user$_@contoso.invalid" } }) + $objects = { param($verdict) @(1..2 | ForEach-Object { [pscustomobject]@{ ObjectGuid = ('00000000-0000-0000-0000-{0:000000000000}' -f $_); Upn = "user$_@contoso.invalid"; Verdict = $verdict } }) } + $older = Write-PraRetentionProof -Folder $work -BatchId $batch -Environment PROD -Object (& $objects 'Covered') + Start-Sleep -Milliseconds 30 + $newer = Write-PraRetentionProof -Folder $work -BatchId $batch -Environment PROD -Object (& $objects 'NotCovered') + $leaf = [IO.Path]::GetFileName($newer.Path) + $usable = Get-PraRetentionProof -Folder @($work) -BatchId $batch -Environment PROD -Row $rows -IgnoreProof $leaf.ToUpperInvariant() + $usable.Complete | Should -BeFalse -Because 'the older Covered proof never stands in for the newest' + @($usable.Ignored).Count | Should -Be 0 + $usable.IgnoreNotApplied | Should -BeExactly $newer.Path + [IO.File]::WriteAllText($newer.Sidecar, ('0' * 64)) + $skipped = Get-PraRetentionProof -Folder @($work) -BatchId $batch -Environment PROD -Row $rows -IgnoreProof $newer.Path.ToLowerInvariant() + $skipped.Complete | Should -BeTrue -Because $skipped.Reason + @($skipped.Ignored) | Should -Be @($newer.Path) + $skipped.Path | Should -BeExactly $older.Path + $skipped.Fingerprint | Should -BeExactly $older.Fingerprint + (Get-PraRetentionProof -Folder @($work) -BatchId $batch -Environment PROD -Row $rows).Complete | Should -BeFalse + } +} + +Describe 'Release 3.3.0 - the Finalize compares what it loads with the originals kept on the AD server, by content, whatever the transport, and applies the .auth rule to a folder (real main, production Directory module, synthetic AD and cloud barrier)' -Tag 'Release330C' { + BeforeAll { + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global + function script:Get-F330Why($Run) { (@(([string]$Run.Output + [string]$Run.Error) -split '\r?\n' | Where-Object { $_ -match 'Stopped at step|refused|Nothing was|cannot|failed|Error' } | Select-Object -First 8) -join ' | ') } + function script:Get-F330Flat($Run) { [regex]::Replace([string]$Run.Output, '\s+', ' ') } + function script:Add-F330Transfer($Runtime, [string]$Section) { + $transform = { param($text) $text.Replace("Execution=@{Phase='Both'}", "Execution=@{Phase='Both'}`r`n $Section") }.GetNewClosure() + Set-GateConfigText $Runtime $transform + } + # The Finalize folder as the cloud server leaves it: the files of the Recover batch folder (the backups, the AD proof and the manifest), without the journal, in a folder named Finalize-. + function script:New-F330Folder($Runtime, $Bundles) { + $id = [guid]::NewGuid().ToString('N') + $folder = Join-Path $Runtime.State.BackupFolder ('Finalize-' + $id) + $null = New-Item -ItemType Directory -Path $folder -Force + foreach ($file in @(Get-ChildItem -LiteralPath (Split-Path $Bundles.Recover -Parent) -File | Where-Object { $_.Name -notlike 'Journal-*' })) { Copy-Item -LiteralPath $file.FullName -Destination $folder } + [pscustomobject]@{ Id = $id; Folder = $folder; Manifest = (Join-Path $folder (Split-Path $Bundles.Manifest -Leaf)) } + } + } + BeforeEach { + $runtime = New-GateRuntime -Name 'finalize-330c' + $env:PRA_GATE_STATE = $runtime.StatePath + $env:PSModulePath = $runtime.Modules + ';' + (Join-Path $PSHOME 'Modules') + Remove-Module PRA.Directory -Force -ErrorAction SilentlyContinue + Get-Module ActiveDirectory -All | Remove-Module -Force -ErrorAction Stop + Import-Module (Join-Path $runtime.Modules 'ActiveDirectory\ActiveDirectory.psm1') -Force -Global + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Directory.psm1') -Force -Global + $context = New-GateContext $runtime + $bundles = New-GateSourceBundles $context + Remove-Item -LiteralPath $runtime.EventPath -Force -ErrorAction SilentlyContinue + $copy = New-F330Folder $runtime $bundles + $arguments = @{Action='Finalize';Mode='Preview';Force=$true;ConfigPath=$runtime.ConfigPath;Batch=$copy.Manifest} + } + AfterAll { Remove-Item -LiteralPath 'Function:\Get-F330Why', 'Function:\Get-F330Flat', 'Function:\Add-F330Transfer', 'Function:\New-F330Folder' -ErrorAction SilentlyContinue } + It 'says that every file the AD server wrote is identical by content to its original, and keeps the cloud files apart; nothing is refused, with or without Transfer.RequireLocalOriginal' { + $run = Invoke-GateProcess $runtime $arguments + $run.ExitCode | Should -Be 0 -Because (Get-F330Why $run) + $text = Get-F330Flat $run + $text | Should -Match 'file\(s\) that this Finalize loads and that the AD server wrote itself are identical, by content, to the originals kept in the Backups folder' + $text | Should -Match 'The Finalize manifest and the report data were written by the cloud server: they cannot be compared with an original kept here' + Add-F330Transfer $runtime 'Transfer=@{RequireLocalOriginal=$true}' + (Invoke-GateProcess $runtime $arguments).ExitCode | Should -Be 0 + } + It 'warns when the originals of the batches it names differ, and Transfer.RequireLocalOriginal stops it before any restore' { + foreach ($raw in @(Get-ChildItem -LiteralPath $runtime.State.BackupFolder -Directory -Filter 'Batch-*' | ForEach-Object { Get-ChildItem -LiteralPath $_.FullName -File -Filter '*.clixml' })) { [IO.File]::AppendAllText($raw.FullName, ' ') } + $run = Invoke-GateProcess $runtime $arguments + $run.ExitCode | Should -Be 0 -Because (Get-F330Why $run) + (Get-F330Flat $run) | Should -Match 'file\(s\) differ from the originals kept on this server, which holds the batch they name' + (Get-F330Flat $run) | Should -Not -Match 'identical, by content' + Add-F330Transfer $runtime 'Transfer=@{RequireLocalOriginal=$true}' + $apply = Invoke-GateProcess $runtime (@{Action='Finalize';Mode='Apply';Force=$true;ConfigPath=$runtime.ConfigPath;Batch=$copy.Manifest}) + $apply.ExitCode | Should -Be 1 + ($apply.MainResult.Issues.Message -join ' ') | Should -Match 'Transfer\.RequireLocalOriginal is on: .*differ from the originals' + @(Get-GateWrites $runtime).Count | Should -Be 0 + } + It 'a Finalize whose batches are not on this server (another server) is a warning, and a refusal with Transfer.RequireLocalOriginal' { + foreach ($folder in @(Get-ChildItem -LiteralPath $runtime.State.BackupFolder -Directory -Filter 'Batch-*')) { Remove-Item -LiteralPath $folder.FullName -Recurse -Force } + $run = Invoke-GateProcess $runtime $arguments + $run.ExitCode | Should -Be 0 -Because (Get-F330Why $run) + (Get-F330Flat $run) | Should -Match 'file\(s\) have no original on this server' + (Get-F330Flat $run) | Should -Not -Match 'identical, by content' + Add-F330Transfer $runtime 'Transfer=@{RequireLocalOriginal=$true}' + $apply = Invoke-GateProcess $runtime (@{Action='Finalize';Mode='Apply';Force=$true;ConfigPath=$runtime.ConfigPath;Batch=$copy.Manifest}) + $apply.ExitCode | Should -Be 1 + ($apply.MainResult.Issues.Message -join ' ') | Should -Match 'Transfer\.RequireLocalOriginal is on: .*have no original on this server' + @(Get-GateWrites $runtime).Count | Should -Be 0 + } + It 'a forged Finalize folder called Batch- followed by an id is not read by id, and what it holds is never an original of itself' { + $forged = Join-Path $runtime.State.BackupFolder ('Batch-' + $copy.Id) + Move-Item -LiteralPath $copy.Folder -Destination $forged + $run = Invoke-GateProcess $runtime @{Action='Finalize';Mode='Preview';Force=$true;ConfigPath=$runtime.ConfigPath;Batch=$copy.Id} + $run.ExitCode | Should -Be 1 + ($run.MainResult.Issues.Message -join ' ') | Should -Match 'expected one RecoverFinalize file, found 0' + @(Get-GateWrites $runtime).Count | Should -Be 0 + } + It 'a Finalize folder copied by hand is a warning when the shared secret is on and a refusal with Transfer.RequireAuthentication, unless a verified import or this server made it' { + $key = Join-Path $runtime.Root 'secret.key'; $null = New-PraAuthKeyFile -Path $key + Add-F330Transfer $runtime ("Transfer=@{Authenticate=`$true;KeyFile='" + $key + "'}") + $warned = Invoke-GateProcess $runtime $arguments + $warned.ExitCode | Should -Be 0 -Because (Get-F330Why $warned) + (Get-F330Flat $warned) | Should -Match 'this Finalize folder was copied by hand: no \.auth file can come with a folder' + Set-GateConfigText $runtime { param($text) $text.Replace('Transfer=@{Authenticate=$true;', 'Transfer=@{RequireAuthentication=$true;') } + $preview = Invoke-GateProcess $runtime $arguments + (Get-F330Flat $preview) | Should -Match 'An Apply of this run would stop here, before it writes anything: Transfer\.RequireAuthentication is on and this Finalize folder was copied by hand' + $refused = Invoke-GateProcess $runtime @{Action='Finalize';Mode='Apply';Force=$true;ConfigPath=$runtime.ConfigPath;Batch=$copy.Manifest} + $refused.ExitCode | Should -Be 1 + ($refused.MainResult.Issues.Message -join ' ') | Should -Match 'Transfer\.RequireAuthentication is on and this Finalize folder was copied by hand' + @(Get-GateWrites $runtime).Count | Should -Be 0 + Write-PraVerifiedMarker -BackupFolder $runtime.State.BackupFolder -FolderPath $copy.Folder -Origin Package -Sha256 'x' -Auth Valid + $verified = Invoke-GateProcess $runtime $arguments + $verified.ExitCode | Should -Be 0 -Because (Get-F330Why $verified) + $markerFile = Join-Path (Join-Path $runtime.State.BackupFolder 'Imported') ($copy.Id + '.verified.json') + $why = if ([IO.File]::Exists($markerFile)) { [IO.File]::ReadAllText($markerFile) + ' | ' + ((Get-ChildItem -LiteralPath $copy.Folder -File | ForEach-Object { $_.Name + '=' + (Get-FileHash -LiteralPath $_.FullName).Hash.Substring(0, 8) }) -join ', ') } else { 'no marker file' } + (Get-F330Flat $verified) | Should -Not -Match 'copied by hand' -Because $why + } +} + +Describe 'Release 3.3.0 - what counts as an original, the licence group by GUID, and the verified marker of a folder (production Common and Directory modules, synthetic folders)' -Tag 'Release330C' { + BeforeAll { + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Directory.psm1') -Force -Global + $script:N330Root = Join-Path $global:PraGate.Root ('last-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) + $null = New-Item -ItemType Directory -Path $script:N330Root -Force + $script:N330Counter = 0 + function script:New-N330Work { $script:N330Counter++; $path = Join-Path $script:N330Root ('w' + $script:N330Counter); $null = New-Item -ItemType Directory -Path $path -Force; $path } + function script:New-N330Folder([string]$Parent, [string]$Name, [string]$Text = 'genuine') { + $folder = Join-Path $Parent $Name + $null = New-Item -ItemType Directory -Path $folder -Force + [IO.File]::WriteAllText((Join-Path $folder 'Convert-x.json'), ('{"Marker":"' + $Text + '"}'), (New-Object Text.UTF8Encoding($false))) + [IO.File]::WriteAllText((Join-Path $folder 'Finalize-x.json'), ('{"Manifest":"' + $Text + '"}'), (New-Object Text.UTF8Encoding($false))) + [IO.File]::WriteAllText((Join-Path $folder 'State-x.json'), ('{"State":"' + $Text + '"}'), (New-Object Text.UTF8Encoding($false))) + $folder + } + function script:Get-N330Files([string]$Folder, [string]$BatchId) { @(Get-ChildItem -LiteralPath $Folder -File | Where-Object Name -Like 'Convert-*' | ForEach-Object { [pscustomobject]@{ Path = $_.FullName; Role = 'Convert backup'; BatchId = $BatchId } }) } + $script:N330Batch = 'cccccccc33333333cccccccc33333333' + } + It 'does not take the folder that holds the loaded files for an original, even when it is called Batch- followed by an id, and does not take a folder extracted from an imported package for one (a Batch folder copied back by hand counts)' { + $work = New-N330Work + $backups = Join-Path $work 'Backups' + $loaded = New-N330Folder $backups ('Batch-' + $script:N330Batch) + $files = Get-N330Files $loaded $script:N330Batch + (Get-PraFinalizeOriginalComparison -File $files -BackupFolder $backups).Status | Should -BeExactly 'NoOriginal' -Because 'a folder that holds what is loaded proves nothing about itself' + $original = New-N330Folder $backups 'Batch-dddddddd44444444dddddddd44444444' + (Get-PraFinalizeOriginalComparison -File $files -BackupFolder $backups).Status | Should -BeExactly 'Match' + $imported = Join-Path $backups 'Imported'; $null = New-Item -ItemType Directory -Path $imported -Force + [IO.File]::WriteAllText((Join-Path $imported 'dddddddd44444444dddddddd44444444.txt'), 'package.zip 2026-11-24') + (Get-PraFinalizeOriginalComparison -File $files -BackupFolder $backups).Status | Should -BeExactly 'NoOriginal' -Because 'a folder extracted from an imported package is not something this server wrote' + Remove-Item -LiteralPath (Join-Path $imported 'dddddddd44444444dddddddd44444444.txt') + Write-PraVerifiedMarker -BackupFolder $backups -FolderPath $original -Origin Package -Auth Valid + (Get-PraFinalizeOriginalComparison -File $files -BackupFolder $backups).Status | Should -BeExactly 'NoOriginal' + [IO.File]::WriteAllText((Join-Path $original 'notes.txt'), 'x') + $other = New-N330Folder $backups 'Batch-eeeeeeee55555555eeeeeeee55555555' + (Get-PraFinalizeOriginalComparison -File $files -BackupFolder $backups).Status | Should -BeExactly 'Match' -Because 'a Batch folder that the operator copied back, with no marker, counts as an original' + (Get-PraFinalizeOriginalComparison -File $files -BackupFolder $backups -ExcludeFolder @($other)).Status | Should -BeExactly 'NoOriginal' + } + It 'reads only .json, .clixml and .sha256 files of the batch folders, and the hash recorded at load when it is given' { + $work = New-N330Work + $backups = Join-Path $work 'Backups' + $loaded = New-N330Folder (Join-Path $work 'Finalize') 'Finalize-x' + $original = New-N330Folder $backups 'Batch-dddddddd44444444dddddddd44444444' + Move-Item -LiteralPath (Join-Path $original 'Convert-x.json') -Destination (Join-Path $original 'Convert-x.txt') + $files = Get-N330Files $loaded 'dddddddd44444444dddddddd44444444' + (Get-PraFinalizeOriginalComparison -File $files -BackupFolder $backups).Status | Should -BeExactly 'Different' -Because 'a .txt file is not read, and the batch folder is here' + Move-Item -LiteralPath (Join-Path $original 'Convert-x.txt') -Destination (Join-Path $original 'Convert-x.json') + (Get-PraFinalizeOriginalComparison -File $files -BackupFolder $backups).Status | Should -BeExactly 'Match' + $recorded = @($files | ForEach-Object { [pscustomobject]@{ Path = $_.Path; Role = $_.Role; BatchId = $_.BatchId; Sha256 = ('0' * 64) } }) + (Get-PraFinalizeOriginalComparison -File $recorded -BackupFolder $backups).Status | Should -BeExactly 'Different' -Because 'the hash recorded at load decides, not a second read of the file' + } + It 'compares the licence group by GUID: a renamed group is the same group, another group with the same name is not, and a record whose DN left its GUID is said ()' -ForEach @(@{ Culture = 'en-US' }, @{ Culture = 'fr-FR' }) { + $old = [Globalization.CultureInfo]::CurrentCulture + try { + [Globalization.CultureInfo]::CurrentCulture = [Globalization.CultureInfo]::GetCultureInfo($Culture) + $guid = '10000000-0000-0000-0000-000000000001' + $record = [pscustomobject]@{ ObjectGuid = '00000000-0000-0000-0000-000000000001'; Licensing = [pscustomobject]@{ Enabled = $true; GroupGuid = $guid; GroupDN = 'CN=License,OU=Tests,DC=gate,DC=invalid' } } + $source = [pscustomobject]@{ Data = [pscustomobject]@{ Records = @($record) } } + $context = @{ Config = @{ DomainController = ''; Licensing = @{ Enabled = $true; GroupDN = 'CN=Renamed,OU=Tests,DC=gate,DC=invalid' }; Retention = @{ Enabled = $false; Tag = @{ Enabled = $false } }; Cloud = @{ TenantId = '' } } } + $same = Test-PraBatchOrigin -Context $context -Source $source -ConfiguredGroupGuid $guid.ToUpperInvariant() + @($same.ConfigMatch).Count | Should -Be 0 -Because 'the configured DN names the same group by its GUID' + $other = Test-PraBatchOrigin -Context $context -Source $source -ConfiguredGroupGuid '20000000-0000-0000-0000-000000000002' + @($other.ConfigMatch).Count | Should -Be 1 + $other.ConfigMatch[0] | Should -Match 'is the group with the GUID 20000000-0000-0000-0000-000000000002' + $moved = Test-PraBatchOrigin -Context $context -Source $source -ConfiguredGroupGuid $guid -GroupDnOfGuid { param($g) 'CN=Elsewhere,OU=Tests,DC=gate,DC=invalid' } + @($moved.ConfigMatch).Count | Should -Be 1 + $moved.ConfigMatch[0] | Should -Match 'with the GUID 10000000-0000-0000-0000-000000000001, and the group with that GUID is now CN=Elsewhere' + $unchanged = Test-PraBatchOrigin -Context $context -Source $source -ConfiguredGroupGuid $guid -GroupDnOfGuid { param($g) 'cn=license, ou=Tests,dc=gate,dc=invalid' } + @($unchanged.ConfigMatch).Count | Should -Be 0 + } + finally { [Globalization.CultureInfo]::CurrentCulture = $old } + } + It 'accepts a Finalize folder as verified only under the Backups folder, at the recorded path, with the recorded hashes, and a later valid verification replaces a weaker one but never the other way' { + $work = New-N330Work + $backups = Join-Path $work 'Backups' + $folder = New-N330Folder $backups 'Finalize-0123456789abcdef0123456789abcdef' + $hash = { param($name) (Get-FileHash -LiteralPath (Join-Path $folder $name) -Algorithm SHA256).Hash.ToLowerInvariant() } + $manifest = & $hash 'Finalize-x.json'; $state = & $hash 'State-x.json' + Test-PraVerifiedMarker -BackupFolder $backups -FolderPath $folder -ManifestSha256 $manifest -StateSha256 $state | Should -BeFalse -Because 'no marker yet' + Write-PraVerifiedMarker -BackupFolder $backups -FolderPath $folder -Origin Package -Sha256 'abc' -Auth Absent + Test-PraVerifiedMarker -BackupFolder $backups -FolderPath $folder -ManifestSha256 $manifest -StateSha256 $state | Should -BeFalse -Because 'the .auth file was absent' + Write-PraVerifiedMarker -BackupFolder $backups -FolderPath $folder -Origin Package -Sha256 'abc' -Auth Valid + Test-PraVerifiedMarker -BackupFolder $backups -FolderPath $folder -ManifestSha256 $manifest -StateSha256 $state | Should -BeTrue + Test-PraVerifiedMarker -BackupFolder $backups -FolderPath $folder.ToUpperInvariant() -ManifestSha256 $manifest.ToUpperInvariant() -StateSha256 $state | Should -BeTrue -Because 'the case of a path or a hash does not matter' + Write-PraVerifiedMarker -BackupFolder $backups -FolderPath $folder -Origin Package -Sha256 'abc' -Auth Invalid + Test-PraVerifiedMarker -BackupFolder $backups -FolderPath $folder -ManifestSha256 $manifest -StateSha256 $state | Should -BeTrue -Because 'a Valid verdict is not replaced by a weaker one' + Test-PraVerifiedMarker -BackupFolder $backups -FolderPath $folder -ManifestSha256 ('0' * 64) -StateSha256 $state | Should -BeFalse -Because 'another manifest' + Test-PraVerifiedMarker -BackupFolder $backups -FolderPath $folder -ManifestSha256 $manifest -StateSha256 ('0' * 64) | Should -BeFalse -Because 'another AD proof' + $elsewhere = New-N330Folder (Join-Path $work 'Elsewhere') 'Finalize-0123456789abcdef0123456789abcdef' + Test-PraVerifiedMarker -BackupFolder $backups -FolderPath $elsewhere -ManifestSha256 $manifest -StateSha256 $state | Should -BeFalse -Because 'the leaf name is not the folder: it is outside the Backups folder' + $inside = Join-Path $backups 'Sub'; $same = New-N330Folder $inside 'Finalize-0123456789abcdef0123456789abcdef' + Test-PraVerifiedMarker -BackupFolder $backups -FolderPath $same -ManifestSha256 $manifest -StateSha256 $state | Should -BeFalse -Because 'another folder of the same name under the Backups folder' + Test-PraVerifiedMarker -BackupFolder (Join-Path $work 'Other') -FolderPath $folder -ManifestSha256 $manifest -StateSha256 $state | Should -BeFalse + $local = New-N330Folder $backups 'Finalize-fedcba9876543210fedcba9876543210' + Write-PraVerifiedMarker -BackupFolder $backups -FolderPath $local -Origin Local + Test-PraVerifiedMarker -BackupFolder $backups -FolderPath $local -ManifestSha256 (& { (Get-FileHash -LiteralPath (Join-Path $local 'Finalize-x.json') -Algorithm SHA256).Hash }) -StateSha256 (& { (Get-FileHash -LiteralPath (Join-Path $local 'State-x.json') -Algorithm SHA256).Hash }) | Should -BeTrue + } +} + +Describe 'Release 3.3.0 - one Windows event per Apply and per safety override, every override recorded, a failed event never changes a run (production Common module)' -Tag 'Release330D' { + BeforeAll { + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global + Register-PraTestProxy PRA.Common 'Get-PraPhaseSetting', 'Get-PraRunSetting', 'Get-PraDefaultConfiguration', 'Get-PraWindowsEventPlan', 'Write-PraApplyEnded' + $global:PraGate.L330DSink = New-Object 'Collections.Generic.List[object]' + $script:NewRunContext = { + param([bool]$Mutate = $true, [string]$Mode = 'Auto', [string]$LogFile = '') + @{ StepIndex = 0; StepTotal = 4; Issues = (New-Object 'Collections.Generic.List[object]'); Warnings = 0; LogFile = $LogFile; Action = 'Recover'; Phase = 'AD'; CurrentPhase = ''; RunId = '20261124_101500-0123456789abcdef' + Version = '9.9.9'; BatchId = '0a1b2c3d'; AllowMutation = $Mutate; ExitCode = 0; Config = @{ Logging = @{ WindowsEvents = $Mode } } + WindowsEventSink = { param($Id, $Type, $Text) $global:PraGate.L330DSink.Add([pscustomobject]@{ Id = [int]$Id; Type = [string]$Type; Text = [string]$Text }) } } + } + $script:Ok = [pscustomobject]@{ Status = 'Success'; ExitCode = 0; SuccessCount = 3; ErrorCount = 0; PendingCount = 0; SkippedCount = 1; WarningCount = 1234; Issues = @() } + } + BeforeEach { $global:PraGate.L330DSink.Clear() } + AfterAll { $global:PraGate.Remove('L330DSink') } + It 'decides by the setting, the source and the rights (, source , administrator ): ' -ForEach @( + @{ Mode = 'Auto'; Exists = $true; Elevated = $false; Expect = 'Write' } + @{ Mode = 'auto'; Exists = $true; Elevated = $true; Expect = 'Write' } + @{ Mode = 'AUTO'; Exists = $false; Elevated = $true; Expect = 'Register' } + @{ Mode = 'Auto'; Exists = $false; Elevated = $false; Expect = 'Warn' } + @{ Mode = 'oFF'; Exists = $true; Elevated = $true; Expect = 'Off' } + @{ Mode = 'OFF'; Exists = $false; Elevated = $false; Expect = 'Off' } + ) { + Get-PraWindowsEventPlan -Mode $Mode -SourceExists $Exists -Elevated $Elevated | Should -BeExactly $Expect + } + It 'says in ONE warning that no event is written when the source is missing and the account is not an administrator, and never fails the run' { + $context = & $script:NewRunContext + Initialize-PraWindowsEvent -Context $context -SourceExists $false -Elevated $false 6>$null + $context.WindowsEventState | Should -BeExactly 'Unavailable' + $context.Warnings | Should -Be 1 + $context.Issues.Count | Should -Be 0 + $context.ExitCode | Should -Be 0 + $context['WarningList'][0].Message | Should -BeLike '*CreateEventSource*PraRemoteMailbox*' + Add-PraOverride -Context $context -Id 'Force' -Text 'Confirmation skipped for this run (-Force)' 6>$null + Write-PraApplyStarted -Context $context 6>$null + Write-PraApplyEnded -Context $context -Result $script:Ok + $global:PraGate.L330DSink.Count | Should -Be 0 + $context.Warnings | Should -Be 1 -Because 'the warning is said once' + $context.Issues.Count | Should -Be 0 + } + It 'writes nothing and says nothing when Logging.WindowsEvents is Off, in any letter case, even without the source' { + $context = & $script:NewRunContext $true 'oFf' + Initialize-PraWindowsEvent -Context $context -SourceExists $false -Elevated $false 6>$null + $context.WindowsEventState | Should -BeExactly 'Off' + $context.Warnings | Should -Be 0 + Write-PraApplyStarted -Context $context 6>$null + Add-PraOverride -Context $context -Id 'Force' -Text 'x' 6>$null + $global:PraGate.L330DSink.Count | Should -Be 0 + } + It 'writes the event 4100 once per Apply, then the event 4200 once per override (an identifier is recorded once whatever its letter case): an override recorded before the Apply started waits for it' { + $context = & $script:NewRunContext + Add-PraOverride -Context $context -Id 'AcceptRetentionRisk' -Count 3 -Text 'Retention check before Recover: 3 mailbox(es) not held, accepted for this run (-AcceptRetentionRisk)' 6>$null + Add-PraOverride -Context $context -Id 'acceptRETENTIONrisk' -Count 3 -Text 'a second line for the same override' 6>$null + $global:PraGate.L330DSink.Count | Should -Be 0 -Because 'the events are not ready yet' + Initialize-PraWindowsEvent -Context $context -SourceExists $true -Elevated $false 6>$null + $context.WindowsEventState | Should -BeExactly 'Ready' + $global:PraGate.L330DSink.Count | Should -Be 0 -Because 'the Apply is not confirmed yet: no event is written for a run that may still be refused' + Add-PraOverride -Context $context -Id 'Off:Transfer.RequireSameDomain' -Origin console -Text 'Transfer.RequireSameDomain turned off for this run from the console' 6>$null + $global:PraGate.L330DSink.Count | Should -Be 0 + Write-PraApplyStarted -Context $context 6>$null + Write-PraApplyStarted -Context $context 6>$null + ($global:PraGate.L330DSink | ForEach-Object Id) -join ',' | Should -BeExactly '4100,4200,4200' -Because 'the start comes first, then each override once' + $first = $global:PraGate.L330DSink[1] + $first.Type | Should -BeExactly 'Warning' + $first.Text | Should -BeLike '*Override=AcceptRetentionRisk*' + $first.Text | Should -BeLike '*Count=3*' + $first.Text | Should -BeLike '*Origin=command line*' + $global:PraGate.L330DSink[2].Text | Should -BeLike '*Origin=console*' + Add-PraOverride -Context $context -Id 'Force' -Text 'Confirmation skipped for this run (-Force)' 6>$null + ($global:PraGate.L330DSink | ForEach-Object Id) -join ',' | Should -BeExactly '4100,4200,4200,4200' -Because 'an override that comes after the start is written at once' + @($context.ConfigOverrides).Count | Should -Be 4 -Because 'every text of an override is kept in the run settings changed' + @($context.OverrideList).Count | Should -Be 3 + } + It 'records the retention check turned off from the console as ONE override (RetentionCheckOff), whatever the letter case of the key, and keeps the other protections as they were (: )' -ForEach @( + @{ Action = 'Recover'; Key = 'Retention.CheckBeforeRecover'; Expected = 'RetentionCheckOff' } + @{ Action = 'recover'; Key = 'retention.checkbeforerecover'; Expected = 'RetentionCheckOff' } + @{ Action = 'Recover'; Key = 'Logging.JournalChain'; Expected = 'RetentionCheckOff,Off:Logging.JournalChain' } + @{ Action = 'Convert'; Key = 'Retention.CheckBeforeRecover'; Expected = 'Off:Retention.CheckBeforeRecover' } + ) { + $entry = [Management.Automation.Language.Parser]::ParseFile((Join-Path $global:PraGate.Package 'Invoke-PraRemoteMailbox.ps1'), [ref]$null, [ref]$null) + $keys = $entry.Find({ param($n) $n -is [Management.Automation.Language.AssignmentStatementAst] -and $n.Left.Extent.Text -ceq '$script:ProtectiveKeys' }, $true) + $keys | Should -Not -BeNullOrEmpty + $script:ProtectiveKeys = @(& ([scriptblock]::Create($keys.Right.Extent.Text))) + $block = $entry.Find({ param($n) $n -is [Management.Automation.Language.IfStatementAst] -and $n.Extent.Text.StartsWith('if ($context.AllowMutation) {', [StringComparison]::Ordinal) -and $n.Extent.Text.Contains('RetentionCheckOff') }, $true) + $block | Should -Not -BeNullOrEmpty + $record = { + param([string]$Action, [string]$Key) + $context = @{ StepIndex = 0; StepTotal = 4; Issues = (New-Object 'Collections.Generic.List[object]'); Warnings = 0; LogFile = ''; AllowMutation = $true; Phase = 'Both' } + $config = @{ Cloud = @{ IdentityCheck = 'On' }; Retention = @{ CheckBeforeRecover = $false } } + $effectivePhase = 'Both' + $configDifferences = @([pscustomobject]@{ Key = $Key; Base = 'True'; Effective = 'False'; Text = ($Key + ' differs') }) + . ([scriptblock]::Create($block.Extent.Text)) + @($context.OverrideList | ForEach-Object { $_.Id }) -join ',' + } + (& $record $Action $Key) | Should -BeExactly $Expected + } + It 'writes no event 4200 for an Apply that was not confirmed (the operator answered no): the overrides stay in the log and in the run settings' { + $context = & $script:NewRunContext + Initialize-PraWindowsEvent -Context $context -SourceExists $true -Elevated $false 6>$null + Add-PraOverride -Context $context -Id 'IgnoreProof' -Text 'Retention proof skipped for this run (-IgnoreProof)' 6>$null + Write-PraApplyEnded -Context $context -Result $script:Ok + $global:PraGate.L330DSink.Count | Should -Be 0 + @($context.OverrideList).Count | Should -Be 1 + @($context.ConfigOverrides) | Should -Contain 'Retention proof skipped for this run (-IgnoreProof)' + } + It 'ends an Apply that started and has no result in the event log as failed (4102), once, and never after its real end was written' { + $context = & $script:NewRunContext + Initialize-PraWindowsEvent -Context $context -SourceExists $true -Elevated $false 6>$null + Write-PraApplyEnded -Context $context + $global:PraGate.L330DSink.Count | Should -Be 0 -Because 'this Apply did not start' + Write-PraApplyStarted -Context $context 6>$null + $null = $context.Issues.Add([pscustomobject]@{ Source = 'Directory'; Message = 'a message that is not in the event' }) + Write-PraApplyEnded -Context $context + Write-PraApplyEnded -Context $context + $failed = @($global:PraGate.L330DSink | Where-Object Id -eq 4102) + $failed.Count | Should -Be 1 + $failed[0].Type | Should -BeExactly 'Error' + $failed[0].Text | Should -BeLike '*Status=Failed*ExitCode=1*FirstErrorSource=Directory*Issues=1*' + $done = & $script:NewRunContext + Initialize-PraWindowsEvent -Context $done -SourceExists $true -Elevated $false 6>$null + Write-PraApplyStarted -Context $done 6>$null + Write-PraApplyEnded -Context $done -Result $script:Ok + Write-PraApplyEnded -Context $done + @($global:PraGate.L330DSink | Where-Object Id -eq 4101).Count | Should -Be 1 + @($global:PraGate.L330DSink | Where-Object Id -eq 4102).Count | Should -Be 1 -Because 'the Apply that ended is not reported as failed afterwards' + } + It 'never lets the end event throw out of Complete-PraRun, and reports the Apply as failed when Complete-PraRun itself stops after the start' { + $text = [IO.File]::ReadAllText((Join-Path $global:PraGate.Package 'module\PRA.Common.psm1')) + + $ast = [Management.Automation.Language.Parser]::ParseInput($text, [ref]$null, [ref]$null) + $complete = $ast.Find({ param($n) $n -is [Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -ceq 'Complete-PraRun' }, $true).Extent.Text + $complete | Should -Match 'try \{ Write-PraApplyEnded -Context \$Context -Result \$result \}\s*\r?\n\s*catch \{ try \{ Write-PraLog' + $complete | Should -Match 'trap \{ try \{ Write-PraApplyEnded -Context \$Context \} catch \{ \$null = \$_ \}; break \}' + $context = & $script:NewRunContext + Initialize-PraWindowsEvent -Context $context -SourceExists $true -Elevated $false 6>$null + Write-PraApplyStarted -Context $context 6>$null + $context.ExitCode = 'not a number' + { Complete-PraRun -Context $context 6>$null } | Should -Throw + @($global:PraGate.L330DSink | Where-Object Id -eq 4102).Count | Should -Be 1 -Because 'the run stopped after the start: the event log says it failed' + } + It 'holds identifiers and counts only: the run, the batch, the SID of the account, the counts; no name, no address, no text of an override' { + $context = & $script:NewRunContext + Initialize-PraWindowsEvent -Context $context -SourceExists $true -Elevated $false 6>$null + Add-PraOverride -Context $context -Id 'IgnoreProof' -Text 'Retention proof skipped for this run (-IgnoreProof): alice@contoso.invalid.json' 6>$null + Write-PraApplyStarted -Context $context 6>$null + Write-PraApplyEnded -Context $context -Result $script:Ok + foreach ($sent in $global:PraGate.L330DSink) { + $sent.Text | Should -Match '(?m)^Run=20261124_101500-0123456789abcdef$' + $sent.Text | Should -Match '(?m)^Batch=0a1b2c3d$' + $sent.Text | Should -Match '(?m)^Account=S-1-\d+(-\d+)+$' + $sent.Text | Should -Not -Match '@|contoso|alice' + $sent.Text | Should -Not -Match '[\x00-\x08\x0B-\x1F]' + } + $global:PraGate.L330DSink.Count | Should -Be 3 + } + It 'writes 4101 when the Apply ends (exit code 0 or 2) and 4102 with the source of the first error when it fails, only for an Apply that started' { + $context = & $script:NewRunContext + Initialize-PraWindowsEvent -Context $context -SourceExists $true -Elevated $false 6>$null + Write-PraApplyEnded -Context $context -Result $script:Ok + $global:PraGate.L330DSink.Count | Should -Be 0 -Because 'this Apply did not start' + Write-PraApplyStarted -Context $context 6>$null + Write-PraApplyEnded -Context $context -Result $script:Ok + $ended = $global:PraGate.L330DSink | Where-Object Id -eq 4101 + @($ended).Count | Should -Be 1 + $ended.Type | Should -BeExactly 'Information' + $ended.Text | Should -BeLike '*Status=Success*' + $ended.Text | Should -BeLike '*Success=3*' + $failed = [pscustomobject]@{ Status = 'Failed'; ExitCode = 1; SuccessCount = 0; ErrorCount = 2; PendingCount = 0; SkippedCount = 0; WarningCount = 0; Issues = @([pscustomobject]@{ Source = 'Directory'; Message = 'a message that is not in the event' }, [pscustomobject]@{ Source = 'Log'; Message = 'x' }) } + Write-PraApplyEnded -Context $context -Result $failed + $sent = $global:PraGate.L330DSink | Where-Object Id -eq 4102 + $sent.Type | Should -BeExactly 'Error' + $sent.Text | Should -BeLike '*FirstErrorSource=Directory*' + $sent.Text | Should -BeLike '*Issues=2*' + $sent.Text | Should -Not -BeLike '*a message that is not in the event*' + } + It 'writes no event for a Preview or a Check, and still records its overrides in the run settings changed' { + $context = & $script:NewRunContext $false + Initialize-PraWindowsEvent -Context $context -SourceExists $true -Elevated $true 6>$null + $context.WindowsEventState | Should -BeExactly 'None' + Add-PraOverride -Context $context -Id 'AcceptRetentionRisk' -Text 'accepted' 6>$null + Write-PraApplyStarted -Context $context 6>$null + $global:PraGate.L330DSink.Count | Should -Be 0 + @($context.ConfigOverrides) | Should -Contain 'accepted' + } + It 'never changes the result when an event cannot be written: one Detail line in the log, no issue, no warning, the exit code as it was' { + $log = Join-Path $global:PraGate.Root ('events-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.log') + $context = & $script:NewRunContext $true 'Auto' $log + $context.WindowsEventSink = { throw 'The event log service does not answer.' } + Initialize-PraWindowsEvent -Context $context -SourceExists $true -Elevated $false 6>$null + Write-PraApplyStarted -Context $context 6>$null + Add-PraOverride -Context $context -Id 'Force' -Text 'Confirmation skipped for this run (-Force)' 6>$null + Write-PraApplyEnded -Context $context -Result $script:Ok + $context.Issues.Count | Should -Be 0 + $context.Warnings | Should -Be 0 + $context.ExitCode | Should -Be 0 + $text = [IO.File]::ReadAllText($log) + $text | Should -Match '\[DETAIL\] Windows event 4100 not written' + $text | Should -Match '\[DETAIL\] Windows event 4200 not written' + $text | Should -Match '\[DETAIL\] Windows event 4101 not written' + $text | Should -Match '\[DETAIL\] OVERRIDE \| Force \| command line \|' + } + It 'gives the same event text under a French culture, with large numbers written without a separator' { + $texts = @{} + $before = [Threading.Thread]::CurrentThread.CurrentCulture + try { + foreach ($culture in 'en-US', 'fr-FR') { + [Threading.Thread]::CurrentThread.CurrentCulture = [Globalization.CultureInfo]::GetCultureInfo($culture) + $global:PraGate.L330DSink.Clear() + $context = & $script:NewRunContext + Initialize-PraWindowsEvent -Context $context -SourceExists $true -Elevated $false 6>$null + Write-PraApplyStarted -Context $context 6>$null + Write-PraApplyEnded -Context $context -Result $script:Ok + $texts[$culture] = (@($global:PraGate.L330DSink | ForEach-Object { [string]$_.Id + ':' + $_.Text }) -join '|') + } + } + finally { [Threading.Thread]::CurrentThread.CurrentCulture = $before } + $texts['fr-FR'] | Should -BeExactly $texts['en-US'] + $texts['fr-FR'] | Should -BeLike '*Warnings=1234*' + } + It 'documents the event numbers of the code in the guide, with their level and their fields' { + $guide = [IO.File]::ReadAllText((Join-Path $global:PraGate.Source 'docs\PraRemoteMailbox-Guide.md')) + $ids = InModuleScope PRA.Common { $script:PraEventId } + $ids.ApplyStarted | Should -Be 4100; $ids.ApplyCompleted | Should -Be 4101; $ids.ApplyFailed | Should -Be 4102; $ids.OverrideUsed | Should -Be 4200 + foreach ($id in $ids.Values) { $guide | Should -Match ('(?m)^\| ' + $id + ' \| (Information|Warning|Error) \|') } + $guide | Should -Match 'source `PraRemoteMailbox`' + } + It 'records in the settings of the report: the identity check, the permission source, the age limit of the proof, whether the policy is named, the Exchange Online child, the confirmation skipped and the overrides' { + $settings = Get-PraPhaseSetting -Context @{ Config = @{ Cloud = @{ IdentityCheck = 'Off' }; Retention = @{ ProofMaxAgeHours = 48; PolicyGuid = '' }; Exo = @{ UseSubprocess = $true }; SharedMailbox = @{ PermissionSource = 'Csv' }; Logging = @{ WindowsEvents = 'auto'; JournalChain = $true } } + ForceUsed = $true; OverrideList = @([pscustomobject]@{ Id = 'Force' }, [pscustomobject]@{ Id = 'IdentityCheckOff' }) } + $settings['Identity check'] | Should -BeExactly 'Off' + $settings['Permission source'] | Should -BeExactly 'Csv' + $settings['Retention proof age limit (hours)'] | Should -BeExactly '48' + $settings['Retention policy named'] | Should -BeExactly 'empty' + $settings['Exchange Online child process'] | Should -BeExactly 'True' + $settings['Confirmation skipped by -Force'] | Should -BeExactly 'True' + $settings['Journal chain'] | Should -BeExactly 'True' + $settings['Safety overrides'] | Should -BeExactly 'Force, IdentityCheckOff' + $old = Get-PraPhaseSetting -Context @{ Config = @{} } + $old['Confirmation skipped by -Force'] | Should -BeExactly 'False' + $old.Contains('Safety overrides') | Should -BeFalse + $old['Windows events'] | Should -BeExactly 'Auto' + $rows = @(Get-PraRunSetting -Config (Get-PraDefaultConfiguration)) + ($rows | Where-Object Name -ceq 'Retention policy named').Value | Should -BeLike 'empty*' + ($rows | Where-Object Name -ceq 'Exchange Online child process').Value | Should -BeExactly 'off' + ($rows | Where-Object Name -ceq 'Journal chain').Value | Should -BeExactly 'off' + } + It 'accepts the new settings in any letter case, refuses a value that is not one of them, and defaults to the behaviour of before' { + $write = { + param([string]$Body) + $path = Join-Path $global:PraGate.Root ('lotd-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.psd1') + [IO.File]::WriteAllText($path, "@{ Scope = @{ Mode = 'Auto' }; Licensing = @{ Enabled = `$false }; $Body }", (New-Object Text.UTF8Encoding($true))) + $path + } + $config = Import-PraConfiguration -Path (& $write "Logging = @{ WindowsEvents = 'oFF'; JournalChain = `$true; RequireJournalChain = `$true; TimestampOffset = `$true }; Exo = @{ ChildStart = 'stdIN' }") -Root $global:PraGate.Package + $config.Logging.WindowsEvents | Should -BeExactly 'Off' + $config.Exo.ChildStart | Should -BeExactly 'Stdin' + ($config.Logging.JournalChain, $config.Logging.RequireJournalChain, $config.Logging.TimestampOffset) -join ',' | Should -BeExactly 'True,True,True' + $plain = Import-PraConfiguration -Path (& $write '') -Root $global:PraGate.Package + $plain.Logging.WindowsEvents | Should -BeExactly 'Auto' + $plain.Exo.ChildStart | Should -BeExactly 'Auto' + ($plain.Logging.JournalChain, $plain.Logging.RequireJournalChain, $plain.Logging.TimestampOffset, $plain.Exo.UseSubprocess) -join ',' | Should -BeExactly 'False,False,False,False' + { Import-PraConfiguration -Path (& $write "Logging = @{ WindowsEvents = 'Sometimes' }") -Root $global:PraGate.Package } | Should -Throw '*Logging.WindowsEvents*Auto or Off*' + { Import-PraConfiguration -Path (& $write "Exo = @{ ChildStart = 'Pipe' }") -Root $global:PraGate.Package } | Should -Throw '*Exo.ChildStart*Auto, Stdin or File*' + { Import-PraConfiguration -Path (& $write "Logging = @{ JournalChain = 'yes' }") -Root $global:PraGate.Package } | Should -Throw '*Logging.JournalChain*true or*false*' + { Import-PraConfiguration -Path (& $write "Logging = @{ Chain = `$true }") -Root $global:PraGate.Package } | Should -Throw '*unknown setting Logging.Chain*' + } + It 'adds the offset of the local time to the text log only when Logging.TimestampOffset is on, and keeps the line as it was otherwise, in any culture' { + $before = [Threading.Thread]::CurrentThread.CurrentCulture + try { + foreach ($culture in 'en-US', 'fr-FR') { + [Threading.Thread]::CurrentThread.CurrentCulture = [Globalization.CultureInfo]::GetCultureInfo($culture) + foreach ($case in @(@{ Offset = $true; Pattern = '^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d\.\d{3}[+-]\d\d:\d\d \[DETAIL\] hello$' }, @{ Offset = $false; Pattern = '^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d\.\d{3} \[DETAIL\] hello$' })) { + $log = Join-Path $global:PraGate.Root ('offset-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.log') + $context = & $script:NewRunContext $false 'Off' $log + $context.Config.Logging.TimestampOffset = $case.Offset + Write-PraLog -Context $context -Message 'hello' -Level Detail + $line = [IO.File]::ReadAllLines($log)[0] + $line | Should -Match $case.Pattern -Because ($culture + ' offset ' + $case.Offset) + if ($case.Offset) { + $written = [regex]::Match($line, '(?[+-])(?\d\d):(?\d\d) \[').Groups + $minutes = ([int]$written['h'].Value * 60 + [int]$written['m'].Value) * $(if ($written['sign'].Value -ceq '-') { -1 } else { 1 }) + $minutes | Should -Be ([int][TimeZoneInfo]::Local.GetUtcOffset([datetime]::Now).TotalMinutes) + } + } + } + } + finally { [Threading.Thread]::CurrentThread.CurrentCulture = $before } + $oldContext = @{ LogFile = (Join-Path $global:PraGate.Root ('offset-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.log')); Warnings = 0; Issues = (New-Object 'Collections.Generic.List[object]') } + Write-PraLog -Context $oldContext -Message 'hello' -Level Detail + [IO.File]::ReadAllLines($oldContext.LogFile)[0] | Should -Match '^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d\.\d{3} \[DETAIL\] hello$' -Because 'a context without a configuration writes the same line as before' + } + It 'calls the new records from the entry script: the overrides through Add-PraOverride, the events after the start-up checks, the start of the Apply at its confirmation, and the journal chain before a Recover reads the batch' { + $text = [IO.File]::ReadAllText((Join-Path $global:PraGate.Source 'Invoke-PraRemoteMailbox.ps1')) + foreach ($id in 'AcceptRetentionRisk', 'IgnoreProof', 'Force', 'IdentityCheckOff', 'RetentionCheckOff') { $text | Should -Match ("Add-PraOverride -Context \`$context -Id '" + $id + "'") -Because $id } + $text | Should -Not -Match "ConfigOverrides = @\(@\(Get-PraList \`$context 'ConfigOverrides'\) \+ \('Retention" + $text | Should -Match 'Initialize-PraWindowsEvent -Context \$context' + $text | Should -Match 'Write-PraApplyStarted -Context \$context; return' + $text | Should -Match 'Assert-PraJournalChain -Context \$context -Path .* -Require:\(\[bool\]\$config\.Logging\.RequireJournalChain\)' + } +} + +Describe 'Release 3.3.0 - the journal names the actor and can seal its lines with a hash chain, a broken chain is a warning and a refusal only when asked (production Directory module, synthetic files)' -Tag 'Release330D' { + BeforeAll { + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Directory.psm1') -Force -Global + $script:Sha = { param([string]$Line) [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData((New-Object Text.UTF8Encoding($false)).GetBytes($Line))).ToLowerInvariant() } + $script:NewJournal = { + param([bool]$Chain, [int]$Count, [string]$Existing = '') + $path = Join-Path $global:PraGate.Root ('journal-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.jsonl') + if ($Existing) { [IO.File]::WriteAllText($path, $Existing, (New-Object Text.UTF8Encoding($false))) } + $global:PraGate.L330DJournal = @{ Path = $path; Chain = $Chain; Count = $Count } + InModuleScope PRA.Directory { + $request = $global:PraGate.L330DJournal + $context = @{ JournalPath = $request.Path; RunId = 'run-1'; Config = @{ Logging = @{ JournalChain = $request.Chain } } } + for ($i = 1; $i -le $request.Count; $i++) { Write-PraJournal -Context $context -Target ('AAAAAAAA-0000-0000-0000-00000000000' + $i) -Operation 'Set-ADUser' -Status 'Started' -Detail ('line ' + $i) } + } + $global:PraGate.Remove('L330DJournal') + $path + } + $script:Chain = { param([string]$Path) InModuleScope PRA.Directory -Parameters @{ Path = $Path } { Test-PraJournalChain -Path $Path } } + $script:Write = { param([string]$Path, [string[]]$Line, [string]$Terminator = "`r`n") [IO.File]::WriteAllText($Path, (($Line -join $Terminator) + $Terminator), (New-Object Text.UTF8Encoding($false))) } + } + It 'names the account by its SID, the computer, the process and the run on every new line, with or without the chain' { + $path = & $script:NewJournal $false 2 + $lines = @([IO.File]::ReadAllLines($path)) + $lines.Count | Should -Be 2 + foreach ($line in $lines) { + $entry = $line | ConvertFrom-Json -DateKind String + $entry.Account | Should -BeExactly ([Security.Principal.WindowsIdentity]::GetCurrent().User.Value) + $entry.Computer | Should -BeExactly ([Environment]::MachineName) + $entry.ProcessId | Should -Be $PID + $entry.RunId | Should -BeExactly 'run-1' + $entry.PSObject.Properties['Prev'] | Should -BeNullOrEmpty -Because 'the chain is off by default' + } + } + It 'chains the lines when asked: START for the first, the SHA-256 of the previous line for the others, and a journal that is intact is read as intact' { + $path = & $script:NewJournal $true 4 + $lines = @([IO.File]::ReadAllLines($path)) + $lines.Count | Should -Be 4 + ($lines[0] | ConvertFrom-Json -DateKind String).Prev | Should -BeExactly 'START' + for ($i = 1; $i -lt 4; $i++) { ($lines[$i] | ConvertFrom-Json -DateKind String).Prev | Should -BeExactly (& $script:Sha $lines[$i - 1]) } + $result = & $script:Chain $path + $result.Chained | Should -BeTrue + $result.Lines | Should -Be 4 + @($result.Broken).Count | Should -Be 0 + } + It 'continues the chain across runs and across an older journal: the first chained line holds the hash of the last line before it' { + $old = '{"RunId":"older","Utc":"2026-11-01T10:00:00.0000000Z","Target":"AAAAAAAA-0000-0000-0000-000000000009","Operation":"Set-ADUser","Status":"Started","Detail":""}' + $path = & $script:NewJournal $true 2 ($old + "`r`n") + $lines = @([IO.File]::ReadAllLines($path)) + ($lines[1] | ConvertFrom-Json -DateKind String).Prev | Should -BeExactly (& $script:Sha $old) + $second = & $script:NewJournal $true 1 ([IO.File]::ReadAllText($path)) + $result = & $script:Chain $second + @($result.Broken).Count | Should -Be 0 + $result.Lines | Should -Be 4 + } + It 'reads an older journal, with no chain at all, as before: nothing is broken, nothing is said' { + $path = Join-Path $global:PraGate.Root ('journal-old-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.jsonl') + & $script:Write $path @('{"RunId":"r","Utc":"u","Target":"AAAAAAAA-0000-0000-0000-000000000001","Operation":"Set-ADUser","Status":"Started","Detail":""}', '{"RunId":"r","Utc":"u","Target":"AAAAAAAA-0000-0000-0000-000000000001","Operation":"Set-ADUser","Status":"Applied","Detail":""}') + $result = & $script:Chain $path + $result.Chained | Should -BeFalse + @($result.Broken).Count | Should -Be 0 + $context = @{ StepIndex = 0; StepTotal = 4; Issues = (New-Object 'Collections.Generic.List[object]'); Warnings = 0; LogFile = ''; Action = 'Recover'; CurrentPhase = '' } + $global:PraGate.L330DJournal = @{ Path = $path; Context = $context } + $null = InModuleScope PRA.Directory { Assert-PraJournalChain -Context $global:PraGate.L330DJournal.Context -Path $global:PraGate.L330DJournal.Path -Require 6>$null } + $global:PraGate.Remove('L330DJournal') + $context.Warnings | Should -Be 0 + } + It 'sees a line that was edited, removed, inserted, replaced or cut, at the line that follows or at the line itself, and documents that the removal of the last line is not seen' { + $path = & $script:NewJournal $true 5 + $original = @([IO.File]::ReadAllLines($path)) + $cases = [ordered]@{ + Edited = @($original[0], $original[1].Replace('line 2', 'line X'), $original[2], $original[3], $original[4]) + Removed = @($original[0], $original[1], $original[3], $original[4]) + Inserted = @($original[0], $original[1], '{"RunId":"forged","Utc":"u","Target":"AAAAAAAA-0000-0000-0000-000000000077","Operation":"Set-ADUser","Status":"Started","Detail":""}', $original[2], $original[3], $original[4]) + Cut = @($original[0], $original[1], $original[2].Substring(0, 40), $original[3], $original[4]) + LastRemoved = @($original[0], $original[1], $original[2], $original[3]) + } + $found = [ordered]@{} + foreach ($name in $cases.Keys) { + $copy = Join-Path $global:PraGate.Root ('journal-' + $name + '-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.jsonl') + & $script:Write $copy $cases[$name] + $found[$name] = @((& $script:Chain $copy).Broken) -join ',' + } + $found.Edited | Should -BeExactly '3' + $found.Removed | Should -BeExactly '3' + $found.Inserted | Should -BeExactly '3,4' + $found.Cut | Should -BeExactly '3,4' + $found.LastRemoved | Should -BeExactly '' -Because 'a journal cut after a complete line is a shorter journal: the chain has no end marker' + } + It 'compares the hash exactly: the same hash in capital letters is a broken link' { + $path = & $script:NewJournal $true 3 + $lines = @([IO.File]::ReadAllLines($path)) + $hash = ($lines[2] | ConvertFrom-Json -DateKind String).Prev + & $script:Write $path @($lines[0], $lines[1], $lines[2].Replace($hash, $hash.ToUpperInvariant())) + @((& $script:Chain $path).Broken) -join ',' | Should -BeExactly '3' + } + It 'starts a new line after a line that was cut by a crash, and the chain goes on from the cut line' { + $path = & $script:NewJournal $true 2 + $cut = [IO.File]::ReadAllText($path).TrimEnd("`r", "`n") + $cut = $cut.Substring(0, $cut.Length - 20) + [IO.File]::WriteAllText($path, $cut, (New-Object Text.UTF8Encoding($false))) + $after = & $script:NewJournal $true 2 $cut + $lines = @([IO.File]::ReadAllLines($after)) + $lines.Count | Should -Be 4 -Because 'the new lines do not stick to the cut line' + $result = & $script:Chain $after + @($result.Broken).Count | Should -Be 0 -Because 'the line after the cut line holds its hash: a crash, not an edit' + @($result.Torn) -join ',' | Should -BeExactly '2' + } + It 'reports the last line as torn when a crash cut it and nothing was written after it, and a cut line that nothing links to as broken' { + $path = & $script:NewJournal $true 3 + $text = [IO.File]::ReadAllText($path).TrimEnd("`r", "`n") + $last = Join-Path $global:PraGate.Root ('journal-last-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.jsonl') + [IO.File]::WriteAllText($last, $text.Substring(0, $text.Length - 30), (New-Object Text.UTF8Encoding($false))) + $result = & $script:Chain $last + @($result.Broken).Count | Should -Be 0 + @($result.Torn) -join ',' | Should -BeExactly '3' + $lines = @([IO.File]::ReadAllLines($path)) + $forged = Join-Path $global:PraGate.Root ('journal-forged-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.jsonl') + & $script:Write $forged @($lines[0], $lines[1].Substring(0, $lines[1].Length - 30), $lines[2]) + $result = & $script:Chain $forged + @($result.Broken) -join ',' | Should -BeExactly '2,3' -Because 'the line after the cut one does not hold the hash of what is left of it' + @($result.Torn).Count | Should -Be 0 + $notJson = Join-Path $global:PraGate.Root ('journal-text-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.jsonl') + & $script:Write $notJson @($lines[0], 'not a journal line', $lines[2]) + $result = & $script:Chain $notJson + @($result.Broken) -join ',' | Should -BeExactly '2,3' + } + It 'does not stop a Recover for a torn line alone, with the refusal on: one warning that names the line, and still a refusal for a broken one' { + $path = & $script:NewJournal $true 2 + $cut = [IO.File]::ReadAllText($path).TrimEnd("`r", "`n") + $after = & $script:NewJournal $true 2 $cut.Substring(0, $cut.Length - 20) + $context = @{ StepIndex = 0; StepTotal = 4; Issues = (New-Object 'Collections.Generic.List[object]'); Warnings = 0; LogFile = ''; Action = 'Recover'; CurrentPhase = '' } + $global:PraGate.L330DJournal = @{ Path = $after; Context = $context } + try { + $result = InModuleScope PRA.Directory { Assert-PraJournalChain -Context $global:PraGate.L330DJournal.Context -Path $global:PraGate.L330DJournal.Path -Require 6>$null } + @($result.Broken).Count | Should -Be 0 + @($result.Torn) -join ',' | Should -BeExactly '2' + $context.Warnings | Should -Be 1 + $context.Issues.Count | Should -Be 0 + $context.WarningList[0].Message | Should -BeLike '*write that was cut at line 2*nothing is blocked*audit logs*' + } + finally { $global:PraGate.Remove('L330DJournal') } + } + It 'keeps the chain once the journal carries it, whatever the setting says later ()' -ForEach @( + @{ Name = 'on then off'; First = $true; Second = $false } + @{ Name = 'on then on'; First = $true; Second = $true } + ) { + $one = & $script:NewJournal $First 2 + $two = & $script:NewJournal $Second 2 ([IO.File]::ReadAllText($one)) + $lines = @([IO.File]::ReadAllLines($two)) + $lines.Count | Should -Be 4 + foreach ($line in $lines) { ($line | ConvertFrom-Json -DateKind String).PSObject.Properties['Prev'] | Should -Not -BeNullOrEmpty } + $result = & $script:Chain $two + @($result.Broken).Count | Should -Be 0 + $result.Lines | Should -Be 4 + } + It 'does not add the chain to a journal that does not carry it while the setting is off, and starts it when the setting is turned on (off then on)' { + $first = & $script:NewJournal $false 2 + foreach ($line in @([IO.File]::ReadAllLines($first))) { ($line | ConvertFrom-Json -DateKind String).PSObject.Properties['Prev'] | Should -BeNullOrEmpty } + $second = & $script:NewJournal $true 2 ([IO.File]::ReadAllText($first)) + $lines = @([IO.File]::ReadAllLines($second)) + ($lines[2] | ConvertFrom-Json -DateKind String).Prev | Should -BeExactly (& $script:Sha $lines[1]) + $result = & $script:Chain $second + @($result.Broken).Count | Should -Be 0 + $result.Chained | Should -BeTrue + } + It 'keeps the chain when the setting changes inside one run and when the tail was cut before the run goes on with the chain off' { + $path = Join-Path $global:PraGate.Root ('journal-toggle-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.jsonl') + $global:PraGate.L330DJournal = @{ Path = $path } + try { + InModuleScope PRA.Directory { + $path = $global:PraGate.L330DJournal.Path + $context = @{ JournalPath = $path; RunId = 'run-1'; Config = @{ Logging = @{ JournalChain = $false } } } + Write-PraJournal -Context $context -Target 'a' -Operation 'Op' -Status 'Started' + $context.Config.Logging.JournalChain = $true + Write-PraJournal -Context $context -Target 'a' -Operation 'Op' -Status 'Applied' + $context.Config.Logging.JournalChain = $false + Write-PraJournal -Context $context -Target 'a' -Operation 'Op' -Status 'Verified' + $bytes = [IO.File]::ReadAllBytes($path) + [IO.File]::WriteAllBytes($path, $bytes[0..($bytes.Length - 25)]) + $other = @{ JournalPath = $path; RunId = 'run-2'; Config = @{ Logging = @{ JournalChain = $false } } } + Write-PraJournal -Context $other -Target 'b' -Operation 'Op' -Status 'Started' + Write-PraJournal -Context $other -Target 'b' -Operation 'Op' -Status 'Applied' + } + $lines = @([IO.File]::ReadAllLines($path)) + $lines.Count | Should -Be 5 + ($lines[0] | ConvertFrom-Json -DateKind String).PSObject.Properties['Prev'] | Should -BeNullOrEmpty -Because 'the first line was written with the chain off, on a journal without it' + foreach ($line in $lines[1, 3, 4]) { ($line | ConvertFrom-Json -DateKind String).Prev | Should -Not -BeNullOrEmpty } + $result = & $script:Chain $path + @($result.Broken).Count | Should -Be 0 + @($result.Torn) -join ',' | Should -BeExactly '3' + } + finally { $global:PraGate.Remove('L330DJournal') } + } + It 'chains after a last line that is longer than the window read at the end of the file, and after a line that someone else appended since the last write' { + $path = Join-Path $global:PraGate.Root ('journal-long-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.jsonl') + $global:PraGate.L330DJournal = @{ Path = $path } + try { + InModuleScope PRA.Directory { + $context = @{ JournalPath = $global:PraGate.L330DJournal.Path; RunId = 'run-1'; Config = @{ Logging = @{ JournalChain = $true } } } + Write-PraJournal -Context $context -Target 'a' -Operation 'Op' -Status 'Started' -Detail ('x' * 30000) + Write-PraJournal -Context $context -Target 'a' -Operation 'Op' -Status 'Applied' + [IO.File]::AppendAllText($context.JournalPath, ('{"RunId":"manual","Detail":"' + ('y' * 20000) + '"}' + "`r`n"), (New-Object Text.UTF8Encoding($false))) + Write-PraJournal -Context $context -Target 'a' -Operation 'Op' -Status 'Verified' + } + $lines = @([IO.File]::ReadAllLines($path)) + $lines.Count | Should -Be 4 + ($lines[1] | ConvertFrom-Json -DateKind String).Prev | Should -BeExactly (& $script:Sha $lines[0]) + ($lines[3] | ConvertFrom-Json -DateKind String).Prev | Should -BeExactly (& $script:Sha $lines[2]) + } + finally { $global:PraGate.Remove('L330DJournal') } + } + It 'writes 2,000 chained lines in a time of the same order as 2,000 lines without the chain, through one handle each, and every line links to the one before it' { + $global:PraGate.L330DJournal = @{ Plain = Join-Path $global:PraGate.Root ('journal-plain-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.jsonl'); Chained = Join-Path $global:PraGate.Root ('journal-timed-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.jsonl') } + try { + $times = InModuleScope PRA.Directory { + $request = $global:PraGate.L330DJournal + $measure = { + param([string]$Path, [bool]$Chain) + $context = @{ JournalPath = $Path; RunId = 'run-1'; Config = @{ Logging = @{ JournalChain = $Chain } } } + $clock = [Diagnostics.Stopwatch]::StartNew() + for ($i = 0; $i -lt 2000; $i++) { Write-PraJournal -Context $context -Target ('AAAAAAAA-0000-0000-0000-000000000001') -Operation 'Set-ADUser' -Status 'Done' -Detail ('line ' + $i) } + $clock.Elapsed.TotalSeconds + } + [pscustomobject]@{ Plain = (& $measure $request.Plain $false); Chained = (& $measure $request.Chained $true) } + } + $times.Chained | Should -BeLessThan (4 * $times.Plain + 3) -Because ('chained {0:n2} s, plain {1:n2} s' -f $times.Chained, $times.Plain) + $lines = @([IO.File]::ReadAllLines($global:PraGate.L330DJournal.Chained)) + $lines.Count | Should -Be 2000 + @((& $script:Chain $global:PraGate.L330DJournal.Chained).Broken).Count | Should -Be 0 + ($lines[1999] | ConvertFrom-Json -DateKind String).Prev | Should -BeExactly (& $script:Sha $lines[1998]) + } + finally { $global:PraGate.Remove('L330DJournal') } + } + It 'reads only a small window at the end of the journal: a big journal costs the same as a small one, and the window grows only for a line that does not fit' { + $path = Join-Path $global:PraGate.Root ('journal-window-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.jsonl') + $line = '{"RunId":"r","Detail":"' + ('z' * 900) + '","Prev":"START"}' + $builder = New-Object Text.StringBuilder + for ($i = 0; $i -lt 6000; $i++) { [void]$builder.Append($line).Append("`r`n") } + [IO.File]::WriteAllText($path, $builder.ToString(), (New-Object Text.UTF8Encoding($false))) + (Get-Item -LiteralPath $path).Length | Should -BeGreaterThan 5000000 + $global:PraGate.L330DJournal = @{ Path = $path } + try { + $probe = InModuleScope PRA.Directory { + $stream = New-Object IO.FileStream($global:PraGate.L330DJournal.Path, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::ReadWrite) + try { + $tail = Get-PraJournalTail -Stream $stream + $moved = $stream.Position + $small = Get-PraJournalTail -Stream $stream -WindowBytes 64 + [pscustomobject]@{ Hash = $tail.Hash; Position = $moved; Length = $stream.Length; Small = $small.Hash; Chained = $tail.Chained } + } + finally { $stream.Dispose() } + } + $probe.Hash | Should -BeExactly (& $script:Sha $line) + $probe.Small | Should -BeExactly $probe.Hash -Because 'a window smaller than the line grows until the line fits' + $probe.Position | Should -Be $probe.Length -Because 'the window ends at the end of the file' + $probe.Chained | Should -BeTrue + $window = InModuleScope PRA.Directory { [regex]::Match((Get-Command Get-PraJournalTail).ScriptBlock.ToString(), '\[int\]\$WindowBytes = (\d+)').Groups[1].Value } + [int]$window | Should -Be 8192 + } + finally { $global:PraGate.Remove('L330DJournal') } + } + It 'warns once with the lines that are broken, and refuses with -Require, before anything is written' { + $path = & $script:NewJournal $true 4 + $lines = @([IO.File]::ReadAllLines($path)) + & $script:Write $path @($lines[0], $lines[2], $lines[3]) + $context = @{ StepIndex = 0; StepTotal = 4; Issues = (New-Object 'Collections.Generic.List[object]'); Warnings = 0; LogFile = ''; Action = 'Recover'; CurrentPhase = '' } + $global:PraGate.L330DJournal = @{ Path = $path; Context = $context } + try { + $result = InModuleScope PRA.Directory { Assert-PraJournalChain -Context $global:PraGate.L330DJournal.Context -Path $global:PraGate.L330DJournal.Path 6>$null } + @($result.Broken) -join ',' | Should -BeExactly '2' + $context.Warnings | Should -Be 1 + $context.Issues.Count | Should -Be 0 + { InModuleScope PRA.Directory { Assert-PraJournalChain -Context $global:PraGate.L330DJournal.Context -Path $global:PraGate.L330DJournal.Path -Require 6>$null } } | Should -Throw '*is broken at line 2*Logging.RequireJournalChain is on, so nothing was changed*' + $context.Warnings | Should -Be 1 -Because 'a refusal is not a second warning' + } + finally { $global:PraGate.Remove('L330DJournal') } + } + It 'still finds the objects a chained journal names (the extra fields are tolerated), and gives the same chain under a French culture' { + $path = & $script:NewJournal $true 3 + $global:PraGate.L330DJournal = @{ Path = $path } + $before = [Threading.Thread]::CurrentThread.CurrentCulture + try { + $set = InModuleScope PRA.Directory { Get-PraJournalTouchedObject -Path $global:PraGate.L330DJournal.Path } + @($set | Sort-Object) -join ',' | Should -BeExactly 'AAAAAAAA-0000-0000-0000-000000000001,AAAAAAAA-0000-0000-0000-000000000002,AAAAAAAA-0000-0000-0000-000000000003' + [Threading.Thread]::CurrentThread.CurrentCulture = [Globalization.CultureInfo]::GetCultureInfo('fr-FR') + $french = & $script:NewJournal $true 3 + $result = & $script:Chain $french + $result.Chained | Should -BeTrue + @($result.Broken).Count | Should -Be 0 + } + finally { [Threading.Thread]::CurrentThread.CurrentCulture = $before; $global:PraGate.Remove('L330DJournal') } + } +} + +Describe 'Release 3.3.0 - the Exchange Online child starts from its standard input, and the temporary script file is only the fallback, never used after the child has connected (production Cloud functions, synthetic child scripts)' -Tag 'Release330D' { + BeforeAll { + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global + $cloudAst = [Management.Automation.Language.Parser]::ParseFile((Join-Path $global:PraGate.Package 'module\PRA.Cloud.psm1'), [ref]$null, [ref]$null) + $script:ExoFunctions = (@('Get-PraExecutionPolicyState', 'Test-PraExoSecurityError', 'Get-PraExoPolicyRefusal', 'Get-PraExoErrorDetail', 'Test-PraExoPolicyRefusal', 'Read-PraExoRefusalDetail', 'Get-PraFileSignatureFact', 'Test-PraExoModuleSignature', 'Get-PraExoModuleCandidate', 'Get-PraExoVerifiedModule', 'Get-PraExoChildFolderPath', 'Test-PraExoChildFallback', 'Remove-PraExoChildFolder', 'Invoke-PraExoChild', 'Invoke-PraExoSubprocess') | ForEach-Object { + $name = $_ + $function = $cloudAst.Find({ param($n) $n -is [Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -ceq $name }, $true) + if ($null -eq $function) { throw ('function not found: ' + $name) } + $function.Extent.Text + }) -join "`n" + $script:StartText = $script:ExoFunctions + $script:Child = @' +$ErrorActionPreference = 'Stop' +Set-StrictMode -Version Latest +$info = [ordered]@{ Script = [string]$PSCommandPath; Ok = $false } +$worker = { + param($a) + + $text = @" +first + +second +"@ + $a + $text.Length +} +try { + $null = & $worker 5 + + $info.Ok = $true +} catch { $info.Ok = $false } +if ($info.Script) { + $folder = Split-Path -Parent $info.Script + $acl = Get-Acl -LiteralPath $folder + $info.Protected = $acl.AreAccessRulesProtected + $info.Sids = @($acl.Access | ForEach-Object { $_.IdentityReference.Translate([Security.Principal.SecurityIdentifier]).Value } | Sort-Object -Unique) + $info.Folder = Split-Path -Leaf $folder +} +[Console]::Out.WriteLine(($info | ConvertTo-Json -Compress)) +exit 3 +'@ + $global:PraGate.L330DModes = New-Object 'Collections.Generic.List[string]' + $script:NewContext = { + param([string]$Start = 'Auto') + $exo = @{ DisableWAM = $false } + if ($Start) { $exo.ChildStart = $Start } + @{ Config = @{ Cloud = @{ TenantId = ''; AppId = ''; CertificateThumbprint = ''; Organization = '' }; Exo = $exo }; TimeoutMinutes = 1; StepIndex = 0; StepTotal = 1; Issues = (New-Object 'Collections.Generic.List[object]'); Warnings = 0; LogFile = ''; Action = 'Recover'; CurrentPhase = '' } + } + } + BeforeEach { $global:PraGate.L330DModes.Clear() } + AfterAll { $global:PraGate.Remove('L330DModes') } + It 'allows the second start only for the first start through the standard input, only when the child never ran its script, never after the child connected and never after a timeout' -ForEach @( + @{ Mode = 'Stdin'; Attempt = 0; Attempts = 2; Started = $false; Connected = $false; TimedOut = $false; Expect = $true } + @{ Mode = 'STDIN'; Attempt = 0; Attempts = 2; Started = $false; Connected = $false; TimedOut = $false; Expect = $true } + @{ Mode = 'Stdin'; Attempt = 0; Attempts = 2; Started = $false; Connected = $true; TimedOut = $false; Expect = $false } + @{ Mode = 'Stdin'; Attempt = 0; Attempts = 2; Started = $false; Connected = $false; TimedOut = $true; Expect = $false } + @{ Mode = 'Stdin'; Attempt = 0; Attempts = 1; Started = $false; Connected = $false; TimedOut = $false; Expect = $false } + @{ Mode = 'Stdin'; Attempt = 0; Attempts = 2; Started = $true; Connected = $false; TimedOut = $false; Expect = $false } + @{ Mode = 'Stdin'; Attempt = 0; Attempts = 2; Started = $true; Connected = $true; TimedOut = $true; Expect = $false } + @{ Mode = 'File'; Attempt = 1; Attempts = 2; Started = $false; Connected = $false; TimedOut = $false; Expect = $false } + @{ Mode = 'File'; Attempt = 0; Attempts = 1; Started = $false; Connected = $false; TimedOut = $false; Expect = $false } + ) { + . ([scriptblock]::Create($script:ExoFunctions)) + Mock Get-PraExecutionPolicyState { [pscustomobject]@{ Effective = 'RemoteSigned'; Source = 'LocalMachine'; Enforced = $false } } + Test-PraExoChildFallback -Mode $Mode -Attempt $Attempt -Attempts $Attempts -Started $Started -Connected $Connected -TimedOut $TimedOut | Should -Be $Expect + } + It 'runs a multi-line script with a here-string, blank lines and a try block from the standard input: no script file, the exit code and the one JSON line come back' { + . ([scriptblock]::Create($script:ExoFunctions)) + Mock Get-PraExecutionPolicyState { [pscustomobject]@{ Effective = 'RemoteSigned'; Source = 'LocalMachine'; Enforced = $false } } + $id = [guid]::NewGuid().ToString('N') + $run = Invoke-PraExoChild -Mode Stdin -Child $script:Child -Id $id -TimeoutMilliseconds 120000 -ProgressPath '' + $run.ExitCode | Should -Be 3 + $run.TimedOut | Should -BeFalse + $run.Err | Should -BeExactly '' + $info = $run.Out | ConvertFrom-Json -DateKind String + $info.Ok | Should -BeTrue + $info.Script | Should -BeExactly '' -Because 'the script is not a file' + @(Get-ChildItem -LiteralPath ([IO.Path]::GetTempPath()) -Filter ('praexo_' + $id + '*') -Force -ErrorAction SilentlyContinue).Count | Should -Be 0 + } + It 'runs the same script from a private folder of the run when it is asked for, and deletes the folder at the end' { + . ([scriptblock]::Create($script:ExoFunctions)) + Mock Get-PraExecutionPolicyState { [pscustomobject]@{ Effective = 'RemoteSigned'; Source = 'LocalMachine'; Enforced = $false } } + $id = [guid]::NewGuid().ToString('N') + $run = Invoke-PraExoChild -Mode File -Child $script:Child -Id $id -TimeoutMilliseconds 120000 -ProgressPath '' + $run.ExitCode | Should -Be 3 + $info = $run.Out | ConvertFrom-Json -DateKind String + $info.Ok | Should -BeTrue + $info.Script | Should -BeLike '*\child.ps1' + $info.Folder | Should -Match '^praexo_[0-9a-f]{32}$' + $info.Folder | Should -Not -BeLike ('*' + $id + '*') -Because 'the name of the folder is not the id that the markers of the temporary folder show' + $info.Protected | Should -BeTrue + foreach ($sid in 'S-1-1-0', 'S-1-5-11', 'S-1-5-32-545') { @($info.Sids) | Should -Not -Contain $sid } + Test-Path -LiteralPath (Join-Path ([IO.Path]::GetTempPath()) $info.Folder) | Should -BeFalse + } + It 'refuses a folder of that name that already exists, uses nothing in it and deletes nothing in it, and a file of that name is refused too' { + . ([scriptblock]::Create($script:ExoFunctions)) + Mock Get-PraExecutionPolicyState { [pscustomobject]@{ Effective = 'RemoteSigned'; Source = 'LocalMachine'; Enforced = $false } } + $id = [guid]::NewGuid().ToString('N') + $existing = Join-Path ([IO.Path]::GetTempPath()) ('praexo_' + [guid]::NewGuid().ToString('N')) + $global:PraGate.L330SFolder = $existing + Mock Get-PraExoChildFolderPath { $global:PraGate.L330SFolder } + $null = New-Item -ItemType Directory -Path $existing -Force + [IO.File]::WriteAllText((Join-Path $existing 'planted.txt'), 'x') + $acl = Get-Acl -LiteralPath $existing + try { + { Invoke-PraExoChild -Mode File -Child 'exit 0' -Id $id -TimeoutMilliseconds 120000 -ProgressPath '' } | Should -Throw '*already exists*This run did not create it*Remove-Item -LiteralPath*' + Test-Path -LiteralPath (Join-Path $existing 'planted.txt') | Should -BeTrue -Because 'the folder is not deleted' + Test-Path -LiteralPath (Join-Path $existing 'child.ps1') | Should -BeFalse -Because 'no script is written into it' + (Get-Acl -LiteralPath $existing).AreAccessRulesProtected | Should -Be $acl.AreAccessRulesProtected -Because 'its ACL is not changed' + Remove-Item -LiteralPath $existing -Recurse -Force + $asFile = Join-Path ([IO.Path]::GetTempPath()) ('praexo_' + [guid]::NewGuid().ToString('N')) + $global:PraGate.L330SFolder = $asFile + [IO.File]::WriteAllText($asFile, 'x') + try { { Invoke-PraExoChild -Mode File -Child 'exit 0' -Id ($id.Substring(1) + 'a') -TimeoutMilliseconds 120000 -ProgressPath '' } | Should -Throw '*already exists*' } + finally { Remove-Item -LiteralPath $asFile -Force -ErrorAction SilentlyContinue } + } + finally { Remove-Item -LiteralPath $existing -Recurse -Force -ErrorAction SilentlyContinue; $global:PraGate.Remove('L330SFolder') } + } + It 'writes one Detail line, and nothing else, when the folder of the script file cannot be deleted: no error, no warning, no issue' { + . ([scriptblock]::Create($script:ExoFunctions)) + Mock Get-PraExecutionPolicyState { [pscustomobject]@{ Effective = 'RemoteSigned'; Source = 'LocalMachine'; Enforced = $false } } + $folder = Join-Path ([IO.Path]::GetTempPath()) ('praexo_' + [guid]::NewGuid().ToString('N')) + $null = New-Item -ItemType Directory -Path $folder -Force + $log = Join-Path $global:PraGate.Root ('exo-folder-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.log') + $context = & $script:NewContext 'Auto' + $context.LogFile = $log + $held = [IO.File]::Open((Join-Path $folder 'child.ps1'), [IO.FileMode]::Create, [IO.FileAccess]::ReadWrite, [IO.FileShare]::None) + try { + { Remove-PraExoChildFolder -Path $folder -Context $context } | Should -Not -Throw + Remove-PraExoChildFolder -Path $folder + @([IO.File]::ReadAllLines($log)).Count | Should -Be 1 + [IO.File]::ReadAllText($log) | Should -Match '\[DETAIL\] The temporary folder of the Exchange Online child process was not deleted \(\w+\)\. Delete it when no program uses it: Remove-Item -LiteralPath' + $context.Warnings | Should -Be 0 + $context.Issues.Count | Should -Be 0 + } + finally { $held.Dispose(); Remove-Item -LiteralPath $folder -Recurse -Force -ErrorAction SilentlyContinue } + Remove-PraExoChildFolder -Path $folder -Context $context + Remove-PraExoChildFolder -Path '' -Context $context + @([IO.File]::ReadAllLines($log)).Count | Should -Be 1 -Because 'a folder that is gone, or no folder, says nothing' + } + It 'reports a child that stops at once as an exit code, not as an exception, so that the caller can decide' { + . ([scriptblock]::Create($script:ExoFunctions)) + Mock Get-PraExecutionPolicyState { [pscustomobject]@{ Effective = 'RemoteSigned'; Source = 'LocalMachine'; Enforced = $false } } + $run = Invoke-PraExoChild -Mode Stdin -Child 'exit 1' -Id ([guid]::NewGuid().ToString('N')) -TimeoutMilliseconds 120000 -ProgressPath '' + $run.ExitCode | Should -Be 1 + } + It 'uses no execution policy parameter and no script file on the standard input path, and the Bypass path only for the file' { + $match = [regex]::Match($script:StartText, "(?s)if \(Test-PraOrdinalIgnoreCaseEqual \`$Mode 'Stdin'\) \{ \`$si\.Arguments = '([^']*)'") + $match.Success | Should -BeTrue + $match.Groups[1].Value | Should -BeExactly '-NoLogo -NoProfile -NonInteractive -Command -' + $match.Groups[1].Value | Should -Not -Match '(?i)ExecutionPolicy|-File' + ([regex]::Matches($script:StartText, '-NonInteractive -ExecutionPolicy Bypass -File')).Count | Should -Be 1 + } + It 'starts once through the standard input and once more from the file, with ONE warning that names the reason, when the child did not connect (Exo.ChildStart )' -ForEach @( + @{ Start = 'Auto' } + @{ Start = 'aUTO' } + @{ Start = '' } + ) { + . ([scriptblock]::Create($script:ExoFunctions)) + Mock Get-PraExecutionPolicyState { [pscustomobject]@{ Effective = 'RemoteSigned'; Source = 'LocalMachine'; Enforced = $false } } + $script:PraExoWorker = { 'worker' } + Mock Invoke-PraExoChild { + $global:PraGate.L330DModes.Add($Mode) + if ($Mode -ceq 'Stdin') { return [pscustomobject]@{ Out = ''; Err = 'cannot run'; ExitCode = 1; TimedOut = $false } } + [pscustomobject]@{ Out = ('{"Protocol":1,"Id":"' + $Id + '","Ok":true,"Data":{"Probe":"ok"},"Error":""}'); Err = ''; ExitCode = 0; TimedOut = $false } + } + $context = & $script:NewContext $Start + $data = Invoke-PraExoSubprocess -Context $context -Operation 'Probe' -Params @{} -Permit $null -OnApplied $null -OnProgress $null 6>$null + $data.Probe | Should -BeExactly 'ok' + ($global:PraGate.L330DModes -join ',') | Should -BeExactly 'Stdin,File' + $context.Warnings | Should -Be 1 + $context.WarningList[0].Message | Should -BeLike '*did not run from its standard input (exit code 1)*AllSigned*Constrained Language*temporary script file*private folder*nothing was sent to Exchange Online*' + } + It 'starts the second time when the first start throws, and says so once' { + . ([scriptblock]::Create($script:ExoFunctions)) + Mock Get-PraExecutionPolicyState { [pscustomobject]@{ Effective = 'RemoteSigned'; Source = 'LocalMachine'; Enforced = $false } } + $script:PraExoWorker = { 'worker' } + Mock Invoke-PraExoChild { + $global:PraGate.L330DModes.Add($Mode) + if ($Mode -ceq 'Stdin') { throw [InvalidOperationException]::new('no start') } + [pscustomobject]@{ Out = ('{"Protocol":1,"Id":"' + $Id + '","Ok":true,"Data":{"Probe":"ok"},"Error":""}'); Err = ''; ExitCode = 0; TimedOut = $false } + } + $context = & $script:NewContext 'Auto' + (Invoke-PraExoSubprocess -Context $context -Operation 'Probe' -Params @{} -Permit $null -OnApplied $null -OnProgress $null 6>$null).Probe | Should -BeExactly 'ok' + ($global:PraGate.L330DModes -join ',') | Should -BeExactly 'Stdin,File' + $context.WarningList[0].Message | Should -BeLike '*(InvalidOperationException)*' + } + It 'never starts the second time after the child connected: the child that stopped after its sign-in is an error, started once, without a warning' { + . ([scriptblock]::Create($script:ExoFunctions)) + Mock Get-PraExecutionPolicyState { [pscustomobject]@{ Effective = 'RemoteSigned'; Source = 'LocalMachine'; Enforced = $false } } + $script:PraExoWorker = { 'worker' } + Mock Invoke-PraExoChild { + $global:PraGate.L330DModes.Add($Mode) + [IO.File]::WriteAllText((Join-Path ([IO.Path]::GetTempPath()) ('praexo_' + $Id + '.connected')), '1') + [pscustomobject]@{ Out = ''; Err = 'The sign-out failed.'; ExitCode = 1; TimedOut = $false } + } + $context = & $script:NewContext 'Auto' + { Invoke-PraExoSubprocess -Context $context -Operation 'Probe' -Params @{} -Permit $null -OnApplied $null -OnProgress $null 6>$null } | Should -Throw '*Exchange Online child process code=1*' + ($global:PraGate.L330DModes -join ',') | Should -BeExactly 'Stdin' + $context.Warnings | Should -Be 0 + @(Get-ChildItem -LiteralPath ([IO.Path]::GetTempPath()) -Filter 'praexo_*.connected' -Force -ErrorAction SilentlyContinue).Count | Should -Be 0 -Because 'the marker is removed at the end' + } + It 'starts the child once and says nothing about the execution policy when the child ran its script and failed before it connected (sign-in or module failure): the failure is reported once' { + . ([scriptblock]::Create($script:ExoFunctions)) + Mock Get-PraExecutionPolicyState { [pscustomobject]@{ Effective = 'RemoteSigned'; Source = 'LocalMachine'; Enforced = $false } } + $script:PraExoWorker = { 'worker' } + Mock Invoke-PraExoChild { + $global:PraGate.L330DModes.Add($Mode) + [IO.File]::WriteAllText((Join-Path ([IO.Path]::GetTempPath()) ('praexo_' + $Id + '.started')), '1') + [pscustomobject]@{ Out = ''; Err = 'AADSTS700027: the certificate was refused.'; ExitCode = 1; TimedOut = $false } + } + $context = & $script:NewContext 'Auto' + { Invoke-PraExoSubprocess -Context $context -Operation 'Probe' -Params @{} -Permit $null -OnApplied $null -OnProgress $null 6>$null } | Should -Throw '*child process code=1*AADSTS700027*' + ($global:PraGate.L330DModes -join ',') | Should -BeExactly 'Stdin' + $context.Warnings | Should -Be 0 + @(Get-ChildItem -LiteralPath ([IO.Path]::GetTempPath()) -Filter 'praexo_*.started' -Force -ErrorAction SilentlyContinue).Count | Should -Be 0 -Because 'the marker is removed at the end' + } + It 'writes the start marker as the first statement of the child, before any module is loaded, with the path of this run, and removes it at the end' { + $child = [regex]::Match($script:StartText, "(?s)\`$child = @'\r?\n(.*?)\r?\n'@").Groups[1].Value + $child | Should -Not -BeNullOrEmpty + ($child -split "`r?`n")[0] | Should -BeExactly "[IO.File]::WriteAllText('__STARTED__','1')" + $child.IndexOf('__STARTED__', [StringComparison]::Ordinal) | Should -BeLessThan $child.IndexOf('Import-Module', [StringComparison]::Ordinal) + $script:StartText | Should -Match '\$child = \$child\.Replace\(''__STARTED__'',\$startedPath\.Replace\("''","''''"\)\)' + $script:StartText | Should -Match "foreach \(\`$leftover in @\(\`$progressPath,\`$connectedPath,\`$startedPath,\`$policyPath\)\)" + } + It 'runs a real child that cannot load the Exchange Online module: one start, the marker written by the child itself, the failure reported once, no warning and no second child' { + $counted = $script:ExoFunctions.Replace("`$exe = Join-Path `$PSHOME 'pwsh.exe'", "`$global:PraGate.L330DRuns++; `$exe = Join-Path `$PSHOME 'pwsh.exe'") + $counted | Should -Not -BeExactly $script:ExoFunctions + . ([scriptblock]::Create($counted)) + $script:PraExoWorker = { 'worker' } + $empty = Join-Path ([IO.Path]::GetTempPath()) ('praexo-empty-' + [guid]::NewGuid().ToString('N')) + $null = New-Item -ItemType Directory -Path $empty -Force + $before = $env:PSModulePath + $global:PraGate.L330DRuns = 0 + try { + $env:PSModulePath = $empty + $context = & $script:NewContext 'Auto' + $message = $null + try { $null = Invoke-PraExoSubprocess -Context $context -Operation 'Probe' -Params @{} -Permit $null -OnApplied $null -OnProgress $null 6>$null } catch { $message = $_.Exception.Message } + $message | Should -BeLike '*Exchange Online child process code=1*' + $global:PraGate.L330DRuns | Should -Be 1 + $context.Warnings | Should -Be 0 + @(Get-ChildItem -LiteralPath ([IO.Path]::GetTempPath()) -Filter 'praexo_*.started' -Force -ErrorAction SilentlyContinue).Count | Should -Be 0 + } + finally { $env:PSModulePath = $before; Remove-Item -LiteralPath $empty -Recurse -Force -ErrorAction SilentlyContinue; $global:PraGate.Remove('L330DRuns') } + } + It 'never starts the second time after a timeout, the state of a write being unknown' { + . ([scriptblock]::Create($script:ExoFunctions)) + Mock Get-PraExecutionPolicyState { [pscustomobject]@{ Effective = 'RemoteSigned'; Source = 'LocalMachine'; Enforced = $false } } + $script:PraExoWorker = { 'worker' } + Mock Invoke-PraExoChild { $global:PraGate.L330DModes.Add($Mode); [pscustomobject]@{ Out = ''; Err = ''; ExitCode = 0; TimedOut = $true } } + $context = & $script:NewContext 'Auto' + { Invoke-PraExoSubprocess -Context $context -Operation 'Probe' -Params @{} -Permit $null -OnApplied $null -OnProgress $null 6>$null } | Should -Throw '*Exchange Online timeout; write state unknown*' + ($global:PraGate.L330DModes -join ',') | Should -BeExactly 'Stdin' + } + It 'follows Exo.ChildStart in any letter case: Stdin alone, File alone, and no second start after a failure of the only start (: )' -ForEach @( + @{ Start = 'stdin'; Expected = 'Stdin' } + @{ Start = 'STDIN'; Expected = 'Stdin' } + @{ Start = 'file'; Expected = 'File' } + @{ Start = 'FILE'; Expected = 'File' } + ) { + . ([scriptblock]::Create($script:ExoFunctions)) + Mock Get-PraExecutionPolicyState { [pscustomobject]@{ Effective = 'RemoteSigned'; Source = 'LocalMachine'; Enforced = $false } } + $script:PraExoWorker = { 'worker' } + Mock Invoke-PraExoChild { $global:PraGate.L330DModes.Add($Mode); [pscustomobject]@{ Out = ''; Err = 'failed'; ExitCode = 1; TimedOut = $false } } + $context = & $script:NewContext $Start + { Invoke-PraExoSubprocess -Context $context -Operation 'Probe' -Params @{} -Permit $null -OnApplied $null -OnProgress $null 6>$null } | Should -Throw '*child process code=1*' + ($global:PraGate.L330DModes -join ',') | Should -BeExactly $Expected + $context.Warnings | Should -Be 0 + } +} + +Describe 'Release 3.3.0 - protection of the files at rest: the envelope, the three keys, the refusals (production Common module, synthetic files)' -Tag 'Release330E' { + BeforeAll { + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global + Register-PraTestProxy PRA.Common 'Read-PraFileByte', 'Get-PraProtectedInfo', 'Get-PraProtectedClearLength', 'Get-PraContentSha256', 'Read-PraProtectedStream' + $script:E330Root = Join-Path $global:PraGate.Root ('prot-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) + $null = New-Item -ItemType Directory -Path $script:E330Root -Force + $script:E330Certificates = New-Object 'Collections.Generic.List[object]' + function script:New-E330Path([string]$Extension = '.json') { Join-Path $script:E330Root ([guid]::NewGuid().ToString('N').Substring(0, 8) + $Extension) } + function script:New-E330Secret([string]$Text) { $secure = New-Object Security.SecureString; foreach ($character in $Text.ToCharArray()) { $secure.AppendChar($character) }; $secure.MakeReadOnly(); $secure } + function script:Use-E330Culture { + param([string]$Name, [scriptblock]$Do) + $old = [Globalization.CultureInfo]::CurrentCulture; $oldUi = [Globalization.CultureInfo]::CurrentUICulture + try { [Globalization.CultureInfo]::CurrentCulture = [Globalization.CultureInfo]::GetCultureInfo($Name); [Globalization.CultureInfo]::CurrentUICulture = [Globalization.CultureInfo]::GetCultureInfo($Name); & $Do } + finally { [Globalization.CultureInfo]::CurrentCulture = $old; [Globalization.CultureInfo]::CurrentUICulture = $oldUi } + } + function script:New-E330Certificate { + param([string]$Name, [switch]$Ecdsa, [switch]$PublicOnly, [switch]$Exportable) + $hash = [Security.Cryptography.HashAlgorithmName]::SHA256 + if ($Ecdsa) { $key = [Security.Cryptography.ECDsa]::Create([Security.Cryptography.ECCurve]::CreateFromFriendlyName('nistP256')); $request = [Security.Cryptography.X509Certificates.CertificateRequest]::new('CN=' + $Name, $key, $hash) } + else { $key = [Security.Cryptography.RSA]::Create(2048); $request = [Security.Cryptography.X509Certificates.CertificateRequest]::new('CN=' + $Name, $key, $hash, [Security.Cryptography.RSASignaturePadding]::Pkcs1) } + $made = $request.CreateSelfSigned([DateTimeOffset]::UtcNow.AddDays(-1), [DateTimeOffset]::UtcNow.AddDays(30)) + $password = [guid]::NewGuid().ToString('N') + $flags = [Security.Cryptography.X509Certificates.X509KeyStorageFlags]::PersistKeySet -bor [Security.Cryptography.X509Certificates.X509KeyStorageFlags]::UserKeySet + if ($Exportable) { $flags = $flags -bor [Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable } + $stored = if ($PublicOnly) { [Security.Cryptography.X509Certificates.X509Certificate2]::new($made.Export([Security.Cryptography.X509Certificates.X509ContentType]::Cert)) } + else { [Security.Cryptography.X509Certificates.X509Certificate2]::new($made.Export([Security.Cryptography.X509Certificates.X509ContentType]::Pfx, $password), $password, $flags) } + $store = [Security.Cryptography.X509Certificates.X509Store]::new('My', 'CurrentUser') + try { $store.Open([Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite); $store.Add($stored) } finally { $store.Dispose() } + $script:E330Certificates.Add($stored) + $made.Dispose(); $key.Dispose() + $stored + } + function script:Add-E330PublicCopy($Certificate, [string]$StoreName) { + $copy = [Security.Cryptography.X509Certificates.X509Certificate2]::new($Certificate.Export([Security.Cryptography.X509Certificates.X509ContentType]::Cert)) + $store = [Security.Cryptography.X509Certificates.X509Store]::new($StoreName, 'CurrentUser') + try { $store.Open([Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite); $store.Add($copy) } finally { $store.Dispose() } + $script:E330Certificates.Add($copy) + $copy + } + function script:Remove-E330Certificate($Certificate, [string]$StoreName = 'My') { + $store = [Security.Cryptography.X509Certificates.X509Store]::new($StoreName, 'CurrentUser') + try { $store.Open([Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite); $store.Remove($Certificate) } finally { $store.Dispose() } + } + function script:Set-E330Byte([string]$Path, [int]$FromEnd) { $bytes = [IO.File]::ReadAllBytes($Path); $bytes[$bytes.Length - $FromEnd] = $bytes[$bytes.Length - $FromEnd] -bxor 1; [IO.File]::WriteAllBytes($Path, $bytes) } + $script:E330Text = ('{"Records":[{"SamAccountName":"contoso-user","proxyAddresses":["smtp:user@contoso.invalid"]}],"Note":"' + ('synthetic ' * 30) + '"}') + } + AfterAll { + Disable-PraProtection + foreach ($certificate in $script:E330Certificates) { + try { + $private = [Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($certificate) + foreach ($storeName in 'My', 'TrustedPeople') { try { Remove-E330Certificate $certificate $storeName } catch { $null = $_ } } + if ($private -is [Security.Cryptography.RSACng]) { try { $private.Key.Delete() } catch { $null = $_ } } + } catch { $null = $_ } + } + } + AfterEach { Disable-PraProtection } + It 'protects a file with a passphrase and reads it back: the clear text is not in the file, another passphrase, none, a changed byte and a cut file are refused, each message names the file ()' -ForEach @(@{ Culture = 'en-US' }, @{ Culture = 'fr-FR' }) { + Use-E330Culture $Culture { + $path = New-E330Path + Enable-PraProtection (New-PraProtection -Mode 'pAsSpHrAsE' -Passphrase (New-E330Secret 'Correct Horse Battery')) + Test-PraProtectionOn | Should -BeTrue + Write-PraProtectedFile -Path $path -Content ([Text.Encoding]::UTF8.GetBytes($script:E330Text)) + Test-PraProtectedFile -Path $path | Should -BeTrue + [Text.Encoding]::UTF8.GetString([IO.File]::ReadAllBytes($path)) | Should -Not -Match 'contoso-user' + Read-PraFileText -Path $path | Should -BeExactly $script:E330Text + (Get-PraProtectedInfo -Path $path).Mode | Should -BeExactly 'Passphrase' + Enable-PraProtection (New-PraProtection -Mode Off -Passphrase (New-E330Secret 'another passphrase')) + { Read-PraFileText -Path $path } | Should -Throw -ErrorId 'PraProtectedWrongKey' -ExpectedMessage ("*'" + (Split-Path $path -Leaf) + "'*passphrase*") + Enable-PraProtection (New-PraProtection -Mode Off) + { Read-PraFileText -Path $path } | Should -Throw -ErrorId 'PraProtectedNoKey' -ExpectedMessage ("*'" + (Split-Path $path -Leaf) + "'*protected*passphrase*") + Enable-PraProtection (New-PraProtection -Mode Off -Passphrase (New-E330Secret 'Correct Horse Battery')) + $changed = New-E330Path; Copy-Item -LiteralPath $path -Destination $changed; Set-E330Byte $changed 40 + { Read-PraFileText -Path $changed } | Should -Throw -ErrorId 'PraProtectedTampered' -ExpectedMessage ("*'" + (Split-Path $changed -Leaf) + "'*changed or damaged*") + $cut = New-E330Path; $bytes = [IO.File]::ReadAllBytes($path); [IO.File]::WriteAllBytes($cut, [byte[]]$bytes[0..($bytes.Length - 17)]) + { Read-PraFileText -Path $cut } | Should -Throw -ErrorId 'PraProtectedTampered' + Read-PraFileText -Path $path | Should -BeExactly $script:E330Text + } + } + It 'protects a file of several chunks, authenticates the header and the order of the chunks, and reads the clear content by length and by hash without the file ever being clear on disk' { + $path = New-E330Path '.clixml' + $content = New-Object byte[] (2621440 + 17) + (New-Object Random 7).NextBytes($content) + Enable-PraProtection (New-PraProtection -Mode Passphrase -Passphrase (New-E330Secret 'chunks')) + Write-PraProtectedFile -Path $path -Content $content + (Get-PraProtectedClearLength -Path $path) | Should -Be $content.Length + (Read-PraFileByte -Path $path).Length | Should -Be $content.Length + (Get-PraContentSha256 -Path $path) | Should -BeExactly ([Convert]::ToHexString([Security.Cryptography.SHA256]::HashData($content)).ToLowerInvariant()) + @(Get-ChildItem -LiteralPath $script:E330Root -Filter '*.tmp').Count | Should -Be 0 + $header = New-E330Path; $bytes = [IO.File]::ReadAllBytes($path); $bytes[20] = $bytes[20] -bxor 1; [IO.File]::WriteAllBytes($header, $bytes) + { Read-PraFileByte -Path $header } | Should -Throw -ErrorId 'PraProtectedWrongKey' -Because 'the nonce is part of the header: the key check no longer fits' + $swapped = New-E330Path + $chunk = 1048576 + 16; $headerLength = ([IO.File]::ReadAllBytes($path)).Length - (2621440 + 17) - 16 * 3 + $all = [IO.File]::ReadAllBytes($path) + $reordered = [byte[]]($all[0..($headerLength - 1)] + $all[($headerLength + $chunk)..($headerLength + 2 * $chunk - 1)] + $all[$headerLength..($headerLength + $chunk - 1)] + $all[($headerLength + 2 * $chunk)..($all.Length - 1)]) + [IO.File]::WriteAllBytes($swapped, $reordered) + { Read-PraFileByte -Path $swapped } | Should -Throw -ErrorId 'PraProtectedTampered' + $dropped = New-E330Path; [IO.File]::WriteAllBytes($dropped, [byte[]]$all[0..($headerLength + $chunk - 1)]) + { Read-PraFileByte -Path $dropped } | Should -Throw -ErrorId 'PraProtectedTampered' -Because 'the first chunk is no longer the last one' + } + It 'reads a clear file as it always did, a protected one the same way, never overwrites, and an empty protected file reads as empty' { + $clear = New-E330Path + [IO.File]::WriteAllText($clear, $script:E330Text, (New-Object Text.UTF8Encoding($true))) + Read-PraFileText -Path $clear | Should -BeExactly $script:E330Text + Test-PraProtectedFile -Path $clear | Should -BeFalse + (Read-PraFileHead -Path $clear -Length 15) | Should -BeExactly $script:E330Text.Substring(0, 12) + Enable-PraProtection (New-PraProtection -Mode Passphrase -Passphrase (New-E330Secret 'same')) + $protected = New-E330Path + Write-PraProtectedFile -Path $protected -Content ([Text.Encoding]::UTF8.GetBytes($script:E330Text)) + (Read-PraFileHead -Path $protected -Length 12) | Should -BeExactly $script:E330Text.Substring(0, 12) + { Write-PraProtectedFile -Path $protected -Content ([byte[]](1, 2, 3)) } | Should -Throw '*already exists*' + { Write-PraProtectedFile -Path $clear -Content ([byte[]](1, 2, 3)) } | Should -Throw '*already exists*' + Read-PraFileText -Path $clear | Should -BeExactly $script:E330Text + $empty = New-E330Path + Write-PraProtectedFile -Path $empty -Content ([byte[]]@()) + Test-PraProtectedFile -Path $empty | Should -BeTrue + (Read-PraFileByte -Path $empty).Length | Should -Be 0 + (Get-PraProtectedClearLength -Path $empty) | Should -Be 0 + $stream = Open-PraContentStream -Path $protected + try { (New-Object IO.StreamReader($stream)).ReadToEnd() | Should -BeExactly $script:E330Text } finally { $stream.Dispose() } + } + It 'protects with a key file made by New-PraAuthKeyFile, refuses another key file and none, and names the key file as the need' { + $keyFile = New-E330Path '.key'; $null = New-PraAuthKeyFile -Path $keyFile + $other = New-E330Path '.key'; $null = New-PraAuthKeyFile -Path $other + $path = New-E330Path + Enable-PraProtection (New-PraProtection -Mode Passphrase -KeyFile $keyFile) + Get-PraProtectionLabel | Should -Match 'key file' + (Test-PraProtectionKey).Ready | Should -BeTrue + Write-PraProtectedFile -Path $path -Content ([Text.Encoding]::UTF8.GetBytes($script:E330Text)) + (Get-PraProtectedInfo -Path $path).Mode | Should -BeExactly 'KeyFile' + Read-PraFileText -Path $path | Should -BeExactly $script:E330Text + [IO.File]::ReadAllText($keyFile).Trim() | Should -Not -BeNullOrEmpty + Enable-PraProtection (New-PraProtection -Mode Off -KeyFile $other) + { Read-PraFileText -Path $path } | Should -Throw -ErrorId 'PraProtectedWrongKey' -ExpectedMessage '*key file*' + Enable-PraProtection (New-PraProtection -Mode Off) + { Read-PraFileText -Path $path } | Should -Throw -ErrorId 'PraProtectedNoKey' -ExpectedMessage '*Storage.KeyFile*' + Enable-PraProtection (New-PraProtection -Mode Passphrase -KeyFile (New-E330Path '.key')) + (Test-PraProtectionKey).Ready | Should -BeFalse + (Test-PraProtectionKey).Reason | Should -Match 'Storage.KeyFile cannot be used' + } + It 'protects with a certificate: a random key per file wrapped with RSA-OAEP, the certificate found by the thumbprint of the header, refusals for a missing certificate, an EC key and a certificate without its private key ()' -ForEach @(@{ Culture = 'en-US' }, @{ Culture = 'fr-FR' }) { + Use-E330Culture $Culture { + $certificate = New-E330Certificate ('pra-e330-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) + $path = New-E330Path; $second = New-E330Path + Enable-PraProtection (New-PraProtection -Mode 'cErTiFiCaTe' -CertificateThumbprint ($certificate.Thumbprint.ToLowerInvariant() -replace '(..)', '$1 ').Trim()) + Get-PraProtectionLabel | Should -BeExactly ('certificate ' + $certificate.Thumbprint) + (Test-PraProtectionKey).Ready | Should -BeTrue + Write-PraProtectedFile -Path $path -Content ([Text.Encoding]::UTF8.GetBytes($script:E330Text)) + Write-PraProtectedFile -Path $second -Content ([Text.Encoding]::UTF8.GetBytes($script:E330Text)) + [Convert]::ToBase64String([IO.File]::ReadAllBytes($path)) | Should -Not -BeExactly ([Convert]::ToBase64String([IO.File]::ReadAllBytes($second))) -Because 'each file has its own key and nonce' + $info = Get-PraProtectedInfo -Path $path + $info.Mode | Should -BeExactly 'Certificate' + $info.KeyId | Should -BeExactly $certificate.Thumbprint + Enable-PraProtection (New-PraProtection -Mode Off) + Read-PraFileText -Path $path | Should -BeExactly $script:E330Text -Because 'the certificate is found by the thumbprint of the header, whatever the settings say' + Set-E330Byte $second 30 + { Read-PraFileText -Path $second } | Should -Throw -ErrorId 'PraProtectedTampered' + $headerChanged = New-E330Path; $bytes = [IO.File]::ReadAllBytes($path); $bytes[60] = $bytes[60] -bxor 1; [IO.File]::WriteAllBytes($headerChanged, $bytes) + { Read-PraFileText -Path $headerChanged } | Should -Throw -ErrorId 'PraProtectedWrongKey' -ExpectedMessage ('*' + $certificate.Thumbprint + '*') + Remove-E330Certificate $certificate + { Read-PraFileText -Path $path } | Should -Throw -ErrorId 'PraProtectedNoKey' -ExpectedMessage ("*'" + (Split-Path $path -Leaf) + "'*" + $certificate.Thumbprint + '*') + Enable-PraProtection (New-PraProtection -Mode Certificate -CertificateThumbprint $certificate.Thumbprint) + (Test-PraProtectionKey).Ready | Should -BeFalse + (Test-PraProtectionKey).Reason | Should -Match 'is not in CurrentUser\\My or LocalMachine\\My' + { Write-PraProtectedFile -Path (New-E330Path) -Content ([byte[]](1)) } | Should -Throw -ErrorId 'PraProtectionNotReady' + @(Get-ChildItem -LiteralPath $script:E330Root -Filter '*.tmp').Count | Should -Be 0 -Because 'a refused write leaves no partial file' + } + } + It 'refuses a certificate that has no RSA key and a certificate without its private key, with a clear message' { + $ec = New-E330Certificate ('pra-e330-ec-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) -Ecdsa + Enable-PraProtection (New-PraProtection -Mode Certificate -CertificateThumbprint $ec.Thumbprint) + $answer = Test-PraProtectionKey + $answer.Ready | Should -BeFalse + $answer.Reason | Should -Match 'has no RSA key' + { Write-PraProtectedFile -Path (New-E330Path) -Content ([byte[]](1)) } | Should -Throw -ErrorId 'PraProtectionNotReady' -ExpectedMessage '*has no RSA key*' + $public = New-E330Certificate ('pra-e330-pub-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) -PublicOnly + Enable-PraProtection (New-PraProtection -Mode Certificate -CertificateThumbprint $public.Thumbprint) + (Test-PraProtectionKey).Ready | Should -BeFalse + (Test-PraProtectionKey).Reason | Should -Match 'no private key' + $withKey = New-E330Certificate ('pra-e330-rsa-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) + Enable-PraProtection (New-PraProtection -Mode Certificate -CertificateThumbprint $withKey.Thumbprint) + $path = New-E330Path + Write-PraProtectedFile -Path $path -Content ([byte[]](1, 2, 3)) + Remove-E330Certificate $withKey + $publicCopy = [Security.Cryptography.X509Certificates.X509Certificate2]::new($withKey.Export([Security.Cryptography.X509Certificates.X509ContentType]::Cert)) + $store = [Security.Cryptography.X509Certificates.X509Store]::new('My', 'CurrentUser') + try { $store.Open([Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite); $store.Add($publicCopy) } finally { $store.Dispose() } + $script:E330Certificates.Add($publicCopy) + { Read-PraFileByte -Path $path } | Should -Throw -ErrorId 'PraProtectedNoKey' -ExpectedMessage '*has no private key*' + } + It 'keeps no key after use: disabling the protection clears the keys derived from a passphrase, and a write that fails leaves no temporary file' { + Enable-PraProtection (New-PraProtection -Mode Passphrase -Passphrase (New-E330Secret 'cached')) + $path = New-E330Path + Write-PraProtectedFile -Path $path -Content ([byte[]](1, 2, 3)) + $cache = & (Get-Module PRA.Common) { $script:PraProtectionKeys } + $cache.Count | Should -BeGreaterThan 0 + $kept = @($cache.Values)[0] + Disable-PraProtection + $cache.Count | Should -Be 0 + (@($kept | Where-Object { $_ -ne 0 }).Count) | Should -Be 0 -Because 'the bytes of the key are cleared' + Get-PraProtection | Should -BeNullOrEmpty + Enable-PraProtection (New-PraProtection -Mode Passphrase -Passphrase (New-E330Secret 'cached')) + { Write-PraProtectedFile -Path (Join-Path $script:E330Root 'no-folder\file.json') -Content ([byte[]](1)) } | Should -Throw + @(Get-ChildItem -LiteralPath $script:E330Root -Recurse -Filter '*.tmp').Count | Should -Be 0 + } + It 'finds the certificate that has a private key this account can use, even when a public-only copy of it comes first in the places searched' { + $certificate = New-E330Certificate ('pra-e330-dup-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) + $null = Add-E330PublicCopy $certificate 'TrustedPeople' + $module = Get-Module PRA.Common + $original = & $module { , $script:PraProtectionStores } + try { + & $module { $script:PraProtectionStores = @(@('CurrentUser', 'TrustedPeople'), @('CurrentUser', 'My')) } + $found = & $module { param($thumbprint) Find-PraProtectionCertificate -Thumbprint $thumbprint } $certificate.Thumbprint + try { + $found.HasPrivateKey | Should -BeTrue + $private = [Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($found) + $private | Should -Not -BeNullOrEmpty + $private.Dispose() + } + finally { $found.Dispose() } + Enable-PraProtection (New-PraProtection -Mode 'Certificate' -CertificateThumbprint $certificate.Thumbprint) + (Test-PraProtectionKey).Ready | Should -BeTrue + $path = New-E330Path + Write-PraProtectedFile -Path $path -Content ([Text.Encoding]::UTF8.GetBytes($script:E330Text)) + Read-PraFileText -Path $path | Should -BeExactly $script:E330Text + & $module { $script:PraProtectionStores = @(, @('CurrentUser', 'TrustedPeople')) } + $publicOnly = & $module { param($thumbprint) Find-PraProtectionCertificate -Thumbprint $thumbprint } $certificate.Thumbprint + try { $publicOnly.HasPrivateKey | Should -BeFalse -Because 'when only the public copy is there, it is what is found' } finally { $publicOnly.Dispose() } + } + finally { & $module { param($places) $script:PraProtectionStores = $places } $original } + } + It 'proves the certificate by wrapping and unwrapping a value, warns once when its private key cannot be exported (the backups are lost with the key), and says nothing of the kind when it can be ()' -ForEach @(@{ Culture = 'en-US' }, @{ Culture = 'fr-FR' }) { + Use-E330Culture $Culture { + $locked = New-E330Certificate ('pra-e330-locked-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) + Enable-PraProtection (New-PraProtection -Mode Certificate -CertificateThumbprint $locked.Thumbprint) + $answer = Test-PraProtectionKey + $answer.Ready | Should -BeTrue + @($answer.Warnings).Count | Should -Be 1 + $answer.Warnings[0] | Should -Match 'cannot be exported' + $answer.Warnings[0] | Should -Match 'New-SelfSignedCertificate .*-KeyExportPolicy Exportable' + $answer.Warnings[0] | Should -Match 'Export-PfxCertificate' + $answer.Warnings[0] | Should -Match $locked.Thumbprint + $open = New-E330Certificate ('pra-e330-open-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) -Exportable + Enable-PraProtection (New-PraProtection -Mode Certificate -CertificateThumbprint $open.Thumbprint) + $good = Test-PraProtectionKey + $good.Ready | Should -BeTrue + @($good.Warnings).Count | Should -Be 0 + $gone = New-E330Certificate ('pra-e330-gone-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) + $key = [Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($gone) + if ($key -is [Security.Cryptography.RSACng]) { + $key.Key.Delete() + Enable-PraProtection (New-PraProtection -Mode Certificate -CertificateThumbprint $gone.Thumbprint) + $broken = Test-PraProtectionKey + $broken.Ready | Should -BeFalse -Because 'the certificate is in the store but its key is gone: a value wrapped for it could not be opened' + $broken.Reason | Should -Not -BeNullOrEmpty + } + } + } + It 'keeps the key material that worked for the run, so a key file or a certificate that goes away later does not stop a write, and forgets it when the protection is disabled' { + $keyFile = New-E330Path '.key'; $null = New-PraAuthKeyFile -Path $keyFile + Enable-PraProtection (New-PraProtection -Mode Passphrase -KeyFile $keyFile) + (Test-PraProtectionKey).Ready | Should -BeTrue + Remove-Item -LiteralPath $keyFile -Force + $path = New-E330Path + Write-PraProtectedFile -Path $path -Content ([Text.Encoding]::UTF8.GetBytes($script:E330Text)) + Read-PraFileText -Path $path | Should -BeExactly $script:E330Text + Disable-PraProtection + Enable-PraProtection (New-PraProtection -Mode Passphrase -KeyFile $keyFile) + { Write-PraProtectedFile -Path (New-E330Path) -Content ([byte[]](1, 2, 3)) } | Should -Throw '*was not found*' + $certificate = New-E330Certificate ('pra-e330-kept-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) + Enable-PraProtection (New-PraProtection -Mode Certificate -CertificateThumbprint $certificate.Thumbprint) + (Test-PraProtectionKey).Ready | Should -BeTrue + Remove-E330Certificate $certificate + $second = New-E330Path + Write-PraProtectedFile -Path $second -Content ([Text.Encoding]::UTF8.GetBytes($script:E330Text)) + Read-PraFileText -Path $second | Should -BeExactly $script:E330Text -Because 'the certificate that Test-PraProtectionKey found stays in use for the run' + Disable-PraProtection + { Write-PraProtectedFile -Path (New-E330Path) -Content ([byte[]](1)) } | Should -Throw -ErrorId 'PraProtectionNotReady' + Enable-PraProtection (New-PraProtection -Mode Certificate -CertificateThumbprint $certificate.Thumbprint) + { Read-PraFileText -Path $second } | Should -Throw -ErrorId 'PraProtectedNoKey' -Because 'once the protection is disabled the certificate is not kept' + } + It 'reads the start of a protected file by decrypting only the first chunks: a damaged later chunk does not stop it, a damaged first chunk does' { + $path = New-E330Path '.json' + $content = New-Object byte[] (2621440 + 17) + [Text.Encoding]::ASCII.GetBytes('{"Operation":"Recover","BatchId":"abc"}').CopyTo($content, 0) + Enable-PraProtection (New-PraProtection -Mode Passphrase -Passphrase (New-E330Secret 'head')) + Write-PraProtectedFile -Path $path -Content $content + (Read-PraFileHead -Path $path -Length 100).Substring(0, 39) | Should -BeExactly '{"Operation":"Recover","BatchId":"abc"}' + (Read-PraFileHead -Path $path -Length 100).Length | Should -Be 100 + $later = New-E330Path; Copy-Item -LiteralPath $path -Destination $later; Set-E330Byte $later 40 + (Read-PraFileHead -Path $later -Length 100).Length | Should -Be 100 + { Read-PraFileByte -Path $later } | Should -Throw -ErrorId 'PraProtectedTampered' + $first = New-E330Path; $bytes = [IO.File]::ReadAllBytes($path); $bytes[100] = $bytes[100] -bxor 1; [IO.File]::WriteAllBytes($first, $bytes) + { Read-PraFileHead -Path $first -Length 100 } | Should -Throw -ErrorId 'PraProtectedTampered' + (Read-PraFileHead -Path $path -Length 1500000).Length | Should -Be 1500000 -Because 'a length that spans two chunks reads both' + } + It 'derives the key of the chunks and the key of the key check separately (HKDF with its own label), for a key file, a passphrase and the data key of a certificate' { + $keyFile = New-E330Path '.key'; $null = New-PraAuthKeyFile -Path $keyFile + Enable-PraProtection (New-PraProtection -Mode Passphrase -KeyFile $keyFile) + $path = New-E330Path + Write-PraProtectedFile -Path $path -Content ([Text.Encoding]::UTF8.GetBytes($script:E330Text)) + $bytes = [IO.File]::ReadAllBytes($path) + $facts = & (Get-Module PRA.Common) { + param($file, $header) + $material = Read-PraAuthKeyFile -Path $file + $salt = [byte[]]$header[26..41]; $nonce = [byte[]]$header[13..24]; $stored = [Convert]::ToBase64String([byte[]]$header[42..49]) + $data = Get-PraProtectedSubKey -Master $material -Salt $salt -Purpose Data + $check = Get-PraProtectedSubKey -Master $material -Salt $salt -Purpose Check + $again = Get-PraProtectedSubKey -Master $material -Salt $salt -Purpose Data + $other = Get-PraProtectedSubKey -Master ([byte[]](1..32)) -Salt $salt -Purpose Data + [pscustomobject]@{ + Different = ([Convert]::ToBase64String($data) -ne [Convert]::ToBase64String($check)); Stable = ([Convert]::ToBase64String($data) -eq [Convert]::ToBase64String($again)); OtherMaster = ([Convert]::ToBase64String($data) -ne [Convert]::ToBase64String($other)) + ByCheckKey = ([Convert]::ToBase64String((Get-PraProtectedKeyCheck -Key $check -Nonce $nonce)) -eq $stored); ByDataKey = ([Convert]::ToBase64String((Get-PraProtectedKeyCheck -Key $data -Nonce $nonce)) -eq $stored) + } + } $keyFile $bytes + $facts.Different | Should -BeTrue + $facts.Stable | Should -BeTrue + $facts.OtherMaster | Should -BeTrue + $facts.ByCheckKey | Should -BeTrue -Because 'the key check of the file is made with the key of its own purpose' + $facts.ByDataKey | Should -BeFalse -Because 'the key that encrypts the chunks is never the key of the key check' + Enable-PraProtection (New-PraProtection -Mode Off -KeyFile $keyFile) + Read-PraFileText -Path $path | Should -BeExactly $script:E330Text + } + It 'accepts the settings in any letter case, resolves the key file, refuses what cannot work, and keeps the shipped file equal to the defaults' { + $make = { param($body) $path = Join-Path $global:PraGate.Root ('cfg-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.psd1'); [IO.File]::WriteAllText($path, "@{ Environment='SYNTHETIC'; Scope=@{Mode='Auto'}; Licensing=@{Enabled=`$false}; $body }", (New-Object Text.UTF8Encoding($true))); $path } + $plain = Import-PraConfiguration -Path (& $make '') -Root $global:PraGate.Source -DeferScopeCheck + $plain.Storage.Protect | Should -BeExactly 'Off' + $plain.Storage.CertificateThumbprint | Should -BeExactly '' + $plain.Storage.KeyFile | Should -BeExactly '' + $plain.Cleanup.OlderThanDays | Should -Be 90 + $thumbprint = 'ab' * 20 + $config = Import-PraConfiguration -Path (& $make "Storage=@{Protect='cErTiFiCaTe';CertificateThumbprint='$(($thumbprint -replace '(.{4})', '$1 ').Trim())'}; Cleanup=@{OlderThanDays=30}") -Root $global:PraGate.Source -DeferScopeCheck + $config.Storage.Protect | Should -BeExactly 'Certificate' + $config.Storage.CertificateThumbprint | Should -BeExactly $thumbprint.ToUpperInvariant() + $config.Cleanup.OlderThanDays | Should -Be 30 + $marked = Import-PraConfiguration -Path (& $make "Storage=@{Protect='certificate';CertificateThumbprint='$([char]0x200E)$thumbprint$([char]0x200F)'}") -Root $global:PraGate.Source -DeferScopeCheck + $marked.Storage.CertificateThumbprint | Should -BeExactly $thumbprint.ToUpperInvariant() -Because 'the invisible marks of a thumbprint copied from the certificate window are dropped' + (Import-PraConfiguration -Path (& $make "Storage=@{Protect='PASSPHRASE';KeyFile='keys\pra.key'}") -Root $global:PraGate.Source -DeferScopeCheck).Storage.KeyFile | Should -BeExactly (Join-Path $global:PraGate.Source 'keys\pra.key') + (Import-PraConfiguration -Path (& $make "Storage=@{Protect='off'}") -Root $global:PraGate.Source -DeferScopeCheck).Storage.Protect | Should -BeExactly 'Off' + { Import-PraConfiguration -Path (& $make "Storage=@{Protect='Aes'}") -Root $global:PraGate.Source -DeferScopeCheck } | Should -Throw '*Storage.Protect must be Off, Certificate or Passphrase*' + { Import-PraConfiguration -Path (& $make "Storage=@{Protect='Certificate'}") -Root $global:PraGate.Source -DeferScopeCheck } | Should -Throw '*requires Storage.CertificateThumbprint*' + { Import-PraConfiguration -Path (& $make "Storage=@{CertificateThumbprint='not a thumbprint'}") -Root $global:PraGate.Source -DeferScopeCheck } | Should -Throw '*40 hexadecimal characters*' + { Import-PraConfiguration -Path (& $make "Storage=@{KeyFile=5}") -Root $global:PraGate.Source -DeferScopeCheck } | Should -Throw '*Storage.KeyFile must be text*' + { Import-PraConfiguration -Path (& $make "Cleanup=@{OlderThanDays=0}") -Root $global:PraGate.Source -DeferScopeCheck } | Should -Throw '*Cleanup.OlderThanDays must be between 1 and 3650*' + { Import-PraConfiguration -Path (& $make "Cleanup=@{Bogus=1}") -Root $global:PraGate.Source -DeferScopeCheck } | Should -Throw '*unknown setting Cleanup.Bogus*' + $shipped = Import-PowerShellDataFile -LiteralPath (Join-Path $global:PraGate.Source 'config\PraRemoteMailbox.config.psd1') + $shipped.Storage.Protect | Should -BeExactly 'Off' + $shipped.Storage.CertificateThumbprint | Should -BeExactly '' + $shipped.Storage.KeyFile | Should -BeExactly '' + $shipped.Cleanup.OlderThanDays | Should -Be 90 + $text = [IO.File]::ReadAllText((Join-Path $global:PraGate.Source 'config\PraRemoteMailbox.config.psd1')) + foreach ($name in 'Protect', 'CertificateThumbprint', 'KeyFile', 'OlderThanDays') { $text | Should -Match ('#\s+' + $name) -Because ('the file documents ' + $name) } + $text | Should -Match 'LOSING the backups' + } + It 'shows the mode in what this run will use and never a passphrase' { + $make = { param($body) $path = Join-Path $global:PraGate.Root ('cfg-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.psd1'); [IO.File]::WriteAllText($path, "@{ Environment='SYNTHETIC'; Scope=@{Mode='Auto'}; Licensing=@{Enabled=`$false}; $body }", (New-Object Text.UTF8Encoding($true))); $path } + $rows = { param($body) $config = Import-PraConfiguration -Path (& $make $body) -Root $global:PraGate.Source -DeferScopeCheck; @(& (Get-Module PRA.Common) { param($c) Get-PraRunSetting -Config $c } $config) | Where-Object Name -EQ 'Protection of the files at rest' } + (& $rows '').Value | Should -BeExactly 'off' + (& $rows "Storage=@{Protect='Certificate';CertificateThumbprint='$('cd' * 20)'}").Value | Should -BeExactly ('certificate ' + ('CD' * 20) + ' (AES-256-GCM)') + (& $rows "Storage=@{Protect='Passphrase'}").Value | Should -BeExactly 'typed passphrase (AES-256-GCM)' + (& $rows "Storage=@{Protect='Passphrase';KeyFile='D:\keys\pra.key'}").Value | Should -Match 'key file D:\\keys\\pra\.key' + } +} + +Describe 'Release 3.3.0 - protected phase data, protected transfer package, and the comparison with the originals when files are protected (production Common module, synthetic folders)' -Tag 'Release330E' { + BeforeAll { + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global + $script:E331Root = Join-Path $global:PraGate.Root ('protb-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) + $null = New-Item -ItemType Directory -Path $script:E331Root -Force + $script:E331Counter = 0 + function script:New-E331Work { $script:E331Counter++; $path = Join-Path $script:E331Root ('w' + $script:E331Counter); $null = New-Item -ItemType Directory -Path $path -Force; $path } + function script:New-E331Secret([string]$Text) { $secure = New-Object Security.SecureString; foreach ($character in $Text.ToCharArray()) { $secure.AppendChar($character) }; $secure.MakeReadOnly(); $secure } + function script:Use-E331Culture { + param([string]$Name, [scriptblock]$Do) + $old = [Globalization.CultureInfo]::CurrentCulture; $oldUi = [Globalization.CultureInfo]::CurrentUICulture + try { [Globalization.CultureInfo]::CurrentCulture = [Globalization.CultureInfo]::GetCultureInfo($Name); [Globalization.CultureInfo]::CurrentUICulture = [Globalization.CultureInfo]::GetCultureInfo($Name); & $Do } + finally { [Globalization.CultureInfo]::CurrentCulture = $old; [Globalization.CultureInfo]::CurrentUICulture = $oldUi } + } + function script:Get-E331Sha([string]$Path) { (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash.ToLowerInvariant() } + # A batch folder as the AD server keeps it: the backup (protected or not), its raw file, and the checksum file of the backup (the SHA-256 of the file as it is stored). + function script:New-E331Folder { + param([string]$Parent, [string]$Name, [string]$Json, [switch]$Protect, [string]$BatchId = 'cccccccc33333333cccccccc33333333') + $folder = Join-Path $Parent $Name + $null = New-Item -ItemType Directory -Path $folder -Force + $jsonBytes = [Text.Encoding]::UTF8.GetBytes('{"Operation":"Convert","BatchId":"' + $BatchId + '",' + $Json.TrimStart().Substring(1)) + $rawBytes = [byte[]](1..300 | ForEach-Object { [byte](($_ * 7) % 251) }) + if ($Protect) { Write-PraProtectedFile -Path (Join-Path $folder 'Convert-x.json') -Content $jsonBytes; Write-PraProtectedFile -Path (Join-Path $folder 'raw.clixml') -Content $rawBytes } + else { [IO.File]::WriteAllBytes((Join-Path $folder 'Convert-x.json'), $jsonBytes); [IO.File]::WriteAllBytes((Join-Path $folder 'raw.clixml'), $rawBytes) } + [IO.File]::WriteAllText((Join-Path $folder 'Convert-x.json.sha256'), (Get-E331Sha (Join-Path $folder 'Convert-x.json')), (New-Object Text.UTF8Encoding($false))) + $folder + } + function script:Get-E331Files { param([string]$Folder, [string]$Id = 'cccccccc33333333cccccccc33333333', [string[]]$Leaf = @('Convert-x.json', 'raw.clixml')) @($Leaf | ForEach-Object { [pscustomobject]@{ Path = (Join-Path $Folder $_); Role = 'Convert backup'; BatchId = $Id } }) } + } + AfterEach { Disable-PraProtection } + It 'writes the phase data and its events protected, hashes the file as it is stored, and reads it back with the key; without the key the report says which file and which key, and goes on ()' -ForEach @(@{ Culture = 'en-US' }, @{ Culture = 'fr-FR' }) { + Use-E331Culture $Culture { + $folder = Join-Path (New-E331Work) 'Batch-abcd1234ef' + $null = New-Item -ItemType Directory -Path $folder -Force + $context = @{ Root = $global:PraGate.Package; Version = '3.3.0'; RunId = ((Get-Date -Format 'yyyyMMdd_HHmmss') + '-' + [guid]::NewGuid().ToString('N')); StartTime = (Get-Date); Action = 'Convert'; Mode = 'Apply'; Phase = 'AD' + CurrentPhase = 'Start'; CurrentOperation = ''; CurrentIdentity = ''; StepIndex = 0; StepTotal = 0; Warnings = 0; Issues = (New-Object 'Collections.Generic.List[object]'); Rows = (New-Object 'Collections.Generic.List[object]') + Server = 'dc01.contoso.com'; Config = @{ Environment = 'GATE' }; AllowMutation = $true; BatchId = 'abcd1234'; LogFile = ''; NextSteps = @(); ExitCode = 0; ResultStatus = ''; CloudConnectFailed = $false } + $guid = [guid]::NewGuid().ToString() + $context.Rows.Add([pscustomobject]@{ ObjectGuid = $guid; SamAccountName = 'alice'; UserPrincipalName = 'alice@contoso.com'; Action = 'Convert'; IsShared = $false; ADApplied = $true; ADVerified = $true; BackupPath = ''; CloudStatus = 'N/A'; CloudDetail = ''; FinalStatus = 'Pending'; Detail = 'detail'; Warnings = ''; LastOperation = ''; GroupAction = '' + CloudMailbox = $null; CloudLicense = $null; PreserveCloudMailbox = $false; PreserveLicense = $false; DeprovisionConfirmed = $false; PermDetail = ''; PermMissing = @() }) + Register-PraObjectName $context $guid 'alice@contoso.com' + $context.CurrentIdentity = $guid + Write-PraStep -Context $context -Title 'Backup and Active Directory changes' | Out-Null + Write-PraItem -Context $context -Status Ok -Text 'backup written on the AD side' + Enable-PraProtection (New-PraProtection -Mode Passphrase -Passphrase (New-E331Secret 'phase passphrase')) + $file = Save-PraPhaseData -Context $context -Folder $folder + $events = Join-Path $folder (([IO.Path]::GetFileName($file)) -replace '^PhaseData-', 'PhaseEvents-' -replace '\.json\z', '.jsonl') + Test-PraProtectedFile -Path $file | Should -BeTrue + Test-PraProtectedFile -Path $events | Should -BeTrue + [IO.File]::ReadAllText($file + '.sha256').Trim() | Should -BeExactly (Get-E331Sha $file) -Because 'the checksum is over the bytes as they are stored' + [IO.File]::ReadAllText($events + '.sha256').Trim() | Should -BeExactly (Get-E331Sha $events) + [Text.Encoding]::UTF8.GetString([IO.File]::ReadAllBytes($events)) | Should -Not -Match 'backup written' + $read = Read-PraPhaseData -Folder @($folder) -Environment 'gate' + @($read.Problems).Count | Should -Be 0 -Because ($read.Problems -join ' | ') + @($read.Phases).Count | Should -Be 1 + $read.Phases[0].Phase.Action | Should -BeExactly 'Convert' + @(@($read.Phases[0].Objects)[0].Steps | Where-Object { $_.Text -eq 'backup written on the AD side' }).Count | Should -Be 1 + Enable-PraProtection (New-PraProtection -Mode Off) + $without = Read-PraPhaseData -Folder @($folder) -Environment 'gate' + @($without.Phases).Count | Should -Be 0 + @($without.Problems).Count | Should -Be 1 + $without.Problems[0] | Should -BeLike ('*' + [IO.Path]::GetFileName($file) + '*protected*passphrase*left out of the report*') + } + } + It 'protects the transfer package as a whole, hashes the stored bytes in the sidecar, reads it with the key, names the file and the key without it, and refuses a changed byte with or without a rewritten sidecar' { + $work = New-E331Work + $id = 'cccccccc33333333cccccccc33333333' + Enable-PraProtection (New-PraProtection -Mode Passphrase -Passphrase (New-E331Secret 'package passphrase')) + $folder = New-E331Folder $work "Batch-$id" '{"Items":["genuine"]}' -Protect + $outbox = Join-Path $work 'Outbox' + $package = New-PraTransferPackage -Kind Convert -Environment GATE -BatchId $id -Folders @($folder) -OutboxFolder $outbox -NextCommand 'next' -ToolVersion '3.3.0' + $package.Verified | Should -BeTrue + Test-PraProtectedFile -Path $package.Path | Should -BeTrue + [IO.File]::ReadAllText($package.Sidecar).Trim() | Should -BeExactly (Get-E331Sha $package.Path) + $package.Fingerprint | Should -BeExactly (Format-PraFingerprint (Get-E331Sha $package.Path)) + @(Get-ChildItem -LiteralPath $outbox -Filter '*.tmp').Count | Should -Be 0 + $info = Get-PraTransferPackage -Path $package.Path -Environment GATE + $info.Valid | Should -BeTrue -Because $info.Error + $info.Sha256 | Should -BeExactly (Get-E331Sha $package.Path) + $imported = Import-PraTransferPackage -Path $package.Path -BackupFolder (Join-Path $work 'Backups') -Environment GATE + Get-E331Sha (Join-Path $imported.Folders[0] 'Convert-x.json') | Should -BeExactly (Get-E331Sha (Join-Path $folder 'Convert-x.json')) -Because 'the files inside travel as they are stored' + Test-PraProtectedFile -Path (Join-Path $imported.Folders[0] 'Convert-x.json') | Should -BeTrue + Enable-PraProtection (New-PraProtection -Mode Off) + $blind = Get-PraTransferPackage -Path $package.Path -Environment GATE + $blind.Valid | Should -BeFalse + $blind.Error | Should -BeLike ('*' + $package.Name + '*protected*passphrase*') + Enable-PraProtection (New-PraProtection -Mode Passphrase -Passphrase (New-E331Secret 'package passphrase')) + $changed = Join-Path $work 'changed'; $null = New-Item -ItemType Directory -Path $changed + $copy = Join-Path $changed $package.Name; Copy-Item -LiteralPath $package.Path -Destination $copy; Copy-Item -LiteralPath $package.Sidecar -Destination ($copy + '.sha256') + $bytes = [IO.File]::ReadAllBytes($copy); $bytes[$bytes.Length - 40] = $bytes[$bytes.Length - 40] -bxor 1; [IO.File]::WriteAllBytes($copy, $bytes) + $byHash = Get-PraTransferPackage -Path $copy -Environment GATE + $byHash.Valid | Should -BeFalse + $byHash.Error | Should -Match 'does not match its \.sha256 file' -Because 'the stored bytes are hashed: no key is needed to see a changed file' + [IO.File]::WriteAllText(($copy + '.sha256'), (Get-E331Sha $copy), (New-Object Text.UTF8Encoding($false))) + $byTag = Get-PraTransferPackage -Path $copy -Environment GATE + $byTag.Valid | Should -BeFalse + $byTag.Error | Should -BeLike ('*' + $package.Name + '*changed or damaged*') + } + It 'still reads a clear package and clear files when the protection is on, and writes a clear package when it is off' { + $work = New-E331Work + $id = 'cccccccc33333333cccccccc33333333' + $folder = New-E331Folder $work "Batch-$id" '{"Items":["clear"]}' + $package = New-PraTransferPackage -Kind Convert -Environment GATE -BatchId $id -Folders @($folder) -OutboxFolder (Join-Path $work 'Outbox') -ToolVersion '3.3.0' + Test-PraProtectedFile -Path $package.Path | Should -BeFalse + Enable-PraProtection (New-PraProtection -Mode Passphrase -Passphrase (New-E331Secret 'on later')) + (Get-PraTransferPackage -Path $package.Path -Environment GATE).Valid | Should -BeTrue + Read-PraFileText -Path (Join-Path $folder 'Convert-x.json') | Should -Match '"Items":\["clear"\]' + } + It 'compares protected files with the originals by content: a copy, a file protected again, a clear file against a protected original and the reverse all match; a changed file differs ()' -ForEach @(@{ Culture = 'en-US' }, @{ Culture = 'fr-FR' }) { + Use-E331Culture $Culture { + $work = New-E331Work + Enable-PraProtection (New-PraProtection -Mode Passphrase -Passphrase (New-E331Secret 'originals')) + $backups = Join-Path $work 'Backups' + $original = New-E331Folder $backups 'Batch-cccccccc33333333cccccccc33333333' '{"Items":["genuine"]}' -Protect + $copy = Join-Path $work 'copy'; $null = New-Item -ItemType Directory -Path $copy + Copy-Item -Path (Join-Path $original '*') -Destination $copy + $same = Get-PraFinalizeOriginalComparison -File (Get-E331Files $copy) -BackupFolder $backups + $same.Status | Should -BeExactly 'Match' + @($same.Matched).Count | Should -Be 2 + $again = New-E331Folder (Join-Path $work 'again') 'Finalize-x' '{"Items":["genuine"]}' -Protect + Get-E331Sha (Join-Path $again 'Convert-x.json') | Should -Not -BeExactly (Get-E331Sha (Join-Path $original 'Convert-x.json')) -Because 'each protected file has its own nonce' + $reprotected = Get-PraFinalizeOriginalComparison -File (Get-E331Files $again) -BackupFolder $backups + $reprotected.Status | Should -BeExactly 'Match' -Because 'the same content under another envelope is the same file' + $clearCopy = New-E331Folder (Join-Path $work 'clear') 'Finalize-x' '{"Items":["genuine"]}' + (Get-PraFinalizeOriginalComparison -File (Get-E331Files $clearCopy) -BackupFolder $backups).Status | Should -BeExactly 'Match' -Because 'a clear file against a protected original' + Disable-PraProtection + $clearOriginals = Join-Path $work 'ClearBackups' + $null = New-E331Folder $clearOriginals 'Batch-cccccccc33333333cccccccc33333333' '{"Items":["genuine"]}' + Enable-PraProtection (New-PraProtection -Mode Passphrase -Passphrase (New-E331Secret 'originals')) + (Get-PraFinalizeOriginalComparison -File (Get-E331Files $again) -BackupFolder $clearOriginals).Status | Should -BeExactly 'Match' -Because 'a protected file against a clear original' + $forged = New-E331Folder (Join-Path $work 'forged') 'Finalize-x' '{"Items":["rewritten"]}' -Protect + $different = Get-PraFinalizeOriginalComparison -File (Get-E331Files $forged) -BackupFolder $backups + $different.Status | Should -BeExactly 'Different' + @($different.NotComparable).Count | Should -Be 0 + } + } + It 'reports a clear file that really differs as different even when another file of the folder cannot be decrypted, and as not comparable only when an original that cannot be decrypted could be its twin ()' -ForEach @(@{ Culture = 'en-US' }, @{ Culture = 'fr-FR' }) { + Use-E331Culture $Culture { + $work = New-E331Work + Enable-PraProtection (New-PraProtection -Mode Passphrase -Passphrase (New-E331Secret 'originals')) + $backups = Join-Path $work 'Backups' + $null = New-E331Folder $backups 'Batch-cccccccc33333333cccccccc33333333' '{"Items":["genuine"]}' -Protect + Enable-PraProtection (New-PraProtection -Mode Off) + $longer = New-E331Folder (Join-Path $work 'longer') 'Finalize-x' '{"Items":["rewritten by someone, and longer"]}' + $result = Get-PraFinalizeOriginalComparison -File (Get-E331Files $longer) -BackupFolder $backups + $result.Status | Should -BeExactly 'Different' + @($result.Different) | Should -Be @('Convert-x.json (Convert backup)') -Because 'no original of that length is unreadable: the file is not what was kept' + @($result.NotComparable) | Should -Be @('raw.clixml (Convert backup)') -Because 'the original of this one has the same length and cannot be decrypted' + $sameLength = New-E331Folder (Join-Path $work 'same') 'Finalize-x' '{"Items":["genuinx"]}' + $maybe = Get-PraFinalizeOriginalComparison -File (Get-E331Files $sameLength) -BackupFolder $backups + $maybe.Status | Should -BeExactly 'NotComparable' + @($maybe.Different).Count | Should -Be 0 + @($maybe.NotComparable).Count | Should -Be 2 + } + } + It 'the package helper of the window reads a protected package with the key of the configuration: valid with the key file, refused with a message that names the package without it' { + $work = New-E331Work + $keyFile = Join-Path $work 'pra.key'; $null = New-PraAuthKeyFile -Path $keyFile + $id = 'cccccccc33333333cccccccc33333333' + Enable-PraProtection (New-PraProtection -Mode Passphrase -KeyFile $keyFile) + $folder = New-E331Folder $work "Batch-$id" '{"Items":["genuine"]}' -Protect + $package = New-PraTransferPackage -Kind Convert -Environment GATE -BatchId $id -Folders @($folder) -OutboxFolder (Join-Path $work 'Outbox') -NextCommand 'next' -ToolVersion '3.3.0' + Disable-PraProtection + $helper = Join-Path $global:PraGate.Package 'module\PRA.Gui.Directory.ps1' + $run = { + param([string[]]$More, [string]$Name) + $result = Join-Path $work ($Name + '.json') + $arguments = @('-NoProfile', '-NonInteractive', '-File', $helper, '-ConfigPath', (Join-Path $work 'none.psd1'), '-ResultPath', $result, '-PackagePath', $package.Path, '-Environment', 'GATE') + $More + $info = New-Object Diagnostics.ProcessStartInfo + $info.FileName = Join-Path $PSHOME 'pwsh.exe' + $info.Arguments = ($arguments | ForEach-Object { '"' + $_ + '"' }) -join ' ' + $info.UseShellExecute = $false; $info.CreateNoWindow = $true; $info.RedirectStandardOutput = $true; $info.RedirectStandardError = $true + $process = [Diagnostics.Process]::Start($info) + try { + $out = $process.StandardOutput.ReadToEndAsync(); $err = $process.StandardError.ReadToEndAsync() + $process.WaitForExit(120000) | Should -BeTrue + $process.ExitCode | Should -Be 0 -Because ($out.Result + $err.Result) + } + finally { $process.Dispose() } + [IO.File]::ReadAllText($result) | ConvertFrom-Json -DateKind String + } + $blind = & $run @() 'blind' + $blind.Success | Should -BeTrue + $blind.Valid | Should -BeFalse + $blind.Error | Should -BeLike ('*' + $package.Name + '*protected*') + $keyed = & $run @('-ProtectMode', 'passphrase', '-ProtectKeyFile', $keyFile) 'keyed' + $keyed.Success | Should -BeTrue + $keyed.Valid | Should -BeTrue -Because $keyed.Error + $keyed.Kind | Should -BeExactly 'Convert' + $mixed = & $run @('-ProtectMode', 'OFF', '-ProtectKeyFile', $keyFile) 'off-with-key' + $mixed.Valid | Should -BeTrue -Because 'a protected file is read with the key file even when the protection of the run is off' + } + It 'says "not comparable" and never "different" when a protected file cannot be decrypted, on either side, and Transfer.RequireLocalOriginal refuses it with the key to give ()' -ForEach @(@{ Culture = 'en-US' }, @{ Culture = 'fr-FR' }) { + Use-E331Culture $Culture { + $work = New-E331Work + Enable-PraProtection (New-PraProtection -Mode Passphrase -Passphrase (New-E331Secret 'originals')) + $backups = Join-Path $work 'Backups' + $null = New-E331Folder $backups 'Batch-cccccccc33333333cccccccc33333333' '{"Items":["genuine"]}' -Protect + $again = New-E331Folder (Join-Path $work 'again') 'Finalize-x' '{"Items":["genuine"]}' -Protect + $clearCopy = New-E331Folder (Join-Path $work 'clear') 'Finalize-x' '{"Items":["genuine"]}' + Enable-PraProtection (New-PraProtection -Mode Off) + foreach ($loaded in @($again, $clearCopy)) { + $blind = Get-PraFinalizeOriginalComparison -File (Get-E331Files $loaded) -BackupFolder $backups + $blind.Status | Should -BeExactly 'NotComparable' + @($blind.Different).Count | Should -Be 0 + @($blind.NotComparable).Count | Should -BeGreaterThan 0 + $finding = Get-PraOriginalFinding -Comparison $blind + @($finding.Refusals).Count | Should -Be 0 + $finding.Warnings[0] | Should -Match 'cannot be compared with the originals kept on this server: a protected file cannot be read with the key of this run' + $finding.Warnings[0] | Should -Not -Match 'differ from the originals' + $strict = Get-PraOriginalFinding -Comparison $blind -RequireLocalOriginal + @($strict.Refusals).Count | Should -Be 1 + $strict.Refusals[0] | Should -Match 'Transfer\.RequireLocalOriginal is on:.*Nothing was restored' + } + $loadedProtected = Get-PraFinalizeOriginalComparison -File (Get-E331Files $again) -BackupFolder (Join-Path $work 'NoBackups') + $loadedProtected.Status | Should -BeExactly 'NoOriginal' -Because 'a server that holds no batch of that name has no original, whatever the key' + } + } +} + +Describe 'Release 3.3.0 - protected backups and AD proof through the production Directory and Backup modules (synthetic AD)' -Tag 'Release330E' { + BeforeEach { + $global:PraGate.Runtime = New-GateRuntime -Name 'protect-e' + $env:PRA_GATE_STATE = $global:PraGate.Runtime.StatePath + $env:PSModulePath = $global:PraGate.Runtime.Modules + ';' + (Join-Path $PSHOME 'Modules') + Import-Module ActiveDirectory -Force -Global + $global:PraGate.Context = New-GateContext $global:PraGate.Runtime + $global:PraGate.Context.LogFile = Join-Path $global:PraGate.Runtime.Root 'logs\unit.log' + $script:E332Secret = New-Object Security.SecureString; foreach ($character in 'backup passphrase'.ToCharArray()) { $script:E332Secret.AppendChar($character) }; $script:E332Secret.MakeReadOnly() + } + AfterEach { Disable-PraProtection } + It 'writes the backup, the raw capture and the AD proof protected, hashes what is stored, and a new run reads them with the key, names the file without it, and refuses a changed byte ()' -ForEach @(@{ Culture = 'en-US' }, @{ Culture = 'fr-FR' }) { + $old = [Globalization.CultureInfo]::CurrentCulture + try { + [Globalization.CultureInfo]::CurrentCulture = [Globalization.CultureInfo]::GetCultureInfo($Culture) + Enable-PraProtection (New-PraProtection -Mode pAsSpHrAsE -Passphrase $script:E332Secret) + $context = $global:PraGate.Context + $bundles = New-GateSourceBundles $context -ApplySnapshots + $folder = Split-Path $bundles.Source -Parent + $source = Import-PraBackup $context $bundles.Source + $rawPath = Join-Path $folder $source.Data.RawFile + foreach ($path in @($bundles.Source, $rawPath, $bundles.State)) { Test-PraProtectedFile -Path $path | Should -BeTrue -Because $path } + [IO.File]::ReadAllText($bundles.Source + '.sha256').Trim() | Should -BeExactly (Get-PraHash $bundles.Source) + [IO.File]::ReadAllText($bundles.State + '.sha256').Trim() | Should -BeExactly (Get-PraHash $bundles.State) + [Text.Encoding]::UTF8.GetString([IO.File]::ReadAllBytes($bundles.Source)) | Should -Not -Match 'SamAccountName' + [Text.Encoding]::UTF8.GetString([IO.File]::ReadAllBytes($rawPath)) | Should -Not -Match 'Objs' + $fresh = New-GateContext $global:PraGate.Runtime + $receipt = Import-PraBackup $fresh $bundles.Source + @($receipt.Data.Records).Count | Should -Be 2 + $proof = Import-PraProof $fresh $bundles.State $receipt 'Recover' + $proof.Data.Operation | Should -BeExactly 'Recover' + Enable-PraProtection (New-PraProtection -Mode Off) + $blind = New-GateContext $global:PraGate.Runtime + { Import-PraBackup $blind $bundles.Source } | Should -Throw -ExpectedMessage ("*'" + (Split-Path $bundles.Source -Leaf) + "'*protected*passphrase*") + Enable-PraProtection (New-PraProtection -Mode Passphrase -Passphrase $script:E332Secret) + $bytes = [IO.File]::ReadAllBytes($bundles.Source); $bytes[$bytes.Length - 30] = $bytes[$bytes.Length - 30] -bxor 1; [IO.File]::WriteAllBytes($bundles.Source, $bytes) + { Import-PraBackup (New-GateContext $global:PraGate.Runtime) $bundles.Source } | Should -Throw -ExpectedMessage '*changed or damaged*' + } + finally { [Globalization.CultureInfo]::CurrentCulture = $old } + } + It 'keeps loading a clear backup and a clear AD proof (schema 3) when the protection is on, and writes clear files when it is off' { + $context = $global:PraGate.Context + $bundles = New-GateSourceBundles $context -ApplySnapshots + foreach ($path in @($bundles.Source, $bundles.State)) { Test-PraProtectedFile -Path $path | Should -BeFalse } + Enable-PraProtection (New-PraProtection -Mode Passphrase -Passphrase $script:E332Secret) + $fresh = New-GateContext $global:PraGate.Runtime + $receipt = Import-PraBackup $fresh $bundles.Source + @($receipt.Data.Records).Count | Should -Be 2 + (Import-PraProof $fresh $bundles.State $receipt 'Recover').Data.Kind | Should -BeExactly 'ADVerified' + } +} + +Describe 'Release 3.3.0 - a search of the backup folder says once that it cannot read a protected file, instead of leaving it out silently (production Directory module, synthetic folders)' -Tag 'Release330E' { + BeforeAll { + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Directory.psm1') -Force -Global + $script:E335Root = Join-Path $global:PraGate.Root ('unread-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) + $null = New-Item -ItemType Directory -Path $script:E335Root -Force + function script:New-E335Secret([string]$Text) { $secure = New-Object Security.SecureString; foreach ($character in $Text.ToCharArray()) { $secure.AppendChar($character) }; $secure.MakeReadOnly(); $secure } + function script:Use-E335Culture { + param([string]$Name, [scriptblock]$Do) + $old = [Globalization.CultureInfo]::CurrentCulture; $oldUi = [Globalization.CultureInfo]::CurrentUICulture + try { [Globalization.CultureInfo]::CurrentCulture = [Globalization.CultureInfo]::GetCultureInfo($Name); [Globalization.CultureInfo]::CurrentUICulture = [Globalization.CultureInfo]::GetCultureInfo($Name); & $Do } + finally { [Globalization.CultureInfo]::CurrentCulture = $old; [Globalization.CultureInfo]::CurrentUICulture = $oldUi } + } + function script:Write-E335File([string]$Path, [string]$Text, [switch]$Protect) { + if ($Protect) { Write-PraProtectedFile -Path $Path -Content ([Text.Encoding]::UTF8.GetBytes($Text)) } + else { [IO.File]::WriteAllText($Path, $Text, (New-Object Text.UTF8Encoding($false))) } + } + } + AfterEach { Disable-PraProtection } + It 'warns once per file that is not readable with the current key (a proof, a Recover backup, a Convert backup), names it, and still finds what it can read ()' -ForEach @(@{ Culture = 'en-US' }, @{ Culture = 'fr-FR' }) { + Use-E335Culture $Culture { + $root = Join-Path $script:E335Root ([guid]::NewGuid().ToString('N').Substring(0, 6)); $null = New-Item -ItemType Directory -Path $root -Force + $hash = 'ab' * 32; $guid = '11111111-1111-1111-1111-111111111111' + $proofId = 'a1b2c3d4e5f60718293a4b5c6d7e8f90'; $stoppedId = 'b1b2c3d4e5f60718293a4b5c6d7e8f91'; $convertId = 'c1b2c3d4e5f60718293a4b5c6d7e8f92'; $clearId = 'd1b2c3d4e5f60718293a4b5c6d7e8f93' + foreach ($id in $proofId, $stoppedId, $convertId, $clearId) { $null = New-Item -ItemType Directory -Path (Join-Path $root ('Batch-' + $id)) -Force } + $stateText = { param($operation, $source) '{"SchemaVersion":2,"Operation":"' + $operation + '","Kind":"ADVerified","Environment":"SYNTHETIC_GATE","SourceBackupHash":"' + $source + '","BackupHash":"' + ('cd' * 32) + '","CreatedUtc":"2026-11-01T00:00:00.0000000Z","Records":[{"ObjectGuid":"' + $guid + '","Operation":"' + $operation + '","ADVerified":true}]}' } + Enable-PraProtection (New-PraProtection -Mode Passphrase -Passphrase (New-E335Secret 'unread')) + Write-E335File (Join-Path $root ('Batch-' + $proofId + '\State-' + $proofId + '.json')) (& $stateText 'Recover' $hash) -Protect + Write-E335File (Join-Path $root ('Batch-' + $stoppedId + '\Recover-SYNTHETIC_GATE-20261116_120000-b1b2c3d4.json')) ('{"SchemaVersion":3,"Operation":"Recover","BatchId":"' + $stoppedId + '","Environment":"SYNTHETIC_GATE","SourceBackupHash":"' + $hash + '","Records":[]}') -Protect + Write-E335File (Join-Path $root ('Batch-' + $convertId + '\State-' + $convertId + '.json')) (& $stateText 'Convert' '') + Write-E335File (Join-Path $root ('Batch-' + $convertId + '\Convert-SYNTHETIC_GATE-20261116_110000-c1b2c3d4.json')) ('{"SchemaVersion":3,"Operation":"Convert","BatchId":"' + $convertId + '","Environment":"SYNTHETIC_GATE","Records":[{"ObjectGuid":"' + $guid + '"}]}') -Protect + Disable-PraProtection + Enable-PraProtection (New-PraProtection -Mode Off) + $log = Join-Path $root 'run.log' + $found = InModuleScope PRA.Directory -Parameters @{ Root = $root; Log = $log; Hash = $hash; Guid = $guid } { + $context = @{ Config = @{ Environment = 'SYNTHETIC_GATE'; Storage = @{ BackupFolder = $Root } }; LogFile = $Log; VerboseEnabled = $false; Warnings = 0 } + $recover = Find-PraRecoverOfBatch $context $Hash @($Guid) + $afterFirst = [int]$context.Warnings + $converted = Find-PraConvertedBatches -Context $context -ObjectGuid @($Guid) + $afterSecond = [int]$context.Warnings + $null = Find-PraRecoverOfBatch $context $Hash @($Guid) + @{ Recover = $recover; Converted = $converted.Count; AfterFirst = $afterFirst; AfterSecond = $afterSecond; Warnings = [int]$context.Warnings } + } + $found.Recover | Should -BeNullOrEmpty + $found.Converted | Should -Be 0 + $found.AfterFirst | Should -Be 2 -Because 'the protected proof and the protected Recover backup, each named once' + $found.AfterSecond | Should -Be 3 -Because 'the protected Convert backup is a third file; the two files already named are not named again' + $found.Warnings | Should -Be 3 -Because 'a second search of the same folder says nothing more' + $lines = @([IO.File]::ReadAllLines($log) | Where-Object { $_ -like '*not readable with the current key*' }) + $lines.Count | Should -Be 3 + foreach ($leaf in ('State-' + $proofId + '.json'), 'Recover-SYNTHETIC_GATE-20261116_120000-b1b2c3d4.json', 'Convert-SYNTHETIC_GATE-20261116_110000-c1b2c3d4.json') { @($lines | Where-Object { $_.Contains($leaf) }).Count | Should -Be 1 -Because $leaf } + Write-E335File (Join-Path $root ('Batch-' + $clearId + '\State-' + $clearId + '.json')) (& $stateText 'Recover' $hash) + $withClear = InModuleScope PRA.Directory -Parameters @{ Root = $root; Log = $log; Hash = $hash; Guid = $guid } { + $context = @{ Config = @{ Environment = 'SYNTHETIC_GATE'; Storage = @{ BackupFolder = $Root } }; LogFile = $Log; VerboseEnabled = $false; Warnings = 0 } + Find-PraRecoverOfBatch $context $Hash @($Guid) + } + $withClear.BatchId | Should -BeExactly $clearId -Because 'a file that cannot be read does not hide a batch that can' + } + } +} + +Describe 'Release 3.3.0 - the effective-rights probe: what the Apply is likely to be refused, read from the security descriptor already in memory (production Directory module, synthetic AD)' -Tag 'Release330E' { + BeforeAll { + function script:New-E333Descriptor { + param([object[]]$Rule, [switch]$Protected) + Add-Type -AssemblyName System.DirectoryServices + $descriptor = New-Object DirectoryServices.ActiveDirectorySecurity + $descriptor.SetOwner((New-Object Security.Principal.SecurityIdentifier('S-1-5-18'))) + $descriptor.SetAccessRuleProtection([bool]$Protected, $false) + foreach ($item in $Rule) { + $type = if ($item.ContainsKey('Type')) { [guid]$item.Type } else { [guid]::Empty } + $inheritance = if ($item.ContainsKey('Inheritance')) { [DirectoryServices.ActiveDirectorySecurityInheritance]$item.Inheritance } else { [DirectoryServices.ActiveDirectorySecurityInheritance]::None } + [void]$descriptor.AddAccessRule((New-Object DirectoryServices.ActiveDirectoryAccessRule((New-Object Security.Principal.SecurityIdentifier([string]$item.Sid)), [DirectoryServices.ActiveDirectoryRights]$item.Rights, [Security.AccessControl.AccessControlType]$item.Access, $type, $inheritance))) + } + $descriptor + } + } + BeforeEach { + $global:PraGate.Runtime = New-GateRuntime -Name 'rights-e' -Extra @{ NativeShared = $true; AclCount = 100 } + $env:PRA_GATE_STATE = $global:PraGate.Runtime.StatePath + $env:PSModulePath = $global:PraGate.Runtime.Modules + ';' + (Join-Path $PSHOME 'Modules') + Import-Module ActiveDirectory -Force -Global + $global:PraGate.Context = New-GateContext $global:PraGate.Runtime + $global:PraGate.Context.LogFile = Join-Path $global:PraGate.Runtime.Root 'logs\unit.log' + $global:PraGate.TokenE333 = @('S-1-5-21-100-200-300-1111', 'S-1-5-21-100-200-300-2222', 'S-1-1-0') + } + AfterEach { $global:PraGateAd.Remove('DenyGenericAll') } + It 'names the object with a Deny entry for this account in the Preview, reads the descriptor once, writes nothing, and does not name an object whose Deny entry is for another account ()' -ForEach @(@{ Culture = 'en-US' }, @{ Culture = 'fr-FR' }) { + $old = [Globalization.CultureInfo]::CurrentCulture + try { + [Globalization.CultureInfo]::CurrentCulture = [Globalization.CultureInfo]::GetCultureInfo($Culture) + $context = $global:PraGate.Context + $global:PraGateAd.DenyGenericAll = 'S-1-5-21-100-200-300-1111' + $plans = InModuleScope PRA.Directory { + Mock Get-PraTokenSid { $global:PraGate.TokenE333 } + @(New-PraPlan $global:PraGate.Context 'user1' 'Convert'; New-PraPlan $global:PraGate.Context 'user2' 'Convert') + } + @($plans[0].Rights).Count | Should -BeGreaterThan 0 + ($plans[0].Rights -join ' ') | Should -Match 'a Deny entry for \*S-1-5-21-100-200-300-1111 \(this account\) covers every property' + $plans[0].Row.Warnings | Should -Match 'Rights probe: a Deny entry' + $global:PraGateAd.DenyGenericAll = 'S-1-5-21-100-200-300-4444' + $other = InModuleScope PRA.Directory { Mock Get-PraTokenSid { $global:PraGate.TokenE333 }; New-PraPlan $global:PraGate.Context 'user1' 'Convert' } + @($other.Rights).Count | Should -Be 0 -Because 'the Deny entry is for an account that is not this one' + $other.Row.Warnings | Should -Not -Match 'Rights probe' + $global:PraGateAd.DenyGenericAll = 'S-1-5-21-100-200-300-1111' + $first = InModuleScope PRA.Directory { Mock Get-PraTokenSid { $global:PraGate.TokenE333 }; New-PraPlan $global:PraGate.Context 'user1' 'Convert' } + $text = Invoke-PraAdPreview $context @($first) *>&1 | Out-String + $text | Should -Match '1 object\(s\) are likely to be refused by Active Directory when this is applied' + $text | Should -Match 'dsacls "CN=' + $context.Warnings | Should -BeGreaterThan 0 + @(Get-GateWrites $global:PraGate.Runtime).Count | Should -Be 0 + @(Get-GateEvents $global:PraGate.Runtime | Where-Object { $_.Operation -eq 'Get-ADUser' -and @($_.Detail.Properties) -contains 'nTSecurityDescriptor' }).Count | Should -BeGreaterThan 0 + } + finally { [Globalization.CultureInfo]::CurrentCulture = $old } + } + It 'sees a Deny entry for a group of the account (by SID), an object protected by AdminSDHolder, and says nothing for an object that has neither' { + $global:PraGateAd.DenyGenericAll = 'S-1-5-21-100-200-300-2222' + $viaGroup = InModuleScope PRA.Directory { Mock Get-PraTokenSid { $global:PraGate.TokenE333 }; New-PraPlan $global:PraGate.Context 'user1' 'Convert' } + ($viaGroup.Rights -join ' ') | Should -Match '\*S-1-5-21-100-200-300-2222 \(a group of this account\)' + $global:PraGateAd.Remove('DenyGenericAll') + $global:PraGateAd.Users[0] | Add-Member -NotePropertyName adminCount -NotePropertyValue 1 -Force + $protected = InModuleScope PRA.Directory { Mock Get-PraTokenSid { $global:PraGate.TokenE333 }; New-PraPlan $global:PraGate.Context 'user1' 'Convert' } + ($protected.Rights -join ' ') | Should -Match 'protected by AdminSDHolder \(adminCount = 1\)' + $global:PraGateAd.Users[0].adminCount = 0 + $clean = InModuleScope PRA.Directory { Mock Get-PraTokenSid { $global:PraGate.TokenE333 }; New-PraPlan $global:PraGate.Context 'user1' 'Convert' } + @($clean.Rights).Count | Should -Be 0 + @($clean.Row.Warnings | Where-Object { $_ -match 'Rights probe' }).Count | Should -Be 0 + } + It 'evaluates the entries in memory: a Deny entry on one property, on its property set, an entry that only children inherit, a blocked inheritance with and without an Allow entry, and a schema that cannot be read' { + $proxy = [guid]'11111111-1111-1111-1111-111111111111'; $set = [guid]'22222222-2222-2222-2222-222222222222'; $target = [guid]'33333333-3333-3333-3333-333333333333' + $global:PraGate.E333 = @{ + Mine = New-E333Descriptor -Rule @(@{ Sid = 'S-1-5-21-100-200-300-1111'; Rights = 'WriteProperty'; Access = 'Deny'; Type = $proxy }) + ViaSet = New-E333Descriptor -Rule @(@{ Sid = 'S-1-5-21-100-200-300-2222'; Rights = 'WriteProperty'; Access = 'Deny'; Type = $set }) + Other = New-E333Descriptor -Rule @(@{ Sid = 'S-1-5-21-100-200-300-1111'; Rights = 'WriteProperty'; Access = 'Deny'; Type = $target }) + ChildrenOnly = New-E333Descriptor -Rule @(@{ Sid = 'S-1-5-21-100-200-300-1111'; Rights = 'GenericAll'; Access = 'Deny'; Inheritance = 'Descendents' }) + ReadOnly = New-E333Descriptor -Rule @(@{ Sid = 'S-1-5-21-100-200-300-1111'; Rights = 'ReadProperty'; Access = 'Deny' }) + BlockedNone = New-E333Descriptor -Protected -Rule @(@{ Sid = 'S-1-5-21-100-200-300-9999'; Rights = 'GenericAll'; Access = 'Allow' }) + BlockedAllowed = New-E333Descriptor -Protected -Rule @(@{ Sid = 'S-1-5-21-100-200-300-2222'; Rights = 'WriteProperty'; Access = 'Allow' }) + DenyAll = New-E333Descriptor -Rule @(@{ Sid = 'S-1-5-21-100-200-300-1111'; Rights = 'GenericAll'; Access = 'Deny' }) + OpenNone = New-E333Descriptor -Rule @(@{ Sid = 'S-1-5-21-100-200-300-9999'; Rights = 'GenericAll'; Access = 'Allow' }) + } + $answers = InModuleScope PRA.Directory { + Mock Get-PraTokenSid { $global:PraGate.TokenE333 } + Mock Get-ADRootDSE { [pscustomobject]@{ schemaNamingContext = 'CN=Schema,CN=Configuration,DC=gate,DC=invalid' } } + Mock Get-ADObject { @([pscustomobject]@{ lDAPDisplayName = 'proxyAddresses'; schemaIDGuid = ([guid]'11111111-1111-1111-1111-111111111111').ToByteArray(); attributeSecurityGUID = ([guid]'22222222-2222-2222-2222-222222222222').ToByteArray() }, [pscustomobject]@{ lDAPDisplayName = 'targetAddress'; schemaIDGuid = ([guid]'44444444-4444-4444-4444-444444444444').ToByteArray(); attributeSecurityGUID = $null }) } + $result = @{} + foreach ($name in $global:PraGate.E333.Keys) { + $context = @{ Server = $global:PraGate.Context.Server; LogFile = ''; VerboseEnabled = $false; Warnings = 0 } + $user = [pscustomobject]@{ nTSecurityDescriptor = $global:PraGate.E333[$name]; adminCount = 0 } + $result[$name] = @(Get-PraRightsFinding -Context $context -User $user -Attribute @('proxyAddresses', 'targetAddress')) + } + Mock Get-ADObject { throw 'SYNTHETIC: the schema is not readable.' } + $context = @{ Server = $global:PraGate.Context.Server; LogFile = ''; VerboseEnabled = $false; Warnings = 0 } + $result['BlockedNoSchema'] = @(Get-PraRightsFinding -Context $context -User ([pscustomobject]@{ nTSecurityDescriptor = $global:PraGate.E333['BlockedNone']; adminCount = 0 }) -Attribute @('proxyAddresses')) + $result['DenyAllNoSchema'] = @(Get-PraRightsFinding -Context $context -User ([pscustomobject]@{ nTSecurityDescriptor = $global:PraGate.E333['DenyAll']; adminCount = 0 }) -Attribute @('proxyAddresses')) + $result + } + ($answers.Mine -join ' ') | Should -Match 'Deny entry for \*S-1-5-21-100-200-300-1111 \(this account\) covers proxyAddresses' + ($answers.Mine -join ' ') | Should -Not -Match 'targetAddress' + ($answers.ViaSet -join ' ') | Should -Match 'a group of this account\) covers proxyAddresses' -Because 'a Deny entry on the property set of the attribute covers it' + @($answers.Other).Count | Should -Be 0 -Because 'a Deny entry on another property' + @($answers.ChildrenOnly).Count | Should -Be 0 -Because 'an entry that only the children inherit does not apply to the object' + @($answers.ReadOnly).Count | Should -Be 0 -Because 'a Deny entry for reading is not a refusal to write' + ($answers.BlockedNone -join ' ') | Should -Match 'inheritance is blocked on this object and none of its entries lets this account write proxyAddresses, targetAddress' + @($answers.BlockedAllowed).Count | Should -Be 0 + @($answers.OpenNone).Count | Should -Be 0 -Because 'only an object that blocks inheritance is reported for a missing Allow entry' + @($answers.BlockedNoSchema).Count | Should -Be 0 -Because 'without the schema a missing Allow entry cannot be told' + ($answers.DenyAllNoSchema -join ' ') | Should -Match 'covers every property' -Because 'an entry that covers every property needs no schema' + } +} + +Describe 'Release 3.3.0 - the cleanup helper: what it lists, what it never lists, and what it deletes only with the typed word (production Common module, synthetic folders)' -Tag 'Release330E' { + BeforeAll { + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global + $script:E334Root = Join-Path $global:PraGate.Root ('clean-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) + $null = New-Item -ItemType Directory -Path $script:E334Root -Force + $script:E334Counter = 0 + function script:Use-E334Culture { + param([string]$Name, [scriptblock]$Do) + $old = [Globalization.CultureInfo]::CurrentCulture; $oldUi = [Globalization.CultureInfo]::CurrentUICulture + try { [Globalization.CultureInfo]::CurrentCulture = [Globalization.CultureInfo]::GetCultureInfo($Name); [Globalization.CultureInfo]::CurrentUICulture = [Globalization.CultureInfo]::GetCultureInfo($Name); & $Do } + finally { [Globalization.CultureInfo]::CurrentCulture = $old; [Globalization.CultureInfo]::CurrentUICulture = $oldUi } + } + # A tree as the tool leaves it: the three configured folders and a temporary folder of the account. + function script:New-E334Tree { + $script:E334Counter++ + $root = Join-Path $script:E334Root ('t' + $script:E334Counter) + foreach ($name in 'Backups', 'logs', 'reports', 'tmp') { $null = New-Item -ItemType Directory -Path (Join-Path $root $name) -Force } + [pscustomobject]@{ Root = $root; Backups = (Join-Path $root 'Backups'); Logs = (Join-Path $root 'logs'); Reports = (Join-Path $root 'reports'); Temp = (Join-Path $root 'tmp') + Config = @{ Environment = 'LAB'; Storage = @{ BackupFolder = (Join-Path $root 'Backups') }; Logging = @{ Folder = (Join-Path $root 'logs') }; Report = @{ Folder = (Join-Path $root 'reports') }; Cleanup = @{ OlderThanDays = 30 } } } + } + function script:Set-E334Age { param([string]$Path, [double]$Days = 100, [double]$Hours = 0) $when = [datetime]::UtcNow.AddDays(-$Days).AddHours(-$Hours); foreach ($item in @(Get-ChildItem -LiteralPath $Path -Recurse -Force -ErrorAction SilentlyContinue) + @(Get-Item -LiteralPath $Path -Force)) { $item.LastWriteTimeUtc = $when } } + function script:New-E334File { param([string]$Path, [string]$Text, [double]$Days = 100, [double]$Hours = 0) [IO.File]::WriteAllText($Path, $Text, (New-Object Text.UTF8Encoding($false))); Set-E334Age $Path $Days $Hours; $Path } + function script:Get-E334Sha([string]$Path) { (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash.ToLowerInvariant() } + # The phase data that a run leaves in a batch folder: one file with its checksum file, the batch named by its first 8 characters like a run does. + function script:New-E334Phase { + param([string]$Folder, [string]$BatchId, [string]$Action, [string]$Side, [string[]]$Guid, [string]$HandOff = '', [string]$Environment = 'LAB') + $objects = ($Guid | ForEach-Object { '{"ObjectGuid":"' + $_ + '","CloudStatus":"Success"}' }) -join ',' + $path = Join-Path $Folder ('PhaseData-20261120000004-' + $Side + '-dddddddd.json') + [IO.File]::WriteAllText($path, ('{"SchemaVersion":2,"Kind":"PhaseData","Environment":"' + $Environment + '","BatchId":"' + $BatchId.Substring(0, 8) + '","Phase":{"Action":"' + $Action + '","Phase":"' + $Side + '","Mode":"Apply","HandOff":"' + $HandOff + '"},"Objects":[' + $objects + ']}'), (New-Object Text.UTF8Encoding($false))) + [IO.File]::WriteAllText($path + '.sha256', (Get-E334Sha $path), (New-Object Text.UTF8Encoding($false))) + } + # A Convert batch folder, or a Recover batch folder whose proof says what the rollback restored (Restored: restored in Active Directory; Deprovision: a shared mailbox that waits for its Finalize) and whose cloud part is recorded in its phase data. + function script:New-E334Batch { + param([string]$Backups, [string]$Id, [string]$Operation = 'Convert', [string[]]$Guid = @('00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000002'), [string]$SourceHash = '', [string[]]$Restored = @(), [string[]]$Deprovision = @(), [string[]]$Tagged = @(), [string[]]$Preserve = @(), [switch]$Partial, [switch]$NoJournal, [switch]$NotApplied, [switch]$NoState, [switch]$NoCloud, [switch]$NoSidecar, [string]$Kind = 'ADVerified', [double]$Days = 100, [string]$Environment = 'LAB') + $folder = Join-Path $Backups ('Batch-' + $Id) + $null = New-Item -ItemType Directory -Path $folder -Force + $records = ($Guid | ForEach-Object { '{"ObjectGuid":"' + $_ + '"' + $(if ($Tagged -contains $_) { ',"Retention":{"Enabled":true}' } else { '' }) + $(if ($Preserve -contains $_) { ',"PreserveCloudMailbox":true' } else { '' }) + '}' }) -join ',' + $json = Join-Path $folder ($Operation + '-LAB-20260101_000000-' + $Id.Substring(0, 8) + '.json') + [IO.File]::WriteAllText($json, ('{"SchemaVersion":3,"Operation":"' + $Operation + '","BatchId":"' + $Id + '","Environment":"' + $Environment + '","Records":[' + $records + ']}'), (New-Object Text.UTF8Encoding($false))) + if (-not $NoJournal) { [IO.File]::WriteAllText((Join-Path $folder ('Journal-' + $Id + '.jsonl')), '{"Operation":"Backup","Status":"Verified","Target":"*"}', (New-Object Text.UTF8Encoding($false))) } + if ($NotApplied) { [IO.File]::WriteAllText((Join-Path $folder 'NOT-APPLIED.txt'), 'Nothing was written.', (New-Object Text.UTF8Encoding($false))) } + if (-not $NoState -and -not $NotApplied) { + $recordsState = (@(@($Restored | ForEach-Object { '{"ObjectGuid":"' + $_ + '","Operation":"Recover","ADVerified":true}' }) + @($Deprovision | ForEach-Object { '{"ObjectGuid":"' + $_ + '","Operation":"Deprovision","ADVerified":true}' })) -join ',') + $state = '{"SchemaVersion":2,"Operation":"' + $Operation + '","Kind":"' + $Kind + '","Environment":"' + $Environment + '","SourceBackupHash":"' + $SourceHash + '"' + $(if ($Partial) { ',"Partial":true' } else { '' }) + ',"Records":[' + $(if ($Operation -eq 'Recover') { $recordsState } else { $records }) + ']}' + $statePath = Join-Path $folder ('State-' + $Id + '.json') + [IO.File]::WriteAllText($statePath, $state, (New-Object Text.UTF8Encoding($false))) + if (-not $NoSidecar) { [IO.File]::WriteAllText($statePath + '.sha256', (Get-E334Sha $statePath), (New-Object Text.UTF8Encoding($false))) } + } + if ($Operation -eq 'Recover' -and -not $NoCloud -and -not $NoState) { New-E334Phase -Folder $folder -BatchId $Id -Action 'Recover' -Side 'Both' -Guid $Guid -Environment $Environment } + Set-E334Age $folder $Days + [pscustomobject]@{ Folder = $folder; Json = $json; Sha = (Get-E334Sha $json); Id = $Id } + } + # A batch folder that the Finalize action wrote on the AD server: its backup and its proof (Recover: objects restored; Tag: retention tags restored). + function script:New-E334Finalized { + param([string]$Backups, [string]$Id, [string]$SourceHash, [string[]]$Recover = @(), [string[]]$Tag = @(), [switch]$NoSidecar, [double]$Days = 100, [string]$Environment = 'LAB') + $folder = Join-Path $Backups ('Batch-' + $Id) + $null = New-Item -ItemType Directory -Path $folder -Force + [IO.File]::WriteAllText((Join-Path $folder ('Finalize-LAB-20260101_000000-' + $Id.Substring(0, 8) + '.json')), ('{"SchemaVersion":3,"Operation":"Finalize","BatchId":"' + $Id + '","Environment":"' + $Environment + '","Records":[]}'), (New-Object Text.UTF8Encoding($false))) + [IO.File]::WriteAllText((Join-Path $folder ('Journal-' + $Id + '.jsonl')), '{"Operation":"Backup","Status":"Verified","Target":"*"}', (New-Object Text.UTF8Encoding($false))) + $records = (@(@($Recover | ForEach-Object { '{"ObjectGuid":"' + $_ + '","Operation":"Recover","ADVerified":true}' }) + @($Tag | ForEach-Object { '{"ObjectGuid":"' + $_ + '","Operation":"RestoreTag","ADVerified":true}' })) -join ',') + $statePath = Join-Path $folder ('State-' + $Id + '.json') + [IO.File]::WriteAllText($statePath, ('{"SchemaVersion":2,"Operation":"Finalize","Kind":"ADVerified","Environment":"' + $Environment + '","SourceBackupHash":"' + $SourceHash + '","Records":[' + $records + ']}'), (New-Object Text.UTF8Encoding($false))) + if (-not $NoSidecar) { [IO.File]::WriteAllText($statePath + '.sha256', (Get-E334Sha $statePath), (New-Object Text.UTF8Encoding($false))) } + Set-E334Age $folder $Days + [pscustomobject]@{ Folder = $folder; Id = $Id } + } + # A Finalize package folder as the cloud server hands it over: the manifest (with its checksum file), and when asked the phase data of the cloud part of the Recover. + function script:New-E334Package { + param([string]$Backups, [string]$Id, [string]$SourceHash, [string[]]$Shared = @(), [string[]]$TagOnly = @(), [string[]]$CloudGuid = @(), [double]$Days = 100, [string]$Environment = 'LAB') + $folder = Join-Path $Backups ('Finalize-' + $Id) + $null = New-Item -ItemType Directory -Path $folder -Force + $items = (@(@($Shared | ForEach-Object { '{"ObjectGuid":"' + $_ + '","RestoreShared":true,"RestoreTag":false,"CloudConfirmed":true,"DeprovisionConfirmed":true}' }) + @($TagOnly | ForEach-Object { '{"ObjectGuid":"' + $_ + '","RestoreShared":false,"RestoreTag":true,"CloudConfirmed":true,"DeprovisionConfirmed":true}' })) -join ',') + $manifest = Join-Path $folder ('Finalize-LAB-20260101_000000-' + $Id.Substring(0, 8) + '.json') + [IO.File]::WriteAllText($manifest, ('{"SchemaVersion":2,"Operation":"RecoverFinalize","Environment":"' + $Environment + '","SourceBackupHash":"' + $SourceHash + '","Items":[' + $items + ']}'), (New-Object Text.UTF8Encoding($false))) + [IO.File]::WriteAllText($manifest + '.sha256', (Get-E334Sha $manifest), (New-Object Text.UTF8Encoding($false))) + if ($CloudGuid.Count) { New-E334Phase -Folder $folder -BatchId $Id -Action 'Recover' -Side 'Cloud' -Guid $CloudGuid -HandOff 'Finalize' -Environment $Environment } + Set-E334Age $folder $Days + [pscustomobject]@{ Folder = $folder; Id = $Id } + } + $script:E334Convert = 'aaaaaaaa11111111aaaaaaaa11111111'; $script:E334Recover = 'bbbbbbbb22222222bbbbbbbb22222222' + $script:E334Guids = @('00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000002') + } + AfterAll { Remove-GateReparsePoint -Root $script:E334Root } + It 'lists the stale Preview folders (more than 24 hours, made of the folders of a package) and nothing else of the logs folder, and deletes them only in the Apply with the typed word ()' -ForEach @(@{ Culture = 'en-US' }, @{ Culture = 'fr-FR' }) { + Use-E334Culture $Culture { + $tree = New-E334Tree + $stale = Join-Path $tree.Logs 'preview-0123456789ab'; $null = New-Item -ItemType Directory -Path (Join-Path $stale ('Batch-' + $script:E334Convert)) -Force; New-E334File (Join-Path $stale ('Batch-' + $script:E334Convert + '\a.json')) '{}' 3 | Out-Null; Set-E334Age $stale 2 + $fresh = Join-Path $tree.Logs 'preview-fedcba987654'; $null = New-Item -ItemType Directory -Path (Join-Path $fresh ('Batch-' + $script:E334Convert)) -Force; Set-E334Age $fresh 0 2 + $foreign = Join-Path $tree.Logs 'preview-aaaaaaaaaaaa'; $null = New-Item -ItemType Directory -Path $foreign -Force; New-E334File (Join-Path $foreign 'notes.txt') 'mine' 5 | Out-Null; Set-E334Age $foreign 5 + $other = Join-Path $tree.Logs 'preview-notahexname'; $null = New-Item -ItemType Directory -Path (Join-Path $other ('Batch-' + $script:E334Convert)) -Force; Set-E334Age $other 5 + $found = Get-PraCleanupCandidate -Config $tree.Config -TempFolder $tree.Temp + @($found.Items).Count | Should -Be 1 + $found.Items[0].Path | Should -BeExactly $stale + $found.Items[0].Kind | Should -BeExactly 'PreviewLeftover' + $found.Items[0].AgeDays | Should -BeGreaterThan 1 + @($found.Kept | Where-Object { $_.Path -eq $foreign }).Count | Should -Be 1 -Because 'a preview- folder that holds something else is left alone and said so' + (Format-PraCleanupSize 1536) | Should -BeExactly '1.5 KB' + $logFile = Join-Path $tree.Root 'run.log' + $context = @{ LogFile = $logFile; VerboseEnabled = $false; Warnings = 0 } + foreach ($word in '', 'delete', 'cleanu', 'yes') { + $none = Invoke-PraCleanup -Config $tree.Config -Item @($found.Items) -ConfirmationWord $word -TempFolder $tree.Temp -Context $context + $none.Confirmed | Should -BeFalse + @($none.Deleted).Count | Should -Be 0 + } + Test-Path -LiteralPath $stale | Should -BeTrue -Because 'without the typed word nothing is deleted' + $done = Invoke-PraCleanup -Config $tree.Config -Item @($found.Items) -ConfirmationWord ' cLeAnUp ' -TempFolder $tree.Temp -Context $context + $done.Confirmed | Should -BeTrue + @($done.Deleted) | Should -Be @($stale) + Test-Path -LiteralPath $stale | Should -BeFalse + foreach ($left in $fresh, $foreign, $other) { Test-Path -LiteralPath $left | Should -BeTrue } + @([IO.File]::ReadAllLines($logFile) | Where-Object { $_ -like '*Cleanup deleted | PreviewLeftover | *' }).Count | Should -Be 1 -Because 'one line per item deleted' + } + } + It 'never lists the folder of a batch that is not finished: an applied Convert with no Recover, a Recover that restored only some objects, a partial or missing proof, another Environment ()' -ForEach @(@{ Culture = 'en-US' }, @{ Culture = 'fr-FR' }) { + Use-E334Culture $Culture { + $tree = New-E334Tree + $applied = New-E334Batch $tree.Backups $script:E334Convert + $half = New-E334Batch $tree.Backups ('c' * 32) + $null = New-E334Batch $tree.Backups ('d' * 32) -Operation Recover -SourceHash $half.Sha -Restored @($script:E334Guids[0]) + $partial = New-E334Batch $tree.Backups ('e' * 32) + $null = New-E334Batch $tree.Backups ('f' * 32) -Operation Recover -SourceHash $partial.Sha -Restored $script:E334Guids -Partial + $noProof = New-E334Batch $tree.Backups ('1' * 32) -Operation Recover -NoState -SourceHash 'x' + $foreignEnvironment = New-E334Batch $tree.Backups ('2' * 32) -Environment 'OTHER' + $unknown = Join-Path $tree.Backups ('Batch-' + ('3' * 32)); $null = New-Item -ItemType Directory -Path $unknown -Force; Set-E334Age $unknown 400 + $found = Get-PraCleanupCandidate -Config $tree.Config -OlderThanDays 1 -TempFolder $tree.Temp + @($found.Items | Where-Object Kind -EQ 'Batch').Count | Should -Be 0 + foreach ($folder in $applied.Folder, $half.Folder, $partial.Folder, (Join-Path $tree.Backups ('Batch-' + ('d' * 32))), (Join-Path $tree.Backups ('Batch-' + ('f' * 32))), $noProof.Folder, $foreignEnvironment.Folder, $unknown) { + Test-Path -LiteralPath $folder | Should -BeTrue + @($found.Items | Where-Object { $_.Path -eq $folder }).Count | Should -Be 0 -Because $folder + } + foreach ($folder in $applied.Folder, $half.Folder, $partial.Folder, (Join-Path $tree.Backups ('Batch-' + ('f' * 32))), $noProof.Folder, $foreignEnvironment.Folder, $unknown) { + @($found.Kept | Where-Object { $_.Path -eq $folder }).Count | Should -BeGreaterOrEqual 1 -Because $folder + } + (@($found.Kept | Where-Object { $_.Path -eq $applied.Folder })[0].Reason) | Should -Match 'not finished' + (@($found.Kept | Where-Object { $_.Path -eq $half.Folder })[0].Reason) | Should -Match '1 object\(s\) are not proven restored' + } + } + It 'lists a finished batch (every object restored by the proof of a Recover batch, or nothing written to Active Directory) when it is old enough, with its Recover batch after it, and deletes the Convert folder first' { + $tree = New-E334Tree + $convert = New-E334Batch $tree.Backups $script:E334Convert + $recover = New-E334Batch $tree.Backups $script:E334Recover -Operation Recover -SourceHash $convert.Sha -Restored $script:E334Guids + $idle = New-E334Batch $tree.Backups ('4' * 32) -NotApplied + $young = New-E334Batch $tree.Backups ('5' * 32) -NotApplied -Days 3 + $found = Get-PraCleanupCandidate -Config $tree.Config -TempFolder $tree.Temp + @($found.Items | ForEach-Object { Split-Path $_.Path -Leaf } | Sort-Object) | Should -Be @(@($convert.Folder, $recover.Folder, $idle.Folder) | ForEach-Object { Split-Path $_ -Leaf } | Sort-Object) + @($found.Items | Where-Object Path -EQ $convert.Folder)[0].Reason | Should -Match 'rolled back and verified' + @($found.Items | Where-Object Path -EQ $idle.Folder)[0].Reason | Should -Match 'nothing was written to Active Directory' + @($found.Items | ForEach-Object Root | Get-PraOrdinalUnique) | Should -Be @($tree.Backups) -Because 'every item is inside a configured folder' + (@($found.Kept | Where-Object { $_.Path -eq $young.Folder })[0].Reason) | Should -Match 'kept until it is 30 day' + $order = New-Object 'Collections.Generic.List[string]' + $context = @{ LogFile = (Join-Path $tree.Root 'run.log'); VerboseEnabled = $false; Warnings = 0 } + $done = Invoke-PraCleanup -Config $tree.Config -Item @($found.Items) -ConfirmationWord 'CLEANUP' -TempFolder $tree.Temp -Context $context + @($done.Deleted).Count | Should -Be 3 + [array]::IndexOf(@($done.Deleted), $convert.Folder) | Should -BeLessThan ([array]::IndexOf(@($done.Deleted), $recover.Folder)) -Because 'the proof of the rollback goes last' + Test-Path -LiteralPath $young.Folder | Should -BeTrue + $again = Get-PraCleanupCandidate -Config $tree.Config -TempFolder $tree.Temp + @($again.Items).Count | Should -Be 0 + } + It 'does not list a Convert batch whose rollback is not finished: the cloud part is not recorded, a shared mailbox or a retention tag waits for its Finalize, a Finalize package is not applied; it lists it when each part is done ()' -ForEach @(@{ Culture = 'en-US' }, @{ Culture = 'fr-FR' }) { + Use-E334Culture $Culture { + $pending = 'rollback not finished \(cloud or Finalize pending\)' + $one = $script:E334Guids[0]; $two = $script:E334Guids[1] + $tree = New-E334Tree + $convert = New-E334Batch $tree.Backups $script:E334Convert + $recover = New-E334Batch $tree.Backups $script:E334Recover -Operation Recover -SourceHash $convert.Sha -Restored $script:E334Guids -NoCloud + $found = Get-PraCleanupCandidate -Config $tree.Config -TempFolder $tree.Temp + @($found.Items | Where-Object Kind -EQ 'Batch').Count | Should -Be 0 + $reason = (@($found.Kept | Where-Object { $_.Path -eq $convert.Folder })[0]).Reason + $reason | Should -Match $pending + $reason | Should -Match '2 object\(s\) without a recorded cloud part' + $null = New-E334Package $tree.Backups ('7' * 32) -SourceHash $convert.Sha -CloudGuid $script:E334Guids + $viaPackage = Get-PraCleanupCandidate -Config $tree.Config -TempFolder $tree.Temp + @($viaPackage.Items | Where-Object Kind -EQ 'Batch').Count | Should -Be 3 -Because 'the cloud part recorded in the Finalize package completes the proof: the Convert, the Recover and the Finalize folders are listed' + + $tree = New-E334Tree + $convert = New-E334Batch $tree.Backups $script:E334Convert + $recover = New-E334Batch $tree.Backups $script:E334Recover -Operation Recover -SourceHash $convert.Sha -Restored @($one) -Deprovision @($two) + $found = Get-PraCleanupCandidate -Config $tree.Config -TempFolder $tree.Temp + @($found.Items | Where-Object Kind -EQ 'Batch').Count | Should -Be 0 + (@($found.Kept | Where-Object { $_.Path -eq $convert.Folder })[0]).Reason | Should -Match ($pending + '.*1 shared mailbox\(es\) not restored by a Finalize') + $other = New-E334Finalized $tree.Backups ('8' * 32) -SourceHash ('ab' * 32) -Recover @($two) + $stillKept = Get-PraCleanupCandidate -Config $tree.Config -TempFolder $tree.Temp + @($stillKept.Items | Where-Object Kind -EQ 'Batch').Count | Should -Be 0 -Because 'the Finalize of another source does not count' + (@($stillKept.Kept | Where-Object { $_.Path -eq $other.Folder })[0]).Reason | Should -Match 'goes with the Convert batch that it rolled back, which is not listed' + $finalized = New-E334Finalized $tree.Backups ('9' * 32) -SourceHash $convert.Sha -Recover @($two) + $done = Get-PraCleanupCandidate -Config $tree.Config -TempFolder $tree.Temp + @($done.Items | ForEach-Object Path | Sort-Object) | Should -Be @(@($convert.Folder, $recover.Folder, $finalized.Folder) | Sort-Object) + (@($done.Items | Where-Object Path -EQ $convert.Folder)[0]).Order | Should -Be 0 + @($done.Items | Where-Object Path -EQ $other.Folder).Count | Should -Be 0 + + $tree = New-E334Tree + $convert = New-E334Batch $tree.Backups $script:E334Convert -Tagged @($one) + $recover = New-E334Batch $tree.Backups $script:E334Recover -Operation Recover -SourceHash $convert.Sha -Restored $script:E334Guids + $found = Get-PraCleanupCandidate -Config $tree.Config -TempFolder $tree.Temp + @($found.Items | Where-Object Kind -EQ 'Batch').Count | Should -Be 0 + (@($found.Kept | Where-Object { $_.Path -eq $convert.Folder })[0]).Reason | Should -Match ($pending + '.*1 retention tag\(s\) not restored by a Finalize') + $finalized = New-E334Finalized $tree.Backups ('9' * 32) -SourceHash $convert.Sha -Tag @($one) + @((Get-PraCleanupCandidate -Config $tree.Config -TempFolder $tree.Temp).Items | Where-Object Kind -EQ 'Batch').Count | Should -Be 3 + + $tree = New-E334Tree + $convert = New-E334Batch $tree.Backups $script:E334Convert -Tagged @($one) + $null = New-E334Batch $tree.Backups $script:E334Recover -Operation Recover -SourceHash $convert.Sha -Restored $script:E334Guids -Preserve @($one) + @((Get-PraCleanupCandidate -Config $tree.Config -TempFolder $tree.Temp).Items | Where-Object Kind -EQ 'Batch').Count | Should -Be 2 -Because 'the cloud mailbox was kept on purpose: its tag stays and nothing is left to restore' + + $tree = New-E334Tree + $convert = New-E334Batch $tree.Backups $script:E334Convert + $recover = New-E334Batch $tree.Backups $script:E334Recover -Operation Recover -SourceHash $convert.Sha -Restored @($one) -Deprovision @($two) + $package = New-E334Package $tree.Backups ('7' * 32) -SourceHash $convert.Sha -Shared @($two) + $unrelated = New-E334Package $tree.Backups ('6' * 32) -SourceHash ('ab' * 32) -Shared @($two) + $found = Get-PraCleanupCandidate -Config $tree.Config -TempFolder $tree.Temp + @($found.Items | Where-Object Kind -EQ 'Batch').Count | Should -Be 0 + (@($found.Kept | Where-Object { $_.Path -eq $convert.Folder })[0]).Reason | Should -Match ($pending + '.*1 object\(s\) of a Finalize package not restored') + $finalized = New-E334Finalized $tree.Backups ('9' * 32) -SourceHash $convert.Sha -Recover @($two) + $done = Get-PraCleanupCandidate -Config $tree.Config -TempFolder $tree.Temp + @($done.Items | ForEach-Object Path | Sort-Object) | Should -Be @(@($convert.Folder, $recover.Folder, $package.Folder, $finalized.Folder) | Sort-Object) + @($done.Items | Where-Object Path -EQ $unrelated.Folder).Count | Should -Be 0 -Because 'the package of another source is not a part of this batch' + } + } + It 'trusts a proof only when its checksum file matches what is stored and it is an AD proof: a missing or wrong checksum, another kind, and a manifest without its checksum are not read ()' -ForEach @(@{ Culture = 'en-US' }, @{ Culture = 'fr-FR' }) { + Use-E334Culture $Culture { + $tree = New-E334Tree + $convert = New-E334Batch $tree.Backups $script:E334Convert + $noSidecar = New-E334Batch $tree.Backups $script:E334Recover -Operation Recover -SourceHash $convert.Sha -Restored $script:E334Guids -NoSidecar + $wrong = New-E334Batch $tree.Backups ('c' * 32) -Operation Recover -SourceHash $convert.Sha -Restored $script:E334Guids + [IO.File]::WriteAllText((Join-Path $wrong.Folder ('State-' + $wrong.Id + '.json.sha256')), ('0' * 64), (New-Object Text.UTF8Encoding($false))) + $kind = New-E334Batch $tree.Backups ('d' * 32) -Operation Recover -SourceHash $convert.Sha -Restored $script:E334Guids -Kind 'Journal' + $manifest = New-E334Package $tree.Backups ('e' * 32) -SourceHash $convert.Sha -CloudGuid $script:E334Guids + Remove-Item -LiteralPath (@(Get-ChildItem -LiteralPath $manifest.Folder -Filter 'Finalize-*.json.sha256')[0].FullName) -Force + $found = Get-PraCleanupCandidate -Config $tree.Config -TempFolder $tree.Temp + @($found.Items | Where-Object Kind -EQ 'Batch').Count | Should -Be 0 -Because 'no proof of the rollback can be trusted' + (@($found.Kept | Where-Object { $_.Path -eq $noSidecar.Folder })[0]).Reason | Should -Match 'the proof cannot be read: its checksum file \(\.sha256\) is missing' + (@($found.Kept | Where-Object { $_.Path -eq $wrong.Folder })[0]).Reason | Should -Match 'the proof cannot be read: it does not match its checksum file' + (@($found.Kept | Where-Object { $_.Path -eq $kind.Folder })[0]).Reason | Should -Match 'a Recover batch whose proof is not complete' + (@($found.Kept | Where-Object { $_.Path -eq $manifest.Folder })[0]).Reason | Should -Match 'the manifest cannot be read: its checksum file \(\.sha256\) is missing' + (@($found.Kept | Where-Object { $_.Path -eq $convert.Folder })[0]).Reason | Should -Match 'no Recover batch proves' + } + } + It 'does not delete the other folders of a batch when the folder of the Convert batch cannot be deleted, and says so' { + $tree = New-E334Tree + $convert = New-E334Batch $tree.Backups $script:E334Convert + $recover = New-E334Batch $tree.Backups $script:E334Recover -Operation Recover -SourceHash $convert.Sha -Restored $script:E334Guids + $found = Get-PraCleanupCandidate -Config $tree.Config -TempFolder $tree.Temp + @($found.Items | Where-Object Kind -EQ 'Batch').Count | Should -Be 2 + @($found.Items | ForEach-Object { $_.Batch } | Get-PraOrdinalUnique) | Should -Be @($script:E334Convert) + $logFile = Join-Path $tree.Root 'run.log' + $context = @{ LogFile = $logFile; VerboseEnabled = $false; Warnings = 0 } + $locked = [IO.File]::Open((Join-Path $convert.Folder ('Journal-' + $script:E334Convert + '.jsonl')), [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::None) + try { $done = Invoke-PraCleanup -Config $tree.Config -Item @($found.Items) -ConfirmationWord 'CLEANUP' -TempFolder $tree.Temp -Context $context } + finally { $locked.Dispose() } + @($done.Deleted).Count | Should -Be 0 + @($done.Failed) | Should -Be @($convert.Folder) + @($done.Skipped) | Should -Be @($recover.Folder) + Test-Path -LiteralPath $recover.Folder | Should -BeTrue -Because 'the proof of the rollback stays while the batch it proves is there' + $log = [IO.File]::ReadAllText($logFile) + $log | Should -Match 'Cleanup could not delete' + $log | Should -Match 'Cleanup left .*the folder of its batch could not be deleted' + } + It 'refuses a reparse point: a batch that holds a junction is not listed and its target is never touched, a junction put in an item after the list was made makes it skipped, and a folder that is a junction is not searched' { + $tree = New-E334Tree + $outside = Join-Path $tree.Root 'outside'; $null = New-Item -ItemType Directory -Path $outside -Force; [IO.File]::WriteAllText((Join-Path $outside 'precious.txt'), 'keep') + $convert = New-E334Batch $tree.Backups $script:E334Convert + $recover = New-E334Batch $tree.Backups $script:E334Recover -Operation Recover -SourceHash $convert.Sha -Restored $script:E334Guids + try { + $null = New-Item -ItemType Junction -Path (Join-Path $convert.Folder 'link') -Target $outside + Set-E334Age $recover.Folder 100 + $found = Get-PraCleanupCandidate -Config $tree.Config -TempFolder $tree.Temp + @($found.Items | Where-Object Kind -EQ 'Batch').Count | Should -Be 0 + (@($found.Kept | Where-Object { $_.Path -eq $convert.Folder })[0].Reason) | Should -Match 'reparse point that is not accepted is inside' + Test-Path -LiteralPath (Join-Path $outside 'precious.txt') | Should -BeTrue + $stale = Join-Path $tree.Logs 'preview-0123456789ab'; $null = New-Item -ItemType Directory -Path (Join-Path $stale ('Batch-' + $script:E334Convert)) -Force; Set-E334Age $stale 3 + $listed = Get-PraCleanupCandidate -Config $tree.Config -TempFolder $tree.Temp + @($listed.Items | Where-Object Path -EQ $stale).Count | Should -Be 1 + $null = New-Item -ItemType Junction -Path (Join-Path $stale ('Batch-' + $script:E334Convert) + '\sneaky') -Target $outside + $done = Invoke-PraCleanup -Config $tree.Config -Item @($listed.Items | Where-Object Path -EQ $stale) -ConfirmationWord 'cleanup' -TempFolder $tree.Temp + @($done.Deleted).Count | Should -Be 0 + @($done.Skipped) | Should -Be @($stale) + Test-Path -LiteralPath (Join-Path $outside 'precious.txt') | Should -BeTrue + $linkedLogs = Join-Path $tree.Root 'linked-logs' + $null = New-Item -ItemType Junction -Path $linkedLogs -Target $outside + $config = @{ Environment = 'LAB'; Storage = @{ BackupFolder = $tree.Backups }; Logging = @{ Folder = $linkedLogs }; Report = @{ Folder = $tree.Reports }; Cleanup = @{ OlderThanDays = 30 } } + [IO.File]::WriteAllText((Join-Path $outside 'PRA_x_1a2b3c4d.log'), 'Audit: host=x'); Set-E334Age (Join-Path $outside 'PRA_x_1a2b3c4d.log') 100 + $viaLink = Get-PraCleanupCandidate -Config $config -TempFolder $tree.Temp + @($viaLink.Items | Where-Object Kind -EQ 'Log').Count | Should -Be 0 + @($viaLink.Notes).Count | Should -Be 1 + $viaLink.Notes[0] | Should -Match 'is a reparse point that is not accepted: nothing is listed in it' + } + finally { Remove-GateReparsePoint -Root $tree.Root } + } + It 'lists the logs, transcripts, reports and effective configurations that carry the mark of the tool and are old enough, never the current run, and never a file that only has the name ()' -ForEach @(@{ Culture = 'en-US' }, @{ Culture = 'fr-FR' }) { + Use-E334Culture $Culture { + $tree = New-E334Tree + $log = New-E334File (Join-Path $tree.Logs 'PRA_20260101_000000-aa_1a2b3c4d.log') 'Audit started: run x' + $transcript = New-E334File (Join-Path $tree.Logs 'PRA_20260101_000000-aa_1a2b3c4d.transcript.txt') ('Transcript started, output file is C:\x\PRA_20260101_000000-aa_1a2b3c4d.transcript.txt' + "`r`n") + $nameOnly = New-E334File (Join-Path $tree.Logs 'PRA_20260101_000000-bb_1a2b3c4e.log') 'somebody else wrote this' + $nameOnlyTranscript = New-E334File (Join-Path $tree.Logs 'PRA_20260101_000000-bb_1a2b3c4e.transcript.txt') 'no file name in it' + $young = New-E334File (Join-Path $tree.Logs 'PRA_20260101_000000-cc_1a2b3c4f.log') 'Audit: host' 5 + $current = New-E334File (Join-Path $tree.Logs 'PRA_20260101_000000-dd_1a2b3c50.log') 'Audit: host' 100 + $html = New-E334File (Join-Path $tree.Reports 'PRA_20260101_000000-aa_1a2b3c4d.html') 'PRA Remote Mailbox' + $csv = New-E334File (Join-Path $tree.Reports 'PRA_20260101_000000-aa_1a2b3c4d.csv') ('"ObjectGuid";"SamAccountName"' + "`r`n") + $foreignHtml = New-E334File (Join-Path $tree.Reports 'PRA_20260101_000000-ee_1a2b3c51.html') 'a page of mine' + $other = New-E334File (Join-Path $tree.Reports 'budget.csv') '"a";"b"' + $gui = Join-Path $tree.Logs 'gui\run-0123456789abcdef0123456789abcdef'; $null = New-Item -ItemType Directory -Path $gui -Force + $null = New-E334File (Join-Path $gui 'effective.config.psd1') "# Generated effective configuration for one run - never edit - the base file is unchanged.`r`n@{}" + Set-E334Age $gui 100 + $guiForeign = Join-Path $tree.Logs 'gui\run-fedcba9876543210fedcba9876543210'; $null = New-Item -ItemType Directory -Path $guiForeign -Force + $null = New-E334File (Join-Path $guiForeign 'effective.config.psd1') '@{ MyOwn = 1 }'; Set-E334Age $guiForeign 100 + $found = Get-PraCleanupCandidate -Config $tree.Config -TempFolder $tree.Temp -ExcludePath @($current) + @($found.Items | ForEach-Object Path | Sort-Object) | Should -Be @(@($log, $transcript, $html, $csv, $gui) | Sort-Object) + @($found.Items | Where-Object Path -EQ $log)[0].Kind | Should -BeExactly 'Log' + @($found.Items | Where-Object Path -EQ $transcript)[0].Kind | Should -BeExactly 'Transcript' + @($found.Items | Where-Object Path -EQ $gui)[0].Kind | Should -BeExactly 'EffectiveConfig' + $found.TotalBytes | Should -BeGreaterThan 0 + foreach ($item in $found.Items) { $item.AgeDays | Should -BeGreaterThan 99; $item.Reason | Should -Not -BeNullOrEmpty } + $done = Invoke-PraCleanup -Config $tree.Config -Item @($found.Items) -ConfirmationWord 'CLEANUP' -TempFolder $tree.Temp -ExcludePath @($current) + @($done.Deleted).Count | Should -Be 5 + foreach ($kept in $nameOnly, $nameOnlyTranscript, $young, $current, $foreignHtml, $other, $guiForeign) { Test-Path -LiteralPath $kept | Should -BeTrue -Because $kept } + } + } + It 'lists the temporary files of the Exchange Online child only when the name, the content and the age (24 hours) agree, and never outside the temporary folder' { + $tree = New-E334Tree + $id = 'ab' * 16 + $started = New-E334File (Join-Path $tree.Temp ('praexo_' + $id + '.started')) '1' 0 30 + $connected = New-E334File (Join-Path $tree.Temp ('praexo_' + $id + '.connected')) '1' 0 30 + $applied = New-E334File (Join-Path $tree.Temp ('praexo_' + $id + '.applied.json')) '{"Receipts":[]}' 0 30 + $progress = New-E334File (Join-Path $tree.Temp ('praexo_' + $id + '.progress.jsonl')) '{"Step":1}' 0 30 + $policyMarker = New-E334File (Join-Path $tree.Temp ('praexo_' + $id + '.policy')) 'System.Management.Automation.PSSecurityException|UnauthorizedAccess,Microsoft.PowerShell.Commands.ImportModuleCommand' 0 30 + $policyForeign = New-E334File (Join-Path $tree.Temp ('praexo_' + ('78' * 16) + '.policy')) 'someone else' 0 30 + $freshOne = New-E334File (Join-Path $tree.Temp ('praexo_' + ('cd' * 16) + '.started')) '1' 0 2 + $wrongContent = New-E334File (Join-Path $tree.Temp ('praexo_' + ('ef' * 16) + '.started')) 'someone else' 0 30 + $badName = New-E334File (Join-Path $tree.Temp 'praexo_notahexid.started') '1' 0 30 + $notJson = New-E334File (Join-Path $tree.Temp ('praexo_' + ('12' * 16) + '.applied.json')) 'plain text' 0 30 + $folder = Join-Path $tree.Temp ('praexo_' + ('34' * 16)); $null = New-Item -ItemType Directory -Path $folder -Force + $null = New-E334File (Join-Path $folder 'child.ps1') "throw 'Invalid Exchange Online request.'" 0 30; Set-E334Age $folder 0 30 + $foreignFolder = Join-Path $tree.Temp ('praexo_' + ('56' * 16)); $null = New-Item -ItemType Directory -Path $foreignFolder -Force + $null = New-E334File (Join-Path $foreignFolder 'child.ps1') 'Write-Host hello' 0 30; Set-E334Age $foreignFolder 0 30 + $found = Get-PraCleanupCandidate -Config $tree.Config -TempFolder $tree.Temp + @($found.Items | Where-Object Kind -EQ 'ExoTemp' | ForEach-Object Path | Sort-Object) | Should -Be @(@($started, $connected, $applied, $progress, $policyMarker, $folder) | Sort-Object) + foreach ($item in $found.Items) { $item.Root | Should -BeExactly ([IO.Path]::GetFullPath($tree.Temp).TrimEnd('\')) } + $done = Invoke-PraCleanup -Config $tree.Config -Item @($found.Items) -ConfirmationWord 'cleanup' -TempFolder $tree.Temp + @($done.Deleted).Count | Should -Be 6 + foreach ($kept in $freshOne, $wrongContent, $badName, $notJson, $foreignFolder, $policyForeign) { Test-Path -LiteralPath $kept | Should -BeTrue -Because $kept } + } +} + +Describe 'Release 3.3.0 - the entry script: -Action Cleanup lists in a Preview and deletes nothing in an Apply that cannot ask for the typed word; Storage.Protect protects what the run writes and says which mode it uses (real main, synthetic AD and cloud barrier)' -Tag 'Release330E' { + It 'lists the old logs in a Preview with the table and the totals, deletes nothing, and in an Apply without a console (-Force does not replace the typed word) deletes nothing and says so' { + $runtime = New-GateRuntime -Name 'e-cleanup' + $log = Join-Path $runtime.Root 'logs\PRA_20260101_000000-aa_1a2b3c4d.log' + [IO.File]::WriteAllText($log, 'Audit: host=x'); (Get-Item -LiteralPath $log).LastWriteTimeUtc = [datetime]::UtcNow.AddDays(-120) + $stale = Join-Path $runtime.Root 'logs\preview-0123456789ab'; $null = New-Item -ItemType Directory -Path (Join-Path $stale ('Batch-' + ('a' * 32))) -Force + foreach ($item in @($stale, (Join-Path $stale ('Batch-' + ('a' * 32))))) { (Get-Item -LiteralPath $item).LastWriteTimeUtc = [datetime]::UtcNow.AddDays(-3) } + $preview = Invoke-GateProcess $runtime @{ Action = 'Cleanup'; Mode = 'Preview'; ConfigPath = $runtime.ConfigPath } -TimeoutSeconds 120 + $preview.ExitCode | Should -Be 0 + $preview.Output | Should -BeLike '*Items to clean up*2 item(s) can be deleted*' + $preview.Output | Should -Match 'Log\s+\d+\.\d\s+\d+ bytes\s+\S*PRA_20260101_000000-aa_1a2b3c4d\.log' + $preview.Output | Should -Match 'PreviewLeftover\s+\d+\.\d' + $preview.Output | Should -BeLike '*Total: 2 item(s)*' + $preview.Output | Should -BeLike '*Nothing was deleted. To delete the items listed above, run the same command with -Mode Apply*CLEANUP*' + Test-Path -LiteralPath $log | Should -BeTrue + $apply = Invoke-GateProcess $runtime @{ Action = 'Cleanup'; Mode = 'Apply'; Force = $true; ConfigPath = $runtime.ConfigPath } -TimeoutSeconds 120 + $apply.ExitCode | Should -BeIn @(0, 2) + $apply.Output | Should -BeLike '*cannot ask for the typed word*-Force does not replace it*nothing was deleted*' + Test-Path -LiteralPath $log | Should -BeTrue + Test-Path -LiteralPath $stale | Should -BeTrue + @(Get-GateWrites $runtime).Count | Should -Be 0 + } + It 'with Storage.Protect on, a Preview says which mode it will use and warns when the key is not there; an Apply stops before it writes anything; off, nothing is said' { + $runtime = New-GateRuntime -Name 'e-protect-missing' + $off = Invoke-GateProcess $runtime @{ Action = 'Convert'; Phase = 'AD'; Mode = 'Preview'; ConfigPath = $runtime.ConfigPath; SearchBase = 'OU=Gate,DC=gate,DC=invalid' } -TimeoutSeconds 120 + $off.Output | Should -Not -BeLike '*Protection of the files at rest is on*' + $off.Output | Should -Match 'Protection of the files at rest\s+off\s+\[configuration file\]' + Set-GateConfigText $runtime { param($text) $text.Replace("Execution=@{Phase='Both'}", "Execution=@{Phase='Both'}`n Storage=@{BackupFolder='$($runtime.State.BackupFolder)';Protect='CERTIFICATE';CertificateThumbprint='$('0a' * 20)'}").Replace("Storage=@{BackupFolder='$($runtime.State.BackupFolder)';ForbiddenBackupRoots=@()}", '') } + $preview = Invoke-GateProcess $runtime @{ Action = 'Convert'; Phase = 'AD'; Mode = 'Preview'; ConfigPath = $runtime.ConfigPath; SearchBase = 'OU=Gate,DC=gate,DC=invalid' } -TimeoutSeconds 120 + $preview.ExitCode | Should -BeIn @(0, 2) + $preview.Output | Should -BeLike ('*Protection of the files at rest is on (certificate ' + ('0A' * 20) + ')*Losing the key means losing those files*') + $preview.Output | Should -BeLike '*is not in CurrentUser\My or LocalMachine\My*An Apply of this run would stop before it writes anything*' + @(Get-GateWrites $runtime).Count | Should -Be 0 + $apply = Invoke-GateProcess $runtime @{ Action = 'Convert'; Phase = 'AD'; Mode = 'Apply'; Force = $true; ConfigPath = $runtime.ConfigPath } -TimeoutSeconds 120 + $apply.ExitCode | Should -Be 1 + $apply.Output | Should -BeLike '*is not in CurrentUser\My or LocalMachine\My*Nothing was written*' + @(Get-GateWrites $runtime).Count | Should -Be 0 + @(Get-ChildItem -LiteralPath $runtime.State.BackupFolder -Filter 'Convert-*.json' -Recurse -ErrorAction SilentlyContinue).Count | Should -Be 0 + } + It 'with a key file, a Convert writes protected files that the run reads back, a later Recover Preview reads them with the key, names the file and the setting when the key is gone, and still reads them when the protection is off but the key file is set' { + $runtime = New-GateRuntime -Name 'e-protect-keyfile' + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global + $keyFile = Join-Path $runtime.Root 'pra.key'; $null = New-PraAuthKeyFile -Path $keyFile + $withKey = { param($mode) Set-GateConfigText $runtime { param($text) ($text -replace "Storage=@\{[^}]*\}", "Storage=@{BackupFolder='$($runtime.State.BackupFolder)';ForbiddenBackupRoots=@();Protect='$mode';KeyFile='$keyFile'}") } } + & $withKey 'passPHRASE' + $convert = Invoke-GateProcess $runtime @{ Action = 'Convert'; Phase = 'AD'; Mode = 'Apply'; Force = $true; ConfigPath = $runtime.ConfigPath } -TimeoutSeconds 120 + $convert.ExitCode | Should -BeIn @(0, 2) -Because $convert.Output + $convert.Output | Should -BeLike '*Protection of the files at rest is on (passphrase from the key file*' + $json = @(Get-ChildItem -LiteralPath $runtime.State.BackupFolder -Filter 'Convert-*.json' -Recurse) + $json.Count | Should -Be 1 + Test-PraProtectedFile -Path $json[0].FullName | Should -BeTrue + foreach ($leaf in 'State-*.json', '*.clixml') { Test-PraProtectedFile -Path (@(Get-ChildItem -LiteralPath $json[0].DirectoryName -Filter $leaf)[0].FullName) | Should -BeTrue -Because $leaf } + [IO.File]::ReadAllText($json[0].FullName + '.sha256').Trim() | Should -BeExactly (Get-FileHash -LiteralPath $json[0].FullName -Algorithm SHA256).Hash.ToLowerInvariant() + $batch = $convert.MainResult.BatchId + $batch | Should -Not -BeNullOrEmpty + $recover = Invoke-GateProcess $runtime @{ Action = 'Recover'; Phase = 'AD'; Mode = 'Preview'; Batch = $batch; ConfigPath = $runtime.ConfigPath } -TimeoutSeconds 120 + $recover.ExitCode | Should -BeIn @(0, 2) -Because $recover.Output + $recover.Output | Should -Not -BeLike '*is protected and this run cannot read it*' + & $withKey 'Off' + $off = Invoke-GateProcess $runtime @{ Action = 'Recover'; Phase = 'AD'; Mode = 'Preview'; Batch = $batch; ConfigPath = $runtime.ConfigPath } -TimeoutSeconds 120 + $off.ExitCode | Should -BeIn @(0, 2) -Because 'a protected file is read with the key file even when the protection is off' + Set-GateConfigText $runtime { param($text) ($text -replace "Storage=@\{[^}]*\}", "Storage=@{BackupFolder='$($runtime.State.BackupFolder)';ForbiddenBackupRoots=@()}") } + $blind = Invoke-GateProcess $runtime @{ Action = 'Recover'; Phase = 'AD'; Mode = 'Preview'; Batch = $batch; ConfigPath = $runtime.ConfigPath } -TimeoutSeconds 120 + $blind.ExitCode | Should -Be 1 + $blind.Output | Should -BeLike ("*'" + $json[0].Name + "'*is protected and this run cannot read it*Storage.KeyFile*") + @(Get-GateWrites $runtime).Count | Should -BeGreaterThan 0 + } + It 'a Preview with the protection on says that the other server needs the same key; an Apply does not; a cloud-only Apply whose key file is gone stops before any cloud change' { + $runtime = New-GateRuntime -Name 'e-protect-twoservers' + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global + $keyFile = Join-Path $runtime.Root 'pra.key'; $null = New-PraAuthKeyFile -Path $keyFile + Set-GateConfigText $runtime { param($text) ($text -replace "Storage=@\{[^}]*\}", "Storage=@{BackupFolder='$($runtime.State.BackupFolder)';ForbiddenBackupRoots=@();Protect='Passphrase';KeyFile='$keyFile'}") } + $preview = Invoke-GateProcess $runtime @{ Action = 'Convert'; Phase = 'AD'; Mode = 'Preview'; ConfigPath = $runtime.ConfigPath; SearchBase = 'OU=Gate,DC=gate,DC=invalid' } -TimeoutSeconds 120 + $preview.ExitCode | Should -BeIn @(0, 2) -Because $preview.Output + $preview.Output | Should -BeLike '*With two servers, the other server reads the files that this run writes*it needs the same key*' + $convert = Invoke-GateProcess $runtime @{ Action = 'Convert'; Phase = 'AD'; Mode = 'Apply'; Force = $true; ConfigPath = $runtime.ConfigPath } -TimeoutSeconds 120 + $convert.ExitCode | Should -BeIn @(0, 2) -Because $convert.Output + $convert.Output | Should -Not -BeLike '*With two servers, the other server reads the files that this run writes*' + $batch = [string]$convert.MainResult.BatchId + $before = @(Get-GateWrites $runtime).Count + Remove-Item -LiteralPath $keyFile -Force + $cloud = Invoke-GateProcess $runtime @{ Action = 'Convert'; Phase = 'Cloud'; Mode = 'Apply'; Force = $true; ConfigPath = $runtime.ConfigPath; Batch = $batch } -TimeoutSeconds 120 + $cloud.ExitCode | Should -Be 1 -Because $cloud.Output + $cloud.Output | Should -BeLike '*Storage.KeyFile cannot be used*Nothing was written*' + @($cloud.Events | Where-Object Operation -EQ 'CloudPhase-SyntheticBarrier').Count | Should -Be 0 -Because 'the key is checked before the cloud part starts' + @(Get-GateWrites $runtime).Count | Should -Be $before + } +} + + +Describe 'Release 3.3.0 - an import that stops before the package is loaded is taken back: the files it extracted and the markers it wrote, while they are still as it left them, never what another run put there (production Common module, synthetic folders)' -Tag 'Release330G' { + BeforeAll { + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global + $script:G330Root = Join-Path $global:PraGate.Root ('undo-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) + $null = New-Item -ItemType Directory -Path $script:G330Root -Force + function script:New-G330Backups { + $backups = Join-Path $script:G330Root ([guid]::NewGuid().ToString('N').Substring(0, 6)) + $null = New-Item -ItemType Directory -Path $backups -Force + $backups + } + function script:Get-G330Sha([string]$Path) { (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash.ToLowerInvariant() } + # A folder as an import leaves it: the files of the package (name and content), and the entries that the importer reports for them. + function script:New-G330Folder { + param([string]$Backups, [string]$Name, [hashtable]$File = @{ 'file.json' = 'content' }) + $folder = Join-Path $Backups $Name + $null = New-Item -ItemType Directory -Path $folder -Force + $entries = foreach ($key in $File.Keys) { + [IO.File]::WriteAllText((Join-Path $folder $key), [string]$File[$key]) + [pscustomobject]@{ Name = ($Name + '/' + $key); Size = 1; Sha256 = (Get-G330Sha (Join-Path $folder $key)) } + } + [pscustomobject]@{ Folder = $folder; Entries = @($entries) } + } + } + It 'names the marker files of an import: the batch id in lower case as Imported\ name.txt and one verified marker per folder, whatever the letter case of the folder name' { + $backups = New-G330Backups + $id = 'A1B2C3D4E5F60718293A4B5C6D7E8F90' + $paths = @(Get-PraImportMarkerPath -BackupFolder $backups -BatchId $id -FolderPath @((Join-Path $backups ('FINALIZE-' + $id)), (Join-Path $backups ('batch-' + ('0' * 32))))) + $paths.Count | Should -Be 3 + $paths[0] | Should -BeExactly (Join-Path (Join-Path $backups 'Imported') ($id.ToLowerInvariant() + '.txt')) + $paths[1] | Should -BeExactly (Get-PraVerifiedMarkerPath -BackupFolder $backups -Id $id) + $paths[2] | Should -BeExactly (Get-PraVerifiedMarkerPath -BackupFolder $backups -Id ('0' * 32)) + } + It 'deletes the files that the import extracted and the folder once it is empty, puts back the marker that was there and deletes the one it made, and leaves the folder that was already there (the Imported folder goes only when the import made it)' -ForEach @(@{ ImportedBefore = $false }, @{ ImportedBefore = $true }) { + $backups = New-G330Backups + $idOld = 'a' * 32; $idNew = 'b' * 32 + $before = New-G330Folder $backups ('Batch-' + $idOld) @{ 'file.json' = 'older batch' } + $created = New-G330Folder $backups ('Finalize-' + $idNew) @{ 'a.json' = 'first'; 'b.json' = 'second' } + $markers = @(Get-PraImportMarkerPath -BackupFolder $backups -BatchId $idNew -FolderPath @($created.Folder, $before.Folder)) + if ($ImportedBefore) { + $null = New-Item -ItemType Directory -Path (Split-Path $markers[0] -Parent) -Force + [IO.File]::WriteAllText($markers[2], 'marker of the older batch') + } + $undo = New-PraImportUndo -BackupFolder $backups -CreatedFolder @($created.Folder) -Entry $created.Entries -MarkerPath $markers + $null = New-Item -ItemType Directory -Path (Split-Path $markers[0] -Parent) -Force + foreach ($marker in $markers) { [IO.File]::WriteAllText($marker, 'written by the import') } + Register-PraImportMarker -Undo $undo + $result = Undo-PraImport -Undo $undo + @($result.Failed).Count | Should -Be 0 + @($result.Kept).Count | Should -Be 0 + @($result.RemovedFolder) | Should -Be @($created.Folder) + Test-Path -LiteralPath $created.Folder | Should -BeFalse -Because 'the files are the ones of the import and the folder is then empty' + [IO.File]::ReadAllText((Join-Path $before.Folder 'file.json')) | Should -BeExactly 'older batch' -Because 'a folder that was there before is not in the list and is never touched' + Test-Path -LiteralPath $markers[0] | Should -BeFalse + Test-Path -LiteralPath $markers[1] | Should -BeFalse + if ($ImportedBefore) { + [IO.File]::ReadAllText($markers[2]) | Should -BeExactly 'marker of the older batch' -Because 'a marker that was there is put back as it was' + Test-Path -LiteralPath (Join-Path $backups 'Imported') | Should -BeTrue + } + else { + Test-Path -LiteralPath $markers[2] | Should -BeFalse + Test-Path -LiteralPath (Join-Path $backups 'Imported') | Should -BeFalse -Because 'the import made the Imported folder and nothing else is in it' + } + } + It 'keeps what another run added to the folder after the import: its files stay, the extracted files go, the folder stays and is named in Kept' { + $backups = New-G330Backups + $created = New-G330Folder $backups ('Batch-' + ('c' * 32)) @{ 'Convert.json' = 'batch'; 'Convert.json.sha256' = 'sum' } + $undo = New-PraImportUndo -BackupFolder $backups -CreatedFolder @($created.Folder) -Entry $created.Entries + [IO.File]::WriteAllText((Join-Path $created.Folder ('Journal-' + ('c' * 32) + '.jsonl')), 'written by a run that accepted the folder as already present') + $null = New-Item -ItemType Directory -Path (Join-Path $created.Folder 'cloud') -Force + [IO.File]::WriteAllText((Join-Path $created.Folder 'cloud\CloudDone.json'), 'cloud record') + $result = Undo-PraImport -Undo $undo + @($result.Failed).Count | Should -Be 0 + @($result.RemovedFolder).Count | Should -Be 0 + @($result.Kept) | Should -Contain $created.Folder + Test-Path -LiteralPath (Join-Path $created.Folder 'Convert.json') | Should -BeFalse -Because 'the extracted files are still as the import left them' + Test-Path -LiteralPath (Join-Path $created.Folder 'Convert.json.sha256') | Should -BeFalse + [IO.File]::ReadAllText((Join-Path $created.Folder ('Journal-' + ('c' * 32) + '.jsonl'))) | Should -BeLike 'written by a run*' + [IO.File]::ReadAllText((Join-Path $created.Folder 'cloud\CloudDone.json')) | Should -BeExactly 'cloud record' + } + It 'keeps an extracted file that another run changed, removes the sub-folder that the import left empty, and removes the folder when only its own files were in it' { + $backups = New-G330Backups + $created = New-G330Folder $backups ('Finalize-' + ('d' * 32)) @{ 'a.json' = 'first'; 'b.json' = 'second' } + $undo = New-PraImportUndo -BackupFolder $backups -CreatedFolder @($created.Folder) -Entry $created.Entries + [IO.File]::WriteAllText((Join-Path $created.Folder 'b.json'), 'second, changed') + $null = New-Item -ItemType Directory -Path (Join-Path $created.Folder 'empty\deeper') -Force + $result = Undo-PraImport -Undo $undo + @($result.Kept) | Should -Contain (Join-Path $created.Folder 'b.json') + @($result.Kept) | Should -Contain $created.Folder + Test-Path -LiteralPath (Join-Path $created.Folder 'a.json') | Should -BeFalse + Test-Path -LiteralPath (Join-Path $created.Folder 'empty') | Should -BeFalse -Because 'the empty folders are removed bottom-up' + [IO.File]::ReadAllText((Join-Path $created.Folder 'b.json')) | Should -BeExactly 'second, changed' + } + It 'does not touch a marker that someone else rewrote after the import, and says so; a marker that is gone stays gone' { + $backups = New-G330Backups + $id = 'e' * 32 + $markers = @(Get-PraImportMarkerPath -BackupFolder $backups -BatchId $id -FolderPath @((Join-Path $backups ('Finalize-' + $id)))) + $undo = New-PraImportUndo -BackupFolder $backups -MarkerPath $markers + $null = New-Item -ItemType Directory -Path (Split-Path $markers[0] -Parent) -Force + [IO.File]::WriteAllText($markers[0], 'written by the import') + [IO.File]::WriteAllText($markers[1], 'written by the import') + Register-PraImportMarker -Undo $undo + [IO.File]::WriteAllText($markers[0], 'rewritten by another run') + Remove-Item -LiteralPath $markers[1] -Force + $result = Undo-PraImport -Undo $undo + @($result.Failed).Count | Should -Be 0 + @($result.Kept) | Should -Contain $markers[0] + [IO.File]::ReadAllText($markers[0]) | Should -BeExactly 'rewritten by another run' + Test-Path -LiteralPath $markers[1] | Should -BeFalse + Test-Path -LiteralPath (Join-Path $backups 'Imported') | Should -BeTrue -Because 'a folder that holds a file is not removed' + } + It 'does not touch a marker that was never registered as written by the import' { + $backups = New-G330Backups + $markers = @(Get-PraImportMarkerPath -BackupFolder $backups -BatchId ('f' * 32)) + $undo = New-PraImportUndo -BackupFolder $backups -MarkerPath $markers + $null = New-Item -ItemType Directory -Path (Split-Path $markers[0] -Parent) -Force + [IO.File]::WriteAllText($markers[0], 'someone else') + $null = Undo-PraImport -Undo $undo + [IO.File]::ReadAllText($markers[0]) | Should -BeExactly 'someone else' + } + It 'refuses to delete a folder that is outside the backup folder or is not named like a batch, and says which' { + $backups = New-G330Backups + $outside = New-G330Folder $script:G330Root ('Batch-' + ('c' * 32)) + $other = New-G330Folder $backups 'Inbox' + $undo = New-PraImportUndo -BackupFolder $backups -CreatedFolder @($outside.Folder, $other.Folder) -Entry @($outside.Entries + $other.Entries) + $result = Undo-PraImport -Undo $undo + @($result.Failed).Count | Should -Be 2 + Test-Path -LiteralPath (Join-Path $outside.Folder 'file.json') | Should -BeTrue + Test-Path -LiteralPath (Join-Path $other.Folder 'file.json') | Should -BeTrue + } + It 'removes a link that stands where a created folder was, not what the link points to' { + $backups = New-G330Backups + $target = New-G330Folder $script:G330Root ('target-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) @{ 'file.json' = 'precious' } + $link = Join-Path $backups ('Batch-' + ('d' * 32)) + try { $null = New-Item -ItemType Junction -Path $link -Target $target.Folder -ErrorAction Stop } catch { Set-ItResult -Skipped -Because 'a junction cannot be made here'; return } + $undo = New-PraImportUndo -BackupFolder $backups -CreatedFolder @($link) + $result = Undo-PraImport -Undo $undo + @($result.Failed).Count | Should -Be 0 + Test-Path -LiteralPath $link | Should -BeFalse + [IO.File]::ReadAllText((Join-Path $target.Folder 'file.json')) | Should -BeExactly 'precious' + } + It 'never throws, even when a file is held open: the file that cannot be removed is reported' { + $backups = New-G330Backups + $created = New-G330Folder $backups ('Batch-' + ('e' * 32)) + $undo = New-PraImportUndo -BackupFolder $backups -CreatedFolder @($created.Folder) -Entry $created.Entries + $held = [IO.File]::Open((Join-Path $created.Folder 'file.json'), [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::None) + try { + $result = $null + try { $result = Undo-PraImport -Undo $undo } catch { $null = $_ } + $result | Should -Not -BeNullOrEmpty -Because 'the function does not throw' + (@($result.Failed) + @($result.Kept)).Count | Should -BeGreaterThan 0 + Test-Path -LiteralPath $created.Folder | Should -BeTrue + } + finally { $held.Dispose() } + } +} + + +Describe 'Release 3.3.0 - the entry script: a package that is refused at its loading leaves nothing in the backup folder, and a leftover folder of the same batch says where it is and what to run (real main, production Directory module, synthetic AD and cloud barrier)' -Tag 'Release330G' { + BeforeAll { + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global + function script:Get-G330Why($Run) { (@(([string]$Run.Output + [string]$Run.Error) -split '\r?\n' | Where-Object { $_ -match 'Stopped at step|refused|Nothing was|cannot|failed|Error' } | Select-Object -First 8) -join ' | ') } + function script:Get-G330Flat($Run) { [regex]::Replace([string]$Run.Output, '\s+', ' ') } + # The Finalize package of the cloud server, made from a folder of the files of the Recover batch; -Tamper changes the Convert backup in it and writes its checksum file again, so that every checksum of the package is right. + function script:New-G330Package { + param($Runtime, $Bundles, [string]$Id, [string]$Out, [switch]$Tamper, [string]$Prefix = 'Finalize-') + $stage = Join-Path (Join-Path $Runtime.Root ('stage-' + [guid]::NewGuid().ToString('N').Substring(0, 6))) ($Prefix + $Id) + $null = New-Item -ItemType Directory -Path $stage -Force + foreach ($file in @(Get-ChildItem -LiteralPath (Split-Path $Bundles.Recover -Parent) -File | Where-Object { $_.Name -notlike 'Journal-*' })) { Copy-Item -LiteralPath $file.FullName -Destination $stage } + if ($Tamper) { + $backup = @(Get-ChildItem -LiteralPath $stage -File -Filter 'Convert-*.json')[0].FullName + [IO.File]::AppendAllText($backup, ' ') + [IO.File]::WriteAllText($backup + '.sha256', (Get-FileHash -LiteralPath $backup -Algorithm SHA256).Hash.ToLowerInvariant()) + } + (New-PraTransferPackage -Kind Finalize -Environment SYNTHETIC_GATE -BatchId $Id -Folders @($stage) -OutboxFolder $Out).Path + } + } + BeforeEach { + $runtime = New-GateRuntime -Name 'refused-330g' + $env:PRA_GATE_STATE = $runtime.StatePath + $env:PSModulePath = $runtime.Modules + ';' + (Join-Path $PSHOME 'Modules') + Remove-Module PRA.Directory -Force -ErrorAction SilentlyContinue + Get-Module ActiveDirectory -All | Remove-Module -Force -ErrorAction Stop + Import-Module (Join-Path $runtime.Modules 'ActiveDirectory\ActiveDirectory.psm1') -Force -Global + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Directory.psm1') -Force -Global + $context = New-GateContext $runtime + $bundles = New-GateSourceBundles $context + Remove-Item -LiteralPath $runtime.EventPath -Force -ErrorAction SilentlyContinue + $id = [guid]::NewGuid().ToString('N') + $good = New-G330Package $runtime $bundles $id (Join-Path $runtime.Root 'good') + $bad = New-G330Package $runtime $bundles $id (Join-Path $runtime.Root 'bad') -Tamper + $backups = $runtime.State.BackupFolder + $arguments = { param($zip, $mode) @{Action='Finalize';Mode=$mode;Force=$true;ConfigPath=$runtime.ConfigPath;Batch=$zip} } + } + AfterAll { Remove-Item -LiteralPath 'Function:\Get-G330Why', 'Function:\Get-G330Flat', 'Function:\New-G330Package' -ErrorAction SilentlyContinue } + It 'refuses an altered Convert backup with re-computed checksums at the loading, says that the proof does not match this backup, and leaves no folder and no marker; the genuine package is then imported' { + $refused = Invoke-GateProcess $runtime (& $arguments $bad 'Apply') + $refused.ExitCode | Should -Be 1 -Because (Get-G330Why $refused) + (Get-G330Flat $refused) | Should -Match "Stopped at step 'Loading the Finalize package'" + ($refused.MainResult.Issues.Message -join ' ') | Should -Match 'The AD proof does not match this Convert backup: the backup was changed after the proof was made, or the proof belongs to another Convert batch\. Do not use these files: copy the transfer package again from the server that wrote it and compare its fingerprint with the one that server printed \(-ExpectedFingerprint\)\.' + ($refused.MainResult.Issues.Message -join ' ') | Should -Not -Match 'built from another Convert batch' + (Get-G330Flat $refused) | Should -Match 'The package was taken back: the run stopped before it loaded it' + Test-Path -LiteralPath (Join-Path $backups ('Finalize-' + $id)) | Should -BeFalse + Test-Path -LiteralPath (Join-Path $backups 'Imported') | Should -BeFalse + @(Get-GateWrites $runtime).Count | Should -Be 0 + $accepted = Invoke-GateProcess $runtime (& $arguments $good 'Apply') + (Get-G330Flat $accepted) | Should -Match 'verified \(checksums, Environment, names\): 1 folder\(s\) extracted, 0 already present and identical' -Because (Get-G330Why $accepted) + (Get-G330Flat $accepted) | Should -Not -Match 'already exists and is different' + Test-Path -LiteralPath (Join-Path $backups ('Finalize-' + $id)) -PathType Container | Should -BeTrue + Test-Path -LiteralPath (Join-Path (Join-Path $backups 'Imported') ($id + '.txt')) | Should -BeTrue + } + It 'leaves what was there before the refused run as it was: a marker of an earlier import is put back byte for byte' { + $null = New-Item -ItemType Directory -Path (Join-Path $backups 'Imported') -Force + $marker = Join-Path (Join-Path $backups 'Imported') ($id + '.txt') + [IO.File]::WriteAllText($marker, 'an earlier import') + $refused = Invoke-GateProcess $runtime (& $arguments $bad 'Apply') + $refused.ExitCode | Should -Be 1 -Because (Get-G330Why $refused) + [IO.File]::ReadAllText($marker) | Should -BeExactly 'an earlier import' + Test-Path -LiteralPath (Join-Path $backups ('Finalize-' + $id)) | Should -BeFalse + Test-Path -LiteralPath (Get-PraVerifiedMarkerPath -BackupFolder $backups -Id $id) | Should -BeFalse + } + It 'a Preview of the altered package is refused the same way and writes nothing to the backup folder' { + $refused = Invoke-GateProcess $runtime (& $arguments $bad 'Preview') + $refused.ExitCode | Should -Be 1 -Because (Get-G330Why $refused) + ($refused.MainResult.Issues.Message -join ' ') | Should -Match 'The AD proof does not match this Convert backup' + Test-Path -LiteralPath (Join-Path $backups ('Finalize-' + $id)) | Should -BeFalse + Test-Path -LiteralPath (Join-Path $backups 'Imported') | Should -BeFalse + } + It 'a folder of the same batch that is not the package is refused with its name, a command that moves it aside, and the command to run again; it is never deleted or changed' { + $leftover = Join-Path $backups ('Finalize-' + $id) + $null = New-Item -ItemType Directory -Path $leftover -Force + [IO.File]::WriteAllText((Join-Path $leftover 'from-a-refused-import.json'), 'x') + $refused = Invoke-GateProcess $runtime (& $arguments $good 'Apply') + $refused.ExitCode | Should -Be 1 -Because (Get-G330Why $refused) + ($refused.MainResult.Issues.Message -join ' ') | Should -Match 'already exists and is different from the package: refused \(nothing was changed\)' + $next = @($refused.MainResult.NextSteps) + $next[0] | Should -BeLike ('The folder ' + $leftover + ' is already in the backup folder and is not the package you gave*Nothing was changed.') + $next[1] | Should -BeLike 'Look at it first. If you did not put it there on purpose, move it aside (nothing is deleted*' + $next[2] | Should -Match ('^Move-Item -LiteralPath ''' + [regex]::Escape($leftover) + ''' -Destination ''' + [regex]::Escape((Join-Path $backups ('Refused-Finalize-' + $id + '-'))) + '\d{14}''$') + $next[3] | Should -Match ('^\.\\Invoke-PraRemoteMailbox\.ps1 -Action Finalize -Mode Apply -Batch ''' + [regex]::Escape($good) + '''') + [IO.File]::ReadAllText((Join-Path $leftover 'from-a-refused-import.json')) | Should -BeExactly 'x' + Invoke-Expression $next[2] + Test-Path -LiteralPath $leftover | Should -BeFalse + @(Get-ChildItem -LiteralPath $backups -Directory -Filter 'Refused-*').Count | Should -Be 1 + $again = Invoke-GateProcess $runtime (& $arguments $good 'Apply') + (Get-G330Flat $again) | Should -Match 'verified \(checksums, Environment, names\): 1 folder\(s\) extracted' -Because (Get-G330Why $again) + } + It 'names the leftover folder whatever the letter case of the folder in the package (the operator types and carries names in any case)' { + $upper = New-G330Package $runtime $bundles $id (Join-Path $runtime.Root 'upper') -Prefix 'FINALIZE-' + $leftover = Join-Path $backups ('Finalize-' + $id) + $null = New-Item -ItemType Directory -Path $leftover -Force + [IO.File]::WriteAllText((Join-Path $leftover 'other.json'), 'x') + $refused = Invoke-GateProcess $runtime (& $arguments $upper 'Apply') + $refused.ExitCode | Should -Be 1 -Because (Get-G330Why $refused) + $next = @($refused.MainResult.NextSteps) + $next[0] | Should -BeLike ('The folder ' + (Join-Path $backups ('FINALIZE-' + $id)) + ' is already in the backup folder*') + $next[2] | Should -BeLike ('Move-Item -LiteralPath ''' + (Join-Path $backups ('FINALIZE-' + $id)) + '''*') + Invoke-Expression $next[2] + Test-Path -LiteralPath (Join-Path $leftover 'other.json') | Should -BeFalse + } + It 'keeps the extracted package once it is loaded, when the run then stops at the confirmation that this console cannot ask' { + $kept = Invoke-GateProcess $runtime @{Action='Finalize';Mode='Apply';ConfigPath=$runtime.ConfigPath;Batch=$good} + $kept.ExitCode | Should -Be 1 -Because (Get-G330Why $kept) + (Get-G330Flat $kept) | Should -Match 'verified \(checksums, Environment, names\): 1 folder\(s\) extracted' + (Get-G330Flat $kept) | Should -Match 'proofs verified' -Because 'the package was loaded before the run stopped' + (Get-G330Flat $kept) | Should -Not -Match 'The package was taken back' + Test-Path -LiteralPath (Join-Path $backups ('Finalize-' + $id)) -PathType Container | Should -BeTrue + Test-Path -LiteralPath (Join-Path (Join-Path $backups 'Imported') ($id + '.txt')) | Should -BeTrue + Test-Path -LiteralPath (Get-PraVerifiedMarkerPath -BackupFolder $backups -Id $id) | Should -BeTrue + @(Get-GateWrites $runtime).Count | Should -Be 0 + } + It 'keeps the extracted package once it is loaded, when an object is no longer as the proof left it and the plan is refused' { + $runtime.State.Users[0] | Add-Member -NotePropertyName targetAddress -NotePropertyValue 'SMTP:changed-since-the-proof@gate.invalid' -Force + [IO.File]::WriteAllText($runtime.StatePath, [Management.Automation.PSSerializer]::Serialize($runtime.State, 35)) + $kept = Invoke-GateProcess $runtime (& $arguments $good 'Apply') + $kept.ExitCode | Should -Be 1 -Because (Get-G330Why $kept) + (Get-G330Flat $kept) | Should -Match 'proofs verified' + (Get-G330Flat $kept) | Should -Not -Match 'The package was taken back' + Test-Path -LiteralPath (Join-Path $backups ('Finalize-' + $id)) -PathType Container | Should -BeTrue + Test-Path -LiteralPath (Join-Path (Join-Path $backups 'Imported') ($id + '.txt')) | Should -BeTrue + } + It 'keeps the extracted package once it is loaded, when the run is stopped (Ctrl+C) while it plans, before the confirmation' { + $runtime.State.Case = 'InterruptRead' + [IO.File]::WriteAllText($runtime.StatePath, [Management.Automation.PSSerializer]::Serialize($runtime.State, 35)) + $kept = Invoke-GateProcess $runtime (& $arguments $good 'Apply') + $kept.ExitCode | Should -Be 1 -Because (Get-G330Why $kept) + (Get-G330Flat $kept) | Should -Match 'the run was interrupted before it finished' + (Get-G330Flat $kept) | Should -Match 'proofs verified' -Because 'the package was loaded before the stop' + (Get-G330Flat $kept) | Should -Not -Match 'The package was taken back' + Test-Path -LiteralPath (Join-Path $backups ('Finalize-' + $id)) -PathType Container | Should -BeTrue + Test-Path -LiteralPath (Join-Path (Join-Path $backups 'Imported') ($id + '.txt')) | Should -BeTrue + } + It 'a package that is taken back leaves no message about its folder that is gone: the report data of the run is not written to it' { + $refused = Invoke-GateProcess $runtime (& $arguments $bad 'Apply') + $refused.ExitCode | Should -Be 1 -Because (Get-G330Why $refused) + Test-Path -LiteralPath (Join-Path $backups ('Finalize-' + $id)) | Should -BeFalse + $log = (@(Get-ChildItem -LiteralPath (Join-Path $runtime.Root 'logs') -Filter '*.log' -File) | ForEach-Object { [IO.File]::ReadAllText($_.FullName) }) -join [Environment]::NewLine + $log | Should -Match 'The package was taken back' + $log | Should -Not -Match 'could not be saved|folder not found|Could not find|n.existe pas' + Test-Path -LiteralPath (Join-Path $backups ('Finalize-' + $id)) | Should -BeFalse + } +} + + +Describe 'Release 3.3.0 - the entry script: the cloud server takes back an altered Convert package that it refused, and the fingerprint is in the next steps of the AD server (real main, production Directory module, synthetic AD and cloud barrier)' -Tag 'Release330G' { + BeforeAll { + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global + function script:Get-G330Why($Run) { (@(([string]$Run.Output + [string]$Run.Error) -split '\r?\n' | Where-Object { $_ -match 'Stopped at step|refused|Nothing was|cannot|failed|Error' } | Select-Object -First 8) -join ' | ') } + function script:Get-G330Flat($Run) { [regex]::Replace([string]$Run.Output, '\s+', ' ') } + # The Convert package of the AD server, unpacked, its Convert backup changed with its checksum file written again, and packed again: every checksum of the package is right. + function script:New-G330ConvertPackage { + param($Runtime, [string]$Zip, [string]$Out) + $info = Get-PraTransferPackage -Path $Zip -Environment SYNTHETIC_GATE + $work = Join-Path $Runtime.Root ('unpack-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) + [IO.Compression.ZipFile]::ExtractToDirectory($Zip, $work) + $folder = @(Get-ChildItem -LiteralPath $work -Directory -Filter 'Batch-*')[0].FullName + $backup = @(Get-ChildItem -LiteralPath $folder -File -Filter 'Convert-*.json')[0].FullName + [IO.File]::AppendAllText($backup, ' ') + [IO.File]::WriteAllText($backup + '.sha256', (Get-FileHash -LiteralPath $backup -Algorithm SHA256).Hash.ToLowerInvariant()) + (New-PraTransferPackage -Kind Convert -Environment SYNTHETIC_GATE -BatchId $info.BatchId -Folders @($folder) -OutboxFolder $Out).Path + } + } + BeforeEach { + Add-Type -AssemblyName System.IO.Compression.FileSystem + $runtime = New-GateRuntime -Name 'cloud-330g' + $env:PRA_GATE_STATE = $runtime.StatePath + $env:PSModulePath = $runtime.Modules + ';' + (Join-Path $PSHOME 'Modules') + Remove-Module PRA.Directory -Force -ErrorAction SilentlyContinue + Get-Module ActiveDirectory -All | Remove-Module -Force -ErrorAction Stop + Import-Module (Join-Path $runtime.Modules 'ActiveDirectory\ActiveDirectory.psm1') -Force -Global + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Directory.psm1') -Force -Global + $made = Invoke-GateProcess $runtime @{Action='Convert';Phase='AD';Mode='Apply';Force=$true;ConfigPath=$runtime.ConfigPath} -TimeoutSeconds 120 + $made.ExitCode | Should -Be 2 -Because (Get-G330Why $made) + $zip = [string]$made.MainResult.TransferPackage + $cloud = New-GateRuntime -Name 'cloud-side-330g' + } + AfterAll { Remove-Item -LiteralPath 'Function:\Get-G330Why', 'Function:\Get-G330Flat', 'Function:\New-G330ConvertPackage' -ErrorAction SilentlyContinue } + It 'writes the fingerprint of the package and the command with -ExpectedFingerprint in the next steps of the AD server, and that command is accepted on the other server' { + $info = Get-PraTransferPackage -Path $zip -Environment SYNTHETIC_GATE + $all = @($made.MainResult.NextSteps) + $next = @($all | Select-Object -Last 4) + $all.Count | Should -BeIn @(4, 5) -Because ($all -join " || ") + $next[0] | Should -BeLike 'Copy these two files, together in the same folder, to the cloud server (anywhere): *.zip and *.zip.sha256. Then run there:' + $next[1] | Should -Match '^\.\\Invoke-PraRemoteMailbox\.ps1 -Action Convert -Phase Cloud -Mode Apply -Batch ''[^'']+\.zip''$' + $next[2] | Should -BeExactly ('The fingerprint of this package is {0}. Read it to the operator of the cloud server by another channel than the one the package travels on; there, add -ExpectedFingerprint so that the import refuses any other package:' -f $info.Fingerprint) + $next[3] | Should -BeExactly ($next[1] + ' -ExpectedFingerprint ' + $info.Fingerprint) + $inbox = Join-Path $cloud.State.BackupFolder 'Inbox'; $null = New-Item -ItemType Directory -Path $inbox -Force + Copy-Item -LiteralPath $zip, ($zip + '.sha256') -Destination $inbox + # The command line is run as printed: its words are read back from the text (the harness adds only the configuration file and -Force, which a run without a console needs). + $tokens = [Management.Automation.Language.Parser]::ParseInput($next[3], [ref]$null, [ref]$null).Find({ param($n) $n -is [Management.Automation.Language.CommandAst] }, $true).CommandElements + $parsed = @{} + for ($position = 1; $position -lt $tokens.Count; $position++) { + if ($tokens[$position] -isnot [Management.Automation.Language.CommandParameterAst]) { continue } + $parsed[$tokens[$position].ParameterName] = [string]$tokens[$position + 1].Value + } + @($parsed.Keys | Sort-Object) | Should -Be @('Action', 'Batch', 'ExpectedFingerprint', 'Mode', 'Phase') + $parsed.Batch | Should -BeExactly ([IO.Path]::GetFileName($zip)) -Because 'the printed command names the file, as the operator types it' + $parsed.ExpectedFingerprint | Should -BeExactly $info.Fingerprint + $accepted = Invoke-GateProcess $cloud ($parsed + @{ConfigPath=$cloud.ConfigPath;Force=$true}) -TimeoutSeconds 120 + $accepted.ExitCode | Should -BeIn @(0, 2) -Because (Get-G330Why $accepted) + (Get-G330Flat $accepted) | Should -Match 'is the one given with -ExpectedFingerprint' + (Get-G330Flat $accepted) | Should -Not -Match 'Stopped at step' + $other = $parsed.Clone(); $other.ExpectedFingerprint = '0000-0000-0000-0000-0000'; $other.ConfigPath = $cloud.ConfigPath; $other.Force = $true + $wrong = Invoke-GateProcess $cloud $other -TimeoutSeconds 120 + $wrong.ExitCode | Should -Be 1 + } + It 'keeps what it extracted when a Convert -Phase AD -Batch package fails after its loading: the confirmation cannot be asked' { + $other = New-GateRuntime -Name 'ad-batch-330g' + $env:PRA_GATE_STATE = $other.StatePath + $inbox = Join-Path $other.State.BackupFolder 'Inbox'; $null = New-Item -ItemType Directory -Path $inbox -Force + Copy-Item -LiteralPath $zip, ($zip + '.sha256') -Destination $inbox + $kept = Invoke-GateProcess $other @{Action='Convert';Phase='AD';Mode='Apply';ConfigPath=$other.ConfigPath;Batch=[IO.Path]::GetFileName($zip)} -TimeoutSeconds 120 + $kept.ExitCode | Should -Be 1 -Because (Get-G330Why $kept) + (Get-G330Flat $kept) | Should -Match 'AD changes already made and verified \(they are not changed again\), backup and proof checked' -Because 'the batch was loaded before the run stopped' + (Get-G330Flat $kept) | Should -Not -Match 'The package was taken back' + $batchId = (Get-PraTransferPackage -Path $zip -Environment SYNTHETIC_GATE).BatchId + Test-Path -LiteralPath (Join-Path $other.State.BackupFolder ('Batch-' + $batchId)) -PathType Container | Should -BeTrue + Test-Path -LiteralPath (Join-Path (Join-Path $other.State.BackupFolder 'Imported') ($batchId + '.txt')) | Should -BeTrue + } + It 'keeps both folders of a Recover package when the cloud phase fails after its loading: the confirmation cannot be asked' { + $recover = Invoke-GateProcess $runtime @{Action='Recover';Phase='AD';Mode='Apply';Force=$true;ConfigPath=$runtime.ConfigPath;Batch=[string]$made.MainResult.BatchId} -TimeoutSeconds 120 + $recover.ExitCode | Should -Be 2 -Because (Get-G330Why $recover) + $package = [string]$recover.MainResult.TransferPackage + $info = Get-PraTransferPackage -Path $package -Environment SYNTHETIC_GATE + @($info.Folders).Count | Should -Be 2 -Because 'a Recover package carries the Recover batch and the Convert batch it rolled back' + $inbox = Join-Path $cloud.State.BackupFolder 'Inbox'; $null = New-Item -ItemType Directory -Path $inbox -Force + Copy-Item -LiteralPath $package, ($package + '.sha256') -Destination $inbox + $kept = Invoke-GateProcess $cloud @{Action='Recover';Phase='Cloud';Mode='Apply';ConfigPath=$cloud.ConfigPath;Batch=[IO.Path]::GetFileName($package)} -TimeoutSeconds 120 + $kept.ExitCode | Should -Be 1 -Because (Get-G330Why $kept) + (Get-G330Flat $kept) | Should -Match 'verified \(checksums, Environment, names\): 2 folder\(s\) extracted' + (Get-G330Flat $kept) | Should -Match ', AD proof verified' -Because 'the batch was loaded before the run stopped' + (Get-G330Flat $kept) | Should -Not -Match 'The package was taken back' + foreach ($folder in @($info.Folders)) { Test-Path -LiteralPath (Join-Path $cloud.State.BackupFolder ([string]$folder)) -PathType Container | Should -BeTrue -Because ([string]$folder) } + Test-Path -LiteralPath (Join-Path (Join-Path $cloud.State.BackupFolder 'Imported') ($info.BatchId + '.txt')) | Should -BeTrue + } + It 'refuses a Convert package whose backup was altered (checksums written again) at the loading of the cloud phase, with the new message, and leaves nothing in its backup folder' { + $altered = New-G330ConvertPackage $runtime $zip (Join-Path $cloud.Root 'drop') + $before = @(Get-GateWrites $cloud).Count + $refused = Invoke-GateProcess $cloud @{Action='Convert';Phase='Cloud';Mode='Apply';Force=$true;ConfigPath=$cloud.ConfigPath;Batch=$altered} -TimeoutSeconds 120 + $refused.ExitCode | Should -Be 1 -Because (Get-G330Why $refused) + ($refused.MainResult.Issues.Message -join ' ') | Should -Match 'The AD proof does not match its backup: the backup was changed or does not belong to this proof\. Do not use these files: copy the transfer package again from the server that wrote it' + (Get-G330Flat $refused) | Should -Match 'The package was taken back: the run stopped before it loaded it' + @(Get-ChildItem -LiteralPath $cloud.State.BackupFolder -Directory -ErrorAction SilentlyContinue | Where-Object Name -Like 'Batch-*').Count | Should -Be 0 + Test-Path -LiteralPath (Join-Path $cloud.State.BackupFolder 'Imported') | Should -BeFalse + @(Get-GateWrites $cloud).Count | Should -Be $before + } +} + + +Describe 'Release 3.3.0 - the retention check of a Recover is not asked for a run that changes nothing in Active Directory, and is asked in full as soon as one object is not yet rolled back (real main, production Directory module, synthetic AD and cloud barrier)' -Tag 'Release330G' { + BeforeAll { + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global + function script:Get-G330Flat($Run) { [regex]::Replace([string]$Run.Output, '\s+', ' ') } + function script:Get-G330Why($Run) { (@(([string]$Run.Output + [string]$Run.Error) -split '\r?\n' | Where-Object { $_ -match 'Stopped at step|refused|Nothing was|cannot|failed|Error' } | Select-Object -First 8) -join ' | ') } + # The directory as a Convert leaves it, for the objects of the batch listed in -Index (the others stay as they were). + function script:Set-G330Converted { + param($Runtime, $Bundles, [int[]]$Index) + $module = Get-Module PRA.Directory + $members = New-Object Collections.Generic.List[string] + foreach ($member in @($Runtime.State.Group.member)) { if ($member) { $members.Add([string]$member) } } + foreach ($position in $Index) { + $plan = $Bundles.Plans[$position] + $user = @($Runtime.State.Users | Where-Object ObjectGUID -eq $plan.Record.ObjectGuid)[0] + foreach ($key in $plan.Kinds.Keys) { $user.$key = & $module { param($state) ConvertFrom-PraStoredValue $state } $plan.Desired[$key] } + $user.uSNChanged = [long]101 + if (-not $members.Contains([string]$user.DistinguishedName)) { $members.Add([string]$user.DistinguishedName) } + } + $Runtime.State.Group.member = @($members.ToArray()) + [IO.File]::WriteAllText($Runtime.StatePath, [Management.Automation.PSSerializer]::Serialize($Runtime.State, 35)) + } + } + BeforeEach { + $runtime = New-GateRuntime -Name 'rolled-330g' + $env:PRA_GATE_STATE = $runtime.StatePath + $env:PSModulePath = $runtime.Modules + ';' + (Join-Path $PSHOME 'Modules') + Remove-Module PRA.Directory -Force -ErrorAction SilentlyContinue + Get-Module ActiveDirectory -All | Remove-Module -Force -ErrorAction Stop + Import-Module (Join-Path $runtime.Modules 'ActiveDirectory\ActiveDirectory.psm1') -Force -Global + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Directory.psm1') -Force -Global + $context = New-GateContext $runtime + $bundles = New-GateSourceBundles $context + Remove-Item -LiteralPath $runtime.EventPath -Force -ErrorAction SilentlyContinue + $runtime.State.Case = 'RetentionUnverified' + $arguments = @{Action='Recover';Phase='AD';Force=$true;ConfigPath=$runtime.ConfigPath;Batch=$bundles.Source} + } + AfterAll { Remove-Item -LiteralPath 'Function:\Get-G330Flat', 'Function:\Get-G330Why', 'Function:\Set-G330Converted' -ErrorAction SilentlyContinue } + It 'a batch whose objects are all back in the state of the backup is not held by the retention check: the Preview proposes the Apply, and the Apply goes on without -AcceptRetentionRisk' { + Set-G330Converted $runtime $bundles -Index @() + $preview = Invoke-GateProcess $runtime -Certificate ($arguments + @{Mode='Preview'}) + $preview.ExitCode | Should -Be 0 -Because (Get-G330Why $preview) + @($preview.Events | Where-Object Operation -eq 'RetentionGate-SyntheticBarrier').Count | Should -Be 0 -Because 'a run with a certificate sign-in would have asked Exchange Online, and it asked nothing' + (Get-G330Flat $preview) | Should -Match 'Retention: this Recover changes nothing in Active Directory \(the 2 object\(s\) are already in the state of the backup\), so it removes no mailbox from Exchange Online and there is no retention to check\. A rollback that is only partly done is checked in full\.' + ($preview.MainResult.NextSteps -join "`n") | Should -Not -Match 'would be refused' + $apply = Invoke-GateProcess $runtime -Certificate ($arguments + @{Mode='Apply'}) + $apply.ExitCode | Should -Be 2 -Because 'a Recover in the AD phase that ends with its transfer package is done and waits for the cloud server' + @($apply.Events | Where-Object Operation -eq 'RetentionGate-SyntheticBarrier').Count | Should -Be 0 + @($apply.Events | Where-Object Operation -like 'Connect*').Count | Should -Be 0 + (Get-G330Flat $apply) | Should -Not -Match 'Recover stopped before any change' + @($apply.MainResult.ConfigOverrides | Where-Object { $_ -match 'AcceptRetentionRisk' }).Count | Should -Be 0 + } + It 'a batch with one object still converted is checked in full: the Preview says that the Apply would be refused, the Apply stops before any change' { + Set-G330Converted $runtime $bundles -Index @(0) + $preview = Invoke-GateProcess $runtime ($arguments + @{Mode='Preview'}) + $preview.ExitCode | Should -Be 0 -Because (Get-G330Why $preview) + (Get-G330Flat $preview) | Should -Not -Match 'this Recover changes nothing in Active Directory' + ($preview.MainResult.NextSteps -join "`n") | Should -Match 'The Apply would be refused as things stand' + $asked = Invoke-GateProcess $runtime -Certificate ($arguments + @{Mode='Preview'}) + $asked.ExitCode | Should -Be 0 -Because (Get-G330Why $asked) + @($asked.Events | Where-Object Operation -eq 'RetentionGate-SyntheticBarrier').Count | Should -Be 1 -Because 'with one object to restore the retention of both is asked of Exchange Online' + $writes = @(Get-GateWrites $runtime).Count + $apply = Invoke-GateProcess $runtime ($arguments + @{Mode='Apply'}) + $apply.ExitCode | Should -Be 1 + ($apply.MainResult.Issues.Message -join ' ') | Should -Match 'Recover stopped before any change' + @(Get-GateWrites $runtime).Count | Should -Be $writes + } + It 'a batch whose objects are all still converted is checked in full, as before' { + Set-G330Converted $runtime $bundles -Index @(0, 1) + $apply = Invoke-GateProcess $runtime ($arguments + @{Mode='Apply'}) + $apply.ExitCode | Should -Be 1 + ($apply.MainResult.Issues.Message -join ' ') | Should -Match 'Recover stopped before any change' + (Get-G330Flat $apply) | Should -Not -Match 'this Recover changes nothing in Active Directory' + } + It 'tells a plan that changes something from one that does not ()' -ForEach @( + @{ Name = 'a string that is the same'; Kind = 'String'; Before = @{ Present = $true; Kind = 'String'; Value = 'Converted' }; After = @{ Present = $true; Kind = 'String'; Value = 'Converted' }; Expect = $false } + @{ Name = 'a string that differs only by its letter case'; Kind = 'String'; Before = @{ Present = $true; Kind = 'String'; Value = 'Converted' }; After = @{ Present = $true; Kind = 'String'; Value = 'converted' }; Expect = $true } + @{ Name = 'a multi-valued attribute with the same values in another order'; Kind = 'MultiString'; Before = @{ Present = $true; Kind = 'MultiString'; Value = @('smtp:a@contoso.invalid', 'SMTP:b@contoso.invalid') }; After = @{ Present = $true; Kind = 'MultiString'; Value = @('SMTP:b@contoso.invalid', 'smtp:a@contoso.invalid') }; Expect = $false } + @{ Name = 'a multi-valued attribute with one value more'; Kind = 'MultiString'; Before = @{ Present = $true; Kind = 'MultiString'; Value = @('smtp:a@contoso.invalid') }; After = @{ Present = $true; Kind = 'MultiString'; Value = @('smtp:a@contoso.invalid', 'smtp:b@contoso.invalid') }; Expect = $true } + @{ Name = 'a multi-valued attribute with one value that differs only by its letter case'; Kind = 'MultiString'; Before = @{ Present = $true; Kind = 'MultiString'; Value = @('smtp:a@contoso.invalid', 'SMTP:b@contoso.invalid') }; After = @{ Present = $true; Kind = 'MultiString'; Value = @('smtp:a@contoso.invalid', 'smtp:b@contoso.invalid') }; Expect = $true } + @{ Name = 'a multi-valued attribute that is empty on both sides'; Kind = 'MultiString'; Before = @{ Present = $true; Kind = 'MultiString'; Value = @() }; After = @{ Present = $true; Kind = 'MultiString'; Value = @() }; Expect = $false } + @{ Name = 'an attribute that is absent and one that is present and empty'; Kind = 'String'; Before = @{ Present = $false; Kind = 'String'; Value = $null }; After = @{ Present = $true; Kind = 'String'; Value = '' }; Expect = $true } + @{ Name = 'an attribute that is present and empty and one that is absent'; Kind = 'String'; Before = @{ Present = $true; Kind = 'String'; Value = '' }; After = @{ Present = $false; Kind = 'String'; Value = $null }; Expect = $true } + @{ Name = 'an attribute that is absent on both sides'; Kind = 'String'; Before = @{ Present = $false; Kind = 'String'; Value = $null }; After = @{ Present = $false; Kind = 'String'; Value = $null }; Expect = $false } + @{ Name = 'an attribute that is present and empty on both sides'; Kind = 'String'; Before = @{ Present = $true; Kind = 'String'; Value = '' }; After = @{ Present = $true; Kind = 'String'; Value = '' }; Expect = $false } + ) { + $plan = [pscustomobject]@{ Kinds = [ordered]@{ first = 'String'; second = $Kind } + Desired = @{ first = @{ Present = $true; Kind = 'String'; Value = 'same' }; second = $After } + Record = [pscustomobject]@{ Attributes = @{ first = @{ Present = $true; Kind = 'String'; Value = 'same' }; second = $Before }; Licensing = [pscustomobject]@{ Enabled = $false; WasMember = $false; DesiredMember = $false } } } + Test-PraPlanChange -Plan $plan | Should -Be $Expect + } + It 'tells a plan that changes the licence group membership from one that does not, and ignores a group that is not managed ()' -ForEach @( + @{ Name = 'member to not member'; Enabled = $true; Was = $true; Desired = $false; Expect = $true } + @{ Name = 'not member to member'; Enabled = $true; Was = $false; Desired = $true; Expect = $true } + @{ Name = 'member and stays'; Enabled = $true; Was = $true; Desired = $true; Expect = $false } + @{ Name = 'not member and stays'; Enabled = $true; Was = $false; Desired = $false; Expect = $false } + @{ Name = 'not managed'; Enabled = $false; Was = $true; Desired = $false; Expect = $false } + ) { + $same = @{ Present = $true; Kind = 'String'; Value = 'same' } + $plan = [pscustomobject]@{ Kinds = [ordered]@{ first = 'String' }; Desired = @{ first = $same } + Record = [pscustomobject]@{ Attributes = @{ first = $same }; Licensing = [pscustomobject]@{ Enabled = $Enabled; WasMember = $Was; DesiredMember = $Desired } } } + Test-PraPlanChange -Plan $plan | Should -Be $Expect + } + It 'reads the plans of the fixture the same way: the Recover of an object that is back as it was changes nothing, the Convert of it does' { + $recoverPlans = @(foreach ($record in (Get-Content -LiteralPath $bundles.Source -Raw | ConvertFrom-Json).Records) { New-PraPlan $context $record.ObjectGuid 'Recover' $record }) + Test-PraPlanChange -Plan $recoverPlans[0] | Should -BeFalse + Test-PraPlanChange -Plan @($bundles.Plans)[0] | Should -BeTrue -Because 'a Convert plan changes the object' + } +} + +Describe 'Release 3.3.0 - the Windows event of a failed Apply carries the batch the run made, the Exchange Online child says how it started, and a Cleanup says why it keeps a protected batch (production Common, Directory and Cloud functions, synthetic data)' -Tag 'Release330G' { + BeforeAll { + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global + Register-PraTestProxy PRA.Common 'Write-PraApplyEnded', 'Get-PraCleanupBatch' + $global:PraGate.L330GSink = New-Object 'Collections.Generic.List[object]' + $script:NewEventContext = { + @{ StepIndex = 0; StepTotal = 4; Issues = (New-Object 'Collections.Generic.List[object]'); Warnings = 0; LogFile = ''; Action = 'Convert'; Phase = 'AD'; CurrentPhase = ''; RunId = '20261124_101500-0123456789abcdef' + Version = '9.9.9'; BatchId = ''; AllowMutation = $true; ExitCode = 1; ApplyEventStarted = $true; Config = @{ Logging = @{ WindowsEvents = 'Auto' } }; WindowsEventState = 'Ready' + WindowsEventSink = { param($Id, $Type, $Text) $global:PraGate.L330GSink.Add([pscustomobject]@{ Id = [int]$Id; Type = [string]$Type; Text = [string]$Text }) } } + } + $cloudAst = [Management.Automation.Language.Parser]::ParseFile((Join-Path $global:PraGate.Package 'module\PRA.Cloud.psm1'), [ref]$null, [ref]$null) + $script:ExoFunctions = (@('Get-PraExecutionPolicyState', 'Test-PraExoSecurityError', 'Get-PraExoPolicyRefusal', 'Get-PraExoErrorDetail', 'Test-PraExoPolicyRefusal', 'Read-PraExoRefusalDetail', 'Get-PraFileSignatureFact', 'Test-PraExoModuleSignature', 'Get-PraExoModuleCandidate', 'Get-PraExoVerifiedModule', 'Get-PraExoChildFolderPath', 'Test-PraExoChildFallback', 'Remove-PraExoChildFolder', 'Invoke-PraExoChild', 'Invoke-PraExoSubprocess') | ForEach-Object { + $name = $_ + $function = $cloudAst.Find({ param($n) $n -is [Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -ceq $name }, $true) + if ($null -eq $function) { throw ('function not found: ' + $name) } + $function.Extent.Text + }) -join "`n" + $global:PraGate.L330GModes = New-Object 'Collections.Generic.List[string]' + $script:NewExoContext = { + param([string]$Start = 'Auto') + $log = Join-Path $global:PraGate.Root ('exo-start-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.log') + @{ Config = @{ Cloud = @{ TenantId = ''; AppId = ''; CertificateThumbprint = ''; Organization = '' }; Exo = @{ DisableWAM = $false; ChildStart = $Start } }; TimeoutMinutes = 1; StepIndex = 0; StepTotal = 1; Issues = (New-Object 'Collections.Generic.List[object]'); Warnings = 0; LogFile = $log; Action = 'Recover'; CurrentPhase = 'Test' } + } + $script:Tree = Join-Path $global:PraGate.Root ('g330-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) + $null = New-Item -ItemType Directory -Path $script:Tree -Force + } + BeforeEach { $global:PraGate.L330GSink.Clear(); $global:PraGate.L330GModes.Clear() } + AfterAll { Disable-PraProtection; $global:PraGate.Remove('L330GSink'); $global:PraGate.Remove('L330GModes') } + It 'event 4102 names the batch that the run made when the run has no batch of its own to report, and keeps the batch it reports when it has one' { + $none = [pscustomobject]@{ Status = 'Failed'; ExitCode = 1; SuccessCount = 0; ErrorCount = 1; PendingCount = 0; SkippedCount = 0; WarningCount = 1; Issues = @([pscustomobject]@{ Source = 'Execution' }) } + $context = & $script:NewEventContext + $context.CreatedBatchId = '4153c5a8' + Write-PraApplyEnded -Context $context -Result $none + $global:PraGate.L330GSink[0].Id | Should -Be 4102 + $global:PraGate.L330GSink[0].Text | Should -BeLike "*`nBatch=4153c5a8`nAccount=*" + $global:PraGate.L330GSink.Clear() + $context = & $script:NewEventContext + $context.BatchId = '0a1b2c3d'; $context.CreatedBatchId = '4153c5a8' + Write-PraApplyEnded -Context $context -Result $none + $global:PraGate.L330GSink[0].Text | Should -BeLike "*`nBatch=0a1b2c3d`nAccount=*" + $global:PraGate.L330GSink.Clear() + $context = & $script:NewEventContext + $context.Source = [pscustomobject]@{ Data = [pscustomobject]@{ BatchId = '99887766554433221100aabbccddeeff' } } + Write-PraApplyEnded -Context $context -Result $none + $global:PraGate.L330GSink[0].Text | Should -BeLike "*`nBatch=99887766`nAccount=*" -Because 'the batch that the run reads is named by its short id' + $global:PraGate.L330GSink.Clear() + $context = & $script:NewEventContext + Write-PraApplyEnded -Context $context -Result $none + $global:PraGate.L330GSink[0].Text | Should -BeLike "*`nBatch=`nAccount=*" -Because 'a run that knows no batch says so' + } + It 'the backup of a batch records its short id in the run, whether or not the run reports that batch' { + $runtime = New-GateRuntime -Name 'created-330g' + $env:PRA_GATE_STATE = $runtime.StatePath + $env:PSModulePath = $runtime.Modules + ';' + (Join-Path $PSHOME 'Modules') + Remove-Module PRA.Directory -Force -ErrorAction SilentlyContinue + Get-Module ActiveDirectory -All | Remove-Module -Force -ErrorAction Stop + Import-Module (Join-Path $runtime.Modules 'ActiveDirectory\ActiveDirectory.psm1') -Force -Global + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Directory.psm1') -Force -Global + $context = New-GateContext $runtime + $bundles = New-GateSourceBundles $context + $recoverId = [string](Get-Content -LiteralPath $bundles.Recover -Raw | ConvertFrom-Json).BatchId + $context.CreatedBatchId | Should -BeExactly $recoverId.Substring(0, 8) + $context.BatchId | Should -BeExactly $recoverId.Substring(0, 8) + $context.BatchId = '' + $context.CreatedBatchId | Should -BeExactly $recoverId.Substring(0, 8) -Because 'the batch of an event does not depend on the batch the run reports at its end' + } + It 'logs once, as a detail, that the Exchange Online child started from its standard input, and again only when the way it starts changes' { + . ([scriptblock]::Create($script:ExoFunctions)) + Mock Get-PraExecutionPolicyState { [pscustomobject]@{ Effective = 'RemoteSigned'; Source = 'LocalMachine'; Enforced = $false } } + $script:PraExoWorker = { 'worker' } + Mock Invoke-PraExoChild { + $global:PraGate.L330GModes.Add($Mode) + [pscustomobject]@{ Out = ('{"Protocol":1,"Id":"' + $Id + '","Ok":true,"Data":{"Probe":"ok"},"Error":""}'); Err = ''; ExitCode = 0; TimedOut = $false } + } + $context = & $script:NewExoContext 'Auto' + foreach ($call in 1..3) { (Invoke-PraExoSubprocess -Context $context -Operation 'Probe' -Params @{} -Permit $null -OnApplied $null -OnProgress $null 6>$null).Probe | Should -BeExactly 'ok' } + ($global:PraGate.L330GModes -join ',') | Should -BeExactly 'Stdin,Stdin,Stdin' + $lines = @([IO.File]::ReadAllLines($context.LogFile) | Where-Object { $_ -match 'Exchange Online child process started from' }) + $lines.Count | Should -Be 1 + $lines[0] | Should -Match '\[DETAIL\] Exchange Online child process started from its standard input \(no script file\)\.$' + $context.Warnings | Should -Be 0 + } + It 'logs that the child started from the temporary script file when the first start did not run (with the warning), and when Exo.ChildStart asks for the file ()' -ForEach @( + @{ Start = 'Auto'; Warnings = 1 } + @{ Start = 'FILE'; Warnings = 0 } + @{ Start = 'file'; Warnings = 0 } + ) { + . ([scriptblock]::Create($script:ExoFunctions)) + Mock Get-PraExecutionPolicyState { [pscustomobject]@{ Effective = 'RemoteSigned'; Source = 'LocalMachine'; Enforced = $false } } + $script:PraExoWorker = { 'worker' } + Mock Invoke-PraExoChild { + $global:PraGate.L330GModes.Add($Mode) + if ($Mode -ceq 'Stdin') { return [pscustomobject]@{ Out = ''; Err = 'cannot run'; ExitCode = 1; TimedOut = $false } } + [pscustomobject]@{ Out = ('{"Protocol":1,"Id":"' + $Id + '","Ok":true,"Data":{"Probe":"ok"},"Error":""}'); Err = ''; ExitCode = 0; TimedOut = $false } + } + $context = & $script:NewExoContext $Start + (Invoke-PraExoSubprocess -Context $context -Operation 'Probe' -Params @{} -Permit $null -OnApplied $null -OnProgress $null 6>$null).Probe | Should -BeExactly 'ok' + $lines = @([IO.File]::ReadAllLines($context.LogFile) | Where-Object { $_ -match 'Exchange Online child process started from' }) + $lines.Count | Should -Be 1 -Because (($lines + $global:PraGate.L330GModes) -join ' | ') + $lines[0] | Should -Match '\[DETAIL\] Exchange Online child process started from a temporary script file in a private folder\.$' + $context.Warnings | Should -Be $Warnings + } + It 'logs nothing about the start of a child that did not run to the end' { + . ([scriptblock]::Create($script:ExoFunctions)) + Mock Get-PraExecutionPolicyState { [pscustomobject]@{ Effective = 'RemoteSigned'; Source = 'LocalMachine'; Enforced = $false } } + $script:PraExoWorker = { 'worker' } + Mock Invoke-PraExoChild { $global:PraGate.L330GModes.Add($Mode); [pscustomobject]@{ Out = ''; Err = 'failed'; ExitCode = 1; TimedOut = $false } } + $context = & $script:NewExoContext 'Stdin' + { Invoke-PraExoSubprocess -Context $context -Operation 'Probe' -Params @{} -Permit $null -OnApplied $null -OnProgress $null 6>$null } | Should -Throw '*child process code=1*' + $text = if ([IO.File]::Exists($context.LogFile)) { [IO.File]::ReadAllText($context.LogFile) } else { '' } + $text | Should -Not -Match 'child process started from' + } + It 'a Cleanup keeps a protected batch that it cannot read and says why and what to do, in the log and the table; with the key it reads the batch like any other' { + $key = Join-Path $script:Tree 'protect.key'; $null = New-PraAuthKeyFile -Path $key + $backups = Join-Path $script:Tree 'Backups' + $id = 'a1b2c3d4e5f60718293a4b5c6d7e8f90' + $folder = Join-Path $backups ('Batch-' + $id) + $null = New-Item -ItemType Directory -Path $folder -Force + Enable-PraProtection (New-PraProtection -Mode Passphrase -KeyFile $key) + $json = '{"SchemaVersion":3,"Operation":"Convert","BatchId":"' + $id + '","Environment":"LAB","Records":[]}' + Write-PraProtectedFile -Path (Join-Path $folder ('Convert-LAB-20260101_000000-' + $id.Substring(0, 8) + '.json')) -Content ([Text.Encoding]::UTF8.GetBytes($json)) + [IO.File]::WriteAllText((Join-Path $folder ('Journal-' + $id + '.jsonl')), '{"Operation":"Backup","Status":"Verified","Target":"*"}') + $old = [datetime]::UtcNow.AddDays(-100) + foreach ($file in [IO.Directory]::GetFiles($folder)) { [IO.File]::SetLastWriteTimeUtc($file, $old) } + [IO.Directory]::SetLastWriteTimeUtc($folder, $old) + Enable-PraProtection (New-PraProtection -Mode Off) + $without = Get-PraCleanupBatch -Root $backups -Environment 'LAB' -Now ([datetime]::UtcNow) -Days 30 + $reason = [string]@($without.Kept | Where-Object { $_.Path -eq $folder })[0].Reason + $reason | Should -BeLike 'a protected backup (Storage.Protect) that this run cannot read without its key, so it is kept untouched*Storage.KeyFile is not set*To clean it up, set the key of the run that protected it in the configuration (Storage.KeyFile or Storage.CertificateThumbprint; a passphrase: give -ProtectPassphrase or type it at a console), then run the Cleanup again' + $reason | Should -Not -BeLike '*does not say that it belongs*' + Enable-PraProtection (New-PraProtection -Mode Off -KeyFile $key) + $with = Get-PraCleanupBatch -Root $backups -Environment 'LAB' -Now ([datetime]::UtcNow) -Days 30 + [string]@($with.Kept | Where-Object { $_.Path -eq $folder })[0].Reason | Should -Not -BeLike 'a protected backup*' -Because 'with the key the backup is read: the verdict is the one of any batch' + Enable-PraProtection (New-PraProtection -Mode Off) + $other = Join-Path $script:Tree 'other.key'; $null = New-PraAuthKeyFile -Path $other + Enable-PraProtection (New-PraProtection -Mode Off -KeyFile $other) + $wrong = Get-PraCleanupBatch -Root $backups -Environment 'LAB' -Now ([datetime]::UtcNow) -Days 30 + [string]@($wrong.Kept | Where-Object { $_.Path -eq $folder })[0].Reason | Should -BeLike 'a protected backup (Storage.Protect) that this run cannot read without its key*' + } +} + +Describe 'Release 3.3.0 - the warning about SYSTEM concerns a run that signs in to Exchange Online with a certificate, and only that one (production Common module, real main)' -Tag 'Release330G' { + BeforeAll { + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global + $script:NewRunContext = { @{ StepIndex = 0; StepTotal = 4; Issues = (New-Object 'Collections.Generic.List[object]'); Warnings = 0; LogFile = ''; Action = 'Convert'; CurrentPhase = '' } } + } + It 'warns for SYSTEM with a certificate sign-in, in any letter case of the SID, and does not warn for SYSTEM without one, nor for another account (certificate: , account: )' -ForEach @( + @{ Certificate = $true; Sid = 'S-1-5-18'; Expect = 1 } + @{ Certificate = $true; Sid = 's-1-5-18'; Expect = 1 } + @{ Certificate = $false; Sid = 'S-1-5-18'; Expect = 0 } + @{ Certificate = $false; Sid = 's-1-5-18'; Expect = 0 } + @{ Certificate = $true; Sid = 'S-1-5-21-1-2-3-1001'; Expect = 0 } + ) { + $context = & $script:NewRunContext + Write-PraRunWarning -Context $context -DiagnosticOutput $false -AccountSid $Sid -CertificateSignIn $Certificate 6>$null + $context.Warnings | Should -Be $Expect + if ($Expect) { $context.WarningList[0].Message | Should -BeLike '*started as SYSTEM*CurrentUser\My store of SYSTEM*' } + $context.Issues.Count | Should -Be 0 + } + It 'keeps the warning for SYSTEM when the caller says nothing about the certificate, and still warns once about -Verbose or -Debug without a certificate' { + $context = & $script:NewRunContext + Write-PraRunWarning -Context $context -DiagnosticOutput $false -AccountSid 'S-1-5-18' 6>$null + $context.Warnings | Should -Be 1 + $context = & $script:NewRunContext + Write-PraRunWarning -Context $context -DiagnosticOutput $true -AccountSid 'S-1-5-18' -CertificateSignIn $false 6>$null + $context.Warnings | Should -Be 1 + $context.WarningList[0].Message | Should -BeLike '*do not share*' + } + It 'says that a run signs in with the certificate when the configuration has the application and its certificate and the run asks Exchange Online ( , check , certificate : )' -ForEach @( + @{ Action = 'Convert'; Phase = 'AD'; Check = $true; Certificate = $true; Expect = $false } + @{ Action = 'Convert'; Phase = 'Both'; Check = $true; Certificate = $true; Expect = $true } + @{ Action = 'convert'; Phase = 'cloud'; Check = $true; Certificate = $true; Expect = $true } + @{ Action = 'Check'; Phase = 'Cloud'; Check = $true; Certificate = $true; Expect = $true } + @{ Action = 'Recover'; Phase = 'AD'; Check = $true; Certificate = $true; Expect = $true } + @{ Action = 'RECOVER'; Phase = 'ad'; Check = $true; Certificate = $true; Expect = $true } + @{ Action = 'Recover'; Phase = 'AD'; Check = $false; Certificate = $true; Expect = $false } + @{ Action = 'Recover'; Phase = 'AD'; Check = $true; Certificate = $false; Expect = $false } + @{ Action = 'Recover'; Phase = 'Both'; Check = $false; Certificate = $true; Expect = $true } + @{ Action = 'Recover'; Phase = 'Cloud'; Check = $false; Certificate = $true; Expect = $true } + @{ Action = 'Finalize'; Phase = 'AD'; Check = $true; Certificate = $true; Expect = $false } + @{ Action = 'Finalize'; Phase = 'Both'; Check = $true; Certificate = $true; Expect = $false } + @{ Action = 'Cleanup'; Phase = ''; Check = $true; Certificate = $true; Expect = $false } + @{ Action = 'Convert'; Phase = 'Both'; Check = $true; Certificate = $false; Expect = $false } + ) { + $cloud = if ($Certificate) { @{ AppId = '22222222-3333-4444-5555-666666666666'; CertificateThumbprint = 'ABCDEF0123456789ABCDEF0123456789ABCDEF01' } } else { @{ AppId = ''; CertificateThumbprint = '' } } + Test-PraCertificateSignIn -Action $Action -Phase $Phase -Config @{ Cloud = $cloud; Retention = @{ CheckBeforeRecover = $Check } } | Should -Be $Expect + } + It 'needs both the application and the thumbprint, and reads a configuration without the sections of 3.2.0' { + Test-PraCertificateSignIn -Action Convert -Phase Both -Config @{ Cloud = @{ AppId = 'app'; CertificateThumbprint = '' } } | Should -BeFalse + Test-PraCertificateSignIn -Action Convert -Phase Both -Config @{ Cloud = @{ AppId = ''; CertificateThumbprint = 'ABC' } } | Should -BeFalse + Test-PraCertificateSignIn -Action Recover -Phase AD -Config @{ Cloud = @{ AppId = 'app'; CertificateThumbprint = 'ABC' } } | Should -BeFalse -Because 'no Retention section: the retention check is not known to be on' + Test-PraCertificateSignIn -Action Convert -Phase Both -Config @{} | Should -BeFalse + } + It 'warns about SYSTEM once for a Recover in the AD phase whose retention check signs in with the certificate, and not for a Convert in the AD phase (any letter case of the SID)' { + $config = @{ Cloud = @{ AppId = 'app'; CertificateThumbprint = 'ABC' }; Retention = @{ CheckBeforeRecover = $true } } + foreach ($case in @(@{ Action = 'Recover'; Expect = 1 }, @{ Action = 'Convert'; Expect = 0 })) { + $context = & $script:NewRunContext + Write-PraRunWarning -Context $context -DiagnosticOutput $false -AccountSid 's-1-5-18' -CertificateSignIn (Test-PraCertificateSignIn -Action $case.Action -Phase 'AD' -Config $config) 6>$null + $context.Warnings | Should -Be $case.Expect -Because $case.Action + } + } +} + + +Describe 'Release 3.3.0 - the command printed for the next phase or the other server carries the objects that the run selected, and works as printed (real main, production Directory module, synthetic AD and cloud barrier)' -Tag 'Release330G' { + BeforeAll { + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global + function script:Get-G330Why($Run) { (@(([string]$Run.Output + [string]$Run.Error) -split '\r?\n' | Where-Object { $_ -match 'Stopped at step|refused|Nothing was|cannot|failed|Error' } | Select-Object -First 8) -join ' | ') } + function script:Get-G330Flat($Run) { [regex]::Replace([string]$Run.Output, '\s+', ' ') } + # A printed command line read back from its text: the words after the script name, each parameter with its value (-Batch 'x.zip' gives Batch = x.zip). + function script:ConvertFrom-G330Command([string]$Text) { + $tokens = [Management.Automation.Language.Parser]::ParseInput($Text, [ref]$null, [ref]$null).Find({ param($n) $n -is [Management.Automation.Language.CommandAst] }, $true).CommandElements + $parsed = @{} + for ($position = 1; $position -lt $tokens.Count; $position++) { + if ($tokens[$position] -isnot [Management.Automation.Language.CommandParameterAst]) { continue } + $parsed[$tokens[$position].ParameterName] = [string]$tokens[$position + 1].Value + } + $parsed + } + # The last printed command of a run that ends with a transfer package: the one that carries the fingerprint. + function script:Get-G330PrintedCommand($Run) { @($Run.MainResult.NextSteps | Where-Object { $_ -match '^\.\\Invoke-PraRemoteMailbox\.ps1 ' } | Select-Object -Last 1)[0] } + function script:Copy-G330Package($Run, $To) { + $package = [string]$Run.MainResult.TransferPackage + $inbox = Join-Path $To.State.BackupFolder 'Inbox'; $null = New-Item -ItemType Directory -Path $inbox -Force + Copy-Item -LiteralPath $package, ($package + '.sha256') -Destination $inbox + [IO.Path]::GetFileName($package) + } + } + BeforeEach { + $runtime = New-GateRuntime -Name 'selection-330g' + $env:PRA_GATE_STATE = $runtime.StatePath + $env:PSModulePath = $runtime.Modules + ';' + (Join-Path $PSHOME 'Modules') + Remove-Module PRA.Directory -Force -ErrorAction SilentlyContinue + Get-Module ActiveDirectory -All | Remove-Module -Force -ErrorAction Stop + Import-Module (Join-Path $runtime.Modules 'ActiveDirectory\ActiveDirectory.psm1') -Force -Global + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Directory.psm1') -Force -Global + $cloud = New-GateRuntime -Name 'selection-cloud-330g' + } + AfterAll { Remove-Item -LiteralPath 'Function:\Get-G330Why', 'Function:\Get-G330Flat', 'Function:\ConvertFrom-G330Command', 'Function:\Get-G330PrintedCommand', 'Function:\Copy-G330Package' -ErrorAction SilentlyContinue } + It 'a Recover of one object of a batch of two: the cloud command carries -Identity as typed, works as printed, and the Finalize command that follows carries it too' { + $convert = Invoke-GateProcess $runtime @{Action='Convert';Phase='AD';Mode='Apply';Force=$true;ConfigPath=$runtime.ConfigPath} -TimeoutSeconds 120 + $convert.ExitCode | Should -Be 2 -Because (Get-G330Why $convert) + $recover = Invoke-GateProcess $runtime @{Action='Recover';Phase='AD';Mode='Apply';Force=$true;ConfigPath=$runtime.ConfigPath;Batch=[string]$convert.MainResult.BatchId;Identity='USER2'} -TimeoutSeconds 120 + $recover.ExitCode | Should -Be 2 -Because (Get-G330Why $recover) + $printed = Get-G330PrintedCommand $recover + $parsed = ConvertFrom-G330Command $printed + @($parsed.Keys | Sort-Object) | Should -Be @('Action', 'Batch', 'ExpectedFingerprint', 'Identity', 'Mode', 'Phase') -Because $printed + $parsed.Identity | Should -BeExactly 'USER2' + $parsed.Phase | Should -BeExactly 'Cloud' + $name = Copy-G330Package $recover $cloud + $parsed.Batch | Should -BeExactly $name + $without = $parsed.Clone(); $without.Remove('Identity'); $without.ConfigPath = $cloud.ConfigPath; $without.Force = $true + $refused = Invoke-GateProcess $cloud $without -TimeoutSeconds 120 + $refused.ExitCode | Should -Be 1 -Because 'without the selection the cloud phase asks for the objects that the AD phase did not verify' + (Get-G330Flat $refused) | Should -Match 'Object not verified by the AD phase of this batch' + $printed = $parsed.Clone(); $printed.ConfigPath = $cloud.ConfigPath; $printed.Force = $true + $worked = Invoke-GateProcess $cloud $printed -TimeoutSeconds 120 + (Get-G330Flat $worked) | Should -Match ', AD proof verified' -Because 'the batch was loaded with its one verified object' + (Get-G330Flat $worked) | Should -Not -Match 'Object not verified by the AD phase of this batch' + } + It 'a Convert of one object in the AD phase: the cloud command carries -Identity as typed and works as printed' { + $runtime.State.ExpectedGuids = @([string]$runtime.State.Users[0].ObjectGUID) + [IO.File]::WriteAllText($runtime.StatePath, [Management.Automation.PSSerializer]::Serialize($runtime.State, 35)) + $convert = Invoke-GateProcess $runtime @{Action='Convert';Phase='AD';Mode='Apply';Force=$true;ConfigPath=$runtime.ConfigPath;Identity='USER1'} -TimeoutSeconds 120 + $convert.ExitCode | Should -Be 2 -Because (Get-G330Why $convert) + $printed = Get-G330PrintedCommand $convert + $parsed = ConvertFrom-G330Command $printed + @($parsed.Keys | Sort-Object) | Should -Be @('Action', 'Batch', 'ExpectedFingerprint', 'Identity', 'Mode', 'Phase') -Because $printed + $parsed.Identity | Should -BeExactly 'USER1' + $null = Copy-G330Package $convert $cloud + $parsed.ConfigPath = $cloud.ConfigPath; $parsed.Force = $true + $worked = Invoke-GateProcess $cloud $parsed -TimeoutSeconds 120 + $worked.ExitCode | Should -BeIn @(0, 2) -Because (Get-G330Why $worked) + (Get-G330Flat $worked) | Should -Not -Match 'Stopped at step' + (Get-G330Flat $worked) | Should -Match 'Batch [0-9a-f]{8}: 1 object\(s\)' + } + It 'a value that needs quoting, typed in another letter case, is printed as a literal that reads back the same and is found in the batch' { + $runtime.State.Users[0].SamAccountName = "o'brien" + $runtime.State.ExpectedGuids = @([string]$runtime.State.Users[0].ObjectGUID) + [IO.File]::WriteAllText($runtime.StatePath, [Management.Automation.PSSerializer]::Serialize($runtime.State, 35)) + $convert = Invoke-GateProcess $runtime @{Action='Convert';Phase='AD';Mode='Apply';Force=$true;ConfigPath=$runtime.ConfigPath;Identity="O'Brien"} -TimeoutSeconds 120 + $convert.ExitCode | Should -Be 2 -Because (Get-G330Why $convert) + $printed = Get-G330PrintedCommand $convert + $printed | Should -Match " -Identity 'O''Brien' " + $parsed = ConvertFrom-G330Command $printed + $parsed.Identity | Should -BeExactly "O'Brien" + $null = Copy-G330Package $convert $cloud + $parsed.ConfigPath = $cloud.ConfigPath; $parsed.Force = $true + $worked = Invoke-GateProcess $cloud $parsed -TimeoutSeconds 120 + $worked.ExitCode | Should -BeIn @(0, 2) -Because (Get-G330Why $worked) + (Get-G330Flat $worked) | Should -Not -Match 'Stopped at step' + } + It 'an identity typed as the distinguished name is printed as the account name of the object, which the cloud phase finds in the batch' { + $dn = [string]$runtime.State.Users[1].DistinguishedName + $runtime.State.ExpectedGuids = @([string]$runtime.State.Users[1].ObjectGUID) + [IO.File]::WriteAllText($runtime.StatePath, [Management.Automation.PSSerializer]::Serialize($runtime.State, 35)) + $convert = Invoke-GateProcess $runtime @{Action='Convert';Phase='AD';Mode='Apply';Force=$true;ConfigPath=$runtime.ConfigPath;Identity=$dn} -TimeoutSeconds 120 + $convert.ExitCode | Should -Be 2 -Because (Get-G330Why $convert) + $parsed = ConvertFrom-G330Command (Get-G330PrintedCommand $convert) + $parsed.Identity | Should -BeExactly ([string]$runtime.State.Users[1].SamAccountName) + $null = Copy-G330Package $convert $cloud + $parsed.ConfigPath = $cloud.ConfigPath; $parsed.Force = $true + $worked = Invoke-GateProcess $cloud $parsed -TimeoutSeconds 120 + $worked.ExitCode | Should -BeIn @(0, 2) -Because (Get-G330Why $worked) + } + It 'a Convert in the AD phase prints neither a scope nor an identity when it names none, and a run that finishes the batch never carries a scope: the cloud phase then does every object' { + $convert = Invoke-GateProcess $runtime @{Action='Convert';Phase='AD';Mode='Apply';Force=$true;ConfigPath=$runtime.ConfigPath;Scope='UsersOnly'} -TimeoutSeconds 120 + $convert.ExitCode | Should -Be 2 -Because (Get-G330Why $convert) + $parsed = ConvertFrom-G330Command (Get-G330PrintedCommand $convert) + $parsed.Contains('Scope') | Should -BeFalse -Because 'the AD phase chose its objects with the scope: the batch holds exactly them' + $parsed.Contains('Identity') | Should -BeFalse + $short = [string]$convert.MainResult.BatchId + foreach ($leftover in @(Get-ChildItem -LiteralPath (Join-Path $runtime.State.BackupFolder 'Outbox') -File)) { Remove-Item -LiteralPath $leftover.FullName -Force } + $finish = Invoke-GateProcess $runtime @{Action='Convert';Phase='AD';Mode='Apply';Force=$true;ConfigPath=$runtime.ConfigPath;Batch=$short;Scope='UsersOnly'} -TimeoutSeconds 120 + $finish.ExitCode | Should -Be 2 -Because (Get-G330Why $finish) + $printed = Get-G330PrintedCommand $finish + $parsedFinish = ConvertFrom-G330Command $printed + $parsedFinish.Contains('Scope') | Should -BeFalse -Because ('finishing a batch does not filter it by the scope: ' + $printed) + $null = Copy-G330Package $finish $cloud + $parsedFinish.ConfigPath = $cloud.ConfigPath; $parsedFinish.Force = $true + $worked = Invoke-GateProcess $cloud $parsedFinish -TimeoutSeconds 120 + $worked.ExitCode | Should -BeIn @(0, 2) -Because (Get-G330Why $worked) + (Get-G330Flat $worked) | Should -Match 'Batch [0-9a-f]{8}: 2 object\(s\)' -Because 'every object of the batch is done' + } + It 'an identity typed as a GUID or as a UPN in capitals is printed as typed and found in the batch ()' -ForEach @(@{ Kind = 'GUID' }, @{ Kind = 'UPN' }) { + $convert = Invoke-GateProcess $runtime @{Action='Convert';Phase='AD';Mode='Apply';Force=$true;ConfigPath=$runtime.ConfigPath} -TimeoutSeconds 120 + $convert.ExitCode | Should -Be 2 -Because (Get-G330Why $convert) + $typed = if ($Kind -ceq 'GUID') { ([string]$runtime.State.Users[1].ObjectGUID).ToUpperInvariant() } else { ([string]$runtime.State.Users[1].UserPrincipalName).ToUpperInvariant() } + $recover = Invoke-GateProcess $runtime @{Action='Recover';Phase='AD';Mode='Apply';Force=$true;ConfigPath=$runtime.ConfigPath;Batch=[string]$convert.MainResult.BatchId;Identity=$typed} -TimeoutSeconds 120 + $recover.ExitCode | Should -Be 2 -Because (Get-G330Why $recover) + $parsed = ConvertFrom-G330Command (Get-G330PrintedCommand $recover) + $parsed.Identity | Should -BeExactly $typed + $null = Copy-G330Package $recover $cloud + $parsed.ConfigPath = $cloud.ConfigPath; $parsed.Force = $true + $worked = Invoke-GateProcess $cloud $parsed -TimeoutSeconds 120 + (Get-G330Flat $worked) | Should -Match ', AD proof verified' -Because (Get-G330Why $worked) + (Get-G330Flat $worked) | Should -Not -Match 'Object not verified by the AD phase of this batch' + } + It 'a typographic apostrophe in an identity is doubled in the printed literal and reads back the same' { + $runtime.State.Users[0].SamAccountName = "o$([char]0x2019)brien" + $runtime.State.ExpectedGuids = @([string]$runtime.State.Users[0].ObjectGUID) + [IO.File]::WriteAllText($runtime.StatePath, [Management.Automation.PSSerializer]::Serialize($runtime.State, 35)) + $typed = "O$([char]0x2019)Brien" + $convert = Invoke-GateProcess $runtime @{Action='Convert';Phase='AD';Mode='Apply';Force=$true;ConfigPath=$runtime.ConfigPath;Identity=$typed} -TimeoutSeconds 120 + $convert.ExitCode | Should -Be 2 -Because (Get-G330Why $convert) + $printed = Get-G330PrintedCommand $convert + $printed | Should -BeLike "* -Identity 'O$([char]0x2019)$([char]0x2019)Brien' *" + $parsed = ConvertFrom-G330Command $printed + $parsed.Identity | Should -BeExactly $typed + $null = Copy-G330Package $convert $cloud + $parsed.ConfigPath = $cloud.ConfigPath; $parsed.Force = $true + $worked = Invoke-GateProcess $cloud $parsed -TimeoutSeconds 120 + $worked.ExitCode | Should -BeIn @(0, 2) -Because (Get-G330Why $worked) + (Get-G330Flat $worked) | Should -Not -Match 'Stopped at step' + } + It 'the command of the fallback, when the transfer package cannot be written, carries the identity and works as printed with the folder copied by hand' { + $runtime.State.ExpectedGuids = @([string]$runtime.State.Users[0].ObjectGUID) + [IO.File]::WriteAllText($runtime.StatePath, [Management.Automation.PSSerializer]::Serialize($runtime.State, 35)) + [IO.File]::WriteAllText((Join-Path $runtime.State.BackupFolder 'Outbox'), 'a file where the Outbox folder should be') + $convert = Invoke-GateProcess $runtime @{Action='Convert';Phase='AD';Mode='Apply';Force=$true;ConfigPath=$runtime.ConfigPath;Identity='USER1'} -TimeoutSeconds 120 + $convert.ExitCode | Should -Be 2 -Because (Get-G330Why $convert) + [string]$convert.MainResult.TransferPackage | Should -BeExactly '' + $steps = @($convert.MainResult.NextSteps) + ($steps -join "`n") | Should -Match 'Copy the folder .* to the Backups folder of the cloud server, then run there:' + $printed = ($steps | Where-Object { $_ -match '^\.\\Invoke-PraRemoteMailbox\.ps1 -Action Convert -Phase Cloud ' } | Select-Object -Last 1) + $parsed = ConvertFrom-G330Command $printed + $parsed.Identity | Should -BeExactly 'USER1' -Because $printed + $folder = @(Get-ChildItem -LiteralPath $runtime.State.BackupFolder -Directory -Filter 'Batch-*')[0].FullName + Copy-Item -LiteralPath $folder -Destination $cloud.State.BackupFolder -Recurse + $parsed.ConfigPath = $cloud.ConfigPath; $parsed.Force = $true + $worked = Invoke-GateProcess $cloud $parsed -TimeoutSeconds 120 + $worked.ExitCode | Should -BeIn @(0, 2) -Because (Get-G330Why $worked) + (Get-G330Flat $worked) | Should -Match 'Batch [0-9a-f]{8}: 1 object\(s\), AD proof verified' + } + It 'under a French culture the printed command is the same text and works as printed' { + $runtime.State.ExpectedGuids = @([string]$runtime.State.Users[0].ObjectGUID) + [IO.File]::WriteAllText($runtime.StatePath, [Management.Automation.PSSerializer]::Serialize($runtime.State, 35)) + $convert = Invoke-GateProcess $runtime @{Action='Convert';Phase='AD';Mode='Apply';Force=$true;ConfigPath=$runtime.ConfigPath;Identity='USER1'} -TimeoutSeconds 120 -Culture 'fr-FR' + $convert.ExitCode | Should -Be 2 -Because (Get-G330Why $convert) + $printed = Get-G330PrintedCommand $convert + $printed | Should -Match "^\.\\Invoke-PraRemoteMailbox\.ps1 -Action Convert -Phase Cloud -Mode Apply -Batch '[^']+\.zip' -Identity 'USER1' -ExpectedFingerprint ([0-9A-F]{4}-){4}[0-9A-F]{4}$" + $old = [Globalization.CultureInfo]::CurrentCulture + try { + [Globalization.CultureInfo]::CurrentCulture = [Globalization.CultureInfo]::GetCultureInfo('fr-FR') + $parsed = ConvertFrom-G330Command $printed + } + finally { [Globalization.CultureInfo]::CurrentCulture = $old } + $parsed.Identity | Should -BeExactly 'USER1' + $null = Copy-G330Package $convert $cloud + $parsed.ConfigPath = $cloud.ConfigPath; $parsed.Force = $true + $worked = Invoke-GateProcess $cloud $parsed -TimeoutSeconds 120 -Culture 'fr-FR' + $worked.ExitCode | Should -BeIn @(0, 2) -Because (Get-G330Why $worked) + (Get-G330Flat $worked) | Should -Match 'Batch [0-9a-f]{8}: 1 object\(s\)' + } + It 'an identity of about 900 characters does not break the package: the manifest holds it, the command that would not fit the manifest is printed in the next steps, and it works as printed' { + $long = 'a' * 900 + $runtime.State.Users[0].SamAccountName = $long + [IO.File]::WriteAllText($runtime.StatePath, [Management.Automation.PSSerializer]::Serialize($runtime.State, 35)) + $convert = Invoke-GateProcess $runtime @{Action='Convert';Phase='AD';Mode='Apply';Force=$true;ConfigPath=$runtime.ConfigPath} -TimeoutSeconds 120 + $convert.ExitCode | Should -Be 2 -Because (Get-G330Why $convert) + $recover = Invoke-GateProcess $runtime @{Action='Recover';Phase='AD';Mode='Apply';Force=$true;ConfigPath=$runtime.ConfigPath;Batch=[string]$convert.MainResult.BatchId;Identity=$long.ToUpperInvariant()} -TimeoutSeconds 120 + $recover.ExitCode | Should -Be 2 -Because (Get-G330Why $recover) + $info = Get-PraTransferPackage -Path ([string]$recover.MainResult.TransferPackage) -Environment SYNTHETIC_GATE + $info.Valid | Should -BeTrue -Because $info.Error + $info.NextCommand | Should -BeExactly '' -Because 'a command of more than 1000 characters does not fit the manifest' + $info.Selection.Identity | Should -BeExactly $long.ToUpperInvariant() + $printed = Get-G330PrintedCommand $recover + $printed.Length | Should -BeGreaterThan 1000 + $parsed = ConvertFrom-G330Command $printed + $parsed.Identity | Should -BeExactly $long.ToUpperInvariant() + $null = Copy-G330Package $recover $cloud + $parsed.ConfigPath = $cloud.ConfigPath; $parsed.Force = $true + $worked = Invoke-GateProcess $cloud $parsed -TimeoutSeconds 120 + (Get-G330Flat $worked) | Should -Match ', AD proof verified' -Because (Get-G330Why $worked) + (Get-G330Flat $worked) | Should -Not -Match 'Object not verified by the AD phase of this batch' + } + It 'an identity of more than 1024 characters is left out of the package with a warning, the scope stays, and the printed command still carries the identity' { + $long = 'b' * 1100 + $runtime.State.Users[0].SamAccountName = $long + [IO.File]::WriteAllText($runtime.StatePath, [Management.Automation.PSSerializer]::Serialize($runtime.State, 35)) + $convert = Invoke-GateProcess $runtime @{Action='Convert';Phase='AD';Mode='Apply';Force=$true;ConfigPath=$runtime.ConfigPath} -TimeoutSeconds 120 + $convert.ExitCode | Should -Be 2 -Because (Get-G330Why $convert) + $recover = Invoke-GateProcess $runtime @{Action='Recover';Phase='AD';Mode='Apply';Force=$true;ConfigPath=$runtime.ConfigPath;Batch=[string]$convert.MainResult.BatchId;Identity=$long;Scope='UsersOnly'} -TimeoutSeconds 120 + $recover.ExitCode | Should -Be 2 -Because (Get-G330Why $recover) + (Get-G330Flat $recover) | Should -Match 'The identity of this run is longer than 1024 characters: it is left out of the transfer package' + $info = Get-PraTransferPackage -Path ([string]$recover.MainResult.TransferPackage) -Environment SYNTHETIC_GATE + $info.Valid | Should -BeTrue -Because $info.Error + $info.Selection.Identity | Should -BeExactly '' + $info.Selection.Scope | Should -BeExactly 'UsersOnly' + $parsed = ConvertFrom-G330Command (Get-G330PrintedCommand $recover) + $parsed.Identity | Should -BeExactly $long + $null = Copy-G330Package $recover $cloud + $parsed.ConfigPath = $cloud.ConfigPath; $parsed.Force = $true + $worked = Invoke-GateProcess $cloud $parsed -TimeoutSeconds 120 + (Get-G330Flat $worked) | Should -Match ', AD proof verified' -Because (Get-G330Why $worked) + (Get-G330Flat $worked) | Should -Not -Match 'This package was made for a part of its batch' -Because 'the run has the identity: there is nothing to add' + } + It 'a package that keeps a scope only still warns a cloud run that has neither the scope nor an identity' { + $convert = Invoke-GateProcess $runtime @{Action='Convert';Phase='AD';Mode='Apply';Force=$true;ConfigPath=$runtime.ConfigPath} -TimeoutSeconds 120 + $convert.ExitCode | Should -Be 2 -Because (Get-G330Why $convert) + $recover = Invoke-GateProcess $runtime @{Action='Recover';Phase='AD';Mode='Apply';Force=$true;ConfigPath=$runtime.ConfigPath;Batch=[string]$convert.MainResult.BatchId;Scope='UsersOnly'} -TimeoutSeconds 120 + $recover.ExitCode | Should -Be 2 -Because (Get-G330Why $recover) + $parsed = ConvertFrom-G330Command (Get-G330PrintedCommand $recover) + $parsed.Remove('Scope') + $null = Copy-G330Package $recover $cloud + $parsed.ConfigPath = $cloud.ConfigPath; $parsed.Force = $true + $worked = Invoke-GateProcess $cloud $parsed -TimeoutSeconds 120 + (Get-G330Flat $worked) | Should -Match 'This package was made for a part of its batch \(-Scope UsersOnly\)' -Because (Get-G330Why $worked) + } + It 'a Convert of one object names the whole of its batch: the package records no selection and the cloud run is not warned, with or without the identity' { + $runtime.State.ExpectedGuids = @([string]$runtime.State.Users[0].ObjectGUID) + [IO.File]::WriteAllText($runtime.StatePath, [Management.Automation.PSSerializer]::Serialize($runtime.State, 35)) + $convert = Invoke-GateProcess $runtime @{Action='Convert';Phase='AD';Mode='Apply';Force=$true;ConfigPath=$runtime.ConfigPath;Identity='USER1'} -TimeoutSeconds 120 + $convert.ExitCode | Should -Be 2 -Because (Get-G330Why $convert) + $info = Get-PraTransferPackage -Path ([string]$convert.MainResult.TransferPackage) -Environment SYNTHETIC_GATE + $info.Selection.Identity | Should -BeExactly '' + $info.Selection.Scope | Should -BeExactly '' + [string]$convert.MainResult.TransferPackageIdentity | Should -BeExactly '' + $parsed = ConvertFrom-G330Command (Get-G330PrintedCommand $convert) + $parsed.Remove('Identity') + $null = Copy-G330Package $convert $cloud + $parsed.ConfigPath = $cloud.ConfigPath; $parsed.Force = $true + $worked = Invoke-GateProcess $cloud $parsed -TimeoutSeconds 120 + $worked.ExitCode | Should -BeIn @(0, 2) -Because (Get-G330Why $worked) + (Get-G330Flat $worked) | Should -Not -Match 'This package was made for a part of its batch' + (Get-G330Flat $worked) | Should -Match 'Batch [0-9a-f]{8}: 1 object\(s\)' + } + It 'a Recover package leaves its selection on the marker of its own batch folder only, also when the Convert folder that it brings along is already there; the Convert batch is then run with the window or the command line, not with the selection of the Recover' { + $convert = Invoke-GateProcess $runtime @{Action='Convert';Phase='AD';Mode='Apply';Force=$true;ConfigPath=$runtime.ConfigPath} -TimeoutSeconds 120 + $convert.ExitCode | Should -Be 2 -Because (Get-G330Why $convert) + $recover = Invoke-GateProcess $runtime @{Action='Recover';Phase='AD';Mode='Apply';Force=$true;ConfigPath=$runtime.ConfigPath;Batch=[string]$convert.MainResult.BatchId;Identity='USER2'} -TimeoutSeconds 120 + $recover.ExitCode | Should -Be 2 -Because (Get-G330Why $recover) + $info = Get-PraTransferPackage -Path ([string]$recover.MainResult.TransferPackage) -Environment SYNTHETIC_GATE + $own = 'Batch-' + $info.BatchId + $other = @($info.Folders | Where-Object { $_ -ne $own }) + $other.Count | Should -Be 1 + Copy-Item -LiteralPath (Join-Path $runtime.State.BackupFolder $other[0]) -Destination $cloud.State.BackupFolder -Recurse + $null = Copy-G330Package $recover $cloud + $parsed = ConvertFrom-G330Command (Get-G330PrintedCommand $recover) + $parsed.ConfigPath = $cloud.ConfigPath; $parsed.Force = $true + $worked = Invoke-GateProcess $cloud $parsed -TimeoutSeconds 120 + (Get-G330Flat $worked) | Should -Match '1 already present and identical' -Because (Get-G330Why $worked) + $mine = Get-PraImportSelection -BackupFolder $cloud.State.BackupFolder -FolderPath (Join-Path $cloud.State.BackupFolder $own) + $mine.Identity | Should -BeExactly 'USER2' + $mine.Kind | Should -BeExactly 'Recover' + Get-PraImportSelection -BackupFolder $cloud.State.BackupFolder -FolderPath (Join-Path $cloud.State.BackupFolder $other[0]) | Should -BeNullOrEmpty -Because 'the Convert batch is not the batch of the package' + Test-Path -LiteralPath (Get-PraVerifiedMarkerPath -BackupFolder $cloud.State.BackupFolder -Id ($other[0] -replace '^Batch-', '')) | Should -BeTrue -Because 'the folder is still a verified import' + } +} + + +Describe 'Release 3.3.0 - the Finalize command printed by the cloud phase of a Recover of one object carries that object and works as printed (real main, production Directory module, synthetic AD and cloud barrier)' -Tag 'Release330G' { + It 'prints -Identity as typed in the Finalize command, and the AD server runs that command as printed' { + $oldEventPath = $env:PRA_EVENT_FILE + try { + $runtime = New-GateRuntime -Name 'finalize-selection-330g' -Shared13 -Case CloudConfirmed13 + $env:PRA_GATE_STATE = $runtime.StatePath; $env:PSModulePath = $runtime.Modules + ';' + (Join-Path $PSHOME 'Modules') + Import-Module ActiveDirectory -Force -Global + $context = New-GateContext $runtime + $plans = @(1..13 | ForEach-Object { New-PraPlan $context ('user' + $_) 'Convert' }) + $source = Invoke-PraAdBatch $context $plans 'Convert' + [IO.File]::WriteAllText($runtime.StatePath, [Management.Automation.PSSerializer]::Serialize($global:PraGateAd, 35)) + $recover = Invoke-GateProcess $runtime -Certificate @{Action='Recover';Mode='Apply';Phase='AD';Force=$true;ConfigPath=$runtime.ConfigPath;Batch=$source.Path;Identity='USER3'} -TimeoutSeconds 120 + $recover.ExitCode | Should -Be 2 -Because ($recover.Output + $recover.Error) + $recoverPath = @(Get-ChildItem -LiteralPath $runtime.State.BackupFolder -Recurse -File -Filter 'Recover-*.json')[0].FullName + $cloud = Invoke-GateProcess $runtime @{Action='Recover';Mode='Apply';Phase='Cloud';Force=$true;ConfigPath=$runtime.ConfigPath;Batch=$recoverPath;Identity='USER3'} -TimeoutSeconds 120 + $cloud.ExitCode | Should -Be 2 -Because ($cloud.Output + $cloud.Error) + $printed = @($cloud.MainResult.NextSteps | Where-Object { $_ -match '^\.\\Invoke-PraRemoteMailbox\.ps1 -Action Finalize ' } | Select-Object -Last 1)[0] + $printed | Should -Not -BeNullOrEmpty + $tokens = [Management.Automation.Language.Parser]::ParseInput($printed, [ref]$null, [ref]$null).Find({ param($n) $n -is [Management.Automation.Language.CommandAst] }, $true).CommandElements + $parsed = @{} + for ($position = 1; $position -lt $tokens.Count; $position++) { if ($tokens[$position] -is [Management.Automation.Language.CommandParameterAst]) { $parsed[$tokens[$position].ParameterName] = [string]$tokens[$position + 1].Value } } + @($parsed.Keys | Sort-Object) | Should -Be @('Action', 'Batch', 'ExpectedFingerprint', 'Identity', 'Mode') -Because $printed + $parsed.Identity | Should -BeExactly 'USER3' + $parsed.Batch | Should -Match '^PRA-SYNTHETIC_GATE-Finalize-[0-9a-f]{8}-for-AD\.zip$' + $parsed.ConfigPath = $runtime.ConfigPath; $parsed.Force = $true + [IO.File]::WriteAllText($runtime.StatePath, [Management.Automation.PSSerializer]::Serialize($runtime.State, 35)) + $done = Invoke-GateProcess $runtime $parsed -TimeoutSeconds 120 + $done.ExitCode | Should -Be 0 -Because ($done.Output + $done.Error) + ([string]$done.Output) | Should -Match 'is the one given with -ExpectedFingerprint' + # Only the object that the selection names is restored by the Finalize, and what it writes is the original value of the object. + $user3 = @($runtime.State.Originals | Where-Object SamAccountName -eq 'user3')[0] + $sets = @($done.Events | Select-Object -Skip @($cloud.Events).Count | Where-Object Operation -ceq 'Set-ADUser') + ([string]$done.Output -replace '\s+', ' ') | Should -Match 'Package [0-9a-f]{8}: 1 object\(s\) confirmed by Exchange Online, proofs verified' + ([string]$done.Output -replace '\s+', ' ') | Should -Match 'Result 1 done . 0 pending . 0 error\(s\)' + @($sets | ForEach-Object { [string]$_.Identity } | Where-Object { $_ -ne [string]$user3.ObjectGUID }).Count | Should -Be 0 -Because 'no other object is written' + $written = @{} + foreach ($set in $sets) { foreach ($key in @($set.Detail.Replace.Keys)) { $written[[string]$key] = $set.Detail.Replace[$key] } } + if ($written.ContainsKey('extensionAttribute1')) { [string]$written['extensionAttribute1'] | Should -BeExactly ([string]$user3.extensionAttribute1) } + @($done.Events | Select-Object -Skip @($cloud.Events).Count | Where-Object { $_.Operation -match '^(Add-|Remove-)' -and [string]$_.Identity -ne [string]$user3.ObjectGUID }).Count | Should -Be 0 -Because 'no other object is touched' + } finally { $env:PRA_EVENT_FILE = $oldEventPath } + } +} + + +Describe 'Release 3.3.0 - a scope carried to the next phase filters the batch the same way, and the printed retention check works as printed (real main, production Directory module, synthetic AD and cloud barrier)' -Tag 'Release330G' { + BeforeAll { + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global + function script:Get-G330Why($Run) { (@(([string]$Run.Output + [string]$Run.Error) -split '\r?\n' | Where-Object { $_ -match 'Stopped at step|refused|Nothing was|cannot|failed|Error' } | Select-Object -First 8) -join ' | ') } + function script:Get-G330Flat($Run) { [regex]::Replace([string]$Run.Output, '\s+', ' ') } + function script:ConvertFrom-G330Command([string]$Text) { + $tokens = [Management.Automation.Language.Parser]::ParseInput($Text, [ref]$null, [ref]$null).Find({ param($n) $n -is [Management.Automation.Language.CommandAst] }, $true).CommandElements + $parsed = @{} + for ($position = 1; $position -lt $tokens.Count; $position++) { + if ($tokens[$position] -isnot [Management.Automation.Language.CommandParameterAst]) { continue } + $parsed[$tokens[$position].ParameterName] = [string]$tokens[$position + 1].Value + } + $parsed + } + function script:Get-G330PrintedCommand($Run, [string]$Pattern = '^\.\\Invoke-PraRemoteMailbox\.ps1 ') { @($Run.MainResult.NextSteps | Where-Object { $_ -match $Pattern } | Select-Object -Last 1)[0] } + } + AfterAll { Remove-Item -LiteralPath 'Function:\Get-G330Why', 'Function:\Get-G330Flat', 'Function:\ConvertFrom-G330Command', 'Function:\Get-G330PrintedCommand' -ErrorAction SilentlyContinue } + It 'a Recover of the shared mailboxes of a mixed batch prints -Scope SharedOnly; the cloud phase run as printed does those objects, and without the scope it stops at the users of the batch' { + $ad = New-GateRuntime -Name 'scope-ad-330g' -Shared13 -Case CloudConfirmed13 + foreach ($position in 0..2) { $ad.State.Users[$position].msExchRecipientTypeDetails = [long]1 } + [IO.File]::WriteAllText($ad.StatePath, [Management.Automation.PSSerializer]::Serialize($ad.State, 35)) + $env:PRA_GATE_STATE = $ad.StatePath; $env:PSModulePath = $ad.Modules + ';' + (Join-Path $PSHOME 'Modules') + Import-Module ActiveDirectory -Force -Global + $context = New-GateContext $ad + $plans = @(1..13 | ForEach-Object { New-PraPlan $context ('user' + $_) 'Convert' }) + $source = Invoke-PraAdBatch $context $plans 'Convert' + [IO.File]::WriteAllText($ad.StatePath, [Management.Automation.PSSerializer]::Serialize($global:PraGateAd, 35)) + $recover = Invoke-GateProcess $ad -Certificate @{Action='Recover';Phase='AD';Mode='Apply';Force=$true;ConfigPath=$ad.ConfigPath;Batch=$source.Path;Scope='SharedOnly'} -TimeoutSeconds 120 + $recover.ExitCode | Should -Be 2 -Because (Get-G330Why $recover) + $printed = Get-G330PrintedCommand $recover + $parsed = ConvertFrom-G330Command $printed + @($parsed.Keys | Sort-Object) | Should -Be @('Action', 'Batch', 'ExpectedFingerprint', 'Mode', 'Phase', 'Scope') -Because $printed + $parsed.Scope | Should -BeExactly 'SharedOnly' + $info = Get-PraTransferPackage -Path ([string]$recover.MainResult.TransferPackage) -Environment SYNTHETIC_GATE + $info.Selection.Scope | Should -BeExactly 'SharedOnly' + $info.Selection.Identity | Should -BeExactly '' + $cloud = New-GateRuntime -Name 'scope-cloud-330g' -Shared13 -Case CloudConfirmed13 + $inbox = Join-Path $cloud.State.BackupFolder 'Inbox'; $null = New-Item -ItemType Directory -Path $inbox -Force + $package = [string]$recover.MainResult.TransferPackage + Copy-Item -LiteralPath $package, ($package + '.sha256') -Destination $inbox + $without = $parsed.Clone(); $without.Remove('Scope'); $without.ConfigPath = $cloud.ConfigPath; $without.Force = $true + $refused = Invoke-GateProcess $cloud $without -TimeoutSeconds 120 + $refused.ExitCode | Should -Be 1 -Because (Get-G330Why $refused) + (Get-G330Flat $refused) | Should -Match 'Object not verified by the AD phase of this batch' + (Get-G330Flat $refused) | Should -Match 'This package was made for a part of its batch \(-Scope SharedOnly\)' -Because 'the run says what the package was made for, and applies nothing by itself' + $parsed.ConfigPath = $cloud.ConfigPath; $parsed.Force = $true + $worked = Invoke-GateProcess $cloud $parsed -TimeoutSeconds 120 + (Get-G330Flat $worked) | Should -Match 'Batch [0-9a-f]{8}: 10 object\(s\), AD proof verified' -Because (Get-G330Why $worked) + (Get-G330Flat $worked) | Should -Not -Match 'Object not verified by the AD phase of this batch' + (Get-G330Flat $worked) | Should -Not -Match 'This package was made for a part of its batch' + } + It 'the retention check printed for the cloud server carries the identity and works as printed' { + $runtime = New-GateRuntime -Name 'check-330g' -Case RetentionUnverified + $env:PRA_GATE_STATE = $runtime.StatePath; $env:PSModulePath = $runtime.Modules + ';' + (Join-Path $PSHOME 'Modules') + Import-Module ActiveDirectory -Force -Global + $context = New-GateContext $runtime + $plans = @(1..2 | ForEach-Object { New-PraPlan $context ('user' + $_) 'Convert' }) + $source = Invoke-PraAdBatch $context $plans 'Convert' + [IO.File]::WriteAllText($runtime.StatePath, [Management.Automation.PSSerializer]::Serialize($global:PraGateAd, 35)) + $preview = Invoke-GateProcess $runtime @{Action='Recover';Phase='AD';Mode='Preview';ConfigPath=$runtime.ConfigPath;Batch=$source.Path;Identity='USER1'} -TimeoutSeconds 120 + $preview.ExitCode | Should -Be 0 -Because (Get-G330Why $preview) + $match = [regex]::Match(($preview.MainResult.NextSteps -join "`n"), 'see them with: (\.\\Invoke-PraRemoteMailbox\.ps1 -Action Check .*? -Expect Retained)') + $match.Success | Should -BeTrue -Because (($preview.MainResult.NextSteps) -join ' || ') + $printed = $match.Groups[1].Value + $parsed = ConvertFrom-G330Command $printed + $parsed.Action | Should -BeExactly 'Check' + $parsed.Identity | Should -BeExactly 'USER1' + $parsed.Expect | Should -BeExactly 'Retained' + $global:PraGateAd.Case = 'Normal' + [IO.File]::WriteAllText($runtime.StatePath, [Management.Automation.PSSerializer]::Serialize($global:PraGateAd, 35)) + $parsed.ConfigPath = $runtime.ConfigPath + $checked = Invoke-GateProcess $runtime -Certificate $parsed -TimeoutSeconds 120 + $checked.ExitCode | Should -Be 0 -Because (Get-G330Why $checked) + (Get-G330Flat $checked) | Should -Match 'Scope one object: USER1' -Because 'the printed identity is the object that the check reads' + (Get-G330Flat $checked) | Should -Match 'Exchange Online checks' + (Get-G330Flat $checked) | Should -Not -Match 'Stopped at step' + } + It 'reads the selection of a run for the next phase: the identity only when the batch holds the object it names or one object, the scope only when the run filtered a batch with it (functions of the entry script)' { + $ast = [Management.Automation.Language.Parser]::ParseFile((Join-Path $global:PraGate.Package 'Invoke-PraRemoteMailbox.ps1'), [ref]$null, [ref]$null) + $text = (@('Get-PraSelectionIdentity', 'Get-PraSelectionScope') | ForEach-Object { + $name = $_ + $function = $ast.Find({ param($n) $n -is [Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -ceq $name }, $true) + $function.Extent.Text + }) -join "`n" + . ([scriptblock]::Create($text)) + $records = @( + [pscustomobject]@{ SamAccountName = 'alice'; UserPrincipalName = 'alice@contoso.invalid'; ObjectGuid = '11111111-1111-1111-1111-111111111111' } + [pscustomobject]@{ SamAccountName = 'bob'; UserPrincipalName = 'bob@contoso.invalid'; ObjectGuid = '22222222-2222-2222-2222-222222222222' }) + $context = @{ Source = [pscustomobject]@{ Data = [pscustomobject]@{ Records = $records } }; Rows = (New-Object 'Collections.Generic.List[object]') } + $Identity = 'BOB@Contoso.Invalid' + Get-PraSelectionIdentity | Should -BeExactly 'BOB@Contoso.Invalid' -Because 'a name that the batch holds is printed as typed' + $Identity = 'CN=Bob,OU=Tests,DC=contoso,DC=invalid' + Get-PraSelectionIdentity | Should -BeExactly '' -Because 'two objects in the batch and none of them is named by the text: nothing is printed' + $Identity = "bob`n-Mode Apply" + Get-PraSelectionIdentity | Should -BeExactly '' -Because 'a control character never reaches a command line' + $Identity = '' + Get-PraSelectionIdentity | Should -BeExactly '' + $Identity = 'CN=Alice,OU=Tests,DC=contoso,DC=invalid' + $context.Source.Data.Records = @($records[0]) + Get-PraSelectionIdentity | Should -BeExactly 'alice' -Because 'the batch holds one object: it is the one' + $context.Source.Data.Records = $records + $context.Rows.Add([pscustomobject]@{ SamAccountName = 'bob' }) + Get-PraSelectionIdentity | Should -BeExactly 'bob' -Because 'the run worked on one object' + foreach ($case in @( + @{ Action = 'Recover'; Phase = 'AD'; Scope = 'SharedOnly'; Batch = 'a1b2c3d4'; Expect = 'SharedOnly' } + @{ Action = 'recover'; Phase = 'Cloud'; Scope = 'usersonly'; Batch = 'a1b2c3d4'; Expect = 'usersonly' } + @{ Action = 'Convert'; Phase = 'Cloud'; Scope = 'SharedOnly'; Batch = 'a1b2c3d4'; Expect = 'SharedOnly' } + @{ Action = 'Convert'; Phase = 'AD'; Scope = 'SharedOnly'; Batch = ''; Expect = '' } + @{ Action = 'Convert'; Phase = 'AD'; Scope = 'SharedOnly'; Batch = 'a1b2c3d4'; Expect = '' } + @{ Action = 'Convert'; Phase = 'Both'; Scope = 'SharedOnly'; Batch = ''; Expect = '' } + @{ Action = 'Check'; Phase = 'Cloud'; Scope = 'UsersOnly'; Batch = 'a1b2c3d4'; Expect = 'UsersOnly' } + @{ Action = 'Check'; Phase = 'Cloud'; Scope = 'UsersOnly'; Batch = ''; Expect = '' } + @{ Action = 'Recover'; Phase = 'AD'; Scope = 'All'; Batch = 'a1b2c3d4'; Expect = '' } + @{ Action = 'Recover'; Phase = 'AD'; Scope = 'all'; Batch = 'a1b2c3d4'; Expect = '' })) { + $Action = $case.Action; $effectivePhase = $case.Phase; $Scope = $case.Scope; $Batch = $case.Batch + Get-PraSelectionScope | Should -BeExactly $case.Expect -Because ($case.Action + ' ' + $case.Phase + ' ' + $case.Scope + ' ' + $case.Batch) + } + } + It 'the command that runs a run again keeps its options: a Recover names the Convert batch that it read and keeps -AcceptRetentionRisk, a Convert names its own batch, a Preview stays a Preview (hook of the entry script)' { + $ast = [Management.Automation.Language.Parser]::ParseFile((Join-Path $global:PraGate.Package 'Invoke-PraRemoteMailbox.ps1'), [ref]$null, [ref]$null) + $assignment = $ast.Find({ param($n) $n -is [Management.Automation.Language.AssignmentStatementAst] -and $n.Left.Extent.Text -ceq '$context.RerunCommandFor' }, $true) + $assignment | Should -Not -BeNullOrEmpty + $hook = Invoke-Expression $assignment.Right.Extent.Text + function Get-PraCommandLine { param([string]$ActionName, [string]$ModeName = 'Apply', [string]$PhaseName = '', [string]$BatchId = '', [switch]$KeepFilters) ('{0}|{1}|{2}|{3}|{4}' -f $ActionName, $PhaseName, $ModeName, $BatchId, $KeepFilters.IsPresent) } + function Get-PraShortId { param([string]$Id) if ($Id.Length -gt 8) { $Id.Substring(0, 8) } else { $Id } } + $context = @{ Source = [pscustomobject]@{ Data = [pscustomobject]@{ BatchId = '0123456789abcdef0123456789abcdef' } } } + $effectiveMode = 'Apply'; $AcceptRetentionRisk = [switch]$true + & $hook 'Recover' 'Both' 'ffffffff' | Should -BeExactly 'Recover|Both|Apply|01234567|True -AcceptRetentionRisk' + & $hook 'Recover' 'Cloud' 'ffffffff' | Should -BeExactly 'Recover|Cloud|Apply|ffffffff|True' -Because 'the cloud phase of a Recover reads the batch it was given (its Source is the Convert batch), and the switch belongs to the AD part' + & $hook 'Recover' '' 'ffffffff' | Should -BeExactly 'Recover||Apply|01234567|True -AcceptRetentionRisk' -Because 'a run with no phase named is the AD part' + & $hook 'Convert' 'Cloud' 'ffffffff' | Should -BeExactly 'Convert|Cloud|Apply|ffffffff|True' -Because 'a Convert is run again with its own batch, and never with a switch that only a Recover has' + $AcceptRetentionRisk = [switch]$false; $effectiveMode = 'Preview' + & $hook 'Recover' 'AD' 'ffffffff' | Should -BeExactly 'Recover|AD|Preview|01234567|True' + } +} + + +Describe 'Release 3.3.0 - the transfer package records the objects it is for as data: optional, read without ever refusing the package, kept on the marker of its own batch only (production Common module, synthetic folders)' -Tag 'Release330G' { + BeforeAll { + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global + Add-Type -AssemblyName System.IO.Compression.FileSystem + $script:G330Pkg = Join-Path $global:PraGate.Root ('sel-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) + $null = New-Item -ItemType Directory -Path $script:G330Pkg -Force + function script:New-G330Package { + param($Selection, [string]$Id = ([guid]::NewGuid().ToString('N'))) + $folder = Join-Path (Join-Path $script:G330Pkg ([guid]::NewGuid().ToString('N').Substring(0, 6))) ('Batch-' + $Id) + $null = New-Item -ItemType Directory -Path $folder -Force + [IO.File]::WriteAllText((Join-Path $folder 'Convert-LAB.json'), '{}') + $parameters = @{ Kind = 'Convert'; Environment = 'LAB'; BatchId = $Id; Folders = @($folder); OutboxFolder = (Join-Path $script:G330Pkg ('out-' + [guid]::NewGuid().ToString('N').Substring(0, 6))) } + if ($null -ne $Selection) { $parameters.Selection = $Selection } + New-PraTransferPackage @parameters + } + # The manifest of a package written again with another Selection (any JSON value), and its checksum file: what another version could have written. + function script:Set-G330Selection($Made, $Value) { + $zip = [IO.Compression.ZipFile]::Open($Made.Path, [IO.Compression.ZipArchiveMode]::Update) + try { + $entry = $zip.GetEntry('transfer.json') + $reader = New-Object IO.StreamReader($entry.Open()); $manifest = $reader.ReadToEnd() | ConvertFrom-Json -AsHashtable; $reader.Dispose() + $manifest['Selection'] = $Value + $entry.Delete() + $replacement = $zip.CreateEntry('transfer.json') + $writer = New-Object IO.StreamWriter($replacement.Open(), (New-Object Text.UTF8Encoding($false))); $writer.Write(($manifest | ConvertTo-Json -Depth 8)); $writer.Dispose() + } + finally { $zip.Dispose() } + [IO.File]::WriteAllText($Made.Sidecar, (Get-FileHash -LiteralPath $Made.Path -Algorithm SHA256).Hash.ToLowerInvariant()) + } + } + AfterAll { Remove-Item -LiteralPath 'Function:\New-G330Package', 'Function:\Set-G330Selection' -ErrorAction SilentlyContinue } + It 'a package made without a selection reports an empty one, and the shape of its report is the one of a package that cannot be read' { + $made = New-G330Package $null + $info = Get-PraTransferPackage -Path $made.Path -Environment LAB + $info.Valid | Should -BeTrue -Because $info.Error + $info.Selection.Identity | Should -BeExactly '' + $info.Selection.Scope | Should -BeExactly '' + $info.Selection.Note | Should -BeExactly '' + $missing = Get-PraTransferPackage -Path (Join-Path $script:G330Pkg 'missing.zip') -Environment LAB + ($missing.PSObject.Properties.Name -join ',') | Should -BeExactly ($info.PSObject.Properties.Name -join ',') + } + It 'records the identity as typed and the scope in its official spelling, whatever the letter case it is given in, and the import returns them' { + $made = New-G330Package @{ Identity = "O$([char]0x2019)Brien"; Scope = 'sharedonly' } + $info = Get-PraTransferPackage -Path $made.Path -Environment LAB + $info.Valid | Should -BeTrue -Because $info.Error + $info.Selection.Identity | Should -BeExactly "O$([char]0x2019)Brien" + $info.Selection.Scope | Should -BeExactly 'SharedOnly' + $info.Selection.Note | Should -BeExactly '' + $imported = Import-PraTransferPackage -Path $made.Path -BackupFolder (Join-Path $script:G330Pkg ('in-' + [guid]::NewGuid().ToString('N').Substring(0, 6))) -Environment LAB + $imported.Selection.Identity | Should -BeExactly "O$([char]0x2019)Brien" + $imported.Selection.Scope | Should -BeExactly 'SharedOnly' + } + It 'never refuses a package for a selection that it cannot read: what is unreadable is left out, what is readable is kept, and the note says what ()' -ForEach @( + @{ Name = 'a scope of a later version'; Selection = @{ Scope = 'Everything' }; Identity = ''; Scope = ''; Note = 'the scope ''Everything'' is not known to this version' } + @{ Name = 'a control character in the identity'; Selection = @{ Identity = "user$([char]1)one" }; Identity = ''; Scope = ''; Note = 'the identity holds a control character' } + @{ Name = 'a line break in the identity'; Selection = @{ Identity = "user`none" }; Identity = ''; Scope = ''; Note = 'the identity holds a control character' } + @{ Name = 'an identity of 1025 characters and a scope'; Selection = @{ Identity = ('a' * 1025); Scope = 'SharedOnly' }; Identity = ''; Scope = 'SharedOnly'; Note = 'the identity is longer than 1024 characters and is left out' } + @{ Name = 'a good identity and a scope of a later version'; Selection = @{ Identity = 'user2'; Scope = 'Nope' }; Identity = 'user2'; Scope = ''; Note = 'is not known to this version' } + ) { + $info = Get-PraTransferPackage -Path (New-G330Package $Selection).Path -Environment LAB + $info.Valid | Should -BeTrue -Because $info.Error + $info.Selection.Identity | Should -BeExactly $Identity + $info.Selection.Scope | Should -BeExactly $Scope + $info.Selection.Note | Should -BeLike ('*' + $Note + '*') + } + It 'reads a selection that is not an object as no selection, with a note ()' -ForEach @( + @{ Name = 'text'; Value = 'user2' } + @{ Name = 'a list'; Value = @('user2') } + @{ Name = 'a number'; Value = 7 } + ) { + $made = New-G330Package $null + Set-G330Selection $made $Value + $info = Get-PraTransferPackage -Path $made.Path -Environment LAB + $info.Valid | Should -BeTrue -Because $info.Error + $info.Selection.Identity | Should -BeExactly '' + $info.Selection.Note | Should -BeLike '*is not an object*' + } + It 'accepts an identity of exactly 1024 characters' { + $info = Get-PraTransferPackage -Path (New-G330Package @{ Identity = ('a' * 1024) }).Path -Environment LAB + $info.Valid | Should -BeTrue -Because $info.Error + $info.Selection.Identity.Length | Should -Be 1024 + $info.Selection.Note | Should -BeExactly '' + } + It 'finds the folder of the batch of the package itself among the folders it brings along, for each kind and in any letter case' -ForEach @( + @{ Kind = 'Recover'; Own = 'Batch-{0}'; Other = 'Batch-ccccccccccccccccccccccccccccccc1' } + @{ Kind = 'Convert'; Own = 'BATCH-{0}'; Other = $null } + @{ Kind = 'Finalize'; Own = 'finalize-{0}'; Other = 'Batch-ccccccccccccccccccccccccccccccc1' } + ) { + $id = 'a1b2c3d4e5f60718293a4b5c6d7e8f90' + $folders = @((Join-Path 'C:\Backups' ($Own -f $id))) + if ($Other) { $folders = @((Join-Path 'C:\Backups' $Other)) + $folders } + Get-PraImportOwnFolder -Imported ([pscustomobject]@{ Kind = $Kind; BatchId = $id.ToUpperInvariant(); Folders = $folders }) | Should -BeExactly (Join-Path 'C:\Backups' ($Own -f $id)) + Get-PraImportOwnFolder -Imported ([pscustomobject]@{ Kind = $Kind; BatchId = ('0' * 32); Folders = $folders }) | Should -BeExactly '' + Get-PraImportOwnFolder -Imported ([pscustomobject]@{ Kind = 'Nothing'; BatchId = $id; Folders = $folders }) | Should -BeExactly '' + } + It 'the verified marker keeps the selection and its kind, and reads it back only for an imported folder whose files are the ones it recorded ()' -ForEach @( + @{ Name = 'intact'; Mutate = { param($state, $manifestless, $marker) }; Expect = $true } + @{ Name = 'the AD proof changed since'; Mutate = { param($state, $manifestless, $marker) [IO.File]::AppendAllText($state, ' ') }; Expect = $false } + ) { + $backups = Join-Path $script:G330Pkg ('marker-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) + $id = [guid]::NewGuid().ToString('N') + $folder = Join-Path $backups ('Batch-' + $id) + $null = New-Item -ItemType Directory -Path $folder -Force + [IO.File]::WriteAllText((Join-Path $folder 'Recover-LAB.json'), '{}') + $state = Join-Path $folder ('State-' + $id + '.json'); [IO.File]::WriteAllText($state, '{"Records":[]}') + Get-PraImportSelection -BackupFolder $backups -FolderPath $folder | Should -BeNullOrEmpty -Because 'no marker yet' + Write-PraVerifiedMarker -BackupFolder $backups -FolderPath $folder -Origin Package -Sha256 'x' -Auth Valid -Selection ([pscustomobject]@{ Identity = 'USER2'; Scope = ''; Kind = 'Recover' }) + & $Mutate $state $null $null + $read = Get-PraImportSelection -BackupFolder $backups -FolderPath $folder + if ($Expect) { + $read.Identity | Should -BeExactly 'USER2' + $read.Scope | Should -BeExactly '' + $read.Kind | Should -BeExactly 'Recover' + } + else { $read | Should -BeNullOrEmpty } + } + It 'reads the selection of a marker only when it is the marker of an import, names the folder and holds data that can be read; a scope of All without an identity names no object' { + $backups = Join-Path $script:G330Pkg ('marker-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) + $id = [guid]::NewGuid().ToString('N') + $folder = Join-Path $backups ('Batch-' + $id) + $null = New-Item -ItemType Directory -Path $folder -Force + [IO.File]::WriteAllText((Join-Path $folder 'Recover-LAB.json'), '{}') + Write-PraVerifiedMarker -BackupFolder $backups -FolderPath $folder -Origin Package -Sha256 'x' -Auth Valid -Selection ([pscustomobject]@{ Identity = 'USER2'; Scope = 'SharedOnly'; Kind = 'Recover' }) + $markerPath = Get-PraVerifiedMarkerPath -BackupFolder $backups -Id $id + $good = [IO.File]::ReadAllText($markerPath) + $mutations = @( + @{ Name = 'a marker of this server'; Mutate = { param($o) $o.Origin = 'Local' } } + @{ Name = 'another folder'; Mutate = { param($o) $o.Path = 'C:\somewhere\else' } } + @{ Name = 'no kind'; Mutate = { param($o) $o.Selection.Remove('Kind') } } + @{ Name = 'a kind that is not one'; Mutate = { param($o) $o.Selection.Kind = 'Other' } } + @{ Name = 'a selection that is a list'; Mutate = { param($o) $o.Selection = @('USER2') } } + @{ Name = 'a selection that is text'; Mutate = { param($o) $o.Selection = 'USER2' } } + @{ Name = 'only the scope All'; Mutate = { param($o) $o.Selection.Identity = ''; $o.Selection.Scope = 'All' } } + @{ Name = 'nothing named'; Mutate = { param($o) $o.Selection.Identity = ''; $o.Selection.Scope = '' } }) + foreach ($mutation in $mutations) { + $object = $good | ConvertFrom-Json -AsHashtable + & $mutation.Mutate $object + [IO.File]::WriteAllText($markerPath, ($object | ConvertTo-Json -Depth 5)) + Get-PraImportSelection -BackupFolder $backups -FolderPath $folder | Should -BeNullOrEmpty -Because $mutation.Name + } + foreach ($partial in @( + @{ Name = 'an identity with a control character'; Mutate = { param($o) $o.Selection.Identity = 'USER2' + [char]1 }; Identity = ''; Scope = 'SharedOnly' } + @{ Name = 'a scope of a later version'; Mutate = { param($o) $o.Selection.Scope = 'Everything' }; Identity = 'USER2'; Scope = '' } + @{ Name = 'an identity of 1025 characters'; Mutate = { param($o) $o.Selection.Identity = ('a' * 1025) }; Identity = ''; Scope = 'SharedOnly' })) { + $object = $good | ConvertFrom-Json -AsHashtable + & $partial.Mutate $object + [IO.File]::WriteAllText($markerPath, ($object | ConvertTo-Json -Depth 5)) + $read = Get-PraImportSelection -BackupFolder $backups -FolderPath $folder + $read.Identity | Should -BeExactly $partial.Identity -Because $partial.Name + $read.Scope | Should -BeExactly $partial.Scope -Because $partial.Name + } + [IO.File]::WriteAllText($markerPath, $good) + (Get-PraImportSelection -BackupFolder $backups -FolderPath $folder).Identity | Should -BeExactly 'USER2' + } + It 'a Finalize marker gives its selection back only while the Finalize manifest and the AD proof are the files it recorded ()' -ForEach @( + @{ Name = 'untouched'; Leaf = ''; Expect = $true } + @{ Name = 'the Finalize manifest changed'; Leaf = 'RecoverFinalize-LAB.json'; Expect = $false } + @{ Name = 'the AD proof changed'; Leaf = 'State-{0}.json'; Expect = $false } + ) { + $backups = Join-Path $script:G330Pkg ('finalize-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) + $id = [guid]::NewGuid().ToString('N') + $folder = Join-Path $backups ('Finalize-' + $id) + $null = New-Item -ItemType Directory -Path $folder -Force + [IO.File]::WriteAllText((Join-Path $folder 'RecoverFinalize-LAB.json'), '{"Items":[]}') + [IO.File]::WriteAllText((Join-Path $folder ('State-' + $id + '.json')), '{"Records":[]}') + Write-PraVerifiedMarker -BackupFolder $backups -FolderPath $folder -Origin Package -Sha256 'x' -Auth Valid -Selection ([pscustomobject]@{ Identity = 'USER2'; Scope = ''; Kind = 'Finalize' }) + if ($Leaf) { [IO.File]::AppendAllText((Join-Path $folder ($Leaf -f $id)), ' ') } + $read = Get-PraImportSelection -BackupFolder $backups -FolderPath $folder + if ($Expect) { $read.Identity | Should -BeExactly 'USER2'; $read.Kind | Should -BeExactly 'Finalize' } else { $read | Should -BeNullOrEmpty } + } + It 'the package helper of the window leaves the selection and the kind of an imported Recover package on the marker of its own batch only, and answers them' { + $work = Join-Path $script:G330Pkg ('helper-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) + $own = [guid]::NewGuid().ToString('N'); $other = [guid]::NewGuid().ToString('N') + $ownFolder = Join-Path $work ('Batch-' + $own); $otherFolder = Join-Path $work ('Batch-' + $other) + foreach ($pair in @(@($ownFolder, 'Recover-LAB.json'), @($otherFolder, 'Convert-LAB.json'))) { $null = New-Item -ItemType Directory -Path $pair[0] -Force; [IO.File]::WriteAllText((Join-Path $pair[0] $pair[1]), '{}') } + $package = New-PraTransferPackage -Kind Recover -Environment LAB -BatchId $own -Folders @($otherFolder, $ownFolder) -OutboxFolder (Join-Path $work 'Outbox') -NextCommand 'next' -ToolVersion '3.3.0' -Selection @{ Identity = 'USER2'; Scope = '' } + $backups = Join-Path $work 'Imported-Backups' + $result = Join-Path $work 'answer.json' + $helper = Join-Path $global:PraGate.Package 'module\PRA.Gui.Directory.ps1' + $arguments = @('-NoProfile', '-NonInteractive', '-File', $helper, '-ConfigPath', (Join-Path $work 'none.psd1'), '-ResultPath', $result, '-PackagePath', $package.Path, '-Environment', 'LAB', '-Import', '-BackupFolder', $backups) + $info = New-Object Diagnostics.ProcessStartInfo + $info.FileName = Join-Path $PSHOME 'pwsh.exe' + $info.Arguments = ($arguments | ForEach-Object { '"' + $_ + '"' }) -join ' ' + $info.UseShellExecute = $false; $info.CreateNoWindow = $true; $info.RedirectStandardOutput = $true; $info.RedirectStandardError = $true + $process = [Diagnostics.Process]::Start($info) + try { + $out = $process.StandardOutput.ReadToEndAsync(); $err = $process.StandardError.ReadToEndAsync() + $process.WaitForExit(120000) | Should -BeTrue + $process.ExitCode | Should -Be 0 -Because ($out.Result + $err.Result) + } + finally { $process.Dispose() } + $answer = [IO.File]::ReadAllText($result) | ConvertFrom-Json -DateKind String + $answer.Success | Should -BeTrue -Because ($answer | ConvertTo-Json -Depth 4 -Compress) + $answer.Kind | Should -BeExactly 'Recover' + $answer.Selection.Identity | Should -BeExactly 'USER2' + $answer.Selection.Kind | Should -BeExactly 'Recover' + $mine = Get-PraImportSelection -BackupFolder $backups -FolderPath (Join-Path $backups ('Batch-' + $own)) + $mine.Identity | Should -BeExactly 'USER2' + $mine.Kind | Should -BeExactly 'Recover' + Get-PraImportSelection -BackupFolder $backups -FolderPath (Join-Path $backups ('Batch-' + $other)) | Should -BeNullOrEmpty -Because 'the Convert batch only travels with the package' + Test-Path -LiteralPath (Get-PraVerifiedMarkerPath -BackupFolder $backups -Id $other) | Should -BeTrue -Because 'it is still a verified import' + } + It 'a Valid verdict that is kept keeps its record, and its selection is replaced by the one of the new import or removed; a weaker verdict never becomes a Valid one' { + $backups = Join-Path $script:G330Pkg ('marker-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) + $id = [guid]::NewGuid().ToString('N') + $folder = Join-Path $backups ('Batch-' + $id) + $null = New-Item -ItemType Directory -Path $folder -Force + [IO.File]::WriteAllText((Join-Path $folder 'Recover-LAB.json'), '{}') + Write-PraVerifiedMarker -BackupFolder $backups -FolderPath $folder -Origin Package -Sha256 'first' -Auth Valid -Selection ([pscustomobject]@{ Identity = 'USER2'; Scope = ''; Kind = 'Recover' }) + Write-PraVerifiedMarker -BackupFolder $backups -FolderPath $folder -Origin Package -Sha256 'second' -Auth Absent -Selection ([pscustomobject]@{ Identity = ''; Scope = 'SharedOnly'; Kind = 'Recover' }) + $markerPath = Get-PraVerifiedMarkerPath -BackupFolder $backups -Id $id + $record = [IO.File]::ReadAllText($markerPath) | ConvertFrom-Json -AsHashtable + $record.Auth | Should -BeExactly 'Valid' + $record.Sha256 | Should -BeExactly 'first' -Because 'the verdict and its package are kept' + (Get-PraImportSelection -BackupFolder $backups -FolderPath $folder).Scope | Should -BeExactly 'SharedOnly' + Write-PraVerifiedMarker -BackupFolder $backups -FolderPath $folder -Origin Package -Sha256 'third' -Auth Absent + $record = [IO.File]::ReadAllText($markerPath) | ConvertFrom-Json -AsHashtable + $record.Auth | Should -BeExactly 'Valid' + $record.ContainsKey('Selection') | Should -BeFalse -Because 'an import that names nothing leaves no selection behind' + Get-PraImportSelection -BackupFolder $backups -FolderPath $folder | Should -BeNullOrEmpty + } +} + +Describe 'Release 3.3.0 - Exchange Online under the execution policy AllSigned: the child starts from the script file, a refusal by the policy is recognised by its type and its identifier, a Group Policy gets a clear error (production Cloud functions, mocked policy, real child processes)' -Tag 'Release330G' { + BeforeAll { + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global + $cloudAst = [Management.Automation.Language.Parser]::ParseFile((Join-Path $global:PraGate.Package 'module\PRA.Cloud.psm1'), [ref]$null, [ref]$null) + $script:PolicyFunctions = (@('Get-PraExecutionPolicyState', 'Test-PraExoSecurityError', 'Get-PraExoPolicyRefusal', 'Get-PraExoErrorDetail', 'Test-PraExoPolicyRefusal', 'Read-PraExoRefusalDetail', 'Get-PraFileSignatureFact', 'Test-PraExoModuleSignature', 'Get-PraExoModuleCandidate', 'Get-PraExoVerifiedModule', 'Get-PraExoChildFolderPath', 'Test-PraExoChildFallback', 'Remove-PraExoChildFolder', 'Invoke-PraExoChild', 'Invoke-PraExoSubprocess') | ForEach-Object { + $name = $_ + $function = $cloudAst.Find({ param($n) $n -is [Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -ceq $name }, $true) + if ($null -eq $function) { throw ('function not found: ' + $name) } + $function.Extent.Text + }) -join "`n" + $script:SecurityText = (@('Test-PraExoSecurityError') | ForEach-Object { + $name = $_ + $cloudAst.Find({ param($n) $n -is [Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -ceq $name }, $true).Extent.Text + }) -join "`n" + $global:PraGate.L330SModes = New-Object 'Collections.Generic.List[string]' + $global:PraGate.L330SRefuse = @() + $global:PraGate.L330SPolicy = [pscustomobject]@{ Effective = 'RemoteSigned'; Source = 'LocalMachine'; Enforced = $false } + $global:PraGate.L330SChild = '' + $script:NewContext = { + param([string]$Start = 'Auto') + $log = Join-Path $global:PraGate.Root ('exo-policy-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.log') + @{ Config = @{ Cloud = @{ TenantId = ''; AppId = ''; CertificateThumbprint = ''; Organization = '' }; Exo = @{ DisableWAM = $false; ChildStart = $Start } }; TimeoutMinutes = 1; StepIndex = 0; StepTotal = 1; Issues = (New-Object 'Collections.Generic.List[object]'); Warnings = 0; LogFile = $log; Action = 'Recover'; CurrentPhase = 'Test' } + } + $script:SetPolicy = { param([string]$Effective, [string]$Source) $global:PraGate.L330SPolicy = [pscustomobject]@{ Effective = $Effective; Source = $Source; Enforced = ($Source -ceq 'MachinePolicy' -or $Source -ceq 'UserPolicy') } } + $script:InCulture = { + param([string]$Name, [scriptblock]$Body) + $thread = [Threading.Thread]::CurrentThread + $before = @($thread.CurrentCulture, $thread.CurrentUICulture) + try { $thread.CurrentCulture = [Globalization.CultureInfo]::GetCultureInfo($Name); $thread.CurrentUICulture = [Globalization.CultureInfo]::GetCultureInfo($Name); & $Body } + finally { $thread.CurrentCulture = $before[0]; $thread.CurrentUICulture = $before[1] } + } + $script:RefusalDetail = 'System.Management.Automation.PSSecurityException|UnauthorizedAccess,Microsoft.PowerShell.Commands.ImportModuleCommand' + $script:FormatDetail = 'System.Management.Automation.RuntimeException|FormatXmlUpdateException,Microsoft.PowerShell.Commands.ImportModuleCommand' + $script:Verified = [pscustomobject]@{ ManifestPath = 'C:\Modules\ExchangeOnlineManagement\3.10.1\ExchangeOnlineManagement.psd1'; Version = '3.10.1'; MinimumVersion = '3.10.1' } + # What the child process leaves in the temporary folder: the start marker, the marker of the refusal by the policy (with the original error) and the marker of the connection. + function global:Set-L330SMarker { param([string]$Id, [string[]]$Kind, [string]$Detail = '') foreach ($name in $Kind) { [IO.File]::WriteAllText((Join-Path ([IO.Path]::GetTempPath()) ('praexo_' + $Id + '.' + $name)), $(if ($name -ceq 'policy') { $Detail } else { '1' })) } } + function global:Get-L330SRequest { param([string]$Child) $match = [regex]::Match($Child, "FromBase64String\('([A-Za-z0-9+/=]+)'\)"); [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($match.Groups[1].Value)) | ConvertFrom-Json } + $script:Tree = Join-Path $global:PraGate.Root ('g330s-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) + $null = New-Item -ItemType Directory -Path $script:Tree -Force + $script:FakeModules = Join-Path $script:Tree 'fake' + $null = New-Item -ItemType Directory -Path (Join-Path $script:FakeModules 'ExchangeOnlineManagement') -Force + [IO.File]::WriteAllText((Join-Path $script:FakeModules 'ExchangeOnlineManagement\ExchangeOnlineManagement.psm1'), @' +function Get-ConnectionInformation { [CmdletBinding()] param() @() } +function Connect-ExchangeOnline { [CmdletBinding()] param($AppId, $CertificateThumbprint, $Organization, [switch]$ShowBanner, [switch]$DisableWAM) if ([string]$env:PRA_FAKE_EXO_CONNECT -ceq 'refuse') { throw [System.Management.Automation.PSSecurityException]::new('SYNTHETIC refusal') } } +function Disconnect-ExchangeOnline { [CmdletBinding()] param($ConnectionId, [switch]$Confirm) } +Export-ModuleMember -Function * +'@) + # A version above any installed one, so that the stand-in is the module that a child process finds first. + [IO.File]::WriteAllText((Join-Path $script:FakeModules 'ExchangeOnlineManagement\ExchangeOnlineManagement.psd1'), "@{ RootModule = 'ExchangeOnlineManagement.psm1'; ModuleVersion = '99.0.0'; GUID = '5b0c9f3e-6a54-4a52-9a7b-1f7a5a6c9d01'; FunctionsToExport = '*' }") + } + BeforeEach { $global:PraGate.L330SModes.Clear(); $global:PraGate.L330SRefuse = @(); & $script:SetPolicy 'RemoteSigned' 'LocalMachine'; $global:PraGate.L330SVerified = $script:Verified; $global:PraGate.L330SDetail = $script:RefusalDetail } + AfterAll { foreach ($key in 'L330SModes', 'L330SRefuse', 'L330SPolicy', 'L330SChild', 'L330SVerified', 'L330SDetail') { $global:PraGate.Remove($key) }; Remove-Item -LiteralPath 'Function:\Set-L330SMarker', 'Function:\Get-L330SRequest' -ErrorAction SilentlyContinue } + It 'reads the policy that applies from the scope that defines it first, and says when it is a Group Policy ()' -ForEach @( + @{ Name = 'machine policy'; Levels = @('AllSigned', 'Undefined', 'Undefined', 'RemoteSigned', 'Restricted'); Effective = 'AllSigned'; Source = 'MachinePolicy'; Enforced = $true } + @{ Name = 'user policy over the others'; Levels = @('Undefined', 'AllSigned', 'Bypass', 'RemoteSigned', 'Restricted'); Effective = 'AllSigned'; Source = 'UserPolicy'; Enforced = $true } + @{ Name = 'process'; Levels = @('Undefined', 'Undefined', 'AllSigned', 'RemoteSigned', 'Restricted'); Effective = 'AllSigned'; Source = 'Process'; Enforced = $false } + @{ Name = 'current user'; Levels = @('Undefined', 'Undefined', 'Undefined', 'AllSigned', 'RemoteSigned'); Effective = 'AllSigned'; Source = 'CurrentUser'; Enforced = $false } + @{ Name = 'local machine'; Levels = @('Undefined', 'Undefined', 'Undefined', 'Undefined', 'AllSigned'); Effective = 'AllSigned'; Source = 'LocalMachine'; Enforced = $false } + @{ Name = 'a group policy that is not AllSigned'; Levels = @('RemoteSigned', 'Undefined', 'Undefined', 'AllSigned', 'AllSigned'); Effective = 'RemoteSigned'; Source = 'MachinePolicy'; Enforced = $true } + ) { + . ([scriptblock]::Create($script:PolicyFunctions)) + $global:PraGate.L330SList = $Levels + Mock Get-ExecutionPolicy { + if ($List) { + $scopes = 'MachinePolicy', 'UserPolicy', 'Process', 'CurrentUser', 'LocalMachine' + foreach ($index in 0..4) { [pscustomobject]@{ Scope = [Microsoft.PowerShell.ExecutionPolicyScope]$scopes[$index]; ExecutionPolicy = [Microsoft.PowerShell.ExecutionPolicy]$global:PraGate.L330SList[$index] } } + } + else { [Microsoft.PowerShell.ExecutionPolicy]$global:PraGate.L330SList[0] } + } + try { + $state = Get-PraExecutionPolicyState + $state.Effective | Should -BeExactly $Effective + $state.Source | Should -BeExactly $Source + $state.Enforced | Should -Be $Enforced + } + finally { $global:PraGate.Remove('L330SList') } + } + It 'reports an empty policy, and no Group Policy, when the policy cannot be read' { + . ([scriptblock]::Create($script:PolicyFunctions)) + Mock Get-ExecutionPolicy { throw 'cannot read' } + $state = Get-PraExecutionPolicyState + $state.Effective | Should -BeExactly '' + $state.Enforced | Should -BeFalse + } + It 'recognises the refusal of a policy by its type, its identifier and its category, and never by the words of its message ()' -ForEach @( + @{ Name = 'the security exception'; Build = { [System.Management.Automation.ErrorRecord]::new([System.Management.Automation.PSSecurityException]::new('x'), 'AnyId', [System.Management.Automation.ErrorCategory]::NotSpecified, $null) }; Expect = $true } + @{ Name = 'the security exception in an inner exception'; Build = { [System.Management.Automation.ErrorRecord]::new([InvalidOperationException]::new('outer', [InvalidOperationException]::new('middle', [System.Management.Automation.PSSecurityException]::new('x'))), 'AnyId', [System.Management.Automation.ErrorCategory]::NotSpecified, $null) }; Expect = $true } + @{ Name = 'the identifier UnauthorizedAccess'; Build = { [System.Management.Automation.ErrorRecord]::new([Exception]::new('x'), 'UnauthorizedAccess', [System.Management.Automation.ErrorCategory]::NotSpecified, $null) }; Expect = $true } + @{ Name = 'the identifier of the import of a module'; Build = { [System.Management.Automation.ErrorRecord]::new([Exception]::new('x'), 'UnauthorizedAccess,Microsoft.PowerShell.Commands.ImportModuleCommand', [System.Management.Automation.ErrorCategory]::NotSpecified, $null) }; Expect = $true } + @{ Name = 'the identifier of a format file that the policy refuses'; Build = { [System.Management.Automation.ErrorRecord]::new([Exception]::new('x'), 'FormatXmlUpdateException,Microsoft.PowerShell.Commands.ImportModuleCommand', [System.Management.Automation.ErrorCategory]::InvalidOperation, $null) }; Expect = $true } + @{ Name = 'the identifier of a type file that the policy refuses'; Build = { [System.Management.Automation.ErrorRecord]::new([Exception]::new('x'), 'TypesXmlUpdateException', [System.Management.Automation.ErrorCategory]::InvalidOperation, $null) }; Expect = $true } + @{ Name = 'the category SecurityError'; Build = { [System.Management.Automation.ErrorRecord]::new([Exception]::new('x'), 'AnyId', [System.Management.Automation.ErrorCategory]::SecurityError, $null) }; Expect = $true } + @{ Name = 'an unwrapped policy UnauthorizedAccessException rethrown via InnerException'; Build = { [System.Management.Automation.ErrorRecord]::new([UnauthorizedAccessException]::new('File tmpEXO.psm1 cannot be loaded. See about_Execution_Policies at https://go.microsoft.com/fwlink/?LinkID=135170.'), 'File tmpEXO.psm1 cannot be loaded. See about_Execution_Policies', [System.Management.Automation.ErrorCategory]::OperationStopped, $null) }; Expect = $true } + @{ Name = 'the words of the message only'; Build = { [System.Management.Automation.ErrorRecord]::new([Exception]::new('File C:\x.psm1 cannot be loaded because it is not digitally signed. UnauthorizedAccess PSSecurityException'), 'AnyId', [System.Management.Automation.ErrorCategory]::NotSpecified, $null) }; Expect = $false } + @{ Name = 'a French message and no identifier'; Build = { [System.Management.Automation.ErrorRecord]::new([Exception]::new('Le fichier n''est pas signe numeriquement'), 'AnyId', [System.Management.Automation.ErrorCategory]::NotSpecified, $null) }; Expect = $false } + @{ Name = 'an ordinary access denied'; Build = { [System.Management.Automation.ErrorRecord]::new([UnauthorizedAccessException]::new('Access to the path is denied.'), 'System.UnauthorizedAccessException', [System.Management.Automation.ErrorCategory]::PermissionDenied, $null) }; Expect = $false } + @{ Name = 'an ordinary rethrown UnauthorizedAccessException'; Build = { [System.Management.Automation.ErrorRecord]::new([UnauthorizedAccessException]::new('Access to the path is denied.'), 'Access to the path is denied.', [System.Management.Automation.ErrorCategory]::OperationStopped, $null) }; Expect = $false } + @{ Name = 'an identifier that only starts like it'; Build = { [System.Management.Automation.ErrorRecord]::new([Exception]::new('x'), 'UnauthorizedAccessError', [System.Management.Automation.ErrorCategory]::NotSpecified, $null) }; Expect = $false } + ) { + . ([scriptblock]::Create($script:PolicyFunctions)) + Test-PraExoSecurityError -ErrorRecord (& $Build) | Should -Be $Expect + } + It 'recognises the real refusal of an unsigned module by AllSigned in a real process, in any Windows language (), and nothing else' -ForEach @(@{ Culture = 'en-US' }, @{ Culture = 'fr-FR' }) { + $script = "[Threading.Thread]::CurrentThread.CurrentUICulture = [Globalization.CultureInfo]::GetCultureInfo('$Culture')`n" + $script:SecurityText + @' + +$import = 'none'; $unwrapped = 'none'; $missing = 'none'; $words = 'none' +try { Import-Module ExchangeOnlineManagement -ErrorAction Stop; $import = 'imported' } catch { $import = [string](Test-PraExoSecurityError $_) } +try { try { Import-Module ExchangeOnlineManagement -ErrorAction Stop } catch { if ($_.Exception.InnerException) { throw $_.Exception.InnerException } else { throw } }; $unwrapped = 'imported' } catch { $unwrapped = [string](Test-PraExoSecurityError $_) } +try { $null = [IO.File]::OpenRead('C:\no\such\folder\at-all.txt') } catch { $missing = [string](Test-PraExoSecurityError $_) } +try { throw 'is not digitally signed' } catch { $words = [string](Test-PraExoSecurityError $_) } +[Console]::Out.WriteLine('RESULT import=' + $import + ' unwrapped=' + $unwrapped + ' missing=' + $missing + ' words=' + $words) +'@ + "`n" + $before = @($env:PSExecutionPolicyPreference, $env:PSModulePath) + try { + $env:PSExecutionPolicyPreference = 'AllSigned' + $env:PSModulePath = $script:FakeModules + ';' + (Join-Path $PSHOME 'Modules') + $info = New-Object Diagnostics.ProcessStartInfo + $info.FileName = Join-Path $PSHOME 'pwsh.exe' + $info.Arguments = '-NoLogo -NoProfile -NonInteractive -Command -' + $info.UseShellExecute = $false; $info.CreateNoWindow = $true; $info.RedirectStandardInput = $true; $info.RedirectStandardOutput = $true; $info.RedirectStandardError = $true + $info.StandardOutputEncoding = New-Object Text.UTF8Encoding($false) + $process = [Diagnostics.Process]::Start($info) + try { + $out = $process.StandardOutput.ReadToEndAsync(); $err = $process.StandardError.ReadToEndAsync() + $line = '& ([scriptblock]::Create([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String(''' + [Convert]::ToBase64String((New-Object Text.UTF8Encoding($false)).GetBytes($script)) + '''))))' + "`n" + $bytes = (New-Object Text.UTF8Encoding($false)).GetBytes($line) + $process.StandardInput.BaseStream.Write($bytes, 0, $bytes.Length); $process.StandardInput.BaseStream.Flush(); $process.StandardInput.Close() + $process.WaitForExit(120000) | Should -BeTrue + $text = $out.Result.Trim() + } + finally { $process.Dispose() } + } + finally { $env:PSExecutionPolicyPreference = $before[0]; $env:PSModulePath = $before[1] } + $text | Should -Match 'RESULT import=' -Because ($text + $err.Result) + $text | Should -Match 'RESULT import=True unwrapped=True missing=False words=False' -Because 'the unsigned module is refused by the policy (including when rethrown via InnerException); a missing file and the words of a message are not' + } + It 'allows the second start after a refusal by the policy, which is not a start that never ran, and still never after a connection, a timeout or a file start' -ForEach @( + @{ Mode = 'Stdin'; Attempt = 0; Attempts = 2; Started = $true; Connected = $false; TimedOut = $false; Policy = $true; Expect = $true } + @{ Mode = 'stdin'; Attempt = 0; Attempts = 2; Started = $true; Connected = $false; TimedOut = $false; Policy = $true; Expect = $true } + @{ Mode = 'Stdin'; Attempt = 0; Attempts = 2; Started = $true; Connected = $false; TimedOut = $false; Policy = $false; Expect = $false } + @{ Mode = 'Stdin'; Attempt = 0; Attempts = 2; Started = $true; Connected = $true; TimedOut = $false; Policy = $true; Expect = $false } + @{ Mode = 'Stdin'; Attempt = 0; Attempts = 2; Started = $true; Connected = $false; TimedOut = $true; Policy = $true; Expect = $false } + @{ Mode = 'Stdin'; Attempt = 0; Attempts = 1; Started = $true; Connected = $false; TimedOut = $false; Policy = $true; Expect = $false } + @{ Mode = 'File'; Attempt = 1; Attempts = 2; Started = $true; Connected = $false; TimedOut = $false; Policy = $true; Expect = $false } + ) { + . ([scriptblock]::Create($script:PolicyFunctions)) + Test-PraExoChildFallback -Mode $Mode -Attempt $Attempt -Attempts $Attempts -Started $Started -Connected $Connected -TimedOut $TimedOut -PolicyRefused $Policy | Should -Be $Expect + } + It 'starts the child directly from the script file when the policy is AllSigned, with one visible warning per run that names the module it checked (scope )' -ForEach @(@{ Source = 'LocalMachine' }, @{ Source = 'CurrentUser' }, @{ Source = 'Process' }) { + . ([scriptblock]::Create($script:PolicyFunctions)) + $script:PraExoWorker = { 'worker' } + & $script:SetPolicy 'AllSigned' $Source + Mock Get-PraExecutionPolicyState { $global:PraGate.L330SPolicy } + Mock Get-PraExoVerifiedModule { $global:PraGate.L330SVerified } + Mock Invoke-PraExoChild { $global:PraGate.L330SModes.Add($Mode); $global:PraGate.L330SChild = $Child; [pscustomobject]@{ Out = ('{"Protocol":1,"Id":"' + $Id + '","Ok":true,"Data":{"Probe":"ok"},"Error":""}'); Err = ''; ExitCode = 0; TimedOut = $false } } + $context = & $script:NewContext 'Auto' + foreach ($call in 1..2) { (Invoke-PraExoSubprocess -Context $context -Operation 'Probe' -Params @{} -Permit $null -OnApplied $null -OnProgress $null 6>$null).Probe | Should -BeExactly 'ok' } + ($global:PraGate.L330SModes -join ',') | Should -BeExactly 'File,File' + $log = [IO.File]::ReadAllText($context.LogFile) + ([regex]::Matches($log, '\[WARN +\] The execution policy is AllSigned \(scope ' + $Source + '\)')).Count | Should -Be 1 + $log | Should -Match 'checked that the files of ExchangeOnlineManagement 3\.10\.1 \(C:\\Modules\\ExchangeOnlineManagement\\3\.10\.1\\ExchangeOnlineManagement\.psd1\) have a valid Microsoft signature' + $context.Warnings | Should -Be 1 -Because 'the choice is a warning, once per run, whatever the number of calls' + $request = Get-L330SRequest $global:PraGate.L330SChild + $request.ExoManifest | Should -BeExactly $global:PraGate.L330SVerified.ManifestPath + $request.ExoMinVersion | Should -BeExactly '3.10.1' + } + It 'checks the module and gives its path to the child only under AllSigned, and warns only when the child starts from the file (, )' -ForEach @( + @{ Start = 'Auto'; Effective = 'RemoteSigned'; Modes = 'Stdin'; Warnings = 0; Checked = $false } + @{ Start = 'Auto'; Effective = 'Unrestricted'; Modes = 'Stdin'; Warnings = 0; Checked = $false } + @{ Start = 'Auto'; Effective = ''; Modes = 'Stdin'; Warnings = 0; Checked = $false } + @{ Start = 'Stdin'; Effective = 'AllSigned'; Modes = 'Stdin'; Warnings = 0; Checked = $true } + @{ Start = 'File'; Effective = 'AllSigned'; Modes = 'File'; Warnings = 1; Checked = $true } + @{ Start = 'FILE'; Effective = 'RemoteSigned'; Modes = 'File'; Warnings = 0; Checked = $false } + ) { + . ([scriptblock]::Create($script:PolicyFunctions)) + $script:PraExoWorker = { 'worker' } + & $script:SetPolicy $Effective 'LocalMachine' + Mock Get-PraExecutionPolicyState { $global:PraGate.L330SPolicy } + Mock Get-PraExoVerifiedModule { $global:PraGate.L330SVerified } + Mock Invoke-PraExoChild { $global:PraGate.L330SModes.Add($Mode); $global:PraGate.L330SChild = $Child; [pscustomobject]@{ Out = ('{"Protocol":1,"Id":"' + $Id + '","Ok":true,"Data":{"Probe":"ok"},"Error":""}'); Err = ''; ExitCode = 0; TimedOut = $false } } + $context = & $script:NewContext $Start + (Invoke-PraExoSubprocess -Context $context -Operation 'Probe' -Params @{} -Permit $null -OnApplied $null -OnProgress $null 6>$null).Probe | Should -BeExactly 'ok' + ($global:PraGate.L330SModes -join ',') | Should -BeExactly $Modes + $context.Warnings | Should -Be $Warnings + $request = Get-L330SRequest $global:PraGate.L330SChild + if ($Checked) { $request.ExoManifest | Should -BeExactly $global:PraGate.L330SVerified.ManifestPath; Should -Invoke Get-PraExoVerifiedModule -Times 1 -Exactly } + else { $request.ExoManifest | Should -BeExactly ''; Should -Invoke Get-PraExoVerifiedModule -Times 0 -Exactly } + } + It 'stops before any child starts when ExchangeOnlineManagement is not validly signed or not installed, with the error and the Next steps, and does not check it under a Group Policy' { + . ([scriptblock]::Create($script:PolicyFunctions)) + $script:PraExoWorker = { 'worker' } + Mock Get-PraExecutionPolicyState { $global:PraGate.L330SPolicy } + Mock Invoke-PraExoChild { $global:PraGate.L330SModes.Add($Mode); [pscustomobject]@{ Out = ''; Err = ''; ExitCode = 0; TimedOut = $false } } + Mock Get-PraExoModuleCandidate { [pscustomobject]@{ Name = 'ExchangeOnlineManagement'; Version = [version]'3.10.1'; Path = 'C:\Modules\EOM\3.10.1\ExchangeOnlineManagement.psd1'; ModuleBase = 'C:\Modules\EOM\3.10.1' } } + Mock Test-PraExoModuleSignature { [pscustomobject]@{ Ok = $false; Checked = 40; Problems = @('netCore\Tampered.dll: HashMismatch', 'ExchangeOnlineManagement.psm1: NotSigned'); ProblemCount = 2 } } + & $script:SetPolicy 'AllSigned' 'CurrentUser' + $context = & $script:NewContext 'Auto' + { Invoke-PraExoSubprocess -Context $context -Operation 'Probe' -Params @{} -Permit $null -OnApplied $null -OnProgress $null 6>$null } | Should -Throw '*ExchangeOnlineManagement 3.10.1 (C:\Modules\EOM\3.10.1) is not validly signed by Microsoft: 2 problem(s) in 40 file(s), first: netCore\Tampered.dll: HashMismatch; ExchangeOnlineManagement.psm1: NotSigned*Nothing was started and nothing was sent to Exchange Online.' + $global:PraGate.L330SModes.Count | Should -Be 0 + $context.NextOnFailure | Should -BeTrue + $context.NextSteps.Count | Should -Be 2 + $context.NextSteps[0] | Should -BeLike 'Install the module again from the PowerShell Gallery and do not edit its files*' + Mock Get-PraExoModuleCandidate { [pscustomobject]@{ Name = 'ExchangeOnlineManagement'; Version = [version]'3.9.0'; Path = 'C:\Modules\EOM\3.9.0\ExchangeOnlineManagement.psd1'; ModuleBase = 'C:\Modules\EOM\3.9.0' } } + $context = & $script:NewContext 'Auto' + { Invoke-PraExoSubprocess -Context $context -Operation 'Probe' -Params @{} -Permit $null -OnApplied $null -OnProgress $null 6>$null } | Should -Throw '*ExchangeOnlineManagement 3.10.1 or later is not installed*Nothing was sent to Exchange Online.' + $context.NextSteps[0] | Should -BeLike 'Install ExchangeOnlineManagement 3.10.1 or later from the PowerShell Gallery*' + $global:PraGate.L330SModes.Count | Should -Be 0 + & $script:SetPolicy 'AllSigned' 'MachinePolicy' + $global:PraGate.L330SRefuse = @('Stdin') + $context = & $script:NewContext 'Auto' + { Invoke-PraExoSubprocess -Context $context -Operation 'Probe' -Params @{} -Permit $null -OnApplied $null -OnProgress $null 6>$null } | Should -Throw -ExceptionType ([System.Management.Automation.RuntimeException]) + Should -Invoke Test-PraExoModuleSignature -Times 1 -Exactly -Because 'only the two runs under a policy that the tool can work with checked the module' + } + It 'picks the highest installed version at the minimum or later, checks it once per run and does not take a lower one ()' -ForEach @( + @{ Case = 'three versions'; Versions = @('3.9.0', '3.11.0', '3.10.1'); Picked = '3.11.0' } + @{ Case = 'one at the minimum'; Versions = @('3.10.1'); Picked = '3.10.1' } + ) { + . ([scriptblock]::Create($script:PolicyFunctions)) + $global:PraGate.L330SVersions = $Versions + Mock Get-PraExoModuleCandidate { foreach ($v in $global:PraGate.L330SVersions) { [pscustomobject]@{ Name = 'ExchangeOnlineManagement'; Version = [version]$v; Path = ('C:\M\' + $v + '\ExchangeOnlineManagement.psd1'); ModuleBase = ('C:\M\' + $v) } } } + Mock Test-PraExoModuleSignature { [pscustomobject]@{ Ok = $true; Checked = 10; Problems = @(); ProblemCount = 0 } } + try { + $context = & $script:NewContext 'Auto' + $first = Get-PraExoVerifiedModule -Context $context + $first.Version | Should -BeExactly $Picked + $first.ManifestPath | Should -BeExactly ('C:\M\' + $Picked + '\ExchangeOnlineManagement.psd1') + $first.MinimumVersion | Should -BeExactly '3.10.1' + $null = Get-PraExoVerifiedModule -Context $context + Should -Invoke Test-PraExoModuleSignature -Times 1 -Exactly + } + finally { $global:PraGate.Remove('L330SVersions') } + } + It 'checks the files of a module folder: valid Microsoft signatures only, outside the reference assemblies and the .NET Framework copies, Newtonsoft.Json.dll of the .NET Foundation the only other signer ()' -ForEach @( + @{ Name = 'every file signed by Microsoft'; Facts = @{}; Ok = $true; Problem = '' } + @{ Name = 'a script that is not signed'; Facts = @{ 'ExchangeOnlineManagement.psm1' = @('NotSigned', '', '') }; Ok = $false; Problem = 'ExchangeOnlineManagement.psm1: NotSigned' } + @{ Name = 'a manifest changed after it was signed'; Facts = @{ 'ExchangeOnlineManagement.psd1' = @('HashMismatch', 'Microsoft Corporation', '8F43288AD272F3103B6FB1428485EA3014C0BCFE') }; Ok = $false; Problem = 'ExchangeOnlineManagement.psd1: HashMismatch' } + @{ Name = 'a dll that is not signed'; Facts = @{ 'netCore\Azure.Core.dll' = @('NotSigned', '', '') }; Ok = $false; Problem = 'netCore\Azure.Core.dll: NotSigned' } + @{ Name = 'a valid signature of another publisher'; Facts = @{ 'netCore\Azure.Core.dll' = @('Valid', 'Someone Else', 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA') }; Ok = $false; Problem = 'netCore\Azure.Core.dll: signed by a publisher that is not Microsoft' } + @{ Name = 'a signature whose chain ends elsewhere but whose name says Microsoft'; Facts = @{ 'ExchangeOnlineManagement.ps1xml' = @('Valid', 'Microsoft Corporation', 'BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB') }; Ok = $false; Problem = 'ExchangeOnlineManagement.ps1xml: signed by a publisher that is not Microsoft' } + @{ Name = 'Newtonsoft.Json.dll of the .NET Foundation'; Facts = @{ 'netCore\Newtonsoft.Json.dll' = @('Valid', 'Json.NET (.NET Foundation)', 'CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC') }; Ok = $true; Problem = '' } + @{ Name = 'Newtonsoft.Json.dll of someone else'; Facts = @{ 'netCore\Newtonsoft.Json.dll' = @('Valid', 'Someone Else', 'CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC') }; Ok = $false; Problem = 'netCore\Newtonsoft.Json.dll: signed by a publisher that is not Microsoft' } + @{ Name = 'another dll of the .NET Foundation'; Facts = @{ 'netCore\Azure.Core.dll' = @('Valid', 'Json.NET (.NET Foundation)', 'CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC') }; Ok = $false; Problem = 'netCore\Azure.Core.dll: signed by a publisher that is not Microsoft' } + @{ Name = 'unsigned reference assemblies and framework copies'; Facts = @{ 'netCore\ref\Reference.dll' = @('NotSigned', '', ''); 'netFramework\Legacy.dll' = @('NotSigned', '', ''); 'netFramework\ref\Legacy.dll' = @('NotSigned', '', '') }; Ok = $true; Problem = '' } + @{ Name = 'the root written in lower case'; Facts = @{ 'netCore\Azure.Core.dll' = @('Valid', 'Microsoft Corporation', '06f1aa330b927b753a40e68cdf22e34bcbef3352') }; Ok = $true; Problem = '' } + ) { + . ([scriptblock]::Create($script:PolicyFunctions)) + $base = Join-Path $script:Tree ('module-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) + foreach ($relative in 'ExchangeOnlineManagement.psd1', 'ExchangeOnlineManagement.psm1', 'ExchangeOnlineManagement.ps1xml', 'netCore\Azure.Core.dll', 'netCore\Newtonsoft.Json.dll', 'netCore\ref\Reference.dll', 'netFramework\Legacy.dll', 'netFramework\ref\Legacy.dll', 'readme.txt', 'netCore\data.json') { + $path = Join-Path $base $relative + $null = New-Item -ItemType Directory -Path (Split-Path $path -Parent) -Force + [IO.File]::WriteAllText($path, 'x') + } + $global:PraGate.L330SFacts = $Facts + Mock Get-PraFileSignatureFact { + $relative = $Path.Substring($Path.IndexOf('module-')).Split('\', 2)[1] + $fact = $global:PraGate.L330SFacts[$relative] + if ($null -eq $fact) { $fact = @('Valid', 'Microsoft Corporation', '8F43288AD272F3103B6FB1428485EA3014C0BCFE') } + [pscustomobject]@{ Status = $fact[0]; Signer = $fact[1]; Root = $fact[2] } + } + try { + $result = Test-PraExoModuleSignature -ModuleBase $base + $result.Ok | Should -Be $Ok -Because (@($result.Problems) -join '; ') + if ($Problem) { @($result.Problems) | Should -Contain $Problem } + $result.Checked | Should -BeGreaterThan 0 + } + finally { $global:PraGate.Remove('L330SFacts') } + } + It 'does not check a file that is not a script, a data file or a dll, and refuses an empty folder' { + . ([scriptblock]::Create($script:PolicyFunctions)) + $base = Join-Path $script:Tree ('module-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) + $null = New-Item -ItemType Directory -Path $base -Force + [IO.File]::WriteAllText((Join-Path $base 'readme.txt'), 'x') + Mock Get-PraFileSignatureFact { throw 'no file is to be read' } + $result = Test-PraExoModuleSignature -ModuleBase $base + $result.Ok | Should -BeFalse -Because 'a folder without any file to check is not a module that was checked' + $result.Checked | Should -Be 0 + } + It 'reads the real signatures of Microsoft files, and a changed copy is refused (real Authenticode, the module installed on this computer)' { + . ([scriptblock]::Create($script:PolicyFunctions)) + $installed = $null + foreach ($root in @((Join-Path ([Environment]::GetFolderPath('MyDocuments')) 'PowerShell\Modules'), (Join-Path $env:ProgramFiles 'PowerShell\Modules'), (Join-Path $env:ProgramFiles 'WindowsPowerShell\Modules'))) { + $folder = Join-Path $root 'ExchangeOnlineManagement' + if (-not (Test-Path -LiteralPath $folder)) { continue } + foreach ($versionFolder in Get-ChildItem -LiteralPath $folder -Directory | Sort-Object { try { [version]$_.Name } catch { [version]'0.0' } } -Descending) { + if ((Test-Path -LiteralPath (Join-Path $versionFolder.FullName 'ExchangeOnlineManagement.psd1')) -and (Test-Path -LiteralPath (Join-Path $versionFolder.FullName 'netCore\ExchangeOnlineManagement.psm1'))) { $installed = $versionFolder.FullName; break } + } + if ($installed) { break } + } + if (-not $installed) { Set-ItResult -Skipped -Because 'ExchangeOnlineManagement is not installed on this computer'; return } + $copy = Join-Path $script:Tree ('real-module-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) + $null = New-Item -ItemType Directory -Path (Join-Path $copy 'netCore') -Force + Copy-Item -LiteralPath (Join-Path $installed 'ExchangeOnlineManagement.psd1') -Destination $copy + Copy-Item -LiteralPath (Join-Path $installed 'netCore\ExchangeOnlineManagement.psm1') -Destination (Join-Path $copy 'netCore') + $good = Test-PraExoModuleSignature -ModuleBase $copy + $good.Ok | Should -BeTrue -Because (@($good.Problems) -join '; ') + $good.Checked | Should -Be 2 + $changed = Join-Path $copy 'netCore\ExchangeOnlineManagement.psm1' + [IO.File]::WriteAllText($changed, ("# changed`r`n" + [IO.File]::ReadAllText($changed)), (New-Object Text.UTF8Encoding($true))) + $bad = Test-PraExoModuleSignature -ModuleBase $copy + $bad.Ok | Should -BeFalse + @($bad.Problems)[0] | Should -BeExactly 'netCore\ExchangeOnlineManagement.psm1: HashMismatch' + $fact = Get-PraFileSignatureFact -Path (Join-Path $installed 'ExchangeOnlineManagement.psd1') + $fact.Status | Should -BeExactly 'Valid' + $fact.Root | Should -Match '^[0-9A-F]{40}$' + (Get-PraFileSignatureFact -Path (Join-Path $script:Tree 'no-such-file.psm1')).Status | Should -BeExactly 'Unreadable' + } + It 'tells the original type and error identifier, the security exception first when it is inside another exception' { + . ([scriptblock]::Create($script:PolicyFunctions)) + $inner = [System.Management.Automation.PSSecurityException]::new('x') + $wrapped = [System.Management.Automation.ErrorRecord]::new([InvalidOperationException]::new('outer', $inner), 'UnauthorizedAccess,Microsoft.PowerShell.Commands.ImportModuleCommand', [System.Management.Automation.ErrorCategory]::SecurityError, $null) + Get-PraExoErrorDetail -ErrorRecord $wrapped | Should -BeExactly 'System.Management.Automation.PSSecurityException|UnauthorizedAccess,Microsoft.PowerShell.Commands.ImportModuleCommand' + $plain = [System.Management.Automation.ErrorRecord]::new([InvalidOperationException]::new('x'), 'FormatXmlUpdateException', [System.Management.Automation.ErrorCategory]::InvalidOperation, $null) + Get-PraExoErrorDetail -ErrorRecord $plain | Should -BeExactly 'System.InvalidOperationException|FormatXmlUpdateException' + $unwrapped = [System.Management.Automation.ErrorRecord]::new([UnauthorizedAccessException]::new('File tmpEXO.psm1 cannot be loaded. See about_Execution_Policies.'), 'File tmpEXO.psm1 cannot be loaded. See about_Execution_Policies.', [System.Management.Automation.ErrorCategory]::OperationStopped, $null) + Get-PraExoErrorDetail -ErrorRecord $unwrapped | Should -BeExactly 'System.UnauthorizedAccessException|UnauthorizedAccess' + } + It 'tells a refusal by the policy only for AllSigned, a security exception or UnauthorizedAccess ()' -ForEach @( + @{ Name = 'AllSigned, any error'; Effective = 'AllSigned'; Detail = 'System.InvalidOperationException|Whatever'; Expect = $true } + @{ Name = 'AllSigned, no detail'; Effective = 'allsigned'; Detail = ''; Expect = $true } + @{ Name = 'another policy, the security exception'; Effective = 'RemoteSigned'; Detail = 'System.Management.Automation.PSSecurityException|AnyId'; Expect = $true } + @{ Name = 'another policy, UnauthorizedAccess'; Effective = 'RemoteSigned'; Detail = 'System.InvalidOperationException|UnauthorizedAccess,Microsoft.PowerShell.Commands.ImportModuleCommand'; Expect = $true } + @{ Name = 'another policy, a format file'; Effective = 'RemoteSigned'; Detail = 'System.Management.Automation.RuntimeException|FormatXmlUpdateException,Microsoft.PowerShell.Commands.ImportModuleCommand'; Expect = $false } + @{ Name = 'another policy, a type file'; Effective = 'Unrestricted'; Detail = 'System.Management.Automation.RuntimeException|TypesXmlUpdateException'; Expect = $false } + @{ Name = 'no policy read, no detail'; Effective = ''; Detail = ''; Expect = $false } + @{ Name = 'another policy, an identifier that only starts like it'; Effective = 'RemoteSigned'; Detail = 'System.InvalidOperationException|UnauthorizedAccessError'; Expect = $false } + ) { + . ([scriptblock]::Create($script:PolicyFunctions)) + Test-PraExoPolicyRefusal -Policy ([pscustomobject]@{ Effective = $Effective; Source = 'LocalMachine'; Enforced = $false }) -Detail $Detail | Should -Be $Expect + } + It 'ends every refusal text with the original error and names the policy in force, never AllSigned when it is another one (, )' -ForEach @( + @{ Mode = 'Stdin'; Effective = 'RemoteSigned'; Source = 'LocalMachine'; Like = '*in the child process started from its standard input. Exo.ChildStart = Stdin cannot work under the execution policy RemoteSigned. Nothing was sent to Exchange Online. Error: System.Management.Automation.PSSecurityException, UnauthorizedAccess,Microsoft.PowerShell.Commands.ImportModuleCommand.'; Steps = 1 } + @{ Mode = 'InProcess'; Effective = 'RemoteSigned'; Source = 'LocalMachine'; Like = '*in this PowerShell process, so Exchange Online cannot be reached in process under the execution policy RemoteSigned. Nothing was sent to Exchange Online. Error: System.Management.Automation.PSSecurityException, UnauthorizedAccess,*'; Steps = 1 } + @{ Mode = 'Stdin'; Effective = 'AllSigned'; Source = 'CurrentUser'; Like = '*in the child process started from its standard input (ExchangeOnlineManagement writes an unsigned temporary module when it connects). Exo.ChildStart = Stdin cannot work under the execution policy AllSigned.*Error: System.Management.Automation.PSSecurityException, UnauthorizedAccess,*'; Steps = 2 } + @{ Mode = 'File'; Effective = 'RemoteSigned'; Source = 'LocalMachine'; Like = '*The execution policy (RemoteSigned) refused a PowerShell file*even in a child process started from a script file with -ExecutionPolicy Bypass*'; Steps = 1 } + @{ Mode = 'InProcess'; Effective = 'AllSigned'; Source = 'MachinePolicy'; Like = '*is set by Group Policy (MachinePolicy)*Error: System.Management.Automation.PSSecurityException, UnauthorizedAccess,*'; Steps = 2 } + @{ Mode = 'InProcess'; Effective = 'RemoteSigned'; Source = 'UserPolicy'; Like = '*the execution policy RemoteSigned is set by Group Policy (UserPolicy) and refuses a PowerShell file that the Exchange Online module needs. The -ExecutionPolicy parameter*'; Steps = 1 } + ) { + . ([scriptblock]::Create($script:PolicyFunctions)) + $context = @{} + $text = Get-PraExoPolicyRefusal -Context $context -Policy ([pscustomobject]@{ Effective = $Effective; Source = $Source; Enforced = ($Source -ceq 'MachinePolicy' -or $Source -ceq 'UserPolicy') }) -Mode $Mode -Detail $script:RefusalDetail + $text | Should -BeLike $Like + if ($Effective -cne 'AllSigned') { $text | Should -Not -Match 'AllSigned' } + $context.NextSteps.Count | Should -Be $Steps + $context.NextOnFailure | Should -BeTrue + } + It 'starts once more from the script file, with one warning and the reason in the log, when the child from the standard input is refused by the policy ()' -ForEach @(@{ Culture = 'en-US' }, @{ Culture = 'fr-FR' }) { + . ([scriptblock]::Create($script:PolicyFunctions)) + $script:PraExoWorker = { 'worker' } + Mock Get-PraExecutionPolicyState { $global:PraGate.L330SPolicy } + $global:PraGate.L330SRefuse = @('Stdin') + $global:PraGate.L330SDetail = $script:RefusalDetail + Mock Invoke-PraExoChild { + $global:PraGate.L330SModes.Add($Mode) + if ($global:PraGate.L330SRefuse -contains $Mode) { + Set-L330SMarker -Id $Id -Kind 'started', 'policy' -Detail $global:PraGate.L330SDetail + return [pscustomobject]@{ Out = '{"Protocol":1,"Id":"x","Ok":false,"Data":null,"Error":"refused"}'; Err = ''; ExitCode = 1; TimedOut = $false } + } + [pscustomobject]@{ Out = ('{"Protocol":1,"Id":"' + $Id + '","Ok":true,"Data":{"Probe":"ok"},"Error":""}'); Err = ''; ExitCode = 0; TimedOut = $false } + } + $context = & $script:NewContext 'Auto' + $before = @(Get-ChildItem -LiteralPath ([IO.Path]::GetTempPath()) -Filter 'praexo_*.policy' -ErrorAction SilentlyContinue).Count + & $script:InCulture $Culture { (Invoke-PraExoSubprocess -Context $context -Operation 'Probe' -Params @{} -Permit $null -OnApplied $null -OnProgress $null 6>$null).Probe | Should -BeExactly 'ok' } + ($global:PraGate.L330SModes -join ',') | Should -BeExactly 'Stdin,File' + $context.Warnings | Should -Be 1 + $log = [IO.File]::ReadAllText($context.LogFile) + $log | Should -Match '\[WARN +\] The execution policy refused a PowerShell file of the Exchange Online module in the child process started from its standard input' + $log | Should -Match '(?m)\[DETAIL\] Exchange Online child process started from a temporary script file in a private folder\.\r?$' + @(Get-ChildItem -LiteralPath ([IO.Path]::GetTempPath()) -Filter 'praexo_*.policy' -ErrorAction SilentlyContinue).Count | Should -Be $before -Because 'the marker of the refusal is deleted at the end' + $global:PraGate.Remove('L330SDetail') + } + It 'does not start a second time for a child that ran and failed for another reason, even under AllSigned' { + . ([scriptblock]::Create($script:PolicyFunctions)) + $script:PraExoWorker = { 'worker' } + Mock Get-PraExecutionPolicyState { $global:PraGate.L330SPolicy } + Mock Invoke-PraExoChild { + $global:PraGate.L330SModes.Add($Mode) + Set-L330SMarker -Id $Id -Kind 'started' + [pscustomobject]@{ Out = '{"Protocol":1,"Id":"x","Ok":false,"Data":null,"Error":"AADSTS700027"}'; Err = ''; ExitCode = 1; TimedOut = $false } + } + $context = & $script:NewContext 'Auto' + { Invoke-PraExoSubprocess -Context $context -Operation 'Probe' -Params @{} -Permit $null -OnApplied $null -OnProgress $null 6>$null } | Should -Throw '*child process code=1*' + ($global:PraGate.L330SModes -join ',') | Should -BeExactly 'Stdin' + $context.ContainsKey('NextSteps') | Should -BeFalse + } + It 'a refusal by the policy that arrives after the child connected is never told as one and never starts the child again: a write may have happened ()' -ForEach @(@{ Mode = 'Stdin' }, @{ Mode = 'File' }) { + . ([scriptblock]::Create($script:PolicyFunctions)) + $script:PraExoWorker = { 'worker' } + Mock Get-PraExecutionPolicyState { $global:PraGate.L330SPolicy } + $global:PraGate.L330SDetail = $script:RefusalDetail + Mock Invoke-PraExoChild { + $global:PraGate.L330SModes.Add($Mode) + Set-L330SMarker -Id $Id -Kind 'started', 'connected', 'policy' -Detail $global:PraGate.L330SDetail + [pscustomobject]@{ Out = '{"Protocol":1,"Id":"x","Ok":false,"Data":null,"Error":"refused after the sign-in"}'; Err = ''; ExitCode = 1; TimedOut = $false } + } + & $script:SetPolicy 'AllSigned' 'CurrentUser' + Mock Get-PraExoVerifiedModule { $global:PraGate.L330SVerified } + $context = & $script:NewContext $Mode + { Invoke-PraExoSubprocess -Context $context -Operation 'Probe' -Params @{} -Permit $null -OnApplied $null -OnProgress $null 6>$null } | Should -Throw '*child process code=1*refused after the sign-in*' + $global:PraGate.L330SModes.Count | Should -Be 1 + $context.ContainsKey('NextSteps') | Should -BeFalse -Because 'the text that says that nothing was sent to Exchange Online would be false' + $global:PraGate.Remove('L330SDetail') + } + It 'under another policy, a refusal that is not a security exception starts the child once more in Auto and is reported as it is in Stdin ()' -ForEach @(@{ Culture = 'en-US' }, @{ Culture = 'fr-FR' }) { + . ([scriptblock]::Create($script:PolicyFunctions)) + $script:PraExoWorker = { 'worker' } + Mock Get-PraExecutionPolicyState { $global:PraGate.L330SPolicy } + $global:PraGate.L330SRefuse = @('Stdin') + $global:PraGate.L330SDetail = $script:FormatDetail + Mock Invoke-PraExoChild { + $global:PraGate.L330SModes.Add($Mode) + if ($global:PraGate.L330SRefuse -contains $Mode) { + Set-L330SMarker -Id $Id -Kind 'started', 'policy' -Detail $global:PraGate.L330SDetail + return [pscustomobject]@{ Out = '{"Protocol":1,"Id":"x","Ok":false,"Data":null,"Error":"format file refused"}'; Err = ''; ExitCode = 1; TimedOut = $false } + } + [pscustomobject]@{ Out = ('{"Protocol":1,"Id":"' + $Id + '","Ok":true,"Data":{"Probe":"ok"},"Error":""}'); Err = ''; ExitCode = 0; TimedOut = $false } + } + $context = & $script:NewContext 'Auto' + & $script:InCulture $Culture { (Invoke-PraExoSubprocess -Context $context -Operation 'Probe' -Params @{} -Permit $null -OnApplied $null -OnProgress $null 6>$null).Probe | Should -BeExactly 'ok' } + ($global:PraGate.L330SModes -join ',') | Should -BeExactly 'Stdin,File' + $global:PraGate.L330SModes.Clear() + $context = & $script:NewContext 'Stdin' + { Invoke-PraExoSubprocess -Context $context -Operation 'Probe' -Params @{} -Permit $null -OnApplied $null -OnProgress $null 6>$null } | Should -Throw '*child process code=1*format file refused*' + $context.ContainsKey('NextSteps') | Should -BeFalse -Because 'a policy that is not AllSigned and an error that is not a refusal by it: the error is told as it is' + $global:PraGate.Remove('L330SDetail') + } + It 'under a Group Policy that enforces AllSigned no start mode can work: one start from the standard input, no check of the module, a clear error with the original error and Next steps ()' -ForEach @(@{ Culture = 'en-US' }, @{ Culture = 'fr-FR' }) { + . ([scriptblock]::Create($script:PolicyFunctions)) + $script:PraExoWorker = { 'worker' } + & $script:SetPolicy 'AllSigned' 'MachinePolicy' + Mock Get-PraExecutionPolicyState { $global:PraGate.L330SPolicy } + Mock Get-PraExoVerifiedModule { throw 'the module is not checked under a Group Policy' } + $global:PraGate.L330SDetail = $script:RefusalDetail + Mock Invoke-PraExoChild { + $global:PraGate.L330SModes.Add($Mode) + Set-L330SMarker -Id $Id -Kind 'started', 'policy' -Detail $global:PraGate.L330SDetail + [pscustomobject]@{ Out = '{"Protocol":1,"Id":"x","Ok":false,"Data":null,"Error":"refused"}'; Err = ''; ExitCode = 1; TimedOut = $false } + } + $context = & $script:NewContext 'Auto' + $box = @{ Message = '' } + & $script:InCulture $Culture { try { Invoke-PraExoSubprocess -Context $context -Operation 'Probe' -Params @{} -Permit $null -OnApplied $null -OnProgress $null 6>$null } catch { $box.Message = $_.Exception.Message } } + ($global:PraGate.L330SModes -join ',') | Should -BeExactly 'Stdin' -Because 'the file start cannot work under a Group Policy: it is not tried' + $box.Message | Should -BeLike '*The Exchange Online part cannot run on this computer: the execution policy AllSigned is set by Group Policy (MachinePolicy)*-ExecutionPolicy parameter of a child process cannot override a Group Policy*no value of Exo.ChildStart and no in-process connection can work*Nothing was sent to Exchange Online. Error: System.Management.Automation.PSSecurityException, UnauthorizedAccess,Microsoft.PowerShell.Commands.ImportModuleCommand.' + $context.NextOnFailure | Should -BeTrue + $context.NextSteps.Count | Should -Be 2 + $context.NextSteps[0] | Should -BeLike 'Ask the administrator of that Group Policy for an exception for this computer*or run the Exchange Online part on a computer where AllSigned is not enforced by Group Policy.' + $context.NextSteps[1] | Should -BeLike '*PowerShell, Active Directory, Microsoft Graph, ExchangeOnlineManagement*Trusted Publishers*' + $global:PraGate.Remove('L330SDetail') + } + It 'refuses Exo.ChildStart = File under a Group Policy that enforces AllSigned before it starts anything (UserPolicy)' { + . ([scriptblock]::Create($script:PolicyFunctions)) + $script:PraExoWorker = { 'worker' } + & $script:SetPolicy 'AllSigned' 'UserPolicy' + Mock Get-PraExecutionPolicyState { $global:PraGate.L330SPolicy } + Mock Invoke-PraExoChild { $global:PraGate.L330SModes.Add($Mode); [pscustomobject]@{ Out = ''; Err = ''; ExitCode = 0; TimedOut = $false } } + $context = & $script:NewContext 'File' + { Invoke-PraExoSubprocess -Context $context -Operation 'Probe' -Params @{} -Permit $null -OnApplied $null -OnProgress $null 6>$null } | Should -Throw '*is set by Group Policy (UserPolicy)*' + $global:PraGate.L330SModes.Count | Should -Be 0 + $context.NextSteps.Count | Should -Be 2 + } + It 'tells Exo.ChildStart = Stdin under AllSigned to use Auto or File, and says when the file start was refused too' { + . ([scriptblock]::Create($script:PolicyFunctions)) + $script:PraExoWorker = { 'worker' } + Mock Get-PraExecutionPolicyState { $global:PraGate.L330SPolicy } + Mock Get-PraExoVerifiedModule { $global:PraGate.L330SVerified } + $global:PraGate.L330SDetail = $script:RefusalDetail + Mock Invoke-PraExoChild { + $global:PraGate.L330SModes.Add($Mode) + Set-L330SMarker -Id $Id -Kind 'started', 'policy' -Detail $global:PraGate.L330SDetail + [pscustomobject]@{ Out = '{"Protocol":1,"Id":"x","Ok":false,"Data":null,"Error":"refused"}'; Err = ''; ExitCode = 1; TimedOut = $false } + } + & $script:SetPolicy 'AllSigned' 'CurrentUser' + $context = & $script:NewContext 'Stdin' + { Invoke-PraExoSubprocess -Context $context -Operation 'Probe' -Params @{} -Permit $null -OnApplied $null -OnProgress $null 6>$null } | Should -Throw '*Exo.ChildStart = Stdin cannot work under the execution policy AllSigned*Error: System.Management.Automation.PSSecurityException, UnauthorizedAccess,*' + ($global:PraGate.L330SModes -join ',') | Should -BeExactly 'Stdin' + $context.NextSteps[0] | Should -BeLike 'Set Exo.ChildStart to Auto or File in the configuration file*-ExecutionPolicy Bypass for that process only*' + $global:PraGate.L330SModes.Clear() + $context = & $script:NewContext 'Auto' + { Invoke-PraExoSubprocess -Context $context -Operation 'Probe' -Params @{} -Permit $null -OnApplied $null -OnProgress $null 6>$null } | Should -Throw '*even in a child process started from a script file with -ExecutionPolicy Bypass*Error: System.Management.Automation.PSSecurityException*' + ($global:PraGate.L330SModes -join ',') | Should -BeExactly 'File' + $context.NextSteps[0] | Should -BeLike 'Look at Get-ExecutionPolicy -List*' + $global:PraGate.Remove('L330SDetail') + } + It 'gives the file of the child a fresh random folder that has nothing to do with the markers of the temporary folder' { + . ([scriptblock]::Create($script:PolicyFunctions)) + $first = Get-PraExoChildFolderPath + $second = Get-PraExoChildFolderPath + $first | Should -Match '\\praexo_[0-9a-f]{32}$' + $first | Should -Not -BeExactly $second + Split-Path $first -Parent | Should -BeExactly ([IO.Path]::GetTempPath().TrimEnd('\')) + } + It 'creates the folder of the script file new, in the place that the path function gives, and deletes it at the end' { + . ([scriptblock]::Create($script:PolicyFunctions)) + $id = [guid]::NewGuid().ToString('N') + $global:PraGate.L330SFolder = Join-Path ([IO.Path]::GetTempPath()) ('praexo_' + [guid]::NewGuid().ToString('N')) + Mock Get-PraExoChildFolderPath { $global:PraGate.L330SFolder } + try { + $run = Invoke-PraExoChild -Mode File -Child "[Console]::Out.WriteLine((Split-Path -Parent `$PSCommandPath)); exit 0" -Id $id -TimeoutMilliseconds 120000 -ProgressPath '' + $run.Out | Should -BeExactly $global:PraGate.L330SFolder + Test-Path -LiteralPath $global:PraGate.L330SFolder | Should -BeFalse -Because 'the folder is deleted at the end' + $global:PraGate.L330SFolder | Should -Not -BeLike ('*' + $id + '*') + } + finally { $global:PraGate.Remove('L330SFolder') } + } + It 'runs the real child: from the script file under AllSigned with the module imported by the path that was checked, and refused under AllSigned from its standard input (real processes, a stand-in of the module)' { + . ([scriptblock]::Create($script:PolicyFunctions)) + $script:PraExoWorker = { param($Operation, $Params, $Permit, $Binding, $OnApplied, $OnProgress) [pscustomobject]@{ Connected = $true; Probe = 'ok'; Binding = $null } } + $fakeManifest = Join-Path $script:FakeModules 'ExchangeOnlineManagement\ExchangeOnlineManagement.psd1' + $global:PraGate.L330SVerified = [pscustomobject]@{ ManifestPath = $fakeManifest; Version = '99.0.0'; MinimumVersion = '3.10.1' } + Mock Get-PraExecutionPolicyState { $global:PraGate.L330SPolicy } + Mock Get-PraExoVerifiedModule { $global:PraGate.L330SVerified } + $before = @($env:PSExecutionPolicyPreference, $env:PSModulePath) + try { + $env:PSExecutionPolicyPreference = 'AllSigned' + $env:PSModulePath = $script:FakeModules + ';' + (Join-Path $PSHOME 'Modules') + & $script:SetPolicy 'AllSigned' 'CurrentUser' + $context = & $script:NewContext 'Auto' + (Invoke-PraExoSubprocess -Context $context -Operation 'Probe' -Params @{} -Permit $null -OnApplied $null -OnProgress $null 6>$null).Probe | Should -BeExactly 'ok' + $context.Warnings | Should -Be 1 + $log = [IO.File]::ReadAllText($context.LogFile) + $log | Should -Match '\[WARN +\] The execution policy is AllSigned \(scope CurrentUser\)' + $log | Should -Match '(?m)\[DETAIL\] Exchange Online child process started from a temporary script file in a private folder\.\r?$' + $global:PraGate.L330SVerified = [pscustomobject]@{ ManifestPath = $fakeManifest; Version = '99.0.0'; MinimumVersion = '100.0.0' } + $context = & $script:NewContext 'Auto' + { Invoke-PraExoSubprocess -Context $context -Operation 'Probe' -Params @{} -Permit $null -OnApplied $null -OnProgress $null 6>$null } | Should -Throw '*child process code=1*' -Because 'the child imports the module with the minimum version: a module that is older than it is refused' + $global:PraGate.L330SVerified = [pscustomobject]@{ ManifestPath = $fakeManifest; Version = '99.0.0'; MinimumVersion = '3.10.1' } + $context = & $script:NewContext 'Stdin' + $box = @{ Message = '' } + try { Invoke-PraExoSubprocess -Context $context -Operation 'Probe' -Params @{} -Permit $null -OnApplied $null -OnProgress $null 6>$null } catch { $box.Message = $_.Exception.Message } + $box.Message | Should -BeLike '*Exo.ChildStart = Stdin cannot work under the execution policy AllSigned*Error: System.Management.Automation.PSSecurityException, UnauthorizedAccess,*' -Because 'the child started from its standard input obeys AllSigned and refuses the stand-in, which is not signed' + } + finally { $env:PSExecutionPolicyPreference = $before[0]; $env:PSModulePath = $before[1]; $global:PraGate.Remove('L330SVerified') } + } + It 'writes the marker of the refusal only when the refusal comes before the sign-in (real child, a stand-in of the module)' { + . ([scriptblock]::Create($script:PolicyFunctions)) + Mock Get-PraExecutionPolicyState { $global:PraGate.L330SPolicy } + $fakeManifest = Join-Path $script:FakeModules 'ExchangeOnlineManagement\ExchangeOnlineManagement.psd1' + $global:PraGate.L330SVerified = [pscustomobject]@{ ManifestPath = $fakeManifest; Version = '99.0.0'; MinimumVersion = '3.10.1' } + Mock Get-PraExoVerifiedModule { $global:PraGate.L330SVerified } + & $script:SetPolicy 'AllSigned' 'CurrentUser' + $before = @($env:PSModulePath, $env:PRA_FAKE_EXO_CONNECT) + try { + $env:PSModulePath = $script:FakeModules + ';' + (Join-Path $PSHOME 'Modules') + # After the sign-in: the worker raises a security exception. The child connected, so the marker is not written and the error is told as it is. + $script:PraExoWorker = { param($Operation, $Params, $Permit, $Binding, $OnApplied, $OnProgress) if ($Operation -ceq 'Probe' -and $null -eq $Binding) { return [pscustomobject]@{ Connected = $true; Binding = @{ Marker = 'bound' } } }; throw [System.Management.Automation.PSSecurityException]::new('SYNTHETIC refusal after the sign-in') } + $context = & $script:NewContext 'File' + { Invoke-PraExoSubprocess -Context $context -Operation 'Probe' -Params @{} -Permit $null -OnApplied $null -OnProgress $null 6>$null } | Should -Throw '*child process code=1*SYNTHETIC refusal after the sign-in*' + $context.ContainsKey('NextSteps') | Should -BeFalse + # Before the sign-in: Connect-ExchangeOnline raises it. The marker is written, with the original error, and the text is the one of the policy. + $env:PRA_FAKE_EXO_CONNECT = 'refuse' + $script:PraExoWorker = { param($Operation, $Params, $Permit, $Binding, $OnApplied, $OnProgress) [pscustomobject]@{ Connected = $true; Probe = 'ok'; Binding = $null } } + $context = & $script:NewContext 'File' + $box = @{ Message = '' } + try { Invoke-PraExoSubprocess -Context $context -Operation 'Probe' -Params @{} -Permit $null -OnApplied $null -OnProgress $null 6>$null } catch { $box.Message = $_.Exception.Message } + $box.Message | Should -BeLike '*The execution policy (AllSigned) refused a PowerShell file of the Exchange Online module even in a child process started from a script file*Error: System.Management.Automation.PSSecurityException, *' + $context.NextSteps.Count | Should -Be 2 + } + finally { $env:PSModulePath = $before[0]; if ($null -eq $before[1]) { Remove-Item Env:\PRA_FAKE_EXO_CONNECT -ErrorAction SilentlyContinue } else { $env:PRA_FAKE_EXO_CONNECT = $before[1] } } + } + It 'in process, a connection that the policy refuses stops with the error that says what to set, with the original error, and the Next steps (, )' -ForEach @( + @{ Case = 'the security exception'; Culture = 'en-US'; Effective = 'AllSigned'; Source = 'CurrentUser'; Throw = { throw [System.Management.Automation.PSSecurityException]::new('SYNTHETIC refusal') }; Like = '*cannot be reached in process under the execution policy AllSigned*Error: System.Management.Automation.PSSecurityException, *'; Step = 'Set Exo.UseSubprocess = $true in the configuration file*' } + @{ Case = 'the security exception'; Culture = 'fr-FR'; Effective = 'AllSigned'; Source = 'CurrentUser'; Throw = { throw [System.Management.Automation.PSSecurityException]::new('SYNTHETIC refus') }; Like = '*cannot be reached in process under the execution policy AllSigned*'; Step = 'Set Exo.UseSubprocess = $true in the configuration file*' } + @{ Case = 'a Group Policy'; Culture = 'en-US'; Effective = 'AllSigned'; Source = 'MachinePolicy'; Throw = { throw [System.Management.Automation.PSSecurityException]::new('SYNTHETIC refusal') }; Like = '*is set by Group Policy (MachinePolicy)*'; Step = 'Ask the administrator of that Group Policy*' } + @{ Case = 'another policy, a security exception'; Culture = 'en-US'; Effective = 'RemoteSigned'; Source = 'LocalMachine'; Throw = { throw [System.Management.Automation.PSSecurityException]::new('SYNTHETIC refusal') }; Like = '*cannot be reached in process under the execution policy RemoteSigned*'; Step = 'Set Exo.UseSubprocess = $true in the configuration file*' } + ) { + . ([scriptblock]::Create($script:PolicyFunctions)) + . ([scriptblock]::Create((@('Get-PraCloudSession', 'Connect-PraCloudSession') | ForEach-Object { + $name = $_ + $cloudAst = [Management.Automation.Language.Parser]::ParseFile((Join-Path $global:PraGate.Package 'module\PRA.Cloud.psm1'), [ref]$null, [ref]$null) + $cloudAst.Find({ param($n) $n -is [Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -ceq $name }, $true).Extent.Text + }) -join "`n")) + & $script:SetPolicy $Effective $Source + Mock Get-PraExecutionPolicyState { $global:PraGate.L330SPolicy } + Mock Get-PraCloudModuleReport { [pscustomobject]@{ Exo = [pscustomobject]@{ Ok = $true; Message = '' }; Graph = [pscustomobject]@{ Ok = $true; Message = ''; Version = '2.41.1' } } } + function Import-Module { [CmdletBinding()] param([Parameter(Position = 0)]$Name, $MinimumVersion, $RequiredVersion) } + function Get-ConnectionInformation { [CmdletBinding()] param() @() } + function Disconnect-ExchangeOnline { [CmdletBinding()] param($ConnectionId, [switch]$Confirm) } + $attempt = $Throw + function Connect-ExchangeOnline { [CmdletBinding()] param($AppId, $CertificateThumbprint, $Organization, [switch]$ShowBanner) & $attempt } + $context = @{ Config = @{ Cloud = @{ TenantId = '20000000-0000-0000-0000-000000000002'; AppId = 'app'; CertificateThumbprint = 'AB'; Organization = 'contoso.onmicrosoft.com' }; Exo = @{ MinModuleVersion = '3.10.1'; UseSubprocess = $false; DisableWAM = $false } }; Issues = (New-Object 'Collections.Generic.List[object]'); Warnings = 0; LogFile = ''; CurrentOperation = '' } + $box = @{ Message = '' } + & $script:InCulture $Culture { try { Connect-PraCloudSession -Context $context -NeedGraph $false -NeedExo $true 6>$null } catch { $box.Message = $_.Exception.Message } } + $box.Message | Should -BeLike $Like + $context.NextOnFailure | Should -BeTrue + $context.NextSteps[0] | Should -BeLike $Step + $context.CurrentOperation | Should -BeExactly 'Connect-ExchangeOnline' + } + It 'in process, an error that is not a refusal by the policy is raised as it is: another error, and a format file refused under a policy that is not AllSigned ()' -ForEach @( + @{ Case = 'another error'; Effective = 'AllSigned'; Throw = { throw 'SYNTHETIC: AADSTS700027 the certificate is not valid' }; Message = '*AADSTS700027*' } + @{ Case = 'a format file under RemoteSigned'; Effective = 'RemoteSigned'; Throw = { $record = [System.Management.Automation.ErrorRecord]::new([Exception]::new('SYNTHETIC format file refused'), 'FormatXmlUpdateException,Microsoft.PowerShell.Commands.ImportModuleCommand', [System.Management.Automation.ErrorCategory]::InvalidOperation, $null); throw $record }; Message = '*SYNTHETIC format file refused*' } + ) { + . ([scriptblock]::Create($script:PolicyFunctions)) + . ([scriptblock]::Create((@('Get-PraCloudSession', 'Connect-PraCloudSession') | ForEach-Object { + $name = $_ + $cloudAst = [Management.Automation.Language.Parser]::ParseFile((Join-Path $global:PraGate.Package 'module\PRA.Cloud.psm1'), [ref]$null, [ref]$null) + $cloudAst.Find({ param($n) $n -is [Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -ceq $name }, $true).Extent.Text + }) -join "`n")) + & $script:SetPolicy $Effective 'CurrentUser' + Mock Get-PraExecutionPolicyState { $global:PraGate.L330SPolicy } + Mock Get-PraCloudModuleReport { [pscustomobject]@{ Exo = [pscustomobject]@{ Ok = $true; Message = '' }; Graph = [pscustomobject]@{ Ok = $true; Message = ''; Version = '2.41.1' } } } + function Import-Module { [CmdletBinding()] param([Parameter(Position = 0)]$Name, $MinimumVersion, $RequiredVersion) } + function Get-ConnectionInformation { [CmdletBinding()] param() @() } + function Disconnect-ExchangeOnline { [CmdletBinding()] param($ConnectionId, [switch]$Confirm) } + $attempt = $Throw + function Connect-ExchangeOnline { [CmdletBinding()] param($AppId, $CertificateThumbprint, $Organization, [switch]$ShowBanner) & $attempt } + $context = @{ Config = @{ Cloud = @{ TenantId = '20000000-0000-0000-0000-000000000002'; AppId = 'app'; CertificateThumbprint = 'AB'; Organization = 'contoso.onmicrosoft.com' }; Exo = @{ MinModuleVersion = '3.10.1'; UseSubprocess = $false; DisableWAM = $false } }; Issues = (New-Object 'Collections.Generic.List[object]'); Warnings = 0; LogFile = ''; CurrentOperation = '' } + { Connect-PraCloudSession -Context $context -NeedGraph $false -NeedExo $true 6>$null } | Should -Throw $Message + $context.ContainsKey('NextSteps') | Should -BeFalse + } + It 'builds a child script that parses, carries the security test and the error detail, and writes the marker of the refusal only before the connection marker exists' { + . ([scriptblock]::Create($script:PolicyFunctions)) + $script:PraExoWorker = { 'worker' } + Mock Get-PraExecutionPolicyState { $global:PraGate.L330SPolicy } + Mock Invoke-PraExoChild { + $global:PraGate.L330SChild = $Child + $global:PraGate.L330SId = $Id + [pscustomobject]@{ Out = ('{"Protocol":1,"Id":"' + $Id + '","Ok":true,"Data":{"Probe":"ok"},"Error":""}'); Err = ''; ExitCode = 0; TimedOut = $false } + } + $context = & $script:NewContext 'Auto' + $null = Invoke-PraExoSubprocess -Context $context -Operation 'Probe' -Params @{} -Permit $null -OnApplied $null -OnProgress $null 6>$null + $errors = $null + [void][Management.Automation.Language.Parser]::ParseInput([string]$global:PraGate.L330SChild, [ref]$null, [ref]$errors) + $errors.Count | Should -Be 0 + $global:PraGate.L330SChild | Should -Match 'function Test-PraExoSecurityError \{' + $global:PraGate.L330SChild | Should -Match 'function Get-PraExoErrorDetail \{' + $global:PraGate.L330SChild | Should -Not -Match '__POLICY__|__SECURITYTEST__|__ERRORDETAIL__|__CONNECTED__|__STARTED__|__REQUEST__|__WORKER__' + $temp = [IO.Path]::GetTempPath() + $policy = (Join-Path $temp ('praexo_' + $global:PraGate.L330SId + '.policy')).Replace("'", "''") + $connected = (Join-Path $temp ('praexo_' + $global:PraGate.L330SId + '.connected')).Replace("'", "''") + $global:PraGate.L330SChild.Contains("-and -not [IO.File]::Exists('" + $connected + "')) { [IO.File]::WriteAllText('" + $policy + "',(Get-PraExoErrorDetail `$_)) }") | Should -BeTrue + $request = Get-L330SRequest $global:PraGate.L330SChild + $request.ExoManifest | Should -BeExactly '' + $global:PraGate.Remove('L330SId') + } +} + +Describe 'Release 3.3.0 - the warning about the certificate chain that the integrity check prints before the log opens is also in the log, the summary and the report of the run, for that run only and not printed a second time (real main)' -Tag 'Release330G' { + It 'writes it once to the log and counts it in the warnings when the integrity check printed it, prints nothing more on the console, and forgets it when the run ends ()' -ForEach @(@{ Culture = '' }, @{ Culture = 'fr-FR' }) { + $runtime = New-GateRuntime -Name ('chain-' + $(if ($Culture) { 'fr' } else { 'en' })) + $arguments = @{ Action = 'Convert'; Mode = 'Preview'; Phase = 'AD'; Force = $true; ConfigPath = $runtime.ConfigPath } + $run = Invoke-GateProcess $runtime $arguments -ChainOnlyWarned -Culture $Culture + $run.ExitCode | Should -Be 0 -Because ([string]$run.Output + [string]$run.Error) + $log = [IO.File]::ReadAllText($run.MainResult.LogFile) + ([regex]::Matches($log, '\[WARN +\] Package integrity: the certificate chain of the publisher cannot be built on this computer')).Count | Should -Be 1 + $run.MainResult.WarningCount | Should -BeGreaterOrEqual 1 + $run.MainResult.Warnings.Message -join ' ' | Should -Match 'Package integrity: the certificate chain of the publisher cannot be built' + [string]$run.Output | Should -Not -Match '(?m)^\s{4,8}\S\s+Package integrity: the certificate chain' -Because 'the integrity check printed it once, before the log; the run adds no item line of its own to the console (the summary of the warnings lists it)' + [string]$run.Output | Should -Match '(?m)Warning\s+Package integrity: the certificate chain' -Because 'the summary of the run lists it among the warnings' + [IO.File]::ReadAllText((Join-Path $runtime.Root 'chain-flag.txt')) | Should -BeExactly 'True' -Because 'the flag of this run is cleared when the run ends, so that the next run in the same console is checked and warned again' + } + It 'writes nothing about it when the integrity check did not print it' { + $runtime = New-GateRuntime -Name 'chain-none' + $run = Invoke-GateProcess $runtime @{ Action = 'Convert'; Mode = 'Preview'; Phase = 'AD'; Force = $true; ConfigPath = $runtime.ConfigPath } + $run.ExitCode | Should -Be 0 -Because ([string]$run.Output + [string]$run.Error) + [IO.File]::ReadAllText($run.MainResult.LogFile) | Should -Not -Match 'Package integrity: the certificate chain' + } + It 'Write-PraLog -NoConsole writes the line to the log and counts the warning without printing it, and prints it without the switch' { + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global + $log = Join-Path $global:PraGate.Root ('nocon-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.log') + $context = @{ Warnings = 0; LogFile = $log; Issues = (New-Object 'Collections.Generic.List[object]'); StepIndex = 0; StepTotal = 1; CurrentPhase = 'Test' } + $quiet = @(Write-PraLog -Context $context -Level Warning -NoConsole -Message 'quiet warning' 6>&1 5>&1 4>&1 3>&1) + $quiet.Count | Should -Be 0 + $context.Warnings | Should -Be 1 + @($context.WarningList | ForEach-Object Message) | Should -Contain 'quiet warning' + $loud = @(Write-PraLog -Context $context -Level Warning -Message 'loud warning' 6>&1 5>&1 4>&1 3>&1) + ($loud | Out-String) | Should -Match 'loud warning' + $context.Warnings | Should -Be 2 + $text = [IO.File]::ReadAllText($log) + $text | Should -Match '\[WARN +\] quiet warning' + $text | Should -Match '\[WARN +\] loud warning' + } +} + +Describe 'Release 3.3.0 - the configuration file keeps its UTF-8 byte order mark' -Tag 'Release330G' { + It 'starts with the byte order mark, like the other text files of the package' { + $bytes = [IO.File]::ReadAllBytes((Join-Path $global:PraGate.Package 'config\PraRemoteMailbox.config.psd1')) + ($bytes[0..2] -join ',') | Should -BeExactly '239,187,191' + } +} \ No newline at end of file diff --git a/tests/PraReport.Tests.ps1 b/tests/PraReport.Tests.ps1 index 582b2e7..8516cf7 100644 --- a/tests/PraReport.Tests.ps1 +++ b/tests/PraReport.Tests.ps1 @@ -1,6 +1,6 @@ <# .SYNOPSIS - High-volume HTML report tests for PRA Remote Mailbox 3.2.0 (offline; synthetic data only: no AD, Exchange, Graph or network). + High-volume HTML report tests for PRA Remote Mailbox 3.3.0 (offline; synthetic data only: no AD, Exchange, Graph or network). .DESCRIPTION Report-only evidence: the real Write-PraReport / Write-PraReportHtml of a fixture copy of the package write the reports of synthetic runs (up to 100,000 rows), and the compressed data is decoded exactly like the page does and @@ -9,9 +9,9 @@ measured generation times (they are measurements, not gates). .NOTES Author : Nicolas Fabert - Version : 3.2.0 + Version : 3.3.0 #> -#Requires -Version 7.5 +#Requires -Version 7.6 BeforeAll { . (Join-Path $PSScriptRoot 'IntegrityFixture.ps1') @@ -192,3 +192,101 @@ Describe 'High-volume reports (report-only, synthetic)' { if ($script:Evidence) { ($script:Measurements | ConvertTo-Json -Depth 5) | Set-Content -LiteralPath (Join-Path $script:Evidence 'generation-measurements.json') -Encoding UTF8 } } } + +Describe 'Release 3.3.0 - the report header lists what the run used and the Deny entries, the footer lists the versions and paths, and a run without them is unchanged' -Tag 'Release330B' { + BeforeAll { + $script:HtmlOf = { + param($Context) + $outcome = & (Get-Module PRA.Common) { param($c) Get-PraOutcome $c } $Context + & (Get-Module PRA.Common) { param($c, $o) Get-PraReportHtml -Context $c -Outcome $o } $Context $outcome + } + } + It 'writes the settings with their sources, the Deny entries and the runtime lines, all encoded' { + $context = New-PraSyntheticContext -PackageRoot $script:Package -Rows 3 + $context.RuntimeLines = @('PowerShell 7.6.9 (C:\Synthetic\PowerShell\7)', 'ExchangeOnlineManagement 3.10.1 (C:\Synthetic x & Co)') + $context.RunSettings = @('Mailbox scope: OU=Wave1 (command line)', 'Backup folder: D:\PRA\Backups (configuration file)') + $context.DenyReport = @('shared1: SendAs to S-1-5-21-1-2-3-3999 (granted anyway: SendAs a@contoso.invalid)') + $text = & $script:HtmlOf $context + $text | Should -Match 'every detail\.
    PowerShell 7\.6\.9 \(C:\\Synthetic\\PowerShell\\7\)
    ExchangeOnlineManagement 3\.10\.1 \(C:\\Synthetic <b>x</b> & Co\)' + $text | Should -Match 'Settings usedMailbox scope: OU=Wave1 \(command line\); Backup folder: D:\\PRA\\Backups \(configuration file\)' + $text | Should -Match 'Deny entriesshared1: SendAs to S-1-5-21-1-2-3-3999 \(granted anyway: SendAs a@contoso\.invalid\)' + $text | Should -Not -Match 'x' + } + It 'leaves the report of an older run as it was: no row for a missing list and nothing after the footer text' { + $context = New-PraSyntheticContext -PackageRoot $script:Package -Rows 3 + $text = & $script:HtmlOf $context + $text | Should -Not -Match 'Settings used' + $text | Should -Not -Match 'Deny entries' + $text | Should -Match 'hold every detail\.' + $text | Should -Not -Match '\{\{[A-Z_]+\}\}' + } +} + +BeforeDiscovery { + $script:CspBrowserAvailable = [bool](@("${env:ProgramFiles(x86)}\Microsoft\Edge\Application\msedge.exe", "$env:ProgramFiles\Microsoft\Edge\Application\msedge.exe", "$env:ProgramFiles\Google\Chrome\Application\chrome.exe") | + Where-Object { $_ -and (Test-Path -LiteralPath $_ -PathType Leaf) } | Select-Object -First 1) +} + +Describe 'Release 3.3.0 - both report templates carry a Content-Security-Policy that names their own inline scripts and style by hash, and the reports still render from a file (repository templates, reports written by the real writer)' -Tag 'Release330D' { + BeforeAll { + $script:CspHash = { param([string]$Text) 'sha256-' + [Convert]::ToBase64String([Security.Cryptography.SHA256]::HashData([Text.Encoding]::UTF8.GetBytes($Text.Replace("`r`n", "`n")))) } + $script:CspDom = { + param([string]$Path) + $browser = @("${env:ProgramFiles(x86)}\Microsoft\Edge\Application\msedge.exe", "$env:ProgramFiles\Microsoft\Edge\Application\msedge.exe", "$env:ProgramFiles\Google\Chrome\Application\chrome.exe") | Where-Object { $_ -and (Test-Path -LiteralPath $_ -PathType Leaf) } | Select-Object -First 1 + $profileFolder = Join-Path ([IO.Path]::GetTempPath()) ('pra-csp-' + [guid]::NewGuid().ToString('N').Substring(0, 8)) + try { + $start = [Diagnostics.ProcessStartInfo]::new($browser) + foreach ($argument in @('--headless=new', '--disable-gpu', '--no-first-run', "--user-data-dir=$profileFolder", '--virtual-time-budget=60000', '--dump-dom', ([Uri]$Path).AbsoluteUri)) { $start.ArgumentList.Add($argument) } + $start.RedirectStandardOutput = $true; $start.RedirectStandardError = $true; $start.UseShellExecute = $false + $process = [Diagnostics.Process]::Start($start) + $output = $process.StandardOutput.ReadToEndAsync(); $null = $process.StandardError.ReadToEndAsync() + if (-not $process.WaitForExit(240000)) { $process.Kill($true) } + return $output.Result + } + finally { Remove-Item -LiteralPath $profileFolder -Recurse -Force -ErrorAction SilentlyContinue } + } + } + It 'puts one policy meta before every script of : nothing is allowed but the inline scripts and the style named by their SHA-256, and no network, frame, form or base address' -ForEach @(@{ Name = 'Report' }, @{ Name = 'GlobalReport' }) { + $text = [IO.File]::ReadAllText((Join-Path $script:Repo ('package\templates\' + $Name + '.template.html'))) + $metas = [regex]::Matches($text, '') + $metas.Count | Should -Be 1 + $metas[0].Index | Should -BeLessThan $text.IndexOf('(.*?)')) + $styles = @([regex]::Matches($text, '(?s)')) + @([regex]::Matches($directives['script-src'], "'sha256-[A-Za-z0-9+/=]+'")).Count | Should -Be $scripts.Count + @([regex]::Matches($directives['style-src'], "'sha256-[A-Za-z0-9+/=]+'")).Count | Should -Be $styles.Count + foreach ($script in $scripts) { $directives['script-src'] | Should -BeLike ("*'" + (& $script:CspHash $script.Groups[1].Value) + "'*") } + foreach ($style in $styles) { $directives['style-src'] | Should -BeLike ("*'" + (& $script:CspHash $style.Groups[1].Value) + "'*") } + $text | Should -Not -Match '(?i)<[a-z][^>]*\s(on[a-z]+|style)\s*=' + $text | Should -Not -Match '(?i)]*src\s*=' + $text | Should -Not -Match '(?]*\s(on[a-z]+|style)\s*=' + $html | Should -Not -Match '\{\{[A-Z_]+\}\}' + } + It 'renders the report from a file in the browser under its policy and does not run a script that the policy does not name' -Skip:(-not $script:CspBrowserAvailable) { + $result = Invoke-PraSyntheticReport -PackageRoot $script:Package -Directory (Join-Path $script:Work 'csp-browser') -Rows 30 -Issues 3 -Warnings 2 -Name 'browser' + $dom = & $script:CspDom $result.Reports.Html + $dom | Should -Match 'data-state="ready"' + $dom | Should -Not -Match 'data-injected' + $text = [IO.File]::ReadAllText($result.Reports.Html) + $injected = Join-Path $script:Work 'csp-browser\injected.html' + [IO.File]::WriteAllText($injected, $text.Replace('', ''), (New-Object Text.UTF8Encoding($true))) + $blocked = & $script:CspDom $injected + $blocked | Should -Match 'data-state="ready"' -Because 'the page itself still runs' + $blocked | Should -Not -Match 'data-injected="yes"' -Because 'a script that the policy does not name is not run' + $noPolicy = Join-Path $script:Work 'csp-browser\no-policy.html' + [IO.File]::WriteAllText($noPolicy, ($text -replace '', '').Replace('', ''), (New-Object Text.UTF8Encoding($true))) + (& $script:CspDom $noPolicy) | Should -Match 'data-injected="yes"' -Because 'without the policy the same script runs: the test proves the policy is what blocks it' + } +} diff --git a/tests/PraRepository.Tests.ps1 b/tests/PraRepository.Tests.ps1 new file mode 100644 index 0000000..2f8301a --- /dev/null +++ b/tests/PraRepository.Tests.ps1 @@ -0,0 +1,799 @@ +<# +.SYNOPSIS + Repository tests for PRA Remote Mailbox 3.3.0 (offline: the workflows, the CI scripts, the pins and the tools of the repository; no AD, Exchange, Graph or network). +.DESCRIPTION + Keeps the repository machinery honest: + - every `uses:` of every workflow is a full commit with an exact tag in its comment; + - the CI PowerShell, Pester and PSScriptAnalyzer are pinned with their hashes, and a package that does not match its hash stops the step; + - the CI runs on PowerShell 7.6, the only supported line, and every runtime file requires it; + - the monthly dependency watch only reads and only reports; + - the tools that write the bill of materials and compare a ZIP with the committed source behave as they say. +.NOTES + Author : Nicolas Fabert + Version : 3.3.0 +#> +#Requires -Version 7.6 + +BeforeAll { + . (Join-Path $PSScriptRoot 'IntegrityFixture.ps1') + $script:Repo = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..')) + $script:Workflows = Join-Path $script:Repo '.github\workflows' + $script:Scripts = Join-Path $script:Repo '.github\scripts' + $script:Work = Join-Path ([IO.Path]::GetTempPath()) ('PR-' + [guid]::NewGuid().ToString('N').Substring(0, 8)) + $null = New-Item -ItemType Directory -Path $script:Work -Force + $script:Counter = 0 + $script:Utf8 = New-Object Text.UTF8Encoding($false) + function script:Read-RepoText([string]$Relative) { [IO.File]::ReadAllText((Join-Path $script:Repo $Relative)) -replace "`r`n", "`n" } + function script:New-Folder([string]$Name = 'w') { $script:Counter++; $path = Join-Path $script:Work ('{0}{1}' -f $Name, $script:Counter); $null = New-Item -ItemType Directory -Path $path -Force; $path } + function script:Get-PinData { Get-Content -LiteralPath (Join-Path $script:Repo '.github\ci-pins.json') -Raw -Encoding UTF8 | ConvertFrom-Json } + # Runs a script in a child PowerShell 7 and returns its exit code and its output. + function script:Invoke-ChildScript { + param([Parameter(Mandatory)][string]$Script, [string[]]$Argument = @(), [hashtable]$Environment = @{}, [string]$WorkingDirectory = $script:Work) + $info = New-Object Diagnostics.ProcessStartInfo (Join-Path $PSHOME 'pwsh.exe') + foreach ($item in @('-NoLogo', '-NoProfile', '-NonInteractive', '-File', $Script) + $Argument) { $info.ArgumentList.Add($item) } + $info.RedirectStandardOutput = $true; $info.RedirectStandardError = $true; $info.UseShellExecute = $false; $info.CreateNoWindow = $true + $info.WorkingDirectory = $WorkingDirectory + foreach ($key in $Environment.Keys) { $info.Environment[$key] = [string]$Environment[$key] } + $process = [Diagnostics.Process]::Start($info) + try { + $errorText = $process.StandardError.ReadToEndAsync() + $output = $process.StandardOutput.ReadToEnd() + $process.WaitForExit() + [pscustomobject]@{ ExitCode = $process.ExitCode; Output = ($output + $errorText.GetAwaiter().GetResult()) } + } + finally { $process.Dispose() } + } + function script:Get-Sha256Hex([string]$Path) { (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash } + function script:Get-Sha512Base64([string]$Path) { $algorithm = [Security.Cryptography.SHA512]::Create(); try { [Convert]::ToBase64String($algorithm.ComputeHash([IO.File]::ReadAllBytes($Path))) } finally { $algorithm.Dispose() } } + # The functions of the dependency watch, without running it. + . (Join-Path $script:Scripts 'Invoke-DependencyWatch.ps1') -LoadOnly +} + +AfterAll { Remove-Item -LiteralPath $script:Work -Recurse -Force -ErrorAction SilentlyContinue } + +Describe 'Release 3.3.0 - every action of every workflow is a full commit with its exact tag (repository files)' -Tag 'Release330a' { + It 'every uses: is owner/name@ and a full commit of 40 hexadecimal characters followed by # vX.Y.Z, in every workflow' { + $pins = @(Get-WatchWorkflowPin $script:Repo) + $pins.Count | Should -BeGreaterThan 4 + @($pins | Where-Object { -not $_.Valid } | ForEach-Object { '{0}:{1} {2}' -f $_.File, $_.Line, $_.Name }) | Should -BeNullOrEmpty + foreach ($pin in $pins) { + $pin.Sha | Should -Match '\A[0-9a-f]{40}\z' + $pin.Tag | Should -Match '\Av\d+\.\d+\.\d+\z' + } + } + It 'reads the same text the workflows hold: no uses: line is missed by the reader' { + $textual = 0 + foreach ($file in Get-ChildItem -LiteralPath $script:Workflows -File -Filter '*.yml') { + $textual += @([IO.File]::ReadAllLines($file.FullName) | Where-Object { $_ -match '^\s*(-\s+)?uses:\s' }).Count + } + @(Get-WatchWorkflowPin $script:Repo).Count | Should -Be $textual + } + It 'one commit has one tag and one tag has one commit, in all the workflows' { + $pins = @(Get-WatchWorkflowPin $script:Repo | Group-Object { '{0}@{1}' -f $_.Repository, $_.Tag }) + foreach ($group in $pins) { @($group.Group.Sha | Sort-Object -Unique).Count | Should -Be 1 -Because $group.Name } + foreach ($group in @(Get-WatchWorkflowPin $script:Repo | Group-Object Sha)) { @($group.Group | ForEach-Object { '{0}@{1}' -f $_.Repository, $_.Tag } | Sort-Object -Unique).Count | Should -Be 1 -Because $group.Name } + } + It 'refuses a floating tag, a short commit, a missing or a partial tag comment, and a pin of an action without a version' { + $folder = New-Folder 'wf' + $workflows = Join-Path $folder '.github\workflows' + $null = New-Item -ItemType Directory -Path $workflows -Force + $sha = 'a' * 40 + $lines = @( + " - uses: actions/checkout@v4" + " - uses: actions/checkout@$($sha.Substring(0, 12)) # v4.1.0" + " - uses: actions/checkout@$sha" + " - uses: actions/checkout@$sha # v4" + " - uses: actions/checkout@$sha # 4.1.0" + " - uses: actions/checkout@$($sha.ToUpperInvariant()) # v4.1.0" + " - uses: actions/checkout@$sha # v4.1.0" + " - uses: github/codeql-action/init@$sha # v4.38.3" + " - uses: ./.github/actions/local" + ) + [IO.File]::WriteAllLines((Join-Path $workflows 'x.yml'), $lines) + $pins = @(Get-WatchWorkflowPin $folder) + $pins.Count | Should -Be 8 + @($pins | Where-Object Valid).Count | Should -Be 2 + ($pins | Where-Object { $_.Name -eq 'github/codeql-action/init' }).Repository | Should -BeExactly 'github/codeql-action' + } + It 'documents the Node 24 majors: checkout v7 and upload-artifact v7 are the pins, the older majors are gone' { + $text = (Get-ChildItem -LiteralPath $script:Workflows -File -Filter '*.yml' | ForEach-Object { [IO.File]::ReadAllText($_.FullName) }) -join "`n" + $text | Should -Not -Match 'actions/checkout@11d5960a326750d5838078e36cf38b85af677262' + $text | Should -Not -Match 'actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02' + $text | Should -Match 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7\.0\.1' + $text | Should -Match 'actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7\.0\.2' + } +} + +Describe 'Release 3.3.0 - the CI runs on PowerShell 7.6, the only supported line (repository files)' -Tag 'Release330a' { + It 'pins the PowerShell release with a version and a SHA-256 together, from the official release page' { + $pins = @((Get-PinData).powerShell) + $pins.Count | Should -Be 1 + $primary = @($pins | Where-Object role -eq 'primary') + $primary.Count | Should -Be 1 + $primary[0].line | Should -BeExactly '7.6' + foreach ($pin in @($primary[0])) { + $pin.version | Should -Match '\A\d+\.\d+\.\d+\z' + $pin.version.StartsWith($pin.line + '.', [StringComparison]::Ordinal) | Should -BeTrue + $pin.sha256 | Should -Match '\A[0-9A-F]{64}\z' + $pin.source | Should -BeExactly ('https://github.com/PowerShell/PowerShell/releases/tag/v' + $pin.version) + $pin.hashSource | Should -BeExactly ('https://github.com/PowerShell/PowerShell/releases/download/v' + $pin.version + '/hashes.sha256') + [datetime]::ParseExact($pin.supportEnds, 'yyyy-MM-dd', [Globalization.CultureInfo]::InvariantCulture) | Should -BeOfType [datetime] + } + } + It 'keeps the version and the hash only in the pin file: the install script holds neither' { + $text = Read-RepoText '.github\scripts\Install-PowerShell.ps1' + foreach ($pin in @((Get-PinData).powerShell)) { + $text | Should -Not -Match ([regex]::Escape($pin.version)) + $text | Should -Not -Match ([regex]::Escape($pin.sha256)) + } + } + It 'the only leg is Validate (PowerShell 7) on the 7.6 line and it fails the workflow' { + $ci = Read-RepoText '.github\workflows\ci.yml' + $ci | Should -Match "(?m)^ name: Validate \(\$\{\{ matrix\.engine \}\}\)$" + $ci | Should -Not -Match 'continue-on-error' + $ci | Should -Match 'include: \[\{"engine":"PowerShell 7","line":"7\.6","package":true\}\]' + $ci | Should -Not -Match '7\.5' + $ci | Should -Match "Install-PowerShell\.ps1 -Line '\$\{\{ matrix\.line \}\}'" + $ci | Should -Match 'name: ci-powershell-\$\{\{ matrix\.line \}\}' + @([regex]::Matches($ci, '"engine":')).Count | Should -Be 1 + } + It 'every runtime file, the manifest and the pin name the same PowerShell line' { + $line = [string]((Get-PinData).powerShell | Where-Object role -eq 'primary').line + (Import-PowerShellDataFile -LiteralPath (Join-Path $script:Repo 'package\PraRemoteMailbox.psd1')).PowerShellVersion | Should -BeExactly $line + foreach ($file in Get-ChildItem -LiteralPath (Join-Path $script:Repo 'package') -Recurse -File | Where-Object { $_.Extension -in '.ps1', '.psm1' }) { + [IO.File]::ReadAllText($file.FullName) | Should -Match ('(?m)^(\uFEFF)?#Requires -Version ' + [regex]::Escape($line) + '\r?$') -Because $file.Name + } + } + It 'the job timeout stays at 150 minutes: the last run took about 75 minutes for the whole job' { + (Read-RepoText '.github\workflows\ci.yml') | Should -Match '(?m)^ timeout-minutes: 150$' + } + It 'the CI scripts take the module versions from the pin file, and the gate asks for the same versions' { + $ci = Read-RepoText '.github\scripts\Invoke-CI.ps1' + $ci | Should -Not -Match 'RequiredVersion\s+\d' + $gate = Read-RepoText 'tests\Invoke-TestGate.ps1' + foreach ($module in @((Get-PinData).modules | Where-Object name -eq 'PSScriptAnalyzer')) { + $gate | Should -Match ('Import-Module PSScriptAnalyzer -RequiredVersion ' + [regex]::Escape($module.version) + ' ') + } + foreach ($module in @((Get-PinData).modules | Where-Object name -eq 'Pester')) { [version]$module.version | Should -BeGreaterOrEqual ([version]'5.0.0') } + } + It 'installs the pinned PowerShell only from an archive that matches its SHA-256, and extracts nothing otherwise' { + $folder = New-Folder 'ps' + $source = Join-Path $folder 'src'; $null = New-Item -ItemType Directory -Path $source + [IO.File]::WriteAllText((Join-Path $source 'pwsh.exe'), 'synthetic', $script:Utf8) + $zip = Join-Path $folder 'PowerShell-9.9.9-win-x64.zip' + [IO.Compression.ZipFile]::CreateFromDirectory($source, $zip) + $script = Join-Path $script:Scripts 'Install-PowerShell.ps1' + $temp = Join-Path $folder 'runner'; $null = New-Item -ItemType Directory -Path $temp + $pathFile = Join-Path $folder 'github-path.txt' + $environment = @{ RUNNER_TEMP = $temp; GITHUB_PATH = $pathFile } + $wrong = Invoke-ChildScript -Script $script -Argument @('-Version', '9.9.9', '-Sha256', ('0' * 64), '-ArchivePath', $zip) -Environment $environment + $wrong.ExitCode | Should -Not -Be 0 + $wrong.Output | Should -Match 'does not match the pinned SHA-256' + Test-Path -LiteralPath (Join-Path $temp 'pwsh-9.9.9') | Should -BeFalse + Test-Path -LiteralPath $pathFile | Should -BeFalse + $good = Invoke-ChildScript -Script $script -Argument @('-Version', '9.9.9', '-Sha256', (Get-Sha256Hex $zip).ToLowerInvariant(), '-ArchivePath', $zip) -Environment $environment + $good.ExitCode | Should -Be 0 -Because $good.Output + Test-Path -LiteralPath (Join-Path $temp 'pwsh-9.9.9\pwsh.exe') | Should -BeTrue + [IO.File]::ReadAllText($pathFile) | Should -Match 'pwsh-9\.9\.9' + $bad = Invoke-ChildScript -Script $script -Argument @('-Version', '7.6', '-Sha256', ('0' * 64), '-ArchivePath', $zip) -Environment $environment + $bad.ExitCode | Should -Not -Be 0 + $bad.Output | Should -Match 'not a release version' + foreach ($alone in @(@('-Version', '9.9.9'), @('-Sha256', (Get-Sha256Hex $zip)))) { + $one = Invoke-ChildScript -Script $script -Argument ($alone + @('-ArchivePath', $zip)) -Environment $environment + $one.ExitCode | Should -Not -Be 0 + $one.Output | Should -Match 'Give both -Version and -Sha256, or neither' + } + } + It 'builds the bill of materials in the CI Package stage, from the built package and its ZIP, and checks it' { + $text = Read-RepoText '.github\scripts\Invoke-CI.ps1' + $stage = $text.Substring($text.IndexOf("'Package' {")) + $stage.IndexOf('& $builder') | Should -BeLessThan $stage.IndexOf('New-Sbom.ps1') + $stage | Should -Match "Resolve-RepositoryFile 'tools/New-Sbom\.ps1'" + $stage | Should -Match '-PackageRoot \$destination -ZipPath \$zipPath' + $stage | Should -Match 'does not describe the ZIP that was built' + $stage | Should -Match 'Bill of materials written and checked' + (Read-RepoText '.github\workflows\ci.yml') | Should -Match '-Stage Package' + } +} + +Describe 'Release 3.3.0 - Pester and PSScriptAnalyzer are pinned with the hashes of their packages (repository files, synthetic package)' -Tag 'Release330a' { + BeforeAll { + # A synthetic package of the shape of a Gallery package, and a pin file written for it. + function script:New-ModulePackage([string]$Folder, [string]$Name, [string]$Version, [string]$ManifestVersion) { + $stage = Join-Path $Folder ('stage-' + $Name); $null = New-Item -ItemType Directory -Path (Join-Path $stage '_rels'), (Join-Path $stage 'package\services') -Force + [IO.File]::WriteAllText((Join-Path $stage ($Name + '.psd1')), "@{ ModuleVersion = '$ManifestVersion'; GUID = '$([guid]::NewGuid())' }", $script:Utf8) + [IO.File]::WriteAllText((Join-Path $stage ($Name + '.psm1')), '# synthetic', $script:Utf8) + [IO.File]::WriteAllText((Join-Path $stage ($Name + '.nuspec')), '', $script:Utf8) + [IO.File]::WriteAllText((Join-Path $stage '[Content_Types].xml'), '', $script:Utf8) + [IO.File]::WriteAllText((Join-Path $stage '_rels\.rels'), '', $script:Utf8) + [IO.File]::WriteAllText((Join-Path $stage 'package\services\core.psmdcp'), '', $script:Utf8) + $packages = Join-Path $Folder 'packages'; $null = New-Item -ItemType Directory -Path $packages -Force + $nupkg = Join-Path $packages ('{0}.{1}.nupkg' -f $Name, $Version) + [IO.Compression.ZipFile]::CreateFromDirectory($stage, $nupkg) + $nupkg + } + function script:Write-ModulePin([string]$Folder, [string]$Name, [string]$Version, [string]$Sha256, [string]$Sha512) { + $pins = [ordered]@{ schema = 1; powerShell = @(); modules = @([ordered]@{ name = $Name; version = $Version; sha256 = $Sha256; sha512Base64 = $Sha512; size = 1; source = 'x'; hashSource = 'x' }) } + $path = Join-Path $Folder 'pins.json' + [IO.File]::WriteAllText($path, ($pins | ConvertTo-Json -Depth 5), $script:Utf8) + $path + } + } + It 'pins each module with a version, the SHA-256 of its package and the SHA-512 that the Gallery publishes for it' { + $modules = @((Get-PinData).modules) + @($modules).Count | Should -Be 2 + @($modules.name) | Should -Contain 'Pester' + @($modules.name) | Should -Contain 'PSScriptAnalyzer' + foreach ($module in $modules) { + $module.version | Should -Match '\A\d+\.\d+\.\d+\z' + $module.sha256 | Should -Match '\A[0-9A-F]{64}\z' + $module.sha512Base64 | Should -Match '\A[A-Za-z0-9+/]{86}==\z' + $module.source | Should -BeExactly ('https://www.powershellgallery.com/packages/{0}/{1}' -f $module.name, $module.version) + ([int64]$module.size) | Should -BeGreaterThan 100000 + } + } + It 'installs a package that matches both hashes, with the version of its manifest, without the packaging files' { + $folder = New-Folder 'mod' + $nupkg = New-ModulePackage $folder 'Pester' '6.1.0' '6.1.0' + $pins = Write-ModulePin $folder 'Pester' '6.1.0' (Get-Sha256Hex $nupkg).ToLowerInvariant() (Get-Sha512Base64 $nupkg) + $envFile = Join-Path $folder 'github-env.txt' + $destination = Join-Path $folder 'modules' + $run = Invoke-ChildScript -Script (Join-Path $script:Scripts 'Initialize-CIModules.ps1') -Argument @('-Destination', $destination, '-PinsPath', $pins, '-PackageDirectory', (Join-Path $folder 'packages')) -Environment @{ GITHUB_ENV = $envFile } + $run.ExitCode | Should -Be 0 -Because $run.Output + $target = Join-Path $destination 'Pester\6.1.0' + Test-Path -LiteralPath (Join-Path $target 'Pester.psd1') | Should -BeTrue + Test-Path -LiteralPath (Join-Path $target 'Pester.psm1') | Should -BeTrue + foreach ($left in '_rels', 'package', '[Content_Types].xml', 'Pester.nuspec') { Test-Path -LiteralPath (Join-Path $target $left) | Should -BeFalse -Because $left } + [IO.File]::ReadAllText($envFile) | Should -Match ('CI_MODULE_PATH=' + [regex]::Escape($destination)) + } + It 'stops at a package whose SHA-256 or SHA-512 differs from the pin, and extracts nothing' -ForEach @( + @{ Case = 'SHA-256'; Match = 'does not match its pinned SHA-256' } + @{ Case = 'SHA-512'; Match = 'does not match its pinned SHA-512' } + @{ Case = 'tampered package'; Match = 'does not match its pinned SHA-256' } + ) { + $folder = New-Folder 'mod' + $nupkg = New-ModulePackage $folder 'Pester' '6.1.0' '6.1.0' + $sha256 = (Get-Sha256Hex $nupkg).ToLowerInvariant(); $sha512 = Get-Sha512Base64 $nupkg + if ($Case -eq 'SHA-256') { $sha256 = '0' * 64 } + if ($Case -eq 'SHA-512') { $sha512 = ('A' * 86) + '==' } + $pins = Write-ModulePin $folder 'Pester' '6.1.0' $sha256 $sha512 + if ($Case -eq 'tampered package') { + $bytes = [IO.File]::ReadAllBytes($nupkg); $bytes[$bytes.Length - 40] = [byte]($bytes[$bytes.Length - 40] -bxor 0x55); [IO.File]::WriteAllBytes($nupkg, $bytes) + } + $destination = Join-Path $folder 'modules' + $run = Invoke-ChildScript -Script (Join-Path $script:Scripts 'Initialize-CIModules.ps1') -Argument @('-Destination', $destination, '-PinsPath', $pins, '-PackageDirectory', (Join-Path $folder 'packages')) -Environment @{ GITHUB_ENV = (Join-Path $folder 'env.txt') } + $run.ExitCode | Should -Not -Be 0 + $run.Output | Should -Match $Match + Test-Path -LiteralPath (Join-Path $destination 'Pester') | Should -BeFalse + Test-Path -LiteralPath (Join-Path $folder 'env.txt') | Should -BeFalse + } + It 'stops at a package whose manifest says another version than the pin, and at a pin that is not valid' { + $folder = New-Folder 'mod' + $nupkg = New-ModulePackage $folder 'Pester' '6.1.0' '6.0.0' + $pins = Write-ModulePin $folder 'Pester' '6.1.0' (Get-Sha256Hex $nupkg) (Get-Sha512Base64 $nupkg) + $run = Invoke-ChildScript -Script (Join-Path $script:Scripts 'Initialize-CIModules.ps1') -Argument @('-Destination', (Join-Path $folder 'modules'), '-PinsPath', $pins, '-PackageDirectory', (Join-Path $folder 'packages')) -Environment @{ GITHUB_ENV = (Join-Path $folder 'env.txt') } + $run.ExitCode | Should -Not -Be 0 + $run.Output | Should -Match 'extracted module version does not match' + $short = Write-ModulePin $folder 'Pester' '6.1.0' 'abc' (Get-Sha512Base64 $nupkg) + $second = Invoke-ChildScript -Script (Join-Path $script:Scripts 'Initialize-CIModules.ps1') -Argument @('-Destination', (Join-Path $folder 'modules2'), '-PinsPath', $short, '-PackageDirectory', (Join-Path $folder 'packages')) -Environment @{ GITHUB_ENV = (Join-Path $folder 'env.txt') } + $second.ExitCode | Should -Not -Be 0 + $second.Output | Should -Match 'hash pins of Pester are not valid' + } + It 'the hash check runs before the package is extracted, in the script text' { + $text = Read-RepoText '.github\scripts\Initialize-CIModules.ps1' + $text.IndexOf('Assert-PackageHash -Path $package') | Should -BeLessThan $text.IndexOf('ExtractToDirectory') + $text | Should -Not -Match 'Save-Module' + } +} + +Describe 'Release 3.3.0 - the monthly dependency watch reads and reports, and writes nothing to GitHub (repository files, synthetic data)' -Tag 'Release330a' { + It 'the workflow is monthly, has read-only contents permission only, and opens no issue and no pull request' { + $text = Read-RepoText '.github\workflows\dependency-watch.yml' + $text | Should -Match "(?m)^ - cron: '\d{1,2} \d{1,2} \d{1,2} \* \*'$" + $text | Should -Match "(?ms)^permissions:\n contents: read\n\n" + @([regex]::Matches($text, '(?m)^\s*permissions:')).Count | Should -Be 1 + $text | Should -Not -Match '(?i)(issues|pull-requests|contents|actions|checks|statuses|security-events|id-token|attestations):\s*write' + $text | Should -Not -Match '(?i)gh (issue|pr)|create-issue|create-pull-request|peter-evans|issues\.create|pulls\.create' + $text | Should -Match "if: \$\{\{ github\.repository == 'Nico77600/PraRemoteMailbox' \}\}" + $text | Should -Match 'workflow_dispatch' + $text | Should -Not -Match '(?m)^\s+pull_request' + } + It 'the script makes only GET requests to https addresses, in one function, and has no other way out to the network' { + $text = Read-RepoText '.github\scripts\Invoke-DependencyWatch.ps1' + $text | Should -Not -Match '(?i)-Method\s+(Post|Put|Patch|Delete)' + @([regex]::Matches($text, 'Invoke-WebRequest|Invoke-RestMethod|\[Net\.|HttpClient|WebClient|curl|\bgh\b\s')).Count | Should -Be 1 + $text | Should -Match "Scheme -ne 'https'" + $text | Should -Match "Host -ceq 'api\.github\.com'" + } + It 'compares a version with the range of an advisory the way GitHub writes it' -ForEach @( + @{ Version = '7.5.11'; Range = '>= 7.5.0, < 7.5.12'; Expected = $true } + @{ Version = '7.5.12'; Range = '>= 7.5.0, < 7.5.12'; Expected = $false } + @{ Version = '7.5.0'; Range = '>= 7.5.0, < 7.5.12'; Expected = $true } + @{ Version = '7.4.9'; Range = '>= 7.5.0, < 7.5.12'; Expected = $false } + @{ Version = '6.1.0'; Range = '<= 6.1.0'; Expected = $true } + @{ Version = '6.1.1'; Range = '<= 6.1.0'; Expected = $false } + @{ Version = '2.0.0'; Range = '= 2.0.0'; Expected = $true } + @{ Version = '2.0.0'; Range = '> 2.0.0'; Expected = $false } + @{ Version = '2.0.0'; Range = '< 7.0.0-rc.1'; Expected = $true } + @{ Version = '7.0.0'; Range = '< 7.0.0-rc.1'; Expected = $false } + @{ Version = '7.0.0'; Range = '<= 7.0.0-rc.1'; Expected = $false } + @{ Version = '7.0.0'; Range = '>= 7.0.0-rc.1, < 7.0.1'; Expected = $true } + @{ Version = '2.0.0'; Range = 'garbage'; Expected = $false } + @{ Version = '2.0.0'; Range = ''; Expected = $false } + ) { + Test-WatchVersionInRange -Version ([version]$Version) -Range $Range | Should -Be $Expected + } + It 'fails for a pinned PowerShell whose line is out of support or named by an advisory, warns for a newer patch, and keeps the floor leg informational' { + $primary = [pscustomobject]@{ role = 'primary'; line = '7.6'; version = '7.6.10'; source = 'https://example.invalid/p'; supportEnds = '2028-11-14'; supportSource = 'https://example.invalid/s' } + $floor = [pscustomobject]@{ role = 'floor'; line = '7.5'; version = '7.5.13'; source = 'https://example.invalid/f'; supportEnds = '2026-11-10'; supportSource = 'https://example.invalid/s' } + $advisory = [pscustomobject]@{ ghsa_id = 'GHSA-xxxx-xxxx-xxxx'; summary = 'synthetic'; html_url = 'https://example.invalid/a'; withdrawn_at = $null; vulnerabilities = @([pscustomobject]@{ vulnerable_version_range = '>= 7.6.0, < 7.6.11' }) } + $today = [datetime]'2026-11-23' + @(Get-WatchPowerShellFinding -Pin $primary -ReleaseTag @('v7.6.10', 'v7.5.13') -Advisory @() -Today $today).Count | Should -Be 0 + @(Get-WatchPowerShellFinding -Pin $primary -ReleaseTag @('v7.6.10') -Advisory @() -Today ([datetime]'2028-11-15') | Where-Object Level -eq 'Fail').Count | Should -Be 1 + @(Get-WatchPowerShellFinding -Pin $primary -ReleaseTag @() -Advisory @() -Today ([datetime]'2028-09-01') | Where-Object Level -eq 'Warn').Count | Should -Be 1 + $behind = @(Get-WatchPowerShellFinding -Pin $primary -ReleaseTag @('v7.6.11', 'v7.7.0', 'v7.6.9') -Advisory @() -Today $today) + $behind.Count | Should -Be 1 + $behind[0].Level | Should -BeExactly 'Warn' + $behind[0].Message | Should -Match '7\.6\.11' + $hit = @(Get-WatchPowerShellFinding -Pin $primary -ReleaseTag @('v7.6.10') -Advisory @($advisory) -Today $today) + $hit.Count | Should -Be 1 + $hit[0].Level | Should -BeExactly 'Fail' + $withdrawn = $advisory.PSObject.Copy(); $withdrawn.withdrawn_at = '2026-01-01T00:00:00Z' + @(Get-WatchPowerShellFinding -Pin $primary -ReleaseTag @('v7.6.10') -Advisory @($withdrawn) -Today $today).Count | Should -Be 0 + $floorFindings = @(Get-WatchPowerShellFinding -Pin $floor -ReleaseTag @('v7.5.13') -Advisory @() -Today $today) + $floorFindings.Count | Should -Be 1 + $floorFindings[0].Level | Should -BeExactly 'Info' + @(Get-WatchPowerShellFinding -Pin $floor -ReleaseTag @('v7.5.14') -Advisory @() -Today $today | Where-Object Level -in 'Fail', 'Warn').Count | Should -Be 0 + } + It 'warns when a module is behind the Gallery, fails when an advisory names its version, and says what to do' { + $pin = [pscustomobject]@{ name = 'Pester'; version = '6.1.0'; source = 'https://example.invalid/m' } + @(Get-WatchModuleFinding -Pin $pin -LatestVersion '6.1.0' -Advisory @()).Count | Should -Be 0 + $behind = @(Get-WatchModuleFinding -Pin $pin -LatestVersion '6.2.0' -Advisory @()) + $behind.Count | Should -Be 1 + $behind[0].Level | Should -BeExactly 'Warn' + $behind[0].Message | Should -Match 'ci-pins\.json' + $advisory = [pscustomobject]@{ ghsa_id = 'GHSA-yyyy'; summary = 's'; html_url = 'u'; vulnerabilities = @([pscustomobject]@{ vulnerable_version_range = '<= 6.1.0' }) } + (@(Get-WatchModuleFinding -Pin $pin -LatestVersion '6.1.0' -Advisory @($advisory)))[0].Level | Should -BeExactly 'Fail' + @(Get-WatchModuleFinding -Pin $pin -LatestVersion $null -Advisory $null).Count | Should -Be 0 + } + It 'fails when the tag of a pinned action points at another commit, warns for a newer release of its major, and informs of a newer major' { + $pin = [pscustomobject]@{ Name = 'actions/checkout'; Repository = 'actions/checkout'; Sha = ('a' * 40); Tag = 'v7.0.1'; File = 'x'; Line = 1; Valid = $true } + @(Get-WatchActionFinding -Pin $pin -ReleaseTag @('v7.0.1', 'v6.1.0') -TagCommit ('a' * 40).ToUpperInvariant() -Advisory @()).Count | Should -Be 0 + (@(Get-WatchActionFinding -Pin $pin -ReleaseTag @('v7.0.1') -TagCommit ('b' * 40) -Advisory @()))[0].Level | Should -BeExactly 'Fail' + $newer = @(Get-WatchActionFinding -Pin $pin -ReleaseTag @('v7.0.1', 'v7.1.0', 'v8.0.0') -TagCommit ('a' * 40) -Advisory @()) + @($newer | Where-Object Level -eq 'Warn').Count | Should -Be 1 + @($newer | Where-Object Level -eq 'Info').Count | Should -Be 1 + $advisory = [pscustomobject]@{ ghsa_id = 'GHSA-zzzz'; summary = 's'; html_url = 'u'; vulnerabilities = @([pscustomobject]@{ package = [pscustomobject]@{ ecosystem = 'actions'; name = 'Actions/Checkout' }; vulnerable_version_range = '< 7.0.2' }) } + (@(Get-WatchActionFinding -Pin $pin -ReleaseTag @('v7.0.1') -TagCommit $null -Advisory @($advisory)))[0].Level | Should -BeExactly 'Fail' + $other = [pscustomobject]@{ ghsa_id = 'GHSA-other'; summary = 's'; html_url = 'u'; vulnerabilities = @([pscustomobject]@{ package = [pscustomobject]@{ ecosystem = 'actions'; name = 'actions/cache' }; vulnerable_version_range = '< 7.0.2' }) } + @(Get-WatchActionFinding -Pin $pin -ReleaseTag @('v7.0.1') -TagCommit $null -Advisory @($other)).Count | Should -Be 0 -Because 'an advisory of another action is not about this pin' + } + It 'warns, and never stays silent, when the version range of an advisory cannot be read, and tells that range from one that does not cover the version' { + Get-WatchRangeState -Version ([version]'1.0.0') -Range '>= 1.0.0, < 2.0.0' | Should -BeExactly 'In' + Get-WatchRangeState -Version ([version]'3.0.0') -Range '>= 1.0.0, < 2.0.0' | Should -BeExactly 'Out' + foreach ($range in @('', ' ', 'garbage', '>= one', '1.0.0', '>= 1.0.0 || < 0.5', '~> 1.0')) { Get-WatchRangeState -Version ([version]'1.0.0') -Range $range | Should -BeExactly 'Unreadable' -Because "'$range'" } + $pin = [pscustomobject]@{ name = 'Pester'; version = '6.1.0'; source = 'https://example.invalid/m' } + $unreadable = [pscustomobject]@{ ghsa_id = 'GHSA-rrrr'; summary = 's'; html_url = 'u'; vulnerabilities = @([pscustomobject]@{ vulnerable_version_range = 'from the start' }) } + $found = @(Get-WatchModuleFinding -Pin $pin -LatestVersion '6.1.0' -Advisory @($unreadable)) + $found.Count | Should -Be 1 + $found[0].Level | Should -BeExactly 'Warn' + $found[0].Message | Should -Match 'GHSA-rrrr' + $found[0].Message | Should -Match 'cannot be read' + $mixed = [pscustomobject]@{ ghsa_id = 'GHSA-mmmm'; summary = 's'; html_url = 'u'; vulnerabilities = @([pscustomobject]@{ vulnerable_version_range = 'from the start' }, [pscustomobject]@{ vulnerable_version_range = '<= 6.1.0' }) } + (@(Get-WatchModuleFinding -Pin $pin -LatestVersion '6.1.0' -Advisory @($mixed)))[0].Level | Should -BeExactly 'Fail' -Because 'a range that covers the version wins over one that cannot be read' + $outside = [pscustomobject]@{ ghsa_id = 'GHSA-oooo'; summary = 's'; html_url = 'u'; vulnerabilities = @([pscustomobject]@{ vulnerable_version_range = '< 5.0.0' }) } + @(Get-WatchModuleFinding -Pin $pin -LatestVersion '6.1.0' -Advisory @($outside)).Count | Should -Be 0 + } + It 'reads the advisories of the nuget packages of PowerShell and of its .NET runtime, by package name, and fails the primary pin and only warns for the floor' { + $primary = [pscustomobject]@{ role = 'primary'; line = '7.6'; version = '7.6.10'; dotNetRuntime = '10.0.15'; source = 'u'; supportEnds = '2028-11-14'; supportSource = 's' } + $floor = [pscustomobject]@{ role = 'floor'; line = '7.5'; version = '7.5.13'; dotNetRuntime = '9.0.22'; source = 'u'; supportEnds = '2028-11-14'; supportSource = 's' } + $runtime = [pscustomobject]@{ ghsa_id = 'GHSA-run1'; summary = 'runtime'; html_url = 'u'; vulnerabilities = @( + [pscustomobject]@{ package = [pscustomobject]@{ ecosystem = 'nuget'; name = 'Microsoft.NETCore.App.Runtime.win-x64' }; vulnerable_version_range = '>= 10.0.0, < 10.0.16' } + [pscustomobject]@{ package = [pscustomobject]@{ ecosystem = 'nuget'; name = 'Microsoft.NETCore.App.Runtime.win-x86' }; vulnerable_version_range = '>= 9.0.0, < 9.0.30' }) } + $sdk = [pscustomobject]@{ ghsa_id = 'GHSA-sdk1'; summary = 'sdk'; html_url = 'u'; vulnerabilities = @([pscustomobject]@{ package = [pscustomobject]@{ ecosystem = 'nuget'; name = 'System.Management.Automation' }; vulnerable_version_range = '>= 7.6.0, < 7.6.11' }) } + $found = @(Get-WatchPowerShellFinding -Pin $primary -ReleaseTag @('v7.6.10') -Advisory @() -Today ([datetime]'2026-11-23') -PackageAdvisory @($sdk) -RuntimeAdvisory @($runtime)) + @($found | Where-Object Level -eq 'Fail').Count | Should -Be 2 + ($found | Where-Object { $_.Component -match '\.NET runtime 10\.0\.15' }).Message | Should -Match 'GHSA-run1' + ($found | Where-Object { $_.Message -match 'GHSA-sdk1' }).Level | Should -BeExactly 'Fail' + $warned = @(Get-WatchPowerShellFinding -Pin $floor -ReleaseTag @('v7.5.13') -Advisory @() -Today ([datetime]'2026-11-23') -PackageAdvisory @() -RuntimeAdvisory @($runtime)) + @($warned | Where-Object Level -eq 'Fail').Count | Should -Be 0 -Because 'the x86 entry and the other range do not name 9.0.22 of the x64 package' + $floorHit = [pscustomobject]@{ ghsa_id = 'GHSA-run2'; summary = 'runtime'; html_url = 'u'; vulnerabilities = @([pscustomobject]@{ package = [pscustomobject]@{ ecosystem = 'nuget'; name = 'Microsoft.NETCore.App.Runtime.win-x64' }; vulnerable_version_range = '>= 9.0.0, < 9.0.23' }) } + (@(Get-WatchPowerShellFinding -Pin $floor -ReleaseTag @('v7.5.13') -Advisory @() -Today ([datetime]'2026-11-23') -PackageAdvisory @() -RuntimeAdvisory @($floorHit) | Where-Object { $_.Message -match 'GHSA-run2' }))[0].Level | Should -BeExactly 'Warn' + } + It 'fails when every lookup failed, or every lookup of one kind of source failed, and counts the lookups that it makes' { + @(Get-WatchSourceFinding -Stats @{ 'GitHub releases' = [pscustomobject]@{ Attempts = 3; Failures = 1 }; 'PowerShell Gallery' = [pscustomobject]@{ Attempts = 2; Failures = 0 } }).Count | Should -Be 0 + $kind = @(Get-WatchSourceFinding -Stats @{ 'GitHub releases' = [pscustomobject]@{ Attempts = 3; Failures = 3 }; 'PowerShell Gallery' = [pscustomobject]@{ Attempts = 2; Failures = 0 } }) + $kind.Count | Should -Be 1 + $kind[0].Level | Should -BeExactly 'Fail' + $kind[0].Component | Should -Match 'GitHub releases' + $all = @(Get-WatchSourceFinding -Stats @{ 'GitHub releases' = [pscustomobject]@{ Attempts = 3; Failures = 3 }; 'PowerShell Gallery' = [pscustomobject]@{ Attempts = 2; Failures = 2 } }) + @($all | Where-Object Level -eq 'Fail').Count | Should -Be 3 + $none = @(Get-WatchSourceFinding -Stats @{}) + $none.Count | Should -Be 1 + $none[0].Level | Should -BeExactly 'Fail' + $script:WatchStats = @{}; $script:WatchCache = @{} + $findings = New-Object 'System.Collections.Generic.List[object]' + $good = Invoke-WatchSource -Kind 'K' -Component 'c' -Findings $findings -Lookup { 'value' } + $bad = Invoke-WatchSource -Kind 'K' -Component 'c' -Findings $findings -Lookup { throw 'Source unavailable: synthetic' } + $cached = Invoke-WatchSource -Kind 'K' -Component 'c' -Findings $findings -Key 'same' -Lookup { 'first' } + $again = Invoke-WatchSource -Kind 'K' -Component 'c' -Findings $findings -Key 'same' -Lookup { 'second' } + $good | Should -BeExactly 'value' + $bad | Should -BeNullOrEmpty + $again | Should -BeExactly 'first' + $script:WatchStats['K'].Attempts | Should -Be 3 + $script:WatchStats['K'].Failures | Should -Be 1 + $findings.Count | Should -Be 1 + $findings[0].Level | Should -BeExactly 'Warn' + $script:WatchStats = @{}; $script:WatchCache = @{} + } + It 'warns 90 days before the signing certificate ends, fails when it has ended, and compares the pinned thumbprint with the one of the signed manifest' { + $certificate = [pscustomobject]@{ thumbprint = '0F28E442889F17B5F4D251E8F96E7CC6E2C9C6D6'; notAfter = '2027-10-13'; warnDays = 90 } + @(Get-WatchCertificateFinding -Certificate $certificate -ManifestThumbprint $certificate.thumbprint -Today ([datetime]'2026-11-23')).Count | Should -Be 0 + @(Get-WatchCertificateFinding -Certificate $certificate -ManifestThumbprint $certificate.thumbprint -Today ([datetime]'2027-07-14')).Count | Should -Be 0 + $near = @(Get-WatchCertificateFinding -Certificate $certificate -ManifestThumbprint $certificate.thumbprint -Today ([datetime]'2027-07-15')) + $near.Count | Should -Be 1 + $near[0].Level | Should -BeExactly 'Warn' + $near[0].Message | Should -Match '2027-10-13 \(90 days\)' + (@(Get-WatchCertificateFinding -Certificate $certificate -ManifestThumbprint $certificate.thumbprint -Today ([datetime]'2027-10-14')))[0].Level | Should -BeExactly 'Fail' + $other = @(Get-WatchCertificateFinding -Certificate $certificate -ManifestThumbprint ('0f28e442889f17b5f4d251e8f96e7cc6e2c9c6d6') -Today ([datetime]'2026-11-23')) + $other.Count | Should -Be 0 -Because 'a thumbprint is compared ignoring case' + $changed = @(Get-WatchCertificateFinding -Certificate $certificate -ManifestThumbprint ('A' * 40) -Today ([datetime]'2026-11-23')) + $changed.Count | Should -Be 1 + $changed[0].Level | Should -BeExactly 'Warn' + } + It 'holds the certificate end date in the pin file, for the certificate that the signed manifest names' { + $pin = (Get-PinData).signingCertificate + $pin.notAfter | Should -BeExactly '2027-10-13' + [int]$pin.warnDays | Should -Be 90 + $pin.thumbprint | Should -Match '\A[0-9A-F]{40}\z' + (Read-RepoText 'package\PackageIntegrity.psd1') | Should -Match ("SignerThumbprint = '" + $pin.thumbprint + "'") + } + It 'writes a message in a workflow command with the percent sign and the line breaks escaped, and uses that for every error and warning' { + ConvertTo-WatchAnnotation "50% done`r`nsecond line`nthird" | Should -BeExactly '50%25 done%0D%0Asecond line%0Athird' + ConvertTo-WatchAnnotation $null | Should -BeExactly '' + ConvertTo-WatchAnnotation '%0A' | Should -BeExactly '%250A' + $text = Read-RepoText '.github\scripts\Invoke-DependencyWatch.ps1' + $text | Should -Match ([regex]::Escape("`$text = ConvertTo-WatchAnnotation ('{0}: {1}' -f `$item.Component, `$item.Message)")) + $text | Should -Match ([regex]::Escape("Write-Output ('::error title=Dependency watch::' + `$text)")) + $text | Should -Match ([regex]::Escape("Write-Output ('::warning title=Dependency watch::' + `$text)")) + $text | Should -Not -Match '::(error|warning)[^\r\n]*\+ \$item' + } + It 'tells where the last run stands: the run date and the 60 days without repository activity after which GitHub stops a scheduled workflow' { + $summary = Format-WatchSummary -Finding @() -Today ([datetime]'2026-11-23') + $summary | Should -Match 'Run date: 2026-11-23 \(UTC\)' + $summary | Should -Match 'after 60 days without repository activity' + $summary | Should -Match 'if no run is listed after 2027-01-02' + $summary | Should -Match 'keep-alive commit is not needed' + } + It 'takes the newer release of an action from the tags of its releases: the codeql-bundle releases and the older major are not candidates' { + $pin = [pscustomobject]@{ Name = 'github/codeql-action/init'; Repository = 'github/codeql-action'; Sha = ('a' * 40); Tag = 'v4.38.3'; File = 'x'; Line = 1; Valid = $true } + $tags = @('codeql-bundle-v2.27.5', 'v3.39.4', 'v4.39.4', 'codeql-bundle-v2.27.4', 'v4.39.3', 'v4.38.3', 'v4.39.5-beta.1') + (Get-WatchLatestInLine -Pinned ([version]'4.38.3') -Tag $tags).ToString() | Should -BeExactly '4.39.4' + $found = @(Get-WatchActionFinding -Pin $pin -ReleaseTag $tags -TagCommit $pin.Sha -Advisory @()) + $found.Count | Should -Be 1 + $found[0].Message | Should -Match '4\.39\.4' + $releases = @( + [pscustomobject]@{ tag_name = 'codeql-bundle-v2.27.5'; name = 'CodeQL Bundle v2.27.5'; draft = $false; prerelease = $false } + [pscustomobject]@{ tag_name = 'v4.39.4'; name = 'v4.39.4'; draft = $false; prerelease = $false } + [pscustomobject]@{ tag_name = 'v4.40.0'; name = 'v4.40.0'; draft = $true; prerelease = $false } + [pscustomobject]@{ tag_name = 'v4.41.0-rc1'; name = 'v4.41.0-rc1'; draft = $false; prerelease = $true }) + $json = ConvertTo-Json -InputObject $releases -Depth 4 + Mock Invoke-WatchRequest -MockWith ({ $json }.GetNewClosure()) + @(Get-WatchReleaseTag 'github/codeql-action') | Should -Be @('codeql-bundle-v2.27.5', 'v4.39.4') + } + It 'reads the declared minimums of the package, and the summary table escapes what it prints' { + $declared = Get-WatchDeclaredMinimum $script:Repo + $declared.PowerShell | Should -Match '\A\d+\.\d+\z' + $declared.ExchangeOnlineManagement | Should -Match '\A\d+\.\d+\.\d+\z' + $declared.GraphAuthentication | Should -Match '\A\d+\.\d+\.\d+\z' + $summary = Format-WatchSummary -Finding @(New-WatchFinding Warn 'a|b' "line one`nline two | pipe" 'https://example.invalid/x') -Today ([datetime]'2026-11-23') + $summary | Should -Match 'a\\\|b' + $summary | Should -Match 'line one line two \\\| pipe' + (Format-WatchSummary -Finding @() -Today ([datetime]'2026-11-23')) | Should -Match 'Nothing to act on' + } +} + +Describe 'Release 3.3.0 - the CodeQL job runs for this repository only (repository files)' -Tag 'Release330a' { + It 'the guard names this repository and no other repository of the account' { + $text = Read-RepoText '.github\workflows\codeql.yml' + $names = @([regex]::Matches($text, 'Nico77600/[A-Za-z0-9_.-]+') | ForEach-Object Value | Sort-Object -Unique) + $names | Should -Be @('Nico77600/PraRemoteMailbox') + $text | Should -Match "(?m)^ if: \$\{\{ github\.repository == 'Nico77600/PraRemoteMailbox' && \(github\.event_name == 'pull_request' \|\| github\.ref == 'refs/heads/main'\) \}\}$" + } +} + +Describe 'Release 3.3.0 - every test file is run by the gate and by the CI (repository files)' -Tag 'Release330a' { + It 'the gate, the CI configuration and the tests folder list the same test files' { + $onDisk = @(Get-ChildItem -LiteralPath $PSScriptRoot -File -Filter '*.Tests.ps1' | ForEach-Object Name | Sort-Object { $_ } -CaseSensitive) + $gate = Read-RepoText 'tests\Invoke-TestGate.ps1' + $inGate = @([regex]::Matches($gate, "Join-Path \`$PSScriptRoot '([A-Za-z0-9.]+\.Tests\.ps1)'") | ForEach-Object { $_.Groups[1].Value } | Sort-Object { $_ } -CaseSensitive) + $inCi = @((Read-RepoText '.github\ci.json' | ConvertFrom-Json).tests | ForEach-Object { [IO.Path]::GetFileName($_) } | Sort-Object { $_ } -CaseSensitive) + ($inGate -join '|') | Should -BeExactly ($onDisk -join '|') + ($inCi -join '|') | Should -BeExactly ($onDisk -join '|') + } +} + +Describe 'Release 3.3.0 - the bill of materials and the dependency declaration of a release ZIP (tool, synthetic package built from the repository package)' -Tag 'Release330a' { + BeforeAll { + $script:Sbom = Join-Path $script:Repo 'tools\New-Sbom.ps1' + $script:SbomWork = New-Folder 'sbom' + $script:SbomPackage = Join-Path $script:SbomWork 'PraRemoteMailbox-9.9.9' + New-PraIntegrityFixture -SourcePackage (Join-Path $script:Repo 'package') -Destination $script:SbomPackage -Changelog (Join-Path $script:Repo 'CHANGELOG.md') -IncludeChangelog + Add-Type -AssemblyName System.IO.Compression.FileSystem + $script:SbomZip = Join-Path $script:SbomWork 'PraRemoteMailbox-9.9.9.zip' + [IO.Compression.ZipFile]::CreateFromDirectory($script:SbomPackage, $script:SbomZip, [IO.Compression.CompressionLevel]::Optimal, $true) + $script:SbomRun = Invoke-ChildScript -Script $script:Sbom -Argument @('-PackageRoot', $script:SbomPackage, '-ZipPath', $script:SbomZip, '-RepositoryRoot', $script:Repo, '-Created', '2026-11-23T10:00:00Z') + $script:SbomFile = $script:SbomZip + '.spdx.json' + $script:DeclarationFile = Join-Path $script:SbomWork 'PraRemoteMailbox-9.9.9-dependencies.md' + } + It 'writes the two files next to the ZIP and returns their paths' { + $script:SbomRun.ExitCode | Should -Be 0 -Because $script:SbomRun.Output + Test-Path -LiteralPath $script:SbomFile | Should -BeTrue + Test-Path -LiteralPath $script:DeclarationFile | Should -BeTrue + $script:SbomRun.Output | Should -Match ([regex]::Escape($script:SbomFile)) + } + It 'describes the ZIP: its SHA-256, one entry per file with its SHA-256, no third-party component shipped' { + $document = [IO.File]::ReadAllText($script:SbomFile) | ConvertFrom-Json -DateKind String + $document.spdxVersion | Should -BeExactly 'SPDX-2.3' + $document.dataLicense | Should -BeExactly 'CC0-1.0' + $document.creationInfo.created | Should -BeExactly '2026-11-23T10:00:00Z' + $root = @($document.packages | Where-Object SPDXID -eq 'SPDXRef-Package-PraRemoteMailbox') + $root.Count | Should -Be 1 + $root[0].checksums[0].checksumValue | Should -BeExactly (Get-Sha256Hex $script:SbomZip).ToLowerInvariant() + $root[0].licenseDeclared | Should -BeExactly 'MIT' + $root[0].filesAnalyzed | Should -BeTrue + $root[0].packageVerificationCode.packageVerificationCodeValue | Should -Match '\A[0-9a-f]{40}\z' + $sha1 = [string[]]@(Get-ChildItem -LiteralPath $script:SbomPackage -Recurse -File | ForEach-Object { (Get-FileHash -LiteralPath $_.FullName -Algorithm SHA1).Hash.ToLowerInvariant() }) + [Array]::Sort($sha1, [StringComparer]::Ordinal) + $expectedCode = [Convert]::ToHexString([Security.Cryptography.SHA1]::HashData([Text.Encoding]::ASCII.GetBytes(($sha1 -join '')))).ToLowerInvariant() + $root[0].packageVerificationCode.packageVerificationCodeValue | Should -BeExactly $expectedCode -Because 'the code is the SHA-1 of the sorted SHA-1 values of the files' + $folderFiles = @(Get-ChildItem -LiteralPath $script:SbomPackage -Recurse -File) + @($document.files).Count | Should -Be $folderFiles.Count + $entry = @($document.files | Where-Object fileName -eq './README.md')[0] + ($entry.checksums | Where-Object algorithm -eq 'SHA256').checksumValue | Should -BeExactly (Get-Sha256Hex (Join-Path $script:SbomPackage 'README.md')).ToLowerInvariant() + @($document.relationships | Where-Object { $_.relationshipType -eq 'CONTAINS' -and $_.spdxElementId -eq $root[0].SPDXID }).Count | Should -Be $folderFiles.Count + @($document.relationships | Where-Object relationshipType -eq 'DESCRIBES').Count | Should -Be 1 + } + It 'declares what is required and not bundled, with the minimums that the package itself holds, and what builds and tests it' { + $document = [IO.File]::ReadAllText($script:SbomFile) | ConvertFrom-Json + $common = [IO.File]::ReadAllText((Join-Path $script:SbomPackage 'module\PRA.Common.psm1')) + $psd1 = [IO.File]::ReadAllText((Join-Path $script:SbomPackage 'PraRemoteMailbox.psd1')) + $declared = [pscustomobject]@{ + PowerShell = [regex]::Match($psd1, "(?m)^\s*PowerShellVersion\s*=\s*'([0-9.]+)'").Groups[1].Value + ExchangeOnlineManagement = [regex]::Match($common, "(?m)^\`$script:PraMinExoVersion\s*=\s*'([0-9.]+)'").Groups[1].Value + GraphAuthentication = [regex]::Match($common, "(?m)^\`$script:PraMinGraphVersion\s*=\s*'([0-9.]+)'").Groups[1].Value + } + $required = @($document.relationships | Where-Object relationshipType -eq 'DEPENDS_ON') + $required.Count | Should -Be 6 + $names = @($document.packages | Where-Object { $_.SPDXID -like 'SPDXRef-Required-*' } | ForEach-Object name | Sort-Object) + $names.Count | Should -Be 6 + foreach ($expected in 'PowerShell', 'ActiveDirectory', 'ADSync', 'ExchangeOnlineManagement', 'Microsoft.Graph.Authentication', 'Microsoft.Graph.Users') { $names | Should -Contain $expected } + (@($document.packages | Where-Object name -eq 'ExchangeOnlineManagement')[0].comment) | Should -Match ('at least version ' + [regex]::Escape($declared.ExchangeOnlineManagement)) + (@($document.packages | Where-Object name -eq 'Microsoft.Graph.Users')[0].comment) | Should -Match ('at least version ' + [regex]::Escape($declared.GraphAuthentication)) + (@($document.packages | Where-Object name -eq 'PowerShell')[0].comment) | Should -Match ('at least version ' + [regex]::Escape($declared.PowerShell)) + $build = @($document.relationships | Where-Object relationshipType -eq 'BUILD_DEPENDENCY_OF') + $pins = Get-PinData + $build.Count | Should -Be (1 + @($pins.modules).Count + @(Get-WatchWorkflowPin $script:Repo | ForEach-Object { '{0}@{1}' -f $_.Repository, $_.Tag } | Sort-Object -Unique).Count) + $pester = @($document.packages | Where-Object { $_.name -eq 'Pester' })[0] + $pester.checksums[0].checksumValue | Should -BeExactly (@($pins.modules | Where-Object name -eq 'Pester')[0].sha256.ToLowerInvariant()) + $declaration = [IO.File]::ReadAllText($script:DeclarationFile) + $declaration | Should -Match 'ships no third-party code and no third-party binary' + $declaration | Should -Match ([regex]::Escape('| ExchangeOnlineManagement | ' + $declared.ExchangeOnlineManagement + ' |')) + $declaration | Should -Match 'actions/checkout \(GitHub Actions\) \| v7\.0\.1 \| 3d3c42e5aac5ba805825da76410c181273ba90b1' + $declaration | Should -Not -Match "`r" + } + It 'is the same bytes when it is written again for the same ZIP and the same time, and never overwrites a file' { + $again = New-Folder 'again' + $second = Invoke-ChildScript -Script $script:Sbom -Argument @('-PackageRoot', $script:SbomPackage, '-ZipPath', $script:SbomZip, '-RepositoryRoot', $script:Repo, '-Created', '2026-11-23T10:00:00Z', '-OutputDirectory', $again) + $second.ExitCode | Should -Be 0 -Because $second.Output + (Get-Sha256Hex (Join-Path $again 'PraRemoteMailbox-9.9.9.zip.spdx.json')) | Should -BeExactly (Get-Sha256Hex $script:SbomFile) + (Get-Sha256Hex (Join-Path $again 'PraRemoteMailbox-9.9.9-dependencies.md')) | Should -BeExactly (Get-Sha256Hex $script:DeclarationFile) + $third = Invoke-ChildScript -Script $script:Sbom -Argument @('-PackageRoot', $script:SbomPackage, '-ZipPath', $script:SbomZip, '-RepositoryRoot', $script:Repo) + $third.ExitCode | Should -Not -Be 0 + $third.Output | Should -Match 'never overwritten' + } + It 'stops when the ZIP and the package folder differ, and when a file does not match the signed manifest (unless -Unsigned)' { + $other = New-Folder 'differ' + $zip = Join-Path $other 'PraRemoteMailbox-9.9.9.zip' + Copy-Item -LiteralPath $script:SbomZip -Destination $zip + $archive = [IO.Compression.ZipFile]::Open($zip, [IO.Compression.ZipArchiveMode]::Update) + try { + $entry = $archive.GetEntry('PraRemoteMailbox-9.9.9/LICENSE') + $stream = $entry.Open(); $stream.SetLength(0); $writer = New-Object IO.StreamWriter($stream); $writer.Write('changed'); $writer.Dispose() + } + finally { $archive.Dispose() } + $run = Invoke-ChildScript -Script $script:Sbom -Argument @('-PackageRoot', $script:SbomPackage, '-ZipPath', $zip, '-RepositoryRoot', $script:Repo, '-OutputDirectory', $other) + $run.ExitCode | Should -Not -Be 0 + $run.Output | Should -Match 'The ZIP and the package folder differ for LICENSE' + $tampered = Join-Path $other 'PraRemoteMailbox-9.9.9' + Copy-Item -LiteralPath $script:SbomPackage -Destination $tampered -Recurse + [IO.File]::AppendAllText((Join-Path $tampered 'LICENSE'), ' ') + $tamperedZip = Join-Path $other 'tampered.zip' + [IO.Compression.ZipFile]::CreateFromDirectory($tampered, $tamperedZip, [IO.Compression.CompressionLevel]::Optimal, $true) + $release = Invoke-ChildScript -Script $script:Sbom -Argument @('-PackageRoot', $tampered, '-ZipPath', $tamperedZip, '-RepositoryRoot', $script:Repo, '-OutputDirectory', (Join-Path $other 'release')) + $release.ExitCode | Should -Not -Be 0 + $release.Output | Should -Match 'does not match the signed manifest: LICENSE' + $unsigned = Invoke-ChildScript -Script $script:Sbom -Argument @('-PackageRoot', $tampered, '-ZipPath', $tamperedZip, '-RepositoryRoot', $script:Repo, '-OutputDirectory', (Join-Path $other 'ci'), '-Unsigned') + $unsigned.ExitCode | Should -Be 0 -Because $unsigned.Output + ([IO.File]::ReadAllText((Join-Path $other 'ci\tampered.zip.spdx.json')) | ConvertFrom-Json).creationInfo.comment | Should -Match 'never a release' + } +} + +Describe 'Release 3.3.0 - comparing a release ZIP with the source committed in git (tool, synthetic repository)' -Tag 'Release330a' { + BeforeAll { + $script:Compare = Join-Path $script:Repo 'tools\Compare-ReleaseSource.ps1' + $script:GitRoot = New-Folder 'git' + function script:Invoke-TestGit([string[]]$Argument) { + $output = & git -C $script:GitRoot -c user.name=gate -c user.email=gate@gate.invalid -c commit.gpgsign=false -c core.autocrlf=false -c core.safecrlf=false @Argument 2>&1 + if ($LASTEXITCODE -ne 0) { throw "git $($Argument -join ' ') failed: $output" } + $output + } + $config = @" +@{ + Environment = 'LAB1' + DomainController = 'dc01.contoso.invalid' + Scope = @{ + SearchBase = 'OU=Tests,DC=contoso,DC=invalid' + GroupDN = 'CN=Scope,DC=contoso,DC=invalid' + CsvPath = 'targets.csv' + } + Routing = @{ + RoutingDomain = 'contoso.mail.onmicrosoft.com' + } + Licensing = @{ + GroupDN = 'CN=License,DC=contoso,DC=invalid' + } + EntraConnect = @{ + Server = 'sync01.contoso.invalid' + } + SharedMailbox = @{ + CsvPath = 'shared.csv' + ExcludeTrusteeSamAccountNames = @('Administrator', 'svc-sync') + } + Cloud = @{ + TenantId = '00000000-0000-0000-0000-000000000001' + Organization = 'contoso.onmicrosoft.com' + AppId = '00000000-0000-0000-0000-000000000002' + CertificateThumbprint = 'AABBCCDDEEFF00112233445566778899AABBCCDD' + UserPrincipalName = 'admin@contoso.invalid' + } + Storage = @{ + CertificateThumbprint = 'AABBCCDDEEFF00112233445566778899AABBCCDD' + } +} +"@ + $script:ExpectedConfig = $config.Replace("'LAB1'", "'PROD'").Replace("'dc01.contoso.invalid'", "''").Replace("'OU=Tests,DC=contoso,DC=invalid'", "''").Replace("'CN=Scope,DC=contoso,DC=invalid'", "''").Replace("'targets.csv'", "''").Replace("'contoso.mail.onmicrosoft.com'", "''").Replace("'CN=License,DC=contoso,DC=invalid'", "''").Replace("'sync01.contoso.invalid'", "''").Replace("'shared.csv'", "''").Replace("@('Administrator', 'svc-sync')", "@('Administrator')").Replace("'00000000-0000-0000-0000-000000000001'", "''").Replace("'contoso.onmicrosoft.com'", "''").Replace("'00000000-0000-0000-0000-000000000002'", "''").Replace("'AABBCCDDEEFF00112233445566778899AABBCCDD'", "''").Replace("'admin@contoso.invalid'", "''") + $files = [ordered]@{ + 'package/module/PRA.Common.psm1' = [Text.Encoding]::UTF8.GetBytes("`$script:ToolVersion = '9.9.9'`r`nfunction x { }`r`n") + 'package/README.md' = [Text.Encoding]::UTF8.GetBytes("# readme`r`nline two`r`n") + 'package/docs/images/a.png' = [byte[]](137, 80, 78, 71, 13, 10, 26, 10, 0, 1, 2, 3) + 'package/config/PraRemoteMailbox.config.psd1' = (New-Object Text.UTF8Encoding($true)).GetPreamble() + [Text.Encoding]::UTF8.GetBytes($config.Replace("`r`n", "`n")) + 'CHANGELOG.md' = [Text.Encoding]::UTF8.GetBytes("# changes`r`n") + 'tests/ignored.ps1' = [Text.Encoding]::UTF8.GetBytes("x`r`n") + } + foreach ($path in $files.Keys) { + $full = Join-Path $script:GitRoot $path + $null = New-Item -ItemType Directory -Path (Split-Path $full -Parent) -Force + [IO.File]::WriteAllBytes($full, [byte[]]$files[$path]) + } + [IO.File]::WriteAllText((Join-Path $script:GitRoot '.gitattributes'), "* text=auto eol=lf`n", $script:Utf8) + Invoke-TestGit @('init', '-q', '-b', 'main') | Out-Null + Invoke-TestGit @('add', '-A') | Out-Null + Invoke-TestGit @('commit', '-q', '-m', 'synthetic') | Out-Null + Invoke-TestGit @('tag', 'v9.9.9') | Out-Null + # The files of the ZIP are the committed blobs, not the working tree: a text file is taken from the object database. + function script:New-ReleaseZip([string]$Path, [hashtable]$Replace = @{}, [string[]]$Skip = @(), [hashtable]$Add = @{}, [string]$Top = 'PraRemoteMailbox-9.9.9') { + $content = [ordered]@{} + foreach ($spec in @(@('module/PRA.Common.psm1', 'package/module/PRA.Common.psm1'), @('README.md', 'package/README.md'), @('docs/images/a.png', 'package/docs/images/a.png'), @('CHANGELOG.md', 'CHANGELOG.md'))) { + $oid = (Invoke-TestGit @('rev-parse', ('v9.9.9:' + $spec[1]))).Trim() + $info = New-Object Diagnostics.ProcessStartInfo 'git' + foreach ($item in @('-C', $script:GitRoot, 'cat-file', 'blob', $oid)) { $info.ArgumentList.Add($item) } + $info.RedirectStandardOutput = $true; $info.UseShellExecute = $false + $process = [Diagnostics.Process]::Start($info); $memory = New-Object IO.MemoryStream; $process.StandardOutput.BaseStream.CopyTo($memory); $process.WaitForExit(); $process.Dispose() + $content[$spec[0]] = $memory.ToArray() + } + $content['config/PraRemoteMailbox.config.psd1'] = (New-Object Text.UTF8Encoding($true)).GetPreamble() + [Text.Encoding]::UTF8.GetBytes($script:ExpectedConfig.Replace("`r`n", "`n")) + foreach ($key in $Replace.Keys) { $content[$key] = [byte[]]$Replace[$key] } + foreach ($key in $Skip) { $content.Remove($key) } + foreach ($key in $Add.Keys) { $content[$key] = [byte[]]$Add[$key] } + $stream = [IO.File]::Open($Path, [IO.FileMode]::CreateNew) + $archive = New-Object IO.Compression.ZipArchive($stream, [IO.Compression.ZipArchiveMode]::Create) + try { + foreach ($key in $content.Keys) { + $entry = $archive.CreateEntry($(if ($key.StartsWith('RAW:')) { $key.Substring(4) } else { $Top + '/' + $key })) + $writer = $entry.Open(); $bytes = [byte[]]$content[$key]; $writer.Write($bytes, 0, $bytes.Length); $writer.Dispose() + } + } + finally { $archive.Dispose(); $stream.Dispose() } + } + function script:Invoke-Compare([string]$Zip, [string]$Commit = 'v9.9.9', [string[]]$Extra = @()) { + Invoke-ChildScript -Script $script:Compare -Argument (@('-ZipPath', $Zip, '-Commit', $Commit, '-RepositoryPath', $script:GitRoot) + $Extra) + } + } + It 'says REPRODUCIBLE when every file of the ZIP has the committed bytes, the configuration has its environment values emptied, and the line endings are those of the blobs' { + $zip = Join-Path (New-Folder 'z') 'PraRemoteMailbox-9.9.9.zip' + New-ReleaseZip $zip + $run = Invoke-Compare $zip + $run.ExitCode | Should -Be 0 -Because $run.Output + $run.Output | Should -Match 'RESULT: REPRODUCIBLE' + $run.Output | Should -Match '5 in the ZIP, 5 identical' + $run.Output | Should -Match 'Not proven : .*built' + $report = Join-Path (Split-Path $zip -Parent) 'report.json' + $json = Invoke-Compare $zip 'main' @('-OutputPath', $report) + $json.ExitCode | Should -Be 0 -Because $json.Output + $data = [IO.File]::ReadAllText($report) | ConvertFrom-Json + $data.Reproducible | Should -BeTrue + $data.Commit | Should -Match '\A[0-9a-f]{40}\z' + $data.ZipSha256 | Should -BeExactly (Get-Sha256Hex $zip).ToLowerInvariant() + (Invoke-Compare $zip 'main' @('-OutputPath', $report)).ExitCode | Should -Be 2 + } + It 'says DIFFERENT, and names the file, for a changed byte, a file that is not committed, a configuration that was not emptied, a path that climbs out, another top folder and a duplicate' -ForEach @( + @{ Case = 'changed byte'; Match = 'README\.md: Different' } + @{ Case = 'file not committed'; Match = 'extra\.txt: NotInCommit' } + @{ Case = 'configuration kept'; Match = 'PraRemoteMailbox\.config\.psd1: Different' } + @{ Case = 'climbing path'; Match = 'Refused' } + @{ Case = 'top folder'; Match = 'top folder of the ZIP is' } + @{ Case = 'duplicate'; Match = 'duplicate entry' } + @{ Case = 'committed file missing'; Match = 'README\.md: MissingFromZip' } + @{ Case = 'committed configuration missing'; Match = 'PraRemoteMailbox\.config\.psd1: MissingFromZip' } + ) { + $zip = Join-Path (New-Folder 'z') 'PraRemoteMailbox-9.9.9.zip' + switch ($Case) { + 'changed byte' { New-ReleaseZip $zip -Replace @{ 'README.md' = [Text.Encoding]::UTF8.GetBytes("# readme`r`nline twO`r`n") } } + 'file not committed' { New-ReleaseZip $zip -Add @{ 'extra.txt' = [byte[]](1, 2, 3) } } + 'configuration kept' { New-ReleaseZip $zip -Replace @{ 'config/PraRemoteMailbox.config.psd1' = [Text.Encoding]::UTF8.GetBytes('@{ Environment = ''LAB1'' }') } } + 'climbing path' { New-ReleaseZip $zip -Add @{ 'RAW:PraRemoteMailbox-9.9.9/../evil.ps1' = [byte[]](1) } } + 'top folder' { New-ReleaseZip $zip -Top 'PraRemoteMailbox-9.9.8' } + 'duplicate' { New-ReleaseZip $zip -Add @{ 'RAW:PraRemoteMailbox-9.9.9/README.md' = [Text.Encoding]::UTF8.GetBytes('x') } } + 'committed file missing' { New-ReleaseZip $zip -Skip @('README.md') } + 'committed configuration missing' { New-ReleaseZip $zip -Skip @('config/PraRemoteMailbox.config.psd1') } + } + $run = Invoke-Compare $zip + $run.ExitCode | Should -Be 1 -Because $run.Output + $run.Output | Should -Match 'RESULT: DIFFERENT' + $run.Output | Should -Match $Match + } + It 'does not compare, and says why, for a missing ZIP, an unknown commit, a commit that is not a plain name, and a ZIP that is not a ZIP' { + $folder = New-Folder 'z' + $zip = Join-Path $folder 'PraRemoteMailbox-9.9.9.zip' + New-ReleaseZip $zip + (Invoke-Compare (Join-Path $folder 'missing.zip')).Output | Should -Match 'NOT COMPARED - The ZIP does not exist' + (Invoke-Compare $zip 'v0.0.0').ExitCode | Should -Be 2 + $injection = Invoke-Compare $zip '--output=x' + $injection.ExitCode | Should -Be 2 + $injection.Output | Should -Match 'must be a commit id, a tag or a branch name' + $notZip = Join-Path $folder 'not.zip' + [IO.File]::WriteAllText($notZip, 'not a zip', $script:Utf8) + (Invoke-Compare $notZip).ExitCode | Should -Be 2 + } + It 'applies to the configuration the same changes as the package builder: the same keys, the same counts, the same two other rules' { + $builder = Read-RepoText 'tools\New-PraPackage.ps1' + $tool = Read-RepoText 'tools\Compare-ReleaseSource.ps1' + $pattern = "@\{ Key\s*=\s*'(\w+)';\s*Count\s*=\s*(\d+) \}" + $fromBuilder = @([regex]::Matches($builder, $pattern) | ForEach-Object { $_.Groups[1].Value + '=' + $_.Groups[2].Value }) + $fromTool = @([regex]::Matches($tool, $pattern) | ForEach-Object { $_.Groups[1].Value + '=' + $_.Groups[2].Value }) + $fromBuilder.Count | Should -Be 11 + ($fromTool -join ',') | Should -BeExactly ($fromBuilder -join ',') + foreach ($rule in @("(?m)^(\s*Environment\s*=\s*)'[^']*'", "(?m)^(\s*ExcludeTrusteeSamAccountNames\s*=\s*)@\([^)]*\)")) { + $builder.Contains($rule) | Should -BeTrue -Because $rule + $tool.Contains($rule) | Should -BeTrue -Because $rule + } + } +} + +Describe 'Release 3.3.0 - the new repository scripts follow the repository conventions (repository files)' -Tag 'Release330a' { + It 'parse, start with a byte order mark, use line feeds, and carry no comment about a fix or a version' -ForEach @( + @{ Relative = '.github\scripts\Install-PowerShell.ps1' }, @{ Relative = '.github\scripts\Initialize-CIModules.ps1' }, @{ Relative = '.github\scripts\Invoke-DependencyWatch.ps1' } + @{ Relative = 'tools\New-Sbom.ps1' }, @{ Relative = 'tools\Compare-ReleaseSource.ps1' } + ) { + $path = Join-Path $script:Repo $Relative + $bytes = [IO.File]::ReadAllBytes($path) + ($bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF) | Should -BeTrue + [Array]::IndexOf($bytes, [byte]13) | Should -Be -1 + $errors = $null; $tokens = $null + $null = [Management.Automation.Language.Parser]::ParseFile($path, [ref]$tokens, [ref]$errors) + $errors.Count | Should -Be 0 + $comments = @($tokens | Where-Object Kind -eq 'Comment' | ForEach-Object Text) -join "`n" + $comments | Should -Not -Match '(?i)\b(bug|fixed|previously|3\.3\.0)\b' + } +} diff --git a/tests/ReportFixture.ps1 b/tests/ReportFixture.ps1 index ca9689a..5ddbd5c 100644 --- a/tests/ReportFixture.ps1 +++ b/tests/ReportFixture.ps1 @@ -1,4 +1,4 @@ -#Requires -Version 7.5 +#Requires -Version 7.6 <# .SYNOPSIS Synthetic report-only data for the HTML report tests (dot-sourced by tests\PraReport.Tests.ps1). diff --git a/tools/Build-Documentation.ps1 b/tools/Build-Documentation.ps1 index 4cbbd0e..b746037 100644 --- a/tools/Build-Documentation.ps1 +++ b/tools/Build-Documentation.ps1 @@ -1,4 +1,4 @@ -#Requires -Version 7.5 +#Requires -Version 7.6 <# .SYNOPSIS Builds package\docs\PraRemoteMailbox-Guide.html from package\docs\PraRemoteMailbox-Guide.md. @@ -27,7 +27,7 @@ .NOTES Author : Nicolas Fabert - Version : 3.2.0 (from the Purview DLP Report builder) + Version : 3.3.0 (from the Purview DLP Report builder) PowerShell pitfall: never name a variable $matches — every -match overwrites the automatic $Matches, and variable names are case-insensitive. #> diff --git a/tools/Compare-ReleaseSource.ps1 b/tools/Compare-ReleaseSource.ps1 new file mode 100644 index 0000000..3d7d134 --- /dev/null +++ b/tools/Compare-ReleaseSource.ps1 @@ -0,0 +1,206 @@ +#Requires -Version 7.6 +<# +.SYNOPSIS + Compares a release ZIP with the source tree committed in git, byte for byte, and states what that proves. + +.DESCRIPTION + For every file of the ZIP the script reads the file committed at -Commit (package\, and CHANGELOG.md of the repository root) straight from the git object + database, without a checkout and without any line-ending conversion, and compares the bytes. The configuration file is the one file that the package builder + changes: its environment values are emptied, so it is compared with the committed file after the same changes. Nothing from the ZIP or from the commit is executed. + + Result REPRODUCIBLE: the ZIP holds exactly the files that the package builder takes from that commit, and every one has the committed bytes. + What it proves: the content of the ZIP is the committed source. What it does not prove: the machine or the build environment that made the ZIP, the bytes of the + ZIP container itself (entry order, time stamps, compression), or that the commit is the one that was reviewed. Compare the commit with the tag and the merged pull request. + + The ZIP has one top folder named PraRemoteMailbox-, the version being the one of the commit. + +.PARAMETER ZipPath + The release ZIP. +.PARAMETER Commit + The commit, tag or branch of the repository to compare with. Default: HEAD. +.PARAMETER RepositoryPath + The git repository. Default: the parent of this script's folder. +.PARAMETER OutputPath + Optional JSON report (never overwritten). + +.NOTES + Exit code 0: reproducible. 1: the ZIP differs from the commit. 2: the comparison could not be made. + Author : Nicolas Fabert +#> +[CmdletBinding()] +param( + [Parameter(Mandatory)][string]$ZipPath, + [string]$Commit = 'HEAD', + [string]$RepositoryPath, + [string]$OutputPath +) +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' +Add-Type -AssemblyName System.IO.Compression +Add-Type -AssemblyName System.IO.Compression.FileSystem + +$maximumEntryBytes = 512MB +$maximumTotalBytes = 2GB +# The keys the package builder empties in the configuration file, with the number of times each one appears (tools\New-PraPackage.ps1). +$emptiedKeys = @( + @{ Key = 'DomainController'; Count = 1 }, @{ Key = 'SearchBase'; Count = 1 }, @{ Key = 'GroupDN'; Count = 2 }, @{ Key = 'CsvPath'; Count = 2 }, + @{ Key = 'RoutingDomain'; Count = 1 }, @{ Key = 'Server'; Count = 1 }, @{ Key = 'TenantId'; Count = 1 }, @{ Key = 'Organization'; Count = 1 }, + @{ Key = 'AppId'; Count = 1 }, @{ Key = 'CertificateThumbprint'; Count = 2 }, @{ Key = 'UserPrincipalName'; Count = 1 } +) +$configurationPath = 'config/PraRemoteMailbox.config.psd1' + +function Invoke-Git { + param([Parameter(Mandatory)][string[]]$Argument, [switch]$Binary) + $info = [Diagnostics.ProcessStartInfo]::new('git') + $info.ArgumentList.Add('-C'); $info.ArgumentList.Add($script:Repository) + foreach ($item in $Argument) { $info.ArgumentList.Add($item) } + $info.RedirectStandardOutput = $true; $info.RedirectStandardError = $true; $info.UseShellExecute = $false; $info.CreateNoWindow = $true + $process = [Diagnostics.Process]::Start($info) + try { + $memory = [IO.MemoryStream]::new() + $errorTask = $process.StandardError.ReadToEndAsync() + $process.StandardOutput.BaseStream.CopyTo($memory) + $process.WaitForExit() + if ($process.ExitCode -ne 0) { throw ('git {0} failed: {1}' -f ($Argument -join ' '), $errorTask.GetAwaiter().GetResult().Trim()) } + if ($Binary) { , $memory.ToArray() } else { [Text.Encoding]::UTF8.GetString($memory.ToArray()) } + } + finally { $process.Dispose() } +} + +function Get-Sha256Text { + param([Parameter(Mandatory)][byte[]]$Bytes) + [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData($Bytes)).ToLowerInvariant() +} + +function ConvertTo-PackagedConfiguration { + <# The committed configuration as the package builder writes it: the environment values emptied, UTF-8 with a byte order mark. #> + param([Parameter(Mandatory)][byte[]]$Bytes) + $skip = if ($Bytes.Length -ge 3 -and $Bytes[0] -eq 0xEF -and $Bytes[1] -eq 0xBB -and $Bytes[2] -eq 0xBF) { 3 } else { 0 } + $text = [Text.UTF8Encoding]::new($false).GetString($Bytes, $skip, $Bytes.Length - $skip) + foreach ($item in $emptiedKeys) { + $pattern = "(?m)^(\s*$($item.Key)\s*=\s*)'([^']*)'" + if ([regex]::Matches($text, $pattern).Count -ne $item.Count) { throw "The key $($item.Key) must appear $($item.Count) time(s) in the committed configuration." } + $text = [regex]::Replace($text, $pattern, '$1''''') + } + $text = [regex]::Replace($text, "(?m)^(\s*Environment\s*=\s*)'[^']*'", '$1''PROD''') + $text = [regex]::Replace($text, "(?m)^(\s*ExcludeTrusteeSamAccountNames\s*=\s*)@\([^)]*\)", '$1@(''Administrator'')') + $encoding = [Text.UTF8Encoding]::new($true) + $preamble = $encoding.GetPreamble() + $body = $encoding.GetBytes($text) + $result = [byte[]]::new($preamble.Length + $body.Length) + [Array]::Copy($preamble, 0, $result, 0, $preamble.Length) + [Array]::Copy($body, 0, $result, $preamble.Length, $body.Length) + , $result +} + +$exitCode = 2 +try { + if ($Commit -notmatch '\A[A-Za-z0-9][A-Za-z0-9._/\-]{0,99}\z') { throw 'The commit must be a commit id, a tag or a branch name.' } + if (-not $RepositoryPath) { $RepositoryPath = Join-Path $PSScriptRoot '..' } + $script:Repository = [IO.Path]::GetFullPath($RepositoryPath) + $ZipPath = [IO.Path]::GetFullPath($ZipPath) + if (-not (Test-Path -LiteralPath $ZipPath -PathType Leaf)) { throw "The ZIP does not exist: $ZipPath" } + if ($OutputPath) { + $OutputPath = [IO.Path]::GetFullPath($OutputPath) + if (Test-Path -LiteralPath $OutputPath) { throw "The report already exists and is not overwritten: $OutputPath" } + } + $sha = (Invoke-Git -Argument @('rev-parse', '--verify', '--end-of-options', ($Commit + '^{commit}'))).Trim() + if ($sha -notmatch '\A[0-9a-f]{40}\z') { throw 'git did not return a commit id.' } + + # The committed files that can be in the ZIP: package\ (as the root of the ZIP) and CHANGELOG.md of the repository root. + $listing = Invoke-Git -Argument @('ls-tree', '-r', '-z', '--full-tree', $sha, '--', 'package', 'CHANGELOG.md') + $committed = [Collections.Generic.Dictionary[string, string]]::new([StringComparer]::Ordinal) + foreach ($record in $listing.Split([char]0, [StringSplitOptions]::RemoveEmptyEntries)) { + $match = [regex]::Match($record, '\A(?\d+) (?\w+) (?[0-9a-f]{40})\t(?.+)\z') + if (-not $match.Success -or $match.Groups['type'].Value -ne 'blob' -or $match.Groups['mode'].Value -eq '120000') { continue } + $path = $match.Groups['path'].Value + $relative = if ($path -ceq 'CHANGELOG.md') { 'CHANGELOG.md' } elseif ($path.StartsWith('package/', [StringComparison]::Ordinal)) { $path.Substring(8) } else { continue } + $committed[$relative] = $match.Groups['oid'].Value + } + if (-not $committed.ContainsKey('module/PRA.Common.psm1')) { throw 'The commit has no package\module\PRA.Common.psm1.' } + $commonBytes = Invoke-Git -Argument @('cat-file', 'blob', $committed['module/PRA.Common.psm1']) -Binary + $versionMatch = [regex]::Match([Text.Encoding]::UTF8.GetString($commonBytes), "(?m)^\`$script:ToolVersion\s*=\s*'([0-9]+\.[0-9]+\.[0-9]+)'") + if (-not $versionMatch.Success) { throw 'The tool version was not found in the committed common module.' } + $version = $versionMatch.Groups[1].Value + $expectedTop = 'PraRemoteMailbox-' + $version + + $results = [Collections.Generic.List[object]]::new() + $zipSha256 = (Get-FileHash -LiteralPath $ZipPath -Algorithm SHA256).Hash.ToLowerInvariant() + $seen = [Collections.Generic.HashSet[string]]::new([StringComparer]::Ordinal) + $total = [long]0 + $tops = [Collections.Generic.HashSet[string]]::new([StringComparer]::Ordinal) + $archive = [IO.Compression.ZipFile]::OpenRead($ZipPath) + try { + foreach ($entry in $archive.Entries) { + if ($entry.FullName.EndsWith('/', [StringComparison]::Ordinal)) { continue } + $slash = $entry.FullName.IndexOf('/') + if ($slash -lt 1) { $results.Add([pscustomobject]@{ Path = $entry.FullName; Status = 'Refused'; Detail = 'outside the top folder' }); continue } + [void]$tops.Add($entry.FullName.Substring(0, $slash)) + $relative = $entry.FullName.Substring($slash + 1) + if ($relative.Length -eq 0 -or $relative.Contains('\') -or @($relative.Split('/') | Where-Object { $_ -in '', '.', '..' }).Count -gt 0) { + $results.Add([pscustomobject]@{ Path = $entry.FullName; Status = 'Refused'; Detail = 'the entry name is not a plain relative path' }); continue + } + if (-not $seen.Add($relative)) { $results.Add([pscustomobject]@{ Path = $relative; Status = 'Refused'; Detail = 'duplicate entry' }); continue } + if ($entry.Length -gt $maximumEntryBytes -or ($total + $entry.Length) -gt $maximumTotalBytes) { throw "The ZIP is larger than this tool accepts: $($entry.FullName)" } + $total += $entry.Length + $stream = $entry.Open() + try { + $memory = [IO.MemoryStream]::new() + $buffer = [byte[]]::new(65536) + while (($read = $stream.Read($buffer, 0, $buffer.Length)) -gt 0) { + if ($memory.Length + $read -gt $entry.Length) { throw "A ZIP entry is larger than its declared size: $($entry.FullName)" } + $memory.Write($buffer, 0, $read) + } + $actual = $memory.ToArray() + } + finally { $stream.Dispose() } + if (-not $committed.ContainsKey($relative)) { + $results.Add([pscustomobject]@{ Path = $relative; Status = 'NotInCommit'; Detail = 'the commit has no such file'; ZipSha256 = (Get-Sha256Text $actual) }); continue + } + $expected = Invoke-Git -Argument @('cat-file', 'blob', $committed[$relative]) -Binary + $note = '' + if ($relative -ceq $configurationPath) { $expected = ConvertTo-PackagedConfiguration $expected; $note = 'configuration with its environment values emptied' } + $zipHash = Get-Sha256Text $actual + $expectedHash = Get-Sha256Text $expected + $results.Add([pscustomobject]@{ + Path = $relative; Status = $(if ($zipHash -ceq $expectedHash) { 'Identical' } else { 'Different' }); Detail = $note + ZipSha256 = $zipHash; ExpectedSha256 = $expectedHash + }) + } + } + finally { $archive.Dispose() } + if ($results.Count -eq 0) { throw 'The ZIP holds no file.' } + $problems = [Collections.Generic.List[string]]::new() + $topNames = [string[]]@($tops) + [Array]::Sort($topNames, [StringComparer]::Ordinal) + if ($tops.Count -ne 1 -or -not $tops.Contains($expectedTop)) { $problems.Add(('The top folder of the ZIP is {0}; {1} is expected for the version of the commit.' -f ($topNames -join ', '), $expectedTop)) } + foreach ($row in @($results | Where-Object Status -ne 'Identical')) { $problems.Add(('{0}: {1}{2}' -f $row.Path, $row.Status, $(if ($row.Detail) { ' (' + $row.Detail + ')' } else { '' }))) } + $notShipped = [string[]]@($committed.Keys | Where-Object { -not $seen.Contains($_) }) + [Array]::Sort($notShipped, [StringComparer]::Ordinal) + foreach ($missing in $notShipped) { $problems.Add(('{0}: MissingFromZip (committed at that commit, not in the ZIP)' -f $missing)) } + + $report = [ordered]@{ + Zip = [IO.Path]::GetFileName($ZipPath); ZipSha256 = $zipSha256; Commit = $sha; Version = $version; TopFolder = $expectedTop + Files = $results.Count; Identical = @($results | Where-Object Status -eq 'Identical').Count; Reproducible = ($problems.Count -eq 0) + Problems = $problems.ToArray(); CommittedButNotInZip = $notShipped; Results = $results.ToArray() + Proves = 'The content of the ZIP is the source committed at the commit (the configuration file with its environment values emptied).' + DoesNotProve = 'The machine or environment that built the ZIP; the bytes of the ZIP container (entry order, time stamps, compression); that the commit is the reviewed one.' + } + if ($OutputPath) { [IO.File]::WriteAllText($OutputPath, ((ConvertTo-Json -InputObject $report -Depth 6) -replace "`r?`n", "`n") + "`n", [Text.UTF8Encoding]::new($false)) } + Write-Output ('ZIP : {0} (SHA-256 {1})' -f $report.Zip, $zipSha256) + Write-Output ('Commit : {0} (version {1})' -f $sha, $version) + Write-Output ('Files : {0} in the ZIP, {1} identical to the commit, {2} committed under package\ (or CHANGELOG.md) and not in the ZIP' -f $report.Files, $report.Identical, $notShipped.Count) + foreach ($problem in $problems) { Write-Output ('Difference : ' + $problem) } + if ($problems.Count -eq 0) { + Write-Output 'RESULT: REPRODUCIBLE - the ZIP holds every committed package file and each has the bytes committed at that commit.' + Write-Output ('Proves : ' + $report.Proves) + Write-Output ('Not proven : ' + $report.DoesNotProve) + $exitCode = 0 + } + else { Write-Output 'RESULT: DIFFERENT - the ZIP is not the source committed at that commit.'; $exitCode = 1 } +} +catch { + Write-Output ('RESULT: NOT COMPARED - ' + $_.Exception.Message) + $exitCode = 2 +} +exit $exitCode diff --git a/tools/DocumentationImages/New-PackageCopy.ps1 b/tools/DocumentationImages/New-PackageCopy.ps1 index e9c007b..3cb372d 100644 --- a/tools/DocumentationImages/New-PackageCopy.ps1 +++ b/tools/DocumentationImages/New-PackageCopy.ps1 @@ -7,7 +7,7 @@ the real file when it exists, an empty placeholder otherwise. Dot-source this file, then call New-DocumentationPackageCopy. .NOTES Author : Nicolas Fabert - Version : 3.2.0 + Version : 3.3.0 Part of : PRA Remote Mailbox (repository tool, not in the package) #> function New-DocumentationPackageCopy { diff --git a/tools/DocumentationImages/Show-ConsoleScreens.ps1 b/tools/DocumentationImages/Show-ConsoleScreens.ps1 index aff7017..4fcebaa 100644 --- a/tools/DocumentationImages/Show-ConsoleScreens.ps1 +++ b/tools/DocumentationImages/Show-ConsoleScreens.ps1 @@ -2,7 +2,7 @@ .SYNOPSIS Photographs the real PRA Remote Mailbox window against a synthetic runtime, for the documentation (repository tool, never shipped). .DESCRIPTION - Called by tools\New-DocumentationImages.ps1, once per scenario and theme, in its own PowerShell 7.5+ STA process. + Called by tools\New-DocumentationImages.ps1, once per scenario and theme, in its own PowerShell 7.6 STA process. It builds the real window (package\module\PRA.Gui.psm1) in a copy of the package whose signature check is substituted (tests\IntegrityFixture.ps1), with the synthetic engine StubEngine.ps1 instead of the real one, then drives the five pages like an operator and renders them to PNG. Callouts (a red frame and a number) mark what the operator must click. @@ -27,10 +27,10 @@ Root of the repository (default: two folders above this script). .NOTES Author : Nicolas Fabert - Version : 3.2.0 + Version : 3.3.0 Part of : PRA Remote Mailbox (repository tool, not in the package) #> -#Requires -Version 7.5 +#Requires -Version 7.6 param( [Parameter(Mandatory)][string]$Shots, [ValidateSet('Light', 'Dark')][string]$Theme = 'Light', @@ -151,7 +151,7 @@ try { $syntheticRoot = 'D:\PRA\PraRemoteMailbox' function Walk($element, [scriptblock]$visit) { & $visit $element; $n = [Windows.Media.VisualTreeHelper]::GetChildrenCount($element); for ($i = 0; $i -lt $n; $i++) { Walk ([Windows.Media.VisualTreeHelper]::GetChild($element, $i)) $visit } } function Mask($text) { if (-not $text) { return $text }; ([string]$text).Replace((Join-Path $root 'Backups'), 'D:\PRA\Backups').Replace($root, $syntheticRoot) } - $leak = (@($real | ForEach-Object { [regex]::Escape($_) }) + @('REDMOND', 'DESKTOP-', 'C:\\Users', '\\AppData\\', 'scratchpad', 'Temp\\claude')) -join '|' + $leak = (@($real | ForEach-Object { [regex]::Escape($_) }) + @([regex]::Escape([IO.Path]::GetTempPath().TrimEnd('\')), 'DESKTOP-', 'C:\\Users', '\\AppData\\')) -join '|' $null = New-Item -ItemType Directory -Path $Shots -Force $theme = $Theme.ToLowerInvariant() function Get-Bounds($name) { diff --git a/tools/DocumentationImages/StubEngine.ps1 b/tools/DocumentationImages/StubEngine.ps1 index 5a5aa17..7d77aa8 100644 --- a/tools/DocumentationImages/StubEngine.ps1 +++ b/tools/DocumentationImages/StubEngine.ps1 @@ -9,7 +9,7 @@ Nothing here reads Active Directory, Exchange Online, Microsoft Graph or Entra Connect. .NOTES Author : Nicolas Fabert - Version : 3.2.0 + Version : 3.3.0 Part of : PRA Remote Mailbox (repository tool, not in the package) #> param($Action, $Mode, $ConfigPath, $Scope, $Phase, $Identity, $MaxObjects, $SearchBase, $CsvPath, $Batch, $BaseConfigPath, $Expect, [switch]$Once, [switch]$Force) diff --git a/tools/DocumentationImages/StubPackageCheck.ps1 b/tools/DocumentationImages/StubPackageCheck.ps1 index 98566c2..12851c9 100644 --- a/tools/DocumentationImages/StubPackageCheck.ps1 +++ b/tools/DocumentationImages/StubPackageCheck.ps1 @@ -8,7 +8,7 @@ nothing else (no directory read). .NOTES Author : Nicolas Fabert - Version : 3.2.0 + Version : 3.3.0 Part of : PRA Remote Mailbox (repository tool, not in the package) #> param([string]$ConfigPath, [string]$ResultPath, [string]$Identity = '', [string]$PackagePath = '', [string]$Environment = '', [string]$BackupFolder = '', [switch]$Import) diff --git a/tools/Measure-PraScale.ps1 b/tools/Measure-PraScale.ps1 index 0c98508..93f8520 100644 --- a/tools/Measure-PraScale.ps1 +++ b/tools/Measure-PraScale.ps1 @@ -27,9 +27,9 @@ pwsh -NoProfile -File .\tools\Measure-PraScale.ps1 -Count 5000 .NOTES Author : Nicolas Fabert - Version : 3.2.0 + Version : 3.3.0 #> -#Requires -Version 7.5 +#Requires -Version 7.6 [CmdletBinding()] param( [ValidateRange(10, 50000)][int]$Count = 5000, diff --git a/tools/New-DocumentationImages.ps1 b/tools/New-DocumentationImages.ps1 index 7fdf4ca..f779469 100644 --- a/tools/New-DocumentationImages.ps1 +++ b/tools/New-DocumentationImages.ps1 @@ -30,10 +30,10 @@ .NOTES Author : Nicolas Fabert - Version : 3.2.0 - Part of : PRA Remote Mailbox (repository tool, not in the package). Needs PowerShell 7.5+, Microsoft Edge, Windows (WPF). + Version : 3.3.0 + Part of : PRA Remote Mailbox (repository tool, not in the package). Needs PowerShell 7.6, Microsoft Edge, Windows (WPF). #> -#Requires -Version 7.5 +#Requires -Version 7.6 [CmdletBinding()] param( [string]$OutputFolder, @@ -225,7 +225,9 @@ if ($all -or $Part -eq 'Reports') { # Measure the page, then photograph it at its own height. $page = Join-Path $work "$name.html" $source = [IO.File]::ReadAllText($pages[$name]) - $probe = "" + # The measuring script below is not one of the scripts that the page's own Content-Security-Policy names: this copy is made without the policy meta. + $source = [regex]::Replace($source, ']*>', '') + $probe ="" $index = $source.LastIndexOf('') $source = $source.Substring(0, $index) + $probe + $source.Substring($index + 7) [IO.File]::WriteAllText($page, $source, [Text.UTF8Encoding]::new($true)) diff --git a/tools/New-PraPackage.ps1 b/tools/New-PraPackage.ps1 index 4a086d7..f30a6e0 100644 --- a/tools/New-PraPackage.ps1 +++ b/tools/New-PraPackage.ps1 @@ -1,4 +1,4 @@ -#Requires -Version 7.5 +#Requires -Version 7.6 <# .SYNOPSIS Copies the files needed to run PRA Remote Mailbox into a separate folder, ready to be zipped. @@ -32,11 +32,11 @@ .EXAMPLE .\tools\New-PraPackage.ps1 - Creates ..\package\PraRemoteMailbox-3.2.0. + Creates ..\package\PraRemoteMailbox-3.3.0. .NOTES Author : Nicolas Fabert - Version : 3.2.0 + Version : 3.3.0 #> [CmdletBinding()] param( @@ -118,7 +118,7 @@ $emptied = New-Object 'Collections.Generic.List[string]' $keys = @( @{ Key='DomainController'; Count=1 }, @{ Key='SearchBase'; Count=1 }, @{ Key='GroupDN'; Count=2 }, @{ Key='CsvPath'; Count=2 }, @{ Key='RoutingDomain'; Count=1 }, @{ Key='Server'; Count=1 }, @{ Key='TenantId'; Count=1 }, @{ Key='Organization'; Count=1 }, - @{ Key='AppId'; Count=1 }, @{ Key='CertificateThumbprint'; Count=1 }, @{ Key='UserPrincipalName'; Count=1 } + @{ Key='AppId'; Count=1 }, @{ Key='CertificateThumbprint'; Count=2 }, @{ Key='UserPrincipalName'; Count=1 } ) foreach ($item in $keys) { $pattern = "(?m)^(\s*$($item.Key)\s*=\s*)'([^']*)'" diff --git a/tools/New-ReadmeImages.ps1 b/tools/New-ReadmeImages.ps1 index 285108a..9cf59e5 100644 --- a/tools/New-ReadmeImages.ps1 +++ b/tools/New-ReadmeImages.ps1 @@ -1,4 +1,4 @@ -#Requires -Version 7.5 +#Requires -Version 7.6 <# .SYNOPSIS Renders the README banner in light and dark themes using the existing guide assets. @@ -64,7 +64,7 @@ body { display: block; margin: 0; padding: 0; } '@ $badges = @( "Version $version" - "$(Get-ReadmeIcon 'terminal' 'icon-sm')PowerShell 7.5+" + "$(Get-ReadmeIcon 'terminal' 'icon-sm')PowerShell 7.6" "$(Get-ReadmeIcon 'shield' 'icon-sm')Backup before every change" "$(Get-ReadmeIcon 'tag' 'icon-sm')MIT license" ) -join '' diff --git a/tools/New-Sbom.ps1 b/tools/New-Sbom.ps1 new file mode 100644 index 0000000..7e914cc --- /dev/null +++ b/tools/New-Sbom.ps1 @@ -0,0 +1,283 @@ +#Requires -Version 7.6 +<# +.SYNOPSIS + Writes the SPDX 2.3 (JSON) software bill of materials and the dependency declaration of a release ZIP, next to the ZIP. + +.DESCRIPTION + Run it at packaging time, on the finished package folder and on the ZIP built from it. It lists what the ZIP ships (the application and every file + with its SHA-256), the modules and the PowerShell version that the package requires and does not bundle, and the components that build and test it. + No third-party code or binary is shipped in the ZIP; the statement is written into both files. + + The ZIP and the package folder must hold the same files byte for byte, or the script stops. Release build: every file that the signed manifest + PackageIntegrity.psd1 lists must equal its entry there. -Unsigned (continuous integration): the committed manifest is not authoritative and is not compared. + The required versions are read as text from the package itself, the build-side pins from .github\ci-pins.json and the workflows of the repository. + + Two files are written, never over an existing one: + .spdx.json the bill of materials + -dependencies.md the dependency declaration for people + The paths written are returned. + +.PARAMETER PackageRoot + The finished package folder (the one the ZIP was built from). +.PARAMETER ZipPath + The release ZIP. +.PARAMETER RepositoryRoot + The repository folder that holds .github (pins and workflows). Default: the parent of this script's folder. +.PARAMETER OutputDirectory + Where the two files go. Default: the folder of the ZIP. +.PARAMETER Unsigned + Continuous-integration build: the manifest is not compared with the files. +.PARAMETER Created + The creation time written in the document. Default: now (UTC). + +.EXAMPLE + .\tools\New-Sbom.ps1 -PackageRoot ..\package\PraRemoteMailbox-X.Y.Z -ZipPath ..\package\PraRemoteMailbox-X.Y.Z.zip + +.NOTES + Author : Nicolas Fabert +#> +[CmdletBinding()] +param( + [Parameter(Mandatory)][string]$PackageRoot, + [Parameter(Mandatory)][string]$ZipPath, + [string]$RepositoryRoot, + [string]$OutputDirectory, + [switch]$Unsigned, + [datetime]$Created = [datetime]::UtcNow +) +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' +Add-Type -AssemblyName System.IO.Compression +Add-Type -AssemblyName System.IO.Compression.FileSystem + +if (-not $RepositoryRoot) { $RepositoryRoot = Join-Path $PSScriptRoot '..' } +$PackageRoot = [IO.Path]::GetFullPath($PackageRoot).TrimEnd('\', '/') +$ZipPath = [IO.Path]::GetFullPath($ZipPath) +$RepositoryRoot = [IO.Path]::GetFullPath($RepositoryRoot).TrimEnd('\', '/') +if (-not (Test-Path -LiteralPath $PackageRoot -PathType Container)) { throw "The package folder does not exist: $PackageRoot" } +if (-not (Test-Path -LiteralPath $ZipPath -PathType Leaf)) { throw "The ZIP does not exist: $ZipPath" } +if (-not $OutputDirectory) { $OutputDirectory = [IO.Path]::GetDirectoryName($ZipPath) } +$OutputDirectory = [IO.Path]::GetFullPath($OutputDirectory) +$zipName = [IO.Path]::GetFileName($ZipPath) +$zipBase = [IO.Path]::GetFileNameWithoutExtension($ZipPath) +$sbomPath = Join-Path $OutputDirectory ($zipName + '.spdx.json') +$declarationPath = Join-Path $OutputDirectory ($zipBase + '-dependencies.md') +foreach ($target in @($sbomPath, $declarationPath)) { + if (Test-Path -LiteralPath $target) { throw "The file already exists; existing files are never overwritten: $target" } +} + +function Get-FileDigest { + param([Parameter(Mandatory)][byte[]]$Bytes) + $sha1 = [Security.Cryptography.SHA1]::HashData($Bytes) + $sha256 = [Security.Cryptography.SHA256]::HashData($Bytes) + [pscustomobject]@{ Sha1 = [Convert]::ToHexString($sha1).ToLowerInvariant(); Sha256 = [Convert]::ToHexString($sha256).ToLowerInvariant() } +} + +function ConvertTo-SpdxId { + param([Parameter(Mandatory)][string]$Text) + 'SPDXRef-' + ($Text -replace '[^A-Za-z0-9.\-]', '-') +} + +# The files of the package folder, by relative path (forward slashes). +$folderFiles = [Collections.Generic.SortedDictionary[string, object]]::new([StringComparer]::Ordinal) +foreach ($file in Get-ChildItem -LiteralPath $PackageRoot -Recurse -File -Force) { + if ($file.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw "A reparse point is not accepted in the package folder: $($file.FullName)" } + $relative = $file.FullName.Substring($PackageRoot.Length + 1).Replace('\', '/') + $folderFiles[$relative] = Get-FileDigest -Bytes ([IO.File]::ReadAllBytes($file.FullName)) +} +if ($folderFiles.Count -eq 0) { throw 'The package folder is empty.' } + +# The ZIP holds one top folder; its files must be the files of the package folder, byte for byte. +$archive = [IO.Compression.ZipFile]::OpenRead($ZipPath) +try { + $zipHashes = [Collections.Generic.SortedDictionary[string, string]]::new([StringComparer]::Ordinal) + foreach ($entry in $archive.Entries) { + if ($entry.FullName.EndsWith('/', [StringComparison]::Ordinal)) { continue } + $slash = $entry.FullName.IndexOf('/') + if ($slash -lt 1) { throw "A ZIP entry is outside the top folder: $($entry.FullName)" } + $relative = $entry.FullName.Substring($slash + 1) + if ($relative.Contains('..') -or $relative.Contains('\') -or $zipHashes.ContainsKey($relative)) { throw "A ZIP entry name is not accepted: $($entry.FullName)" } + $stream = $entry.Open() + try { + $memory = [IO.MemoryStream]::new() + $stream.CopyTo($memory) + $zipHashes[$relative] = (Get-FileDigest -Bytes $memory.ToArray()).Sha256 + } + finally { $stream.Dispose() } + } +} +finally { $archive.Dispose() } +if ($zipHashes.Count -ne $folderFiles.Count) { throw "The ZIP holds $($zipHashes.Count) files and the package folder $($folderFiles.Count)." } +foreach ($relative in $folderFiles.Keys) { + if (-not $zipHashes.ContainsKey($relative)) { throw "The ZIP does not hold $relative." } + if ($zipHashes[$relative] -cne $folderFiles[$relative].Sha256) { throw "The ZIP and the package folder differ for $relative." } +} + +# The signed manifest. +$manifestPath = Join-Path $PackageRoot 'PackageIntegrity.psd1' +if (-not (Test-Path -LiteralPath $manifestPath -PathType Leaf)) { throw 'PackageIntegrity.psd1 is missing from the package folder.' } +$manifest = Import-PowerShellDataFile -LiteralPath $manifestPath +if (-not $Unsigned) { + foreach ($entry in @($manifest.Files)) { + $relative = ([string]$entry.Path).Replace('\', '/') + if (-not $folderFiles.ContainsKey($relative)) { throw "The manifest lists a file that is not shipped: $relative" } + if ($folderFiles[$relative].Sha256 -cne ([string]$entry.Sha256).ToLowerInvariant()) { throw "A shipped file does not match the signed manifest: $relative" } + } +} + +# What the package declares, read as text. +$common = [IO.File]::ReadAllText((Join-Path $PackageRoot 'module/PRA.Common.psm1')) +$psd1 = [IO.File]::ReadAllText((Join-Path $PackageRoot 'PraRemoteMailbox.psd1')) +function Get-Declared { + param([Parameter(Mandatory)][string]$Text, [Parameter(Mandatory)][string]$Pattern, [Parameter(Mandatory)][string]$What) + $match = [regex]::Match($Text, $Pattern) + if (-not $match.Success) { throw "$What was not found in the package." } + $match.Groups[1].Value +} +$version = Get-Declared $common "(?m)^\`$script:ToolVersion\s*=\s*'([0-9]+\.[0-9]+\.[0-9]+)'" 'The tool version' +$manifestVersion = Get-Declared $psd1 "(?m)^\s*ModuleVersion\s*=\s*'([0-9.]+)'" 'The module version' +if ($manifestVersion -cne $version) { throw "The module manifest says $manifestVersion and the common module $version." } +$powerShellMinimum = Get-Declared $psd1 "(?m)^\s*PowerShellVersion\s*=\s*'([0-9.]+)'" 'The PowerShell version' +$exoMinimum = Get-Declared $common "(?m)^\`$script:PraMinExoVersion\s*=\s*'([0-9.]+)'" 'The Exchange Online module minimum' +$graphMinimum = Get-Declared $common "(?m)^\`$script:PraMinGraphVersion\s*=\s*'([0-9.]+)'" 'The Microsoft Graph module minimum' +$signer = if ($manifest.ContainsKey('SignerThumbprint')) { [string]$manifest.SignerThumbprint } else { '' } +$zipSha256 = (Get-FileHash -LiteralPath $ZipPath -Algorithm SHA256).Hash.ToLowerInvariant() + +# What builds and tests it. +$pins = Get-Content -LiteralPath (Join-Path $RepositoryRoot '.github/ci-pins.json') -Raw -Encoding UTF8 | ConvertFrom-Json +$actionPins = [Collections.Generic.SortedDictionary[string, object]]::new([StringComparer]::Ordinal) +foreach ($workflow in Get-ChildItem -LiteralPath (Join-Path $RepositoryRoot '.github/workflows') -File | Where-Object { $_.Extension -in '.yml', '.yaml' }) { + foreach ($line in [IO.File]::ReadAllLines($workflow.FullName)) { + $match = [regex]::Match($line, '\buses:\s*(?[A-Za-z0-9_.-]+/[A-Za-z0-9_./-]+)@(?[0-9a-f]{40})\s*#\s*(?v\d+\.\d+\.\d+)') + if (-not $match.Success) { continue } + $name = $match.Groups['name'].Value + $repository = ($name.Split('/') | Select-Object -First 2) -join '/' + $key = '{0}@{1}' -f $repository, $match.Groups['tag'].Value + if (-not $actionPins.ContainsKey($key)) { $actionPins[$key] = [pscustomobject]@{ Repository = $repository; Sha = $match.Groups['sha'].Value; Tag = $match.Groups['tag'].Value } } + } +} + +function New-SpdxPackage { + param( + [Parameter(Mandatory)][string]$Id, [Parameter(Mandatory)][string]$Name, [string]$Version, [string]$Supplier = 'NOASSERTION', + [string]$DownloadLocation = 'NOASSERTION', [string]$Sha256, [string]$License = 'NOASSERTION', [string]$Purl, + [string]$Purpose = 'LIBRARY', [string]$Comment, [switch]$WithFiles, [string]$VerificationCode + ) + $package = [ordered]@{ SPDXID = $Id; name = $Name } + if ($Version) { $package['versionInfo'] = $Version } + $package['supplier'] = $Supplier + $package['downloadLocation'] = $DownloadLocation + $package['filesAnalyzed'] = [bool]$WithFiles + if ($WithFiles) { + $package['packageVerificationCode'] = [ordered]@{ packageVerificationCodeValue = $VerificationCode } + $package['licenseInfoFromFiles'] = @('NOASSERTION') + } + if ($Sha256) { $package['checksums'] = @([ordered]@{ algorithm = 'SHA256'; checksumValue = $Sha256.ToLowerInvariant() }) } + $package['licenseConcluded'] = $License + $package['licenseDeclared'] = $License + $package['copyrightText'] = 'NOASSERTION' + $package['primaryPackagePurpose'] = $Purpose + if ($Purl) { $package['externalRefs'] = @([ordered]@{ referenceCategory = 'PACKAGE-MANAGER'; referenceType = 'purl'; referenceLocator = $Purl }) } + if ($Comment) { $package['comment'] = $Comment } + $package +} + +$packages = [Collections.Generic.List[object]]::new() +$relationships = [Collections.Generic.List[object]]::new() +$files = [Collections.Generic.List[object]]::new() +$rootId = 'SPDXRef-Package-PraRemoteMailbox' +$fileSha1 = [string[]]@($folderFiles.Values | ForEach-Object { $_.Sha1 }) +[Array]::Sort($fileSha1, [StringComparer]::Ordinal) +$verification = [Convert]::ToHexString([Security.Cryptography.SHA1]::HashData([Text.Encoding]::ASCII.GetBytes(($fileSha1 -join '')))).ToLowerInvariant() +$rootComment = 'Release ZIP {0}. The checksum is the ZIP. {1} files, each with its SHA-256 below; no third-party code or binary is shipped.' -f $zipName, $folderFiles.Count +if ($signer) { $rootComment += " Publisher certificate thumbprint $signer." } +$packages.Add((New-SpdxPackage -Id $rootId -Name 'PraRemoteMailbox' -Version $version -Supplier 'Person: Nico77600' ` + -DownloadLocation "https://github.com/Nico77600/PraRemoteMailbox/releases/download/v$version/$zipName" -Sha256 $zipSha256 -License 'MIT' -Purpose 'APPLICATION' ` + -Purl "pkg:github/Nico77600/PraRemoteMailbox@v$version" -WithFiles -VerificationCode $verification ` + -Comment $rootComment)) +$relationships.Add([ordered]@{ spdxElementId = 'SPDXRef-DOCUMENT'; relationshipType = 'DESCRIBES'; relatedSpdxElement = $rootId }) +$index = 0 +foreach ($relative in $folderFiles.Keys) { + $index++ + $fileId = 'SPDXRef-File-{0:D4}' -f $index + $files.Add([ordered]@{ + SPDXID = $fileId; fileName = './' + $relative + checksums = @([ordered]@{ algorithm = 'SHA1'; checksumValue = $folderFiles[$relative].Sha1 }, [ordered]@{ algorithm = 'SHA256'; checksumValue = $folderFiles[$relative].Sha256 }) + licenseConcluded = 'NOASSERTION'; licenseInfoInFiles = @('NOASSERTION'); copyrightText = 'NOASSERTION' + }) + $relationships.Add([ordered]@{ spdxElementId = $rootId; relationshipType = 'CONTAINS'; relatedSpdxElement = $fileId }) +} + +$required = @( + @{ Name = 'PowerShell'; Version = $powerShellMinimum; Supplier = 'Organization: Microsoft Corporation'; Purpose = 'APPLICATION'; Purl = 'pkg:github/PowerShell/PowerShell'; Note = 'PowerShell 7, Core edition, on the administration servers. Not bundled.' } + @{ Name = 'ActiveDirectory'; Version = ''; Supplier = 'Organization: Microsoft Corporation'; Purpose = 'LIBRARY'; Purl = ''; Note = 'RSAT module of Windows on the Active Directory side. A Windows component; not bundled.' } + @{ Name = 'ADSync'; Version = ''; Supplier = 'Organization: Microsoft Corporation'; Purpose = 'LIBRARY'; Purl = ''; Note = 'Module of Microsoft Entra Connect Sync, on the synchronisation server. Not bundled.' } + @{ Name = 'ExchangeOnlineManagement'; Version = $exoMinimum; Supplier = 'Organization: Microsoft Corporation'; Purpose = 'LIBRARY'; Purl = 'pkg:nuget/ExchangeOnlineManagement'; Note = 'Cloud side. Not bundled.' } + @{ Name = 'Microsoft.Graph.Authentication'; Version = $graphMinimum; Supplier = 'Organization: Microsoft Corporation'; Purpose = 'LIBRARY'; Purl = 'pkg:nuget/Microsoft.Graph.Authentication'; Note = 'Cloud side. Not bundled; both Graph modules in one version.' } + @{ Name = 'Microsoft.Graph.Users'; Version = $graphMinimum; Supplier = 'Organization: Microsoft Corporation'; Purpose = 'LIBRARY'; Purl = 'pkg:nuget/Microsoft.Graph.Users'; Note = 'Cloud side. Not bundled; both Graph modules in one version.' } +) +foreach ($item in $required) { + $id = ConvertTo-SpdxId ('Required-' + $item.Name) + $purl = if ($item.Purl -and $item.Version -and $item.Purl.StartsWith('pkg:nuget', [StringComparison]::Ordinal)) { '{0}@{1}?repository_url=https://www.powershellgallery.com/api/v2' -f $item.Purl, $item.Version } elseif ($item.Purl) { $item.Purl } else { '' } + $comment = if ($item.Version) { 'Required, at least version {0}. {1}' -f $item.Version, $item.Note } else { 'Required. {0}' -f $item.Note } + $packages.Add((New-SpdxPackage -Id $id -Name $item.Name -Supplier $item.Supplier -Purpose $item.Purpose -Purl $purl -Comment $comment)) + $relationships.Add([ordered]@{ spdxElementId = $rootId; relationshipType = 'DEPENDS_ON'; relatedSpdxElement = $id; comment = 'Required at run time, not bundled.' }) +} + +foreach ($pin in @($pins.powerShell | Where-Object { $_.role -eq 'primary' })) { + $id = ConvertTo-SpdxId ('Build-PowerShell-' + $pin.version) + $packages.Add((New-SpdxPackage -Id $id -Name 'PowerShell (continuous integration)' -Version ([string]$pin.version) -Supplier 'Organization: Microsoft Corporation' ` + -DownloadLocation ('https://github.com/PowerShell/PowerShell/releases/download/v{0}/PowerShell-{0}-win-x64.zip' -f $pin.version) -Sha256 ([string]$pin.sha256) -License 'MIT' -Purpose 'APPLICATION' ` + -Purl ('pkg:github/PowerShell/PowerShell@v{0}' -f $pin.version) -Comment 'Runs the tests and builds the package. Not shipped. The checksum is the archive.')) + $relationships.Add([ordered]@{ spdxElementId = $id; relationshipType = 'BUILD_DEPENDENCY_OF'; relatedSpdxElement = $rootId }) +} +foreach ($pin in @($pins.modules)) { + $id = ConvertTo-SpdxId ('Build-' + $pin.name + '-' + $pin.version) + $packages.Add((New-SpdxPackage -Id $id -Name ([string]$pin.name) -Version ([string]$pin.version) -Supplier 'NOASSERTION' ` + -DownloadLocation ('https://www.powershellgallery.com/api/v2/package/{0}/{1}' -f $pin.name, $pin.version) -Sha256 ([string]$pin.sha256) -Purpose 'LIBRARY' ` + -Purl ('pkg:nuget/{0}@{1}?repository_url=https://www.powershellgallery.com/api/v2' -f $pin.name, $pin.version) -Comment 'Analysis and test module of the continuous integration. Not shipped. The checksum is the package.')) + $relationships.Add([ordered]@{ spdxElementId = $id; relationshipType = 'BUILD_DEPENDENCY_OF'; relatedSpdxElement = $rootId }) +} +foreach ($pin in $actionPins.Values) { + $id = ConvertTo-SpdxId ('Build-Action-' + $pin.Repository + '-' + $pin.Tag) + $packages.Add((New-SpdxPackage -Id $id -Name ([string]$pin.Repository) -Version ([string]$pin.Tag) -Supplier 'NOASSERTION' ` + -DownloadLocation ('https://github.com/{0}/archive/{1}.zip' -f $pin.Repository, $pin.Sha) -Purpose 'LIBRARY' -Purl ('pkg:github/{0}@{1}' -f $pin.Repository, $pin.Sha) ` + -Comment ('GitHub Actions step of the workflows, pinned to commit {0}. Not shipped.' -f $pin.Sha))) + $relationships.Add([ordered]@{ spdxElementId = $id; relationshipType = 'BUILD_DEPENDENCY_OF'; relatedSpdxElement = $rootId }) +} + +$namespaceTail = '{0}-{1}' -f $zipBase, $zipSha256.Substring(0, 32) +$document = [ordered]@{ + spdxVersion = 'SPDX-2.3' + dataLicense = 'CC0-1.0' + SPDXID = 'SPDXRef-DOCUMENT' + name = $zipBase + documentNamespace = 'https://github.com/Nico77600/PraRemoteMailbox/spdx/' + $namespaceTail + creationInfo = [ordered]@{ + created = $Created.ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ', [Globalization.CultureInfo]::InvariantCulture) + creators = @("Tool: PraRemoteMailbox-New-Sbom-$version") + comment = $(if ($Unsigned) { 'Unsigned continuous-integration build; never a release.' } else { 'Generated from the package folder, the ZIP and the signed manifest PackageIntegrity.psd1.' }) + } + packages = $packages.ToArray() + files = $files.ToArray() + relationships = $relationships.ToArray() +} +$json = ConvertTo-Json -InputObject $document -Depth 10 +[IO.Directory]::CreateDirectory($OutputDirectory) | Out-Null +$utf8 = [Text.UTF8Encoding]::new($false) +[IO.File]::WriteAllText($sbomPath, ($json -replace "`r?`n", "`n") + "`n", $utf8) + +$declaration = [Text.StringBuilder]::new() +[void]$declaration.AppendLine("# PRA Remote Mailbox $version - dependency declaration").AppendLine() +[void]$declaration.AppendLine("Release ZIP: $zipName").AppendLine("ZIP SHA-256: $zipSha256") +if ($signer) { [void]$declaration.AppendLine("Publisher certificate thumbprint: $signer") } +[void]$declaration.AppendLine().AppendLine('The ZIP ships no third-party code and no third-party binary. Its files, each with its SHA-256, are listed in the signed manifest PackageIntegrity.psd1 inside the ZIP and in the bill of materials ' + $zipName + '.spdx.json.').AppendLine() +[void]$declaration.AppendLine('## Required to run (not bundled)').AppendLine().AppendLine('| Component | Minimum | Note |').AppendLine('| --- | --- | --- |') +foreach ($item in $required) { [void]$declaration.AppendLine(('| {0} | {1} | {2} |' -f $item.Name, $(if ($item.Version) { $item.Version } else { '-' }), $item.Note)) } +[void]$declaration.AppendLine().AppendLine('## Used to build and test (not shipped)').AppendLine().AppendLine('| Component | Version | SHA-256 or commit |').AppendLine('| --- | --- | --- |') +foreach ($pin in @($pins.powerShell | Where-Object { $_.role -eq 'primary' })) { [void]$declaration.AppendLine(('| PowerShell (CI) | {0} | {1} |' -f $pin.version, $pin.sha256.ToLowerInvariant())) } +foreach ($pin in @($pins.modules)) { [void]$declaration.AppendLine(('| {0} | {1} | {2} |' -f $pin.name, $pin.version, $pin.sha256.ToLowerInvariant())) } +foreach ($pin in $actionPins.Values) { [void]$declaration.AppendLine(('| {0} (GitHub Actions) | {1} | {2} |' -f $pin.Repository, $pin.Tag, $pin.Sha)) } +[IO.File]::WriteAllText($declarationPath, ($declaration.ToString() -replace "`r?`n", "`n"), $utf8) +$sbomPath +$declarationPath