From 9d03911b938632600cf49d24c19a511494b5a61c Mon Sep 17 00:00:00 2001 From: Nicolas Fabert <195452170+Nico77600@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:56:24 +0100 Subject: [PATCH 01/16] Interrupted runs fail, partial Convert batches resume or roll back safely, batch grant settings, Recover-aware resume --- package/Invoke-PraRemoteMailbox.ps1 | 337 +++++++++- package/PraRemoteMailbox.psd1 | 4 +- package/docs/PraRemoteMailbox-Guide.md | 34 +- package/docs/PraRemoteMailbox-UserGuide.md | 4 +- package/module/PRA.Cloud.psm1 | 24 +- package/module/PRA.Common.psm1 | 104 ++- package/module/PRA.Directory.psm1 | 216 ++++++- package/module/PRA.Gui.psm1 | 49 +- tests/PraRemoteMailbox.Gui.Tests.ps1 | 70 ++ tests/PraRemoteMailbox.Tests.ps1 | 707 ++++++++++++++++++++- 10 files changed, 1463 insertions(+), 86 deletions(-) diff --git a/package/Invoke-PraRemoteMailbox.ps1 b/package/Invoke-PraRemoteMailbox.ps1 index 58aa55d..b3c1681 100644 --- a/package/Invoke-PraRemoteMailbox.ps1 +++ b/package/Invoke-PraRemoteMailbox.ps1 @@ -283,7 +283,7 @@ $context = @{ Once = [bool]$Once; IntervalMinutes = 0; TimeoutMinutes = 0 VerboseEnabled = ((Test-PraOrdinalIgnoreCaseEqual $VerbosePreference 'Continue') -or (Test-PraOrdinalIgnoreCaseEqual $DebugPreference 'Continue')) SourceBackupHash = ''; Source = $null; Proof = $null; LastVerifiedReceipt = $null; OperationFailed = $false; JournalPath = '' - BatchId = ''; NextSteps = @() + BatchId = ''; NextSteps = @(); RunReachedEnd = $false; ChangesStarted = $false } $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. @@ -312,13 +312,13 @@ function ConvertTo-PraLiteral { 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, - [ValidateSet('', 'Identity', 'SearchBase', 'CsvPath', 'Group', 'None')][string]$Only = '', [string]$GroupName = '') + [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. $keepSelector = { param([string]$Name) (-not $Only) -or (Test-PraOrdinalIgnoreCaseEqual $Only $Name) } if ($PhaseName) { $parts += "-Phase $PhaseName" } if ((Test-PraOrdinalIgnoreCaseEqual $ModeName 'Apply')) { $parts += '-Mode Apply' } - if ($BatchId) { $parts += $(if ($BatchId -match '^[0-9a-fA-F]+$') { "-Batch $BatchId" } else { '-Batch ' + (ConvertTo-PraLiteral $BatchId) }) } + if ($BatchId) { $parts += $(if ($BatchId -match '^[0-9a-fA-F]+\z') { "-Batch $BatchId" } else { '-Batch ' + (ConvertTo-PraLiteral $BatchId) }) } if ($KeepFilters) { if ($Identity -and (& $keepSelector 'Identity')) { $parts += '-Identity ' + (ConvertTo-PraLiteral $Identity) } if ((-not (Test-PraOrdinalIgnoreCaseEqual $Scope 'All'))) { $parts += "-Scope $Scope" } @@ -327,10 +327,12 @@ function Get-PraCommandLine { $groupValue = if ($GroupName) { $GroupName } else { $Group } if ($groupValue -and (& $keepSelector 'Group')) { $parts += '-Group ' + (ConvertTo-PraLiteral $groupValue) } # On another server the CSV file is a file of that server: only its name is written, the operator copies the file there. - if ($CsvPath -and (& $keepSelector 'CsvPath')) { $parts += '-CsvPath ' + (ConvertTo-PraLiteral $(if ($OtherServer) { [IO.Path]::GetFileName($CsvPath) } else { $CsvPath })) } + 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' } } + # 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) } # On another server the configuration file is that server's own: -ConfigPath is not repeated. # Run from the window, -ConfigPath is the generated configuration of that run: the suggested command names the configuration file itself. if ($script:ConfigPathBound -and -not $OtherServer) { $parts += '-ConfigPath ' + (ConvertTo-PraLiteral $(if ($BaseConfigPath) { $BaseConfigPath } else { $ConfigPath })) } @@ -392,6 +394,8 @@ function Get-PraFallbackNext { } if ($applied -and $newBatch) { $batchId = [string]$context.BatchId + $partial = Get-PraValue $context 'PartialBatch' $null + if ($null -ne $partial) { return @(Get-PraPartialStopStep $partial) } if ($null -ne $context.Proof -and $batchId) { $kept = 'What this run already did is kept (Active Directory is changed and verified).' if ((Test-PraOrdinalIgnoreCaseEqual $Action 'Convert') -and (Test-PraOrdinalIgnoreCaseEqual $effectivePhase 'AD')) { @@ -399,6 +403,12 @@ function Get-PraFallbackNext { } return @(('{0} Fix the problem named above, then run the Exchange Online part:' -f $kept), (Get-PraCommandLine -ActionName $Action -PhaseName 'Cloud' -BatchId $batchId)) } + $mayBe = @(Get-PraList $context 'MayBeChanged') + if (($written -gt 0 -or $mayBe.Count) -and $batchId -and (Test-PraOrdinalIgnoreCaseEqual $Action 'Convert')) { + return @(('Active Directory {0} for {1} object(s) before the stop (see the journal and the backup named above) and none of them is verified. Do not run the Apply again before reading what is left. To put them back as they were, roll the batch back (run the Preview first, then the same command with -Mode Apply):' -f $(if ($written -gt 0) { 'was changed' } else { 'may have been changed' }), [Math]::Max($written, $mayBe.Count)), + (Get-PraCommandLine -ActionName 'Recover' -ModeName 'Preview' -BatchId $batchId), + 'To see first what the batch holds in Exchange Online, run the Check:', (Get-PraCommandLine -ActionName 'Check' -ModeName 'Preview' -BatchId $batchId)) + } if ($written -gt 0) { return @(('Active Directory was changed for {0} object(s) before the stop (see the journal and the backup named above). Do not run the Apply again before reading what is left: run the Preview of the same command:' -f $written), (Get-PraCommandLine -ActionName $Action -PhaseName $phaseName -ModeName 'Preview' -BatchId $typedBatch -KeepFilters)) @@ -429,7 +439,7 @@ function Get-PraBatchFile { elseif (Test-Path -LiteralPath $candidate -PathType Leaf) { return $candidate } else { throw "Batch file or folder not found: $candidate" } } else { - if ($Value -notmatch '^[0-9a-fA-F]{8,32}$') { throw "Invalid batch ID '$Value': use the 8 characters (or more) shown at the end of the previous run, or the path of the batch JSON file." } + if ($Value -notmatch '^[0-9a-fA-F]{8,32}\z') { throw "Invalid batch ID '$Value': use the 8 characters (or more) shown at the end of the previous run, or the path of the batch JSON file." } if (-not (Test-Path -LiteralPath $context.BackupFolder -PathType Container)) { $isCheck = (Test-PraOrdinalIgnoreCaseEqual $Action 'Check') $packageSuffix = if ((Test-PraOrdinalIgnoreCaseEqual $Action 'Finalize')) { '-for-AD.zip' } else { '-for-Cloud.zip' } @@ -776,6 +786,195 @@ function Send-PraPlanCount { Write-PraEvent -Kind count -Data @{ count = $Count; stepIds = $ids } } +function Set-PraRowsAwaitCloud { + <# Phase Both: the AD part is verified and the Exchange Online part is still to come. The objects are Pending until the cloud part confirms them. #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Changes the status of the in-memory result rows only.')] + param() + foreach ($row in $context.Rows) { + if ((Test-PraOrdinalIn ([string]$row.FinalStatus) @('Success', 'AlreadyDone'))) { $row.FinalStatus = 'Pending' } + } +} + +function Assert-PraBatchNotRolledBack { + <# A Convert batch that a Recover batch rolled back, or started to roll back, cannot be resumed: its objects are not converted any more (or not for certain), and a resume would hand over, or grant permissions, for a batch that no longer holds. #> + param([Parameter(Mandatory)][string[]]$ObjectGuid) + $recover = Find-PraRecoverOfBatch -Context $context -SourceHash ([string]$context.Source.Hash) -ObjectGuid $ObjectGuid + if ($null -eq $recover) { return } + $short = Get-PraShortId ([string]$context.Source.Data.BatchId) + $check = (Get-PraCommandLine -ActionName 'Check' -ModeName 'Preview' -BatchId $recover.ShortId) -replace '^(\.\\Invoke-PraRemoteMailbox\.ps1 -Action Check -Batch [0-9a-fA-F]+)', '$1 -Expect Deprovisioned' + $what = if (Test-PraOrdinalEqual $recover.Basis 'State') { 'already rolled back objects of it' } + elseif (Test-PraOrdinalEqual $recover.Basis 'Journal') { 'started to roll back objects of it (it stopped before its proof)' } + else { 'was started on it and its journal is not here: every object counts as rolled back' } + $steps = @(('Batch {0} was rolled back by Recover batch {1}: its objects are not converted any more. To check what the rollback left, run:' -f $short, $recover.ShortId), $check) + if (-not (Test-PraOrdinalEqual $recover.Basis 'State')) { + $steps = @(('Recover batch {1} {2}. To see what is left, run:' -f $short, $recover.ShortId, $what), $check, + ('To finish the rollback of batch {0}, run the Preview of the Recover (then the same command with -Mode Apply):' -f $short), (Get-PraCommandLine -ActionName 'Recover' -ModeName 'Preview' -BatchId $short)) + } + $context.NextSteps = $steps + @('To convert objects again, start a new Convert (run its Preview first):', (Get-PraCommandLine -ActionName 'Convert' -PhaseName 'AD' -ModeName 'Preview' -KeepFilters)) + $context.NextOnFailure = $true; $context.NoChangeMade = $true; $context.CurrentIdentity = '' + throw ('Convert batch {0} cannot be resumed: Recover batch {1} {2}. Nothing was changed.' -f $short, $recover.ShortId, $what) +} + +function Get-PraBatchTouchedSet { + <# The objects that the journal of the Convert batch in $context.Source shows as written or about to be written. #> + $journal = Join-Path (Split-Path $context.Source.Path -Parent) ('Journal-' + [string]$context.Source.Data.BatchId + '.jsonl') + return (Get-PraJournalTouchedObject -Path $journal) +} + +function Get-PraPartialSourceProof { + <# The AD proof of the Convert batch in $context.Source when it is marked partial (checked in full), else $null. A batch without a readable proof is not partial for this purpose. #> + $path = Join-Path (Split-Path $context.Source.Path -Parent) ('State-' + [string]$context.Source.Data.BatchId + '.json') + if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { return $null } + try { $raw = [IO.File]::ReadAllText($path) | ConvertFrom-PraJson } catch { return $null } + if ((Get-PraValue $raw 'Partial' $false) -ne $true) { return $null } + return (Import-PraProof $context $path $context.Source 'Convert') +} + +function Set-PraUnprovenRow { + <# + .SYNOPSIS + A record of a partial batch that its AD proof does not list: the batch stopped on it after a write was started (it may be partly changed: Pending, to roll back), + or never reached it (Skipped, nothing was written). Either way it leaves this run. + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Changes the status of an in-memory result row only.')] + param([Parameter(Mandatory)]$Row, [Parameter(Mandatory)]$Record, [Parameter(Mandatory)][string]$Reason) + $guid = [string]$Record.ObjectGuid + $Row.ADApplied = $false; $Row.ADVerified = $false + if ($script:Touched.Contains($guid)) { + $Row.FinalStatus = 'Pending' + $Row.Detail = 'may be partly changed: the batch stopped on this object after a write was started; roll the batch back (Recover) to restore it' + [void]$script:MayBeChanged.Add($guid) + $text = 'may be partly changed (the batch stopped on it after a write was started)'; $status = 'Warn' + } + else { + $Row.FinalStatus = 'Skipped'; $Row.Detail = 'not converted by this batch: it stopped at its first error before this object, nothing was written to it' + $text = $Reason; $status = 'Skip' + } + $context.Rows.Add($Row); [void]$script:NotConverted.Add($guid) + $context.CurrentIdentity = $guid + Write-PraItem -Context $context -Status $status -Text $text + $context.CurrentIdentity = '' +} + +function New-PraPartialContinuation { + <# What the Next steps need of a partial batch that this run leaves partly out: who was not converted, who may be partly changed, who can be written in a CSV. #> + param([Parameter(Mandatory)][string]$Side, [Parameter(Mandatory)][int]$Verified) + $left = @($context.Rows | Where-Object { $script:NotConverted.Contains([string]$_.ObjectGuid) -and -not $script:MayBeChanged.Contains([string]$_.ObjectGuid) }) + $maybe = @($context.Rows | Where-Object { $script:MayBeChanged.Contains([string]$_.ObjectGuid) }) + $ids = New-Object 'Collections.Generic.List[string]' + foreach ($row in $left) { foreach ($value in @([string]$row.SamAccountName, [string]$row.UserPrincipalName, [string]$row.ObjectGuid, [string](Get-PraValue $row.BackupRec 'DistinguishedName' ''))) { if ($value) { $ids.Add($value) } } } + return [pscustomobject]@{ ShortId = $context.BatchId; Verified = $Verified; Complete = $false; Side = $Side + NotConverted = [string[]]@($left | ForEach-Object { [string]$_.SamAccountName }); NotConvertedIdentifiers = [string[]]$ids.ToArray(); MayBeChanged = [string[]]@($maybe | ForEach-Object { [string]$_.SamAccountName }) } +} + +function Write-PraRemainingCsv { + <# + .SYNOPSIS + A CSV of the objects that are still to convert, to give to a new Convert (-CsvPath): the lines of the CSV of this run that name them, with the same columns, or one + Identity column. Written in the log folder (private). Returns its path, or '' when there is nothing to write or the file cannot be written. + #> + param([Parameter(Mandatory)]$Partial) + $names = @($Partial.NotConverted) + if (-not $names.Count -or (Test-PraOrdinalEqual $Partial.Side 'Cloud')) { return '' } + $folder = [string]$context.LogFolder + if (-not $folder -or -not (Test-Path -LiteralPath $folder -PathType Container)) { return '' } + $source = '' + if (Test-PraOrdinalEqual $Partial.Side 'Run') { + $source = if ($CsvPath) { $CsvPath } elseif ((Test-PraOrdinalIgnoreCaseEqual ([string](Get-PraValue (Get-PraValue $context.Config 'Scope' @{}) 'Mode' '')) 'Csv')) { [string](Get-PraValue $context.Config.Scope 'CsvPath' '') } else { '' } + if (-not $source) { return '' } + } + try { + $delimiter = ',' + if ($source) { + $text = Read-PraCsvText -Path $source + $header = ($text -split '\r?\n', 2)[0] + $delimiter = if ($header -match '(?i)(^|,)\s*"?Identity"?\s*(,|$)') { ',' } else { ';' } + $rows = @(ConvertFrom-Csv -InputObject $text -Delimiter $delimiter -ErrorAction Stop) + $wanted = New-Object 'Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase) + foreach ($id in @($Partial.NotConvertedIdentifiers)) { [void]$wanted.Add($id) } + $keep = @($rows | Where-Object { $wanted.Contains(([string](Get-PraValue $_ 'Identity' '')).Trim()) }) + if (-not $keep.Count) { return '' } + $columns = @($rows[0].PSObject.Properties.Name) + } + else { $keep = @($names | ForEach-Object { [pscustomobject]@{ Identity = $_ } }); $columns = @('Identity') } + $quote = { param($value) '"' + ([string]$value).Replace('"', '""') + '"' } + $lines = @(($columns | ForEach-Object { & $quote $_ }) -join $delimiter) + foreach ($row in $keep) { $lines += (($columns | ForEach-Object { & $quote (Get-PraValue $row $_ '') }) -join $delimiter) } + $path = Join-Path $folder ('ToConvert-{0}-{1}.csv' -f $Partial.ShortId, $context.RunId.Substring(0, 15)) + Write-PraImmutableFile $path (($lines -join "`r`n") + "`r`n") + return $path + } + catch { return '' } +} + +function Get-PraPartialRestStep { + <# The objects that a partial Convert batch did not convert: how to convert them (a CSV of those only), what to do about the objects that may be partly changed, how to undo the batch. #> + param([Parameter(Mandatory)]$Partial) + $cloud = (Test-PraOrdinalEqual $Partial.Side 'Cloud') + $where = if ($cloud) { 'On the AD server: ' } else { '' } + $names = @($Partial.NotConverted); $shown = @($names | Select-Object -First 10) + $list = ($shown -join ', ') + $(if ($names.Count -gt $shown.Count) { ', and {0} more' -f ($names.Count - $shown.Count) } else { '' }) + $steps = @() + if ($names.Count) { + $csv = Write-PraRemainingCsv $Partial + if ($csv) { + $steps += ('{0} object(s) were not converted by batch {1} (it stopped at its first error, nothing was written to them): {2}. To convert them, fix the problem named by that error, then run a new Convert with the file {3}, which lists only them (run the Preview first):' -f $names.Count, $Partial.ShortId, $list, $csv) + $steps += (Get-PraCommandLine -ActionName 'Convert' -PhaseName 'AD' -ModeName 'Preview' -KeepFilters:(Test-PraOrdinalEqual $Partial.Side 'Run') -CsvOverride $csv) + } + else { + $steps += ('{0}{1} object(s) were not converted by batch {2} (it stopped at its first error, nothing was written to them): {3}. To convert them, fix the problem named by that error, then run a new Convert for those objects only{4}; the converted ones are skipped or refused (run the Preview first):' -f $where, $names.Count, $Partial.ShortId, $list, $(if ($cloud) { ' (a CSV file with an Identity column that lists only them)' } else { '' })) + $steps += (Get-PraCommandLine -ActionName 'Convert' -PhaseName 'AD' -ModeName 'Preview' -KeepFilters:(Test-PraOrdinalEqual $Partial.Side 'Run') -OtherServer:$cloud) + } + } + $maybe = @($Partial.MayBeChanged) + if ($maybe.Count) { + $steps += ('{0}{1} object(s) may be partly changed: {2}. The batch stopped on them after a write was started, so they are not in the list above. Roll batch {3} back to restore them (its converted objects are restored too, the others are left as they are): run the Preview, then the same command with -Mode Apply:' -f $where, $maybe.Count, ($maybe -join ', '), $Partial.ShortId) + } + else { + $steps += ('{0}To undo batch {1} instead (its {2} converted object(s) are restored, the others are left as they are), run the Preview of the rollback, then the same command with -Mode Apply:' -f $where, $Partial.ShortId, $Partial.Verified) + } + $steps += (Get-PraCommandLine -ActionName 'Recover' -ModeName 'Preview' -BatchId $Partial.ShortId -OtherServer:$cloud) + return $steps +} + +function Get-PraPartialStopStep { + <# A Convert batch stopped after some objects were converted and verified: how to continue them, then how to convert the others, what to do about an object that may be partly changed, or how to undo the batch. #> + param([Parameter(Mandatory)]$Partial) + $both = (Test-PraOrdinalIgnoreCaseEqual $effectivePhase 'Both') + $what = if ($Partial.Complete) { 'All {1} object(s) are converted and verified (their AD proof is written) but the run stopped before it finished' } else { 'The batch stopped at its first error: {0} of {1} object(s) are converted and verified (their AD proof is written), the others were not converted by it' } + $steps = @((($what + '. What this run already did is kept. To continue the {0} converted object(s) ({2}; AD is not changed again):') -f $Partial.Verified, $Partial.Planned, $(if ($both) { 'Entra Connect synchronisation' } else { 'Entra Connect synchronisation, then the transfer package' })), + (Get-PraCommandLine -ActionName 'Convert' -PhaseName 'AD' -BatchId $Partial.ShortId)) + if ($both) { $steps += @('Then the Exchange Online part of those objects:', (Get-PraCommandLine -ActionName 'Convert' -PhaseName 'Cloud' -BatchId $Partial.ShortId)) } + if ($Partial.Complete) { return $steps } + return $steps + @(Get-PraPartialRestStep ([pscustomobject]@{ ShortId = $Partial.ShortId; Verified = $Partial.Verified; NotConverted = $Partial.NotConverted; NotConvertedIdentifiers = $Partial.NotConvertedIdentifiers; MayBeChanged = $Partial.MayBeChanged; Side = 'Run' })) +} + +function Initialize-PraGrantSetting { + <# + .SYNOPSIS + The shared mailbox permissions that the cloud phase of a Convert batch grants follow the settings that the Convert run had: they are stored in the batch. + When this server's configuration differs, the batch values are used and a warning names them. A batch from an older version has none: this server's configuration is used, with a warning. + #> + # A Check of one account has no batch: this server's configuration decides. + if ($null -eq $context.Source) { return } + $sharedCount = @($context.Source.Data.Records | Where-Object { [bool](Get-PraValue $_ 'IsShared' $false) }).Count + $local = Get-PraValue $context.Config 'SharedMailbox' @{} + $names = @('Enabled', 'PermissionSource', 'GrantFullAccess', 'GrantSendAs', 'GrantSendOnBehalf') + $stored = Get-PraValue $context.Source.Data 'GrantSettings' $null + if ($null -eq $stored) { + $context.GrantSettingsSource = 'Configuration' + if ($sharedCount) { Write-PraItem -Context $context -Status Warn -Text ('This batch was written by an older version: it does not record the shared mailbox permission settings, so the configuration of this server decides ({0}).' -f (($names | ForEach-Object { '{0} = {1}' -f $_, (Get-PraValue $local $_ '') }) -join ', ')) } + return + } + $context.GrantSettingsSource = 'Batch' + $context.BatchGrantSettings = @{} + foreach ($name in $names) { $context.BatchGrantSettings[$name] = Get-PraValue $stored $name $null } + $different = @($names | Where-Object { -not (Test-PraOrdinalIgnoreCaseEqual ([string](Get-PraValue $stored $_ '')) ([string](Get-PraValue $local $_ ''))) }) + if ($different.Count -and $sharedCount) { + Write-PraItem -Context $context -Status Warn -Text ('The shared mailbox permission settings of this server differ from the ones of the batch ({0}). The batch values are used: {1}.' -f (($different | ForEach-Object { '{0}: batch {1}, this server {2}' -f $_, (Get-PraValue $stored $_ ''), (Get-PraValue $local $_ '') }) -join '; '), (($names | ForEach-Object { '{0} = {1}' -f $_, (Get-PraValue $stored $_ '') }) -join ', ')) + } +} + function Get-PraSkipReason { param([bool]$HasWork = $true) if (-not $HasWork) { return 'Nothing to do.' } @@ -791,9 +990,17 @@ $script:PreviewPackage = '' $script:PackageArgument = '' $script:ImportedFolders = @() $script:ConfirmBound = $PSBoundParameters.ContainsKey('Confirm') +# The objects of a partial Convert batch that this run leaves out (not converted by that batch), and what the Next steps need to name them. +$script:NotConverted = New-Object 'Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase) +$script:PartialContinuation = $null +# The objects that the journal of a partial batch shows as written or about to be written, those among them that the batch did not verify, and whether the proof of the source is partial. +$script:Touched = New-Object 'Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase) +$script:MayBeChanged = New-Object 'Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase) +$script:SourcePartial = $false # Known from the start; the run sets it from the configuration. $effectivePhase = [string]$Phase try { + $context.RunReachedEnd = $false # --------------------------------------------------------------------------------------------- # Configuration, audit files, banner. # --------------------------------------------------------------------------------------------- @@ -988,14 +1195,19 @@ try { if (-not (Test-Path -LiteralPath $proofPath -PathType Leaf)) { throw 'This batch has no AD proof (State file): its AD changes were not verified, so it cannot be finished from here. Nothing was changed.' } $context.SourceBackupHash = $context.Source.Hash $context.Proof = Import-PraProof $context $proofPath $context.Source 'Convert' + Assert-PraBatchNotRolledBack -ObjectGuid @($context.Proof.Data.Records | ForEach-Object { [string]$_.ObjectGuid }) $context.BatchId = Get-PraShortId ([string]$context.Source.Data.BatchId) $context.PhaseFolders = @($batchFolder) # The preflight runs before any object is marked: a refused run has touched nothing and must not show objects as done. Test-PraSyncAvailable + if ($context.Proof.Partial) { $script:Touched = Get-PraBatchTouchedSet } foreach ($record in @($context.Source.Data.Records)) { - if (@($context.Proof.Data.Records | Where-Object { Test-PraOrdinalIgnoreCaseEqual $_.ObjectGuid $record.ObjectGuid }).Count -ne 1) { throw "Object not verified by the AD phase of this batch: $($record.SamAccountName). The batch cannot be finished from here. Nothing was changed." } + $proven = @($context.Proof.Data.Records | Where-Object { Test-PraOrdinalIgnoreCaseEqual $_.ObjectGuid $record.ObjectGuid }) + if ($proven.Count -ne 1 -and -not ($context.Proof.Partial -and $proven.Count -eq 0)) { throw "Object not verified by the AD phase of this batch: $($record.SamAccountName). The batch cannot be finished from here. Nothing was changed." } $row = New-PraRow $context $record - $row.ADVerified = $true; $row.ADApplied = $true; $row.BackupPath = $context.Proof.Receipt.Path + $row.BackupPath = $context.Proof.Receipt.Path + if ($proven.Count -eq 0) { Set-PraUnprovenRow -Row $row -Record $record -Reason 'not converted by this batch (it stopped at its first error before this object)'; continue } + $row.ADVerified = $true; $row.ADApplied = $true $row.FinalStatus = if ($context.AllowMutation) { 'Success' } else { 'Planned' } $row.Detail = 'AD changes made and verified by an earlier run of this batch; they are not changed again.' $context.Rows.Add($row) @@ -1004,8 +1216,15 @@ try { Write-PraItem -Context $context -Status Info -Text 'AD changes made and verified by an earlier run of this batch; not changed again' $context.CurrentIdentity = '' } - Send-PraPlanCount $context.Rows.Count - Write-PraItem -Context $context -Status Ok -Text ("Batch {0}: {1} object(s), AD changes already made and verified (they are not changed again), backup and proof checked" -f $context.BatchId, $context.Rows.Count) + $convertedCount = $context.Rows.Count - $script:NotConverted.Count + Send-PraPlanCount $convertedCount + Write-PraItem -Context $context -Status Ok -Text ("Batch {0}: {1} object(s), AD changes already made and verified (they are not changed again), backup and proof checked" -f $context.BatchId, $convertedCount) + if ($script:NotConverted.Count) { + $script:PartialContinuation = New-PraPartialContinuation -Side 'AD' -Verified $convertedCount + $leftOut = $script:NotConverted.Count - $script:MayBeChanged.Count + if ($leftOut) { Write-PraItem -Context $context -Status Warn -Text ('{0} object(s) of this batch were not converted by it (it stopped at its first error): they are left out of this run, see the next steps.' -f $leftOut) } + if ($script:MayBeChanged.Count) { Write-PraItem -Context $context -Status Warn -Text ('{0} object(s) may be partly changed (the batch stopped on them after a write was started): {1}. Roll the batch back to restore them, see the next steps.' -f $script:MayBeChanged.Count, (@($script:PartialContinuation.MayBeChanged) -join ', ')) } + } if ($context.AllowMutation) { Confirm-PraApply ("Finish batch {0}? {1}A transfer package is written. AD is not changed again." -f $context.BatchId, $(if ($config.EntraConnect.Sync) { 'Entra Connect synchronises first. ' } else { '' })) $context.PhaseWriteFolder = $batchFolder @@ -1062,6 +1281,7 @@ try { $context.Proof = Import-PraProof $context $receipt.StatePath $receipt 'Convert' $context.BatchId = Get-PraShortId $receipt.Data.BatchId Invoke-PraSync $context + if ((Test-PraOrdinalIgnoreCaseEqual $effectivePhase 'Both')) { Set-PraRowsAwaitCloud } # The Exchange Online part does not start when the synchronisation could not run: its mailboxes would not appear. The Next steps say how to go on. $runCloud = (Test-PraOrdinalIgnoreCaseEqual $effectivePhase 'Both') -and ($null -eq (Get-PraValue $context 'SyncFailure' $null)) if ((Test-PraOrdinalIgnoreCaseEqual $effectivePhase 'AD')) { @@ -1088,6 +1308,25 @@ try { $context.SourceBackupHash = $context.Source.Hash $records = @(Select-PraSourceRecord $context.Source) $context.PhaseFolders = @(Split-Path $context.Source.Path -Parent) + # A Convert batch that stopped at its first error converted only some objects: the rollback takes those, and the object that the batch stopped on (it may be partly changed). + # The others were never touched by it, and may have been converted by another batch since: they are not rolled back. + $sourceProof = Get-PraPartialSourceProof + if ($null -ne $sourceProof) { + $script:Touched = Get-PraBatchTouchedSet + $proven = New-Object 'Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase) + foreach ($entry in @($sourceProof.Data.Records)) { [void]$proven.Add([string]$entry.ObjectGuid) } + $taken = New-Object 'Collections.Generic.List[object]'; $left = New-Object 'Collections.Generic.List[object]' + foreach ($record in $records) { if ($proven.Contains([string]$record.ObjectGuid) -or $script:Touched.Contains([string]$record.ObjectGuid)) { $taken.Add($record) } else { $left.Add($record) } } + foreach ($record in $left) { + $row = New-PraRow $context $record + $row.FinalStatus = 'Skipped'; $row.Detail = 'not converted by this batch (it stopped at its first error before this object): nothing to roll back' + $context.Rows.Add($row); [void]$script:NotConverted.Add([string]$record.ObjectGuid) + $context.CurrentIdentity = [string]$record.ObjectGuid + Write-PraItem -Context $context -Status Skip -Text 'not converted by this batch: nothing to roll back' + $context.CurrentIdentity = '' + } + $records = $taken.ToArray() + } Send-PraPlanCount $records.Count Write-PraItem -Context $context -Status Ok -Text ("Convert batch {0}: {1} object(s) selected, backup and SHA-256 verified" -f (Get-PraShortId ([string]$context.Source.Data.BatchId)), $records.Count) Write-PraStep -Context $context -Title 'Active Directory connection' -Icon Directory @@ -1126,6 +1365,7 @@ try { $context.Proof = Import-PraProof $context $receipt.StatePath $context.Source 'Recover' $context.BatchId = Get-PraShortId $receipt.Data.BatchId Invoke-PraSync $context + if ((Test-PraOrdinalIgnoreCaseEqual $effectivePhase 'Both')) { Set-PraRowsAwaitCloud } $runCloud = (Test-PraOrdinalIgnoreCaseEqual $effectivePhase 'Both') -and ($null -eq (Get-PraValue $context 'SyncFailure' $null)) if ((Test-PraOrdinalIgnoreCaseEqual $effectivePhase 'AD')) { Write-PraStep -Context $context -Title 'Creating the transfer package' -Icon Batch @@ -1174,9 +1414,25 @@ try { else { $context.Source = Import-PraBackup $context $batchFile; $context.BatchId = Get-PraShortId $batchData.BatchId } } else { - $context.Source = Import-PraBackup $context (Get-PraBatchFile -Value $Batch -Operations @('Convert')) - $context.BatchId = Get-PraShortId ([string]$context.Source.Data.BatchId) - if (-not $context.Source.Legacy) { $proofPath = Join-Path (Split-Path $context.Source.Path -Parent) ('State-' + $context.Source.Data.BatchId + '.json') } + $isCheck = (Test-PraOrdinalIgnoreCaseEqual $Action 'Check') + $batchFile = Get-PraBatchFile -Value $Batch -Operations $(if ($isCheck) { @('Convert', 'Recover') } else { @('Convert') }) + $fromRecover = $false + if ($isCheck) { + # A Recover batch ID given to Check: the Convert batch that it rolled back is the source (as in the cloud phase of a Recover). + $batchData = [IO.File]::ReadAllText($batchFile) | ConvertFrom-PraJson + if (Test-PraOrdinalEqual $batchData.Operation 'Recover') { + $fromRecover = $true + $context.Source = Import-PraBackup $context (Find-PraConvertSource -Hash ([string]$batchData.SourceBackupHash)) + $context.BatchId = Get-PraShortId ([string]$batchData.BatchId) + Write-PraItem -Context $context -Status Info -Text ('Batch {0} is a Recover batch: the Convert batch {1} that it rolled back is checked.' -f $context.BatchId, (Get-PraShortId ([string]$context.Source.Data.BatchId))) + if (-not (Test-PraOrdinalIgnoreCaseEqual $Expect 'Deprovisioned')) { Write-PraItem -Context $context -Status Warn -Text 'The default expectation is Provisioned; to check a rollback, give -Expect Deprovisioned.' } + } + } + if (-not $fromRecover) { + $context.Source = Import-PraBackup $context $batchFile + $context.BatchId = Get-PraShortId ([string]$context.Source.Data.BatchId) + if (-not $context.Source.Legacy) { $proofPath = Join-Path (Split-Path $context.Source.Path -Parent) ('State-' + $context.Source.Data.BatchId + '.json') } + } } if (-not (Test-PraOrdinalEqual $context.Source.Data.Operation 'Convert')) { throw 'The source of a cloud phase must be the original Convert batch.' } $context.SourceBackupHash = $context.Source.Hash @@ -1187,6 +1443,11 @@ try { # The journal folder is created after the operator's confirmation (below), never before it. $needCloudJournal = $true } + if ((Test-PraOrdinalIgnoreCaseEqual $Action 'Convert')) { + Assert-PraBatchNotRolledBack -ObjectGuid @($(if ($null -ne $context.Proof) { $context.Proof.Data.Records | ForEach-Object { [string]$_.ObjectGuid } } else { $records | ForEach-Object { [string]$_.ObjectGuid } })) + } + $script:SourcePartial = ((Test-PraOrdinalIgnoreCaseEqual $Action 'Recover') -and $null -ne $context.Proof -and $null -ne (Get-PraPartialSourceProof)) + if (($null -ne $context.Proof -and (Test-PraOrdinalIgnoreCaseEqual $Action 'Convert') -and $context.Proof.Partial) -or $script:SourcePartial) { $script:Touched = Get-PraBatchTouchedSet } foreach ($record in $records) { $row = New-PraRow $context $record $originalLicensing = Get-PraValue $record 'Licensing' $null @@ -1196,6 +1457,13 @@ try { $row.SharedFullAccess = Get-PraValue $holders 'FullAccess' @(); $row.SharedSendAs = Get-PraValue $holders 'SendAs' @(); $row.SharedSendOnBehalf = Get-PraValue $holders 'SendOnBehalf' @() if ($null -ne $context.Proof) { $verified = @($context.Proof.Data.Records | Where-Object { Test-PraOrdinalIgnoreCaseEqual $_.ObjectGuid $record.ObjectGuid }) + if ($verified.Count -eq 0 -and ($context.Proof.Partial -or $script:SourcePartial)) { + # Partial batch: this object was not converted by it (or may be partly changed); the cloud part leaves it out. + $row.BackupPath = $context.Proof.Receipt.Path + Set-PraUnprovenRow -Row $row -Record $record -Reason 'not converted by this batch (it stopped at its first error before this object)' + $row.CloudStatus = 'Skipped' + continue + } if ($verified.Count -ne 1) { throw "Object not verified by the AD phase of this batch: $($record.SamAccountName)" } $row.ADVerified = $true; $row.DeproPending = (Test-PraOrdinalEqual $verified[0].Operation 'Deprovision'); $row.BackupPath = $context.Proof.Receipt.Path $provenPlan = @($context.Proof.Receipt.Data.Records | Where-Object { Test-PraOrdinalIgnoreCaseEqual $_.ObjectGuid $record.ObjectGuid })[0] @@ -1204,8 +1472,15 @@ try { $context.Rows.Add($row) } $context.PhaseFolders = @(@(Split-Path $context.Source.Path -Parent) + $(if ($proofPath) { @(Split-Path $proofPath -Parent) } else { @() })) - Send-PraPlanCount $context.Rows.Count - Write-PraItem -Context $context -Status Ok -Text ("Batch {0}: {1} object(s){2}" -f $context.BatchId, $records.Count, $(if ($null -ne $context.Proof) { ', AD proof verified' } else { '' })) + $convertedCount = $context.Rows.Count - $script:NotConverted.Count + Send-PraPlanCount $convertedCount + Write-PraItem -Context $context -Status Ok -Text ("Batch {0}: {1} object(s){2}" -f $context.BatchId, $convertedCount, $(if ($null -ne $context.Proof) { ', AD proof verified' } else { '' })) + if ($script:NotConverted.Count -and (Test-PraOrdinalIgnoreCaseEqual $Action 'Convert')) { + $script:PartialContinuation = New-PraPartialContinuation -Side 'Cloud' -Verified $convertedCount + $leftOut = $script:NotConverted.Count - $script:MayBeChanged.Count + if ($leftOut) { Write-PraItem -Context $context -Status Warn -Text ('{0} object(s) of this batch were not converted by it (it stopped at its first error): they are left out of this run, see the next steps.' -f $leftOut) } + if ($script:MayBeChanged.Count) { Write-PraItem -Context $context -Status Warn -Text ('{0} object(s) may be partly changed (the batch stopped on them after a write was started): {1}. They are left out of this run, see the next steps.' -f $script:MayBeChanged.Count, (@($script:PartialContinuation.MayBeChanged) -join ', ')) } + } } $runCloud = $true } @@ -1213,7 +1488,8 @@ try { # --------------------------------------------------------------------------------------------- # Exchange Online part (after the AD part in phase Both, or alone in phase Cloud / Check). # --------------------------------------------------------------------------------------------- - if ($runCloud -and $context.Rows.Count -gt 0) { + $cloudRows = @($context.Rows | Where-Object { -not $script:NotConverted.Contains([string]$_.ObjectGuid) }) + if ($runCloud -and $cloudRows.Count -gt 0) { if ($context.Issues.Count) { throw 'Cloud part not started: the AD part has errors.' } $cloudTitle = switch ($cloudAction) { 'Recover' { 'Exchange Online: deprovisioning checks' } default { 'Exchange Online: mailboxes, licences and permissions' } } if ((Test-PraOrdinalIgnoreCaseEqual $Action 'Check')) { $cloudTitle = 'Exchange Online checks' } @@ -1221,17 +1497,18 @@ try { # A preview of the cloud phase looks once: it never waits for the cloud. if (-not $context.AllowMutation -and (-not (Test-PraOrdinalIgnoreCaseEqual $Action 'Check'))) { $context.Once = $true } if ($context.AllowMutation -and (Test-PraOrdinalIgnoreCaseEqual $effectivePhase 'Cloud') -and (Test-PraOrdinalIgnoreCaseEqual $Action 'Convert')) { - $grants = 0; foreach ($row in $context.Rows) { $grants += @($row.SharedFullAccess).Count + @($row.SharedSendAs).Count + @($row.SharedSendOnBehalf).Count } - Confirm-PraApply ("Complete {0} object(s) in Exchange Online (wait for the mailboxes, grant up to {1} shared mailbox permission(s))?" -f $context.Rows.Count, $grants) + $grants = 0; foreach ($row in $cloudRows) { $grants += @($row.SharedFullAccess).Count + @($row.SharedSendAs).Count + @($row.SharedSendOnBehalf).Count } + Confirm-PraApply ("Complete {0} object(s) in Exchange Online (wait for the mailboxes, grant up to {1} shared mailbox permission(s))?" -f $cloudRows.Count, $grants) } elseif ($context.AllowMutation -and (Test-PraOrdinalIgnoreCaseEqual $effectivePhase 'Cloud') -and (Test-PraOrdinalIgnoreCaseEqual $Action 'Recover')) { - Confirm-PraApply ("Check the deprovisioning of {0} object(s) in Exchange Online, then package any final shared mailbox and tag restoration for the AD server?" -f $context.Rows.Count) + Confirm-PraApply ("Check the deprovisioning of {0} object(s) in Exchange Online, then package any final shared mailbox and tag restoration for the AD server?" -f $cloudRows.Count) } if ($needCloudJournal) { Initialize-PraCloudJournal } Initialize-PraCloudAuthority + if ((Test-PraOrdinalIgnoreCaseEqual $cloudAction 'Convert')) { Initialize-PraGrantSetting } Import-Module (Join-Path $PSScriptRoot 'module\PRA.Cloud.psm1') -Force -ErrorAction Stop - if ((Test-PraOrdinalIgnoreCaseEqual $Action 'Check') -and (Test-PraOrdinalIgnoreCaseEqual $Expect 'Retained')) { Invoke-PraRetentionCheck -Context $context -Rows $context.Rows.ToArray() } - else { Invoke-PraCloudPhase -Context $context -Rows $context.Rows.ToArray() -Act $cloudAction } + if ((Test-PraOrdinalIgnoreCaseEqual $Action 'Check') -and (Test-PraOrdinalIgnoreCaseEqual $Expect 'Retained')) { Invoke-PraRetentionCheck -Context $context -Rows $cloudRows } + else { Invoke-PraCloudPhase -Context $context -Rows $cloudRows -Act $cloudAction } $cloudErrors = @($context.Rows | Where-Object { Test-PraOrdinalEqual $_.CloudStatus 'Error' }) $runErrors = @($cloudErrors | Where-Object { [bool](Get-PraValue $_ 'RunError' $false) }).Count $notExpected = $cloudErrors.Count - $runErrors @@ -1297,11 +1574,11 @@ try { if ((Test-PraOrdinalIgnoreCaseEqual $Action 'Recover')) { Write-PraStep -Context $context -Title 'Final restore of shared mailboxes and tags' -Icon Write if ($context.AllowMutation) { - $tagged = @($context.Rows | Where-Object { [bool](Get-PraValue (Get-PraValue $_.BackupRec 'Retention' $null) 'Enabled' $false) }) + $tagged = @($cloudRows | Where-Object { [bool](Get-PraValue (Get-PraValue $_.BackupRec 'Retention' $null) 'Enabled' $false) }) foreach ($row in $tagged | Where-Object PreserveCloudMailbox) { $row.FinalStatus = 'Pending'; $row.Detail += ' | Cloud mailbox kept on purpose: the retention tag stays.' } - $followup = @($context.Rows | Where-Object { -not $_.PreserveCloudMailbox -and ($_.DeproPending -or $tagged.Contains($_)) }) + $followup = @($cloudRows | Where-Object { -not $_.PreserveCloudMailbox -and ($_.DeproPending -or $tagged.Contains($_)) }) foreach ($row in $followup) { if (-not (Test-PraOrdinalEqual $row.CloudStatus 'Success') -or $row.DeprovisionConfirmed -ne $true -or $row.ADVerified -ne $true) { throw 'Cloud deprovisioning or AD proof not confirmed: restore and tag clean-up blocked.' } } if (-not $followup.Count) { Write-PraItem -Context $context -Status Skip -Text 'Nothing left to restore.' } elseif ((Test-PraOrdinalIgnoreCaseEqual $effectivePhase 'Cloud') -or $defer -or -not @(Get-Module -ListAvailable ActiveDirectory).Count) { @@ -1379,6 +1656,10 @@ try { $checkCommand = Get-PraCommandLine -ActionName 'Check' -ModeName 'Preview' -BatchId $(if ($script:PreviewPackage) { $script:PreviewPackage } else { $context.BatchId }) -KeepFilters $context.NextSteps = @(@(Get-PraList $context 'NextSteps') + ('X500 missing in Exchange Online for {0} object(s) (replies to old messages can bounce): run an Entra Connect synchronisation, then check again: {1}' -f $x500Missing.Count, $checkCommand)) } + + # The objects of a partial batch that this run leaves out: how to convert them, or how to undo the batch. + if ($null -ne $script:PartialContinuation) { $context.NextSteps = @(Get-PraList $context 'NextSteps') + @(Get-PraPartialRestStep $script:PartialContinuation) } + $context.RunReachedEnd = $true } catch { $failure = $_; $failureOperation = $context.CurrentOperation @@ -1431,6 +1712,16 @@ catch { } } finally { + # A run that ends without reaching the end of the main block and without an error (Ctrl+C, a closed window, a stop of the host) is never a success. + $interrupted = $false + if (-not [bool](Get-PraValue $context 'RunReachedEnd' $false) -and [int]$context.ExitCode -ne 1) { + $interrupted = $true + try { + $where = "Stopped at step '{0}' (operation {1}{2}): the run was interrupted before it finished (Ctrl+C, a closed window or a stop of the host)." -f $context.CurrentPhase, $context.CurrentOperation, $(if ($context.CurrentIdentity) { ', object ' + $context.CurrentIdentity } else { '' }) + Write-PraLog -Context $context -Message $where -Level Error + } catch { $null = $_ } + $context.ExitCode = 1 + } Initialize-PraPermissionCache -Context $context if ([string](Get-PraValue $context 'PreviewStaging' '')) { try { [IO.Directory]::Delete($context.PreviewStaging, $true) } catch { try { Write-PraLog -Context $context -Message ('The temporary Preview folder could not be deleted: {0}' -f $_.Exception.Message) -Level Detail } catch { $null = $_ } } @@ -1446,6 +1737,8 @@ finally { try { $context.FallbackNext = @(Get-PraFallbackNext) } catch { $context.FallbackNext = @('Fix the problem named above, then run the same command again with the same options.') } $result = Complete-PraRun -Context $context + # A run whose pipeline was stopped gives its exit code to the process only through the host. + if ($interrupted -and (Test-PraOwnEntryProcess)) { try { $Host.SetShouldExit([int]$result.ExitCode) } catch { $null = $_ } } if ($PassThru) { $result } exit $result.ExitCode } diff --git a/package/PraRemoteMailbox.psd1 b/package/PraRemoteMailbox.psd1 index 28ff287..c858cfc 100644 --- a/package/PraRemoteMailbox.psd1 +++ b/package/PraRemoteMailbox.psd1 @@ -33,11 +33,11 @@ # Configuration, paths and CSV (PRA.Common) 'Import-PraConfiguration', 'Test-PraScopeConfiguration', 'New-PraEffectiveConfiguration', 'Get-PraConfigurationDifference', 'Resolve-PraPath', 'Read-PraCsvText', 'Read-PraTargetCsv', 'Get-PraTargetOverride', 'Get-PraToolVersion', 'Get-PraCloudModuleReport', 'Get-PraValue', 'Get-PraList', # Ordinal helpers, JSON and native calls (PRA.Common) - 'Test-PraOrdinalEqual', 'Test-PraOrdinalIgnoreCaseEqual', 'Test-PraOrdinalIn', 'Test-PraOrdinalIgnoreCaseIn', 'Get-PraOrdinalSorted', 'Get-PraOrdinalUnique', 'Compare-PraX500Address', 'ConvertFrom-PraJson', 'Get-PraNativeProcessApi', 'Get-PraWin32ErrorText', + 'Test-PraOrdinalEqual', 'Test-PraOrdinalIgnoreCaseEqual', 'Test-PraOrdinalIn', 'Test-PraOrdinalIgnoreCaseIn', 'Get-PraOrdinalSorted', 'Get-PraOrdinalUnique', 'Compare-PraX500Address', 'ConvertFrom-PraJson', 'Get-PraNativeProcessApi', 'Get-PraWin32ErrorText', 'Test-PraOwnEntryProcess', # Private folders, phase data and transfer package (PRA.Common) 'New-PraPrivateDirectorySecurity', 'Initialize-PraPrivateFolder', 'Register-PraObjectName', 'Register-PraObjectBackup', 'Save-PraPhaseData', 'Copy-PraPhaseData', 'Get-PraTransferPackageName', 'Get-PraTransferPackage', 'New-PraTransferPackage', 'Import-PraTransferPackage', # Active Directory, backup and proof (PRA.Directory) - 'Initialize-PraDirectory', 'Initialize-PraPermissionCache', 'Get-PraUser', 'Resolve-PraGroup', 'Get-PraGroupMember', 'Get-PraExpectedX500', 'Get-PraTarget', 'New-PraRow', 'New-PraPlan', 'Invoke-PraAdPreview', 'Invoke-PraAdBatch', 'Invoke-PraAdReplication', 'Invoke-PraSync', 'Test-PraSyncServer', 'Start-PraSyncProbe', 'Import-PraBackup', 'Import-PraProof', 'Assert-PraReceipt', 'Assert-PraFollowupState', 'Get-PraHash', 'Write-PraImmutableFile', 'New-PraPrivateDirectory', 'Write-PraJournal' + 'Initialize-PraDirectory', 'Initialize-PraPermissionCache', 'Get-PraUser', 'Resolve-PraGroup', 'Get-PraGroupMember', 'Get-PraExpectedX500', 'Get-PraTarget', 'Find-PraRecoverOfBatch', 'Get-PraJournalTouchedObject', 'New-PraRow', 'New-PraPlan', 'Invoke-PraAdPreview', 'Invoke-PraAdBatch', 'Invoke-PraAdReplication', 'Invoke-PraSync', 'Test-PraSyncServer', 'Start-PraSyncProbe', 'Import-PraBackup', 'Import-PraProof', 'Assert-PraReceipt', 'Assert-PraFollowupState', 'Get-PraHash', 'Write-PraImmutableFile', 'New-PraPrivateDirectory', 'Write-PraJournal' ) CmdletsToExport = @() VariablesToExport = @() diff --git a/package/docs/PraRemoteMailbox-Guide.md b/package/docs/PraRemoteMailbox-Guide.md index 2873f74..0cd164a 100644 --- a/package/docs/PraRemoteMailbox-Guide.md +++ b/package/docs/PraRemoteMailbox-Guide.md @@ -223,7 +223,7 @@ check | Done | on-premises again > **The cloud X500 address is kept.** While an object is a remote mailbox, Entra Connect (Exchange hybrid writeback) adds an `X500:` address of the cloud mailbox to `proxyAddresses` and sets `msDS-ExternalDirectoryObjectId`. A Recover restores `proxyAddresses` as captured before the Convert **plus every `X500:` address that is on the object at that moment and was not in the original list**: nothing else is kept, the routing `smtp:` address added by Convert is still removed, no `X500:` is invented, and an address that was already original is not duplicated. Without it, a reply to a message sent from the cloud during the disaster, or a cached Outlook address, would bounce after the rollback. The Preview says *N cloud X500 address(es) kept*, and the batch records the list (`KeptX500`; a batch written before 3.0.0 has none). > [!NOTE] -> **Nothing is automatic after an error.** The first error stops the batch: no next object, no sync, no cloud write, and no automatic rollback. The journal of the batch (`Journal-.jsonl`) says exactly which write was started, applied and verified. Read the summary, fix the cause, run the same command again: objects already done are detected (`AlreadyDone`). **Once the AD changes are made, a Convert is not run again:** the objects are remote mailboxes, so the same command refuses them ("already converted by batch ...") and names the command that finishes the batch (`-Phase AD -Batch`, see [Exit codes](#exit-codes)). An Entra Connect sync that cannot run after the verified AD writes is not an error of the run (Pending, exit code 2, the transfer package is written). +> **Nothing is automatic after an error.** The first error stops the batch: no next object, no sync, no cloud write, and no automatic rollback. The journal of the batch (`Journal-.jsonl`) says exactly which write was started, applied and verified. **The objects converted and verified before the error keep their AD proof:** the State file is written for them and marked *partial* (it says how many objects were planned). The objects that were not reached are *Pending*, never *skipped*. The Next steps give the exact commands: continue the converted objects (`-Phase AD -Batch `, then `-Phase Cloud -Batch ` for the Exchange Online part), convert the others (fix the cause, then run a new Convert for those objects only: a converted object is refused by the same command, "already converted by batch ...", so with `-CsvPath` list only the others), or roll the whole batch back (`-Action Recover -Batch `, Preview first). **Once the AD changes are made, a Convert is not run again** for the converted objects (see [Exit codes](#exit-codes)). A run that is stopped from outside (Ctrl+C, a closed console, a stop of the host) ends the same way: `RESULT: FAIL`, exit code 1, the stop named in the summary and the command that goes on, never `PASS`. The exit code is given to the process only when the run is the entry of its own PowerShell process (`pwsh -File`, `-Command`, the console's child process): a command typed in an interactive window never closes that window. When every object of a batch was verified and the run stopped before the end, the AD proof written is the normal one (not partial). An Entra Connect sync that cannot run after the verified AD writes is not an error of the run (Pending, exit code 2, the transfer package is written). > [!TIP] > **Two servers are supported.** If no single server reaches both Active Directory and Microsoft 365 (for example an AD server on an isolated network), run the AD part with `-Phase AD` on the AD server, copy the **transfer package** it writes (the `.zip` **and** its `.sha256` file, both in `Backups\Outbox\`, [chapter 10](#10-files-batches-proofs-and-packages)), and run `-Phase Cloud -Batch ` on the **cloud server**. That is not a server hosted in the cloud: it is any Windows machine of the organisation that reaches Microsoft 365 through the Internet (server room or administrator workstation), with no access to AD. The summary of each step prints the command of the next one. @@ -436,7 +436,7 @@ Everything is set in `config\PraRemoteMailbox.config.psd1` — the command line | `SharedMailbox.RemoteRecipientType` | 97 (first provisioning of a shared mailbox), 99 with archive. | | `SharedMailbox.PermissionSource` | Where FullAccess / SendAs holders are read, without Exchange: `AD` (default: the copy Exchange keeps on the account), `Csv` (`Shared,Group`), `CustomAttribute` (a group tagged with the name of the mailbox), `None`. Groups are expanded to their users. Details: [chapter 2](#2-how-it-works), *Shared mailbox permissions*. | | `CaptureSendOnBehalf` | SendOnBehalf holders from `publicDelegates`. | -| `GrantFullAccess`, `GrantSendAs`, `GrantSendOnBehalf`, `AutoMapping` | What is granted in Exchange Online. | +| `GrantFullAccess`, `GrantSendAs`, `GrantSendOnBehalf`, `AutoMapping` | What is granted in Exchange Online. The values of `Enabled`, `PermissionSource` and the three `Grant...` settings in force at the Convert are **stored in the batch** (`GrantSettings`); the cloud phase of any server follows the batch. When the configuration of the cloud server differs, a warning names the values used (the batch's). A batch written before 3.2.0 has none: the configuration of the server is used, with a warning. A permission that the batch carries and the settings in force do not grant (old batch, or a batch converted with settings that grant none) is **never silent**: the run ends *done with warnings*, the warning names each permission (`FullAccess`, `SendAs`, `SendOnBehalf` and the trustee), and the report and the CSV say *to grant by hand* (the lists are also in the backup file). | | `ExcludeTrusteeSamAccountNames` | Accounts never reproduced (e.g. service or admin accounts found in the ACLs). | | `KeepCloudSharedOnRecover` | `$true` = Recover keeps the cloud shared mailbox (rare). | | `DeferOnPremRestore` | With phase Both, `$true` defers final AD restoration to Finalize. Phase Cloud always packages it, regardless of this setting. | @@ -472,7 +472,7 @@ converge is a **warning that names it**; the synchronisation still runs, and the | `Cloud.TenantId`, `Cloud.Organization` | Tenant GUID and initial domain (`tenant.onmicrosoft.com`). Every session is checked against them. **When `Cloud.AppId` is set, both are required** (the tenant must be a GUID): the configuration is refused at load otherwise. | | `Cloud.AppId` + `Cloud.CertificateThumbprint` | Certificate sign-in (unattended, [annex C](#annex-c--certificate-sign-in-application)). Both empty = interactive sign-in (`Cloud.UserPrincipalName` = expected account). | | `Cloud.CheckMailbox`, `CheckLicense`, `MailboxCheckVia`, `RequiredSkuPartNumber` | What "ready" means for a user: mailbox (Exchange Online type, or Graph provisioning) and licence. `MailboxCheckVia` is `Exo` by default (mailbox type in Exchange Online) or `Graph` (provisioning). | -| `Exo.MinModuleVersion` | Oldest `ExchangeOnlineManagement` accepted (default `3.10.1`). With an older module the tool stops before any change and gives the `Install-Module` command; `Exo.UseSubprocess` is the only way to the child process. The Microsoft Graph minimum (`2.41.1`, one same version for `Authentication` and `Users`) is fixed in the tool. | +| `Exo.MinModuleVersion` | Oldest `ExchangeOnlineManagement` accepted (default `3.10.1`, which is also the lowest value used: a lower setting is raised to it). With an older module the tool stops before any change and gives the `Install-Module` command; `Exo.UseSubprocess` is the only way to the child process. The Microsoft Graph minimum (`2.41.1`, one same version for `Authentication` and `Users`) is fixed in the tool. | | `Exo.DisableWAM` | `$false` (default): interactive sign-in through the Windows broker (WAM). `$true`: browser sign-in instead. See [chapter 8](#8-everyday-use), *Cloud sign-in from the window*. | | `Exo.GrantVerifyAttempts`, `GrantVerifyDelaySeconds` | After **one** grant, re-read up to N times (never granted twice). | | `Exo.UseSubprocess` | Run every Exchange Online call in a child PowerShell 7 process (certificate only; automatic with a module older than `MinModuleVersion`). | @@ -614,7 +614,7 @@ voids the previous Preview. The list is revalidated and hashed before Run. AD st `\Inbox`, with their state. **Import package...** takes a `.zip` from anywhere: the console verifies it (all checks before any write, [chapter 10](#10-files-batches-proofs-and-packages)), extracts it into `Storage.BackupFolder` and selects its batch. A package picked in the list is imported when you continue to the verification page. -A Convert batch whose AD part is verified (it has its `State-.json`) but whose Entra Connect sync did not end (the last `ADSync` line of its journal is `Failed`), or that has no package in `Backups\Outbox` on a server that cannot do the cloud part, is marked **finish it here** (orange). Selecting it makes the phase **AD** and runs `Convert -Phase AD -Batch ` ([Exit codes](#exit-codes)): the Entra Connect check, the synchronisation again, the package; Active Directory is not written and the cloud sign-in is not needed. The Next steps page of a run whose sync could not start puts the sync before the copy of the package. An engine refusal "already converted by batch ..." sent from the console names this path (Task, Continue a batch) instead of a command line. +A Convert batch whose proof is *partial* (it stopped at its first error: some objects were verified, the others were not converted) is labelled **Partial: k of n converted**, and *Continue a batch* offers it as *finish it here* (the synchronisation first, then the package, as the command line does): so is any batch whose journal has no Entra Connect entry that ended well when `EntraConnect.Sync` is on; the files of the global report (`PhaseData-...`) are not batches and are never listed. A Convert batch whose AD part is verified (it has its `State-.json`) but whose Entra Connect sync did not end (the last `ADSync` line of its journal is `Failed`), or that has no package in `Backups\Outbox` on a server that cannot do the cloud part, is marked **finish it here** (orange). Selecting it makes the phase **AD** and runs `Convert -Phase AD -Batch ` ([Exit codes](#exit-codes)): the Entra Connect check, the synchronisation again, the package; Active Directory is not written and the cloud sign-in is not needed. The Next steps page of a run whose sync could not start puts the sync before the copy of the package. An engine refusal "already converted by batch ..." sent from the console names this path (Task, Continue a batch) instead of a command line. **Safety is unchanged.** Run is locked until a successful Preview of **exactly** the same request, files and configuration; the engine independently rereads the directory, backs up and verifies the targets before every write. Type **CONVERT**, **RECOVER** or **FINALIZE** (any letter case, surrounding spaces @@ -771,7 +771,7 @@ Users get their original attributes back and leave the licence group. Shared mai .\Invoke-PraRemoteMailbox.ps1 -Action Check -Batch 1d5ac20b -Expect Deprovisioned # after a Recover ``` -Read only. Check waits for the expected state (up to `Polling.TimeoutMinutes`); add `-Once` for a single pass. Each wait line says what is awaited: a mailbox that is still on-premises never reaches the expected state without a Convert, so use `-Once` for it. A failed Check counts one error. It also shows whether the mailbox carries the X500 addresses recorded by the Convert (section *X500 addresses*, [chapter 2](#2-how-it-works)). +Read only. `-Batch` also takes the ID printed by a Recover: Check then reads the Convert batch that it rolled back (give `-Expect Deprovisioned`). Check waits for the expected state (up to `Polling.TimeoutMinutes`); add `-Once` for a single pass. Each wait line says what is awaited: a mailbox that is still on-premises never reaches the expected state without a Convert, so use `-Once` for it. A failed Check counts one error. It also shows whether the mailbox carries the X500 addresses recorded by the Convert (section *X500 addresses*, [chapter 2](#2-how-it-works)). ### Scenario C — Convert on two servers @@ -828,6 +828,14 @@ A `Convert` or `Recover` with `-Phase AD` therefore exits with **2** when it end The batch, its backup and its proof are checked in full; the Entra Connect check is made as for a conversion (it stops with nothing written if it fails); the synchronisation runs again; the transfer package is written. **Active Directory is not written** and the same objects are not converted twice. A Preview shows what would be done. A batch without proof is refused ("cannot be finished from here"). The same command is printed when a conversion is started again for an object that is already converted. +**A partial batch.** A Convert stops at its first error. The objects verified before it have their AD proof, marked *partial* (the proof says how many objects were planned). `-Phase AD -Batch ` and `-Phase Cloud -Batch ` accept it: the objects of the proof are continued, and each other object of the backup is reported *not converted by this batch* (`Skipped`, one line each, a warning for the batch). The Next steps then say how to convert those objects (fix the cause, then a new Convert for them only: the converted ones are refused by the same command) or how to undo the batch. **The object the batch stopped on** may be partly changed (a write was started, the batch stopped before it was verified: the journal has a *Started* or *Applied* line for it). It is not in the list of objects to convert again: it is reported *may be partly changed* (`Pending`), and the Next steps give the rollback (`-Action Recover -Batch `, Preview first), which restores it. The objects that were never touched are `Skipped`. + +`-Action Recover -Batch ` of a partial batch takes **only** the objects of the proof and the object the batch stopped on; every other object of the backup is reported `Skipped` ("not converted by this batch": nothing to roll back), so an object that another batch converted since is not rolled back by this one. `-Action Check -Batch ` of a partial batch reports the objects that were never converted as *not as expected*. + +**New Convert for the objects that are left.** With `-CsvPath`, the Next steps give a command with a CSV file that lists only the objects still to convert (same columns as your file, written in the log folder); with `-Identity`, `-SearchBase` or `-Group` the command keeps the filters: the converted objects are not eligible any more and are skipped. On the cloud server the AD-side commands are introduced by *On the AD server:* and are written without this server's configuration path. + +**A Convert batch that a Recover rolled back, or started to roll back, cannot be resumed** (`-Phase AD -Batch` and the cloud phase refuse it: "Convert batch X cannot be resumed: Recover batch Y already rolled back objects of it"). A Recover that stopped before its proof counts too: its journal tells which objects it had started on; a journal that is missing counts for every object. On two servers the cloud server learns of the Recover only when the Recover package has been imported there: until then it cannot refuse. + ## 9. Reading the results @@ -868,6 +876,7 @@ for Convert (AD, then Cloud) as for Recover (AD, Cloud, then Finalize), whatever - **Privacy.** Names, statuses and messages only: no secret, no token. Every value is HTML-encoded; spreadsheet formulas are neutralised in the CSV; the files are private like the other reports and backups. Above 2,000 objects the HTML opens the journey of the objects that are not simply *done*; the CSV lists all. - The `.sha256` next to a PhaseData file is an integrity check, not proof of origin: the protection against a changed file is the SHA-256 of every entry in `transfer.json`, verified at import; the report decides nothing from this data. +- **A cloud part completed by a later run.** When the cloud part of a phase Both run failed (objects not ready in time) and `-Phase Cloud -Batch ` completed it, the verdict of the object follows the later run: the cloud error of the earlier run stays in its journey as an *Earlier run* line and does not make the object *failed*. - **Phase Both** uses the same layout (one phase). The per-phase HTML report also lists the run settings changed (the per-phase CSV keeps its 22 columns). ### Warnings @@ -883,9 +892,9 @@ A warning never stops the run and never changes the exit code; it says that some | `Planned` | Preview: this is what Apply would do. | | `Success` | Done and verified (AD re-read; cloud state reached). | | `AlreadyDone` | Nothing to change: the object was already in the expected state (counted as done). | -| `Pending` | AD done, waiting for another step (shared mailbox deprovisioning, Finalize). | +| `Pending` | AD done, waiting for another step (shared mailbox deprovisioning, Finalize, the Exchange Online part of phase Both), or not reached because the run stopped (an error, or a stop from outside). | | `Error` | Stopped; see `Detail` and the log. | -| `Skipped` | Not processed (the batch stopped before it, or no applicable check). | +| `Skipped` | Not processed: no applicable check, or not converted by a partial batch (it stopped at its first error before this object). | ### The CSV columns @@ -1111,7 +1120,12 @@ After a change of the engine, repeat the campaign of [annex B](#annex-b--lab-tes | `AD is changed and verified. The Entra Connect sync did not run: ...` (Pending, exit code 2) | the check passed, then the cycle failed (right removed, server down, timeout, scheduler suspended); the Next steps give the first line of the message, the full technical message is in the log. For a suspended scheduler: run `Set-ADSyncScheduler -SchedulerSuspended $false` on the Entra Connect server, then the delta sync | | `The RSAT ActiveDirectory module is not installed on this server: ...` | the AD part was started on a server without the RSAT feature Active Directory module | install the RSAT feature, or run the AD part on a server that has it | do not convert again: run a delta sync on the Entra Connect server, then carry the package (or `-Phase Cloud -Batch `) as the Next steps say | | ` is already converted by batch (it is a remote mailbox now)` | a Convert was started again for an object that the batch `` already converted | nothing is converted. To finish that batch (sync + package) run the command given in the Next steps: `-Action Convert -Phase AD -Mode Apply -Batch ` | -| `This batch has no AD proof (State file) ... cannot be finished from here` | `-Phase AD -Batch` on a batch whose AD changes were not verified | use the cloud phase only for a batch with a proof; otherwise run a Preview of a new Convert | +| `This batch has no AD proof (State file) ... cannot be finished from here` | `-Phase AD -Batch` on a batch that stopped before its first verified object (or a batch of an old version): no object of it is proven | nothing is finished from here. Put back what the batch changed with `-Action Recover -Batch ` (Preview first), then run a new Convert | +| ` object(s) of this batch were not converted by it (it stopped at its first error)` (warning; the objects are `Skipped`) | `-Phase AD -Batch` or `-Phase Cloud -Batch` of a **partial** batch: its AD proof lists only the objects verified before the first error | the converted objects are continued. For the others: fix the cause, then run a new Convert for those objects only (with `-CsvPath`, list only them), or roll the batch back (`-Action Recover -Batch `, Preview first). The Next steps give the commands | +| `Convert batch cannot be resumed: Recover batch already rolled back objects of it` | `-Phase AD -Batch` or `-Phase Cloud -Batch` on a Convert batch that a Recover already rolled back | nothing is changed. To convert objects again, start a new Convert; to see what the rollback left, `-Action Check -Batch -Expect Deprovisioned` | +| `Stopped at step ...: the run was interrupted before it finished (Ctrl+C, a closed window or a stop of the host)` (`RESULT: FAIL`, exit code 1) | the run was stopped from outside | read the Next steps: they continue the batch (or say how to undo it); what the run did is kept | +| `: shared mailbox permission(s) not granted by the settings ... - to grant by hand: FullAccess ; ...` (warning, *done with warnings*) | the batch carries permissions that the settings in force do not grant: a batch written before 3.2.0 on a server whose configuration grants less, or a batch converted with settings that grant none | grant the listed permissions by hand (`Add-MailboxPermission`, `Add-RecipientPermission`, `Set-Mailbox -GrantSendOnBehalfTo`), or correct the settings and run the cloud phase again. Nothing else is wrong | +| `The shared mailbox permission settings of this server differ from the ones of the batch (...)` (warning) | the cloud server has another `SharedMailbox` configuration than the server that converted | nothing to do: the batch values are used, and the warning names them | | `An Exchange Online session already exists in this console` | the console was used for EXO before | open a new PowerShell 7 window | | `Microsoft Graph: found Microsoft.Graph.Authentication 2.40.0; Microsoft.Graph.Users 2.35.1. The tool needs both in one same version 2.41.1 or later` | the Graph modules installed are too old, or not in one same version (two versions of Graph in one session fail with *Assembly with same name is already loaded*) | run the commands of the message, one per module and both for the same version (`Install-Module Microsoft.Graph.Authentication -MinimumVersion 2.41.1 -Scope CurrentUser`, then `Install-Module Microsoft.Graph.Users -MinimumVersion 2.41.1 -Scope CurrentUser`; `-Scope AllUsers` needs a window opened as administrator). `Install-Module` refuses `-MinimumVersion` with several names. Nothing was changed. The tool imports both modules in that same version. The same text is on the Microsoft.Graph light of the Setup page | | `ExchangeOnlineManagement: found 3.9.0; the tool needs 3.10.1 or later` | the module is too old | `Install-Module ExchangeOnlineManagement -MinimumVersion 3.10.1 -Scope CurrentUser` (`-Scope AllUsers` in a window opened as administrator). Nothing was changed | @@ -1260,9 +1274,9 @@ $app # -> Cloud.AppId | File | Format | Key fields | |---|---|---| -| Backup `---.json` | schema **3** (schema 1 and 2 of 1.2.x/1.3.0-1.3.2 still read) | `Operation` (Convert, Recover, Finalize), `BatchId`, `Environment`, `Server`, `RawFile` + `RawHash`, `SourceBackupHash` (Recover/Finalize: SHA-256 of the Convert backup), `Records[]` (`Attributes` = before, `PlannedAttributes` = after, `Licensing`, `Retention`, `SharedPermissions`, `CapturedUsnChanged`) | +| Backup `---.json` | schema **3** (schema 1 and 2 of 1.2.x/1.3.0-1.3.2 still read) | `Operation` (Convert, Recover, Finalize), `BatchId`, `Environment`, `Server`, `RawFile` + `RawHash`, `SourceBackupHash` (Recover/Finalize: SHA-256 of the Convert backup), `GrantSettings` (Convert: `Enabled`, `PermissionSource`, `GrantFullAccess`, `GrantSendAs`, `GrantSendOnBehalf` in force at the Convert), `Records[]` (`Attributes` = before, `PlannedAttributes` = after, `Licensing`, `Retention`, `SharedPermissions`, `CapturedUsnChanged`) | | Capture `.clixml` | `PraDataOnlyClixml-v1` | every attribute returned by AD, closed descriptors (no native object) | -| AD proof `State-.json` | schema 2 | `Kind = ADVerified`, `BackupFile` + `BackupHash`, `Records[]` (`ObjectGuid`, `Operation`, `VerifiedUsnChanged`) | +| AD proof `State-.json` | schema 2 | `Kind = ADVerified`, `BackupFile` + `BackupHash`, `Records[]` (`ObjectGuid`, `Operation`, `VerifiedUsnChanged`); a Convert batch that stopped at its first error has `Partial = true` and `PlannedCount` (the number of objects planned), and lists only the objects verified | | Journal `Journal-.jsonl` (AD) and `CloudOperations.jsonl` (cloud phase, folder `-cloud`, created after the confirmation) | one JSON per line | `RunId`, `Utc`, `Target`, `Operation`, `Status`, `Detail`. Statuses: **Started**, **Applied**, **Verified** (a write and its re-read), **FailedOrIndeterminate** (AD write failed or unknown), **Failed** (cloud write failed), **Initialized** (cloud journal opened, no cloud write yet), **Completed** (Entra Connect cycle finished) | | Finalize package manifest | schema 2, `Operation = RecoverFinalize` | `SourceBackupHash`, `StateHash`, `Items[]` (`RestoreShared`, `RestoreTag`, `DeprovisionConfirmed`) | diff --git a/package/docs/PraRemoteMailbox-UserGuide.md b/package/docs/PraRemoteMailbox-UserGuide.md index dcf0e1a..f317ab2 100644 --- a/package/docs/PraRemoteMailbox-UserGuide.md +++ b/package/docs/PraRemoteMailbox-UserGuide.md @@ -662,7 +662,9 @@ Find what you **see** in the left column. The middle column says what it **means | An **orange triangle** (warning) | The tool can go on, but you must read. | Read the text. If you understand it, go on. If not, stop and ask. | | I do not see **Phase: …** on the **Task** page | You did not click a big card yet. | Click a big card. The card **What will happen on this server** appears at the bottom. The pink pill is on its left. | | The **wait is long** (*attempt 5 of 13*) | The directory is sending the news to the cloud. | Wait. It is normal up to **15 minutes**. The mailboxes can take up to **an hour** to appear. Do not close the window. | -| A **step turns red** during the run | The tool stopped on purpose, at the first error. | Do not click anything. Take a photo. Stop and ask. The people already done are kept. | +| A **step turns red** during the run | The tool stopped on purpose, at the first error. | Do not click anything. Take a photo. Stop and ask. The people already done are kept. The **Next steps** page names the commands: continue the people already moved, move the others later, or roll the batch back. | +| The run ends with **Error** and says it was **interrupted** | The window or the black console was closed, or the run was stopped (Ctrl+C), before the end. What it did is kept: nothing is undone. | Do not start the move again. Read the **Next steps** page: it gives the command that goes on with the same batch. | +| A batch is marked **Partial: 3 of 10 converted** | The move stopped at its first error. Three people were moved and checked, the other seven were not moved. | Continue the batch to finish the three people. Move the others in a new move after the cause is fixed, or roll the whole batch back. Ask your administrator. | | A package line is red: **Invalid** | The file is damaged, comes from another environment, or its `.zip.sha256` file is not next to it. | Copy the `.zip` and the `.zip.sha256` files again, together in the same folder, without renaming them. Check that both servers have the same `Environment`. | | *Active Directory replication was NOT confirmed on …* | One directory server did not receive the change in time. | Read the **Next steps** page. It says to start the synchronisation again later. Ask your administrator. | | The result says **Pending** | A part remains. It is **not** an error. | Do what the **Next steps** page says. On two servers: carry the package to the other server. | diff --git a/package/module/PRA.Cloud.psm1 b/package/module/PRA.Cloud.psm1 index a2be455..027f625 100644 --- a/package/module/PRA.Cloud.psm1 +++ b/package/module/PRA.Cloud.psm1 @@ -422,7 +422,7 @@ function Get-PraNetworkFailure { $texts.Add([string]$e.Message) if ($e -is [System.Net.Sockets.SocketException] -or $e -is [TimeoutException] -or $e -is [System.Threading.Tasks.TaskCanceledException]) { $network=$true } elseif ($e -is [System.Net.Http.HttpRequestException] -and $null -eq $e.StatusCode) { $network=$true } - elseif ($e -is [System.Net.WebException] -and ([string]$e.Status) -match '^(ConnectFailure|NameResolutionFailure|Timeout|ConnectionClosed|ReceiveFailure|SendFailure|ProxyNameResolutionFailure|KeepAliveFailure)$') { $network=$true } + elseif ($e -is [System.Net.WebException] -and ([string]$e.Status) -match '^(ConnectFailure|NameResolutionFailure|Timeout|ConnectionClosed|ReceiveFailure|SendFailure|ProxyNameResolutionFailure|KeepAliveFailure)\z') { $network=$true } if ($e -is [AggregateException]) { foreach ($inner in $e.InnerExceptions) { $queue.Enqueue($inner) } } elseif ($null -ne $e.InnerException) { $queue.Enqueue($e.InnerException) } } @@ -771,7 +771,9 @@ function Close-PraCloudSession { function Get-PraPermissionRequest { param([hashtable]$Context,$Row) if (-not [bool](Get-PraValue $Row 'IsShared' $false)) { return } - $cfg = Get-PraValue $Context.Config 'SharedMailbox' @{} + # The settings stored in the batch by the Convert run decide; a batch that has none follows the configuration of this server. + $cfg = Get-PraValue $Context 'BatchGrantSettings' $null + if ($null -eq $cfg) { $cfg = Get-PraValue $Context.Config 'SharedMailbox' @{} } if (-not [bool](Get-PraValue $cfg 'Enabled' $false)) { return } foreach ($right in @('FullAccess','SendAs','SendOnBehalf')) { if ((-not (Test-PraOrdinalIgnoreCaseEqual $right 'SendOnBehalf')) -and (Test-PraOrdinalIgnoreCaseEqual (Get-PraValue $cfg 'PermissionSource' 'None') 'None')) { continue } @@ -1064,6 +1066,22 @@ function Invoke-PraCloudPhase { Write-PraCloudError -Context $Context -Row $row -Message 'Invalid keep flags (PreserveCloudMailbox is for shared mailboxes only).' -RunError; continue } $requests=@(); if ((Test-PraOrdinalIgnoreCaseEqual $Act 'Convert')) { $requests=@(Get-PraPermissionRequest $Context $row) } + # A permission that the record carries and the settings in effect do not grant is never silent: a warning names it (the result is "done with warnings"), + # and the row says it is to grant by hand (report and CSV). + if ($shared -and (Test-PraOrdinalIgnoreCaseEqual $Act 'Convert')) { + $notGranted=New-Object 'System.Collections.Generic.List[string]' + foreach ($right in @('FullAccess','SendAs','SendOnBehalf')) { + foreach ($trustee in @((Get-PraValue $row ('Shared'+$right) @()) | Where-Object { -not [string]::IsNullOrWhiteSpace([string]$_) } | Get-PraOrdinalUnique -IgnoreCase)) { + if (-not @($requests | Where-Object { (Test-PraOrdinalEqual $_.Right $right) -and (Test-PraOrdinalIgnoreCaseEqual $_.Trustee ([string]$trustee)) }).Count) { $notGranted.Add(('{0} {1}' -f $right,[string]$trustee)) } + } + } + if ($notGranted.Count) { + $whose=if (Test-PraOrdinalIgnoreCaseEqual ([string](Get-PraValue $Context 'GrantSettingsSource' 'Configuration')) 'Batch') { 'the settings the batch was converted with' } else { 'the settings of this server (this batch does not record its own)' } + $note=('{0}: {1} shared mailbox permission(s) not granted by {2} - to grant by hand: {3}.' -f $upn,$notGranted.Count,$whose,($notGranted -join '; ')) + $row.Warnings=([string](Get-PraValue $row 'Warnings' '') + '; ' + $note).Trim(' ',';') + $null=Write-PraLog -Context $Context -Message ($note + ' They are in the backup file and in the report.') -Level Warning + } + } $mb=([bool](Get-PraValue $cloud 'CheckMailbox' $false) -or (Test-PraOrdinalIgnoreCaseEqual $Act 'Recover') -or $requests.Count -gt 0) $lic=-not $shared -and [bool](Get-PraValue $cloud 'CheckLicense' $false) if (-not $mb -and -not $lic) { @@ -1087,6 +1105,8 @@ function Invoke-PraCloudPhase { } } $graphMailbox=$mb -and -not $shared -and (Test-PraOrdinalIgnoreCaseEqual $via 'Graph') + # The object is waited for from here on: it is not done until the checks below say so. + $row.FinalStatus='Pending' $exoMailbox=$mb -and ((Test-PraOrdinalIgnoreCaseEqual $Act 'Recover') -or $shared -or (Test-PraOrdinalIgnoreCaseEqual $via 'Exo')) $needGraph=$needGraph -or $lic -or $graphMailbox; $needExo=$needExo -or $exoMailbox [void]$states.Add(@{ Row=$row; Upn=$upn; Shared=$shared; Mailbox=$mb; License=$lic; GraphMailbox=$graphMailbox diff --git a/package/module/PRA.Common.psm1 b/package/module/PRA.Common.psm1 index 36724b0..75dec40 100644 --- a/package/module/PRA.Common.psm1 +++ b/package/module/PRA.Common.psm1 @@ -53,6 +53,7 @@ $script:ToolVersion = '3.1.4' $script:TranscriptOwner = $null $script:PraNativePath = $null $script:PraNativeProcess = $null +$script:PraEventWriteWarned = $false # Columns of the CSV report, in this order (also the fields copied from each result row). $script:RowFields = @('ObjectGuid','SamAccountName','UserPrincipalName','Action','IsShared','ADApplied','ADVerified', 'GroupAction','BackupPath','LastOperation','CloudMailbox','CloudLicense','CloudStatus','CloudDetail','PreserveCloudMailbox', @@ -226,6 +227,8 @@ function Get-PraCloudModuleReport { $Available = @(Get-Module -ListAvailable -Name 'Microsoft.Graph.Authentication', 'Microsoft.Graph.Users', 'ExchangeOnlineManagement' -SkipEditionCheck -ErrorAction SilentlyContinue) } if (-not $PSBoundParameters.ContainsKey('Loaded')) { $Loaded = @(Get-Module -Name 'Microsoft.Graph.*' -ErrorAction SilentlyContinue) } + # The built-in minimum is the floor: a lower value in the configuration does not lower it. + if ([version]$MinExo -lt [version]$script:PraMinExoVersion) { $MinExo = $script:PraMinExoVersion } $minGraphVersion = [version]$MinGraph; $minExoVersion = [version]$MinExo $versionsOf = { param([object[]]$Modules, [string]$Name) @@ -457,24 +460,69 @@ function Add-PraWarning { }) } +function ConvertTo-PraPlainMessage { + <# + .SYNOPSIS + The text of an error without its stack: the lines "at Namespace.Type.Method(...)", "at , file: line N" and "--- End of ... stack trace ---" are removed. + The card, the console and the report show this text; the log keeps the whole detail. The empty parts that Exchange Online puts between its separators ("||You can't use...") + are removed too, so that no stray pipe is shown. + #> + [CmdletBinding()] + param([AllowNull()][AllowEmptyString()][string]$Text) + if ([string]::IsNullOrEmpty($Text)) { return '' } + $frame = '^\s*(at\s+(<[^>\r\n]+>|[^\s(,]+\([^\r\n]*|[^\s,]+,\s+[^\r\n]*?\bline\s+\d+[^\r\n]*)|---\s*End of [^\r\n]*---)\s*$' + $kept = @([regex]::Split($Text, '\r?\n') | Where-Object { $_ -notmatch $frame }) + $plain = ($kept -join [Environment]::NewLine).TrimEnd() + $plain = [regex]::Replace($plain, '\|(?:[ \t]*\|)+', '|') + $plain = [regex]::Replace($plain, '(?m)^[ \t]*\|[ \t]*|(?<=:[ \t]+)\|[ \t]*', '') + return ([regex]::Replace($plain, '(?m)[ \t]*\|[ \t]*(?=\r?$)', '')) +} + +function Test-PraOwnEntryProcess { + <# + .SYNOPSIS + True when this PowerShell process was started for one script or one command (pwsh -File, -Command or -EncodedCommand, without -NoExit): the console's child + process, a scheduled task, a batch file. False for an interactive session where the operator typed the command: its window must never be closed by the run. + .PARAMETER Arguments + The command line of the process (the first item is the program); the process's own when not given. + #> + [CmdletBinding()] + [OutputType([bool])] + param([string[]]$Arguments = [Environment]::GetCommandLineArgs()) + $own = $false + for ($i = 1; $i -lt $Arguments.Count; $i++) { + $argument = [string]$Arguments[$i] + if ($argument.Length -lt 2 -or -not ($argument.StartsWith('-', [StringComparison]::Ordinal) -or $argument.StartsWith('/', [StringComparison]::Ordinal))) { continue } + $name = $argument.TrimStart('-', '/') + if (Test-PraOrdinalIn $name @('noexit', 'noe') -IgnoreCase) { return $false } + if (Test-PraOrdinalIn $name @('file', 'f', 'command', 'c', 'commandwithargs', 'cwa', 'encodedcommand', 'e', 'ec') -IgnoreCase) { $own = $true } + } + return $own +} + function Write-PraEvent { - <# Optional JSONL channel to the window; CLI runs without PRA_EVENT_FILE are unchanged. #> + <# Optional JSONL channel to the window; CLI runs without PRA_EVENT_FILE are unchanged. A line that cannot be written (another program holds the file) never stops the run: it is tried three times, the first failure of the run is said once on the console. #> [CmdletBinding()] param([Parameter(Mandatory)][ValidateSet('start','step','item','summary','result','plan','progress','count')][string]$Kind, [hashtable]$Data = @{}) if (-not $env:PRA_EVENT_FILE) { return } $record = [ordered]@{ time = [datetime]::UtcNow.ToString('o'); kind = $Kind } foreach ($key in $Data.Keys) { $record[$key] = $Data[$key] } $line = ($record | ConvertTo-Json -Compress -Depth 8) + "`n" + $reason = '' for ($attempt = 1; $attempt -le 3; $attempt++) { try { [IO.File]::AppendAllText($env:PRA_EVENT_FILE, $line, (New-Object Text.UTF8Encoding($false))) return } - catch [IO.IOException] { - if ($attempt -eq 3) { throw } - Start-Sleep -Milliseconds 50 + catch { + $reason = [string]$_.Exception.Message + if ($attempt -lt 3) { Start-Sleep -Milliseconds 50 } } } + if (-not $script:PraEventWriteWarned) { + $script:PraEventWriteWarned = $true + try { Write-PraHost @(' ', (Get-PraIcon 'Warn'), ('The progress file of the window cannot be written ({0}): the run goes on, the window may miss some events.' -f $reason)) -Color $script:Theme.Warn } catch { $null = $_ } + } } function Get-PraStepId { @@ -557,7 +605,7 @@ function Write-PraLog { if ((Test-PraOrdinalIgnoreCaseEqual $Level 'Warning')) { $Context.Warnings = [int](Get-PraValue $Context 'Warnings' 0) + 1; Add-PraWarning $Context $Message } if ((Test-PraOrdinalIgnoreCaseEqual $Level 'Error')) { Add-PraIssue $Context $Message } Write-PraLogFile -Context $Context -Level $logLevel -Message $Message - $text = $Message -replace '[\r\n]+', ' | ' + $text = (ConvertTo-PraPlainMessage $Message) -replace '[\r\n]+', ' | ' switch ($Level) { 'Debug' { $verbose = [bool](Get-PraValue $Context 'VerboseEnabled' ((Test-PraOrdinalIgnoreCaseEqual $VerbosePreference 'Continue'))) @@ -909,7 +957,7 @@ function Get-PraPhysicalPath { if (@($full.Split('\') | Select-Object -Skip 3 | Where-Object { [string]::Equals($_, '.', [StringComparison]::Ordinal) -or [string]::Equals($_, '..', [StringComparison]::Ordinal) }).Count) { throw "Path $Path uses a device namespace with relative segments; it cannot be resolved safely." } } $existing = $full.TrimEnd('\') - if ($existing -match '^[A-Za-z]:$' -or $existing -match '^\\\\[?.]\\[A-Za-z]:$') { $existing += '\' } + if ($existing -match '^[A-Za-z]:\z' -or $existing -match '^\\\\[?.]\\[A-Za-z]:\z') { $existing += '\' } $missing = New-Object Collections.Generic.List[string] while (-not ([IO.Directory]::Exists($existing) -or [IO.File]::Exists($existing))) { $parent = [IO.Path]::GetDirectoryName($existing) @@ -1362,6 +1410,9 @@ function Get-PraOutcome { $runErrors = 0 # A run refused before any change (Entra Connect check, cloud modules, domain controller refusing the account) touched no object: only its error is a result row. $untouched = [bool](Get-PraValue $Context 'NoChangeMade' $false) + # In an Apply whose batch exists (its backup is written), an object still Planned when the run ends is not done: it is Pending, never counted as a success or as skipped. + $appliesChanges = (Test-PraOrdinalIgnoreCaseEqual ([string](Get-PraValue $Context 'Mode' '')) 'Apply') -and (Test-PraOrdinalIn ([string](Get-PraValue $Context 'Action' '')) @('Convert', 'Recover', 'Finalize') -IgnoreCase) -and + ([bool](Get-PraValue $Context 'ChangesStarted' $false) -or -not [string]::IsNullOrEmpty([string](Get-PraValue $Context 'BatchId' ''))) foreach ($row in $(if ($untouched) { @() } else { $Context.Rows.ToArray() })) { $copy = [ordered]@{} # Same lookup as Get-PraValue (missing and $null both give $null), inlined: this loop runs 22 times per row on very large runs. @@ -1375,6 +1426,10 @@ function Get-PraOutcome { if (-not (Test-PraOrdinalIn $copy.FinalStatus $script:FinalStatuses)) { $copy.Detail = 'Final status missing or invalid: {0}. {1}' -f $copy.FinalStatus, $copy.Detail; $copy.FinalStatus = 'Error' } + elseif ($appliesChanges -and (Test-PraOrdinalEqual $copy.FinalStatus 'Planned')) { + $copy.FinalStatus = 'Pending' + if (-not $copy.Detail) { $copy.Detail = 'not finished: the run ended before this object was done; the next steps say how to go on' } + } if (Test-PraOrdinalEqual $copy.FinalStatus 'Error') { foreach ($field in @('ObjectGuid','SamAccountName','UserPrincipalName')) { if ($copy[$field]) { $errorIdentities[[string]$copy[$field]] = $true } } if ([bool](Get-PraValue $row 'RunError' $false)) { $runErrors++ } @@ -1719,6 +1774,13 @@ function Complete-PraRun { if (([int]$Context.ExitCode -ne 0 -or $Context.CloudConnectFailed -or (Test-PraOrdinalIgnoreCaseEqual (Get-PraValue $Context 'ResultStatus' '') 'Failed')) -and $Context.Issues.Count -eq 0 -and -not [bool](Get-PraValue $Context 'Cancelled' $false)) { Add-PraIssue $Context 'Failure reported by the run (exit code / cloud connection).' 'Run' } + # No stack line reaches the card, the console or the report: the log holds the whole detail. + foreach ($entry in @($Context.Issues.ToArray()) + @(@(Get-PraValue $Context 'WarningList' @()) | ForEach-Object { $_ })) { + if ($entry -is [pscustomobject] -and $entry.PSObject.Properties['Message']) { + $plain = ConvertTo-PraPlainMessage ([string]$entry.Message) + if (-not [string]::Equals($plain, [string]$entry.Message, [StringComparison]::Ordinal)) { $entry.Message = $plain } + } + } foreach ($key in @('LogFile','TranscriptPath','BackupFiles','StateFiles')) { $candidates = Get-PraValue $Context $key if ((Test-PraOrdinalIn $key @('LogFile','TranscriptPath') -IgnoreCase)) { $candidates = [string]$candidates } @@ -2347,14 +2409,14 @@ function Get-PraConfigurationFlat { } function Get-PraConfigurationDifference { - <# What the run changes compared with the configuration file: one object (Key, Base, Effective, Text = 'Key: base -> effective') per setting whose value differs. #> + <# What the run changes compared with the configuration file: one object (Key, Base, Effective, Text = 'Key: base -> effective') per setting whose value differs (the letter case is not a difference). #> [CmdletBinding()] param([Parameter(Mandatory)][Collections.IDictionary]$Base, [Parameter(Mandatory)][Collections.IDictionary]$Effective) $baseFlat = @{} foreach ($row in @(Get-PraConfigurationFlat -Configuration $Base)) { $baseFlat[$row.Key] = $row.Value } foreach ($row in @(Get-PraConfigurationFlat -Configuration $Effective)) { $before = if ($baseFlat.ContainsKey($row.Key)) { [string]$baseFlat[$row.Key] } else { '' } - if (-not (Test-PraOrdinalEqual $before $row.Value)) { + if (-not (Test-PraOrdinalIgnoreCaseEqual $before $row.Value)) { $beforeText = if ($before) { $before } else { '(empty)' }; $afterText = if ($row.Value) { $row.Value } else { '(empty)' } [pscustomobject][ordered]@{ Key = $row.Key; Base = $before; Effective = $row.Value; Text = ('{0}: {1} -> {2}' -f $row.Key, $beforeText, $afterText) } } @@ -2693,7 +2755,7 @@ function Get-PraGlobalModel { The data of the global report: the phases of the batch (earlier phases read from the PhaseData files of $Context.PhaseFolders, then this run), and one entry per object with its stage in each phase, its journey across the servers and its verdict. .DESCRIPTION - Verdict: failed when any phase failed it; otherwise pending when its last stage is Pending (it is expected on a later side, or it was + Verdict: failed when any phase failed it (the cloud error of a stage that did both sides is replaced by a later stage that covers the cloud side); otherwise pending when its last stage is Pending (it is expected on a later side, or it was filtered out there); skipped; done with warnings when a warning was raised; otherwise done. A side that was not carried is listed as not available. #> [CmdletBinding()] @@ -2782,12 +2844,12 @@ function Get-PraGlobalModel { $stage = $same[0] $earlierResult = [ordered]@{ Time = ''; Step = 'Earlier run'; Status = 'Info'; Text = (Limit-PraText (('{0} - {1}' -f $stage.Status, $stage.Detail).Trim(' ', '-')) 300) } $warnings = (@($stage.Warnings, [string](Get-PraValue $item 'Warnings' '')) | Where-Object { $_ } | Get-PraOrdinalUnique) -join ' | ' - $stage.Status = [string](Get-PraValue $item 'FinalStatus' ''); $stage.Detail = [string](Get-PraValue $item 'Detail' ''); $stage.Warnings = $warnings + $stage.Status = [string](Get-PraValue $item 'FinalStatus' ''); $stage.Detail = [string](Get-PraValue $item 'Detail' ''); $stage.Warnings = $warnings; $stage.ADVerified = ((Get-PraValue $item 'ADVerified' $null) -eq $true) $stage.Steps = @(@($stage.Steps) + @($earlierResult) + @(Get-PraList $item 'Steps')) continue } [void]$entry.Stages.Add([pscustomobject]@{ Phase = $stagePhase; Present = $true; HandedOverTo = ''; StatusDisplay = ''; Status = [string](Get-PraValue $item 'FinalStatus' ''); Detail = [string](Get-PraValue $item 'Detail' ''); Warnings = [string](Get-PraValue $item 'Warnings' '') - Steps = @(Get-PraList $item 'Steps') }) + ADVerified = ((Get-PraValue $item 'ADVerified' $null) -eq $true); Superseded = $false; Steps = @(Get-PraList $item 'Steps') }) } } $verdicts = @{ Done = 0; Warn = 0; Failed = 0; Pending = 0; Skipped = 0 } @@ -2796,9 +2858,23 @@ function Get-PraGlobalModel { $staged = New-Object 'Collections.Generic.List[object]' foreach ($phase in $stagePhases) { $stage = @($entry.Stages | Where-Object { [object]::ReferenceEquals($_.Phase, $phase) }) - if ($stage.Count) { $staged.Add($stage[0]) } else { $staged.Add([pscustomobject]@{ Phase = $phase; Present = $false; HandedOverTo = ''; StatusDisplay = ''; Status = ''; Detail = ''; Warnings = ''; Steps = @() }) } + if ($stage.Count) { $staged.Add($stage[0]) } else { $staged.Add([pscustomobject]@{ Phase = $phase; Present = $false; HandedOverTo = ''; StatusDisplay = ''; Status = ''; Detail = ''; Warnings = ''; ADVerified = $false; Superseded = $false; Steps = @() }) } } $entry.Stages = $staged + # An error of the cloud part of a stage that did both sides (its AD part was verified) is not final when a later stage of the same operation covers the cloud side for this object: + # that stage replaces the cloud result, and the earlier error stays in its journey as an "Earlier run" line. + for ($i = 0; $i -lt $staged.Count; $i++) { + $stage = $staged[$i] + if (-not $stage.Present -or -not (Test-PraOrdinalEqual $stage.Status 'Error') -or -not $stage.ADVerified -or -not (Test-PraOrdinalEqual ([string](Get-PraValue $stage.Phase.Header 'Phase' '')) 'Both')) { continue } + for ($j = $i + 1; $j -lt $staged.Count; $j++) { + $later = $staged[$j] + if (-not $later.Present -or -not (Test-PraOrdinalEqual ([string](Get-PraValue $later.Phase.Header 'Action' '')) ([string](Get-PraValue $stage.Phase.Header 'Action' ''))) -or + -not (Test-PraOrdinalIn ([string](Get-PraValue $later.Phase.Header 'Phase' '')) @('Cloud', 'Both'))) { continue } + $stage.Superseded = $true + $later.Steps = @([ordered]@{ Time = ''; Step = 'Earlier run'; Status = 'Info'; Text = (Limit-PraText (('{0} - {1}' -f $stage.Status, $stage.Detail).Trim(' ', '-')) 300) }) + @($later.Steps) + break + } + } # Display only: a Pending stage that a later phase lists for this object reads "Handed over" (it is Pending when no later phase lists it). for ($i = 0; $i -lt $staged.Count; $i++) { $stage = $staged[$i] @@ -2811,7 +2887,7 @@ function Get-PraGlobalModel { } $present = @($staged | Where-Object { $_.Present }) $last = $present[$present.Count - 1] - $failedAnywhere = @($present | Where-Object { Test-PraOrdinalEqual $_.Status 'Error' }).Count -gt 0 + $failedAnywhere = @($present | Where-Object { (Test-PraOrdinalEqual $_.Status 'Error') -and -not $_.Superseded }).Count -gt 0 $warned = @($present | Where-Object { $_.Warnings.Trim() -or @($_.Steps | Where-Object { Test-PraOrdinalEqual (Get-PraValue $_ 'Status' '') 'Warn' }).Count }).Count -gt 0 $lastStage = $staged[$staged.Count - 1] if ($failedAnywhere) { $entry.Verdict = 'failed' } @@ -3039,7 +3115,7 @@ function Write-PraGlobalReport { #endregion Export-ModuleMember -Function Register-PraObjectName, Get-PraList, Register-PraObjectBackup, Save-PraPhaseData, Copy-PraPhaseData, Read-PraPhaseData, New-PraPhaseRecord, Get-PraGlobalModel, Write-PraGlobalReport, Write-PraGlobalReportHtml, Write-PraGlobalReportCsv, Test-PraGlobalReportWanted, Limit-PraText, Get-PraEventObjectName, Test-PraOrdinalEqual, Test-PraOrdinalIgnoreCaseEqual, Test-PraOrdinalIn, Test-PraOrdinalIgnoreCaseIn, Get-PraOrdinalSorted, Get-PraOrdinalUnique, Compare-PraX500Address, ConvertFrom-PraJson, Get-PraNativeProcessApi, Read-PraCsvText, Get-PraToolVersion, Get-PraCloudModuleReport, New-PraPrivateDirectorySecurity, Initialize-PraPrivateFolder, ConvertTo-PraCsvCell, Get-PraValue, Format-PraDuration, Add-PraIssue, Write-PraLog, Write-PraItem, Write-PraBanner, Write-PraStep, - Write-PraSummary, Write-PraHost, Resolve-PraPath, Import-PraConfiguration, Test-PraScopeConfiguration, Initialize-PraAudit, Get-PraOutcome, Complete-PraRun, Write-PraEvent, Get-PraWin32ErrorText, Get-PraTargetOverride, Read-PraTargetCsv, Write-PraProgress, Get-PraTransferPackageName, Get-PraTransferPackage, Import-PraTransferPackage, New-PraTransferPackage, New-PraEffectiveConfiguration, Get-PraConfigurationDifference + Write-PraSummary, Write-PraHost, Resolve-PraPath, Import-PraConfiguration, Test-PraScopeConfiguration, Initialize-PraAudit, Get-PraOutcome, Complete-PraRun, Write-PraEvent, Get-PraWin32ErrorText, Test-PraOwnEntryProcess, Get-PraTargetOverride, Read-PraTargetCsv, Write-PraProgress, Get-PraTransferPackageName, Get-PraTransferPackage, Import-PraTransferPackage, New-PraTransferPackage, New-PraEffectiveConfiguration, Get-PraConfigurationDifference # SIG # Begin signature block # MIImKgYJKoZIhvcNAQcCoIImGzCCJhcCAQExDzANBglghkgBZQMEAgEFADB5Bgor diff --git a/package/module/PRA.Directory.psm1 b/package/module/PRA.Directory.psm1 index c600a1e..5a379d0 100644 --- a/package/module/PRA.Directory.psm1 +++ b/package/module/PRA.Directory.psm1 @@ -449,7 +449,7 @@ function Get-PraUsn { [CmdletBinding()] param($User) $value = Get-PraValue $User 'uSNChanged' $null - if ($null -eq $value -or [string]$value -notmatch '^[0-9]+$' -or [int64]$value -le 0) { throw 'uSNChanged missing or invalid: the AD version of the object cannot be proven.' } + if ($null -eq $value -or [string]$value -notmatch '^[0-9]+\z' -or [int64]$value -le 0) { throw 'uSNChanged missing or invalid: the AD version of the object cannot be proven.' } return ([int64]$value).ToString([Globalization.CultureInfo]::InvariantCulture) } @@ -515,7 +515,7 @@ function Find-PraConvertedBatch { $environment = [string]$Context.Config.Environment $candidates = New-Object 'Collections.Generic.List[object]' $rolledBack = New-Object 'Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase) - foreach ($folder in @(Get-ChildItem -LiteralPath $root -Directory -Recurse -ErrorAction Stop | Where-Object { $_.Name -match '^(Batch|Finalize)-[0-9a-f]{32}$' })) { + foreach ($folder in @(Get-ChildItem -LiteralPath $root -Directory -Recurse -ErrorAction Stop | Where-Object { $_.Name -match '^(Batch|Finalize)-[0-9a-f]{32}\z' })) { foreach ($stateFile in @(Get-ChildItem -LiteralPath $folder.FullName -File -Filter 'State-*.json' -ErrorAction Stop)) { try { $state = Get-Content -LiteralPath $stateFile.FullName -Raw -Encoding UTF8 -ErrorAction Stop | ConvertFrom-PraJson } catch { continue } $stateEnvironment = [string](Get-PraValue $state 'Environment' '') @@ -553,6 +553,89 @@ function Find-PraConvertedBatch { return $null } +function Get-PraJournalTouchedObject { + <# + .SYNOPSIS + The objects (GUIDs, ignoring the case) that the journal of a batch shows as written or about to be written: a Started or Applied line of an AD write. + An object that has such a line may be changed, whatever the batch proved. A missing or unreadable journal gives an empty set. + #> + [CmdletBinding()] + param([string]$Path) + $set = New-Object 'Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase) + if (-not $Path -or -not [IO.File]::Exists($Path)) { return , $set } + try { + foreach ($line in [IO.File]::ReadLines($Path)) { + if (-not ($line.Contains('"Status":"Started"') -or $line.Contains('"Status":"Applied"'))) { continue } + $entry = $line | ConvertFrom-PraJson + if (Test-PraOrdinalIn ([string](Get-PraValue $entry 'Operation' '')) @('Set-ADUser', 'Add-ADGroupMember', 'Remove-ADGroupMember')) { + $target = [string](Get-PraValue $entry 'Target' '') + if ($target -and -not (Test-PraOrdinalEqual $target '*')) { [void]$set.Add($target) } + } + } + } + catch { $null = $_ } + return , $set +} + +function Find-PraRecoverOfBatch { + <# + .SYNOPSIS + The Recover batch that rolled back, or started to roll back, objects of a Convert batch. $null when there is none. + .DESCRIPTION + First the State files (the AD proof of a Recover): the one that names the Convert backup (SourceBackupHash) and lists at least one of the objects given + (any object when none is given). Then the Recover backups that have no State file (a Recover that stopped before its proof): the objects that its journal + shows as written or about to be written count as rolled back; a journal that is missing counts for every object. Basis says which: State, Journal or Unknown. + A batch of another Environment is ignored. + #> + [CmdletBinding()] + param([hashtable]$Context, [Parameter(Mandatory)][string]$SourceHash, [string[]]$ObjectGuid = @()) + try { + $root = [string]$Context.Config.Storage.BackupFolder + if (-not $root -or -not (Test-Path -LiteralPath $root -PathType Container)) { return $null } + $environment = [string]$Context.Config.Environment + foreach ($folder in @(Get-ChildItem -LiteralPath $root -Directory -Recurse -ErrorAction Stop | Where-Object { $_.Name -match '^(Batch|Finalize)-[0-9a-f]{32}\z' })) { + $withState = New-Object 'Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase) + foreach ($stateFile in @(Get-ChildItem -LiteralPath $folder.FullName -File -Filter 'State-*.json' -ErrorAction Stop)) { + $id = [regex]::Match($stateFile.Name, '^State-(?[0-9a-fA-F]{32})\.json\z').Groups['id'].Value + if ($id) { [void]$withState.Add($id) } + try { $state = Get-Content -LiteralPath $stateFile.FullName -Raw -Encoding UTF8 -ErrorAction Stop | ConvertFrom-PraJson } catch { continue } + if (-not (Test-PraOrdinalEqual ([string](Get-PraValue $state 'Operation' '')) 'Recover')) { continue } + $stateEnvironment = [string](Get-PraValue $state 'Environment' '') + if ($stateEnvironment -and -not (Test-PraOrdinalIgnoreCaseEqual $stateEnvironment $environment)) { continue } + if (-not (Test-PraOrdinalIgnoreCaseEqual ([string](Get-PraValue $state 'SourceBackupHash' '')) $SourceHash)) { continue } + $stateRecords = Get-PraValue $state 'Records' @() + $listed = @($stateRecords | ForEach-Object { [string]$_.ObjectGuid }) + if ($ObjectGuid.Count -and -not @($ObjectGuid | Where-Object { Test-PraOrdinalIn $_ $listed -IgnoreCase }).Count) { continue } + if (-not $id) { continue } + return [pscustomobject]@{ BatchId = $id.ToLowerInvariant(); ShortId = $id.Substring(0, 8).ToLowerInvariant(); Folder = $folder.FullName; Basis = 'State' } + } + foreach ($backupFile in @(Get-ChildItem -LiteralPath $folder.FullName -File -Filter 'Recover-*.json' -ErrorAction Stop)) { + # The head of the file holds the fields that tell the batch (they come before the records). + $stream = [IO.File]::Open($backupFile.FullName, [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) } finally { $stream.Dispose() } + if ($head -notmatch '"Operation":\s*"Recover"') { continue } + $headHash = [regex]::Match($head, '"SourceBackupHash":\s*"(?[0-9a-fA-F]+)"').Groups['h'].Value + if (-not (Test-PraOrdinalIgnoreCaseEqual $headHash $SourceHash)) { continue } + $headEnvironment = [regex]::Match($head, '"Environment":\s*"(?[^"]*)"').Groups['e'].Value + if ($headEnvironment -and -not (Test-PraOrdinalIgnoreCaseEqual $headEnvironment $environment)) { continue } + $id = [regex]::Match($head, '"BatchId":\s*"(?[0-9a-fA-F]{32})"').Groups['i'].Value + if (-not $id -or $withState.Contains($id)) { continue } + $journal = Join-Path $folder.FullName ('Journal-' + $id + '.jsonl') + $basis = 'Journal' + if (-not [IO.File]::Exists($journal)) { $basis = 'Unknown' } + else { + $touched = Get-PraJournalTouchedObject -Path $journal + if ($ObjectGuid.Count) { if (-not @($ObjectGuid | Where-Object { $touched.Contains($_) }).Count) { continue } } + elseif (-not $touched.Count) { continue } + } + return [pscustomobject]@{ BatchId = $id.ToLowerInvariant(); ShortId = $id.Substring(0, 8).ToLowerInvariant(); Folder = $folder.FullName; Basis = $basis } + } + } + } + catch { Write-PraLog -Context $Context -Message ('The backup folder could not be searched for a Recover batch: {0}' -f $_.Exception.Message) -Level Detail } + return $null +} + function Get-PraSkipReason { <# Plain reason why a user of a selected group is not converted. #> param($User, [bool]$Excluded) @@ -1002,13 +1085,13 @@ function Get-PraRoutingAddress { $address = if ($primary.Count) { $primary[0].Substring(5) } else { [string](Get-PraValue $User 'mail' '') } $local = if ($address) { ($address -split '@', 2)[0] } else { [string](Get-PraValue $User 'mailNickname' '') } if ($Context.Config.Routing.AutoDetect) { - $existing = @($proxies | Where-Object { $_ -imatch '^smtp:.+@.+\.mail\.onmicrosoft\.com$' } | ForEach-Object { $_.Substring(5) }) + $existing = @($proxies | Where-Object { $_ -imatch '^smtp:.+@.+\.mail\.onmicrosoft\.com\z' } | ForEach-Object { $_.Substring(5) }) $match = @($existing | Where-Object { (Test-PraOrdinalIgnoreCaseEqual (($_ -split '@', 2)[0]) $local) -and $_ -imatch "@$([regex]::Escape($domain))\z" }) if (-not $match.Count) { $match = @($existing | Where-Object { $_ -imatch "@$([regex]::Escape($domain))\z" }) } if ($match.Count -eq 1) { return [string]$match[0] } if ($match.Count -gt 1) { throw "Several routing addresses possible for $($User.SamAccountName): keep one proxy address in $domain." } } - if (-not $local -or $local -match '[\s@]' -or $domain -notmatch '^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$') { throw "No valid routing address for $($User.SamAccountName) (check Routing.RoutingDomain and the mail alias)." } + if (-not $local -or $local -match '[\s@]' -or $domain -notmatch '^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\z') { throw "No valid routing address for $($User.SamAccountName) (check Routing.RoutingDomain and the mail alias)." } return "$local@$domain" } @@ -1178,8 +1261,8 @@ function Resolve-PraAclTrustee { param([hashtable]$Context, $Reference, [Collections.Generic.List[string]]$Unknown) $sid = if ($Reference -is [Security.Principal.SecurityIdentifier]) { $Reference } else { $Reference.Translate([Security.Principal.SecurityIdentifier]) } # BUILTIN, NT AUTHORITY and Domain/Enterprise/Schema Admins are never reproduced. - if ($sid.Value -match '^S-1-5-32-' -or $sid.Value -match '^S-1-5-[0-9]+$' -or - $sid.Value -match '^S-1-5-21-[0-9]+-[0-9]+-[0-9]+-(512|518|519)$') { return } + if ($sid.Value -match '^S-1-5-32-' -or $sid.Value -match '^S-1-5-[0-9]+\z' -or + $sid.Value -match '^S-1-5-21-[0-9]+-[0-9]+-[0-9]+-(512|518|519)\z') { return } # Named accounts and groups (Organization Management, Exchange Trusted Subsystem, ...) are filtered by name once the SID is # resolved to its AD object (see $excludedGroups below); the ACE reference is a SID here, so a name pattern could never match. $cache = Get-PraPermissionCache -Context $Context @@ -1281,7 +1364,7 @@ function Get-PraSharedPermission { } CustomAttribute { $attr = [string]$settings.CustomAttribute - if ($attr -notmatch '^extensionAttribute([1-9]|1[0-5])$') { throw 'SharedMailbox.CustomAttribute is invalid.' } + if ($attr -notmatch '^extensionAttribute([1-9]|1[0-5])\z') { throw 'SharedMailbox.CustomAttribute is invalid.' } $filters = @(@((Get-PraValue $User 'mailNickname' ''), $User.SamAccountName, (Get-PraValue $User 'DisplayName' '')) | Where-Object { $_ } | Get-PraOrdinalUnique | ForEach-Object { "($attr=$(ConvertTo-PraLdapValue $_))" }) $groups = @(Get-ADGroup -LDAPFilter ('(|' + ($filters -join '') + ')') -Server $Context.Server -ErrorAction Stop) if ($groups.Count -ne 1) { throw "Permission group not found or not unique for $($User.SamAccountName) ($attr)." } @@ -1331,7 +1414,7 @@ function New-PraRow { UserPrincipalName=[string](Get-PraValue $Record 'UserPrincipalName' ''); Action=$Context.Action IsShared=[bool](Get-PraValue $Record 'IsShared' $false); ADApplied=$null; ADVerified=$null; GroupAction='' BackupPath=''; LastOperation=''; CloudMailbox=$null; CloudLicense=$null; CloudStatus='N/A'; CloudDetail='' - FinalStatus='Skipped'; Detail=''; SharedFullAccess=@(); SharedSendAs=@(); SharedSendOnBehalf=@(); PermMissing=@(); PermDetail=''; Warnings='' + FinalStatus='Planned'; Detail=''; SharedFullAccess=@(); SharedSendAs=@(); SharedSendOnBehalf=@(); PermMissing=@(); PermDetail=''; Warnings='' BackupRec=$Record; DeproPending=$false; RestoreDeferred=$false PreserveCloudMailbox=$false; PreserveLicense=$false; DeprovisionConfirmed=$false } @@ -1364,7 +1447,7 @@ function New-PraPlan { $tag = if ((Test-PraOrdinalIgnoreCaseEqual $Operation 'Convert')) { $config.Retention.Tag } else { Get-PraValue $SourceRecord 'Retention' $null } $tagEnabled = if ((Test-PraOrdinalIgnoreCaseEqual $Operation 'Convert')) { $config.Retention.Enabled -and $tag.Enabled } else { [bool](Get-PraValue $tag 'Enabled' $false) } $tagAttr = if ($tagEnabled) { [string]$tag.Attribute } else { '' } - if ($tagAttr -and $tagAttr -notmatch '^extensionAttribute([1-9]|1[0-5])$') { throw "Retention tag attribute not allowed: $tagAttr" } + if ($tagAttr -and $tagAttr -notmatch '^extensionAttribute([1-9]|1[0-5])\z') { throw "Retention tag attribute not allowed: $tagAttr" } if ((Test-PraOrdinalIgnoreCaseEqual $Operation 'RestoreTag') -and -not $tagEnabled) { throw 'The original value of the retention tag is not in the backup: tag clean-up refused.' } $kinds = [ordered]@{}; foreach ($name in $script:AttributeKinds.Keys) { $kinds[$name] = $script:AttributeKinds[$name] } if ($tagAttr) { $kinds[$tagAttr] = 'String' } @@ -1496,7 +1579,7 @@ function Assert-PraStoredRecord { $kinds = [ordered]@{}; foreach ($name in $script:AttributeKinds.Keys) { $kinds[$name] = $script:AttributeKinds[$name] } $retention = Get-PraValue $Record 'Retention' $null if ($null -ne $retention -and $retention.Enabled) { - if ($retention.Attribute -notmatch '^extensionAttribute([1-9]|1[0-5])$' -or $retention.Value -isnot [string]) { throw 'Backup: invalid retention tag metadata.' } + if ($retention.Attribute -notmatch '^extensionAttribute([1-9]|1[0-5])\z' -or $retention.Value -isnot [string]) { throw 'Backup: invalid retention tag metadata.' } $kinds[$retention.Attribute] = 'String' } foreach ($name in $kinds.Keys) { @@ -1527,7 +1610,7 @@ function Assert-PraStoredRecord { foreach ($value in @($expectedStored)) { if ($value -isnot [string] -or -not (Test-PraX500Address $value) -or $value.Length -gt $script:MaxExpectedX500Length) { throw 'Backup: invalid list of expected X500 addresses.' } } } if (-not $Legacy) { - if ($Record.CapturedUsnChanged -isnot [string] -or $Record.CapturedUsnChanged -notmatch '^[1-9][0-9]*$') { throw 'Backup: original uSNChanged missing or invalid.' } + if ($Record.CapturedUsnChanged -isnot [string] -or $Record.CapturedUsnChanged -notmatch '^[1-9][0-9]*\z') { throw 'Backup: original uSNChanged missing or invalid.' } $null = [int64]::Parse($Record.CapturedUsnChanged, [Globalization.CultureInfo]::InvariantCulture) if (-not (Test-PraOrdinalIn $Record.RequestedOperation @('Convert','Recover','Deprovision','RestoreTag','AlreadyRecovered'))) { throw 'Backup: invalid planned operation.' } if ($Record.PreserveCloudMailbox -isnot [bool] -or $Record.PreserveLicense -isnot [bool]) { throw 'Backup: invalid cloud post-conditions.' } @@ -1575,6 +1658,11 @@ function Import-PraBackup { $key = ([guid]$record.ObjectGuid).ToString() if ($seen.ContainsKey($key)) { throw "Same GUID twice in the backup: $key" }; $seen[$key] = $true } + $grant = Get-PraValue $data 'GrantSettings' $null + if ($null -ne $grant) { + if (-not (Test-PraOrdinalEqual $data.Operation 'Convert') -or (Get-PraValue $grant 'Enabled' $null) -isnot [bool] -or (Get-PraValue $grant 'GrantFullAccess' $null) -isnot [bool] -or (Get-PraValue $grant 'GrantSendAs' $null) -isnot [bool] -or + (Get-PraValue $grant 'GrantSendOnBehalf' $null) -isnot [bool] -or (Get-PraValue $grant 'PermissionSource' $null) -isnot [string] -or -not (Test-PraOrdinalIn ([string]$grant.PermissionSource) @('AD', 'Csv', 'CustomAttribute', 'None') -IgnoreCase)) { throw 'Backup: invalid shared mailbox grant settings.' } + } $hash = Get-PraHash $pathResolved if (-not (Test-PraOrdinalEqual $hash $hashBeforeRead)) { throw 'Backup JSON changed while it was read.' } $rawPath = ''; $rawHash = '' @@ -1640,6 +1728,17 @@ function Assert-PraRecordMatchesPlan { } } +function Get-PraGrantSettingSnapshot { + <# The settings that decide which shared mailbox permissions the cloud phase grants, as the Convert run had them: stored in the batch, so that the cloud phase of any server follows the batch. #> + [CmdletBinding()] + param([Parameter(Mandatory)][hashtable]$Context) + $shared = Get-PraValue $Context.Config 'SharedMailbox' @{} + return [ordered]@{ + Enabled = [bool](Get-PraValue $shared 'Enabled' $false); PermissionSource = [string](Get-PraValue $shared 'PermissionSource' 'None') + GrantFullAccess = [bool](Get-PraValue $shared 'GrantFullAccess' $false); GrantSendAs = [bool](Get-PraValue $shared 'GrantSendAs' $false); GrantSendOnBehalf = [bool](Get-PraValue $shared 'GrantSendOnBehalf' $false) + } +} + function Save-PraBatch { <# .SYNOPSIS @@ -1670,6 +1769,7 @@ function Save-PraBatch { RawFile=[IO.Path]::GetFileName($rawPath); RawHash=(Get-PraHash $rawPath) SourceBackupHash=$Context.SourceBackupHash; Records=@($Plans | ForEach-Object { $_.Record }) } + if ((Test-PraOrdinalEqual $Operation 'Convert')) { $data['GrantSettings'] = Get-PraGrantSettingSnapshot -Context $Context } $Context.CurrentOperation = 'Write-BackupJson' $json = $data | ConvertTo-Json -Depth 30 Write-PraImmutableFile $path $json @@ -1685,6 +1785,8 @@ function Save-PraBatch { Assert-PraRecordMatchesPlan -Stored $record -Expected $Plans[$i].Record } $Context.BackupFiles.Add($path) + $Context.ChangesStarted = $true + if ((Test-PraOrdinalIn $Operation @('Convert', 'Recover'))) { $Context.BatchId = $id.Substring(0, 8) } $Context.JournalPath = Join-Path $directory ('Journal-' + $id + '.jsonl') Write-PraImmutableFile $Context.JournalPath '' $Context.StateFiles.Add($Context.JournalPath) @@ -1807,7 +1909,7 @@ function Invoke-PraAdBatch { if ([bool](Get-PraValue $Context 'OperationFailed' $false) -or $Context.Issues.Count -gt 0 -or @($Context.Rows | Where-Object FinalStatus -eq 'Error').Count -gt 0) { throw 'No new batch after an error in this run.' } if (-not $Plans.Count) { Write-PraItem -Context $Context -Status Skip -Text 'Nothing to do.'; return $null } foreach ($plan in $Plans) { if (-not $Context.Rows.Contains($plan.Row)) { $Context.Rows.Add($plan.Row) } } - $receipt = $null + $receipt = $null; $stateWritten = $false try { foreach ($plan in $Plans) { if (-not [bool](Get-PraValue $plan 'Previewed' $false)) { Write-PraAdDelta -Context $Context -Plan $plan -Stage Planned } } if (-not $Context.AllowMutation -or (-not (Test-PraOrdinalIgnoreCaseEqual $Context.Mode 'Apply')) -or (Test-PraOrdinalIgnoreCaseEqual $Context.Action 'Check') -or $WhatIfPreference) { @@ -1848,7 +1950,9 @@ function Invoke-PraAdBatch { else { $plan.Row.GroupAction = if ($groupState.Enabled) { 'Preserved' } else { 'N/A' } } Assert-PraCurrentState $Context $plan $plan.Desired $groupState.DesiredMember $plan.Row.ADVerified = $true; $plan.Row.ADApplied = $changed; $plan.Row.LastOperation = 'ADVerified' - $plan.Row.FinalStatus = if ($plan.Row.DeproPending) { 'Pending' } elseif ($changed) { 'Success' } else { 'AlreadyDone' } + # Phase Both: the object is Pending from its verification on, until the cloud part confirms it. + $awaitsCloud = (Test-PraOrdinalIgnoreCaseEqual ([string](Get-PraValue $Context 'Phase' '')) 'Both') -and (Test-PraOrdinalIn $Operation @('Convert', 'Recover')) + $plan.Row.FinalStatus = if ($plan.Row.DeproPending -or $awaitsCloud) { 'Pending' } elseif ($changed) { 'Success' } else { 'AlreadyDone' } Write-PraJournal $Context $plan.Record.ObjectGuid $plan.Operation 'Verified' Write-PraLog -Context $Context -Message "AD VERIFIED | $($plan.Record.SamAccountName) | $($plan.Row.FinalStatus)" -Level Detail Write-PraAdDelta -Context $Context -Plan $plan -Stage Verified @@ -1872,6 +1976,7 @@ function Invoke-PraAdBatch { Write-PraImmutableFile ($statePath + '.sha256') (Get-PraHash $statePath) $Context.StateFiles.Add($statePath) $receipt | Add-Member -NotePropertyName StatePath -NotePropertyValue $statePath + $stateWritten = $true $Context.LastVerifiedReceipt = $receipt return $receipt } @@ -1892,7 +1997,7 @@ function Invoke-PraAdBatch { } catch { Write-PraLog -Context $Context -Message ('The folder of the backup could not be marked as not applied: {0}' -f $_.Exception.Message) -Level Detail } # Nothing was written: no object is reported as done, skipped or failed, and the error does not name the last object looked at. - $Context.NoChangeMade = $true; $Context.CurrentIdentity = '' + $Context.NoChangeMade = $true; $Context.NotApplied = $true; $Context.CurrentIdentity = '' try { Write-PraLog -Context $Context -Message $plain -Level Error } catch { $Context.Issues.Add([pscustomobject]@{ Message = $plain; Source = 'ADBatch' }) } throw $plain @@ -1901,7 +2006,70 @@ function Invoke-PraAdBatch { catch { $Context.Issues.Add([pscustomobject]@{ Message=$failure.Exception.Message; Source='ADBatch' }) } throw $failure } - finally { Initialize-PraPermissionCache -Context $Context } + finally { + # A batch that stops (the first error, or a run that is stopped from outside) keeps what it did: the objects verified so far get their AD proof, marked partial. + if (-not $stateWritten -and $null -ne $receipt) { + try { Save-PraPartialProof -Context $Context -Receipt $receipt -Plans $Plans -Operation $Operation } + catch { try { Write-PraLog -Context $Context -Message ('The AD proof of the objects verified so far could not be written: {0}' -f $_.Exception.Message) -Level Detail } catch { $null = $_ } } + } + Initialize-PraPermissionCache -Context $Context + } +} + +function Save-PraPartialProof { + <# + .SYNOPSIS + A batch that stopped (the first error, or a run stopped from outside): says what each object that was not verified is, and for a Convert batch writes the + State file (AD proof) of the objects that were written AND verified. The proof is marked Partial with the number planned, except when every object is + verified: then it is the normal proof. What is left is recorded in the context (PartialBatch). + .DESCRIPTION + An object that is not verified but has a Started or Applied line in the journal may be partly changed: it is named so, and kept apart from the objects that + were never touched. The batch id stays in the context only when something was written (or may have been) or a proof exists. + #> + [CmdletBinding()] + param([Parameter(Mandatory)][hashtable]$Context, [Parameter(Mandatory)]$Receipt, [Parameter(Mandatory)][object[]]$Plans, [string]$Operation) + $touched = Get-PraJournalTouchedObject -Path ([string](Get-PraValue $Context 'JournalPath' '')) + $notApplied = [bool](Get-PraValue $Context 'NotApplied' $false) + $verified = @($Plans | Where-Object { (Get-PraValue $_.Row 'ADVerified' $false) -eq $true }) + $maybe = New-Object 'Collections.Generic.List[object]'; $untouched = New-Object 'Collections.Generic.List[object]' + foreach ($plan in $Plans) { + if ((Get-PraValue $plan.Row 'ADVerified' $false) -eq $true) { continue } + $guid = [string]$plan.Record.ObjectGuid + if (-not $notApplied -and ((Get-PraValue $plan.Row 'ADApplied' $null) -eq $true -or $touched.Contains($guid))) { + $maybe.Add($plan) + $plan.Row.Detail = ([string]$plan.Row.Detail + ' | may be partly changed: a write was started and the batch stopped before it was verified; roll the batch back to restore it').Trim(' ', '|') + } + else { + $untouched.Add($plan) + if ((Test-PraOrdinalEqual ([string]$plan.Row.FinalStatus) 'Planned')) { $plan.Row.Detail = ([string]$plan.Row.Detail + ' | not done: the batch stopped before this object, nothing was written to it').Trim(' ', '|') } + } + } + if (-not $verified.Count -and -not $maybe.Count -and (Test-PraOrdinalIn $Operation @('Convert', 'Recover'))) { $Context.BatchId = '' } + $Context.MayBeChanged = [string[]]@($maybe | ForEach-Object { [string]$_.Record.SamAccountName }) + if (-not (Test-PraOrdinalEqual $Operation 'Convert')) { return } + if (-not $verified.Count) { return } + $complete = ($verified.Count -eq $Plans.Count) + $state = [ordered]@{ + SchemaVersion=2; Operation=$Operation; Kind='ADVerified'; Environment=$Context.Config.Environment; RunId=$Context.RunId + BackupFile=[IO.Path]::GetFileName($Receipt.Path); BackupHash=$Receipt.Hash; SourceBackupHash=$Context.SourceBackupHash + CreatedUtc=[DateTime]::UtcNow.ToString('o') + } + if (-not $complete) { $state['Partial'] = $true; $state['PlannedCount'] = $Plans.Count } + $state['Records'] = @($verified | ForEach-Object { [ordered]@{ ObjectGuid=$_.Record.ObjectGuid; Operation=$_.Operation; ADVerified=$true; VerifiedUsnChanged=$_.ExpectedUsnChanged } }) + $statePath = Join-Path (Split-Path $Receipt.Path -Parent) ('State-' + $Receipt.Data.BatchId + '.json') + Write-PraImmutableFile $statePath ($state | ConvertTo-Json -Depth 12) + Write-PraImmutableFile ($statePath + '.sha256') (Get-PraHash $statePath) + $Context.StateFiles.Add($statePath) + $Receipt | Add-Member -NotePropertyName StatePath -NotePropertyValue $statePath -Force + $identifiers = New-Object 'Collections.Generic.List[string]' + foreach ($plan in $untouched) { foreach ($name in 'SamAccountName', 'UserPrincipalName', 'DistinguishedName', 'ObjectGuid') { $value = [string](Get-PraValue $plan.Record $name ''); if ($value) { $identifiers.Add($value) } } } + $Context.PartialBatch = [pscustomobject]@{ + BatchId=[string]$Receipt.Data.BatchId; ShortId=([string]$Receipt.Data.BatchId).Substring(0, 8); Verified=$verified.Count; Planned=$Plans.Count; StatePath=$statePath; Complete=$complete + NotConverted=[string[]]@($untouched | ForEach-Object { [string]$_.Record.SamAccountName }); NotConvertedIdentifiers=[string[]]$identifiers.ToArray() + MayBeChanged=[string[]]@($maybe | ForEach-Object { [string]$_.Record.SamAccountName }); Side='Run' + } + Write-PraJournal $Context '*' 'ADBatch' $(if ($complete) { 'Verified' } else { 'Partial' }) ('{0} of {1} object(s) verified; the AD proof lists only those' -f $verified.Count, $Plans.Count) + Write-PraLog -Context $Context -Message ('{0} AD PROOF | {1} of {2} object(s) | {3}' -f $(if ($complete) { 'STOPPED BATCH' } else { 'PARTIAL' }), $verified.Count, $Plans.Count, $statePath) -Level Detail } function Import-PraProof { @@ -1922,7 +2090,15 @@ function Import-PraProof { if (-not (Test-PraOrdinalEqual ([IO.Path]::GetFileName($data.BackupFile)) $data.BackupFile)) { throw 'AD proof: invalid backup path.' } $receipt = Import-PraBackup $Context (Join-Path (Split-Path $Path -Parent) $data.BackupFile) if (-not (Test-PraOrdinalIgnoreCaseEqual $receipt.Hash $data.BackupHash) -or -not (Test-PraOrdinalEqual $receipt.Data.Operation $Operation) -or -not (Test-PraOrdinalEqual $receipt.Data.RunId $data.RunId) -or -not (Test-PraOrdinalIgnoreCaseEqual $receipt.Data.SourceBackupHash $data.SourceBackupHash)) { throw 'AD proof does not match its backup, operation or source.' } - if (@($data.Records).Count -ne @($receipt.Data.Records).Count) { throw 'AD proof incomplete compared with its backup.' } + $partialField = Get-PraValue $data 'Partial' $false + if ($partialField -isnot [bool]) { throw 'AD proof: invalid Partial marker.' } + $planned = @($receipt.Data.Records).Count + if ($partialField) { + # Only a Convert batch that stopped at its first error has a partial proof: it lists the verified objects and says how many were planned. + $plannedField = Get-PraValue $data 'PlannedCount' $null + if (-not (Test-PraOrdinalEqual $Operation 'Convert') -or ($plannedField -isnot [int] -and $plannedField -isnot [long]) -or [long]$plannedField -ne $planned -or @($data.Records).Count -lt 1 -or @($data.Records).Count -ge $planned) { throw 'AD proof: invalid partial proof.' } + } + elseif (@($data.Records).Count -ne $planned) { throw 'AD proof incomplete compared with its backup.' } $expectedSource = if ((Test-PraOrdinalIgnoreCaseEqual $Operation 'Convert')) { $data.BackupHash } else { $data.SourceBackupHash } if (-not (Test-PraOrdinalIgnoreCaseEqual $expectedSource $Source.Hash)) { throw 'AD proof built from another Convert batch.' } $seen = @{} @@ -1931,12 +2107,12 @@ function Import-PraProof { $captured = @($receipt.Data.Records | Where-Object { Test-PraOrdinalIgnoreCaseEqual $_.ObjectGuid $record.ObjectGuid }) $allowed = switch ($Operation) { Convert { @('Convert') } Recover { @('Recover','Deprovision','AlreadyRecovered') } Finalize { @('Recover','RestoreTag','AlreadyRecovered') } Retention { @('RestoreTag') } default { @() } } if ($captured.Count -ne 1 -or -not (Test-PraOrdinalIn $record.Operation $allowed) -or -not (Test-PraOrdinalEqual $record.Operation $captured[0].RequestedOperation) -or - $record.VerifiedUsnChanged -isnot [string] -or $record.VerifiedUsnChanged -notmatch '^[1-9][0-9]*$') { throw 'AD proof: operation or version does not match the backup.' } + $record.VerifiedUsnChanged -isnot [string] -or $record.VerifiedUsnChanged -notmatch '^[1-9][0-9]*\z') { throw 'AD proof: operation or version does not match the backup.' } $null = [int64]::Parse($record.VerifiedUsnChanged, [Globalization.CultureInfo]::InvariantCulture) $seen[$record.ObjectGuid] = $true } if (-not $seen.Count) { throw 'AD proof is empty.' } - return [pscustomobject]@{ Data=$data; Path=$Path; Hash=$hash; Receipt=$receipt } + return [pscustomobject]@{ Data=$data; Path=$Path; Hash=$hash; Receipt=$receipt; Partial=$partialField; PlannedCount=$planned } } function Assert-PraFollowupState { @@ -2376,7 +2552,7 @@ function Invoke-PraSync { try { Write-PraJournal $Context '*' 'ADSync' 'Failed' $failure.Technical } catch { Write-PraLog -Context $Context -Message ('The journal cannot be written: {0}' -f $_.Exception.Message) -Level Detail } $Context['SyncFailure'] = [pscustomobject]@{ Server = $target; Kind = $failure.Kind; Reason = $failure.Reason; Technical = $failure.Technical } foreach ($row in $Context.Rows) { - if ((Get-PraValue $row 'ADApplied' $null) -eq $true -and (Test-PraOrdinalEqual ([string]$row.FinalStatus) 'Success')) { + if ((Get-PraValue $row 'ADApplied' $null) -eq $true -and (Test-PraOrdinalIn ([string]$row.FinalStatus) @('Success', 'Pending'))) { $row.FinalStatus = 'Pending'; $row.Detail = ([string]$row.Detail + ' | AD changed and verified; the Entra Connect sync has to be run').Trim(' ', '|') } } @@ -2390,7 +2566,7 @@ function Invoke-PraSync { #endregion Export-ModuleMember -Function ConvertTo-PraLdapValue, Get-PraHash, Write-PraImmutableFile, New-PraPrivateDirectory, Write-PraJournal, - Initialize-PraDirectory, Get-PraUser, Resolve-PraGroup, Get-PraGroupMember, Get-PraExpectedX500, Get-PraTarget, New-PraRow, New-PraPlan, Import-PraBackup, Invoke-PraAdPreview, Invoke-PraAdBatch, + Initialize-PraDirectory, Get-PraUser, Resolve-PraGroup, Get-PraGroupMember, Get-PraExpectedX500, Get-PraTarget, Find-PraRecoverOfBatch, Get-PraJournalTouchedObject, New-PraRow, New-PraPlan, Import-PraBackup, Invoke-PraAdPreview, Invoke-PraAdBatch, Import-PraProof, Invoke-PraSync, Test-PraSyncServer, Start-PraSyncProbe, Invoke-PraAdReplication, Assert-PraReceipt, Test-PraStateEqual, Assert-PraFollowupState, Initialize-PraPermissionCache # SIG # Begin signature block diff --git a/package/module/PRA.Gui.psm1 b/package/module/PRA.Gui.psm1 index eaf6a17..3eb00ff 100644 --- a/package/module/PRA.Gui.psm1 +++ b/package/module/PRA.Gui.psm1 @@ -216,6 +216,13 @@ function Read-PraGuiBatch { return $item } +function Test-PraGuiBatchSideFile { + <# True for the files that share a batch folder with the batch file and are not batches: the proof (State-), the journal, the data of the global report (PhaseData-, PhaseEvents-). #> + param([string]$Name) + foreach ($prefix in @('State-', 'Journal-', 'PhaseData-', 'PhaseEvents-')) { if ($Name.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase)) { return $true } } + return $false +} + function Read-PraGuiState { param([string]$Root, [string]$ConfigPath, [hashtable]$ScopeOverride=@{}) $state = [pscustomobject]@{ Root=$Root; ConfigPath=$ConfigPath; Config=$null; ConfigError=''; Batches=@(); OtherEnvironment=@(); BatchError='' } @@ -225,7 +232,7 @@ function Read-PraGuiState { if (-not (Test-Path -LiteralPath $folder)) { $state.BatchError='Backup folder not present yet: '+$folder; return $state } try { $state.Batches = @(Get-ChildItem -LiteralPath $folder -Recurse -File -Filter '*.json' -ErrorAction Stop | - Where-Object { -not $_.Name.StartsWith('State-', [StringComparison]::OrdinalIgnoreCase) -and -not $_.Name.StartsWith('Journal-', [StringComparison]::OrdinalIgnoreCase) -and (Split-Path $_.DirectoryName -Leaf) -match '^(Batch|Finalize)-' } | + Where-Object { -not (Test-PraGuiBatchSideFile $_.Name) -and (Split-Path $_.DirectoryName -Leaf) -match '^(Batch|Finalize)-' } | ForEach-Object { Read-PraGuiBatch -Path $_.FullName -Environment $state.Config.Environment }) # A batch of another environment is not an error of the folder: it is listed apart (a run can switch to its environment). $state.OtherEnvironment = @($state.Batches | Where-Object { $_.EnvMismatch } | ForEach-Object { Read-PraGuiBatch -Path $_.Path -Environment $state.Config.Environment -AnyEnvironment } | Where-Object { $_.Valid }) @@ -236,7 +243,7 @@ function Read-PraGuiState { function Resolve-PraGuiBatch { param([string]$Value, [string]$Operation, $State) if (-not $Value) { return $null } - if ($Value -match '^[a-fA-F0-9]{8,32}$') { + if ($Value -match '^[a-fA-F0-9]{8,32}\z') { $found = @($State.Batches | Where-Object { $_.BatchId.StartsWith($Value,[StringComparison]::OrdinalIgnoreCase) -and (Test-GuiOrdinal $_.Operation $Operation) }) if ($found.Count -gt 1) { $hashes=@(Get-GuiOrdinalUnique @($found | ForEach-Object { Get-PraGuiFileHash $_.Path }) -IgnoreCase) @@ -259,7 +266,7 @@ function Resolve-PraGuiBatch { if (-not [IO.Path]::IsPathRooted($path)) { $path=Join-Path $State.Root $path } $entry = Get-Item -LiteralPath $path -ErrorAction Stop $found = @(if ($entry.PSIsContainer) { - @(Get-ChildItem -LiteralPath $entry.FullName -File -Filter '*.json' -ErrorAction Stop | Where-Object { -not $_.Name.StartsWith('State-', [StringComparison]::OrdinalIgnoreCase) } | + @(Get-ChildItem -LiteralPath $entry.FullName -File -Filter '*.json' -ErrorAction Stop | Where-Object { -not (Test-PraGuiBatchSideFile $_.Name) } | ForEach-Object { Read-PraGuiBatch $_.FullName $State.Config.Environment } | Where-Object { Test-GuiOrdinal $_.Operation $Operation }) } else { Read-PraGuiBatch $entry.FullName $State.Config.Environment }) } @@ -339,11 +346,13 @@ function Test-PraGuiResult { if ($null -eq (Get-PraGuiValue $Result $field)) { return $false } } if (-not (Test-GuiOrdinal $Result.kind 'result') -or -not (Test-GuiOrdinal $Result.action $Request.Action) -or -not (Test-GuiOrdinal $Result.mode $Request.Mode) -or -not (Test-GuiOrdinal $Result.phase $Request.Phase)) { return $false } - if ([string]$Result.exitCode -notmatch '^[012]$' -or [int]$Result.exitCode -ne $NativeExitCode -or $NativeExitCode -eq 1) { return $false } - foreach ($field in @('success','error','pending','skipped','planned','total')) { if ([string]$Result.$field -notmatch '^\d+$') { return $false } } + if ([string]$Result.exitCode -notmatch '^[012]\z' -or [int]$Result.exitCode -ne $NativeExitCode -or $NativeExitCode -eq 1) { return $false } + foreach ($field in @('success','error','pending','skipped','planned','total')) { if ([string]$Result.$field -notmatch '^\d+\z') { return $false } } if ([int]$Result.error -ne 0 -or @((Get-PraGuiValue $Result 'issues' @())).Count) { return $false } if ([int64]$Result.total -ne ([int64]$Result.success+[int64]$Result.error+[int64]$Result.pending+[int64]$Result.skipped+[int64]$Result.planned)) { return $false } if ($NativeExitCode -eq 2) { return (Test-GuiOrdinal $Result.status 'Pending') -and [int]$Result.pending -gt 0 } + # An Apply that leaves planned objects did not do them: only a Preview ends Planned. + if ((Test-GuiOrdinal $Request.Mode 'Apply' -IgnoreCase) -and ((Test-GuiOrdinal $Result.status 'Planned') -or [int]$Result.planned -gt 0)) { return $false } return (Test-GuiOrdinalIn $Result.status @('Success','Planned')) -and [int]$Result.pending -eq 0 } @@ -1317,6 +1326,15 @@ function Test-PraGuiBatchSyncFailed { return $last.Contains('"Status":"Failed"') } +function Test-PraGuiBatchSyncCompleted { + <# True when the journal of the batch has an Entra Connect entry that ended well. #> + param([string]$Folder, [string]$BatchId) + $journal=Join-Path $Folder ('Journal-'+$BatchId+'.jsonl') + if (-not (Test-Path -LiteralPath $journal -PathType Leaf)) { return $false } + try { foreach ($line in [IO.File]::ReadLines($journal)) { if ($line.Contains('"Operation":"ADSync"') -and $line.Contains('"Status":"Completed"')) { return $true } } } catch { return $false } + return $false +} + function Get-PraGuiFinishReason { <# .SYNOPSIS @@ -1326,6 +1344,13 @@ function Get-PraGuiFinishReason { param($Item) $g=$script:Gui if (Test-PraGuiBatchSyncFailed $Item.Folder $Item.BatchId) { return 'AD part done, sync did not run: finish it here' } + # A batch with no Entra Connect entry that ended well goes through the AD part first (the synchronisation, then the package), as the command line does: a partial batch always, any other batch when the configuration asks for the synchronisation. + if (-not (Test-PraGuiBatchSyncCompleted $Item.Folder $Item.BatchId)) { + $partialText=Get-PraGuiPartialText (Join-Path $Item.Folder ('State-'+$Item.BatchId+'.json')) + $syncOn=[bool](Get-PraGuiValue (Get-PraGuiValue $g.State.Config 'EntraConnect' @{}) 'Sync' $false) + if ($partialText) { return 'AD part partly done, sync not run: finish it here' } + if ($syncOn) { return 'AD part done, sync not confirmed: finish it here' } + } $package='' try { $package=Get-PraTransferPackageName -Kind Convert -Environment ([string]$Item.Environment) -BatchId ([string]$Item.BatchId) } catch { return '' } $outbox=Join-Path $g.State.Config.Storage.BackupFolder 'Outbox' @@ -1334,6 +1359,17 @@ function Get-PraGuiFinishReason { return '' } +function Get-PraGuiPartialText { + <# 'Partial: k of n converted' for a Convert batch whose AD proof is marked partial (it stopped at its first error), else ''. #> + param([string]$ProofPath) + try { + if (-not (Test-Path -LiteralPath $ProofPath -PathType Leaf)) { return '' } + $proof=[IO.File]::ReadAllText($ProofPath) | ConvertFrom-PraJson + if ((Get-PraGuiValue $proof 'Partial' $false) -ne $true) { return '' } + return 'Partial: {0} of {1} converted' -f @(Get-PraGuiValue $proof 'Records' @()).Count,(Get-PraGuiValue $proof 'PlannedCount' '?') + } catch { return '' } +} + function Get-PraGuiBatchEntry { <# .SYNOPSIS @@ -1379,7 +1415,8 @@ function Get-PraGuiBatchEntry { $state_='AD part done, cloud part to do' $why=Get-PraGuiFinishReason $item if ($why) { $state_=$why; $level='Warn'; $finish=$true } - } else { $state_='No AD proof'; $level='Warn'; $selectable=$false } } else { $state_='Can be rolled back' } } + } else { $state_='No AD proof'; $level='Warn'; $selectable=$false } } else { $state_='Can be rolled back' } + if ($hasProof -and $selectable) { $partialText=Get-PraGuiPartialText $proofPath; if ($partialText) { $state_=$partialText+' · '+$state_; $level='Warn' } } } 'Recover' { if ($hasProof) { $state_='AD rollback done, cloud part to do' } else { $state_='No AD proof'; $level='Warn'; $selectable=$false } } 'RecoverFinalize' { $state_='Ready to finalize' } } diff --git a/tests/PraRemoteMailbox.Gui.Tests.ps1 b/tests/PraRemoteMailbox.Gui.Tests.ps1 index f0e4fed..c0c1057 100644 --- a/tests/PraRemoteMailbox.Gui.Tests.ps1 +++ b/tests/PraRemoteMailbox.Gui.Tests.ps1 @@ -2025,3 +2025,73 @@ AfterAll { } } } + +Describe 'Release 3.2.0 - the console: the data files of the global report are not batches, an Apply with planned objects is not Done, a partial batch is labelled (synthetic, no engine)' -Tag 'Release320a' { + It 'does not list PhaseData and PhaseEvents files as unreadable batches, and resolves a batch folder that holds them' { + $runtime = New-GuiTestRoot + $batch = New-GuiTestBatch -Runtime $runtime + Write-GuiTestJson (Join-Path $batch.Folder 'PhaseData-20261116101010-AD-1a2b3c4d.json') @{ SchemaVersion = 1; Kind = 'PhaseData'; Environment = 'GuiSynthetic'; Objects = @() } + Write-GuiTestFile (Join-Path $batch.Folder 'phasedata-20261116101011-cloud-1a2b3c4d.json') '{"Kind":"PhaseData"}' + Write-GuiTestFile (Join-Path $batch.Folder 'PhaseEvents-20261116101010-AD-1a2b3c4d.json') '{"Step":"x"}' + Write-GuiTestFile (Join-Path $batch.Folder 'PhaseEvents-20261116101010-AD-1a2b3c4d.jsonl') '{"Step":"x"}' + $state = Read-PraGuiState $runtime.Root $runtime.Config + @($state.Batches).Count | Should -Be 1 -Because (($state.Batches | ForEach-Object Label) -join "`n") + @($state.Batches | Where-Object { -not $_.Valid }).Count | Should -Be 0 + $found = Resolve-PraGuiBatch $batch.Folder 'Convert' $state + $found.Path | Should -BeExactly $batch.Path + (Resolve-PraGuiBatch $batch.Id 'Convert' $state).Path | Should -BeExactly $batch.Path + } + It 'an Apply whose result is Planned, or has planned objects, is not a success; a Preview that plans is still valid' { + $apply = New-PraGuiRequest -Phase AD -Mode Apply + Test-PraGuiResult (New-GuiTestResult $apply) $apply 0 | Should -BeFalse -Because 'Planned is the status of a Preview' + $mixed = New-GuiTestResult $apply -Planned 1 -Success 2; $mixed.status = 'Success' + Test-PraGuiResult $mixed $apply 0 | Should -BeFalse -Because 'an object is still planned' + Test-PraGuiResult (New-GuiTestResult $apply -Planned 0 -Success 2) $apply 0 | Should -BeTrue + Test-PraGuiResult (New-GuiTestResult $apply -ExitCode 2 -Planned 0 -Pending 2) $apply 2 | Should -BeTrue + $preview = New-PraGuiRequest -Phase AD -Mode Preview + Test-PraGuiResult (New-GuiTestResult $preview) $preview 0 | Should -BeTrue + $apply = New-PraGuiRequest -Phase AD -Mode 'APPLY' + Test-PraGuiResult (New-GuiTestResult $apply) $apply 0 | Should -BeFalse -Because 'the mode is not case sensitive' + } + It 'labels a batch whose AD proof is partial with the number of objects converted, and nothing for a complete proof' { + $runtime = New-GuiTestRoot + $partial = New-GuiTestBatch -Runtime $runtime + $records = @(1..3 | ForEach-Object { @{ ObjectGuid = [guid]::NewGuid().ToString(); Operation = 'Convert'; ADVerified = $true } }) + Write-GuiTestJson $partial.Proof @{ SchemaVersion = 2; Operation = 'Convert'; Kind = 'ADVerified'; Environment = 'GuiSynthetic'; Partial = $true; PlannedCount = 10; Records = $records } + (& (Get-Module PRA.Gui) { param($path) Get-PraGuiPartialText $path } $partial.Proof) | Should -BeExactly 'Partial: 3 of 10 converted' + $complete = New-GuiTestBatch -Runtime $runtime + (& (Get-Module PRA.Gui) { param($path) Get-PraGuiPartialText $path } $complete.Proof) | Should -BeExactly '' + (& (Get-Module PRA.Gui) { param($path) Get-PraGuiPartialText $path } (Join-Path $runtime.Root 'missing.json')) | Should -BeExactly '' + } +} + +Describe 'Release 3.2.0 - the console continues a partial batch, or a batch whose synchronisation is not confirmed, with the AD part first (synthetic, no engine)' -Tag 'Release320a' { + It 'offers the AD part first for a partial batch, and for a batch without a good Entra Connect entry when the configuration asks for the synchronisation' { + $runtime = New-GuiTestRoot + $partial = New-GuiTestBatch -Runtime $runtime + Write-GuiTestJson $partial.Proof @{ SchemaVersion = 2; Operation = 'Convert'; Kind = 'ADVerified'; Environment = 'GuiSynthetic'; Partial = $true; PlannedCount = 10; Records = @(@{ ObjectGuid = [guid]::NewGuid().ToString(); Operation = 'Convert'; ADVerified = $true }) } + $plain = New-GuiTestBatch -Runtime $runtime + $synced = New-GuiTestBatch -Runtime $runtime + Write-GuiTestFile (Join-Path $synced.Folder ('Journal-' + $synced.Id + '.jsonl')) ("{`"RunId`":`"r`",`"Operation`":`"ADSync`",`"Status`":`"Started`"}`r`n{`"RunId`":`"r`",`"Operation`":`"ADSync`",`"Status`":`"Completed`"}`r`n") + $items = @{} + foreach ($name in 'partial', 'plain', 'synced') { $batch = Get-Variable $name -ValueOnly; $items[$name] = [pscustomobject]@{ Folder = $batch.Folder; BatchId = $batch.Id; Environment = 'GuiSynthetic' } } + $reasons = & (Get-Module PRA.Gui) { + param($Items, $Folder) + $saved = $script:Gui + try { + $result = @{} + foreach ($sync in $false, $true) { + $script:Gui = [pscustomobject]@{ State = [pscustomobject]@{ Config = @{ EntraConnect = @{ Sync = $sync }; Storage = @{ BackupFolder = $Folder } } }; Detect = $null } + foreach ($name in 'partial', 'plain', 'synced') { $result[$name + '-' + $sync] = [string](Get-PraGuiFinishReason $Items[$name]) } + } + $result + } + finally { $script:Gui = $saved } + } $items (Join-Path $runtime.Root 'Backups') + $reasons['partial-False'] | Should -BeExactly 'AD part partly done, sync not run: finish it here' + $reasons['partial-True'] | Should -BeExactly 'AD part partly done, sync not run: finish it here' + $reasons['plain-True'] | Should -BeExactly 'AD part done, sync not confirmed: finish it here' + $reasons['plain-False'] | Should -Not -Match 'finish it here' -Because 'the configuration leaves the synchronisation to the operator' + $reasons['synced-True'] | Should -Not -Match 'finish it here' -Because 'its journal has an Entra Connect entry that ended well' + } +} diff --git a/tests/PraRemoteMailbox.Tests.ps1 b/tests/PraRemoteMailbox.Tests.ps1 index ea2285f..6f02e06 100644 --- a/tests/PraRemoteMailbox.Tests.ps1 +++ b/tests/PraRemoteMailbox.Tests.ps1 @@ -42,6 +42,13 @@ function Write-GateEvent { $event = [ordered]@{ Operation=$Operation; Identity=[string]$Identity; Server=$Server; Detail=$Detail; Synthetic=$true; Utc=[datetime]::UtcNow.ToString('o') } [IO.File]::AppendAllText($global:PraGateAd.EventPath, (($event | ConvertTo-Json -Depth 10 -Compress) + "`r`n")) } +function Stop-GatePipeline { + # What Ctrl+C does to a run: the pipeline that runs the script is stopped, the finally blocks run, the next statements do not. + $runspace=[Management.Automation.Runspaces.Runspace]::DefaultRunspace + $method=$runspace.GetType().GetMethod('GetCurrentlyRunningPipeline',[Reflection.BindingFlags]'Instance,Public,NonPublic',$null,[Type]::EmptyTypes,$null) + $null=$method.Invoke($runspace,@()).StopAsync() + Microsoft.PowerShell.Utility\Start-Sleep -Seconds 60 +} function Assert-GateServer { param([string]$Server) if ($Server -cne $global:PraGateAd.Server) { throw "Synthetic DC mismatch: '$Server'" } @@ -170,6 +177,7 @@ function Get-ADUser { param([object]$Identity,[string]$LDAPFilter,[string[]]$Properties,[string]$Server,[string]$SearchBase) Assert-GateServer $Server Write-GateEvent 'Get-ADUser' $Identity $Server @{LDAPFilter=$LDAPFilter; Properties=$Properties; SearchBase=$SearchBase} + if ($global:PraGateAd.Case -eq 'InterruptRead') { Stop-GatePipeline } if ($global:PraGateAd.Case -eq 'MissingUser') { return } if ($global:PraGateAd.Case -eq 'AmbiguousUser') { foreach ($user in $global:PraGateAd.Users) { Copy-GateUser $user -Capture:('*' -in $Properties) }; return } if ($global:PraGateAd.ContainsKey('TrusteeUsers') -and $Identity) { @@ -239,6 +247,9 @@ function Set-ADUser { param([object]$Identity,[hashtable]$Replace,[string[]]$Clear,[string]$Server) Assert-GateServer $Server Assert-GateBackupBarrier + $writeTarget=@($global:PraGateAd.Users | Where-Object ObjectGUID -eq ([string]$Identity))[0] + if ($global:PraGateAd.Case -eq 'FailAtSam' -and $null -ne $writeTarget -and $writeTarget.SamAccountName -eq $global:PraGateAd.FailSam) { throw 'SYNTHETIC: this object changed since it was planned (uSNChanged).' } + if ($global:PraGateAd.Case -eq 'InterruptAtSam' -and $null -ne $writeTarget -and $writeTarget.SamAccountName -eq $global:PraGateAd.FailSam) { Stop-GatePipeline } # A refusal of the domain controller, in another language than English: the engine must still tell it from any other error. if ($global:PraGateAd.Case -eq 'AccessDenied') { throw [UnauthorizedAccessException]::new('Droits d''acces insuffisants pour executer l''operation.') } Write-GateEvent 'Set-ADUser' $Identity $Server @{Replace=$Replace;Clear=$Clear} @@ -303,7 +314,13 @@ function Invoke-PraCloudPhase { [IO.File]::AppendAllText($state.EventPath,('{"Operation":"CloudPhase-SyntheticBarrier","Synthetic":true}'+"`r`n")) $seen=@(foreach ($row in $Rows) { [ordered]@{ Upn=[string]$row.UserPrincipalName; ExpectedX500=@(Get-PraList $row.BackupRec 'ExpectedX500'); Note=[string](Get-PraValue $row.BackupRec 'ExpectedX500Note' '') } }) [IO.File]::AppendAllText($state.EventPath,((@{Operation='CloudRows-SyntheticBarrier';Synthetic=$true;Rows=$seen} | ConvertTo-Json -Depth 8 -Compress)+"`r`n")) - if ($state.Case -eq 'CloudX500Missing') { + if ($state.Case -eq 'CloudInterrupt') { + # Ctrl+C during the wait for the mailboxes: the pipeline is stopped, nothing is confirmed. + $runspace=[Management.Automation.Runspaces.Runspace]::DefaultRunspace + $method=$runspace.GetType().GetMethod('GetCurrentlyRunningPipeline',[Reflection.BindingFlags]'Instance,Public,NonPublic',$null,[Type]::EmptyTypes,$null) + $null=$method.Invoke($runspace,@()).StopAsync() + Microsoft.PowerShell.Utility\Start-Sleep -Seconds 60 + } elseif ($state.Case -eq 'CloudX500Missing') { # What the real cloud phase does for an object whose X500 address is not in Exchange Online: a warning item, the object listed for the Next steps, the conversion done. foreach ($row in $Rows) { $row.CloudStatus='Success'; $row.CloudMailbox=$true; $row.CloudLicense=$true; $row.FinalStatus='Success'; $row.CloudDetail='SYNTHETIC: mailbox ready.' } $Context.CurrentIdentity=[string]$Rows[0].ObjectGuid @@ -428,7 +445,7 @@ Export-ModuleMember -Function Get-ADSyncScheduler,Start-ADSyncSyncCycle } } function global:New-GateRuntime { - param([string]$Name='case',[string]$Case='Normal',[switch]$Preexisting,[switch]$Shared13,[ValidateRange(3,500)][int]$TrusteeCount=8,[ValidateRange(100,120)][int]$AclCount=100) + param([string]$Name='case',[string]$Case='Normal',[switch]$Preexisting,[switch]$Shared13,[ValidateRange(3,500)][int]$TrusteeCount=8,[ValidateRange(100,120)][int]$AclCount=100,[ValidateRange(2,13)][int]$UserCount=2,[hashtable]$Extra=@{}) $caseName=$Name $root=Join-Path $global:PraGate.Root ([guid]::NewGuid().ToString('N').Substring(0,6)) $modules=Join-Path $root 'modules'; $package=Join-Path $root 'package' @@ -443,7 +460,7 @@ Export-ModuleMember -Function Get-ADSyncScheduler,Start-ADSyncSyncCycle Copy-Item -Path (Join-Path $global:PraGate.Package '*') -Destination $package -Recurse -Force [IO.File]::WriteAllText((Join-Path $package 'module\PRA.Cloud.psm1'),$global:PraGate.CloudSource,(New-Object Text.UTF8Encoding($true))) Set-PraFixtureHash -Root $package -Relative 'module\PRA.Cloud.psm1' - $users=@((New-GateUser 1),(New-GateUser 2)) + $users=@(1..$UserCount | ForEach-Object { New-GateUser $_ }) if ($Shared13) { $users=@(1..13 | ForEach-Object { New-GateUser $_ }) foreach ($user in $users) { @@ -456,6 +473,7 @@ Export-ModuleMember -Function Get-ADSyncScheduler,Start-ADSyncSyncCycle $group=[pscustomobject]@{ ObjectGUID=[guid]'10000000-0000-0000-0000-000000000001'; DistinguishedName='CN=License,OU=Tests,DC=gate,DC=invalid'; objectClass='group'; member=@() } if ($Preexisting) { $group.member=@($users | ForEach-Object DistinguishedName) } $state=@{ Case=$Case; Users=$users; Originals=([Management.Automation.PSSerializer]::Deserialize([Management.Automation.PSSerializer]::Serialize($users,30))); Group=$group; Server='dc01.gate.invalid'; BackupFolder=(Join-Path $root 'backups'); ExpectedGuids=@($users | ForEach-Object { [string]$_.ObjectGUID }); EventPath=(Join-Path $root 'events.jsonl') } + foreach ($key in $Extra.Keys) { $state[$key]=$Extra[$key] } if ($Shared13) { $state.NativeShared=$true; $state.AclCount=$AclCount $state.PermissionGroups=@(1..3 | ForEach-Object { [pscustomobject]@{ObjectGUID=[guid]('20000000-0000-0000-0000-{0:000000000000}' -f $_);DistinguishedName="CN=Permission$_,OU=Tests,DC=gate,DC=invalid";SamAccountName="permission$_";objectClass='group';objectSid=('S-1-5-21-100-200-300-'+(2000+$_))} }) @@ -4227,9 +4245,12 @@ Describe 'GUI events mirror the existing engine without extra mutations' -Tag 'G $event.text | Should -BeExactly $text $event.identity | Should -BeExactly 'user@gate.invalid' } - It 'surfaces an unavailable event channel rather than pretending the window received the event' { + It 'says that the event channel is unavailable, once, and never stops the run for it' { $env:PRA_EVENT_FILE=Join-Path $runtime.Root 'missing\events.jsonl' - { Write-PraEvent -Kind item -Data @{text='not delivered'} } | Should -Throw + InModuleScope PRA.Common { $script:PraEventWriteWarned=$false } + $said=& { Write-PraEvent -Kind item -Data @{text='not delivered'} } 6>&1 | Out-String + $said | Should -Match 'The progress file of the window cannot be written' + (& { Write-PraEvent -Kind item -Data @{text='not delivered either'} } 6>&1 | Out-String) | Should -Not -Match 'cannot be written' } It 'reports the actual Preview result and phase, preserving the native result and write-free behavior' { $run=Invoke-GateProcess $runtime @{Action='Convert';Phase='AD';Mode='Preview';ConfigPath=$runtime.ConfigPath} @@ -8524,16 +8545,17 @@ Describe 'Release 3.1.3 - every stop ends with a next step, and the Error block $steps[1] | Should -Match "^\.\\Invoke-PraRemoteMailbox\.ps1 -Action Check -Identity 'user1' -ConfigPath " $run.Output | Should -Match 'then run the Check again:' } - It 'a partial AD batch says which objects may be changed and proposes the Preview, never the Apply again' { + It 'a batch stopped after a write that no object verified says which objects may be changed and proposes the rollback Preview and the Check, never the Apply again' { $runtime = New-GateRuntime -Name 'partial-ad-313e' -Case 'SecondMutationFailure' $run = Invoke-GateProcess $runtime @{Action='Convert';Phase='AD';Mode='Apply';Force=$true;ConfigPath=$runtime.ConfigPath} -TimeoutSeconds 120 $run.ExitCode | Should -Be 1 -Because ($run.Output + $run.Error) @(Get-GateWrites $runtime).Count | Should -BeGreaterThan 0 $steps = @($run.MainResult.NextSteps) - $steps[0] | Should -Match '^Active Directory was changed for [0-9]+ object\(s\) before the stop \(see the journal and the backup named above\)\. Do not run the Apply again before reading what is left: run the Preview of the same command:$' - $steps[1] | Should -Match '^\.\\Invoke-PraRemoteMailbox\.ps1 -Action Convert -Phase AD -ConfigPath ' + $steps[0] | Should -Match '^Active Directory was changed for [0-9]+ object\(s\) before the stop \(see the journal and the backup named above\) and none of them is verified\. Do not run the Apply again before reading what is left\. To put them back as they were, roll the batch back \(run the Preview first, then the same command with -Mode Apply\):$' + $steps[1] | Should -Match '^\.\\Invoke-PraRemoteMailbox\.ps1 -Action Recover -Batch [0-9a-f]{8} -ConfigPath ' $steps[1] | Should -Not -Match '-Mode Apply' - $run.Output | Should -Match 'run the Preview of the same command' + $steps[3] | Should -Match '^\.\\Invoke-PraRemoteMailbox\.ps1 -Action Check -Batch [0-9a-f]{8} -ConfigPath ' + $run.Output | Should -Match 'roll the batch back' } It 'a stop before anything was written ends with the same command, as typed (usage, batch not found, cloud pre-check)' { $usage = New-GateRuntime -Name 'usage-313e' @@ -9372,3 +9394,670 @@ AfterAll { foreach ($name in @('New-GateUser','New-GateRuntime','New-GateContext','Get-GateEvents','Set-GateConfigText','Get-GateWrites','Save-GateDeltaEvidence','Invoke-GateProcess','New-GateSourceBundles','Get-GateCodec','Get-GateExpectedNodes','Assert-GateWireSnapshot','Save-GateOomEvidence')) { Remove-Item -LiteralPath ('Function:\'+$name) -ErrorAction SilentlyContinue } Remove-Variable PraGateAd,PraGate -Scope Global -ErrorAction SilentlyContinue } + +Describe 'Release 3.2.0 - a run stopped from outside ends FAIL with exit code 1 and the command that continues the batch, never PASS (real main, synthetic)' -Tag 'Release320a' { + It 'a Convert Apply stopped during the AD writes: FAIL, exit code 1, the stop named, the objects done and not done told apart, the proof of the verified object written' { + $runtime = New-GateRuntime -Name 'interrupt-ad-320a' -Case 'InterruptAtSam' -Extra @{ FailSam = 'user2' } + $run = Invoke-GateProcess $runtime @{Action='Convert';Phase='AD';Mode='Apply';Force=$true;ConfigPath=$runtime.ConfigPath} -TimeoutSeconds 120 + $run.ExitCode | Should -Be 1 -Because ($run.Output + $run.Error) + $run.Output | Should -Match '(?m)^\s*RESULT: FAIL\s*$' + $run.Output | Should -Not -Match '(?m)^\s*RESULT: PASS\s*$' + $run.Output | Should -Not -Match 'Convert finished' + $run.Output | Should -Match 'the run was interrupted before it finished' + $run.Output | Should -Match '1 done . 1 pending . 1 error\(s\) . 0 skipped' + $batch = [regex]::Match($run.Output, '(?m)^\s*\S+\s+Batch\s+(?[0-9a-f]{8})\s*$').Groups['id'].Value + $batch | Should -Match '^[0-9a-f]{8}$' -Because $run.Output + $run.Output | Should -Match ('-Action Convert -Phase AD -Mode Apply -Batch ' + $batch + ' -ConfigPath') + $state = @(Get-ChildItem -LiteralPath $runtime.State.BackupFolder -Recurse -File -Filter 'State-*.json') + $state.Count | Should -Be 1 + $proof = [IO.File]::ReadAllText($state[0].FullName) | ConvertFrom-Json -DateKind String + $proof.Partial | Should -BeTrue + $proof.PlannedCount | Should -Be 2 + @($proof.Records).Count | Should -Be 1 + (Get-Content -LiteralPath @(Get-ChildItem -LiteralPath (Join-Path $runtime.Root 'logs') -Filter '*.log')[0].FullName -Tail 2) -join "`n" | Should -Match 'RESULT: FAIL' + } + It 'a Phase Both Apply stopped in the cloud wait: no object is a success, the phase data says Failed, the Exchange Online part is the next step' { + $runtime = New-GateRuntime -Name 'interrupt-cloud-320a' -Case 'CloudInterrupt' + $run = Invoke-GateProcess $runtime @{Action='Convert';Phase='Both';Mode='Apply';Force=$true;ConfigPath=$runtime.ConfigPath} -TimeoutSeconds 120 + $run.ExitCode | Should -Be 1 -Because ($run.Output + $run.Error) + $run.Output | Should -Match '(?m)^\s*RESULT: FAIL\s*$' + $run.Output | Should -Not -Match '(?m)^\s*RESULT: PASS\s*$' + $run.Output | Should -Match '0 done . 2 pending . 1 error\(s\) . 0 skipped' + $run.Output | Should -Match 'the run was interrupted before it finished' + $run.Output | Should -Match '-Action Convert -Phase Cloud -Mode Apply -Batch [0-9a-f]{8} -ConfigPath' + $data = @(Get-ChildItem -LiteralPath $runtime.State.BackupFolder -Recurse -File -Filter 'PhaseData-*.json') + $data.Count | Should -Be 1 + $phase = [IO.File]::ReadAllText($data[0].FullName) | ConvertFrom-Json -DateKind String + $phase.Phase.Status | Should -BeExactly 'Failed' + $phase.Phase.ExitCode | Should -Be 1 + @($phase.Objects | Where-Object FinalStatus -eq 'Success').Count | Should -Be 0 + } + It 'a Preview and a Check stopped the same way end FAIL too' { + $preview = New-GateRuntime -Name 'interrupt-preview-320a' -Case 'InterruptRead' + $run = Invoke-GateProcess $preview @{Action='Convert';Phase='AD';Mode='Preview';ConfigPath=$preview.ConfigPath} -TimeoutSeconds 120 + $run.ExitCode | Should -Be 1 -Because ($run.Output + $run.Error) + $run.Output | Should -Match '(?m)^\s*RESULT: FAIL\s*$' + $run.Output | Should -Not -Match '(?m)^\s*RESULT: PASS\s*$' + $run.Output | Should -Match 'the run was interrupted before it finished' + $check = New-GateRuntime -Name 'interrupt-check-320a' -Case 'InterruptRead' + $run = Invoke-GateProcess $check @{Action='Check';Identity='user1';Once=$true;ConfigPath=$check.ConfigPath} -TimeoutSeconds 120 + $run.ExitCode | Should -Be 1 -Because ($run.Output + $run.Error) + $run.Output | Should -Match '(?m)^\s*RESULT: FAIL\s*$' + $run.Output | Should -Not -Match '(?m)^\s*RESULT: PASS\s*$' + } +} + +Describe 'Release 3.2.0 - an object that was not reached is not skipped: Planned becomes Pending in an Apply whose batch exists, Pending in phase Both until the cloud part confirms it (production Common module)' -Tag 'Release320a' { + BeforeAll { + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global + function global:New-OutcomeContext320 { + param([string]$Mode = 'Apply', [string]$Action = 'Convert', [string]$BatchId = '', [string[]]$Statuses) + $context = @{ Mode = $Mode; Action = $Action; Issues = (New-Object 'Collections.Generic.List[object]'); Rows = (New-Object 'Collections.Generic.List[object]'); ExitCode = 0; CloudConnectFailed = $false; ResultStatus = ''; BatchId = $BatchId } + foreach ($status in $Statuses) { $context.Rows.Add([pscustomobject]@{ ObjectGuid = [guid]::NewGuid().ToString(); SamAccountName = 'u'; UserPrincipalName = 'u@gate.invalid'; Action = $Action; FinalStatus = $status; Detail = ''; CloudStatus = 'N/A' }) } + $context + } + } + AfterAll { Remove-Item -LiteralPath 'Function:\New-OutcomeContext320' -ErrorAction SilentlyContinue } + It 'counts a Planned object of an Apply that has its batch as Pending (exit code 2), and keeps it Planned in a Preview and in an Apply without a batch' { + $applied = Get-PraOutcome (New-OutcomeContext320 -BatchId 'abcd1234' -Statuses @('Success', 'Planned', 'Planned')) + $applied.Counts.Pending | Should -Be 2 + $applied.Counts.Skipped | Should -Be 0 + $applied.Counts.Planned | Should -Be 0 + $applied.ExitCode | Should -Be 2 + @($applied.Rows | Where-Object FinalStatus -eq 'Pending')[0].Detail | Should -Match 'not finished' + $started = New-OutcomeContext320 -Statuses @('Planned'); $started.ChangesStarted = $true + (Get-PraOutcome $started).Counts.Pending | Should -Be 1 + $preview = Get-PraOutcome (New-OutcomeContext320 -Mode Preview -BatchId 'abcd1234' -Statuses @('Planned', 'Planned')) + $preview.Counts.Planned | Should -Be 2 + $preview.Counts.Pending | Should -Be 0 + $noBatch = Get-PraOutcome (New-OutcomeContext320 -Statuses @('Planned')) + $noBatch.Counts.Planned | Should -Be 1 + $noBatch.Counts.Pending | Should -Be 0 + } + It 'creates every row Planned, so that an object that no step reached never reads Skipped' { + $row = New-PraRow @{ ObjectNames = @{}; Action = 'Convert' } ([pscustomobject]@{ ObjectGuid = [guid]::NewGuid().ToString(); SamAccountName = 'u'; UserPrincipalName = 'u@gate.invalid'; IsShared = $false }) + $row.FinalStatus | Should -BeExactly 'Planned' + } + It 'the cloud phase sets the row of an object it waits for to Pending before its first call, so that a run that ends there never reports it as done' { + Get-Module PRA.Cloud -All | Remove-Module -Force -ErrorAction SilentlyContinue + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Cloud.psm1') -Force -Global + $runtime = New-GateRuntime -Name 'pending-cloud-320a' + $context = New-GateContext $runtime -Mode Apply -Action Convert + $context.Phase = 'Cloud'; $context.Once = $true; $context.IntervalMinutes = 0; $context.TimeoutMinutes = 1 + $context.Config.Cloud = @{ CheckMailbox = $true; CheckLicense = $false; MailboxCheckVia = 'Exo'; RequiredSkuPartNumber = ''; TenantId = '20000000-0000-0000-0000-000000000002' } + $context.LogFile = Join-Path $runtime.Root 'logs\pending-cloud.log' + $global:PraGate.Context320 = $context + $global:PraGate.Row320 = New-PraRow $context ([pscustomobject]@{ ObjectGuid = '00000000-0000-0000-0000-000000000001'; UserPrincipalName = 'user1@gate.invalid'; SamAccountName = 'user1'; IsShared = $false }) + $global:PraGate.Row320.FinalStatus = 'Success' + $global:PraGate.Seen320 = '' + InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { $global:PraGate.Seen320 = [string]$global:PraGate.Row320.FinalStatus; throw 'SYNTHETIC: the process is stopped here' } + Mock Close-PraCloudSession { } + Invoke-PraCloudPhase $global:PraGate.Context320 @($global:PraGate.Row320) 'Convert' + } + $global:PraGate.Seen320 | Should -BeExactly 'Pending' + $global:PraGate.Row320.FinalStatus | Should -Not -BeExactly 'Success' + Remove-Module PRA.Cloud -Force -ErrorAction SilentlyContinue + } +} + +Describe 'Release 3.2.0 - a Convert batch stopped at its first error is continued, checked and rolled back (real main, production Directory module, synthetic AD)' -Tag 'Release320a' { + BeforeAll { + $global:PraGate.R2 = New-GateRuntime -Name 'partial-320a' -Case 'FailAtSam' -UserCount 10 -Extra @{ FailSam = 'user3' } + $runtime = $global:PraGate.R2 + $env:PRA_GATE_STATE = $runtime.StatePath; $env:PSModulePath = $runtime.Modules + ';' + (Join-Path $PSHOME 'Modules') + Remove-Module PRA.Directory -Force -ErrorAction SilentlyContinue + Get-Module ActiveDirectory -All | Remove-Module -Force -ErrorAction Stop + Import-Module (Join-Path $runtime.Modules 'ActiveDirectory\ActiveDirectory.psm1') -Force -Global + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Directory.psm1') -Force -Global + $context = New-GateContext $runtime + # The order of the engine: account name in capitals, then the GUID: user1, user10, user2, user3 (fails: the fourth object), user4 ... + $global:PraGate.R2Plans = @(foreach ($sam in 'user1', 'user10', 'user2', 'user3', 'user4', 'user5', 'user6', 'user7', 'user8', 'user9') { New-PraPlan $context $sam 'Convert' }) + $global:PraGate.R2Error = '' + try { $null = Invoke-PraAdBatch $context $global:PraGate.R2Plans 'Convert' } catch { $global:PraGate.R2Error = [string]$_.Exception.Message } + $global:PraGate.R2Context = $context + $global:PraGate.R2Partial = $context.PartialBatch + # What the domain controller holds after the run (the objects converted before the error), for the processes that follow. + $global:PraGateAd.Case = 'Normal' + [IO.File]::WriteAllText($runtime.StatePath, [Management.Automation.PSSerializer]::Serialize($global:PraGateAd, 35)) + $global:PraGate.R2Folder = Split-Path @(Get-ChildItem -LiteralPath $runtime.State.BackupFolder -Recurse -File -Filter 'Convert-*.json')[0].FullName -Parent + $global:PraGate.R2Json = @(Get-ChildItem -LiteralPath $global:PraGate.R2Folder -File -Filter 'Convert-*.json')[0].FullName + $global:PraGate.R2Id = ([IO.File]::ReadAllText($global:PraGate.R2Json) | ConvertFrom-Json -DateKind String).BatchId + $global:PraGate.R2Csv = Join-Path $runtime.Root 'all-ten.csv' + [IO.File]::WriteAllText($global:PraGate.R2Csv, ("Identity`r`n" + ((1..10 | ForEach-Object { 'user' + $_ }) -join "`r`n") + "`r`n"), (New-Object Text.UTF8Encoding($true))) + $global:PraGate.R2Rest = Join-Path $runtime.Root 'seven-left.csv' + [IO.File]::WriteAllText($global:PraGate.R2Rest, ("Identity`r`n" + ((3..9 | ForEach-Object { 'user' + $_ }) -join "`r`n") + "`r`n"), (New-Object Text.UTF8Encoding($true))) + } + AfterAll { foreach ($key in 'R2', 'R2Plans', 'R2Error', 'R2Context', 'R2Partial', 'R2Folder', 'R2Json', 'R2Id', 'R2Csv', 'R2Rest', 'R2Lookup') { $global:PraGate.Remove($key) } } + It 'keeps the first error as the stop of the batch and writes the AD proof of the three verified objects, marked partial with the number planned' { + $global:PraGate.R2Error | Should -Match 'SYNTHETIC: this object changed since it was planned' + $partial = $global:PraGate.R2Partial + $partial.Verified | Should -Be 3 + $partial.Planned | Should -Be 10 + $partial.NotConverted.Count | Should -Be 6 + @($partial.MayBeChanged) -join ',' | Should -BeExactly 'user3' -Because 'the batch stopped on user3 after its write was started: it may be partly changed, it is not an object to convert again' + $partial.NotConverted | Should -Not -Contain 'user3' + $proof = [IO.File]::ReadAllText($partial.StatePath) | ConvertFrom-Json -DateKind String + $proof.Partial | Should -BeTrue + $proof.PlannedCount | Should -Be 10 + @($proof.Records).Count | Should -Be 3 + (Get-FileHash -LiteralPath $partial.StatePath -Algorithm SHA256).Hash.ToLowerInvariant() | Should -BeExactly ([IO.File]::ReadAllText($partial.StatePath + '.sha256').Trim().ToLowerInvariant()) + $rows = $global:PraGate.R2Context.Rows.ToArray() + @($rows | Where-Object { $_.FinalStatus -eq 'Success' }).Count | Should -Be 3 + @($rows | Where-Object { $_.FinalStatus -eq 'Error' }).Count | Should -Be 1 + @($rows | Where-Object { $_.FinalStatus -eq 'Planned' }).Count | Should -Be 6 -Because 'the objects that were not reached stay Planned: Pending in the result, never Skipped' + (Get-PraOutcome $global:PraGate.R2Context).Counts.Skipped | Should -Be 0 + } + It 'Import-PraProof accepts the partial proof and refuses a proof that lists fewer objects without saying so, or that lies about the number planned' { + $context = $global:PraGate.R2Context + $source = Import-PraBackup $context $global:PraGate.R2Json + $proof = Import-PraProof $context $global:PraGate.R2Partial.StatePath $source 'Convert' + $proof.Partial | Should -BeTrue + $proof.PlannedCount | Should -Be 10 + $copyRoot = Join-Path $global:PraGate.R2.Root 'copies' + foreach ($case in @(@{ Name = 'unmarked'; Edit = { param($p) $p.PSObject.Properties.Remove('Partial'); $p.PSObject.Properties.Remove('PlannedCount') }; Message = '*incomplete*' }, + @{ Name = 'wrong-count'; Edit = { param($p) $p.PlannedCount = 9 }; Message = '*invalid partial proof*' }, + @{ Name = 'text-marker'; Edit = { param($p) $p.Partial = 'yes' }; Message = '*Partial marker*' })) { + $folder = Join-Path $copyRoot $case.Name + Copy-Item -LiteralPath $global:PraGate.R2Folder -Destination $folder -Recurse + $path = Join-Path $folder ([IO.Path]::GetFileName($global:PraGate.R2Partial.StatePath)) + $edited = [IO.File]::ReadAllText($path) | ConvertFrom-Json -DateKind String + & $case.Edit $edited + Remove-Item -LiteralPath $path, ($path + '.sha256') -Force + [IO.File]::WriteAllText($path, ($edited | ConvertTo-Json -Depth 12), (New-Object Text.UTF8Encoding($true))) + [IO.File]::WriteAllText($path + '.sha256', (Get-PraHash $path), (New-Object Text.UTF8Encoding($true))) + { Import-PraProof $context $path $source 'Convert' } | Should -Throw $case.Message -Because $case.Name + } + } + It 'Find-PraConvertedBatch names the partial batch for an object that it converted, and not for the others' { + $global:PraGate.R2Lookup = @{ Root = $global:PraGate.R2.State.BackupFolder; Converted = ([string]$global:PraGate.R2Plans[0].Record.ObjectGuid); Other = ([string]$global:PraGate.R2Plans[4].Record.ObjectGuid) } + $found = InModuleScope PRA.Directory { + $context = @{ Config = @{ Environment = 'SYNTHETIC_GATE'; Storage = @{ BackupFolder = $global:PraGate.R2Lookup.Root } } } + @{ Converted = (Find-PraConvertedBatch $context $global:PraGate.R2Lookup.Converted); Other = (Find-PraConvertedBatch $context $global:PraGate.R2Lookup.Other) } + } + $found.Converted.ShortId | Should -BeExactly $global:PraGate.R2Id.Substring(0, 8) + $found.Other | Should -BeNullOrEmpty + } + It 'the same CSV is refused for its first converted object with the command that continues the batch; the objects left are eligible' { + $refused = Invoke-GateProcess $global:PraGate.R2 @{Action='Convert';Phase='AD';Mode='Preview';CsvPath=$global:PraGate.R2Csv;ConfigPath=$global:PraGate.R2.ConfigPath} -TimeoutSeconds 120 + $refused.ExitCode | Should -Be 1 -Because ($refused.Output + $refused.Error) + $refused.Output | Should -Match ('is already converted by batch ' + $global:PraGate.R2Id.Substring(0, 8)) + $refused.Output | Should -Match ('-Action Convert -Phase AD -Mode Apply -Batch ' + $global:PraGate.R2Id.Substring(0, 8)) + $rest = Invoke-GateProcess $global:PraGate.R2 @{Action='Convert';Phase='AD';Mode='Preview';CsvPath=$global:PraGate.R2Rest;ConfigPath=$global:PraGate.R2.ConfigPath} -TimeoutSeconds 120 + $rest.ExitCode | Should -Be 0 -Because ($rest.Output + $rest.Error) + $rest.MainResult.PlannedCount | Should -Be 7 + } + It 'continues the converted objects with -Phase AD -Batch: AD is not written, the three are handed over, the object the batch stopped on is told as maybe changed, the six others as not converted, with a CSV to convert them or the rollback' { + $before = @(Get-GateWrites $global:PraGate.R2).Count + $run = Invoke-GateProcess $global:PraGate.R2 @{Action='Convert';Phase='AD';Mode='Apply';Force=$true;ConfigPath=$global:PraGate.R2.ConfigPath;Batch=$global:PraGate.R2Id.Substring(0, 8)} -TimeoutSeconds 120 + $run.ExitCode | Should -Be 2 -Because ($run.Output + $run.Error) + @(Get-GateWrites $global:PraGate.R2).Count | Should -Be $before + $run.MainResult.PendingCount | Should -Be 4 -Because 'three handed over, one that may be partly changed' + $run.MainResult.SkippedCount | Should -Be 6 + $run.MainResult.ErrorCount | Should -Be 0 + $run.Output | Should -Match '6 object\(s\) of this batch were not converted by it' + $run.Output | Should -Match '1 object\(s\) may be partly changed \(the batch stopped on them after a write was started\): user3' + $short = $global:PraGate.R2Id.Substring(0, 8) + $steps = @($run.MainResult.NextSteps) + ($steps -join "`n") | Should -Match 'Copy these two files' + $at = @($steps | Where-Object { $_ -match ('^6 object\(s\) were not converted by batch ' + $short + ' \(it stopped at its first error, nothing was written to them\): user4, user5, user6, user7, user8, user9\. .*the file .*ToConvert-' + $short) }) + $at.Count | Should -Be 1 -Because ($steps -join "`n") + ($steps -join "`n") | Should -Match '-Action Convert -Phase AD -CsvPath ''[^'']*ToConvert-' + ($steps -join "`n") | Should -Match '1 object\(s\) may be partly changed: user3\.' + ($steps -join "`n") | Should -Match ('-Action Recover -Batch ' + $short + ' -ConfigPath') + $csv = [regex]::Match(($steps -join "`n"), 'with the file (?

[^ ]+\.csv), which lists only them').Groups['p'].Value + Test-Path -LiteralPath $csv | Should -BeTrue -Because ($steps -join "`n") + @(Import-Csv -LiteralPath $csv).Identity -join ',' | Should -BeExactly 'user4,user5,user6,user7,user8,user9' + Test-Path -LiteralPath $run.MainResult.TransferPackage | Should -BeTrue + } + It 'the cloud part of the partial batch takes the three converted objects only; Check reads every object of the backup' { + $short = $global:PraGate.R2Id.Substring(0, 8) + $cloud = Invoke-GateProcess $global:PraGate.R2 @{Action='Convert';Phase='Cloud';Mode='Apply';Force=$true;ConfigPath=$global:PraGate.R2.ConfigPath;Batch=$short} -TimeoutSeconds 120 + $cloud.ExitCode | Should -Be 2 -Because ($cloud.Output + $cloud.Error) + $seen = @(Get-GateEvents $global:PraGate.R2 | Where-Object Operation -eq 'CloudRows-SyntheticBarrier') + $seen[$seen.Count - 1].Rows.Count | Should -Be 3 + $cloud.MainResult.SkippedCount | Should -Be 6 + $cloud.Output | Should -Match '6 object\(s\) of this batch were not converted by it' + $cloudSteps = @($cloud.MainResult.NextSteps | Where-Object { $_ -match 'Action (Recover|Convert) ' -and $_ -match 'Invoke-PraRemoteMailbox' }) + @($cloudSteps | Where-Object { $_ -match 'Action Recover -Batch|Action Convert -Phase AD( |$)' }).Count | Should -Be 2 + @($cloudSteps | Where-Object { ($_ -match 'Action Recover -Batch|Action Convert -Phase AD( |$)') -and $_ -match '-ConfigPath' }).Count | Should -Be 0 -Because 'the AD-side commands are for the AD server: no configuration path of this server' + @($cloud.MainResult.NextSteps | Where-Object { $_ -match '^On the AD server: ' }).Count | Should -BeGreaterThan 0 + $check = Invoke-GateProcess $global:PraGate.R2 @{Action='Check';Batch=$short;ConfigPath=$global:PraGate.R2.ConfigPath} -TimeoutSeconds 120 + $check.ExitCode | Should -Be 0 -Because ($check.Output + $check.Error) + $seen = @(Get-GateEvents $global:PraGate.R2 | Where-Object Operation -eq 'CloudRows-SyntheticBarrier') + $seen[$seen.Count - 1].Rows.Count | Should -Be 10 + } + It 'Recover of the partial batch restores the converted objects; Check -Batch given the Recover batch finds its Convert source' { + $short = $global:PraGate.R2Id.Substring(0, 8) + # Another batch converted user5 since: this batch never touched it, so its rollback must leave it alone. + $state = [Management.Automation.PSSerializer]::Deserialize([IO.File]::ReadAllText($global:PraGate.R2.StatePath)) + $other = @($state.Users | Where-Object SamAccountName -eq 'user5')[0] + $other.homeMDB = $null; $other.msExchRecipientTypeDetails = [long]2147483648; $other.targetAddress = 'SMTP:user5@other.invalid' + [IO.File]::WriteAllText($global:PraGate.R2.StatePath, [Management.Automation.PSSerializer]::Serialize($state, 35)) + $before = @(Get-GateWrites $global:PraGate.R2 | Where-Object Operation -eq 'Set-ADUser').Count + $recover = Invoke-GateProcess $global:PraGate.R2 @{Action='Recover';Phase='AD';Mode='Apply';Force=$true;ConfigPath=$global:PraGate.R2.ConfigPath;Batch=$short} -TimeoutSeconds 120 + $recover.ExitCode | Should -Be 2 -Because ($recover.Output + $recover.Error) + $recover.MainResult.ErrorCount | Should -Be 0 + $recover.MainResult.TotalCount | Should -Be 10 + $recover.MainResult.SkippedCount | Should -Be 6 -Because 'the objects the batch never touched are not rolled back (one of them was converted by another batch since)' + (@(Get-GateWrites $global:PraGate.R2 | Where-Object Operation -eq 'Set-ADUser').Count - $before) | Should -Be 3 + $converted = @(Get-GateEvents $global:PraGate.R2 | Where-Object { $_.Operation -eq 'Set-ADUser' } | ForEach-Object { [string]$_.Identity }) + @($converted | Where-Object { $_ -match '^00000000-0000-0000-0000-0*(5)$' }).Count | Should -Be 0 + $recoverId = [string]$recover.MainResult.BatchId + $recoverId | Should -Match '^[0-9a-f]{8}$' + $check = Invoke-GateProcess $global:PraGate.R2 @{Action='Check';Batch=$recoverId;Expect='Deprovisioned';Once=$true;ConfigPath=$global:PraGate.R2.ConfigPath} -TimeoutSeconds 120 + $check.ExitCode | Should -Be 0 -Because ($check.Output + $check.Error) + $check.Output | Should -Match ('Batch ' + $recoverId + ' is a Recover batch: the Convert batch ' + $short + ' that it rolled back is checked') + $wrongDefault = Invoke-GateProcess $global:PraGate.R2 @{Action='Check';Batch=$recoverId.ToUpperInvariant();Once=$true;ConfigPath=$global:PraGate.R2.ConfigPath} -TimeoutSeconds 120 + $wrongDefault.Output | Should -Match 'give -Expect Deprovisioned' -Because 'the batch ID is accepted in any letter case' + } + It 'a Convert batch that a Recover already rolled back cannot be resumed: -Phase AD -Batch and the cloud part refuse it with a next step, nothing is changed' { + $short = $global:PraGate.R2Id.Substring(0, 8) + $before = @(Get-GateWrites $global:PraGate.R2).Count + foreach ($phase in 'AD', 'Cloud') { + $run = Invoke-GateProcess $global:PraGate.R2 @{Action='Convert';Phase=$phase;Mode='Apply';Force=$true;ConfigPath=$global:PraGate.R2.ConfigPath;Batch=$short} -TimeoutSeconds 120 + $run.ExitCode | Should -Be 1 -Because ($run.Output + $run.Error) + $run.Output | Should -Match ('Convert batch ' + $short + ' cannot be resumed: Recover batch [0-9a-f]{8} already rolled back objects of it') -Because $phase + ($run.MainResult.NextSteps -join "`n") | Should -Match '-Action Check -Batch [0-9a-f]{8} -Expect Deprovisioned' -Because $phase + ($run.MainResult.NextSteps -join "`n") | Should -Match '-Action Convert -Phase AD -ConfigPath' -Because $phase + $run.Output | Should -Not -Match 'Copy these two files' + } + @(Get-GateWrites $global:PraGate.R2).Count | Should -Be $before + } + It 'a Recover that stopped before its proof counts too: its journal tells the objects it started on, and a missing journal counts for every object' { + $short = $global:PraGate.R2Id.Substring(0, 8) + $convertName = Split-Path $global:PraGate.R2Folder -Leaf + $recoverFolder = @(Get-ChildItem -LiteralPath $global:PraGate.R2.State.BackupFolder -Directory -Filter 'Batch-*' | Where-Object { $_.Name -ne $convertName })[0].FullName + foreach ($file in @(Get-ChildItem -LiteralPath $recoverFolder -File -Filter 'State-*')) { Remove-Item -LiteralPath $file.FullName -Force } + foreach ($phase in 'AD', 'Cloud') { + $run = Invoke-GateProcess $global:PraGate.R2 @{Action='Convert';Phase=$phase;Mode='Apply';Force=$true;ConfigPath=$global:PraGate.R2.ConfigPath;Batch=$short} -TimeoutSeconds 120 + $run.ExitCode | Should -Be 1 -Because ($run.Output + $run.Error) + $run.Output | Should -Match ('Convert batch ' + $short + ' cannot be resumed: Recover batch [0-9a-f]{8} started to roll back objects of it \(it stopped before its proof\)') -Because $phase + ($run.MainResult.NextSteps -join "`n") | Should -Match '-Action Recover -Batch ' -Because $phase + } + $journal = @(Get-ChildItem -LiteralPath $recoverFolder -File -Filter 'Journal-*.jsonl')[0] + Rename-Item -LiteralPath $journal.FullName -NewName ($journal.Name + '.away') + $run = Invoke-GateProcess $global:PraGate.R2 @{Action='Convert';Phase='AD';Mode='Apply';Force=$true;ConfigPath=$global:PraGate.R2.ConfigPath;Batch=$short} -TimeoutSeconds 120 + $run.ExitCode | Should -Be 1 -Because ($run.Output + $run.Error) + $run.Output | Should -Match 'its journal is not here: every object counts as rolled back' + } +} + +Describe 'Release 3.2.0 - the object a batch stopped on, the CSV of the objects left, the AD proof of a batch whose objects were all verified (real main and production Directory module, synthetic AD)' -Tag 'Release320a' { + It 'a CSV of the objects still to convert (same columns as the input) is written and named in the Next steps; the object the batch stopped on is not in it and gets the rollback' { + $runtime = New-GateRuntime -Name 'csv-left-320a' -Case 'FailAtSam' -UserCount 10 -Extra @{ FailSam = 'user3' } + $csv = Join-Path $runtime.Root 'input.csv' + [IO.File]::WriteAllText($csv, ("Identity,Note`r`n" + ((1..10 | ForEach-Object { 'user' + $_ + ',note ' + $_ }) -join "`r`n") + "`r`n"), (New-Object Text.UTF8Encoding($true))) + $run = Invoke-GateProcess $runtime @{Action='Convert';Phase='AD';Mode='Apply';Force=$true;CsvPath=$csv;ConfigPath=$runtime.ConfigPath} -TimeoutSeconds 120 + $run.ExitCode | Should -Be 1 -Because ($run.Output + $run.Error) + $steps = @($run.MainResult.NextSteps) + $joined = $steps -join "`n" + $joined | Should -Match '6 object\(s\) were not converted by batch [0-9a-f]{8} \(it stopped at its first error, nothing was written to them\): user4, user5, user6, user7, user8, user9\.' + $joined | Should -Match '1 object\(s\) may be partly changed: user3\.' + $left = [regex]::Match($joined, 'with the file (?

[^ ]+\.csv), which lists only them').Groups['p'].Value + Test-Path -LiteralPath $left | Should -BeTrue -Because $joined + $rows = @(Import-Csv -LiteralPath $left) + ($rows.Identity -join ',') | Should -BeExactly 'user4,user5,user6,user7,user8,user9' + ($rows.Note -join ',') | Should -BeExactly 'note 4,note 5,note 6,note 7,note 8,note 9' + $command = @($steps | Where-Object { $_ -match '^\.\\Invoke-PraRemoteMailbox\.ps1 -Action Convert -Phase AD .*-CsvPath' }) + $command.Count | Should -Be 1 + $command[0] | Should -Match ([regex]::Escape("-CsvPath '" + $left + "'")) + $command[0] | Should -Not -Match ([regex]::Escape($csv)) + $run.Output | Should -Match '(?m)^\s*RESULT: FAIL\s*$' + } + It 'an object that failed before any write is not partly changed: it is listed as not converted, and no journal line names it' { + $runtime = New-GateRuntime -Name 'untouched-320a' -UserCount 3 + $env:PRA_GATE_STATE = $runtime.StatePath; $env:PSModulePath = $runtime.Modules + ';' + (Join-Path $PSHOME 'Modules') + Remove-Module PRA.Directory -Force -ErrorAction SilentlyContinue + Get-Module ActiveDirectory -All | Remove-Module -Force -ErrorAction Stop + Import-Module (Join-Path $runtime.Modules 'ActiveDirectory\ActiveDirectory.psm1') -Force -Global + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Directory.psm1') -Force -Global + $context = New-GateContext $runtime + $plans = @(foreach ($sam in 'user1', 'user2', 'user3') { New-PraPlan $context $sam 'Convert' }) + $plans[1].ExpectedUsnChanged = '1' + $failure = '' + try { $null = Invoke-PraAdBatch $context $plans 'Convert' } catch { $failure = [string]$_.Exception.Message } + $failure | Should -Match 'uSNChanged changed' + $partial = $context.PartialBatch + $partial.Verified | Should -Be 1 + @($partial.MayBeChanged).Count | Should -Be 0 + @($partial.NotConverted) -join ',' | Should -BeExactly 'user2,user3' + $touched = Get-PraJournalTouchedObject -Path $context.JournalPath + $touched.Count | Should -Be 1 + $touched.Contains([string]$plans[1].Record.ObjectGuid) | Should -BeFalse + } + It 'every object verified and the State write fails: the proof written is the normal one, and Import-PraProof accepts it' { + $runtime = New-GateRuntime -Name 'allverified-320a' -UserCount 3 + $env:PRA_GATE_STATE = $runtime.StatePath; $env:PSModulePath = $runtime.Modules + ';' + (Join-Path $PSHOME 'Modules') + Remove-Module PRA.Directory -Force -ErrorAction SilentlyContinue + Get-Module ActiveDirectory -All | Remove-Module -Force -ErrorAction Stop + Import-Module (Join-Path $runtime.Modules 'ActiveDirectory\ActiveDirectory.psm1') -Force -Global + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Directory.psm1') -Force -Global + $context = New-GateContext $runtime + $plans = @(foreach ($sam in 'user1', 'user2', 'user3') { New-PraPlan $context $sam 'Convert' }) + $global:PraGate.StateFail320 = 1 + $failure = '' + InModuleScope PRA.Directory -Parameters @{ Context = $context; Plans = $plans } { + $script:OriginalWrite320 = (Get-Command Write-PraImmutableFile -CommandType Function).ScriptBlock + Mock Write-PraImmutableFile { & $script:OriginalWrite320 -Path $Path -Text $Text } + Mock Write-PraImmutableFile { throw 'SYNTHETIC: disk full' } -ParameterFilter { ([string]$Path -like '*\State-*.json') -and ($global:PraGate.StateFail320-- -gt 0) } + try { $null = Invoke-PraAdBatch $Context $Plans 'Convert' } catch { $global:PraGate.StateFailure320 = [string]$_.Exception.Message } + } + $global:PraGate.StateFailure320 | Should -Match 'disk full' + $partial = $context.PartialBatch + $partial.Complete | Should -BeTrue + $proof = [IO.File]::ReadAllText($partial.StatePath) | ConvertFrom-Json -DateKind String + $proof.PSObject.Properties.Name | Should -Not -Contain 'Partial' + @($proof.Records).Count | Should -Be 3 + $source = Import-PraBackup $context @(Get-ChildItem -LiteralPath $runtime.State.BackupFolder -Recurse -File -Filter 'Convert-*.json')[0].FullName + $accepted = Import-PraProof $context $partial.StatePath $source 'Convert' + $accepted.Partial | Should -BeFalse + @($accepted.Data.Records).Count | Should -Be 3 + $global:PraGate.Remove('StateFail320'); $global:PraGate.Remove('StateFailure320') + } + It 'in phase Both an object is Pending as soon as it is verified, so that a stop or an interruption never leaves it done' { + foreach ($phase in 'Both', 'AD') { + $runtime = New-GateRuntime -Name ('both-pending-320a-' + $phase) -Case 'FailAtSam' -UserCount 2 -Extra @{ FailSam = 'user2' } + $env:PRA_GATE_STATE = $runtime.StatePath; $env:PSModulePath = $runtime.Modules + ';' + (Join-Path $PSHOME 'Modules') + Remove-Module PRA.Directory -Force -ErrorAction SilentlyContinue + Get-Module ActiveDirectory -All | Remove-Module -Force -ErrorAction Stop + Import-Module (Join-Path $runtime.Modules 'ActiveDirectory\ActiveDirectory.psm1') -Force -Global + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Directory.psm1') -Force -Global + $context = New-GateContext $runtime + $context.Phase = $phase + $plans = @(foreach ($sam in 'user1', 'user2') { New-PraPlan $context $sam 'Convert' }) + try { $null = Invoke-PraAdBatch $context $plans 'Convert' } catch { $null = $_ } + $plans[0].Row.ADVerified | Should -BeTrue + $plans[0].Row.FinalStatus | Should -BeExactly $(if ($phase -eq 'Both') { 'Pending' } else { 'Success' }) + } + } + It 'a run refused by the domain controller before any write names no batch: not on the card, not in the result' { + $runtime = New-GateRuntime -Name 'notapplied-320a' -Case 'AccessDenied' + $run = Invoke-GateProcess $runtime @{Action='Convert';Phase='AD';Mode='Apply';Force=$true;ConfigPath=$runtime.ConfigPath} -TimeoutSeconds 120 + $run.ExitCode | Should -Be 1 -Because ($run.Output + $run.Error) + $run.Output | Should -Match 'NOT-APPLIED' + $run.Output | Should -Not -Match '(?m)^\s*\S+\s+Batch\s+[0-9a-f]{8}\s*$' + [string]$run.MainResult.BatchId | Should -BeExactly '' + $run.Output | Should -Not -Match '\(batch [0-9a-f]{8}\)' + } +} + +Describe 'Release 3.2.0 - the global report: a later stage that covers the cloud side replaces the cloud error of an earlier phase Both stage (production Common module)' -Tag 'Release320a' { + BeforeAll { + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global + $script:R5Root = Join-Path $global:PraGate.Root ('r5-' + [guid]::NewGuid().ToString('N').Substring(0, 8)) + $null = New-Item -ItemType Directory -Path $script:R5Root -Force + $script:R5Dot = [string][char]0x00B7 + function global:New-R5Row { + param([string]$Sam, [string]$Status, [string]$Cloud, [string]$Guid, [bool]$AdVerified = $true) + [pscustomobject]@{ ObjectGuid = $Guid; SamAccountName = $Sam; UserPrincipalName = "$Sam@contoso.com"; Action = 'Convert'; IsShared = $false; ADApplied = $true; ADVerified = $AdVerified + BackupPath = 'D:\PRA\Backups\Batch-x\Convert.json'; CloudStatus = $Cloud; CloudDetail = ''; FinalStatus = $Status; Detail = $(if ($Status -eq 'Error') { 'cloud: not ready in time' } else { 'detail' }); Warnings = ''; LastOperation = ''; GroupAction = '' + CloudMailbox = $null; CloudLicense = $null; PreserveCloudMailbox = $false; PreserveLicense = $false; DeprovisionConfirmed = $false; PermDetail = ''; PermMissing = @() } + } + function global:New-R5Context { + param([string]$Phase, [object[]]$Rows, [string[]]$PhaseFolders = @(), [int]$Minutes = 0, [string]$Name = 'run') + $context = @{ Root = $global:PraGate.Package; Version = '3.2.0'; RunId = ((Get-Date -Format 'yyyyMMdd_HHmmss') + '-' + [guid]::NewGuid().ToString('N')); StartTime = (Get-Date).AddMinutes($Minutes); Action = 'Convert'; Mode = 'Apply'; Phase = $Phase + CurrentPhase = 'Start'; CurrentOperation = ''; CurrentIdentity = ''; StepIndex = 0; StepTotal = 0; Warnings = 0; Issues = (New-Object 'Collections.Generic.List[object]'); Rows = (New-Object 'Collections.Generic.List[object]') + Server = 'dc01.contoso.com'; Config = @{ Environment = 'GATE'; Cloud = @{ Organization = 'contoso.onmicrosoft.com' } }; AllowMutation = $true; ReportFolder = (Join-Path $script:R5Root ('reports-' + $Name)); NoReport = $false; BatchId = 'abcd1234' + LogFile = ''; NextSteps = @(); ExitCode = 0; CloudConnectFailed = $false; ResultStatus = ''; PhaseFolders = $PhaseFolders; ConfigOverrides = @() } + foreach ($row in $Rows) { $context.Rows.Add($row) } + $context + } + } + AfterAll { Remove-Item -LiteralPath 'Function:\New-R5Row', 'Function:\New-R5Context' -ErrorAction SilentlyContinue } + It 'user2 failed in the cloud part of the Both run and was completed by -Phase Cloud: done, not failed; the earlier error stays in the journey as an Earlier run line' { + $folder = Join-Path $script:R5Root 'Batch-1111111111'; $null = New-Item -ItemType Directory -Path $folder -Force + $g1 = [guid]::NewGuid().ToString(); $g2 = [guid]::NewGuid().ToString() + $both = New-R5Context -Phase Both -Rows @((New-R5Row 'user1' 'Success' 'Success' $g1), (New-R5Row 'user2' 'Error' 'Error' $g2)) -Minutes -10 -Name 'both' + $null = Save-PraPhaseData -Context $both -Folder $folder -HandOff '' + $cloud = New-R5Context -Phase Cloud -Rows @((New-R5Row 'user2' 'Success' 'Success' $g2)) -PhaseFolders @($folder) -Minutes 0 -Name 'cloud' + $report = Write-PraGlobalReport -Context $cloud + $model = $cloud.GlobalModel + @($model.Phases | ForEach-Object Label) -join '|' | Should -BeExactly "Convert $script:R5Dot AD + Cloud|Convert $script:R5Dot Cloud" + $user2 = $model.Objects | Where-Object Name -eq 'user2@contoso.com' + $user2.Verdict | Should -BeExactly 'done' + $model.Counts.Failed | Should -Be 0 + @($user2.Stages | ForEach-Object Status) -join ',' | Should -BeExactly 'Error,Success' + @($user2.Stages[1].Steps | Where-Object Step -eq 'Earlier run').Count | Should -Be 1 + (@($user2.Stages[1].Steps | Where-Object Step -eq 'Earlier run')[0].Text) | Should -Match 'cloud: not ready in time' + $html = [IO.File]::ReadAllText($report.Html) + $html | Should -Match 'Earlier run' + $html | Should -Not -Match '

Result
Failed
' + } + It 'an error that is not on the cloud side stays final, and so does a cloud error that no later stage covers' { + $folder = Join-Path $script:R5Root 'Batch-2222222222'; $null = New-Item -ItemType Directory -Path $folder -Force + $g1 = [guid]::NewGuid().ToString(); $g2 = [guid]::NewGuid().ToString() + $both = New-R5Context -Phase Both -Rows @((New-R5Row 'user1' 'Error' 'N/A' $g1 -AdVerified $false), (New-R5Row 'user2' 'Error' 'Error' $g2)) -Minutes -10 -Name 'both2' + $null = Save-PraPhaseData -Context $both -Folder $folder -HandOff '' + $cloud = New-R5Context -Phase Cloud -Rows @((New-R5Row 'user1' 'Success' 'Success' $g1)) -PhaseFolders @($folder) -Minutes 0 -Name 'cloud2' + $null = Write-PraGlobalReport -Context $cloud + ($cloud.GlobalModel.Objects | Where-Object Name -eq 'user1@contoso.com').Verdict | Should -BeExactly 'failed' -Because 'its AD part failed: a cloud run does not repair it' + ($cloud.GlobalModel.Objects | Where-Object Name -eq 'user2@contoso.com').Verdict | Should -BeExactly 'failed' -Because 'the cloud run did not list this object' + $cloud.GlobalModel.Counts.Failed | Should -Be 2 + } +} + +Describe 'Release 3.2.0 - the shared mailbox permissions follow the batch: stored at Convert, used by the cloud phase, a record that carries permissions while nothing is granted is an error (production Cloud and Directory modules, synthetic)' -Tag 'Release320a' { + BeforeAll { + $global:PraGate.R6NetworkPath = Join-Path $global:PraGate.Root 'PraGateR6Network.psm1' + [IO.File]::WriteAllText($global:PraGate.R6NetworkPath, "if (`$env:PRA_GATE_NONET -cne 'SYNTHETIC-NO-NETWORK') { throw 'Synthetic interlock absent.' }`nExport-ModuleMember -Function @()`n", (New-Object Text.UTF8Encoding($true))) + Get-Module PRA.Cloud -All | Remove-Module -Force -ErrorAction SilentlyContinue + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Cloud.psm1') -Force -Global + } + AfterAll { Remove-Module PRA.Cloud -Force -ErrorAction SilentlyContinue } + It 'Get-PraPermissionRequest takes the settings of the batch when the context has them, the configuration of the server otherwise' { + $global:PraGate.R6Row = [pscustomobject]@{ IsShared = $true; SharedFullAccess = @('a@gate.invalid'); SharedSendAs = @('b@gate.invalid'); SharedSendOnBehalf = @('c@gate.invalid') } + $global:PraGate.R6Config = @{ SharedMailbox = @{ Enabled = $true; PermissionSource = 'AD'; GrantFullAccess = $true; GrantSendAs = $true; GrantSendOnBehalf = $true } } + $rights = InModuleScope PRA.Cloud { + $server = @{ Config = $global:PraGate.R6Config } + $batch = @{ Config = $global:PraGate.R6Config; BatchGrantSettings = @{ Enabled = $true; PermissionSource = 'AD'; GrantFullAccess = $true; GrantSendAs = $false; GrantSendOnBehalf = $false } } + $off = @{ Config = @{ SharedMailbox = @{ Enabled = $false; PermissionSource = 'AD'; GrantFullAccess = $true; GrantSendAs = $true; GrantSendOnBehalf = $true } }; BatchGrantSettings = @{ Enabled = $true; PermissionSource = 'None'; GrantFullAccess = $true; GrantSendAs = $true; GrantSendOnBehalf = $true } } + @{ Server = @(Get-PraPermissionRequest $server $global:PraGate.R6Row | ForEach-Object Right) -join ','; Batch = @(Get-PraPermissionRequest $batch $global:PraGate.R6Row | ForEach-Object Right) -join ','; Off = @(Get-PraPermissionRequest $off $global:PraGate.R6Row | ForEach-Object Right) -join ',' } + } + $rights.Server | Should -BeExactly 'FullAccess,SendAs,SendOnBehalf' + $rights.Batch | Should -BeExactly 'FullAccess' -Because 'the batch grants FullAccess only, whatever this server says' + $rights.Off | Should -BeExactly 'SendOnBehalf' -Because 'the batch says PermissionSource None: only SendOnBehalf, although this server has the setting off' + } + It 'a permission that the settings in force do not grant is never silent, for an old batch and for a batch whose own settings grant none: a warning that names each permission, the row says to grant it by hand, no error' { + foreach ($source in 'Configuration', 'Batch') { + $runtime = New-GateRuntime -Name ('grant-none-320a-' + $source) + $context = New-GateContext $runtime -Mode Apply -Action Convert + $context.Phase = 'Cloud'; $context.Once = $true; $context.IntervalMinutes = 0; $context.TimeoutMinutes = 1; $context.GrantSettingsSource = $source + $context.Config.Cloud = @{ CheckMailbox = $false; CheckLicense = $false; MailboxCheckVia = 'Exo'; RequiredSkuPartNumber = ''; TenantId = '20000000-0000-0000-0000-000000000002' } + $context.Config.SharedMailbox = @{ Enabled = $false; PermissionSource = 'AD'; GrantFullAccess = $false; GrantSendAs = $false; GrantSendOnBehalf = $false } + $context.LogFile = Join-Path $runtime.Root 'logs\grant-none.log' + if ($source -eq 'Batch') { $context.BatchGrantSettings = @{ Enabled = $true; PermissionSource = 'AD'; GrantFullAccess = $false; GrantSendAs = $false; GrantSendOnBehalf = $false } } + $global:PraGate.R6Context = $context + $global:PraGate.R6Row = New-PraRow $context ([pscustomobject]@{ ObjectGuid = '00000000-0000-0000-0000-000000000001'; UserPrincipalName = 'shared1@gate.invalid'; SamAccountName = 'shared1'; IsShared = $true }) + $global:PraGate.R6Row.SharedFullAccess = @('a@gate.invalid'); $global:PraGate.R6Row.SharedSendAs = @('b@gate.invalid') + InModuleScope PRA.Cloud { + Mock Close-PraCloudSession { } + Invoke-PraCloudPhase $global:PraGate.R6Context @($global:PraGate.R6Row) 'Convert' + } + $row = $global:PraGate.R6Row; $context = $global:PraGate.R6Context + $context.Issues.Count | Should -Be 0 -Because $source + $row.FinalStatus | Should -Not -BeExactly 'Error' + $context.Warnings | Should -Be 1 -Because $source + $warning = @(Get-PraList $context 'WarningList')[0].Message + $warning | Should -Match 'shared1@gate\.invalid: 2 shared mailbox permission\(s\) not granted by ' + $warning | Should -Match 'to grant by hand: FullAccess a@gate\.invalid; SendAs b@gate\.invalid\.' + $warning | Should -Match $(if ($source -eq 'Batch') { 'the settings the batch was converted with' } else { 'the settings of this server \(this batch does not record its own\)' }) + $row.Warnings | Should -Match 'to grant by hand: FullAccess a@gate\.invalid; SendAs b@gate\.invalid' -Because 'the report and the CSV carry it' + } + } +} + +Describe 'Release 3.2.0 - the grant settings are stored in the batch at Convert and the cloud phase says which settings it uses (real main, 13 synthetic shared mailboxes)' -Tag 'Release320a' { + It 'stores SharedMailbox.Enabled, PermissionSource and the three Grant settings in the batch, and a cloud server with other settings warns and uses the batch values' { + $runtime = New-GateRuntime -Name 'grant-batch-320a' -Shared13 -Case CloudConfirmed13 + $ad = Invoke-GateProcess $runtime @{Action='Convert';Mode='Apply';Phase='AD';Force=$true;ConfigPath=$runtime.ConfigPath} -TimeoutSeconds 180 + $ad.ExitCode | Should -Be 2 -Because ($ad.Output + $ad.Error) + $json = @(Get-ChildItem -LiteralPath $runtime.State.BackupFolder -Recurse -File -Filter 'Convert-*.json')[0] + $batch = [IO.File]::ReadAllText($json.FullName) | ConvertFrom-Json -DateKind String + $batch.GrantSettings.Enabled | Should -BeTrue + $batch.GrantSettings.PermissionSource | Should -BeExactly 'AD' + $batch.GrantSettings.GrantFullAccess | Should -BeTrue + $batch.GrantSettings.GrantSendAs | Should -BeTrue + $batch.GrantSettings.GrantSendOnBehalf | Should -BeTrue + Set-GateConfigText $runtime { param($text) $text.Replace("PermissionSource='AD'", "PermissionSource='AD';GrantSendAs=`$false;GrantSendOnBehalf=`$false") } + $cloud = Invoke-GateProcess $runtime @{Action='Convert';Mode='Apply';Phase='Cloud';Force=$true;ConfigPath=$runtime.ConfigPath;Batch=[string]$ad.MainResult.BatchId} -TimeoutSeconds 180 + $cloud.Output | Should -Match ([regex]::Escape('The shared mailbox permission settings of this server differ from the ones of the batch (GrantSendAs: batch True, this server False; GrantSendOnBehalf: batch True, this server False). The batch values are used: Enabled = True, PermissionSource = AD, GrantFullAccess = True, GrantSendAs = True, GrantSendOnBehalf = True.')) + } + It 'a batch of an older version has no stored settings: the configuration of this server is used, with a warning that says so' { + $runtime = New-GateRuntime -Name 'grant-legacy-320a' -Shared13 -Case CloudConfirmed13 + $env:PRA_GATE_STATE = $runtime.StatePath; $env:PSModulePath = $runtime.Modules + ';' + (Join-Path $PSHOME 'Modules') + Remove-Module PRA.Directory -Force -ErrorAction SilentlyContinue + Get-Module ActiveDirectory -All | Remove-Module -Force -ErrorAction Stop + Import-Module (Join-Path $runtime.Modules 'ActiveDirectory\ActiveDirectory.psm1') -Force -Global + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Directory.psm1') -Force -Global + $context = New-GateContext $runtime + $plans = @(1..13 | ForEach-Object { New-PraPlan $context ('user' + $_) 'Convert' }) + $source = InModuleScope PRA.Directory -Parameters @{ Context = $context; Plans = $plans } { + Mock Get-PraGrantSettingSnapshot { $null } + Invoke-PraAdBatch $Context $Plans 'Convert' + } + [IO.File]::WriteAllText($runtime.StatePath, [Management.Automation.PSSerializer]::Serialize($global:PraGateAd, 35)) + ([IO.File]::ReadAllText($source.Path) | ConvertFrom-Json -DateKind String).GrantSettings | Should -BeNullOrEmpty + $cloud = Invoke-GateProcess $runtime @{Action='Convert';Mode='Apply';Phase='Cloud';Force=$true;ConfigPath=$runtime.ConfigPath;Batch=$source.Path} -TimeoutSeconds 180 + $cloud.Output | Should -Match ([regex]::Escape('This batch was written by an older version: it does not record the shared mailbox permission settings, so the configuration of this server decides (')) + } +} + +Describe 'Release 3.2.0 - small items of the common module: module minimum, event file, configuration differences, plain messages (production Common module)' -Tag 'Release320a' { + BeforeAll { Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global } + It 'Exo.MinModuleVersion cannot lower the built-in minimum' { + $modules = @( + [pscustomobject]@{ Name = 'ExchangeOnlineManagement'; Version = [version]'3.9.5' } + [pscustomobject]@{ Name = 'Microsoft.Graph.Authentication'; Version = [version]'2.41.1' } + [pscustomobject]@{ Name = 'Microsoft.Graph.Users'; Version = [version]'2.41.1' }) + $report = Get-PraCloudModuleReport -MinExo '3.9.0' -Available $modules -Loaded @() + $report.Exo.Ok | Should -BeFalse + $report.Exo.Message | Should -Match 'the tool needs 3\.10\.1 or later|needs 3\.10\.1' + (Get-PraCloudModuleReport -MinExo '3.11.0' -Available @($modules + [pscustomobject]@{ Name = 'ExchangeOnlineManagement'; Version = [version]'3.10.2' }) -Loaded @()).Exo.Message | Should -Match '3\.11\.0' + (Get-PraCloudModuleReport -MinExo '3.9.0' -Available @($modules[1], $modules[2], [pscustomobject]@{ Name = 'ExchangeOnlineManagement'; Version = [version]'3.10.1' }) -Loaded @()).Exo.Ok | Should -BeTrue + } + It 'a write of the event file that fails never stops the run, and it is said once' { + $file = Join-Path $global:PraGate.Root ('events-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.jsonl') + $old = $env:PRA_EVENT_FILE; $env:PRA_EVENT_FILE = $file + $hold = New-Object IO.FileStream($file, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::None) + InModuleScope PRA.Common { $script:PraEventWriteWarned = $false } + try { + $first = & { Write-PraEvent -Kind count -Data @{ count = 1 } } 6>&1 | Out-String + $second = & { Write-PraEvent -Kind count -Data @{ count = 2 } } 6>&1 | Out-String + } + finally { $hold.Dispose(); $env:PRA_EVENT_FILE = $old } + $first | Should -Match 'The progress file of the window cannot be written' + $second | Should -Not -Match 'The progress file of the window cannot be written' + } + It 'a setting that differs by letter case only is not a change' { + $base = @{ Scope = @{ Mode = 'Auto'; SearchBase = 'OU=Tests,DC=gate,DC=invalid' }; Environment = 'Gate' } + @(Get-PraConfigurationDifference -Base $base -Effective @{ Scope = @{ Mode = 'AUTO'; SearchBase = 'ou=tests,dc=gate,dc=invalid' }; Environment = 'GATE' }).Count | Should -Be 0 + $changed = @(Get-PraConfigurationDifference -Base $base -Effective @{ Scope = @{ Mode = 'Csv'; SearchBase = 'OU=Tests,DC=gate,DC=invalid' }; Environment = 'Gate' }) + $changed.Count | Should -Be 1 + $changed[0].Key | Should -BeExactly 'Scope.Mode' + } + It 'the card, the console and the report show no stack line and no stray Exchange Online pipe; the log keeps the detail' { + $text = "The call failed.`r`n at Microsoft.Exchange.Foo.Bar(String x)`r`n at , C:\x\y.ps1: line 12`r`n--- End of inner exception stack trace ---`r`nOperation: ||You can't use this: the object is busy.|" + $plain = InModuleScope PRA.Common -Parameters @{ Text = $text } { ConvertTo-PraPlainMessage $Text } + $plain | Should -Not -Match 'Microsoft\.Exchange\.Foo|ScriptBlock|End of inner' + $plain | Should -Not -Match '\|\|' + $plain | Should -Match 'The call failed\.' + $plain | Should -Match "You can't use this: the object is busy\." + $ctx = @{ Root = $global:PraGate.Package; Version = '3.2.0'; RunId = ((Get-Date -Format 'yyyyMMdd_HHmmss') + '-' + [guid]::NewGuid().ToString('N')); StartTime = Get-Date; Action = 'Convert'; Mode = 'Apply'; Phase = 'AD' + CurrentPhase = 'Start'; CurrentOperation = ''; CurrentIdentity = ''; StepIndex = 0; Warnings = 0; Issues = (New-Object 'Collections.Generic.List[object]'); Rows = (New-Object 'Collections.Generic.List[object]') + Server = ''; Config = @{ Environment = 'GATE' }; AllowMutation = $true; ReportFolder = (Join-Path $global:PraGate.Root 'reports-320a'); NoReport = $true; BatchId = ''; LogFile = ''; TranscriptStarted = $false + NextSteps = @(); ExitCode = 1; CloudConnectFailed = $false; ResultStatus = '' } + $ctx.Issues.Add([pscustomobject]@{ Timestamp = 't'; Phase = 'p'; Operation = 'Cloud'; Identity = ''; Source = 'Cloud'; Message = $text }) + $result = Complete-PraRun -Context $ctx + $result.Issues[0].Message | Should -Not -Match 'Microsoft\.Exchange\.Foo|ScriptBlock' + $result.Issues[0].Message | Should -Match 'The call failed\.' + } + It 'a batch ID that ends with a line feed is not a batch ID' { + $runtime = New-GateRuntime -Name 'batch-id-lf-320a' + $run = Invoke-GateProcess $runtime @{Action='Recover';Phase='AD';Mode='Preview';ConfigPath=$runtime.ConfigPath;Batch=("deadbeef" + [char]10)} -ExplicitArguments -TimeoutSeconds 60 + $run.ExitCode | Should -Be 1 -Because ($run.Output + $run.Error) + ($run.MainResult.Issues.Message -join ' ') | Should -Match 'Invalid batch ID' + } +} + +Describe 'Release 3.2.0 - a Recover batch rolled back objects of a Convert batch: Find-PraRecoverOfBatch (production Directory module, synthetic folders)' -Tag 'Release320a' { + It 'finds the Recover batch by the hash of its Convert source and the objects it lists, and ignores another Environment and other objects' { + $root = Join-Path $global:PraGate.Root ('recover-of-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) + $id = 'a1b2c3d4e5f60718293a4b5c6d7e8f90' + $folder = Join-Path $root ('Batch-' + $id); $null = New-Item -ItemType Directory -Path $folder -Force + $hash = 'ab' * 32 + $state = [ordered]@{ SchemaVersion = 2; Operation = 'Recover'; Kind = 'ADVerified'; Environment = 'SYNTHETIC_GATE'; SourceBackupHash = $hash; Records = @([ordered]@{ ObjectGuid = '11111111-1111-1111-1111-111111111111'; Operation = 'Recover'; ADVerified = $true }) } + [IO.File]::WriteAllText((Join-Path $folder ('State-' + $id + '.json')), ($state | ConvertTo-Json -Depth 5), (New-Object Text.UTF8Encoding($true))) + $global:PraGate.RecoverOf = @{ Root = $root; Hash = $hash } + $found = InModuleScope PRA.Directory { + $context = @{ Config = @{ Environment = 'synthetic_gate'; Storage = @{ BackupFolder = $global:PraGate.RecoverOf.Root } } } + $other = @{ Config = @{ Environment = 'ANOTHER'; Storage = @{ BackupFolder = $global:PraGate.RecoverOf.Root } } } + @{ Same = (Find-PraRecoverOfBatch $context $global:PraGate.RecoverOf.Hash.ToUpperInvariant() @('11111111-1111-1111-1111-111111111111')) + Listed = (Find-PraRecoverOfBatch $context $global:PraGate.RecoverOf.Hash @()) + OtherObject = (Find-PraRecoverOfBatch $context $global:PraGate.RecoverOf.Hash @('22222222-2222-2222-2222-222222222222')) + OtherHash = (Find-PraRecoverOfBatch $context ('cd' * 32) @()) + OtherEnvironment = (Find-PraRecoverOfBatch $other $global:PraGate.RecoverOf.Hash @()) } + } + $found.Same.ShortId | Should -BeExactly 'a1b2c3d4' + $found.Listed.BatchId | Should -BeExactly $id + $found.OtherObject | Should -BeNullOrEmpty + $found.OtherHash | Should -BeNullOrEmpty + $found.OtherEnvironment | Should -BeNullOrEmpty + } +} + +Describe 'Release 3.2.0 - the exit code goes to the host only when the script is the entry of its own process; a Recover that stopped is found by its backup and its journal (production Common and Directory modules)' -Tag 'Release320a' { + BeforeAll { Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global } + It 'decides from the command line of the process: -File, -Command and -EncodedCommand are an own process, an interactive session is not, -NoExit is not' { + $pwsh = 'C:\Program Files\PowerShell\7\pwsh.exe' + Test-PraOwnEntryProcess -Arguments @($pwsh, '-NoProfile', '-File', 'C:\x\Invoke-PraRemoteMailbox.ps1', '-Action', 'Check') | Should -BeTrue + Test-PraOwnEntryProcess -Arguments @($pwsh, '-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', 'AAAA') | Should -BeTrue + Test-PraOwnEntryProcess -Arguments @($pwsh, '-Command', '& .\Invoke-PraRemoteMailbox.ps1') | Should -BeTrue + Test-PraOwnEntryProcess -Arguments @($pwsh, '-FILE', 'x.ps1') | Should -BeTrue -Because 'the option name is not case sensitive' + Test-PraOwnEntryProcess -Arguments @($pwsh) | Should -BeFalse -Because 'a window the operator opened and typed in' + Test-PraOwnEntryProcess -Arguments @($pwsh, '-NoProfile') | Should -BeFalse + Test-PraOwnEntryProcess -Arguments @($pwsh, '-NoExit', '-Command', 'Get-Date') | Should -BeFalse + Test-PraOwnEntryProcess -Arguments @($pwsh, '-Command', 'Get-Date', '-NoExit') | Should -BeFalse + Test-PraOwnEntryProcess -Arguments @() | Should -BeFalse + } + It 'the engine gives its exit code to the host only through that decision' { + $engine = [IO.File]::ReadAllText((Join-Path $global:PraGate.Source 'Invoke-PraRemoteMailbox.ps1')) + $engine | Should -Match 'if \(\$interrupted -and \(Test-PraOwnEntryProcess\)\) \{ try \{ \$Host\.SetShouldExit' + ([regex]::Matches($engine, 'SetShouldExit')).Count | Should -Be 1 + } + It 'finds a Recover that stopped before its proof by its backup, and tells the objects from its journal; a journal that is missing counts for every object; a Recover with no write counts for none' { + $root = Join-Path $global:PraGate.Root ('recover-stopped-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) + $hash = 'ef' * 32 + $make = { + param($Id, [bool]$Journal, [string[]]$Started) + $folder = Join-Path $root ('Batch-' + $Id); $null = New-Item -ItemType Directory -Path $folder -Force + $head = [ordered]@{ SchemaVersion = 3; RawFormat = 'PraDataOnlyClixml-v1'; Operation = 'Recover'; RunId = 'r'; BatchId = $Id; Environment = 'SYNTHETIC_GATE'; Server = 's'; NamingContext = 'n'; CreatedUtc = 'u'; RawFile = 'x.clixml'; RawHash = 'h'; SourceBackupHash = $hash; Records = @(@{ ObjectGuid = '11111111-1111-1111-1111-111111111111' }) } + [IO.File]::WriteAllText((Join-Path $folder ('Recover-SYNTHETIC_GATE-20261116_120000-' + $Id.Substring(0, 8) + '.json')), ($head | ConvertTo-Json -Depth 5), (New-Object Text.UTF8Encoding($true))) + if ($Journal) { + $lines = @(foreach ($guid in $Started) { (@{ RunId = 'r'; Utc = 'u'; Target = $guid; Operation = 'Set-ADUser'; Status = 'Started'; Detail = '' } | ConvertTo-Json -Compress) }) + [IO.File]::WriteAllText((Join-Path $folder ('Journal-' + $Id + '.jsonl')), (($lines + '{"RunId":"r","Utc":"u","Target":"*","Operation":"Backup","Status":"Verified","Detail":""}') -join "`r`n"), (New-Object Text.UTF8Encoding($true))) + } + } + $global:PraGate.StoppedRecover = @{ Root = $root; Hash = $hash } + $find = { + param($Objects) + $global:PraGate.StoppedObjects = $Objects + InModuleScope PRA.Directory { + $context = @{ Config = @{ Environment = 'SYNTHETIC_GATE'; Storage = @{ BackupFolder = $global:PraGate.StoppedRecover.Root } } } + Find-PraRecoverOfBatch $context $global:PraGate.StoppedRecover.Hash ([string[]]$global:PraGate.StoppedObjects) + } + } + & $make 'a1a1a1a1b2b2b2b2c3c3c3c3d4d4d4d4' $true @('11111111-1111-1111-1111-111111111111') + $hit = & $find @('11111111-1111-1111-1111-111111111111') + $hit.Basis | Should -BeExactly 'Journal' + $hit.ShortId | Should -BeExactly 'a1a1a1a1' + (& $find @('22222222-2222-2222-2222-222222222222')) | Should -BeNullOrEmpty -Because 'its journal never names that object' + Remove-Item -LiteralPath $root -Recurse -Force + & $make 'a1a1a1a1b2b2b2b2c3c3c3c3d4d4d4d4' $false @() + (& $find @('22222222-2222-2222-2222-222222222222')).Basis | Should -BeExactly 'Unknown' + Remove-Item -LiteralPath $root -Recurse -Force + & $make 'a1a1a1a1b2b2b2b2c3c3c3c3d4d4d4d4' $true @() + (& $find @('11111111-1111-1111-1111-111111111111')) | Should -BeNullOrEmpty -Because 'the Recover wrote nothing' + $global:PraGate.Remove('StoppedRecover'); $global:PraGate.Remove('StoppedObjects') + } +} From 9d7d8e41449c81b4f56fb60bc65a1a9de1efddb6 Mon Sep 17 00:00:00 2001 From: Nicolas Fabert <195452170+Nico77600@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:48:37 +0100 Subject: [PATCH 02/16] Cloud identity confirmed by source anchor, bounded retries with Retry-After and run back-off; console continue and partial recover follow-ups --- package/Invoke-PraRemoteMailbox.ps1 | 73 +- package/PraRemoteMailbox.psd1 | 2 +- package/config/PraRemoteMailbox.config.psd1 | 3 + package/docs/PraRemoteMailbox-Guide.md | 35 +- package/docs/PraRemoteMailbox-UserGuide.md | 2 + package/module/PRA.Cloud.psm1 | 353 ++++++- package/module/PRA.Common.psm1 | 56 +- package/module/PRA.Directory.psm1 | 69 +- package/module/PRA.Gui.psm1 | 22 +- tests/PraRemoteMailbox.Gui.Tests.ps1 | 51 + tests/PraRemoteMailbox.Tests.ps1 | 992 +++++++++++++++++++- 11 files changed, 1610 insertions(+), 48 deletions(-) diff --git a/package/Invoke-PraRemoteMailbox.ps1 b/package/Invoke-PraRemoteMailbox.ps1 index b3c1681..2852ad9 100644 --- a/package/Invoke-PraRemoteMailbox.ps1 +++ b/package/Invoke-PraRemoteMailbox.ps1 @@ -818,16 +818,18 @@ function Assert-PraBatchNotRolledBack { function Get-PraBatchTouchedSet { <# The objects that the journal of the Convert batch in $context.Source shows as written or about to be written. #> $journal = Join-Path (Split-Path $context.Source.Path -Parent) ('Journal-' + [string]$context.Source.Data.BatchId + '.jsonl') - return (Get-PraJournalTouchedObject -Path $journal) + return , (Get-PraJournalTouchedObject -Path $journal) } function Get-PraPartialSourceProof { - <# The AD proof of the Convert batch in $context.Source when it is marked partial (checked in full), else $null. A batch without a readable proof is not partial for this purpose. #> + <# The AD proof of the Convert batch in $context.Source when it is marked partial (checked in full), else $null. A batch without a State file is not partial for this purpose. + A State file that cannot be read, or that fails its checks (missing or wrong .sha256, damaged content), gives Unusable = $true with the Reason: the caller falls back to the journal. #> $path = Join-Path (Split-Path $context.Source.Path -Parent) ('State-' + [string]$context.Source.Data.BatchId + '.json') if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { return $null } - try { $raw = [IO.File]::ReadAllText($path) | ConvertFrom-PraJson } catch { return $null } + try { $raw = [IO.File]::ReadAllText($path) | ConvertFrom-PraJson } catch { return [pscustomobject]@{ Unusable = $true; Reason = 'the State file cannot be read' } } if ((Get-PraValue $raw 'Partial' $false) -ne $true) { return $null } - return (Import-PraProof $context $path $context.Source 'Convert') + try { return (Import-PraProof $context $path $context.Source 'Convert') } + catch { return [pscustomobject]@{ Unusable = $true; Reason = (([string]$_.Exception.Message -split '\r?\n')[0]).Trim() } } } function Set-PraUnprovenRow { @@ -867,6 +869,15 @@ function New-PraPartialContinuation { NotConverted = [string[]]@($left | ForEach-Object { [string]$_.SamAccountName }); NotConvertedIdentifiers = [string[]]$ids.ToArray(); MayBeChanged = [string[]]@($maybe | ForEach-Object { [string]$_.SamAccountName }) } } +function ConvertTo-PraIdentityKey { + <# The key an identity is matched by: a GUID in any form (braces, no dashes, any case) is its 32 lower-case digits, any other text is itself (the comparison ignores the case). #> + param([AllowNull()][string]$Value) + $text = ([string]$Value).Trim() + $guid = [guid]::Empty + if ($text -and [guid]::TryParse($text, [ref]$guid)) { return $guid.ToString('N') } + return $text +} + function Write-PraRemainingCsv { <# .SYNOPSIS @@ -891,8 +902,20 @@ function Write-PraRemainingCsv { $delimiter = if ($header -match '(?i)(^|,)\s*"?Identity"?\s*(,|$)') { ',' } else { ';' } $rows = @(ConvertFrom-Csv -InputObject $text -Delimiter $delimiter -ErrorAction Stop) $wanted = New-Object 'Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase) - foreach ($id in @($Partial.NotConvertedIdentifiers)) { [void]$wanted.Add($id) } - $keep = @($rows | Where-Object { $wanted.Contains(([string](Get-PraValue $_ 'Identity' '')).Trim()) }) + foreach ($id in @($Partial.NotConvertedIdentifiers)) { [void]$wanted.Add((ConvertTo-PraIdentityKey $id)) } + $converted = New-Object 'Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase) + foreach ($row in @($context.Rows | Where-Object { -not $script:NotConverted.Contains([string]$_.ObjectGuid) })) { + foreach ($value in @([string]$row.SamAccountName, [string]$row.UserPrincipalName, [string]$row.ObjectGuid, [string](Get-PraValue $row.BackupRec 'DistinguishedName' ''))) { if ($value) { [void]$converted.Add((ConvertTo-PraIdentityKey $value)) } } + } + $keep = New-Object 'Collections.Generic.List[object]'; $unknown = New-Object 'Collections.Generic.List[string]'; $leftOut = 0 + foreach ($row in $rows) { + $key = ConvertTo-PraIdentityKey ([string](Get-PraValue $row 'Identity' '')) + if ($wanted.Contains($key)) { $keep.Add($row) } + elseif ($converted.Contains($key)) { $leftOut++ } + else { $keep.Add($row); $unknown.Add([string](Get-PraValue $row 'Identity' '')) } + } + if ($unknown.Count) { Write-PraItem -Context $context -Status Warn -Text ('{0} line(s) of the file {1} name no object of batch {2} ({3}): they are kept in the new file, check them.' -f $unknown.Count, $source, $Partial.ShortId, (($unknown | Select-Object -First 5) -join ', ')) } + if ($leftOut) { Write-PraItem -Context $context -Status Info -Text ('{0} line(s) of the file {1} name objects that batch {2} converted or stopped on: they are left out of the new file.' -f $leftOut, $source, $Partial.ShortId) } if (-not $keep.Count) { return '' } $columns = @($rows[0].PSObject.Properties.Name) } @@ -1138,6 +1161,12 @@ try { Write-PraItem -Context $context -Status Ok -Icon Batch -Text ('Transfer package {0} verified (checksums, Environment, names): {1} folder(s) extracted, {2} already present and identical' -f $imported.Name, $imported.Created.Count, $imported.Existing.Count) if ((-not (Test-PraOrdinalIgnoreCaseEqual $effectiveMode 'Apply'))) { Write-PraItem -Context $context -Status Info -Text 'Preview: the package was verified and read from a private temporary folder, deleted at the end. Nothing was written to the backup folder.' } $script:ImportedFolders = @($imported.Created) + if ((Test-PraOrdinalIgnoreCaseEqual $effectiveMode 'Apply')) { + # The console tells an imported batch from one converted here by this file (outside the batch folder, which travels with the package). + $markerFolder = Join-Path $importRoot 'Imported' + Initialize-PraPrivateFolder -Path $markerFolder + [IO.File]::WriteAllText((Join-Path $markerFolder (([string]$imported.BatchId).ToLowerInvariant() + '.txt')), ('{0} {1}' -f $imported.Name, [DateTime]::UtcNow.ToString('o')), (New-Object Text.UTF8Encoding($false))) + } $Batch = [string]$imported.BatchId if ($PSBoundParameters.ContainsKey('Batch')) { $PSBoundParameters['Batch'] = $Batch } } @@ -1314,7 +1343,23 @@ try { if ($null -ne $sourceProof) { $script:Touched = Get-PraBatchTouchedSet $proven = New-Object 'Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase) - foreach ($entry in @($sourceProof.Data.Records)) { [void]$proven.Add([string]$entry.ObjectGuid) } + if ([bool](Get-PraValue $sourceProof 'Unusable' $false)) { + # The proof cannot be trusted: the journal says which objects the batch may have changed, and those are rolled back. A named object (-Identity) is rolled back on its own. + $backupFolder = Split-Path $context.Source.Path -Parent + $short = Get-PraShortId ([string]$context.Source.Data.BatchId) + Write-PraItem -Context $context -Status Warn -Text ('The AD proof of batch {0} is marked partial but cannot be used ({1}): the journal of the batch decides which objects are rolled back.' -f $short, $sourceProof.Reason) + if (-not $Identity -and -not $script:Touched.Count) { + $first = $records | Select-Object -First 1 + $context.NextSteps = @(('The backup of batch {0} is {1}: it holds the original values of every object of the batch.' -f $short, $context.Source.Path), + 'If you know that an object was converted by this batch, roll it back on its own (run the Preview, then the same command with -Mode Apply):', + ((Get-PraCommandLine -ActionName 'Recover' -ModeName 'Preview' -BatchId $short) + ' -Identity ' + (ConvertTo-PraLiteral ([string](Get-PraValue $first 'SamAccountName' 'user')))), + 'Otherwise restore the attributes of the objects from that backup file by hand (the backups are the only way back), or copy the original State file and its .sha256 file back into the batch folder and run the same Recover again.') + $context.NextOnFailure = $true; $context.NoChangeMade = $true; $context.CurrentIdentity = '' + throw ('Recover of batch {0} cannot go on: its AD proof is partial but unusable ({1}) and its journal lists no object that was written. Nothing was changed.' -f $short, $sourceProof.Reason) + } + if ($Identity) { foreach ($record in $records) { [void]$script:Touched.Add([string]$record.ObjectGuid) } } + } + else { foreach ($entry in @($sourceProof.Data.Records)) { [void]$proven.Add([string]$entry.ObjectGuid) } } $taken = New-Object 'Collections.Generic.List[object]'; $left = New-Object 'Collections.Generic.List[object]' foreach ($record in $records) { if ($proven.Contains([string]$record.ObjectGuid) -or $script:Touched.Contains([string]$record.ObjectGuid)) { $taken.Add($record) } else { $left.Add($record) } } foreach ($record in $left) { @@ -1393,6 +1438,7 @@ try { Initialize-PraDirectory $context $user = Get-PraUser $context $Identity $record = [pscustomobject]@{ ObjectGuid = ([guid]$user.ObjectGUID).ToString(); SamAccountName = $user.SamAccountName; UserPrincipalName = $user.UserPrincipalName; IsShared = ((Test-PraOrdinalIn $user.msExchRecipientTypeDetails @(4, 34359738368) -IgnoreCase)) + SourceAnchor = [pscustomobject]@{ ObjectGuid = [string](ConvertTo-PraImmutableId -Value $user.ObjectGUID); ConsistencyGuid = [string](ConvertTo-PraImmutableId -Value (Get-PraValue $user 'mS-DS-ConsistencyGuid' $null)) } ExpectedX500 = [string[]]@(Get-PraExpectedX500 -LegacyExchangeDN ([string](Get-PraValue $user 'legacyExchangeDN' '')) -ProxyAddresses @($user.proxyAddresses)) } } $context.Rows.Add((New-PraRow $context $record)) @@ -1521,7 +1567,10 @@ try { } elseif ($context.Issues.Count -or $cloudErrors.Count) { $isCheck = (Test-PraOrdinalIgnoreCaseEqual $Action 'Check') - $network = [bool](Get-PraValue $context 'NetworkFailure' $false) + $throttled = [bool](Get-PraValue $context 'CloudThrottled' $false) + $network = [bool](Get-PraValue $context 'NetworkFailure' $false) -or $throttled + $unanswered = if ($throttled) { 'Microsoft 365 limited the requests of this run' } else { 'Microsoft 365 did not answer from this machine' } + $whenAgain = if ($throttled) { 'in a few minutes' } else { 'when the connection works' } # The stop names the first object whose check failed. if (-not [int](Get-PraValue $context 'CloudNotReached' 0) -and -not (Test-PraOrdinalIn ([string]$context.CurrentOperation) @('Connect-MgGraph', 'Connect-ExchangeOnline'))) { $failedIssues = @($context.Issues.ToArray() | Where-Object { Test-PraOrdinalEqual ([string](Get-PraValue $_ 'Source' '')) 'Cloud' }) @@ -1530,12 +1579,12 @@ try { $context.CurrentIdentity = [string](Get-PraValue $failedIssues[0] 'Identity' '') } } - $lead = if ($network) { 'Microsoft 365 did not answer' } elseif ($isCheck) { 'The Exchange Online check could not be done' } else { 'Exchange Online check failed' } + $lead = if ($throttled) { 'Microsoft 365 limited the requests of this run' } elseif ($network) { 'Microsoft 365 did not answer' } elseif ($isCheck) { 'The Exchange Online check could not be done' } else { 'Exchange Online check failed' } if (-not $context.AllowMutation) { $again = if ($isCheck) { 'Check' } else { 'Preview' } $stop = '{0}. Nothing was changed. Run the {1} again.' -f $lead, $again $rerun = Get-PraCommandLine -ActionName $Action -PhaseName $(if ($isCheck) { '' } else { $effectivePhase }) -ModeName 'Preview' -BatchId $(if ($script:PreviewPackage) { $script:PreviewPackage } else { $Batch }) -KeepFilters - $first = if ($network) { 'Microsoft 365 did not answer from this machine. Nothing was changed: run the {0} again when the connection works:' -f $again } else { 'Nothing was changed. Fix the problem named above, then run the {0} again:' -f $again } + $first = if ($network) { '{0}. Nothing was changed: run the {1} again {2}:' -f $unanswered, $again, $whenAgain } else { 'Nothing was changed. Fix the problem named above, then run the {0} again:' -f $again } $context.NextSteps = @($first, $rerun) $context.NextOnFailure = $true throw $stop @@ -1544,7 +1593,7 @@ try { # The command is given as the operator typed it: the package path or the batch ID. $typedBatch = if ($script:PackageArgument) { $script:PackageArgument } elseif ($Batch) { $Batch } else { $context.BatchId } if ($network -and (Test-PraOrdinalIgnoreCaseEqual $effectivePhase 'Cloud')) { - $context.NextSteps = @('Microsoft 365 did not answer from this machine. What this run already did is kept: run the same command again when the connection works:', (Get-PraCommandLine -ActionName $Action -PhaseName 'Cloud' -BatchId $typedBatch -KeepFilters)) + $context.NextSteps = @(('{0}. What this run already did is kept: run the same command again {1}:' -f $unanswered, $whenAgain), (Get-PraCommandLine -ActionName $Action -PhaseName 'Cloud' -BatchId $typedBatch -KeepFilters)) $context.NextOnFailure = $true } elseif ((Test-PraOrdinalIgnoreCaseEqual $effectivePhase 'Cloud')) { @@ -1563,7 +1612,7 @@ try { elseif ((Test-PraOrdinalIgnoreCaseEqual $effectivePhase 'Both') -and $context.BatchId -and $null -ne $context.Proof) { # The Active Directory part of the batch is written and verified (Convert or Recover): only the Exchange Online part is left, and the batch is continued by its ID. $bothContinues = $true - $bothFirst = if ($network) { 'Microsoft 365 did not answer from this machine. What this run already did is kept (Active Directory is changed and verified): run the Exchange Online part when the connection works:' } else { 'What this run already did is kept (Active Directory is changed and verified). Fix the problem named above, then run the Exchange Online part:' } + $bothFirst = if ($network) { '{0}. What this run already did is kept (Active Directory is changed and verified): run the Exchange Online part {1}:' -f $unanswered, $whenAgain } else { 'What this run already did is kept (Active Directory is changed and verified). Fix the problem named above, then run the Exchange Online part:' } $context.NextSteps = @($bothFirst, (Get-PraCommandLine -ActionName $Action -PhaseName 'Cloud' -BatchId $context.BatchId)) $context.NextOnFailure = $true } diff --git a/package/PraRemoteMailbox.psd1 b/package/PraRemoteMailbox.psd1 index c858cfc..950874c 100644 --- a/package/PraRemoteMailbox.psd1 +++ b/package/PraRemoteMailbox.psd1 @@ -33,7 +33,7 @@ # Configuration, paths and CSV (PRA.Common) 'Import-PraConfiguration', 'Test-PraScopeConfiguration', 'New-PraEffectiveConfiguration', 'Get-PraConfigurationDifference', 'Resolve-PraPath', 'Read-PraCsvText', 'Read-PraTargetCsv', 'Get-PraTargetOverride', 'Get-PraToolVersion', 'Get-PraCloudModuleReport', 'Get-PraValue', 'Get-PraList', # Ordinal helpers, JSON and native calls (PRA.Common) - 'Test-PraOrdinalEqual', 'Test-PraOrdinalIgnoreCaseEqual', 'Test-PraOrdinalIn', 'Test-PraOrdinalIgnoreCaseIn', 'Get-PraOrdinalSorted', 'Get-PraOrdinalUnique', 'Compare-PraX500Address', 'ConvertFrom-PraJson', 'Get-PraNativeProcessApi', 'Get-PraWin32ErrorText', 'Test-PraOwnEntryProcess', + 'Test-PraOrdinalEqual', 'Test-PraOrdinalIgnoreCaseEqual', 'Test-PraOrdinalIn', 'Test-PraOrdinalIgnoreCaseIn', 'Get-PraOrdinalSorted', 'Get-PraOrdinalUnique', 'ConvertTo-PraImmutableId', 'Get-PraSourceAnchor', 'Compare-PraX500Address', 'ConvertFrom-PraJson', 'Get-PraNativeProcessApi', 'Get-PraWin32ErrorText', 'Test-PraOwnEntryProcess', # Private folders, phase data and transfer package (PRA.Common) 'New-PraPrivateDirectorySecurity', 'Initialize-PraPrivateFolder', 'Register-PraObjectName', 'Register-PraObjectBackup', 'Save-PraPhaseData', 'Copy-PraPhaseData', 'Get-PraTransferPackageName', 'Get-PraTransferPackage', 'New-PraTransferPackage', 'Import-PraTransferPackage', # Active Directory, backup and proof (PRA.Directory) diff --git a/package/config/PraRemoteMailbox.config.psd1 b/package/config/PraRemoteMailbox.config.psd1 index 9d3a2bf..93646c0 100644 --- a/package/config/PraRemoteMailbox.config.psd1 +++ b/package/config/PraRemoteMailbox.config.psd1 @@ -147,6 +147,9 @@ CheckLicense = $true # wait for a licence with Exchange enabled (users) MailboxCheckVia = 'Exo' # Exo (mailbox type in Exchange Online) or Graph (provisioning) RequiredSkuPartNumber = '' # '' = any licence with Exchange; e.g. 'SPE_E3' + IdentityCheck = 'Anchor' # Anchor = the Entra ID account must carry the AD source anchor (objectGUID or ms-DS-ConsistencyGuid); Off = accounts are found by UPN only + RetryBudgetObjectSeconds = 180 # most seconds one object waits in retries of throttled or unreachable cloud calls (0 = no retry) + RetryBudgetRunMinutes = 30 # most minutes the whole run waits in retries; used up, the run stops cleanly (0 = no retry) } # Exchange Online module. diff --git a/package/docs/PraRemoteMailbox-Guide.md b/package/docs/PraRemoteMailbox-Guide.md index 0cd164a..1f30696 100644 --- a/package/docs/PraRemoteMailbox-Guide.md +++ b/package/docs/PraRemoteMailbox-Guide.md @@ -110,7 +110,7 @@ cloud | Exchange Online | mailbox, licence, permissions | **Backup** | One private folder `Backups\Batch-`: the typed values to restore (JSON), every AD value (CLIXML), their SHA-256, then everything is **re-read and compared** with the plan. | | **AD changes** | Per object: current state re-checked, `Set-ADUser`, AD re-read, licence group, AD re-read. The **first error stops the batch**. | | **Entra Connect** | One Delta cycle, local or on `EntraConnect.Server`; the tool waits for its end. Before the first AD write the tool proves that the synchronisation is possible **for the account that runs it** (an authenticated, read-only call to `Get-ADSyncScheduler`): otherwise the run stops with nothing written. A cycle that fails after the verified AD writes does not fail the run: [Pending, exit code 2](#exit-codes). | -| **Exchange Online** | The tool waits (up to `Polling.TimeoutMinutes`) for the mailboxes and the licences, then grants FullAccess / SendAs / SendOnBehalf on the shared mailboxes and checks each grant. | +| **Exchange Online** | The tool first confirms, for each object, that the Microsoft Entra ID account with its UPN is the account synchronised from this AD object ([chapter 3](#3-things-to-know)). It then waits (up to `Polling.TimeoutMinutes`) for the mailboxes and the licences, then grants FullAccess / SendAs / SendOnBehalf on the shared mailboxes and checks each grant. | | **X500 control** | For each mailbox that is ready, the tool proves that it carries the X500 addresses recorded by the AD phase (next section). A missing one is a warning; the conversion stays done. | ### What changes in AD @@ -225,6 +225,16 @@ check | Done | on-premises again > [!NOTE] > **Nothing is automatic after an error.** The first error stops the batch: no next object, no sync, no cloud write, and no automatic rollback. The journal of the batch (`Journal-.jsonl`) says exactly which write was started, applied and verified. **The objects converted and verified before the error keep their AD proof:** the State file is written for them and marked *partial* (it says how many objects were planned). The objects that were not reached are *Pending*, never *skipped*. The Next steps give the exact commands: continue the converted objects (`-Phase AD -Batch `, then `-Phase Cloud -Batch ` for the Exchange Online part), convert the others (fix the cause, then run a new Convert for those objects only: a converted object is refused by the same command, "already converted by batch ...", so with `-CsvPath` list only the others), or roll the whole batch back (`-Action Recover -Batch `, Preview first). **Once the AD changes are made, a Convert is not run again** for the converted objects (see [Exit codes](#exit-codes)). A run that is stopped from outside (Ctrl+C, a closed console, a stop of the host) ends the same way: `RESULT: FAIL`, exit code 1, the stop named in the summary and the command that goes on, never `PASS`. The exit code is given to the process only when the run is the entry of its own PowerShell process (`pwsh -File`, `-Command`, the console's child process): a command typed in an interactive window never closes that window. When every object of a batch was verified and the run stopped before the end, the AD proof written is the normal one (not partial). An Entra Connect sync that cannot run after the verified AD writes is not an error of the run (Pending, exit code 2, the transfer package is written). +> [!NOTE] +> **The cloud account is confirmed, never found by UPN alone.** A UPN can belong to another account in the cloud (a cloud-only account with the same UPN, or an account synchronised from another object when Entra ID gave the synchronised object another UPN). Before the tool reads or changes anything in the cloud for an object, it reads the Microsoft Entra ID account with that UPN and compares its `onPremisesImmutableId` with the **source anchor** that the AD phase recorded in the batch (`SourceAnchor`): the base64 text of the `objectGUID` and, when the object has one, of `ms-DS-ConsistencyGuid`. The account is the right one when it carries either text (they are compared exactly: they are machine identifiers, letter case counts). In phase `Both` this is part of the pre-check, before any AD write. +> +> A **different account**, a **cloud-only** account, **two accounts**, or an account synchronised under **another UPN** is an **error for that object**: nothing is read in Exchange Online for it and nothing is changed on it. The message says which case it is and what to do (give one of the two accounts another UPN, or remove the duplicate, then run the same command again). The Exchange Online object found by UPN must then carry the `ExternalDirectoryObjectId` of the confirmed account, in every read (recipient, mailbox, permissions, retention check); another object stops the call. For a shared mailbox the same check is made for **each trustee** of a permission to grant (the batch records their anchors, `SharedTrusteeAnchors`; a trustee without recorded anchors must at least be a synchronised account, not a cloud-only one), so that a permission is never granted to another person. An object that is not in Microsoft Entra ID yet is waited for like any object that is not ready. +> +> **Older batches and the records without an anchor.** A batch, backup or transfer package written before 3.2.0 has no `SourceAnchor`: the anchor is derived from the `ObjectGuid` of the record (the usual source anchor), and an error then says that the record is old. A tenant whose source anchor is neither the `objectGUID` nor `ms-DS-ConsistencyGuid` (or whose `ms-DS-ConsistencyGuid` differs from the `objectGUID` in a batch of an older version) can set `Cloud.IdentityCheck = 'Off'` after checking the accounts by hand: accounts are then found by UPN only, and the run says so once. A `Check -Identity ` has no AD record at all: the account is found by UPN with a warning, and no permission is ever granted for such a record. The retention check reads an **inactive** mailbox (its account is deleted) by UPN only. + +> [!NOTE] +> **Throttling and temporary failures do not end an object.** A read of Microsoft Graph or Exchange Online that fails with HTTP 408, 429, 502, 503, 504, a timeout or no answer at all is sent again (at most five tries, after the `Retry-After` of the answer, or 5, 10, 20, 40 seconds), within `Cloud.RetryBudgetObjectSeconds` for one object and `Cloud.RetryBudgetRunMinutes` for the whole run; every retry is in the log (Detail level). A throttled answer (429, 503) also **slows every following call of the run** (a pause that doubles up to 30 seconds and halves after each success), so that a batch of thousands of objects does not turn into thousands of refused calls. An object whose own budget is used up stays pending and is read again at the next check of the wait; only at the end of the wait is it an error ("Microsoft 365 could not be read"). When the budget of the **run** is used up, the cloud part stops with **one** error (not one per object), the objects not finished stay *Pending*, and the Next steps give the command to run again a few minutes later. Any other failure (a 4xx other than 408 and 429, a refusal, a bad answer) is **not** sent again. A grant is never sent again: the next run finds the permission already granted or grants it. + > [!TIP] > **Two servers are supported.** If no single server reaches both Active Directory and Microsoft 365 (for example an AD server on an isolated network), run the AD part with `-Phase AD` on the AD server, copy the **transfer package** it writes (the `.zip` **and** its `.sha256` file, both in `Backups\Outbox\`, [chapter 10](#10-files-batches-proofs-and-packages)), and run `-Phase Cloud -Batch ` on the **cloud server**. That is not a server hosted in the cloud: it is any Windows machine of the organisation that reaches Microsoft 365 through the Internet (server room or administrator workstation), with no access to AD. The summary of each step prints the command of the next one. @@ -324,16 +334,16 @@ dsacls 'DC=contoso,DC=com' /G "${who}:CA;Replication synchronization" | **Delegated scopes requested by the code** | `User.Read.All` (the only scope: `Connect-MgGraph -Scopes 'User.Read.All'`, `PRA.Cloud.psm1:595`) | none (no scope is requested) | | **Application permissions** | none | `User.Read.All` (Microsoft Graph, type *Application*) | | **Admin consent** | **Yes, once**: an administrator accepts `User.Read.All` for the organisation the first time (the sign-in window shows *Permissions requested*) | **Yes**: *Grant admin consent* on the application registration | -| **What it reads** | `Get-MgUser -UserId -Property Id,UserPrincipalName` (pre-check, `:771`); `Get-MgUser -Property assignedPlans, provisionedPlans, assignedLicenses` (`:873`); `Get-MgUserLicenseDetail -UserId -All` (`:894`) | the same three calls | +| **What it reads** | `Get-MgUser -UserId -Property id,userPrincipalName,onPremisesImmutableId,onPremisesSyncEnabled` (the account of each object and of each trustee, once per run; and `Get-MgUser -Filter "onPremisesImmutableId eq ''"` only when the UPN does not give the right account); `Get-MgUser -UserId -Property Id,UserPrincipalName` (pre-check); `Get-MgUser -Property assignedPlans, provisionedPlans, assignedLicenses`; `Get-MgUserLicenseDetail -UserId -All` | the same calls | | **Sign-in** | the admin who signs in needs a role that can read other users' licences: see *What the code cannot tell you* | `Connect-MgGraph -ClientId -CertificateThumbprint -TenantId ` (`:595`) | -The tool never writes anything through Microsoft Graph. Graph reads **user** mailboxes only (a shared mailbox has no licence and is checked through Exchange Online), and only when `Cloud.CheckLicense` is `$true` (the default) or `Cloud.MailboxCheckVia = 'Graph'` (`PRA.Cloud.psm1:941-947`). +The tool never writes anything through Microsoft Graph. It reads the account of every object, and of every trustee of a permission to grant, to confirm it ([chapter 3](#3-things-to-know)): that needs no other permission than `User.Read.All`, and it is skipped only with `Cloud.IdentityCheck = 'Off'`. The licence and the provisioning are read for **user** mailboxes only (a shared mailbox has no licence and is checked through Exchange Online), and only when `Cloud.CheckLicense` is `$true` (the default) or `Cloud.MailboxCheckVia = 'Graph'`. Every Graph read is sent again after a temporary failure, within the retry budgets of the configuration. #### Exchange Online | What the tool does | Cmdlet | Code | |---|---|---| -| Finds a recipient or a mailbox, its type, its holds | `Get-EXORecipient`, `Get-EXOMailbox` (also `-InactiveMailboxOnly`) | `PRA.Cloud.psm1:157`, `:186-187`, `:292` | +| Finds a recipient or a mailbox, its type, its holds; the object found by UPN must carry the `ExternalDirectoryObjectId` of the Entra ID account confirmed for the object | `Get-EXORecipient`, `Get-EXOMailbox` (also `-InactiveMailboxOnly`) | `PRA.Cloud.psm1:157`, `:186-187`, `:292` | | Reads the FullAccess and SendAs holders of a shared mailbox | `Get-EXOMailboxPermission`, `Get-EXORecipientPermission` | `:252-253`, `:262-263` | | Reads the SendOnBehalf holders | `Get-Mailbox -Filter` (property `GrantSendOnBehalfTo`) | `:283` | | **Grants** FullAccess (Convert, shared mailboxes only) | `Add-MailboxPermission -AccessRights FullAccess` | `:359` | @@ -472,6 +482,8 @@ converge is a **warning that names it**; the synchronisation still runs, and the | `Cloud.TenantId`, `Cloud.Organization` | Tenant GUID and initial domain (`tenant.onmicrosoft.com`). Every session is checked against them. **When `Cloud.AppId` is set, both are required** (the tenant must be a GUID): the configuration is refused at load otherwise. | | `Cloud.AppId` + `Cloud.CertificateThumbprint` | Certificate sign-in (unattended, [annex C](#annex-c--certificate-sign-in-application)). Both empty = interactive sign-in (`Cloud.UserPrincipalName` = expected account). | | `Cloud.CheckMailbox`, `CheckLicense`, `MailboxCheckVia`, `RequiredSkuPartNumber` | What "ready" means for a user: mailbox (Exchange Online type, or Graph provisioning) and licence. `MailboxCheckVia` is `Exo` by default (mailbox type in Exchange Online) or `Graph` (provisioning). | +| `Cloud.IdentityCheck` | `Anchor` (default): the Entra ID account of every object, and of every trustee of a permission to grant, must carry the Active Directory source anchor (`onPremisesImmutableId` = base64 of the `objectGUID` or of `ms-DS-ConsistencyGuid`): another account, a cloud-only account or an ambiguous answer is an error for the object and nothing is changed on it ([chapter 3](#3-things-to-know)). `Off`: accounts are found by UPN only, with one notice per run; for a tenant whose source anchor is another attribute. Any letter case. | +| `Cloud.RetryBudgetObjectSeconds`, `Cloud.RetryBudgetRunMinutes` | How long a read of Microsoft Graph or Exchange Online that fails with 408, 429, 502, 503, 504, a timeout or no answer may wait in retries: at most `RetryBudgetObjectSeconds` seconds for one object (default 180, 0 to 3600) and `RetryBudgetRunMinutes` minutes for the whole run (default 30, 0 to 720). `0` = no retry. A run that used up its budget stops with one error and the command to run again; an object that used up its own stays pending until the wait ends. | | `Exo.MinModuleVersion` | Oldest `ExchangeOnlineManagement` accepted (default `3.10.1`, which is also the lowest value used: a lower setting is raised to it). With an older module the tool stops before any change and gives the `Install-Module` command; `Exo.UseSubprocess` is the only way to the child process. The Microsoft Graph minimum (`2.41.1`, one same version for `Authentication` and `Users`) is fixed in the tool. | | `Exo.DisableWAM` | `$false` (default): interactive sign-in through the Windows broker (WAM). `$true`: browser sign-in instead. See [chapter 8](#8-everyday-use), *Cloud sign-in from the window*. | | `Exo.GrantVerifyAttempts`, `GrantVerifyDelaySeconds` | After **one** grant, re-read up to N times (never granted twice). | @@ -1126,6 +1138,17 @@ After a change of the engine, repeat the campaign of [annex B](#annex-b--lab-tes | `Stopped at step ...: the run was interrupted before it finished (Ctrl+C, a closed window or a stop of the host)` (`RESULT: FAIL`, exit code 1) | the run was stopped from outside | read the Next steps: they continue the batch (or say how to undo it); what the run did is kept | | `: shared mailbox permission(s) not granted by the settings ... - to grant by hand: FullAccess ; ...` (warning, *done with warnings*) | the batch carries permissions that the settings in force do not grant: a batch written before 3.2.0 on a server whose configuration grants less, or a batch converted with settings that grant none | grant the listed permissions by hand (`Add-MailboxPermission`, `Add-RecipientPermission`, `Set-Mailbox -GrantSendOnBehalfTo`), or correct the settings and run the cloud phase again. Nothing else is wrong | | `The shared mailbox permission settings of this server differ from the ones of the batch (...)` (warning) | the cloud server has another `SharedMailbox` configuration than the server that converted | nothing to do: the batch values are used, and the warning names them | +| `: the Microsoft Entra ID account with this UPN is not the account synchronised from this Active Directory object (it is a cloud-only account / it is synchronised from another Active Directory object)` | the UPN of the AD object belongs to another account in the cloud: Entra ID gave the synchronised object another UPN, or a cloud-only account had the UPN first | nothing was changed on it, and nothing was read in Exchange Online. Give one of the two accounts another UPN so that Entra Connect synchronises the object under its own UPN, or leave the object out, then run the same command again. A record written by an older version says so: if the tenant uses another source anchor, check the account by hand and set `Cloud.IdentityCheck = 'Off'` | +| `: the account synchronised from this Active Directory object is in Microsoft Entra ID, not ` | the account of the object has another UPN in the cloud | make the UPN in AD and in Entra ID the same, let Entra Connect synchronise, run the same command again | +| `: Microsoft Entra ID returned 2 accounts for this UPN` / `... has 2 accounts that carry the source anchor of this Active Directory object` | duplicate accounts in Entra ID | remove the duplicate account, run the same command again | +| `Permissions on are not granted. : the Microsoft Entra ID account ...` | a trustee of a permission is a cloud-only account or another account than the AD user | nothing was granted for this mailbox. Fix the UPN of the trustee account as for an object, then run the same command again | +| `The Exchange Online recipient / mailbox is not the Microsoft Entra ID account confirmed for this object: ` | Exchange Online returned another object than the account that was confirmed (the `ExternalDirectoryObjectId` differs) | nothing was changed. Wait for Exchange Online to settle and run the same command again; if it stays, ask for the object in Exchange Online | +| `: the Microsoft Entra ID account is found by its UPN only: this object has no Active Directory identity in the record` (warning) | `-Action Check -Identity ` has no AD read | give the sAMAccountName, or `-Batch`, to have the account confirmed | +| `Microsoft 365 is limiting or not answering this run: the N minute(s) allowed for retries are used up ...` | the retries of the run used up `Cloud.RetryBudgetRunMinutes` (heavy throttling, or Microsoft 365 not answering) | what the run did is kept; the objects not finished stay *Pending*. Run the same command again in a few minutes (Next steps), or raise the budget | +| `: Microsoft 365 kept limiting the requests or was unavailable (HTTP 429) and the retry time of this object is used up` | an object used up `Cloud.RetryBudgetObjectSeconds` until the end of the wait | run the same command again in a few minutes | +| `The AD proof of batch is marked partial but cannot be used (...): the journal of the batch decides which objects are rolled back` (warning) | the State file of a partial Convert batch has no `.sha256`, was changed, or is damaged | Recover rolls back the objects that the journal shows as written (a Started or Applied line), and leaves the others alone. Put the original State file and its `.sha256` back to use the proof again | +| `Recover of batch cannot go on: its AD proof is partial but unusable (...) and its journal lists no object that was written` | the same, and the journal of the batch is missing or empty | nothing was changed. The Next steps give the backup file, the Recover of one named object (`-Identity`), and the manual restore: the attributes of the objects are restored by hand from that backup file | +| ` line(s) of the file name no object of batch (...): they are kept in the new file, check them` (warning) | the CSV of the objects left keeps every line that it cannot match to an object of the batch (for example an identity written as `DOMAIN\account`); a GUID matches in any form (braces, no dashes, any case) | check those lines; the lines of converted objects are left out and counted in an information line | | `An Exchange Online session already exists in this console` | the console was used for EXO before | open a new PowerShell 7 window | | `Microsoft Graph: found Microsoft.Graph.Authentication 2.40.0; Microsoft.Graph.Users 2.35.1. The tool needs both in one same version 2.41.1 or later` | the Graph modules installed are too old, or not in one same version (two versions of Graph in one session fail with *Assembly with same name is already loaded*) | run the commands of the message, one per module and both for the same version (`Install-Module Microsoft.Graph.Authentication -MinimumVersion 2.41.1 -Scope CurrentUser`, then `Install-Module Microsoft.Graph.Users -MinimumVersion 2.41.1 -Scope CurrentUser`; `-Scope AllUsers` needs a window opened as administrator). `Install-Module` refuses `-MinimumVersion` with several names. Nothing was changed. The tool imports both modules in that same version. The same text is on the Microsoft.Graph light of the Setup page | | `ExchangeOnlineManagement: found 3.9.0; the tool needs 3.10.1 or later` | the module is too old | `Install-Module ExchangeOnlineManagement -MinimumVersion 3.10.1 -Scope CurrentUser` (`-Scope AllUsers` in a window opened as administrator). Nothing was changed | @@ -1282,6 +1305,10 @@ $app # -> Cloud.AppId 3.1.0 adds one optional field to each record of a Convert backup, `ExpectedX500` (the X500 addresses to verify in Exchange Online); a backup without it is read as before. +3.2.0 adds two optional fields to each record of a Convert backup: `SourceAnchor` (`ObjectGuid` and `ConsistencyGuid`: the base64 `onPremisesImmutableId` texts of the object, `ConsistencyGuid` empty when the object has no `ms-DS-ConsistencyGuid`) and `SharedTrusteeAnchors` (for a shared mailbox, the anchors of each trustee by UPN, `ms-DS-ConsistencyGuid` first). A backup, batch or transfer package without them is read as before: the anchor is then derived from the `ObjectGuid` of the record (trustees: no anchor, a synchronised account is required). + +An Apply that imports a transfer package also writes a small text file `Backups\Imported\.txt` (the package name and the time), outside the batch folder. The console reads it to tell a batch imported on this server from one converted here: only the second is offered "finish it here" (AD part first), and only on a server that can run the AD part. + Every JSON has a `.sha256` file; a mismatch is refused. **Version 2.0.0 reads the batches of 1.3.x** (tested: Recover of a 1.3.6 Convert batch in the lab). **The formats did not change in 3.0.0** (backup schema 3, `PraDataOnlyClixml-v1`, proof schema 2, Finalize manifest schema 2). The codec writes the same bytes under PowerShell 7 and under Windows PowerShell 5.1 (by design; `tests\PraLegacyFixtures.Tests.ps1` replays, in the gate, backups, proofs and a Finalize package written by the real 2.2.0 under Windows PowerShell 5.1 and frozen in `tests\fixtures\ps51-2.2.0`), and every hash is a hash of the file bytes, so a backup, a proof or a Finalize package produced by 2.x is read, verified and restored by 3.0.0 without conversion. The JSON written by PowerShell 7 is formatted differently (2-space indentation, no Unicode escapes for the characters `<`, `>`, `&` and the apostrophe) but is the same JSON; 2.2.x reads it. One cosmetic difference in new files: the order of the multi-value lists is an ordinal sort (upper-case before lower-case, by UTF-16 code unit), where 2.x wrote the culture-aware order of Windows PowerShell 5.1; the comparisons sort both sides again, so no check depends on it. The CSV report keeps its UTF-8 BOM, as in 2.x. diff --git a/package/docs/PraRemoteMailbox-UserGuide.md b/package/docs/PraRemoteMailbox-UserGuide.md index f317ab2..204a982 100644 --- a/package/docs/PraRemoteMailbox-UserGuide.md +++ b/package/docs/PraRemoteMailbox-UserGuide.md @@ -655,6 +655,8 @@ Find what you **see** in the left column. The middle column says what it **means | *Microsoft Graph: found … The tool needs both in one same version 2.41.1 or later* | The Microsoft 365 programs on this server are too old, or not in the same version. **Nothing was changed.** | Ask your administrator to run the command written in the message. Press **Check again**. | | *Nothing was changed in AD. This account cannot write to …* | The directory server refused your account. | Run the tool on that directory server, or with an account that has the rights. The **Next steps** give the command: run the **Preview** first, then the same command with `-Mode Apply`. The backup folder that was written is kept: it is not a batch to continue. | | *… Microsoft 365 did not answer (network)* | The connection to Microsoft 365 did not work for a moment. **Nothing was changed** by a Preview or a Check. | Press the button again, or run the command of the **Next steps** again when the connection works. If it comes back, ask your administrator to check the network. | +| *Microsoft 365 is limiting or not answering this run …* or *… kept limiting the requests …* | Microsoft 365 slowed the tool down, or did not answer, for too long. The tool already tried again many times. **Nothing was changed** on the people it did not reach. What it did is kept. | Wait a few minutes. Run the command of the **Next steps** again. If it comes back every time, ask your administrator to raise the retry time in the settings file. | +| *… is not the account synchronised from this Active Directory object* (or *… returned 2 accounts …*) | In the cloud, the e-mail address of this person belongs to **another** account. It can be an account made by hand, or a duplicate. The tool stopped for this person. It never works on the wrong account. **Nothing was changed on it.** | Ask your administrator to give one of the two accounts another address, or to remove the duplicate. Then run the same command again. | | *The domain controller … does not answer from this machine* | This server cannot reach the directory server. **Nothing was changed.** | Run the check on a server that reaches the directory server, or give the e-mail address of the mailbox instead of the account name. | | *A Microsoft Graph session already exists in this console* | A cloud session is already open in the same window. | Close all PowerShell windows. Open a new one. Start again. | | **The red button stays grey** on **Verify** | The preview is not done, or the word is not typed. | Press **Preview**. Type the word **CONVERT**, **RECOVER** or **FINALIZE**. Spaces and capitals do not matter. | diff --git a/package/module/PRA.Cloud.psm1 b/package/module/PRA.Cloud.psm1 index 027f625..5434779 100644 --- a/package/module/PRA.Cloud.psm1 +++ b/package/module/PRA.Cloud.psm1 @@ -28,6 +28,15 @@ bounded re-reads (Exo.GrantVerifyAttempts x Exo.GrantVerifyDelaySeconds) and a line "Verified". A grant is never retried. + Identity: unless Cloud.IdentityCheck = Off, the Microsoft Entra ID account of every object (and of every trustee of a permission to grant) must carry the Active + Directory source anchor of the object (onPremisesImmutableId = base64 of the objectGUID or of ms-DS-ConsistencyGuid). Another account, a cloud-only account or an + ambiguous answer is an error for that object and nothing is changed on it. The Exchange Online object found by UPN must carry the ExternalDirectoryObjectId of + that account. + + Retries: a read of Microsoft Graph or Exchange Online is sent again on 408, 429, 502, 503, 504, a timeout or no answer (Retry-After honoured), within + Cloud.RetryBudgetObjectSeconds for an object and Cloud.RetryBudgetRunMinutes for the run; a throttled answer slows the calls of the whole run, and a run that used + up its budget stops with one error. Any other failure is not sent again. + Sessions: Microsoft Graph is connected before Exchange Online; an Exchange Online or Graph session that already exists in the console is refused; tenant, token, connection ID and module path are checked before each call. Exo.UseSubprocess (or @@ -187,6 +196,8 @@ $script:PraExoWorker = { if (-not [guid]::TryParse($oid,[ref]$parsed) -or $parsed -eq [guid]::Empty -or [string]::IsNullOrWhiteSpace($smtp)) { throw "Recipient identity incomplete: $Upn" } $expected=V (V $P 'ExpectedIdentities' @{}) $Upn if ($null -ne $expected -and (-not (SameIgnoreCase $oid (V $expected 'ObjectId')) -or -not (SameIgnoreCase $smtp (V $expected 'PrimarySmtpAddress')))) { throw "Recipient identity changed since the pre-check: $Upn" } + $confirmed=V (V $P 'VerifiedObjectIds' @{}) $Upn + if ($null -ne $confirmed -and $confirmed -and -not (SameIgnoreCase $oid $confirmed)) { throw "The Exchange Online recipient is not the Microsoft Entra ID account confirmed for this object: $Upn" } $keys = @($Upn) + @(foreach ($key in @('UserPrincipalName','PrimarySmtpAddress','ExternalDirectoryObjectId','Guid','DistinguishedName','Identity','Alias','Name','DisplayName','Sid','SamAccountName')) { $val = [string](V $items[0] $key); if (-not [string]::IsNullOrWhiteSpace($val)) { $val } }) @@ -195,7 +206,7 @@ $script:PraExoWorker = { } function Mailbox { param([string]$Upn,[switch]$Hold) - $grantParameters = @{ Filter=(ExactFilter $Upn); Properties=@('RecipientTypeDetails','EmailAddresses','LegacyExchangeDN'); ResultSize='Unlimited' } + $grantParameters = @{ Filter=(ExactFilter $Upn); Properties=@('RecipientTypeDetails','EmailAddresses','LegacyExchangeDN','ExternalDirectoryObjectId'); ResultSize='Unlimited' } if ($Hold) { $grantParameters.Properties += @('IsInactiveMailbox','InPlaceHolds','LitigationHoldEnabled','RetentionHoldEnabled') } $items = @(Get-EXOMailbox @grantParameters -ErrorAction Stop) if ($Hold -and $items.Count -eq 0) { $items = @(Get-EXOMailbox @grantParameters -InactiveMailboxOnly -ErrorAction Stop) } @@ -203,6 +214,8 @@ $script:PraExoWorker = { if ($items.Count -eq 0) { return @{ Found=$false; Type=$null; Holds=@(); IsInactive=$false; Litigation=$false; RetentionHold=$false; HasAddresses=$false; Addresses=[string[]]@() } } $m = $items[0]; $type = [string](V $m 'RecipientTypeDetails') if (-not $type) { throw "Mailbox type not returned: $Upn" } + $mailboxOid=[string](V $m 'ExternalDirectoryObjectId' ''); $confirmed=V (V $P 'VerifiedObjectIds' @{}) $Upn + if ($mailboxOid -and $null -ne $confirmed -and $confirmed -and -not (SameIgnoreCase $mailboxOid $confirmed)) { throw "The Exchange Online mailbox is not the Microsoft Entra ID account confirmed for this object: $Upn" } $holds = V -Object $m -Name 'InPlaceHolds' -Default @() # EmailAddresses (every proxy address of the mailbox, X500 included): whether Exchange Online returned the property at all is kept apart from "empty". $hasAddresses = if ($m -is [System.Collections.IDictionary]) { $m.Contains('EmailAddresses') } else { $null -ne $m.PSObject.Properties['EmailAddresses'] } @@ -305,6 +318,8 @@ $script:PraExoWorker = { } $mb = @(Get-Mailbox -Filter (ExactFilter $Upn) -ResultSize Unlimited -ErrorAction Stop) if ($mb.Count -ne 1) { throw "Mailbox not unique for the SendOnBehalf read: $Upn" } + $behalfOid=[string](V $mb[0] 'ExternalDirectoryObjectId' '') + if ($behalfOid -and -not (SameIgnoreCase $behalfOid $Target.ObjectId)) { throw "The mailbox of the SendOnBehalf read is not the confirmed Exchange Online recipient: $Upn" } $delegates=V -Object $mb[0] -Name 'GrantSendOnBehalfTo' -Default @() foreach ($delegate in $delegates) { if ($null -eq $delegate) { continue } @@ -409,7 +424,9 @@ function Get-PraCloudSession { $Context['_PraCloudSession'] = @{ GraphAttempted=$false; ExoAttempted=$false; Graph=$false; Exo=$false; Subprocess=$false Binding=$null; OwnedExoIds=@(); GraphContext=$null; Identities=@{}; Preflight=$false } } - return $Context['_PraCloudSession'] + $session = $Context['_PraCloudSession'] + foreach ($name in @('Verified', 'IdentityCache')) { if (-not $session.ContainsKey($name)) { $session[$name] = @{} } } + return $session } function Get-PraNetworkFailure { @@ -462,10 +479,265 @@ function Write-PraCloudFailure { Write-PraCloudError -Context $Context -Row $Row -Message $plain -Technical $raw -RunError return } + $info=Get-PraCloudFailureInfo $ErrorRecord + if ($info.Throttled) { + $plain='{0}Microsoft 365 kept limiting the requests or was unavailable (HTTP {1}) and the retry time of this object is used up. Run again in a few minutes.' -f $(if ($Upn) { $Upn + ': ' } else { '' }), $info.Status + Write-PraCloudError -Context $Context -Row $Row -Message $plain -Technical $raw -RunError + return + } $message=$(if ($Extra) { $raw + ' | ' + $Extra } else { $raw }) if ($Expectation) { Write-PraCloudError -Context $Context -Row $Row -Message $message } else { Write-PraCloudError -Context $Context -Row $Row -Message $message -RunError } } +function Get-PraCloudFailureInfo { + <# What a failed cloud call says about itself: Status (the HTTP status, 0 when there is none), RetryAfter (seconds, 0 when none, never more than two minutes), Transient (the same read can be sent again: 408, 429, 502, 503, 504, a timeout or a connection that did not answer), Throttled (429 or 503) and NotFound (404). Looks at the inner exceptions, then at the text (the Exchange Online child process only returns text). #> + [CmdletBinding()] + param([Parameter(Mandatory)]$ErrorRecord) + $status = 0; $retryAfter = 0 + $texts = New-Object 'System.Collections.Generic.List[string]' + $queue = New-Object 'System.Collections.Generic.Queue[object]'; $queue.Enqueue($ErrorRecord.Exception) + $detail = [string](Get-PraValue (Get-PraValue $ErrorRecord 'ErrorDetails' $null) 'Message' '') + if ($detail) { $texts.Add($detail) } + $visited = 0 + while ($queue.Count -gt 0 -and $visited -lt 20) { + $visited++ + $e = $queue.Dequeue(); if ($null -eq $e) { continue } + $texts.Add([string]$e.Message) + $response = Get-PraValue $e 'Response' $null + foreach ($holder in @($e, $response)) { + if ($null -eq $holder -or $status -ne 0) { continue } + $code = Get-PraValue $holder 'StatusCode' $null + if ($null -ne $code) { try { $status = [int]$code } catch { $status = 0 } } + } + $headers = Get-PraValue $response 'Headers' $null + if ($null -ne $headers -and $retryAfter -eq 0) { + $parsed = 0 + $retry = Get-PraValue $headers 'RetryAfter' $null + if ($null -ne $retry) { + $delta = Get-PraValue $retry 'Delta' $null; $when = Get-PraValue $retry 'Date' $null + if ($null -ne $delta) { try { $retryAfter = [int][Math]::Ceiling(([TimeSpan]$delta).TotalSeconds) } catch { $retryAfter = 0 } } + elseif ($null -ne $when) { try { $retryAfter = [int][Math]::Ceiling(([DateTimeOffset]$when - [DateTimeOffset]::UtcNow).TotalSeconds) } catch { $retryAfter = 0 } } + } + elseif ([int]::TryParse([string](Get-PraValue $headers 'Retry-After' ''), [ref]$parsed)) { $retryAfter = $parsed } + } + if ($e -is [AggregateException]) { foreach ($inner in $e.InnerExceptions) { $queue.Enqueue($inner) } } + elseif ($null -ne $e.InnerException) { $queue.Enqueue($e.InnerException) } + } + $all = $texts -join ' ' + if ($status -eq 0) { + foreach ($match in [regex]::Matches($all, '(?i)(?:HttpStatusCode|status ?code|status)\D{0,40}?(\d{3})(?!\d)')) { + $candidate = [int]$match.Groups[1].Value + if ($candidate -ge 400 -and $candidate -le 599) { $status = $candidate; break } + } + } + if ($status -eq 0) { + if ($all -match '(?i)TooManyRequests|Too Many Requests|throttl') { $status = 429 } + elseif ($all -match '(?i)ServiceUnavailable|Service Unavailable') { $status = 503 } + elseif ($all -match '(?i)GatewayTimeout|Gateway Timeout') { $status = 504 } + elseif ($all -match '(?i)BadGateway|Bad Gateway') { $status = 502 } + elseif ($all -match '(?i)RequestTimeout|Request Timeout') { $status = 408 } + elseif ($all -match '(?i)Request_ResourceNotFound') { $status = 404 } + } + if ($retryAfter -le 0 -and $all -match '(?i)retry[- ]after\D{0,20}(\d{1,5})') { $retryAfter = [int]$Matches[1] } + $retryAfter = [Math]::Min([Math]::Max($retryAfter, 0), 120) + $transient = $false + if ($status -ne 0) { $transient = (Test-PraOrdinalIn $status @(408, 429, 502, 503, 504)) } + else { $transient = ($null -ne (Get-PraNetworkFailure $ErrorRecord)) -or ($all -match '(?i)\btimeout\b|timed out|task was canceled|operation was canceled') } + return [pscustomobject]@{ Status = $status; RetryAfter = $retryAfter; Transient = [bool]$transient; Throttled = (Test-PraOrdinalIn $status @(429, 503)); NotFound = ($status -eq 404) } +} + +function Get-PraRetryState { + <# The retry budgets of this run (Cloud.RetryBudgetObjectSeconds per object, Cloud.RetryBudgetRunMinutes for the run) and what has been spent. Created on first use. #> + [CmdletBinding()] + param([hashtable]$Context) + if (-not $Context.ContainsKey('_PraRetry')) { + $cloud = Get-PraValue $Context.Config 'Cloud' @{} + $Context['_PraRetry'] = @{ ObjectBudget = [int](Get-PraValue $cloud 'RetryBudgetObjectSeconds' 180); RunBudget = ([int](Get-PraValue $cloud 'RetryBudgetRunMinutes' 30) * 60) + RunSpent = 0; Objects = @{}; Retries = 0; Throttled = 0; Pace = 0; RunExhausted = $false } + } + return $Context['_PraRetry'] +} + +function Stop-PraCloudRun { + <# The retry time of the run is used up: ONE plain error ends the cloud part (nothing is asked of Microsoft 365 any more), never one failure per object. #> + [CmdletBinding()] + param([hashtable]$Context, [Exception]$Inner = $null) + $state = Get-PraRetryState $Context + $state.RunExhausted = $true; $Context.CloudThrottled = $true + $minutes = [Math]::Round($state.RunBudget / 60.0, 1) + $message = 'Microsoft 365 is limiting or not answering this run: the {0} minute(s) allowed for retries are used up ({1} retries, {2} throttled answers). Nothing more is asked of Microsoft 365. What this run already did is kept: run the same command again in a few minutes.' -f $minutes, $state.Retries, $state.Throttled + $failure = [System.InvalidOperationException]::new($message, $Inner) + $failure.Data['PraRunBudget'] = $true + throw $failure +} + +function Invoke-PraCloudCall { + <# + .SYNOPSIS + One read of Microsoft Graph or Exchange Online that can be sent again. A transient failure (408, 429, 502, 503, 504, a timeout, no answer) is retried after the + Retry-After of the answer, or 5, 10, 20, 40 seconds, at most five tries, within the budget of the object and the budget of the run; each retry is in the log (Detail). + A throttled answer also slows the next calls of the whole run (a pause that doubles up to 30 seconds and halves after each success). Any other failure (a 4xx + other than 408 and 429, a refusal, a bad answer) is thrown as it is at once. -NoRetry: one try (a write is never sent again). + #> + [CmdletBinding()] + param([Parameter(Mandatory)][hashtable]$Context, [Parameter(Mandatory)][string]$Call, [Parameter(Mandatory)][scriptblock]$Script, [object[]]$ArgumentList = @(), [switch]$NoRetry) + $state = Get-PraRetryState $Context + $key = [string](Get-PraValue $Context 'CurrentIdentity' '') + if ($NoRetry -or $state.ObjectBudget -le 0 -or $state.RunBudget -le 0) { return (& $Script @ArgumentList) } + if ($state.RunExhausted) { Stop-PraCloudRun -Context $Context } + if ($state.Pace -gt 0) { + if (($state.RunSpent + $state.Pace) -gt $state.RunBudget) { Stop-PraCloudRun -Context $Context } + $null = Write-PraLog -Context $Context -Message ('Cloud calls slowed down after throttling: pausing {0} s before {1}' -f $state.Pace, $Call) -Level Detail + Start-Sleep -Seconds $state.Pace + $state.RunSpent += $state.Pace + } + for ($try = 1; $true; $try++) { + try { + $answer = & $Script @ArgumentList + if ($state.Pace -gt 0) { $state.Pace = [int][Math]::Floor($state.Pace / 2) } + return $answer + } + catch { + $failure = $_ + $info = Get-PraCloudFailureInfo $failure + if (-not $info.Transient) { throw } + if ($info.Throttled) { $state.Throttled++; $state.Pace = [int][Math]::Min(30, [Math]::Max(2, $state.Pace * 2)) } + $spent = if ($state.Objects.ContainsKey($key)) { [int]$state.Objects[$key] } else { 0 } + $wait = if ($info.RetryAfter -gt 0) { [int]$info.RetryAfter } else { [int][Math]::Min(60, 5 * [Math]::Pow(2, $try - 1)) } + $runOut = (($state.RunSpent + $wait) -gt $state.RunBudget) + if ($try -ge 5 -or ($spent + $wait) -gt $state.ObjectBudget -or $runOut) { + $null = Write-PraLog -Context $Context -Message ('Retry budget used up | {0} | {1} | status {2} | {3} tries | object {4} of {5} s, run {6} of {7} s' -f $Call, $key, $info.Status, $try, $spent, $state.ObjectBudget, $state.RunSpent, $state.RunBudget) -Level Detail + if ($runOut) { Stop-PraCloudRun -Context $Context -Inner $failure.Exception } + throw $failure + } + $null = Write-PraLog -Context $Context -Message ('Retry {0} | {1} | {2} | status {3}{4} | waiting {5} s | object {6} of {7} s, run {8} of {9} s' -f $try, $Call, $key, $(if ($info.Status) { $info.Status } else { 'no answer' }), $(if ($info.RetryAfter -gt 0) { ' (Retry-After ' + $info.RetryAfter + ' s)' } else { '' }), $wait, ($spent + $wait), $state.ObjectBudget, ($state.RunSpent + $wait), $state.RunBudget) -Level Detail + Start-Sleep -Seconds $wait + $state.Objects[$key] = $spent + $wait; $state.RunSpent += $wait; $state.Retries++ + } + } +} + +function Test-PraIdentityCheck { + <# Cloud.IdentityCheck: Anchor (the default, also when the setting is missing) confirms every cloud account against the Active Directory source anchor; Off finds accounts by UPN only. #> + [CmdletBinding()] + param([hashtable]$Context) + return (-not (Test-PraOrdinalIgnoreCaseEqual ([string](Get-PraValue (Get-PraValue $Context.Config 'Cloud' @{}) 'IdentityCheck' 'Anchor')) 'Off')) +} + +function Get-PraEntraAccount { + <# The Entra ID accounts found by UPN (-Upn) or by source anchor (-Anchor), read only. An account that does not exist is an empty answer, never an error. #> + [CmdletBinding()] + param([hashtable]$Context, [string]$Upn, [string]$Anchor) + Assert-PraGraphSession $Context + $select = @('id', 'userPrincipalName', 'onPremisesImmutableId', 'onPremisesSyncEnabled') + if ($Anchor) { + $filter = "onPremisesImmutableId eq '{0}'" -f $Anchor.Replace("'", "''") + $byAnchor = { param($Filter, $Property) Get-MgUser -Filter $Filter -Property $Property -ErrorAction Stop } + return @(Invoke-PraCloudCall -Context $Context -Call 'Microsoft Graph user by source anchor' -Script $byAnchor -ArgumentList @($filter, $select)) + } + $byUpn = { param($UserId, $Property) Get-MgUser -UserId $UserId -Property $Property -ErrorAction Stop } + try { return @(Invoke-PraCloudCall -Context $Context -Call 'Microsoft Graph user' -Script $byUpn -ArgumentList @($Upn, $select)) } + catch { if ((Get-PraCloudFailureInfo $_).NotFound) { return @() }; throw } +} + +function Resolve-PraCloudIdentity { + <# + .SYNOPSIS + Confirms that the Entra ID account found by UPN is the account synchronised from the Active Directory object (read only). + .DESCRIPTION + Status Match the account carries one of the source anchors (onPremisesImmutableId, compared exactly). + Status Mismatch the account with this UPN carries another anchor, is not synchronised (cloud only), or the synchronised account has another UPN. + Status Ambiguous Microsoft Entra ID returns several accounts. + Status NotFound no account by UPN and none by anchor (not synchronised yet). + Status NoAnchor the record has no usable anchor: the account is only found by UPN (-SyncedOnly: a cloud-only account is still a Mismatch). + -Recorded $false: the anchors were derived from the objectGUID of a record written by an older version. + #> + [CmdletBinding()] + param([hashtable]$Context, [Parameter(Mandatory)][string]$Upn, [AllowNull()][string[]]$Anchors, [bool]$Recorded = $true, [switch]$SyncedOnly) + $anchorList = @($Anchors | Where-Object { $_ }) + $result = { param($Status, $ObjectId, $Message, $Technical) [pscustomobject]@{ Status = $Status; ObjectId = $ObjectId; Message = $Message; Technical = $Technical } } + $older = if ($Recorded) { '' } else { ' The record was written by an older version and holds only the objectGUID: if your tenant uses ms-DS-ConsistencyGuid as source anchor with another value, check the account by hand and set Cloud.IdentityCheck = Off in the configuration file.' } + $accounts = @(Get-PraEntraAccount -Context $Context -Upn $Upn) + if ($accounts.Count -gt 1) { + return (& $result 'Ambiguous' '' ('{0}: Microsoft Entra ID returned {1} accounts for this UPN, so the right one cannot be chosen. Nothing was changed on it. Remove the duplicate account in Microsoft Entra ID, then run the same command again.' -f $Upn, $accounts.Count) ('accounts=' + (@($accounts | ForEach-Object { [string](Get-PraValue $_ 'Id' '') }) -join ','))) + } + if ($accounts.Count -eq 1) { + $id = [string](Get-PraValue $accounts[0] 'Id' ''); $found = [string](Get-PraValue $accounts[0] 'OnPremisesImmutableId' '') + if (-not $anchorList.Count) { + if ($SyncedOnly -and -not $found) { return (& $result 'Mismatch' $id ('{0}: the Microsoft Entra ID account with this UPN is a cloud-only account, not an account synchronised from Active Directory. Nothing was changed on it. Give one of the two accounts another UPN, then run the same command again.' -f $Upn) ('id=' + $id)) } + return (& $result 'NoAnchor' $id '' ('id=' + $id)) + } + if (Test-PraOrdinalIn $found $anchorList) { return (& $result 'Match' $id '' ('id=' + $id + '; onPremisesImmutableId=' + $found)) } + $why = if ($found) { 'it is synchronised from another Active Directory object' } else { 'it is a cloud-only account' } + return (& $result 'Mismatch' $id ('{0}: the Microsoft Entra ID account with this UPN is not the account synchronised from this Active Directory object ({1}). Nothing was changed on it. Give one of the two accounts another UPN so that Entra Connect can synchronise this object under its own UPN, or leave this object out, then run the same command again.{2}' -f $Upn, $why, $older) ('id=' + $id + '; onPremisesImmutableId=' + $found + '; expected=' + ($anchorList -join ' or '))) + } + if (-not $anchorList.Count) { return (& $result 'NotFound' '' '' '') } + $byAnchor = @{} + foreach ($anchor in $anchorList) { + foreach ($account in @(Get-PraEntraAccount -Context $Context -Anchor $anchor)) { + $accountId = [string](Get-PraValue $account 'Id' '') + if ($accountId -and -not $byAnchor.ContainsKey($accountId)) { $byAnchor[$accountId] = $account } + } + } + if ($byAnchor.Count -gt 1) { return (& $result 'Ambiguous' '' ('{0}: Microsoft Entra ID has {1} accounts that carry the source anchor of this Active Directory object, so the right one cannot be chosen. Nothing was changed on it. Remove the duplicate account in Microsoft Entra ID, then run the same command again.' -f $Upn, $byAnchor.Count) ('accounts=' + (@($byAnchor.Keys) -join ','))) } + if ($byAnchor.Count -eq 1) { + $other = @($byAnchor.Values)[0] + return (& $result 'Mismatch' ([string](Get-PraValue $other 'Id' '')) ('{0}: the account synchronised from this Active Directory object is {1} in Microsoft Entra ID, not {0}. Nothing was changed on it. Make the UPN in Active Directory and in Microsoft Entra ID the same (then let Entra Connect synchronise), then run the same command again.' -f $Upn, [string](Get-PraValue $other 'UserPrincipalName' '')) ('id=' + [string](Get-PraValue $other 'Id' ''))) + } + return (& $result 'NotFound' '' '' '') +} + +function Confirm-PraCloudIdentity { + <# The Entra ID account (and the account of each trustee) of one object is the one synchronised from Active Directory. Returns Ok, Wait (not in Microsoft Entra ID yet: read again at the next check) or Failed (an error is recorded; the object is never acted on). #> + [CmdletBinding()] + param([hashtable]$Context, $State, [switch]$Throw) + $row = $State.Row; $upn = [string]$State.Upn + $fail = { param($Message, $Technical) if ($Throw) { throw $Message }; Write-PraCloudError -Context $Context -Row $row -Message $Message -Technical $Technical -RunError; return 'Failed' } + if (-not (Test-PraIdentityCheck $Context)) { + if (-not [bool](Get-PraValue $Context 'IdentityCheckOffSaid' $false)) { + $Context.IdentityCheckOffSaid = $true + Write-PraItem -Context $Context -Status Info -Text 'Cloud.IdentityCheck = Off: the Microsoft Entra ID accounts are found by UPN only, they are not confirmed against Active Directory.' + } + return 'Ok' + } + $session = Get-PraCloudSession $Context + $source = Get-PraValue $row 'BackupRec' $null; if ($null -eq $source) { $source = $row } + $anchor = Get-PraSourceAnchor -Record $source + if ($session.IdentityCache.ContainsKey($upn)) { $verdict = $session.IdentityCache[$upn] } + else { + $verdict = Resolve-PraCloudIdentity -Context $Context -Upn $upn -Anchors $anchor.Candidates -Recorded $anchor.Recorded + if (Test-PraOrdinalIn $verdict.Status @('Match', 'Mismatch', 'Ambiguous')) { $session.IdentityCache[$upn] = $verdict } + } + if (Test-PraOrdinalIn $verdict.Status @('Mismatch', 'Ambiguous')) { return (& $fail $verdict.Message $verdict.Technical) } + if (Test-PraOrdinalEqual $verdict.Status 'NotFound') { + if ($Throw) { throw ('{0}: the account is not in Microsoft Entra ID (neither by UPN nor by source anchor). It must be synchronised from Active Directory before this run: run the Entra Connect sync, then run the command again.' -f $upn) } + $State.PlainText = 'the account is not in Microsoft Entra ID yet (the Entra Connect sync has not run)' + $row.CloudStatus = 'Pending' + return 'Wait' + } + if (Test-PraOrdinalEqual $verdict.Status 'NoAnchor') { + if ($Context.AllowMutation -is [bool] -and $Context.AllowMutation -and @($State.Requests).Count) { + return (& $fail ('{0}: the Active Directory identity of this object is not in the record, so the Microsoft Entra ID account cannot be confirmed and no permission is granted. Give the object by its sAMAccountName or run its batch, then run the command again.' -f $upn) '') + } + $note = '{0}: the Microsoft Entra ID account is found by its UPN only: this object has no Active Directory identity in the record (the identity was given as a UPN). Give its sAMAccountName or -Batch to have it confirmed.' -f $upn + Write-PraItem -Context $Context -Status Warn -Text $note + $row.Warnings = ([string](Get-PraValue $row 'Warnings' '') + '; ' + $note).Trim(' ', ';') + } + $session.Verified[$upn] = [string]$verdict.ObjectId + $trustees = @(@($State.Requests) | ForEach-Object { [string]$_.Trustee } | Get-PraOrdinalUnique -IgnoreCase) + foreach ($trustee in $trustees) { + $stored = Get-PraValue (Get-PraValue $source 'SharedTrusteeAnchors' $null) $trustee $null + if ($session.IdentityCache.ContainsKey($trustee)) { $answer = $session.IdentityCache[$trustee] } + else { + $answer = Resolve-PraCloudIdentity -Context $Context -Upn $trustee -Anchors ([string[]]@(if ($null -ne $stored) { @($stored) })) -Recorded ($null -ne $stored) -SyncedOnly + if (Test-PraOrdinalIn $answer.Status @('Match', 'Mismatch', 'Ambiguous')) { $session.IdentityCache[$trustee] = $answer } + } + if (Test-PraOrdinalIn $answer.Status @('Mismatch', 'Ambiguous')) { return (& $fail ('Permissions on {0} are not granted. {1}' -f $upn, $answer.Message) $answer.Technical) } + if (-not (Test-PraOrdinalEqual $answer.Status 'NotFound')) { $session.Verified[$trustee] = [string]$answer.ObjectId } + } + return 'Ok' +} + function Read-PraExoProgress { <# New complete lines of the progress file of the child process (from Offset); each valid line is passed to Relay (attempt, max, next). Returns the new offset. #> param([string]$Path,[long]$Offset,[scriptblock]$Relay) @@ -623,13 +895,24 @@ function Invoke-PraExo { -not (Test-PraOrdinalEqual $Context.Mode 'Apply') -or -not (Test-PraOrdinalEqual $Context.Action 'Convert') -or -not (Test-PraOrdinalIn $Context.Phase @('Cloud','Both')) -or $WhatIfPreference)) { throw 'Grant without an active write authorisation.' } $Params=$Params.Clone() $Params.ExpectedIdentities=Get-PraValue $session 'Identities' @{} + $verified=@{} + foreach ($name in @(@([string](Get-PraValue $Params 'Upn' '')) + @([string](Get-PraValue $Params 'Trustee' '')) + @(Get-PraList $Params 'Requests' | ForEach-Object { [string](Get-PraValue $_ 'Trustee' '') }))) { + if ($name -and $session.Verified.ContainsKey($name)) { $verified[$name]=[string]$session.Verified[$name] } + } + $Params.VerifiedObjectIds=$verified if ((Test-PraOrdinalIgnoreCaseEqual $Operation 'Grant')) { $exo=Get-PraValue $Context.Config 'Exo' @{} $Params.GrantVerifyAttempts=Get-PraValue $exo 'GrantVerifyAttempts' 13 $Params.GrantVerifyDelaySeconds=Get-PraValue $exo 'GrantVerifyDelaySeconds' 10 } - $results = @(if ($session.Subprocess) { Invoke-PraExoSubprocess -Context $Context -Operation $Operation -Params $Params -Permit $Permit -OnApplied $OnApplied -OnProgress $OnProgress } - else { & $script:PraExoWorker $Operation $Params $Permit (Get-PraValue $session 'Binding' $null) $OnApplied $OnProgress }) + $dispatch = { + param($Ctx, $Sess, $Op, $Prm, $Prt, $Applied, $Progress) + if ($Sess.Subprocess) { Invoke-PraExoSubprocess -Context $Ctx -Operation $Op -Params $Prm -Permit $Prt -OnApplied $Applied -OnProgress $Progress } + else { & $script:PraExoWorker $Op $Prm $Prt (Get-PraValue $Sess 'Binding' $null) $Applied $Progress } + } + $dispatchArguments = @($Context, $session, $Operation, $Params, $Permit, $OnApplied, $OnProgress) + $results = @(if (Test-PraOrdinalIgnoreCaseEqual $Operation 'Grant') { & $dispatch @dispatchArguments } + else { Invoke-PraCloudCall -Context $Context -Call ('Exchange Online ' + $Operation) -Script $dispatch -ArgumentList $dispatchArguments }) if ($results.Count -ne 1) { throw 'Exchange Online result not unique.' } $result=$results[0] $booleans=switch ($Operation) { 'Probe' { 'Connected' }; 'Permission' { 'TrusteeFound'; 'Verified' }; 'Grant' { 'TrusteeFound'; 'Verified'; 'Mutated' }; default { 'Found' } } @@ -815,6 +1098,7 @@ function Initialize-PraCloudPreflight { $mailboxCheck=($isRecover -or [bool](Get-PraValue $cloud 'CheckMailbox' $false)) if (-not $shared -and ([bool](Get-PraValue $cloud 'CheckLicense' $false) -or ($mailboxCheck -and (Test-PraOrdinalIgnoreCaseEqual $via 'Graph')))) { $needGraph=$true } } + if (Test-PraIdentityCheck $Context) { $needGraph=$true } # EXO resolves each target even while it is still a MailUser; no provisioning assertion here. Connect-PraCloudSession -Context $Context -NeedGraph $needGraph -NeedExo ($Rows.Count -gt 0) $session=Get-PraCloudSession $Context @@ -822,6 +1106,7 @@ function Initialize-PraCloudPreflight { $upn=[string](Get-PraValue $row 'UserPrincipalName' '') $Context.CurrentIdentity=$upn; $Context.CurrentOperation='ResolvePreflightIdentity' $requests=if ($isRecover) { @() } else { @(Get-PraPermissionRequest $Context $row) } + $null=Confirm-PraCloudIdentity -Context $Context -State @{ Row=$row; Upn=$upn; Requests=$requests; PlainText='' } -Throw $result=Invoke-PraExo -Context $Context -Operation Preflight -Params @{ Upn=$upn; Requests=$requests } $identities=Get-PraValue $result 'Identities' @{} $names=if ($identities -is [System.Collections.IDictionary]) { @($identities.Keys) } else { @($identities.PSObject.Properties.Name) } @@ -835,7 +1120,8 @@ function Initialize-PraCloudPreflight { } if ($needGraph -and -not [bool](Get-PraValue $row 'IsShared' $false)) { Assert-PraGraphSession $Context - $users=@(Get-MgUser -UserId $upn -Property Id,UserPrincipalName -ErrorAction Stop) + $readUser={ param($UserId,$Property) Get-MgUser -UserId $UserId -Property $Property -ErrorAction Stop } + $users=@(Invoke-PraCloudCall -Context $Context -Call 'Microsoft Graph user' -Script $readUser -ArgumentList @($upn,@('Id','UserPrincipalName'))) $target=Get-PraValue $identities $upn $null if ($users.Count -ne 1 -or -not (Test-PraOrdinalIgnoreCaseEqual ([string](Get-PraValue $users[0] 'Id' '')) ([string](Get-PraValue $target 'ObjectId' ''))) -or -not (Test-PraOrdinalIgnoreCaseEqual ([string](Get-PraValue $users[0] 'UserPrincipalName' '')) $upn)) { throw "Graph and Exchange Online identities differ at the pre-check: $upn" } @@ -937,7 +1223,8 @@ function Get-PraGraphFact { if (-not (Get-PraCloudSession $Context).Graph) { throw 'Microsoft Graph required but not connected.' } Assert-PraGraphSession $Context $props=@('assignedPlans'); if ($Mailbox) { $props+='provisionedPlans' }; if ($License) { $props+='assignedLicenses' }; if ($Addresses) { $props+='proxyAddresses' } - $users=@(Get-MgUser -UserId $Upn -Property $props -ErrorAction Stop) + $readUser={ param($UserId,$Property) Get-MgUser -UserId $UserId -Property $Property -ErrorAction Stop } + $users=@(Invoke-PraCloudCall -Context $Context -Call 'Microsoft Graph user' -Script $readUser -ArgumentList @($Upn,$props)) if ($users.Count -ne 1 -or $null -eq $users[0]) { throw "Microsoft Graph: user not found or not unique ($Upn)." } $values=@{}; $sentinel=New-Object object foreach ($prop in $props) { @@ -958,7 +1245,8 @@ function Get-PraGraphFact { if ($Mailbox) { $prov=@($values.provisionedPlans | Where-Object { (Test-PraOrdinalIgnoreCaseEqual (Get-PraValue $_ 'Service' '') 'exchange') -and (Test-PraOrdinalIgnoreCaseEqual (Get-PraValue $_ 'ProvisioningStatus' '') 'Success') }).Count -gt 0 } $required=[string](Get-PraValue (Get-PraValue $Context.Config 'Cloud' @{}) 'RequiredSkuPartNumber' '') if ($Mailbox -or ($License -and $required)) { - $details=@(Get-MgUserLicenseDetail -UserId $Upn -All -ErrorAction Stop) + $readDetails={ param($UserId) Get-MgUserLicenseDetail -UserId $UserId -All -ErrorAction Stop } + $details=@(Invoke-PraCloudCall -Context $Context -Call 'Microsoft Graph licence details' -Script $readDetails -ArgumentList @($Upn)) foreach ($d in $details) { $sku += [string](Get-PraValue $d 'SkuPartNumber' '') foreach ($p in @((Get-PraValue $d 'ServicePlans' @()) | Where-Object { ([string](Get-PraValue $_ 'ServicePlanName' '')).StartsWith('EXCHANGE_',[StringComparison]::OrdinalIgnoreCase) })) { @@ -1111,20 +1399,31 @@ function Invoke-PraCloudPhase { $needGraph=$needGraph -or $lic -or $graphMailbox; $needExo=$needExo -or $exoMailbox [void]$states.Add(@{ Row=$row; Upn=$upn; Shared=$shared; Mailbox=$mb; License=$lic; GraphMailbox=$graphMailbox ExoMailbox=$exoMailbox; Requests=$requests; PreserveMailbox=$preserveMailbox; PreserveLicense=$preserveLicense; Done=$false; PlainText='' - X500=$x500Expected; X500Reads=0; X500Failure=''; X500Last=$null; CoreDone=$false }) + X500=$x500Expected; X500Reads=0; X500Failure=''; X500Last=$null; CoreDone=$false; IdentityChecked=$false; LastFailure=$null }) } if ($states.Count -eq 0) { return } + if (Test-PraIdentityCheck $Context) { $needGraph=$true } try { Connect-PraCloudSession -Context $Context -NeedGraph $needGraph -NeedExo $needExo } catch { $Context.CloudConnectFailed=$true; throw } $clock=[Diagnostics.Stopwatch]::StartNew(); $timeout=[double]$Context.TimeoutMinutes*60; $attempt=0 $x500MaxReads=3 # first read + two re-reads at the polling interval: the cloud value can lag one synchronisation, never a long new wait + $stopRun=$null do { $attempt++; $pending=@($states | Where-Object { -not $_.Done }) $null=Write-PraLog -Context $Context -Message ("Check {0}: {1} object(s) in Exchange Online" -f $attempt, $pending.Count) -Level Info foreach ($s in $pending) { $row=$s.Row; $Context.CurrentIdentity=[string](Get-PraValue $row 'ObjectGuid' $s.Upn); $Context.CurrentOperation='CloudCheck' try { + $s.LastFailure=$null if ($s.CoreDone) { $null=Invoke-PraX500Step -Context $Context -State $s -Fresh $null -MaxReads $x500MaxReads -Final ([bool]$Context.Once); continue } + if (-not $s.IdentityChecked) { + $Context.CurrentOperation='ConfirmIdentity' + $outcome=Confirm-PraCloudIdentity -Context $Context -State $s + $Context.CurrentOperation='CloudCheck' + if (Test-PraOrdinalEqual $outcome 'Failed') { $s.Done=$true; continue } + if (Test-PraOrdinalEqual $outcome 'Wait') { continue } + $s.IdentityChecked=$true + } $details=New-Object 'System.Collections.Generic.List[string]'; $plain=New-Object 'System.Collections.Generic.List[string]'; $mbok=$true; $licok=$true; $facts=$null if ($s.GraphMailbox -or $s.License) { $facts=Get-PraGraphFact -Context $Context -Upn $s.Upn -Mailbox $s.GraphMailbox -License $s.License -Addresses ([bool]($null -ne $s.X500 -and $s.GraphMailbox)) } if ($s.ExoMailbox) { @@ -1194,8 +1493,19 @@ function Invoke-PraCloudPhase { $null=Invoke-PraX500Step -Context $Context -State $s -Fresh $fresh -MaxReads $x500MaxReads -Final ([bool]$Context.Once) } else { $s.Done=$true } } else { $row.CloudStatus='Pending' } - } catch { Write-PraCloudFailure -Context $Context -Row $row -ErrorRecord $_ -Upn $s.Upn -Extra ([string]$row.PermDetail); $s.Done=$true } + } catch { + $failure=$_ + $info=Get-PraCloudFailureInfo $failure + if ((Get-PraRetryState $Context).RunExhausted) { $stopRun=$failure; break } + if ($info.Transient -and -not $Context.Once -and $clock.Elapsed.TotalSeconds -lt $timeout) { + $s.LastFailure=$failure; $row.CloudStatus='Pending' + $s.PlainText='Microsoft 365 could not be read just now ({0}); the read is repeated at the next check' -f $(if ($info.Status) { 'HTTP ' + $info.Status } else { 'no answer' }) + $null=Write-PraLog -Context $Context -Message ("{0} | cloud read failed, repeated at the next check | {1}" -f $s.Upn, ([string]$failure.Exception.Message -replace '\s+',' ')) -Level Detail + } + else { Write-PraCloudFailure -Context $Context -Row $row -ErrorRecord $failure -Upn $s.Upn -Extra ([string]$row.PermDetail); $s.Done=$true } + } } + if ($null -ne $stopRun) { break } $pending=@($states | Where-Object { -not $_.Done }) if (-not $pending.Count -or $Context.Once -or $clock.Elapsed.TotalSeconds -ge $timeout) { break } $seconds=[Math]::Min([Math]::Max(1,([double]$Context.IntervalMinutes*60)),[Math]::Max(0,($timeout-$clock.Elapsed.TotalSeconds))) @@ -1213,7 +1523,17 @@ function Invoke-PraCloudPhase { if ($seconds -gt 0) { Start-Sleep -Milliseconds ([int][Math]::Min(2147483647,($seconds*1000))) } } while ($true) $preview=(-not $Context.AllowMutation -and (Test-PraOrdinalIn $Context.Action @('Convert','Recover'))) - foreach ($s in $states) { + if ($null -ne $stopRun) { + foreach ($s in @($states | Where-Object { -not $_.Done -and $_.CoreDone })) { Complete-PraX500Check -Context $Context -State $s } + $unfinished=@($states | Where-Object { -not $_.Done }) + foreach ($s in $unfinished) { + $s.Row.CloudStatus='Pending'; $s.Row.FinalStatus='Pending' + $s.Row.Detail=([string]$s.Row.Detail+' | not finished: the retry time of the run is used up').Trim(' ','|') + } + $Context.CurrentIdentity=''; $Context.CurrentOperation='CloudCheck' + Write-PraCloudError -Context $Context -Row $null -Message ('{0} {1} object(s) were not finished.' -f $stopRun.Exception.Message, $unfinished.Count) -Technical ([string]$stopRun.Exception.InnerException.Message) + } + else { foreach ($s in $states) { if ($s.Done) { continue } if ($s.CoreDone) { Complete-PraX500Check -Context $Context -State $s; continue } if ($preview) { @@ -1222,13 +1542,14 @@ function Invoke-PraCloudPhase { $null=Write-PraLog -Context $Context -Message ("{0}: not yet in the expected state: {1}" -f $s.Upn, $(if ($s.PlainText) { $s.PlainText } else { 'see the log' })) -Level Info $null=Write-PraLog -Context $Context -Message ("{0}: technical detail: {1}" -f $s.Upn, $s.Row.CloudDetail) -Level Detail } + elseif ($null -ne $s.LastFailure) { Write-PraCloudFailure -Context $Context -Row $s.Row -ErrorRecord $s.LastFailure -Upn $s.Upn -Extra ([string]$s.Row.PermDetail) } else { $because=$(if ($s.PlainText) { $s.PlainText } else { 'see the log' }) $message=$(if ($Context.Once) { '{0}: not in the expected state: {1}.' -f $s.Upn,$because } else { '{0}: still not in the expected state after waiting {1} min: {2}.' -f $s.Upn,$Context.TimeoutMinutes,$because }) $Context.CloudNotReached=[int]$Context.CloudNotReached+1 Write-PraCloudError -Context $Context -Row $s.Row -Message $message -Technical ('Expected state not reached (timeout or -Once): '+$s.Row.CloudDetail) } - } + } } } catch { $failure=$_ foreach ($row in $Rows) { Write-PraCloudFailure -Context $Context -Row $row -ErrorRecord $failure -Upn ([string](Get-PraValue $row 'UserPrincipalName' '')) } @@ -1255,7 +1576,7 @@ function Invoke-PraRetentionCheck { if (-not [guid]::TryParse($raw,[ref]$parsed) -or $parsed -eq [guid]::Empty) { throw 'Retention.PolicyGuid is not a GUID.' } $guid=$parsed.ToString('N') } - try { Connect-PraCloudSession -Context $Context -NeedGraph $false -NeedExo $true } + try { Connect-PraCloudSession -Context $Context -NeedGraph (Test-PraIdentityCheck $Context) -NeedExo $true } catch { $Context.CloudConnectFailed=$true; throw } $cloud=Get-PraValue $Context.Config 'Cloud' @{}; $name=[string](Get-PraValue $cfg 'PolicyName' '') if (-not $guid -and $name -and [bool](Get-PraValue $cfg 'UseComplianceSession' $false) -and -not [string](Get-PraValue $cloud 'AppId' '')) { @@ -1270,7 +1591,8 @@ function Invoke-PraRetentionCheck { $session.OwnedExoIds=@($session.OwnedExoIds)+$newIds } try { - $policies=@(Get-RetentionCompliancePolicy -Identity $name -ErrorAction Stop) + $readPolicy={ param($Identity) Get-RetentionCompliancePolicy -Identity $Identity -ErrorAction Stop } + $policies=@(Invoke-PraCloudCall -Context $Context -Call 'Get-RetentionCompliancePolicy' -Script $readPolicy -ArgumentList @($name)) if ($policies.Count -ne 1) { throw 'Retention policy not found or not unique.' } $raw=[string](Get-PraValue $policies[0] 'Guid' '') if (-not $raw) { $raw=[string](Get-PraValue $policies[0] 'ExchangeObjectId' '') } @@ -1285,7 +1607,10 @@ function Invoke-PraRetentionCheck { $Context.CurrentOperation='VerifyRetention'; $Context.CurrentIdentity=[string](Get-PraValue $row 'ObjectGuid' '') $row.CloudMailbox=$null; $row.CloudLicense=$null; $row.CloudStatus='Pending' try { - $h=Invoke-PraExo -Context $Context -Operation 'Hold' -Params @{ Upn=[string](Get-PraValue $row 'UserPrincipalName' '') } + $holdUpn=[string](Get-PraValue $row 'UserPrincipalName' '') + # An inactive mailbox has no account in Microsoft Entra ID any more: it is found by UPN only. An account that exists must be the synchronised one. + if ((Test-PraIdentityCheck $Context) -and (Test-PraOrdinalEqual (Confirm-PraCloudIdentity -Context $Context -State @{ Row=$row; Upn=$holdUpn; Requests=@(); PlainText='' }) 'Failed')) { continue } + $h=Invoke-PraExo -Context $Context -Operation 'Hold' -Params @{ Upn=$holdUpn } $row.CloudMailbox=[bool](Get-PraValue $h 'Found' $false) $holds=Get-PraValue $h 'Holds' @(); $holds=@($holds | Where-Object { $null -ne $_ }) $included=$false; $excluded=$false; $deleteOnly=$false diff --git a/package/module/PRA.Common.psm1 b/package/module/PRA.Common.psm1 index 75dec40..f18ca43 100644 --- a/package/module/PRA.Common.psm1 +++ b/package/module/PRA.Common.psm1 @@ -417,6 +417,53 @@ function Get-PraList { foreach ($item in $value) { if ($null -ne $item) { $item } } } +function ConvertTo-PraImmutableId { + <# The onPremisesImmutableId that a GUID gives: the base64 text of its 16 bytes in Active Directory byte order. A GUID (object, text or 16 bytes) only; $null for anything else, the empty GUID included. #> + [CmdletBinding()] + [OutputType([string])] + param([AllowNull()][object]$Value) + if ($null -eq $Value) { return $null } + if ($Value -isnot [guid] -and $Value -isnot [byte[]] -and $Value -is [System.Collections.IEnumerable] -and $Value -isnot [string]) { + $items = @($Value | Where-Object { $null -ne $_ }) + if ($items.Count -eq 1) { return (ConvertTo-PraImmutableId -Value $items[0]) } + if ($items.Count -eq 16 -and -not @($items | Where-Object { $_ -isnot [byte] }).Count) { return (ConvertTo-PraImmutableId -Value ([byte[]]$items)) } + return $null + } + $guid = [guid]::Empty + if ($Value -is [guid]) { $guid = $Value } + elseif ($Value -is [byte[]]) { if ($Value.Length -ne 16) { return $null }; $guid = [guid]::new([byte[]]$Value) } + elseif (-not [guid]::TryParse([string]$Value, [ref]$guid)) { return $null } + if ($guid -eq [guid]::Empty) { return $null } + return [Convert]::ToBase64String($guid.ToByteArray()) +} + +function Get-PraSourceAnchor { + <# + .SYNOPSIS + The source anchors of one Active Directory record, as the onPremisesImmutableId texts the Entra ID account may carry. + .DESCRIPTION + A record written by this version holds SourceAnchor (ObjectGuid and ConsistencyGuid, both base64); the Entra ID account is the right one when it carries either. + A record without it (backup, transfer package or batch of an older version) has only its ObjectGuid: the anchor is derived from it (Recorded = $false). + A record without a usable GUID has no anchor (Usable = $false). The texts are base64 and are compared exactly. + #> + [CmdletBinding()] + param([AllowNull()][object]$Record) + $candidates = New-Object 'Collections.Generic.List[string]' + $stored = Get-PraValue $Record 'SourceAnchor' $null + $recorded = $false + if ($null -ne $stored) { + foreach ($name in @('ConsistencyGuid', 'ObjectGuid')) { + $text = [string](Get-PraValue $stored $name '') + if ($text -cmatch '^[A-Za-z0-9+/]{22}==\z' -and -not $candidates.Contains($text)) { $candidates.Add($text); $recorded = $true } + } + } + if (-not $recorded) { + $derived = ConvertTo-PraImmutableId -Value (Get-PraValue $Record 'ObjectGuid' $null) + if ($derived) { $candidates.Add($derived) } + } + return [pscustomobject]@{ Candidates = [string[]]$candidates.ToArray(); Recorded = $recorded; Usable = ($candidates.Count -gt 0) } +} + function Format-PraDuration { <# .SYNOPSIS @@ -1147,6 +1194,7 @@ function Get-PraDefaultConfiguration { Cloud = @{ TenantId=''; Organization=''; AppId=''; CertificateThumbprint=''; UserPrincipalName='' CheckMailbox=$true; CheckLicense=$true; MailboxCheckVia='Exo'; RequiredSkuPartNumber='' + IdentityCheck='Anchor'; RetryBudgetObjectSeconds=180; RetryBudgetRunMinutes=30 } Exo = @{ MinModuleVersion='3.10.1'; UseSubprocess=$false; DisableWAM=$false; GrantVerifyAttempts=13; GrantVerifyDelaySeconds=10 } Polling = @{ IntervalMinutes=1; TimeoutMinutes=60 } @@ -1273,6 +1321,12 @@ function Import-PraConfiguration { $badValue = $cloud.MailboxCheckVia $cloud.MailboxCheckVia = Resolve-PraOfficialValue $cloud.MailboxCheckVia @('Graph','Exo') if ($null -eq $cloud.MailboxCheckVia) { throw (Get-PraConfigurationValueError $file 'Cloud.MailboxCheckVia' 'Exo or Graph' $badValue) } + $badValue = $cloud.IdentityCheck + $cloud.IdentityCheck = Resolve-PraOfficialValue $cloud.IdentityCheck @('Anchor','Off') + if ($null -eq $cloud.IdentityCheck) { throw (Get-PraConfigurationValueError $file 'Cloud.IdentityCheck' 'Anchor or Off' $badValue) } + if ($cloud.RetryBudgetObjectSeconds -lt 0 -or $cloud.RetryBudgetObjectSeconds -gt 3600 -or $cloud.RetryBudgetRunMinutes -lt 0 -or $cloud.RetryBudgetRunMinutes -gt 720) { + throw 'Configuration: Cloud.RetryBudgetObjectSeconds must be 0..3600 and Cloud.RetryBudgetRunMinutes 0..720 (0 = no retry).' + } if ([bool]$cloud.AppId -ne [bool]$cloud.CertificateThumbprint) { throw 'Configuration: Cloud.AppId and Cloud.CertificateThumbprint go together (both set = certificate sign-in, both empty = interactive sign-in).' } if ($cloud.AppId) { # Certificate (app-only) sign-in cannot work without the tenant: refuse it at load, not in the middle of a run. @@ -3114,7 +3168,7 @@ function Write-PraGlobalReport { } #endregion -Export-ModuleMember -Function Register-PraObjectName, Get-PraList, Register-PraObjectBackup, Save-PraPhaseData, Copy-PraPhaseData, Read-PraPhaseData, New-PraPhaseRecord, Get-PraGlobalModel, Write-PraGlobalReport, Write-PraGlobalReportHtml, Write-PraGlobalReportCsv, Test-PraGlobalReportWanted, Limit-PraText, Get-PraEventObjectName, Test-PraOrdinalEqual, Test-PraOrdinalIgnoreCaseEqual, Test-PraOrdinalIn, Test-PraOrdinalIgnoreCaseIn, Get-PraOrdinalSorted, Get-PraOrdinalUnique, Compare-PraX500Address, ConvertFrom-PraJson, Get-PraNativeProcessApi, Read-PraCsvText, Get-PraToolVersion, Get-PraCloudModuleReport, New-PraPrivateDirectorySecurity, Initialize-PraPrivateFolder, ConvertTo-PraCsvCell, Get-PraValue, Format-PraDuration, Add-PraIssue, Write-PraLog, Write-PraItem, Write-PraBanner, Write-PraStep, +Export-ModuleMember -Function Register-PraObjectName, Get-PraList, ConvertTo-PraImmutableId, Get-PraSourceAnchor, Register-PraObjectBackup, Save-PraPhaseData, Copy-PraPhaseData, Read-PraPhaseData, New-PraPhaseRecord, Get-PraGlobalModel, Write-PraGlobalReport, Write-PraGlobalReportHtml, Write-PraGlobalReportCsv, Test-PraGlobalReportWanted, Limit-PraText, Get-PraEventObjectName, Test-PraOrdinalEqual, Test-PraOrdinalIgnoreCaseEqual, Test-PraOrdinalIn, Test-PraOrdinalIgnoreCaseIn, Get-PraOrdinalSorted, Get-PraOrdinalUnique, Compare-PraX500Address, ConvertFrom-PraJson, Get-PraNativeProcessApi, Read-PraCsvText, Get-PraToolVersion, Get-PraCloudModuleReport, New-PraPrivateDirectorySecurity, Initialize-PraPrivateFolder, ConvertTo-PraCsvCell, Get-PraValue, Format-PraDuration, Add-PraIssue, Write-PraLog, Write-PraItem, Write-PraBanner, Write-PraStep, Write-PraSummary, Write-PraHost, Resolve-PraPath, Import-PraConfiguration, Test-PraScopeConfiguration, Initialize-PraAudit, Get-PraOutcome, Complete-PraRun, Write-PraEvent, Get-PraWin32ErrorText, Test-PraOwnEntryProcess, Get-PraTargetOverride, Read-PraTargetCsv, Write-PraProgress, Get-PraTransferPackageName, Get-PraTransferPackage, Import-PraTransferPackage, New-PraTransferPackage, New-PraEffectiveConfiguration, Get-PraConfigurationDifference # SIG # Begin signature block diff --git a/package/module/PRA.Directory.psm1 b/package/module/PRA.Directory.psm1 index 5a379d0..c572acd 100644 --- a/package/module/PRA.Directory.psm1 +++ b/package/module/PRA.Directory.psm1 @@ -427,6 +427,7 @@ function Get-PraUser { param([hashtable]$Context, [Parameter(Mandatory)][string]$Identity, [string[]]$ExtraProperties = @(), [switch]$Capture) $properties = @('memberOf','uSNChanged','DisplayName','mail','mailNickname','msExchArchiveGUID','legacyExchangeDN') + @($script:AttributeKinds.Keys) + $ExtraProperties if ($Capture) { $properties += @('*','msExchMailboxSecurityDescriptor','nTSecurityDescriptor','publicDelegates') } + elseif (Test-PraConsistencyGuidSchema -Context $Context) { $properties += 'mS-DS-ConsistencyGuid' } $properties = @($properties | Get-PraOrdinalUnique -IgnoreCase) $server = $Context.Server if ($Identity -match '@' -and $Identity -notmatch '^(CN|OU|DC)=') { @@ -1028,7 +1029,8 @@ function Write-PraAdDelta { if ((-not (Test-PraOrdinalIgnoreCaseEqual $afterType $beforeType))) { $typeText += (' {0} ' -f [char]0x2192) + $(if ($script:RecipientTypeNames.ContainsKey($afterType)) { $script:RecipientTypeNames[$afterType] } else { $afterType }) } if ((Test-PraOrdinalIgnoreCaseEqual $Stage 'Verified')) { $groupAction = [string](Get-PraValue $Plan.Row 'GroupAction' '') - $statusText = switch ([string]$Plan.Row.FinalStatus) { 'Pending' { 'next: Exchange Online deprovisioning check' } 'AlreadyDone' { 'already in the expected state' } default { 'done' } } + $pendingText = if ((Test-PraOrdinalIgnoreCaseEqual $Plan.Operation 'Convert')) { 'next: Exchange Online part (mailbox, licence, permissions)' } else { 'next: Exchange Online deprovisioning check' } + $statusText = switch ([string]$Plan.Row.FinalStatus) { 'Pending' { $pendingText } 'AlreadyDone' { 'already in the expected state' } default { 'done' } } $text = '{0} {1} {2} AD verified, {3} attribute(s) changed{4} {2} {5}' -f $record.SamAccountName, $typeText, [char]0x00B7, ($Plan.Kinds.Count - $unchanged), $(if ((Test-PraOrdinalIn $groupAction @('Added','Removed') -IgnoreCase)) { ', licence group ' + $groupAction.ToLowerInvariant() } else { '' }), $statusText Write-PraItem -Context $Context -Status Ok -Text $text return @@ -1167,6 +1169,7 @@ function Initialize-PraPermissionCache { [CmdletBinding()] param([hashtable]$Context) [void]$script:PermissionCaches.Remove($Context) + [void]$Context.Remove('_PraTrusteeAnchors') } function Get-PraPermissionCache { @@ -1200,6 +1203,34 @@ function Add-PraPermissionCache { $cache.Order.Enqueue($Key); $cache.UpnCount += $Upns.Count; $cache.CharacterCount += $characters } +function Test-PraConsistencyGuidSchema { + <# True when the schema of the forest has ms-DS-ConsistencyGuid (read once per run, never an error: an answer that cannot be read is "no"). #> + [CmdletBinding()] + param([hashtable]$Context) + if ($Context.ContainsKey('_PraConsistencyGuidSchema')) { return [bool]$Context['_PraConsistencyGuidSchema'] } + $available = $false + try { + $schema = [string](Get-ADRootDSE -Server $Context.Server -ErrorAction Stop).schemaNamingContext + if ($schema) { $available = (@(Get-ADObject -SearchBase $schema -LDAPFilter '(&(objectClass=attributeSchema)(lDAPDisplayName=mS-DS-ConsistencyGuid))' -Server $Context.Server -ErrorAction Stop).Count -eq 1) } + } + catch { Write-PraLog -Context $Context -Message ('ms-DS-ConsistencyGuid: schema not readable, only the objectGUID is recorded for trustees ({0})' -f $_.Exception.Message) -Level Detail } + $Context['_PraConsistencyGuidSchema'] = $available + return $available +} + +function Add-PraTrusteeAnchor { + <# Remembers the source anchors (objectGUID, and ms-DS-ConsistencyGuid when the object has it) of a trustee seen in this run, by UPN. #> + [CmdletBinding()] + param([hashtable]$Context, [string]$Upn, $Object) + if (-not $Context.ContainsKey('_PraTrusteeAnchors')) { $Context['_PraTrusteeAnchors'] = New-Object 'Collections.Generic.Dictionary[string,string[]]' ([StringComparer]::OrdinalIgnoreCase) } + $anchors = New-Object 'Collections.Generic.List[string]' + foreach ($value in @((Get-PraValue $Object 'mS-DS-ConsistencyGuid' $null), (Get-PraValue $Object 'ObjectGUID' $null))) { + $text = ConvertTo-PraImmutableId -Value $value + if ($text -and -not $anchors.Contains($text)) { $anchors.Add($text) } + } + if ($anchors.Count) { $Context['_PraTrusteeAnchors'][$Upn] = [string[]]$anchors.ToArray() } +} + function Expand-PraTrustee { <# UPN(s) of a trustee: the user itself, or the members of a group (recursive), minus the exclusions. #> [CmdletBinding()] @@ -1209,6 +1240,7 @@ function Expand-PraTrustee { if (Test-PraOrdinalIgnoreCaseEqual $Object.objectClass 'user') { $upn = [string](Get-PraValue $Object 'userPrincipalName' '') if (-not $upn) { throw "Trustee without UPN: $($Object.DistinguishedName)" } + Add-PraTrusteeAnchor -Context $Context -Upn $upn -Object $Object return $upn } if (-not (Test-PraOrdinalIgnoreCaseEqual $Object.objectClass 'group')) { throw "Unsupported trustee type: $($Object.objectClass)" } @@ -1231,11 +1263,13 @@ function Expand-PraTrustee { foreach ($upn in $cache.Entries[$memberKey].Upns) { [void]$upns.Add($upn) } } else { - $user = Get-ADUser -Identity $member.DistinguishedName -Properties userPrincipalName, sAMAccountName -Server $Context.Server -ErrorAction Stop + $memberProperties = @('userPrincipalName', 'sAMAccountName') + @(if (Test-PraConsistencyGuidSchema -Context $Context) { 'mS-DS-ConsistencyGuid' }) + $user = Get-ADUser -Identity $member.DistinguishedName -Properties $memberProperties -Server $Context.Server -ErrorAction Stop $memberUpns = @() if (-not (Test-PraOrdinalIn -IgnoreCase $user.SamAccountName $excluded)) { if (-not $user.UserPrincipalName) { throw "Trustee without UPN: $($member.DistinguishedName)" } $memberUpns = @([string]$user.UserPrincipalName); [void]$upns.Add([string]$user.UserPrincipalName) + Add-PraTrusteeAnchor -Context $Context -Upn ([string]$user.UserPrincipalName) -Object $user } Add-PraPermissionCache -Context $Context -Key $memberKey -Upns $memberUpns } @@ -1270,7 +1304,8 @@ function Resolve-PraAclTrustee { if ($cache.Entries.ContainsKey($key)) { return $cache.Entries[$key].Upns } $Context.CurrentOperation = 'Resolve-PermissionTrustee'; $Context.CurrentIdentity = $sid.Value Write-PraLog -Context $Context -Message ("PERMISSIONS TRUSTEE | DC=$($Context.Server) | SID=$($sid.Value)") -Level Debug - $objects = @(Get-ADObject -Filter "objectSid -eq '$($sid.Value)'" -Properties objectClass, userPrincipalName, sAMAccountName -Server $Context.Server -ErrorAction Stop) + $trusteeProperties = @('objectClass', 'userPrincipalName', 'sAMAccountName') + @(if (Test-PraConsistencyGuidSchema -Context $Context) { 'mS-DS-ConsistencyGuid' }) + $objects = @(Get-ADObject -Filter "objectSid -eq '$($sid.Value)'" -Properties $trusteeProperties -Server $Context.Server -ErrorAction Stop) if ($objects.Count -eq 0) { if ($null -eq $Unknown) { throw "Permission trustee not found in AD: $($sid.Value)" } Write-PraLog -Context $Context -Message ("PERMISSIONS TRUSTEE | SID=$($sid.Value) | not found in AD (deleted account or another domain): ignored") -Level Detail @@ -1383,7 +1418,8 @@ function Get-PraSharedPermission { if ($cache.Entries.ContainsKey($key)) { $upns = $cache.Entries[$key].Upns } else { $Context.CurrentOperation = 'Resolve-PublicDelegate'; $Context.CurrentIdentity = [string]$dn - $delegate = Get-ADObject -Identity $dn -Properties objectClass, userPrincipalName, sAMAccountName -Server $Context.Server -ErrorAction Stop + $delegateProperties = @('objectClass', 'userPrincipalName', 'sAMAccountName') + @(if (Test-PraConsistencyGuidSchema -Context $Context) { 'mS-DS-ConsistencyGuid' }) + $delegate = Get-ADObject -Identity $dn -Properties $delegateProperties -Server $Context.Server -ErrorAction Stop $upns = [string[]]@(Expand-PraTrustee -Context $Context -Object $delegate) Add-PraPermissionCache -Context $Context -Key $key -Upns $upns } @@ -1537,8 +1573,17 @@ function New-PraPlan { $sourceLicensing = Get-PraValue $SourceRecord 'Licensing' $null $preserveMailbox = $shared -and (Test-PraOrdinalIgnoreCaseEqual $Operation 'Recover') -and [bool](Get-PraValue $Context 'KeepCloudShared' $false) $preserveLicense = ((Test-PraOrdinalIgnoreCaseEqual $Operation 'Recover')) -and [bool](Get-PraValue $sourceLicensing 'Enabled' $false) -and [bool](Get-PraValue $sourceLicensing 'WasMember' $false) + $trusteeAnchors = [ordered]@{} + $knownAnchors = Get-PraValue $Context '_PraTrusteeAnchors' $null + if ($null -ne $knownAnchors) { + foreach ($trustee in @(@($permissions.FullAccess) + @($permissions.SendAs) + @($permissions.SendOnBehalf) | Get-PraOrdinalUnique -IgnoreCase | Get-PraOrdinalSorted -IgnoreCase)) { + if ($knownAnchors.ContainsKey([string]$trustee)) { $trusteeAnchors[[string]$trustee] = [string[]]@($knownAnchors[[string]$trustee]) } + } + } $record = [ordered]@{ ObjectGuid=([guid]$user.ObjectGUID).ToString(); DistinguishedName=[string]$user.DistinguishedName + SourceAnchor=[ordered]@{ ObjectGuid=[string](ConvertTo-PraImmutableId -Value $user.ObjectGUID); ConsistencyGuid=[string](ConvertTo-PraImmutableId -Value (Get-PraValue $user 'mS-DS-ConsistencyGuid' $null)) } + SharedTrusteeAnchors=$trusteeAnchors SamAccountName=[string]$user.SamAccountName; UserPrincipalName=[string]$user.UserPrincipalName; DisplayName=[string](Get-PraValue $user 'DisplayName' $user.SamAccountName) CapturedUtc=[DateTime]::UtcNow.ToString('o'); CapturedUsnChanged=(Get-PraUsn $user); IsShared=$shared; RequestedOperation=$Operation Attributes=$before; PlannedAttributes=$desired; Licensing=$licensing @@ -1609,6 +1654,22 @@ function Assert-PraStoredRecord { if (@($expectedStored).Count -gt $script:MaxExpectedX500) { throw 'Backup: too many expected X500 addresses.' } foreach ($value in @($expectedStored)) { if ($value -isnot [string] -or -not (Test-PraX500Address $value) -or $value.Length -gt $script:MaxExpectedX500Length) { throw 'Backup: invalid list of expected X500 addresses.' } } } + # Source anchors (absent from a batch written without them: the anchor is derived from the GUID of the record). + $anchorStored = Get-PraValue $Record 'SourceAnchor' $null + if ($null -ne $anchorStored) { + foreach ($name in @('ObjectGuid', 'ConsistencyGuid')) { + $text = Get-PraValue $anchorStored $name $null + if ($text -isnot [string] -or ($text -and $text -cnotmatch '^[A-Za-z0-9+/]{22}==\z')) { throw 'Backup: invalid source anchor.' } + } + if (-not [string](Get-PraValue $anchorStored 'ObjectGuid' '')) { throw 'Backup: invalid source anchor.' } + } + $trusteeStored = Get-PraValue $Record 'SharedTrusteeAnchors' $null + if ($null -ne $trusteeStored) { + $trusteeNames = if ($trusteeStored -is [Collections.IDictionary]) { @($trusteeStored.Keys) } else { @($trusteeStored.PSObject.Properties | ForEach-Object { $_.Name }) } + foreach ($name in $trusteeNames) { + foreach ($text in @(Get-PraList $trusteeStored ([string]$name))) { if ($text -isnot [string] -or $text -cnotmatch '^[A-Za-z0-9+/]{22}==\z') { throw 'Backup: invalid trustee source anchor.' } } + } + } if (-not $Legacy) { if ($Record.CapturedUsnChanged -isnot [string] -or $Record.CapturedUsnChanged -notmatch '^[1-9][0-9]*\z') { throw 'Backup: original uSNChanged missing or invalid.' } $null = [int64]::Parse($Record.CapturedUsnChanged, [Globalization.CultureInfo]::InvariantCulture) diff --git a/package/module/PRA.Gui.psm1 b/package/module/PRA.Gui.psm1 index 3eb00ff..fa424a7 100644 --- a/package/module/PRA.Gui.psm1 +++ b/package/module/PRA.Gui.psm1 @@ -1335,6 +1335,19 @@ function Test-PraGuiBatchSyncCompleted { return $false } +function Test-PraGuiBatchImported { + <# True when the batch came from a transfer package imported on this server: the engine leaves \Imported\.txt, and the package may still wait in the Inbox. #> + param($Item) + try { + $root=[string]$script:Gui.State.Config.Storage.BackupFolder + if (-not $root) { return $false } + $id=([string]$Item.BatchId).ToLowerInvariant() + if (Test-Path -LiteralPath (Join-Path (Join-Path $root 'Imported') ($id+'.txt')) -PathType Leaf) { return $true } + $package=Get-PraTransferPackageName -Kind Convert -Environment ([string]$Item.Environment) -BatchId ([string]$Item.BatchId) + return (Test-Path -LiteralPath (Join-Path (Join-Path $root 'Inbox') $package) -PathType Leaf) + } catch { return $false } +} + function Get-PraGuiFinishReason { <# .SYNOPSIS @@ -1343,9 +1356,12 @@ function Get-PraGuiFinishReason { #> param($Item) $g=$script:Gui - if (Test-PraGuiBatchSyncFailed $Item.Folder $Item.BatchId) { return 'AD part done, sync did not run: finish it here' } + # The AD part is finished on the server that ran it: a batch imported from a transfer package, or a server that cannot run the AD part, goes on with the cloud part. + $adHere=(-not $g.Detect) -or (Test-GuiOrdinalIn ([string]$g.Detect.Role) @('AD','Both') -IgnoreCase) + $finishHere=$adHere -and -not (Test-PraGuiBatchImported $Item) + if ($finishHere -and (Test-PraGuiBatchSyncFailed $Item.Folder $Item.BatchId)) { return 'AD part done, sync did not run: finish it here' } # A batch with no Entra Connect entry that ended well goes through the AD part first (the synchronisation, then the package), as the command line does: a partial batch always, any other batch when the configuration asks for the synchronisation. - if (-not (Test-PraGuiBatchSyncCompleted $Item.Folder $Item.BatchId)) { + if ($finishHere -and -not (Test-PraGuiBatchSyncCompleted $Item.Folder $Item.BatchId)) { $partialText=Get-PraGuiPartialText (Join-Path $Item.Folder ('State-'+$Item.BatchId+'.json')) $syncOn=[bool](Get-PraGuiValue (Get-PraGuiValue $g.State.Config 'EntraConnect' @{}) 'Sync' $false) if ($partialText) { return 'AD part partly done, sync not run: finish it here' } @@ -1355,7 +1371,7 @@ function Get-PraGuiFinishReason { try { $package=Get-PraTransferPackageName -Kind Convert -Environment ([string]$Item.Environment) -BatchId ([string]$Item.BatchId) } catch { return '' } $outbox=Join-Path $g.State.Config.Storage.BackupFolder 'Outbox' $cloudHere=(-not $g.Detect) -or ([bool]$g.Detect.Cloud -and -not (Test-PraGuiNetworkDown)) - if (-not $cloudHere -and -not (Test-Path -LiteralPath (Join-Path $outbox $package) -PathType Leaf)) { return 'AD part done, no package yet: finish it here' } + if ($finishHere -and -not $cloudHere -and -not (Test-Path -LiteralPath (Join-Path $outbox $package) -PathType Leaf)) { return 'AD part done, no package yet: finish it here' } return '' } diff --git a/tests/PraRemoteMailbox.Gui.Tests.ps1 b/tests/PraRemoteMailbox.Gui.Tests.ps1 index c0c1057..9324fbc 100644 --- a/tests/PraRemoteMailbox.Gui.Tests.ps1 +++ b/tests/PraRemoteMailbox.Gui.Tests.ps1 @@ -2094,4 +2094,55 @@ Describe 'Release 3.2.0 - the console continues a partial batch, or a batch whos $reasons['plain-False'] | Should -Not -Match 'finish it here' -Because 'the configuration leaves the synchronisation to the operator' $reasons['synced-True'] | Should -Not -Match 'finish it here' -Because 'its journal has an Entra Connect entry that ended well' } + It 'finishes a batch here only when it was converted on this server and this server can run the AD part: an imported batch, or a cloud-only server, goes on with the cloud part (partial, plain and sync-failed batches, Sync on and off)' { + $runtime = New-GuiTestRoot + $backups = Join-Path $runtime.Root 'Backups' + $makeBatch = { + param([string]$Kind, [bool]$Imported) + $batch = New-GuiTestBatch -Runtime $runtime + if ($Kind -eq 'partial') { Write-GuiTestJson $batch.Proof @{ SchemaVersion = 2; Operation = 'Convert'; Kind = 'ADVerified'; Environment = 'GuiSynthetic'; Partial = $true; PlannedCount = 10; Records = @(@{ ObjectGuid = [guid]::NewGuid().ToString(); Operation = 'Convert'; ADVerified = $true }) } } + if ($Kind -eq 'failed') { Write-GuiTestFile (Join-Path $batch.Folder ('Journal-' + $batch.Id + '.jsonl')) ("{`"RunId`":`"r`",`"Operation`":`"ADSync`",`"Status`":`"Started`"}`r`n{`"RunId`":`"r`",`"Operation`":`"ADSync`",`"Status`":`"Failed`"}`r`n") } + if ($Imported) { Write-GuiTestFile (Join-Path $backups ('Imported\' + $batch.Id + '.txt')) 'Convert-package 2026-11-17' } + [pscustomobject]@{ Folder = $batch.Folder; BatchId = $batch.Id; Environment = 'GuiSynthetic' } + } + $items = @{} + foreach ($kind in 'plain', 'partial', 'failed') { foreach ($imported in $false, $true) { $items[$kind + '-' + $imported] = & $makeBatch $kind $imported } } + $inbox = & $makeBatch 'plain' $false + $package = & (Get-Module PRA.Gui) { param($Item) Get-PraTransferPackageName -Kind Convert -Environment $Item.Environment -BatchId $Item.BatchId } $inbox + Write-GuiTestFile (Join-Path $backups ('Inbox\' + $package)) 'synthetic package' + $items['inbox'] = $inbox + $reasons = & (Get-Module PRA.Gui) { + param($Items, $Folder) + $saved = $script:Gui + try { + $result = @{} + foreach ($role in 'Cloud', 'AD', 'Both') { + foreach ($sync in $false, $true) { + $script:Gui = [pscustomobject]@{ State = [pscustomobject]@{ Config = @{ EntraConnect = @{ Sync = $sync }; Storage = @{ BackupFolder = $Folder } } }; Detect = [pscustomobject]@{ Role = $role; AD = ($role -ne 'Cloud'); Cloud = ($role -ne 'AD') } } + foreach ($name in $Items.Keys) { $result[$role + '-' + $sync + '-' + $name] = [string](Get-PraGuiFinishReason $Items[$name]) } + } + } + $result + } + finally { $script:Gui = $saved } + } $items $backups + foreach ($sync in $false, $true) { + foreach ($kind in 'plain', 'partial', 'failed', 'inbox') { + foreach ($role in 'Cloud', 'AD', 'Both') { + $name = if ($kind -eq 'inbox') { 'inbox' } else { $kind + '-True' } + $reasons[$role + '-' + $sync + '-' + $name] | Should -Not -Match 'finish it here' -Because ('imported batch, role ' + $role + ', sync ' + $sync + ', ' + $kind) + } + } + foreach ($kind in 'partial', 'failed') { + $reasons['Cloud-' + $sync + '-' + $kind + '-False'] | Should -Not -Match 'finish it here' -Because 'a cloud-only server has no AD part to finish' + $reasons['AD-' + $sync + '-' + $kind + '-False'] | Should -Match 'finish it here' -Because 'a local batch of a server that has AD' + $reasons['Both-' + $sync + '-' + $kind + '-False'] | Should -Match 'finish it here' + } + $reasons['Cloud-' + $sync + '-plain-False'] | Should -Not -Match 'finish it here' + $reasons['AD-' + $sync + '-plain-False'] | Should -Match 'finish it here' -Because 'a server that only has AD and no package yet finishes its own batch' + } + $reasons['AD-True-plain-False'] | Should -BeExactly 'AD part done, sync not confirmed: finish it here' + $reasons['Both-False-plain-False'] | Should -Not -Match 'finish it here' -Because 'a plain local batch with Sync off is left to the operator when the cloud part can run here' + $reasons['Both-True-plain-False'] | Should -BeExactly 'AD part done, sync not confirmed: finish it here' + } } diff --git a/tests/PraRemoteMailbox.Tests.ps1 b/tests/PraRemoteMailbox.Tests.ps1 index 6f02e06..3d5d1c4 100644 --- a/tests/PraRemoteMailbox.Tests.ps1 +++ b/tests/PraRemoteMailbox.Tests.ps1 @@ -190,7 +190,14 @@ function Get-ADUser { } foreach ($user in $global:PraGateAd.Users) { $match=$false - if ($Identity) { $match=([string]$Identity -in @([string]$user.ObjectGUID,$user.SamAccountName,$user.DistinguishedName)) } + if ($Identity) { + $match=([string]$Identity -in @([string]$user.ObjectGUID,$user.SamAccountName,$user.DistinguishedName)) + # A GUID with braces or without dashes, and a down-level logon name (GATE\sam), are accepted as the directory accepts them. + if (-not $match) { + $digits=([string]$Identity).Trim().Trim('{','}').Replace('-','') + $match=($digits -ieq ([string]$user.ObjectGUID).Replace('-','')) -or (([string]$Identity -match '^GATE\\(?.+)$') -and $Matches.sam -ieq $user.SamAccountName) + } + } elseif ($LDAPFilter -like '(userPrincipalName=*') { $encoded=$user.UserPrincipalName.Replace('\','\5c').Replace('*','\2a').Replace('(','\28').Replace(')','\29').Replace([string][char]0,'\00') $match=$LDAPFilter -ieq ('(userPrincipalName='+$encoded+')') @@ -222,7 +229,7 @@ function Get-ADGroupMember { } function Get-ADObject { [CmdletBinding()] - param([object]$Identity,[string]$Filter,[string[]]$Properties,[string]$Server) + param([object]$Identity,[string]$Filter,[string]$LDAPFilter,[string]$SearchBase,[string[]]$Properties,[string]$Server) Assert-GateServer $Server Write-GateEvent 'Get-ADObject' $Identity $Server @{Filter=$Filter;Properties=$Properties} if ($global:PraGateAd.ContainsKey('PermissionGroups')) { @@ -356,6 +363,13 @@ function Invoke-PraCloudPhase { [void]$Context.Issues.Add([pscustomobject]@{ Timestamp=(Get-Date).ToString('o'); Phase='Cloud'; Source='Cloud'; Operation='Connect-MgGraph'; Identity=[string]$row.ObjectGuid; Message=$text }) Write-PraItem -Context $Context -Status Fail -Text $text } + } elseif ($state.Case -eq 'CloudThrottled') { + # What the real cloud phase does when the retry time of the run is used up: ONE run error, the rows not finished, never one error per row. + $Context.CloudThrottled=$true; $Context.CurrentPhase='Cloud'; $Context.CurrentOperation='CloudCheck'; $Context.CurrentIdentity='' + foreach ($row in $Rows) { $row.CloudStatus='Pending'; $row.FinalStatus='Pending'; $row.CloudDetail='SYNTHETIC: not finished, the retry time of the run is used up.' } + $text='Microsoft 365 is limiting or not answering this run: the 30 minute(s) allowed for retries are used up (40 retries, 12 throttled answers). Nothing more is asked of Microsoft 365. What this run already did is kept: run the same command again in a few minutes. '+@($Rows).Count+' object(s) were not finished.' + [void]$Context.Issues.Add([pscustomobject]@{ Timestamp=(Get-Date).ToString('o'); Phase='Cloud'; Source='Cloud'; Operation='CloudCheck'; Identity=''; Message=$text }) + Write-PraItem -Context $Context -Status Fail -Text $text } elseif ($state.Case -eq 'CloudWaitTimeout') { # What the real cloud phase does when the objects are still not in the expected state after the wait: a cloud error on each row (not a run error) and their number. $Context.CurrentPhase='Cloud'; $Context.CurrentOperation='CloudCheck'; $Context.CloudNotReached=0 @@ -2612,7 +2626,7 @@ Export-ModuleMember -Function Get-EXOMailbox,Get-EXORecipient,Get-MgUser,Get-MgU $global:PraGate.CloudContext=New-GateContext $global:PraGate.Runtime -Mode Preview -Action Recover $global:PraGate.CloudContext.Phase='Cloud'; $global:PraGate.CloudContext.Once=$true $global:PraGate.CloudContext.CheckScope='Both'; $global:PraGate.CloudContext.IntervalMinutes=0; $global:PraGate.CloudContext.TimeoutMinutes=0 - $global:PraGate.CloudContext.Config.Cloud=@{CheckMailbox=$true;CheckLicense=$false;MailboxCheckVia='Exo';RequiredSkuPartNumber='';TenantId='20000000-0000-0000-0000-000000000002'} + $global:PraGate.CloudContext.Config.Cloud=@{CheckMailbox=$true;CheckLicense=$false;MailboxCheckVia='Exo';RequiredSkuPartNumber='';IdentityCheck='Off';TenantId='20000000-0000-0000-0000-000000000002'} $global:PraGate.CloudContext.Config.SharedMailbox.GrantFullAccess=$false $global:PraGate.CloudRow=New-PraRow $global:PraGate.CloudContext ([pscustomobject]@{ObjectGuid='00000000-0000-0000-0000-000000000001';UserPrincipalName='user1@gate.invalid';IsShared=$false}) $global:PraGate.CloudCalls=@{Writes=0;Connected=0} @@ -3077,7 +3091,7 @@ Export-ModuleMember -Function Get-ConnectionInformation,Get-EXORecipient,Get-EXO BeforeEach { $context=New-GateContext $global:PraGate.Runtime $context.Phase='Both' - $context.Config.Cloud=@{TenantId=$global:PraGate.Native.Tenant;UserPrincipalName='operator@gate.invalid';CheckMailbox=$true;CheckLicense=$true;MailboxCheckVia='Exo';AppId='';CertificateThumbprint=''} + $context.Config.Cloud=@{TenantId=$global:PraGate.Native.Tenant;UserPrincipalName='operator@gate.invalid';CheckMailbox=$true;CheckLicense=$true;MailboxCheckVia='Exo';IdentityCheck='Off';AppId='';CertificateThumbprint=''} $context.Config.Exo=@{MinModuleVersion='3.10.0';UseSubprocess=$false;DisableWAM=$true;GrantVerifyAttempts=13;GrantVerifyDelaySeconds=10} $context.Config.SharedMailbox.PermissionSource='AD';$context.Config.SharedMailbox.GrantFullAccess=$true;$context.Config.SharedMailbox.GrantSendAs=$true $global:PraGate.NativeContext=$context @@ -6779,7 +6793,7 @@ Export-ModuleMember -Function Get-EXOMailbox,Get-EXORecipient,Get-MgUser,Get-MgU $global:PraGate.Runtime=New-GateRuntime -Name 'x500-cloud' $context=New-GateContext $global:PraGate.Runtime -Mode Apply -Action Convert $context.Phase='Cloud'; $context.Once=$false; $context.CheckScope='Both'; $context.IntervalMinutes=0; $context.TimeoutMinutes=5 - $context.Config.Cloud=@{CheckMailbox=$true;CheckLicense=$false;MailboxCheckVia='Exo';RequiredSkuPartNumber='';TenantId='20000000-0000-0000-0000-000000000002'} + $context.Config.Cloud=@{CheckMailbox=$true;CheckLicense=$false;MailboxCheckVia='Exo';RequiredSkuPartNumber='';IdentityCheck='Off';TenantId='20000000-0000-0000-0000-000000000002'} $context.Config.SharedMailbox.GrantFullAccess=$false $context.LogFile=Join-Path $global:PraGate.Runtime.Root 'logs\x500-cloud.log' $global:PraGate.CloudContext=$context @@ -7865,7 +7879,7 @@ Export-ModuleMember -Function Get-EXOMailbox,Get-EXORecipient,Get-MgUser,Get-MgU $global:PraGate.Runtime=New-GateRuntime -Name 'check-313' $context=New-GateContext $global:PraGate.Runtime -Mode Preview -Action Check $context.Phase='Cloud'; $context.Once=$false; $context.CheckScope='Both'; $context.IntervalMinutes=1; $context.TimeoutMinutes=3 - $context.Config.Cloud=@{CheckMailbox=$true;CheckLicense=$false;MailboxCheckVia='Exo';RequiredSkuPartNumber='';TenantId='20000000-0000-0000-0000-000000000002'} + $context.Config.Cloud=@{CheckMailbox=$true;CheckLicense=$false;MailboxCheckVia='Exo';RequiredSkuPartNumber='';IdentityCheck='Off';TenantId='20000000-0000-0000-0000-000000000002'} $context.Config.SharedMailbox.GrantFullAccess=$false $context.LogFile=Join-Path $global:PraGate.Runtime.Root 'logs\check-313.log' $global:PraGate.CloudContext=$context @@ -8116,7 +8130,7 @@ Export-ModuleMember -Function Get-EXOMailbox,Get-EXORecipient,Get-ConnectionInfo $global:PraGate.Runtime=New-GateRuntime -Name 'network-313c' $context=New-GateContext $global:PraGate.Runtime -Mode Preview -Action Check $context.Phase='Cloud'; $context.Once=$true; $context.CheckScope='Both'; $context.IntervalMinutes=1; $context.TimeoutMinutes=3 - $context.Config.Cloud=@{CheckMailbox=$true;CheckLicense=$false;MailboxCheckVia='Exo';RequiredSkuPartNumber='';TenantId='20000000-0000-0000-0000-000000000002'} + $context.Config.Cloud=@{CheckMailbox=$true;CheckLicense=$false;MailboxCheckVia='Exo';RequiredSkuPartNumber='';IdentityCheck='Off';TenantId='20000000-0000-0000-0000-000000000002'} $context.Config.SharedMailbox.GrantFullAccess=$false $context.LogFile=Join-Path $global:PraGate.Runtime.Root 'logs\network-313c.log' $global:PraGate.CloudContext=$context @@ -9484,7 +9498,7 @@ Describe 'Release 3.2.0 - an object that was not reached is not skipped: Planned $runtime = New-GateRuntime -Name 'pending-cloud-320a' $context = New-GateContext $runtime -Mode Apply -Action Convert $context.Phase = 'Cloud'; $context.Once = $true; $context.IntervalMinutes = 0; $context.TimeoutMinutes = 1 - $context.Config.Cloud = @{ CheckMailbox = $true; CheckLicense = $false; MailboxCheckVia = 'Exo'; RequiredSkuPartNumber = ''; TenantId = '20000000-0000-0000-0000-000000000002' } + $context.Config.Cloud = @{ CheckMailbox = $true; CheckLicense = $false; MailboxCheckVia = 'Exo'; RequiredSkuPartNumber = ''; IdentityCheck = 'Off'; TenantId = '20000000-0000-0000-0000-000000000002' } $context.LogFile = Join-Path $runtime.Root 'logs\pending-cloud.log' $global:PraGate.Context320 = $context $global:PraGate.Row320 = New-PraRow $context ([pscustomobject]@{ ObjectGuid = '00000000-0000-0000-0000-000000000001'; UserPrincipalName = 'user1@gate.invalid'; SamAccountName = 'user1'; IsShared = $false }) @@ -9863,7 +9877,7 @@ Describe 'Release 3.2.0 - the shared mailbox permissions follow the batch: store $runtime = New-GateRuntime -Name ('grant-none-320a-' + $source) $context = New-GateContext $runtime -Mode Apply -Action Convert $context.Phase = 'Cloud'; $context.Once = $true; $context.IntervalMinutes = 0; $context.TimeoutMinutes = 1; $context.GrantSettingsSource = $source - $context.Config.Cloud = @{ CheckMailbox = $false; CheckLicense = $false; MailboxCheckVia = 'Exo'; RequiredSkuPartNumber = ''; TenantId = '20000000-0000-0000-0000-000000000002' } + $context.Config.Cloud = @{ CheckMailbox = $false; CheckLicense = $false; MailboxCheckVia = 'Exo'; RequiredSkuPartNumber = ''; IdentityCheck = 'Off'; TenantId = '20000000-0000-0000-0000-000000000002' } $context.Config.SharedMailbox = @{ Enabled = $false; PermissionSource = 'AD'; GrantFullAccess = $false; GrantSendAs = $false; GrantSendOnBehalf = $false } $context.LogFile = Join-Path $runtime.Root 'logs\grant-none.log' if ($source -eq 'Batch') { $context.BatchGrantSettings = @{ Enabled = $true; PermissionSource = 'AD'; GrantFullAccess = $false; GrantSendAs = $false; GrantSendOnBehalf = $false } } @@ -10061,3 +10075,963 @@ Describe 'Release 3.2.0 - the exit code goes to the host only when the script is $global:PraGate.Remove('StoppedRecover'); $global:PraGate.Remove('StoppedObjects') } } + +Describe 'Release 3.2.0 - source anchors and the new cloud settings (production Common module)' -Tag 'Release320b' { + BeforeAll { Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global } + It 'ConvertTo-PraImmutableId gives the base64 of the 16 bytes of a GUID, whatever the form (object, text in any letter case, bytes, a one-item collection) and nothing for anything else' { + $guid = [guid]'ab12cd34-0000-4000-8000-0000000000ef' + $expected = [Convert]::ToBase64String($guid.ToByteArray()) + ConvertTo-PraImmutableId -Value $guid | Should -BeExactly $expected + ConvertTo-PraImmutableId -Value 'AB12CD34-0000-4000-8000-0000000000EF' | Should -BeExactly $expected + ConvertTo-PraImmutableId -Value 'ab12cd34-0000-4000-8000-0000000000ef' | Should -BeExactly $expected + ConvertTo-PraImmutableId -Value ([byte[]]$guid.ToByteArray()) | Should -BeExactly $expected + ConvertTo-PraImmutableId -Value @(, [byte[]]$guid.ToByteArray()) | Should -BeExactly $expected + ConvertTo-PraImmutableId -Value $null | Should -BeNullOrEmpty + ConvertTo-PraImmutableId -Value '' | Should -BeNullOrEmpty + ConvertTo-PraImmutableId -Value 'not a guid' | Should -BeNullOrEmpty + ConvertTo-PraImmutableId -Value ([guid]::Empty) | Should -BeNullOrEmpty + ConvertTo-PraImmutableId -Value ([byte[]](1, 2, 3)) | Should -BeNullOrEmpty + } + It 'Get-PraSourceAnchor: a record with SourceAnchor gives both anchors, an older record derives the objectGUID anchor (and says so), a record without a GUID has no anchor' { + $guid = 'ab12cd34-0000-4000-8000-0000000000ef'; $other = 'cd34ef56-0000-4000-8000-0000000000aa' + $objectAnchor = [Convert]::ToBase64String(([guid]$guid).ToByteArray()); $consistencyAnchor = [Convert]::ToBase64String(([guid]$other).ToByteArray()) + $current = Get-PraSourceAnchor -Record ([pscustomobject]@{ ObjectGuid = $guid; SourceAnchor = [pscustomobject]@{ ObjectGuid = $objectAnchor; ConsistencyGuid = $consistencyAnchor } }) + $current.Recorded | Should -BeTrue + $current.Candidates | Should -BeExactly @($consistencyAnchor, $objectAnchor) + $objectOnly = Get-PraSourceAnchor -Record ([pscustomobject]@{ ObjectGuid = $guid; SourceAnchor = [pscustomobject]@{ ObjectGuid = $objectAnchor; ConsistencyGuid = '' } }) + $objectOnly.Candidates | Should -BeExactly @($objectAnchor) + $older = Get-PraSourceAnchor -Record ([pscustomobject]@{ ObjectGuid = $guid.ToUpperInvariant() }) + $older.Recorded | Should -BeFalse + $older.Usable | Should -BeTrue + $older.Candidates | Should -BeExactly @($objectAnchor) -Because 'a GUID written in capitals gives the same anchor' + $none = Get-PraSourceAnchor -Record ([pscustomobject]@{ ObjectGuid = ''; UserPrincipalName = 'user1@gate.invalid' }) + $none.Usable | Should -BeFalse + @($none.Candidates).Count | Should -Be 0 + (Get-PraSourceAnchor -Record $null).Usable | Should -BeFalse + $damaged = Get-PraSourceAnchor -Record ([pscustomobject]@{ ObjectGuid = $guid; SourceAnchor = [pscustomobject]@{ ObjectGuid = 'not base64'; ConsistencyGuid = '' } }) + $damaged.Recorded | Should -BeFalse -Because 'a stored anchor that is not base64 is never trusted: the anchor is derived from the GUID' + $damaged.Candidates | Should -BeExactly @($objectAnchor) + } + It 'Cloud.IdentityCheck and the two retry budgets have defaults, are checked, and the value is read in any letter case; the configuration file says the same as the defaults' { + $defaults = InModuleScope PRA.Common { Get-PraDefaultConfiguration } + $defaults.Cloud.IdentityCheck | Should -BeExactly 'Anchor' + $defaults.Cloud.RetryBudgetObjectSeconds | Should -Be 180 + $defaults.Cloud.RetryBudgetRunMinutes | Should -Be 30 + $shipped = Import-PowerShellDataFile -LiteralPath (Join-Path $global:PraGate.Source 'config\PraRemoteMailbox.config.psd1') + $shipped.Cloud.IdentityCheck | Should -BeExactly 'Anchor' + $shipped.Cloud.RetryBudgetObjectSeconds | Should -Be 180 + $shipped.Cloud.RetryBudgetRunMinutes | Should -Be 30 + $runtime = New-GateRuntime -Name 'config-320b' + Set-GateConfigText $runtime { param($t) $t.Replace("Execution=@{Phase='Both'}", "Execution=@{Phase='Both'}; Cloud=@{IdentityCheck='oFF'}") } + (Import-PraConfiguration -Path $runtime.ConfigPath -Root $runtime.Package -DeferScopeCheck).Cloud.IdentityCheck | Should -BeExactly 'Off' + Set-GateConfigText $runtime { param($t) $t.Replace("IdentityCheck='oFF'", "IdentityCheck='aNCHOR'") } + (Import-PraConfiguration -Path $runtime.ConfigPath -Root $runtime.Package -DeferScopeCheck).Cloud.IdentityCheck | Should -BeExactly 'Anchor' + Set-GateConfigText $runtime { param($t) $t.Replace("IdentityCheck='aNCHOR'", "IdentityCheck='upn'") } + { Import-PraConfiguration -Path $runtime.ConfigPath -Root $runtime.Package -DeferScopeCheck } | Should -Throw '*Cloud.IdentityCheck must be Anchor or Off*' + Set-GateConfigText $runtime { param($t) $t.Replace("IdentityCheck='upn'", 'RetryBudgetObjectSeconds=-1') } + { Import-PraConfiguration -Path $runtime.ConfigPath -Root $runtime.Package -DeferScopeCheck } | Should -Throw '*Cloud.RetryBudgetObjectSeconds must be 0..3600*' + Set-GateConfigText $runtime { param($t) $t.Replace('RetryBudgetObjectSeconds=-1', 'RetryBudgetRunMinutes=721') } + { Import-PraConfiguration -Path $runtime.ConfigPath -Root $runtime.Package -DeferScopeCheck } | Should -Throw '*Cloud.RetryBudgetRunMinutes 0..720*' + Set-GateConfigText $runtime { param($t) $t.Replace('RetryBudgetRunMinutes=721', 'RetryBudgetRunMinutes=0;RetryBudgetObjectSeconds=0') } + $zero = Import-PraConfiguration -Path $runtime.ConfigPath -Root $runtime.Package -DeferScopeCheck + $zero.Cloud.RetryBudgetRunMinutes | Should -Be 0 -Because '0 means no retry' + Set-GateConfigText $runtime { param($t) $t.Replace('RetryBudgetRunMinutes=0;RetryBudgetObjectSeconds=0', 'RetryBudgetRunMinutes=1.5') } + { Import-PraConfiguration -Path $runtime.ConfigPath -Root $runtime.Package -DeferScopeCheck } | Should -Throw '*must be a whole number*' + } +} + +Describe 'Release 3.2.0 - the source anchors are recorded at Convert and read back (production Directory module, synthetic AD)' -Tag 'Release320b' { + BeforeAll { + function global:Use-Directory320b { + param($Runtime) + $env:PRA_GATE_STATE = $Runtime.StatePath + $env:PSModulePath = $Runtime.Modules + ';' + (Join-Path $PSHOME 'Modules') + Remove-Module PRA.Directory -Force -ErrorAction SilentlyContinue + Get-Module ActiveDirectory -All | Remove-Module -Force -ErrorAction SilentlyContinue + Import-Module (Join-Path $Runtime.Modules 'ActiveDirectory\ActiveDirectory.psm1') -Force -Global -ErrorAction Stop + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Directory.psm1') -Force -Global -ErrorAction Stop + New-GateContext $Runtime -Mode Preview + } + } + AfterAll { Remove-Item -LiteralPath 'Function:\Use-Directory320b' -ErrorAction SilentlyContinue } + It 'the record of a Convert holds the objectGUID anchor, and the ms-DS-ConsistencyGuid anchor when the object has one; the record survives its JSON file and is accepted by the reader' { + $runtime = New-GateRuntime -Name 'anchor-320b' -UserCount 2 + $consistency = [byte[]](9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10) + Add-Member -InputObject $runtime.State.Users[1] -NotePropertyName 'mS-DS-ConsistencyGuid' -NotePropertyValue $consistency -Force + [IO.File]::WriteAllText($runtime.StatePath, [Management.Automation.PSSerializer]::Serialize($runtime.State, 35)) + $context = Use-Directory320b $runtime + $plain = New-PraPlan $context 'user1' 'Convert' + $withConsistency = New-PraPlan $context 'user2' 'Convert' + $plain.Record.SourceAnchor.ObjectGuid | Should -BeExactly ([Convert]::ToBase64String(([guid]$runtime.State.Users[0].ObjectGUID).ToByteArray())) + $plain.Record.SourceAnchor.ConsistencyGuid | Should -BeExactly '' + $withConsistency.Record.SourceAnchor.ObjectGuid | Should -BeExactly ([Convert]::ToBase64String(([guid]$runtime.State.Users[1].ObjectGUID).ToByteArray())) + $withConsistency.Record.SourceAnchor.ConsistencyGuid | Should -BeExactly ([Convert]::ToBase64String($consistency)) + $withConsistency.Record.SharedTrusteeAnchors.Count | Should -Be 0 + $global:PraGate.Anchor320b = ($withConsistency.Record | ConvertTo-Json -Depth 30) | ConvertFrom-PraJson + $global:PraGate.Anchor320bLegacy = ($withConsistency.Record | ConvertTo-Json -Depth 30) | ConvertFrom-PraJson + $global:PraGate.Anchor320bLegacy.PSObject.Properties.Remove('SourceAnchor'); $global:PraGate.Anchor320bLegacy.PSObject.Properties.Remove('SharedTrusteeAnchors') + InModuleScope PRA.Directory { + { Assert-PraStoredRecord $global:PraGate.Anchor320b } | Should -Not -Throw + { Assert-PraStoredRecord $global:PraGate.Anchor320b -Planned } | Should -Not -Throw + { Assert-PraStoredRecord $global:PraGate.Anchor320bLegacy } | Should -Not -Throw -Because 'a record written by an older version has no anchor' + } + (Get-PraSourceAnchor -Record $global:PraGate.Anchor320b).Candidates.Count | Should -Be 2 + (Get-PraSourceAnchor -Record $global:PraGate.Anchor320bLegacy).Recorded | Should -BeFalse + Remove-Variable Anchor320b, Anchor320bLegacy -Scope Global -ErrorAction SilentlyContinue + $global:PraGate.Remove('Anchor320b'); $global:PraGate.Remove('Anchor320bLegacy') + } + It 'a stored anchor that is not a base64 GUID is refused by the backup reader' { + $runtime = New-GateRuntime -Name 'anchor-bad-320b' -UserCount 2 + $context = Use-Directory320b $runtime + $plan = New-PraPlan $context 'user1' 'Convert' + $global:PraGate.AnchorBad320b = ($plan.Record | ConvertTo-Json -Depth 30) | ConvertFrom-PraJson + $global:PraGate.AnchorBad320b.SourceAnchor.ObjectGuid = 'AAAA' + InModuleScope PRA.Directory { { Assert-PraStoredRecord $global:PraGate.AnchorBad320b } | Should -Throw '*invalid source anchor*' } + $global:PraGate.AnchorBad320b.SourceAnchor.ObjectGuid = (Get-PraSourceAnchor -Record $plan.Record).Candidates[0] + $global:PraGate.AnchorBad320b | Add-Member -NotePropertyName SharedTrusteeAnchors -NotePropertyValue ([pscustomobject]@{ 'a@gate.invalid' = @('AAAA') }) -Force + InModuleScope PRA.Directory { { Assert-PraStoredRecord $global:PraGate.AnchorBad320b } | Should -Throw '*invalid trustee source anchor*' } + $global:PraGate.Remove('AnchorBad320b') + } + It 'the anchors of a trustee (user, member of a group) are remembered by UPN, ms-DS-ConsistencyGuid first, and go into the record of the shared mailbox' { + $runtime = New-GateRuntime -Name 'anchor-trustee-320b' -UserCount 2 + $context = Use-Directory320b $runtime + $trusteeGuid = [guid]'50000000-0000-0000-0000-000000000001'; $consistency = [byte[]](1..16) + $global:PraGate.Trustee320b = [pscustomobject]@{ objectClass = 'user'; sAMAccountName = 'trustee1'; userPrincipalName = 'Trustee1@gate.invalid'; DistinguishedName = 'CN=Trustee1,OU=Tests,DC=gate,DC=invalid'; ObjectGUID = $trusteeGuid; 'mS-DS-ConsistencyGuid' = $consistency } + $global:PraGate.TrusteeContext320b = $context + $upns = InModuleScope PRA.Directory { @(Expand-PraTrustee -Context $global:PraGate.TrusteeContext320b -Object $global:PraGate.Trustee320b) } + $upns | Should -BeExactly @('Trustee1@gate.invalid') + $stored = $context['_PraTrusteeAnchors']['trustee1@GATE.invalid'] + $stored | Should -BeExactly @(([Convert]::ToBase64String($consistency)), ([Convert]::ToBase64String($trusteeGuid.ToByteArray()))) -Because 'the lookup ignores the case of the UPN, the first anchor is the ms-DS-ConsistencyGuid' + $global:PraGate.Remove('Trustee320b'); $global:PraGate.Remove('TrusteeContext320b') + } + It 'ms-DS-ConsistencyGuid is asked for by name only when the schema has it, and that is read once; an unreadable schema is "no", never an error' { + $runtime = New-GateRuntime -Name 'anchor-schema-320b' -UserCount 2 + $context = Use-Directory320b $runtime + $global:PraGate.SchemaContext320b = $context; $global:PraGate.SchemaReads320b = 0 + $first = InModuleScope PRA.Directory { + Mock Get-ADRootDSE { $global:PraGate.SchemaReads320b++; [pscustomobject]@{ schemaNamingContext = 'CN=Schema,CN=Configuration,DC=gate,DC=invalid' } } + Mock Get-ADObject { @([pscustomobject]@{ DistinguishedName = 'CN=ms-DS-ConsistencyGuid,CN=Schema,CN=Configuration,DC=gate,DC=invalid' }) } + @((Test-PraConsistencyGuidSchema -Context $global:PraGate.SchemaContext320b), (Test-PraConsistencyGuidSchema -Context $global:PraGate.SchemaContext320b)) + } + $first | Should -BeExactly @($true, $true) + $global:PraGate.SchemaReads320b | Should -Be 1 + $second = New-GateContext $runtime -Mode Preview + $global:PraGate.SchemaContext320b = $second + $none = InModuleScope PRA.Directory { + Mock Get-ADRootDSE { [pscustomobject]@{ schemaNamingContext = 'CN=Schema,CN=Configuration,DC=gate,DC=invalid' } } + Mock Get-ADObject { throw 'SYNTHETIC: the schema is not readable.' } + Test-PraConsistencyGuidSchema -Context $global:PraGate.SchemaContext320b + } + $none | Should -BeFalse + $global:PraGate.Remove('SchemaContext320b'); $global:PraGate.Remove('SchemaReads320b') + } +} + +Describe 'Release 3.2.0 - the cloud account is the one synchronised from Active Directory, never found by UPN alone (production Cloud module, mocked Microsoft Graph and Exchange Online, no network)' -Tag 'Release320b' { + BeforeAll { + $global:PraGate.R7NetworkPath = Join-Path $global:PraGate.Root 'PraGateR7Network.psm1' + $networkSource = @' +if ($env:PRA_GATE_NONET -cne 'SYNTHETIC-NO-NETWORK') { throw 'Synthetic interlock absent.' } +function Get-EXOMailbox { [CmdletBinding()]param($Filter,$Properties,$ResultSize,[switch]$InactiveMailboxOnly) throw 'SYNTHETIC BLOCK: EXO mailbox' } +function Get-EXORecipient { [CmdletBinding()]param($UserPrincipalName,$Filter,$Properties,$ResultSize) throw 'SYNTHETIC BLOCK: EXO recipient' } +function Get-MgUser { [CmdletBinding()]param($UserId,$Filter,$Property) throw 'SYNTHETIC BLOCK: Graph user' } +function Get-MgUserLicenseDetail { [CmdletBinding()]param($UserId,[switch]$All) throw 'SYNTHETIC BLOCK: Graph licence' } +function Get-MgContext { [CmdletBinding()]param() [pscustomobject]@{TenantId='20000000-0000-0000-0000-000000000002';ContextScope='Process'} } +function Get-ConnectionInformation { [CmdletBinding()]param() [pscustomobject]@{TenantID='20000000-0000-0000-0000-000000000002';State='Connected';TokenStatus='Active';ConnectionId='30000000-0000-0000-0000-000000000003';ModuleName=$global:PraGate.R7NetworkPath} } +Export-ModuleMember -Function Get-EXOMailbox,Get-EXORecipient,Get-MgUser,Get-MgUserLicenseDetail,Get-MgContext,Get-ConnectionInformation +'@ + [IO.File]::WriteAllText($global:PraGate.R7NetworkPath, $networkSource, (New-Object Text.UTF8Encoding($true))) + Get-Module PRA.Cloud -All | Remove-Module -Force -ErrorAction SilentlyContinue + Import-Module $global:PraGate.R7NetworkPath -Global -Force + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Cloud.psm1') -Force -Global + function global:New-R7Anchor { param([string]$Guid) [Convert]::ToBase64String(([guid]$Guid).ToByteArray()) } + function global:New-R7Row { + param([string]$Upn = 'user1@gate.invalid', [string]$Guid = 'ab12cd34-0000-4000-8000-0000000000ef', [string]$Consistency = '', [switch]$Legacy, [switch]$NoGuid) + $record = [ordered]@{ ObjectGuid = $(if ($NoGuid) { '' } else { $Guid }); UserPrincipalName = $Upn; SamAccountName = $Upn.Split('@')[0]; IsShared = $false } + if (-not $Legacy -and -not $NoGuid) { $record.SourceAnchor = [ordered]@{ ObjectGuid = (New-R7Anchor $Guid); ConsistencyGuid = $Consistency } } + New-PraRow $global:PraGate.CloudContext ([pscustomobject]$record) + } + function global:New-R7Account { param([string]$Id, [string]$Upn, [string]$Immutable) [pscustomobject]@{ Id = $Id; UserPrincipalName = $Upn; OnPremisesImmutableId = $Immutable; OnPremisesSyncEnabled = [bool]$Immutable } } + } + BeforeEach { + $global:PraGate.Runtime = New-GateRuntime -Name 'identity-320b' + $context = New-GateContext $global:PraGate.Runtime -Mode Apply -Action Convert + $context.Phase = 'Cloud'; $context.Once = $false; $context.CheckScope = 'Both'; $context.IntervalMinutes = 0; $context.TimeoutMinutes = 5 + $context.Config.Cloud = @{ CheckMailbox = $true; CheckLicense = $false; MailboxCheckVia = 'Exo'; RequiredSkuPartNumber = ''; IdentityCheck = 'Anchor'; TenantId = '20000000-0000-0000-0000-000000000002' } + $context.Config.SharedMailbox.GrantFullAccess = $false + $context.LogFile = Join-Path $global:PraGate.Runtime.Root 'logs\identity-320b.log' + $global:PraGate.CloudContext = $context + $global:PraGate.R7Binding = @{ TenantId = '20000000-0000-0000-0000-000000000002'; ConnectionId = '30000000-0000-0000-0000-000000000003'; ModuleLocation = $global:PraGate.R7NetworkPath; ModulePath = $global:PraGate.R7NetworkPath } + $global:PraGate.R7Accounts = @(); $global:PraGate.R7GraphCalls = New-Object 'Collections.Generic.List[string]'; $global:PraGate.R7ExoCalls = 0; $global:PraGate.R7Mailbox = $null + } + AfterAll { + Remove-Item -LiteralPath 'Function:\New-R7Anchor', 'Function:\New-R7Row', 'Function:\New-R7Account' -ErrorAction SilentlyContinue + Remove-Module PRA.Cloud, PraGateR7Network -Force -ErrorAction SilentlyContinue + } + It 'identity case "": ' -ForEach @( + @{ Name = 'the account carries the objectGUID anchor'; Expect = 'Success'; Upn = 'user1@gate.invalid'; Guid = 'ab12cd34-0000-4000-8000-0000000000ef'; Consistency = ''; Imm = [Convert]::ToBase64String(([guid]'ab12cd34-0000-4000-8000-0000000000ef').ToByteArray()); Legacy = $false; Message = '' } + @{ Name = 'the account carries the ms-DS-ConsistencyGuid anchor, not the objectGUID one'; Expect = 'Success'; Upn = 'user1@gate.invalid'; Guid = 'ab12cd34-0000-4000-8000-0000000000ef'; Consistency = [Convert]::ToBase64String(([guid]'cd34ef56-0000-4000-8000-0000000000aa').ToByteArray()); Imm = [Convert]::ToBase64String(([guid]'cd34ef56-0000-4000-8000-0000000000aa').ToByteArray()); Legacy = $false; Message = '' } + @{ Name = 'the UPN is typed in other letter case than in Microsoft Entra ID'; Expect = 'Success'; Upn = 'USER1@GATE.INVALID'; Guid = 'ab12cd34-0000-4000-8000-0000000000ef'; Consistency = ''; Imm = [Convert]::ToBase64String(([guid]'ab12cd34-0000-4000-8000-0000000000ef').ToByteArray()); Legacy = $false; Message = '' } + @{ Name = 'a record of an older version (no anchor stored) whose objectGUID matches'; Expect = 'Success'; Upn = 'user1@gate.invalid'; Guid = 'ab12cd34-0000-4000-8000-0000000000ef'; Consistency = ''; Imm = [Convert]::ToBase64String(([guid]'ab12cd34-0000-4000-8000-0000000000ef').ToByteArray()); Legacy = $true; Message = '' } + @{ Name = 'the UPN is held by a cloud-only account'; Expect = 'Error'; Upn = 'user1@gate.invalid'; Guid = 'ab12cd34-0000-4000-8000-0000000000ef'; Consistency = ''; Imm = ''; Legacy = $false; Message = 'user1@gate\.invalid: the Microsoft Entra ID account with this UPN is not the account synchronised from this Active Directory object \(it is a cloud-only account\)\. Nothing was changed on it\. Give one of the two accounts another UPN' } + @{ Name = 'the UPN is held by an account synchronised from another object'; Expect = 'Error'; Upn = 'user1@gate.invalid'; Guid = 'ab12cd34-0000-4000-8000-0000000000ef'; Consistency = ''; Imm = [Convert]::ToBase64String(([guid]'11111111-0000-4000-8000-000000000001').ToByteArray()); Legacy = $false; Message = '\(it is synchronised from another Active Directory object\)' } + @{ Name = 'the anchor of the account differs only by letter case (it is a machine id, compared exactly)'; Expect = 'Error'; Upn = 'user1@gate.invalid'; Guid = 'ab12cd34-0000-4000-8000-0000000000ef'; Consistency = ''; Imm = ([Convert]::ToBase64String(([guid]'ab12cd34-0000-4000-8000-0000000000ef').ToByteArray())).ToLowerInvariant(); Legacy = $false; Message = 'synchronised from another Active Directory object' } + @{ Name = 'a record of an older version whose objectGUID does not match: the message says how to go on'; Expect = 'Error'; Upn = 'user1@gate.invalid'; Guid = 'ab12cd34-0000-4000-8000-0000000000ef'; Consistency = ''; Imm = [Convert]::ToBase64String(([guid]'11111111-0000-4000-8000-000000000001').ToByteArray()); Legacy = $true; Message = 'The record was written by an older version and holds only the objectGUID: .*set Cloud\.IdentityCheck = Off' } + ) { + $anchor = [Convert]::ToBase64String(([guid]$Guid).ToByteArray()) + if ($Name -match 'letter case \(it is a machine id') { $Imm | Should -Not -BeExactly $anchor } + $global:PraGate.R7Accounts = @(New-R7Account -Id 'aaaaaaaa-0000-0000-0000-000000000001' -Upn 'user1@gate.invalid' -Immutable $Imm) + $global:PraGate.R7Mailbox = [pscustomobject]@{ RecipientTypeDetails = 'UserMailbox'; EmailAddresses = [string[]]@('SMTP:user1@gate.invalid'); ExternalDirectoryObjectId = 'aaaaaaaa-0000-0000-0000-000000000001' } + $global:PraGate.CloudRow = New-R7Row -Upn $Upn -Guid $Guid -Consistency $Consistency -Legacy:$Legacy + InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { param($Context) $Context['_PraCloudSession'] = @{ Graph = $true; Exo = $true; Subprocess = $false; Binding = $global:PraGate.R7Binding } } + Mock Assert-PraGraphSession { } + Mock Close-PraCloudSession { } + Mock Start-Sleep { } + Mock Get-MgUser { + param($UserId, $Filter, $Property) + $global:PraGate.R7GraphCalls.Add($(if ($UserId) { 'upn:' + $UserId } else { 'anchor:' + $Filter })) + if ($UserId) { + $found = @($global:PraGate.R7Accounts | Where-Object { $_.UserPrincipalName -ieq $UserId }) + if (-not $found.Count) { throw [System.Net.Http.HttpRequestException]::new('Request_ResourceNotFound: Resource does not exist.', $null, [System.Net.HttpStatusCode]::NotFound) } + $found + } + elseif ($Filter -match "^onPremisesImmutableId eq '(.+)'$") { $wanted = $Matches[1]; @($global:PraGate.R7Accounts | Where-Object { $_.OnPremisesImmutableId -ceq $wanted }) } + } + Mock Get-EXOMailbox { $global:PraGate.R7ExoCalls++; $global:PraGate.R7Mailbox } + Invoke-PraCloudPhase $global:PraGate.CloudContext @($global:PraGate.CloudRow) 'Convert' + } + $row = $global:PraGate.CloudRow; $context = $global:PraGate.CloudContext + if ($Expect -eq 'Success') { + $context.Issues.Count | Should -Be 0 + $row.CloudStatus | Should -BeExactly 'Success' + $global:PraGate.R7ExoCalls | Should -BeGreaterThan 0 + $global:PraGate.R7GraphCalls.Count | Should -Be 1 -Because 'one read by UPN is enough when the account carries the anchor' + } + else { + $context.Issues.Count | Should -Be 1 + [string]$context.Issues[0].Message | Should -Match $Message + $row.CloudStatus | Should -BeExactly 'Error' + $row.RunError | Should -BeTrue -Because 'the object could not be confirmed: it is not "not in the expected state"' + $global:PraGate.R7ExoCalls | Should -Be 0 -Because 'the object is never acted on: Exchange Online is not even read' + } + } + It 'the synchronised account has another UPN in Microsoft Entra ID: an error with both UPNs, and nothing read in Exchange Online' { + $anchor = New-R7Anchor 'ab12cd34-0000-4000-8000-0000000000ef' + $global:PraGate.R7Accounts = @(New-R7Account -Id 'aaaaaaaa-0000-0000-0000-000000000001' -Upn 'renamed1@gate.invalid' -Immutable $anchor) + $global:PraGate.CloudRow = New-R7Row + InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { param($Context) $Context['_PraCloudSession'] = @{ Graph = $true; Exo = $true; Subprocess = $false; Binding = $global:PraGate.R7Binding } } + Mock Assert-PraGraphSession { } + Mock Close-PraCloudSession { } + Mock Start-Sleep { } + Mock Get-MgUser { + param($UserId, $Filter, $Property) + if ($UserId) { throw [System.Net.Http.HttpRequestException]::new('Request_ResourceNotFound: Resource does not exist.', $null, [System.Net.HttpStatusCode]::NotFound) } + $wanted = ([regex]::Match($Filter, "'(.+)'")).Groups[1].Value; @($global:PraGate.R7Accounts | Where-Object { $_.OnPremisesImmutableId -ceq $wanted }) + } + Mock Get-EXOMailbox { $global:PraGate.R7ExoCalls++ } + Invoke-PraCloudPhase $global:PraGate.CloudContext @($global:PraGate.CloudRow) 'Convert' + } + $context = $global:PraGate.CloudContext + $context.Issues.Count | Should -Be 1 + [string]$context.Issues[0].Message | Should -Match 'user1@gate\.invalid: the account synchronised from this Active Directory object is renamed1@gate\.invalid in Microsoft Entra ID, not user1@gate\.invalid\. Nothing was changed on it\. Make the UPN in Active Directory and in Microsoft Entra ID the same' + $global:PraGate.R7ExoCalls | Should -Be 0 + } + It 'an ambiguous answer is an error: two accounts for the UPN, or two accounts that carry the anchor' { + $anchor = New-R7Anchor 'ab12cd34-0000-4000-8000-0000000000ef' + $global:PraGate.R7Accounts = @((New-R7Account -Id 'aaaaaaaa-0000-0000-0000-000000000001' -Upn 'user1@gate.invalid' -Immutable $anchor), (New-R7Account -Id 'aaaaaaaa-0000-0000-0000-000000000002' -Upn 'user1@gate.invalid' -Immutable '')) + $global:PraGate.CloudRow = New-R7Row + InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { param($Context) $Context['_PraCloudSession'] = @{ Graph = $true; Exo = $true; Subprocess = $false; Binding = $global:PraGate.R7Binding } } + Mock Assert-PraGraphSession { } + Mock Close-PraCloudSession { } + Mock Start-Sleep { } + Mock Get-MgUser { param($UserId, $Filter, $Property) @($global:PraGate.R7Accounts) } + Mock Get-EXOMailbox { $global:PraGate.R7ExoCalls++ } + Invoke-PraCloudPhase $global:PraGate.CloudContext @($global:PraGate.CloudRow) 'Convert' + } + $context = $global:PraGate.CloudContext + [string]$context.Issues[0].Message | Should -Match 'user1@gate\.invalid: Microsoft Entra ID returned 2 accounts for this UPN, so the right one cannot be chosen\. Nothing was changed on it\. Remove the duplicate account' + $global:PraGate.R7ExoCalls | Should -Be 0 + $global:PraGate.CloudRow.CloudStatus | Should -BeExactly 'Error' + $global:PraGate.R7Accounts = @((New-R7Account -Id 'aaaaaaaa-0000-0000-0000-000000000001' -Upn 'old1@gate.invalid' -Immutable $anchor), (New-R7Account -Id 'aaaaaaaa-0000-0000-0000-000000000002' -Upn 'old2@gate.invalid' -Immutable $anchor)) + $global:PraGate.CloudContext.Issues.Clear() + $global:PraGate.CloudRow = New-R7Row + InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { param($Context) $Context['_PraCloudSession'] = @{ Graph = $true; Exo = $true; Subprocess = $false; Binding = $global:PraGate.R7Binding } } + Mock Assert-PraGraphSession { } + Mock Close-PraCloudSession { } + Mock Start-Sleep { } + Mock Get-MgUser { + param($UserId, $Filter, $Property) + if ($UserId) { throw [System.Net.Http.HttpRequestException]::new('Request_ResourceNotFound: Resource does not exist.', $null, [System.Net.HttpStatusCode]::NotFound) } + @($global:PraGate.R7Accounts) + } + Mock Get-EXOMailbox { $global:PraGate.R7ExoCalls++ } + Invoke-PraCloudPhase $global:PraGate.CloudContext @($global:PraGate.CloudRow) 'Convert' + } + [string]$global:PraGate.CloudContext.Issues[0].Message | Should -Match 'user1@gate\.invalid: Microsoft Entra ID has 2 accounts that carry the source anchor of this Active Directory object, so the right one cannot be chosen' + $global:PraGate.R7ExoCalls | Should -Be 0 + } + It 'an account that is not in Microsoft Entra ID yet is waited for (the sync has not run), never confirmed and never an identity error' { + $global:PraGate.CloudContext.Once = $true + $global:PraGate.CloudRow = New-R7Row + InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { param($Context) $Context['_PraCloudSession'] = @{ Graph = $true; Exo = $true; Subprocess = $false; Binding = $global:PraGate.R7Binding } } + Mock Assert-PraGraphSession { } + Mock Close-PraCloudSession { } + Mock Start-Sleep { } + Mock Get-MgUser { param($UserId, $Filter, $Property) if ($UserId) { throw [System.Net.Http.HttpRequestException]::new('Request_ResourceNotFound: Resource does not exist.', $null, [System.Net.HttpStatusCode]::NotFound) } } + Mock Get-EXOMailbox { $global:PraGate.R7ExoCalls++ } + Invoke-PraCloudPhase $global:PraGate.CloudContext @($global:PraGate.CloudRow) 'Convert' + } + $context = $global:PraGate.CloudContext + [string]$context.Issues[0].Message | Should -Match 'user1@gate\.invalid: not in the expected state: the account is not in Microsoft Entra ID yet \(the Entra Connect sync has not run\)\.' + Get-PraValue $global:PraGate.CloudRow 'RunError' $null | Should -BeNullOrEmpty -Because 'it is "not in the expected state", not an object that could not be read' + $global:PraGate.R7ExoCalls | Should -Be 0 + } + It 'the Exchange Online object found by UPN must be the confirmed account: another ExternalDirectoryObjectId stops the object (mailbox read)' { + $anchor = New-R7Anchor 'ab12cd34-0000-4000-8000-0000000000ef' + $global:PraGate.R7Accounts = @(New-R7Account -Id 'aaaaaaaa-0000-0000-0000-000000000001' -Upn 'user1@gate.invalid' -Immutable $anchor) + $global:PraGate.R7Mailbox = [pscustomobject]@{ RecipientTypeDetails = 'UserMailbox'; EmailAddresses = [string[]]@('SMTP:user1@gate.invalid'); ExternalDirectoryObjectId = 'bbbbbbbb-0000-0000-0000-000000000009' } + $global:PraGate.CloudRow = New-R7Row + $global:PraGate.CloudContext.Once = $true + InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { param($Context) $Context['_PraCloudSession'] = @{ Graph = $true; Exo = $true; Subprocess = $false; Binding = $global:PraGate.R7Binding } } + Mock Assert-PraGraphSession { } + Mock Close-PraCloudSession { } + Mock Start-Sleep { } + Mock Get-MgUser { param($UserId, $Filter, $Property) @($global:PraGate.R7Accounts | Where-Object { $_.UserPrincipalName -ieq $UserId }) } + Mock Get-EXOMailbox { param($Filter, $Properties, $ResultSize) $global:PraGate.R7ExoCalls++; $global:PraGate.R7Props = @($Properties); $global:PraGate.R7Mailbox } + Invoke-PraCloudPhase $global:PraGate.CloudContext @($global:PraGate.CloudRow) 'Convert' + } + $global:PraGate.R7Props | Should -Contain 'ExternalDirectoryObjectId' -Because 'the property is asked for' + $context = $global:PraGate.CloudContext + $context.Issues.Count | Should -Be 1 + [string]$context.Issues[0].Message | Should -Match 'The Exchange Online mailbox is not the Microsoft Entra ID account confirmed for this object: user1@gate\.invalid' + $global:PraGate.CloudRow.CloudStatus | Should -BeExactly 'Error' + } + It 'Cloud.IdentityCheck = Off finds accounts by UPN only, reads nothing in Microsoft Entra ID for the identity, and says so ONCE for the run' { + $global:PraGate.CloudContext.Config.Cloud.IdentityCheck = 'oFf' + $global:PraGate.R7Mailbox = [pscustomobject]@{ RecipientTypeDetails = 'UserMailbox'; EmailAddresses = [string[]]@('SMTP:x@gate.invalid'); ExternalDirectoryObjectId = 'aaaaaaaa-0000-0000-0000-000000000001' } + $global:PraGate.CloudRows = @((New-R7Row -Upn 'user1@gate.invalid'), (New-R7Row -Upn 'user2@gate.invalid' -Guid 'cd34ef56-0000-4000-8000-0000000000aa')) + InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { param($Context, $NeedGraph) $global:PraGate.R7NeedGraph = $NeedGraph; $Context['_PraCloudSession'] = @{ Graph = $true; Exo = $true; Subprocess = $false; Binding = $global:PraGate.R7Binding } } + Mock Close-PraCloudSession { } + Mock Start-Sleep { } + Mock Get-MgUser { $global:PraGate.R7GraphCalls.Add('called') } + Mock Get-EXOMailbox { $global:PraGate.R7ExoCalls++; $global:PraGate.R7Mailbox } + Invoke-PraCloudPhase $global:PraGate.CloudContext $global:PraGate.CloudRows 'Convert' + } + $context = $global:PraGate.CloudContext + $global:PraGate.R7GraphCalls.Count | Should -Be 0 + $global:PraGate.R7NeedGraph | Should -BeFalse -Because 'nothing else needs Microsoft Graph in this configuration' + $context.Issues.Count | Should -Be 0 + @($global:PraGate.CloudRows | Where-Object { $_.CloudStatus -ceq 'Success' }).Count | Should -Be 2 + $context.Warnings | Should -Be 0 -Because 'an explicit setting is a notice, not a warning' + @(Get-PraList $context 'Journey' | Where-Object { $_.Text -match 'Cloud\.IdentityCheck = Off: the Microsoft Entra ID accounts are found by UPN only' }).Count | Should -Be 1 + } + It 'a record without any Active Directory identity (a Check given a UPN) is found by UPN with ONE warning that says how to have it confirmed; a write is refused for it' { + $context = New-GateContext $global:PraGate.Runtime -Mode Preview -Action Check + $context.Phase = 'Cloud'; $context.Once = $true; $context.IntervalMinutes = 0; $context.TimeoutMinutes = 1 + $context.Config.Cloud = @{ CheckMailbox = $true; CheckLicense = $false; MailboxCheckVia = 'Exo'; RequiredSkuPartNumber = ''; IdentityCheck = 'Anchor'; TenantId = '20000000-0000-0000-0000-000000000002' } + $context.LogFile = Join-Path $global:PraGate.Runtime.Root 'logs\identity-noanchor-320b.log' + $global:PraGate.CloudContext = $context + $global:PraGate.R7Accounts = @(New-R7Account -Id 'aaaaaaaa-0000-0000-0000-000000000001' -Upn 'user1@gate.invalid' -Immutable 'anything') + $global:PraGate.R7Mailbox = [pscustomobject]@{ RecipientTypeDetails = 'UserMailbox'; EmailAddresses = [string[]]@('SMTP:user1@gate.invalid'); ExternalDirectoryObjectId = 'aaaaaaaa-0000-0000-0000-000000000001' } + $global:PraGate.CloudRow = New-R7Row -NoGuid + InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { param($Context) $Context['_PraCloudSession'] = @{ Graph = $true; Exo = $true; Subprocess = $false; Binding = $global:PraGate.R7Binding } } + Mock Assert-PraGraphSession { } + Mock Close-PraCloudSession { } + Mock Start-Sleep { } + Mock Get-MgUser { param($UserId, $Filter, $Property) @($global:PraGate.R7Accounts | Where-Object { $_.UserPrincipalName -ieq $UserId }) } + Mock Get-EXOMailbox { $global:PraGate.R7ExoCalls++; $global:PraGate.R7Mailbox } + Invoke-PraCloudPhase $global:PraGate.CloudContext @($global:PraGate.CloudRow) 'Convert' + } + $row = $global:PraGate.CloudRow + $context.Issues.Count | Should -Be 0 + $row.CloudStatus | Should -BeExactly 'Success' + $context.Warnings | Should -Be 1 + $row.Warnings | Should -Match 'user1@gate\.invalid: the Microsoft Entra ID account is found by its UPN only: this object has no Active Directory identity in the record \(the identity was given as a UPN\)\. Give its sAMAccountName or -Batch to have it confirmed\.' + $apply = New-GateContext $global:PraGate.Runtime -Mode Apply -Action Convert + $apply.Config.Cloud = $context.Config.Cloud; $apply.LogFile = $context.LogFile; $global:PraGate.ApplyContext = $apply; $global:PraGate.ApplyRow = New-PraRow $apply ([pscustomobject]@{ ObjectGuid = ''; UserPrincipalName = 'shared1@gate.invalid'; SamAccountName = 'shared1'; IsShared = $true }) + $outcome = InModuleScope PRA.Cloud { + Mock Get-MgUser { param($UserId, $Filter, $Property) @([pscustomobject]@{ Id = 'aaaaaaaa-0000-0000-0000-000000000003'; UserPrincipalName = $UserId; OnPremisesImmutableId = 'x' }) } + Mock Assert-PraGraphSession { } + $state = @{ Row = $global:PraGate.ApplyRow; Upn = 'shared1@gate.invalid'; Requests = @([pscustomobject]@{ Right = 'FullAccess'; Trustee = 'trustee1@gate.invalid' }); PlainText = '' } + Confirm-PraCloudIdentity -Context $global:PraGate.ApplyContext -State $state + } + $outcome | Should -BeExactly 'Failed' + [string]$apply.Issues[0].Message | Should -Match 'the Active Directory identity of this object is not in the record, so the Microsoft Entra ID account cannot be confirmed and no permission is granted' + } + It 'trustees: a cloud-only account, an account that carries another anchor and an ambiguous answer stop the object before any grant; a recorded anchor (ms-DS-ConsistencyGuid first) or a synchronised account of an older record passes' { + $trusteeGuid = 'ab12cd34-0000-4000-8000-000000000bbb' + $trusteeAnchor = New-R7Anchor $trusteeGuid; $trusteeConsistency = [Convert]::ToBase64String([byte[]](1..16)) + $global:PraGate.R7Accounts = @( + (New-R7Account -Id 'cccccccc-0000-0000-0000-000000000001' -Upn 'cloudonly@gate.invalid' -Immutable ''), + (New-R7Account -Id 'cccccccc-0000-0000-0000-000000000002' -Upn 'other@gate.invalid' -Immutable (New-R7Anchor '11111111-0000-4000-8000-000000000001')), + (New-R7Account -Id 'cccccccc-0000-0000-0000-000000000003' -Upn 'good@gate.invalid' -Immutable $trusteeConsistency), + (New-R7Account -Id 'cccccccc-0000-0000-0000-000000000004' -Upn 'older@gate.invalid' -Immutable 'any-synchronised-anchor'), + (New-R7Account -Id 'dddddddd-0000-0000-0000-000000000001' -Upn 'shared1@gate.invalid' -Immutable $trusteeAnchor)) + $record = [pscustomobject]@{ ObjectGuid = $trusteeGuid; UserPrincipalName = 'shared1@gate.invalid'; IsShared = $true + SourceAnchor = [pscustomobject]@{ ObjectGuid = $trusteeAnchor; ConsistencyGuid = '' } + SharedTrusteeAnchors = [pscustomobject]@{ 'good@gate.invalid' = @($trusteeConsistency, (New-R7Anchor '22222222-0000-4000-8000-000000000002')); 'cloudonly@gate.invalid' = @($trusteeAnchor); 'other@gate.invalid' = @($trusteeAnchor) } } + $global:PraGate.R7Record = $record; $global:PraGate.R7Cases = @( + @{ Trustee = 'cloudonly@gate.invalid'; Outcome = 'Failed'; Message = 'Permissions on shared1@gate\.invalid are not granted\. cloudonly@gate\.invalid: the Microsoft Entra ID account with this UPN is not the account synchronised from this Active Directory object \(it is a cloud-only account\)' } + @{ Trustee = 'other@gate.invalid'; Outcome = 'Failed'; Message = 'other@gate\.invalid: .*\(it is synchronised from another Active Directory object\)' } + @{ Trustee = 'GOOD@gate.invalid'; Outcome = 'Ok'; Message = '' } + @{ Trustee = 'older@gate.invalid'; Outcome = 'Ok'; Message = '' } + @{ Trustee = 'unknown@gate.invalid'; Outcome = 'Ok'; Message = '' }) + InModuleScope PRA.Cloud { + Mock Get-MgUser { + param($UserId, $Filter, $Property) + if ($UserId) { + $found = @($global:PraGate.R7Accounts | Where-Object { $_.UserPrincipalName -ieq $UserId }) + if (-not $found.Count) { throw [System.Net.Http.HttpRequestException]::new('Request_ResourceNotFound', $null, [System.Net.HttpStatusCode]::NotFound) } + $found + } + else { @() } + } + Mock Assert-PraGraphSession { } + Mock Start-Sleep { } + foreach ($case in $global:PraGate.R7Cases) { + $context = New-GateContext $global:PraGate.Runtime -Mode Apply -Action Convert + $context.Config.Cloud = @{ IdentityCheck = 'Anchor' } + $context['_PraCloudSession'] = @{ Graph = $true } + $row = [pscustomobject]@{ ObjectGuid = ''; UserPrincipalName = 'shared1@gate.invalid'; CloudStatus = 'Pending'; FinalStatus = 'Pending'; CloudDetail = ''; Detail = ''; BackupRec = $global:PraGate.R7Record } + $state = @{ Row = $row; Upn = 'shared1@gate.invalid'; Requests = @([pscustomobject]@{ Right = 'FullAccess'; Trustee = $case.Trustee }); PlainText = '' } + $outcome = Confirm-PraCloudIdentity -Context $context -State $state + $outcome | Should -BeExactly $case.Outcome -Because $case.Trustee + if ($case.Outcome -ceq 'Failed') { [string]$context.Issues[0].Message | Should -Match $case.Message; $row.CloudStatus | Should -BeExactly 'Error' } + else { $context.Issues.Count | Should -Be 0 -Because $case.Trustee } + } + } + } + It 'the retention check confirms the account of an active mailbox before it reads the holds, and an inactive mailbox (no account) is read by UPN' { + $anchor = New-R7Anchor 'ab12cd34-0000-4000-8000-0000000000ef' + $context = New-GateContext $global:PraGate.Runtime -Mode Preview -Action Check + $context.Config.Cloud = @{ CheckMailbox = $true; CheckLicense = $false; MailboxCheckVia = 'Exo'; RequiredSkuPartNumber = ''; IdentityCheck = 'Anchor'; TenantId = '20000000-0000-0000-0000-000000000002' } + $context.Config.Retention = @{ Enabled = $true; PolicyGuid = '40000000-0000-0000-0000-000000000004'; PolicyName = ''; UseComplianceSession = $false } + $context.LogFile = Join-Path $global:PraGate.Runtime.Root 'logs\identity-retention-320b.log' + $global:PraGate.CloudContext = $context + $global:PraGate.R7Mailbox = [pscustomobject]@{ RecipientTypeDetails = 'UserMailbox'; EmailAddresses = [string[]]@('SMTP:user1@gate.invalid'); InPlaceHolds = @('mbx40000000000000000000000000000004'); IsInactiveMailbox = $false } + foreach ($case in @(@{ Imm = ''; Expect = 'Error' }, @{ Imm = $anchor; Expect = 'Success' }, @{ Imm = 'none'; Expect = 'Success' })) { + $global:PraGate.R7ExoCalls = 0 + $global:PraGate.R7Accounts = @(if ($case.Imm -cne 'none') { New-R7Account -Id 'aaaaaaaa-0000-0000-0000-000000000001' -Upn 'user1@gate.invalid' -Immutable $case.Imm }) + $global:PraGate.CloudContext.Issues.Clear() + $global:PraGate.CloudRow = New-R7Row + InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { param($Context) $Context['_PraCloudSession'] = @{ Graph = $true; Exo = $true; Subprocess = $false; Binding = $global:PraGate.R7Binding } } + Mock Assert-PraGraphSession { } + Mock Close-PraCloudSession { } + Mock Start-Sleep { } + Mock Get-MgUser { + param($UserId, $Filter, $Property) + if (-not $UserId) { return @() } + $found = @($global:PraGate.R7Accounts | Where-Object { $_.UserPrincipalName -ieq $UserId }) + if (-not $found.Count) { throw [System.Net.Http.HttpRequestException]::new('Request_ResourceNotFound', $null, [System.Net.HttpStatusCode]::NotFound) } + $found + } + Mock Get-EXOMailbox { $global:PraGate.R7ExoCalls++; $global:PraGate.R7Mailbox } + Invoke-PraRetentionCheck $global:PraGate.CloudContext @($global:PraGate.CloudRow) + } + if ($case.Expect -ceq 'Error') { $global:PraGate.CloudRow.CloudStatus | Should -BeExactly 'Error'; $global:PraGate.R7ExoCalls | Should -Be 0 -Because 'the holds of another account are never read' } + else { $global:PraGate.CloudRow.CloudStatus | Should -BeExactly 'Success' -Because ($case.Imm + ' ' + (@($global:PraGate.CloudContext.Issues | ForEach-Object Message) -join ';')); $global:PraGate.R7ExoCalls | Should -BeGreaterThan 0 } + } + } + It 'Exchange Online is told which account was confirmed: the recipient read (Preflight, Permission, Grant) and the SendOnBehalf mailbox read refuse another ExternalDirectoryObjectId (worker, mocked cmdlets)' { + $global:PraGate.R7Worker = @{ Binding = $global:PraGate.R7Binding } + $result = InModuleScope PRA.Cloud { + Mock Get-EXORecipient { [pscustomobject]@{ RecipientTypeDetails = 'UserMailbox'; PrimarySmtpAddress = 'user1@gate.invalid'; ExternalDirectoryObjectId = 'bbbbbbbb-0000-0000-0000-000000000009'; Guid = [guid]::NewGuid(); DistinguishedName = 'CN=user1' } } + $verified = @{ 'user1@gate.invalid' = 'aaaaaaaa-0000-0000-0000-000000000001' } + $answers = @{} + foreach ($operation in 'Recipient', 'Preflight') { + try { $null = & $script:PraExoWorker $operation @{ Upn = 'USER1@gate.invalid'; VerifiedObjectIds = $verified; Requests = @() } $null $global:PraGate.R7Worker.Binding $null $null; $answers[$operation] = 'accepted' } + catch { $answers[$operation] = $_.Exception.Message } + } + $verified = @{ 'user1@gate.invalid' = 'BBBBBBBB-0000-0000-0000-000000000009' } + try { $null = & $script:PraExoWorker 'Recipient' @{ Upn = 'user1@gate.invalid'; VerifiedObjectIds = $verified } $null $global:PraGate.R7Worker.Binding $null $null; $answers.Same = 'accepted' } catch { $answers.Same = $_.Exception.Message } + $answers + } + $result.Recipient | Should -Match 'The Exchange Online recipient is not the Microsoft Entra ID account confirmed for this object: USER1@gate\.invalid' + $result.Preflight | Should -Match 'The Exchange Online recipient is not the Microsoft Entra ID account confirmed for this object' + $result.Same | Should -BeExactly 'accepted' -Because 'the object ids are GUIDs: their letter case never matters' + } +} + +Describe 'Release 3.2.0 - transient cloud failures are retried within a budget, and throttling backs off the whole run (production Cloud module, no network)' -Tag 'Release320b' { + BeforeAll { + Get-Module PRA.Cloud -All | Remove-Module -Force -ErrorAction SilentlyContinue + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Cloud.psm1') -Force -Global + function global:New-R8Failure { + param([int]$Status = 0, [int]$RetryAfter = 0, [string]$Text = '', [string]$Kind = 'Http') + $exception = switch ($Kind) { + 'Timeout' { [TimeoutException]::new('The operation has timed out.') } + 'Socket' { [System.Net.Http.HttpRequestException]::new('No connection could be made.', [System.Net.Sockets.SocketException]::new(10061)) } + 'Plain' { [InvalidOperationException]::new($Text) } + default { if ($Status) { [System.Net.Http.HttpRequestException]::new($(if ($Text) { $Text } else { "Response status code does not indicate success: $Status." }), $null, [System.Net.HttpStatusCode]$Status) } else { [System.Net.Http.HttpRequestException]::new($Text) } } + } + if ($RetryAfter) { + $response = [System.Net.Http.HttpResponseMessage]::new([System.Net.HttpStatusCode]$Status) + $response.Headers.RetryAfter = [System.Net.Http.Headers.RetryConditionHeaderValue]::new([TimeSpan]::FromSeconds($RetryAfter)) + Add-Member -InputObject $exception -NotePropertyName Response -NotePropertyValue $response + } + [Management.Automation.ErrorRecord]::new($exception, 'x', [Management.Automation.ErrorCategory]::NotSpecified, $null) + } + function global:New-R8Context { + param([int]$ObjectSeconds = 180, [int]$RunMinutes = 30, [string]$Name = 'retry') + $runtime = New-GateRuntime -Name ($Name + '-320b') + $context = New-GateContext $runtime -Mode Apply -Action Convert + $context.Config.Cloud = @{ CheckMailbox = $true; CheckLicense = $false; MailboxCheckVia = 'Exo'; RequiredSkuPartNumber = ''; IdentityCheck = 'Off'; TenantId = '20000000-0000-0000-0000-000000000002'; RetryBudgetObjectSeconds = $ObjectSeconds; RetryBudgetRunMinutes = $RunMinutes } + $context.LogFile = Join-Path $runtime.Root ('logs\' + $Name + '.log') + $context.CurrentIdentity = 'object1' + $context + } + } + AfterAll { + Remove-Item -LiteralPath 'Function:\New-R8Failure', 'Function:\New-R8Context' -ErrorAction SilentlyContinue + Remove-Module PRA.Cloud -Force -ErrorAction SilentlyContinue + } + It 'Get-PraCloudFailureInfo reads the status, the Retry-After and the nature of a failure ()' -ForEach @( + @{ Name = '429 with a Retry-After header of 7 s'; Make = { New-R8Failure -Status 429 -RetryAfter 7 }; Status = 429; RetryAfter = 7; Transient = $true; Throttled = $true } + @{ Name = '429 with Retry-After in the text (Exchange Online child process)'; Make = { New-R8Failure -Kind Plain -Text 'Exchange Online child process code=1, stdout=[{"Error":"HttpStatusCode=429 TooManyRequests Retry-After: 9"}]' }; Status = 429; RetryAfter = 9; Transient = $true; Throttled = $true } + @{ Name = 'a Retry-After of 500 s is never waited more than two minutes'; Make = { New-R8Failure -Status 429 -RetryAfter 500 }; Status = 429; RetryAfter = 120; Transient = $true; Throttled = $true } + @{ Name = '503'; Make = { New-R8Failure -Status 503 }; Status = 503; RetryAfter = 0; Transient = $true; Throttled = $true } + @{ Name = '504'; Make = { New-R8Failure -Status 504 }; Status = 504; RetryAfter = 0; Transient = $true; Throttled = $false } + @{ Name = '502'; Make = { New-R8Failure -Status 502 }; Status = 502; RetryAfter = 0; Transient = $true; Throttled = $false } + @{ Name = '408'; Make = { New-R8Failure -Status 408 }; Status = 408; RetryAfter = 0; Transient = $true; Throttled = $false } + @{ Name = 'the name of the error only (ServiceUnavailable)'; Make = { New-R8Failure -Kind Plain -Text 'Microsoft Graph: ServiceUnavailable, the service is busy.' }; Status = 503; RetryAfter = 0; Transient = $true; Throttled = $true } + @{ Name = 'a timeout'; Make = { New-R8Failure -Kind Timeout }; Status = 0; RetryAfter = 0; Transient = $true; Throttled = $false } + @{ Name = 'a connection that does not answer'; Make = { New-R8Failure -Kind Socket }; Status = 0; RetryAfter = 0; Transient = $true; Throttled = $false } + @{ Name = '404 is permanent'; Make = { New-R8Failure -Status 404 }; Status = 404; RetryAfter = 0; Transient = $false; Throttled = $false } + @{ Name = '403 is permanent'; Make = { New-R8Failure -Status 403 }; Status = 403; RetryAfter = 0; Transient = $false; Throttled = $false } + @{ Name = '401 is permanent'; Make = { New-R8Failure -Status 401 }; Status = 401; RetryAfter = 0; Transient = $false; Throttled = $false } + @{ Name = '400 is permanent'; Make = { New-R8Failure -Status 400 }; Status = 400; RetryAfter = 0; Transient = $false; Throttled = $false } + @{ Name = '500 is not retried'; Make = { New-R8Failure -Status 500 }; Status = 500; RetryAfter = 0; Transient = $false; Throttled = $false } + @{ Name = 'any other error'; Make = { New-R8Failure -Kind Plain -Text 'SYNTHETIC: the answer is not valid.' }; Status = 0; RetryAfter = 0; Transient = $false; Throttled = $false } + ) { + $global:PraGate.R8Record = & $Make + $info = InModuleScope PRA.Cloud { Get-PraCloudFailureInfo $global:PraGate.R8Record } + $info.Status | Should -Be $Status + $info.RetryAfter | Should -Be $RetryAfter + $info.Transient | Should -Be $Transient + $info.Throttled | Should -Be $Throttled + } + It 'a 429 with Retry-After is waited as told and the read then succeeds: the waits are the Retry-After values, every retry is in the log at Detail level, nothing is an error' { + $global:PraGate.R8Context = New-R8Context -Name 'retry-after' + $global:PraGate.R8Sleeps = New-Object 'Collections.Generic.List[int]'; $global:PraGate.R8Calls = 0 + $answer = InModuleScope PRA.Cloud { + Mock Start-Sleep { param($Seconds) $global:PraGate.R8Sleeps.Add([int]$Seconds) } + $read = { $global:PraGate.R8Calls++; if ($global:PraGate.R8Calls -le 2) { throw (New-R8Failure -Status 429 -RetryAfter 7) }; 'the user' } + Invoke-PraCloudCall -Context $global:PraGate.R8Context -Call 'Microsoft Graph user' -Script $read + } + $answer | Should -BeExactly 'the user' + $global:PraGate.R8Calls | Should -Be 3 + @($global:PraGate.R8Sleeps) | Should -BeExactly @(7, 7) + $log = [IO.File]::ReadAllText($global:PraGate.R8Context.LogFile) + $log | Should -Match '\[DETAIL\] Retry 1 \| Microsoft Graph user \| object1 \| status 429 \(Retry-After 7 s\) \| waiting 7 s \| object 7 of 180 s, run 7 of 1800 s' + $log | Should -Match '\[DETAIL\] Retry 2 \| Microsoft Graph user \| object1 \| status 429 \(Retry-After 7 s\) \| waiting 7 s \| object 14 of 180 s, run 14 of 1800 s' + $global:PraGate.R8Context.Issues.Count | Should -Be 0 + $global:PraGate.R8Context.Warnings | Should -Be 0 + } + It 'without Retry-After the waits are 5, 10, 20 and 40 s, and the fifth failure ends the read with the error of the service (five tries at most)' { + $global:PraGate.R8Context = New-R8Context -ObjectSeconds 3600 -Name 'five-tries' + $global:PraGate.R8Sleeps = New-Object 'Collections.Generic.List[int]'; $global:PraGate.R8Calls = 0 + $message = InModuleScope PRA.Cloud { + Mock Start-Sleep { param($Seconds) $global:PraGate.R8Sleeps.Add([int]$Seconds) } + $read = { $global:PraGate.R8Calls++; throw (New-R8Failure -Status 504 -Text 'SYNTHETIC gateway timeout') } + try { Invoke-PraCloudCall -Context $global:PraGate.R8Context -Call 'Exchange Online Mailbox' -Script $read; 'no error' } catch { $_.Exception.Message } + } + $message | Should -BeExactly 'SYNTHETIC gateway timeout' + $global:PraGate.R8Calls | Should -Be 5 + @($global:PraGate.R8Sleeps) | Should -BeExactly @(5, 10, 20, 40) + } + It 'a permanent error is thrown at once and never retried: 404, 403, 400 and an error without status (one call, no wait); a write (-NoRetry) is never sent again either' { + foreach ($case in @(@{ Status = 404 }, @{ Status = 403 }, @{ Status = 400 }, @{ Status = 0 })) { + $global:PraGate.R8Context = New-R8Context -Name 'permanent' + $global:PraGate.R8Sleeps = New-Object 'Collections.Generic.List[int]'; $global:PraGate.R8Calls = 0; $global:PraGate.R8Status = $case.Status + $message = InModuleScope PRA.Cloud { + Mock Start-Sleep { param($Seconds) $global:PraGate.R8Sleeps.Add([int]$Seconds) } + $read = { $global:PraGate.R8Calls++; if ($global:PraGate.R8Status) { throw (New-R8Failure -Status $global:PraGate.R8Status -Text "SYNTHETIC refusal $($global:PraGate.R8Status)") } else { throw (New-R8Failure -Kind Plain -Text 'SYNTHETIC refusal 0') } } + try { Invoke-PraCloudCall -Context $global:PraGate.R8Context -Call 'Microsoft Graph user' -Script $read; 'no error' } catch { $_.Exception.Message } + } + $message | Should -BeExactly ('SYNTHETIC refusal ' + $case.Status) + $global:PraGate.R8Calls | Should -Be 1 -Because ([string]$case.Status) + $global:PraGate.R8Sleeps.Count | Should -Be 0 + } + $global:PraGate.R8Context = New-R8Context -Name 'nowrite'; $global:PraGate.R8Calls = 0 + InModuleScope PRA.Cloud { + Mock Start-Sleep { } + $write = { $global:PraGate.R8Calls++; throw (New-R8Failure -Status 429 -RetryAfter 3) } + try { Invoke-PraCloudCall -Context $global:PraGate.R8Context -Call 'Add permission' -Script $write -NoRetry } catch { $null = $_ } + } + $global:PraGate.R8Calls | Should -Be 1 + } + It 'the budget of an object is bounded: when the next wait would pass it, the read ends with the error of the service, and another object has its own budget' { + $global:PraGate.R8Context = New-R8Context -ObjectSeconds 10 -Name 'object-budget' + $global:PraGate.R8Sleeps = New-Object 'Collections.Generic.List[int]'; $global:PraGate.R8Calls = 0 + $messages = InModuleScope PRA.Cloud { + Mock Start-Sleep { param($Seconds) $global:PraGate.R8Sleeps.Add([int]$Seconds) } + $read = { $global:PraGate.R8Calls++; throw (New-R8Failure -Status 429 -RetryAfter 7 -Text 'SYNTHETIC throttled') } + $first = try { Invoke-PraCloudCall -Context $global:PraGate.R8Context -Call 'Microsoft Graph user' -Script $read; 'no error' } catch { $_.Exception.Message } + $global:PraGate.R8Context.CurrentIdentity = 'object2' + $second = try { Invoke-PraCloudCall -Context $global:PraGate.R8Context -Call 'Microsoft Graph user' -Script $read; 'no error' } catch { $_.Exception.Message } + @($first, $second) + } + $messages | Should -BeExactly @('SYNTHETIC throttled', 'SYNTHETIC throttled') + $global:PraGate.R8Calls | Should -Be 4 -Because 'two tries for each object: the second wait (7 + 7 s) would pass the 10 s of the object' + $log = [IO.File]::ReadAllText($global:PraGate.R8Context.LogFile) + $log | Should -Match 'Retry budget used up \| Microsoft Graph user \| object1 \| status 429 \| 2 tries \| object 7 of 10 s' + $log | Should -Match 'Retry budget used up \| Microsoft Graph user \| object2 \| status 429 \| 2 tries \| object 7 of 10 s' + } + It 'a retry budget of 0 means no retry: one call, the error of the service' { + foreach ($case in @(@{ Object = 0; Run = 30 }, @{ Object = 180; Run = 0 })) { + $global:PraGate.R8Context = New-R8Context -ObjectSeconds $case.Object -RunMinutes $case.Run -Name 'budget-zero'; $global:PraGate.R8Calls = 0 + $message = InModuleScope PRA.Cloud { + Mock Start-Sleep { throw 'no wait expected' } + $read = { $global:PraGate.R8Calls++; throw (New-R8Failure -Status 429 -RetryAfter 3 -Text 'SYNTHETIC throttled') } + try { Invoke-PraCloudCall -Context $global:PraGate.R8Context -Call 'Microsoft Graph user' -Script $read; 'no error' } catch { $_.Exception.Message } + } + $message | Should -BeExactly 'SYNTHETIC throttled' + $global:PraGate.R8Calls | Should -Be 1 + } + } + It 'the budget of the run is bounded: used up, ONE plain error stops the run, and the next calls are not even sent' { + $global:PraGate.R8Context = New-R8Context -ObjectSeconds 3600 -RunMinutes 1 -Name 'run-budget' + $global:PraGate.R8Sleeps = New-Object 'Collections.Generic.List[int]'; $global:PraGate.R8Calls = 0 + $result = InModuleScope PRA.Cloud { + Mock Start-Sleep { param($Seconds) $global:PraGate.R8Sleeps.Add([int]$Seconds) } + $read = { $global:PraGate.R8Calls++; throw (New-R8Failure -Status 429 -RetryAfter 30 -Text 'SYNTHETIC throttled') } + $first = try { Invoke-PraCloudCall -Context $global:PraGate.R8Context -Call 'Microsoft Graph user' -Script $read; $null } catch { $_.Exception } + $callsAfterFirst = $global:PraGate.R8Calls + $global:PraGate.R8Context.CurrentIdentity = 'object2' + $second = try { Invoke-PraCloudCall -Context $global:PraGate.R8Context -Call 'Microsoft Graph user' -Script $read; $null } catch { $_.Exception } + @{ First = $first; Second = $second; CallsAfterFirst = $callsAfterFirst; State = (Get-PraRetryState $global:PraGate.R8Context) } + } + $result.First.Message | Should -Match '^Microsoft 365 is limiting or not answering this run: the 1 minute\(s\) allowed for retries are used up \(2 retries, 3 throttled answers\)\. Nothing more is asked of Microsoft 365\. What this run already did is kept: run the same command again in a few minutes\.$' + $result.First.Data['PraRunBudget'] | Should -BeTrue + $result.CallsAfterFirst | Should -Be 3 + $global:PraGate.R8Calls | Should -Be 3 -Because 'the second object is refused before any call' + $result.Second.Message | Should -Match '^Microsoft 365 is limiting or not answering this run' + $result.State.RunExhausted | Should -BeTrue + $global:PraGate.R8Context.CloudThrottled | Should -BeTrue + @($global:PraGate.R8Sleeps) | Should -BeExactly @(30, 30) + } + It 'a throttled answer slows the calls of the whole run: the next calls pause 4, 2, 1 s (halved after each success) before they are sent, then no pause' { + $global:PraGate.R8Context = New-R8Context -ObjectSeconds 3600 -Name 'pace' + $global:PraGate.R8Sleeps = New-Object 'Collections.Generic.List[int]'; $global:PraGate.R8Calls = 0 + $log = InModuleScope PRA.Cloud { + Mock Start-Sleep { param($Seconds) $global:PraGate.R8Sleeps.Add([int]$Seconds) } + $flaky = { $global:PraGate.R8Calls++; if ($global:PraGate.R8Calls -le 3) { throw (New-R8Failure -Status 503) }; 'ok' } + $fine = { 'ok' } + $null = Invoke-PraCloudCall -Context $global:PraGate.R8Context -Call 'first' -Script $flaky + $global:PraGate.R8Sleeps.Add(-1) + foreach ($name in 'b', 'c', 'd', 'e') { $global:PraGate.R8Context.CurrentIdentity = $name; $null = Invoke-PraCloudCall -Context $global:PraGate.R8Context -Call ('call ' + $name) -Script $fine; $global:PraGate.R8Sleeps.Add(-1) } + [IO.File]::ReadAllText($global:PraGate.R8Context.LogFile) + } + (@($global:PraGate.R8Sleeps) -join ',') | Should -BeExactly '5,10,20,-1,4,-1,2,-1,1,-1,-1' -Because 'the retries of the first call, then one pause before each of the next calls while the pace is above 0' + $log | Should -Match 'Cloud calls slowed down after throttling: pausing 4 s before call b' + $log | Should -Match 'pausing 1 s before call d' + $log | Should -Not -Match 'pausing .* before call e' + } + It 'a batch of 5000 objects under permanent throttling does not become 5000 failures: the run stops after the budget, with a bounded number of calls' { + $global:PraGate.R8Context = New-R8Context -ObjectSeconds 180 -RunMinutes 10 -Name 'storm' + $global:PraGate.R8Calls = 0 + $global:PraGate.R8Sleeps = New-Object 'Collections.Generic.List[int]' + $summary = InModuleScope PRA.Cloud { + Mock Start-Sleep { param($Seconds) $global:PraGate.R8Sleeps.Add([int]$Seconds) } + $read = { $global:PraGate.R8Calls++; throw (New-R8Failure -Status 429 -Text 'SYNTHETIC throttled') } + $reached = 0; $failures = 0 + foreach ($index in 1..5000) { + $global:PraGate.R8Context.CurrentIdentity = 'object' + $index + try { $null = Invoke-PraCloudCall -Context $global:PraGate.R8Context -Call 'Microsoft Graph user' -Script $read } + catch { $failures++; if ((Get-PraRetryState $global:PraGate.R8Context).RunExhausted) { break } } + $reached++ + } + @{ Reached = $reached; Failures = $failures; State = (Get-PraRetryState $global:PraGate.R8Context) } + } + $summary.State.RunExhausted | Should -BeTrue + $summary.Reached | Should -BeLessThan 25 -Because 'the run stopped; it did not go through 5000 objects' + $global:PraGate.R8Calls | Should -BeLessThan 150 + $summary.State.RunSpent | Should -BeLessOrEqual 600 + ($global:PraGate.R8Sleeps | Measure-Object -Sum).Sum | Should -BeLessOrEqual 600 + } +} + +Describe 'Release 3.2.0 - a transient failure does not end the object in the cloud phase (production Cloud module, mocked Exchange Online, no network)' -Tag 'Release320b' { + BeforeAll { + $global:PraGate.R8NetworkPath = Join-Path $global:PraGate.Root 'PraGateR8Network.psm1' + $networkSource = @' +if ($env:PRA_GATE_NONET -cne 'SYNTHETIC-NO-NETWORK') { throw 'Synthetic interlock absent.' } +function Get-EXOMailbox { [CmdletBinding()]param($Filter,$Properties,$ResultSize,[switch]$InactiveMailboxOnly) throw 'SYNTHETIC BLOCK: EXO mailbox' } +function Get-ConnectionInformation { [CmdletBinding()]param() [pscustomobject]@{TenantID='20000000-0000-0000-0000-000000000002';State='Connected';TokenStatus='Active';ConnectionId='30000000-0000-0000-0000-000000000003';ModuleName=$global:PraGate.R8NetworkPath} } +Export-ModuleMember -Function Get-EXOMailbox,Get-ConnectionInformation +'@ + [IO.File]::WriteAllText($global:PraGate.R8NetworkPath, $networkSource, (New-Object Text.UTF8Encoding($true))) + Get-Module PRA.Cloud -All | Remove-Module -Force -ErrorAction SilentlyContinue + Import-Module $global:PraGate.R8NetworkPath -Global -Force + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Cloud.psm1') -Force -Global + function global:New-R8Failure2 { + param([int]$Status, [int]$RetryAfter = 0) + $exception = [System.Net.Http.HttpRequestException]::new("Response status code does not indicate success: $Status.", $null, [System.Net.HttpStatusCode]$Status) + if ($RetryAfter) { + $response = [System.Net.Http.HttpResponseMessage]::new([System.Net.HttpStatusCode]$Status) + $response.Headers.RetryAfter = [System.Net.Http.Headers.RetryConditionHeaderValue]::new([TimeSpan]::FromSeconds($RetryAfter)) + Add-Member -InputObject $exception -NotePropertyName Response -NotePropertyValue $response + } + $exception + } + } + BeforeEach { + $global:PraGate.Runtime = New-GateRuntime -Name 'phase-retry-320b' + $context = New-GateContext $global:PraGate.Runtime -Mode Apply -Action Convert + $context.Phase = 'Cloud'; $context.Once = $false; $context.CheckScope = 'Both'; $context.IntervalMinutes = 0; $context.TimeoutMinutes = 5 + $context.Config.Cloud = @{ CheckMailbox = $true; CheckLicense = $false; MailboxCheckVia = 'Exo'; RequiredSkuPartNumber = ''; IdentityCheck = 'Off'; TenantId = '20000000-0000-0000-0000-000000000002' } + $context.Config.SharedMailbox.GrantFullAccess = $false + $context.LogFile = Join-Path $global:PraGate.Runtime.Root 'logs\phase-retry-320b.log' + $global:PraGate.CloudContext = $context + $global:PraGate.R8Binding = @{ TenantId = '20000000-0000-0000-0000-000000000002'; ConnectionId = '30000000-0000-0000-0000-000000000003'; ModuleLocation = $global:PraGate.R8NetworkPath; ModulePath = $global:PraGate.R8NetworkPath } + $global:PraGate.R8Calls = 0; $global:PraGate.R8Sleeps = New-Object 'Collections.Generic.List[int]'; $global:PraGate.R8Failures = @{} + $global:PraGate.R8Mailbox = [pscustomobject]@{ RecipientTypeDetails = 'UserMailbox'; EmailAddresses = [string[]]@('SMTP:x@gate.invalid') } + $global:PraGate.CloudRows = @(1..3 | ForEach-Object { New-PraRow $context ([pscustomobject]@{ ObjectGuid = ('00000000-0000-0000-0000-00000000000' + $_); UserPrincipalName = "user$_@gate.invalid"; SamAccountName = "user$_"; IsShared = $false }) }) + } + AfterAll { + Remove-Item -LiteralPath 'Function:\New-R8Failure2' -ErrorAction SilentlyContinue + Remove-Module PRA.Cloud, PraGateR8Network -Force -ErrorAction SilentlyContinue + } + It 'a 429 and a 503 on the first read of two objects are retried inside the call: every object ends Success, no error, and the retries are in the log' { + $global:PraGate.R8Failures = @{ 'user1@gate.invalid' = @{ Status = 429; RetryAfter = 6; Times = 1 }; 'user3@gate.invalid' = @{ Status = 503; RetryAfter = 0; Times = 2 } } + InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { param($Context) $Context['_PraCloudSession'] = @{ Graph = $false; Exo = $true; Subprocess = $false; Binding = $global:PraGate.R8Binding } } + Mock Close-PraCloudSession { } + Mock Start-Sleep { param($Seconds, $Milliseconds) if ($Seconds) { $global:PraGate.R8Sleeps.Add([int]$Seconds) } } + Mock Get-EXOMailbox { + param($Filter, $Properties, $ResultSize) + $global:PraGate.R8Calls++ + $upn = ([regex]::Match($Filter, "'(.+)'")).Groups[1].Value + $plan = $global:PraGate.R8Failures[$upn] + if ($null -ne $plan -and $plan.Times -gt 0) { $plan.Times--; throw (New-R8Failure2 -Status $plan.Status -RetryAfter $plan.RetryAfter) } + $global:PraGate.R8Mailbox + } + Invoke-PraCloudPhase $global:PraGate.CloudContext $global:PraGate.CloudRows 'Convert' + } + $context = $global:PraGate.CloudContext + $context.Issues.Count | Should -Be 0 + @($global:PraGate.CloudRows | Where-Object { $_.CloudStatus -ceq 'Success' }).Count | Should -Be 3 + $global:PraGate.R8Calls | Should -Be 6 -Because 'three reads and three retries' + $log = [IO.File]::ReadAllText($context.LogFile) + $log | Should -Match '\[DETAIL\] Retry 1 \| Exchange Online Mailbox \| 00000000-0000-0000-0000-000000000001 \| status 429 \(Retry-After 6 s\) \| waiting 6 s' + $log | Should -Match '\[DETAIL\] Retry 2 \| Exchange Online Mailbox \| 00000000-0000-0000-0000-000000000003 \| status 503 \| waiting 10 s' + } + It 'the budget of an object used up in a wait that goes on: the object stays pending and is read again at the next check, and ends Success when the service answers again; it is not an error' { + $global:PraGate.CloudContext.Config.Cloud.RetryBudgetObjectSeconds = 12 + $global:PraGate.CloudRows = @($global:PraGate.CloudRows[0]) + $global:PraGate.R8Failures = @{ 'user1@gate.invalid' = @{ Status = 503; RetryAfter = 0; Times = 6 } } + InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { param($Context) $Context['_PraCloudSession'] = @{ Graph = $false; Exo = $true; Subprocess = $false; Binding = $global:PraGate.R8Binding } } + Mock Close-PraCloudSession { } + Mock Start-Sleep { param($Seconds, $Milliseconds) if ($Seconds) { $global:PraGate.R8Sleeps.Add([int]$Seconds) } } + Mock Get-EXOMailbox { + param($Filter, $Properties, $ResultSize) + $global:PraGate.R8Calls++ + $plan = $global:PraGate.R8Failures['user1@gate.invalid'] + if ($plan.Times -gt 0) { $plan.Times--; throw (New-R8Failure2 -Status $plan.Status) } + $global:PraGate.R8Mailbox + } + Invoke-PraCloudPhase $global:PraGate.CloudContext $global:PraGate.CloudRows 'Convert' + } + $context = $global:PraGate.CloudContext + $context.Issues.Count | Should -Be 0 + $global:PraGate.CloudRows[0].CloudStatus | Should -BeExactly 'Success' + $global:PraGate.CloudRows[0].FinalStatus | Should -BeExactly 'Success' + $global:PraGate.R8Calls | Should -Be 7 + $log = [IO.File]::ReadAllText($context.LogFile) + $log | Should -Match 'Retry budget used up' + $log | Should -Match 'user1@gate\.invalid \| cloud read failed, repeated at the next check' + } + It 'a look that cannot wait for the next check (-Once) ends the object at once, in plain words, as an object that could not be read (a run error), never "not in the expected state"' { + $global:PraGate.CloudContext.Once = $true + $global:PraGate.CloudContext.Config.Cloud.RetryBudgetObjectSeconds = 5 + $global:PraGate.CloudRows = @($global:PraGate.CloudRows[0]) + InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { param($Context) $Context['_PraCloudSession'] = @{ Graph = $false; Exo = $true; Subprocess = $false; Binding = $global:PraGate.R8Binding } } + Mock Close-PraCloudSession { } + Mock Start-Sleep { } + Mock Get-EXOMailbox { $global:PraGate.R8Calls++; throw (New-R8Failure2 -Status 429) } + Invoke-PraCloudPhase $global:PraGate.CloudContext $global:PraGate.CloudRows 'Convert' + } + $context = $global:PraGate.CloudContext + $context.Issues.Count | Should -Be 1 + [string]$context.Issues[0].Message | Should -BeExactly 'user1@gate.invalid: Microsoft 365 kept limiting the requests or was unavailable (HTTP 429) and the retry time of this object is used up. Run again in a few minutes.' + $global:PraGate.CloudRows[0].CloudStatus | Should -BeExactly 'Error' + $global:PraGate.CloudRows[0].RunError | Should -BeTrue + } + It 'a permanent refusal (403) is not retried and ends the object at once with its own message' { + $global:PraGate.CloudRows = @($global:PraGate.CloudRows[0]) + InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { param($Context) $Context['_PraCloudSession'] = @{ Graph = $false; Exo = $true; Subprocess = $false; Binding = $global:PraGate.R8Binding } } + Mock Close-PraCloudSession { } + Mock Start-Sleep { param($Seconds, $Milliseconds) if ($Seconds) { $global:PraGate.R8Sleeps.Add([int]$Seconds) } } + Mock Get-EXOMailbox { $global:PraGate.R8Calls++; throw (New-R8Failure2 -Status 403) } + Invoke-PraCloudPhase $global:PraGate.CloudContext $global:PraGate.CloudRows 'Convert' + } + $context = $global:PraGate.CloudContext + $global:PraGate.R8Calls | Should -Be 1 + $global:PraGate.R8Sleeps.Count | Should -Be 0 + $context.Issues.Count | Should -Be 1 + [string]$context.Issues[0].Message | Should -Be 'Response status code does not indicate success: 403.' + $global:PraGate.CloudRows[0].CloudStatus | Should -BeExactly 'Error' + } + It 'the retry time of the run used up in the cloud phase: ONE run error for the run (not one per object), the objects not finished stay Pending, nothing more is asked of Exchange Online' { + $global:PraGate.CloudContext.Config.Cloud.RetryBudgetRunMinutes = 1 + $global:PraGate.CloudContext.Config.Cloud.RetryBudgetObjectSeconds = 3600 + $global:PraGate.CloudRows = @(1..6 | ForEach-Object { New-PraRow $global:PraGate.CloudContext ([pscustomobject]@{ ObjectGuid = ('00000000-0000-0000-0000-00000000000' + $_); UserPrincipalName = "user$_@gate.invalid"; SamAccountName = "user$_"; IsShared = $false }) }) + InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { param($Context) $Context['_PraCloudSession'] = @{ Graph = $false; Exo = $true; Subprocess = $false; Binding = $global:PraGate.R8Binding } } + Mock Close-PraCloudSession { } + Mock Start-Sleep { param($Seconds, $Milliseconds) if ($Seconds) { $global:PraGate.R8Sleeps.Add([int]$Seconds) } } + Mock Get-EXOMailbox { $global:PraGate.R8Calls++; throw (New-R8Failure2 -Status 429 -RetryAfter 30) } + Invoke-PraCloudPhase $global:PraGate.CloudContext $global:PraGate.CloudRows 'Convert' + } + $context = $global:PraGate.CloudContext + $context.Issues.Count | Should -Be 1 -Because 'one error for the run' + [string]$context.Issues[0].Message | Should -Match '^Microsoft 365 is limiting or not answering this run: the 1 minute\(s\) allowed for retries are used up .* 6 object\(s\) were not finished\.$' + $context.CloudThrottled | Should -BeTrue + @($global:PraGate.CloudRows | Where-Object { $_.CloudStatus -ceq 'Error' }).Count | Should -Be 0 + @($global:PraGate.CloudRows | Where-Object { $_.FinalStatus -ceq 'Pending' }).Count | Should -Be 6 + $global:PraGate.R8Calls | Should -Be 3 -Because 'the first object tried three times; no other object was asked' + } +} + +Describe 'Release 3.2.0 - the run says that Microsoft 365 limited its requests, with the command to run again (real main, synthetic)' -Tag 'Release320b' { + It 'a Check whose retry time is used up: ONE error for the run, "limited the requests", nothing changed, the Check proposed again later' { + $runtime = New-GateRuntime -Name 'check-throttled-320b' -Case 'CloudThrottled' + $run = Invoke-GateProcess $runtime @{Action='Check';Identity='user1';ConfigPath=$runtime.ConfigPath} -TimeoutSeconds 120 + $run.ExitCode | Should -Be 1 -Because ($run.Output + $run.Error) + $run.Output | Should -Match ([regex]::Escape('Microsoft 365 is limiting or not answering this run: the 30 minute(s) allowed for retries are used up')) + $run.Output | Should -Match "Stopped at step 'Cloud' \(operation CloudCheck\): Microsoft 365 limited the requests of this run\. Nothing was changed\. Run the Check again\." + $steps = @($run.MainResult.NextSteps) + $steps[0] | Should -BeExactly 'Microsoft 365 limited the requests of this run. Nothing was changed: run the Check again in a few minutes:' + $steps[1] | Should -Match '^\.\\Invoke-PraRemoteMailbox\.ps1 -Action Check -Identity ''user1''' + $run.Output | Should -Not -Match 'did not answer' + @(Get-GateWrites $runtime).Count | Should -Be 0 + } +} + +Describe 'Release 3.2.0 - a partial batch whose proof cannot be used is rolled back from its journal; a Convert says its Exchange Online part (real main, production Directory module, synthetic AD)' -Tag 'Release320a' { + BeforeAll { + $global:PraGate.R3 = New-GateRuntime -Name 'partial-unusable-320a' -Case 'FailAtSam' -UserCount 10 -Extra @{ FailSam = 'user3' } + $runtime = $global:PraGate.R3 + $env:PRA_GATE_STATE = $runtime.StatePath; $env:PSModulePath = $runtime.Modules + ';' + (Join-Path $PSHOME 'Modules') + Remove-Module PRA.Directory -Force -ErrorAction SilentlyContinue + Get-Module ActiveDirectory -All | Remove-Module -Force -ErrorAction Stop + Import-Module (Join-Path $runtime.Modules 'ActiveDirectory\ActiveDirectory.psm1') -Force -Global + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Directory.psm1') -Force -Global + $context = New-GateContext $runtime + $global:PraGate.R3Plans = @(foreach ($sam in 'user1', 'user10', 'user2', 'user3', 'user4', 'user5', 'user6', 'user7', 'user8', 'user9') { New-PraPlan $context $sam 'Convert' }) + try { $null = Invoke-PraAdBatch $context $global:PraGate.R3Plans 'Convert' } catch { $null = $_ } + $global:PraGateAd.Case = 'Normal' + [IO.File]::WriteAllText($runtime.StatePath, [Management.Automation.PSSerializer]::Serialize($global:PraGateAd, 35)) + $global:PraGate.R3Folder = Split-Path @(Get-ChildItem -LiteralPath $runtime.State.BackupFolder -Recurse -File -Filter 'Convert-*.json')[0].FullName -Parent + $global:PraGate.R3Json = @(Get-ChildItem -LiteralPath $global:PraGate.R3Folder -File -Filter 'Convert-*.json')[0].FullName + $global:PraGate.R3Id = ([IO.File]::ReadAllText($global:PraGate.R3Json) | ConvertFrom-Json -DateKind String).BatchId + } + AfterAll { foreach ($key in 'R3', 'R3Plans', 'R3Folder', 'R3Json', 'R3Id') { $global:PraGate.Remove($key) } } + It 'Recover of a partial batch whose State file has no .sha256 or was changed: a warning says the proof cannot be used, and the objects the journal shows as written (three verified, one stopped on) are taken, the six others are not' { + $short = $global:PraGate.R3Id.Substring(0, 8) + $state = Join-Path $global:PraGate.R3Folder ('State-' + $global:PraGate.R3Id + '.json') + foreach ($case in 'missing-sha256', 'tampered-state') { + if ($case -eq 'missing-sha256') { Move-Item -LiteralPath ($state + '.sha256') -Destination ($state + '.sha256.away') } + else { [IO.File]::WriteAllText($state, ([IO.File]::ReadAllText($state).Replace('"PlannedCount": 10', '"PlannedCount": 11')), (New-Object Text.UTF8Encoding($true))) } + try { + $run = Invoke-GateProcess $global:PraGate.R3 @{Action='Recover';Phase='AD';Mode='Preview';ConfigPath=$global:PraGate.R3.ConfigPath;Batch=$short} -TimeoutSeconds 120 + $run.ExitCode | Should -Be 0 -Because ($case + ': ' + $run.Output + $run.Error) + $run.Output | Should -Match ('The AD proof of batch ' + $short + ' is marked partial but cannot be used \(') -Because $case + $run.Output | Should -Match 'the journal of the batch decides which objects are rolled back' -Because $case + $run.MainResult.PlannedCount | Should -Be 4 -Because $case + $run.MainResult.SkippedCount | Should -Be 6 -Because $case + } + finally { + if ($case -eq 'missing-sha256') { Move-Item -LiteralPath ($state + '.sha256.away') -Destination ($state + '.sha256') } + else { [IO.File]::WriteAllText($state, ([IO.File]::ReadAllText($state).Replace('"PlannedCount": 11', '"PlannedCount": 10')), (New-Object Text.UTF8Encoding($true))) } + } + } + } + It 'no journal either: Recover refuses with the backup path, the Recover of a named object and the manual restore as next steps, writes nothing, and the named object is rolled back on its own' { + $short = $global:PraGate.R3Id.Substring(0, 8) + $state = Join-Path $global:PraGate.R3Folder ('State-' + $global:PraGate.R3Id + '.json') + $journal = Join-Path $global:PraGate.R3Folder ('Journal-' + $global:PraGate.R3Id + '.jsonl') + Move-Item -LiteralPath ($state + '.sha256') -Destination ($state + '.sha256.away'); Move-Item -LiteralPath $journal -Destination ($journal + '.away') + try { + $before = @(Get-GateWrites $global:PraGate.R3).Count + $run = Invoke-GateProcess $global:PraGate.R3 @{Action='Recover';Phase='AD';Mode='Apply';Force=$true;ConfigPath=$global:PraGate.R3.ConfigPath;Batch=$short} -TimeoutSeconds 120 + $run.ExitCode | Should -Be 1 -Because ($run.Output + $run.Error) + $run.Output | Should -Match ('Recover of batch ' + $short + ' cannot go on: its AD proof is partial but unusable \(.*\) and its journal lists no object that was written\. Nothing was changed\.') + @(Get-GateWrites $global:PraGate.R3).Count | Should -Be $before + $steps = @($run.MainResult.NextSteps); $joined = $steps -join "`n" + $joined | Should -Match ([regex]::Escape($global:PraGate.R3Json)) + $joined | Should -Match ('-Action Recover .*-Batch ' + $short + '.*-Identity ''user1''') + $joined | Should -Match 'restore the attributes of the objects from that backup file by hand' + $one = Invoke-GateProcess $global:PraGate.R3 @{Action='Recover';Phase='AD';Mode='Preview';ConfigPath=$global:PraGate.R3.ConfigPath;Batch=$short;Identity='USER1'} -TimeoutSeconds 120 + $one.ExitCode | Should -Be 0 -Because ($one.Output + $one.Error) + $one.MainResult.PlannedCount | Should -Be 1 + $one.Output | Should -Match 'is marked partial but cannot be used' + } + finally { Move-Item -LiteralPath ($state + '.sha256.away') -Destination ($state + '.sha256'); Move-Item -LiteralPath ($journal + '.away') -Destination $journal } + } + It 'with the proof unusable and the journal present, the Apply rolls back the objects the journal names and leaves the others alone' { + $short = $global:PraGate.R3Id.Substring(0, 8) + $state = Join-Path $global:PraGate.R3Folder ('State-' + $global:PraGate.R3Id + '.json') + Move-Item -LiteralPath ($state + '.sha256') -Destination ($state + '.sha256.away') + try { + $before = @(Get-GateWrites $global:PraGate.R3 | Where-Object Operation -eq 'Set-ADUser').Count + $run = Invoke-GateProcess $global:PraGate.R3 @{Action='Recover';Phase='AD';Mode='Apply';Force=$true;ConfigPath=$global:PraGate.R3.ConfigPath;Batch=$short} -TimeoutSeconds 120 + $run.ExitCode | Should -Be 2 -Because ($run.Output + $run.Error) + $run.MainResult.ErrorCount | Should -Be 0 + (@(Get-GateWrites $global:PraGate.R3 | Where-Object Operation -eq 'Set-ADUser').Count - $before) | Should -Be 3 + $run.MainResult.SkippedCount | Should -Be 6 + } + finally { Move-Item -LiteralPath ($state + '.sha256.away') -Destination ($state + '.sha256') } + } + It 'the line of a verified object says the Exchange Online part (mailbox, licence, permissions) for a Convert, and keeps the deprovisioning check for a Recover or a Deprovision' { + $context = New-GateContext $global:PraGate.R3 -Mode Apply -Action Convert + $context.Journey = New-Object 'Collections.Generic.List[object]' + $plan = New-PraPlan $context 'user5' 'Convert' + $plan.Row.ADVerified = $true; $plan.Row.FinalStatus = 'Pending' + $texts = @{} + foreach ($operation in 'Convert', 'Recover', 'Deprovision') { + $plan.Operation = $operation + $context.Journey.Clear() + & (Get-Module PRA.Directory) { param($c, $p) Write-PraAdDelta -Context $c -Plan $p -Stage Verified } $context $plan 6>$null + $texts[$operation] = (@(Get-PraList $context 'Journey' | ForEach-Object { [string]$_.Text }) -join ' | ') + } + $texts['Convert'] | Should -Match 'AD verified, .* next: Exchange Online part \(mailbox, licence, permissions\)$' + $texts['Convert'] | Should -Not -Match 'deprovisioning' + $texts['Recover'] | Should -Match 'next: Exchange Online deprovisioning check$' + $texts['Deprovision'] | Should -Match 'next: Exchange Online deprovisioning check$' + } +} + +Describe 'Release 3.2.0 - the CSV of the objects left matches GUIDs in any form, and never drops a line without saying so (real main, synthetic AD)' -Tag 'Release320a' { + It 'GUIDs with braces, without dashes and in capitals match; a line that names no object of the batch (GATE\user8) is kept with a warning; the lines of converted objects are left out and counted' { + $runtime = New-GateRuntime -Name 'csv-guid-320a' -Case 'FailAtSam' -UserCount 10 -Extra @{ FailSam = 'user3' } + $guid = { param($n) '00000000-0000-0000-0000-{0:000000000000}' -f $n } + $identity = @{ 1 = ('{' + (& $guid 1).ToUpperInvariant() + '}'); 2 = 'user2'; 3 = 'user3'; 4 = (& $guid 4).Replace('-', '').ToUpperInvariant(); 5 = ('{' + (& $guid 5) + '}'); 6 = (& $guid 6).ToUpperInvariant() + 7 = 'USER7'; 8 = 'GATE\user8'; 9 = 'user9@gate.invalid'; 10 = 'user10' } + $csv = Join-Path $runtime.Root 'forms.csv' + [IO.File]::WriteAllText($csv, ("Identity,Note`r`n" + ((1..10 | ForEach-Object { $identity[$_] + ',note ' + $_ }) -join "`r`n") + "`r`n"), (New-Object Text.UTF8Encoding($true))) + $run = Invoke-GateProcess $runtime @{Action='Convert';Phase='AD';Mode='Apply';Force=$true;CsvPath=$csv;ConfigPath=$runtime.ConfigPath} -TimeoutSeconds 120 + $run.ExitCode | Should -Be 1 -Because ($run.Output + $run.Error) + $joined = @($run.MainResult.NextSteps) -join "`n" + $left = [regex]::Match($joined, 'with the file (?

[^ ]+\.csv), which lists only them').Groups['p'].Value + Test-Path -LiteralPath $left | Should -BeTrue -Because $joined + $rows = @(Import-Csv -LiteralPath $left) + ($rows.Note -join ',') | Should -BeExactly 'note 4,note 5,note 6,note 7,note 8,note 9' -Because 'every object left has its line, whatever the form of its identity; the converted objects and the one stopped on have none' + ($rows.Identity -join '|') | Should -BeExactly ($identity[4] + '|' + $identity[5] + '|' + $identity[6] + '|USER7|GATE\user8|user9@gate.invalid') + $run.Output | Should -Match ([regex]::Escape('1 line(s) of the file ' + $csv + ' name no object of batch')) + $run.Output | Should -Match 'GATE\\user8\): they are kept in the new file, check them' + $run.Output | Should -Match ([regex]::Escape('4 line(s) of the file ' + $csv + ' name objects that batch')) + } +} From be0614fa3b524e6a01fad4f565d7ee3e943a51b2 Mon Sep 17 00:00:00 2001 From: Nicolas Fabert <195452170+Nico77600@users.noreply.github.com> Date: Tue, 17 Nov 2026 23:05:10 +0100 Subject: [PATCH 03/16] Lot B review fixes; scale to thousands of objects: incremental receipt checks, indexed lookups, console caches, raised limits, scale measurement tool --- package/Invoke-PraRemoteMailbox.ps1 | 60 +- package/PraRemoteMailbox.psd1 | 4 +- package/docs/PraRemoteMailbox-Guide.md | 26 +- package/module/PRA.Cloud.psm1 | 244 +++++++-- package/module/PRA.Common.psm1 | 52 +- package/module/PRA.Directory.psm1 | 372 ++++++++++--- package/module/PRA.Gui.psm1 | 202 +++++-- tests/PraRemoteMailbox.Gui.Tests.ps1 | 134 ++++- tests/PraRemoteMailbox.Tests.ps1 | 732 ++++++++++++++++++++++++- tools/Measure-PraScale.ps1 | 287 ++++++++++ 10 files changed, 1891 insertions(+), 222 deletions(-) create mode 100644 tools/Measure-PraScale.ps1 diff --git a/package/Invoke-PraRemoteMailbox.ps1 b/package/Invoke-PraRemoteMailbox.ps1 index 2852ad9..2c12f59 100644 --- a/package/Invoke-PraRemoteMailbox.ps1 +++ b/package/Invoke-PraRemoteMailbox.ps1 @@ -506,16 +506,15 @@ function Initialize-PraCloudAuthority { <# .SYNOPSIS Callbacks given to the cloud module. Before each Exchange Online write, AssertCloudAuthorization - re-reads the AD proof of the object; JournalMutation records the write in the batch journal. + checks the AD proof of the object (read in full once, then by its stamps) and the backup; JournalMutation records the write in the batch journal. #> # GetNewClosure captures local variables, not the $context of the script: copy it first. $capturedContext = $context $context.AssertCloudAuthorization = { param($Row) if (-not $capturedContext.AllowMutation -or $capturedContext.OperationFailed -or $capturedContext.Issues.Count -gt 0 -or $null -eq $capturedContext.Proof) { throw 'Cloud write refused: no authorisation or the run already has an error.' } - $proof = Import-PraProof $capturedContext $capturedContext.Proof.Path $capturedContext.Source $capturedContext.Action - if (@($proof.Data.Records | Where-Object { Test-PraOrdinalIgnoreCaseEqual $_.ObjectGuid $Row.ObjectGuid }).Count -ne 1) { throw 'Cloud write refused: the object is not in a verified AD phase.' } - Assert-PraReceipt $capturedContext $capturedContext.Source $Row.ObjectGuid + Assert-PraCloudProofObject -Context $capturedContext -ProofPath $capturedContext.Proof.Path -Source $capturedContext.Source -Operation $capturedContext.Action -ObjectGuid ([string]$Row.ObjectGuid) + Assert-PraReceipt $capturedContext $capturedContext.Source ([string]$Row.ObjectGuid) }.GetNewClosure() $context.JournalMutation = { param($Target, $Operation, $Status, $Detail) Write-PraJournal $capturedContext $Target $Operation $Status ([string]$Detail) }.GetNewClosure() } @@ -606,22 +605,27 @@ function Get-PraFinalizeInput { $records = @(Select-PraSourceRecord $context.Source); $seen = @{} $items = @($manifest.Items) if (-not $items.Count) { throw 'Finalize package is empty.' } + $proofIndex = Get-PraRecordIndex $context.Proof.Data.Records + $snapshotIndex = Get-PraRecordIndex $context.Proof.Receipt.Data.Records + $sourceIndex = Get-PraRecordIndex $context.Source.Data.Records foreach ($item in $items) { if ($item.CloudConfirmed -isnot [bool] -or -not $item.CloudConfirmed -or $item.DeprovisionConfirmed -isnot [bool] -or -not $item.DeprovisionConfirmed -or $item.RestoreShared -isnot [bool] -or $item.RestoreTag -isnot [bool] -or - -not (Test-PraOrdinalIn $item.ObjectGuid @($context.Proof.Data.Records.ObjectGuid) -IgnoreCase) -or $seen.ContainsKey($item.ObjectGuid)) { throw 'Finalize package: invalid object confirmation.' } - $proofEntry = @($context.Proof.Data.Records | Where-Object { Test-PraOrdinalIgnoreCaseEqual $_.ObjectGuid $item.ObjectGuid })[0] - $snapshotEntry = @($context.Proof.Receipt.Data.Records | Where-Object { Test-PraOrdinalIgnoreCaseEqual $_.ObjectGuid $item.ObjectGuid })[0] - $sourceEntry = @($context.Source.Data.Records | Where-Object { Test-PraOrdinalIgnoreCaseEqual $_.ObjectGuid $item.ObjectGuid })[0] + $null -eq (Find-PraRecord $proofIndex ([string]$item.ObjectGuid)) -or $seen.ContainsKey($item.ObjectGuid)) { throw 'Finalize package: invalid object confirmation.' } + $proofEntry = Find-PraRecord $proofIndex ([string]$item.ObjectGuid) + $snapshotEntry = Find-PraRecord $snapshotIndex ([string]$item.ObjectGuid) + $sourceEntry = Find-PraRecord $sourceIndex ([string]$item.ObjectGuid) if ($snapshotEntry.PreserveCloudMailbox -or ($item.RestoreShared -and (-not (Test-PraOrdinalEqual $proofEntry.Operation 'Deprovision') -or -not $sourceEntry.IsShared)) -or ($item.RestoreTag -and -not [bool](Get-PraValue (Get-PraValue $sourceEntry 'Retention' $null) 'Enabled' $false)) -or (-not $item.RestoreShared -and -not $item.RestoreTag)) { throw 'Finalize package does not match the AD operations it proves.' } $seen[$item.ObjectGuid] = $true } - if ($Identity -and @($records | Where-Object { Test-PraOrdinalIn $_.ObjectGuid @($items.ObjectGuid) -IgnoreCase }).Count -ne 1) { throw "Identity '$Identity' is not authorised by this Finalize package." } + $itemByGuid = New-Object 'Collections.Generic.Dictionary[string,object]' ([StringComparer]::OrdinalIgnoreCase) + foreach ($item in $items) { $itemByGuid[[string]$item.ObjectGuid] = $item } + $authorised = New-Object 'Collections.Generic.List[object]' + foreach ($record in $records) { if ($itemByGuid.ContainsKey([string]$record.ObjectGuid)) { $authorised.Add($record) } } + if ($Identity -and $authorised.Count -ne 1) { throw "Identity '$Identity' is not authorised by this Finalize package." } $context.BatchId = Get-PraShortId ((Split-Path (Split-Path $path -Parent) -Leaf) -replace '^Finalize-', '') - return @($records | Where-Object { Test-PraOrdinalIn $_.ObjectGuid @($items.ObjectGuid) -IgnoreCase } | ForEach-Object { - $recordGuid = $_.ObjectGuid - [pscustomobject]@{ Record = $_; Item = ($items | Where-Object { Test-PraOrdinalIgnoreCaseEqual $_.ObjectGuid $recordGuid }) } }) + return @($authorised | ForEach-Object { [pscustomobject]@{ Record = $_; Item = $itemByGuid[[string]$_.ObjectGuid] } }) } function Format-PraByteSize { @@ -818,7 +822,7 @@ function Assert-PraBatchNotRolledBack { function Get-PraBatchTouchedSet { <# The objects that the journal of the Convert batch in $context.Source shows as written or about to be written. #> $journal = Join-Path (Split-Path $context.Source.Path -Parent) ('Journal-' + [string]$context.Source.Data.BatchId + '.jsonl') - return , (Get-PraJournalTouchedObject -Path $journal) + return , (Get-PraJournalTouchedObject -Path $journal -Context $context) } function Get-PraPartialSourceProof { @@ -827,6 +831,7 @@ function Get-PraPartialSourceProof { $path = Join-Path (Split-Path $context.Source.Path -Parent) ('State-' + [string]$context.Source.Data.BatchId + '.json') if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { return $null } try { $raw = [IO.File]::ReadAllText($path) | ConvertFrom-PraJson } catch { return [pscustomobject]@{ Unusable = $true; Reason = 'the State file cannot be read' } } + if ($null -eq $raw -or $null -eq (Get-PraValue $raw 'Kind' $null)) { return [pscustomobject]@{ Unusable = $true; Reason = 'the State file is not an AD proof' } } if ((Get-PraValue $raw 'Partial' $false) -ne $true) { return $null } try { return (Import-PraProof $context $path $context.Source 'Convert') } catch { return [pscustomobject]@{ Unusable = $true; Reason = (([string]$_.Exception.Message -split '\r?\n')[0]).Trim() } } @@ -921,8 +926,9 @@ function Write-PraRemainingCsv { } else { $keep = @($names | ForEach-Object { [pscustomobject]@{ Identity = $_ } }); $columns = @('Identity') } $quote = { param($value) '"' + ([string]$value).Replace('"', '""') + '"' } - $lines = @(($columns | ForEach-Object { & $quote $_ }) -join $delimiter) - foreach ($row in $keep) { $lines += (($columns | ForEach-Object { & $quote (Get-PraValue $row $_ '') }) -join $delimiter) } + $lines = New-Object 'Collections.Generic.List[string]' + $lines.Add((($columns | ForEach-Object { & $quote $_ }) -join $delimiter)) + foreach ($row in $keep) { $lines.Add((($columns | ForEach-Object { & $quote (Get-PraValue $row $_ '') }) -join $delimiter)) } $path = Join-Path $folder ('ToConvert-{0}-{1}.csv' -f $Partial.ShortId, $context.RunId.Substring(0, 15)) Write-PraImmutableFile $path (($lines -join "`r`n") + "`r`n") return $path @@ -1230,12 +1236,13 @@ try { # The preflight runs before any object is marked: a refused run has touched nothing and must not show objects as done. Test-PraSyncAvailable if ($context.Proof.Partial) { $script:Touched = Get-PraBatchTouchedSet } + $provenIndex = Get-PraRecordIndex $context.Proof.Data.Records foreach ($record in @($context.Source.Data.Records)) { - $proven = @($context.Proof.Data.Records | Where-Object { Test-PraOrdinalIgnoreCaseEqual $_.ObjectGuid $record.ObjectGuid }) - if ($proven.Count -ne 1 -and -not ($context.Proof.Partial -and $proven.Count -eq 0)) { throw "Object not verified by the AD phase of this batch: $($record.SamAccountName). The batch cannot be finished from here. Nothing was changed." } + $provenCount = if ($null -eq (Find-PraRecord $provenIndex ([string]$record.ObjectGuid))) { 0 } elseif ($provenIndex.Duplicates.Contains([string]$record.ObjectGuid)) { 2 } else { 1 } + if ($provenCount -ne 1 -and -not ($context.Proof.Partial -and $provenCount -eq 0)) { throw "Object not verified by the AD phase of this batch: $($record.SamAccountName). The batch cannot be finished from here. Nothing was changed." } $row = New-PraRow $context $record $row.BackupPath = $context.Proof.Receipt.Path - if ($proven.Count -eq 0) { Set-PraUnprovenRow -Row $row -Record $record -Reason 'not converted by this batch (it stopped at its first error before this object)'; continue } + if ($provenCount -eq 0) { Set-PraUnprovenRow -Row $row -Record $record -Reason 'not converted by this batch (it stopped at its first error before this object)'; continue } $row.ADVerified = $true; $row.ADApplied = $true $row.FinalStatus = if ($context.AllowMutation) { 'Success' } else { 'Planned' } $row.Detail = 'AD changes made and verified by an earlier run of this batch; they are not changed again.' @@ -1494,6 +1501,8 @@ try { } $script:SourcePartial = ((Test-PraOrdinalIgnoreCaseEqual $Action 'Recover') -and $null -ne $context.Proof -and $null -ne (Get-PraPartialSourceProof)) if (($null -ne $context.Proof -and (Test-PraOrdinalIgnoreCaseEqual $Action 'Convert') -and $context.Proof.Partial) -or $script:SourcePartial) { $script:Touched = Get-PraBatchTouchedSet } + $verifiedIndex = if ($null -ne $context.Proof) { Get-PraRecordIndex $context.Proof.Data.Records } else { $null } + $plannedIndex = if ($null -ne $context.Proof) { Get-PraRecordIndex $context.Proof.Receipt.Data.Records } else { $null } foreach ($record in $records) { $row = New-PraRow $context $record $originalLicensing = Get-PraValue $record 'Licensing' $null @@ -1502,17 +1511,18 @@ try { $holders = Get-PraValue $record 'SharedPermissions' $null $row.SharedFullAccess = Get-PraValue $holders 'FullAccess' @(); $row.SharedSendAs = Get-PraValue $holders 'SendAs' @(); $row.SharedSendOnBehalf = Get-PraValue $holders 'SendOnBehalf' @() if ($null -ne $context.Proof) { - $verified = @($context.Proof.Data.Records | Where-Object { Test-PraOrdinalIgnoreCaseEqual $_.ObjectGuid $record.ObjectGuid }) - if ($verified.Count -eq 0 -and ($context.Proof.Partial -or $script:SourcePartial)) { + $verifiedRecord = Find-PraRecord $verifiedIndex ([string]$record.ObjectGuid) + $verifiedCount = if ($null -eq $verifiedRecord) { 0 } elseif ($verifiedIndex.Duplicates.Contains([string]$record.ObjectGuid)) { 2 } else { 1 } + if ($verifiedCount -eq 0 -and ($context.Proof.Partial -or $script:SourcePartial)) { # Partial batch: this object was not converted by it (or may be partly changed); the cloud part leaves it out. $row.BackupPath = $context.Proof.Receipt.Path Set-PraUnprovenRow -Row $row -Record $record -Reason 'not converted by this batch (it stopped at its first error before this object)' $row.CloudStatus = 'Skipped' continue } - if ($verified.Count -ne 1) { throw "Object not verified by the AD phase of this batch: $($record.SamAccountName)" } - $row.ADVerified = $true; $row.DeproPending = (Test-PraOrdinalEqual $verified[0].Operation 'Deprovision'); $row.BackupPath = $context.Proof.Receipt.Path - $provenPlan = @($context.Proof.Receipt.Data.Records | Where-Object { Test-PraOrdinalIgnoreCaseEqual $_.ObjectGuid $record.ObjectGuid })[0] + if ($verifiedCount -ne 1) { throw "Object not verified by the AD phase of this batch: $($record.SamAccountName)" } + $row.ADVerified = $true; $row.DeproPending = (Test-PraOrdinalEqual $verifiedRecord.Operation 'Deprovision'); $row.BackupPath = $context.Proof.Receipt.Path + $provenPlan = Find-PraRecord $plannedIndex ([string]$record.ObjectGuid) $row.PreserveCloudMailbox = [bool]$provenPlan.PreserveCloudMailbox; $row.PreserveLicense = [bool]$provenPlan.PreserveLicense } $context.Rows.Add($row) @@ -1627,7 +1637,9 @@ try { foreach ($row in $tagged | Where-Object PreserveCloudMailbox) { $row.FinalStatus = 'Pending'; $row.Detail += ' | Cloud mailbox kept on purpose: the retention tag stays.' } - $followup = @($cloudRows | Where-Object { -not $_.PreserveCloudMailbox -and ($_.DeproPending -or $tagged.Contains($_)) }) + $taggedSet = New-Object 'Collections.Generic.HashSet[object]' ([Collections.Generic.ReferenceEqualityComparer]::Instance) + foreach ($taggedRow in $tagged) { [void]$taggedSet.Add($taggedRow) } + $followup = @($cloudRows | Where-Object { -not $_.PreserveCloudMailbox -and ($_.DeproPending -or $taggedSet.Contains($_)) }) foreach ($row in $followup) { if (-not (Test-PraOrdinalEqual $row.CloudStatus 'Success') -or $row.DeprovisionConfirmed -ne $true -or $row.ADVerified -ne $true) { throw 'Cloud deprovisioning or AD proof not confirmed: restore and tag clean-up blocked.' } } if (-not $followup.Count) { Write-PraItem -Context $context -Status Skip -Text 'Nothing left to restore.' } elseif ((Test-PraOrdinalIgnoreCaseEqual $effectivePhase 'Cloud') -or $defer -or -not @(Get-Module -ListAvailable ActiveDirectory).Count) { diff --git a/package/PraRemoteMailbox.psd1 b/package/PraRemoteMailbox.psd1 index 950874c..82c6d38 100644 --- a/package/PraRemoteMailbox.psd1 +++ b/package/PraRemoteMailbox.psd1 @@ -33,11 +33,11 @@ # Configuration, paths and CSV (PRA.Common) 'Import-PraConfiguration', 'Test-PraScopeConfiguration', 'New-PraEffectiveConfiguration', 'Get-PraConfigurationDifference', 'Resolve-PraPath', 'Read-PraCsvText', 'Read-PraTargetCsv', 'Get-PraTargetOverride', 'Get-PraToolVersion', 'Get-PraCloudModuleReport', 'Get-PraValue', 'Get-PraList', # Ordinal helpers, JSON and native calls (PRA.Common) - 'Test-PraOrdinalEqual', 'Test-PraOrdinalIgnoreCaseEqual', 'Test-PraOrdinalIn', 'Test-PraOrdinalIgnoreCaseIn', 'Get-PraOrdinalSorted', 'Get-PraOrdinalUnique', 'ConvertTo-PraImmutableId', 'Get-PraSourceAnchor', 'Compare-PraX500Address', 'ConvertFrom-PraJson', 'Get-PraNativeProcessApi', 'Get-PraWin32ErrorText', 'Test-PraOwnEntryProcess', + 'Test-PraOrdinalEqual', 'Test-PraOrdinalIgnoreCaseEqual', 'Test-PraOrdinalIn', 'Test-PraOrdinalIgnoreCaseIn', 'Get-PraOrdinalSorted', 'Get-PraOrdinalUnique', 'New-PraRecordIndex', 'Get-PraRecordIndex', 'Find-PraRecord', 'ConvertTo-PraImmutableId', 'Get-PraSourceAnchor', 'Compare-PraX500Address', 'ConvertFrom-PraJson', 'Get-PraNativeProcessApi', 'Get-PraWin32ErrorText', 'Test-PraOwnEntryProcess', # Private folders, phase data and transfer package (PRA.Common) 'New-PraPrivateDirectorySecurity', 'Initialize-PraPrivateFolder', 'Register-PraObjectName', 'Register-PraObjectBackup', 'Save-PraPhaseData', 'Copy-PraPhaseData', 'Get-PraTransferPackageName', 'Get-PraTransferPackage', 'New-PraTransferPackage', 'Import-PraTransferPackage', # Active Directory, backup and proof (PRA.Directory) - 'Initialize-PraDirectory', 'Initialize-PraPermissionCache', 'Get-PraUser', 'Resolve-PraGroup', 'Get-PraGroupMember', 'Get-PraExpectedX500', 'Get-PraTarget', 'Find-PraRecoverOfBatch', 'Get-PraJournalTouchedObject', 'New-PraRow', 'New-PraPlan', 'Invoke-PraAdPreview', 'Invoke-PraAdBatch', 'Invoke-PraAdReplication', 'Invoke-PraSync', 'Test-PraSyncServer', 'Start-PraSyncProbe', 'Import-PraBackup', 'Import-PraProof', 'Assert-PraReceipt', 'Assert-PraFollowupState', 'Get-PraHash', 'Write-PraImmutableFile', 'New-PraPrivateDirectory', 'Write-PraJournal' + 'Initialize-PraDirectory', 'Initialize-PraPermissionCache', 'Get-PraUser', 'Resolve-PraGroup', 'Get-PraGroupMember', 'Get-PraExpectedX500', 'Get-PraTarget', 'Find-PraRecoverOfBatch', 'Get-PraJournalTouchedObject', 'New-PraRow', 'New-PraPlan', 'Invoke-PraAdPreview', 'Invoke-PraAdBatch', 'Invoke-PraAdReplication', 'Invoke-PraSync', 'Test-PraSyncServer', 'Start-PraSyncProbe', 'Import-PraBackup', 'Import-PraProof', 'Assert-PraReceipt', 'Assert-PraCloudProofObject', 'Assert-PraFollowupState', 'Get-PraHash', 'Write-PraImmutableFile', 'New-PraPrivateDirectory', 'Write-PraJournal' ) CmdletsToExport = @() VariablesToExport = @() diff --git a/package/docs/PraRemoteMailbox-Guide.md b/package/docs/PraRemoteMailbox-Guide.md index 1f30696..6b6ca4d 100644 --- a/package/docs/PraRemoteMailbox-Guide.md +++ b/package/docs/PraRemoteMailbox-Guide.md @@ -337,7 +337,7 @@ dsacls 'DC=contoso,DC=com' /G "${who}:CA;Replication synchronization" | **What it reads** | `Get-MgUser -UserId -Property id,userPrincipalName,onPremisesImmutableId,onPremisesSyncEnabled` (the account of each object and of each trustee, once per run; and `Get-MgUser -Filter "onPremisesImmutableId eq ''"` only when the UPN does not give the right account); `Get-MgUser -UserId -Property Id,UserPrincipalName` (pre-check); `Get-MgUser -Property assignedPlans, provisionedPlans, assignedLicenses`; `Get-MgUserLicenseDetail -UserId -All` | the same calls | | **Sign-in** | the admin who signs in needs a role that can read other users' licences: see *What the code cannot tell you* | `Connect-MgGraph -ClientId -CertificateThumbprint -TenantId ` (`:595`) | -The tool never writes anything through Microsoft Graph. It reads the account of every object, and of every trustee of a permission to grant, to confirm it ([chapter 3](#3-things-to-know)): that needs no other permission than `User.Read.All`, and it is skipped only with `Cloud.IdentityCheck = 'Off'`. The licence and the provisioning are read for **user** mailboxes only (a shared mailbox has no licence and is checked through Exchange Online), and only when `Cloud.CheckLicense` is `$true` (the default) or `Cloud.MailboxCheckVia = 'Graph'`. Every Graph read is sent again after a temporary failure, within the retry budgets of the configuration. +The tool never writes anything through Microsoft Graph. **Since 3.2.0 it reads Microsoft Graph for every object** (shared mailboxes and runs without a licence check included), and for every trustee of a permission to grant, to confirm the account ([chapter 3](#3-things-to-know)): `User.Read.All` must be consented (delegated: the signing-in administrator; application: admin consent on the app registration) for every run of the cloud part, and the read is skipped only with `Cloud.IdentityCheck = 'Off'`. A refusal by Graph (403, insufficient privileges) stops the object with a message that names `User.Read.All` and the `Off` alternative; in phase Both the pre-check stops before any AD write. The account is read by its UPN once, then by its confirmed id. The licence and the provisioning are read for **user** mailboxes only (a shared mailbox has no licence and is checked through Exchange Online), and only when `Cloud.CheckLicense` is `$true` (the default) or `Cloud.MailboxCheckVia = 'Graph'`. Every Graph read is sent again after a temporary failure, within the retry budgets of the configuration. #### Exchange Online @@ -886,7 +886,7 @@ for Convert (AD, then Cloud) as for Recover (AD, Cloud, then Finalize), whatever - **Older batches, folders copied by hand.** Without phase data (or with a file that fails its checksum, its schema or its Environment) the report is still written, and the missing side is listed as *not available (folder from an older version or copied manually)*; the verdicts then come from the sides that were carried. - **Privacy.** Names, statuses and messages only: no secret, no token. Every value is HTML-encoded; spreadsheet formulas are neutralised in the CSV; the files are private like the other reports and - backups. Above 2,000 objects the HTML opens the journey of the objects that are not simply *done*; the CSV lists all. + backups. Above 10,000 objects the HTML opens the journey of the objects that are not simply *done*; the CSV lists all. A phase keeps at most 10,000 errors and 10,000 warnings, 1,000,000 journey lines and 40 steps per object. - The `.sha256` next to a PhaseData file is an integrity check, not proof of origin: the protection against a changed file is the SHA-256 of every entry in `transfer.json`, verified at import; the report decides nothing from this data. - **A cloud part completed by a later run.** When the cloud part of a phase Both run failed (objects not ready in time) and `-Phase Cloud -Batch ` completed it, the verdict of the object follows the later run: the cloud error of the earlier run stays in its journey as an *Earlier run* line and does not make the object *failed*. - **Phase Both** uses the same layout (one phase). The per-phase HTML report also lists the run settings changed (the per-phase CSV keeps its 22 columns). @@ -966,7 +966,7 @@ The package is **verified completely before anything is written**: - the `.sha256` file is present and equals the SHA-256 of the ZIP; `transfer.json` is present once, well formed, of a known kind and of the **same `Environment` as the configuration**; - every entry is exactly `transfer.json` or `/`: a path, a separator other than that one, `..`, a drive, a rooted or UNC name, a control character, a trailing dot or space, a reserved device name, an unexpected or duplicated name is **refused** (zip-slip), and so is a manifest entry that is missing; -- declared sizes equal the real ones, and the totals are bounded (at most 2000 entries, 256 MB per entry, 512 MB in all): a compression bomb is refused before it is read; +- declared sizes equal the real ones, and the totals are bounded (at most 2000 entries, 2 GB per entry, 4 GB in all: room for a batch of 5,000 objects): a compression bomb is refused before it is read, with the message *the content is too large* or *an entry is too large*; - the SHA-256 of **every entry** is computed from the stream and compared to the manifest, **before the first byte is written**. Then each folder is extracted under `Storage.BackupFolder` with its original name, as a **private folder** (leaf-only ACL, like the backups). A folder that already exists with **identical** files is accepted @@ -977,6 +977,17 @@ the package replaces the copy of the folders, not the verifications. .\Invoke-PraRemoteMailbox.ps1 -Action Convert -Phase Cloud -Mode Apply -Batch 'PRA-PROD-Convert-490cc62e-for-Cloud.zip' ``` +### Batch size + +A batch of **5,000 objects** is supported. The checks that grew with the square of the batch (the backup fingerprint recomputed for every write, the searches of the whole batch for each object, the console reading every batch file at every refresh) are gone: what is done for one object costs the same in a batch of 50 and in a batch of 5,000. + +- The backup is written and read back in full once, with the SHA-256 of its files. Writing and reading the data-only CLIXML is the work that remains and it is linear: about 0.5 s per object measured on a loaded workstation with synthetic users of 45 attributes (an object of your directory with more attributes costs more). Plan on roughly 45 minutes for the backup of 5,000 objects, and the same again each time a server reads the batch for the first time (the cloud server, Finalize). +- Each write checks the fields of the backup, the record of the object and the length and last write time of the files; the complete check runs when the backup is read, after every 200 such checks and before the AD proof is written. The AD proof is read in full once per run by the cloud phase; each permission grant then costs a comparison of stamps. +- The Active Directory part, the Entra Connect wait and the Exchange Online wait are not made faster by this: the AD part reads and re-reads each object several times, and the licence group is read in full for each object. +- The console keeps what it read of each batch file while the file and its `.sha256` file are unchanged, so a refresh costs a listing of the folder. A reload after a new batch reads that batch only. +- The bounds that remain: a transfer package is refused above 2 GB for one entry and 4 GB in all (with the message *too large*); a phase keeps at most 40 steps per object, 1,000,000 journey lines, 10,000 errors and 10,000 warnings; the global report page shows the journey of every object up to 10,000 objects (the CSV lists all objects). +- `tools\Measure-PraScale.ps1` times these steps on synthetic data (no directory, no tenant, no network): `pwsh -File .\tools\Measure-PraScale.ps1 -Count 5000`. Run the heavy steps (`BackupSave`, `AdBatch`, `ProofImport`) with a smaller `-Count` first: they take hours at 5,000. + # Part IV · Maintain @@ -1000,7 +1011,7 @@ The run state is one hashtable, the **context** (`$context`), created by the ent 1. **Read everything, then write.** Every object of the batch is read and planned before the first write. 2. **Backup before the first write**, for the whole batch: typed JSON (what Recover restores), data-only CLIXML (every AD value), SHA-256, private folder, new files only, then **re-read and compared** with the plans. A failure at the 13th object stops before any write. -3. **Before each write**: no previous error, Apply mode, approval, backup unchanged, and the object **re-read**: same `uSNChanged`, same DN, same values as in the backup. After each write: re-read of the expected values. +3. **Before each write**: no previous error, Apply mode, approval, backup unchanged (for each write: the fields of the backup in memory, the record of the object, and the length and last write time of its three files; the complete check, every record and the SHA-256 of the files, runs when the backup is read, after every 200 such checks and before the proof is written), and the object **re-read**: same `uSNChanged`, same DN, same values as in the backup. After each write: re-read of the expected values. 4. **First error = stop**: no next object, no sync, no cloud write, no automatic rollback. The journal records `Started` before and `Applied` after every write. 5. **Proofs**: the State file lists the objects verified; the cloud phase, Finalize and the sync refuse a batch without a valid proof, and Finalize refuses an object changed since the proof. One change is accepted: the writeback of Entra Connect, when the `X500:` addresses of `proxyAddresses` are the only difference from the list of the proof and every other managed attribute is as the proof left it (the list of kept addresses is then computed again). 6. **A cloud error is never "absent"**: deprovisioning is confirmed only when Exchange Online returns no mailbox **and** a MailUser recipient. Only then are the shared mailboxes restored on-premises. @@ -1139,6 +1150,9 @@ After a change of the engine, repeat the campaign of [annex B](#annex-b--lab-tes | `: shared mailbox permission(s) not granted by the settings ... - to grant by hand: FullAccess ; ...` (warning, *done with warnings*) | the batch carries permissions that the settings in force do not grant: a batch written before 3.2.0 on a server whose configuration grants less, or a batch converted with settings that grant none | grant the listed permissions by hand (`Add-MailboxPermission`, `Add-RecipientPermission`, `Set-Mailbox -GrantSendOnBehalfTo`), or correct the settings and run the cloud phase again. Nothing else is wrong | | `The shared mailbox permission settings of this server differ from the ones of the batch (...)` (warning) | the cloud server has another `SharedMailbox` configuration than the server that converted | nothing to do: the batch values are used, and the warning names them | | `: the Microsoft Entra ID account with this UPN is not the account synchronised from this Active Directory object (it is a cloud-only account / it is synchronised from another Active Directory object)` | the UPN of the AD object belongs to another account in the cloud: Entra ID gave the synchronised object another UPN, or a cloud-only account had the UPN first | nothing was changed on it, and nothing was read in Exchange Online. Give one of the two accounts another UPN so that Entra Connect synchronises the object under its own UPN, or leave the object out, then run the same command again. A record written by an older version says so: if the tenant uses another source anchor, check the account by hand and set `Cloud.IdentityCheck = 'Off'` | +| `: the Microsoft Entra ID account with this UPN is synchronised, but its onPremisesImmutableId ...` | the account is synchronised but carries another anchor than the `objectGUID` or `ms-DS-ConsistencyGuid` of the record, or one that is not the base64 of a GUID: the tenant may use another source anchor (a mail or employee attribute, for example) | nothing was changed. Check by hand that the account is the one of the object, then set `Cloud.IdentityCheck = 'Off'` and run the same command again. Changing UPNs is not the answer here | +| `: Microsoft Graph refused to read the Microsoft Entra ID account that confirms this object (HTTP 403)` | the identity check needs `User.Read.All` and the sign-in does not have it | give `User.Read.All` (delegated: the administrator consents; application: add it and grant admin consent), or set `Cloud.IdentityCheck = 'Off'`; run the same command again. Nothing was changed | +| `: a shared mailbox permission could not be granted or verified (...)` | the grant step failed (for example a throttled answer after the Add): it is never repeated in the same run | run the cloud phase again later: it reads the permissions first and grants only what is missing | | `: the account synchronised from this Active Directory object is in Microsoft Entra ID, not ` | the account of the object has another UPN in the cloud | make the UPN in AD and in Entra ID the same, let Entra Connect synchronise, run the same command again | | `: Microsoft Entra ID returned 2 accounts for this UPN` / `... has 2 accounts that carry the source anchor of this Active Directory object` | duplicate accounts in Entra ID | remove the duplicate account, run the same command again | | `Permissions on are not granted. : the Microsoft Entra ID account ...` | a trustee of a permission is a cloud-only account or another account than the AD user | nothing was granted for this mailbox. Fix the UPN of the trustee account as for an object, then run the same command again | @@ -1305,7 +1319,7 @@ $app # -> Cloud.AppId 3.1.0 adds one optional field to each record of a Convert backup, `ExpectedX500` (the X500 addresses to verify in Exchange Online); a backup without it is read as before. -3.2.0 adds two optional fields to each record of a Convert backup: `SourceAnchor` (`ObjectGuid` and `ConsistencyGuid`: the base64 `onPremisesImmutableId` texts of the object, `ConsistencyGuid` empty when the object has no `ms-DS-ConsistencyGuid`) and `SharedTrusteeAnchors` (for a shared mailbox, the anchors of each trustee by UPN, `ms-DS-ConsistencyGuid` first). A backup, batch or transfer package without them is read as before: the anchor is then derived from the `ObjectGuid` of the record (trustees: no anchor, a synchronised account is required). +3.2.0 adds two optional fields to each record of a Convert backup: `SourceAnchor` (`ObjectGuid` and `ConsistencyGuid`: the base64 `onPremisesImmutableId` texts of the object, `ConsistencyGuid` empty when the object has no `ms-DS-ConsistencyGuid`) and `SharedTrusteeAnchors` (for a shared mailbox, the anchors of each trustee by UPN, `ms-DS-ConsistencyGuid` first). `SharedTrusteeAnchorsIncomplete` (a boolean) is `true` when the schema could not be read for the trustees: a trustee then only has to be a synchronised account. A backup, batch or transfer package without them is read as before: the anchor is then derived from the `ObjectGuid` of the record (trustees: no anchor, a synchronised account is required). An Apply that imports a transfer package also writes a small text file `Backups\Imported\.txt` (the package name and the time), outside the batch folder. The console reads it to tell a batch imported on this server from one converted here: only the second is offered "finish it here" (AD part first), and only on a server that can run the AD part. @@ -1331,6 +1345,8 @@ Every JSON has a `.sha256` file; a mismatch is refused. **Version 2.0.0 reads th - Release checklist: gate PASS · lab campaign ([annex B](#annex-b--lab-test-campaign-2026-09-30)) · `pwsh tools\New-DocumentationImages.ps1` (PowerShell 7.5+, Microsoft Edge, documentation only: every picture of the README and the guides, then the two HTML guides) · **owner signature and manifest (below)** · `tools\New-PraPackage.ps1` · git tag `vX.Y.Z`. - **Signature and manifest after a change.** Editing a signed or hashed file invalidates its signature or hash, and the package then refuses to start (by design). The owner (1) signs, with the timestamp, every PowerShell file of the inventory (`Invoke-PraRemoteMailbox.ps1`, `PraRemoteMailbox.psd1`, `PraRemoteMailbox.psm1`, `module\PRA.Common.psm1`, `PRA.Directory.psm1`, `PRA.Backup.psm1`, `PRA.Cloud.psm1`, `PRA.Gui.psm1`, `PRA.Gui.Directory.ps1`, `Test-PackageIntegrity.ps1`); (2) regenerates `PackageIntegrity.psd1` with the SHA256 of **every** inventory file taken from the final signed bytes (the hash of a signed script includes its signature block, so it cannot be computed before signing), then signs the manifest; (3) runs the gate and `tools\New-PraPackage.ps1`. The gate and the Pester suites also pass on an unsigned working tree (the native-state tests accept the fail-closed state); `tools\New-PraPackage.ps1` and the CI *Package* stage refuse an unsigned or changed source. +**From 3.1.x to 3.2.0.** The configuration file keeps working (three new optional settings under `Cloud`: `IdentityCheck`, `RetryBudgetObjectSeconds`, `RetryBudgetRunMinutes`). **3.2.0 reads Microsoft Graph for every object**, shared mailboxes and runs without a licence check included, to confirm the account of the object and of each trustee: the permission `User.Read.All` (delegated, with the consent of the signing-in administrator; or application, with admin consent) must therefore be in place for every run of the cloud part, not only for the licence checks. A refusal by Graph (403, insufficient privileges) stops the object with a message that names the permission. The alternative is `Cloud.IdentityCheck = 'Off'`, which finds the accounts by UPN only and reads nothing for this purpose (a tenant whose source anchor is neither the `objectGUID` nor `ms-DS-ConsistencyGuid` needs it). Batches and backups of 3.1.x are read as before. + **From 1.3.6**: keep the old `Backups` folders; copy the values of `DRP-Config.psd1` into the new file (same sections; `ADConnect` → `EntraConnect`; `BackupFolder/LogFolder/ReportFolder` → `Storage/Logging/Report`; `Safety` → `Storage.ForbiddenBackupRoots`); keep the same `Environment` to use the old batches. Command mapping: see `CHANGELOG.md` (table "Changed"). diff --git a/package/module/PRA.Cloud.psm1 b/package/module/PRA.Cloud.psm1 index 5434779..3814335 100644 --- a/package/module/PRA.Cloud.psm1 +++ b/package/module/PRA.Cloud.psm1 @@ -155,6 +155,13 @@ $script:PraExoWorker = { if ([string]::IsNullOrWhiteSpace($Upn) -or $Upn -match '[\r\n\x00]') { throw 'Empty or invalid UPN.' } return "UserPrincipalName -eq '$($Upn.Replace("'","''"))'" } + # The Exchange Online object of a confirmed account is looked up by the Entra id (its ExternalDirectoryObjectId); the UPN is the key only when no id is known. + function Confirmed { + param([string]$Upn) + $id=V (V $P 'VerifiedObjectIds' @{}) $Upn + if ($null -ne $id -and $id) { return [string]$id } + return '' + } function MissingRecipient { param([System.Management.Automation.ErrorRecord]$Record,[string]$Upn) # A selector read (-UserPrincipalName) answers an absent object with HTTP 404 ManagementObjectNotFoundException @@ -177,12 +184,15 @@ $script:PraExoWorker = { # Recipient exposes a dedicated UPN selector, not a UserPrincipalName output/filter property. # "Not found" is read through -ErrorVariable (no transcript error line); any other error stops. $recipientErrors=$null - try { $items = @(Get-EXORecipient -UserPrincipalName $Upn -Properties RecipientTypeDetails,PrimarySmtpAddress,ExternalDirectoryObjectId,Guid,DistinguishedName -ResultSize Unlimited -ErrorAction SilentlyContinue -ErrorVariable recipientErrors -WarningAction Stop) } - catch { if (-not (MissingRecipient $_ $Upn)) { throw }; $items=@(); $recipientErrors=@($_) } + $byId=Confirmed $Upn + $selector=if ($byId) { @{ Identity=$byId } } else { @{ UserPrincipalName=$Upn; ResultSize='Unlimited' } } + $missingKey=if ($byId) { $byId } else { $Upn } + try { $items = @(Get-EXORecipient @selector -Properties RecipientTypeDetails,PrimarySmtpAddress,ExternalDirectoryObjectId,Guid,DistinguishedName -ErrorAction SilentlyContinue -ErrorVariable recipientErrors -WarningAction Stop) } + catch { if (-not (MissingRecipient $_ $missingKey)) { throw }; $items=@(); $recipientErrors=@($_) } $recipientErrors=@($recipientErrors | Where-Object { $null -ne $_ }) if ($recipientErrors.Count) { foreach ($record in $recipientErrors) { - if ($record -isnot [System.Management.Automation.ErrorRecord] -or -not (MissingRecipient $record $Upn)) { throw $record } + if ($record -isnot [System.Management.Automation.ErrorRecord] -or -not (MissingRecipient $record $missingKey)) { throw $record } } if ($items.Count) { throw "Exchange Online returned a recipient and 'not found' for: $Upn" } return @{ Found=$false; Type=$null; Keys=@() } @@ -206,16 +216,33 @@ $script:PraExoWorker = { } function Mailbox { param([string]$Upn,[switch]$Hold) - $grantParameters = @{ Filter=(ExactFilter $Upn); Properties=@('RecipientTypeDetails','EmailAddresses','LegacyExchangeDN','ExternalDirectoryObjectId'); ResultSize='Unlimited' } - if ($Hold) { $grantParameters.Properties += @('IsInactiveMailbox','InPlaceHolds','LitigationHoldEnabled','RetentionHoldEnabled') } - $items = @(Get-EXOMailbox @grantParameters -ErrorAction Stop) - if ($Hold -and $items.Count -eq 0) { $items = @(Get-EXOMailbox @grantParameters -InactiveMailboxOnly -ErrorAction Stop) } + $properties = @('RecipientTypeDetails','EmailAddresses','LegacyExchangeDN','ExternalDirectoryObjectId') + if ($Hold) { $properties += @('IsInactiveMailbox','InPlaceHolds','LitigationHoldEnabled','RetentionHoldEnabled') } + $byId = Confirmed $Upn + if ($byId) { + try { $items = @(Get-EXOMailbox -Identity $byId -Properties $properties -ErrorAction Stop) } + catch { if ($_.Exception.Message -notmatch "(?i)couldn.t be found|HttpStatusCode=404|ManagementObjectNotFoundException") { throw }; $items = @() } + } + else { $items = @(Get-EXOMailbox -Filter (ExactFilter $Upn) -Properties $properties -ResultSize Unlimited -ErrorAction Stop) } + $inactiveByUpn = $false + if ($Hold -and $items.Count -eq 0) { + # The inactive mailbox of a deleted account has no account to confirm and another ExternalDirectoryObjectId than a live account with the same UPN: + # it is found by UPN, told apart by the recorded anchor when Exchange Online exposes it, and several candidates are an ambiguity, never a guess. + $items = @(Get-EXOMailbox -Filter (ExactFilter $Upn) -Properties $properties -ResultSize Unlimited -InactiveMailboxOnly -ErrorAction Stop) + if ($items.Count -gt 1) { + $anchors = @(V $P 'Anchors' @() | Where-Object { $_ }) + $matching = @($items | Where-Object { $own = [string](V $_ 'ImmutableId' ''); $own -and (InSet $own $anchors) }) + if ($matching.Count -ne 1) { throw "Exchange Online has $($items.Count) inactive mailboxes for $Upn and nothing tells which one belongs to this object: the retention cannot be checked for it." } + $items = $matching + } + $inactiveByUpn = ($items.Count -eq 1) + } if ($items.Count -gt 1) { throw "Exchange Online mailbox not unique: $Upn" } if ($items.Count -eq 0) { return @{ Found=$false; Type=$null; Holds=@(); IsInactive=$false; Litigation=$false; RetentionHold=$false; HasAddresses=$false; Addresses=[string[]]@() } } $m = $items[0]; $type = [string](V $m 'RecipientTypeDetails') if (-not $type) { throw "Mailbox type not returned: $Upn" } $mailboxOid=[string](V $m 'ExternalDirectoryObjectId' ''); $confirmed=V (V $P 'VerifiedObjectIds' @{}) $Upn - if ($mailboxOid -and $null -ne $confirmed -and $confirmed -and -not (SameIgnoreCase $mailboxOid $confirmed)) { throw "The Exchange Online mailbox is not the Microsoft Entra ID account confirmed for this object: $Upn" } + if (-not $inactiveByUpn -and $mailboxOid -and $null -ne $confirmed -and $confirmed -and -not (SameIgnoreCase $mailboxOid $confirmed)) { throw "The Exchange Online mailbox is not the Microsoft Entra ID account confirmed for this object: $Upn" } $holds = V -Object $m -Name 'InPlaceHolds' -Default @() # EmailAddresses (every proxy address of the mailbox, X500 included): whether Exchange Online returned the property at all is kept apart from "empty". $hasAddresses = if ($m -is [System.Collections.IDictionary]) { $m.Contains('EmailAddresses') } else { $null -ne $m.PSObject.Properties['EmailAddresses'] } @@ -227,7 +254,7 @@ $script:PraExoWorker = { if ($ownDn -and -not (InSetIgnoreCase ('X500:' + $ownDn) $addressList)) { $addressList += ('X500:' + $ownDn) } return @{ Found=$true; Type=$type; Holds=@($holds | Where-Object { $null -ne $_ }); IsInactive=[bool](V -Object $m -Name 'IsInactiveMailbox' -Default $false) Litigation=[bool](V -Object $m -Name 'LitigationHoldEnabled' -Default $false); RetentionHold=[bool](V -Object $m -Name 'RetentionHoldEnabled' -Default $false) - HasAddresses=[bool]$hasAddresses; Addresses=[string[]]$addressList } + HasAddresses=[bool]$hasAddresses; Addresses=[string[]]$addressList; IdentityByUpn=[bool]$inactiveByUpn } } function NormalizeAcl { param([object[]]$Entries,[string]$Right,$Target) @@ -285,8 +312,9 @@ $script:PraExoWorker = { function Permission { param([string]$Upn,[string]$Trustee,[string]$Right,$Recipient,$Target,[switch]$AllowPendingVisibility) if ((SameIgnoreCase $Right 'FullAccess') -or (SameIgnoreCase $Right 'SendAs')) { - $globalRaw=@(if ((SameIgnoreCase $Right 'FullAccess')) { Get-EXOMailboxPermission -Identity $Upn -ErrorAction Stop -WarningAction Stop } - else { Get-EXORecipientPermission -Identity $Upn -ErrorAction Stop -WarningAction Stop }) + $lookupKey=$(if (Confirmed $Upn) { Confirmed $Upn } else { $Upn }) + $globalRaw=@(if ((SameIgnoreCase $Right 'FullAccess')) { Get-EXOMailboxPermission -Identity $lookupKey -ErrorAction Stop -WarningAction Stop } + else { Get-EXORecipientPermission -Identity $lookupKey -ErrorAction Stop -WarningAction Stop }) if ($globalRaw.Count -eq 0 -or $globalRaw.Count -ge 1000) { throw "$Right permission list empty or possibly truncated." } $globalEntries=@(NormalizeAcl $globalRaw $Right $Target) if (-not @($globalEntries | Where-Object { (InSetIgnoreCase $_.Principal @('NT AUTHORITY\SELF','S-1-5-10')) -and (InSetIgnoreCase $Right $_.Rights) -and -not $_.Inherited }).Count) { throw "$Right permission list without the expected SELF entry." } @@ -295,8 +323,8 @@ $script:PraExoWorker = { # not -ErrorAction Stop, so that Windows PowerShell does not write it as an error in the transcript. # Every error record is checked: anything else than that exact answer stops. $filteredErrors=$null - $filteredRaw=@(if ((SameIgnoreCase $Right 'FullAccess')) { Get-EXOMailboxPermission -Identity $Upn -User $Trustee -ErrorAction SilentlyContinue -ErrorVariable filteredErrors -WarningAction Stop } - else { Get-EXORecipientPermission -Identity $Upn -Trustee $Trustee -ErrorAction Stop -WarningAction Stop }) + $filteredRaw=@(if ((SameIgnoreCase $Right 'FullAccess')) { Get-EXOMailboxPermission -Identity $lookupKey -User $Trustee -ErrorAction SilentlyContinue -ErrorVariable filteredErrors -WarningAction Stop } + else { Get-EXORecipientPermission -Identity $lookupKey -Trustee $Trustee -ErrorAction Stop -WarningAction Stop }) $filteredErrors=@($filteredErrors | Where-Object { $null -ne $_ }) if ($filteredErrors.Count) { foreach ($record in $filteredErrors) { @@ -316,7 +344,7 @@ $script:PraExoWorker = { } return (@($actualEntries | Where-Object { -not $_.Inherited -and (SameIgnoreCase $_.Control 'Allow') }).Count -gt 0) } - $mb = @(Get-Mailbox -Filter (ExactFilter $Upn) -ResultSize Unlimited -ErrorAction Stop) + $mb = @(if (Confirmed $Upn) { Get-Mailbox -Identity (Confirmed $Upn) -ErrorAction Stop } else { Get-Mailbox -Filter (ExactFilter $Upn) -ResultSize Unlimited -ErrorAction Stop }) if ($mb.Count -ne 1) { throw "Mailbox not unique for the SendOnBehalf read: $Upn" } $behalfOid=[string](V $mb[0] 'ExternalDirectoryObjectId' '') if ($behalfOid -and -not (SameIgnoreCase $behalfOid $Target.ObjectId)) { throw "The mailbox of the SendOnBehalf read is not the confirmed Exchange Online recipient: $Upn" } @@ -481,7 +509,9 @@ function Write-PraCloudFailure { } $info=Get-PraCloudFailureInfo $ErrorRecord if ($info.Throttled) { - $plain='{0}Microsoft 365 kept limiting the requests or was unavailable (HTTP {1}) and the retry time of this object is used up. Run again in a few minutes.' -f $(if ($Upn) { $Upn + ': ' } else { '' }), $info.Status + $retried=[bool]($ErrorRecord.Exception.Data['PraRetryExhausted']) + $plain=if ($retried) { '{0}Microsoft 365 kept limiting the requests or was unavailable (HTTP {1}) and the retry time of this object is used up. Run again in a few minutes.' -f $(if ($Upn) { $Upn + ': ' } else { '' }), $info.Status } + else { '{0}Microsoft 365 limited the requests or was unavailable (HTTP {1}); the call was not sent again (a look that cannot wait, a retry budget of 0, or a write). Run again in a few minutes.' -f $(if ($Upn) { $Upn + ': ' } else { '' }), $info.Status } Write-PraCloudError -Context $Context -Row $Row -Message $plain -Technical $raw -RunError return } @@ -489,6 +519,21 @@ function Write-PraCloudFailure { if ($Expectation) { Write-PraCloudError -Context $Context -Row $Row -Message $message } else { Write-PraCloudError -Context $Context -Row $Row -Message $message -RunError } } +function ConvertTo-PraRetryAfterSecond { + <# The seconds that a Retry-After value asks for: a number of seconds, or an HTTP date (RFC 1123, read with the invariant culture) counted from now. 0 for anything else and for a date in the past. #> + [CmdletBinding()] + param([AllowNull()][string]$Text) + $value = ([string]$Text).Trim() + $seconds = 0 + if ($value -cmatch '^\d{1,5}\z' -and [int]::TryParse($value, [Globalization.NumberStyles]::None, [Globalization.CultureInfo]::InvariantCulture, [ref]$seconds)) { return $seconds } + $when = [DateTimeOffset]::MinValue + $styles = [Globalization.DateTimeStyles]::AssumeUniversal -bor [Globalization.DateTimeStyles]::AllowWhiteSpaces + if ($value -and ([DateTimeOffset]::TryParseExact($value, 'r', [Globalization.CultureInfo]::InvariantCulture, $styles, [ref]$when) -or [DateTimeOffset]::TryParse($value, [Globalization.CultureInfo]::InvariantCulture, $styles, [ref]$when))) { + return [int][Math]::Min(86400, [Math]::Max(0, [Math]::Ceiling(($when - [DateTimeOffset]::UtcNow).TotalSeconds))) + } + return 0 +} + function Get-PraCloudFailureInfo { <# What a failed cloud call says about itself: Status (the HTTP status, 0 when there is none), RetryAfter (seconds, 0 when none, never more than two minutes), Transient (the same read can be sent again: 408, 429, 502, 503, 504, a timeout or a connection that did not answer), Throttled (429 or 503) and NotFound (404). Looks at the inner exceptions, then at the text (the Exchange Online child process only returns text). #> [CmdletBinding()] @@ -511,14 +556,13 @@ function Get-PraCloudFailureInfo { } $headers = Get-PraValue $response 'Headers' $null if ($null -ne $headers -and $retryAfter -eq 0) { - $parsed = 0 $retry = Get-PraValue $headers 'RetryAfter' $null if ($null -ne $retry) { $delta = Get-PraValue $retry 'Delta' $null; $when = Get-PraValue $retry 'Date' $null if ($null -ne $delta) { try { $retryAfter = [int][Math]::Ceiling(([TimeSpan]$delta).TotalSeconds) } catch { $retryAfter = 0 } } elseif ($null -ne $when) { try { $retryAfter = [int][Math]::Ceiling(([DateTimeOffset]$when - [DateTimeOffset]::UtcNow).TotalSeconds) } catch { $retryAfter = 0 } } } - elseif ([int]::TryParse([string](Get-PraValue $headers 'Retry-After' ''), [ref]$parsed)) { $retryAfter = $parsed } + else { $retryAfter = ConvertTo-PraRetryAfterSecond ([string](Get-PraValue $headers 'Retry-After' '')) } } if ($e -is [AggregateException]) { foreach ($inner in $e.InnerExceptions) { $queue.Enqueue($inner) } } elseif ($null -ne $e.InnerException) { $queue.Enqueue($e.InnerException) } @@ -538,7 +582,14 @@ function Get-PraCloudFailureInfo { elseif ($all -match '(?i)RequestTimeout|Request Timeout') { $status = 408 } elseif ($all -match '(?i)Request_ResourceNotFound') { $status = 404 } } - if ($retryAfter -le 0 -and $all -match '(?i)retry[- ]after\D{0,20}(\d{1,5})') { $retryAfter = [int]$Matches[1] } + if ($retryAfter -le 0) { + $dateText = [regex]::Match($all, '(?i)retry[- ]after\W{0,8}(?(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s+\d{1,2}\s+[A-Za-z]{3}\s+\d{4}\s+\d{2}:\d{2}:\d{2}\s+GMT)') + if ($dateText.Success) { $retryAfter = ConvertTo-PraRetryAfterSecond $dateText.Groups['d'].Value } + else { + $numberText = [regex]::Match($all, '(?i)retry[- ]after\D{0,20}?(?\d{1,5})(?!\d|\s*[A-Za-z]{3}\s+\d{4})') + if ($numberText.Success) { $retryAfter = [int]$numberText.Groups['n'].Value } + } + } $retryAfter = [Math]::Min([Math]::Max($retryAfter, 0), 120) $transient = $false if ($status -ne 0) { $transient = (Test-PraOrdinalIn $status @(408, 429, 502, 503, 504)) } @@ -563,9 +614,16 @@ function Stop-PraCloudRun { [CmdletBinding()] param([hashtable]$Context, [Exception]$Inner = $null) $state = Get-PraRetryState $Context - $state.RunExhausted = $true; $Context.CloudThrottled = $true + $state.RunExhausted = $true $minutes = [Math]::Round($state.RunBudget / 60.0, 1) - $message = 'Microsoft 365 is limiting or not answering this run: the {0} minute(s) allowed for retries are used up ({1} retries, {2} throttled answers). Nothing more is asked of Microsoft 365. What this run already did is kept: run the same command again in a few minutes.' -f $minutes, $state.Retries, $state.Throttled + if ($state.Throttled -gt 0) { + $Context.CloudThrottled = $true + $message = 'Microsoft 365 is limiting or not answering this run: the {0} minute(s) allowed for retries are used up ({1} retries, {2} throttled answers). Nothing more is asked of Microsoft 365. What this run already did is kept: run the same command again in a few minutes.' -f $minutes, $state.Retries, $state.Throttled + } + else { + $Context.NetworkFailure = $true + $message = 'Microsoft 365 did not answer (network): the {0} minute(s) allowed for retries are used up ({1} retries). Nothing more is asked of Microsoft 365. What this run already did is kept: run the same command again when the connection works.' -f $minutes, $state.Retries + } $failure = [System.InvalidOperationException]::new($message, $Inner) $failure.Data['PraRunBudget'] = $true throw $failure @@ -592,6 +650,7 @@ function Invoke-PraCloudCall { $state.RunSpent += $state.Pace } for ($try = 1; $true; $try++) { + $clock = [Diagnostics.Stopwatch]::StartNew() try { $answer = & $Script @ArgumentList if ($state.Pace -gt 0) { $state.Pace = [int][Math]::Floor($state.Pace / 2) } @@ -602,12 +661,16 @@ function Invoke-PraCloudCall { $info = Get-PraCloudFailureInfo $failure if (-not $info.Transient) { throw } if ($info.Throttled) { $state.Throttled++; $state.Pace = [int][Math]::Min(30, [Math]::Max(2, $state.Pace * 2)) } - $spent = if ($state.Objects.ContainsKey($key)) { [int]$state.Objects[$key] } else { 0 } + # The seconds that the failed call itself took (a timeout) count against both budgets, like the waits. + $took = [int][Math]::Floor($clock.Elapsed.TotalSeconds) + $spent = $(if ($state.Objects.ContainsKey($key)) { [int]$state.Objects[$key] } else { 0 }) + $took + $state.Objects[$key] = $spent; $state.RunSpent += $took $wait = if ($info.RetryAfter -gt 0) { [int]$info.RetryAfter } else { [int][Math]::Min(60, 5 * [Math]::Pow(2, $try - 1)) } $runOut = (($state.RunSpent + $wait) -gt $state.RunBudget) if ($try -ge 5 -or ($spent + $wait) -gt $state.ObjectBudget -or $runOut) { $null = Write-PraLog -Context $Context -Message ('Retry budget used up | {0} | {1} | status {2} | {3} tries | object {4} of {5} s, run {6} of {7} s' -f $Call, $key, $info.Status, $try, $spent, $state.ObjectBudget, $state.RunSpent, $state.RunBudget) -Level Detail if ($runOut) { Stop-PraCloudRun -Context $Context -Inner $failure.Exception } + $failure.Exception.Data['PraRetryExhausted'] = $true throw $failure } $null = Write-PraLog -Context $Context -Message ('Retry {0} | {1} | {2} | status {3}{4} | waiting {5} s | object {6} of {7} s, run {8} of {9} s' -f $try, $Call, $key, $(if ($info.Status) { $info.Status } else { 'no answer' }), $(if ($info.RetryAfter -gt 0) { ' (Retry-After ' + $info.RetryAfter + ' s)' } else { '' }), $wait, ($spent + $wait), $state.ObjectBudget, ($state.RunSpent + $wait), $state.RunBudget) -Level Detail @@ -627,9 +690,9 @@ function Test-PraIdentityCheck { function Get-PraEntraAccount { <# The Entra ID accounts found by UPN (-Upn) or by source anchor (-Anchor), read only. An account that does not exist is an empty answer, never an error. #> [CmdletBinding()] - param([hashtable]$Context, [string]$Upn, [string]$Anchor) + param([hashtable]$Context, [string]$Upn, [string]$Anchor, [string[]]$Property = @()) Assert-PraGraphSession $Context - $select = @('id', 'userPrincipalName', 'onPremisesImmutableId', 'onPremisesSyncEnabled') + $select = @(@('id', 'userPrincipalName', 'onPremisesImmutableId', 'onPremisesSyncEnabled') + @($Property) | Get-PraOrdinalUnique -IgnoreCase) if ($Anchor) { $filter = "onPremisesImmutableId eq '{0}'" -f $Anchor.Replace("'", "''") $byAnchor = { param($Filter, $Property) Get-MgUser -Filter $Filter -Property $Property -ErrorAction Stop } @@ -653,11 +716,11 @@ function Resolve-PraCloudIdentity { -Recorded $false: the anchors were derived from the objectGUID of a record written by an older version. #> [CmdletBinding()] - param([hashtable]$Context, [Parameter(Mandatory)][string]$Upn, [AllowNull()][string[]]$Anchors, [bool]$Recorded = $true, [switch]$SyncedOnly) + param([hashtable]$Context, [Parameter(Mandatory)][string]$Upn, [AllowNull()][string[]]$Anchors, [bool]$Recorded = $true, [switch]$SyncedOnly, [string[]]$Property = @()) $anchorList = @($Anchors | Where-Object { $_ }) - $result = { param($Status, $ObjectId, $Message, $Technical) [pscustomobject]@{ Status = $Status; ObjectId = $ObjectId; Message = $Message; Technical = $Technical } } - $older = if ($Recorded) { '' } else { ' The record was written by an older version and holds only the objectGUID: if your tenant uses ms-DS-ConsistencyGuid as source anchor with another value, check the account by hand and set Cloud.IdentityCheck = Off in the configuration file.' } - $accounts = @(Get-PraEntraAccount -Context $Context -Upn $Upn) + $result = { param($Status, $ObjectId, $Message, $Technical, $Account = $null) [pscustomobject]@{ Status = $Status; ObjectId = $ObjectId; Message = $Message; Technical = $Technical; Account = $Account } } + $older = if ($Recorded) { '' } else { ' The record was written by an older version: it holds only the objectGUID, not the ms-DS-ConsistencyGuid.' } + $accounts = @(Get-PraEntraAccount -Context $Context -Upn $Upn -Property $Property) if ($accounts.Count -gt 1) { return (& $result 'Ambiguous' '' ('{0}: Microsoft Entra ID returned {1} accounts for this UPN, so the right one cannot be chosen. Nothing was changed on it. Remove the duplicate account in Microsoft Entra ID, then run the same command again.' -f $Upn, $accounts.Count) ('accounts=' + (@($accounts | ForEach-Object { [string](Get-PraValue $_ 'Id' '') }) -join ','))) } @@ -665,11 +728,14 @@ function Resolve-PraCloudIdentity { $id = [string](Get-PraValue $accounts[0] 'Id' ''); $found = [string](Get-PraValue $accounts[0] 'OnPremisesImmutableId' '') if (-not $anchorList.Count) { if ($SyncedOnly -and -not $found) { return (& $result 'Mismatch' $id ('{0}: the Microsoft Entra ID account with this UPN is a cloud-only account, not an account synchronised from Active Directory. Nothing was changed on it. Give one of the two accounts another UPN, then run the same command again.' -f $Upn) ('id=' + $id)) } - return (& $result 'NoAnchor' $id '' ('id=' + $id)) + return (& $result 'NoAnchor' $id '' ('id=' + $id) $accounts[0]) } - if (Test-PraOrdinalIn $found $anchorList) { return (& $result 'Match' $id '' ('id=' + $id + '; onPremisesImmutableId=' + $found)) } - $why = if ($found) { 'it is synchronised from another Active Directory object' } else { 'it is a cloud-only account' } - return (& $result 'Mismatch' $id ('{0}: the Microsoft Entra ID account with this UPN is not the account synchronised from this Active Directory object ({1}). Nothing was changed on it. Give one of the two accounts another UPN so that Entra Connect can synchronise this object under its own UPN, or leave this object out, then run the same command again.{2}' -f $Upn, $why, $older) ('id=' + $id + '; onPremisesImmutableId=' + $found + '; expected=' + ($anchorList -join ' or '))) + if (Test-PraOrdinalIn $found $anchorList) { return (& $result 'Match' $id '' ('id=' + $id + '; onPremisesImmutableId=' + $found) $accounts[0]) } + if ($found) { + $form = if ($found -cmatch '^[A-Za-z0-9+/]{22}==\z') { 'is the base64 of a GUID, but not the objectGUID or the ms-DS-ConsistencyGuid of this Active Directory object' } else { 'is not the base64 of a GUID' } + return (& $result 'Mismatch' $id ('{0}: the Microsoft Entra ID account with this UPN is synchronised, but its onPremisesImmutableId {1}. Nothing was changed on it. Your tenant may use another source anchor than the objectGUID or the ms-DS-ConsistencyGuid: check by hand that this account is the one of this object, then set Cloud.IdentityCheck = ''Off'' in the configuration file and run the same command again.{2}' -f $Upn, $form, $older) ('id=' + $id + '; onPremisesImmutableId=' + $found + '; expected=' + ($anchorList -join ' or '))) + } + return (& $result 'Mismatch' $id ('{0}: the Microsoft Entra ID account with this UPN is not the account synchronised from this Active Directory object (it is a cloud-only account). Nothing was changed on it. Give one of the two accounts another UPN so that Entra Connect can synchronise this object under its own UPN, or leave this object out, then run the same command again.{1}' -f $Upn, $older) ('id=' + $id + '; onPremisesImmutableId=; expected=' + ($anchorList -join ' or '))) } if (-not $anchorList.Count) { return (& $result 'NotFound' '' '' '') } $byAnchor = @{} @@ -687,6 +753,18 @@ function Resolve-PraCloudIdentity { return (& $result 'NotFound' '' '' '') } +function Get-PraGraphRefusal { + <# $null unless Microsoft Graph refused the read of an account (401, 403, insufficient privileges): then the plain message with its next step (the permission, or Cloud.IdentityCheck = Off) and the technical text. #> + [CmdletBinding()] + param([Parameter(Mandatory)]$ErrorRecord, [string]$Upn = '') + $info = Get-PraCloudFailureInfo $ErrorRecord + $raw = [string]$ErrorRecord.Exception.Message + $refused = (Test-PraOrdinalIn $info.Status @(401, 403)) -or ($raw -match '(?i)Insufficient privileges|Authorization_RequestDenied|Authorization_IdentityNotFound|Forbidden') + if (-not $refused) { return $null } + $message = '{0}: Microsoft Graph refused to read the Microsoft Entra ID account that confirms this object ({1}). Nothing was changed. The tool reads every account with the permission User.Read.All: with a sign-in by a person, the administrator must consent to User.Read.All; with a certificate (application), add the application permission User.Read.All to the app registration and grant admin consent. Then run the same command again. Or set Cloud.IdentityCheck = ''Off'' in the configuration file: the accounts are then found by UPN only, without this read.' -f $Upn, $(if ($info.Status) { 'HTTP ' + $info.Status } else { 'insufficient privileges' }) + return [pscustomobject]@{ Message = $message; Technical = $raw } +} + function Confirm-PraCloudIdentity { <# The Entra ID account (and the account of each trustee) of one object is the one synchronised from Active Directory. Returns Ok, Wait (not in Microsoft Entra ID yet: read again at the next check) or Failed (an error is recorded; the object is never acted on). #> [CmdletBinding()] @@ -705,7 +783,8 @@ function Confirm-PraCloudIdentity { $anchor = Get-PraSourceAnchor -Record $source if ($session.IdentityCache.ContainsKey($upn)) { $verdict = $session.IdentityCache[$upn] } else { - $verdict = Resolve-PraCloudIdentity -Context $Context -Upn $upn -Anchors $anchor.Candidates -Recorded $anchor.Recorded + try { $verdict = Resolve-PraCloudIdentity -Context $Context -Upn $upn -Anchors $anchor.Candidates -Recorded $anchor.Recorded -Property ([string[]]@(Get-PraList $State 'FactProps')) } + catch { $refusal = Get-PraGraphRefusal -ErrorRecord $_ -Upn $upn; if ($null -eq $refusal) { throw }; return (& $fail $refusal.Message $refusal.Technical) } if (Test-PraOrdinalIn $verdict.Status @('Match', 'Mismatch', 'Ambiguous')) { $session.IdentityCache[$upn] = $verdict } } if (Test-PraOrdinalIn $verdict.Status @('Mismatch', 'Ambiguous')) { return (& $fail $verdict.Message $verdict.Technical) } @@ -724,12 +803,17 @@ function Confirm-PraCloudIdentity { $row.Warnings = ([string](Get-PraValue $row 'Warnings' '') + '; ' + $note).Trim(' ', ';') } $session.Verified[$upn] = [string]$verdict.ObjectId + # The account read for the identity also carries the properties of the first facts read: it is passed on once, never kept. + $State.Account = $verdict.Account; $verdict.Account = $null $trustees = @(@($State.Requests) | ForEach-Object { [string]$_.Trustee } | Get-PraOrdinalUnique -IgnoreCase) + # A record whose trustee anchors are incomplete (the schema could not be read) asks no more of a trustee than an older record: a synchronised account. + $incomplete = [bool](Get-PraValue $source 'SharedTrusteeAnchorsIncomplete' $false) foreach ($trustee in $trustees) { - $stored = Get-PraValue (Get-PraValue $source 'SharedTrusteeAnchors' $null) $trustee $null + $stored = if ($incomplete) { $null } else { Get-PraValue (Get-PraValue $source 'SharedTrusteeAnchors' $null) $trustee $null } if ($session.IdentityCache.ContainsKey($trustee)) { $answer = $session.IdentityCache[$trustee] } else { - $answer = Resolve-PraCloudIdentity -Context $Context -Upn $trustee -Anchors ([string[]]@(if ($null -ne $stored) { @($stored) })) -Recorded ($null -ne $stored) -SyncedOnly + try { $answer = Resolve-PraCloudIdentity -Context $Context -Upn $trustee -Anchors ([string[]]@(if ($null -ne $stored) { @($stored) })) -Recorded ($null -ne $stored) -SyncedOnly } + catch { $refusal = Get-PraGraphRefusal -ErrorRecord $_ -Upn $trustee; if ($null -eq $refusal) { throw }; return (& $fail $refusal.Message $refusal.Technical) } if (Test-PraOrdinalIn $answer.Status @('Match', 'Mismatch', 'Ambiguous')) { $session.IdentityCache[$trustee] = $answer } } if (Test-PraOrdinalIn $answer.Status @('Mismatch', 'Ambiguous')) { return (& $fail ('Permissions on {0} are not granted. {1}' -f $upn, $answer.Message) $answer.Technical) } @@ -1118,7 +1202,12 @@ function Initialize-PraCloudPreflight { -not (Test-PraOrdinalIgnoreCaseEqual (Get-PraValue $previous 'PrimarySmtpAddress') (Get-PraValue $identity 'PrimarySmtpAddress')))) { throw 'Contradictory identities at the pre-check.' } $session.Identities[$name]=$identity } - if ($needGraph -and -not [bool](Get-PraValue $row 'IsShared' $false)) { + if ($session.Verified.ContainsKey($upn) -and [string]$session.Verified[$upn]) { + # The account was read for the identity check: its id is compared with the one Exchange Online returns, with no second read. + $confirmedTarget=Get-PraValue $identities $upn $null + if (-not (Test-PraOrdinalIgnoreCaseEqual ([string]$session.Verified[$upn]) ([string](Get-PraValue $confirmedTarget 'ObjectId' '')))) { throw "Graph and Exchange Online identities differ at the pre-check: $upn" } + } + elseif ($needGraph -and -not [bool](Get-PraValue $row 'IsShared' $false)) { Assert-PraGraphSession $Context $readUser={ param($UserId,$Property) Get-MgUser -UserId $UserId -Property $Property -ErrorAction Stop } $users=@(Invoke-PraCloudCall -Context $Context -Call 'Microsoft Graph user' -Script $readUser -ArgumentList @($upn,@('Id','UserPrincipalName'))) @@ -1207,7 +1296,13 @@ function Invoke-PraSharedPermission { -not (Test-PraOrdinalEqual $Context.Action 'Convert') -or -not (Test-PraOrdinalIn $Context.Phase @('Cloud','Both')) -or $WhatIfPreference) { throw 'Permission missing and writes are not allowed in this mode.' } # Native ShouldProcess per right; it never replaces the approval, proof and journal of the grant. if (-not $PSCmdlet.ShouldProcess($upn,"Grant $($request.Right) to $($request.Trustee)")) { throw 'Exchange Online grant refused (ShouldProcess).' } - Invoke-PraPermissionGrant -Context $Context -Row $Row -Params $p + # A failure of the grant step is final for this run, whatever its cause: the grant is never sent twice. A later run reads the permissions first. + try { Invoke-PraPermissionGrant -Context $Context -Row $Row -Params $p } + catch { + $grantFailure = [System.InvalidOperationException]::new([string]$_.Exception.Message, $_.Exception) + $grantFailure.Data['PraGrantFailed'] = $true + throw $grantFailure + } $null=Write-PraLog -Context $Context -Message ("{0}: {1} granted to {2} and verified" -f $upn,$request.Right,$request.Trustee) -Level Sub } $verified++ @@ -1218,15 +1313,33 @@ function Invoke-PraSharedPermission { return $toGrant } +function Get-PraGraphFactProperty { + <# The Graph properties that Get-PraGraphFact reads for these questions. #> + param([bool]$Mailbox,[bool]$License,[bool]$Addresses=$false) + $props=@('assignedPlans'); if ($Mailbox) { $props+='provisionedPlans' }; if ($License) { $props+='assignedLicenses' }; if ($Addresses) { $props+='proxyAddresses' } + return $props +} + function Get-PraGraphFact { - param([hashtable]$Context,[string]$Upn,[bool]$Mailbox,[bool]$License,[bool]$Addresses=$false) + <# The Graph facts of one account. The account is read by the Entra id confirmed for the object (by UPN when none is known). -Account: the user already read with these properties (the identity check), used once instead of a second read. #> + param([hashtable]$Context,[string]$Upn,[bool]$Mailbox,[bool]$License,[bool]$Addresses=$false,$Account=$null) if (-not (Get-PraCloudSession $Context).Graph) { throw 'Microsoft Graph required but not connected.' } Assert-PraGraphSession $Context - $props=@('assignedPlans'); if ($Mailbox) { $props+='provisionedPlans' }; if ($License) { $props+='assignedLicenses' }; if ($Addresses) { $props+='proxyAddresses' } - $readUser={ param($UserId,$Property) Get-MgUser -UserId $UserId -Property $Property -ErrorAction Stop } - $users=@(Invoke-PraCloudCall -Context $Context -Call 'Microsoft Graph user' -Script $readUser -ArgumentList @($Upn,$props)) + $props=@(Get-PraGraphFactProperty -Mailbox $Mailbox -License $License -Addresses $Addresses) + $verified=(Get-PraCloudSession $Context).Verified + $confirmed=if ($verified.ContainsKey($Upn) -and [string]$verified[$Upn]) { [string]$verified[$Upn] } else { '' } + $lookup=if ($confirmed) { $confirmed } else { $Upn } + $sentinel=New-Object object + $prefetched=($null -ne $Account -and -not @($props | Where-Object { [object]::ReferenceEquals((Get-PraValue $Account $_ $sentinel),$sentinel) }).Count) + if ($prefetched) { $users=@($Account) } + else { + $readUser={ param($UserId,$Property) Get-MgUser -UserId $UserId -Property $Property -ErrorAction Stop } + $users=@(Invoke-PraCloudCall -Context $Context -Call 'Microsoft Graph user' -Script $readUser -ArgumentList @($lookup,@($props + 'id'))) + } if ($users.Count -ne 1 -or $null -eq $users[0]) { throw "Microsoft Graph: user not found or not unique ($Upn)." } - $values=@{}; $sentinel=New-Object object + $returnedId=[string](Get-PraValue $users[0] 'Id' '') + if ($confirmed -and $returnedId -and -not (Test-PraOrdinalIgnoreCaseEqual $returnedId $confirmed)) { throw "Microsoft Graph returned another account than the one confirmed for this object: $Upn" } + $values=@{} foreach ($prop in $props) { $value=Get-PraValue $users[0] $prop $sentinel if ([object]::ReferenceEquals($value,$sentinel)) { throw "Microsoft Graph: property not returned ($prop)." } @@ -1246,7 +1359,7 @@ function Get-PraGraphFact { $required=[string](Get-PraValue (Get-PraValue $Context.Config 'Cloud' @{}) 'RequiredSkuPartNumber' '') if ($Mailbox -or ($License -and $required)) { $readDetails={ param($UserId) Get-MgUserLicenseDetail -UserId $UserId -All -ErrorAction Stop } - $details=@(Invoke-PraCloudCall -Context $Context -Call 'Microsoft Graph licence details' -Script $readDetails -ArgumentList @($Upn)) + $details=@(Invoke-PraCloudCall -Context $Context -Call 'Microsoft Graph licence details' -Script $readDetails -ArgumentList @($lookup)) foreach ($d in $details) { $sku += [string](Get-PraValue $d 'SkuPartNumber' '') foreach ($p in @((Get-PraValue $d 'ServicePlans' @()) | Where-Object { ([string](Get-PraValue $_ 'ServicePlanName' '')).StartsWith('EXCHANGE_',[StringComparison]::OrdinalIgnoreCase) })) { @@ -1315,7 +1428,11 @@ function Invoke-PraX500Step { if (-not $addresses.Has) { throw $(if ($State.ExoMailbox) { 'EmailAddresses not returned by Exchange Online' } else { 'proxyAddresses not returned by Microsoft Graph' }) } $State.X500Last = Compare-PraX500Address -Expected $State.X500 -Actual $addresses.List } - catch { $State.X500Failure = [string]$_.Exception.Message; $State.X500Last = $null } + catch { + # The stop of the run is not a result of the control: it goes to the caller. + if ((Get-PraRetryState $Context).RunExhausted) { throw } + $State.X500Failure = [string]$_.Exception.Message; $State.X500Last = $null + } $good = ([string]::IsNullOrEmpty($State.X500Failure) -and $State.X500Last.Missing.Count -eq 0) if ($good -or $Final -or $State.X500Reads -ge $MaxReads) { Complete-PraX500Check -Context $Context -State $State; return $true } $found = if ($null -ne $State.X500Last) { 'X500:{0} of {1} present, read {2} of {3}' -f $State.X500Last.Present.Count, $State.X500Last.Total, $State.X500Reads, $MaxReads } else { 'X500:not readable yet, read {0} of {1}' -f $State.X500Reads, $MaxReads } @@ -1358,9 +1475,11 @@ function Invoke-PraCloudPhase { # and the row says it is to grant by hand (report and CSV). if ($shared -and (Test-PraOrdinalIgnoreCaseEqual $Act 'Convert')) { $notGranted=New-Object 'System.Collections.Generic.List[string]' + $requested=New-Object 'System.Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase) + foreach ($request in $requests) { [void]$requested.Add(([string]$request.Right)+'|'+([string]$request.Trustee)) } foreach ($right in @('FullAccess','SendAs','SendOnBehalf')) { foreach ($trustee in @((Get-PraValue $row ('Shared'+$right) @()) | Where-Object { -not [string]::IsNullOrWhiteSpace([string]$_) } | Get-PraOrdinalUnique -IgnoreCase)) { - if (-not @($requests | Where-Object { (Test-PraOrdinalEqual $_.Right $right) -and (Test-PraOrdinalIgnoreCaseEqual $_.Trustee ([string]$trustee)) }).Count) { $notGranted.Add(('{0} {1}' -f $right,[string]$trustee)) } + if (-not $requested.Contains($right+'|'+[string]$trustee)) { $notGranted.Add(('{0} {1}' -f $right,[string]$trustee)) } } } if ($notGranted.Count) { @@ -1418,6 +1537,7 @@ function Invoke-PraCloudPhase { if ($s.CoreDone) { $null=Invoke-PraX500Step -Context $Context -State $s -Fresh $null -MaxReads $x500MaxReads -Final ([bool]$Context.Once); continue } if (-not $s.IdentityChecked) { $Context.CurrentOperation='ConfirmIdentity' + if ($s.GraphMailbox -or $s.License) { $s.FactProps=[string[]]@(Get-PraGraphFactProperty -Mailbox $s.GraphMailbox -License $s.License -Addresses ([bool]($null -ne $s.X500 -and $s.GraphMailbox))) } $outcome=Confirm-PraCloudIdentity -Context $Context -State $s $Context.CurrentOperation='CloudCheck' if (Test-PraOrdinalEqual $outcome 'Failed') { $s.Done=$true; continue } @@ -1425,7 +1545,10 @@ function Invoke-PraCloudPhase { $s.IdentityChecked=$true } $details=New-Object 'System.Collections.Generic.List[string]'; $plain=New-Object 'System.Collections.Generic.List[string]'; $mbok=$true; $licok=$true; $facts=$null - if ($s.GraphMailbox -or $s.License) { $facts=Get-PraGraphFact -Context $Context -Upn $s.Upn -Mailbox $s.GraphMailbox -License $s.License -Addresses ([bool]($null -ne $s.X500 -and $s.GraphMailbox)) } + if ($s.GraphMailbox -or $s.License) { + $facts=Get-PraGraphFact -Context $Context -Upn $s.Upn -Mailbox $s.GraphMailbox -License $s.License -Addresses ([bool]($null -ne $s.X500 -and $s.GraphMailbox)) -Account (Get-PraValue $s 'Account' $null) + $s.Account=$null + } if ($s.ExoMailbox) { $m=Invoke-PraExo -Context $Context -Operation 'Mailbox' -Params @{ Upn=$s.Upn } if ((Test-PraOrdinalIgnoreCaseEqual $Act 'Recover')) { @@ -1497,6 +1620,11 @@ function Invoke-PraCloudPhase { $failure=$_ $info=Get-PraCloudFailureInfo $failure if ((Get-PraRetryState $Context).RunExhausted) { $stopRun=$failure; break } + if ($failure.Exception.Data['PraGrantFailed'] -eq $true) { + # The grant step is never repeated in this run (a second Add would need a new approval and new journal lines): the object ends here, a later run reads the permissions first. + Write-PraCloudError -Context $Context -Row $row -RunError -Message ('{0}: a shared mailbox permission could not be granted or verified ({1}). It is not granted a second time in this run: run the cloud phase again later, it reads the permissions first and grants only what is missing.' -f $s.Upn, ([string]$failure.Exception.Message -replace '\s+',' ')) -Technical ([string]$failure.Exception.Message) + $s.Done=$true; continue + } if ($info.Transient -and -not $Context.Once -and $clock.Elapsed.TotalSeconds -lt $timeout) { $s.LastFailure=$failure; $row.CloudStatus='Pending' $s.PlainText='Microsoft 365 could not be read just now ({0}); the read is repeated at the next check' -f $(if ($info.Status) { 'HTTP ' + $info.Status } else { 'no answer' }) @@ -1513,7 +1641,7 @@ function Invoke-PraCloudPhase { $notReady=@($pending | Where-Object { -not $_.CoreDone }) # A Check says what it waits for: a mailbox that was never converted (still on-premises) does not reach the expected state, and the wait is long. -Once looks once. $checkHint=if ((Test-PraOrdinalIgnoreCaseEqual $Context.Action 'Check')) { ' Waiting for {0}. A mailbox that is still on-premises never gets there without a Convert; with -Once the check looks once and stops.' -f $(if ((Test-PraOrdinalIgnoreCaseEqual $Act 'Recover')) { 'the mailbox to be deprovisioned (a MailUser) in Exchange Online' } else { 'the mailbox to exist in Exchange Online' }) } else { '' } - if ($notReady.Count) { Write-PraItem -Context $Context -Status Info -Icon Clock -Text ("Not ready yet: {0} - next check in {1:0} s (waiting up to {2} min in total).{3}" -f (($notReady | ForEach-Object { $_.Upn }) -join ', '), $seconds, $Context.TimeoutMinutes, $checkHint) } + if ($notReady.Count) { Write-PraItem -Context $Context -Status Info -Icon Clock -Text ("Not ready yet: {0} - next check in {1:0} s (waiting up to {2} min in total).{3}" -f ((@($notReady | Select-Object -First 20 | ForEach-Object { $_.Upn }) -join ', ') + $(if ($notReady.Count -gt 20) { ' and {0} more (all of them are in the log)' -f ($notReady.Count - 20) } else { '' })), $seconds, $Context.TimeoutMinutes, $checkHint) } foreach ($s in @($pending | Where-Object { $_.CoreDone })) { Write-PraItem -Context $Context -Status Info -Icon Clock -Text ("{0}: mailbox ready; X500 addresses not all visible yet, check {1} of {2} in {3:0} s" -f $s.Upn, ([int]$s.X500Reads + 1), $x500MaxReads, $seconds) } foreach ($s in $pending) { $null=Write-PraLog -Context $Context -Message ("{0} | {1}" -f $s.Upn, $s.Row.CloudDetail) -Level Detail } $intervalSeconds=[Math]::Max(1,([double]$Context.IntervalMinutes*60)) @@ -1531,7 +1659,7 @@ function Invoke-PraCloudPhase { $s.Row.Detail=([string]$s.Row.Detail+' | not finished: the retry time of the run is used up').Trim(' ','|') } $Context.CurrentIdentity=''; $Context.CurrentOperation='CloudCheck' - Write-PraCloudError -Context $Context -Row $null -Message ('{0} {1} object(s) were not finished.' -f $stopRun.Exception.Message, $unfinished.Count) -Technical ([string]$stopRun.Exception.InnerException.Message) + Write-PraCloudError -Context $Context -Row $null -Message ('{0} {1} object(s) were not finished.' -f $stopRun.Exception.Message, $unfinished.Count) -Technical $(if ($null -ne $stopRun.Exception.InnerException) { [string]$stopRun.Exception.InnerException.Message } else { '' }) } else { foreach ($s in $states) { if ($s.Done) { continue } @@ -1602,6 +1730,7 @@ function Invoke-PraRetentionCheck { foreach ($id in $newIds) { Disconnect-ExchangeOnline -ConnectionId $id -Confirm:$false -ErrorAction Stop 6>$null | Out-Null } } } + $stopRun=$null foreach ($row in $Rows) { Add-Member -InputObject $row -NotePropertyName DeprovisionConfirmed -NotePropertyValue $false -Force $Context.CurrentOperation='VerifyRetention'; $Context.CurrentIdentity=[string](Get-PraValue $row 'ObjectGuid' '') @@ -1610,8 +1739,14 @@ function Invoke-PraRetentionCheck { $holdUpn=[string](Get-PraValue $row 'UserPrincipalName' '') # An inactive mailbox has no account in Microsoft Entra ID any more: it is found by UPN only. An account that exists must be the synchronised one. if ((Test-PraIdentityCheck $Context) -and (Test-PraOrdinalEqual (Confirm-PraCloudIdentity -Context $Context -State @{ Row=$row; Upn=$holdUpn; Requests=@(); PlainText='' }) 'Failed')) { continue } - $h=Invoke-PraExo -Context $Context -Operation 'Hold' -Params @{ Upn=$holdUpn } + $holdSource=Get-PraValue $row 'BackupRec' $null; if ($null -eq $holdSource) { $holdSource=$row } + $h=Invoke-PraExo -Context $Context -Operation 'Hold' -Params @{ Upn=$holdUpn; Anchors=[string[]]@((Get-PraSourceAnchor -Record $holdSource).Candidates) } $row.CloudMailbox=[bool](Get-PraValue $h 'Found' $false) + if ([bool](Get-PraValue $h 'IdentityByUpn' $false)) { + $note=('{0}: the inactive mailbox is found by its UPN only: its account is deleted, so it cannot be confirmed against Active Directory. Check that it is the mailbox of this object.' -f $holdUpn) + Write-PraItem -Context $Context -Status Warn -Text $note + $row.Warnings=([string](Get-PraValue $row 'Warnings' '') + '; ' + $note).Trim(' ',';') + } $holds=Get-PraValue $h 'Holds' @(); $holds=@($holds | Where-Object { $null -ne $_ }) $included=$false; $excluded=$false; $deleteOnly=$false foreach ($hold in $holds) { @@ -1630,7 +1765,18 @@ function Invoke-PraRetentionCheck { $row.CloudStatus='Success'; if (-not (Test-PraOrdinalIgnoreCaseEqual $row.FinalStatus 'Error')) { $row.FinalStatus='Success' } $row.CloudDetail+=' | COVERED (GUID='+$guid+')' $null=Write-PraLog -Context $Context -Message $row.CloudDetail -Level Success - } catch { Write-PraCloudFailure -Context $Context -Row $row -ErrorRecord $_ -Upn ([string](Get-PraValue $row 'UserPrincipalName' '')) -Expectation } + } catch { + $failure=$_ + # The retry time of the run is used up: ONE error for the run, the rows not checked stay Pending (never one error per row). + if ((Get-PraRetryState $Context).RunExhausted) { $stopRun=$failure; break } + Write-PraCloudFailure -Context $Context -Row $row -ErrorRecord $failure -Upn ([string](Get-PraValue $row 'UserPrincipalName' '')) -Expectation + } + } + if ($null -ne $stopRun) { + $notChecked=@($Rows | Where-Object { -not (Test-PraOrdinalIn ([string](Get-PraValue $_ 'CloudStatus' '')) @('Success','Error')) }) + foreach ($row in $notChecked) { $row.CloudStatus='Pending'; $row.FinalStatus='Pending'; $row.Detail=([string](Get-PraValue $row 'Detail' '')+' | not checked: the retry time of the run is used up').Trim(' ','|') } + $Context.CurrentIdentity=''; $Context.CurrentOperation='VerifyRetention' + Write-PraCloudError -Context $Context -Row $null -Message ('{0} {1} object(s) were not checked.' -f $stopRun.Exception.Message, $notChecked.Count) -Technical $(if ($null -ne $stopRun.Exception.InnerException) { [string]$stopRun.Exception.InnerException.Message } else { '' }) } } catch { $failure=$_ diff --git a/package/module/PRA.Common.psm1 b/package/module/PRA.Common.psm1 index f18ca43..c933008 100644 --- a/package/module/PRA.Common.psm1 +++ b/package/module/PRA.Common.psm1 @@ -182,6 +182,48 @@ function Get-PraOrdinalUnique { process { if ($null -ne $InputObject -and $seen.Add([string]$InputObject)) { [string]$InputObject } } } +$script:PraRecordIndexCache = New-Object 'Runtime.CompilerServices.ConditionalWeakTable[object,object]' + +function New-PraRecordIndex { + <# The records of a list by ObjectGuid (ordinal, ignoring the case): ByGuid finds one record without scanning the list, Duplicates holds the GUIDs that more than one record carries (the first record is kept). #> + [CmdletBinding()] + param([AllowNull()][AllowEmptyCollection()][object]$Record) + $map = New-Object 'Collections.Generic.Dictionary[string,object]' ([StringComparer]::OrdinalIgnoreCase) + $duplicates = New-Object 'Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase) + $count = 0 + foreach ($item in @($Record)) { + if ($null -eq $item) { continue } + $count++ + $key = [string]$item.ObjectGuid + if ($map.ContainsKey($key)) { [void]$duplicates.Add($key); continue } + $map.Add($key, $item) + } + return [pscustomobject]@{ ByGuid = $map; Duplicates = $duplicates; Count = $count } +} + +function Get-PraRecordIndex { + <# New-PraRecordIndex of a records array, built once: the same array (and the same number of records) gives the same index. A value that is not an array is indexed each time. #> + [CmdletBinding()] + param([AllowNull()][AllowEmptyCollection()][object]$Record) + if ($Record -is [object[]]) { + $cached = $null + if ($script:PraRecordIndexCache.TryGetValue($Record, [ref]$cached) -and $cached.Count -eq $Record.Length) { return $cached } + $index = New-PraRecordIndex -Record $Record + $script:PraRecordIndexCache.AddOrUpdate($Record, $index) + return $index + } + return (New-PraRecordIndex -Record $Record) +} + +function Find-PraRecord { + <# The record of an index (New-PraRecordIndex, Get-PraRecordIndex) for a GUID in any letter case; $null when there is none. #> + [CmdletBinding()] + param([Parameter(Mandatory)]$Index, [AllowNull()][AllowEmptyString()][string]$Guid) + $found = $null + if ($Guid -and $Index.ByGuid.TryGetValue($Guid, [ref]$found)) { return $found } + return $null +} + function Compare-PraX500Address { <# .SYNOPSIS @@ -2012,7 +2054,7 @@ $script:PraTransferKinds = @{ Recover = @{ Direction = 'ToCloud'; Target = 'Cloud'; Prefix = 'Batch-' } Finalize = @{ Direction = 'ToAD'; Target = 'AD'; Prefix = 'Finalize-' } } -$script:PraTransferLimits = @{ MaxEntries = [int]2000; MaxEntryBytes = [long]268435456; MaxTotalBytes = [long]536870912; MaxManifestBytes = [long]1048576 } +$script:PraTransferLimits = @{ MaxEntries = [int]2000; MaxEntryBytes = [long]2147483648; MaxTotalBytes = [long]4294967296; MaxManifestBytes = [long]1048576 } function Remove-PraStaleStaging { <# Sweeps the staging folders ('.importing-*') that a killed import left in the backup folder (older than 15 minutes: never an import in progress). #> @@ -2551,7 +2593,7 @@ function New-PraEffectiveConfiguration { # small machine-readable file (PhaseData-*.json + .sha256) in the batch folder it creates; the file travels in the transfer package with the batch # (listed in transfer.json with its SHA-256 like every entry, so a changed file is refused at import). It is DATA FOR A REPORT: nothing in the engine # decides anything from it. It is read as untrusted input (size, schema, checksum, Environment) and every value is HTML-encoded when it is shown. -$script:PraPhaseLimits = @{ MaxBytes = [long]67108864; MaxText = 2000; MaxStepText = 300; MaxStepsPerObject = 40; MaxJourney = 200000; MaxObjects = 200000; MaxFiles = 24; MaxIssues = 500; DetailedObjects = 2000 } +$script:PraPhaseLimits = @{ MaxBytes = [long]268435456; MaxText = 2000; MaxStepText = 300; MaxStepsPerObject = 40; MaxJourney = 1000000; MaxObjects = 200000; MaxFiles = 24; MaxIssues = 10000; DetailedObjects = 10000 } $script:PraPhaseFilter = 'PhaseData-*.json' $script:PraNotAvailable = 'not available (folder from an older version or copied manually)' # Display only: a Pending phase (or stage) that a later phase of the same report took over is shown as handed over; the verdict logic reads the raw status. @@ -3099,8 +3141,8 @@ function Write-PraGlobalReportHtml { $issues = @(Get-PraList $phase.Record 'Issues'); $warnings = @(Get-PraList $phase.Record 'Warnings') if (-not $issues.Count -and -not $warnings.Count) { continue } [void]$sb.Append('

').Append((& $h ('Errors and warnings ' + [char]0x00B7 + ' ' + $phase.Label))).Append('

') - foreach ($issue in ($issues | Select-Object -First 200)) { [void]$sb.Append('') } - foreach ($warning in ($warnings | Select-Object -First 200)) { [void]$sb.Append('') } + foreach ($issue in ($issues | Select-Object -First $script:PraPhaseLimits.MaxIssues)) { [void]$sb.Append('') } + foreach ($warning in ($warnings | Select-Object -First $script:PraPhaseLimits.MaxIssues)) { [void]$sb.Append('') } [void]$sb.Append('
KindTimeStepObjectMessage
error').Append((& $h (Get-PraValue $issue 'Timestamp' ''))).Append('').Append((& $h (Get-PraValue $issue 'Phase' ''))).Append('').Append((& $h (Get-PraValue $issue 'Identity' ''))).Append('').Append((& $h (Get-PraValue $issue 'Message' ''))).Append('
warning').Append((& $h (Get-PraValue $warning 'Timestamp' ''))).Append('').Append((& $h (Get-PraValue $warning 'Phase' ''))).Append('').Append((& $h (Get-PraValue $warning 'Message' ''))).Append('
error').Append((& $h (Get-PraValue $issue 'Timestamp' ''))).Append('').Append((& $h (Get-PraValue $issue 'Phase' ''))).Append('').Append((& $h (Get-PraValue $issue 'Identity' ''))).Append('').Append((& $h (Get-PraValue $issue 'Message' ''))).Append('
warning').Append((& $h (Get-PraValue $warning 'Timestamp' ''))).Append('').Append((& $h (Get-PraValue $warning 'Phase' ''))).Append('').Append((& $h (Get-PraValue $warning 'Message' ''))).Append('
') } [void]$sb.Append('

Generated by PRA Remote Mailbox v').Append((& $h $Model.Version)).Append('. This report holds names and statuses only: no secret, no token.

') @@ -3168,7 +3210,7 @@ function Write-PraGlobalReport { } #endregion -Export-ModuleMember -Function Register-PraObjectName, Get-PraList, ConvertTo-PraImmutableId, Get-PraSourceAnchor, Register-PraObjectBackup, Save-PraPhaseData, Copy-PraPhaseData, Read-PraPhaseData, New-PraPhaseRecord, Get-PraGlobalModel, Write-PraGlobalReport, Write-PraGlobalReportHtml, Write-PraGlobalReportCsv, Test-PraGlobalReportWanted, Limit-PraText, Get-PraEventObjectName, Test-PraOrdinalEqual, Test-PraOrdinalIgnoreCaseEqual, Test-PraOrdinalIn, Test-PraOrdinalIgnoreCaseIn, Get-PraOrdinalSorted, Get-PraOrdinalUnique, Compare-PraX500Address, ConvertFrom-PraJson, Get-PraNativeProcessApi, Read-PraCsvText, Get-PraToolVersion, Get-PraCloudModuleReport, New-PraPrivateDirectorySecurity, Initialize-PraPrivateFolder, ConvertTo-PraCsvCell, Get-PraValue, Format-PraDuration, Add-PraIssue, Write-PraLog, Write-PraItem, Write-PraBanner, Write-PraStep, +Export-ModuleMember -Function Register-PraObjectName, Get-PraList, ConvertTo-PraImmutableId, Get-PraSourceAnchor, Register-PraObjectBackup, Save-PraPhaseData, Copy-PraPhaseData, Read-PraPhaseData, New-PraPhaseRecord, Get-PraGlobalModel, Write-PraGlobalReport, Write-PraGlobalReportHtml, Write-PraGlobalReportCsv, Test-PraGlobalReportWanted, Limit-PraText, Get-PraEventObjectName, Test-PraOrdinalEqual, Test-PraOrdinalIgnoreCaseEqual, Test-PraOrdinalIn, Test-PraOrdinalIgnoreCaseIn, Get-PraOrdinalSorted, Get-PraOrdinalUnique, New-PraRecordIndex, Get-PraRecordIndex, Find-PraRecord, Compare-PraX500Address, ConvertFrom-PraJson, Get-PraNativeProcessApi, Read-PraCsvText, Get-PraToolVersion, Get-PraCloudModuleReport, New-PraPrivateDirectorySecurity, Initialize-PraPrivateFolder, ConvertTo-PraCsvCell, Get-PraValue, Format-PraDuration, Add-PraIssue, Write-PraLog, Write-PraItem, Write-PraBanner, Write-PraStep, Write-PraSummary, Write-PraHost, Resolve-PraPath, Import-PraConfiguration, Test-PraScopeConfiguration, Initialize-PraAudit, Get-PraOutcome, Complete-PraRun, Write-PraEvent, Get-PraWin32ErrorText, Test-PraOwnEntryProcess, Get-PraTargetOverride, Read-PraTargetCsv, Write-PraProgress, Get-PraTransferPackageName, Get-PraTransferPackage, Import-PraTransferPackage, New-PraTransferPackage, New-PraEffectiveConfiguration, Get-PraConfigurationDifference # SIG # Begin signature block diff --git a/package/module/PRA.Directory.psm1 b/package/module/PRA.Directory.psm1 index c572acd..25206a9 100644 --- a/package/module/PRA.Directory.psm1 +++ b/package/module/PRA.Directory.psm1 @@ -100,7 +100,6 @@ function Write-PraDataFingerprint { Structural SHA-256 of closed JSON data (strings, numbers, arrays, dictionaries, note properties). Used to detect a change of a validated backup in memory. Any other type is refused. #> - [CmdletBinding()] param([hashtable]$State, [AllowNull()]$Value, [int]$Depth = 0) if ($Depth -gt 64) { throw 'Receipt data too deep or cyclic.' } $State.Nodes++ @@ -140,6 +139,12 @@ function Write-PraDataFingerprint { $writer.Write($State.Bytes, 0, ($count * 2)) } } + elseif ($null -eq $item) { + if ($Depth -ge 64) { throw 'Receipt data too deep or cyclic.' } + $State.Nodes++ + if ($State.Nodes -gt 10000000) { throw 'Receipt data too large.' } + $writer.Write([byte]0) + } else { Write-PraDataFingerprint -State $State -Value $item -Depth ($Depth + 1) } } return @@ -158,8 +163,32 @@ function Write-PraDataFingerprint { $writer.Write([byte]9); $writer.Write([int]$properties.Count) foreach ($property in $properties) { if ($property.MemberType -ne [Management.Automation.PSMemberTypes]::NoteProperty) { throw 'Executable property not allowed in a receipt.' } - Write-PraDataFingerprint -State $State -Value ([string]$property.Name) -Depth ($Depth + 1) - Write-PraDataFingerprint -State $State -Value $property.Value -Depth ($Depth + 1) + # The name and a text value are written here, with the same bytes and limits as a call for each, to spare a call per value. + $text = [string]$property.Name + if ($Depth -ge 64) { throw 'Receipt data too deep or cyclic.' } + $State.Nodes++ + if ($State.Nodes -gt 10000000) { throw 'Receipt data too large.' } + $writer.Write([byte]1); $writer.Write([int]$text.Length) + for ($offset = 0; $offset -lt $text.Length; $offset += 1024) { + $count = [math]::Min(1024, $text.Length - $offset) + $text.CopyTo($offset, $State.Characters, 0, $count) + [Buffer]::BlockCopy($State.Characters, 0, $State.Bytes, 0, ($count * 2)) + $writer.Write($State.Bytes, 0, ($count * 2)) + } + $child = $property.Value + if ($child -is [string]) { + if ($Depth -ge 64) { throw 'Receipt data too deep or cyclic.' } + $State.Nodes++ + if ($State.Nodes -gt 10000000) { throw 'Receipt data too large.' } + $writer.Write([byte]1); $writer.Write([int]$child.Length) + for ($offset = 0; $offset -lt $child.Length; $offset += 1024) { + $count = [math]::Min(1024, $child.Length - $offset) + $child.CopyTo($offset, $State.Characters, 0, $count) + [Buffer]::BlockCopy($State.Characters, 0, $State.Bytes, 0, ($count * 2)) + $writer.Write($State.Bytes, 0, ($count * 2)) + } + } + else { Write-PraDataFingerprint -State $State -Value $child -Depth ($Depth + 1) } } return } @@ -181,18 +210,59 @@ function Get-PraDataFingerprint { finally { $writer.Dispose(); $crypto.Dispose(); $hash.Dispose() } } +# A backup that is checked before every write is checked in two ways. Cheap, for each write: the fields of the receipt, the fingerprint of the record about to be +# written, and the length and the last write time of the three files. Complete, at the boundaries of a batch and after this many cheap checks: the fingerprint of +# every record and the SHA-256 of the files. +$script:ReceiptFileHashEvery = 200 + +function Get-PraFileStamp { + <# Length and last write time (UTC ticks) of a file, as text; 'missing' when it is not there. #> + [CmdletBinding()] + param([Parameter(Mandatory)][string]$Path) + $info = New-Object IO.FileInfo $Path + if (-not $info.Exists) { return 'missing' } + return ('{0}|{1}' -f $info.Length, $info.LastWriteTimeUtc.Ticks) +} + +function Get-PraReceiptEnvelope { + <# The fields of a backup other than its records, as an ordered dictionary that Get-PraDataFingerprint accepts. A member that is not a plain value is refused without being read. #> + [CmdletBinding()] + param([Parameter(Mandatory)]$Data) + $envelope = [ordered]@{} + foreach ($property in $Data.PSObject.Properties) { + if ([string]::Equals($property.Name, 'Records', [StringComparison]::Ordinal)) { continue } + if ($property.MemberType -ne [Management.Automation.PSMemberTypes]::NoteProperty) { throw 'Executable property not allowed in a receipt.' } + $envelope[[string]$property.Name] = $property.Value + } + return $envelope +} + function Add-PraValidatedReceipt { - <# Remembers a backup validated in this run, with its hashes and a fingerprint of its content. #> + <# Remembers a backup validated in this run, with its hashes, the stamps of its files, the fingerprint of its fields and the fingerprint of each record. #> [CmdletBinding()] param([hashtable]$Context, $Receipt, [string]$RawPath = '', [string]$RawHash = '') - $guids = New-Object 'Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase) - foreach ($record in $Receipt.Data.Records) { [void]$guids.Add([string]$record.ObjectGuid) } + $data = $Receipt.Data + $recordsArray = $data.Records + if ($recordsArray -isnot [object[]]) { throw 'Backup records are not a list.' } + $fingerprints = New-Object 'Collections.Generic.Dictionary[string,string]' ([StringComparer]::OrdinalIgnoreCase) + $positions = New-Object 'Collections.Generic.Dictionary[string,int]' ([StringComparer]::OrdinalIgnoreCase) + for ($position = 0; $position -lt $recordsArray.Length; $position++) { + $key = [string]$recordsArray[$position].ObjectGuid + $positions[$key] = $position + $fingerprints[$key] = Get-PraDataFingerprint -Data $recordsArray[$position] + } + $schema = [int](Get-PraValue $data 'SchemaVersion' 1) $entry = [pscustomobject]@{ - Receipt=$Receipt; Data=$Receipt.Data; Path=[string]$Receipt.Path; Hash=[string]$Receipt.Hash - RawPath=$RawPath; RawHash=$RawHash; Environment=[string]$Receipt.Data.Environment - SchemaVersion=[int](Get-PraValue $Receipt.Data 'SchemaVersion' 1); RawFormat=[string](Get-PraValue $Receipt.Data 'RawFormat' '') - Operation=[string]$Receipt.Data.Operation; Legacy=[bool]$Receipt.Legacy; Guids=$guids - DataFingerprint=(Get-PraDataFingerprint -Data $Receipt.Data) + Receipt=$Receipt; Data=$data; Path=[string]$Receipt.Path; Hash=[string]$Receipt.Hash + RawPath=$RawPath; RawHash=$RawHash; Environment=[string]$data.Environment + SchemaVersion=$schema; RawFormat=[string](Get-PraValue $data 'RawFormat' '') + Operation=[string]$data.Operation; Legacy=[bool]$Receipt.Legacy + RecordsArray=$recordsArray; RecordRefs=[object[]]$recordsArray.Clone(); Positions=$positions; Fingerprints=$fingerprints + EnvelopeFingerprint=(Get-PraDataFingerprint -Data (Get-PraReceiptEnvelope -Data $data)) + JsonStamp=(Get-PraFileStamp -Path ([string]$Receipt.Path)) + SidecarStamp=$(if ($schema -ge 2) { Get-PraFileStamp -Path ([string]$Receipt.Path + '.sha256') } else { '' }) + RawStamp=$(if ($schema -ge 2) { Get-PraFileStamp -Path $RawPath } else { '' }) + ChecksSinceFileHash=0 } $registry = Get-PraReceiptRegistry -Context $Context $registry.Add($entry) @@ -207,9 +277,15 @@ function Get-PraReceiptEntry { } function Assert-PraReceiptIntegrity { - <# The backup is unchanged in memory and on disk (JSON, .sha256, CLIXML) since its validation. #> + <# + .SYNOPSIS + The backup is unchanged in memory and on disk (JSON, .sha256, CLIXML) since its validation. + .DESCRIPTION + -Full: the fingerprint of every record and the SHA-256 of the three files. Without it: the fields of the receipt, the record of -ObjectGuid, and the length and + last write time of the three files; the SHA-256 of the files is computed again after every ReceiptFileHashEvery checks of that kind. + #> [CmdletBinding()] - param([hashtable]$Context, $Entry) + param([hashtable]$Context, $Entry, [string]$ObjectGuid = '', [switch]$Full) $receipt = $Entry.Receipt if (-not (Test-PraOrdinalIgnoreCaseEqual $Entry.Environment $Context.Config.Environment) -or -not (Test-PraOrdinalIgnoreCaseEqual $receipt.Path $Entry.Path) -or -not (Test-PraOrdinalIgnoreCaseEqual $receipt.Data.Environment $Entry.Environment) -or -not (Test-PraOrdinalEqual $receipt.Data.Operation $Entry.Operation) -or @@ -219,14 +295,44 @@ function Assert-PraReceiptIntegrity { -not (Test-PraOrdinalEqual $receipt.Hash $Entry.Hash) -or -not [object]::ReferenceEquals($receipt.Data, $Entry.Data)) { throw 'Backup receipt changed, or it belongs to another context.' } - if (-not (Test-PraOrdinalEqual (Get-PraDataFingerprint -Data $receipt.Data) $Entry.DataFingerprint)) { throw 'Backup content changed in memory since its validation.' } - if (-not (Test-PraOrdinalEqual (Get-PraHash -Path $Entry.Path) $Entry.Hash)) { throw 'Backup JSON file changed since its validation.' } - if ($Entry.SchemaVersion -ge 2) { - $sidecar = (Get-Content -LiteralPath ($Entry.Path + '.sha256') -Raw -ErrorAction Stop).Trim() - if (-not (Test-PraOrdinalIgnoreCaseEqual $sidecar $Entry.Hash)) { throw 'Backup .sha256 file changed since its validation.' } - if (-not (Test-PraOrdinalIgnoreCaseEqual $receipt.Data.RawHash $Entry.RawHash) -or - -not (Test-PraOrdinalIgnoreCaseEqual ([IO.Path]::GetFileName($Entry.RawPath)) $receipt.Data.RawFile) -or - -not (Test-PraOrdinalEqual (Get-PraHash -Path $Entry.RawPath) $Entry.RawHash)) { throw 'Backup CLIXML file changed since its validation.' } + $memoryChanged = 'Backup content changed in memory since its validation.' + if (-not [object]::ReferenceEquals($receipt.Data.Records, $Entry.RecordsArray)) { throw $memoryChanged } + if (-not (Test-PraOrdinalEqual (Get-PraDataFingerprint -Data (Get-PraReceiptEnvelope -Data $receipt.Data)) $Entry.EnvelopeFingerprint)) { throw $memoryChanged } + if ($Full -or -not $ObjectGuid) { + for ($position = 0; $position -lt $Entry.RecordRefs.Length; $position++) { + $record = $Entry.RecordsArray[$position] + $expected = '' + if (-not [object]::ReferenceEquals($record, $Entry.RecordRefs[$position]) -or -not $Entry.Fingerprints.TryGetValue([string]$record.ObjectGuid, [ref]$expected) -or + -not (Test-PraOrdinalEqual (Get-PraDataFingerprint -Data $record) $expected)) { throw $memoryChanged } + } + } + else { + $position = 0 + if (-not $Entry.Positions.TryGetValue($ObjectGuid, [ref]$position)) { throw "Object not covered by the validated backup: $ObjectGuid" } + $record = $Entry.RecordsArray[$position] + if (-not [object]::ReferenceEquals($record, $Entry.RecordRefs[$position]) -or + -not (Test-PraOrdinalEqual (Get-PraDataFingerprint -Data $record) $Entry.Fingerprints[$ObjectGuid])) { throw $memoryChanged } + } + $hashFiles = $Full -or -not $ObjectGuid -or (++$Entry.ChecksSinceFileHash -ge $script:ReceiptFileHashEvery) + if ($hashFiles) { + $Entry.ChecksSinceFileHash = 0 + if (-not (Test-PraOrdinalEqual (Get-PraHash -Path $Entry.Path) $Entry.Hash)) { throw 'Backup JSON file changed since its validation.' } + if ($Entry.SchemaVersion -ge 2) { + $sidecar = (Get-Content -LiteralPath ($Entry.Path + '.sha256') -Raw -ErrorAction Stop).Trim() + if (-not (Test-PraOrdinalIgnoreCaseEqual $sidecar $Entry.Hash)) { throw 'Backup .sha256 file changed since its validation.' } + if (-not (Test-PraOrdinalIgnoreCaseEqual $receipt.Data.RawHash $Entry.RawHash) -or + -not (Test-PraOrdinalIgnoreCaseEqual ([IO.Path]::GetFileName($Entry.RawPath)) $receipt.Data.RawFile) -or + -not (Test-PraOrdinalEqual (Get-PraHash -Path $Entry.RawPath) $Entry.RawHash)) { throw 'Backup CLIXML file changed since its validation.' } + } + } + else { + if (-not (Test-PraOrdinalEqual (Get-PraFileStamp -Path $Entry.Path) $Entry.JsonStamp)) { throw 'Backup JSON file changed since its validation.' } + if ($Entry.SchemaVersion -ge 2) { + if (-not (Test-PraOrdinalEqual (Get-PraFileStamp -Path ($Entry.Path + '.sha256')) $Entry.SidecarStamp)) { throw 'Backup .sha256 file changed since its validation.' } + if (-not (Test-PraOrdinalIgnoreCaseEqual $receipt.Data.RawHash $Entry.RawHash) -or + -not (Test-PraOrdinalIgnoreCaseEqual ([IO.Path]::GetFileName($Entry.RawPath)) $receipt.Data.RawFile) -or + -not (Test-PraOrdinalEqual (Get-PraFileStamp -Path $Entry.RawPath) $Entry.RawStamp)) { throw 'Backup CLIXML file changed since its validation.' } + } } } @@ -510,71 +616,120 @@ function Find-PraConvertedBatch { #> [CmdletBinding()] param([hashtable]$Context, [string]$ObjectGuid) + $found = Find-PraConvertedBatches -Context $Context -ObjectGuid @($ObjectGuid) + $holder = $null + if ($found.TryGetValue($ObjectGuid, [ref]$holder)) { return $holder } + return $null +} + +function Find-PraConvertedBatches { + <# + .SYNOPSIS + Find-PraConvertedBatch for many objects with one search of the backup folder: a dictionary (GUID in any letter case) of the batch of each object that has one. + .DESCRIPTION + Each State file is read once, and each Convert backup of a candidate batch is read once, however many objects are asked for. + #> + [CmdletBinding()] + param([hashtable]$Context, [AllowEmptyCollection()][string[]]$ObjectGuid) + $result = New-Object 'Collections.Generic.Dictionary[string,object]' ([StringComparer]::OrdinalIgnoreCase) try { $root = [string]$Context.Config.Storage.BackupFolder - if (-not $root -or -not (Test-Path -LiteralPath $root -PathType Container)) { return $null } + if (-not $root -or -not $ObjectGuid.Count -or -not (Test-Path -LiteralPath $root -PathType Container)) { return , $result } $environment = [string]$Context.Config.Environment - $candidates = New-Object 'Collections.Generic.List[object]' - $rolledBack = New-Object 'Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase) + $wanted = New-Object 'Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase) + foreach ($guid in $ObjectGuid) { if ($guid) { [void]$wanted.Add($guid) } } + $candidates = New-Object 'Collections.Generic.Dictionary[string,object]' ([StringComparer]::OrdinalIgnoreCase) + $rolledBack = New-Object 'Collections.Generic.Dictionary[string,object]' ([StringComparer]::OrdinalIgnoreCase) foreach ($folder in @(Get-ChildItem -LiteralPath $root -Directory -Recurse -ErrorAction Stop | Where-Object { $_.Name -match '^(Batch|Finalize)-[0-9a-f]{32}\z' })) { foreach ($stateFile in @(Get-ChildItem -LiteralPath $folder.FullName -File -Filter 'State-*.json' -ErrorAction Stop)) { try { $state = Get-Content -LiteralPath $stateFile.FullName -Raw -Encoding UTF8 -ErrorAction Stop | ConvertFrom-PraJson } catch { continue } $stateEnvironment = [string](Get-PraValue $state 'Environment' '') if ($stateEnvironment -and -not (Test-PraOrdinalIgnoreCaseEqual $stateEnvironment $environment)) { continue } - $stateRecords = Get-PraValue $state 'Records' @() - if (@($stateRecords | Where-Object { Test-PraOrdinalIgnoreCaseEqual ([string]$_.ObjectGuid) $ObjectGuid }).Count -ne 1) { continue } $operation = [string](Get-PraValue $state 'Operation' '') - if (Test-PraOrdinalEqual $operation 'Recover') { - $source = [string](Get-PraValue $state 'SourceBackupHash' '') - if ($source) { $null = $rolledBack.Add($source) } - } - elseif ((Test-PraOrdinalEqual $operation 'Convert') -and $folder.Name.StartsWith('Batch-', [StringComparison]::OrdinalIgnoreCase)) { - $created = [datetime]::MinValue - if (-not [datetime]::TryParse([string](Get-PraValue $state 'CreatedUtc' ''), [Globalization.CultureInfo]::InvariantCulture, [Globalization.DateTimeStyles]::RoundtripKind, [ref]$created)) { $created = $folder.LastWriteTimeUtc } - $candidates.Add([pscustomobject]@{ Folder = $folder; Ticks = $created.ToUniversalTime().Ticks; BackupHash = [string](Get-PraValue $state 'BackupHash' '') }) + $isRecover = Test-PraOrdinalEqual $operation 'Recover' + $isConvert = (Test-PraOrdinalEqual $operation 'Convert') -and $folder.Name.StartsWith('Batch-', [StringComparison]::OrdinalIgnoreCase) + if (-not $isRecover -and -not $isConvert) { continue } + $source = [string](Get-PraValue $state 'SourceBackupHash' '') + $created = [datetime]::MinValue + if ($isConvert -and -not [datetime]::TryParse([string](Get-PraValue $state 'CreatedUtc' ''), [Globalization.CultureInfo]::InvariantCulture, [Globalization.DateTimeStyles]::RoundtripKind, [ref]$created)) { $created = $folder.LastWriteTimeUtc } + $backupHash = [string](Get-PraValue $state 'BackupHash' '') + $index = Get-PraRecordIndex (Get-PraValue $state 'Records' @()) + foreach ($guid in $wanted) { + if (-not $index.ByGuid.ContainsKey($guid) -or $index.Duplicates.Contains($guid)) { continue } + if ($isRecover) { + if (-not $source) { continue } + if (-not $rolledBack.ContainsKey($guid)) { $rolledBack[$guid] = New-Object 'Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase) } + $null = $rolledBack[$guid].Add($source) + } + else { + if (-not $candidates.ContainsKey($guid)) { $candidates[$guid] = New-Object 'Collections.Generic.List[object]' } + $candidates[$guid].Add([pscustomobject]@{ Folder = $folder; Ticks = $created.ToUniversalTime().Ticks; BackupHash = $backupHash }) + } } } } - # Newest first (the name breaks a tie); the sort is on the time, not on the folder name. - $newestFirst = @($candidates | ForEach-Object { [pscustomobject]@{ Key = (([int64]::MaxValue - $_.Ticks).ToString('D20', [Globalization.CultureInfo]::InvariantCulture) + '|' + $_.Folder.Name); Item = $_ } } | Get-PraOrdinalSorted -Property Key | ForEach-Object Item) - foreach ($candidate in $newestFirst) { - if ($candidate.BackupHash -and $rolledBack.Contains($candidate.BackupHash)) { continue } - $folder = $candidate.Folder - $batchId = $folder.Name.Substring(6) - foreach ($file in @(Get-ChildItem -LiteralPath $folder.FullName -File -Filter 'Convert-*.json' -ErrorAction Stop)) { - try { $data = Get-Content -LiteralPath $file.FullName -Raw -Encoding UTF8 -ErrorAction Stop | ConvertFrom-PraJson } catch { continue } - if (-not (Test-PraOrdinalEqual ([string](Get-PraValue $data 'Operation' '')) 'Convert')) { continue } - if (@(@($data.Records) | Where-Object { Test-PraOrdinalIgnoreCaseEqual ([string]$_.ObjectGuid) $ObjectGuid }).Count -eq 1) { - return [pscustomobject]@{ BatchId = $batchId; ShortId = $batchId.Substring(0, 8); Folder = $folder.FullName } + $convertFiles = New-Object 'Collections.Generic.Dictionary[string,object]' ([StringComparer]::OrdinalIgnoreCase) + foreach ($guid in $wanted) { + $list = $null + if (-not $candidates.TryGetValue($guid, [ref]$list)) { continue } + $hashes = $null; $null = $rolledBack.TryGetValue($guid, [ref]$hashes) + # Newest first (the name breaks a tie); the sort is on the time, not on the folder name. + $newestFirst = @($list | ForEach-Object { [pscustomobject]@{ Key = (([int64]::MaxValue - $_.Ticks).ToString('D20', [Globalization.CultureInfo]::InvariantCulture) + '|' + $_.Folder.Name); Item = $_ } } | Get-PraOrdinalSorted -Property Key | ForEach-Object Item) + foreach ($candidate in $newestFirst) { + if ($candidate.BackupHash -and $null -ne $hashes -and $hashes.Contains($candidate.BackupHash)) { continue } + $folder = $candidate.Folder + $batchId = $folder.Name.Substring(6) + foreach ($file in @(Get-ChildItem -LiteralPath $folder.FullName -File -Filter 'Convert-*.json' -ErrorAction Stop)) { + if (-not $convertFiles.ContainsKey($file.FullName)) { + $index = $null + try { + $data = Get-Content -LiteralPath $file.FullName -Raw -Encoding UTF8 -ErrorAction Stop | ConvertFrom-PraJson + if (Test-PraOrdinalEqual ([string](Get-PraValue $data 'Operation' '')) 'Convert') { $index = New-PraRecordIndex -Record (Get-PraValue $data 'Records' @()) } + } catch { $index = $null } + $convertFiles[$file.FullName] = $index + } + $held = $convertFiles[$file.FullName] + if ($null -ne $held -and $held.ByGuid.ContainsKey($guid) -and -not $held.Duplicates.Contains($guid)) { + $result[$guid] = [pscustomobject]@{ BatchId = $batchId; ShortId = $batchId.Substring(0, 8); Folder = $folder.FullName } + break + } } + if ($result.ContainsKey($guid)) { break } } } } catch { Write-PraLog -Context $Context -Message ('The backup folder could not be searched for a batch of this object: {0}' -f $_.Exception.Message) -Level Detail } - return $null + return , $result } function Get-PraJournalTouchedObject { <# .SYNOPSIS The objects (GUIDs, ignoring the case) that the journal of a batch shows as written or about to be written: a Started or Applied line of an AD write. - An object that has such a line may be changed, whatever the batch proved. A missing or unreadable journal gives an empty set. + An object that has such a line may be changed, whatever the batch proved. A missing or unreadable journal gives an empty set. A line that cannot be parsed is skipped, + the others are still read; with -Context ONE warning says how many were skipped. #> [CmdletBinding()] - param([string]$Path) + param([string]$Path, [hashtable]$Context) $set = New-Object 'Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase) if (-not $Path -or -not [IO.File]::Exists($Path)) { return , $set } + $skipped = 0 try { foreach ($line in [IO.File]::ReadLines($Path)) { + if ($line.Trim().Length -and -not $line.TrimStart().StartsWith('{', [StringComparison]::Ordinal)) { $skipped++; continue } if (-not ($line.Contains('"Status":"Started"') -or $line.Contains('"Status":"Applied"'))) { continue } - $entry = $line | ConvertFrom-PraJson - if (Test-PraOrdinalIn ([string](Get-PraValue $entry 'Operation' '')) @('Set-ADUser', 'Add-ADGroupMember', 'Remove-ADGroupMember')) { - $target = [string](Get-PraValue $entry 'Target' '') - if ($target -and -not (Test-PraOrdinalEqual $target '*')) { [void]$set.Add($target) } + try { + $entry = $line | ConvertFrom-PraJson + if (Test-PraOrdinalIn ([string](Get-PraValue $entry 'Operation' '')) @('Set-ADUser', 'Add-ADGroupMember', 'Remove-ADGroupMember')) { + $target = [string](Get-PraValue $entry 'Target' '') + if ($target -and -not (Test-PraOrdinalEqual $target '*')) { [void]$set.Add($target) } + } } + catch { $skipped++ } } } catch { $null = $_ } + if ($skipped -and $null -ne $Context) { Write-PraItem -Context $Context -Status Warn -Text ('{0} line(s) of the journal {1} cannot be read and were skipped: an object that only they name is not listed as written.' -f $skipped, (Split-Path $Path -Leaf)) } return , $set } @@ -605,8 +760,11 @@ function Find-PraRecoverOfBatch { if ($stateEnvironment -and -not (Test-PraOrdinalIgnoreCaseEqual $stateEnvironment $environment)) { continue } if (-not (Test-PraOrdinalIgnoreCaseEqual ([string](Get-PraValue $state 'SourceBackupHash' '')) $SourceHash)) { continue } $stateRecords = Get-PraValue $state 'Records' @() - $listed = @($stateRecords | ForEach-Object { [string]$_.ObjectGuid }) - if ($ObjectGuid.Count -and -not @($ObjectGuid | Where-Object { Test-PraOrdinalIn $_ $listed -IgnoreCase }).Count) { continue } + $listed = New-Object 'Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase) + foreach ($listedRecord in @($stateRecords)) { [void]$listed.Add([string]$listedRecord.ObjectGuid) } + $anyListed = -not $ObjectGuid.Count + foreach ($wantedGuid in $ObjectGuid) { if ($listed.Contains($wantedGuid)) { $anyListed = $true; break } } + if (-not $anyListed) { continue } if (-not $id) { continue } return [pscustomobject]@{ BatchId = $id.ToLowerInvariant(); ShortId = $id.Substring(0, 8).ToLowerInvariant(); Folder = $folder.FullName; Basis = 'State' } } @@ -626,7 +784,11 @@ function Find-PraRecoverOfBatch { if (-not [IO.File]::Exists($journal)) { $basis = 'Unknown' } else { $touched = Get-PraJournalTouchedObject -Path $journal - if ($ObjectGuid.Count) { if (-not @($ObjectGuid | Where-Object { $touched.Contains($_) }).Count) { continue } } + if ($ObjectGuid.Count) { + $anyTouched = $false + foreach ($wantedGuid in $ObjectGuid) { if ($touched.Contains($wantedGuid)) { $anyTouched = $true; break } } + if (-not $anyTouched) { continue } + } elseif (-not $touched.Count) { continue } } return [pscustomobject]@{ BatchId = $id.ToLowerInvariant(); ShortId = $id.Substring(0, 8).ToLowerInvariant(); Folder = $folder.FullName; Basis = $basis } @@ -801,9 +963,10 @@ function Get-PraTarget { } if ($alreadyRemote.Count) { $batchIds = New-Object 'Collections.Generic.List[string]' + $holders = Find-PraConvertedBatches -Context $Context -ObjectGuid $alreadyRemote.ToArray() foreach ($remoteId in $alreadyRemote) { - $holder = Find-PraConvertedBatch $Context $remoteId - if ($null -ne $holder -and -not (Test-PraOrdinalIn -IgnoreCase $holder.ShortId @($batchIds))) { $batchIds.Add([string]$holder.ShortId) } + $holder = $null + if ($holders.TryGetValue($remoteId, [ref]$holder) -and -not (Test-PraOrdinalIn -IgnoreCase $holder.ShortId @($batchIds))) { $batchIds.Add([string]$holder.ShortId) } } if ($batchIds.Count) { $Context.ContinueSteps = @(Get-PraContinueStep $Context @($batchIds)) @@ -1212,8 +1375,13 @@ function Test-PraConsistencyGuidSchema { try { $schema = [string](Get-ADRootDSE -Server $Context.Server -ErrorAction Stop).schemaNamingContext if ($schema) { $available = (@(Get-ADObject -SearchBase $schema -LDAPFilter '(&(objectClass=attributeSchema)(lDAPDisplayName=mS-DS-ConsistencyGuid))' -Server $Context.Server -ErrorAction Stop).Count -eq 1) } + else { $Context['_PraConsistencyGuidSchemaUnreadable'] = $true } + } + catch { + # The anchors recorded for trustees are then incomplete: the record says so (SharedTrusteeAnchorsIncomplete) and a trustee only has to be a synchronised account. + $Context['_PraConsistencyGuidSchemaUnreadable'] = $true + Write-PraLog -Context $Context -Message ('ms-DS-ConsistencyGuid: schema not readable, only the objectGUID is recorded for trustees ({0})' -f $_.Exception.Message) -Level Detail } - catch { Write-PraLog -Context $Context -Message ('ms-DS-ConsistencyGuid: schema not readable, only the objectGUID is recorded for trustees ({0})' -f $_.Exception.Message) -Level Detail } $Context['_PraConsistencyGuidSchema'] = $available return $available } @@ -1583,7 +1751,7 @@ function New-PraPlan { $record = [ordered]@{ ObjectGuid=([guid]$user.ObjectGUID).ToString(); DistinguishedName=[string]$user.DistinguishedName SourceAnchor=[ordered]@{ ObjectGuid=[string](ConvertTo-PraImmutableId -Value $user.ObjectGUID); ConsistencyGuid=[string](ConvertTo-PraImmutableId -Value (Get-PraValue $user 'mS-DS-ConsistencyGuid' $null)) } - SharedTrusteeAnchors=$trusteeAnchors + SharedTrusteeAnchors=$trusteeAnchors; SharedTrusteeAnchorsIncomplete=[bool](Get-PraValue $Context '_PraConsistencyGuidSchemaUnreadable' $false) SamAccountName=[string]$user.SamAccountName; UserPrincipalName=[string]$user.UserPrincipalName; DisplayName=[string](Get-PraValue $user 'DisplayName' $user.SamAccountName) CapturedUtc=[DateTime]::UtcNow.ToString('o'); CapturedUsnChanged=(Get-PraUsn $user); IsShared=$shared; RequestedOperation=$Operation Attributes=$before; PlannedAttributes=$desired; Licensing=$licensing @@ -1594,7 +1762,8 @@ function New-PraPlan { $row = New-PraRow $Context $record if ($null -ne $SourceRecord) { $row.BackupRec = $SourceRecord } else { $row.BackupRec = [pscustomobject]$record } $row.PreserveCloudMailbox = [bool]$preserveMailbox; $row.PreserveLicense = [bool]$preserveLicense - $ignoredEntries = Get-PraValue (Get-PraValue $Context '_PraIgnoredTrustees' @{}) $record.ObjectGuid @() + $ignoredTable = if ($Context.ContainsKey('_PraIgnoredTrustees')) { $Context['_PraIgnoredTrustees'] } else { @{} } + $ignoredEntries = if ($ignoredTable.ContainsKey($record.ObjectGuid)) { $ignoredTable[$record.ObjectGuid] } else { @() } $ignoredEntries = @($ignoredEntries | Where-Object { $_ }) if ($shared -and (Test-PraOrdinalIgnoreCaseEqual $Operation 'Convert') -and $ignoredEntries.Count) { $row.Warnings = 'Permission entries ignored (account unknown in AD): ' + ($ignoredEntries -join '; ') } $row.IsShared = $shared; $row.SharedFullAccess = @($permissions.FullAccess); $row.SharedSendAs = @($permissions.SendAs); $row.SharedSendOnBehalf = @($permissions.SendOnBehalf) @@ -1670,6 +1839,7 @@ function Assert-PraStoredRecord { foreach ($text in @(Get-PraList $trusteeStored ([string]$name))) { if ($text -isnot [string] -or $text -cnotmatch '^[A-Za-z0-9+/]{22}==\z') { throw 'Backup: invalid trustee source anchor.' } } } } + if ($null -ne (Get-PraValue $Record 'SharedTrusteeAnchorsIncomplete' $null) -and (Get-PraValue $Record 'SharedTrusteeAnchorsIncomplete' $null) -isnot [bool]) { throw 'Backup: invalid trustee anchor marker.' } if (-not $Legacy) { if ($Record.CapturedUsnChanged -isnot [string] -or $Record.CapturedUsnChanged -notmatch '^[1-9][0-9]*\z') { throw 'Backup: original uSNChanged missing or invalid.' } $null = [int64]::Parse($Record.CapturedUsnChanged, [Globalization.CultureInfo]::InvariantCulture) @@ -1696,7 +1866,7 @@ function Import-PraBackup { $registry = Get-PraReceiptRegistry -Context $Context foreach ($entry in $registry) { if (Test-PraOrdinalIgnoreCaseEqual $entry.Path $pathResolved) { - Assert-PraReceiptIntegrity -Context $Context -Entry $entry + Assert-PraReceiptIntegrity -Context $Context -Entry $entry -Full Write-PraLog -Context $Context -Message ("BACKUP INTEGRITY | already validated | $pathResolved | hashes re-read") -Level Debug return $entry.Receipt } @@ -1866,13 +2036,14 @@ function Save-PraBatch { function Assert-PraReceipt { <# .SYNOPSIS - The object is covered by the validated backup, and the backup is unchanged. + The object is covered by the validated backup, and the backup is unchanged: the cheap check of Assert-PraReceiptIntegrity for the object, or with -Full (or + without an object) the complete one. #> [CmdletBinding()] - param([hashtable]$Context, $Receipt, [string]$ObjectGuid) + param([hashtable]$Context, $Receipt, [string]$ObjectGuid = '', [switch]$Full) $entry = Get-PraReceiptEntry -Context $Context -Receipt $Receipt - if (-not $entry.Guids.Contains($ObjectGuid)) { throw "Object not covered by the validated backup: $ObjectGuid" } - Assert-PraReceiptIntegrity -Context $Context -Entry $entry + if ($ObjectGuid -and -not $entry.Positions.ContainsKey($ObjectGuid)) { throw "Object not covered by the validated backup: $ObjectGuid" } + Assert-PraReceiptIntegrity -Context $Context -Entry $entry -ObjectGuid $ObjectGuid -Full:$Full } function Assert-PraCurrentState { @@ -1907,7 +2078,8 @@ function Invoke-PraAdWrite { #> [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Low')] param([hashtable]$Context, $Receipt, $Plan, [string]$Operation, [scriptblock]$Write) - if ([bool](Get-PraValue $Context 'OperationFailed' $false) -or $Context.Issues.Count -gt 0 -or @($Context.Rows | Where-Object FinalStatus -eq 'Error').Count -gt 0) { throw 'Safety stop: no AD write after an error in this run.' } + # The batch refuses to start with a row in error (Invoke-PraAdBatch) and stops at the first error it meets: here the row of the object and the run state are enough. + if ([bool](Get-PraValue $Context 'OperationFailed' $false) -or $Context.Issues.Count -gt 0 -or (Test-PraOrdinalEqual ([string]$Plan.Row.FinalStatus) 'Error')) { throw 'Safety stop: no AD write after an error in this run.' } if (-not $Context.AllowMutation -or (-not (Test-PraOrdinalIgnoreCaseEqual $Context.Mode 'Apply')) -or (Test-PraOrdinalIgnoreCaseEqual $Context.Action 'Check') -or $WhatIfPreference) { throw 'Safety stop: AD writes are not allowed in this mode.' } if (-not $PSCmdlet.ShouldProcess($Plan.Record.ObjectGuid, $Operation)) { throw 'AD write not authorised (ShouldProcess).' } Assert-PraReceipt $Context $Receipt $Plan.Record.ObjectGuid @@ -1934,13 +2106,22 @@ function Invoke-PraAdPreview { #> [CmdletBinding()] param([hashtable]$Context, [AllowEmptyCollection()][object[]]$Plans) + Add-PraPlanRow -Context $Context -Plans $Plans foreach ($plan in $Plans) { - if (-not $Context.Rows.Contains($plan.Row)) { $Context.Rows.Add($plan.Row) } Write-PraAdDelta -Context $Context -Plan $plan -Stage Planned $plan.Previewed = $true } } +function Add-PraPlanRow { + <# Adds the row of each plan to the results of the run; a row that is already there is not added again. One set of the rows, not a search of the list for each plan. #> + [CmdletBinding()] + param([hashtable]$Context, [AllowEmptyCollection()][object[]]$Plans) + $known = New-Object 'Collections.Generic.HashSet[object]' ([Collections.Generic.ReferenceEqualityComparer]::Instance) + foreach ($row in $Context.Rows) { [void]$known.Add($row) } + foreach ($plan in $Plans) { if ($known.Add($plan.Row)) { $Context.Rows.Add($plan.Row) } } +} + function Test-PraAdAccessDenied { <# True when an Active Directory error is a refusal of the account: UnauthorizedAccessException, the directory error 8344 (insufficient access rights) or 5 (access denied) in the error id (they do not depend on the language of Windows), or the English words. #> [CmdletBinding()] @@ -1969,7 +2150,7 @@ function Invoke-PraAdBatch { $Context.LastVerifiedReceipt = $null if ([bool](Get-PraValue $Context 'OperationFailed' $false) -or $Context.Issues.Count -gt 0 -or @($Context.Rows | Where-Object FinalStatus -eq 'Error').Count -gt 0) { throw 'No new batch after an error in this run.' } if (-not $Plans.Count) { Write-PraItem -Context $Context -Status Skip -Text 'Nothing to do.'; return $null } - foreach ($plan in $Plans) { if (-not $Context.Rows.Contains($plan.Row)) { $Context.Rows.Add($plan.Row) } } + Add-PraPlanRow -Context $Context -Plans $Plans $receipt = $null; $stateWritten = $false try { foreach ($plan in $Plans) { if (-not [bool](Get-PraValue $plan 'Previewed' $false)) { Write-PraAdDelta -Context $Context -Plan $plan -Stage Planned } } @@ -2026,6 +2207,8 @@ function Invoke-PraAdBatch { throw } } + # End of the writes: the backup is checked in full (every record, every file) before the proof that relies on it is written. + Assert-PraReceipt -Context $Context -Receipt $receipt -Full $state = [ordered]@{ SchemaVersion=2; Operation=$Operation; Kind='ADVerified'; Environment=$Context.Config.Environment; RunId=$Context.RunId BackupFile=[IO.Path]::GetFileName($receipt.Path); BackupHash=$receipt.Hash; SourceBackupHash=$Context.SourceBackupHash @@ -2162,18 +2345,43 @@ function Import-PraProof { elseif (@($data.Records).Count -ne $planned) { throw 'AD proof incomplete compared with its backup.' } $expectedSource = if ((Test-PraOrdinalIgnoreCaseEqual $Operation 'Convert')) { $data.BackupHash } else { $data.SourceBackupHash } if (-not (Test-PraOrdinalIgnoreCaseEqual $expectedSource $Source.Hash)) { throw 'AD proof built from another Convert batch.' } - $seen = @{} + $seen = New-Object 'Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase) + $sourceIndex = Get-PraRecordIndex $Source.Data.Records + $backupIndex = Get-PraRecordIndex $receipt.Data.Records + $allowed = switch ($Operation) { Convert { @('Convert') } Recover { @('Recover','Deprovision','AlreadyRecovered') } Finalize { @('Recover','RestoreTag','AlreadyRecovered') } Retention { @('RestoreTag') } default { @() } } foreach ($record in @($data.Records)) { - if ($record.ADVerified -isnot [bool] -or -not $record.ADVerified -or -not (Test-PraOrdinalIn -IgnoreCase $record.ObjectGuid @($Source.Data.Records.ObjectGuid)) -or $seen.ContainsKey($record.ObjectGuid)) { throw 'AD proof: invalid or duplicated object.' } - $captured = @($receipt.Data.Records | Where-Object { Test-PraOrdinalIgnoreCaseEqual $_.ObjectGuid $record.ObjectGuid }) - $allowed = switch ($Operation) { Convert { @('Convert') } Recover { @('Recover','Deprovision','AlreadyRecovered') } Finalize { @('Recover','RestoreTag','AlreadyRecovered') } Retention { @('RestoreTag') } default { @() } } - if ($captured.Count -ne 1 -or -not (Test-PraOrdinalIn $record.Operation $allowed) -or -not (Test-PraOrdinalEqual $record.Operation $captured[0].RequestedOperation) -or + if ($record.ADVerified -isnot [bool] -or -not $record.ADVerified -or $null -eq (Find-PraRecord $sourceIndex ([string]$record.ObjectGuid)) -or $seen.Contains([string]$record.ObjectGuid)) { throw 'AD proof: invalid or duplicated object.' } + $captured = Find-PraRecord $backupIndex ([string]$record.ObjectGuid) + if ($null -eq $captured -or $backupIndex.Duplicates.Contains([string]$record.ObjectGuid) -or -not (Test-PraOrdinalIn $record.Operation $allowed) -or -not (Test-PraOrdinalEqual $record.Operation $captured.RequestedOperation) -or $record.VerifiedUsnChanged -isnot [string] -or $record.VerifiedUsnChanged -notmatch '^[1-9][0-9]*\z') { throw 'AD proof: operation or version does not match the backup.' } $null = [int64]::Parse($record.VerifiedUsnChanged, [Globalization.CultureInfo]::InvariantCulture) - $seen[$record.ObjectGuid] = $true + [void]$seen.Add([string]$record.ObjectGuid) } if (-not $seen.Count) { throw 'AD proof is empty.' } - return [pscustomobject]@{ Data=$data; Path=$Path; Hash=$hash; Receipt=$receipt; Partial=$partialField; PlannedCount=$planned } + $proofIndex = Get-PraRecordIndex $data.Records + return [pscustomobject]@{ Data=$data; Path=$Path; Hash=$hash; Receipt=$receipt; Partial=$partialField; PlannedCount=$planned; VerifiedIndex=$proofIndex } +} + +function Assert-PraCloudProofObject { + <# + .SYNOPSIS + Before an Exchange Online write: the object is in the verified AD proof of the batch. + .DESCRIPTION + The proof is read and checked in full the first time (Import-PraProof, which also checks the backup in full); the answer is kept in the run context with the stamps + (length and last write time) of the State file and its .sha256 file, and used for every later write until one of them changes. The caller checks the backup + for the object with Assert-PraReceipt. + #> + [CmdletBinding()] + param([hashtable]$Context, [Parameter(Mandatory)][string]$ProofPath, [Parameter(Mandatory)]$Source, [Parameter(Mandatory)][string]$Operation, [Parameter(Mandatory)][string]$ObjectGuid) + $stamp = (Get-PraFileStamp -Path $ProofPath) + '|' + (Get-PraFileStamp -Path ($ProofPath + '.sha256')) + $check = if ($Context.ContainsKey('_PraProofCheck')) { $Context['_PraProofCheck'] } else { $null } + if ($null -eq $check -or -not (Test-PraOrdinalIgnoreCaseEqual $check.Path $ProofPath) -or -not [object]::ReferenceEquals($check.Source, $Source) -or + -not (Test-PraOrdinalIgnoreCaseEqual $check.Operation $Operation) -or -not (Test-PraOrdinalEqual $check.Stamp $stamp)) { + $proof = Import-PraProof $Context $ProofPath $Source $Operation + $check = [pscustomobject]@{ Path = $ProofPath; Source = $Source; Operation = $Operation; Stamp = $stamp; Index = $proof.VerifiedIndex } + $Context['_PraProofCheck'] = $check + } + if ($null -eq (Find-PraRecord $check.Index $ObjectGuid)) { throw 'Cloud write refused: the object is not in a verified AD phase.' } } function Assert-PraFollowupState { @@ -2185,10 +2393,12 @@ function Assert-PraFollowupState { [CmdletBinding()] param([hashtable]$Context, $Plan, $Proof) if (-not (Test-PraOrdinalIgnoreCaseEqual $Context.Server $Proof.Receipt.Data.Server)) { throw "Finalize: use the domain controller of the proof '$($Proof.Receipt.Data.Server)' (uSNChanged cannot be compared between DCs); set DomainController in the configuration." } - $verified = @($Proof.Data.Records | Where-Object { Test-PraOrdinalIgnoreCaseEqual $_.ObjectGuid $Plan.Record.ObjectGuid }) - $captured = @($Proof.Receipt.Data.Records | Where-Object { Test-PraOrdinalIgnoreCaseEqual $_.ObjectGuid $Plan.Record.ObjectGuid }) - if ($verified.Count -ne 1 -or $captured.Count -ne 1) { throw 'Finalize: object not in the AD proof.' } - $previous = $captured[0] + $planGuid = [string]$Plan.Record.ObjectGuid + $verifiedIndex = Get-PraRecordIndex $Proof.Data.Records + $capturedIndex = Get-PraRecordIndex $Proof.Receipt.Data.Records + $verifiedRecord = Find-PraRecord $verifiedIndex $planGuid + $previous = Find-PraRecord $capturedIndex $planGuid + if ($null -eq $verifiedRecord -or $null -eq $previous -or $verifiedIndex.Duplicates.Contains($planGuid) -or $capturedIndex.Duplicates.Contains($planGuid)) { throw 'Finalize: object not in the AD proof.' } if ($previous.Licensing.Enabled) { $group = Get-PraGroup $Context $previous.Licensing.GroupGuid if (-not (Test-PraOrdinalIgnoreCaseEqual $group.DistinguishedName $previous.Licensing.GroupDN) -or @@ -2216,7 +2426,7 @@ function Assert-PraFollowupState { # as the proof left it; at least one X500 entry must have been added or removed. Any other change still refuses the restore. Limit: an attribute # that the tool does not manage cannot be told apart from msDS-ExternalDirectoryObjectId by the version alone, so in that one situation it is not # detected (the managed attributes, the licence group, the DN and the non-X500 addresses are). - $versionKept = (Test-PraOrdinalEqual (Get-PraUsn $Plan.User) $verified[0].VerifiedUsnChanged) + $versionKept = (Test-PraOrdinalEqual (Get-PraUsn $Plan.User) $verifiedRecord.VerifiedUsnChanged) $sameDn = (Test-PraOrdinalEqual $Plan.User.DistinguishedName $previous.DistinguishedName) $writeback = $false if (-not $versionKept -and $sameDn) { @@ -2628,7 +2838,7 @@ function Invoke-PraSync { Export-ModuleMember -Function ConvertTo-PraLdapValue, Get-PraHash, Write-PraImmutableFile, New-PraPrivateDirectory, Write-PraJournal, Initialize-PraDirectory, Get-PraUser, Resolve-PraGroup, Get-PraGroupMember, Get-PraExpectedX500, Get-PraTarget, Find-PraRecoverOfBatch, Get-PraJournalTouchedObject, New-PraRow, New-PraPlan, Import-PraBackup, Invoke-PraAdPreview, Invoke-PraAdBatch, - Import-PraProof, Invoke-PraSync, Test-PraSyncServer, Start-PraSyncProbe, Invoke-PraAdReplication, Assert-PraReceipt, Test-PraStateEqual, Assert-PraFollowupState, Initialize-PraPermissionCache + Import-PraProof, Invoke-PraSync, Test-PraSyncServer, Start-PraSyncProbe, Invoke-PraAdReplication, Assert-PraReceipt, Assert-PraCloudProofObject, Test-PraStateEqual, Assert-PraFollowupState, Initialize-PraPermissionCache # SIG # Begin signature block # MIImKQYJKoZIhvcNAQcCoIImGjCCJhYCAQExDzANBglghkgBZQMEAgEFADB5Bgor diff --git a/package/module/PRA.Gui.psm1 b/package/module/PRA.Gui.psm1 index fa424a7..2dbb594 100644 --- a/package/module/PRA.Gui.psm1 +++ b/package/module/PRA.Gui.psm1 @@ -184,6 +184,19 @@ function Get-PraGuiFileHash { return (Get-FileHash -LiteralPath $Path -Algorithm SHA256 -ErrorAction Stop).Hash.ToLowerInvariant() } +$script:PraGuiHashCache = New-Object 'Collections.Generic.Dictionary[string,object]' ([StringComparer]::OrdinalIgnoreCase) + +function Get-PraGuiStampedHash { + <# SHA-256 of a batch file, computed again only when its length or last write time changed. Only for finding which batch file has a given hash; the files that a run relies on are hashed in full by Get-PraGuiGuard. #> + param([string]$Path) + $stamp = Get-PraGuiFileStamp $Path + $cached = $null + if ($script:PraGuiHashCache.TryGetValue($Path, [ref]$cached) -and [string]::Equals($cached.Stamp, $stamp, [StringComparison]::Ordinal)) { return [string]$cached.Hash } + $hash = Get-PraGuiFileHash $Path + $script:PraGuiHashCache[$Path] = [pscustomobject]@{ Stamp=$stamp; Hash=$hash } + return $hash +} + function ConvertTo-PraGuiHash { param([string]$Value) $hash=$Value.Trim() @@ -195,25 +208,71 @@ function Read-PraGuiBatch { <# -AnyEnvironment: the Environment of the file is recorded but not compared (the list of batches of every environment of the backup folder). #> param([string]$Path, [string]$Environment, [switch]$AnyEnvironment) $item = [pscustomobject]@{ Path=$Path; Folder=(Split-Path $Path -Parent); Operation='?'; BatchId=''; Status=''; Valid=$false; Data=$null; Label=''; CopyPaths=@(); Environment=''; EnvMismatch=$false } + try { + $core = Get-PraGuiBatchCore -Path $Path + $item.Operation = $core.Operation; $item.BatchId = $core.BatchId + if ($core.Error) { throw $core.Error } + $item.Environment = [string]$core.Data.Environment + if (-not $AnyEnvironment -and -not (Test-GuiOrdinal $item.Environment $Environment -IgnoreCase)) { $item.EnvMismatch=$true; throw 'Environment differs from configuration.' } + $problem = Get-PraGuiBatchCoreProblem -Core $core -Path $Path + if ($problem) { throw $problem } + $item.Data=$core.Data; $item.Valid=$true; $item.Status='Readable metadata - the engine still verifies everything' + } catch { $item.Status='INVALID: '+$_.Exception.Message } + $item.Label='{0} · {1} · {2}' -f $item.Operation,$item.BatchId,$item.Status + return $item +} + +# What the window knows of a batch file, read once and kept while the file and its .sha256 file keep their length and last write time: the window reads the state +# of the backup folder at every refresh, and a batch of thousands of objects is a large file. +$script:PraGuiBatchCache = New-Object 'Collections.Generic.Dictionary[string,object]' ([StringComparer]::OrdinalIgnoreCase) + +function Get-PraGuiFileStamp { + param([string]$Path) + $info = New-Object IO.FileInfo $Path + if (-not $info.Exists) { return 'missing' } + return ('{0}|{1}' -f $info.Length, $info.LastWriteTimeUtc.Ticks) +} + +function Get-PraGuiBatchCore { + <# The part of Read-PraGuiBatch that does not depend on the Environment of the window: Operation, BatchId, Error (the first refusal before the Environment check, or ''), and a small Data (the fields the window shows, the number of records and of shared mailboxes). #> + param([string]$Path) + $stamp = (Get-PraGuiFileStamp $Path) + '|' + (Get-PraGuiFileStamp ($Path + '.sha256')) + $cached = $null + if ($script:PraGuiBatchCache.TryGetValue($Path, [ref]$cached) -and (Test-GuiOrdinal $cached.Stamp $stamp)) { return $cached } + $core = [pscustomobject]@{ Stamp=$stamp; Operation='?'; BatchId=''; Error=''; Data=$null; Schema=0; Problem=$null } try { $data = [IO.File]::ReadAllText($Path) | ConvertFrom-PraJson - $item.Operation = [string](Get-PraGuiValue $data 'Operation' '?') - $item.BatchId = [string](Get-PraGuiValue $data 'BatchId' ((Split-Path $item.Folder -Leaf) -replace '^(Batch|Finalize)-','')) - if (-not (Test-GuiOrdinalIn $item.Operation @('Convert','Recover','RecoverFinalize'))) { throw 'Not a Convert, Recover or RecoverFinalize package.' } + $core.Operation = [string](Get-PraGuiValue $data 'Operation' '?') + $core.BatchId = [string](Get-PraGuiValue $data 'BatchId' ((Split-Path (Split-Path $Path -Parent) -Leaf) -replace '^(Batch|Finalize)-','')) + if (-not (Test-GuiOrdinalIn $core.Operation @('Convert','Recover','RecoverFinalize'))) { throw 'Not a Convert, Recover or RecoverFinalize package.' } if (Test-GuiOrdinal (Get-PraGuiValue $data 'Kind' '') 'ADVerified' -IgnoreCase) { throw 'State/proof is not a batch.' } - $item.Environment = [string](Get-PraGuiValue $data 'Environment' '') - if (-not $AnyEnvironment -and -not (Test-GuiOrdinal $item.Environment $Environment -IgnoreCase)) { $item.EnvMismatch=$true; throw 'Environment differs from configuration.' } + $records = @(if (Test-GuiOrdinal $core.Operation 'RecoverFinalize') { Get-PraGuiValue $data 'Items' @() } else { Get-PraGuiValue $data 'Records' @() }) + $shared = 0 + foreach ($record in $records) { if ($null -ne $record -and [bool](Get-PraGuiValue $record 'IsShared' $false)) { $shared++ } } $schema = Get-PraGuiValue $data 'SchemaVersion' 1 - $schema = $schema -as [int] # numeric comparisons below need an integer, not the raw JSON value (string, long or double) + $core.Data = [pscustomobject]@{ + Operation=$core.Operation; BatchId=(Get-PraGuiValue $data 'BatchId' $null); Kind=[string](Get-PraGuiValue $data 'Kind' ''); Environment=[string](Get-PraGuiValue $data 'Environment' '') + SchemaVersion=$schema; RunId=[string](Get-PraGuiValue $data 'RunId' ''); CreatedUtc=[string](Get-PraGuiValue $data 'CreatedUtc' ''); SourceBackupHash=[string](Get-PraGuiValue $data 'SourceBackupHash' '') + RecordCount=$records.Count; FirstRecordMissing=($records.Count -eq 0 -or $null -eq $records[0]); SharedCount=$shared } + } catch { $core.Error = $_.Exception.Message } + $script:PraGuiBatchCache[$Path] = $core + return $core +} + +function Get-PraGuiBatchCoreProblem { + <# The refusals of Read-PraGuiBatch that come after the Environment check (schema, records, SHA-256 of the file); computed once for a stamp. #> + param($Core, [string]$Path) + if ($null -ne $Core.Problem) { return [string]$Core.Problem } + $problem = '' + try { + $schema = $Core.Data.SchemaVersion -as [int] # numeric comparisons below need an integer, not the raw JSON value (string, long or double) if ($null -eq $schema) { throw 'Unsupported schema.' } - if (((Test-GuiOrdinal $item.Operation 'RecoverFinalize') -and $schema -ne 2) -or (-not (Test-GuiOrdinalIn $schema @(1,2,3) -IgnoreCase))) { throw 'Unsupported schema.' } - $records = @(if (Test-GuiOrdinal $item.Operation 'RecoverFinalize') { Get-PraGuiValue $data 'Items' @() } else { Get-PraGuiValue $data 'Records' @() }) - if (-not $records.Count -or $null -eq $records[0]) { throw 'Empty or missing records.' } + if (((Test-GuiOrdinal $Core.Operation 'RecoverFinalize') -and $schema -ne 2) -or (-not (Test-GuiOrdinalIn $schema @(1,2,3) -IgnoreCase))) { throw 'Unsupported schema.' } + if ($Core.Data.FirstRecordMissing) { throw 'Empty or missing records.' } if ($schema -ge 2 -and -not (Test-GuiOrdinal (ConvertTo-PraGuiHash ([IO.File]::ReadAllText($Path+'.sha256'))) (Get-PraGuiFileHash $Path) -IgnoreCase)) { throw 'SHA-256 mismatch.' } - $item.Data=$data; $item.Valid=$true; $item.Status='Readable metadata - the engine still verifies everything' - } catch { $item.Status='INVALID: '+$_.Exception.Message } - $item.Label='{0} · {1} · {2}' -f $item.Operation,$item.BatchId,$item.Status - return $item + } catch { $problem = $_.Exception.Message } + $Core.Problem = $problem + return $problem } function Test-PraGuiBatchSideFile { @@ -320,7 +379,7 @@ function Get-PraGuiGuard { $hash = [string](Get-PraGuiValue $batch.Data 'SourceBackupHash' '') if (-not $hash) { throw 'Recover batch lacks its original Convert source hash.' } $hash=ConvertTo-PraGuiHash $hash - $sources = @($state.Batches | Where-Object { $_.Valid -and (Test-GuiOrdinal $_.Operation 'Convert') -and (Test-GuiOrdinal (Get-PraGuiFileHash $_.Path) $hash -IgnoreCase) }) + $sources = @($state.Batches | Where-Object { $_.Valid -and (Test-GuiOrdinal $_.Operation 'Convert') -and (Test-GuiOrdinal (Get-PraGuiStampedHash $_.Path) $hash -IgnoreCase) }) if (-not $sources.Count) { throw 'Copy the ORIGINAL Convert folder into Storage.BackupFolder as well as the Recover folder.' } foreach ($source in $sources) { foreach ($file in @(Get-ChildItem -LiteralPath $source.Folder -Recurse -File -ErrorAction Stop)) { $files.Add($file.FullName) } @@ -1269,6 +1328,19 @@ function ConvertTo-PraGuiPlural { return ('{0} {1}' -f $Count,$Many) } +$script:PraGuiCsvCache = New-Object 'Collections.Generic.Dictionary[string,object]' ([StringComparer]::OrdinalIgnoreCase) + +function Get-PraGuiCsvRowText { + <# The sentence about the rows of the target CSV file (or the reason it cannot be used), read again only when the file's length or last write time changed: the window asks at every refresh, and a refresh follows each key typed in the confirmation box. #> + param([string]$Path) + $stamp=Get-PraGuiFileStamp $Path + $cached=$null + if ($script:PraGuiCsvCache.TryGetValue($Path,[ref]$cached) -and [string]::Equals($cached.Stamp,$stamp,[StringComparison]::Ordinal)) { return [string]$cached.Text } + try { $text=' ' + (ConvertTo-PraGuiPlural @(Read-PraTargetCsv -Path $Path).Count 'row' 'rows') + '.' } catch { $text=' ' + $_.Exception.Message } + $script:PraGuiCsvCache[$Path]=[pscustomobject]@{ Stamp=$stamp; Text=$text } + return $text +} + function Get-PraGuiSourceText { <# Title and sentence of the chosen object source. #> $g=$script:Gui @@ -1283,7 +1355,7 @@ function Get-PraGuiSourceText { 'Group' { return @('AD group',('{0} (members of nested groups included).' -f (Get-PraGuiField 'Group'))) } 'Csv' { $path=Get-PraGuiField 'Csv'; $rows='' - try { if ($path -and (Test-Path -LiteralPath $path -PathType Leaf)) { $rows=' ' + (ConvertTo-PraGuiPlural @(Read-PraTargetCsv -Path $path).Count 'row' 'rows') + '.' } } catch { $rows=' ' + $_.Exception.Message } + if ($path -and (Test-Path -LiteralPath $path -PathType Leaf)) { $rows=Get-PraGuiCsvRowText $path } return @('CSV file',($path+'.'+$rows)) } } @@ -1419,9 +1491,8 @@ function Get-PraGuiBatchEntry { Package=$false; Path=$item.Path; Environment=''; BatchId=''; Operation='' })) continue } - $data=$item.Data - $records=@(if (Test-GuiOrdinal $item.Operation 'RecoverFinalize') { Get-PraGuiValue $data 'Items' @() } else { Get-PraGuiValue $data 'Records' @() }) - $shared=@($records | Where-Object { [bool](Get-PraGuiValue $_ 'IsShared' $false) }).Count + $recordCount=[int]$item.Data.RecordCount + $shared=[int]$item.Data.SharedCount $proofPath=Join-Path $item.Folder ('State-'+$item.BatchId+'.json') $hasProof=Test-Path -LiteralPath $proofPath -PathType Leaf $state_='Ready'; $level='Ok'; $selectable=$true; $finish=$false @@ -1439,7 +1510,7 @@ function Get-PraGuiBatchEntry { if ($notApplied -and (Test-GuiOrdinalIn $item.Operation @('Convert','Recover'))) { $state_='Nothing was written to AD: not a batch to continue'; $level='Warn'; $selectable=$false; $finish=$false } $glyph=switch ($item.Operation) { 'Convert' { [string][char]0xE753 } 'Recover' { [string][char]0xE7A7 } default { [string][char]0xE930 } } $label=if (Test-GuiOrdinal $item.Operation 'RecoverFinalize') { 'Finalize' } else { [string]$item.Operation } - $sub='{0}, {1} shared · environment {2} · {3}' -f (ConvertTo-PraGuiPlural $records.Count 'mailbox' 'mailboxes'),$shared,$item.Environment,(Split-Path $item.Folder -Leaf) + $sub='{0}, {1} shared · environment {2} · {3}' -f (ConvertTo-PraGuiPlural $recordCount 'mailbox' 'mailboxes'),$shared,$item.Environment,(Split-Path $item.Folder -Leaf) $rows.Add((New-PraGuiRow @{ Title=('{0} · {1}' -f $label,(Format-PraGuiDate (Get-PraGuiBatchCreated $item))); Sub=$sub; State=$state_; Level=$level; Selectable=$selectable; Glyph=$glyph Package=$false; Path=$item.Path; Environment=$item.Environment; BatchId=$item.BatchId; Operation=[string]$item.Operation; Finish=$finish })) } @@ -1715,6 +1786,23 @@ function Test-PraGuiConfirmed { return Test-PraGuiConfirmation $g.Controls.ConfirmBox.Text $g.Action } +function Get-PraGuiVerTally { + <# Count, Shared, Warn and Failed of the rows of the preview, counted once for a given list (the same rows give the same answer: the view is refreshed at each key typed in the confirmation box). #> + $g=$script:Gui + $rows=$g.VerRows + $t=if ($g.ContainsKey('VerTally')) { $g.VerTally } else { $null } + if ($t -and $t.Count -eq $rows.Count) { return $t } + $shared=0; $warn=0; $failed=0 + foreach ($row in $rows) { + if ([string]::Equals([string]$row.Type,'Shared',[StringComparison]::OrdinalIgnoreCase)) { $shared++ } + $status=[string]$row.Status + if ([string]::Equals($status,'Warn',[StringComparison]::OrdinalIgnoreCase)) { $warn++ } elseif ([string]::Equals($status,'Fail',[StringComparison]::OrdinalIgnoreCase)) { $failed++ } + } + $t=[pscustomobject]@{ Count=$rows.Count; Shared=$shared; Warn=$warn; Failed=$failed } + $g.VerTally=$t + return $t +} + function Update-PraGuiVerifyView { $g=$script:Gui; $c=$g.Controls $action=$g.Action @@ -1758,12 +1846,10 @@ function Update-PraGuiVerifyView { $c.VerEmpty.Visibility='Visible'; $c.VerBar.Visibility='Collapsed'; $c.VerEmptyText.Text='Click Preview to see exactly what would change. The preview only reads: nothing is modified.' } else { - $rows=@($g.VerRows) - $shared=@($rows | Where-Object { (Test-GuiOrdinal $_.Type 'Shared' -IgnoreCase) }).Count - $warn=@($rows | Where-Object { (Test-GuiOrdinal $_.Status 'Warn' -IgnoreCase) }).Count - $failed=@($rows | Where-Object { (Test-GuiOrdinal $_.Status 'Fail' -IgnoreCase) }).Count + $tally=Get-PraGuiVerTally + $shared=$tally.Shared; $warn=$tally.Warn; $failed=$tally.Failed $verb=switch ($action) { 'Convert' { 'converted' } 'Recover' { 'rolled back' } 'Finalize' { 'finalized' } default { 'checked' } } - $count=$rows.Count + $count=$tally.Count $c.VerEmpty.Visibility=Get-PraGuiVisibility ($count -eq 0); $c.VerBar.Visibility='Collapsed'; $c.VerEmptyText.Text='The preview found no object to process.' $kinds=New-Object 'Collections.Generic.List[string]' if ($count-$shared -gt 0) { $kinds.Add((ConvertTo-PraGuiPlural ($count-$shared) 'user' 'users')) } @@ -1953,7 +2039,7 @@ function Initialize-PraGuiRunModel { param($Request) $g=$script:Gui; $c=$g.Controls $steps=New-Object 'Collections.ObjectModel.ObservableCollection[object]' - $model=@{ Steps=$steps; ById=@{}; Objects=@{}; Messages=@{}; Raw=@{}; Current=''; Follow=$true; Dirty=$true; Selected=$null; Info=@{}; BatchBackup='' } + $model=@{ Steps=$steps; ById=@{}; Objects=@{}; ObjectIndex=@{}; Messages=@{}; Raw=@{}; Current=''; Follow=$true; Dirty=$true; Selected=$null; Info=@{}; BatchBackup='' } $titles=@(Get-PraGuiPlanTitle $Request.Action $Request.Phase ([string](Get-PraGuiValue $Request 'Batch' ''))) for ($i=0; $i -lt $titles.Count; $i++) { $row=New-PraGuiStepRow ('s'+($i+1)) ($i+1) $titles[$i] @@ -2052,6 +2138,29 @@ function Invoke-PraGuiStepEvent { $m.Dirty=$true } +function Get-PraGuiModelObject { + <# The row of an object in a step of the run model, by name (ignoring the case); $null when the step has none. The row is returned as itself (a row is an ExpandoObject). #> + param($Model, [string]$StepId, [string]$Name) + if ($Model.ContainsKey('ObjectIndex') -and $Model.ObjectIndex.ContainsKey($StepId)) { + $row=$null + if ($Model.ObjectIndex[$StepId].TryGetValue($Name,[ref]$row)) { return ,$row } + return $null + } + # A step whose rows were put in the model without the dictionary (nothing of the run itself does that). + if ($Model.Objects.ContainsKey($StepId)) { foreach ($candidate in $Model.Objects[$StepId]) { if (Test-GuiOrdinal $candidate.Name $Name -IgnoreCase) { return ,$candidate } } } + return $null +} + +function Add-PraGuiModelObject { + <# Adds the row of an object to a step of the run model and to the dictionary of that step. #> + param($Model, [string]$StepId, [string]$Name, $Row) + if (-not $Model.ContainsKey('ObjectIndex')) { $Model['ObjectIndex']=@{} } + if (-not $Model.ObjectIndex.ContainsKey($StepId)) { $Model.ObjectIndex[$StepId]=New-Object 'Collections.Generic.Dictionary[string,object]' ([StringComparer]::OrdinalIgnoreCase) } + if (-not $Model.Objects.ContainsKey($StepId)) { $Model.Objects[$StepId]=New-Object 'Collections.ObjectModel.ObservableCollection[object]' } + $Model.Objects[$StepId].Add($Row) + if (-not $Model.ObjectIndex[$StepId].ContainsKey($Name)) { $Model.ObjectIndex[$StepId][$Name]=$Row } +} + function Invoke-PraGuiItemEvent { param($Record) $g=$script:Gui; $m=$g.Model; $run=$g.Run @@ -2074,8 +2183,8 @@ function Invoke-PraGuiItemEvent { $id=[string]$row.Id if ($identity) { if (-not $m.Objects.ContainsKey($id)) { $m.Objects[$id]=New-Object 'Collections.ObjectModel.ObservableCollection[object]' } - $existing=$null - foreach ($candidate in $m.Objects[$id]) { if (Test-GuiOrdinal $candidate.Name $identity -IgnoreCase) { $existing=$candidate; break } } + # One dictionary per step (name, ignoring the case): the object of an event is found without scanning the list of the step. + $existing=Get-PraGuiModelObject $m $id $identity $backup=[string](Get-PraGuiValue $Record 'backup' '') if ($backup) { $key=$identity.ToLowerInvariant() @@ -2086,7 +2195,7 @@ function Invoke-PraGuiItemEvent { $keepStatus=if ([int]$worse[[string]$existing.Status] -gt [int]$worse[$status]) { [string]$existing.Status } else { $status } Set-PraGuiRow $existing @{ Result=$text; Status=$keepStatus } } - else { $m.Objects[$id].Add((New-PraGuiRow @{ Name=$identity; Upn=''; Result=$text; Status=$status; Identity=$identity })) } + else { Add-PraGuiModelObject $m $id $identity (New-PraGuiRow @{ Name=$identity; Upn=''; Result=$text; Status=$status; Identity=$identity }) } if (-not [int]$row.Expected) { Set-PraGuiRow $row @{ Counter=(ConvertTo-PraGuiPlural $m.Objects[$id].Count 'object' 'objects') } } else { # "1 / 2 objects" and a proportional bar while the step works, not only at its end. @@ -2220,11 +2329,10 @@ function Show-PraGuiObjectCard { if (-not (Test-GuiOrdinal $step.Status 'Skip' -IgnoreCase)) { $journey.Add((New-PraGuiRow @{ Title=[string]$step.Label; Caption=$(if ($step.Note) { 'Whole batch · ' + [string]$step.Note } else { 'Whole batch' }); Status=[string]$step.Status })) } continue } - foreach ($candidate in $m.Objects[$id]) { - if (Test-GuiOrdinal $candidate.Name $identity -IgnoreCase) { - $journey.Add((New-PraGuiRow @{ Title=[string]$step.Label; Caption=[string]$candidate.Result; Status=[string]$candidate.Status })) - if ((Test-GuiOrdinalIn $candidate.Status @('Warn','Fail') -IgnoreCase)) { $messages.Add((New-PraGuiRow @{ Text=[string]$candidate.Result; Status=[string]$candidate.Status })) } - } + $candidate=Get-PraGuiModelObject $m $id $identity + if ($candidate) { + $journey.Add((New-PraGuiRow @{ Title=[string]$step.Label; Caption=[string]$candidate.Result; Status=[string]$candidate.Status })) + if ((Test-GuiOrdinalIn $candidate.Status @('Warn','Fail') -IgnoreCase)) { $messages.Add((New-PraGuiRow @{ Text=[string]$candidate.Result; Status=[string]$candidate.Status })) } } } $c.Journey.ItemsSource=$journey @@ -2326,14 +2434,19 @@ function Remove-PraGuiCsvGuard { } function Read-PraGuiReport { - <# The CSV report of a run, with the formula guards removed from the shown values. #> + <# The CSV report of a run, with the formula guards removed from the columns the window shows or uses (the same rule as Remove-PraGuiCsvGuard, written inline: one call per cell is slow on thousands of rows). #> param([string]$Path) $rows=@(Import-Csv -LiteralPath $Path -Delimiter ';' -Encoding UTF8 -ErrorAction Stop) + $shown=@('SamAccountName','UserPrincipalName','BackupPath','Warnings','FinalStatus','Detail') foreach ($row in $rows) { - foreach ($property in @($row.PSObject.Properties)) { - if ($property.Value -is [string]) { $property.Value=Remove-PraGuiCsvGuard $property.Value } + foreach ($name in $shown) { + $property=$row.PSObject.Properties[$name] + if ($null -eq $property) { continue } + $value=$property.Value + if ($value -is [string] -and $value.Length -ge 2 -and $value.StartsWith([string][char]39,[StringComparison]::Ordinal) -and "=+-@`t`r".IndexOf([string]$value[1],[StringComparison]::Ordinal) -ge 0) { $property.Value=$value.Substring(1) } } - if ($row.PSObject.Properties['IsShared']) { $row.IsShared=(Test-GuiOrdinal $row.IsShared 'True' -IgnoreCase) } + $shared=$row.PSObject.Properties['IsShared'] + if ($shared) { $shared.Value=[string]::Equals([string]$shared.Value,'True',[StringComparison]::OrdinalIgnoreCase) } } return $rows } @@ -2502,6 +2615,8 @@ function Complete-PraGuiRun { if ($batchFiles.Count) { $g.Model.BatchBackup=[string]$batchFiles[0] } } if ((Test-GuiOrdinal $run.Purpose 'Preview' -IgnoreCase)) { + # The list is detached while its rows are replaced (one layout of the list, not one per row) and bound again below. + $g.Controls.VerList.ItemsSource=$null $g.VerRows.Clear() foreach ($objectRow in $rows) { $g.VerRows.Add((ConvertTo-PraGuiObjectRow $objectRow)) } $g.Previewed=$valid @@ -3232,6 +3347,8 @@ function New-PraGuiWindow { $c.HeaderSub.ToolTip='Host: '+$env:COMPUTERNAME+' · UI: PowerShell '+$PSVersionTable.PSVersion+' · engine: '+(Get-PraGuiEngine) $c.ActivityLog.ItemsSource=$g.Lines; $c.Lights.ItemsSource=$g.LightRows; $c.BatchList.ItemsSource=$g.BatchRows; $c.NextSteps.ItemsSource=$g.NextRows; $c.Timeline.ItemsSource=$g.TimelineRows $c.VerList.ItemsSource=$g.VerRows + # The counts of the preview rows are kept until the rows change. + $g.VerRows.Add_CollectionChanged({ $gui=$script:Gui; if ($gui) { $gui.VerTally=$null } }) $g.VerView=[Windows.Data.CollectionViewSource]::GetDefaultView($g.VerRows) $g.VerView.Filter=[Predicate[object]]{ param($row) @@ -3273,7 +3390,12 @@ function New-PraGuiWindow { $c.F_Group.Add_TextChanged({ if ($script:Gui.Updating -eq 0) { Set-PraGuiGroupInfo '' } }) $c.F_Group.Add_LostFocus({ if ($script:Gui.Updating -eq 0 -and $script:Gui.Page -eq 2) { try { Start-PraGuiGroupLookup } catch { Set-PraGuiGroupInfo $_.Exception.Message 'Warn' } } }) $c.F_Group.Add_KeyDown({ param($sender,$keyArguments) if ([int]$keyArguments.Key -eq [int][Windows.Input.Key]::Return) { try { Start-PraGuiGroupLookup } catch { Set-PraGuiGroupInfo $_.Exception.Message 'Warn' } } }) - $c.ConfirmBox.Add_TextChanged({ Update-PraGuiView }) + # A refresh follows a pause in the typing, not each key: the refresh reads the state of the page (the CSV file, the preview rows). + $confirmTimer=New-Object Windows.Threading.DispatcherTimer + $confirmTimer.Interval=[timespan]::FromMilliseconds(100) + $confirmTimer.Add_Tick({ $script:Gui.ConfirmTimer.Stop(); Update-PraGuiView }) + $g.ConfirmTimer=$confirmTimer + $c.ConfirmBox.Add_TextChanged({ $script:Gui.ConfirmTimer.Stop(); $script:Gui.ConfirmTimer.Start() }) $c.BatchList.Add_SelectionChanged({ $gui=$script:Gui if ($gui.Updating -gt 0 -or $gui.Run) { return } @@ -3295,8 +3417,8 @@ function New-PraGuiWindow { Add-PraGuiLine ($windowControl.Title+': closing refused, an atomic action is running. Wait for it to end; do not kill the engine.') 'Warn' } }) - $form.Add_Closed({ $script:Gui.Timer.Stop(); $script:Gui.Pending=$null; $script:Gui.NetJob=$null; $script:Gui.SyncJob=$null; if ($script:GuiNetHttp) { $script:GuiNetHttp.Dispose(); $script:GuiNetHttp=$null } }) - $g.HandlerNames+=@('BatchList.SelectionChanged','StepList.SelectionChanged','DetObjList.SelectionChanged','ConfirmBox.TextChanged','F_ExpOnce.Checked','F_ExpOnce.Unchecked','Timer.Tick','Form.Closing','Form.Closed') + $form.Add_Closed({ $script:Gui.Timer.Stop(); $script:Gui.ConfirmTimer.Stop(); $script:Gui.Pending=$null; $script:Gui.NetJob=$null; $script:Gui.SyncJob=$null; if ($script:GuiNetHttp) { $script:GuiNetHttp.Dispose(); $script:GuiNetHttp=$null } }) + $g.HandlerNames+=@('BatchList.SelectionChanged','StepList.SelectionChanged','DetObjList.SelectionChanged','ConfirmBox.TextChanged','ConfirmTimer.Tick','F_ExpOnce.Checked','F_ExpOnce.Unchecked','Timer.Tick','Form.Closing','Form.Closed') foreach ($name in @('System','Light','Dark')) { $c['Th_'+$name].IsChecked=((Test-GuiOrdinal $name $Theme -IgnoreCase)) } $c.Nav1.IsChecked=$true Set-PraGuiField 'Source' 'Single' diff --git a/tests/PraRemoteMailbox.Gui.Tests.ps1 b/tests/PraRemoteMailbox.Gui.Tests.ps1 index 9324fbc..8dfa91d 100644 --- a/tests/PraRemoteMailbox.Gui.Tests.ps1 +++ b/tests/PraRemoteMailbox.Gui.Tests.ps1 @@ -660,17 +660,17 @@ try { if(-not $g.Pending){throw ('Preview not authorized: '+$c.SumText.Text+' '+$g.PreviewError)} if($c.VerList.Items.Count -ne 1){throw 'The grid is not populated by the Preview report'} if($g.Model.Steps.Count -ne 3 -or $g.Model.Steps[2].Status -ne 'Ok'){throw 'The plan and step events did not drive the steps'} - $c.ConfirmBox.Text='CONVERTX' + $c.ConfirmBox.Text='CONVERTX'; Pump 350 if($c.BtnNext.IsEnabled){throw 'A wrong confirmation word enabled Run'} - $c.ConfirmBox.Text='convert' + $c.ConfirmBox.Text='convert'; Pump 350 if(-not $c.BtnNext.IsEnabled){throw 'Lowercase confirmation did not enable Run'} - $c.ConfirmBox.Text=' CoNvErT ' + $c.ConfirmBox.Text=' CoNvErT '; Pump 350 if(-not $c.BtnNext.IsEnabled){throw 'Mixed-case confirmation with spaces did not enable Run'} $c.F_Identity.Text='other@example.invalid'; Pump if($g.Pending -or $c.BtnNext.IsEnabled -or $c.ConfirmBox.Text){throw 'Changing the object source preserved the authorization'} $c.F_Identity.Text='synthetic@example.invalid'; Pump Click $g 'BtnPreview'; Wait-Run $g - $c.ConfirmBox.Text='CONVERT' + $c.ConfirmBox.Text='CONVERT'; Pump 350 if(-not $c.BtnNext.IsEnabled){throw 'A fresh Preview did not reauthorize Run'} [IO.File]::AppendAllText($Config,"`n# Changed input") Click $g 'BtnNext' @@ -2026,6 +2026,132 @@ AfterAll { } } +Describe 'Release 3.2.0 - scale: the console reads a batch file again only when it changed, finds an object of an event without a scan, and reads its CSV files by their stamp (synthetic, no engine)' -Tag 'Release320c' { + It 'keeps what it read of a batch while the file and its .sha256 file are unchanged, and reads again only the file that changed' { + $runtime=New-GuiTestRoot + $batches=@(1..3 | ForEach-Object { New-GuiTestBatch $runtime }) + $first=Read-PraGuiState $runtime.Root $runtime.Config + $first.Batches.Count | Should -Be 3 + $second=Read-PraGuiState $runtime.Root $runtime.Config + foreach ($item in $second.Batches) { + $before=@($first.Batches | Where-Object Path -eq $item.Path)[0] + [object]::ReferenceEquals($item.Data,$before.Data) | Should -BeTrue -Because 'the batch was not read again' + } + $changed=$batches[1] + $data=$changed.Data.Clone(); $data.Records=@($data.Records[0],$data.Records[0]); $data.Environment='GuiSynthetic' + Write-GuiTestJson $changed.Path $data + $third=Read-PraGuiState $runtime.Root $runtime.Config + foreach ($item in $third.Batches) { + $before=@($second.Batches | Where-Object Path -eq $item.Path)[0] + [object]::ReferenceEquals($item.Data,$before.Data) | Should -Be ($item.Path -ne $changed.Path) + } + @($third.Batches | Where-Object Path -eq $changed.Path)[0].Data.RecordCount | Should -Be 2 + [IO.File]::WriteAllText($batches[2].Path+'.sha256',('0'*64),$script:GuiEncoding) + $fourth=Read-PraGuiState $runtime.Root $runtime.Config + @($fourth.Batches | Where-Object Path -eq $batches[2].Path)[0].Status | Should -Match 'SHA-256 mismatch' -Because 'a changed .sha256 file is a change of the batch' + } + It 'keeps in the batch only what the window shows (the counts), so that a batch of thousands of objects costs little memory, and counts the shared mailboxes' { + $runtime=New-GuiTestRoot + $batch=New-GuiTestBatch $runtime + $data=$batch.Data.Clone() + $data.Records=@(1..2000 | ForEach-Object { @{ObjectGuid=[guid]::NewGuid().ToString();SamAccountName=('user'+$_);UserPrincipalName=('user'+$_+'@contoso.invalid');IsShared=(($_ % 4) -eq 0)} }) + Write-GuiTestJson $batch.Path $data + $item=Read-PraGuiBatch $batch.Path 'GuiSynthetic' + $item.Valid | Should -BeTrue + $item.Data.RecordCount | Should -Be 2000 + $item.Data.SharedCount | Should -Be 500 + $item.Data.PSObject.Properties.Name | Should -Not -Contain 'Records' + $item.Data.BatchId | Should -BeExactly $batch.Id + (Read-PraGuiBatch $batch.Path 'OtherSynthetic').EnvMismatch | Should -BeTrue + (Read-PraGuiBatch $batch.Path 'otherSYNTHETIC' -AnyEnvironment).Valid | Should -BeTrue + (Read-PraGuiBatch $batch.Path 'guisynthetic').Valid | Should -BeTrue -Because 'the Environment is compared ignoring the letter case' + } + It 'finds the row of an object in a step by its name in any letter case, without scanning the rows of the step' { + $result=& (Get-Module PRA.Gui) { + $model=@{ Objects=@{}; ObjectIndex=@{} } + $clock=[Diagnostics.Stopwatch]::StartNew() + for ($i=1; $i -le 3000; $i++) { Add-PraGuiModelObject $model 's3' ('User'+$i+'@contoso.invalid') (New-PraGuiRow @{ Name=('User'+$i+'@contoso.invalid'); Result='ok' }) } + $hits=0 + for ($i=1; $i -le 3000; $i++) { $row=Get-PraGuiModelObject $model 's3' ('USER'+$i+'@CONTOSO.INVALID'); if ($row -and $row.Result -ceq 'ok') { $hits++ } } + $plain=@{ Objects=@{ s1=(New-Object 'Collections.ObjectModel.ObservableCollection[object]') } } + $plain.Objects.s1.Add((New-PraGuiRow @{ Name='Only@contoso.invalid'; Result='x' })) + @{ Rows=$model.Objects['s3'].Count; Hits=$hits; Seconds=$clock.Elapsed.TotalSeconds; Missing=(Get-PraGuiModelObject $model 's3' 'nobody@contoso.invalid'); NoStep=(Get-PraGuiModelObject $model 's9' 'x'); Scan=(Get-PraGuiModelObject $plain 's1' 'ONLY@contoso.invalid') } + } + $result.Rows | Should -Be 3000 + $result.Hits | Should -Be 3000 + $result.Missing | Should -BeNullOrEmpty + $result.NoStep | Should -BeNullOrEmpty + $result.Scan.Result | Should -BeExactly 'x' -Because 'a model built without the dictionary is still searched' + $result.Seconds | Should -BeLessThan 60 + } + It 'says how many rows its target CSV file has from the stamp of the file, and reads the file again when it changes' { + $runtime=New-GuiTestRoot + $csv=Join-Path $runtime.Root 'targets.csv' + Write-GuiTestFile $csv ("Identity`r`n"+((1..50 | ForEach-Object { 'user'+$_+'@contoso.invalid' }) -join "`r`n")) + $global:PraGuiCsv=$csv + $text=& (Get-Module PRA.Gui) { Get-PraGuiCsvRowText $global:PraGuiCsv } + $text | Should -BeExactly ' 50 rows.' + & (Get-Module PRA.Gui) { $script:PraGuiCsvCache[$global:PraGuiCsv].Text=' kept from the first reading.' } + (& (Get-Module PRA.Gui) { Get-PraGuiCsvRowText $global:PraGuiCsv }) | Should -BeExactly ' kept from the first reading.' -Because 'the file was not read again' + Write-GuiTestFile $csv ("Identity`r`n"+((1..7 | ForEach-Object { 'user'+$_+'@contoso.invalid' }) -join "`r`n")) + (& (Get-Module PRA.Gui) { Get-PraGuiCsvRowText $global:PraGuiCsv }) | Should -BeExactly ' 7 rows.' + Write-GuiTestFile $csv "Wrong`r`nsynthetic@example.invalid" + (& (Get-Module PRA.Gui) { Get-PraGuiCsvRowText $global:PraGuiCsv }) | Should -Match 'requires an Identity column' + Remove-Variable PraGuiCsv -Scope Global + $source=Get-Content -LiteralPath $script:GuiModule -Raw + $source | Should -Match '\$c\.ConfirmBox\.Add_TextChanged\(\{ \$script:Gui\.ConfirmTimer\.Stop\(\); \$script:Gui\.ConfirmTimer\.Start\(\) \}\)' -Because 'a refresh follows a pause in the typing, not each key' + $source | Should -Not -Match 'ConfirmBox\.Add_TextChanged\(\{ Update-PraGuiView \}\)' + } + It 'reads the per-run CSV of thousands of rows with the formula guard removed from the columns it shows, and the shared flag as a boolean' { + $runtime=New-GuiTestRoot + $path=Join-Path $runtime.Root 'run.csv' + $lines=New-Object 'Collections.Generic.List[string]' + $lines.Add('"ObjectGuid";"SamAccountName";"UserPrincipalName";"IsShared";"BackupPath";"Warnings";"FinalStatus";"Detail";"CloudDetail"') + for ($i=1; $i -le 3000; $i++) { $lines.Add(('"{0}";"''=user{1}";"user{1}@contoso.invalid";"{2}";"B{1}";"";"Planned";"''-detail {1}";"''=kept"' -f [guid]::NewGuid(),$i,$(if ($i % 2) { 'True' } else { 'False' }))) } + [IO.File]::WriteAllText($path,($lines -join "`r`n"),$script:GuiEncoding) + $global:PraGuiReport=$path + $clock=[Diagnostics.Stopwatch]::StartNew() + $rows=@(& (Get-Module PRA.Gui) { Read-PraGuiReport $global:PraGuiReport }) + $seconds=$clock.Elapsed.TotalSeconds + Remove-Variable PraGuiReport -Scope Global + $rows.Count | Should -Be 3000 + $rows[0].SamAccountName | Should -BeExactly '=user1' + $rows[0].Detail | Should -BeExactly '-detail 1' + $rows[0].IsShared | Should -BeTrue + $rows[1].IsShared | Should -BeFalse + $rows[0].UserPrincipalName | Should -BeExactly 'user1@contoso.invalid' + $rows[0].CloudDetail | Should -BeExactly "'=kept" -Because 'a column the window does not show keeps its guard' + $seconds | Should -BeLessThan 60 + } + It 'counts the rows of a preview once for a given list (a refresh follows each key typed in the confirmation box)' { + $result=& (Get-Module PRA.Gui) { + $saved=$script:Gui + try { + $rows=New-Object 'Collections.ObjectModel.ObservableCollection[object]' + for ($i=1; $i -le 3000; $i++) { $rows.Add((New-PraGuiRow @{ Type=$(if ($i % 3 -eq 0) { 'Shared' } else { 'User' }); Status=$(if ($i % 10 -eq 0) { 'Warn' } elseif ($i % 50 -eq 0) { 'Fail' } else { 'Ok' }) })) } + $script:Gui=@{ VerRows=$rows } + $first=[pscustomobject]@{ } + $tally=Get-PraGuiVerTally + $first=[pscustomobject]@{ Count=$tally.Count; Shared=$tally.Shared; Warn=$tally.Warn; Failed=$tally.Failed } + $script:Gui.VerTally.Warn=-1 + $second=Get-PraGuiVerTally + $keptWarn=$second.Warn + $rows.Add((New-PraGuiRow @{ Type='Shared'; Status='Fail' })) + $third=Get-PraGuiVerTally + @{ First=$first; Same=($keptWarn -eq -1); Third=$third } + } finally { $script:Gui=$saved } + } + $result.First.Count | Should -Be 3000 + $result.First.Shared | Should -Be 1000 + $result.First.Warn | Should -Be 300 + $result.First.Failed | Should -Be 0 -Because 'a row that is a multiple of 50 is also a multiple of 10 and counts as a warning' + $result.Same | Should -BeTrue + $result.Third.Count | Should -Be 3001 + $result.Third.Shared | Should -Be 1001 + $result.Third.Failed | Should -Be 1 + } +} + Describe 'Release 3.2.0 - the console: the data files of the global report are not batches, an Apply with planned objects is not Done, a partial batch is labelled (synthetic, no engine)' -Tag 'Release320a' { It 'does not list PhaseData and PhaseEvents files as unreadable batches, and resolves a batch folder that holds them' { $runtime = New-GuiTestRoot diff --git a/tests/PraRemoteMailbox.Tests.ps1 b/tests/PraRemoteMailbox.Tests.ps1 index 3d5d1c4..2da008f 100644 --- a/tests/PraRemoteMailbox.Tests.ps1 +++ b/tests/PraRemoteMailbox.Tests.ps1 @@ -1968,7 +1968,7 @@ Describe 'OOM permission cache, receipt identity and thirteen shared snapshots' elseif ($Path -like '*.json') { $global:PraGate.ReceiptCounts.JsonHashes++ } & $script:GateRealHash $Path } - foreach ($i in 1..3) { Assert-PraReceipt $global:PraGate.Context $global:PraGate.Receipt $global:PraGate.Plan.Record.ObjectGuid } + foreach ($i in 1..3) { Assert-PraReceipt $global:PraGate.Context $global:PraGate.Receipt $global:PraGate.Plan.Record.ObjectGuid -Full } } $global:PraGate.ReceiptCounts.Imports | Should -Be 0 $global:PraGate.ReceiptCounts.RawTests | Should -Be 0 @@ -5614,11 +5614,15 @@ Describe 'Release 3.0.0 - transfer package: verification, extraction and refusal $stream = [IO.File]::Open($zipPath, [IO.FileMode]::CreateNew) $zip = New-Object IO.Compression.ZipArchive($stream, 'Create') $entry = $zip.CreateEntry('Batch-aaaaaaaa11111111aaaaaaaa11111111/zeros.bin', [IO.Compression.CompressionLevel]::Fastest); $s = $entry.Open() - $chunk = New-Object byte[] 1048576; for ($i = 0; $i -lt 257; $i++) { $s.Write($chunk, 0, $chunk.Length) } + $chunk = New-Object byte[] 1048576; for ($i = 0; $i -lt 3; $i++) { $s.Write($chunk, 0, $chunk.Length) } $s.Dispose(); $zip.Dispose(); $stream.Dispose() [IO.File]::WriteAllText($zipPath + '.sha256', (Get-FileHash -LiteralPath $zipPath).Hash.ToLowerInvariant()) (Get-Item -LiteralPath $zipPath).Length | Should -BeLessThan 5MB - $info = Get-PraTransferPackage -Path $zipPath -Environment LAB + try { + InModuleScope PRA.Common { $script:PraTransferLimits.MaxEntryBytes = 2MB } + $info = Get-PraTransferPackage -Path $zipPath -Environment LAB + } + finally { InModuleScope PRA.Common { $script:PraTransferLimits.MaxEntryBytes = [long]2147483648 } } $info.Valid | Should -BeFalse $info.Error | Should -Match 'too large' (Get-TpChildren $w.Backups) | Should -Be 0 @@ -5631,12 +5635,16 @@ Describe 'Release 3.0.0 - transfer package: verification, extraction and refusal $chunk = New-Object byte[] 1048576 foreach ($n in 1..3) { $entry = $zip.CreateEntry("Batch-aaaaaaaa11111111aaaaaaaa11111111/z$n.bin", [IO.Compression.CompressionLevel]::Fastest); $s = $entry.Open() - for ($i = 0; $i -lt 200; $i++) { $s.Write($chunk, 0, $chunk.Length) } + for ($i = 0; $i -lt 2; $i++) { $s.Write($chunk, 0, $chunk.Length) } $s.Dispose() } $zip.Dispose(); $stream.Dispose() [IO.File]::WriteAllText($zipPath + '.sha256', (Get-FileHash -LiteralPath $zipPath).Hash.ToLowerInvariant()) - $info = Get-PraTransferPackage -Path $zipPath -Environment LAB + try { + InModuleScope PRA.Common { $script:PraTransferLimits.MaxTotalBytes = 5MB } + $info = Get-PraTransferPackage -Path $zipPath -Environment LAB + } + finally { InModuleScope PRA.Common { $script:PraTransferLimits.MaxTotalBytes = [long]4294967296 } } $info.Valid | Should -BeFalse $info.Error | Should -Match 'too large|zip bomb' } @@ -10076,6 +10084,234 @@ Describe 'Release 3.2.0 - the exit code goes to the host only when the script is } } +Describe 'Release 3.2.0 - scale: records are found in a dictionary, not by scanning a list; the limits that bounded a large batch are raised (production Common module)' -Tag 'Release320c' { + BeforeAll { Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global } + It 'finds a record by its GUID in any letter case, reports a GUID that two records carry, and builds one index for one array' { + $first = [pscustomobject]@{ ObjectGuid = 'AAAAAAAA-0000-0000-0000-000000000001'; Name = 'one' } + $second = [pscustomobject]@{ ObjectGuid = 'aaaaaaaa-0000-0000-0000-000000000002'; Name = 'two' } + $again = [pscustomobject]@{ ObjectGuid = 'AAAAAAAA-0000-0000-0000-000000000002'; Name = 'two again' } + $records = [object[]]@($first, $second, $again) + $index = Get-PraRecordIndex $records + (Find-PraRecord $index 'aaaaaaaa-0000-0000-0000-000000000001').Name | Should -BeExactly 'one' + (Find-PraRecord $index 'AAAAAAAA-0000-0000-0000-000000000002').Name | Should -BeExactly 'two' -Because 'the first record of a GUID is kept' + $index.Duplicates.Contains('aaaaaaaa-0000-0000-0000-000000000002') | Should -BeTrue + $index.Duplicates.Contains('aaaaaaaa-0000-0000-0000-000000000001') | Should -BeFalse + Find-PraRecord $index 'bbbbbbbb-0000-0000-0000-000000000001' | Should -BeNullOrEmpty + Find-PraRecord $index '' | Should -BeNullOrEmpty + [object]::ReferenceEquals((Get-PraRecordIndex $records), $index) | Should -BeTrue + $longer = [object[]]@($records + $first) + [object]::ReferenceEquals((Get-PraRecordIndex $longer), $index) | Should -BeFalse + (Get-PraRecordIndex $longer).Duplicates.Contains('aaaaaaaa-0000-0000-0000-000000000001') | Should -BeTrue + (New-PraRecordIndex -Record @()).Count | Should -Be 0 + } + It 'indexes 5,000 records and answers 5,000 lookups (a scan of the list for each record took minutes)' { + $records = [object[]]@(1..5000 | ForEach-Object { [pscustomobject]@{ ObjectGuid = ('{0:x8}-1111-2222-3333-444444444444' -f $_) } }) + $clock = [Diagnostics.Stopwatch]::StartNew() + $index = Get-PraRecordIndex $records + $found = 0 + foreach ($record in $records) { if ($null -ne (Find-PraRecord $index ([string]$record.ObjectGuid).ToUpperInvariant())) { $found++ } } + $found | Should -Be 5000 + $index.Duplicates.Count | Should -Be 0 + $clock.Elapsed.TotalSeconds | Should -BeLessThan 30 + } + It 'raises the package and report limits to what 5,000 objects need, and a transfer package above a limit is refused with the reason' { + InModuleScope PRA.Common { + $script:PraTransferLimits.MaxEntries | Should -Be 2000 + $script:PraTransferLimits.MaxEntryBytes | Should -Be 2147483648 + $script:PraTransferLimits.MaxTotalBytes | Should -Be 4294967296 + $script:PraPhaseLimits.MaxBytes | Should -Be 268435456 + $script:PraPhaseLimits.MaxJourney | Should -Be 1000000 + $script:PraPhaseLimits.MaxIssues | Should -Be 10000 + $script:PraPhaseLimits.DetailedObjects | Should -Be 10000 + } + $root = Join-Path $global:PraGate.Root ('limits-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) + $id = 'a1b2c3d4e5f60718293a4b5c6d7e8f90' + $folder = Join-Path $root ('Batch-' + $id); $null = New-Item -ItemType Directory -Path $folder -Force + [IO.File]::WriteAllText((Join-Path $folder 'Convert-SYNTHETIC_GATE-20261117_100000-a1b2c3d4.json'), ('{"synthetic":"' + ('x' * 200) + '"}')) + $package = New-PraTransferPackage -Kind Convert -Environment 'SYNTHETIC_GATE' -BatchId $id -Folders @($folder) -OutboxFolder (Join-Path $root 'Outbox') + (Get-PraTransferPackage -Path $package.Path -Environment 'SYNTHETIC_GATE').Valid | Should -BeTrue + try { + InModuleScope PRA.Common { $script:PraTransferLimits.MaxEntryBytes = 10 } + $refused = Get-PraTransferPackage -Path $package.Path -Environment 'SYNTHETIC_GATE' + $refused.Valid | Should -BeFalse + $refused.Error | Should -Match 'is too large' + InModuleScope PRA.Common { $script:PraTransferLimits.MaxEntryBytes = 2147483648; $script:PraTransferLimits.MaxTotalBytes = 10 } + (Get-PraTransferPackage -Path $package.Path -Environment 'SYNTHETIC_GATE').Error | Should -Match 'content is too large' + } + finally { InModuleScope PRA.Common { $script:PraTransferLimits.MaxEntryBytes = 2147483648; $script:PraTransferLimits.MaxTotalBytes = 4294967296 } } + (Get-PraTransferPackage -Path $package.Path -Environment 'SYNTHETIC_GATE').Valid | Should -BeTrue + } +} + +Describe 'Release 3.2.0 - scale: the backup is checked in full at the boundaries of a batch and cheaply for each write (production Directory module, synthetic AD)' -Tag 'Release320c' { + BeforeEach { + $global:PraGate.Runtime = New-GateRuntime -Name 'scale-receipt' -UserCount 4 + $env:PRA_GATE_STATE = $global:PraGate.Runtime.StatePath + $env:PSModulePath = $global:PraGate.Runtime.Modules + ';' + (Join-Path $PSHOME 'Modules') + Import-Module ActiveDirectory -Force -Global + $global:PraGate.Context = New-GateContext $global:PraGate.Runtime + $global:PraGate.Context.LogFile = Join-Path $global:PraGate.Runtime.Root 'logs\scale-receipt.log' + $global:PraGate.Counters = @{ Readbacks = 0; Writes = 0; FaultReached = 0 } + $global:PraGate.Scale = @{ Fingerprints = 0; Hashes = 0; RawHashes = 0; Imports = 0; Calls = 0 } + } + It 'one write costs the fingerprint of its own record and no file hash; the complete check fingerprints every record and hashes the files; the files are hashed again after a number of cheap checks' { + $context = $global:PraGate.Context + $plans = @(1..4 | ForEach-Object { New-PraPlan $context ('user' + $_) 'Convert' }) + $receipt = & (Get-Module PRA.Directory) { param($c, $p) Save-PraBatch $c $p 'Convert' } $context $plans + $global:PraGate.Scale.Receipt = $receipt; $global:PraGate.Scale.Guid = [string]$plans[0].Record.ObjectGuid + $global:PraGate.Scale.Stages = @{} + InModuleScope PRA.Directory { + $script:RealFingerprint = (Get-Command Get-PraDataFingerprint).ScriptBlock + $script:RealHash = (Get-Command Get-PraHash).ScriptBlock + Mock Get-PraDataFingerprint { param($Data) $global:PraGate.Scale.Fingerprints++; & $script:RealFingerprint -Data $Data } + Mock Get-PraHash { param($Path) $global:PraGate.Scale.Hashes++; & $script:RealHash $Path } + $state = $global:PraGate.Scale + foreach ($i in 1..5) { Assert-PraReceipt $global:PraGate.Context $state.Receipt $state.Guid } + $state.Stages.Cheap = @{ Fingerprints = $state.Fingerprints; Hashes = $state.Hashes } + Assert-PraReceipt -Context $global:PraGate.Context -Receipt $state.Receipt -Full + $state.Stages.Full = @{ Fingerprints = $state.Fingerprints; Hashes = $state.Hashes } + Assert-PraReceipt -Context $global:PraGate.Context -Receipt $state.Receipt + $state.Stages.NoObject = @{ Fingerprints = $state.Fingerprints; Hashes = $state.Hashes } + $script:ReceiptFileHashEvery = 3 + try { foreach ($i in 1..7) { Assert-PraReceipt $global:PraGate.Context $state.Receipt $state.Guid } } + finally { $script:ReceiptFileHashEvery = 200 } + $state.Stages.Periodic = @{ Fingerprints = $state.Fingerprints; Hashes = $state.Hashes } + } + $stages = $global:PraGate.Scale.Stages + $stages.Cheap.Fingerprints | Should -Be 10 -Because 'the fields of the receipt and the record of the object, for each of the five checks' + $stages.Cheap.Hashes | Should -Be 0 + ($stages.Full.Fingerprints - $stages.Cheap.Fingerprints) | Should -Be 5 -Because 'the fields and the four records' + ($stages.Full.Hashes - $stages.Cheap.Hashes) | Should -Be 2 -Because 'the JSON and the CLIXML file' + ($stages.NoObject.Fingerprints - $stages.Full.Fingerprints) | Should -Be 5 -Because 'a check without an object is the complete one' + ($stages.NoObject.Hashes - $stages.Full.Hashes) | Should -Be 2 + ($stages.Periodic.Hashes - $stages.NoObject.Hashes) | Should -Be 4 -Because 'the files are hashed at the third and at the sixth cheap check' + } + It 'a change of another record in memory is found by the complete check, a change of the record about to be written by the cheap one; a same-length change of a file is found by the complete check only' { + $context = $global:PraGate.Context + $plans = @(1..4 | ForEach-Object { New-PraPlan $context ('user' + $_) 'Convert' }) + $receipt = & (Get-Module PRA.Directory) { param($c, $p) Save-PraBatch $c $p 'Convert' } $context $plans + $first = [string]$plans[0].Record.ObjectGuid; $last = [string]$plans[3].Record.ObjectGuid + $original = $receipt.Data.Records[3].Attributes.homeMDB.Value + $receipt.Data.Records[3].Attributes.homeMDB.Value = 'CN=Injected,DC=gate,DC=invalid' + { Assert-PraReceipt $context $receipt $first } | Should -Not -Throw + { Assert-PraReceipt $context $receipt $last } | Should -Throw '*changed in memory since its validation*' + { Assert-PraReceipt -Context $context -Receipt $receipt -Full } | Should -Throw '*changed in memory since its validation*' + $receipt.Data.Records[3].Attributes.homeMDB.Value = $original + { Assert-PraReceipt -Context $context -Receipt $receipt -Full } | Should -Not -Throw + $swap = $receipt.Data.Records[0]; $receipt.Data.Records[0] = $receipt.Data.Records[1] + { Assert-PraReceipt $context $receipt $first } | Should -Throw '*changed in memory since its validation*' -Because 'a record put in the place of another is not the record that was validated' + $receipt.Data.Records[0] = $swap + { Assert-PraReceipt -Context $context -Receipt $receipt -Full } | Should -Not -Throw + $stamp = (Get-Item -LiteralPath $receipt.Path).LastWriteTimeUtc + $text = [IO.File]::ReadAllText($receipt.Path) + $changed = $text.Replace('"SamAccountName": "user1"', '"SamAccountName": "user9"') + $changed.Length | Should -Be $text.Length + $changed | Should -Not -BeExactly $text + [IO.File]::WriteAllText($receipt.Path, $changed, (New-Object Text.UTF8Encoding($false))) + [IO.File]::SetLastWriteTimeUtc($receipt.Path, $stamp) + { Assert-PraReceipt $context $receipt $first } | Should -Not -Throw -Because 'same length, same last write time: the cheap check cannot see it' + { Assert-PraReceipt -Context $context -Receipt $receipt -Full } | Should -Throw '*Backup JSON file changed since its validation*' + [IO.File]::AppendAllText($receipt.Path, ' ') + { Assert-PraReceipt $context $receipt $first } | Should -Throw '*Backup JSON file changed since its validation*' -Because 'a longer file is seen by the cheap check' + } + It 'a batch whose record is changed in memory after its own write is stopped by the complete check before its AD proof is written' { + $context = $global:PraGate.Context + $plans = @(1..4 | ForEach-Object { New-PraPlan $context ('user' + $_) 'Convert' }) + $global:PraGate.Scale.Plans = $plans + $context.Approval = { + param($Target, $Operation) + $global:PraGate.Scale.Calls++ + if ($global:PraGate.Scale.Calls -eq 6) { + $entry = & (Get-Module PRA.Directory) { param($c) (Get-PraReceiptRegistry -Context $c)[0] } $global:PraGate.Context + $entry.Receipt.Data.Records[0].Attributes.homeMDB.Value = 'CN=Injected,DC=gate,DC=invalid' + } + $true + } + InModuleScope PRA.Directory { + $script:RealHash = (Get-Command Get-PraHash).ScriptBlock + Mock Get-PraHash { param($Path) if ($Path -like '*.clixml') { $global:PraGate.Scale.RawHashes++ }; & $script:RealHash $Path } + { Invoke-PraAdBatch $global:PraGate.Context $global:PraGate.Scale.Plans 'Convert' } | Should -Throw '*changed in memory since its validation*' + } + @(Get-GateWrites $global:PraGate.Runtime).Count | Should -Be 8 -Because 'every object was written before the complete check at the end' + $global:PraGate.Scale.RawHashes | Should -BeLessThan 8 -Because 'the CLIXML is hashed when the backup is written and read, and once more by the complete check: not for each of the eight writes' + $global:PraGate.Context.OperationFailed | Should -BeTrue + } + It 'the cloud phase reads the AD proof in full once and by the stamps of its files for the next writes; a changed proof is read again; an object that is not in it is refused' { + $context = $global:PraGate.Context + $plans = @(1..4 | ForEach-Object { New-PraPlan $context ('user' + $_) 'Convert' }) + $receipt = Invoke-PraAdBatch $context $plans 'Convert' + $context.Source = $receipt; $context.SourceBackupHash = $receipt.Hash + $global:PraGate.Scale.Receipt = $receipt; $global:PraGate.Scale.Guids = @($plans | ForEach-Object { [string]$_.Record.ObjectGuid }) + InModuleScope PRA.Directory { + $script:RealProof = (Get-Command Import-PraProof).ScriptBlock + Mock Import-PraProof { param($Context, $Path, $Source, $Operation) $global:PraGate.Scale.Imports++; & $script:RealProof $Context $Path $Source $Operation } + $state = $global:PraGate.Scale; $c = $global:PraGate.Context + foreach ($guid in $state.Guids) { Assert-PraCloudProofObject -Context $c -ProofPath $state.Receipt.StatePath -Source $state.Receipt -Operation 'Convert' -ObjectGuid $guid.ToUpperInvariant() } + foreach ($guid in $state.Guids) { Assert-PraCloudProofObject -Context $c -ProofPath $state.Receipt.StatePath -Source $state.Receipt -Operation 'Convert' -ObjectGuid $guid } + $state.AfterEight = $state.Imports + { Assert-PraCloudProofObject -Context $c -ProofPath $state.Receipt.StatePath -Source $state.Receipt -Operation 'Convert' -ObjectGuid '99999999-9999-9999-9999-999999999999' } | Should -Throw '*not in a verified AD phase*' + $sidecar = $state.Receipt.StatePath + '.sha256' + [IO.File]::WriteAllText($sidecar, [IO.File]::ReadAllText($sidecar)) + Assert-PraCloudProofObject -Context $c -ProofPath $state.Receipt.StatePath -Source $state.Receipt -Operation 'Convert' -ObjectGuid $state.Guids[0] + $state.AfterRewrite = $state.Imports + [IO.File]::AppendAllText($state.Receipt.StatePath, ' ') + { Assert-PraCloudProofObject -Context $c -ProofPath $state.Receipt.StatePath -Source $state.Receipt -Operation 'Convert' -ObjectGuid $state.Guids[0] } | Should -Throw '*SHA-256 mismatch*' + } + $global:PraGate.Scale.AfterEight | Should -Be 1 -Because 'eight checks, one reading of the proof' + $global:PraGate.Scale.AfterRewrite | Should -Be 2 -Because 'the .sha256 file has a new last write time: the proof is read again' + } + It 'the rows of a batch are added to the results once, however often the batch is previewed or applied' { + $context = $global:PraGate.Context + $plans = @(1..4 | ForEach-Object { New-PraPlan $context ('user' + $_) 'Convert' }) + $context.Mode = 'Preview'; $context.AllowMutation = $false + Invoke-PraAdPreview $context $plans + Invoke-PraAdPreview $context $plans + $context.Rows.Count | Should -Be 4 + $null = Invoke-PraAdBatch $context $plans 'Convert' + $context.Rows.Count | Should -Be 4 + @(Get-GateWrites $global:PraGate.Runtime).Count | Should -Be 0 + } +} + +Describe 'Release 3.2.0 - scale: one search of the backup folder serves every object (production Directory module, synthetic folders)' -Tag 'Release320c' { + It 'names the batch of each object (the newest one that a Recover did not roll back) reading each State file and each Convert backup once, not once per object' { + $root = Join-Path $global:PraGate.Root ('converted-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) + $guids = @(1..100 | ForEach-Object { '00000000-0000-0000-0000-{0:000000000000}' -f $_ }) + $make = { + param($Id, [string]$Operation, [string[]]$Listed, [string]$Created, [string]$BackupHash, [string]$SourceHash) + $folder = Join-Path $root ('Batch-' + $Id); $null = New-Item -ItemType Directory -Path $folder -Force + $state = [ordered]@{ SchemaVersion = 2; Operation = $Operation; Kind = 'ADVerified'; Environment = 'SYNTHETIC_GATE'; BackupHash = $BackupHash; SourceBackupHash = $SourceHash; CreatedUtc = $Created; Records = @($Listed | ForEach-Object { [ordered]@{ ObjectGuid = $_; Operation = $Operation; ADVerified = $true } }) } + [IO.File]::WriteAllText((Join-Path $folder ('State-' + $Id + '.json')), ($state | ConvertTo-Json -Depth 5), (New-Object Text.UTF8Encoding($true))) + if ($Operation -ceq 'Convert') { + $backup = [ordered]@{ SchemaVersion = 3; Operation = 'Convert'; Environment = 'SYNTHETIC_GATE'; BatchId = $Id; Records = @($Listed | ForEach-Object { [ordered]@{ ObjectGuid = $_ } }) } + [IO.File]::WriteAllText((Join-Path $folder ('Convert-SYNTHETIC_GATE-20261101_000000-' + $Id.Substring(0, 8) + '.json')), ($backup | ConvertTo-Json -Depth 5), (New-Object Text.UTF8Encoding($true))) + } + } + $older = '1111aaaa22223333444455556666bbbb'; $newer = '2222bbbb33334444555566667777cccc'; $recover = '3333cccc44445555666677778888dddd' + & $make $older 'Convert' $guids[0..59] '2026-11-01T10:00:00.0000000Z' ('ab' * 32) '' + & $make $newer 'Convert' $guids[40..99] '2026-11-02T10:00:00.0000000Z' ('cd' * 32) '' + & $make $recover 'Recover' $guids[40..49] '2026-11-03T10:00:00.0000000Z' ('ef' * 32) ('CD' * 32) + $global:PraGate.ConvertedBatches = @{ Root = $root; Guids = $guids; Reads = 0 } + $result = InModuleScope PRA.Directory { + $script:RealStateIndex = (Get-Command Get-PraRecordIndex).ScriptBlock + $script:RealBackupIndex = (Get-Command New-PraRecordIndex).ScriptBlock + Mock Get-PraRecordIndex { param($Record) $global:PraGate.ConvertedBatches.Reads++; & $script:RealStateIndex -Record $Record } + Mock New-PraRecordIndex { param($Record) $global:PraGate.ConvertedBatches.Reads++; & $script:RealBackupIndex -Record $Record } + $context = @{ Config = @{ Environment = 'synthetic_gate'; Storage = @{ BackupFolder = $global:PraGate.ConvertedBatches.Root } } } + $map = Find-PraConvertedBatches -Context $context -ObjectGuid ([string[]]($global:PraGate.ConvertedBatches.Guids + @('FFFFFFFF-0000-0000-0000-000000000001'))) + @{ Map = $map; Reads = $global:PraGate.ConvertedBatches.Reads; Single = (Find-PraConvertedBatch $context $global:PraGate.ConvertedBatches.Guids[4].ToUpperInvariant()) } + } + $result.Map.Count | Should -Be 100 + $result.Reads | Should -Be 5 -Because 'three State files and the two Convert backups, whatever the number of objects' + $result.Map[$guids[3]].ShortId | Should -BeExactly '1111aaaa' + $result.Map[$guids[45]].ShortId | Should -BeExactly '1111aaaa' -Because 'the newer batch was rolled back for this object' + $result.Map[$guids[55]].ShortId | Should -BeExactly '2222bbbb' + $result.Map[$guids[99].ToUpperInvariant()].ShortId | Should -BeExactly '2222bbbb' -Because 'the GUID is asked in any letter case' + $result.Map.ContainsKey('FFFFFFFF-0000-0000-0000-000000000001') | Should -BeFalse + $result.Single.ShortId | Should -BeExactly '1111aaaa' + } +} + Describe 'Release 3.2.0 - source anchors and the new cloud settings (production Common module)' -Tag 'Release320b' { BeforeAll { Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global } It 'ConvertTo-PraImmutableId gives the base64 of the 16 bytes of a GUID, whatever the form (object, text in any letter case, bytes, a one-item collection) and nothing for anything else' { @@ -10232,8 +10468,8 @@ Describe 'Release 3.2.0 - the cloud account is the one synchronised from Active $global:PraGate.R7NetworkPath = Join-Path $global:PraGate.Root 'PraGateR7Network.psm1' $networkSource = @' if ($env:PRA_GATE_NONET -cne 'SYNTHETIC-NO-NETWORK') { throw 'Synthetic interlock absent.' } -function Get-EXOMailbox { [CmdletBinding()]param($Filter,$Properties,$ResultSize,[switch]$InactiveMailboxOnly) throw 'SYNTHETIC BLOCK: EXO mailbox' } -function Get-EXORecipient { [CmdletBinding()]param($UserPrincipalName,$Filter,$Properties,$ResultSize) throw 'SYNTHETIC BLOCK: EXO recipient' } +function Get-EXOMailbox { [CmdletBinding()]param($Identity,$Filter,$Properties,$ResultSize,[switch]$InactiveMailboxOnly) throw 'SYNTHETIC BLOCK: EXO mailbox' } +function Get-EXORecipient { [CmdletBinding()]param($Identity,$UserPrincipalName,$Filter,$Properties,$ResultSize) throw 'SYNTHETIC BLOCK: EXO recipient' } function Get-MgUser { [CmdletBinding()]param($UserId,$Filter,$Property) throw 'SYNTHETIC BLOCK: Graph user' } function Get-MgUserLicenseDetail { [CmdletBinding()]param($UserId,[switch]$All) throw 'SYNTHETIC BLOCK: Graph licence' } function Get-MgContext { [CmdletBinding()]param() [pscustomobject]@{TenantId='20000000-0000-0000-0000-000000000002';ContextScope='Process'} } @@ -10274,9 +10510,9 @@ Export-ModuleMember -Function Get-EXOMailbox,Get-EXORecipient,Get-MgUser,Get-MgU @{ Name = 'the UPN is typed in other letter case than in Microsoft Entra ID'; Expect = 'Success'; Upn = 'USER1@GATE.INVALID'; Guid = 'ab12cd34-0000-4000-8000-0000000000ef'; Consistency = ''; Imm = [Convert]::ToBase64String(([guid]'ab12cd34-0000-4000-8000-0000000000ef').ToByteArray()); Legacy = $false; Message = '' } @{ Name = 'a record of an older version (no anchor stored) whose objectGUID matches'; Expect = 'Success'; Upn = 'user1@gate.invalid'; Guid = 'ab12cd34-0000-4000-8000-0000000000ef'; Consistency = ''; Imm = [Convert]::ToBase64String(([guid]'ab12cd34-0000-4000-8000-0000000000ef').ToByteArray()); Legacy = $true; Message = '' } @{ Name = 'the UPN is held by a cloud-only account'; Expect = 'Error'; Upn = 'user1@gate.invalid'; Guid = 'ab12cd34-0000-4000-8000-0000000000ef'; Consistency = ''; Imm = ''; Legacy = $false; Message = 'user1@gate\.invalid: the Microsoft Entra ID account with this UPN is not the account synchronised from this Active Directory object \(it is a cloud-only account\)\. Nothing was changed on it\. Give one of the two accounts another UPN' } - @{ Name = 'the UPN is held by an account synchronised from another object'; Expect = 'Error'; Upn = 'user1@gate.invalid'; Guid = 'ab12cd34-0000-4000-8000-0000000000ef'; Consistency = ''; Imm = [Convert]::ToBase64String(([guid]'11111111-0000-4000-8000-000000000001').ToByteArray()); Legacy = $false; Message = '\(it is synchronised from another Active Directory object\)' } - @{ Name = 'the anchor of the account differs only by letter case (it is a machine id, compared exactly)'; Expect = 'Error'; Upn = 'user1@gate.invalid'; Guid = 'ab12cd34-0000-4000-8000-0000000000ef'; Consistency = ''; Imm = ([Convert]::ToBase64String(([guid]'ab12cd34-0000-4000-8000-0000000000ef').ToByteArray())).ToLowerInvariant(); Legacy = $false; Message = 'synchronised from another Active Directory object' } - @{ Name = 'a record of an older version whose objectGUID does not match: the message says how to go on'; Expect = 'Error'; Upn = 'user1@gate.invalid'; Guid = 'ab12cd34-0000-4000-8000-0000000000ef'; Consistency = ''; Imm = [Convert]::ToBase64String(([guid]'11111111-0000-4000-8000-000000000001').ToByteArray()); Legacy = $true; Message = 'The record was written by an older version and holds only the objectGUID: .*set Cloud\.IdentityCheck = Off' } + @{ Name = 'the UPN is held by an account synchronised from another object'; Expect = 'Error'; Upn = 'user1@gate.invalid'; Guid = 'ab12cd34-0000-4000-8000-0000000000ef'; Consistency = ''; Imm = [Convert]::ToBase64String(([guid]'11111111-0000-4000-8000-000000000001').ToByteArray()); Legacy = $false; Message = 'is synchronised, but its onPremisesImmutableId is the base64 of a GUID, but not the objectGUID or the ms-DS-ConsistencyGuid.*may use another source anchor.*Cloud\.IdentityCheck = ''Off''' } + @{ Name = 'the anchor of the account differs only by letter case (it is a machine id, compared exactly)'; Expect = 'Error'; Upn = 'user1@gate.invalid'; Guid = 'ab12cd34-0000-4000-8000-0000000000ef'; Consistency = ''; Imm = ([Convert]::ToBase64String(([guid]'ab12cd34-0000-4000-8000-0000000000ef').ToByteArray())).ToLowerInvariant(); Legacy = $false; Message = 'synchronised, but its onPremisesImmutableId' } + @{ Name = 'a record of an older version whose objectGUID does not match: the message says how to go on'; Expect = 'Error'; Upn = 'user1@gate.invalid'; Guid = 'ab12cd34-0000-4000-8000-0000000000ef'; Consistency = ''; Imm = [Convert]::ToBase64String(([guid]'11111111-0000-4000-8000-000000000001').ToByteArray()); Legacy = $true; Message = 'may use another source anchor.*Cloud\.IdentityCheck = ''Off''.*The record was written by an older version: it holds only the objectGUID' } ) { $anchor = [Convert]::ToBase64String(([guid]$Guid).ToByteArray()) if ($Name -match 'letter case \(it is a machine id') { $Imm | Should -Not -BeExactly $anchor } @@ -10403,7 +10639,7 @@ Export-ModuleMember -Function Get-EXOMailbox,Get-EXORecipient,Get-MgUser,Get-MgU Mock Close-PraCloudSession { } Mock Start-Sleep { } Mock Get-MgUser { param($UserId, $Filter, $Property) @($global:PraGate.R7Accounts | Where-Object { $_.UserPrincipalName -ieq $UserId }) } - Mock Get-EXOMailbox { param($Filter, $Properties, $ResultSize) $global:PraGate.R7ExoCalls++; $global:PraGate.R7Props = @($Properties); $global:PraGate.R7Mailbox } + Mock Get-EXOMailbox { param($Identity, $Filter, $Properties, $ResultSize) $global:PraGate.R7ExoCalls++; $global:PraGate.R7Props = @($Properties); $global:PraGate.R7Lookup = [string]$Identity; $global:PraGate.R7Mailbox } Invoke-PraCloudPhase $global:PraGate.CloudContext @($global:PraGate.CloudRow) 'Convert' } $global:PraGate.R7Props | Should -Contain 'ExternalDirectoryObjectId' -Because 'the property is asked for' @@ -10480,7 +10716,7 @@ Export-ModuleMember -Function Get-EXOMailbox,Get-EXORecipient,Get-MgUser,Get-MgU SharedTrusteeAnchors = [pscustomobject]@{ 'good@gate.invalid' = @($trusteeConsistency, (New-R7Anchor '22222222-0000-4000-8000-000000000002')); 'cloudonly@gate.invalid' = @($trusteeAnchor); 'other@gate.invalid' = @($trusteeAnchor) } } $global:PraGate.R7Record = $record; $global:PraGate.R7Cases = @( @{ Trustee = 'cloudonly@gate.invalid'; Outcome = 'Failed'; Message = 'Permissions on shared1@gate\.invalid are not granted\. cloudonly@gate\.invalid: the Microsoft Entra ID account with this UPN is not the account synchronised from this Active Directory object \(it is a cloud-only account\)' } - @{ Trustee = 'other@gate.invalid'; Outcome = 'Failed'; Message = 'other@gate\.invalid: .*\(it is synchronised from another Active Directory object\)' } + @{ Trustee = 'other@gate.invalid'; Outcome = 'Failed'; Message = 'other@gate\.invalid: .*is synchronised, but its onPremisesImmutableId' } @{ Trustee = 'GOOD@gate.invalid'; Outcome = 'Ok'; Message = '' } @{ Trustee = 'older@gate.invalid'; Outcome = 'Ok'; Message = '' } @{ Trustee = 'unknown@gate.invalid'; Outcome = 'Ok'; Message = '' }) @@ -10905,6 +11141,478 @@ Export-ModuleMember -Function Get-EXOMailbox,Get-ConnectionInformation } } +Describe 'Release 3.2.0 - the stop of a run, a grant never repeated, custom source anchors, Graph refusals, one read per account, lookups by the confirmed id, inactive mailboxes (production Cloud module, mocked boundaries, no network)' -Tag 'Release320b' { + BeforeAll { + $global:PraGate.R9NetworkPath = Join-Path $global:PraGate.Root 'PraGateR9Network.psm1' + $networkSource = @' +if ($env:PRA_GATE_NONET -cne 'SYNTHETIC-NO-NETWORK') { throw 'Synthetic interlock absent.' } +function Get-EXOMailbox { [CmdletBinding()]param($Identity,$Filter,$Properties,$ResultSize,[switch]$InactiveMailboxOnly) throw 'SYNTHETIC BLOCK: EXO mailbox' } +function Get-EXORecipient { [CmdletBinding()]param($Identity,$UserPrincipalName,$Filter,$Properties,$ResultSize) throw 'SYNTHETIC BLOCK: EXO recipient' } +function Get-MgUser { [CmdletBinding()]param($UserId,$Filter,$Property) throw 'SYNTHETIC BLOCK: Graph user' } +function Get-MgUserLicenseDetail { [CmdletBinding()]param($UserId,[switch]$All) throw 'SYNTHETIC BLOCK: Graph licence' } +function Get-MgContext { [CmdletBinding()]param() [pscustomobject]@{TenantId='20000000-0000-0000-0000-000000000002';ContextScope='Process'} } +function Get-ConnectionInformation { [CmdletBinding()]param() [pscustomobject]@{TenantID='20000000-0000-0000-0000-000000000002';State='Connected';TokenStatus='Active';ConnectionId='30000000-0000-0000-0000-000000000003';ModuleName=$global:PraGate.R9NetworkPath} } +Export-ModuleMember -Function Get-EXOMailbox,Get-EXORecipient,Get-MgUser,Get-MgUserLicenseDetail,Get-MgContext,Get-ConnectionInformation +'@ + [IO.File]::WriteAllText($global:PraGate.R9NetworkPath, $networkSource, (New-Object Text.UTF8Encoding($true))) + Get-Module PRA.Cloud -All | Remove-Module -Force -ErrorAction SilentlyContinue + Import-Module $global:PraGate.R9NetworkPath -Global -Force + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Cloud.psm1') -Force -Global + function global:New-R9Anchor { param([string]$Guid) [Convert]::ToBase64String(([guid]$Guid).ToByteArray()) } + function global:New-R9Row { + param([string]$Upn = 'user1@gate.invalid', [string]$Guid = 'ab12cd34-0000-4000-8000-0000000000ef', [switch]$Shared, [string[]]$Trustees = @(), [hashtable]$TrusteeAnchors = $null, [switch]$Incomplete) + $record = [ordered]@{ ObjectGuid = $Guid; UserPrincipalName = $Upn; SamAccountName = $Upn.Split('@')[0]; IsShared = [bool]$Shared; SourceAnchor = [ordered]@{ ObjectGuid = (New-R9Anchor $Guid); ConsistencyGuid = '' } } + if ($null -ne $TrusteeAnchors) { $record.SharedTrusteeAnchors = [pscustomobject]$TrusteeAnchors } + if ($Incomplete) { $record.SharedTrusteeAnchorsIncomplete = $true } + $row = New-PraRow $global:PraGate.CloudContext ([pscustomobject]$record) + if ($Trustees.Count) { $row.SharedFullAccess = $Trustees } + $row + } + function global:New-R9Account { + param([string]$Id = 'aaaaaaaa-0000-0000-0000-000000000001', [string]$Upn = 'user1@gate.invalid', [string]$Immutable = '', [switch]$Ready) + [pscustomobject]@{ Id = $Id; UserPrincipalName = $Upn; OnPremisesImmutableId = $Immutable; OnPremisesSyncEnabled = [bool]$Immutable + assignedPlans = @([pscustomobject]@{ Service = 'exchange'; CapabilityStatus = 'Enabled' }) + provisionedPlans = @(if ($Ready) { [pscustomobject]@{ Service = 'exchange'; ProvisioningStatus = 'Success' } }) + assignedLicenses = @([pscustomobject]@{ SkuId = 'sku' }) } + } + function global:New-R9Failure { + param([int]$Status, [int]$RetryAfter = 0, [string]$Text = '') + $exception = [System.Net.Http.HttpRequestException]::new($(if ($Text) { $Text } else { "Response status code does not indicate success: $Status." }), $null, [System.Net.HttpStatusCode]$Status) + if ($RetryAfter) { + $response = [System.Net.Http.HttpResponseMessage]::new([System.Net.HttpStatusCode]$Status) + $response.Headers.RetryAfter = [System.Net.Http.Headers.RetryConditionHeaderValue]::new([TimeSpan]::FromSeconds($RetryAfter)) + Add-Member -InputObject $exception -NotePropertyName Response -NotePropertyValue $response + } + $exception + } + } + BeforeEach { + $global:PraGate.Runtime = New-GateRuntime -Name 'review-320b' + $context = New-GateContext $global:PraGate.Runtime -Mode Apply -Action Convert + $context.Phase = 'Cloud'; $context.Once = $false; $context.CheckScope = 'Both'; $context.IntervalMinutes = 0; $context.TimeoutMinutes = 5 + $context.Config.Cloud = @{ CheckMailbox = $true; CheckLicense = $false; MailboxCheckVia = 'Exo'; RequiredSkuPartNumber = ''; IdentityCheck = 'Off'; TenantId = '20000000-0000-0000-0000-000000000002' } + $context.Config.SharedMailbox = @{ Enabled = $true; PermissionSource = 'AD'; GrantFullAccess = $true; GrantSendAs = $false; GrantSendOnBehalf = $false; AutoMapping = $false } + $context.LogFile = Join-Path $global:PraGate.Runtime.Root 'logs\review-320b.log' + $global:PraGate.CloudContext = $context + $global:PraGate.R9Binding = @{ TenantId = '20000000-0000-0000-0000-000000000002'; ConnectionId = '30000000-0000-0000-0000-000000000003'; ModuleLocation = $global:PraGate.R9NetworkPath; ModulePath = $global:PraGate.R9NetworkPath } + $global:PraGate.R9Calls = 0; $global:PraGate.R9Grants = 0; $global:PraGate.R9Reads = New-Object 'Collections.Generic.List[string]'; $global:PraGate.R9Mailbox = [pscustomobject]@{ RecipientTypeDetails = 'UserMailbox'; EmailAddresses = [string[]]@('SMTP:x@gate.invalid') } + } + AfterAll { + Remove-Item -LiteralPath 'Function:\New-R9Anchor', 'Function:\New-R9Row', 'Function:\New-R9Account', 'Function:\New-R9Failure' -ErrorAction SilentlyContinue + Remove-Module PRA.Cloud, PraGateR9Network -Force -ErrorAction SilentlyContinue + } + It 'the pause before a call that would pass the run budget stops the run like a retry does: one error, the rows done keep their result, the others stay Pending, nothing is turned into an error' { + $global:PraGate.CloudContext.Config.Cloud.RetryBudgetRunMinutes = 1 + $global:PraGate.CloudRows = @(1..3 | ForEach-Object { New-R9Row -Upn "user$_@gate.invalid" -Guid ('00000000-0000-0000-0000-00000000000' + $_) }) + InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { param($Context) $Context['_PraCloudSession'] = @{ Graph = $false; Exo = $true; Subprocess = $false; Binding = $global:PraGate.R9Binding } } + Mock Close-PraCloudSession { } + Mock Start-Sleep { } + Mock Get-EXOMailbox { + $global:PraGate.R9Calls++ + $state = Get-PraRetryState $global:PraGate.CloudContext + $state.Pace = 30; $state.RunSpent = 50; $state.Throttled = 3 + $global:PraGate.R9Mailbox + } + Invoke-PraCloudPhase $global:PraGate.CloudContext $global:PraGate.CloudRows 'Convert' + } + $context = $global:PraGate.CloudContext; $rows = $global:PraGate.CloudRows + $context.Issues.Count | Should -Be 1 + [string]$context.Issues[0].Message | Should -Match 'minute\(s\) allowed for retries are used up .* 2 object\(s\) were not finished\.$' + $rows[0].CloudStatus | Should -BeExactly 'Success' + $rows[0].FinalStatus | Should -BeExactly 'Success' + @($rows[1], $rows[2] | Where-Object { $_.FinalStatus -ceq 'Pending' }).Count | Should -Be 2 + @($rows | Where-Object { $_.CloudStatus -ceq 'Error' }).Count | Should -Be 0 + $global:PraGate.R9Calls | Should -Be 1 -Because 'the second object was refused before any call' + $context.CloudThrottled | Should -BeTrue + } + It 'a grant whose step failed is never sent twice in a run: the error is final for the object, one grant, one error, the next step is the cloud phase again later' { + $global:PraGate.CloudRows = @(New-R9Row -Upn 'shared1@gate.invalid' -Shared -Trustees @('trustee1@gate.invalid')) + InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { param($Context) $Context['_PraCloudSession'] = @{ Graph = $false; Exo = $true; Subprocess = $false; Binding = $global:PraGate.R9Binding } } + Mock Close-PraCloudSession { } + Mock Start-Sleep { } + Mock Invoke-PraExo { + if ($Operation -ceq 'Mailbox') { @{ Found = $true; Type = 'SharedMailbox'; HasAddresses = $false; Addresses = @() } } + else { @{ TrusteeFound = $true; Verified = $false; Mutated = $false } } + } + Mock Invoke-PraPermissionGrant { $global:PraGate.R9Grants++; throw 'Add returned, verification failed: Response status code does not indicate success: 429 (Too Many Requests).' } + Invoke-PraCloudPhase $global:PraGate.CloudContext $global:PraGate.CloudRows 'Convert' + } + $context = $global:PraGate.CloudContext + $global:PraGate.R9Grants | Should -Be 1 -Because 'a second check would grant again with a new approval and new journal lines' + $context.Issues.Count | Should -Be 1 + [string]$context.Issues[0].Message | Should -Match 'shared1@gate\.invalid: a shared mailbox permission could not be granted or verified \(Add returned, verification failed: .*429.*\)\. It is not granted a second time in this run: run the cloud phase again later, it reads the permissions first and grants only what is missing\.' + [string]$context.Issues[0].Message | Should -Not -Match 'retry time' + $global:PraGate.CloudRows[0].CloudStatus | Should -BeExactly 'Error' + $global:PraGate.CloudRows[0].RunError | Should -BeTrue + } + It 'a synchronised account whose onPremisesImmutableId is not an anchor of the record (a GUID that is not the objectGUID, text that is not a GUID) says that the tenant may use another source anchor and points to IdentityCheck = Off, for a current record and an older one; it never advises another UPN' { + $global:PraGate.CloudContext.Config.Cloud.IdentityCheck = 'Anchor' + $global:PraGate.R9Anchor = New-R9Anchor 'ab12cd34-0000-4000-8000-0000000000ef' + $global:PraGate.R9Cases = @(@{ Imm = 'jdoe@contoso.com'; Form = 'is not the base64 of a GUID'; Recorded = $true }, @{ Imm = (New-R9Anchor '11111111-0000-4000-8000-000000000001'); Form = 'is the base64 of a GUID, but not the objectGUID or the ms-DS-ConsistencyGuid'; Recorded = $false }) + InModuleScope PRA.Cloud { + Mock Assert-PraGraphSession { } + Mock Get-MgUser { param($UserId, $Filter, $Property) [pscustomobject]@{ Id = 'aaaaaaaa-0000-0000-0000-000000000001'; UserPrincipalName = $UserId; OnPremisesImmutableId = $global:PraGate.R9Imm; OnPremisesSyncEnabled = $true } } + foreach ($case in $global:PraGate.R9Cases) { + $global:PraGate.R9Imm = $case.Imm + $verdict = Resolve-PraCloudIdentity -Context $global:PraGate.CloudContext -Upn 'user1@gate.invalid' -Anchors @($global:PraGate.R9Anchor) -Recorded $case.Recorded + $verdict.Status | Should -BeExactly 'Mismatch' + $verdict.Message | Should -Match ([regex]::Escape('its onPremisesImmutableId ' + $case.Form)) + $verdict.Message | Should -Match 'Your tenant may use another source anchor than the objectGUID or the ms-DS-ConsistencyGuid' + $verdict.Message | Should -Match ([regex]::Escape("set Cloud.IdentityCheck = 'Off'")) + $verdict.Message | Should -Not -Match 'another UPN' + if (-not $case.Recorded) { $verdict.Message | Should -Match 'written by an older version' } else { $verdict.Message | Should -Not -Match 'older version' } + } + } + } + It 'a record whose trustee anchors are incomplete (the schema could not be read) asks no more of a trustee than a synchronised account; a complete record still compares the anchors' { + $global:PraGate.CloudContext.Config.Cloud.IdentityCheck = 'Anchor' + $objectGuid = 'ab12cd34-0000-4000-8000-000000000bbb'; $anchor = New-R9Anchor $objectGuid + $global:PraGate.R9Accounts = @{ 'shared1@gate.invalid' = $anchor; 'good@gate.invalid' = 'a-synchronised-anchor-of-another-kind' } + $global:PraGate.R9Rows = @{ Incomplete = (New-R9Row -Upn 'shared1@gate.invalid' -Guid $objectGuid -Shared -TrusteeAnchors @{ 'good@gate.invalid' = @((New-R9Anchor '22222222-0000-4000-8000-000000000002')) } -Incomplete) + Complete = (New-R9Row -Upn 'shared1@gate.invalid' -Guid $objectGuid -Shared -TrusteeAnchors @{ 'good@gate.invalid' = @((New-R9Anchor '22222222-0000-4000-8000-000000000002')) }) } + $outcomes = InModuleScope PRA.Cloud { + Mock Assert-PraGraphSession { } + Mock Get-MgUser { param($UserId, $Filter, $Property) if ($UserId) { [pscustomobject]@{ Id = 'cccccccc-0000-0000-0000-000000000001'; UserPrincipalName = $UserId; OnPremisesImmutableId = $global:PraGate.R9Accounts[$UserId]; OnPremisesSyncEnabled = $true } } } + $result = @{} + foreach ($name in 'Incomplete', 'Complete') { + $context = New-GateContext $global:PraGate.Runtime -Mode Apply -Action Convert + $context.Config.Cloud = @{ IdentityCheck = 'Anchor' } + $state = @{ Row = $global:PraGate.R9Rows[$name]; Upn = 'shared1@gate.invalid'; Requests = @([pscustomobject]@{ Right = 'FullAccess'; Trustee = 'good@gate.invalid' }); PlainText = '' } + $result[$name] = Confirm-PraCloudIdentity -Context $context -State $state + } + $result + } + $outcomes.Incomplete | Should -BeExactly 'Ok' + $outcomes.Complete | Should -BeExactly 'Failed' + } + It 'a Graph refusal (403, insufficient privileges) in the identity check names User.Read.All (delegated, application with admin consent) and the IdentityCheck = Off alternative; in the pre-check it stops before any change' { + $global:PraGate.CloudContext.Config.Cloud.IdentityCheck = 'Anchor' + $global:PraGate.CloudRows = @(New-R9Row) + $result = InModuleScope PRA.Cloud { + Mock Assert-PraGraphSession { } + Mock Get-MgUser { throw (New-R9Failure -Status 403 -Text 'Insufficient privileges to complete the operation.') } + $state = @{ Row = $global:PraGate.CloudRows[0]; Upn = 'user1@gate.invalid'; Requests = @(); PlainText = '' } + $outcome = Confirm-PraCloudIdentity -Context $global:PraGate.CloudContext -State $state + $thrown = '' + try { $null = Confirm-PraCloudIdentity -Context $global:PraGate.CloudContext -State $state -Throw } catch { $thrown = $_.Exception.Message } + @{ Outcome = $outcome; Thrown = $thrown } + } + $result.Outcome | Should -BeExactly 'Failed' + $context = $global:PraGate.CloudContext + $context.Issues.Count | Should -Be 1 + foreach ($text in @([string]$context.Issues[0].Message, [string]$result.Thrown)) { + $text | Should -Match 'user1@gate\.invalid: Microsoft Graph refused to read the Microsoft Entra ID account that confirms this object \(HTTP 403\)\. Nothing was changed\.' + $text | Should -Match 'permission User\.Read\.All: with a sign-in by a person, the administrator must consent to User\.Read\.All; with a certificate \(application\), add the application permission User\.Read\.All to the app registration and grant admin consent' + $text | Should -Match ([regex]::Escape("set Cloud.IdentityCheck = 'Off'")) + } + $global:PraGate.CloudRows[0].RunError | Should -BeTrue + } + It 'the account is read once for the identity and the first facts (one Graph read at the first check), then by its confirmed id at the next check; the Graph properties are folded in one select' { + $global:PraGate.CloudContext.Config.Cloud = @{ CheckMailbox = $true; CheckLicense = $true; MailboxCheckVia = 'Graph'; RequiredSkuPartNumber = ''; IdentityCheck = 'Anchor'; TenantId = '20000000-0000-0000-0000-000000000002' } + $global:PraGate.R9Anchor = New-R9Anchor 'ab12cd34-0000-4000-8000-0000000000ef'; $global:PraGate.R9Props = @() + $global:PraGate.CloudRows = @(New-R9Row) + InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { param($Context) $Context['_PraCloudSession'] = @{ Graph = $true; Exo = $false; Subprocess = $false; Binding = $null } } + Mock Assert-PraGraphSession { } + Mock Close-PraCloudSession { } + Mock Start-Sleep { } + Mock Get-MgUser { + param($UserId, $Filter, $Property) + $global:PraGate.R9Reads.Add([string]$UserId) + if ($global:PraGate.R9Reads.Count -eq 1) { $global:PraGate.R9Props = @($Property) } + New-R9Account -Immutable $global:PraGate.R9Anchor -Ready:($global:PraGate.R9Reads.Count -ge 2) + } + Mock Get-MgUserLicenseDetail { param($UserId, $All) $global:PraGate.R9Reads.Add('licence:' + $UserId); @() } + Invoke-PraCloudPhase $global:PraGate.CloudContext $global:PraGate.CloudRows 'Convert' + } + $context = $global:PraGate.CloudContext + $context.Issues.Count | Should -Be 0 + $global:PraGate.CloudRows[0].CloudStatus | Should -BeExactly 'Success' + @($global:PraGate.R9Reads)[0] | Should -BeExactly 'user1@gate.invalid' + @($global:PraGate.R9Reads | Where-Object { $_ -notmatch '^licence:' }).Count | Should -Be 2 -Because 'one read for the identity and the first facts, one read at the next check' + @($global:PraGate.R9Reads | Where-Object { $_ -notmatch '^licence:' })[1] | Should -BeExactly 'aaaaaaaa-0000-0000-0000-000000000001' -Because 'the facts are read by the confirmed id' + foreach ($name in 'id', 'onPremisesImmutableId', 'onPremisesSyncEnabled', 'assignedPlans', 'provisionedPlans', 'assignedLicenses') { @($global:PraGate.R9Props) | Should -Contain $name } + } + It 'the pre-check reuses the account read for the identity: one Graph read per object, and its id is compared with the one Exchange Online returns' { + $global:PraGate.CloudContext.Config.Cloud = @{ CheckMailbox = $true; CheckLicense = $true; MailboxCheckVia = 'Exo'; RequiredSkuPartNumber = ''; IdentityCheck = 'Anchor'; TenantId = '20000000-0000-0000-0000-000000000002' } + $global:PraGate.CloudContext.Phase = 'Both' + $global:PraGate.R9Anchor = New-R9Anchor 'ab12cd34-0000-4000-8000-0000000000ef' + $global:PraGate.CloudRows = @(New-R9Row) + $outcome = InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { param($Context) $Context['_PraCloudSession'] = @{ Graph = $true; Exo = $true; Subprocess = $false; Binding = $global:PraGate.R9Binding; Identities = @{}; Preflight = $false } } + Mock Assert-PraGraphSession { } + Mock Close-PraCloudSession { } + Mock Get-MgUser { param($UserId, $Filter, $Property) $global:PraGate.R9Reads.Add([string]$UserId); New-R9Account -Immutable $global:PraGate.R9Anchor } + Mock Invoke-PraExo { @{ Found = $true; Type = 'UserMailbox'; Identities = @{ 'user1@gate.invalid' = @{ ObjectId = $global:PraGate.R9ExoId; PrimarySmtpAddress = 'user1@gate.invalid' } } } } + $answers = @{} + foreach ($exoId in 'aaaaaaaa-0000-0000-0000-000000000001', 'bbbbbbbb-0000-0000-0000-000000000009') { + $global:PraGate.R9ExoId = $exoId; $global:PraGate.R9Reads.Clear(); $global:PraGate.CloudContext.Remove('_PraCloudSession') + try { Initialize-PraCloudPreflight -Context $global:PraGate.CloudContext -Rows $global:PraGate.CloudRows; $answers[$exoId] = @{ Error = ''; Reads = $global:PraGate.R9Reads.Count } } + catch { $answers[$exoId] = @{ Error = $_.Exception.Message; Reads = $global:PraGate.R9Reads.Count } } + } + $answers + } + $outcome['aaaaaaaa-0000-0000-0000-000000000001'].Error | Should -BeExactly '' + $outcome['aaaaaaaa-0000-0000-0000-000000000001'].Reads | Should -Be 1 + $outcome['bbbbbbbb-0000-0000-0000-000000000009'].Error | Should -Match 'Graph and Exchange Online identities differ at the pre-check: user1@gate\.invalid' + } + It 'the budgets count the seconds that a failed call itself took, not only the waits (a call that times out after 2 s counts for 2 s)' { + $global:PraGate.CloudContext.Config.Cloud.RetryBudgetObjectSeconds = 3 + $global:PraGate.CloudContext.CurrentIdentity = 'object1' + $global:PraGate.R9Failure = New-R9Failure -Status 429 -RetryAfter 1 + $result = InModuleScope PRA.Cloud { + Mock Start-Sleep { } + $slow = { $global:PraGate.R9Calls++; [Threading.Thread]::Sleep(2100); throw $global:PraGate.R9Failure } + try { Invoke-PraCloudCall -Context $global:PraGate.CloudContext -Call 'Microsoft Graph user' -Script $slow; $null } catch { $_.Exception.Message } + @{ Calls = $global:PraGate.R9Calls; Spent = (Get-PraRetryState $global:PraGate.CloudContext).RunSpent } + } + $result.Calls | Should -Be 2 -Because '2 s of the call + 1 s of wait = 3 s, then 2 s more of the second call: over the 3 s of the object' + $result.Spent | Should -BeGreaterOrEqual 5 + [IO.File]::ReadAllText($global:PraGate.CloudContext.LogFile) | Should -Match 'Retry budget used up \| Microsoft Graph user \| object1 \| status 429 \| 2 tries \| object [5-9] of 3 s' + } + It 'a Retry-After given as an HTTP date is a date, never the day number: seconds from now (capped), a past date gives 0, a number stays a number, in the text and in a header table' { + $future = [DateTimeOffset]::UtcNow.AddSeconds(90).ToString('r', [Globalization.CultureInfo]::InvariantCulture) + $global:PraGate.R9Texts = @( + @{ Text = "HttpStatusCode=429 TooManyRequests Retry-After: $future"; Min = 85; Max = 91 } + @{ Text = 'HttpStatusCode=429 Retry-After: Wed, 21 Oct 2015 07:28:00 GMT'; Min = 0; Max = 0 } + @{ Text = 'HttpStatusCode=429 Retry-After: 30'; Min = 30; Max = 30 } + @{ Text = 'HttpStatusCode=503 retry-after=7 seconds'; Min = 7; Max = 7 }) + $global:PraGate.R9Future = $future + $answers = InModuleScope PRA.Cloud { + $found = @(foreach ($case in $global:PraGate.R9Texts) { (Get-PraCloudFailureInfo ([Management.Automation.ErrorRecord]::new([InvalidOperationException]::new($case.Text), 'x', [Management.Automation.ErrorCategory]::NotSpecified, $null))).RetryAfter }) + $exception = [System.Net.Http.HttpRequestException]::new('Too Many Requests', $null, [System.Net.HttpStatusCode]429) + Add-Member -InputObject $exception -NotePropertyName Response -NotePropertyValue ([pscustomobject]@{ StatusCode = 429; Headers = @{ 'Retry-After' = $global:PraGate.R9Future } }) + $header = (Get-PraCloudFailureInfo ([Management.Automation.ErrorRecord]::new($exception, 'x', [Management.Automation.ErrorCategory]::NotSpecified, $null))).RetryAfter + @{ Found = $found; Header = $header } + } + for ($i = 0; $i -lt $global:PraGate.R9Texts.Count; $i++) { $answers.Found[$i] | Should -BeGreaterOrEqual $global:PraGate.R9Texts[$i].Min; $answers.Found[$i] | Should -BeLessOrEqual $global:PraGate.R9Texts[$i].Max } + $answers.Header | Should -BeGreaterOrEqual 85 + $answers.Header | Should -BeLessOrEqual 91 + } + It 'the wording says what happened: a throttled answer that was not retried (budget 0) is not "retry time used up"; a run stopped by network failures is a network failure, not "limited the requests"' { + $global:PraGate.CloudContext.Config.Cloud.RetryBudgetObjectSeconds = 0 + $global:PraGate.CloudContext.Once = $true + $global:PraGate.CloudRows = @(New-R9Row) + InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { param($Context) $Context['_PraCloudSession'] = @{ Graph = $false; Exo = $true; Subprocess = $false; Binding = $global:PraGate.R9Binding } } + Mock Close-PraCloudSession { } + Mock Start-Sleep { } + Mock Get-EXOMailbox { throw (New-R9Failure -Status 429) } + Invoke-PraCloudPhase $global:PraGate.CloudContext $global:PraGate.CloudRows 'Convert' + } + [string]$global:PraGate.CloudContext.Issues[0].Message | Should -BeExactly 'user1@gate.invalid: Microsoft 365 limited the requests or was unavailable (HTTP 429); the call was not sent again (a look that cannot wait, a retry budget of 0, or a write). Run again in a few minutes.' + $global:PraGate.CloudContext = New-GateContext $global:PraGate.Runtime -Mode Apply -Action Convert + $global:PraGate.CloudContext.Config.Cloud = @{ RetryBudgetObjectSeconds = 3600; RetryBudgetRunMinutes = 1; IdentityCheck = 'Off' } + $global:PraGate.CloudContext.LogFile = Join-Path $global:PraGate.Runtime.Root 'logs\network-stop.log' + $global:PraGate.CloudContext.CurrentIdentity = 'object1' + $stop = InModuleScope PRA.Cloud { + Mock Start-Sleep { } + $down = { throw [System.Net.Http.HttpRequestException]::new('No connection could be made.', [System.Net.Sockets.SocketException]::new(10061)) } + try { Invoke-PraCloudCall -Context $global:PraGate.CloudContext -Call 'Microsoft Graph user' -Script $down; '' } catch { $_.Exception.Message } + } + $stop | Should -Match '^Microsoft 365 did not answer \(network\): the 1 minute\(s\) allowed for retries are used up \(3 retries\)\. Nothing more is asked of Microsoft 365\.' + Get-PraValue $global:PraGate.CloudContext 'CloudThrottled' $false | Should -BeFalse + $global:PraGate.CloudContext.NetworkFailure | Should -BeTrue + } + It 'the Exchange Online object of a confirmed account is looked up by its Entra id (recipient, mailbox, SendOnBehalf mailbox), by the UPN only when no id is known; the ExternalDirectoryObjectId is still compared' { + $global:PraGate.R9Worker = @{ Binding = $global:PraGate.R9Binding } + $global:PraGate.R9Seen = @{} + $result = InModuleScope PRA.Cloud { + Mock Get-EXORecipient { + param($Identity, $UserPrincipalName, $Filter, $Properties, $ResultSize) + $global:PraGate.R9Seen['Recipient'] = '{0}|{1}' -f $Identity, $UserPrincipalName + [pscustomobject]@{ RecipientTypeDetails = 'UserMailbox'; PrimarySmtpAddress = 'user1@gate.invalid'; ExternalDirectoryObjectId = $global:PraGate.R9ExoId; Guid = [guid]::NewGuid(); DistinguishedName = 'CN=user1' } + } + Mock Get-EXOMailbox { + param($Identity, $Filter, $Properties, $ResultSize, $InactiveMailboxOnly) + $global:PraGate.R9Seen['Mailbox'] = '{0}|{1}' -f $Identity, $Filter + [pscustomobject]@{ RecipientTypeDetails = 'UserMailbox'; EmailAddresses = [string[]]@('SMTP:user1@gate.invalid'); ExternalDirectoryObjectId = $global:PraGate.R9ExoId } + } + $global:PraGate.R9ExoId = 'aaaaaaaa-0000-0000-0000-000000000001' + $answers = @{} + foreach ($operation in 'Recipient', 'Mailbox') { + $null = & $script:PraExoWorker $operation @{ Upn = 'User1@Gate.Invalid'; VerifiedObjectIds = @{ 'user1@gate.invalid' = 'AAAAAAAA-0000-0000-0000-000000000001' } } $null $global:PraGate.R9Worker.Binding $null $null + $answers[$operation + '-confirmed'] = $global:PraGate.R9Seen[$operation] + $null = & $script:PraExoWorker $operation @{ Upn = 'user1@gate.invalid'; VerifiedObjectIds = @{} } $null $global:PraGate.R9Worker.Binding $null $null + $answers[$operation + '-unknown'] = $global:PraGate.R9Seen[$operation] + } + $global:PraGate.R9ExoId = 'bbbbbbbb-0000-0000-0000-000000000009' + try { $null = & $script:PraExoWorker 'Mailbox' @{ Upn = 'user1@gate.invalid'; VerifiedObjectIds = @{ 'user1@gate.invalid' = 'aaaaaaaa-0000-0000-0000-000000000001' } } $null $global:PraGate.R9Worker.Binding $null $null; $answers.Compared = '' } catch { $answers.Compared = $_.Exception.Message } + $answers + } + $result['Recipient-confirmed'] | Should -BeExactly 'AAAAAAAA-0000-0000-0000-000000000001|' + $result['Mailbox-confirmed'] | Should -BeExactly 'AAAAAAAA-0000-0000-0000-000000000001|' + $result['Recipient-unknown'] | Should -BeExactly '|user1@gate.invalid' + $result['Mailbox-unknown'] | Should -Match '^\|UserPrincipalName -eq ''user1@gate\.invalid''' + $result.Compared | Should -Match 'The Exchange Online mailbox is not the Microsoft Entra ID account confirmed for this object' + } + It 'an inactive mailbox is not refused for carrying the ExternalDirectoryObjectId of its deleted account: it is found by UPN and flagged; several inactive mailboxes are an ambiguity unless the recorded anchor tells them apart' { + $global:PraGate.R9Worker = @{ Binding = $global:PraGate.R9Binding } + $anchor = New-R9Anchor 'ab12cd34-0000-4000-8000-0000000000ef' + $inactive = { param($Eoid, $Immutable, $Hold) $m = [pscustomobject]@{ RecipientTypeDetails = 'UserMailbox'; EmailAddresses = [string[]]@('SMTP:user1@gate.invalid'); ExternalDirectoryObjectId = $Eoid; IsInactiveMailbox = $true; InPlaceHolds = @($Hold) }; if ($Immutable) { Add-Member -InputObject $m -NotePropertyName ImmutableId -NotePropertyValue $Immutable }; $m } + $global:PraGate.R9Cases = @{ + One = @(& $inactive 'dddddddd-0000-0000-0000-000000000001' '' 'mbx40000000000000000000000000000004') + Two = @((& $inactive 'dddddddd-0000-0000-0000-000000000001' '' 'mbx40000000000000000000000000000004'), (& $inactive 'dddddddd-0000-0000-0000-000000000002' '' 'mbx40000000000000000000000000000004')) + Tell = @((& $inactive 'dddddddd-0000-0000-0000-000000000001' 'not-this-anchor' 'mbx40000000000000000000000000000001'), (& $inactive 'dddddddd-0000-0000-0000-000000000002' $anchor 'mbx40000000000000000000000000000002')) } + $global:PraGate.R9Anchor = $anchor + $result = InModuleScope PRA.Cloud { + Mock Get-EXOMailbox { + param($Identity, $Filter, $Properties, $ResultSize, $InactiveMailboxOnly) + if ($Identity) { throw "The operation couldn't be performed because object 'x' couldn't be found on 'y'." } + if ($InactiveMailboxOnly) { $global:PraGate.R9Inactive } + } + $answers = @{} + foreach ($name in 'One', 'Two', 'Tell') { + $global:PraGate.R9Inactive = $global:PraGate.R9Cases[$name] + try { $answers[$name] = & $script:PraExoWorker 'Hold' @{ Upn = 'user1@gate.invalid'; VerifiedObjectIds = @{ 'user1@gate.invalid' = 'aaaaaaaa-0000-0000-0000-000000000001' }; Anchors = @($global:PraGate.R9Anchor) } $null $global:PraGate.R9Worker.Binding $null $null } + catch { $answers[$name] = $_.Exception.Message } + } + $answers + } + $result.One.Found | Should -BeTrue + $result.One.IdentityByUpn | Should -BeTrue + $result.Two | Should -Match 'Exchange Online has 2 inactive mailboxes for user1@gate\.invalid and nothing tells which one belongs to this object' + $result.Tell.Found | Should -BeTrue + @($result.Tell.Holds) | Should -BeExactly @('mbx40000000000000000000000000000002') -Because 'the mailbox that carries the recorded anchor' + } + It 'the retention check says that an inactive mailbox was found by UPN only (a warning on the object), and the check still goes on' { + $context = New-GateContext $global:PraGate.Runtime -Mode Preview -Action Check + $context.Config.Cloud = @{ CheckMailbox = $true; CheckLicense = $false; MailboxCheckVia = 'Exo'; RequiredSkuPartNumber = ''; IdentityCheck = 'Off'; TenantId = '20000000-0000-0000-0000-000000000002' } + $context.Config.Retention = @{ Enabled = $true; PolicyGuid = '40000000-0000-0000-0000-000000000004'; PolicyName = ''; UseComplianceSession = $false } + $context.LogFile = Join-Path $global:PraGate.Runtime.Root 'logs\retention-inactive.log' + $global:PraGate.CloudContext = $context; $global:PraGate.CloudRows = @(New-R9Row) + InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { param($Context) $Context['_PraCloudSession'] = @{ Graph = $false; Exo = $true; Subprocess = $false; Binding = $global:PraGate.R9Binding } } + Mock Close-PraCloudSession { } + Mock Invoke-PraExo { @{ Found = $true; Type = 'UserMailbox'; Holds = @('mbx40000000000000000000000000000004'); IsInactive = $true; Litigation = $false; RetentionHold = $false; IdentityByUpn = $true } } + Invoke-PraRetentionCheck $global:PraGate.CloudContext $global:PraGate.CloudRows + } + $global:PraGate.CloudRows[0].CloudStatus | Should -BeExactly 'Success' + $global:PraGate.CloudRows[0].Warnings | Should -Match 'user1@gate\.invalid: the inactive mailbox is found by its UPN only: its account is deleted, so it cannot be confirmed against Active Directory' + $context.Warnings | Should -Be 1 + } + It 'the retention check stops like the cloud phase when the retry time of the run is used up: one error, the rows not checked stay Pending (never one error per row)' { + $context = New-GateContext $global:PraGate.Runtime -Mode Preview -Action Check + $context.Config.Cloud = @{ CheckMailbox = $true; CheckLicense = $false; MailboxCheckVia = 'Exo'; RequiredSkuPartNumber = ''; IdentityCheck = 'Off'; TenantId = '20000000-0000-0000-0000-000000000002'; RetryBudgetRunMinutes = 1; RetryBudgetObjectSeconds = 3600 } + $context.Config.Retention = @{ Enabled = $true; PolicyGuid = '40000000-0000-0000-0000-000000000004'; PolicyName = ''; UseComplianceSession = $false } + $context.LogFile = Join-Path $global:PraGate.Runtime.Root 'logs\retention-stop.log' + $global:PraGate.CloudContext = $context + $global:PraGate.CloudRows = @(1..4 | ForEach-Object { New-R9Row -Upn "user$_@gate.invalid" -Guid ('00000000-0000-0000-0000-00000000000' + $_) }) + InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { param($Context) $Context['_PraCloudSession'] = @{ Graph = $false; Exo = $true; Subprocess = $false; Binding = $global:PraGate.R9Binding } } + Mock Close-PraCloudSession { } + Mock Start-Sleep { } + Mock Get-EXOMailbox { $global:PraGate.R9Calls++; throw (New-R9Failure -Status 429 -RetryAfter 30) } + Invoke-PraRetentionCheck $global:PraGate.CloudContext $global:PraGate.CloudRows + } + $context.Issues.Count | Should -Be 1 + [string]$context.Issues[0].Message | Should -Match 'minute\(s\) allowed for retries are used up .* 4 object\(s\) were not checked\.$' + @($global:PraGate.CloudRows | Where-Object { $_.CloudStatus -ceq 'Error' }).Count | Should -Be 0 + @($global:PraGate.CloudRows | Where-Object { $_.CloudStatus -ceq 'Pending' }).Count | Should -Be 4 + $global:PraGate.R9Calls | Should -Be 3 -Because 'the first object tried three times, nothing else was asked' + } + It 'the X500 control does not swallow the stop of the run (it goes to the caller), and still reports its own failures as a result of the control' { + $global:PraGate.R9Row = [pscustomobject]@{ CloudDetail = '' } + $result = InModuleScope PRA.Cloud { + Mock Get-PraCloudAddress { throw 'SYNTHETIC: read failed' } + $state = @{ Row = $global:PraGate.R9Row; Upn = 'user1@gate.invalid'; ExoMailbox = $true; X500 = @('X500:/o=a'); X500Reads = 0; X500Failure = ''; X500Last = $null } + $first = Invoke-PraX500Step -Context $global:PraGate.CloudContext -State $state -Fresh $null -MaxReads 3 -Final $false + $kept = $state.X500Failure + (Get-PraRetryState $global:PraGate.CloudContext).RunExhausted = $true + $thrown = '' + try { $null = Invoke-PraX500Step -Context $global:PraGate.CloudContext -State $state -Fresh $null -MaxReads 3 -Final $false } catch { $thrown = $_.Exception.Message } + @{ First = $first; Kept = $kept; Thrown = $thrown } + } + $result.First | Should -BeFalse + $result.Kept | Should -BeExactly 'SYNTHETIC: read failed' + $result.Thrown | Should -BeExactly 'SYNTHETIC: read failed' + } +} + +Describe 'Release 3.2.0 - Recover from the journal when the State file is unreadable, a journal line that cannot be read, the trustee anchor marker (real main, production Directory module, synthetic AD)' -Tag 'Release320b' { + BeforeAll { + $global:PraGate.R4 = New-GateRuntime -Name 'partial-journal-320b' -Case 'FailAtSam' -UserCount 10 -Extra @{ FailSam = 'user3' } + $runtime = $global:PraGate.R4 + $env:PRA_GATE_STATE = $runtime.StatePath; $env:PSModulePath = $runtime.Modules + ';' + (Join-Path $PSHOME 'Modules') + Remove-Module PRA.Directory -Force -ErrorAction SilentlyContinue + Get-Module ActiveDirectory -All | Remove-Module -Force -ErrorAction Stop + Import-Module (Join-Path $runtime.Modules 'ActiveDirectory\ActiveDirectory.psm1') -Force -Global + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Directory.psm1') -Force -Global + $context = New-GateContext $runtime + $plans = @(foreach ($sam in 'user1', 'user10', 'user2', 'user3', 'user4', 'user5', 'user6', 'user7', 'user8', 'user9') { New-PraPlan $context $sam 'Convert' }) + try { $null = Invoke-PraAdBatch $context $plans 'Convert' } catch { $null = $_ } + $global:PraGateAd.Case = 'Normal' + [IO.File]::WriteAllText($runtime.StatePath, [Management.Automation.PSSerializer]::Serialize($global:PraGateAd, 35)) + $global:PraGate.R4Folder = Split-Path @(Get-ChildItem -LiteralPath $runtime.State.BackupFolder -Recurse -File -Filter 'Convert-*.json')[0].FullName -Parent + $global:PraGate.R4Id = ([IO.File]::ReadAllText(@(Get-ChildItem -LiteralPath $global:PraGate.R4Folder -File -Filter 'Convert-*.json')[0].FullName) | ConvertFrom-Json -DateKind String).BatchId + } + AfterAll { foreach ($key in 'R4', 'R4Folder', 'R4Id') { $global:PraGate.Remove($key) } } + It 'a State file that cannot be parsed is not a partial proof: Recover warns, falls back to the journal and takes only the objects it names (three verified, one stopped on)' { + $short = $global:PraGate.R4Id.Substring(0, 8) + $state = Join-Path $global:PraGate.R4Folder ('State-' + $global:PraGate.R4Id + '.json') + $original = [IO.File]::ReadAllBytes($state) + [IO.File]::WriteAllText($state, '{ this is not json', (New-Object Text.UTF8Encoding($true))) + try { + $run = Invoke-GateProcess $global:PraGate.R4 @{Action='Recover';Phase='AD';Mode='Preview';ConfigPath=$global:PraGate.R4.ConfigPath;Batch=$short} -TimeoutSeconds 120 + $run.ExitCode | Should -Be 0 -Because ($run.Output + $run.Error) + $run.Output | Should -Match ('The AD proof of batch ' + $short + ' is marked partial but cannot be used \(the State file cannot be read\)') + $run.MainResult.PlannedCount | Should -Be 4 + $run.MainResult.SkippedCount | Should -Be 6 + } + finally { [IO.File]::WriteAllBytes($state, $original) } + } + It 'a journal line that cannot be read is skipped with ONE warning and the others are still read' { + $short = $global:PraGate.R4Id.Substring(0, 8) + $state = Join-Path $global:PraGate.R4Folder ('State-' + $global:PraGate.R4Id + '.json') + $journal = Join-Path $global:PraGate.R4Folder ('Journal-' + $global:PraGate.R4Id + '.jsonl') + $originalJournal = [IO.File]::ReadAllBytes($journal) + Move-Item -LiteralPath ($state + '.sha256') -Destination ($state + '.sha256.away') + [IO.File]::AppendAllText($journal, "this line is not json`r`n" + '{"RunId":"r","Utc":"x","Target":"00000000-0000-0000-0000-00000000000' + "`r`n" + '{"RunId":"r","Operation":"Set-ADUser","Status":"Started","Target":"00000000-0000-0000-0000-000000000005","Detail":"t"' + "`r`n") + try { + $run = Invoke-GateProcess $global:PraGate.R4 @{Action='Recover';Phase='AD';Mode='Preview';ConfigPath=$global:PraGate.R4.ConfigPath;Batch=$short} -TimeoutSeconds 120 + $run.ExitCode | Should -Be 0 -Because ($run.Output + $run.Error) + $run.Output | Should -Match '[0-9]+ line\(s\) of the journal Journal-[0-9a-f]{32}\.jsonl cannot be read and were skipped' + $run.MainResult.WarningCount | Should -Be 2 -Because 'the unusable proof (no .sha256) and ONE warning for all the damaged lines' + $run.MainResult.PlannedCount | Should -Be 4 -Because 'the objects of the lines that can be read are still taken, the truncated line names nothing' + } + finally { [IO.File]::WriteAllBytes($journal, $originalJournal); Move-Item -LiteralPath ($state + '.sha256.away') -Destination ($state + '.sha256') } + } + It 'Get-PraJournalTouchedObject reads the lines around a damaged one and counts the skipped ones in a single warning, without a context it stays silent' { + $path = Join-Path $global:PraGate.R4.Root 'journal-damaged.jsonl' + [IO.File]::WriteAllText($path, ('{"Operation":"Set-ADUser","Status":"Started","Target":"AAAAAAAA-0000-0000-0000-000000000001"}' + "`r`n" + 'garbage' + "`r`n" + '{"Operation":"Set-ADUser","Status":"Applied","Target":' + "`r`n" + '{"Operation":"Add-ADGroupMember","Status":"Started","Target":"00000000-0000-0000-0000-000000000002"}' + "`r`n")) + $context = New-GateContext $global:PraGate.R4 -Mode Preview -Action Recover + $set = Get-PraJournalTouchedObject -Path $path -Context $context + @($set | Sort-Object) -join ',' | Should -BeExactly '00000000-0000-0000-0000-000000000002,AAAAAAAA-0000-0000-0000-000000000001' + $set.Contains('aaaaaaaa-0000-0000-0000-000000000001') | Should -BeTrue -Because 'the case of a GUID never matters' + $context.Warnings | Should -Be 1 + @(Get-PraList $context 'WarningList')[0].Message | Should -Match '^2 line\(s\) of the journal journal-damaged\.jsonl cannot be read and were skipped' + $silent = Get-PraJournalTouchedObject -Path $path + $silent.Count | Should -Be 2 + } + It 'the record marks incomplete trustee anchors when the schema cannot be read, and not when it can; the marker must be a boolean' { + $context = New-GateContext $global:PraGate.R4 -Mode Preview + $global:PraGate.R4Context = $context + $null = InModuleScope PRA.Directory { Test-PraConsistencyGuidSchema -Context $global:PraGate.R4Context } + (New-PraPlan $context 'user5' 'Convert').Record.SharedTrusteeAnchorsIncomplete | Should -BeTrue -Because 'the synthetic schema cannot be read' + $readable = New-GateContext $global:PraGate.R4 -Mode Preview + $global:PraGate.R4Context = $readable + $null = InModuleScope PRA.Directory { + Mock Get-ADRootDSE { [pscustomobject]@{ schemaNamingContext = 'CN=Schema,CN=Configuration,DC=gate,DC=invalid' } } + Mock Get-ADObject { @([pscustomobject]@{ DistinguishedName = 'CN=ms-DS-ConsistencyGuid,CN=Schema,CN=Configuration,DC=gate,DC=invalid' }) } + Test-PraConsistencyGuidSchema -Context $global:PraGate.R4Context + } + $plan = New-PraPlan $readable 'user6' 'Convert' + $plan.Record.SharedTrusteeAnchorsIncomplete | Should -BeFalse + $global:PraGate.R4Record = ($plan.Record | ConvertTo-Json -Depth 30) | ConvertFrom-PraJson + InModuleScope PRA.Directory { { Assert-PraStoredRecord $global:PraGate.R4Record } | Should -Not -Throw } + $global:PraGate.R4Record.SharedTrusteeAnchorsIncomplete = 'yes' + InModuleScope PRA.Directory { { Assert-PraStoredRecord $global:PraGate.R4Record } | Should -Throw '*invalid trustee anchor marker*' } + $global:PraGate.Remove('R4Context'); $global:PraGate.Remove('R4Record') + } +} + Describe 'Release 3.2.0 - the run says that Microsoft 365 limited its requests, with the command to run again (real main, synthetic)' -Tag 'Release320b' { It 'a Check whose retry time is used up: ONE error for the run, "limited the requests", nothing changed, the Check proposed again later' { $runtime = New-GateRuntime -Name 'check-throttled-320b' -Case 'CloudThrottled' diff --git a/tools/Measure-PraScale.ps1 b/tools/Measure-PraScale.ps1 new file mode 100644 index 0000000..80861b1 --- /dev/null +++ b/tools/Measure-PraScale.ps1 @@ -0,0 +1,287 @@ +<# +.SYNOPSIS + Times the batch-size sensitive steps of PRA Remote Mailbox on synthetic data (no directory, no tenant, no network). +.DESCRIPTION + Builds -Count synthetic users (contoso, gate.invalid) behind an in-memory Active Directory and times, with the production modules of -Package: + Plan one read-only plan per user (New-PraPlan) + BackupSave the backup of the whole batch: JSON, CLIXML, SHA-256, re-read, comparison with the plans (Save-PraBatch) + AdBatch the AD phase: backup, then for each object the guarded writes, the journal and the AD proof (Invoke-PraAdBatch) + ProofImport the AD proof read and checked against its backup (Import-PraProof) and the per-write checks of the cloud phase + Journal one line appended to the batch journal, and the journal readers of a partial batch + CloudPhase the cloud phase bookkeeping (Invoke-PraCloudPhase) with every Microsoft 365 call replaced by a local answer + Report the per-run CSV and HTML report + GlobalReport the phase data, the global model, the global HTML and CSV report + GuiState the state read of the console (Read-PraGuiState), cold and warm, on a backup folder of batches + Nothing is written outside -WorkFolder. The package is copied with the signature check substituted (tests\IntegrityFixture.ps1). +.PARAMETER Count + Number of synthetic objects (default 5000). +.PARAMETER Package + The package folder to measure (default: the package of this repository). Give an older package to time the same steps before a change. +.PARAMETER Step + The steps to run (default: all). +.PARAMETER WorkFolder + Folder for the copy of the package and the files written by the steps; default: a new folder under the temp folder, deleted at the end. +.PARAMETER OutputPath + Also writes the timings as JSON. +.EXAMPLE + pwsh -NoProfile -File .\tools\Measure-PraScale.ps1 -Count 5000 +.NOTES + Author : Nicolas Fabert + Version: 3.1.4 +#> +#Requires -Version 7.5 +[CmdletBinding()] +param( + [ValidateRange(10, 50000)][int]$Count = 5000, + [string]$Package = '', + [string[]]$Step = @('Plan', 'BackupSave', 'AdBatch', 'ProofImport', 'Journal', 'CloudPhase', 'Report', 'GlobalReport', 'GuiState'), + [string]$WorkFolder = '', + [string]$OutputPath = '' +) +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' +$all = @('Plan', 'BackupSave', 'AdBatch', 'ProofImport', 'Journal', 'CloudPhase', 'Report', 'GlobalReport', 'GuiState') +$Step = @($Step | ForEach-Object { $_ -split ',' } | Where-Object { $_ }) +foreach ($name in $Step) { if ($all -notcontains $name) { throw "Unknown step '$name'. Steps: $($all -join ', ')." } } +$repository = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..')) +if (-not $Package) { $Package = Join-Path $repository 'package' } +$Package = [IO.Path]::GetFullPath($Package) +$ownWork = -not $WorkFolder +if ($ownWork) { $WorkFolder = Join-Path ([IO.Path]::GetTempPath()) ('PraScale-' + [guid]::NewGuid().ToString('N').Substring(0, 8)) } +$null = New-Item -ItemType Directory -Path $WorkFolder -Force +. (Join-Path $repository 'tests\IntegrityFixture.ps1') +$fixture = Join-Path $WorkFolder 'package' +$changelog = Join-Path $repository 'CHANGELOG.md' +if (-not (Test-Path -LiteralPath $changelog)) { $changelog = Join-Path $WorkFolder 'CHANGELOG.md'; Set-Content -LiteralPath $changelog -Value '# synthetic' } +New-PraIntegrityFixture -SourcePackage $Package -Destination $fixture -Changelog $changelog +$env:PRA_GATE_NONET = 'SYNTHETIC-NO-NETWORK' +foreach ($name in 'PRA.Common', 'PRA.Backup', 'PRA.Directory') { Import-Module (Join-Path $fixture "module\$name.psm1") -Force -Global } +Import-Module (Join-Path $fixture 'module\PRA.Cloud.psm1') -Force -Global +$timings = New-Object 'Collections.Generic.List[object]' +function Measure-Step { + param([string]$Name, [string]$Detail, [scriptblock]$Script) + $clock = [Diagnostics.Stopwatch]::StartNew() + $value = & $Script 6>$null + $clock.Stop() + $row = [pscustomobject]@{ Step = $Name; Detail = $Detail; Seconds = [math]::Round($clock.Elapsed.TotalSeconds, 2) } + $timings.Add($row) + Write-Host ('{0,-14} {1,9:N2} s {2}' -f $Name, $clock.Elapsed.TotalSeconds, $Detail) + return $value +} + +# In-memory Active Directory: the cmdlets the Directory module calls, over a dictionary of synthetic users. +$global:PraScaleAd = @{ Users = New-Object 'Collections.Generic.List[object]'; ByKey = New-Object 'Collections.Generic.Dictionary[string,object]' ([StringComparer]::OrdinalIgnoreCase) + Members = New-Object 'Collections.Generic.List[string]'; Group = $null } +function global:Get-ADDomainController { [CmdletBinding()] param([switch]$Discover, [switch]$Writable, [string]$Identity, [string]$Server) [pscustomobject]@{ HostName = 'dc01.gate.invalid'; IsReadOnly = $false } } +function global:Get-ADUser { + [CmdletBinding()] + param([object]$Identity, [string]$LDAPFilter, [string[]]$Properties, [string]$Server, [string]$SearchBase) + $found = $null + if ($Identity -and $global:PraScaleAd.ByKey.TryGetValue([string]$Identity, [ref]$found)) { return $found } +} +function global:Get-ADGroup { + [CmdletBinding()] + param([object]$Identity, [string[]]$Properties, [string]$Server, [string]$LDAPFilter) + return $global:PraScaleAd.Group +} +function global:Set-ADUser { + [CmdletBinding(SupportsShouldProcess)] + param([object]$Identity, [hashtable]$Replace, [string[]]$Clear, [string]$Server) + $user = $global:PraScaleAd.ByKey[[string]$Identity] + if ($null -ne $Replace) { foreach ($key in $Replace.Keys) { $user.$key = $Replace[$key] } } + foreach ($key in $Clear) { $user.$key = $null } + $user.uSNChanged = [long]$user.uSNChanged + 1 +} +function global:Add-ADGroupMember { + [CmdletBinding(SupportsShouldProcess)] + param([object]$Identity, [object[]]$Members, [string]$Server) + foreach ($id in $Members) { $global:PraScaleAd.Members.Add([string]$global:PraScaleAd.ByKey[[string]$id].DistinguishedName) } + $global:PraScaleAd.Group.member = $global:PraScaleAd.Members.ToArray() +} + +function New-ScaleUser { + param([int]$Index) + $text = 'Synthetic value of the attribute for the user number {0}, long enough to look like a directory value.' -f $Index + $user = [ordered]@{ + ObjectGUID = [guid]('00000000-0000-0000-0000-{0:000000000000}' -f $Index) + DistinguishedName = "CN=User$Index,OU=Tests,DC=gate,DC=invalid"; SamAccountName = "user$Index" + UserPrincipalName = "user$Index@contoso.gate.invalid"; DisplayName = "Synthetic User $Index"; Name = "User$Index"; objectClass = 'user' + mail = "user$Index@contoso.gate.invalid"; mailNickname = "user$Index"; legacyExchangeDN = "/o=Synthetic/ou=Gate/cn=Recipients/cn=user$Index" + uSNChanged = [long](1000 + $Index); memberOf = @(); publicDelegates = @(); msExchArchiveGUID = $null + homeMDB = "CN=Database$($Index % 7),CN=Databases,DC=gate,DC=invalid"; homeMTA = 'CN=OriginalMTA,DC=gate,DC=invalid' + msExchHomeServerName = '/o=Synthetic/ou=Gate/cn=Servers/cn=Original'; msExchMailboxGuid = [byte[]](0, 1, 2, 127, 128, 254, 255, ($Index % 256), 1, 2, 3, 4, 5, 6, 7, 8) + mDBUseDefaults = $false; msExchRecipientDisplayType = 0; msExchRecipientTypeDetails = [long]1; msExchRemoteRecipientType = $null; targetAddress = $null + proxyAddresses = [string[]]@("SMTP:user$Index@contoso.gate.invalid", "smtp:alias$Index@contoso.gate.invalid", "smtp:other$Index@fabrikam.gate.invalid", 'X500:/o=Synthetic/ou=Gate/cn=User') + extensionAttribute1 = "OriginalTag-$Index" + nTSecurityDescriptor = [byte[]]::new(2400); msExchMailboxSecurityDescriptor = [byte[]]::new(1800) + } + for ($a = 1; $a -le 30; $a++) { $user["scaleAttribute$a"] = $text } + return [pscustomobject]$user +} + +function New-ScaleContext { + param([string]$Name, [string]$Action = 'Convert', [string]$Mode = 'Apply') + $root = Join-Path $WorkFolder $Name + foreach ($folder in 'backups', 'logs', 'reports') { $null = New-Item -ItemType Directory -Path (Join-Path $root $folder) -Force } + $config = @{ + Environment = 'SYNTHETIC_SCALE'; DomainController = '' + Scope = @{ Mode = 'Auto'; SearchBase = 'OU=Tests,DC=gate,DC=invalid'; GroupDN = ''; CsvPath = ''; IncludeShared = $false; IncludeRoom = $false; IncludeEquip = $false; ExcludeSamAccountNames = @() } + Routing = @{ AutoDetect = $false; RoutingDomain = 'contoso.mail.onmicrosoft.com' } + Licensing = @{ Enabled = $true; GroupDN = 'CN=License,OU=Tests,DC=gate,DC=invalid' } + SharedMailbox = @{ Enabled = $true; PermissionSource = 'None'; CaptureSendOnBehalf = $false; RemoteRecipientType = 97; ExcludeTrusteeSamAccountNames = @(); GrantFullAccess = $true; GrantSendAs = $true; GrantSendOnBehalf = $true } + EntraConnect = @{ Sync = $false; Server = ''; PolicyType = 'Delta'; TimeoutMinutes = 1 } + Retention = @{ Enabled = $true; Tag = @{ Enabled = $true; Attribute = 'extensionAttribute1'; Value = 'Converted' } } + Remote = @{ RecipientType = 1; HandleArchives = $true; ClearMailboxGuid = $true } + Cloud = @{ CheckMailbox = $true; CheckLicense = $false; MailboxCheckVia = 'Exo'; IdentityCheck = 'Off' } + Exo = @{ GrantVerifyAttempts = 3; GrantVerifyDelaySeconds = 1 } + Execution = @{ Phase = 'AD' }; Storage = @{ BackupFolder = (Join-Path $root 'backups'); ForbiddenBackupRoots = @() } + Logging = @{ Folder = (Join-Path $root 'logs') }; Report = @{ Enabled = $true; Folder = (Join-Path $root 'reports') } + } + @{ + Root = $fixture; RunId = '20261117_100000-' + [guid]::NewGuid().ToString('N').Substring(0, 8); Version = 'scale'; StartTime = Get-Date; Action = $Action; Mode = $Mode; Phase = 'AD' + CurrentPhase = 'Scale'; CurrentOperation = ''; CurrentIdentity = ''; StepIndex = 0; Warnings = 0; Config = $config + Issues = (New-Object 'Collections.Generic.List[object]'); Rows = (New-Object 'Collections.Generic.List[object]') + BackupFiles = (New-Object 'Collections.Generic.List[string]'); StateFiles = (New-Object 'Collections.Generic.List[string]') + BackupFolder = (Join-Path $root 'backups'); LogFolder = (Join-Path $root 'logs'); ReportFolder = (Join-Path $root 'reports') + LogFile = (Join-Path $root 'logs\run.log'); TranscriptPath = ''; TranscriptStarted = $false; NoReport = $false; Server = 'dc01.gate.invalid'; NamingContext = 'DC=gate,DC=invalid' + AllowMutation = ($Mode -eq 'Apply'); Approval = { param($Target, $Operation) $true } + SourceBackupHash = ''; Source = $null; Proof = $null; JournalPath = ''; ExitCode = 0; ResultStatus = ''; CloudConnectFailed = $false + TimeoutMinutes = 1; IntervalMinutes = 0; Once = $false + } +} + +Write-Host ('PRA scale measurement: {0} objects, package {1}' -f $Count, $Package) +for ($i = 1; $i -le $Count; $i++) { + $user = New-ScaleUser $i + $global:PraScaleAd.Users.Add($user) + foreach ($key in ([string]$user.ObjectGUID), $user.DistinguishedName, $user.SamAccountName) { $global:PraScaleAd.ByKey[$key] = $user } +} +$global:PraScaleAd.Group = [pscustomobject]@{ ObjectGUID = [guid]'10000000-0000-0000-0000-000000000001'; DistinguishedName = 'CN=License,OU=Tests,DC=gate,DC=invalid'; objectClass = 'group'; member = [string[]]@() } +$guids = @($global:PraScaleAd.Users | ForEach-Object { [string]$_.ObjectGUID }) +$context = New-ScaleContext 'plan' +$plans = $null +$runBackupSave = $Step -contains 'BackupSave' +$needPlans = $Step.Count -gt 0 +$plans = Measure-Step 'Plan' "$Count plans" { $list = New-Object 'Collections.Generic.List[object]'; foreach ($guid in $guids) { $list.Add((New-PraPlan $context $guid 'Convert')) }; , $list.ToArray() } +$plans = @($plans) + +$batchContext = $null; $receipt = $null +if ($Step -contains 'BackupSave') { + $saveContext = New-ScaleContext 'save' + $null = Measure-Step 'BackupSave' "$Count records" { & (Get-Module PRA.Directory) { param($c, $p) $null = Save-PraBatch $c $p 'Convert' } $saveContext $plans } +} +$batchContext = New-ScaleContext 'batch' +if ($Step -contains 'AdBatch' -or $Step -contains 'ProofImport') { + $receipt = Measure-Step 'AdBatch' "$Count objects: backup, guarded writes, journal, proof" { Invoke-PraAdBatch $batchContext $plans 'Convert' } + $batchContext.Source = $receipt; $batchContext.SourceBackupHash = $receipt.Hash + $batchFolder = Split-Path $receipt.Path -Parent; $backupHash = $receipt.Hash; $batchId = [string]$receipt.Data.BatchId +} +else { + # The steps that follow do not need the written backup: a batch folder with the JSON of the records, its proof and its journal is made without the CLIXML codec. + $batchId = [guid]::NewGuid().ToString('N'); $batchFolder = Join-Path $batchContext.BackupFolder ('Batch-' + $batchId) + $null = New-Item -ItemType Directory -Path $batchFolder -Force + $utf8 = New-Object Text.UTF8Encoding($false) + $backup = [ordered]@{ SchemaVersion = 3; Operation = 'Convert'; Environment = 'SYNTHETIC_SCALE'; BatchId = $batchId; Records = @($plans | ForEach-Object { $_.Record }) } + $backupPath = Join-Path $batchFolder ('Convert-SYNTHETIC_SCALE-20261117_100000-' + $batchId.Substring(0, 8) + '.json') + [IO.File]::WriteAllText($backupPath, ($backup | ConvertTo-Json -Depth 30), $utf8) + $backupHash = Get-PraHash $backupPath + [IO.File]::WriteAllText($backupPath + '.sha256', $backupHash, $utf8) + $proof = [ordered]@{ SchemaVersion = 2; Operation = 'Convert'; Kind = 'ADVerified'; Environment = 'SYNTHETIC_SCALE'; BackupHash = $backupHash; CreatedUtc = '2026-11-17T10:00:00.0000000Z' + Records = @($plans | ForEach-Object { [ordered]@{ ObjectGuid = $_.Record.ObjectGuid; Operation = 'Convert'; ADVerified = $true } }) } + $statePath = Join-Path $batchFolder ('State-' + $batchId + '.json') + [IO.File]::WriteAllText($statePath, ($proof | ConvertTo-Json -Depth 5), $utf8) + [IO.File]::WriteAllText($statePath + '.sha256', (Get-PraHash $statePath), $utf8) + [IO.File]::WriteAllText((Join-Path $batchFolder ('Journal-' + $batchId + '.jsonl')), '', $utf8) + foreach ($plan in $plans) { $plan.Row.FinalStatus = 'Success'; $plan.Row.ADApplied = $true; $plan.Row.ADVerified = $true; $plan.Row.BackupPath = $backupPath; $batchContext.Rows.Add($plan.Row) } + $batchContext.BatchId = $batchId.Substring(0, 8) +} +if ($Step -contains 'ProofImport' -and $null -ne $receipt) { + $proofContext = New-ScaleContext 'proof' + $cheap = [bool](& (Get-Module PRA.Directory) { [bool](Get-Command Assert-PraCloudProofObject -ErrorAction SilentlyContinue) }) + $checked = if ($cheap) { $Count } else { [Math]::Min($Count, 20) } + $null = Measure-Step 'ProofImport' "import of the proof, then $checked per-object checks of the cloud phase" { + $source = Import-PraBackup $proofContext $receipt.Path + $proofContext.Source = $source + $proof = Import-PraProof $proofContext $receipt.StatePath $source 'Convert' + $proofContext.Proof = $proof + $proofPath = $receipt.StatePath + foreach ($guid in ($guids | Select-Object -First $checked)) { + if ($cheap) { + & (Get-Module PRA.Directory) { param($c, $p, $s, $g) Assert-PraCloudProofObject -Context $c -ProofPath $p -Source $s -Operation 'Convert' -ObjectGuid $g } $proofContext $proofPath $source $guid + Assert-PraReceipt $proofContext $source $guid + } + else { + $again = Import-PraProof $proofContext $proofPath $source 'Convert' + if (@($again.Data.Records | Where-Object { Test-PraOrdinalIgnoreCaseEqual $_.ObjectGuid $guid }).Count -ne 1) { throw 'not in the proof' } + Assert-PraReceipt $proofContext $source $guid + } + } + } +} +if ($Step -contains 'Journal') { + $journalContext = New-ScaleContext 'journal' + $journalContext.JournalPath = Join-Path $batchFolder ('Journal-' + $batchId + '.jsonl') + $null = Measure-Step 'Journal' "$Count Started lines, then the readers of the partial batch" { + foreach ($guid in $guids) { Write-PraJournal $journalContext $guid 'Set-ADUser' 'Started' } + $touched = Get-PraJournalTouchedObject -Path $journalContext.JournalPath + $null = Find-PraRecoverOfBatch -Context $batchContext -SourceHash $backupHash -ObjectGuid $guids + } +} +if ($Step -contains 'CloudPhase') { + $cloudContext = New-ScaleContext 'cloud' 'Convert' 'Apply' + $cloudContext.Phase = 'Cloud' + $cloudRows = @($plans | ForEach-Object { $_.Row }) + foreach ($row in $cloudRows) { $row.FinalStatus = 'Pending'; $row.ADVerified = $true } + $notReady = New-Object 'Collections.Generic.HashSet[string]' + foreach ($row in ($cloudRows | Select-Object -First ([int]($Count / 5)))) { [void]$notReady.Add([string]$row.UserPrincipalName) } + $global:PraScaleNotReady = $notReady; $global:PraScalePolls = 0 + & (Get-Module PRA.Cloud) { + function script:Connect-PraCloudSession { param($Context, $NeedGraph, $NeedExo) } + function script:Close-PraCloudSession { param($Context) } + function script:Confirm-PraCloudIdentity { param($Context, $State, [switch]$Throw) 'Ok' } + function script:Invoke-PraExo { param($Context, $Operation, $Params, $Permit, $OnApplied, $OnProgress) + if ($Operation -eq 'Mailbox') { return @{ Found = ($global:PraScaleNotReady.Count -eq 0 -or $global:PraScalePolls -gt 0 -or -not $global:PraScaleNotReady.Contains([string]$Params.Upn)); Type = 'UserMailbox'; HasAddresses = $true; Addresses = [string[]]@() } } + return @{} } + function script:Invoke-PraSharedPermission { param($Context, $Row, $Requests) 0 } + } + $null = Measure-Step 'CloudPhase' "$Count rows, 2 checks, Microsoft 365 answered locally" { + Invoke-PraCloudPhase -Context $cloudContext -Rows $cloudRows -Act Convert + } +} +if ($Step -contains 'Report') { + $null = Measure-Step 'Report' "CSV and HTML of $Count rows" { + $reports = @{ Csv = (Join-Path $batchContext.ReportFolder 'scale.csv'); Html = (Join-Path $batchContext.ReportFolder 'scale.html'); CsvFailed = $false; HtmlFailed = $false } + $null = New-Item -ItemType File -Path $reports.Csv, $reports.Html -Force + & (Get-Module PRA.Common) { param($c, $r) Write-PraReport $c $r } $batchContext $reports + } +} +if ($Step -contains 'GlobalReport') { + $batchContext.PhaseFolders = @($batchFolder) + $null = Measure-Step 'GlobalReport' "phase data, model, HTML and CSV of $Count objects" { + $null = Save-PraPhaseData -Context $batchContext -Folder $batchFolder + $null = Write-PraGlobalReport -Context $batchContext + } +} +if ($Step -contains 'GuiState') { + Import-Module (Join-Path $fixture 'module\PRA.Gui.psm1') -Force -Global + $guiRoot = Join-Path $WorkFolder 'gui' + $null = New-Item -ItemType Directory -Path $guiRoot -Force + $guiConfig = Join-Path $guiRoot 'gui.config.psd1' + $backups = Join-Path $guiRoot 'backups' + Set-Content -LiteralPath $guiConfig -Value ("@{ Environment = 'SYNTHETIC_SCALE'; Scope = @{ Mode = 'Auto' }; Licensing = @{ Enabled = `$false }; EntraConnect = @{ Sync = `$false }; Execution = @{ Phase = 'AD' }; Storage = @{ BackupFolder = '" + $backups.Replace("'", "''") + "' } }") + $source = $batchFolder + for ($b = 1; $b -le 5; $b++) { + $copy = Join-Path $backups ('Batch-' + $b.ToString('x32')) + $null = New-Item -ItemType Directory -Path $copy -Force + Copy-Item -Path (Join-Path $source '*.json'), (Join-Path $source '*.sha256') -Destination $copy + } + foreach ($label in '5 batches, first read', '5 batches, second read (nothing changed)') { + $state = Measure-Step 'GuiState' $label { Read-PraGuiState $fixture $guiConfig } + if ($state.ConfigError -or $state.BatchError -or @($state.Batches | Where-Object Valid).Count -ne 5) { throw ('The console state is not the expected one: ' + $state.ConfigError + $state.BatchError) } + } +} + +$result = [pscustomobject]@{ Count = $Count; Package = $Package; PowerShell = [string]$PSVersionTable.PSVersion; Timings = $timings.ToArray() } +if ($OutputPath) { [IO.File]::WriteAllText($OutputPath, ($result | ConvertTo-Json -Depth 5), (New-Object Text.UTF8Encoding($false))) } +if ($ownWork) { Remove-Item -LiteralPath $WorkFolder -Recurse -Force -ErrorAction SilentlyContinue } +$result From c1f02c46b00b13892d35436b61c427cef491787e Mon Sep 17 00:00:00 2001 From: Nicolas Fabert <195452170+Nico77600@users.noreply.github.com> Date: Wed, 18 Nov 2026 07:59:14 +0100 Subject: [PATCH 04/16] Faster backup codec and AD batch, licence group read by memberOf, grants by confirmed id, unfinished rows kept, damaged journal handling, console cache reload --- package/Invoke-PraRemoteMailbox.ps1 | 54 +- package/docs/PraRemoteMailbox-Guide.md | 15 +- package/module/PRA.Backup.psm1 | 139 +++-- package/module/PRA.Cloud.psm1 | 232 ++++++-- package/module/PRA.Common.psm1 | 48 +- package/module/PRA.Directory.psm1 | 180 ++++-- package/module/PRA.Gui.psm1 | 14 +- tests/PraLegacyFixtures.Tests.ps1 | 2 +- tests/PraRemoteMailbox.Gui.Tests.ps1 | 48 ++ tests/PraRemoteMailbox.Tests.ps1 | 783 ++++++++++++++++++++++++- tools/Measure-PraScale.ps1 | 10 +- 11 files changed, 1336 insertions(+), 189 deletions(-) diff --git a/package/Invoke-PraRemoteMailbox.ps1 b/package/Invoke-PraRemoteMailbox.ps1 index 2c12f59..75c8771 100644 --- a/package/Invoke-PraRemoteMailbox.ps1 +++ b/package/Invoke-PraRemoteMailbox.ps1 @@ -419,6 +419,31 @@ function Get-PraFallbackNext { return @('Fix the problem named above, then run the same command again:', $same) } +function Get-PraJsonOperation { + <# + .SYNOPSIS + The Operation field of a batch JSON file, read without parsing the whole file. + .DESCRIPTION + A backup of thousands of objects is tens of megabytes; its Operation field is one of the first properties of the envelope. + The head of the file is read and the field is taken from it when only scalar properties come before it (a nested property of + the same name cannot be taken). Any other shape, or a file that cannot be read this way, is parsed in full as before. + #> + param([Parameter(Mandatory)][string]$Path) + $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 = '' } + $scalar = '(?:"(?:[^"\\]|\\[^u]|\\u[0-9a-fA-F]{4})*"|-?[0-9]+(?:\.[0-9]+)?(?:[eE][-+]?[0-9]+)?|true|false|null)' + $match = [regex]::Match($head, '\A\s*\{(?:\s*"(?:[^"\\]|\\[^u]|\\u[0-9a-fA-F]{4})*"\s*:\s*' + $scalar + '\s*,)*\s*"Operation"\s*:\s*"([^"\\]*)"\s*[,}]') + if ($match.Success) { return $match.Groups[1].Value } + return [string](([IO.File]::ReadAllText($Path) | ConvertFrom-PraJson).Operation) +} + function Get-PraBatchFile { <# .SYNOPSIS @@ -460,7 +485,7 @@ 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 $_.Name.StartsWith('State-', [StringComparison]::OrdinalIgnoreCase) })) { - try { $operation = [string](([IO.File]::ReadAllText($file.FullName) | ConvertFrom-PraJson).Operation) } catch { continue } + try { $operation = Get-PraJsonOperation $file.FullName } catch { 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) } } @@ -808,6 +833,7 @@ function Assert-PraBatchNotRolledBack { $check = (Get-PraCommandLine -ActionName 'Check' -ModeName 'Preview' -BatchId $recover.ShortId) -replace '^(\.\\Invoke-PraRemoteMailbox\.ps1 -Action Check -Batch [0-9a-fA-F]+)', '$1 -Expect Deprovisioned' $what = if (Test-PraOrdinalEqual $recover.Basis 'State') { 'already rolled back objects of it' } elseif (Test-PraOrdinalEqual $recover.Basis 'Journal') { 'started to roll back objects of it (it stopped before its proof)' } + elseif (Test-PraOrdinalEqual $recover.Basis 'Damaged') { 'was started on it and its journal has lines that cannot be read: every object counts as rolled back' } else { 'was started on it and its journal is not here: every object counts as rolled back' } $steps = @(('Batch {0} was rolled back by Recover batch {1}: its objects are not converted any more. To check what the rollback left, run:' -f $short, $recover.ShortId), $check) if (-not (Test-PraOrdinalEqual $recover.Basis 'State')) { @@ -822,7 +848,10 @@ function Assert-PraBatchNotRolledBack { function Get-PraBatchTouchedSet { <# The objects that the journal of the Convert batch in $context.Source shows as written or about to be written. #> $journal = Join-Path (Split-Path $context.Source.Path -Parent) ('Journal-' + [string]$context.Source.Data.BatchId + '.jsonl') - return , (Get-PraJournalTouchedObject -Path $journal -Context $context) + $skipped = 0 + $set = Get-PraJournalTouchedObject -Path $journal -Context $context -SkippedCount ([ref]$skipped) + $script:TouchedSkipped = $skipped + return , $set } function Get-PraPartialSourceProof { @@ -1024,6 +1053,7 @@ $script:NotConverted = New-Object 'Collections.Generic.HashSet[string]' ([String $script:PartialContinuation = $null # The objects that the journal of a partial batch shows as written or about to be written, those among them that the batch did not verify, and whether the proof of the source is partial. $script:Touched = New-Object 'Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase) +$script:TouchedSkipped = 0 $script:MayBeChanged = New-Object 'Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase) $script:SourcePartial = $false # Known from the start; the run sets it from the configuration. @@ -1355,13 +1385,16 @@ try { $backupFolder = Split-Path $context.Source.Path -Parent $short = Get-PraShortId ([string]$context.Source.Data.BatchId) Write-PraItem -Context $context -Status Warn -Text ('The AD proof of batch {0} is marked partial but cannot be used ({1}): the journal of the batch decides which objects are rolled back.' -f $short, $sourceProof.Reason) - if (-not $Identity -and -not $script:Touched.Count) { + if (-not $Identity -and ($script:TouchedSkipped -gt 0 -or -not $script:Touched.Count)) { $first = $records | Select-Object -First 1 + $journalDamaged = ($script:TouchedSkipped -gt 0) $context.NextSteps = @(('The backup of batch {0} is {1}: it holds the original values of every object of the batch.' -f $short, $context.Source.Path), 'If you know that an object was converted by this batch, roll it back on its own (run the Preview, then the same command with -Mode Apply):', ((Get-PraCommandLine -ActionName 'Recover' -ModeName 'Preview' -BatchId $short) + ' -Identity ' + (ConvertTo-PraLiteral ([string](Get-PraValue $first 'SamAccountName' 'user')))), 'Otherwise restore the attributes of the objects from that backup file by hand (the backups are the only way back), or copy the original State file and its .sha256 file back into the batch folder and run the same Recover again.') + if ($journalDamaged) { $context.NextSteps = @(('The journal of batch {0} has {1} line(s) that cannot be read: it may not name every object that the batch changed, so the rollback is not guessed.' -f $short, $script:TouchedSkipped)) + @($context.NextSteps) } $context.NextOnFailure = $true; $context.NoChangeMade = $true; $context.CurrentIdentity = '' + if ($journalDamaged) { throw ('Recover of batch {0} cannot go on: its AD proof is partial but unusable ({1}) and {2} line(s) of its journal cannot be read, so the objects that the batch wrote cannot be told for certain. Nothing was changed.' -f $short, $sourceProof.Reason, $script:TouchedSkipped) } throw ('Recover of batch {0} cannot go on: its AD proof is partial but unusable ({1}) and its journal lists no object that was written. Nothing was changed.' -f $short, $sourceProof.Reason) } if ($Identity) { foreach ($record in $records) { [void]$script:Touched.Add([string]$record.ObjectGuid) } } @@ -1565,6 +1598,19 @@ try { Import-Module (Join-Path $PSScriptRoot 'module\PRA.Cloud.psm1') -Force -ErrorAction Stop if ((Test-PraOrdinalIgnoreCaseEqual $Action 'Check') -and (Test-PraOrdinalIgnoreCaseEqual $Expect 'Retained')) { Invoke-PraRetentionCheck -Context $context -Rows $cloudRows } else { Invoke-PraCloudPhase -Context $context -Rows $cloudRows -Act $cloudAction } + # Each grant checked the backup cheaply; a cloud-only run that sent at least one ends with one complete check, so that it never ends without it. + if ($context.AllowMutation -and (Test-PraOrdinalIgnoreCaseEqual $effectivePhase 'Cloud') -and (Test-PraOrdinalIgnoreCaseEqual $Action 'Convert') -and [int](Get-PraValue $context 'GrantsSent' 0) -gt 0) { + try { + Assert-PraReceipt -Context $context -Receipt $context.Source -Full + Write-PraItem -Context $context -Status Ok -Icon Backup -Text ('Backup of the batch checked in full after {0} permission grant(s)' -f [int]$context.GrantsSent) + } + catch { + $context.NextSteps = @('The backup of this batch changed while the shared mailbox permissions were granted. Check the Backups folder of this server (nobody should write there during a run), then run the same command again, it reads the permissions first and grants only what is missing:', + (Get-PraCommandLine -ActionName $Action -PhaseName 'Cloud' -BatchId $(if ($script:PackageArgument) { $script:PackageArgument } elseif ($Batch) { $Batch } else { $context.BatchId }) -KeepFilters)) + $context.NextOnFailure = $true + throw ('The final check of the backup failed after {0} grant(s): {1}' -f [int]$context.GrantsSent, $_.Exception.Message) + } + } $cloudErrors = @($context.Rows | Where-Object { Test-PraOrdinalEqual $_.CloudStatus 'Error' }) $runErrors = @($cloudErrors | Where-Object { [bool](Get-PraValue $_ 'RunError' $false) }).Count $notExpected = $cloudErrors.Count - $runErrors @@ -1792,7 +1838,7 @@ finally { catch { Write-PraLog -Context $context -Message ('The data for the global report could not be saved ({0}).' -f $_.Exception.Message) -Level Detail } } if (Get-Command Close-PraCloudSession -ErrorAction SilentlyContinue) { - try { Close-PraCloudSession -Context $context } catch { $context.Issues.Add([pscustomobject]@{ Message = "Cloud sign-out: $($_.Exception.Message)"; Source = 'Cloud' }) } + try { Close-PraCloudSession -Context $context } catch { Write-PraItem -Context $context -Status Warn -Text ('The sign-out of Microsoft 365 failed ({0}). What this run did is not affected. If a session is still open, close it: Disconnect-ExchangeOnline -Confirm:$false; Disconnect-MgGraph' -f ([string]$_.Exception.Message -replace '\s+', ' ')) } } # What a failed run proposes when no step set a more specific next step. try { $context.FallbackNext = @(Get-PraFallbackNext) } diff --git a/package/docs/PraRemoteMailbox-Guide.md b/package/docs/PraRemoteMailbox-Guide.md index 6b6ca4d..137314d 100644 --- a/package/docs/PraRemoteMailbox-Guide.md +++ b/package/docs/PraRemoteMailbox-Guide.md @@ -230,7 +230,9 @@ check | Done | on-premises again > > A **different account**, a **cloud-only** account, **two accounts**, or an account synchronised under **another UPN** is an **error for that object**: nothing is read in Exchange Online for it and nothing is changed on it. The message says which case it is and what to do (give one of the two accounts another UPN, or remove the duplicate, then run the same command again). The Exchange Online object found by UPN must then carry the `ExternalDirectoryObjectId` of the confirmed account, in every read (recipient, mailbox, permissions, retention check); another object stops the call. For a shared mailbox the same check is made for **each trustee** of a permission to grant (the batch records their anchors, `SharedTrusteeAnchors`; a trustee without recorded anchors must at least be a synchronised account, not a cloud-only one), so that a permission is never granted to another person. An object that is not in Microsoft Entra ID yet is waited for like any object that is not ready. > -> **Older batches and the records without an anchor.** A batch, backup or transfer package written before 3.2.0 has no `SourceAnchor`: the anchor is derived from the `ObjectGuid` of the record (the usual source anchor), and an error then says that the record is old. A tenant whose source anchor is neither the `objectGUID` nor `ms-DS-ConsistencyGuid` (or whose `ms-DS-ConsistencyGuid` differs from the `objectGUID` in a batch of an older version) can set `Cloud.IdentityCheck = 'Off'` after checking the accounts by hand: accounts are then found by UPN only, and the run says so once. A `Check -Identity ` has no AD record at all: the account is found by UPN with a warning, and no permission is ever granted for such a record. The retention check reads an **inactive** mailbox (its account is deleted) by UPN only. +> **Older batches and the records without an anchor.** A batch, backup or transfer package written before 3.2.0 has no `SourceAnchor`: the anchor is derived from the `ObjectGuid` of the record (the usual source anchor), and an error then says that the record is old. A tenant whose source anchor is neither the `objectGUID` nor `ms-DS-ConsistencyGuid` (or whose `ms-DS-ConsistencyGuid` differs from the `objectGUID` in a batch of an older version) can set `Cloud.IdentityCheck = 'Off'` after checking the accounts by hand: accounts are then found by UPN only, and the run says so once. A `Check -Identity ` has no AD record at all: the account is found by UPN with a warning, and no permission is ever granted for such a record. The retention check reads an **inactive** mailbox (its account is deleted) by UPN only, and says so with a warning. When the account of the object **is** confirmed, an inactive mailbox with the same UPN that carries another `ExternalDirectoryObjectId` belongs to an earlier account: the check says *not this object's mailbox*, the object is not covered, and that mailbox never decides the verdict. Without a confirmed account, two inactive mailboxes for the same UPN stop the check (nothing tells which one is the object's): the message gives the `Get-EXOMailbox -InactiveMailboxOnly` command that lists them. +> +> **Permissions are written with the confirmed id.** The Exchange Online object of a confirmed account is read with the `-ExternalDirectoryObjectId` parameter (recipient, mailbox, permissions), and a permission is written (`Add-MailboxPermission`, `Add-RecipientPermission`, `Set-Mailbox`) with the confirmed id of the mailbox and of the trustee in `-Identity`, `-User` and `-Trustee`. The UPN is used only for an object that has no confirmed account (`Cloud.IdentityCheck = 'Off'`). A grant that the run already sent (mailbox, right, trustee) is never sent again in the same run, even if a later read does not show it yet. > [!NOTE] > **Throttling and temporary failures do not end an object.** A read of Microsoft Graph or Exchange Online that fails with HTTP 408, 429, 502, 503, 504, a timeout or no answer at all is sent again (at most five tries, after the `Retry-After` of the answer, or 5, 10, 20, 40 seconds), within `Cloud.RetryBudgetObjectSeconds` for one object and `Cloud.RetryBudgetRunMinutes` for the whole run; every retry is in the log (Detail level). A throttled answer (429, 503) also **slows every following call of the run** (a pause that doubles up to 30 seconds and halves after each success), so that a batch of thousands of objects does not turn into thousands of refused calls. An object whose own budget is used up stays pending and is read again at the next check of the wait; only at the end of the wait is it an error ("Microsoft 365 could not be read"). When the budget of the **run** is used up, the cloud part stops with **one** error (not one per object), the objects not finished stay *Pending*, and the Next steps give the command to run again a few minutes later. Any other failure (a 4xx other than 408 and 429, a refusal, a bad answer) is **not** sent again. A grant is never sent again: the next run finds the permission already granted or grants it. @@ -981,11 +983,11 @@ the package replaces the copy of the folders, not the verifications. A batch of **5,000 objects** is supported. The checks that grew with the square of the batch (the backup fingerprint recomputed for every write, the searches of the whole batch for each object, the console reading every batch file at every refresh) are gone: what is done for one object costs the same in a batch of 50 and in a batch of 5,000. -- The backup is written and read back in full once, with the SHA-256 of its files. Writing and reading the data-only CLIXML is the work that remains and it is linear: about 0.5 s per object measured on a loaded workstation with synthetic users of 45 attributes (an object of your directory with more attributes costs more). Plan on roughly 45 minutes for the backup of 5,000 objects, and the same again each time a server reads the batch for the first time (the cloud server, Finalize). +- The backup is written once and read back once in full (the same pass validates the file and compares it with what was captured), with the SHA-256 of its files. Writing and reading the data-only CLIXML is the work that remains and it is linear: about 0.2 s per object for the whole backup, measured on a loaded workstation with synthetic users of 45 attributes (an object of your directory with more attributes costs more). Plan on roughly 18 minutes for the backup of 5,000 objects, and about 8 minutes each time a server reads the batch for the first time (the cloud server, Finalize). - Each write checks the fields of the backup, the record of the object and the length and last write time of the files; the complete check runs when the backup is read, after every 200 such checks and before the AD proof is written. The AD proof is read in full once per run by the cloud phase; each permission grant then costs a comparison of stamps. -- The Active Directory part, the Entra Connect wait and the Exchange Online wait are not made faster by this: the AD part reads and re-reads each object several times, and the licence group is read in full for each object. -- The console keeps what it read of each batch file while the file and its `.sha256` file are unchanged, so a refresh costs a listing of the folder. A reload after a new batch reads that batch only. -- The bounds that remain: a transfer package is refused above 2 GB for one entry and 4 GB in all (with the message *too large*); a phase keeps at most 40 steps per object, 1,000,000 journey lines, 10,000 errors and 10,000 warnings; the global report page shows the journey of every object up to 10,000 objects (the CSV lists all objects). +- The Active Directory part, the Entra Connect wait and the Exchange Online wait are not made faster by this: the AD part reads and re-reads each object several times (each write is preceded and followed by a read of the object), and the Entra Connect and Exchange Online waits are those of the services. The licence group is not read in full for each object: whether an object is a member comes from its own memberOf attribute, and a group of thousands of members is read once for the objects of a run. On the synthetic data, planning takes about 0.05 s per object, the AD part about 0.2 s per object after the backup (about 18 minutes for 5,000 objects), and reading the AD proof and the per-object checks of the cloud phase about 14 minutes for 5,000 objects. +- The console keeps what it read of each batch file while the file and its `.sha256` file are unchanged, so a refresh costs a listing of the folder. A reload after a new batch reads that batch only. A failure to read a file (a lock) is never kept, and the **Reload** link forgets everything the window kept about batch files and CSV files. +- The bounds that remain: a transfer package is refused above 2 GB for one entry and 4 GB in all (with the message *too large*); a phase keeps at most 40 steps per object, 1,000,000 journey lines, 10,000 errors and 10,000 warnings; the global report page shows the journey of every object up to 10,000 objects (the CSV lists all objects); one PhaseData file is at most 64 MB (the writer drops the steps of a larger one) and the PhaseData files read for one report at most 256 MB together (a file that would pass it is not read: the report says so and tells to move the files of other batches out of the batch folder). A cloud-only run that sent permission grants ends with one complete check of the backup. - `tools\Measure-PraScale.ps1` times these steps on synthetic data (no directory, no tenant, no network): `pwsh -File .\tools\Measure-PraScale.ps1 -Count 5000`. Run the heavy steps (`BackupSave`, `AdBatch`, `ProofImport`) with a smaller `-Count` first: they take hours at 5,000. # Part IV · Maintain @@ -1152,6 +1154,8 @@ After a change of the engine, repeat the campaign of [annex B](#annex-b--lab-tes | `: the Microsoft Entra ID account with this UPN is not the account synchronised from this Active Directory object (it is a cloud-only account / it is synchronised from another Active Directory object)` | the UPN of the AD object belongs to another account in the cloud: Entra ID gave the synchronised object another UPN, or a cloud-only account had the UPN first | nothing was changed on it, and nothing was read in Exchange Online. Give one of the two accounts another UPN so that Entra Connect synchronises the object under its own UPN, or leave the object out, then run the same command again. A record written by an older version says so: if the tenant uses another source anchor, check the account by hand and set `Cloud.IdentityCheck = 'Off'` | | `: the Microsoft Entra ID account with this UPN is synchronised, but its onPremisesImmutableId ...` | the account is synchronised but carries another anchor than the `objectGUID` or `ms-DS-ConsistencyGuid` of the record, or one that is not the base64 of a GUID: the tenant may use another source anchor (a mail or employee attribute, for example) | nothing was changed. Check by hand that the account is the one of the object, then set `Cloud.IdentityCheck = 'Off'` and run the same command again. Changing UPNs is not the answer here | | `: Microsoft Graph refused to read the Microsoft Entra ID account that confirms this object (HTTP 403)` | the identity check needs `User.Read.All` and the sign-in does not have it | give `User.Read.All` (delegated: the administrator consents; application: add it and grant admin consent), or set `Cloud.IdentityCheck = 'Off'`; run the same command again. Nothing was changed | +| `: Microsoft Graph did not accept the sign-in (HTTP 401): the sign-in expired or was refused` | the Graph sign-in expired during a long run, or the certificate or application was refused | sign in again: run the same command again (a refusal of Graph, 401 or 403, stops the run once: ONE error, the objects not reached stay *Pending*, nothing is asked of Graph again) | +| `The sign-out of Microsoft 365 failed (...)` (warning) | a session could not be closed at the end of the run | what the run did is not affected, no object is an error; close a session that is still open with `Disconnect-ExchangeOnline -Confirm:$false; Disconnect-MgGraph` | | `: a shared mailbox permission could not be granted or verified (...)` | the grant step failed (for example a throttled answer after the Add): it is never repeated in the same run | run the cloud phase again later: it reads the permissions first and grants only what is missing | | `: the account synchronised from this Active Directory object is in Microsoft Entra ID, not ` | the account of the object has another UPN in the cloud | make the UPN in AD and in Entra ID the same, let Entra Connect synchronise, run the same command again | | `: Microsoft Entra ID returned 2 accounts for this UPN` / `... has 2 accounts that carry the source anchor of this Active Directory object` | duplicate accounts in Entra ID | remove the duplicate account, run the same command again | @@ -1162,6 +1166,7 @@ After a change of the engine, repeat the campaign of [annex B](#annex-b--lab-tes | `: Microsoft 365 kept limiting the requests or was unavailable (HTTP 429) and the retry time of this object is used up` | an object used up `Cloud.RetryBudgetObjectSeconds` until the end of the wait | run the same command again in a few minutes | | `The AD proof of batch is marked partial but cannot be used (...): the journal of the batch decides which objects are rolled back` (warning) | the State file of a partial Convert batch has no `.sha256`, was changed, or is damaged | Recover rolls back the objects that the journal shows as written (a Started or Applied line), and leaves the others alone. Put the original State file and its `.sha256` back to use the proof again | | `Recover of batch cannot go on: its AD proof is partial but unusable (...) and its journal lists no object that was written` | the same, and the journal of the batch is missing or empty | nothing was changed. The Next steps give the backup file, the Recover of one named object (`-Identity`), and the manual restore: the attributes of the objects are restored by hand from that backup file | +| `Recover of batch cannot go on: its AD proof is partial but unusable (...) and line(s) of its journal cannot be read` | the same, and the journal has a line that is damaged (not JSON, cut short, or without its Operation, Status and Target): it may hide a write, so the tool does not guess | nothing was changed. Name the objects yourself (`-Identity`, Preview first), or restore them by hand from the backup file. A Convert batch whose Recover journal has such a line is refused too (`cannot be resumed`: every object counts as rolled back) | | ` line(s) of the file name no object of batch (...): they are kept in the new file, check them` (warning) | the CSV of the objects left keeps every line that it cannot match to an object of the batch (for example an identity written as `DOMAIN\account`); a GUID matches in any form (braces, no dashes, any case) | check those lines; the lines of converted objects are left out and counted in an information line | | `An Exchange Online session already exists in this console` | the console was used for EXO before | open a new PowerShell 7 window | | `Microsoft Graph: found Microsoft.Graph.Authentication 2.40.0; Microsoft.Graph.Users 2.35.1. The tool needs both in one same version 2.41.1 or later` | the Graph modules installed are too old, or not in one same version (two versions of Graph in one session fail with *Assembly with same name is already loaded*) | run the commands of the message, one per module and both for the same version (`Install-Module Microsoft.Graph.Authentication -MinimumVersion 2.41.1 -Scope CurrentUser`, then `Install-Module Microsoft.Graph.Users -MinimumVersion 2.41.1 -Scope CurrentUser`; `-Scope AllUsers` needs a window opened as administrator). `Install-Module` refuses `-MinimumVersion` with several names. Nothing was changed. The tool imports both modules in that same version. The same text is on the Microsoft.Graph light of the Setup page | diff --git a/package/module/PRA.Backup.psm1 b/package/module/PRA.Backup.psm1 index a639cd5..2528788 100644 --- a/package/module/PRA.Backup.psm1 +++ b/package/module/PRA.Backup.psm1 @@ -55,6 +55,10 @@ $script:PraRawFormat = 'PraDataOnlyClixml-v1' $script:PraRawNamespace = 'http://schemas.microsoft.com/powershell/2004/04' $script:PraRawDepth = 16 $script:PraRawNodes = 1000000 +$script:PraXmlElement = [Xml.XmlNodeType]::Element +$script:PraOrdinal = [StringComparison]::Ordinal +$script:PraRawMemoryClock = $null +$script:PraRawMemoryText = '' $script:PraRawCulture = [Globalization.CultureInfo]::InvariantCulture $script:PraRawEscape = [regex]'[_\x00-\x1f\x7f-\x9f\uD800-\uDFFF￾￿]' $script:PraRawUnescape = [regex]'_x([0-9a-fA-F]{4})_' @@ -303,15 +307,18 @@ function Assert-PraRawDescriptor { $Budget.Left-- if ($Depth -gt $script:PraRawDepth -or $Budget.Left -lt 0) { throw 'Raw: descriptor depth/node limit or cycle.' } if ($Descriptor -isnot [Collections.IDictionary] -or $Descriptor.Count -ne 4) { throw 'Raw: invalid descriptor shape.' } - foreach ($field in @('Kind','Type','Value','Items')) { - if (-not $Descriptor.Contains($field)) { throw "Raw: missing descriptor field $field." } - } - if ($Descriptor.Kind -isnot [string] -or $Descriptor.Type -isnot [string] -or $Descriptor.Items -isnot [object[]]) { + if (-not $Descriptor.Contains('Kind')) { throw 'Raw: missing descriptor field Kind.' } + if (-not $Descriptor.Contains('Type')) { throw 'Raw: missing descriptor field Type.' } + if (-not $Descriptor.Contains('Value')) { throw 'Raw: missing descriptor field Value.' } + if (-not $Descriptor.Contains('Items')) { throw 'Raw: missing descriptor field Items.' } + $kind = $Descriptor['Kind']; $type = $Descriptor['Type']; $value = $Descriptor['Value']; $items = $Descriptor['Items'] + if ($kind -isnot [string] -or $type -isnot [string] -or $items -isnot [object[]]) { throw 'Raw: invalid descriptor field type.' } - Assert-PraRawScalar $Descriptor.Kind $Descriptor.Type $Descriptor.Value - if (-not [string]::Equals($Descriptor.Kind, 'Collection', [StringComparison]::Ordinal) -and $Descriptor.Items.Count -ne 0) { throw 'Raw: scalar has children.' } - foreach ($item in $Descriptor.Items) { Assert-PraRawDescriptor $item ($Depth+1) $Budget } + # A text value (the common attribute) needs no further check than its kind and type. + if (-not ([string]::Equals($kind, 'Scalar', [StringComparison]::Ordinal) -and [string]::Equals($type, 'String', [StringComparison]::Ordinal) -and $value -is [string])) { Assert-PraRawScalar $kind $type $value } + if (-not [string]::Equals($kind, 'Collection', [StringComparison]::Ordinal) -and $items.Count -ne 0) { throw 'Raw: scalar has children.' } + foreach ($item in $items) { Assert-PraRawDescriptor $item ($Depth+1) $Budget } } function Assert-PraRawSnapshot { @@ -373,16 +380,30 @@ function Write-PraRawObjectStart { function Write-PraRawNode { param([hashtable]$State,$Descriptor,[int]$Depth) - Write-PraRawObjectStart $State - $State.Writer.WriteStartElement('MS',$script:PraRawNamespace) - Write-PraRawElement $State 'I32' 'Depth' $Depth.ToString($script:PraRawCulture) - Write-PraRawElement $State 'S' 'Kind' $Descriptor.Kind - Write-PraRawElement $State 'S' 'Type' $Descriptor.Type - $tag = if ($null -eq $Descriptor.Value) { 'Nil' } else { 'S' } - Write-PraRawElement $State $tag 'Value' $Descriptor.Value - Write-PraRawElement $State 'I32' 'Count' $Descriptor.Items.Count.ToString($script:PraRawCulture) - $State.Writer.WriteEndElement(); $State.Writer.WriteEndElement() - foreach ($item in $Descriptor.Items) { Write-PraRawNode $State $item ($Depth+1) } + # The element calls of Write-PraRawObjectStart and Write-PraRawElement written out: the same XML, a node costs a handful of calls instead of dozens. + $writer = $State.Writer; $ns = $script:PraRawNamespace; $culture = $script:PraRawCulture; $escape = $script:PraRawEscape + $writer.WriteStartElement('Obj',$ns); $writer.WriteAttributeString('RefId',$State.RefId.ToString($culture)); $State.RefId++ + $writer.WriteStartElement('MS',$ns) + $writer.WriteStartElement('I32',$ns); $writer.WriteAttributeString('N','Depth'); $writer.WriteString($Depth.ToString($culture)); $writer.WriteEndElement() + $text = $Descriptor.Kind + $writer.WriteStartElement('S',$ns); $writer.WriteAttributeString('N','Kind') + if ($text.Length -gt 0) { if ($escape.IsMatch($text)) { Write-PraRawString $writer $text } else { $writer.WriteString($text) } } + $writer.WriteEndElement() + $text = $Descriptor.Type + $writer.WriteStartElement('S',$ns); $writer.WriteAttributeString('N','Type') + if ($text.Length -gt 0) { if ($escape.IsMatch($text)) { Write-PraRawString $writer $text } else { $writer.WriteString($text) } } + $writer.WriteEndElement() + $text = $Descriptor.Value + if ($null -eq $text) { $writer.WriteStartElement('Nil',$ns); $writer.WriteAttributeString('N','Value'); $writer.WriteEndElement() } + else { + $writer.WriteStartElement('S',$ns); $writer.WriteAttributeString('N','Value') + if ($text.Length -gt 0) { if ($escape.IsMatch($text)) { Write-PraRawString $writer $text } else { $writer.WriteString($text) } } + $writer.WriteEndElement() + } + $items = $Descriptor.Items + $writer.WriteStartElement('I32',$ns); $writer.WriteAttributeString('N','Count'); $writer.WriteString($items.Count.ToString($culture)); $writer.WriteEndElement() + $writer.WriteEndElement(); $writer.WriteEndElement() + foreach ($item in $items) { Write-PraRawNode $State $item ($Depth+1) } } function Write-PraRawProgress { @@ -392,9 +413,14 @@ function Write-PraRawProgress { if ($null -ne $sam -and [string]::Equals($sam.Kind, 'Scalar', [StringComparison]::Ordinal) -and [string]::Equals($sam.Type, 'String', [StringComparison]::Ordinal)) { $name = $sam.Value } if ($name.Length -gt 128) { $name = $name.Substring(0,128) } $name = [regex]::Replace($name,'[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]','?') - $process = [Diagnostics.Process]::GetCurrentProcess() - try { $private = [Math]::Round($process.PrivateMemorySize64 / 1MB,1).ToString($script:PraRawCulture) } - finally { $process.Dispose() } + # The private memory of the process is read once a second, not for every object (the read takes milliseconds). + if ($null -eq $script:PraRawMemoryClock -or $script:PraRawMemoryClock.ElapsedMilliseconds -ge 1000) { + $process = [Diagnostics.Process]::GetCurrentProcess() + try { $script:PraRawMemoryText = [Math]::Round($process.PrivateMemorySize64 / 1MB,1).ToString($script:PraRawCulture) } + finally { $process.Dispose() } + $script:PraRawMemoryClock = [Diagnostics.Stopwatch]::StartNew() + } + $private = $script:PraRawMemoryText Write-PraLog -Context $Context -Message "RAW $Stage | GUID=$($Snapshot.ObjectGUID) | name=$name | attributes=$($Snapshot.Attributes.Count) | privateMiB=$private | bytes=$Bytes" -Level Debug } @@ -431,10 +457,15 @@ function Write-PraRawCapture { Write-PraRawElement $state 'S' $field $value } Write-PraRawObjectStart $state 'Attributes'; $writer.WriteStartElement('DCT',$script:PraRawNamespace) + $ns = $script:PraRawNamespace; $escape = $script:PraRawEscape foreach ($name in $snapshot.Attributes.Keys) { - $writer.WriteStartElement('En',$script:PraRawNamespace) - Write-PraRawElement $state 'S' 'Key' $name - Write-PraRawObjectStart $state 'Value'; $writer.WriteStartElement('LST',$script:PraRawNamespace) + # Write-PraRawElement (the key) and Write-PraRawObjectStart (the value) written out: the same XML. + $writer.WriteStartElement('En',$ns) + $writer.WriteStartElement('S',$ns); $writer.WriteAttributeString('N','Key') + if ($name.Length -gt 0) { if ($escape.IsMatch($name)) { Write-PraRawString $writer $name } else { $writer.WriteString($name) } } + $writer.WriteEndElement() + $writer.WriteStartElement('Obj',$ns); $writer.WriteAttributeString('RefId',$state.RefId.ToString($script:PraRawCulture)); $state.RefId++ + $writer.WriteAttributeString('N','Value'); $writer.WriteStartElement('LST',$ns) Write-PraRawNode $state $snapshot.Attributes[$name] 0 $writer.WriteEndElement(); $writer.WriteEndElement(); $writer.WriteEndElement() } @@ -476,7 +507,9 @@ function Assert-PraRawXmlStart { function Read-PraRawStart { param([Xml.XmlReader]$Reader,[string]$Tag) - Assert-PraRawXmlStart $Reader $Tag + # An element of the expected name and namespace without attribute is accepted here; any other one goes through Assert-PraRawXmlStart, which says what is wrong. + if (-not ($Reader.MoveToContent() -eq [Xml.XmlNodeType]::Element -and $Reader.AttributeCount -eq 0 -and [string]::Equals($Reader.LocalName, $Tag, [StringComparison]::Ordinal) -and + [string]::Equals($Reader.NamespaceURI, $script:PraRawNamespace, [StringComparison]::Ordinal))) { Assert-PraRawXmlStart $Reader $Tag } if ($Reader.IsEmptyElement) { throw "Raw XML: empty $Tag container." } $Reader.ReadStartElement() } @@ -494,7 +527,10 @@ function Read-PraRawEnd { function Read-PraRawObjectStart { param([hashtable]$State,[string]$Name='') $reader = $State.Reader - Assert-PraRawXmlStart $reader 'Obj' @('RefId','N') + # The attributes an object has (RefId, and N when it is named) are checked here; any other shape goes through Assert-PraRawXmlStart, which says what is wrong. + $null = $reader.MoveToContent(); $attributes = $reader.AttributeCount + if (-not ($reader.NodeType -eq [Xml.XmlNodeType]::Element -and [string]::Equals($reader.LocalName, 'Obj', [StringComparison]::Ordinal) -and [string]::Equals($reader.NamespaceURI, $script:PraRawNamespace, [StringComparison]::Ordinal) -and + $null -ne $reader.GetAttribute('RefId') -and (($Name.Length -eq 0 -and $attributes -eq 1) -or ($Name.Length -gt 0 -and $attributes -eq 2 -and $null -ne $reader.GetAttribute('N'))))) { Assert-PraRawXmlStart $reader 'Obj' @('RefId','N') } if (-not [string]::Equals($reader.GetAttribute('RefId'), $State.RefId.ToString($script:PraRawCulture), [StringComparison]::Ordinal) -or -not [string]::Equals((ConvertFrom-PraRawString ([string]$reader.GetAttribute('N'))), $Name, [StringComparison]::Ordinal) -or $reader.IsEmptyElement) { throw 'Raw XML: object identity/name/sequence invalid; shared references are forbidden.' @@ -504,8 +540,13 @@ function Read-PraRawObjectStart { function Read-PraRawElement { param([Xml.XmlReader]$Reader,[string]$Tag,[string]$Name) - Assert-PraRawXmlStart $Reader $Tag @('N') - if (-not [string]::Equals((ConvertFrom-PraRawString ([string]$Reader.GetAttribute('N'))), $Name, [StringComparison]::Ordinal)) { throw "Raw XML: expected member $Name." } + # A member element has the attribute N and no other: checked here, any other shape goes through Assert-PraRawXmlStart, which says what is wrong. + $null = $Reader.MoveToContent() + $member = $Reader.GetAttribute('N') + if (-not ($Reader.NodeType -eq [Xml.XmlNodeType]::Element -and $Reader.AttributeCount -eq 1 -and $null -ne $member -and [string]::Equals($Reader.LocalName, $Tag, [StringComparison]::Ordinal) -and + [string]::Equals($Reader.NamespaceURI, $script:PraRawNamespace, [StringComparison]::Ordinal))) { Assert-PraRawXmlStart $Reader $Tag @('N'); $member = [string]$Reader.GetAttribute('N') } + if ($member.IndexOf('_x', [StringComparison]::Ordinal) -ge 0) { $member = ConvertFrom-PraRawString $member } + if (-not [string]::Equals($member, $Name, [StringComparison]::Ordinal)) { throw "Raw XML: expected member $Name." } if ([string]::Equals($Tag, 'Nil', [StringComparison]::Ordinal)) { if (-not [string]::Equals($Reader.ReadElementContentAsString(), '', [StringComparison]::Ordinal)) { throw 'Raw XML: nonempty Nil.' } return $null @@ -523,14 +564,46 @@ function Read-PraRawNode { $Budget.Left-- if ($Depth -gt $script:PraRawDepth -or $Budget.Left -lt 0) { throw 'Raw XML: descriptor depth/node limit.' } $reader = $State.Reader - Read-PraRawObjectStart $State; Read-PraRawStart $reader 'MS' - if ((-not (Test-PraOrdinalIgnoreCaseEqual (Read-PraRawElement $reader 'I32' 'Depth') $Depth))) { throw 'Raw XML: invalid descriptor preorder depth.' } - $kind = Read-PraRawElement $reader 'S' 'Kind'; $type = Read-PraRawElement $reader 'S' 'Type' + # The opening of the object and of its member list, the five members of a descriptor and the two closings are read here when they are exactly what the writer produces + # (the right element, namespace, attributes, a text without escape); any other shape goes through the functions that check it and say what is wrong. + $ns = $script:PraRawNamespace; $element = $script:PraXmlElement; $ordinal = $script:PraOrdinal + $null = $reader.MoveToContent() + if ($reader.NodeType -eq $element -and $reader.AttributeCount -eq 1 -and [string]::Equals($reader.LocalName, 'Obj', $ordinal) -and [string]::Equals($reader.NamespaceURI, $ns, $ordinal) -and + [string]::Equals($reader.GetAttribute('RefId'), $State.RefId.ToString($script:PraRawCulture), $ordinal) -and -not $reader.IsEmptyElement) { $State.RefId++; $reader.ReadStartElement() } + else { Read-PraRawObjectStart $State } + $null = $reader.MoveToContent() + if ($reader.NodeType -eq $element -and $reader.AttributeCount -eq 0 -and [string]::Equals($reader.LocalName, 'MS', $ordinal) -and [string]::Equals($reader.NamespaceURI, $ns, $ordinal) -and -not $reader.IsEmptyElement) { $reader.ReadStartElement() } + else { Read-PraRawStart $reader 'MS' } + $null = $reader.MoveToContent() + if ($reader.NodeType -eq $element -and $reader.AttributeCount -eq 1 -and [string]::Equals($reader.LocalName, 'I32', $ordinal) -and [string]::Equals($reader.NamespaceURI, $ns, $ordinal) -and [string]::Equals($reader.GetAttribute('N'), 'Depth', $ordinal)) { $number = $reader.ReadElementContentAsString() } + else { $number = [string](Read-PraRawElement $reader 'I32' 'Depth') } + if (-not [string]::Equals($number, $Depth.ToString($script:PraRawCulture), $ordinal)) { + $parsed = 0 + if ([int]::TryParse($number, $script:PraRawCulture, [ref]$parsed) -and $parsed -eq [int]$Depth) { throw 'Raw XML: noncanonical Int32.' } + throw 'Raw XML: invalid descriptor preorder depth.' + } + $null = $reader.MoveToContent() + if ($reader.NodeType -eq $element -and $reader.AttributeCount -eq 1 -and [string]::Equals($reader.LocalName, 'S', $ordinal) -and [string]::Equals($reader.NamespaceURI, $ns, $ordinal) -and [string]::Equals($reader.GetAttribute('N'), 'Kind', $ordinal)) { $kind = $reader.ReadElementContentAsString(); if ($kind.IndexOf('_x', $ordinal) -ge 0) { $kind = ConvertFrom-PraRawString $kind } } + else { $kind = Read-PraRawElement $reader 'S' 'Kind' } + $null = $reader.MoveToContent() + if ($reader.NodeType -eq $element -and $reader.AttributeCount -eq 1 -and [string]::Equals($reader.LocalName, 'S', $ordinal) -and [string]::Equals($reader.NamespaceURI, $ns, $ordinal) -and [string]::Equals($reader.GetAttribute('N'), 'Type', $ordinal)) { $type = $reader.ReadElementContentAsString(); if ($type.IndexOf('_x', $ordinal) -ge 0) { $type = ConvertFrom-PraRawString $type } } + else { $type = Read-PraRawElement $reader 'S' 'Type' } $null = $reader.MoveToContent(); $tag = $reader.LocalName - if (-not ([string]::Equals($tag, 'S', [StringComparison]::Ordinal) -or [string]::Equals($tag, 'Nil', [StringComparison]::Ordinal))) { throw 'Raw XML: invalid descriptor value type.' } - $value = Read-PraRawElement $reader $tag 'Value'; $count = Read-PraRawElement $reader 'I32' 'Count' + if (-not ([string]::Equals($tag, 'S', $ordinal) -or [string]::Equals($tag, 'Nil', $ordinal))) { throw 'Raw XML: invalid descriptor value type.' } + if ($reader.NodeType -eq $element -and $reader.AttributeCount -eq 1 -and [string]::Equals($reader.NamespaceURI, $ns, $ordinal) -and [string]::Equals($reader.GetAttribute('N'), 'Value', $ordinal) -and [string]::Equals($tag, 'S', $ordinal)) { $value = $reader.ReadElementContentAsString(); if ($value.IndexOf('_x', $ordinal) -ge 0) { $value = ConvertFrom-PraRawString $value } } + else { $value = Read-PraRawElement $reader $tag 'Value' } + $null = $reader.MoveToContent() + if ($reader.NodeType -eq $element -and $reader.AttributeCount -eq 1 -and [string]::Equals($reader.LocalName, 'I32', $ordinal) -and [string]::Equals($reader.NamespaceURI, $ns, $ordinal) -and [string]::Equals($reader.GetAttribute('N'), 'Count', $ordinal)) { + $number = $reader.ReadElementContentAsString(); $count = [int]::Parse($number, $script:PraRawCulture) + if (-not [string]::Equals($count.ToString($script:PraRawCulture), $number, $ordinal)) { throw 'Raw XML: noncanonical Int32.' } + } + else { $count = Read-PraRawElement $reader 'I32' 'Count' } if ($count -lt 0 -or $count -gt $Budget.Left -or (-not [string]::Equals($kind, 'Collection', [StringComparison]::Ordinal) -and $count -ne 0)) { throw 'Raw XML: invalid item cardinality.' } - Read-PraRawEnd $reader 'MS'; Read-PraRawEnd $reader 'Obj' + $end = [Xml.XmlNodeType]::EndElement + $null = $reader.MoveToContent() + if ($reader.NodeType -eq $end -and [string]::Equals($reader.LocalName, 'MS', $ordinal) -and [string]::Equals($reader.NamespaceURI, $ns, $ordinal)) { $reader.ReadEndElement() } else { Read-PraRawEnd $reader 'MS' } + $null = $reader.MoveToContent() + if ($reader.NodeType -eq $end -and [string]::Equals($reader.LocalName, 'Obj', $ordinal) -and [string]::Equals($reader.NamespaceURI, $ns, $ordinal)) { $reader.ReadEndElement() } else { Read-PraRawEnd $reader 'Obj' } $items = [Collections.Generic.List[object]]::new() for ($i=0; $i -lt $count; $i++) { $items.Add((Read-PraRawNode $State ($Depth+1) $Budget)) } return ,([ordered]@{Kind=$kind; Type=$type; Value=$value; Items=[object[]]$items.ToArray()}) diff --git a/package/module/PRA.Cloud.psm1 b/package/module/PRA.Cloud.psm1 index 3814335..b512598 100644 --- a/package/module/PRA.Cloud.psm1 +++ b/package/module/PRA.Cloud.psm1 @@ -30,8 +30,8 @@ Identity: unless Cloud.IdentityCheck = Off, the Microsoft Entra ID account of every object (and of every trustee of a permission to grant) must carry the Active Directory source anchor of the object (onPremisesImmutableId = base64 of the objectGUID or of ms-DS-ConsistencyGuid). Another account, a cloud-only account or an - ambiguous answer is an error for that object and nothing is changed on it. The Exchange Online object found by UPN must carry the ExternalDirectoryObjectId of - that account. + ambiguous answer is an error for that object and nothing is changed on it. The Exchange Online object of a confirmed account is read with -ExternalDirectoryObjectId (by UPN + only when no account is confirmed) and must carry the ExternalDirectoryObjectId of that account; a permission is written with the confirmed ids of the mailbox and of the trustee. Retries: a read of Microsoft Graph or Exchange Online is sent again on 408, 429, 502, 503, 504, a timeout or no answer (Retry-After honoured), within Cloud.RetryBudgetObjectSeconds for an object and Cloud.RetryBudgetRunMinutes for the run; a throttled answer slows the calls of the whole run, and a run that used @@ -162,9 +162,31 @@ $script:PraExoWorker = { if ($null -ne $id -and $id) { return [string]$id } return '' } + # The selector of a read of the Exchange Online object: the dedicated -ExternalDirectoryObjectId parameter for a confirmed account, the UPN as the identity otherwise. + function Selector { + param([string]$Upn) + $id=Confirmed $Upn + if ($id) { return @{ ExternalDirectoryObjectId=$id } } + return @{ Identity=$Upn } + } + # The value that names the object in a write (-Identity, -User, -Trustee): the confirmed Entra id, the UPN only when no id is known. + function WriteKey { + param([string]$Name) + $id=Confirmed $Name + if ($id) { return $id } + return $Name + } + # An absent object by a GUID is told like an absent object by a UPN: the key is echoed in the text, in any casing. + function NotFoundText { + param([string]$Text,[string]$Key) + foreach ($form in @(("object '"+$Key+"' couldn't be found"),("Couldn't find object `""+$Key+"`""),("object '"+$Key+"' couldn"+[char]0x2019+"t be found"))) { + if ($Text.IndexOf($form,[StringComparison]::OrdinalIgnoreCase) -ge 0) { return $true } + } + return $false + } function MissingRecipient { param([System.Management.Automation.ErrorRecord]$Record,[string]$Upn) - # A selector read (-UserPrincipalName) answers an absent object with HTTP 404 ManagementObjectNotFoundException + # A selector read (-UserPrincipalName or -ExternalDirectoryObjectId) answers an absent object with HTTP 404 ManagementObjectNotFoundException # instead of an empty result (for example while a deprovisioned mailbox turns into a MailUser). $text=$Record.Exception.Message if ($text -notmatch 'HttpStatusCode=404') { return $false } @@ -172,10 +194,8 @@ $script:PraExoWorker = { if (-not $json.Success) { return $false } try { $payload=$json.Value | ConvertFrom-Json -DateKind String -ErrorAction Stop - # Substring searches are ordinal and case-insensitive. - $object="object '"+$Upn+"' couldn't be found" $detail=@($payload.error.details | Where-Object { ([string]$_.message).IndexOf('|Microsoft.Exchange.Configuration.Tasks.ManagementObjectNotFoundException|',[StringComparison]::OrdinalIgnoreCase) -ge 0 }) - return ((SameOrdinal $payload.error.code 'NotFound') -and ([string]$payload.error.message).IndexOf($object,[StringComparison]::OrdinalIgnoreCase) -ge 0 -and $detail.Count -gt 0 -and ([string]$detail[0].message).IndexOf($object,[StringComparison]::OrdinalIgnoreCase) -ge 0) + return ((SameOrdinal $payload.error.code 'NotFound') -and (NotFoundText ([string]$payload.error.message) $Upn) -and $detail.Count -gt 0 -and (NotFoundText ([string]$detail[0].message) $Upn)) } catch { return $false } } function Recipient { @@ -185,7 +205,7 @@ $script:PraExoWorker = { # "Not found" is read through -ErrorVariable (no transcript error line); any other error stops. $recipientErrors=$null $byId=Confirmed $Upn - $selector=if ($byId) { @{ Identity=$byId } } else { @{ UserPrincipalName=$Upn; ResultSize='Unlimited' } } + $selector=if ($byId) { @{ ExternalDirectoryObjectId=$byId } } else { @{ UserPrincipalName=$Upn; ResultSize='Unlimited' } } $missingKey=if ($byId) { $byId } else { $Upn } try { $items = @(Get-EXORecipient @selector -Properties RecipientTypeDetails,PrimarySmtpAddress,ExternalDirectoryObjectId,Guid,DistinguishedName -ErrorAction SilentlyContinue -ErrorVariable recipientErrors -WarningAction Stop) } catch { if (-not (MissingRecipient $_ $missingKey)) { throw }; $items=@(); $recipientErrors=@($_) } @@ -220,22 +240,27 @@ $script:PraExoWorker = { if ($Hold) { $properties += @('IsInactiveMailbox','InPlaceHolds','LitigationHoldEnabled','RetentionHoldEnabled') } $byId = Confirmed $Upn if ($byId) { - try { $items = @(Get-EXOMailbox -Identity $byId -Properties $properties -ErrorAction Stop) } - catch { if ($_.Exception.Message -notmatch "(?i)couldn.t be found|HttpStatusCode=404|ManagementObjectNotFoundException") { throw }; $items = @() } + try { $items = @(Get-EXOMailbox -ExternalDirectoryObjectId $byId -Properties $properties -ErrorAction Stop) } + catch { if ($_.Exception.Message -notmatch "(?i)couldn.t be found|couldn.t find|HttpStatusCode=404|ManagementObjectNotFoundException") { throw }; $items = @() } } else { $items = @(Get-EXOMailbox -Filter (ExactFilter $Upn) -Properties $properties -ResultSize Unlimited -ErrorAction Stop) } $inactiveByUpn = $false if ($Hold -and $items.Count -eq 0) { - # The inactive mailbox of a deleted account has no account to confirm and another ExternalDirectoryObjectId than a live account with the same UPN: - # it is found by UPN, told apart by the recorded anchor when Exchange Online exposes it, and several candidates are an ambiguity, never a guess. + # The inactive mailbox of a deleted account has no account to confirm and another ExternalDirectoryObjectId than a live account with the same UPN. + # Without a confirmed account it is found by UPN, and several candidates are an ambiguity, never a guess. With a confirmed account, an inactive + # mailbox that carries another ExternalDirectoryObjectId belongs to an earlier account: it is not the mailbox of this object and never decides the verdict. $items = @(Get-EXOMailbox -Filter (ExactFilter $Upn) -Properties $properties -ResultSize Unlimited -InactiveMailboxOnly -ErrorAction Stop) - if ($items.Count -gt 1) { - $anchors = @(V $P 'Anchors' @() | Where-Object { $_ }) - $matching = @($items | Where-Object { $own = [string](V $_ 'ImmutableId' ''); $own -and (InSet $own $anchors) }) - if ($matching.Count -ne 1) { throw "Exchange Online has $($items.Count) inactive mailboxes for $Upn and nothing tells which one belongs to this object: the retention cannot be checked for it." } - $items = $matching + if ($byId) { + $own = @($items | Where-Object { SameIgnoreCase ([string](V $_ 'ExternalDirectoryObjectId' '')) $byId }) + if (-not $own.Count -and $items.Count) { + return @{ Found=$false; Type=$null; Holds=@(); IsInactive=$false; Litigation=$false; RetentionHold=$false; HasAddresses=$false; Addresses=[string[]]@(); EarlierAccount=$true; EarlierCount=[int]$items.Count } + } + $items = $own + } + elseif ($items.Count -gt 1) { + throw ("Exchange Online has $($items.Count) inactive mailboxes for $Upn and nothing tells which one belongs to this object: the retention cannot be checked for it. To list them, run: Get-EXOMailbox -InactiveMailboxOnly -Filter ""$(ExactFilter $Upn)"" -Properties ExternalDirectoryObjectId,WhenSoftDeleted,InPlaceHolds | Format-List Name,ExternalDirectoryObjectId,WhenSoftDeleted,InPlaceHolds. Then check by hand, in the Microsoft Purview portal, the retention of the mailbox of this object.") } - $inactiveByUpn = ($items.Count -eq 1) + $inactiveByUpn = (-not $byId -and $items.Count -eq 1) } if ($items.Count -gt 1) { throw "Exchange Online mailbox not unique: $Upn" } if ($items.Count -eq 0) { return @{ Found=$false; Type=$null; Holds=@(); IsInactive=$false; Litigation=$false; RetentionHold=$false; HasAddresses=$false; Addresses=[string[]]@() } } @@ -312,9 +337,9 @@ $script:PraExoWorker = { function Permission { param([string]$Upn,[string]$Trustee,[string]$Right,$Recipient,$Target,[switch]$AllowPendingVisibility) if ((SameIgnoreCase $Right 'FullAccess') -or (SameIgnoreCase $Right 'SendAs')) { - $lookupKey=$(if (Confirmed $Upn) { Confirmed $Upn } else { $Upn }) - $globalRaw=@(if ((SameIgnoreCase $Right 'FullAccess')) { Get-EXOMailboxPermission -Identity $lookupKey -ErrorAction Stop -WarningAction Stop } - else { Get-EXORecipientPermission -Identity $lookupKey -ErrorAction Stop -WarningAction Stop }) + $lookup=Selector $Upn + $globalRaw=@(if ((SameIgnoreCase $Right 'FullAccess')) { Get-EXOMailboxPermission @lookup -ErrorAction Stop -WarningAction Stop } + else { Get-EXORecipientPermission @lookup -ErrorAction Stop -WarningAction Stop }) if ($globalRaw.Count -eq 0 -or $globalRaw.Count -ge 1000) { throw "$Right permission list empty or possibly truncated." } $globalEntries=@(NormalizeAcl $globalRaw $Right $Target) if (-not @($globalEntries | Where-Object { (InSetIgnoreCase $_.Principal @('NT AUTHORITY\SELF','S-1-5-10')) -and (InSetIgnoreCase $Right $_.Rights) -and -not $_.Inherited }).Count) { throw "$Right permission list without the expected SELF entry." } @@ -323,8 +348,8 @@ $script:PraExoWorker = { # not -ErrorAction Stop, so that Windows PowerShell does not write it as an error in the transcript. # Every error record is checked: anything else than that exact answer stops. $filteredErrors=$null - $filteredRaw=@(if ((SameIgnoreCase $Right 'FullAccess')) { Get-EXOMailboxPermission -Identity $lookupKey -User $Trustee -ErrorAction SilentlyContinue -ErrorVariable filteredErrors -WarningAction Stop } - else { Get-EXORecipientPermission -Identity $lookupKey -Trustee $Trustee -ErrorAction Stop -WarningAction Stop }) + $filteredRaw=@(if ((SameIgnoreCase $Right 'FullAccess')) { Get-EXOMailboxPermission @lookup -User $Trustee -ErrorAction SilentlyContinue -ErrorVariable filteredErrors -WarningAction Stop } + else { Get-EXORecipientPermission @lookup -Trustee $Trustee -ErrorAction Stop -WarningAction Stop }) $filteredErrors=@($filteredErrors | Where-Object { $null -ne $_ }) if ($filteredErrors.Count) { foreach ($record in $filteredErrors) { @@ -421,10 +446,11 @@ $script:PraExoWorker = { ($delay -isnot [int] -and $delay -isnot [long]) -or $delay -lt 1 -or $delay -gt 30) { throw 'Invalid Exchange Online verification cadence (1..60 reads, 1..30 seconds).' } if ($OnApplied -isnot [scriptblock]) { throw 'The Applied journal callback is required before an Exchange Online grant.' } $write=Session $right + $writeTarget=WriteKey $upn; $writeTrustee=WriteKey $trustee switch ($right) { - 'FullAccess' { & $write.Command -Identity $upn -User $trustee -AccessRights FullAccess -AutoMapping:([bool](V -Object $P -Name 'AutoMapping' -Default $false)) -InheritanceType All -Confirm:$false -ErrorAction Stop | Out-Null } - 'SendAs' { & $write.Command -Identity $upn -Trustee $trustee -AccessRights SendAs -Confirm:$false -ErrorAction Stop | Out-Null } - 'SendOnBehalf' { & $write.Command -Identity $upn -GrantSendOnBehalfTo @{ Add=$trustee } -Confirm:$false -ErrorAction Stop | Out-Null } + 'FullAccess' { & $write.Command -Identity $writeTarget -User $writeTrustee -AccessRights FullAccess -AutoMapping:([bool](V -Object $P -Name 'AutoMapping' -Default $false)) -InheritanceType All -Confirm:$false -ErrorAction Stop | Out-Null } + 'SendAs' { & $write.Command -Identity $writeTarget -Trustee $writeTrustee -AccessRights SendAs -Confirm:$false -ErrorAction Stop | Out-Null } + 'SendOnBehalf' { & $write.Command -Identity $writeTarget -GrantSendOnBehalfTo @{ Add=$writeTrustee } -Confirm:$false -ErrorAction Stop | Out-Null } } # Add returned. Persist this fact before any eventual-consistency read, never repeat Add. try { @@ -630,6 +656,17 @@ function Stop-PraCloudRun { } function Invoke-PraCloudCall { + <# One read with retries (Invoke-PraCloudCallCore). A failure of a Microsoft Graph call is marked (Data PraGraph), so that a refusal of Microsoft Graph is told apart from a failure of Exchange Online. #> + [CmdletBinding()] + param([Parameter(Mandatory)][hashtable]$Context, [Parameter(Mandatory)][string]$Call, [Parameter(Mandatory)][scriptblock]$Script, [object[]]$ArgumentList = @(), [switch]$NoRetry) + try { return (Invoke-PraCloudCallCore @PSBoundParameters) } + catch { + if ($Call.StartsWith('Microsoft Graph', [StringComparison]::OrdinalIgnoreCase)) { $_.Exception.Data['PraGraph'] = $true } + throw + } +} + +function Invoke-PraCloudCallCore { <# .SYNOPSIS One read of Microsoft Graph or Exchange Online that can be sent again. A transient failure (408, 429, 502, 503, 504, a timeout, no answer) is retried after the @@ -761,8 +798,12 @@ function Get-PraGraphRefusal { $raw = [string]$ErrorRecord.Exception.Message $refused = (Test-PraOrdinalIn $info.Status @(401, 403)) -or ($raw -match '(?i)Insufficient privileges|Authorization_RequestDenied|Authorization_IdentityNotFound|Forbidden') if (-not $refused) { return $null } - $message = '{0}: Microsoft Graph refused to read the Microsoft Entra ID account that confirms this object ({1}). Nothing was changed. The tool reads every account with the permission User.Read.All: with a sign-in by a person, the administrator must consent to User.Read.All; with a certificate (application), add the application permission User.Read.All to the app registration and grant admin consent. Then run the same command again. Or set Cloud.IdentityCheck = ''Off'' in the configuration file: the accounts are then found by UPN only, without this read.' -f $Upn, $(if ($info.Status) { 'HTTP ' + $info.Status } else { 'insufficient privileges' }) - return [pscustomobject]@{ Message = $message; Technical = $raw } + if ($info.Status -eq 401) { + $expired = '{0}: Microsoft Graph did not accept the sign-in (HTTP 401): the sign-in expired or was refused. Nothing was changed. Sign in again: run the same command again and sign in when asked. With a certificate (application), check that the certificate is installed and still valid, and that Cloud.TenantId and Cloud.AppId are the ones of your app registration.' -f $Upn + return [pscustomobject]@{ Message = $expired; Technical = $raw; Kind = 'Expired' } + } + $message ='{0}: Microsoft Graph refused to read the Microsoft Entra ID account that confirms this object ({1}). Nothing was changed. The tool reads every account with the permission User.Read.All: with a sign-in by a person, the administrator must consent to User.Read.All; with a certificate (application), add the application permission User.Read.All to the app registration and grant admin consent. Then run the same command again. Or set Cloud.IdentityCheck = ''Off'' in the configuration file: the accounts are then found by UPN only, without this read.' -f $Upn, $(if ($info.Status) { 'HTTP ' + $info.Status } else { 'insufficient privileges' }) + return [pscustomobject]@{ Message = $message; Technical = $raw; Kind = 'Denied' } } function Confirm-PraCloudIdentity { @@ -784,7 +825,7 @@ function Confirm-PraCloudIdentity { if ($session.IdentityCache.ContainsKey($upn)) { $verdict = $session.IdentityCache[$upn] } else { try { $verdict = Resolve-PraCloudIdentity -Context $Context -Upn $upn -Anchors $anchor.Candidates -Recorded $anchor.Recorded -Property ([string[]]@(Get-PraList $State 'FactProps')) } - catch { $refusal = Get-PraGraphRefusal -ErrorRecord $_ -Upn $upn; if ($null -eq $refusal) { throw }; return (& $fail $refusal.Message $refusal.Technical) } + catch { $refusal = Get-PraGraphRefusal -ErrorRecord $_ -Upn $upn; if ($null -eq $refusal) { throw }; if (-not $Throw) { $Context.GraphRefused = $true }; return (& $fail $refusal.Message $refusal.Technical) } if (Test-PraOrdinalIn $verdict.Status @('Match', 'Mismatch', 'Ambiguous')) { $session.IdentityCache[$upn] = $verdict } } if (Test-PraOrdinalIn $verdict.Status @('Mismatch', 'Ambiguous')) { return (& $fail $verdict.Message $verdict.Technical) } @@ -813,7 +854,7 @@ function Confirm-PraCloudIdentity { if ($session.IdentityCache.ContainsKey($trustee)) { $answer = $session.IdentityCache[$trustee] } else { try { $answer = Resolve-PraCloudIdentity -Context $Context -Upn $trustee -Anchors ([string[]]@(if ($null -ne $stored) { @($stored) })) -Recorded ($null -ne $stored) -SyncedOnly } - catch { $refusal = Get-PraGraphRefusal -ErrorRecord $_ -Upn $trustee; if ($null -eq $refusal) { throw }; return (& $fail $refusal.Message $refusal.Technical) } + catch { $refusal = Get-PraGraphRefusal -ErrorRecord $_ -Upn $trustee; if ($null -eq $refusal) { throw }; if (-not $Throw) { $Context.GraphRefused = $true }; return (& $fail $refusal.Message $refusal.Technical) } if (Test-PraOrdinalIn $answer.Status @('Match', 'Mismatch', 'Ambiguous')) { $session.IdentityCache[$trustee] = $answer } } if (Test-PraOrdinalIn $answer.Status @('Mismatch', 'Ambiguous')) { return (& $fail ('Permissions on {0} are not granted. {1}' -f $upn, $answer.Message) $answer.Technical) } @@ -1094,7 +1135,7 @@ function Assert-PraGraphSession { function Close-PraCloudSession { <# .SYNOPSIS - Signs out the sessions opened by this module; a sign-out failure is an error. + Signs out the sessions opened by this module; a sign-out failure is a warning (the session stays recorded, a later call tries again). #> [CmdletBinding()] param([Parameter(Mandatory)][hashtable]$Context) @@ -1128,9 +1169,9 @@ function Close-PraCloudSession { catch { [void]$errors.Add('Microsoft Graph sign-out: '+$_.Exception.Message) } } if ($errors.Count) { - $Context.CloudConnectFailed=$true; $Context.CurrentOperation='Close-PraCloudSession' - Write-PraCloudError -Context $Context -Row $null -Message ($errors -join ' | ') - throw ($errors -join ' | ') + $Context.CurrentOperation='Close-PraCloudSession' + Write-PraSignOutWarning -Context $Context -Message ($errors -join ' | ') + return } [void]$Context.Remove('_PraCloudSession') } @@ -1225,6 +1266,22 @@ function Initialize-PraCloudPreflight { } } +function Get-PraGrantKey { + <# The identity of one grant in this run: the mailbox (its confirmed Entra id, else its UPN), the right and the trustee (its confirmed id, else as given). #> + param([hashtable]$Context,[string]$Upn,[string]$Right,[string]$Trustee) + $verified=(Get-PraCloudSession $Context).Verified + $mailbox=if ($verified.ContainsKey($Upn) -and [string]$verified[$Upn]) { [string]$verified[$Upn] } else { $Upn } + $who=if ($verified.ContainsKey($Trustee) -and [string]$verified[$Trustee]) { [string]$verified[$Trustee] } else { $Trustee } + return ($mailbox+'|'+$Right+'|'+$who) +} + +function Get-PraGrantsApplied { + <# The grants already sent in this run (mailbox id, right, trustee; ignoring case): a grant in this set is never sent again, whatever a later read shows. #> + param([hashtable]$Context) + if (-not $Context.ContainsKey('_PraGrantsApplied')) { $Context['_PraGrantsApplied']=New-Object 'System.Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase) } + return ,$Context['_PraGrantsApplied'] +} + function Invoke-PraPermissionGrant { param([hashtable]$Context,$Row,[hashtable]$Params) if ($Context.AllowMutation -isnot [bool] -or -not $Context.AllowMutation -or -not (Test-PraOrdinalEqual $Context.Mode 'Apply') -or @@ -1245,6 +1302,8 @@ function Invoke-PraPermissionGrant { $detail="UPN=$target; Trustee=$($Params.Trustee); Right=$($Params.Right); ObjectGuid=$($Context.CurrentIdentity)" $Row.LastOperation=$operation $null = & $Context.JournalMutation $target $operation 'Started' $detail + [void](Get-PraGrantsApplied $Context).Add((Get-PraGrantKey -Context $Context -Upn $target -Right ([string]$Params.Right) -Trustee ([string]$Params.Trustee))) + $Context.GrantsSent=[int](Get-PraValue $Context 'GrantsSent' 0)+1 $permit=@{ AllowMutation=$true; Approved=$true; Authorized=$true; JournalStarted=$true; Target=$target Trustee=$Params.Trustee; Right=$Params.Right; Action=$Context.Action; Mode=$Context.Mode; Phase=$Context.Phase } try { @@ -1292,6 +1351,10 @@ function Invoke-PraSharedPermission { } if ((Get-PraValue $r 'Verified' $false) -ne $true) { if ($preview) { $toGrant++; continue } + if ((Get-PraGrantsApplied $Context).Contains((Get-PraGrantKey -Context $Context -Upn $upn -Right ([string]$request.Right) -Trustee ([string]$request.Trustee)))) { + $null=Write-PraLog -Context $Context -Message ("{0}: {1} to {2} was already sent in this run; it is not sent again although the last read does not show it yet" -f $upn,$request.Right,$request.Trustee) -Level Detail + $verified++; continue + } if ($Context.AllowMutation -isnot [bool] -or -not $Context.AllowMutation -or -not (Test-PraOrdinalEqual $Context.Mode 'Apply') -or -not (Test-PraOrdinalEqual $Context.Action 'Convert') -or -not (Test-PraOrdinalIn $Context.Phase @('Cloud','Both')) -or $WhatIfPreference) { throw 'Permission missing and writes are not allowed in this mode.' } # Native ShouldProcess per right; it never replaces the approval, proof and journal of the grant. @@ -1338,7 +1401,7 @@ function Get-PraGraphFact { } if ($users.Count -ne 1 -or $null -eq $users[0]) { throw "Microsoft Graph: user not found or not unique ($Upn)." } $returnedId=[string](Get-PraValue $users[0] 'Id' '') - if ($confirmed -and $returnedId -and -not (Test-PraOrdinalIgnoreCaseEqual $returnedId $confirmed)) { throw "Microsoft Graph returned another account than the one confirmed for this object: $Upn" } + if ($confirmed -and $returnedId -and -not (Test-PraOrdinalIgnoreCaseEqual $returnedId $confirmed)) { throw "Microsoft Graph returned another account than the one confirmed for this object: $Upn. Nothing was changed on it. Run the same command again, the account is then confirmed once more. If this comes back, look at the account: Get-MgUser -UserId $confirmed -Property Id,UserPrincipalName,OnPremisesImmutableId" } $values=@{} foreach ($prop in $props) { $value=Get-PraValue $users[0] $prop $sentinel @@ -1440,6 +1503,33 @@ function Invoke-PraX500Step { return $false } +function Write-PraUnfinishedFailure { + <# A failure that ends a cloud part before every row is done. A row that finished (Success, Skipped, Planned, Error) keeps its result. A run stop (the retry time of the run is used up) leaves the other rows Pending under ONE error; any other failure is an error of each row that was not finished (or one run error when every row had finished). -What: 'finished' or 'checked'. #> + param([hashtable]$Context,[AllowEmptyCollection()][object[]]$Rows,[Parameter(Mandatory)]$ErrorRecord,[string]$What='finished') + $unfinished=@($Rows | Where-Object { -not (Test-PraOrdinalIn ([string](Get-PraValue $_ 'CloudStatus' '')) @('Success','Skipped','Error','Planned')) }) + $runStop=((Get-PraRetryState $Context).RunExhausted -or ($ErrorRecord.Exception.Data['PraRunBudget'] -eq $true)) + if ($runStop) { + foreach ($row in $unfinished) { + $row.CloudStatus='Pending'; $row.FinalStatus='Pending' + $row.Detail=([string](Get-PraValue $row 'Detail' '')+' | not '+$What+': the retry time of the run is used up').Trim(' ','|') + } + $Context.CurrentIdentity='' + Write-PraCloudError -Context $Context -Row $null -Message ('{0} {1} object(s) were not {2}.' -f $ErrorRecord.Exception.Message, $unfinished.Count, $What) -Technical $(if ($null -ne $ErrorRecord.Exception.InnerException) { [string]$ErrorRecord.Exception.InnerException.Message } else { '' }) + return + } + foreach ($row in $unfinished) { Write-PraCloudFailure -Context $Context -Row $row -ErrorRecord $ErrorRecord -Upn ([string](Get-PraValue $row 'UserPrincipalName' '')) } + if (-not $unfinished.Count) { Write-PraCloudFailure -Context $Context -Row $null -ErrorRecord $ErrorRecord } +} + +function Write-PraSignOutWarning { + <# The sign-out of the cloud sessions failed: a warning, never an error of an object (what the run did is not changed by it). #> + param([hashtable]$Context,[Parameter(Mandatory)][string]$Message) + $null=Write-PraLog -Context $Context -Message ('Technical detail: sign-out failed: {0}' -f $Message) -Level Detail + if ([bool](Get-PraValue $Context 'CloudSignOutWarned' $false)) { return } + $Context.CloudSignOutWarned=$true + Write-PraItem -Context $Context -Status Warn -Text ('The sign-out of Microsoft 365 failed ({0}). What this run did is not affected. If a session is still open, close it: Disconnect-ExchangeOnline -Confirm:$false; Disconnect-MgGraph' -f ($Message -replace '\s+',' ')) +} + function Invoke-PraCloudPhase { <# .SYNOPSIS @@ -1448,7 +1538,7 @@ function Invoke-PraCloudPhase { [CmdletBinding()] param([Parameter(Mandatory)][hashtable]$Context,[Parameter(Mandatory)][AllowEmptyCollection()][object[]]$Rows, [Parameter(Mandatory)][ValidateSet('Convert','Recover')][string]$Act) - $Context.CurrentPhase='Cloud'; $Context.CurrentOperation='Prepare'; $Context.CurrentIdentity=''; $Context.CloudConnectFailed=$false; $Context.NetworkFailure=$false; $Context.NotYetExpected=0; $Context.CloudNotReached=0 + $Context.CurrentPhase='Cloud'; $Context.CurrentOperation='Prepare'; $Context.CurrentIdentity=''; $Context.CloudConnectFailed=$false; $Context.NetworkFailure=$false; $Context.NotYetExpected=0; $Context.CloudNotReached=0; $Context.GraphRefused=$false $states=New-Object 'System.Collections.Generic.List[object]' try { if (-not (Test-PraOrdinalIn $Act @('Convert','Recover'))) { throw 'Unknown -Act.' } @@ -1526,7 +1616,7 @@ function Invoke-PraCloudPhase { catch { $Context.CloudConnectFailed=$true; throw } $clock=[Diagnostics.Stopwatch]::StartNew(); $timeout=[double]$Context.TimeoutMinutes*60; $attempt=0 $x500MaxReads=3 # first read + two re-reads at the polling interval: the cloud value can lag one synchronisation, never a long new wait - $stopRun=$null + $stopRun=$null; $graphStop=$false do { $attempt++; $pending=@($states | Where-Object { -not $_.Done }) $null=Write-PraLog -Context $Context -Message ("Check {0}: {1} object(s) in Exchange Online" -f $attempt, $pending.Count) -Level Info @@ -1540,14 +1630,15 @@ function Invoke-PraCloudPhase { if ($s.GraphMailbox -or $s.License) { $s.FactProps=[string[]]@(Get-PraGraphFactProperty -Mailbox $s.GraphMailbox -License $s.License -Addresses ([bool]($null -ne $s.X500 -and $s.GraphMailbox))) } $outcome=Confirm-PraCloudIdentity -Context $Context -State $s $Context.CurrentOperation='CloudCheck' - if (Test-PraOrdinalEqual $outcome 'Failed') { $s.Done=$true; continue } + if (Test-PraOrdinalEqual $outcome 'Failed') { $s.Done=$true; if ([bool](Get-PraValue $Context 'GraphRefused' $false)) { $graphStop=$true; break }; continue } if (Test-PraOrdinalEqual $outcome 'Wait') { continue } $s.IdentityChecked=$true } $details=New-Object 'System.Collections.Generic.List[string]'; $plain=New-Object 'System.Collections.Generic.List[string]'; $mbok=$true; $licok=$true; $facts=$null if ($s.GraphMailbox -or $s.License) { - $facts=Get-PraGraphFact -Context $Context -Upn $s.Upn -Mailbox $s.GraphMailbox -License $s.License -Addresses ([bool]($null -ne $s.X500 -and $s.GraphMailbox)) -Account (Get-PraValue $s 'Account' $null) + $account=Get-PraValue $s 'Account' $null $s.Account=$null + $facts=Get-PraGraphFact -Context $Context -Upn $s.Upn -Mailbox $s.GraphMailbox -License $s.License -Addresses ([bool]($null -ne $s.X500 -and $s.GraphMailbox)) -Account $account } if ($s.ExoMailbox) { $m=Invoke-PraExo -Context $Context -Operation 'Mailbox' -Params @{ Upn=$s.Upn } @@ -1620,6 +1711,14 @@ function Invoke-PraCloudPhase { $failure=$_ $info=Get-PraCloudFailureInfo $failure if ((Get-PraRetryState $Context).RunExhausted) { $stopRun=$failure; break } + if ($failure.Exception.Data['PraGraph'] -eq $true) { + # A refusal of Microsoft Graph (no permission, expired sign-in) is the same for every object: ONE error, the objects not finished stay Pending. + $refusal=Get-PraGraphRefusal -ErrorRecord $failure -Upn $s.Upn + if ($null -ne $refusal) { + Write-PraCloudError -Context $Context -Row $row -Message $refusal.Message -Technical $refusal.Technical -RunError + $s.Done=$true; $Context.GraphRefused=$true; $graphStop=$true; break + } + } if ($failure.Exception.Data['PraGrantFailed'] -eq $true) { # The grant step is never repeated in this run (a second Add would need a new approval and new journal lines): the object ends here, a later run reads the permissions first. Write-PraCloudError -Context $Context -Row $row -RunError -Message ('{0}: a shared mailbox permission could not be granted or verified ({1}). It is not granted a second time in this run: run the cloud phase again later, it reads the permissions first and grants only what is missing.' -f $s.Upn, ([string]$failure.Exception.Message -replace '\s+',' ')) -Technical ([string]$failure.Exception.Message) @@ -1633,7 +1732,7 @@ function Invoke-PraCloudPhase { else { Write-PraCloudFailure -Context $Context -Row $row -ErrorRecord $failure -Upn $s.Upn -Extra ([string]$row.PermDetail); $s.Done=$true } } } - if ($null -ne $stopRun) { break } + if ($null -ne $stopRun -or $graphStop) { break } $pending=@($states | Where-Object { -not $_.Done }) if (-not $pending.Count -or $Context.Once -or $clock.Elapsed.TotalSeconds -ge $timeout) { break } $seconds=[Math]::Min([Math]::Max(1,([double]$Context.IntervalMinutes*60)),[Math]::Max(0,($timeout-$clock.Elapsed.TotalSeconds))) @@ -1651,7 +1750,16 @@ function Invoke-PraCloudPhase { if ($seconds -gt 0) { Start-Sleep -Milliseconds ([int][Math]::Min(2147483647,($seconds*1000))) } } while ($true) $preview=(-not $Context.AllowMutation -and (Test-PraOrdinalIn $Context.Action @('Convert','Recover'))) - if ($null -ne $stopRun) { + if ($graphStop) { + foreach ($s in @($states | Where-Object { -not $_.Done -and $_.CoreDone })) { Complete-PraX500Check -Context $Context -State $s } + $unfinished=@($states | Where-Object { -not $_.Done }) + foreach ($s in $unfinished) { + $s.Row.CloudStatus='Pending'; $s.Row.FinalStatus='Pending' + $s.Row.Detail=([string]$s.Row.Detail+' | not finished: Microsoft Graph refused the read, see the error above').Trim(' ','|') + } + $null=Write-PraLog -Context $Context -Message ('Microsoft Graph refused a read: {0} object(s) were not finished and nothing more is asked of Microsoft Graph in this run' -f $unfinished.Count) -Level Detail + } + elseif ($null -ne $stopRun) { foreach ($s in @($states | Where-Object { -not $_.Done -and $_.CoreDone })) { Complete-PraX500Check -Context $Context -State $s } $unfinished=@($states | Where-Object { -not $_.Done }) foreach ($s in $unfinished) { @@ -1679,12 +1787,10 @@ function Invoke-PraCloudPhase { } } } } catch { - $failure=$_ - foreach ($row in $Rows) { Write-PraCloudFailure -Context $Context -Row $row -ErrorRecord $failure -Upn ([string](Get-PraValue $row 'UserPrincipalName' '')) } - if ($Rows.Count -eq 0) { Write-PraCloudFailure -Context $Context -Row $null -ErrorRecord $failure } + Write-PraUnfinishedFailure -Context $Context -Rows $Rows -ErrorRecord $_ -What 'finished' } finally { try { Close-PraCloudSession $Context } - catch { foreach ($row in $Rows) { Write-PraCloudError -Context $Context -Row $row -Message ('Cloud sign-out failed: '+$_.Exception.Message) -RunError } } + catch { Write-PraSignOutWarning -Context $Context -Message ([string]$_.Exception.Message) } } } @@ -1695,7 +1801,7 @@ function Invoke-PraRetentionCheck { #> [CmdletBinding()] param([Parameter(Mandatory)][hashtable]$Context,[Parameter(Mandatory)][AllowEmptyCollection()][object[]]$Rows) - $Context.CurrentPhase='Retention'; $Context.CurrentOperation='Prepare'; $Context.CurrentIdentity=''; $Context.CloudConnectFailed=$false; $Context.NetworkFailure=$false + $Context.CurrentPhase='Retention'; $Context.CurrentOperation='Prepare'; $Context.CurrentIdentity=''; $Context.CloudConnectFailed=$false; $Context.NetworkFailure=$false; $Context.GraphRefused=$false try { if ($Rows.Count -eq 0) { return } $cfg=Get-PraValue $Context.Config 'Retention' @{}; $raw=[string](Get-PraValue $cfg 'PolicyGuid' '') @@ -1730,7 +1836,7 @@ function Invoke-PraRetentionCheck { foreach ($id in $newIds) { Disconnect-ExchangeOnline -ConnectionId $id -Confirm:$false -ErrorAction Stop 6>$null | Out-Null } } } - $stopRun=$null + $stopRun=$null; $graphStop=$false foreach ($row in $Rows) { Add-Member -InputObject $row -NotePropertyName DeprovisionConfirmed -NotePropertyValue $false -Force $Context.CurrentOperation='VerifyRetention'; $Context.CurrentIdentity=[string](Get-PraValue $row 'ObjectGuid' '') @@ -1738,10 +1844,18 @@ function Invoke-PraRetentionCheck { try { $holdUpn=[string](Get-PraValue $row 'UserPrincipalName' '') # An inactive mailbox has no account in Microsoft Entra ID any more: it is found by UPN only. An account that exists must be the synchronised one. - if ((Test-PraIdentityCheck $Context) -and (Test-PraOrdinalEqual (Confirm-PraCloudIdentity -Context $Context -State @{ Row=$row; Upn=$holdUpn; Requests=@(); PlainText='' }) 'Failed')) { continue } - $holdSource=Get-PraValue $row 'BackupRec' $null; if ($null -eq $holdSource) { $holdSource=$row } - $h=Invoke-PraExo -Context $Context -Operation 'Hold' -Params @{ Upn=$holdUpn; Anchors=[string[]]@((Get-PraSourceAnchor -Record $holdSource).Candidates) } + if ((Test-PraIdentityCheck $Context) -and (Test-PraOrdinalEqual (Confirm-PraCloudIdentity -Context $Context -State @{ Row=$row; Upn=$holdUpn; Requests=@(); PlainText='' }) 'Failed')) { + if ([bool](Get-PraValue $Context 'GraphRefused' $false)) { $graphStop=$true; break } + continue + } + $h=Invoke-PraExo -Context $Context -Operation 'Hold' -Params @{ Upn=$holdUpn } $row.CloudMailbox=[bool](Get-PraValue $h 'Found' $false) + if ([bool](Get-PraValue $h 'EarlierAccount' $false)) { + $note=('{0}: not this object''s mailbox. Exchange Online has an inactive mailbox with this UPN, but it belongs to an earlier account (another ExternalDirectoryObjectId than the account confirmed for this object), so its retention does not count for this object. To see it, run: Get-EXOMailbox -InactiveMailboxOnly -Filter "UserPrincipalName -eq ''{1}''" -Properties ExternalDirectoryObjectId,WhenSoftDeleted | Format-List Name,ExternalDirectoryObjectId,WhenSoftDeleted' -f $holdUpn, $holdUpn.Replace("'","''")) + Write-PraItem -Context $Context -Status Warn -Text $note + $row.Warnings=([string](Get-PraValue $row 'Warnings' '') + '; ' + $note).Trim(' ',';') + throw ('Not covered by the policy: the only inactive mailbox with this UPN is not this object''s mailbox (it belongs to an earlier account). Retention: Found=False; EarlierAccount=True') + } if ([bool](Get-PraValue $h 'IdentityByUpn' $false)) { $note=('{0}: the inactive mailbox is found by its UPN only: its account is deleted, so it cannot be confirmed against Active Directory. Check that it is the mailbox of this object.' -f $holdUpn) Write-PraItem -Context $Context -Status Warn -Text $note @@ -1769,22 +1883,32 @@ function Invoke-PraRetentionCheck { $failure=$_ # The retry time of the run is used up: ONE error for the run, the rows not checked stay Pending (never one error per row). if ((Get-PraRetryState $Context).RunExhausted) { $stopRun=$failure; break } + if ($failure.Exception.Data['PraGraph'] -eq $true) { + $refusal=Get-PraGraphRefusal -ErrorRecord $failure -Upn ([string](Get-PraValue $row 'UserPrincipalName' '')) + if ($null -ne $refusal) { + Write-PraCloudError -Context $Context -Row $row -Message $refusal.Message -Technical $refusal.Technical -RunError + $Context.GraphRefused=$true; $graphStop=$true; break + } + } Write-PraCloudFailure -Context $Context -Row $row -ErrorRecord $failure -Upn ([string](Get-PraValue $row 'UserPrincipalName' '')) -Expectation } } - if ($null -ne $stopRun) { + if ($graphStop) { + $notChecked=@($Rows | Where-Object { -not (Test-PraOrdinalIn ([string](Get-PraValue $_ 'CloudStatus' '')) @('Success','Error')) }) + foreach ($row in $notChecked) { $row.CloudStatus='Pending'; $row.FinalStatus='Pending'; $row.Detail=([string](Get-PraValue $row 'Detail' '')+' | not checked: Microsoft Graph refused the read, see the error above').Trim(' ','|') } + $null=Write-PraLog -Context $Context -Message ('Microsoft Graph refused a read: {0} object(s) were not checked and nothing more is asked of Microsoft Graph in this run' -f $notChecked.Count) -Level Detail + } + elseif ($null -ne $stopRun) { $notChecked=@($Rows | Where-Object { -not (Test-PraOrdinalIn ([string](Get-PraValue $_ 'CloudStatus' '')) @('Success','Error')) }) foreach ($row in $notChecked) { $row.CloudStatus='Pending'; $row.FinalStatus='Pending'; $row.Detail=([string](Get-PraValue $row 'Detail' '')+' | not checked: the retry time of the run is used up').Trim(' ','|') } $Context.CurrentIdentity=''; $Context.CurrentOperation='VerifyRetention' Write-PraCloudError -Context $Context -Row $null -Message ('{0} {1} object(s) were not checked.' -f $stopRun.Exception.Message, $notChecked.Count) -Technical $(if ($null -ne $stopRun.Exception.InnerException) { [string]$stopRun.Exception.InnerException.Message } else { '' }) } } catch { - $failure=$_ - foreach ($row in $Rows) { Write-PraCloudFailure -Context $Context -Row $row -ErrorRecord $failure -Upn ([string](Get-PraValue $row 'UserPrincipalName' '')) } - if ($Rows.Count -eq 0) { Write-PraCloudFailure -Context $Context -Row $null -ErrorRecord $failure } + Write-PraUnfinishedFailure -Context $Context -Rows $Rows -ErrorRecord $_ -What 'checked' } finally { try { Close-PraCloudSession $Context } - catch { foreach ($row in $Rows) { Write-PraCloudError -Context $Context -Row $row -Message ('Sign-out after the retention check failed: '+$_.Exception.Message) -RunError } } + catch { Write-PraSignOutWarning -Context $Context -Message ([string]$_.Exception.Message) } } } diff --git a/package/module/PRA.Common.psm1 b/package/module/PRA.Common.psm1 index c933008..81dba82 100644 --- a/package/module/PRA.Common.psm1 +++ b/package/module/PRA.Common.psm1 @@ -656,12 +656,17 @@ function Write-PraProgress { } function Write-PraLogFile { - <# Appends one line to the log file. A log that cannot be written stops the run (audit). #> + <# Appends one line (or, with -Lines, a block of lines in one write) to the log file. A log that cannot be written stops the run (audit). #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWriteHost','',Justification='Last-resort console message when the log is broken.')] - param([Parameter(Mandatory)][hashtable]$Context, [Parameter(Mandatory)][string]$Level, [AllowEmptyString()][string]$Message) + param([Parameter(Mandatory)][hashtable]$Context, [Parameter(Mandatory)][string]$Level, [AllowEmptyString()][string]$Message, [string[]]$Lines) if (-not $Context.LogFile) { return } - $line = '{0} [{1,-6}] {2}' -f (Get-Date).ToString('yyyy-MM-dd HH:mm:ss.fff'), $Level, ($Message -replace '[\r\n]+', ' | ') - try { [IO.File]::AppendAllText($Context.LogFile, $line + "`r`n", (New-Object Text.UTF8Encoding($false))) } + if ($PSBoundParameters.ContainsKey('Lines')) { + $block = New-Object Text.StringBuilder + foreach ($entry in $Lines) { [void]$block.Append(('{0} [{1,-6}] {2}' -f (Get-Date).ToString('yyyy-MM-dd HH:mm:ss.fff'), $Level, ($entry -replace '[\r\n]+', ' | '))).Append("`r`n") } + $text = $block.ToString() + } + else { $text = ('{0} [{1,-6}] {2}' -f (Get-Date).ToString('yyyy-MM-dd HH:mm:ss.fff'), $Level, ($Message -replace '[\r\n]+', ' | ')) + "`r`n" } + try { [IO.File]::AppendAllText($Context.LogFile, $text, (New-Object Text.UTF8Encoding($false))) } catch { $failure = 'The log file cannot be written: {0}' -f $_.Exception.Message Add-PraIssue $Context $failure 'Log' @@ -683,18 +688,27 @@ function Write-PraLog { Detail log only (full values, technical traces) Debug log only; also on the console with -Verbose Step log only (step headers are drawn by Write-PraStep) + .PARAMETER Lines + Several Detail lines written to the log in one write (the lines of one object, for example). Detail only. .PARAMETER ForegroundColor Console colour of the text (presentation only: it never changes the level or the counters). #> - [CmdletBinding()] - param([Parameter(Mandatory)][hashtable]$Context, [Parameter(Mandatory)][AllowEmptyString()][string]$Message, - [ValidateSet('Info','Sub','Success','Warning','Error','Debug','Step','Detail')][string]$Level = 'Info', + [CmdletBinding(DefaultParameterSetName = 'One')] + param([Parameter(Mandatory, Position = 0)][hashtable]$Context, [Parameter(Mandatory, Position = 1, ParameterSetName = 'One')][AllowEmptyString()][string]$Message, + [Parameter(Mandatory, ParameterSetName = 'Block')][AllowEmptyString()][string[]]$Lines, + [Parameter(Position = 2)][ValidateSet('Info','Sub','Success','Warning','Error','Debug','Step','Detail')][string]$Level = 'Info', [ConsoleColor]$ForegroundColor) + if ([string]::Equals($PSCmdlet.ParameterSetName, 'Block', [StringComparison]::Ordinal)) { + if (-not (Test-PraOrdinalIgnoreCaseEqual $Level 'Detail')) { throw 'Write-PraLog -Lines is for the Detail level only.' } + Write-PraLogFile -Context $Context -Level 'DETAIL' -Lines $Lines + return + } $logLevel = @{ Info='INFO'; Sub='INFO'; Success='OK'; Warning='WARN'; Error='ERROR'; Debug='DEBUG'; Step='STEP'; Detail='DETAIL' }[$Level] if ((Test-PraOrdinalIgnoreCaseEqual $Level 'Warning')) { $Context.Warnings = [int](Get-PraValue $Context 'Warnings' 0) + 1; Add-PraWarning $Context $Message } if ((Test-PraOrdinalIgnoreCaseEqual $Level 'Error')) { Add-PraIssue $Context $Message } Write-PraLogFile -Context $Context -Level $logLevel -Message $Message - $text = (ConvertTo-PraPlainMessage $Message) -replace '[\r\n]+', ' | ' + # The Detail and Step levels go to the log only: their plain text is not needed. + $text = if ((Test-PraOrdinalIgnoreCaseEqual $Level 'Detail') -or (Test-PraOrdinalIgnoreCaseEqual $Level 'Step')) { '' } else { (ConvertTo-PraPlainMessage $Message) -replace '[\r\n]+', ' | ' } switch ($Level) { 'Debug' { $verbose = [bool](Get-PraValue $Context 'VerboseEnabled' ((Test-PraOrdinalIgnoreCaseEqual $VerbosePreference 'Continue'))) @@ -2593,7 +2607,8 @@ function New-PraEffectiveConfiguration { # small machine-readable file (PhaseData-*.json + .sha256) in the batch folder it creates; the file travels in the transfer package with the batch # (listed in transfer.json with its SHA-256 like every entry, so a changed file is refused at import). It is DATA FOR A REPORT: nothing in the engine # decides anything from it. It is read as untrusted input (size, schema, checksum, Environment) and every value is HTML-encoded when it is shown. -$script:PraPhaseLimits = @{ MaxBytes = [long]268435456; MaxText = 2000; MaxStepText = 300; MaxStepsPerObject = 40; MaxJourney = 1000000; MaxObjects = 200000; MaxFiles = 24; MaxIssues = 10000; DetailedObjects = 10000 } +# MaxFileBytes: the largest PhaseData file (the writer drops the steps above it, the reader refuses a larger file); MaxBytes: all the files read for one report together. +$script:PraPhaseLimits = @{ MaxBytes = [long]268435456; MaxFileBytes = [long]67108864; MaxText = 2000; MaxStepText = 300; MaxStepsPerObject = 40; MaxJourney = 1000000; MaxObjects = 200000; MaxFiles = 24; MaxIssues = 10000; DetailedObjects = 10000 } $script:PraPhaseFilter = 'PhaseData-*.json' $script:PraNotAvailable = 'not available (folder from an older version or copied manually)' # Display only: a Pending phase (or stage) that a later phase of the same report took over is shown as handed over; the verdict logic reads the raw status. @@ -2731,9 +2746,12 @@ function Save-PraPhaseData { param([Parameter(Mandatory)][hashtable]$Context, [Parameter(Mandatory)][string]$Folder, [string]$HandOff = '') if (-not [IO.Directory]::Exists($Folder)) { throw "Phase data: folder not found: $Folder" } $json = (New-PraPhaseRecord -Context $Context -HandOff $HandOff) | ConvertTo-Json -Depth 8 -Compress - if ($json.Length -gt $script:PraPhaseLimits.MaxBytes / 4) { $json = (New-PraPhaseRecord -Context $Context -HandOff $HandOff -NoSteps) | ConvertTo-Json -Depth 8 -Compress } $bytes = (New-Object Text.UTF8Encoding($false)).GetBytes($json) - if ($bytes.LongLength -gt $script:PraPhaseLimits.MaxBytes) { throw 'Phase data: the file would be larger than the limit.' } + if ($bytes.LongLength -gt $script:PraPhaseLimits.MaxFileBytes) { + $json = (New-PraPhaseRecord -Context $Context -HandOff $HandOff -NoSteps) | ConvertTo-Json -Depth 8 -Compress + $bytes = (New-Object Text.UTF8Encoding($false)).GetBytes($json) + } + if ($bytes.LongLength -gt $script:PraPhaseLimits.MaxFileBytes) { throw 'Phase data: the file would be larger than the limit.' } $runId = [string](Get-PraValue $Context 'RunId' '') $short = ($runId -replace '\A[^-]*-', '' -replace '[^0-9A-Za-z]', '') if ($short.Length -gt 8) { $short = $short.Substring(0, 8) } @@ -2784,7 +2802,7 @@ function Read-PraPhaseData { $phases = New-Object 'Collections.Generic.List[object]' $problems = New-Object 'Collections.Generic.List[string]' $seen = New-Object 'Collections.Generic.HashSet[string]' -ArgumentList ([StringComparer]::Ordinal) - $total = 0 + $total = 0; $budget = [long]0 foreach ($directory in @($Folder | Where-Object { $_ } | Get-PraOrdinalUnique -IgnoreCase)) { if (-not [IO.Directory]::Exists($directory)) { continue } $files = [string[]][IO.Directory]::GetFiles($directory, $script:PraPhaseFilter) @@ -2795,7 +2813,11 @@ function Read-PraPhaseData { if ($total -gt $limits.MaxFiles) { $problems.Add('Phase data: too many files, the rest is ignored.'); break } try { $length = ([IO.FileInfo]$file).Length - if ($length -lt 2 -or $length -gt $limits.MaxBytes) { throw 'the size is not acceptable' } + if ($length -lt 2 -or $length -gt $limits.MaxFileBytes) { throw ('the size is not acceptable (at most {0} MB for one file)' -f [long]($limits.MaxFileBytes / 1MB)) } + if (($budget + $length) -gt $limits.MaxBytes) { + throw ('not read: the files read before it already use {0} MB of the {1} MB allowed for one report. Move the PhaseData files of other batches out of the batch folder (a batch folder holds only the files of its own batch), then run again' -f [long]($budget / 1MB), [long]($limits.MaxBytes / 1MB)) + } + $budget += $length $sidecar = $file + '.sha256' if (-not [IO.File]::Exists($sidecar)) { throw 'the .sha256 file is missing' } $stream = New-Object IO.FileStream($file, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::Read) diff --git a/package/module/PRA.Directory.psm1 b/package/module/PRA.Directory.psm1 index 25206a9..192468f 100644 --- a/package/module/PRA.Directory.psm1 +++ b/package/module/PRA.Directory.psm1 @@ -77,8 +77,13 @@ function Write-PraMemoryStage { <# Log only: stage of a backup and private memory of the process (large batches). #> [CmdletBinding()] param([hashtable]$Context, [string]$Stage, [string]$Identity = '', [string]$Detail = '') - $process = [Diagnostics.Process]::GetCurrentProcess() - try { $privateMiB = [math]::Round(($process.PrivateMemorySize64 / 1MB), 1) } finally { $process.Dispose() } + # The memory of the process is read once a second at most (the read takes milliseconds and the trace is called for every object). + if ($null -eq $script:MemoryClock -or $script:MemoryClock.ElapsedMilliseconds -ge 1000) { + $process = [Diagnostics.Process]::GetCurrentProcess() + try { $script:MemoryText = [math]::Round(($process.PrivateMemorySize64 / 1MB), 1).ToString([Globalization.CultureInfo]::InvariantCulture) } finally { $process.Dispose() } + $script:MemoryClock = [Diagnostics.Stopwatch]::StartNew() + } + $privateMiB = $script:MemoryText Write-PraLog -Context $Context -Message ("BACKUP/AD | $Stage | GUID=$Identity | $Detail | PrivateMiB=$privateMiB | Process64Bit=$([Environment]::Is64BitProcess)") -Level Debug } @@ -188,6 +193,12 @@ function Write-PraDataFingerprint { $writer.Write($State.Bytes, 0, ($count * 2)) } } + elseif ($child -is [bool]) { + if ($Depth -ge 64) { throw 'Receipt data too deep or cyclic.' } + $State.Nodes++ + if ($State.Nodes -gt 10000000) { throw 'Receipt data too large.' } + $writer.Write([byte]2); $writer.Write([bool]$child) + } else { Write-PraDataFingerprint -State $State -Value $child -Depth ($Depth + 1) } } return @@ -215,6 +226,12 @@ function Get-PraDataFingerprint { # every record and the SHA-256 of the files. $script:ReceiptFileHashEvery = 200 +# The members of the licence group are read once and shared by the objects of a run for this many seconds (Get-PraGroupMemberSet). +$script:GroupMemberSeconds = 30 +$script:LogEscape = [regex]::new('[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\\"]') +$script:MemoryClock = $null +$script:MemoryText = '' + function Get-PraFileStamp { <# Length and last write time (UTC ticks) of a file, as text; 'missing' when it is not there. #> [CmdletBinding()] @@ -283,9 +300,11 @@ function Assert-PraReceiptIntegrity { .DESCRIPTION -Full: the fingerprint of every record and the SHA-256 of the three files. Without it: the fields of the receipt, the record of -ObjectGuid, and the length and last write time of the three files; the SHA-256 of the files is computed again after every ReceiptFileHashEvery checks of that kind. + -WithoutRecord (with an object): the same, but the record of the object is only looked for, not fingerprinted: for a check that is followed by another one, made + after the operator approved the write, which does fingerprint it. #> [CmdletBinding()] - param([hashtable]$Context, $Entry, [string]$ObjectGuid = '', [switch]$Full) + param([hashtable]$Context, $Entry, [string]$ObjectGuid = '', [switch]$Full, [switch]$WithoutRecord) $receipt = $Entry.Receipt if (-not (Test-PraOrdinalIgnoreCaseEqual $Entry.Environment $Context.Config.Environment) -or -not (Test-PraOrdinalIgnoreCaseEqual $receipt.Path $Entry.Path) -or -not (Test-PraOrdinalIgnoreCaseEqual $receipt.Data.Environment $Entry.Environment) -or -not (Test-PraOrdinalEqual $receipt.Data.Operation $Entry.Operation) -or @@ -311,7 +330,7 @@ function Assert-PraReceiptIntegrity { if (-not $Entry.Positions.TryGetValue($ObjectGuid, [ref]$position)) { throw "Object not covered by the validated backup: $ObjectGuid" } $record = $Entry.RecordsArray[$position] if (-not [object]::ReferenceEquals($record, $Entry.RecordRefs[$position]) -or - -not (Test-PraOrdinalEqual (Get-PraDataFingerprint -Data $record) $Entry.Fingerprints[$ObjectGuid])) { throw $memoryChanged } + (-not $WithoutRecord -and -not (Test-PraOrdinalEqual (Get-PraDataFingerprint -Data $record) $Entry.Fingerprints[$ObjectGuid]))) { throw $memoryChanged } } $hashFiles = $Full -or -not $ObjectGuid -or (++$Entry.ChecksSinceFileHash -ge $script:ReceiptFileHashEvery) if ($hashFiles) { @@ -573,6 +592,32 @@ function Get-PraGroup { return $groups[0] } +function Get-PraGroupMemberSet { + <# + .SYNOPSIS + The licence group and the set of its members, read once and kept for a short time instead of being read again for every object. + .DESCRIPTION + A group of thousands of members is a read of hundreds of kilobytes. The plan of an object and the check before the final restore only need to know whether the object + was in the group a moment ago, so the read is shared by the objects of a run: it is read again when it is older than the keeping time or after any write to a group + by this run. The check that comes with every write is not served from here: it reads the memberOf attribute of the object itself (Assert-PraCurrentState). + .OUTPUTS + An object with Group (the group, as Get-PraGroup returns it) and Members (a case-insensitive set of distinguished names). + #> + [CmdletBinding()] + param([hashtable]$Context, [Parameter(Mandatory)][string]$Identity) + $generation = [int](Get-PraValue $Context 'PraGroupGeneration' 0) + if (-not $Context.ContainsKey('PraGroupMembers')) { $Context['PraGroupMembers'] = New-Object 'Collections.Generic.Dictionary[string,object]' ([StringComparer]::OrdinalIgnoreCase) } + $cache = $Context['PraGroupMembers'] + $entry = $null + if ($cache.TryGetValue($Identity, [ref]$entry) -and [int]$entry.Generation -eq [int]$generation -and $entry.Clock.Elapsed.TotalSeconds -lt $script:GroupMemberSeconds) { return $entry } + $group = Get-PraGroup $Context $Identity + $members = New-Object 'Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase) + foreach ($member in @($group.member)) { [void]$members.Add([string]$member) } + $entry = [pscustomobject]@{ Group = $group; Members = $members; Generation = $generation; Clock = [Diagnostics.Stopwatch]::StartNew() } + $cache[$Identity] = $entry + return $entry +} + function Resolve-PraGroup { <# .SYNOPSIS @@ -706,22 +751,32 @@ function Get-PraJournalTouchedObject { <# .SYNOPSIS The objects (GUIDs, ignoring the case) that the journal of a batch shows as written or about to be written: a Started or Applied line of an AD write. - An object that has such a line may be changed, whatever the batch proved. A missing or unreadable journal gives an empty set. A line that cannot be parsed is skipped, - the others are still read; with -Context ONE warning says how many were skipped. + An object that has such a line may be changed, whatever the batch proved. A missing or unreadable journal gives an empty set. A line that cannot be read (not JSON, + cut short, or without its Operation, Status and Target) is skipped, the others are still read; with -Context ONE warning says how many were skipped, and -SkippedCount + receives that number. #> [CmdletBinding()] - param([string]$Path, [hashtable]$Context) + param([string]$Path, [hashtable]$Context, [ref]$SkippedCount) $set = New-Object 'Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase) + if ($null -ne $SkippedCount) { $SkippedCount.Value = 0 } if (-not $Path -or -not [IO.File]::Exists($Path)) { return , $set } $skipped = 0 try { foreach ($line in [IO.File]::ReadLines($Path)) { - if ($line.Trim().Length -and -not $line.TrimStart().StartsWith('{', [StringComparison]::Ordinal)) { $skipped++; continue } - if (-not ($line.Contains('"Status":"Started"') -or $line.Contains('"Status":"Applied"'))) { continue } + $text = $line.Trim() + if (-not $text.Length) { continue } + if (-not $text.StartsWith('{', [StringComparison]::Ordinal)) { $skipped++; continue } + if (-not ($line.Contains('"Status":"Started"') -or $line.Contains('"Status":"Applied"'))) { + # A line that is not a write is not parsed (the journal can be large): only its shape is checked. + if (-not $text.EndsWith('}', [StringComparison]::Ordinal) -or -not $text.Contains('"Operation":') -or -not $text.Contains('"Status":') -or -not $text.Contains('"Target":')) { $skipped++ } + continue + } try { $entry = $line | ConvertFrom-PraJson - if (Test-PraOrdinalIn ([string](Get-PraValue $entry 'Operation' '')) @('Set-ADUser', 'Add-ADGroupMember', 'Remove-ADGroupMember')) { - $target = [string](Get-PraValue $entry 'Target' '') + $operation = Get-PraValue $entry 'Operation' $null; $target = Get-PraValue $entry 'Target' $null + if ($null -eq $operation -or $null -eq $target -or $null -eq (Get-PraValue $entry 'Status' $null)) { $skipped++; continue } + if (Test-PraOrdinalIn ([string]$operation) @('Set-ADUser', 'Add-ADGroupMember', 'Remove-ADGroupMember')) { + $target = [string]$target if ($target -and -not (Test-PraOrdinalEqual $target '*')) { [void]$set.Add($target) } } } @@ -729,7 +784,13 @@ function Get-PraJournalTouchedObject { } } catch { $null = $_ } - if ($skipped -and $null -ne $Context) { Write-PraItem -Context $Context -Status Warn -Text ('{0} line(s) of the journal {1} cannot be read and were skipped: an object that only they name is not listed as written.' -f $skipped, (Split-Path $Path -Leaf)) } + if ($null -ne $SkippedCount) { $SkippedCount.Value = $skipped } + if ($skipped -and $null -ne $Context) { + $batchId = [regex]::Match((Split-Path $Path -Leaf), '^Journal-(?[0-9a-fA-F]{8})[0-9a-fA-F]{24}\.jsonl\z').Groups['id'].Value + $hook = Get-PraValue $Context 'CommandLineFor' $null + $command = if ($hook -is [scriptblock] -and $batchId) { ([string](& $hook 'Recover' '' $batchId)) -replace ' -Mode Apply', '' } else { '.\Invoke-PraRemoteMailbox.ps1 -Action Recover -Batch ' + $(if ($batchId) { $batchId } else { '' }) } + Write-PraItem -Context $Context -Status Warn -Text ('{0} line(s) of the journal {1} cannot be read and were skipped: an object that only they name is not listed as written. If an object may have been converted by this batch, roll it back on its own with its Preview first: {2} -Identity , then the same command with -Mode Apply. Or restore it by hand from the backup file of the batch.' -f $skipped, (Split-Path $Path -Leaf), $command) + } return , $set } @@ -740,7 +801,7 @@ function Find-PraRecoverOfBatch { .DESCRIPTION First the State files (the AD proof of a Recover): the one that names the Convert backup (SourceBackupHash) and lists at least one of the objects given (any object when none is given). Then the Recover backups that have no State file (a Recover that stopped before its proof): the objects that its journal - shows as written or about to be written count as rolled back; a journal that is missing counts for every object. Basis says which: State, Journal or Unknown. + shows as written or about to be written count as rolled back; a journal that is missing, or that has a line which cannot be read, counts for every object. Basis says which: State, Journal, Damaged or Unknown. A batch of another Environment is ignored. #> [CmdletBinding()] @@ -783,8 +844,11 @@ function Find-PraRecoverOfBatch { $basis = 'Journal' if (-not [IO.File]::Exists($journal)) { $basis = 'Unknown' } else { - $touched = Get-PraJournalTouchedObject -Path $journal - if ($ObjectGuid.Count) { + $damaged = 0 + $touched = Get-PraJournalTouchedObject -Path $journal -SkippedCount ([ref]$damaged) + # A journal with a line that cannot be read may hide a write: every object counts as rolled back (the caller refuses, never guesses). + if ($damaged -gt 0) { $basis = 'Damaged' } + elseif ($ObjectGuid.Count) { $anyTouched = $false foreach ($wantedGuid in $ObjectGuid) { if ($touched.Contains($wantedGuid)) { $anyTouched = $true; break } } if (-not $anyTouched) { continue } @@ -1059,7 +1123,9 @@ function ConvertTo-PraLogText { <# Escapes control characters, quotes and backslashes of an AD value (the value is never cut). #> [CmdletBinding()] param([AllowEmptyString()][string]$Value) - return [regex]::Replace($Value, '[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\\"]', [Text.RegularExpressions.MatchEvaluator]{ + # Most values have nothing to escape: the test is one match, and the replacement (a delegate made for each call) is only built for the others. + if (-not $script:LogEscape.IsMatch($Value)) { return $Value } + return $script:LogEscape.Replace($Value, [Text.RegularExpressions.MatchEvaluator]{ param($match) # On the character CODE, never on the string (ICU string comparison ignores control characters: U+0001 -eq U+0008). $code = [int][char]$match.Value[0] @@ -1147,16 +1213,18 @@ function Write-PraAdDelta { $afterLabel = if ((Test-PraOrdinalIgnoreCaseEqual $Stage 'Verified')) { 'VERIFIED' } else { 'PLANNED' } $heading = if ((Test-PraOrdinalIgnoreCaseEqual $Stage 'Verified')) { 'AD VERIFIED' } else { 'AD PLAN - planned values, not applied' } $record = $Plan.Record - Write-PraLog -Context $Context -Message ("$heading | $(ConvertTo-PraLogText -Value $record.SamAccountName) | $($Plan.Operation) | Mode=$($Context.Mode) | GUID=$($record.ObjectGuid)") -Level Detail + # The log lines of the object (every attribute with its values) are written in one go. + $logLines = New-Object 'Collections.Generic.List[string]' + $logLines.Add("$heading | $(ConvertTo-PraLogText -Value $record.SamAccountName) | $($Plan.Operation) | Mode=$($Context.Mode) | GUID=$($record.ObjectGuid)") $palette = @{ ADD='Green'; CHANGE='Yellow'; REMOVE='Red'; UNCHANGED='DarkGray' } $consoleLines = New-Object 'Collections.Generic.List[object]' $unchanged = 0 foreach ($name in $Plan.Kinds.Keys) { $before = $record.Attributes[$name]; $after = $Plan.Desired[$name] $change = if (Test-PraStateEqual -Left $before -Right $after) { 'UNCHANGED' } elseif (-not $before.Present) { 'ADD' } elseif (-not $after.Present) { 'REMOVE' } else { 'CHANGE' } - Write-PraLog -Context $Context -Message "ATTRIBUTE | $name | $change | Type=$($Plan.Kinds[$name])" -Level Detail - foreach ($value in @(Format-PraAttributeValue -State $before)) { Write-PraLog -Context $Context -Message " $name | BEFORE : $value" -Level Detail } - foreach ($value in @(Format-PraAttributeValue -State $after)) { Write-PraLog -Context $Context -Message " $name | $afterLabel : $value" -Level Detail } + $logLines.Add("ATTRIBUTE | $name | $change | Type=$($Plan.Kinds[$name])") + foreach ($value in @(Format-PraAttributeValue -State $before)) { $logLines.Add(" $name | BEFORE : $value") } + foreach ($value in @(Format-PraAttributeValue -State $after)) { $logLines.Add(" $name | $afterLabel : $value") } if ((Test-PraOrdinalIgnoreCaseEqual $change 'UNCHANGED')) { $unchanged++; continue } if ((Test-PraOrdinalIgnoreCaseEqual ($Plan.Kinds[$name]) 'MultiString') -and $before.Present -and $after.Present) { $old = @($before.Value); $new = @($after.Value) @@ -1170,15 +1238,16 @@ function Write-PraAdDelta { $change = if ((Test-PraOrdinalIgnoreCaseEqual $group.WasMember $group.DesiredMember)) { 'UNCHANGED' } elseif ($group.DesiredMember) { 'ADD' } else { 'REMOVE' } $beforeText = if ($group.WasMember) { 'Member' } else { 'Not member' } $afterText = if ($group.DesiredMember) { 'Member' } else { 'Not member' } - Write-PraLog -Context $Context -Message "LICENCE GROUP | $(ConvertTo-PraLogText -Value $group.GroupDN) | $change" -Level Detail - Write-PraLog -Context $Context -Message " Licence group | BEFORE : $beforeText" -Level Detail - Write-PraLog -Context $Context -Message " Licence group | $afterLabel : $afterText" -Level Detail + $logLines.Add("LICENCE GROUP | $(ConvertTo-PraLogText -Value $group.GroupDN) | $change") + $logLines.Add(" Licence group | BEFORE : $beforeText") + $logLines.Add(" Licence group | $afterLabel : $afterText") if ((-not (Test-PraOrdinalIgnoreCaseEqual $change 'UNCHANGED'))) { $groupName = (($group.GroupDN -split ',')[0] -replace '^CN=', '') $consoleLines.Add(@(('licence group ' + $groupName), ('{0} {1} {2}' -f $beforeText.ToLowerInvariant(), [char]0x2192, $afterText.ToLowerInvariant()), $palette[$change])) } } - else { Write-PraLog -Context $Context -Message 'LICENCE GROUP | not managed for this operation' -Level Detail } + else { $logLines.Add('LICENCE GROUP | not managed for this operation') } + Write-PraLog -Context $Context -Lines $logLines.ToArray() -Level Detail $shared = $record.SharedPermissions $permissionText = '' if ($record.IsShared -and (Test-PraOrdinalIgnoreCaseEqual $Plan.Operation 'Convert')) { @@ -1683,9 +1752,11 @@ function New-PraPlan { if ($tagEnabled) { $desired[$tagAttr] = @{ Present=$true; Kind='String'; Value=[string]$tag.Value } } if ($shared) { $permissions = Get-PraSharedPermission $Context $user } elseif ($config.Licensing.Enabled) { - $group = Get-PraGroup $Context $config.Licensing.GroupDN + # The group is read without its members: whether the object is in it comes from the memberOf attribute of the object, read just above. + $group = Get-PraGroup $Context $config.Licensing.GroupDN -WithoutMembers + $memberOf = Get-PraValue $user 'memberOf' @() $licensing.Enabled = $true; $licensing.GroupGuid = ([guid]$group.ObjectGUID).ToString(); $licensing.GroupDN = [string]$group.DistinguishedName - $licensing.WasMember = (Test-PraOrdinalIn -IgnoreCase ([string]$user.DistinguishedName) @($group.member)); $licensing.DesiredMember = $true + $licensing.WasMember = (Test-PraOrdinalIn -IgnoreCase ([string]$group.DistinguishedName) @($memberOf)); $licensing.DesiredMember = $true } } elseif ((Test-PraOrdinalIgnoreCaseEqual $Operation 'Deprovision')) { @@ -1722,9 +1793,10 @@ function New-PraPlan { } $sourceGroup = Get-PraValue $SourceRecord 'Licensing' $null if ($null -ne $sourceGroup -and $sourceGroup.Enabled) { - $group = Get-PraGroup $Context $sourceGroup.GroupGuid + $group = Get-PraGroup $Context ([string]$sourceGroup.GroupGuid) -WithoutMembers + $memberOf = Get-PraValue $user 'memberOf' @() $licensing.Enabled = $true; $licensing.GroupGuid = ([guid]$group.ObjectGUID).ToString(); $licensing.GroupDN = [string]$group.DistinguishedName - $licensing.WasMember = (Test-PraOrdinalIn -IgnoreCase ([string]$user.DistinguishedName) @($group.member)); $licensing.DesiredMember = [bool]$sourceGroup.WasMember + $licensing.WasMember = (Test-PraOrdinalIn -IgnoreCase ([string]$group.DistinguishedName) @($memberOf)); $licensing.DesiredMember = [bool]$sourceGroup.WasMember } elseif ([bool](Get-PraValue $SourceRecord 'AddedToLicenseGroup' $false)) { throw 'Old backup without the GUID of the licence group: removal refused (a group with the same DN may have been re-created). Have the backup migrated before restoring this batch.' @@ -1859,9 +1931,11 @@ function Import-PraBackup { .SYNOPSIS Reads and fully validates a backup (JSON, .sha256, CLIXML) and returns its receipt. Schema 3 (current), 2 and 1 (old versions, read with their restrictions) are accepted. + .PARAMETER ExpectedSnapshots + The captures in memory that the CLIXML file must hold exactly (the backup that has just been written): they are compared in the same pass that validates the file. #> [CmdletBinding()] - param([hashtable]$Context, [Parameter(Mandatory)][string]$Path) + param([hashtable]$Context, [Parameter(Mandatory)][string]$Path, [AllowEmptyCollection()][object[]]$ExpectedSnapshots) $pathResolved = (Get-Item -LiteralPath $Path -ErrorAction Stop).FullName $registry = Get-PraReceiptRegistry -Context $Context foreach ($entry in $registry) { @@ -1907,7 +1981,8 @@ function Import-PraBackup { $format = if ($version -eq 3) { [string]$data.RawFormat } else { '' } $Context.CurrentOperation = 'Validate-RawCapture' Write-PraMemoryStage -Context $Context -Stage 'RAW VALIDATE BEGIN' -Detail ("schema=$version objects=$($records.Count) file=$rawPath") - $null = Test-PraRawCapture -Context $Context -LiteralPath $rawPath -Records $records -RawFormat $format + if ($PSBoundParameters.ContainsKey('ExpectedSnapshots')) { $null = Test-PraRawCapture -Context $Context -LiteralPath $rawPath -Records $records -RawFormat $format -ExpectedSnapshots $ExpectedSnapshots } + else { $null = Test-PraRawCapture -Context $Context -LiteralPath $rawPath -Records $records -RawFormat $format } # A change during the read never yields a receipt for different content. if (-not (Test-PraOrdinalEqual (Get-PraHash -Path $rawPath) $rawHash)) { throw 'Backup CLIXML changed during its validation.' } Write-PraMemoryStage -Context $Context -Stage 'RAW VALIDATE END' -Detail ("bytes=$((Get-Item -LiteralPath $rawPath -ErrorAction Stop).Length)") @@ -2007,8 +2082,8 @@ function Save-PraBatch { $json = $null Write-PraImmutableFile ($path + '.sha256') (Get-PraHash $path) $Context.CurrentOperation = 'Validate-BackupAgainstPlan' - $null = Test-PraRawCapture -Context $Context -LiteralPath $rawPath -Records $data.Records -RawFormat $data.RawFormat -ExpectedSnapshots $snapshots - $receipt = Import-PraBackup $Context $path + # One pass over the CLIXML file validates it and compares it with the captures in memory. + $receipt = Import-PraBackup $Context $path -ExpectedSnapshots $snapshots # A valid JSON is not necessarily complete: compare it with the plans in memory. for ($i = 0; $i -lt $Plans.Count; $i++) { $record = $receipt.Data.Records[$i] @@ -2040,10 +2115,10 @@ function Assert-PraReceipt { without an object) the complete one. #> [CmdletBinding()] - param([hashtable]$Context, $Receipt, [string]$ObjectGuid = '', [switch]$Full) + param([hashtable]$Context, $Receipt, [string]$ObjectGuid = '', [switch]$Full, [switch]$WithoutRecord) $entry = Get-PraReceiptEntry -Context $Context -Receipt $Receipt if ($ObjectGuid -and -not $entry.Positions.ContainsKey($ObjectGuid)) { throw "Object not covered by the validated backup: $ObjectGuid" } - Assert-PraReceiptIntegrity -Context $Context -Entry $entry -ObjectGuid $ObjectGuid -Full:$Full + Assert-PraReceiptIntegrity -Context $Context -Entry $entry -ObjectGuid $ObjectGuid -Full:$Full -WithoutRecord:$WithoutRecord } function Assert-PraCurrentState { @@ -2059,9 +2134,11 @@ function Assert-PraCurrentState { if (-not (Test-PraStateEqual $Expected[$name] $actual[$name])) { throw "AD state differs from the expected state | GUID=$($Plan.Record.ObjectGuid) | attribute=$name | DC=$($Context.Server)" } } if ($Plan.Record.Licensing.Enabled) { - $group = Get-PraGroup $Context $Plan.Record.Licensing.GroupGuid + # The group itself is read again each time (its name and GUID), without its members; whether this object is in it comes from the memberOf attribute of the object just read. + $group = Get-PraGroup $Context $Plan.Record.Licensing.GroupGuid -WithoutMembers + $memberOf = Get-PraValue $user 'memberOf' @() if (-not (Test-PraOrdinalIgnoreCaseEqual $group.DistinguishedName $Plan.Record.Licensing.GroupDN) -or - (-not (Test-PraOrdinalIgnoreCaseEqual (Test-PraOrdinalIn -IgnoreCase ([string]$user.DistinguishedName) @($group.member)) $ExpectedMember))) { throw 'Licence group membership differs from the backup/plan.' } + (-not (Test-PraOrdinalIgnoreCaseEqual (Test-PraOrdinalIn -IgnoreCase ([string]$group.DistinguishedName) @($memberOf)) $ExpectedMember))) { throw 'Licence group membership differs from the backup/plan.' } } if ($AcceptNewVersion) { $Plan.ExpectedUsnChanged = $version } } @@ -2082,7 +2159,8 @@ function Invoke-PraAdWrite { if ([bool](Get-PraValue $Context 'OperationFailed' $false) -or $Context.Issues.Count -gt 0 -or (Test-PraOrdinalEqual ([string]$Plan.Row.FinalStatus) 'Error')) { throw 'Safety stop: no AD write after an error in this run.' } if (-not $Context.AllowMutation -or (-not (Test-PraOrdinalIgnoreCaseEqual $Context.Mode 'Apply')) -or (Test-PraOrdinalIgnoreCaseEqual $Context.Action 'Check') -or $WhatIfPreference) { throw 'Safety stop: AD writes are not allowed in this mode.' } if (-not $PSCmdlet.ShouldProcess($Plan.Record.ObjectGuid, $Operation)) { throw 'AD write not authorised (ShouldProcess).' } - Assert-PraReceipt $Context $Receipt $Plan.Record.ObjectGuid + # Before the approval the object is only looked for in the backup, and the files are checked: the record itself is fingerprinted by the check after the approval. + Assert-PraReceipt $Context $Receipt $Plan.Record.ObjectGuid -WithoutRecord if (-not (& $Context.Approval $Plan.Record.DistinguishedName $Operation)) { throw "Operation refused: $Operation. Batch stopped." } # An interactive confirmation can take time: the object and the backup are re-checked after it. $expected = if ((Test-PraOrdinalIgnoreCaseEqual $Operation 'Set-ADUser')) { $Plan.Record.Attributes } else { $Plan.Desired } @@ -2092,6 +2170,8 @@ function Invoke-PraAdWrite { $Plan.Row.LastOperation = $Operation; $Plan.Row.Detail += " | attempt=$Operation" Write-PraJournal $Context $Plan.Record.ObjectGuid $Operation 'Started' Write-PraLog -Context $Context -Message "AD WRITE BEGIN | $Operation | DC=$($Context.Server) | GUID=$($Plan.Record.ObjectGuid) | backup=$($Receipt.Path)" -Level Detail + # A write to a group makes the members read earlier by this run out of date. + if ($Operation.EndsWith('ADGroupMember', [StringComparison]::OrdinalIgnoreCase)) { $Context['PraGroupGeneration'] = [int](Get-PraValue $Context 'PraGroupGeneration' 0) + 1 } # Any exception goes up to Invoke-PraAdBatch: no next object, no sync. & $Write | Out-Null $Plan.Row.ADApplied = $true @@ -2167,7 +2247,7 @@ function Invoke-PraAdBatch { foreach ($plan in $Plans) { try { $before = $plan.Record.Attributes; $groupState = $plan.Record.Licensing - Assert-PraCurrentState $Context $plan $before $groupState.WasMember + # Every write re-reads the object first (Invoke-PraAdWrite), and the object is read again after the last one: no read of its own here. $replace = @{}; $clear = New-Object 'Collections.Generic.List[string]' foreach ($name in $plan.Kinds.Keys) { if (Test-PraStateEqual $before[$name] $plan.Desired[$name]) { continue } @@ -2182,8 +2262,6 @@ function Invoke-PraAdBatch { Write-PraJournal $Context $plan.Record.ObjectGuid 'Set-ADUser' 'Verified' } if ($groupState.Enabled -and (-not (Test-PraOrdinalIgnoreCaseEqual $groupState.WasMember $groupState.DesiredMember))) { - # Re-read before each new write: the group must not have changed. - Assert-PraCurrentState $Context $plan $plan.Desired $groupState.WasMember $parameters = @{ Identity=[guid]$groupState.GroupGuid; Members=[guid]$plan.Record.ObjectGuid; Server=$Context.Server; ErrorAction='Stop'; Confirm=$false } if ($groupState.DesiredMember) { Invoke-PraAdWrite $Context $receipt $plan 'Add-ADGroupMember' { Add-ADGroupMember @parameters }; $plan.Row.GroupAction = 'Added' } else { Invoke-PraAdWrite $Context $receipt $plan 'Remove-ADGroupMember' { Remove-ADGroupMember @parameters }; $plan.Row.GroupAction = 'Removed' } @@ -2400,9 +2478,9 @@ function Assert-PraFollowupState { $previous = Find-PraRecord $capturedIndex $planGuid if ($null -eq $verifiedRecord -or $null -eq $previous -or $verifiedIndex.Duplicates.Contains($planGuid) -or $capturedIndex.Duplicates.Contains($planGuid)) { throw 'Finalize: object not in the AD proof.' } if ($previous.Licensing.Enabled) { - $group = Get-PraGroup $Context $previous.Licensing.GroupGuid - if (-not (Test-PraOrdinalIgnoreCaseEqual $group.DistinguishedName $previous.Licensing.GroupDN) -or - (-not (Test-PraOrdinalIgnoreCaseEqual (Test-PraOrdinalIn -IgnoreCase ([string]$Plan.User.DistinguishedName) @($group.member)) ($previous.Licensing.DesiredMember)))) { throw 'Finalize: licence group membership differs from the AD proof.' } + $groupRead = Get-PraGroupMemberSet $Context ([string]$previous.Licensing.GroupGuid) + if (-not (Test-PraOrdinalIgnoreCaseEqual $groupRead.Group.DistinguishedName $previous.Licensing.GroupDN) -or + (-not (Test-PraOrdinalIgnoreCaseEqual $groupRead.Members.Contains([string]$Plan.User.DistinguishedName) ($previous.Licensing.DesiredMember)))) { throw 'Finalize: licence group membership differs from the AD proof.' } } # Already finished (replay): only the complete original state is accepted, it needs no write. $original = $Plan.Row.BackupRec @@ -2531,6 +2609,8 @@ function Invoke-PraAdReplication { $pending = @($changed | Where-Object { -not $failed.Contains([string]$_.Record.ObjectGuid) }) for ($attempt = 1; $attempt -le $attempts -and $pending.Count; $attempt++) { $stillPending = New-Object 'Collections.Generic.List[object]' + # The members of a licence group are read once for each attempt on the destination, not once for each object. + $destinationGroups = New-Object 'Collections.Generic.Dictionary[string,object]' ([StringComparer]::OrdinalIgnoreCase) foreach ($plan in $pending) { $Context.CurrentOperation = 'Verify-ADReplication'; $Context.CurrentIdentity = [string]$plan.Record.ObjectGuid $match = $false @@ -2542,8 +2622,18 @@ function Invoke-PraAdReplication { $match = $true foreach ($name in $names) { if (-not (Test-PraStateEqual $plan.Desired[$name] $actual[$name])) { $match = $false; break } } if ($match -and (Test-PraOrdinalIn ([string](Get-PraValue $plan.Row 'GroupAction' '')) @('Added', 'Removed'))) { - $group = @(Get-ADGroup -Identity ([guid]$plan.Record.Licensing.GroupGuid) -Properties member -Server $destination -ErrorAction Stop) - $isMember = ($group.Count -eq 1) -and (Test-PraOrdinalIn -IgnoreCase ([string]$plan.Record.DistinguishedName) @($group[0].member)) + $groupKey = [string]$plan.Record.Licensing.GroupGuid + $destinationSet = $null + if (-not $destinationGroups.TryGetValue($groupKey, [ref]$destinationSet)) { + $group = @(Get-ADGroup -Identity ([guid]$groupKey) -Properties member -Server $destination -ErrorAction Stop) + $destinationSet = $null + if ($group.Count -eq 1) { + $destinationSet = New-Object 'Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase) + foreach ($member in @($group[0].member)) { [void]$destinationSet.Add([string]$member) } + } + $destinationGroups[$groupKey] = $destinationSet + } + $isMember = ($null -ne $destinationSet) -and $destinationSet.Contains([string]$plan.Record.DistinguishedName) $match = ($isMember -eq [bool]$plan.Record.Licensing.DesiredMember) } } diff --git a/package/module/PRA.Gui.psm1 b/package/module/PRA.Gui.psm1 index 2dbb594..68e7829 100644 --- a/package/module/PRA.Gui.psm1 +++ b/package/module/PRA.Gui.psm1 @@ -240,8 +240,10 @@ function Get-PraGuiBatchCore { $cached = $null if ($script:PraGuiBatchCache.TryGetValue($Path, [ref]$cached) -and (Test-GuiOrdinal $cached.Stamp $stamp)) { return $cached } $core = [pscustomobject]@{ Stamp=$stamp; Operation='?'; BatchId=''; Error=''; Data=$null; Schema=0; Problem=$null } + # An answer about the content is kept; a failure to read the file (a lock, a sharing violation, a missing right) is not: the next refresh reads it again. try { - $data = [IO.File]::ReadAllText($Path) | ConvertFrom-PraJson + try { $text = [IO.File]::ReadAllText($Path) } catch { $core.Error = $_.Exception.Message; return $core } + $data = $text | ConvertFrom-PraJson $core.Operation = [string](Get-PraGuiValue $data 'Operation' '?') $core.BatchId = [string](Get-PraGuiValue $data 'BatchId' ((Split-Path (Split-Path $Path -Parent) -Leaf) -replace '^(Batch|Finalize)-','')) if (-not (Test-GuiOrdinalIn $core.Operation @('Convert','Recover','RecoverFinalize'))) { throw 'Not a Convert, Recover or RecoverFinalize package.' } @@ -1336,11 +1338,17 @@ function Get-PraGuiCsvRowText { $stamp=Get-PraGuiFileStamp $Path $cached=$null if ($script:PraGuiCsvCache.TryGetValue($Path,[ref]$cached) -and [string]::Equals($cached.Stamp,$stamp,[StringComparison]::Ordinal)) { return [string]$cached.Text } - try { $text=' ' + (ConvertTo-PraGuiPlural @(Read-PraTargetCsv -Path $Path).Count 'row' 'rows') + '.' } catch { $text=' ' + $_.Exception.Message } + # The sentence about a file that can be read is kept; a failure is told but never kept, so that a lock that ends is not shown again. + try { $text=' ' + (ConvertTo-PraGuiPlural @(Read-PraTargetCsv -Path $Path).Count 'row' 'rows') + '.' } catch { return (' ' + $_.Exception.Message) } $script:PraGuiCsvCache[$Path]=[pscustomobject]@{ Stamp=$stamp; Text=$text } return $text } +function Clear-PraGuiFileCache { + <# Forgets what the window kept about batch files, target CSV files and their hashes: the next refresh reads them again (the Reload link). #> + $script:PraGuiBatchCache.Clear(); $script:PraGuiCsvCache.Clear(); $script:PraGuiHashCache.Clear() +} + function Get-PraGuiSourceText { <# Title and sentence of the chosen object source. #> $g=$script:Gui @@ -3205,7 +3213,7 @@ function Invoke-PraGuiClick { Invoke-PraGuiChange } 'BtnOpenConfig' { Open-PraGuiPath $g.ConfigPath } - 'BtnReload' { if (-not $g.Run) { Update-PraGuiState } } + 'BtnReload' { if (-not $g.Run) { Clear-PraGuiFileCache; Update-PraGuiState } } 'BtnCopyCmd' { [Windows.Clipboard]::SetText($c.CmdLine.Text) } 'BtnPickOu' { Start-PraGuiOuLookup } 'BtnCheckIdentity' { Start-PraGuiIdentityLookup } diff --git a/tests/PraLegacyFixtures.Tests.ps1 b/tests/PraLegacyFixtures.Tests.ps1 index 822ec2a..2c6605e 100644 --- a/tests/PraLegacyFixtures.Tests.ps1 +++ b/tests/PraLegacyFixtures.Tests.ps1 @@ -116,7 +116,7 @@ BeforeAll { # Production functions of the entry script, extracted unchanged (they read $context, $Batch, $Identity, $Scope). $tokens = $null; $errors = $null $mainAst = [Management.Automation.Language.Parser]::ParseFile((Join-Path $repo 'package\Invoke-PraRemoteMailbox.ps1'), [ref]$tokens, [ref]$errors) - $wanted = @('Get-PraShortId', 'Get-PraBatchFile', 'Select-PraSourceRecord', 'Get-PraFinalizeInput') + $wanted = @('Get-PraShortId', 'Get-PraJsonOperation', 'Get-PraBatchFile', 'Select-PraSourceRecord', 'Get-PraFinalizeInput') $script:EntryFunctions = (@($mainAst.FindAll({ param($n) $n -is [Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -in $wanted }, $true) | ForEach-Object { $_.Extent.Text }) -join "`n") } diff --git a/tests/PraRemoteMailbox.Gui.Tests.ps1 b/tests/PraRemoteMailbox.Gui.Tests.ps1 index 8dfa91d..2c82c58 100644 --- a/tests/PraRemoteMailbox.Gui.Tests.ps1 +++ b/tests/PraRemoteMailbox.Gui.Tests.ps1 @@ -2272,3 +2272,51 @@ Describe 'Release 3.2.0 - the console continues a partial batch, or a batch whos $reasons['Both-True-plain-False'] | Should -BeExactly 'AD part done, sync not confirmed: finish it here' } } + +Describe 'Release 3.2.0 - the console does not keep a failure to read a file, and Reload forgets what it kept (synthetic, no engine)' -Tag 'Release320c' { + It 'a batch file that is locked is told but not kept: the next refresh reads it; an answer about the content (not a batch) is kept while the file is unchanged' { + $runtime=New-GuiTestRoot + $batch=New-GuiTestBatch $runtime + $global:PraGuiLocked=$batch.Path + $lock=[IO.File]::Open($batch.Path,[IO.FileMode]::Open,[IO.FileAccess]::Read,[IO.FileShare]::None) + try { $locked=& (Get-Module PRA.Gui) { Get-PraGuiBatchCore $global:PraGuiLocked } } finally { $lock.Dispose() } + $locked.Error | Should -Not -BeNullOrEmpty + $locked.Data | Should -BeNullOrEmpty + (& (Get-Module PRA.Gui) { $script:PraGuiBatchCache.ContainsKey($global:PraGuiLocked) }) | Should -BeFalse -Because 'a lock that ends must not stick' + $after=& (Get-Module PRA.Gui) { Get-PraGuiBatchCore $global:PraGuiLocked } + $after.Error | Should -BeExactly '' + $after.Data.RecordCount | Should -Be 1 + [object]::ReferenceEquals($after,(& (Get-Module PRA.Gui) { Get-PraGuiBatchCore $global:PraGuiLocked })) | Should -BeTrue + $other=Join-Path $runtime.Root 'Backups\Batch-notabatch\Other-fixture.json' + Write-GuiTestJson $other @{SchemaVersion=2;Operation='Other';Records=@()} + $global:PraGuiLocked=$other + $first=& (Get-Module PRA.Gui) { Get-PraGuiBatchCore $global:PraGuiLocked } + $first.Error | Should -Match 'Not a Convert, Recover or RecoverFinalize package' + [object]::ReferenceEquals($first,(& (Get-Module PRA.Gui) { Get-PraGuiBatchCore $global:PraGuiLocked })) | Should -BeTrue -Because 'the content of the unchanged file will not answer differently' + Remove-Variable PraGuiLocked -Scope Global + } + It 'the sentence about a target CSV file is not kept when the file cannot be read (a lock), and is read again when the lock ends' { + $runtime=New-GuiTestRoot + $csv=Join-Path $runtime.Root 'targets-locked.csv' + Write-GuiTestFile $csv ("Identity`r`n"+((1..3 | ForEach-Object { 'user'+$_+'@contoso.invalid' }) -join "`r`n")) + $global:PraGuiCsv=$csv + $lock=[IO.File]::Open($csv,[IO.FileMode]::Open,[IO.FileAccess]::Read,[IO.FileShare]::None) + try { $locked=& (Get-Module PRA.Gui) { Get-PraGuiCsvRowText $global:PraGuiCsv } } finally { $lock.Dispose() } + $locked | Should -Not -Match '^ 3 rows\.$' + $locked.Trim().Length | Should -BeGreaterThan 0 + (& (Get-Module PRA.Gui) { $script:PraGuiCsvCache.ContainsKey($global:PraGuiCsv) }) | Should -BeFalse + (& (Get-Module PRA.Gui) { Get-PraGuiCsvRowText $global:PraGuiCsv }) | Should -BeExactly ' 3 rows.' + Remove-Variable PraGuiCsv -Scope Global + } + It 'Reload clears the caches of batch files, CSV files and hashes, and the Reload button does it before it reads the state' { + $runtime=New-GuiTestRoot + $batch=New-GuiTestBatch $runtime + $global:PraGuiLocked=$batch.Path + $null=& (Get-Module PRA.Gui) { Get-PraGuiBatchCore $global:PraGuiLocked; $script:PraGuiCsvCache['x']=[pscustomobject]@{Stamp='s';Text='t'}; $script:PraGuiHashCache['y']=[pscustomobject]@{Stamp='s';Hash='h'} } + (& (Get-Module PRA.Gui) { $script:PraGuiBatchCache.Count + $script:PraGuiCsvCache.Count + $script:PraGuiHashCache.Count }) | Should -BeGreaterThan 2 + & (Get-Module PRA.Gui) { Clear-PraGuiFileCache } + (& (Get-Module PRA.Gui) { $script:PraGuiBatchCache.Count + $script:PraGuiCsvCache.Count + $script:PraGuiHashCache.Count }) | Should -Be 0 + Remove-Variable PraGuiLocked -Scope Global + (Get-Content -LiteralPath $script:GuiModule -Raw) | Should -Match "'BtnReload' \{ if \(-not \`$g\.Run\) \{ Clear-PraGuiFileCache; Update-PraGuiState \} \}" + } +} \ No newline at end of file diff --git a/tests/PraRemoteMailbox.Tests.ps1 b/tests/PraRemoteMailbox.Tests.ps1 index 2da008f..4cde853 100644 --- a/tests/PraRemoteMailbox.Tests.ps1 +++ b/tests/PraRemoteMailbox.Tests.ps1 @@ -93,6 +93,11 @@ function Copy-GateUser { $copy.msExchMailboxSecurityDescriptor=$mailbox Write-GateEvent 'NativeSecurityDescriptor' $copy.ObjectGUID $global:PraGateAd.Server @{NtBase64=[Convert]::ToBase64String($copy.nTSecurityDescriptor.GetSecurityDescriptorBinaryForm());MailboxBase64=[Convert]::ToBase64String($mailbox.GetSecurityDescriptorBinaryForm());AceCount=$copy.nTSecurityDescriptor.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]).Count;IdentityType='System.Security.Principal.SecurityIdentifier'} } + # A directory keeps the memberOf attribute of a user in step with the members of a group: every read of a user shows the synthetic licence group there. + if ($copy.objectClass -eq 'user' -and $global:PraGateAd.ContainsKey('Group') -and $null -ne $global:PraGateAd.Group) { + $inGroup=@($global:PraGateAd.Group.member) -contains [string]$copy.DistinguishedName + Add-Member -InputObject $copy -NotePropertyName memberOf -NotePropertyValue @(if ($inGroup) { [string]$global:PraGateAd.Group.DistinguishedName }) -Force + } return $copy } function Get-GateSha { @@ -341,6 +346,10 @@ function Invoke-PraCloudPhase { foreach ($row in $Rows) { $row.CloudStatus='Success'; $row.CloudMailbox=$true; $row.CloudLicense=$true; $row.DeprovisionConfirmed=$true; $row.FinalStatus='Success'; $row.CloudDetail='SYNTHETIC cloud confirmation followed by concurrent AD edit.' } } elseif ($state.Case -eq 'CloudConfirmed13') { foreach ($row in $Rows) { $row.CloudStatus='Success'; $row.CloudMailbox=$false; $row.CloudLicense=$false; $row.DeprovisionConfirmed=$true; $row.FinalStatus='Success'; $row.CloudDetail='SYNTHETIC: explicitly confirmed absent shared mailbox, no connection.' } + } elseif ($state.Case -eq 'CloudGrantSent') { + # What the real cloud phase leaves behind after it sent permission grants: the rows done and the number of grants sent. + foreach ($row in $Rows) { $row.CloudStatus='Success'; $row.CloudMailbox=$false; $row.CloudLicense=$false; $row.FinalStatus='Success'; $row.CloudDetail='SYNTHETIC: grants sent.' } + $Context.GrantsSent=[int]@($Rows).Count } elseif ($state.Case -eq 'CloudNetworkFailure') { # What the real cloud phase does when Microsoft 365 does not answer: a run error on each row, in plain words. $Context.NetworkFailure=$true; $Context.CurrentPhase='Cloud'; $Context.CurrentOperation='CloudCheck' @@ -857,8 +866,10 @@ Describe 'Directory internal invariants - synthetic modules only' { } $global:PraGate.Counters.ReadbackIds=@() Mock Import-PraBackup { - param($Context,$Path) - $result=& $script:GateActualImport $Context $Path + param($Context,$Path,$ExpectedSnapshots) + $importArguments=@{Context=$Context;Path=$Path} + if ($PSBoundParameters.ContainsKey('ExpectedSnapshots')) { $importArguments.ExpectedSnapshots=$ExpectedSnapshots } + $result=& $script:GateActualImport @importArguments $global:PraGate.Counters.Readbacks++ $global:PraGate.Counters.ReadbackIds=@($result.Data.Records | ForEach-Object ObjectGuid) return $result @@ -867,7 +878,7 @@ Describe 'Directory internal invariants - synthetic modules only' { $receipt=Invoke-PraAdBatch $global:PraGate.Context $plans 'Convert' $receipt.Data.Records.Count | Should -Be 2 $global:PraGate.Counters.Readbacks | Should -Be 1 -Because 'one complete import registers the receipt; each mutation rehashes it without reparsing raw' - $global:PraGate.Counters.RawValidations.Count | Should -Be 2 + $global:PraGate.Counters.RawValidations.Count | Should -Be 1 -Because 'one pass over the CLIXML file validates it and compares it with the captures in memory' @($global:PraGate.Counters.RawValidations | Where-Object { $_.Count -ne 2 -or $_.Bytes -le 0 -or $_.Format -cne 'PraDataOnlyClixml-v1' -or $_.Writes -ne 0 }).Count | Should -Be 0 @($global:PraGate.Counters.RawValidations | Where-Object Expected).Count | Should -Be 1 } @@ -3274,6 +3285,15 @@ function Invoke-PraExo { & $OnApplied @{Verified=$true;Mutated=$true} } +function Get-PraGrantsApplied { + param($Context) + if (-not $Context.ContainsKey('_PraGrantsApplied')) { $Context['_PraGrantsApplied']=New-Object 'System.Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase) } + return ,$Context['_PraGrantsApplied'] +} +function Get-PraGrantKey { + param($Context,$Upn,$Right,$Trustee) + return ($Upn+'|'+$Right+'|'+$Trustee) +} Export-ModuleMember -Function Invoke-PraPermissionGrant '@ $global:PraGate.AuthorityModulePath=Join-Path $global:PraGate.Root 'PraGateAuthorityGrant.psm1' @@ -10312,6 +10332,160 @@ Describe 'Release 3.2.0 - scale: one search of the backup folder serves every ob } } +Describe 'Release 3.2.0 - scale: the backup codec writes the bytes of its format and reads only what the format allows (production Backup module, synthetic capture)' -Tag 'Release320c' { + BeforeAll { + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Backup.psm1') -Force -Global + $sid = New-Object Security.Principal.SecurityIdentifier('S-1-5-21-100-200-300-3001') + $user = [ordered]@{ + ObjectGUID = [guid]'00112233-4455-6677-8899-aabbccddeeff'; DistinguishedName = 'CN=Golden,OU=Tests,DC=gate,DC=invalid' + Name = 'Golden'; Empty = ''; NullValue = $null; Flag = $true; Number = [int]42; Big = [long]::MaxValue; Dbl = [double]1.5 + Text = (' literal_x0041_ & < > ' + [char]0 + "`r`n`t" + [char]0xD800 + ' end') + Bytes = [byte[]](0, 1, 2, 255); Guid = [guid]'11112222-3333-4444-5555-666677778888'; Sid = $sid + When = [datetime]::SpecifyKind([datetime]'2026-09-07T01:02:03', [DateTimeKind]::Utc) + Multi = [string[]]@('a', 'b', 'a'); Nested = [object[]]@('first', $null, [object[]]@(), [object[]]@('n1', 'n2'), [byte[]](0, 255)) + } + $global:PraGate.Codec = @{ Context = @{ LogFile = ''; Warnings = 0; Issues = (New-Object 'Collections.Generic.List[object]') } + Snapshot = (ConvertTo-PraRawSnapshot -User ([pscustomobject]$user) -CapturedUtc '2026-11-17T10:00:00.0000000Z') } + } + It 'writes exactly the bytes that the format defines (the hash of a capture with every kind of value is fixed)' { + $path = Join-Path $global:PraGate.Root ('golden-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.clixml') + Write-PraRawCapture -Context $global:PraGate.Codec.Context -LiteralPath $path -Snapshots @($global:PraGate.Codec.Snapshot) + (Get-Item -LiteralPath $path).Length | Should -Be 5455 + (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash | Should -BeExactly 'E53FC396F9C41A0ACA8C16EA515A676CDD88C9BC3BDACF53DA239B36FA5A058D' + } + It 'refuses an element out of its place, an extra attribute, a number that is not canonical and a sequence number that is out of order, with the message of the strict reader' { + $path = Join-Path $global:PraGate.Root ('golden-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.clixml') + Write-PraRawCapture -Context $global:PraGate.Codec.Context -LiteralPath $path -Snapshots @($global:PraGate.Codec.Snapshot) + $text = [IO.File]::ReadAllText($path) + $records = @([pscustomobject]@{ ObjectGUID = '00112233-4455-6677-8899-aabbccddeeff' }) + $format = 'PraDataOnlyClixml-v1' + $cases = [ordered]@{ + 'member name' = @('N="Kind"', 'N="Kynd"', '*expected member Kind*') + 'extra attribute' = @('', '', '*unexpected attribute X*') + 'depth number' = @('0', '00', '*noncanonical Int32*') + 'sequence number' = @('RefId="4"', 'RefId="9"', '*object identity/name/sequence invalid*') + } + foreach ($name in $cases.Keys) { + $pattern = [regex]::new([regex]::Escape($cases[$name][0])) + $changed = $pattern.Replace($text, $cases[$name][1], 1) + $changed | Should -Not -BeExactly $text -Because $name + $tampered = $path + '.' + ($name -replace ' ', '-') + '.clixml' + [IO.File]::WriteAllText($tampered, $changed, (New-Object Text.UTF8Encoding($false))) + { Test-PraRawCapture -Context $global:PraGate.Codec.Context -LiteralPath $tampered -Records $records -RawFormat $format } | Should -Throw $cases[$name][2] -Because $name + } + } +} + +Describe 'Release 3.2.0 - scale: the licence group is read once for the objects of a run, and the check that comes with every write reads the object itself (production Directory module, synthetic AD)' -Tag 'Release320c' { + BeforeEach { + $global:PraGate.Runtime = New-GateRuntime -Name 'scale-group' -UserCount 4 + $env:PRA_GATE_STATE = $global:PraGate.Runtime.StatePath + $env:PSModulePath = $global:PraGate.Runtime.Modules + ';' + (Join-Path $PSHOME 'Modules') + Import-Module ActiveDirectory -Force -Global + $global:PraGate.Context = New-GateContext $global:PraGate.Runtime + $global:PraGate.Context.LogFile = Join-Path $global:PraGate.Runtime.Root 'logs\scale-group.log' + } + It 'reads a group of 5000 members once for 5000 objects, in any letter case, and again after a write to a group and after the keeping time' { + $global:PraGate.GroupScale = @{ Reads = 0; Members = [string[]]@(1..5000 | ForEach-Object { 'CN=Member{0},OU=Tests,DC=gate,DC=invalid' -f $_ }) } + $result = InModuleScope PRA.Directory { + Mock Get-PraGroup { $global:PraGate.GroupScale.Reads++; [pscustomobject]@{ ObjectGUID = [guid]'10000000-0000-0000-0000-000000000001'; DistinguishedName = 'CN=License,OU=Tests,DC=gate,DC=invalid'; member = $global:PraGate.GroupScale.Members } } + $context = @{} + $found = 0 + foreach ($i in 1..5000) { + $read = Get-PraGroupMemberSet $context 'CN=License,OU=Tests,DC=gate,DC=invalid' + if ($read.Members.Contains(('cn=member{0},ou=tests,dc=gate,dc=invalid' -f $i))) { $found++ } + } + $stages = @{ Found = $found; Reads = $global:PraGate.GroupScale.Reads } + $stages.Stranger = (Get-PraGroupMemberSet $context 'cn=license,ou=tests,dc=gate,dc=invalid').Members.Contains('CN=Stranger,OU=Tests,DC=gate,DC=invalid') + $stages.SameGroupOtherCase = $global:PraGate.GroupScale.Reads + $context['PraGroupGeneration'] = 1 + $null = Get-PraGroupMemberSet $context 'CN=License,OU=Tests,DC=gate,DC=invalid' + $stages.AfterWrite = $global:PraGate.GroupScale.Reads + $script:GroupMemberSeconds = 0 + try { $null = Get-PraGroupMemberSet $context 'CN=License,OU=Tests,DC=gate,DC=invalid'; $null = Get-PraGroupMemberSet $context 'CN=License,OU=Tests,DC=gate,DC=invalid' } + finally { $script:GroupMemberSeconds = 30 } + $stages.AfterKeepingTime = $global:PraGate.GroupScale.Reads + $stages + } + $result.Found | Should -Be 5000 + $result.Reads | Should -Be 1 -Because 'one read of the group for the 5000 objects' + $result.Stranger | Should -BeFalse + $result.SameGroupOtherCase | Should -Be 1 -Because 'the group named in another letter case is the same group' + $result.AfterWrite | Should -Be 2 + $result.AfterKeepingTime | Should -Be 4 -Because 'with no keeping time, each request reads the group' + } + It 'the check of a write reads the group without its members and takes the membership of the object from the memberOf attribute that was just read' { + $context = $global:PraGate.Context + $plans = @(1..2 | ForEach-Object { New-PraPlan $context ('user' + $_) 'Convert' }) + $plans[0].Record.Licensing.Enabled | Should -BeTrue + $plans[0].Record.Licensing.WasMember | Should -BeFalse + $global:PraGate.GroupCalls = New-Object 'Collections.Generic.List[bool]' + $check = { + param($Context, $Plan, [bool]$Member) + & (Get-Module PRA.Directory) { param($c, $p, $m) Assert-PraCurrentState $c $p $p.Record.Attributes $m } $Context $Plan $Member + } + InModuleScope PRA.Directory { + $script:RealGroup = (Get-Command Get-PraGroup).ScriptBlock + Mock Get-PraGroup { param($Context, $Identity, [switch]$WithoutMembers) $global:PraGate.GroupCalls.Add([bool]$WithoutMembers); & $script:RealGroup -Context $Context -Identity $Identity -WithoutMembers:$WithoutMembers } + } + { & $check $context $plans[0] $false } | Should -Not -Throw + { & $check $context $plans[0] $true } | Should -Throw '*Licence group membership differs*' + $global:PraGateAd.Group.member = @($global:PraGateAd.Group.member) + [string]$global:PraGateAd.Users[0].DistinguishedName.ToLowerInvariant() + { & $check $context $plans[0] $true } | Should -Not -Throw -Because 'the directory compares the names of the group and of its members without regard to letter case' + { & $check $context $plans[0] $false } | Should -Throw '*Licence group membership differs*' + { & $check $context $plans[1] $false } | Should -Not -Throw + @($global:PraGate.GroupCalls | Where-Object { -not $_ }).Count | Should -Be 0 -Because 'no check of a write asks for the members of the group' + $global:PraGate.GroupCalls.Count | Should -BeGreaterThan 4 + } +} + +Describe 'Release 3.2.0 - scale: the Operation of a batch file is read from its head; the log takes the lines of an object in one write (production Common module, entry script function, synthetic files)' -Tag 'Release320c' { + BeforeAll { + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global + $tokens = $null; $errors = $null + $entryAst = [Management.Automation.Language.Parser]::ParseFile((Join-Path $global:PraGate.Package 'Invoke-PraRemoteMailbox.ps1'), [ref]$tokens, [ref]$errors) + $definition = $entryAst.FindAll({ param($n) $n -is [Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -ceq 'Get-PraJsonOperation' }, $true)[0].Extent.Text + . ([scriptblock]::Create($definition)) + } + It 'takes the Operation from the head of a large file without reading the rest, whatever the layout, and parses the whole file when the head does not tell' { + $folder = Join-Path $global:PraGate.Root ('operation-' + [guid]::NewGuid().ToString('N').Substring(0, 6)); $null = New-Item -ItemType Directory -Path $folder -Force + $utf8 = New-Object Text.UTF8Encoding($true) + $body = '"Records":[' + (('{"ObjectGuid":"00000000-0000-0000-0000-000000000001","Operation":"Nested","Text":"' + ('x' * 200) + '"},') * 20000) + '{"ObjectGuid":"x"}]' + # The head tells: the file after the head is not JSON at all, so only a read of the head can answer. + $head = Join-Path $folder 'head.json' + [IO.File]::WriteAllText($head, ("{`r`n ""SchemaVersion"": 3,`r`n ""Operation"": ""Convert"",`r`n ""Records"": [" + ('?' * 20000)), $utf8) + Get-PraJsonOperation $head | Should -BeExactly 'Convert' + $compact = Join-Path $folder 'compact.json' + [IO.File]::WriteAllText($compact, ('{"SchemaVersion":3,"RawFormat":"PraDataOnlyClixml-v1","Operation":"RecoverFinalize","Items":[' + ('?' * 20000)), (New-Object Text.UTF8Encoding($false))) + Get-PraJsonOperation $compact | Should -BeExactly 'RecoverFinalize' + # The head does not tell: the Operation comes after a list, so the whole file is parsed and the field of the top level is the one that counts, not the one of a record. + $late = Join-Path $folder 'late.json' + [IO.File]::WriteAllText($late, ('{"SchemaVersion":3,' + $body + ',"Operation":"Recover"}'), $utf8) + Get-PraJsonOperation $late | Should -BeExactly 'Recover' + # An escape in the value and a file that is not JSON: the whole-file parse decides, as before. + $escaped = Join-Path $folder 'escaped.json' + [IO.File]::WriteAllText($escaped, '{"Operation":"Con\u0076ert","Records":[]}', $utf8) + Get-PraJsonOperation $escaped | Should -BeExactly 'Convert' + $broken = Join-Path $folder 'broken.json' + [IO.File]::WriteAllText($broken, '{"SchemaVersion":3,"Records":[', $utf8) + { Get-PraJsonOperation $broken } | Should -Throw + } + It 'writes the lines of one call to the log in the format of a single line, one write for all of them, and only for the Detail level' { + $log = Join-Path $global:PraGate.Root ('lines-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.log') + $context = @{ LogFile = $log; Warnings = 0; Issues = (New-Object 'Collections.Generic.List[object]') } + Write-PraLog -Context $context -Message 'one' -Level Detail + Write-PraLog -Context $context -Lines @('two', "three`r`nwith a break", '') -Level Detail + $lines = @([IO.File]::ReadAllLines($log)) + $lines.Count | Should -Be 4 + $lines[0] | Should -Match '^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d\.\d{3} \[DETAIL\] one$' + $lines[1] | Should -Match '^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d\.\d{3} \[DETAIL\] two$' + $lines[2] | Should -Match '\[DETAIL\] three \| with a break$' + $lines[3] | Should -Match '\[DETAIL\] $' + { Write-PraLog -Context $context -Lines @('x') -Level Info } | Should -Throw '*Detail level only*' + } +} + Describe 'Release 3.2.0 - source anchors and the new cloud settings (production Common module)' -Tag 'Release320b' { BeforeAll { Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global } It 'ConvertTo-PraImmutableId gives the base64 of the 16 bytes of a GUID, whatever the form (object, text in any letter case, bytes, a one-item collection) and nothing for anything else' { @@ -10468,8 +10642,8 @@ Describe 'Release 3.2.0 - the cloud account is the one synchronised from Active $global:PraGate.R7NetworkPath = Join-Path $global:PraGate.Root 'PraGateR7Network.psm1' $networkSource = @' if ($env:PRA_GATE_NONET -cne 'SYNTHETIC-NO-NETWORK') { throw 'Synthetic interlock absent.' } -function Get-EXOMailbox { [CmdletBinding()]param($Identity,$Filter,$Properties,$ResultSize,[switch]$InactiveMailboxOnly) throw 'SYNTHETIC BLOCK: EXO mailbox' } -function Get-EXORecipient { [CmdletBinding()]param($Identity,$UserPrincipalName,$Filter,$Properties,$ResultSize) throw 'SYNTHETIC BLOCK: EXO recipient' } +function Get-EXOMailbox { [CmdletBinding()]param($Identity,$ExternalDirectoryObjectId,$Filter,$Properties,$ResultSize,[switch]$InactiveMailboxOnly) throw 'SYNTHETIC BLOCK: EXO mailbox' } +function Get-EXORecipient { [CmdletBinding()]param($Identity,$ExternalDirectoryObjectId,$UserPrincipalName,$Filter,$Properties,$ResultSize) throw 'SYNTHETIC BLOCK: EXO recipient' } function Get-MgUser { [CmdletBinding()]param($UserId,$Filter,$Property) throw 'SYNTHETIC BLOCK: Graph user' } function Get-MgUserLicenseDetail { [CmdletBinding()]param($UserId,[switch]$All) throw 'SYNTHETIC BLOCK: Graph licence' } function Get-MgContext { [CmdletBinding()]param() [pscustomobject]@{TenantId='20000000-0000-0000-0000-000000000002';ContextScope='Process'} } @@ -11146,8 +11320,8 @@ Describe 'Release 3.2.0 - the stop of a run, a grant never repeated, custom sour $global:PraGate.R9NetworkPath = Join-Path $global:PraGate.Root 'PraGateR9Network.psm1' $networkSource = @' if ($env:PRA_GATE_NONET -cne 'SYNTHETIC-NO-NETWORK') { throw 'Synthetic interlock absent.' } -function Get-EXOMailbox { [CmdletBinding()]param($Identity,$Filter,$Properties,$ResultSize,[switch]$InactiveMailboxOnly) throw 'SYNTHETIC BLOCK: EXO mailbox' } -function Get-EXORecipient { [CmdletBinding()]param($Identity,$UserPrincipalName,$Filter,$Properties,$ResultSize) throw 'SYNTHETIC BLOCK: EXO recipient' } +function Get-EXOMailbox { [CmdletBinding()]param($Identity,$ExternalDirectoryObjectId,$Filter,$Properties,$ResultSize,[switch]$InactiveMailboxOnly) throw 'SYNTHETIC BLOCK: EXO mailbox' } +function Get-EXORecipient { [CmdletBinding()]param($Identity,$ExternalDirectoryObjectId,$UserPrincipalName,$Filter,$Properties,$ResultSize) throw 'SYNTHETIC BLOCK: EXO recipient' } function Get-MgUser { [CmdletBinding()]param($UserId,$Filter,$Property) throw 'SYNTHETIC BLOCK: Graph user' } function Get-MgUserLicenseDetail { [CmdletBinding()]param($UserId,[switch]$All) throw 'SYNTHETIC BLOCK: Graph licence' } function Get-MgContext { [CmdletBinding()]param() [pscustomobject]@{TenantId='20000000-0000-0000-0000-000000000002';ContextScope='Process'} } @@ -11421,13 +11595,13 @@ Export-ModuleMember -Function Get-EXOMailbox,Get-EXORecipient,Get-MgUser,Get-MgU $global:PraGate.R9Seen = @{} $result = InModuleScope PRA.Cloud { Mock Get-EXORecipient { - param($Identity, $UserPrincipalName, $Filter, $Properties, $ResultSize) - $global:PraGate.R9Seen['Recipient'] = '{0}|{1}' -f $Identity, $UserPrincipalName + param($Identity, $ExternalDirectoryObjectId, $UserPrincipalName, $Filter, $Properties, $ResultSize) + $global:PraGate.R9Seen['Recipient'] = '{0}|{1}' -f $ExternalDirectoryObjectId, $UserPrincipalName [pscustomobject]@{ RecipientTypeDetails = 'UserMailbox'; PrimarySmtpAddress = 'user1@gate.invalid'; ExternalDirectoryObjectId = $global:PraGate.R9ExoId; Guid = [guid]::NewGuid(); DistinguishedName = 'CN=user1' } } Mock Get-EXOMailbox { - param($Identity, $Filter, $Properties, $ResultSize, $InactiveMailboxOnly) - $global:PraGate.R9Seen['Mailbox'] = '{0}|{1}' -f $Identity, $Filter + param($Identity, $ExternalDirectoryObjectId, $Filter, $Properties, $ResultSize, $InactiveMailboxOnly) + $global:PraGate.R9Seen['Mailbox'] = '{0}|{1}' -f $ExternalDirectoryObjectId, $Filter [pscustomobject]@{ RecipientTypeDetails = 'UserMailbox'; EmailAddresses = [string[]]@('SMTP:user1@gate.invalid'); ExternalDirectoryObjectId = $global:PraGate.R9ExoId } } $global:PraGate.R9ExoId = 'aaaaaaaa-0000-0000-0000-000000000001' @@ -11448,25 +11622,22 @@ Export-ModuleMember -Function Get-EXOMailbox,Get-EXORecipient,Get-MgUser,Get-MgU $result['Mailbox-unknown'] | Should -Match '^\|UserPrincipalName -eq ''user1@gate\.invalid''' $result.Compared | Should -Match 'The Exchange Online mailbox is not the Microsoft Entra ID account confirmed for this object' } - It 'an inactive mailbox is not refused for carrying the ExternalDirectoryObjectId of its deleted account: it is found by UPN and flagged; several inactive mailboxes are an ambiguity unless the recorded anchor tells them apart' { + It 'an inactive mailbox of a deleted account (no account to confirm) is found by UPN and flagged; several inactive mailboxes are an ambiguity, never a guess' { $global:PraGate.R9Worker = @{ Binding = $global:PraGate.R9Binding } - $anchor = New-R9Anchor 'ab12cd34-0000-4000-8000-0000000000ef' - $inactive = { param($Eoid, $Immutable, $Hold) $m = [pscustomobject]@{ RecipientTypeDetails = 'UserMailbox'; EmailAddresses = [string[]]@('SMTP:user1@gate.invalid'); ExternalDirectoryObjectId = $Eoid; IsInactiveMailbox = $true; InPlaceHolds = @($Hold) }; if ($Immutable) { Add-Member -InputObject $m -NotePropertyName ImmutableId -NotePropertyValue $Immutable }; $m } + $inactive = { param($Eoid, $Hold) [pscustomobject]@{ RecipientTypeDetails = 'UserMailbox'; EmailAddresses = [string[]]@('SMTP:user1@gate.invalid'); ExternalDirectoryObjectId = $Eoid; IsInactiveMailbox = $true; InPlaceHolds = @($Hold) } } $global:PraGate.R9Cases = @{ - One = @(& $inactive 'dddddddd-0000-0000-0000-000000000001' '' 'mbx40000000000000000000000000000004') - Two = @((& $inactive 'dddddddd-0000-0000-0000-000000000001' '' 'mbx40000000000000000000000000000004'), (& $inactive 'dddddddd-0000-0000-0000-000000000002' '' 'mbx40000000000000000000000000000004')) - Tell = @((& $inactive 'dddddddd-0000-0000-0000-000000000001' 'not-this-anchor' 'mbx40000000000000000000000000000001'), (& $inactive 'dddddddd-0000-0000-0000-000000000002' $anchor 'mbx40000000000000000000000000000002')) } - $global:PraGate.R9Anchor = $anchor + One = @(& $inactive 'dddddddd-0000-0000-0000-000000000001' 'mbx40000000000000000000000000000004') + Two = @((& $inactive 'dddddddd-0000-0000-0000-000000000001' 'mbx40000000000000000000000000000004'), (& $inactive 'dddddddd-0000-0000-0000-000000000002' 'mbx40000000000000000000000000000004')) } $result = InModuleScope PRA.Cloud { Mock Get-EXOMailbox { - param($Identity, $Filter, $Properties, $ResultSize, $InactiveMailboxOnly) - if ($Identity) { throw "The operation couldn't be performed because object 'x' couldn't be found on 'y'." } + param($Identity, $ExternalDirectoryObjectId, $Filter, $Properties, $ResultSize, $InactiveMailboxOnly) + if ($Identity -or $ExternalDirectoryObjectId) { throw "The operation couldn't be performed because object 'x' couldn't be found on 'y'." } if ($InactiveMailboxOnly) { $global:PraGate.R9Inactive } } $answers = @{} - foreach ($name in 'One', 'Two', 'Tell') { + foreach ($name in 'One', 'Two') { $global:PraGate.R9Inactive = $global:PraGate.R9Cases[$name] - try { $answers[$name] = & $script:PraExoWorker 'Hold' @{ Upn = 'user1@gate.invalid'; VerifiedObjectIds = @{ 'user1@gate.invalid' = 'aaaaaaaa-0000-0000-0000-000000000001' }; Anchors = @($global:PraGate.R9Anchor) } $null $global:PraGate.R9Worker.Binding $null $null } + try { $answers[$name] = & $script:PraExoWorker 'Hold' @{ Upn = 'user1@gate.invalid'; VerifiedObjectIds = @{} } $null $global:PraGate.R9Worker.Binding $null $null } catch { $answers[$name] = $_.Exception.Message } } $answers @@ -11474,8 +11645,6 @@ Export-ModuleMember -Function Get-EXOMailbox,Get-EXORecipient,Get-MgUser,Get-MgU $result.One.Found | Should -BeTrue $result.One.IdentityByUpn | Should -BeTrue $result.Two | Should -Match 'Exchange Online has 2 inactive mailboxes for user1@gate\.invalid and nothing tells which one belongs to this object' - $result.Tell.Found | Should -BeTrue - @($result.Tell.Holds) | Should -BeExactly @('mbx40000000000000000000000000000002') -Because 'the mailbox that carries the recorded anchor' } It 'the retention check says that an inactive mailbox was found by UPN only (a warning on the object), and the check still goes on' { $context = New-GateContext $global:PraGate.Runtime -Mode Preview -Action Check @@ -11563,7 +11732,7 @@ Describe 'Release 3.2.0 - Recover from the journal when the State file is unread } finally { [IO.File]::WriteAllBytes($state, $original) } } - It 'a journal line that cannot be read is skipped with ONE warning and the others are still read' { + It 'a journal line that cannot be read is skipped with ONE warning and the others are still read; without the objects named by -Identity the Recover refuses to guess, with the command that names them' { $short = $global:PraGate.R4Id.Substring(0, 8) $state = Join-Path $global:PraGate.R4Folder ('State-' + $global:PraGate.R4Id + '.json') $journal = Join-Path $global:PraGate.R4Folder ('Journal-' + $global:PraGate.R4Id + '.jsonl') @@ -11572,10 +11741,16 @@ Describe 'Release 3.2.0 - Recover from the journal when the State file is unread [IO.File]::AppendAllText($journal, "this line is not json`r`n" + '{"RunId":"r","Utc":"x","Target":"00000000-0000-0000-0000-00000000000' + "`r`n" + '{"RunId":"r","Operation":"Set-ADUser","Status":"Started","Target":"00000000-0000-0000-0000-000000000005","Detail":"t"' + "`r`n") try { $run = Invoke-GateProcess $global:PraGate.R4 @{Action='Recover';Phase='AD';Mode='Preview';ConfigPath=$global:PraGate.R4.ConfigPath;Batch=$short} -TimeoutSeconds 120 - $run.ExitCode | Should -Be 0 -Because ($run.Output + $run.Error) + $run.ExitCode | Should -Be 1 -Because ($run.Output + $run.Error) $run.Output | Should -Match '[0-9]+ line\(s\) of the journal Journal-[0-9a-f]{32}\.jsonl cannot be read and were skipped' - $run.MainResult.WarningCount | Should -Be 2 -Because 'the unusable proof (no .sha256) and ONE warning for all the damaged lines' - $run.MainResult.PlannedCount | Should -Be 4 -Because 'the objects of the lines that can be read are still taken, the truncated line names nothing' + $run.Output | Should -Match 'Recover of batch [0-9a-f]{8} cannot go on: its AD proof is partial but unusable .* line\(s\) of its journal cannot be read, so the objects that the batch wrote cannot be told for certain\. Nothing was changed\.' + $steps = @($run.MainResult.NextSteps) + $steps[0] | Should -Match 'has [0-9]+ line\(s\) that cannot be read' + @($steps | Where-Object { $_ -match '^\.\\Invoke-PraRemoteMailbox\.ps1 -Action Recover .*-Batch [0-9a-f]{8} .*-Identity ''' }).Count | Should -Be 1 + @($steps | Where-Object { $_ -match 'restore the attributes of the objects from that backup file by hand' }).Count | Should -Be 1 + $named = Invoke-GateProcess $global:PraGate.R4 @{Action='Recover';Phase='AD';Mode='Preview';ConfigPath=$global:PraGate.R4.ConfigPath;Batch=$short;Identity='user5'} -TimeoutSeconds 120 + $named.ExitCode | Should -Be 0 -Because ($named.Output + $named.Error) + $named.MainResult.PlannedCount | Should -Be 1 -Because 'the operator names the object, nothing is guessed' } finally { [IO.File]::WriteAllBytes($journal, $originalJournal); Move-Item -LiteralPath ($state + '.sha256.away') -Destination ($state + '.sha256') } } @@ -11743,3 +11918,555 @@ Describe 'Release 3.2.0 - the CSV of the objects left matches GUIDs in any form, $run.Output | Should -Match ([regex]::Escape('4 line(s) of the file ' + $csv + ' name objects that batch')) } } + +Describe 'Release 3.2.0 - review of the cloud part: writes by the confirmed id, an inactive mailbox of an earlier account, rows that finished are kept, refusals of Graph stop the run once, a grant is never sent twice (production Cloud module, mocked boundaries, no network)' -Tag 'Release320c' { + BeforeAll { + $global:PraGate.R10Path = Join-Path $global:PraGate.Root 'PraGateR10Network.psm1' + $networkSource = @' +if ($env:PRA_GATE_NONET -cne 'SYNTHETIC-NO-NETWORK') { throw 'Synthetic interlock absent.' } +function Find-R10Object { + param([string]$Key) + foreach ($name in @($global:PraGate.R10.Objects.Keys)) { + $o = $global:PraGate.R10.Objects[$name] + if ([string]::Equals($Key, $name, [StringComparison]::OrdinalIgnoreCase) -or [string]::Equals($Key, $o.Id, [StringComparison]::OrdinalIgnoreCase)) { return $o } + } + $m = ($global:PraGate.R10.NotFoundForm -f $Key.ToLowerInvariant()) + $payload = @{ error = @{ code = 'NotFound'; message = $m; details = @(@{ code = 'Context'; message = ('Ex6F9304|Microsoft.Exchange.Configuration.Tasks.ManagementObjectNotFoundException|' + $m); target = '' }); innererror = @{ message = $m; type = 'Microsoft.Exchange.Admin.OData.Core.ODataServiceException' } } } + throw ('Error while querying REST service. HttpStatusCode=404 ErrorMessage=' + ($payload | ConvertTo-Json -Depth 6 -Compress)) +} +function Get-R10Selector { param($Id, $Upn, $Identity, $Filter) if ($Id) { return @('EDOID', [string]$Id) }; if ($Upn) { return @('UPN', [string]$Upn) }; if ($Filter) { return @('Filter', ([regex]::Match([string]$Filter, "'([^']+)'").Groups[1].Value)) }; return @('Identity', [string]$Identity) } +function Get-EXORecipient { + [CmdletBinding()]param($Identity, $ExternalDirectoryObjectId, $UserPrincipalName, $Filter, $Properties, $ResultSize) + $s = Get-R10Selector $ExternalDirectoryObjectId $UserPrincipalName $Identity $Filter + $global:PraGate.R10.Calls.Add('Get-EXORecipient|' + $s[0] + '=' + $s[1]) + $o = Find-R10Object $s[1] + [pscustomobject]@{ RecipientTypeDetails = $o.Type; PrimarySmtpAddress = $o.Smtp; ExternalDirectoryObjectId = $o.Id; Guid = $o.Guid; DistinguishedName = ('CN=' + $o.Name) } +} +function Get-EXOMailbox { + [CmdletBinding()]param($Identity, $ExternalDirectoryObjectId, $UserPrincipalName, $Filter, $Properties, $ResultSize, [switch]$InactiveMailboxOnly) + $s = Get-R10Selector $ExternalDirectoryObjectId $UserPrincipalName $Identity $Filter + $global:PraGate.R10.Calls.Add('Get-EXOMailbox|' + $s[0] + '=' + $s[1]) + $o = Find-R10Object $s[1] + [pscustomobject]@{ RecipientTypeDetails = $o.Type; EmailAddresses = [string[]]@('SMTP:' + $o.Smtp); ExternalDirectoryObjectId = $o.Id } +} +function Get-Mailbox { + [CmdletBinding()]param($Identity, $Filter, $ResultSize) + $s = Get-R10Selector $null $null $Identity $Filter + $global:PraGate.R10.Calls.Add('Get-Mailbox|' + $s[0] + '=' + $s[1]) + $o = Find-R10Object $s[1] + [pscustomobject]@{ ExternalDirectoryObjectId = $o.Id; GrantSendOnBehalfTo = @(if ($global:PraGate.R10.Added.Contains('SendOnBehalf')) { 'trustee1@gate.invalid' }) } +} +function New-R10Acl { + param($Right, $Principal, $Target) + $entry = [ordered]@{ Identity = $Target.Id; AccessRights = @($Right); IsInherited = $false } + if ($Right -ceq 'FullAccess') { $entry.User = $Principal; $entry.Deny = $false } else { $entry.Trustee = $Principal; $entry.AccessControlType = 'Allow' } + [pscustomobject]$entry +} +function Get-EXOMailboxPermission { + [CmdletBinding()]param($Identity, $ExternalDirectoryObjectId, $User, $ResultSize) + $s = Get-R10Selector $ExternalDirectoryObjectId $null $Identity $null + $global:PraGate.R10.Calls.Add('Get-EXOMailboxPermission|' + $s[0] + '=' + $s[1]) + $o = Find-R10Object $s[1] + if ($User) { if ($global:PraGate.R10.Added.Contains('FullAccess')) { New-R10Acl 'FullAccess' 'trustee1@gate.invalid' $o }; return } + New-R10Acl 'FullAccess' 'NT AUTHORITY\SELF' $o + if ($global:PraGate.R10.Added.Contains('FullAccess')) { New-R10Acl 'FullAccess' 'trustee1@gate.invalid' $o } +} +function Get-EXORecipientPermission { + [CmdletBinding()]param($Identity, $ExternalDirectoryObjectId, $Trustee, $ResultSize) + $s = Get-R10Selector $ExternalDirectoryObjectId $null $Identity $null + $global:PraGate.R10.Calls.Add('Get-EXORecipientPermission|' + $s[0] + '=' + $s[1]) + $o = Find-R10Object $s[1] + if ($Trustee) { if ($global:PraGate.R10.Added.Contains('SendAs')) { New-R10Acl 'SendAs' 'trustee1@gate.invalid' $o }; return } + New-R10Acl 'SendAs' 'NT AUTHORITY\SELF' $o + if ($global:PraGate.R10.Added.Contains('SendAs')) { New-R10Acl 'SendAs' 'trustee1@gate.invalid' $o } +} +function Add-MailboxPermission { [CmdletBinding(SupportsShouldProcess)]param($Identity, $User, $AccessRights, [bool]$AutoMapping, $InheritanceType) $global:PraGate.R10.Calls.Add('Add-MailboxPermission|Identity=' + $Identity + '|User=' + $User); [void]$global:PraGate.R10.Added.Add('FullAccess') } +function Add-RecipientPermission { [CmdletBinding(SupportsShouldProcess)]param($Identity, $Trustee, $AccessRights) $global:PraGate.R10.Calls.Add('Add-RecipientPermission|Identity=' + $Identity + '|Trustee=' + $Trustee); [void]$global:PraGate.R10.Added.Add('SendAs') } +function Set-Mailbox { [CmdletBinding(SupportsShouldProcess)]param($Identity, $GrantSendOnBehalfTo) $global:PraGate.R10.Calls.Add('Set-Mailbox|Identity=' + $Identity + '|Add=' + $GrantSendOnBehalfTo.Add); [void]$global:PraGate.R10.Added.Add('SendOnBehalf') } +function Get-MgUser { [CmdletBinding()]param($UserId, $Filter, $Property) throw 'SYNTHETIC BLOCK: Graph user' } +function Get-MgUserLicenseDetail { [CmdletBinding()]param($UserId, [switch]$All) throw 'SYNTHETIC BLOCK: Graph licence' } +function Connect-IPPSSession { [CmdletBinding()]param([switch]$ShowBanner) } +function Get-RetentionCompliancePolicy { [CmdletBinding()]param($Identity) throw 'SYNTHETIC BLOCK: retention policy' } +function Disconnect-ExchangeOnline { [CmdletBinding(SupportsShouldProcess)]param($ConnectionId) if ($global:PraGate.R10.SignOutFails) { throw 'SYNTHETIC sign-out refused' } } +function Get-ConnectionInformation { [CmdletBinding()]param() [pscustomobject]@{ TenantID = '20000000-0000-0000-0000-000000000002'; State = 'Connected'; TokenStatus = 'Active'; ConnectionId = '30000000-0000-0000-0000-000000000003'; ModuleName = $global:PraGate.R10Path } } +Export-ModuleMember -Function Get-EXORecipient, Get-EXOMailbox, Get-Mailbox, Get-EXOMailboxPermission, Get-EXORecipientPermission, Add-MailboxPermission, Add-RecipientPermission, Set-Mailbox, Get-MgUser, Get-MgUserLicenseDetail, Connect-IPPSSession, Get-RetentionCompliancePolicy, Disconnect-ExchangeOnline, Get-ConnectionInformation +'@ + [IO.File]::WriteAllText($global:PraGate.R10Path, $networkSource, (New-Object Text.UTF8Encoding($true))) + Get-Module PRA.Cloud, PraGateR9Network -All | Remove-Module -Force -ErrorAction SilentlyContinue + Import-Module $global:PraGate.R10Path -Global -Force + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Cloud.psm1') -Force -Global + $global:PraGate.R10Runtime = New-GateRuntime -Name 'review-320c' + function global:New-R10Anchor { param([string]$Guid) [Convert]::ToBase64String(([guid]$Guid).ToByteArray()) } + function global:New-R10Row { + param([string]$Upn = 'user1@gate.invalid', [string]$Guid = 'ab12cd34-0000-4000-8000-0000000000ef', [switch]$Shared) + $record = [ordered]@{ ObjectGuid = $Guid; UserPrincipalName = $Upn; SamAccountName = $Upn.Split('@')[0]; IsShared = [bool]$Shared; SourceAnchor = [ordered]@{ ObjectGuid = (New-R10Anchor $Guid); ConsistencyGuid = '' } } + New-PraRow $global:PraGate.R10Context ([pscustomobject]$record) + } + function global:New-R10Rows { param([int]$Count) @(1..$Count | ForEach-Object { New-R10Row -Upn "user$_@gate.invalid" -Guid ('00000000-0000-0000-0000-{0:000000000000}' -f $_) }) } + function global:New-R10Failure { + param([int]$Status, [int]$RetryAfter = 0, [string]$Text = '') + $exception = [System.Net.Http.HttpRequestException]::new($(if ($Text) { $Text } else { "Response status code does not indicate success: $Status." }), $null, [System.Net.HttpStatusCode]$Status) + if ($RetryAfter) { + $response = [System.Net.Http.HttpResponseMessage]::new([System.Net.HttpStatusCode]$Status) + $response.Headers.RetryAfter = [System.Net.Http.Headers.RetryConditionHeaderValue]::new([TimeSpan]::FromSeconds($RetryAfter)) + Add-Member -InputObject $exception -NotePropertyName Response -NotePropertyValue $response + } + $exception + } + function global:Invoke-R10Grant { + param([string]$Right, [hashtable]$Ids, [string]$Upn = 'shared1@gate.invalid') + $global:PraGate.R10Args = @{ Right = $Right; Ids = $Ids; Upn = $Upn } + InModuleScope PRA.Cloud { + $a = $global:PraGate.R10Args + $binding = @{ TenantId = '20000000-0000-0000-0000-000000000002'; ConnectionId = '30000000-0000-0000-0000-000000000003'; ModuleLocation = $global:PraGate.R10Path; ModulePath = $global:PraGate.R10Path } + $permit = @{ AllowMutation = $true; Approved = $true; Authorized = $true; JournalStarted = $true; Target = $a.Upn; Trustee = 'trustee1@gate.invalid'; Right = $a.Right; Action = 'Convert'; Mode = 'Apply'; Phase = 'Cloud' } + $p = @{ Upn = $a.Upn; Trustee = 'trustee1@gate.invalid'; Right = $a.Right; VerifiedObjectIds = $a.Ids; GrantVerifyAttempts = 2; GrantVerifyDelaySeconds = 1; AutoMapping = $false } + & $script:PraExoWorker 'Grant' $p $permit $binding { } $null + } + } + } + BeforeEach { + $context = New-GateContext $global:PraGate.R10Runtime -Mode Apply -Action Convert + $context.Phase = 'Cloud'; $context.Once = $false; $context.CheckScope = 'Both'; $context.IntervalMinutes = 0; $context.TimeoutMinutes = 5; $context.AllowMutation = $true + $context.Config.Cloud = @{ CheckMailbox = $true; CheckLicense = $false; MailboxCheckVia = 'Exo'; RequiredSkuPartNumber = ''; IdentityCheck = 'Off'; TenantId = '20000000-0000-0000-0000-000000000002' } + $context.Config.SharedMailbox = @{ Enabled = $true; PermissionSource = 'AD'; GrantFullAccess = $true; GrantSendAs = $false; GrantSendOnBehalf = $false; AutoMapping = $false } + $context.LogFile = Join-Path $global:PraGate.R10Runtime.Root ('logs\review-320c-' + [guid]::NewGuid().ToString('N').Substring(0, 8) + '.log') + $global:PraGate.R10Context = $context + $global:PraGate.R10Binding = @{ TenantId = '20000000-0000-0000-0000-000000000002'; ConnectionId = '30000000-0000-0000-0000-000000000003'; ModuleLocation = $global:PraGate.R10Path; ModulePath = $global:PraGate.R10Path } + $global:PraGate.R10 = @{ + Calls = New-Object 'Collections.Generic.List[string]'; Added = New-Object 'Collections.Generic.HashSet[string]'; NotFoundForm = ''; SignOutFails = $false; GraphCalls = 0; Grants = 0; Accounts = $null + Objects = @{ 'shared1@gate.invalid' = @{ Id = 'aaaaaaaa-0000-0000-0000-000000000001'; Smtp = 'shared1@gate.invalid'; Type = 'SharedMailbox'; Name = 'shared1'; Guid = [guid]'11111111-0000-0000-0000-000000000001' } + 'trustee1@gate.invalid' = @{ Id = 'bbbbbbbb-0000-0000-0000-000000000002'; Smtp = 'trustee1@gate.invalid'; Type = 'UserMailbox'; Name = 'trustee1'; Guid = [guid]'11111111-0000-0000-0000-000000000002' } } } + } + AfterAll { + Remove-Item -LiteralPath 'Function:\New-R10Anchor', 'Function:\New-R10Row', 'Function:\New-R10Rows', 'Function:\New-R10Failure', 'Function:\Invoke-R10Grant' -ErrorAction SilentlyContinue + Remove-Module PRA.Cloud, PraGateR10Network -Force -ErrorAction SilentlyContinue + foreach ($key in 'R10', 'R10Context', 'R10Binding', 'R10Runtime', 'R10Path', 'R10Args', 'R10Rows', 'R10Case', 'R10Cases', 'R10Inactive', 'R10Anchor') { $global:PraGate.Remove($key) } + } + It 'a grant is written with the confirmed Entra ids of the mailbox and of the trustee, and every read of the confirmed objects uses -ExternalDirectoryObjectId' -ForEach @( + @{ Right = 'FullAccess'; Add = 'Add-MailboxPermission|Identity=AAAAAAAA-0000-0000-0000-000000000001|User=BBBBBBBB-0000-0000-0000-000000000002' } + @{ Right = 'SendAs'; Add = 'Add-RecipientPermission|Identity=AAAAAAAA-0000-0000-0000-000000000001|Trustee=BBBBBBBB-0000-0000-0000-000000000002' } + @{ Right = 'SendOnBehalf'; Add = 'Set-Mailbox|Identity=AAAAAAAA-0000-0000-0000-000000000001|Add=BBBBBBBB-0000-0000-0000-000000000002' }) { + $result = Invoke-R10Grant -Right $Right -Ids @{ 'shared1@gate.invalid' = 'AAAAAAAA-0000-0000-0000-000000000001'; 'trustee1@gate.invalid' = 'BBBBBBBB-0000-0000-0000-000000000002' } + $result.Verified | Should -BeTrue + $calls = @($global:PraGate.R10.Calls) + @($calls | Where-Object { $_ -like 'Add-*' -or $_ -like 'Set-*' }) | Should -BeExactly @($Add) + @($calls | Where-Object { $_ -match '^Get-EXO' -and $_ -notmatch '\|EDOID=' }).Count | Should -Be 0 -Because ('every Exchange Online read of a confirmed object is by -ExternalDirectoryObjectId: ' + ($calls -join '; ')) + @($calls | Where-Object { $_ -match '\|UPN=|\|Filter=' }).Count | Should -Be 0 + } + It 'a grant is written with the UPN when no id is known, and a trustee without an id stays a UPN while the mailbox has its id' { + $none = Invoke-R10Grant -Right 'FullAccess' -Ids @{} -Upn 'Shared1@Gate.Invalid' + $none.Verified | Should -BeTrue + @($global:PraGate.R10.Calls | Where-Object { $_ -like 'Add-*' }) | Should -BeExactly @('Add-MailboxPermission|Identity=Shared1@Gate.Invalid|User=trustee1@gate.invalid') + @($global:PraGate.R10.Calls) | Should -Contain 'Get-EXORecipient|UPN=Shared1@Gate.Invalid' + $global:PraGate.R10.Calls.Clear(); [void]$global:PraGate.R10.Added.Clear() + $mixed = Invoke-R10Grant -Right 'SendAs' -Ids @{ 'shared1@gate.invalid' = 'aaaaaaaa-0000-0000-0000-000000000001' } + $mixed.Verified | Should -BeTrue + @($global:PraGate.R10.Calls | Where-Object { $_ -like 'Add-*' }) | Should -BeExactly @('Add-RecipientPermission|Identity=aaaaaaaa-0000-0000-0000-000000000001|Trustee=trustee1@gate.invalid') + } + It 'an object that Exchange Online does not find by its id is "not found" for a GUID in each text it uses, whatever the letter case of the echoed id' -ForEach @( + @{ Form = "The operation couldn't be performed because object '{0}' couldn't be found on 'SYNTH'." } + @{ Form = ("The operation couldn't be performed because object '{0}' couldn" + [char]0x2019 + "t be found on 'SYNTH'.") } + @{ Form = "Couldn't find object ""{0}"". Please make sure that it was spelled correctly or specify a different object." }) { + $global:PraGate.R10.NotFoundForm = $Form + $global:PraGate.R10.Objects = @{} + $answers = InModuleScope PRA.Cloud { + $ids = @{ 'user9@gate.invalid' = 'CCCCCCCC-0000-0000-0000-000000000009' } + @{ Recipient = (& $script:PraExoWorker 'Recipient' @{ Upn = 'user9@gate.invalid'; VerifiedObjectIds = $ids } $null $global:PraGate.R10Binding $null $null) + Mailbox = (& $script:PraExoWorker 'Mailbox' @{ Upn = 'user9@gate.invalid'; VerifiedObjectIds = $ids } $null $global:PraGate.R10Binding $null $null) } + } + $answers.Recipient.Found | Should -BeFalse + $answers.Mailbox.Found | Should -BeFalse + } + It 'a 404 that names another object is not "not found" for the object that was asked for (the read stops)' { + $global:PraGate.R10.NotFoundForm = "The operation couldn't be performed because object 'somebody-else' couldn't be found on 'SYNTH'. {0}" + $global:PraGate.R10.Objects = @{} + $message = InModuleScope PRA.Cloud { + try { $null = & $script:PraExoWorker 'Recipient' @{ Upn = 'user9@gate.invalid'; VerifiedObjectIds = @{ 'user9@gate.invalid' = 'CCCCCCCC-0000-0000-0000-000000000009' } } $null $global:PraGate.R10Binding $null $null; '' } catch { $_.Exception.Message } + } + $message | Should -Match 'HttpStatusCode=404' + } + It 'with a confirmed account, an inactive mailbox found by UPN that carries another ExternalDirectoryObjectId belongs to an earlier account and is told apart, the own one is taken; without an account, several are an ambiguity with the command that lists them' { + $global:PraGate.R10Cases = @{ + Foreign = @([pscustomobject]@{ RecipientTypeDetails = 'UserMailbox'; EmailAddresses = [string[]]@('SMTP:user1@gate.invalid'); ExternalDirectoryObjectId = 'dddddddd-0000-0000-0000-000000000001'; IsInactiveMailbox = $true; InPlaceHolds = @('mbx40000000000000000000000000000004') }) + Own = @([pscustomobject]@{ RecipientTypeDetails = 'UserMailbox'; EmailAddresses = [string[]]@('SMTP:user1@gate.invalid'); ExternalDirectoryObjectId = 'dddddddd-0000-0000-0000-000000000001'; IsInactiveMailbox = $true; InPlaceHolds = @('mbx40000000000000000000000000000001') }, + [pscustomobject]@{ RecipientTypeDetails = 'UserMailbox'; EmailAddresses = [string[]]@('SMTP:user1@gate.invalid'); ExternalDirectoryObjectId = 'AAAAAAAA-0000-0000-0000-000000000001'; IsInactiveMailbox = $true; InPlaceHolds = @('mbx40000000000000000000000000000002') }) + Two = @(1..2 | ForEach-Object { [pscustomobject]@{ RecipientTypeDetails = 'UserMailbox'; EmailAddresses = [string[]]@('SMTP:user1@gate.invalid'); ExternalDirectoryObjectId = ('dddddddd-0000-0000-0000-00000000000' + $_); IsInactiveMailbox = $true; InPlaceHolds = @() } }) } + $result = InModuleScope PRA.Cloud { + Mock Get-EXOMailbox { + param($Identity, $ExternalDirectoryObjectId, $UserPrincipalName, $Filter, $Properties, $ResultSize, $InactiveMailboxOnly) + if ($Identity -or $ExternalDirectoryObjectId) { throw "The operation couldn't be performed because object 'x' couldn't be found on 'y'." } + if ($InactiveMailboxOnly) { $global:PraGate.R10Inactive } + } + $confirmed = @{ 'user1@gate.invalid' = 'aaaaaaaa-0000-0000-0000-000000000001' } + $answers = @{} + foreach ($case in @(@('Foreign', $confirmed), @('Own', $confirmed), @('Two', @{}))) { + $global:PraGate.R10Inactive = $global:PraGate.R10Cases[$case[0]] + try { $answers[$case[0]] = & $script:PraExoWorker 'Hold' @{ Upn = 'user1@gate.invalid'; VerifiedObjectIds = $case[1] } $null $global:PraGate.R10Binding $null $null } + catch { $answers[$case[0]] = $_.Exception.Message } + } + $answers + } + $result.Foreign.Found | Should -BeFalse + $result.Foreign.EarlierAccount | Should -BeTrue + $result.Own.Found | Should -BeTrue + @($result.Own.Holds) | Should -BeExactly @('mbx40000000000000000000000000000002') -Because 'only the mailbox of the confirmed account decides' + [bool]$result.Own.IdentityByUpn | Should -BeFalse + $result.Two | Should -Match 'Exchange Online has 2 inactive mailboxes for user1@gate\.invalid and nothing tells which one belongs to this object' + $result.Two | Should -Match ([regex]::Escape('To list them, run: Get-EXOMailbox -InactiveMailboxOnly -Filter "UserPrincipalName -eq ''user1@gate.invalid''" -Properties ExternalDirectoryObjectId,WhenSoftDeleted,InPlaceHolds')) + } + It 'the retention check reports an inactive mailbox of an earlier account as not this object''s mailbox: a warning, not covered, never a verdict from that mailbox' { + $context = New-GateContext $global:PraGate.R10Runtime -Mode Preview -Action Check + $context.Config.Cloud = @{ CheckMailbox = $true; CheckLicense = $false; MailboxCheckVia = 'Exo'; RequiredSkuPartNumber = ''; IdentityCheck = 'Off'; TenantId = '20000000-0000-0000-0000-000000000002' } + $context.Config.Retention = @{ Enabled = $true; PolicyGuid = '40000000-0000-0000-0000-000000000004'; PolicyName = ''; UseComplianceSession = $false } + $context.LogFile = Join-Path $global:PraGate.R10Runtime.Root 'logs\retention-earlier.log' + $global:PraGate.R10Context = $context; $global:PraGate.R10Rows = @(New-R10Row) + InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { param($Context) $Context['_PraCloudSession'] = @{ Graph = $false; Exo = $true; Subprocess = $false; Binding = $global:PraGate.R10Binding } } + Mock Close-PraCloudSession { } + Mock Invoke-PraExo { @{ Found = $false; Type = $null; Holds = @(); IsInactive = $false; Litigation = $false; RetentionHold = $false; EarlierAccount = $true } } + Invoke-PraRetentionCheck $global:PraGate.R10Context $global:PraGate.R10Rows + } + $row = $global:PraGate.R10Rows[0] + $row.CloudStatus | Should -BeExactly 'Error' + $row.Warnings | Should -Match 'user1@gate\.invalid: not this object''s mailbox\. Exchange Online has an inactive mailbox with this UPN, but it belongs to an earlier account' + $row.Warnings | Should -Match ([regex]::Escape('Get-EXOMailbox -InactiveMailboxOnly -Filter "UserPrincipalName -eq ''user1@gate.invalid''"')) + $context.Warnings | Should -Be 1 + $context.Issues.Count | Should -Be 1 + [string]$context.Issues[0].Message | Should -Match 'Not covered by the policy: the only inactive mailbox with this UPN is not this object''s mailbox' + } + It 'a failure that ends the cloud phase half way keeps the rows that finished and makes an error only of the others' { + $global:PraGate.R10Rows = New-R10Rows 3 + InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { param($Context) $Context['_PraCloudSession'] = @{ Graph = $false; Exo = $true; Subprocess = $false; Binding = $global:PraGate.R10Binding } } + Mock Close-PraCloudSession { } + Mock Start-Sleep { } + Mock Write-PraProgress { throw 'SYNTHETIC failure after the first check' } + Mock Invoke-PraExo { if ($Params.Upn -ceq 'user1@gate.invalid') { @{ Found = $true; Type = 'UserMailbox'; HasAddresses = $false; Addresses = @() } } else { @{ Found = $false; Type = $null } } } + Invoke-PraCloudPhase $global:PraGate.R10Context $global:PraGate.R10Rows 'Convert' + } + $rows = $global:PraGate.R10Rows + $rows[0].CloudStatus | Should -BeExactly 'Success' + $rows[0].FinalStatus | Should -BeExactly 'Success' + $rows[1].CloudStatus | Should -BeExactly 'Error' + $rows[2].CloudStatus | Should -BeExactly 'Error' + $global:PraGate.R10Context.Issues.Count | Should -Be 2 -Because 'one error for each row that did not finish, none for the row that did' + [string]$global:PraGate.R10Context.Issues[0].Message | Should -Match 'SYNTHETIC failure after the first check' + } + It 'a run stop that comes before the loop (the sign-in, the policy lookup) is ONE error and the rows stay Pending, in the cloud phase and in the retention check' { + $global:PraGate.R10Rows = New-R10Rows 4 + InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { param($Context) Stop-PraCloudRun -Context $Context } + Mock Close-PraCloudSession { } + Invoke-PraCloudPhase $global:PraGate.R10Context $global:PraGate.R10Rows 'Convert' + } + $context = $global:PraGate.R10Context + $context.Issues.Count | Should -Be 1 + [string]$context.Issues[0].Message | Should -Match 'did not answer \(network\).* 4 object\(s\) were not finished\.$' + @($global:PraGate.R10Rows | Where-Object { $_.CloudStatus -ceq 'Pending' -and $_.FinalStatus -ceq 'Pending' }).Count | Should -Be 4 + $retention = New-GateContext $global:PraGate.R10Runtime -Mode Preview -Action Check + $retention.Config.Cloud = @{ CheckMailbox = $true; MailboxCheckVia = 'Exo'; IdentityCheck = 'Off'; TenantId = '20000000-0000-0000-0000-000000000002'; AppId = ''; RetryBudgetRunMinutes = 1; RetryBudgetObjectSeconds = 3600 } + $retention.Config.Retention = @{ Enabled = $true; PolicyGuid = ''; PolicyName = 'Policy1'; UseComplianceSession = $true } + $retention.LogFile = Join-Path $global:PraGate.R10Runtime.Root 'logs\retention-policy-stop.log' + $global:PraGate.R10Context = $retention; $global:PraGate.R10Rows = New-R10Rows 4 + InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { param($Context) $Context['_PraCloudSession'] = @{ Graph = $false; Exo = $true; Subprocess = $false; Binding = $global:PraGate.R10Binding; OwnedExoIds = @(); ExoAttempted = $false } } + Mock Close-PraCloudSession { } + Mock Start-Sleep { } + Mock Get-RetentionCompliancePolicy { throw (New-R10Failure -Status 429 -RetryAfter 30) } + Invoke-PraRetentionCheck $global:PraGate.R10Context $global:PraGate.R10Rows + } + $retention.Issues.Count | Should -Be 1 + [string]$retention.Issues[0].Message | Should -Match 'allowed for retries are used up .* 4 object\(s\) were not checked\.$' + @($global:PraGate.R10Rows | Where-Object { $_.CloudStatus -ceq 'Pending' -and $_.FinalStatus -ceq 'Pending' }).Count | Should -Be 4 + @($global:PraGate.R10Rows | Where-Object { $_.CloudStatus -ceq 'Error' }).Count | Should -Be 0 + } + It 'a failure of the sign-out at the end of the phase is a warning, never an error of an object: the rows keep their result' { + $global:PraGate.R10Rows = New-R10Rows 2 + InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { param($Context) $Context['_PraCloudSession'] = @{ Graph = $false; Exo = $true; Subprocess = $false; Binding = $global:PraGate.R10Binding } } + Mock Close-PraCloudSession { throw 'SYNTHETIC sign-out refused' } + Mock Invoke-PraExo { @{ Found = $true; Type = 'UserMailbox'; HasAddresses = $false; Addresses = @() } } + Invoke-PraCloudPhase $global:PraGate.R10Context $global:PraGate.R10Rows 'Convert' + } + $context = $global:PraGate.R10Context + $context.Issues.Count | Should -Be 0 + $context.Warnings | Should -Be 1 + @($global:PraGate.R10Rows | Where-Object { $_.CloudStatus -ceq 'Success' }).Count | Should -Be 2 + } + It 'Close-PraCloudSession does not throw when a sign-out fails: one warning for the run with the command to close the session, no error' { + $closing = $global:PraGate.R10Context + $closing['_PraCloudSession'] = @{ ExoAttempted = $true; Exo = $true; OwnedExoIds = @('30000000-0000-0000-0000-000000000003'); GraphAttempted = $false; Graph = $false; Verified = @{}; IdentityCache = @{} } + $global:PraGate.R10.SignOutFails = $true + { Close-PraCloudSession $closing } | Should -Not -Throw + { Close-PraCloudSession $closing } | Should -Not -Throw + $closing.Issues.Count | Should -Be 0 + $closing.Warnings | Should -Be 1 -Because 'one warning for the run, not one for each call' + [string](@(Get-PraList $closing 'WarningList')[0].Message) | Should -Match 'The sign-out of Microsoft 365 failed \(Exchange Online sign-out: SYNTHETIC sign-out refused\)\. .* Disconnect-ExchangeOnline -Confirm:\$false; Disconnect-MgGraph$' + $closing.CloudConnectFailed | Should -BeFalse + } + It 'Write-PraUnfinishedFailure keeps a row that finished; a run stop leaves the others Pending under ONE error, another failure is an error for each unfinished row (retention wording "checked")' { + $global:PraGate.R10Rows = New-R10Rows 4 + $global:PraGate.R10Rows[0].CloudStatus = 'Success'; $global:PraGate.R10Rows[0].FinalStatus = 'Success' + $global:PraGate.R10Rows[1].CloudStatus = 'Error'; $global:PraGate.R10Rows[1].FinalStatus = 'Error' + $global:PraGate.R10Rows[2].CloudStatus = 'Pending'; $global:PraGate.R10Rows[3].CloudStatus = 'Pending' + InModuleScope PRA.Cloud { + $failure = [Management.Automation.ErrorRecord]::new([InvalidOperationException]::new('SYNTHETIC other failure'), 'x', [Management.Automation.ErrorCategory]::NotSpecified, $null) + Write-PraUnfinishedFailure -Context $global:PraGate.R10Context -Rows $global:PraGate.R10Rows -ErrorRecord $failure -What 'checked' + } + $global:PraGate.R10Context.Issues.Count | Should -Be 2 + $global:PraGate.R10Rows[0].CloudStatus | Should -BeExactly 'Success' + $global:PraGate.R10Rows[1].CloudStatus | Should -BeExactly 'Error' + $global:PraGate.R10Rows[2].CloudStatus | Should -BeExactly 'Error' + $global:PraGate.R10Rows[3].CloudStatus | Should -BeExactly 'Error' + $stop = New-GateContext $global:PraGate.R10Runtime -Mode Preview -Action Check + $stop.LogFile = Join-Path $global:PraGate.R10Runtime.Root 'logs\unfinished.log' + $global:PraGate.R10Context = $stop; $global:PraGate.R10Rows = New-R10Rows 3 + $global:PraGate.R10Rows[0].CloudStatus = 'Success'; $global:PraGate.R10Rows[0].FinalStatus = 'Success' + InModuleScope PRA.Cloud { + try { Stop-PraCloudRun -Context $global:PraGate.R10Context } catch { $global:PraGate.R10Failure = $_ } + Write-PraUnfinishedFailure -Context $global:PraGate.R10Context -Rows $global:PraGate.R10Rows -ErrorRecord $global:PraGate.R10Failure -What 'checked' + } + $stop.Issues.Count | Should -Be 1 + [string]$stop.Issues[0].Message | Should -Match ' 2 object\(s\) were not checked\.$' + $global:PraGate.R10Rows[0].CloudStatus | Should -BeExactly 'Success' + @($global:PraGate.R10Rows | Where-Object { $_.CloudStatus -ceq 'Pending' -and $_.FinalStatus -ceq 'Pending' }).Count | Should -Be 2 + $global:PraGate.Remove('R10Failure') + } + It 'a Graph refusal (, identity check ) stops the run once: ONE error, the rows not reached stay Pending, Microsoft Graph is asked once' -ForEach @( + @{ Status = 403; Check = 'Anchor'; Licence = $false; Text = 'Insufficient privileges to complete the operation.'; Expect = 'permission User\.Read\.All: with a sign-in by a person' } + @{ Status = 401; Check = 'Anchor'; Licence = $false; Text = 'Response status code does not indicate success: 401 (Unauthorized).'; Expect = 'the sign-in expired or was refused\. Nothing was changed\. Sign in again: run the same command again' } + @{ Status = 403; Check = 'Off'; Licence = $true; Text = 'Insufficient privileges to complete the operation.'; Expect = 'permission User\.Read\.All: with a sign-in by a person' }) { + $global:PraGate.R10Context.Config.Cloud = @{ CheckMailbox = (-not $Licence); CheckLicense = $Licence; MailboxCheckVia = 'Exo'; RequiredSkuPartNumber = ''; IdentityCheck = $Check; TenantId = '20000000-0000-0000-0000-000000000002' } + $global:PraGate.R10Rows = New-R10Rows 5 + $global:PraGate.R10Case = @{ Status = $Status; Text = $Text } + InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { param($Context) $Context['_PraCloudSession'] = @{ Graph = $true; Exo = $true; Subprocess = $false; Binding = $global:PraGate.R10Binding } } + Mock Assert-PraGraphSession { } + Mock Close-PraCloudSession { } + Mock Start-Sleep { } + Mock Invoke-PraExo { @{ Found = $true; Type = 'UserMailbox'; HasAddresses = $false; Addresses = @() } } + Mock Get-MgUser { $global:PraGate.R10.GraphCalls++; throw (New-R10Failure -Status $global:PraGate.R10Case.Status -Text $global:PraGate.R10Case.Text) } + Invoke-PraCloudPhase $global:PraGate.R10Context $global:PraGate.R10Rows 'Convert' + } + $context = $global:PraGate.R10Context; $rows = $global:PraGate.R10Rows + $global:PraGate.R10.GraphCalls | Should -Be 1 + $context.Issues.Count | Should -Be 1 + [string]$context.Issues[0].Message | Should -Match $Expect + if ($Status -eq 401) { [string]$context.Issues[0].Message | Should -Not -Match 'User\.Read\.All' } else { [string]$context.Issues[0].Message | Should -Not -Match 'expired' } + $rows[0].CloudStatus | Should -BeExactly 'Error' + @($rows[1..4] | Where-Object { $_.CloudStatus -ceq 'Pending' -and $_.FinalStatus -ceq 'Pending' }).Count | Should -Be 4 + } + It 'the retention check stops once on a Graph refusal too, and the rows not reached stay Pending' { + $context = New-GateContext $global:PraGate.R10Runtime -Mode Preview -Action Check + $context.Config.Cloud = @{ CheckMailbox = $true; MailboxCheckVia = 'Exo'; IdentityCheck = 'Anchor'; TenantId = '20000000-0000-0000-0000-000000000002' } + $context.Config.Retention = @{ Enabled = $true; PolicyGuid = '40000000-0000-0000-0000-000000000004'; PolicyName = ''; UseComplianceSession = $false } + $context.LogFile = Join-Path $global:PraGate.R10Runtime.Root 'logs\retention-refused.log' + $global:PraGate.R10Context = $context; $global:PraGate.R10Rows = New-R10Rows 4 + InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { param($Context) $Context['_PraCloudSession'] = @{ Graph = $true; Exo = $true; Subprocess = $false; Binding = $global:PraGate.R10Binding } } + Mock Assert-PraGraphSession { } + Mock Close-PraCloudSession { } + Mock Get-MgUser { $global:PraGate.R10.GraphCalls++; throw (New-R10Failure -Status 403 -Text 'Insufficient privileges to complete the operation.') } + Invoke-PraRetentionCheck $global:PraGate.R10Context $global:PraGate.R10Rows + } + $global:PraGate.R10.GraphCalls | Should -Be 1 + $context.Issues.Count | Should -Be 1 + [string]$context.Issues[0].Message | Should -Match 'permission User\.Read\.All' + $global:PraGate.R10Rows[0].CloudStatus | Should -BeExactly 'Error' + @($global:PraGate.R10Rows[1..3] | Where-Object { $_.CloudStatus -ceq 'Pending' -and $_.FinalStatus -ceq 'Pending' }).Count | Should -Be 3 + } + It 'a grant already sent in this run is never sent again, whatever a later read shows, in any letter case; it is said at Detail' { + $global:PraGate.R10Rows = @(New-R10Row -Upn 'shared1@gate.invalid' -Shared) + Add-Member -InputObject $global:PraGate.R10Rows[0] -NotePropertyName ADVerified -NotePropertyValue $true -Force + $context = $global:PraGate.R10Context + $context.Approval = { param($Target, $Operation) $true } + $context.AssertCloudAuthorization = { param($Row) $true } + $context.JournalMutation = { param($Target, $Operation, $Status, $Detail) } + InModuleScope PRA.Cloud { + Mock Invoke-PraExo { + if ($Operation -ceq 'Grant') { $global:PraGate.R10.Grants++; @{ TrusteeFound = $true; Verified = $true; Mutated = $true; Error = '' } } + else { @{ TrusteeFound = $true; Verified = $false; Mutated = $false } } + } + $row = $global:PraGate.R10Rows[0] + $null = Invoke-PraSharedPermission -Context $global:PraGate.R10Context -Row $row -Requests @([pscustomobject]@{ Right = 'FullAccess'; Trustee = 'trustee1@gate.invalid' }) + $null = Invoke-PraSharedPermission -Context $global:PraGate.R10Context -Row $row -Requests @([pscustomobject]@{ Right = 'FullAccess'; Trustee = 'TRUSTEE1@Gate.Invalid' }) + } + $global:PraGate.R10.Grants | Should -Be 1 -Because 'the second check read the permission as missing again, and did not send it again' + $context.GrantsSent | Should -Be 1 + [IO.File]::ReadAllText($context.LogFile) | Should -Match 'shared1@gate\.invalid: FullAccess to TRUSTEE1@Gate\.Invalid was already sent in this run; it is not sent again although the last read does not show it yet' + } + It 'the account of the identity check is used once for the Graph facts and never kept after a failure: the next check reads again' { + $context = $global:PraGate.R10Context + $context.Config.Cloud = @{ CheckMailbox = $true; CheckLicense = $false; MailboxCheckVia = 'Graph'; RequiredSkuPartNumber = ''; IdentityCheck = 'Anchor'; TenantId = '20000000-0000-0000-0000-000000000002' } + $global:PraGate.R10Rows = @(New-R10Row) + $global:PraGate.R10Anchor = New-R10Anchor 'ab12cd34-0000-4000-8000-0000000000ef' + $global:PraGate.R10.Accounts = New-Object 'Collections.Generic.List[bool]' + InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { param($Context) $Context['_PraCloudSession'] = @{ Graph = $true; Exo = $false; Subprocess = $false; Binding = $null } } + Mock Assert-PraGraphSession { } + Mock Close-PraCloudSession { } + Mock Start-Sleep { } + Mock Get-MgUser { param($UserId, $Filter, $Property) [pscustomobject]@{ Id = 'aaaaaaaa-0000-0000-0000-000000000001'; UserPrincipalName = $UserId; OnPremisesImmutableId = $global:PraGate.R10Anchor; OnPremisesSyncEnabled = $true; assignedPlans = @([pscustomobject]@{ Service = 'exchange'; CapabilityStatus = 'Enabled' }); provisionedPlans = @([pscustomobject]@{ Service = 'exchange'; ProvisioningStatus = 'Success' }); assignedLicenses = @() } } + Mock Get-MgUserLicenseDetail { @() } + Mock Get-PraGraphFact { + param($Context, $Upn, $Mailbox, $License, $Addresses, $Account) + $global:PraGate.R10.Accounts.Add(($null -ne $Account)) + if ($global:PraGate.R10.Accounts.Count -eq 1) { throw (New-R10Failure -Status 503) } + @{ Enabled = $true; Provisioned = $true; LicenseCount = 0; RequiredSku = ''; RequiredSkuOk = $true; Detail = ''; Addresses = [string[]]@() } + } + Invoke-PraCloudPhase $global:PraGate.R10Context $global:PraGate.R10Rows 'Convert' + } + @($global:PraGate.R10.Accounts) | Should -BeExactly @($true, $false) -Because 'the first read got the account of the identity check, the second was not given a kept one' + $global:PraGate.R10Rows[0].CloudStatus | Should -BeExactly 'Success' + } + It 'a Graph account other than the confirmed one is refused with a next step that names the account to look at' { + $global:PraGate.R10Case = @{ Other = 'cccccccc-0000-0000-0000-000000000003' } + $message = InModuleScope PRA.Cloud { + Mock Assert-PraGraphSession { } + Mock Get-MgUser { [pscustomobject]@{ Id = $global:PraGate.R10Case.Other; assignedPlans = @(); provisionedPlans = @(); assignedLicenses = @() } } + $session = Get-PraCloudSession $global:PraGate.R10Context + $session.Graph = $true; $session.Verified['user1@gate.invalid'] = 'aaaaaaaa-0000-0000-0000-000000000001' + try { Get-PraGraphFact -Context $global:PraGate.R10Context -Upn 'user1@gate.invalid' -Mailbox $true -License $false; '' } catch { $_.Exception.Message } + } + $message | Should -Match 'Microsoft Graph returned another account than the one confirmed for this object: user1@gate\.invalid\. Nothing was changed on it\. Run the same command again' + $message | Should -Match ([regex]::Escape('Get-MgUser -UserId aaaaaaaa-0000-0000-0000-000000000001 -Property Id,UserPrincipalName,OnPremisesImmutableId')) + } +} + +Describe 'Release 3.2.0 - review of the journal fallback and the phase data limits (production Directory and Common modules, synthetic folders)' -Tag 'Release320c' { + BeforeAll { Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Common.psm1') -Force -Global } + It 'a journal line that is damaged counts as skipped even when it starts with a brace: not JSON, cut short, or without its Operation, Status and Target; blank lines are not damage; the count is given back' { + $path = Join-Path $global:PraGate.Root ('journal-damage-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.jsonl') + $lines = @( + '{"RunId":"r","Utc":"u","Target":"AAAAAAAA-0000-0000-0000-000000000001","Operation":"Set-ADUser","Status":"Started","Detail":""}' + '' + '{"RunId":"r","Utc":"u","Target":"AAAAAAAA-0000-0000-0000-000000000001","Operation":"Set-ADUser","Status":"Verified","Detail":""}' + '{"RunId":"r","Utc":"u","Target":"AAAAAAAA-0000-0000-0000-000000000002","Operation":"Set-ADUser","Status":"Verified"' + '{"RunId":"r","Utc":"u","Detail":"no target, no operation, no status"}' + '{"RunId":"r","Utc":"u","Operation":"Set-ADUser","Status":"Started","Detail":"a write without its target"}' + '{"RunId":"r","Utc":"u","Target":"AAAAAAAA-0000-0000-0000-000000000003","Operation":"Set-ADUser","Status":"Applied","Detail":""}') + [IO.File]::WriteAllText($path, ($lines -join "`r`n"), (New-Object Text.UTF8Encoding($false))) + $global:PraGate.R10Path2 = $path + $result = InModuleScope PRA.Directory { + $skipped = 0 + $set = Get-PraJournalTouchedObject -Path $global:PraGate.R10Path2 -SkippedCount ([ref]$skipped) + @{ Set = (@($set | Sort-Object) -join ','); Skipped = $skipped } + } + $result.Set | Should -BeExactly 'AAAAAAAA-0000-0000-0000-000000000001,AAAAAAAA-0000-0000-0000-000000000003' + $result.Skipped | Should -Be 3 -Because 'the cut Verified line, the line without its fields, and the write without its target' + $clean = Join-Path $global:PraGate.Root ('journal-clean-' + [guid]::NewGuid().ToString('N').Substring(0, 6) + '.jsonl') + [IO.File]::WriteAllText($clean, ($lines[0] + "`r`n`r`n" + $lines[2] + "`r`n"), (New-Object Text.UTF8Encoding($false))) + $global:PraGate.R10Path2 = $clean + (InModuleScope PRA.Directory { $skipped = -1; $null = Get-PraJournalTouchedObject -Path $global:PraGate.R10Path2 -SkippedCount ([ref]$skipped); $skipped }) | Should -Be 0 + $global:PraGate.Remove('R10Path2') + } + It 'the warning about skipped journal lines ends with the command that names an object (the Preview of the Recover first) and the manual restore' { + $path = Join-Path $global:PraGate.Root ('Journal-a1b2c3d4e5f60718293a4b5c6d7e8f90.jsonl') + [IO.File]::WriteAllText($path, "garbage`r`n", (New-Object Text.UTF8Encoding($false))) + $global:PraGate.R10Path2 = $path + $context = @{ Warnings = 0; WarningList = (New-Object 'Collections.Generic.List[object]'); CurrentIdentity = ''; LogFile = ''; CommandLineFor = { param([string]$ActionName, [string]$PhaseName, [string]$BatchId) ('.\Invoke-PraRemoteMailbox.ps1 -Action {0} -Mode Apply -Batch {1} -ConfigPath ''C:\x.psd1''' -f $ActionName, $BatchId) } } + $global:PraGate.R10Context = $context + InModuleScope PRA.Directory { + Mock Write-PraItem { $global:PraGate.R10Warning = $Text } + $null = Get-PraJournalTouchedObject -Path $global:PraGate.R10Path2 -Context $global:PraGate.R10Context + } + $global:PraGate.R10Warning | Should -Match '^1 line\(s\) of the journal Journal-a1b2c3d4e5f60718293a4b5c6d7e8f90\.jsonl cannot be read and were skipped' + $global:PraGate.R10Warning | Should -Match ([regex]::Escape('with its Preview first: .\Invoke-PraRemoteMailbox.ps1 -Action Recover -Batch a1b2c3d4 -ConfigPath ''C:\x.psd1'' -Identity , then the same command with -Mode Apply.')) + $global:PraGate.R10Warning | Should -Match 'Or restore it by hand from the backup file of the batch\.$' + foreach ($key in 'R10Path2', 'R10Context', 'R10Warning') { $global:PraGate.Remove($key) } + } + It 'a Recover batch whose journal has a line that cannot be read counts as having rolled back every object, so a Convert is refused rather than guessed' { + $root = Join-Path $global:PraGate.Root ('recover-damaged-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) + $hash = 'ef' * 32; $id = 'a1a1a1a1b2b2b2b2c3c3c3c3d4d4d4d4' + $folder = Join-Path $root ('Batch-' + $id); $null = New-Item -ItemType Directory -Path $folder -Force + $head = [ordered]@{ SchemaVersion = 3; RawFormat = 'PraDataOnlyClixml-v1'; Operation = 'Recover'; RunId = 'r'; BatchId = $id; Environment = 'SYNTHETIC_GATE'; Server = 's'; NamingContext = 'n'; CreatedUtc = 'u'; RawFile = 'x.clixml'; RawHash = 'h'; SourceBackupHash = $hash; Records = @(@{ ObjectGuid = '11111111-1111-1111-1111-111111111111' }) } + [IO.File]::WriteAllText((Join-Path $folder ('Recover-SYNTHETIC_GATE-20261116_120000-' + $id.Substring(0, 8) + '.json')), ($head | ConvertTo-Json -Depth 5), (New-Object Text.UTF8Encoding($true))) + $good = '{"RunId":"r","Utc":"u","Target":"11111111-1111-1111-1111-111111111111","Operation":"Set-ADUser","Status":"Started","Detail":""}' + $global:PraGate.R10Case = @{ Root = $root; Hash = $hash; Journal = (Join-Path $folder ('Journal-' + $id + '.jsonl')) } + $find = { + param($Lines, $Object) + [IO.File]::WriteAllText($global:PraGate.R10Case.Journal, ($Lines -join "`r`n"), (New-Object Text.UTF8Encoding($true))) + $global:PraGate.R10Case.Object = $Object + InModuleScope PRA.Directory { + $context = @{ Config = @{ Environment = 'SYNTHETIC_GATE'; Storage = @{ BackupFolder = $global:PraGate.R10Case.Root } } } + Find-PraRecoverOfBatch $context $global:PraGate.R10Case.Hash ([string[]]@($global:PraGate.R10Case.Object)) + } + } + (& $find @($good) '22222222-2222-2222-2222-222222222222') | Should -BeNullOrEmpty -Because 'a whole journal that never names the object says it was not rolled back' + $damaged = & $find @($good, '{"RunId":"r","Utc":"u","Target":"3333') '22222222-2222-2222-2222-222222222222' + $damaged.Basis | Should -BeExactly 'Damaged' -Because 'a line that cannot be read may be the write of that object' + $damaged.ShortId | Should -BeExactly 'a1a1a1a1' + $global:PraGate.Remove('R10Case') + } + It 'the phase data limits: one file at most MaxFileBytes (the size the writer can produce, a quarter of the total), the files of one report together at most MaxBytes, with the reason and the way out' { + InModuleScope PRA.Common { + $script:PraPhaseLimits.MaxFileBytes | Should -Be 67108864 + $script:PraPhaseLimits.MaxFileBytes | Should -Be ($script:PraPhaseLimits.MaxBytes / 4) + } + $root = Join-Path $global:PraGate.Root ('limits-phase-' + [guid]::NewGuid().ToString('N').Substring(0, 6)) + $make = { + param($Name) + $folder = Join-Path $root $Name; $null = New-Item -ItemType Directory -Path $folder -Force + $context = @{ Root = $global:PraGate.Package; Version = '3.2.0'; RunId = ((Get-Date -Format 'yyyyMMdd_HHmmss') + '-' + [guid]::NewGuid().ToString('N')); StartTime = Get-Date; Action = 'Convert'; Mode = 'Apply'; Phase = 'AD' + CurrentPhase = 'Start'; CurrentOperation = ''; CurrentIdentity = ''; StepIndex = 0; StepTotal = 0; Warnings = 0; Issues = (New-Object 'Collections.Generic.List[object]'); Rows = (New-Object 'Collections.Generic.List[object]') + Server = 'dc01.contoso.com'; Config = @{ Environment = 'GATE' }; AllowMutation = $true; ReportFolder = (Join-Path $root 'reports'); NoReport = $true; BatchId = 'abcd1234'; LogFile = ''; NextSteps = @(); ExitCode = 0; CloudConnectFailed = $false; ResultStatus = ''; PhaseFolders = @(); ConfigOverrides = @() } + $guid = [guid]::NewGuid().ToString() + $context.Rows.Add([pscustomobject]@{ ObjectGuid = $guid; SamAccountName = 'alice'; UserPrincipalName = 'alice@contoso.com'; Action = 'Convert'; IsShared = $false; ADApplied = $true; ADVerified = $true; BackupPath = 'D:\x.json'; CloudStatus = 'N/A'; CloudDetail = ''; FinalStatus = 'Pending'; Detail = 'd'; Warnings = ''; LastOperation = ''; GroupAction = ''; CloudMailbox = $null; CloudLicense = $null; PreserveCloudMailbox = $false; PreserveLicense = $false; DeprovisionConfirmed = $false; PermDetail = ''; PermMissing = @() }) + Register-PraObjectName $context $guid 'alice@contoso.com' + $context.CurrentIdentity = $guid + Write-PraStep -Context $context -Title 'Backup and Active Directory changes' | Out-Null + foreach ($i in 1..40) { Write-PraItem -Context $context -Status Ok -Text ('step {0} {1}' -f $i, ('x' * 280)) } + @{ Context = $context; Folder = $folder } + } + $one = & $make 'one' + $small = Save-PraPhaseData -Context $one.Context -Folder $one.Folder + $fullBytes = ([IO.FileInfo]$small).Length + $lessBytes = (New-Object Text.UTF8Encoding($false)).GetByteCount(((New-PraPhaseRecord -Context $one.Context -NoSteps) | ConvertTo-Json -Depth 8 -Compress)) + $fullBytes | Should -BeGreaterThan ($lessBytes + 2000) -Because 'the steps make the file larger, so a limit can fall between the two' + $global:PraGate.R10Case = @{ File = $fullBytes; Less = $lessBytes; Folder = $one.Folder; Context = $one.Context; Second = (& $make 'two'); Third = (& $make 'three') } + InModuleScope PRA.Common { + $case = $global:PraGate.R10Case + $saved = @{ File = $script:PraPhaseLimits.MaxFileBytes; Total = $script:PraPhaseLimits.MaxBytes } + try { + # The writer drops the steps above the limit of one file, and the reader accepts what the writer wrote. + $script:PraPhaseLimits.MaxFileBytes = [long](($case.File + $case.Less) / 2) + $folder = Join-Path (Split-Path $case.Folder -Parent) 'fallback'; $null = New-Item -ItemType Directory -Path $folder -Force + $path = Save-PraPhaseData -Context $case.Context -Folder $folder + $global:PraGate.R10Case.Fallback = @{ Length = ([IO.FileInfo]$path).Length; Limit = $script:PraPhaseLimits.MaxFileBytes; Read = (Read-PraPhaseData -Folder @($folder) -Environment 'GATE') } + # A file above the limit of one file is refused with the size. + $script:PraPhaseLimits.MaxFileBytes = 100 + $global:PraGate.R10Case.TooBig = (Read-PraPhaseData -Folder @($case.Folder) -Environment 'GATE') + # Several files within the limit of one, together above the limit of the report: the file that does not fit is refused. + $script:PraPhaseLimits.MaxFileBytes = $saved.File + $script:PraPhaseLimits.MaxBytes = [long]($case.File * 2.5) + $set = Join-Path (Split-Path $case.Folder -Parent) 'set'; $null = New-Item -ItemType Directory -Path $set -Force + foreach ($context in @($case.Context, $case.Second.Context, $case.Third.Context)) { $null = Save-PraPhaseData -Context $context -Folder $set } + $global:PraGate.R10Case.Budget = (Read-PraPhaseData -Folder @($set) -Environment 'GATE') + } + finally { $script:PraPhaseLimits.MaxFileBytes = $saved.File; $script:PraPhaseLimits.MaxBytes = $saved.Total } + } + $case = $global:PraGate.R10Case + $case.Fallback.Length | Should -BeLessOrEqual $case.Fallback.Limit + $case.Fallback.Read.Phases.Count | Should -Be 1 + $case.Fallback.Read.Problems.Count | Should -Be 0 + $case.TooBig.Phases.Count | Should -Be 0 + ($case.TooBig.Problems -join ' ') | Should -Match 'the size is not acceptable \(at most \d+ MB for one file\)' + $case.Budget.Phases.Count | Should -Be 2 -Because 'the third file would take the files of the report above their total' + ($case.Budget.Problems -join ' ') | Should -Match 'not read: the files read before it already use \d+ MB of the \d+ MB allowed for one report\. Move the PhaseData files of other batches out of the batch folder' + $global:PraGate.Remove('R10Case') + } +} + +Describe 'Release 3.2.0 - a cloud-only run that sent permission grants ends with one complete check of the backup (real main, 13 synthetic shared mailboxes)' -Tag 'Release320c' { + It 'checks the backup in full after the grants of a Cloud phase, and only then' { + $runtime = New-GateRuntime -Name 'grant-full-320c' -Shared13 -Case CloudGrantSent + $ad = Invoke-GateProcess $runtime @{Action='Convert';Mode='Apply';Phase='AD';Force=$true;ConfigPath=$runtime.ConfigPath} -TimeoutSeconds 180 + $ad.ExitCode | Should -Be 2 -Because ($ad.Output + $ad.Error) + $ad.Output | Should -Not -Match 'checked in full after' + $cloud = Invoke-GateProcess $runtime @{Action='Convert';Mode='Apply';Phase='Cloud';Force=$true;ConfigPath=$runtime.ConfigPath;Batch=[string]$ad.MainResult.BatchId} -TimeoutSeconds 180 + $cloud.Output | Should -Match 'Backup of the batch checked in full after 13 permission grant\(s\)' + $engine = [IO.File]::ReadAllText((Join-Path $global:PraGate.Source 'Invoke-PraRemoteMailbox.ps1')) + $engine | Should -Match "Test-PraOrdinalIgnoreCaseEqual \`$effectivePhase 'Cloud'\) -and \(Test-PraOrdinalIgnoreCaseEqual \`$Action 'Convert'\) -and \[int\]\(Get-PraValue \`$context 'GrantsSent' 0\) -gt 0" -Because 'no grant sent, no extra check' + } +} diff --git a/tools/Measure-PraScale.ps1 b/tools/Measure-PraScale.ps1 index 80861b1..d58e484 100644 --- a/tools/Measure-PraScale.ps1 +++ b/tools/Measure-PraScale.ps1 @@ -26,8 +26,8 @@ .EXAMPLE pwsh -NoProfile -File .\tools\Measure-PraScale.ps1 -Count 5000 .NOTES - Author : Nicolas Fabert - Version: 3.1.4 + Author : Nicolas Fabert + Version : 3.1.4 #> #Requires -Version 7.5 [CmdletBinding()] @@ -95,7 +95,11 @@ function global:Set-ADUser { function global:Add-ADGroupMember { [CmdletBinding(SupportsShouldProcess)] param([object]$Identity, [object[]]$Members, [string]$Server) - foreach ($id in $Members) { $global:PraScaleAd.Members.Add([string]$global:PraScaleAd.ByKey[[string]$id].DistinguishedName) } + foreach ($id in $Members) { + $member = $global:PraScaleAd.ByKey[[string]$id] + $global:PraScaleAd.Members.Add([string]$member.DistinguishedName) + $member.memberOf = @([string]$global:PraScaleAd.Group.DistinguishedName) + } $global:PraScaleAd.Group.member = $global:PraScaleAd.Members.ToArray() } From af8af4956cadbf31e5359a86fb882442538d29f9 Mon Sep 17 00:00:00 2001 From: Nicolas Fabert <195452170+Nico77600@users.noreply.github.com> Date: Thu, 19 Nov 2026 05:41:02 +0100 Subject: [PATCH 05/16] Global report without caps, console sections, review fixes --- .gitattributes | 1 + package/Invoke-PraRemoteMailbox.ps1 | 75 +- package/PraRemoteMailbox.psd1 | 2 +- package/docs/PraRemoteMailbox-Guide.md | 51 +- package/docs/PraRemoteMailbox-UserGuide.md | 4 + package/module/PRA.Backup.psm1 | 4 +- package/module/PRA.Cloud.psm1 | 83 +- package/module/PRA.Common.psm1 | 732 ++++++++++++----- package/module/PRA.Directory.psm1 | 41 +- package/module/PRA.Gui.psm1 | 169 +++- package/module/PRA.Gui.xaml | 20 +- package/module/Test-PackageIntegrity.ps1 | 1 + package/templates/GlobalReport.template.html | 483 +++++++++++ tests/IntegrityFixture.ps1 | 2 +- tests/PackageIntegrity.Tests.ps1 | 4 +- tests/PraLegacyFixtures.Tests.ps1 | 2 +- tests/PraRemoteMailbox.Gui.Tests.ps1 | 232 +++++- tests/PraRemoteMailbox.Tests.ps1 | 807 +++++++++++++++++-- tools/Measure-PraScale.ps1 | 26 +- tools/New-PraPackage.ps1 | 2 +- 20 files changed, 2341 insertions(+), 400 deletions(-) create mode 100644 package/templates/GlobalReport.template.html diff --git a/.gitattributes b/.gitattributes index aa4847f..87340bb 100644 --- a/.gitattributes +++ b/.gitattributes @@ -21,6 +21,7 @@ package/PackageIntegrity.psd1 -text whitespace=blank-at-eol,space-before-tab,bla # Stable hashed files (SHA256 in the signed manifest) and the distribution copy of the changelog. package/module/PRA.Gui.xaml -text whitespace=blank-at-eol,space-before-tab,blank-at-eof,cr-at-eol package/templates/Report.template.html -text whitespace=blank-at-eol,space-before-tab,blank-at-eof,cr-at-eol +package/templates/GlobalReport.template.html -text whitespace=blank-at-eol,space-before-tab,blank-at-eof,cr-at-eol package/config/Targets.sample.csv -text whitespace=blank-at-eol,space-before-tab,blank-at-eof,cr-at-eol package/config/SharedPermissions.sample.csv -text whitespace=blank-at-eol,space-before-tab,blank-at-eof,cr-at-eol package/README.md -text whitespace=blank-at-eol,space-before-tab,blank-at-eof,cr-at-eol diff --git a/package/Invoke-PraRemoteMailbox.ps1 b/package/Invoke-PraRemoteMailbox.ps1 index 75c8771..1c01629 100644 --- a/package/Invoke-PraRemoteMailbox.ps1 +++ b/package/Invoke-PraRemoteMailbox.ps1 @@ -419,16 +419,18 @@ function Get-PraFallbackNext { return @('Fix the problem named above, then run the same command again:', $same) } -function Get-PraJsonOperation { +function Get-PraJsonHeader { <# .SYNOPSIS - The Operation field of a batch JSON file, read without parsing the whole file. + Some scalar fields of a batch JSON file (Operation, BatchId, SourceBackupHash), read without parsing the whole file. .DESCRIPTION - A backup of thousands of objects is tens of megabytes; its Operation field is one of the first properties of the envelope. - The head of the file is read and the field is taken from it when only scalar properties come before it (a nested property of - the same name cannot be taken). Any other shape, or a file that cannot be read this way, is parsed in full as before. + A backup of thousands of objects is tens of megabytes; the scalar fields of its envelope come before its records. The head of the file is read and each field + is taken from it when only plain scalar properties (text without escapes, numbers, true, false, null) come before it, so that a nested property of the same name + is never taken. Any other shape, a field that is not there, or a file that cannot be read this way is parsed in full. + .OUTPUTS + An object with the requested fields (the whole parsed file when it had to be parsed). #> - param([Parameter(Mandatory)][string]$Path) + 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) @@ -438,10 +440,34 @@ function Get-PraJsonOperation { $head = [Text.Encoding]::UTF8.GetString($buffer, 0, $count).TrimStart([char]0xFEFF) } finally { $stream.Dispose() } } catch { $head = '' } - $scalar = '(?:"(?:[^"\\]|\\[^u]|\\u[0-9a-fA-F]{4})*"|-?[0-9]+(?:\.[0-9]+)?(?:[eE][-+]?[0-9]+)?|true|false|null)' - $match = [regex]::Match($head, '\A\s*\{(?:\s*"(?:[^"\\]|\\[^u]|\\u[0-9a-fA-F]{4})*"\s*:\s*' + $scalar + '\s*,)*\s*"Operation"\s*:\s*"([^"\\]*)"\s*[,}]') - if ($match.Success) { return $match.Groups[1].Value } - return [string](([IO.File]::ReadAllText($Path) | ConvertFrom-PraJson).Operation) + $values = New-Object 'Collections.Generic.Dictionary[string,string]' ([StringComparer]::Ordinal) + $open = [regex]::Match($head, '\A\s*\{') + if ($open.Success) { + $pair = [regex]::new('\G\s*"(?[^"\\]*)"\s*:\s*(?:"(?[^"\\]*)"|(?-?[0-9]+(?:\.[0-9]+)?(?:[eE][-+]?[0-9]+)?|true|false|null))\s*(?,|\})') + $position = $open.Length + while ($true) { + $m = $pair.Match($head, $position) + if (-not $m.Success) { break } + $position = $m.Index + $m.Length + $key = $m.Groups['n'].Value + if (-not $values.ContainsKey($key)) { $values[$key] = $(if ($m.Groups['s'].Success) { $m.Groups['s'].Value } else { $m.Groups['x'].Value }) } + if (Test-PraOrdinalEqual $m.Groups['end'].Value '}') { break } + } + } + $header = [ordered]@{} + foreach ($field in $Name) { + if (-not $values.ContainsKey($field)) { return ([IO.File]::ReadAllText($Path) | ConvertFrom-PraJson) } + $header[$field] = $values[$field] + } + return [pscustomobject]$header +} + +function Test-PraBatchSideFile { + <# True for the files of a batch folder that are not a batch file, by name: the proof (State-), the journal, the data of the global report (PhaseData-, PhaseEvents-) and any checksum file. #> + param([Parameter(Mandatory)][string]$Name) + if ($Name.EndsWith('.sha256', [StringComparison]::OrdinalIgnoreCase)) { return $true } + foreach ($prefix in @('State-', 'Journal-', 'PhaseData-', 'PhaseEvents-')) { if ($Name.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase)) { return $true } } + return $false } function Get-PraBatchFile { @@ -484,8 +510,8 @@ 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 $_.Name.StartsWith('State-', [StringComparison]::OrdinalIgnoreCase) })) { - try { $operation = Get-PraJsonOperation $file.FullName } catch { continue } + 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 } # 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) } } @@ -625,6 +651,7 @@ function Get-PraFinalizeInput { } $context.Source = Import-PraBackup $context (Join-Path (Split-Path $path -Parent) $manifest.SourceBackupFile) $context.PhaseFolders = @(Split-Path $path -Parent) + 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.' } $records = @(Select-PraSourceRecord $context.Source); $seen = @{} @@ -679,8 +706,14 @@ function Publish-PraTransferPackage { $context.HandOff = $Kind $phaseFolder = [string](Get-PraValue $context 'PhaseWriteFolder' '') if ($phaseFolder -and -not [bool](Get-PraValue $context 'PhaseDataSaved' $false)) { - try { $null = Save-PraPhaseData -Context $context -Folder $phaseFolder -HandOff $Kind; $context.PhaseDataSaved = $true } + $saved = '' + try { $saved = Save-PraPhaseData -Context $context -Folder $phaseFolder -HandOff $Kind; $context.PhaseDataSaved = $true } catch { Write-PraLog -Context $context -Message ('The data for the global report could not be saved ({0}): the package is complete, the other server will report this side as not available.' -f $_.Exception.Message) -Level Warning } + # The cloud phase of a Recover also leaves its data in the batch of the AD rollback, so that the console can tell that its cloud part is done. + if ($saved -and (Test-PraOrdinalIgnoreCaseEqual $Kind 'Finalize') -and $null -ne (Get-PraValue $context 'Proof' $null)) { + try { $null = Copy-PraPhaseFile -Path $saved -Destination (Split-Path $context.Proof.Path -Parent) } + catch { Write-PraLog -Context $context -Message ('The data of this phase could not be copied to the batch of the AD rollback ({0}).' -f $_.Exception.Message) -Level Detail } + } } try { $name = Get-PraTransferPackageName -Kind $Kind -Environment $context.Config.Environment -BatchId $BatchId @@ -825,7 +858,7 @@ function Set-PraRowsAwaitCloud { } function Assert-PraBatchNotRolledBack { - <# A Convert batch that a Recover batch rolled back, or started to roll back, cannot be resumed: its objects are not converted any more (or not for certain), and a resume would hand over, or grant permissions, for a batch that no longer holds. #> + <# A Convert batch that a Recover batch rolled back, or started to roll back, cannot be resumed: its objects are not converted any more (or not for certain), and a resume would hand over, or grant permissions, for a batch whose conversion is undone. #> param([Parameter(Mandatory)][string[]]$ObjectGuid) $recover = Find-PraRecoverOfBatch -Context $context -SourceHash ([string]$context.Source.Hash) -ObjectGuid $ObjectGuid if ($null -eq $recover) { return } @@ -1490,10 +1523,10 @@ try { $proofPath = '' if ((Test-PraOrdinalIgnoreCaseEqual $Action 'Recover')) { $batchFile = Get-PraBatchFile -Value $Batch -Operations @('Recover','Convert') - $batchData = [IO.File]::ReadAllText($batchFile) | ConvertFrom-PraJson + $batchData = Get-PraJsonHeader $batchFile @('Operation', 'BatchId') if (Test-PraOrdinalEqual $batchData.Operation 'Recover') { $proofPath = Join-Path (Split-Path $batchFile -Parent) ('State-' + $batchData.BatchId + '.json') - $context.Source = Import-PraBackup $context (Find-PraConvertSource -Hash ([string]$batchData.SourceBackupHash)) + $context.Source = Import-PraBackup $context (Find-PraConvertSource -Hash ([string](Get-PraJsonHeader $batchFile @('SourceBackupHash')).SourceBackupHash)) $context.BatchId = Get-PraShortId $batchData.BatchId } elseif ($context.AllowMutation) { throw "Batch $Batch is a Convert batch: the cloud phase of a Recover needs the batch printed by its AD phase (it proves that AD was restored)." } @@ -1505,10 +1538,10 @@ try { $fromRecover = $false if ($isCheck) { # A Recover batch ID given to Check: the Convert batch that it rolled back is the source (as in the cloud phase of a Recover). - $batchData = [IO.File]::ReadAllText($batchFile) | ConvertFrom-PraJson + $batchData = Get-PraJsonHeader $batchFile @('Operation', 'BatchId') if (Test-PraOrdinalEqual $batchData.Operation 'Recover') { $fromRecover = $true - $context.Source = Import-PraBackup $context (Find-PraConvertSource -Hash ([string]$batchData.SourceBackupHash)) + $context.Source = Import-PraBackup $context (Find-PraConvertSource -Hash ([string](Get-PraJsonHeader $batchFile @('SourceBackupHash')).SourceBackupHash)) $context.BatchId = Get-PraShortId ([string]$batchData.BatchId) Write-PraItem -Context $context -Status Info -Text ('Batch {0} is a Recover batch: the Convert batch {1} that it rolled back is checked.' -f $context.BatchId, (Get-PraShortId ([string]$context.Source.Data.BatchId))) if (-not (Test-PraOrdinalIgnoreCaseEqual $Expect 'Deprovisioned')) { Write-PraItem -Context $context -Status Warn -Text 'The default expectation is Provisioned; to check a rollback, give -Expect Deprovisioned.' } @@ -1561,6 +1594,8 @@ try { $context.Rows.Add($row) } $context.PhaseFolders = @(@(Split-Path $context.Source.Path -Parent) + $(if ($proofPath) { @(Split-Path $proofPath -Parent) } else { @() })) + # The cloud phase of a Convert keeps what it did in the batch folder, so that the console can tell a finished batch from one that is still to do. + if ($context.AllowMutation -and (Test-PraOrdinalIgnoreCaseEqual $Action 'Convert') -and (Test-PraOrdinalIgnoreCaseEqual $effectivePhase 'Cloud')) { $context.PhaseWriteFolder = Split-Path $context.Source.Path -Parent } $convertedCount = $context.Rows.Count - $script:NotConverted.Count Send-PraPlanCount $convertedCount Write-PraItem -Context $context -Status Ok -Text ("Batch {0}: {1} object(s){2}" -f $context.BatchId, $convertedCount, $(if ($null -ne $context.Proof) { ', AD proof verified' } else { '' })) @@ -1598,8 +1633,8 @@ try { Import-Module (Join-Path $PSScriptRoot 'module\PRA.Cloud.psm1') -Force -ErrorAction Stop if ((Test-PraOrdinalIgnoreCaseEqual $Action 'Check') -and (Test-PraOrdinalIgnoreCaseEqual $Expect 'Retained')) { Invoke-PraRetentionCheck -Context $context -Rows $cloudRows } else { Invoke-PraCloudPhase -Context $context -Rows $cloudRows -Act $cloudAction } - # Each grant checked the backup cheaply; a cloud-only run that sent at least one ends with one complete check, so that it never ends without it. - if ($context.AllowMutation -and (Test-PraOrdinalIgnoreCaseEqual $effectivePhase 'Cloud') -and (Test-PraOrdinalIgnoreCaseEqual $Action 'Convert') -and [int](Get-PraValue $context 'GrantsSent' 0) -gt 0) { + # Each grant checks the backup cheaply; a Convert that sent at least one (phase Cloud or Both) ends its grant work with one complete check. + if ($context.AllowMutation -and (Test-PraOrdinalIn $effectivePhase @('Cloud','Both') -IgnoreCase) -and (Test-PraOrdinalIgnoreCaseEqual $Action 'Convert') -and [int](Get-PraValue $context 'GrantsSent' 0) -gt 0) { try { Assert-PraReceipt -Context $context -Receipt $context.Source -Full Write-PraItem -Context $context -Status Ok -Icon Backup -Text ('Backup of the batch checked in full after {0} permission grant(s)' -f [int]$context.GrantsSent) diff --git a/package/PraRemoteMailbox.psd1 b/package/PraRemoteMailbox.psd1 index 82c6d38..87b88d1 100644 --- a/package/PraRemoteMailbox.psd1 +++ b/package/PraRemoteMailbox.psd1 @@ -35,7 +35,7 @@ # Ordinal helpers, JSON and native calls (PRA.Common) 'Test-PraOrdinalEqual', 'Test-PraOrdinalIgnoreCaseEqual', 'Test-PraOrdinalIn', 'Test-PraOrdinalIgnoreCaseIn', 'Get-PraOrdinalSorted', 'Get-PraOrdinalUnique', 'New-PraRecordIndex', 'Get-PraRecordIndex', 'Find-PraRecord', 'ConvertTo-PraImmutableId', 'Get-PraSourceAnchor', 'Compare-PraX500Address', 'ConvertFrom-PraJson', 'Get-PraNativeProcessApi', 'Get-PraWin32ErrorText', 'Test-PraOwnEntryProcess', # Private folders, phase data and transfer package (PRA.Common) - 'New-PraPrivateDirectorySecurity', 'Initialize-PraPrivateFolder', 'Register-PraObjectName', 'Register-PraObjectBackup', 'Save-PraPhaseData', 'Copy-PraPhaseData', 'Get-PraTransferPackageName', 'Get-PraTransferPackage', 'New-PraTransferPackage', 'Import-PraTransferPackage', + 'New-PraPrivateDirectorySecurity', 'Initialize-PraPrivateFolder', 'Register-PraObjectName', 'Register-PraObjectBackup', 'Save-PraPhaseData', 'Copy-PraPhaseData', 'Copy-PraPhaseFile', 'Get-PraTransferPackageName', 'Get-PraTransferPackage', 'New-PraTransferPackage', 'Import-PraTransferPackage', # Active Directory, backup and proof (PRA.Directory) 'Initialize-PraDirectory', 'Initialize-PraPermissionCache', 'Get-PraUser', 'Resolve-PraGroup', 'Get-PraGroupMember', 'Get-PraExpectedX500', 'Get-PraTarget', 'Find-PraRecoverOfBatch', 'Get-PraJournalTouchedObject', 'New-PraRow', 'New-PraPlan', 'Invoke-PraAdPreview', 'Invoke-PraAdBatch', 'Invoke-PraAdReplication', 'Invoke-PraSync', 'Test-PraSyncServer', 'Start-PraSyncProbe', 'Import-PraBackup', 'Import-PraProof', 'Assert-PraReceipt', 'Assert-PraCloudProofObject', 'Assert-PraFollowupState', 'Get-PraHash', 'Write-PraImmutableFile', 'New-PraPrivateDirectory', 'Write-PraJournal' ) diff --git a/package/docs/PraRemoteMailbox-Guide.md b/package/docs/PraRemoteMailbox-Guide.md index 137314d..4f1a8c4 100644 --- a/package/docs/PraRemoteMailbox-Guide.md +++ b/package/docs/PraRemoteMailbox-Guide.md @@ -230,9 +230,9 @@ check | Done | on-premises again > > A **different account**, a **cloud-only** account, **two accounts**, or an account synchronised under **another UPN** is an **error for that object**: nothing is read in Exchange Online for it and nothing is changed on it. The message says which case it is and what to do (give one of the two accounts another UPN, or remove the duplicate, then run the same command again). The Exchange Online object found by UPN must then carry the `ExternalDirectoryObjectId` of the confirmed account, in every read (recipient, mailbox, permissions, retention check); another object stops the call. For a shared mailbox the same check is made for **each trustee** of a permission to grant (the batch records their anchors, `SharedTrusteeAnchors`; a trustee without recorded anchors must at least be a synchronised account, not a cloud-only one), so that a permission is never granted to another person. An object that is not in Microsoft Entra ID yet is waited for like any object that is not ready. > -> **Older batches and the records without an anchor.** A batch, backup or transfer package written before 3.2.0 has no `SourceAnchor`: the anchor is derived from the `ObjectGuid` of the record (the usual source anchor), and an error then says that the record is old. A tenant whose source anchor is neither the `objectGUID` nor `ms-DS-ConsistencyGuid` (or whose `ms-DS-ConsistencyGuid` differs from the `objectGUID` in a batch of an older version) can set `Cloud.IdentityCheck = 'Off'` after checking the accounts by hand: accounts are then found by UPN only, and the run says so once. A `Check -Identity ` has no AD record at all: the account is found by UPN with a warning, and no permission is ever granted for such a record. The retention check reads an **inactive** mailbox (its account is deleted) by UPN only, and says so with a warning. When the account of the object **is** confirmed, an inactive mailbox with the same UPN that carries another `ExternalDirectoryObjectId` belongs to an earlier account: the check says *not this object's mailbox*, the object is not covered, and that mailbox never decides the verdict. Without a confirmed account, two inactive mailboxes for the same UPN stop the check (nothing tells which one is the object's): the message gives the `Get-EXOMailbox -InactiveMailboxOnly` command that lists them. +> **Older batches and the records without an anchor.** A batch, backup or transfer package written before 3.2.0 has no `SourceAnchor`: the anchor is derived from the `ObjectGuid` of the record (the usual source anchor), and an error then says that the record is old. A tenant whose source anchor is neither the `objectGUID` nor `ms-DS-ConsistencyGuid` (or whose `ms-DS-ConsistencyGuid` differs from the `objectGUID` in a batch of an older version) can set `Cloud.IdentityCheck = 'Off'` after checking the accounts by hand: accounts are then found by UPN only, and the run says so once. A `Check -Identity ` has no AD record at all: the account is found by UPN with a warning, and no permission is ever granted for such a record. The retention check reads an **inactive** mailbox (its account is deleted) by UPN only, and says so with a warning. When the account of the object **is** confirmed, an inactive mailbox with the same UPN that carries another `ExternalDirectoryObjectId` belongs to an earlier account: the check says *not this object's mailbox*, the object is not covered, and that mailbox never decides the verdict. An inactive mailbox that carries no `ExternalDirectoryObjectId` at all is a candidate found by UPN (with the same warning). Several candidates are told apart by the mailbox GUID that the batch recorded from Active Directory (`msExchMailboxGuid`, for an object that had an on-premises mailbox); when the record has none, or it matches none or several, the check stops (nothing tells which one is the object's) and the message gives the `Get-EXOMailbox -InactiveMailboxOnly` command that lists them. In the deprovisioning check of a Recover only an explicit *not found* for the object's id counts as an absent mailbox: any other error, a `404` that does not name the id included, is a failed read, never a confirmation. > -> **Permissions are written with the confirmed id.** The Exchange Online object of a confirmed account is read with the `-ExternalDirectoryObjectId` parameter (recipient, mailbox, permissions), and a permission is written (`Add-MailboxPermission`, `Add-RecipientPermission`, `Set-Mailbox`) with the confirmed id of the mailbox and of the trustee in `-Identity`, `-User` and `-Trustee`. The UPN is used only for an object that has no confirmed account (`Cloud.IdentityCheck = 'Off'`). A grant that the run already sent (mailbox, right, trustee) is never sent again in the same run, even if a later read does not show it yet. +> **Permissions are written with the confirmed id.** The Exchange Online object of a confirmed account is read with the `-ExternalDirectoryObjectId` parameter (recipient, mailbox, permissions), and a permission is written (`Add-MailboxPermission`, `Add-RecipientPermission`, `Set-Mailbox`) with the confirmed id of the mailbox and of the trustee in `-Identity`, `-User` and `-Trustee`. The UPN is used only for an object that has no confirmed account (`Cloud.IdentityCheck = 'Off'`). A grant that the run already sent (mailbox, right, trustee) is never sent again in the same run. If a later read does not show it, it is not counted as verified: the object ends *done with warnings*, and the warning names the permission to check by hand. > [!NOTE] > **Throttling and temporary failures do not end an object.** A read of Microsoft Graph or Exchange Online that fails with HTTP 408, 429, 502, 503, 504, a timeout or no answer at all is sent again (at most five tries, after the `Retry-After` of the answer, or 5, 10, 20, 40 seconds), within `Cloud.RetryBudgetObjectSeconds` for one object and `Cloud.RetryBudgetRunMinutes` for the whole run; every retry is in the log (Detail level). A throttled answer (429, 503) also **slows every following call of the run** (a pause that doubles up to 30 seconds and halves after each success), so that a batch of thousands of objects does not turn into thousands of refused calls. An object whose own budget is used up stays pending and is read again at the next check of the wait; only at the end of the wait is it an error ("Microsoft 365 could not be read"). When the budget of the **run** is used up, the cloud part stops with **one** error (not one per object), the objects not finished stay *Pending*, and the Next steps give the command to run again a few minutes later. Any other failure (a 4xx other than 408 and 429, a refusal, a bad answer) is **not** sent again. A grant is never sent again: the next run finds the permission already granted or grants it. @@ -628,7 +628,9 @@ voids the previous Preview. The list is revalidated and hashed before Run. AD st `\Inbox`, with their state. **Import package...** takes a `.zip` from anywhere: the console verifies it (all checks before any write, [chapter 10](#10-files-batches-proofs-and-packages)), extracts it into `Storage.BackupFolder` and selects its batch. A package picked in the list is imported when you continue to the verification page. -A Convert batch whose proof is *partial* (it stopped at its first error: some objects were verified, the others were not converted) is labelled **Partial: k of n converted**, and *Continue a batch* offers it as *finish it here* (the synchronisation first, then the package, as the command line does): so is any batch whose journal has no Entra Connect entry that ended well when `EntraConnect.Sync` is on; the files of the global report (`PhaseData-...`) are not batches and are never listed. A Convert batch whose AD part is verified (it has its `State-.json`) but whose Entra Connect sync did not end (the last `ADSync` line of its journal is `Failed`), or that has no package in `Backups\Outbox` on a server that cannot do the cloud part, is marked **finish it here** (orange). Selecting it makes the phase **AD** and runs `Convert -Phase AD -Batch ` ([Exit codes](#exit-codes)): the Entra Connect check, the synchronisation again, the package; Active Directory is not written and the cloud sign-in is not needed. The Next steps page of a run whose sync could not start puts the sync before the copy of the package. An engine refusal "already converted by batch ..." sent from the console names this path (Task, Continue a batch) instead of a command line. +A Convert batch whose proof is *partial* (it stopped at its first error: some objects were verified, the others were not converted) is labelled **Partial: k of n converted**, and *Continue a batch* offers it as *finish it here* (the synchronisation first, then the package, as the command line does): so is any batch whose journal has no Entra Connect entry that ended well when `EntraConnect.Sync` is on; the files of the global report (`PhaseData-...`, `PhaseEvents-...`) are not batches and are never listed. A Convert batch whose AD part is verified (it has its `State-.json`) but whose Entra Connect sync did not end (the last `ADSync` line of its journal is `Failed`), or that has no package in `Backups\Outbox` on a server that cannot do the cloud part, is marked **finish it here** (orange). Selecting it makes the phase **AD** and runs `Convert -Phase AD -Batch ` ([Exit codes](#exit-codes)): the Entra Connect check, the synchronisation again, the package; Active Directory is not written and the cloud sign-in is not needed. The Next steps page of a run whose sync could not start puts the sync before the copy of the package. An engine refusal "already converted by batch ..." sent from the console names this path (Task, Continue a batch) instead of a command line. + +**Sections of the list.** Each row says what the batch needs, with an icon in its status pill. Rows that **need attention** come first, in orange: *Partial: k of n converted*, *Cloud part pending: n objects not ready, run it again* (the last cloud run left objects not ready), *Cloud part stopped: run it again* (it failed or was cancelled) and the *finish it here* rows. The other batches that are still **to do** follow, in the accent colour (*AD part done, cloud part to do*, *AD rollback done, cloud part to do*, *Ready to finalize*). The **Finished** rows (green check) come last, are greyed and cannot be picked in *Continue a batch*, *Continue a rollback* or *Complete a rollback*: *Finished: cloud part done*, *Cloud part done: finalize on the AD server*, *Finalized: the directory is restored*. In *Roll back a conversion* a finished conversion is still a batch to roll back, and says *Finished · can be rolled back*. Above the list, **To do (n)**, **Finished (n)** and **All (n)** choose the section: the lists that continue a batch or finalize a rollback start on *To do*, the others on *All*, changing the mode puts the section back, and a section with nothing in it says why (for example *Nothing is left to do here: 3 finished and hidden*). The console reads this from the `PhaseData-*.json` files of the batch folder, which the cloud phase of a Convert (in the Convert batch folder), the cloud phase of a Recover (in the batch of the AD rollback) and the Finalize now leave there: the **last** cloud-side run of the batch decides (a later failed run reopens a finished batch), only the first 64 KB of each file are read, and the answer is kept while the file does not change. A batch with no such file (a batch of an earlier version, a folder copied by hand) is shown as still to do. A partial batch is never shown as finished, whatever its cloud part did. The letter case of the values in the file does not matter. **Safety is unchanged.** Run is locked until a successful Preview of **exactly** the same request, files and configuration; the engine independently rereads the directory, backs up and verifies the targets before every write. Type **CONVERT**, **RECOVER** or **FINALIZE** (any letter case, surrounding spaces @@ -874,21 +876,35 @@ Requirement: a current desktop Microsoft Edge or Google Chrome (the page needs ` With two servers, each side writes its own report (as before). The **last** server also writes ONE **global report** that follows every object from the first server to the last, for Convert (AD, then Cloud) as for Recover (AD, Cloud, then Finalize), whatever the type of the objects (users, shared mailboxes, all): -- **How the data travels.** Each side that hands over to another keeps what it did in `PhaseData-