src/ingest/Import-Governance.ps1
|
#Requires -Version 7.0 Set-StrictMode -Version Latest $ErrorActionPreference = 'Stop' <# .SYNOPSIS Native governance collector — populate collect.json's `governance` object directly from Azure Resource Graph + the ambient ARM token, with NO third-party dependency on the Azure Governance Visualizer. .DESCRIPTION This is the default governance ingestor (AB#5041). It replaces the `Import-AzGovViz` dependency for everything the assessment rules and the ALZ benchmark actually query: governance.managementGroups[] <- ARG resourcecontainers governance.policyAssignments[] <- ARG policyresources governance.roleAssignments[] <- ARG authorizationresources governance.budgets[] <- ARM REST (Microsoft.Consumption) governance.resourceLocks[] <- ARM REST (Microsoft.Authorization/locks) governance.pimEligibility[] <- Azure RBAC role eligibility schedules (see NOTES) governance.roleAssignmentSchedules[] <- Azure RBAC role assignment schedules (see NOTES) governance.classicAdministrators[] <- not collected here (see NOTES) Why native instead of AzGovViz: the visualizer is heavy third-party code that is not StrictMode-safe and hard-fails on retired ARM APIs (e.g. classicAdministrators -> 404 InvalidResourceType), which took the whole Scout run down with it. Every governance signal the rules read is a first-class ARG table (policyresources / authorizationresources / resourcecontainers) or a simple ambient-token ARM REST call — no cloned repo, no AzAPICall install prompt, no interactive prompts, fully unattended. AzGovViz remains available as an opt-in ingestor (`Import-AzGovViz`) for anyone who wants the full visualizer output, but nothing depends on it by default. The object is attached with the SAME `Add-Member -NotePropertyName governance` shape the AzGovViz ingestor used, so the rule engine, Compare-Benchmark, and the report renderers see an identical contract. Read-only throughout: Reader at the management-group root is sufficient (policy/role/MG reads via ARG; budgets/locks via ARM GET). .NOTES Tracks ADO Story AB#5041 (supersedes the AzGovViz hard dependency; Story AB#5038). One dataset is deliberately NOT collected here: * classicAdministrators - the classic administrators ARM API is retired (returns 404 InvalidResourceType) and classic co-admins are being removed platform-wide, so an empty set reflects reality. CAF-IDN-03 asserts `notExists`, i.e. an empty set is the compliant (Pass) outcome. PIM is collected, through Azure RBAC rather than Graph. This note used to say it needed an Entra ID P2 license and a Graph application permission and so was left empty; that was wrong about the route. `Get-AzRoleEligibilitySchedule` and `Get-AzRoleAssignmentSchedule` are Azure Resource Manager reads that the Reader role covers, and the collect pass (Get-ScoutGovernanceDataset, through Get-ScoutRbacScheduleDataset) was already making the first one per subscription and discarding the answer. When the collect pass supplied them (`governance.rbacSchedulesRead`) this function reuses them; with no raw pass (-Source TypedQueries) it makes the same per-subscription reads itself, so both collect.json paths carry the same keys. `pimEligibilityAvailable` is true only when the read answered for EVERY subscription -- see Get-ScoutRbacScheduleDataset. Issue #104: the same is now true of the four datasets above. `policyAssignmentsAvailable`, `roleAssignmentsAvailable`, `budgetsAvailable` and `resourceLocksAvailable` are true only when EVERY read of the dataset answered (an empty answer counts), and each has a `...Reason` that counts what did not. They used to mean "some rows came back", so a budget read denied for one subscription of 42 left the flag true and the rules scored 41 subscriptions' budgets as the estate's. When the collect pass read the datasets (`governance.governanceRead`) its rows, flags and reasons are reused as they are; otherwise this function reads them and decides the same way (Get-ScoutGovernanceReadSummary). #> function Import-Governance { [CmdletBinding()] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', 'ManagementGroupId', Justification = 'Accepted for call-site parity with Invoke-ScoutAssessmentCore -- Line 206 always passes it -- but every ARG query here runs tenant-wide; MG-scoped filtering is not implemented yet.')] param($Collect, [string] $ManagementGroupId) Import-Module Az.ResourceGraph -ErrorAction Stop if (-not (Get-Command Invoke-AzRestMethod -ErrorAction SilentlyContinue)) { Import-Module Az.Accounts -ErrorAction Stop } if (-not (Get-Command Get-ScoutRbacScheduleDataset -ErrorAction SilentlyContinue)) { . (Join-Path $PSScriptRoot '../collect/Get-ScoutRbacScheduleDataset.ps1') } if (-not (Get-Command Get-ScoutGovernanceReadSummary -ErrorAction SilentlyContinue)) { . (Join-Path $PSScriptRoot '../collect/Get-ScoutGovernanceReadSummary.ps1') } # ---- ARG helper: paged, scoped to the management group when one is supplied ---- # Mirrors Invoke-Collect's paging: Search-AzGraph rejects -Skip 0 # (ValidateRange minimum is 1), so omit it on the first page. function Invoke-GovArg([string] $Query, [switch] $UseTenantScope) { $rows = @(); $skip = 0 do { $params = @{ Query = $Query; First = 1000; ErrorAction = 'Stop' } if ($skip -gt 0) { $params.Skip = $skip } # AB#6901 -- management groups are TENANT-level containers, invisible to a default # (subscription-scoped) Resource Graph call: proven live, 0 rows default vs 18 with # -UseTenantScope, same SPN, same tenant. The two scope parameters are mutually # exclusive on Search-AzGraph, and an explicit -ManagementGroupId run is already # scoped to the subtree the caller asked for, so tenant scope only applies when no # management group was supplied. if ($UseTenantScope -and -not $ManagementGroupId) { $params.UseTenantScope = $true } elseif ($ManagementGroupId) { $params.ManagementGroup = $ManagementGroupId } # AB#6779. `@(Search-AzGraph @params)` collects the PSResourceGraphResponse WRAPPER as # a single element rather than the rows -- always, not only when the result is empty. # That made $batch.Count permanently 1, so this loop's `-eq 1000` condition could NEVER # fire and every query here was silently capped at its first page. Reading `.Data` is # the only shape that behaves the same whether the result is empty or not. # Assigned in STATEMENTS, not as `$batch = if (...) { @($response.Data) }`: an if-block # yields its body through the output stream and an EMPTY array contributes zero objects # to it, so the expression form assigns $null on exactly the empty result this handles, # and `$batch.Count` below then throws under StrictMode. $response = Search-AzGraph @params $batch = @() if ($null -ne $response -and $response.PSObject.Properties['Data']) { $batch = @($response.Data) } elseif ($null -ne $response) { $batch = @($response) } $rows += $batch; $skip += 1000 } while ($batch.Count -eq 1000) return , $rows } # 1) management groups (Compare-Benchmark matches archetype names against .name). # -UseTenantScope is REQUIRED here (AB#6901): without it the query returned zero rows on # every run in the product's history -- empty in all eight reference tenants across both # corpus runs -- so archetype matching and the MG-hierarchy rules always scored an estate # with no management groups at all. $mgQuery = @' resourcecontainers | where type =~ "microsoft.management/managementgroups" | project name, id, displayName = tostring(properties.displayName), parent = tostring(properties.details.parent.name) '@ $mgs = @() # Issue #104: the hierarchy is only COMPLETE when the tenant-level read answered. The default-scope retry below is a # floor, not an answer: it cannot see management groups at all (0 rows against 18 for the same identity), so a tenant # whose tenant-level read was refused must read "management groups not assessed", never "no management groups". $mgFailed = 1 try { $mgs = Invoke-GovArg $mgQuery -UseTenantScope $mgFailed = 0 } catch { # Tenant scope needs a tenant-level read the caller may not hold (Reader at root MG). The # default-scope retry keeps the old behavior as the floor rather than trading one empty # result for a new hard failure. Write-Verbose "Import-Governance: tenant-scoped management-group query failed, retrying at default scope (AB#6901): $($_.Exception.Message)" try { $mgs = Invoke-GovArg $mgQuery } catch { Write-Warning "Import-Governance: management-group query failed: $($_.Exception.Message)" } } $mgSummary = Get-ScoutGovernanceReadSummary -Label 'Management groups' -Unit 'query scope(s)' -Asked 1 -Failed $mgFailed if ($mgSummary.Reason) { Write-Warning "Import-Governance: $($mgSummary.Reason)" } # ---- what the collect pass already handed over (AB#6779) ---------------------------------- # Four of the six datasets below are now collected by Get-ScoutRawInventory, because the four # inventory collectors that render them (Identity/RoleAssignments, Management/PolicyAssignments, # Management/ResourceLocks, Management/Budgets) run over the raw pass's resource rows, not over # collect.json. Invoke-Collect puts them on $Collect.governance before this function is called. # # Re-querying them here would be four round trips for rows already in memory -- exactly the # duplication AB#6773 spent a release removing -- so each one is skipped when it is already # populated. Nothing is skipped when it is EMPTY: an empty array is indistinguishable from # "the raw pass never ran" (-Source TypedQueries, -FromCollect on an old file), and quietly # reporting zero role assignments would be the worst possible failure mode for a governance # assessment. # # Every return carries the unary comma. A bare `return @()` is pipeline-UNROLLED to zero output # objects, so the caller captures $null and `$policy.Count` is a StrictMode throw rather than 0 # -- the same idiom Invoke-Collect's Invoke-CollectQuery already documents. function Get-GovAlreadyCollected([string] $Name) { if (-not $Collect.PSObject.Properties['governance'] -or $null -eq $Collect.governance) { return , @() } if (-not $Collect.governance.PSObject.Properties[$Name]) { return , @() } return , @($Collect.governance.$Name | Where-Object { $_ }) } # ---- issue #104: did EVERY read answer? --------------------------------------------------------------- # Each dataset below carries `<name>Available` and `<name>Reason`. Available is $true only when every read of # the dataset answered (an empty answer counts), NOT when "some rows came back": 39 of 42 subscriptions' budgets # are not the estate's budgets, and a rule that passes on "no budget is missing a notification" would pass on them. # # When the collect pass already read the dataset (`governance.governanceRead`), its rows AND its flag and reason are # used as they are -- an empty array there is a real answer, and re-asking would only repeat a read that failed. # Without that marker (-Source TypedQueries, or rows an older collect left behind) this function reads the dataset # itself and decides the flag from its own reads. $governanceFromCollectPass = $false if ($Collect.PSObject.Properties['governance'] -and $null -ne $Collect.governance -and $Collect.governance.PSObject.Properties['governanceRead']) { $governanceFromCollectPass = [bool]$Collect.governance.governanceRead } function Get-GovCollectedValue([string] $Name) { if ($Collect.PSObject.Properties['governance'] -and $null -ne $Collect.governance -and $Collect.governance.PSObject.Properties[$Name]) { return $Collect.governance.$Name } return $null } $govSummaries = [System.Collections.Generic.List[object]]::new() # 2) policy assignments - keep the nested `properties` object so rule JSONPaths # (@.properties.enforcementMode / .parameters / .displayName) resolve unchanged. $policy = Get-GovAlreadyCollected 'policyAssignments' $policyAssignmentsAvailable = $false $policyAssignmentsReason = $null if ($governanceFromCollectPass) { $policyAssignmentsAvailable = [bool](Get-GovCollectedValue 'policyAssignmentsAvailable') $policyAssignmentsReason = Get-GovCollectedValue 'policyAssignmentsReason' Write-Verbose "Import-Governance: reusing $($policy.Count) policy assignments from the collect pass (AB#6779), available=$policyAssignmentsAvailable." } elseif ($policy.Count -gt 0) { $policyAssignmentsAvailable = $true Write-Verbose "Import-Governance: reusing $($policy.Count) policy assignments from the collect pass (AB#6779)." } else { $policyFailed = 0 try { $policy = Invoke-GovArg @' policyresources | where type =~ "microsoft.authorization/policyassignments" | project name, id, type, properties '@ } catch { $policyFailed = 1 Write-Warning "Import-Governance: policy-assignment query failed: $($_.Exception.Message)" } $summary = Get-ScoutGovernanceReadSummary -Label 'Policy assignments' -Unit 'query scope(s)' -Asked 1 -Failed $policyFailed $policyAssignmentsAvailable = [bool]$summary.Available $policyAssignmentsReason = $summary.Reason $govSummaries.Add($summary) } # 3) role assignments - properties.principalType drives CAF-IDN-01/05. $roles = Get-GovAlreadyCollected 'roleAssignments' $roleAssignmentsAvailable = $false $roleAssignmentsReason = $null if ($governanceFromCollectPass) { $roleAssignmentsAvailable = [bool](Get-GovCollectedValue 'roleAssignmentsAvailable') $roleAssignmentsReason = Get-GovCollectedValue 'roleAssignmentsReason' Write-Verbose "Import-Governance: reusing $($roles.Count) role assignments from the collect pass (AB#6779), available=$roleAssignmentsAvailable." } elseif ($roles.Count -gt 0) { $roleAssignmentsAvailable = $true Write-Verbose "Import-Governance: reusing $($roles.Count) role assignments from the collect pass (AB#6779)." } else { $roleFailed = 0 try { $roles = Invoke-GovArg @' authorizationresources | where type =~ "microsoft.authorization/roleassignments" | project name, id, type, properties '@ } catch { $roleFailed = 1 Write-Warning "Import-Governance: role-assignment query failed: $($_.Exception.Message)" } $summary = Get-ScoutGovernanceReadSummary -Label 'Role assignments' -Unit 'query scope(s)' -Asked 1 -Failed $roleFailed $roleAssignmentsAvailable = [bool]$summary.Available $roleAssignmentsReason = $summary.Reason $govSummaries.Add($summary) } # 4/5) budgets + resource locks - neither is indexed by Resource Graph, so pull # them per subscription via the ambient ARM token (Invoke-AzRestMethod uses # the current Az context; works headless under an SPN login). Read-only GET. $budgets = Get-GovAlreadyCollected 'budgets' $locks = Get-GovAlreadyCollected 'resourceLocks' $subIds = @($Collect.subscriptions | ForEach-Object { if ($_ -and $_.PSObject.Properties['id']) { $_.id } } | Where-Object { $_ }) # The two reads share a loop but are skipped INDEPENDENTLY. Skipping only when both are in # hand would be wrong the other way round: appending a second copy of the budgets to a set the # collect pass already supplied would double every budget row. $allSubIds = @($subIds) $budgetsReused = $governanceFromCollectPass -or $budgets.Count -gt 0 $locksReused = $governanceFromCollectPass -or $locks.Count -gt 0 $budgetsAvailable = $false; $budgetsReason = $null $resourceLocksAvailable = $false; $resourceLocksReason = $null if ($budgetsReused) { if ($governanceFromCollectPass) { $budgetsAvailable = [bool](Get-GovCollectedValue 'budgetsAvailable') $budgetsReason = Get-GovCollectedValue 'budgetsReason' } else { $budgetsAvailable = $true } } if ($locksReused) { if ($governanceFromCollectPass) { $resourceLocksAvailable = [bool](Get-GovCollectedValue 'resourceLocksAvailable') $resourceLocksReason = Get-GovCollectedValue 'resourceLocksReason' } else { $resourceLocksAvailable = $true } } if ($budgetsReused -or $locksReused) { Write-Verbose "Import-Governance: reusing $($budgets.Count) budgets and $($locks.Count) resource locks from the collect pass (AB#6779)." } if ($budgetsReused -and $locksReused) { $subIds = @() } $budgetsFailed = 0; $budgetStatus = [System.Collections.Generic.List[string]]::new() $locksFailed = 0; $lockStatus = [System.Collections.Generic.List[string]]::new() foreach ($sub in $subIds) { if (-not $budgetsReused) { try { $resp = Invoke-AzRestMethod -Method GET -Path "/subscriptions/$sub/providers/Microsoft.Consumption/budgets?api-version=2023-11-01" if ($resp.StatusCode -eq 200) { $val = ($resp.Content | ConvertFrom-Json -Depth 100).value if ($val) { $budgets += $val } } else { $budgetsFailed++; $budgetStatus.Add([string]$resp.StatusCode) } } catch { $budgetsFailed++ Write-Warning "Import-Governance: budgets read failed for $sub`: $($_.Exception.Message)" } } if (-not $locksReused) { try { $resp = Invoke-AzRestMethod -Method GET -Path "/subscriptions/$sub/providers/Microsoft.Authorization/locks?api-version=2020-05-01" if ($resp.StatusCode -eq 200) { $val = ($resp.Content | ConvertFrom-Json -Depth 100).value if ($val) { $locks += $val } } else { $locksFailed++; $lockStatus.Add([string]$resp.StatusCode) } } catch { $locksFailed++ Write-Warning "Import-Governance: resource-lock read failed for $sub`: $($_.Exception.Message)" } } } $noSubscriptions = 'No subscription was available to read from.' if (-not $budgetsReused) { $summary = Get-ScoutGovernanceReadSummary -Label 'Budgets' -Unit 'subscription(s)' -Asked $subIds.Count -Failed $budgetsFailed -StatusCode $budgetStatus.ToArray() -NothingAskedReason "Budgets were not read. $noSubscriptions" $budgetsAvailable = [bool]$summary.Available; $budgetsReason = $summary.Reason; $govSummaries.Add($summary) } if (-not $locksReused) { $summary = Get-ScoutGovernanceReadSummary -Label 'Resource locks' -Unit 'subscription(s)' -Asked $subIds.Count -Failed $locksFailed -StatusCode $lockStatus.ToArray() -NothingAskedReason "Resource locks were not read. $noSubscriptions" $resourceLocksAvailable = [bool]$summary.Available; $resourceLocksReason = $summary.Reason; $govSummaries.Add($summary) } foreach ($summary in $govSummaries) { if ($summary.Reason -and $summary.Asked -gt 0) { Write-Warning "Import-Governance: $($summary.Reason)" } } # 6) Azure RBAC PIM schedules: eligibility (who CAN elevate) and role assignment schedules # (who has access now, and whether it needed an activation). The collect pass reads them # once per subscription; reuse that answer when it asked, otherwise ask here so the typed # path carries the same keys. Never throws -- an unreadable schedule is "not available". $rbacRead = $false if ($Collect.PSObject.Properties['governance'] -and $null -ne $Collect.governance -and $Collect.governance.PSObject.Properties['rbacSchedulesRead']) { $rbacRead = [bool]$Collect.governance.rbacSchedulesRead } $rbac = $null if ($rbacRead) { $rbac = [pscustomobject]@{ pimEligibility = Get-GovAlreadyCollected 'pimEligibility' pimEligibilityAvailable = [bool](Get-GovCollectedValue 'pimEligibilityAvailable') pimEligibilityReason = Get-GovCollectedValue 'pimEligibilityReason' roleAssignmentSchedules = Get-GovAlreadyCollected 'roleAssignmentSchedules' roleAssignmentSchedulesMeasured = [bool](Get-GovCollectedValue 'roleAssignmentSchedulesMeasured') roleAssignmentSchedulesReason = Get-GovCollectedValue 'roleAssignmentSchedulesReason' privilegedAccessMeasured = [bool](Get-GovCollectedValue 'privilegedAccessMeasured') } Write-Verbose "Import-Governance: reusing $(@($rbac.pimEligibility).Count) PIM eligibility and $(@($rbac.roleAssignmentSchedules).Count) role assignment schedule rows from the collect pass." } else { try { $rbac = Get-ScoutRbacScheduleDataset -SubscriptionId $allSubIds } catch { $rbacFailure = "The Azure RBAC schedule read failed: $($_.Exception.Message)" Write-Warning "Import-Governance: $rbacFailure" $rbac = [pscustomobject]@{ pimEligibility = @(); pimEligibilityAvailable = $false; pimEligibilityReason = $rbacFailure roleAssignmentSchedules = @(); roleAssignmentSchedulesMeasured = $false; roleAssignmentSchedulesReason = $rbacFailure privilegedAccessMeasured = $false } } } # Normalize every dataset to a clean array of real objects. The paged ARG # helper's `return , $rows` idiom preserves populated arrays intact, but for a # query that yields ZERO rows it leaks a single-element wrapper whose element is # an empty array — which would otherwise report as Count=1 and trip StrictMode # member access downstream (and, worse, make Compare-Benchmark's governance # guard think management-group data exists when it does not). Filtering to # truthy elements collapses that wrapper back to a genuine empty set while # leaving real policy/role/MG objects untouched. $gov = [pscustomobject]@{ managementGroups = @($mgs | Where-Object { $_ }) managementGroupsAvailable = [bool]$mgSummary.Available managementGroupsReason = $mgSummary.Reason policyAssignmentsAvailable = $policyAssignmentsAvailable policyAssignmentsReason = $policyAssignmentsReason policyAssignments = @($policy | Where-Object { $_ }) roleAssignmentsAvailable = $roleAssignmentsAvailable roleAssignmentsReason = $roleAssignmentsReason roleAssignments = @($roles | Where-Object { $_ }) budgetsAvailable = $budgetsAvailable budgetsReason = $budgetsReason budgets = @($budgets | Where-Object { $_ }) resourceLocksAvailable = $resourceLocksAvailable resourceLocksReason = $resourceLocksReason resourceLocks = @($locks | Where-Object { $_ }) # Issue #104: true when the collect pass read the four datasets above; this function then reused them. governanceRead = $governanceFromCollectPass # Azure RBAC PIM schedules -- see NOTES. Same keys as Invoke-Collect's governance block. pimEligibilityAvailable = [bool]$rbac.pimEligibilityAvailable pimEligibilityReason = $rbac.pimEligibilityReason pimEligibility = @($rbac.pimEligibility | Where-Object { $_ }) roleAssignmentSchedulesMeasured = [bool]$rbac.roleAssignmentSchedulesMeasured roleAssignmentSchedulesReason = $rbac.roleAssignmentSchedulesReason roleAssignmentSchedules = @($rbac.roleAssignmentSchedules | Where-Object { $_ }) privilegedAccessMeasured = [bool]$rbac.privilegedAccessMeasured rbacSchedulesRead = $true classicAdministrators = @() # retired ARM API - see NOTES } $Collect | Add-Member -NotePropertyName governance -NotePropertyValue $gov -Force # Issue #104: a dataset THIS function read, in part, is a Partial row in the collect's collection health (counts only), # the same row the raw pass writes for the datasets it reads. A reused dataset already has its row. if ($Collect.PSObject.Properties['_meta'] -and $null -ne $Collect._meta -and $Collect._meta.PSObject.Properties['collectionHealth']) { $partialRows = @( foreach ($summary in @($mgSummary) + @($govSummaries)) { if ($null -eq $summary -or $summary.Available -or $summary.Asked -le 0) { continue } [pscustomobject]@{ Dataset = [string]$summary.Label; Source = 'Data completeness'; Operation = 'Read every scope'; Status = 'Partial' Reason = [string]$summary.Reason; ScopesAsked = $summary.Asked; ScopesAnswered = $summary.Answered; ScopesFailed = $summary.Failed ResourceTypes = @(); Collectors = @() } } ) if ($partialRows.Count -gt 0) { $Collect._meta.collectionHealth = @($Collect._meta.collectionHealth) + $partialRows } } Write-Verbose ("Import-Governance: MGs={0} policyAssignments={1} roleAssignments={2} budgets={3} locks={4}" -f ` @($mgs).Count, @($policy).Count, @($roles).Count, @($budgets).Count, @($locks).Count) return $Collect } |