From e568bd610094400a354d19f471230263115fac4e Mon Sep 17 00:00:00 2001 From: Nicolas Fabert <195452170+Nico77600@users.noreply.github.com> Date: Thu, 5 Nov 2026 12:00:05 +0100 Subject: [PATCH 01/14] X500 control: read legacyExchangeDN at Convert and record the expected X500 addresses in the batch (read only) --- package/PraRemoteMailbox.psd1 | 4 +-- package/module/PRA.Common.psm1 | 19 +++++++++++- package/module/PRA.Directory.psm1 | 51 ++++++++++++++++++++++++++++--- 3 files changed, 67 insertions(+), 7 deletions(-) diff --git a/package/PraRemoteMailbox.psd1 b/package/PraRemoteMailbox.psd1 index d8d6dd1..ea5b8e9 100644 --- a/package/PraRemoteMailbox.psd1 +++ b/package/PraRemoteMailbox.psd1 @@ -33,11 +33,11 @@ # Configuration, paths and CSV (PRA.Common) 'Import-PraConfiguration', 'New-PraEffectiveConfiguration', 'Get-PraConfigurationDifference', 'Resolve-PraPath', 'Read-PraCsvText', 'Read-PraTargetCsv', 'Get-PraTargetOverride', 'Get-PraToolVersion', 'Get-PraValue', 'Get-PraList', # Ordinal helpers, JSON and native calls (PRA.Common) - 'Test-PraOrdinalEqual', 'Test-PraOrdinalIgnoreCaseEqual', 'Test-PraOrdinalIn', 'Test-PraOrdinalIgnoreCaseIn', 'Sort-PraOrdinal', 'Get-PraOrdinalUnique', 'ConvertFrom-PraJson', 'Get-PraNativeProcessApi', 'Get-PraWin32ErrorText', + 'Test-PraOrdinalEqual', 'Test-PraOrdinalIgnoreCaseEqual', 'Test-PraOrdinalIn', 'Test-PraOrdinalIgnoreCaseIn', 'Sort-PraOrdinal', 'Get-PraOrdinalUnique', 'Compare-PraX500Address', 'ConvertFrom-PraJson', 'Get-PraNativeProcessApi', 'Get-PraWin32ErrorText', # 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', 'Get-PraTarget', 'New-PraRow', 'New-PraPlan', 'Invoke-PraAdPreview', 'Invoke-PraAdBatch', 'Invoke-PraAdReplication', 'Invoke-PraSync', 'Import-PraBackup', 'Import-PraProof', 'Assert-PraReceipt', 'Assert-PraFollowupState', 'Get-PraHash', 'Write-PraImmutableFile', 'New-PraPrivateDirectory', 'Write-PraJournal' + 'Initialize-PraDirectory', 'Initialize-PraPermissionCache', 'Get-PraUser', 'Get-PraExpectedX500', 'Get-PraTarget', 'New-PraRow', 'New-PraPlan', 'Invoke-PraAdPreview', 'Invoke-PraAdBatch', 'Invoke-PraAdReplication', 'Invoke-PraSync', 'Import-PraBackup', 'Import-PraProof', 'Assert-PraReceipt', 'Assert-PraFollowupState', 'Get-PraHash', 'Write-PraImmutableFile', 'New-PraPrivateDirectory', 'Write-PraJournal' ) CmdletsToExport = @() VariablesToExport = @() diff --git a/package/module/PRA.Common.psm1 b/package/module/PRA.Common.psm1 index a86c4e5..0cafd6c 100644 --- a/package/module/PRA.Common.psm1 +++ b/package/module/PRA.Common.psm1 @@ -171,6 +171,23 @@ function Get-PraOrdinalUnique { begin { $seen = New-Object 'Collections.Generic.HashSet[string]' -ArgumentList $(if ($IgnoreCase) { [StringComparer]::OrdinalIgnoreCase } else { [StringComparer]::Ordinal }) } process { if ($null -ne $InputObject -and $seen.Add([string]$InputObject)) { [string]$InputObject } } } + +function Compare-PraX500Address { + <# + .SYNOPSIS + Which of the expected X500 addresses a cloud mailbox carries (EmailAddresses / proxyAddresses): Present and Missing, in the order of Expected. + .DESCRIPTION + Read only. The whole value is compared, ordinal and ignoring case (Exchange Online may write the type prefix in lower case); the values are returned + exactly as they are in Expected. + #> + [CmdletBinding()] + param([AllowNull()][string[]]$Expected, [AllowNull()][string[]]$Actual) + $actualSet = New-Object 'Collections.Generic.HashSet[string]' -ArgumentList ([StringComparer]::OrdinalIgnoreCase) + foreach ($value in @($Actual)) { if ($null -ne $value) { [void]$actualSet.Add([string]$value) } } + $present = New-Object 'Collections.Generic.List[string]'; $missing = New-Object 'Collections.Generic.List[string]' + foreach ($value in @($Expected)) { if ($null -eq $value) { continue }; if ($actualSet.Contains([string]$value)) { $present.Add([string]$value) } else { $missing.Add([string]$value) } } + return [pscustomobject]@{ Total = ($present.Count + $missing.Count); Present = [string[]]$present.ToArray(); Missing = [string[]]$missing.ToArray() } +} #endregion function Get-PraToolVersion { @@ -2811,7 +2828,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, Sort-PraOrdinal, Get-PraOrdinalUnique, ConvertFrom-PraJson, Get-PraNativeProcessApi, Read-PraCsvText, Get-PraToolVersion, 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, 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, Sort-PraOrdinal, Get-PraOrdinalUnique, Compare-PraX500Address, ConvertFrom-PraJson, Get-PraNativeProcessApi, Read-PraCsvText, Get-PraToolVersion, 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, 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 # SIG # Begin signature block diff --git a/package/module/PRA.Directory.psm1 b/package/module/PRA.Directory.psm1 index 888c705..c51008f 100644 --- a/package/module/PRA.Directory.psm1 +++ b/package/module/PRA.Directory.psm1 @@ -62,6 +62,9 @@ $script:AttributeKinds = [ordered]@{ mDBUseDefaults='Bool'; msExchRecipientDisplayType='Int'; msExchRecipientTypeDetails='Long' msExchRemoteRecipientType='Long'; targetAddress='String'; proxyAddresses='MultiString' } +# Bounds of the list of X500 addresses expected in Exchange Online (record field ExpectedX500): count and length of one value. +$script:MaxExpectedX500 = 2000 +$script:MaxExpectedX500Length = 2048 # Display names of msExchRecipientTypeDetails values (console only). $script:RecipientTypeNames = @{ '1'='UserMailbox'; '4'='SharedMailbox'; '16'='RoomMailbox'; '32'='EquipmentMailbox'; '128'='MailUser' @@ -398,7 +401,7 @@ function Get-PraUser { #> [CmdletBinding()] param([hashtable]$Context, [Parameter(Mandatory)][string]$Identity, [string[]]$ExtraProperties = @(), [switch]$Capture) - $properties = @('memberOf','uSNChanged','DisplayName','mail','mailNickname','msExchArchiveGUID') + @($script:AttributeKinds.Keys) + $ExtraProperties + $properties = @('memberOf','uSNChanged','DisplayName','mail','mailNickname','msExchArchiveGUID','legacyExchangeDN') + @($script:AttributeKinds.Keys) + $ExtraProperties if ($Capture) { $properties += @('*','msExchMailboxSecurityDescriptor','nTSecurityDescriptor','publicDelegates') } $properties = @($properties | Get-PraOrdinalUnique -IgnoreCase) $server = $Context.Server @@ -735,6 +738,12 @@ function Write-PraAdDelta { foreach ($value in $keptCloud) { Write-PraLog -Context $Context -Message (" proxyAddresses | KEPT X500 (written back by Entra Connect) : {0}" -f (ConvertTo-PraLogText -Value $value)) -Level Detail } Write-PraItem -Context $Context -Status Info -Text ('{0}: {1} cloud X500 address(es) kept (written back by Entra Connect; replies to messages sent from the cloud keep working)' -f $record.SamAccountName, $keptCloud.Count) } + if ((Test-PraOrdinalIgnoreCaseEqual $Plan.Operation 'Convert')) { + # The cloud phase proves these addresses in Exchange Online (a reply to an old message is addressed by legacyExchangeDN); here the operator only sees how many. + $verifyX500 = @(if ($record.Contains('ExpectedX500')) { $record['ExpectedX500'] | Where-Object { $_ } }) + foreach ($value in $verifyX500) { Write-PraLog -Context $Context -Message (" X500 to verify in Exchange Online : {0}" -f (ConvertTo-PraLogText -Value $value)) -Level Detail } + Write-PraItem -Context $Context -Status Info -Text ('{0}: X500 to verify after the conversion: {1}{2}' -f $record.SamAccountName, $verifyX500.Count, $(if ($verifyX500.Count) { '' } else { ' (no legacyExchangeDN and no X500 address on premises)' })) + } if (-not $consoleLines.Count) { Write-PraHost @(@(' '), @('no change: the object is already in the expected state', 'DarkGray')) } elseif ($unchanged) { Write-PraHost @(@(' '), @(('{0} other managed attribute(s) unchanged (full values in the log)' -f $unchanged), 'DarkGray')) } if ($permissionText) { @@ -812,6 +821,26 @@ function Get-PraX500Difference { if ($same) { for ($i = 0; $i -lt $a.Count; $i++) { if (-not (Test-PraOrdinalEqual ([string]$a[$i]) ([string]$b[$i]))) { $same = $false; break } } } return [pscustomobject]@{ OtherEqual = $same; Added = [string[]]$added.ToArray(); Removed = [string[]]@($removed) } } + +function Get-PraExpectedX500 { + <# + .SYNOPSIS + X500 addresses that the cloud mailbox must carry so that a reply to an old message, a meeting update or a cached Outlook entry (all addressed by + legacyExchangeDN, internally IMCEAEX) still reaches it: X500: when it is not empty, then every X500 entry of the on-premises proxyAddresses. + .DESCRIPTION + Read only. Duplicates are removed (ordinal, ignoring case, on the whole value); the first spelling is kept, byte for byte. The prefix of the + legacyExchangeDN is written X500: (the type prefix of the other entries keeps whatever case it has on premises). + #> + [OutputType([string[]])] + param([AllowNull()][AllowEmptyString()][string]$LegacyExchangeDN, [AllowNull()][string[]]$ProxyAddresses) + $seen = New-Object 'Collections.Generic.HashSet[string]' -ArgumentList ([StringComparer]::OrdinalIgnoreCase) + $list = New-Object 'Collections.Generic.List[string]' + if (-not [string]::IsNullOrWhiteSpace($LegacyExchangeDN)) { $value = 'X500:' + $LegacyExchangeDN; if ($seen.Add($value)) { $list.Add($value) } } + foreach ($address in @($ProxyAddresses)) { if (Test-PraX500Address $address) { if ($seen.Add([string]$address)) { $list.Add([string]$address) } } } + if ($list.Count -gt $script:MaxExpectedX500) { throw "Too many X500 addresses to verify ($($list.Count), limit $($script:MaxExpectedX500)): conversion refused before any change." } + foreach ($value in $list) { if ($value.Length -gt $script:MaxExpectedX500Length) { throw "X500 address too long to verify ($($value.Length) characters, limit $($script:MaxExpectedX500Length)): conversion refused before any change." } } + return [string[]]$list.ToArray() +} #endregion #region 4. Shared permissions ------------------------------------------------------------------ @@ -1114,10 +1143,12 @@ function New-PraPlan { $desired = [ordered]@{}; foreach ($name in $before.Keys) { $desired[$name] = $before[$name] } $permissions = @{ FullAccess=@(); SendAs=@(); SendOnBehalf=@() } $licensing = [ordered]@{ Enabled=$false; GroupGuid=''; GroupDN=''; WasMember=$false; DesiredMember=$false } - $routing = ''; $alreadyRecovered = $false; $keptX500 = @() + $routing = ''; $alreadyRecovered = $false; $keptX500 = @(); $expectedX500 = @() if ((Test-PraOrdinalIgnoreCaseEqual $Operation 'Convert')) { if (-not $user.homeMDB -or [int64]$user.msExchRecipientTypeDetails -notin @(1, 4, 16, 32)) { throw "Not an on-premises mailbox (homeMDB / msExchRecipientTypeDetails): $Identity" } $routing = Get-PraRoutingAddress $Context $user + # X500 addresses the cloud mailbox must carry (read only: legacyExchangeDN is never written, restored or modified; the control runs in the cloud phase). + $expectedX500 = @(Get-PraExpectedX500 -LegacyExchangeDN ([string](Get-PraValue $user 'legacyExchangeDN' '')) -ProxyAddresses @($user.proxyAddresses)) $rrt = if ($shared) { [int64]$config.SharedMailbox.RemoteRecipientType } else { [int64]$config.Remote.RecipientType } if ($shared -and (Test-PraOrdinalIn $rrt @(100, 102) -IgnoreCase)) { throw "SharedMailbox.RemoteRecipientType=$rrt means an already migrated mailbox (Migrated+Shared): first provisioning refused before any change: $Identity" } if ($config.Remote.HandleArchives -and (Get-PraValue $user 'msExchArchiveGUID' $null)) { $rrt = $rrt -bor 2 } @@ -1199,7 +1230,7 @@ function New-PraPlan { Attributes=$before; PlannedAttributes=$desired; Licensing=$licensing Retention=[ordered]@{ Enabled=[bool]$tagEnabled; Attribute=$tagAttr; Value=$(if ($tagEnabled) { [string]$tag.Value } else { '' }) } SharedPermissions=$permissions; PreserveCloudMailbox=[bool]$preserveMailbox; PreserveLicense=[bool]$preserveLicense - KeptX500=[string[]]@($keptX500) + KeptX500=[string[]]@($keptX500); ExpectedX500=[string[]]@($expectedX500) } $row = New-PraRow $Context $record if ($null -ne $SourceRecord) { $row.BackupRec = $SourceRecord } else { $row.BackupRec = [pscustomobject]$record } @@ -1257,6 +1288,13 @@ function Assert-PraStoredRecord { # Cloud X500 addresses kept by a Recover (absent in a batch written before 3.0.0: none). $keptStored = Get-PraValue $Record 'KeptX500' $null if ($null -ne $keptStored) { foreach ($value in @($keptStored)) { if ($value -isnot [string] -or -not (Test-PraX500Address $value)) { throw 'Backup: invalid list of kept X500 addresses.' } } } + # X500 addresses expected in Exchange Online (absent in a batch written before 3.1.0: the control is skipped). + $expectedStored = Get-PraValue $Record 'ExpectedX500' $null + if ($null -ne $expectedStored) { + if ($expectedStored -isnot [string] -and $expectedStored -isnot [array]) { throw 'Backup: invalid list of expected X500 addresses.' } + 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.' } } + } if (-not $Legacy) { if ($Record.CapturedUsnChanged -isnot [string] -or $Record.CapturedUsnChanged -notmatch '^[1-9][0-9]*$') { throw 'Backup: original uSNChanged missing or invalid.' } $null = [int64]::Parse($Record.CapturedUsnChanged, [Globalization.CultureInfo]::InvariantCulture) @@ -1343,6 +1381,11 @@ function Assert-PraRecordMatchesPlan { if ($storedKept.Count -ne $wantedKept.Count) { throw 'Backup re-read: kept X500 addresses not preserved.' } for ($index = 0; $index -lt $wantedKept.Count; $index++) { if (-not (Test-PraOrdinalEqual ([string]$storedKept[$index]) ([string]$wantedKept[$index]))) { throw 'Backup re-read: kept X500 addresses not preserved.' } } } + if ($Expected.Contains('ExpectedX500')) { + $storedExpected = @(if ($null -ne $Stored.PSObject.Properties['ExpectedX500']) { $Stored.ExpectedX500 | Where-Object { $null -ne $_ } }); $wantedExpected = @($Expected['ExpectedX500']) + if ($storedExpected.Count -ne $wantedExpected.Count) { throw 'Backup re-read: expected X500 addresses not preserved.' } + for ($index = 0; $index -lt $wantedExpected.Count; $index++) { if (-not (Test-PraOrdinalEqual ([string]$storedExpected[$index]) ([string]$wantedExpected[$index]))) { throw 'Backup re-read: expected X500 addresses not preserved.' } } + } foreach ($section in @('Attributes','PlannedAttributes')) { $actualNames = @($Stored.$section.PSObject.Properties.Name) if ($actualNames.Count -ne $Expected[$section].Count) { throw "Backup re-read: missing or extra attributes in $section." } @@ -1916,7 +1959,7 @@ function Invoke-PraSync { #endregion Export-ModuleMember -Function ConvertTo-PraLdapValue, Get-PraHash, Write-PraImmutableFile, New-PraPrivateDirectory, Write-PraJournal, - Initialize-PraDirectory, Get-PraUser, Get-PraTarget, New-PraRow, New-PraPlan, Import-PraBackup, Invoke-PraAdPreview, Invoke-PraAdBatch, + Initialize-PraDirectory, Get-PraUser, Get-PraExpectedX500, Get-PraTarget, New-PraRow, New-PraPlan, Import-PraBackup, Invoke-PraAdPreview, Invoke-PraAdBatch, Import-PraProof, Invoke-PraSync, Invoke-PraAdReplication, Assert-PraReceipt, Test-PraStateEqual, Assert-PraFollowupState, Initialize-PraPermissionCache # SIG # Begin signature block From 417662191ea2fe5dab12762d3447689f134fe874 Mon Sep 17 00:00:00 2001 From: Nicolas Fabert <195452170+Nico77600@users.noreply.github.com> Date: Thu, 5 Nov 2026 12:08:48 +0100 Subject: [PATCH 02/14] X500 control: compare the expected addresses with the cloud mailbox (Exchange Online or Graph), warn when missing, tests --- package/Invoke-PraRemoteMailbox.ps1 | 12 +- package/module/PRA.Cloud.psm1 | 112 ++++++- package/module/PRA.Directory.psm1 | 4 +- tests/PraRemoteMailbox.Tests.ps1 | 442 +++++++++++++++++++++++++++- 4 files changed, 555 insertions(+), 15 deletions(-) diff --git a/package/Invoke-PraRemoteMailbox.ps1 b/package/Invoke-PraRemoteMailbox.ps1 index 48661bb..170cb2a 100644 --- a/package/Invoke-PraRemoteMailbox.ps1 +++ b/package/Invoke-PraRemoteMailbox.ps1 @@ -925,11 +925,12 @@ try { $stepTitle = switch ($Action) { 'Check' { 'Objects to check' } 'Recover' { 'Loading the Recover batch' } default { 'Loading the batch of the AD phase' } } Write-PraStep -Context $context -Title $stepTitle -Icon Batch if ((Test-PraOrdinalIgnoreCaseEqual $Action 'Check') -and $Identity -and -not $Batch) { - if ($Identity -match '@') { $record = [pscustomobject]@{ ObjectGuid = ''; SamAccountName = $Identity; UserPrincipalName = $Identity; IsShared = ((Test-PraOrdinalIgnoreCaseEqual $Scope 'SharedOnly')) } } + if ($Identity -match '@') { $record = [pscustomobject]@{ ObjectGuid = ''; SamAccountName = $Identity; UserPrincipalName = $Identity; IsShared = ((Test-PraOrdinalIgnoreCaseEqual $Scope 'SharedOnly')); ExpectedX500Note = 'identity given as a UPN, no Active Directory read: give the sAMAccountName or -Batch' } } else { 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)) } + $record = [pscustomobject]@{ ObjectGuid = ([guid]$user.ObjectGUID).ToString(); SamAccountName = $user.SamAccountName; UserPrincipalName = $user.UserPrincipalName; IsShared = ((Test-PraOrdinalIn $user.msExchRecipientTypeDetails @(4, 34359738368) -IgnoreCase)) + ExpectedX500 = [string[]]@(Get-PraExpectedX500 -LegacyExchangeDN ([string](Get-PraValue $user 'legacyExchangeDN' '')) -ProxyAddresses @($user.proxyAddresses)) } } $context.Rows.Add((New-PraRow $context $record)) Write-PraItem -Context $context -Status Ok -Text ("{0} ({1})" -f $record.UserPrincipalName, $(if ($record.IsShared) { 'shared mailbox' } else { 'user mailbox' })) @@ -1057,6 +1058,13 @@ try { if ($context.AllowMutation -and (Test-PraOrdinalIgnoreCaseEqual $Action 'Convert') -and (Test-PraOrdinalIn $effectivePhase @('Both','Cloud') -IgnoreCase) -and $context.BatchId -and -not $context.Issues.Count) { $context.NextSteps = @($(if ((Test-PraOrdinalIgnoreCaseEqual $effectivePhase 'Cloud')) { 'To roll back this batch later, on the AD server: ' + (Get-PraCommandLine -ActionName 'Recover' -ModeName 'Preview' -BatchId $context.BatchId -OtherServer) } else { 'To roll back this batch later: ' + (Get-PraCommandLine -ActionName 'Recover' -ModeName 'Preview' -BatchId $context.BatchId) })) } + + # X500 addresses missing in Exchange Online (warning of the cloud phase): synchronise, then check again. + $x500Missing = @(Get-PraList $context 'X500Missing') + if ($x500Missing.Count) { + $checkCommand = Get-PraCommandLine -ActionName 'Check' -ModeName 'Preview' -BatchId $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)) + } } catch { $failure = $_; $failureOperation = $context.CurrentOperation diff --git a/package/module/PRA.Cloud.psm1 b/package/module/PRA.Cloud.psm1 index 11a8f5c..19aaa84 100644 --- a/package/module/PRA.Cloud.psm1 +++ b/package/module/PRA.Cloud.psm1 @@ -181,17 +181,21 @@ $script:PraExoWorker = { } function Mailbox { param([string]$Upn,[switch]$Hold) - $grantParameters = @{ Filter=(ExactFilter $Upn); Properties=@('RecipientTypeDetails'); ResultSize='Unlimited' } + $grantParameters = @{ Filter=(ExactFilter $Upn); Properties=@('RecipientTypeDetails','EmailAddresses'); 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) } 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 } } + 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" } $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'] } + $rawAddresses = V -Object $m -Name 'EmailAddresses' -Default @() 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) } + Litigation=[bool](V -Object $m -Name 'LitigationHoldEnabled' -Default $false); RetentionHold=[bool](V -Object $m -Name 'RetentionHoldEnabled' -Default $false) + HasAddresses=[bool]$hasAddresses; Addresses=[string[]]@($rawAddresses | Where-Object { $null -ne $_ } | ForEach-Object { [string]$_ }) } } function NormalizeAcl { param([object[]]$Entries,[string]$Right,$Target) @@ -866,10 +870,10 @@ function Invoke-PraSharedPermission { } function Get-PraGraphFact { - param([hashtable]$Context,[string]$Upn,[bool]$Mailbox,[bool]$License) + param([hashtable]$Context,[string]$Upn,[bool]$Mailbox,[bool]$License,[bool]$Addresses=$false) 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' } + $props=@('assignedPlans'); if ($Mailbox) { $props+='provisionedPlans' }; if ($License) { $props+='assignedLicenses' }; if ($Addresses) { $props+='proxyAddresses' } $users=@(Get-MgUser -UserId $Upn -Property $props -ErrorAction Stop) 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 @@ -903,7 +907,69 @@ function Get-PraGraphFact { } $count=0; if ($License) { $count=$values.assignedLicenses.Count } return @{ Enabled=$enabled; Provisioned=$prov; LicenseCount=$count; RequiredSku=$required - RequiredSkuOk=(-not $required -or (Test-PraOrdinalIgnoreCaseIn $required $sku)); Detail=($plans -join ',') } + RequiredSkuOk=(-not $required -or (Test-PraOrdinalIgnoreCaseIn $required $sku)); Detail=($plans -join ','); Addresses=[string[]]@(if ($Addresses) { $values.proxyAddresses | ForEach-Object { [string]$_ } }) } +} + +function Get-PraCloudAddress { + <# Addresses of the cloud mailbox (read only): Exchange Online EmailAddresses, or the Entra proxyAddresses when the mailbox check goes through Graph. Has = the property was returned. #> + param([hashtable]$Context,$State) + if ($State.ExoMailbox) { + $m = Invoke-PraExo -Context $Context -Operation 'Mailbox' -Params @{ Upn=$State.Upn } + if ((Get-PraValue $m 'Found' $false) -ne $true) { throw 'the mailbox is no longer found in Exchange Online' } + return @{ Has=[bool](Get-PraValue $m 'HasAddresses' $false); List=[string[]]@(Get-PraList $m 'Addresses') } + } + $facts = Get-PraGraphFact -Context $Context -Upn $State.Upn -Mailbox $false -License $false -Addresses $true + return @{ Has=$true; List=[string[]]@($facts.Addresses) } +} + +function Complete-PraX500Check { + <# Result of the X500 control of one object: an Ok line when every expected address is there, otherwise ONE warning (the conversion itself stays done). #> + param([hashtable]$Context,$State) + $row = $State.Row; $failure = [string](Get-PraValue $State 'X500Failure' ''); $last = $State.X500Last + $Context.CurrentIdentity = [string](Get-PraValue $row 'ObjectGuid' $State.Upn); $Context.CurrentOperation = 'X500Check' + $State.Done = $true + if (-not $failure -and $null -ne $last -and $last.Missing.Count -eq 0) { + Write-PraItem -Context $Context -Status Ok -Text ('{0}: X500: {1} of {1} present (legacyExchangeDN + older X500)' -f $State.Upn, $last.Total) + $row.CloudDetail = ([string]$row.CloudDetail + ' | X500:present=' + $last.Total + '/' + $last.Total).Trim(' ', '|') + return + } + $advice = 'Replies to old messages and meeting updates to this mailbox can bounce (IMCEAEX NDR). Check that Entra Connect syncs proxyAddresses and legacyExchangeDN for this object, run a sync, then run -Action Check.' + if ($failure) { + $text = '{0}: X500 could not be verified in Exchange Online ({1}). {2}' -f $State.Upn, $failure, $advice + $row.CloudDetail = ([string]$row.CloudDetail + ' | X500:not verified').Trim(' ', '|') + } + else { + $shown = @($last.Missing | Select-Object -First 5) -join ', ' + if ($last.Missing.Count -gt 5) { $shown += (' + {0} more (full list in the log)' -f ($last.Missing.Count - 5)) } + foreach ($value in $last.Missing) { Write-PraLog -Context $Context -Message ('{0} | X500 missing in Exchange Online : {1}' -f $State.Upn, $value) -Level Detail } + $text = '{0}: X500 missing in Exchange Online: {1}. {2}' -f $State.Upn, $shown, $advice + $row.CloudDetail = ([string]$row.CloudDetail + ' | X500:missing=' + $last.Missing.Count + '/' + $last.Total).Trim(' ', '|') + } + Write-PraItem -Context $Context -Status Warn -Text $text + $row.Warnings = ([string](Get-PraValue $row 'Warnings' '') + '; ' + $text).Trim(' ', ';') + if (-not $Context.ContainsKey('X500Missing')) { $Context['X500Missing'] = New-Object 'Collections.Generic.List[string]' } + [void]$Context['X500Missing'].Add([string]$State.Upn) +} + +function Invoke-PraX500Step { + <# + .SYNOPSIS + One read of the X500 control (Convert): the addresses read in this iteration (Fresh) or a new read. Returns true once the result is final: + every address present, or the bounded number of reads used up, or Final (a single look: preview, -Once). + #> + param([hashtable]$Context,$State,$Fresh,[int]$MaxReads,[bool]$Final) + $State.X500Reads++; $State.X500Failure = '' + try { + $addresses = if ($null -ne $Fresh) { $Fresh } else { Get-PraCloudAddress -Context $Context -State $State } + 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 } + $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 } + $State.Row.CloudDetail = ([string]$State.Row.CloudDetail -replace ' \| X500:[^|]*\z', '') + ' | ' + $found + return $false } function Invoke-PraCloudPhase { @@ -942,24 +1008,44 @@ function Invoke-PraCloudPhase { if (-not $mb -and -not $lic) { $row.CloudStatus='Skipped'; $row.CloudDetail='No applicable check; no restore confirmation.'; $row.FinalStatus='Skipped'; continue } + # X500 control (Convert): the addresses recorded by the AD phase must be on the cloud mailbox. A batch written before 3.1.0 has none: skipped, never a failure. + $x500Expected=$null + if ($mb -and (Test-PraOrdinalIgnoreCaseEqual $Act 'Convert')) { + $source=Get-PraValue $row 'BackupRec' $null + $stored=Get-PraValue $source 'ExpectedX500' $null + $Context.CurrentIdentity=[string](Get-PraValue $row 'ObjectGuid' $upn); $Context.CurrentOperation='X500Check' + if ($null -eq $stored) { + Write-PraItem -Context $Context -Status Info -Text ('{0}: X500 control skipped, expected addresses not available ({1})' -f $upn, [string](Get-PraValue $source 'ExpectedX500Note' 'batch from 3.0.0 or older')) + } + else { + $x500Expected=[string[]]@(@($stored) | Where-Object { $null -ne $_ } | ForEach-Object { [string]$_ }) + if (-not $x500Expected.Count) { + Write-PraItem -Context $Context -Status Info -Text ('{0}: X500 control skipped, nothing to verify (no legacyExchangeDN and no X500 address on premises)' -f $upn) + $x500Expected=$null + } + } + } $graphMailbox=$mb -and -not $shared -and (Test-PraOrdinalIgnoreCaseEqual $via 'Graph') $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 - ExoMailbox=$exoMailbox; Requests=$requests; PreserveMailbox=$preserveMailbox; PreserveLicense=$preserveLicense; Done=$false }) + ExoMailbox=$exoMailbox; Requests=$requests; PreserveMailbox=$preserveMailbox; PreserveLicense=$preserveLicense; Done=$false + X500=$x500Expected; X500Reads=0; X500Failure=''; X500Last=$null; CoreDone=$false }) } if ($states.Count -eq 0) { return } 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 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 { + if ($s.CoreDone) { $null=Invoke-PraX500Step -Context $Context -State $s -Fresh $null -MaxReads $x500MaxReads -Final ([bool]$Context.Once); continue } $details=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 } + 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) { $m=Invoke-PraExo -Context $Context -Operation 'Mailbox' -Params @{ Upn=$s.Upn } if ((Test-PraOrdinalIgnoreCaseEqual $Act 'Recover')) { @@ -1005,7 +1091,13 @@ function Invoke-PraCloudPhase { $null=Write-PraLog -Context $Context -Message ("{0}: {1}" -f $s.Upn, $what) -Level Success } } - $s.Done=$true + $s.CoreDone=$true + if ($null -ne $s.X500) { + $fresh=$null + if ($s.ExoMailbox) { $fresh=@{ Has=[bool](Get-PraValue $m 'HasAddresses' $false); List=[string[]]@(Get-PraList $m 'Addresses') } } + elseif ($s.GraphMailbox -and $null -ne $facts) { $fresh=@{ Has=$true; List=[string[]]@($facts.Addresses) } } + $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-PraCloudError -Context $Context -Row $row -Message ($_.Exception.Message+' | '+[string]$row.PermDetail); $s.Done=$true } } @@ -1016,12 +1108,14 @@ function Invoke-PraCloudPhase { 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)) $waitText=if ((Test-PraOrdinalIgnoreCaseEqual $Act 'Recover')) { 'Waiting for Exchange Online to finish deprovisioning' } elseif ((Test-PraOrdinalIgnoreCaseEqual $Act 'Convert')) { 'Waiting for the mailbox and licence to appear in Exchange Online' } else { 'Waiting for Exchange Online' } + if (@($pending | Where-Object { -not $_.CoreDone }).Count -eq 0) { $waitText='Waiting for the X500 addresses to appear in Exchange Online (Entra Connect synchronisation)' } Write-PraProgress -Context $Context -Text ("{0} ({1} object(s) not ready)" -f $waitText,$pending.Count) -Current ([int]$clock.Elapsed.TotalSeconds) -Total ([int]$timeout) -Attempt $attempt -MaxAttempts ([int][Math]::Ceiling($timeout/$intervalSeconds)+1) -NextInSeconds ([int][Math]::Ceiling($seconds)) 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 ($s.Done) { continue } + if ($s.CoreDone) { Complete-PraX500Check -Context $Context -State $s; continue } if ($preview) { $s.Row.CloudStatus='Pending'; $s.Row.FinalStatus='Planned' $s.Row.Detail=([string]$s.Row.Detail+' | not yet in the expected state in Exchange Online (preview): '+$s.Row.CloudDetail).Trim(' ','|') diff --git a/package/module/PRA.Directory.psm1 b/package/module/PRA.Directory.psm1 index c51008f..da213f4 100644 --- a/package/module/PRA.Directory.psm1 +++ b/package/module/PRA.Directory.psm1 @@ -837,8 +837,8 @@ function Get-PraExpectedX500 { $list = New-Object 'Collections.Generic.List[string]' if (-not [string]::IsNullOrWhiteSpace($LegacyExchangeDN)) { $value = 'X500:' + $LegacyExchangeDN; if ($seen.Add($value)) { $list.Add($value) } } foreach ($address in @($ProxyAddresses)) { if (Test-PraX500Address $address) { if ($seen.Add([string]$address)) { $list.Add([string]$address) } } } - if ($list.Count -gt $script:MaxExpectedX500) { throw "Too many X500 addresses to verify ($($list.Count), limit $($script:MaxExpectedX500)): conversion refused before any change." } - foreach ($value in $list) { if ($value.Length -gt $script:MaxExpectedX500Length) { throw "X500 address too long to verify ($($value.Length) characters, limit $($script:MaxExpectedX500Length)): conversion refused before any change." } } + if ($list.Count -gt $script:MaxExpectedX500) { throw "Too many X500 addresses to verify ($($list.Count), limit $($script:MaxExpectedX500))." } + foreach ($value in $list) { if ($value.Length -gt $script:MaxExpectedX500Length) { throw "X500 address too long to verify ($($value.Length) characters, limit $($script:MaxExpectedX500Length))." } } return [string[]]$list.ToArray() } #endregion diff --git a/tests/PraRemoteMailbox.Tests.ps1 b/tests/PraRemoteMailbox.Tests.ps1 index e2e0ca1..805f254 100644 --- a/tests/PraRemoteMailbox.Tests.ps1 +++ b/tests/PraRemoteMailbox.Tests.ps1 @@ -296,7 +296,15 @@ function Invoke-PraCloudPhase { param([hashtable]$Context,[object[]]$Rows,[string]$Act) $state=[Management.Automation.PSSerializer]::Deserialize([IO.File]::ReadAllText($env:PRA_GATE_STATE)) [IO.File]::AppendAllText($state.EventPath,('{"Operation":"CloudPhase-SyntheticBarrier","Synthetic":true}'+"`r`n")) - if ($state.Case -eq 'CloudConcurrentChange') { + $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') { + # 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 + Write-PraItem -Context $Context -Status Warn -Text ($Rows[0].UserPrincipalName+': X500 missing in Exchange Online: X500:/o=Synthetic/cn=old. Replies to old messages and meeting updates to this mailbox can bounce (IMCEAEX NDR).') + $Context['X500Missing']=New-Object 'Collections.Generic.List[string]'; [void]$Context['X500Missing'].Add([string]$Rows[0].UserPrincipalName) + } elseif ($state.Case -eq 'CloudConcurrentChange') { # Model a third-party edit during polling, not a cmdlet call by the product. $global:PraGateAd.Users[0].homeMDB='CN=ThirdParty,DC=gate,DC=invalid' $global:PraGateAd.Users[0].uSNChanged=[long]$global:PraGateAd.Users[0].uSNChanged+1 @@ -340,7 +348,7 @@ Export-ModuleMember -Function Get-ADSyncScheduler,Start-ADSyncSyncCycle 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@gate.invalid"; DisplayName="Synthetic User $Index"; Name="User$Index"; objectClass='user' - mail="user$Index@gate.invalid"; mailNickname="user$Index"; uSNChanged=[long]100; memberOf=@(); publicDelegates=@() + mail="user$Index@gate.invalid"; mailNickname="user$Index"; legacyExchangeDN="/o=Synthetic/ou=Gate/cn=Recipients/cn=user$Index"; uSNChanged=[long]100; memberOf=@(); publicDelegates=@() nTSecurityDescriptor=$null; msExchMailboxSecurityDescriptor=$null; msExchArchiveGUID=$null homeMDB="CN=Database$Index,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) @@ -6419,6 +6427,436 @@ Describe 'Release 3.0.0 lot 2c - the window switch -ForceAdReplication and -Base } } +Describe 'Release 3.1.0 - X500 control: Active Directory side (expected addresses recorded in the batch, read only)' -Tag 'Lot6' { + BeforeEach { + $global:PraGate.Runtime=New-GateRuntime -Name 'x500-ad' + $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\x500-ad.log' + $global:PraGate.Legacy1='X500:/o=Synthetic/ou=Gate/cn=Recipients/cn=user1' + $global:PraGate.Older='X500:/o=Synthetic/ou=Gate/cn=User' + } + It 'reads legacyExchangeDN with the other attributes and records X500: first, then the on-premises X500 proxies; nothing else is managed' { + $plan=New-PraPlan $global:PraGate.Context 'user1' 'Convert' + @($plan.Record.ExpectedX500) | Should -BeExactly @($global:PraGate.Legacy1,$global:PraGate.Older) + $plan.Record.ExpectedX500 | Should -BeOfType ([string]) + $plan.Kinds.Keys | Should -Not -Contain 'legacyExchangeDN' + $plan.Record.Attributes.Keys | Should -Not -Contain 'legacyExchangeDN' + $plan.Record.PlannedAttributes.Keys | Should -Not -Contain 'legacyExchangeDN' + $read=@(Get-GateEvents $global:PraGate.Runtime | Where-Object Operation -eq 'Get-ADUser')[0] + @($read.Detail.Properties) | Should -Contain 'legacyExchangeDN' + @(Get-GateWrites $global:PraGate.Runtime).Count | Should -Be 0 + } + It 'removes duplicates (ordinal, ignoring case, whole value), keeps the first spelling byte for byte and ignores non-X500 proxies' { + $user=$global:PraGateAd.Users[0] + $user.proxyAddresses=[string[]]@($user.proxyAddresses)+'x500:/O=SYNTHETIC/OU=GATE/CN=RECIPIENTS/CN=USER1'+'x500:/o=synthetic/ou=gate/cn=user'+'X500:/o=Old/cn=A B '+'X500:/o=Old/cn=A B '+'smtp:x500:not.x500@gate.invalid' + $plan=New-PraPlan $global:PraGate.Context 'user1' 'Convert' + @($plan.Record.ExpectedX500) | Should -BeExactly @($global:PraGate.Legacy1,$global:PraGate.Older,'X500:/o=Old/cn=A B ') + # a value that differs by one character is another address + $user.proxyAddresses=[string[]]@($user.proxyAddresses)+'X500:/o=Old/cn=A B' + @((New-PraPlan $global:PraGate.Context 'user1' 'Convert').Record.ExpectedX500).Count | Should -Be 4 + } + It 'keeps only the X500 proxies when legacyExchangeDN is empty or absent' -ForEach @(@{Shape='empty'},@{Shape='absent'}) { + $user=$global:PraGateAd.Users[0] + if ($Shape -eq 'empty') { $user.legacyExchangeDN='' } else { $user.PSObject.Properties.Remove('legacyExchangeDN') } + $plan=New-PraPlan $global:PraGate.Context 'user1' 'Convert' + @($plan.Record.ExpectedX500) | Should -BeExactly @($global:PraGate.Older) + $user.proxyAddresses=[string[]]@($user.proxyAddresses | Where-Object { $_ -cne $global:PraGate.Older }) + @((New-PraPlan $global:PraGate.Context 'user1' 'Convert').Record.ExpectedX500).Count | Should -Be 0 + } + It 'writes the field in the batch JSON, re-reads it, and never writes, restores or clears legacyExchangeDN' { + $context=$global:PraGate.Context + $plans=@(New-PraPlan $context 'user1' 'Convert';New-PraPlan $context 'user2' 'Convert') + $receipt=Invoke-PraAdBatch $context $plans 'Convert' + $saved=Import-PraBackup $context $receipt.Path + @($saved.Data.Records[0].ExpectedX500) | Should -BeExactly @($global:PraGate.Legacy1,$global:PraGate.Older) + @($saved.Data.Records[1].ExpectedX500) | Should -BeExactly @('X500:/o=Synthetic/ou=Gate/cn=Recipients/cn=user2',$global:PraGate.Older) + $global:PraGateAd.Users[0].legacyExchangeDN | Should -BeExactly '/o=Synthetic/ou=Gate/cn=Recipients/cn=user1' + $writes=@(Get-GateEvents $global:PraGate.Runtime | Where-Object Operation -eq 'Set-ADUser') + $writes.Count | Should -BeGreaterThan 0 + ($writes | ConvertTo-Json -Depth 10) | Should -Not -Match 'legacyExchangeDN' + # Recover: the field is empty (nothing to verify after a rollback) and legacyExchangeDN is still untouched. + $context.Action='Recover'; $context.Source=$receipt; $context.SourceBackupHash=$receipt.Hash + $recover=@(foreach ($record in $receipt.Data.Records) { New-PraPlan $context $record.ObjectGuid 'Recover' $record }) + @($recover[0].Record.ExpectedX500).Count | Should -Be 0 + $null=Invoke-PraAdBatch $context $recover 'Recover' + $global:PraGateAd.Users[0].legacyExchangeDN | Should -BeExactly '/o=Synthetic/ou=Gate/cn=Recipients/cn=user1' + (Get-GateEvents $global:PraGate.Runtime | Where-Object Operation -eq 'Set-ADUser' | ConvertTo-Json -Depth 10) | Should -Not -Match 'legacyExchangeDN' + } + It 'shows "X500 to verify after the conversion: N" per object in the plan (information, nothing changes)' { + $context=$global:PraGate.Context + $context.Mode='Preview'; $context.AllowMutation=$false + $plans=@(New-PraPlan $context 'user1' 'Convert';New-PraPlan $context 'user2' 'Convert') + Invoke-PraAdPreview $context $plans + $log=[IO.File]::ReadAllText($context.LogFile) + $log | Should -Match 'user1: X500 to verify after the conversion: 2' + $log | Should -Match 'user2: X500 to verify after the conversion: 2' + $log | Should -Match ([regex]::Escape('X500 to verify in Exchange Online : '+$global:PraGate.Legacy1)) + $context.Warnings | Should -Be 0 + @(Get-GateWrites $global:PraGate.Runtime).Count | Should -Be 0 + $global:PraGateAd.Users[0].PSObject.Properties.Remove('legacyExchangeDN') + $global:PraGateAd.Users[0].proxyAddresses=[string[]]@($global:PraGateAd.Users[0].proxyAddresses | Where-Object { $_ -cne $global:PraGate.Older }) + Invoke-PraAdPreview $context @(New-PraPlan $context 'user1' 'Convert') + [IO.File]::ReadAllText($context.LogFile) | Should -Match 'user1: X500 to verify after the conversion: 0 \(no legacyExchangeDN and no X500 address on premises\)' + } + It 'reads a record written before 3.1.0 (no ExpectedX500) and refuses an invalid field like KeptX500' { + InModuleScope PRA.Directory { + $plan=New-PraPlan $global:PraGate.Context 'user1' 'Convert' + $record=($plan.Record | ConvertTo-Json -Depth 20 | ConvertFrom-Json -DateKind String) + { Assert-PraStoredRecord $record } | Should -Not -Throw + $record.PSObject.Properties.Remove('ExpectedX500') + { Assert-PraStoredRecord $record } | Should -Not -Throw + $bad=@{ + NotX500=@('smtp:not.x500@gate.invalid'); NullEntry=@('X500:/o=a',$null); Number=@(7); Nested=@(@('X500:/o=a')) + TooLong=@('X500:'+('a' * 2100)); TooMany=@(1..2001 | ForEach-Object { 'X500:/o=Synthetic/cn=' + $_ }); Object=([pscustomobject]@{Value='X500:/o=a'}) + } + foreach ($name in $bad.Keys) { + $record | Add-Member -NotePropertyName ExpectedX500 -NotePropertyValue $bad[$name] -Force + { Assert-PraStoredRecord $record } | Should -Throw '*expected X500*' -Because $name + } + $record | Add-Member -NotePropertyName ExpectedX500 -NotePropertyValue @('X500:/o=a','x500:/o=B') -Force + { Assert-PraStoredRecord $record } | Should -Not -Throw + } + } + It 'refuses a re-read batch whose expected X500 list differs from the plan, and refuses an object with too many X500 addresses before any change' { + InModuleScope PRA.Directory { + $plan=New-PraPlan $global:PraGate.Context 'user1' 'Convert' + $stored=($plan.Record | ConvertTo-Json -Depth 20 | ConvertFrom-Json -DateKind String) + { Assert-PraRecordMatchesPlan -Stored $stored -Expected $plan.Record } | Should -Not -Throw + $stored.ExpectedX500=@($stored.ExpectedX500[0]) + { Assert-PraRecordMatchesPlan -Stored $stored -Expected $plan.Record } | Should -Throw '*expected X500 addresses not preserved*' + $stored.ExpectedX500=@($stored.ExpectedX500[0],($plan.Record.ExpectedX500[1].ToLowerInvariant())) + { Assert-PraRecordMatchesPlan -Stored $stored -Expected $plan.Record } | Should -Throw '*expected X500 addresses not preserved*' + $global:PraGateAd.Users[0].proxyAddresses=[string[]]@(1..2001 | ForEach-Object { 'X500:/o=Synthetic/cn=' + $_ }) + { New-PraPlan $global:PraGate.Context 'user1' 'Convert' } | Should -Throw '*Too many X500 addresses*' + } + @(Get-GateWrites $global:PraGate.Runtime).Count | Should -Be 0 + } +} + +Describe 'Release 3.1.0 - X500 control: Exchange Online side (production Cloud module, mocked boundaries, no network)' -Tag 'Lot6' { + BeforeAll { + $global:PraGate.X500NetworkPath=Join-Path $global:PraGate.Root 'PraGateX500Network.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,$Property) throw 'SYNTHETIC BLOCK: Graph user' } +function Get-MgUserLicenseDetail { [CmdletBinding()]param($UserId,[switch]$All) throw 'SYNTHETIC BLOCK: Graph license' } +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.X500NetworkPath} } +Export-ModuleMember -Function Get-EXOMailbox,Get-EXORecipient,Get-MgUser,Get-MgUserLicenseDetail,Get-ConnectionInformation,Get-MgContext +'@ + [IO.File]::WriteAllText($global:PraGate.X500NetworkPath,$networkSource,(New-Object Text.UTF8Encoding($true))) + Import-Module $global:PraGate.X500NetworkPath -Global -Force + Import-Module (Join-Path $global:PraGate.Package 'module\PRA.Cloud.psm1') -Force -Global + $global:PraGate.X500Legacy='X500:/o=Synthetic/ou=Gate/cn=Recipients/cn=user1' + $global:PraGate.X500Older='X500:/o=Synthetic/ou=Gate/cn=User' + $global:PraGate.X500Oldest='X500:/o=Contoso/ou=First Administrative Group/cn=Recipients/cn=user1' + function global:New-X500Row { + param([string]$Upn='user1@gate.invalid',[string]$Guid='00000000-0000-0000-0000-000000000001',[string[]]$Expected,[switch]$NoField,[string]$Note='') + $record=[ordered]@{ObjectGuid=$Guid;UserPrincipalName=$Upn;IsShared=$false} + if (-not $NoField) { $record.ExpectedX500=[string[]]$Expected } + if ($Note) { $record.ExpectedX500Note=$Note } + New-PraRow $global:PraGate.CloudContext ([pscustomobject]$record) + } + function global:Get-X500Log { [IO.File]::ReadAllText($global:PraGate.CloudContext.LogFile) } + } + BeforeEach { + $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.SharedMailbox.GrantFullAccess=$false + $context.LogFile=Join-Path $global:PraGate.Runtime.Root 'logs\x500-cloud.log' + $global:PraGate.CloudContext=$context + $global:PraGate.X500Calls=0; $global:PraGate.X500Reply=$null + $global:PraGate.X500Binding=@{TenantId='20000000-0000-0000-0000-000000000002';ConnectionId='30000000-0000-0000-0000-000000000003';ModuleLocation=$global:PraGate.X500NetworkPath;ModulePath=$global:PraGate.X500NetworkPath} + } + AfterAll { + Remove-Item -LiteralPath 'Function:\New-X500Row','Function:\Get-X500Log' -ErrorAction SilentlyContinue + Remove-Module PRA.Cloud,PraGateX500Network -Force -ErrorAction SilentlyContinue + } + It 'every expected address present (case of the type prefix may differ): an Ok line, no warning, one read' { + $global:PraGate.CloudRow=New-X500Row -Expected @($global:PraGate.X500Legacy,$global:PraGate.X500Older,$global:PraGate.X500Oldest) + $global:PraGate.X500Reply=[pscustomobject]@{RecipientTypeDetails='UserMailbox';EmailAddresses=[string[]]@('SMTP:user1@gate.invalid','smtp:user1@synthetic.mail.onmicrosoft.com',$global:PraGate.X500Legacy.Replace('X500:','x500:'),$global:PraGate.X500Older,$global:PraGate.X500Oldest)} + InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { param($Context) $Context['_PraCloudSession']=@{Graph=$false;Exo=$true;Subprocess=$false;Binding=$global:PraGate.X500Binding} } + Mock Close-PraCloudSession { } + Mock Start-Sleep { } + Mock Get-EXOMailbox { $global:PraGate.X500Calls++; $global:PraGate.X500Reply } + Invoke-PraCloudPhase $global:PraGate.CloudContext @($global:PraGate.CloudRow) 'Convert' + } + $row=$global:PraGate.CloudRow + $row.CloudStatus | Should -BeExactly 'Success' + $row.FinalStatus | Should -BeExactly 'Success' + $row.Warnings | Should -BeNullOrEmpty + $row.CloudDetail | Should -Match 'X500:present=3/3' + $global:PraGate.CloudContext.Warnings | Should -Be 0 + $global:PraGate.CloudContext.Issues.Count | Should -Be 0 + @(Get-PraList $global:PraGate.CloudContext 'X500Missing').Count | Should -Be 0 + Get-X500Log | Should -Match ([regex]::Escape('user1@gate.invalid: X500: 3 of 3 present (legacyExchangeDN + older X500)')) + $global:PraGate.X500Calls | Should -Be 1 + } + It 'one address missing after the bounded re-reads: ONE warning listing it (not an error), counted everywhere, the conversion stays done' { + $global:PraGate.CloudRow=New-X500Row -Expected @($global:PraGate.X500Legacy,$global:PraGate.X500Older,$global:PraGate.X500Oldest) + $global:PraGate.X500Reply=[pscustomobject]@{RecipientTypeDetails='UserMailbox';EmailAddresses=[string[]]@('SMTP:user1@gate.invalid',$global:PraGate.X500Legacy,$global:PraGate.X500Older)} + InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { param($Context) $Context['_PraCloudSession']=@{Graph=$false;Exo=$true;Subprocess=$false;Binding=$global:PraGate.X500Binding} } + Mock Close-PraCloudSession { } + Mock Start-Sleep { } + Mock Get-EXOMailbox { $global:PraGate.X500Calls++; $global:PraGate.X500Reply } + Invoke-PraCloudPhase $global:PraGate.CloudContext @($global:PraGate.CloudRow) 'Convert' + } + $row=$global:PraGate.CloudRow; $context=$global:PraGate.CloudContext + $global:PraGate.X500Calls | Should -Be 3 -Because 'the first read and two re-reads, never a long new wait' + $row.CloudStatus | Should -BeExactly 'Success' + $row.FinalStatus | Should -BeExactly 'Success' + $context.Issues.Count | Should -Be 0 + $context.Warnings | Should -Be 1 + $warnings=@(Get-PraList $context 'WarningList') + $warnings.Count | Should -Be 1 + $warnings[0].Message | Should -BeExactly ('user1@gate.invalid: X500 missing in Exchange Online: '+$global:PraGate.X500Oldest+'. Replies to old messages and meeting updates to this mailbox can bounce (IMCEAEX NDR). Check that Entra Connect syncs proxyAddresses and legacyExchangeDN for this object, run a sync, then run -Action Check.') + $row.Warnings | Should -Match ([regex]::Escape($global:PraGate.X500Oldest)) + $row.CloudDetail | Should -Match 'X500:missing=1/3' + @(Get-PraList $context 'X500Missing') | Should -BeExactly @('user1@gate.invalid') + @(Get-PraList $context 'Journey' | Where-Object { $_.Status -eq 'Warn' -and $_.Text -match 'X500 missing' }).Count | Should -Be 1 + Get-X500Log | Should -Match '\[WARN \] user1@gate.invalid: X500 missing in Exchange Online' + Get-X500Log | Should -Match ([regex]::Escape('user1@gate.invalid | X500 missing in Exchange Online : '+$global:PraGate.X500Oldest)) + } + It 'a value that lags one synchronisation: missing at the first read, present at the second: Ok after the re-read, progress events sent' { + $global:PraGate.CloudRow=New-X500Row -Expected @($global:PraGate.X500Legacy,$global:PraGate.X500Older) + $global:PraGate.X500Reply=[pscustomobject]@{RecipientTypeDetails='UserMailbox';EmailAddresses=[string[]]@('SMTP:user1@gate.invalid',$global:PraGate.X500Legacy)} + $eventFile=Join-Path $global:PraGate.Runtime.Root 'x500.events.jsonl'; $oldEvent=$env:PRA_EVENT_FILE; $env:PRA_EVENT_FILE=$eventFile + try { + InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { param($Context) $Context['_PraCloudSession']=@{Graph=$false;Exo=$true;Subprocess=$false;Binding=$global:PraGate.X500Binding} } + Mock Close-PraCloudSession { } + Mock Start-Sleep { } + Mock Get-EXOMailbox { + $global:PraGate.X500Calls++ + if ($global:PraGate.X500Calls -ge 2) { $global:PraGate.X500Reply.EmailAddresses=[string[]]@('SMTP:user1@gate.invalid',$global:PraGate.X500Legacy,$global:PraGate.X500Older) } + $global:PraGate.X500Reply + } + Invoke-PraCloudPhase $global:PraGate.CloudContext @($global:PraGate.CloudRow) 'Convert' + } + } finally { $env:PRA_EVENT_FILE=$oldEvent } + $row=$global:PraGate.CloudRow; $context=$global:PraGate.CloudContext + $global:PraGate.X500Calls | Should -Be 2 + $row.CloudStatus | Should -BeExactly 'Success' + $context.Warnings | Should -Be 0 + $context.Issues.Count | Should -Be 0 + @(Get-PraList $context 'X500Missing').Count | Should -Be 0 + Get-X500Log | Should -Match ([regex]::Escape('user1@gate.invalid: X500: 2 of 2 present (legacyExchangeDN + older X500)')) + $progress=@(Get-Content -LiteralPath $eventFile -Encoding UTF8 | ForEach-Object { $_ | ConvertFrom-Json -DateKind String } | Where-Object kind -eq 'progress') + $progress.Count | Should -BeGreaterThan 0 + ($progress.text -join ' ') | Should -Match 'Waiting for the X500 addresses to appear in Exchange Online' + } + It 'a batch without the field (3.0.0 or older) is skipped with an explicit information line, never a warning or a failure' { + $global:PraGate.CloudRow=New-X500Row -NoField + $global:PraGate.X500Reply=[pscustomobject]@{RecipientTypeDetails='UserMailbox';EmailAddresses=[string[]]@('SMTP:user1@gate.invalid')} + InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { param($Context) $Context['_PraCloudSession']=@{Graph=$false;Exo=$true;Subprocess=$false;Binding=$global:PraGate.X500Binding} } + Mock Close-PraCloudSession { } + Mock Start-Sleep { } + Mock Get-EXOMailbox { $global:PraGate.X500Calls++; $global:PraGate.X500Reply } + Invoke-PraCloudPhase $global:PraGate.CloudContext @($global:PraGate.CloudRow) 'Convert' + } + $global:PraGate.CloudRow.CloudStatus | Should -BeExactly 'Success' + $global:PraGate.CloudContext.Warnings | Should -Be 0 + $global:PraGate.CloudContext.Issues.Count | Should -Be 0 + $global:PraGate.X500Calls | Should -Be 1 + Get-X500Log | Should -Match ([regex]::Escape('user1@gate.invalid: X500 control skipped, expected addresses not available (batch from 3.0.0 or older)')) + } + It 'an empty list (no legacyExchangeDN, no X500) says there is nothing to verify' { + $global:PraGate.CloudRow=New-X500Row -Expected @() + $global:PraGate.X500Reply=[pscustomobject]@{RecipientTypeDetails='UserMailbox';EmailAddresses=[string[]]@('SMTP:user1@gate.invalid')} + InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { param($Context) $Context['_PraCloudSession']=@{Graph=$false;Exo=$true;Subprocess=$false;Binding=$global:PraGate.X500Binding} } + Mock Close-PraCloudSession { } + Mock Start-Sleep { } + Mock Get-EXOMailbox { $global:PraGate.X500Calls++; $global:PraGate.X500Reply } + Invoke-PraCloudPhase $global:PraGate.CloudContext @($global:PraGate.CloudRow) 'Convert' + } + $global:PraGate.CloudRow.CloudStatus | Should -BeExactly 'Success' + $global:PraGate.CloudContext.Warnings | Should -Be 0 + Get-X500Log | Should -Match 'X500 control skipped, nothing to verify' + } + It 'EmailAddresses not returned by Exchange Online: a warning (cannot be proven), not an error, and the request asks for the property' { + $global:PraGate.CloudRow=New-X500Row -Expected @($global:PraGate.X500Legacy) + $global:PraGate.X500Reply=[pscustomobject]@{RecipientTypeDetails='UserMailbox'} + InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { param($Context) $Context['_PraCloudSession']=@{Graph=$false;Exo=$true;Subprocess=$false;Binding=$global:PraGate.X500Binding} } + Mock Close-PraCloudSession { } + Mock Start-Sleep { } + Mock Get-EXOMailbox { param($Filter,$Properties,$ResultSize) $global:PraGate.X500Calls++; $global:PraGate.X500Props=@($Properties); $global:PraGate.X500Reply } + Invoke-PraCloudPhase $global:PraGate.CloudContext @($global:PraGate.CloudRow) 'Convert' + } + $global:PraGate.X500Props | Should -Contain 'EmailAddresses' + $global:PraGate.CloudRow.CloudStatus | Should -BeExactly 'Success' + $global:PraGate.CloudContext.Issues.Count | Should -Be 0 + $global:PraGate.CloudContext.Warnings | Should -Be 1 + $global:PraGate.CloudRow.Warnings | Should -Match 'X500 could not be verified in Exchange Online \(EmailAddresses not returned by Exchange Online\)' + } + It 'a single look (preview or -Once) reads once, never waits, and warns about what is missing' { + $global:PraGate.CloudRow=New-X500Row -Expected @($global:PraGate.X500Legacy,$global:PraGate.X500Older) + $global:PraGate.CloudContext.Mode='Preview'; $global:PraGate.CloudContext.AllowMutation=$false; $global:PraGate.CloudContext.Once=$true + $global:PraGate.X500Reply=[pscustomobject]@{RecipientTypeDetails='UserMailbox';EmailAddresses=[string[]]@($global:PraGate.X500Legacy)} + InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { param($Context) $Context['_PraCloudSession']=@{Graph=$false;Exo=$true;Subprocess=$false;Binding=$global:PraGate.X500Binding} } + Mock Close-PraCloudSession { } + Mock Start-Sleep { throw 'A single look must not wait.' } + Mock Get-EXOMailbox { $global:PraGate.X500Calls++; $global:PraGate.X500Reply } + Invoke-PraCloudPhase $global:PraGate.CloudContext @($global:PraGate.CloudRow) 'Convert' + } + $global:PraGate.X500Calls | Should -Be 1 + $global:PraGate.CloudContext.Warnings | Should -Be 1 + $global:PraGate.CloudContext.Issues.Count | Should -Be 0 + $global:PraGate.CloudRow.Warnings | Should -Match ([regex]::Escape($global:PraGate.X500Older)) + } + It 'two objects: the one that is complete is Ok, the other one warns, and the next-step list counts only the second' { + $global:PraGate.CloudRow=New-X500Row -Expected @($global:PraGate.X500Legacy) + $second=New-X500Row -Upn 'user2@gate.invalid' -Guid '00000000-0000-0000-0000-000000000002' -Expected @('X500:/o=Synthetic/ou=Gate/cn=Recipients/cn=user2') + $global:PraGate.X500Reply=[pscustomobject]@{RecipientTypeDetails='UserMailbox';EmailAddresses=[string[]]@($global:PraGate.X500Legacy)} + $global:PraGate.X500Second=$second + InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { param($Context) $Context['_PraCloudSession']=@{Graph=$false;Exo=$true;Subprocess=$false;Binding=$global:PraGate.X500Binding} } + Mock Close-PraCloudSession { } + Mock Start-Sleep { } + Mock Get-EXOMailbox { $global:PraGate.X500Calls++; $global:PraGate.X500Reply } + Invoke-PraCloudPhase $global:PraGate.CloudContext @($global:PraGate.CloudRow,$global:PraGate.X500Second) 'Convert' + } + $global:PraGate.CloudRow.Warnings | Should -BeNullOrEmpty + $global:PraGate.X500Second.Warnings | Should -Match 'user2@gate.invalid: X500 missing in Exchange Online: X500:/o=Synthetic/ou=Gate/cn=Recipients/cn=user2' + @(Get-PraList $global:PraGate.CloudContext 'X500Missing') | Should -BeExactly @('user2@gate.invalid') + $global:PraGate.CloudContext.Warnings | Should -Be 1 + $global:PraGate.CloudRow.CloudStatus | Should -BeExactly 'Success' + $global:PraGate.X500Second.CloudStatus | Should -BeExactly 'Success' + } + It 'Microsoft Graph mailbox check: the Entra proxyAddresses are compared, so no Exchange Online session is needed' { + $global:PraGate.CloudContext.Config.Cloud.MailboxCheckVia='Graph' + $global:PraGate.CloudRow=New-X500Row -Expected @($global:PraGate.X500Legacy,$global:PraGate.X500Older) + InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { param($Context) $Context['_PraCloudSession']=@{Graph=$true;Exo=$false;Subprocess=$false;GraphContext=@{TenantId='20000000-0000-0000-0000-000000000002';ContextScope='Process'}} } + Mock Close-PraCloudSession { } + Mock Start-Sleep { } + Mock Get-EXOMailbox { throw 'The Graph path must not call Exchange Online.' } + Mock Get-MgUser { + $global:PraGate.X500Calls++ + [pscustomobject]@{assignedPlans=@([pscustomobject]@{Service='exchange';CapabilityStatus='Enabled'});provisionedPlans=@([pscustomobject]@{Service='exchange';ProvisioningStatus='Success'}) + proxyAddresses=[string[]]@('SMTP:user1@gate.invalid',$global:PraGate.X500Legacy,$global:PraGate.X500Older)} + } + Mock Get-MgUserLicenseDetail { [pscustomobject]@{SkuPartNumber='SYNTHETIC';ServicePlans=@([pscustomobject]@{ServicePlanName='EXCHANGE_S_ENTERPRISE';ProvisioningStatus='Success'})} } + Invoke-PraCloudPhase $global:PraGate.CloudContext @($global:PraGate.CloudRow) 'Convert' + } + $global:PraGate.CloudRow.CloudStatus | Should -BeExactly 'Success' + $global:PraGate.CloudContext.Warnings | Should -Be 0 + $global:PraGate.X500Calls | Should -Be 1 + Get-X500Log | Should -Match ([regex]::Escape('X500: 2 of 2 present')) + } + It 'Check shows the same comparison read-only (present, missing) and says when the identity was given as a UPN' { + $context=$global:PraGate.CloudContext + $context.Mode='Preview'; $context.Action='Check'; $context.AllowMutation=$false; $context.Once=$false; $context.TimeoutMinutes=1 + $global:PraGate.CloudRow=New-X500Row -Expected @($global:PraGate.X500Legacy,$global:PraGate.X500Older) + $global:PraGate.X500Second=New-X500Row -Upn 'upn.only@gate.invalid' -Guid '00000000-0000-0000-0000-000000000009' -NoField -Note 'identity given as a UPN, no Active Directory read: give the sAMAccountName or -Batch' + $global:PraGate.X500Reply=[pscustomobject]@{RecipientTypeDetails='UserMailbox';EmailAddresses=[string[]]@($global:PraGate.X500Legacy)} + InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { param($Context) $Context['_PraCloudSession']=@{Graph=$false;Exo=$true;Subprocess=$false;Binding=$global:PraGate.X500Binding} } + Mock Close-PraCloudSession { } + Mock Start-Sleep { } + Mock Get-EXOMailbox { $global:PraGate.X500Calls++; $global:PraGate.X500Reply } + Invoke-PraCloudPhase $global:PraGate.CloudContext @($global:PraGate.CloudRow,$global:PraGate.X500Second) 'Convert' + } + $global:PraGate.CloudRow.Warnings | Should -Match ([regex]::Escape($global:PraGate.X500Older)) + $global:PraGate.CloudContext.Warnings | Should -Be 1 + Get-X500Log | Should -Match ([regex]::Escape('upn.only@gate.invalid: X500 control skipped, expected addresses not available (identity given as a UPN')) + @(Get-GateWrites $global:PraGate.Runtime).Count | Should -Be 0 + } + It 'the warning travels into the run result, the per-phase data and the global report, HTML-encoded and without markup injection' { + $hostile='X500:/o=Synthetic/cn=A&B "q"' + $global:PraGate.CloudRow=New-X500Row -Expected @($global:PraGate.X500Legacy,$hostile) + $global:PraGate.X500Reply=[pscustomobject]@{RecipientTypeDetails='UserMailbox';EmailAddresses=[string[]]@($global:PraGate.X500Legacy)} + InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { param($Context) $Context['_PraCloudSession']=@{Graph=$false;Exo=$true;Subprocess=$false;Binding=$global:PraGate.X500Binding} } + Mock Close-PraCloudSession { } + Mock Start-Sleep { } + Mock Get-EXOMailbox { $global:PraGate.X500Calls++; $global:PraGate.X500Reply } + Invoke-PraCloudPhase $global:PraGate.CloudContext @($global:PraGate.CloudRow) 'Convert' + } + $context=$global:PraGate.CloudContext + $context.Rows.Add($global:PraGate.CloudRow); $context.BatchId='abcd1234'; $context.NextSteps=@(); $context.PhaseFolders=@() + @(Get-PraList $context 'WarningList').Count | Should -Be 1 + $phase = New-PraPhaseRecord -Context $context + (@(Get-PraList $phase 'Warnings') | ForEach-Object { $_.Message }) -join ' ' | Should -Match 'X500 missing in Exchange Online' + $report=Write-PraGlobalReport -Context $context + $html=[IO.File]::ReadAllText($report.Html) + $html | Should -Not -Match 'A&B' + $html | Should -Match ([regex]::Escape('<b>A&B</b>')) + $html | Should -Match 'X500 missing in Exchange Online' + $csv=[IO.File]::ReadAllText($report.Csv) + $csv | Should -Match 'X500 missing in Exchange Online' + } + It 'two servers: the expected X500 list travels in the transfer package and is the one the cloud server proves' { + $adRuntime=New-GateRuntime -Name 'x500-two-ad' + $oldEvent=$env:PRA_EVENT_FILE; $env:PRA_EVENT_FILE=Join-Path $adRuntime.Root 'engine.events.jsonl' + try { + $run=Invoke-GateProcess $adRuntime @{Action='Convert';Phase='AD';Mode='Apply';Force=$true;ConfigPath=$adRuntime.ConfigPath} -TimeoutSeconds 120 + $run.ExitCode | Should -BeIn @(0,2) -Because ($run.Output+$run.Error) + $zip=@(Get-Content -LiteralPath $env:PRA_EVENT_FILE -Encoding UTF8 | ForEach-Object { $_ | ConvertFrom-Json -DateKind String } | Where-Object kind -eq 'result')[0].transferPackage + } finally { $env:PRA_EVENT_FILE=$oldEvent } + $cloudRuntime=New-GateRuntime -Name 'x500-two-cloud' + $imported=Import-PraTransferPackage -Path $zip -BackupFolder $cloudRuntime.State.BackupFolder -Environment SYNTHETIC_GATE -ExpectedKind Convert + $batchFile=@(Get-ChildItem -LiteralPath $imported.Folders[0] -File -Filter 'Convert-*.json' | Where-Object { -not $_.Name.EndsWith('.sha256',[StringComparison]::Ordinal) })[0] + $importContext=New-GateContext $cloudRuntime + $receipt=Import-PraBackup $importContext $batchFile.FullName + @($receipt.Data.Records[0].ExpectedX500) | Should -BeExactly @($global:PraGate.X500Legacy,$global:PraGate.X500Older) + # the cloud server: the row is built from the stored record, exactly as the entry script does + $global:PraGate.CloudRow=New-X500Row -Expected @() + $global:PraGate.CloudRow.BackupRec=$receipt.Data.Records[0] + $global:PraGate.X500Reply=[pscustomobject]@{RecipientTypeDetails='UserMailbox';EmailAddresses=[string[]]@($global:PraGate.X500Legacy)} + InModuleScope PRA.Cloud { + Mock Connect-PraCloudSession { param($Context) $Context['_PraCloudSession']=@{Graph=$false;Exo=$true;Subprocess=$false;Binding=$global:PraGate.X500Binding} } + Mock Close-PraCloudSession { } + Mock Start-Sleep { } + Mock Get-EXOMailbox { $global:PraGate.X500Calls++; $global:PraGate.X500Reply } + Invoke-PraCloudPhase $global:PraGate.CloudContext @($global:PraGate.CloudRow) 'Convert' + } + $global:PraGate.CloudContext.Warnings | Should -Be 1 + $global:PraGate.CloudRow.Warnings | Should -Match ([regex]::Escape('X500 missing in Exchange Online: '+$global:PraGate.X500Older+'.')) + $global:PraGate.CloudRow.CloudStatus | Should -BeExactly 'Success' + } +} + +Describe 'Release 3.1.0 - X500 control through the real main (Check of one identity, Next steps)' -Tag 'Lot6' { + It 'Check -Identity reads legacyExchangeDN in Active Directory (sAMAccountName) or says why it cannot (UPN)' -ForEach @( + @{Identity='user1';Expected='X500:/o=Synthetic/ou=Gate/cn=Recipients/cn=user1|X500:/o=Synthetic/ou=Gate/cn=User';Note=''} + @{Identity='user1@gate.invalid';Expected='';Note='identity given as a UPN, no Active Directory read'} + ) { + $runtime=New-GateRuntime -Name 'x500-check-main' + $run=Invoke-GateProcess $runtime @{Action='Check';Identity=$Identity;ConfigPath=$runtime.ConfigPath} -TimeoutSeconds 120 + $run.ExitCode | Should -BeIn @(0,2) -Because ($run.Output+$run.Error) + $barrier=@($run.Events | Where-Object Operation -eq 'CloudRows-SyntheticBarrier') + $barrier.Count | Should -Be 1 + $row=@($barrier[0].Rows)[0] + (@($row.ExpectedX500) -join '|') | Should -BeExactly $Expected + [string]$row.Note | Should -Match ([regex]::Escape($Note)) + @(Get-GateWrites $runtime).Count | Should -Be 0 + } + It 'a missing X500 reported by the cloud phase is a warning in the result and a line in the Next steps with the Check command; the exit code does not change' { + $runtime=New-GateRuntime -Name 'x500-next-steps' -Case CloudX500Missing + $run=Invoke-GateProcess $runtime @{Action='Convert';Phase='Both';Mode='Apply';Force=$true;ConfigPath=$runtime.ConfigPath} -TimeoutSeconds 120 + $run.ExitCode | Should -Be 0 -Because ($run.Output+$run.Error) + $run.MainResult.ErrorCount | Should -Be 0 + $run.MainResult.WarningCount | Should -BeGreaterThan 0 + $next=($run.MainResult.NextSteps -join "`n") + $next | Should -Match 'X500 missing in Exchange Online for 1 object\(s\) \(replies to old messages can bounce\): run an Entra Connect synchronisation, then check again: \.\\Invoke-PraRemoteMailbox\.ps1 -Action Check -Batch [0-9a-f]{8} ' + $next | Should -Match 'To roll back this batch later' + $run.Output | Should -Match 'X500 missing in Exchange Online' + } +} + AfterAll { $env:PSModulePath=$global:PraGate.OriginalModulePath $env:PRA_GATE_NONET=$global:PraGate.OriginalNonet From 43a615f2c0619d67f8c415b6a719681fc8116ab5 Mon Sep 17 00:00:00 2001 From: Nicolas Fabert <195452170+Nico77600@users.noreply.github.com> Date: Thu, 5 Nov 2026 12:17:06 +0100 Subject: [PATCH 03/14] 3.1.0: version bump, X500 control documented (reference guide, user guide, README, CHANGELOG), guides rebuilt --- CHANGELOG.md | 16 ++++++++++ README.md | 3 +- package/Invoke-PraRemoteMailbox.ps1 | 2 +- package/PackageIntegrity.psd1 | 2 +- package/PraRemoteMailbox.psd1 | 2 +- package/PraRemoteMailbox.psm1 | 2 +- package/README.md | 2 +- package/config/PraRemoteMailbox.config.psd1 | 2 +- package/docs/PraRemoteMailbox-Guide.html | 31 ++++++++++++++++--- package/docs/PraRemoteMailbox-Guide.md | 26 +++++++++++++--- package/docs/PraRemoteMailbox-UserGuide.html | 11 +++++-- package/docs/PraRemoteMailbox-UserGuide.md | 3 +- package/module/PRA.Backup.psm1 | 2 +- package/module/PRA.Cloud.psm1 | 2 +- package/module/PRA.Common.psm1 | 6 ++-- package/module/PRA.Directory.psm1 | 2 +- package/module/PRA.Gui.Directory.ps1 | 2 +- package/module/PRA.Gui.psm1 | 2 +- package/templates/Report.template.html | 2 +- tests/IntegrityFixture.ps1 | 2 +- tests/Invoke-TestGate.ps1 | 2 +- tests/PackageIntegrity.Tests.ps1 | 4 +-- tests/PraDocumentation.Tests.ps1 | 4 +-- tests/PraRemoteMailbox.Tests.ps1 | 6 ++-- tests/PraReport.Tests.ps1 | 4 +-- tools/Build-Documentation.ps1 | 2 +- tools/DocumentationImages/New-PackageCopy.ps1 | 2 +- .../Show-ConsoleScreens.ps1 | 2 +- tools/DocumentationImages/StubEngine.ps1 | 2 +- .../DocumentationImages/StubPackageCheck.ps1 | 2 +- tools/New-DocumentationImages.ps1 | 2 +- tools/New-PraPackage.ps1 | 4 +-- 32 files changed, 110 insertions(+), 48 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a407de..c266dd5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,22 @@ All notable changes of PRA Remote Mailbox. Author: Nicolas Fabert. Versions foll a MAJOR version changes the command line or the configuration file, a MINOR version adds a feature, a PATCH version fixes a defect. The backup formats have their own version (see the guide, annex D). +## 3.1.0 — 2026-11-05 + +### Added +- **X500 control at Convert.** The AD phase now also reads `legacyExchangeDN` (read only, never written or restored) and + records in the batch the X500 addresses the cloud mailbox must carry: `X500:` plus the X500 addresses + already in the on-premises `proxyAddresses`. Once the mailbox is ready, the cloud phase proves them in Exchange Online + (the Entra `proxyAddresses` when the mailbox check goes through Graph), re-reads a few times for a synchronisation lag, + and warns per mailbox when one is missing: replies to old messages and meeting updates could bounce (IMCEAEX NDR). + The conversion stays done. +- The preview shows *X500 to verify after the conversion: N*; `-Action Check` and the console's *Check a mailbox* show + the same comparison, read only. The warning is counted in the result, the reports and the Next steps. + +### Changed +- A batch written before 3.1.0 has no expected list: the control is skipped with an information line, never a failure. + The backup schema is unchanged (one more optional field per record). + ## 3.0.0 — 2026-11-05 **Breaking: PowerShell 7.5+ required.** Windows PowerShell 5.1 is refused before any code runs; use 2.x there. diff --git a/README.md b/README.md index c9fd1a2..e50bba6 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,7 @@ In a hybrid organisation, a mailbox hosted on-premises is only a *mail user* for Done by hand, this means rewriting about ten Exchange attributes per object in Active Directory, for hundreds of objects, under stress — and keeping every original value to come back later: a wrong or lost value cannot be repaired without a backup. This tool does the conversion in a planned, verified and **reversible** way. -**Author:** Nicolas Fabert · **Version:** 3.0.0, 2026-11-05 ([changelog](CHANGELOG.md)). +**Author:** Nicolas Fabert · **Version:** 3.1.0, 2026-11-05 ([changelog](CHANGELOG.md)). > [!CAUTION] > Convert creates **new, empty** mailboxes in Exchange Online: the content of the on-premises mailboxes is not moved. A Recover deprovisions the cloud mailboxes: export first what was received in the cloud during the disaster, or protect it with a retention policy (reference guide, chapter 6). @@ -145,6 +145,7 @@ Keep the `Backups` folder on a durable, protected volume: the backups are the on - **Signed package.** The runtime lives in `package\` (same layout as the extracted release ZIP). Every runtime file authenticates the owner-signed manifest before it runs; a changed, missing or unexpected stable file stops the tool before any import or operation. The configuration and your CSV lists are data, outside that check. There is no unsigned mode. The tool refuses to run from any tree whose files are not signed by the owner: use a signed release package. Backup, log and report folders inside the package are limited to the canonical `Backups`, `logs` and `reports`. See [package/README.md](package/README.md). - **One script, one configuration file.** The scope is one object (`-Identity`), an OU, the members of an AD group or a CSV list — users only, shared mailboxes only, or both. - **Preview by default.** Without `-Mode Apply` the tool only reads. With `-Mode Apply` it shows the plan and asks **one** confirmation (`-Force` for unattended runs). +- **X500 control.** The batch records the X500 addresses (`legacyExchangeDN` and older X500) that the cloud mailbox must carry; the cloud phase proves them and warns if one is missing, because replies to old messages would otherwise bounce. - **One batch ID** links the steps: every Apply prints it with the exact next command, and `-Action Recover -Batch ` rolls the batch back. - **One or two servers**: everything from one server, or the AD part on-premises and the cloud part on an isolated server. diff --git a/package/Invoke-PraRemoteMailbox.ps1 b/package/Invoke-PraRemoteMailbox.ps1 index 170cb2a..c02cc6f 100644 --- a/package/Invoke-PraRemoteMailbox.ps1 +++ b/package/Invoke-PraRemoteMailbox.ps1 @@ -131,7 +131,7 @@ .NOTES Author : Nicolas Fabert - Version : 3.0.0 + Version : 3.1.0 Requires : PowerShell 7.5 or later (pwsh.exe; Windows PowerShell 5.1 is refused), RSAT ActiveDirectory, ExchangeOnlineManagement 3.10+, Microsoft.Graph.Authentication and Microsoft.Graph.Users (cloud part), ADSync (sync; through the Windows PowerShell compatibility layer when local). diff --git a/package/PackageIntegrity.psd1 b/package/PackageIntegrity.psd1 index 91741e8..6b316aa 100644 --- a/package/PackageIntegrity.psd1 +++ b/package/PackageIntegrity.psd1 @@ -1,4 +1,4 @@ -# PRA Remote Mailbox 3.0.0 - authenticated package integrity manifest +# PRA Remote Mailbox 3.1.0 - authenticated package integrity manifest # Generated only after the final stable-file signatures and timestamps. @{ SchemaVersion = 1 diff --git a/package/PraRemoteMailbox.psd1 b/package/PraRemoteMailbox.psd1 index ea5b8e9..2454ef9 100644 --- a/package/PraRemoteMailbox.psd1 +++ b/package/PraRemoteMailbox.psd1 @@ -19,7 +19,7 @@ # @{ RootModule = 'PraRemoteMailbox.psm1' - ModuleVersion = '3.0.0' + ModuleVersion = '3.1.0' GUID = '1d97585b-d077-4d74-bf10-4e36d16308b6' Author = 'Nicolas Fabert' Description = 'PRA Remote Mailbox: disaster-recovery tool for an Exchange hybrid environment. Converts on-premises mailboxes to remote mailboxes and back (Active Directory and Exchange Online), with a backup before every write, a proof after it, a guided console and a transfer package between the Active Directory server and the cloud server.' diff --git a/package/PraRemoteMailbox.psm1 b/package/PraRemoteMailbox.psm1 index 69af962..dba0459 100644 --- a/package/PraRemoteMailbox.psm1 +++ b/package/PraRemoteMailbox.psm1 @@ -18,7 +18,7 @@ .NOTES Author : Nicolas Fabert - Version : 3.0.0 + Version : 3.1.0 History : see CHANGELOG.md #> #Requires -Version 7.5 diff --git a/package/README.md b/package/README.md index aaf6a6d..11a42d2 100644 --- a/package/README.md +++ b/package/README.md @@ -1,6 +1,6 @@ # PRA Remote Mailbox -When the on-premises Exchange servers are lost, gives every user a mailbox in Exchange Online and rolls everything back when Exchange is available again. PowerShell 7.5+ engine, optional WPF window. Author: Nicolas Fabert. Version 3.0.0. +When the on-premises Exchange servers are lost, gives every user a mailbox in Exchange Online and rolls everything back when Exchange is available again. PowerShell 7.5+ engine, optional WPF window. Author: Nicolas Fabert. Version 3.1.0. This folder contains everything needed to run the tool: `Invoke-PraRemoteMailbox.ps1`, its modules and WPF window, the configuration and CSV samples, the report template and the two guides (user guide and reference guide). Tests and build tools stay outside it, in the repository. diff --git a/package/config/PraRemoteMailbox.config.psd1 b/package/config/PraRemoteMailbox.config.psd1 index f7a9689..2c7354b 100644 --- a/package/config/PraRemoteMailbox.config.psd1 +++ b/package/config/PraRemoteMailbox.config.psd1 @@ -2,7 +2,7 @@ # PRA Remote Mailbox - configuration file # -------------------------------------------------------------------------- # Author : Nicolas Fabert -# Version : 3.0.0 +# Version : 3.1.0 # # This file is read by Invoke-PraRemoteMailbox.ps1. It is a PowerShell data # file: text between quotes, $true / $false, numbers, and @( ) for lists. diff --git a/package/docs/PraRemoteMailbox-Guide.html b/package/docs/PraRemoteMailbox-Guide.html index d498acb..b9f34c6 100644 --- a/package/docs/PraRemoteMailbox-Guide.html +++ b/package/docs/PraRemoteMailbox-Guide.html @@ -184,9 +184,9 @@ main { padding: 0; max-width: none; } .section { break-inside: avoid-page; box-shadow: none; } .part { break-before: page; } } -