diff --git a/powershell/assets/MaesterSettings.psd1 b/powershell/assets/MaesterSettings.psd1 index 48f21d5a73..aac067ca75 100644 --- a/powershell/assets/MaesterSettings.psd1 +++ b/powershell/assets/MaesterSettings.psd1 @@ -6,6 +6,7 @@ SchemaVersion = '1.0' Settings = @{ EmergencyAccessAccounts = @{ Type = 'object[]'; Default = @(); Sensitive = $false; Description = 'Emergency access (break glass) accounts and groups excluded from Conditional Access checks.' } + DelegatedAdminTenants = @{ Type = 'string[]'; Default = @(); Sensitive = $false; Description = 'Tenant IDs allowed to administer this tenant through Tenant Governance, GDAP or Microsoft Entra role assignments (allowlist).' } DataverseEnvironmentUrl = @{ Type = 'string'; Default = ''; Sensitive = $false; Description = 'URL of the Dataverse environment that the Copilot Studio checks read.' } GitHubOrganization = @{ Type = 'string'; Default = ''; Sensitive = $false; Description = 'GitHub organization that the GitHub checks read.' } GitHubApiBaseUri = @{ Type = 'string'; Default = 'https://api.github.com'; Sensitive = $false; Description = 'Base URI of the GitHub REST API.' } diff --git a/powershell/assets/templates/maester-config.json b/powershell/assets/templates/maester-config.json index f4c4b25b13..66f3a5735b 100644 --- a/powershell/assets/templates/maester-config.json +++ b/powershell/assets/templates/maester-config.json @@ -1,6 +1,7 @@ { "GlobalSettings": { - "EmergencyAccessAccounts": [] + "EmergencyAccessAccounts": [], + "DelegatedAdminTenants": [] }, "TestSettings": [] } diff --git a/powershell/internal/checks/maester/entra/Get-MtCaRiskRemediationPolicyResult.ps1 b/powershell/internal/checks/maester/entra/Get-MtCaRiskRemediationPolicyResult.ps1 new file mode 100644 index 0000000000..4cdf4946f1 --- /dev/null +++ b/powershell/internal/checks/maester/entra/Get-MtCaRiskRemediationPolicyResult.ps1 @@ -0,0 +1,112 @@ +function Get-MtCaRiskRemediationPolicyResult { + <# + .SYNOPSIS + Evaluates the Conditional Access policies that require risk remediation for risky users. + + .DESCRIPTION + Shared evaluation of MT.1253, also used by MT.1013 to skip the password change check when MT.1253's + requirement is met. A policy qualifies when it: + - is enabled, + - includes all users, excluding only emergency access accounts and the guest/external-user selector, + - targets all resources, + - is scoped to every user risk level from MinimumUserRiskLevel up to high, and + - requires the riskRemediation grant control. + + Emergency access comes from the EmergencyAccessAccounts setting. Without the setting, a user or group excluded + from every Conditional Access policy that targets users (at least two) is taken as emergency access, as MT.1005 + does. Get-MtEmergencyAccessAccount throws when a configured entry cannot be resolved. + + Returns one object with the policies, a report row per risk remediation policy and whether any policy qualifies. + + .EXAMPLE + (Get-MtCaRiskRemediationPolicyResult).Pass + + Returns $true when at least one policy requires risk remediation for high-risk users as MT.1253 requires. + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param( + # Lowest user risk level that a qualifying policy must cover; every higher level must be covered too. + [ValidateSet('high', 'medium', 'low')] + [string] $MinimumUserRiskLevel = 'high' + ) + + $requiredRiskLevels = switch ($MinimumUserRiskLevel) { + 'low' { @('low', 'medium', 'high') } + 'medium' { @('medium', 'high') } + default { @('high') } + } + + $policies = @(Get-MtConditionalAccessPolicy) + $riskRemediationPolicies = @($policies | Where-Object { + @($_.grantControls.builtInControls) -contains 'riskRemediation' + } | Sort-Object -Property displayName) + + # Emergency access exclusions are allowed. They come from the EmergencyAccessAccounts setting; the helper fails if + # a configured object cannot be resolved. Without the setting, a user or group excluded from every Conditional + # Access policy that targets users is taken as emergency access, as MT.1005 does. One policy is not enough to + # tell an emergency access account from any other exclusion. + $emergencyAccess = @(Get-MtEmergencyAccessAccount) + $emergencyUserIds = @($emergencyAccess | Where-Object { $_.Type -eq 'user' -and $_.ObjectId } | ForEach-Object { $_.ObjectId }) + $emergencyGroupIds = @($emergencyAccess | Where-Object { $_.Type -eq 'group' -and $_.ObjectId } | ForEach-Object { $_.ObjectId }) + $emergencyAccessDetected = $false + if ($emergencyAccess.Count -eq 0) { + $userPolicies = @($policies | Where-Object { + -not $_.conditions.applications.includeAuthenticationContextClassReferences -and + -not $_.conditions.clientApplications.includeServicePrincipals -and + -not $_.conditions.clientApplications.includeAgentIdServicePrincipals + }) + if ($userPolicies.Count -ge 2) { + $excludedFromAll = { + param([string] $Property) + @($userPolicies | ForEach-Object { @($_.conditions.users.$Property | Where-Object { $_ -and $_ -ne 'GuestsOrExternalUsers' } | Select-Object -Unique) } | + Group-Object | Where-Object { $_.Count -eq $userPolicies.Count } | ForEach-Object { $_.Name }) + } + $emergencyUserIds = & $excludedFromAll 'excludeUsers' + $emergencyGroupIds = & $excludedFromAll 'excludeGroups' + $emergencyAccessDetected = ($emergencyUserIds.Count + $emergencyGroupIds.Count) -gt 0 + } + } + + $report = foreach ($policy in $riskRemediationPolicies) { + $userRiskLevels = @($policy.conditions.userRiskLevels | Where-Object { $_ }) + $missingRiskLevels = @($requiredRiskLevels | Where-Object { $_ -notin $userRiskLevels }) + $users = $policy.conditions.users + # Both the legacy GuestsOrExternalUsers token and excludeGuestsOrExternalUsers select only guest/external + # users, for whom risk remediation is unsupported. Neither exempts arbitrary workforce users or roles. + $unapprovedUsers = @($users.excludeUsers | Where-Object { $_ -and $_ -ne 'GuestsOrExternalUsers' -and $_ -notin $emergencyUserIds }) + $unapprovedGroups = @($users.excludeGroups | Where-Object { $_ -and $_ -notin $emergencyGroupIds }) + $excludedRoles = @($users.excludeRoles | Where-Object { $_ }) + $checks = [ordered]@{ + 'Enabled' = $policy.state -eq 'enabled' + 'All users' = @($policy.conditions.users.includeUsers) -contains 'All' + 'Only approved user exclusions' = ($unapprovedUsers.Count + $unapprovedGroups.Count + $excludedRoles.Count) -eq 0 + 'All resources' = @($policy.conditions.applications.includeApplications) -contains 'All' + "User risk $($requiredRiskLevels -join ', ')" = $missingRiskLevels.Count -eq 0 + } + $failed = @($checks.GetEnumerator() | Where-Object { -not $_.Value } | ForEach-Object { $_.Key }) + $exclusionCount = @($policy.conditions.users.excludeUsers | Where-Object { $_ }).Count + + @($policy.conditions.users.excludeGroups | Where-Object { $_ }).Count + + @($policy.conditions.users.excludeRoles | Where-Object { $_ }).Count + + $(if ($users.excludeGuestsOrExternalUsers) { 1 } else { 0 }) + + [pscustomobject]@{ + Policy = $policy + UserRiskLevels = if ($userRiskLevels.Count -gt 0) { $userRiskLevels -join ', ' } else { 'None' } + Exclusions = $exclusionCount + Failed = $failed -join ', ' + Pass = $failed.Count -eq 0 + } + } + $report = @($report) + + [pscustomobject]@{ + RequiredRiskLevels = $requiredRiskLevels + Policies = $policies + Report = $report + Pass = @($report | Where-Object { $_.Pass }).Count -gt 0 + EmergencyUserIds = @($emergencyUserIds) + EmergencyGroupIds = @($emergencyGroupIds) + EmergencyAccessDetected = $emergencyAccessDetected + } +} diff --git a/powershell/internal/checks/maester/entra/Test-MtAccessPackageDrift.ps1 b/powershell/internal/checks/maester/entra/Test-MtAccessPackageDrift.ps1 new file mode 100644 index 0000000000..ed94109b49 --- /dev/null +++ b/powershell/internal/checks/maester/entra/Test-MtAccessPackageDrift.ps1 @@ -0,0 +1,419 @@ +ο»Ώfunction Test-MtAccessPackageDrift { + <# + .SYNOPSIS + Checks that the access to governed resources of one scope comes from access package assignments. + + .DESCRIPTION + Shared check of MT.1255 (groups that are not role-assignable), MT.1256 (role-assignable groups) and MT.1257 + (enterprise applications). Access package drift (Microsoft Entra ID Governance > Access Guardian, Microsoft Graph + beta accessDriftSummary) compares the members of governed groups and the app role assignments of governed + enterprise applications with the access package assignments that should grant them. It lists only resources + with drift, so the resources of the entitlement management catalogs tell whether a resource of the scope is + governed at all: + + - drift in the scope: the check fails when a resource has unauthorized or missing access (missing access only + lists the resource for review when IncludeMissingAccess is $false) and lists the drifted resources; + - no drift, and governed resources in the scope: the check passes; + - no drift, and no governed resource in the scope (or the catalogs cannot be read): the check is skipped. + + Writes the result with Add-MtTestResultDetail and returns $true, $false, or $null when the check is skipped. + + .EXAMPLE + Test-MtAccessPackageDrift -Scope RoleAssignableGroup + + Checks the drift of governed role-assignable groups. + #> + [CmdletBinding()] + [OutputType([bool])] + param( + # The governed resources to check: groups that are not role-assignable, role-assignable groups, or enterprise applications. + [Parameter(Mandatory)] + [ValidateSet('Group', 'RoleAssignableGroup', 'Application')] + [string] $Scope, + + # Also fail when an access package assignment is missing its expected group membership or app role assignment. + # Set to $false to fail on unauthorized access only and list missing access for review. + [bool] $IncludeMissingAccess = $true, + + # Object IDs of governed groups or applications whose drift is ignored. + [string[]] $ExcludedResourceId, + + # Maximum number of resources listed in the result; the others are counted. + [ValidateRange(1, 1000)] + [int] $MaxResources = 50 + ) + + $scopeInfo = switch ($Scope) { + 'Group' { + @{ DriftType = 'group'; OriginSystem = 'AadGroup'; Kind = 'group that is not role-assignable'; Singular = 'governed group'; Plural = 'governed groups'; Heading = 'πŸ‘₯ Groups'; Column = 'Group' + Access = 'members'; Note = 'Role-assignable groups are checked by MT.1256.' } + } + 'RoleAssignableGroup' { + @{ DriftType = 'group'; OriginSystem = 'AadGroup'; Kind = 'role-assignable group'; Singular = 'governed role-assignable group'; Plural = 'governed role-assignable groups'; Heading = '🚨 Role-assignable groups'; Column = 'Group' + Access = 'members'; Note = 'Members of role-assignable groups can be assigned Microsoft Entra roles, so access that bypasses the access package is privileged access.' } + } + 'Application' { + @{ DriftType = 'application'; OriginSystem = 'AadApplication'; Kind = 'enterprise application'; Singular = 'governed application'; Plural = 'governed applications'; Heading = '🧩 Applications'; Column = 'Application' + Access = 'app role assignments'; Note = $null } + } + } + $pluralize = { + param([int] $Count, [string] $Singular, [string] $Plural) + "$Count $(if ($Count -eq 1) { $Singular } else { $Plural })" + } + $excluded = [System.Collections.Generic.HashSet[string]]::new([string[]]@($ExcludedResourceId | Where-Object { $_ }), [System.StringComparer]::OrdinalIgnoreCase) + + # The drift report lists only resources with drift; $expand=details adds up to five drift records each. The + # request is the same for the group checks, so the second one is answered from the cache. + $summaries = [System.Collections.Generic.List[object]]::new() + try { + $driftSplat = @{ + ApiVersion = 'beta' + RelativeUri = 'identityGovernance/insights/accessDriftSummary' + Filter = "resource/type eq '$($scopeInfo.DriftType)' and driftSource eq 'entra'" + QueryParameters = @{ '$expand' = 'details'; '$top' = '100' } + ErrorAction = 'Stop' + } + foreach ($summary in @(Invoke-MtGraphRequest @driftSplat)) { + if ($null -ne $summary -and $summary.resource.identifier -and -not $excluded.Contains("$($summary.resource.identifier)")) { + $summaries.Add($summary) + } + } + } catch { + $statusCode = if ($_.Exception.Response) { [int]$_.Exception.Response.StatusCode } else { 0 } + if ($statusCode -in @(401, 403)) { + Add-MtTestResultDetail -SkippedBecause NotAuthorized + return $null + } + if ($statusCode -in @(400, 404)) { + Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "The access package drift report could not be read from Microsoft Graph ($statusCode). The report is in preview and may not be available in this tenant yet." + return $null + } + throw + } + + # The governed resources of the scope: the groups or applications that are resources of an entitlement + # management catalog. They tell a resource without drift from a scope with nothing to check. + $governedIds = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) + $catalogError = $null + try { + $catalogs = @(Invoke-MtGraphRequest -RelativeUri 'identityGovernance/entitlementManagement/catalogs' -ApiVersion v1.0 -Select 'id' -ErrorAction Stop) + foreach ($catalog in @($catalogs | Where-Object { $_.id })) { + $catalogResources = @(Invoke-MtGraphRequest -RelativeUri "identityGovernance/entitlementManagement/catalogs/$($catalog.id)/resources" -ApiVersion v1.0 ` + -Select 'id', 'originId', 'originSystem' -ErrorAction Stop) + foreach ($catalogResource in $catalogResources) { + if ($catalogResource.originSystem -eq $scopeInfo.OriginSystem -and $catalogResource.originId -and -not $excluded.Contains("$($catalogResource.originId)")) { + $null = $governedIds.Add("$($catalogResource.originId)") + } + } + } + } catch { + $statusCode = if ($_.Exception.Response) { [int]$_.Exception.Response.StatusCode } else { $null } + $catalogError = "$(if ($statusCode) { "HTTP $($statusCode): " })$(("$($_.Exception.Message)" -split '\r?\n')[0])" + Write-Verbose "Could not read the resources of the entitlement management catalogs: $catalogError" + } + + # Role-assignable groups can hold Microsoft Entra roles: they are checked on their own (MT.1256), so the groups + # of the report and of the catalogs are split by isAssignableToRole. + if ($scopeInfo.DriftType -eq 'group') { + $groupIds = @(@($summaries | ForEach-Object { "$($_.resource.identifier)" }) + @($governedIds) | Where-Object { $_ }) + $groupIds = @([System.Collections.Generic.HashSet[string]]::new([string[]]$groupIds, [System.StringComparer]::OrdinalIgnoreCase)) + $roleAssignableIds = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) + if ($groupIds.Count -gt 0) { + foreach ($groupId in $groupIds) { + $parsedGroupId = [guid]::Empty + if (-not [guid]::TryParse($groupId, [ref]$parsedGroupId)) { + throw "Could not classify governed group '$groupId': the resource identifier is not a group object ID." + } + } + # The Graph helper omits batch 404 responses. Verify missing groups individually before treating them + # as deleted: an incomplete batch response is not evidence that a group cannot hold a role. + try { + $groups = @(Invoke-MtGraphRequest -RelativeUri 'groups' -UniqueId $groupIds -Select 'id', 'isAssignableToRole' -ErrorAction Stop) + } catch { + # A single group is requested without a batch, so a deleted group throws instead of returning an error body. + $statusCode = if ($_.Exception.Response) { [int]$_.Exception.Response.StatusCode } else { $null } + if ($groupIds.Count -ne 1 -or $statusCode -ne 404) { throw } + $groups = @([pscustomobject]@{ error = [pscustomobject]@{ code = 'Request_ResourceNotFound' } }) + } + $errorResponses = @($groups | Where-Object { $_.error }) + $otherErrors = @($errorResponses | Where-Object { "$($_.error.code)" -ne 'Request_ResourceNotFound' }) + if ($otherErrors.Count -gt 0) { + $codes = @($otherErrors | ForEach-Object { "$($_.error.code): $(("$($_.error.message)" -split '\r?\n')[0])" } | Select-Object -Unique) -join '; ' + throw "Could not classify governed groups: Microsoft Graph returned $($otherErrors.Count) error(s) for $($groupIds.Count) groups ($codes)." + } + $resolved = @($groups | Where-Object { -not $_.error }) + if (@($resolved | Where-Object { -not $_.id -or "$($_.id)" -notin $groupIds }).Count -gt 0) { + throw 'Could not classify governed groups: Microsoft Graph returned a group response without a requested group ID.' + } + $missingIds = @($groupIds | Where-Object { $groupId = $_; -not ($resolved | Where-Object { "$($_.id)" -eq $groupId }) }) + $deletedIds = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) + if ($errorResponses.Count -gt 0) { + if ($missingIds.Count -ne $errorResponses.Count) { + throw "Could not classify governed groups: Microsoft Graph returned $($errorResponses.Count) not-found responses for $($missingIds.Count) unresolved of $($groupIds.Count) groups." + } + foreach ($missingId in $missingIds) { $null = $deletedIds.Add($missingId) } + } else { + foreach ($missingId in $missingIds) { + Write-Verbose "The group batch did not return '$missingId'; verifying it with an individual request." + try { + $retriedGroups = @(Invoke-MtGraphRequest -RelativeUri 'groups' -UniqueId $missingId -Select 'id', 'isAssignableToRole' -ErrorAction Stop) + } catch { + $statusCode = if ($_.Exception.Response) { [int]$_.Exception.Response.StatusCode } else { $null } + if ($statusCode -ne 404) { throw } + $null = $deletedIds.Add($missingId) + continue + } + if ($retriedGroups.Count -ne 1 -or "$($retriedGroups[0].id)" -ne $missingId) { + throw "Could not classify governed group '$missingId': the individual request did not return exactly the requested group." + } + $groups += $retriedGroups + } + } + foreach ($deletedId in $deletedIds) { Write-Verbose "Governed group $deletedId no longer exists; it is not role-assignable." } + foreach ($groupId in $groupIds) { + if ($deletedIds.Contains($groupId)) { continue } + $resolvedGroups = @($groups | Where-Object { "$($_.id)" -eq $groupId }) + if ($resolvedGroups.Count -ne 1) { + throw "Could not classify governed group '$groupId': Microsoft Graph did not return the group exactly once." + } + # Microsoft Graph returns null for groups created without the property: they are not role-assignable. + $isAssignableToRole = $resolvedGroups[0].isAssignableToRole + if ($null -ne $isAssignableToRole -and $isAssignableToRole -isnot [bool]) { + throw "Could not classify governed group '$groupId': isAssignableToRole is not a boolean." + } + if ($isAssignableToRole -eq $true) { $null = $roleAssignableIds.Add($groupId) } + } + } + $wantRoleAssignable = $Scope -eq 'RoleAssignableGroup' + $summaries = @($summaries | Where-Object { $roleAssignableIds.Contains("$($_.resource.identifier)") -eq $wantRoleAssignable }) + $governedIds = [System.Collections.Generic.HashSet[string]]::new([string[]]@($governedIds | Where-Object { $roleAssignableIds.Contains($_) -eq $wantRoleAssignable }), [System.StringComparer]::OrdinalIgnoreCase) + } + $drifted = @($summaries) + + if ($drifted.Count -eq 0) { + if ($catalogError) { + Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Access package drift reports no drift for $($scopeInfo.Plural), but the resources of the entitlement management catalogs could not be read ($catalogError), so it is not known whether any of them are governed." + return $null + } + if ($governedIds.Count -eq 0) { + $exclusionText = if ($excluded.Count -gt 0) { ' (after ExcludedResourceId)' } else { '' } + Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "No $($scopeInfo.Kind) is a resource of an entitlement management catalog$exclusionText, so there is no access package drift to check." + return $null + } + Add-MtTestResultDetail -Result "Well done. Access package drift reports no unauthorized or missing access on the $(& $pluralize $governedIds.Count $scopeInfo.Singular $scopeInfo.Plural)." + return $true + } + + # The report has one summary per resource and catalog: list a resource in several catalogs once. Its counts + # are the highest of its catalogs, because the same identities usually drift in each of them. + $resources = @($drifted | Group-Object -Property { "$($_.resource.identifier)" } | ForEach-Object { + $catalogSummaries = @($_.Group | Sort-Object -Property { $_.resource.catalogName }) + [pscustomobject]@{ + Type = $catalogSummaries[0].resource.type + Name = $catalogSummaries[0].resource.displayName + Summaries = $catalogSummaries + Unauthorized = [int]($catalogSummaries | ForEach-Object { [int]$_.driftCounts.unauthorized } | Measure-Object -Maximum).Maximum + Missing = [int]($catalogSummaries | ForEach-Object { [int]$_.driftCounts.missing } | Measure-Object -Maximum).Maximum + } + } | Sort-Object -Property @{ Expression = 'Unauthorized'; Descending = $true }, @{ Expression = 'Name' }) + $unauthorizedCount = [int]($resources | Measure-Object -Property Unauthorized -Sum).Sum + $missingCount = [int]($resources | Measure-Object -Property Missing -Sum).Sum + $testResult = @($resources | Where-Object { $_.Unauthorized -gt 0 -or ($IncludeMissingAccess -and $_.Missing -gt 0) }).Count -eq 0 + + $governedText = if (-not $catalogError -and $governedIds.Count -ge $resources.Count) { " of $($governedIds.Count)" } else { '' } + if ($testResult) { + $testResultMarkdown = "Well done. No $($scopeInfo.Singular) has unauthorized $($scopeInfo.Access)." + # Missing access only passes when IncludeMissingAccess is $false: it is listed for review. + if ($missingCount -gt 0) { + $testResultMarkdown += " $missingCount access package $(if ($missingCount -eq 1) { 'assignment is' } else { 'assignments are' }) missing the expected access on $($resources.Count)$governedText $(if ($resources.Count -eq 1) { $scopeInfo.Singular } else { $scopeInfo.Plural }); review them below." + } + } else { + $testResultMarkdown = "Access package drift reports **$unauthorizedCount** unauthorized and **$missingCount** missing access on $($resources.Count)$governedText $(if ($resources.Count -eq 1) { $scopeInfo.Singular } else { $scopeInfo.Plural })." + if ($unauthorizedCount -gt 0) { + $testResultMarkdown += " Remove $($scopeInfo.Access) that were granted outside an access package, or move them into an access package assignment." + } + if ($IncludeMissingAccess -and $missingCount -gt 0) { + $testResultMarkdown += " Reprocess the access package assignments that are missing their expected access." + } + } + if ($scopeInfo.Note) { $testResultMarkdown += " $($scopeInfo.Note)" } + + # The report is refreshed about once a day; show when its data was created. + $createdTimes = @($drifted | ForEach-Object { + $created = [datetimeoffset]::MinValue + if ($_.createdDateTime -and [datetimeoffset]::TryParse("$($_.createdDateTime)", [cultureinfo]::InvariantCulture, [System.Globalization.DateTimeStyles]::AssumeUniversal, [ref]$created)) { $created } + }) + if ($createdTimes.Count -gt 0) { + $dataAsOf = ($createdTimes | Sort-Object -Descending | Select-Object -First 1).UtcDateTime.ToString('yyyy-MM-dd HH:mm', [cultureinfo]::InvariantCulture) + $testResultMarkdown += "`n`n_Drift data as of $dataAsOf UTC._" + } + if ($catalogError) { + $testResultMarkdown += "`n`n❔ The resources of the entitlement management catalogs could not be read ($($catalogError -replace '\|', '\|')), so only the resources with drift are counted." + } + + # Link every object to its admin portal page: the Affected objects page of the report picks them up + # from these deep links (see powershell/internal/report/affected-objects). + $entraPortal = $__MtSession.AdminPortalUrl.Entra + # The kinds of object in the drift report, mapped to the shared portal link templates. + $sharedLinkTemplates = (Get-MtPortalLinkTemplate).LinkTemplates + $linkTemplates = @{ + group = $sharedLinkTemplates.Groups + application = $sharedLinkTemplates.ServicePrincipals + servicePrincipal = $sharedLinkTemplates.ServicePrincipals + user = $sharedLinkTemplates.Users + catalog = $sharedLinkTemplates.AccessPackageCatalogs + accessPackage = $sharedLinkTemplates.AccessPackages + } + $formatLink = { + param([string] $Kind, [string] $Id, [string] $Name) + $text = Get-MtSafeMarkdown $(if ($Name) { $Name } elseif ($Id) { $Id } else { 'Unknown' }) + $parsedGuid = [guid]::Empty + $isGuid = [guid]::TryParse($Id, [ref]$parsedGuid) + if ($entraPortal -and $isGuid -and $linkTemplates.ContainsKey($Kind)) { + return "[$text]($($linkTemplates[$Kind] -f $Id))" + } + return $text + } + # A catalog of a drifted resource, linked to the drift details of the resource in that catalog + # (Access Guardian > Reports > Access Drift). Falls back to the catalog's own page when no summary id is known. + $formatCatalogDriftLink = { + param($Summary) + if (-not $entraPortal -or -not $Summary.id) { + return "πŸ“š $(& $formatLink 'catalog' $Summary.resource.catalogIdentifier $Summary.resource.catalogName)" + } + # EscapeDataString leaves ( ) ! * ' unencoded; encode them too so they cannot end the markdown link. + $encode = { + param([string] $Value) + [uri]::EscapeDataString($Value) -replace '\(', '%28' -replace '\)', '%29' -replace '!', '%21' -replace '\*', '%2A' -replace "'", '%27' + } + $segments = @( + "summaryId/$(& $encode $Summary.id)" + "resourceId/$(& $encode $Summary.resource.identifier)" + "catalogIdentifier/$(& $encode $Summary.resource.catalogIdentifier)" + "catalogName/$(& $encode $Summary.resource.catalogName)" + "resourceType/$(& $encode $Summary.resource.type)" + "resourceName/$(& $encode $Summary.resource.displayName)" + "driftTotal~/$([int]$Summary.driftCounts.total)" + "driftUnauthorized~/$([int]$Summary.driftCounts.unauthorized)" + "driftMissing~/$([int]$Summary.driftCounts.missing)" + ) + $catalogName = if ($Summary.resource.catalogName) { $Summary.resource.catalogName } elseif ($Summary.resource.catalogIdentifier) { $Summary.resource.catalogIdentifier } else { 'Unknown catalog' } + $title = "View access drift of $($Summary.resource.displayName) in catalog $catalogName" + # The title sits in a quoted link title inside a table cell: drop quotes and backslashes, escape pipes. + $title = $title -replace '["\\]', '' -replace '\r?\n', ' ' -replace '\|', '\|' + return "πŸ“š [$(Get-MtSafeMarkdown $catalogName)]($($entraPortal)#view/Microsoft_Azure_ELMAdmin/ReconReviewAccessDriftBlade.ReactView/$($segments -join '/') `"$title`")" + } + + # The kind and name of each identity in the examples. The drift report documents only user and group, but service + # principals and agent identities appear too, named only by their app ID, so the object type and display name + # are read from the directory in one batch. + $identityKinds = @{} + $identityNames = @{} + $identityIds = @($resources | ForEach-Object { $_.Summaries } | ForEach-Object { $_.details } | Where-Object { $null -ne $_ } | + ForEach-Object { $_.identities } | Where-Object { $null -ne $_ -and $_.identityType -ne 'group' -and $_.identifier } | + ForEach-Object { "$($_.identifier)" } | Where-Object { $parsedIdentityId = [guid]::Empty; [guid]::TryParse($_, [ref]$parsedIdentityId) } | Select-Object -Unique) + if ($identityIds.Count -gt 0) { + try { + foreach ($directoryObject in @(Invoke-MtGraphRequest -RelativeUri 'directoryObjects' -UniqueId $identityIds -Select 'id', 'displayName' -ErrorAction Stop)) { + if (-not $directoryObject.id) { continue } + if ($directoryObject.'@odata.type') { $identityKinds["$($directoryObject.id)"] = "$($directoryObject.'@odata.type')" } + if ($directoryObject.displayName) { $identityNames["$($directoryObject.id)"] = "$($directoryObject.displayName)" } + } + } catch { + Write-Verbose "Could not read the object type of the drifted identities: $($_.Exception.Message)" + } + } + $resolveIdentityKind = { + param($Identity) + $type = if ($identityKinds.ContainsKey("$($Identity.identifier)")) { $identityKinds["$($Identity.identifier)"] } else { "$($Identity.identityType)" } + switch -Regex ($type) { + 'agent' { 'agent'; break } + 'servicePrincipal|application' { 'servicePrincipal'; break } + 'group' { 'group'; break } + default { 'user' } + } + } + # Identities of the examples: users, groups, service principals and agent identities are marked, and a guest + # shows the address it was invited with instead of its user principal name (alias_domain#EXT#@tenant). + $formatIdentity = { + param($Identity) + $kind = & $resolveIdentityKind $Identity + $name = if ($Identity.principalName) { $Identity.principalName } else { $Identity.displayName } + # A service principal or agent identity is named by its app ID in the report: show its display name instead, + # as for any identity the report names only by an ID. + $directoryName = $identityNames["$($Identity.identifier)"] + $parsedName = [guid]::Empty + if ($directoryName -and ($kind -in @('servicePrincipal', 'agent') -or -not $name -or [guid]::TryParse("$name", [ref]$parsedName))) { + $name = $directoryName + } + $guestSuffix = '' + if ($kind -eq 'user' -and "$name" -match '^(?.+)_(?[^_@#]+)#EXT#@') { + $name = "$($Matches.alias)@$($Matches.domain)" + $guestSuffix = ' (guest)' + } + $icon = switch ($kind) { 'group' { 'πŸ‘₯' } 'servicePrincipal' { '🧩' } 'agent' { 'πŸ€–' } default { 'πŸ‘€' } } + $linkKind = switch ($kind) { 'group' { 'group' } 'servicePrincipal' { 'servicePrincipal' } 'agent' { 'servicePrincipal' } default { 'user' } } + "$icon $(& $formatLink $linkKind $Identity.identifier $name)$guestSuffix" + } + # Examples of one resource across its catalogs, grouped by drift type. The report returns up to five drift + # records per summary, so "+N more" points to the drift details for the rest. + $formatExamples = { + param($Resource) + $lines = foreach ($driftType in @('unauthorized', 'missing')) { + $total = if ($driftType -eq 'unauthorized') { $Resource.Unauthorized } else { $Resource.Missing } + if ($total -eq 0) { continue } + $seen = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) + $items = foreach ($detail in @($Resource.Summaries | ForEach-Object { $_.details } | Where-Object { $null -ne $_ -and $_.driftType -eq $driftType })) { + $identities = @($detail.identities | Where-Object { $null -ne $_ -and $seen.Add("$($_.identifier)|$($_.principalName)") } | ForEach-Object { & $formatIdentity $_ }) + if ($identities.Count -eq 0) { continue } + $text = $identities -join ', ' + if ($detail.accessPackage.identifier -or $detail.accessPackage.displayName) { + $text += " (access package: $(& $formatLink 'accessPackage' $detail.accessPackage.identifier $detail.accessPackage.displayName))" + } + $text + } + $label = if ($driftType -eq 'unauthorized') { '🚫 Unauthorized' } else { '⚠️ Missing' } + $more = $total - $seen.Count + "$($label): $(if (@($items).Count -gt 0) { @($items) -join ', ' } else { 'no examples returned' })$(if ($more -gt 0) { " Β· **+$more more**" })" + } + # Table cells cannot hold line breaks, so the drift types are separated by an escaped pipe. + if (@($lines).Count -gt 0) { @($lines) -join ' \| ' } else { 'None returned' } + } + + # Missing access is only a column when a resource has some, or when it fails the check. + $showMissing = $IncludeMissingAccess -or @($resources | Where-Object { $_.Missing -gt 0 }).Count -gt 0 + $testResultMarkdown += "`n`n#### $($scopeInfo.Heading) ($($resources.Count))`n`n" + if ($showMissing) { + $testResultMarkdown += "| $($scopeInfo.Column) | Drift in Catalog(s) | Unauthorized | Missing | Examples |`n| --- | --- | ---: | ---: | --- |`n" + } else { + $testResultMarkdown += "| $($scopeInfo.Column) | Drift in Catalog(s) | Unauthorized | Examples |`n| --- | --- | ---: | --- |`n" + } + foreach ($resource in @($resources | Select-Object -First $MaxResources)) { + $first = $resource.Summaries[0] + $resourceLink = & $formatLink $first.resource.type $first.resource.identifier $first.resource.displayName + # Each catalog of the resource links to the drift details of the resource in that catalog. + # Catalogs are separated by an escaped pipe; counts only when they differ. + $countsDiffer = @($resource.Summaries | ForEach-Object { "$([int]$_.driftCounts.unauthorized)|$([int]$_.driftCounts.missing)" } | Select-Object -Unique).Count -gt 1 + $catalogText = @($resource.Summaries | ForEach-Object { + $line = & $formatCatalogDriftLink $_ + if ($countsDiffer) { + $line += " ($([int]$_.driftCounts.unauthorized) unauthorized$(if ($showMissing) { ", $([int]$_.driftCounts.missing) missing" }))" + } + $line + }) -join ' \| ' + $examplesText = & $formatExamples $resource + if ($showMissing) { + $testResultMarkdown += "| $resourceLink | $catalogText | $($resource.Unauthorized) | $($resource.Missing) | $examplesText |`n" + } else { + $testResultMarkdown += "| $resourceLink | $catalogText | $($resource.Unauthorized) | $examplesText |`n" + } + } + $hiddenCount = $resources.Count - $MaxResources + if ($hiddenCount -gt 0) { + $testResultMarkdown += "`n… and $(& $pluralize $hiddenCount $scopeInfo.Singular $scopeInfo.Plural) with less drift. See all of them in the Microsoft Entra admin center under **ID Governance** > **Access Guardian** > **Reports** > **Access Drift**.`n" + } + + Add-MtTestResultDetail -Result $testResultMarkdown + return $testResult +} diff --git a/powershell/internal/connect/Test-MtContext.ps1 b/powershell/internal/connect/Test-MtContext.ps1 index 898b016e0b..8cdfe9b24d 100644 --- a/powershell/internal/connect/Test-MtContext.ps1 +++ b/powershell/internal/connect/Test-MtContext.ps1 @@ -25,12 +25,17 @@ $message = "Not connected to Microsoft Graph. Please use 'Connect-Maester'. For more information, use 'Get-Help Connect-Maester'." $validContext = $false } else { + # Preview scopes that only the Global cloud offers cannot be granted in a national cloud, so they are not + # required there. A Graph environment Maester does not know, such as a custom one, is treated as national. + $environment = if (-not $context.Environment -or $context.Environment -eq 'Global') { 'Global' } + elseif ($context.Environment -in @('China', 'Germany', 'USGov', 'USGovDoD')) { $context.Environment } + else { 'USGov' } $requiredScopes = if ($context.AuthType -eq 'Delegated') { Get-MtGraphScope -SendMail:$SendMail -SendTeamsMessage:$SendTeamsMessage ` - -IncludePreview:$IncludePreview + -IncludePreview:$IncludePreview -Environment $environment } else { # Do not include Mail.Send for applications. Not compatible with Exchange Online RBAC for Applications - Get-MtGraphScope -SendTeamsMessage:$SendTeamsMessage -IncludePreview:$IncludePreview + Get-MtGraphScope -SendTeamsMessage:$SendTeamsMessage -IncludePreview:$IncludePreview -Environment $environment } $scopeComparison = Compare-MtGraphScope ` -CurrentScopes $context.Scopes ` diff --git a/powershell/internal/connect/Write-MtGraphConsentHelp.ps1 b/powershell/internal/connect/Write-MtGraphConsentHelp.ps1 index a097855559..390df9bba6 100644 --- a/powershell/internal/connect/Write-MtGraphConsentHelp.ps1 +++ b/powershell/internal/connect/Write-MtGraphConsentHelp.ps1 @@ -58,7 +58,9 @@ if ($Privileged) { '-Privileged' } if ($IncludePreview) { '-IncludePreview' } ) -join ' ' - $scopeCommand = "(Get-MtGraphScope $scopeSwitches)".Replace(' )', ')') + # Get-MtGraphScope leaves out the Global-only preview scopes in a national cloud, so it needs the cloud too. + $scopeEnvironmentArg = if ($IncludePreview -and $Environment -and $Environment -ne 'Global') { " -Environment $Environment" } else { '' } + $scopeCommand = "(Get-MtGraphScope $scopeSwitches$scopeEnvironmentArg)".Replace(' )', ')') # Keep the tenant and cloud from the failed connection so consent lands in the right place. $connectionArgs = @( diff --git a/powershell/internal/report/Get-GraphObjectMarkdown.ps1 b/powershell/internal/report/Get-GraphObjectMarkdown.ps1 index 9d3f657c18..af57447fb2 100644 --- a/powershell/internal/report/Get-GraphObjectMarkdown.ps1 +++ b/powershell/internal/report/Get-GraphObjectMarkdown.ps1 @@ -22,8 +22,8 @@ # The type of graph object, this will be used to show the right deeplink to the test results report. # If not specified, the function will try to determine the type based on the object. [Parameter(Mandatory = $false)] - [ValidateSet('AuthenticationMethod', 'AuthorizationPolicy', 'ConditionalAccess', 'ConsentPolicy', - 'Devices', 'Domains', 'Groups', 'IdentityProtection', 'Users', 'UserRole' + [ValidateSet('AccessPackageCatalogs', 'AccessPackages', 'AuthenticationMethod', 'AuthorizationPolicy', 'ConditionalAccess', 'ConsentPolicy', + 'Devices', 'Domains', 'Groups', 'IdentityProtection', 'ServicePrincipals', 'Users', 'UserRole' )] [string] $GraphObjectType, diff --git a/powershell/internal/report/affected-objects/ConvertTo-MtAffectedObjectRecord.ps1 b/powershell/internal/report/affected-objects/ConvertTo-MtAffectedObjectRecord.ps1 index cbe09e7d8a..55640f2cd4 100644 --- a/powershell/internal/report/affected-objects/ConvertTo-MtAffectedObjectRecord.ps1 +++ b/powershell/internal/report/affected-objects/ConvertTo-MtAffectedObjectRecord.ps1 @@ -29,11 +29,14 @@ # GraphObjectType β†’ canonical object type. Must match the type names emitted by # Get-MtAffectedObjectFromMarkdown so records from both sources dedupe correctly. $canonicalType = @{ - ConditionalAccess = 'ConditionalAccessPolicy' - Users = 'User' - UserRole = 'User' - Groups = 'Group' - Devices = 'Device' + AccessPackageCatalogs = 'AccessPackageCatalog' + AccessPackages = 'AccessPackage' + ConditionalAccess = 'ConditionalAccessPolicy' + Users = 'User' + UserRole = 'User' + Groups = 'Group' + Devices = 'Device' + ServicePrincipals = 'ServicePrincipal' } # GraphObjectType whose objects are really another type: the check links to a settings blade @@ -45,7 +48,6 @@ # Kept out of Get-MtPortalLinkTemplate: Get-GraphObjectMarkdown would render these types without a link. # Applications are absent because markdown deep links identify them by appId, not object id. $odataObjectType = @{ - '#microsoft.graph.servicePrincipal' = 'ServicePrincipal' '#microsoft.graph.directoryRole' = 'DirectoryRole' '#microsoft.graph.conditionalAccessPolicy' = 'ConditionalAccessPolicy' } diff --git a/powershell/internal/report/affected-objects/Get-MtAffectedObjectFromMarkdown.ps1 b/powershell/internal/report/affected-objects/Get-MtAffectedObjectFromMarkdown.ps1 index b3178f99dc..796209c3db 100644 --- a/powershell/internal/report/affected-objects/Get-MtAffectedObjectFromMarkdown.ps1 +++ b/powershell/internal/report/affected-objects/Get-MtAffectedObjectFromMarkdown.ps1 @@ -47,6 +47,7 @@ function Get-MtAffectedObjectFromMarkdown { @{ System = 'EntraID'; Type = 'AgentIdentityBlueprintPrincipal'; Regex = "AgentBlueprintDetails\.MenuView/~/\w+/objectId/($guid)" } @{ System = 'Intune'; Type = 'ConfigurationPolicy'; Regex = "Microsoft_Intune_Workflows/PolicySummaryBlade/policyId/($guid)" } @{ System = 'EntraID'; Type = 'AccessPackageCatalog'; Regex = "Microsoft_Azure_ELMAdmin/CatalogBlade/catalogId/($guid)" } + @{ System = 'EntraID'; Type = 'AccessPackageCatalogDrift'; Regex = "ReconReviewAccessDriftBlade\.ReactView/(?:[^/]+/[^/]+/)*?catalogIdentifier/($guid)" } @{ System = 'EntraID'; Type = 'AccessPackage'; Regex = "EntitlementMenuBlade/~/overview/entitlementId/($guid)" } @{ System = 'EntraID'; Type = 'PimAlert'; Regex = "Microsoft_Azure_PIMCommon/AlertDetail/providerId/aadroles/alertId/([^/)\s]+)" } @{ System = 'EntraID'; Type = 'EntraRecommendation'; Regex = "RecommendationDetails\.ReactView/recommendationId/([^/)\s]+)" } diff --git a/powershell/internal/report/affected-objects/Get-MtAffectedObjectTypeDefinition.ps1 b/powershell/internal/report/affected-objects/Get-MtAffectedObjectTypeDefinition.ps1 index 3d21ee002d..d3d3e228f5 100644 --- a/powershell/internal/report/affected-objects/Get-MtAffectedObjectTypeDefinition.ps1 +++ b/powershell/internal/report/affected-objects/Get-MtAffectedObjectTypeDefinition.ps1 @@ -31,6 +31,7 @@ EntraID = @( 'AccessPackage' 'AccessPackageCatalog' + 'AccessPackageCatalogDrift' 'AgentIdentity' 'AgentIdentityBlueprint' 'AgentIdentityBlueprintPrincipal' diff --git a/powershell/internal/report/affected-objects/Get-MtPortalLinkTemplate.ps1 b/powershell/internal/report/affected-objects/Get-MtPortalLinkTemplate.ps1 index 250ff6a6b3..47e9a4ea35 100644 --- a/powershell/internal/report/affected-objects/Get-MtPortalLinkTemplate.ps1 +++ b/powershell/internal/report/affected-objects/Get-MtPortalLinkTemplate.ps1 @@ -9,7 +9,8 @@ RelatedObjects records for the affected objects). Link templates use {0} as the placeholder for the object id. Types without {0} - are tenant-level settings surfaces that have no per-object deep link. + are tenant-level settings surfaces that have no per-object deep link. App registrations are + not listed: their portal blade is addressed by appId, not by object id. #> [CmdletBinding()] [OutputType([hashtable])] @@ -18,25 +19,31 @@ return @{ # GraphObjectType β†’ portal deep-link template ({0} = object id) LinkTemplates = @{ - AuthenticationMethod = "$($__MtSession.AdminPortalUrl.Entra)#view/Microsoft_AAD_IAM/AuthenticationMethodsMenuBlade/~/AdminAuthMethods" - AuthorizationPolicy = "$($__MtSession.AdminPortalUrl.Entra)#view/Microsoft_AAD_UsersAndTenants/UserManagementMenuBlade/~/UserSettings/menuId/UserSettings" - ConditionalAccess = "$($__MtSession.AdminPortalUrl.Entra)#view/Microsoft_AAD_ConditionalAccess/PolicyBlade/policyId/{0}" - ConsentPolicy = "$($__MtSession.AdminPortalUrl.Entra)#view/Microsoft_AAD_IAM/ConsentPoliciesMenuBlade/~/UserSettings" - Devices = "$($__MtSession.AdminPortalUrl.Entra)#view/Microsoft_AAD_Devices/DeviceDetailsMenuBlade/~/Properties/objectId/{0}" - Domains = "$($__MtSession.AdminPortalUrl.Entra)#view/Microsoft_AAD_IAM/DomainsManagementMenuBlade/~/CustomDomainNames" - Groups = "$($__MtSession.AdminPortalUrl.Entra)#view/Microsoft_AAD_IAM/GroupDetailsMenuBlade/~/Overview/groupId/{0}" - IdentityProtection = "$($__MtSession.AdminPortalUrl.Entra)#view/Microsoft_AAD_IAM/IdentityProtectionMenuBlade/~/UsersAtRiskAlerts/fromNav/Identity" - Users = "$($__MtSession.AdminPortalUrl.Entra)#view/Microsoft_AAD_UsersAndTenants/UserProfileMenuBlade/~/overview/userId/{0}" - UserRole = "$($__MtSession.AdminPortalUrl.Entra)#view/Microsoft_AAD_UsersAndTenants/UserProfileMenuBlade/~/AdministrativeRole/userId/{0}" + AccessPackageCatalogs = "$($__MtSession.AdminPortalUrl.Entra)#view/Microsoft_Azure_ELMAdmin/CatalogBlade/catalogId/{0}" + AccessPackages = "$($__MtSession.AdminPortalUrl.Entra)#view/Microsoft_Azure_ELMAdmin/EntitlementMenuBlade/~/overview/entitlementId/{0}" + AuthenticationMethod = "$($__MtSession.AdminPortalUrl.Entra)#view/Microsoft_AAD_IAM/AuthenticationMethodsMenuBlade/~/AdminAuthMethods" + AuthorizationPolicy = "$($__MtSession.AdminPortalUrl.Entra)#view/Microsoft_AAD_UsersAndTenants/UserManagementMenuBlade/~/UserSettings/menuId/UserSettings" + ConditionalAccess = "$($__MtSession.AdminPortalUrl.Entra)#view/Microsoft_AAD_ConditionalAccess/PolicyBlade/policyId/{0}" + ConsentPolicy = "$($__MtSession.AdminPortalUrl.Entra)#view/Microsoft_AAD_IAM/ConsentPoliciesMenuBlade/~/UserSettings" + Devices = "$($__MtSession.AdminPortalUrl.Entra)#view/Microsoft_AAD_Devices/DeviceDetailsMenuBlade/~/Properties/objectId/{0}" + Domains = "$($__MtSession.AdminPortalUrl.Entra)#view/Microsoft_AAD_IAM/DomainsManagementMenuBlade/~/CustomDomainNames" + Groups = "$($__MtSession.AdminPortalUrl.Entra)#view/Microsoft_AAD_IAM/GroupDetailsMenuBlade/~/Overview/groupId/{0}" + IdentityProtection = "$($__MtSession.AdminPortalUrl.Entra)#view/Microsoft_AAD_IAM/IdentityProtectionMenuBlade/~/UsersAtRiskAlerts/fromNav/Identity" + ServicePrincipals = "$($__MtSession.AdminPortalUrl.Entra)#view/Microsoft_AAD_IAM/ManagedAppMenuBlade/~/Overview/objectId/{0}" + Users = "$($__MtSession.AdminPortalUrl.Entra)#view/Microsoft_AAD_UsersAndTenants/UserProfileMenuBlade/~/overview/userId/{0}" + UserRole = "$($__MtSession.AdminPortalUrl.Entra)#view/Microsoft_AAD_UsersAndTenants/UserProfileMenuBlade/~/AdministrativeRole/userId/{0}" } # @odata.type β†’ GraphObjectType (auto-detection when no explicit type is passed) OdataTypeMapping = @{ - '#microsoft.graph.user' = 'Users' - '#microsoft.graph.group' = 'Groups' - '#microsoft.graph.device' = 'Devices' + '#microsoft.graph.accessPackage' = 'AccessPackages' + '#microsoft.graph.accessPackageCatalog' = 'AccessPackageCatalogs' + '#microsoft.graph.device' = 'Devices' + '#microsoft.graph.group' = 'Groups' + '#microsoft.graph.servicePrincipal' = 'ServicePrincipals' + '#microsoft.graph.user' = 'Users' } # GraphObjectType β†’ whether the deep link addresses a single object instance # (types not listed here resolve to a tenant-level settings surface) - InstanceTypes = @('ConditionalAccess', 'Devices', 'Groups', 'Users', 'UserRole') + InstanceTypes = @('AccessPackageCatalogs', 'AccessPackages', 'ConditionalAccess', 'Devices', 'Groups', 'ServicePrincipals', 'Users', 'UserRole') } } diff --git a/powershell/internal/report/affected-objects/README.md b/powershell/internal/report/affected-objects/README.md index 1ef0024cd2..5f66a93f79 100644 --- a/powershell/internal/report/affected-objects/README.md +++ b/powershell/internal/report/affected-objects/README.md @@ -78,16 +78,20 @@ When a test calls `Add-MtTestResultDetail -GraphObjects ...`, the objects are co 1. Explicit `-GraphObjectType` parameter, mapped to a canonical type name (`ConditionalAccess` β†’ `ConditionalAccessPolicy`, `Users`/`UserRole` β†’ `User`, - `Groups` β†’ `Group`, `Devices` β†’ `Device`) so records dedupe against source 2. + `Groups` β†’ `Group`, `Devices` β†’ `Device`, `ServicePrincipals` β†’ `ServicePrincipal`, + `AccessPackages` β†’ `AccessPackage`, `AccessPackageCatalogs` β†’ `AccessPackageCatalog`) + so records dedupe against source 2. 2. `@odata.type` sniffing per object (`#microsoft.graph.user` β†’ `User`, etc.), using the shared mapping in `Get-MtPortalLinkTemplate`, plus object-only mappings for - `servicePrincipal`, `directoryRole` and `conditionalAccessPolicy`. + `directoryRole` and `conditionalAccessPolicy`. 3. Other types are still captured: the raw `@odata.type` becomes the `Type`, and the record is an `Instance` if the object has an id. Unless the type is added to the catalog, the type filter then drops it with a warning (see below). Portal deep links come from the same shared template table (`Get-MtPortalLinkTemplate`), which is environment-aware via `$__MtSession.AdminPortalUrl` (Global/USGov/China clouds). +Checks that build their own links (for example MT.1254 and MT.1255–MT.1257) read the URLs from +that table too, so a blade change is fixed in one place. The records are stored per test in `$__MtSession.TestResultDetail[].RelatedObjects` and flow into the report JSON under `Tests[n].ResultDetail.RelatedObjects`. @@ -111,6 +115,7 @@ pattern acts as a type system: | `AgentBlueprintDetails.MenuView/~/*/objectId/{guid}` | AgentIdentityBlueprintPrincipal | | `Microsoft_Intune_Workflows/PolicySummaryBlade/policyId/{guid}` | ConfigurationPolicy (Intune) | | `Microsoft_Azure_ELMAdmin/CatalogBlade/catalogId/{guid}` | AccessPackageCatalog | +| `ReconReviewAccessDriftBlade.ReactView/.../catalogIdentifier/{guid}` | AccessPackageCatalogDrift | | `EntitlementMenuBlade/~/overview/entitlementId/{guid}` | AccessPackage | | `Microsoft_Azure_PIMCommon/AlertDetail/.../alertId/{id}` | PimAlert | | `RecommendationDetails.ReactView/recommendationId/{id}` | EntraRecommendation | @@ -202,9 +207,9 @@ After the merge, `Select-MtAffectedObjectByType` filters the inventory against t | `ExcludedTypes` | Recognised types that are deliberately not affected objects. Dropped silently. | | Everything else | Systems absent from `KnownTypes` (`MicrosoftGraph`) pass through unchanged β€” their `Type` is a Graph resource path and cannot be enumerated. | -Currently inventoried: `EntraID` β€” AccessPackage, AccessPackageCatalog, AgentIdentity, -AgentIdentityBlueprint, AgentIdentityBlueprintPrincipal, AppRegistration, AuthenticationMethod, AuthorizationPolicy, -ConditionalAccessPolicy, ConsentPolicy, Device, DirectoryRole, Domains, Group, ServicePrincipal, User; +Currently inventoried: `EntraID` β€” AccessPackage, AccessPackageCatalog, AccessPackageCatalogDrift, +AgentIdentity, AgentIdentityBlueprint, AgentIdentityBlueprintPrincipal, AppRegistration, AuthenticationMethod, +AuthorizationPolicy, ConditionalAccessPolicy, ConsentPolicy, Device, DirectoryRole, Domains, Group, ServicePrincipal, User; `DefenderXDR` β€” Device; `ExchangeOnline` β€” SharingPolicy, TransportRule; `Intune` β€” ConfigurationPolicy; `GitHub` β€” GitHubOrganization, GitHubRepository, GitHubResource. diff --git a/powershell/public/connect/Connect-Maester.ps1 b/powershell/public/connect/Connect-Maester.ps1 index 723fa64c30..bd5e6b34a9 100644 --- a/powershell/public/connect/Connect-Maester.ps1 +++ b/powershell/public/connect/Connect-Maester.ps1 @@ -486,7 +486,7 @@ try { $scopes = Get-MtGraphScope -SendMail:$SendMail -SendTeamsMessage:$SendTeamsMessage ` - -Privileged:$Privileged -IncludePreview:$IncludePreview + -Privileged:$Privileged -IncludePreview:$IncludePreview -Environment $Environment $connectParams = @{ Scopes = $scopes diff --git a/powershell/public/connect/Get-MtGraphScope.ps1 b/powershell/public/connect/Get-MtGraphScope.ps1 index 5d2f7fc8c1..9a8f1af658 100644 --- a/powershell/public/connect/Get-MtGraphScope.ps1 +++ b/powershell/public/connect/Get-MtGraphScope.ps1 @@ -31,6 +31,13 @@ Connects to Microsoft Graph with the additional scopes required by preview tests. + .Example + Connect-MgGraph -Environment USGov -Scopes (Get-MtGraphScope -IncludePreview -Environment USGov) + + Connects to Microsoft Graph for US Government with the preview scopes that this cloud offers. Scopes of preview + features that only the worldwide (Global) cloud offers, such as Tenant Governance, are left out: a national cloud + rejects a sign-in that requests a permission it does not publish. + .LINK https://maester.dev/docs/commands/Get-MtGraphScope #> @@ -48,7 +55,12 @@ [switch] $Privileged, # If specified, the cmdlet will include scopes required by preview tests. [Parameter(Mandatory = $false)] - [switch] $IncludePreview + [switch] $IncludePreview, + # The Microsoft Graph cloud the scopes are requested in, as passed to Connect-Maester and Connect-MgGraph. + # Preview scopes of features that only the worldwide cloud offers are included only for Global. + [Parameter(Mandatory = $false)] + [ValidateSet('China', 'Germany', 'Global', 'USGov', 'USGovDoD')] + [string] $Environment = 'Global' ) # Any changes made to these permission scopes should be reflected in the documentation. @@ -102,8 +114,28 @@ 'IdentityRiskyUser.Read.All' ) + # Preview scopes of APIs that Microsoft Graph documents only for the worldwide (Global) service, which GCC also + # uses. National clouds (US Government L4/L5, China) do not offer them, and Connect-MgGraph fails there when it + # requests a permission the cloud does not publish: + # - ConfigurationMonitoring.Read.All: Tenant Configuration Management (configurationMonitors, configurationDrifts) + # - RemoteTenantGroups.Read.All: remoteTenantGroups + # - TenantGovernance-*: governanceRelationships, relatedTenants (not in China; kept together with the feature) + # - CrossTenantInformation.ReadBasic.All: available everywhere, but only used with the Tenant Governance checks + $globalOnlyPreviewScopes = @( + 'ConfigurationMonitoring.Read.All' + 'CrossTenantInformation.ReadBasic.All' + 'RemoteTenantGroups.Read.All' + 'TenantGovernance-RelatedTenant.Read.All' + 'TenantGovernance-Relationship.Read.All' + ) + if ($IncludePreview) { Write-Verbose -Message 'Adding preview scopes.' + if ($Environment -eq 'Global') { + $previewScopes = @($previewScopes + $globalOnlyPreviewScopes) + } else { + Write-Verbose -Message "Leaving out the preview scopes that are only available in the Global cloud ($Environment)." + } $scopes = @($previewScopes + $scopes) } diff --git a/powershell/public/run/Add-MtTestResultDetail.ps1 b/powershell/public/run/Add-MtTestResultDetail.ps1 index 3f4fa78dba..a3529e2e48 100644 --- a/powershell/public/run/Add-MtTestResultDetail.ps1 +++ b/powershell/public/run/Add-MtTestResultDetail.ps1 @@ -58,8 +58,8 @@ [Object[]] $GraphObjects, # The type of graph object, this will be used to show the right deep-link to the test results report. - [ValidateSet('AuthenticationMethod', 'AuthorizationPolicy', 'ConditionalAccess', 'ConsentPolicy', - 'Devices', 'Domains', 'Groups', 'IdentityProtection', 'Users', 'UserRole' + [ValidateSet('AccessPackageCatalogs', 'AccessPackages', 'AuthenticationMethod', 'AuthorizationPolicy', 'ConditionalAccess', 'ConsentPolicy', + 'Devices', 'Domains', 'Groups', 'IdentityProtection', 'ServicePrincipals', 'Users', 'UserRole' )] [string] $GraphObjectType, diff --git a/powershell/tests/fixtures/golden/config-layouts/custom-only/expected.json b/powershell/tests/fixtures/golden/config-layouts/custom-only/expected.json index caa59f333a..d32f05b7fa 100644 --- a/powershell/tests/fixtures/golden/config-layouts/custom-only/expected.json +++ b/powershell/tests/fixtures/golden/config-layouts/custom-only/expected.json @@ -54,6 +54,7 @@ "ConfigSource": "Custom/maester-config.json", "GlobalSettings": { "DataverseEnvironmentUrl": "", + "DelegatedAdminTenants": [], "EmergencyAccessAccounts": [ { "Type": "User", @@ -74,6 +75,7 @@ "ConfigSource": "Custom/maester-config.json", "GlobalSettings": { "DataverseEnvironmentUrl": "", + "DelegatedAdminTenants": [], "EmergencyAccessAccounts": [ { "Type": "User", diff --git a/powershell/tests/fixtures/golden/config-layouts/empty/expected.json b/powershell/tests/fixtures/golden/config-layouts/empty/expected.json index 868e4a8057..ea601989ae 100644 --- a/powershell/tests/fixtures/golden/config-layouts/empty/expected.json +++ b/powershell/tests/fixtures/golden/config-layouts/empty/expected.json @@ -51,6 +51,7 @@ "ConfigSource": "defaults", "GlobalSettings": { "DataverseEnvironmentUrl": "", + "DelegatedAdminTenants": [], "EmergencyAccessAccounts": [], "GitHubOrganization": "" }, @@ -65,6 +66,7 @@ "ConfigSource": "defaults", "GlobalSettings": { "DataverseEnvironmentUrl": "", + "DelegatedAdminTenants": [], "EmergencyAccessAccounts": [], "GitHubOrganization": "" }, diff --git a/powershell/tests/fixtures/golden/config-layouts/root-custom-tenant/expected.json b/powershell/tests/fixtures/golden/config-layouts/root-custom-tenant/expected.json index e805f75524..6f8fba1c29 100644 --- a/powershell/tests/fixtures/golden/config-layouts/root-custom-tenant/expected.json +++ b/powershell/tests/fixtures/golden/config-layouts/root-custom-tenant/expected.json @@ -62,6 +62,7 @@ "ConfigSource": "maester-config.json, Custom/maester-config.json", "GlobalSettings": { "DataverseEnvironmentUrl": "", + "DelegatedAdminTenants": [], "EmergencyAccessAccounts": [ { "Type": "User", @@ -83,6 +84,7 @@ "ConfigSource": "maester-config.json, Custom/maester-config.json, maester-config.11111111-2222-3333-4444-555555555555.json", "GlobalSettings": { "DataverseEnvironmentUrl": "", + "DelegatedAdminTenants": [], "EmergencyAccessAccounts": [ { "Type": "User", diff --git a/powershell/tests/fixtures/golden/config-layouts/tenant-only/expected.json b/powershell/tests/fixtures/golden/config-layouts/tenant-only/expected.json index 96612d070c..169f0e5f18 100644 --- a/powershell/tests/fixtures/golden/config-layouts/tenant-only/expected.json +++ b/powershell/tests/fixtures/golden/config-layouts/tenant-only/expected.json @@ -55,6 +55,7 @@ "ConfigSource": "defaults", "GlobalSettings": { "DataverseEnvironmentUrl": "", + "DelegatedAdminTenants": [], "EmergencyAccessAccounts": [], "GitHubOrganization": "" }, @@ -69,6 +70,7 @@ "ConfigSource": "maester-config.11111111-2222-3333-4444-555555555555.json", "GlobalSettings": { "DataverseEnvironmentUrl": "", + "DelegatedAdminTenants": [], "EmergencyAccessAccounts": [ { "Type": "User", diff --git a/powershell/tests/fixtures/golden/selection.json b/powershell/tests/fixtures/golden/selection.json index 05f976972c..b95b2fe41f 100644 --- a/powershell/tests/fixtures/golden/selection.json +++ b/powershell/tests/fixtures/golden/selection.json @@ -21,7 +21,7 @@ "AD" ] }, - "SelectedCount": 571, + "SelectedCount": 572, "SelectedFamilies": [ "MT.1024", "MT.1059", @@ -532,6 +532,7 @@ "MT.1250", "MT.1251", "MT.1252", + "MT.1253", "ORCA.100", "ORCA.101", "ORCA.102", @@ -760,7 +761,7 @@ "AD" ] }, - "SelectedCount": 527, + "SelectedCount": 528, "SelectedFamilies": [ "MT.1024", "MT.1059", @@ -1227,6 +1228,7 @@ "MT.1250", "MT.1251", "MT.1252", + "MT.1253", "ORCA.100", "ORCA.101", "ORCA.102", @@ -1308,7 +1310,7 @@ "AD" ] }, - "SelectedCount": 587, + "SelectedCount": 588, "SelectedFamilies": [ "MT.1024", "MT.1033", @@ -1837,6 +1839,7 @@ "MT.1250", "MT.1251", "MT.1252", + "MT.1253", "ORCA.100", "ORCA.101", "ORCA.102", @@ -1918,7 +1921,7 @@ "AD" ] }, - "SelectedCount": 588, + "SelectedCount": 594, "SelectedFamilies": [ "MT.1024", "MT.1059", @@ -2445,6 +2448,12 @@ "MT.1250", "MT.1251", "MT.1252", + "MT.1253", + "MT.1254", + "MT.1255", + "MT.1256", + "MT.1257", + "MT.1258", "MT.1260", "ORCA.100", "ORCA.101", @@ -2527,7 +2536,7 @@ "AD" ] }, - "SelectedCount": 618, + "SelectedCount": 624, "SelectedFamilies": [ "MT.1024", "MT.1033", @@ -3086,6 +3095,12 @@ "MT.1250", "MT.1251", "MT.1252", + "MT.1253", + "MT.1254", + "MT.1255", + "MT.1256", + "MT.1257", + "MT.1258", "MT.1260", "ORCA.100", "ORCA.101", @@ -3366,7 +3381,7 @@ "AD" ] }, - "SelectedCount": 527, + "SelectedCount": 528, "SelectedFamilies": [ "MT.1024", "MT.1059", @@ -3833,6 +3848,7 @@ "MT.1250", "MT.1251", "MT.1252", + "MT.1253", "ORCA.100", "ORCA.101", "ORCA.102", @@ -3920,7 +3936,7 @@ "AD" ] }, - "SelectedCount": 574, + "SelectedCount": 580, "SelectedFamilies": [ "MT.1024", "MT.1033", @@ -4435,6 +4451,12 @@ "MT.1250", "MT.1251", "MT.1252", + "MT.1253", + "MT.1254", + "MT.1255", + "MT.1256", + "MT.1257", + "MT.1258", "MT.1260", "ORCA.100", "ORCA.101", diff --git a/powershell/tests/functions/Get-GraphObjectMarkdown.Tests.ps1 b/powershell/tests/functions/Get-GraphObjectMarkdown.Tests.ps1 index 43aab858b5..643da87628 100644 --- a/powershell/tests/functions/Get-GraphObjectMarkdown.Tests.ps1 +++ b/powershell/tests/functions/Get-GraphObjectMarkdown.Tests.ps1 @@ -22,4 +22,22 @@ Get-GraphObjectMarkdown -GraphObjects $policy -GraphObjectType ConditionalAccess | Should -BeLike ' - `[Require MFA`](*PolicyBlade/policyId/00000000-0000-0000-0000-000000000002)*' } + + It 'links a object by its object id' -ForEach @( + @{ Type = 'ServicePrincipals'; Blade = 'ManagedAppMenuBlade/~/Overview/objectId/' } + @{ Type = 'AccessPackages'; Blade = 'EntitlementMenuBlade/~/overview/entitlementId/' } + @{ Type = 'AccessPackageCatalogs'; Blade = 'CatalogBlade/catalogId/' } + ) { + $object = [pscustomobject]@{ id = '00000000-0000-0000-0000-000000000003'; displayName = 'Payroll' } + + Get-GraphObjectMarkdown -GraphObjects $object -GraphObjectType $Type -AsPlainTextLink | + Should -BeLike "``[Payroll``](*$($Blade)00000000-0000-0000-0000-000000000003)" + } + + It 'detects a service principal from its odata type' { + $object = [pscustomobject]@{ '@odata.type' = '#microsoft.graph.servicePrincipal'; id = '00000000-0000-0000-0000-000000000004'; displayName = 'Payroll' } + + Get-GraphObjectMarkdown -GraphObjects $object -AsPlainTextLink | + Should -BeLike '`[Payroll`](*ManagedAppMenuBlade/~/Overview/objectId/00000000-0000-0000-0000-000000000004)' + } } diff --git a/powershell/tests/functions/Get-MtAffectedObject.Tests.ps1 b/powershell/tests/functions/Get-MtAffectedObject.Tests.ps1 index 10403041c2..c7f08634da 100644 --- a/powershell/tests/functions/Get-MtAffectedObject.Tests.ps1 +++ b/powershell/tests/functions/Get-MtAffectedObject.Tests.ps1 @@ -107,6 +107,24 @@ Describe 'Affected objects' { $result.Kept | Should -Be 1 $result.Warnings | Should -Be 0 } + + It 'Should give a record its canonical type and portal link' -ForEach @( + @{ GraphObjectType = 'ServicePrincipals'; Expected = 'ServicePrincipal'; Blade = 'ManagedAppMenuBlade/~/Overview/objectId/' } + @{ GraphObjectType = 'AccessPackages'; Expected = 'AccessPackage'; Blade = 'EntitlementMenuBlade/~/overview/entitlementId/' } + @{ GraphObjectType = 'AccessPackageCatalogs'; Expected = 'AccessPackageCatalog'; Blade = 'CatalogBlade/catalogId/' } + ) { + $record = InModuleScope Maester -Parameters @{ GraphObjectType = $GraphObjectType } { + param($GraphObjectType) + ConvertTo-MtAffectedObjectRecord -GraphObjectType $GraphObjectType -GraphObjects ([PSCustomObject]@{ + id = '44444444-4444-4444-4444-444444444444' + displayName = 'Payroll' + }) + } + + $record.Type | Should -Be $Expected + $record.AnchorKind | Should -Be 'Instance' + $record.PortalLink | Should -BeLike "*$($Blade)44444444-4444-4444-4444-444444444444" + } } Context 'Get-MtAffectedObjectFromMarkdown' { @@ -198,6 +216,20 @@ Describe 'Affected objects' { $affectedObject.DisplayName | Should -Be 'Mailbox Migration Account' } + It 'Should capture the catalog of an access drift link' { + $markdown = '| πŸ“š [Contoso Catalog \| \(Sales\)](https://entra.microsoft.com/#view/Microsoft_Azure_ELMAdmin/ReconReviewAccessDriftBlade.ReactView/summaryId/v1_0000/resourceId/aaaaaaaa-1111-2222-3333-444444444444/catalogIdentifier/bbbbbbbb-1111-2222-3333-444444444444/catalogName/Contoso%20Catalog%20%7C%20%28Sales%29/resourceType/group/resourceName/Sales%20Team/driftTotal~/4/driftUnauthorized~/4/driftMissing~/0 "View access drift") |' + + $affectedObject = InModuleScope Maester -Parameters @{ Markdown = $markdown } { + param($Markdown) + Get-MtAffectedObjectFromMarkdown -Markdown $Markdown -TestId 'MT.1255' + } + + @($affectedObject).Count | Should -Be 1 + $affectedObject.Type | Should -Be 'AccessPackageCatalogDrift' + $affectedObject.Id | Should -Be 'bbbbbbbb-1111-2222-3333-444444444444' + $affectedObject.DisplayName | Should -Be 'Contoso Catalog | (Sales)' + } + It 'Should capture users listed as empty links by their UPN' { $markdown = "| ❌ Fail | [jane@contoso.com]() | 07/14/2026 |`n| ❌ Fail | [not a user]() | 07/14/2026 |" diff --git a/powershell/tests/functions/Get-MtGraphScope.Tests.ps1 b/powershell/tests/functions/Get-MtGraphScope.Tests.ps1 index fac28c2596..7eb307130f 100644 --- a/powershell/tests/functions/Get-MtGraphScope.Tests.ps1 +++ b/powershell/tests/functions/Get-MtGraphScope.Tests.ps1 @@ -86,4 +86,38 @@ Describe 'Get-MtGraphScope' { $roleManagementIndex | Should -BeLessThan $roleManagementAlertIndex $roleManagementAlertIndex | Should -BeLessThan $securityIdentitiesSensorsIndex } + + It 'Includes the Global-only preview scopes with IncludePreview in the Global cloud' { + foreach ($scopes in @((Get-MtGraphScope -IncludePreview), (Get-MtGraphScope -IncludePreview -Environment Global))) { + $scopes | Should -Contain 'ConfigurationMonitoring.Read.All' + $scopes | Should -Contain 'CrossTenantInformation.ReadBasic.All' + $scopes | Should -Contain 'RemoteTenantGroups.Read.All' + $scopes | Should -Contain 'TenantGovernance-RelatedTenant.Read.All' + $scopes | Should -Contain 'TenantGovernance-Relationship.Read.All' + } + } + + It 'Leaves out the Global-only preview scopes in the cloud' -ForEach @( + @{ Environment = 'USGov' } + @{ Environment = 'USGovDoD' } + @{ Environment = 'China' } + @{ Environment = 'Germany' } + ) { + $scopes = Get-MtGraphScope -IncludePreview -Environment $Environment + + $scopes | Should -Contain 'AgentIdentity.Read.All' + $scopes | Should -Contain 'IdentityRiskyUser.Read.All' + $scopes | Should -Not -Contain 'ConfigurationMonitoring.Read.All' + $scopes | Should -Not -Contain 'CrossTenantInformation.ReadBasic.All' + $scopes | Should -Not -Contain 'RemoteTenantGroups.Read.All' + $scopes | Should -Not -Contain 'TenantGovernance-RelatedTenant.Read.All' + $scopes | Should -Not -Contain 'TenantGovernance-Relationship.Read.All' + } + + It 'Never includes the Global-only preview scopes without IncludePreview' { + $scopes = Get-MtGraphScope -Environment Global + + $scopes | Should -Not -Contain 'ConfigurationMonitoring.Read.All' + $scopes | Should -Not -Contain 'TenantGovernance-Relationship.Read.All' + } } diff --git a/powershell/tests/functions/Test-MtAccessPackageDrift.Tests.ps1 b/powershell/tests/functions/Test-MtAccessPackageDrift.Tests.ps1 new file mode 100644 index 0000000000..db72f9d0f2 --- /dev/null +++ b/powershell/tests/functions/Test-MtAccessPackageDrift.Tests.ps1 @@ -0,0 +1,327 @@ +ο»ΏBeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force +} + +Describe 'MT.1255 and MT.1256 complete governed group classification' { + BeforeEach { + InModuleScope Maester { + $script:cleanGroupId = '11111111-1111-1111-1111-111111111111' + $script:driftGroupId = '22222222-2222-2222-2222-222222222222' + $script:groupResponses = @( + @{ id = $script:cleanGroupId; isAssignableToRole = $true } + @{ id = $script:driftGroupId; isAssignableToRole = $true } + ) + $script:driftSummaries = @(@{ + resource = @{ identifier = $script:driftGroupId; type = 'group'; displayName = 'Drifted privileged group'; catalogId = 'catalog-1' } + driftCounts = @{ unauthorized = 1; missing = 0; total = 1 } + details = @() + }) + Mock Invoke-MtGraphRequest { + switch ($RelativeUri) { + 'identityGovernance/insights/accessDriftSummary' { $script:driftSummaries } + 'identityGovernance/entitlementManagement/catalogs' { @{ id = 'catalog-1' } } + 'identityGovernance/entitlementManagement/catalogs/catalog-1/resources' { + @{ originId = $script:cleanGroupId; originSystem = 'AadGroup' } + @{ originId = $script:driftGroupId; originSystem = 'AadGroup' } + } + 'groups' { $script:groupResponses } + default { throw "Unexpected Graph call: $RelativeUri" } + } + } + Mock Add-MtTestResultDetail { } + } + } + + It 'Fails when both privileged groups resolve and one has unauthorized access' { + InModuleScope Maester { + Test-MtAccessPackageDrift -Scope RoleAssignableGroup | Should -BeFalse + } + } + + It 'Passes when governed privileged groups resolve and none has drift' { + InModuleScope Maester { + $script:driftSummaries = @() + Test-MtAccessPackageDrift -Scope RoleAssignableGroup | Should -BeTrue + } + } + + It 'Separates complete mixed ordinary and privileged group responses correctly' { + InModuleScope Maester { + $script:groupResponses[1].isAssignableToRole = $false + Test-MtAccessPackageDrift -Scope RoleAssignableGroup | Should -BeTrue + Test-MtAccessPackageDrift -Scope Group | Should -BeFalse + } + } + + It 'Passes ordinary governed groups when complete classification shows no drift' { + InModuleScope Maester { + $script:driftSummaries = @() + $script:groupResponses[0].isAssignableToRole = $false + $script:groupResponses[1].isAssignableToRole = $false + Test-MtAccessPackageDrift -Scope Group | Should -BeTrue + } + } + + It 'Treats a isAssignableToRole as an ordinary group' -ForEach @( + @{ Response = 'null' }, @{ Response = 'missing' } + ) { + InModuleScope Maester -Parameters @{ Response = $Response } { + param($Response) + if ($Response -eq 'null') { $script:groupResponses[1].isAssignableToRole = $null } + else { $script:groupResponses[1].Remove('isAssignableToRole') } + Test-MtAccessPackageDrift -Scope RoleAssignableGroup | Should -BeTrue + Test-MtAccessPackageDrift -Scope Group | Should -BeFalse + } + } + + It 'Skips an empty governed scope rather than classifying an empty response as success' { + InModuleScope Maester { + $script:driftSummaries = @() + Mock Invoke-MtGraphRequest { @() } -ParameterFilter { $RelativeUri -eq 'identityGovernance/entitlementManagement/catalogs' } + Test-MtAccessPackageDrift -Scope RoleAssignableGroup | Should -BeNullOrEmpty + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { $SkippedBecause -eq 'Custom' } + Should -Invoke Invoke-MtGraphRequest -Times 0 -Exactly -ParameterFilter { $RelativeUri -eq 'groups' } + } + } + + It 'Never passes either scope for a group response' -ForEach @( + @{ Response = 'mixed success and error' }, @{ Response = 'empty' }, + @{ Response = 'missing group' }, @{ Response = 'string classification' }, + @{ Response = 'duplicate group' }, @{ Response = 'unexpected ID' }, + @{ Response = 'error only' }, @{ Response = 'null body' } + ) { + InModuleScope Maester -Parameters @{ Response = $Response } { + param($Response) + switch ($Response) { + 'mixed success and error' { $script:groupResponses = @($script:groupResponses[0], @{ error = @{ code = 'Authorization_RequestDenied' } }) } + 'empty' { $script:groupResponses = @() } + 'missing group' { $script:groupResponses = @($script:groupResponses[0]) } + 'string classification' { $script:groupResponses[1].isAssignableToRole = 'false' } + 'duplicate group' { $script:groupResponses += $script:groupResponses[1] } + 'unexpected ID' { $script:groupResponses[1].id = '33333333-3333-3333-3333-333333333333' } + 'error only' { $script:groupResponses = @(@{ error = @{ code = 'NotFound' } }) } + 'null body' { $script:groupResponses = @($null) } + } + { Test-MtAccessPackageDrift -Scope RoleAssignableGroup } | Should -Throw '*Could not classify governed group*' + { Test-MtAccessPackageDrift -Scope Group } | Should -Throw '*Could not classify governed group*' + Should -Invoke Add-MtTestResultDetail -Times 0 -Exactly + } + } + + It 'Treats a deleted governed group (batch 404) as not role-assignable instead of failing the run' { + InModuleScope Maester { + $script:groupResponses = @($script:groupResponses[0], @{ error = @{ code = 'Request_ResourceNotFound'; message = 'Resource does not exist.' } }) + Test-MtAccessPackageDrift -Scope RoleAssignableGroup | Should -BeTrue + Test-MtAccessPackageDrift -Scope Group | Should -BeFalse + } + } + + It 'Errors when 404 responses do not account for exactly the missing groups' { + InModuleScope Maester { + $script:groupResponses = @( + $script:groupResponses[0] + @{ error = @{ code = 'Request_ResourceNotFound' } } + @{ error = @{ code = 'Request_ResourceNotFound' } } + ) + { Test-MtAccessPackageDrift -Scope RoleAssignableGroup } | Should -Throw '*Could not classify governed groups*' + } + } + + It 'Verifies only the three omitted groups in a batch of 74 and accepts confirmed deletions' { + InModuleScope Maester { + $script:allGroupIds = @(1..74 | ForEach-Object { '00000000-0000-0000-0000-{0:d12}' -f $_ }) + $script:missingGroupIds = @($script:allGroupIds[-3..-1]) + $script:driftSummaries = @() + $script:groupResponses = @($script:allGroupIds | Where-Object { $_ -notin $script:missingGroupIds } | + ForEach-Object { @{ id = $_; isAssignableToRole = $true } }) + Mock Invoke-MtGraphRequest { + $script:allGroupIds | ForEach-Object { @{ originId = $_; originSystem = 'AadGroup' } } + } -ParameterFilter { $RelativeUri -eq 'identityGovernance/entitlementManagement/catalogs/catalog-1/resources' } + Mock Invoke-MtGraphRequest { + throw [Microsoft.PowerShell.Commands.HttpResponseException]::new('Not found', [System.Net.Http.HttpResponseMessage]::new([System.Net.HttpStatusCode]::NotFound)) + } -ParameterFilter { $RelativeUri -eq 'groups' -and @($UniqueId).Count -eq 1 -and $UniqueId[0] -in $script:missingGroupIds } + + Test-MtAccessPackageDrift -Scope RoleAssignableGroup | Should -BeTrue + + Should -Invoke Invoke-MtGraphRequest -Times 1 -Exactly -ParameterFilter { $RelativeUri -eq 'groups' -and @($UniqueId).Count -eq 74 } + Should -Invoke Invoke-MtGraphRequest -Times 3 -Exactly -ParameterFilter { + $RelativeUri -eq 'groups' -and @($UniqueId).Count -eq 1 -and $UniqueId[0] -in $script:missingGroupIds -and -not $DisableCache + } + } + } + + It 'Recovers an omitted privileged group before evaluating the scope' -ForEach @( + @{ Scope = 'RoleAssignableGroup'; Expected = $false } + @{ Scope = 'Group'; Expected = $true } + ) { + InModuleScope Maester -Parameters @{ Scope = $Scope; Expected = $Expected } { + param($Scope, $Expected) + $script:groupResponses = @($script:groupResponses[0]) + $script:groupResponses[0].isAssignableToRole = $false + Mock Invoke-MtGraphRequest { + @{ id = $script:driftGroupId; isAssignableToRole = $true } + } -ParameterFilter { $RelativeUri -eq 'groups' -and @($UniqueId).Count -eq 1 -and $UniqueId[0] -eq $script:driftGroupId } + + Test-MtAccessPackageDrift -Scope $Scope | Should -Be $Expected + + Should -Invoke Invoke-MtGraphRequest -Times 1 -Exactly -ParameterFilter { + $RelativeUri -eq 'groups' -and @($UniqueId).Count -eq 1 -and $UniqueId[0] -eq $script:driftGroupId -and -not $DisableCache + } + } + } + + It 'Does not treat an omitted group as deleted when its individual lookup returns HTTP ' -ForEach @( + @{ Status = 403 }, @{ Status = 503 } + ) { + InModuleScope Maester -Parameters @{ Status = $Status } { + param($Status) + $script:groupResponses = @($script:groupResponses[0]) + Mock Invoke-MtGraphRequest { + throw [Microsoft.PowerShell.Commands.HttpResponseException]::new('Group lookup failed', [System.Net.Http.HttpResponseMessage]::new([System.Net.HttpStatusCode]$Status)) + } -ParameterFilter { $RelativeUri -eq 'groups' -and @($UniqueId).Count -eq 1 } + + { Test-MtAccessPackageDrift -Scope RoleAssignableGroup } | Should -Throw '*Group lookup failed*' + { Test-MtAccessPackageDrift -Scope Group } | Should -Throw '*Group lookup failed*' + Should -Invoke Add-MtTestResultDetail -Times 0 -Exactly + } + } + + It 'Names the Graph error code when a group cannot be read' { + InModuleScope Maester { + $script:groupResponses = @($script:groupResponses[0], @{ error = @{ code = 'Authorization_RequestDenied'; message = 'Insufficient privileges.' } }) + { Test-MtAccessPackageDrift -Scope RoleAssignableGroup } | Should -Throw '*Authorization_RequestDenied: Insufficient privileges.*' + } + } + + It 'Treats a single deleted governed group (unbatched 404) as not role-assignable' { + InModuleScope Maester { + $script:driftSummaries = @() + Mock Invoke-MtGraphRequest { @{ originId = $script:driftGroupId; originSystem = 'AadGroup' } } -ParameterFilter { + $RelativeUri -eq 'identityGovernance/entitlementManagement/catalogs/catalog-1/resources' + } + Mock Invoke-MtGraphRequest { + throw [Microsoft.PowerShell.Commands.HttpResponseException]::new('Not found', [System.Net.Http.HttpResponseMessage]::new([System.Net.HttpStatusCode]::NotFound)) + } -ParameterFilter { $RelativeUri -eq 'groups' } + Test-MtAccessPackageDrift -Scope Group | Should -BeTrue + } + } + + It 'Requests a group once when its ID differs only in case' { + InModuleScope Maester { + $script:driftSummaries[0].resource.identifier = $script:driftGroupId.ToUpperInvariant() + $script:groupResponses[1].isAssignableToRole = $false + Test-MtAccessPackageDrift -Scope Group | Should -BeFalse + Should -Invoke Invoke-MtGraphRequest -Times 1 -Exactly -ParameterFilter { $RelativeUri -eq 'groups' -and @($UniqueId).Count -eq 2 } + } + } + + It 'Does not discard malformed governed group identifiers before classifying' { + InModuleScope Maester { + $script:driftGroupId = 'not-a-guid' + { Test-MtAccessPackageDrift -Scope RoleAssignableGroup } | Should -Throw '*not a group object ID*' + } + } + + It 'Propagates a terminating group lookup error' { + InModuleScope Maester { + Mock Invoke-MtGraphRequest { throw 'Group request failed' } -ParameterFilter { $RelativeUri -eq 'groups' } + { Test-MtAccessPackageDrift -Scope RoleAssignableGroup } | Should -Throw '*Group request failed*' + } + } + + It 'Does not require classification of explicitly excluded resources' { + InModuleScope Maester { + $script:groupResponses = @($script:groupResponses[0]) + Test-MtAccessPackageDrift -Scope RoleAssignableGroup -ExcludedResourceId $script:driftGroupId | Should -BeTrue + Should -Invoke Invoke-MtGraphRequest -Times 1 -Exactly -ParameterFilter { + $RelativeUri -eq 'groups' -and @($UniqueId).Count -eq 1 -and $UniqueId -contains $script:cleanGroupId + } + } + } +} + +Describe 'MT.1257 governed application drift' { + BeforeEach { + InModuleScope Maester { + $script:appId = '44444444-4444-4444-4444-444444444444' + $script:catalogResources = @( + @{ originId = $script:appId; originSystem = 'AadApplication' } + @{ originId = '11111111-1111-1111-1111-111111111111'; originSystem = 'AadGroup' } + ) + $script:driftSummaries = @(@{ + resource = @{ identifier = $script:appId; type = 'application'; displayName = 'Payroll'; catalogId = 'catalog-1' } + driftCounts = @{ unauthorized = 2; missing = 0; total = 2 } + details = @() + }) + Mock Invoke-MtGraphRequest { + switch ($RelativeUri) { + 'identityGovernance/insights/accessDriftSummary' { $script:driftSummaries } + 'identityGovernance/entitlementManagement/catalogs' { @{ id = 'catalog-1' } } + 'identityGovernance/entitlementManagement/catalogs/catalog-1/resources' { $script:catalogResources } + default { throw "Unexpected Graph call: $RelativeUri" } + } + } + Mock Add-MtTestResultDetail { } + } + } + + It 'Fails on unauthorized app role assignments and requests only application drift' { + InModuleScope Maester { + Test-MtAccessPackageDrift -Scope Application | Should -BeFalse + Should -Invoke Invoke-MtGraphRequest -Times 1 -Exactly -ParameterFilter { + $RelativeUri -eq 'identityGovernance/insights/accessDriftSummary' -and $Filter -like "resource/type eq 'application'*" + } + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { $Result -like '*Payroll*' -and $Result -like '*app role assignments*' } + } + } + + It 'Links the drifted application with the shared service principal template' { + InModuleScope Maester { + $portalUrl = $__MtSession.AdminPortalUrl + try { + $__MtSession.AdminPortalUrl = @{ Entra = 'https://entra.microsoft.com/' } + Test-MtAccessPackageDrift -Scope Application | Should -BeFalse + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { + $Result.Contains("[Payroll]($((Get-MtPortalLinkTemplate).LinkTemplates.ServicePrincipals -f $script:appId))") + } + } finally { + $__MtSession.AdminPortalUrl = $portalUrl + } + } + } + + It 'Passes governed applications without drift' { + InModuleScope Maester { + $script:driftSummaries = @() + Test-MtAccessPackageDrift -Scope Application | Should -BeTrue + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { $Result -like 'Well done.*1 governed application.' } + } + } + + It 'Skips when no application is a resource of a catalog' { + InModuleScope Maester { + $script:driftSummaries = @() + $script:catalogResources = @($script:catalogResources[1]) + Test-MtAccessPackageDrift -Scope Application | Should -BeNullOrEmpty + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { $SkippedBecause -eq 'Custom' -and $SkippedCustomReason -like '*enterprise application*' } + } + } + + It 'Fails missing app role assignments only while IncludeMissingAccess is set' { + InModuleScope Maester { + $script:driftSummaries[0].driftCounts = @{ unauthorized = 0; missing = 1; total = 1 } + Test-MtAccessPackageDrift -Scope Application | Should -BeFalse + Test-MtAccessPackageDrift -Scope Application -IncludeMissingAccess $false | Should -BeTrue + } + } + + It 'Is run by MT.1257 with its parameters' { + InModuleScope Maester { + Mock Test-MtAccessPackageDrift { $true } + Test-MtAccessPackageDriftApplication -IncludeMissingAccess $false -ExcludedResourceId $script:appId -MaxResources 5 | Should -BeTrue + Should -Invoke Test-MtAccessPackageDrift -Times 1 -Exactly -ParameterFilter { + $Scope -eq 'Application' -and -not $IncludeMissingAccess -and $ExcludedResourceId -contains $script:appId -and $MaxResources -eq 5 + } + } + } +} diff --git a/powershell/tests/functions/Test-MtCaRequirePasswordChangeForHighUserRisk.Tests.ps1 b/powershell/tests/functions/Test-MtCaRequirePasswordChangeForHighUserRisk.Tests.ps1 new file mode 100644 index 0000000000..ebff4520ed --- /dev/null +++ b/powershell/tests/functions/Test-MtCaRequirePasswordChangeForHighUserRisk.Tests.ps1 @@ -0,0 +1,80 @@ +BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force +} + +Describe 'MT.1013 password change for high user risk' { + BeforeEach { + InModuleScope Maester { + $script:passwordPolicy = @{ + id = 'policy-pw'; displayName = 'Password change'; state = 'enabled' + grantControls = @{ builtInControls = @('passwordChange') } + conditions = @{ + users = @{ includeUsers = @('All'); excludeUsers = @(); excludeGroups = @(); excludeRoles = @() } + applications = @{ includeApplications = @('All') } + userRiskLevels = @('high') + } + } + $script:riskPolicy = @{ + id = 'policy-rr'; displayName = 'Risk remediation'; state = 'enabled' + grantControls = @{ builtInControls = @('riskRemediation') } + conditions = @{ + users = @{ includeUsers = @('All'); excludeUsers = @(); excludeGroups = @(); excludeRoles = @() } + applications = @{ includeApplications = @('All') } + userRiskLevels = @('high') + } + } + $script:policies = @($script:passwordPolicy) + Mock Get-MtConditionalAccessPolicy { $script:policies } + Mock Get-MtEmergencyAccessAccount { @() } + Mock Add-MtTestResultDetail { } + } + } + + It 'Is skipped with a reason that names MT.1253 when a risk remediation policy meets MT.1253' { + InModuleScope Maester { + $script:policies = @($script:riskPolicy) + Test-MtCaRequirePasswordChangeForHighUserRisk | Should -BeNullOrEmpty + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { + $SkippedBecause -eq 'Custom' -and $SkippedCustomReason -like "MT.1253 is met: 'Risk remediation' requires risk remediation*" + } + } + } + + It 'Passes with a password change policy when no risk remediation policy exists' { + InModuleScope Maester { + Test-MtCaRequirePasswordChangeForHighUserRisk | Should -BeTrue + Should -Invoke Add-MtTestResultDetail -Times 0 -ParameterFilter { $SkippedBecause } + } + } + + It 'Is not skipped when the risk remediation policy does not meet MT.1253 ()' -ForEach @( + @{ Case = 'report-only'; Change = { param($p) $p.state = 'enabledForReportingButNotEnforced' } } + @{ Case = 'user exclusion'; Change = { param($p) $p.conditions.users.excludeUsers = @('11111111-1111-1111-1111-111111111111') } } + @{ Case = 'medium risk only'; Change = { param($p) $p.conditions.userRiskLevels = @('medium') } } + ) { + InModuleScope Maester -Parameters @{ Change = $Change } { + param($Change) + & $Change $script:riskPolicy + $script:policies = @($script:passwordPolicy, $script:riskPolicy) + Test-MtCaRequirePasswordChangeForHighUserRisk | Should -BeTrue + Should -Invoke Add-MtTestResultDetail -Times 0 -ParameterFilter { $SkippedBecause } + } + } + + It 'Fails without a password change policy when the risk remediation policy does not meet MT.1253' { + InModuleScope Maester { + $script:riskPolicy.conditions.applications.includeApplications = @('00000002-0000-0ff1-ce00-000000000000') + $script:policies = @($script:riskPolicy) + Test-MtCaRequirePasswordChangeForHighUserRisk | Should -BeFalse + } + } + + It 'Runs the password change check when the MT.1253 evaluation fails' { + InModuleScope Maester { + $script:policies = @($script:passwordPolicy, $script:riskPolicy) + Mock Get-MtEmergencyAccessAccount { throw 'Emergency access account could not be resolved' } + Test-MtCaRequirePasswordChangeForHighUserRisk | Should -BeTrue + Should -Invoke Add-MtTestResultDetail -Times 0 -ParameterFilter { $SkippedBecause } + } + } +} diff --git a/powershell/tests/functions/Test-MtCaRequireRiskRemediationForHighUserRisk.Tests.ps1 b/powershell/tests/functions/Test-MtCaRequireRiskRemediationForHighUserRisk.Tests.ps1 new file mode 100644 index 0000000000..c1f62a532f --- /dev/null +++ b/powershell/tests/functions/Test-MtCaRequireRiskRemediationForHighUserRisk.Tests.ps1 @@ -0,0 +1,164 @@ +ο»ΏBeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force +} + +Describe 'MT.1253 risk remediation policy coverage' { + BeforeEach { + InModuleScope Maester { + $script:riskPolicy = @{ + id = 'policy-1'; displayName = 'Risk remediation'; state = 'enabled' + grantControls = @{ builtInControls = @('riskRemediation') } + conditions = @{ + users = @{ includeUsers = @('All'); excludeUsers = @(); excludeGroups = @(); excludeRoles = @() } + applications = @{ includeApplications = @('All') } + userRiskLevels = @('high') + } + } + Mock Get-MtConditionalAccessPolicy { $script:riskPolicy } + Mock Get-MtEmergencyAccessAccount { @() } + Mock Invoke-MtGraphRequest { throw 'Unexpected Graph call in offline test' } + Mock Get-GraphObjectMarkdown { 'Risk remediation policy' } + Mock Add-MtTestResultDetail { } + } + } + + It 'Passes an enabled all-user all-resource high-risk remediation policy' { + InModuleScope Maester { + Test-MtCaRequireRiskRemediationForHighUserRisk | Should -BeTrue + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { $Result -like 'Well done.*' } + } + } + + It 'Rejects an arbitrary exclusion even though All users is included' -ForEach @( + @{ Field = 'excludeUsers' }, @{ Field = 'excludeGroups' }, @{ Field = 'excludeRoles' } + ) { + InModuleScope Maester -Parameters @{ Field = $Field } { + param($Field) + $script:riskPolicy.conditions.users[$Field] = @('11111111-1111-1111-1111-111111111111') + Test-MtCaRequireRiskRemediationForHighUserRisk | Should -BeFalse + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { $Result -like '*Only approved user exclusions*' } + } + } + + It 'Accepts configured emergency users and dedicated groups together with guest selectors' { + InModuleScope Maester { + Mock Get-MtEmergencyAccessAccount { + @{ ObjectId = 'bg-user'; Type = 'user' } + @{ ObjectId = 'bg-group'; Type = 'group' } + } + $script:riskPolicy.conditions.users.excludeUsers = @('bg-user', 'GuestsOrExternalUsers') + $script:riskPolicy.conditions.users.excludeGroups = @('bg-group') + $script:riskPolicy.conditions.users.excludeGuestsOrExternalUsers = @{ + guestOrExternalUserTypes = 'b2bCollaborationGuest,b2bCollaborationMember' + externalTenants = @{ membershipKind = 'all' } + } + Test-MtCaRequireRiskRemediationForHighUserRisk | Should -BeTrue + } + } + + It 'Does not let an approved emergency exclusion approve an unrelated workforce group' { + InModuleScope Maester { + Mock Get-MtEmergencyAccessAccount { @{ ObjectId = 'bg-user'; Type = 'user' } } + $script:riskPolicy.conditions.users.excludeUsers = @('bg-user') + $script:riskPolicy.conditions.users.excludeGroups = @('workforce') + Test-MtCaRequireRiskRemediationForHighUserRisk | Should -BeFalse + } + } + + It 'Does not approve a group using an emergency user entry with the same ID' { + InModuleScope Maester { + Mock Get-MtEmergencyAccessAccount { @{ ObjectId = 'same-id'; Type = 'user' } } + $script:riskPolicy.conditions.users.excludeGroups = @('same-id') + Test-MtCaRequireRiskRemediationForHighUserRisk | Should -BeFalse + } + } + + It 'Accepts a excluded from every Conditional Access policy when EmergencyAccessAccounts is not set' -ForEach @( + @{ Type = 'user'; Field = 'excludeUsers' }, @{ Type = 'group'; Field = 'excludeGroups' } + ) { + InModuleScope Maester -Parameters @{ Field = $Field } { + param($Field) + $script:riskPolicy.conditions.users[$Field] = @('bg-id') + Mock Get-MtConditionalAccessPolicy { + $script:riskPolicy + @{ id = 'policy-2'; displayName = 'MFA'; state = 'enabled'; conditions = @{ users = @{ includeUsers = @('All'); $Field = @('bg-id') } } } + } + Test-MtCaRequireRiskRemediationForHighUserRisk | Should -BeTrue + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { $Result -like '*detected automatically*bg-id*' } + } + } + + It 'Rejects an exclusion that another Conditional Access policy does not share' { + InModuleScope Maester { + $script:riskPolicy.conditions.users.excludeUsers = @('bg-id', 'workforce') + Mock Get-MtConditionalAccessPolicy { + $script:riskPolicy + @{ id = 'policy-2'; displayName = 'MFA'; state = 'enabled'; conditions = @{ users = @{ includeUsers = @('All'); excludeUsers = @('bg-id') } } } + } + Test-MtCaRequireRiskRemediationForHighUserRisk | Should -BeFalse + } + } + + It 'Does not detect emergency access when EmergencyAccessAccounts is set' { + InModuleScope Maester { + Mock Get-MtEmergencyAccessAccount { @{ ObjectId = 'configured'; Type = 'user' } } + $script:riskPolicy.conditions.users.excludeUsers = @('bg-id') + Mock Get-MtConditionalAccessPolicy { + $script:riskPolicy + @{ id = 'policy-2'; displayName = 'MFA'; state = 'enabled'; conditions = @{ users = @{ includeUsers = @('All'); excludeUsers = @('bg-id') } } } + } + Test-MtCaRequireRiskRemediationForHighUserRisk | Should -BeFalse + } + } + + It 'Propagates emergency account resolution errors instead of passing' { + InModuleScope Maester { + Mock Get-MtEmergencyAccessAccount { throw 'Could not resolve configured emergency access object(s)' } + { Test-MtCaRequireRiskRemediationForHighUserRisk } | Should -Throw '*Could not resolve*' + } + } + + It 'Rejects a policy that is ' -ForEach @( + @{ Condition = 'report-only' }, @{ Condition = 'limited to a group' }, + @{ Condition = 'limited to an application' }, @{ Condition = 'missing high risk' }, + @{ Condition = 'password-change only' } + ) { + InModuleScope Maester -Parameters @{ Condition = $Condition } { + param($Condition) + switch ($Condition) { + 'report-only' { $script:riskPolicy.state = 'enabledForReportingButNotEnforced' } + 'limited to a group' { $script:riskPolicy.conditions.users.includeUsers = @(); $script:riskPolicy.conditions.users.includeGroups = @('group') } + 'limited to an application' { $script:riskPolicy.conditions.applications.includeApplications = @('app') } + 'missing high risk' { $script:riskPolicy.conditions.userRiskLevels = @('medium') } + 'password-change only' { $script:riskPolicy.grantControls.builtInControls = @('passwordChange') } + } + Test-MtCaRequireRiskRemediationForHighUserRisk | Should -BeFalse + } + } + + It 'Requires all risk levels selected by the parameter' { + InModuleScope Maester { + Test-MtCaRequireRiskRemediationForHighUserRisk -MinimumUserRiskLevel medium | Should -BeFalse + $script:riskPolicy.conditions.userRiskLevels = @('medium', 'high') + Test-MtCaRequireRiskRemediationForHighUserRisk -MinimumUserRiskLevel medium | Should -BeTrue + } + } + + It 'Passes if a second policy qualifies, without accepting the excluded workforce policy' { + InModuleScope Maester { + Mock Get-MtConditionalAccessPolicy { + $script:riskPolicy + $other = $script:riskPolicy.Clone() + $other.id = 'policy-2' + $other.conditions = @{ + users = @{ includeUsers = @('All'); excludeGroups = @('workforce') } + applications = @{ includeApplications = @('All') } + userRiskLevels = @('high') + } + $other + } + Test-MtCaRequireRiskRemediationForHighUserRisk | Should -BeTrue + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { $Result -like '*Only approved user exclusions*' } + } + } +} diff --git a/powershell/tests/functions/Test-MtContext.Tests.ps1 b/powershell/tests/functions/Test-MtContext.Tests.ps1 index 1b235ff55e..62e5011457 100644 --- a/powershell/tests/functions/Test-MtContext.Tests.ps1 +++ b/powershell/tests/functions/Test-MtContext.Tests.ps1 @@ -54,4 +54,25 @@ Describe 'Test-MtContext β€” Microsoft Graph scopes' { Should -Invoke Get-MtGraphScope -ModuleName Maester -Times 1 -Exactly ` -ParameterFilter { $IncludePreview } } + + It 'Requires the scopes of the cloud when connected to ' -ForEach @( + @{ Environment = 'USGov'; Expected = 'USGov' } + @{ Environment = 'USGovDoD'; Expected = 'USGovDoD' } + @{ Environment = 'China'; Expected = 'China' } + @{ Environment = 'Global'; Expected = 'Global' } + @{ Environment = $null; Expected = 'Global' } + @{ Environment = 'CustomCloud'; Expected = 'USGov' } + ) { + Mock Get-MgContext { + [PSCustomObject]@{ AuthType = 'Delegated'; Scopes = @('Directory.Read.All'); Environment = $Environment } + } -ModuleName Maester + Mock Get-MtGraphScope { @('Directory.Read.All') } -ModuleName Maester + + InModuleScope Maester { + Test-MtContext -IncludePreview | Should -BeTrue + } + + Should -Invoke Get-MtGraphScope -ModuleName Maester -Times 1 -Exactly ` + -ParameterFilter { $IncludePreview -and $Environment -eq $Expected } + } } diff --git a/powershell/tests/functions/Test-MtCrossTenantAdministrationRelationship.Tests.ps1 b/powershell/tests/functions/Test-MtCrossTenantAdministrationRelationship.Tests.ps1 new file mode 100644 index 0000000000..3b5c26d524 --- /dev/null +++ b/powershell/tests/functions/Test-MtCrossTenantAdministrationRelationship.Tests.ps1 @@ -0,0 +1,376 @@ +ο»ΏBeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force +} + +Describe 'MT.1258 GDAP and Tenant Governance assessment with optional enrichment' { + BeforeEach { + InModuleScope Maester { + $script:ownTenantId = '11111111-1111-1111-1111-111111111111' + $script:adminTenantId = '22222222-2222-2222-2222-222222222222' + $script:failedSources = @() + $script:governanceRelationships = @() + $script:remoteGroups = @() + $script:roleAssignments = @() + $script:partners = @() + $script:serviceProviders = @() + $script:skus = @() + $script:relatedTenants = @() + $script:auditEvents = @() + Mock Get-MtSetting { @() } + Mock Get-MgContext { [pscustomobject]@{ Environment = 'Global' } } + Mock Add-MtTestResultDetail { } + Mock Invoke-MtGraphRequest { + if ($RelativeUri -in $script:failedSources) { throw "Source unavailable: $RelativeUri" } + switch ($RelativeUri) { + 'organization' { @{ id = $script:ownTenantId } } + 'directory/tenantGovernance/governanceRelationships' { $script:governanceRelationships } + 'directory/remoteTenantGroups' { $script:remoteGroups } + 'directory/partners' { $script:partners } + 'policies/crossTenantAccessPolicy/partners' { $script:serviceProviders } + 'subscribedSkus' { $script:skus } + 'directory/tenantGovernance/relatedTenants' { $script:relatedTenants } + 'roleManagement/directory/roleAssignments' { $script:roleAssignments } + # Requested with -DisablePaging, which returns the raw response with the events in .value. + 'auditLogs/directoryAudits' { [pscustomobject]@{ value = @($script:auditEvents) } } + 'roleManagement/directory/roleDefinitions' { + @{ id = 'role-1'; displayName = 'Global Administrator'; isPrivileged = $true } + } + default { @() } + } + } + } + } + + It 'Passes when every source is readable and no tenant has access' { + InModuleScope Maester { + Test-MtCrossTenantAdministrationRelationship | Should -BeTrue + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { -not $Investigate -and $Result -like 'Well done.*' } + } + } + + It 'Investigates remote tenant groups failure even when all other sources are empty' { + InModuleScope Maester { + $script:failedSources = @('directory/remoteTenantGroups') + Test-MtCrossTenantAdministrationRelationship | Should -BeTrue + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { + $Investigate -and $Result -like '*remote tenant groups could not be read*' + } + } + } + + It 'Investigates rather than passes when an unclassified role holder lacks principalOrganizationId' { + InModuleScope Maester { + $script:failedSources = @('directory/remoteTenantGroups') + $script:roleAssignments = @(@{ principalId = 'remote-group'; roleDefinitionId = 'role-1'; directoryScopeId = '/' }) + Test-MtCrossTenantAdministrationRelationship | Should -BeTrue + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { $Investigate } + } + } + + It 'Assesses a GDAP partner through remote groups without requiring a service provider mark or role assignment' { + InModuleScope Maester { + $script:remoteGroups = @(@{ id = 'remote-group'; remoteGroupId = 'partner-group'; remoteTenantId = $script:adminTenantId; displayName = 'Partner admins' }) + Test-MtCrossTenantAdministrationRelationship | Should -BeFalse + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { -not $Investigate -and $Result -like '*Not allowlisted*' } + } + } + + It 'Does not assess an unrelated foreign role holder even when marked as a service provider' { + InModuleScope Maester { + $script:roleAssignments = @(@{ principalId = 'remote-group'; principalOrganizationId = $script:adminTenantId; roleDefinitionId = 'role-1'; directoryScopeId = '/' }) + $script:serviceProviders = @(@{ tenantId = $script:adminTenantId; isServiceProvider = $true }) + Test-MtCrossTenantAdministrationRelationship | Should -BeTrue + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { + -not $Investigate -and $Result -like '*Service providers in cross-tenant access settings*' -and $Result -notlike '*Not allowlisted*' + } + } + } + + It 'Passes an allowlisted GDAP partner only when assessment sources are readable' { + InModuleScope Maester { + Mock Get-MtSetting { @($script:adminTenantId) } -ParameterFilter { $Name -eq 'DelegatedAdminTenants' } + $script:remoteGroups = @(@{ id = 'remote-group'; remoteTenantId = $script:adminTenantId }) + Test-MtCrossTenantAdministrationRelationship | Should -BeTrue + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { -not $Investigate } + $script:failedSources = @('directory/remoteTenantGroups') + Test-MtCrossTenantAdministrationRelationship | Should -BeTrue + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { $Investigate } + } + } + + It 'Matches allowlist entries written with braces or without hyphens' { + InModuleScope Maester { + Mock Get-MtSetting { @('{22222222-2222-2222-2222-222222222222}', '33333333333333333333333333333333') } -ParameterFilter { $Name -eq 'DelegatedAdminTenants' } + $script:remoteGroups = @( + @{ id = 'remote-group-1'; remoteTenantId = $script:adminTenantId } + @{ id = 'remote-group-2'; remoteTenantId = '33333333-3333-3333-3333-333333333333' } + ) + Test-MtCrossTenantAdministrationRelationship | Should -BeTrue + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { -not $Investigate -and $Result -notlike '*Not allowlisted*' } + } + } + + It 'Preserves known governance failure despite remote group and enrichment failures' { + InModuleScope Maester { + $script:failedSources = @('directory/remoteTenantGroups', 'policies/crossTenantAccessPolicy/partners', 'directory/partners', 'roleManagement/directory/roleAssignments') + $script:governanceRelationships = @(@{ + id = 'relationship-1'; status = 'active'; governedTenantId = $script:ownTenantId + governingTenantId = $script:adminTenantId; governingTenantName = 'Unapproved administrator' + }) + Test-MtCrossTenantAdministrationRelationship | Should -BeFalse + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { -not $Investigate -and $Result -like '*Not allowlisted*' } + } + } + + It 'Errors when both assessment sources fail even when enrichment sources are readable' { + InModuleScope Maester { + $script:failedSources = @('directory/remoteTenantGroups', 'directory/tenantGovernance/governanceRelationships') + { Test-MtCrossTenantAdministrationRelationship } | Should -Throw '*None of the relationship sources could be read*' + } + } + + It 'Does not treat legacy DAP or CSP partner metadata as GDAP even with a service provider mark' { + InModuleScope Maester { + $script:partners = @(@{ partnerTenantId = $script:adminTenantId; companyType = 'resellerPartnerDelegatedAdmin'; roleIds = @('role-1') }) + $script:serviceProviders = @(@{ tenantId = $script:adminTenantId; isServiceProvider = $true }) + Test-MtCrossTenantAdministrationRelationship | Should -BeTrue + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { + -not $Investigate -and $Result -like '*Legacy DAP roles*' -and $Result -like '*Informational only; no GDAP established*' -and $Result -notlike '*Not allowlisted*' + } + } + } + + It 'Keeps a service provider mark informational for a former governing tenant' { + InModuleScope Maester { + $script:governanceRelationships = @(@{ + id = 'old-relationship'; status = 'terminated'; governedTenantId = $script:ownTenantId + governingTenantId = $script:adminTenantId + }) + $script:serviceProviders = @(@{ tenantId = $script:adminTenantId; isServiceProvider = $true }) + $script:partners = @(@{ partnerTenantId = $script:adminTenantId }) + Test-MtCrossTenantAdministrationRelationship | Should -BeTrue + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { + -not $Investigate -and $Result -like '*Former Tenant Governance*' -and $Result -notlike '*Not allowlisted*' + } + } + } + + It 'Fails a governing tenant whose relationship is pending termination' { + InModuleScope Maester { + $script:governanceRelationships = @(@{ + id = 'pending'; status = 'terminationRequestedByGoverningTenant'; governedTenantId = $script:ownTenantId + governingTenantId = $script:adminTenantId; governingTenantName = 'Governing tenant' + }) + Test-MtCrossTenantAdministrationRelationship | Should -BeFalse + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { + -not $Investigate -and $Result -like '*1 through Tenant Governance*' -and $Result -like '*terminationRequestedByGoverningTenant*' + } + } + } + + It 'Does not assess an outbound relationship in which this tenant governs another tenant' { + InModuleScope Maester { + $script:governanceRelationships = @(@{ + id = 'outbound'; status = 'active'; governingTenantId = $script:ownTenantId; governedTenantId = $script:adminTenantId + }) + Test-MtCrossTenantAdministrationRelationship | Should -BeTrue + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { -not $Investigate -and $Result -like 'Well done.*' } + } + } + + It 'Investigates remote groups still exposed for a former governing tenant' { + InModuleScope Maester { + $script:governanceRelationships = @(@{ + id = 'old-relationship'; status = 'terminated'; governedTenantId = $script:ownTenantId + governingTenantId = $script:adminTenantId + }) + $script:remoteGroups = @(@{ id = 'remote-group'; remoteTenantId = $script:adminTenantId }) + Test-MtCrossTenantAdministrationRelationship | Should -BeTrue + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { + $Investigate -and $Result -like '*remote tenant groups are still exposed*' + } + } + } + + It 'Does not count an active governing tenant again as GDAP' { + InModuleScope Maester { + $script:governanceRelationships = @(@{ + id = 'relationship'; status = 'active'; governedTenantId = $script:ownTenantId + governingTenantId = $script:adminTenantId + }) + $script:remoteGroups = @(@{ id = 'remote-group'; remoteTenantId = $script:adminTenantId }) + Test-MtCrossTenantAdministrationRelationship | Should -BeFalse + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { + -not $Investigate -and $Result -like '*1 through Tenant Governance*' -and $Result -notlike '*1 through GDAP*' + } + } + } + + It 'Assesses remote groups of a tenant that this tenant governs as GDAP' { + InModuleScope Maester { + $script:governanceRelationships = @(@{ + id = 'outbound'; status = 'active'; governingTenantId = $script:ownTenantId + governedTenantId = $script:adminTenantId + }) + $script:remoteGroups = @(@{ id = 'remote-group'; remoteTenantId = $script:adminTenantId }) + Test-MtCrossTenantAdministrationRelationship | Should -BeFalse + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { + -not $Investigate -and $Result -like '*1 through GDAP*' + } + } + } + + It 'Does not change the verdict when informational sources fail' { + InModuleScope Maester { + $script:failedSources = @('policies/crossTenantAccessPolicy/partners', 'directory/partners', 'roleManagement/directory/roleAssignments') + Test-MtCrossTenantAdministrationRelationship | Should -BeTrue + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { + -not $Investigate -and $Result -like '*cross-tenant access partners could not be read*' -and + $Result -like '*CSP partner information could not be read*' -and $Result -like '*directory role information could not be read*' + } + } + } + + It 'Skips discovery without a Governance licence but still assesses relationships' { + InModuleScope Maester { + Test-MtCrossTenantAdministrationRelationship | Should -BeTrue + Should -Invoke Invoke-MtGraphRequest -Times 0 -Exactly -ParameterFilter { $RelativeUri -eq 'directory/tenantGovernance/relatedTenants' } + Should -Invoke Invoke-MtGraphRequest -Times 1 -Exactly -ParameterFilter { $RelativeUri -eq 'directory/tenantGovernance/governanceRelationships' } + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { + -not $Investigate -and $Result -like '*discovery was skipped because the tenant has no*' + } + } + } + + It 'Does not request licences or discovery when explicitly disabled' { + InModuleScope Maester { + Test-MtCrossTenantAdministrationRelationship -IncludeTenantDiscovery $false | Should -BeTrue + Should -Invoke Invoke-MtGraphRequest -Times 0 -Exactly -ParameterFilter { + $RelativeUri -in @('subscribedSkus', 'directory/tenantGovernance/relatedTenants') + } + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { + -not $Investigate -and $Result -like '*discovery is disabled by IncludeTenantDiscovery*' + } + } + } + + It 'Reports unknown licensing without treating it as absent or changing the verdict' { + InModuleScope Maester { + $script:failedSources = @('subscribedSkus') + Test-MtCrossTenantAdministrationRelationship | Should -BeTrue + Should -Invoke Invoke-MtGraphRequest -Times 0 -Exactly -ParameterFilter { $RelativeUri -eq 'directory/tenantGovernance/relatedTenants' } + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { + -not $Investigate -and $Result -like '*licensing could not be confirmed*' -and $Result -notlike '*tenant has no Microsoft Entra ID Governance licence*' + } + } + } + + It 'Includes licensed inbound admin-app metrics by default without assessing activity-only tenants' { + InModuleScope Maester { + $script:skus = @(@{ capabilityStatus = 'Enabled'; servicePlans = @(@{ servicePlanId = 'e866a266-3cff-43a3-acca-0c90a7e00c8b' }) }) + $script:relatedTenants = @(@{ + id = $script:adminTenantId + appB2BSignInActivityMetrics = @{ recent = @{ inboundMonthlyTotalUsers = 12; inboundMonthlyTotalApplications = 3 } } + }) + Test-MtCrossTenantAdministrationRelationship | Should -BeTrue + Should -Invoke Invoke-MtGraphRequest -Times 1 -Exactly -ParameterFilter { $RelativeUri -eq 'directory/tenantGovernance/relatedTenants' } + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { + -not $Investigate -and $Result -like '*12 users*3 admin apps*' -and $Result -like '*Related tenants with inbound admin app sign-ins (information only)*' -and $Result -notlike '*Not allowlisted*' + } + } + } + + It 'Shows inbound metrics for allowlisted GDAP partners as information' { + InModuleScope Maester { + Mock Get-MtSetting { @($script:adminTenantId) } -ParameterFilter { $Name -eq 'DelegatedAdminTenants' } + $script:remoteGroups = @(@{ id = 'remote-group'; remoteTenantId = $script:adminTenantId }) + $script:skus = @(@{ capabilityStatus = 'Enabled'; servicePlans = @(@{ servicePlanId = 'e866a266-3cff-43a3-acca-0c90a7e00c8b' }) }) + $script:relatedTenants = @(@{ + id = $script:adminTenantId + appB2BSignInActivityMetrics = @{ recent = @{ inboundMonthlyTotalUsers = 7; inboundMonthlyTotalApplications = 2 } } + }) + Test-MtCrossTenantAdministrationRelationship | Should -BeTrue + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { + -not $Investigate -and $Result -like '*7 users*2 admin apps*' -and $Result -notlike '*Not allowlisted*' + } + } + } + + It 'Reports discovery failures without changing the assessment' { + InModuleScope Maester { + $script:skus = @(@{ capabilityStatus = 'Enabled'; servicePlans = @(@{ servicePlanId = 'e866a266-3cff-43a3-acca-0c90a7e00c8b' }) }) + $script:failedSources = @('directory/tenantGovernance/relatedTenants') + Test-MtCrossTenantAdministrationRelationship | Should -BeTrue + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { + -not $Investigate -and $Result -like '*related tenants could not be read*' + } + } + } + + It 'Skips outside the worldwide cloud without calling Graph' { + InModuleScope Maester { + Mock Get-MgContext { [pscustomobject]@{ Environment = 'USGov' } } + Test-MtCrossTenantAdministrationRelationship | Should -BeNullOrEmpty + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { $SkippedBecause -eq 'Custom' -and $SkippedCustomReason -like '*USGov*' } + Should -Invoke Invoke-MtGraphRequest -Times 0 -Exactly + } + } + + Context 'First recorded change from the audit log' { + BeforeEach { + InModuleScope Maester { + $script:governanceRelationships = @(@{ + id = 'relationship-1'; status = 'active'; governedTenantId = $script:ownTenantId + governingTenantId = $script:adminTenantId; governingTenantName = 'Governing tenant' + }) + $script:newAuditEvent = { + param([string] $Result, [string] $User, $Date = '2026-10-01T08:00:00Z') + [pscustomobject]@{ + result = $Result; activityDisplayName = 'Update governance relationship'; activityDateTime = $Date + initiatedBy = [pscustomobject]@{ user = [pscustomobject]@{ userPrincipalName = $User } } + } + } + } + } + + It 'Shows the first successful change and skips a failed attempt before it' { + InModuleScope Maester { + $script:auditEvents = @( + (& $script:newAuditEvent 'failure' 'attacker@contoso.com') + (& $script:newAuditEvent 'success' 'admin@contoso.com') + ) + $null = Test-MtCrossTenantAdministrationRelationship + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { + $Result -like '*First recorded change (audit log)*' -and $Result -like '*admin@contoso.com*' -and + $Result -notlike '*attacker@contoso.com*' -and $Result -notlike '*Approved by*' + } + } + } + + It 'Shows a neutral note when the audit log holds no successful change' { + InModuleScope Maester { + $script:auditEvents = @(& $script:newAuditEvent 'failure' 'attacker@contoso.com') + $null = Test-MtCrossTenantAdministrationRelationship + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { + $Result -like '*No successful change found in the audit log*' -and $Result -notlike '*retention)_*' + } + } + } + + It 'Shows an unknown date instead of failing when the event date cannot be read' { + InModuleScope Maester { + $script:auditEvents = @(& $script:newAuditEvent 'success' 'admin@contoso.com' $null) + { $null = Test-MtCrossTenantAdministrationRelationship } | Should -Not -Throw + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { $Result -like '*admin@contoso.com*on an unknown date*' } + } + } + + It 'Shows that the audit log is not available when it cannot be read' { + InModuleScope Maester { + $script:failedSources = @('auditLogs/directoryAudits') + $null = Test-MtCrossTenantAdministrationRelationship + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { $Result -like '*Audit log not available*' } + } + } + } +} diff --git a/powershell/tests/functions/Test-MtEntraTenantConfigurationDrift.Tests.ps1 b/powershell/tests/functions/Test-MtEntraTenantConfigurationDrift.Tests.ps1 new file mode 100644 index 0000000000..fe11b0b027 --- /dev/null +++ b/powershell/tests/functions/Test-MtEntraTenantConfigurationDrift.Tests.ps1 @@ -0,0 +1,233 @@ +BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force +} + +Describe 'MT.1254 Tenant Configuration Management drift' { + BeforeEach { + InModuleScope Maester { + $script:now = (Get-Date).ToUniversalTime() + $script:monitor = [pscustomobject]@{ + id = 'mon-1'; displayName = 'Security baseline'; status = 'active'; inactivationReason = $null + monitorRunFrequencyInHours = 6; mode = 'monitorOnly'; createdDateTime = $script:now.AddDays(-30).ToString('o') + } + $script:instance = [pscustomobject]@{ Id = 'mon-1'; Data = $script:monitor } + $script:drifts = @() + $script:runs = @([pscustomobject]@{ + monitorId = 'mon-1'; runStatus = 'successful'; driftsCount = 0 + runInitiationDateTime = $script:now.AddHours(-2).ToString('o'); runCompletionDateTime = $script:now.AddHours(-2).AddMinutes(3).ToString('o') + }) + $script:runsFail = $false + $script:newDrift = { + param([string] $MonitorId = 'mon-1') + [pscustomobject]@{ + id = [guid]::NewGuid().Guid; monitorId = $MonitorId; status = 'active' + resourceType = 'microsoft.entra.conditionalaccesspolicy'; baselineResourceDisplayName = 'Block legacy authentication' + resourceInstanceIdentifier = [pscustomobject]@{ DisplayName = 'Block legacy authentication'; Id = [guid]::NewGuid().Guid } + firstReportedDateTime = $script:now.AddDays(-3).ToString('o') + driftedProperties = @([pscustomobject]@{ propertyName = 'State'; currentValue = 'disabled'; desiredValue = 'enabled' }) + } + } + Mock Invoke-MtGraphRequest { + switch ($RelativeUri) { + 'admin/configurationManagement/configurationDrifts' { $script:drifts } + 'admin/configurationManagement/configurationMonitoringResults' { + if ($script:runsFail) { throw 'Service unavailable' } + $script:runs + } + default { throw "Unexpected Graph call: $RelativeUri" } + } + } + Mock Add-MtTestResultDetail { } + } + } + + It 'Passes an active monitor that ran on schedule and reports no drift' { + InModuleScope Maester { + Test-MtEntraTenantConfigurationDrift -Instance $script:instance | Should -BeTrue + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { -not $Investigate -and $Result -like 'Well done.*' } + } + } + + It 'Fails on an active drift of the monitor and shows the current and desired value' { + InModuleScope Maester { + $script:drifts = @(& $script:newDrift) + Test-MtEntraTenantConfigurationDrift -Instance $script:instance | Should -BeFalse + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { + -not $Investigate -and $Result -like '*Block legacy authentication*' -and $Result.Contains('| State | `disabled` | `enabled` |') + } + } + } + + It 'Links a drifted Entra object with the shared portal link template' { + InModuleScope Maester { + $portalUrl = $__MtSession.AdminPortalUrl + try { + $__MtSession.AdminPortalUrl = @{ Entra = 'https://entra.microsoft.com/' } + $script:drifts = @(& $script:newDrift) + $script:policyId = $script:drifts[0].resourceInstanceIdentifier.Id + Test-MtEntraTenantConfigurationDrift -Instance $script:instance | Should -BeFalse + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { + $Result.Contains("[Block legacy authentication]($((Get-MtPortalLinkTemplate).LinkTemplates.ConditionalAccess -f $script:policyId))") + } + } finally { + $__MtSession.AdminPortalUrl = $portalUrl + } + } + } + + It 'Ignores the drift of another monitor' { + InModuleScope Maester { + $script:drifts = @(& $script:newDrift -MonitorId 'mon-2') + Test-MtEntraTenantConfigurationDrift -Instance $script:instance | Should -BeTrue + } + } + + It 'Investigates no drift when ' -ForEach @( + @{ Condition = 'the monitor is inactive'; Note = '*inactive and no longer detects drift*' } + @{ Condition = 'the last run failed'; Note = '*did not report success (status: failed)*' } + @{ Condition = 'the last run was partially successful'; Note = '*did not report success (status: partiallySuccessful)*' } + @{ Condition = 'the last run status is unknownFutureValue'; Note = '*did not report success (status: unknownFutureValue)*' } + @{ Condition = 'the last run has no status'; Note = '*did not report success (status: none)*' } + @{ Condition = 'the last run has no start time'; Note = '*has not run as scheduled*' } + @{ Condition = 'the monitor is overdue'; Note = '*has not run as scheduled*' } + @{ Condition = 'the runs cannot be read'; Note = '*runs could not be read*' } + ) { + InModuleScope Maester -Parameters @{ Condition = $Condition; Note = $Note } { + param($Condition, $Note) + switch ($Condition) { + 'the monitor is inactive' { $script:monitor.status = 'inactive'; $script:monitor.inactivationReason = 'Missing permissions' } + 'the last run failed' { $script:runs[0].runStatus = 'failed' } + 'the last run was partially successful' { $script:runs[0].runStatus = 'partiallySuccessful' } + 'the last run status is unknownFutureValue' { $script:runs[0].runStatus = 'unknownFutureValue' } + 'the last run has no status' { $script:runs[0].runStatus = $null } + 'the last run has no start time' { $script:runs[0].runInitiationDateTime = $null } + 'the monitor is overdue' { $script:runs[0].runInitiationDateTime = $script:now.AddHours(-20).ToString('o') } + 'the runs cannot be read' { $script:runsFail = $true } + } + Test-MtEntraTenantConfigurationDrift -Instance $script:instance | Should -BeTrue + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { $Investigate -and $Result -like $Note } + } + } + + It 'Fails rather than investigates when an overdue monitor reports drift' { + InModuleScope Maester { + $script:runs[0].runInitiationDateTime = $script:now.AddHours(-20).ToString('o') + $script:drifts = @(& $script:newDrift) + Test-MtEntraTenantConfigurationDrift -Instance $script:instance | Should -BeFalse + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { -not $Investigate } + } + } + + It 'Waits for the first run of a new monitor instead of calling it overdue' { + InModuleScope Maester { + $script:monitor.createdDateTime = $script:now.AddMinutes(-10).ToString('o') + $script:runs = @() + Test-MtEntraTenantConfigurationDrift -Instance $script:instance | Should -BeTrue + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { + $Investigate -and $Result -like '*has not run yet*' -and $Result -notlike '*has not run as scheduled*' + } + } + } + + It 'Calls a monitor without runs overdue once two run intervals have passed since its creation' { + InModuleScope Maester { + $script:monitor.createdDateTime = $script:now.AddDays(-2).ToString('o') + $script:runs = @() + Test-MtEntraTenantConfigurationDrift -Instance $script:instance | Should -BeTrue + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { $Investigate -and $Result -like '*has not run as scheduled*' } + } + } + + It 'Reads days of runs for a monitor that runs every h' -ForEach @( + @{ Frequency = 6; Days = 7 }, @{ Frequency = 168; Days = 15 } + ) { + InModuleScope Maester -Parameters @{ Frequency = $Frequency; Days = $Days } { + param($Frequency, $Days) + $script:monitor.monitorRunFrequencyInHours = $Frequency + $since = $script:now.Date.AddDays(-$Days).ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", [cultureinfo]::InvariantCulture) + Test-MtEntraTenantConfigurationDrift -Instance $script:instance | Should -BeTrue + Should -Invoke Invoke-MtGraphRequest -Times 1 -Exactly -ParameterFilter { + $RelativeUri -eq 'admin/configurationManagement/configurationMonitoringResults' -and $Filter -eq "runInitiationDateTime ge $since" + } + } + } + + It 'Skips as not authorized when the drifts cannot be read' { + InModuleScope Maester { + Mock Invoke-MtGraphRequest { + throw [Microsoft.PowerShell.Commands.HttpResponseException]::new('Forbidden', [System.Net.Http.HttpResponseMessage]::new([System.Net.HttpStatusCode]::Forbidden)) + } -ParameterFilter { $RelativeUri -eq 'admin/configurationManagement/configurationDrifts' } + Test-MtEntraTenantConfigurationDrift -Instance $script:instance | Should -BeNullOrEmpty + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { $SkippedBecause -eq 'NotAuthorized' } + } + } + + It 'Escapes the inactivation reason' { + InModuleScope Maester { + $script:monitor.status = 'inactive' + $script:monitor.inactivationReason = '[Sign in](https://phish.example)' + Test-MtEntraTenantConfigurationDrift -Instance $script:instance | Should -BeTrue + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { $Result.Contains('Sign in') -and -not $Result.Contains('[Sign in](https://phish.example)') } + } + } +} + +Describe 'MT.1254 monitor instances' { + BeforeEach { + InModuleScope Maester { + $script:monitors = @( + [pscustomobject]@{ id = 'mon-b'; displayName = 'Baseline B' } + [pscustomobject]@{ id = $null; displayName = 'Without ID' } + [pscustomobject]@{ id = 'mon-a'; displayName = 'Baseline A' } + ) + Mock Get-MgContext { [pscustomobject]@{ Environment = 'Global' } } + Mock Invoke-MtGraphRequest { $script:monitors } + Mock Add-MtTestResultDetail { } + } + } + + It 'Returns one instance per monitor, sorted by name, and ignores entries without an ID' { + InModuleScope Maester { + $instances = @(Get-MtTenantConfigurationMonitorInstance) + $instances.Id | Should -Be @('mon-a', 'mon-b') + $instances[0].Title | Should -BeLike "*'Baseline A'*" + } + } + + It 'Returns no instance when the tenant has no monitor' { + InModuleScope Maester { + $script:monitors = @() + Get-MtTenantConfigurationMonitorInstance | Should -BeNullOrEmpty + Should -Invoke Add-MtTestResultDetail -Times 0 -Exactly + } + } + + It 'Skips the family as not authorized on HTTP ' -ForEach @( + @{ Code = 401 }, @{ Code = 403 } + ) { + InModuleScope Maester -Parameters @{ Code = $Code } { + param($Code) + Mock Invoke-MtGraphRequest { + throw [Microsoft.PowerShell.Commands.HttpResponseException]::new('Denied', [System.Net.Http.HttpResponseMessage]::new([System.Net.HttpStatusCode]$Code)) + } + { Get-MtTenantConfigurationMonitorInstance } | Should -Not -Throw + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { $SkippedBecause -eq 'NotAuthorized' } + } + } + + It 'Propagates other errors' { + InModuleScope Maester { + Mock Invoke-MtGraphRequest { throw 'Service unavailable' } + { Get-MtTenantConfigurationMonitorInstance } | Should -Throw '*Service unavailable*' + } + } + + It 'Skips the family outside the worldwide cloud without calling Graph' { + InModuleScope Maester { + Mock Get-MgContext { [pscustomobject]@{ Environment = 'USGov' } } + Get-MtTenantConfigurationMonitorInstance | Should -BeNullOrEmpty + Should -Invoke Add-MtTestResultDetail -Times 1 -Exactly -ParameterFilter { $SkippedBecause -eq 'Custom' -and $SkippedCustomReason -like '*USGov*' } + Should -Invoke Invoke-MtGraphRequest -Times 0 -Exactly + } + } +} diff --git a/powershell/tests/functions/Write-MtGraphConsentHelp.Tests.ps1 b/powershell/tests/functions/Write-MtGraphConsentHelp.Tests.ps1 index 67894c7be9..41a95f00d4 100644 --- a/powershell/tests/functions/Write-MtGraphConsentHelp.Tests.ps1 +++ b/powershell/tests/functions/Write-MtGraphConsentHelp.Tests.ps1 @@ -105,4 +105,28 @@ Describe 'Write-MtGraphConsentHelp' { Should -Invoke Write-Host -ModuleName Maester -Times 0 -Exactly -ParameterFilter { $Object -match 'If you closed the sign-in window' } Should -Invoke Write-Host -ModuleName Maester -Times 1 -Exactly -ParameterFilter { $Object -match '^Ask a Global Administrator' } } + + It 'Passes the cloud to Get-MtGraphScope for preview scopes in a national cloud' { + InModuleScope Maester { + $errorRecord = [System.Management.Automation.ErrorRecord]::new( + [System.Exception]::new('AADSTS65001: consent required'), 'AuthFailed', 'AuthenticationError', $null) + $null = Write-MtGraphConsentHelp -ErrorRecord $errorRecord -Environment USGov -IncludePreview + } + + Should -Invoke Write-Host -ModuleName Maester -Times 1 -Exactly -ParameterFilter { + $Object -match [regex]::Escape('Connect-MgGraph -Scopes (Get-MtGraphScope -IncludePreview -Environment USGov) -Environment USGov') + } + } + + It 'Does not pass the cloud to Get-MtGraphScope without preview scopes' { + InModuleScope Maester { + $errorRecord = [System.Management.Automation.ErrorRecord]::new( + [System.Exception]::new('AADSTS65001: consent required'), 'AuthFailed', 'AuthenticationError', $null) + $null = Write-MtGraphConsentHelp -ErrorRecord $errorRecord -Environment USGov -SendMail + } + + Should -Invoke Write-Host -ModuleName Maester -Times 1 -Exactly -ParameterFilter { + $Object -match [regex]::Escape('Connect-MgGraph -Scopes (Get-MtGraphScope -SendMail) -Environment USGov') + } + } } diff --git a/report/src/lib/affectedObjectTypes.ts b/report/src/lib/affectedObjectTypes.ts index 56182d74f3..a116daf79a 100644 --- a/report/src/lib/affectedObjectTypes.ts +++ b/report/src/lib/affectedObjectTypes.ts @@ -21,6 +21,7 @@ const knownTypes: Record = { DirectoryRole: ["Directory role", "directory-role"], AccessPackage: ["Access package", "identity-governance"], AccessPackageCatalog: ["Access package catalog", "identity-governance"], + AccessPackageCatalogDrift: ["Access package catalog drift", "identity-governance"], SharingPolicy: ["Sharing policy", "exchange"], TransportRule: ["Mail flow rule", "mail-alert"], } diff --git a/tests/maester-config.json b/tests/maester-config.json index 98bd046440..528d21199e 100644 --- a/tests/maester-config.json +++ b/tests/maester-config.json @@ -3,6 +3,7 @@ "ConfigVersion": "", "GlobalSettings": { "EmergencyAccessAccounts": [], + "DelegatedAdminTenants": [], "DataverseEnvironmentUrl": "", "GitHubOrganization": "" }, diff --git a/tests/maester/entra/Test.MT.1013.md b/tests/maester/entra/Test.MT.1013.md index a82cb39cd8..b4b99da4f0 100644 --- a/tests/maester/entra/Test.MT.1013.md +++ b/tests/maester/entra/Test.MT.1013.md @@ -1,5 +1,7 @@ Checks if the tenant has at least one Conditional Access policy requiring password change for high user risk. +This check is skipped when [MT.1253](https://maester.dev/docs/tests/MT.1253) is met: an enabled policy requires **Require risk remediation** for high user risk. Risk remediation replaces **Require password change** and also remediates users who sign in without a password, so a tenant that uses it does not need a password change policy. + See [User risk-based password change - Microsoft Learn](https://learn.microsoft.com/entra/identity/conditional-access/howto-conditional-access-policy-risk-user) -%TestResult% \ No newline at end of file +%TestResult% diff --git a/tests/maester/entra/Test.MT.1013.ps1 b/tests/maester/entra/Test.MT.1013.ps1 index 21fa7fae72..ce63e43017 100644 --- a/tests/maester/entra/Test.MT.1013.ps1 +++ b/tests/maester/entra/Test.MT.1013.ps1 @@ -6,6 +6,9 @@ .Description Password change for high user risk is a good way to prevent compromised accounts from being used to access your tenant. + The check is skipped when MT.1253 is met: an enabled policy that requires risk remediation for high user risk. + Risk remediation replaces password change and also remediates users who sign in without a password. + Learn more: https://learn.microsoft.com/entra/identity/conditional-access/howto-conditional-access-policy-risk-user @@ -35,6 +38,22 @@ [OutputType([bool])] param () + # Require risk remediation (MT.1253) is the higher maturity level of this requirement: when a policy meets it, + # a password change policy is no longer needed. The same evaluation as MT.1253 decides, so the two never disagree. + # If it cannot run (for example an EmergencyAccessAccounts entry that cannot be resolved), this check runs as before. + try { + $riskRemediation = Get-MtCaRiskRemediationPolicyResult -ErrorAction Stop + } catch { + Write-Verbose "Could not evaluate the risk remediation policies of MT.1253: $($_.Exception.Message)" + $riskRemediation = $null + } + if ($riskRemediation -and $riskRemediation.Pass) { + $passing = @($riskRemediation.Report | Where-Object { $_.Pass } | ForEach-Object { "'$($_.Policy.displayName)'" }) + $verb = if ($passing.Count -eq 1) { 'requires' } else { 'require' } + Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "MT.1253 is met: $($passing -join ', ') $verb risk remediation for high user risk, which replaces the password change grant control." + return $null + } + $policies = Get-MtConditionalAccessPolicy | Where-Object { $_.state -eq 'enabled' } # Only check policies that have password change as a grant control $policies = $policies | Where-Object { $_.grantControls.builtInControls -contains 'passwordChange' } diff --git a/tests/maester/entra/Test.MT.1253.md b/tests/maester/entra/Test.MT.1253.md new file mode 100644 index 0000000000..729e206bc9 --- /dev/null +++ b/tests/maester/entra/Test.MT.1253.md @@ -0,0 +1,35 @@ +At least one enabled Conditional Access policy should require risk remediation for all users when user risk is high. + +Microsoft Entra ID Protection raises a user's risk when it sees signs that the account is compromised, such as leaked credentials, password spray or an anomalous token. A user risk policy with the **Require risk remediation** grant control lets users fix that risk themselves, and Microsoft Entra ID Protection picks the remediation flow that fits the risk and the user's authentication method: + +* **Password-based users** perform a secure password change after MFA, and their previous sessions are revoked. +* **Passwordless users** have their sessions revoked and must sign in again. +* **An attacker-added device** is disabled so that it can no longer get tokens. + +The older **Require password change** control only works for users who sign in with a password, so it leaves passwordless users without a way to remediate the risk themselves. When you select **Require risk remediation**, Conditional Access also applies **Require authentication strength** and **Sign-in frequency - Every time**, so the user signs in again with a strong method after the sessions are revoked. + +This check passes when an enabled policy includes **All users**, targets **All resources**, covers the **High** user risk level and requires risk remediation. Raise the `MinimumUserRiskLevel` parameter to `medium` or `low` if your policy must cover those levels as well. Users must be registered for MFA before they can remediate. + +The policy may exclude only your emergency access accounts and groups. Maester takes them from the `EmergencyAccessAccounts` setting; a configured entry that cannot be resolved makes the check report an error. Without the setting, a user or group that is excluded from every Conditional Access policy (at least two) is taken as emergency access, as in MT.1005. Any other user, group or directory role exclusion disqualifies the policy, even when it includes **All users**. Risk remediation is not supported for guest and external users, so excluding **Guest or external users** is allowed; individual guest accounts or guest groups are not. Make sure emergency access accounts are excluded; MT.1005 checks that. + +#### Remediation action + +1. In **Entra ID**, navigate to **Conditional Access** > **[Policies](https://entra.microsoft.com/#view/Microsoft_AAD_ConditionalAccess/ConditionalAccessBlade/~/Policies)**. +2. Select **New policy**, or open the Microsoft-managed risk remediation policy if your tenant has one. +3. Under **Users**, include **All users** and exclude your emergency access accounts. List them in `EmergencyAccessAccounts` in `maester-config.json`. Remove other user, group and role exclusions; to leave out guests, exclude **Guest or external users** instead of individual accounts. +4. Under **Target resources**, include **All resources (formerly 'All cloud apps')**. +5. Under **Conditions** > **User risk**, set **Configure** to **Yes** and select **High**. +6. Under **Grant**, select **Grant access** and **Require risk remediation**. **Require authentication strength** and **Sign-in frequency - Every time** are selected automatically. +7. Review the impact in **Report-only** mode, then set **Enable policy** to **On** and click **Save**. +8. If an existing policy requires **Require password change** for user risk, replace it with this policy. + +#### Related links + +* [Entra admin center - Conditional Access policies](https://entra.microsoft.com/#view/Microsoft_AAD_ConditionalAccess/ConditionalAccessBlade/~/Policies) +* [Require remediation for risky users](https://learn.microsoft.com/entra/identity/conditional-access/policy-risk-based-user#require-risk-remediation) +* [Require risk remediation control](https://learn.microsoft.com/entra/id-protection/concept-identity-protection-policies#require-risk-remediation-control) +* [Remediate risks and unblock users](https://learn.microsoft.com/entra/id-protection/howto-identity-protection-remediate-unblock) +* [Microsoft-managed Conditional Access policies](https://learn.microsoft.com/entra/identity/conditional-access/managed-policies) + + +%TestResult% diff --git a/tests/maester/entra/Test.MT.1253.ps1 b/tests/maester/entra/Test.MT.1253.ps1 new file mode 100644 index 0000000000..a370ab61db --- /dev/null +++ b/tests/maester/entra/Test.MT.1253.ps1 @@ -0,0 +1,91 @@ +ο»Ώfunction Test-MtCaRequireRiskRemediationForHighUserRisk { + <# + .SYNOPSIS + Checks if at least one enabled Conditional Access policy requires risk remediation for high-risk users. + + .DESCRIPTION + The "Require risk remediation" grant control (riskRemediation) lets Microsoft Entra ID Protection pick the + remediation flow that fits the user's risk and authentication method: a secure password change for + password-based users, session revocation and a fresh sign-in for passwordless users, and disabling an + attacker-added device. Unlike "Require password change", it also remediates users who sign in without a + password. + + The check passes when at least one enabled Conditional Access policy: + - includes all users, excluding only emergency access accounts and the guest/external-user selector, + - targets all resources, + - is scoped to the high user risk level (and to every lower level named by MinimumUserRiskLevel), and + - requires the riskRemediation grant control. + + Learn more: + https://learn.microsoft.com/entra/identity/conditional-access/policy-risk-based-user#require-risk-remediation + + .EXAMPLE + Test-MtCaRequireRiskRemediationForHighUserRisk + + .LINK + https://maester.dev/docs/tests/MT.1253 + #> + [MaesterTest( + Id = 'MT.1253', + Title = 'At least one Conditional Access policy is configured to require risk remediation when user risk is high.', + Product = 'entra', + Feature = 'conditional-access', + Area = 'authentication', + ResourceType = 'Tenant', + Severity = 'Medium', + UserImpact = 'Medium', + ImplementationCost = 'Medium', + Mitre = 'T1078.004', + Control = 'nist-800-53-r5:AC-2(12)', + Service = 'Graph', + License = 'AAD_PREMIUM_P2', + Author = 'Cloud-Architekt' + )] + [CmdletBinding()] + [OutputType([bool])] + param( + # Lowest user risk level that a qualifying policy must cover; every higher level must be covered too. + [ValidateSet('high', 'medium', 'low')] + [string] $MinimumUserRiskLevel = 'high' + ) + + # The evaluation is shared with MT.1013, which is skipped when this requirement is met. + $evaluation = Get-MtCaRiskRemediationPolicyResult -MinimumUserRiskLevel $MinimumUserRiskLevel + $requiredRiskLevels = $evaluation.RequiredRiskLevels + $policies = $evaluation.Policies + $report = $evaluation.Report + $emergencyUserIds = $evaluation.EmergencyUserIds + $emergencyGroupIds = $evaluation.EmergencyGroupIds + $emergencyAccessDetected = $evaluation.EmergencyAccessDetected + $testResult = $evaluation.Pass + + $table = "| Policy | State | User risk levels | User exclusions | Failed checks | Result |`n" + $table += "| --- | --- | --- | --- | --- | --- |`n" + foreach ($row in $report) { + $policyLink = Get-GraphObjectMarkdown -GraphObjects $row.Policy -GraphObjectType ConditionalAccess -AsPlainTextLink + $failedText = if ($row.Failed) { $row.Failed } else { 'None' } + $resultText = if ($row.Pass) { 'βœ… Pass' } else { '❌ Fail' } + $table += "| $policyLink | $($row.Policy.state) | $($row.UserRiskLevels) | $($row.Exclusions) | $failedText | $resultText |`n" + } + + if ($testResult) { + $testResultMarkdown = "Well done. At least one enabled Conditional Access policy requires risk remediation for all users at user risk level $($requiredRiskLevels -join ', '), with only approved emergency access or guest/external-user exclusions.`n`n$table" + } elseif ($report.Count -gt 0) { + $testResultMarkdown = "No enabled Conditional Access policy requires risk remediation for all users and all resources at user risk level $($requiredRiskLevels -join ', '). These policies use the **Require risk remediation** grant control but do not meet every condition:`n`n$table" + } else { + $testResultMarkdown = 'No Conditional Access policy uses the **Require risk remediation** grant control.' + $passwordChangePolicies = @($policies | Where-Object { + $_.state -eq 'enabled' -and @($_.grantControls.builtInControls) -contains 'passwordChange' + }) + if ($passwordChangePolicies.Count -gt 0) { + $testResultMarkdown += " $($passwordChangePolicies.Count) enabled $(if ($passwordChangePolicies.Count -eq 1) { 'policy requires' } else { 'policies require' }) **Require password change** instead, which does not remediate users who sign in without a password. Consider replacing the grant control with **Require risk remediation**." + } + } + if ($report.Count -gt 0 -and $emergencyAccessDetected) { + $detected = @($emergencyUserIds | ForEach-Object { "user ``$_``" }) + @($emergencyGroupIds | ForEach-Object { "group ``$_``" }) + $testResultMarkdown += "`n`nEmergency access was detected automatically, because it is excluded from every Conditional Access policy: $($detected -join ', '). Set ``EmergencyAccessAccounts`` in maester-config.json to name the accounts and groups yourself." + } + + Add-MtTestResultDetail -Result $testResultMarkdown + return $testResult +} diff --git a/tests/maester/entra/Test.MT.1254.md b/tests/maester/entra/Test.MT.1254.md new file mode 100644 index 0000000000..d488ba08da --- /dev/null +++ b/tests/maester/entra/Test.MT.1254.md @@ -0,0 +1,32 @@ +Tenant Configuration Management monitors should report no active configuration drift. + +Configuration management in Microsoft Entra Tenant Governance, built on the Microsoft Graph Tenant Configuration Management APIs (also called Unified Tenant Configuration Management, UTCM), runs monitors that compare the tenant's settings with a JSON configuration baseline. A baseline can cover more than 200 resource types across Entra, Exchange Online, Intune, Teams, Purview and Defender, such as Conditional Access policies, authentication method policies or transport rules. When a setting no longer matches the baseline, the monitor reports a configuration drift with the current and the desired value of each drifted property. + +An active drift means the tenant is no longer in the state you approved. It may be an emergency change that was never written back to the baseline, a change made outside your change process, or an attacker who weakened a policy to keep access. Until a drift is investigated and closed, you cannot rely on the baseline as a description of your security configuration. + +This check has one result per monitor (πŸ“‘), named `MT.1254.`, so each monitor passes or fails on its own and the owner of each baseline sees their own result. A result fails when its monitor reports an active drift; drifts that a later monitor run marked as fixed are not listed. Each result starts with a summary of the monitor, one line per property: its status (🟒 active or ⏸️ inactive with the reason), its last run (outcome, time, duration and the drifts it found, with a link to the πŸ“Š **Monitor results** of the monitor), how often it runs, its number of active drifts and how long the oldest of them has been active, its mode, its description, and when and by whom it was created and last changed. A last run that failed is marked ❌, a monitor that has not run for more than two run intervals is marked ⏰ overdue, and a new monitor that is still waiting for its first run is marked ⏳. The drift follows in one table per resource type, marked with the icon of its workload (πŸ†” Entra ID, πŸ“§ Exchange Online, πŸ’» Intune, πŸ’¬ Teams, πŸ”’ Purview, πŸ›‘οΈ Defender). Each resource (πŸ“„), or tenant-wide setting (βš™οΈ) such as the authorization policy or the Exchange organization configuration, has one row per drifted property with the current and the desired value, and the date it was first detected, oldest first. For list values, such as the users excluded from a Conditional Access policy, only the items that differ are shown: πŸ”΄ items that are not in the baseline, and 🟒 items of the baseline that are missing. Entra resources such as Conditional Access policies and groups link to the object itself and are listed on the **Affected objects** page of the report; other resources link to the monitor. + +To leave out a monitor that tracks settings you do not want to gate on, disable its result in `maester-config.json` (a `TestSettings` entry with `"Id": "MT.1254."` and `"Enabled": false`), or run with `-ExcludeTestId MT.1254.`. For monitors with a lot of drift, `MaxDriftsPerMonitor` (default 50), `MaxPropertiesPerResource` (default 5) and `MaximumValueLength` (default 80) keep the result readable; the rest is counted as **+N more**. These can be set for all monitors or for one. When the tenant has no monitor, the check is skipped. When a monitor reports no drift but is inactive (⏸️), its last run did not report success (failed, partially successful or an unknown status), it is overdue, it has not run yet or its runs cannot be read, its result is **Investigate**, because the missing drift may only mean that the settings were not checked. + +The connection needs the `ConfigurationMonitoring.Read.All` Microsoft Graph permission. It is included in `Get-MtGraphScope -IncludePreview`. Without it, the check is skipped. Tenant Configuration Management is only available in the worldwide Microsoft Graph service (Commercial and GCC); in other clouds the check is skipped. + +**Report confidentiality:** Current and desired configuration values are displayed without secret-specific redaction; length limits are not masking. Treat exported reports as confidential: they can also contain UPNs, names, partner details and privileged relationships. Restrict access and review the content before sharing. + +#### Remediation action + +1. In the results below, select a monitor to open it in the [Microsoft Entra admin center](https://entra.microsoft.com), or browse to **Tenant Governance** > **Monitors**. +2. Select the **Configuration drifts** tab and open each drift listed in the results. +3. Select the **Drifted properties** value to compare the actual and the expected value, and find out who changed the setting in the audit log of the workload. +4. If the change was not approved, restore the setting to the desired value. If it was approved, update the monitor's baseline to the new value. +5. Wait for the next monitor run (monitors run every six hours by default). It marks the drift as `fixed`. +6. If a monitor is inactive, or its last run failed, check its **Monitor results** and grant the Tenant Configuration Management service principal the permissions it needs. + +#### Related links + +* [Configuration management in Microsoft Entra Tenant Governance](https://learn.microsoft.com/entra/id-governance/tenant-governance/configuration-management) +* [View monitor results and manage monitors](https://learn.microsoft.com/entra/id-governance/tenant-governance/how-to-see-monitor-results) +* [Set up permissions for tenant monitoring](https://learn.microsoft.com/entra/id-governance/tenant-governance/how-to-set-up-permissions-tenant-monitoring) +* [Microsoft Graph - List configurationDrifts](https://learn.microsoft.com/graph/api/configurationmanagement-list-configurationdrifts?view=graph-rest-1.0) + + +%TestResult% diff --git a/tests/maester/entra/Test.MT.1254.ps1 b/tests/maester/entra/Test.MT.1254.ps1 new file mode 100644 index 0000000000..d29bc75f01 --- /dev/null +++ b/tests/maester/entra/Test.MT.1254.ps1 @@ -0,0 +1,471 @@ +ο»Ώfunction Get-MtTenantConfigurationMonitorInstance { + <# + .SYNOPSIS + Returns one MT.1254 instance per Tenant Configuration Management monitor. + + .DESCRIPTION + Instance source of the MT.1254 family. Reads the configuration monitors of the tenant and returns one instance + per monitor, keyed by the monitor id, with the monitor as its data. Without monitors there are no instances and + the family is skipped. + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param() + + # Tenant Configuration Management is only available in the worldwide Microsoft Graph service. + $graphEnvironment = (Get-MgContext).Environment + if ($graphEnvironment -and $graphEnvironment -ne 'Global') { + Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Tenant Configuration Management is not available in the $graphEnvironment cloud." + return + } + + try { + $monitors = @(Invoke-MtGraphRequest -RelativeUri 'admin/configurationManagement/configurationMonitors' -ApiVersion v1.0 ` + -Select 'id', 'displayName', 'description', 'status', 'inactivationReason', 'monitorRunFrequencyInHours', 'mode', 'createdDateTime', 'lastModifiedDateTime', 'createdBy', 'lastModifiedBy' -ErrorAction Stop) + } catch { + if ($_.Exception.Response -and [int]$_.Exception.Response.StatusCode -in @(401, 403)) { + # The skip from the instance source skips the whole family, as the drift request does for one monitor. + Add-MtTestResultDetail -SkippedBecause NotAuthorized + return + } + throw + } + + foreach ($monitor in @($monitors | Where-Object { $_.id } | Sort-Object -Property displayName)) { + $name = if ($monitor.displayName) { $monitor.displayName } else { $monitor.id } + [pscustomobject]@{ + Id = $monitor.id + Title = "Tenant Configuration Management monitor '$name' reports no active configuration drift." + Data = $monitor + } + } +} + +function Test-MtEntraTenantConfigurationDrift { + <# + .SYNOPSIS + Checks that a Tenant Configuration Management monitor reports no active configuration drift. + + .DESCRIPTION + Microsoft Entra Tenant Governance configuration management (Unified Tenant Configuration Management, UTCM) + runs monitors that compare the tenant's settings across Entra, Exchange Online, Intune, Teams, Purview and + Defender with a JSON configuration baseline. Each difference is reported as a configuration drift with the + drifted properties and their current and desired values. + + The check is a family with one result per monitor. Each result fails when its monitor reports an active + drift, and shows the monitor's status and latest run and one table per resource type. When the monitor + reports no drift but is inactive, its last run failed, it is overdue, it has not run yet or its runs cannot + be read, the result is Investigate. Without monitors, without the ConfigurationMonitoring.Read.All permission + or outside the worldwide cloud the family is skipped. + + Learn more: + https://learn.microsoft.com/entra/id-governance/tenant-governance/configuration-management + + .EXAMPLE + Invoke-MtTest -Id MT.1254 + + .LINK + https://maester.dev/docs/tests/MT.1254 + #> + [MaesterTest( + Id = 'MT.1254', + Title = 'Tenant Configuration Management monitors report no active configuration drift.', + Product = 'entra', + Feature = 'monitoring', + Area = 'infrastructure', + ResourceType = 'Tenant', + Severity = 'Medium', + UserImpact = 'Low', + ImplementationCost = 'Medium', + Mitre = ('T1484', 'T1556.009'), + Control = ('nist-800-53-r5:CM-6', 'nist-800-53-r5:CM-2'), + Service = 'Graph', + Permission = 'Graph:Scope:ConfigurationMonitoring.Read.All', + Cloud = ('Commercial', 'GCC'), + Lifecycle = 'Preview', + InstanceSource = 'Get-MtTenantConfigurationMonitorInstance', + Author = 'Cloud-Architekt' + )] + [CmdletBinding()] + [OutputType([bool])] + param( + # The configuration monitor to check, supplied by the engine. + $Instance, + + # Longest number of characters shown for a current or desired property value in the result. + [ValidateRange(20, 1000)] + [int] $MaximumValueLength = 80, + + # Maximum number of drifts listed for the monitor; the others are counted. + [ValidateRange(1, 1000)] + [int] $MaxDriftsPerMonitor = 50, + + # Maximum number of drifted properties listed for each resource; the others are counted. + [ValidateRange(1, 100)] + [int] $MaxPropertiesPerResource = 5 + ) + + $monitor = $Instance.Data + $nowUtc = (Get-Date).ToUniversalTime() + $toUtc = { + param($Value) + if ($Value -is [datetime]) { return $Value.ToUniversalTime() } + if ($Value -is [datetimeoffset]) { return $Value.UtcDateTime } + $parsed = [datetimeoffset]::MinValue + if ($Value -and [datetimeoffset]::TryParse("$Value", [cultureinfo]::InvariantCulture, [System.Globalization.DateTimeStyles]::AssumeUniversal, [ref]$parsed)) { + return $parsed.UtcDateTime + } + return $null + } + + # The active drifts of every monitor are read once and served from the request cache to the other monitors. + try { + $drifts = @(Invoke-MtGraphRequest -RelativeUri 'admin/configurationManagement/configurationDrifts' -ApiVersion v1.0 ` + -Filter "status eq 'active'" ` + -Select 'id', 'monitorId', 'resourceType', 'baselineResourceDisplayName', 'resourceInstanceIdentifier', 'firstReportedDateTime', 'status', 'driftedProperties' ` + -ErrorAction Stop | Where-Object { $_.monitorId -eq $monitor.id }) + } catch { + if ($_.Exception.Response -and $_.Exception.Response.StatusCode -in @(401, 403)) { + Add-MtTestResultDetail -SkippedBecause NotAuthorized + return $null + } + throw + } + + $isActive = -not $monitor.status -or $monitor.status -eq 'active' + $frequency = if ([int]$monitor.monitorRunFrequencyInHours -gt 0) { [int]$monitor.monitorRunFrequencyInHours } else { 6 } + # A monitor is overdue when it has not started a run for more than two run intervals (plus an hour of slack). + $overdueAfterHours = 2 * $frequency + 1 + + # The latest run of the monitor. The runs of the last days are read once for all monitors: the start of the + # window is a whole day, so every monitor with the same schedule sends the same request and the cache answers + # it. The window always covers the overdue limit, so a monitor on a long schedule is not overdue for lack of data. + $runLookbackDays = [int][math]::Max(7, [math]::Ceiling($overdueAfterHours / 24)) + $since = $nowUtc.Date.AddDays(-$runLookbackDays).ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", [cultureinfo]::InvariantCulture) + $runsQuery = @{ + RelativeUri = 'admin/configurationManagement/configurationMonitoringResults' + ApiVersion = 'v1.0' + ErrorAction = 'Stop' + } + $runsError = $null + $runs = @() + try { + $runs = @(Invoke-MtGraphRequest @runsQuery -Filter "runInitiationDateTime ge $since" -QueryParameters @{ '$top' = '999' }) + } catch { + Write-Verbose "Could not read the monitor runs since $($since): $($_.Exception.Message)" + try { + $runs = @(Invoke-MtGraphRequest @runsQuery) + } catch { + $statusCode = if ($_.Exception.Response) { [int]$_.Exception.Response.StatusCode } else { $null } + $message = ("$($_.Exception.Message)" -split '\r?\n')[0] + if ($message.Length -gt 160) { $message = $message.Substring(0, 160) + '…' } + $runsError = "$(if ($statusCode) { "HTTP $($statusCode): " })$message" + Write-Verbose "Could not read the monitor runs: $runsError" + } + } + $lastRun = $runs | Where-Object { $null -ne $_ -and $_.monitorId -eq $monitor.id } | + Sort-Object -Property { & $toUtc $_.runInitiationDateTime } -Descending | Select-Object -First 1 + + $lastRunStarted = if ($lastRun) { & $toUtc $lastRun.runInitiationDateTime } else { $null } + # Without a run, the monitor is measured from its creation: a new monitor waits for its first run. + $createdUtc = & $toUtc $monitor.createdDateTime + $awaitingFirstRun = $isActive -and -not $runsError -and $null -eq $lastRun -and $createdUtc -and ($nowUtc - $createdUtc).TotalHours -le $overdueAfterHours + # A run without a readable start time cannot show that the monitor ran on schedule. + $isOverdue = $isActive -and -not $runsError -and -not $awaitingFirstRun -and ($null -eq $lastRun -or -not $lastRunStarted -or ($nowUtc - $lastRunStarted).TotalHours -gt $overdueAfterHours) + # Only a confirmed successful run shows that the drift list is complete. failed, partiallySuccessful, + # unknownFutureValue, a missing status or any status Microsoft Graph adds later needs investigation. + $runNotSuccessful = $isActive -and -not $runsError -and $null -ne $lastRun -and "$($lastRun.runStatus)" -ne 'successful' + + $entraPortal = $__MtSession.AdminPortalUrl.Entra + $escape = { + param($Text) + "$Text" -replace '\r?\n', ' ' -replace '\|', '\|' + } + $monitorUrl = "$($entraPortal)#view/Microsoft_Entra_TenantManagement/MonitorDetails.ReactView/monitorId/$($monitor.id)" + # The Monitor results tab of Tenant Governance, filtered to this monitor by a JSON filter in the URL. + $monitorFilter = [uri]::EscapeDataString((ConvertTo-Json -InputObject @{ monitorId = "$($monitor.id)" } -Compress)) -replace '\(', '%28' -replace '\)', '%29' + $monitorResultsUrl = "$($entraPortal)#view/Microsoft_Entra_TenantManagement/InternalMonitor.ReactView/initialTab/monitorResults/monitorResultsFilterParams~/$monitorFilter" + $monitorResultsLink = if ($entraPortal) { "πŸ“Š [Monitor results]($monitorResultsUrl)" } else { $null } + $monitorName = Get-MtSafeMarkdown $(if ($monitor.displayName) { $monitor.displayName } else { $monitor.id }) + $monitorLink = if ($entraPortal) { "πŸ“‘ [$monitorName]($monitorUrl)" } else { "πŸ“‘ $monitorName" } + + $formatAge = { + param([datetime] $Utc) + $hours = ($nowUtc - $Utc).TotalHours + if ($hours -lt 1) { 'less than an hour ago' } elseif ($hours -lt 48) { "$([int][math]::Floor($hours)) h ago" } else { "$([int][math]::Floor($hours / 24)) days ago" } + } + $runIcon = '❔' + $runText = if (-not $isActive) { + $runIcon = '⏸️' + 'Not running while the monitor is inactive' + } elseif ($runsError) { + 'Unknown, the monitor runs could not be read' + } elseif ($awaitingFirstRun) { + $runIcon = '⏳' + 'No run yet since the monitor was created' + } elseif ($null -eq $lastRun) { + $runIcon = '⏰' + "No run in the last $runLookbackDays days" + } else { + $runIcon, $runStatus = switch ($lastRun.runStatus) { + 'successful' { 'βœ…', 'Successful' } + 'partiallySuccessful' { '⚠️', 'Partially successful' } + 'failed' { '❌', 'Failed' } + default { '❔', "$($lastRun.runStatus)" } + } + $when = if ($lastRunStarted) { "$($lastRunStarted.ToString('yyyy-MM-dd HH:mm', [cultureinfo]::InvariantCulture)) UTC ($(& $formatAge $lastRunStarted))" } else { 'unknown time' } + $lastRunCompleted = & $toUtc $lastRun.runCompletionDateTime + $duration = if ($lastRunStarted -and $lastRunCompleted -and $lastRunCompleted -ge $lastRunStarted) { + $minutes = ($lastRunCompleted - $lastRunStarted).TotalMinutes + " Β· took $(if ($minutes -lt 1) { 'less than a minute' } else { "$([int][math]::Round($minutes)) min" })" + } else { '' } + $found = if ($null -ne $lastRun.driftsCount -and $lastRun.runStatus -ne 'failed') { " Β· found $([int]$lastRun.driftsCount) $(if ([int]$lastRun.driftsCount -eq 1) { 'drift' } else { 'drifts' })" } else { '' } + "$runStatus Β· $when$duration$found$(if ($isOverdue) { ' Β· ⏰ **overdue**' })" + } + $formatIdentity = { + param($IdentitySet) + $who = if ($IdentitySet.user.userPrincipalName) { "πŸ‘€ $($IdentitySet.user.userPrincipalName)" } + elseif ($IdentitySet.user.displayName) { "πŸ‘€ $($IdentitySet.user.displayName)" } + elseif ($IdentitySet.application.displayName) { "🧩 $($IdentitySet.application.displayName)" } + elseif ($IdentitySet.app.displayName) { "🧩 $($IdentitySet.app.displayName)" } + else { $null } + if ($who) { " by $(Get-MtSafeMarkdown $who)" } else { '' } + } + $formatChangeDate = { + param($Value) + $date = & $toUtc $Value + if (-not $date) { return $null } + "$($date.ToString('yyyy-MM-dd', [cultureinfo]::InvariantCulture)) ($(& $formatAge $date))" + } + + # microsoft.. β†’ a workload icon and name; the full type stays visible for searching the docs. + $workloads = @{ + entra = @{ Icon = 'πŸ†”'; Name = 'Entra ID' } + exchange = @{ Icon = 'πŸ“§'; Name = 'Exchange Online' } + intune = @{ Icon = 'πŸ’»'; Name = 'Intune' } + teams = @{ Icon = 'πŸ’¬'; Name = 'Teams' } + securityandcompliance = @{ Icon = 'πŸ”’'; Name = 'Purview' } + purview = @{ Icon = 'πŸ”’'; Name = 'Purview' } + defender = @{ Icon = 'πŸ›‘οΈ'; Name = 'Defender' } + } + $formatResourceType = { + param([string] $ResourceType) + $workload = ($ResourceType -split '\.')[1] + $info = if ($workload -and $workloads.ContainsKey($workload)) { $workloads[$workload] } else { @{ Icon = '🧩'; Name = $(if ($workload) { $workload } else { 'Unknown workload' }) } } + "$($info.Icon) $($info.Name) Β· ``$ResourceType``" + } + # Entra resources with an object id link to the object itself, which also lists them as affected objects. + # Every other resource links to the monitor, where the drift can be reviewed. + $sharedLinkTemplates = (Get-MtPortalLinkTemplate).LinkTemplates + $objectLinkTemplates = @{ + 'microsoft.entra.conditionalaccesspolicy' = @{ Key = 'Id'; Template = $sharedLinkTemplates.ConditionalAccess } + 'microsoft.entra.group' = @{ Key = 'Id'; Template = $sharedLinkTemplates.Groups } + 'microsoft.entra.user' = @{ Key = 'Id'; Template = $sharedLinkTemplates.Users } + 'microsoft.entra.serviceprincipal' = @{ Key = 'Id'; Template = $sharedLinkTemplates.ServicePrincipals } + # App registrations open by appId; the shared templates address objects by object id. + 'microsoft.entra.application' = @{ Key = 'AppId'; Template = "$($entraPortal)#view/Microsoft_AAD_RegisteredApps/ApplicationMenuBlade/~/Overview/appId/{0}" } + } + $resourceKey = { + param($Drift) + "$($Drift.resourceType)|$(ConvertTo-Json -InputObject $Drift.resourceInstanceIdentifier -Compress -Depth 5)|$($Drift.baselineResourceDisplayName)" + } + $formatResource = { + param($Drift) + # Microsoft365DSC-style keys that do not name an object: IsSingleInstance = 'Yes' marks a tenant-wide setting, + # and Ensure or the connection parameters are never names. + $ignoredKeys = @('IsSingleInstance', 'Ensure', 'Credential', 'ApplicationId', 'ApplicationSecret', 'TenantId', 'CertificateThumbprint', 'CertificatePath', 'ManagedIdentity', 'AccessTokens') + $identifier = @{} + $isSingleInstance = $false + if ($Drift.resourceInstanceIdentifier) { + foreach ($property in $Drift.resourceInstanceIdentifier.PSObject.Properties) { + if ($property.Name -like '@odata*' -or $null -eq $property.Value -or "$($property.Value)" -eq '') { continue } + if ($property.Name -eq 'IsSingleInstance') { $isSingleInstance = $true } + if ($property.Name -in $ignoredKeys) { continue } + $identifier[$property.Name] = "$($property.Value)" + } + } + # The instance identifier names the object; the baseline display name is only the label of the baseline entry. + $name = foreach ($key in 'DisplayName', 'Name', 'Identity', 'UserPrincipalName', 'Id') { + if ($identifier.ContainsKey($key)) { $identifier[$key]; break } + } + if (-not $name -and $identifier.Count -gt 0) { $name = @($identifier.Values)[0] } + # A tenant-wide setting has no instance name: it is named by its baseline entry (βš™οΈ) instead of an object (πŸ“„). + $icon = if (-not $name -and $isSingleInstance) { 'βš™οΈ' } else { 'πŸ“„' } + if (-not $name) { + $name = if ($Drift.baselineResourceDisplayName) { $Drift.baselineResourceDisplayName } elseif ($isSingleInstance) { 'Tenant-wide setting' } else { 'Unnamed resource' } + } + $text = Get-MtSafeMarkdown $name + + $title = if ($Drift.baselineResourceDisplayName -and $Drift.baselineResourceDisplayName -ne $name) { "Baseline entry: $($Drift.baselineResourceDisplayName)" } elseif ($icon -eq 'βš™οΈ') { 'Tenant-wide setting' } else { $null } + $titleText = if ($title) { " `"$($title -replace '["\\]', '' -replace '\r?\n', ' ' -replace '\|', '\|')`"" } else { '' } + if (-not $entraPortal) { return "$icon $text" } + + $object = $objectLinkTemplates["$($Drift.resourceType)".ToLowerInvariant()] + $parsedGuid = [guid]::Empty + if ($object -and $identifier.ContainsKey($object.Key) -and [guid]::TryParse($identifier[$object.Key], [ref]$parsedGuid)) { + return "$icon [$text]($($object.Template -f $identifier[$object.Key])$titleText)" + } + return "$icon [$text]($monitorUrl$titleText)" + } + # Drifted property values are JSON: show scalars as they are and objects as compact JSON in a code span. + $formatValue = { + param($Value) + if ($null -eq $Value) { return '_empty_' } + $text = if ($Value -is [string] -or $Value -is [ValueType]) { [string]$Value } else { ConvertTo-Json -InputObject $Value -Depth 5 -Compress } + if ($text -eq '') { return '_empty_' } + if ($text.Length -gt $MaximumValueLength) { $text = $text.Substring(0, $MaximumValueLength) + '…' } + return '`' + ($text -replace '\|', '\|' -replace '`', "'" -replace '\r?\n', ' ') + '`' + } + # A list value, given as an array or as a JSON array string, as its items in compact JSON; IsList is $false otherwise. + $readList = { + param($Value) + if ($null -eq $Value -or "$Value".Trim() -eq '') { return [pscustomobject]@{ IsList = $false; IsEmpty = $true; Items = @() } } + $items = $null + if ($Value -is [string]) { + $text = $Value.Trim() + if ($text.StartsWith('[') -and $text.EndsWith(']')) { + try { + $parsed = ConvertFrom-Json -InputObject $text -ErrorAction Stop + $items = @($parsed | ForEach-Object { $_ }) + } catch { $items = $null } + } + } elseif ($Value -is [System.Collections.IEnumerable] -and $Value -isnot [System.Collections.IDictionary]) { + $items = @($Value | ForEach-Object { $_ }) + } + if ($null -eq $items) { return [pscustomobject]@{ IsList = $false; IsEmpty = $false; Items = @() } } + $keys = @($items | Where-Object { $null -ne $_ } | ForEach-Object { + if ($_ -is [string] -or $_ -is [ValueType]) { [string]$_ } else { ConvertTo-Json -InputObject $_ -Depth 5 -Compress } + }) + [pscustomobject]@{ IsList = $true; IsEmpty = $keys.Count -eq 0; Items = $keys } + } + # For list values only the items that differ are shown: a long list cut at MaximumValueLength would hide them. + # Returns $null when the values are not lists or differ only in order, so they are shown as they are. + $formatListChange = { + param($Current, $Desired) + $currentList = & $readList $Current + $desiredList = & $readList $Desired + if (-not ($currentList.IsList -or $desiredList.IsList)) { return $null } + if (-not ($currentList.IsList -or $currentList.IsEmpty) -or -not ($desiredList.IsList -or $desiredList.IsEmpty)) { return $null } + $currentSet = [System.Collections.Generic.HashSet[string]]::new([string[]]$currentList.Items, [System.StringComparer]::Ordinal) + $desiredSet = [System.Collections.Generic.HashSet[string]]::new([string[]]$desiredList.Items, [System.StringComparer]::Ordinal) + $extra = @($currentList.Items | Where-Object { -not $desiredSet.Contains($_) } | Select-Object -Unique) + $missing = @($desiredList.Items | Where-Object { -not $currentSet.Contains($_) } | Select-Object -Unique) + if ($extra.Count -eq 0 -and $missing.Count -eq 0) { return $null } + $maxItems = 5 + $formatSide = { + param([string[]] $Changed, [int] $Total, [string] $Icon, [string] $Suffix) + $countText = "$Total $(if ($Total -eq 1) { 'item' } else { 'items' })" + if ($Changed.Count -eq 0) { return $(if ($Total -eq 0) { '_empty_' } else { $countText }) } + $shownItems = @($Changed | Select-Object -First $maxItems | ForEach-Object { & $formatValue $_ }) -join ', ' + $moreText = if ($Changed.Count -gt $maxItems) { " +$($Changed.Count - $maxItems) more" } else { '' } + "$Icon $shownItems$moreText $Suffix ($countText)" + } + [pscustomobject]@{ + Current = & $formatSide $extra $currentList.Items.Count 'πŸ”΄' 'not in baseline' + Desired = & $formatSide $missing $desiredList.Items.Count '🟒' 'missing' + } + } + $formatFirstDetected = { + param($Value) + $detected = & $toUtc $Value + if (-not $detected) { return 'Unknown' } + $days = [int][math]::Floor(($nowUtc - $detected).TotalDays) + $age = if ($days -lt 1) { 'today' } elseif ($days -eq 1) { '1 day' } else { "$days days" } + "$($detected.ToString('yyyy-MM-dd', [cultureinfo]::InvariantCulture)) ($age)" + } + # One row per drifted property; the resource and its first detection are only on its first row, so the rows of + # one resource read as a group. + $formatDriftRows = { + param($Drift) + $resource = & $formatResource $Drift + $detected = & $formatFirstDetected $Drift.firstReportedDateTime + $properties = @($Drift.driftedProperties | Where-Object { $null -ne $_ }) + if ($properties.Count -eq 0) { return "| $resource | _Not reported_ | | | $detected |`n" } + $rows = '' + $first = $true + foreach ($property in @($properties | Select-Object -First $MaxPropertiesPerResource)) { + $cells = if ($first) { "| $resource |" } else { '| |' } + $change = & $formatListChange $property.currentValue $property.desiredValue + $currentText = if ($change) { $change.Current } else { & $formatValue $property.currentValue } + $desiredText = if ($change) { $change.Desired } else { & $formatValue $property.desiredValue } + $rows += "$cells $(Get-MtSafeMarkdown $property.propertyName) | $currentText | $desiredText | $(if ($first) { $detected }) |`n" + $first = $false + } + if ($properties.Count -gt $MaxPropertiesPerResource) { + $rows += "| | _+$($properties.Count - $MaxPropertiesPerResource) more properties_ | | | |`n" + } + $rows + } + + # Summary, then the monitor's status and last run. + $testResult = $drifts.Count -eq 0 + $runsIncomplete = $runNotSuccessful -or $isOverdue -or $awaitingFirstRun -or [bool]$runsError + if (-not $testResult) { + $resourceCount = @($drifts | ForEach-Object { & $resourceKey $_ } | Select-Object -Unique).Count + $testResultMarkdown = "$monitorLink reports **$($drifts.Count)** active configuration $(if ($drifts.Count -eq 1) { 'drift' } else { 'drifts' }) on $resourceCount $(if ($resourceCount -eq 1) { 'resource' } else { 'resources' }). Restore each setting to the desired value, or update the baseline if the change was intended." + } elseif (-not $isActive -or $runsIncomplete) { + $testResultMarkdown = "$monitorLink reports no active configuration drift, but this can be incomplete." + } else { + $testResultMarkdown = "Well done. $monitorLink reports no active configuration drift." + } + $notes = @( + if (-not $isActive) { '⏸️ The monitor is inactive and no longer detects drift. Check its permissions and turn it on again, or delete it.' } + if ($runNotSuccessful) { "⚠️ The last run did not report success (status: $(if ($lastRun.runStatus) { Get-MtSafeMarkdown "$($lastRun.runStatus)" } else { 'none' })), so drift may be missing or out of date. Check the $(if ($entraPortal) { "[Monitor results]($monitorResultsUrl)" } else { '**Monitor results**' }) of the monitor." } + if ($isOverdue) { "⏰ The monitor has not run as scheduled (every $frequency h)." } + if ($awaitingFirstRun) { "⏳ The monitor has not run yet. Its first run is expected within $overdueAfterHours h of its creation; until then, no drift only means that the settings were not checked." } + if ($runsError) { "❔ The monitor runs could not be read, so the last run is unknown ($(& $escape $runsError))." } + ) + # The warnings follow the monitor's properties, directly under the result sentence. + + # The monitor at a glance: one line per property, each with its own icon. + $resourceTotal = @($drifts | ForEach-Object { & $resourceKey $_ } | Select-Object -Unique).Count + $modeText = switch ($monitor.mode) { + 'monitorOnly' { 'Monitor only: reports drift and does not change settings' } + $null { $null } + default { "$($monitor.mode)" } + } + # How long the tenant has been out of line with the baseline: the first detection of the oldest active drift. + $oldestDrift = @($drifts | ForEach-Object { & $toUtc $_.firstReportedDateTime } | Where-Object { $_ } | Sort-Object | Select-Object -First 1) + $oldestText = if ($oldestDrift.Count -gt 0) { " Β· oldest since $(& $formatFirstDetected $oldestDrift[0])" } else { '' } + $created = & $formatChangeDate $monitor.createdDateTime + $modified = & $formatChangeDate $monitor.lastModifiedDateTime + $card = @( + if ($isActive) { '🟒 **Status:** Active' } else { "⏸️ **Status:** Inactive$(if ($monitor.inactivationReason) { " Β· $(Get-MtSafeMarkdown $monitor.inactivationReason)" })" } + "$runIcon **Last run:** $runText$(if ($monitorResultsLink) { " Β· $monitorResultsLink" })" + "⏱️ **Schedule:** Every $frequency h" + if ($drifts.Count -gt 0) { "πŸ”€ **Active drifts:** $($drifts.Count) on $resourceTotal $(if ($resourceTotal -eq 1) { 'resource' } else { 'resources' })$oldestText" } else { '✨ **Active drifts:** None' } + if ($modeText) { "πŸ› οΈ **Mode:** $modeText" } + if ($monitor.description) { "πŸ“ **Description:** $(Get-MtSafeMarkdown $monitor.description)" } + if ($created) { "πŸ—“οΈ **Created:** $created$(& $formatIdentity $monitor.createdBy)" } + if ($modified -and "$($monitor.lastModifiedDateTime)" -ne "$($monitor.createdDateTime)") { "✏️ **Last changed:** $modified$(& $formatIdentity $monitor.lastModifiedBy)" } + ) + $testResultMarkdown += "`n`n" + (($card | ForEach-Object { "- $_" }) -join "`n") + "`n" + if ($notes.Count -gt 0) { $testResultMarkdown += "`n" + ($notes -join "`n`n") + "`n" } + + # One table per resource type, oldest drift first. + if (-not $testResult) { + $testResultMarkdown += "`n### πŸ”€ Configuration drift`n" + $sorted = @($drifts | Sort-Object -Property resourceType, @{ Expression = { & $toUtc $_.firstReportedDateTime } }) + $shown = @($sorted | Select-Object -First $MaxDriftsPerMonitor) + foreach ($typeGroup in @($shown | Group-Object -Property resourceType)) { + $typeTotal = @($sorted | Where-Object { $_.resourceType -eq $typeGroup.Name }).Count + $testResultMarkdown += "`n#### $(& $formatResourceType $typeGroup.Name) Β· $typeTotal $(if ($typeTotal -eq 1) { 'resource' } else { 'resources' })`n`n" + $testResultMarkdown += "| Resource | Property | Current value | Desired value | First detected |`n| --- | --- | --- | --- | --- |`n" + foreach ($drift in $typeGroup.Group) { + $testResultMarkdown += & $formatDriftRows $drift + } + } + $hidden = $sorted.Count - $shown.Count + if ($hidden -gt 0) { + $testResultMarkdown += "`n… and $hidden more $(if ($hidden -eq 1) { 'drift' } else { 'drifts' }). Open $monitorLink to see all of them.`n" + } + } + + # No drift is only reassuring when the monitor is active and actually ran. + if ($testResult -and (-not $isActive -or $runsIncomplete)) { + Add-MtTestResultDetail -Result $testResultMarkdown -Investigate + return $testResult + } + Add-MtTestResultDetail -Result $testResultMarkdown + return $testResult +} diff --git a/tests/maester/entra/Test.MT.1255.md b/tests/maester/entra/Test.MT.1255.md new file mode 100644 index 0000000000..f3db0a7740 --- /dev/null +++ b/tests/maester/entra/Test.MT.1255.md @@ -0,0 +1,42 @@ +Members of governed groups should come from access package assignments. + +When a group is a resource in an entitlement management catalog, access to it is meant to be requested, approved, reviewed and removed through access packages. The access package drift report in **Access Guardian** compares the direct members of each governed group with the access package assignments that should grant them, and reports two kinds of drift for users and agent IDs: + +* **Unauthorized access**: The group has members without a corresponding access package assignment. An owner or administrator added them directly, or the access was left behind when an assignment ended. This access skips the approval, access reviews and expiration of the access package, and an attacker who controls an account with rights to the group can use it to keep access. +* **Missing assignments**: an access package assignment is active, but the expected group membership does not exist, usually because provisioning failed. + +This check fails when a governed group has unauthorized access or missing assignments. The result lists the groups with drift, sorted by unauthorized access, with the number of unauthorized and missing identities and examples of the affected users (πŸ‘€), groups (πŸ‘₯), service principals (🧩) and agent identities (πŸ€–). Each catalog (πŸ“š) in the **Drift in Catalog(s)** column opens the drift details of the group in that catalog. The report returns up to five drift records per resource, so **+N more** shows how many identities are not listed. Missing assignments usually mean that provisioning failed, so approved users lack the access they requested. To fail on unauthorized access only and list missing assignments for review, set the `IncludeMissingAccess` parameter to `$false`. Use `ExcludedResourceId` to leave out groups, and `MaxResources` (default 50) to limit the rows of the table. Each object in the result links to its admin portal page, and is listed on the **Affected objects** page of the report when you run `Invoke-Maester -IncludeAffectedObjects`. + +The drift report lists only resources with drift, so Maester also reads the resources of your entitlement management catalogs. The check passes when governed groups exist and none has drift, and it is skipped when no group that is not role-assignable is a resource of a catalog. Role-assignable groups are left out: MT.1256 checks them. + +What the report covers: + +* A resource in more than one catalog is listed once, with each catalog and its own drift link; its counts are the highest of its catalogs. +* Nested group drift is not included. The report compares access package assignments only with the users directly assigned to the group. +* The report is in preview and is refreshed about once a day, so its data can be up to 24 hours old and a remediated resource keeps failing this check until the next refresh. The **Access drift data as of** timestamp on the report page shows how current the results are. + +The check needs a Microsoft Entra ID Governance or Microsoft Entra Suite licence, and is skipped without it. Maester reads the report and the catalogs with the `EntitlementManagement.Read.All` permission. With delegated access, results are limited to the catalogs the signed-in user can read; the Global Administrator, Identity Governance Administrator, Directory Reader, Reports Reader, Catalog Owner and Catalog Reader roles can view the report. + +Groups omitted from a batch response are checked individually. Only a confirmed HTTP 404 is treated as a deleted group. If Maester cannot read whether a governed group is role-assignable, the check reports **Error** rather than a result. Restore read access to the groups and run it again. + +#### Remediation action + +1. Sign in to the [Microsoft Entra admin center](https://entra.microsoft.com) and browse to **ID Governance** > **Access Guardian** > **Reports** > **Access Drift**. +2. On the **Groups** tab, sort or filter by **Unauthorized access**, and select a resource name to open its drift details, or select a catalog (πŸ“š) in the results below to open them directly. +3. For each identity with **Unauthorized access**, find out who granted the access and whether it is needed: + * If it is needed, [assign the user to an access package](https://learn.microsoft.com/entra/id-governance/entitlement-management-access-package-assignments#directly-assign-an-identity) from the drift details page. The access package picker is scoped to the resource's catalog and shows which access packages include the resource. + * If it is not needed, select **View group** and remove the group membership. +4. For users with **Missing assignments**, [reprocess their access package assignments](https://learn.microsoft.com/entra/id-governance/entitlement-management-reprocess-access-package-assignments) from the drift details page. +5. Prevent new drift: remove group owners who grant access directly, and use access reviews on the access packages. +6. Changes apply to the resource within a few minutes, but the report, and this check, show them only after the next refresh. + +#### Related links + +* [View access package drift reports](https://learn.microsoft.com/entra/id-governance/entitlement-management-reports#view-access-package-drift) +* [Directly assign an identity to an access package](https://learn.microsoft.com/entra/id-governance/entitlement-management-access-package-assignments#directly-assign-an-identity) +* [Reprocess access package assignments](https://learn.microsoft.com/entra/id-governance/entitlement-management-reprocess-access-package-assignments) +* [Microsoft Graph - List accessDriftSummary](https://learn.microsoft.com/graph/api/accessdriftsummary-list?view=graph-rest-beta) +* [What is entitlement management?](https://learn.microsoft.com/entra/id-governance/entitlement-management-overview) + + +%TestResult% diff --git a/tests/maester/entra/Test.MT.1255.ps1 b/tests/maester/entra/Test.MT.1255.ps1 new file mode 100644 index 0000000000..bbca989f10 --- /dev/null +++ b/tests/maester/entra/Test.MT.1255.ps1 @@ -0,0 +1,56 @@ +ο»Ώfunction Test-MtAccessPackageDriftGroup { + <# + .SYNOPSIS + Checks that the members of governed groups come from access package assignments. + + .DESCRIPTION + Runs the shared check Test-MtAccessPackageDrift -Scope Group. Access package drift (Microsoft Entra ID + Governance > Access Guardian, Microsoft Graph beta accessDriftSummary) compares the members of governed groups that are not role-assignable + with the access package assignments that should grant them. The check fails when one has unauthorized or missing access, + passes when groups are governed and none has drift, and is skipped when no group that is not role-assignable is a resource of an + entitlement management catalog. Role-assignable groups are checked by MT.1256. + + Learn more: + https://learn.microsoft.com/entra/id-governance/entitlement-management-reports#view-access-package-drift + + .EXAMPLE + Test-MtAccessPackageDriftGroup + + .LINK + https://maester.dev/docs/tests/MT.1255 + #> + [MaesterTest( + Id = 'MT.1255', + Title = 'Members of governed groups come from access package assignments.', + Product = 'entra', + Feature = 'identity-governance', + Area = 'identity-lifecycle', + ResourceType = 'Group', + Severity = 'Medium', + UserImpact = 'Medium', + ImplementationCost = 'Medium', + Mitre = 'T1098', + Control = 'nist-800-53-r5:AC-2', + Service = 'Graph', + License = 'Entra_Identity_Governance', + Permission = 'Graph:Scope:EntitlementManagement.Read.All', + Lifecycle = 'Preview', + Author = 'Cloud-Architekt' + )] + [CmdletBinding()] + [OutputType([bool])] + param( + # Also fail when an access package assignment is missing its expected group membership. + # Set to $false to fail on unauthorized access only and list missing access for review. + [bool] $IncludeMissingAccess = $true, + + # Object IDs of governed groups whose drift this check ignores. + [string[]] $ExcludedResourceId, + + # Maximum number of groups listed in the result; the others are counted. + [ValidateRange(1, 1000)] + [int] $MaxResources = 50 + ) + + Test-MtAccessPackageDrift -Scope Group -IncludeMissingAccess $IncludeMissingAccess -ExcludedResourceId $ExcludedResourceId -MaxResources $MaxResources +} diff --git a/tests/maester/entra/Test.MT.1256.md b/tests/maester/entra/Test.MT.1256.md new file mode 100644 index 0000000000..fabbdd3b78 --- /dev/null +++ b/tests/maester/entra/Test.MT.1256.md @@ -0,0 +1,45 @@ +Members of governed role-assignable groups should come from access package assignments. + +When a role-assignable group is a resource in an entitlement management catalog, access to it is meant to be requested, approved, reviewed and removed through access packages. The access package drift report in **Access Guardian** compares the direct members of each governed role-assignable group with the access package assignments that should grant them, and reports two kinds of drift for users and agent IDs: + +* **Unauthorized access**: The group has members without a corresponding access package assignment. An owner or administrator added them directly, or the access was left behind when an assignment ended. This access skips the approval, access reviews and expiration of the access package, and an attacker who controls an account with rights to the role-assignable group can use it to keep access. +* **Missing assignments**: an access package assignment is active, but the expected group membership does not exist, usually because provisioning failed. + +Members of a role-assignable group can be assigned Microsoft Entra roles, through an active or eligible role assignment of the group or Privileged Identity Management for groups. Unauthorized access to such a group is privileged access that bypasses the approval and reviews you set up for it, so review these groups first. + +This check fails when a governed role-assignable group has unauthorized access or missing assignments. The result lists the role-assignable groups with drift, sorted by unauthorized access, with the number of unauthorized and missing identities and examples of the affected users (πŸ‘€), groups (πŸ‘₯), service principals (🧩) and agent identities (πŸ€–). Each catalog (πŸ“š) in the **Drift in Catalog(s)** column opens the drift details of the role-assignable group in that catalog. The report returns up to five drift records per resource, so **+N more** shows how many identities are not listed. Missing assignments usually mean that provisioning failed, so approved users lack the access they requested. To fail on unauthorized access only and list missing assignments for review, set the `IncludeMissingAccess` parameter to `$false`. Use `ExcludedResourceId` to leave out role-assignable groups, and `MaxResources` (default 50) to limit the rows of the table. Each object in the result links to its admin portal page, and is listed on the **Affected objects** page of the report when you run `Invoke-Maester -IncludeAffectedObjects`. + +The drift report lists only resources with drift, so Maester also reads the resources of your entitlement management catalogs. The check passes when governed role-assignable groups exist and none has drift, and it is skipped when no role-assignable group is a resource of a catalog. Groups that are not role-assignable are checked by MT.1255. + +What the report covers: + +* A resource in more than one catalog is listed once, with each catalog and its own drift link; its counts are the highest of its catalogs. +* Nested group drift is not included. The report compares access package assignments only with the users directly assigned to the group. +* The report is in preview and is refreshed about once a day, so its data can be up to 24 hours old and a remediated resource keeps failing this check until the next refresh. The **Access drift data as of** timestamp on the report page shows how current the results are. + +The check needs a Microsoft Entra ID Governance or Microsoft Entra Suite licence, and is skipped without it. Maester reads the report and the catalogs with the `EntitlementManagement.Read.All` permission. With delegated access, results are limited to the catalogs the signed-in user can read; the Global Administrator, Identity Governance Administrator, Directory Reader, Reports Reader, Catalog Owner and Catalog Reader roles can view the report. + +Groups omitted from a batch response are checked individually. Only a confirmed HTTP 404 is treated as a deleted group. If Maester cannot read whether a governed group is role-assignable, the check reports **Error** rather than a result. Restore read access to the groups and run it again. + +#### Remediation action + +1. Sign in to the [Microsoft Entra admin center](https://entra.microsoft.com) and browse to **ID Governance** > **Access Guardian** > **Reports** > **Access Drift**. +2. On the **Groups** tab, sort or filter by **Unauthorized access**, and select a resource name to open its drift details, or select a catalog (πŸ“š) in the results below to open them directly. +3. For each identity with **Unauthorized access**, find out who granted the access and whether it is needed: + * If it is needed, [assign the user to an access package](https://learn.microsoft.com/entra/id-governance/entitlement-management-access-package-assignments#directly-assign-an-identity) from the drift details page. The access package picker is scoped to the resource's catalog and shows which access packages include the resource. + * If it is not needed, select **View group** and remove the group membership. +4. For users with **Missing assignments**, [reprocess their access package assignments](https://learn.microsoft.com/entra/id-governance/entitlement-management-reprocess-access-package-assignments) from the drift details page. +5. Prevent new drift: remove group owners who grant access directly, and use access reviews on the access packages. +6. Changes apply to the resource within a few minutes, but the report, and this check, show them only after the next refresh. + +#### Related links + +* [View access package drift reports](https://learn.microsoft.com/entra/id-governance/entitlement-management-reports#view-access-package-drift) +* [Directly assign an identity to an access package](https://learn.microsoft.com/entra/id-governance/entitlement-management-access-package-assignments#directly-assign-an-identity) +* [Reprocess access package assignments](https://learn.microsoft.com/entra/id-governance/entitlement-management-reprocess-access-package-assignments) +* [Microsoft Graph - List accessDriftSummary](https://learn.microsoft.com/graph/api/accessdriftsummary-list?view=graph-rest-beta) +* [Use Microsoft Entra groups to manage role assignments](https://learn.microsoft.com/entra/identity/role-based-access-control/groups-concept) +* [What is entitlement management?](https://learn.microsoft.com/entra/id-governance/entitlement-management-overview) + + +%TestResult% diff --git a/tests/maester/entra/Test.MT.1256.ps1 b/tests/maester/entra/Test.MT.1256.ps1 new file mode 100644 index 0000000000..fe8b6a4409 --- /dev/null +++ b/tests/maester/entra/Test.MT.1256.ps1 @@ -0,0 +1,56 @@ +ο»Ώfunction Test-MtAccessPackageDriftRoleAssignableGroup { + <# + .SYNOPSIS + Checks that the members of governed role-assignable groups come from access package assignments. + + .DESCRIPTION + Runs the shared check Test-MtAccessPackageDrift -Scope RoleAssignableGroup. Access package drift (Microsoft Entra ID + Governance > Access Guardian, Microsoft Graph beta accessDriftSummary) compares the members of governed role-assignable groups + with the access package assignments that should grant them. The check fails when one has unauthorized or missing access, + passes when role-assignable groups are governed and none has drift, and is skipped when no role-assignable group is a resource of an + entitlement management catalog. Members of role-assignable groups can be assigned Microsoft Entra roles, so unauthorized access is privileged access. + + Learn more: + https://learn.microsoft.com/entra/id-governance/entitlement-management-reports#view-access-package-drift + + .EXAMPLE + Test-MtAccessPackageDriftRoleAssignableGroup + + .LINK + https://maester.dev/docs/tests/MT.1256 + #> + [MaesterTest( + Id = 'MT.1256', + Title = 'Members of governed role-assignable groups come from access package assignments.', + Product = 'entra', + Feature = 'identity-governance', + Area = 'privileged-access', + ResourceType = 'Group', + Severity = 'Medium', + UserImpact = 'Medium', + ImplementationCost = 'Medium', + Mitre = 'T1098.003', + Control = ('nist-800-53-r5:AC-2', 'nist-800-53-r5:AC-6(5)'), + Service = 'Graph', + License = 'Entra_Identity_Governance', + Permission = 'Graph:Scope:EntitlementManagement.Read.All', + Lifecycle = 'Preview', + Author = 'Cloud-Architekt' + )] + [CmdletBinding()] + [OutputType([bool])] + param( + # Also fail when an access package assignment is missing its expected group membership. + # Set to $false to fail on unauthorized access only and list missing access for review. + [bool] $IncludeMissingAccess = $true, + + # Object IDs of governed role-assignable groups whose drift this check ignores. + [string[]] $ExcludedResourceId, + + # Maximum number of role-assignable groups listed in the result; the others are counted. + [ValidateRange(1, 1000)] + [int] $MaxResources = 50 + ) + + Test-MtAccessPackageDrift -Scope RoleAssignableGroup -IncludeMissingAccess $IncludeMissingAccess -ExcludedResourceId $ExcludedResourceId -MaxResources $MaxResources +} diff --git a/tests/maester/entra/Test.MT.1257.md b/tests/maester/entra/Test.MT.1257.md new file mode 100644 index 0000000000..3931f7f730 --- /dev/null +++ b/tests/maester/entra/Test.MT.1257.md @@ -0,0 +1,40 @@ +App role assignments of governed applications should come from access package assignments. + +When an enterprise application is a resource in an entitlement management catalog, access to it is meant to be requested, approved, reviewed and removed through access packages. The access package drift report in **Access Guardian** compares the app role assignments of each governed enterprise application with the access package assignments that should grant them, and reports two kinds of drift for users and agent IDs: + +* **Unauthorized access**: The application has app role assignments without a corresponding access package assignment. An owner or administrator added them directly, or the access was left behind when an assignment ended. This access skips the approval, access reviews and expiration of the access package, and an attacker who controls an account with rights to the enterprise application can use it to keep access. +* **Missing assignments**: an access package assignment is active, but the expected app role assignment does not exist, usually because provisioning failed. + +This check fails when a governed application has unauthorized access or missing assignments. The result lists the applications with drift, sorted by unauthorized access, with the number of unauthorized and missing identities and examples of the affected users (πŸ‘€), groups (πŸ‘₯), service principals (🧩) and agent identities (πŸ€–). Each catalog (πŸ“š) in the **Drift in Catalog(s)** column opens the drift details of the enterprise application in that catalog. The report returns up to five drift records per resource, so **+N more** shows how many identities are not listed. Missing assignments usually mean that provisioning failed, so approved users lack the access they requested. To fail on unauthorized access only and list missing assignments for review, set the `IncludeMissingAccess` parameter to `$false`. Use `ExcludedResourceId` to leave out applications, and `MaxResources` (default 50) to limit the rows of the table. Each object in the result links to its admin portal page, and is listed on the **Affected objects** page of the report when you run `Invoke-Maester -IncludeAffectedObjects`. + +The drift report lists only resources with drift, so Maester also reads the resources of your entitlement management catalogs. The check passes when governed applications exist and none has drift, and it is skipped when no enterprise application is a resource of a catalog. + +What the report covers: + +* A resource in more than one catalog is listed once, with each catalog and its own drift link; its counts are the highest of its catalogs. +* Drift between entitlement management and third-party applications, Azure roles or SharePoint sites is not included. +* The report is in preview and is refreshed about once a day, so its data can be up to 24 hours old and a remediated resource keeps failing this check until the next refresh. The **Access drift data as of** timestamp on the report page shows how current the results are. + +The check needs a Microsoft Entra ID Governance or Microsoft Entra Suite licence, and is skipped without it. Maester reads the report and the catalogs with the `EntitlementManagement.Read.All` permission. With delegated access, results are limited to the catalogs the signed-in user can read; the Global Administrator, Identity Governance Administrator, Directory Reader, Reports Reader, Catalog Owner and Catalog Reader roles can view the report. + +#### Remediation action + +1. Sign in to the [Microsoft Entra admin center](https://entra.microsoft.com) and browse to **ID Governance** > **Access Guardian** > **Reports** > **Access Drift**. +2. On the **Applications** tab, sort or filter by **Unauthorized access**, and select a resource name to open its drift details, or select a catalog (πŸ“š) in the results below to open them directly. +3. For each identity with **Unauthorized access**, find out who granted the access and whether it is needed: + * If it is needed, [assign the user to an access package](https://learn.microsoft.com/entra/id-governance/entitlement-management-access-package-assignments#directly-assign-an-identity) from the drift details page. The access package picker is scoped to the resource's catalog and shows which access packages include the resource. + * If it is not needed, select **View application** and remove the app role assignment. +4. For users with **Missing assignments**, [reprocess their access package assignments](https://learn.microsoft.com/entra/id-governance/entitlement-management-reprocess-access-package-assignments) from the drift details page. +5. Prevent new drift: remove application owners who grant access directly, and use access reviews on the access packages. +6. Changes apply to the resource within a few minutes, but the report, and this check, show them only after the next refresh. + +#### Related links + +* [View access package drift reports](https://learn.microsoft.com/entra/id-governance/entitlement-management-reports#view-access-package-drift) +* [Directly assign an identity to an access package](https://learn.microsoft.com/entra/id-governance/entitlement-management-access-package-assignments#directly-assign-an-identity) +* [Reprocess access package assignments](https://learn.microsoft.com/entra/id-governance/entitlement-management-reprocess-access-package-assignments) +* [Microsoft Graph - List accessDriftSummary](https://learn.microsoft.com/graph/api/accessdriftsummary-list?view=graph-rest-beta) +* [What is entitlement management?](https://learn.microsoft.com/entra/id-governance/entitlement-management-overview) + + +%TestResult% diff --git a/tests/maester/entra/Test.MT.1257.ps1 b/tests/maester/entra/Test.MT.1257.ps1 new file mode 100644 index 0000000000..ac15eea73a --- /dev/null +++ b/tests/maester/entra/Test.MT.1257.ps1 @@ -0,0 +1,56 @@ +ο»Ώfunction Test-MtAccessPackageDriftApplication { + <# + .SYNOPSIS + Checks that the app role assignments of governed applications come from access package assignments. + + .DESCRIPTION + Runs the shared check Test-MtAccessPackageDrift -Scope Application. Access package drift (Microsoft Entra ID + Governance > Access Guardian, Microsoft Graph beta accessDriftSummary) compares the app role assignments of governed enterprise applications + with the access package assignments that should grant them. The check fails when one has unauthorized or missing access, + passes when applications are governed and none has drift, and is skipped when no enterprise application is a resource of an + entitlement management catalog. + + Learn more: + https://learn.microsoft.com/entra/id-governance/entitlement-management-reports#view-access-package-drift + + .EXAMPLE + Test-MtAccessPackageDriftApplication + + .LINK + https://maester.dev/docs/tests/MT.1257 + #> + [MaesterTest( + Id = 'MT.1257', + Title = 'App role assignments of governed applications come from access package assignments.', + Product = 'entra', + Feature = 'identity-governance', + Area = 'identity-lifecycle', + ResourceType = 'ServicePrincipal', + Severity = 'Medium', + UserImpact = 'Medium', + ImplementationCost = 'Medium', + Mitre = 'T1098', + Control = 'nist-800-53-r5:AC-2', + Service = 'Graph', + License = 'Entra_Identity_Governance', + Permission = 'Graph:Scope:EntitlementManagement.Read.All', + Lifecycle = 'Preview', + Author = 'Cloud-Architekt' + )] + [CmdletBinding()] + [OutputType([bool])] + param( + # Also fail when an access package assignment is missing its expected app role assignment. + # Set to $false to fail on unauthorized access only and list missing access for review. + [bool] $IncludeMissingAccess = $true, + + # Object IDs of governed applications whose drift this check ignores. + [string[]] $ExcludedResourceId, + + # Maximum number of applications listed in the result; the others are counted. + [ValidateRange(1, 1000)] + [int] $MaxResources = 50 + ) + + Test-MtAccessPackageDrift -Scope Application -IncludeMissingAccess $IncludeMissingAccess -ExcludedResourceId $ExcludedResourceId -MaxResources $MaxResources +} diff --git a/tests/maester/entra/Test.MT.1258.md b/tests/maester/entra/Test.MT.1258.md new file mode 100644 index 0000000000..5fc043b73b --- /dev/null +++ b/tests/maester/entra/Test.MT.1258.md @@ -0,0 +1,92 @@ +Only allowlisted tenants should administer this tenant through **GDAP or Microsoft Entra Tenant Governance**. + +Both features create a trust path into your tenant: an attacker who compromises a governing tenant or GDAP partner can use its delegated privileges. This check compares the following tenants with the [`DelegatedAdminTenants`](https://maester.dev/docs/configuration/delegated-admin-tenants) allowlist: + +* **Tenant Governance:** governing tenants of relationships in which your tenant is governed and that are not terminated. A relationship whose termination was requested (`terminationRequestedByGoverningTenant`) still grants its roles, so it counts. Relationships in which your tenant governs another tenant are outbound and not assessed. +* **GDAP:** partner tenants identified through Microsoft Graph's **remote tenant groups**, excluding tenants already identified through Tenant Governance. These groups are exposed after delegated privileges are established through Partner Center or Tenant Governance. + +The customer-side APIs do not expose the complete GDAP relationship inventory, its authorized roles, expiration dates or auto-extension settings. A relationship that exposes no remote tenant groups cannot be identified as GDAP by this check. Review the [Partner relationships](https://go.microsoft.com/fwlink/p/?linkid=2074649) page for the full inventory. A passing result is limited to the relationships visible through these sources. + +#### Why remote tenant groups identify GDAP partners + +To the best of current knowledge, remote tenant groups are the strongest signal visible from the customer tenant that **names** a GDAP partner, so this check uses them as its only GDAP anchor. Other signals were considered and not used for the verdict: + +| Signal in your tenant | Names the partner | Why it is not the anchor | +| --- | --- | --- | +| **Remote tenant groups** (chosen) | Yes, tenant and group | Microsoft documents them as discoverable once delegated admin is set up through Partner Center or Tenant Governance. Whether they are removed when a relationship ends is not documented. | +| GDAP service principal *Partner customer delegated admin offline processor* (`a3475900-ccec-4a69-98f5-a65cd5dc5306`) | No | Documented to be removed when the **last** GDAP relationship ends, but it exists once per tenant and does not say which partner the relationship is with. | +| GDAP service principal *Partner customer delegated administration* (`2832473f-ec63-45fb-976f-5d45a7d4bb91`) | No | Required when a GDAP relationship is accepted, and it sets up the service-provider mark in the cross-tenant access settings. It exists once per tenant, does not name the partner, and is not documented to be removed when relationships end. | +| Cross-tenant access service-provider mark (`isServiceProvider`) | Yes | Set when a GDAP relationship is accepted, but it can remain after the relationship ends. | +| CSP partner list (`directory/partners`) | Yes | Describes reseller and legacy DAP partnerships, not GDAP. | +| GDAP relationships (`delegatedAdminRelationships`) | Yes | Readable only by the partner's tenant. | + +If Microsoft adds a customer-side API for GDAP relationships, it should replace this anchor. + +Source for both GDAP service principals: [GDAP FAQ for customers: What are the two Microsoft Entra GDAP service principals that are created in the customer's tenant?](https://learn.microsoft.com/partner-center/customers/gdap-migration-faq#what-are-the-two-microsoft-entra-gdap-service-principals-that-are-created-in-the-customer-s-tenant-) + +**Outside the verdict:** legacy DAP, CSP partner metadata, unrelated foreign Microsoft Entra role assignments, inbound sign-in activity, and cross-tenant access service-provider marks. In particular, a service-provider mark can remain after a relationship ends; it does not prove that GDAP is active, even alongside partner metadata or role assignments. + +#### Allowlist and results + +List approved governing and GDAP partner tenant IDs in `GlobalSettings`: + +```json +{ + "GlobalSettings": { + "DelegatedAdminTenants": [ + "00000000-0000-0000-0000-000000000000", + "11111111-1111-1111-1111-111111111111" + ] + } +} +``` + +Without an allowlist, every tenant identified through an in-scope relationship fails. Allowlisted relationships are counted rather than listed in the assessment tables. Known privileged roles are highlighted to help prioritize review; role information does not independently establish a relationship. + +The report includes: + +* **Tenant Governance:** inbound relationships that are not terminated, with any pending termination flagged, policy roles, provisioned applications, creation time and approval information where available. +* **GDAP and informational CSP partners:** GDAP remote groups, visible roles and partner metadata. Legacy DAP roles and partners without GDAP evidence are explicitly informational. +* **Service providers in cross-tenant access settings:** informational entries only, including former governance tenants with a leftover mark. +* **Related tenants with inbound admin app sign-ins:** optional informational metrics, including activity from allowlisted tenants. + +If either the governance-relationship source or the remote-tenant-group source cannot be read, an otherwise passing result becomes **Investigate**. A former governing tenant with remote groups still exposed also needs investigation because the groups' origin cannot be distinguished from GDAP. A leftover service-provider mark or CSP partner record alone does not require investigation. A known unallowlisted in-scope tenant still produces **Failed** even if another source is unavailable. + +#### Optional tenant discovery + +`IncludeTenantDiscovery` defaults to `true`. Discovery runs only when a **Microsoft Entra ID Governance** service plan is available. If the licence is absent or cannot be confirmed, the discovery request is skipped and the report explains why. The relationship assessment still runs. + +Discovery must also be enabled under **Tenant governance** > **Related tenants**. Its **Admin app sign-ins (inbound)** metrics show the number of inbound users and predefined Microsoft administrative applications in the last month, not all B2B collaboration activity. Missing metrics are shown as unavailable, not as evidence of no activity. Discovery failures never change the verdict. + +To disable the optional requests: + +```json +{ + "TestSettings": [ + { "Id": "MT.1258", "Parameters": { "IncludeTenantDiscovery": false } } + ] +} +``` + +The assessment needs `Directory.Read.All`, `TenantGovernance-Relationship.Read.All` and `RemoteTenantGroups.Read.All`. Optional enrichment uses `TenantGovernance-RelatedTenant.Read.All` for discovery, `CrossTenantInformation.ReadBasic.All` for tenant names, `Policy.Read.All` for service-provider information, `RoleManagement.Read.Directory` (or `RoleManagement.Read.All`) for role details, and `AuditLog.Read.All` for approval history. These scopes are included in `Get-MtGraphScope -IncludePreview`. Unavailable enrichment is reported without changing the assessment. + +#### Remediation action + +1. For each unallowlisted **GDAP partner or governing tenant**, confirm whether it should administer your tenant. Add its tenant ID to `DelegatedAdminTenants` only if approved. +2. For **Tenant Governance**, open the [Microsoft Entra admin center](https://entra.microsoft.com), then **Tenant governance** > **Governing tenants**. Review granted roles and provisioned applications. Terminate unnecessary relationships where the policy permits, or ask the governing tenant to terminate them. +3. For **GDAP**, open [Partner relationships](https://go.microsoft.com/fwlink/p/?linkid=2074649) in the Microsoft 365 admin center under **Settings**. Review each relationship's roles and expiration; remove unnecessary delegated access or ask the partner to reduce privileges. +4. For an **Investigate** result, restore access to unreadable assessment sources or verify the former governing tenant's relationship on the Partner relationships page, then rerun the check. + +Legacy DAP and stale service-provider configurations warrant a separate review, but are not failures of this GDAP/Tenant Governance check. Treat reports as confidential: they contain administrative relationships, role details, partner contacts and activity metrics. + +#### Related links + +* [Governance relationships in Microsoft Entra Tenant Governance](https://learn.microsoft.com/entra/id-governance/tenant-governance/governance-relationships) +* [Introduction to granular delegated admin privileges (GDAP)](https://learn.microsoft.com/partner-center/customers/gdap-introduction) +* [Customer-led removal of a GDAP relationship](https://learn.microsoft.com/partner-center/customers/gdap-customer-terminate) +* [Microsoft Graph remote tenant groups](https://learn.microsoft.com/graph/api/resources/remotetenantgroup?view=graph-rest-beta) +* [GDAP FAQ for customers: GDAP service principals in the customer tenant](https://learn.microsoft.com/partner-center/customers/gdap-migration-faq#what-are-the-two-microsoft-entra-gdap-service-principals-that-are-created-in-the-customer-s-tenant-) +* [Signals and metrics for tenant discovery](https://learn.microsoft.com/entra/id-governance/tenant-governance/signals-metrics) + + +%TestResult% diff --git a/tests/maester/entra/Test.MT.1258.ps1 b/tests/maester/entra/Test.MT.1258.ps1 new file mode 100644 index 0000000000..0043b130ab --- /dev/null +++ b/tests/maester/entra/Test.MT.1258.ps1 @@ -0,0 +1,617 @@ +ο»Ώfunction Test-MtCrossTenantAdministrationRelationship { + <# + .SYNOPSIS + Checks that only allowlisted tenants administer this tenant through Tenant Governance or GDAP. + + .DESCRIPTION + Two features let administrators of another Microsoft Entra tenant act in this tenant: + + - Microsoft Entra Tenant Governance: a governance relationship that is not terminated, in which this tenant is the governed + tenant. Its policy assigns Microsoft Entra roles to groups of the governing tenant and can provision + multitenant applications with their permissions. + - Granular delegated admin privileges (GDAP): a Cloud Solution Provider (CSP) partner with a delegated admin + relationship. The partner appears as a service provider in the cross-tenant access settings, and its + security groups hold Microsoft Entra roles in this tenant. + + Governing tenants (any relationship status except terminated) and GDAP partner tenants identified through remote tenant groups must be listed in + DelegatedAdminTenants. Without the setting no tenant is allowlisted. Legacy DAP, unrelated foreign role + assignments and cross-tenant service provider marks do not affect the verdict. The service provider mark can + remain after a relationship ends and is shown only for information. + + Remote tenant groups are, to the best of current knowledge, the strongest customer-side signal that names a GDAP + partner, so they are the only GDAP anchor. The two GDAP service principals that Microsoft creates in the customer + tenant do not name the partner either: "Partner customer delegated admin offline processor" + (a3475900-ccec-4a69-98f5-a65cd5dc5306) is documented to be removed when the last GDAP relationship ends, and + "Partner customer delegated administration" (2832473f-ec63-45fb-976f-5d45a7d4bb91) is required when a + relationship is accepted and sets up the service provider mark. The delegatedAdminRelationships API is readable + only by the partner. The .md compares the signals. Source: + https://learn.microsoft.com/partner-center/customers/gdap-migration-faq#what-are-the-two-microsoft-entra-gdap-service-principals-that-are-created-in-the-customer-s-tenant- + + Related tenant discovery optionally enriches the result with inbound admin-app user and application counts. + It is enabled by default and is skipped when Microsoft Entra ID Governance licensing cannot be confirmed. + Discovery and other enrichment failures are reported but do not affect the verdict. An unreadable governance + relationship or remote tenant group source makes an otherwise passing result Investigate. Remote groups of a + former governing tenant also need investigation because their GDAP origin cannot be confirmed. + + Learn more: + https://learn.microsoft.com/entra/id-governance/tenant-governance/governance-relationships + https://learn.microsoft.com/partner-center/customers/gdap-introduction + + .EXAMPLE + Test-MtCrossTenantAdministrationRelationship + + .LINK + https://maester.dev/docs/tests/MT.1258 + #> + [MaesterTest( + Id = 'MT.1258', + Title = 'Only allowlisted tenants can administer this tenant through GDAP or Tenant Governance.', + Product = 'entra', + Feature = 'external-identities', + Area = 'privileged-access', + ResourceType = 'Tenant', + Severity = 'Medium', + UserImpact = 'Low', + ImplementationCost = 'Low', + Mitre = 'T1199', + Control = 'nist-800-53-r5:AC-6(5)', + Service = 'Graph', + Permission = ('Graph:Scope:Directory.Read.All', 'Graph:Scope:TenantGovernance-Relationship.Read.All', 'Graph:Scope:RemoteTenantGroups.Read.All'), + Cloud = ('Commercial', 'GCC'), + Lifecycle = 'Preview', + Author = 'Cloud-Architekt' + )] + [CmdletBinding()] + [OutputType([bool])] + param( + # Include informational inbound admin-app user and application counts when Governance licensing is available. + [bool] $IncludeTenantDiscovery = $true + ) + + # Tenant Governance and remote tenant groups are only available in the worldwide Microsoft Graph service. The Cloud + # attribute is enforced only when the run config turns it on, so the check also skips itself outside Global. + $graphEnvironment = (Get-MgContext).Environment + if ($graphEnvironment -and $graphEnvironment -ne 'Global') { + Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Tenant Governance is not available in the $graphEnvironment cloud." + return $null + } + + $entraPortal = $__MtSession.AdminPortalUrl.Entra + $nowUtc = (Get-Date).ToUniversalTime() + # Microsoft 365 admin center > Settings > Partner relationships (the fwlink Microsoft documents for customers). + $partnerRelationshipsUrl = 'https://go.microsoft.com/fwlink/p/?linkid=2074649' + + $describeError = { + param($ErrorRecord) + $statusCode = if ($ErrorRecord.Exception.Response) { [int]$ErrorRecord.Exception.Response.StatusCode } else { $null } + $message = ("$($ErrorRecord.Exception.Message)" -split '\r?\n')[0].TrimEnd('.', ' ') + if ($message.Length -gt 160) { $message = $message.Substring(0, 160) + '…' } + [pscustomobject]@{ + StatusCode = $statusCode + Text = "$(if ($statusCode) { "HTTP $($statusCode): " })$message" -replace '\|', '\|' + } + } + $toUtc = { + param($Value) + if ($Value -is [datetime]) { return $Value.ToUniversalTime() } + if ($Value -is [datetimeoffset]) { return $Value.UtcDateTime } + $parsed = [datetimeoffset]::MinValue + if ($Value -and [datetimeoffset]::TryParse("$Value", [cultureinfo]::InvariantCulture, [System.Globalization.DateTimeStyles]::AssumeUniversal, [ref]$parsed)) { + return $parsed.UtcDateTime + } + return $null + } + $formatDate = { + param($Value) + $date = & $toUtc $Value + if (-not $date) { return 'Unknown' } + $days = [int][math]::Floor(($nowUtc - $date).TotalDays) + $age = if ($days -lt 1) { 'today' } elseif ($days -eq 1) { '1 day ago' } else { "$days days ago" } + "$($date.ToString('yyyy-MM-dd', [cultureinfo]::InvariantCulture)) ($age)" + } + + $ownTenantId = "$(@(Invoke-MtGraphRequest -RelativeUri 'organization' -Select 'id')[0].id)" + $sourceErrors = [System.Collections.Generic.List[object]]::new() + $informationErrors = [System.Collections.Generic.List[object]]::new() + + # Tenant Governance: relationships that are not terminated in which this tenant is governed. Every tenant that takes part in a + # governance relationship, whatever its status, is remembered: governance relationships use cross-tenant GDAP, + # so the cross-tenant access settings mark those tenants as service providers too, even after termination. + $governance = @() + $formerGoverningIds = @() + $governanceTenantIds = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) + try { + $allGovernance = @(Invoke-MtGraphRequest -RelativeUri 'directory/tenantGovernance/governanceRelationships' -ApiVersion beta -ErrorAction Stop) + foreach ($relationship in $allGovernance) { + foreach ($tenantId in @("$($relationship.governingTenantId)", "$($relationship.governedTenantId)") | Where-Object { $_ -and $_ -ne $ownTenantId }) { + $null = $governanceTenantIds.Add($tenantId) + } + } + # Only a terminated relationship has ended: one whose termination is requested still grants its roles, and + # an unknown future status is treated as current rather than silently passing. + $governance = @($allGovernance | + Where-Object { $_.status -ne 'terminated' -and "$($_.governedTenantId)" -eq $ownTenantId -and "$($_.governingTenantId)" -ne $ownTenantId } | + Sort-Object -Property { & $toUtc $_.creationDateTime }) + # Tenants that governed this tenant only in relationships that have been terminated. + $activeGoverningIds = @($governance | ForEach-Object { "$($_.governingTenantId)" }) + $formerGoverningIds = @($allGovernance | + Where-Object { $_.status -eq 'terminated' -and "$($_.governedTenantId)" -eq $ownTenantId -and $_.governingTenantId -and "$($_.governingTenantId)" -ne $ownTenantId } | + ForEach-Object { "$($_.governingTenantId)" } | Where-Object { $_ -notin $activeGoverningIds } | Select-Object -Unique) + } catch { + $sourceErrors.Add([pscustomobject]@{ Source = 'Tenant Governance relationships'; Error = (& $describeError $_) }) + } + + # Service provider marks can outlive the relationship and never determine the verdict. + $allServiceProviderIds = @() + try { + $allServiceProviderIds = @(Invoke-MtGraphRequest -RelativeUri 'policies/crossTenantAccessPolicy/partners' -ApiVersion v1.0 -ErrorAction Stop | + Where-Object { $_.isServiceProvider -eq $true -and $_.tenantId -and "$($_.tenantId)" -ne $ownTenantId } | ForEach-Object { "$($_.tenantId)" } | Select-Object -Unique) + } catch { + $informationErrors.Add([pscustomobject]@{ Source = 'cross-tenant access partners'; Error = (& $describeError $_) }) + } + + # Partner metadata and legacy DAP roles are informational, not evidence of GDAP. + $directoryPartners = @() + try { + $directoryPartners = @(Invoke-MtGraphRequest -RelativeUri 'directory/partners' -ApiVersion beta -ErrorAction Stop | + Where-Object { $_.partnerTenantId -and "$($_.partnerTenantId)" -ne $ownTenantId }) + } catch { + $informationErrors.Add([pscustomobject]@{ Source = 'CSP partner information'; Error = (& $describeError $_) }) + } + + # Groups of other tenants that hold access in this tenant, such as the admin groups of a GDAP partner. They + # name the group and its tenant for the role assignments below. + $remoteGroupById = @{} + try { + foreach ($remoteGroup in @(Invoke-MtGraphRequest -RelativeUri 'directory/remoteTenantGroups' -ApiVersion beta -ErrorAction Stop)) { + foreach ($key in @("$($remoteGroup.id)", "$($remoteGroup.remoteGroupId)") | Where-Object { $_ }) { $remoteGroupById[$key] = $remoteGroup } + } + } catch { + $sourceErrors.Add([pscustomobject]@{ Source = 'remote tenant groups'; Error = (& $describeError $_) }) + } + + # Directory roles held by principals of another tenant: the groups of a GDAP partner or a governing tenant. A + # principal belongs to another tenant when principalOrganizationId names it, or when it is a remote tenant group. + $foreignAssignments = @() + $roleNames = @{} + $privilegedRoles = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) + try { + $foreignAssignments = @(Invoke-MtGraphRequest -RelativeUri 'roleManagement/directory/roleAssignments' -ApiVersion beta ` + -Select 'id', 'principalId', 'principalOrganizationId', 'roleDefinitionId', 'directoryScopeId' -ErrorAction Stop | ForEach-Object { + $foreignTenantId = if ($_.principalOrganizationId -and "$($_.principalOrganizationId)" -ne $ownTenantId) { "$($_.principalOrganizationId)" } + elseif ($remoteGroupById.ContainsKey("$($_.principalId)")) { "$($remoteGroupById["$($_.principalId)"].remoteTenantId)" } + else { $null } + if ($foreignTenantId) { + [pscustomobject]@{ TenantId = $foreignTenantId; principalId = "$($_.principalId)"; roleDefinitionId = "$($_.roleDefinitionId)"; directoryScopeId = $_.directoryScopeId } + } + }) + foreach ($definition in @(Invoke-MtGraphRequest -RelativeUri 'roleManagement/directory/roleDefinitions' -ApiVersion beta ` + -Select 'id', 'templateId', 'displayName', 'isPrivileged' -ErrorAction Stop)) { + foreach ($key in @($definition.id, $definition.templateId) | Where-Object { $_ }) { + $roleNames[$key] = $definition.displayName + if ($definition.isPrivileged -eq $true) { $null = $privilegedRoles.Add($key) } + } + } + } catch { + $informationErrors.Add([pscustomobject]@{ Source = 'directory role information'; Error = (& $describeError $_) }) + } + + # Admin app sign-ins: Tenant Governance related tenant discovery reports, per related tenant, how many users of + # that tenant signed in to the predefined Microsoft admin portals of this tenant in the last month. Discovery + # needs Microsoft Entra ID Governance (service plan Entra_Identity_Governance) and must be turned on. + $hasGovernanceLicense = $false + $licenseError = $null + if ($IncludeTenantDiscovery) { + try { + $hasGovernanceLicense = @(Invoke-MtGraphRequest -RelativeUri 'subscribedSkus' -ErrorAction Stop | Where-Object { $_.capabilityStatus -eq 'Enabled' } | + ForEach-Object { $_.servicePlans.servicePlanId }) -contains 'e866a266-3cff-43a3-acca-0c90a7e00c8b' + } catch { + $licenseError = & $describeError $_ + } + } + $adminSignIns = @{} + $relatedTenantIds = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) + $microsoftTenantIds = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) + $relatedError = $null + $related = @() + if ($IncludeTenantDiscovery -and $hasGovernanceLicense) { + try { + $related = @(Invoke-MtGraphRequest -RelativeUri 'directory/tenantGovernance/relatedTenants' -ApiVersion v1.0 -ErrorAction Stop | Where-Object { $_.id }) + } catch { + $relatedError = & $describeError $_ + } + } + foreach ($relatedTenant in $related) { + $null = $relatedTenantIds.Add("$($relatedTenant.id)") + if ($relatedTenant.isMicrosoftInfrastructure -eq $true) { $null = $microsoftTenantIds.Add("$($relatedTenant.id)") } + $metrics = $relatedTenant.appB2BSignInActivityMetrics + $snapshot = if ($metrics.recent) { $metrics.recent } elseif ($metrics.initial) { $metrics.initial } else { $null } + if ($snapshot) { $adminSignIns["$($relatedTenant.id)"] = $snapshot } + } + $adminSignInsUnavailable = if (-not $IncludeTenantDiscovery) { + 'tenant discovery is disabled by IncludeTenantDiscovery' + } elseif ($licenseError) { + "tenant discovery was skipped because Governance licensing could not be confirmed ($($licenseError.Text))" + } elseif (-not $hasGovernanceLicense) { + 'tenant discovery was skipped because the tenant has no Microsoft Entra ID Governance licence' + } elseif ($relatedError) { + "the related tenants could not be read ($($relatedError.Text))" + } elseif ($related.Count -eq 0) { + 'Tenant Governance reports no related tenants. Related tenant discovery may not be turned on (**Tenant governance** > **Related tenants**)' + } else { $null } + $formatAdminSignIns = { + param([string] $TenantId) + if ($adminSignInsUnavailable) { return 'β€”' } + if (-not $adminSignIns.ContainsKey($TenantId)) { return 'Not available' } + $users = [int]$adminSignIns[$TenantId].inboundMonthlyTotalUsers + $apps = [int]$adminSignIns[$TenantId].inboundMonthlyTotalApplications + if ($users -eq 0 -and $apps -eq 0) { return 'None' } + "πŸ”‘ $users $(if ($users -eq 1) { 'user' } else { 'users' }) Β· $apps admin $(if ($apps -eq 1) { 'app' } else { 'apps' })" + } + $testPrivilegedRole = { + param([string] $Id, [string] $Name) + # Microsoft Graph's isPrivileged decides for the roles it returned; Maester's role table only for the others. + if ($roleNames.ContainsKey($Id)) { return $privilegedRoles.Contains($Id) } + $display = if ($Name) { $Name } else { $Id } + $roleInfo = Get-MtRoleInfo -RoleName ($display -replace '[^A-Za-z0-9]', '') + [bool]($roleInfo -and $roleInfo.IsPrivileged) + } + $formatRole = { + param([string] $Id, [string] $Name) + $display = if ($Name) { $Name } elseif ($roleNames.ContainsKey($Id)) { $roleNames[$Id] } else { $Id } + $safe = Get-MtSafeMarkdown $display + if (& $testPrivilegedRole $Id $display) { "🚨 **$safe**" } else { $safe } + } + + # Only the two assessment sources determine completeness; enrichment cannot prove a pass. + if ($sourceErrors.Count -eq 2) { + if (@($sourceErrors | Where-Object { $_.Error.StatusCode -in @(401, 403) }).Count -eq $sourceErrors.Count) { + Add-MtTestResultDetail -SkippedBecause NotAuthorized + return $null + } + throw "None of the relationship sources could be read: $(($sourceErrors | ForEach-Object { "$($_.Source) ($($_.Error.Text))" }) -join '; ')" + } + + # Display names of tenants that the relationships do not name, such as GDAP partners. + $tenantNames = @{} + foreach ($relationship in $governance) { $tenantNames["$($relationship.governingTenantId)"] = $relationship.governingTenantName } + foreach ($remoteGroup in $remoteGroupById.Values) { + if ($remoteGroup.remoteTenantId -and $remoteGroup.remoteTenantDisplayName -and -not $tenantNames["$($remoteGroup.remoteTenantId)"]) { + $tenantNames["$($remoteGroup.remoteTenantId)"] = "$($remoteGroup.remoteTenantDisplayName)$(if ($remoteGroup.remoteTenantPrimaryDomain) { " ($($remoteGroup.remoteTenantPrimaryDomain))" })" + } + } + foreach ($partner in $directoryPartners) { + if ($partner.companyName -and -not $tenantNames["$($partner.partnerTenantId)"]) { $tenantNames["$($partner.partnerTenantId)"] = $partner.companyName } + } + $lookupTenant = { + param([string] $TenantId) + if ($tenantNames.ContainsKey($TenantId) -and $tenantNames[$TenantId]) { return $tenantNames[$TenantId] } + try { + $info = Invoke-MtGraphRequest -RelativeUri "tenantRelationships/findTenantInformationByTenantId(tenantId='$TenantId')" -ApiVersion v1.0 -ErrorAction Stop + $name = if ($info.displayName) { "$($info.displayName)$(if ($info.defaultDomainName) { " ($($info.defaultDomainName))" })" } else { $null } + } catch { + Write-Verbose "Could not look up tenant $($TenantId): $($_.Exception.Message)" + $name = $null + } + $tenantNames[$TenantId] = $name + $name + } + # Allowlisted tenants: the DelegatedAdminTenants setting, like EmergencyAccessAccounts a list in the GlobalSettings + # of maester-config.json. Each entry is a tenant ID as a string. + $allowlistedTenantIds = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) + $allowlistEntries = Get-MtSetting -Name 'DelegatedAdminTenants' + foreach ($entry in @($allowlistEntries | Where-Object { $null -ne $_ -and "$_" -ne '' })) { + $parsedTenantId = [guid]::Empty + if ($entry -isnot [string] -or -not [guid]::TryParse($entry.Trim(), [ref]$parsedTenantId)) { + Write-Warning "MT.1258: an entry of the DelegatedAdminTenants setting is not a tenant ID and is ignored: $(ConvertTo-Json -InputObject $entry -Compress -Depth 3). Write each tenant ID as a string." + continue + } + # The parsed form, so that braced or unhyphenated entries match the hyphenated IDs that Graph returns. + $null = $allowlistedTenantIds.Add($parsedTenantId.ToString()) + } + $allowlistConfigured = $allowlistedTenantIds.Count -gt 0 + $formatTenant = { + param([string] $TenantId, [string] $Name, [string] $Url, [switch] $NoMarker) + $label = if ($Name) { Get-MtSafeMarkdown $Name } else { 'Unknown tenant' } + $linked = if ($Url) { "[$label]($Url)" } else { $label } + $marker = if (-not $NoMarker -and $notAllowlistedSet -and $notAllowlistedSet.Contains($TenantId)) { '❌ **Not allowlisted** Β· ' } else { '' } + "$marker🏒 $linked Β· ``$TenantId``" + } + + # The first successful change to an object that the audit log records, and who made it. Which audit activity + # approves a relationship is not confirmed, and the audit log keeps entries only within its retention (30 days by + # default), so this is shown as the first recorded change, not as proof of who approved the relationship. + # Found is $false when the log could not be read or holds no successful change for the object. + $findFirstChange = { + param([string] $TargetId) + try { + # -DisablePaging keeps the lookup to one page of 10 events, and returns the raw response: the events are in .value. + $response = Invoke-MtGraphRequest -RelativeUri 'auditLogs/directoryAudits' -ApiVersion v1.0 ` + -Filter "targetResources/any(t:t/id eq '$TargetId')" -QueryParameters @{ '$orderby' = 'activityDateTime asc'; '$top' = '10' } -DisablePaging -ErrorAction Stop + $audit = @($response.value) + } catch { + Write-Verbose "Could not read the audit log for $($TargetId): $($_.Exception.Message)" + return [pscustomobject]@{ Found = $false; Text = '_Audit log not available_' } + } + # A failed or rejected attempt did not change the object. + $entry = $audit | Where-Object { + "$($_.result)" -eq 'success' -and ($_.initiatedBy.user.userPrincipalName -or $_.initiatedBy.user.displayName -or $_.initiatedBy.app.displayName) + } | Select-Object -First 1 + if (-not $entry) { return [pscustomobject]@{ Found = $false; Text = '_No successful change found in the audit log_' } } + $who = if ($entry.initiatedBy.user.userPrincipalName) { "πŸ‘€ $(Get-MtSafeMarkdown $entry.initiatedBy.user.userPrincipalName)" } + elseif ($entry.initiatedBy.user.displayName) { "πŸ‘€ $(Get-MtSafeMarkdown $entry.initiatedBy.user.displayName)" } + else { "🧩 $(Get-MtSafeMarkdown $entry.initiatedBy.app.displayName)" } + $date = & $toUtc $entry.activityDateTime + $dateText = if ($date) { $date.ToString('yyyy-MM-dd', [cultureinfo]::InvariantCulture) } else { 'an unknown date' } + [pscustomobject]@{ Found = $true; Text = "$who Β· $(Get-MtSafeMarkdown $entry.activityDisplayName) on $dateText" } + } + + $assignmentsByTenant = @{} + foreach ($assignment in $foreignAssignments) { + $tenantId = "$($assignment.TenantId)" + if (-not $assignmentsByTenant.ContainsKey($tenantId)) { $assignmentsByTenant[$tenantId] = [System.Collections.Generic.List[object]]::new() } + $assignmentsByTenant[$tenantId].Add($assignment) + } + $formatAssignedRoles = { + param([string] $TenantId) + if ($assignmentsByTenant.ContainsKey($TenantId)) { + $byGroup = $assignmentsByTenant[$TenantId] | Group-Object -Property principalId + return @($byGroup | ForEach-Object { + $roles = @($_.Group | Sort-Object -Property roleDefinitionId -Unique | ForEach-Object { & $formatRole "$($_.roleDefinitionId)" $null } | Sort-Object) + $scopes = @($_.Group | Where-Object { $_.directoryScopeId -and $_.directoryScopeId -ne '/' }) + $group = if ($remoteGroupById.ContainsKey($_.Name) -and $remoteGroupById[$_.Name].remoteGroupDisplayName) { Get-MtSafeMarkdown $remoteGroupById[$_.Name].remoteGroupDisplayName } else { "``$($_.Name)``" } + "πŸ‘₯ $($group): $($roles -join ', ')$(if ($scopes.Count -gt 0) { ' (scoped)' })" + }) -join ' \| ' + } + # The groups of a GDAP partner are known as remote tenant groups, but their roles are not directory role + # assignments of this tenant: list the groups, and leave the roles to the Partner relationships page. + $groups = @($remoteGroupById.Values | Where-Object { "$($_.remoteTenantId)" -eq $TenantId } | Sort-Object -Property id -Unique | + ForEach-Object { if ($_.remoteGroupDisplayName) { $_.remoteGroupDisplayName } else { $_.remoteGroupId } } | Sort-Object) + if ($groups.Count -gt 0) { + return "$(@($groups | ForEach-Object { "πŸ‘₯ $(Get-MtSafeMarkdown $_)" }) -join ', ') Β· _roles shown on the [Partner relationships]($partnerRelationshipsUrl) page_" + } + '_None found_' + } + + $governingIds = @($governance | ForEach-Object { "$($_.governingTenantId)" }) + # Remote tenant groups are exposed after delegated privileges are established through Partner Center or + # Tenant Governance. Exclude governance tenants rather than using stale service provider marks to infer GDAP. + $remoteGroupTenantIds = @($remoteGroupById.Values | ForEach-Object { "$($_.remoteTenantId)" } | Where-Object { $_ } | Select-Object -Unique) + # Active governing tenants are assessed above and former governing tenants are investigated below; a tenant that + # this tenant governs has no governance path in, so its remote groups still count as GDAP. + $providerIds = @($remoteGroupTenantIds | Where-Object { $_ -ne $ownTenantId -and $_ -notin $governingIds -and $_ -notin $formerGoverningIds }) + # Tenants whose users signed in to the admin portals of this tenant, other than Microsoft's own infrastructure. + $adminActiveIds = @($adminSignIns.Keys | Where-Object { + $_ -ne $ownTenantId -and -not $microsoftTenantIds.Contains($_) -and + ([int]$adminSignIns[$_].inboundMonthlyTotalUsers -gt 0 -or [int]$adminSignIns[$_].inboundMonthlyTotalApplications -gt 0) + }) + # Privileged Microsoft Entra roles each tenant holds in this tenant: through a Tenant Governance policy, a + # directory role assignment or legacy DAP roles. GDAP roles are not visible from this tenant. + $privilegedByTenant = @{} + $markPrivileged = { + param([string] $TenantId, [string] $RoleId, [string] $RoleName) + if ($TenantId -and $RoleId -and (& $testPrivilegedRole $RoleId $RoleName)) { + if (-not $privilegedByTenant.ContainsKey($TenantId)) { $privilegedByTenant[$TenantId] = [System.Collections.Generic.List[string]]::new() } + $display = if ($RoleName) { $RoleName } elseif ($roleNames.ContainsKey($RoleId)) { $roleNames[$RoleId] } else { $RoleId } + if (-not $privilegedByTenant[$TenantId].Contains($display)) { $privilegedByTenant[$TenantId].Add($display) } + } + } + foreach ($relationship in $governance) { + foreach ($assignment in @($relationship.policySnapshot.delegatedAdministrationRoleAssignments | Where-Object { $null -ne $_ })) { + foreach ($template in @($assignment.roleTemplates | Where-Object { $null -ne $_ })) { & $markPrivileged "$($relationship.governingTenantId)" "$($template.id)" "$($template.name)" } + } + } + foreach ($tenantId in $assignmentsByTenant.Keys) { + foreach ($assignment in $assignmentsByTenant[$tenantId]) { & $markPrivileged $tenantId "$($assignment.roleDefinitionId)" $null } + } + foreach ($partner in $directoryPartners) { + foreach ($roleId in @($partner.roleIds | Where-Object { $_ })) { & $markPrivileged "$($partner.partnerTenantId)" "$roleId" $null } + } + + $accessTenantIds = @(@($governingIds) + @($providerIds) | Where-Object { $_ -and $_ -ne $ownTenantId } | Select-Object -Unique) + $notAllowlisted = @($accessTenantIds | Where-Object { -not $allowlistedTenantIds.Contains($_) }) + $notAllowlistedSet = [System.Collections.Generic.HashSet[string]]::new([string[]]@($notAllowlisted), [System.StringComparer]::OrdinalIgnoreCase) + $notAllowlistedPrivileged = @($notAllowlisted | Where-Object { $privilegedByTenant.ContainsKey($_) }) + $allowlistedWithAccess = @($accessTenantIds | Where-Object { $allowlistedTenantIds.Contains($_) }) + $allowlistedWithoutAccess = @($allowlistedTenantIds | Where-Object { $_ -notin $accessTenantIds } | Sort-Object) + $shownGovernance = @($governance | Where-Object { -not $allowlistedTenantIds.Contains("$($_.governingTenantId)") }) + $shownProviderIds = @($providerIds | Where-Object { -not $allowlistedTenantIds.Contains($_) }) + $tenantLabel = { + param([string] $TenantId) + $name = & $lookupTenant $TenantId + if ($name) { "$(Get-MtSafeMarkdown $name) ($('`{0}`' -f $TenantId))" } else { '`{0}`' -f $TenantId } + } + + if ($notAllowlisted.Count -eq 0) { + $testResultMarkdown = if ($sourceErrors.Count -gt 0) { + 'No tenant that is not allowlisted was found, but not every source could be read, so this can be incomplete.' + } elseif ($accessTenantIds.Count -eq 0) { + 'Well done. No governing tenant or GDAP partner with remote tenant groups was found. Legacy DAP and unrelated Microsoft Entra role assignments are outside this assessment.' + } else { + "Well done. All $($accessTenantIds.Count) $(if ($accessTenantIds.Count -eq 1) { 'tenant' } else { 'tenants' }) identified through GDAP or active Tenant Governance are allowlisted in ``DelegatedAdminTenants``." + } + } else { + $parts = @( + $governanceCount = @($notAllowlisted | Where-Object { $_ -in $governingIds }).Count + $partnerCount = @($notAllowlisted | Where-Object { $_ -in $providerIds }).Count + if ($governanceCount -gt 0) { "$governanceCount through Tenant Governance" } + if ($partnerCount -gt 0) { "$partnerCount through GDAP" } + ) + $testResultMarkdown = "❌ **$(if ($notAllowlisted.Count -eq 1) { '1 tenant has' } else { "$($notAllowlisted.Count) tenants have" }) delegated admin access to this tenant without being allowlisted in ``DelegatedAdminTenants``** ($($parts -join ', ')): $(@($notAllowlisted | ForEach-Object { & $tenantLabel $_ }) -join ', '). Remove the relationship if it is not needed, or add the tenant to ``DelegatedAdminTenants`` if it is allowed to administer this tenant." + if (-not $allowlistConfigured) { + $testResultMarkdown += " No tenant is allowlisted yet: list the tenants allowed to administer this tenant in the ``DelegatedAdminTenants`` setting in the ``GlobalSettings`` of ``maester-config.json``." + } + if ($notAllowlistedPrivileged.Count -gt 0) { + $privilegedText = @($notAllowlistedPrivileged | ForEach-Object { + $name = & $lookupTenant $_ + $label = if ($name) { Get-MtSafeMarkdown $name } else { '`{0}`' -f $_ } + $roles = @($privilegedByTenant[$_] | Sort-Object | ForEach-Object { Get-MtSafeMarkdown $_ }) -join ', ' + "$($label): $roles" + }) -join '; ' + $testResultMarkdown += "`n`n🚨 **Tenants that are not allowlisted hold privileged Microsoft Entra roles in this tenant ($privilegedText). An attacker who compromises such a tenant can use these roles to take over this tenant. Review them first.**" + } + } + if ($allowlistedWithAccess.Count -gt 0) { + $testResultMarkdown += "`n`nβœ… $(if ($allowlistedWithAccess.Count -eq 1) { '1 allowlisted tenant is' } else { "$($allowlistedWithAccess.Count) allowlisted tenants are" }) not listed: $(@($allowlistedWithAccess | ForEach-Object { & $tenantLabel $_ }) -join ', ')." + } + if ($allowlistedWithoutAccess.Count -gt 0) { + $allowlistedList = @($allowlistedWithoutAccess | ForEach-Object { & $tenantLabel $_ }) -join ', ' + $testResultMarkdown += "`n`nℹ️ Allowlisted in ``DelegatedAdminTenants`` but not found through active Tenant Governance or GDAP remote tenant groups: $allowlistedList. Verify the relationships before removing them from the list." + } + + # Discovery enriches the report only; report skipped or unavailable metrics even when no tenants are listed. + if ($adminSignInsUnavailable) { + $testResultMarkdown += "`n`nℹ️ **Admin app sign-ins are not available:** $adminSignInsUnavailable. This does not affect the GDAP and Tenant Governance assessment." + } else { + $watermarks = @($adminSignIns.Values | ForEach-Object { & $toUtc $_.watermarkDateTime } | Where-Object { $_ }) + $asOf = if ($watermarks.Count -gt 0) { " Data as of $(($watermarks | Sort-Object -Descending | Select-Object -First 1).ToString('yyyy-MM-dd', [cultureinfo]::InvariantCulture))." } else { '' } + $testResultMarkdown += "`n`nπŸ”‘ **Admin app sign-ins** are a **specialized subset of B2B sign-ins** that occur when users **authenticate across tenants to predefined Microsoft Entra administrative applications.** These sign-ins usually indicate cross-tenant administrative activity, not just collaboration. The column shows the inbound users and admin apps of the last month, from Tenant Governance related tenant discovery.$asOf A tenant that holds privileged roles but has no admin app sign-ins may no longer need its access." + } + foreach ($sourceError in $sourceErrors) { + $testResultMarkdown += "`n`n❔ The $($sourceError.Source) could not be read, so the list below can be incomplete ($($sourceError.Error.Text))." + } + foreach ($informationError in $informationErrors) { + $testResultMarkdown += "`n`nℹ️ The $($informationError.Source) could not be read ($($informationError.Error.Text)). This informational data does not affect the assessment." + } + $formerGoverningToVerify = @($formerGoverningIds | Where-Object { $_ -in $remoteGroupTenantIds -and -not $allowlistedTenantIds.Contains($_) } | Sort-Object) + if ($formerGoverningToVerify.Count -gt 0) { + $testResultMarkdown += "`n`n❔ **Verify $(if ($formerGoverningToVerify.Count -eq 1) { 'this former governing tenant' } else { 'these former governing tenants' }):** $(@($formerGoverningToVerify | ForEach-Object { & $tenantLabel $_ }) -join ', '). Its Tenant Governance relationship is terminated, but remote tenant groups are still exposed. Their origin cannot be distinguished from GDAP: verify the [Partner relationships]($partnerRelationshipsUrl) page. A leftover service provider mark alone does not require investigation." + } + + if ($shownGovernance.Count -gt 0) { + $testResultMarkdown += "`n`n### πŸ›οΈ Tenant Governance`n`n" + $testResultMarkdown += "| Governing tenant | Established | First recorded change (audit log) | Roles granted (governing tenant group: roles) | Apps provisioned in this tenant | Admin app sign-ins (inbound) |`n| --- | --- | --- | --- | --- | --- |`n" + foreach ($relationship in $shownGovernance) { + $tenantId = "$($relationship.governingTenantId)" + $url = if ($entraPortal) { "$($entraPortal)#view/Microsoft_Entra_TenantManagement/TenantDetails.ReactView/id/$tenantId/selectedTab/relationship" } else { $null } + $created = "$(& $formatDate $relationship.creationDateTime)$(switch ($relationship.createdType) { 'approvedByAdmin' { ' Β· approved by an admin' } 'addOnTenant' { ' Β· created as add-on tenant' } default { '' } })" + if ("$($relationship.status)" -ne 'active') { $created += " Β· ⚠️ status: $(Get-MtSafeMarkdown "$($relationship.status)") (roles remain until terminated)" } + $roles = @($relationship.policySnapshot.delegatedAdministrationRoleAssignments | Where-Object { $null -ne $_ } | ForEach-Object { + $roleList = @($_.roleTemplates | Where-Object { $null -ne $_ } | ForEach-Object { & $formatRole "$($_.id)" "$($_.name)" } | Sort-Object) + "πŸ‘₯ $(Get-MtSafeMarkdown $(if ($_.groupDisplayName) { $_.groupDisplayName } else { $_.groupId })): $($roleList -join ', ')" + }) + $apps = @($relationship.policySnapshot.multiTenantApplicationsToProvision | Where-Object { $null -ne $_ } | ForEach-Object { + $permissions = @($_.requiredResourceAccesses | ForEach-Object { $_.permissions } | Where-Object { $null -ne $_ }) + $appRoles = @($permissions | Where-Object { $_.type -eq 'role' }).Count + $scopes = @($permissions | Where-Object { $_.type -ne 'role' }).Count + $appName = if ($_.displayName) { Get-MtSafeMarkdown $_.displayName } else { "``$($_.appId)``" } + "🧩 $appName ($appRoles application, $scopes delegated permissions)" + }) + $rolesText = if ($roles.Count -gt 0) { $roles -join ' \| ' } else { '_None_' } + $appsText = if ($apps.Count -gt 0) { $apps -join ' \| ' } else { '_None_' } + $testResultMarkdown += "| $(& $formatTenant $tenantId $relationship.governingTenantName $url) | $created | $((& $findFirstChange "$($relationship.id)").Text) | $rolesText | $appsText | $(& $formatAdminSignIns $tenantId) |`n" + } + } + + $informationalPartnerIds = @($directoryPartners | ForEach-Object { "$($_.partnerTenantId)" } | Where-Object { $_ -notin $accessTenantIds } | Select-Object -Unique) + $reportedPartnerIds = @(@($shownProviderIds) + @($informationalPartnerIds) | Select-Object -Unique) + if ($reportedPartnerIds.Count -gt 0) { + $partnerById = @{} + foreach ($partner in $directoryPartners) { $partnerById["$($partner.partnerTenantId)"] = $partner } + $formatPartnerType = { + param($Partner) + if (-not $Partner.companyType) { return $null } + switch ("$($Partner.companyType)") { + 'microsoftSupport' { 'Microsoft support' } + 'syndicatePartner' { 'Syndication partner' } + 'breadthPartner' { 'Breadth partner' } + 'breadthPartnerDelegatedAdmin' { 'Breadth partner with delegated admin' } + 'resellerPartnerDelegatedAdmin' { 'Reseller with delegated admin' } + 'valueAddedResellerPartnerDelegatedAdmin' { 'Value-added reseller with delegated admin' } + default { "$($Partner.companyType)" } + } + } + $testResultMarkdown += "`n### 🀝 GDAP and informational CSP partners`n`n" + $testResultMarkdown += "Only GDAP partners identified through remote tenant groups are assessed here. Legacy DAP roles and other CSP partner metadata are informational only.`n`n" + $testResultMarkdown += "| Partner tenant | Relationship | Partner groups with access (roles where visible) | Admin app sign-ins (inbound) | Partner support |`n| --- | --- | --- | --- | --- |`n" + foreach ($tenantId in @($reportedPartnerIds | Sort-Object -Property { & $lookupTenant $_ })) { + $partner = $partnerById[$tenantId] + $relationship = @( + $partnerType = & $formatPartnerType $partner + if ($partnerType) { "🀝 $partnerType" } + if ($tenantId -in $providerIds) { 'πŸ” GDAP (remote tenant groups exposed)' } + else { 'ℹ️ Informational only; no GDAP established by this check' } + # Legacy delegated admin privileges (DAP) give the partner standing roles such as Global Administrator. + $dapRoles = @($partner.roleIds | Where-Object { $_ }) + if ($dapRoles.Count -gt 0) { "⚠️ **Legacy DAP roles:** $(@($dapRoles | ForEach-Object { & $formatRole "$_" $null } | Sort-Object) -join ', ')" } + $firstChange = & $findFirstChange $tenantId + if ($firstChange.Found) { "πŸ“ First recorded change: $($firstChange.Text)" } + ) + $supportUrl = if ($partner.supportUrl -and "$($partner.supportUrl)" -match '^https?://') { "$($partner.supportUrl)".Replace(')', '%29') } else { $null } + $support = @( + if ($partner.supportTelephones) { "πŸ“ž $(Get-MtSafeMarkdown (@($partner.supportTelephones) -join ', '))" } + if ($partner.supportEmails) { "βœ‰οΈ $(Get-MtSafeMarkdown (@($partner.supportEmails) -join ', '))" } + if ($supportUrl) { "🌐 [Support]($supportUrl)" } + ) + $relationshipText = if ($relationship.Count -gt 0) { $relationship -join ' Β· ' } else { '_Unknown_' } + $supportText = if ($support.Count -gt 0) { $support -join ' Β· ' } else { 'β€”' } + $testResultMarkdown += "| $(& $formatTenant $tenantId (& $lookupTenant $tenantId) $partnerRelationshipsUrl) | $relationshipText | $(& $formatAssignedRoles $tenantId) | $(& $formatAdminSignIns $tenantId) | $supportText |`n" + } + $testResultMarkdown += "`nEach GDAP relationship, with its authorized roles, expiration date, auto-extend setting and status, is shown on the [Partner relationships]($partnerRelationshipsUrl) page of the Microsoft 365 admin center. Microsoft Graph returns the relationships themselves only to the partner's tenant, so this check cannot show them or link to a single relationship.`n" + } + + $crossTenantUrl = if ($entraPortal) { "$($entraPortal)#view/Microsoft_AAD_IAM/CompanyRelationshipsMenuBlade/~/CrossTenantAccessSettings/menuId/CrossTenantAccessSettings" } else { $null } + # A related tenant links to its page in Tenant governance > Related tenants; any other tenant to the cross-tenant access settings. + $relatedTenantUrl = { + param([string] $TenantId) + if ($entraPortal -and $relatedTenantIds.Contains($TenantId)) { "$($entraPortal)#view/Microsoft_Entra_TenantManagement/TenantDetails.ReactView/id/$TenantId" } else { $crossTenantUrl } + } + $adminSignInUsers = { + param([string] $TenantId) + if ($adminSignIns.ContainsKey($TenantId)) { [int]$adminSignIns[$TenantId].inboundMonthlyTotalUsers } else { 0 } + } + + if ($adminActiveIds.Count -gt 0) { + $testResultMarkdown += "`n`n### 🌐 Related tenants with inbound admin app sign-ins (information only)`n`n" + $testResultMarkdown += "Activity does not establish a GDAP or Tenant Governance relationship and does not affect the verdict. This includes allowlisted tenants.`n`n" + $testResultMarkdown += "| Tenant | Admin app sign-ins (inbound) |`n| --- | --- |`n" + foreach ($tenantId in @($adminActiveIds | Sort-Object -Property @{ Expression = { & $adminSignInUsers $_ }; Descending = $true }, @{ Expression = { $_ } })) { + $testResultMarkdown += "| $(& $formatTenant $tenantId (& $lookupTenant $tenantId) (& $relatedTenantUrl $tenantId) -NoMarker) | $(& $formatAdminSignIns $tenantId) |`n" + } + } + + # For information: every service provider of the cross-tenant access settings, with the relationship found for it. + # Neither the mark nor failure to read this table changes the verdict. + if ($allServiceProviderIds.Count -gt 0) { + $partnerIdList = @($directoryPartners | ForEach-Object { "$($_.partnerTenantId)" }) + $formatServiceProviderRelationship = { + param([string] $TenantId) + $found = @( + if ($TenantId -in $governingIds) { 'πŸ›οΈ Tenant Governance (governs this tenant)' } + elseif ($TenantId -in $formerGoverningIds) { 'πŸ›οΈ Former Tenant Governance (terminated)' } + elseif ($governanceTenantIds.Contains($TenantId)) { 'πŸ›οΈ Tenant Governance (does not govern this tenant)' } + if ($TenantId -in $partnerIdList) { '🀝 CSP partner' } + if ($TenantId -in $remoteGroupTenantIds) { 'πŸ‘₯ Partner groups known here' } + if ($assignmentsByTenant.ContainsKey($TenantId)) { 'πŸ›‘οΈ Holds Microsoft Entra roles' } + ) + $text = if ($found.Count -gt 0) { $found -join ' Β· ' } else { '_No relationship, groups or roles found: the mark may be left over from an ended relationship_' } + if ($microsoftTenantIds.Contains($TenantId)) { $text = "Ⓜ️ Microsoft infrastructure Β· $text" } + $text + } + $markOnlyCount = @($allServiceProviderIds | Where-Object { $_ -notin $accessTenantIds -and $_ -notin $partnerIdList -and -not $governanceTenantIds.Contains($_) }).Count + $crossTenantText = if ($crossTenantUrl) { "[cross-tenant access settings]($crossTenantUrl)" } else { 'cross-tenant access settings' } + $testResultMarkdown += "`n`n### ℹ️ Service providers in cross-tenant access settings`n`n" + $testResultMarkdown += "For information only: the tenants marked as service providers in the $crossTenantText. The mark can remain after a relationship ends and is never used to determine the verdict, even when other partner metadata or role assignments are present." + if ($markOnlyCount -gt 0) { + $testResultMarkdown += " $(if ($markOnlyCount -eq 1) { '1 service provider has' } else { "$markOnlyCount service providers have" }) no relationship, groups or roles here: remove the partner configuration from the cross-tenant access settings if you no longer work with it." + } + $testResultMarkdown += "`n`n| Tenant | Relationship found | Admin app sign-ins (inbound) |`n| --- | --- | --- |`n" + foreach ($tenantId in @($allServiceProviderIds | Sort-Object -Property @{ Expression = { & $adminSignInUsers $_ }; Descending = $true }, @{ Expression = { & $lookupTenant $_ } })) { + $testResultMarkdown += "| $(& $formatTenant $tenantId (& $lookupTenant $tenantId) (& $relatedTenantUrl $tenantId) -NoMarker) | $(& $formatServiceProviderRelationship $tenantId) | $(& $formatAdminSignIns $tenantId) |`n" + } + } + + # A tenant that is not allowlisted fails the check. + if ($notAllowlisted.Count -gt 0) { + Add-MtTestResultDetail -Result $testResultMarkdown + return $false + } + # No tenant failed, but a source could not be read or a former governing tenant may still have access: a person + # has to confirm the result. + if ($sourceErrors.Count -gt 0 -or $formerGoverningToVerify.Count -gt 0) { + Add-MtTestResultDetail -Result $testResultMarkdown -Investigate + return $true + } + Add-MtTestResultDetail -Result $testResultMarkdown + return $true +} diff --git a/website/docs/configuration/delegated-admin-tenants.md b/website/docs/configuration/delegated-admin-tenants.md new file mode 100644 index 0000000000..39b18fde9d --- /dev/null +++ b/website/docs/configuration/delegated-admin-tenants.md @@ -0,0 +1,57 @@ +--- +title: Delegated Admin Tenants +sidebar_position: 2.5 +--- + +# Configuring Delegated Admin Tenants + +MT.1258 assesses other Microsoft Entra tenants that administer your tenant through two paths: + +- **Tenant Governance**: a governing tenant whose governance relationship assigns Microsoft Entra roles in your tenant to its groups. +- **Granular delegated admin privileges (GDAP)**: partner tenants identified through remote tenant groups, excluding tenants already identified through Tenant Governance. To the best of current knowledge, remote tenant groups are the strongest customer-side signal that names a GDAP partner; the [MT.1258 guide](https://maester.dev/docs/tests/MT.1258) compares the other signals and explains why they were not chosen. The customer-side APIs do not expose a complete GDAP relationship inventory; verify relationships without exposed remote groups on the Microsoft 365 **Partner relationships** page. + +Each is a trust path into your tenant: an attacker who compromises the other tenant can use the roles it holds. The `DelegatedAdminTenants` setting is the allowlist for these GDAP and Tenant Governance relationships (any governance relationship that is not terminated, including one whose termination is pending). Legacy DAP, unrelated foreign Microsoft Entra role assignments and cross-tenant service-provider marks are outside this check's verdict. Service-provider marks can remain after relationships end and are shown only for information. + +## Why Configure Delegated Admin Tenants? + +Maester cannot tell a partner you work with from one you no longer know about. Listing your delegated admin tenants: + +- **Turns an inventory into a check**: a tenant that is not on the list fails the check, and the result names it. +- **Points at the risk**: the result names the privileged Microsoft Entra roles, such as Global Administrator, that a tenant that is not allowlisted holds in your tenant. +- **Documents your partners**: the list records which tenants may administer your tenant. + +Without the setting, no tenant is allowlisted, so every tenant identified through an in-scope relationship fails the check. + +## Configuration Format + +Delegated admin tenants are configured in the `GlobalSettings` section of your custom `maester-config.json` file, like the [emergency access accounts](./emergency-access-accounts.md). + +```json +{ + "GlobalSettings": { + "DelegatedAdminTenants": [ + "00000000-0000-0000-0000-000000000000", + "11111111-1111-1111-1111-111111111111" + ] + } +} +``` + +Each entry is the Microsoft Entra tenant ID of a governing or partner tenant, as a string. An entry that is not a tenant ID is ignored, with a warning. The result shows the name of each tenant, so the list does not need one. + +## Finding the Tenant IDs + +Run the check once without the setting. Its result lists identified governing tenants and GDAP partners, with their names and tenant IDs, under **Tenant Governance** and **GDAP and informational CSP partners**. Add the in-scope tenants you approve, and remove unnecessary relationships. Legacy DAP and informational CSP partners do not need to be allowlisted for this check. + +**Service providers in cross-tenant access settings** is informational only and never changes the verdict. Optional tenant discovery adds inbound admin-app user/application metrics, not additional tenants to assess. It is enabled by default, skipped when Microsoft Entra ID Governance licensing is unavailable, and can be disabled with `TestSettings` for MT.1258: `"Parameters": { "IncludeTenantDiscovery": false }`. Discovery and other enrichment failures do not affect the verdict. + +You can also find them in the admin portals: + +- **Tenant Governance**: in the [Microsoft Entra admin center](https://entra.microsoft.com), browse to **Tenant governance** > **Governing tenants**. +- **GDAP**: in the Microsoft 365 admin center, open [Partner relationships](https://go.microsoft.com/fwlink/p/?linkid=2074649) under **Settings**. + +## Tests that use this setting + +| Test | Description | +| --- | --- | +| [MT.1258](https://maester.dev/docs/tests/MT.1258) | Only allowlisted tenants can administer this tenant through GDAP or Tenant Governance. | diff --git a/website/docs/configuration/overview.md b/website/docs/configuration/overview.md index 912fb81d56..8671b2f45e 100644 --- a/website/docs/configuration/overview.md +++ b/website/docs/configuration/overview.md @@ -120,6 +120,7 @@ The following global settings are available for customization: | Setting | Description | Documentation | |---------|-------------|---------------| | `EmergencyAccessAccounts` | Define your break glass accounts and groups | [Emergency Access Accounts](./emergency-access-accounts.md) | +| `DelegatedAdminTenants` | Allowlist the tenants that may administer your tenant through GDAP or Tenant Governance | [Delegated Admin Tenants](./delegated-admin-tenants.md) | | `XspmExternalDataUris` | Override the HTTPS sources used by XSPM Advanced Hunting queries | This page | The GitHub and Dataverse settings are listed in the [run configuration reference](./run-configuration.md#globalsettings). diff --git a/website/docs/configuration/run-configuration.md b/website/docs/configuration/run-configuration.md index c77624d549..1fb35bf003 100644 --- a/website/docs/configuration/run-configuration.md +++ b/website/docs/configuration/run-configuration.md @@ -134,6 +134,7 @@ Tenant-wide settings that tests read with `Get-MtSetting`. Maester knows these: | Setting | Type | Default | Used by | | --- | --- | --- | --- | | `EmergencyAccessAccounts` | array | none | Conditional Access checks. See [Emergency access accounts](./emergency-access-accounts.md). | +| `DelegatedAdminTenants` | array | none | MT.1258. The tenants allowed to administer this tenant through GDAP or Tenant Governance. See [Delegated admin tenants](./delegated-admin-tenants.md). | | `DataverseEnvironmentUrl` | string | | Copilot Studio checks. | | `GitHubOrganization` | string | | GitHub checks. | | `GitHubApiBaseUri` | string | `https://api.github.com` | GitHub checks. | diff --git a/website/docs/sections/permissions.md b/website/docs/sections/permissions.md index 05f1d58a0d..53ccca6873 100644 --- a/website/docs/sections/permissions.md +++ b/website/docs/sections/permissions.md @@ -38,3 +38,17 @@ To run preview tests, also grant these application permissions: - **AgentIdentityBlueprintPrincipal.Read.All** - **Application.Read.All** - **IdentityRiskyUser.Read.All** + +To run preview tests of features that only the worldwide (Global) cloud offers, also grant these application +permissions. Commercial and GCC tenants use the Global cloud. + +- **ConfigurationMonitoring.Read.All** +- **CrossTenantInformation.ReadBasic.All** +- **RemoteTenantGroups.Read.All** +- **TenantGovernance-RelatedTenant.Read.All** +- **TenantGovernance-Relationship.Read.All** + +`Get-MtGraphScope -IncludePreview` includes them only for `-Environment Global` (the default), and +`Connect-Maester -Environment` passes the cloud on. A connection to a national cloud (US Government, US Government +DoD or China) does not request them, because Microsoft Graph does not offer these APIs there and the sign-in would +fail on a permission the cloud does not publish.