From 988062a68115377968afd408ecde6f3e04ee857e Mon Sep 17 00:00:00 2001 From: agnivesh <320655+agnivesh@users.noreply.github.com> Date: Tue, 10 Nov 2026 13:50:29 +0000 Subject: [PATCH 01/11] feat(entra): add MT.1276 hard deletion protection check Add a preview test that compares the users, groups, applications and service principals listed in the HardDeletionProtectedObjects setting with their isHardDeleteProtectionEnabled value in Microsoft Graph beta. An unprotected, soft-deleted or missing listed object fails the test. The test also queries the objects that have protection, active and soft deleted. When every listed object is protected but others are not listed, or when nothing is listed, the result is Investigate and a table shows the other protected objects (first 25, with the total). Register the setting, add the backup-and-recovery Entra feature, add the test to the golden selection fixture, move the lookups into internal helpers with unit tests, and document the setting on a new Hard Deletion Protection page. --- powershell/assets/MaesterSettings.psd1 | 1 + powershell/assets/MaesterTaxonomy.psd1 | 1 + .../entra/Format-MtEntraHardDeletionTable.ps1 | 52 +++++ .../Get-MtEntraHardDeletionObjectStatus.ps1 | 81 ++++++++ ...Get-MtEntraHardDeletionProtectedObject.ps1 | 46 +++++ .../tests/fixtures/golden/selection.json | 9 +- ...st-MtEntraHardDeletionProtection.Tests.ps1 | 174 ++++++++++++++++ tests/maester/entra/Test.MT.1276.md | 27 +++ tests/maester/entra/Test.MT.1276.ps1 | 94 +++++++++ .../configuration/hard-deletion-protection.md | 192 ++++++++++++++++++ website/docs/configuration/overview.md | 1 + .../docs/configuration/run-configuration.md | 5 + website/src/data/test-builder.json | 4 + 13 files changed, 684 insertions(+), 3 deletions(-) create mode 100644 powershell/internal/checks/maester/entra/Format-MtEntraHardDeletionTable.ps1 create mode 100644 powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionObjectStatus.ps1 create mode 100644 powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionProtectedObject.ps1 create mode 100644 powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 create mode 100644 tests/maester/entra/Test.MT.1276.md create mode 100644 tests/maester/entra/Test.MT.1276.ps1 create mode 100644 website/docs/configuration/hard-deletion-protection.md diff --git a/powershell/assets/MaesterSettings.psd1 b/powershell/assets/MaesterSettings.psd1 index c5aecd9439..21edb4c77e 100644 --- a/powershell/assets/MaesterSettings.psd1 +++ b/powershell/assets/MaesterSettings.psd1 @@ -29,6 +29,7 @@ SchemaVersion = '1.0' Settings = @{ EmergencyAccessAccounts = @{ Type = 'object[]'; Items = @{ Properties = @{ Id = $null; UserPrincipalName = $null; Type = @('User', 'Group') }; RequireAny = @('Id', 'UserPrincipalName') }; Default = @(); Sensitive = $false; Description = 'Emergency access (break glass) accounts and groups. Checks of Conditional Access, privileged roles and sign-in activity treat them as the exception they are.' } + HardDeletionProtectedObjects = @{ Type = 'object[]'; Items = @{ Properties = @{ Id = $null; Type = @('User', 'Group', 'Application', 'ServicePrincipal') }; RequireAny = @('Id') }; Default = @(); Sensitive = $false; Description = 'Critical users, groups, applications and service principals (Type and Id) that must have Hard Deletion Protection enabled.' } ParkedDomains = @{ Type = 'string[]'; Kind = 'Entra.Domain'; Default = @(); Sensitive = $false; Description = 'Accepted domains that never send email. The email authentication checks expect them to deny all mail.' } DefenderEndpointPolicyFiltering = @{ Type = 'string'; AllowedValues = @('All', 'IncludeUnassigned', 'OnlyAssigned'); Default = 'OnlyAssigned'; Sensitive = $false; Description = 'Which Defender for Endpoint policies the Defender checks read: All, IncludeUnassigned or OnlyAssigned.' } DefenderEndpointComplianceLogic = @{ Type = 'string'; AllowedValues = @('EffectivePolicy', 'AllPolicies', 'AnyPolicy'); Default = 'EffectivePolicy'; Sensitive = $false; Description = 'How the Defender for Endpoint checks combine policies: EffectivePolicy, AllPolicies or AnyPolicy.' } diff --git a/powershell/assets/MaesterTaxonomy.psd1 b/powershell/assets/MaesterTaxonomy.psd1 index 1c0373c93f..3e7cdcf392 100644 --- a/powershell/assets/MaesterTaxonomy.psd1 +++ b/powershell/assets/MaesterTaxonomy.psd1 @@ -42,6 +42,7 @@ @{ Key = 'agent-identities'; Name = 'Agent identities' } @{ Key = 'monitoring'; Name = 'Logs and monitoring' } @{ Key = 'recommendations'; Name = 'Entra recommendations' } + @{ Key = 'backup-and-recovery'; Name = 'Backup and recovery' } ) } @{ diff --git a/powershell/internal/checks/maester/entra/Format-MtEntraHardDeletionTable.ps1 b/powershell/internal/checks/maester/entra/Format-MtEntraHardDeletionTable.ps1 new file mode 100644 index 0000000000..9b874eea10 --- /dev/null +++ b/powershell/internal/checks/maester/entra/Format-MtEntraHardDeletionTable.ps1 @@ -0,0 +1,52 @@ +function Format-MtEntraHardDeletionTable { + <# + .SYNOPSIS + Formats Hard Deletion Protection objects as a Markdown table, capped at a number of rows. + + .DESCRIPTION + Builds a table with the columns Type, Object ID, Display name and one more column taken from the + StateProperty. When there are more rows than Limit, the table shows the first Limit rows and a line + gives the total. + + .PARAMETER InputObject + The objects to list. Each has Type, Id and DisplayName. + + .PARAMETER StateProperty + The property shown in the last column, for example Status or State. + + .PARAMETER StateHeading + The heading of the last column. + + .PARAMETER Limit + The most rows to show. The default is 25. + + .EXAMPLE + Format-MtEntraHardDeletionTable -InputObject $Rows -StateProperty Status -StateHeading Status + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory)] + [object[]] $InputObject, + + [Parameter(Mandatory)] + [string] $StateProperty, + + [Parameter(Mandatory)] + [string] $StateHeading, + + [Parameter()] + [ValidateRange(1, 1000)] + [int] $Limit = 25 + ) + + $Table = "| Type | Object ID | Display name | $StateHeading |`n| --- | --- | --- | --- |" + foreach ($Row in @($InputObject | Select-Object -First $Limit)) { + $DisplayName = [System.Net.WebUtility]::HtmlEncode([string]$Row.DisplayName) -replace '\|', '|' + $Table += "`n| $($Row.Type) | $($Row.Id) | $DisplayName | $($Row.$StateProperty) |" + } + if (@($InputObject).Count -gt $Limit) { + $Table += "`n`nShowing the first $Limit of $(@($InputObject).Count) objects." + } + $Table +} diff --git a/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionObjectStatus.ps1 b/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionObjectStatus.ps1 new file mode 100644 index 0000000000..a59db78330 --- /dev/null +++ b/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionObjectStatus.ps1 @@ -0,0 +1,81 @@ +function Get-MtEntraHardDeletionObjectStatus { + <# + .SYNOPSIS + Returns the Hard Deletion Protection status of one object listed in the Maester config. + + .DESCRIPTION + Reads the object from Microsoft Graph beta. Status is 'Protected', 'Not protected', 'Soft deleted' or + 'Not found'. An object that cannot be read as an active object is 'Soft deleted' when it appears in the + supplied protected objects as soft deleted, and 'Not found' otherwise. Any Graph error other than + HTTP 404 is thrown. + + .PARAMETER Configured + A HardDeletionProtectedObjects entry with Type and Id. + + .PARAMETER ProtectedObject + The output of Get-MtEntraHardDeletionProtectedObject. + + .EXAMPLE + Get-MtEntraHardDeletionObjectStatus -Configured $Entry -ProtectedObject $Protected + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param( + [Parameter(Mandatory)] + [object] $Configured, + + [Parameter()] + [AllowEmptyCollection()] + [object[]] $ProtectedObject = @() + ) + + $EndpointByType = @{ + user = 'users' + group = 'groups' + application = 'applications' + serviceprincipal = 'servicePrincipals' + } + $TypeNames = @{ + user = 'User' + group = 'Group' + application = 'Application' + serviceprincipal = 'ServicePrincipal' + } + + $Type = ([string]$Configured.Type).ToLowerInvariant() + if (!$EndpointByType.ContainsKey($Type) -or [string]::IsNullOrWhiteSpace($Configured.Id)) { + throw ( + "Invalid HardDeletionProtectedObjects entry (Type '$($Configured.Type)', Id '$($Configured.Id)'). " + + 'Type must be User, Group, Application or ServicePrincipal and Id must be an object ID.' + ) + } + + $Object = $null + try { + $Object = Invoke-MtGraphRequest -ApiVersion 'beta' ` + -RelativeUri "$($EndpointByType[$Type])/$($Configured.Id)" ` + -Select @('id', 'displayName', 'isHardDeleteProtectionEnabled') -ErrorAction Stop + } catch { + if ($_.Exception.Response.StatusCode -ne [System.Net.HttpStatusCode]::NotFound) { throw } + } + + $DisplayName = '' + $Status = 'Not found' + if ($Object) { + $DisplayName = [string]$Object.displayName + $Status = if ($Object.isHardDeleteProtectionEnabled -eq $true) { 'Protected' } else { 'Not protected' } + } else { + $Deleted = @($ProtectedObject | Where-Object { $_.Id -eq [string]$Configured.Id -and $_.State -eq 'Soft deleted' }) + if ($Deleted.Count -gt 0) { + $DisplayName = $Deleted[0].DisplayName + $Status = 'Soft deleted' + } + } + + [pscustomobject]@{ + Type = $TypeNames[$Type] + Id = [string]$Configured.Id + DisplayName = $DisplayName + Status = $Status + } +} diff --git a/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionProtectedObject.ps1 b/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionProtectedObject.ps1 new file mode 100644 index 0000000000..37db0e61b5 --- /dev/null +++ b/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionProtectedObject.ps1 @@ -0,0 +1,46 @@ +function Get-MtEntraHardDeletionProtectedObject { + <# + .SYNOPSIS + Returns the users, groups, applications and service principals that have Hard Deletion Protection. + + .DESCRIPTION + Queries Microsoft Graph beta for objects whose isHardDeleteProtectionEnabled property is true, both + among active objects and among soft-deleted ones. Each result has Type, Id, DisplayName and State + ('Active' or 'Soft deleted'). + + .EXAMPLE + Get-MtEntraHardDeletionProtectedObject + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param() + + $Sources = @( + @{ Type = 'User'; Path = 'users'; Deleted = 'directory/deletedItems/microsoft.graph.user' } + @{ Type = 'Group'; Path = 'groups'; Deleted = 'directory/deletedItems/microsoft.graph.group' } + @{ Type = 'Application'; Path = 'applications'; Deleted = 'directory/deletedItems/microsoft.graph.application' } + @{ + Type = 'ServicePrincipal' + Path = 'servicePrincipals' + Deleted = 'directory/deletedItems/microsoft.graph.servicePrincipal' + } + ) + + foreach ($Source in $Sources) { + foreach ($State in 'Active', 'Soft deleted') { + $Path = if ($State -eq 'Active') { $Source.Path } else { $Source.Deleted } + $Objects = @( + Invoke-MtGraphRequest -ApiVersion 'beta' -RelativeUri $Path ` + -Filter 'isHardDeleteProtectionEnabled eq true' -Select @('id', 'displayName') + ) + foreach ($Object in $Objects) { + [pscustomobject]@{ + Type = $Source.Type + Id = [string]$Object.id + DisplayName = [string]$Object.displayName + State = $State + } + } + } + } +} diff --git a/powershell/tests/fixtures/golden/selection.json b/powershell/tests/fixtures/golden/selection.json index ae970e7cfd..51a6f7e37a 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.1276", "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.1276", "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.1276", "ORCA.100", "ORCA.101", "ORCA.102", diff --git a/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 b/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 new file mode 100644 index 0000000000..899447639a --- /dev/null +++ b/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 @@ -0,0 +1,174 @@ +Describe 'Test-MtEntraHardDeletionProtection' { + 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-MtEntraHardDeletionProtection + + $script:UserId = '11111111-1111-1111-1111-111111111111' + $script:GroupId = '22222222-2222-2222-2222-222222222222' + } + + BeforeEach { + $State = @{ Detail = $null; Investigate = $false; Listed = @(); Protected = @{}; ObjectById = @{} } + + Mock -ModuleName Maester Get-MtSetting -MockWith { return $State.Listed }.GetNewClosure() + Mock -ModuleName Maester Add-MtTestResultDetail -MockWith { + param($Result, [switch] $Investigate) + $State.Detail = $Result + $State.Investigate = [bool]$Investigate + }.GetNewClosure() + Mock -ModuleName Maester Invoke-MtGraphRequest -MockWith { + [CmdletBinding()] + param($RelativeUri, $ApiVersion, $Filter, $Select) + if ($RelativeUri -match '^(users|groups|applications|servicePrincipals)/[^/]+$') { + $object = $State.ObjectById[$RelativeUri.Split('/')[-1]] + if ($null -eq $object) { + $exception = [System.Exception]::new('NotFound (Not Found).') + $exception | Add-Member -NotePropertyName Response -NotePropertyValue ( + [pscustomobject]@{ StatusCode = [System.Net.HttpStatusCode]::NotFound } + ) + throw $exception + } + return $object + } + $key = [string]$RelativeUri + if ($State.Protected.Keys -contains $key) { return $State.Protected[$key] } + return @() + }.GetNewClosure() + } + + AfterEach { + if ($null -ne $State.Detail) { + $State.Detail | Should -Not -Match '`[^`]+`' + } + } + + Context 'No objects are listed' { + It 'is Investigate and says nothing is protected yet' { + Test-MtEntraHardDeletionProtection | Should -BeNullOrEmpty + $State.Investigate | Should -BeTrue + $State.Detail | Should -Match 'verified manually' + $State.Detail | Should -Match 'No object in Microsoft Entra has Hard Deletion Protection yet' + } + + It 'is Investigate and lists the protected objects it finds' { + $State.Protected['users'] = @([pscustomobject]@{ id = $script:UserId; displayName = 'Admin One' }) + $State.Protected['directory/deletedItems/microsoft.graph.group'] = @( + [pscustomobject]@{ id = $script:GroupId; displayName = 'Deleted group' } + ) + + Test-MtEntraHardDeletionProtection | Should -BeNullOrEmpty + $State.Investigate | Should -BeTrue + $State.Detail | Should -Match '2 object\(s\) have Hard Deletion Protection' + $State.Detail | Should -Match "User \| $($script:UserId) \| Admin One \| Active" + $State.Detail | Should -Match "Group \| $($script:GroupId) \| Deleted group \| Soft deleted" + } + } + + Context 'Objects are listed' { + It 'passes when every listed object is protected and nothing else is' { + $State.Listed = @([pscustomobject]@{ Type = 'User'; Id = $script:UserId }) + $State.ObjectById[$script:UserId] = [pscustomobject]@{ + id = $script:UserId; displayName = 'Admin One'; isHardDeleteProtectionEnabled = $true + } + $State.Protected['users'] = @([pscustomobject]@{ id = $script:UserId; displayName = 'Admin One' }) + + Test-MtEntraHardDeletionProtection | Should -BeTrue + $State.Investigate | Should -BeFalse + $State.Detail | Should -Match 'Well done' + } + + It 'is Investigate when listed objects pass but other protected objects are not listed' { + $State.Listed = @([pscustomobject]@{ Type = 'User'; Id = $script:UserId }) + $State.ObjectById[$script:UserId] = [pscustomobject]@{ + id = $script:UserId; displayName = 'Admin One'; isHardDeleteProtectionEnabled = $true + } + $State.Protected['users'] = @( + [pscustomobject]@{ id = $script:UserId; displayName = 'Admin One' } + [pscustomobject]@{ id = $script:GroupId; displayName = 'Other admin' } + ) + + Test-MtEntraHardDeletionProtection | Should -BeNullOrEmpty + $State.Investigate | Should -BeTrue + $State.Detail | Should -Match 'Other admin' + $State.Detail | Should -Not -Match 'Admin One \|' + } + + It 'fails and lists an unprotected object, even when other protected objects are not listed' { + $State.Listed = @([pscustomobject]@{ Type = 'user'; Id = $script:UserId }) + $State.ObjectById[$script:UserId] = [pscustomobject]@{ + id = $script:UserId; displayName = 'Plain | User'; isHardDeleteProtectionEnabled = $null + } + $State.Protected['groups'] = @([pscustomobject]@{ id = $script:GroupId; displayName = 'Some group' }) + + Test-MtEntraHardDeletionProtection | Should -BeFalse + $State.Investigate | Should -BeFalse + $State.Detail | Should -Match '1 of 1 listed object' + $State.Detail | Should -Match 'User \| 11111111-1111-1111-1111-111111111111 \| Plain | User \| Not protected' + $State.Detail | Should -Match 'Some group' + } + + It 'fails an object that cannot be found' { + $State.Listed = @([pscustomobject]@{ Type = 'Group'; Id = $script:GroupId }) + + Test-MtEntraHardDeletionProtection | Should -BeFalse + $State.Detail | Should -Match 'Not found' + } + + It 'fails a listed object that is protected but soft deleted' { + $State.Listed = @([pscustomobject]@{ Type = 'Group'; Id = $script:GroupId }) + $State.Protected['directory/deletedItems/microsoft.graph.group'] = @( + [pscustomobject]@{ id = $script:GroupId; displayName = 'Deleted group' } + ) + + Test-MtEntraHardDeletionProtection | Should -BeFalse + $State.Detail | Should -Match 'Group \| 22222222-2222-2222-2222-222222222222 \| Deleted group \| Soft deleted' + } + + It 'shows the first 25 unlisted objects and the total' { + $State.Listed = @([pscustomobject]@{ Type = 'User'; Id = $script:UserId }) + $State.ObjectById[$script:UserId] = [pscustomobject]@{ + id = $script:UserId; displayName = 'Admin One'; isHardDeleteProtectionEnabled = $true + } + $State.Protected['groups'] = @( + 1..30 | ForEach-Object { + [pscustomobject]@{ id = ('33333333-3333-3333-3333-{0:D12}' -f $_); displayName = "Group $_" } + } + ) + + Test-MtEntraHardDeletionProtection | Should -BeNullOrEmpty + $State.Detail | Should -Match '30 other object\(s\)' + $State.Detail | Should -Match 'Showing the first 25 of 30 objects' + $State.Detail | Should -Match 'Group 25 \|' + $State.Detail | Should -Not -Match 'Group 26 \|' + } + } + + Context 'Errors' { + It 'throws for an invalid object type' { + $State.Listed = @([pscustomobject]@{ Type = 'Device'; Id = $script:UserId }) + + { Test-MtEntraHardDeletionProtection } | + Should -Throw '*Type must be User, Group, Application or ServicePrincipal*' + } + + It 'throws for a Graph error that is not a 404' { + $State.Listed = @([pscustomobject]@{ Type = 'User'; Id = $script:UserId }) + Mock -ModuleName Maester Invoke-MtGraphRequest -MockWith { + [CmdletBinding()] + param($RelativeUri, $ApiVersion, $Filter, $Select) + if ($RelativeUri -like 'users/*') { + $exception = [System.Exception]::new('Forbidden (Forbidden).') + $exception | Add-Member -NotePropertyName Response -NotePropertyValue ( + [pscustomobject]@{ StatusCode = [System.Net.HttpStatusCode]::Forbidden } + ) + throw $exception + } + return @() + } + + { Test-MtEntraHardDeletionProtection } | Should -Throw '*Forbidden*' + } + } +} diff --git a/tests/maester/entra/Test.MT.1276.md b/tests/maester/entra/Test.MT.1276.md new file mode 100644 index 0000000000..034b640940 --- /dev/null +++ b/tests/maester/entra/Test.MT.1276.md @@ -0,0 +1,27 @@ +Critical Entra objects should have Hard Deletion Protection enabled. + +This test reads the users, groups, applications and service principals listed in the +`HardDeletionProtectedObjects` setting of the Maester config and compares each one with its Hard Deletion +Protection setting in Microsoft Entra. Any listed object that is not protected, is soft deleted, or cannot be found +fails the test. If nothing is listed, or every listed object is protected but other objects in Microsoft Entra +have protection and are not listed, the result is **Investigate**: check whether the list is complete. + +See [Hard Deletion Protection](https://maester.dev/docs/configuration/hard-deletion-protection) for the +configuration format and for suggestions on which objects to list. + +#### Remediation action: + +1. Sign in to the [Microsoft Entra admin center](https://entra.microsoft.com) as at least a **Microsoft Entra Backup Administrator**. +2. Browse to **Backup and recovery** > **Hard deletion protection**. +3. Select **Add protection** and choose one object type. +4. Select the reported objects (up to 20 per operation) and review the permanent-protection warning. +5. Select **Save**. + +Protection is permanent and cannot be removed once enabled. + +#### Related links + +* [Configure Hard Deletion Protection in Microsoft Entra (preview)](https://learn.microsoft.com/entra/backup/configure-hard-deletion-protection) + + +%TestResult% diff --git a/tests/maester/entra/Test.MT.1276.ps1 b/tests/maester/entra/Test.MT.1276.ps1 new file mode 100644 index 0000000000..fb14e35e6c --- /dev/null +++ b/tests/maester/entra/Test.MT.1276.ps1 @@ -0,0 +1,94 @@ +function Test-MtEntraHardDeletionProtection { + <# + .SYNOPSIS + Checks that the critical Entra objects listed in the Maester config have Hard Deletion Protection enabled. + + .DESCRIPTION + Reads the HardDeletionProtectedObjects setting and checks that each listed user, group, application or + service principal has isHardDeleteProtectionEnabled set to true. Protection is permanent once enabled, so + Maester never guesses which objects are critical. + + The result is Failed when a listed object is not protected, is soft deleted or cannot be found. The result + is Investigate when nothing is listed, or when every listed object is protected but other objects in the + tenant have protection and are not listed, because the config and the tenant then disagree. + + Hard Deletion Protection is in preview and the property is only available in Microsoft Graph beta. + + .EXAMPLE + Test-MtEntraHardDeletionProtection + + .LINK + https://maester.dev/docs/commands/Test-MtEntraHardDeletionProtection + #> + [MaesterTest( + Id = 'MT.1276', + Title = 'Critical Entra objects should have Hard Deletion Protection enabled (Preview).', + Product = 'entra', + Feature = 'backup-and-recovery', + Area = 'data-protection', + ResourceType = 'Tenant', + Severity = 'Medium', + UserImpact = 'Low', + ImplementationCost = 'Low', + Mitre = ('T1485', 'T1531'), + Service = 'Graph', + Lifecycle = 'Preview', + Author = 'agnivesh' + )] + [CmdletBinding()] + [OutputType([bool])] + param() + + $ConfiguredObjects = @(Get-MtSetting -Name 'HardDeletionProtectedObjects' | Where-Object { $_ }) + $Protected = @(Get-MtEntraHardDeletionProtectedObject) + + if ($ConfiguredObjects.Count -eq 0) { + $Result = 'No objects are listed in HardDeletionProtectedObjects in the Maester config, so Hard Deletion ' + + "Protection must be verified manually.`n`n" + if ($Protected.Count -gt 0) { + $Result += "These $($Protected.Count) object(s) have Hard Deletion Protection in Microsoft Entra. " + + "Add the ones that matter to the config so this test can check them:`n`n" + $Result += Format-MtEntraHardDeletionTable -InputObject $Protected -StateProperty State -StateHeading State + } else { + $Result += 'No object in Microsoft Entra has Hard Deletion Protection yet. Add the critical users, ' + + 'groups, applications and service principals to protect to GlobalSettings.' + + 'HardDeletionProtectedObjects, then enable protection on them. See ' + + 'https://maester.dev/docs/configuration/hard-deletion-protection for the format.' + } + Add-MtTestResultDetail -Investigate -Result $Result + return $null + } + + $Rows = @( + foreach ($Configured in $ConfiguredObjects) { + Get-MtEntraHardDeletionObjectStatus -Configured $Configured -ProtectedObject $Protected + } + ) + $Unlisted = @($Protected | Where-Object { $Rows.Id -notcontains $_.Id }) + $UnlistedTable = if ($Unlisted.Count -gt 0) { + "`n`n$($Unlisted.Count) other object(s) have Hard Deletion Protection in Microsoft Entra but are not " + + "listed in the Maester config:`n`n" + + (Format-MtEntraHardDeletionTable -InputObject $Unlisted -StateProperty State -StateHeading State) + } else { + '' + } + + $Failing = @($Rows | Where-Object { $_.Status -ne 'Protected' }) + if ($Failing.Count -gt 0) { + $Result = "$($Failing.Count) of $($Rows.Count) listed object(s) do not have Hard Deletion Protection " + + "enabled, or are deleted or missing.`n`n" + + (Format-MtEntraHardDeletionTable -InputObject $Failing -StateProperty Status -StateHeading Status) + Add-MtTestResultDetail -Result ($Result + $UnlistedTable) + return $false + } + + if ($Unlisted.Count -gt 0) { + $Result = "All $($Rows.Count) listed object(s) have Hard Deletion Protection enabled. Check whether the " + + 'other protected objects below belong in the Maester config.' + $UnlistedTable + Add-MtTestResultDetail -Investigate -Result $Result + return $null + } + + Add-MtTestResultDetail -Result "Well done. All $($Rows.Count) listed object(s) have Hard Deletion Protection enabled." + return $true +} diff --git a/website/docs/configuration/hard-deletion-protection.md b/website/docs/configuration/hard-deletion-protection.md new file mode 100644 index 0000000000..41bbb9d6a1 --- /dev/null +++ b/website/docs/configuration/hard-deletion-protection.md @@ -0,0 +1,192 @@ +--- +title: Hard Deletion Protection +sidebar: + order: 3 +--- + +# Configuring Hard Deletion Protection + +Hard Deletion Protection (preview) is a Microsoft Entra feature that stops a protected object from being permanently deleted during the first seven days after it is soft deleted. The object can still be soft deleted and restored, so you have time to notice the deletion, investigate it and recover the object. + +Maester includes tests that check the objects you list in the Maester configuration against their Hard Deletion Protection setting in Microsoft Entra. + +:::caution +Protection is **permanent**. Once enabled on an object it cannot be removed. If you enable it by mistake, soft delete the object and wait seven days before you permanently delete it. Microsoft intends the feature for selected critical objects, not for every object in the tenant. +::: + +## How Hard Deletion Protection Works + +- The seven-day protection window starts when the object is soft deleted. +- An attempt to permanently delete the object during the window is blocked. In testing, Microsoft Graph returned `403 Forbidden` with the `Authorization_RequestDenied` error code and a message that gives the time the window ends. The Microsoft Graph reference documents `409 Conflict` for this case, so match on the message and not on the status code if you build detection around it. +- After the window ends, the object can be permanently deleted as normal. +- If you restore the object, protection stays enabled. If you soft delete it again, a new seven-day window starts. +- Protection can only be enabled on active (not deleted) objects. +- Enabling protection is recorded in the Microsoft Entra audit logs. + +Supported objects: + +| Object | Notes | +|--------|-------| +| Users | Cloud-only users, including guests. Users synchronized from on-premises Active Directory are not supported. | +| Groups | Cloud-only Microsoft 365 and security groups. Mail-enabled security groups and distribution groups are not supported. | +| Applications | App registrations in your tenant. | +| Service principals | Service principals in your tenant, such as enterprise applications. Some system-created service principals, such as those for Azure Automation accounts, cannot be protected. | + +Microsoft Entra Agent ID objects are supported through their underlying user, application and service principal types. No additional license is required. + +## Configuration Format + +Hard Deletion Protection objects are configured in the `GlobalSettings` section of your custom `maester-config.json` file. + +### Basic Structure + +```json +{ + "GlobalSettings": { + "HardDeletionProtectedObjects": [ + // The critical objects that must be protected + ] + } +} +``` + +### Supported Parameters + +Each entry in the `HardDeletionProtectedObjects` array supports the following parameters: + +| Parameter | Required | Description | +|-----------|----------|-------------| +| `Type` | Yes | The type of object. Must be `User`, `Group`, `Application` or `ServicePrincipal` | +| `Id` | Yes | The Object ID (GUID) of the object | + +For an application, use the **Object ID** of the app registration, not the Application (client) ID. For a service principal, use the Object ID of the enterprise application. + +## Configuration Examples + +```json +{ + "GlobalSettings": { + "HardDeletionProtectedObjects": [ + { "Type": "User", "Id": "00000000-0000-0000-0000-000000000001" }, + { "Type": "Group", "Id": "00000000-0000-0000-0000-000000000002" }, + { "Type": "Application", "Id": "00000000-0000-0000-0000-000000000003" }, + { "Type": "ServicePrincipal", "Id": "00000000-0000-0000-0000-000000000004" } + ] + } +} +``` + +## What the Test Reports + +| Situation | Result | +|-----------|--------| +| Every listed object has protection enabled, and no other object in Microsoft Entra has protection | **Passed** | +| Every listed object has protection enabled, but other objects in Microsoft Entra have protection and are not listed | **Investigate**. The other objects are listed so you can decide whether they belong in the configuration | +| A listed object does not have protection enabled, or Microsoft Entra returns no value for it | **Failed**, and the object is listed in the result | +| A listed object is soft deleted | **Failed**, and the object is listed with the status `Soft deleted` | +| A listed object does not exist | **Failed**, and the object is listed with the status `Not found` | +| No objects are listed in the configuration | **Investigate**. Protection has to be verified manually. The objects that already have protection in Microsoft Entra are listed to help you build the configuration | + +Microsoft Graph returns `null` for an object that is not protected, so an unprotected object and an object that cannot be protected (such as a synchronized user) both appear as not protected. + +The result lists at most 25 objects in each table and gives the total when there are more. Each table shows the object type, object ID, display name, and whether the object is active or soft deleted. A failed result also lists the objects that have protection but are not in the configuration, so you can see both gaps at once. + +## Which Objects to Protect + +Protect the objects whose permanent loss would be hard to recover from or would help an attacker hide their tracks. These are suggestions, not requirements. Start small and add objects as you decide they are critical. + +### Users + +- **Emergency access (break glass) accounts** - Losing them can lock you out of the tenant. See [Emergency Access Accounts](./emergency-access-accounts.md). +- **Administrators** - Global Administrators and other holders of privileged roles. Protection can stop a departing administrator or an attacker from removing the accounts that can undo their changes. +- **Executives and other VIP accounts** - Accounts with high-value mailboxes and data, and accounts that are often targeted. +- **Critical business accounts** - Finance, HR and legal approvers, and accounts that own critical processes. +- **Dedicated service accounts** - Cloud-only user accounts that applications or integrations sign in with. + +### Groups + +- **Role-assignable groups** - Groups that grant Microsoft Entra roles. +- **Groups used in Conditional Access policies** - Groups that policies include or exclude, such as emergency access or exception groups. +- **Groups that grant access to sensitive apps or data** - Including the Microsoft 365 groups behind critical teams and sites. + +### Applications and service principals + +- **Applications with high-privilege permissions** - For example Microsoft Graph application permissions that can read or change many objects. +- **Line-of-business and single sign-on apps** - Apps that many users depend on to work. +- **Automation and pipeline identities** - Apps and service principals used by deployment pipelines, backup tools and security tooling, and the workload identities behind agents. +- **Identity infrastructure apps** - Apps that other services or federation depend on. + +### What not to protect + +- Test and temporary objects, since protection cannot be undone. +- Users synchronized from on-premises Active Directory, which are not supported. +- Whole categories of objects. The feature is not designed for blanket protection, and you can protect only 20 objects of one type per operation in the portal. + +## Enabling Protection + +Maester does not enable protection. Use the Microsoft Entra admin center or Microsoft Graph. + +### Microsoft Entra admin center + +1. Sign in to the [Microsoft Entra admin center](https://entra.microsoft.com) as at least a **Microsoft Entra Backup Administrator**. +2. Browse to **Backup and recovery** > **Hard deletion protection**. +3. Select **Add protection** and choose one object type. +4. Select up to 20 objects and review the permanent-protection warning. +5. Select **Save**. + +### Microsoft Graph + +Set `isHardDeleteProtectionEnabled` to `true` on the object with the Microsoft Graph beta endpoint. The calling app or user needs the `HardDeletionSetting.ReadWrite.Enable` permission and the Global Administrator or Backup Administrator role. + +```powershell +Connect-MgGraph -Scopes 'HardDeletionSetting.ReadWrite.Enable' + +$body = @{ isHardDeleteProtectionEnabled = $true } +Invoke-MgGraphRequest -Method PATCH -Uri 'https://graph.microsoft.com/beta/users/' -Body $body +``` + +Use `groups`, `applications` or `servicePrincipals` in place of `users` for the other object types. + +## Finding Object IDs + +### In the Microsoft Entra admin center + +1. Go to the [Microsoft Entra admin center](https://entra.microsoft.com) +2. Open **Users**, **Groups**, **App registrations** or **Enterprise applications** +3. Search for the object +4. Copy the **Object ID** from its overview page + +### With PowerShell + +```powershell +Get-MgUser -UserId "admin@contoso.com" | Select-Object Id, UserPrincipalName +Get-MgGroup -Filter "displayName eq 'Privileged Access Group'" | Select-Object Id, DisplayName +Get-MgApplication -Filter "displayName eq 'Contoso Deployment'" | Select-Object Id, DisplayName +Get-MgServicePrincipal -Filter "displayName eq 'Contoso Deployment'" | Select-Object Id, DisplayName +``` + +## Related Tests + +| Test ID | Description | +|---------|-------------| +| MT.1276 | Critical Entra objects should have Hard Deletion Protection enabled (Preview) | + +MT.1276 is a preview test. Run it with the `-IncludePreview` switch of `Invoke-Maester`. + +## Best Practices + +1. **Protect deliberately** - Protection is permanent, so list only the objects you are sure about. + +2. **Combine it with Protected Actions** - Protected Actions can require phishing-resistant MFA before someone permanently deletes an object. Hard Deletion Protection blocks the deletion during its window even when the user passes that check. Protected Actions needs Microsoft Entra ID P1 or P2. + +3. **Monitor deletions** - Protection does not stop soft deletion. Alert on deletions of your critical objects so that you notice them within the seven days. + +4. **Keep the list current** - Add new critical objects as you create them and review the list when staff or roles change. + +## Learn More + +- [Configure Hard Deletion Protection in Microsoft Entra (preview)](https://learn.microsoft.com/entra/backup/configure-hard-deletion-protection) +- [Microsoft Graph permissions reference: HardDeletionSetting.ReadWrite.Enable](https://learn.microsoft.com/graph/permissions-reference) +- [Hard Deletion Protection for Entra ID Directory Objects (Office 365 for IT Pros)](https://office365itpros.com/2026/11/09/hard-deletion-protection/) +- [Microsoft adds hard deletion protection for Entra ID (Our Cloud Network)](https://ourcloudnetwork.com/microsoft-adds-hard-deletion-protection-for-entra-id/) +- [Hard Deletion Protection in Microsoft Entra ID (HTMD)](https://www.anoopcnair.com/hard-deletion-protection-in-microsoft-entra-id/) diff --git a/website/docs/configuration/overview.md b/website/docs/configuration/overview.md index 54bce6c518..7c3a649a58 100644 --- a/website/docs/configuration/overview.md +++ b/website/docs/configuration/overview.md @@ -141,6 +141,7 @@ The following global settings are available for customization: | `DefenderEndpointPolicyFiltering` | Which Defender for Endpoint policies the Defender checks read: `All`, `IncludeUnassigned` or `OnlyAssigned` (default) | This page | | `DefenderEndpointComplianceLogic` | How the Defender for Endpoint checks combine policies: `EffectivePolicy` (default), `AllPolicies` or `AnyPolicy` | This page | | `XspmExternalDataUris` | Override the HTTPS sources used by XSPM Advanced Hunting queries | This page | +| `HardDeletionProtectedObjects` | Define the critical users, groups, applications and service principals that must have Hard Deletion Protection enabled | [Hard Deletion Protection](./hard-deletion-protection.md) | The GitHub and Dataverse settings are listed in the [run configuration reference](./run-configuration.md#globalsettings). diff --git a/website/docs/configuration/run-configuration.md b/website/docs/configuration/run-configuration.md index 06c37a8e9d..bfcbf28477 100644 --- a/website/docs/configuration/run-configuration.md +++ b/website/docs/configuration/run-configuration.md @@ -80,6 +80,10 @@ Keys Maester does not know are kept and passed through, so they do no harm. The "EmergencyAccessAccounts": [ { "Type": "User", "UserPrincipalName": "BreakGlass1@contoso.com" }, { "Type": "Group", "Id": "00000000-0000-0000-0000-000000000000" } + ], + "HardDeletionProtectedObjects": [ + { "Type": "User", "Id": "00000000-0000-0000-0000-000000000001" }, + { "Type": "ServicePrincipal", "Id": "00000000-0000-0000-0000-000000000002" } ] }, "Selection": { @@ -153,6 +157,7 @@ Maester knows these: | `DefenderEndpointComplianceLogic` | string | `EffectivePolicy` | Defender for Endpoint checks. | | `DataverseEnvironmentUrl` | string | | Copilot Studio checks. | | `AzureDevOpsOrganization` | string | | Default organization for `Connect-Maester -Service AzureDevOps`. | +| `HardDeletionProtectedObjects` | array | none | Critical objects (`Type` and `Id`) that must have Hard Deletion Protection enabled. See [Hard Deletion Protection](./hard-deletion-protection.md). | | `GitHubOrganization` | string | | GitHub checks. | | `GitHubApiBaseUri` | string | `https://api.github.com` | GitHub checks. | | `GitHubApiVersion` | string | `2022-11-28` | GitHub checks. | diff --git a/website/src/data/test-builder.json b/website/src/data/test-builder.json index 2b025d35ea..67be0026d5 100644 --- a/website/src/data/test-builder.json +++ b/website/src/data/test-builder.json @@ -310,6 +310,10 @@ { "key": "recommendations", "name": "Entra recommendations" + }, + { + "key": "backup-and-recovery", + "name": "Backup and recovery" } ] }, From 84ac1c8fee52617dfdd27f627110a116a3bfcbe5 Mon Sep 17 00:00:00 2001 From: agnivesh <320655+agnivesh@users.noreply.github.com> Date: Tue, 10 Nov 2026 14:24:20 +0000 Subject: [PATCH 02/11] docs(entra): say how MT.1276 limits destructive deletion by a compromised admin --- tests/maester/entra/Test.MT.1276.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/maester/entra/Test.MT.1276.md b/tests/maester/entra/Test.MT.1276.md index 034b640940..832dc99589 100644 --- a/tests/maester/entra/Test.MT.1276.md +++ b/tests/maester/entra/Test.MT.1276.md @@ -6,6 +6,10 @@ Protection setting in Microsoft Entra. Any listed object that is not protected, fails the test. If nothing is listed, or every listed object is protected but other objects in Microsoft Entra have protection and are not listed, the result is **Investigate**: check whether the list is complete. +Protection limits destructive deletion by a compromised administrator. A protected object stays recoverable for +seven days after it is soft deleted, so an attacker cannot permanently destroy accounts or remove access +(MITRE T1485 Data Destruction and T1531 Account Access Removal) before someone notices. + See [Hard Deletion Protection](https://maester.dev/docs/configuration/hard-deletion-protection) for the configuration format and for suggestions on which objects to list. From a6b806831b5ff302efcba727993159024234cc4b Mon Sep 17 00:00:00 2001 From: agnivesh <320655+agnivesh@users.noreply.github.com> Date: Tue, 10 Nov 2026 14:30:14 +0000 Subject: [PATCH 03/11] test(entra): drop unused mock parameters from the MT.1276 tests --- .../functions/Test-MtEntraHardDeletionProtection.Tests.ps1 | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 b/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 index 899447639a..1c8eebd976 100644 --- a/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 +++ b/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 @@ -19,8 +19,7 @@ $State.Investigate = [bool]$Investigate }.GetNewClosure() Mock -ModuleName Maester Invoke-MtGraphRequest -MockWith { - [CmdletBinding()] - param($RelativeUri, $ApiVersion, $Filter, $Select) + param($RelativeUri) if ($RelativeUri -match '^(users|groups|applications|servicePrincipals)/[^/]+$') { $object = $State.ObjectById[$RelativeUri.Split('/')[-1]] if ($null -eq $object) { @@ -156,8 +155,7 @@ It 'throws for a Graph error that is not a 404' { $State.Listed = @([pscustomobject]@{ Type = 'User'; Id = $script:UserId }) Mock -ModuleName Maester Invoke-MtGraphRequest -MockWith { - [CmdletBinding()] - param($RelativeUri, $ApiVersion, $Filter, $Select) + param($RelativeUri) if ($RelativeUri -like 'users/*') { $exception = [System.Exception]::new('Forbidden (Forbidden).') $exception | Add-Member -NotePropertyName Response -NotePropertyValue ( From 187706544bff11bdf54183ccdb2a42f3bed90a5f Mon Sep 17 00:00:00 2001 From: agnivesh <320655+agnivesh@users.noreply.github.com> Date: Tue, 10 Nov 2026 15:46:53 +0000 Subject: [PATCH 04/11] fix(entra): report a deleted MT.1276 object as soft deleted, not missing A listed object that was soft deleted without protection is not in the protected-object list, so it was reported as Not found. When the active lookup returns 404, look for the object among the deleted items of the same type and report Soft deleted when it is there. --- .../Get-MtEntraHardDeletionObjectStatus.ps1 | 57 +++++++------------ ...st-MtEntraHardDeletionProtection.Tests.ps1 | 40 ++++++++++--- tests/maester/entra/Test.MT.1276.ps1 | 2 +- 3 files changed, 55 insertions(+), 44 deletions(-) diff --git a/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionObjectStatus.ps1 b/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionObjectStatus.ps1 index a59db78330..36d3c1950d 100644 --- a/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionObjectStatus.ps1 +++ b/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionObjectStatus.ps1 @@ -5,41 +5,28 @@ .DESCRIPTION Reads the object from Microsoft Graph beta. Status is 'Protected', 'Not protected', 'Soft deleted' or - 'Not found'. An object that cannot be read as an active object is 'Soft deleted' when it appears in the - supplied protected objects as soft deleted, and 'Not found' otherwise. Any Graph error other than - HTTP 404 is thrown. + 'Not found'. When the active lookup returns HTTP 404, the function looks for the object among the deleted + items of the same type. It reports 'Soft deleted' when it finds the object there, whether or not the object + has protection, and 'Not found' when neither lookup finds it. Any Graph error other than HTTP 404 is thrown. .PARAMETER Configured A HardDeletionProtectedObjects entry with Type and Id. - .PARAMETER ProtectedObject - The output of Get-MtEntraHardDeletionProtectedObject. - .EXAMPLE - Get-MtEntraHardDeletionObjectStatus -Configured $Entry -ProtectedObject $Protected + Get-MtEntraHardDeletionObjectStatus -Configured $Entry #> [CmdletBinding()] [OutputType([pscustomobject])] param( [Parameter(Mandatory)] - [object] $Configured, - - [Parameter()] - [AllowEmptyCollection()] - [object[]] $ProtectedObject = @() + [object] $Configured ) $EndpointByType = @{ - user = 'users' - group = 'groups' - application = 'applications' - serviceprincipal = 'servicePrincipals' - } - $TypeNames = @{ - user = 'User' - group = 'Group' - application = 'Application' - serviceprincipal = 'ServicePrincipal' + user = @{ Name = 'User'; Path = 'users'; GraphType = 'user' } + group = @{ Name = 'Group'; Path = 'groups'; GraphType = 'group' } + application = @{ Name = 'Application'; Path = 'applications'; GraphType = 'application' } + serviceprincipal = @{ Name = 'ServicePrincipal'; Path = 'servicePrincipals'; GraphType = 'servicePrincipal' } } $Type = ([string]$Configured.Type).ToLowerInvariant() @@ -49,33 +36,33 @@ 'Type must be User, Group, Application or ServicePrincipal and Id must be an object ID.' ) } + $Endpoint = $EndpointByType[$Type] $Object = $null + $Status = 'Not found' try { - $Object = Invoke-MtGraphRequest -ApiVersion 'beta' ` - -RelativeUri "$($EndpointByType[$Type])/$($Configured.Id)" ` + $Object = Invoke-MtGraphRequest -ApiVersion 'beta' -RelativeUri "$($Endpoint.Path)/$($Configured.Id)" ` -Select @('id', 'displayName', 'isHardDeleteProtectionEnabled') -ErrorAction Stop + $Status = if ($Object.isHardDeleteProtectionEnabled -eq $true) { 'Protected' } else { 'Not protected' } } catch { if ($_.Exception.Response.StatusCode -ne [System.Net.HttpStatusCode]::NotFound) { throw } } - $DisplayName = '' - $Status = 'Not found' - if ($Object) { - $DisplayName = [string]$Object.displayName - $Status = if ($Object.isHardDeleteProtectionEnabled -eq $true) { 'Protected' } else { 'Not protected' } - } else { - $Deleted = @($ProtectedObject | Where-Object { $_.Id -eq [string]$Configured.Id -and $_.State -eq 'Soft deleted' }) - if ($Deleted.Count -gt 0) { - $DisplayName = $Deleted[0].DisplayName + if (!$Object) { + try { + $Object = Invoke-MtGraphRequest -ApiVersion 'beta' ` + -RelativeUri "directory/deletedItems/microsoft.graph.$($Endpoint.GraphType)/$($Configured.Id)" ` + -Select @('id', 'displayName') -ErrorAction Stop $Status = 'Soft deleted' + } catch { + if ($_.Exception.Response.StatusCode -ne [System.Net.HttpStatusCode]::NotFound) { throw } } } [pscustomobject]@{ - Type = $TypeNames[$Type] + Type = $Endpoint.Name Id = [string]$Configured.Id - DisplayName = $DisplayName + DisplayName = if ($Object) { [string]$Object.displayName } else { '' } Status = $Status } } diff --git a/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 b/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 index 1c8eebd976..372bf3844b 100644 --- a/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 +++ b/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 @@ -10,7 +10,13 @@ } BeforeEach { - $State = @{ Detail = $null; Investigate = $false; Listed = @(); Protected = @{}; ObjectById = @{} } + $State = @{ + Detail = $null; Investigate = $false; Listed = @(); Protected = @{}; ObjectById = @{}; DeletedById = @{} + } + $NotFoundError = [System.Exception]::new('NotFound (Not Found).') + $NotFoundError | Add-Member -NotePropertyName Response -NotePropertyValue ( + [pscustomobject]@{ StatusCode = [System.Net.HttpStatusCode]::NotFound } + ) Mock -ModuleName Maester Get-MtSetting -MockWith { return $State.Listed }.GetNewClosure() Mock -ModuleName Maester Add-MtTestResultDetail -MockWith { @@ -20,15 +26,14 @@ }.GetNewClosure() Mock -ModuleName Maester Invoke-MtGraphRequest -MockWith { param($RelativeUri) + if ($RelativeUri -match '^directory/deletedItems/microsoft\.graph\.[A-Za-z]+/[^/]+$') { + $deleted = $State.DeletedById[$RelativeUri.Split('/')[-1]] + if ($null -eq $deleted) { throw $NotFoundError } + return $deleted + } if ($RelativeUri -match '^(users|groups|applications|servicePrincipals)/[^/]+$') { $object = $State.ObjectById[$RelativeUri.Split('/')[-1]] - if ($null -eq $object) { - $exception = [System.Exception]::new('NotFound (Not Found).') - $exception | Add-Member -NotePropertyName Response -NotePropertyValue ( - [pscustomobject]@{ StatusCode = [System.Net.HttpStatusCode]::NotFound } - ) - throw $exception - } + if ($null -eq $object) { throw $NotFoundError } return $object } $key = [string]$RelativeUri @@ -117,6 +122,7 @@ It 'fails a listed object that is protected but soft deleted' { $State.Listed = @([pscustomobject]@{ Type = 'Group'; Id = $script:GroupId }) + $State.DeletedById[$script:GroupId] = [pscustomobject]@{ id = $script:GroupId; displayName = 'Deleted group' } $State.Protected['directory/deletedItems/microsoft.graph.group'] = @( [pscustomobject]@{ id = $script:GroupId; displayName = 'Deleted group' } ) @@ -125,6 +131,24 @@ $State.Detail | Should -Match 'Group \| 22222222-2222-2222-2222-222222222222 \| Deleted group \| Soft deleted' } + It 'reports a listed object that was soft deleted without protection as soft deleted, not as not found' { + $State.Listed = @([pscustomobject]@{ Type = 'User'; Id = $script:UserId }) + $State.DeletedById[$script:UserId] = [pscustomobject]@{ id = $script:UserId; displayName = 'Removed user' } + + Test-MtEntraHardDeletionProtection | Should -BeFalse + $State.Detail | Should -Match 'User \| 11111111-1111-1111-1111-111111111111 \| Removed user \| Soft deleted' + $State.Detail | Should -Not -Match 'Not found' + } + + It 'looks for a deleted object among deleted items of the listed type only' { + $State.Listed = @([pscustomobject]@{ Type = 'Group'; Id = $script:GroupId }) + + Test-MtEntraHardDeletionProtection | Should -BeFalse + Should -Invoke -ModuleName Maester Invoke-MtGraphRequest -Times 1 -ParameterFilter { + $RelativeUri -eq "directory/deletedItems/microsoft.graph.group/$('22222222-2222-2222-2222-222222222222')" + } + } + It 'shows the first 25 unlisted objects and the total' { $State.Listed = @([pscustomobject]@{ Type = 'User'; Id = $script:UserId }) $State.ObjectById[$script:UserId] = [pscustomobject]@{ diff --git a/tests/maester/entra/Test.MT.1276.ps1 b/tests/maester/entra/Test.MT.1276.ps1 index fb14e35e6c..1d3252e1ac 100644 --- a/tests/maester/entra/Test.MT.1276.ps1 +++ b/tests/maester/entra/Test.MT.1276.ps1 @@ -61,7 +61,7 @@ $Rows = @( foreach ($Configured in $ConfiguredObjects) { - Get-MtEntraHardDeletionObjectStatus -Configured $Configured -ProtectedObject $Protected + Get-MtEntraHardDeletionObjectStatus -Configured $Configured } ) $Unlisted = @($Protected | Where-Object { $Rows.Id -notcontains $_.Id }) From 7039aee19fc21a719aa20de9f973e2e6836a3594 Mon Sep 17 00:00:00 2001 From: agnivesh <320655+agnivesh@users.noreply.github.com> Date: Wed, 18 Nov 2026 09:45:29 +0000 Subject: [PATCH 05/11] refactor(entra): bind the MT.1276 setting as a parameter and test a real 404 Read HardDeletionProtectedObjects through a MaesterParameter instead of Get-MtSetting, as the other tests do now. The registry entry has Items, so a wrong Type or an entry without an Id stops the run before any test starts. Build the 404 and 403 in the unit tests from the real HttpResponseException, and add a test that an error without an HTTP response is thrown and not reported as Not found. Document the check of the list on the Hard Deletion Protection page. --- ...st-MtEntraHardDeletionProtection.Tests.ps1 | 50 +++++++++++-------- tests/maester/entra/Test.MT.1276.ps1 | 10 ++-- .../configuration/hard-deletion-protection.md | 2 + website/src/data/test-builder.json | 14 ++++++ 4 files changed, 53 insertions(+), 23 deletions(-) diff --git a/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 b/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 index 372bf3844b..497b90cb25 100644 --- a/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 +++ b/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 @@ -13,12 +13,12 @@ $State = @{ Detail = $null; Investigate = $false; Listed = @(); Protected = @{}; ObjectById = @{}; DeletedById = @{} } - $NotFoundError = [System.Exception]::new('NotFound (Not Found).') - $NotFoundError | Add-Member -NotePropertyName Response -NotePropertyValue ( - [pscustomobject]@{ StatusCode = [System.Net.HttpStatusCode]::NotFound } + # The exception Invoke-MtGraphRequest lets through for a single request that Graph answers with 404. + $NotFoundError = [Microsoft.PowerShell.Commands.HttpResponseException]::new( + 'Response status code does not indicate success: NotFound (Not Found).', + [System.Net.Http.HttpResponseMessage]::new([System.Net.HttpStatusCode]::NotFound) ) - Mock -ModuleName Maester Get-MtSetting -MockWith { return $State.Listed }.GetNewClosure() Mock -ModuleName Maester Add-MtTestResultDetail -MockWith { param($Result, [switch] $Investigate) $State.Detail = $Result @@ -50,7 +50,7 @@ Context 'No objects are listed' { It 'is Investigate and says nothing is protected yet' { - Test-MtEntraHardDeletionProtection | Should -BeNullOrEmpty + Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeNullOrEmpty $State.Investigate | Should -BeTrue $State.Detail | Should -Match 'verified manually' $State.Detail | Should -Match 'No object in Microsoft Entra has Hard Deletion Protection yet' @@ -62,7 +62,7 @@ [pscustomobject]@{ id = $script:GroupId; displayName = 'Deleted group' } ) - Test-MtEntraHardDeletionProtection | Should -BeNullOrEmpty + Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeNullOrEmpty $State.Investigate | Should -BeTrue $State.Detail | Should -Match '2 object\(s\) have Hard Deletion Protection' $State.Detail | Should -Match "User \| $($script:UserId) \| Admin One \| Active" @@ -78,7 +78,7 @@ } $State.Protected['users'] = @([pscustomobject]@{ id = $script:UserId; displayName = 'Admin One' }) - Test-MtEntraHardDeletionProtection | Should -BeTrue + Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeTrue $State.Investigate | Should -BeFalse $State.Detail | Should -Match 'Well done' } @@ -93,7 +93,7 @@ [pscustomobject]@{ id = $script:GroupId; displayName = 'Other admin' } ) - Test-MtEntraHardDeletionProtection | Should -BeNullOrEmpty + Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeNullOrEmpty $State.Investigate | Should -BeTrue $State.Detail | Should -Match 'Other admin' $State.Detail | Should -Not -Match 'Admin One \|' @@ -106,7 +106,7 @@ } $State.Protected['groups'] = @([pscustomobject]@{ id = $script:GroupId; displayName = 'Some group' }) - Test-MtEntraHardDeletionProtection | Should -BeFalse + Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeFalse $State.Investigate | Should -BeFalse $State.Detail | Should -Match '1 of 1 listed object' $State.Detail | Should -Match 'User \| 11111111-1111-1111-1111-111111111111 \| Plain | User \| Not protected' @@ -116,7 +116,7 @@ It 'fails an object that cannot be found' { $State.Listed = @([pscustomobject]@{ Type = 'Group'; Id = $script:GroupId }) - Test-MtEntraHardDeletionProtection | Should -BeFalse + Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeFalse $State.Detail | Should -Match 'Not found' } @@ -127,7 +127,7 @@ [pscustomobject]@{ id = $script:GroupId; displayName = 'Deleted group' } ) - Test-MtEntraHardDeletionProtection | Should -BeFalse + Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeFalse $State.Detail | Should -Match 'Group \| 22222222-2222-2222-2222-222222222222 \| Deleted group \| Soft deleted' } @@ -135,7 +135,7 @@ $State.Listed = @([pscustomobject]@{ Type = 'User'; Id = $script:UserId }) $State.DeletedById[$script:UserId] = [pscustomobject]@{ id = $script:UserId; displayName = 'Removed user' } - Test-MtEntraHardDeletionProtection | Should -BeFalse + Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeFalse $State.Detail | Should -Match 'User \| 11111111-1111-1111-1111-111111111111 \| Removed user \| Soft deleted' $State.Detail | Should -Not -Match 'Not found' } @@ -143,7 +143,7 @@ It 'looks for a deleted object among deleted items of the listed type only' { $State.Listed = @([pscustomobject]@{ Type = 'Group'; Id = $script:GroupId }) - Test-MtEntraHardDeletionProtection | Should -BeFalse + Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeFalse Should -Invoke -ModuleName Maester Invoke-MtGraphRequest -Times 1 -ParameterFilter { $RelativeUri -eq "directory/deletedItems/microsoft.graph.group/$('22222222-2222-2222-2222-222222222222')" } @@ -160,7 +160,7 @@ } ) - Test-MtEntraHardDeletionProtection | Should -BeNullOrEmpty + Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeNullOrEmpty $State.Detail | Should -Match '30 other object\(s\)' $State.Detail | Should -Match 'Showing the first 25 of 30 objects' $State.Detail | Should -Match 'Group 25 \|' @@ -172,7 +172,7 @@ It 'throws for an invalid object type' { $State.Listed = @([pscustomobject]@{ Type = 'Device'; Id = $script:UserId }) - { Test-MtEntraHardDeletionProtection } | + { Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed } | Should -Throw '*Type must be User, Group, Application or ServicePrincipal*' } @@ -181,16 +181,26 @@ Mock -ModuleName Maester Invoke-MtGraphRequest -MockWith { param($RelativeUri) if ($RelativeUri -like 'users/*') { - $exception = [System.Exception]::new('Forbidden (Forbidden).') - $exception | Add-Member -NotePropertyName Response -NotePropertyValue ( - [pscustomobject]@{ StatusCode = [System.Net.HttpStatusCode]::Forbidden } + throw [Microsoft.PowerShell.Commands.HttpResponseException]::new( + 'Response status code does not indicate success: Forbidden (Forbidden).', + [System.Net.Http.HttpResponseMessage]::new([System.Net.HttpStatusCode]::Forbidden) ) - throw $exception } return @() } - { Test-MtEntraHardDeletionProtection } | Should -Throw '*Forbidden*' + { Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed } | Should -Throw '*Forbidden*' + } + + It 'throws, instead of reporting Not found, when the error has no HTTP response' { + $State.Listed = @([pscustomobject]@{ Type = 'User'; Id = $script:UserId }) + Mock -ModuleName Maester Invoke-MtGraphRequest -MockWith { + param($RelativeUri) + if ($RelativeUri -like 'users/*') { throw [System.InvalidOperationException]::new('Batch request failed.') } + return @() + } + + { Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed } | Should -Throw '*Batch request failed*' } } } diff --git a/tests/maester/entra/Test.MT.1276.ps1 b/tests/maester/entra/Test.MT.1276.ps1 index 1d3252e1ac..40c56db6ed 100644 --- a/tests/maester/entra/Test.MT.1276.ps1 +++ b/tests/maester/entra/Test.MT.1276.ps1 @@ -4,7 +4,7 @@ Checks that the critical Entra objects listed in the Maester config have Hard Deletion Protection enabled. .DESCRIPTION - Reads the HardDeletionProtectedObjects setting and checks that each listed user, group, application or + Takes the HardDeletionProtectedObjects setting as a parameter and checks that each listed user, group, application or service principal has isHardDeleteProtectionEnabled set to true. Protection is permanent once enabled, so Maester never guesses which objects are critical. @@ -37,9 +37,13 @@ )] [CmdletBinding()] [OutputType([bool])] - param() + param ( + # The objects to check, from the HardDeletionProtectedObjects setting: a Type and an Id each. + [MaesterParameter(Setting = 'HardDeletionProtectedObjects')] + [object[]] $HardDeletionProtectedObjects = @() + ) - $ConfiguredObjects = @(Get-MtSetting -Name 'HardDeletionProtectedObjects' | Where-Object { $_ }) + $ConfiguredObjects = @($HardDeletionProtectedObjects | Where-Object { $_ }) $Protected = @(Get-MtEntraHardDeletionProtectedObject) if ($ConfiguredObjects.Count -eq 0) { diff --git a/website/docs/configuration/hard-deletion-protection.md b/website/docs/configuration/hard-deletion-protection.md index 41bbb9d6a1..8de06e6568 100644 --- a/website/docs/configuration/hard-deletion-protection.md +++ b/website/docs/configuration/hard-deletion-protection.md @@ -61,6 +61,8 @@ Each entry in the `HardDeletionProtectedObjects` array supports the following pa For an application, use the **Object ID** of the app registration, not the Application (client) ID. For a service principal, use the Object ID of the enterprise application. +Maester checks the list before a run starts. A `Type` that is not one of the four values, or an entry without an `Id`, stops the run with a message that names the entry. A property name that is not listed above, such as `ObjectId`, is reported as a warning. + ## Configuration Examples ```json diff --git a/website/src/data/test-builder.json b/website/src/data/test-builder.json index 67be0026d5..ad93d32bbc 100644 --- a/website/src/data/test-builder.json +++ b/website/src/data/test-builder.json @@ -18325,6 +18325,15 @@ "description": "GitHub organization that the GitHub checks read.", "connection": true }, + { + "name": "HardDeletionProtectedObjects", + "type": "object[]", + "kind": null, + "default": [], + "allowedValues": [], + "description": "Critical users, groups, applications and service principals (Type and Id) that must have Hard Deletion Protection enabled.", + "connection": false + }, { "name": "ParkedDomains", "type": "string[]", @@ -18403,6 +18412,11 @@ "type": "int", "tests": 1 }, + { + "name": "HardDeletionProtectedObjects", + "type": "object[]", + "tests": 1 + }, { "name": "MailboxServicePlanIds", "type": "string[]", From 26bfd197305816b79aa1d0197ad072994c18e1c1 Mon Sep 17 00:00:00 2001 From: agnivesh <320655+agnivesh@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:16:51 +0000 Subject: [PATCH 06/11] fix(entra): tighten the MT.1276 lookups and match the docs to the output Require a listed Id to be a GUID and use its canonical form in both Graph requests and in the result. Decide whether an object was not found with Test-MtGraphNotFoundError, which also reads the inner exception. Return an object once when it shows up as both active and soft deleted, and exclude a protected object from the unlisted table only when both its Type and Id are listed. Point .LINK at the MT.1276 test page. Tighten the deleted-item lookup assertion and add tests for each case. In the docs, separate the Status and State columns, say that an entry without a Type or with a non-GUID Id fails the test, and name the Backup Administrator role for the Graph procedure. --- .../Get-MtEntraHardDeletionObjectStatus.ps1 | 21 ++++-- ...Get-MtEntraHardDeletionProtectedObject.ps1 | 27 +++++-- ...st-MtEntraHardDeletionProtection.Tests.ps1 | 75 +++++++++++++++++-- tests/maester/entra/Test.MT.1276.ps1 | 6 +- .../configuration/hard-deletion-protection.md | 11 ++- 5 files changed, 115 insertions(+), 25 deletions(-) diff --git a/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionObjectStatus.ps1 b/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionObjectStatus.ps1 index 36d3c1950d..c65ac01d46 100644 --- a/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionObjectStatus.ps1 +++ b/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionObjectStatus.ps1 @@ -7,7 +7,10 @@ Reads the object from Microsoft Graph beta. Status is 'Protected', 'Not protected', 'Soft deleted' or 'Not found'. When the active lookup returns HTTP 404, the function looks for the object among the deleted items of the same type. It reports 'Soft deleted' when it finds the object there, whether or not the object - has protection, and 'Not found' when neither lookup finds it. Any Graph error other than HTTP 404 is thrown. + has protection, and 'Not found' when neither lookup finds it. Any Graph error other than a 404 is thrown. + + The Id must be the object ID, a GUID. The function uses its canonical lower-case form in both requests and + in the result, so the result matches the objects that Get-MtEntraHardDeletionProtectedObject returns. .PARAMETER Configured A HardDeletionProtectedObjects entry with Type and Id. @@ -30,38 +33,40 @@ } $Type = ([string]$Configured.Type).ToLowerInvariant() - if (!$EndpointByType.ContainsKey($Type) -or [string]::IsNullOrWhiteSpace($Configured.Id)) { + $ParsedId = [guid]::Empty + if (!$EndpointByType.ContainsKey($Type) -or ![guid]::TryParse([string]$Configured.Id, [ref]$ParsedId)) { throw ( "Invalid HardDeletionProtectedObjects entry (Type '$($Configured.Type)', Id '$($Configured.Id)'). " + - 'Type must be User, Group, Application or ServicePrincipal and Id must be an object ID.' + 'Type must be User, Group, Application or ServicePrincipal and Id must be the object ID (a GUID).' ) } $Endpoint = $EndpointByType[$Type] + $Id = $ParsedId.ToString() $Object = $null $Status = 'Not found' try { - $Object = Invoke-MtGraphRequest -ApiVersion 'beta' -RelativeUri "$($Endpoint.Path)/$($Configured.Id)" ` + $Object = Invoke-MtGraphRequest -ApiVersion 'beta' -RelativeUri "$($Endpoint.Path)/$Id" ` -Select @('id', 'displayName', 'isHardDeleteProtectionEnabled') -ErrorAction Stop $Status = if ($Object.isHardDeleteProtectionEnabled -eq $true) { 'Protected' } else { 'Not protected' } } catch { - if ($_.Exception.Response.StatusCode -ne [System.Net.HttpStatusCode]::NotFound) { throw } + if (!(Test-MtGraphNotFoundError -ErrorRecord $_)) { throw } } if (!$Object) { try { $Object = Invoke-MtGraphRequest -ApiVersion 'beta' ` - -RelativeUri "directory/deletedItems/microsoft.graph.$($Endpoint.GraphType)/$($Configured.Id)" ` + -RelativeUri "directory/deletedItems/microsoft.graph.$($Endpoint.GraphType)/$Id" ` -Select @('id', 'displayName') -ErrorAction Stop $Status = 'Soft deleted' } catch { - if ($_.Exception.Response.StatusCode -ne [System.Net.HttpStatusCode]::NotFound) { throw } + if (!(Test-MtGraphNotFoundError -ErrorRecord $_)) { throw } } } [pscustomobject]@{ Type = $Endpoint.Name - Id = [string]$Configured.Id + Id = $Id DisplayName = if ($Object) { [string]$Object.displayName } else { '' } Status = $Status } diff --git a/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionProtectedObject.ps1 b/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionProtectedObject.ps1 index 37db0e61b5..7525c2fed3 100644 --- a/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionProtectedObject.ps1 +++ b/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionProtectedObject.ps1 @@ -8,6 +8,10 @@ among active objects and among soft-deleted ones. Each result has Type, Id, DisplayName and State ('Active' or 'Soft deleted'). + The two reads happen one after the other, so an object can show up in both when it is soft deleted or + restored between them. The function returns such an object once, with the State 'Active or soft deleted', + and does not claim that either read is newer. + .EXAMPLE Get-MtEntraHardDeletionProtectedObject #> @@ -26,6 +30,7 @@ } ) + $Observed = [System.Collections.Generic.List[object]]::new() foreach ($Source in $Sources) { foreach ($State in 'Active', 'Soft deleted') { $Path = if ($State -eq 'Active') { $Source.Path } else { $Source.Deleted } @@ -34,13 +39,23 @@ -Filter 'isHardDeleteProtectionEnabled eq true' -Select @('id', 'displayName') ) foreach ($Object in $Objects) { - [pscustomobject]@{ - Type = $Source.Type - Id = [string]$Object.id - DisplayName = [string]$Object.displayName - State = $State - } + $Observed.Add([pscustomobject]@{ + Type = $Source.Type + Id = [string]$Object.id + DisplayName = [string]$Object.displayName + State = $State + }) } } } + + foreach ($Group in @($Observed | Group-Object -Property Type, Id)) { + $States = @($Group.Group.State | Select-Object -Unique) + [pscustomobject]@{ + Type = $Group.Group[0].Type + Id = $Group.Group[0].Id + DisplayName = $Group.Group[0].DisplayName + State = if ($States.Count -eq 1) { $States[0] } else { 'Active or soft deleted' } + } + } } diff --git a/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 b/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 index 497b90cb25..7fb76c341d 100644 --- a/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 +++ b/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 @@ -11,7 +11,7 @@ BeforeEach { $State = @{ - Detail = $null; Investigate = $false; Listed = @(); Protected = @{}; ObjectById = @{}; DeletedById = @{} + Detail = $null; Investigate = $false; Listed = @(); Protected = @{}; ObjectById = @{}; DeletedById = @{}; Wrap = $false } # The exception Invoke-MtGraphRequest lets through for a single request that Graph answers with 404. $NotFoundError = [Microsoft.PowerShell.Commands.HttpResponseException]::new( @@ -28,12 +28,12 @@ param($RelativeUri) if ($RelativeUri -match '^directory/deletedItems/microsoft\.graph\.[A-Za-z]+/[^/]+$') { $deleted = $State.DeletedById[$RelativeUri.Split('/')[-1]] - if ($null -eq $deleted) { throw $NotFoundError } + if ($null -eq $deleted) { throw $(if ($State.Wrap) { [System.InvalidOperationException]::new('Request failed.', $NotFoundError) } else { $NotFoundError }) } return $deleted } if ($RelativeUri -match '^(users|groups|applications|servicePrincipals)/[^/]+$') { $object = $State.ObjectById[$RelativeUri.Split('/')[-1]] - if ($null -eq $object) { throw $NotFoundError } + if ($null -eq $object) { throw $(if ($State.Wrap) { [System.InvalidOperationException]::new('Request failed.', $NotFoundError) } else { $NotFoundError }) } return $object } $key = [string]$RelativeUri @@ -68,6 +68,17 @@ $State.Detail | Should -Match "User \| $($script:UserId) \| Admin One \| Active" $State.Detail | Should -Match "Group \| $($script:GroupId) \| Deleted group \| Soft deleted" } + + It 'counts an object once when it shows up as both active and soft deleted' { + $State.Protected['users'] = @([pscustomobject]@{ id = $script:UserId; displayName = 'Admin One' }) + $State.Protected['directory/deletedItems/microsoft.graph.user'] = @( + [pscustomobject]@{ id = $script:UserId; displayName = 'Admin One' } + ) + + Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeNullOrEmpty + $State.Detail | Should -Match '1 object\(s\) have Hard Deletion Protection' + $State.Detail | Should -Match 'Admin One \| Active or soft deleted' + } } Context 'Objects are listed' { @@ -140,15 +151,67 @@ $State.Detail | Should -Not -Match 'Not found' } - It 'looks for a deleted object among deleted items of the listed type only' { + It 'looks for a deleted object only among the deleted items of the listed type' { $State.Listed = @([pscustomobject]@{ Type = 'Group'; Id = $script:GroupId }) Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeFalse - Should -Invoke -ModuleName Maester Invoke-MtGraphRequest -Times 1 -ParameterFilter { - $RelativeUri -eq "directory/deletedItems/microsoft.graph.group/$('22222222-2222-2222-2222-222222222222')" + Should -Invoke -ModuleName Maester Invoke-MtGraphRequest -Times 1 -Exactly -ParameterFilter { + $RelativeUri -eq 'directory/deletedItems/microsoft.graph.group/22222222-2222-2222-2222-222222222222' + } + Should -Invoke -ModuleName Maester Invoke-MtGraphRequest -Times 0 -Exactly -ParameterFilter { + $RelativeUri -like 'directory/deletedItems/microsoft.graph.*/22222222-2222-2222-2222-222222222222' -and + $RelativeUri -notlike 'directory/deletedItems/microsoft.graph.group/*' } } + It 'reports a 404 that sits on the inner exception as not found' { + $State.Listed = @([pscustomobject]@{ Type = 'Group'; Id = $script:GroupId }) + $State.Wrap = $true + + Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeFalse + $State.Detail | Should -Match 'Group \| 22222222-2222-2222-2222-222222222222 \| \| Not found' + } + + It 'rejects an Id that is not a GUID before it calls Graph' { + $State.Listed = @([pscustomobject]@{ Type = 'User'; Id = 'admin@contoso.com' }) + + { Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed } | + Should -Throw '*Id must be the object ID (a GUID)*' + Should -Invoke -ModuleName Maester Invoke-MtGraphRequest -Times 0 -Exactly -ParameterFilter { + $RelativeUri -like 'users/*' + } + } + + It 'uses the canonical lower-case form of the Id in the request and in the result' { + $State.Listed = @([pscustomobject]@{ Type = 'User'; Id = '{AAAAAAAA-1111-2222-3333-BBBBBBBBBBBB}' }) + $State.ObjectById['aaaaaaaa-1111-2222-3333-bbbbbbbbbbbb'] = [pscustomobject]@{ + id = 'aaaaaaaa-1111-2222-3333-bbbbbbbbbbbb'; displayName = 'Mixed case'; isHardDeleteProtectionEnabled = $null + } + + Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeFalse + $State.Detail | Should -Match 'User \| aaaaaaaa-1111-2222-3333-bbbbbbbbbbbb \| Mixed case \| Not protected' + } + + It 'keeps a protected object in the unlisted table when its Id is listed under another Type' { + $State.Listed = @([pscustomobject]@{ Type = 'Group'; Id = $script:UserId }) + $State.Protected['users'] = @([pscustomobject]@{ id = $script:UserId; displayName = 'Admin One' }) + + Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeFalse + $State.Detail | Should -Match 'Group \| 11111111-1111-1111-1111-111111111111 \| \| Not found' + $State.Detail | Should -Match 'User \| 11111111-1111-1111-1111-111111111111 \| Admin One \| Active' + } + + It 'does not list a correctly listed object as unlisted' { + $State.Listed = @([pscustomobject]@{ Type = 'User'; Id = $script:UserId }) + $State.ObjectById[$script:UserId] = [pscustomobject]@{ + id = $script:UserId; displayName = 'Admin One'; isHardDeleteProtectionEnabled = $true + } + $State.Protected['users'] = @([pscustomobject]@{ id = $script:UserId; displayName = 'Admin One' }) + + Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeTrue + $State.Detail | Should -Not -Match 'other object' + } + It 'shows the first 25 unlisted objects and the total' { $State.Listed = @([pscustomobject]@{ Type = 'User'; Id = $script:UserId }) $State.ObjectById[$script:UserId] = [pscustomobject]@{ diff --git a/tests/maester/entra/Test.MT.1276.ps1 b/tests/maester/entra/Test.MT.1276.ps1 index 40c56db6ed..7cb8439eda 100644 --- a/tests/maester/entra/Test.MT.1276.ps1 +++ b/tests/maester/entra/Test.MT.1276.ps1 @@ -18,7 +18,7 @@ Test-MtEntraHardDeletionProtection .LINK - https://maester.dev/docs/commands/Test-MtEntraHardDeletionProtection + https://maester.dev/docs/tests/MT.1276 #> [MaesterTest( Id = 'MT.1276', @@ -68,7 +68,9 @@ Get-MtEntraHardDeletionObjectStatus -Configured $Configured } ) - $Unlisted = @($Protected | Where-Object { $Rows.Id -notcontains $_.Id }) + $ListedKeys = @{} + foreach ($Row in $Rows) { $ListedKeys["$($Row.Type)|$($Row.Id)"] = $true } + $Unlisted = @($Protected | Where-Object { -not $ListedKeys.ContainsKey("$($_.Type)|$($_.Id)") }) $UnlistedTable = if ($Unlisted.Count -gt 0) { "`n`n$($Unlisted.Count) other object(s) have Hard Deletion Protection in Microsoft Entra but are not " + "listed in the Maester config:`n`n" + diff --git a/website/docs/configuration/hard-deletion-protection.md b/website/docs/configuration/hard-deletion-protection.md index 8de06e6568..e30d1db8a4 100644 --- a/website/docs/configuration/hard-deletion-protection.md +++ b/website/docs/configuration/hard-deletion-protection.md @@ -61,7 +61,7 @@ Each entry in the `HardDeletionProtectedObjects` array supports the following pa For an application, use the **Object ID** of the app registration, not the Application (client) ID. For a service principal, use the Object ID of the enterprise application. -Maester checks the list before a run starts. A `Type` that is not one of the four values, or an entry without an `Id`, stops the run with a message that names the entry. A property name that is not listed above, such as `ObjectId`, is reported as a warning. +Maester checks the list before a run starts. A `Type` that is not one of the four values, or an entry without an `Id`, stops the run with a message that names the entry. A property name that is not listed above, such as `ObjectId`, is reported as a warning. An entry without a `Type`, or with an `Id` that is not a GUID (a user principal name, for example), passes that check and then makes the test fail with an error that names the entry. ## Configuration Examples @@ -91,7 +91,12 @@ Maester checks the list before a run starts. A `Type` that is not one of the fou Microsoft Graph returns `null` for an object that is not protected, so an unprotected object and an object that cannot be protected (such as a synchronized user) both appear as not protected. -The result lists at most 25 objects in each table and gives the total when there are more. Each table shows the object type, object ID, display name, and whether the object is active or soft deleted. A failed result also lists the objects that have protection but are not in the configuration, so you can see both gaps at once. +The result lists at most 25 objects in each table and gives the total when there are more. Every table shows the object type, object ID and display name, and one more column: + +- **Status** in the table of failing listed objects. It is `Not protected`, `Soft deleted` or `Not found`. This is the outcome of the check for that entry. +- **State** in the table of protected objects that are not in the configuration, which is also the table you get when nothing is listed. It is `Active` or `Soft deleted`, and `Active or soft deleted` when the two reads of the run disagree about an object, for example because it was deleted between them. The result does not say which read is newer. + +A failed result also lists the protected objects that are not in the configuration, so you can see both gaps at once. ## Which Objects to Protect @@ -138,7 +143,7 @@ Maester does not enable protection. Use the Microsoft Entra admin center or Micr ### Microsoft Graph -Set `isHardDeleteProtectionEnabled` to `true` on the object with the Microsoft Graph beta endpoint. The calling app or user needs the `HardDeletionSetting.ReadWrite.Enable` permission and the Global Administrator or Backup Administrator role. +Set `isHardDeleteProtectionEnabled` to `true` on the object with the Microsoft Graph beta endpoint. The calling app or user needs the `HardDeletionSetting.ReadWrite.Enable` permission, and the caller must have the Microsoft Entra Backup Administrator role. ```powershell Connect-MgGraph -Scopes 'HardDeletionSetting.ReadWrite.Enable' From ba5cb4e100ff1f1084c383dae300b9c3707c2d08 Mon Sep 17 00:00:00 2001 From: agnivesh <320655+agnivesh@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:51:20 +0000 Subject: [PATCH 07/11] fix(entra): stop the MT.1276 inventory read on a Graph error Pass -ErrorAction Stop to the protected-object reads, as the status helper does, so the helper does not depend on how Invoke-MtGraphRequest reports an error. Make the GUID casing test case-sensitive on the result row and on the requested URI, so it fails if the helper sends or returns an upper-case GUID. --- .../maester/entra/Get-MtEntraHardDeletionProtectedObject.ps1 | 3 ++- .../functions/Test-MtEntraHardDeletionProtection.Tests.ps1 | 5 ++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionProtectedObject.ps1 b/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionProtectedObject.ps1 index 7525c2fed3..a8e897e2a2 100644 --- a/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionProtectedObject.ps1 +++ b/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionProtectedObject.ps1 @@ -36,7 +36,8 @@ $Path = if ($State -eq 'Active') { $Source.Path } else { $Source.Deleted } $Objects = @( Invoke-MtGraphRequest -ApiVersion 'beta' -RelativeUri $Path ` - -Filter 'isHardDeleteProtectionEnabled eq true' -Select @('id', 'displayName') + -Filter 'isHardDeleteProtectionEnabled eq true' -Select @('id', 'displayName') ` + -ErrorAction Stop ) foreach ($Object in $Objects) { $Observed.Add([pscustomobject]@{ diff --git a/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 b/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 index 7fb76c341d..02c5888f59 100644 --- a/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 +++ b/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 @@ -189,7 +189,10 @@ } Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeFalse - $State.Detail | Should -Match 'User \| aaaaaaaa-1111-2222-3333-bbbbbbbbbbbb \| Mixed case \| Not protected' + $State.Detail | Should -MatchExactly 'User \| aaaaaaaa-1111-2222-3333-bbbbbbbbbbbb \| Mixed case \| Not protected' + Should -Invoke -ModuleName Maester Invoke-MtGraphRequest -Times 1 -Exactly -ParameterFilter { + $RelativeUri -ceq 'users/aaaaaaaa-1111-2222-3333-bbbbbbbbbbbb' + } } It 'keeps a protected object in the unlisted table when its Id is listed under another Type' { From f2a3b8b1c41ac7e82b3e1f88aa0f61173aad4159 Mon Sep 17 00:00:00 2001 From: agnivesh <320655+agnivesh@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:25:55 +0000 Subject: [PATCH 08/11] fix(entra): polish the MT.1276 messages, remediation and example Keep a display name with line breaks in one table cell, count an entry that is listed more than once as one object, and say that the scan did not find protected objects instead of claiming that none exist. Give recovery steps for soft-deleted and missing objects, describe the T1531 benefit as recovery, and use Invoke-Maester in the example. Test the invalid-Id check at the helper boundary, where no Graph call is possible, and show an empty list in the basic docs example. --- .../entra/Format-MtEntraHardDeletionTable.ps1 | 3 +- ...st-MtEntraHardDeletionProtection.Tests.ps1 | 43 ++++++++++++++++--- tests/maester/entra/Test.MT.1276.md | 15 ++++++- tests/maester/entra/Test.MT.1276.ps1 | 14 +++--- .../configuration/hard-deletion-protection.md | 6 +-- 5 files changed, 65 insertions(+), 16 deletions(-) diff --git a/powershell/internal/checks/maester/entra/Format-MtEntraHardDeletionTable.ps1 b/powershell/internal/checks/maester/entra/Format-MtEntraHardDeletionTable.ps1 index 9b874eea10..a73e752bce 100644 --- a/powershell/internal/checks/maester/entra/Format-MtEntraHardDeletionTable.ps1 +++ b/powershell/internal/checks/maester/entra/Format-MtEntraHardDeletionTable.ps1 @@ -42,7 +42,8 @@ $Table = "| Type | Object ID | Display name | $StateHeading |`n| --- | --- | --- | --- |" foreach ($Row in @($InputObject | Select-Object -First $Limit)) { - $DisplayName = [System.Net.WebUtility]::HtmlEncode([string]$Row.DisplayName) -replace '\|', '|' + $DisplayName = [string]$Row.DisplayName -replace '\r\n|\r|\n', ' ' + $DisplayName = [System.Net.WebUtility]::HtmlEncode($DisplayName) -replace '\|', '|' $Table += "`n| $($Row.Type) | $($Row.Id) | $DisplayName | $($Row.$StateProperty) |" } if (@($InputObject).Count -gt $Limit) { diff --git a/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 b/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 index 02c5888f59..a5d623d5b9 100644 --- a/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 +++ b/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 @@ -53,7 +53,7 @@ Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeNullOrEmpty $State.Investigate | Should -BeTrue $State.Detail | Should -Match 'verified manually' - $State.Detail | Should -Match 'No object in Microsoft Entra has Hard Deletion Protection yet' + $State.Detail | Should -Match 'The scan did not find any objects with Hard Deletion Protection' } It 'is Investigate and lists the protected objects it finds' { @@ -172,14 +172,47 @@ $State.Detail | Should -Match 'Group \| 22222222-2222-2222-2222-222222222222 \| \| Not found' } - It 'rejects an Id that is not a GUID before it calls Graph' { + It 'rejects an Id that is not a GUID without calling Graph' { + InModuleScope Maester { + $Entry = [pscustomobject]@{ Type = 'User'; Id = 'admin@contoso.com' } + { Get-MtEntraHardDeletionObjectStatus -Configured $Entry } | + Should -Throw '*Id must be the object ID (a GUID)*' + } + Should -Invoke -ModuleName Maester Invoke-MtGraphRequest -Times 0 -Exactly + } + + It 'fails the check with an error that names the entry when an Id is not a GUID' { $State.Listed = @([pscustomobject]@{ Type = 'User'; Id = 'admin@contoso.com' }) { Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed } | - Should -Throw '*Id must be the object ID (a GUID)*' - Should -Invoke -ModuleName Maester Invoke-MtGraphRequest -Times 0 -Exactly -ParameterFilter { - $RelativeUri -like 'users/*' + Should -Throw "*Id 'admin@contoso.com'*" + } + + It 'keeps a display name with line breaks in one table cell' { + $State.Listed = @([pscustomobject]@{ Type = 'User'; Id = $script:UserId }) + $State.ObjectById[$script:UserId] = [pscustomobject]@{ + id = $script:UserId; displayName = "Ops`r`nTeam`nLead"; isHardDeleteProtectionEnabled = $null + } + + Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeFalse + $State.Detail | Should -Match 'User \| 11111111-1111-1111-1111-111111111111 \| Ops Team Lead \| Not protected' + } + + It 'counts an entry that is listed more than once as one object' { + $State.Listed = @( + [pscustomobject]@{ Type = 'User'; Id = $script:UserId } + [pscustomobject]@{ Type = 'user'; Id = $script:UserId.ToUpperInvariant() } + [pscustomobject]@{ Type = 'User'; Id = "{$($script:UserId)}" } + [pscustomobject]@{ Type = 'Group'; Id = $script:GroupId } + ) + $State.ObjectById[$script:UserId] = [pscustomobject]@{ + id = $script:UserId; displayName = 'Plain user'; isHardDeleteProtectionEnabled = $null } + + Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeFalse + $State.Detail | Should -Match '2 of 2 listed object\(s\)' + [regex]::Matches($State.Detail, '\| User \|').Count | Should -Be 1 + $State.Detail | Should -Match 'Group \| 22222222-2222-2222-2222-222222222222 \| \| Not found' } It 'uses the canonical lower-case form of the Id in the request and in the result' { diff --git a/tests/maester/entra/Test.MT.1276.md b/tests/maester/entra/Test.MT.1276.md index 832dc99589..3ba65e144b 100644 --- a/tests/maester/entra/Test.MT.1276.md +++ b/tests/maester/entra/Test.MT.1276.md @@ -7,20 +7,31 @@ fails the test. If nothing is listed, or every listed object is protected but ot have protection and are not listed, the result is **Investigate**: check whether the list is complete. Protection limits destructive deletion by a compromised administrator. A protected object stays recoverable for -seven days after it is soft deleted, so an attacker cannot permanently destroy accounts or remove access -(MITRE T1485 Data Destruction and T1531 Account Access Removal) before someone notices. +seven days after it is soft deleted, so an attacker cannot permanently destroy it before someone notices +(MITRE T1485 Data Destruction). Soft deletion still removes access, so for T1531 Account Access Removal the +benefit is recovery: the object can be restored while protection holds. See [Hard Deletion Protection](https://maester.dev/docs/configuration/hard-deletion-protection) for the configuration format and for suggestions on which objects to list. #### Remediation action: +For an object with the status **Not protected**: + 1. Sign in to the [Microsoft Entra admin center](https://entra.microsoft.com) as at least a **Microsoft Entra Backup Administrator**. 2. Browse to **Backup and recovery** > **Hard deletion protection**. 3. Select **Add protection** and choose one object type. 4. Select the reported objects (up to 20 per operation) and review the permanent-protection warning. 5. Select **Save**. +For an object with the status **Soft deleted**: protection can only be enabled on an active object. Restore the +object from the deleted items in the Microsoft Entra admin center first. A restored object keeps protection if it +already had it. If it did not, follow the steps above. + +For an object with the status **Not found**: check the `Type` and `Id` in the Maester config. The `Id` is the object +ID, not the application (client) ID or a user principal name. If the object was permanently deleted, remove it from +the config. + Protection is permanent and cannot be removed once enabled. #### Related links diff --git a/tests/maester/entra/Test.MT.1276.ps1 b/tests/maester/entra/Test.MT.1276.ps1 index 7cb8439eda..814ca2f43f 100644 --- a/tests/maester/entra/Test.MT.1276.ps1 +++ b/tests/maester/entra/Test.MT.1276.ps1 @@ -15,7 +15,7 @@ Hard Deletion Protection is in preview and the property is only available in Microsoft Graph beta. .EXAMPLE - Test-MtEntraHardDeletionProtection + Invoke-Maester -TestId MT.1276 -IncludePreview .LINK https://maester.dev/docs/tests/MT.1276 @@ -54,7 +54,7 @@ "Add the ones that matter to the config so this test can check them:`n`n" $Result += Format-MtEntraHardDeletionTable -InputObject $Protected -StateProperty State -StateHeading State } else { - $Result += 'No object in Microsoft Entra has Hard Deletion Protection yet. Add the critical users, ' + + $Result += 'The scan did not find any objects with Hard Deletion Protection. Add the critical users, ' + 'groups, applications and service principals to protect to GlobalSettings.' + 'HardDeletionProtectedObjects, then enable protection on them. See ' + 'https://maester.dev/docs/configuration/hard-deletion-protection for the format.' @@ -63,13 +63,17 @@ return $null } + $ListedKeys = @{} $Rows = @( foreach ($Configured in $ConfiguredObjects) { - Get-MtEntraHardDeletionObjectStatus -Configured $Configured + $Row = Get-MtEntraHardDeletionObjectStatus -Configured $Configured + $Key = "$($Row.Type)|$($Row.Id)" + if (-not $ListedKeys.ContainsKey($Key)) { + $ListedKeys[$Key] = $true + $Row + } } ) - $ListedKeys = @{} - foreach ($Row in $Rows) { $ListedKeys["$($Row.Type)|$($Row.Id)"] = $true } $Unlisted = @($Protected | Where-Object { -not $ListedKeys.ContainsKey("$($_.Type)|$($_.Id)") }) $UnlistedTable = if ($Unlisted.Count -gt 0) { "`n`n$($Unlisted.Count) other object(s) have Hard Deletion Protection in Microsoft Entra but are not " + diff --git a/website/docs/configuration/hard-deletion-protection.md b/website/docs/configuration/hard-deletion-protection.md index e30d1db8a4..fed48ab7e6 100644 --- a/website/docs/configuration/hard-deletion-protection.md +++ b/website/docs/configuration/hard-deletion-protection.md @@ -43,13 +43,13 @@ Hard Deletion Protection objects are configured in the `GlobalSettings` section ```json { "GlobalSettings": { - "HardDeletionProtectedObjects": [ - // The critical objects that must be protected - ] + "HardDeletionProtectedObjects": [] } } ``` +An empty list is the default. Add one entry per critical object, as in the examples below. + ### Supported Parameters Each entry in the `HardDeletionProtectedObjects` array supports the following parameters: From 9f76ca35cd39fa8ab3bd7238e407a00199638427 Mon Sep 17 00:00:00 2001 From: agnivesh <320655+agnivesh@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:49:24 +0000 Subject: [PATCH 09/11] fix(entra): escape display names and use the documented deleted-item route Show a tenant display name through Get-MtSafeMarkdown, so a name that looks like a link or an image is plain text in the report. Read a soft-deleted object through GET directory/deletedItems/{id}, the documented single-item route, and check its @odata.type against the configured type. An object of another type is reported as not found. Limit the setup text to objects that support Hard Deletion Protection, add restore steps for service principals (Graph only), and use a GUID with hex letters in the deduplication test. --- .../entra/Format-MtEntraHardDeletionTable.ps1 | 6 +- .../Get-MtEntraHardDeletionObjectStatus.ps1 | 16 +++-- ...st-MtEntraHardDeletionProtection.Tests.ps1 | 63 ++++++++++++++----- tests/maester/entra/Test.MT.1276.md | 13 +++- tests/maester/entra/Test.MT.1276.ps1 | 8 +-- 5 files changed, 76 insertions(+), 30 deletions(-) diff --git a/powershell/internal/checks/maester/entra/Format-MtEntraHardDeletionTable.ps1 b/powershell/internal/checks/maester/entra/Format-MtEntraHardDeletionTable.ps1 index a73e752bce..01ccfd155f 100644 --- a/powershell/internal/checks/maester/entra/Format-MtEntraHardDeletionTable.ps1 +++ b/powershell/internal/checks/maester/entra/Format-MtEntraHardDeletionTable.ps1 @@ -5,7 +5,8 @@ .DESCRIPTION Builds a table with the columns Type, Object ID, Display name and one more column taken from the - StateProperty. When there are more rows than Limit, the table shows the first Limit rows and a line + StateProperty. The display name comes from the tenant, so it goes through Get-MtSafeMarkdown: a name that + looks like a link or an image is shown as text, and a pipe or a line break does not break the row. When there are more rows than Limit, the table shows the first Limit rows and a line gives the total. .PARAMETER InputObject @@ -42,8 +43,7 @@ $Table = "| Type | Object ID | Display name | $StateHeading |`n| --- | --- | --- | --- |" foreach ($Row in @($InputObject | Select-Object -First $Limit)) { - $DisplayName = [string]$Row.DisplayName -replace '\r\n|\r|\n', ' ' - $DisplayName = [System.Net.WebUtility]::HtmlEncode($DisplayName) -replace '\|', '|' + $DisplayName = Get-MtSafeMarkdown -Text ([string]$Row.DisplayName) $Table += "`n| $($Row.Type) | $($Row.Id) | $DisplayName | $($Row.$StateProperty) |" } if (@($InputObject).Count -gt $Limit) { diff --git a/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionObjectStatus.ps1 b/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionObjectStatus.ps1 index c65ac01d46..41c788ca8d 100644 --- a/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionObjectStatus.ps1 +++ b/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionObjectStatus.ps1 @@ -5,9 +5,10 @@ .DESCRIPTION Reads the object from Microsoft Graph beta. Status is 'Protected', 'Not protected', 'Soft deleted' or - 'Not found'. When the active lookup returns HTTP 404, the function looks for the object among the deleted - items of the same type. It reports 'Soft deleted' when it finds the object there, whether or not the object - has protection, and 'Not found' when neither lookup finds it. Any Graph error other than a 404 is thrown. + 'Not found'. When the active lookup returns HTTP 404, the function reads the object through the documented + single-item route, directory/deletedItems/{id}, and checks that it has the configured type. It reports + 'Soft deleted' when it finds the object there, whether or not the object has protection. An object of another + type, or none, gives 'Not found'. Any Graph error other than a 404 is thrown. The Id must be the object ID, a GUID. The function uses its canonical lower-case form in both requests and in the result, so the result matches the objects that Get-MtEntraHardDeletionProtectedObject returns. @@ -55,10 +56,13 @@ if (!$Object) { try { - $Object = Invoke-MtGraphRequest -ApiVersion 'beta' ` - -RelativeUri "directory/deletedItems/microsoft.graph.$($Endpoint.GraphType)/$Id" ` + $Deleted = Invoke-MtGraphRequest -ApiVersion 'beta' -RelativeUri "directory/deletedItems/$Id" ` -Select @('id', 'displayName') -ErrorAction Stop - $Status = 'Soft deleted' + $DeletedType = [string]$Deleted.'@odata.type' + if (!$DeletedType -or $DeletedType -eq "#microsoft.graph.$($Endpoint.GraphType)") { + $Object = $Deleted + $Status = 'Soft deleted' + } } catch { if (!(Test-MtGraphNotFoundError -ErrorRecord $_)) { throw } } diff --git a/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 b/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 index a5d623d5b9..42bbed7b8f 100644 --- a/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 +++ b/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 @@ -26,7 +26,7 @@ }.GetNewClosure() Mock -ModuleName Maester Invoke-MtGraphRequest -MockWith { param($RelativeUri) - if ($RelativeUri -match '^directory/deletedItems/microsoft\.graph\.[A-Za-z]+/[^/]+$') { + if ($RelativeUri -match '^directory/deletedItems/[0-9a-fA-F-]{36}$') { $deleted = $State.DeletedById[$RelativeUri.Split('/')[-1]] if ($null -eq $deleted) { throw $(if ($State.Wrap) { [System.InvalidOperationException]::new('Request failed.', $NotFoundError) } else { $NotFoundError }) } return $deleted @@ -120,7 +120,7 @@ Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeFalse $State.Investigate | Should -BeFalse $State.Detail | Should -Match '1 of 1 listed object' - $State.Detail | Should -Match 'User \| 11111111-1111-1111-1111-111111111111 \| Plain | User \| Not protected' + $State.Detail | Should -Match 'User \| 11111111-1111-1111-1111-111111111111 \| Plain \\\| User \| Not protected' $State.Detail | Should -Match 'Some group' } @@ -133,7 +133,9 @@ It 'fails a listed object that is protected but soft deleted' { $State.Listed = @([pscustomobject]@{ Type = 'Group'; Id = $script:GroupId }) - $State.DeletedById[$script:GroupId] = [pscustomobject]@{ id = $script:GroupId; displayName = 'Deleted group' } + $State.DeletedById[$script:GroupId] = [pscustomobject]@{ + id = $script:GroupId; displayName = 'Deleted group'; '@odata.type' = '#microsoft.graph.group' + } $State.Protected['directory/deletedItems/microsoft.graph.group'] = @( [pscustomobject]@{ id = $script:GroupId; displayName = 'Deleted group' } ) @@ -144,24 +146,55 @@ It 'reports a listed object that was soft deleted without protection as soft deleted, not as not found' { $State.Listed = @([pscustomobject]@{ Type = 'User'; Id = $script:UserId }) - $State.DeletedById[$script:UserId] = [pscustomobject]@{ id = $script:UserId; displayName = 'Removed user' } + $State.DeletedById[$script:UserId] = [pscustomobject]@{ + id = $script:UserId; displayName = 'Removed user'; '@odata.type' = '#microsoft.graph.user' + } Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeFalse $State.Detail | Should -Match 'User \| 11111111-1111-1111-1111-111111111111 \| Removed user \| Soft deleted' $State.Detail | Should -Not -Match 'Not found' } - It 'looks for a deleted object only among the deleted items of the listed type' { + It 'reads a deleted object through the documented deletedItems route, once' { $State.Listed = @([pscustomobject]@{ Type = 'Group'; Id = $script:GroupId }) Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeFalse Should -Invoke -ModuleName Maester Invoke-MtGraphRequest -Times 1 -Exactly -ParameterFilter { - $RelativeUri -eq 'directory/deletedItems/microsoft.graph.group/22222222-2222-2222-2222-222222222222' + $RelativeUri -eq 'directory/deletedItems/22222222-2222-2222-2222-222222222222' } Should -Invoke -ModuleName Maester Invoke-MtGraphRequest -Times 0 -Exactly -ParameterFilter { - $RelativeUri -like 'directory/deletedItems/microsoft.graph.*/22222222-2222-2222-2222-222222222222' -and - $RelativeUri -notlike 'directory/deletedItems/microsoft.graph.group/*' + $RelativeUri -like 'directory/deletedItems/microsoft.graph.*/22222222-2222-2222-2222-222222222222' + } + } + + It 'reports a deleted object of another type as not found' { + $State.Listed = @([pscustomobject]@{ Type = 'Group'; Id = $script:UserId }) + $State.DeletedById[$script:UserId] = [pscustomobject]@{ + id = $script:UserId; displayName = 'Removed user'; '@odata.type' = '#microsoft.graph.user' + } + + Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeFalse + $State.Detail | Should -Match 'Group \| 11111111-1111-1111-1111-111111111111 \| \| Not found' + $State.Detail | Should -Not -Match 'Soft deleted' + } + + It 'shows a display name that looks like a link or an image as plain text' { + $State.Listed = @( + [pscustomobject]@{ Type = 'User'; Id = $script:UserId } + [pscustomobject]@{ Type = 'Group'; Id = $script:GroupId } + ) + $State.ObjectById[$script:UserId] = [pscustomobject]@{ + id = $script:UserId; displayName = '[Sign in](https://phish.example)'; isHardDeleteProtectionEnabled = $null } + $State.ObjectById[$script:GroupId] = [pscustomobject]@{ + id = $script:GroupId; displayName = '![x](https://attacker.example/p.png)'; isHardDeleteProtectionEnabled = $null + } + + Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeFalse + $State.Detail.Contains('\[Sign in\]\(https\://phish.example\)') | Should -BeTrue + $State.Detail.Contains('\!\[x\]\(https\://attacker.example/p.png\)') | Should -BeTrue + $State.Detail.Contains('[Sign in](') | Should -BeFalse + $State.Detail.Contains('![x](') | Should -BeFalse } It 'reports a 404 that sits on the inner exception as not found' { @@ -199,19 +232,21 @@ } It 'counts an entry that is listed more than once as one object' { + $HexId = 'aabbccdd-1111-2222-3333-eeeeffff0000' $State.Listed = @( - [pscustomobject]@{ Type = 'User'; Id = $script:UserId } - [pscustomobject]@{ Type = 'user'; Id = $script:UserId.ToUpperInvariant() } - [pscustomobject]@{ Type = 'User'; Id = "{$($script:UserId)}" } + [pscustomobject]@{ Type = 'User'; Id = $HexId } + [pscustomobject]@{ Type = 'user'; Id = $HexId.ToUpperInvariant() } + [pscustomobject]@{ Type = 'User'; Id = "{$HexId}" } [pscustomobject]@{ Type = 'Group'; Id = $script:GroupId } ) - $State.ObjectById[$script:UserId] = [pscustomobject]@{ - id = $script:UserId; displayName = 'Plain user'; isHardDeleteProtectionEnabled = $null + $State.ObjectById[$HexId] = [pscustomobject]@{ + id = $HexId; displayName = 'Plain user'; isHardDeleteProtectionEnabled = $null } + $HexId | Should -Not -BeExactly $HexId.ToUpperInvariant() Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeFalse $State.Detail | Should -Match '2 of 2 listed object\(s\)' - [regex]::Matches($State.Detail, '\| User \|').Count | Should -Be 1 + [regex]::Matches($State.Detail, '\| User \| aabbccdd-1111-2222-3333-eeeeffff0000 \|').Count | Should -Be 1 $State.Detail | Should -Match 'Group \| 22222222-2222-2222-2222-222222222222 \| \| Not found' } diff --git a/tests/maester/entra/Test.MT.1276.md b/tests/maester/entra/Test.MT.1276.md index 3ba65e144b..2d532dd16e 100644 --- a/tests/maester/entra/Test.MT.1276.md +++ b/tests/maester/entra/Test.MT.1276.md @@ -24,9 +24,15 @@ For an object with the status **Not protected**: 4. Select the reported objects (up to 20 per operation) and review the permanent-protection warning. 5. Select **Save**. -For an object with the status **Soft deleted**: protection can only be enabled on an active object. Restore the -object from the deleted items in the Microsoft Entra admin center first. A restored object keeps protection if it -already had it. If it did not, follow the steps above. +For an object with the status **Soft deleted**: protection can only be enabled on an active object, so restore the +object first. A restored object keeps protection if it already had it. If it did not, follow the steps above. + +* A user or a group: restore it from **Deleted users** or **Deleted groups** in the Microsoft Entra admin center. +* An application: restore it from **App registrations** > **Deleted applications**. +* A service principal: the admin center does not show deleted service principals. Restore it with Microsoft Graph, + `POST https://graph.microsoft.com/v1.0/directory/deletedItems/{id}/restore`, or with + `Restore-MgDirectoryDeletedItem -DirectoryObjectId `, as at least an Application Administrator or Cloud + Application Administrator. Customers cannot restore a deleted managed identity. For an object with the status **Not found**: check the `Type` and `Id` in the Maester config. The `Id` is the object ID, not the application (client) ID or a user principal name. If the object was permanently deleted, remove it from @@ -37,6 +43,7 @@ Protection is permanent and cannot be removed once enabled. #### Related links * [Configure Hard Deletion Protection in Microsoft Entra (preview)](https://learn.microsoft.com/entra/backup/configure-hard-deletion-protection) +* [Restore a soft deleted enterprise application](https://learn.microsoft.com/entra/identity/enterprise-apps/restore-application) %TestResult% diff --git a/tests/maester/entra/Test.MT.1276.ps1 b/tests/maester/entra/Test.MT.1276.ps1 index 814ca2f43f..429f355c8d 100644 --- a/tests/maester/entra/Test.MT.1276.ps1 +++ b/tests/maester/entra/Test.MT.1276.ps1 @@ -54,10 +54,10 @@ "Add the ones that matter to the config so this test can check them:`n`n" $Result += Format-MtEntraHardDeletionTable -InputObject $Protected -StateProperty State -StateHeading State } else { - $Result += 'The scan did not find any objects with Hard Deletion Protection. Add the critical users, ' + - 'groups, applications and service principals to protect to GlobalSettings.' + - 'HardDeletionProtectedObjects, then enable protection on them. See ' + - 'https://maester.dev/docs/configuration/hard-deletion-protection for the format.' + $Result += 'The scan did not find any objects with Hard Deletion Protection. Add the critical objects that support ' + + 'it to GlobalSettings.HardDeletionProtectedObjects, then enable protection on them. See ' + + 'https://maester.dev/docs/configuration/hard-deletion-protection for the format and for ' + + 'the objects that support it.' } Add-MtTestResultDetail -Investigate -Result $Result return $null From 369e32f6c2369319e4f84a7b84494371f56a3cf9 Mon Sep 17 00:00:00 2001 From: agnivesh <320655+agnivesh@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:34:03 +0000 Subject: [PATCH 10/11] fix(entra): fail closed on a deleted item without a type and tighten the text Treat a deleted-item response without an @odata.type as not found, so an object of another type cannot show as soft deleted. A user, a group, an application and a service principal all return the type on the documented route. When an entry is listed twice and the lookups differ, keep the failure. Say that the scan for protected objects is not a snapshot, give the exact protection window, check that an object can be protected before sending the admin to Add protection, and note the permission and the application registration case when restoring a service principal. Soft deleting an object that was protected by mistake is only for retiring it. Wrap the lines of the check, its helpers and its tests to 100 characters, and name the third argument of the test helpers. --- .../entra/Format-MtEntraHardDeletionTable.ps1 | 11 +- .../Get-MtEntraHardDeletionObjectStatus.ps1 | 46 ++- ...Get-MtEntraHardDeletionProtectedObject.ps1 | 29 +- ...st-MtEntraHardDeletionProtection.Tests.ps1 | 347 +++++++++++------- tests/maester/entra/Test.MT.1276.md | 19 +- tests/maester/entra/Test.MT.1276.ps1 | 95 ++--- .../configuration/hard-deletion-protection.md | 4 +- 7 files changed, 332 insertions(+), 219 deletions(-) diff --git a/powershell/internal/checks/maester/entra/Format-MtEntraHardDeletionTable.ps1 b/powershell/internal/checks/maester/entra/Format-MtEntraHardDeletionTable.ps1 index 01ccfd155f..79dc47d2ac 100644 --- a/powershell/internal/checks/maester/entra/Format-MtEntraHardDeletionTable.ps1 +++ b/powershell/internal/checks/maester/entra/Format-MtEntraHardDeletionTable.ps1 @@ -4,10 +4,13 @@ Formats Hard Deletion Protection objects as a Markdown table, capped at a number of rows. .DESCRIPTION - Builds a table with the columns Type, Object ID, Display name and one more column taken from the - StateProperty. The display name comes from the tenant, so it goes through Get-MtSafeMarkdown: a name that - looks like a link or an image is shown as text, and a pipe or a line break does not break the row. When there are more rows than Limit, the table shows the first Limit rows and a line - gives the total. + Builds a table with the columns Type, Object ID, Display name and one more column taken from + the StateProperty. The display name comes from the tenant, so it goes through + Get-MtSafeMarkdown: a name that looks like a link or an image is shown as text, and a pipe or + a line break does not break the row. + + When there are more rows than Limit, the table shows the first Limit rows and a line gives + the total. .PARAMETER InputObject The objects to list. Each has Type, Id and DisplayName. diff --git a/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionObjectStatus.ps1 b/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionObjectStatus.ps1 index 41c788ca8d..73981922fc 100644 --- a/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionObjectStatus.ps1 +++ b/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionObjectStatus.ps1 @@ -4,14 +4,18 @@ Returns the Hard Deletion Protection status of one object listed in the Maester config. .DESCRIPTION - Reads the object from Microsoft Graph beta. Status is 'Protected', 'Not protected', 'Soft deleted' or - 'Not found'. When the active lookup returns HTTP 404, the function reads the object through the documented - single-item route, directory/deletedItems/{id}, and checks that it has the configured type. It reports - 'Soft deleted' when it finds the object there, whether or not the object has protection. An object of another - type, or none, gives 'Not found'. Any Graph error other than a 404 is thrown. + Reads the object from Microsoft Graph beta. Status is 'Protected', 'Not protected', + 'Soft deleted' or 'Not found'. - The Id must be the object ID, a GUID. The function uses its canonical lower-case form in both requests and - in the result, so the result matches the objects that Get-MtEntraHardDeletionProtectedObject returns. + When the active lookup returns HTTP 404, the function reads the object through the + documented single-item route, directory/deletedItems/{id}, and checks that its @odata.type is + the configured type. It reports 'Soft deleted' when it finds the object there, whether or not + the object has protection. An object of another type, a response without an @odata.type, or + no object gives 'Not found'. Any Graph error other than a 404 is thrown. + + The Id must be the object ID, a GUID. The function uses its canonical lower-case form in both + requests and in the result, so the result matches the objects that + Get-MtEntraHardDeletionProtectedObject returns. .PARAMETER Configured A HardDeletionProtectedObjects entry with Type and Id. @@ -29,16 +33,22 @@ $EndpointByType = @{ user = @{ Name = 'User'; Path = 'users'; GraphType = 'user' } group = @{ Name = 'Group'; Path = 'groups'; GraphType = 'group' } - application = @{ Name = 'Application'; Path = 'applications'; GraphType = 'application' } - serviceprincipal = @{ Name = 'ServicePrincipal'; Path = 'servicePrincipals'; GraphType = 'servicePrincipal' } + application = @{ + Name = 'Application'; Path = 'applications'; GraphType = 'application' + } + serviceprincipal = @{ + Name = 'ServicePrincipal'; Path = 'servicePrincipals'; GraphType = 'servicePrincipal' + } } $Type = ([string]$Configured.Type).ToLowerInvariant() $ParsedId = [guid]::Empty - if (!$EndpointByType.ContainsKey($Type) -or ![guid]::TryParse([string]$Configured.Id, [ref]$ParsedId)) { + $IdIsGuid = [guid]::TryParse([string]$Configured.Id, [ref]$ParsedId) + if (!$EndpointByType.ContainsKey($Type) -or !$IdIsGuid) { throw ( - "Invalid HardDeletionProtectedObjects entry (Type '$($Configured.Type)', Id '$($Configured.Id)'). " + - 'Type must be User, Group, Application or ServicePrincipal and Id must be the object ID (a GUID).' + "Invalid HardDeletionProtectedObjects entry (Type '$($Configured.Type)', " + + "Id '$($Configured.Id)'). Type must be User, Group, Application or " + + 'ServicePrincipal and Id must be the object ID (a GUID).' ) } $Endpoint = $EndpointByType[$Type] @@ -49,17 +59,21 @@ try { $Object = Invoke-MtGraphRequest -ApiVersion 'beta' -RelativeUri "$($Endpoint.Path)/$Id" ` -Select @('id', 'displayName', 'isHardDeleteProtectionEnabled') -ErrorAction Stop - $Status = if ($Object.isHardDeleteProtectionEnabled -eq $true) { 'Protected' } else { 'Not protected' } + $Status = if ($Object.isHardDeleteProtectionEnabled -eq $true) { + 'Protected' + } else { + 'Not protected' + } } catch { if (!(Test-MtGraphNotFoundError -ErrorRecord $_)) { throw } } if (!$Object) { try { - $Deleted = Invoke-MtGraphRequest -ApiVersion 'beta' -RelativeUri "directory/deletedItems/$Id" ` + $Deleted = Invoke-MtGraphRequest -ApiVersion 'beta' ` + -RelativeUri "directory/deletedItems/$Id" ` -Select @('id', 'displayName') -ErrorAction Stop - $DeletedType = [string]$Deleted.'@odata.type' - if (!$DeletedType -or $DeletedType -eq "#microsoft.graph.$($Endpoint.GraphType)") { + if ([string]$Deleted.'@odata.type' -eq "#microsoft.graph.$($Endpoint.GraphType)") { $Object = $Deleted $Status = 'Soft deleted' } diff --git a/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionProtectedObject.ps1 b/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionProtectedObject.ps1 index a8e897e2a2..fa8589f326 100644 --- a/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionProtectedObject.ps1 +++ b/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionProtectedObject.ps1 @@ -1,16 +1,18 @@ function Get-MtEntraHardDeletionProtectedObject { <# .SYNOPSIS - Returns the users, groups, applications and service principals that have Hard Deletion Protection. + Returns the users, groups, applications and service principals that have Hard Deletion + Protection. .DESCRIPTION - Queries Microsoft Graph beta for objects whose isHardDeleteProtectionEnabled property is true, both - among active objects and among soft-deleted ones. Each result has Type, Id, DisplayName and State - ('Active' or 'Soft deleted'). + Queries Microsoft Graph beta for objects whose isHardDeleteProtectionEnabled property is + true, both among active objects and among soft-deleted ones. Each result has Type, Id, + DisplayName and State ('Active' or 'Soft deleted'). - The two reads happen one after the other, so an object can show up in both when it is soft deleted or - restored between them. The function returns such an object once, with the State 'Active or soft deleted', - and does not claim that either read is newer. + The reads happen one after the other, so the scan is not a snapshot. An object that is soft + deleted or restored while it runs can show up in both reads, or in neither. The function + returns an object seen in both reads once, with the State 'Active or soft deleted', and does + not claim that either read is newer. An object seen in neither read is missed. .EXAMPLE Get-MtEntraHardDeletionProtectedObject @@ -19,14 +21,15 @@ [OutputType([pscustomobject])] param() + $DeletedRoot = 'directory/deletedItems/microsoft.graph' $Sources = @( - @{ Type = 'User'; Path = 'users'; Deleted = 'directory/deletedItems/microsoft.graph.user' } - @{ Type = 'Group'; Path = 'groups'; Deleted = 'directory/deletedItems/microsoft.graph.group' } - @{ Type = 'Application'; Path = 'applications'; Deleted = 'directory/deletedItems/microsoft.graph.application' } + @{ Type = 'User'; Path = 'users'; Deleted = "$DeletedRoot.user" } + @{ Type = 'Group'; Path = 'groups'; Deleted = "$DeletedRoot.group" } + @{ Type = 'Application'; Path = 'applications'; Deleted = "$DeletedRoot.application" } @{ Type = 'ServicePrincipal' Path = 'servicePrincipals' - Deleted = 'directory/deletedItems/microsoft.graph.servicePrincipal' + Deleted = "$DeletedRoot.servicePrincipal" } ) @@ -36,8 +39,8 @@ $Path = if ($State -eq 'Active') { $Source.Path } else { $Source.Deleted } $Objects = @( Invoke-MtGraphRequest -ApiVersion 'beta' -RelativeUri $Path ` - -Filter 'isHardDeleteProtectionEnabled eq true' -Select @('id', 'displayName') ` - -ErrorAction Stop + -Filter 'isHardDeleteProtectionEnabled eq true' ` + -Select @('id', 'displayName') -ErrorAction Stop ) foreach ($Object in $Objects) { $Observed.Add([pscustomobject]@{ diff --git a/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 b/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 index 42bbed7b8f..0aafb0e6d3 100644 --- a/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 +++ b/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 @@ -7,13 +7,42 @@ $script:UserId = '11111111-1111-1111-1111-111111111111' $script:GroupId = '22222222-2222-2222-2222-222222222222' + $script:UserRow = "User \| $($script:UserId) \|" + $script:GroupRow = "Group \| $($script:GroupId) \|" + + function Get-Entry { + param($Type, $Id) + [pscustomobject]@{ Type = $Type; Id = $Id } + } + + function Get-GraphObject { + param($Id, $Name, $Protected = $null) + [pscustomobject]@{ + id = $Id; displayName = $Name; isHardDeleteProtectionEnabled = $Protected + } + } + + function Get-InventoryObject { + param($Id, $Name) + [pscustomobject]@{ id = $Id; displayName = $Name } + } + + function Get-DeletedObject { + param($Id, $Name, $ODataType) + [pscustomobject]@{ id = $Id; displayName = $Name; '@odata.type' = $ODataType } + } + + function Invoke-Check { + Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed + } } BeforeEach { $State = @{ - Detail = $null; Investigate = $false; Listed = @(); Protected = @{}; ObjectById = @{}; DeletedById = @{}; Wrap = $false + Detail = $null; Investigate = $false; Listed = @(); Protected = @{} + ObjectById = @{}; DeletedById = @{}; Sequence = @{}; Seen = @{}; Wrap = $false } - # The exception Invoke-MtGraphRequest lets through for a single request that Graph answers with 404. + # The exception Invoke-MtGraphRequest lets through for a request Graph answers with 404. $NotFoundError = [Microsoft.PowerShell.Commands.HttpResponseException]::new( 'Response status code does not indicate success: NotFound (Not Found).', [System.Net.Http.HttpResponseMessage]::new([System.Net.HttpStatusCode]::NotFound) @@ -26,15 +55,26 @@ }.GetNewClosure() Mock -ModuleName Maester Invoke-MtGraphRequest -MockWith { param($RelativeUri) + $notFound = $NotFoundError + if ($State.Wrap) { + $notFound = [System.InvalidOperationException]::new( + 'Request failed.', $NotFoundError + ) + } + $id = $RelativeUri.Split('/')[-1] if ($RelativeUri -match '^directory/deletedItems/[0-9a-fA-F-]{36}$') { - $deleted = $State.DeletedById[$RelativeUri.Split('/')[-1]] - if ($null -eq $deleted) { throw $(if ($State.Wrap) { [System.InvalidOperationException]::new('Request failed.', $NotFoundError) } else { $NotFoundError }) } - return $deleted + if ($null -eq $State.DeletedById[$id]) { throw $notFound } + return $State.DeletedById[$id] } if ($RelativeUri -match '^(users|groups|applications|servicePrincipals)/[^/]+$') { - $object = $State.ObjectById[$RelativeUri.Split('/')[-1]] - if ($null -eq $object) { throw $(if ($State.Wrap) { [System.InvalidOperationException]::new('Request failed.', $NotFoundError) } else { $NotFoundError }) } - return $object + if ($State.Sequence.ContainsKey($id)) { + $step = [int]$State.Seen[$id] + $State.Seen[$id] = $step + 1 + $answers = $State.Sequence[$id] + return $answers[[Math]::Min($step, $answers.Count - 1)] + } + if ($null -eq $State.ObjectById[$id]) { throw $notFound } + return $State.ObjectById[$id] } $key = [string]$RelativeUri if ($State.Protected.Keys -contains $key) { return $State.Protected[$key] } @@ -50,32 +90,32 @@ Context 'No objects are listed' { It 'is Investigate and says nothing is protected yet' { - Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeNullOrEmpty + Invoke-Check | Should -BeNullOrEmpty $State.Investigate | Should -BeTrue $State.Detail | Should -Match 'verified manually' - $State.Detail | Should -Match 'The scan did not find any objects with Hard Deletion Protection' + $State.Detail | Should -Match 'The scan did not find any objects with Hard Deletion' } It 'is Investigate and lists the protected objects it finds' { - $State.Protected['users'] = @([pscustomobject]@{ id = $script:UserId; displayName = 'Admin One' }) + $State.Protected['users'] = @(Get-InventoryObject $script:UserId 'Admin One') $State.Protected['directory/deletedItems/microsoft.graph.group'] = @( - [pscustomobject]@{ id = $script:GroupId; displayName = 'Deleted group' } + Get-InventoryObject $script:GroupId 'Deleted group' ) - Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeNullOrEmpty + Invoke-Check | Should -BeNullOrEmpty $State.Investigate | Should -BeTrue $State.Detail | Should -Match '2 object\(s\) have Hard Deletion Protection' - $State.Detail | Should -Match "User \| $($script:UserId) \| Admin One \| Active" - $State.Detail | Should -Match "Group \| $($script:GroupId) \| Deleted group \| Soft deleted" + $State.Detail | Should -Match "$($script:UserRow) Admin One \| Active" + $State.Detail | Should -Match "$($script:GroupRow) Deleted group \| Soft deleted" } It 'counts an object once when it shows up as both active and soft deleted' { - $State.Protected['users'] = @([pscustomobject]@{ id = $script:UserId; displayName = 'Admin One' }) + $State.Protected['users'] = @(Get-InventoryObject $script:UserId 'Admin One') $State.Protected['directory/deletedItems/microsoft.graph.user'] = @( - [pscustomobject]@{ id = $script:UserId; displayName = 'Admin One' } + Get-InventoryObject $script:UserId 'Admin One' ) - Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeNullOrEmpty + Invoke-Check | Should -BeNullOrEmpty $State.Detail | Should -Match '1 object\(s\) have Hard Deletion Protection' $State.Detail | Should -Match 'Admin One \| Active or soft deleted' } @@ -83,114 +123,116 @@ Context 'Objects are listed' { It 'passes when every listed object is protected and nothing else is' { - $State.Listed = @([pscustomobject]@{ Type = 'User'; Id = $script:UserId }) - $State.ObjectById[$script:UserId] = [pscustomobject]@{ - id = $script:UserId; displayName = 'Admin One'; isHardDeleteProtectionEnabled = $true - } - $State.Protected['users'] = @([pscustomobject]@{ id = $script:UserId; displayName = 'Admin One' }) + $State.Listed = @(Get-Entry User $script:UserId) + $State.ObjectById[$script:UserId] = + Get-GraphObject $script:UserId 'Admin One' -Protected $true + $State.Protected['users'] = @(Get-InventoryObject $script:UserId 'Admin One') - Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeTrue + Invoke-Check | Should -BeTrue $State.Investigate | Should -BeFalse $State.Detail | Should -Match 'Well done' } It 'is Investigate when listed objects pass but other protected objects are not listed' { - $State.Listed = @([pscustomobject]@{ Type = 'User'; Id = $script:UserId }) - $State.ObjectById[$script:UserId] = [pscustomobject]@{ - id = $script:UserId; displayName = 'Admin One'; isHardDeleteProtectionEnabled = $true - } + $State.Listed = @(Get-Entry User $script:UserId) + $State.ObjectById[$script:UserId] = + Get-GraphObject $script:UserId 'Admin One' -Protected $true $State.Protected['users'] = @( - [pscustomobject]@{ id = $script:UserId; displayName = 'Admin One' } - [pscustomobject]@{ id = $script:GroupId; displayName = 'Other admin' } + Get-InventoryObject $script:UserId 'Admin One' + Get-InventoryObject $script:GroupId 'Other admin' ) - Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeNullOrEmpty + Invoke-Check | Should -BeNullOrEmpty $State.Investigate | Should -BeTrue $State.Detail | Should -Match 'Other admin' $State.Detail | Should -Not -Match 'Admin One \|' } - It 'fails and lists an unprotected object, even when other protected objects are not listed' { - $State.Listed = @([pscustomobject]@{ Type = 'user'; Id = $script:UserId }) - $State.ObjectById[$script:UserId] = [pscustomobject]@{ - id = $script:UserId; displayName = 'Plain | User'; isHardDeleteProtectionEnabled = $null - } - $State.Protected['groups'] = @([pscustomobject]@{ id = $script:GroupId; displayName = 'Some group' }) + It 'fails and lists an unprotected object, even when others are not listed' { + $State.Listed = @(Get-Entry user $script:UserId) + $State.ObjectById[$script:UserId] = Get-GraphObject $script:UserId 'Plain | User' + $State.Protected['groups'] = @(Get-InventoryObject $script:GroupId 'Some group') - Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeFalse + Invoke-Check | Should -BeFalse $State.Investigate | Should -BeFalse $State.Detail | Should -Match '1 of 1 listed object' - $State.Detail | Should -Match 'User \| 11111111-1111-1111-1111-111111111111 \| Plain \\\| User \| Not protected' + $State.Detail | Should -Match "$($script:UserRow) Plain \\\| User \| Not protected" $State.Detail | Should -Match 'Some group' } It 'fails an object that cannot be found' { - $State.Listed = @([pscustomobject]@{ Type = 'Group'; Id = $script:GroupId }) + $State.Listed = @(Get-Entry Group $script:GroupId) - Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeFalse + Invoke-Check | Should -BeFalse $State.Detail | Should -Match 'Not found' } It 'fails a listed object that is protected but soft deleted' { - $State.Listed = @([pscustomobject]@{ Type = 'Group'; Id = $script:GroupId }) - $State.DeletedById[$script:GroupId] = [pscustomobject]@{ - id = $script:GroupId; displayName = 'Deleted group'; '@odata.type' = '#microsoft.graph.group' - } + $State.Listed = @(Get-Entry Group $script:GroupId) + $State.DeletedById[$script:GroupId] = + Get-DeletedObject $script:GroupId 'Deleted group' ` + -ODataType '#microsoft.graph.group' $State.Protected['directory/deletedItems/microsoft.graph.group'] = @( - [pscustomobject]@{ id = $script:GroupId; displayName = 'Deleted group' } + Get-InventoryObject $script:GroupId 'Deleted group' ) - Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeFalse - $State.Detail | Should -Match 'Group \| 22222222-2222-2222-2222-222222222222 \| Deleted group \| Soft deleted' + Invoke-Check | Should -BeFalse + $State.Detail | Should -Match "$($script:GroupRow) Deleted group \| Soft deleted" } - It 'reports a listed object that was soft deleted without protection as soft deleted, not as not found' { - $State.Listed = @([pscustomobject]@{ Type = 'User'; Id = $script:UserId }) - $State.DeletedById[$script:UserId] = [pscustomobject]@{ - id = $script:UserId; displayName = 'Removed user'; '@odata.type' = '#microsoft.graph.user' - } + It 'reports a listed object soft deleted without protection as soft deleted' { + $State.Listed = @(Get-Entry User $script:UserId) + $State.DeletedById[$script:UserId] = + Get-DeletedObject $script:UserId 'Removed user' ` + -ODataType '#microsoft.graph.user' - Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeFalse - $State.Detail | Should -Match 'User \| 11111111-1111-1111-1111-111111111111 \| Removed user \| Soft deleted' + Invoke-Check | Should -BeFalse + $State.Detail | Should -Match "$($script:UserRow) Removed user \| Soft deleted" $State.Detail | Should -Not -Match 'Not found' } It 'reads a deleted object through the documented deletedItems route, once' { - $State.Listed = @([pscustomobject]@{ Type = 'Group'; Id = $script:GroupId }) + $State.Listed = @(Get-Entry Group $script:GroupId) - Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeFalse - Should -Invoke -ModuleName Maester Invoke-MtGraphRequest -Times 1 -Exactly -ParameterFilter { - $RelativeUri -eq 'directory/deletedItems/22222222-2222-2222-2222-222222222222' - } - Should -Invoke -ModuleName Maester Invoke-MtGraphRequest -Times 0 -Exactly -ParameterFilter { - $RelativeUri -like 'directory/deletedItems/microsoft.graph.*/22222222-2222-2222-2222-222222222222' - } + Invoke-Check | Should -BeFalse + Should -Invoke -ModuleName Maester Invoke-MtGraphRequest -Times 1 -Exactly ` + -ParameterFilter { + $RelativeUri -eq 'directory/deletedItems/22222222-2222-2222-2222-222222222222' + } + Should -Invoke -ModuleName Maester Invoke-MtGraphRequest -Times 0 -Exactly ` + -ParameterFilter { + $RelativeUri -like 'directory/deletedItems/microsoft.graph.*/22222222-*' + } } It 'reports a deleted object of another type as not found' { - $State.Listed = @([pscustomobject]@{ Type = 'Group'; Id = $script:UserId }) - $State.DeletedById[$script:UserId] = [pscustomobject]@{ - id = $script:UserId; displayName = 'Removed user'; '@odata.type' = '#microsoft.graph.user' - } + $State.Listed = @(Get-Entry Group $script:UserId) + $State.DeletedById[$script:UserId] = + Get-DeletedObject $script:UserId 'Removed user' ` + -ODataType '#microsoft.graph.user' + + Invoke-Check | Should -BeFalse + $State.Detail | Should -Match "Group \| $($script:UserId) \| \| Not found" + $State.Detail | Should -Not -Match 'Soft deleted' + } - Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeFalse - $State.Detail | Should -Match 'Group \| 11111111-1111-1111-1111-111111111111 \| \| Not found' + It 'reports a deleted object without an @odata.type as not found' { + $State.Listed = @(Get-Entry User $script:UserId) + $State.DeletedById[$script:UserId] = Get-InventoryObject $script:UserId 'Removed user' + + Invoke-Check | Should -BeFalse + $State.Detail | Should -Match "$($script:UserRow) \| Not found" $State.Detail | Should -Not -Match 'Soft deleted' } It 'shows a display name that looks like a link or an image as plain text' { - $State.Listed = @( - [pscustomobject]@{ Type = 'User'; Id = $script:UserId } - [pscustomobject]@{ Type = 'Group'; Id = $script:GroupId } - ) - $State.ObjectById[$script:UserId] = [pscustomobject]@{ - id = $script:UserId; displayName = '[Sign in](https://phish.example)'; isHardDeleteProtectionEnabled = $null - } - $State.ObjectById[$script:GroupId] = [pscustomobject]@{ - id = $script:GroupId; displayName = '![x](https://attacker.example/p.png)'; isHardDeleteProtectionEnabled = $null - } + $State.Listed = @(Get-Entry User $script:UserId; Get-Entry Group $script:GroupId) + $State.ObjectById[$script:UserId] = + Get-GraphObject $script:UserId '[Sign in](https://phish.example)' + $State.ObjectById[$script:GroupId] = + Get-GraphObject $script:GroupId '![x](https://attacker.example/p.png)' - Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeFalse + Invoke-Check | Should -BeFalse $State.Detail.Contains('\[Sign in\]\(https\://phish.example\)') | Should -BeTrue $State.Detail.Contains('\!\[x\]\(https\://attacker.example/p.png\)') | Should -BeTrue $State.Detail.Contains('[Sign in](') | Should -BeFalse @@ -198,11 +240,11 @@ } It 'reports a 404 that sits on the inner exception as not found' { - $State.Listed = @([pscustomobject]@{ Type = 'Group'; Id = $script:GroupId }) + $State.Listed = @(Get-Entry Group $script:GroupId) $State.Wrap = $true - Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeFalse - $State.Detail | Should -Match 'Group \| 22222222-2222-2222-2222-222222222222 \| \| Not found' + Invoke-Check | Should -BeFalse + $State.Detail | Should -Match "$($script:GroupRow) \| Not found" } It 'rejects an Id that is not a GUID without calling Graph' { @@ -215,86 +257,113 @@ } It 'fails the check with an error that names the entry when an Id is not a GUID' { - $State.Listed = @([pscustomobject]@{ Type = 'User'; Id = 'admin@contoso.com' }) + $State.Listed = @(Get-Entry User 'admin@contoso.com') - { Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed } | - Should -Throw "*Id 'admin@contoso.com'*" + { Invoke-Check } | Should -Throw "*Id 'admin@contoso.com'*" } It 'keeps a display name with line breaks in one table cell' { - $State.Listed = @([pscustomobject]@{ Type = 'User'; Id = $script:UserId }) - $State.ObjectById[$script:UserId] = [pscustomobject]@{ - id = $script:UserId; displayName = "Ops`r`nTeam`nLead"; isHardDeleteProtectionEnabled = $null - } + $State.Listed = @(Get-Entry User $script:UserId) + $State.ObjectById[$script:UserId] = + Get-GraphObject $script:UserId "Ops`r`nTeam`nLead" - Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeFalse - $State.Detail | Should -Match 'User \| 11111111-1111-1111-1111-111111111111 \| Ops Team Lead \| Not protected' + Invoke-Check | Should -BeFalse + $State.Detail | Should -Match "$($script:UserRow) Ops Team Lead \| Not protected" } It 'counts an entry that is listed more than once as one object' { $HexId = 'aabbccdd-1111-2222-3333-eeeeffff0000' $State.Listed = @( - [pscustomobject]@{ Type = 'User'; Id = $HexId } - [pscustomobject]@{ Type = 'user'; Id = $HexId.ToUpperInvariant() } - [pscustomobject]@{ Type = 'User'; Id = "{$HexId}" } - [pscustomobject]@{ Type = 'Group'; Id = $script:GroupId } + Get-Entry User $HexId + Get-Entry user $HexId.ToUpperInvariant() + Get-Entry User "{$HexId}" + Get-Entry Group $script:GroupId ) - $State.ObjectById[$HexId] = [pscustomobject]@{ - id = $HexId; displayName = 'Plain user'; isHardDeleteProtectionEnabled = $null - } + $State.ObjectById[$HexId] = Get-GraphObject $HexId 'Plain user' $HexId | Should -Not -BeExactly $HexId.ToUpperInvariant() - Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeFalse + Invoke-Check | Should -BeFalse $State.Detail | Should -Match '2 of 2 listed object\(s\)' - [regex]::Matches($State.Detail, '\| User \| aabbccdd-1111-2222-3333-eeeeffff0000 \|').Count | Should -Be 1 - $State.Detail | Should -Match 'Group \| 22222222-2222-2222-2222-222222222222 \| \| Not found' + [regex]::Matches($State.Detail, "\| User \| $HexId \|").Count | Should -Be 1 + $State.Detail | Should -Match "$($script:GroupRow) \| Not found" + } + + It 'keeps one passing row when an entry is listed twice and both lookups pass' { + $State.Listed = @(Get-Entry User $script:UserId; Get-Entry User "{$script:UserId}") + $State.ObjectById[$script:UserId] = + Get-GraphObject $script:UserId 'Admin One' -Protected $true + $State.Protected['users'] = @(Get-InventoryObject $script:UserId 'Admin One') + + Invoke-Check | Should -BeTrue + $State.Detail | Should -Match 'All 1 listed object\(s\)' + } + + It 'lets a failing lookup win when an entry is listed twice and the lookups differ' { + $State.Listed = @(Get-Entry User $script:UserId; Get-Entry User "{$script:UserId}") + $State.Sequence[$script:UserId] = @( + Get-GraphObject $script:UserId 'Admin One' -Protected $true + Get-GraphObject $script:UserId 'Admin One' -Protected $null + ) + + Invoke-Check | Should -BeFalse + $State.Detail | Should -Match '1 of 1 listed object' + $State.Detail | Should -Match "$($script:UserRow) Admin One \| Not protected" + } + + It 'keeps the failure when the failing lookup comes first' { + $State.Listed = @(Get-Entry User $script:UserId; Get-Entry User "{$script:UserId}") + $State.Sequence[$script:UserId] = @( + Get-GraphObject $script:UserId 'Admin One' -Protected $null + Get-GraphObject $script:UserId 'Admin One' -Protected $true + ) + + Invoke-Check | Should -BeFalse + $State.Detail | Should -Match "$($script:UserRow) Admin One \| Not protected" } It 'uses the canonical lower-case form of the Id in the request and in the result' { - $State.Listed = @([pscustomobject]@{ Type = 'User'; Id = '{AAAAAAAA-1111-2222-3333-BBBBBBBBBBBB}' }) - $State.ObjectById['aaaaaaaa-1111-2222-3333-bbbbbbbbbbbb'] = [pscustomobject]@{ - id = 'aaaaaaaa-1111-2222-3333-bbbbbbbbbbbb'; displayName = 'Mixed case'; isHardDeleteProtectionEnabled = $null - } + $State.Listed = @(Get-Entry User '{AAAAAAAA-1111-2222-3333-BBBBBBBBBBBB}') + $State.ObjectById['aaaaaaaa-1111-2222-3333-bbbbbbbbbbbb'] = + Get-GraphObject 'aaaaaaaa-1111-2222-3333-bbbbbbbbbbbb' 'Mixed case' - Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeFalse - $State.Detail | Should -MatchExactly 'User \| aaaaaaaa-1111-2222-3333-bbbbbbbbbbbb \| Mixed case \| Not protected' - Should -Invoke -ModuleName Maester Invoke-MtGraphRequest -Times 1 -Exactly -ParameterFilter { - $RelativeUri -ceq 'users/aaaaaaaa-1111-2222-3333-bbbbbbbbbbbb' - } + Invoke-Check | Should -BeFalse + $State.Detail | Should -MatchExactly ( + 'User \| aaaaaaaa-1111-2222-3333-bbbbbbbbbbbb \| Mixed case \| Not protected' + ) + Should -Invoke -ModuleName Maester Invoke-MtGraphRequest -Times 1 -Exactly ` + -ParameterFilter { $RelativeUri -ceq 'users/aaaaaaaa-1111-2222-3333-bbbbbbbbbbbb' } } - It 'keeps a protected object in the unlisted table when its Id is listed under another Type' { - $State.Listed = @([pscustomobject]@{ Type = 'Group'; Id = $script:UserId }) - $State.Protected['users'] = @([pscustomobject]@{ id = $script:UserId; displayName = 'Admin One' }) + It 'keeps a protected object in the unlisted table when listed under another Type' { + $State.Listed = @(Get-Entry Group $script:UserId) + $State.Protected['users'] = @(Get-InventoryObject $script:UserId 'Admin One') - Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeFalse - $State.Detail | Should -Match 'Group \| 11111111-1111-1111-1111-111111111111 \| \| Not found' - $State.Detail | Should -Match 'User \| 11111111-1111-1111-1111-111111111111 \| Admin One \| Active' + Invoke-Check | Should -BeFalse + $State.Detail | Should -Match "Group \| $($script:UserId) \| \| Not found" + $State.Detail | Should -Match "$($script:UserRow) Admin One \| Active" } It 'does not list a correctly listed object as unlisted' { - $State.Listed = @([pscustomobject]@{ Type = 'User'; Id = $script:UserId }) - $State.ObjectById[$script:UserId] = [pscustomobject]@{ - id = $script:UserId; displayName = 'Admin One'; isHardDeleteProtectionEnabled = $true - } - $State.Protected['users'] = @([pscustomobject]@{ id = $script:UserId; displayName = 'Admin One' }) + $State.Listed = @(Get-Entry User $script:UserId) + $State.ObjectById[$script:UserId] = + Get-GraphObject $script:UserId 'Admin One' -Protected $true + $State.Protected['users'] = @(Get-InventoryObject $script:UserId 'Admin One') - Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeTrue + Invoke-Check | Should -BeTrue $State.Detail | Should -Not -Match 'other object' } It 'shows the first 25 unlisted objects and the total' { - $State.Listed = @([pscustomobject]@{ Type = 'User'; Id = $script:UserId }) - $State.ObjectById[$script:UserId] = [pscustomobject]@{ - id = $script:UserId; displayName = 'Admin One'; isHardDeleteProtectionEnabled = $true - } + $State.Listed = @(Get-Entry User $script:UserId) + $State.ObjectById[$script:UserId] = + Get-GraphObject $script:UserId 'Admin One' -Protected $true $State.Protected['groups'] = @( 1..30 | ForEach-Object { - [pscustomobject]@{ id = ('33333333-3333-3333-3333-{0:D12}' -f $_); displayName = "Group $_" } + Get-InventoryObject ('33333333-3333-3333-3333-{0:D12}' -f $_) "Group $_" } ) - Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed | Should -BeNullOrEmpty + Invoke-Check | Should -BeNullOrEmpty $State.Detail | Should -Match '30 other object\(s\)' $State.Detail | Should -Match 'Showing the first 25 of 30 objects' $State.Detail | Should -Match 'Group 25 \|' @@ -304,37 +373,41 @@ Context 'Errors' { It 'throws for an invalid object type' { - $State.Listed = @([pscustomobject]@{ Type = 'Device'; Id = $script:UserId }) + $State.Listed = @(Get-Entry Device $script:UserId) - { Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed } | + { Invoke-Check } | Should -Throw '*Type must be User, Group, Application or ServicePrincipal*' } It 'throws for a Graph error that is not a 404' { - $State.Listed = @([pscustomobject]@{ Type = 'User'; Id = $script:UserId }) + $State.Listed = @(Get-Entry User $script:UserId) Mock -ModuleName Maester Invoke-MtGraphRequest -MockWith { param($RelativeUri) if ($RelativeUri -like 'users/*') { throw [Microsoft.PowerShell.Commands.HttpResponseException]::new( 'Response status code does not indicate success: Forbidden (Forbidden).', - [System.Net.Http.HttpResponseMessage]::new([System.Net.HttpStatusCode]::Forbidden) + [System.Net.Http.HttpResponseMessage]::new( + [System.Net.HttpStatusCode]::Forbidden + ) ) } return @() } - { Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed } | Should -Throw '*Forbidden*' + { Invoke-Check } | Should -Throw '*Forbidden*' } It 'throws, instead of reporting Not found, when the error has no HTTP response' { - $State.Listed = @([pscustomobject]@{ Type = 'User'; Id = $script:UserId }) + $State.Listed = @(Get-Entry User $script:UserId) Mock -ModuleName Maester Invoke-MtGraphRequest -MockWith { param($RelativeUri) - if ($RelativeUri -like 'users/*') { throw [System.InvalidOperationException]::new('Batch request failed.') } + if ($RelativeUri -like 'users/*') { + throw [System.InvalidOperationException]::new('Batch request failed.') + } return @() } - { Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed } | Should -Throw '*Batch request failed*' + { Invoke-Check } | Should -Throw '*Batch request failed*' } } } diff --git a/tests/maester/entra/Test.MT.1276.md b/tests/maester/entra/Test.MT.1276.md index 2d532dd16e..cc22d51884 100644 --- a/tests/maester/entra/Test.MT.1276.md +++ b/tests/maester/entra/Test.MT.1276.md @@ -6,17 +6,19 @@ Protection setting in Microsoft Entra. Any listed object that is not protected, fails the test. If nothing is listed, or every listed object is protected but other objects in Microsoft Entra have protection and are not listed, the result is **Investigate**: check whether the list is complete. -Protection limits destructive deletion by a compromised administrator. A protected object stays recoverable for -seven days after it is soft deleted, so an attacker cannot permanently destroy it before someone notices -(MITRE T1485 Data Destruction). Soft deletion still removes access, so for T1531 Account Access Removal the -benefit is recovery: the object can be restored while protection holds. +Protection limits destructive deletion by a compromised administrator. For seven days after an object is soft +deleted, it cannot be permanently deleted, which gives time to notice and restore it (MITRE T1485 Data +Destruction). After the seven days, permanent deletion is possible again. Soft deletion still removes access, so +for T1531 Account Access Removal the benefit is recovery: the object can be restored while protection holds. See [Hard Deletion Protection](https://maester.dev/docs/configuration/hard-deletion-protection) for the configuration format and for suggestions on which objects to list. #### Remediation action: -For an object with the status **Not protected**: +For an object with the status **Not protected**, first check that it can be protected. Users synchronized from +on-premises Active Directory and mail-enabled security groups cannot be, and also show as not protected. Remove +them from the config, or protect another object instead. For an object that can be protected: 1. Sign in to the [Microsoft Entra admin center](https://entra.microsoft.com) as at least a **Microsoft Entra Backup Administrator**. 2. Browse to **Backup and recovery** > **Hard deletion protection**. @@ -29,10 +31,13 @@ object first. A restored object keeps protection if it already had it. If it did * A user or a group: restore it from **Deleted users** or **Deleted groups** in the Microsoft Entra admin center. * An application: restore it from **App registrations** > **Deleted applications**. -* A service principal: the admin center does not show deleted service principals. Restore it with Microsoft Graph, +* A service principal: the admin center does not show deleted service principals. If its application registration + was deleted too, restore the registration from **Deleted applications** first, which also restores its service + principal. Otherwise restore the service principal with Microsoft Graph, `POST https://graph.microsoft.com/v1.0/directory/deletedItems/{id}/restore`, or with `Restore-MgDirectoryDeletedItem -DirectoryObjectId `, as at least an Application Administrator or Cloud - Application Administrator. Customers cannot restore a deleted managed identity. + Application Administrator. Use a separate delegated Graph connection that has `Application.ReadWrite.All`, not + the read-only connection Maester uses. Customers cannot restore a deleted managed identity. For an object with the status **Not found**: check the `Type` and `Id` in the Maester config. The `Id` is the object ID, not the application (client) ID or a user principal name. If the object was permanently deleted, remove it from diff --git a/tests/maester/entra/Test.MT.1276.ps1 b/tests/maester/entra/Test.MT.1276.ps1 index 429f355c8d..0f569d51fb 100644 --- a/tests/maester/entra/Test.MT.1276.ps1 +++ b/tests/maester/entra/Test.MT.1276.ps1 @@ -1,18 +1,21 @@ function Test-MtEntraHardDeletionProtection { <# .SYNOPSIS - Checks that the critical Entra objects listed in the Maester config have Hard Deletion Protection enabled. + Checks that the critical Entra objects in the Maester config have Hard Deletion Protection. .DESCRIPTION - Takes the HardDeletionProtectedObjects setting as a parameter and checks that each listed user, group, application or - service principal has isHardDeleteProtectionEnabled set to true. Protection is permanent once enabled, so - Maester never guesses which objects are critical. + Takes the HardDeletionProtectedObjects setting as a parameter and checks that each listed + user, group, application or service principal has isHardDeleteProtectionEnabled set to + true. Protection is permanent once enabled, so Maester never guesses which objects are + critical. - The result is Failed when a listed object is not protected, is soft deleted or cannot be found. The result - is Investigate when nothing is listed, or when every listed object is protected but other objects in the - tenant have protection and are not listed, because the config and the tenant then disagree. + The result is Failed when a listed object is not protected, is soft deleted or cannot be + found. The result is Investigate when nothing is listed, or when every listed object is + protected but other objects in the tenant have protection and are not listed, because the + config and the tenant then disagree. - Hard Deletion Protection is in preview and the property is only available in Microsoft Graph beta. + Hard Deletion Protection is in preview and the property is only available in Microsoft + Graph beta. .EXAMPLE Invoke-Maester -TestId MT.1276 -IncludePreview @@ -38,7 +41,7 @@ [CmdletBinding()] [OutputType([bool])] param ( - # The objects to check, from the HardDeletionProtectedObjects setting: a Type and an Id each. + # The objects to check, from the HardDeletionProtectedObjects setting: a Type and an Id. [MaesterParameter(Setting = 'HardDeletionProtectedObjects')] [object[]] $HardDeletionProtectedObjects = @() ) @@ -47,58 +50,68 @@ $Protected = @(Get-MtEntraHardDeletionProtectedObject) if ($ConfiguredObjects.Count -eq 0) { - $Result = 'No objects are listed in HardDeletionProtectedObjects in the Maester config, so Hard Deletion ' + - "Protection must be verified manually.`n`n" + $Result = 'No objects are listed in HardDeletionProtectedObjects in the Maester ' + + "config, so Hard Deletion Protection must be verified manually.`n`n" if ($Protected.Count -gt 0) { - $Result += "These $($Protected.Count) object(s) have Hard Deletion Protection in Microsoft Entra. " + - "Add the ones that matter to the config so this test can check them:`n`n" - $Result += Format-MtEntraHardDeletionTable -InputObject $Protected -StateProperty State -StateHeading State + $Result += "These $($Protected.Count) object(s) have Hard Deletion Protection in " + + 'Microsoft Entra. Add the ones that matter to the config so this test can ' + + "check them:`n`n" + $Result += Format-MtEntraHardDeletionTable -InputObject $Protected ` + -StateProperty State -StateHeading State } else { - $Result += 'The scan did not find any objects with Hard Deletion Protection. Add the critical objects that support ' + - 'it to GlobalSettings.HardDeletionProtectedObjects, then enable protection on them. See ' + - 'https://maester.dev/docs/configuration/hard-deletion-protection for the format and for ' + - 'the objects that support it.' + $Result += 'The scan did not find any objects with Hard Deletion Protection. Add ' + + 'the critical objects that support it to ' + + 'GlobalSettings.HardDeletionProtectedObjects, then enable protection on ' + + 'them. See https://maester.dev/docs/configuration/hard-deletion-protection ' + + 'for the format and for the objects that support it.' } Add-MtTestResultDetail -Investigate -Result $Result return $null } - $ListedKeys = @{} - $Rows = @( - foreach ($Configured in $ConfiguredObjects) { - $Row = Get-MtEntraHardDeletionObjectStatus -Configured $Configured - $Key = "$($Row.Type)|$($Row.Id)" - if (-not $ListedKeys.ContainsKey($Key)) { - $ListedKeys[$Key] = $true - $Row - } + # An entry listed twice counts once. When the two lookups disagree, the failure wins. + $RowIndex = @{} + $Rows = [System.Collections.Generic.List[object]]::new() + foreach ($Configured in $ConfiguredObjects) { + $Row = Get-MtEntraHardDeletionObjectStatus -Configured $Configured + $Key = "$($Row.Type)|$($Row.Id)" + if (-not $RowIndex.ContainsKey($Key)) { + $RowIndex[$Key] = $Rows.Count + $Rows.Add($Row) + } elseif ($Rows[$RowIndex[$Key]].Status -eq 'Protected' -and $Row.Status -ne 'Protected') { + $Rows[$RowIndex[$Key]] = $Row } - ) - $Unlisted = @($Protected | Where-Object { -not $ListedKeys.ContainsKey("$($_.Type)|$($_.Id)") }) - $UnlistedTable = if ($Unlisted.Count -gt 0) { - "`n`n$($Unlisted.Count) other object(s) have Hard Deletion Protection in Microsoft Entra but are not " + - "listed in the Maester config:`n`n" + - (Format-MtEntraHardDeletionTable -InputObject $Unlisted -StateProperty State -StateHeading State) - } else { - '' + } + + $Unlisted = @($Protected | Where-Object { -not $RowIndex.ContainsKey("$($_.Type)|$($_.Id)") }) + $UnlistedTable = '' + if ($Unlisted.Count -gt 0) { + $UnlistedTable = "`n`n$($Unlisted.Count) other object(s) have Hard Deletion Protection " + + "in Microsoft Entra but are not listed in the Maester config:`n`n" + + (Format-MtEntraHardDeletionTable -InputObject $Unlisted ` + -StateProperty State -StateHeading State) } $Failing = @($Rows | Where-Object { $_.Status -ne 'Protected' }) if ($Failing.Count -gt 0) { - $Result = "$($Failing.Count) of $($Rows.Count) listed object(s) do not have Hard Deletion Protection " + - "enabled, or are deleted or missing.`n`n" + - (Format-MtEntraHardDeletionTable -InputObject $Failing -StateProperty Status -StateHeading Status) + $Result = "$($Failing.Count) of $($Rows.Count) listed object(s) do not have Hard " + + "Deletion Protection enabled, or are deleted or missing.`n`n" + + (Format-MtEntraHardDeletionTable -InputObject $Failing ` + -StateProperty Status -StateHeading Status) Add-MtTestResultDetail -Result ($Result + $UnlistedTable) return $false } if ($Unlisted.Count -gt 0) { - $Result = "All $($Rows.Count) listed object(s) have Hard Deletion Protection enabled. Check whether the " + - 'other protected objects below belong in the Maester config.' + $UnlistedTable + $Result = "All $($Rows.Count) listed object(s) have Hard Deletion Protection enabled. " + + 'Check whether the other protected objects below belong in the Maester config.' + + $UnlistedTable Add-MtTestResultDetail -Investigate -Result $Result return $null } - Add-MtTestResultDetail -Result "Well done. All $($Rows.Count) listed object(s) have Hard Deletion Protection enabled." + Add-MtTestResultDetail -Result ( + "Well done. All $($Rows.Count) listed object(s) have Hard Deletion Protection enabled." + ) return $true } diff --git a/website/docs/configuration/hard-deletion-protection.md b/website/docs/configuration/hard-deletion-protection.md index fed48ab7e6..81a482eb02 100644 --- a/website/docs/configuration/hard-deletion-protection.md +++ b/website/docs/configuration/hard-deletion-protection.md @@ -11,7 +11,7 @@ Hard Deletion Protection (preview) is a Microsoft Entra feature that stops a pro Maester includes tests that check the objects you list in the Maester configuration against their Hard Deletion Protection setting in Microsoft Entra. :::caution -Protection is **permanent**. Once enabled on an object it cannot be removed. If you enable it by mistake, soft delete the object and wait seven days before you permanently delete it. Microsoft intends the feature for selected critical objects, not for every object in the tenant. +Protection is **permanent**. Once enabled on an object it cannot be removed, and soft deleting the object does not undo it. Soft delete an object that you protected by mistake only if you want to retire it: it stops working while it is deleted, you can restore it for up to 30 days, and you can permanently delete it seven days after the soft delete. Microsoft intends the feature for selected critical objects, not for every object in the tenant. ::: ## How Hard Deletion Protection Works @@ -98,6 +98,8 @@ The result lists at most 25 objects in each table and gives the total when there A failed result also lists the protected objects that are not in the configuration, so you can see both gaps at once. +The scan for protected objects reads the active and the deleted objects one after the other, so it is not a snapshot. An object that is soft deleted or restored while the scan runs can be listed twice (shown once, with the state `Active or soft deleted`), or be missed. If an object you expect is missing from a table, run the test again. + ## Which Objects to Protect Protect the objects whose permanent loss would be hard to recover from or would help an attacker hide their tracks. These are suggestions, not requirements. Start small and add objects as you decide they are critical. From 424506064fed55e16e8c78438d3499fb099f0bc7 Mon Sep 17 00:00:00 2001 From: agnivesh <320655+agnivesh@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:09:45 +0000 Subject: [PATCH 11/11] fix(entra): accept Agent ID subtypes of a soft-deleted object A soft-deleted agent user, agent identity, agent identity blueprint or blueprint principal comes back from deletedItems with its own @odata.type, not user, servicePrincipal or application. The strict type check reported such an object as not found. Accept the subtypes under the type they are covered by. Key the active fixtures of the unit tests by resource path and ID, so a lookup routed to the wrong endpoint fails, and give the mock one string for the parameter that the real command takes as an array. Add synchronized groups to the objects that cannot be protected, and say that running the test again does not show objects past the table limit. --- .../Get-MtEntraHardDeletionObjectStatus.ps1 | 30 +++++-- ...st-MtEntraHardDeletionProtection.Tests.ps1 | 82 +++++++++++++------ tests/maester/entra/Test.MT.1276.md | 6 +- .../configuration/hard-deletion-protection.md | 2 +- 4 files changed, 84 insertions(+), 36 deletions(-) diff --git a/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionObjectStatus.ps1 b/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionObjectStatus.ps1 index 73981922fc..cfa37cec6d 100644 --- a/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionObjectStatus.ps1 +++ b/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionObjectStatus.ps1 @@ -9,9 +9,13 @@ When the active lookup returns HTTP 404, the function reads the object through the documented single-item route, directory/deletedItems/{id}, and checks that its @odata.type is - the configured type. It reports 'Soft deleted' when it finds the object there, whether or not - the object has protection. An object of another type, a response without an @odata.type, or - no object gives 'Not found'. Any Graph error other than a 404 is thrown. + the configured type or one of its Agent ID subtypes: agentUser for User, + agentIdentityBlueprint for Application, and agentIdentity or + agentIdentityBlueprintPrincipal for ServicePrincipal. + + It reports 'Soft deleted' when it finds the object there, whether or not the object has + protection. An object of another type, a response without an @odata.type, or no object + gives 'Not found'. Any Graph error other than a 404 is thrown. The Id must be the object ID, a GUID. The function uses its canonical lower-case form in both requests and in the result, so the result matches the objects that @@ -30,14 +34,22 @@ [object] $Configured ) + # GraphTypes are the @odata.type values a deleted object of this type can have. Agent ID objects + # are covered through their underlying user, application and service principal types. $EndpointByType = @{ - user = @{ Name = 'User'; Path = 'users'; GraphType = 'user' } - group = @{ Name = 'Group'; Path = 'groups'; GraphType = 'group' } + user = @{ + Name = 'User'; Path = 'users'; GraphTypes = @('user', 'agentUser') + } + group = @{ Name = 'Group'; Path = 'groups'; GraphTypes = @('group') } application = @{ - Name = 'Application'; Path = 'applications'; GraphType = 'application' + Name = 'Application'; Path = 'applications' + GraphTypes = @('application', 'agentIdentityBlueprint') } serviceprincipal = @{ - Name = 'ServicePrincipal'; Path = 'servicePrincipals'; GraphType = 'servicePrincipal' + Name = 'ServicePrincipal'; Path = 'servicePrincipals' + GraphTypes = @( + 'servicePrincipal', 'agentIdentity', 'agentIdentityBlueprintPrincipal' + ) } } @@ -52,6 +64,7 @@ ) } $Endpoint = $EndpointByType[$Type] + $AcceptedTypes = @($Endpoint.GraphTypes | ForEach-Object { "#microsoft.graph.$_" }) $Id = $ParsedId.ToString() $Object = $null @@ -73,7 +86,8 @@ $Deleted = Invoke-MtGraphRequest -ApiVersion 'beta' ` -RelativeUri "directory/deletedItems/$Id" ` -Select @('id', 'displayName') -ErrorAction Stop - if ([string]$Deleted.'@odata.type' -eq "#microsoft.graph.$($Endpoint.GraphType)") { + $DeletedType = [string]$Deleted.'@odata.type' + if ($DeletedType -in $AcceptedTypes) { $Object = $Deleted $Status = 'Soft deleted' } diff --git a/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 b/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 index 0aafb0e6d3..76b1fb9213 100644 --- a/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 +++ b/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 @@ -55,29 +55,30 @@ }.GetNewClosure() Mock -ModuleName Maester Invoke-MtGraphRequest -MockWith { param($RelativeUri) + # The real parameter is an array, and a hashtable lookup with an array returns an array. + $uri = [string]$RelativeUri $notFound = $NotFoundError if ($State.Wrap) { $notFound = [System.InvalidOperationException]::new( 'Request failed.', $NotFoundError ) } - $id = $RelativeUri.Split('/')[-1] - if ($RelativeUri -match '^directory/deletedItems/[0-9a-fA-F-]{36}$') { + $id = $uri.Split('/')[-1] + if ($uri -match '^directory/deletedItems/[0-9a-fA-F-]{36}$') { if ($null -eq $State.DeletedById[$id]) { throw $notFound } return $State.DeletedById[$id] } - if ($RelativeUri -match '^(users|groups|applications|servicePrincipals)/[^/]+$') { - if ($State.Sequence.ContainsKey($id)) { - $step = [int]$State.Seen[$id] - $State.Seen[$id] = $step + 1 - $answers = $State.Sequence[$id] + if ($uri -match '^(users|groups|applications|servicePrincipals)/[^/]+$') { + if ($State.Sequence.ContainsKey($uri)) { + $step = [int]$State.Seen[$uri] + $State.Seen[$uri] = $step + 1 + $answers = $State.Sequence[$uri] return $answers[[Math]::Min($step, $answers.Count - 1)] } - if ($null -eq $State.ObjectById[$id]) { throw $notFound } - return $State.ObjectById[$id] + if ($null -eq $State.ObjectById[$uri]) { throw $notFound } + return $State.ObjectById[$uri] } - $key = [string]$RelativeUri - if ($State.Protected.Keys -contains $key) { return $State.Protected[$key] } + if ($State.Protected.Keys -contains $uri) { return $State.Protected[$uri] } return @() }.GetNewClosure() } @@ -124,7 +125,7 @@ Context 'Objects are listed' { It 'passes when every listed object is protected and nothing else is' { $State.Listed = @(Get-Entry User $script:UserId) - $State.ObjectById[$script:UserId] = + $State.ObjectById["users/$($script:UserId)"] = Get-GraphObject $script:UserId 'Admin One' -Protected $true $State.Protected['users'] = @(Get-InventoryObject $script:UserId 'Admin One') @@ -135,7 +136,7 @@ It 'is Investigate when listed objects pass but other protected objects are not listed' { $State.Listed = @(Get-Entry User $script:UserId) - $State.ObjectById[$script:UserId] = + $State.ObjectById["users/$($script:UserId)"] = Get-GraphObject $script:UserId 'Admin One' -Protected $true $State.Protected['users'] = @( Get-InventoryObject $script:UserId 'Admin One' @@ -150,7 +151,8 @@ It 'fails and lists an unprotected object, even when others are not listed' { $State.Listed = @(Get-Entry user $script:UserId) - $State.ObjectById[$script:UserId] = Get-GraphObject $script:UserId 'Plain | User' + $State.ObjectById["users/$($script:UserId)"] = + Get-GraphObject $script:UserId 'Plain | User' $State.Protected['groups'] = @(Get-InventoryObject $script:GroupId 'Some group') Invoke-Check | Should -BeFalse @@ -225,11 +227,41 @@ $State.Detail | Should -Not -Match 'Soft deleted' } + It 'reports a soft-deleted listed as as soft deleted' -ForEach @( + @{ Type = 'User'; Subtype = 'agentUser' } + @{ Type = 'Application'; Subtype = 'agentIdentityBlueprint' } + @{ Type = 'ServicePrincipal'; Subtype = 'agentIdentity' } + @{ Type = 'ServicePrincipal'; Subtype = 'agentIdentityBlueprintPrincipal' } + ) { + $State.Listed = @(Get-Entry $Type $script:UserId) + $State.DeletedById[$script:UserId] = Get-DeletedObject $script:UserId 'Agent object' ` + -ODataType "#microsoft.graph.$Subtype" + + Invoke-Check | Should -BeFalse + $Row = "$Type \| $($script:UserId) \| Agent object" + $State.Detail | Should -Match "$Row \| Soft deleted" + } + + It 'reports a soft-deleted listed as as not found' -ForEach @( + @{ Type = 'Group'; Subtype = 'agentUser' } + @{ Type = 'User'; Subtype = 'agentIdentity' } + @{ Type = 'Application'; Subtype = 'agentUser' } + @{ Type = 'ServicePrincipal'; Subtype = 'agentIdentityBlueprint' } + ) { + $State.Listed = @(Get-Entry $Type $script:UserId) + $State.DeletedById[$script:UserId] = Get-DeletedObject $script:UserId 'Agent object' ` + -ODataType "#microsoft.graph.$Subtype" + + Invoke-Check | Should -BeFalse + $State.Detail | Should -Match "$Type \| $($script:UserId) \| \| Not found" + $State.Detail | Should -Not -Match 'Soft deleted' + } + It 'shows a display name that looks like a link or an image as plain text' { $State.Listed = @(Get-Entry User $script:UserId; Get-Entry Group $script:GroupId) - $State.ObjectById[$script:UserId] = + $State.ObjectById["users/$($script:UserId)"] = Get-GraphObject $script:UserId '[Sign in](https://phish.example)' - $State.ObjectById[$script:GroupId] = + $State.ObjectById["groups/$($script:GroupId)"] = Get-GraphObject $script:GroupId '![x](https://attacker.example/p.png)' Invoke-Check | Should -BeFalse @@ -264,7 +296,7 @@ It 'keeps a display name with line breaks in one table cell' { $State.Listed = @(Get-Entry User $script:UserId) - $State.ObjectById[$script:UserId] = + $State.ObjectById["users/$($script:UserId)"] = Get-GraphObject $script:UserId "Ops`r`nTeam`nLead" Invoke-Check | Should -BeFalse @@ -279,7 +311,7 @@ Get-Entry User "{$HexId}" Get-Entry Group $script:GroupId ) - $State.ObjectById[$HexId] = Get-GraphObject $HexId 'Plain user' + $State.ObjectById["users/$HexId"] = Get-GraphObject $HexId 'Plain user' $HexId | Should -Not -BeExactly $HexId.ToUpperInvariant() Invoke-Check | Should -BeFalse @@ -290,7 +322,7 @@ It 'keeps one passing row when an entry is listed twice and both lookups pass' { $State.Listed = @(Get-Entry User $script:UserId; Get-Entry User "{$script:UserId}") - $State.ObjectById[$script:UserId] = + $State.ObjectById["users/$($script:UserId)"] = Get-GraphObject $script:UserId 'Admin One' -Protected $true $State.Protected['users'] = @(Get-InventoryObject $script:UserId 'Admin One') @@ -300,7 +332,7 @@ It 'lets a failing lookup win when an entry is listed twice and the lookups differ' { $State.Listed = @(Get-Entry User $script:UserId; Get-Entry User "{$script:UserId}") - $State.Sequence[$script:UserId] = @( + $State.Sequence["users/$($script:UserId)"] = @( Get-GraphObject $script:UserId 'Admin One' -Protected $true Get-GraphObject $script:UserId 'Admin One' -Protected $null ) @@ -312,7 +344,7 @@ It 'keeps the failure when the failing lookup comes first' { $State.Listed = @(Get-Entry User $script:UserId; Get-Entry User "{$script:UserId}") - $State.Sequence[$script:UserId] = @( + $State.Sequence["users/$($script:UserId)"] = @( Get-GraphObject $script:UserId 'Admin One' -Protected $null Get-GraphObject $script:UserId 'Admin One' -Protected $true ) @@ -323,7 +355,7 @@ It 'uses the canonical lower-case form of the Id in the request and in the result' { $State.Listed = @(Get-Entry User '{AAAAAAAA-1111-2222-3333-BBBBBBBBBBBB}') - $State.ObjectById['aaaaaaaa-1111-2222-3333-bbbbbbbbbbbb'] = + $State.ObjectById['users/aaaaaaaa-1111-2222-3333-bbbbbbbbbbbb'] = Get-GraphObject 'aaaaaaaa-1111-2222-3333-bbbbbbbbbbbb' 'Mixed case' Invoke-Check | Should -BeFalse @@ -336,6 +368,8 @@ It 'keeps a protected object in the unlisted table when listed under another Type' { $State.Listed = @(Get-Entry Group $script:UserId) + $State.ObjectById["users/$($script:UserId)"] = + Get-GraphObject $script:UserId 'Admin One' -Protected $true $State.Protected['users'] = @(Get-InventoryObject $script:UserId 'Admin One') Invoke-Check | Should -BeFalse @@ -345,7 +379,7 @@ It 'does not list a correctly listed object as unlisted' { $State.Listed = @(Get-Entry User $script:UserId) - $State.ObjectById[$script:UserId] = + $State.ObjectById["users/$($script:UserId)"] = Get-GraphObject $script:UserId 'Admin One' -Protected $true $State.Protected['users'] = @(Get-InventoryObject $script:UserId 'Admin One') @@ -355,7 +389,7 @@ It 'shows the first 25 unlisted objects and the total' { $State.Listed = @(Get-Entry User $script:UserId) - $State.ObjectById[$script:UserId] = + $State.ObjectById["users/$($script:UserId)"] = Get-GraphObject $script:UserId 'Admin One' -Protected $true $State.Protected['groups'] = @( 1..30 | ForEach-Object { diff --git a/tests/maester/entra/Test.MT.1276.md b/tests/maester/entra/Test.MT.1276.md index cc22d51884..2e84db137b 100644 --- a/tests/maester/entra/Test.MT.1276.md +++ b/tests/maester/entra/Test.MT.1276.md @@ -16,9 +16,9 @@ configuration format and for suggestions on which objects to list. #### Remediation action: -For an object with the status **Not protected**, first check that it can be protected. Users synchronized from -on-premises Active Directory and mail-enabled security groups cannot be, and also show as not protected. Remove -them from the config, or protect another object instead. For an object that can be protected: +For an object with the status **Not protected**, first check that it can be protected. Users and groups +synchronized from on-premises Active Directory and mail-enabled security groups cannot be, and also show as not +protected. Remove them from the config, or protect another object instead. For an object that can be protected: 1. Sign in to the [Microsoft Entra admin center](https://entra.microsoft.com) as at least a **Microsoft Entra Backup Administrator**. 2. Browse to **Backup and recovery** > **Hard deletion protection**. diff --git a/website/docs/configuration/hard-deletion-protection.md b/website/docs/configuration/hard-deletion-protection.md index 81a482eb02..f97069c1b1 100644 --- a/website/docs/configuration/hard-deletion-protection.md +++ b/website/docs/configuration/hard-deletion-protection.md @@ -98,7 +98,7 @@ The result lists at most 25 objects in each table and gives the total when there A failed result also lists the protected objects that are not in the configuration, so you can see both gaps at once. -The scan for protected objects reads the active and the deleted objects one after the other, so it is not a snapshot. An object that is soft deleted or restored while the scan runs can be listed twice (shown once, with the state `Active or soft deleted`), or be missed. If an object you expect is missing from a table, run the test again. +The scan for protected objects reads the active and the deleted objects one after the other, so it is not a snapshot. An object that is soft deleted or restored while the scan runs can be listed twice (shown once, with the state `Active or soft deleted`), or be missed. If an object you expect is missing from a table, run the test again, which answers a missed scan. Running it again does not show objects beyond the table limit of 25: to see all of them, use the Microsoft Entra admin center or Microsoft Graph. ## Which Objects to Protect