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--