diff --git a/powershell/Maester.psd1 b/powershell/Maester.psd1 index 4a24c9eed2..80e1d8654e 100644 --- a/powershell/Maester.psd1 +++ b/powershell/Maester.psd1 @@ -86,6 +86,7 @@ 'Get-MtAuthenticationMethodPolicyConfig', 'Get-MtAzureManagementGroup', 'Get-MtConditionalAccessPolicy', + 'Get-MtConditionalAccessPolicyPlan', 'Get-MtConnectionState', 'Get-MtConnector', 'Get-MtExo', diff --git a/powershell/internal/checks/maester/entra/Test-MtCaAllAppsExists.ps1 b/powershell/internal/checks/maester/entra/Test-MtCaAllAppsExists.ps1 index 2e02feb2ca..e40d96ea44 100644 --- a/powershell/internal/checks/maester/entra/Test-MtCaAllAppsExists.ps1 +++ b/powershell/internal/checks/maester/entra/Test-MtCaAllAppsExists.ps1 @@ -39,11 +39,12 @@ See [Plan a Conditional Access deployment - Microsoft Learn](https://learn.microsoft.com/entra/identity/conditional-access/plan-conditional-access#apply-conditional-access-policies-to-every-app)' if ($SkipCheckAllUsers.IsPresent) { - $testResult = "These Conditional Access policies target all cloud apps:`n`n" + $testResult = "These Conditional Access policies target all cloud apps:`n`n%TestResult%" } else { - $testResult = "These Conditional Access policies target all cloud apps and all users:`n`n" + $testResult = "These Conditional Access policies target all cloud apps and all users:`n`n%TestResult%" } + $matchingPolicies = [System.Collections.Generic.List[object]]::new() $result = $false foreach ($policy in $policies) { if ( ( $SkipCheckAllUsers.IsPresent -or $policy.conditions.users.includeUsers -eq 'All' ) ` @@ -51,7 +52,7 @@ ) { $result = $true $currentResult = $true - $testResult += " - [$(Get-MtSafeMarkdown $policy.displayName)](https://entra.microsoft.com/#view/Microsoft_AAD_ConditionalAccess/PolicyBlade/policyId/$($($policy.id))?%23view/Microsoft_AAD_ConditionalAccess/ConditionalAccessBlade/~/Policies?=)`n" + $matchingPolicies.Add($policy) } else { $currentResult = $false } @@ -66,7 +67,7 @@ } } - Add-MtTestResultDetail -Description $testDescription -Result $testResult + Add-MtTestResultDetail -Description $testDescription -Result $testResult -GraphObjects $matchingPolicies.ToArray() -GraphObjectType ConditionalAccess return $result } diff --git a/powershell/internal/report/Get-GraphObjectMarkdown.ps1 b/powershell/internal/report/Get-GraphObjectMarkdown.ps1 index 9d3f657c18..b38b19ce07 100644 --- a/powershell/internal/report/Get-GraphObjectMarkdown.ps1 +++ b/powershell/internal/report/Get-GraphObjectMarkdown.ps1 @@ -22,7 +22,7 @@ # 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', + [ValidateSet('AuthenticationMethod', 'AuthorizationPolicy', 'ConditionalAccess', 'ConditionalAccessPlan', 'ConsentPolicy', 'Devices', 'Domains', 'Groups', 'IdentityProtection', 'Users', 'UserRole' )] [string] $GraphObjectType, @@ -52,16 +52,32 @@ } if($currentGraphObjectType) { - $link = $markdownLinkTemplate[$currentGraphObjectType] -f $item.id + if ($currentGraphObjectType -eq 'ConditionalAccess' -and (Get-ObjectProperty $item 'planId')) { + $link = $markdownLinkTemplate.ConditionalAccessPlan -f $item.planId + } else { + $link = $markdownLinkTemplate[$currentGraphObjectType] -f $item.id + } } else { $link = "#" } + # A plan URL contains only the parent ID. Keep the rule identity in the link title so + # custom Markdown tables and rehydrated reports can recover it without changing the URL. + $linkTitle = '' + if ($currentGraphObjectType -eq 'ConditionalAccess' -and + (Get-ObjectProperty $item 'sourceType') -eq 'PolicyPlanRule' -and + (Get-ObjectProperty $item 'planId')) { + $ruleId = [string](Get-ObjectProperty $item 'id') + if ($ruleId -match '^[0-9a-fA-F]{8}-(?:[0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}$') { + $linkTitle = ' "ConditionalAccessPolicyRule:{0}"' -f $ruleId + } + } + if ($AsPlainTextLink) { - $result += "[$displayName]($link)" + $result += "[$displayName]($link$linkTitle)" } else { - $result += " - [$displayName]($link)`n" + $result += " - [$displayName]($link$linkTitle)`n" } } diff --git a/powershell/internal/report/affected-objects/ConvertTo-MtAffectedObjectRecord.ps1 b/powershell/internal/report/affected-objects/ConvertTo-MtAffectedObjectRecord.ps1 index cbe09e7d8a..9c8cbc02ba 100644 --- a/powershell/internal/report/affected-objects/ConvertTo-MtAffectedObjectRecord.ps1 +++ b/powershell/internal/report/affected-objects/ConvertTo-MtAffectedObjectRecord.ps1 @@ -30,6 +30,7 @@ # Get-MtAffectedObjectFromMarkdown so records from both sources dedupe correctly. $canonicalType = @{ ConditionalAccess = 'ConditionalAccessPolicy' + ConditionalAccessPlan = 'ConditionalAccessPolicyPlan' Users = 'User' UserRole = 'User' Groups = 'Group' @@ -67,12 +68,13 @@ $type = $objectTypeAlias[$type] } + $isPlanRule = (Get-ObjectProperty $item 'sourceType') -eq 'PolicyPlanRule' -and (Get-ObjectProperty $item 'planId') $portalLink = $null if ($type -and $portalLinkTemplate.LinkTemplates.ContainsKey($type)) { $template = $portalLinkTemplate.LinkTemplates[$type] # A per-object template without the id would open a broken blade. if ($id -or -not $template.Contains('{0}')) { - $portalLink = $template -f $id + $portalLink = if ($isPlanRule) { $portalLinkTemplate.LinkTemplates.ConditionalAccessPlan -f $item.planId } else { $template -f $id } } } @@ -90,7 +92,8 @@ [PSCustomObject]@{ System = 'EntraID' AnchorKind = $anchorKind - Type = if ($type -and $canonicalType.ContainsKey($type)) { $canonicalType[$type] } + Type = if ($isPlanRule) { 'ConditionalAccessPolicyRule' } + elseif ($type -and $canonicalType.ContainsKey($type)) { $canonicalType[$type] } elseif ($type) { $type } elseif ($odataType -and $odataObjectType.ContainsKey($odataType)) { $odataObjectType[$odataType] } elseif ($odataType) { $odataType } diff --git a/powershell/internal/report/affected-objects/Get-MtAffectedObjectFromMarkdown.ps1 b/powershell/internal/report/affected-objects/Get-MtAffectedObjectFromMarkdown.ps1 index 86eddea483..cbedda5a91 100644 --- a/powershell/internal/report/affected-objects/Get-MtAffectedObjectFromMarkdown.ps1 +++ b/powershell/internal/report/affected-objects/Get-MtAffectedObjectFromMarkdown.ps1 @@ -13,6 +13,9 @@ `[name](url "title")`), the display name is captured too, with markdown escapes such as `\(` and `\_` removed. The matched URL is kept as the record's PortalLink. + Plan-rule links can carry a ConditionalAccessPolicyRule: title. For those links the rule ID + identifies the affected object while the unchanged plan URL remains its PortalLink. + Links with an empty target whose text is a user principal name (`[user@contoso.com]()`, as the Entra recommendation checks write them) are captured as users keyed by that UPN. #> @@ -34,6 +37,7 @@ # Ordered: more specific patterns first. Id = first capture group. $patterns = @( + @{ System = 'EntraID'; Type = 'ConditionalAccessPolicyPlan'; Regex = "Microsoft_AAD_ConditionalAccess/PolicyPlanView\.ReactView/planId/($guid)" } @{ System = 'EntraID'; Type = 'ConditionalAccessPolicy'; Regex = "Microsoft_AAD_ConditionalAccess/PolicyBlade/policyId/($guid)" } # The appId suffix is optional: some checks link the enterprise app by object id only. @{ System = 'EntraID'; Type = 'ServicePrincipal'; Regex = "ManagedAppMenuBlade/~/\w+/objectId/($guid)(?:/appId/$guid)?" } @@ -64,9 +68,10 @@ # different occurrence. .NET allows the repeated 'url' group name across the alternation. # https only: display names are not escaped in result markdown, so a crafted name can smuggle # a javascript: url into a link that would otherwise match a portal pattern. - # The name may contain one level of brackets ("[RaviK] - Policy") and the url may be followed - # by a link title (`[name](url "title")`). - $linkPattern = '\[(?(?:[^\[\]]|\[[^\[\]]*\])+)\]\((?https://[^)\s]+)(?:\s+"[^"]*")?\)|(?https://[^\s)\]]+)' + # Consume backslash escapes before interpreting brackets. Generated names can contain escaped + # unmatched or nested brackets; legacy unescaped names may contain one bracketed group. + # The url may be followed by a link title (`[name](url "title")`). + $linkPattern = '\[(?(?:\\.|[^\[\]\\]|\[(?:\\.|[^\[\]\\])*\])+)\]\((?https://[^)\s]+)(?:\s+"(?[^"]*)")?\)|(?<url>https://[^\s)\]]+)' # Markdown backslash escapes (\( \_ \* ...) that result markdown adds around display names. # Must stay a superset of what Get-MtSafeMarkdown escapes, or a name keeps a literal # backslash on the affected-objects page. `:` and `@` were added there for GFM autolink @@ -86,11 +91,19 @@ $displayName = $link.Groups['name'].Value -replace $markdownEscape, '$1' } + $type = $pattern.Type + $id = $match.Groups[1].Value + if ($type -eq 'ConditionalAccessPolicyPlan' -and + $link.Groups['title'].Value -match "^ConditionalAccessPolicyRule:($guid)$") { + $type = 'ConditionalAccessPolicyRule' + $id = $Matches[1] + } + $records.Add([PSCustomObject]@{ System = $pattern.System AnchorKind = 'Instance' - Type = $pattern.Type - Id = $match.Groups[1].Value + Type = $type + Id = $id DisplayName = $displayName PortalLink = $url TestId = $TestId diff --git a/powershell/internal/report/affected-objects/Get-MtAffectedObjectTypeDefinition.ps1 b/powershell/internal/report/affected-objects/Get-MtAffectedObjectTypeDefinition.ps1 index 3d21ee002d..c8f2e45e77 100644 --- a/powershell/internal/report/affected-objects/Get-MtAffectedObjectTypeDefinition.ps1 +++ b/powershell/internal/report/affected-objects/Get-MtAffectedObjectTypeDefinition.ps1 @@ -38,6 +38,8 @@ 'AuthenticationMethod' 'AuthorizationPolicy' 'ConditionalAccessPolicy' + 'ConditionalAccessPolicyPlan' + 'ConditionalAccessPolicyRule' 'ConsentPolicy' 'Device' 'DirectoryRole' diff --git a/powershell/internal/report/affected-objects/Get-MtPortalLinkTemplate.ps1 b/powershell/internal/report/affected-objects/Get-MtPortalLinkTemplate.ps1 index 250ff6a6b3..83f3d93ecb 100644 --- a/powershell/internal/report/affected-objects/Get-MtPortalLinkTemplate.ps1 +++ b/powershell/internal/report/affected-objects/Get-MtPortalLinkTemplate.ps1 @@ -20,6 +20,7 @@ LinkTemplates = @{ AuthenticationMethod = "$($__MtSession.AdminPortalUrl.Entra)#view/Microsoft_AAD_IAM/AuthenticationMethodsMenuBlade/~/AdminAuthMethods" AuthorizationPolicy = "$($__MtSession.AdminPortalUrl.Entra)#view/Microsoft_AAD_UsersAndTenants/UserManagementMenuBlade/~/UserSettings/menuId/UserSettings" + ConditionalAccessPlan = "$($__MtSession.AdminPortalUrl.Entra)#view/Microsoft_AAD_ConditionalAccess/PolicyPlanView.ReactView/planId/{0}" 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}" @@ -31,12 +32,14 @@ } # @odata.type → GraphObjectType (auto-detection when no explicit type is passed) OdataTypeMapping = @{ + '#microsoft.graph.conditionalAccessPolicyPlan' = 'ConditionalAccessPlan' + '#microsoft.graph.conditionalAccessPolicyRule' = 'ConditionalAccess' '#microsoft.graph.user' = 'Users' '#microsoft.graph.group' = 'Groups' '#microsoft.graph.device' = 'Devices' } # 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 = @('ConditionalAccess', 'ConditionalAccessPlan', 'Devices', 'Groups', 'Users', 'UserRole') } } diff --git a/powershell/internal/services/entra/ConvertTo-MtConditionalAccessPolicy.ps1 b/powershell/internal/services/entra/ConvertTo-MtConditionalAccessPolicy.ps1 new file mode 100644 index 0000000000..33e35109d9 --- /dev/null +++ b/powershell/internal/services/entra/ConvertTo-MtConditionalAccessPolicy.ps1 @@ -0,0 +1,46 @@ +function ConvertTo-MtConditionalAccessPolicy { + <# + .SYNOPSIS + Projects a plan rule into the policy shape used by Maester's Conditional Access checks. + + .DESCRIPTION + Preserves the real rule ID, state, original rule conditions and controls. Exposes inherited effective conditions, + grantControls and sessionControls at the same paths as a standalone policy, with explicit parent-plan metadata. + Never mutates the cached plan or rule and never treats a plan owner as an administrator or a rule assignment. + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param( + [Parameter(Mandatory)] [object] $Plan, + [Parameter(Mandatory)] [object] $Rule + ) + + if ([string]::IsNullOrWhiteSpace([string]$Plan.id) -or [string]::IsNullOrWhiteSpace([string]$Rule.id)) { + throw 'Conditional Access plans and rules must have IDs before they can be evaluated.' + } + if ($Rule.state -notin @('enabled', 'disabled', 'enabledForReportingButNotEnforced')) { + throw "Conditional Access rule '$($Rule.id)' has an unsupported state '$($Rule.state)'." + } + # Copy only inherited targeting; serializing the sibling rules for each projection is quadratic. + $sharedConditions = ConvertTo-Json -InputObject $Plan.sharedConditions -Depth 100 | ConvertFrom-Json -AsHashtable + $copy = $Rule | ConvertTo-Json -Depth 100 | ConvertFrom-Json -AsHashtable + if (-not $copy.controls -or (-not $copy.controls.grantControls -and -not $copy.controls.sessionControls)) { + throw "Conditional Access rule '$($Rule.id)' has no supported enforcement controls." + } + $copy['@odata.type'] = '#microsoft.graph.conditionalAccessPolicyRule' + $copy['ruleConditions'] = $copy.conditions + try { + $copy['conditions'] = Merge-MtConditionalAccessCondition -Shared $sharedConditions -Rule $copy.conditions + } catch { + throw "Cannot evaluate rule '$($Rule.id)' in plan '$($Plan.id)': $($_.Exception.Message)" + } + $copy['grantControls'] = $copy.controls.grantControls + $copy['sessionControls'] = $copy.controls.sessionControls + $copy['displayName'] = "[Plan: $($Plan.displayName)] [Rule: $($Rule.displayName)]" + $copy['planId'] = $Plan.id + $copy['planDisplayName'] = $Plan.displayName + $copy['planOwners'] = @($Plan.owners) + $copy['sharedConditions'] = $sharedConditions + $copy['sourceType'] = 'PolicyPlanRule' + return [pscustomobject]$copy +} diff --git a/powershell/internal/services/entra/Merge-MtConditionalAccessCondition.ps1 b/powershell/internal/services/entra/Merge-MtConditionalAccessCondition.ps1 new file mode 100644 index 0000000000..64a9ee74a8 --- /dev/null +++ b/powershell/internal/services/entra/Merge-MtConditionalAccessCondition.ps1 @@ -0,0 +1,88 @@ +function Merge-MtConditionalAccessCondition { + <# + .SYNOPSIS + Combines inherited and rule-specific Conditional Access conditions without overwriting exclusions. + + .DESCRIPTION + Merges Graph condition dictionaries recursively and unions collection values. Null and empty optional + values do not erase inherited targeting. Incompatible scalar values, including conflicting filter expressions, + terminate the read: inventing a lossy effective policy could make an uncovered scenario pass a security check. + Inputs are JSON-compatible copies owned by the policy adapter, not objects in the Graph session cache. + #> + [CmdletBinding()] + param( + [AllowNull()] [object] $Shared, + [AllowNull()] [object] $Rule, + [string] $PropertyPath = 'conditions' + ) + + if ($null -eq $Shared) { Write-Output -NoEnumerate -InputObject $Rule; return } + if ($null -eq $Rule) { Write-Output -NoEnumerate -InputObject $Shared; return } + + if ($Shared -is [System.Collections.IDictionary] -and $Rule -is [System.Collections.IDictionary]) { + # Guest type and tenant membership form a pair. Unioning both independently invents cross-products + # (type A in tenant X plus type B in tenant Y must not become both types in both tenants). + if ($PropertyPath -match '\.(includeGuestsOrExternalUsers|excludeGuestsOrExternalUsers)$') { + $sharedTypes = @(([string]$Shared.guestOrExternalUserTypes -split ',') | Sort-Object -Unique) -join ',' + $ruleTypes = @(([string]$Rule.guestOrExternalUserTypes -split ',') | Sort-Object -Unique) -join ',' + # Tenant membership is a set, independent of member order, duplicate IDs or JSON key order. + # Keep a missing scope distinct from both all and an empty enumerated scope. + $tenantScopes = foreach ($condition in @($Shared, $Rule)) { + if ($null -eq $condition.externalTenants) { + 'absent' + } else { + [ordered]@{ + membershipKind = $condition.externalTenants.membershipKind + members = @($condition.externalTenants.members | Sort-Object -Unique) + } | ConvertTo-Json -Depth 100 -Compress + } + } + if ($sharedTypes -ne $ruleTypes -and $tenantScopes[0] -ne $tenantScopes[1]) { + throw "Cannot safely combine guest types and tenant sets at '$PropertyPath' without broadening the targeting." + } + } + # The all-external-tenants discriminator denotes the union's entire tenant set. + if ($PropertyPath -like '*.externalTenants' -and ($Shared.membershipKind -eq 'all' -or $Rule.membershipKind -eq 'all')) { + $all = if ($Shared.membershipKind -eq 'all') { $Shared } else { $Rule } + Write-Output -NoEnumerate -InputObject $all + return + } + $merged = [ordered]@{} + $keys = @(@($Shared.Keys) + @($Rule.Keys) | Select-Object -Unique) + foreach ($key in $keys) { + if ($key -like '*@odata.context') { continue } + $merged[$key] = Merge-MtConditionalAccessCondition -Shared $Shared[$key] -Rule $Rule[$key] -PropertyPath "$PropertyPath.$key" + } + Write-Output -NoEnumerate -InputObject $merged + return + } + + if ($Shared -is [System.Collections.IList] -and $Rule -is [System.Collections.IList]) { + $union = [System.Collections.Generic.List[object]]::new() + $seen = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) + foreach ($value in @($Shared) + @($Rule)) { + $key = ConvertTo-Json -InputObject $value -Depth 100 -Compress + if ($seen.Add($key)) { $union.Add($value) } + } + # These collection properties use All as a wildcard, not an additional narrowing condition. + if ($PropertyPath -match '\.(includeUsers|includeApplications|includePlatforms|includeLocations|clientAppTypes)$') { + $all = @($union | Where-Object { $_ -is [string] -and $_ -eq 'all' }) + if ($all.Count -gt 0) { Write-Output -NoEnumerate -InputObject @($all[0]); return } + } + Write-Output -NoEnumerate -InputObject $union.ToArray() + return + } + + if ($Shared -is [string] -and [string]::IsNullOrWhiteSpace($Shared)) { Write-Output -NoEnumerate -InputObject $Rule; return } + if ($Rule -is [string] -and [string]::IsNullOrWhiteSpace($Rule)) { Write-Output -NoEnumerate -InputObject $Shared; return } + if (($Shared | ConvertTo-Json -Depth 100 -Compress) -ceq ($Rule | ConvertTo-Json -Depth 100 -Compress)) { + Write-Output -NoEnumerate -InputObject $Shared + return + } + if ($Shared -is [string] -and $Rule -is [string] -and + $PropertyPath -match '\.(guestOrExternalUserTypes|insiderRiskLevels|agentIdRiskLevels|transferMethods)$') { + $flags = @(@($Shared -split ',') + @($Rule -split ',') | ForEach-Object { $_.Trim() } | Where-Object { $_ } | Select-Object -Unique) + return $flags -join ',' + } + throw "Cannot safely combine Conditional Access plan and rule values at '$PropertyPath'. The inventory is incomplete; use a scenario evaluation for this condition instead of assuming coverage." +} diff --git a/powershell/public/run/Add-MtTestResultDetail.ps1 b/powershell/public/run/Add-MtTestResultDetail.ps1 index 3f4fa78dba..e85adcb7ab 100644 --- a/powershell/public/run/Add-MtTestResultDetail.ps1 +++ b/powershell/public/run/Add-MtTestResultDetail.ps1 @@ -58,7 +58,7 @@ [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', + [ValidateSet('AuthenticationMethod', 'AuthorizationPolicy', 'ConditionalAccess', 'ConditionalAccessPlan', 'ConsentPolicy', 'Devices', 'Domains', 'Groups', 'IdentityProtection', 'Users', 'UserRole' )] [string] $GraphObjectType, diff --git a/powershell/public/services/entra/Get-MtConditionalAccessPolicy.ps1 b/powershell/public/services/entra/Get-MtConditionalAccessPolicy.ps1 index c12205b153..c21d1f70ff 100644 --- a/powershell/public/services/entra/Get-MtConditionalAccessPolicy.ps1 +++ b/powershell/public/services/entra/Get-MtConditionalAccessPolicy.ps1 @@ -1,26 +1,58 @@ function Get-MtConditionalAccessPolicy { <# - .Synopsis - Returns all the Conditional Access policies in the tenant. + .SYNOPSIS + Returns standalone Conditional Access policies and effective policy plan rules. - .Description - Returns all the Conditional Access policies in the tenant. + .DESCRIPTION + Reads standalone policies and beta policy plans through the Graph session cache. Each plan rule is projected + into the policy shape used by existing checks: inherited conditions are combined without dropping exclusions, + and nested grant/session controls are exposed at the policy level. The rule retains its own ID and state, + with planId, planDisplayName, planOwners, sourceType, sharedConditions and ruleConditions identifying its source. + Owners are metadata only. Disabled and report-only rules retain their states and are not promoted to enabled. + An empty plan inventory is valid. A failed read or an unsafe condition combination terminates the inventory + instead of presenting partial data as complete. Reading requires CA read access, not write permissions. + Delegated callers also need a supported Microsoft Entra role: Conditional Access Administrator is the least + privileged built-in role supported for listing plans; an appropriate custom role is also supported. + Policy.Read.All alone is not sufficient for every delegated caller. Existing CA checks read plans through + the combined inventory, so callers who can read standalone policies may now encounter a plan-read error. + See https://learn.microsoft.com/graph/api/conditionalaccessroot-list-plans?view=graph-rest-beta - .Example - Get-MtConditionalAccessPolicy + .PARAMETER StandaloneOnly + Returns only standalone policies, without reading the preview plans endpoint. This is an explicit inventory + selection for callers that need original Graph policy objects, not a fallback used by security checks. + + .PARAMETER DisableCache + Forwards an explicit diagnostic caller's cache choice. Security checks leave this switch unset. + + .EXAMPLE + Get-MtConditionalAccessPolicy | Where-Object state -EQ enabled + + Returns enabled standalone policies and enabled plan rules with effective conditions. + + .EXAMPLE + Get-MtConditionalAccessPolicy -StandaloneOnly + + Returns the standalone policy inventory without making a plans request. .LINK https://maester.dev/docs/commands/Get-MtConditionalAccessPolicy #> - [CmdletBinding()] - param( - # Specify if this request should skip cache and go directly to Graph. - [Parameter(Mandatory = $false)] - [Switch]$DisableCache - ) - - Write-Verbose -Message "Getting Conditional Access policies." + [CmdletBinding()] + [OutputType([object[]])] + param( + [switch] $StandaloneOnly, + [switch] $DisableCache + ) - return Invoke-MtGraphRequest -RelativeUri 'identity/conditionalAccess/policies' -ApiVersion beta -DisableCache:$DisableCache + Write-Verbose -Message 'Reading standalone Conditional Access policies and effective plan rules.' + $policies = @(Invoke-MtGraphRequest -RelativeUri 'identity/conditionalAccess/policies' -ApiVersion beta -DisableCache:$DisableCache -ErrorAction Stop) + if ($StandaloneOnly) { return $policies } + $effectiveRules = [System.Collections.Generic.List[object]]::new() + foreach ($plan in @(Get-MtConditionalAccessPolicyPlan -DisableCache:$DisableCache -ErrorAction Stop)) { + foreach ($rule in @($plan.rules)) { + $effectiveRules.Add((ConvertTo-MtConditionalAccessPolicy -Plan $plan -Rule $rule)) + } + } + return @($policies) + @($effectiveRules.ToArray()) } diff --git a/powershell/public/services/entra/Get-MtConditionalAccessPolicyPlan.ps1 b/powershell/public/services/entra/Get-MtConditionalAccessPolicyPlan.ps1 new file mode 100644 index 0000000000..434a83be5b --- /dev/null +++ b/powershell/public/services/entra/Get-MtConditionalAccessPolicyPlan.ps1 @@ -0,0 +1,60 @@ +function Get-MtConditionalAccessPolicyPlan { + <# + .SYNOPSIS + Returns Conditional Access policy plans with their complete rule inventories. + + .DESCRIPTION + Reads the beta plans and rules endpoints through Maester's Graph session cache. Rules are kept in their + original Graph shape, including controls and rule-specific conditions. Shared conditions and owners stay + on the parent plan. Empty plan inventories return no objects; failed reads terminate instead of hiding plans. + This preview API accepts Policy.Read.All; write permissions are not required. + For delegated access, Microsoft documents Conditional Access Administrator as the least privileged supported + built-in role for listing plans; an appropriate custom role is also supported. + On 18 November 2026, julien-ly reported successful plan and rule reads in one tenant with either Global Reader + or Security Reader and delegated Policy.Read.All. This describes observed preview behavior in that tenant; + validate plan and rule access with the intended audit identity against Microsoft's documented requirements. + Existing CA checks read plans through the combined inventory, so callers who can read standalone policies + may still encounter a plan-read error. + + .PARAMETER MetadataOnly + Reads only plan metadata and does not request child rules. Useful for accountability checks. + + .PARAMETER DisableCache + Forwards an explicit diagnostic caller's cache choice to every inventory request. Security checks leave the + switch unset so that they use the same tenant snapshot as the rest of the Maester run. + + .EXAMPLE + Get-MtConditionalAccessPolicyPlan + + Returns each plan and its rules without modifying the cached Graph objects. + + .LINK + https://maester.dev/docs/commands/Get-MtConditionalAccessPolicyPlan + + .LINK + https://learn.microsoft.com/graph/api/conditionalaccessroot-list-plans?view=graph-rest-beta + + .LINK + https://github.com/maester365/maester/pull/2733#issuecomment-6979345045 + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param( + [switch] $MetadataOnly, + [switch] $DisableCache + ) + + Write-Verbose -Message 'Reading Conditional Access policy plan metadata and rule inventories.' + $plans = @(Invoke-MtGraphRequest -RelativeUri 'identity/conditionalAccess/plans' -ApiVersion beta -DisableCache:$DisableCache -ErrorAction Stop) + $inventory = [System.Collections.Generic.List[object]]::new() + foreach ($plan in $plans) { + if ([string]::IsNullOrWhiteSpace([string]$plan.id)) { throw 'Conditional Access plan inventory contains a plan without an ID.' } + $planId = [uri]::EscapeDataString([string]$plan.id) + $copy = $plan | ConvertTo-Json -Depth 100 | ConvertFrom-Json -AsHashtable + if (-not $MetadataOnly) { + $copy['rules'] = @(Invoke-MtGraphRequest -RelativeUri "identity/conditionalAccess/plans/$planId/rules" -ApiVersion beta -DisableCache:$DisableCache -ErrorAction Stop) + } + $inventory.Add([pscustomobject]$copy) + } + return $inventory.ToArray() +} diff --git a/powershell/public/services/entra/Test-MtConditionalAccessWhatIf.ps1 b/powershell/public/services/entra/Test-MtConditionalAccessWhatIf.ps1 index 1a895d268d..b181cc8084 100644 --- a/powershell/public/services/entra/Test-MtConditionalAccessWhatIf.ps1 +++ b/powershell/public/services/entra/Test-MtConditionalAccessWhatIf.ps1 @@ -7,6 +7,10 @@ This function tests a Conditional Access evaluation with What If for a given scenario. The function uses the Microsoft Graph API to evaluate the Conditional Access policies. + Evaluated plan rules are matched by rule ID to the cached plan inventory and annotated with planId, + planDisplayName and sourceType for reporting. All evaluation fields and filtering are preserved. + Reading plans requires a supported delegated Entra role (Conditional Access Administrator or an appropriate + custom role) in addition to the Graph read permission. A failed plan read terminates the operation. Learn more: https://learn.microsoft.com/entra/identity/conditional-access/what-if-tool @@ -217,6 +221,30 @@ if (!$AllResults) { $ConditionalAccessWhatIfResult = $ConditionalAccessWhatIfResult | Where-Object { $_.policyApplies -eq $true } } + if ($ConditionalAccessWhatIfResult) { + # Match IDs, never names: evaluation results do not identify the parent plan. + $planByRuleId = @{} + foreach ($plan in @(Get-MtConditionalAccessPolicyPlan -ErrorAction Stop)) { + foreach ($rule in @($plan.rules)) { + if ($rule.id) { $planByRuleId[[string]$rule.id] = $plan } + } + } + $ConditionalAccessWhatIfResult = foreach ($policy in $ConditionalAccessWhatIfResult) { + $plan = $planByRuleId[[string]$policy.id] + if ($plan) { + # Annotate a copy so the original evaluation response is not changed. + $copy = $policy | Select-Object * + $copy | Add-Member -NotePropertyMembers @{ + planId = $plan.id + planDisplayName = $plan.displayName + sourceType = 'PolicyPlanRule' + } -Force + $copy + } else { + $policy + } + } + } return $ConditionalAccessWhatIfResult } catch { throw diff --git a/powershell/tests/fixtures/conditional-access-plans/plan.json b/powershell/tests/fixtures/conditional-access-plans/plan.json new file mode 100644 index 0000000000..cc6dea0269 --- /dev/null +++ b/powershell/tests/fixtures/conditional-access-plans/plan.json @@ -0,0 +1,137 @@ +{ + "@odata.context": "https://graph.microsoft.com/beta/$metadata#identity/conditionalAccess/plans/$entity", + "id": "00000000-0000-4000-8000-000000000001", + "displayName": "CAPLAB-20261108 Shared scope", + "description": "Isolated test. Disabled test users only. Do not reuse as production policy.", + "owners": [ + "00000000-0000-4000-8000-000000000002", + "00000000-0000-4000-8000-000000000003" + ], + "tags": [ + "CAPLAB-20261108", + "Maester-compatibility" + ], + "templateId": null, + "createdDateTime": "2026-11-08T07:45:48.5466863Z", + "modifiedDateTime": "2026-11-08T07:45:48.5466863Z", + "deletedDateTime": null, + "sharedConditions": { + "userRiskLevels": [], + "signInRiskLevels": [], + "clientAppTypes": [ + "all" + ], + "platforms": null, + "locations": null, + "times": null, + "deviceStates": null, + "devices": null, + "clientApplications": null, + "agents": null, + "actionsAndDestinations": null, + "applications": { + "includeApplications": [ + "00000000-0000-4000-8000-000000000004" + ], + "excludeApplications": [], + "includeUserActions": [], + "includeAgentActions": [], + "includeAuthenticationContextClassReferences": [], + "applicationFilter": null + }, + "users": { + "includeUsers": [], + "excludeUsers": [ + "00000000-0000-4000-8000-000000000005" + ], + "includeGroups": [ + "00000000-0000-4000-8000-000000000006" + ], + "excludeGroups": [], + "includeRoles": [], + "excludeRoles": [], + "includeGuestsOrExternalUsers": null, + "excludeGuestsOrExternalUsers": null + } + }, + "rules@odata.context": "https://graph.microsoft.com/beta/$metadata#identity/conditionalAccess/plans('00000000-0000-4000-8000-000000000001')/rules", + "rules": [ + { + "id": "00000000-0000-4000-8000-000000000007", + "displayName": "CAPLAB-20261108 Require MFA", + "description": null, + "state": "enabledForReportingButNotEnforced", + "conditions": { + "userRiskLevels": [], + "signInRiskLevels": [], + "clientAppTypes": [ + "all" + ], + "applications": null, + "users": null, + "platforms": null, + "locations": null, + "times": null, + "deviceStates": null, + "devices": null, + "clientApplications": null, + "agents": null, + "actionsAndDestinations": null + }, + "controls": { + "sessionControls": null, + "grantControls": { + "operator": "OR", + "builtInControls": [ + "mfa" + ], + "customAuthenticationFactors": [], + "termsOfUse": [], + "authenticationStrength@odata.context": "https://graph.microsoft.com/beta/$metadata#identity/conditionalAccess/plans('00000000-0000-4000-8000-000000000001')/rules('00000000-0000-4000-8000-000000000007')/controls/grantControls/authenticationStrength/$entity", + "authenticationStrength": null + } + } + }, + { + "id": "00000000-0000-4000-8000-000000000008", + "displayName": "CAPLAB-20261108 Windows compliant", + "description": null, + "state": "enabledForReportingButNotEnforced", + "conditions": { + "userRiskLevels": [], + "signInRiskLevels": [], + "clientAppTypes": [ + "all" + ], + "applications": null, + "users": null, + "locations": null, + "times": null, + "deviceStates": null, + "devices": null, + "clientApplications": null, + "agents": null, + "actionsAndDestinations": null, + "platforms": { + "includePlatforms": [ + "windows" + ], + "excludePlatforms": [] + } + }, + "controls": { + "sessionControls": null, + "grantControls": { + "operator": "OR", + "builtInControls": [ + "compliantDevice" + ], + "customAuthenticationFactors": [], + "termsOfUse": [], + "authenticationStrength@odata.context": "https://graph.microsoft.com/beta/$metadata#identity/conditionalAccess/plans('00000000-0000-4000-8000-000000000001')/rules('00000000-0000-4000-8000-000000000008')/controls/grantControls/authenticationStrength/$entity", + "authenticationStrength": null + } + } + } + ] +} diff --git a/powershell/tests/fixtures/conditional-access-plans/requester-windows-resource-a.json b/powershell/tests/fixtures/conditional-access-plans/requester-windows-resource-a.json new file mode 100644 index 0000000000..d4f52fc781 --- /dev/null +++ b/powershell/tests/fixtures/conditional-access-plans/requester-windows-resource-a.json @@ -0,0 +1,153 @@ +{ + "value": [ + { + "id": "00000000-0000-4000-8000-000000000007", + "templateId": null, + "displayName": "[Plan: CAPLAB-20261108 Shared scope] [Rule: CAPLAB-20261108 Require MFA]", + "createdDateTime": null, + "modifiedDateTime": null, + "state": "enabledForReportingButNotEnforced", + "deletedDateTime": null, + "policyApplies": true, + "analysisReasons": "notSet", + "partialEnablementStrategy": null, + "sessionControls": null, + "conditions": { + "userRiskLevels": [], + "signInRiskLevels": [], + "clientAppTypes": [ + "all" + ], + "servicePrincipalRiskLevels": [], + "agentIdRiskLevels": null, + "insiderRiskLevels": null, + "purviewDataLossPreventionRules": null, + "agentSessionRiskLevels": null, + "clients": null, + "platforms": null, + "locations": null, + "times": null, + "deviceStates": null, + "devices": null, + "clientApplications": null, + "authenticationFlows": null, + "federatedTokens": null, + "agents": null, + "agentContext": null, + "actionsAndDestinations": null, + "applications": { + "includeApplications": [ + "00000000-0000-4000-8000-000000000004" + ], + "excludeApplications": [], + "includeUserActions": [], + "includeAgentActions": [], + "includeAuthenticationContextClassReferences": [], + "applicationFilter": null, + "networkAccess": null, + "globalSecureAccess": null + }, + "users": { + "includeUsers": [], + "excludeUsers": [ + "00000000-0000-4000-8000-000000000005" + ], + "includeGroups": [ + "00000000-0000-4000-8000-000000000006" + ], + "excludeGroups": [], + "includeRoles": [], + "excludeRoles": [], + "includeGuestsOrExternalUsers": null, + "excludeGuestsOrExternalUsers": null + } + }, + "grantControls": { + "operator": "OR", + "builtInControls": [ + "mfa" + ], + "customAuthenticationFactors": [], + "termsOfUse": [], + "authenticationStrength": null + } + }, + { + "id": "00000000-0000-4000-8000-000000000008", + "templateId": null, + "displayName": "[Plan: CAPLAB-20261108 Shared scope] [Rule: CAPLAB-20261108 Windows compliant]", + "createdDateTime": null, + "modifiedDateTime": null, + "state": "enabledForReportingButNotEnforced", + "deletedDateTime": null, + "policyApplies": true, + "analysisReasons": "notSet", + "partialEnablementStrategy": null, + "sessionControls": null, + "conditions": { + "userRiskLevels": [], + "signInRiskLevels": [], + "clientAppTypes": [ + "all" + ], + "servicePrincipalRiskLevels": [], + "agentIdRiskLevels": null, + "insiderRiskLevels": null, + "purviewDataLossPreventionRules": null, + "agentSessionRiskLevels": null, + "clients": null, + "locations": null, + "times": null, + "deviceStates": null, + "devices": null, + "clientApplications": null, + "authenticationFlows": null, + "federatedTokens": null, + "agents": null, + "agentContext": null, + "actionsAndDestinations": null, + "applications": { + "includeApplications": [ + "00000000-0000-4000-8000-000000000004" + ], + "excludeApplications": [], + "includeUserActions": [], + "includeAgentActions": [], + "includeAuthenticationContextClassReferences": [], + "applicationFilter": null, + "networkAccess": null, + "globalSecureAccess": null + }, + "users": { + "includeUsers": [], + "excludeUsers": [ + "00000000-0000-4000-8000-000000000005" + ], + "includeGroups": [ + "00000000-0000-4000-8000-000000000006" + ], + "excludeGroups": [], + "includeRoles": [], + "excludeRoles": [], + "includeGuestsOrExternalUsers": null, + "excludeGuestsOrExternalUsers": null + }, + "platforms": { + "includePlatforms": [ + "windows" + ], + "excludePlatforms": [] + } + }, + "grantControls": { + "operator": "OR", + "builtInControls": [ + "compliantDevice" + ], + "customAuthenticationFactors": [], + "termsOfUse": [], + "authenticationStrength": null + } + } + ] +} diff --git a/powershell/tests/fixtures/conditional-access-plans/rules.json b/powershell/tests/fixtures/conditional-access-plans/rules.json new file mode 100644 index 0000000000..c06685aaa2 --- /dev/null +++ b/powershell/tests/fixtures/conditional-access-plans/rules.json @@ -0,0 +1,82 @@ +{ + "@odata.context": "https://graph.microsoft.com/beta/$metadata#identity/conditionalAccess/plans('00000000-0000-4000-8000-000000000001')/rules", + "value": [ + { + "id": "00000000-0000-4000-8000-000000000007", + "displayName": "CAPLAB-20261108 Require MFA", + "description": null, + "state": "enabledForReportingButNotEnforced", + "conditions": { + "userRiskLevels": [], + "signInRiskLevels": [], + "clientAppTypes": [ + "all" + ], + "applications": null, + "users": null, + "platforms": null, + "locations": null, + "times": null, + "deviceStates": null, + "devices": null, + "clientApplications": null, + "agents": null, + "actionsAndDestinations": null + }, + "controls": { + "sessionControls": null, + "grantControls": { + "operator": "OR", + "builtInControls": [ + "mfa" + ], + "customAuthenticationFactors": [], + "termsOfUse": [], + "authenticationStrength@odata.context": "https://graph.microsoft.com/beta/$metadata#identity/conditionalAccess/plans('00000000-0000-4000-8000-000000000001')/rules('00000000-0000-4000-8000-000000000007')/controls/grantControls/authenticationStrength/$entity", + "authenticationStrength": null + } + } + }, + { + "id": "00000000-0000-4000-8000-000000000008", + "displayName": "CAPLAB-20261108 Windows compliant", + "description": null, + "state": "enabledForReportingButNotEnforced", + "conditions": { + "userRiskLevels": [], + "signInRiskLevels": [], + "clientAppTypes": [ + "all" + ], + "applications": null, + "users": null, + "locations": null, + "times": null, + "deviceStates": null, + "devices": null, + "clientApplications": null, + "agents": null, + "actionsAndDestinations": null, + "platforms": { + "includePlatforms": [ + "windows" + ], + "excludePlatforms": [] + } + }, + "controls": { + "sessionControls": null, + "grantControls": { + "operator": "OR", + "builtInControls": [ + "compliantDevice" + ], + "customAuthenticationFactors": [], + "termsOfUse": [], + "authenticationStrength@odata.context": "https://graph.microsoft.com/beta/$metadata#identity/conditionalAccess/plans('00000000-0000-4000-8000-000000000001')/rules('00000000-0000-4000-8000-000000000008')/controls/grantControls/authenticationStrength/$entity", + "authenticationStrength": null + } + } + } + ] +} diff --git a/powershell/tests/fixtures/golden/selection.json b/powershell/tests/fixtures/golden/selection.json index ae970e7cfd..9bdb56f8ff 100644 --- a/powershell/tests/fixtures/golden/selection.json +++ b/powershell/tests/fixtures/golden/selection.json @@ -1951,7 +1951,7 @@ "AD" ] }, - "SelectedCount": 609, + "SelectedCount": 610, "SelectedFamilies": [ "MT.1024", "MT.1059", @@ -2500,6 +2500,7 @@ "MT.1259", "MT.1260", "MT.1265", + "MT.1275", "ORCA.100", "ORCA.101", "ORCA.102", @@ -2581,7 +2582,7 @@ "AD" ] }, - "SelectedCount": 639, + "SelectedCount": 640, "SelectedFamilies": [ "MT.1024", "MT.1033", @@ -3162,6 +3163,7 @@ "MT.1259", "MT.1260", "MT.1265", + "MT.1275", "ORCA.100", "ORCA.101", "ORCA.102", @@ -4006,7 +4008,7 @@ "AD" ] }, - "SelectedCount": 595, + "SelectedCount": 596, "SelectedFamilies": [ "MT.1024", "MT.1033", @@ -4543,6 +4545,7 @@ "MT.1259", "MT.1260", "MT.1265", + "MT.1275", "ORCA.100", "ORCA.101", "ORCA.102", diff --git a/powershell/tests/functions/Get-GraphObjectMarkdown.Tests.ps1 b/powershell/tests/functions/Get-GraphObjectMarkdown.Tests.ps1 index ea1a192dd6..843c9c90ff 100644 --- a/powershell/tests/functions/Get-GraphObjectMarkdown.Tests.ps1 +++ b/powershell/tests/functions/Get-GraphObjectMarkdown.Tests.ps1 @@ -1,6 +1,10 @@ Describe 'Get-GraphObjectMarkdown' { BeforeAll { Import-Module $PSScriptRoot/../../Maester.psd1 -Force + InModuleScope Maester { + $script:PlanReportingPreviousPortalUrl = $__MtSession.AdminPortalUrl + $__MtSession.AdminPortalUrl = @{ Entra = 'https://entra.microsoft.com/' } + } . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" Use-MtModuleFunction -Name Get-GraphObjectMarkdown } @@ -24,4 +28,63 @@ Get-GraphObjectMarkdown -GraphObjects $policy -GraphObjectType ConditionalAccess | Should -BeLike ' - `[Require MFA`](*PolicyBlade/policyId/00000000-0000-0000-0000-000000000002)*' } + It 'Links a projected plan rule to its parent plan instead of the standalone policy blade' { + $rule = [pscustomobject]@{ id = 'rule-id'; displayName = 'Plan rule'; planId = 'plan-id'; sourceType = 'PolicyPlanRule' } + Get-GraphObjectMarkdown -GraphObjects $rule -GraphObjectType ConditionalAccess -AsPlainTextLink | + Should -BeLike '*PolicyPlanView.ReactView/planId/plan-id)' + } + + It 'Links owner findings directly to the policy plan' { + $plan = [pscustomobject]@{ id = 'plan-id'; displayName = 'Plan' } + Get-GraphObjectMarkdown -GraphObjects $plan -GraphObjectType ConditionalAccessPlan -AsPlainTextLink | + Should -BeLike '*PolicyPlanView.ReactView/planId/plan-id)' + } + + + It 'Preserves distinct rule identities for <DisplayName> through a Markdown-only table' -ForEach @( + @{ DisplayName = 'Same [name] | rule' } + @{ DisplayName = 'Rule ] review' } + @{ DisplayName = 'Rule [ review' } + @{ DisplayName = '[Plan: [Prod] Access] [Rule: MFA]' } + @{ DisplayName = 'Back\slash [Plan: [Prod]] [Rule: MFA] ]' } + ) { + $objects = InModuleScope Maester -Parameters @{ DisplayName = $DisplayName } { + param($DisplayName) + $planId = '00000000-0000-4000-8000-000000000001' + $rules = @( + [pscustomobject]@{ id = '00000000-0000-4000-8000-000000000007'; displayName = $DisplayName; planId = $planId; sourceType = 'PolicyPlanRule' } + [pscustomobject]@{ id = '00000000-0000-4000-8000-000000000008'; displayName = $DisplayName; planId = $planId; sourceType = 'PolicyPlanRule' } + ) + $markdown = "| Policy | Finding |`n| --- | --- |`n" + foreach ($rule in $rules) { + $markdown += "| $(Get-GraphObjectMarkdown -GraphObjects $rule -GraphObjectType ConditionalAccess -AsPlainTextLink) | Review |`n" + } + Get-MtAffectedObject -ExcludeSessionCache -MaesterResults ([pscustomobject]@{ + Tests = @([pscustomobject]@{ Id = 'MT.1184'; ResultDetail = @{ TestResult = $markdown } }) + }) + } + @($objects).Count | Should -Be 2 + $objects.Id | Sort-Object | Should -Be @('00000000-0000-4000-8000-000000000007', '00000000-0000-4000-8000-000000000008') + foreach ($record in $objects) { + $record.Type | Should -Be ConditionalAccessPolicyRule + $record.DisplayName | Should -Be $DisplayName + $record.Tests | Should -Be @('MT.1184') + $record.PortalLink | Should -BeLike '*PolicyPlanView.ReactView/planId/00000000-0000-4000-8000-000000000001' + } + } + + It 'Keeps an ordinary plan link as a plan record' { + $objects = InModuleScope Maester { + $plan = [pscustomobject]@{ id = '00000000-0000-4000-8000-000000000001'; displayName = 'Plan' } + $markdown = Get-GraphObjectMarkdown -GraphObjects $plan -GraphObjectType ConditionalAccessPlan + Get-MtAffectedObjectFromMarkdown -Markdown $markdown -TestId 'MT.1275' + } + @($objects).Count | Should -Be 1 + $objects.Type | Should -Be ConditionalAccessPolicyPlan + $objects.Id | Should -Be '00000000-0000-4000-8000-000000000001' + } +} + +AfterAll { + InModuleScope Maester { $__MtSession.AdminPortalUrl = $script:PlanReportingPreviousPortalUrl } } diff --git a/powershell/tests/functions/Get-MtAffectedObject.Tests.ps1 b/powershell/tests/functions/Get-MtAffectedObject.Tests.ps1 index 86d42d3f8f..e47d6f03a8 100644 --- a/powershell/tests/functions/Get-MtAffectedObject.Tests.ps1 +++ b/powershell/tests/functions/Get-MtAffectedObject.Tests.ps1 @@ -190,11 +190,7 @@ Describe 'Affected objects' { # literal backslash on the affected-objects page. This drives the whole set through # both sides rather than naming a few characters, so adding one to the helper without # adding it here fails this case instead of reaching the page. - # Every character Get-MtSafeMarkdown escapes, except '[' and ']'. Those two are left out - # for a reason that is not the unescape pattern: $linkPattern admits at most one level of - # brackets in a name, so an escaped bracket breaks the link match before the unescape is - # ever reached. That is a pre-existing limit of the link pattern and is unchanged here. - $chars = @('\', '`', '*', '_', '(', ')', '!', '|', '<', '>', '~', ':', '@') + $chars = @('\', '`', '*', '_', '[', ']', '(', ')', '!', '|', '<', '>', '~', ':', '@') foreach ($c in $chars) { $nombre = InModuleScope Maester -Parameters @{ C = $c } { param($C) @@ -1301,3 +1297,28 @@ Describe 'Affected objects' { } } } + +Describe 'Conditional Access plan affected objects' { + It 'Keeps a rule identity while linking to its parent plan' { + $record = InModuleScope Maester { + ConvertTo-MtAffectedObjectRecord -GraphObjectType ConditionalAccess -GraphObjects ([pscustomobject]@{ + id = '11111111-1111-1111-1111-111111111111' + displayName = 'Rule' + planId = '22222222-2222-2222-2222-222222222222' + sourceType = 'PolicyPlanRule' + }) + } + $record.Type | Should -Be ConditionalAccessPolicyRule + $record.Id | Should -Be '11111111-1111-1111-1111-111111111111' + $record.AnchorKind | Should -Be Instance + $record.PortalLink | Should -BeLike '*PolicyPlanView.ReactView/planId/22222222-2222-2222-2222-222222222222' + } + + It 'Recognizes a plan deep link in existing Markdown reports' { + $record = InModuleScope Maester { + Get-MtAffectedObjectFromMarkdown -Markdown '[Plan](https://entra.microsoft.com/#view/Microsoft_AAD_ConditionalAccess/PolicyPlanView.ReactView/planId/22222222-2222-2222-2222-222222222222)' + } + $record.Type | Should -Be ConditionalAccessPolicyPlan + $record.Id | Should -Be '22222222-2222-2222-2222-222222222222' + } +} diff --git a/powershell/tests/functions/Get-MtConditionalAccessPolicy.Tests.ps1 b/powershell/tests/functions/Get-MtConditionalAccessPolicy.Tests.ps1 new file mode 100644 index 0000000000..c39cd6d671 --- /dev/null +++ b/powershell/tests/functions/Get-MtConditionalAccessPolicy.Tests.ps1 @@ -0,0 +1,375 @@ +BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force + InModuleScope Maester { + $script:PlanReportingPreviousPortalUrl = $__MtSession.AdminPortalUrl + $__MtSession.AdminPortalUrl = @{ Entra = 'https://entra.microsoft.com/' } + } + . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" + Use-MtModuleFunction -Name ConvertTo-MtConditionalAccessPolicy, Merge-MtConditionalAccessCondition, Test-MtCaDeviceComplianceExists + $script:planFixture = Get-Content "$PSScriptRoot/../fixtures/conditional-access-plans/plan.json" -Raw | ConvertFrom-Json + $script:ruleFixture = (Get-Content "$PSScriptRoot/../fixtures/conditional-access-plans/rules.json" -Raw | ConvertFrom-Json).value + $script:evaluatedFixture = (Get-Content "$PSScriptRoot/../fixtures/conditional-access-plans/requester-windows-resource-a.json" -Raw | ConvertFrom-Json).value + function New-PlanFixture { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Returns a fresh in-memory fixture copy without changing external state.')] + [CmdletBinding()] + param() + + $script:planFixture | ConvertTo-Json -Depth 100 | ConvertFrom-Json + } + function New-RuleFixture { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Returns a fresh in-memory fixture copy without changing external state.')] + [CmdletBinding()] + param() + + $script:ruleFixture[1] | ConvertTo-Json -Depth 100 | ConvertFrom-Json + } +} + +Describe 'Conditional Access plan inventory' { + BeforeEach { + Mock Invoke-MtGraphRequest -ModuleName Maester { throw "Unexpected endpoint: $RelativeUri" } + Mock Invoke-MtGraphRequest -ModuleName Maester { @() } -ParameterFilter { $RelativeUri -eq 'identity/conditionalAccess/plans' } + Mock Invoke-MtGraphRequest -ModuleName Maester { + [pscustomobject]@{ id = 'standalone'; state = 'enabled'; displayName = 'Standalone' } + } -ParameterFilter { $RelativeUri -eq 'identity/conditionalAccess/policies' } + } + + It 'Accepts an empty plans inventory alongside standalone policies' { + $result = @(Get-MtConditionalAccessPolicy) + $result.Count | Should -Be 1 + $result[0].id | Should -Be standalone + } + + It 'Does not invent plans when both inventories are empty' { + Mock Invoke-MtGraphRequest -ModuleName Maester { @() } -ParameterFilter { $RelativeUri -eq 'identity/conditionalAccess/policies' } + @(Get-MtConditionalAccessPolicy).Count | Should -Be 0 + } + + It 'Offers an explicit standalone inventory without any preview request' { + @(Get-MtConditionalAccessPolicy -StandaloneOnly).Count | Should -Be 1 + Should -Not -Invoke Invoke-MtGraphRequest -ModuleName Maester -ParameterFilter { $RelativeUri -eq 'identity/conditionalAccess/plans' } + } + + It 'Propagates forbidden plans access rather than silently returning standalone-only data' { + Mock Invoke-MtGraphRequest -ModuleName Maester { throw '403 Forbidden' } -ParameterFilter { $RelativeUri -eq 'identity/conditionalAccess/plans' } + { Get-MtConditionalAccessPolicy } | Should -Throw '*403 Forbidden*' + } + + It 'Propagates a failed rule read' { + Mock Invoke-MtGraphRequest -ModuleName Maester { [pscustomobject]@{ id = 'plan' } } -ParameterFilter { $RelativeUri -eq 'identity/conditionalAccess/plans' } + Mock Invoke-MtGraphRequest -ModuleName Maester { throw '503 Unavailable' } -ParameterFilter { $RelativeUri -eq 'identity/conditionalAccess/plans/plan/rules' } + { Get-MtConditionalAccessPolicy } | Should -Throw '*503 Unavailable*' + } + + It 'Rejects a malformed plan instead of treating it as an empty inventory' { + Mock Invoke-MtGraphRequest -ModuleName Maester { [pscustomobject]@{ displayName = 'Missing ID' } } -ParameterFilter { $RelativeUri -eq 'identity/conditionalAccess/plans' } + { Get-MtConditionalAccessPolicyPlan } | Should -Throw '*without an ID*' + } + + It 'Reads every rule and leaves cached plan objects unchanged' { + $script:cachedPlan = [pscustomobject]@{ id = 'plan'; displayName = 'Plan'; owners = @('owner') } + Mock Invoke-MtGraphRequest -ModuleName Maester { $script:cachedPlan } -ParameterFilter { $RelativeUri -eq 'identity/conditionalAccess/plans' } + Mock Invoke-MtGraphRequest -ModuleName Maester { @([pscustomobject]@{ id = 'rule-a' }, [pscustomobject]@{ id = 'rule-b' }) } -ParameterFilter { $RelativeUri -eq 'identity/conditionalAccess/plans/plan/rules' } + $result = @(Get-MtConditionalAccessPolicyPlan) + $result[0].rules.Count | Should -Be 2 + $script:cachedPlan.PSObject.Properties.Name | Should -Not -Contain rules + $result[0].rules[0].controls | Should -BeNullOrEmpty + Should -Invoke Invoke-MtGraphRequest -ModuleName Maester -Times 2 -Exactly -ParameterFilter { -not $DisableCache -and $ApiVersion -eq 'beta' } + } + + It 'Reads owner metadata without requesting child rules' { + Mock Invoke-MtGraphRequest -ModuleName Maester { [pscustomobject]@{ id = 'plan'; owners = @('owner') } } -ParameterFilter { $RelativeUri -eq 'identity/conditionalAccess/plans' } + $result = @(Get-MtConditionalAccessPolicyPlan -MetadataOnly) + $result[0].owners | Should -Be @('owner') + Should -Not -Invoke Invoke-MtGraphRequest -ModuleName Maester -ParameterFilter { $RelativeUri -like '*/rules' } + } + + It 'Retains the real rule ID and state in a combined inventory' { + Mock Invoke-MtGraphRequest -ModuleName Maester { $script:planFixture } -ParameterFilter { $RelativeUri -eq 'identity/conditionalAccess/plans' } + Mock Invoke-MtGraphRequest -ModuleName Maester { $script:ruleFixture } -ParameterFilter { $RelativeUri -like 'identity/conditionalAccess/plans/*/rules' } + $result = @(Get-MtConditionalAccessPolicy) + $result.Count | Should -Be 3 + $result[1].id | Should -Be $script:ruleFixture[0].id + $result[1].state | Should -Be enabledForReportingButNotEnforced + $result[1].sourceType | Should -Be PolicyPlanRule + $result[1].planId | Should -Be $script:planFixture.id + } +} + +Describe 'Plan rule projection' { + It 'Matches inherited targeting and controls in anonymized live Entra evaluation fixtures' { + foreach ($rule in $script:ruleFixture) { + $policy = ConvertTo-MtConditionalAccessPolicy -Plan $script:planFixture -Rule $rule + $engine = $script:evaluatedFixture | Where-Object id -EQ $rule.id + $policy.conditions.users | ConvertTo-Json -Depth 30 -Compress | Should -Be ($engine.conditions.users | ConvertTo-Json -Depth 30 -Compress) + $expectedApplications = [ordered]@{} + foreach ($key in $policy.conditions.applications.Keys) { $expectedApplications[$key] = $engine.conditions.applications.$key } + $policy.conditions.applications | ConvertTo-Json -Depth 30 -Compress | Should -Be ($expectedApplications | ConvertTo-Json -Depth 30 -Compress) + $policy.conditions.platforms | ConvertTo-Json -Depth 30 -Compress | Should -Be ($engine.conditions.platforms | ConvertTo-Json -Depth 30 -Compress) + $policy.grantControls.builtInControls | Should -Be $engine.grantControls.builtInControls + $policy.grantControls.operator | Should -Be $engine.grantControls.operator + $policy.state | Should -Be $engine.state + } + } + + It 'Accumulates shared and per-rule exclusions without mutating either source' { + $plan = New-PlanFixture + $rule = New-RuleFixture + $rule.conditions.users = [pscustomobject]@{ excludeUsers = @('rule-exclusion') } + $beforePlan = $plan | ConvertTo-Json -Depth 100 -Compress + $beforeRule = $rule | ConvertTo-Json -Depth 100 -Compress + $policy = ConvertTo-MtConditionalAccessPolicy -Plan $plan -Rule $rule + $policy.conditions.users.excludeUsers | Should -Contain $plan.sharedConditions.users.excludeUsers[0] + $policy.conditions.users.excludeUsers | Should -Contain rule-exclusion + ($plan | ConvertTo-Json -Depth 100 -Compress) | Should -Be $beforePlan + ($rule | ConvertTo-Json -Depth 100 -Compress) | Should -Be $beforeRule + } + + It 'Projects a rule without reading sibling rule payloads' { + $result = InModuleScope Maester -Parameters @{ Plan = (New-PlanFixture); Rule = (New-RuleFixture) } { + param($Plan, $Rule) + $script:ProjectionSiblingReads = 0 + $Plan.PSObject.Properties.Remove('rules') + $Plan | Add-Member -MemberType ScriptProperty -Name rules -Value { + $script:ProjectionSiblingReads++ + @([pscustomobject]@{ id = 'unrelated-rule' }) + } + try { + $policy = ConvertTo-MtConditionalAccessPolicy -Plan $Plan -Rule $Rule + [pscustomobject]@{ Reads = $script:ProjectionSiblingReads; Policy = $policy } + } finally { + Remove-Variable ProjectionSiblingReads -Scope Script + } + } + $result.Reads | Should -Be 0 + $result.Policy.id | Should -Be $script:ruleFixture[1].id + $result.Policy.conditions.users.excludeUsers | Should -Be $script:planFixture.sharedConditions.users.excludeUsers + } + + It 'Keeps shared conditions independent of the cached parent after projection' { + $plan = New-PlanFixture + $before = $plan | ConvertTo-Json -Depth 100 -Compress + $policy = ConvertTo-MtConditionalAccessPolicy -Plan $plan -Rule (New-RuleFixture) + $policy.sharedConditions.users.excludeUsers[0] = 'changed-in-result' + ($plan | ConvertTo-Json -Depth 100 -Compress) | Should -Be $before + } + + It 'Preserves a rule state of <State>' -ForEach @( + @{ State = 'enabled' }, @{ State = 'disabled' }, @{ State = 'enabledForReportingButNotEnforced' } + ) { + $rule = New-RuleFixture + $rule.state = $State + (ConvertTo-MtConditionalAccessPolicy -Plan $script:planFixture -Rule $rule).state | Should -Be $State + } + + It 'Retains AND/OR and authentication strength requirements without changing their meaning' { + $rule = New-RuleFixture + $rule.controls.grantControls.operator = 'AND' + $rule.controls.grantControls.builtInControls = @('mfa', 'compliantDevice') + $rule.controls.grantControls.authenticationStrength = [pscustomobject]@{ id = 'strength'; requirementsSatisfied = 'mfa' } + $policy = ConvertTo-MtConditionalAccessPolicy -Plan $script:planFixture -Rule $rule + $policy.grantControls.operator | Should -Be AND + $policy.grantControls.builtInControls | Should -Be @('mfa', 'compliantDevice') + $policy.grantControls.authenticationStrength.id | Should -Be strength + } + + It 'Preserves session-only controls' { + $rule = New-RuleFixture + $rule.controls.grantControls = $null + $rule.controls.sessionControls = [pscustomobject]@{ signInFrequency = @{ isEnabled = $true; value = 1; type = 'hours' } } + $policy = ConvertTo-MtConditionalAccessPolicy -Plan $script:planFixture -Rule $rule + $policy.sessionControls.signInFrequency.value | Should -Be 1 + $policy.grantControls | Should -BeNullOrEmpty + } + + It 'Does not put owners into user assignments' { + $policy = ConvertTo-MtConditionalAccessPolicy -Plan $script:planFixture -Rule $script:ruleFixture[0] + $policy.planOwners.Count | Should -Be 2 + foreach ($owner in $policy.planOwners) { $policy.conditions.users.includeUsers | Should -Not -Contain $owner } + } + + It 'Rejects unknown states and missing enforcement controls' { + $rule = New-RuleFixture + $rule.state = 'futureState' + { ConvertTo-MtConditionalAccessPolicy -Plan $script:planFixture -Rule $rule } | Should -Throw '*unsupported state*' + $rule.state = 'enabled'; $rule.controls = $null + { ConvertTo-MtConditionalAccessPolicy -Plan $script:planFixture -Rule $rule } | Should -Throw '*enforcement controls*' + } + + It 'Rejects conflicting filters instead of claiming coverage with an overwritten filter' { + $plan = New-PlanFixture + $rule = New-RuleFixture + $plan.sharedConditions.devices = @{ deviceFilter = @{ mode = 'include'; rule = 'device.isCompliant -eq True' } } + $rule.conditions.devices = @{ deviceFilter = @{ mode = 'include'; rule = 'device.trustType -eq "AzureAD"' } } + { ConvertTo-MtConditionalAccessPolicy -Plan $plan -Rule $rule } | Should -Throw '*Cannot safely combine*conditions.devices.deviceFilter.rule*' + } + + It 'Unions inherited target lists and multi-valued flags' { + $result = Merge-MtConditionalAccessCondition -Shared @{ users = @{ includeGroups = @('a'); includeGuestsOrExternalUsers = @{ guestOrExternalUserTypes = 'internalGuest' } }; signInRiskLevels = @('high') } -Rule @{ users = @{ includeGroups = @('b', 'a'); includeGuestsOrExternalUsers = @{ guestOrExternalUserTypes = 'b2bCollaborationGuest' } }; signInRiskLevels = @('medium') } + $result.users.includeGroups | Should -Be @('a', 'b') + $result.signInRiskLevels | Should -Be @('high', 'medium') + $result.users.includeGuestsOrExternalUsers.guestOrExternalUserTypes | Should -Be 'internalGuest,b2bCollaborationGuest' + } + + It 'Rejects a guest-scope union that would introduce type/tenant cross-products' { + $shared = @{ users = @{ includeGuestsOrExternalUsers = @{ guestOrExternalUserTypes = 'internalGuest'; externalTenants = @{ membershipKind = 'enumerated'; members = @('tenant-a') } } } } + $rule = @{ users = @{ includeGuestsOrExternalUsers = @{ guestOrExternalUserTypes = 'b2bCollaborationGuest'; externalTenants = @{ membershipKind = 'enumerated'; members = @('tenant-b') } } } } + { Merge-MtConditionalAccessCondition -Shared $shared -Rule $rule } | Should -Throw '*without broadening*' + } + + It 'Merges equivalent tenant sets independently of order for <Scope>' -ForEach @( + @{ Scope = 'includeGuestsOrExternalUsers' } + @{ Scope = 'excludeGuestsOrExternalUsers' } + ) { + $shared = @{ guestOrExternalUserTypes = 'internalGuest'; externalTenants = [ordered]@{ membershipKind = 'enumerated'; members = @('tenant-a', 'tenant-b') } } + $rule = @{ guestOrExternalUserTypes = 'b2bCollaborationGuest'; externalTenants = [ordered]@{ members = @('TENANT-B', 'tenant-a', 'tenant-a'); membershipKind = 'enumerated' } } + $beforeShared = $shared | ConvertTo-Json -Depth 100 -Compress + $beforeRule = $rule | ConvertTo-Json -Depth 100 -Compress + $result = Merge-MtConditionalAccessCondition -Shared $shared -Rule $rule -PropertyPath "conditions.users.$Scope" + $result.guestOrExternalUserTypes | Should -Be 'internalGuest,b2bCollaborationGuest' + $result.externalTenants.members | Should -Be @('tenant-a', 'tenant-b') + ($shared | ConvertTo-Json -Depth 100 -Compress) | Should -Be $beforeShared + ($rule | ConvertTo-Json -Depth 100 -Compress) | Should -Be $beforeRule + } + + It 'Keeps absent, all and enumerated tenant scopes distinct for <Scope>' -ForEach @( + @{ Scope = 'includeGuestsOrExternalUsers' } + @{ Scope = 'excludeGuestsOrExternalUsers' } + ) { + foreach ($pair in @( + @{ Shared = $null; Rule = @{ membershipKind = 'all' } } + @{ Shared = $null; Rule = @{ membershipKind = 'enumerated'; members = @() } } + @{ Shared = @{ membershipKind = 'all' }; Rule = @{ membershipKind = 'enumerated'; members = @() } } + @{ Shared = @{ membershipKind = 'enumerated'; members = @('tenant-a') }; Rule = @{ membershipKind = 'enumerated'; members = @() } } + @{ Shared = @{ membershipKind = 'enumerated'; members = @('tenant-a') }; Rule = @{ membershipKind = 'enumerated'; members = @('tenant-b') } } + )) { + $shared = @{ guestOrExternalUserTypes = 'internalGuest'; externalTenants = $pair.Shared } + $rule = @{ guestOrExternalUserTypes = 'b2bCollaborationGuest'; externalTenants = $pair.Rule } + { Merge-MtConditionalAccessCondition -Shared $shared -Rule $rule -PropertyPath "conditions.users.$Scope" } | Should -Throw '*without broadening*' + } + } + + It 'Merges different guest types when both tenant scopes are all' { + $shared = @{ guestOrExternalUserTypes = 'internalGuest'; externalTenants = @{ membershipKind = 'all' } } + $rule = @{ guestOrExternalUserTypes = 'b2bCollaborationGuest'; externalTenants = @{ membershipKind = 'all' } } + $result = Merge-MtConditionalAccessCondition -Shared $shared -Rule $rule -PropertyPath 'conditions.users.includeGuestsOrExternalUsers' + $result.externalTenants.membershipKind | Should -Be all + $result.guestOrExternalUserTypes | Should -Be 'internalGuest,b2bCollaborationGuest' + } + + It 'Does not mistake Graph response annotations for targeting conflicts' { + $result = Merge-MtConditionalAccessCondition -Shared @{ '@odata.context' = 'shared'; clientAppTypes = @('all') } -Rule @{ '@odata.context' = 'rule'; clientAppTypes = @('browser') } + $result.clientAppTypes | Should -Be @('all') + $result.Contains('@odata.context') | Should -BeFalse + } + + It 'Preserves the all-external-tenants scope when unioned with selected tenants' { + $result = Merge-MtConditionalAccessCondition -Shared @{ users = @{ excludeGuestsOrExternalUsers = @{ externalTenants = @{ membershipKind = 'all' } } } } -Rule @{ users = @{ excludeGuestsOrExternalUsers = @{ externalTenants = @{ membershipKind = 'enumerated'; members = @('tenant') } } } } + $result.users.excludeGuestsOrExternalUsers.externalTenants.membershipKind | Should -Be all + } +} + +Describe 'Plans participate in an existing native CA check' { + BeforeEach { + Mock Add-MtTestResultDetail -ModuleName Maester {} + Mock Invoke-MtGraphRequest -ModuleName Maester { @() } -ParameterFilter { $RelativeUri -eq 'identity/conditionalAccess/policies' } + Mock Invoke-MtGraphRequest -ModuleName Maester { $script:planFixture } -ParameterFilter { $RelativeUri -eq 'identity/conditionalAccess/plans' } + $script:testRule = New-RuleFixture + Mock Invoke-MtGraphRequest -ModuleName Maester { $script:testRule } -ParameterFilter { $RelativeUri -like 'identity/conditionalAccess/plans/*/rules' } + } + + It 'Recognizes enabled device-compliance enforcement supplied only by a plan' { + $script:testRule.state = 'enabled' + Test-MtCaDeviceComplianceExists | Should -BeTrue + } + + It 'Does not count a <State> rule as active protection' -ForEach @( + @{ State = 'disabled' }, @{ State = 'enabledForReportingButNotEnforced' } + ) { + $script:testRule.state = $State + Test-MtCaDeviceComplianceExists | Should -BeFalse + } +} + +Describe 'Plan inventory transport uses cached paging' { + BeforeEach { + InModuleScope Maester { $__MtSession.GraphCache = @{} } + Mock Get-MgContext -ModuleName Maester { @{ Environment = 'Global'; TenantId = 'plan-test-tenant' } } + Mock Get-MgEnvironment -ModuleName Maester { @{ GraphEndpoint = 'https://graph.microsoft.com/' } } + Mock Invoke-MgGraphRequest -ModuleName Maester { + switch -Wildcard ($Uri.ToString()) { + '*plans/plan-a/rules' { return [pscustomobject]@{ value = @(@{ id = 'rule-a' }) } } + '*plans/plan-b/rules' { return [pscustomobject]@{ value = @(@{ id = 'rule-b' }) } } + '*plans?*skiptoken*' { return [pscustomobject]@{ value = @(@{ id = 'plan-b'; displayName = 'B' }) } } + '*conditionalAccess/plans*' { return [pscustomobject]@{ value = @(@{ id = 'plan-a'; displayName = 'A' }); '@odata.nextLink' = 'https://graph.microsoft.com/beta/identity/conditionalAccess/plans?$skiptoken=next' } } + default { throw "Unexpected URI: $Uri" } + } + } + } + + It 'Reads the next page and reuses the completed plans and rules inventories' { + $first = @(Get-MtConditionalAccessPolicyPlan) + $second = @(Get-MtConditionalAccessPolicyPlan) + $first.Count | Should -Be 2 + $second[1].rules[0].id | Should -Be rule-b + Should -Invoke Invoke-MgGraphRequest -ModuleName Maester -Times 4 -Exactly + } +} + +Describe 'Plan rule reporting through the actual device-compliance check' { + BeforeEach { + Mock Invoke-MtGraphRequest -ModuleName Maester { throw "Unexpected endpoint: $RelativeUri" } + Mock Invoke-MtGraphRequest -ModuleName Maester { @() } -ParameterFilter { $RelativeUri -eq 'identity/conditionalAccess/policies' } + Mock Invoke-MtGraphRequest -ModuleName Maester { $script:planFixture } -ParameterFilter { $RelativeUri -eq 'identity/conditionalAccess/plans' } + $script:reportRules = $script:ruleFixture | ConvertTo-Json -Depth 100 | ConvertFrom-Json + foreach ($rule in $script:reportRules) { + $rule.state = 'enabled' + $rule.controls.grantControls.builtInControls = @('compliantDevice') + } + $nonMatchingRule = New-RuleFixture + $nonMatchingRule.id = '00000000-0000-4000-8000-000000000009' + $nonMatchingRule.state = 'enabled' + $nonMatchingRule.controls.grantControls.builtInControls = @('mfa') + $script:reportRules += $nonMatchingRule + Mock Invoke-MtGraphRequest -ModuleName Maester { $script:reportRules } -ParameterFilter { $RelativeUri -like 'identity/conditionalAccess/plans/*/rules' } + } + + It 'Keeps two matching rules from one plan distinct, attributed and linked to their parent' { + $report = InModuleScope Maester { + $previousCollection = $__MtSession.IncludeAffectedObjects + $previousDetails = $__MtSession.TestResultDetail + $previousTest = [Maester.Engine.MtSession]::EnterTest('MT.1001') + try { + $__MtSession.IncludeAffectedObjects = $true + $__MtSession.TestResultDetail = @{} + $passed = Test-MtCaDeviceComplianceExists + $detail = $__MtSession.TestResultDetail['MT.1001'] + $inventory = @(Get-MtAffectedObject -ExcludeSessionCache -MaesterResults ([pscustomobject]@{ + Tests = @([pscustomobject]@{ Id = 'MT.1001'; ResultDetail = $detail }) + })) + [pscustomobject]@{ Passed = $passed; Detail = $detail; Inventory = $inventory } + } finally { + $__MtSession.IncludeAffectedObjects = $previousCollection + $__MtSession.TestResultDetail = $previousDetails + [Maester.Engine.MtSession]::ExitTest($previousTest) + } + } + + $report.Passed | Should -BeTrue + @($report.Detail.RelatedObjects).Count | Should -Be 2 + $report.Detail.RelatedObjects.Id | Sort-Object | Should -Be @($script:ruleFixture.id | Sort-Object) + $report.Detail.TestResult | Should -Not -Match '%TestResult%|PolicyBlade/policyId|00000000-0000-4000-8000-000000000009' + $report.Inventory.Count | Should -Be 2 + $report.Inventory.UniqueId | Select-Object -Unique | Should -HaveCount 2 + foreach ($record in $report.Inventory) { + $record.Type | Should -Be ConditionalAccessPolicyRule + $record.Tests | Should -Be @('MT.1001') + $record.Sources | Should -Contain GraphObjects + $record.PortalLink | Should -BeLike "*PolicyPlanView.ReactView/planId/$($script:planFixture.id)" + } + } +} + +AfterAll { + InModuleScope Maester { $__MtSession.AdminPortalUrl = $script:PlanReportingPreviousPortalUrl } +} diff --git a/powershell/tests/functions/Test-MtCaPlanHasOwner.Tests.ps1 b/powershell/tests/functions/Test-MtCaPlanHasOwner.Tests.ps1 new file mode 100644 index 0000000000..37ca225c50 --- /dev/null +++ b/powershell/tests/functions/Test-MtCaPlanHasOwner.Tests.ps1 @@ -0,0 +1,37 @@ +BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force + . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" + Use-MtModuleFunction -Name Test-MtCaPlanHasOwner +} +Describe 'Conditional Access plan accountability' { + BeforeEach { + Mock Add-MtTestResultDetail -ModuleName Maester {} + Mock Get-MtConditionalAccessPolicyPlan -ModuleName Maester { [pscustomobject]@{ id = 'plan'; owners = @('owner'); displayName = 'Plan' } } + } + It 'Passes when every plan records an owner' { + Test-MtCaPlanHasOwner | Should -BeTrue + Should -Invoke Get-MtConditionalAccessPolicyPlan -ModuleName Maester -Times 1 -ParameterFilter { $MetadataOnly } + } + It 'Fails on a plan without an owner without attributing administrative rights' { + Mock Get-MtConditionalAccessPolicyPlan -ModuleName Maester { [pscustomobject]@{ id = 'plan'; owners = @(); displayName = 'Unowned' } } + Test-MtCaPlanHasOwner | Should -BeFalse + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -Times 1 -ParameterFilter { $GraphObjectType -eq 'ConditionalAccessPlan' -and $GraphObjects[0].id -eq 'plan' } + } + It 'Treats null and whitespace entries as missing ownership' { + Mock Get-MtConditionalAccessPolicyPlan -ModuleName Maester { [pscustomobject]@{ id = 'plan'; owners = @($null, ' '); displayName = 'Unowned' } } + Test-MtCaPlanHasOwner | Should -BeFalse + } + It 'Skips a tenant without plans even if standalone policies exist' { + Mock Get-MtConditionalAccessPolicyPlan -ModuleName Maester { @() } + Test-MtCaPlanHasOwner | Should -BeNullOrEmpty + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -Times 1 -Exactly -ParameterFilter { $SkippedBecause -eq 'NotApplicable' } + } + It 'Does not mistake a forbidden inventory read for an empty plans inventory' { + Mock Get-MtConditionalAccessPolicyPlan -ModuleName Maester { throw '403 Forbidden' } + { Test-MtCaPlanHasOwner } | Should -Throw '*403*' + } + It 'Preserves service errors instead of returning a successful governance result' { + Mock Get-MtConditionalAccessPolicyPlan -ModuleName Maester { throw '503 unavailable' } + { Test-MtCaPlanHasOwner } | Should -Throw '*503*' + } +} diff --git a/powershell/tests/functions/Test-MtCisConditionalAccessReporting.Tests.ps1 b/powershell/tests/functions/Test-MtCisConditionalAccessReporting.Tests.ps1 new file mode 100644 index 0000000000..961854bbcf --- /dev/null +++ b/powershell/tests/functions/Test-MtCisConditionalAccessReporting.Tests.ps1 @@ -0,0 +1,126 @@ +BeforeDiscovery { + $script:CisReportingCases = foreach ($id in @('1.3.2') + @(1..13 + 15..17 | ForEach-Object { "5.2.2.$_" })) { + foreach ($state in @('enabled','disabled','enabledForReportingButNotEnforced')) { + @{ Id = "CIS.M365.$id"; State = $state; Expected = $state -eq 'enabled' } + } + } +} +BeforeAll { + $script:root = (Resolve-Path "$PSScriptRoot/../../..").Path + Import-Module "$script:root/powershell/Maester.psd1" -Force + $script:adminRoles = @(& (Get-Module Maester) { Get-MtCisAdministratorRole | ForEach-Object Id }) +} +Describe 'CIS Conditional Access tables with tenant-controlled names' { + BeforeEach { + $script:plan = Get-Content "$script:root/powershell/tests/fixtures/conditional-access-plans/plan.json" -Raw | ConvertFrom-Json -AsHashtable + $script:rule = (Get-Content "$script:root/powershell/tests/fixtures/conditional-access-plans/rules.json" -Raw | ConvertFrom-Json -AsHashtable).value[0] + $script:plan.displayName = "CA | [Prod] \ Main`nPlan" + $script:rule.displayName = 'MFA | **required** [review](https://example.invalid)' + $script:rule.conditions = $null + $script:standalonePolicy = $null + $script:rule.controls.grantControls = @{ operator='OR'; builtInControls=@('mfa'); customAuthenticationFactors=@(); termsOfUse=@(); authenticationStrength=$null } + $script:rule.controls.sessionControls = $null + $script:plan.sharedConditions.users = @{ includeUsers=@('All'); excludeUsers=@(); includeGroups=@();excludeGroups=@();includeRoles=$script:adminRoles;excludeRoles=@() } + $script:plan.sharedConditions.applications = @{ includeApplications=@('All');excludeApplications=@();includeUserActions=@();includeAuthenticationContextClassReferences=@();applicationFilter=$null } + Mock Test-MtConnection -ModuleName Maester { $true } + Mock Get-MgContext -ModuleName Maester { $null } + Mock Invoke-MtGraphRequest -ModuleName Maester { + switch -Wildcard ($RelativeUri) { + 'organization' { [pscustomobject]@{ DisplayName = 'Report test tenant' } } + 'identity/conditionalAccess/policies' { $script:standalonePolicy } + 'identity/conditionalAccess/plans' { [pscustomobject]$script:plan } + 'identity/conditionalAccess/plans/*/rules' { [pscustomobject]$script:rule } + 'identity/conditionalAccess/namedLocations' { @() } + 'policies/activityBasedTimeoutPolicies' { [pscustomobject]@{ definition=@('{"ActivityBasedTimeoutPolicy":{"ApplicationPolicies":[{"WebSessionIdleTimeout":"03:00:00"}]}}') } } + default { throw "Unexpected endpoint: $RelativeUri" } + } + } + } + It '<Id> preserves table columns and the <State> verdict for policies and plan rules' -ForEach $script:CisReportingCases { + $script:rule.state = $State + $scope = $script:plan.sharedConditions + $controls = $script:rule.controls + switch ($Id) { + 'CIS.M365.1.3.2' { + $scope.applications.includeApplications=@('Office365');$scope.clientAppTypes=@('browser') + $controls.sessionControls=@{applicationEnforcedRestrictions=@{isEnabled=$true}} + } + 'CIS.M365.5.2.2.3' { $scope.clientAppTypes=@('exchangeActiveSync','other');$controls.grantControls.builtInControls=@('block') } + 'CIS.M365.5.2.2.4' { $controls.sessionControls=@{persistentBrowser=@{isEnabled=$true;mode='never'};signInFrequency=@{isEnabled=$true;frequencyInterval='everyTime'}} } + 'CIS.M365.5.2.2.5' { $controls.grantControls.builtInControls=@();$controls.grantControls.authenticationStrength=@{id='strength';allowedCombinations=@('fido2')} } + 'CIS.M365.5.2.2.6' { + $scope.userRiskLevels=@('high');$controls.grantControls.operator='AND';$controls.grantControls.builtInControls=@('mfa','passwordChange') + $controls.sessionControls=@{signInFrequency=@{isEnabled=$true;frequencyInterval='everyTime'}} + } + 'CIS.M365.5.2.2.7' { $scope.signInRiskLevels=@('medium','high');$controls.grantControls.builtInControls=@('block') } + 'CIS.M365.5.2.2.8' { $scope.signInRiskLevels=@('medium','high');$controls.grantControls.builtInControls=@('block') } + 'CIS.M365.5.2.2.9' { $controls.grantControls.builtInControls=@('compliantDevice') } + 'CIS.M365.5.2.2.10' { + $scope.applications.includeApplications=@();$scope.applications.includeUserActions=@('urn:user:registersecurityinfo') + $controls.grantControls.builtInControls=@('compliantDevice') + } + 'CIS.M365.5.2.2.11' { + $scope.applications.includeApplications=@('d4ebce55-015a-49b5-a083-c84d1797ae8c') + $controls.sessionControls=@{signInFrequency=@{isEnabled=$true;frequencyInterval='everyTime'}} + } + 'CIS.M365.5.2.2.12' { $scope.authenticationFlows=@{transferMethods=@('deviceCodeFlow')};$controls.grantControls.builtInControls=@('block') } + 'CIS.M365.5.2.2.13' { $controls.sessionControls=@{signInFrequency=@{isEnabled=$true;frequencyInterval='everyTime'}} } + 'CIS.M365.5.2.2.15' { $scope.locations=@{includeLocations=@('All');excludeLocations=@('AllTrusted')};$controls.grantControls.builtInControls=@('block') } + 'CIS.M365.5.2.2.16' { + $scope.applications.includeApplications=@('00000002-0000-0ff1-ce00-000000000000','00000003-0000-0ff1-ce00-000000000000','cc15fd57-2c6c-4117-a88c-83b1d56b4bbe') + $scope.platforms=@{includePlatforms=@('windows');excludePlatforms=@()};$scope.clientAppTypes=@('mobileAppsAndDesktopClients') + $controls.sessionControls=@{secureSignInSession=@{isEnabled=$true}} + } + 'CIS.M365.5.2.2.17' { $scope.authenticationFlows=@{transferMethods=@('authenticationTransfer')};$controls.grantControls.builtInControls=@('block') } + } + $script:standalonePolicy = [pscustomobject]@{ + id = 'standalone-policy' + displayName = 'Standalone | [Prod] \ Access' + state = $State + conditions = $scope + grantControls = $controls.grantControls + sessionControls = $controls.sessionControls + } + $config = [pscustomobject]@{ + Environment = [pscustomobject]@{ + Licenses = @('AAD_PREMIUM', 'AAD_PREMIUM_P2') + Services = [pscustomobject]@{ Graph = $true } + } + } + $row = Invoke-MtTest -Id $Id -Config $config + $outcome = if ($Expected) { 'Passed' } else { 'Failed' } + $row.Result | Should -Be $outcome -Because ($row.ReasonDetail | Out-String) + $lines = @($row.ResultDetail.TestResult -split "`n" | Where-Object { $_.StartsWith('|') }) + $columnCount = ([regex]::Split($lines[0], '(?<!\\)\|')).Count + foreach ($line in $lines) { + ([regex]::Split($line, '(?<!\\)\|')).Count | Should -Be $columnCount -Because "each result row must keep the header's columns" + } + $candidates = @($lines | Where-Object { $_ -like '*Standalone*' -or $_ -like '*Main Plan*' }) + $candidates | Should -HaveCount 2 + foreach ($candidate in $candidates) { + $cells = [regex]::Split($candidate, '(?<!\\)\|') + $cells[-2].Trim() | Should -Be $(if ($Expected) { '✅ Pass' } else { '❌ Fail' }) + $candidate | Should -Match ([regex]::Escape($State)) + $candidate | Should -Match '\\\|' + } + # The raw inventory is still usable as data, rather than carrying Markdown escapes. + $script:standalonePolicy.displayName | Should -BeExactly 'Standalone | [Prod] \ Access' + $script:plan.displayName | Should -BeExactly "CA | [Prod] \ Main`nPlan" + $report = & (Get-Module Maester) { + param($row) + ConvertTo-MtMaesterResult -NativeRows @($row) -SkipVersionCheck + } $row + $html = Get-MtHtmlReport -MaesterResults $report + $match = [regex]::Match($html, '<script type="application/octet-stream" id="maester-report-data" data-encoding="gzip\+base64">([A-Za-z0-9+/=]*)</script>') + $match.Success | Should -BeTrue + $stream = [IO.MemoryStream]::new([Convert]::FromBase64String($match.Groups[1].Value)) + $reader = [IO.StreamReader]::new([IO.Compression.GZipStream]::new($stream, [IO.Compression.CompressionMode]::Decompress)) + try { $embedded = $reader.ReadToEnd() | ConvertFrom-Json } finally { $reader.Dispose() } + $embedded.Tests[0].Result | Should -Be $outcome + $embedded.Tests[0].ResultDetail.TestResult | Should -BeExactly $row.ResultDetail.TestResult + $embedded.PassedCount | Should -Be ([int]$Expected) + $embedded.FailedCount | Should -Be ([int](-not $Expected)) + Should -Invoke Invoke-MtGraphRequest -ModuleName Maester -Times 1 -Exactly -ParameterFilter { $RelativeUri -eq 'identity/conditionalAccess/plans' } + Should -Invoke Invoke-MtGraphRequest -ModuleName Maester -Times 1 -Exactly -ParameterFilter { $RelativeUri -like 'identity/conditionalAccess/plans/*/rules' } + } +} diff --git a/powershell/tests/functions/Test-MtConditionalAccessWhatIf.Tests.ps1 b/powershell/tests/functions/Test-MtConditionalAccessWhatIf.Tests.ps1 index b9e4b145fa..458779b284 100644 --- a/powershell/tests/functions/Test-MtConditionalAccessWhatIf.Tests.ps1 +++ b/powershell/tests/functions/Test-MtConditionalAccessWhatIf.Tests.ps1 @@ -1,5 +1,13 @@ BeforeAll { Import-Module "$PSScriptRoot/../../Maester.psd1" -Force + InModuleScope Maester { + $script:PlanReportingPreviousPortalUrl = $__MtSession.AdminPortalUrl + $__MtSession.AdminPortalUrl = @{ Entra = 'https://entra.microsoft.com/' } + } + . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" + Use-MtModuleFunction -Name Get-GraphObjectMarkdown, Test-MtCaWhatIfEmergencyAccessNotBlocked + $script:evaluationFixture = (Get-Content "$PSScriptRoot/../fixtures/conditional-access-plans/requester-windows-resource-a.json" -Raw | ConvertFrom-Json).value + $script:planFixture = Get-Content "$PSScriptRoot/../fixtures/conditional-access-plans/plan.json" -Raw | ConvertFrom-Json } Describe 'Test-MtConditionalAccessWhatIf' -Tag 'Unit' { @@ -8,6 +16,10 @@ Describe 'Test-MtConditionalAccessWhatIf' -Tag 'Unit' { $script:appId = '00000002-0000-0ff1-ce00-000000000000' } + BeforeEach { + Mock -ModuleName Maester Get-MtConditionalAccessPolicyPlan { @() } + } + It 'returns only the policies that apply' { Mock -ModuleName Maester Invoke-MgGraphRequest { [pscustomobject]@{ value = @( @@ -28,3 +40,146 @@ Describe 'Test-MtConditionalAccessWhatIf' -Tag 'Unit' { Should -Throw '*Insufficient privileges*' } } + +Describe 'What If plan-rule reporting' { + BeforeEach { + $script:evaluation = $script:evaluationFixture | ConvertTo-Json -Depth 100 | ConvertFrom-Json + Mock Invoke-MgGraphRequest -ModuleName Maester { [pscustomobject]@{ value = $script:evaluation } } -ParameterFilter { $Method -eq 'POST' } + Mock Get-MtConditionalAccessPolicyPlan -ModuleName Maester { $script:planFixture } + } + + It 'Enriches the evaluation fixture by rule ID and preserves every original field without mutating the response' { + $before = $script:evaluation | ConvertTo-Json -Depth 100 -Compress + $result = @(Test-MtConditionalAccessWhatIf -UserId $script:userId -IncludeApplications $script:appId) + $result.Count | Should -Be 2 + foreach ($policy in $result) { + $original = $script:evaluation | Where-Object id -EQ $policy.id + $policy.sourceType | Should -Be PolicyPlanRule + $policy.planId | Should -Be $script:planFixture.id + $policy.planDisplayName | Should -Be $script:planFixture.displayName + $originalFields = $policy | Select-Object -Property $original.PSObject.Properties.Name + ($originalFields | ConvertTo-Json -Depth 100 -Compress) | Should -Be ($original | ConvertTo-Json -Depth 100 -Compress) + Get-GraphObjectMarkdown -GraphObjects $policy -GraphObjectType ConditionalAccess -AsPlainTextLink | + Should -BeLike "*PolicyPlanView.ReactView/planId/$($script:planFixture.id)*" + } + ($script:evaluation | ConvertTo-Json -Depth 100 -Compress) | Should -Be $before + Should -Invoke Get-MtConditionalAccessPolicyPlan -ModuleName Maester -Times 1 -Exactly -ParameterFilter { -not $DisableCache } + } + + It 'Does not infer plan membership from names or change standalone evaluation results' { + $standalone = $script:evaluation[0] | Select-Object * + $standalone.id = '00000000-0000-4000-8000-000000000099' + $script:evaluation = @($standalone) + $before = $standalone | ConvertTo-Json -Depth 100 -Compress + $result = @(Test-MtConditionalAccessWhatIf -UserId $script:userId -IncludeApplications $script:appId) + ($result[0] | ConvertTo-Json -Depth 100 -Compress) | Should -Be $before + $result[0].PSObject.Properties.Name | Should -Not -Contain planId + Get-GraphObjectMarkdown -GraphObjects $result -GraphObjectType ConditionalAccess -AsPlainTextLink | + Should -BeLike "*PolicyBlade/policyId/$($standalone.id))" + } + + It 'Associates identically named rules and plans using their IDs' { + $secondPlan = $script:planFixture | ConvertTo-Json -Depth 100 | ConvertFrom-Json + $secondPlan.id = '00000000-0000-4000-8000-000000000010' + $secondPlan.rules = @($secondPlan.rules[1]) + $firstPlan = $script:planFixture | ConvertTo-Json -Depth 100 | ConvertFrom-Json + $firstPlan.rules = @($firstPlan.rules[0]) + $script:sameNamePlans = @($firstPlan, $secondPlan) + foreach ($policy in $script:evaluation) { $policy.displayName = 'Same name' } + Mock Get-MtConditionalAccessPolicyPlan -ModuleName Maester { $script:sameNamePlans } + $result = @(Test-MtConditionalAccessWhatIf -UserId $script:userId -IncludeApplications $script:appId) + $result[0].planId | Should -Be $firstPlan.id + $result[1].planId | Should -Be $secondPlan.id + $result.displayName | Should -Be @('Same name', 'Same name') + } + + It 'Preserves a nonapplying rule with AllResults and filters it otherwise' { + $script:evaluation[1].policyApplies = $false + $all = @(Test-MtConditionalAccessWhatIf -UserId $script:userId -IncludeApplications $script:appId -AllResults) + $applied = @(Test-MtConditionalAccessWhatIf -UserId $script:userId -IncludeApplications $script:appId) + $all.Count | Should -Be 2 + $all[1].policyApplies | Should -BeFalse + $all[1].planId | Should -Be $script:planFixture.id + $applied.id | Should -Be @($script:evaluation[0].id) + } + + It 'Does not read the inventory when no evaluation result applies' { + foreach ($policy in $script:evaluation) { $policy.policyApplies = $false } + @(Test-MtConditionalAccessWhatIf -UserId $script:userId -IncludeApplications $script:appId).Count | Should -Be 0 + Should -Not -Invoke Get-MtConditionalAccessPolicyPlan -ModuleName Maester + } + + It 'Propagates an unreadable inventory instead of rendering plan rules as standalone policies' { + Mock Get-MtConditionalAccessPolicyPlan -ModuleName Maester { throw '403 plans access denied' } + { Test-MtConditionalAccessWhatIf -UserId $script:userId -IncludeApplications $script:appId } | Should -Throw '*403 plans access denied*' + } + + It 'Keeps rule identity and plan links through the actual MT.1034 check and affected-object collector' { + $report = InModuleScope Maester -Parameters @{ UserId = $script:userId } { + param($UserId) + $previousCollection = $__MtSession.IncludeAffectedObjects + $previousDetails = $__MtSession.TestResultDetail + $previousTest = [Maester.Engine.MtSession]::EnterTest('MT.1034.0') + try { + $__MtSession.IncludeAffectedObjects = $true + $__MtSession.TestResultDetail = @{} + $passed = Test-MtCaWhatIfEmergencyAccessNotBlocked -Instance ([pscustomobject]@{ + Data = [pscustomobject]@{ id = $UserId; userPrincipalName = 'emergency@example.com' } + }) + $detail = $__MtSession.TestResultDetail['MT.1034.0'] + $inventory = @(Get-MtAffectedObject -ExcludeSessionCache -MaesterResults ([pscustomobject]@{ + Tests = @([pscustomobject]@{ Id = 'MT.1034.0'; ResultDetail = $detail }) + })) + [pscustomobject]@{ Passed = $passed; Detail = $detail; Inventory = $inventory } + } finally { + $__MtSession.IncludeAffectedObjects = $previousCollection + $__MtSession.TestResultDetail = $previousDetails + [Maester.Engine.MtSession]::ExitTest($previousTest) + } + } + $report.Passed | Should -BeFalse + $report.Detail.TestResult | Should -Not -Match 'PolicyBlade/policyId|%TestResult%' + $report.Inventory.Count | Should -Be 2 + $report.Inventory.Id | Sort-Object | Should -Be @($script:evaluationFixture.id | Sort-Object) + foreach ($record in $report.Inventory) { + $record.Type | Should -Be ConditionalAccessPolicyRule + $record.Tests | Should -Be @('MT.1034.0') + $record.PortalLink | Should -BeLike "*PolicyPlanView.ReactView/planId/$($script:planFixture.id)" + } + } +} + +AfterAll { + InModuleScope Maester { $__MtSession.AdminPortalUrl = $script:PlanReportingPreviousPortalUrl } +} + +Describe 'Repeated What If evaluations use the cached plan inventory' { + BeforeEach { + InModuleScope Maester { + $script:WhatIfPreviousGraphCache = $__MtSession.GraphCache + $__MtSession.GraphCache = @{} + } + Mock Get-MgContext -ModuleName Maester { @{ Environment = 'Global'; TenantId = 'plan-test-tenant' } } + Mock Get-MgEnvironment -ModuleName Maester { @{ GraphEndpoint = 'https://graph.microsoft.com/' } } + Mock Invoke-MgGraphRequest -ModuleName Maester { + if ($Method -eq 'POST') { return [pscustomobject]@{ value = $script:evaluationFixture } } + if ($Uri.ToString() -like '*/rules') { return [pscustomobject]@{ '@odata.context' = 'https://graph.microsoft.com/beta/$metadata#identity/conditionalAccess/plans/rules'; value = $script:planFixture.rules } } + if ($Uri.ToString() -like '*/plans') { return [pscustomobject]@{ '@odata.context' = 'https://graph.microsoft.com/beta/$metadata#identity/conditionalAccess/plans'; value = @($script:planFixture) } } + throw "Unexpected URI: $Uri" + } + } + + AfterEach { + InModuleScope Maester { $__MtSession.GraphCache = $script:WhatIfPreviousGraphCache } + } + + It 'Evaluates each scenario but reads the plan and rules only once' { + $first = @(Test-MtConditionalAccessWhatIf -UserId $script:userId -IncludeApplications $script:appId) + $second = @(Test-MtConditionalAccessWhatIf -UserId $script:userId -IncludeApplications $script:appId -DevicePlatform windows) + $first.Count | Should -Be 2 + $second.Count | Should -Be 2 + $second.planId | Select-Object -Unique | Should -Be $script:planFixture.id + Should -Invoke Invoke-MgGraphRequest -ModuleName Maester -Times 2 -Exactly -ParameterFilter { $Method -eq 'POST' } + Should -Invoke Invoke-MgGraphRequest -ModuleName Maester -Times 2 -Exactly -ParameterFilter { $Method -ne 'POST' } + } +} diff --git a/powershell/tests/general/GraphCacheUsage.Tests.ps1 b/powershell/tests/general/GraphCacheUsage.Tests.ps1 index ac1965b0f0..047b344f64 100644 --- a/powershell/tests/general/GraphCacheUsage.Tests.ps1 +++ b/powershell/tests/general/GraphCacheUsage.Tests.ps1 @@ -9,6 +9,7 @@ 'powershell/internal/services/graph/Invoke-MtGraphRequestCache.ps1' 'powershell/internal/services/entra/Get-MtDirectoryRoleAssignment.ps1' 'powershell/public/services/entra/Get-MtConditionalAccessPolicy.ps1' + 'powershell/public/services/entra/Get-MtConditionalAccessPolicyPlan.ps1' 'powershell/internal/services/global-secure-access/Get-MtPrivateAccessApplication.ps1' 'powershell/internal/services/defender/Get-MdeConfiguration.ps1' 'powershell/internal/services/github/Invoke-MtGitHubRequest.ps1' diff --git a/tests/cis/Test.CIS.M365.1.3.2.ps1 b/tests/cis/Test.CIS.M365.1.3.2.ps1 index 3a5308d250..864ab730d5 100644 --- a/tests/cis/Test.CIS.M365.1.3.2.ps1 +++ b/tests/cis/Test.CIS.M365.1.3.2.ps1 @@ -74,7 +74,7 @@ $resultMd += "| Web session idle timeout | $timeoutText | $(if ($timeoutOk) { '✅ Pass' } else { '❌ Fail' }) |`n" $resultMd += "| Conditional Access policy with app enforced restrictions | $(if ($policyOk) { 'Found' } else { 'Not found' }) | $(if ($policyOk) { '✅ Pass' } else { '❌ Fail' }) |`n" foreach ($row in $report) { - $resultMd += "| $($row.Name) ($($row.State)) | $(if ($row.Failed) { $row.Failed } else { 'None' }) | $(if ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" + $resultMd += "| $(Get-MtSafeMarkdown $row.Name) ($($row.State)) | $(if ($row.Failed) { $row.Failed } else { 'None' }) | $(if ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" } if ($testResult) { diff --git a/tests/cis/Test.CIS.M365.5.2.2.1.ps1 b/tests/cis/Test.CIS.M365.5.2.2.1.ps1 index efaf8f84f6..f9532109fa 100644 --- a/tests/cis/Test.CIS.M365.5.2.2.1.ps1 +++ b/tests/cis/Test.CIS.M365.5.2.2.1.ps1 @@ -66,7 +66,7 @@ $resultMd = "| Policy | State | Excluded applications | Failed checks | Result |`n" $resultMd += "| --- | --- | --- | --- | --- |`n" foreach ($row in $report) { - $resultMd += "| $($row.Name) | $($row.State) | $($row.ExcludedApplications) | $(if ($row.Failed) { $row.Failed } else { 'None' }) | $(if ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" + $resultMd += "| $(Get-MtSafeMarkdown $row.Name) | $($row.State) | $($row.ExcludedApplications) | $(if ($row.Failed) { $row.Failed } else { 'None' }) | $(if ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" } if ($testResult) { diff --git a/tests/cis/Test.CIS.M365.5.2.2.10.ps1 b/tests/cis/Test.CIS.M365.5.2.2.10.ps1 index 4889a07eb1..eb3922f874 100644 --- a/tests/cis/Test.CIS.M365.5.2.2.10.ps1 +++ b/tests/cis/Test.CIS.M365.5.2.2.10.ps1 @@ -63,7 +63,7 @@ $resultMd = "| Policy | State | Failed checks | Result |`n" $resultMd += "| --- | --- | --- | --- |`n" foreach ($row in $report) { - $resultMd += "| $($row.Name) | $($row.State) | $(if ($row.Failed) { $row.Failed } else { 'None' }) | $(if ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" + $resultMd += "| $(Get-MtSafeMarkdown $row.Name) | $($row.State) | $(if ($row.Failed) { $row.Failed } else { 'None' }) | $(if ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" } if ($testResult) { diff --git a/tests/cis/Test.CIS.M365.5.2.2.11.ps1 b/tests/cis/Test.CIS.M365.5.2.2.11.ps1 index bcfe6404e0..30b3831d33 100644 --- a/tests/cis/Test.CIS.M365.5.2.2.11.ps1 +++ b/tests/cis/Test.CIS.M365.5.2.2.11.ps1 @@ -66,7 +66,7 @@ $resultMd = "| Policy | State | Failed checks | Result |`n" $resultMd += "| --- | --- | --- | --- |`n" foreach ($row in $report) { - $resultMd += "| $($row.Name) | $($row.State) | $(if ($row.Failed) { $row.Failed } else { 'None' }) | $(if ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" + $resultMd += "| $(Get-MtSafeMarkdown $row.Name) | $($row.State) | $(if ($row.Failed) { $row.Failed } else { 'None' }) | $(if ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" } if ($testResult) { diff --git a/tests/cis/Test.CIS.M365.5.2.2.12.ps1 b/tests/cis/Test.CIS.M365.5.2.2.12.ps1 index a0602ef702..ccf98b7109 100644 --- a/tests/cis/Test.CIS.M365.5.2.2.12.ps1 +++ b/tests/cis/Test.CIS.M365.5.2.2.12.ps1 @@ -65,7 +65,7 @@ $resultMd = "| Policy | State | Failed checks | Result |`n" $resultMd += "| --- | --- | --- | --- |`n" foreach ($row in $report) { - $resultMd += "| $($row.Name) | $($row.State) | $(if ($row.Failed) { $row.Failed } else { 'None' }) | $(if ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" + $resultMd += "| $(Get-MtSafeMarkdown $row.Name) | $($row.State) | $(if ($row.Failed) { $row.Failed } else { 'None' }) | $(if ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" } if ($testResult) { diff --git a/tests/cis/Test.CIS.M365.5.2.2.13.ps1 b/tests/cis/Test.CIS.M365.5.2.2.13.ps1 index 2cc1346d61..21c1f783f4 100644 --- a/tests/cis/Test.CIS.M365.5.2.2.13.ps1 +++ b/tests/cis/Test.CIS.M365.5.2.2.13.ps1 @@ -74,7 +74,7 @@ $resultMd = "| Policy | State | Failed checks | Result |`n" $resultMd += "| --- | --- | --- | --- |`n" foreach ($row in $report) { - $resultMd += "| $($row.Name) | $($row.State) | $(if ($row.Failed) { $row.Failed } else { 'None' }) | $(if ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" + $resultMd += "| $(Get-MtSafeMarkdown $row.Name) | $($row.State) | $(if ($row.Failed) { $row.Failed } else { 'None' }) | $(if ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" } if ($testResult) { diff --git a/tests/cis/Test.CIS.M365.5.2.2.15.ps1 b/tests/cis/Test.CIS.M365.5.2.2.15.ps1 index f97c48284a..411006227a 100644 --- a/tests/cis/Test.CIS.M365.5.2.2.15.ps1 +++ b/tests/cis/Test.CIS.M365.5.2.2.15.ps1 @@ -73,7 +73,7 @@ $resultMd = "| Policy | State | Failed checks | Result |`n" $resultMd += "| --- | --- | --- | --- |`n" foreach ($row in $report) { - $resultMd += "| $($row.Name) | $($row.State) | $(if ($row.Failed) { $row.Failed } else { 'None' }) | $(if ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" + $resultMd += "| $(Get-MtSafeMarkdown $row.Name) | $($row.State) | $(if ($row.Failed) { $row.Failed } else { 'None' }) | $(if ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" } if ($testResult) { diff --git a/tests/cis/Test.CIS.M365.5.2.2.16.ps1 b/tests/cis/Test.CIS.M365.5.2.2.16.ps1 index b38d5a427a..58aadbd1ac 100644 --- a/tests/cis/Test.CIS.M365.5.2.2.16.ps1 +++ b/tests/cis/Test.CIS.M365.5.2.2.16.ps1 @@ -69,7 +69,7 @@ $resultMd = "| Policy | State | Failed checks | Result |`n" $resultMd += "| --- | --- | --- | --- |`n" foreach ($row in $report) { - $resultMd += "| $($row.Name) | $($row.State) | $(if ($row.Failed) { $row.Failed } else { 'None' }) | $(if ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" + $resultMd += "| $(Get-MtSafeMarkdown $row.Name) | $($row.State) | $(if ($row.Failed) { $row.Failed } else { 'None' }) | $(if ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" } if ($testResult) { diff --git a/tests/cis/Test.CIS.M365.5.2.2.17.ps1 b/tests/cis/Test.CIS.M365.5.2.2.17.ps1 index 4aab6c1c4b..2c1414e237 100644 --- a/tests/cis/Test.CIS.M365.5.2.2.17.ps1 +++ b/tests/cis/Test.CIS.M365.5.2.2.17.ps1 @@ -65,7 +65,7 @@ $resultMd = "| Policy | State | Failed checks | Result |`n" $resultMd += "| --- | --- | --- | --- |`n" foreach ($row in $report) { - $resultMd += "| $($row.Name) | $($row.State) | $(if ($row.Failed) { $row.Failed } else { 'None' }) | $(if ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" + $resultMd += "| $(Get-MtSafeMarkdown $row.Name) | $($row.State) | $(if ($row.Failed) { $row.Failed } else { 'None' }) | $(if ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" } if ($testResult) { diff --git a/tests/cis/Test.CIS.M365.5.2.2.2.ps1 b/tests/cis/Test.CIS.M365.5.2.2.2.ps1 index 54fa171663..c7597a3d1e 100644 --- a/tests/cis/Test.CIS.M365.5.2.2.2.ps1 +++ b/tests/cis/Test.CIS.M365.5.2.2.2.ps1 @@ -74,7 +74,7 @@ $resultMd = "| Policy | State | Excluded applications | Failed checks | Result |`n" $resultMd += "| --- | --- | --- | --- | --- |`n" foreach ($row in $report) { - $resultMd += "| $($row.Name) | $($row.State) | $($row.ExcludedApplications) | $(if ($row.Failed) { $row.Failed } else { 'None' }) | $(if ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" + $resultMd += "| $(Get-MtSafeMarkdown $row.Name) | $($row.State) | $($row.ExcludedApplications) | $(if ($row.Failed) { $row.Failed } else { 'None' }) | $(if ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" } if ($testResult) { diff --git a/tests/cis/Test.CIS.M365.5.2.2.3.ps1 b/tests/cis/Test.CIS.M365.5.2.2.3.ps1 index e41512a077..b56daf4cb8 100644 --- a/tests/cis/Test.CIS.M365.5.2.2.3.ps1 +++ b/tests/cis/Test.CIS.M365.5.2.2.3.ps1 @@ -64,7 +64,7 @@ $resultMd = "| Policy | State | Failed checks | Result |`n" $resultMd += "| --- | --- | --- | --- |`n" foreach ($row in $report) { - $resultMd += "| $($row.Name) | $($row.State) | $(if ($row.Failed) { $row.Failed } else { 'None' }) | $(if ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" + $resultMd += "| $(Get-MtSafeMarkdown $row.Name) | $($row.State) | $(if ($row.Failed) { $row.Failed } else { 'None' }) | $(if ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" } if ($testResult) { diff --git a/tests/cis/Test.CIS.M365.5.2.2.4.ps1 b/tests/cis/Test.CIS.M365.5.2.2.4.ps1 index adb246bb51..996e5ecca9 100644 --- a/tests/cis/Test.CIS.M365.5.2.2.4.ps1 +++ b/tests/cis/Test.CIS.M365.5.2.2.4.ps1 @@ -75,7 +75,7 @@ $resultMd = "| Policy | State | Failed checks | Result |`n" $resultMd += "| --- | --- | --- | --- |`n" foreach ($row in $report) { - $resultMd += "| $($row.Name) | $($row.State) | $(if ($row.Failed) { $row.Failed } else { 'None' }) | $(if ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" + $resultMd += "| $(Get-MtSafeMarkdown $row.Name) | $($row.State) | $(if ($row.Failed) { $row.Failed } else { 'None' }) | $(if ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" } if ($testResult) { diff --git a/tests/cis/Test.CIS.M365.5.2.2.5.ps1 b/tests/cis/Test.CIS.M365.5.2.2.5.ps1 index 820a423840..6284d44e13 100644 --- a/tests/cis/Test.CIS.M365.5.2.2.5.ps1 +++ b/tests/cis/Test.CIS.M365.5.2.2.5.ps1 @@ -69,7 +69,7 @@ $resultMd = "| Policy | State | Excluded applications | Failed checks | Result |`n" $resultMd += "| --- | --- | --- | --- | --- |`n" foreach ($row in $report) { - $resultMd += "| $($row.Name) | $($row.State) | $($row.ExcludedApplications) | $(if ($row.Failed) { $row.Failed } else { 'None' }) | $(if ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" + $resultMd += "| $(Get-MtSafeMarkdown $row.Name) | $($row.State) | $($row.ExcludedApplications) | $(if ($row.Failed) { $row.Failed } else { 'None' }) | $(if ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" } if ($testResult) { diff --git a/tests/cis/Test.CIS.M365.5.2.2.6.ps1 b/tests/cis/Test.CIS.M365.5.2.2.6.ps1 index 5df83d98fe..df688f38aa 100644 --- a/tests/cis/Test.CIS.M365.5.2.2.6.ps1 +++ b/tests/cis/Test.CIS.M365.5.2.2.6.ps1 @@ -67,7 +67,7 @@ $resultMd = "| Policy | State | Failed checks | Result |`n" $resultMd += "| --- | --- | --- | --- |`n" foreach ($row in $report) { - $resultMd += "| $($row.Name) | $($row.State) | $(if ($row.Failed) { $row.Failed } else { 'None' }) | $(if ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" + $resultMd += "| $(Get-MtSafeMarkdown $row.Name) | $($row.State) | $(if ($row.Failed) { $row.Failed } else { 'None' }) | $(if ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" } if ($testResult) { diff --git a/tests/cis/Test.CIS.M365.5.2.2.7.ps1 b/tests/cis/Test.CIS.M365.5.2.2.7.ps1 index f7e7b38769..5edd09a2dc 100644 --- a/tests/cis/Test.CIS.M365.5.2.2.7.ps1 +++ b/tests/cis/Test.CIS.M365.5.2.2.7.ps1 @@ -67,7 +67,7 @@ $resultMd = "| Policy | State | Failed checks | Result |`n" $resultMd += "| --- | --- | --- | --- |`n" foreach ($row in $report) { - $resultMd += "| $($row.Name) | $($row.State) | $(if ($row.Failed) { $row.Failed } else { 'None' }) | $(if ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" + $resultMd += "| $(Get-MtSafeMarkdown $row.Name) | $($row.State) | $(if ($row.Failed) { $row.Failed } else { 'None' }) | $(if ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" } if ($testResult) { diff --git a/tests/cis/Test.CIS.M365.5.2.2.8.ps1 b/tests/cis/Test.CIS.M365.5.2.2.8.ps1 index a2b0432629..586a2ee4b6 100644 --- a/tests/cis/Test.CIS.M365.5.2.2.8.ps1 +++ b/tests/cis/Test.CIS.M365.5.2.2.8.ps1 @@ -65,7 +65,7 @@ $resultMd = "| Policy | State | Failed checks | Result |`n" $resultMd += "| --- | --- | --- | --- |`n" foreach ($row in $report) { - $resultMd += "| $($row.Name) | $($row.State) | $(if ($row.Failed) { $row.Failed } else { 'None' }) | $(if ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" + $resultMd += "| $(Get-MtSafeMarkdown $row.Name) | $($row.State) | $(if ($row.Failed) { $row.Failed } else { 'None' }) | $(if ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" } if ($testResult) { diff --git a/tests/cis/Test.CIS.M365.5.2.2.9.ps1 b/tests/cis/Test.CIS.M365.5.2.2.9.ps1 index e81977a24c..6deee9a71a 100644 --- a/tests/cis/Test.CIS.M365.5.2.2.9.ps1 +++ b/tests/cis/Test.CIS.M365.5.2.2.9.ps1 @@ -62,7 +62,7 @@ $resultMd = "| Policy | State | Failed checks | Result |`n" $resultMd += "| --- | --- | --- | --- |`n" foreach ($row in $report) { - $resultMd += "| $($row.Name) | $($row.State) | $(if ($row.Failed) { $row.Failed } else { 'None' }) | $(if ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" + $resultMd += "| $(Get-MtSafeMarkdown $row.Name) | $($row.State) | $(if ($row.Failed) { $row.Failed } else { 'None' }) | $(if ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" } if ($testResult) { diff --git a/tests/maester/entra/Test.MT.1001.ps1 b/tests/maester/entra/Test.MT.1001.ps1 index 45084f37a1..a4bec0d55e 100644 --- a/tests/maester/entra/Test.MT.1001.ps1 +++ b/tests/maester/entra/Test.MT.1001.ps1 @@ -39,26 +39,27 @@ $policies = Get-MtConditionalAccessPolicy | Where-Object { $_.state -eq 'enabled' } + $matchingPolicies = [System.Collections.Generic.List[object]]::new() $result = $false $testDescription = ' It is recommended to have at least one Conditional Access policy that enforces the use of a compliant device. See [Require a compliant device, Microsoft Entra hybrid joined device, or MFA - Microsoft Learn](https://learn.microsoft.com/entra/identity/conditional-access/howto-conditional-access-policy-compliant-device)' - $testResult = "These Conditional Access policies enforce the use of a compliant device :`n`n" + $testResult = "These Conditional Access policies enforce the use of a compliant device :`n`n%TestResult%" foreach ($policy in $policies) { if ($policy.grantControls.builtInControls -contains 'compliantDevice') { Write-Verbose -Message "Found a Conditional Access policy requiring device compliance: $($policy.displayName)" $result = $true - $testResult += " - [$(Get-MtSafeMarkdown $policy.displayName)](https://entra.microsoft.com/#view/Microsoft_AAD_ConditionalAccess/PolicyBlade/policyId/$($($policy.id))?%23view/Microsoft_AAD_ConditionalAccess/ConditionalAccessBlade/~/Policies?=)`n" + $matchingPolicies.Add($policy) } } if ($result -eq $false) { $testResult = 'There was no Conditional Access policy requiring device compliance.' } - Add-MtTestResultDetail -Description $testDescription -Result $testResult + Add-MtTestResultDetail -Description $testDescription -Result $testResult -GraphObjects $matchingPolicies.ToArray() -GraphObjectType ConditionalAccess return $result } diff --git a/tests/maester/entra/Test.MT.1009.ps1 b/tests/maester/entra/Test.MT.1009.ps1 index cfae9f6cdc..416f39ff49 100644 --- a/tests/maester/entra/Test.MT.1009.ps1 +++ b/tests/maester/entra/Test.MT.1009.ps1 @@ -45,8 +45,9 @@ Legacy authentication is an unsecure method to authenticate. This function check Conditional Access policy that blocks legacy authentication. See [Block legacy authentication - Microsoft Learn](https://learn.microsoft.com/entra/identity/conditional-access/howto-conditional-access-policy-block-legacy)" - $testResult = "These Conditional Access policies block legacy authentication for other clients :`n`n" + $testResult = "These Conditional Access policies block legacy authentication for other clients :`n`n%TestResult%" + $matchingPolicies = [System.Collections.Generic.List[object]]::new() $result = $false foreach ($policy in $policies) { if ( $policy.grantControls.builtInControls -contains 'block' ` @@ -56,7 +57,7 @@ See [Block legacy authentication - Microsoft Learn](https://learn.microsoft.com/ ) { $result = $true $CurrentResult = $true - $testResult += " - [$(Get-MtSafeMarkdown $policy.displayName)](https://entra.microsoft.com/#view/Microsoft_AAD_ConditionalAccess/PolicyBlade/policyId/$($($policy.id))?%23view/Microsoft_AAD_ConditionalAccess/ConditionalAccessBlade/~/Policies?=)`n" + $matchingPolicies.Add($policy) } else { $CurrentResult = $false } @@ -66,7 +67,7 @@ See [Block legacy authentication - Microsoft Learn](https://learn.microsoft.com/ if ($result -eq $false) { $testResult = "There was no Conditional Access policy blocking legacy authentication for other clients." } - Add-MtTestResultDetail -Description $testDescription -Result $testResult + Add-MtTestResultDetail -Description $testDescription -Result $testResult -GraphObjects $matchingPolicies.ToArray() -GraphObjectType ConditionalAccess return $result } diff --git a/tests/maester/entra/Test.MT.1010.ps1 b/tests/maester/entra/Test.MT.1010.ps1 index 6f8fe50830..1a824fa378 100644 --- a/tests/maester/entra/Test.MT.1010.ps1 +++ b/tests/maester/entra/Test.MT.1010.ps1 @@ -44,8 +44,9 @@ Legacy authentication is an unsecure method to authenticate. This function check Conditional Access policy that blocks legacy authentication. See [Block legacy authentication - Microsoft Learn](https://learn.microsoft.com/entra/identity/conditional-access/howto-conditional-access-policy-block-legacy)' - $testResult = "These Conditional Access policies block legacy authentication for Exchange Active Sync:`n`n" + $testResult = "These Conditional Access policies block legacy authentication for Exchange Active Sync:`n`n%TestResult%" + $matchingPolicies = [System.Collections.Generic.List[object]]::new() $result = $false foreach ($policy in $policies) { if ( $policy.grantControls.builtInControls -contains 'block' -and @@ -56,7 +57,7 @@ See [Block legacy authentication - Microsoft Learn](https://learn.microsoft.com/ ) { $result = $true $currentResult = $true - $testResult += " - [$(Get-MtSafeMarkdown $policy.displayName)](https://entra.microsoft.com/#view/Microsoft_AAD_ConditionalAccess/PolicyBlade/policyId/$($($policy.id))?%23view/Microsoft_AAD_ConditionalAccess/ConditionalAccessBlade/~/Policies?=)`n" + $matchingPolicies.Add($policy) } else { $currentResult = $false } @@ -67,6 +68,6 @@ See [Block legacy authentication - Microsoft Learn](https://learn.microsoft.com/ $testResult = 'There was no Conditional Access policy blocking legacy authentication for Exchange Active Sync.' } - Add-MtTestResultDetail -Description $testDescription -Result $testResult + Add-MtTestResultDetail -Description $testDescription -Result $testResult -GraphObjects $matchingPolicies.ToArray() -GraphObjectType ConditionalAccess return $result } diff --git a/tests/maester/entra/Test.MT.1014.ps1 b/tests/maester/entra/Test.MT.1014.ps1 index ee62744ea9..77426d1ac4 100644 --- a/tests/maester/entra/Test.MT.1014.ps1 +++ b/tests/maester/entra/Test.MT.1014.ps1 @@ -77,8 +77,9 @@ Microsoft recommends requiring device compliance for administrators that are mem * User Administrator See [Require compliant or Microsoft Entra hybrid joined device for administrators - Microsoft Learn](https://aka.ms/CATemplatesAdminDevices)' - $testResult = "These Conditional Access policies require compliant or Microsoft Entra hybrid joined device for administrators:`n`n" + $testResult = "These Conditional Access policies require compliant or Microsoft Entra hybrid joined device for administrators:`n`n%TestResult%" + $matchingPolicies = [System.Collections.Generic.List[object]]::new() $result = $false foreach ($policy in $policies) { $PolicyIncludesAllRoles = $true @@ -101,7 +102,7 @@ See [Require compliant or Microsoft Entra hybrid joined device for administrator $policy.conditions.applications.includeApplications -eq 'All' ) { Write-Verbose -Message "Found a Conditional Access policy requiring device compliance for admins: $($policy.displayName)" - $testResult += " - [$(Get-MtSafeMarkdown $policy.displayName)](https://entra.microsoft.com/#view/Microsoft_AAD_ConditionalAccess/PolicyBlade/policyId/$($($policy.id))?%23view/Microsoft_AAD_ConditionalAccess/ConditionalAccessBlade/~/Policies?=)`n" + $matchingPolicies.Add($policy) $result = $true } } @@ -109,7 +110,7 @@ See [Require compliant or Microsoft Entra hybrid joined device for administrator if ($result -eq $false) { $testResult = 'There was no Conditional Access policy requiring compliant or Microsoft Entra hybrid joined device for administrators.' } - Add-MtTestResultDetail -Description $testDescription -Result $testResult + Add-MtTestResultDetail -Description $testDescription -Result $testResult -GraphObjects $matchingPolicies.ToArray() -GraphObjectType ConditionalAccess return $result } diff --git a/tests/maester/entra/Test.MT.1015.ps1 b/tests/maester/entra/Test.MT.1015.ps1 index 5c5a79741a..f0afbfce93 100644 --- a/tests/maester/entra/Test.MT.1015.ps1 +++ b/tests/maester/entra/Test.MT.1015.ps1 @@ -41,8 +41,9 @@ Microsoft recommends blocking access for unknown or unsupported device platforms. See [Block access for unknown or unsupported device platform - Microsoft Learn](https://learn.microsoft.com/entra/identity/conditional-access/howto-policy-unknown-unsupported-device)' - $testResult = "These Conditional Access policies block access for unknown or unsupported device platforms:`n`n" + $testResult = "These Conditional Access policies block access for unknown or unsupported device platforms:`n`n%TestResult%" + $matchingPolicies = [System.Collections.Generic.List[object]]::new() $result = $false foreach ($policy in $policies) { if ( $policy.grantControls.builtInControls -eq 'block' ` @@ -50,7 +51,7 @@ See [Block access for unknown or unsupported device platform - Microsoft Learn]( ) { $result = $true $CurrentResult = $true - $testResult += " - [$(Get-MtSafeMarkdown $policy.displayName)](https://entra.microsoft.com/#view/Microsoft_AAD_ConditionalAccess/PolicyBlade/policyId/$($($policy.id))?%23view/Microsoft_AAD_ConditionalAccess/ConditionalAccessBlade/~/Policies?=)`n" + $matchingPolicies.Add($policy) } else { $CurrentResult = $false } @@ -60,7 +61,7 @@ See [Block access for unknown or unsupported device platform - Microsoft Learn]( if ($result -eq $false) { $testResult = 'There was no Conditional Access policy blocking access for unknown or unsupported device platforms.' } - Add-MtTestResultDetail -Description $testDescription -Result $testResult + Add-MtTestResultDetail -Description $testDescription -Result $testResult -GraphObjects $matchingPolicies.ToArray() -GraphObjectType ConditionalAccess return $result } diff --git a/tests/maester/entra/Test.MT.1017.ps1 b/tests/maester/entra/Test.MT.1017.ps1 index 6d6cd6f2ba..5729890330 100644 --- a/tests/maester/entra/Test.MT.1017.ps1 +++ b/tests/maester/entra/Test.MT.1017.ps1 @@ -46,8 +46,9 @@ Microsoft recommends disabling browser persistence for users accessing the tenant from an unmanaged device. See [Require reauthentication and disable browser persistence - Microsoft Learn](https://aka.ms/CATemplatesBrowserSession)' - $testResult = "These Conditional Access policies enforce a non-persistent browser session:`n`n" + $testResult = "These Conditional Access policies enforce a non-persistent browser session:`n`n%TestResult%" + $matchingPolicies = [System.Collections.Generic.List[object]]::new() $result = $false foreach ($policy in $policies) { if (-not $AllDevices.IsPresent) { @@ -88,7 +89,7 @@ See [Require reauthentication and disable browser persistence - Microsoft Learn] ) { $result = $true $CurrentResult = $true - $testResult += " - [$(Get-MtSafeMarkdown $policy.displayName)](https://entra.microsoft.com/#view/Microsoft_AAD_ConditionalAccess/PolicyBlade/policyId/$($($policy.id))?%23view/Microsoft_AAD_ConditionalAccess/ConditionalAccessBlade/~/Policies?=)`n" + $matchingPolicies.Add($policy) } else { $CurrentResult = $false } @@ -99,6 +100,6 @@ See [Require reauthentication and disable browser persistence - Microsoft Learn] $testResult = 'There was no Conditional Access policy enforcing non persistent browser session for non-corporate devices.' } - Add-MtTestResultDetail -Description $testDescription -Result $testResult + Add-MtTestResultDetail -Description $testDescription -Result $testResult -GraphObjects $matchingPolicies.ToArray() -GraphObjectType ConditionalAccess return $result } diff --git a/tests/maester/entra/Test.MT.1018.ps1 b/tests/maester/entra/Test.MT.1018.ps1 index 25471b9f58..30665a8b5d 100644 --- a/tests/maester/entra/Test.MT.1018.ps1 +++ b/tests/maester/entra/Test.MT.1018.ps1 @@ -45,8 +45,9 @@ Microsoft recommends disabling browser persistence for users accessing the tenant from a unmanaged device. See [Require reauthentication and disable browser persistence - Microsoft Learn](https://aka.ms/CATemplatesBrowserSession)' - $testResult = "These Conditional Access policies enforce sign-in frequency:`n`n" + $testResult = "These Conditional Access policies enforce sign-in frequency:`n`n%TestResult%" + $matchingPolicies = [System.Collections.Generic.List[object]]::new() $result = $false foreach ($policy in $policies) { # Check if device filter for compliant or hybrid Azure AD joined devices is present @@ -76,7 +77,7 @@ See [Require reauthentication and disable browser persistence - Microsoft Learn] ) { $result = $true $CurrentResult = $true - $testResult += " - [$(Get-MtSafeMarkdown $policy.displayName)](https://entra.microsoft.com/#view/Microsoft_AAD_ConditionalAccess/PolicyBlade/policyId/$($($policy.id))?%23view/Microsoft_AAD_ConditionalAccess/ConditionalAccessBlade/~/Policies?=)`n" + $matchingPolicies.Add($policy) } else { $CurrentResult = $false } @@ -87,6 +88,6 @@ See [Require reauthentication and disable browser persistence - Microsoft Learn] $testResult = 'There was no Conditional Access policy enforcing sign-in frequency for non-corporate devices.' } - Add-MtTestResultDetail -Description $testDescription -Result $testResult + Add-MtTestResultDetail -Description $testDescription -Result $testResult -GraphObjects $matchingPolicies.ToArray() -GraphObjectType ConditionalAccess return $result } diff --git a/tests/maester/entra/Test.MT.1019.ps1 b/tests/maester/entra/Test.MT.1019.ps1 index 8b986aef65..be4ef4444e 100644 --- a/tests/maester/entra/Test.MT.1019.ps1 +++ b/tests/maester/entra/Test.MT.1019.ps1 @@ -42,8 +42,9 @@ Microsoft recommends blocking or limiting access to SharePoint, OneDrive, and Exchange content from unmanaged devices. See [Use application enforced restrictions for unmanaged devices - Microsoft Learn](https://aka.ms/CATemplatesAppRestrictions)' - $testResult = "These Conditional Access policies enforce restrictions for unmanaged devices:`n`n" + $testResult = "These Conditional Access policies enforce restrictions for unmanaged devices:`n`n%TestResult%" + $matchingPolicies = [System.Collections.Generic.List[object]]::new() $result = $false foreach ($policy in $policies) { if ( $policy.conditions.users.includeUsers -eq 'All' ` @@ -53,7 +54,7 @@ See [Use application enforced restrictions for unmanaged devices - Microsoft Lea ) { $result = $true $CurrentResult = $true - $testResult += " - [$(Get-MtSafeMarkdown $policy.displayName)](https://entra.microsoft.com/#view/Microsoft_AAD_ConditionalAccess/PolicyBlade/policyId/$($($policy.id))?%23view/Microsoft_AAD_ConditionalAccess/ConditionalAccessBlade/~/Policies?=)`n" + $matchingPolicies.Add($policy) } else { $CurrentResult = $false } @@ -64,6 +65,6 @@ See [Use application enforced restrictions for unmanaged devices - Microsoft Lea $testResult = 'There was no Conditional Access policy enforcing restrictions for unmanaged devices.' } - Add-MtTestResultDetail -Description $testDescription -Result $testResult + Add-MtTestResultDetail -Description $testDescription -Result $testResult -GraphObjects $matchingPolicies.ToArray() -GraphObjectType ConditionalAccess return $result } diff --git a/tests/maester/entra/Test.MT.1020.ps1 b/tests/maester/entra/Test.MT.1020.ps1 index 703666a8ca..9b4765e6cb 100644 --- a/tests/maester/entra/Test.MT.1020.ps1 +++ b/tests/maester/entra/Test.MT.1020.ps1 @@ -49,7 +49,7 @@ param () $testDescription = 'It is recommended to exclude directory/OnPremises synchronization accounts from all Conditional Access policies scoped to all cloud apps.' - $testResult = "The following Conditional Access policies are scoped to all users but don't exclude the directory/OnPremises synchronization accounts:`n`n" + $testResult = "The following Conditional Access policies are scoped to all users but don't exclude the directory/OnPremises synchronization accounts:`n`n%TestResult%" $DirectorySynchronizationAccountsRole = Get-MtRoleInfo -RoleName 'DirectorySynchronizationAccounts' $OnPremisesDirectorySyncAccountRole = Get-MtRoleInfo -RoleName 'OnPremisesDirectorySyncAccount' @@ -88,6 +88,7 @@ $policies = Get-MtConditionalAccessPolicy | Where-Object { $_.state -eq 'enabled' } + $matchingPolicies = [System.Collections.Generic.List[object]]::new() $result = $true foreach ($policy in ( $policies | Sort-Object -Property displayName ) ) { if ( $policy.conditions.applications.includeApplications -ne 'All' ) { @@ -156,7 +157,7 @@ # Directory synchronization accounts are not excluded $CurrentResult = $false $result = $false - $testResult += " - [$(Get-MtSafeMarkdown $policy.displayName)](https://entra.microsoft.com/#view/Microsoft_AAD_ConditionalAccess/PolicyBlade/policyId/$($($policy.id))?%23view/Microsoft_AAD_ConditionalAccess/ConditionalAccessBlade/~/Policies?=)`n" + $matchingPolicies.Add($policy) } } @@ -167,6 +168,6 @@ $testResult = 'All Conditional Access policies scoped to all cloud apps exclude the directory synchronization accounts.' } - Add-MtTestResultDetail -Description $testDescription -Result $testResult + Add-MtTestResultDetail -Description $testDescription -Result $testResult -GraphObjects $matchingPolicies.ToArray() -GraphObjectType ConditionalAccess return $result } diff --git a/tests/maester/entra/Test.MT.1275.md b/tests/maester/entra/Test.MT.1275.md new file mode 100644 index 0000000000..6179f6ca92 --- /dev/null +++ b/tests/maester/entra/Test.MT.1275.md @@ -0,0 +1,25 @@ +Every Conditional Access policy plan should record an accountable owner. + +Owner metadata helps administrators identify the team responsible for reviewing and maintaining a plan. Missing metadata is a governance hygiene finding: it does not disable policy enforcement. Plan ownership grants no administrator role or edit permission. + +This check examines only whether the `owners` collection contains an entry. It does not resolve owner IDs, verify account activity, or inspect group members. A deleted user ID can remain recorded on a plan and will therefore pass this presence check. Owner lifecycle and approval reachability require separate validation. + +Plans are optional. A tenant with no plans is **NotApplicable**, including a tenant protected entirely by standalone Conditional Access policies. A failed API read is an error, not an empty inventory. + +#### Remediation action + +1. In **Entra ID**, open **Conditional Access** > **[Policy plans (Preview)](https://entra.microsoft.com/#view/Microsoft_AAD_ConditionalAccess/ConditionalAccessBlade/~/PolicyPlans/menuId/Policies)**. +2. Review the plans listed in the result and agree with the relevant administrators or application teams who is accountable for each plan. +3. Open each plan, select **Edit plan**, add the responsible individual or group under **Owners**, and save. +4. Include the recorded owners in the organization's ownership review process. Grant administrative permissions separately only when the person's job requires them. + +The recommended fix changes accountability metadata and does not disrupt end-user sign-ins. Coordinating responsibility across the affected teams may require work beyond the portal edit itself. + +#### Related links + +- [Conditional Access policy plans](https://learn.microsoft.com/entra/identity/conditional-access/concept-conditional-access-policy-plans) +- [Create and maintain a policy plan](https://learn.microsoft.com/entra/identity/conditional-access/how-to-create-conditional-access-policy-plan) +- [Policy plan owner metadata](https://learn.microsoft.com/graph/api/conditionalaccesspolicyplan-update?view=graph-rest-beta) + +<!--- Results ---> +%TestResult% diff --git a/tests/maester/entra/Test.MT.1275.ps1 b/tests/maester/entra/Test.MT.1275.ps1 new file mode 100644 index 0000000000..7643742aff --- /dev/null +++ b/tests/maester/entra/Test.MT.1275.ps1 @@ -0,0 +1,51 @@ +function Test-MtCaPlanHasOwner { + <# + .SYNOPSIS + Checks that each Conditional Access policy plan records an accountable owner. + + .DESCRIPTION + Reports plans with an empty owners collection as a metadata hygiene finding. Owners document responsibility; + they do not grant edit rights or change enforcement. This read-only check does not resolve directory objects, + detect deleted or disabled owners, inspect group membership, or require tenants to use plans. + + .EXAMPLE + Test-MtCaPlanHasOwner + + Checks owner metadata on existing plans and skips when the tenant has no plans. + #> + [MaesterTest( + Id = 'MT.1275', + Title = 'Conditional Access policy plans have a recorded accountable owner.', + Product = 'entra', + Feature = 'conditional-access', + Area = 'identity-lifecycle', + ResourceType = 'Policy', + Severity = 'Low', + UserImpact = 'Low', + ImplementationCost = 'Medium', + Mitre = 'None', + Service = 'Graph', + Permission = 'Graph:Scope:Policy.Read.All', + License = 'AAD_PREMIUM', + Lifecycle = 'Preview', + Author = 'FiraSenax' + )] + [CmdletBinding()] + [OutputType([bool])] + param() + + $plans = @(Get-MtConditionalAccessPolicyPlan -MetadataOnly) + if ($plans.Count -eq 0) { + Add-MtTestResultDetail -SkippedBecause NotApplicable + return + } + $missing = @($plans | Where-Object { + @($_.owners | Where-Object { -not [string]::IsNullOrWhiteSpace([string]$_) }).Count -eq 0 + }) + if ($missing.Count -gt 0) { + Add-MtTestResultDetail -Result "Record an accountable owner for these Conditional Access policy plans. Owners are metadata and receive no edit permissions.`n`n%TestResult%" -GraphObjects $missing -GraphObjectType ConditionalAccessPlan + return $false + } + Add-MtTestResultDetail -Result "Well done. All $($plans.Count) discovered Conditional Access policy plans record an owner. This validates metadata presence, not owner existence, activity or group membership." + return $true +} diff --git a/website/docs/configuration/conditional-access-policy-plans.mdx b/website/docs/configuration/conditional-access-policy-plans.mdx new file mode 100644 index 0000000000..868c51cb34 --- /dev/null +++ b/website/docs/configuration/conditional-access-policy-plans.mdx @@ -0,0 +1,54 @@ +--- +title: Conditional Access policy plans +description: How Maester reads policy plans, inherits conditions, and checks owner metadata. +--- + +Conditional Access policy plans are a Microsoft Entra preview feature. A plan contains shared targeting and one or more rules. The rules retain their own enforcement state and grant/session controls. + +## Inventory used by CA checks + +`Get-MtConditionalAccessPolicy` returns standalone policies and projected plan rules. Existing checks can read a rule's effective `conditions`, `grantControls`, `sessionControls`, and `state` at the same paths as a standalone policy. Projection does not activate rules or turn report-only configuration into protection. + +A projected rule keeps its real rule ID. The following metadata distinguishes it from a standalone policy: + +| Property | Meaning | +| --- | --- | +| `sourceType` | `PolicyPlanRule` | +| `planId`, `planDisplayName` | The parent plan | +| `planOwners` | Recorded owner IDs; no permissions are granted | +| `sharedConditions` | The original plan conditions | +| `ruleConditions`, `controls` | The original rule-specific configuration | + +The readable name includes both plan and rule names. Checks pass matching rules as structured result objects so affected-object reports preserve each rule ID and its test attribution. Report links open the parent plan. What If results are associated with plans by rule ID using the cached plan inventory; their evaluation fields are preserved. A rule ID must not be looked up at the standalone `/policies/{id}` endpoint. + +`Get-MtConditionalAccessPolicyPlan` exposes the original plan/rule shape. Use `-MetadataOnly` when checking plan metadata without needing child rules. Both commands use the existing Graph session cache and automatic pagination. Checks report on the same snapshot and must not bypass that cache. + +## Conditions and errors + +The adapter preserves inherited targeting and accumulates inclusions and exclusions. Controls remain specific to each rule. Response annotations do not affect targeting. + +Some combinations cannot safely be flattened into a single condition set. Conflicting scalar/filter expressions, and guest scopes whose type/tenant unions would introduce a cross-product, terminate the inventory rather than inventing effective coverage. These errors identify the plan, rule, and condition to investigate with Entra's scenario evaluation. The adapter is configuration input for existing checks, not a replacement for Entra's sign-in engine or proof of full tenant coverage. + +No plans is a valid empty inventory: standalone policies continue to be evaluated. A permission error, unsupported preview API, throttled request, or malformed record must not be mistaken for no plans. Such failures propagate to the caller. `-StandaloneOnly` explicitly selects the original standalone inventory for diagnostic/export callers; security checks must not use it to hide unreadable plans. + +## Read permissions + +This integration reads configuration only and does not request write permissions. `Policy.Read.All` is the existing Maester permission used for the standalone inventory and the tested plans endpoints. For delegated access, [Microsoft documents](https://learn.microsoft.com/graph/api/conditionalaccessroot-list-plans?view=graph-rest-beta) **Conditional Access Administrator** as the least privileged supported built-in Entra role for listing plans; an appropriate custom role is also supported. The Graph permission alone does not grant this role. + +In a [tenant validation reported by julien-ly on 18 November 2026](https://github.com/maester365/maester/pull/2733#issuecomment-6979345045), an account assigned a single directory role, either **Global Reader** or **Security Reader**, successfully read standalone policies, listed plans, retrieved a plan with inline rules, and read the rules endpoint. The client used delegated `Policy.Read.All` only. These results describe the preview service behavior observed in that tenant; Microsoft's documented role requirements remain the support reference. Validate plan and rule access with the intended audit identity before relying on either reader role. + +This affects existing CA checks: the combined collector now requests plans as well as standalone policies. A delegated caller who previously could read standalone policies may receive a plan-read authorization error, even with `Policy.Read.All`. Such an error propagates to the check rather than silently returning standalone-only coverage. Preview availability can also prevent a plans request from succeeding. + +Microsoft currently documents `Policy.Read.ConditionalAccess` for listing plans, but that scope alone returned 403 in the isolated tenant experiment behind this change. No general scope regression or new universal permission requirement is inferred from that one-tenant result. + +## Owner metadata check + +**MT.1275** reports existing plans with no recorded owner as a low-severity hygiene finding. A tenant with no plans is **NotApplicable**, including a tenant that uses only standalone CA policies. It is a preview check; select it explicitly or include preview tests. + +Owner metadata grants no edit rights and has no enforcement effect. The check does not resolve owner IDs, detect inactive/deleted identities, or inspect owner-group membership. Those are separate lifecycle checks with separate directory-read requirements. + +## References + +- [Microsoft Entra policy plans](https://learn.microsoft.com/entra/identity/conditional-access/concept-conditional-access-policy-plans) +- [Plans API and read permissions](https://learn.microsoft.com/graph/api/conditionalaccessroot-list-plans?view=graph-rest-beta) +- [Standalone policy read permissions](https://learn.microsoft.com/graph/api/conditionalaccessroot-list-policies?view=graph-rest-1.0)