-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMapAz.psm1
More file actions
851 lines (721 loc) · 30 KB
/
MapAz.psm1
File metadata and controls
851 lines (721 loc) · 30 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
Add-Type -TypeDefinition @"
public class EnrichedOp {
public string ResourceId;
public string ResourceName;
public string ResourceType;
public string Operation;
public string OperationType;
public string ProviderNamespace;
public string UserId;
public string UserName;
public string Plane;
public EnrichedOp(string rid, string rname, string rtype,string op, string optype, string pns,string uid, string uname, string pl) {
ResourceId = rid;
ResourceName = rname;
ResourceType = rtype;
Operation = op;
OperationType= optype;
ProviderNamespace= pns;
UserId = uid;
UserName = uname;
Plane = pl;
}
}
"@ -Language CSharp
function Clear-MapAzScriptCache
{
[CmdletBinding()]
param()
begin
{
$global:allRoleDefinitions = @()
$global:allRoleAssignments = @()
$global:allResources = @()
$global:allUsers = @()
$global:allOperations = @()
$global:allResourceactionProviders = @()
$global:OpsByRoleAssignment = @{}
$global:allGroupMembers = @()
}
}
function Get-MapAzResourceProvider {
[CmdletBinding()]
param(
[string]
$NameSpace)
begin{
if (-not (Get-Variable -Name allResourceactionProviders -Scope Global -ErrorAction SilentlyContinue) -or -not $global:allResourceactionProviders){
Write-Verbose 'Fetching all resource actionProviders...'
$global:allResourceactionProviders += Get-AzResourceProvider -ErrorAction SilentlyContinue
}
}
process {
if ($NameSpace) {$global:allResourceactionProviders | Where-Object { $_.ProviderNamespace -like "$NameSpace*" }}
else {$global:allResourceactionProviders}
}
}
function Test-MapAzUserGroupMembership {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string] $GroupId,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string] $UserId
)
begin {
if (-not (Get-Variable -Name allGroupMembers -Scope Global -ErrorAction SilentlyContinue) `
-or -not $global:allGroupMembers)
{
Write-Verbose 'Caching all group members...'
$global:allGroupMembers = @()
# Fetch every AAD group once
$allGroups = Get-AzADGroup
foreach ($grp in $allGroups) {
Write-Verbose " • Loading members of '$($grp.DisplayName)' ($($grp.Id))"
$members = Get-AzADGroupMember -GroupObjectId $grp.Id -ErrorAction SilentlyContinue
$global:allGroupMembers += [PSCustomObject]@{
GroupId = $grp.Id
Members = $members
}
}
}
}
process {
function Test-Member {
param(
[string] $CurrentGroupId,
[string] $SearchUserId,
[string[]] $Visited
)
if ($Visited -contains $CurrentGroupId) { return $false }
$Visited += $CurrentGroupId
# Get cached entry
$entry = $global:allGroupMembers |
Where-Object { $_.GroupId -eq $CurrentGroupId }
if (-not $entry) { return $false }
$members = $entry.Members
# Direct user?
if ($members.Id -contains $SearchUserId) {
return $true
}
# Recurse into nested groups
$subGroups = $members | Where-Object { $_.ObjectType -eq 'Group' }
foreach ($sg in $subGroups) {
if (Test-Member -CurrentGroupId $sg.Id `
-SearchUserId $SearchUserId `
-Visited $Visited) {
return $true
}
}
return $false
}
# Kickoff with empty visited list
$isMember = Test-Member -CurrentGroupId $GroupId `
-SearchUserId $UserId `
-Visited @()
# Output boolean
$isMember
}
}
function Get-MapAzProviderOperations {
[CmdletBinding()]
param(
[ValidateNotNullOrEmpty()]
[string]
$action,
[bool]
$IsDataAction)
begin{
if (-not (Get-Variable -Name allOperations -Scope Global -ErrorAction SilentlyContinue) -or -not $global:allOperations)
{
Write-Verbose 'Fetching all operations...'
$global:allOperations += Get-AzProviderOperation -ErrorAction SilentlyContinue
}
}
process {
if ($action) {
$global:allOperations.Where({
$_.Operation -like $action -and $_.IsDataAction -eq $IsDataAction
})
}
else {$global:allOperations}
}
}
function Get-MapAzUsers {
[CmdletBinding()]
param(
[ValidateNotNullOrEmpty()]
[string]
$userId,
[ValidateNotNullOrEmpty()]
[string]
$userPrincipalName)
begin{
if (-not (Get-Variable -Name allUsers -Scope Global -ErrorAction SilentlyContinue) -or -not $global:allUsers)
{
Write-Host 'Fetching all users...'
$global:allUsers = @()
$global:allUsers += Get-AzAdUser
Write-Host 'Fetching all service principals...'
$global:allUsers += Get-AzADServicePrincipal
Write-Host 'Fetching all groups...'
$global:allUsers += Get-AzADGroup
Write-Host 'Fetching all managed identities...'
$subs = Get-AzSubscription
foreach ($sub in $subs) {
Write-Verbose "Switching to subscription $($sub.Name) ($($sub.Id))"
Set-AzContext -Subscription $sub.Id | Out-Null
$global:allUsers += Get-AzUserAssignedIdentity -ErrorAction SilentlyContinue
}
}
}
end {
if ($UserId -or $userPrincipalName) {
$matches = $global:allUsers | Where-Object { ($_.Id -eq $UserId) -or ($_.UserPrincipalName -eq $userPrincipalName) }
if (-not $matches) { Write-Warning "No user found with Id $UserId or UPN $userPrincipalName."}
return $matches
}
else {
$global:allUsers
}
}
}
function Get-MapAzRoleDefinitions {
[CmdletBinding()]
param(
[ValidateNotNullOrEmpty()]
[string]
$roleId)
begin{
if (-not (Get-Variable -Name allRoleDefinitions -Scope Global -ErrorAction SilentlyContinue) -or -not $global:allRoleDefinitions)
{
Write-Verbose 'Fetching all role definitions...'
$subs = Get-AzSubscription
$global:allRoleDefinitions = @()
foreach ($sub in $subs) {
Write-Verbose "Switching to subscription $($sub.Name) ($($sub.Id))"
Set-AzContext -Subscription $sub.Id | Out-Null
$global:allRoleDefinitions += Get-AzRoleDefinition -ErrorAction SilentlyContinue
}
}
}
process {
$global:allRoleDefinitions | Where-Object { $_.Id -eq $roleId }
}
}
function Get-MapAzRoleAssignments {
[CmdletBinding()]
param(
[ValidateNotNullOrEmpty()]
[string] $UserId,
[ValidateNotNullOrEmpty()]
[string] $UserName
)
begin {
# If they passed -UserName, resolve it to an ObjectId
if ($UserName) {
Write-Verbose "Resolving user principal name '$UserName' to object ID..."
$u = Get-MapAzUsers -userPrincipalName $UserName
$UserId = $u.Id
}
else
{
$u = Get-MapAzUsers -userId $UserId
$UserName = $u.UserPrincipalName
}
if (-not (Get-Variable -Name allRoleAssignments -Scope Global -ErrorAction SilentlyContinue) `
-or -not $global:allRoleAssignments)
{
Write-Verbose "Fetching all role assignments for $UserName ($UserId)"
$global:allRoleAssignments = @()
$subs = Get-AzSubscription
foreach ($sub in $subs) {
Write-Verbose "Switching to subscription $($sub.Name) ($($sub.Id))"
Set-AzContext -Subscription $sub.Id | Out-Null
$ra = Get-AzRoleAssignment -ErrorAction SilentlyContinue
if (-not ($global:allRoleAssignments).Where({$_.RoleAssignmentId -eq $ra.RoleAssignmentId})){
$global:allRoleAssignments += $ra
}
}
}
}
process {
if (-not $UserId -and -not $UserName) {
$global:allRoleAssignments
}
else {
$global:allRoleAssignments |
Where-Object {
($_.ObjectId -eq $UserId) -or
($_.ObjectType -eq 'Group' -and
(Test-MapAzUserGroupMembership -GroupId $_.ObjectId -UserId $UserId))
}
}
}
}
function Get-MapAzProviderErrorInfo {
[CmdletBinding()]
param(
[Parameter(Mandatory, ValueFromPipeline)]
[string[]]$Message
)
process {
foreach ($msg in $Message) {
# extract the comma-separated api-versions inside single quotes
$apiMatch = [regex]::Match($msg, "supported api-versions are '([^']+)'")
$apiVersions = if ($apiMatch.Success) {
$apiMatch.Groups[1].Value `
-split ',' `
| ForEach-Object { $_.Trim() } `
| Where-Object { $_ -ne '' }
} else { @() }
# extract the comma-separated locations inside single quotes
$locMatch = [regex]::Match($msg, "supported locations are '([^']+)'")
$locations = if ($locMatch.Success) {
$locMatch.Groups[1].Value `
-split ',' `
| ForEach-Object { $_.Trim() } `
| Where-Object { $_ -ne '' }
} else { @() }
# output a structured object
[PSCustomObject]@{
Message = $msg
ApiVersions = $apiVersions
Locations = $locations
}
}
}
}
function Get-MapAzResourceViaRESTAPINative {
[CmdletBinding()]
param(
[Parameter(Mandatory, Position=0)]
[string]$Uri,
[Parameter(Mandatory, Position=1)]
[string]$Token
)
begin {
# Default API version
$script:apiver = "2021-04-01"
}
process {
$uriAndApi = $Uri + "?api-version=" + $script:apiver
Write-Verbose "Trying to GET resource at URI: $uriAndApi"
$httpResp = Invoke-WebRequest -Method GET -Uri $uriAndApi -Headers @{ Authorization = "Bearer $Token" } -SkipHttpErrorCheck
if ($httpResp.StatusCode -ne 200) {
$statuscode = $httpResp.StatusCode
$httpJson = $httpResp.Content | ConvertFrom-Json
$errorCode = $httpJson.error.code
Write-Debug "Got error $statuscode : $errorCode for URI: $uri"
if ($errorCode -like "NoRegisteredProviderFound") {
$errMsg = $httpJson.error.Message | Get-MapAzProviderErrorInfo
if ($errMsg.ApiVersions) {
$script:apiver = $errMsg.ApiVersions[-1]
$uriAndApi = $Uri + "?api-version=" + $script:apiver
Write-Debug "Changing API versoin, trying URI: $uriAndApi"
$httpResp = Invoke-WebRequest -Method GET -Uri $uriAndApi -Headers @{ Authorization = "Bearer $Token" } -SkipHttpErrorCheck
}
}
}
if ($httpResp.StatusCode -ne 200) {
try{
$httpJson = $httpResp.Content | ConvertFrom-Json
$errorCode = $httpJson.error.code
Write-Debug "Got error $statuscode : $errorCode for URI: $uri"
}
catch {
Write-Debug "Http content is not JSON!"
}
}
$httpResp
}
}
function Get-MapAzResourceViaRESTAPI {
[CmdletBinding()]
param([string]$Uri)
begin {
#Import-Module Az
$script:apiver = "2021-04-01"
}
process {
$uriAndApi = $Uri + "?api-version=" + $script:apiver
Write-Verbose "Trying to GET resource at URI: $uriAndApi"
$httpResp = Invoke-AzRestMethod -Method GET -Path $uriAndApi
if ($httpResp.StatusCode -ne 200) {
$statuscode = $httpResp.StatusCode
$httpJson = $httpResp.Content | ConvertFrom-Json
$errorCode = $httpJson.error.code
Write-Debug "Got error $statuscode : $errorCode for URI: $uri"
if ($errorCode -like "NoRegisteredProviderFound") {
$errMsg = $httpJson.error.Message | Get-MapAzProviderErrorInfo
if ($errMsg.ApiVersions) {
$script:apiver = $errMsg.ApiVersions[-1]
$uriAndApi = $Uri + "?api-version=" + $script:apiver
#Write-Debug "Changing API versoin, trying URI: $uriAndApi"
$httpResp = Invoke-AzRestMethod -Method GET -Path $uriAndApi
}
}
}
if ($httpResp.StatusCode -ne 200) {
try{
$httpJson = $httpResp.Content | ConvertFrom-Json
$errorCode = $httpJson.error.code
Write-Verbose "Got error $statuscode : $errorCode for URI: $uri"
}
catch {
Write-Debug "Http content is not JSON!"
}
}
$httpResp
}
}
function Get-MapAzResourceAndSubResources {
[CmdletBinding()]
param(
[string]$SubscriptionId,
[string]$ResGroup,
[string]$ProviderName,
[string]$ResourceName,
[string]$ResourceType)
begin {
if (-not $global:allResources) { $global:allResources= @()}
}
process {
Write-Host "Scanning sub resources for resource: $ResourceName at group: $ResGroup"
foreach ($subResType in ((Get-MapAzResourceProvider -NameSpace $ProviderName).ResourceTypes.ResourceTypeName).Where({$_ -like "$ResourceType/*"})){
$subType = $subResType.Replace("$ResourceType/","")
$subResId = "/subscriptions/$SubscriptionId/resourceGroups/$ResGroup/providers/$ProviderName/$ResourceType/$ResourceName/$subType"
if (-not (($global:allResources).ResourceId -contains $subResId)){
Write-Verbose "Trying to get sub resource $subResId"
$httpResp = Get-MapAzResourceViaRESTAPI -Uri $subResId
if ($httpResp.StatusCode -eq 200) {
try {
$subResources = ($httpResp.Content | ConvertFrom-Json).value
if (-not (($global:allResources).ResourceId -contains $subResId)){
Write-Host "Found parent resource: $($subResId)" -ForegroundColor Green
$er = [PSCustomObject]@{
Name = $null
ResourceGroupName = $ResGroup
ResourceType = $ResourceType + "/" + $subType
Location = $null
ResourceId = $subResId
Tags = @{}
}
$global:allResources += $er
}
}
catch {
Write-Debug "Failed to parse JSON for URI $($item.Uri): $($_.Exception.Message)"
}
foreach ($subResource in $subResources){
if (($subResource.PSObject.Properties.Name -contains "Id") -and ($subResource.PSObject.Properties.Name -contains "type")){
if($subResource.type -like "$ProviderName*"){
Write-Host "Found sub resource: $($subResource.Id)" -ForegroundColor Green
$results = Get-AzResource -ResourceId $subResource.Id -ErrorAction SilentlyContinue
foreach ($res in $results){
if (($res.PSObject.Properties.Name -contains "ResourceType") -and $res.ResourceType){
$global:allResources += $res
$subrestype = $res.ResourceType.Replace("$ProviderName/","")
Get-MapAzResourceAndSubResources -SubscriptionId $SubscriptionId -ResGroup $ResGroup -ProviderName $ProviderName -ResourceName $res.Name -ResourceType $subrestype
}
else {Write-Debug "No type for resource $($res.Id)"}
}
}
else {
Write-Debug "This is not a resource: $($subResource.Id)"
Write-Debug "breaking loop, assuming other elements are the same..."
break
}
}
}
}
}
}
}
}
function Get-MapAzResource {
[CmdletBinding()]
param(
[Parameter(
Position = 0,
HelpMessage = 'Scope to filter resources by ResourceId prefix'
)]
[string]$Scope,
[Parameter(
HelpMessage = 'Optional resource type to filter (e.g., Microsoft.Compute/virtualMachines)'
)]
[string]$ResType,
[switch]$ScanSubResources
)
begin {
if (-not (Get-Variable -Name allResources -Scope Global -ErrorAction SilentlyContinue) -or -not $global:allResources){
Write-Verbose 'Fetching all subscriptions and resources...'
$subs = Get-AzSubscription
$global:allResources = @()
foreach ($sub in $subs) {
Write-Host "Switching to subscription $($sub.Name) ($($sub.Id))"
Set-AzContext -Subscription $sub.Id | Out-Null
$resources = Get-AzResource -ErrorAction SilentlyContinue
foreach ($res in $resources){
if (-not (($global:allResources).ResourceId -contains $res.Id)){
$global:allResources += $res
}
if ($ScanSubResources.IsPresent){
$providerName = $res.ResourceType.Split("/")[0]
$resType = $res.ResourceType.Replace("$providerName/","")
Get-MapAzResourceAndSubResources -SubscriptionId $sub -ResGroup $res.ResourceGroupName -ProviderName $providerName -ResourceName $res.Name -ResourceType $resType
}
}
}
}
}
process {
if ($Scope -or $ResType) {
# Filter the fresh or cached list
($global:allResources).Where({
($_.ResourceId -like "$Scope*") -and ($_.ResourceType -like "$ResType*")
})
}
else {
# Return a shallow copy of the full list
$global:allResources | ForEach-Object { $_ }
}
}
}
function Resolve-MapAzAccessPlane {
[CmdletBinding()]
param(
[Parameter()]
[string[]] $Actions,
[Parameter()]
[string] $ResourceScope,
[Parameter(Mandatory)]
[string]$Plane,
[string[]] $NotActions,
[bool]$IsDataAction
)
begin {
$OpsByAction = @{}
}
process {
$resAccessList = [System.Collections.Generic.List[PSCustomObject]]::new()
foreach ($action in $Actions) {
Write-Verbose "Processing action '$action'"
# Parse action into namespace, provider path, and operation
$parts = $action.Split('/')
$ns = $parts[0]
$prov = $parts[0..($parts.Length - 2)] -join '/'
$op = $parts[-1]
# Cache provider operations once per namespace
if (-not $OpsByAction.ContainsKey($ns)) {
Write-Verbose "Fetching provider operations for namespace '$ns'"
$OpsByAction[$action] = Get-MapAzProviderOperations -action $action -IsDataAction $IsDataAction
}
#Remove actions negated by not actions
$allowedOps = ($OpsByAction[$action]).Where({
foreach ($notAction in $NotActions){
if ($_.Operation -like $notAction) {return $false}
}
return $true
})
$nonResourceOperations = $allowedOps.Where({-not $_.ResourceName -and $_.IsDataAction -eq $false})
foreach ($nonResOp in $nonResourceOperations){
$resAccessList.Add([PSCustomObject]@{
ResourceId = $null
ResourceType = $null
ResourceName = $null
Operation = $nonResOp.Operation
OperationType = $nonResOp.Operation.Split('/')[-1]
ProviderNamespace = $nonResOp.ProviderNamespace
Plane = "Control"
})
}
Write-Verbose "Getting resources of type '$prov' under '$ResourceScope'"
$resources = Get-MapAzResource -Scope $ResourceScope -ResType $prov
Write-Verbose "Found $($resources.Count) matching resources"
$resources | Group-Object -Property ResourceType | ForEach-Object {
$type = $_.Name
$group = $_.Group
Write-Verbose "Filtering operations for resource type '$type'"
$matches = $allowedOps.Where({$_.Operation -like "$type/$op"})
Write-Verbose "Found $($matches.Count) matching operations for a resource of type '$type'"
foreach ($r in $group) {
foreach ($mo in $matches) {
$resAccessList.Add([PSCustomObject]@{
ResourceId = $r.ResourceId
ResourceType = $type
ResourceName = $r.Name
Operation = $mo.Operation
OperationType = $mo.Operation.Split('/')[-1]
ProviderNamespace = $mo.ProviderNamespace
Plane = $Plane
})
}
}
}
}
return $resAccessList | Sort-Object ResourceId, ResourceType ,ResourceName, Operation, OperationType, Plane -Unique
}
}
function Get-MapAzRoleAssignmentAccess {
[CmdletBinding(DefaultParameterSetName = 'ByUPN')]
param(
[Parameter(
Mandatory = $true,
Position = 0,
HelpMessage = 'Role Id'
)]
[ValidateNotNullOrEmpty()]
$Assignment,
[Parameter(
Mandatory = $false,
HelpMessage = 'Optional scope to filter results (e.g. /subscriptions/<id>)'
)]
[string]$ResourceScope)
begin {
Write-Host "Resolving assignments for role $($Assignment.RoleDefinitionName)"
$resScope = if ($ResourceScope) { $ResourceScope.ToLower() } else { $null }
$roleAccessList = [System.Collections.Generic.List[PSCustomObject]]::new()
if (-not $global:OpsByRoleAssignment) {
Write-Verbose "Initializing role assugment cache..."
$global:OpsByRoleAssignment = @{}
}
}
process {
$roles = Get-MapAzRoleDefinitions -roleId $Assignment.RoleDefinitionId
foreach ($role in $roles) {
$scope = $Assignment.Scope
if ( -not $global:OpsByRoleAssignment.ContainsKey($Assignment.RoleAssignmentId)){
Write-Host "Processing Role '$($role.Name)' for scope '$scope'"
if (-not $resScope -or $resScope.StartsWith($scope.ToLower())) {
$actions = $role.Actions
$notactions = $role.NotActions
Write-Verbose "Fetching control plane operations for role '$($Assignment.RoleAssignmentId)'"
Resolve-MapAzAccessPlane -Actions $actions -NotActions $notactions -ResourceScope $resScope -Plane "Control" -IsDataAction $false |
ForEach-Object { $roleAccessList.Add($_) }
$dataActions = $role.DataActions
$notDataActions = $role.NotDataActions
Write-Verbose "Fetching data plane operations for role '$($Assignment.RoleAssignmentId)'"
Resolve-MapAzAccessPlane -Actions $dataActions -NotActions $notDataActions -ResourceScope $resScope -Plane "Data" -IsDataAction $true |
ForEach-Object { $roleAccessList.Add($_) }
$global:OpsByRoleAssignment[$Assignment.RoleAssignmentId] = $roleAccessList
}
}
else {Write-Verbose "Role assigment already cached : '$($Assignment.RoleDefinitionName) : $($Assignment.RoleDefinitionId)'"}
}
}
end {
Write-Host "Sorting and de-duplicating results for Role '$($Assignment.RoleDefinitionName)'"
$result = $result | Sort-Object ResourceId, ResourceName, Operation, OperationType -Unique
Write-Host "Total unique access entries: $($result.Count)"
return $result
}
}
function Get-MapAzUserAccess {
[CmdletBinding(DefaultParameterSetName = 'ByUPN')]
param(
[Parameter(
Mandatory = $true,
ParameterSetName = 'ByUPN',
Position = 0,
HelpMessage = 'User Principal Name (e.g. alice@contoso.com)'
)]
[ValidateNotNullOrEmpty()]
[string]$UserPrincipalName,
[Parameter(
Mandatory = $true,
ParameterSetName = 'ById',
Position = 0,
HelpMessage = 'Azure AD ObjectId GUID'
)]
[ValidateNotNullOrEmpty()]
[string]$UserId,
[Parameter(
Mandatory = $false,
HelpMessage = 'Optional scope to filter results (e.g. /subscriptions/<id>)'
)]
[string]$ResourceScope
)
begin {
if ($PSCmdlet.ParameterSetName -eq 'ByUPN') {
$userassignments = Get-MapAzRoleAssignments -UserName $UserPrincipalName -ErrorAction SilentlyContinue
$currUserId = (Get-MapAzUsers -userPrincipalName $UserPrincipalName).Id
$currUserPrincipalName = $UserPrincipalName
}
else {
$userassignments = Get-MapAzRoleAssignments -UserId $UserId -ErrorAction SilentlyContinue
$currUserPrincipalName = (Get-MapAzUsers -userId $UserId).UserPrincipalName
$currUserId = $UserId
}
if (-not $userassignments) {
Write-Warning "Could not find User Assignments for user $((@($UserPrincipalName, $UserId, ("Unknown")) | Where-Object { $_ -ne $null} | Select-Object -First 1))"
return
}
Write-Verbose "Found $($userassignments.Count) assignment(s)."
$resScope = if ($ResourceScope) { $ResourceScope.ToLower() } else { $null }
}
process {
foreach ($assignment in $userassignments) {
Get-MapAzRoleAssignmentAccess -Assignment $assignment -ResourceScope $resScope
}
}
end {
Write-Host "Collecting assignments and their access for '$currUserPrincipalName':'$currUserId'"
$assignmentCount = 0
[int]$totalCount = 0
foreach ($a in $userAssignments) {
$ops = $global:OpsByRoleAssignment[$a.RoleAssignmentId]
if ($ops) {
$totalCount += $ops.Count
$assignmentCount++
}
}
[EnrichedOp[]]$results = New-Object EnrichedOp[] $totalCount
[int]$idx = 0
foreach ($a in $userAssignments) {
$ops = $global:OpsByRoleAssignment[$a.RoleAssignmentId]
if ($ops) {
foreach ($op in $ops) {
$results[$idx++] = [EnrichedOp]::new(
$op.ResourceId,
$op.ResourceName,
$op.ResourceType,
$op.Operation,
$op.OperationType,
$op.ProviderNamespace,
$currUserId,
$currUserPrincipalName,
$op.Plane
)
}
}
}
Write-Host "Filtering duplicate operations..."
$results = $results | Sort-Object UserId,UserName, ResourceId, ResourceName, ResourceType, Operation, OperationType -Unique
Write-Host "Total assigned roles for $$currUserPrincipalName: $assignmentCount"
Write-Host "Total unique access entries: $($results.Count)"
return $results
}
}
function Get-MapAzAllUsersAccess {
[CmdletBinding()]
param()
begin {
Write-Host "Collecting assignments for all users and converting to access objects..."
}
process {
$allAccess = Get-MapAzUsers | ForEach-Object {Get-MapAzUserAccess -UserId $_.Id}
}
end
{
return $allAccess
}
}
# Export the function when the module is imported
Export-ModuleMember -Function Get-MapAzUserAssigments,Get-MapAzResource,Test-MapAzUserGroupMembership,
Get-MapAzRoleAssignments,Clear-MapAzScriptCache,Get-MapAzUserAccess,
Get-MapAzUsers,Get-MapAzProviderOperations,Get-MapAzResourceProvider,
Get-MapAzAllUsersAccess,Get-MapAzResourceViaRESTAPI,Get-MapAzResourceAndSubResources,
Get-MapAzResourceViaNativeRESTAPI,Get-MapAzThrottleLimit,Set-MapAzThrottleLimit