From d735905cbe27f51274ca7cfc1b4c6bd44c6e60f4 Mon Sep 17 00:00:00 2001 From: Julien Ly Date: Fri, 20 Nov 2026 17:13:51 +0100 Subject: [PATCH 1/2] feat(entra): add MT.1287 - user consent grants to third-party apps should not remain after user consent is restricted --- .../tests/fixtures/golden/selection.json | 21 ++- .../Test-MtEntraUserConsentGrant.Tests.ps1 | 155 ++++++++++++++++++ tests/maester/entra/Test.MT.1287.md | 43 +++++ tests/maester/entra/Test.MT.1287.ps1 | 151 +++++++++++++++++ 4 files changed, 363 insertions(+), 7 deletions(-) create mode 100644 powershell/tests/functions/Test-MtEntraUserConsentGrant.Tests.ps1 create mode 100644 tests/maester/entra/Test.MT.1287.md create mode 100644 tests/maester/entra/Test.MT.1287.ps1 diff --git a/powershell/tests/fixtures/golden/selection.json b/powershell/tests/fixtures/golden/selection.json index ae970e7cfd..18f28848cc 100644 --- a/powershell/tests/fixtures/golden/selection.json +++ b/powershell/tests/fixtures/golden/selection.json @@ -21,7 +21,7 @@ "AD" ] }, - "SelectedCount": 582, + "SelectedCount": 583, "SelectedFamilies": [ "MT.1024", "MT.1059", @@ -543,6 +543,7 @@ "MT.1251", "MT.1252", "MT.1265", + "MT.1287", "ORCA.100", "ORCA.101", "ORCA.102", @@ -771,7 +772,7 @@ "AD" ] }, - "SelectedCount": 538, + "SelectedCount": 539, "SelectedFamilies": [ "MT.1024", "MT.1059", @@ -1249,6 +1250,7 @@ "MT.1251", "MT.1252", "MT.1265", + "MT.1287", "ORCA.100", "ORCA.101", "ORCA.102", @@ -1330,7 +1332,7 @@ "AD" ] }, - "SelectedCount": 598, + "SelectedCount": 599, "SelectedFamilies": [ "MT.1024", "MT.1033", @@ -1870,6 +1872,7 @@ "MT.1251", "MT.1252", "MT.1265", + "MT.1287", "ORCA.100", "ORCA.101", "ORCA.102", @@ -1951,7 +1954,7 @@ "AD" ] }, - "SelectedCount": 609, + "SelectedCount": 610, "SelectedFamilies": [ "MT.1024", "MT.1059", @@ -2500,6 +2503,7 @@ "MT.1259", "MT.1260", "MT.1265", + "MT.1287", "ORCA.100", "ORCA.101", "ORCA.102", @@ -2581,7 +2585,7 @@ "AD" ] }, - "SelectedCount": 639, + "SelectedCount": 640, "SelectedFamilies": [ "MT.1024", "MT.1033", @@ -3162,6 +3166,7 @@ "MT.1259", "MT.1260", "MT.1265", + "MT.1287", "ORCA.100", "ORCA.101", "ORCA.102", @@ -3441,7 +3446,7 @@ "AD" ] }, - "SelectedCount": 538, + "SelectedCount": 539, "SelectedFamilies": [ "MT.1024", "MT.1059", @@ -3919,6 +3924,7 @@ "MT.1251", "MT.1252", "MT.1265", + "MT.1287", "ORCA.100", "ORCA.101", "ORCA.102", @@ -4006,7 +4012,7 @@ "AD" ] }, - "SelectedCount": 595, + "SelectedCount": 596, "SelectedFamilies": [ "MT.1024", "MT.1033", @@ -4543,6 +4549,7 @@ "MT.1259", "MT.1260", "MT.1265", + "MT.1287", "ORCA.100", "ORCA.101", "ORCA.102", diff --git a/powershell/tests/functions/Test-MtEntraUserConsentGrant.Tests.ps1 b/powershell/tests/functions/Test-MtEntraUserConsentGrant.Tests.ps1 new file mode 100644 index 0000000000..d45c4711c4 --- /dev/null +++ b/powershell/tests/functions/Test-MtEntraUserConsentGrant.Tests.ps1 @@ -0,0 +1,155 @@ +BeforeAll { + Import-Module $PSScriptRoot/../../Maester.psd1 -Force + . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" + # Check functions that became native tests are not exported. + Use-MtModuleFunction -Name Test-MtEntraUserConsentGrant +} + +Describe 'MT.1287: Test-MtEntraUserConsentGrant' -Tag 'Unit' { + BeforeAll { + # Graph errors name the status, not its number: "Response status code does not indicate success: Forbidden (Forbidden)." + function Get-HttpError ([int]$StatusCode) { + $response = [System.Net.Http.HttpResponseMessage]::new([System.Net.HttpStatusCode]$StatusCode) + [Microsoft.PowerShell.Commands.HttpResponseException]::new("Response status code does not indicate success: $([System.Net.HttpStatusCode]$StatusCode) ($($response.ReasonPhrase)).", $response) + } + + function Get-TestServicePrincipal { + param( + [string] $Id, + [string] $DisplayName, + [string] $OwnerTenantId = 'third-party-tenant', + [string] $Publisher, + [bool] $AccountEnabled = $true + ) + [pscustomobject]@{ + id = $Id + appId = "app-$Id" + displayName = $DisplayName + appOwnerOrganizationId = $OwnerTenantId + verifiedPublisher = [pscustomobject]@{ displayName = $Publisher } + accountEnabled = $AccountEnabled + } + } + + function Get-TestGrant { + param( + [string] $ClientId, + [string] $PrincipalId, + [string] $ResourceId = 'graph', + [string] $Scope = 'User.Read' + ) + [pscustomobject]@{ + id = "$ClientId-$PrincipalId-$ResourceId" + clientId = $ClientId + principalId = $PrincipalId + resourceId = $ResourceId + scope = $Scope + } + } + } + + BeforeEach { + $script:TestResult = $null + $script:SkippedBecause = $null + $script:Investigate = $false + # Policy IDs without the ManagePermissionGrantsForSelf prefix. None means user consent is turned off. + $script:ConsentPolicies = @() + $script:Grants = @() + $script:ServicePrincipals = @( + Get-TestServicePrincipal -Id 'graph' -DisplayName 'Microsoft Graph' -OwnerTenantId 'f8cdef31-a31e-4b4a-93e4-5f571e91255a' + Get-TestServicePrincipal -Id 'exo' -DisplayName 'Office 365 Exchange Online' -OwnerTenantId 'f8cdef31-a31e-4b4a-93e4-5f571e91255a' + ) + + Mock -ModuleName Maester Add-MtTestResultDetail { + param($Result, $SkippedBecause, [switch]$Investigate) + + $script:TestResult = $Result + $script:SkippedBecause = $SkippedBecause + $script:Investigate = $Investigate.IsPresent + } + + Mock -ModuleName Maester Get-MgContext { [pscustomobject]@{ TenantId = 'own-tenant' } } + + # A group owner consent policy is always there: it must not count as user consent. + Mock -ModuleName Maester Invoke-MtGraphRequest -ParameterFilter { $RelativeUri -eq 'policies/authorizationPolicy' } { + $Assigned = @($script:ConsentPolicies | ForEach-Object { "ManagePermissionGrantsForSelf.$_" }) + $Assigned += 'ManagePermissionGrantsForOwnedResource.microsoft-dynamically-managed-permissions-for-team' + [pscustomobject]@{ defaultUserRolePermissions = [pscustomobject]@{ permissionGrantPoliciesAssigned = $Assigned } } + } + Mock -ModuleName Maester Invoke-MtGraphRequest -ParameterFilter { $RelativeUri -eq 'oauth2PermissionGrants' } { $script:Grants } + Mock -ModuleName Maester Invoke-MtGraphRequest -ParameterFilter { $RelativeUri -eq 'servicePrincipals' } { + $script:ServicePrincipals | Where-Object { $_.id -in $UniqueId } + } + } + + It 'is skipped as not applicable when users can consent to any app' { + $script:ConsentPolicies = @('microsoft-user-default-legacy') + + Test-MtEntraUserConsentGrant | Should -BeNullOrEmpty + $script:SkippedBecause | Should -Be 'NotApplicable' + Should -Invoke Invoke-MtGraphRequest -ModuleName Maester -Times 0 -Exactly -ParameterFilter { $RelativeUri -eq 'oauth2PermissionGrants' } + } + + It 'passes when user consent is turned off and no user grant remains' { + Test-MtEntraUserConsentGrant | Should -BeTrue + $script:TestResult | Should -BeLike 'Well done.*' + Should -Invoke Invoke-MtGraphRequest -ModuleName Maester -Times 0 -Exactly -ParameterFilter { $RelativeUri -eq 'servicePrincipals' } + } + + It 'fails when user consent is turned off and a third-party app keeps user grants' { + $script:ServicePrincipals += Get-TestServicePrincipal -Id 'crm' -DisplayName 'Contoso CRM' -Publisher 'Contoso Ltd' + $script:Grants = @( + Get-TestGrant -ClientId 'crm' -PrincipalId 'user-1' -Scope 'User.Read Mail.Read' + Get-TestGrant -ClientId 'crm' -PrincipalId 'user-2' -Scope ' offline_access User.Read ' + Get-TestGrant -ClientId 'crm' -PrincipalId 'user-2' -ResourceId 'exo' -Scope 'EWS.AccessAsUser.All' + ) + + Test-MtEntraUserConsentGrant | Should -BeFalse + $script:Investigate | Should -BeFalse + $script:TestResult | Should -BeLike 'User consent is turned off, but 1 third-party app(s) still hold delegated permissions that 2 user(s)*' + $script:TestResult | Should -Match ([regex]::Escape('[Contoso CRM](') + '[^)]*/Permissions/objectId/crm/appId/app-crm\)') + $script:TestResult | Should -Match ([regex]::Escape( + '| Contoso Ltd | 2 | Microsoft Graph\: Mail.Read, offline\_access, User.Read; Office 365 Exchange Online\: EWS.AccessAsUser.All |' + )) + } + + It 'passes when only Microsoft apps, apps of this tenant and disabled apps keep user grants' { + $script:ServicePrincipals += @( + Get-TestServicePrincipal -Id 'msapp' -DisplayName 'Microsoft app' -OwnerTenantId '72f988bf-86f1-41af-91ab-2d7cd011db47' + Get-TestServicePrincipal -Id 'inhouse' -DisplayName 'In-house app' -OwnerTenantId 'own-tenant' + Get-TestServicePrincipal -Id 'retired' -DisplayName 'Retired app' -AccountEnabled $false + ) + $script:Grants = @( + Get-TestGrant -ClientId 'msapp' -PrincipalId 'user-1' + Get-TestGrant -ClientId 'inhouse' -PrincipalId 'user-1' + Get-TestGrant -ClientId 'retired' -PrincipalId 'user-2' + ) + + Test-MtEntraUserConsentGrant | Should -BeTrue + $script:TestResult | Should -BeLike 'Well done.*' + } + + It 'asks for a review when user consent is limited and a third-party app keeps user grants' { + $script:ConsentPolicies = @('microsoft-user-default-low') + $script:ServicePrincipals += Get-TestServicePrincipal -Id 'notes' -DisplayName 'Notes app' + $script:Grants = @(Get-TestGrant -ClientId 'notes' -PrincipalId 'user-1' -Scope 'Files.Read') + + Test-MtEntraUserConsentGrant | Should -BeTrue + $script:Investigate | Should -BeTrue + $script:TestResult | Should -BeLike 'User consent is limited by*microsoft-user-default-low*1 third-party app(s)*' + $script:TestResult | Should -Match ([regex]::Escape('| None | 1 | Microsoft Graph\: Files.Read |')) + } + + It 'is skipped as not authorized when Graph answers 403' { + Mock -ModuleName Maester Invoke-MtGraphRequest -ParameterFilter { $RelativeUri -eq 'oauth2PermissionGrants' } { throw (Get-HttpError 403) } + + Test-MtEntraUserConsentGrant | Should -BeNullOrEmpty + $script:SkippedBecause | Should -Be 'NotAuthorized' + } + + It 'lets other Graph errors reach the engine' { + Mock -ModuleName Maester Invoke-MtGraphRequest -ParameterFilter { $RelativeUri -eq 'policies/authorizationPolicy' } { throw (Get-HttpError 500) } + + { Test-MtEntraUserConsentGrant } | Should -Throw -ExpectedMessage '*InternalServerError*' + } +} diff --git a/tests/maester/entra/Test.MT.1287.md b/tests/maester/entra/Test.MT.1287.md new file mode 100644 index 0000000000..90ffc88c7e --- /dev/null +++ b/tests/maester/entra/Test.MT.1287.md @@ -0,0 +1,43 @@ +User consent grants to third-party apps should not remain after user consent is restricted. + +When users consent to an app for themselves, Microsoft Entra ID records a delegated permission grant, and the app can access data on their behalf. Restricting user consent only affects future consents: the grants given before the change remain, and the apps keep their access until an administrator revokes the grants. This includes an app that users consented to through a consent phishing campaign. + +This check reads the consent policies assigned to the default user role, then the delegated permission grants that users gave for themselves. It lists the third-party apps that hold such grants, with their verified publisher, the number of users and the permissions granted. Microsoft first-party apps and apps registered in your tenant are not listed. Neither are apps whose sign-in is disabled: tokens aren't issued for them. + +- **User consent is turned off**: every remaining grant predates the change, and the test fails. +- **User consent is limited**, for example to apps from verified publishers for selected permissions: the current policy may allow some of the grants, so the result asks for a review. +- **Users can consent to any app**: the grants are expected, and the test is skipped. Restrict user consent first: EIDSCA.AP08 checks this setting. + +An administrator can also grant consent on behalf of a single user through Microsoft Graph. Such a grant looks the same as user consent: check with the app owner before you revoke it. + +### Remediation action: + +1. Sign in to the [Microsoft Entra admin center][entra-admin-center] as at least a Cloud Application Administrator. +2. Open each reported app from the result table. The **User consent** tab of its **Permissions** page lists the permissions that users granted. +3. Decide with the app owner or the users whether the app is still needed. To let users request an app they need, [enable the admin consent workflow][admin-consent-workflow]. +4. The admin center can't revoke the permissions on the **User consent** tab. Revoke them with Microsoft Graph PowerShell, using the **Object ID** shown on the app's **Overview** page: + + ```powershell + Connect-MgGraph -Scopes 'DelegatedPermissionGrant.ReadWrite.All' + Get-MgOauth2PermissionGrant -All -Filter "clientId eq ''" | + Where-Object ConsentType -eq 'Principal' | + ForEach-Object { Remove-MgOauth2PermissionGrant -OAuth2PermissionGrantId $_.Id } + ``` + +5. To block an app at once while you review it, set **Enabled for users to sign in?** to **No** on its **Properties** page: tokens are no longer issued for it. + +### Related links + +* [Configure how users consent to applications][user-consent] +* [Review permissions granted to enterprise applications][review-permissions] +* [Configure the admin consent workflow][admin-consent-workflow] +* [Properties of an enterprise application: Enabled for users to sign in?][app-properties] + +[entra-admin-center]: https://entra.microsoft.com +[user-consent]: https://learn.microsoft.com/entra/identity/enterprise-apps/configure-user-consent +[review-permissions]: https://learn.microsoft.com/entra/identity/enterprise-apps/manage-application-permissions +[admin-consent-workflow]: https://learn.microsoft.com/entra/identity/enterprise-apps/configure-admin-consent-workflow +[app-properties]: https://learn.microsoft.com/entra/identity/enterprise-apps/application-properties#enabled-for-users-to-sign-in + + +%TestResult% diff --git a/tests/maester/entra/Test.MT.1287.ps1 b/tests/maester/entra/Test.MT.1287.ps1 new file mode 100644 index 0000000000..7efb423a99 --- /dev/null +++ b/tests/maester/entra/Test.MT.1287.ps1 @@ -0,0 +1,151 @@ +function Test-MtEntraUserConsentGrant { + <# + .SYNOPSIS + Finds third-party apps that keep the delegated permissions users granted, after user consent is restricted. + + .DESCRIPTION + Restricting user consent only affects future consents. The delegated permissions that users granted + before the change remain, and the apps keep accessing data on the users' behalf until an administrator + revokes the grants. + + This check reads the consent policies assigned to the default user role, then the delegated permission + grants that users gave for themselves (consent type Principal). It lists the apps that hold such grants, + except Microsoft first-party apps, apps registered in this tenant, and apps whose sign-in is disabled, + since tokens aren't issued for them. + + When user consent is turned off, every grant left predates the change, and the test fails. When user + consent is limited, for example to apps from verified publishers, the current policy may allow some of + the grants, so the result asks for a review. When users can consent to any app, the grants are expected + and the test is skipped: EIDSCA.AP08 checks that setting. + + An administrator can also grant consent on behalf of a single user through Microsoft Graph. Such a grant + looks the same as user consent. + + .EXAMPLE + Test-MtEntraUserConsentGrant + + .LINK + https://maester.dev/docs/commands/Test-MtEntraUserConsentGrant + + .LINK + https://learn.microsoft.com/entra/identity/enterprise-apps/configure-user-consent + #> + [MaesterTest( + Id = 'MT.1287', + Title = 'User consent grants to third-party apps should not remain after user consent is restricted.', + Product = 'entra', + Feature = 'app-consent', + Area = 'applications', + ResourceType = 'ServicePrincipal', + Severity = 'Medium', + UserImpact = 'Medium', + ImplementationCost = 'Medium', + Mitre = 'T1528', + Control = 'nist-800-53-r5:AC-6', + Service = 'Graph', + Author = 'julien-ly' + )] + [CmdletBinding()] + [OutputType([bool])] + param() + + # Tenants where Microsoft registers its first-party apps. + $MicrosoftTenantIds = @('f8cdef31-a31e-4b4a-93e4-5f571e91255a', '72f988bf-86f1-41af-91ab-2d7cd011db47') + $TenantId = [string](Get-MgContext).TenantId + + try { + $UserRolePermissions = (Invoke-MtGraphRequest -ApiVersion 'v1.0' -RelativeUri 'policies/authorizationPolicy').defaultUserRolePermissions + if ($null -eq $UserRolePermissions) { + throw 'Could not read the permissions of the default user role from the authorization policy.' + } + # Only the ManagePermissionGrantsForSelf policies set what users can consent to for themselves. + $ConsentPolicies = @( + $UserRolePermissions.permissionGrantPoliciesAssigned | + Where-Object { "$_" -like 'ManagePermissionGrantsForSelf.*' } | + ForEach-Object { "$_".Substring('ManagePermissionGrantsForSelf.'.Length) } + ) + if ($ConsentPolicies -contains 'microsoft-user-default-legacy') { + Add-MtTestResultDetail -SkippedBecause NotApplicable -Result ( + 'Users can consent to any app, so the grants they gave are expected. Restrict user consent first: EIDSCA.AP08 checks this setting.' + ) + return $null + } + + $Grants = @( + Invoke-MtGraphRequest -ApiVersion 'v1.0' -RelativeUri 'oauth2PermissionGrants' -Filter "consentType eq 'Principal'" ` + -Select @('id', 'clientId', 'principalId', 'resourceId', 'scope') + ) + # Read each client app and each resource API once. + $ServicePrincipalById = @{} + $ServicePrincipalIds = @($Grants | ForEach-Object { [string]$_.clientId; [string]$_.resourceId } | Where-Object { $_ } | Sort-Object -Unique) + if ($ServicePrincipalIds.Count -gt 0) { + Invoke-MtGraphRequest -ApiVersion 'v1.0' -RelativeUri 'servicePrincipals' -UniqueId $ServicePrincipalIds ` + -Select @('id', 'appId', 'displayName', 'appOwnerOrganizationId', 'verifiedPublisher', 'accountEnabled') | + ForEach-Object { $ServicePrincipalById[[string]$_.id] = $_ } + } + } catch { + # Graph answers 403 when the signed-in account cannot read the authorization policy, the grants or the apps. + # Any other error goes to the engine, which reports it. + if ($_.Exception.Response -and [int]$_.Exception.Response.StatusCode -eq 403) { + Add-MtTestResultDetail -SkippedBecause NotAuthorized + return $null + } + throw + } + + $UserIds = [System.Collections.Generic.HashSet[string]]::new() + $Findings = @( + foreach ($ClientGrants in ($Grants | Group-Object -Property { [string]$_.clientId })) { + $Client = $ServicePrincipalById[[string]$ClientGrants.Name] + if ($null -eq $Client) { continue } + # Microsoft first-party apps and apps registered in this tenant are not third-party apps. + # Tokens aren't issued for an app whose sign-in is disabled, so its grants are not used. + $OwnerTenantId = [string]$Client.appOwnerOrganizationId + if ($OwnerTenantId -in $MicrosoftTenantIds -or ($TenantId -and $OwnerTenantId -eq $TenantId) -or $Client.accountEnabled -eq $false) { + continue + } + + $Permissions = foreach ($ResourceGrants in ($ClientGrants.Group | Group-Object -Property { [string]$_.resourceId })) { + $Resource = $ServicePrincipalById[[string]$ResourceGrants.Name] + $ResourceName = if ($Resource -and $Resource.displayName) { [string]$Resource.displayName } else { [string]$ResourceGrants.Name } + $Scopes = @($ResourceGrants.Group | ForEach-Object { "$($_.scope)" -split '\s+' } | Where-Object { $_ } | Sort-Object -Unique) + if ($Scopes.Count -gt 0) { "$($ResourceName): $($Scopes -join ', ')" } + } + $AppUserIds = @($ClientGrants.Group | ForEach-Object { [string]$_.principalId } | Where-Object { $_ } | Sort-Object -Unique) + foreach ($UserId in $AppUserIds) { [void]$UserIds.Add($UserId) } + + [pscustomobject]@{ + ServicePrincipal = $Client + Publisher = if ($Client.verifiedPublisher) { [string]$Client.verifiedPublisher.displayName } else { '' } + Users = $AppUserIds.Count + Permissions = @($Permissions | Sort-Object) -join '; ' + } + } + ) + + if ($Findings.Count -eq 0) { + Add-MtTestResultDetail -Result 'Well done. No third-party app holds delegated permissions that users granted for themselves.' + return $true + } + + $Findings = @($Findings | Sort-Object -Property @{ Expression = { $_.Users }; Descending = $true }, @{ Expression = { [string]$_.ServicePrincipal.displayName } }) + $Table = "| App | Verified publisher | Users | Delegated permissions |`n| --- | --- | --- | --- |" + foreach ($Item in $Findings) { + $App = Get-MtLinkServicePrincipal -ServicePrincipal $Item.ServicePrincipal -Blade Permissions + $Publisher = if ($Item.Publisher) { Get-MtSafeMarkdown -Text $Item.Publisher } else { 'None' } + $Table += "`n| $App | $Publisher | $($Item.Users) | $(Get-MtSafeMarkdown -Text $Item.Permissions) |" + } + + if ($ConsentPolicies.Count -eq 0) { + $Result = "User consent is turned off, but $($Findings.Count) third-party app(s) still hold delegated permissions that $($UserIds.Count) user(s) granted for themselves. " + $Result += 'Turning off user consent only blocks new consents: these grants keep working until you revoke them.' + Add-MtTestResultDetail -Result "$Result`n`n$Table" + return $false + } + + $PolicyList = ($ConsentPolicies | ForEach-Object { "``$_``" }) -join ', ' + $Result = "User consent is limited by $PolicyList. $($Findings.Count) third-party app(s) hold delegated permissions that $($UserIds.Count) user(s) granted for themselves. " + $Result += 'Grants given before the restriction keep working: check that the current policy allows them, and revoke the others.' + Add-MtTestResultDetail -Result "$Result`n`n$Table" -Investigate + return $true +} From 0c15ea7476ab3a3ce66e7f0fea206be5d19daac3 Mon Sep 17 00:00:00 2001 From: Julien Ly Date: Fri, 20 Nov 2026 17:26:19 +0100 Subject: [PATCH 2/2] MT.1287: report a 403 from the batched service principal lookup as NotAuthorized --- .../Test-MtEntraUserConsentGrant.Tests.ps1 | 26 +++++++++++++++++++ tests/maester/entra/Test.MT.1287.ps1 | 5 +++- 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/powershell/tests/functions/Test-MtEntraUserConsentGrant.Tests.ps1 b/powershell/tests/functions/Test-MtEntraUserConsentGrant.Tests.ps1 index d45c4711c4..3aa1e858b5 100644 --- a/powershell/tests/functions/Test-MtEntraUserConsentGrant.Tests.ps1 +++ b/powershell/tests/functions/Test-MtEntraUserConsentGrant.Tests.ps1 @@ -147,6 +147,32 @@ Describe 'MT.1287: Test-MtEntraUserConsentGrant' -Tag 'Unit' { $script:SkippedBecause | Should -Be 'NotAuthorized' } + It 'is skipped as not authorized when a batched lookup answers 403' { + $script:ServicePrincipals += Get-TestServicePrincipal -Id 'crm' -DisplayName 'Contoso CRM' + $script:Grants = @(Get-TestGrant -ClientId 'crm' -PrincipalId 'user-1') + # The shape Invoke-MtGraphRequest throws for a failed request inside a batch. + Mock -ModuleName Maester Invoke-MtGraphRequest -ParameterFilter { $RelativeUri -eq 'servicePrincipals' } { + throw [System.Management.Automation.ErrorRecord]::new( + [System.InvalidOperationException]::new("Graph batch request for 'servicePrincipals/crm' failed with status 403"), + 'MtGraphBatchRequestFailed', [System.Management.Automation.ErrorCategory]::PermissionDenied, 'servicePrincipals/crm') + } + + Test-MtEntraUserConsentGrant | Should -BeNullOrEmpty + $script:SkippedBecause | Should -Be 'NotAuthorized' + } + + It 'lets other batch errors reach the engine' { + $script:ServicePrincipals += Get-TestServicePrincipal -Id 'crm' -DisplayName 'Contoso CRM' + $script:Grants = @(Get-TestGrant -ClientId 'crm' -PrincipalId 'user-1') + Mock -ModuleName Maester Invoke-MtGraphRequest -ParameterFilter { $RelativeUri -eq 'servicePrincipals' } { + throw [System.Management.Automation.ErrorRecord]::new( + [System.InvalidOperationException]::new("Graph batch request for 'servicePrincipals/crm' failed with status 500"), + 'MtGraphBatchRequestFailed', [System.Management.Automation.ErrorCategory]::InvalidResult, 'servicePrincipals/crm') + } + + { Test-MtEntraUserConsentGrant } | Should -Throw -ExpectedMessage '*status 500*' + } + It 'lets other Graph errors reach the engine' { Mock -ModuleName Maester Invoke-MtGraphRequest -ParameterFilter { $RelativeUri -eq 'policies/authorizationPolicy' } { throw (Get-HttpError 500) } diff --git a/tests/maester/entra/Test.MT.1287.ps1 b/tests/maester/entra/Test.MT.1287.ps1 index 7efb423a99..8b3e505b1c 100644 --- a/tests/maester/entra/Test.MT.1287.ps1 +++ b/tests/maester/entra/Test.MT.1287.ps1 @@ -85,8 +85,11 @@ } } catch { # Graph answers 403 when the signed-in account cannot read the authorization policy, the grants or the apps. + # In a batched lookup, Invoke-MtGraphRequest reports that 403 as a PermissionDenied error, with no response. # Any other error goes to the engine, which reports it. - if ($_.Exception.Response -and [int]$_.Exception.Response.StatusCode -eq 403) { + $Forbidden = ($_.Exception.Response -and [int]$_.Exception.Response.StatusCode -eq 403) -or + ($_.FullyQualifiedErrorId -like 'MtGraphBatchRequestFailed*' -and $_.CategoryInfo.Category -eq 'PermissionDenied') + if ($Forbidden) { Add-MtTestResultDetail -SkippedBecause NotAuthorized return $null }