-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathAudit-ExoAppAccessPolicies.ps1
More file actions
1867 lines (1737 loc) · 99 KB
/
Copy pathAudit-ExoAppAccessPolicies.ps1
File metadata and controls
1867 lines (1737 loc) · 99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#Requires -Modules ExchangeOnlineManagement, Microsoft.Graph.Authentication
<#
.SYNOPSIS
Inventories Exchange Application Access Policies, generates RBAC migration commands,
and audits the tenant for unconstrained Exchange application access.
.DESCRIPTION
Maps Application Access Policies to their Entra apps, target groups/mailboxes, and
granted permissions. Also scans Graph + Exchange Online service principals for apps
holding Exchange application permissions with NO mailbox scoping (Microsoft's model
is insecure-by-default: portal admin consent grants org-wide mailbox access unless a
policy or RBAC scope is added separately).
Outputs an HTML report and a companion .ps1 with the migration commands.
Safety model of the generated commands:
- Steps 1-4 (service principal pointer, management scope, role assignments, test)
are additive: they change nothing that exists.
- Cutover (revoke Entra grants + remove policy) is LIVE code guarded by its own
verification: it runs Test-ServicePrincipalAuthorization first and aborts unless
RBAC is confirmed InScope, and removes the (now-inert) policy only after every
grant revocation succeeded. Remove-ApplicationAccessPolicy is called with
-Confirm:$false because it does NOT reliably prompt in the modern REST-based EXO
module (the docs claim Remove-* cmdlets pause, but these don't) - the verification
is the real gate, not a phantom prompt.
- Actions that would RESTORE tenant-wide access (removing a policy whose target was
deleted) are gated behind an explicit opt-in variable.
- Blocks whose policy target could only be matched by NAME (not object id) are
emitted fully commented and must be verified by a human first.
.PARAMETER UseDeviceCode
Sign in to Microsoft Graph and Exchange Online with device-code flow instead of the
default interactive browser prompt (maps to Connect-MgGraph -UseDeviceCode and
Connect-ExchangeOnline -Device). Useful for headless/remote sessions - but note that
some tenants restrict device-code sign-in via Conditional Access.
.EXAMPLE
.\Audit-ExoAppAccessPolicies.ps1
Signs in to Microsoft Graph and Exchange Online interactively (browser prompt),
audits all Application Access Policies and Exchange app permissions, and saves an
HTML report plus a companion migration .ps1 to the desktop.
.EXAMPLE
.\Audit-ExoAppAccessPolicies.ps1 -UseDeviceCode
Same audit, but both sign-ins use device-code flow (for remote/headless sessions).
.INPUTS
None. This script does not accept pipeline input.
.OUTPUTS
Saved to an 'AppAccessPolicyMigration' folder on the desktop:
AppAccessPolicyMigration_<TenantName>_<yyyyMMdd_HHmmss>.html (report)
AppAccessPolicyMigration_<TenantName>_<yyyyMMdd_HHmmss>.ps1 (migration commands)
.NOTES
Author: Mike Crowley
https://mikecrowley.us
Permissions required:
- Microsoft Graph: Application.Read.All, Directory.Read.All
(the generated cutover blocks additionally need AppRoleAssignment.ReadWrite.All)
- Exchange Online: Organization Management (View-Only recipients minimum for the audit)
Notable caveats surfaced by the report:
- MemberOfGroup scopes cover DIRECT group members only (policies honored nesting)
- DenyAccess policies have no RBAC equivalent and must not be migrated blindly
- IMAP/POP app permissions have no RBAC roles (scoped via Add-MailboxPermission)
- Delegated-only apps never needed a policy (policies constrain app-only access)
- EWS is blocked for non-Microsoft apps Oct 1, 2026 and removed after Apr 2027
.LINK
https://learn.microsoft.com/en-us/exchange/permissions-exo/application-rbac
.LINK
https://learn.microsoft.com/en-us/entra/identity/enterprise-apps/deactivate-app-registration
.LINK
https://learn.microsoft.com/en-us/powershell/module/exchangepowershell/new-applicationaccesspolicy
.LINK
https://learn.microsoft.com/en-us/powershell/exchange/recipientfilter-properties
#>
[CmdletBinding()]
param(
# Device-code sign-in for headless/remote sessions. Interactive browser auth is the
# default because a growing number of tenants restrict device-code flow.
[switch]$UseDeviceCode
)
Disconnect-MgGraph -ErrorAction SilentlyContinue
$graphConnect = @{ NoWelcome = $true; ContextScope = 'Process'; Scopes = @('Application.Read.All', 'Directory.Read.All') }
$exoConnect = @{ ShowBanner = $false }
if ($UseDeviceCode) {
$graphConnect['UseDeviceCode'] = $true
$exoConnect['Device'] = $true
}
# ExchangeOnlineManagement 3.7+ signs in through the Windows broker (WAM) by default,
# and MSAL's broker crashes (NullReferenceException in RuntimeBroker, or "window handle
# must be configured") in windowless hosts like the VS Code integrated console and ISE.
# -DisableWAM is the documented escape hatch, but 3.9.2 has been observed constructing
# the broker anyway. Connect-MgGraph survives these hosts by silently falling back to
# device code; this ladder gives Connect-ExchangeOnline the same resilience:
# interactive (browser preferred off-console) -> -DisableWAM retry -> device code.
$ExoHasDisableWam = (Get-Command Connect-ExchangeOnline).Parameters.ContainsKey('DisableWAM')
if (-not $UseDeviceCode -and $ExoHasDisableWam -and $Host.Name -ne 'ConsoleHost') {
$exoConnect['DisableWAM'] = $true
}
# Two sign-ins are unavoidable here: Graph PowerShell and the Exchange Online module are
# different first-party client apps, so their tokens cannot be shared. Validate Graph
# immediately after its sign-in - a broken Graph session should cost one sign-in, not two
# (Graph credentials acquire tokens lazily, so Connect-MgGraph can "succeed" while the
# first real call fails).
Write-Host 'Sign-in 1 of 2: Microsoft Graph' -ForegroundColor Cyan
if ($UseDeviceCode) {
Write-Host ' (Graph and Exchange Online each issue their own device code - complete this one first)'
}
Connect-MgGraph @graphConnect
try {
$Org = Invoke-MgGraphRequest -Uri "v1.0/organization" -ErrorAction Stop
}
catch {
if ("$_" -match 'authentication failed|AuthenticationFailed|Object reference not set') {
throw "Microsoft Graph sign-in did not complete (device-code prompts can time out or be completed out of order). Rerun the script. Original error: $_"
}
throw "Microsoft Graph query failed. Verify consent for Application.Read.All and Directory.Read.All. Error: $_"
}
$TenantName = ($Org.value[0].displayName -replace '[^\w\-]', '')
$TenantId = "$($Org.value[0].id)"
Write-Host "Sign-in 2 of 2: Exchange Online ($($Org.value[0].displayName))" -ForegroundColor Cyan
$WamCrashPattern = 'RuntimeBroker|Object reference not set|window handle'
$ExoConnected = $false
try {
Connect-ExchangeOnline @exoConnect
$ExoConnected = $true
}
catch {
if ("$_" -notmatch $WamCrashPattern) { throw }
if ($ExoHasDisableWam -and -not $exoConnect.ContainsKey('DisableWAM')) {
Write-Warning 'Windows broker (WAM) sign-in failed in this host - retrying with browser auth (-DisableWAM).'
$exoConnect['DisableWAM'] = $true
try {
Connect-ExchangeOnline @exoConnect
$ExoConnected = $true
}
catch {
if ("$_" -notmatch $WamCrashPattern) { throw }
}
}
}
if (-not $ExoConnected) {
if ($PSVersionTable.PSEdition -eq 'Core') {
Write-Warning ('Exchange Online sign-in keeps hitting the WAM broker crash (it can occur even with -DisableWAM ' +
'in windowless hosts) - falling back to device-code sign-in, as Connect-MgGraph does automatically. ' +
'If Conditional Access blocks device code, run this script from a regular PowerShell 7 console instead.')
$null = $exoConnect.Remove('DisableWAM')
$exoConnect['Device'] = $true
try {
Connect-ExchangeOnline @exoConnect
}
catch {
throw ("The device-code fallback also failed (Conditional Access may block device-code sign-in). " +
"Run this script from a regular PowerShell 7 console, where broker sign-in works. Original error: $_")
}
}
else {
throw ('Connect-ExchangeOnline cannot initialize the Windows broker (WAM) in this host (VS Code integrated ' +
'console / ISE), and the device-code fallback (-Device) requires PowerShell 7. Run the script from a ' +
'regular PowerShell 7 console.')
}
}
#region Helpers
function Invoke-GraphSafe {
# Distinguishes "object not found" (404) from every other failure (auth, throttling,
# network). Only a true 404 may drive orphan/not-found classifications.
param([string]$Uri)
try {
return @{ Ok = $true; Data = (Invoke-MgGraphRequest -Uri $Uri -ErrorAction Stop) }
}
catch {
$msg = $_.Exception.Message
$status = $null
try { $status = [int]$_.Exception.StatusCode } catch { }
if (-not $status) { try { $status = [int]$_.Exception.Response.StatusCode } catch { } }
$notFound = ($status -eq 404) -or
($msg -match 'Request_ResourceNotFound|ResourceNotFound|\bNotFound\b|\bNot Found\b|Status:\s*404|\b404\b')
return @{ Ok = $false; NotFound = [bool]$notFound; Error = $msg }
}
}
function EscSq { param([string]$s) if ($null -eq $s) { '' } else { $s.Replace("'", "''") } }
function EscDq { param([string]$s) if ($null -eq $s) { '' } else { $s.Replace('`', '``').Replace('$', '`$').Replace('"', '`"') } }
function HtmlEnc { param([string]$s) [System.Net.WebUtility]::HtmlEncode("$s") }
function Get-ExoGroupDn {
# Resolve an Entra group to its Exchange DistinguishedName for a MemberOfGroup filter.
# Strategies are independent try/catches so one unsupported filter or cmdlet cannot
# take the others down (Get-Group does not accept every filterable property, and
# M365 groups are only visible to Get-UnifiedGroup / Get-Recipient).
param([string]$GroupId, [string]$GroupEmail)
try {
$r = Get-Recipient -Filter "ExternalDirectoryObjectId -eq '$GroupId'" -ErrorAction Stop | Select-Object -First 1
if ($r.DistinguishedName) { return "$($r.DistinguishedName)" }
}
catch { }
if ($GroupEmail) {
try {
$r = Get-Recipient -Identity $GroupEmail -ErrorAction Stop | Select-Object -First 1
# Guard against a stale email pointing at a different object
if ($r.DistinguishedName -and (-not $r.ExternalDirectoryObjectId -or "$($r.ExternalDirectoryObjectId)" -eq $GroupId)) {
return "$($r.DistinguishedName)"
}
}
catch { }
try {
$g = Get-Group -Identity $GroupEmail -ErrorAction Stop | Select-Object -First 1
if ($g.DistinguishedName -and (-not $g.ExternalDirectoryObjectId -or "$($g.ExternalDirectoryObjectId)" -eq $GroupId)) {
return "$($g.DistinguishedName)"
}
}
catch { }
try {
$u = Get-UnifiedGroup -Identity $GroupEmail -ErrorAction Stop | Select-Object -First 1
if ($u.DistinguishedName -and (-not $u.ExternalDirectoryObjectId -or "$($u.ExternalDirectoryObjectId)" -eq $GroupId)) {
return "$($u.DistinguishedName)"
}
}
catch { }
}
return $null
}
function Find-GroupByScopeName {
# Last-resort fallback, used only when the policy Identity carries no object GUID.
# Requires an UNAMBIGUOUS match; name matches are always flagged for human review.
param([string]$ScopeName)
if (-not $ScopeName) { return @{ Match = $null; Ambiguous = $false } }
$escaped = $ScopeName.Replace("'", "''")
foreach ($prop in @('mailNickname', 'displayName', 'mail')) {
$r = Invoke-GraphSafe "v1.0/groups?`$filter=$prop eq '$escaped'&`$select=id,displayName,mail,mailNickname"
if ($r.Ok -and $r.Data.value.Count -eq 1) { return @{ Match = $r.Data.value[0]; Ambiguous = $false } }
if ($r.Ok -and $r.Data.value.Count -gt 1) { return @{ Match = $null; Ambiguous = $true } }
}
return @{ Match = $null; Ambiguous = $false }
}
function Find-RecipientByScopeName {
param([string]$ScopeName)
if (-not $ScopeName) { return $null }
try {
return Get-Recipient -Identity $ScopeName -ErrorAction Stop |
Select-Object DisplayName, PrimarySmtpAddress, RecipientType, RecipientTypeDetails, ExternalDirectoryObjectId
}
catch { }
return $null
}
#endregion Helpers
#region Permission -> RBAC role maps
# Per https://learn.microsoft.com/en-us/exchange/permissions-exo/application-rbac
# (Supported Application Roles table). RBAC for Applications covers Microsoft Graph
# and EWS only. Note: some Graph permission names carry a .All suffix that the role
# name drops (e.g. MailboxFolder.Read.All -> Application MailboxFolder.Read).
$GraphAppId = '00000003-0000-0000-c000-000000000000'
$ExoAppId = '00000002-0000-0ff1-ce00-000000000000'
$GraphRoleMap = @{
'Mail.Read' = 'Application Mail.Read'
'Mail.ReadBasic' = 'Application Mail.ReadBasic'
'Mail.ReadBasic.All' = 'Application Mail.ReadBasic'
'Mail.ReadWrite' = 'Application Mail.ReadWrite'
'Mail.Send' = 'Application Mail.Send'
'MailboxSettings.Read' = 'Application MailboxSettings.Read'
'MailboxSettings.ReadWrite' = 'Application MailboxSettings.ReadWrite'
'Calendars.Read' = 'Application Calendars.Read'
'Calendars.ReadWrite' = 'Application Calendars.ReadWrite'
'Contacts.Read' = 'Application Contacts.Read'
'Contacts.ReadWrite' = 'Application Contacts.ReadWrite'
'MailboxFolder.Read.All' = 'Application MailboxFolder.Read'
'MailboxFolder.ReadWrite.All' = 'Application MailboxFolder.ReadWrite'
'MailboxItem.Read.All' = 'Application MailboxItem.Read'
'MailboxItem.Export.All' = 'Application MailboxItem.Export'
'MailboxItem.ImportExport.All' = 'Application MailboxItem.ImportExport'
'MailboxConfigItem.Read' = 'Application MailboxConfigItem.Read'
'MailboxConfigItem.ReadWrite' = 'Application MailboxConfigItem.ReadWrite'
'MailTips.ReadBasic.All' = 'Application MailTips.ReadBasic.All'
}
$ExoRoleMap = @{
'full_access_as_app' = 'Application EWS.AccessAsApp'
'SMTP.SendAsApp' = 'Application SMTP.SendAsApp'
}
# EXO app roles with NO RBAC equivalent (RBAC supports Graph + EWS only). IMAP/POP
# app-only access is authorized per-mailbox via Add-MailboxPermission on the Exchange
# service principal - it is not replaced by RBAC and must not be revoked blindly.
$UnmappableExoRoles = @('IMAP.AccessAsApp', 'POP.AccessAsApp')
# Graph Exchange-data app permissions that App Access Policies constrain but that have
# no RBAC role (removing the policy would leave them unscoped).
$UnmappableGraphExchange = @('Calendars.ReadBasic')
$EwsRetirementWarning = '# WARNING: EWS is blocked for non-Microsoft apps starting Oct 1, 2026 (EWSAllowedAppIDs allowlist) and removed after Apr 2027. Plan a Microsoft Graph migration for this app.'
#endregion Permission -> RBAC role maps
# Cache well-known resource service principals for permission-name resolution.
# These MUST load - without them, granted permissions cannot be identified and every
# app would be misreported as having no Exchange permissions.
$ServicePrincipals = @{}
foreach ($id in @($GraphAppId, $ExoAppId)) {
$r = Invoke-GraphSafe "v1.0/servicePrincipals(appId='$id')"
if ($r.Ok) { $ServicePrincipals[$id] = $r.Data }
else { throw "Could not load well-known service principal $id (needed to resolve permission names). Error: $($r.Error)" }
}
$ResourceAppIdCache = @{} # resource SP objectId -> appId (successes only; failures are never cached)
function Resolve-PermissionName {
param([string]$ResourceAppId, [string]$PermissionId)
$sp = $ServicePrincipals[$ResourceAppId]
if (-not $sp) { return $PermissionId }
$match = $sp.appRoles | Where-Object { $_.id -eq $PermissionId }
if ($match) { return $match.value } else { return $PermissionId }
}
# Cache existing management scopes so generated blocks REUSE any scope whose filter
# already covers the target - whatever its name. This honors hand-made or renamed
# scopes instead of minting duplicates alongside them.
$ExistingScopes = @()
try { $ExistingScopes = @(Get-ManagementScope -ErrorAction Stop) } catch { }
# Cache existing Exchange Service Principals. Track failure explicitly - an empty cache
# from a failed call would silently break RBAC detection and the EXO SP column.
$ExchangeServicePrincipals = @{}
$ExoSpCacheOk = $true
try {
Get-ServicePrincipal -ErrorAction Stop | ForEach-Object {
$ExchangeServicePrincipals[$_.AppId] = $_
}
}
catch { $ExoSpCacheOk = $false }
# In tenants where no policy has ever been created, Get-ApplicationAccessPolicy does not
# return an empty result - it throws "object 'OU=...\*' couldn't be found" because the
# policy container itself doesn't exist. Treat that as zero policies.
try {
$Policies = @(Get-ApplicationAccessPolicy -ErrorAction Stop)
}
catch {
if ("$_" -match "couldn't be found|could not be found|ManagementObjectNotFound") {
Write-Host 'No Application Access Policies exist in this tenant.' -ForegroundColor Yellow
$Policies = @()
}
else { throw }
}
$ScopeRegistry = @{} # target object GUID -> management scope name (reuse across apps sharing a target)
$UsedScopeNames = @{} # scope name -> target GUID (uniqueness)
$Report = foreach ($Policy in $Policies) {
$AppId = $Policy.AppId
$AccessRight = "$($Policy.AccessRight)"
$IsDeny = $AccessRight -match 'Deny'
$Issues = @()
$MigrationStatus = 'Ready'
$MigrationBlockers = @()
$PolicyIdSafe = EscSq "$($Policy.Identity)"
# --- Application identity: the SERVICE PRINCIPAL is authoritative. Multi-tenant /
# third-party apps have no application object in this tenant, only a service principal.
$spRes = Invoke-GraphSafe "v1.0/servicePrincipals(appId='$AppId')?`$select=id,appId,displayName,accountEnabled"
$appRes = Invoke-GraphSafe "v1.0/applications(appId='$AppId')?`$select=id,displayName"
$SpLive = $spRes.Ok
$EntraSpObjectId = if ($SpLive) { $spRes.Data.id } else { $null }
$SpAccountEnabled = if ($SpLive) { $spRes.Data.accountEnabled } else { $null }
# Deactivation state (https://learn.microsoft.com/en-us/entra/identity/enterprise-apps/deactivate-app-registration):
# isDisabled lives on the APPLICATION object (global token block; beta endpoint),
# accountEnabled on the SERVICE PRINCIPAL (tenant-scoped sign-in block). Supplementary
# read - failure here must never affect classification.
$AppDeactivated = $null
$DisabledByMicrosoft = $null
if ($appRes.Ok) {
$disRes = Invoke-GraphSafe "beta/applications(appId='$AppId')?`$select=isDisabled,disabledByMicrosoftStatus"
if ($disRes.Ok) {
$AppDeactivated = [bool]$disRes.Data.isDisabled
if ($disRes.Data.disabledByMicrosoftStatus) { $DisabledByMicrosoft = "$($disRes.Data.disabledByMicrosoftStatus)" }
}
}
$AppDisplayName = if ($SpLive) { "$($spRes.Data.displayName)".Trim() }
elseif ($appRes.Ok) { "$($appRes.Data.displayName)".Trim() }
else { $AppId }
$AppObjectId = if ($appRes.Ok) { $appRes.Data.id } else { $null }
if (-not $spRes.Ok -and -not $spRes.NotFound) {
$Issues += 'Lookup Error'
$MigrationStatus = 'Error'
$MigrationBlockers += "Graph service principal lookup failed - rerun or investigate: $($spRes.Error)"
}
elseif (-not $SpLive -and $appRes.NotFound) {
$Issues += 'Orphaned'
$MigrationStatus = 'Delete Only'
$MigrationBlockers += 'App and service principal deleted in Entra ID - policy is inert; remove policy only'
}
elseif (-not $SpLive -and -not $appRes.Ok) {
$Issues += 'Lookup Error'
$MigrationStatus = 'Error'
$MigrationBlockers += "Service principal not found and application lookup failed - rerun before acting: $($appRes.Error)"
}
elseif (-not $SpLive) {
$Issues += 'No Service Principal'
$MigrationStatus = 'Review'
$MigrationBlockers += 'App registration exists but has no service principal in this tenant - the app cannot get app-only tokens, so the policy is dormant'
}
$ExoSpExists = $ExchangeServicePrincipals.ContainsKey($AppId)
# Actual (live) RBAC application role assignments in Exchange for this app. Detects
# half-finished migrations: grants already revoked but the legacy policy left behind.
$LiveRbacRoles = @()
if ($ExoSpExists) {
try {
$LiveRbacRoles = @(Test-ServicePrincipalAuthorization -Identity $AppId -ErrorAction Stop |
ForEach-Object { "$($_.RoleName)" } | Where-Object { $_ } | Select-Object -Unique)
}
catch { }
}
# --- Granted APPLICATION permissions (appRoleAssignments on the service principal) ---
$MigratedPerms = @() # display strings for permissions replaced by RBAC roles
$KeepPerms = @() # display strings for permissions NOT replaced by RBAC - must be kept
$RbacRoles = @()
$RevocationCmds = @() # per-permission grant revocation commands (run inside the verified cutover gate)
$HasImapPop = $false
$HasEws = $false
$HasUnmappableExchange = $false
if ($SpLive) {
$uri = "v1.0/servicePrincipals/$EntraSpObjectId/appRoleAssignments"
while ($uri) {
$aRes = Invoke-GraphSafe $uri
if (-not $aRes.Ok) {
$Issues += 'Permission Lookup Error'
if ($MigrationStatus -ne 'Error') { $MigrationStatus = 'Error' }
$MigrationBlockers += "Could not enumerate app permissions: $($aRes.Error)"
break
}
foreach ($assignment in $aRes.Data.value) {
if (-not $ResourceAppIdCache.ContainsKey($assignment.resourceId)) {
$rRes = Invoke-GraphSafe "v1.0/servicePrincipals/$($assignment.resourceId)?`$select=appId"
if ($rRes.Ok) { $ResourceAppIdCache[$assignment.resourceId] = $rRes.Data.appId }
else {
$Issues += 'Permission Lookup Error'
if ($MigrationStatus -ne 'Error') { $MigrationStatus = 'Error' }
$MigrationBlockers += "Could not resolve a permission's resource ($($assignment.resourceId)): $($rRes.Error)"
continue
}
}
$resourceAppId = $ResourceAppIdCache[$assignment.resourceId]
$permName = Resolve-PermissionName -ResourceAppId $resourceAppId -PermissionId $assignment.appRoleId
$resourceName = switch ($resourceAppId) {
$GraphAppId { 'Graph' }
$ExoAppId { 'EXO' }
default { 'Other' }
}
$display = "$resourceName`:$permName"
$role = $null
if ($resourceAppId -eq $GraphAppId -and $GraphRoleMap.ContainsKey($permName)) { $role = $GraphRoleMap[$permName] }
elseif ($resourceAppId -eq $ExoAppId -and $ExoRoleMap.ContainsKey($permName)) { $role = $ExoRoleMap[$permName] }
if ($role) {
$MigratedPerms += $display
$RbacRoles += $role
if ($role -eq 'Application EWS.AccessAsApp') { $HasEws = $true }
# A 404 on the DELETE means the grant is already gone - the desired end
# state - so reruns of the cutover stay green (idempotent).
$RevocationCmds += " try { Invoke-MgGraphRequest -Method DELETE -Uri 'v1.0/servicePrincipals/$EntraSpObjectId/appRoleAssignments/$($assignment.id)' -ErrorAction Stop; Write-Host 'Revoked $display' } catch { if (`"`$_`" -match 'Request_ResourceNotFound|\b404\b') { Write-Host 'Already revoked: $display' } else { `$revokeFailed = `$true; Write-Warning `"Revocation FAILED ($display): `$_`" } }"
}
else {
$KeepPerms += $display
if ($resourceAppId -eq $ExoAppId -and $UnmappableExoRoles -contains $permName) { $HasImapPop = $true }
elseif ($resourceAppId -eq $ExoAppId) {
# Unmapped EXO role (e.g. legacy Outlook REST Mail.*): assume the policy
# constrains it, so removal guidance must NOT be generated (safe direction).
$HasUnmappableExchange = $true
}
if ($resourceAppId -eq $GraphAppId -and $UnmappableGraphExchange -contains $permName) { $HasUnmappableExchange = $true }
}
}
$uri = $aRes.Data.'@odata.nextLink'
}
}
$RbacRoles = @($RbacRoles | Select-Object -Unique)
# --- Granted DELEGATED permissions (oauth2PermissionGrants). Policies and RBAC only
# constrain app-only access; a policy on a delegated-only app has no effect.
$DelegatedExchangeScopes = @()
$DelegatedLookupOk = $false
if ($SpLive) {
$uri = "v1.0/servicePrincipals/$EntraSpObjectId/oauth2PermissionGrants"
$grants = @()
$grantsOk = $true
while ($uri) {
$gRes = Invoke-GraphSafe $uri
if (-not $gRes.Ok) { $grantsOk = $false; break }
$grants += $gRes.Data.value
$uri = $gRes.Data.'@odata.nextLink'
}
if ($grantsOk) {
$DelegatedLookupOk = $true
$exchangeResourceIds = @($ServicePrincipals.Values | ForEach-Object { $_.id })
foreach ($grant in $grants) {
if ($exchangeResourceIds -contains $grant.resourceId -and $grant.scope) {
foreach ($s in ($grant.scope -split '\s+' | Where-Object { $_ })) {
if ($s -match '^(Mail|Calendars|Contacts|MailboxSettings|MailboxFolder|MailboxItem|MailTips|EWS|IMAP|POP|SMTP)([._-]|$)' -or $s -eq 'full_access_as_user') {
$DelegatedExchangeScopes += $s
}
}
}
}
$DelegatedExchangeScopes = @($DelegatedExchangeScopes | Select-Object -Unique)
}
}
# --- Exchange relevance (runs before the deny check so deny rows keep this context) ---
if ($SpLive -and $RbacRoles.Count -eq 0 -and $MigrationStatus -eq 'Ready') {
# Unmappable-but-policy-constrained permissions MUST win over every branch that
# emits policy-removal guidance - removing the policy would unscope them.
if ($HasUnmappableExchange) {
$Issues += 'Unmappable Permission'
$MigrationStatus = 'Review'
$MigrationBlockers += 'App holds Exchange permissions this policy constrains but that have no RBAC role. Keep the policy, or move the app to a supported permission, before removing anything.'
if ($HasImapPop) {
$MigrationBlockers += 'App also holds IMAP/POP permissions (never policy-constrained; scoped via Add-MailboxPermission on the Exchange service principal).'
}
}
elseif ($HasImapPop) {
$Issues += 'IMAP/POP Only'
$MigrationStatus = 'Review'
$MigrationBlockers += 'Only IMAP/POP app permissions: policies do not constrain IMAP/POP (they cover Graph/REST/EWS) and RBAC has no equivalent. Mailbox reach is controlled via Add-MailboxPermission on the Exchange service principal.'
}
elseif ($LiveRbacRoles.Count -gt 0) {
# Grants revoked + RBAC assignments live = an interrupted cutover. The policy
# constrains nothing now (it only ever constrained Entra grants).
$Issues += 'Finish Migration'
$MigrationStatus = 'Review'
$MigrationBlockers += "Live RBAC role assignments exist ($($LiveRbacRoles -join ', ')) and no matching tenant-wide Entra grants remain. Migration is nearly complete - remove the legacy policy to finish."
}
elseif ($DelegatedLookupOk -and $DelegatedExchangeScopes.Count -gt 0) {
$Issues += 'Delegated Only'
$MigrationStatus = 'Review'
$MigrationBlockers += "App's Exchange permissions are DELEGATED only ($($DelegatedExchangeScopes -join ', ')). Policies constrain app-only access, so this policy has no effect - likely created under a misunderstanding. Delegated access is already limited to what each signed-in user can reach."
}
else {
$Issues += 'No Exchange Permissions'
$MigrationStatus = 'Review'
$note = 'App has no Exchange (Graph Outlook/EWS) application permissions - this policy has no effect today.'
if (-not $DelegatedLookupOk) { $note += ' (Delegated permissions could not be checked in this run.)' }
$MigrationBlockers += $note
}
}
if ($HasImapPop -and $RbacRoles.Count -gt 0) {
$Issues += 'IMAP/POP'
$MigrationBlockers += 'App also holds IMAP/POP permissions, which RBAC cannot replace. Keep them; IMAP/POP mailbox access is controlled via Add-MailboxPermission on the Exchange service principal.'
}
if ($RbacRoles.Count -gt 0 -and $LiveRbacRoles.Count -gt 0 -and $MigrationStatus -in @('Ready', 'Review')) {
# Tenant-wide grants remain AND RBAC assignments exist - likely a partial cutover.
$Issues += 'RBAC Live'
$MigrationBlockers += "Live RBAC assignments already exist ($($LiveRbacRoles -join ', ')) while tenant-wide grants remain. If a previous cutover was interrupted, rerun this block's cutover to finish revoking and remove the policy."
}
# --- Deny check AFTER relevance so those notes are preserved; deny dominates below ---
if ($IsDeny -and $MigrationStatus -in @('Ready', 'Review')) {
$Issues += 'Deny Policy'
$MigrationStatus = 'Review'
$MigrationBlockers = @('DenyAccess policy: RBAC has no deny equivalent. Do NOT create a scope on this group (that would invert the policy). Keep the policy for now or redesign scoping.') + $MigrationBlockers
}
# --- Deactivation / sign-in state. A blocked app gets no new tokens, so the policy has
# no live effect and this row is a retire-vs-migrate decision, not a plain migration.
$SignInBlocked = $false
if ($MigrationStatus -in @('Ready', 'Review')) {
if ($DisabledByMicrosoft) {
$SignInBlocked = $true
$Issues += 'Disabled by Microsoft'
$MigrationStatus = 'Review'
$MigrationBlockers += "App is disabled BY MICROSOFT (disabledByMicrosoftStatus = $DisabledByMicrosoft) - investigate for fraud/compromise before migrating anything."
}
if ($AppDeactivated -eq $true) {
$SignInBlocked = $true
$Issues += 'Deactivated'
$MigrationStatus = 'Review'
$MigrationBlockers += 'App registration is DEACTIVATED (isDisabled = true): no new tokens are issued, so this policy has no live effect. Retiring? Remove the policy and revoke remaining grants. Keeping? Reactivate (App registrations > Deactivated applications) before end-to-end testing.'
}
elseif ($SpLive -and $SpAccountEnabled -eq $false) {
$SignInBlocked = $true
$Issues += 'Sign-in Disabled'
$MigrationStatus = 'Review'
$MigrationBlockers += 'Enterprise application sign-in is DISABLED in this tenant (accountEnabled = false): no new tokens, so this policy has no live effect. Retiring? Remove the policy and revoke remaining grants. Keeping? Re-enable sign-in before end-to-end testing.'
}
}
# --- Resolve the policy target. The trailing GUID of the policy Identity is the
# target's Entra object id - exact, unlike display-name matching.
$ScopeGuid = $null
if ("$($Policy.Identity)" -match ';([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})\s*$') {
$ScopeGuid = $Matches[1]
}
$TargetType = 'Not Found'
$TargetName = $Policy.ScopeName
$TargetEmail = $null
$GroupInfo = $null
$UserInfo = $null
$GroupDN = $null
$TargetEdoid = $null
$TestMailbox = $null
$TestMailboxChecks = 0
$HasNestedGroups = $false
$ResolvedByName = $false
if ($ScopeGuid) {
$g = Invoke-GraphSafe "v1.0/groups/$ScopeGuid`?`$select=id,displayName,mail,mailNickname"
if ($g.Ok) { $GroupInfo = $g.Data }
elseif ($g.NotFound) {
$u = Invoke-GraphSafe "v1.0/users/$ScopeGuid`?`$select=id,displayName,mail,userPrincipalName"
if ($u.Ok) { $UserInfo = $u.Data }
elseif ($u.NotFound) {
# Both 404: the target object was deleted. Never fall back to name matching
# here - any name match would necessarily be a DIFFERENT object.
if ($MigrationStatus -in @('Ready', 'Review')) {
$Issues += 'Target Missing'
$MigrationStatus = 'Blocked'
$MigrationBlockers += 'Policy target object was DELETED in Entra ID. For a RestrictAccess policy that means the app is currently denied on ALL mailboxes.'
}
}
else {
$Issues += 'Lookup Error'
if ($MigrationStatus -ne 'Error') { $MigrationStatus = 'Error' }
$MigrationBlockers += "Target user lookup failed - rerun before acting: $($u.Error)"
}
}
else {
$Issues += 'Lookup Error'
if ($MigrationStatus -ne 'Error') { $MigrationStatus = 'Error' }
$MigrationBlockers += "Target group lookup failed - rerun before acting: $($g.Error)"
}
}
else {
$nameResult = Find-GroupByScopeName -ScopeName $Policy.ScopeName
if ($nameResult.Ambiguous -and $MigrationStatus -in @('Ready', 'Review')) {
$Issues += 'Ambiguous Name'
$MigrationStatus = 'Blocked'
$MigrationBlockers += "Multiple groups match the policy scope name '$($Policy.ScopeName)' - cannot determine the intended target"
}
elseif ($nameResult.Match) {
$GroupInfo = $nameResult.Match
$ResolvedByName = $true
}
}
if ($GroupInfo) {
$TargetType = 'Group'
$TargetName = $GroupInfo.displayName
$TargetEmail = $GroupInfo.mail
$GroupDN = Get-ExoGroupDn -GroupId $GroupInfo.id -GroupEmail $TargetEmail
if (-not $GroupDN -and $MigrationStatus -in @('Ready', 'Review')) {
$Issues += 'Group Not In EXO'
$MigrationStatus = 'Blocked'
$MigrationBlockers += 'Group is not an Exchange recipient - MemberOfGroup scopes only work with Exchange-recognized groups (M365 group, mail-enabled security group, or DL)'
}
# Nested groups: MemberOfGroup scopes match DIRECT members only, while App Access
# Policies honored nested membership (per PolicyScopeGroupId documentation).
if ($GroupDN) {
$membersOk = $true
$memberUri = "v1.0/groups/$($GroupInfo.id)/members?`$select=id&`$top=999"
while ($memberUri) {
$m = Invoke-GraphSafe $memberUri
if (-not $m.Ok) { $membersOk = $false; break }
if (-not $HasNestedGroups) {
$HasNestedGroups = [bool]($m.Data.value | Where-Object { $_.'@odata.type' -eq '#microsoft.graph.group' })
}
if (-not $TestMailbox) {
foreach ($memberUser in ($m.Data.value | Where-Object { $_.'@odata.type' -eq '#microsoft.graph.user' })) {
if ($TestMailboxChecks -ge 5) { break }
$TestMailboxChecks++
$fu = Invoke-GraphSafe "v1.0/users/$($memberUser.id)?`$select=mail,userPrincipalName"
if (-not $fu.Ok) { continue }
$candidate = if ($fu.Data.mail) { $fu.Data.mail } else { $fu.Data.userPrincipalName }
if (-not $candidate) { continue }
# Must be a real Exchange recipient, or the cutover InScope test can never pass
try {
if (Get-Recipient -Identity $candidate -ErrorAction Stop) { $TestMailbox = "$candidate"; break }
}
catch { }
}
}
if ($HasNestedGroups -and $TestMailbox) { break }
$memberUri = $m.Data.'@odata.nextLink'
}
if ($HasNestedGroups -and $MigrationStatus -eq 'Ready') {
$Issues += 'Nested Groups'
$MigrationStatus = 'Review'
$MigrationBlockers += 'Group contains nested groups: MemberOfGroup scopes cover DIRECT members only. Flatten membership (add nested members directly) before cutover.'
}
if (-not $membersOk -and $MigrationStatus -eq 'Ready') {
$Issues += 'Members Unverified'
$MigrationStatus = 'Review'
$MigrationBlockers += 'Could not enumerate group members to check for nested groups - verify manually before cutover'
}
if ($ResolvedByName -and $MigrationStatus -in @('Ready', 'Review')) {
$Issues += 'Resolved By Name'
$MigrationStatus = 'Review'
$MigrationBlockers += 'Target was matched by NAME only (policy identity carried no object id). Verify this is the intended group; the generated commands are commented out until then.'
}
}
}
elseif ($UserInfo) {
# Require an actual Exchange recipient behind the Entra user, otherwise the
# generated scope filter would match nothing.
$Recipient = $null
try {
$Recipient = Get-Recipient -Filter "ExternalDirectoryObjectId -eq '$($UserInfo.id)'" -ErrorAction Stop | Select-Object -First 1
}
catch { }
if (-not $Recipient -and $UserInfo.userPrincipalName) {
try { $Recipient = Get-Recipient -Identity $UserInfo.userPrincipalName -ErrorAction Stop | Select-Object -First 1 } catch { }
}
if ($Recipient) {
$TargetType = "$($Recipient.RecipientTypeDetails)"
$TargetName = $UserInfo.displayName
$TargetEmail = if ($Recipient.PrimarySmtpAddress) { "$($Recipient.PrimarySmtpAddress)" } else { $UserInfo.mail }
$TargetEdoid = $UserInfo.id
$TestMailbox = $TargetEmail
$Issues += 'Single Mailbox'
}
elseif ($MigrationStatus -in @('Ready', 'Review')) {
$TargetType = 'User'
$TargetName = $UserInfo.displayName
$TargetEmail = $UserInfo.mail
$Issues += 'No EXO Recipient'
$MigrationStatus = 'Blocked'
$MigrationBlockers += 'Entra user exists but has no Exchange recipient - a RestrictAccess policy pointing at it denies the app on ALL mailboxes'
}
}
elseif ($MigrationStatus -in @('Ready', 'Review')) {
$Recipient = Find-RecipientByScopeName -ScopeName $Policy.ScopeName
if ($Recipient -and $Recipient.ExternalDirectoryObjectId) {
$TargetType = "$($Recipient.RecipientTypeDetails)"
$TargetName = $Recipient.DisplayName
$TargetEmail = "$($Recipient.PrimarySmtpAddress)"
$TargetEdoid = "$($Recipient.ExternalDirectoryObjectId)"
$TestMailbox = $TargetEmail
$Issues += 'Single Mailbox'
if (-not $ScopeGuid) {
$ResolvedByName = $true
$Issues += 'Resolved By Name'
$MigrationStatus = 'Review'
$MigrationBlockers += 'Target was matched by NAME only. Verify this is the intended recipient; the generated commands are commented out until then.'
}
}
elseif (-not ($Issues -contains 'Target Missing') -and -not ($Issues -contains 'Ambiguous Name')) {
$Issues += 'Target Missing'
$MigrationStatus = 'Blocked'
$MigrationBlockers += 'Target group/mailbox not found'
}
}
# Entra portal deep links
$TargetGuidForLink = if ($GroupInfo) { $GroupInfo.id } elseif ($UserInfo) { $UserInfo.id } else { $TargetEdoid }
$Links = [ordered]@{}
if ($AppObjectId) { $Links['App registration'] = "https://entra.microsoft.com/#view/Microsoft_AAD_RegisteredApps/ApplicationMenuBlade/~/Overview/appId/$AppId" }
if ($EntraSpObjectId) { $Links['Enterprise app'] = "https://entra.microsoft.com/#view/Microsoft_AAD_IAM/ManagedAppMenuBlade/~/Overview/objectId/$EntraSpObjectId/appId/$AppId" }
$TargetLink = if ($GroupInfo) { "https://entra.microsoft.com/#view/Microsoft_AAD_IAM/GroupDetailsMenuBlade/~/Overview/groupId/$($GroupInfo.id)" }
elseif ($TargetGuidForLink) { "https://entra.microsoft.com/#view/Microsoft_AAD_IAM/UserDetailsMenuBlade/~/Profile/userId/$TargetGuidForLink" }
else { $null }
# --- Build migration commands / call to action. EVERY row gets one. ---
$MigrationCommands = @()
$CanGenerate = (-not $IsDeny) -and $SpLive -and $EntraSpObjectId -and $RbacRoles.Count -gt 0 -and
($GroupDN -or $TargetEdoid) -and $MigrationStatus -in @('Ready', 'Review')
if ($CanGenerate) {
$targetKey = if ($GroupInfo) { $GroupInfo.id } else { $TargetEdoid }
if ($GroupDN) {
$filter = "MemberOfGroup -eq '$(EscDq (EscSq $GroupDN))'"
$filterKey = $GroupDN
}
else {
$filter = "ExternalDirectoryObjectId -eq '$targetKey'"
$filterKey = $targetKey
}
# Scope name resolution, in priority order:
# 1. a scope already chosen for this target earlier in this run
# 2. an EXISTING tenant scope whose filter covers this target (any name -
# honors renamed / hand-made scopes; naming convention: AppRBAC-<Agency>-<Purpose>)
# 3. mint a new name in the convention: AppRBAC-<Target>, hyphen-separated
if ($ScopeRegistry.ContainsKey($targetKey)) {
$scopeName = $ScopeRegistry[$targetKey]
}
else {
$existingScope = $ExistingScopes |
Where-Object { $_.RecipientFilter -like "*$filterKey*" -or $_.RecipientFilter -like "*$(EscSq $filterKey)*" } |
Select-Object -First 1
if ($existingScope) {
$scopeName = "$($existingScope.Name)"
}
else {
$targetSafe = if ($GroupInfo -and $GroupInfo.mailNickname) { $GroupInfo.mailNickname }
elseif ($GroupInfo) { $GroupInfo.displayName }
elseif ($TargetEmail) { ($TargetEmail -split '@')[0] }
else { $TargetName }
$targetSafe = ("$targetSafe".Trim() -replace '[^A-Za-z0-9]+', '-').Trim('-')
$scopeName = "AppRBAC-$targetSafe"
if ($scopeName.Length -gt 64) { $scopeName = $scopeName.Substring(0, 64).Trim('-') } # scope name limit
$n = 2
while ($UsedScopeNames.ContainsKey($scopeName) -and $UsedScopeNames[$scopeName] -ne $targetKey) {
$scopeName = "AppRBAC-$targetSafe-$n"; $n++
}
}
$UsedScopeNames[$scopeName] = $targetKey
$ScopeRegistry[$targetKey] = $scopeName
}
$MigrationCommands += "# ==== $AppDisplayName ($AppId) -> $TargetName [$AccessRight] ===="
$MigrationCommands += "# Steps 1-4 are additive and do not change existing access."
if ($SignInBlocked) {
$MigrationCommands += "# NOTE: this app cannot currently obtain tokens (deactivated / sign-in disabled)."
$MigrationCommands += "# Steps 1-3 can be staged and the Step 4 test cmdlet still evaluates, but the app"
$MigrationCommands += "# itself cannot be end-to-end tested until re-enabled. If it is being RETIRED, skip"
$MigrationCommands += "# migration: revoke its grants and remove the policy instead."
}
$MigrationCommands += ""
$MigrationCommands += "# Step 1: Exchange service principal pointer (idempotent)"
if ($ExoSpExists) {
$MigrationCommands += "# Already exists in Exchange Online - nothing to do."
}
else {
$MigrationCommands += "if (-not (Get-ServicePrincipal -Identity '$AppId' -ErrorAction SilentlyContinue)) {"
$MigrationCommands += " New-ServicePrincipal -AppId '$AppId' -ObjectId '$EntraSpObjectId' -DisplayName '$(EscSq $AppDisplayName)'"
$MigrationCommands += "}"
}
$MigrationCommands += ""
$MigrationCommands += "# Step 2: Management scope (idempotent; warns if the name is taken by a different filter)"
if ($GroupDN) {
$MigrationCommands += "# NOTE: MemberOfGroup covers DIRECT members only - nested group members are out of scope."
}
else {
$MigrationCommands += "# Single-mailbox scope. To cover more mailboxes later, create a mail-enabled security"
$MigrationCommands += "# group instead and use: `"MemberOfGroup -eq '<group DN>'`""
}
$MigrationCommands += "`$scope = `$null"
$MigrationCommands += "`$scopeConflict = `$false"
$MigrationCommands += "`$scope = Get-ManagementScope -Identity '$scopeName' -ErrorAction SilentlyContinue"
$MigrationCommands += "if (-not `$scope) {"
$MigrationCommands += " New-ManagementScope -Name '$scopeName' -RecipientRestrictionFilter `"$filter`""
$MigrationCommands += "} elseif (`$scope.RecipientFilter -notlike '*$(EscSq $filterKey)*') {"
$MigrationCommands += " `$scopeConflict = `$true"
$MigrationCommands += " Write-Warning `"Scope '$scopeName' already exists with a DIFFERENT filter: `$(`$scope.RecipientFilter) - role assignments skipped; resolve the conflict first.`""
$MigrationCommands += "}"
$MigrationCommands += ""
$MigrationCommands += "# Step 3: RBAC role assignments (idempotent - skips roles already assigned; skipped"
$MigrationCommands += "# entirely on a scope-name conflict)"
$MigrationCommands += "if (-not `$scopeConflict) {"
$MigrationCommands += " `$liveRoles = @(Test-ServicePrincipalAuthorization -Identity '$AppId' -ErrorAction SilentlyContinue | ForEach-Object { `$_.RoleName })"
foreach ($role in $RbacRoles) {
$MigrationCommands += " if (`$liveRoles -notcontains '$role') { New-ManagementRoleAssignment -App '$AppId' -Role '$role' -CustomResourceScope '$scopeName' }"
}
$MigrationCommands += "}"
if ($HasEws) { $MigrationCommands += $EwsRetirementWarning }
$MigrationCommands += ""
$MigrationCommands += "# Step 4: VERIFY - expect InScope = True for an in-scope mailbox"
if ($TestMailbox) {
$MigrationCommands += "Test-ServicePrincipalAuthorization -Identity '$AppId' -Resource '$(EscSq $TestMailbox)' | Format-Table"
}
else {
$MigrationCommands += "# No member mailbox found automatically - substitute one:"
$MigrationCommands += "# Test-ServicePrincipalAuthorization -Identity '$AppId' -Resource '<member mailbox>' | Format-Table"
}
$MigrationCommands += "# Also confirm the application itself still works before continuing."
$MigrationCommands += ""
$NeedsFlattenGate = ($Issues -contains 'Nested Groups') -or ($Issues -contains 'Members Unverified')
$rolesList = ($RbacRoles | ForEach-Object { "'$(EscSq $_)'" }) -join ', '
$MigrationCommands += "# ---- Step 5-6: CUTOVER. Verifies EVERY migrated role is live and InScope, revokes the"
$MigrationCommands += "# tenant-wide grants (each one checked), then removes the now-inert legacy policy."
$MigrationCommands += "# Entra + RBAC grants are a union - scoping only takes effect after the tenant-wide grant"
$MigrationCommands += "# is revoked. Nothing here runs unverified: the policy is removed ONLY after RBAC is"
$MigrationCommands += "# confirmed InScope AND every revocation succeeded. Remove is explicit (-Confirm:`$false)"
$MigrationCommands += "# because Remove-ApplicationAccessPolicy does NOT reliably prompt in the modern EXO module."
$MigrationCommands += "`$expectedRoles = @($rolesList)"
if ($TestMailbox) {
$MigrationCommands += "`$cutoverTestMailbox = '$(EscSq $TestMailbox)' # in-scope member found by the audit; substitute if needed"
}
else {
$MigrationCommands += "`$cutoverTestMailbox = '<member mailbox>' # REQUIRED: set to a mailbox inside the new scope"
}
$MigrationCommands += "`$auth = if (`$cutoverTestMailbox -notlike '<*') { @(Test-ServicePrincipalAuthorization -Identity '$AppId' -Resource `$cutoverTestMailbox -ErrorAction SilentlyContinue) } else { @() }"
$MigrationCommands += "`$missingRoles = @(`$expectedRoles | Where-Object { `$role = `$_; -not (`$auth | Where-Object { `$_.RoleName -eq `$role -and `$_.InScope }) })"
if ($NeedsFlattenGate) {
$MigrationCommands += "`$nestedGroupsHandled = `$false # set to `$true after adding nested-group members DIRECTLY to the group"
}
$MigrationCommands += "if (`$missingRoles.Count -gt 0) {"
$MigrationCommands += " Write-Warning `"$(EscDq $AppDisplayName): roles not verified InScope for `$cutoverTestMailbox (missing: `$(`$missingRoles -join ', ')) - cutover skipped. Run steps 1-4; if they succeeded, try a different in-scope mailbox.`""
$MigrationCommands += "} elseif (@((Get-MgContext).Scopes) -notcontains 'AppRoleAssignment.ReadWrite.All') {"
$MigrationCommands += " Write-Warning 'Graph session lacks AppRoleAssignment.ReadWrite.All - run: Connect-MgGraph -Scopes AppRoleAssignment.ReadWrite.All'"
if ($NeedsFlattenGate) {
$MigrationCommands += "} elseif (-not `$nestedGroupsHandled) {"
$MigrationCommands += " Write-Warning `"$(EscDq $AppDisplayName): the scope covers DIRECT members only - flatten nested groups, then set ```$nestedGroupsHandled = ```$true and rerun.`""
}
$MigrationCommands += "} else {"
$MigrationCommands += " `$revokeFailed = `$false"
if ($KeepPerms.Count -gt 0) {
$MigrationCommands += " # KEEP (NOT replaced by RBAC - do not revoke): $($KeepPerms -join ', ')"
}
$MigrationCommands += $RevocationCmds
$MigrationCommands += " if (`$revokeFailed) {"
$MigrationCommands += " Write-Warning 'One or more revocations FAILED - the legacy policy was NOT removed. Fix the errors above and rerun this cutover block.'"
$MigrationCommands += " } elseif (@(Get-ApplicationAccessPolicy | Where-Object { `$_.Identity -eq '$PolicyIdSafe' }).Count -eq 0) {"
$MigrationCommands += " Write-Host '$(EscSq $AppDisplayName): legacy policy already removed - migration complete.'"
$MigrationCommands += " } else {"
$MigrationCommands += " Write-Host 'Tenant-wide grants revoked. Exchange caches app permissions 30 min - 2 h; re-test the app.'"
$MigrationCommands += " # The policy is now inert (it only constrained the Entra grants, which are gone)."
$MigrationCommands += " Remove-ApplicationAccessPolicy -Identity '$PolicyIdSafe' -Confirm:`$false"
$MigrationCommands += " if (@(Get-ApplicationAccessPolicy | Where-Object { `$_.Identity -eq '$PolicyIdSafe' }).Count -eq 0) {"
$MigrationCommands += " Write-Host '$(EscSq $AppDisplayName): legacy policy removed - migration complete.'"
$MigrationCommands += " } else {"
$MigrationCommands += " Write-Warning '$(EscSq $AppDisplayName): legacy policy still present (removal failed) - rerun this cutover block to finish.'"
$MigrationCommands += " }"
$MigrationCommands += " }"
$MigrationCommands += "}"
$MigrationCommands += "# Hygiene afterwards: App registrations > API permissions - delete the revoked rows"
$MigrationCommands += "# ('not granted' leftovers). Removing entries there does NOT revoke access by itself."
if (-not $AppObjectId) {
$MigrationCommands += "# (App is registered in another tenant - only the grant revocation applies here.)"
}
if ($ResolvedByName) {
$MigrationCommands = @(
"# !! TARGET MATCHED BY NAME ONLY - VERIFY BEFORE RUNNING !!"
"# The policy identity carried no object id, so '$TargetName' was found by name match."
"# Confirm it is the intended target, then uncomment this block."
) + ($MigrationCommands | ForEach-Object { if ($_ -and $_ -notmatch '^\s*#') { "# $_" } else { $_ } })
}
}
elseif ($MigrationStatus -eq 'Delete Only') {
$MigrationCommands += "# App and service principal are gone from Entra ID - the policy is inert."
$MigrationCommands += "# Cross-check your app inventory, then remove it:"
$MigrationCommands += "Remove-ApplicationAccessPolicy -Identity '$PolicyIdSafe' -Confirm:`$false"
}
elseif ($IsDeny) {
$MigrationCommands += "# DenyAccess policy - do NOT migrate with restrict-style commands (a scope on this"
$MigrationCommands += "# group would GRANT access to exactly the mailboxes currently denied)."
$MigrationCommands += "# Review what is denied and who is in the target (links in this row), then either keep"
$MigrationCommands += "# this policy or redesign scoping so the allow-side groups exclude these recipients."
$MigrationCommands += "Get-ApplicationAccessPolicy -Identity '$PolicyIdSafe' | Format-List"
}
elseif ($Issues -contains 'Finish Migration') {
$MigrationCommands += "# FINISH MIGRATION: RBAC is live ($($LiveRbacRoles -join ', ')) and the matching tenant-wide"
$MigrationCommands += "# Entra grants are gone, so this legacy policy constrains nothing. Verify, then remove it:"
if ($TestMailbox) {
$MigrationCommands += "Test-ServicePrincipalAuthorization -Identity '$AppId' -Resource '$(EscSq $TestMailbox)' | Format-Table # expect InScope = True"
}
else {
$MigrationCommands += "Test-ServicePrincipalAuthorization -Identity '$AppId' | Format-Table # spot-check InScope with an in-scope mailbox via -Resource"
}
$MigrationCommands += "# Confirm the application still works, then remove the now-inert policy:"
$MigrationCommands += "Remove-ApplicationAccessPolicy -Identity '$PolicyIdSafe' -Confirm:`$false"
$MigrationCommands += "if (@(Get-ApplicationAccessPolicy | Where-Object { `$_.Identity -eq '$PolicyIdSafe' }).Count -eq 0) {"
$MigrationCommands += " Write-Host '$(EscSq $AppDisplayName): legacy policy removed - migration complete.'"
$MigrationCommands += "} else {"
$MigrationCommands += " Write-Warning '$(EscSq $AppDisplayName): legacy policy still present (removal failed).'"
$MigrationCommands += "}"
}
elseif ($Issues -contains 'Delegated Only') {
$MigrationCommands += "# Exchange permissions are DELEGATED only ($($DelegatedExchangeScopes -join ', '))."
$MigrationCommands += "# Policies constrain app-only access, so this policy does nothing today. Removing it"
$MigrationCommands += "# changes no behavior:"
$MigrationCommands += "Remove-ApplicationAccessPolicy -Identity '$PolicyIdSafe' -Confirm:`$false"
}
elseif ($Issues -contains 'No Exchange Permissions') {
$MigrationCommands += "# No Exchange application permissions -> this policy has no effect today."
if ($KeepPerms.Count -gt 0) { $MigrationCommands += "# KEEP (not Exchange-related): $($KeepPerms -join ', ')" }
$MigrationCommands += "# Removing the policy changes no behavior. If the app is granted Exchange permissions"
$MigrationCommands += "# later, scope it with RBAC at that time."
$MigrationCommands += "Remove-ApplicationAccessPolicy -Identity '$PolicyIdSafe' -Confirm:`$false"
}
elseif ($Issues -contains 'Unmappable Permission') {
$MigrationCommands += "# This policy constrains permissions that have no RBAC role: $($KeepPerms -join ', ')"