diff --git a/.github/skills/maester-test-expert/SKILL.md b/.github/skills/maester-test-expert/SKILL.md index 3ec07b238a..700bb747e7 100644 --- a/.github/skills/maester-test-expert/SKILL.md +++ b/.github/skills/maester-test-expert/SKILL.md @@ -190,6 +190,7 @@ in [Choosing the attribute values](#choosing-the-attribute-values). | `ImplementationCost` | string | `Low`, `Medium`, `High` | Yes, unless `Severity` is `Info` | Leave it out of an `Info` check. | | `Mitre` | string[] | ATT&CK technique IDs (`T1110`, `T1110.003`), or the single value `None` | Yes | At most five. Never a technique beside one of its own sub-techniques. | | `Control` | string[] | `:` | CIS, CISA and ASD checks | The requirements the check implements or supports. A CIS check sets `Control = 'cis-m365:5.1.5.1'`, a CISA check `Control = 'cisa-scuba:MS.AAD.3.1'`, an ASD check `Control = 'essential-eight:ISM-1504'`; any other check may name the same requirements. The first one that a framework file knows becomes the `Benchmark` of the result. For a shipped framework the requirement must exist in its file. | +| `Step` | string[] | Step IDs `.` from `powershell/assets/steps` | No | The steps of the defender's path the check verifies, at most three. See [Steps of the defender's path](#steps-of-the-defenders-path-step). | | `Service` | string[] | `Graph`, `Azure`, `ExchangeOnline`, `SecurityCompliance`, `SharePointOnline`, `Teams`, `Dataverse`, `AzureDevOps`, `GitHub`, `ActiveDirectory`, or `None` | Yes | All listed must be connected. Registry: `powershell/assets/MaesterServiceRegistry.psd1`. | | `License` | string[] | Tokens from `powershell/assets/MaesterLicenseTable.psd1`; `A&B` = both | No | Tenant needs any one element. | | `Permission` | string[] | `::`; `\|` joins alternatives | No | The permissions the check needs, for example `'Graph:Scope:Policy.Read.All'`. Every element is needed; inside an element any one alternative is enough, least privileged first. The service must be in `Service`, the kind one the service registry lists for it. Recorded; not enforced in 3.0. See "Permission" in `website/docs/writing-tests/index.mdx`. | @@ -411,6 +412,23 @@ only when nothing applies. It is the only way a check is mapped to a framework. The first value that names a requirement in a framework file becomes the `Benchmark` of the result, so the order matters. An inventory count, or a health, licensing or tidiness check, usually lists nothing. +### Steps of the defender's path (`Step`) + +`Step` names the steps of the defender's path a check verifies: one change or one tenant state from the step +catalogue (`powershell/assets/steps/.json`), such as `entra.ca-require-compliant-device`. The catalogue +says what has to be done before each step, citing Microsoft Learn. Look for a step whenever a check is about a +change that Learn says needs something else in place first. + +- Name a step only when a tenant set up the way the step's Learn sources describe passes the check. A check that + rejects a control Learn now recommends names no step until it is fixed. +- Checks with different definitions of done name different steps, even when they read the same setting. Checks in + different suites that test the same thing name the same step. +- At most three. A built-in check names only steps that are in the catalogue; add a new step there, in Maester's own + words with a Learn URL without a locale, `Reviewed`, and `Unchecked` or `Measure` where they apply, in the same pull + request. +- Rules and the catalogue format: "Step" in `website/docs/writing-tests/index.mdx` and the Step section of the + attribute rubric. `Get-MtTest -Step ` lists the checks that already name a step. + ### A requirement another suite already checks (shims) Benchmarks overlap: CIS, CISA, ASD and Maester tests often read the same setting. Before writing a check for a diff --git a/.github/workflows/step-sources.yaml b/.github/workflows/step-sources.yaml new file mode 100644 index 0000000000..7cf8f19e57 --- /dev/null +++ b/.github/workflows/step-sources.yaml @@ -0,0 +1,96 @@ +# Checks the Microsoft Learn pages that the defender's path catalogue cites (powershell/assets/steps) against the +# Learn mirrors, and keeps one issue open (labelled step-sources) that lists the steps whose sources changed since +# a maintainer last reviewed them, with a link to each change. Every run updates that issue; it is closed when every +# source is current again, and the next change opens a new one. The workflow never opens pull requests: a maintainer +# re-reads each page, updates the step if Learn changed the order, and sets the source's Reviewed date. +# See build/steps/README.md. +name: step-sources + +on: + workflow_dispatch: + schedule: + - cron: '41 5 * * 1' + +permissions: {} + +concurrency: + group: step-sources + cancel-in-progress: false + +env: + SOURCES_LABEL: step-sources + SOURCES_TITLE: "Defender's path: step sources changed on Microsoft Learn" + +jobs: + step-sources: + runs-on: ubuntu-latest + timeout-minutes: 30 + permissions: + contents: read + issues: write + + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + sparse-checkout: | + build/steps + powershell/assets/steps + + - name: Update the Learn mirrors + shell: pwsh + run: ./build/steps/Update-MtLearnMirror.ps1 -Links Catalog | Out-Null + + - name: Check the step sources + id: check + shell: pwsh + env: + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + $out = Join-Path $env:RUNNER_TEMP 'step-sources' + $null = ./build/steps/Test-MtStepSource.ps1 -OutputPath $out + $code = $LASTEXITCODE + if ($code -notin 0, 1) { throw "Test-MtStepSource.ps1 could not check the sources (exit code $code)." } + # An issue body holds at most 65,536 characters. A longer report is cut at a line and points to the artifact. + $body = (Get-Content -LiteralPath (Join-Path $out 'step-sources.md') -Raw).TrimEnd() + $footer = "`n`nFrom [this run]($env:RUN_URL) of the step-sources workflow." + if ($body.Length -gt 60000) { + $body = $body.Substring(0, $body.LastIndexOf("`n", 60000)) + "`n`nThe list is cut short here. The step-sources artifact of the run has all of it." + } + Set-Content -LiteralPath (Join-Path $env:RUNNER_TEMP 'step-sources-issue.md') -Value ($body + $footer) -Encoding utf8NoBOM + "needs-review=$(if ($code -eq 1) { 'true' } else { 'false' })" | Out-File -FilePath $env:GITHUB_OUTPUT -Append -Encoding utf8 + # Sources that need review are reported in the issue, not as a failed run. + exit 0 + + - name: Keep the report + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: step-sources + path: ${{ runner.temp }}/step-sources/ + retention-days: 30 + + - name: Open, update or close the step sources issue + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + NEEDS_REVIEW: ${{ steps.check.outputs.needs-review }} + run: | + set -euo pipefail + body="$RUNNER_TEMP/step-sources-issue.md" + issue=$(gh issue list --label "$SOURCES_LABEL" --state open --limit 1 --json number --jq '.[0].number // empty') + if [ "$NEEDS_REVIEW" = "true" ]; then + if [ -n "$issue" ]; then + gh issue edit "$issue" --body-file "$body" + echo "Updated issue #$issue." + else + gh label create "$SOURCES_LABEL" --color c5def5 --description "A Learn page that the step catalogue cites changed" --force + url=$(gh issue create --title "$SOURCES_TITLE" --body-file "$body" --label "$SOURCES_LABEL") + echo "Opened ${url}." + fi + elif [ -n "$issue" ]; then + gh issue edit "$issue" --body-file "$body" + gh issue close "$issue" --reason completed --comment "Every step source matches the page it was reviewed against. The next change opens a new issue." + echo "Closed issue #$issue." + else + echo "Every step source matches the page it was reviewed against." + fi diff --git a/.gitignore b/.gitignore index 07ea343bb4..b57fa8f98c 100644 --- a/.gitignore +++ b/.gitignore @@ -571,3 +571,7 @@ website/src/data/sponsors.json website/public/readme/ website/docs/commands/*.mdx !website/docs/commands/readme.mdx +website/docs/defenders-path/*.md + +# Learn mirror clones and the step tooling's index (build/steps/Update-MtLearnMirror.ps1) +build/steps/.cache/ diff --git a/build/Build-MaesterModule.ps1 b/build/Build-MaesterModule.ps1 index 43cac602f1..2d526600ac 100644 --- a/build/Build-MaesterModule.ps1 +++ b/build/Build-MaesterModule.ps1 @@ -692,6 +692,9 @@ foreach ($MarkdownFile in $MarkdownFiles) { # :, on a framework key that two suites declare, and on a test whose Control # names one of these frameworks and a requirement its file does not have. A test's Benchmark in the # catalog is the requirement its Control names, with the facts the framework file holds about it. +# It fails too on a problem in the step catalogue (powershell/assets/steps) and on a test or pack that names a +# step the catalogue does not have. Whether every step is named by a test is a unit test (StepCatalog.Tests.ps1), +# because the build may be given a folder that holds only some of the tests. # The source module is imported in a separate runspace, so the caller's session (which may itself have # Maester loaded, as in the module's own tests) is not changed. $CatalogResult = [pscustomobject]@{ Tests = @(); Problems = @(); Suites = @{}; Version = $SourceManifest.ModuleVersion; GraphScope = @(); Taxonomy = $null } @@ -715,6 +718,8 @@ if ($NativeTestFiles.Count -gt 0) { $CatalogRunspace = [powershell]::Create(); t foreach ($message in @(Get-MtAttackTechniqueProblem -Mitre $t.Mitre)) { "$($t.File): $message" } } $problems = @($problems) + @(Get-MtFrameworkProblem -Test $tests -Root $TestsRoot) + # The step catalogue of the defender's path, and the steps the tests and the packs name. + $problems = @($problems) + @(Get-MtStepProblem -Test $tests -PackRoot (Join-Path (Split-Path -Path $TestsRoot -Parent) 'packs')) $suites = @{} foreach ($manifest in Get-ChildItem -Path $TestsRoot -Filter 'suite.json' -Recurse -File) { $suite = Get-Content -LiteralPath $manifest.FullName -Raw | ConvertFrom-Json diff --git a/build/docs/Export-MtTestCatalogForDocs.ps1 b/build/docs/Export-MtTestCatalogForDocs.ps1 index 33afe3402c..0da788badf 100644 --- a/build/docs/Export-MtTestCatalogForDocs.ps1 +++ b/build/docs/Export-MtTestCatalogForDocs.ps1 @@ -14,7 +14,8 @@ A test of a suite that implements a published benchmark also has Benchmark, from the framework file of its suite (tests//frameworks/.json): Framework, Version, Requirement and the requirement's own facts, such as the CIS level and profiles. Its Control lists the controls of other frameworks that the - requirement relates to. Benchmark is null for every other test. Frameworks at the top level gives the Name, + requirement relates to. Benchmark is null for every other test. Step lists the steps of the defender's path + the test verifies (powershell/assets/steps), which the goal pages of the site list. Frameworks at the top level gives the Name, Version and Url of each framework by Key. Packs lists the packs that ship with Maester (packs//maester-pack.json) with the tests of their catalog, @@ -88,6 +89,7 @@ $catalog = foreach ($t in $sorted) { ImplementationCost = if ($t.ImplementationCost) { "$($t.ImplementationCost)" } else { '' } Mitre = ConvertTo-StringArray $t.Mitre Control = ConvertTo-StringArray $t.Control + Step = ConvertTo-StringArray $t.Step Benchmark = $t.Benchmark Service = ConvertTo-StringArray $t.Service License = ConvertTo-StringArray $t.License diff --git a/build/eidsca/Update-EidscaTests.ps1 b/build/eidsca/Update-EidscaTests.ps1 index 2388328f34..426c0bc875 100644 --- a/build/eidsca/Update-EidscaTests.ps1 +++ b/build/eidsca/Update-EidscaTests.ps1 @@ -15,7 +15,7 @@ files exactly. CI reruns it and fails on drift (powershell/tests/general/EidscaGenerator.Tests.ps1). Severity comes from the EIDSCA config, which is the source of truth for it. The Maester classification attributes that the EIDSCA config does not carry (RelatedProduct, Feature, Area, ResourceType, UserImpact, ImplementationCost, - Mitre and Control) come from eidsca-test-metadata.json and Author/Contributor from the authorship seed (design + Mitre, Control and Step) come from eidsca-test-metadata.json and Author/Contributor from the authorship seed (design section 11), so regeneration keeps them. Edit the metadata file, never the generated tests. A check without a metadata row is generated with a warning and fails the attribute unit tests until the row is added. @@ -51,7 +51,7 @@ param ( [string] $PageTitleCachePath = "$PSScriptRoot/PageTitles.json", # Maester classification of each check that the EIDSCA config does not carry: TestSettings rows with Id and the - # RelatedProduct, Feature, Area, ResourceType, UserImpact, ImplementationCost, Mitre and Control. Read only. + # RelatedProduct, Feature, Area, ResourceType, UserImpact, ImplementationCost, Mitre, Control and Step. Read only. [string] $MaesterConfigPath = "$PSScriptRoot/eidsca-test-metadata.json", # Authorship seed with the author and contributors of each check (design section 11). @@ -573,6 +573,7 @@ function GetMaesterTestAttribute($meta) { } if ($meta.Mitre.Count -gt 0) { $lines.Add(" Mitre = $(FormatAttributeList $meta.Mitre)") } if ($meta.Control.Count -gt 0) { $lines.Add(" Control = $(FormatAttributeList $meta.Control)") } + if ($meta.Step.Count -gt 0) { $lines.Add(" Step = $(FormatAttributeList $meta.Step)") } $lines.Add(" Service = $(FormatAttributeList $meta.Service)") if ($meta.License.Count -gt 0) { $lines.Add(" License = $(FormatAttributeList $meta.License)") } if ($meta.Author.Count -gt 0) { $lines.Add(" Author = $(FormatAttributeList $meta.Author)") } @@ -719,6 +720,7 @@ foreach ($control in $aadsc) { ImplementationCost = if (-not $isInfo) { & $metadataValue 'ImplementationCost' } Mitre = @(& $metadataValue 'Mitre' | Where-Object { $_ }) Control = @(& $metadataValue 'Control' | Where-Object { $_ }) + Step = @(& $metadataValue 'Step' | Where-Object { $_ }) Service = @('Graph') License = @($skipCheck.License) Author = $authors diff --git a/build/eidsca/eidsca-test-metadata.json b/build/eidsca/eidsca-test-metadata.json index d55e051382..26ff89a051 100644 --- a/build/eidsca/eidsca-test-metadata.json +++ b/build/eidsca/eidsca-test-metadata.json @@ -13,6 +13,9 @@ "Control": [ "nist-800-53-r5:IA-2(1)", "nist-800-53-r5:IA-2(2)" + ], + "Step": [ + "entra.passkeys-enabled" ] }, { @@ -24,6 +27,9 @@ "ImplementationCost": "Low", "Mitre": [ "T1566.002" + ], + "Step": [ + "entra.passkeys-enabled" ] }, { @@ -423,6 +429,9 @@ "ImplementationCost": "Low", "Mitre": [ "None" + ], + "Step": [ + "entra.temporary-access-pass" ] }, { diff --git a/build/orca/Update-OrcaTests.ps1 b/build/orca/Update-OrcaTests.ps1 index de6bda72e1..cb95cbe227 100644 --- a/build/orca/Update-OrcaTests.ps1 +++ b/build/orca/Update-OrcaTests.ps1 @@ -17,8 +17,8 @@ Each upstream check becomes a Maester 3.0 native test (design sections 3 and 14): tests/orca/Test.ORCA..ps1 with one [MaesterTest] function, and tests/orca/Test.ORCA..md. Maester metadata that ORCA does not carry (severity, author, contributors and the classification - attributes RelatedProduct, Feature, Area, ResourceType, UserImpact, ImplementationCost and Mitre) is - read from build/orca/orca-test-metadata.json. Edit that file, never the generated tests. + attributes RelatedProduct, Feature, Area, ResourceType, UserImpact, ImplementationCost, Mitre, Control + and Step) is read from build/orca/orca-test-metadata.json. Edit that file, never the generated tests. .PARAMETER Offline Regenerates only the native tests from the committed check files. Nothing is downloaded. @@ -352,6 +352,7 @@ foreach ($check in $checks) { } if ($meta.Mitre) { $attribute.Add("Mitre = $(Format-OrcaList @($meta.Mitre))") } if ($meta.Control) { $attribute.Add("Control = $(Format-OrcaList @($meta.Control))") } + if ($meta.Step) { $attribute.Add("Step = $(Format-OrcaList @($meta.Step))") } $attribute.Add("Service = $(Format-OrcaList $services)") # Defender for Office 365 Plan 1 or 2. ORCA detects MDO itself and reports 'not completed' without it. if ($check.Services -eq 'MDO') { $attribute.Add("License = 'ATP_ENTERPRISE'") } diff --git a/build/orca/orca-test-metadata.json b/build/orca/orca-test-metadata.json index c8d0d5080f..64fd38d27d 100644 --- a/build/orca/orca-test-metadata.json +++ b/build/orca/orca-test-metadata.json @@ -177,6 +177,9 @@ ], "Control": [ "nist-800-53-r5:SC-8" + ], + "Step": [ + "defender.dkim" ] }, "ORCA.108.1": { @@ -198,6 +201,9 @@ ], "Control": [ "nist-800-53-r5:SC-8" + ], + "Step": [ + "defender.dkim" ] }, "ORCA.109": { @@ -1164,6 +1170,9 @@ ], "Control": [ "nist-800-53-r5:SI-8" + ], + "Step": [ + "defender.spf-hard-fail" ] }, "ORCA.236": { diff --git a/build/steps/Find-MtStepCandidate.ps1 b/build/steps/Find-MtStepCandidate.ps1 new file mode 100644 index 0000000000..56adc5de32 --- /dev/null +++ b/build/steps/Find-MtStepCandidate.ps1 @@ -0,0 +1,471 @@ +<# +.SYNOPSIS +Finds what Microsoft Learn says must come first on the pages that check guides and step sources link, and writes it +as proposals for a maintainer to review. + +.DESCRIPTION +The defender's path catalogue (powershell/assets/steps) orders fixes the way Learn documents them. This script +reads the mirror file of every Learn page that a check guide (tests/**/Test.*.md) or a step source links, through +the index that Update-MtLearnMirror.ps1 writes, and pulls out: + +- Sections whose heading says they list prerequisites: "Prerequisites", "Before you begin", "Requirements", + "License requirements" and the like. The whole section is kept. +- Sentences outside those sections with an ordering cue (-Cue): "before you", "first", "must", "requires" or + "prerequisite", "won't work without" and its variants, "only after". + +Each proposal records the mirror file and line, a link to that line on GitHub, the heading it sits under and the cues +it matched. The page records its title, ms.topic, the steps and tests that link it, and source_path and +original_content_git_url from its front matter. + +The proposals are written to a JSON file for a maintainer to review (-OutputPath). They quote Learn, so they are +reading material, never catalogue text: a step's Note is written in Maester's own words. Nothing is written to the +catalogue. + +With -SuggestNote, the script also asks a model (the Claude API, with the key in ANTHROPIC_API_KEY) to propose Note +text in its own words for the first -MaxPages pages with proposals. Each suggestion is checked: one line, at most +200 characters, and no run of -MaxSharedWords or more words copied from the page. A suggestion that fails is kept +with Accepted false and the reason. It is off by default and is still only a proposal. + +.PARAMETER Root +The repository root. + +.PARAMETER CachePath +The cache folder that Update-MtLearnMirror.ps1 writes. Defaults to build/steps/.cache. + +.PARAMETER CatalogPath +The step catalogue folder. Defaults to powershell/assets/steps under -Root. + +.PARAMETER Links +Which links to read: All (check guides and step sources, the default), Guides or Catalog. + +.PARAMETER Url +Read only the pages whose URL or key matches one of these wildcard patterns. + +.PARAMETER Cue +The sentence cues to look for. Defaults to all of them. + +.PARAMETER OutputPath +The JSON file to write. Defaults to step-candidates.json in the cache folder. + +.PARAMETER SuggestNote +Ask a model to propose Note text for each page with proposals. + +.PARAMETER Model +The Claude model -SuggestNote uses. + +.PARAMETER MaxPages +The most pages -SuggestNote sends to the model. + +.PARAMETER MaxSharedWords +A suggested Note that shares this many words in a row with the page is rejected as copied. + +.EXAMPLE +./build/steps/Find-MtStepCandidate.ps1 + +Writes build/steps/.cache/step-candidates.json with the proposals from every linked page. + +.EXAMPLE +./build/steps/Find-MtStepCandidate.ps1 -Links Catalog -Url '*conditional-access*' -SuggestNote + +Reads the Conditional Access pages that step sources cite, and asks the model for Note text for each. +#> +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWriteHost', '', Justification = 'Build script output for the console')] +[CmdletBinding()] +param( + [string] $Root = (Resolve-Path (Join-Path $PSScriptRoot '../..')).Path, + + [string] $CachePath = (Join-Path $PSScriptRoot '.cache'), + + [string] $CatalogPath, + + [ValidateSet('All', 'Guides', 'Catalog')] + [string] $Links = 'All', + + [string[]] $Url, + + [ValidateSet('before-you', 'first', 'must', 'requires', 'without', 'only-after')] + [string[]] $Cue = @('before-you', 'first', 'must', 'requires', 'without', 'only-after'), + + [string] $OutputPath, + + [switch] $SuggestNote, + + [string] $Model = $(if ($env:MAESTER_STEP_MODEL) { $env:MAESTER_STEP_MODEL } else { 'claude-sonnet-5-5' }), + + [ValidateRange(1, 500)] + [int] $MaxPages = 10, + + [ValidateRange(4, 50)] + [int] $MaxSharedWords = 8 +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' +foreach ($helper in Get-ChildItem -Path (Join-Path $PSScriptRoot 'helpers') -Filter '*.ps1') { . $helper.FullName } + +# The sentence cues. "first" leaves out the phrases where it says nothing about order, and "requires" leaves out the +# bare verb, which in Conditional Access names a grant control ("Require multifactor authentication"). +$script:StepCue = [ordered]@{ + 'before-you' = '\bbefore (?:you|your)\b' + 'first' = '\bfirst\b(?![- ](?:party|parties|time|times|name|names|line|page|row|column|half|day|run|seen|place|sign-in|signs?|log|logs|login|launch|launches|open|opens|start|starts|use|uses)\b)' + 'must' = '\bmust\b' + 'requires' = '\b(?:requires|required|prerequisites?)\b' + 'without' = "\b(?:won't|will not|doesn't|does not|don't|do not|can't|cannot|isn't|is not|aren't|are not)\b[^.]{0,80}?\bwithout\b" + 'only-after' = '\bonly (?:after|once)\b' +} +# Headings of the sections that list prerequisites. +$script:PrerequisiteHeading = '^(?:prerequisites?|before you (?:begin|start|get started)|(?:license |licensing )?requirements|licensing|what you need(?: to know)?(?: before you (?:begin|start))?|requirements and prerequisites|prerequisites and requirements)$' + +function Find-MtPrerequisiteText { + <# + .SYNOPSIS + Finds the prerequisite sections and the sentences with ordering cues in the body of a Learn page. + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param( + [Parameter(Mandatory)] [AllowEmptyCollection()] [AllowEmptyString()] [string[]] $Line, + # The line number, in the file, of the first line passed. + [int] $FirstLine = 1, + [string[]] $Cue = @($script:StepCue.Keys), + [int] $MaxSectionLength = 4000 + ) + + $limit = $MaxSectionLength + $headings = [System.Collections.Generic.List[object]]::new() + $section = $null + $inFence = $false + $found = [System.Collections.Generic.List[object]]::new() + + # Dot-sourced, so that it can clear $section. + $closeSection = { + if (-not $section) { return } + $text = ($section.Lines -join "`n").Trim() + if ($text.Length -gt $limit) { $text = $text.Substring(0, $limit) + ' [cut]' } + if ($text) { + $found.Add([pscustomobject][ordered]@{ + Kind = 'Section' + Heading = $section.Heading + Line = $section.Line + EndLine = $section.EndLine + Cues = @('section') + Text = $text + }) + } + $section = $null + } + + for ($i = 0; $i -lt $Line.Count; $i++) { + $raw = $Line[$i] + $number = $FirstLine + $i + if ($raw -match '^\s*(```|~~~)') { $inFence = -not $inFence; continue } + if ($inFence) { continue } + + $heading = [regex]::Match($raw, '^(?#{1,6})\s+(?.+?)\s*#*\s*$') + if ($heading.Success) { + $level = $heading.Groups['hashes'].Value.Length + $title = ($heading.Groups['text'].Value -replace '\[([^\]]+)\]\([^)]*\)', '$1' -replace '[*_`]', '').Trim().TrimEnd(':') + if ($section -and $level -le $section.Level) { . $closeSection } + while ($headings.Count -gt 0 -and $headings[$headings.Count - 1].Level -ge $level) { $headings.RemoveAt($headings.Count - 1) } + $headings.Add([pscustomobject]@{ Level = $level; Title = $title }) + if (-not $section -and $title -match "(?i)$script:PrerequisiteHeading") { + $section = [pscustomobject]@{ Heading = $title; Level = $level; Line = $number; EndLine = $number; Lines = [System.Collections.Generic.List[string]]::new() } + } + continue + } + + # Plain text of the line: no quote or list markers, link targets, emphasis, images or callout markers. + $text = $raw -replace '^(\s*>)+\s?', '' -replace '^\s*(?:[-*+]|\d+\.)\s+', '' + if ($text -match '^\s*(?:!\[|:::|' + +function Get-MtLearnPageBody { + <# + .SYNOPSIS + Returns the body of a mirror file at a commit, normalized for comparison, or $null when the file is not there. + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory)] [string] $Repository, + [Parameter(Mandatory)] [string] $Revision, + [Parameter(Mandatory)] [string] $Path + ) + + $lines = Invoke-MtGit -Path $Repository -Arguments '-c', 'core.quotePath=false', 'show', "${Revision}:$Path" -AllowFailure + if ($LASTEXITCODE -ne 0) { return $null } + $body = (Split-MtLearnFrontMatter -Text (@($lines) -join "`n")).Body + ((($body -split "`n") | ForEach-Object { $_.TrimEnd() }) -join "`n").Trim() +} + +function Get-MtGitHubFileLink { + <# + .SYNOPSIS + Builds a GitHub link to a file's diff in a commit or comparison, or to its history. + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory)] [string] $Repository, + [Parameter(Mandatory)] [string] $Path, + [Parameter(Mandatory)] [ValidateSet('Commit', 'Compare', 'History')] [string] $Kind, + [string] $From, + [Parameter(Mandatory)] [string] $To + ) + + # GitHub names a file's diff on a commit or compare page by the SHA-256 of its path. + $hash = [System.Convert]::ToHexString([System.Security.Cryptography.SHA256]::HashData([System.Text.Encoding]::UTF8.GetBytes($Path))).ToLowerInvariant() + $escaped = ($Path -split '/' | ForEach-Object { [System.Uri]::EscapeDataString($_) }) -join '/' + switch ($Kind) { + 'Commit' { "https://github.com/$Repository/commit/$To#diff-$hash" } + 'Compare' { "https://github.com/$Repository/compare/$From...$To#diff-$hash" } + 'History' { "https://github.com/$Repository/commits/$To/$escaped" } + } +} + +function Test-MtStepSourceChange { + <# + .SYNOPSIS + Checks one step source against the mirror history and returns its result. + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param( + [Parameter(Mandatory)] [pscustomobject] $Source, + [Parameter(Mandatory)] [pscustomobject] $Index + ) + + $result = [pscustomobject][ordered]@{ + Step = $Source.Step + StepTitle = $Source.StepTitle + File = $Source.File + Index = $Source.Index + Url = $Source.Url + Mirror = $Source.Mirror + Reviewed = $Source.Reviewed + Status = 'NotFound' + Detail = $null + Path = $null + Baseline = $null + Head = $null + Commits = @() + DiffLink = $null + HistoryLink = $null + Problems = @() + NeedsReview = $true + } + $problems = [System.Collections.Generic.List[string]]::new() + + $page = Resolve-MtLearnPage -Index $Index -Url $Source.Url + if (-not $page.Path) { + $result.Detail = switch ($page.Status) { + 'Missing' { 'Learn answers 404 for this URL: the page was removed.' } + 'External' { "Learn redirects this URL to $($page.Detail)." } + 'Unresolved' { 'No mirror has this URL and Learn has not been asked about it. Run Update-MtLearnMirror.ps1.' } + default { if ($page.Detail) { $page.Detail } else { "No mirror has the page$(if ($page.ResolvedKey -and $page.ResolvedKey -ne $page.Key) { " it redirects to ($($page.ResolvedKey))" })." } } + } + return $result + } + if ($page.Status -eq 'Redirected') { + $problems.Add("Learn redirects this URL to https://learn.microsoft.com/$($page.ResolvedKey). Cite the new URL.") + } + if ($Source.Mirror -and $Source.Mirror -ne $page.Mirror) { + $problems.Add("Mirror is $($Source.Mirror), but the page is in $($page.Mirror).") + } + $result.Path = $page.Path + $result.Problems = $problems.ToArray() + + $repository = Join-Path $Index.MirrorPath $page.Mirror + if (-not (Test-Path -LiteralPath (Join-Path $repository '.git'))) { + throw "The mirror $($page.Mirror) is in the index but not in $($Index.MirrorPath). Run Update-MtLearnMirror.ps1." + } + $remote = if ($Index.Mirrors.Contains($page.Mirror) -and $Index.Mirrors[$page.Mirror]['Repository']) { $Index.Mirrors[$page.Mirror]['Repository'] } else { "$($Index.Owner)/$($page.Mirror)" } + $head = Invoke-MtGit -Path $repository -Arguments 'rev-parse', 'HEAD' | Select-Object -First 1 + $result.Head = $head + $result.HistoryLink = Get-MtGitHubFileLink -Repository $remote -Path $page.Path -Kind History -To $head + + # The page as it was at the end of the Reviewed day. + $baseline = Invoke-MtGit -Path $repository -Arguments 'rev-list', '-1', '--first-parent', "--before=$($Source.Reviewed)T23:59:59Z", 'HEAD' | Select-Object -First 1 + if (-not $baseline) { + $result.Status = 'NoBaseline' + $result.Detail = "The mirror's history starts after $($Source.Reviewed), so it can't show what changed since. Re-read the page." + return $result + } + $result.Baseline = $baseline + + $before = Get-MtLearnPageBody -Repository $repository -Revision $baseline -Path $page.Path + if ($null -eq $before) { + $result.Status = 'New' + $result.Detail = "The page's file ($($page.Path)) was not in the mirror on $($Source.Reviewed): the page moved or was published since. Re-read it." + $result.NeedsReview = $true + return $result + } + + # Walk the commits that touched the file, keeping those that changed the body. + $log = @(Invoke-MtGit -Path $repository -Arguments '-c', 'core.quotePath=false', 'log', '--first-parent', '--reverse', '--format=%H%x1f%cI%x1f%s', "$baseline..HEAD", '--', $page.Path) + $changes = [System.Collections.Generic.List[object]]::new() + $previous = $before + $touched = 0 + foreach ($line in $log | Where-Object { $_ }) { + $sha, $date, $subject = $line -split [char]0x1f, 3 + $touched++ + $body = Get-MtLearnPageBody -Repository $repository -Revision $sha -Path $page.Path + if ($body -ceq $previous) { continue } + $changes.Add([pscustomobject][ordered]@{ + Sha = $sha + Date = $date + Subject = $subject + Link = Get-MtGitHubFileLink -Repository $remote -Path $page.Path -Kind Commit -To $sha + }) + $previous = $body + } + + $now = Get-MtLearnPageBody -Repository $repository -Revision $head -Path $page.Path + if ($now -ceq $before) { + $result.Status = 'Unchanged' + $result.Detail = if ($touched -eq 0) { 'No commit since the baseline.' } + elseif ($changes.Count -eq 0) { "$touched commit$(if ($touched -ne 1) { 's' }) since the baseline changed only the front matter." } + else { "The page's text changed and changed back since the baseline." } + } else { + $result.Status = 'Changed' + $result.Commits = $changes.ToArray() + $last = $changes[$changes.Count - 1].Sha + $result.DiffLink = if ($changes.Count -eq 1) { $changes[0].Link } else { Get-MtGitHubFileLink -Repository $remote -Path $page.Path -Kind Compare -From $baseline -To $last } + $result.Detail = "$($changes.Count) commit$(if ($changes.Count -ne 1) { 's' }) changed the page's text since $($Source.Reviewed)." + } + $result.NeedsReview = $result.Status -ne 'Unchanged' -or $problems.Count -gt 0 + $result +} + +function ConvertTo-MtStepSourceMarkdown { + <# + .SYNOPSIS + Writes the results as the body of the weekly issue: the steps whose sources need review, with links to the + changes. + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory)] [AllowEmptyCollection()] [object[]] $Result, + [System.Collections.IDictionary] $Mirrors = @{}, + [string] $Checked = [datetime]::UtcNow.ToString('yyyy-MM-dd', [System.Globalization.CultureInfo]::InvariantCulture) + ) + + $cell = { param($text) ([string] $text) -replace '\|', '\|' -replace '\r?\n', ' ' } + $review = @($Result | Where-Object NeedsReview) + $lines = [System.Collections.Generic.List[string]]::new() + $lines.Add($script:IssueMarker) + $versions = @($Mirrors.GetEnumerator() | ForEach-Object { "``$($_.Key)`` at $(([string] $_.Value['Commit']).Substring(0, [math]::Min(7, ([string] $_.Value['Commit']).Length)))" }) + $mirrorText = if ($versions.Count) { " against $($versions -join ', ')" } else { '' } + $lines.Add("Checked on $Checked$mirrorText by ``build/steps/Test-MtStepSource.ps1``.") + $lines.Add('') + if ($review.Count -eq 0) { + $lines.Add("All $(@($Result).Count) Learn sources of the step catalogue match the page each one was reviewed against.") + return ($lines -join "`n") + } + + $steps = @($review | Select-Object -ExpandProperty Step -Unique) + $lines.Add("$($review.Count) of $(@($Result).Count) Learn sources need a maintainer to re-read the page, in $($steps.Count) step$(if ($steps.Count -ne 1) { 's' }).") + $lines.Add('') + $lines.Add('For each one, read the change on Learn, and update the step if the order it describes changed. Then set the source''s `Reviewed` to the date you read it. Commits that change only a page''s front matter are not counted.') + foreach ($stepId in $steps) { + $rows = @($review | Where-Object Step -EQ $stepId) + $lines.Add('') + $lines.Add("### ``$stepId`` $(& $cell $rows[0].StepTitle)") + $lines.Add('') + $lines.Add("In ``powershell/assets/steps/$($rows[0].File)``.") + $lines.Add('') + $lines.Add('| Source | Reviewed | What changed | Links |') + $lines.Add('| --- | --- | --- | --- |') + foreach ($row in $rows) { + $what = @( + switch ($row.Status) { + 'Changed' { "$($row.Commits.Count) change$(if ($row.Commits.Count -ne 1) { 's' }) to the text ($((@($row.Commits) | ForEach-Object { ([string] $_.Date).Substring(0, 10) }) -join ', '))." } + 'Unchanged' { } + default { $row.Detail } + } + $row.Problems + ) | Where-Object { $_ } + $commits = @($row.Commits) + $links = @( + if ($row.DiffLink) { "[diff]($($row.DiffLink))" } + # A compare page can be too large to show one file, so each commit is linked as well. + if ($commits.Count -gt 1) { 'commits ' + (($commits | ForEach-Object { "[$(([string] $_.Sha).Substring(0, 7))]($($_.Link))" }) -join ' ') } + if ($row.HistoryLink) { "[history]($($row.HistoryLink))" } + ) + $label = ConvertTo-MtLearnKey $row.Url + if (-not $label) { $label = $row.Url } + $lines.Add("| $($row.Index). [$(& $cell $label)]($($row.Url)) | $($row.Reviewed) | $(& $cell ($what -join ' ')) | $($links -join ', ') |") + } + } + $lines -join "`n" +} + +# Lets the unit tests dot-source the functions above without running the script. +if ($MyInvocation.InvocationName -eq '.') { return } + +try { + if (-not $CatalogPath) { $CatalogPath = Join-Path $Root 'powershell/assets/steps' } + $index = Read-MtLearnIndex -CachePath $CachePath + $sources = @(Get-MtStepSource -Path $CatalogPath | Where-Object Url) + if ($Step) { $sources = @($sources | Where-Object { $id = $_.Step; $Step | Where-Object { $id -like $_ } }) } + + $results = foreach ($source in $sources) { + Write-Host "Checking $($source.Step) source $($source.Index)" + Test-MtStepSourceChange -Source $source -Index $index + } + $results = @($results) +} catch { + Write-Error -ErrorRecord $_ -ErrorAction Continue + exit 2 +} + +if ($OutputPath) { + $null = New-Item -ItemType Directory -Path $OutputPath -Force + ConvertTo-Json -InputObject $results -Depth 6 | Set-Content -LiteralPath (Join-Path $OutputPath 'step-sources.json') -Encoding utf8NoBOM + ConvertTo-MtStepSourceMarkdown -Result $results -Mirrors $index.Mirrors | Set-Content -LiteralPath (Join-Path $OutputPath 'step-sources.md') -Encoding utf8NoBOM +} + +if ($ShowDiff) { + foreach ($row in $results | Where-Object Status -EQ 'Changed') { + $repository = Join-Path $index.MirrorPath (Resolve-MtLearnPage -Index $index -Url $row.Url).Mirror + $temp = Join-Path ([System.IO.Path]::GetTempPath()) "mt-step-source-$([guid]::NewGuid().ToString('n'))" + $null = New-Item -ItemType Directory -Path $temp + try { + Set-Content -LiteralPath (Join-Path $temp 'reviewed.md') -Value (Get-MtLearnPageBody -Repository $repository -Revision $row.Baseline -Path $row.Path) -Encoding utf8NoBOM + Set-Content -LiteralPath (Join-Path $temp 'now.md') -Value (Get-MtLearnPageBody -Repository $repository -Revision $row.Head -Path $row.Path) -Encoding utf8NoBOM + Write-Host "`n$($row.Step) source $($row.Index): $($row.Url)" + & git -C $temp diff --no-index --no-color --unified=2 -- reviewed.md now.md | ForEach-Object { Write-Host $_ } + } finally { + Remove-Item -LiteralPath $temp -Recurse -Force + } + } +} + +$results +$needsReview = @($results | Where-Object NeedsReview) +Write-Host "$($needsReview.Count) of $($results.Count) sources need review." +exit $(if ($needsReview.Count -gt 0) { 1 } else { 0 }) diff --git a/build/steps/Update-MtLearnMirror.ps1 b/build/steps/Update-MtLearnMirror.ps1 new file mode 100644 index 0000000000..5682504f2d --- /dev/null +++ b/build/steps/Update-MtLearnMirror.ps1 @@ -0,0 +1,443 @@ +<# +.SYNOPSIS +Clones or updates the Microsoft Learn mirrors and writes the URL-to-file index that the step tooling reads. + +.DESCRIPTION +The defender's path catalogue (powershell/assets/steps, docs/proposals/defenders-path.md section 13) cites Learn +pages. Nine public mirrors built with merill/learn-mirror keep those pages in git: Learn is crawled four times a day +and each run that finds changed pages commits them. This script keeps a clone of each mirror in a cache folder and +writes what the other scripts in build/steps need to find a page's file without the network: + + /mirrors// a blobless clone of each mirror (history and the current files) + /index.json every page of every mirror: key -> Mirror, Path (and Target when Learn + redirects the page to another one) + /redirects.json what Learn answered for linked URLs that no mirror has under that key + +A key is a Learn URL's path with no locale, query, anchor or trailing slash, in lowercase. The index is read from +each mirror's .learn-mirror/state.json, which maps every page URL the crawler knows to the file it wrote, and the +mirror's learn-mirror.config.json, whose include and exclude patterns say which URLs the mirror covers. A mirror +with no state file is indexed from the canonicalUrl in each page's front matter. + +Check guides still link many pages by an old URL (mem/intune/..., microsoft-365/security/defender/..., +azure/active-directory/...), which Learn redirects. For each URL that the check guides (tests/**/Test.*.md) or +the step sources link and that no mirror has under that key, the script asks Learn where it goes and caches the +answer for -RedirectMaxAge days. Learn's answers to HEAD requests often leave the redirect out (on 5 November 2026 +HEAD returned 200 for microsoft-365/security/defender/microsoft-secure-score, which GET redirects), so each lookup +is a GET that reads only the response headers and never the page. Redirects are followed one hop at a time, at +most -RequestsPerSecond requests a second. + +The cache folder is ignored by git. Nothing outside it is written. + +.PARAMETER Root +The repository root. Check guides are read from tests/ and step sources from powershell/assets/steps. + +.PARAMETER CachePath +The cache folder. Defaults to build/steps/.cache. + +.PARAMETER Mirror +The mirrors to clone and index. Defaults to all nine. + +.PARAMETER Owner +The GitHub account that holds the mirrors. + +.PARAMETER Links +Which links to resolve through Learn's redirects: All (check guides and step sources, the default), Guides, +Catalog or None. + +.PARAMETER RedirectMaxAge +How many days a cached answer from Learn is used before it is asked again. 0 asks again for every URL. + +.PARAMETER RequestsPerSecond +The most requests a second sent to Learn. + +.PARAMETER NoFetch +Use the clones already in the cache folder, without fetching. A mirror that has not been cloned is left out. + +.EXAMPLE +./build/steps/Update-MtLearnMirror.ps1 + +Clones or updates the nine mirrors, writes the index and resolves the links of every check guide and step source. + +.EXAMPLE +./build/steps/Update-MtLearnMirror.ps1 -Mirror entra-docs-mirror, intune-docs-mirror -Links Catalog + +Updates two mirrors and resolves only the step sources' links. The weekly step-sources workflow runs it like this. +#> +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWriteHost', '', Justification = 'Build script output for the console')] +[CmdletBinding()] +param( + [string] $Root = (Resolve-Path (Join-Path $PSScriptRoot '../..')).Path, + + [string] $CachePath = (Join-Path $PSScriptRoot '.cache'), + + [ValidateSet('entra-docs-mirror', 'intune-docs-mirror', 'defender-docs-mirror', 'security-docs-mirror', 'purview-docs-mirror', + 'teams-docs-mirror', 'sharepoint-docs-mirror', 'exchange-docs-mirror', 'windows-server-docs-mirror')] + [string[]] $Mirror = @('entra-docs-mirror', 'intune-docs-mirror', 'defender-docs-mirror', 'security-docs-mirror', 'purview-docs-mirror', + 'teams-docs-mirror', 'sharepoint-docs-mirror', 'exchange-docs-mirror', 'windows-server-docs-mirror'), + + [ValidatePattern('^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}$')] + [string] $Owner = 'merill', + + [ValidateSet('All', 'Guides', 'Catalog', 'None')] + [string] $Links = 'All', + + [ValidateRange(0, 3650)] + [int] $RedirectMaxAge = 30, + + [ValidateRange(0.1, 20)] + [double] $RequestsPerSecond = 4, + + [switch] $NoFetch +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' +foreach ($helper in Get-ChildItem -Path (Join-Path $PSScriptRoot 'helpers') -Filter '*.ps1') { . $helper.FullName } + +$script:LearnOrigin = 'https://learn.microsoft.com' +$script:UserAgent = 'Maester-step-tooling/1.0 (+https://github.com/maester365/maester)' +$script:LearnClient = $null +$script:LearnClock = $null + +function Sync-MtLearnMirrorClone { + <# + .SYNOPSIS + Clones a mirror into the cache folder, or brings an existing clone up to date. Returns the clone's folder, or + nothing when -NoFetch is set and there is no clone. + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory)] [string] $Name, + [Parameter(Mandatory)] [string] $Owner, + [Parameter(Mandatory)] [string] $MirrorPath, + [switch] $NoFetch + ) + + $folder = Join-Path $MirrorPath $Name + if (-not (Test-Path -LiteralPath (Join-Path $folder '.git'))) { + if ($NoFetch) { + Write-Warning "$Name has not been cloned yet, so it is left out. Run without -NoFetch to clone it." + return + } + # Blobless: the whole history, but only the current version of each file. Older versions are fetched + # when a script asks for one. + $null = Invoke-MtGit -Path $MirrorPath -Arguments 'clone', '--quiet', '--filter=blob:none', '--single-branch', '--no-tags', + "https://github.com/$Owner/$Name.git", $Name + return $folder + } + if (-not $NoFetch) { + $null = Invoke-MtGit -Path $folder -Arguments 'fetch', '--quiet', '--filter=blob:none', '--no-tags', 'origin' + # The clone belongs to the cache, so it follows the mirror exactly. + $null = Invoke-MtGit -Path $folder -Arguments 'reset', '--quiet', '--hard', '@{upstream}' + } + $folder +} + +function Get-MtLearnMirrorPage { + <# + .SYNOPSIS + Reads a mirror's configuration and the pages it holds: Key, Path and, for a URL that Learn redirects, Target. + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param( + [Parameter(Mandatory)] [string] $Path + ) + + $config = @{} + $configFile = Join-Path $Path 'learn-mirror.config.json' + if (Test-Path -LiteralPath $configFile) { $config = Get-Content -LiteralPath $configFile -Raw | ConvertFrom-Json -AsHashtable } + + $tracked = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::Ordinal) + foreach ($file in Invoke-MtGit -Path $Path -Arguments '-c', 'core.quotePath=false', 'ls-files') { $null = $tracked.Add($file) } + + $pages = [System.Collections.Generic.List[object]]::new() + $stateFile = Join-Path $Path '.learn-mirror/state.json' + if (Test-Path -LiteralPath $stateFile) { + $state = (Get-Content -LiteralPath $stateFile -Raw | ConvertFrom-Json -AsHashtable)['pages'] + foreach ($entry in $state.GetEnumerator()) { + $key = ConvertTo-MtLearnKey $entry.Key + if ([string]::IsNullOrEmpty($key)) { continue } + # An alias is another URL that serves the same page. Its file is the one its original URL was written to. + $page = $entry.Value + for ($hop = 0; $hop -lt 5 -and -not $page['path'] -and $page['aliasOf'] -and $state.ContainsKey($page['aliasOf']); $hop++) { + $page = $state[$page['aliasOf']] + } + $file = $page['path'] + if (-not $file -or -not $tracked.Contains($file)) { continue } + $target = if ($entry.Value['redirectedTo']) { ConvertTo-MtLearnKey $entry.Value['redirectedTo'] } else { $null } + $pages.Add([pscustomobject]@{ Key = $key; Path = $file; Target = if ($target -and $target -ne $key) { $target } else { $null } }) + } + } else { + Write-Warning "$(Split-Path $Path -Leaf) has no .learn-mirror/state.json. Indexing it from each page's canonicalUrl." + foreach ($file in $tracked | Where-Object { $_ -like '*.md' -and $_ -notlike '.*' }) { + $head = Get-Content -LiteralPath (Join-Path $Path $file) -TotalCount 80 + $canonical = $head | Where-Object { $_ -match '^canonicalUrl:\s*(\S+)' } | Select-Object -First 1 + if (-not $canonical) { continue } + $key = ConvertTo-MtLearnKey (($canonical -replace '^canonicalUrl:\s*', '').Trim()) + if ($key) { $pages.Add([pscustomobject]@{ Key = $key; Path = $file; Target = $null }) } + } + } + + [pscustomobject]@{ + Include = $config['include'] + Exclude = @($config['exclude'] | Where-Object { $_ }) + Pages = $pages + } +} + +function Send-MtLearnRequest { + <# + .SYNOPSIS + Sends one GET to Learn without following redirects and returns the status, the Location header and any + Retry-After, without reading the page. + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param( + [Parameter(Mandatory)] [string] $Uri + ) + + if (-not $script:LearnClient) { + $handler = [System.Net.Http.HttpClientHandler]::new() + $handler.AllowAutoRedirect = $false + $script:LearnClient = [System.Net.Http.HttpClient]::new($handler) + $script:LearnClient.Timeout = [TimeSpan]::FromSeconds(30) + } + $request = [System.Net.Http.HttpRequestMessage]::new([System.Net.Http.HttpMethod]::Get, $Uri) + # Learn applies its redirects to Markdown requests as it does to pages, and learn-mirror crawls this way. + $null = $request.Headers.TryAddWithoutValidation('Accept', 'text/markdown') + $null = $request.Headers.TryAddWithoutValidation('User-Agent', $script:UserAgent) + try { + $response = $script:LearnClient.SendAsync($request, [System.Net.Http.HttpCompletionOption]::ResponseHeadersRead).GetAwaiter().GetResult() + $retryAfter = $null + if ($response.Headers.RetryAfter -and $null -ne $response.Headers.RetryAfter.Delta) { $retryAfter = [int] $response.Headers.RetryAfter.Delta.TotalSeconds } + [pscustomobject]@{ + Status = [int] $response.StatusCode + Location = if ($response.Headers.Location) { $response.Headers.Location.OriginalString } else { $null } + RetryAfter = $retryAfter + } + $response.Dispose() + } finally { + $request.Dispose() + } +} + +function Resolve-MtLearnRedirect { + <# + .SYNOPSIS + Asks Learn where a page key goes, one hop at a time. Returns the answer to cache (Status Redirect, Page, Missing + or External, To, Hops and Checked), or nothing when Learn could not be asked. + #> + [CmdletBinding()] + [OutputType([System.Collections.Specialized.OrderedDictionary])] + param( + [Parameter(Mandatory)] [string] $Key, + [double] $RequestsPerSecond = 4, + [int] $MaxHops = 8 + ) + + $uri = "$script:LearnOrigin/en-us/$Key" + $hops = 0 + $retries = 0 + $answer = $null + while ($true) { + # Space the requests out. + if (-not $script:LearnClock) { $script:LearnClock = [System.Diagnostics.Stopwatch]::new() } + $wait = (1000 / $RequestsPerSecond) - $script:LearnClock.Elapsed.TotalMilliseconds + if ($script:LearnClock.IsRunning -and $wait -gt 0) { Start-Sleep -Milliseconds ([int][math]::Ceiling($wait)) } + $script:LearnClock.Restart() + + try { + $response = Send-MtLearnRequest -Uri $uri + } catch { + Write-Warning "Could not ask Learn about ${Key}: $($_.Exception.Message)" + return + } + + if ($response.Status -in 429, 503) { + if (++$retries -gt 3) { Write-Warning "Learn kept throttling the lookup of $Key. It is left unresolved."; return } + $delay = if ($response.RetryAfter) { [math]::Min($response.RetryAfter, 120) } else { 15 * $retries } + Start-Sleep -Seconds $delay + continue + } + if ($response.Status -ge 200 -and $response.Status -lt 300) { + $final = ConvertTo-MtLearnKey $uri + $answer = [ordered]@{ Status = if ($final -ne $Key) { 'Redirect' } else { 'Page' }; To = $final; Hops = $hops } + break + } + if ($response.Status -in 404, 410) { + $answer = [ordered]@{ Status = 'Missing'; To = ConvertTo-MtLearnKey $uri; Hops = $hops } + break + } + if ($response.Status -in 301, 302, 303, 307, 308 -and $response.Location) { + $next = [System.Uri]::new([System.Uri]::new($uri), $response.Location).AbsoluteUri + if ($null -eq (ConvertTo-MtLearnKey $next)) { + $answer = [ordered]@{ Status = 'External'; To = $next; Hops = $hops + 1 } + break + } + if (++$hops -gt $MaxHops) { Write-Warning "$Key redirects more than $MaxHops times. It is left unresolved."; return } + $uri = $next + continue + } + Write-Warning "Learn answered $($response.Status) for $Key. It is left unresolved." + return + } + $answer['Checked'] = [datetime]::UtcNow.ToString('yyyy-MM-ddTHH:mm:ssZ', [System.Globalization.CultureInfo]::InvariantCulture) + $answer +} + +function Select-MtLearnLookup { + <# + .SYNOPSIS + Returns the linked pages to ask Learn about: those no mirror has under their key, with no cached answer or one + older than -MaxAge days. + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param( + [Parameter(Mandatory)] [AllowEmptyCollection()] [object[]] $Link, + [Parameter(Mandatory)] [System.Collections.IDictionary] $Pages, + [Parameter(Mandatory)] [System.Collections.IDictionary] $Redirects, + [int] $MaxAge = 30, + [datetime] $Now = [datetime]::UtcNow + ) + + $cutoff = $Now.ToUniversalTime().AddDays(-$MaxAge) + # A generic dictionary has ContainsKey; an ordered dictionary has only Contains. + $has = { param($dictionary, $key) if ($dictionary.PSObject.Methods['ContainsKey']) { $dictionary.ContainsKey($key) } else { $dictionary.Contains($key) } } + foreach ($item in $Link) { + if (& $has $Pages $item.Key) { continue } + if (-not (& $has $Redirects $item.Key)) { $item; continue } + # ConvertFrom-Json may already have read the timestamp as a date. + $checked = $Redirects[$item.Key]['Checked'] + if ($checked -isnot [datetime]) { + $parsed = [datetime]::MinValue + $style = [System.Globalization.DateTimeStyles]::AdjustToUniversal -bor [System.Globalization.DateTimeStyles]::AssumeUniversal + if (-not [datetime]::TryParse([string] $checked, [System.Globalization.CultureInfo]::InvariantCulture, $style, [ref] $parsed)) { $item; continue } + $checked = $parsed + } + if ($MaxAge -eq 0 -or $checked.ToUniversalTime() -lt $cutoff) { $item } + } +} + +function Save-MtLearnRedirect { + <# + .SYNOPSIS + Writes the redirect answers to redirects.json, sorted by key. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] [string] $Path, + [Parameter(Mandatory)] [System.Collections.IDictionary] $Redirects + ) + + $sorted = [ordered]@{} + foreach ($key in @($Redirects.Keys) | Sort-Object) { $sorted[$key] = $Redirects[$key] } + [ordered]@{ Version = 1; Redirects = $sorted } | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $Path -Encoding utf8NoBOM +} + +# Lets the unit tests dot-source the functions above without running the script. +if ($MyInvocation.InvocationName -eq '.') { return } + +if (-not (Get-Command git -ErrorAction SilentlyContinue)) { throw 'git is required.' } +$mirrorRoot = Join-Path $CachePath 'mirrors' +$null = New-Item -ItemType Directory -Path $mirrorRoot -Force +$CachePath = (Resolve-Path -LiteralPath $CachePath).Path +$mirrorRoot = Join-Path $CachePath 'mirrors' + +try { + # 1. The mirrors and their pages. + $pages = [System.Collections.Generic.SortedDictionary[string, object]]::new([System.StringComparer]::OrdinalIgnoreCase) + $mirrorInfo = [ordered]@{} + foreach ($name in $Mirror) { + Write-Host "$(if ($NoFetch) { 'Reading' } else { 'Updating' }) $Owner/$name" + $folder = Sync-MtLearnMirrorClone -Name $name -Owner $Owner -MirrorPath $mirrorRoot -NoFetch:$NoFetch + if (-not $folder) { continue } + $content = Get-MtLearnMirrorPage -Path $folder + $added = 0 + foreach ($page in $content.Pages) { + if ($pages.ContainsKey($page.Key)) { + if ($pages[$page.Key].Mirror -ne $name) { Write-Verbose "$($page.Key) is in both $($pages[$page.Key].Mirror) and $name. The first is used." } + continue + } + $entry = [ordered]@{ Mirror = $name; Path = $page.Path } + if ($page.Target) { $entry['Target'] = $page.Target } + $pages[$page.Key] = $entry + $added++ + } + $mirrorInfo[$name] = [ordered]@{ + Repository = "$Owner/$name" + Commit = (Invoke-MtGit -Path $folder -Arguments 'rev-parse', 'HEAD') | Select-Object -First 1 + CommitDate = (Invoke-MtGit -Path $folder -Arguments 'log', '-1', '--format=%cI') | Select-Object -First 1 + Pages = $added + Include = $content.Include + Exclude = $content.Exclude + } + } + $index = [ordered]@{ + Version = 1 + Generated = [datetime]::UtcNow.ToString('yyyy-MM-ddTHH:mm:ssZ', [System.Globalization.CultureInfo]::InvariantCulture) + Owner = $Owner + Mirrors = $mirrorInfo + Pages = $pages + } + $index | ConvertTo-Json -Depth 5 -Compress | Set-Content -LiteralPath (Join-Path $CachePath 'index.json') -Encoding utf8NoBOM + Write-Host "Indexed $($pages.Count) pages from $($mirrorInfo.Count) mirrors." + + # 2. Linked URLs that no mirror has under that key: ask Learn where they go. + $redirectFile = Join-Path $CachePath 'redirects.json' + $redirects = [ordered]@{} + if (Test-Path -LiteralPath $redirectFile) { + $saved = Get-Content -LiteralPath $redirectFile -Raw | ConvertFrom-Json -AsHashtable -Depth 10 + if ($saved -and $saved['Redirects']) { foreach ($entry in $saved['Redirects'].GetEnumerator()) { $redirects[$entry.Key] = $entry.Value } } + } + $linked = @() + if ($Links -ne 'None') { + $linked = @(Get-MtLearnLink -Root $Root -Links $Links) + $todo = @(Select-MtLearnLookup -Link $linked -Pages $pages -Redirects $redirects -MaxAge $RedirectMaxAge) + if ($todo.Count -gt 0) { Write-Host "Asking Learn about $($todo.Count) linked URLs that no mirror has under that key." } + $done = 0 + foreach ($link in $todo) { + $answer = Resolve-MtLearnRedirect -Key $link.Key -RequestsPerSecond $RequestsPerSecond + if ($answer) { $redirects[$link.Key] = $answer } + if ((++$done % 25) -eq 0) { + Save-MtLearnRedirect -Path $redirectFile -Redirects $redirects + Write-Host " $done of $($todo.Count)" + } + } + Save-MtLearnRedirect -Path $redirectFile -Redirects $redirects + } + + # 3. Summary. + $readIndex = Read-MtLearnIndex -CachePath $CachePath + $resolved = foreach ($link in $linked) { [pscustomobject]@{ Link = $link; Page = Resolve-MtLearnPage -Index $readIndex -Url $link.Url } } + $byStatus = [ordered]@{} + foreach ($status in 'Mirrored', 'Redirected', 'NotInMirror', 'NotMirrored', 'Missing', 'External', 'Unresolved') { + $byStatus[$status] = @($resolved | Where-Object { $_.Page.Status -eq $status }).Count + } + if ($linked.Count -gt 0) { + Write-Host "Linked pages: $($linked.Count). $(($byStatus.GetEnumerator() | Where-Object Value | ForEach-Object { "$($_.Key) $($_.Value)" }) -join ', ')." + $guidePages = @($resolved | Where-Object { $_.Page.Mirror -in 'intune-docs-mirror', 'defender-docs-mirror' -and ($_.Link.From | Where-Object Kind -EQ 'Guide') }) + if ($guidePages.Count -gt 0) { + $redirected = @($guidePages | Where-Object { $_.Page.Status -eq 'Redirected' }) + $count = { param($items) @($items | ForEach-Object { $_.Link.From | Where-Object Kind -EQ 'Guide' }).Count } + Write-Host "Intune and Defender pages linked from check guides: $($redirected.Count) of $($guidePages.Count) are linked by a URL that Learn redirects ($(& $count $redirected) of $(& $count $guidePages) links)." + } + foreach ($item in $resolved | Where-Object { $_.Page.Status -in 'Missing', 'NotInMirror', 'Unresolved' }) { + $where = ($item.Link.From | Select-Object -First 3 | ForEach-Object { if ($_.Line) { "$($_.File):$($_.Line)" } else { "$($_.File) ($($_.Id))" } }) -join ', ' + Write-Host " $($item.Page.Status): $($item.Link.Url) ($where)" + } + } + + [pscustomobject]@{ + CachePath = $CachePath + Mirrors = @($mirrorInfo.Keys) + Pages = $pages.Count + Links = $linked.Count + Status = [pscustomobject]$byStatus + } +} finally { + if ($script:LearnClient) { $script:LearnClient.Dispose(); $script:LearnClient = $null } +} diff --git a/build/steps/helpers/ConvertTo-MtLearnKey.ps1 b/build/steps/helpers/ConvertTo-MtLearnKey.ps1 new file mode 100644 index 0000000000..072944558b --- /dev/null +++ b/build/steps/helpers/ConvertTo-MtLearnKey.ps1 @@ -0,0 +1,37 @@ +function ConvertTo-MtLearnKey { + <# + .SYNOPSIS + Turns a Microsoft Learn URL into the key the step tooling indexes pages by. + + .DESCRIPTION + The key is the URL's path with no locale, query, fragment or trailing slash, in lowercase: both + https://learn.microsoft.com/intune/device-security/compliance/overview and the same page under a locale and with + an anchor give intune/device-security/compliance/overview. Learn paths are not case-sensitive, so neither is the + key. The site root gives an empty key. + + docs.microsoft.com URLs are read as Learn URLs, because Learn redirects them. Any other URL returns $null. + + .PARAMETER Url + The URL to convert. + + .EXAMPLE + ConvertTo-MtLearnKey 'https://learn.microsoft.com/entra/identity/conditional-access/overview#policy' + + Returns entra/identity/conditional-access/overview. + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory, Position = 0, ValueFromPipeline)] + [AllowEmptyString()] + [string] $Url + ) + + process { + $match = [regex]::Match($Url, '^(?i)https?://(?:learn|docs)\.microsoft\.com(?/[^?#\s]*)?') + if (-not $match.Success) { return $null } + $path = $match.Groups['path'].Value.Trim('/') + $path = [regex]::Replace($path, '^[a-z]{2}-[a-z]{2}(/|$)', '', 'IgnoreCase') + $path.Trim('/').ToLowerInvariant() + } +} diff --git a/build/steps/helpers/Get-MtLearnLink.ps1 b/build/steps/helpers/Get-MtLearnLink.ps1 new file mode 100644 index 0000000000..76fcee8347 --- /dev/null +++ b/build/steps/helpers/Get-MtLearnLink.ps1 @@ -0,0 +1,79 @@ +function Get-MtLearnLink { + <# + .SYNOPSIS + Lists the Microsoft Learn pages that check guides and step sources link to. + + .DESCRIPTION + Finds the Learn links in the check guides (tests/**/Test.*.md) and in the Url of each step source in the + catalogue, and returns one object per page: Key (see ConvertTo-MtLearnKey), Url (the first link seen, without + its anchor or query) and From, the places that link to it. Each place has Kind (Guide or Source), Id (the test ID + of a guide, or the step ID of a source), File (relative to -Root) and Line (guides only). + + .PARAMETER Root + The repository root. + + .PARAMETER Links + Which links to read: All (the default), Guides or Catalog. + + .PARAMETER CatalogPath + The step catalogue folder. Defaults to powershell/assets/steps under -Root. + + .EXAMPLE + Get-MtLearnLink -Root . -Links Catalog + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param( + [Parameter(Mandatory)] + [string] $Root, + + [ValidateSet('All', 'Guides', 'Catalog')] + [string] $Links = 'All', + + [string] $CatalogPath + ) + + if (-not $CatalogPath) { $CatalogPath = Join-Path $Root 'powershell/assets/steps' } + $pages = [ordered]@{} + $add = { + param([string] $url, [hashtable] $from) + $key = ConvertTo-MtLearnKey $url + # Not a Learn URL, or the site's home page. + if ([string]::IsNullOrEmpty($key)) { return } + if (-not $pages.Contains($key)) { + $pages[$key] = [pscustomobject][ordered]@{ + Key = $key + Url = ($url -split '[?#]')[0] + From = [System.Collections.Generic.List[object]]::new() + } + } + $pages[$key].From.Add([pscustomobject]$from) + } + + if ($Links -in 'All', 'Catalog') { + foreach ($source in Get-MtStepSource -Path $CatalogPath | Where-Object Url) { + & $add $source.Url ([ordered]@{ Kind = 'Source'; Id = $source.Step; File = "powershell/assets/steps/$($source.File)"; Line = $null }) + } + } + + if ($Links -in 'All', 'Guides') { + $testsFolder = Join-Path $Root 'tests' + $guides = Get-ChildItem -LiteralPath $testsFolder -Recurse -File -Filter 'Test.*.md' -ErrorAction SilentlyContinue | + Sort-Object FullName + $pattern = [regex]::new('https?://(?:learn|docs)\.microsoft\.com/[^\s)<>"''`\]]+', 'IgnoreCase') + foreach ($guide in $guides) { + $relative = [System.IO.Path]::GetRelativePath($Root, $guide.FullName) -replace '\\', '/' + $id = $guide.Name -replace '^Test\.', '' -replace '\.md$', '' + $lineNumber = 0 + foreach ($line in [System.IO.File]::ReadLines($guide.FullName)) { + $lineNumber++ + foreach ($match in $pattern.Matches($line)) { + $url = $match.Value.TrimEnd('.', ',', ';', ':', '*', '_') + & $add $url ([ordered]@{ Kind = 'Guide'; Id = $id; File = $relative; Line = $lineNumber }) + } + } + } + } + + $pages.Values +} diff --git a/build/steps/helpers/Get-MtStepSource.ps1 b/build/steps/helpers/Get-MtStepSource.ps1 new file mode 100644 index 0000000000..5cd0f88757 --- /dev/null +++ b/build/steps/helpers/Get-MtStepSource.ps1 @@ -0,0 +1,57 @@ +function Get-MtStepSource { + <# + .SYNOPSIS + Lists the sources of every step in the step catalogue. + + .DESCRIPTION + Reads the step files of the defender's path catalogue (powershell/assets/steps/.json; goals.json and the + schema hold no sources) and returns one object per source with Step, StepTitle, File, Index (the source's + position in the step's Sources, from 1), Url, Mirror, Maintainer, Note and Reviewed (yyyy-MM-dd). + + The catalogue is read as JSON and not validated: Get-MtStepCatalog and StepCatalog.Tests.ps1 do that. A file + that is not valid JSON stops the script, so a broken catalogue is never reported as unchanged. + + .PARAMETER Path + The catalogue folder. + + .EXAMPLE + Get-MtStepSource -Path ./powershell/assets/steps | Where-Object Url + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param( + [Parameter(Mandatory)] + [string] $Path + ) + + if (-not (Test-Path -LiteralPath $Path -PathType Container)) { throw "The step catalogue folder '$Path' does not exist." } + $files = Get-ChildItem -LiteralPath $Path -Filter '*.json' -File | Where-Object Name -NotIn 'goals.json', 'steps.schema.json' | Sort-Object Name + foreach ($file in $files) { + try { + $content = Get-Content -LiteralPath $file.FullName -Raw | ConvertFrom-Json -AsHashtable -ErrorAction Stop + } catch { + throw "$($file.Name) is not valid JSON: $($_.Exception.Message)" + } + foreach ($step in @($content['Steps'])) { + if ($step -isnot [System.Collections.IDictionary]) { continue } + $index = 0 + foreach ($source in @($step['Sources'])) { + if ($source -isnot [System.Collections.IDictionary]) { continue } + $index++ + $reviewed = $source['Reviewed'] + if ($reviewed -is [datetime]) { $reviewed = $reviewed.ToString('yyyy-MM-dd', [System.Globalization.CultureInfo]::InvariantCulture) } + [pscustomobject][ordered]@{ + Step = [string] $step['Id'] + StepTitle = [string] $step['Title'] + File = $file.Name + Index = $index + Url = if ($source['Url']) { [string] $source['Url'] } else { $null } + Mirror = if ($source['Mirror']) { [string] $source['Mirror'] } else { $null } + Maintainer = if ($source['Maintainer']) { [string] $source['Maintainer'] } else { $null } + Note = [string] $source['Note'] + Reviewed = if ($reviewed) { [string] $reviewed } else { $null } + } + } + } + } +} diff --git a/build/steps/helpers/Invoke-MtGit.ps1 b/build/steps/helpers/Invoke-MtGit.ps1 new file mode 100644 index 0000000000..c52650829b --- /dev/null +++ b/build/steps/helpers/Invoke-MtGit.ps1 @@ -0,0 +1,43 @@ +function Invoke-MtGit { + <# + .SYNOPSIS + Runs git in a repository and returns its output as lines. + + .DESCRIPTION + Runs git -C . When git fails, it throws with git's error message, unless -AllowFailure is + set, in which case it returns nothing. Standard error is never mixed into the returned lines. + + .PARAMETER Path + The repository folder. + + .PARAMETER Arguments + The git arguments. + + .PARAMETER AllowFailure + Return nothing instead of throwing when git exits with an error. + + .EXAMPLE + Invoke-MtGit -Path ./mirror -Arguments 'rev-parse', 'HEAD' + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory)] + [string] $Path, + + [Parameter(Mandatory)] + [string[]] $Arguments, + + [switch] $AllowFailure + ) + + $errors = [System.Collections.Generic.List[string]]::new() + $lines = & git -C $Path @Arguments 2>&1 | ForEach-Object { + if ($_ -is [System.Management.Automation.ErrorRecord]) { $errors.Add($_.ToString()) } else { [string] $_ } + } + if ($LASTEXITCODE -ne 0) { + if ($AllowFailure) { return } + throw "git $($Arguments -join ' ') failed in ${Path}: $($errors -join ' ')" + } + $lines +} diff --git a/build/steps/helpers/Read-MtLearnIndex.ps1 b/build/steps/helpers/Read-MtLearnIndex.ps1 new file mode 100644 index 0000000000..ec0c46b5d7 --- /dev/null +++ b/build/steps/helpers/Read-MtLearnIndex.ps1 @@ -0,0 +1,60 @@ +function Read-MtLearnIndex { + <# + .SYNOPSIS + Reads the URL-to-file index and the redirect answers that Update-MtLearnMirror.ps1 writes. + + .DESCRIPTION + Update-MtLearnMirror.ps1 keeps its cache folder laid out like this: + + mirrors// a clone of each Learn mirror + index.json every page of every mirror: key -> Mirror, Path (and Target when Learn redirects it) + redirects.json what Learn answered for linked URLs that no mirror has under that key + + Returns an object with Path (the cache folder), MirrorPath, Generated, Owner, Mirrors (name -> Repository, + Commit, CommitDate, Pages, Include, Exclude), Pages and Redirects. Pages and Redirects are dictionaries keyed + without regard to case. + + .PARAMETER CachePath + The cache folder. + + .EXAMPLE + $index = Read-MtLearnIndex -CachePath ./build/steps/.cache + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param( + [Parameter(Mandatory)] + [string] $CachePath + ) + + $indexFile = Join-Path $CachePath 'index.json' + if (-not (Test-Path -LiteralPath $indexFile -PathType Leaf)) { + throw "There is no Learn mirror index at '$indexFile'. Run build/steps/Update-MtLearnMirror.ps1 first." + } + $content = Get-Content -LiteralPath $indexFile -Raw | ConvertFrom-Json -AsHashtable -Depth 10 + + $pages = [System.Collections.Generic.Dictionary[string, object]]::new([System.StringComparer]::OrdinalIgnoreCase) + foreach ($entry in $content['Pages'].GetEnumerator()) { $pages[$entry.Key] = $entry.Value } + + $redirects = [System.Collections.Generic.Dictionary[string, object]]::new([System.StringComparer]::OrdinalIgnoreCase) + $redirectFile = Join-Path $CachePath 'redirects.json' + if (Test-Path -LiteralPath $redirectFile -PathType Leaf) { + $cached = Get-Content -LiteralPath $redirectFile -Raw | ConvertFrom-Json -AsHashtable -Depth 10 + if ($cached -and $cached['Redirects']) { + foreach ($entry in $cached['Redirects'].GetEnumerator()) { $redirects[$entry.Key] = $entry.Value } + } + } + + $mirrors = [ordered]@{} + if ($content['Mirrors']) { foreach ($entry in $content['Mirrors'].GetEnumerator()) { $mirrors[$entry.Key] = $entry.Value } } + + [pscustomobject]@{ + Path = $CachePath + MirrorPath = Join-Path $CachePath 'mirrors' + Generated = $content['Generated'] + Owner = $content['Owner'] + Mirrors = $mirrors + Pages = $pages + Redirects = $redirects + } +} diff --git a/build/steps/helpers/Resolve-MtLearnPage.ps1 b/build/steps/helpers/Resolve-MtLearnPage.ps1 new file mode 100644 index 0000000000..64a84c59e2 --- /dev/null +++ b/build/steps/helpers/Resolve-MtLearnPage.ps1 @@ -0,0 +1,84 @@ +function Resolve-MtLearnPage { + <# + .SYNOPSIS + Finds the mirror file of a Microsoft Learn URL, following the redirects that Update-MtLearnMirror.ps1 recorded. + + .DESCRIPTION + Makes no network calls: it reads only the index that Read-MtLearnIndex returns. Returns an object with Url, + Key, ResolvedKey (the page the URL ends up at), Mirror, Path (relative to the mirror's root), Detail and Status: + + - Mirrored a mirror has the page under this URL + - Redirected Learn redirects the URL to a page a mirror has + - NotInMirror the page is in the scope of a mirror (its include pattern), but the mirror doesn't have it + - NotMirrored the page exists, but no mirror covers it (Microsoft Graph, PowerShell reference and so on) + - Missing Learn answers 404 for it + - External Learn redirects it to another site (Detail holds the URL) + - Unresolved neither the index nor the redirect answers know it: run Update-MtLearnMirror.ps1 + + .PARAMETER Index + The index from Read-MtLearnIndex. + + .PARAMETER Url + The Learn URL. + + .EXAMPLE + Resolve-MtLearnPage -Index $index -Url 'https://learn.microsoft.com/mem/intune/protect/device-compliance-get-started' + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param( + [Parameter(Mandatory)] + [pscustomobject] $Index, + + [Parameter(Mandatory)] + [string] $Url + ) + + $key = ConvertTo-MtLearnKey $Url + $result = [pscustomobject][ordered]@{ + Url = $Url + Key = $key + ResolvedKey = $null + Status = 'Unresolved' + Mirror = $null + Path = $null + Detail = $null + } + if ($null -eq $key) { $result.Detail = 'Not a Microsoft Learn URL.'; return $result } + + $usePage = { + param($pageKey, $status) + $page = $Index.Pages[$pageKey] + $result.Status = if ($page['Target']) { 'Redirected' } else { $status } + $result.ResolvedKey = if ($page['Target']) { $page['Target'] } else { $pageKey } + $result.Mirror = $page['Mirror'] + $result.Path = $page['Path'] + } + + if ($Index.Pages.ContainsKey($key)) { & $usePage $key 'Mirrored'; return $result } + if (-not $Index.Redirects.ContainsKey($key)) { return $result } + + $answer = $Index.Redirects[$key] + switch ($answer['Status']) { + 'Missing' { $result.Status = 'Missing'; $result.Detail = 'Learn answers 404.' } + 'External' { $result.Status = 'External'; $result.Detail = $answer['To'] } + default { + $target = if ($answer['To']) { [string] $answer['To'] } else { $key } + if ($answer['Status'] -eq 'Redirect' -and $Index.Pages.ContainsKey($target)) { & $usePage $target 'Redirected'; break } + $result.ResolvedKey = $target + $result.Status = 'NotMirrored' + # The localized URL is what the mirrors' include patterns describe. + $localized = 'https://learn.microsoft.com/' + 'en-us/' + $target + foreach ($mirror in $Index.Mirrors.GetEnumerator()) { + $include = $mirror.Value['Include'] + if (-not $include -or $localized -notmatch "(?i)$include") { continue } + if (@($mirror.Value['Exclude']) | Where-Object { $_ -and $localized -match "(?i)$_" }) { continue } + $result.Status = 'NotInMirror' + $result.Mirror = $mirror.Key + $result.Detail = "The page is in the scope of $($mirror.Key), but the mirror doesn't have it yet." + break + } + } + } + $result +} diff --git a/build/steps/helpers/Split-MtLearnFrontMatter.ps1 b/build/steps/helpers/Split-MtLearnFrontMatter.ps1 new file mode 100644 index 0000000000..c49bbce5bf --- /dev/null +++ b/build/steps/helpers/Split-MtLearnFrontMatter.ps1 @@ -0,0 +1,55 @@ +function Split-MtLearnFrontMatter { + <# + .SYNOPSIS + Splits a mirrored Learn page into its front matter and its body. + + .DESCRIPTION + A page in a Learn mirror starts with YAML front matter between two --- lines: the page's title, canonicalUrl, + ms.topic, source_path (the file in the original repository) and original_content_git_url, among others. The + rest is the page as Learn serves it as Markdown, with includes expanded. + + Returns an object with: + + - FrontMatter: the top-level scalar keys of the front matter (key: value lines), as an ordered dictionary. + Lists and nested values are left out. + - Body: the text after the front matter, with Windows line endings changed to `n. + - BodyLine: the 1-based line number, in the file, of the body's first line. + + A page with no front matter has an empty FrontMatter and the whole text as Body. + + .PARAMETER Text + The page's text. + + .EXAMPLE + Split-MtLearnFrontMatter -Text (Get-Content -Raw ./overview.md) + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param( + [Parameter(Mandatory)] + [AllowEmptyString()] + [string] $Text + ) + + $normalized = $Text -replace "`r`n", "`n" + $lines = $normalized -split "`n" + $frontMatter = [ordered]@{} + $bodyIndex = 0 + if ($lines.Count -gt 1 -and $lines[0].TrimEnd() -eq '---') { + for ($i = 1; $i -lt $lines.Count; $i++) { + if ($lines[$i].TrimEnd() -eq '---') { $bodyIndex = $i + 1; break } + $pair = [regex]::Match($lines[$i], '^(?[A-Za-z0-9_.\-]+):[ \t]*(?.*)$') + if ($pair.Success -and $pair.Groups['value'].Value -ne '') { + $frontMatter[$pair.Groups['key'].Value] = $pair.Groups['value'].Value.Trim().Trim('"', "'") + } + } + # An opening --- with no closing one is not front matter. + if ($bodyIndex -eq 0) { $frontMatter = [ordered]@{} } + } + + [pscustomobject]@{ + FrontMatter = $frontMatter + Body = ($lines | Select-Object -Skip $bodyIndex) -join "`n" + BodyLine = $bodyIndex + 1 + } +} diff --git a/docs/proposals/defenders-path.md b/docs/proposals/defenders-path.md new file mode 100644 index 0000000000..23e9f0f448 --- /dev/null +++ b/docs/proposals/defenders-path.md @@ -0,0 +1,797 @@ +# Design: the defender's path + +> **Status: accepted for implementation, 2026-11-05.** The owner accepted every recommendation in section 17. +> Targets Maester 3.1: main is in the 3.0 code freeze from 7 November 2026. + +## 1. Summary + +Attack-path tools show the route an attacker takes. The defender's path shows the order a defender has to work +in: what has to be in place before a fix works, what a fix unlocks, and whether the tenant is ready for it. +Microsoft Learn documents this order page by page, but no assessment tool uses it. The owner ruled on 5 November +2026 that it should be Maester's strong point. + +The design adds four things: + +- **A catalogue of steps.** A step is one change an administrator makes ("Assign a compliance policy for each + platform") or one state the tenant must reach ("Devices that sign in are compliant"). The catalogue says + how steps relate (requires, requires one of, only when, recommended first, conflicts) and how to switch each + one on. Every relationship cites Microsoft Learn in Maester's own words. Goals group the steps that lead to + one outcome, such as "Require compliant devices". +- **A `Step` attribute on tests.** A test names the step it verifies. Tests in different suites that check the + same setting name the same step, so CIS, CISA, Maester and Zero Trust checks fall into one place. +- **`Steps` and `Goals` in the result.** For every step in scope the engine works out its status (Done, Not + done, Unknown, Not checked, Not applicable), whether it can start (Ready, Blocked, Unconfirmed), what blocks + it and what it unlocks, and its place in the order. The report, the console, CSV and Markdown all read + these. None of them works the order out again. +- **Measures.** Some prerequisites are states of the tenant, not settings: the share of devices that sign in + and are compliant, for example. The engine reads these figures from Graph for the steps in scope and compares + each with its step's threshold. A measure isn't a test. It has no severity and never changes a pass rate. + +A run without any test that names a step looks exactly as it does today. + +## 2. The problem + +The action plan ranks failed tests by severity, user impact and implementation cost (`priority()` in +`report/src/lib/model.ts`). It knows nothing about order. In a tenant with no Intune compliance policies it can +put MT.1001 ("At least one Conditional Access policy is configured with device compliance") near the top. +Following that advice before devices are enrolled and covered by compliance policies locks users out. The +guide for MT.1001 says only "Review the configuration described above." + +Microsoft Learn is explicit about the order for this change and many others: + +| Change | What Learn says comes first | +| --- | --- | +| Require a compliant device in Conditional Access | An Intune compliance policy, and at least one compliant device, before the policy is on | +| User-risk and sign-in-risk policies | Users registered for MFA, and password writeback for synced users. Remediate existing risky users first | +| Token protection | Windows devices joined or registered, Apple devices managed with the SSO plug-in. Pilot in report-only | + +Three things make this hard to bolt onto the current model: + +- Several suites check the same setting. MT.1001 and ZTA.24824 both check that Conditional Access requires a + compliant device. Prerequisites tagged on each test would be repeated and would drift. +- Many prerequisites are not settings. "Devices are enrolled" is a state of the tenant, so it needs its own + node and often its own check. +- Some prerequisites have alternatives, and some apply only to some tenants. Password writeback, for example, + matters only for synced users. + +So the unit is the change, not the test: tests point at a step, and the catalogue holds the facts. This is the +model the framework files already use. The mapping lives on the test's `Control`, and +`tests//frameworks/.json` holds the requirements. + +## 3. Terms + +| Term | Meaning | +| --- | --- | +| Step | One change or one tenant state, with an ID such as `intune.compliance-policies` | +| Prerequisite | A step that another step requires, requires one of, or recommends first | +| Goal | An outcome and the step that achieves it, such as "Require compliant devices". Its steps are that step and its prerequisites, followed down every level | +| Measure | A figure the engine reads from Graph for a step that is a tenant state, such as the share of compliant devices. The step is done when the figure meets its threshold | +| Verifying tests | The tests whose `Step` names a step | + +The name shown to readers is "Defender's path". In the report it reads as "Defender's path · Require compliant +devices · 3 of 7 steps done". + +## 4. The catalogue + +### 4.1 Files + +``` +powershell/assets/steps/ + goals.json the goals, in the order the report shows them + entra.json the steps whose Product is entra + intune.json + defender.json + ... one file per product key that has steps +``` + +The catalogue ships in the module beside the taxonomy registry and is read at run time, so it needs no build +step. Files are split by product to keep merge conflicts small. A step's file is named after the product in its +ID. + +Each file has this shape: + +```json +{ + "$schema": "./steps.schema.json", + "Product": "entra", + "Steps": [ ] +} +``` + +`powershell/assets/steps/steps.schema.json` describes both file types so that editors validate as you type. + +### 4.2 A step + +```json +{ + "Id": "entra.ca-require-compliant-device", + "Title": "Require a compliant device in Conditional Access", + "Summary": "Sign-ins from devices Intune does not mark compliant are blocked.", + "Requires": ["intune.compliance-policies", "intune.devices-compliant", "entra.emergency-access-excluded", "entra.ca-exclude-sync-accounts"], + "RequiresOneOf": [], + "RecommendedFirst": ["intune.mark-unassigned-noncompliant"], + "Conflicts": [], + "OnlyWhen": [], + "Rollout": [ + "Create the policy in report-only mode and review the sign-ins it would block.", + "Turn it on for a pilot group.", + "Turn it on for all users, keeping the emergency access accounts excluded." + ], + "Sources": [ + { + "Url": "https://learn.microsoft.com/entra/identity/conditional-access/policy-all-users-device-compliance", + "Mirror": "entra-docs-mirror", + "Note": "Create an Intune compliance policy first, and have at least one compliant device, or the policy blocks everyone.", + "Reviewed": "2026-11-05" + } + ] +} +``` + +| Field | Required | Rule | +| --- | --- | --- | +| `Id` | yes | `.`. The product key comes from the taxonomy, and the name is lowercase kebab-case. Stable once shipped, like a test ID | +| `Title` | yes | Imperative for a change ("Require…", "Assign…"), a statement for a state ("Devices that sign in are compliant"). One line | +| `Summary` | yes | One sentence on what changes for users or the tenant | +| `Requires` | no | Steps that must be done first, or the change fails or locks users out | +| `RequiresOneOf` | no | Groups of at least two steps. Any one step in a group is enough | +| `RecommendedFirst` | no | Steps that make this one safer or more useful. They never block | +| `Conflicts` | no | Steps that must be off before this one can be on. Declared on the step that needs the other one off | +| `OnlyWhen` | no | Conditions from section 4.4. All must hold, or the step is Not applicable | +| `Rollout` | no | Ordered sentences on how to switch it on safely | +| `Sources` | yes | At least one. See section 4.5 | +| `Measure` | no | `{ "Key": "", "MinimumShare": <1 to 100> }`. The figure that decides whether a state step is done (section 11) | +| `Unchecked` | when no test names the step and it has no `Measure` | Why Maester can't check it yet, in one sentence | + +A step has no severity, cost or licence of its own. Those stay on its verifying tests, so they are never +declared twice. A measure's service, licence and permissions are in the measure registry. + +### 4.3 Relationships + +| Relationship | Meaning | Effect on the plan | Example | +| --- | --- | --- | --- | +| Requires | Must be done first | Blocks the step while the prerequisite is Not done | Compliant-device CA requires compliance policies | +| RequiresOneOf | Any one of a group will do | Blocks the step while every step in the group is Not done | A managed-device grant is met by a compliant device or a hybrid joined one | +| RecommendedFirst | Works without it, but is safer after it | Orders only, never blocks | Remediate high-risk users (MT.1260) before the user-risk policy | +| Conflicts | The other step must be off first | Blocks the step while the conflicting step is Done | Conditional Access policies can't be turned on while security defaults are on | +| OnlyWhen | Applies to some tenants only | Not applicable when a condition is false | Password writeback, only for hybrid identity | +| Rollout | How to switch it on | Shown in How to fix | Report-only, a pilot group, then everyone | + +### 4.4 Conditions + +`OnlyWhen` takes keys from a closed list, so that the engine can evaluate every condition without running a +check: + +| Condition | True when | Read from | +| --- | --- | --- | +| `hybrid-identity` | The tenant syncs identities from on-premises | `onPremisesSyncEnabled` on the organization, which the tenant context already reads | +| `license:` | The tenant has the service plan, written as in a test's `License` | The licences the tenant context already reads | + +If a condition cannot be read, for example because Graph is not connected, the step is Unknown, not Not +applicable. New conditions are added to this list and to the engine together. + +A `license:` condition joins service plans with `&`, so every plan must be present. A step that any one of +several plans unlocks has no `OnlyWhen`, and its tests' `License` gates decide instead. PIM (Entra ID P2 or +Entra ID Governance) and Defender for Endpoint (P1, P2 or Business) are both like this. + +### 4.5 Sources and wording + +- `Url` is the Learn page with no locale, the form the check guides use. +- `Mirror` names the Learn mirror repository that holds the page, out of the nine `merill/*-docs-mirror` + repositories. The tooling of section 13 finds the file from the URL, so the path is not written by hand. +- `Note` is Maester's own wording of what the page says about order, up to 200 characters. Never copy + Microsoft's text. +- `Reviewed` is the date someone last read the page against the step. The change-detection workflow compares + it with the mirror's history. +- A relationship that Learn does not document can cite a maintainer instead: + `{ "Maintainer": "merill", "Note": "...", "Reviewed": "..." }`. The unit tests count these, and the review keeps + them rare. + +### 4.6 Goals + +```json +{ + "Goals": [ + { + "Id": "compliant-devices", + "Title": "Require compliant devices", + "Summary": "Only devices that Intune manages and marks compliant can reach Microsoft 365.", + "Step": "entra.ca-require-compliant-device" + } + ] +} +``` + +A goal's steps are not listed. They are its `Step` plus everything that step requires, requires one of, or +recommends first, followed down every level. A step can belong to several goals. For example, +`entra.emergency-access-excluded` sits under five goals: compliant devices, managed devices, risk policies, +phishing-resistant MFA and token protection. Goal IDs are lowercase kebab-case with no product prefix, because a +goal often spans products. + +## 5. The `Step` attribute + +```powershell +[MaesterTest( + Id = 'MT.1001', + Title = 'At least one Conditional Access policy is configured with device compliance.', + Product = 'entra', + Feature = 'conditional-access', + Step = 'entra.ca-require-compliant-device', + ... +)] +``` + +| Property | Type | Values | Built-in tests | Notes | +| --- | --- | --- | --- | --- | +| `Step` | string[] | step IDs | optional | Usually one value, at most three. Pattern `^[a-z0-9][a-z0-9-]*\.[a-z0-9][a-z0-9-]*$`, at most 80 characters. Stored in lowercase | + +- It is added to `MaesterTestAttribute` in `src/Maester.Engine` and to `powershell/assets/MaesterTestSchema.psd1` + together, since a unit test compares them. The DLL in `powershell/lib/` is rebuilt. +- A built-in test must name steps that exist in the catalogue, or the build fails. A custom test or a pack test + may name any built-in step. A step ID the catalogue does not have stays on the row with a warning and is left + out of `Steps`. Custom catalogues are not part of this design (section 18). +- A family instance can set `Step` the way it sets `Product` and `Feature` on the + `feat/zta-taxonomy-mapping` branch (`Get-MtInstanceAttribute`). The Zero Trust pack takes each test's + steps from its hand-kept `taxonomy.json`, next to `AlsoCheckedBy`. +- Pester-format tests have no `Step`. +- Tests with different definitions of done get different steps, even when they read the same setting. CISA + MS.AAD.3.7 asks for a compliant or a hybrid joined device, and CIS 5.2.2.9 for an all-users policy that may + accept either. MT.1001 needs device compliance. So CISA 3.7 and CIS 5.2.2.9 name + `entra.ca-require-managed-device` and MT.1001 names `entra.ca-require-compliant-device`. Otherwise one step + would pass and fail in the same run. +- A test names a step only when a tenant set up the way Learn describes passes it. A test may check less than + the step, and then it is one of several verifiers. A test that fails Learn's own setup, for example because it + rejects a control Learn now recommends, names no step until it is fixed (section 15). +- `Step` is not a taxonomy tag and adds no tag. `Get-MtTest -Step` and `Invoke-Maester -Step` select by it + (section 8). + +## 6. A step's status in a run + +### 6.1 Status + +A step's status comes from the results of its verifying tests in this run and, for a step with a `Measure`, +from the figure the engine read. A test the run did not select counts as not run. + +| Status | Rule, checked in this order | +| --- | --- | +| Not applicable | An `OnlyWhen` condition is false, or every verifying test that ran was skipped as `NotApplicable` | +| Not done | Any verifying test failed, or the measure is below its threshold | +| Unknown | Nothing failed, but a test ended as Investigate, Error or Skipped, or the measure couldn't be read (service not connected, no licence, missing permission). The reason codes are kept | +| Done | Every test that ran passed and the measure, if there is one, met its threshold. At least one test or measure gave a result | +| Not checked | No verifying test ran and no measure was read. `Reason` is `NotSelected` when tests exist, `MeasureOff` when the run config turned the measure off, and `NoCheck` when the step has neither (it is `Unchecked`) | + +Done means done as far as this run checked. The step record says how many of its tests ran ("1 of 2 checks +ran"). The three statuses Not done, Unknown and Not checked never blur. Unknown says the run could not tell, +Not checked says it did not look, and neither is counted as Not done. + +### 6.2 Readiness + +Readiness applies to steps that are Not done, Unknown or Not checked. Prerequisites that are Not applicable +count as met, except inside a `RequiresOneOf` group. There a Not applicable step is left out of the group, and a +group with no step left counts as met. Otherwise `entra.hybrid-join`, which applies only to hybrid tenants, would +meet the device group of `entra.ca-require-managed-device` in every cloud-only tenant. + +| Readiness | Rule | +| --- | --- | +| Blocked | A `Requires` step is Not done, every step of a `RequiresOneOf` group is Not done, or a `Conflicts` step is Done. `BlockedBy` lists them | +| Unconfirmed | Not blocked, but a prerequisite is Unknown or Not checked. `Unconfirmed` lists them | +| Ready | Every `Requires` step is Done and every `RequiresOneOf` group has a step that is Done | + +`RecommendedFirst` never changes readiness. It appears as "Recommended first" with the step's status. + +### 6.3 Order + +Steps get a `Rank` so that every output lists them in the same order: + +1. **Group:** Ready, then Unconfirmed, then Blocked. Within the Unconfirmed group, the prerequisites to check + come right before the steps they would confirm. +2. **Dependencies:** `Requires`, `RequiresOneOf` and `RecommendedFirst` edges, in topological order. The unit + tests guarantee that the graph has no cycles. +3. **Value:** a step's own value is the highest `priority()` among its failed tests. Its unlock value is the sum + of the values of the Not done steps that depend on it, at any depth. "Enroll devices in Intune" therefore + ranks by the controls it enables, not by its own severity. +4. **ID**, so the order is stable. + +`priority()` moves from the report into the engine as `Get-MtTestPriority`, so that the console and Markdown rank +the same way. The report keeps its copy for results that have no `Steps`. A unit test checks that the two give +the same numbers on the golden fixture. + +The defender's path adds no score. Pass rates, framework coverage and the headline numbers are unchanged. + +## 7. Results + +### 7.1 Rows + +Every native row gains `Step` (a list, empty when the test names none). A family instance's row carries the +instance's value. + +### 7.2 `Steps` and `Goals` + +Two top-level properties. Like `Packs` and `Attachments`, they are written only when they have content (here, +when a row in the result names a step), so every other result stays as it is. + +```json +"Steps": [ + { + "Id": "entra.ca-require-compliant-device", + "Title": "Require a compliant device in Conditional Access", + "Summary": "Sign-ins from devices Intune does not mark compliant are blocked.", + "Product": "entra", + "Goals": ["compliant-devices"], + "Status": "NotDone", + "Reason": null, + "Readiness": "Blocked", + "BlockedBy": ["intune.compliance-policies"], + "Unconfirmed": ["intune.devices-compliant"], + "Unlocks": [], + "Rank": 9, + "Tests": [ + { "Id": "MT.1001", "Result": "Failed" }, + { "Id": "ZTA.24824", "Result": "NotRun", "ReasonCode": "NotInRun" } + ], + "Earlier": null, + "Measure": null, + "Requires": ["intune.compliance-policies", "intune.devices-compliant", "entra.emergency-access-excluded", "entra.ca-exclude-sync-accounts"], + "RequiresOneOf": [], + "RecommendedFirst": ["intune.mark-unassigned-noncompliant"], + "Conflicts": [], + "OnlyWhen": [], + "Rollout": ["..."], + "Sources": [{ "Url": "...", "Note": "...", "Reviewed": "2026-11-05" }] + } +], +"Goals": [ + { + "Id": "compliant-devices", + "Title": "Require compliant devices", + "Step": "entra.ca-require-compliant-device", + "Steps": ["entra.emergency-access-excluded", "intune.compliance-policies", "..."], + "Done": 3, + "Applicable": 7, + "Status": "InProgress" + } +] +``` + +- **Scope.** A step is in scope when a row that ran names it, or when it is a prerequisite, at any depth, of + such a step. A goal is in scope when any of its steps is. A row ran when its result is anything but + `NotRun`. +- **Tests come from the inventory, not only the rows.** `Tests` lists every test the engine knows that names + the step: built-in tests from the catalog, custom tests that were discovered, and pack tests from each pack's + catalogue. A test with no row has `Result` `NotRun` and `ReasonCode` `NotInRun`. The report can then name the + command that checks it. This is how `Frameworks` already lists requirements that no row checks. +- **`Measure`** is set on a step that has one, whether or not it could be read: + `{ "Key": "devices-compliant", "Count": 412, "Total": 580, "Share": 71, "MinimumShare": 95, "Met": false, + "ReadAt": "...", "Caveat": "...", "ObjectCount": 168, "Objects": [{ "Type": "Device", "Id": "...", + "DisplayName": "..." }], "ReasonCode": null }`. `Objects` holds up to 100 of the objects that fall short. `ReasonCode` says why a measure + couldn't be read, with the same codes a skipped test uses. +- **`Earlier`** is set on a step that is Not checked in this run when an earlier result in the output folder + checked it: `{ "Status": "Done", "ExecutedAt": "...", "File": "..." }`. It is never mixed into this run's + status or counts. `Get-MtPreviousResult` gains `LastKnown`, which is the newest earlier result for each test ID + a step in scope names. It reads only files that `History` already lists, and only when some step in scope is + Not checked. Today `Results` covers the newest earlier run only, and after a one-check run that run says + little. +- **Goal status** is `Done` when every applicable step is Done, `NotStarted` when none is, and `InProgress` + otherwise. When a step is Unknown or Not checked, the goal shows that count next to its progress. +- Built by `Get-MtResultStep` (internal, `powershell/internal/report/`) in `ConvertTo-MtMaesterResult`, next to + `Get-MtResultFramework`. `Merge-MtPartitionResult` builds it again from the merged rows, as it does + `Frameworks`, so that a multi-tenant or partitioned run is ordered as a whole. +- Additive, so the result schema moves from 2.1 to 2.2, and `website/docs/result-schema.md` documents both + properties. + +### 7.3 Other outputs + +| Output | Change | +| --- | --- | +| CSV and Excel | `Step`, `Readiness` and `BlockedBy` columns on each test row | +| Markdown report | A "Do these first" list: the first five Ready steps, each with its failed tests. A one-line count of Blocked and Unconfirmed steps | +| JUnit XML | None | +| Console | One line in the run summary when `Steps` is present: `Defender's path: 3 ready · 2 blocked · 1 to check first` | + +### 7.4 Choices made in M3 + +Where the design was silent, M3 chose the simplest thing consistent with it. `website/docs/result-schema.md` documents +the result as built. + +- **Reason codes.** `Reason` is also set for `NotApplicable` (`ConditionNotMet`, `TestsNotApplicable`) and `Unknown` + (`ConditionUnknown`, else the first reason code of the tests or the measure, or `Investigate` for a test that ended + as Investigate, which has no reason code). A measure that can't be read carries `ServiceNotConnected` or + `LicenseNotFound` as a test would, and two codes tests don't have: `PermissionNotGranted` (the Graph connection lists + its permissions and lacks every alternative of one; a 403 from the reader gives it too) and `MeasureError` (the + reader threw). `MeasureOff` is the `ReasonCode` of a measure the run config turned off. +- **Mixed verifiers.** A test skipped as `NotApplicable` next to tests that gave a result is left out, not counted as + Unknown. An `OnlyWhen` condition that can't be read makes the step Unknown before any test is looked at. +- **Readiness and Conflicts.** `BlockedBy` and `Unconfirmed` are both filled whatever the readiness, so a Blocked step + still lists what is left to check. A conflicting step that is Unknown or Not checked is Unconfirmed. Conflicting + steps are in scope (without their own prerequisites), so their status is known. +- **Rank.** Done steps follow the Blocked group, then Not applicable steps. Within a group, the order is topological + over the edges between members of the group; among the steps that can come next, the highest value (own value + plus unlock value) wins, then the ID. +- **Unlocks** lists the steps in scope that depend on the step directly and are not Done or Not applicable, in rank + order. +- **Tests** always carry `ReasonCode` (`null` when none) and are sorted by ID with the numbers compared as numbers. + A family test is left out when its instances have rows. +- **Measures.** `Share` is the whole percentage rounded down, so a step never shows 95% while it misses 95%; `Met` + compares `Count` and `Total` exactly. With no object to count (`Total` 0), `Share` is `null` and `Met` is false: + a compliant-device policy with no compliant device blocks everyone. Measures are read in `Invoke-Maester` right + after the tests, while affected objects are still collected, and the readers write facts for the objects they + list (source `Maester measures`): `device.managed`, `device.compliant`, `device.os`, `device.joinType`, and + `user.mfaCapable` and `user.mfaRegistered` under the object ID and the UPN. The Affected objects page lists the + same objects as `Steps[].Measure.Objects` (up to 100 per measure), with the source `Measure` and no test. +- **Goals.** A goal's `Steps` are its steps in scope, in catalogue order (prerequisites first). It also has + `Summary`, `Unknown` and `NotChecked`, and `Status` `NotApplicable` when none of its steps applies. +- **Earlier** comes from all the `LastKnown` entries of a step's tests, judged by the status rules without measures; + `ExecutedAt` and `File` are the newest entry's. +- **Tenant context.** The tenant context did not read `onPremisesSyncEnabled`. It now records it as `HybridIdentity` + from the organization it already reads, with no extra request. +- **Selection.** `-IncludePrerequisites` is a second pass of `Resolve-MtNativePlan` (`-PrerequisiteStep`): the include + selectors (`-TestId`, the typed selectors, `-Tag`) are lifted for tests of the prerequisites, and the exclusions + (`-ExcludeTestId`, `-ExcludeProduct`, `-ExcludeTag`, a disabled or unlisted test) still apply. A long-running family + keeps its long-running exclusion, which is how the Zero Trust family stays out without `-Suite ZTA` or + `-IncludeLongRunning`. `Selection.Step` and `Selection.IncludePrerequisites` get no default in the resolved config, + so a resolved config without them is unchanged. +- **Priority parity.** `Get-MtTestPriority` is checked against numbers computed with the report's formula. A test on + the report side that compares its `priority()` with the same rows is for M4. + +## 8. Selection + +| Parameter | Config key | Selects | +| --- | --- | --- | +| `-Step` | `Selection.Step` | Tests whose `Step` matches. Takes a list, and `*` wildcards work (`intune.*`) | +| `-IncludePrerequisites` | `Selection.IncludePrerequisites` | Adds the verifying tests of every prerequisite of the steps that the selected tests name, at any depth | + +- They combine with the other selectors as in section 4 of the + [test attributes design](./maester-3.0-test-attributes.md). `-IncludePrerequisites` is applied last, so + `Invoke-Maester -TestId MT.1001 -IncludePrerequisites` runs MT.1001 and the checks of everything it depends on. +- Prerequisite tests that are Preview or LongRunning are included when `-IncludePrerequisites` reaches them, + the same way an exact `-TestId` includes them. The ZTA family is the exception: it is included only when + `-Suite ZTA` or `-IncludeLongRunning` is also given, because it runs the whole assessment. Its steps then show + as Not checked with that command. +- `Get-MtTest -Step` filters the same way. There is no goal selector, because `-Step + -IncludePrerequisites` selects a whole goal. No new public command is added in Phase 1. +- Measures are not selected. After the tests, the engine reads the measure of every step in scope, so a run of + MT.1001 alone still shows how many devices are compliant. In the run config, `Measures.Enabled` (default + `true`) turns measures off, and `Measures.MinimumShare.` changes a threshold. + +## 9. Report + +Every view below is hidden when the result has no `Steps`, the same way views without data are hidden today. + +- **Action plan.** Opens with the defender's path: three groups of step cards in `Rank` order: Ready now, Check + first and Blocked. A card shows the step, its failed tests or its measure ("71% of devices that sign + in are compliant, 95% needed", with the devices that fall short), what it unlocks ("unlocks 2 steps, 6 failed + checks"), its rollout and its sources. Below the groups, a lane for each goal in scope shows its steps in + order with a status chip each. The existing ranked list of failed tests stays below that. A failed test whose + step is Blocked moves after the tests that can be fixed now and shows "Blocked by …". +- **Test page.** When the test's step has prerequisites, a "Before you fix this" panel lists each one with its + status and where that status came from: a test in this run, a measure (with its figure), an earlier run (with + its date), or Not checked. It also gives + the command that checks what is missing: + `Invoke-Maester -TestId MT.1001 -IncludePrerequisites`. The How to fix tab adds the step's rollout. +- **Overview.** One card: Ready now, Blocked and Check first counts, with a link to the action plan. +- **Small runs.** With one to three tests that ran, there are no lanes. Each test page carries "Before you fix + this" (section 10). + +The report reads `Steps` and `Goals` as written and works out nothing itself. + +## 10. Scoping rules + +The rule for every output: scope everything to what ran, and never infer a status for a test that did not run. + +| Run | Report | Console | Result | +| --- | --- | --- | --- | +| Full run | Groups and a lane for every goal in scope | The summary line | `Steps`, `Goals` | +| One suite or product | Only goals with a step in scope. A step whose tests were not selected shows "Not checked in this run" and the command to include them | The line, when a step is in scope | The steps in scope, with all their tests | +| One to three tests | No lanes. "Before you fix this" on each test page, with the measures of the prerequisites and `Earlier` statuses with their dates | Nothing extra | The same | +| Tests that name no step (GitHub, Azure DevOps, Active Directory, most custom tests) | No change. The views stay hidden | No change | No `Steps` | +| A verifying test that couldn't run, or a measure that couldn't be read (service not connected, no licence, missing permission) | The step is Unknown, with the reason and the fix command, and never Not done | Counted with the tests that didn't run | `Status` `Unknown` with the reason codes | + +## 11. Measures + +17 of the 43 steps in the first catalogue have no Maester check (section 15). Two of them are tenant states that +a figure from Graph settles, so in Phase 1 they get measures, not tests. The owner ruled on 5 November 2026 that +readiness is a data point, not a test. A share of compliant devices isn't a misconfiguration and has no meaningful +severity or ATT&CK technique, so it must not change pass rates or the test count. A measure also runs whenever its +step is in scope, so "Before you fix this" shows a real figure even after a one-test run, where a test would have +had to be selected. + +A measure is an entry in the measure registry, `powershell/assets/MaesterMeasures.psd1`: + +```powershell +@{ + Measures = @( + @{ + Key = 'devices-compliant' + Function = 'Get-MtDeviceComplianceShare' + Title = 'Devices that sign in are compliant' + Unit = 'devices' + Caveat = "Devices that aren't registered or joined in Microsoft Entra ID can't be counted. ..." + Service = 'Graph' + License = 'INTUNE_A' + Permission = 'Graph:Scope:Device.Read.All | Graph:Scope:Directory.Read.All' + } + ) +} +``` + +- `Service`, `License` and `Permission` use the grammar of the test attributes, and the engine applies them the + way it gates a test. A measure whose gate fails is Unknown with the matching reason code. +- `Function` names an internal reader in `powershell/internal/services//`. It reads through the Graph + cache and returns `Count` (the objects that meet the bar), `Total`, and `Objects` (those that fall short, as + `Type`, `Id` and `DisplayName`). The engine keeps up to 100 of them. +- `Caveat` is optional: one line of 200 characters or less on what the figure can't see or leaves out. The + engine copies it to the step's `Measure`, and the report shows it with the figure. +- The engine works out `Share`, compares it with the step's `MinimumShare` or the run config's override, and + writes the result to the step (section 7.2). +- Facts attach only to objects the run lists (section 12). Readers write facts with the shared keys for the + objects they list once M3 puts a measure's objects on the Affected objects page. + +| Key | Step | Reads | Notes | +| --- | --- | --- | --- | +| `devices-compliant` | `intune.devices-compliant` | Entra `devices` that signed in within 30 days, by `isManaged` and `isCompliant` | Needs Intune (`INTUNE_A`): only Intune marks devices compliant, and a compliance partner's devices need Intune licences too. The objects are the devices a compliant-device policy would block. Devices with no Entra identity can't be seen, and the caveat says so | +| `mfa-capable` | `entra.mfa-registered` | `reports/authenticationMethods/userRegistrationDetails` for enabled member users, by `isMfaCapable` | Needs Entra ID P1. `isMfaCapable`, not `isMfaRegistered`, because a method the authentication methods policy doesn't allow can't complete MFA. Leaves out guests and the emergency access and directory sync accounts | + +Later: phishing-resistant method registration for all users (ZTA.21782 covers privileged users only), +password writeback once a Graph API reports it, security defaults being off in tenants licensed for +Conditional Access (section 15), and hybrid join and Windows device registration, which need sign-in data to +see the devices that have no identity yet. The emergency access accounts holding Global Administrator as a +permanent active assignment is another state with no Maester check. + +The Defender–Intune connector is not covered. MT.1098 checks the health of the Mobile Threat Defense connectors it +finds, and skips or passes when the Defender connector is missing. The `defender-device-risk` goal needs four +checks before Maester can follow it: the Defender connector is enabled, its compliance toggle is on for each +platform that has a compliance policy, and Windows and Android Enterprise compliance policies require a machine +risk score. + +A measure isn't a test: it has no ID, no row in `Tests` and no attribute review, and it plays no part in pass +rates, frameworks or the test count. Packs can't add measures in Phase 1. + +## 12. Object facts + +The Zero Trust facts work (`Add-MtAffectedObjectFact`, maester365/maester#2681) puts facts on +listed objects: join type, managed and compliant for devices, MFA and passwordless for users. They are the +drill-down behind a lane ("38 devices aren't managed"). They can't replace measures, because facts attach +only to objects the run lists and come from the Zero Trust export only when it ran. Measures write facts too. + +This design asked that work to give each fact a stable key and a raw value before the command ships, so that a +lane's drill-down never parses display text. It did, in maester365/maester#2681: a fact has `Name`, `Value` +(display text), `Tone`, an optional `Key` (dotted camelCase, `^[a-z][A-Za-z0-9]*(\.[a-z][A-Za-z0-9]*)+$`), an +optional `Raw` (boolean, number, string, string list, or ISO 8601 UTC date), `Source` and `AsOf`. A fact with the +same `Key` from the same `Source` replaces the earlier one. The shared keys are listed under "Fact keys" in +`website/docs/writing-tests/formatting-test-results.md`. The ones this design reads: + +| Key | Raw | Used for | +| --- | --- | --- | +| `device.managed`, `device.compliant` | bool | The devices behind `intune.devices-compliant`. Management and compliance are separate facts | +| `device.joinType` | `AzureAd`, `ServerAd` or `Workplace` | Join coverage, for hybrid join and token protection | +| `device.os` | string | Which platforms need a compliance policy | +| `user.mfaRegistered`, `user.passwordless` | bool | The users behind `entra.mfa-registered` and the phishing-resistant steps. The `mfa-capable` measure counts `isMfaCapable`, which `user.mfaRegistered` doesn't cover, so M3 adds a `user.mfaCapable` key to the shared list | +| `user.privilegedRoles` | string list | The admins step of phishing-resistant MFA, and the privileged access goal | +| `signIn.daysSince` | int, or null when none is recorded | Leaving out stale devices and users. Counted from the fact's `AsOf`, not from now | + +User facts are recorded under both the object ID and the UPN, so a record has them whichever way it was keyed. +The measures write the same keys for the objects they list. + +## 13. Keeping the catalogue current + +The sources are the nine Learn mirrors built with `merill/learn-mirror`. They crawl Learn four times a day and +make one commit per changed page. They cover Entra, Intune, Defender, security (Zero Trust), Purview, Teams, +SharePoint, Exchange and Windows Server. The tooling lives in `build/steps/`: + +| Script | Job | +| --- | --- | +| `Update-MtLearnMirror.ps1` | Clones or updates the mirrors into a cache folder, and builds a URL-to-file index. Old URLs are followed through Learn's redirects: 23 of the 77 Intune and Defender links in check guides are redirects today | +| `Find-MtStepCandidate.ps1` | For the Learn pages that check guides and catalogue sources link, pulls the prerequisite sections and sentences ("before you", "first", "must", "won't work without") with their file and line. Writes proposals as JSON for a maintainer, and optionally asks a model to reword them as `Note` text. Nothing enters the catalogue without review | +| `Test-MtStepSource.ps1` | For each source, lists the mirror commits to its file since `Reviewed`. Exits non-zero when any changed | + +A scheduled workflow, `.github/workflows/step-sources.yaml`, runs `Test-MtStepSource.ps1` weekly and keeps one +issue open that lists the steps whose sources changed, with the diff link for each. It opens issues, never pull +requests. A maintainer re-reads the page and bumps `Reviewed`. + +The unit tests make no network calls. They check that every `Url` is a well-formed Learn URL. Only the workflow +checks it against the mirrors. + +## 14. Enforcement + +`powershell/tests/general/StepCatalog.Tests.ps1`: + +- every file matches the schema and has no unknown keys; +- step IDs are unique, their product key is in the taxonomy, and the file they are in is named after that key; +- every ID in `Requires`, `RequiresOneOf`, `RecommendedFirst`, `Conflicts` and a goal's `Step` exists; +- every `RequiresOneOf` group has at least two steps, and no step names the same step in two relationships; +- `Requires`, `RequiresOneOf` and `RecommendedFirst` together have no cycle, and the message names the cycle; +- every `OnlyWhen` key is a known condition; +- every step has a source, every `Note` is 200 characters or less, and maintainer-only sources are under 10% + of all sources; +- every step belongs to at least one goal, and goal IDs are unique; +- every `Measure` key is in the measure registry and its `MinimumShare` is from 1 to 100, and every registry + entry names a reader function the module has. + +`Get-MtStepProblem` makes these checks, plus two about the tests: every `Step` that a built-in test or a +`packs/*/taxonomy.json` names exists, and (with `-Coverage`, over every built-in test) `Unchecked` is set exactly +on the steps that no test names and that have no `Measure`. `./build/Build-MaesterModule.ps1` fails on all of them except the `Unchecked` +check, because the build can run on a folder that holds only some of the tests. A run only warns about a step +the catalogue does not have. + +## 15. The first catalogue + +Milestone M2 checked every step and relationship against the Learn mirrors on 5 November 2026. Where Learn +disagreed with the draft, Learn won. The catalogue has 43 steps (27 Entra, 9 Intune, 7 Defender) in eight goals, +with 76 sources. All of them cite Learn; none cites a maintainer. 43 tests name a step: 37 hand-written tests, +plus 3 EIDSCA and 3 ORCA tests, whose generators now read `Step` from their metadata files. 17 steps have no +Maester test. Two of them get measures (section 11), and the other 15 are `Unchecked`. For 9 of those the Zero Trust +pack has a check today (for one, on Android only), and their `Unchecked` text names its IDs. The pack's tests name steps once its `taxonomy.json` (on `feat/zta-taxonomy-mapping`) carries +`Step`. + +Each row lists the steps in the order the catalogue puts them. The brackets give conditions and the main +relationships: "recommended first" marks a `RecommendedFirst` and "one of" a `RequiresOneOf` group. The step files +have the exact lists. The tests are listed in the same order as the steps, separated by a dot. + +| Goal (steps) | Steps, in order | Verifying tests | +| --- | --- | --- | +| Foundation, under most goals | `entra.emergency-access-accounts` (recommended first) → `entra.emergency-access-excluded` · `entra.ca-exclude-sync-accounts` (only when `hybrid-identity`) | unchecked (ZTA.21835) · MT.1005, MT.1034 · MT.1020 | +| `compliant-devices` Require compliant devices (8) | `intune.compliance-policies` → `intune.automatic-enrollment` (recommended first) → `intune.devices-compliant` → `intune.mark-unassigned-noncompliant` (recommended first) → `entra.ca-require-compliant-device` | unchecked (ZTA.24541–24543, ZTA.24545, ZTA.24547) · unchecked (ZTA.24546) · measure `devices-compliant` · MT.1054, CIS.M365.4.1 · MT.1001 | +| `managed-devices` Require managed devices (10) | `entra.hybrid-join` (only when hybrid) → `entra.ca-require-managed-device-admins` (needs one of `intune.compliance-policies` and `entra.hybrid-join`; recommended first) → `entra.ca-require-managed-device` (needs one of `intune.devices-compliant` and `entra.hybrid-join`) | unchecked · MT.1014 · CIS.M365.5.2.2.9, CISA.MS.AAD.3.7 | +| `risk-policies` Use risk-based Conditional Access (10) | `entra.mfa-registered` → `entra.trusted-named-locations` (recommended first) → `entra.ca-sign-in-risk` (recommended first) · `entra.remediate-risky-users` and `entra.password-hash-sync` (only when hybrid; both recommended first) · `entra.password-writeback` (only when hybrid) → `entra.ca-user-risk` | measure `mfa-capable` · CIS.M365.5.2.2.14 · CIS.M365.5.2.2.7, MT.1012 · MT.1260 · CIS.M365.5.1.8.1 · unchecked · unchecked (see below) | +| `phishing-resistant-mfa` Require phishing-resistant MFA (12) | `entra.temporary-access-pass` (recommended first) and one of `entra.passkeys-enabled`, `intune.windows-hello`, `entra.certificate-based-auth`, `intune.macos-platform-sso` → `entra.phishing-resistant-registered-admins` → `entra.phishing-resistant-admins` (recommended first) · `entra.phishing-resistant-registered-all` → `entra.phishing-resistant-all` | EIDSCA.AT01 · EIDSCA.AF01, AF02 · unchecked (ZTA.24551) · unchecked · unchecked (ZTA.24568) · unchecked (ZTA.21782) · CIS.M365.5.2.2.5 · unchecked (ZTA.21801) · CISA.MS.AAD.3.1, ASD.ISM-1872 | +| `privileged-access` Replace standing admin access with PIM (4) | `entra.emergency-access-accounts` → `entra.pim-approval-global-admin` and `entra.pim-notifications` (recommended first) → `entra.pim-eligible-roles` | unchecked (ZTA.21835) · CIS.M365.5.3.4, CISA.MS.AAD.7.6 · CISA.MS.AAD.7.7, 7.8, 7.9 · CIS.M365.5.3.1, ASD.ISM-1649, MT.1031, CISA.MS.AAD.7.5 | +| `token-protection` Protect sign-in tokens on Windows (5) | `entra.windows-devices-registered` and `entra.ca-block-unknown-platforms` (recommended first) → `entra.ca-token-protection-windows` | unchecked: needs sign-in logs · MT.1015 · CIS.M365.5.2.2.16 | +| `email-authentication` Authenticate mail from your domains (6) | `defender.spf` and `defender.dkim` (recommended first) → `defender.dmarc-published` (recommended first) → `defender.spf-hard-fail` (recommended first) → `defender.dmarc-enforce` (recommended first) → `defender.dmarc-reject`. The last two steps require SPF and DKIM | CIS.M365.2.1.8, CISA.MS.EXO.2.2 · CIS.M365.2.1.9, CISA.MS.EXO.3.1, ORCA.108, ORCA.108.1 · CISA.MS.EXO.4.1 · ORCA.235 · CIS.M365.2.1.10 · CISA.MS.EXO.4.2, MT.1182 | +| `defender-device-risk` Use Defender device risk in compliance (5) | `intune.defender-connector` → `intune.defender-compliance-evaluation` · `defender.endpoint-onboarding` and `intune.compliance-policies` (recommended first) → `intune.compliance-device-risk` | unchecked · unchecked (ZTA.24871, Android only) · unchecked (ZTA.41045) · see `compliant-devices` · MT.1231 | + +The count after each goal includes the foundation steps it reaches. A step can count in several goals, so the +counts add up to more than 43. + +### Changes from the draft + +- **A new goal, `managed-devices`.** A compliant or hybrid joined device is something Learn offers organizations + that aren't ready to require compliance for everyone (policy-all-users-device-compliance). It is another end + state, not a step towards compliant devices. It is also what CIS 5.2.2.9 and CISA 3.7 ask for. MT.1014 covers + admin roles only, so it gets its own step, `entra.ca-require-managed-device-admins`. Learn offers the admin + policy first, so that step is recommended first. `entra.hybrid-join` is new and Unchecked. Graph shows which + devices are hybrid joined, but not the domain PCs that aren't. +- **Foundation.** `entra.emergency-access-accounts` is new. Learn's prerequisite for PIM is that the accounts + exist and keep Global Administrator as a permanent active assignment (security-emergency-access, + pim-deployment-plan). That is a different fact from their Conditional Access exclusion. The same page creates + the accounts before it excludes them, so the new step is recommended before `entra.emergency-access-excluded`. +- **Risk policies.** + - Password writeback is required only for the user-risk policy. Sign-in risk is cleared with MFA + (howto-identity-protection-configure-risk-policies). + - Password hash sync and remediating existing high-risk users are recommended before the user-risk policy. Learn + puts the review first in its deployment plan (how-to-deploy-identity-protection) and ties leaked-credential + detection to password hash sync (id-protection-faq). + - The goal ends at `entra.ca-user-risk`, with the sign-in risk policy recommended first. Unremediated sign-in risk + raises user risk (howto-identity-protection-remediate-unblock). + - Learn's rule that the two risk conditions go in separate policies is a warning, not an order. It is now in both + steps' rollout, so `entra.ca-risk-policies-separate` and MT.1049 left the catalogue. + - `entra.trusted-named-locations` (CIS 5.2.2.14) is new and recommended before sign-in risk. Some detections use + trusted locations to cut false positives. + - `entra.ca-user-risk` is `Unchecked`. Learn now recommends the Require risk remediation grant (policy-risk-based-user), + and MT.1013 and CIS 5.2.2.6 accept only Require password change. +- **Phishing-resistant MFA.** + - Windows Hello for Business is one of the methods that meet the phishing-resistant strength, not a link in the + chain (concept-authentication-strengths). It is now `intune.windows-hello`, in a "one of" group with passkeys, + certificate-based authentication and macOS Platform SSO. A tenant that uses only one of them is not blocked. + - Registration is split into admins and all users, and enforcement requires each. Learn warns that an + unregistered admin can lock the tenant out (policy-admin-phish-resistant-mfa). + - The Temporary Access Pass is one of two ways to bootstrap registration, so it is recommended first, not + required. + - Admins come first "typically", so the admin policy is recommended before the all-users one, not required. +- **Privileged access.** + - The draft's `entra.pim-alerts` became `entra.pim-notifications`. CISA 7.7 checks notification recipients, not + PIM security alerts. + - `entra.pim-approval-global-admin` (CIS 5.3.4, CISA 7.6) is new. It requires the emergency access accounts, + because approval with no available approver locks the tenant (pim-how-to-change-default-settings). + - Learn sets role settings before it hands out eligible assignments (pim-getting-started), so both settings steps + are recommended first. + - `entra.pim-roles-used` (MT.1030) left the goal. Learn treats unused roles as an alert to act on and access + reviews as the prevention, not as a rollout step. +- **Token protection.** The step is `entra.ca-token-protection-windows`, because every test checks a Windows + policy and Learn deploys Apple separately with its own prerequisites. Device registration is recommended first, + not required: current Windows builds prompt unregistered users to register (deployment-guide-token-protection-windows). + The same guide pairs the policy with blocking unknown platforms, which MT.1015 checks. +- **Email authentication.** + - The steps are `defender.*`. Learn documents them under Defender for Office 365, DKIM is set up in the Defender + portal, and most of the tests declare `defender`. + - SPF and DKIM are required only by the steps that enforce DMARC. A p=none record changes no delivery, and Learn + advises publishing one early to find senders (email-authentication-spf-configure). + - `dmarc-monitor` became `defender.dmarc-published` (CISA 4.1). + - CIS 2.1.10 rejects p=none, so it verifies `defender.dmarc-enforce`, which means quarantine or reject with + reports on every domain, as the deployment guide asks (mdo-deployment-guide). + - The goal ends at p=reject (`defender.dmarc-reject`, CISA 4.2 and MT.1182). + - ORCA.235 fails `~all`, so it verifies its own step, `defender.spf-hard-fail`. +- **Defender device risk.** + - Learn connects the services before it onboards devices, so the draft order is reversed. + - The connector's per-platform compliance toggle is a step of its own (configure-integration). + - Compliance policies are recommended first, not required, because the risk score is one setting inside them. + - MT.1098 doesn't verify the connector (section 11). MT.1235 reads the third-party threat level on Android + device administrator, not Defender's risk score. MT.1216 reads a macOS setting that Learn doesn't document. + Only MT.1231 (iOS) verifies the step. + +### Tests that check a related setting but name no step + +| Tests | Why | +| --- | --- | +| MT.1013, CIS.M365.5.2.2.6 | Reject Learn's Require risk remediation grant. They name `entra.ca-user-risk` once they accept it, which needs `Prefer: include-unknown-enum-members` on the policy request | +| CISA.MS.AAD.2.1, CISA.MS.AAD.2.3, CIS.M365.5.2.2.8 | Block risky users or sign-ins. Learn prefers self-remediation and treats a block as a stopgap | +| MT.1049 | Its rule moved into the risk steps' rollout | +| CISA.MS.AAD.3.6 | Covers a different set of admin roles from CIS 5.2.2.5 and Learn, so the two would disagree in one run | +| EIDSCA.AF03–AF06, EIDSCA.AT02 | Hardening that Learn makes optional | +| MT.1025–MT.1028, MT.1030, CISA.MS.AAD.7.4 | Admin-account hygiene, not eligibility. CISA 7.4 also fails the permanent emergency access accounts that Learn asks for | +| CISA.MS.EXO.4.3 | Applies only to CISA's own reporting address | +| MT.1098, MT.1216, MT.1235 | See "Defender device risk" above | + +Some tagged tests check less than their step, and the step record says how many of its tests ran: + +- MT.1001 accepts any enabled policy that uses the compliant-device control. +- CISA 3.7 fails a stricter policy that requires compliance only. +- MT.1231 fails a tenant with no iOS compliance policy. +- CISA 7.5 fails emergency access assignments made outside PIM. + +Fixing these is test work, outside this design. + +The first catalogue has no `Conflicts` entry yet. The obvious one is security defaults. Learn says to turn them +off before relying on Conditional Access (security-defaults, plan-conditional-access). MT.1021 can't verify it, +because it checks that security defaults are on and skips any tenant with Entra ID P1 or better, which is every +tenant that uses Conditional Access. A measure or check of whether security defaults are off where Conditional Access is +licensed would make the conflict checkable. It is listed with the later measures in section 11. + +Candidates for later goals come from the research and from this pass: + +- legacy authentication, guest access, app consent and workload credentials; +- hybrid hardening, SSPR and LAPS; +- data protection, SharePoint sharing and audit; +- Defender for Office 365, Global Secure Access and AI agents; +- Copilot readiness, Insider Risk and Defender for Cloud Apps; +- third-party mail filters, Defender for Identity, Power Platform and Active Directory; +- privileged access hygiene (MT.1025–MT.1030, CIS 5.3.3), token protection on Apple devices, and third-party + Mobile Threat Defense. + +## 16. Delivery + +| Milestone | Work | Needs | +| --- | --- | --- | +| M1 Format | Schema and loader (`Get-MtStepCatalog`, internal), the `Step` attribute in C#, the schema table and the reader, `StepCatalog.Tests.ps1`, and the compliant-devices goal as the fixture | This design | +| M2 Catalogue | Expert pass on the seven goals against the mirrors, then `Step` on about 75 tests, plus `Step` in the Zero Trust `taxonomy.json` | M1, and the instance-attribute change on `feat/zta-taxonomy-mapping` | +| M3 Engine | `Step` on rows, reading the measures of the steps in scope, `Get-MtResultStep` (status, readiness, rank, scope), `LastKnown`, `-Step`, `-IncludePrerequisites`, `Get-MtTest -Step`, CSV and Markdown columns, the console line | M1 | +| M4 Report | Action plan groups and lanes, Before you fix this, rollout in How to fix, the overview card | M3's result shape. It can start on sample data once section 7 is final | +| M5 Measures | The measure registry, the two readers of section 11, and `Measure` on their steps | M1 for the format. The readers can be written before it | +| M6 Tooling | `build/steps/` scripts and the weekly workflow | M1 | +| M7 Docs and site | `Step` in `website/docs/writing-tests/index.mdx`, a defender's path page, and one page per goal on maester.dev built by `prepare-data.mjs` | M2 | + +Once M1 lands, M2, M5 and M6 touch different files and can run in parallel sessions. M3 and M4 follow in order. + +## 17. Decisions + +The owner accepted the recommended answer to each decision on 5 November 2026, and changed decision 10 later that day. +Three rulings on the measures followed: `devices-compliant` declares the Intune licence, because only Intune marks +devices compliant; a registry entry may carry a `Caveat`; and the MFA measure counts `isMfaCapable`. + +| # | Decision | Ruling | Alternatives considered | +| --- | --- | --- | --- | +| 1 | Name readers see | **Defender's path**, the counterpart of an attack path | "Implementation order", "Do this first" | +| 2 | Attribute name | **`Step`** | `Change` (clashes with the report's Changes page and with drift), `Prerequisite` (says the opposite of what most tests are) | +| 3 | What a lane is called | **Goal** (`Goals` in the result) | "Path", which clashes with `-Path` on `Invoke-Maester` and `Get-MtTest` and with file paths in the result | +| 4 | Where the catalogue lives | **`powershell/assets/steps/`**, beside the taxonomy, with no build change | A top-level `steps/` folder like `packs/`, which is easier to find but needs a build copy and a layout rule. Not under `tests/`, which holds only suites | +| 5 | Statuses | **Done, Not done, Unknown, Not checked, Not applicable** | Only Done and Not done, which turns every gap into a failure | +| 6 | Investigate | **Counts as Unknown** | Counts as Not done | +| 7 | Conflicts | **Block** while the conflicting step is on, declared on the step that needs the other off | Warn only | +| 8 | Selectors | **`-Step` and `-IncludePrerequisites`**, no goal selector, no new public command | A `Get-MtStep` command, which would add public API to keep | +| 9 | Packs and custom tests | **May name built-in steps.** Their own catalogues come later | Built-in tests only | +| 10 | Prerequisites that are tenant states | **Measures: figures read from Graph for the steps in scope, with `MinimumShare` (default 95) on the step and a run config override.** Changed from tests with a `MinimumShare` parameter | New tests, which would add findings with no real severity and change pass rates | +| 11 | Earlier statuses | **`LastKnown` per test, read only when a step in scope is Not checked** | The newest earlier run only, which says little after a one-check run | +| 12 | Catalogue wording | **Maester's own words and a link, 200 characters at most** | Quoting Learn | +| 13 | Mining output | **Proposals for review, and a weekly issue for changed sources** | A workflow that opens pull requests | +| 14 | Fact keys | **Ask the facts work for `Key` and a raw value before it ships** | Add them later. That breaks nothing, but costs more | +| 15 | Action plan | **The defender's path leads the page, with the ranked list below** | A separate page, which keeps today's plan unchanged but hides the strong point | + +## 18. Not in this design + +- The insights step (`Insight..ps1`), attack scenarios, the most exposed identities and the reader profile. + They are the rest of Phase 1 and get a design of their own. Steps are the same unit as the planned "fix once, + close many" groups, so that work reuses this catalogue. +- Custom step catalogues for users and packs. +- Measured user impact from sign-in logs and report-only results. It would add measures later. +- Goals for GitHub, Azure DevOps and Active Directory. Until they exist, those runs look as they do today. +- A model that decides pass, fail, severity or order. Order comes from the catalogue, and every relationship + cites its source. diff --git a/powershell/assets/MaesterMeasures.psd1 b/powershell/assets/MaesterMeasures.psd1 new file mode 100644 index 0000000000..14751174a2 --- /dev/null +++ b/powershell/assets/MaesterMeasures.psd1 @@ -0,0 +1,49 @@ +# The measure registry of the defender's path (docs/proposals/defenders-path.md, section 11). +# +# A measure is a figure the engine reads from Graph for a step that is a state of the tenant, such as the share of +# devices that sign in and are compliant. A step names a measure in the step catalogue +# (powershell/assets/steps/.json) as "Measure": { "Key": "", "MinimumShare": <1 to 100> }, and the step +# is done when the figure meets its threshold. A measure is not a test: it has no ID, no result row and no place in +# pass rates. +# +# Keys of each entry: +# Key lowercase kebab-case, the name a step's Measure uses +# Function the internal reader in powershell/internal/services//. It reads through the Graph cache and +# returns Count (objects that meet the bar), Total and Objects (those that fall short, as Type, Id and +# DisplayName) +# Title one line, shown with the figure, for example 'Devices that sign in are compliant' +# Unit what is counted, plural, for example 'devices' +# Caveat one line of 200 characters or less, shown with the figure, on what it can't see or leaves out +# (optional) +# Service services that must all be connected, as in a test's Service attribute +# License service plans, any one of which is enough, as in a test's License attribute (optional) +# Permission permissions the reader needs, as in a test's Permission attribute (optional) +@{ + Measures = @( + @{ + # Step intune.devices-compliant. isCompliant is set by Intune, also for the devices of a compliance partner, + # which needs Intune licences as well, so a tenant without Intune has no figure to read. + Key = 'devices-compliant' + Function = 'Get-MtDeviceComplianceShare' + Title = 'Devices that sign in are compliant' + Unit = 'devices' + Caveat = "Devices that aren't registered or joined in Microsoft Entra ID can't be counted. A compliant-device policy blocks them too." + Service = 'Graph' + License = 'INTUNE_A' + Permission = 'Graph:Scope:Device.Read.All | Graph:Scope:Directory.Read.All' + } + @{ + # Step entra.mfa-registered. isMfaCapable, not isMfaRegistered: the method must also be one the + # authentication methods policy allows, or the user still can't complete MFA. The registration report needs + # Microsoft Entra ID P1 and AuditLog.Read.All. + Key = 'mfa-capable' + Function = 'Get-MtMfaCapableShare' + Title = 'Enabled member users can complete MFA' + Unit = 'users' + Caveat = 'Counts only methods the authentication methods policy allows. Guests, disabled users, emergency access and directory sync accounts are left out.' + Service = 'Graph' + License = 'AAD_PREMIUM' + Permission = ('Graph:Scope:AuditLog.Read.All', 'Graph:Scope:Directory.Read.All') + } + ) +} diff --git a/powershell/assets/MaesterTestSchema.psd1 b/powershell/assets/MaesterTestSchema.psd1 index 27f70fe52a..c63163b138 100644 --- a/powershell/assets/MaesterTestSchema.psd1 +++ b/powershell/assets/MaesterTestSchema.psd1 @@ -132,6 +132,13 @@ Pattern = '^[a-z0-9][a-z0-9.\-]*:[^\s,]+$' Description = 'Requirements of frameworks the test supports, written :, beside the benchmark it is named after.' } + Step = @{ + Type = 'string[]' + Required = 'No' + Pattern = '^[a-z0-9][a-z0-9\-]*\.[a-z0-9][a-z0-9\-]*$' + MaxLength = 80 + Description = 'Steps of the defender''s path the test verifies, written ., for example entra.ca-require-compliant-device. A test shipped with Maester names steps of the step catalogue.' + } Service = @{ Type = 'string[]' Required = 'BuiltIn' diff --git a/powershell/assets/ReportTemplate.html b/powershell/assets/ReportTemplate.html index 7aa2fcea39..56d43ebcb2 100644 --- a/powershell/assets/ReportTemplate.html +++ b/powershell/assets/ReportTemplate.html @@ -6,56 +6,62 @@ Maester - + `,document.head.appendChild(e),()=>{let e=document.getElementById(`print-styles`);e&&e.remove()}},[]),z(`div`,{children:[z(`div`,{className:`no-print mb-6 flex items-center justify-end`,children:z(_p,{variant:`primary`,onClick:()=>{n(!0),setTimeout(()=>{window.print(),n(!1)},100)},disabled:t,children:[z(Cu,{className:`mr-2 h-4 w-4`}),t?`Preparing...`:`Print Report`]})}),z(`div`,{className:`print-content`,children:[z(`div`,{className:`mb-6`,children:[z(`div`,{className:`mb-4 flex items-center gap-3`,children:[z(`img`,{src:Gp,alt:`Maester Logo`,className:`h-10 w-10`}),z(`h1`,{className:`text-2xl font-semibold tracking-tight text-gray-900 dark:text-gray-100`,children:`Maester Test Results`})]}),z(`p`,{className:`mt-1 text-sm text-gray-500 dark:text-gray-400`,children:[r,` • `,i]})]}),z(`div`,{className:`mb-8 grid grid-cols-4 gap-4`,children:[z(`div`,{className:`rounded-md border border-gray-200 bg-white p-4 dark:border-gray-700 dark:bg-gray-800`,children:[z(`div`,{className:`text-2xl font-semibold text-gray-900 dark:text-white`,children:e.TotalCount}),z(`div`,{className:`text-sm text-gray-500 dark:text-gray-400`,children:`Total Tests`})]}),z(`div`,{className:`rounded-md border border-emerald-200 bg-emerald-50 p-4 dark:border-emerald-800 dark:bg-emerald-950`,children:[z(`div`,{className:`text-2xl font-semibold text-emerald-700 dark:text-emerald-400`,children:e.PassedCount}),z(`div`,{className:`text-sm text-emerald-600 dark:text-emerald-500`,children:`Passed`})]}),z(`div`,{className:`rounded-md border border-red-200 bg-red-50 p-4 dark:border-red-800 dark:bg-red-950`,children:[z(`div`,{className:`text-2xl font-semibold text-red-700 dark:text-red-400`,children:e.FailedCount}),z(`div`,{className:`text-sm text-red-600 dark:text-red-500`,children:`Failed`})]}),z(`div`,{className:`rounded-md border border-purple-200 bg-purple-50 p-4 dark:border-purple-800 dark:bg-purple-950`,children:[z(`div`,{className:`text-2xl font-semibold text-purple-700 dark:text-purple-400`,children:e.InvestigateCount||0}),z(`div`,{className:`text-sm text-purple-600 dark:text-purple-500`,children:`Investigate`})]}),z(`div`,{className:`rounded-md border border-amber-200 bg-amber-50 p-4 dark:border-amber-800 dark:bg-amber-950`,children:[z(`div`,{className:`text-2xl font-semibold text-amber-700 dark:text-amber-400`,children:e.SkippedCount}),z(`div`,{className:`text-sm text-amber-600 dark:text-amber-500`,children:`Skipped`})]})]}),z(`div`,{className:`mb-8`,children:[z(`h2`,{className:`mb-4 text-xl font-semibold text-gray-900 dark:text-white`,children:`Summary`}),z(`div`,{className:`overflow-x-auto rounded-md border border-gray-200 dark:border-gray-700`,children:z(`table`,{className:`min-w-full border-collapse text-left text-sm dark:text-gray-300`,children:[z(`thead`,{className:`bg-gray-50 text-gray-700 dark:bg-gray-800 dark:text-gray-300`,children:z(`tr`,{children:[z(`th`,{className:`border-b border-gray-200 p-2 dark:border-gray-700`,children:`ID`}),z(`th`,{className:`border-b border-gray-200 p-2 dark:border-gray-700`,children:`Title`}),z(`th`,{className:`border-b border-gray-200 p-2 text-center dark:border-gray-700`,children:`Severity`}),z(`th`,{className:`border-b border-gray-200 p-2 text-center dark:border-gray-700`,children:`Status`})]})}),z(`tbody`,{children:e.Tests.map((e,t)=>z(`tr`,{className:`border-b border-gray-200 bg-white hover:bg-gray-50 dark:border-gray-700 dark:bg-gray-900 dark:hover:bg-gray-800`,children:[z(`td`,{className:`p-2 font-mono text-xs text-gray-900 dark:text-gray-300`,children:e.Id}),z(`td`,{className:`p-2 dark:text-gray-300`,children:z(`button`,{onClick:()=>{let t=document.getElementById(`detail-${e.Id}`);t&&t.scrollIntoView({behavior:`smooth`})},className:`text-left text-blue-600 hover:text-blue-800 hover:underline dark:text-blue-400 dark:hover:text-blue-300`,children:e.Title||e.Name})}),z(`td`,{className:`p-2 text-center`,children:z(Vp,{Severity:e.Severity})}),z(`td`,{className:`p-2 text-center`,children:z(Bp,{Result:e.Result})})]},t))})]})})]}),z(`div`,{children:[z(`h2`,{className:`mb-4 text-xl font-semibold text-gray-900 dark:text-white`,children:`Test Details`}),z(`div`,{className:`space-y-6`,children:e.Tests.map((e,t)=>z(`div`,{id:`detail-${e.Id}`,className:`detail-section rounded-md border border-gray-200 p-4 dark:border-gray-700`,children:z(Wp,{Item:e,isPrintView:!0})},t))})]})]})]})}function qp(){let{selectedTenant:e}=an(),{pathname:t}=Zt(),n=fn(e,t),r=Ne(null),[i,a]=F();return I(()=>{a(void 0),n&&r.current&&bn(n,r.current).catch(e=>a(e instanceof Error?e.message:String(e)))},[n?.Id]),n?z(`div`,{className:`flex h-full flex-col`,children:[z(`div`,{className:`flex items-center justify-between gap-4 border-b border-gray-200 bg-white px-6 py-2 dark:border-gray-800 dark:bg-black`,children:[z(`p`,{className:`truncate text-sm text-gray-500 dark:text-gray-400`,children:n.FileName?`${n.Name} · ${n.FileName}`:n.Name}),z(Mf,{variant:`light`,icon:Zl,onClick:()=>xn(n),children:`Open in new tab`})]}),i?z(`p`,{className:`p-6 text-sm text-red-600 dark:text-red-400`,children:[n.Name,` could not be shown: `,i]}):z(`iframe`,{ref:r,title:n.Name,sandbox:gn,className:`w-full flex-1 border-0 bg-white`},n.Id)]}):z(`div`,{className:`p-6 text-sm text-gray-500 dark:text-gray-400`,children:[`This report is not embedded in this file`,e?.TenantName?` for ${e.TenantName}`:``,`.`]})}function Jp(e){try{return decodeURIComponent(e)}catch{return e}}function Yp({pathname:e}){let[,t=``,n=``]=e.split(`/`);switch(t){case`tenants`:return z(vl,{});case`plan`:return z(rl,{});case`tests`:return z(al,{});case`product`:return z(sl,{productKey:Jp(n)});case`framework`:return z(dl,{frameworkKey:Jp(n)});case`attack`:return z(fl,{});case`pack`:return z(pl,{packId:Jp(n)});case`changes`:return z(ml,{});case`run`:case`settings`:return z(hl,{});case`system`:return z(`div`,{className:`mt-wrap`,children:z(sp,{})});case`config`:return z(`div`,{className:`mt-wrap`,children:z(mp,{})});case`affected-objects`:return z(`div`,{className:`mt-wrap`,children:z(ip,{})});case`view`:return z(`div`,{className:`mt-wrap`,children:z(n===`excel`?Lp:n===`markdown`?zp:Kp,{})});default:return z(el,{})}}function Xp({testResults:e}){let{pathname:t}=Zt(),n=t.startsWith(`/reports/`);return z(nn,{children:z(sn,{testResults:e,children:z(yr,{children:z(Cc,{flush:n,children:n?z(qp,{}):z(Yp,{pathname:t})})})})})}var Zp=`maester-report-data`;async function Qp(){let e=document.getElementById(Zp)?.textContent?.trim();if(!e)throw Error(`Report data was not embedded in the generated HTML file`);let t=e.replace(/^(?:const|let|var)\s+\w+\s*=\s*/,``);return JSON.parse(t)}var $p=document.getElementById(`root`);Qp().then(e=>{Wt.createRoot($p).render(z(Vt.StrictMode,{children:z(Yt,{children:z(Xp,{testResults:e})})}))},e=>{console.error(e),$p.textContent=`The report data could not be loaded. Try generating the report again.`}); diff --git a/powershell/assets/ReportTemplate.md b/powershell/assets/ReportTemplate.md index 19d4506772..7825b45018 100644 --- a/powershell/assets/ReportTemplate.md +++ b/powershell/assets/ReportTemplate.md @@ -11,7 +11,7 @@ This is a summary of the test results from the Maester test run. | **%TotalCount%** | **%PassedCount%** | **%FailedCount%** | **%InvestigateCount%** | **%SkippedCount%** |**%NotRunCount%** | -## Test summary +%DefendersPath%## Test summary %TestSummary% diff --git a/powershell/assets/steps/defender.json b/powershell/assets/steps/defender.json new file mode 100644 index 0000000000..b6b98a79a1 --- /dev/null +++ b/powershell/assets/steps/defender.json @@ -0,0 +1,169 @@ +{ + "$schema": "./steps.schema.json", + "Product": "defender", + "Steps": [ + { + "Id": "defender.endpoint-onboarding", + "Title": "Eligible devices are onboarded to Defender for Endpoint", + "Summary": "Every device that Defender for Endpoint can protect reports to it through a working sensor, so the device has a risk level.", + "RecommendedFirst": ["intune.defender-connector"], + "Rollout": [ + "Assign an Intune EDR onboarding policy to a test device group, and check that the devices appear in the Defender portal's device inventory.", + "Then assign it to all Windows devices.", + "Deploy the Defender app to macOS, Android and iOS/iPadOS devices, which have no automatic onboarding package." + ], + "Unchecked": "No Maester check yet. The Zero Trust Assessment pack checks it (ZTA.41045) once its results can name steps.", + "Sources": [ + { + "Url": "https://learn.microsoft.com/defender-endpoint/onboarding-endpoint-manager", + "Mirror": "defender-docs-mirror", + "Note": "Onboarding Windows devices through Intune lists the Intune connection as a prerequisite.", + "Reviewed": "2026-11-05" + }, + { + "Url": "https://learn.microsoft.com/intune/device-security/microsoft-defender/configure-integration", + "Mirror": "intune-docs-mirror", + "Note": "With the connection, Intune gets Defender's onboarding package for its EDR policy. Without it, you paste an onboarding package into the policy yourself.", + "Reviewed": "2026-11-05" + } + ] + }, + { + "Id": "defender.spf", + "Title": "Publish an SPF record for every domain that sends mail", + "Summary": "Receiving servers can check that mail from your domains comes from Microsoft 365 or another sender you list.", + "Rollout": [ + "List every system that sends as the domain: Microsoft 365, on-premises servers and third-party services.", + "Publish one SPF TXT record per sending domain and subdomain, and keep it under ten DNS lookups.", + "Give domains that never send mail the record v=spf1 -all." + ], + "Sources": [ + { + "Url": "https://learn.microsoft.com/defender-office-365/email-authentication-spf-configure", + "Mirror": "defender-docs-mirror", + "Note": "Each custom domain and sending subdomain needs one SPF TXT record naming Microsoft 365 and any other senders. onmicrosoft.com is covered already.", + "Reviewed": "2026-11-05" + } + ] + }, + { + "Id": "defender.spf-hard-fail", + "Title": "End every SPF record with -all", + "Summary": "Receivers are told to reject mail from servers that the SPF record doesn't list, so DMARC can act on spoofed mail with no signature.", + "RecommendedFirst": ["defender.spf", "defender.dmarc-published"], + "Rollout": [ + "Keep ~all until the DMARC aggregate reports show no legitimate source failing SPF.", + "Change the qualifier to -all one domain at a time, keeping one SPF record per domain." + ], + "Sources": [ + { + "Url": "https://learn.microsoft.com/defender-office-365/email-authentication-about", + "Mirror": "defender-docs-mirror", + "Note": "Start with the senders you know and ~all, add the others as you find them, then move to -all, so mail from a sender you missed isn't bounced.", + "Reviewed": "2026-11-05" + }, + { + "Url": "https://learn.microsoft.com/defender-office-365/email-authentication-spf-configure", + "Mirror": "defender-docs-mirror", + "Note": "DMARC reports show which servers send as the domain, so publish a DMARC record early and read its reports before -all rejects a source nobody listed.", + "Reviewed": "2026-11-05" + } + ] + }, + { + "Id": "defender.dkim", + "Title": "Sign outbound mail with DKIM for every custom domain", + "Summary": "Mail from your custom domains carries a DKIM signature that matches the From domain and survives forwarding.", + "Rollout": [ + "Read the two CNAME values for the domain from the Defender portal or Get-DkimSigningConfig.", + "Create both selector CNAME records at the DNS host and wait until Microsoft 365 detects them.", + "Turn on DKIM signing for the domain and confirm that its status shows it is signing." + ], + "Sources": [ + { + "Url": "https://learn.microsoft.com/defender-office-365/email-authentication-dkim-configure", + "Mirror": "defender-docs-mirror", + "Note": "Custom domains aren't signed until both selector CNAME records exist and signing is on. onmicrosoft.com is signed already, and parked domains need no DKIM.", + "Reviewed": "2026-11-05" + } + ] + }, + { + "Id": "defender.dmarc-published", + "Title": "Publish a DMARC record for every domain", + "Summary": "Every domain, onmicrosoft.com included, has a DMARC record, so receivers check alignment and report who sends mail as you.", + "RecommendedFirst": ["defender.spf", "defender.dkim"], + "Rollout": [ + "Publish v=DMARC1; p=none with a rua address that a dedicated mailbox or a reporting service reads.", + "Add the record for the onmicrosoft.com domain in the Microsoft 365 admin center.", + "Read the aggregate reports regularly to find senders that fail SPF or DKIM." + ], + "Sources": [ + { + "Url": "https://learn.microsoft.com/defender-office-365/email-authentication-dmarc-configure", + "Mirror": "defender-docs-mirror", + "Note": "Set up SPF and DKIM before DMARC, which passes only on aligned SPF or DKIM. A p=none record changes no delivery and starts the reports.", + "Reviewed": "2026-11-05" + }, + { + "Url": "https://learn.microsoft.com/defender-office-365/email-authentication-dmarc-configure", + "Mirror": "defender-docs-mirror", + "Note": "The onmicrosoft.com domain needs a DMARC record of its own, added in the Microsoft 365 admin center.", + "Reviewed": "2026-11-05" + } + ] + }, + { + "Id": "defender.dmarc-enforce", + "Title": "Enforce DMARC with reporting on every domain", + "Summary": "Receivers quarantine or reject mail that fails DMARC for any of your domains, and send you aggregate and failure reports.", + "Requires": ["defender.spf", "defender.dkim"], + "RecommendedFirst": ["defender.dmarc-published", "defender.spf-hard-fail"], + "Rollout": [ + "Start with a low-volume domain or subdomain, and leave the parent domain for last.", + "Move from p=none to p=quarantine, and raise pct in steps from 10 to 100 while you watch the reports.", + "Keep the rua and ruf addresses in the record so that failures go on being reported." + ], + "Sources": [ + { + "Url": "https://learn.microsoft.com/defender-office-365/email-authentication-dmarc-configure", + "Mirror": "defender-docs-mirror", + "Note": "An enforcing policy acts on mail that fails both aligned SPF and DKIM. Set both up on every sending domain first, and run p=none with reports before you enforce.", + "Reviewed": "2026-11-05" + }, + { + "Url": "https://learn.microsoft.com/defender-office-365/mdo-deployment-guide", + "Mirror": "defender-docs-mirror", + "Note": "The deployment guide sets up SPF, DKIM and DMARC in that order, and expects quarantine or reject with report addresses on each custom domain.", + "Reviewed": "2026-11-05" + }, + { + "Url": "https://learn.microsoft.com/defender-office-365/email-authentication-spf-configure", + "Mirror": "defender-docs-mirror", + "Note": "With ~all, DMARC in effect ignores SPF failures on mail that has no DKIM signature. Ending SPF in -all lets the policy act on that mail.", + "Reviewed": "2026-11-05" + } + ] + }, + { + "Id": "defender.dmarc-reject", + "Title": "Reject mail that fails DMARC on every domain", + "Summary": "Receivers reject mail that claims to come from your domains but fails DMARC, parked domains and onmicrosoft.com included.", + "Requires": ["defender.spf", "defender.dkim"], + "RecommendedFirst": ["defender.dmarc-enforce"], + "Rollout": [ + "After a period at p=quarantine, move each domain to p=reject, raising pct in steps if needed.", + "Do the subdomains in order of volume, then the parent domain.", + "Set parked domains and an unused onmicrosoft.com domain to p=reject straight away." + ], + "Sources": [ + { + "Url": "https://learn.microsoft.com/defender-office-365/email-authentication-dmarc-configure", + "Mirror": "defender-docs-mirror", + "Note": "The target is p=reject on every domain, reached after a period at quarantine. Parked domains and an onmicrosoft.com domain that sends nothing can go straight there.", + "Reviewed": "2026-11-05" + } + ] + } + ] +} diff --git a/powershell/assets/steps/entra.json b/powershell/assets/steps/entra.json new file mode 100644 index 0000000000..b45de7b96b --- /dev/null +++ b/powershell/assets/steps/entra.json @@ -0,0 +1,602 @@ +{ + "$schema": "./steps.schema.json", + "Product": "entra", + "Steps": [ + { + "Id": "entra.emergency-access-accounts", + "Title": "Keep at least two emergency access accounts with permanent Global Administrator", + "Summary": "Cloud-only break-glass accounts can always sign in and administer the tenant, even when every other admin role is eligible.", + "Unchecked": "No Maester check yet. The Zero Trust Assessment pack checks it (ZTA.21835) once its results can name steps.", + "Sources": [ + { + "Url": "https://learn.microsoft.com/entra/identity/role-based-access-control/security-emergency-access", + "Mirror": "entra-docs-mirror", + "Note": "Create two or more cloud-only accounts on the onmicrosoft.com domain, and in PIM give them Global Administrator as a permanent active assignment, not an eligible one.", + "Reviewed": "2026-11-05" + }, + { + "Url": "https://learn.microsoft.com/entra/id-governance/privileged-identity-management/pim-deployment-plan", + "Mirror": "entra-docs-mirror", + "Note": "The plan leaves no permanent active privileged assignments except the emergency access accounts, which keep Global Administrator.", + "Reviewed": "2026-11-05" + } + ] + }, + { + "Id": "entra.emergency-access-excluded", + "Title": "Exclude emergency access accounts from Conditional Access", + "Summary": "Emergency access accounts can still sign in when a Conditional Access policy goes wrong.", + "RecommendedFirst": ["entra.emergency-access-accounts"], + "Sources": [ + { + "Url": "https://learn.microsoft.com/entra/identity/role-based-access-control/security-emergency-access", + "Mirror": "entra-docs-mirror", + "Note": "Create the accounts, then exclude them, best through one group, from every enforced policy that can block or limit sign-in. Report-only policies need no exclusion.", + "Reviewed": "2026-11-05" + } + ] + }, + { + "Id": "entra.ca-exclude-sync-accounts", + "Title": "Exclude directory sync accounts from Conditional Access", + "Summary": "The accounts that Microsoft Entra Connect and Cloud Sync use keep syncing when new policies apply.", + "OnlyWhen": ["hybrid-identity"], + "Sources": [ + { + "Url": "https://learn.microsoft.com/entra/identity/conditional-access/policy-all-users-device-compliance", + "Mirror": "entra-docs-mirror", + "Note": "With Microsoft Entra Connect or Cloud Sync, exclude the Directory Synchronization Accounts role from policies that target all users.", + "Reviewed": "2026-11-05" + } + ] + }, + { + "Id": "entra.ca-require-compliant-device", + "Title": "Require a compliant device in Conditional Access", + "Summary": "Sign-ins from devices that Intune does not mark compliant are blocked.", + "Requires": [ + "intune.compliance-policies", + "intune.devices-compliant", + "entra.emergency-access-excluded", + "entra.ca-exclude-sync-accounts" + ], + "RecommendedFirst": ["intune.mark-unassigned-noncompliant"], + "Rollout": [ + "Create the policy in report-only mode and review the sign-ins it would block.", + "Turn it on for a pilot group.", + "Turn it on for all users, keeping the emergency access accounts excluded." + ], + "Sources": [ + { + "Url": "https://learn.microsoft.com/entra/identity/conditional-access/policy-all-users-device-compliance", + "Mirror": "entra-docs-mirror", + "Note": "The policy doesn't work as intended without an Intune compliance policy. Create one first, have at least one compliant device, and start in report-only.", + "Reviewed": "2026-11-05" + }, + { + "Url": "https://learn.microsoft.com/entra/identity/conditional-access/concept-conditional-access-grant", + "Mirror": "entra-docs-mirror", + "Note": "A device can be marked compliant only once it is registered in Microsoft Entra ID and enrolled in Intune or a supported partner.", + "Reviewed": "2026-11-05" + }, + { + "Url": "https://learn.microsoft.com/intune/device-security/conditional-access-integration/device-based-policies", + "Mirror": "intune-docs-mirror", + "Note": "Intune's guide sets up compliance policies before device-based Conditional Access, and tests the new policy with a small group first.", + "Reviewed": "2026-11-05" + } + ] + }, + { + "Id": "entra.hybrid-join", + "Title": "Domain-joined Windows PCs are hybrid joined to Microsoft Entra ID", + "Summary": "Windows PCs joined to on-premises Active Directory also have a Microsoft Entra device identity that Conditional Access can use.", + "OnlyWhen": ["hybrid-identity"], + "Rollout": [ + "Turn on hybrid join for a pilot group of varied devices first.", + "Then turn it on for every computer that should be hybrid joined." + ], + "Unchecked": "No check yet. Graph lists the devices that are hybrid joined, but not the domain-joined PCs that are not.", + "Sources": [ + { + "Url": "https://learn.microsoft.com/entra/identity/devices/how-to-hybrid-join", + "Mirror": "entra-docs-mirror", + "Note": "Hybrid join needs Microsoft Entra Connect syncing the computer objects with their device attributes, and the device setting that lets users register devices.", + "Reviewed": "2026-11-05" + }, + { + "Url": "https://learn.microsoft.com/entra/identity/devices/hybrid-join-plan", + "Mirror": "entra-docs-mirror", + "Note": "Roll hybrid join out to a pilot group with targeted deployment before the whole organization.", + "Reviewed": "2026-11-05" + } + ] + }, + { + "Id": "entra.ca-require-managed-device-admins", + "Title": "Require a compliant or hybrid joined device for administrators", + "Summary": "Accounts in admin roles can sign in only from a device that Intune marks compliant or that is hybrid joined.", + "Requires": ["entra.emergency-access-excluded"], + "RequiresOneOf": [["intune.compliance-policies", "entra.hybrid-join"]], + "Rollout": [ + "Create the policy for the admin roles in report-only mode and review the sign-ins it would block.", + "Turn it on, keeping the emergency access accounts excluded." + ], + "Sources": [ + { + "Url": "https://learn.microsoft.com/entra/identity/conditional-access/policy-alt-admin-device-compliand-hybrid", + "Mirror": "entra-docs-mirror", + "Note": "The hybrid joined option works only for devices that are already hybrid joined, and compliance needs Intune policies. Exclude emergency access accounts; start in report-only.", + "Reviewed": "2026-11-05" + } + ] + }, + { + "Id": "entra.ca-require-managed-device", + "Title": "Require a compliant or hybrid joined device in Conditional Access", + "Summary": "Sign-ins from devices that are neither compliant in Intune nor hybrid joined are blocked.", + "Requires": ["entra.emergency-access-excluded", "entra.ca-exclude-sync-accounts"], + "RequiresOneOf": [["intune.devices-compliant", "entra.hybrid-join"]], + "RecommendedFirst": ["intune.mark-unassigned-noncompliant", "entra.ca-require-managed-device-admins"], + "Rollout": [ + "Create the policy in report-only mode and review the sign-ins it would block.", + "Turn it on for a pilot group.", + "Turn it on for all users, keeping the emergency access and directory sync accounts excluded." + ], + "Sources": [ + { + "Url": "https://learn.microsoft.com/entra/identity/conditional-access/concept-conditional-access-grant", + "Mirror": "entra-docs-mirror", + "Note": "Either signal will do. Compliance needs devices registered and enrolled in Intune; the hybrid option covers only domain-joined Windows PCs that are hybrid joined.", + "Reviewed": "2026-11-05" + }, + { + "Url": "https://learn.microsoft.com/entra/identity/conditional-access/policy-alt-all-users-compliant-hybrid-or-mfa", + "Mirror": "entra-docs-mirror", + "Note": "The all-users template excludes the emergency access accounts and, with Connect or Cloud Sync, the directory sync accounts, and starts in report-only.", + "Reviewed": "2026-11-05" + }, + { + "Url": "https://learn.microsoft.com/entra/identity/conditional-access/policy-all-users-device-compliance", + "Mirror": "entra-docs-mirror", + "Note": "Organizations not ready to require managed devices for everyone can start with the policy for administrators.", + "Reviewed": "2026-11-05" + } + ] + }, + { + "Id": "entra.windows-devices-registered", + "Title": "Windows devices that sign in are registered with Microsoft Entra ID", + "Summary": "Windows PCs used for Microsoft 365 have a device identity, so their sign-in tokens can be bound to the device.", + "Unchecked": "Needs sign-in logs. Graph lists registered devices but not the Windows PCs that sign in without one.", + "Sources": [ + { + "Url": "https://learn.microsoft.com/entra/identity/conditional-access/concept-token-protection", + "Mirror": "entra-docs-mirror", + "Note": "Token protection binds tokens to Windows devices that are joined, hybrid joined or registered. Sign-ins from other devices show up as unbound requests.", + "Reviewed": "2026-11-05" + } + ] + }, + { + "Id": "entra.ca-block-unknown-platforms", + "Title": "Block access from unknown or unsupported device platforms", + "Summary": "Sign-ins from device platforms that Conditional Access doesn't recognize are blocked, so platform-based policies can't be sidestepped.", + "Requires": ["entra.emergency-access-excluded"], + "Rollout": [ + "Create the policy in report-only mode and review the sign-ins it would block.", + "Turn it on, keeping the emergency access accounts excluded." + ], + "Sources": [ + { + "Url": "https://learn.microsoft.com/entra/identity/conditional-access/policy-all-users-device-unknown-unsupported", + "Mirror": "entra-docs-mirror", + "Note": "Platform conditions read the user agent, so use this block alongside other policies. Exclude the emergency access accounts.", + "Reviewed": "2026-11-05" + } + ] + }, + { + "Id": "entra.ca-token-protection-windows", + "Title": "Require token protection for sign-in sessions on Windows", + "Summary": "Exchange, SharePoint and Teams accept only device-bound sign-in tokens from Windows desktop apps, so a stolen token can't be replayed elsewhere.", + "Requires": ["entra.emergency-access-excluded"], + "RecommendedFirst": ["entra.windows-devices-registered", "entra.ca-block-unknown-platforms"], + "Rollout": [ + "Create the policy in report-only mode for a pilot group, desktop apps only, for Exchange, SharePoint and Teams.", + "Review interactive and non-interactive sign-ins for unbound requests over a full working cycle.", + "Exclude unsupported device types with a device filter, then turn the policy on for users who are ready and widen it." + ], + "Sources": [ + { + "Url": "https://learn.microsoft.com/entra/identity/conditional-access/deployment-guide-token-protection-windows", + "Mirror": "entra-docs-mirror", + "Note": "Current Windows builds prompt users on unregistered devices to register. Pilot in report-only and look for unbound sign-ins before you enforce. Exclude emergency access accounts.", + "Reviewed": "2026-11-05" + }, + { + "Url": "https://learn.microsoft.com/entra/identity/conditional-access/deployment-guide-token-protection-windows", + "Mirror": "entra-docs-mirror", + "Note": "Pair the policy with one that blocks unknown platforms, so a client can't avoid it by reporting a different platform.", + "Reviewed": "2026-11-05" + }, + { + "Url": "https://learn.microsoft.com/entra/identity/conditional-access/concept-token-protection", + "Mirror": "entra-docs-mirror", + "Note": "Windows and Apple devices have separate deployment guides, each with its own prerequisites. This step covers Windows.", + "Reviewed": "2026-11-05" + } + ] + }, + { + "Id": "entra.mfa-registered", + "Title": "Enabled member users are registered for MFA", + "Summary": "Users already have an MFA method that policy allows, so policies that ask for MFA or self-remediation don't leave them stuck.", + "Measure": { "Key": "mfa-capable", "MinimumShare": 95 }, + "Sources": [ + { + "Url": "https://learn.microsoft.com/entra/id-protection/howto-identity-protection-configure-risk-policies", + "Mirror": "entra-docs-mirror", + "Note": "Users need to register for MFA before a risk policy asks them to remediate. Those who haven't stay blocked until an admin steps in.", + "Reviewed": "2026-11-05" + } + ] + }, + { + "Id": "entra.password-hash-sync", + "Title": "Turn on password hash synchronization", + "Summary": "Microsoft Entra ID holds hashes of synced users' passwords, so leaked credentials can be matched to those users.", + "OnlyWhen": ["hybrid-identity"], + "Sources": [ + { + "Url": "https://learn.microsoft.com/entra/id-protection/id-protection-faq", + "Mirror": "entra-docs-mirror", + "Note": "Leaked-credential detection needs password hash sync for synced users, and only leaks found after it is on are matched, so turn it on early.", + "Reviewed": "2026-11-05" + } + ] + }, + { + "Id": "entra.password-writeback", + "Title": "Turn on password writeback", + "Summary": "Password changes made in Microsoft Entra ID, including risk remediation, are written back to on-premises Active Directory.", + "OnlyWhen": ["hybrid-identity"], + "Unchecked": "Microsoft Graph doesn't report whether password writeback is on.", + "Sources": [ + { + "Url": "https://learn.microsoft.com/entra/id-protection/howto-identity-protection-configure-risk-policies", + "Mirror": "entra-docs-mirror", + "Note": "Synced users can clear user risk with a secure password change only when password writeback is turned on.", + "Reviewed": "2026-11-05" + } + ] + }, + { + "Id": "entra.remediate-risky-users", + "Title": "Remediate the users that ID Protection already rates high risk", + "Summary": "Existing high-risk users are investigated, then remediated or dismissed, before risk policies start acting on them.", + "Sources": [ + { + "Url": "https://learn.microsoft.com/entra/id-protection/howto-identity-protection-configure-risk-policies", + "Mirror": "entra-docs-mirror", + "Note": "Investigate and clear the active risks before you turn the risk policies on.", + "Reviewed": "2026-11-05" + }, + { + "Url": "https://learn.microsoft.com/entra/id-protection/how-to-deploy-identity-protection", + "Mirror": "entra-docs-mirror", + "Note": "Learn's deployment plan starts by reviewing the users and sign-ins already in the ID Protection reports.", + "Reviewed": "2026-11-05" + } + ] + }, + { + "Id": "entra.trusted-named-locations", + "Title": "Mark known networks as trusted named locations", + "Summary": "ID Protection treats sign-ins from the organization's own networks as less risky, which cuts false positives.", + "Sources": [ + { + "Url": "https://learn.microsoft.com/entra/id-protection/howto-identity-protection-configure-risk-policies", + "Mirror": "entra-docs-mirror", + "Note": "Some risk detections use trusted locations to cut false positives, so mark office and VPN ranges as trusted before sign-in risk prompts start.", + "Reviewed": "2026-11-05" + } + ] + }, + { + "Id": "entra.ca-sign-in-risk", + "Title": "Require MFA for medium and high sign-in risk in Conditional Access", + "Summary": "Sign-ins that ID Protection rates medium or high risk need a fresh MFA, which also clears the sign-in risk.", + "Requires": ["entra.mfa-registered", "entra.emergency-access-excluded"], + "RecommendedFirst": ["entra.ca-exclude-sync-accounts", "entra.trusted-named-locations"], + "Rollout": [ + "Create the policy in report-only mode and review the sign-ins it would affect.", + "Turn it on for a pilot group.", + "Turn it on for all users, keeping the emergency access accounts excluded.", + "Keep it as its own policy, with no user risk condition." + ], + "Sources": [ + { + "Url": "https://learn.microsoft.com/entra/identity/conditional-access/policy-risk-based-sign-in", + "Mirror": "entra-docs-mirror", + "Note": "A user can't register MFA during a risky sign-in, so an unregistered user is blocked instead of prompted. Exclude emergency access accounts and service accounts.", + "Reviewed": "2026-11-05" + }, + { + "Url": "https://learn.microsoft.com/entra/id-protection/howto-identity-protection-configure-risk-policies", + "Mirror": "entra-docs-mirror", + "Note": "Keep sign-in risk and user risk in separate policies. For medium and high sign-in risk, ask for MFA and reauthentication every time.", + "Reviewed": "2026-11-05" + }, + { + "Url": "https://learn.microsoft.com/entra/id-protection/how-to-deploy-identity-protection", + "Mirror": "entra-docs-mirror", + "Note": "Start sign-in risk policies with a subset of users before the whole organization.", + "Reviewed": "2026-11-05" + } + ] + }, + { + "Id": "entra.ca-user-risk", + "Title": "Require risk remediation for high user risk in Conditional Access", + "Summary": "Users that ID Protection rates high risk must remediate, with a secure password change or a fresh sign-in, before they get access.", + "Requires": ["entra.mfa-registered", "entra.password-writeback", "entra.emergency-access-excluded"], + "RecommendedFirst": [ + "entra.remediate-risky-users", + "entra.password-hash-sync", + "entra.ca-exclude-sync-accounts", + "entra.ca-sign-in-risk" + ], + "Rollout": [ + "Create the policy in report-only mode and review its impact, including the risk-based policy impact workbook.", + "Turn it on for a pilot group.", + "Turn it on for all users, keeping the emergency access accounts excluded.", + "Keep it as its own policy, with no sign-in risk condition." + ], + "Unchecked": "MT.1013 accepts only Require password change, not the Require risk remediation control that Learn now recommends, so it can't verify the step yet.", + "Sources": [ + { + "Url": "https://learn.microsoft.com/entra/identity/conditional-access/policy-risk-based-user", + "Mirror": "entra-docs-mirror", + "Note": "The policy targets all users and resources, excludes emergency access accounts and service accounts, asks for risk remediation at high user risk, and starts in report-only.", + "Reviewed": "2026-11-05" + }, + { + "Url": "https://learn.microsoft.com/entra/id-protection/howto-identity-protection-configure-risk-policies", + "Mirror": "entra-docs-mirror", + "Note": "Users not registered for MFA can't self-remediate and stay blocked, and synced users also need password writeback. Clear existing risk before turning the policy on.", + "Reviewed": "2026-11-05" + }, + { + "Url": "https://learn.microsoft.com/entra/id-protection/howto-identity-protection-remediate-unblock", + "Mirror": "entra-docs-mirror", + "Note": "Sign-in risk left unremediated raises user risk. A sign-in risk policy lets users clear it with MFA first.", + "Reviewed": "2026-11-05" + }, + { + "Url": "https://learn.microsoft.com/entra/id-protection/id-protection-faq", + "Mirror": "entra-docs-mirror", + "Note": "Leaked credentials set user risk to high, and for synced users the detection needs password hash sync.", + "Reviewed": "2026-11-05" + } + ] + }, + { + "Id": "entra.passkeys-enabled", + "Title": "Enable passkeys (FIDO2) in the Authentication methods policy", + "Summary": "Users in scope can register a passkey on a security key, in Microsoft Authenticator or with a passkey provider.", + "Rollout": [ + "Enable it for a pilot group that includes admins, and watch registrations in the Authentication methods activity report.", + "Give admins a passkey profile that allows only device-bound passkeys.", + "Widen the targets group by group." + ], + "Sources": [ + { + "Url": "https://learn.microsoft.com/entra/identity/authentication/how-to-authentication-passkeys-fido2", + "Mirror": "entra-docs-mirror", + "Note": "Turn on Passkey (FIDO2) for the users who will register and allow self-service setup, or they can't add a passkey in Security info.", + "Reviewed": "2026-11-05" + } + ] + }, + { + "Id": "entra.temporary-access-pass", + "Title": "Enable Temporary Access Pass", + "Summary": "Admins can issue a time-limited pass, so a user with no MFA method can sign in and register a passwordless one.", + "Sources": [ + { + "Url": "https://learn.microsoft.com/entra/identity/authentication/howto-authentication-temporary-access-pass", + "Mirror": "entra-docs-mirror", + "Note": "A pass works only for users in scope of the Temporary Access Pass method, so enable it and target the users who onboard or recover with it.", + "Reviewed": "2026-11-05" + } + ] + }, + { + "Id": "entra.certificate-based-auth", + "Title": "Configure Microsoft Entra certificate-based authentication", + "Summary": "Users can sign in with a smart card or certificate that Microsoft Entra ID accepts as multifactor.", + "Unchecked": "No Maester or Zero Trust Assessment check yet.", + "Sources": [ + { + "Url": "https://learn.microsoft.com/entra/identity/authentication/how-to-deploy-phishing-resistant-passwordless-authentication", + "Mirror": "entra-docs-mirror", + "Note": "Certificate-based authentication takes more setup than passkeys, so Learn suggests it only where it is needed.", + "Reviewed": "2026-11-05" + }, + { + "Url": "https://learn.microsoft.com/entra/identity/authentication/concept-authentication-strengths", + "Mirror": "entra-docs-mirror", + "Note": "Only multifactor certificate-based authentication is part of the phishing-resistant strength.", + "Reviewed": "2026-11-05" + } + ] + }, + { + "Id": "entra.phishing-resistant-registered-admins", + "Title": "Administrators have a phishing-resistant method registered", + "Summary": "Every account that holds an admin role can already sign in with a passkey, Windows Hello for Business, Platform SSO or a certificate.", + "RequiresOneOf": [["entra.passkeys-enabled", "intune.windows-hello", "entra.certificate-based-auth", "intune.macos-platform-sso"]], + "RecommendedFirst": ["entra.temporary-access-pass"], + "Unchecked": "No Maester check yet. The Zero Trust Assessment pack checks it (ZTA.21782) once its results can name steps.", + "Sources": [ + { + "Url": "https://learn.microsoft.com/entra/identity/authentication/concept-authentication-strengths", + "Mirror": "entra-docs-mirror", + "Note": "A strength can be met only with methods the tenant has enabled and the user has registered. Any method in the phishing-resistant strength will do.", + "Reviewed": "2026-11-05" + }, + { + "Url": "https://learn.microsoft.com/entra/identity/conditional-access/policy-admin-phish-resistant-mfa", + "Mirror": "entra-docs-mirror", + "Note": "Admins register a phishing-resistant method before the policy is on, using a Temporary Access Pass if they have no MFA method yet.", + "Reviewed": "2026-11-05" + } + ] + }, + { + "Id": "entra.phishing-resistant-admins", + "Title": "Require phishing-resistant MFA for administrator roles", + "Summary": "Accounts in admin roles must sign in with a phishing-resistant method to reach any resource.", + "Requires": ["entra.phishing-resistant-registered-admins", "entra.emergency-access-excluded"], + "Rollout": [ + "Create the policy for the admin roles in report-only mode and review the sign-ins it would block.", + "Turn it on for admins on Windows and iOS first, then macOS and Android.", + "Keep the emergency access accounts excluded." + ], + "Sources": [ + { + "Url": "https://learn.microsoft.com/entra/identity/conditional-access/policy-admin-phish-resistant-mfa", + "Mirror": "entra-docs-mirror", + "Note": "Admins without a phishing-resistant method are locked out when the policy turns on, which can lock you out of the tenant. Exclude the emergency access accounts.", + "Reviewed": "2026-11-05" + } + ] + }, + { + "Id": "entra.phishing-resistant-registered-all", + "Title": "Users have a phishing-resistant method registered", + "Summary": "Users can already sign in with a passkey, Windows Hello for Business, Platform SSO or a certificate on the devices they use.", + "RequiresOneOf": [["entra.passkeys-enabled", "intune.windows-hello", "entra.certificate-based-auth", "intune.macos-platform-sso"]], + "RecommendedFirst": ["entra.temporary-access-pass"], + "Unchecked": "No Maester check yet. A measure is planned, and the Zero Trust Assessment pack checks it (ZTA.21801) once its results can name steps.", + "Sources": [ + { + "Url": "https://learn.microsoft.com/entra/identity/authentication/how-to-deploy-phishing-resistant-passwordless-authentication", + "Mirror": "entra-docs-mirror", + "Note": "Users register a portable credential first and device-bound ones after. New users and users with no MFA method start with a Temporary Access Pass.", + "Reviewed": "2026-11-05" + }, + { + "Url": "https://learn.microsoft.com/entra/identity/authentication/concept-authentication-strengths", + "Mirror": "entra-docs-mirror", + "Note": "A strength can be met only with methods the tenant has enabled and the user has registered. Any method in the phishing-resistant strength will do.", + "Reviewed": "2026-11-05" + } + ] + }, + { + "Id": "entra.phishing-resistant-all", + "Title": "Require phishing-resistant MFA for all users", + "Summary": "Every user must sign in with a phishing-resistant method to reach any resource.", + "Requires": [ + "entra.phishing-resistant-registered-all", + "entra.emergency-access-excluded", + "entra.ca-exclude-sync-accounts" + ], + "RecommendedFirst": ["entra.phishing-resistant-admins"], + "Rollout": [ + "Create the all-users policy in report-only mode early, before registration campaigns, to see which sign-ins it would block.", + "Enforce it in waves, one policy per device platform, for groups of users who are ready.", + "Once almost every user is in a ready group, turn the all-users policy on and remove the per-platform policies." + ], + "Sources": [ + { + "Url": "https://learn.microsoft.com/entra/identity/authentication/concept-authentication-strength-how-it-works", + "Mirror": "entra-docs-mirror", + "Note": "A user who hasn't registered a method the strength accepts can't reach the resource, so get users registered before you enforce it.", + "Reviewed": "2026-11-05" + }, + { + "Url": "https://learn.microsoft.com/entra/identity/authentication/how-to-deploy-phishing-resistant-passwordless-authentication", + "Mirror": "entra-docs-mirror", + "Note": "Enforcement typically starts with admins and then reaches other users in waves by device platform, with the emergency access accounts excluded.", + "Reviewed": "2026-11-05" + }, + { + "Url": "https://learn.microsoft.com/entra/identity/conditional-access/policy-all-users-mfa-strength", + "Mirror": "entra-docs-mirror", + "Note": "With Connect or Cloud Sync, exclude the Directory Synchronization Accounts role from all-user authentication strength policies.", + "Reviewed": "2026-11-05" + } + ] + }, + { + "Id": "entra.pim-approval-global-admin", + "Title": "Require approval to activate Global Administrator in PIM", + "Summary": "Each Global Administrator activation waits for a named approver before it takes effect.", + "Requires": ["entra.emergency-access-accounts"], + "Rollout": ["Name at least two approvers before you require approval."], + "Sources": [ + { + "Url": "https://learn.microsoft.com/entra/id-governance/privileged-identity-management/pim-how-to-change-default-settings", + "Mirror": "entra-docs-mirror", + "Note": "With approval on, no named approver and no active Global or Privileged Role Administrator, nobody can approve. Permanent emergency access accounts avoid that lock-out.", + "Reviewed": "2026-11-05" + }, + { + "Url": "https://learn.microsoft.com/entra/id-governance/privileged-identity-management/pim-deployment-plan", + "Mirror": "entra-docs-mirror", + "Note": "The plan's example settings have another Global Administrator approve each Global Administrator activation.", + "Reviewed": "2026-11-05" + } + ] + }, + { + "Id": "entra.pim-notifications", + "Title": "Send PIM notifications for privileged roles to a monitored mailbox", + "Summary": "Assignments to and activations of highly privileged roles email a security mailbox as well as the default recipients.", + "Sources": [ + { + "Url": "https://learn.microsoft.com/entra/id-governance/privileged-identity-management/pim-how-to-change-default-settings", + "Mirror": "entra-docs-mirror", + "Note": "Each role's PIM settings can copy assignment and activation emails to extra recipients, such as a mailbox the security team watches.", + "Reviewed": "2026-11-05" + } + ] + }, + { + "Id": "entra.pim-eligible-roles", + "Title": "Make privileged role assignments eligible in PIM", + "Summary": "Administrators hold privileged roles as eligible assignments they activate when needed. Only the emergency access accounts stay permanently active.", + "Requires": ["entra.emergency-access-accounts"], + "RecommendedFirst": ["entra.pim-approval-global-admin", "entra.pim-notifications"], + "Rollout": [ + "Pilot with a small group of admins, and check that activation, approval and notifications work as planned.", + "Make Global Administrator and Security Administrator assignments eligible first, then the other privileged roles.", + "Remove service principals from privileged roles or give them time-bound active assignments, since they can't be eligible.", + "If activation fails in production, make the affected assignments active again, then fix the settings." + ], + "Sources": [ + { + "Url": "https://learn.microsoft.com/entra/id-governance/privileged-identity-management/pim-getting-started", + "Mirror": "entra-docs-mirror", + "Note": "For Microsoft Entra roles, configure the role settings first, then give eligible assignments, then let users activate them just in time.", + "Reviewed": "2026-11-05" + }, + { + "Url": "https://learn.microsoft.com/entra/identity/role-based-access-control/security-emergency-access", + "Mirror": "entra-docs-mirror", + "Note": "If every Global and Privileged Role Administrator is eligible and activation needs an approver nobody can be, the tenant is locked out. Keep emergency accounts active.", + "Reviewed": "2026-11-05" + }, + { + "Url": "https://learn.microsoft.com/entra/id-governance/privileged-identity-management/pim-deployment-plan", + "Mirror": "entra-docs-mirror", + "Note": "Pilot with test users, convert the most privileged roles first, and roll back by making assignments active again if activation fails.", + "Reviewed": "2026-11-05" + } + ] + } + ] +} diff --git a/powershell/assets/steps/goals.json b/powershell/assets/steps/goals.json new file mode 100644 index 0000000000..15b1cd5eba --- /dev/null +++ b/powershell/assets/steps/goals.json @@ -0,0 +1,53 @@ +{ + "$schema": "./steps.schema.json", + "Goals": [ + { + "Id": "compliant-devices", + "Title": "Require compliant devices", + "Summary": "Only devices that Intune manages and marks compliant can reach Microsoft 365.", + "Step": "entra.ca-require-compliant-device" + }, + { + "Id": "managed-devices", + "Title": "Require managed devices", + "Summary": "Only devices that Intune marks compliant or that are hybrid joined to Microsoft Entra ID can reach Microsoft 365.", + "Step": "entra.ca-require-managed-device" + }, + { + "Id": "risk-policies", + "Title": "Use risk-based Conditional Access", + "Summary": "Users and sign-ins that ID Protection rates risky must prove themselves with MFA or a secure password change before they get in.", + "Step": "entra.ca-user-risk" + }, + { + "Id": "phishing-resistant-mfa", + "Title": "Require phishing-resistant MFA", + "Summary": "Every user signs in with a passkey, Windows Hello for Business or another method that a phishing site can't replay.", + "Step": "entra.phishing-resistant-all" + }, + { + "Id": "privileged-access", + "Title": "Replace standing admin access with PIM", + "Summary": "Administrators activate privileged roles when they need them, and only the emergency access accounts keep standing access.", + "Step": "entra.pim-eligible-roles" + }, + { + "Id": "token-protection", + "Title": "Protect sign-in tokens on Windows", + "Summary": "Sign-in tokens for Exchange, SharePoint and Teams are bound to the Windows device they were issued to, so they can't be replayed elsewhere.", + "Step": "entra.ca-token-protection-windows" + }, + { + "Id": "email-authentication", + "Title": "Authenticate mail from your domains", + "Summary": "Receivers can tell real mail from your domains from spoofed mail, and reject the spoofed mail.", + "Step": "defender.dmarc-reject" + }, + { + "Id": "defender-device-risk", + "Title": "Use Defender device risk in compliance", + "Summary": "Devices that Defender for Endpoint rates risky become noncompliant, so the compliant-device Conditional Access policy blocks them.", + "Step": "intune.compliance-device-risk" + } + ] +} diff --git a/powershell/assets/steps/intune.json b/powershell/assets/steps/intune.json new file mode 100644 index 0000000000..b572301f0c --- /dev/null +++ b/powershell/assets/steps/intune.json @@ -0,0 +1,177 @@ +{ + "$schema": "./steps.schema.json", + "Product": "intune", + "Steps": [ + { + "Id": "intune.compliance-policies", + "Title": "Assign a compliance policy for each platform in use", + "Summary": "Intune can mark a device compliant only when a compliance policy covers its platform.", + "Unchecked": "No Maester check yet. The Zero Trust Assessment pack checks it (ZTA.24541 to ZTA.24547) once its results can name steps.", + "Sources": [ + { + "Url": "https://learn.microsoft.com/intune/device-security/compliance/overview", + "Mirror": "intune-docs-mirror", + "Note": "Compliance policies set the rules each platform's devices must meet, and Conditional Access acts on the compliance state they produce.", + "Reviewed": "2026-11-05" + }, + { + "Url": "https://learn.microsoft.com/intune/device-security/conditional-access-integration/device-based-policies", + "Mirror": "intune-docs-mirror", + "Note": "Device-based Conditional Access starts with compliance policies, one per platform, because the policy can only act on the status they report.", + "Reviewed": "2026-11-05" + } + ] + }, + { + "Id": "intune.automatic-enrollment", + "Title": "Turn on automatic Intune enrollment for Windows", + "Summary": "Windows devices enroll in Intune when users join or register them in Microsoft Entra ID.", + "Unchecked": "No Maester check yet. The Zero Trust Assessment pack checks it (ZTA.24546) once its results can name steps.", + "Sources": [ + { + "Url": "https://learn.microsoft.com/intune/device-enrollment/windows/enable-automatic-mdm", + "Mirror": "intune-docs-mirror", + "Note": "Automatic enrollment enrolls Windows devices in Intune as they join or register with Microsoft Entra ID.", + "Reviewed": "2026-11-05" + } + ] + }, + { + "Id": "intune.devices-compliant", + "Title": "Devices that sign in are compliant", + "Summary": "Most devices that sign in are enrolled in Intune and marked compliant, so requiring compliance blocks few users.", + "Requires": ["intune.compliance-policies"], + "RecommendedFirst": ["intune.automatic-enrollment"], + "Measure": { "Key": "devices-compliant", "MinimumShare": 95 }, + "Sources": [ + { + "Url": "https://learn.microsoft.com/entra/identity/conditional-access/concept-conditional-access-grant", + "Mirror": "entra-docs-mirror", + "Note": "Only devices registered in Microsoft Entra ID and enrolled in Intune can be marked compliant, so unenrolled devices fail a compliant-device policy.", + "Reviewed": "2026-11-05" + } + ] + }, + { + "Id": "intune.mark-unassigned-noncompliant", + "Title": "Mark devices with no compliance policy as not compliant", + "Summary": "A device that no compliance policy covers can't pass Conditional Access by default.", + "Sources": [ + { + "Url": "https://learn.microsoft.com/intune/device-security/compliance/overview", + "Mirror": "intune-docs-mirror", + "Note": "When Conditional Access uses compliance, review the tenant setting that decides how devices with no compliance policy are marked.", + "Reviewed": "2026-11-05" + } + ] + }, + { + "Id": "intune.windows-hello", + "Title": "Configure Windows Hello for Business on Windows devices", + "Summary": "Users set up a Windows Hello for Business key on their PCs and sign in with a PIN or biometric.", + "RecommendedFirst": ["entra.passkeys-enabled"], + "Unchecked": "No Maester check yet. The Zero Trust Assessment pack checks it (ZTA.24551) once its results can name steps.", + "Sources": [ + { + "Url": "https://learn.microsoft.com/entra/identity/authentication/how-to-deploy-phishing-resistant-passwordless-authentication", + "Mirror": "entra-docs-mirror", + "Note": "Give users a portable passkey first. They can then use it to set up Windows Hello for Business on each PC.", + "Reviewed": "2026-11-05" + }, + { + "Url": "https://learn.microsoft.com/intune/solutions/passwordless", + "Mirror": "intune-docs-mirror", + "Note": "Intune gets Windows devices ready for Windows Hello for Business by delivering its policy settings at enrollment and keeping them in place after.", + "Reviewed": "2026-11-05" + } + ] + }, + { + "Id": "intune.macos-platform-sso", + "Title": "Configure Platform SSO with the Secure Enclave key on macOS", + "Summary": "Mac users sign in with a hardware-bound key that counts as a phishing-resistant method.", + "Unchecked": "No Maester check yet. The Zero Trust Assessment pack checks it (ZTA.24568) once its results can name steps.", + "Sources": [ + { + "Url": "https://learn.microsoft.com/intune/device-configuration/settings-catalog/configure-platform-sso-macos", + "Mirror": "intune-docs-mirror", + "Note": "Platform SSO is set with an Intune settings catalog policy, best assigned as users enroll their Macs. Secure Enclave is the recommended method.", + "Reviewed": "2026-11-05" + } + ] + }, + { + "Id": "intune.defender-connector", + "Title": "Connect Defender for Endpoint to Intune", + "Summary": "Defender for Endpoint and Intune share device data, so Intune can receive the risk level Defender gives each device.", + "Unchecked": "No check yet. MT.1098 reports connector health, but it skips or passes when the Defender for Endpoint connector is missing.", + "Sources": [ + { + "Url": "https://learn.microsoft.com/intune/device-security/microsoft-defender/configure-integration", + "Mirror": "intune-docs-mirror", + "Note": "Turn on the Intune connection in the Defender portal's advanced features, then check that Intune shows the connection as enabled. It can take about 15 minutes.", + "Reviewed": "2026-11-05" + }, + { + "Url": "https://learn.microsoft.com/defender-endpoint/advanced-features", + "Mirror": "defender-docs-mirror", + "Note": "The integration has to be on in both Defender for Endpoint and Intune before Intune can use Defender's device data.", + "Reviewed": "2026-11-05" + } + ] + }, + { + "Id": "intune.defender-compliance-evaluation", + "Title": "Turn on compliance policy evaluation in the Defender for Endpoint connector", + "Summary": "Compliance policies for Windows, iOS/iPadOS and Android can use the risk level that Defender for Endpoint reports for those devices.", + "Requires": ["intune.defender-connector"], + "Unchecked": "No Maester check yet. The Zero Trust Assessment pack checks the Android toggle only (ZTA.24871).", + "Sources": [ + { + "Url": "https://learn.microsoft.com/intune/device-security/microsoft-defender/configure-integration", + "Mirror": "intune-docs-mirror", + "Note": "Once the connection shows enabled, turn on compliance policy evaluation for each platform in the connector. Each platform has its own toggle.", + "Reviewed": "2026-11-05" + }, + { + "Url": "https://learn.microsoft.com/defender-endpoint/configure-conditional-access", + "Mirror": "defender-docs-mirror", + "Note": "Defender's own walkthrough checks the connection and the platform's compliance toggle before it builds the compliance policy.", + "Reviewed": "2026-11-05" + } + ] + }, + { + "Id": "intune.compliance-device-risk", + "Title": "Require a Defender for Endpoint machine risk score in compliance policies", + "Summary": "Devices that Defender for Endpoint rates above the allowed risk level are marked noncompliant.", + "Requires": ["intune.defender-compliance-evaluation"], + "RecommendedFirst": ["defender.endpoint-onboarding", "intune.compliance-policies"], + "Rollout": [ + "Set the threshold to Low, the level most organizations use. High blocks nothing and only reports.", + "Assign the policy to a test group and confirm that its devices report the expected compliance state.", + "Widen the assignment. Where a compliant-device policy is on, risky devices lose access as soon as they are marked noncompliant." + ], + "Sources": [ + { + "Url": "https://learn.microsoft.com/intune/device-security/mobile-threat-defense/enable-connector", + "Mirror": "intune-docs-mirror", + "Note": "A platform's compliance policies use the connector's data only while that platform's toggle is on.", + "Reviewed": "2026-11-05" + }, + { + "Url": "https://learn.microsoft.com/intune/device-security/microsoft-defender/overview", + "Mirror": "intune-docs-mirror", + "Note": "Connect the services, onboard devices, then add the risk rule to compliance. Conditional Access then blocks the devices marked noncompliant.", + "Reviewed": "2026-11-05" + }, + { + "Url": "https://learn.microsoft.com/intune/device-security/microsoft-defender/configure-integration", + "Mirror": "intune-docs-mirror", + "Note": "The risk score is one setting in each platform's compliance policy, so set up those policies first. Low suits most organizations; High only reports.", + "Reviewed": "2026-11-05" + } + ] + } + ] +} diff --git a/powershell/assets/steps/steps.schema.json b/powershell/assets/steps/steps.schema.json new file mode 100644 index 0000000000..7b9acac2ee --- /dev/null +++ b/powershell/assets/steps/steps.schema.json @@ -0,0 +1,170 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://maester.dev/schemas/steps.schema.json", + "title": "Maester step catalogue", + "description": "A file of the defender's path catalogue: goals.json, or .json with the steps of one product. See docs/proposals/defenders-path.md, section 4.", + "type": "object", + "oneOf": [ + { "required": ["Steps"] }, + { "required": ["Goals"] } + ], + "properties": { + "$schema": { "type": "string" }, + "Product": { + "description": "The taxonomy product key of every step in the file. The file is named after it.", + "type": "string", + "pattern": "^[a-z0-9][a-z0-9-]*$" + }, + "Steps": { + "type": "array", + "items": { "$ref": "#/$defs/step" } + }, + "Goals": { + "description": "The goals, in the order the report shows them.", + "type": "array", + "items": { "$ref": "#/$defs/goal" } + } + }, + "dependentRequired": { "Steps": ["Product"] }, + "additionalProperties": false, + "$defs": { + "stepId": { + "type": "string", + "pattern": "^[a-z0-9][a-z0-9-]*\\.[a-z0-9][a-z0-9-]*$", + "maxLength": 80 + }, + "stepIds": { + "type": "array", + "items": { "$ref": "#/$defs/stepId" }, + "uniqueItems": true + }, + "step": { + "type": "object", + "required": ["Id", "Title", "Summary", "Sources"], + "properties": { + "Id": { + "description": ".. Stable once shipped, like a test ID.", + "$ref": "#/$defs/stepId" + }, + "Title": { + "description": "Imperative for a change, a statement for a tenant state. One line.", + "type": "string", + "pattern": "^[^\\r\\n]+$", + "maxLength": 100 + }, + "Summary": { + "description": "One sentence on what changes for users or the tenant.", + "type": "string", + "pattern": "^[^\\r\\n]+$", + "maxLength": 200 + }, + "Requires": { + "description": "Steps that must be done first, or the change fails or locks users out.", + "$ref": "#/$defs/stepIds" + }, + "RequiresOneOf": { + "description": "Groups of at least two steps. Any one step of a group is enough.", + "type": "array", + "items": { "allOf": [{ "$ref": "#/$defs/stepIds" }, { "minItems": 2 }] } + }, + "RecommendedFirst": { + "description": "Steps that make this one safer or more useful. They never block.", + "$ref": "#/$defs/stepIds" + }, + "Conflicts": { + "description": "Steps that must be off before this one can be on.", + "$ref": "#/$defs/stepIds" + }, + "OnlyWhen": { + "description": "Conditions that must all hold, or the step is Not applicable: hybrid-identity, or license:.", + "type": "array", + "items": { "type": "string", "pattern": "^(hybrid-identity|license:[A-Za-z0-9_\\-]+(&[A-Za-z0-9_\\-]+)*)$" }, + "uniqueItems": true + }, + "Rollout": { + "description": "Ordered sentences on how to switch the step on safely.", + "type": "array", + "items": { "type": "string", "pattern": "^[^\\r\\n]+$", "maxLength": 200 } + }, + "Sources": { + "type": "array", + "minItems": 1, + "items": { "$ref": "#/$defs/source" } + }, + "Measure": { + "description": "The figure from the measure registry (powershell/assets/MaesterMeasures.psd1) that decides whether a step that is a state of the tenant is done.", + "type": "object", + "required": ["Key", "MinimumShare"], + "properties": { + "Key": { "type": "string", "pattern": "^[a-z0-9][a-z0-9-]*$" }, + "MinimumShare": { "description": "The share, in percent, at which the step is done.", "type": "integer", "minimum": 1, "maximum": 100 } + }, + "additionalProperties": false + }, + "Unchecked": { + "description": "Why no test or measure verifies the step yet. Required when no built-in test names the step and it has no Measure.", + "type": "string", + "pattern": "^[^\\r\\n]+$", + "maxLength": 200 + } + }, + "additionalProperties": false + }, + "source": { + "type": "object", + "required": ["Note", "Reviewed"], + "oneOf": [ + { "required": ["Url"] }, + { "required": ["Maintainer"] } + ], + "properties": { + "Url": { + "description": "The Microsoft Learn page, with no locale.", + "type": "string", + "pattern": "^https://learn\\.microsoft\\.com/(?![a-z]{2}-[a-z]{2}/)[^\\s]+$" + }, + "Mirror": { + "description": "The merill/*-docs-mirror repository that holds the page.", + "type": "string", + "pattern": "^[a-z0-9-]+-docs-mirror$" + }, + "Maintainer": { + "description": "The GitHub handle of the maintainer who stands behind a relationship that Learn does not document.", + "type": "string", + "pattern": "^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}$" + }, + "Note": { + "description": "Maester's own wording of what the source says about order. Never Microsoft's text.", + "type": "string", + "pattern": "^[^\\r\\n]+$", + "maxLength": 200 + }, + "Reviewed": { + "description": "When someone last read the source against the step.", + "type": "string", + "format": "date", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$" + } + }, + "additionalProperties": false + }, + "goal": { + "type": "object", + "required": ["Id", "Title", "Summary", "Step"], + "properties": { + "Id": { + "type": "string", + "pattern": "^[a-z0-9][a-z0-9-]*$", + "maxLength": 60 + }, + "Title": { "type": "string", "pattern": "^[^\\r\\n]+$", "maxLength": 100 }, + "Summary": { "type": "string", "pattern": "^[^\\r\\n]+$", "maxLength": 200 }, + "Step": { + "description": "The step that achieves the goal. The goal's steps are this step and its prerequisites, at any depth.", + "$ref": "#/$defs/stepId" + } + }, + "additionalProperties": false + } + } +} diff --git a/powershell/internal/connect/Read-MtTenantContext.ps1 b/powershell/internal/connect/Read-MtTenantContext.ps1 index 5dd4a2c4c8..1b0f8565e6 100644 --- a/powershell/internal/connect/Read-MtTenantContext.ps1 +++ b/powershell/internal/connect/Read-MtTenantContext.ps1 @@ -63,6 +63,9 @@ function Read-MtTenantContext { $primaryDomain = $null $tenantType = 'Unknown' $tenantTypeSource = 'Unknown' + # Whether the tenant syncs identities from on-premises (the hybrid-identity condition of the defender's path). + # $null when the organization could not be read. + $hybridIdentity = $null if ($graphConnected) { try { $organization = @(Invoke-MtGraphRequest -RelativeUri 'organization' -ErrorAction Stop) | Select-Object -First 1 @@ -70,6 +73,8 @@ function Read-MtTenantContext { $primaryDomain = @($organization.verifiedDomains | Where-Object { $_.isDefault } | Select-Object -First 1).name $tenantType = switch ($organization.tenantType) { 'AAD' { 'Workforce' } 'CIAM' { 'External' } default { 'Unknown' } } if ($tenantType -ne 'Unknown') { $tenantTypeSource = 'Detected' } + if ($organization -and $organization.PSObject.Properties['onPremisesSyncEnabled']) { $hybridIdentity = $organization.onPremisesSyncEnabled -eq $true } + elseif ($organization -is [System.Collections.IDictionary] -and $organization.Contains('onPremisesSyncEnabled')) { $hybridIdentity = $organization['onPremisesSyncEnabled'] -eq $true } } catch { Write-Verbose "Could not read the organization: $($_.Exception.Message)" } @@ -154,5 +159,6 @@ function Read-MtTenantContext { AuthType = if ($mgContext) { [string]$mgContext.AuthType } else { $null } Account = if ($mgContext) { $mgContext.Account } else { $null } Scopes = if ($mgContext) { @($mgContext.Scopes) } else { @() } + HybridIdentity = $hybridIdentity } } diff --git a/powershell/internal/engine/Get-MtMeasureRegistry.ps1 b/powershell/internal/engine/Get-MtMeasureRegistry.ps1 new file mode 100644 index 0000000000..7419a51be1 --- /dev/null +++ b/powershell/internal/engine/Get-MtMeasureRegistry.ps1 @@ -0,0 +1,83 @@ +function Get-MtMeasureRegistry { + <# + .SYNOPSIS + Returns the measure registry of the defender's path (assets/MaesterMeasures.psd1), with the problems found in + it. Cached for the session. + + .DESCRIPTION + A measure is a figure the engine reads from Graph for a step that is a state of the tenant + (docs/proposals/defenders-path.md, section 11). Steps name a measure by its Key in the step catalogue. + + Returns an object with Measures, a case-sensitive dictionary of key to entry (Key, Function, Title, Unit, Caveat, + Service, License, Permission, each list as an array, Caveat empty when the entry has none), and Problems, one + message for each entry that is wrong. Whether the reader function exists is checked by Get-MtStepProblem, which + runs in the module. + + -Path reads another file, such as a fixture in the unit tests, and is not cached. + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param( + # The registry file. Defaults to the module's assets/MaesterMeasures.psd1. + [Parameter()] [string] $Path + ) + + if (-not $Path -and $script:__MtMeasureRegistry) { return $script:__MtMeasureRegistry } + $file = if ($Path) { $Path } else { Join-Path $ExecutionContext.SessionState.Module.ModuleBase 'assets/MaesterMeasures.psd1' } + $name = [System.IO.Path]::GetFileName($file) + + $problems = [System.Collections.Generic.List[string]]::new() + $measures = [System.Collections.Generic.Dictionary[string, object]]::new([System.StringComparer]::Ordinal) + $schema = Get-MtTestSchema + $services = Get-MtServiceRegistry + $keys = @('Key', 'Function', 'Title', 'Unit', 'Caveat', 'Service', 'License', 'Permission') + + $data = $null + try { $data = Import-PowerShellDataFile -LiteralPath $file -ErrorAction Stop } + catch { $problems.Add("${name}: the file can't be read: $($_.Exception.Message)") } + + foreach ($entry in @($data.Measures | Where-Object { $null -ne $_ })) { + if ($entry -isnot [hashtable]) { $problems.Add("${name}: every measure must be a hashtable."); continue } + $key = $entry['Key'] + if ($key -isnot [string] -or $key -cnotmatch '^[a-z0-9][a-z0-9-]*$') { $problems.Add("${name}: '$key' is not a measure key (lowercase kebab-case)."); continue } + if ($measures.ContainsKey($key)) { $problems.Add("${name}: the measure '$key' is listed twice."); continue } + $where = "$name ($key)" + foreach ($k in $entry.Keys) { if ($k -cnotin $keys) { $problems.Add("${where}: unknown key '$k'.") } } + if ($entry['Function'] -isnot [string] -or $entry['Function'] -cnotmatch '^[A-Z][a-z]+-Mt[A-Za-z0-9]+$') { $problems.Add("${where}: Function must name a Maester function, Verb-MtNoun.") } + foreach ($text in 'Title', 'Unit') { + if ($entry[$text] -isnot [string] -or $entry[$text] -notmatch '^[^\r\n]+$') { $problems.Add("${where}: $text must be one line of text.") } + } + if ($entry.ContainsKey('Caveat') -and ($entry['Caveat'] -isnot [string] -or $entry['Caveat'] -notmatch '^[^\r\n]{1,200}$')) { + $problems.Add("${where}: Caveat must be one line of 200 characters or less.") + } + $service = @($entry['Service'] | Where-Object { $_ }) + if ($service.Count -eq 0) { $problems.Add("${where}: Service is required.") } + foreach ($s in $service) { + if (-not (Resolve-MtServiceName -Name ([string]$s) -Registry $services)) { $problems.Add("${where}: Service '$s' is not in the service registry.") } + } + foreach ($l in @($entry['License'] | Where-Object { $_ })) { + if ([string]$l -notmatch $schema.Properties.License.Pattern) { $problems.Add("${where}: License '$l' is not valid.") } + } + foreach ($p in @($entry['Permission'] | Where-Object { $_ })) { + if ([string]$p -notmatch $schema.Properties.Permission.Pattern) { $problems.Add("${where}: Permission '$p' is not valid. Write ::.") } + } + $measures[$key] = [pscustomobject][ordered]@{ + Key = $key + Function = [string]$entry['Function'] + Title = [string]$entry['Title'] + Unit = [string]$entry['Unit'] + Caveat = if ($entry['Caveat'] -is [string]) { $entry['Caveat'] } else { '' } + Service = [string[]]@($service) + License = [string[]]@($entry['License'] | Where-Object { $_ }) + Permission = [string[]]@($entry['Permission'] | Where-Object { $_ }) + } + } + + $registry = [pscustomobject]@{ + Path = $file + Measures = $measures + Problems = $problems.ToArray() + } + if (-not $Path) { $script:__MtMeasureRegistry = $registry } + $registry +} diff --git a/powershell/internal/engine/Get-MtMeasureSetting.ps1 b/powershell/internal/engine/Get-MtMeasureSetting.ps1 new file mode 100644 index 0000000000..8166e05d9c --- /dev/null +++ b/powershell/internal/engine/Get-MtMeasureSetting.ps1 @@ -0,0 +1,33 @@ +function Get-MtMeasureSetting { + <# + .SYNOPSIS + Returns the Measures section of a run config: whether measures are read, and the thresholds it changes. + + .DESCRIPTION + Measures.Enabled (default true) turns the measures of the defender's path off, and + Measures.MinimumShare. changes the threshold of a measure, a whole number from 1 to 100 + (docs/proposals/defenders-path.md, section 8). Resolve-MtRunConfig has already rejected values out of range. + + Returns an object with Enabled (bool) and MinimumShare (a hashtable of measure key to threshold). + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param( + # The resolved run config, or $null. + [Parameter()] [AllowNull()] [object] $RunConfig + ) + + $enabled = $true + $minimum = @{} + $section = if ($RunConfig -and $RunConfig.PSObject.Properties['Measures']) { $RunConfig.Measures } else { $null } + if ($section) { + if ($section.PSObject.Properties['Enabled'] -and $null -ne $section.Enabled) { $enabled = [bool]$section.Enabled } + $shares = if ($section.PSObject.Properties['MinimumShare']) { $section.MinimumShare } else { $null } + if ($shares -is [System.Collections.IDictionary]) { + foreach ($key in $shares.Keys) { if ($null -ne $shares[$key]) { $minimum[[string]$key] = [int]$shares[$key] } } + } elseif ($shares) { + foreach ($p in $shares.PSObject.Properties) { if ($null -ne $p.Value) { $minimum[$p.Name] = [int]$p.Value } } + } + } + [pscustomobject]@{ Enabled = $enabled; MinimumShare = $minimum } +} diff --git a/powershell/internal/engine/Get-MtNativeTestInventory.ps1 b/powershell/internal/engine/Get-MtNativeTestInventory.ps1 index 105884c6b1..2fafb24771 100644 --- a/powershell/internal/engine/Get-MtNativeTestInventory.ps1 +++ b/powershell/internal/engine/Get-MtNativeTestInventory.ps1 @@ -76,6 +76,15 @@ function Get-MtNativeTestInventory { Write-Warning "These tests have a Control that names the framework '$($group.Name)' and a requirement that '$($group.Group[0].Framework.File)' does not have, so it gives them no Benchmark: $references." } + # A Step that the step catalogue does not have is ignored, with one warning that lists the tests. The build + # fails on it for a built-in test (Get-MtStepProblem). + $unknownSteps = @(foreach ($t in $tests) { + foreach ($step in @($t.Step | Where-Object { $_ })) { if (-not (Get-MtStepCatalog).Steps.ContainsKey($step)) { "$($t.Id) ($step)" } } + }) + if ($unknownSteps.Count -gt 0) { + Write-Warning "These tests name a step that the step catalogue does not have, so the step is ignored: $($unknownSteps -join ', ')." + } + # A shim returns another test's function: ShimOf names that test, so a report can show the two as one setting. $byFunction = @{} foreach ($t in $tests) { if ($t.FunctionName -and $t.Id -and -not $byFunction.ContainsKey($t.FunctionName)) { $byFunction[$t.FunctionName] = $t.Id } } diff --git a/powershell/internal/engine/Get-MtStepCatalog.ps1 b/powershell/internal/engine/Get-MtStepCatalog.ps1 new file mode 100644 index 0000000000..1b3b28f95d --- /dev/null +++ b/powershell/internal/engine/Get-MtStepCatalog.ps1 @@ -0,0 +1,287 @@ +function Get-MtStepCatalog { + <# + .SYNOPSIS + Returns the step catalogue of the defender's path (assets/steps), with the problems found in it. Cached for the + session. + + .DESCRIPTION + The catalogue (docs/proposals/defenders-path.md, section 4) is a folder of JSON files: goals.json holds the + goals, and .json the steps of one product. A step is one change an administrator makes or one + state the tenant must reach. Tests name the steps they verify with the Step attribute; the catalogue holds how + steps relate (Requires, RequiresOneOf, RecommendedFirst, Conflicts, OnlyWhen), how to switch each on (Rollout), + the Microsoft Learn pages behind them (Sources) and, for a step that is a state of the tenant, the measure that + decides whether it is done (Measure: the Key of a measure in the measure registry and a MinimumShare). + + Returns an object with: + + - Steps: a case-sensitive dictionary of step ID to step, in file and catalogue order. Each step has every field + of the format, lists as arrays and missing fields as empty arrays or $null, plus File. + - Goals: the goals in catalogue order. Each has Id, Title, Summary, Step and Steps: the goal's step and its + prerequisites at any depth (through Requires, RequiresOneOf and RecommendedFirst), prerequisites first. + - Problems: one message for each thing that is wrong, each starting with the file name. The build fails on + any (Get-MtStepProblem); a run uses what is valid. + + -Path reads another folder, such as a fixture in the unit tests, and is not cached. + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param( + # The catalogue folder. Defaults to the module's assets/steps. + [Parameter()] [string] $Path + ) + + if (-not $Path -and $script:__MtStepCatalog) { return $script:__MtStepCatalog } + $folder = if ($Path) { $Path } else { Join-Path $ExecutionContext.SessionState.Module.ModuleBase 'assets/steps' } + + $problems = [System.Collections.Generic.List[string]]::new() + $steps = [System.Collections.Generic.Dictionary[string, object]]::new([System.StringComparer]::Ordinal) + $goals = [System.Collections.Generic.List[object]]::new() + $stepPattern = '^[a-z0-9][a-z0-9-]*\.[a-z0-9][a-z0-9-]*$' + $linePattern = '^[^\r\n]+$' + $stepKeys = @('Id', 'Title', 'Summary', 'Requires', 'RequiresOneOf', 'RecommendedFirst', 'Conflicts', 'OnlyWhen', 'Rollout', 'Sources', 'Measure', 'Unchecked') + $sourceKeys = @('Url', 'Mirror', 'Maintainer', 'Note', 'Reviewed') + $goalKeys = @('Id', 'Title', 'Summary', 'Step') + $taxonomy = Get-MtTaxonomy + + # A text field: one line, at most -Max characters. Returns the value, or $null after recording a problem. + $checkText = { + param($where, $name, $value, $max, [bool] $required) + if ($null -eq $value -or ($value -is [string] -and $value -eq '')) { + if ($required) { $problems.Add("${where}: $name is required.") } + return $null + } + if ($value -isnot [string] -or $value -notmatch $linePattern) { $problems.Add("${where}: $name must be one line of text."); return $null } + if ($value.Length -gt $max) { $problems.Add("${where}: $name is longer than $max characters.") } + $value + } + # A list of step IDs. Returns the valid IDs. + $checkIds = { + param($where, $name, $value) + if ($null -eq $value) { return , @() } + $ids = @($value) + if ($value -is [string]) { $problems.Add("${where}: $name must be a list of step IDs."); return , @() } + $valid = [System.Collections.Generic.List[string]]::new() + foreach ($id in $ids) { + if ($id -isnot [string] -or $id -cnotmatch $stepPattern) { $problems.Add("${where}: $name has '$id', which is not a step ID (.)."); continue } + if ($valid.Contains($id)) { $problems.Add("${where}: $name lists '$id' twice."); continue } + $valid.Add($id) + } + , $valid.ToArray() + } + + if (-not (Test-Path -LiteralPath $folder -PathType Container)) { + $problems.Add("$($folder): the step catalogue folder does not exist.") + } + $files = @(Get-ChildItem -LiteralPath $folder -Filter '*.json' -File -ErrorAction SilentlyContinue | Where-Object { $_.Name -ne 'steps.schema.json' } | Sort-Object Name) + + foreach ($file in $files) { + $name = $file.Name + try { + $content = Get-Content -LiteralPath $file.FullName -Raw | ConvertFrom-Json -AsHashtable -ErrorAction Stop + } catch { + $problems.Add("${name}: the file is not valid JSON: $($_.Exception.Message)") + continue + } + if ($content -isnot [System.Collections.IDictionary]) { $problems.Add("${name}: the file must hold a JSON object."); continue } + + if ($name -eq 'goals.json') { + foreach ($key in $content.Keys) { if ($key -notin '$schema', 'Goals') { $problems.Add("${name}: unknown key '$key'. goals.json holds only Goals.") } } + foreach ($g in @($content['Goals'])) { + if ($g -isnot [System.Collections.IDictionary]) { $problems.Add("${name}: every goal must be an object."); continue } + foreach ($key in $g.Keys) { if ($key -cnotin $goalKeys) { $problems.Add("${name}: goal '$($g['Id'])' has the unknown key '$key'.") } } + $id = $g['Id'] + if ($id -isnot [string] -or $id -cnotmatch '^[a-z0-9][a-z0-9-]*$') { $problems.Add("${name}: '$id' is not a goal ID (lowercase kebab-case)."); continue } + if ($goals | Where-Object { $_.Id -eq $id }) { $problems.Add("${name}: the goal '$id' is listed twice."); continue } + $where = "$name ($id)" + $goal = [ordered]@{ + Id = $id + Title = & $checkText $where 'Title' $g['Title'] 100 $true + Summary = & $checkText $where 'Summary' $g['Summary'] 200 $true + Step = $null + Steps = @() + } + if ($g['Step'] -isnot [string] -or $g['Step'] -cnotmatch $stepPattern) { $problems.Add("${where}: Step must name the step that achieves the goal.") } + else { $goal.Step = $g['Step'] } + $goals.Add([pscustomobject]$goal) + } + continue + } + + $product = $content['Product'] + $fileProduct = [System.IO.Path]::GetFileNameWithoutExtension($name) + foreach ($key in $content.Keys) { if ($key -notin '$schema', 'Product', 'Steps') { $problems.Add("${name}: unknown key '$key'. A step file holds Product and Steps.") } } + if ($product -cne $fileProduct) { $problems.Add("${name}: Product is '$product'. A step file is named after its product, so it must be '$fileProduct'.") } + if (-not $taxonomy.Lookup.Product.ContainsKey($fileProduct) -or $taxonomy.Lookup.Product[$fileProduct].Key -cne $fileProduct) { + $problems.Add("${name}: '$fileProduct' is not a product key of the taxonomy registry.") + } + + foreach ($s in @($content['Steps'])) { + if ($s -isnot [System.Collections.IDictionary]) { $problems.Add("${name}: every step must be an object."); continue } + $id = $s['Id'] + if ($id -isnot [string] -or $id -cnotmatch $stepPattern) { $problems.Add("${name}: '$id' is not a step ID (., lowercase)."); continue } + if ($id.Length -gt 80) { $problems.Add("${name}: the step ID '$id' is longer than 80 characters.") } + if (-not $id.StartsWith("$fileProduct.", [System.StringComparison]::Ordinal)) { $problems.Add("${name}: the step '$id' must start with '$fileProduct.', the product of its file.") } + if ($steps.ContainsKey($id)) { $problems.Add("${name}: the step '$id' is also in $($steps[$id].File)."); continue } + $where = "$name ($id)" + foreach ($key in $s.Keys) { if ($key -cnotin $stepKeys) { $problems.Add("${where}: unknown key '$key'.") } } + + $oneOf = [System.Collections.Generic.List[object]]::new() + if ($null -ne $s['RequiresOneOf']) { + foreach ($group in @($s['RequiresOneOf'])) { + $members = & $checkIds $where 'RequiresOneOf' $group + if ($group -is [string] -or $members.Count -lt 2) { $problems.Add("${where}: each RequiresOneOf group lists at least two steps."); continue } + $oneOf.Add($members) + } + } + $onlyWhen = [System.Collections.Generic.List[string]]::new() + foreach ($condition in @($s['OnlyWhen'] | Where-Object { $null -ne $_ })) { + if ($condition -is [string] -and ($condition -ceq 'hybrid-identity' -or $condition -cmatch '^license:[A-Za-z0-9_\-]+(&[A-Za-z0-9_\-]+)*$')) { $onlyWhen.Add($condition) } + else { $problems.Add("${where}: OnlyWhen has '$condition', which is not a known condition (hybrid-identity, license:).") } + } + $rollout = @(foreach ($sentence in @($s['Rollout'] | Where-Object { $null -ne $_ })) { & $checkText $where 'Rollout' $sentence 200 $true }) + + $sources = [System.Collections.Generic.List[object]]::new() + foreach ($src in @($s['Sources'] | Where-Object { $null -ne $_ })) { + if ($src -isnot [System.Collections.IDictionary]) { $problems.Add("${where}: every source must be an object."); continue } + foreach ($key in $src.Keys) { if ($key -cnotin $sourceKeys) { $problems.Add("${where}: a source has the unknown key '$key'.") } } + $url = $src['Url']; $maintainer = $src['Maintainer'] + if ([bool]$url -eq [bool]$maintainer) { $problems.Add("${where}: a source has either a Url or a Maintainer."); } + if ($url -and ($url -isnot [string] -or $url -notmatch '^https://learn\.microsoft\.com/\S+$')) { $problems.Add("${where}: the source '$url' is not a Microsoft Learn URL.") } + elseif ($url -and $url -match '^https://learn\.microsoft\.com/[a-z]{2}-[a-z]{2}/') { $problems.Add("${where}: the source '$url' has a locale. Leave it out, as the check guides do.") } + if ($maintainer -and ($maintainer -isnot [string] -or $maintainer -notmatch '^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}$')) { $problems.Add("${where}: the source maintainer '$maintainer' is not a GitHub handle.") } + if ($src['Mirror'] -and ($src['Mirror'] -isnot [string] -or $src['Mirror'] -notmatch '^[a-z0-9-]+-docs-mirror$')) { $problems.Add("${where}: the source mirror '$($src['Mirror'])' is not the name of a docs mirror repository.") } + $reviewed = $src['Reviewed'] + if ($reviewed -is [datetime]) { $reviewed = $reviewed.ToString('yyyy-MM-dd', [System.Globalization.CultureInfo]::InvariantCulture) } + $date = [datetime]::MinValue + if ($reviewed -isnot [string] -or -not [datetime]::TryParseExact($reviewed, 'yyyy-MM-dd', [System.Globalization.CultureInfo]::InvariantCulture, [System.Globalization.DateTimeStyles]::None, [ref] $date)) { + $problems.Add("${where}: a source needs Reviewed, the date it was last read against the step (yyyy-MM-dd).") + } + $sources.Add([pscustomobject][ordered]@{ + Url = if ($url) { [string]$url } else { $null } + Mirror = if ($src['Mirror']) { [string]$src['Mirror'] } else { $null } + Maintainer = if ($maintainer) { [string]$maintainer } else { $null } + Note = & $checkText $where 'A source''s Note' $src['Note'] 200 $true + Reviewed = $reviewed + }) + } + if ($sources.Count -eq 0) { $problems.Add("${where}: a step needs at least one source.") } + + # Measure: the figure that decides whether a state step is done. Whether its Key is in the measure + # registry is checked by Get-MtStepProblem. + $measure = $null + if ($null -ne $s['Measure']) { + $m = $s['Measure'] + if ($m -isnot [System.Collections.IDictionary]) { + $problems.Add("${where}: Measure must be an object with Key and MinimumShare.") + } else { + foreach ($key in $m.Keys) { if ($key -cnotin 'Key', 'MinimumShare') { $problems.Add("${where}: Measure has the unknown key '$key'.") } } + $measureKey = $m['Key'] + $minimum = $m['MinimumShare'] + $validKey = $measureKey -is [string] -and $measureKey -cmatch '^[a-z0-9][a-z0-9-]*$' + $validMinimum = ($minimum -is [int] -or $minimum -is [long]) -and $minimum -ge 1 -and $minimum -le 100 + if (-not $validKey) { $problems.Add("${where}: Measure's Key '$measureKey' is not a measure key (lowercase kebab-case).") } + if (-not $validMinimum) { $problems.Add("${where}: Measure's MinimumShare must be a whole number from 1 to 100.") } + if ($validKey -and $validMinimum) { $measure = [pscustomobject][ordered]@{ Key = $measureKey; MinimumShare = [int]$minimum } } + } + if ($s['Unchecked']) { $problems.Add("${where}: the step has a Measure, so it must not have Unchecked.") } + } + + $steps[$id] = [pscustomobject][ordered]@{ + Id = $id + Product = $fileProduct + Title = & $checkText $where 'Title' $s['Title'] 100 $true + Summary = & $checkText $where 'Summary' $s['Summary'] 200 $true + Requires = & $checkIds $where 'Requires' $s['Requires'] + RequiresOneOf = $oneOf.ToArray() + RecommendedFirst = & $checkIds $where 'RecommendedFirst' $s['RecommendedFirst'] + Conflicts = & $checkIds $where 'Conflicts' $s['Conflicts'] + OnlyWhen = $onlyWhen.ToArray() + Rollout = $rollout + Sources = $sources.ToArray() + Measure = $measure + Unchecked = & $checkText $where 'Unchecked' $s['Unchecked'] 200 $false + File = $name + } + } + } + + # References: every step a relationship names exists, no step names itself, and none names a step in two + # relationships. + $edges = @{} + foreach ($step in $steps.Values) { + $where = "$($step.File) ($($step.Id))" + $named = @{} + $relations = [ordered]@{ + Requires = @($step.Requires) + RequiresOneOf = @($step.RequiresOneOf | ForEach-Object { $_ }) + RecommendedFirst = @($step.RecommendedFirst) + Conflicts = @($step.Conflicts) + } + foreach ($relation in $relations.Keys) { + foreach ($other in ($relations[$relation] | Select-Object -Unique)) { + if ($other -ceq $step.Id) { $problems.Add("${where}: $relation names the step itself."); continue } + if (-not $steps.ContainsKey($other)) { $problems.Add("${where}: $relation names '$other', which is not in the catalogue."); continue } + if ($named.ContainsKey($other) -and $named[$other] -ne $relation) { $problems.Add("${where}: '$other' is in both $($named[$other]) and $relation.") } + $named[$other] = $relation + } + } + # Order edges: the step comes after these. + $edges[$step.Id] = @(@($relations.Requires) + @($relations.RequiresOneOf) + @($relations.RecommendedFirst) | Where-Object { $_ -cne $step.Id -and $steps.ContainsKey($_) } | Select-Object -Unique) + } + + # Cycles through Requires, RequiresOneOf and RecommendedFirst. Each cycle is reported once, from its first step + # in catalogue order. + $state = @{} + $reported = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::Ordinal) + $visit = $null + $visit = { + param($id, [System.Collections.Generic.List[string]] $trail) + $state[$id] = 'Visiting' + $trail.Add($id) + foreach ($next in $edges[$id]) { + if ($state[$next] -eq 'Visiting') { + $cycle = @($trail.GetRange($trail.IndexOf($next), $trail.Count - $trail.IndexOf($next))) + $next + $key = (@($cycle | Select-Object -SkipLast 1 | Sort-Object) -join ' ') + if ($reported.Add($key)) { $problems.Add("$($steps[$next].File) ($next): the steps depend on each other in a cycle: $($cycle -join ' -> ').") } + } elseif (-not $state[$next]) { + & $visit $next $trail + } + } + $trail.RemoveAt($trail.Count - 1) + $state[$id] = 'Done' + } + foreach ($id in @($steps.Keys)) { if (-not $state[$id]) { & $visit $id ([System.Collections.Generic.List[string]]::new()) } } + + # A goal's steps: its step and every prerequisite at any depth, prerequisites first. The walk stops at a step + # it has seen, so a cycle (already reported) does not loop. + $inGoal = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::Ordinal) + foreach ($goal in $goals) { + if (-not $goal.Step) { continue } + if (-not $steps.ContainsKey($goal.Step)) { $problems.Add("goals.json ($($goal.Id)): Step names '$($goal.Step)', which is not in the catalogue."); continue } + $order = [System.Collections.Generic.List[string]]::new() + $seen = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::Ordinal) + $walk = $null + $walk = { + param($id) + if (-not $seen.Add($id)) { return } + foreach ($next in $edges[$id]) { & $walk $next } + $order.Add($id) + } + & $walk $goal.Step + $goal.Steps = $order.ToArray() + foreach ($id in $order) { $null = $inGoal.Add($id) } + } + foreach ($step in $steps.Values) { + if (-not $inGoal.Contains($step.Id)) { $problems.Add("$($step.File) ($($step.Id)): the step belongs to no goal. Make it a goal's step or a prerequisite of one.") } + } + if ($files.Count -gt 0 -and -not ($files | Where-Object Name -EQ 'goals.json')) { $problems.Add("goals.json: the catalogue has no goals file.") } + + $catalog = [pscustomobject]@{ + Path = $folder + Steps = $steps + Goals = $goals.ToArray() + Problems = $problems.ToArray() + } + if (-not $Path) { $script:__MtStepCatalog = $catalog } + $catalog +} diff --git a/powershell/internal/engine/Get-MtStepPrerequisite.ps1 b/powershell/internal/engine/Get-MtStepPrerequisite.ps1 new file mode 100644 index 0000000000..a93d501550 --- /dev/null +++ b/powershell/internal/engine/Get-MtStepPrerequisite.ps1 @@ -0,0 +1,44 @@ +function Get-MtStepPrerequisite { + <# + .SYNOPSIS + Returns the prerequisites of steps of the defender's path, at any depth. + + .DESCRIPTION + A prerequisite is a step that another step requires, requires one of, or recommends first + (docs/proposals/defenders-path.md, section 3). This follows those three relationships down every level from + -Step and returns each step it reaches once, in the order it reaches them. A step of -Step is returned only when + another step of -Step reaches it. Step IDs the catalogue does not have are ignored. + + Used by -IncludePrerequisites (section 8) and by the scope of a result's Steps (section 7.2). + #> + [CmdletBinding()] + [OutputType([string])] + param( + # The steps whose prerequisites are wanted. + [Parameter()] [AllowNull()] [AllowEmptyCollection()] [string[]] $Step = @(), + + # The step catalogue. Defaults to the module's. + [Parameter()] [object] $Catalog = (Get-MtStepCatalog) + ) + + $steps = $Catalog.Steps + $start = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::Ordinal) + foreach ($id in @($Step | Where-Object { $_ })) { $null = $start.Add(([string]$id).ToLowerInvariant()) } + $seen = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::Ordinal) + $queue = [System.Collections.Generic.Queue[string]]::new() + foreach ($id in $start) { if ($steps.ContainsKey($id)) { $queue.Enqueue($id) } } + $reached = [System.Collections.Generic.List[string]]::new() + $visited = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::Ordinal) + while ($queue.Count -gt 0) { + $id = $queue.Dequeue() + if (-not $visited.Add($id)) { continue } + $s = $steps[$id] + $next = @(@($s.Requires) + @($s.RequiresOneOf | ForEach-Object { $_ }) + @($s.RecommendedFirst) | Where-Object { $_ }) + foreach ($other in $next) { + if (-not $steps.ContainsKey($other)) { continue } + if ($seen.Add($other)) { $reached.Add($other) } + $queue.Enqueue($other) + } + } + foreach ($id in $reached) { $id } +} diff --git a/powershell/internal/engine/Get-MtStepProblem.ps1 b/powershell/internal/engine/Get-MtStepProblem.ps1 new file mode 100644 index 0000000000..b57bf1f9f1 --- /dev/null +++ b/powershell/internal/engine/Get-MtStepProblem.ps1 @@ -0,0 +1,96 @@ +function Get-MtStepProblem { + <# + .SYNOPSIS + Returns one message for each thing that is wrong with the step catalogue or with the steps that tests name. + + .DESCRIPTION + Used by the catalog build, which fails on any message, and by the unit tests (docs/proposals/defenders-path.md, + section 14). It returns: + + - the problems of the catalogue itself (Get-MtStepCatalog) and of the measure registry (Get-MtMeasureRegistry); + - a step whose Measure names a key the registry does not have, and a registry entry whose reader function the + module does not have; + - a test whose Step names a step the catalogue does not have; + - with -Coverage, when -Test is every built-in test: a step that no test names and that has no Measure but has + no Unchecked reason, and a step that a test names but still has one; + - too many sources that cite a maintainer instead of Microsoft Learn (more than one in ten). + + The build checks a test folder that may hold only some of the tests (a fixture, in the unit tests), so it leaves + out -Coverage; the unit tests pass it with the full set. + + A pack's tests name steps in its taxonomy.json (packs//taxonomy.json, Tests..Step), which -PackRoot + reads. Each message starts with the path of a file and names the step or the test. + #> + [CmdletBinding()] + [OutputType([string])] + param( + # The built-in tests (Get-MtNativeTestInventory). + [Parameter(Mandatory)] [AllowEmptyCollection()] [object[]] $Test, + + # The folder that holds the packs that ship with Maester. + [Parameter()] [string] $PackRoot, + + # The catalogue to check. Defaults to the module's. + [Parameter()] [object] $Catalog = (Get-MtStepCatalog), + + # The measure registry the catalogue's Measure keys refer to. Defaults to the module's. + [Parameter()] [object] $Registry = (Get-MtMeasureRegistry), + + # -Test is every built-in test: check that each step is named by a test or says in Unchecked why not. + [Parameter()] [switch] $Coverage + ) + + $Catalog.Problems + $Registry.Problems + foreach ($measure in $Registry.Measures.Values) { + if (-not (Get-Command -Name $measure.Function -CommandType Function -ErrorAction SilentlyContinue)) { + "$([System.IO.Path]::GetFileName($Registry.Path)) ($($measure.Key)): the reader function $($measure.Function) does not exist." + } + } + foreach ($step in $Catalog.Steps.Values) { + if ($step.Measure -and -not $Registry.Measures.ContainsKey($step.Measure.Key)) { + "$($step.File) ($($step.Id)): Measure names '$($step.Measure.Key)', which is not in the measure registry." + } + } + + # Which tests name each step. + $namedBy = @{} + $add = { param($step, $by) if (-not $namedBy.ContainsKey($step)) { $namedBy[$step] = [System.Collections.Generic.List[string]]::new() }; $namedBy[$step].Add($by) } + foreach ($t in $Test) { + if (-not $t.Id) { continue } + foreach ($step in @($t.PSObject.Properties['Step'] | ForEach-Object { $_.Value } | Where-Object { $_ })) { + if ($Catalog.Steps.ContainsKey($step)) { & $add $step $t.Id } + else { "$($t.File): the test $($t.Id) names the step '$step', which is not in the step catalogue." } + } + } + if ($PackRoot -and (Test-Path -LiteralPath $PackRoot -PathType Container)) { + foreach ($file in Get-ChildItem -LiteralPath $PackRoot -Filter 'taxonomy.json' -Recurse -File -Depth 1) { + try { $taxonomy = Get-Content -LiteralPath $file.FullName -Raw | ConvertFrom-Json -AsHashtable -ErrorAction Stop } catch { continue } + if ($taxonomy -isnot [System.Collections.IDictionary] -or $taxonomy['Tests'] -isnot [System.Collections.IDictionary]) { continue } + foreach ($id in $taxonomy['Tests'].Keys) { + $entry = $taxonomy['Tests'][$id] + if ($entry -isnot [System.Collections.IDictionary] -or -not $entry.Contains('Step')) { continue } + foreach ($step in @($entry['Step'] | Where-Object { $_ })) { + if ($Catalog.Steps.ContainsKey([string]$step)) { & $add ([string]$step) "$($file.Directory.Name):$id" } + else { "$($file.FullName): the test $id names the step '$step', which is not in the step catalogue." } + } + } + } + } + + $checked = if ($Coverage) { @($Catalog.Steps.Values) } else { @() } + foreach ($step in $checked) { + $where = "$($step.File) ($($step.Id))" + if ($namedBy.ContainsKey($step.Id) -and $step.Unchecked) { + "${where}: $($namedBy[$step.Id] -join ', ') verify the step, so it must not have Unchecked." + } elseif (-not $namedBy.ContainsKey($step.Id) -and -not $step.Measure -and -not $step.Unchecked) { + "${where}: no test names the step and it has no Measure. Name it in the Step attribute of the tests that verify it, give it a Measure, or say why neither can in Unchecked." + } + } + + $sources = @($Catalog.Steps.Values | ForEach-Object { $_.Sources }) + $maintainerOnly = @($sources | Where-Object { $_.Maintainer -and -not $_.Url }) + if ($sources.Count -ge 10 -and $maintainerOnly.Count * 10 -gt $sources.Count) { + "$($Catalog.Path): $($maintainerOnly.Count) of $($sources.Count) sources cite a maintainer instead of Microsoft Learn. Keep it to one in ten." + } +} diff --git a/powershell/internal/engine/Get-MtStepScope.ps1 b/powershell/internal/engine/Get-MtStepScope.ps1 new file mode 100644 index 0000000000..36689a62ea --- /dev/null +++ b/powershell/internal/engine/Get-MtStepScope.ps1 @@ -0,0 +1,48 @@ +function Get-MtStepScope { + <# + .SYNOPSIS + Returns the steps of the defender's path that a run's result covers: its scope. + + .DESCRIPTION + A step is in scope when a row that ran names it, or when it is a prerequisite, at any depth, of such a step + (docs/proposals/defenders-path.md, section 7.2). A row ran when its Result is anything but NotRun. The steps + that a step in scope declares in Conflicts are in scope too, without their own prerequisites, because a + conflicting step that is Done blocks it. Step IDs that the catalogue does not have are left out. + + Returns an object with Named (the steps the rows that ran name, in the order of the rows) and Steps (every step + in scope, in catalogue order). Both are empty when no row that ran names a step. + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param( + # Result rows, with Result and Step. + [Parameter()] [AllowNull()] [AllowEmptyCollection()] [object[]] $InputObject = @(), + + # The step catalogue. Defaults to the module's. + [Parameter()] [object] $Catalog = (Get-MtStepCatalog) + ) + + $steps = $Catalog.Steps + $named = [System.Collections.Generic.List[string]]::new() + foreach ($row in $InputObject) { + if ($null -eq $row -or [string]$row.Result -eq 'NotRun') { continue } + $property = $row.PSObject.Properties['Step'] + if (-not $property) { continue } + foreach ($id in @($property.Value | Where-Object { $_ })) { + $key = ([string]$id).ToLowerInvariant() + if ($steps.ContainsKey($key) -and -not $named.Contains($key)) { $named.Add($key) } + } + } + + $inScope = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::Ordinal) + foreach ($id in $named) { $null = $inScope.Add($id) } + foreach ($id in @(Get-MtStepPrerequisite -Step $named.ToArray() -Catalog $Catalog)) { $null = $inScope.Add($id) } + foreach ($id in @($inScope)) { + foreach ($other in @($steps[$id].Conflicts | Where-Object { $_ -and $steps.ContainsKey($_) })) { $null = $inScope.Add($other) } + } + + [pscustomobject]@{ + Named = $named.ToArray() + Steps = [string[]]@($steps.Keys | Where-Object { $inScope.Contains($_) }) + } +} diff --git a/powershell/internal/engine/Invoke-MtNativePlan.ps1 b/powershell/internal/engine/Invoke-MtNativePlan.ps1 index 2934b6ae0f..e7fbea131a 100644 --- a/powershell/internal/engine/Invoke-MtNativePlan.ps1 +++ b/powershell/internal/engine/Invoke-MtNativePlan.ps1 @@ -432,7 +432,7 @@ function ConvertTo-MtNativeRow { later), the 3.0 fields Source, Suite, Format, ReasonCode, ReasonDetail, ParentId, InstanceId, Parameters, Diagnostics and Package, and the test's attributes (test attribute design, section 3): Product (the key), RelatedProduct, Feature, Area, ResourceType, UserImpact, ImplementationCost, Mitre, Control, - Lifecycle, ReplacedBy, Service, License and Permission. An attribute the test does not declare is null + Lifecycle, ReplacedBy, Service, License, Permission and Step. An attribute the test does not declare is null or an empty list, never left out. Tag holds the tags the author wrote, plus the instance's own. Benchmark is the requirement of a published benchmark that the test implements: the first Control of the @@ -593,7 +593,7 @@ function Get-MtInstanceAttribute { Returns the attribute values a family instance sets for itself, checked against the taxonomy. .DESCRIPTION - An instance may set Product, RelatedProduct, Feature, Area, UserImpact, ImplementationCost and Mitre. Only + An instance may set Product, RelatedProduct, Feature, Area, UserImpact, ImplementationCost, Mitre and Step. Only values the taxonomy knows are returned: a product key or alias (as its key), a feature of that product, an area key, Low, Medium or High, and ATT&CK techniques of the pinned release. A value that does not pass is left out, so the row keeps its family's value. A Feature is checked against the instance's Product when it sets @@ -643,6 +643,12 @@ function Get-MtInstanceAttribute { if ($value -in 'Low', 'Medium', 'High') { $values[$name] = (Get-Culture).TextInfo.ToTitleCase($value.ToLowerInvariant()) } } + # Step: the steps of the defender's path the instance verifies, in lowercase, at most three. A step the catalogue + # doesn't have stays on the row and is left out of the result's Steps. + $step = @(@(Get-MtInstanceValue -Instance $Instance -Name 'Step') | Where-Object { $_ } | ForEach-Object { ([string]$_).ToLowerInvariant() } | + Where-Object { $_.Length -le 80 -and $_ -cmatch '^[a-z0-9][a-z0-9-]*\.[a-z0-9][a-z0-9-]*$' } | Select-Object -Unique) + if ($step.Count) { $values.Step = [string[]]@($step | Select-Object -First 3) } + $mitre = @(@(Get-MtInstanceValue -Instance $Instance -Name 'Mitre') | Where-Object { $_ } | ForEach-Object { [string]$_ }) if ($mitre.Count) { $techniques = @($mitre | Where-Object { $_ -ne 'None' -and -not (Get-MtAttackTechniqueProblem -Mitre $_) } | Select-Object -Unique) @@ -694,7 +700,8 @@ function Get-MtRowAttribute { .DESCRIPTION RelatedProduct, Feature, Area, ResourceType, UserImpact, ImplementationCost, Mitre, Control, Lifecycle, - ReplacedBy, Service, License and Permission, in that order, then Benchmark (test attribute design, + ReplacedBy, Service, License, Permission and Step (the steps of the defender's path it verifies), in that order, + then Benchmark (test attribute design, section 6), which is null unless a Control of the test names a requirement of a framework. Without -Test every field is null, which is what a Pester-format row carries. #> @@ -705,10 +712,10 @@ function Get-MtRowAttribute { ) $fields = [ordered]@{} - foreach ($name in 'RelatedProduct', 'Feature', 'Area', 'ResourceType', 'UserImpact', 'ImplementationCost', 'Mitre', 'Control', 'Lifecycle', 'ReplacedBy', 'Service', 'License', 'Permission') { + foreach ($name in 'RelatedProduct', 'Feature', 'Area', 'ResourceType', 'UserImpact', 'ImplementationCost', 'Mitre', 'Control', 'Lifecycle', 'ReplacedBy', 'Service', 'License', 'Permission', 'Step') { if (-not $Test) { $fields[$name] = $null; continue } $property = $Test.PSObject.Properties[$name] - $fields[$name] = if ($name -in 'RelatedProduct', 'Mitre', 'Control', 'Service', 'License', 'Permission') { + $fields[$name] = if ($name -in 'RelatedProduct', 'Mitre', 'Control', 'Service', 'License', 'Permission', 'Step') { , [string[]]@($(if ($property) { $property.Value }) | Where-Object { $_ }) } elseif ($property -and $property.Value) { [string]$property.Value } else { $null } } diff --git a/powershell/internal/engine/Invoke-MtStepMeasure.ps1 b/powershell/internal/engine/Invoke-MtStepMeasure.ps1 new file mode 100644 index 0000000000..4977ca5453 --- /dev/null +++ b/powershell/internal/engine/Invoke-MtStepMeasure.ps1 @@ -0,0 +1,104 @@ +function Invoke-MtStepMeasure { + <# + .SYNOPSIS + Reads the measures of the defender's path steps that a run covers, after its tests. + + .DESCRIPTION + A measure is a figure the engine reads from Graph for a step that is a state of the tenant + (docs/proposals/defenders-path.md, section 11). Measures are not selected: after the tests, the engine reads the + measure of every step in scope (Get-MtStepScope), so a run of one test still shows the figures of its + prerequisites. Each measure is read once, even when several steps name it. + + A measure is gated like a test: every Service must be connected, the tenant must have one of the License plans + when its licences are known, and when the Graph connection lists its permissions, each Permission element must + have an alternative it holds (a Graph:Scope permission the connection has, or its ReadWrite form; other kinds + can't be checked and count as held). A measure whose gate fails isn't read and carries the reason code a test + would: ServiceNotConnected, LicenseNotFound, or PermissionNotGranted. A reader that throws gives MeasureError, + or PermissionNotGranted when Graph answered 403. Readers go through the session cache like the checks. + + The readers may add object facts with Add-MtAffectedObjectFact, so call this while the run collects affected + objects. + + Returns a hashtable of measure key to the raw reading: Key, Count, Total, Objects (all the objects that fall + short, as the reader returned them), ReadAt (ISO 8601 UTC), ReasonCode and ReasonDetail. Count, Total and Objects + are $null and ReasonCode set when the measure could not be read. Returns an empty hashtable when no step in scope + has a measure, or when -Disabled. + #> + [CmdletBinding()] + [OutputType([hashtable])] + param( + # The result rows of the run, with Result and Step. + [Parameter()] [AllowNull()] [AllowEmptyCollection()] [object[]] $InputObject = @(), + + # The tenant context of the run: connected services, licences and the permissions of the Graph connection. + [Parameter()] [AllowNull()] [object] $TenantContext, + + # The run config turned measures off (Measures.Enabled = false). + [Parameter()] [switch] $Disabled, + + # The step catalogue. Defaults to the module's. + [Parameter()] [object] $Catalog = (Get-MtStepCatalog), + + # The measure registry. Defaults to the module's. + [Parameter()] [object] $Registry = (Get-MtMeasureRegistry) + ) + + $readings = @{} + if ($Disabled) { return $readings } + $scope = Get-MtStepScope -InputObject $InputObject -Catalog $Catalog + $keys = [System.Collections.Generic.List[string]]::new() + foreach ($id in $scope.Steps) { + $measure = $Catalog.Steps[$id].Measure + if ($measure -and -not $keys.Contains($measure.Key)) { $keys.Add($measure.Key) } + } + + $enforce = @{ Service = $true; License = $true; TenantType = $false; Cloud = $false } + $scopes = @(if ($TenantContext -and $TenantContext.PSObject.Properties['Scopes']) { $TenantContext.Scopes | Where-Object { $_ } }) + foreach ($key in $keys) { + $reading = [pscustomobject][ordered]@{ Key = $key; Count = $null; Total = $null; Objects = $null; ReadAt = $null; ReasonCode = $null; ReasonDetail = $null } + $readings[$key] = $reading + $entry = $null + if (-not $Registry.Measures.TryGetValue($key, [ref] $entry)) { + $reading.ReasonCode = 'MeasureError'; $reading.ReasonDetail = "The measure registry has no measure '$key'." + continue + } + + # The gates of a test: services, then licences. + $gate = Test-MtApplicability -Test ([pscustomobject]@{ Platform = @(); TenantType = @(); Cloud = @(); UnregisteredServices = @(); Service = $entry.Service; License = $entry.License }) -TenantContext $TenantContext -Enforce $enforce + if ($gate) { $reading.ReasonCode = $gate.ReasonCode; $reading.ReasonDetail = $gate.ReasonDetail; continue } + + # Permissions, when the Graph connection lists the ones it holds. + if ($scopes.Count -gt 0) { + $missing = foreach ($element in $entry.Permission) { + $held = $false + foreach ($alternative in @(ConvertFrom-MtPermission -Value $element)) { + if ($alternative.Service -ne 'Graph' -or $alternative.Kind -ne 'Scope') { $held = $true; break } + $readWrite = $alternative.Name -replace '\.Read\.', '.ReadWrite.' + if ($scopes | Where-Object { $_ -eq $alternative.Name -or $_ -eq $readWrite }) { $held = $true; break } + } + if (-not $held) { $element } + } + if (@($missing).Count -gt 0) { + $reading.ReasonCode = 'PermissionNotGranted' + $reading.ReasonDetail = "The Graph connection lacks a permission this figure needs: $(@($missing) -join '; ')." + continue + } + } + + try { + Write-Verbose "Reading the measure $key with $($entry.Function)." + $value = & $entry.Function -ErrorAction Stop + $reading.Count = [int]$value.Count + $reading.Total = [int]$value.Total + $reading.Objects = @($value.Objects | Where-Object { $null -ne $_ }) + } catch { + $message = Get-MtFirstLine $_.Exception.Message + $forbidden = $_.Exception.Message -match '\b403\b|Forbidden|Authorization_RequestDenied' + $reading.ReasonCode = if ($forbidden) { 'PermissionNotGranted' } else { 'MeasureError' } + $reading.ReasonDetail = $message + Write-Verbose "The measure $key could not be read: $message" + } + $reading.ReadAt = [datetime]::UtcNow.ToString('yyyy-MM-ddTHH:mm:ssZ', [cultureinfo]::InvariantCulture) + } + $readings +} diff --git a/powershell/internal/engine/Merge-MtPartitionResult.ps1 b/powershell/internal/engine/Merge-MtPartitionResult.ps1 index 69ce47098e..e40dfe0e2b 100644 --- a/powershell/internal/engine/Merge-MtPartitionResult.ps1 +++ b/powershell/internal/engine/Merge-MtPartitionResult.ps1 @@ -102,6 +102,29 @@ function Merge-MtPartitionResult { if ($merged.Contains('Frameworks')) { $merged.Frameworks = @(Get-MtResultFramework -InputObject $rows) } $packs = @($Results | ForEach-Object { if ($_.PSObject.Properties['Packs']) { $_.Packs } } | Where-Object { $_ } | Group-Object -Property Id | ForEach-Object { $_.Group[0] }) if ($packs.Count -gt 0) { $merged.Packs = $packs } + # The defender's path, ordered for the run as a whole: the measures each part read are reused (the first part + # that read a measure wins), and a step that is still Not checked keeps the Earlier status a part found. + $merged.Remove('Steps'); $merged.Remove('Goals') + $partSteps = @($Results | ForEach-Object { if ($_.PSObject.Properties['Steps']) { $_.Steps } } | Where-Object { $_ }) + $measures = @{} + foreach ($s in $partSteps) { + $m = if ($s.PSObject.Properties['Measure']) { $s.Measure } else { $null } + if (-not $m -or -not $m.Key) { continue } + $read = -not $m.ReasonCode + if ($measures.ContainsKey([string]$m.Key) -and ($null -eq $measures[[string]$m.Key].ReasonCode -or -not $read)) { continue } + $measures[[string]$m.Key] = [pscustomobject]@{ Count = $m.Count; Total = $m.Total; Objects = @($m.Objects); ObjectCount = $m.ObjectCount; ReadAt = $m.ReadAt; ReasonCode = $m.ReasonCode } + } + $measureSetting = Get-MtMeasureSetting -RunConfig $(if ($first.PSObject.Properties['MaesterConfig']) { $first.MaesterConfig } else { $null }) + $tenantContext = if ($first.PSObject.Properties['TenantContext']) { $first.TenantContext } else { $null } + $mergedSteps = Get-MtResultStep -InputObject $rows -Measure $measures -MeasuresDisabled:(-not $measureSetting.Enabled) -MinimumShare $measureSetting.MinimumShare -TenantContext $tenantContext + if ($mergedSteps) { + foreach ($s in @($mergedSteps.Steps | Where-Object { $_.Status -eq 'NotChecked' })) { + $earlier = $partSteps | Where-Object { $_.Id -eq $s.Id -and $_.PSObject.Properties['Earlier'] -and $_.Earlier } | Select-Object -First 1 + if ($earlier) { $s.Earlier = $earlier.Earlier } + } + $merged.Steps = @($mergedSteps.Steps) + $merged.Goals = @($mergedSteps.Goals) + } # A part's previous result may be another part of an earlier run, which holds only some of the tests. $merged.Remove('Previous') $merged.Partitions = @($partitions) diff --git a/powershell/internal/engine/Read-MtNativeTest.ps1 b/powershell/internal/engine/Read-MtNativeTest.ps1 index d62ee68d4e..93b17c184e 100644 --- a/powershell/internal/engine/Read-MtNativeTest.ps1 +++ b/powershell/internal/engine/Read-MtNativeTest.ps1 @@ -51,6 +51,7 @@ function Read-MtNativeTest { ImplementationCost = $null Mitre = @() Control = @() + Step = @() Service = @() License = @() Permission = @() @@ -280,6 +281,13 @@ function Read-MtNativeTest { } # Control: the framework key is lowercase. $test.Control = @($test.Control | ForEach-Object { $parts = $_ -split ':', 2; if ($parts.Count -eq 2) { "$($parts[0].ToLowerInvariant()):$($parts[1])" } else { $_ } }) + # Step: the steps of the defender's path the test verifies (docs/proposals/defenders-path.md, section 5), stored in + # lowercase like the catalogue's IDs. Whether a step exists in the catalogue is checked by the build and the + # inventory, not here. + $test.Step = @($test.Step | ForEach-Object { $_.ToLowerInvariant() } | Select-Object -Unique) + if ($test.Step.Count -gt 3) { + & $addError 'InvalidMetadata' "Property 'Step' names $($test.Step.Count) steps. A test verifies at most three; a test that checks more is several tests." $attributeLine + } foreach ($name in $schema.Properties.Keys) { $definition = $schema.Properties[$name] diff --git a/powershell/internal/engine/Resolve-MtNativePlan.ps1 b/powershell/internal/engine/Resolve-MtNativePlan.ps1 index 47b0347339..e932ac5c30 100644 --- a/powershell/internal/engine/Resolve-MtNativePlan.ps1 +++ b/powershell/internal/engine/Resolve-MtNativePlan.ps1 @@ -15,7 +15,14 @@ function Resolve-MtNativePlan { Each plan row has: Test, Disposition (Run, NotRun, Skipped or Error), ReasonCode, ReasonDetail, LegacySkipCode, Parameters (the bound hashtable), EffectiveParameters, TimeoutSeconds, Setting (the - TestSettings row), InstancePatterns (for a family selected by instance ID) and ExactlyNamed. + TestSettings row), InstancePatterns (for a family selected by instance ID), ExactlyNamed and Prerequisite. + + -PrerequisiteStep is the second pass of -IncludePrerequisites (docs/proposals/defenders-path.md, section 8): a test + that names one of these steps is selected even if -TestId, the typed selectors or -Tag leave it out, and runs + like a test named by its exact ID, so its Preview and LongRunning exclusions are lifted. A long-running family + (the Zero Trust Assessment) is the exception: it still needs -IncludeLongRunning or its suite named in -Suite. + The exclusions (-ExcludeTestId, -ExcludeProduct, -ExcludeTag, a disabled or unlisted test) still apply. + Prerequisite is true on the rows it selected. #> [CmdletBinding()] [OutputType([pscustomobject])] @@ -31,6 +38,8 @@ function Resolve-MtNativePlan { [Parameter()] [string[]] $AutoExcludedTag = @(), # Parameter values that win over the config (Invoke-MtTest -Parameter), by test ID. [Parameter()] [hashtable] $ParameterOverride = @{}, + # The prerequisite steps of the steps the selected tests name (-IncludePrerequisites). + [Parameter()] [AllowEmptyCollection()] [string[]] $PrerequisiteStep = @(), [Parameter()] [switch] $DryRun ) @@ -59,6 +68,7 @@ function Resolve-MtNativePlan { foreach ($tag in $tags.Legacy) { if ($tag -like $pattern) { return 'Legacy' } } } $legacyTagUsed = [ordered]@{} + $prerequisites = [System.Collections.Generic.HashSet[string]]::new([string[]]@($PrerequisiteStep | Where-Object { $_ } | ForEach-Object { $_.ToLowerInvariant() }), [System.StringComparer]::Ordinal) foreach ($t in $Test) { $row = [ordered]@{ @@ -73,6 +83,7 @@ function Resolve-MtNativePlan { Setting = $null InstancePatterns = @() ExactlyNamed = $false + Prerequisite = $false } $set = { param($disposition, $code, $detail, $legacy) $row.Disposition = $disposition; $row.ReasonCode = $code; $row.ReasonDetail = $detail; $row.LegacySkipCode = $legacy } @@ -91,6 +102,8 @@ function Resolve-MtNativePlan { } $isFamily = [bool]$t.InstanceSource + # Reached by -IncludePrerequisites: the include selectors don't apply. + $viaPrerequisite = $prerequisites.Count -gt 0 -and [bool](@($t.Step) | Where-Object { $_ -and $prerequisites.Contains(([string]$_).ToLowerInvariant()) }) $setting = Get-MtTestSetting -RunConfig $RunConfig -Id $t.Id $row.Setting = $setting @@ -118,7 +131,7 @@ function Resolve-MtNativePlan { & $set 'NotRun' 'ExcludedByProduct' "Excluded by product ($($excludedBy -join ', '))." [pscustomobject]$row; continue } - if ($Selection.TestId.Count -gt 0) { + if ($Selection.TestId.Count -gt 0 -and -not $viaPrerequisite) { $includedBy = @(Test-MtIdMatch -Id $t.Id -Pattern $Selection.TestId) if (-not $includedBy -and $isFamily) { $instancePatterns = @($Selection.TestId | Where-Object { $_ -like "$($t.Id).*" -and -not ($_.Contains('*') -and "$($t.Id).*" -like $_) }) @@ -133,10 +146,10 @@ function Resolve-MtNativePlan { $row.ExactlyNamed = [bool]($includedBy | Where-Object { -not $_.Contains('*') }) } - # Typed selectors: Product (or RelatedProduct), Feature, Area, the effective severity and Suite. - if ($selectorInUse) { + # Typed selectors: Product (or RelatedProduct), Feature, Area, the effective severity, Suite and Step. + if ($selectorInUse -and -not $viaPrerequisite) { $severity = if ($setting -and $setting.PSObject.Properties['Severity'] -and $setting.Severity) { [string]$setting.Severity } else { [string]$t.Severity } - $miss = Test-MtSelectorMatch -Selection $Selection -Product (@($t.Product) + @($t.RelatedProduct)) -Feature $t.Feature -Area $t.Area -Severity $severity -Suite $t.Suite + $miss = Test-MtSelectorMatch -Selection $Selection -Product (@($t.Product) + @($t.RelatedProduct)) -Feature $t.Feature -Area $t.Area -Severity $severity -Suite $t.Suite -Step @($t.Step) if ($miss) { & $set 'NotRun' 'NotSelected' "Not selected by -$($miss.Selector) ($($miss.Value -join ', '))." [pscustomobject]$row; continue @@ -150,10 +163,17 @@ function Resolve-MtNativePlan { # long-running tests run too. if ($t.PSObject.Properties['PackSelected'] -and $t.PackSelected) { $row.ExactlyNamed = $true } + # A prerequisite runs as if named by its exact ID, except a long-running family, which runs the whole + # assessment: it still needs -IncludeLongRunning (or its suite named, above). + if ($viaPrerequisite) { + $row.Prerequisite = $true + if (-not ($isFamily -and $t.LongRunning)) { $row.ExactlyNamed = $true } + } + # Selection by tag: the tags of the test and its suite and, for a built-in test, its ID and its # Maester 2.x tags (section 5.1). A pattern that only a 2.x tag answers is noted for the warning below. $tags = if ($IncludeTag.Count -gt 0 -or $userExcludeTag.Count -gt 0) { Get-MtSelectionTag -Test $t } else { $null } - $included = $IncludeTag.Count -eq 0 + $included = $IncludeTag.Count -eq 0 -or $viaPrerequisite if (-not $included) { foreach ($pattern in $IncludeTag) { $via = & $matchTag $tags $pattern diff --git a/powershell/internal/engine/Resolve-MtRunConfig.ps1 b/powershell/internal/engine/Resolve-MtRunConfig.ps1 index 1b2957bcc6..6c6c682b9d 100644 --- a/powershell/internal/engine/Resolve-MtRunConfig.ps1 +++ b/powershell/internal/engine/Resolve-MtRunConfig.ps1 @@ -272,6 +272,25 @@ function Complete-MtRunConfig { if ($Config.Selection.OnUnknownId -notin 'Warn', 'Ignore', 'Error') { throw "Selection.OnUnknownId must be 'Warn', 'Ignore' or 'Error', not '$($Config.Selection.OnUnknownId)'." } + # Selection.Step and Selection.IncludePrerequisites (the defender's path) are read only when set. + if ($Config.Selection.PSObject.Properties['Step'] -and $null -ne $Config.Selection.Step) { + $Config.Selection.Step = @($Config.Selection.Step | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }) + } + # Measures: Enabled is a bool, and each MinimumShare a whole number from 1 to 100. + if ($Config.PSObject.Properties['Measures'] -and $null -ne $Config.Measures) { + $measures = $Config.Measures + if ($measures.PSObject.Properties['Enabled'] -and $null -ne $measures.Enabled -and $measures.Enabled -isnot [bool]) { + throw "Measures.Enabled must be true or false, not '$($measures.Enabled)'." + } + $shares = if ($measures.PSObject.Properties['MinimumShare']) { $measures.MinimumShare } else { $null } + $pairs = if ($shares -is [System.Collections.IDictionary]) { @($shares.GetEnumerator() | ForEach-Object { [pscustomobject]@{ Name = [string]$_.Key; Value = $_.Value } }) } + elseif ($shares) { @($shares.PSObject.Properties | ForEach-Object { [pscustomobject]@{ Name = $_.Name; Value = $_.Value } }) } + else { @() } + foreach ($pair in $pairs) { + $valid = ($pair.Value -is [int] -or $pair.Value -is [long]) -and $pair.Value -ge 1 -and $pair.Value -le 100 + if (-not $valid) { throw "Measures.MinimumShare.$($pair.Name) must be a whole number from 1 to 100, not '$($pair.Value)'." } + } + } $Config | Add-Member -MemberType NoteProperty -Name 'ConfigSource' -Value $ConfigSource -Force diff --git a/powershell/internal/engine/Resolve-MtSelection.ps1 b/powershell/internal/engine/Resolve-MtSelection.ps1 index a5d74e5b56..54fda24b1c 100644 --- a/powershell/internal/engine/Resolve-MtSelection.ps1 +++ b/powershell/internal/engine/Resolve-MtSelection.ps1 @@ -4,7 +4,7 @@ function Resolve-MtSelection { Combines the run config's Selection section with the Invoke-Maester parameters (design section 7.3). .DESCRIPTION - -Tag, -TestId and the typed selectors (-Product, -Feature, -Area, -Severity, -Suite) replace the config + -Tag, -TestId and the typed selectors (-Product, -Feature, -Area, -Severity, -Suite, -Step) replace the config lists, and so does -Pack; -ExcludeTag, -ExcludeTestId and -ExcludeProduct add to them; the include switches are true when either source sets them. A product named by an alias, such as Entra ID, becomes its key, in -Product and -ExcludeProduct alike. @@ -29,8 +29,10 @@ function Resolve-MtSelection { [Parameter()] [string[]] $Severity, [Parameter()] [string[]] $Suite, [Parameter()] [string[]] $Pack, + [Parameter()] [string[]] $Step, [Parameter()] [switch] $IncludePreview, - [Parameter()] [switch] $IncludeLongRunning + [Parameter()] [switch] $IncludeLongRunning, + [Parameter()] [switch] $IncludePrerequisites ) $s = $RunConfig.Selection @@ -52,22 +54,25 @@ function Resolve-MtSelection { if (-not [string]::IsNullOrWhiteSpace($item)) { & $productKey ([string]$item) } } [pscustomobject]@{ - Tag = @(if ($Tag) { $Tag } else { $s.Tag }) - ExcludeTag = @(@($s.ExcludeTag) + @($ExcludeTag) | Where-Object { $_ } | Select-Object -Unique) - TestId = @(if ($TestId) { $TestId } else { $s.TestId }) - ExcludeTestId = @(@($s.ExcludeTestId) + @($ExcludeTestId) | Where-Object { $_ } | Select-Object -Unique) - Product = [string[]]@($products) - ExcludeProduct = [string[]]@($excludeProducts | Select-Object -Unique) - Feature = [string[]]@(& $selector $Feature 'Feature') - Area = [string[]]@(& $selector $Area 'Area') - Severity = [string[]]@(& $selector $Severity 'Severity') - Suite = [string[]]@(& $selector $Suite 'Suite') - Pack = [string[]]@(& $selector $Pack 'Pack') - IncludePreview = $IncludePreview.IsPresent -or [bool]$s.IncludePreview - IncludeLongRunning = $IncludeLongRunning.IsPresent -or [bool]$s.IncludeLongRunning - DefaultAction = $s.DefaultAction - OnUnknownId = $s.OnUnknownId - BuiltIn = $s.BuiltIn + Tag = @(if ($Tag) { $Tag } else { $s.Tag }) + ExcludeTag = @(@($s.ExcludeTag) + @($ExcludeTag) | Where-Object { $_ } | Select-Object -Unique) + TestId = @(if ($TestId) { $TestId } else { $s.TestId }) + ExcludeTestId = @(@($s.ExcludeTestId) + @($ExcludeTestId) | Where-Object { $_ } | Select-Object -Unique) + Product = [string[]]@($products) + ExcludeProduct = [string[]]@($excludeProducts | Select-Object -Unique) + Feature = [string[]]@(& $selector $Feature 'Feature') + Area = [string[]]@(& $selector $Area 'Area') + Severity = [string[]]@(& $selector $Severity 'Severity') + Suite = [string[]]@(& $selector $Suite 'Suite') + Pack = [string[]]@(& $selector $Pack 'Pack') + # Steps of the defender's path are stored in lowercase. + Step = [string[]]@(& $selector $Step 'Step' | ForEach-Object { $_.ToLowerInvariant() }) + IncludePreview = $IncludePreview.IsPresent -or [bool]$s.IncludePreview + IncludeLongRunning = $IncludeLongRunning.IsPresent -or [bool]$s.IncludeLongRunning + IncludePrerequisites = $IncludePrerequisites.IsPresent -or ($s.PSObject.Properties['IncludePrerequisites'] -and [bool]$s.IncludePrerequisites) + DefaultAction = $s.DefaultAction + OnUnknownId = $s.OnUnknownId + BuiltIn = $s.BuiltIn } } @@ -77,11 +82,13 @@ function Test-MtSelectorMatch { Checks a test against the typed selectors of a run and returns the first selector it does not match, or $null. .DESCRIPTION - The typed selectors are Product, Feature, Area, Severity and Suite (test attribute design, section 4). + The typed selectors are Product, Feature, Area, Severity, Suite (test attribute design, section 4) and Step + (the steps of the defender's path a test verifies). The values of one selector are alternatives, with '*' wildcards as for tags; different selectors must all match. Product matches the test's Product or any of its RelatedProduct values. A test that has no value for a selector in use does not match it, which is how a Pester-format test, which has no Product, - Feature or Area, is left out of a run that selects by one of them. + Feature, Area or Step, is left out of a run that selects by one of them. Step, like Product, takes a list: a test + matches when any of its steps does. Returns an object with Selector (the name) and Value (the selector's values), or nothing when the test matches every selector in use. @@ -95,10 +102,11 @@ function Test-MtSelectorMatch { [Parameter()] [AllowNull()] [AllowEmptyString()] [string] $Feature, [Parameter()] [AllowNull()] [AllowEmptyString()] [string] $Area, [Parameter()] [AllowNull()] [AllowEmptyString()] [string] $Severity, - [Parameter()] [AllowNull()] [AllowEmptyString()] [string] $Suite + [Parameter()] [AllowNull()] [AllowEmptyString()] [string] $Suite, + [Parameter()] [AllowNull()] [AllowEmptyCollection()] [string[]] $Step ) - $values = [ordered]@{ Product = @($Product); Feature = @($Feature); Area = @($Area); Severity = @($Severity); Suite = @($Suite) } + $values = [ordered]@{ Product = @($Product); Feature = @($Feature); Area = @($Area); Severity = @($Severity); Suite = @($Suite); Step = @($Step) } foreach ($name in $values.Keys) { if (-not $Selection.PSObject.Properties[$name]) { continue } $patterns = @($Selection.$name | Where-Object { $_ }) @@ -115,14 +123,14 @@ function Test-MtSelectorMatch { function Test-MtSelectorInUse { <# .SYNOPSIS - True when a run selects by Product, Feature, Area, Severity or Suite. + True when a run selects by Product, Feature, Area, Severity, Suite or Step. #> [CmdletBinding()] [OutputType([bool])] param( [Parameter(Mandatory)] [pscustomobject] $Selection ) - foreach ($name in 'Product', 'Feature', 'Area', 'Severity', 'Suite') { + foreach ($name in 'Product', 'Feature', 'Area', 'Severity', 'Suite', 'Step') { if ($Selection.PSObject.Properties[$name] -and @($Selection.$name | Where-Object { $_ }).Count -gt 0) { return $true } } $false diff --git a/powershell/internal/engine/completion/ConvertTo-MtCompletionTest.ps1 b/powershell/internal/engine/completion/ConvertTo-MtCompletionTest.ps1 index 552764bc9c..e7250493db 100644 --- a/powershell/internal/engine/completion/ConvertTo-MtCompletionTest.ps1 +++ b/powershell/internal/engine/completion/ConvertTo-MtCompletionTest.ps1 @@ -4,7 +4,7 @@ Keeps what Tab completion uses of test rows: the catalogue, a custom test inventory or a pack's test list. .DESCRIPTION - Each row has Id, Title, Product, RelatedProduct, Feature, Area, Severity, Suite, Control (the references and + Each row has Id, Title, Product, RelatedProduct, Feature, Area, Severity, Suite, Step, Control (the references and the requirement IDs alone, so MS.AAD.3.1 finds the test mapped to cisa-scuba:MS.AAD.3.1), Lifecycle, LongRunning, IsFamily, Tags (what -Tag matches, without the test's ID: its own tags, its suite's and, for a built-in test, its Maester 2.x tags), Source (BuiltIn, Custom or Pack), Pack, SortKey (the ID with its @@ -47,6 +47,7 @@ Area = [string]$t.Area Severity = [string]$t.Severity Suite = [string]$t.Suite + Step = [string[]]@($t.Step | Where-Object { $_ }) Control = $control.ToArray() Lifecycle = [string]$t.Lifecycle LongRunning = [bool]$t.LongRunning diff --git a/powershell/internal/engine/completion/Get-MtArgumentCompleterTable.ps1 b/powershell/internal/engine/completion/Get-MtArgumentCompleterTable.ps1 index b4516ae360..051e4dd60b 100644 --- a/powershell/internal/engine/completion/Get-MtArgumentCompleterTable.ps1 +++ b/powershell/internal/engine/completion/Get-MtArgumentCompleterTable.ps1 @@ -27,6 +27,7 @@ & $row 'Invoke-Maester' 'Area' 'Area' & $row 'Invoke-Maester' 'Severity' 'Severity' & $row 'Invoke-Maester' 'Suite' 'Suite' + & $row 'Invoke-Maester' 'Step' 'Step' & $row 'Invoke-Maester' 'Tag' 'Tag' & $row 'Invoke-Maester' 'ExcludeTag' 'Tag' & $row 'Invoke-Maester' 'TestId' 'TestId' @@ -39,6 +40,7 @@ & $row 'Get-MtTest' 'Area' 'Area' & $row 'Get-MtTest' 'Severity' 'Severity' & $row 'Get-MtTest' 'Suite' 'Suite' + & $row 'Get-MtTest' 'Step' 'Step' & $row 'Invoke-MtTest' 'Id' 'TestId' # Writing a test: the keys the taxonomy allows, whatever tests exist. diff --git a/powershell/internal/engine/completion/Get-MtCompletionCandidate.ps1 b/powershell/internal/engine/completion/Get-MtCompletionCandidate.ps1 index 6edf5beefe..716afe4556 100644 --- a/powershell/internal/engine/completion/Get-MtCompletionCandidate.ps1 +++ b/powershell/internal/engine/completion/Get-MtCompletionCandidate.ps1 @@ -13,7 +13,9 @@ are listed, since selectors combine with AND; otherwise every key the taxonomy has is listed. The tooltip gives the number of tests. The Taxonomy* kinds list the taxonomy's keys alone, for writing a test. - Kinds: Product, TaxonomyProduct, Feature, TaxonomyFeature, Area, TaxonomyArea, Severity, Suite, Tag, TestId, + Step lists the steps of the defender's path that the tests name, with each step's title. + + Kinds: Product, TaxonomyProduct, Feature, TaxonomyFeature, Area, TaxonomyArea, Severity, Suite, Step, Tag, TestId, Pack, PackId, InstalledPackId, Service, TestService, ResourceType, Mitre, Setting and Role. #> [CmdletBinding()] @@ -176,6 +178,19 @@ } } + 'Step' { + $steps = (Get-MtStepCatalog).Steps + $set = & $testSet + $counts = & $tally $set.Tests { param($t) $t.Step } + $order = 0 + foreach ($key in ($counts.Keys | Sort-Object)) { + $step = $null + $title = if ($steps.TryGetValue($key, [ref] $step)) { $step.Title } else { $null } + $tip = @($(if ($title) { $title } else { 'A step the step catalogue does not have.' })) + @(& $countText $counts[$key] $set.Narrowed) + & $candidate $key (++$order) ($tip -join "`n") $null @($(if ($title) { $title })) + } + } + 'Tag' { $replacement = (Get-MtLegacyTagTable).Replacement $set = & $testSet diff --git a/powershell/internal/engine/completion/Get-MtCompletionTestSet.ps1 b/powershell/internal/engine/completion/Get-MtCompletionTestSet.ps1 index 9395daa8bf..5480d94d68 100644 --- a/powershell/internal/engine/completion/Get-MtCompletionTestSet.ps1 +++ b/powershell/internal/engine/completion/Get-MtCompletionTestSet.ps1 @@ -57,14 +57,14 @@ } $idName = if ($CommandName -eq 'Invoke-Maester') { 'TestId' } else { 'Id' } - $selectorNames = @('Product', 'ExcludeProduct', 'Feature', 'Area', 'Severity', 'Suite', 'Tag', 'ExcludeTag', $idName, 'ExcludeTestId') + $selectorNames = @('Product', 'ExcludeProduct', 'Feature', 'Area', 'Severity', 'Suite', 'Step', 'Tag', 'ExcludeTag', $idName, 'ExcludeTestId') $narrowed = @($selectorNames | Where-Object { @(& $strings $_).Count -gt 0 }).Count -gt 0 if (-not $narrowed) { return [pscustomobject]@{ Tests = $tests.ToArray(); Narrowed = $false } } # Resolve-MtSelection turns product aliases into keys. The matching below is that of Test-MtSelectorMatch, # Test-MtProductExcluded and Test-MtIdMatch, written as plain loops: they run for every test on each Tab. - $selection = Resolve-MtSelection -RunConfig ([pscustomobject]@{ Selection = [pscustomobject]@{} }) -Product @(& $strings 'Product') -ExcludeProduct @(& $strings 'ExcludeProduct') -Feature @(& $strings 'Feature') -Area @(& $strings 'Area') -Severity @(& $strings 'Severity') -Suite @(& $strings 'Suite') - $selectors = @(foreach ($name in 'Product', 'Feature', 'Area', 'Severity', 'Suite') { + $selection = Resolve-MtSelection -RunConfig ([pscustomobject]@{ Selection = [pscustomobject]@{} }) -Product @(& $strings 'Product') -ExcludeProduct @(& $strings 'ExcludeProduct') -Feature @(& $strings 'Feature') -Area @(& $strings 'Area') -Severity @(& $strings 'Severity') -Suite @(& $strings 'Suite') -Step @(& $strings 'Step') + $selectors = @(foreach ($name in 'Product', 'Feature', 'Area', 'Severity', 'Suite', 'Step') { $patterns = @($selection.$name | Where-Object { $_ }) if ($patterns.Count -gt 0) { [pscustomobject]@{ Name = $name; Patterns = $patterns } } }) diff --git a/powershell/internal/report/ConvertTo-MtMaesterResult.ps1 b/powershell/internal/report/ConvertTo-MtMaesterResult.ps1 index f04e8cdc0a..04db115225 100644 --- a/powershell/internal/report/ConvertTo-MtMaesterResult.ps1 +++ b/powershell/internal/report/ConvertTo-MtMaesterResult.ps1 @@ -565,13 +565,32 @@ $runResult = if ($failed) { 'Failed' } else { 'Passed' } } + # The defender's path (docs/proposals/defenders-path.md, section 7.2): the steps the rows name and their + # prerequisites, with the measures read after the tests. Never fail the conversion over it. + $resultSteps = $null + $stepArguments = $null + try { + $measureSetting = Get-MtMeasureSetting -RunConfig $__MtSession.MaesterConfig + $stepArguments = @{ + InputObject = $mtTests + Measure = if ($RunContext -and $RunContext.PSObject.Properties['Measures'] -and $RunContext.Measures) { $RunContext.Measures } else { @{} } + MeasuresDisabled = -not $measureSetting.Enabled + MinimumShare = $measureSetting.MinimumShare + TenantContext = if ($RunContext -and $RunContext.TenantContext) { $RunContext.TenantContext } else { $null } + } + if ($RunContext -and $RunContext.PSObject.Properties['NativeTests'] -and $RunContext.NativeTests) { $stepArguments.Inventory = @($RunContext.NativeTests) } + $resultSteps = Get-MtResultStep @stepArguments + } catch { + Write-Verbose "Failed to build the defender's path: $($_.Exception.Message)" + } + # Consolidated inventory of all objects referenced by the run (RelatedObjects, - # result markdown deep links and the session request caches). Never fail the + # result markdown deep links, the objects of the measures and the session request caches). Never fail the # results conversion over inventory issues. $affectedObjects = @() if ($IncludeAffectedObjects.IsPresent) { try { - $affectedObjects = @(Get-MtAffectedObject -MaesterResults ([PSCustomObject]@{ Tests = $mtTests })) + $affectedObjects = @(Get-MtAffectedObject -MaesterResults ([PSCustomObject]@{ Tests = $mtTests; Steps = $(if ($resultSteps) { $resultSteps.Steps } else { @() }) })) } catch { Write-Verbose "Failed to build affected objects: $($_.Exception.Message)" } @@ -619,8 +638,8 @@ ConnectionSummary = @(GetConnectionSummary) PesterConfig = GetPesterConfigInfo $PesterConfiguration MaesterConfig = New-MtResultConfig -RunConfig $__MtSession.MaesterConfig -Rows $mtTests -NativeRows $NativeRows - # Additive in result schema 2.1. - SchemaVersion = '2.1' + # Additive in result schema 2.1, and Steps and Goals in 2.2. + SchemaVersion = '2.2' # A string: CurrentVersion keeps its 2.x shape ([version] serialised as an object). CatalogVersion = [string]$currentVersion TenantContext = if ($RunContext -and $RunContext.TenantContext) { $RunContext.TenantContext } else { $null } @@ -660,16 +679,32 @@ # The previous run on the tenant, for a report that shows what changed. Never fail the conversion over it. # This runs before the run writes its own files, so the file at this run's output path, when the caller reuses - # a name such as TestResults-latest, is the previous run and is read like any other. + # a name such as TestResults-latest, is the previous run and is read like any other. When a step of the + # defender's path is Not checked, LastKnown holds the newest earlier result of each of its tests, which gives + # the step's Earlier status. if ($IncludePrevious.IsPresent -and $OutputFiles -and $OutputFiles.PSObject.Properties['OutputFolder']) { try { - $previous = Get-MtPreviousResult -Folder ([string]$OutputFiles.OutputFolder) -TenantId $tenantId - if ($previous) { $mtTestResults | Add-Member -MemberType NoteProperty -Name 'Previous' -Value $previous } + $previousArguments = @{ Folder = [string]$OutputFiles.OutputFolder; TenantId = $tenantId } + $notChecked = @(if ($resultSteps) { $resultSteps.Steps | Where-Object { $_.Status -eq 'NotChecked' } }) + if ($notChecked.Count -gt 0) { $previousArguments.LastKnownId = [string[]]@($notChecked | ForEach-Object { $_.Tests.Id } | Where-Object { $_ } | Select-Object -Unique) } + $previous = Get-MtPreviousResult @previousArguments + if ($previous) { + $mtTestResults | Add-Member -MemberType NoteProperty -Name 'Previous' -Value $previous + if ($notChecked.Count -gt 0 -and $previous.PSObject.Properties['LastKnown'] -and $previous.LastKnown) { + $resultSteps = Get-MtResultStep @stepArguments -LastKnown $previous.LastKnown + } + } } catch { Write-Verbose "Failed to read the previous result: $($_.Exception.Message)" } } + # Steps and Goals, only when a row that ran names a step, so other results are unchanged. + if ($resultSteps) { + $mtTestResults | Add-Member -MemberType NoteProperty -Name 'Steps' -Value @($resultSteps.Steps) + $mtTestResults | Add-Member -MemberType NoteProperty -Name 'Goals' -Value @($resultSteps.Goals) + } + # Add output files information if provided if ($OutputFiles) { $mtTestResults | Add-Member -MemberType NoteProperty -Name 'OutputFiles' -Value $OutputFiles diff --git a/powershell/internal/report/Get-MtMarkdownReport.ps1 b/powershell/internal/report/Get-MtMarkdownReport.ps1 index 2930e6f90e..f96f9e1975 100644 --- a/powershell/internal/report/Get-MtMarkdownReport.ps1 +++ b/powershell/internal/report/Get-MtMarkdownReport.ps1 @@ -6,6 +6,10 @@ .Description This markdown report can be used in GitHub actions to display the test results in a formatted way. + When the results have the defender's path (Steps), the report starts with "Do these first": the first five + steps that are ready, in rank order, each with its failed tests, and one line that counts the steps that are + blocked and those whose prerequisites need checking first. + .Example $pesterResults = Invoke-Pester -PassThru $maesterResults = ConvertTo-MtMaesterResult -PesterResults $pesterResults @@ -115,12 +119,45 @@ return $details.ToString() } + # The defender's path: the first five Ready steps with their failed tests, and the count of the others. + function GetDefendersPath() { + if (-not ($MaesterResults.PSObject.Properties['Steps'] -and $MaesterResults.Steps)) { return '' } + $steps = @($MaesterResults.Steps | Sort-Object -Property { [int]$_.Rank }) + $ready = @($steps | Where-Object { $_.Readiness -eq 'Ready' }) + $blocked = @($steps | Where-Object { $_.Readiness -eq 'Blocked' }).Count + $unconfirmed = @($steps | Where-Object { $_.Readiness -eq 'Unconfirmed' }).Count + $titles = @{} + foreach ($test in @($MaesterResults.Tests)) { if ($test.Id -and -not $titles.ContainsKey([string]$test.Id)) { $titles[[string]$test.Id] = [string]$test.Title } } + $text = [System.Text.StringBuilder]::new("## Do these first`n`n") + if ($ready.Count -eq 0) { + [void]$text.Append("No step of the defender's path is ready to start.`n`n") + } + $number = 0 + foreach ($step in @($ready | Select-Object -First 5)) { + $number++ + [void]$text.Append("$number. **$($step.Title)** (``$($step.Id)``)`n") + foreach ($t in @($step.Tests | Where-Object { $_.Result -eq 'Failed' })) { + $title = if ($titles.ContainsKey([string]$t.Id)) { ": $($titles[[string]$t.Id])" } else { '' } + [void]$text.Append(" - $($StatusIconSm['Failed']) $($t.Id)$title`n") + } + if ($step.Measure -and $null -ne $step.Measure.Share) { + [void]$text.Append(" - $($step.Measure.Share)% of $($step.Measure.Total) meet it, $($step.Measure.MinimumShare)% needed`n") + } + } + if ($number -gt 0) { [void]$text.Append("`n") } + $blockedText = if ($blocked -eq 1) { '1 step is blocked' } else { "$blocked steps are blocked" } + $checkText = if ($unconfirmed -eq 1) { '1 step has prerequisites to check first' } else { "$unconfirmed steps have prerequisites to check first" } + [void]$text.Append("$blockedText, and $checkText.`n`n") + return $text.ToString() + } + $markdownFilePath = Join-Path -Path $PSScriptRoot -ChildPath '../../assets/ReportTemplate.md' $templateMarkdown = Get-Content -Path $markdownFilePath -Raw # Execute functions first so they don't mess with the markdown template $textSummary = GetTestSummary $textDetails = GetTestDetails + $textDefendersPath = GetDefendersPath $templateMarkdown = $templateMarkdown -replace '%TenandId%', $MaesterResults.TenantId $templateMarkdown = $templateMarkdown -replace '%TenantName%', $MaesterResults.TenantName @@ -134,6 +171,8 @@ $templateMarkdown = $templateMarkdown -replace '%SkippedCount%', $MaesterResults.SkippedCount $templateMarkdown = $templateMarkdown -replace '%NotRunCount%', $MaesterResults.NotRunCount + # A literal replacement: step titles are text, not a regular expression's replacement pattern. + $templateMarkdown = $templateMarkdown.Replace('%DefendersPath%', $textDefendersPath) $templateMarkdown = $templateMarkdown -replace '%TestSummary%', $textSummary $templateMarkdown = $templateMarkdown -replace '%TestDetails%', $textDetails diff --git a/powershell/internal/report/Get-MtPreviousResult.ps1 b/powershell/internal/report/Get-MtPreviousResult.ps1 index e2036b187d..0fd737439a 100644 --- a/powershell/internal/report/Get-MtPreviousResult.ps1 +++ b/powershell/internal/report/Get-MtPreviousResult.ps1 @@ -14,6 +14,11 @@ second copy of the findings. The comparison is the one Compare-MtTestResult makes. A result file starts with its counts, ExecutedAt and TenantId, so History reads only the start of each file; only the newest file is read in full. + + With -LastKnownId, the result also has LastKnown: for each of these test IDs, the newest earlier result that ran + it (Result other than NotRun), as Result, ReasonCode, ExecutedAt and File. It reads only the files History lists, + newest first, and stops once every ID is found. The defender's path uses it for the steps a run did not check + (docs/proposals/defenders-path.md, section 7.2), so a one-check run still shows what an earlier run found. #> [CmdletBinding()] [OutputType([pscustomobject])] @@ -31,7 +36,10 @@ [Parameter()] [int] $MaxFiles = 15, # How many earlier runs History lists. - [Parameter()] [int] $HistoryCount = 10 + [Parameter()] [int] $HistoryCount = 10, + + # Test IDs whose newest earlier result LastKnown gives. + [Parameter()] [AllowNull()] [AllowEmptyCollection()] [string[]] $LastKnownId ) if (-not $Folder -or -not (Test-Path -LiteralPath $Folder -PathType Container)) { return } @@ -98,10 +106,36 @@ foreach ($key in $_.Counts.Keys) { $entry[$key] = $_.Counts[$key] } [pscustomobject]$entry }) - [pscustomobject][ordered]@{ + $out = [pscustomobject][ordered]@{ ExecutedAt = $previous.Header.ExecutedAt.ToString('o', [cultureinfo]::InvariantCulture) File = $previous.Header.File.Name Results = [pscustomobject]$results History = $history } + + if ($null -ne $LastKnownId) { + $wanted = [System.Collections.Generic.HashSet[string]]::new([string[]]@($LastKnownId | Where-Object { $_ }), [System.StringComparer]::OrdinalIgnoreCase) + $lastKnown = [ordered]@{} + $listed = @($headers | Where-Object { $_.Counts.Contains('Total') } | Select-Object -First $HistoryCount) + foreach ($header in $listed) { + if ($wanted.Count -eq 0) { break } + $result = if ([object]::ReferenceEquals($header, $previous.Header)) { $previous.Result } else { + try { Get-Content -LiteralPath $header.File.FullName -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop } catch { $null } + } + if ($result -isnot [pscustomobject] -or -not $result.PSObject.Properties['Tests']) { continue } + foreach ($row in @($result.Tests)) { + $id = if ($row.PSObject.Properties['Id'] -and $row.Id) { [string]$row.Id } else { $null } + if (-not $id -or -not $wanted.Contains($id) -or [string]$row.Result -eq 'NotRun') { continue } + $null = $wanted.Remove($id) + $lastKnown[$id] = [pscustomobject][ordered]@{ + Result = [string]$row.Result + ReasonCode = if ($row.PSObject.Properties['ReasonCode'] -and $row.ReasonCode) { [string]$row.ReasonCode } else { $null } + ExecutedAt = $header.ExecutedAt.ToString('o', [cultureinfo]::InvariantCulture) + File = $header.File.Name + } + } + } + $out | Add-Member -MemberType NoteProperty -Name 'LastKnown' -Value ([pscustomobject]$lastKnown) + } + $out } diff --git a/powershell/internal/report/Get-MtResultStep.ps1 b/powershell/internal/report/Get-MtResultStep.ps1 new file mode 100644 index 0000000000..fc85d3a9e8 --- /dev/null +++ b/powershell/internal/report/Get-MtResultStep.ps1 @@ -0,0 +1,407 @@ +function Get-MtResultStep { + <# + .SYNOPSIS + Builds the Steps and Goals of a result: the defender's path of the run, with each step's status, readiness and + place in the order. + + .DESCRIPTION + Implements sections 6 and 7.2 of docs/proposals/defenders-path.md. The steps in scope (Get-MtStepScope) are the + steps that rows that ran name and their prerequisites at any depth. For each one: + + - Status, from its verifying tests in this run and its measure, checked in this order: NotApplicable (an OnlyWhen + condition is false, or every verifying test that ran was skipped as NotApplicable), Unknown when an OnlyWhen + condition can't be read, NotDone (a test failed or the measure is below its threshold), Unknown (a test ended + as Investigate, Error or Skipped, or the measure couldn't be read), Done (every test that ran passed and the + measure met its threshold) and NotChecked (no test ran and no measure was read). A test skipped as + NotApplicable next to tests that gave a result is left out. Reason says why a step is NotApplicable, Unknown + or NotChecked (section 7.2 of the design, and the result schema). + - Readiness, for a step that is NotDone, Unknown or NotChecked: Blocked when a Requires step is NotDone, every + step of a RequiresOneOf group is NotDone, or a Conflicts step is Done (BlockedBy lists them); Unconfirmed when + not blocked but a prerequisite is Unknown or NotChecked (Unconfirmed lists them); Ready otherwise. A + NotApplicable prerequisite counts as met, except in a RequiresOneOf group, which leaves it out; a group with no + step left is met. + - Rank: Ready, then Unconfirmed, then Blocked, then Done, then NotApplicable; within a group, prerequisites + before the steps that depend on them, then the highest value first (the highest Get-MtTestPriority of its + failed tests, plus the values of the NotDone steps that depend on it at any depth), then the ID. + - Tests: every test the engine knows that names the step (-Inventory) and every row that does, with its Result + and ReasonCode. A test with no row is NotRun with ReasonCode NotInRun. A family is represented by its instances' + rows when it has some. + - Measure, for a step that has one, whether or not it could be read: the figure, its threshold (MinimumShare, or + the run config's override) and up to -MaxObjects of the objects that fall short. + - Earlier, for a NotChecked step whose tests an earlier run checked (-LastKnown, from Get-MtPreviousResult). + + Goals lists each goal that has a step in scope, with its steps in scope in catalogue order (prerequisites first) + and how many are Done, Applicable, Unknown and NotChecked. + + Returns an object with Steps and Goals, or nothing when no row that ran names a step. + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '', Justification = 'MeasuresDisabled, TenantContext, LastKnown, MaxObjects and Registry are read inside script blocks, which the rule does not follow.')] + [CmdletBinding()] + [OutputType([pscustomobject])] + param( + # Result rows, with Id, Result, ReasonCode, Step, ParentId and the attributes Get-MtTestPriority reads. + [Parameter()] [AllowNull()] [AllowEmptyCollection()] [object[]] $InputObject = @(), + + # The tests the engine knows (the built-in catalog, custom and pack tests), with Id and Step. Defaults to the + # built-in catalog. + [Parameter()] [AllowNull()] [AllowEmptyCollection()] [object[]] $Inventory, + + # The measures read for this run (Invoke-MtStepMeasure): measure key to Count, Total, Objects, ReadAt and + # ReasonCode, and optionally ObjectCount when Objects holds only some of them. + [Parameter()] [AllowNull()] [hashtable] $Measure = @{}, + + # The run config turned measures off. + [Parameter()] [switch] $MeasuresDisabled, + + # Thresholds from the run config (Measures.MinimumShare), by measure key. + [Parameter()] [AllowNull()] [hashtable] $MinimumShare = @{}, + + # The tenant context, for OnlyWhen conditions: HybridIdentity and Licenses. + [Parameter()] [AllowNull()] [object] $TenantContext, + + # The newest earlier result of each test ID (Get-MtPreviousResult -LastKnownId): ID to Result, ExecutedAt, File. + [Parameter()] [AllowNull()] [object] $LastKnown, + + # The most objects a step's Measure keeps. + [Parameter()] [int] $MaxObjects = 100, + + # The step catalogue. Defaults to the module's. + [Parameter()] [object] $Catalog = (Get-MtStepCatalog), + + # The measure registry, for each measure's Caveat. Defaults to the module's. + [Parameter()] [object] $Registry = (Get-MtMeasureRegistry) + ) + + $scope = Get-MtStepScope -InputObject $InputObject -Catalog $Catalog + if ($scope.Named.Count -eq 0) { return } + if ($null -eq $Inventory) { $Inventory = @(Get-MtTestCatalog) } + if ($null -eq $Measure) { $Measure = @{} } + if ($null -eq $MinimumShare) { $MinimumShare = @{} } + $ordinal = [System.StringComparer]::Ordinal + $catalogSteps = $Catalog.Steps + $inScope = [System.Collections.Generic.HashSet[string]]::new([string[]]$scope.Steps, $ordinal) + $stepsOf = { + param($item) + $p = $item.PSObject.Properties['Step'] + if (-not $p) { return @() } + @($p.Value | Where-Object { $_ } | ForEach-Object { ([string]$_).ToLowerInvariant() }) + } + # A property of an object, or a key of a dictionary (a measure reading may be either). + $field = { + param($item, $name) + if ($null -eq $item) { return $null } + if ($item -is [System.Collections.IDictionary]) { if ($item.Contains($name)) { return , $item[$name] } else { return $null } } + $p = $item.PSObject.Properties[$name] + if ($p) { , $p.Value } else { $null } + } + + # Rows and known tests by step. + $rowsByStep = @{} + $rowById = @{} + $parentsWithRows = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) + foreach ($row in $InputObject) { + if ($null -eq $row) { continue } + if ($row.Id -and -not $rowById.ContainsKey([string]$row.Id)) { $rowById[[string]$row.Id] = $row } + $parent = & $field $row 'ParentId' + if ($parent) { $null = $parentsWithRows.Add([string]$parent) } + foreach ($id in (& $stepsOf $row)) { + if (-not $inScope.Contains($id)) { continue } + if (-not $rowsByStep.ContainsKey($id)) { $rowsByStep[$id] = [System.Collections.Generic.List[object]]::new() } + $rowsByStep[$id].Add($row) + } + } + $testsByStep = @{} + foreach ($t in @($Inventory | Where-Object { $_ -and $_.Id })) { + foreach ($id in (& $stepsOf $t)) { + if (-not $inScope.Contains($id)) { continue } + if (-not $testsByStep.ContainsKey($id)) { $testsByStep[$id] = [System.Collections.Generic.List[object]]::new() } + $testsByStep[$id].Add($t) + } + } + + # OnlyWhen: True, False or Unknown. + $conditionOf = { + param([string] $condition) + if ($condition -eq 'hybrid-identity') { + $hybrid = if ($TenantContext) { & $field $TenantContext 'HybridIdentity' } else { $null } + if ($null -eq $hybrid) { return 'Unknown' } + return $(if ($hybrid) { 'True' } else { 'False' }) + } + if ($condition -like 'license:*') { + $licenses = if ($TenantContext) { & $field $TenantContext 'Licenses' } else { $null } + if (-not $licenses -or [string]$licenses.State -ne 'Known') { return 'Unknown' } + return $(if (Test-MtLicenseRequirement -Requirement @($condition.Substring(8)) -Licenses $licenses) { 'True' } else { 'False' }) + } + 'Unknown' + } + + # The measure of a step, in the shape of the result. + $measureOf = { + param($step) + $m = $step.Measure + $key = $m.Key + $entry = $null + $caveat = if ($Registry.Measures.TryGetValue($key, [ref] $entry) -and $entry.Caveat) { $entry.Caveat } else { $null } + $minimum = [int]$m.MinimumShare + if ($MinimumShare.ContainsKey($key) -and $null -ne $MinimumShare[$key]) { $minimum = [int]$MinimumShare[$key] } + $out = [ordered]@{ + Key = $key; Count = $null; Total = $null; Share = $null; MinimumShare = $minimum; Met = $null; ReadAt = $null + Caveat = $caveat; ObjectCount = $null; Objects = @(); ReasonCode = $null + } + $reading = if ($Measure.ContainsKey($key)) { $Measure[$key] } else { $null } + if ($MeasuresDisabled) { $out.ReasonCode = 'MeasureOff' } + elseif ($null -eq $reading) { $out.ReasonCode = 'NotRead' } + else { + $out.ReadAt = & $field $reading 'ReadAt' + $code = & $field $reading 'ReasonCode' + if ($code) { $out.ReasonCode = [string]$code } + else { + $count = [int](& $field $reading 'Count') + $total = [int](& $field $reading 'Total') + $objects = @(& $field $reading 'Objects' | ForEach-Object { $_ } | Where-Object { $null -ne $_ }) + $objectCount = & $field $reading 'ObjectCount' + $out.Count = $count + $out.Total = $total + $out.Share = if ($total -gt 0) { [int][math]::Floor($count * 100.0 / $total) } else { $null } + # Compared without rounding: 94.9% does not meet 95%. No object to count meets nothing. + $out.Met = $total -gt 0 -and ($count * 100.0) -ge ($minimum * $total) + $out.ObjectCount = if ($null -ne $objectCount) { [int]$objectCount } else { $objects.Count } + $out.Objects = @($objects | Select-Object -First $MaxObjects | ForEach-Object { + [pscustomobject][ordered]@{ Type = [string](& $field $_ 'Type'); Id = [string](& $field $_ 'Id'); DisplayName = [string](& $field $_ 'DisplayName') } + }) + } + } + [pscustomobject]$out + } + + # Status of each step in scope. + $status = @{} + $records = [ordered]@{} + foreach ($id in $scope.Steps) { + $step = $catalogSteps[$id] + $rows = if ($rowsByStep.ContainsKey($id)) { @($rowsByStep[$id]) } else { @() } + + # Tests: the rows, and the known tests with no row. + $tests = [System.Collections.Generic.List[object]]::new() + $listed = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) + foreach ($row in $rows) { + if (-not $row.Id -or -not $listed.Add([string]$row.Id)) { continue } + $tests.Add([pscustomobject][ordered]@{ Id = [string]$row.Id; Result = [string]$row.Result; ReasonCode = $(if (& $field $row 'ReasonCode') { [string](& $field $row 'ReasonCode') } else { $null }) }) + } + foreach ($t in @(if ($testsByStep.ContainsKey($id)) { $testsByStep[$id] })) { + $tid = [string]$t.Id + if ($listed.Contains($tid)) { continue } + if ((& $field $t 'InstanceSource') -and $parentsWithRows.Contains($tid)) { continue } + $null = $listed.Add($tid) + $row = if ($rowById.ContainsKey($tid)) { $rowById[$tid] } else { $null } + $tests.Add([pscustomobject][ordered]@{ + Id = $tid + Result = if ($row) { [string]$row.Result } else { 'NotRun' } + ReasonCode = if ($row) { $(if (& $field $row 'ReasonCode') { [string](& $field $row 'ReasonCode') } else { $null }) } else { 'NotInRun' } + }) + } + $sortedTests = @($tests | Sort-Object -Property @{ Expression = { ($_.Id -replace '\d+', { $_.Value.PadLeft(10, '0') }) } }) + + # Not $measure: PowerShell names ignore case, and that is the -Measure parameter. + $stepMeasure = if ($step.Measure) { & $measureOf $step } else { $null } + $measureRead = $stepMeasure -and -not $stepMeasure.ReasonCode + $measureUnread = $stepMeasure -and $stepMeasure.ReasonCode -and $stepMeasure.ReasonCode -notin 'MeasureOff', 'NotRead' + + $ran = @($sortedTests | Where-Object { $_.Result -ne 'NotRun' }) + $counted = @($ran | Where-Object { -not ($_.Result -eq 'Skipped' -and $_.ReasonCode -eq 'NotApplicable') }) + $conditions = @($step.OnlyWhen | ForEach-Object { & $conditionOf $_ }) + + $state = $null; $reason = $null + if ($conditions -contains 'False') { $state = 'NotApplicable'; $reason = 'ConditionNotMet' } + elseif ($conditions -contains 'Unknown') { $state = 'Unknown'; $reason = 'ConditionUnknown' } + elseif ($ran.Count -gt 0 -and $counted.Count -eq 0 -and -not $measureRead) { $state = 'NotApplicable'; $reason = 'TestsNotApplicable' } + elseif (($counted | Where-Object { $_.Result -eq 'Failed' }) -or ($measureRead -and -not $stepMeasure.Met)) { $state = 'NotDone' } + else { + $unsure = @($counted | Where-Object { $_.Result -in 'Investigate', 'Error', 'Skipped' }) + if ($unsure.Count -gt 0 -or $measureUnread) { + $state = 'Unknown' + $reason = if ($unsure.Count -gt 0) { $(if ($unsure[0].ReasonCode) { $unsure[0].ReasonCode } else { $unsure[0].Result }) } else { $stepMeasure.ReasonCode } + } elseif ($counted.Count -gt 0 -or $measureRead) { $state = 'Done' } + else { + $state = 'NotChecked' + $reason = if ($sortedTests.Count -gt 0) { 'NotSelected' } elseif ($stepMeasure -and $stepMeasure.ReasonCode -eq 'MeasureOff') { 'MeasureOff' } elseif ($stepMeasure) { 'NotRead' } else { 'NoCheck' } + } + } + $status[$id] = $state + + # A step's own value: the highest priority among its failed tests. + $own = 0.0 + foreach ($row in @($rows | Where-Object { $_.Result -eq 'Failed' })) { $p = Get-MtTestPriority -InputObject $row; if ($p -gt $own) { $own = $p } } + + $records[$id] = [ordered]@{ + Step = $step; Status = $state; Reason = $reason; Tests = $sortedTests; Measure = $stepMeasure; Own = $own + } + } + + # Readiness. + $notMet = { param($other) $status.ContainsKey($other) -and $status[$other] -in 'Unknown', 'NotChecked' } + foreach ($id in $scope.Steps) { + $r = $records[$id] + $step = $r.Step + $blockedBy = [System.Collections.Generic.List[string]]::new() + $unconfirmed = [System.Collections.Generic.List[string]]::new() + $addTo = { param($list, $other) if (-not $list.Contains($other)) { $list.Add($other) } } + foreach ($other in @($step.Requires)) { + if (-not $status.ContainsKey($other)) { continue } + if ($status[$other] -eq 'NotDone') { & $addTo $blockedBy $other } + elseif (& $notMet $other) { & $addTo $unconfirmed $other } + } + foreach ($group in @($step.RequiresOneOf)) { + $members = @($group | Where-Object { $status.ContainsKey($_) -and $status[$_] -ne 'NotApplicable' }) + if ($members.Count -eq 0 -or ($members | Where-Object { $status[$_] -eq 'Done' })) { continue } + $open = @($members | Where-Object { $status[$_] -ne 'NotDone' }) + if ($open.Count -eq 0) { foreach ($m in $members) { & $addTo $blockedBy $m } } + else { foreach ($m in $open) { & $addTo $unconfirmed $m } } + } + foreach ($other in @($step.Conflicts)) { + if (-not $status.ContainsKey($other)) { continue } + if ($status[$other] -eq 'Done') { & $addTo $blockedBy $other } + elseif (& $notMet $other) { & $addTo $unconfirmed $other } + } + $r.BlockedBy = $blockedBy.ToArray() + $r.Unconfirmed = $unconfirmed.ToArray() + $r.Readiness = if ($r.Status -notin 'NotDone', 'Unknown', 'NotChecked') { $null } + elseif ($blockedBy.Count -gt 0) { 'Blocked' } + elseif ($unconfirmed.Count -gt 0) { 'Unconfirmed' } + else { 'Ready' } + } + + # Order edges within the scope: a step comes after its prerequisites. Dependents are the reverse. + $prerequisitesOf = @{} + $dependentsOf = @{} + foreach ($id in $scope.Steps) { $dependentsOf[$id] = [System.Collections.Generic.List[string]]::new() } + foreach ($id in $scope.Steps) { + $step = $catalogSteps[$id] + $before = @(@($step.Requires) + @($step.RequiresOneOf | ForEach-Object { $_ }) + @($step.RecommendedFirst) | Where-Object { $_ -and $inScope.Contains($_) } | Select-Object -Unique) + $prerequisitesOf[$id] = $before + foreach ($p in $before) { if (-not $dependentsOf[$p].Contains($id)) { $dependentsOf[$p].Add($id) } } + } + + # Value: own value plus the own values of the NotDone steps that depend on it, at any depth. + $value = @{} + foreach ($id in $scope.Steps) { + $seen = [System.Collections.Generic.HashSet[string]]::new($ordinal) + $queue = [System.Collections.Generic.Queue[string]]::new() + foreach ($d in $dependentsOf[$id]) { $queue.Enqueue($d) } + $unlock = 0.0 + while ($queue.Count -gt 0) { + $d = $queue.Dequeue() + if (-not $seen.Add($d)) { continue } + if ($status[$d] -eq 'NotDone') { $unlock += $records[$d].Own } + foreach ($next in $dependentsOf[$d]) { $queue.Enqueue($next) } + } + $value[$id] = $records[$id].Own + $unlock + } + + # Rank: by group, then topologically within the group, then by value and ID. + $groupOf = { + param($id) + $r = $records[$id] + switch ($r.Readiness) { 'Ready' { 0 } 'Unconfirmed' { 1 } 'Blocked' { 2 } default { if ($r.Status -eq 'Done') { 3 } else { 4 } } } + } + $rank = 0 + foreach ($group in 0..4) { + $members = [System.Collections.Generic.List[string]]::new() + foreach ($id in $scope.Steps) { if ((& $groupOf $id) -eq $group) { $members.Add($id) } } + $placed = [System.Collections.Generic.HashSet[string]]::new($ordinal) + while ($placed.Count -lt $members.Count) { + $available = @($members | Where-Object { + $candidate = $_ + -not $placed.Contains($candidate) -and -not ($prerequisitesOf[$candidate] | Where-Object { $members.Contains($_) -and -not $placed.Contains($_) }) + }) + # A cycle (which the catalogue's checks rule out) must not loop: take what is left. + if ($available.Count -eq 0) { $available = @($members | Where-Object { -not $placed.Contains($_) }) } + $next = $available | Sort-Object -Property @{ Expression = { $value[$_] }; Descending = $true }, @{ Expression = { $_ } } | Select-Object -First 1 + $null = $placed.Add($next) + $rank++ + $records[$next].Rank = $rank + } + } + + # Goals that have a step in scope. + $goalsOf = @{} + $goals = foreach ($goal in $Catalog.Goals) { + $goalSteps = @($goal.Steps | Where-Object { $inScope.Contains($_) }) + if ($goalSteps.Count -eq 0) { continue } + foreach ($id in $goalSteps) { + if (-not $goalsOf.ContainsKey($id)) { $goalsOf[$id] = [System.Collections.Generic.List[string]]::new() } + $goalsOf[$id].Add($goal.Id) + } + $applicable = @($goalSteps | Where-Object { $status[$_] -ne 'NotApplicable' }) + $done = @($applicable | Where-Object { $status[$_] -eq 'Done' }).Count + [pscustomobject][ordered]@{ + Id = $goal.Id + Title = $goal.Title + Summary = $goal.Summary + Step = $goal.Step + Steps = [string[]]$goalSteps + Done = $done + Applicable = $applicable.Count + Unknown = @($applicable | Where-Object { $status[$_] -eq 'Unknown' }).Count + NotChecked = @($applicable | Where-Object { $status[$_] -eq 'NotChecked' }).Count + Status = if ($applicable.Count -eq 0) { 'NotApplicable' } elseif ($done -eq $applicable.Count) { 'Done' } elseif ($done -eq 0) { 'NotStarted' } else { 'InProgress' } + } + } + + # Earlier: what an earlier run found for a step this run did not check. + $lastKnownOf = { + param($testId) + if ($null -eq $LastKnown) { return $null } + if ($LastKnown -is [System.Collections.IDictionary]) { if ($LastKnown.Contains($testId)) { return $LastKnown[$testId] } else { return $null } } + $p = $LastKnown.PSObject.Properties[$testId] + if ($p) { $p.Value } else { $null } + } + $earlierOf = { + param($tests) + $known = @(foreach ($t in $tests) { $k = & $lastKnownOf $t.Id; if ($k -and [string]$k.Result -and [string]$k.Result -ne 'NotRun') { $k } }) + if ($known.Count -eq 0) { return $null } + $counted = @($known | Where-Object { [string]$_.Result -ne 'Skipped' -or [string](& $field $_ 'ReasonCode') -ne 'NotApplicable' }) + $state = if ($counted.Count -eq 0) { 'NotApplicable' } + elseif ($counted | Where-Object { [string]$_.Result -eq 'Failed' }) { 'NotDone' } + elseif ($counted | Where-Object { [string]$_.Result -in 'Investigate', 'Error', 'Skipped' }) { 'Unknown' } + else { 'Done' } + $newest = $known | Sort-Object -Property @{ Expression = { [string]$_.ExecutedAt } } -Descending | Select-Object -First 1 + [pscustomobject][ordered]@{ Status = $state; ExecutedAt = $newest.ExecutedAt; File = $newest.File } + } + + $ranked = @($scope.Steps | Sort-Object -Property @{ Expression = { $records[$_].Rank } }) + $out = foreach ($id in $ranked) { + $r = $records[$id] + $step = $r.Step + $unlocks = @($dependentsOf[$id] | Where-Object { $status[$_] -notin 'Done', 'NotApplicable' } | Sort-Object -Property @{ Expression = { $records[$_].Rank } }) + [pscustomobject][ordered]@{ + Id = $id + Title = $step.Title + Summary = $step.Summary + Product = $step.Product + Goals = [string[]]@(if ($goalsOf.ContainsKey($id)) { $goalsOf[$id] }) + Status = $r.Status + Reason = $r.Reason + Readiness = $r.Readiness + BlockedBy = [string[]]$r.BlockedBy + Unconfirmed = [string[]]$r.Unconfirmed + Unlocks = [string[]]$unlocks + Rank = $r.Rank + Tests = @($r.Tests) + Earlier = if ($r.Status -eq 'NotChecked') { & $earlierOf $r.Tests } else { $null } + Measure = $r.Measure + Requires = [string[]]@($step.Requires) + RequiresOneOf = @(foreach ($g in @($step.RequiresOneOf)) { , [string[]]@($g) }) + RecommendedFirst = [string[]]@($step.RecommendedFirst) + Conflicts = [string[]]@($step.Conflicts) + OnlyWhen = [string[]]@($step.OnlyWhen) + Rollout = [string[]]@($step.Rollout) + Sources = @($step.Sources) + } + } + + [pscustomobject]@{ + Steps = @($out) + Goals = @($goals) + } +} diff --git a/powershell/internal/report/Get-MtTestPriority.ps1 b/powershell/internal/report/Get-MtTestPriority.ps1 new file mode 100644 index 0000000000..7320a03af5 --- /dev/null +++ b/powershell/internal/report/Get-MtTestPriority.ps1 @@ -0,0 +1,54 @@ +function Get-MtTestPriority { + <# + .SYNOPSIS + Returns how urgent fixing a test is, the number the report's action plan ranks failed tests by. + + .DESCRIPTION + The engine's copy of priority() in report/src/lib/model.ts (docs/proposals/defenders-path.md, section 6.3), so + that the defender's path, the console and the Markdown report rank the same way as the report. Severity counts + most; within a severity, a fix that users won't notice and that costs little comes first, then a test that + addresses more ATT&CK techniques and maps to more framework requirements: + + severity weight x 4 + ease of UserImpact x 1.5 + ease of ImplementationCost x 1.5 + + min(ATT&CK techniques, 3) x 0.3 + (Control references + 1 when Benchmark is set) x 0.2 + + Severity weights are Critical 4, High 3, Medium 2, Low 1 and Info 0, and any other value 2. Ease is Low 2, + Medium 1 and High 0, and 1 when the attribute is not set. 'None' is not counted as a technique. A row without a + Severity uses ResultDetail.Severity, as the report does. Keep the two copies the same: a unit test checks the + numbers. + #> + [CmdletBinding()] + [OutputType([double])] + param( + # A result row. + [Parameter(Mandatory, ValueFromPipeline)] [AllowNull()] [object] $InputObject + ) + + process { + if ($null -eq $InputObject) { return } + $value = { + param($name) + $property = $InputObject.PSObject.Properties[$name] + if ($property) { $property.Value } else { $null } + } + $severity = [string](& $value 'Severity') + if (-not $severity) { + $detail = & $value 'ResultDetail' + if ($detail -and $detail.PSObject.Properties['Severity']) { $severity = [string]$detail.Severity } + } + $severityWeight = @{ Critical = 4; High = 3; Medium = 2; Low = 1; Info = 0 } + $ease = @{ Low = 2; Medium = 1; High = 0 } + # Case-sensitive lookups, like the report's. + $weightOf = { param($table, $key, $default) $key = [string]$key; foreach ($k in $table.Keys) { if ($k -ceq $key) { return $table[$k] } }; $default } + + $mitre = @(& $value 'Mitre' | Where-Object { $_ -and [string]$_ -ne 'None' }).Count + $control = @(& $value 'Control' | Where-Object { $_ }).Count + $benchmark = if (& $value 'Benchmark') { 1 } else { 0 } + + [double]((& $weightOf $severityWeight $severity 2) * 4 + + (& $weightOf $ease (& $value 'UserImpact') 1) * 1.5 + + (& $weightOf $ease (& $value 'ImplementationCost') 1) * 1.5 + + [math]::Min($mitre, 3) * 0.3 + + ($control + $benchmark) * 0.2) + } +} diff --git a/powershell/internal/report/affected-objects/Get-MtAffectedObject.ps1 b/powershell/internal/report/affected-objects/Get-MtAffectedObject.ps1 index 98712bfc16..65ade891ea 100644 --- a/powershell/internal/report/affected-objects/Get-MtAffectedObject.ps1 +++ b/powershell/internal/report/affected-objects/Get-MtAffectedObject.ps1 @@ -8,6 +8,8 @@ function Get-MtAffectedObject { 1. Structured RelatedObjects captured by Add-MtTestResultDetail (per-test attribution, strongest signal) 2. Portal deep links parsed from result markdown (covers ad-hoc $portalLink sites and old reports) 3. Session request caches (run-level view of every Graph/GitHub resource the run touched) + 4. The objects that fall short of a measure of the defender's path (Steps[].Measure.Objects), with Source + Measure, so that the facts their readers add have an object to attach to Records are deduplicated on System/Type/Id; per-test attribution is aggregated into a Tests array so each object shows which checks reference it. @@ -62,6 +64,30 @@ function Get-MtAffectedObject { } } + # Source 4: the objects of the measures. They name no test: the step's measure lists them. + if ($MaesterResults -and $MaesterResults.PSObject.Properties['Steps'] -and $MaesterResults.Steps) { + $linkTemplates = (Get-MtPortalLinkTemplate).LinkTemplates + foreach ($step in @($MaesterResults.Steps)) { + $measure = Get-ObjectProperty $step 'Measure' + if (-not $measure) { continue } + foreach ($item in @(Get-ObjectProperty $measure 'Objects')) { + if ($null -eq $item -or -not $item.Id -or -not $item.Type) { continue } + $template = switch ([string]$item.Type) { 'Device' { $linkTemplates.Devices } 'User' { $linkTemplates.Users } default { $null } } + $records.Add([PSCustomObject]@{ + System = 'EntraID' + AnchorKind = 'Instance' + Type = [string]$item.Type + Id = [string]$item.Id + DisplayName = [string]$item.DisplayName + UserPrincipalName = $null + PortalLink = if ($template) { $template -f $item.Id } else { $null } + TestId = $null + Source = 'Measure' + }) + } + } + } + # Source 3: run-level cache view if (-not $ExcludeSessionCache) { foreach ($cached in @(Get-MtAffectedObjectFromCache)) { @@ -105,7 +131,7 @@ function Get-MtAffectedObject { # Consolidate: one record per System/Type/Id with aggregated test attribution. # Structured GraphObjects records win over markdown/cache records for the same object. # Unknown sources rank last so a record with a missing Source never outranks a structured one. - $sourceRank = @{ GraphObjects = 0; Markdown = 1; GraphCache = 2; GitHubCache = 2 } + $sourceRank = @{ GraphObjects = 0; Markdown = 1; Measure = 1; GraphCache = 2; GitHubCache = 2 } # Objects passed without an id fall back to their UPN or name, otherwise distinct users would # merge into one object and all but the first would escape redaction. $identityOf = { diff --git a/powershell/internal/services/entra/Get-MtDeviceComplianceShare.ps1 b/powershell/internal/services/entra/Get-MtDeviceComplianceShare.ps1 new file mode 100644 index 0000000000..865f99a80d --- /dev/null +++ b/powershell/internal/services/entra/Get-MtDeviceComplianceShare.ps1 @@ -0,0 +1,93 @@ +function Get-MtDeviceComplianceShare { + <# + .SYNOPSIS + Counts the devices that signed in recently and are marked compliant, for the devices-compliant measure. + + .DESCRIPTION + The reader of the devices-compliant measure (powershell/assets/MaesterMeasures.psd1), which decides the step + intune.devices-compliant of the defender's path. A Conditional Access policy that requires a compliant device + blocks every device that Microsoft Entra ID doesn't mark compliant, so the share of compliant devices among the + devices in use says whether such a policy can be turned on. + + Reads the enabled devices in Microsoft Entra ID that signed in within the last SignedInWithinDays days + (approximateLastSignInDateTime), through the Graph cache. A device counts when isCompliant is true: Intune sets + it, also for the devices of a compliance partner, and it is what a compliant-device grant checks. The measure + declares the Intune licence, so a tenant without Intune gets no figure. Devices that are not compliant are + returned as the objects that fall short, most recent sign-in first, whether they are managed (isManaged) and + noncompliant or not managed at all. + + A device that has no Microsoft Entra identity (neither registered nor joined) can't be seen this way, so it is + neither counted nor listed. A compliant-device policy blocks it too. + + Returns an object with Count (compliant devices), Total (devices that signed in) and Objects (the devices that + aren't compliant, as Type, Id and DisplayName). + + For each device it lists, it adds the object facts device.managed, device.compliant, device.os and device.joinType + (design section 12) with Add-MtAffectedObjectFact, from the source 'Maester measures'. The engine puts the + objects of a measure on the Affected objects page, so the facts have an object to attach to. A run that doesn't + collect affected objects keeps no facts. + + .EXAMPLE + Get-MtDeviceComplianceShare + + Returns the number of compliant devices among the enabled devices that signed in within the last 30 days. + + .EXAMPLE + Get-MtDeviceComplianceShare -SignedInWithinDays 14 + + Counts only the devices that signed in within the last 14 days. + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param( + # Devices that signed in within this many days are counted. approximateLastSignInDateTime is approximate, so + # keep it well above a week. + [ValidateRange(1, 365)] + [int] $SignedInWithinDays = 30 + ) + + # Start of the UTC day, so the request, and so its cache entry, stays the same for the whole day. + $since = [datetime]::UtcNow.Date.AddDays(-$SignedInWithinDays).ToString('yyyy-MM-ddTHH:mm:ssZ', [cultureinfo]::InvariantCulture) + $deviceSplat = @{ + RelativeUri = 'devices' + Filter = "accountEnabled eq true and approximateLastSignInDateTime ge $since" + # isManaged, operatingSystem and trustType are read for the object facts device.managed, device.os and + # device.joinType (design section 12). + Select = 'id', 'displayName', 'approximateLastSignInDateTime', 'isCompliant', 'isManaged', 'operatingSystem', 'trustType' + QueryParameters = @{ '$count' = 'true' } + } + $devices = @(Invoke-MtGraphRequest @deviceSplat | Where-Object { $null -ne $_ }) + + $notCompliant = @($devices | Where-Object { $_.isCompliant -ne $true }) + + # Object facts for the devices listed, with the shared keys. + $joinTypes = @{ AzureAd = 'Microsoft Entra joined'; ServerAd = 'Microsoft Entra hybrid joined'; Workplace = 'Microsoft Entra registered' } + $facts = foreach ($device in $notCompliant) { + if (-not $device.id) { continue } + $managed = $device.isManaged -eq $true + $list = [System.Collections.Generic.List[object]]::new() + $list.Add(@{ Name = 'Management'; Value = $(if ($managed) { 'Managed' } else { 'Not managed' }); Tone = $(if ($managed) { 'Info' } else { 'Warning' }); Key = 'device.managed'; Raw = $managed }) + $list.Add(@{ Name = 'Compliance'; Value = 'Not compliant'; Tone = 'Warning'; Key = 'device.compliant'; Raw = $false }) + if ($device.operatingSystem) { $list.Add(@{ Name = 'Operating system'; Value = [string]$device.operatingSystem; Key = 'device.os'; Raw = [string]$device.operatingSystem }) } + $trust = [string]$device.trustType + if ($trust) { $list.Add(@{ Name = 'Join type'; Value = $(if ($joinTypes.ContainsKey($trust)) { $joinTypes[$trust] } else { $trust }); Key = 'device.joinType'; Raw = $trust }) } + [pscustomobject]@{ Type = 'Device'; Id = [string]$device.id; Fact = $list.ToArray() } + } + if (@($facts).Count -gt 0) { $facts | Add-MtAffectedObjectFact -Source 'Maester measures' } + + [pscustomobject][ordered]@{ + Count = $devices.Count - $notCompliant.Count + Total = $devices.Count + Objects = @( + $notCompliant | + Sort-Object -Property @{ Expression = { $_.approximateLastSignInDateTime -as [datetime] }; Descending = $true }, displayName, id | + ForEach-Object { + [pscustomobject][ordered]@{ + Type = 'Device' + Id = [string]$_.id + DisplayName = [string]$_.displayName + } + } + ) + } +} diff --git a/powershell/internal/services/entra/Get-MtMfaCapableShare.ps1 b/powershell/internal/services/entra/Get-MtMfaCapableShare.ps1 new file mode 100644 index 0000000000..7a7773d4ec --- /dev/null +++ b/powershell/internal/services/entra/Get-MtMfaCapableShare.ps1 @@ -0,0 +1,93 @@ +function Get-MtMfaCapableShare { + <# + .SYNOPSIS + Counts the enabled member users who can complete multifactor authentication, for the mfa-capable measure. + + .DESCRIPTION + The reader of the mfa-capable measure (powershell/assets/MaesterMeasures.psd1), which decides the step + entra.mfa-registered of the defender's path. User-risk and sign-in-risk policies ask users to complete MFA, and + a user who hasn't registered a method that is allowed can't, so the share of users who can says whether those + policies can be turned on. + + Reads the authentication methods registration report (reports/authenticationMethods/userRegistrationDetails), + which needs Microsoft Entra ID P1, through the Graph cache. A member user counts when isMfaCapable is true: the + user has registered a strong method that the authentication methods policy allows. isMfaRegistered is not + enough, because it is also true for a method the policy no longer allows. Left out of the count: + + - disabled users, which the report also lists; + - the emergency access accounts in the Maester configuration (EmergencyAccessAccounts), and the users in the + emergency access groups it names, because they stay excluded from these policies; + - the users that hold a directory synchronization role, which Conditional Access policies exclude too. + + A configured emergency access account that can't be found stops the reader with an error, as it does in the + checks that read them, so the figure never counts an account that should have been left out. + + Returns an object with Count (users who can complete MFA), Total (the users counted) and Objects (the users who + can't, as Type, Id and DisplayName, administrators first). + + For each user it lists, it adds the object facts user.mfaCapable and user.mfaRegistered (design section 12) with + Add-MtAffectedObjectFact, from the source 'Maester measures', under the object ID and the user principal name, + so a record has them whichever way it was keyed. A run that doesn't collect affected objects keeps no facts. + + .EXAMPLE + Get-MtMfaCapableShare + + Returns the number of enabled member users who can complete MFA, apart from the emergency access and directory + synchronization accounts. + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param() + + # The whole report, with no $select or $filter, so other readers of the report share its cache entry. + $registrations = @(Invoke-MtGraphRequest -RelativeUri 'reports/authenticationMethods/userRegistrationDetails' | Where-Object { $null -ne $_ }) + + $excluded = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) + foreach ($user in @(Invoke-MtGraphRequest -RelativeUri 'users' -Filter 'accountEnabled eq false' -Select 'id' | Where-Object { $null -ne $_ })) { + $null = $excluded.Add([string]$user.id) + } + foreach ($account in @(Get-MtEmergencyAccessAccount)) { + if ($account.Type -eq 'group') { + $groupUsers = @(Get-MtGroupMember -GroupId $account.ObjectId -Recursive | Where-Object { $_.'@odata.type' -eq '#microsoft.graph.user' }) + foreach ($member in $groupUsers) { $null = $excluded.Add([string]$member.id) } + } elseif ($account.ObjectId) { + $null = $excluded.Add([string]$account.ObjectId) + } + } + foreach ($member in @(Get-MtRoleMember -Role 'DirectorySynchronizationAccounts', 'OnPremisesDirectorySyncAccount' | Where-Object { $_.'@odata.type' -ne '#microsoft.graph.servicePrincipal' })) { + if ($member.id) { $null = $excluded.Add([string]$member.id) } + } + + $users = @($registrations | Where-Object { $_.userType -eq 'member' -and $_.id -and -not $excluded.Contains([string]$_.id) }) + $notCapable = @($users | Where-Object { $_.isMfaCapable -ne $true }) + + # Object facts for the users listed (design section 12), under the object ID and the UPN. + $facts = foreach ($user in $notCapable) { + $list = [System.Collections.Generic.List[object]]::new() + $list.Add(@{ Name = 'Can complete MFA'; Value = 'No: no method the policy allows is registered'; Tone = $(if ($user.isAdmin -eq $true) { 'Risk' } else { 'Warning' }); Key = 'user.mfaCapable'; Raw = $false }) + if ($null -ne $user.isMfaRegistered) { + $registered = $user.isMfaRegistered -eq $true + $list.Add(@{ Name = 'MFA'; Value = $(if ($registered) { 'Registered' } else { 'Not registered' }); Tone = $(if ($registered) { 'Info' } else { 'Warning' }); Key = 'user.mfaRegistered'; Raw = $registered }) + } + $fact = $list.ToArray() + [pscustomobject]@{ Type = 'User'; Id = [string]$user.id; Fact = $fact } + if ($user.userPrincipalName) { [pscustomobject]@{ Type = 'User'; Id = [string]$user.userPrincipalName; Fact = $fact } } + } + if (@($facts).Count -gt 0) { $facts | Add-MtAffectedObjectFact -Source 'Maester measures' } + + [pscustomobject][ordered]@{ + Count = $users.Count - $notCapable.Count + Total = $users.Count + Objects = @( + $notCapable | + Sort-Object -Property @{ Expression = { $_.isAdmin -eq $true }; Descending = $true }, userPrincipalName, id | + ForEach-Object { + [pscustomobject][ordered]@{ + Type = 'User' + Id = [string]$_.id + DisplayName = if ($_.userDisplayName) { [string]$_.userDisplayName } else { [string]$_.userPrincipalName } + } + } + ) + } +} diff --git a/powershell/internal/session/Format-MtConsoleText.ps1 b/powershell/internal/session/Format-MtConsoleText.ps1 index 4f4d519106..a88fc7ca5e 100644 --- a/powershell/internal/session/Format-MtConsoleText.ps1 +++ b/powershell/internal/session/Format-MtConsoleText.ps1 @@ -234,6 +234,9 @@ function Write-MtRunSummary { Product is a key: the name comes from the result's Taxonomy, else from the taxonomy registry. The product with the most passed tests is first and the others follow in descending order of passed tests; the products whose tests were all skipped are last, by name. + + When the result has the defender's path (Steps), one more line counts its steps by readiness: + "Defender's path: 3 ready · 2 blocked · 1 to check first". #> [CmdletBinding()] param( @@ -326,6 +329,16 @@ function Write-MtRunSummary { $separator = if ($Console.Unicode) { ' ' } else { ', ' } $total = "$($MaesterResults.TotalCount) tests$(if ($duration) { ", $duration" })" Write-MtConsoleLine " $($text -join $separator) $(Format-MtConsoleText "($total)" -Style Dim -Console $Console)" + if ($MaesterResults.PSObject.Properties['Steps'] -and @($MaesterResults.Steps).Count -gt 0) { + $readiness = @($MaesterResults.Steps | ForEach-Object { [string]$_.Readiness }) + $dot = if ($Console.Unicode) { " $([char]0x00B7) " } else { ', ' } + $path = @( + "$(@($readiness | Where-Object { $_ -eq 'Ready' }).Count) ready" + "$(@($readiness | Where-Object { $_ -eq 'Blocked' }).Count) blocked" + "$(@($readiness | Where-Object { $_ -eq 'Unconfirmed' }).Count) to check first" + ) -join $dot + Write-MtConsoleLine " $(Format-MtConsoleText "Defender's path:" -Style Bold -Console $Console) $path" + } if ($ReportPath) { $shown = $ReportPath if ($Console.Hyperlink) { diff --git a/powershell/lib/Maester.Engine.dll b/powershell/lib/Maester.Engine.dll index 296cb55a1c..21e768f3ea 100644 Binary files a/powershell/lib/Maester.Engine.dll and b/powershell/lib/Maester.Engine.dll differ diff --git a/powershell/public/report/Convert-MtResultsToFlatObject.ps1 b/powershell/public/report/Convert-MtResultsToFlatObject.ps1 index ab3c318936..e2376b8dc0 100644 --- a/powershell/public/report/Convert-MtResultsToFlatObject.ps1 +++ b/powershell/public/report/Convert-MtResultsToFlatObject.ps1 @@ -9,6 +9,10 @@ The function also supports reading Maester test results from a JSON file and exporting the flattened object to a CSV. + When the results have the defender's path (Steps), each row also has Step (the steps the test verifies), + Readiness (whether those steps can start: Ready, Unconfirmed or Blocked) and BlockedBy (the steps that block + them). They are empty for a test that names no step and for a step that is done. + .PARAMETER InputObject Use the Maester test results from the pipeline or as an input object (JSON). @@ -129,12 +133,20 @@ [string]$TruncationFYI = 'NOTE: DETAILS ARE TRUNCATED DUE TO FIELD SIZE LIMITATIONS. PLEASE SEE THE HTML REPORT FOR FULL DETAILS.' + $ResultObject = $null if ($PSCmdlet.ParameterSetName -eq 'FromInputObject') { - $JsonData = $InputObject.Tests + $ResultObject = $InputObject } if ($PSCmdlet.ParameterSetName -eq 'FromFile') { - $JsonData = (Get-Content -Path $JsonFilePath | ConvertFrom-Json).Tests + $ResultObject = Get-Content -Path $JsonFilePath | ConvertFrom-Json + } + $JsonData = if ($ResultObject) { $ResultObject.Tests } else { $null } + + # The steps of the defender's path, by ID, for the Step, Readiness and BlockedBy columns. + $StepById = @{} + if ($ResultObject -and $ResultObject.PSObject.Properties['Steps']) { + foreach ($Step in @($ResultObject.Steps)) { if ($Step -and $Step.Id) { $StepById[[string]$Step.Id] = $Step } } } $FlattenedResults = New-Object System.Collections.Generic.List[PSObject] @@ -156,6 +168,9 @@ $TestResultDetail = $_.ResultDetail.TestResult } + $RowSteps = @(if ($_.PSObject.Properties['Step']) { $_.Step | Where-Object { $_ } }) + $KnownSteps = @($RowSteps | Where-Object { $StepById.ContainsKey([string]$_) } | ForEach-Object { $StepById[[string]$_] }) + # Add the flattened object to the FlattenedResults list. $FlattenedResults.Add([PSCustomObject]@{ ID = $_.ID @@ -173,6 +188,9 @@ Name = $_.Name HelpUrl = $_.HelpUrl TestScriptFile = [System.IO.Path]::GetFileName($_.ScriptBlockFile) + Step = $RowSteps -join ', ' + Readiness = @($KnownSteps | ForEach-Object { $_.Readiness } | Where-Object { $_ } | Select-Object -Unique) -join ', ' + BlockedBy = @($KnownSteps | ForEach-Object { $_.BlockedBy } | Where-Object { $_ } | Select-Object -Unique) -join ', ' }) } diff --git a/powershell/public/run/Get-MtTest.ps1 b/powershell/public/run/Get-MtTest.ps1 index d566769d76..b82af18218 100644 --- a/powershell/public/run/Get-MtTest.ps1 +++ b/powershell/public/run/Get-MtTest.ps1 @@ -31,6 +31,10 @@ function Get-MtTest { .PARAMETER Suite Only tests of these suites, for example Maester, CISA or AD. + .PARAMETER Step + Only tests that verify these steps of the defender's path, for example entra.ca-require-compliant-device. + '*' wildcards are allowed (intune.*). A test matches when any of the steps in its Step attribute does. + .PARAMETER Path A Test..ps1 file or a folder of them to validate. @@ -45,6 +49,11 @@ function Get-MtTest { Shows every problem in the custom tests. + .EXAMPLE + Get-MtTest -Step 'intune.*' | Format-Table Id, Title, Step + + Lists the tests that verify a step of the defender's path in Intune. + .LINK https://maester.dev/docs/commands/Get-MtTest #> @@ -72,6 +81,9 @@ function Get-MtTest { [Parameter()] [string[]] $Suite, + [Parameter()] + [string[]] $Step, + [Parameter()] [string] $Path ) @@ -85,7 +97,7 @@ function Get-MtTest { @(Get-MtTestCatalog) } # The typed selectors, with the same matching as Invoke-Maester. - $selection = Resolve-MtSelection -RunConfig ([pscustomobject]@{ Selection = [pscustomobject]@{} }) -Product $Product -Feature $Feature -Area $Area -Severity $Severity -Suite $Suite + $selection = Resolve-MtSelection -RunConfig ([pscustomobject]@{ Selection = [pscustomobject]@{} }) -Product $Product -Feature $Feature -Area $Area -Severity $Severity -Suite $Suite -Step $Step $selectorInUse = Test-MtSelectorInUse -Selection $selection foreach ($t in $tests) { if ($Id -and -not (Test-MtIdMatch -Id $t.Id -Pattern $Id)) { continue } @@ -94,7 +106,7 @@ function Get-MtTest { $selectionTags = Get-MtSelectionTag -Test $t if (-not (@($selectionTags.Own) + @($selectionTags.Legacy) | Where-Object { $tg = $_; $Tag | Where-Object { $tg -like $_ } })) { continue } } - if ($selectorInUse -and (Test-MtSelectorMatch -Selection $selection -Product (@($t.Product) + @($t.RelatedProduct)) -Feature $t.Feature -Area $t.Area -Severity $t.Severity -Suite $t.Suite)) { continue } + if ($selectorInUse -and (Test-MtSelectorMatch -Selection $selection -Product (@($t.Product) + @($t.RelatedProduct)) -Feature $t.Feature -Area $t.Area -Severity $t.Severity -Suite $t.Suite -Step @($t.Step))) { continue } $copy = [ordered]@{} foreach ($p in $t.PSObject.Properties) { $copy[$p.Name] = $p.Value } $copy.IsValid = -not ($t.Errors -and $t.Errors.Count -gt 0) diff --git a/powershell/public/run/Invoke-Maester.ps1 b/powershell/public/run/Invoke-Maester.ps1 index d66115c165..f8f36364ff 100644 --- a/powershell/public/run/Invoke-Maester.ps1 +++ b/powershell/public/run/Invoke-Maester.ps1 @@ -199,6 +199,17 @@ # Only run the tests of these suites, for example Maester, CISA, CIS, ASD, EIDSCA, ORCA or AD. '*' wildcards are allowed. [string[]] $Suite, + # Only run the tests that verify these steps of the defender's path, for example + # entra.ca-require-compliant-device. '*' wildcards are allowed (intune.*). A test matches when any of its steps + # does. Combines with the other selectors like -Feature. Get-MtTest -Step lists the tests a step has. + [string[]] $Step, + + # Also run the tests that verify the prerequisites, at any depth, of the steps the selected tests name, so + # that Invoke-Maester -TestId MT.1001 -IncludePrerequisites checks everything MT.1001 depends on. Applied after + # the other selectors; the exclusions still apply. Preview and long-running prerequisite tests run too, except + # the Zero Trust Assessment family, which still needs -Suite ZTA or -IncludeLongRunning. + [switch] $IncludePrerequisites, + # Run these Maester Packs, by pack ID or code, for example ZTA or maester.zero-trust-assessment. # '*' wildcards are allowed. An installed pack runs only when it is named here (or turned on with # "Enabled": true in the config), so installing a pack never adds its tests to every run. A pack named @@ -534,11 +545,11 @@ $selection = Resolve-MtSelection -RunConfig $runConfig -Tag $Tag -ExcludeTag $ExcludeTag -TestId $TestId -ExcludeTestId $ExcludeTestId ` -Product $Product -ExcludeProduct $ExcludeProduct -Feature $Feature -Area $Area -Severity $Severity -Suite $Suite -Pack $Pack ` - -IncludePreview:$IncludePreview -IncludeLongRunning:$IncludeLongRunning + -Step $Step -IncludePreview:$IncludePreview -IncludeLongRunning:$IncludeLongRunning -IncludePrerequisites:$IncludePrerequisites if ($SkipBuiltIn) { $selection.BuiltIn = 'None' } # The selectors live in $selection from here on. A test runs in a child scope of this function, so a # test that reads a $Severity or $Product it never set would otherwise see the value of the parameter. - $Product = $ExcludeProduct = $Feature = $Area = $Severity = $Suite = $Pack = $null + $Product = $ExcludeProduct = $Feature = $Area = $Severity = $Suite = $Pack = $Step = $null $Tag = $selection.Tag $ExcludeTag = $selection.ExcludeTag $IncludePreview = [switch]$selection.IncludePreview @@ -870,6 +881,15 @@ if ($nativeTests.Count -gt 0) { $nativePlan = @(Resolve-MtNativePlan -Test $nativeTests -Selection $selection -RunConfig $runConfig -TenantContext $tenantContext ` -IncludeTag @($pesterFilter.Tag) -ExcludeTag $nativeExcludeTag -AutoExcludedTag @($autoExcludedTag) -DryRun:$DryRun) + # -IncludePrerequisites, applied last: the tests of every prerequisite of the steps the selected tests name. + if ($selection.IncludePrerequisites) { + $selectedSteps = @($nativePlan | Where-Object { $_.Disposition -ne 'NotRun' -or $_.ReasonCode -eq 'DryRun' } | ForEach-Object { $_.Test.Step } | Where-Object { $_ } | Select-Object -Unique) + $prerequisiteSteps = @(Get-MtStepPrerequisite -Step $selectedSteps) + if ($prerequisiteSteps.Count -gt 0) { + $nativePlan = @(Resolve-MtNativePlan -Test $nativeTests -Selection $selection -RunConfig $runConfig -TenantContext $tenantContext ` + -IncludeTag @($pesterFilter.Tag) -ExcludeTag $nativeExcludeTag -AutoExcludedTag @($autoExcludedTag) -PrerequisiteStep $prerequisiteSteps -DryRun:$DryRun) + } + } } # The services of this run: one line in the dashboard header, and the list in the scrollback. @@ -937,6 +957,10 @@ Superseded = $superseded TenantContext = $tenantContext PackSet = @($packSet) + # The defender's path: every native test the engine knows (each step lists its tests from them) and the + # measures read after the tests. + NativeTests = @($nativeTests) + Measures = @{} } Write-MtProgress -Activity 'Starting Maester' -Status 'Discovering tests to run...' -Force @@ -956,6 +980,15 @@ if ($collectDashboardMessages) { $PSDefaultParameterValues = $defaultParameterValues } $nativeRows = @(Invoke-MtNativePlan -Plan $nativePlan -RunConfig $runConfig -Selection $selection -Verbosity $Verbosity) if ($collectDashboardMessages) { $PSDefaultParameterValues = $collectingDefaults } + # The measures of the defender's path steps in scope, after the tests and while affected objects are + # collected, so that their readers can add object facts. Never fail the run over them. + if (-not $DryRun) { + try { + $runContext.Measures = Invoke-MtStepMeasure -InputObject $nativeRows -TenantContext $tenantContext -Disabled:(-not (Get-MtMeasureSetting -RunConfig $runConfig).Enabled) + } catch { + Write-Verbose "The measures of the defender's path could not be read: $($_.Exception.Message)" + } + } } $nativeTimer.Stop() $pesterConfig = $null diff --git a/powershell/tests/functions/MeasureReaders.Tests.ps1 b/powershell/tests/functions/MeasureReaders.Tests.ps1 new file mode 100644 index 0000000000..528de90b80 --- /dev/null +++ b/powershell/tests/functions/MeasureReaders.Tests.ps1 @@ -0,0 +1,175 @@ +# The readers of the defender's path measures (docs/proposals/defenders-path.md, section 11, and +# powershell/assets/MaesterMeasures.psd1): what each one reads from Graph, what it counts and which objects it lists. +BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force -WarningAction SilentlyContinue +} + +Describe 'The measure registry' { + It 'Names a reader that exists for every measure, and has no problems' { + InModuleScope Maester { + $registry = Get-MtMeasureRegistry + $registry.Problems | Should -BeNullOrEmpty + $registry.Measures.Keys | Should -Be @('devices-compliant', 'mfa-capable') + foreach ($measure in $registry.Measures.Values) { + Get-Command -Name $measure.Function -CommandType Function | Should -Not -BeNullOrEmpty + $measure.Caveat | Should -Not -BeNullOrEmpty + } + # Only Intune marks devices compliant, also for a compliance partner's devices. + $registry.Measures['devices-compliant'].License | Should -Be @('INTUNE_A') + } + } +} + +Describe 'Get-MtDeviceComplianceShare' { + BeforeAll { + $script:devices = @( + [pscustomobject]@{ id = 'd1'; displayName = 'Compliant laptop'; approximateLastSignInDateTime = '2026-11-04T08:00:00Z'; isCompliant = $true; isManaged = $true } + [pscustomobject]@{ id = 'd2'; displayName = 'Noncompliant laptop'; approximateLastSignInDateTime = '2026-10-20T08:00:00Z'; isCompliant = $false; isManaged = $true } + [pscustomobject]@{ id = 'd3'; displayName = 'Personal phone'; approximateLastSignInDateTime = '2026-11-03T08:00:00Z'; isCompliant = $null; isManaged = $false } + [pscustomobject]@{ id = 'd4'; displayName = 'Compliant phone'; approximateLastSignInDateTime = '2026-11-01T08:00:00Z'; isCompliant = $true; isManaged = $true } + ) + } + + It 'Counts the compliant devices and lists the others, most recent sign-in first' { + InModuleScope Maester -Parameters @{ Devices = $script:devices } { + Mock Invoke-MtGraphRequest { $Devices } -ParameterFilter { $RelativeUri -eq 'devices' } + + $result = Get-MtDeviceComplianceShare + + $result.Count | Should -Be 2 + $result.Total | Should -Be 4 + $result.Objects.Id | Should -Be @('d3', 'd2') + $result.Objects[0].Type | Should -Be 'Device' + $result.Objects[0].DisplayName | Should -Be 'Personal phone' + $result.Objects[0].PSObject.Properties.Name | Should -Be @('Type', 'Id', 'DisplayName') + } + } + + It 'Reads the enabled devices that signed in since the start of the UTC day, SignedInWithinDays ago' { + InModuleScope Maester { + Mock Invoke-MtGraphRequest { } + $since = [datetime]::UtcNow.Date.AddDays(-14).ToString('yyyy-MM-ddTHH:mm:ssZ', [cultureinfo]::InvariantCulture) + + $null = Get-MtDeviceComplianceShare -SignedInWithinDays 14 + + Should -Invoke Invoke-MtGraphRequest -Times 1 -Exactly -ParameterFilter { + $RelativeUri -eq 'devices' -and + $Filter -eq "accountEnabled eq true and approximateLastSignInDateTime ge $since" -and + $Select -contains 'isCompliant' -and $Select -contains 'isManaged' -and + $QueryParameters['$count'] -eq 'true' -and -not $DisableCache + } + } + } + + It 'Returns zero of zero when no device signed in' { + InModuleScope Maester { + Mock Invoke-MtGraphRequest { } + + $result = Get-MtDeviceComplianceShare + + $result.Count | Should -Be 0 + $result.Total | Should -Be 0 + @($result.Objects).Count | Should -Be 0 + } + } +} + +Describe 'Get-MtMfaCapableShare' { + BeforeAll { + $script:report = @( + [pscustomobject]@{ id = 'u1'; userPrincipalName = 'ann@contoso.com'; userDisplayName = 'Ann'; userType = 'member'; isMfaCapable = $true; isAdmin = $false } + # Bob registered a method the authentication methods policy no longer allows, so he can't complete MFA. + [pscustomobject]@{ id = 'u2'; userPrincipalName = 'bob@contoso.com'; userDisplayName = 'Bob'; userType = 'member'; isMfaRegistered = $true; isMfaCapable = $false; isAdmin = $false } + [pscustomobject]@{ id = 'u3'; userPrincipalName = 'admin@contoso.com'; userDisplayName = 'Admin'; userType = 'member'; isMfaCapable = $false; isAdmin = $true } + [pscustomobject]@{ id = 'g1'; userPrincipalName = 'guest#EXT#@contoso.com'; userDisplayName = 'Guest'; userType = 'guest'; isMfaCapable = $false; isAdmin = $false } + [pscustomobject]@{ id = 'x1'; userPrincipalName = 'left@contoso.com'; userDisplayName = 'Left'; userType = 'member'; isMfaCapable = $false; isAdmin = $false } + [pscustomobject]@{ id = 'bg1'; userPrincipalName = 'bg1@contoso.com'; userDisplayName = 'Break glass 1'; userType = 'member'; isMfaCapable = $false; isAdmin = $true } + [pscustomobject]@{ id = 'bg2'; userPrincipalName = 'bg2@contoso.com'; userDisplayName = 'Break glass 2'; userType = 'member'; isMfaCapable = $false; isAdmin = $true } + [pscustomobject]@{ id = 's1'; userPrincipalName = 'Sync_SRV@contoso.onmicrosoft.com'; userDisplayName = 'On-Premises Directory Synchronization Service Account'; userType = 'member'; isMfaCapable = $false; isAdmin = $false } + [pscustomobject]@{ id = 'u4'; userPrincipalName = 'cat@contoso.com'; userDisplayName = 'Cat'; userType = 'member'; isMfaCapable = $true; isAdmin = $false } + ) + } + + Context 'With emergency access accounts and a sync account' { + BeforeEach { + # Defined outside InModuleScope, so the mock bodies can read the report from this file's scope. + Mock -ModuleName Maester Invoke-MtGraphRequest { $script:report } -ParameterFilter { $RelativeUri -eq 'reports/authenticationMethods/userRegistrationDetails' } + Mock -ModuleName Maester Invoke-MtGraphRequest { @([pscustomobject]@{ id = 'x1' }) } -ParameterFilter { $RelativeUri -eq 'users' } + Mock -ModuleName Maester Get-MtEmergencyAccessAccount { + [pscustomobject]@{ ObjectId = 'bg1'; DisplayName = 'Break glass 1'; Type = 'user' } + [pscustomobject]@{ ObjectId = '7c2c5a3e-0d4b-4f7a-9a51-2f0c8e6d1b11'; DisplayName = 'Break glass group'; Type = 'group' } + } + Mock -ModuleName Maester Get-MtGroupMember { + [pscustomobject]@{ id = 'bg2'; '@odata.type' = '#microsoft.graph.user' } + [pscustomobject]@{ id = 'nested'; '@odata.type' = '#microsoft.graph.group' } + } -ParameterFilter { $GroupId -eq '7c2c5a3e-0d4b-4f7a-9a51-2f0c8e6d1b11' -and $Recursive } + Mock -ModuleName Maester Get-MtRoleMember { + [pscustomobject]@{ id = 's1'; '@odata.type' = '#microsoft.graph.user' } + [pscustomobject]@{ id = 'u1'; '@odata.type' = '#microsoft.graph.servicePrincipal' } + } + } + + It 'Counts the member users who can complete MFA, leaving out guests, disabled, emergency access and sync accounts' { + InModuleScope Maester { + $result = Get-MtMfaCapableShare + + $result.Count | Should -Be 2 + $result.Total | Should -Be 4 + } + } + + It 'Lists the users who cannot complete MFA, administrators first' { + InModuleScope Maester { + $result = Get-MtMfaCapableShare + + $result.Objects.Id | Should -Be @('u3', 'u2') + $result.Objects[0].Type | Should -Be 'User' + $result.Objects[0].DisplayName | Should -Be 'Admin' + $result.Objects[0].PSObject.Properties.Name | Should -Be @('Type', 'Id', 'DisplayName') + } + } + + It 'Reads the whole report, so other readers share its cache entry, and only the disabled users' { + InModuleScope Maester { + $null = Get-MtMfaCapableShare + + Should -Invoke Invoke-MtGraphRequest -Times 1 -Exactly -ParameterFilter { + $RelativeUri -eq 'reports/authenticationMethods/userRegistrationDetails' -and -not $Select -and -not $Filter -and -not $DisableCache + } + Should -Invoke Invoke-MtGraphRequest -Times 1 -Exactly -ParameterFilter { + $RelativeUri -eq 'users' -and $Filter -eq 'accountEnabled eq false' -and -not $DisableCache + } + Should -Invoke Get-MtRoleMember -Times 1 -Exactly -ParameterFilter { + ($Role -join ',') -eq 'DirectorySynchronizationAccounts,OnPremisesDirectorySyncAccount' + } + } + } + } + + It 'Counts every enabled member user when no emergency access account is configured' { + InModuleScope Maester -Parameters @{ Report = $script:report } { + Mock Invoke-MtGraphRequest { $Report } -ParameterFilter { $RelativeUri -eq 'reports/authenticationMethods/userRegistrationDetails' } + Mock Invoke-MtGraphRequest { } -ParameterFilter { $RelativeUri -eq 'users' } + Mock Get-MtEmergencyAccessAccount { } + Mock Get-MtGroupMember { } + Mock Get-MtRoleMember { } + + $result = Get-MtMfaCapableShare + + $result.Count | Should -Be 2 + $result.Total | Should -Be 8 + Should -Invoke Get-MtGroupMember -Times 0 + } + } + + It 'Stops when a configured emergency access account cannot be resolved' { + InModuleScope Maester -Parameters @{ Report = $script:report } { + Mock Invoke-MtGraphRequest { $Report } -ParameterFilter { $RelativeUri -eq 'reports/authenticationMethods/userRegistrationDetails' } + Mock Invoke-MtGraphRequest { } -ParameterFilter { $RelativeUri -eq 'users' } + Mock Get-MtEmergencyAccessAccount { throw 'Could not resolve configured emergency access object(s): user: gone@contoso.com (not found)' } + Mock Get-MtRoleMember { } + + { Get-MtMfaCapableShare } | Should -Throw '*Could not resolve configured emergency access*' + } + } +} diff --git a/powershell/tests/functions/engine/DefendersPath.Tests.ps1 b/powershell/tests/functions/engine/DefendersPath.Tests.ps1 new file mode 100644 index 0000000000..adb0f1125c --- /dev/null +++ b/powershell/tests/functions/engine/DefendersPath.Tests.ps1 @@ -0,0 +1,512 @@ +# The engine of the defender's path (docs/proposals/defenders-path.md, sections 6 to 12, milestone M3): the steps in +# scope, their status, readiness and rank (Get-MtResultStep), the priority it ranks by (Get-MtTestPriority), the +# measures read after the tests (Invoke-MtStepMeasure), LastKnown in the previous result, selection by -Step and +# -IncludePrerequisites, and the CSV, Markdown and console outputs. +# +# Most cases use a fixture catalogue written to TestDrive: +# +# entra.base no prerequisite +# intune.policies no prerequisite +# intune.compliant requires intune.policies; decided by the devices-compliant measure (95%) +# entra.hybrid only when hybrid-identity +# entra.goal requires entra.base and intune.policies, and one of intune.compliant and entra.hybrid +# defender.other unrelated, the step of a second goal +BeforeAll { + Import-Module "$PSScriptRoot/../../../Maester.psd1" -Force -WarningAction SilentlyContinue + + $source = [ordered]@{ Url = 'https://learn.microsoft.com/entra/identity/example'; Note = 'Do the other step first.'; Reviewed = '2026-11-05' } + $files = @{ + 'goals.json' = [ordered]@{ Goals = @( + [ordered]@{ Id = 'goal-one'; Title = 'Goal one'; Summary = 'What goal one achieves.'; Step = 'entra.goal' } + [ordered]@{ Id = 'goal-two'; Title = 'Goal two'; Summary = 'What goal two achieves.'; Step = 'defender.other' } + ) + } + 'entra.json' = [ordered]@{ Product = 'entra'; Steps = @( + [ordered]@{ Id = 'entra.base'; Title = 'Base'; Summary = 'Base.'; Sources = @($source) } + [ordered]@{ Id = 'entra.hybrid'; Title = 'Hybrid'; Summary = 'Hybrid.'; OnlyWhen = @('hybrid-identity'); Unchecked = 'No check.'; Sources = @($source) } + [ordered]@{ + Id = 'entra.goal'; Title = 'Goal step'; Summary = 'Goal.'; Requires = @('entra.base', 'intune.policies') + RequiresOneOf = @(, @('intune.compliant', 'entra.hybrid')); Rollout = @('Report-only first.'); Sources = @($source) + } + ) + } + 'intune.json' = [ordered]@{ Product = 'intune'; Steps = @( + [ordered]@{ Id = 'intune.policies'; Title = 'Policies'; Summary = 'Policies.'; Sources = @($source) } + [ordered]@{ Id = 'intune.compliant'; Title = 'Compliant'; Summary = 'Compliant.'; Requires = @('intune.policies'); Measure = [ordered]@{ Key = 'devices-compliant'; MinimumShare = 95 }; Sources = @($source) } + ) + } + 'defender.json' = [ordered]@{ Product = 'defender'; Steps = @([ordered]@{ Id = 'defender.other'; Title = 'Other'; Summary = 'Other.'; Sources = @($source) }) } + } + $folder = Join-Path $TestDrive 'steps' + $null = New-Item -ItemType Directory -Path $folder + foreach ($name in $files.Keys) { ConvertTo-Json -InputObject $files[$name] -Depth 10 | Set-Content -LiteralPath (Join-Path $folder $name) } + $script:catalog = InModuleScope Maester -Parameters @{ F = $folder } { Get-MtStepCatalog -Path $F } + + # A result row. + function New-Row { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Test helper that returns an object.')] + param([string] $Id, [string] $Result, [string[]] $Step, [string] $Severity = 'High', [string] $ReasonCode) + [pscustomobject]@{ + Id = $Id; Title = "Title of $Id"; Result = $Result; ReasonCode = $(if ($ReasonCode) { $ReasonCode } else { $null }); Step = $Step; Severity = $Severity + UserImpact = 'Low'; ImplementationCost = 'Low'; Mitre = @(); Control = @(); Benchmark = $null; ParentId = $null + } + } + # Get-MtResultStep on the fixture catalogue. + function Get-Path { + param([object[]] $Row, [object[]] $Inventory = @(), [hashtable] $Measure = @{}, [object] $TenantContext = [pscustomobject]@{ HybridIdentity = $false }, [hashtable] $Extra = @{}) + InModuleScope Maester -Parameters @{ R = $Row; I = $Inventory; M = $Measure; T = $TenantContext; C = $script:catalog; X = $Extra } { + Get-MtResultStep -InputObject $R -Inventory $I -Measure $M -TenantContext $T -Catalog $C @X + } + } + $script:halfCompliant = @{ 'devices-compliant' = @{ Count = 50; Total = 100; Objects = @( + [pscustomobject]@{ Type = 'Device'; Id = 'd1'; DisplayName = 'Laptop' } + [pscustomobject]@{ Type = 'Device'; Id = 'd2'; DisplayName = 'Phone' } + ); ReadAt = '2026-11-06T08:00:00Z'; ReasonCode = $null + } + } + $script:rows = @( + (New-Row -Id 'T.goal' -Result 'Failed' -Step @('entra.goal')) + (New-Row -Id 'T.base' -Result 'Passed' -Step @('entra.base')) + (New-Row -Id 'T.pol' -Result 'Failed' -Step @('intune.policies') -Severity 'Medium') + ) +} + +Describe 'Get-MtTestPriority' { + It 'Gives the numbers of priority() in the report' -ForEach @( + @{ Name = 'every attribute'; Row = [pscustomobject]@{ Severity = 'High'; UserImpact = 'Low'; ImplementationCost = 'Medium'; Mitre = @('T1110', 'T1078', 'None'); Control = @('a', 'b'); Benchmark = [pscustomobject]@{ Id = 'x' } }; Expected = 17.7 } + @{ Name = 'no attributes'; Row = [pscustomobject]@{ Severity = 'Unknown' }; Expected = 11 } + @{ Name = 'Info, hard to fix'; Row = [pscustomobject]@{ Severity = 'Info'; UserImpact = 'High'; ImplementationCost = 'High' }; Expected = 0 } + @{ Name = 'severity from the result detail'; Row = [pscustomobject]@{ Severity = ''; ResultDetail = [pscustomobject]@{ Severity = 'Critical' } }; Expected = 19 } + @{ Name = 'at most three techniques'; Row = [pscustomobject]@{ Severity = 'Low'; UserImpact = 'Low'; ImplementationCost = 'Low'; Mitre = @('T1', 'T2', 'T3', 'T4', 'T5') }; Expected = 10.9 } + ) { + $value = InModuleScope Maester -Parameters @{ R = $Row } { Get-MtTestPriority -InputObject $R } + [math]::Round($value, 6) | Should -Be $Expected -Because $Name + } +} + +Describe 'Get-MtStepPrerequisite and Get-MtStepScope' { + It 'Follows Requires, RequiresOneOf and RecommendedFirst down every level' { + $found = InModuleScope Maester -Parameters @{ C = $script:catalog } { @(Get-MtStepPrerequisite -Step 'entra.goal' -Catalog $C) } + $found | Sort-Object | Should -Be @('entra.base', 'entra.hybrid', 'intune.compliant', 'intune.policies') + } + + It 'Scopes to the steps that rows that ran name, and their prerequisites' { + $rows = @((New-Row -Id 'T.1' -Result 'Passed' -Step @('intune.compliant')), (New-Row -Id 'T.2' -Result 'NotRun' -Step @('defender.other')), (New-Row -Id 'T.3' -Result 'Passed' -Step @('not.in-catalog'))) + $scope = InModuleScope Maester -Parameters @{ R = $rows; C = $script:catalog } { Get-MtStepScope -InputObject $R -Catalog $C } + $scope.Named | Should -Be @('intune.compliant') + $scope.Steps | Should -Be @('intune.policies', 'intune.compliant') + } +} + +Describe 'Get-MtResultStep' { + It 'Returns nothing when no row that ran names a step' { + Get-Path -Row @((New-Row -Id 'T.1' -Result 'Passed' -Step @()), (New-Row -Id 'T.2' -Result 'NotRun' -Step @('entra.base'))) | Should -BeNullOrEmpty + } + + Context 'A run with a failed goal step, a failed prerequisite and a measure below its threshold' { + BeforeAll { + $inventory = @([pscustomobject]@{ Id = 'T.goal'; Step = @('entra.goal') }, [pscustomobject]@{ Id = 'T.goal2'; Step = @('entra.goal') }) + $script:path = Get-Path -Row $script:rows -Inventory $inventory -Measure $script:halfCompliant + $script:byId = @{} + foreach ($s in $script:path.Steps) { $script:byId[$s.Id] = $s } + } + + It 'Lists the steps in scope and leaves the others out' { + @($script:path.Steps.Id | Sort-Object) | Should -Be @('entra.base', 'entra.goal', 'entra.hybrid', 'intune.compliant', 'intune.policies') + } + + It 'Works out each status' { + $byId['entra.base'].Status | Should -Be 'Done' + $byId['intune.policies'].Status | Should -Be 'NotDone' + $byId['intune.compliant'].Status | Should -Be 'NotDone' + $byId['entra.goal'].Status | Should -Be 'NotDone' + $byId['entra.hybrid'].Status | Should -Be 'NotApplicable' + $byId['entra.hybrid'].Reason | Should -Be 'ConditionNotMet' + } + + It 'Blocks a step on a NotDone requirement and on a group whose applicable steps are all NotDone' { + $byId['intune.policies'].Readiness | Should -Be 'Ready' + $byId['intune.compliant'].Readiness | Should -Be 'Blocked' + $byId['intune.compliant'].BlockedBy | Should -Be @('intune.policies') + $byId['entra.goal'].Readiness | Should -Be 'Blocked' + $byId['entra.goal'].BlockedBy | Should -Be @('intune.policies', 'intune.compliant') + $byId['entra.base'].Readiness | Should -BeNullOrEmpty + } + + It 'Ranks Ready first, prerequisites before their dependents, then Done and Not applicable' { + @($script:path.Steps.Id) | Should -Be @('intune.policies', 'intune.compliant', 'entra.goal', 'entra.base', 'entra.hybrid') + # ForEach-Object, not .Rank: an array's own Rank property (its number of dimensions) wins over member enumeration. + @($script:path.Steps | ForEach-Object Rank) | Should -Be @(1, 2, 3, 4, 5) + $byId['intune.policies'].Unlocks | Should -Be @('intune.compliant', 'entra.goal') + } + + It 'Lists the tests from the inventory, with NotInRun for a test that has no row' { + $tests = $byId['entra.goal'].Tests + $tests.Id | Should -Be @('T.goal', 'T.goal2') + $tests[0].Result | Should -Be 'Failed' + $tests[1].Result | Should -Be 'NotRun' + $tests[1].ReasonCode | Should -Be 'NotInRun' + } + + It 'Writes the measure in the shape of the result' { + $m = $byId['intune.compliant'].Measure + $m.PSObject.Properties.Name | Should -Be @('Key', 'Count', 'Total', 'Share', 'MinimumShare', 'Met', 'ReadAt', 'Caveat', 'ObjectCount', 'Objects', 'ReasonCode') + $m.Key | Should -Be 'devices-compliant' + $m.Share | Should -Be 50 + $m.MinimumShare | Should -Be 95 + $m.Met | Should -BeFalse + $m.ObjectCount | Should -Be 2 + $m.Objects.Id | Should -Be @('d1', 'd2') + $m.Caveat | Should -Not -BeNullOrEmpty + $m.ReasonCode | Should -BeNullOrEmpty + $byId['entra.base'].Measure | Should -BeNullOrEmpty + } + + It 'Lists the goals in scope with their progress' { + @($script:path.Goals).Count | Should -Be 1 + $goal = $script:path.Goals[0] + $goal.Id | Should -Be 'goal-one' + $goal.Steps | Should -Be @('entra.base', 'intune.policies', 'intune.compliant', 'entra.hybrid', 'entra.goal') + $goal.Applicable | Should -Be 4 + $goal.Done | Should -Be 1 + $goal.Status | Should -Be 'InProgress' + $byId['entra.base'].Goals | Should -Be @('goal-one') + } + + It 'Serialises to JSON with the objects of the measure intact' { + $json = [pscustomobject]@{ Steps = $script:path.Steps } | ConvertTo-Json -Depth 5 | ConvertFrom-Json + ($json.Steps | Where-Object Id -EQ 'intune.compliant').Measure.Objects[0].DisplayName | Should -Be 'Laptop' + ($json.Steps | Where-Object Id -EQ 'entra.goal').RequiresOneOf[0] | Should -Be @('intune.compliant', 'entra.hybrid') + } + } + + It 'Meets the threshold the run config sets, and keeps at most -MaxObjects objects' { + $path = Get-Path -Row $script:rows -Measure $script:halfCompliant -Extra @{ MinimumShare = @{ 'devices-compliant' = 40 }; MaxObjects = 1 } + $step = $path.Steps | Where-Object Id -EQ 'intune.compliant' + $step.Status | Should -Be 'Done' + $step.Measure.MinimumShare | Should -Be 40 + $step.Measure.Met | Should -BeTrue + @($step.Measure.Objects).Count | Should -Be 1 + $step.Measure.ObjectCount | Should -Be 2 + } + + It 'Is Unknown, never Not done, when a test is Investigate or a measure could not be read, and the step that needs it is Unconfirmed' { + $rows = @((New-Row -Id 'T.goal' -Result 'Failed' -Step @('entra.goal')), (New-Row -Id 'T.base' -Result 'Investigate' -Step @('entra.base')), (New-Row -Id 'T.pol' -Result 'Passed' -Step @('intune.policies'))) + $measure = @{ 'devices-compliant' = @{ ReasonCode = 'LicenseNotFound'; ReadAt = $null } } + $path = Get-Path -Row $rows -Measure $measure + $byId = @{}; foreach ($s in $path.Steps) { $byId[$s.Id] = $s } + $byId['entra.base'].Status | Should -Be 'Unknown' + $byId['entra.base'].Reason | Should -Be 'Investigate' + $byId['intune.compliant'].Status | Should -Be 'Unknown' + $byId['intune.compliant'].Reason | Should -Be 'LicenseNotFound' + $byId['intune.compliant'].Measure.ReasonCode | Should -Be 'LicenseNotFound' + $byId['entra.goal'].Readiness | Should -Be 'Unconfirmed' + $byId['entra.goal'].Unconfirmed | Should -Be @('entra.base', 'intune.compliant') + $byId['entra.goal'].BlockedBy | Should -BeNullOrEmpty + } + + It 'Is Unknown when an OnlyWhen condition cannot be read' { + $path = Get-Path -Row $script:rows -Measure $script:halfCompliant -TenantContext $null + ($path.Steps | Where-Object Id -EQ 'entra.hybrid').Status | Should -Be 'Unknown' + ($path.Steps | Where-Object Id -EQ 'entra.hybrid').Reason | Should -Be 'ConditionUnknown' + } + + It 'Is Not applicable when every verifying test that ran was skipped as NotApplicable' { + $path = Get-Path -Row @((New-Row -Id 'T.base' -Result 'Skipped' -Step @('entra.base') -ReasonCode 'NotApplicable')) + $path.Steps[0].Status | Should -Be 'NotApplicable' + $path.Steps[0].Reason | Should -Be 'TestsNotApplicable' + } + + It 'Says why a step is Not checked, and gives the Earlier status of an earlier run' { + $inventory = @([pscustomobject]@{ Id = 'T.base'; Step = @('entra.base') }) + $lastKnown = [pscustomobject]@{ 'T.base' = [pscustomobject]@{ Result = 'Passed'; ReasonCode = $null; ExecutedAt = '2026-11-01T08:00:00.0000000+00:00'; File = 'TestResults-old.json' } } + $path = Get-Path -Row @((New-Row -Id 'T.goal' -Result 'Failed' -Step @('entra.goal'))) -Inventory $inventory -Extra @{ MeasuresDisabled = $true; LastKnown = $lastKnown } + $byId = @{}; foreach ($s in $path.Steps) { $byId[$s.Id] = $s } + $byId['entra.base'].Status | Should -Be 'NotChecked' + $byId['entra.base'].Reason | Should -Be 'NotSelected' + $byId['entra.base'].Earlier.Status | Should -Be 'Done' + $byId['entra.base'].Earlier.File | Should -Be 'TestResults-old.json' + $byId['intune.policies'].Reason | Should -Be 'NoCheck' + $byId['intune.policies'].Earlier | Should -BeNullOrEmpty + $byId['intune.compliant'].Reason | Should -Be 'MeasureOff' + $byId['intune.compliant'].Measure.ReasonCode | Should -Be 'MeasureOff' + $goal = $path.Goals[0] + $goal.NotChecked | Should -Be 3 + $goal.Status | Should -Be 'NotStarted' + } +} + +Describe 'Invoke-MtStepMeasure' { + BeforeAll { + $registryFile = Join-Path $TestDrive 'measures.psd1' + @" +@{ Measures = @(@{ Key = 'devices-compliant'; Function = 'Get-MtDeviceComplianceShare'; Title = 'Devices'; Unit = 'devices'; Service = 'Graph'; License = 'INTUNE_A'; Permission = 'Graph:Scope:Device.Read.All | Graph:Scope:Directory.Read.All' }) } +"@ | Set-Content -LiteralPath $registryFile + $script:registry = InModuleScope Maester -Parameters @{ F = $registryFile } { Get-MtMeasureRegistry -Path $F } + function New-Context { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Test helper that returns an object.')] + param([bool] $Graph = $true, [string[]] $Plans = @('INTUNE_A'), [string[]] $Scopes = @('Directory.Read.All')) + [pscustomobject]@{ + Platform = 'Linux'; TenantType = 'Workforce'; Cloud = 'Commercial'; Services = [pscustomobject]@{ Graph = $Graph } + Licenses = [pscustomobject]@{ State = 'Known'; ServicePlanNames = $Plans; ServicePlanIds = @(); SkuIds = @() }; Scopes = $Scopes + } + } + function Read-Measure { + param([object] $Context, [switch] $Disabled, [switch] $Throw) + InModuleScope Maester -Parameters @{ T = $Context; D = [bool]$Disabled; E = [bool]$Throw; R = $script:rows; C = $script:catalog; G = $script:registry } { + if ($E) { Mock Get-MtDeviceComplianceShare { throw 'Service unavailable' } } + else { Mock Get-MtDeviceComplianceShare { [pscustomobject]@{ Count = 3; Total = 4; Objects = @([pscustomobject]@{ Type = 'Device'; Id = 'd1'; DisplayName = 'Laptop' }) } } } + Invoke-MtStepMeasure -InputObject $R -TenantContext $T -Disabled:$D -Catalog $C -Registry $G + } + } + } + + It 'Reads each measure of the steps in scope once' { + $readings = Read-Measure (New-Context) + @($readings.Keys) | Should -Be @('devices-compliant') + $readings['devices-compliant'].Count | Should -Be 3 + $readings['devices-compliant'].Total | Should -Be 4 + $readings['devices-compliant'].ReasonCode | Should -BeNullOrEmpty + $readings['devices-compliant'].ReadAt | Should -Match '^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ$' + } + + It 'Gates a measure like a test: ' -ForEach @( + @{ Code = 'ServiceNotConnected'; Graph = $false; Plans = @('INTUNE_A'); Scopes = @('Directory.Read.All') } + @{ Code = 'LicenseNotFound'; Graph = $true; Plans = @('AAD_PREMIUM'); Scopes = @('Directory.Read.All') } + @{ Code = 'PermissionNotGranted'; Graph = $true; Plans = @('INTUNE_A'); Scopes = @('User.Read.All') } + ) { + $readings = Read-Measure (New-Context -Graph $Graph -Plans $Plans -Scopes $Scopes) + $readings['devices-compliant'].ReasonCode | Should -Be $Code + $readings['devices-compliant'].Count | Should -BeNullOrEmpty + } + + It 'Accepts the ReadWrite form of a permission' { + (Read-Measure (New-Context -Scopes @('Device.ReadWrite.All')))['devices-compliant'].ReasonCode | Should -BeNullOrEmpty + } + + It 'Records MeasureError when the reader throws' { + $readings = Read-Measure (New-Context) -Throw + $readings['devices-compliant'].ReasonCode | Should -Be 'MeasureError' + $readings['devices-compliant'].ReasonDetail | Should -BeLike '*Service unavailable*' + } + + It 'Reads nothing when the run config turns measures off' { + (Read-Measure (New-Context) -Disabled).Count | Should -Be 0 + } +} + +Describe 'Get-MtMeasureSetting and the Measures section of the run config' { + It 'Defaults to on, with no thresholds' { + $setting = InModuleScope Maester { Get-MtMeasureSetting -RunConfig $null } + $setting.Enabled | Should -BeTrue + $setting.MinimumShare.Count | Should -Be 0 + } + + It 'Reads Enabled and MinimumShare from a resolved config' { + $setting = InModuleScope Maester { + $config = Resolve-MtRunConfig -Config ([pscustomobject]@{ Measures = [pscustomobject]@{ Enabled = $false; MinimumShare = [pscustomobject]@{ 'devices-compliant' = [long]80 } } }) + Get-MtMeasureSetting -RunConfig $config + } + $setting.Enabled | Should -BeFalse + $setting.MinimumShare['devices-compliant'] | Should -Be 80 + } + + It 'Rejects a threshold outside 1 to 100' { + { InModuleScope Maester { Resolve-MtRunConfig -Config ([pscustomobject]@{ Measures = [pscustomobject]@{ MinimumShare = [pscustomobject]@{ 'devices-compliant' = [long]120 } } }) } } | + Should -Throw '*Measures.MinimumShare.devices-compliant*' + } +} + +Describe 'Get-MtPreviousResult -LastKnownId' { + BeforeAll { + $script:history = Join-Path $TestDrive 'history' + $null = New-Item -ItemType Directory -Path $script:history + $write = { + param($name, $executedAt, $tests, $age) + $path = Join-Path $script:history $name + [ordered]@{ TotalCount = @($tests).Count; PassedCount = 0; ExecutedAt = $executedAt; TenantId = 't1'; Tests = @($tests) } | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $path + (Get-Item -LiteralPath $path).LastWriteTimeUtc = [datetime]::UtcNow.AddHours(-$age) + } + & $write 'TestResults-old.json' '2026-11-01T08:00:00Z' @(@{ Id = 'X'; Result = 'Passed' }, @{ Id = 'Y'; Result = 'Failed' }) 48 + & $write 'TestResults-new.json' '2026-11-05T08:00:00Z' @(@{ Id = 'X'; Result = 'NotRun'; ReasonCode = 'NotSelected' }, @{ Id = 'Z'; Result = 'Passed' }) 1 + } + + It 'Gives the newest earlier result that ran each test' { + $previous = InModuleScope Maester -Parameters @{ F = $script:history } { Get-MtPreviousResult -Folder $F -TenantId 't1' -LastKnownId 'X', 'Y', 'W' } + $previous.File | Should -Be 'TestResults-new.json' + $previous.LastKnown.X.Result | Should -Be 'Passed' + $previous.LastKnown.X.File | Should -Be 'TestResults-old.json' + $previous.LastKnown.Y.Result | Should -Be 'Failed' + $previous.LastKnown.PSObject.Properties['W'] | Should -BeNullOrEmpty + } + + It 'Leaves LastKnown out when no ID is asked for' { + $previous = InModuleScope Maester -Parameters @{ F = $script:history } { Get-MtPreviousResult -Folder $F -TenantId 't1' } + $previous.PSObject.Properties['LastKnown'] | Should -BeNullOrEmpty + } +} + +Describe 'Selection by step' { + BeforeAll { + $script:prqFolder = Join-Path $TestDrive 'prerequisites' + $null = New-Item -ItemType Directory -Path $script:prqFolder + $tests = @( + @{ Id = 'PRQ.1'; Extra = "Step = 'entra.ca-require-compliant-device'" } + @{ Id = 'PRQ.2'; Extra = "Step = 'intune.compliance-policies', Lifecycle = 'Preview'" } + @{ Id = 'PRQ.3'; Extra = "Step = 'defender.spf'" } + ) + foreach ($t in $tests) { + $name = 'Test-' + ($t.Id -replace '[^A-Za-z0-9]', '') + @" +function $name { + [MaesterTest(Id = '$($t.Id)', Title = 'Title of $($t.Id)', Severity = 'High', $($t.Extra))] + [CmdletBinding()] + param() + `$true +} +"@ | Set-Content (Join-Path $script:prqFolder "Test.$($t.Id).ps1") + "Description of $($t.Id).`n`n`n%TestResult%" | Set-Content (Join-Path $script:prqFolder "Test.$($t.Id).md") + } + # The plan rows of the fixture tests, with a second pass for -IncludePrerequisites as Invoke-Maester makes it. + function Get-StepPlan { + param([hashtable] $Parameters = @{}) + InModuleScope Maester -Parameters @{ P = $Parameters; F = $script:prqFolder } { + $tests = @(Get-MtNativeTestInventory -Path $F -Root $F) + $runConfig = Resolve-MtRunConfig -Config @{} + $selection = Resolve-MtSelection -RunConfig $runConfig @P + # Preview tests are left out by default, as Invoke-Maester does. + $auto = @(if (-not $selection.IncludePreview) { 'Preview' }) + $plan = @(Resolve-MtNativePlan -Test $tests -Selection $selection -RunConfig $runConfig -AutoExcludedTag $auto -ExcludeTag $auto) + if ($selection.IncludePrerequisites) { + $steps = @($plan | Where-Object { $_.Disposition -ne 'NotRun' } | ForEach-Object { $_.Test.Step } | Select-Object -Unique) + $plan = @(Resolve-MtNativePlan -Test $tests -Selection $selection -RunConfig $runConfig -AutoExcludedTag $auto -ExcludeTag $auto -PrerequisiteStep @(Get-MtStepPrerequisite -Step $steps)) + } + $plan + } + } + } + + It '-Step selects the tests that verify a matching step, with wildcards' { + $plan = Get-StepPlan @{ Step = 'Intune.*', 'defender.spf'; IncludePreview = $true } + @($plan | Where-Object Disposition -EQ 'Run' | ForEach-Object { $_.Test.Id } | Sort-Object) | Should -Be @('PRQ.2', 'PRQ.3') + ($plan | Where-Object { $_.Test.Id -eq 'PRQ.1' }).ReasonCode | Should -Be 'NotSelected' + } + + It '-IncludePrerequisites adds the tests of the prerequisites, preview tests too, and nothing else' { + $plan = Get-StepPlan @{ TestId = 'PRQ.1'; IncludePrerequisites = $true } + @($plan | Where-Object Disposition -EQ 'Run' | ForEach-Object { $_.Test.Id } | Sort-Object) | Should -Be @('PRQ.1', 'PRQ.2') + ($plan | Where-Object { $_.Test.Id -eq 'PRQ.2' }).Prerequisite | Should -BeTrue + ($plan | Where-Object { $_.Test.Id -eq 'PRQ.3' }).Disposition | Should -Be 'NotRun' + } + + It 'Keeps the exclusions when it adds prerequisites' { + $plan = Get-StepPlan @{ TestId = 'PRQ.1'; ExcludeTestId = 'PRQ.2'; IncludePrerequisites = $true } + ($plan | Where-Object { $_.Test.Id -eq 'PRQ.2' }).ReasonCode | Should -Be 'ExcludedById' + } + + It 'Leaves out a Pester-format test, which names no step' { + $miss = InModuleScope Maester { + $selection = Resolve-MtSelection -RunConfig (Resolve-MtRunConfig -Config @{}) -Step 'entra.*' + Test-MtSelectorMatch -Selection $selection -Suite 'Custom' + } + $miss.Selector | Should -Be 'Step' + } + + It 'Get-MtTest -Step filters the same way' { + @(Get-MtTest -Path $script:prqFolder -Step 'intune.*').Id | Should -Be @('PRQ.2') + } + + It 'Puts the step of a family instance on its row' { + $values = InModuleScope Maester { Get-MtInstanceAttribute -Instance @{ Id = 'a'; Step = @('Entra.Base', 'not a step') } -Product 'entra' } + $values.Step | Should -Be @('entra.base') + } +} + +Describe 'Outputs of the defender''s path' { + BeforeAll { + $path = Get-Path -Row $script:rows -Measure $script:halfCompliant + $script:result = [pscustomobject]@{ + TenantId = 't1'; TenantName = 'Contoso'; CurrentVersion = '3.1.0'; ExecutedAt = '2026-11-06'; TotalCount = 3; PassedCount = 1; FailedCount = 2 + InvestigateCount = 0; SkippedCount = 0; NotRunCount = 0; ErrorCount = 0; Tests = @($script:rows); Steps = $path.Steps; Goals = $path.Goals + } + } + + It 'Adds Step, Readiness and BlockedBy columns to the CSV rows' { + $flat = @(Convert-MtResultsToFlatObject -InputObject $script:result -PassThru) + $goal = $flat | Where-Object ID -EQ 'T.goal' + $goal.Step | Should -Be 'entra.goal' + $goal.Readiness | Should -Be 'Blocked' + $goal.BlockedBy | Should -Be 'intune.policies, intune.compliant' + ($flat | Where-Object ID -EQ 'T.base').Readiness | Should -Be '' + } + + It 'Starts the Markdown report with the Ready steps and a count of the others' { + $markdown = InModuleScope Maester -Parameters @{ R = $script:result } { Get-MtMarkdownReport -MaesterResults $R } + $markdown.Contains('## Do these first') | Should -BeTrue + $markdown.Contains('1. **Policies** (`intune.policies`)') | Should -BeTrue + $markdown.Contains('T.pol: Title of T.pol') | Should -BeTrue + $markdown.Contains('2 steps are blocked, and 0 steps have prerequisites to check first.') | Should -BeTrue + $markdown.Contains('%DefendersPath%') | Should -BeFalse + $markdown.IndexOf('## Do these first') | Should -BeLessThan $markdown.IndexOf('## Test summary') + } + + It 'Leaves the Markdown report as it was without Steps' { + $plain = $script:result | Select-Object -Property * -ExcludeProperty Steps, Goals + $markdown = InModuleScope Maester -Parameters @{ R = $plain } { Get-MtMarkdownReport -MaesterResults $R } + $markdown.Contains('Do these first') | Should -BeFalse + $markdown.Contains('%DefendersPath%') | Should -BeFalse + } + + It 'Adds one line to the console summary' { + $console = [pscustomobject]@{ Mode = 'Stream'; CI = $null; Ansi = $false; Unicode = $false; ColorDepth = 'None'; Width = 120; Taskbar = $false; Hyperlink = $false } + $lines = @(InModuleScope Maester -Parameters @{ c = $console; r = $script:result } { param($c, $r) Write-MtRunSummary -MaesterResults $r -Console $c 6>&1 } | ForEach-Object { "$_" }) + @($lines | Where-Object { $_ -like "*Defender's path:*" }) | Should -Be @(" Defender's path: 1 ready, 2 blocked, 0 to check first") + $plain = $script:result | Select-Object -Property * -ExcludeProperty Steps, Goals + $without = @(InModuleScope Maester -Parameters @{ c = $console; r = $plain } { param($c, $r) Write-MtRunSummary -MaesterResults $r -Console $c 6>&1 } | ForEach-Object { "$_" }) + @($without | Where-Object { $_ -like "*Defender's path*" }).Count | Should -Be 0 + } +} + +Describe 'ConvertTo-MtMaesterResult with steps' { + BeforeEach { + InModuleScope Maester { + $__MtSession.TestResultDetail = @{} + $__MtSession.MaesterConfig = [PSCustomObject]@{ GlobalSettings = [PSCustomObject]@{}; TestSettings = @(); TestSettingsHash = @{} } + } + Mock Test-MtConnection -ModuleName Maester { $false } + Mock Get-MtModuleVersion -ModuleName Maester { '0.0.0-test' } + Mock Get-MtLatestModuleVersion -ModuleName Maester { $null } + } + AfterEach { + InModuleScope Maester { $__MtSession.MaesterConfig = $null } + } + + It 'Writes Steps and Goals and schema 2.2 when a row names a step, and Step on the row' { + $result = InModuleScope Maester { + $row = [pscustomobject]@{ + Index = 0; Id = 'CONTOSO.1'; Title = 'Emergency access is excluded'; Name = 'CONTOSO.1: Emergency access is excluded'; HelpUrl = ''; Severity = 'High' + Tag = @(); Result = 'Failed'; Block = 'Entra ID'; Product = 'entra'; ResultDetail = $null; ReasonCode = $null; ParentId = $null + Step = [string[]]@('entra.emergency-access-excluded') + } + ConvertTo-MtMaesterResult -NativeRows @($row) -SkipVersionCheck + } + $result.SchemaVersion | Should -Be '2.2' + # Both are Ready; the step recommended first comes first. + @($result.Steps.Id) | Should -Be @('entra.emergency-access-accounts', 'entra.emergency-access-excluded') + $result.Steps[0].Status | Should -Be 'NotChecked' + $step = $result.Steps[1] + $step.Status | Should -Be 'NotDone' + $step.Readiness | Should -Be 'Ready' + ($step.Tests | Where-Object Id -EQ 'MT.1005').ReasonCode | Should -Be 'NotInRun' + $result.Goals.Id | Should -Contain 'compliant-devices' + } + + It 'Writes no Steps when no row names a step' { + $result = InModuleScope Maester { + $row = [pscustomobject]@{ Index = 0; Id = 'CONTOSO.2'; Title = 't'; Name = 'CONTOSO.2: t'; HelpUrl = ''; Severity = 'High'; Tag = @(); Result = 'Passed'; Block = 'Custom'; Product = $null; ResultDetail = $null; ReasonCode = $null; ParentId = $null; Step = [string[]]@() } + ConvertTo-MtMaesterResult -NativeRows @($row) -SkipVersionCheck + } + $result.PSObject.Properties['Steps'] | Should -BeNullOrEmpty + $result.PSObject.Properties['Goals'] | Should -BeNullOrEmpty + } +} diff --git a/powershell/tests/functions/engine/Invoke-Maester.Selection.Tests.ps1 b/powershell/tests/functions/engine/Invoke-Maester.Selection.Tests.ps1 index f68c8d6f34..da12d5504a 100644 --- a/powershell/tests/functions/engine/Invoke-Maester.Selection.Tests.ps1 +++ b/powershell/tests/functions/engine/Invoke-Maester.Selection.Tests.ps1 @@ -84,8 +84,8 @@ Describe 'Invoke-Maester selection (Pester provider)' { Context 'Default run' { BeforeAll { $script:r = Invoke-MaesterRun 'Default' } - It 'Writes result schema 2.1 with the additive fields' { - $r.SchemaVersion | Should -Be '2.1' + It 'Writes result schema 2.2 with the additive fields' { + $r.SchemaVersion | Should -Be '2.2' $r.CatalogVersion | Should -BeOfType [string] $r.CatalogVersion | Should -Match '^\d+\.\d+' $r.Selection.BuiltIn | Should -Be 'None' diff --git a/powershell/tests/functions/engine/Invoke-MtEngineRun.Tests.ps1 b/powershell/tests/functions/engine/Invoke-MtEngineRun.Tests.ps1 index 65835ff17a..4cc3b34694 100644 --- a/powershell/tests/functions/engine/Invoke-MtEngineRun.Tests.ps1 +++ b/powershell/tests/functions/engine/Invoke-MtEngineRun.Tests.ps1 @@ -84,9 +84,9 @@ Describe 'Maester.Engine attribute types' { $attr.Service | Should -Be @('Graph', 'Exchange') } - It 'Has the 27 properties of the design' { + It 'Has the 28 properties of the design' { $expected = 'Id', 'Title', 'Product', 'RelatedProduct', 'Feature', 'Area', 'ResourceType', 'Severity', 'UserImpact', - 'ImplementationCost', 'Mitre', 'Control', 'Service', 'License', 'Permission', 'TenantType', 'Cloud', 'Platform', + 'ImplementationCost', 'Mitre', 'Control', 'Step', 'Service', 'License', 'Permission', 'TenantType', 'Cloud', 'Platform', 'Lifecycle', 'ReplacedBy', 'LongRunning', 'Exclusive', 'InstanceSource', 'Tag', 'Author', 'Contributor', 'HelpUrl' $actual = [MaesterTestAttribute].GetProperties() | Where-Object { $_.DeclaringType -eq [MaesterTestAttribute] } | ForEach-Object Name $actual | Sort-Object | Should -Be ($expected | Sort-Object) diff --git a/powershell/tests/functions/engine/MaesterTestSchema.Tests.ps1 b/powershell/tests/functions/engine/MaesterTestSchema.Tests.ps1 index fc277d5c88..437e9bc9a0 100644 --- a/powershell/tests/functions/engine/MaesterTestSchema.Tests.ps1 +++ b/powershell/tests/functions/engine/MaesterTestSchema.Tests.ps1 @@ -13,7 +13,7 @@ Describe 'MaesterTest schema table' { It 'Declares the same type as the attribute for <_>' -ForEach @( 'Id', 'Title', 'Product', 'RelatedProduct', 'Feature', 'Area', 'ResourceType', 'Severity', 'UserImpact', - 'ImplementationCost', 'Mitre', 'Control', 'Service', 'License', 'Permission', 'TenantType', 'Cloud', 'Platform', + 'ImplementationCost', 'Mitre', 'Control', 'Step', 'Service', 'License', 'Permission', 'TenantType', 'Cloud', 'Platform', 'Lifecycle', 'ReplacedBy', 'LongRunning', 'Exclusive', 'InstanceSource', 'Tag', 'Author', 'Contributor', 'HelpUrl' ) { $map = @{ 'System.String' = 'string'; 'System.String[]' = 'string[]'; 'System.Boolean' = 'bool' } @@ -25,7 +25,7 @@ Describe 'MaesterTest schema table' { # The list above is written out because -ForEach is read at discovery; this keeps it complete. $checked = @( 'Id', 'Title', 'Product', 'RelatedProduct', 'Feature', 'Area', 'ResourceType', 'Severity', 'UserImpact', - 'ImplementationCost', 'Mitre', 'Control', 'Service', 'License', 'Permission', 'TenantType', 'Cloud', 'Platform', + 'ImplementationCost', 'Mitre', 'Control', 'Step', 'Service', 'License', 'Permission', 'TenantType', 'Cloud', 'Platform', 'Lifecycle', 'ReplacedBy', 'LongRunning', 'Exclusive', 'InstanceSource', 'Tag', 'Author', 'Contributor', 'HelpUrl' ) @($script:schema.Properties.Keys | Where-Object { $_ -notin $checked }) | Should -BeNullOrEmpty diff --git a/powershell/tests/functions/engine/StepCatalog.Tests.ps1 b/powershell/tests/functions/engine/StepCatalog.Tests.ps1 new file mode 100644 index 0000000000..4d5c01a975 --- /dev/null +++ b/powershell/tests/functions/engine/StepCatalog.Tests.ps1 @@ -0,0 +1,366 @@ +# The step catalogue of the defender's path (docs/proposals/defenders-path.md, sections 4, 5 and 14): how +# Get-MtStepCatalog reads a catalogue folder and what it reports as a problem, how Get-MtStepProblem checks the steps +# that tests and packs name, and how the reader treats the Step attribute. +# +# Each catalogue is written to TestDrive from a valid base: three entra steps and one intune step under one goal. +BeforeAll { + Import-Module "$PSScriptRoot/../../../Maester.psd1" -Force -WarningAction SilentlyContinue + + function New-Source { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Test helper that returns a hashtable.')] + param([string] $Url = 'https://learn.microsoft.com/entra/identity/example') + [ordered]@{ Url = $Url; Note = 'Do the other step first.'; Reviewed = '2026-11-05' } + } + + # The files of a valid catalogue, as hashtables to change before they are written. + function Get-BaseCatalog { + @{ + 'goals.json' = [ordered]@{ Goals = @([ordered]@{ Id = 'goal'; Title = 'A goal'; Summary = 'What the goal achieves.'; Step = 'entra.c' }) } + 'entra.json' = [ordered]@{ + Product = 'entra' + Steps = @( + [ordered]@{ Id = 'entra.a'; Title = 'Step A'; Summary = 'A.'; Sources = @(New-Source) } + [ordered]@{ Id = 'entra.b'; Title = 'Step B'; Summary = 'B.'; Requires = @('entra.a'); OnlyWhen = @('hybrid-identity'); Sources = @(New-Source) } + [ordered]@{ + Id = 'entra.c'; Title = 'Step C'; Summary = 'C.'; Requires = @('entra.b'); RequiresOneOf = @(, @('entra.a', 'intune.d')) + Rollout = @('Report-only first.', 'Then everyone.'); Sources = @((New-Source), [ordered]@{ Maintainer = 'merill'; Note = 'From experience.'; Reviewed = '2026-11-05' }) + } + ) + } + 'intune.json' = [ordered]@{ Product = 'intune'; Steps = @([ordered]@{ Id = 'intune.d'; Title = 'Step D'; Summary = 'D.'; Unchecked = 'No check yet.'; Sources = @(New-Source 'https://learn.microsoft.com/intune/example') }) } + } + } + + # Writes a catalogue to a new TestDrive folder and reads it. + function Read-Catalog { + param([hashtable] $Files) + $folder = Join-Path $TestDrive ('steps' + [guid]::NewGuid().ToString('n')) + $null = New-Item -ItemType Directory -Path $folder + foreach ($name in $Files.Keys) { + $value = $Files[$name] + $text = if ($value -is [string]) { $value } else { ConvertTo-Json -InputObject $value -Depth 10 } + Set-Content -LiteralPath (Join-Path $folder $name) -Value $text + } + InModuleScope Maester -Parameters @{ F = $folder } { Get-MtStepCatalog -Path $F } + } + + # The problems of a catalogue after a change to the base. + function Get-Problem { + param([scriptblock] $Change) + $files = Get-BaseCatalog + & $Change $files + @((Read-Catalog $files).Problems) + } + + # Writes a measure registry to TestDrive and reads it. + function Read-Registry { + param([string] $Text) + $file = Join-Path $TestDrive ('measures' + [guid]::NewGuid().ToString('n') + '.psd1') + Set-Content -LiteralPath $file -Value $Text + InModuleScope Maester -Parameters @{ F = $file } { Get-MtMeasureRegistry -Path $F } + } + # A registry with one valid measure, whose reader is a function the module has. + $script:validRegistryText = "@{ Measures = @( @{ Key = 'devices-compliant'; Function = 'Get-MtStepCatalog'; Title = 'Devices that sign in are compliant'; Unit = 'devices'; Service = 'Graph'; License = 'INTUNE_A'; Permission = 'Graph:Scope:Device.Read.All' } ) }" + + # The step of the base catalogue with the given ID, to change. + function Get-Step { + param([hashtable] $Files, [string] $Id) + $file = "$($Id.Split('.')[0]).json" + $Files[$file].Steps | Where-Object { $_.Id -eq $Id } + } +} + +Describe 'Get-MtStepCatalog' { + Context 'A valid catalogue' { + BeforeAll { $script:valid = Read-Catalog (Get-BaseCatalog) } + + It 'Has no problems' { + $script:valid.Problems | Should -BeNullOrEmpty + } + + It 'Reads every step with all its fields, lists as arrays' { + $script:valid.Steps.Keys | Should -Be @('entra.a', 'entra.b', 'entra.c', 'intune.d') + $c = $script:valid.Steps['entra.c'] + $c.Product | Should -Be 'entra' + $c.File | Should -Be 'entra.json' + $c.Requires | Should -Be @('entra.b') + $c.RequiresOneOf[0] | Should -Be @('entra.a', 'intune.d') + $c.RecommendedFirst | Should -HaveCount 0 + $c.Rollout | Should -Be @('Report-only first.', 'Then everyone.') + $c.Sources | Should -HaveCount 2 + $c.Sources[1].Maintainer | Should -Be 'merill' + $script:valid.Steps['entra.b'].OnlyWhen | Should -Be @('hybrid-identity') + $script:valid.Steps['intune.d'].Unchecked | Should -Be 'No check yet.' + } + + It 'Gives a goal its step and every prerequisite, prerequisites first' { + $script:valid.Goals | Should -HaveCount 1 + $script:valid.Goals[0].Steps | Should -Be @('entra.a', 'entra.b', 'intune.d', 'entra.c') + } + + It 'Keeps a Reviewed date as yyyy-MM-dd text' { + $script:valid.Steps['entra.a'].Sources[0].Reviewed | Should -Be '2026-11-05' + } + } + + Context 'Problems' { + It 'Reports a relationship to a step that is not in the catalogue' { + Get-Problem { param($f) (Get-Step $f 'entra.c').Requires = @('entra.b', 'entra.missing') } | + Should -Contain "entra.json (entra.c): Requires names 'entra.missing', which is not in the catalogue." + } + + It 'Reports a step that names itself' { + Get-Problem { param($f) (Get-Step $f 'entra.a').RecommendedFirst = @('entra.a') } | + Should -Contain 'entra.json (entra.a): RecommendedFirst names the step itself.' + } + + It 'Reports a step named in two relationships' { + Get-Problem { param($f) (Get-Step $f 'entra.c').RecommendedFirst = @('entra.b') } | + Should -Contain "entra.json (entra.c): 'entra.b' is in both Requires and RecommendedFirst." + } + + It 'Reports a RequiresOneOf group of one step' { + Get-Problem { param($f) (Get-Step $f 'entra.c').RequiresOneOf = @(, @('entra.a')) } | + Should -Contain 'entra.json (entra.c): each RequiresOneOf group lists at least two steps.' + } + + It 'Reports a cycle once, with its path' { + $problems = Get-Problem { param($f) (Get-Step $f 'entra.a').Requires = @('entra.b') } + @($problems | Where-Object { $_ -like '*in a cycle*' }) | Should -HaveCount 1 + $problems | Should -Contain 'entra.json (entra.a): the steps depend on each other in a cycle: entra.a -> entra.b -> entra.a.' + } + + It 'Reports a condition that is not known' { + Get-Problem { param($f) (Get-Step $f 'entra.b').OnlyWhen = @('on-premises') } | + Should -Contain "entra.json (entra.b): OnlyWhen has 'on-premises', which is not a known condition (hybrid-identity, license:)." + } + + It 'Accepts a licence condition' { + Get-Problem { param($f) (Get-Step $f 'entra.b').OnlyWhen = @('license:AAD_PREMIUM_P2') } | Should -BeNullOrEmpty + } + + It 'Reports a source with a locale, one that is not on Learn, and one without Reviewed' { + # Split, so that the repository's check for language-specific URLs does not flag this file. + $localeUrl = 'https://learn.microsoft.com/' + 'en-us/entra/x' + $problems = Get-Problem { + param($f) + (Get-Step $f 'entra.a').Sources = @( + (New-Source $localeUrl), + (New-Source 'https://example.com/x'), + [ordered]@{ Url = 'https://learn.microsoft.com/entra/y'; Note = 'N.' } + ) + } + $problems | Should -Contain "entra.json (entra.a): the source '$localeUrl' has a locale. Leave it out, as the check guides do." + $problems | Should -Contain "entra.json (entra.a): the source 'https://example.com/x' is not a Microsoft Learn URL." + $problems | Should -Contain 'entra.json (entra.a): a source needs Reviewed, the date it was last read against the step (yyyy-MM-dd).' + } + + It 'Reports a step with no source and a Note that is too long' { + $problems = Get-Problem { + param($f) + (Get-Step $f 'entra.a').Sources = @() + (Get-Step $f 'entra.b').Sources = @([ordered]@{ Url = 'https://learn.microsoft.com/entra/x'; Note = ('x' * 201); Reviewed = '2026-11-05' }) + } + $problems | Should -Contain 'entra.json (entra.a): a step needs at least one source.' + $problems | Should -Contain "entra.json (entra.b): A source's Note is longer than 200 characters." + } + + It 'Reports a step file whose Product is not its name, and a step outside its product' { + $problems = Get-Problem { + param($f) + $f['intune.json'].Product = 'entra' + (Get-Step $f 'entra.a').Id = 'intune.a' + (Get-Step $f 'entra.b').Requires = @('intune.a') + } + $problems | Should -Contain "intune.json: Product is 'entra'. A step file is named after its product, so it must be 'intune'." + $problems | Should -Contain "entra.json: the step 'intune.a' must start with 'entra.', the product of its file." + } + + It 'Reports a file named after a product the taxonomy does not have' { + $problems = Get-Problem { param($f) $f['contoso.json'] = [ordered]@{ Product = 'contoso'; Steps = @() } } + $problems | Should -Contain "contoso.json: 'contoso' is not a product key of the taxonomy registry." + } + + It 'Reports a step that is in two files, an unknown key and an invalid ID' { + $problems = Get-Problem { + param($f) + $f['entra.json'].Steps += [ordered]@{ Id = 'entra.a'; Title = 'Again'; Summary = 'Again.'; Sources = @(New-Source) } + (Get-Step $f 'entra.b').Severity = 'High' + $f['entra.json'].Steps += [ordered]@{ Id = 'Entra.Upper'; Title = 'Upper'; Summary = 'U.'; Sources = @(New-Source) } + } + $problems | Should -Contain "entra.json: the step 'entra.a' is also in entra.json." + $problems | Should -Contain "entra.json (entra.b): unknown key 'Severity'." + $problems | Should -Contain "entra.json: 'Entra.Upper' is not a step ID (., lowercase)." + } + + It 'Reports a step in no goal, and a goal whose step is missing' { + $problems = Get-Problem { + param($f) + $f['intune.json'].Steps += [ordered]@{ Id = 'intune.orphan'; Title = 'Orphan'; Summary = 'O.'; Sources = @(New-Source) } + $f['goals.json'].Goals += [ordered]@{ Id = 'other'; Title = 'Other'; Summary = 'O.'; Step = 'entra.missing' } + } + $problems | Should -Contain 'intune.json (intune.orphan): the step belongs to no goal. Make it a goal''s step or a prerequisite of one.' + $problems | Should -Contain "goals.json (other): Step names 'entra.missing', which is not in the catalogue." + } + + It 'Reads a Measure, and reports one that is wrong or sits beside Unchecked' { + $files = Get-BaseCatalog + $d = Get-Step $files 'intune.d' + $d.Remove('Unchecked') + $d.Measure = [ordered]@{ Key = 'devices-compliant'; MinimumShare = 90 } + $catalog = Read-Catalog $files + $catalog.Problems | Should -BeNullOrEmpty + $catalog.Steps['intune.d'].Measure.Key | Should -Be 'devices-compliant' + $catalog.Steps['intune.d'].Measure.MinimumShare | Should -Be 90 + $catalog.Steps['entra.a'].Measure | Should -BeNullOrEmpty + + $problems = Get-Problem { + param($f) + (Get-Step $f 'intune.d').Measure = [ordered]@{ Key = 'Devices'; MinimumShare = 0; Extra = 1 } + (Get-Step $f 'entra.a').Measure = 'devices-compliant' + } + $problems | Should -Contain "intune.json (intune.d): Measure has the unknown key 'Extra'." + $problems | Should -Contain "intune.json (intune.d): Measure's Key 'Devices' is not a measure key (lowercase kebab-case)." + $problems | Should -Contain "intune.json (intune.d): Measure's MinimumShare must be a whole number from 1 to 100." + $problems | Should -Contain 'intune.json (intune.d): the step has a Measure, so it must not have Unchecked.' + $problems | Should -Contain 'entra.json (entra.a): Measure must be an object with Key and MinimumShare.' + } + + It 'Reports a missing goals file and a file that is not JSON' { + $files = Get-BaseCatalog + $files.Remove('goals.json') + $files['intune.json'] = '{ not json' + $problems = @((Read-Catalog $files).Problems) + $problems | Should -Contain 'goals.json: the catalogue has no goals file.' + @($problems | Where-Object { $_ -like 'intune.json: the file is not valid JSON*' }) | Should -HaveCount 1 + } + } +} + +Describe 'Get-MtStepProblem' { + BeforeAll { + $script:catalog = Read-Catalog (Get-BaseCatalog) + function New-FakeTest { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Test helper that returns an object.')] + param([string] $Id, [string[]] $Step) + [pscustomobject]@{ Id = $Id; File = "/tests/Test.$Id.ps1"; Step = $Step } + } + $script:registry = Read-Registry $script:validRegistryText + function Get-TestProblem { + param([object[]] $Test, [string] $PackRoot, [object] $Catalog = $script:catalog, [object] $Registry = $script:registry) + InModuleScope Maester -Parameters @{ T = $Test; C = $Catalog; P = $PackRoot; R = $Registry } { @(Get-MtStepProblem -Test $T -Catalog $C -Registry $R -PackRoot $P -Coverage) } + } + # The base catalogue with a Measure in place of Unchecked on intune.d. + function Get-MeasureCatalog { + param([string] $Key = 'devices-compliant') + $files = Get-BaseCatalog + $d = Get-Step $files 'intune.d' + $d.Remove('Unchecked') + $d.Measure = [ordered]@{ Key = $Key; MinimumShare = 95 } + Read-Catalog $files + } + } + + It 'Has no problems when every checked step has a test and the rest say why not' { + Get-TestProblem @((New-FakeTest 'T.1' @('entra.a')), (New-FakeTest 'T.2' @('entra.b', 'entra.c'))) | Should -BeNullOrEmpty + } + + It 'Reports a test that names a step the catalogue does not have' { + Get-TestProblem @((New-FakeTest 'T.1' @('entra.a', 'entra.nope')), (New-FakeTest 'T.2' @('entra.b', 'entra.c'))) | + Should -Contain "/tests/Test.T.1.ps1: the test T.1 names the step 'entra.nope', which is not in the step catalogue." + } + + It 'Reports a step no test names that has no Unchecked, and a named step that has one' { + $problems = Get-TestProblem @((New-FakeTest 'T.1' @('entra.a', 'intune.d'))) + $problems | Should -Contain 'entra.json (entra.b): no test names the step and it has no Measure. Name it in the Step attribute of the tests that verify it, give it a Measure, or say why neither can in Unchecked.' + $problems | Should -Contain 'intune.json (intune.d): T.1 verify the step, so it must not have Unchecked.' + } + + It 'Leaves out the Unchecked check without -Coverage, as the build does for a folder that holds only some tests' { + $problems = InModuleScope Maester -Parameters @{ C = $script:catalog; R = $script:registry } { @(Get-MtStepProblem -Test @() -Catalog $C -Registry $R) } + $problems | Should -BeNullOrEmpty + } + + It 'Counts a step with a Measure as checked' { + Get-TestProblem @((New-FakeTest 'T.1' @('entra.a')), (New-FakeTest 'T.2' @('entra.b', 'entra.c'))) -Catalog (Get-MeasureCatalog) | + Should -BeNullOrEmpty + } + + It 'Reports a Measure key the registry does not have' { + Get-TestProblem @((New-FakeTest 'T.1' @('entra.a')), (New-FakeTest 'T.2' @('entra.b', 'entra.c'))) -Catalog (Get-MeasureCatalog 'mfa-registered') | + Should -Contain "intune.json (intune.d): Measure names 'mfa-registered', which is not in the measure registry." + } + + It 'Reports a registry entry whose reader does not exist, and entries that are wrong' { + $registry = Read-Registry @" +@{ Measures = @( + @{ Key = 'devices-compliant'; Function = 'Get-MtNoSuchReader'; Title = 'Devices'; Unit = 'devices'; Service = 'Graph' } + @{ Key = 'Bad Key'; Function = 'Get-MtStepCatalog'; Title = 'T'; Unit = 'u'; Service = 'Graph' } + @{ Key = 'mfa-registered'; Function = 'reader'; Unit = 'users'; Service = 'NoSuchService'; Permission = 'not a permission'; Colour = 'red'; Caveat = "two`nlines" } +) } +"@ + $problems = Get-TestProblem @((New-FakeTest 'T.1' @('entra.a')), (New-FakeTest 'T.2' @('entra.b', 'entra.c'))) -Catalog (Get-MeasureCatalog) -Registry $registry + $name = [System.IO.Path]::GetFileName($registry.Path) + $problems | Should -Contain "$name (devices-compliant): the reader function Get-MtNoSuchReader does not exist." + $problems | Should -Contain "${name}: 'Bad Key' is not a measure key (lowercase kebab-case)." + $problems | Should -Contain "$name (mfa-registered): Function must name a Maester function, Verb-MtNoun." + $problems | Should -Contain "$name (mfa-registered): Title must be one line of text." + $problems | Should -Contain "$name (mfa-registered): Service 'NoSuchService' is not in the service registry." + $problems | Should -Contain "$name (mfa-registered): Permission 'not a permission' is not valid. Write ::." + $problems | Should -Contain "$name (mfa-registered): unknown key 'Colour'." + $problems | Should -Contain "$name (mfa-registered): Caveat must be one line of 200 characters or less." + } + + It 'Counts the steps a pack names in its taxonomy.json' { + $packs = Join-Path $TestDrive 'packs' + $null = New-Item -ItemType Directory -Path (Join-Path $packs 'zta') -Force + '{ "Tests": { "100": { "Product": "entra", "Step": ["entra.b"] }, "101": { "Step": ["entra.unknown"] } } }' | + Set-Content (Join-Path $packs 'zta/taxonomy.json') + $problems = Get-TestProblem @((New-FakeTest 'T.1' @('entra.a')), (New-FakeTest 'T.2' @('entra.c'))) -PackRoot $packs + @($problems | Where-Object { $_ -like '*entra.b*' }) | Should -BeNullOrEmpty + @($problems | Where-Object { $_ -like "*the test 101 names the step 'entra.unknown'*" }) | Should -HaveCount 1 + } +} + +Describe 'The Step attribute' { + BeforeAll { + function Read-StepTest { + param([string] $Step) + $folder = Join-Path $TestDrive ('t' + [guid]::NewGuid().ToString('n')) + $null = New-Item -ItemType Directory -Path $folder + "function Test-StepFixture {`n [MaesterTest(Id = 'STEP.1', Title = 'Step fixture', Step = $Step, Service = 'None')]`n [CmdletBinding()]`n param()`n `$true`n}" | + Set-Content (Join-Path $folder 'Test.STEP.1.ps1') + 'Description.' | Set-Content (Join-Path $folder 'Test.STEP.1.md') + InModuleScope Maester -Parameters @{ F = (Join-Path $folder 'Test.STEP.1.ps1') } { Read-MtNativeTest -Path $F } + } + } + + It 'Reads one step or a list, and drops repeats' { + (Read-StepTest "'entra.a'").Step | Should -Be @('entra.a') + $t = Read-StepTest "('entra.a', 'intune.d', 'entra.a')" + $t.Step | Should -Be @('entra.a', 'intune.d') + $t.Errors | Should -BeNullOrEmpty + } + + It 'Stores a step in lowercase' { + (Read-StepTest "'Entra.CA-Require'").Step | Should -Be @('entra.ca-require') + } + + It 'Rejects a value that is not a step ID' { + @((Read-StepTest "'entra_a'").Errors.Message) | Should -Contain "Property 'Step' value 'entra_a' is not valid." + } + + It 'Rejects more than three steps' { + @((Read-StepTest "('entra.a', 'entra.b', 'entra.c', 'intune.d')").Errors.Message) | + Should -Contain "Property 'Step' names 4 steps. A test verifies at most three; a test that checks more is several tests." + } + + It 'Defaults to an empty list' { + $folder = Join-Path $TestDrive 'nostep' + $null = New-Item -ItemType Directory -Path $folder + "function Test-NoStep {`n [MaesterTest(Id = 'STEP.2', Title = 'No step', Service = 'None')]`n [CmdletBinding()]`n param()`n `$true`n}" | Set-Content (Join-Path $folder 'Test.STEP.2.ps1') + 'Description.' | Set-Content (Join-Path $folder 'Test.STEP.2.md') + $t = InModuleScope Maester -Parameters @{ F = (Join-Path $folder 'Test.STEP.2.ps1') } { Read-MtNativeTest -Path $F } + $t.Step.Count | Should -Be 0 + } +} diff --git a/powershell/tests/general/StepCatalog.Tests.ps1 b/powershell/tests/general/StepCatalog.Tests.ps1 new file mode 100644 index 0000000000..439e3aeae2 --- /dev/null +++ b/powershell/tests/general/StepCatalog.Tests.ps1 @@ -0,0 +1,56 @@ +# The step catalogue of the defender's path (docs/proposals/defenders-path.md, sections 4 and 14) and the steps that +# the built-in tests and the packs that ship with Maester name. The catalog build fails on the same problems +# (Get-MtStepProblem); the rules themselves are tested on fixtures in functions/engine/StepCatalog.Tests.ps1. + +BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force -WarningAction SilentlyContinue + $script:repoRoot = (Resolve-Path "$PSScriptRoot/../../..").Path + $script:folder = Join-Path $script:repoRoot 'powershell/assets/steps' + + $files = @(Get-ChildItem -Path (Join-Path $script:repoRoot 'tests') -Recurse -File -Filter 'Test.*.ps1' | + Where-Object { $_.FullName -notmatch '[\\/]custom[\\/]' }) + $script:tests = @(InModuleScope Maester -Parameters @{ Files = $files.FullName } { + foreach ($file in $Files) { [pscustomobject](Read-MtNativeTest -Path $file -BuiltIn) } + }) + $script:catalog = InModuleScope Maester { Get-MtStepCatalog } +} + +Describe 'The step catalogue' { + It 'Has steps and goals' { + $script:catalog.Steps.Count | Should -BeGreaterThan 0 + $script:catalog.Goals.Count | Should -BeGreaterThan 0 + } + + It 'Has no problems, and every step a built-in test or pack names is in it' { + $problems = @(InModuleScope Maester -Parameters @{ Tests = $script:tests; PackRoot = (Join-Path $script:repoRoot 'packs') } { + Get-MtStepProblem -Test $Tests -PackRoot $PackRoot -Coverage + }) + $problems | Should -BeNullOrEmpty + } + + It 'Matches its JSON schema: <_>' -ForEach @( + Get-ChildItem -Path (Join-Path (Resolve-Path "$PSScriptRoot/../../..").Path 'powershell/assets/steps') -Filter '*.json' | + Where-Object Name -NE 'steps.schema.json' | ForEach-Object Name + ) { + $json = Get-Content -LiteralPath (Join-Path $script:folder $_) -Raw + Test-Json -Json $json -SchemaFile (Join-Path $script:folder 'steps.schema.json') -ErrorAction SilentlyContinue | Should -BeTrue + } + + It 'Is valid JSON Schema itself and rejects a step with an unknown key' { + $bad = '{ "Product": "entra", "Steps": [ { "Id": "entra.x", "Title": "X", "Summary": "S.", "Sources": [ { "Url": "https://learn.microsoft.com/entra/x", "Note": "N.", "Reviewed": "2026-11-05" } ], "Severity": "High" } ] }' + Test-Json -Json $bad -SchemaFile (Join-Path $script:folder 'steps.schema.json') -ErrorAction SilentlyContinue | Should -BeFalse + } + + It 'Has goals whose steps are the goal step and its prerequisites, prerequisites first' { + foreach ($goal in $script:catalog.Goals) { + $goal.Steps[-1] | Should -Be $goal.Step -Because $goal.Id + for ($i = 0; $i -lt $goal.Steps.Count; $i++) { + $step = $script:catalog.Steps[$goal.Steps[$i]] + $before = @($goal.Steps | Select-Object -First $i) + foreach ($prerequisite in @($step.Requires) + @($step.RecommendedFirst) + @($step.RequiresOneOf | ForEach-Object { $_ })) { + $before | Should -Contain $prerequisite -Because "$($step.Id) depends on $prerequisite in the goal $($goal.Id)" + } + } + } + } +} diff --git a/powershell/tests/general/StepTooling.Tests.ps1 b/powershell/tests/general/StepTooling.Tests.ps1 new file mode 100644 index 0000000000..5021e4bc9f --- /dev/null +++ b/powershell/tests/general/StepTooling.Tests.ps1 @@ -0,0 +1,604 @@ +# Unit tests for the tooling in build/steps that keeps the defender's path catalogue current: Update-MtLearnMirror.ps1, +# Find-MtStepCandidate.ps1 and Test-MtStepSource.ps1, and their helpers. +# No test makes a network call: the mirror is a git repository built in TestDrive, -NoFetch keeps git local, and +# the requests to Learn and to the Claude API are mocked. + +Describe 'Step catalogue tooling' { + BeforeAll { + $script:repoRoot = (Resolve-Path (Join-Path $PSScriptRoot '../../..')).Path + $script:stepsFolder = Join-Path $script:repoRoot 'build/steps' + $script:updateScript = Join-Path $script:stepsFolder 'Update-MtLearnMirror.ps1' + $script:findScript = Join-Path $script:stepsFolder 'Find-MtStepCandidate.ps1' + $script:testScript = Join-Path $script:stepsFolder 'Test-MtStepSource.ps1' + . $script:updateScript + . $script:findScript + . $script:testScript + + # Split so that no line holds a localized Learn URL (LanguageNeutralMicrosoftUrls.Tests.ps1). + $script:learn = 'https://learn.microsoft.com' + $script:localized = 'https://learn.microsoft.com/' + 'en-us' + + function Invoke-FixtureGit { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Test helper that only builds test data.')] + param([string] $Path, [string[]] $Arguments, [string] $Date = '2026-10-01T10:00:00Z') + $env:GIT_AUTHOR_DATE = $Date + $env:GIT_COMMITTER_DATE = $Date + try { + $output = & git -C $Path -c user.name=Maester -c user.email=tests@maester.dev -c commit.gpgsign=false -c core.hooksPath=/dev/null @Arguments 2>&1 + if ($LASTEXITCODE -ne 0) { throw "git $($Arguments -join ' ') failed: $output" } + } finally { + Remove-Item Env:GIT_AUTHOR_DATE, Env:GIT_COMMITTER_DATE -ErrorAction SilentlyContinue + } + } + + function New-FixturePage { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Test helper that only builds test data.')] + param([string] $Path, [string] $Key, [string] $Body, [string] $Topic = 'how-to') + $null = New-Item -ItemType Directory -Path (Split-Path $Path) -Force + $text = @( + '---' + "title: Fixture $Key | Microsoft Learn" + "canonicalUrl: $script:localized/$Key" + "ms.topic: $Topic" + "source_path: $Key.md" + '---' + '' + $Body + ) -join "`n" + Set-Content -LiteralPath $Path -Value $text -Encoding utf8NoBOM -NoNewline + } + + function New-FixtureState { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Test helper that only builds test data.')] + param([string] $Mirror, [hashtable] $Pages) + $state = [ordered]@{ version = 1; cursor = $null; pages = [ordered]@{} } + foreach ($key in $Pages.Keys | Sort-Object) { $state.pages["$script:localized/$key"] = $Pages[$key] } + $null = New-Item -ItemType Directory -Path (Join-Path $Mirror '.learn-mirror') -Force + $state | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath (Join-Path $Mirror '.learn-mirror/state.json') -Encoding utf8NoBOM + } + + # A mirror with this history: + # 2026-10-01 page-a and page-b published + # 2026-10-10 page-a: front matter only + # 2026-10-20 page-b: its text changes + # 2026-10-25 page-c published + $script:cache = Join-Path $TestDrive 'cache' + $script:fixtureMirror = Join-Path $script:cache 'mirrors/entra-docs-mirror' + $null = New-Item -ItemType Directory -Path $script:fixtureMirror -Force + Invoke-FixtureGit -Path $script:fixtureMirror -Arguments 'init', '-q', '-b', 'main' + @{ + include = '^https://learn\.microsoft\.com/' + 'en-us/fixture/' + exclude = @('^https://learn\.microsoft\.com/' + 'en-us/fixture/skip/') + } | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $script:fixtureMirror 'learn-mirror.config.json') -Encoding utf8NoBOM + $bodyA = "# Page A`n`n## Prerequisites`n`n- A licence.`n`n## Steps`n`nCreate the policy first." + $bodyB = "# Page B`n`nYou must turn it on." + New-FixturePage -Path (Join-Path $script:fixtureMirror 'docs/page-a.md') -Key 'fixture/page-a' -Body $bodyA + New-FixturePage -Path (Join-Path $script:fixtureMirror 'docs/page-b.md') -Key 'fixture/page-b' -Body $bodyB + $statePages = @{ + 'fixture/page-a' = @{ path = 'docs/page-a.md'; sourcePath = 'page-a.md' } + 'fixture/page-b' = @{ path = 'docs/page-b.md'; sourcePath = 'page-b.md' } + # An old URL that Learn redirects, and an alias that shares its original's file. + 'fixture/old-b' = @{ path = 'docs/page-b.md'; redirectedTo = "$script:localized/fixture/page-b" } + 'fixture/alias-a' = @{ aliasOf = "$script:localized/fixture/page-a" } + # The state names a file that is not in the mirror. + 'fixture/gone' = @{ path = 'docs/gone.md' } + } + New-FixtureState -Mirror $script:fixtureMirror -Pages $statePages + Invoke-FixtureGit -Path $script:fixtureMirror -Arguments 'add', '-A' + Invoke-FixtureGit -Path $script:fixtureMirror -Arguments 'commit', '-q', '-m', 'Mirror Learn: 2 added' -Date '2026-10-01T10:00:00Z' + + New-FixturePage -Path (Join-Path $script:fixtureMirror 'docs/page-a.md') -Key 'fixture/page-a' -Body $bodyA -Topic 'concept-article' + Invoke-FixtureGit -Path $script:fixtureMirror -Arguments 'commit', '-q', '-am', 'Mirror Learn: 1 changed' -Date '2026-10-10T10:00:00Z' + + New-FixturePage -Path (Join-Path $script:fixtureMirror 'docs/page-b.md') -Key 'fixture/page-b' -Body "# Page B`n`nYou must turn it on, and then wait a day." + Invoke-FixtureGit -Path $script:fixtureMirror -Arguments 'commit', '-q', '-am', 'Mirror Learn: 1 changed' -Date '2026-10-20T10:00:00Z' + $script:changeSha = (& git -C $script:fixtureMirror rev-parse HEAD) + + New-FixturePage -Path (Join-Path $script:fixtureMirror 'docs/page-c.md') -Key 'fixture/page-c' -Body "# Page C`n`nNew." + $statePages['fixture/page-c'] = @{ path = 'docs/page-c.md' } + New-FixtureState -Mirror $script:fixtureMirror -Pages $statePages + Invoke-FixtureGit -Path $script:fixtureMirror -Arguments 'add', '-A' + Invoke-FixtureGit -Path $script:fixtureMirror -Arguments 'commit', '-q', '-m', 'Mirror Learn: 1 added' -Date '2026-10-25T10:00:00Z' + + # Answers from Learn for linked URLs that the mirror doesn't have under that key. + $null = New-Item -ItemType Directory -Path $script:cache -Force + @{ + Version = 1 + Redirects = [ordered]@{ + 'fixture/moved' = [ordered]@{ Status = 'Redirect'; To = 'fixture/page-a'; Hops = 1; Checked = '2026-11-01T00:00:00Z' } + 'fixture/removed' = [ordered]@{ Status = 'Missing'; To = 'fixture/removed'; Hops = 0; Checked = '2026-11-01T00:00:00Z' } + 'fixture/unknown' = [ordered]@{ Status = 'Page'; To = 'fixture/unknown'; Hops = 0; Checked = '2026-11-01T00:00:00Z' } + 'graph/api/x' = [ordered]@{ Status = 'Page'; To = 'graph/api/x'; Hops = 0; Checked = '2026-11-01T00:00:00Z' } + 'fixture/away' = [ordered]@{ Status = 'External'; To = 'https://github.com/x'; Hops = 1; Checked = '2026-11-01T00:00:00Z' } + } + } | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath (Join-Path $script:cache 'redirects.json') -Encoding utf8NoBOM + + # The index, written by the update script itself. -NoFetch and -Links None keep it off the network. + $script:fixtureRoot = Join-Path $TestDrive 'repo' + $null = New-Item -ItemType Directory -Path (Join-Path $script:fixtureRoot 'tests/maester/entra') -Force + $guide = @( + '# MT.9001' + "See [the policy]($script:learn/Fixture/Page-A#create). Also $script:localized/fixture/page-b." + "And ($script:learn/graph/api/x?view=graph-rest-1.0), ." + "The site itself: $script:learn/" + ) -join "`n" + Set-Content -LiteralPath (Join-Path $script:fixtureRoot 'tests/maester/entra/Test.MT.9001.md') -Value $guide -Encoding utf8NoBOM + $script:updateResult = & $script:updateScript -Root $script:fixtureRoot -CachePath $script:cache -Mirror entra-docs-mirror -Links None -NoFetch 6>$null + $script:index = Read-MtLearnIndex -CachePath $script:cache + + function New-FixtureCatalog { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Test helper that only builds test data.')] + param([string] $Name, [object[]] $Steps) + $folder = Join-Path $TestDrive $Name + $null = New-Item -ItemType Directory -Path $folder -Force + [ordered]@{ Product = 'entra'; Steps = $Steps } | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath (Join-Path $folder 'entra.json') -Encoding utf8NoBOM + '{ "Goals": [] }' | Set-Content -LiteralPath (Join-Path $folder 'goals.json') + $folder + } + function New-FixtureStep { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Test helper that only builds test data.')] + param([string] $Id, [string] $Key, [string] $Reviewed, [string] $Mirror = 'entra-docs-mirror') + [ordered]@{ + Id = $Id + Title = "Title of $Id" + Summary = 'Summary.' + Sources = @([ordered]@{ Url = "$script:learn/$Key"; Mirror = $Mirror; Note = 'Note.'; Reviewed = $Reviewed }) + } + } + } + + Context 'Learn URLs' { + It 'keys a URL by its path, without locale, anchor, query, trailing slash or case' { + ConvertTo-MtLearnKey "$script:localized/Entra/Identity/Overview/?view=x#anchor" | Should -Be 'entra/identity/overview' + ConvertTo-MtLearnKey "$script:learn/intune/" | Should -Be 'intune' + ConvertTo-MtLearnKey 'https://docs.microsoft.com/' | Should -Be '' + ConvertTo-MtLearnKey ('https://docs.microsoft.com/' + 'de-de/azure/active-directory/x') | Should -Be 'azure/active-directory/x' + } + + It 'returns nothing for another site' { + ConvertTo-MtLearnKey 'https://github.com/merill/entra-docs-mirror' | Should -BeNullOrEmpty + ConvertTo-MtLearnKey 'https://learn.microsoft.com.example.com/x' | Should -BeNullOrEmpty + } + } + + Context 'Front matter' { + It 'splits the front matter from the body and gives the body''s first line' { + $split = Split-MtLearnFrontMatter -Text "---`r`ntitle: A page`r`nms.topic: how-to`r`nms.collection:`r`n- one`r`n---`r`n`r`n# A page`r`nText." + $split.FrontMatter['title'] | Should -Be 'A page' + $split.FrontMatter['ms.topic'] | Should -Be 'how-to' + $split.FrontMatter.Contains('ms.collection') | Should -BeFalse + $split.BodyLine | Should -Be 7 + $split.Body | Should -Be "`n# A page`nText." + } + + It 'treats a page with no closing --- as all body' { + $split = Split-MtLearnFrontMatter -Text "---`ntitle: x`nno end" + $split.FrontMatter.Count | Should -Be 0 + $split.BodyLine | Should -Be 1 + } + } + + Context 'Linked pages' { + BeforeAll { + $script:linkCatalog = New-FixtureCatalog -Name 'link-catalog' -Steps @( + (New-FixtureStep -Id 'entra.a' -Key 'fixture/page-a' -Reviewed '2026-10-05'), + [ordered]@{ Id = 'entra.m'; Title = 'M'; Summary = 'S.'; Sources = @(@{ Maintainer = 'merill'; Note = 'N.'; Reviewed = '2026-10-05' }) } + ) + } + + It 'reads the Learn links of check guides and step sources, with where each comes from' { + $links = @(Get-MtLearnLink -Root $script:fixtureRoot -CatalogPath $script:linkCatalog) + $links.Key | Should -Be @('fixture/page-a', 'fixture/page-b', 'graph/api/x') + $pageA = $links | Where-Object Key -EQ 'fixture/page-a' + $pageA.From.Kind | Should -Be @('Source', 'Guide') + ($pageA.From | Where-Object Kind -EQ 'Guide').Id | Should -Be 'MT.9001' + ($pageA.From | Where-Object Kind -EQ 'Guide').Line | Should -Be 2 + ($links | Where-Object Key -EQ 'fixture/page-b').Url | Should -Be "$script:localized/fixture/page-b" + ($links | Where-Object Key -EQ 'graph/api/x').Url | Should -Be "$script:learn/graph/api/x" + } + + It 'reads only the step sources with -Links Catalog' { + @(Get-MtLearnLink -Root $script:fixtureRoot -CatalogPath $script:linkCatalog -Links Catalog).Key | Should -Be @('fixture/page-a') + } + + It 'lists the sources of each step, and maintainer sources without a Url' { + $sources = @(Get-MtStepSource -Path $script:linkCatalog) + $sources.Count | Should -Be 2 + $sources[0].Step | Should -Be 'entra.a' + $sources[0].Reviewed | Should -Be '2026-10-05' + $sources[1].Url | Should -BeNullOrEmpty + $sources[1].Maintainer | Should -Be 'merill' + } + } + + Context 'Mirror index' { + It 'indexes the pages the mirror state lists, with redirects and aliases' { + $script:updateResult.Pages | Should -Be 5 + $script:index.Pages['fixture/page-a']['Path'] | Should -Be 'docs/page-a.md' + $script:index.Pages['fixture/alias-a']['Path'] | Should -Be 'docs/page-a.md' + $script:index.Pages['fixture/old-b']['Target'] | Should -Be 'fixture/page-b' + $script:index.Pages['FIXTURE/PAGE-C']['Path'] | Should -Be 'docs/page-c.md' + } + + It 'leaves out a page whose file is not in the mirror' { + $script:index.Pages.ContainsKey('fixture/gone') | Should -BeFalse + } + + It 'records the mirror''s commit and the URLs it covers' { + $info = $script:index.Mirrors['entra-docs-mirror'] + $info['Commit'] | Should -Be (& git -C $script:fixtureMirror rev-parse HEAD) + $info['Repository'] | Should -Be 'merill/entra-docs-mirror' + $info['Include'] | Should -Match 'fixture' + } + + It 'indexes a mirror with no state file from each page''s canonicalUrl' { + $plain = Join-Path $TestDrive 'plain-mirror' + $null = New-Item -ItemType Directory -Path $plain -Force + Invoke-FixtureGit -Path $plain -Arguments 'init', '-q', '-b', 'main' + New-FixturePage -Path (Join-Path $plain 'docs/one.md') -Key 'plain/one' -Body 'One.' + Invoke-FixtureGit -Path $plain -Arguments 'add', '-A' + Invoke-FixtureGit -Path $plain -Arguments 'commit', '-q', '-m', 'one' + $content = Get-MtLearnMirrorPage -Path $plain 3>$null + $content.Pages.Key | Should -Be 'plain/one' + $content.Pages.Path | Should -Be 'docs/one.md' + } + + It 'asks Learn only about linked pages with no mirror file and no fresh answer' { + $links = @('fixture/page-a', 'fixture/new', 'fixture/fresh', 'fixture/stale', 'fixture/unreadable') | ForEach-Object { [pscustomobject]@{ Key = $_ } } + $answers = [ordered]@{ + 'fixture/fresh' = @{ Checked = '2026-11-01T00:00:00Z' } + 'fixture/stale' = @{ Checked = [datetime]::new(2026, 8, 1, 0, 0, 0, [System.DateTimeKind]::Utc) } + 'fixture/unreadable' = @{ Checked = 'not a date' } + } + $now = [datetime]::new(2026, 11, 5, 0, 0, 0, [System.DateTimeKind]::Utc) + (Select-MtLearnLookup -Link $links -Pages $script:index.Pages -Redirects $answers -MaxAge 30 -Now $now).Key | + Should -Be @('fixture/new', 'fixture/stale', 'fixture/unreadable') + (Select-MtLearnLookup -Link $links -Pages $script:index.Pages -Redirects $answers -MaxAge 0 -Now $now).Key | + Should -Be @('fixture/new', 'fixture/fresh', 'fixture/stale', 'fixture/unreadable') + } + } + + Context 'Asking Learn where a URL goes' { + BeforeAll { + Mock Start-Sleep { } + } + + It 'follows redirects one hop at a time and records where they end' { + Mock Send-MtLearnRequest { + switch -Wildcard ($Uri) { + '*/mem/intune/old' { [pscustomobject]@{ Status = 301; Location = '/en-us/intune/intune/old'; RetryAfter = $null } } + '*/intune/intune/old' { [pscustomobject]@{ Status = 301; Location = '/en-us/intune/new'; RetryAfter = $null } } + '*/intune/new' { [pscustomobject]@{ Status = 200; Location = $null; RetryAfter = $null } } + } + } + $answer = Resolve-MtLearnRedirect -Key 'mem/intune/old' -RequestsPerSecond 20 + $answer.Status | Should -Be 'Redirect' + $answer.To | Should -Be 'intune/new' + $answer.Hops | Should -Be 2 + $answer.Checked | Should -Match '^\d{4}-\d{2}-\d{2}T' + Should -Invoke Send-MtLearnRequest -Times 3 -Exactly + } + + It 'records a page that is served at its URL, even after a redirect that only adds a query' { + Mock Send-MtLearnRequest { + if ($Uri -like '*view=*') { [pscustomobject]@{ Status = 200; Location = $null; RetryAfter = $null } } + else { [pscustomobject]@{ Status = 301; Location = '/en-us/graph/api/user-get?view=graph-rest-1.0'; RetryAfter = $null } } + } + $answer = Resolve-MtLearnRedirect -Key 'graph/api/user-get' -RequestsPerSecond 20 + $answer.Status | Should -Be 'Page' + $answer.To | Should -Be 'graph/api/user-get' + } + + It 'records a removed page and a redirect to another site' { + Mock Send-MtLearnRequest { [pscustomobject]@{ Status = 404; Location = $null; RetryAfter = $null } } + (Resolve-MtLearnRedirect -Key 'fixture/removed' -RequestsPerSecond 20).Status | Should -Be 'Missing' + Mock Send-MtLearnRequest { [pscustomobject]@{ Status = 302; Location = 'https://techcommunity.microsoft.com/x'; RetryAfter = $null } } + $answer = Resolve-MtLearnRedirect -Key 'fixture/away' -RequestsPerSecond 20 + $answer.Status | Should -Be 'External' + $answer.To | Should -Be 'https://techcommunity.microsoft.com/x' + } + + It 'waits and retries when Learn throttles' { + $script:calls = 0 + Mock Send-MtLearnRequest { + $script:calls++ + if ($script:calls -eq 1) { [pscustomobject]@{ Status = 429; Location = $null; RetryAfter = 7 } } + else { [pscustomobject]@{ Status = 200; Location = $null; RetryAfter = $null } } + } + (Resolve-MtLearnRedirect -Key 'fixture/page' -RequestsPerSecond 20).Status | Should -Be 'Page' + Should -Invoke Start-Sleep -ParameterFilter { $Seconds -eq 7 } -Times 1 -Exactly + } + + It 'caches nothing when Learn fails' { + Mock Send-MtLearnRequest { [pscustomobject]@{ Status = 500; Location = $null; RetryAfter = $null } } + Resolve-MtLearnRedirect -Key 'fixture/page' -RequestsPerSecond 20 3>$null | Should -BeNullOrEmpty + Mock Send-MtLearnRequest { throw 'No network' } + Resolve-MtLearnRedirect -Key 'fixture/page' -RequestsPerSecond 20 3>$null | Should -BeNullOrEmpty + } + } + + Context 'Resolving a URL to its mirror file' { + It 'resolves to ' -ForEach @( + @{ Url = 'https://learn.microsoft.com/fixture/page-a'; Status = 'Mirrored'; Path = 'docs/page-a.md'; Resolved = 'fixture/page-a' } + @{ Url = 'https://learn.microsoft.com/fixture/old-b'; Status = 'Redirected'; Path = 'docs/page-b.md'; Resolved = 'fixture/page-b' } + @{ Url = 'https://learn.microsoft.com/fixture/moved'; Status = 'Redirected'; Path = 'docs/page-a.md'; Resolved = 'fixture/page-a' } + @{ Url = 'https://learn.microsoft.com/fixture/unknown'; Status = 'NotInMirror'; Path = $null; Resolved = 'fixture/unknown' } + @{ Url = 'https://learn.microsoft.com/graph/api/x'; Status = 'NotMirrored'; Path = $null; Resolved = 'graph/api/x' } + @{ Url = 'https://learn.microsoft.com/fixture/removed'; Status = 'Missing'; Path = $null; Resolved = $null } + @{ Url = 'https://learn.microsoft.com/fixture/away'; Status = 'External'; Path = $null; Resolved = $null } + @{ Url = 'https://learn.microsoft.com/fixture/never-asked'; Status = 'Unresolved'; Path = $null; Resolved = $null } + ) { + $page = Resolve-MtLearnPage -Index $script:index -Url $Url + $page.Status | Should -Be $Status + $page.Path | Should -Be $Path + $page.ResolvedKey | Should -Be $Resolved + if ($Path) { $page.Mirror | Should -Be 'entra-docs-mirror' } + } + } + + Context 'Changed sources' { + BeforeAll { + $script:sourceCatalog = New-FixtureCatalog -Name 'source-catalog' -Steps @( + (New-FixtureStep -Id 'entra.front-matter-only' -Key 'fixture/page-a' -Reviewed '2026-10-05'), + (New-FixtureStep -Id 'entra.text-changed' -Key 'fixture/page-b' -Reviewed '2026-10-05'), + (New-FixtureStep -Id 'entra.reviewed-on-change-day' -Key 'fixture/page-b' -Reviewed '2026-10-20'), + (New-FixtureStep -Id 'entra.page-published-later' -Key 'fixture/page-c' -Reviewed '2026-10-05'), + (New-FixtureStep -Id 'entra.reviewed-before-mirror' -Key 'fixture/page-a' -Reviewed '2026-09-01'), + (New-FixtureStep -Id 'entra.old-url-other-mirror' -Key 'fixture/moved' -Reviewed '2026-10-05' -Mirror 'intune-docs-mirror'), + (New-FixtureStep -Id 'entra.page-removed' -Key 'fixture/removed' -Reviewed '2026-10-05'), + [ordered]@{ Id = 'entra.maintainer'; Title = 'M'; Summary = 'S.'; Sources = @(@{ Maintainer = 'merill'; Note = 'N.'; Reviewed = '2026-10-05' }) } + ) + $script:sourceOut = Join-Path $TestDrive 'source-out' + $script:sourceResults = @(& $script:testScript -Root $script:fixtureRoot -CachePath $script:cache -CatalogPath $script:sourceCatalog -OutputPath $script:sourceOut 6>$null) + $script:sourceExit = $LASTEXITCODE + $script:byStep = @{} + foreach ($row in $script:sourceResults) { $script:byStep[$row.Step] = $row } + } + + It 'checks every source with a Url and exits 1 when one needs review' { + $script:sourceResults.Count | Should -Be 7 + $script:byStep.ContainsKey('entra.maintainer') | Should -BeFalse + $script:sourceExit | Should -Be 1 + } + + It 'ignores commits that change only the front matter' { + $row = $script:byStep['entra.front-matter-only'] + $row.Status | Should -Be 'Unchanged' + $row.NeedsReview | Should -BeFalse + $row.Detail | Should -Match '1 commit since the baseline changed only the front matter' + } + + It 'lists the commit that changed the text, with a link to the file''s diff' { + $row = $script:byStep['entra.text-changed'] + $row.Status | Should -Be 'Changed' + $row.NeedsReview | Should -BeTrue + @($row.Commits).Count | Should -Be 1 + $row.Commits[0].Sha | Should -Be $script:changeSha + $hash = [System.Convert]::ToHexString([System.Security.Cryptography.SHA256]::HashData([System.Text.Encoding]::UTF8.GetBytes('docs/page-b.md'))).ToLowerInvariant() + $row.DiffLink | Should -Be "https://github.com/merill/entra-docs-mirror/commit/$($script:changeSha)#diff-$hash" + $row.HistoryLink | Should -BeLike 'https://github.com/merill/entra-docs-mirror/commits/*/docs/page-b.md' + } + + It 'counts a change on the Reviewed day as read' { + $script:byStep['entra.reviewed-on-change-day'].Status | Should -Be 'Unchanged' + } + + It 'reports a page that was published after Reviewed, and a mirror that starts after it' { + $script:byStep['entra.page-published-later'].Status | Should -Be 'New' + $script:byStep['entra.reviewed-before-mirror'].Status | Should -Be 'NoBaseline' + $script:byStep['entra.page-removed'].Status | Should -Be 'NotFound' + $script:byStep['entra.page-removed'].Detail | Should -Match '404' + } + + It 'flags a URL that Learn redirects and a Mirror that names the wrong mirror' { + $row = $script:byStep['entra.old-url-other-mirror'] + $row.Status | Should -Be 'Unchanged' + $row.NeedsReview | Should -BeTrue + $row.Problems | Should -HaveCount 2 + $row.Problems[0] | Should -Match 'redirects this URL to https://learn.microsoft.com/fixture/page-a' + $row.Problems[1] | Should -Match 'Mirror is intune-docs-mirror, but the page is in entra-docs-mirror' + } + + It 'writes the issue body with only the steps that need review' { + $markdown = Get-Content -LiteralPath (Join-Path $script:sourceOut 'step-sources.md') -Raw + $markdown | Should -Match '^' + $markdown | Should -Match '5 of 7 Learn sources need a maintainer to re-read the page, in 5 steps' + $markdown | Should -Match '### `entra.text-changed` Title of entra.text-changed' + $markdown | Should -Match ([regex]::Escape("[diff](https://github.com/merill/entra-docs-mirror/commit/$($script:changeSha)#diff-")) + $markdown | Should -Not -Match 'entra.front-matter-only' + $json = Get-Content -LiteralPath (Join-Path $script:sourceOut 'step-sources.json') -Raw | ConvertFrom-Json + $json.Count | Should -Be 7 + } + + It 'exits 0 when no source needs review' { + $null = & $script:testScript -Root $script:fixtureRoot -CachePath $script:cache -CatalogPath $script:sourceCatalog -Step 'entra.front-matter-only', 'entra.reviewed-on-change-*' 6>$null + $LASTEXITCODE | Should -Be 0 + } + + It 'exits 2 when there is no index' { + $null = & $script:testScript -Root $script:fixtureRoot -CachePath (Join-Path $TestDrive 'no-cache') -CatalogPath $script:sourceCatalog 6>$null 2>$null + $LASTEXITCODE | Should -Be 2 + } + + It 'says so when every source is current' { + $markdown = ConvertTo-MtStepSourceMarkdown -Result @($script:byStep['entra.front-matter-only']) -Checked '2026-11-05' + $markdown | Should -Match 'All 1 Learn sources of the step catalogue match' + } + } + + Context 'Prerequisite text' { + BeforeAll { + $page = @( + '# Require compliant devices - Microsoft Entra ID | Microsoft Learn' + '' + 'Microsoft Entra ID works with first-party apps.' + '' + '## Prerequisites' + '' + '- A [Microsoft Entra ID P1](https://example.com/p1) licence.' + '- Devices enrolled in **Intune**.' + '' + '### Licences' + '' + '| Feature | Licence |' + '| --- | --- |' + '| Policy | P1 |' + '' + '## Create a policy' + '' + 'Create a compliance policy first. Then sign in. You must exclude your emergency access accounts.' + '' + '```powershell' + '# You must not see this.' + '```' + '' + '> [!WARNING]' + "> The policy won't work as intended without a compliant device." + '' + 'Select **Require multifactor authentication**, which requires Microsoft Entra ID P1.' + 'When a user first signs in, they pick a certificate.' + '' + '## Before you begin' + '' + 'Read the overview.' + ) + $script:found = @(Find-MtPrerequisiteText -Line $page -FirstLine 41) + } + + It 'keeps a prerequisite section whole, with its subsections, up to the next heading of its level' { + $sections = @($script:found | Where-Object Kind -EQ 'Section') + $sections.Heading | Should -Be @('Prerequisites', 'Before you begin') + $sections[0].Line | Should -Be 45 + $sections[0].EndLine | Should -Be 54 + $sections[0].Text | Should -Be "A Microsoft Entra ID P1 licence.`nDevices enrolled in Intune.`nFeature | Licence`nPolicy | P1" + $sections[1].Text | Should -Be 'Read the overview.' + } + + It 'keeps the sentences with ordering cues, with their line, heading and cues' { + $sentences = @($script:found | Where-Object Kind -EQ 'Sentence') + $sentences.Text | Should -Be @( + 'Create a compliance policy first.' + 'You must exclude your emergency access accounts.' + "The policy won't work as intended without a compliant device." + 'Select Require multifactor authentication, which requires Microsoft Entra ID P1.' + ) + $sentences[0].Line | Should -Be 58 + $sentences[0].Heading | Should -Be 'Create a policy' + $sentences[0].Cues | Should -Be @('first') + $sentences[2].Cues | Should -Be @('without') + $sentences[3].Cues | Should -Be @('requires') + } + + It 'leaves out code, first-party and first sign-in, and the bare verb require' { + ($script:found.Text -join ' ') | Should -Not -Match 'not see this|first-party|first signs' + } + + It 'looks only for the cues it is given' { + $only = @(Find-MtPrerequisiteText -Line @('You must do it first.', 'You must not.') -Cue 'first') + $only.Text | Should -Be 'You must do it first.' + } + } + + Context 'Note suggestions' { + It 'measures the longest run of words shared with the page' { + Measure-MtSharedWordRun -Text 'Create the compliance policy before the device' -Source 'You should create the compliance policy first.' | Should -Be 4 + Measure-MtSharedWordRun -Text '' -Source 'x' | Should -Be 0 + } + + It 'keeps a suggestion in its own words and rejects one that is copied, too long or not one line' { + $page = [pscustomobject]@{ Url = 'u'; Candidates = @([pscustomobject]@{ Text = 'Create a compliance policy first and ensure you have at least one compliant device before proceeding.' }) } + $notes = @( + @{ note = 'Have Intune mark at least one device compliant before the policy is on.'; lines = @(74) } + @{ note = 'Create a compliance policy first and ensure you have at least one compliant device.'; lines = @(74) } + @{ note = ('x' * 201); lines = @() } + @{ note = "Two`nlines."; lines = @() } + ) + $response = [pscustomobject]@{ stop_reason = 'end_turn'; content = @([pscustomobject]@{ type = 'text'; text = (@{ notes = $notes; untrusted_instructions = $false } | ConvertTo-Json -Depth 5) }) } + $suggestions = @(Get-MtStepNoteSuggestion -Page $page -Response $response) + $suggestions.Accepted | Should -Be @($true, $false, $false, $false) + $suggestions[1].Reason | Should -Match 'copies 14 words' + $suggestions[2].Reason | Should -Match '201 characters' + $suggestions[3].Reason | Should -Match 'more than one line' + } + + It 'drops every suggestion when the model reports instructions in the page' { + $page = [pscustomobject]@{ Url = 'u'; Candidates = @() } + $response = [pscustomobject]@{ stop_reason = 'end_turn'; content = @([pscustomobject]@{ type = 'text'; text = '{"notes":[{"note":"x","lines":[]}],"untrusted_instructions":true}' }) } + Get-MtStepNoteSuggestion -Page $page -Response $response 3>$null | Should -BeNullOrEmpty + } + + It 'sends the page''s passages as data, inside tags the page cannot close' { + $page = [pscustomobject]@{ Url = 'u'; Title = 'T'; LinkedFrom = [pscustomobject]@{ Steps = @('entra.a'); Tests = @('MT.1') }; Candidates = @([pscustomobject]@{ Line = 3; Heading = 'H'; Text = 'Do it first.' }) } + $body = New-MtStepNoteRequest -Page $page -Model 'claude-sonnet-5-5' + $body.model | Should -Be 'claude-sonnet-5-5' + $body.messages[0].content | Should -Match '\n\[line 3, under ''H''\] Do it first\.\n' + $body.messages[0].content | Should -Match 'step entra.a, test MT.1' + $body.output_config.format.type | Should -Be 'json_schema' + } + } + + Context 'Proposals file' { + BeforeAll { + $script:findCatalog = New-FixtureCatalog -Name 'find-catalog' -Steps @(New-FixtureStep -Id 'entra.a' -Key 'fixture/alias-a' -Reviewed '2026-10-05') + $script:findOut = Join-Path $TestDrive 'find/step-candidates.json' + Mock Invoke-WebRequest { throw 'No network calls in unit tests.' } + $null = & $script:findScript -Root $script:fixtureRoot -CachePath $script:cache -CatalogPath $script:findCatalog -OutputPath $script:findOut 6>$null + $script:proposals = Get-Content -LiteralPath $script:findOut -Raw | ConvertFrom-Json + } + + It 'groups the URLs of one page and records who links it' { + $pageA = $script:proposals.Pages | Where-Object Path -EQ 'docs/page-a.md' + $pageA.Url | Should -Be 'https://learn.microsoft.com/fixture/page-a' + $pageA.LinkedAs.Count | Should -Be 2 + $pageA.LinkedFrom.Steps | Should -Be 'entra.a' + $pageA.LinkedFrom.Tests | Should -Be 'MT.9001' + $pageA.Topic | Should -Be 'concept-article' + $pageA.Title | Should -Be 'Fixture fixture/page-a' + $script:proposals.Pages[0].Path | Should -Be 'docs/page-a.md' + } + + It 'links each proposal to its line in the mirror' { + $pageA = $script:proposals.Pages | Where-Object Path -EQ 'docs/page-a.md' + $pageA.Candidates.Kind | Should -Be @('Section', 'Sentence') + $pageA.Candidates[1].Text | Should -Be 'Create the policy first.' + $pageA.Candidates[1].Line | Should -Be 16 + $pageA.Candidates[1].Link | Should -Be "https://github.com/merill/entra-docs-mirror/blob/$(& git -C $script:fixtureMirror rev-parse HEAD)/docs/page-a.md?plain=1#L16" + $pageA.SuggestedNotes.Count | Should -Be 0 + } + + It 'lists the linked pages that no mirror has' { + $script:proposals.NotFound.Url | Should -Be 'https://learn.microsoft.com/graph/api/x' + $script:proposals.NotFound.Status | Should -Be 'NotMirrored' + } + + It 'needs an API key for -SuggestNote' { + $saved = $env:ANTHROPIC_API_KEY + try { + $env:ANTHROPIC_API_KEY = $null + { & $script:findScript -Root $script:fixtureRoot -CachePath $script:cache -CatalogPath $script:findCatalog -OutputPath $script:findOut -SuggestNote 6>$null } | + Should -Throw '*ANTHROPIC_API_KEY*' + } finally { + $env:ANTHROPIC_API_KEY = $saved + } + } + } + + Context 'Workflow' { + BeforeAll { + $script:workflow = Get-Content -LiteralPath (Join-Path $script:repoRoot '.github/workflows/step-sources.yaml') -Raw + } + + It 'runs weekly and by hand, with only the permissions it needs' { + $script:workflow | Should -Match '(?m)^ schedule:\s*\n\s*- cron: ''\d+ \d+ \* \* \d''' + $script:workflow | Should -Match '(?m)^ workflow_dispatch:' + $script:workflow | Should -Match '(?m)^permissions: \{\}' + $script:workflow | Should -Match '(?m)^ permissions:\r?\n contents: read\r?\n issues: write\r?\n\r?\n steps:' + $script:workflow | Should -Match 'persist-credentials: false' + } + + It 'keeps one issue and never opens a pull request' { + $script:workflow | Should -Match 'gh issue edit' + $script:workflow | Should -Not -Match 'pull-requests:|gh pr |create-pull-request' + } + } +} diff --git a/powershell/tests/general/TestShims.Tests.ps1 b/powershell/tests/general/TestShims.Tests.ps1 index 3238d8c04b..bee6ea04c0 100644 --- a/powershell/tests/general/TestShims.Tests.ps1 +++ b/powershell/tests/general/TestShims.Tests.ps1 @@ -39,7 +39,7 @@ BeforeAll { # The attributes that say what a check is about, how urgent it is and where it runs. A shim declares the # same values as the test it calls; its own are Id, Title, Control, Author and Contributor. $script:sameAttributes = @('Product', 'RelatedProduct', 'Feature', 'Area', 'ResourceType', 'Severity', 'UserImpact', - 'ImplementationCost', 'Mitre', 'Service', 'License', 'Permission', 'TenantType', 'Cloud', 'Platform', 'Lifecycle', + 'ImplementationCost', 'Mitre', 'Step', 'Service', 'License', 'Permission', 'TenantType', 'Cloud', 'Platform', 'Lifecycle', 'LongRunning', 'Exclusive') } diff --git a/report/README.md b/report/README.md index 71e18007fb..d766615985 100644 --- a/report/README.md +++ b/report/README.md @@ -69,12 +69,17 @@ Add one of these to the address of the development server to check other kinds o | `http://localhost:5173/?sample=2x` | A Maester 2.x result | | `http://localhost:5173/?sample=one` | A run of one test (the report shows the test itself) | | `http://localhost:5173/?sample=suite` | A run of the CIS suite | +| `http://localhost:5173/?sample=step` | A run of MT.1001 alone, with the defender's path of its prerequisites ("Before you fix this") | | `http://localhost:5173/?sample=tenants` | A merged result of five tenants (`Merge-MtMaesterResult`), which opens on the page that compares them | ### How the report is put together - `src/lib/model.ts` turns a result into what the views use: rows with every field, counts, the ranking of failures, framework coverage, packs and the changes since the previous run. +- `src/lib/defendersPath.ts` reads the result's `Steps` and `Goals` (the defender's path, + `docs/proposals/defenders-path.md`) into types. It is the only file that knows their shape. The report shows + what the engine wrote and works nothing out; a result without `Steps` shows no path. The sample's `Steps` and + `Goals` are in `src/lib/sampleSteps.ts`, and `src/components/report/path.tsx` has the views. - `src/components/report/views.ts` lists the views in the sidebar. A view is listed only when it has something to show, so a small run gets a short sidebar. A pack's view is built from its rows' `Fields`, so a new pack needs no code. diff --git a/report/src/components/report/TestDetail.tsx b/report/src/components/report/TestDetail.tsx index 88a7979945..14ffa67a06 100644 --- a/report/src/components/report/TestDetail.tsx +++ b/report/src/components/report/TestDetail.tsx @@ -10,6 +10,7 @@ import { FRAMEWORK_LABEL, REASONS, RESULT_LABEL, TACTICS, outcomeOf, requirement import { useReport } from "./ReportContext" import { Cmd, FeatureMark, Icon, Pill, ProductMark, Sev, copyText, formatDate, type IconName } from "./ui" import { testAsMarkdown } from "./aiText" +import { BeforeYouFix, StepRollout, stepsOfRow } from "./path" function Fact({ icon, label, value }: { icon: IconName; label: string; value: ReactNode }) { if (!value) return null @@ -61,18 +62,18 @@ export function DetailHeader({ test, inline }: { test: Row; inline?: boolean }) ) } -function tabsFor(test: Row, tenants: number) { +function tabsFor(test: Row, tenants: number, rollout: boolean) { const guide = splitGuide(test.Description) const tabs: [string, string, IconName, number | null][] = [["finding", "Finding", "finding", null]] - if (guide.fix || guide.about) tabs.push(["fix", "How to fix", "fix", null]) + if (guide.fix || guide.about || rollout) tabs.push(["fix", "How to fix", "fix", null]) if (tenants > 1) tabs.push(["tenants", "Tenants", "tenant", tenants]) tabs.push(["details", "Details", "tag", null], ["frameworks", "Frameworks", "framework", requirementsOf(test).length], ["attack", "ATT&CK", "attack", test.Mitre.length], ["history", "History", "history", null]) return tabs } export function DetailTabs({ test }: { test: Row }) { - const { tab, setTab, models } = useReport() - const tabs = tabsFor(test, models.length) + const { tab, setTab, model, models } = useReport() + const tabs = tabsFor(test, models.length, stepsOfRow(model, test).some((s) => s.Rollout.length > 0)) const current = tabs.some(([k]) => k === tab) ? tab : "finding" const onKey = (e: KeyboardEvent) => { if (e.key !== "ArrowRight" && e.key !== "ArrowLeft") return @@ -95,7 +96,7 @@ export function DetailTabs({ test }: { test: Row }) { export function DetailBody({ test }: { test: Row }) { const { model, models, tenantIndex, selectTenant, tab } = useReport() const { pathname } = useLocation() - const tabs = tabsFor(test, models.length) + const tabs = tabsFor(test, models.length, stepsOfRow(model, test).some((s) => s.Rollout.length > 0)) const current = tabs.some(([k]) => k === tab) ? tab : "finding" const ref = useRef(null) useEffect(() => { ref.current?.scrollTo(0, 0) }, [current, test.Id]) @@ -112,12 +113,14 @@ export function DetailBody({ test }: { test: Row }) { {outcome &&
What an attacker could do: {outcome.title.toLowerCase()}. {outcome.text}
} {test.ReasonCode &&
{(REASONS[test.ReasonCode] || [test.ReasonCode])[0]}. {test.ReasonDetail}
}

What Maester found

{test.Detail ? {test.Detail} :

The test recorded no details.

}
+ {guide.about &&

Why it matters

{guide.about}
} ) else if (current === "fix") body = ( <> -

How to fix it

{guide.fix || guide.about}
+ {(guide.fix || guide.about) &&

How to fix it

{guide.fix || guide.about}
} +

Then check it again

) diff --git a/report/src/components/report/lists.tsx b/report/src/components/report/lists.tsx index 6265037834..b3b4f952a0 100644 --- a/report/src/components/report/lists.tsx +++ b/report/src/components/report/lists.tsx @@ -4,6 +4,7 @@ import { RESULT_LABEL, isQuickWin, maesterVersion, sortTests, tally, type Model, import { reportHeading } from "@/lib/runSubject" import { useReport } from "./ReportContext" import { FeatureMark, Pill, ProductMark, Sev } from "./ui" +import { blockedStepsOf } from "./path" export const GROUPS: Record = { none: "No grouping", product: "Product", area: "Area", feature: "Feature", severity: "Severity", source: "Source", result: "Result" } @@ -78,6 +79,7 @@ export function FixList({ rows, limit }: { rows: Row[]; limit: number }) {
{model.productName(t.Product)}·{t.Id} {model.changes.newlyFailing.includes(t) && New since last run} + {blockedStepsOf(model, t).slice(0, 1).map((s) => Blocked by: {s.BlockedBy.map((id) => model.path?.step(id)?.Title || id).join("; ")})}
diff --git a/report/src/components/report/nav.ts b/report/src/components/report/nav.ts index 5cb8627e18..bfb4ebcdd1 100644 --- a/report/src/components/report/nav.ts +++ b/report/src/components/report/nav.ts @@ -107,7 +107,7 @@ export function buildNav(model: Model, extra: NavExtras): NavModel { // The pages that cover the whole run. const summary: NavItem[] = [{ key: "/", title: focused ? (model.rows.length === 1 ? "Result" : "Results") : "Overview", path: "/", icon: "home" }] - if (model.failing.length >= 2) summary.push({ key: "/plan", title: "Action plan", path: "/plan", icon: "fix", count: model.failing.length, bad: true }) + if (model.failing.length >= 2 || (!focused && model.path)) summary.push({ key: "/plan", title: "Action plan", path: "/plan", icon: "fix", count: model.failing.length, bad: true }) if (!focused && model.previous && model.changes.newlyFailing.length + model.changes.fixed.length > 0) { summary.push({ key: "/changes", title: "Changes since last run", path: "/changes", icon: "history", count: model.changes.newlyFailing.length, bad: true }) } diff --git a/report/src/components/report/path.tsx b/report/src/components/report/path.tsx new file mode 100644 index 0000000000..f56d076b3e --- /dev/null +++ b/report/src/components/report/path.tsx @@ -0,0 +1,318 @@ +// The defender's path in the report: the action plan's step groups and goal lanes, the overview card, "Before you +// fix this" and the rollout on a test page. Everything here reads the result's Steps and Goals as the engine wrote +// them (lib/defendersPath.ts); nothing works out a status, an order or a count of its own. + +import { useEffect, useState } from "react" +import { Link } from "@/lib/router" +import { REASONS, fixCommand, type Model, type Row } from "@/lib/model" +import { + GOAL_STATUS_LABEL, GROUPS, NOT_CHECKED_REASON, READINESS_LABEL, STATUS_LABEL, measureFigure, prerequisiteMet, prerequisitesOf, testsThatRan, + type DefendersPath, type Goal, type Step, type StepMeasure, type StepStatus, +} from "@/lib/defendersPath" +import { useReport } from "./ReportContext" +import { Cmd, Pill, ProductMark, formatDate, plural } from "./ui" + +const STATUS_CLASS: Record = { Done: "Passed", NotDone: "Failed", Unknown: "Investigate", NotChecked: "NotRun", NotApplicable: "Skipped" } +const KIND_LABEL: Record = { Requires: "Required", RequiresOneOf: "One of these", RecommendedFirst: "Recommended first", Conflicts: "Must be off" } + +export const StepPill = ({ status }: { status: StepStatus }) => {STATUS_LABEL[status]} + +function Readiness({ step }: { step: Step }) { + // "Ready" on a step this run could not check says nothing the group heading doesn't. + if (!step.Readiness || (step.Readiness === "Ready" && step.Status !== "NotDone")) return null + const tone = step.Readiness === "Ready" ? " good" : step.Readiness === "Blocked" ? " bad" : " warn" + return {READINESS_LABEL[step.Readiness]} +} + +/** The steps a test verifies: the result's Steps that list it, then any other step its row names. */ +export function stepsOfRow(model: Model, t: Row): Step[] { + const path = model.path + if (!path) return [] + const out = [...path.stepsOfTest(t.Id)] + for (const id of t.Step) { const s = path.step(id); if (s && !out.includes(s)) out.push(s) } + return out +} + +/** The steps a failed test waits for, when its step is Blocked. */ +export function blockedStepsOf(model: Model, t: Row): Step[] { + return stepsOfRow(model, t).filter((s) => s.Readiness === "Blocked") +} + +// Opens the step's group when the card is past its first few, then scrolls to the card. +function scrollToStep(id: string) { + window.dispatchEvent(new CustomEvent("mt-step", { detail: id })) + window.setTimeout(() => document.getElementById(`mt-step-${id}`)?.scrollIntoView({ behavior: "smooth", block: "start" }), 30) +} + +function StepRef({ path, id, linked }: { path: DefendersPath; id: string; linked?: boolean }) { + const s = path.step(id) + const label = s ? s.Title : id + if (linked && s && path.group(s)) return + return {label} +} + +function TestRef({ id }: { id: string }) { + const { model, openTest } = useReport() + return model.byId.has(id) + ? { e.preventDefault(); openTest(id) }}>{id} + : {id} +} + +function typeName(type: string, n: number) { + const name = type ? type.replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase() : "object" + return n === 1 ? name : `${name}s` +} + +/** A measure: its figure against the share needed, its caveat and the objects that fall short. */ +export function MeasureView({ measure, title }: { measure: StepMeasure; title: string }) { + if (measure.ReasonCode) { + const [head, text] = REASONS[measure.ReasonCode] || [measure.ReasonCode, ""] + return
{title}Couldn't be read

{head}. {text}

+ } + const share = measure.Share ?? 0 + const type = measure.Objects[0]?.Type || "" + return ( +
+
{title}{measureFigure(measure)}
+
+ + {measure.MinimumShare !== null && } +
+ {measure.Caveat &&

{measure.Caveat}

} + {measure.ObjectCount > 0 && ( +
+ {measure.ObjectCount} {typeName(type, measure.ObjectCount)} fall short +
    {measure.Objects.slice(0, 20).map((o) =>
  • {o.DisplayName}
  • )}
+ {measure.ObjectCount > Math.min(20, measure.Objects.length) &&

{measure.ObjectCount - Math.min(20, measure.Objects.length)} more{measure.Objects.length < measure.ObjectCount ? `. The result keeps the first ${measure.Objects.length}` : " in the result"}.

} +
+ )} + {measure.ReadAt &&

Read {formatDate(measure.ReadAt, true)}.

} +
+ ) +} + +function Sources({ step }: { step: Step }) { + if (!step.Sources.length) return null + return ( + + ) +} + +/** Why this run could not tell whether a step is done, and the command that would. */ +function NotKnown({ step }: { step: Step }) { + const { model } = useReport() + if (step.Status === "NotChecked") { + return ( +
+ {step.Reason === "NoCheck" && step.Unchecked ? step.Unchecked : NOT_CHECKED_REASON[step.Reason || ""] || "Not checked in this run."} + {step.Earlier && {STATUS_LABEL[step.Earlier.Status]} in an earlier run on {formatDate(step.Earlier.ExecutedAt)}.} + {step.Reason === "NotSelected" && } +
+ ) + } + if (step.Status !== "Unknown") return null + const unsure = testsThatRan(step).filter((t) => t.Result !== "Passed" && t.Result !== "Failed") + const codes = [...new Set([...unsure.map((t) => t.ReasonCode || (t.Result === "Error" ? "TestError" : t.Result)), ...(step.Measure?.ReasonCode ? [step.Measure.ReasonCode] : [])])] + const commands = [...new Set(unsure.map((t) => { const row = model.byId.get(t.Id); return row ? fixCommand(row) : "" }).filter(Boolean))] + return ( +
+ This run could not tell: {codes.map((c) => (REASONS[c] || [c])[0].toLowerCase()).join(", ") || "a check needs a closer look"}. + {commands.slice(0, 2).map((c) => )} +
+ ) +} + +export function StepCard({ step }: { step: Step }) { + const { model } = useReport() + const path = model.path! + const ran = testsThatRan(step) + const failed = step.Tests.filter((t) => t.Result === "Failed") + const unlocked = step.Unlocks.map((id) => path.step(id)).filter((s): s is Step => !!s) + const unlockedFailures = unlocked.reduce((n, s) => n + s.Tests.filter((t) => t.Result === "Failed").length, 0) + return ( +
+
+ + {step.Title} + +
+ {step.Summary &&

{step.Summary}

} + {step.Measure && } + {step.BlockedBy.length > 0 &&
Blocked by{step.BlockedBy.map((id) => )}
} + {step.Unconfirmed.length > 0 &&
Check first{step.Unconfirmed.map((id) => )}
} + + {step.Tests.length > 0 && ( +
+ {failed.length ? `${plural(failed.length, "check")} failed · ` : ""}{ran.length} of {plural(step.Tests.length, "check")} ran + {step.Tests.map((t) => {t.Result === "NotRun" ? Not in this run : })} +
+ )} + {unlocked.length > 0 && ( +
Unlocks {plural(unlocked.length, "step")}{unlockedFailures ? `, ${plural(unlockedFailures, "failed check")}` : ""}{unlocked.map((s) => )}
+ )} + {(step.Rollout.length > 0 || step.Sources.length > 0) && ( +
+ {step.Rollout.length ? "How to roll it out" : "Sources"} + {step.Rollout.length > 0 &&
    {step.Rollout.map((r, i) =>
  1. {r}
  2. )}
} + +
+ )} +
+ ) +} + +const GROUP_LIMIT = 6 + +function Group({ group, steps }: { group: (typeof GROUPS)[number]; steps: Step[] }) { + const [all, setAll] = useState(false) + // A link to a step's card shows the whole group, so the card is there to scroll to. + useEffect(() => { + const show = (e: Event) => { if (steps.some((s) => s.Id === (e as CustomEvent).detail)) setAll(true) } + window.addEventListener("mt-step", show) + return () => window.removeEventListener("mt-step", show) + }, [steps]) + const shown = all ? steps : steps.slice(0, GROUP_LIMIT) + return ( +
+

{group.title} · {steps.length}

+

{group.text}

+
{shown.map((s) => )}
+ {steps.length > shown.length && } +
+ ) +} + +/** The action plan's three groups of steps, in Rank order. */ +export function PathGroups() { + const { model } = useReport() + const path = model.path + if (!path) return null + return <>{GROUPS.map((g) => (path.groups[g.key].length ? : null))} +} + +function Lane({ goal }: { goal: Goal }) { + const { model } = useReport() + const path = model.path! + const steps = goal.Steps.map((id) => ({ id, step: path.step(id) })) + const open = steps.filter(({ step }) => step && (step.Status === "Unknown" || step.Status === "NotChecked")).length + return ( +
+
+ {goal.Title} · {goal.Done} of {plural(goal.Applicable, "step")} done{open ? ` · ${open} to check` : ""} + {GOAL_STATUS_LABEL[goal.Status]} +
+
    + {steps.map(({ id, step }) => ( +
  1. +