From ed17a9d55d77490f10f2ed5806a6fe92003b8b9d Mon Sep 17 00:00:00 2001 From: Eduard Arbona Date: Fri, 6 Nov 2026 22:26:08 -0400 Subject: [PATCH 1/8] feat(azure): add MT.1266 - Azure secure score per subscription Defender for Cloud scores every subscription it covers and expresses the result as a percentage of the maximum achievable score. An assessor reads that number first and the recommendations afterwards. MT.1266 brings the number into a Maester run, one result per subscription, with the regulatory compliance standards of that subscription as a summary table in the same result. The target is a parameter (80% by default) because a score target is a business decision rather than a vendor rule, and a TestSettings row can set another value per subscription. Three decisions worth naming: - The percentage is computed from the current and maximum score instead of read from properties.score.percentage, whose unit the two Azure samples present differently. - The compliance standards come from microsoft.security/regulatorycompliance- standards, which already carries the control counts, rather than from the control level aggregated back up. - A subscription whose maximum score is zero is emitted and then skipped with that reason. Defender assessed nothing there, and no score is not a score of zero, let alone a pass. Subscription and standard names are tenant-controlled, so both go through Get-MtSafeMarkdown. Closes #2515. Part of #2510. --- .../services/azure/Get-MtAzureSecureScore.ps1 | 128 ++++++++++++ .../tests/fixtures/golden/selection.json | 9 +- .../Test-MtAzureSecureScore.Tests.ps1 | 188 ++++++++++++++++++ tests/maester/azure/Test.MT.1266.md | 36 ++++ tests/maester/azure/Test.MT.1266.ps1 | 142 +++++++++++++ 5 files changed, 500 insertions(+), 3 deletions(-) create mode 100644 powershell/internal/services/azure/Get-MtAzureSecureScore.ps1 create mode 100644 powershell/tests/functions/Test-MtAzureSecureScore.Tests.ps1 create mode 100644 tests/maester/azure/Test.MT.1266.md create mode 100644 tests/maester/azure/Test.MT.1266.ps1 diff --git a/powershell/internal/services/azure/Get-MtAzureSecureScore.ps1 b/powershell/internal/services/azure/Get-MtAzureSecureScore.ps1 new file mode 100644 index 0000000000..1f29e7fb7d --- /dev/null +++ b/powershell/internal/services/azure/Get-MtAzureSecureScore.ps1 @@ -0,0 +1,128 @@ +function Get-MtAzureSecureScore { + <# + .SYNOPSIS + Returns one row per Azure subscription with the Microsoft Defender for Cloud secure score and the + state of the regulatory compliance standards assigned to it. + + .DESCRIPTION + Runs three Azure Resource Graph queries over the subscriptions the signed-in account can read: the + secure score per subscription, the regulatory compliance standards per subscription, and the + subscription names from ResourceContainers so the result names a subscription instead of only its + GUID. + + The percentage is computed from the current and maximum score rather than read from + properties.score.percentage, whose unit the Azure samples present two different ways: the secure + score page divides current by max itself while the Resource Graph sample projects the property + directly. Dividing here removes the ambiguity. + + A subscription with a maximum score of zero is still returned. Defender for Cloud produced a score + row for it but assessed nothing, and the caller must say so rather than drop the subscription + silently or read it as a pass. + + An empty secure score result means Defender for Cloud produced no score for these subscriptions. + The caller must skip in that case. + + Errors are deliberately not caught here, so a failed query surfaces instead of being read as an + estate with no score. + + .EXAMPLE + Get-MtAzureSecureScore + + Returns the secure score and compliance standards of each readable subscription. + #> + [CmdletBinding()] + [OutputType([System.Collections.Generic.List[pscustomobject]])] + param() + + # properties.score.max is cast because the score arrives as a dynamic value. + $scoreQuery = @' +securityresources +| where type == "microsoft.security/securescores" +| extend currentScore = todouble(properties.score.current), + maxScore = todouble(properties.score.max), + initiative = tostring(properties.displayName) +| project subscriptionId, currentScore, maxScore, initiative +| sort by subscriptionId asc +'@ + + # The standards level already carries the control counts this needs, so there is no reason to read + # the control level and aggregate it back up. + $standardQuery = @' +securityresources +| where type == "microsoft.security/regulatorycompliancestandards" +| extend standard = name, + state = tostring(properties.state), + passedControls = toint(properties.passedControls), + failedControls = toint(properties.failedControls), + skippedControls = toint(properties.skippedControls), + unsupportedControls = toint(properties.unsupportedControls) +| project subscriptionId, standard, state, passedControls, failedControls, skippedControls, unsupportedControls +| sort by subscriptionId asc, standard asc +'@ + + $nameQuery = @' +resourcecontainers +| where type == "microsoft.resources/subscriptions" +| project subscriptionId, subscriptionName = name +'@ + + Write-Verbose 'Querying the Defender for Cloud secure score through Azure Resource Graph...' + $scoreRows = @(Invoke-MtAzureResourceGraphRequest -Query $scoreQuery) + + $result = [System.Collections.Generic.List[pscustomobject]]::new() + if ($scoreRows.Count -eq 0) { + # -NoEnumerate keeps an empty list from collapsing to $null. + Write-Output $result -NoEnumerate + return + } + + Write-Verbose 'Querying the regulatory compliance standards...' + $standardRows = @(Invoke-MtAzureResourceGraphRequest -Query $standardQuery) + Write-Verbose 'Querying the subscription names...' + $nameRows = @(Invoke-MtAzureResourceGraphRequest -Query $nameQuery) + + $nameLookup = @{} + foreach ($row in $nameRows) { + if (-not $row -or [string]::IsNullOrWhiteSpace([string]$row.subscriptionId)) { continue } + $nameLookup[[string]$row.subscriptionId] = [string]$row.subscriptionName + } + + $standardLookup = @{} + foreach ($row in $standardRows) { + if (-not $row -or [string]::IsNullOrWhiteSpace([string]$row.subscriptionId)) { continue } + $id = [string]$row.subscriptionId + if (-not $standardLookup.ContainsKey($id)) { + $standardLookup[$id] = [System.Collections.Generic.List[pscustomobject]]::new() + } + $standardLookup[$id].Add([pscustomobject]@{ + Standard = [string]$row.standard + State = [string]$row.state + PassedControls = [int]($row.passedControls) + FailedControls = [int]($row.failedControls) + SkippedControls = [int]($row.skippedControls) + UnsupportedControls = [int]($row.unsupportedControls) + }) + } + + foreach ($row in $scoreRows) { + if (-not $row -or [string]::IsNullOrWhiteSpace([string]$row.subscriptionId)) { continue } + $id = [string]$row.subscriptionId + $current = [double]($row.currentScore) + $max = [double]($row.maxScore) + # A maximum of zero means nothing was assessed. Reporting 0% there would read as a bad score + # rather than as no score, so the percentage stays null and the caller skips the subscription. + $percentage = if ($max -gt 0) { [math]::Round(($current / $max) * 100, 1) } else { $null } + + $result.Add([pscustomobject]@{ + SubscriptionId = $id + SubscriptionName = if ($nameLookup.ContainsKey($id)) { $nameLookup[$id] } else { $id } + Initiative = [string]$row.initiative + CurrentScore = $current + MaxScore = $max + ScorePercentage = $percentage + StandardList = if ($standardLookup.ContainsKey($id)) { @($standardLookup[$id]) } else { @() } + }) + } + + Write-Output $result -NoEnumerate +} diff --git a/powershell/tests/fixtures/golden/selection.json b/powershell/tests/fixtures/golden/selection.json index 05f976972c..c0faca9dba 100644 --- a/powershell/tests/fixtures/golden/selection.json +++ b/powershell/tests/fixtures/golden/selection.json @@ -1918,7 +1918,7 @@ "AD" ] }, - "SelectedCount": 588, + "SelectedCount": 589, "SelectedFamilies": [ "MT.1024", "MT.1059", @@ -2446,6 +2446,7 @@ "MT.1251", "MT.1252", "MT.1260", + "MT.1266", "ORCA.100", "ORCA.101", "ORCA.102", @@ -2527,7 +2528,7 @@ "AD" ] }, - "SelectedCount": 618, + "SelectedCount": 619, "SelectedFamilies": [ "MT.1024", "MT.1033", @@ -3087,6 +3088,7 @@ "MT.1251", "MT.1252", "MT.1260", + "MT.1266", "ORCA.100", "ORCA.101", "ORCA.102", @@ -3920,7 +3922,7 @@ "AD" ] }, - "SelectedCount": 574, + "SelectedCount": 575, "SelectedFamilies": [ "MT.1024", "MT.1033", @@ -4436,6 +4438,7 @@ "MT.1251", "MT.1252", "MT.1260", + "MT.1266", "ORCA.100", "ORCA.101", "ORCA.102", diff --git a/powershell/tests/functions/Test-MtAzureSecureScore.Tests.ps1 b/powershell/tests/functions/Test-MtAzureSecureScore.Tests.ps1 new file mode 100644 index 0000000000..d3678830e1 --- /dev/null +++ b/powershell/tests/functions/Test-MtAzureSecureScore.Tests.ps1 @@ -0,0 +1,188 @@ +Describe 'Azure secure score and regulatory compliance' { + BeforeAll { + Import-Module $PSScriptRoot/../../Maester.psd1 -Force + . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" + # Native test, its instance source and the internal helper; none is exported. + Use-MtModuleFunction -Name Test-MtAzureSecureScore, + Get-MtAzureSecureScoreInstance, + Get-MtAzureSecureScore + + function Get-TestSubscription { + param( + [double] $Current = 44, [double] $Max = 55, [string] $Name = 'Contoso Production', + [object] $Percentage = 80, [object[]] $Standards = $null + ) + if ($null -eq $Standards) { + $Standards = @( + [pscustomobject]@{ Standard = 'Azure-Security-Benchmark'; State = 'Failed'; PassedControls = 30; FailedControls = 4; SkippedControls = 1; UnsupportedControls = 0 } + ) + } + return [pscustomobject]@{ + SubscriptionId = '11111111-2222-3333-4444-555555555555' + SubscriptionName = $Name + Initiative = 'ascScore' + CurrentScore = $Current + MaxScore = $Max + ScorePercentage = $Percentage + StandardList = @($Standards) + } + } + } + + BeforeEach { + $script:TestResult = $null + $script:SkippedBecause = $null + $script:SkippedCustomReason = $null + $script:Severity = $null + + Mock -ModuleName Maester Add-MtTestResultDetail { + param($Result, $SkippedBecause, $SkippedCustomReason, $Severity) + + $script:TestResult = $Result + $script:SkippedBecause = $SkippedBecause + $script:SkippedCustomReason = $SkippedCustomReason + $script:Severity = $Severity + } + } + + Context 'MT.1266 secure score' { + It 'passes at the target and fails below it' { + $at = [pscustomobject]@{ Data = Get-TestSubscription -Percentage 80 } + Test-MtAzureSecureScore -Instance $at | Should -BeTrue -Because '80 meets a target of 80' + + $below = [pscustomobject]@{ Data = Get-TestSubscription -Percentage 79.9 } + Test-MtAzureSecureScore -Instance $below | Should -BeFalse + } + + It 'honours a target other than the default' { + $i = [pscustomobject]@{ Data = Get-TestSubscription -Percentage 85 } + + Test-MtAzureSecureScore -Instance $i -MinimumScorePercentage 90 | Should -BeFalse + Test-MtAzureSecureScore -Instance $i -MinimumScorePercentage 80 | Should -BeTrue + $script:TestResult | Should -Match 'against a target of \*\*80%\*\*' + } + + It 'skips with a reason when Defender for Cloud assessed nothing, rather than reporting zero' { + $i = [pscustomobject]@{ Data = Get-TestSubscription -Current 0 -Max 0 -Percentage $null } + + Test-MtAzureSecureScore -Instance $i | Should -BeNullOrEmpty + $script:SkippedBecause | Should -Be 'Custom' + $script:SkippedCustomReason | Should -Match 'maximum secure score is zero' + $script:TestResult | Should -BeNullOrEmpty -Because 'a skip reports the reason, not a score table' + } + + It 'escapes the subscription name in the skip reason too, not only in the result' { + $i = [pscustomobject]@{ Data = Get-TestSubscription -Current 0 -Max 0 -Percentage $null -Name '[Sign in again](https://phish.example)' } + + $null = Test-MtAzureSecureScore -Instance $i + $script:SkippedCustomReason | Should -Not -Match '\[Sign in again\]\(https' + $script:SkippedCustomReason | Should -Match '\\\[Sign in again\\\]' + } + + It 'reports the compliance standards as a summary, worst first' { + $i = [pscustomobject]@{ Data = Get-TestSubscription -Standards @( + [pscustomobject]@{ Standard = 'Azure-CIS-1.4.0'; State = 'Failed'; PassedControls = 10; FailedControls = 2; SkippedControls = 0; UnsupportedControls = 1 }, + [pscustomobject]@{ Standard = 'Azure-Security-Benchmark'; State = 'Failed'; PassedControls = 30; FailedControls = 9; SkippedControls = 1; UnsupportedControls = 0 } + ) } + + $null = Test-MtAzureSecureScore -Instance $i + $script:TestResult | Should -Match 'Regulatory compliance standards assigned to this subscription' + $benchmarkRow = ([regex]::Match($script:TestResult, '(?m)^\| Azure-Security-Benchmark .*$')).Index + $cisRow = ([regex]::Match($script:TestResult, '(?m)^\| Azure-CIS-1\\?\.4\\?\.0 .*$')).Index + $benchmarkRow | Should -BeLessThan $cisRow -Because 'nine failed controls outrank two' + } + + It 'says so when no standard is assigned, instead of showing an empty table' { + $i = [pscustomobject]@{ Data = Get-TestSubscription -Standards @() } + + $null = Test-MtAzureSecureScore -Instance $i + $script:TestResult | Should -Match 'No regulatory compliance standard is assigned' + $script:TestResult | Should -Not -Match '\| Standard \| State \|' + } + + It 'escapes a subscription name that contains markdown, so it cannot render as a link' { + $i = [pscustomobject]@{ Data = Get-TestSubscription -Name '[Sign in again](https://phish.example)' } + + $null = Test-MtAzureSecureScore -Instance $i + $script:TestResult | Should -Not -Match '\[Sign in again\]\(https' + $script:TestResult | Should -Match '\\\[Sign in again\\\]' + } + } + + Context 'Get-MtAzureSecureScoreInstance (MT.1266 instance source)' { + It 'emits one instance per subscription, and none when there is no score' { + Mock -ModuleName Maester Get-MtAzureSecureScore { @(Get-TestSubscription), @(Get-TestSubscription) } + @(Get-MtAzureSecureScoreInstance).Count | Should -Be 2 + + Mock -ModuleName Maester Get-MtAzureSecureScore { @() } + @(Get-MtAzureSecureScoreInstance).Count | Should -Be 0 + } + + It 'uses the subscription id as the instance id and names the subscription in the title' { + Mock -ModuleName Maester Get-MtAzureSecureScore { @(Get-TestSubscription -Name 'Contoso Production') } + + $instance = @(Get-MtAzureSecureScoreInstance)[0] + $instance.Id | Should -Be '11111111-2222-3333-4444-555555555555' + $instance.Title | Should -Match "subscription 'Contoso Production'" + } + } + + Context 'Get-MtAzureSecureScore' { + BeforeEach { + Mock -ModuleName Maester Invoke-MtAzureResourceGraphRequest { + param($Query, $ApiVersion) + + if ($Query -match 'securescores') { + return @([pscustomobject]@{ subscriptionId = 'sub-1'; currentScore = 44; maxScore = 55; initiative = 'ascScore' }, + [pscustomobject]@{ subscriptionId = 'sub-2'; currentScore = 0; maxScore = 0; initiative = 'ascScore' }) + } + if ($Query -match 'regulatorycompliancestandards') { + return @([pscustomobject]@{ subscriptionId = 'sub-1'; standard = 'Azure-Security-Benchmark'; state = 'Failed'; passedControls = 30; failedControls = 4; skippedControls = 1; unsupportedControls = 0 }) + } + return @([pscustomobject]@{ subscriptionId = 'sub-1'; subscriptionName = 'Contoso Production' }) + } + } + + It 'computes the percentage from the current and maximum score' { + # No @(): the helper writes the list with -NoEnumerate, so @() would wrap it in a single + # element and the filter would see the whole list rather than its rows. + $rows = Get-MtAzureSecureScore + + ($rows | Where-Object { $_.SubscriptionId -eq 'sub-1' }).ScorePercentage | Should -Be 80 -Because '44 of 55 is 80%' + } + + It 'leaves the percentage null when the maximum score is zero, rather than reporting zero per cent' { + # No @(): the helper writes the list with -NoEnumerate, so @() would wrap it in a single + # element and the filter would see the whole list rather than its rows. + $rows = Get-MtAzureSecureScore + + ($rows | Where-Object { $_.SubscriptionId -eq 'sub-2' }).ScorePercentage | Should -BeNullOrEmpty + } + + It 'falls back to the subscription id when the name is not readable' { + # No @(): the helper writes the list with -NoEnumerate, so @() would wrap it in a single + # element and the filter would see the whole list rather than its rows. + $rows = Get-MtAzureSecureScore + + ($rows | Where-Object { $_.SubscriptionId -eq 'sub-2' }).SubscriptionName | Should -Be 'sub-2' + } + + It 'attaches the standards to their own subscription only' { + # No @(): the helper writes the list with -NoEnumerate, so @() would wrap it in a single + # element and the filter would see the whole list rather than its rows. + $rows = Get-MtAzureSecureScore + + @(($rows | Where-Object { $_.SubscriptionId -eq 'sub-1' }).StandardList).Count | Should -Be 1 + @(($rows | Where-Object { $_.SubscriptionId -eq 'sub-2' }).StandardList).Count | Should -Be 0 + } + + It 'returns an empty list, not null, when there is no secure score, and asks for nothing else' { + Mock -ModuleName Maester Invoke-MtAzureResourceGraphRequest { @() } + + $rows = Get-MtAzureSecureScore + $null -ne $rows | Should -BeTrue + @($rows).Count | Should -Be 0 + Should -Invoke -ModuleName Maester Invoke-MtAzureResourceGraphRequest -Times 1 -Exactly -Because 'without a score there is nothing to enrich' + } + } +} diff --git a/tests/maester/azure/Test.MT.1266.md b/tests/maester/azure/Test.MT.1266.md new file mode 100644 index 0000000000..7d555a1b55 --- /dev/null +++ b/tests/maester/azure/Test.MT.1266.md @@ -0,0 +1,36 @@ +Ensure every Azure subscription **meets the Microsoft Defender for Cloud secure score target**. + +Defender for Cloud scores every subscription it covers against its recommendations and expresses the result as a percentage of the maximum achievable score. An assessor reads that number first and the individual recommendations afterwards. This check brings the number into a Maester run, **one result per subscription**, and carries the state of the regulatory compliance standards assigned to that subscription in the same result. + +A subscription **passes** when its secure score reaches the target and **fails** below it. The target is a business decision rather than a vendor rule, so it is a parameter: **80%** by default. + +```powershell +# Raise the bar for one subscription in the Maester config +TestSettings = @( + @{ Id = 'MT.1266.00000000-0000-0000-0000-000000000000'; Parameters = @{ MinimumScorePercentage = 90 } } +) +``` + +The percentage is computed from the current and maximum score rather than read from `properties.score.percentage`, whose unit the Azure samples present two different ways — the secure score page divides current by max itself while the Resource Graph sample projects the property directly. Dividing removes the ambiguity. + +## Regulatory compliance + +The standards assigned to the subscription are reported as a **summary table**: state, and how many controls passed, failed, were skipped or are unsupported. They are deliberately not separate results. The controls behind those numbers are the Defender for Cloud recommendations that `MT.1257` already reports one by one, and raising them again here would count the same finding twice. + +The Microsoft cloud security benchmark is assigned by default, so an empty list usually means it was removed rather than that nothing applies. Other standards, such as CIS Azure, need Defender CSPM. + +## When this is skipped + +- **The maximum score is zero.** Defender for Cloud produced a score row for the subscription but assessed nothing in it, so there is no percentage to compare. The subscription is still reported, with that reason: **no score is not a score of zero, and it is not a pass.** +- **No score at all.** When Defender for Cloud returns no secure score for the readable subscriptions, the instance source emits nothing and the engine skips the family with `NoInstances`. A tenant with no scored subscription has no score to meet. + +## How to remediate + +Open **Microsoft Defender for Cloud** → **Secure score**, which lists the security controls by how many points each would add. The points are weighted, so the controls at the top of that list move the number furthest. `MT.1257` reports the individual recommendations behind each control. + +## Permissions + +Read-only. Reader or Security Reader on the subscriptions, or on a management group above them. The queries run through Azure Resource Graph, so they cover every readable subscription in three calls regardless of how many subscriptions there are. + + +%TestResult% diff --git a/tests/maester/azure/Test.MT.1266.ps1 b/tests/maester/azure/Test.MT.1266.ps1 new file mode 100644 index 0000000000..d4d3d28420 --- /dev/null +++ b/tests/maester/azure/Test.MT.1266.ps1 @@ -0,0 +1,142 @@ +function Get-MtAzureSecureScoreInstance { + <# + .SYNOPSIS + Returns one MT.1266 instance per Azure subscription Microsoft Defender for Cloud scores. + + .DESCRIPTION + Instance source of the MT.1266 family. The suffix is the subscription ID (MT.1266.) + and the title names the subscription, so each subscription carries its own result and its own + history. + + Every subscription Defender for Cloud scored is emitted, including one whose maximum score is zero. + That subscription is skipped by the test with a reason rather than dropped here: a subscription the + user knows exists should not vanish from the report. + + When Defender for Cloud returns no score at all the source emits nothing and the engine skips the + family with NoInstances. A tenant with no scored subscription has no score to meet, and must never + be reported as meeting it. + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param() + + foreach ($subscription in Get-MtAzureSecureScore) { + [pscustomobject]@{ + Id = $subscription.SubscriptionId + Title = "The Defender for Cloud secure score of subscription '$($subscription.SubscriptionName)' should meet the target." + Data = $subscription + } + } +} + +function Test-MtAzureSecureScore { + <# + .SYNOPSIS + Checks that an Azure subscription meets the Microsoft Defender for Cloud secure score target. + + .DESCRIPTION + Defender for Cloud scores every subscription it covers against its recommendations and expresses the + result as a percentage of the maximum achievable score. An assessor reads that number first and the + individual recommendations afterwards. This check brings the number into a Maester run, one result + per subscription, and carries the state of the regulatory compliance standards assigned to that + subscription in the same result. + + A subscription passes when its secure score reaches MinimumScorePercentage and fails below it. The + target is a business decision rather than a vendor rule, so it is a parameter: 80 by default, and a + TestSettings row in the config can set another value per subscription instance. + + The regulatory compliance standards are reported as a summary table, not as separate results. Each + standard's controls are already covered by the Defender for Cloud recommendation check (MT.1257), + and reporting them twice would double count the same finding. + + .PARAMETER MinimumScorePercentage + The secure score percentage a subscription must reach to pass. 80 by default. + + .PARAMETER Instance + The subscription to check, supplied by the engine. + + .OUTPUTS + [bool] - True when the subscription reaches the target, false when it does not, null when skipped. + + .EXAMPLE + Test-MtAzureSecureScore + + Returns one result per scored Azure subscription. + + .LINK + https://maester.dev/docs/commands/Test-MtAzureSecureScore + #> + [MaesterTest( + Id = 'MT.1266', + Title = 'Azure subscriptions should meet the Microsoft Defender for Cloud secure score target.', + Product = 'azure', + RelatedProduct = 'defender', + Feature = 'subscriptions', + Area = 'infrastructure', + ResourceType = 'Tenant', + Severity = 'Medium', + UserImpact = 'Low', + ImplementationCost = 'Medium', + Mitre = 'None', + Lifecycle = 'Preview', + Service = 'Azure', + Permission = 'Azure:Role:Reader | Azure:Role:Security Reader', + InstanceSource = 'Get-MtAzureSecureScoreInstance', + Author = 'earbona23' + )] + [CmdletBinding()] + [OutputType([bool])] + param( + # The secure score percentage a subscription must reach to pass. + [ValidateRange(0, 100)] + [int] $MinimumScorePercentage = 80, + + # The subscription to check, supplied by the engine. + $Instance + ) + + $subscription = $Instance.Data + $name = Get-MtSafeMarkdown ([string]$subscription.SubscriptionName) + + if ($null -eq $subscription.ScorePercentage) { + # Defender for Cloud produced a score row with a maximum of zero, so it assessed nothing in this + # subscription. No score is not a score of zero, and it is certainly not a pass. + # $name, not the raw SubscriptionName: the reason is rendered as markdown like any other result + # text, and a subscription name is tenant-controlled. + Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Defender for Cloud assessed nothing in subscription '$name': its maximum secure score is zero, so there is no percentage to compare." + return $null + } + + $percentage = [double]$subscription.ScorePercentage + $testResult = $percentage -ge $MinimumScorePercentage + + $testResultMarkdown = "The Defender for Cloud secure score of **$name** is **$percentage%**, against a target of **$MinimumScorePercentage%**.`n`n" + $testResultMarkdown += "| Property | Value |`n| --- | --- |`n" + $testResultMarkdown += "| Subscription | $name |`n" + $testResultMarkdown += "| Subscription ID | ``$($subscription.SubscriptionId)`` |`n" + $testResultMarkdown += "| Secure score | $($subscription.CurrentScore) of $($subscription.MaxScore) points |`n" + $testResultMarkdown += "| Percentage | $percentage% |`n" + $testResultMarkdown += "| Target | $MinimumScorePercentage% |`n" + + $standards = @($subscription.StandardList | Where-Object { $_ -and -not [string]::IsNullOrWhiteSpace($_.Standard) }) + if ($standards.Count -gt 0) { + $testResultMarkdown += "`n**Regulatory compliance standards assigned to this subscription.** Reported as a summary: the controls behind these numbers are covered by MT.1257, and repeating them here would count the same finding twice.`n`n" + $testResultMarkdown += "| Standard | State | Passed | Failed | Skipped | Unsupported |`n| --- | --- | --- | --- | --- | --- |`n" + foreach ($standard in ($standards | Sort-Object -Property @{ Expression = { [int]$_.FailedControls } ; Descending = $true }, Standard)) { + $standardName = Get-MtSafeMarkdown ([string]$standard.Standard) + $state = Get-MtSafeMarkdown ([string]$standard.State) + $testResultMarkdown += "| $standardName | $state | $($standard.PassedControls) | $($standard.FailedControls) | $($standard.SkippedControls) | $($standard.UnsupportedControls) |`n" + } + } else { + $testResultMarkdown += "`nNo regulatory compliance standard is assigned to this subscription. The Microsoft cloud security benchmark is assigned by default, so an empty list usually means it was removed.`n" + } + + if ($testResult) { + $testResultMarkdown += "`nWell done. This subscription is at or above the secure score target." + } else { + $testResultMarkdown += "`nRaise the score in **Microsoft Defender for Cloud** → **Secure score**, which lists the controls by how many points each would add. The points are weighted, so the controls at the top of that list move the number furthest." + } + + Add-MtTestResultDetail -Result $testResultMarkdown + return $testResult +} From 0481ebc16c87a52e1a2b6c9e6fc8c0bac3e13065 Mon Sep 17 00:00:00 2001 From: Eduard Arbona Date: Fri, 6 Nov 2026 23:23:35 -0400 Subject: [PATCH 2/8] fix(MT.1266): ResourceType is AzureResource, not Tenant Tenant means one environment-wide setting, and each instance of this family reports one subscription's own score. AzureResource is the closest key the taxonomy has, and MT.1065 already uses it. Raised by the attribute review. --- tests/maester/azure/Test.MT.1266.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/maester/azure/Test.MT.1266.ps1 b/tests/maester/azure/Test.MT.1266.ps1 index d4d3d28420..dab6aee428 100644 --- a/tests/maester/azure/Test.MT.1266.ps1 +++ b/tests/maester/azure/Test.MT.1266.ps1 @@ -73,7 +73,7 @@ function Test-MtAzureSecureScore { RelatedProduct = 'defender', Feature = 'subscriptions', Area = 'infrastructure', - ResourceType = 'Tenant', + ResourceType = 'AzureResource', Severity = 'Medium', UserImpact = 'Low', ImplementationCost = 'Medium', From dd2f18976fa2e7f88edd66ebdd62374707b57b36 Mon Sep 17 00:00:00 2001 From: Eduard Arbona <175124143+earbona23@users.noreply.github.com> Date: Sat, 7 Nov 2026 13:04:54 -0400 Subject: [PATCH 3/8] fix(MT.1266): ask Azure for the default initiative only Secure score resources are per initiative, and the instance ID for this family is the subscription ID. A second initiative in one subscription therefore repeats the instance ID, and a repeated instance ID is not a soft failure: Invoke-MtNativePlan.ps1:325-331 returns a single InvalidInstanceId Error row for the whole family and evaluates nothing. One extra initiative anywhere in the estate would take MT.1266 out across all of it. 'ascScore' is the ASC Default initiative, per the Azure API's own parameter description, and Get-AzSecuritySecureScore documents the resource as /subscriptions//providers/Microsoft.Security/secureScores/ascScore. The new unit test honours the filter in the mock rather than asserting on the query text: without the name filter the mock answers with the two rows Azure would really return for one subscription, and the test fails. Verified both ways, 15 of 15 with the filter and exactly that one test red without it. Also drops the unused $ApiVersion from the mock's param block, which is code scanning alert 3155. --- .../services/azure/Get-MtAzureSecureScore.ps1 | 8 +++- .../Test-MtAzureSecureScore.Tests.ps1 | 37 ++++++++++++++++++- 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/powershell/internal/services/azure/Get-MtAzureSecureScore.ps1 b/powershell/internal/services/azure/Get-MtAzureSecureScore.ps1 index 1f29e7fb7d..70ed794685 100644 --- a/powershell/internal/services/azure/Get-MtAzureSecureScore.ps1 +++ b/powershell/internal/services/azure/Get-MtAzureSecureScore.ps1 @@ -1,4 +1,4 @@ -function Get-MtAzureSecureScore { +function Get-MtAzureSecureScore { <# .SYNOPSIS Returns one row per Azure subscription with the Microsoft Defender for Cloud secure score and the @@ -34,10 +34,16 @@ function Get-MtAzureSecureScore { [OutputType([System.Collections.Generic.List[pscustomobject]])] param() + # The name filter is not cosmetic. Score resources are per initiative, and the instance ID for + # this family is the subscription ID, so a second initiative in one subscription would produce a + # repeated instance ID. Invoke-MtNativePlan returns a single InvalidInstanceId Error row for the + # whole family in that case and evaluates nothing, so one extra initiative anywhere in the estate + # would take MT.1266 out everywhere. 'ascScore' is the ASC Default initiative, per the Azure API. # properties.score.max is cast because the score arrives as a dynamic value. $scoreQuery = @' securityresources | where type == "microsoft.security/securescores" +| where name == "ascScore" | extend currentScore = todouble(properties.score.current), maxScore = todouble(properties.score.max), initiative = tostring(properties.displayName) diff --git a/powershell/tests/functions/Test-MtAzureSecureScore.Tests.ps1 b/powershell/tests/functions/Test-MtAzureSecureScore.Tests.ps1 index d3678830e1..a18f777aa7 100644 --- a/powershell/tests/functions/Test-MtAzureSecureScore.Tests.ps1 +++ b/powershell/tests/functions/Test-MtAzureSecureScore.Tests.ps1 @@ -1,4 +1,4 @@ -Describe 'Azure secure score and regulatory compliance' { +Describe 'Azure secure score and regulatory compliance' { BeforeAll { Import-Module $PSScriptRoot/../../Maester.psd1 -Force . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" @@ -130,7 +130,7 @@ Describe 'Azure secure score and regulatory compliance' { Context 'Get-MtAzureSecureScore' { BeforeEach { Mock -ModuleName Maester Invoke-MtAzureResourceGraphRequest { - param($Query, $ApiVersion) + param($Query) if ($Query -match 'securescores') { return @([pscustomobject]@{ subscriptionId = 'sub-1'; currentScore = 44; maxScore = 55; initiative = 'ascScore' }, @@ -176,6 +176,39 @@ Describe 'Azure secure score and regulatory compliance' { @(($rows | Where-Object { $_.SubscriptionId -eq 'sub-2' }).StandardList).Count | Should -Be 0 } + It 'asks Azure for the default initiative only, so one subscription cannot yield two rows' { + # The instance ID for this family is the subscription ID, so two score rows for one + # subscription would repeat it, and Invoke-MtNativePlan answers a repeated instance ID + # with a single InvalidInstanceId Error row for the WHOLE family: one extra initiative + # anywhere would take MT.1266 out across the estate. Score resources are per initiative, + # so the query has to ask for the ASC Default one by name. + # + # The mock honours the filter instead of asserting on the query text: without the + # name filter it answers with the two rows Azure would really return, and this test + # fails. That is the point of writing it this way. + Mock -ModuleName Maester Invoke-MtAzureResourceGraphRequest { + param($Query) + + if ($Query -match 'securescores') { + if ($Query -match 'name == "ascScore"') { + return @([pscustomobject]@{ subscriptionId = 'sub-1'; currentScore = 44; maxScore = 55; initiative = 'ASC Default' }) + } + + return @([pscustomobject]@{ subscriptionId = 'sub-1'; currentScore = 44; maxScore = 55; initiative = 'ASC Default' }, + [pscustomobject]@{ subscriptionId = 'sub-1'; currentScore = 10; maxScore = 90; initiative = 'Custom initiative' }) + } + if ($Query -match 'regulatorycompliancestandards') { return @() } + return @([pscustomobject]@{ subscriptionId = 'sub-1'; subscriptionName = 'Contoso Production' }) + } + + # No @(): the helper writes the list with -NoEnumerate, so @() would wrap it in a single + # element and the filter would see the whole list rather than its rows. + $rows = Get-MtAzureSecureScore + + @($rows | Where-Object { $_.SubscriptionId -eq 'sub-1' }).Count | Should -Be 1 -Because 'one subscription is one instance, whatever initiatives it carries' + ($rows | Where-Object { $_.SubscriptionId -eq 'sub-1' }).ScorePercentage | Should -Be 80 -Because 'the default initiative is the one that counts' + } + It 'returns an empty list, not null, when there is no secure score, and asks for nothing else' { Mock -ModuleName Maester Invoke-MtAzureResourceGraphRequest { @() } From 7df8b713702e15a6f1cf59c5fa3a7744bb6bbbb6 Mon Sep 17 00:00:00 2001 From: Eduard Arbona <175124143+earbona23@users.noreply.github.com> Date: Sat, 7 Nov 2026 17:06:57 -0400 Subject: [PATCH 4/8] chore: save the new PowerShell files as UTF-8 with BOM Per the ruling on #2663: every .ps1, .psm1 and .psd1 is UTF-8 with a byte order mark. These files were written without one, so they would fail the check #2714 adds once it lands. Only the three bytes EF BB BF are prepended; nothing else in the files changes. --- tests/maester/azure/Test.MT.1266.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/maester/azure/Test.MT.1266.ps1 b/tests/maester/azure/Test.MT.1266.ps1 index dab6aee428..98d1aca558 100644 --- a/tests/maester/azure/Test.MT.1266.ps1 +++ b/tests/maester/azure/Test.MT.1266.ps1 @@ -1,4 +1,4 @@ -function Get-MtAzureSecureScoreInstance { +function Get-MtAzureSecureScoreInstance { <# .SYNOPSIS Returns one MT.1266 instance per Azure subscription Microsoft Defender for Cloud scores. From e50565c93e9b7efb7e9aefa09c626b085c06aec2 Mon Sep 17 00:00:00 2001 From: Merill Fernando Date: Sun, 8 Nov 2026 12:40:35 +1100 Subject: [PATCH 5/8] fix(azure): MT.1266 compares the unrounded secure score with the target Get-MtAzureSecureScore rounded the percentage to one decimal before MT.1266 compared it with the target, so 79.96% read as 80.0 and passed an 80% target. The helper now returns the exact percentage, computed in decimal so that 57 of 100 is 57 and not 56.99999999999999. MT.1266 compares that value and shows it cut, not rounded, to one decimal, so a score just under the target never reads as reaching it. Co-Authored-By: Claude Opus 5.5 Entire-Checkpoint: 01M6WD10PJBN5SGSRR904FSFMQ --- .../services/azure/Get-MtAzureSecureScore.ps1 | 5 +++- .../Test-MtAzureSecureScore.Tests.ps1 | 24 +++++++++++++++++++ tests/maester/azure/Test.MT.1266.ps1 | 6 +++-- 3 files changed, 32 insertions(+), 3 deletions(-) diff --git a/powershell/internal/services/azure/Get-MtAzureSecureScore.ps1 b/powershell/internal/services/azure/Get-MtAzureSecureScore.ps1 index 70ed794685..e6f2882cac 100644 --- a/powershell/internal/services/azure/Get-MtAzureSecureScore.ps1 +++ b/powershell/internal/services/azure/Get-MtAzureSecureScore.ps1 @@ -117,7 +117,10 @@ resourcecontainers $max = [double]($row.maxScore) # A maximum of zero means nothing was assessed. Reporting 0% there would read as a bad score # rather than as no score, so the percentage stays null and the caller skips the subscription. - $percentage = if ($max -gt 0) { [math]::Round(($current / $max) * 100, 1) } else { $null } + # Not rounded: the caller compares it with the target, and 79.96 rounded to 80.0 would pass a target + # of 80. Round only for display. Decimal, not double: in double 57 of 100 is 56.99999999999999 and would + # miss a target of 57. + $percentage = if ($max -gt 0) { [double]([decimal]$current * 100 / [decimal]$max) } else { $null } $result.Add([pscustomobject]@{ SubscriptionId = $id diff --git a/powershell/tests/functions/Test-MtAzureSecureScore.Tests.ps1 b/powershell/tests/functions/Test-MtAzureSecureScore.Tests.ps1 index a18f777aa7..a5126eff79 100644 --- a/powershell/tests/functions/Test-MtAzureSecureScore.Tests.ps1 +++ b/powershell/tests/functions/Test-MtAzureSecureScore.Tests.ps1 @@ -54,6 +54,13 @@ Test-MtAzureSecureScore -Instance $below | Should -BeFalse } + It 'fails a score just under the target, and shows it under the target' { + $i = [pscustomobject]@{ Data = Get-TestSubscription -Percentage 79.96 } + + Test-MtAzureSecureScore -Instance $i | Should -BeFalse -Because '79.96 is below a target of 80' + $script:TestResult | Should -Match 'is \*\*79\.9%\*\*' + } + It 'honours a target other than the default' { $i = [pscustomobject]@{ Data = Get-TestSubscription -Percentage 85 } @@ -151,6 +158,23 @@ ($rows | Where-Object { $_.SubscriptionId -eq 'sub-1' }).ScorePercentage | Should -Be 80 -Because '44 of 55 is 80%' } + It 'returns the percentage unrounded, so the test compares the exact value with the target' -ForEach @( + @{ Current = 79.96; Max = 100; Expected = 79.96 } + @{ Current = 57; Max = 100; Expected = 57 } + @{ Current = 1; Max = 3; Expected = 100 / 3 } + ) { + Mock -ModuleName Maester Invoke-MtAzureResourceGraphRequest { + param($Query) + if ($Query -match 'securescores') { return @([pscustomobject]@{ subscriptionId = 'sub-1'; currentScore = $Current; maxScore = $Max; initiative = 'ascScore' }) } + return @() + }.GetNewClosure() + + # No @(): the helper writes the list with -NoEnumerate. + $rows = Get-MtAzureSecureScore + + ($rows | Where-Object { $_.SubscriptionId -eq 'sub-1' }).ScorePercentage | Should -Be $Expected + } + It 'leaves the percentage null when the maximum score is zero, rather than reporting zero per cent' { # No @(): the helper writes the list with -NoEnumerate, so @() would wrap it in a single # element and the filter would see the whole list rather than its rows. diff --git a/tests/maester/azure/Test.MT.1266.ps1 b/tests/maester/azure/Test.MT.1266.ps1 index 98d1aca558..812b58e7a2 100644 --- a/tests/maester/azure/Test.MT.1266.ps1 +++ b/tests/maester/azure/Test.MT.1266.ps1 @@ -107,8 +107,10 @@ function Test-MtAzureSecureScore { return $null } - $percentage = [double]$subscription.ScorePercentage - $testResult = $percentage -ge $MinimumScorePercentage + # Compare the exact percentage. The one shown is cut, not rounded, to one decimal, so a score just under the + # target never reads as reaching it (79.96 shows as 79.9, not 80). + $testResult = [double]$subscription.ScorePercentage -ge $MinimumScorePercentage + $percentage = [math]::Floor([double]$subscription.ScorePercentage * 10) / 10 $testResultMarkdown = "The Defender for Cloud secure score of **$name** is **$percentage%**, against a target of **$MinimumScorePercentage%**.`n`n" $testResultMarkdown += "| Property | Value |`n| --- | --- |`n" From 1a244f703e340c082bcfe366cf85b82f236aa029 Mon Sep 17 00:00:00 2001 From: Eduard Arbona <175124143+earbona23@users.noreply.github.com> Date: Sun, 8 Nov 2026 10:57:32 -0400 Subject: [PATCH 6/8] style: canonical attribute property order Ran the files through build/migration/Convert-MtTestAttributes.ps1, which the repo uses to keep [MaesterTest(...)] properties in one order. main reports Reordered=0 and these were the only files in the tree that did not, which came from how they were written rather than from any change in behaviour. The tool now reports Changed=0 Reordered=0 here too. No values were altered. --- tests/maester/azure/Test.MT.1266.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/maester/azure/Test.MT.1266.ps1 b/tests/maester/azure/Test.MT.1266.ps1 index 812b58e7a2..7bcf07e700 100644 --- a/tests/maester/azure/Test.MT.1266.ps1 +++ b/tests/maester/azure/Test.MT.1266.ps1 @@ -78,9 +78,9 @@ function Test-MtAzureSecureScore { UserImpact = 'Low', ImplementationCost = 'Medium', Mitre = 'None', - Lifecycle = 'Preview', Service = 'Azure', Permission = 'Azure:Role:Reader | Azure:Role:Security Reader', + Lifecycle = 'Preview', InstanceSource = 'Get-MtAzureSecureScoreInstance', Author = 'earbona23' )] From 267a33efecf8ba469af0de559f571c08cebe32ad Mon Sep 17 00:00:00 2001 From: Eduard Arbona Date: Wed, 11 Nov 2026 11:48:38 -0400 Subject: [PATCH 7/8] chore(website): regenerate the test builder data for the new parameter #2758 added test parameters to website/src/data/test-builder.json, so a branch that declares one has to regenerate it with build/website/Update-MtTestBuilderData.ps1. TestBuilderData.Tests.ps1 fails otherwise. --- website/src/data/test-builder.json | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/website/src/data/test-builder.json b/website/src/data/test-builder.json index 2b025d35ea..a63c0e6742 100644 --- a/website/src/data/test-builder.json +++ b/website/src/data/test-builder.json @@ -18524,6 +18524,11 @@ "type": "int", "tests": 1 }, + { + "name": "MinimumScorePercentage", + "type": "int", + "tests": 1 + }, { "name": "ParkedDomains", "type": "string[]", From c92055a6d4f6f0fd6be9524e2826fc5f71d15f40 Mon Sep 17 00:00:00 2001 From: Eduard Arbona <175124143+earbona23@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:01:46 -0400 Subject: [PATCH 8/8] fix(azure): bind the secure score list before enumerating it (MT.1266) --- tests/maester/azure/Test.MT.1266.ps1 | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/maester/azure/Test.MT.1266.ps1 b/tests/maester/azure/Test.MT.1266.ps1 index 7bcf07e700..ed665b01cb 100644 --- a/tests/maester/azure/Test.MT.1266.ps1 +++ b/tests/maester/azure/Test.MT.1266.ps1 @@ -20,7 +20,9 @@ [OutputType([pscustomobject])] param() - foreach ($subscription in Get-MtAzureSecureScore) { + $scores = Get-MtAzureSecureScore + + foreach ($subscription in $scores) { [pscustomobject]@{ Id = $subscription.SubscriptionId Title = "The Defender for Cloud secure score of subscription '$($subscription.SubscriptionName)' should meet the target."