diff --git a/.github/skills/maester-test-expert/SKILL.md b/.github/skills/maester-test-expert/SKILL.md index 3ec07b238a..a58c985e11 100644 --- a/.github/skills/maester-test-expert/SKILL.md +++ b/.github/skills/maester-test-expert/SKILL.md @@ -76,12 +76,12 @@ background to avoid user confusion. | `Test..ps1` | `tests//[/]` | One function with a `[MaesterTest(...)]` attribute. Reads the tenant, decides, calls `Add-MtTestResultDetail`, returns `$true`/`$false`. | | `Test..md` | Same folder, same base name | Description, `#### Remediation action`, optional `#### Related links`, then `` and `%TestResult%`. Shown in the report. | | `suite.json` | Each suite folder (already exists) | The suite's ID, name, `Source` and help URL template. Do not edit for a single check. | -| `frameworks/.json` | Beside the `suite.json` of the CIS, CISA and ASD suites | The catalogue of the benchmark: its name and version, and one entry per requirement with its level, profiles or criticality (ASD: maturity level and strategy, or ISM guideline, section and applicability). It does not list tests. A CIS, CISA or ASD check names its requirement in `Control`; add the requirement here in the same pull request if it is new, or the build fails. The ASD files are generated by `build/asd/Update-AsdFramework.ps1`. | +| `frameworks/.json` | Beside the `suite.json` of the CIS, CISA, ASD and DISA suites | The catalogue of the benchmark: its name and version, and one entry per requirement with its level, profiles or criticality (ASD: maturity level and strategy, or ISM guideline, section and applicability). It does not list tests. A CIS, CISA or ASD check names its requirement in `Control`; add the requirement here in the same pull request if it is new, or the build fails. The ASD files are generated by `build/asd/Update-AsdFramework.ps1`. | Suite folders: `tests/maester//` (`MT.xxxx`; services such as `entra`, `exchange`, `teams`, `defender`, `azure`, `intune`, and `xspm` for exposure management, which has its own `suite.json`), `tests/cisa//` (`CISA.MS.*`), `tests/cis/` (`CIS.M365.*`), `tests/asd//` (`ASD.ISM-xxxx`, named after the ISM control the -check implements), `tests/ad//` (`AD-*`), and the generated `tests/eidsca/` and +check implements), `tests/disa/` (`DISA.V-xxxxxx`, named after the STIG rule), `tests/ad//` (`AD-*`), and the generated `tests/eidsca/` and `tests/orca/`. Every folder name is lowercase kebab-case; see the repository layout in [the contributing guide](../../../website/docs/contributing.md#repository-layout). @@ -104,8 +104,18 @@ New-MtTest -Id MT.1234 -Title 'At least one Conditional Access policy blocks dev ``` Only `-Id` and `-Title` are required, so you can scaffold first and set the other values once the `.md` is -written (see [Choosing the attribute values](#choosing-the-attribute-values)). `New-MtTest` does not write -`Author`; add it. +written (see [Choosing the attribute values](#choosing-the-attribute-values)). `New-MtTest` is made for custom +tests, so for a built-in check finish what it leaves: + +- It warns that the `MT`, `CIS`, `CISA`, `ASD` and other built-in prefixes are reserved. For a check that ships + with Maester the warning is expected; ignore it. +- It names the function after the ID (`Test-MT1234`). Rename it to say what it checks + (`Test-MtCaBlockDeviceCodeFlow`), with the `Mt` prefix and an approved verb. +- `-Setting EmergencyAccessAccounts` (one or more registered settings) writes the bound parameter for each, with + the registry's type, default and allowed values. Other parameters are added by hand; the + [test builder](https://maester.dev/test-builder) writes them and checks their names. +- It does not write `Author`. Add the contributor's GitHub handle; ask if you do not know it, and do not take it + from the git email address. ```powershell function Test-MtCaBlockDeviceCodeFlow { @@ -235,6 +245,10 @@ Licence tokens: `AAD_PREMIUM` (Entra ID P1 or better), `AAD_PREMIUM_P2`, `Entra_ that kind exist). Never return `$null` to mean "not applicable". - Never use `NotConnected*` or `NotLicensed*` skip codes in a built-in check; declare `Service` / `License`. +- A check that needs a setting the organisation has not filled in, such as `EmergencyAccessAccounts`, must not + fail and must not pass: skip with `-SkippedBecause Custom -SkippedCustomReason ''`, naming + the setting and linking its configuration page (see `tests/maester/global-secure-access/Test.MT.1191.ps1`). + `NotApplicable` is for tenant state, not for missing configuration. - Checks that need delegated permissions skip with `-SkippedBecause NotSupportedAppPermission` when `(Get-MgContext).AuthType -ne 'Delegated'`. @@ -254,8 +268,12 @@ param( ) ``` -- Types: `int`, `bool`, `switch`, `string`, `string[]`. Constant defaults. Nothing mandatory: the check must run - with no config. +- Types: `int`, `bool`, `switch`, `string`, `string[]` (and `object[]` only when bound to a setting). Constant + defaults. Nothing mandatory: the check must run with no config. +- Names follow the rubric's "Parameter names": PascalCase; `Maximum`/`Minimum` + what + unit + (`MaximumInactiveDays`, never `MaxInactiveDays` or `...InDays`); plural lists (`ExcludedGroups`); say what is + measured. Reuse a name other tests already use for the same idea (`Get-MtTest` lists them). Unit tests + (`TestParameterNames.Tests.ps1`) and the attribute review enforce this. - Every parameter has a **one-line** `#` comment directly above it (only the nearest comment line is read), or `.PARAMETER` help. The unit tests require a description. - Thresholds get `ValidateRange`; choices get `ValidateSet`. @@ -279,8 +297,34 @@ Each instance object has `Id` (required, unique, `^[A-Za-z0-9][A-Za-z0-9._-]{0,1 ### Settings -Read tenant-wide settings with `Get-MtSetting -Name ` (for example `EmergencyAccessAccounts`). New settings -Maester itself reads go in `powershell/assets/MaesterSettings.psd1` with a type, default and description. +A tenant-wide setting (`EmergencyAccessAccounts`, `ParkedDomains`, ...) reaches a check as a parameter bound to it, +never through `Get-MtSetting` in the check: + +```powershell +param( + # Emergency access (break glass) accounts and groups, from the EmergencyAccessAccounts setting. + [MaesterParameter(Setting = 'EmergencyAccessAccounts')] + [object[]] $EmergencyAccessAccounts = @() +) +``` + +The engine binds `GlobalSettings.` when the test's `TestSettings` row does not set the parameter, and +records `Source = 'Setting'`. Pass the value on to helpers (`Get-MtEmergencyAccessAccount -Account +$EmergencyAccessAccounts`). Bind only a fact about the tenant or a choice made once for all tests; a value a +benchmark sets stays a plain parameter. A new built-in setting goes in `powershell/assets/MaesterSettings.psd1` +with its `Type`, default, description, `AllowedValues`, `Items` (for a list of objects) and, for IDs or domains, +`Kind`. The parameter's type, default and `ValidateSet` must match the registry entry, because the config is +checked against the registry once before a run. + +- A built-in test never calls `Get-MtSetting`, and a helper never reads a setting that tests bind. +- A shim declares each bound parameter of the test it calls and passes it on + (`return Test-MtX -EmergencyAccessAccounts $EmergencyAccessAccounts`); otherwise the called test runs with the + default. +- A connection or transport setting that a connect command or data helper needs is read with `Get-MtSetting` and + must still be registered; the read is recorded on the result as `SettingsRead`. +- A pack declares its `Namespace.Key` settings under `Settings` in `maester-pack.json`. + +`powershell/tests/general/TestParameterNames.Tests.ps1` and `TestShims.Tests.ps1` enforce these. ## Data Retrieval @@ -531,8 +575,16 @@ the rubric. When you review a check yourself, follow "Reviewing a test's attribu rules of a custom test, so it does not report a missing attribute or a key that is not in the taxonomy. 9. **Run against a tenant**: `Connect-Maester; Invoke-MtTest -Path ` (or `Invoke-MtTest -Id `). Try `-Parameter @{...}` for each parameter. Check the row's `Result`, `ReasonCode`, `ResultDetail.TestResult`. -10. **Run the unit tests**: `./powershell/tests/pester.ps1`. `powershell/tests/general/NativeTestLint.Tests.ps1` - and `powershell/tests/general/NativeTestAttributes.Tests.ps1` check every built-in test. +10. **Update the golden fixture.** A new built-in test changes the number of tests each selection returns, so + `powershell/tests/general/Golden.Tests.ps1` fails until you run `./build/golden/Export-MtGoldenFixture.ps1` and + commit `powershell/tests/fixtures/golden/selection.json`. Commit only that file: on macOS and Windows the + script can also rewrite the case of a path in `config-layouts/`, which you revert. +11. **Update the pages that list the tests of a setting.** If the check binds `EmergencyAccessAccounts`, add it to + "Related Tests" in `website/docs/configuration/emergency-access-accounts.md`. +12. **Run the unit tests**: `./powershell/tests/pester.ps1`. `powershell/tests/general/NativeTestLint.Tests.ps1` + and `powershell/tests/general/NativeTestAttributes.Tests.ps1` check every built-in test. A new `.ps1` file + needs a UTF-8 byte order mark (`FileEncoding.Tests.ps1`); the test only sees files git tracks, so `git add` + the new files before the run. ## Converting a User's Pester-format Test diff --git a/.github/workflows/blog-cards.yaml b/.github/workflows/blog-cards.yaml index 59081fbbeb..1cb10ab787 100644 --- a/.github/workflows/blog-cards.yaml +++ b/.github/workflows/blog-cards.yaml @@ -64,7 +64,7 @@ jobs: run: node scripts/blog-cards/generate-blog-cards.mjs --suggest - name: Create pull request - uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8.1.1 + uses: peter-evans/create-pull-request@15733dbdfeedb4f7fdb73d13c6f5ac83b710fab8 # v8.1.2 with: token: ${{ steps.app-token.outputs.token }} branch: automation/blog-cards diff --git a/.github/workflows/build-engine.yaml b/.github/workflows/build-engine.yaml index 2dae47b33b..442cbf99ec 100644 --- a/.github/workflows/build-engine.yaml +++ b/.github/workflows/build-engine.yaml @@ -32,7 +32,7 @@ jobs: with: persist-credentials: false - - uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 + - uses: actions/setup-dotnet@0f4a354dd5547a28c70b7853dbd95d5b67886e73 # v6.1.0 with: global-json-file: src/global.json diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index a7cd713817..f55ef138c0 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -77,13 +77,13 @@ jobs: # uses: actions/setup-example@v1 - name: Setup .NET if: matrix.language == 'csharp' - uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 + uses: actions/setup-dotnet@0f4a354dd5547a28c70b7853dbd95d5b67886e73 # v6.1.0 with: global-json-file: src/global.json # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL - uses: github/codeql-action/init@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4 + uses: github/codeql-action/init@33d7b85da1a04171e211befe2c739303b9a4c066 # v4 with: languages: ${{ matrix.language }} build-mode: ${{ matrix.build-mode }} @@ -109,6 +109,6 @@ jobs: run: dotnet build Maester.Engine.csproj -c Release -o "$RUNNER_TEMP/maester-engine" -nologo - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4 + uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # v4 with: category: "/language:${{matrix.language}}" diff --git a/.github/workflows/eidsca-sync.yaml b/.github/workflows/eidsca-sync.yaml index 8ff50ae9e3..091325669c 100644 --- a/.github/workflows/eidsca-sync.yaml +++ b/.github/workflows/eidsca-sync.yaml @@ -107,7 +107,7 @@ jobs: # With no changes against main, the action closes an open pull request and deletes its branch. - name: Create or update the sync pull request id: pr - uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8.1.1 + uses: peter-evans/create-pull-request@15733dbdfeedb4f7fdb73d13c6f5ac83b710fab8 # v8.1.2 with: token: ${{ steps.app-token.outputs.token }} commit-message: 'chore: update EIDSCA tests from the EIDSCA config' diff --git a/.github/workflows/publish-module-manualversionupdate.yaml b/.github/workflows/publish-module-manualversionupdate.yaml index a97ac39812..17ec057b83 100644 --- a/.github/workflows/publish-module-manualversionupdate.yaml +++ b/.github/workflows/publish-module-manualversionupdate.yaml @@ -124,7 +124,7 @@ jobs: run: node ./build/Update-WebsiteReleaseVersion.mjs "$MODULE_VERSION" - name: Create website release version pull request - uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8.1.1 + uses: peter-evans/create-pull-request@15733dbdfeedb4f7fdb73d13c6f5ac83b710fab8 # v8.1.2 with: token: ${{ steps.app-token.outputs.token }} commit-message: 'ci(docs): update website release version ${{ steps.moduleversion.outputs.tag }}' diff --git a/.github/workflows/publish-module.yaml b/.github/workflows/publish-module.yaml index 408636eaef..f135b3059d 100644 --- a/.github/workflows/publish-module.yaml +++ b/.github/workflows/publish-module.yaml @@ -124,7 +124,7 @@ jobs: run: node ./build/Update-WebsiteReleaseVersion.mjs "$MODULE_VERSION" - name: Create website release version pull request - uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8.1.1 + uses: peter-evans/create-pull-request@15733dbdfeedb4f7fdb73d13c6f5ac83b710fab8 # v8.1.2 with: token: ${{ steps.app-token.outputs.token }} commit-message: 'ci(docs): update website release version ${{ steps.moduleversion.outputs.tag }}' diff --git a/.github/workflows/update-eam-classification.yaml b/.github/workflows/update-eam-classification.yaml index d9e7130423..a35ab1751c 100644 --- a/.github/workflows/update-eam-classification.yaml +++ b/.github/workflows/update-eam-classification.yaml @@ -156,7 +156,7 @@ jobs: - name: Create Pull Request if: steps.diff.outputs.changed == 'true' - uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8.1.1 + uses: peter-evans/create-pull-request@15733dbdfeedb4f7fdb73d13c6f5ac83b710fab8 # v8.1.2 with: token: ${{ steps.app-token.outputs.token }} commit-message: 'chore: update EAM role classification' diff --git a/.github/workflows/update-license-service-plans.yaml b/.github/workflows/update-license-service-plans.yaml index 4a29be8268..9c41b9eb27 100644 --- a/.github/workflows/update-license-service-plans.yaml +++ b/.github/workflows/update-license-service-plans.yaml @@ -40,7 +40,7 @@ jobs: permission-pull-requests: write - name: Create Pull Request - uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8.1.1 + uses: peter-evans/create-pull-request@15733dbdfeedb4f7fdb73d13c6f5ac83b710fab8 # v8.1.2 with: token: ${{ steps.app-token.outputs.token }} add-paths: | diff --git a/.github/workflows/update-public-suffix-list.yaml b/.github/workflows/update-public-suffix-list.yaml index 1bd2bbb683..bb062de96a 100644 --- a/.github/workflows/update-public-suffix-list.yaml +++ b/.github/workflows/update-public-suffix-list.yaml @@ -36,7 +36,7 @@ jobs: permission-pull-requests: write - name: Create Pull Request - uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8.1.1 + uses: peter-evans/create-pull-request@15733dbdfeedb4f7fdb73d13c6f5ac83b710fab8 # v8.1.2 with: token: ${{ steps.app-token.outputs.token }} commit-message: 'chore: update public suffix list' diff --git a/.github/workflows/update-role-definitions.yaml b/.github/workflows/update-role-definitions.yaml index 8fa51a73ae..41d4c70274 100644 --- a/.github/workflows/update-role-definitions.yaml +++ b/.github/workflows/update-role-definitions.yaml @@ -38,7 +38,7 @@ jobs: - name: Create Pull Request if: success() - uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8.1.1 + uses: peter-evans/create-pull-request@15733dbdfeedb4f7fdb73d13c6f5ac83b710fab8 # v8.1.2 with: token: ${{ steps.app-token.outputs.token }} title: Update Entra ID role definitions diff --git a/AGENTS.md b/AGENTS.md index de6f66ec5b..6db6151908 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -26,7 +26,10 @@ maester.dev), `report/` (React app that builds the HTML report template). ## Commands -- Unit tests: `./powershell/tests/pester.ps1` — run before pushing. These enforce +- New built-in test: `git add` its files, then `./build/golden/Export-MtGoldenFixture.ps1` and commit + `powershell/tests/fixtures/golden/selection.json` (the selection counts change); the unit tests fail otherwise. +- Unit tests: `./powershell/tests/pester.ps1` — run before pushing. Some checks (file encoding) only see files + git tracks, so `git add` new files first. These enforce naming, exports, help, and PSScriptAnalyzer conventions; fix what they flag. - Build module: `./build/Build-MaesterModule.ps1`; validate: `./build/Test-MaesterModuleOutput.ps1` - Website: `cd website && npm ci && npm start` · Report: `cd report && npm ci && npm run build` @@ -51,17 +54,20 @@ maester.dev), `report/` (React app that builds the HTML report template). - A test is mapped to a framework in one place: the `Control` attribute, `:`. A CIS test carries `Control = 'cis-m365:5.1.5.1'`, a CISA test `Control = 'cisa-scuba:MS.AAD.3.1'`, and any other test may name the same requirements. An ASD test carries `Control = 'essential-eight:ISM-1504'` (or `ism:` for a - control outside the maturity model). Every test in `tests/cis`, `tests/cisa` and `tests/asd` must name a requirement of its + control outside the maturity model). A DISA test carries the STIG rule it checks, `Control = 'disa-stig-entra-id:V-270233'`. + Every test in `tests/cis`, `tests/cisa`, `tests/asd` and `tests/disa` must name a requirement of its suite's framework. The engine builds `Benchmark` from the first `Control` that a framework file knows and adds that requirement's `Related` references to `Control`; do not repeat those, and do not add benchmark tags. - A framework file is a catalogue, not a list of tests: `tests//frameworks/.json` (`tests/cis/frameworks/cis-m365.json`, `tests/cis/frameworks/cis-github.json`, `tests/cisa/frameworks/cisa-scuba.json`, and the generated `tests/asd/frameworks/essential-eight.json` and - `tests/asd/frameworks/ism.json`, written by `build/asd/Update-AsdFramework.ps1` from the ISM OSCAL release), + `tests/asd/frameworks/ism.json`, written by `build/asd/Update-AsdFramework.ps1` from the ISM OSCAL release, and + the DISA STIG files `tests/disa/frameworks/disa-stig-entra-id.json`, `disa-stig-intune-mdm.json` and + `disa-stig-intune-desktop.json`), declared in the suite's `suite.json` (`Frameworks`: `Key`, `Version`). It holds the framework's name and version and each requirement's `Id` and facts (CIS `Level` and `Profile`; CISA `Criticality`, `Upstream` and `Related` NIST references; Essential Eight `Level` and `Strategy`; - ISM `Guideline`, `Section` and `Applicability`), never the text of a benchmark and + ISM `Guideline`, `Section` and `Applicability`; DISA STIG `Category`, `RuleId` and `StigId`), never the text of a benchmark and never a `Tests` list. When a new test implements a requirement the file does not have, add the requirement in the same commit, or `./build/Build-MaesterModule.ps1` and the unit tests fail. - Checks read through the session cache. A run reports on one snapshot of the tenant, so no check, pack or helper @@ -87,7 +93,7 @@ enforces them. When writing or reviewing a change, check every added, moved or r framework files, `frameworks/.json` beside its `suite.json` (lowercase key; nothing else goes in a `frameworks/` folder). Suites: `maester//` (plus `drift/`; `maester/xspm/` has its own suite.json), - `cis/`, `cisa//`, `asd//`, `ad//`, generated `eidsca/` and `orca/`, and `custom/` + `cis/`, `cisa//`, `asd//`, `disa/`, `ad//`, generated `eidsca/` and `orca/`, and `custom/` (reserved for users; never commit tests there). - `powershell/public/` (exported) is grouped by job: `run/`, `connect/`, `report/`, `app/`, `packs/`, `services//`. `powershell/internal/` uses `engine/`, `session/`, `connect/`, diff --git a/README.md b/README.md index 4d04e37b9c..ae436dcdad 100644 --- a/README.md +++ b/README.md @@ -152,8 +152,8 @@ Contributions are welcome! If you want to contribute new tests or improve existi Thank you to the organisations and people who sponsor Maester and its maintainers. You make Maester possible.

- CyberDrain     - Increment + Increment     + CyberDrain

The people and organisations who sponsor the maintainers of Maester diff --git a/build/docs/Export-MtTestCatalogForDocs.ps1 b/build/docs/Export-MtTestCatalogForDocs.ps1 index 4383f526c0..b861bda0a2 100644 --- a/build/docs/Export-MtTestCatalogForDocs.ps1 +++ b/build/docs/Export-MtTestCatalogForDocs.ps1 @@ -7,6 +7,9 @@ with Get-MtTest and writes its metadata to a JSON file. website/scripts/generate-test-docs.mjs reads that file, plus each test's Test..md, to build the test pages of the website. + Each test also has TenantType, Cloud, Platform, Exclusive and Parameters (name, type, description, default, + range, allowed values, kind and bound setting), which the test builder reads to load an existing test. + Each test has its attributes (Product, RelatedProduct, Feature, Area and ResourceType as taxonomy keys), the derived Block, Suite and Source, and LegacyTag: the tags it carried in Maester 2.x, which -Tag still matches. Taxonomy at the top level gives the display names of the keys and ATT&CK techniques the tests use. @@ -92,9 +95,25 @@ $catalog = foreach ($t in $sorted) { Service = ConvertTo-StringArray $t.Service License = ConvertTo-StringArray $t.License Permission = ConvertTo-StringArray $t.Permission + TenantType = ConvertTo-StringArray $t.TenantType + Cloud = ConvertTo-StringArray $t.Cloud + Platform = ConvertTo-StringArray $t.Platform Lifecycle = "$($t.Lifecycle)" ReplacedBy = if ($t.ReplacedBy) { "$($t.ReplacedBy)" } else { '' } LongRunning = [bool]$t.LongRunning + Exclusive = [bool]$t.Exclusive + Parameters = @($t.Parameters | Where-Object { $_ -and -not $_.EngineOwned } | ForEach-Object { + [ordered]@{ + Name = $_.Name + Type = $_.Type + Description = "$($_.Description)" + Default = if ($_.HasDefault) { $_.Default } else { $null } + Range = if ($_.Range) { , @($_.Range) } else { $null } + AllowedValues = ConvertTo-StringArray $_.AllowedValues + Kind = "$($_.Kind)" + Setting = "$($_.Setting)" + } + }) InstanceSource = if ($t.InstanceSource) { "$($t.InstanceSource)" } else { '' } Tag = ConvertTo-StringArray $t.Tag LegacyTag = ConvertTo-StringArray (& $module { param($test) (Get-MtSelectionTag -Test $test).Legacy } $t) diff --git a/build/review/Invoke-MtAttributeReview.ps1 b/build/review/Invoke-MtAttributeReview.ps1 index b55d40d765..ee8534ced2 100644 --- a/build/review/Invoke-MtAttributeReview.ps1 +++ b/build/review/Invoke-MtAttributeReview.ps1 @@ -87,6 +87,9 @@ $ErrorActionPreference = 'Stop' # The attributes the rubric governs. Everything else on [MaesterTest] is mechanical and checked by unit tests. $script:RubricAttribute = @('Product', 'RelatedProduct', 'Feature', 'Area', 'ResourceType', 'Severity', 'UserImpact', 'ImplementationCost', 'Mitre') +# What the review judges: the rubric attributes, and the names of the test's parameters (the rubric's +# "Parameter names" section). Parameters is read from the param() block, not from [MaesterTest]. +$script:ReviewedAttribute = @($script:RubricAttribute) + 'Parameters' # A test file larger than this is not sent. It is reported as not reviewable instead of being cut short. $script:MaxSourceLength = 120000 @@ -152,6 +155,43 @@ function Get-MtReviewAttribute { $result } +function Get-MtReviewParameter { + <# + .SYNOPSIS + Reads the parameters of the [MaesterTest] function from the text of a test file without running it, as + "Name [type]" or "Name [type] setting=Setting", sorted. Parameters the engine supplies are left out. + #> + [CmdletBinding()] + [OutputType([string[]])] + param( + [AllowEmptyString()] + [string] $Content + ) + + if ([string]::IsNullOrWhiteSpace($Content) -or $Content -match '(?im)^\s*using\s+(module|assembly|namespace)\b') { return , @() } + $tokens = $null + $parseErrors = $null + $ast = [System.Management.Automation.Language.Parser]::ParseInput($Content, [ref] $tokens, [ref] $parseErrors) + $function = $ast.FindAll({ + param($node) + $node -is [System.Management.Automation.Language.FunctionDefinitionAst] -and $node.Body.ParamBlock -and + @($node.Body.ParamBlock.Attributes | Where-Object { $_.TypeName.Name -in 'MaesterTest', 'MaesterTestAttribute' }).Count -gt 0 + }, $true) | Select-Object -First 1 + if (-not $function) { return , @() } + $parameters = foreach ($parameter in $function.Body.ParamBlock.Parameters) { + $name = $parameter.Name.VariablePath.UserPath + if ($name -eq 'Instance' -or $name -like 'Mt*') { continue } + $type = $parameter.Attributes | Where-Object { $_ -is [System.Management.Automation.Language.TypeConstraintAst] } | Select-Object -First 1 + $typeName = if ($type) { $type.TypeName.Name.ToLowerInvariant() -replace '^switchparameter$', 'switch' } else { 'object' } + $setting = $parameter.Attributes | Where-Object { $_ -is [System.Management.Automation.Language.AttributeAst] -and $_.TypeName.Name -in 'MaesterParameter', 'MaesterParameterAttribute' } | + ForEach-Object { $_.NamedArguments | Where-Object ArgumentName -EQ 'Setting' } | Select-Object -First 1 + $text = "$name [$typeName]" + if ($setting -and $setting.Argument -is [System.Management.Automation.Language.StringConstantExpressionAst]) { $text += " setting=$($setting.Argument.Value)" } + $text + } + , @($parameters | Sort-Object) +} + function ConvertTo-MtReviewValue { <# .SYNOPSIS @@ -252,11 +292,14 @@ function Get-MtReviewTarget { foreach ($name in $script:RubricAttribute) { if ($declared.Attributes.Contains($name)) { $target.Declared[$name] = $declared.Attributes[$name] } } + $parameters = Get-MtReviewParameter -Content $source.Head + if ($parameters.Count -gt 0) { $target.Declared['Parameters'] = $parameters } if ($declared.Attributes.Contains('Id')) { $target.Id = [string] $declared.Attributes['Id'] } if ($declared.Attributes.Contains('Title')) { $target.Title = [string] $declared.Attributes['Title'] } if ($target.IsNew) { $target.Changed = @($script:RubricAttribute) + if ($parameters.Count -gt 0) { $target.Changed += 'Parameters' } } else { $previous = Get-MtReviewAttribute -Content $source.Base $target.Previous = [ordered]@{} @@ -266,6 +309,10 @@ function Get-MtReviewTarget { $after = ConvertTo-MtReviewValue -Value $(if ($declared.Attributes.Contains($name)) { $declared.Attributes[$name] }) if ($before -cne $after) { $target.Changed += $name } } + $previousParameters = Get-MtReviewParameter -Content $source.Base + if ($previousParameters.Count -gt 0) { $target.Previous['Parameters'] = $previousParameters } + # A renamed, added or rebound parameter is reviewed; a removed one is not. + if (@($parameters | Where-Object { $_ -cnotin $previousParameters }).Count -gt 0) { $target.Changed += 'Parameters' } if ($target.Changed.Count -eq 0) { continue } # nothing the rubric governs changed } @@ -300,6 +347,7 @@ function Get-MtReviewIndex { foreach ($name in $script:RubricAttribute) { if ($read.Attributes.Contains($name)) { $entry[$name] = $read.Attributes[$name] } } + $entry['Parameters'] = Get-MtReviewParameter -Content (Get-Content -LiteralPath $file.FullName -Raw) [pscustomobject]$entry } } @@ -359,6 +407,28 @@ function Get-MtReviewRelatedTest { $related | Sort-Object -Property Id | Select-Object -First $MaxRelated } +function Get-MtReviewParameterName { + <# + .SYNOPSIS + Lists the parameter names the repository already uses, with their types, settings and how many tests use + each, so the reviewer can ask a new test to reuse an established name instead of inventing a synonym. + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param( + [AllowEmptyCollection()] + [object[]] $Index, + [string] $ExcludeId + ) + + $entries = foreach ($test in @($Index | Where-Object { $_.Id -ne $ExcludeId -and $_.PSObject.Properties['Parameters'] })) { + foreach ($text in @($test.Parameters)) { if ($text -match '^(?\S+) \[(?[^\]]+)\]') { [pscustomobject]@{ Name = $Matches.name; Text = $text } } } + } + $entries | Group-Object Name | Sort-Object Name | ForEach-Object { + [pscustomobject]@{ Name = $_.Name; Tests = $_.Count; Signature = @($_.Group.Text | Sort-Object -Unique) -join '; ' } + } +} + function Get-MtReviewSystem { <# .SYNOPSIS @@ -416,6 +486,9 @@ function New-MtReviewRequestBody { $previous = if ($Target.IsNew) { 'none' } else { $Target.Previous | ConvertTo-Json -Depth 4 -Compress } $markdown = if ($Target.Markdown) { $Target.Markdown } else { '(the test has no Markdown file)' } $related = if (@($Target.Related).Count -gt 0) { ConvertTo-Json -InputObject @($Target.Related) -Depth 4 -Compress } else { 'none' } + $parameterNames = if ($Target.PSObject.Properties['ParameterNames'] -and @($Target.ParameterNames).Count -gt 0) { + (@($Target.ParameterNames) | ForEach-Object { "$($_.Name) ($($_.Tests)): $($_.Signature)" }) -join "`n" + } else { 'none' } $user = @( "Review this $(if ($Target.IsNew) { 'new' } else { 'changed' }) test: $($Target.Id) ($($Target.Path))." '' @@ -423,6 +496,8 @@ function New-MtReviewRequestBody { "declared_attributes: $($Target.Declared | ConvertTo-Json -Depth 4 -Compress)" "previous_attributes: $previous" "related_tests: $related" + "existing_parameter_names:" + $parameterNames '' "" $Target.Source @@ -442,7 +517,7 @@ function New-MtReviewRequestBody { items = [ordered]@{ type = 'object' properties = [ordered]@{ - attribute = @{ type = 'string'; enum = @($script:RubricAttribute) } + attribute = @{ type = 'string'; enum = @($script:ReviewedAttribute) } declared = @{ type = 'string' } expected = @{ type = 'string' } reason = @{ type = 'string' } @@ -728,7 +803,10 @@ function Invoke-MtAttributeReview { $removed = @($File | ForEach-Object { $_ -replace '\\', '/' } | Where-Object { $_ -match '^tests/.+/Test\.[^/]+\.ps1$' -and -not (Test-Path -LiteralPath (Join-Path $HeadRoot $_) -PathType Leaf) }) foreach ($target in $targets) { - if (-not $target.Error) { $target.Related = @(Get-MtReviewRelatedTest -Target $target -Index $index -Changed $targets -Removed $removed) } + if (-not $target.Error) { + $target.Related = @(Get-MtReviewRelatedTest -Target $target -Index $index -Changed $targets -Removed $removed) + $target | Add-Member -NotePropertyName ParameterNames -NotePropertyValue @(Get-MtReviewParameterName -Index $index -ExcludeId $target.Id) -Force + } } $results = foreach ($target in $targets) { if ($target.Error) { diff --git a/build/review/attribute-review-prompt.md b/build/review/attribute-review-prompt.md index 25765e56fa..abffd3992c 100644 --- a/build/review/attribute-review-prompt.md +++ b/build/review/attribute-review-prompt.md @@ -7,10 +7,15 @@ text define how each attribute value is chosen. They are the only authority for ## What you receive -- `attributes_to_review`: the attributes to judge. For a new test this is every rubric attribute. For a changed - test it is the attributes whose values changed. +- `attributes_to_review`: the attributes to judge. For a new test this is every rubric attribute, and + `Parameters` when it has any. For a changed test it is the attributes whose values changed, and `Parameters` + when a parameter was added, renamed or bound to another setting. - `declared_attributes`: the values in the version under review. - `previous_attributes`: the values before the change, or `none` for a new test. +- `declared_attributes.Parameters`: the test's parameters as `Name [type]`, or `Name [type] setting=Setting` for + a parameter bound to a setting. +- `existing_parameter_names`: the parameter names other tests in the repository use, one per line as + `Name (number of tests): signatures`. - `related_tests`: the other tests in the repository with the same `Product` and `Feature`, each with its id, title and rubric attributes, or `none`. They come from the repository, not from the pull request, except that a test the pull request also changes is shown with its new values. @@ -63,8 +68,16 @@ judge the attributes on their merits. `None` is a finding when the description names attacker behaviour the control addresses. A plausible technique that is merely absent is a note. +10. `Parameters`: judge each name against the rubric's "Parameter names" section. A finding when a name does + not say what it measures, when it invents a synonym for a name in `existing_parameter_names` that means the + same thing (for example `DormantDays` where other tests use `MaximumInactiveDays`), when it reuses an + existing name for something different, or when a parameter is bound to a setting for a value a benchmark + sets. Write `declared` as the parameter's current name and `expected` as the name to use, or `unbound` for a + binding to remove. Report one finding for each parameter that needs a change. + Unit tests already check that required attributes are present and that keys and technique IDs exist. You do -not need to repeat those checks, but report an invalid key or ID if you notice one. +not need to repeat those checks, but report an invalid key or ID if you notice one. They also check the +mechanical parameter rules (PascalCase, `Maximum` not `Max`, no `In` before a unit, plural lists). ## Output diff --git a/build/website/Update-MtTestBuilderData.ps1 b/build/website/Update-MtTestBuilderData.ps1 index 3923159624..1175662aff 100644 --- a/build/website/Update-MtTestBuilderData.ps1 +++ b/build/website/Update-MtTestBuilderData.ps1 @@ -16,6 +16,9 @@ tests/*/frameworks/*.json frameworks and their requirements tests/**/Test.*.ps1 which tests name each requirement in Control powershell/assets/MaesterNistControls.json the pinned NIST SP 800-53 control list + powershell/assets/MaesterSettings.psd1 the settings a parameter can be bound to + powershell/assets/MaesterParameterKinds.psd1 the kinds of value a parameter can hold + tests/**/Test.*.ps1 the parameter names tests already use website/docs/writing-tests/attribute-rubric.md the rubric, one section per attribute Run it after changing any of those files and commit the result. A unit test @@ -121,6 +124,40 @@ $frameworks = foreach ($file in (Get-ChildItem (Join-Path $root 'tests') -Filter } } +# Settings a parameter can be bound to, the kinds of value, and the parameter names the built-in tests use, so +# the page can offer a setting, check a name against the naming rules and suggest a name that is already in use. +$settingRegistry = Import-PowerShellDataFile (Join-Path $assets 'MaesterSettings.psd1') +$kindRegistry = Import-PowerShellDataFile (Join-Path $assets 'MaesterParameterKinds.psd1') +$settings = foreach ($name in ($settingRegistry.Settings.Keys | Sort-Object)) { + $entry = $settingRegistry.Settings[$name] + [ordered]@{ + name = $name + type = $entry.Type + kind = if ($entry.ContainsKey('Kind')) { $entry.Kind } else { $null } + default = $entry.Default + allowedValues = @(if ($entry.ContainsKey('AllowedValues')) { $entry.AllowedValues }) + description = $entry.Description + connection = [bool]($entry.ContainsKey('Role') -and $entry.Role -eq 'Connection') + } +} +$typeNames = @{ 'int' = 'int'; 'int32' = 'int'; 'bool' = 'bool'; 'boolean' = 'bool'; 'switch' = 'switch'; 'string' = 'string'; 'string[]' = 'string[]'; 'object[]' = 'object[]' } +$parameterUse = @{} +foreach ($file in (Get-ChildItem (Join-Path $root 'tests') -Filter 'Test.*.ps1' -Recurse | Sort-Object FullName)) { + $ast = [System.Management.Automation.Language.Parser]::ParseFile($file.FullName, [ref]$null, [ref]$null) + $functions = $ast.FindAll({ param($node) $node -is [System.Management.Automation.Language.FunctionDefinitionAst] -and $node.Body.ParamBlock -and ($node.Body.ParamBlock.Attributes.TypeName.Name -match '^MaesterTest(Attribute)?$') }, $false) + foreach ($function in $functions) { + foreach ($parameter in $function.Body.ParamBlock.Parameters) { + $name = $parameter.Name.VariablePath.UserPath + if ($name -eq 'Instance' -or $name -like 'Mt*') { continue } + $type = $parameter.Attributes | Where-Object { $_ -is [System.Management.Automation.Language.TypeConstraintAst] } | Select-Object -Last 1 + $typeName = if ($type) { $type.TypeName.FullName.ToLowerInvariant() -replace '^system\.', '' } else { '' } + $typeName = if ($typeNames.ContainsKey($typeName)) { $typeNames[$typeName] } else { $typeName } + if (-not $parameterUse.ContainsKey($name)) { $parameterUse[$name] = [ordered]@{ name = $name; type = $typeName; tests = 0 } } + $parameterUse[$name].tests++ + } + } +} + $data = [ordered]@{ note = 'Generated by build/website/Update-MtTestBuilderData.ps1. Do not edit.' idPattern = $schema.IdPattern @@ -149,6 +186,9 @@ $data = [ordered]@{ tactics = @($attack.Tactics | ForEach-Object { [ordered]@{ id = $_.Id; name = $_.Name } }) techniques = @($attack.Techniques | ForEach-Object { [ordered]@{ id = $_.Id; name = $_.Name; tactics = @($_.Tactics) } }) } + settings = @($settings) + parameterKinds = @($kindRegistry.Kinds.Keys | Sort-Object) + parameterNames = @($parameterUse.Keys | Sort-Object | ForEach-Object { $parameterUse[$_] }) rubric = $rubric } diff --git a/packs/zero-trust-assessment/maester-pack.json b/packs/zero-trust-assessment/maester-pack.json index 6706a31caf..faac85b632 100644 --- a/packs/zero-trust-assessment/maester-pack.json +++ b/packs/zero-trust-assessment/maester-pack.json @@ -38,6 +38,20 @@ { "Name": "ZeroTrustAssessment", "MinimumVersion": "3.1.0", "Install": "User", "Process": "Child" } ] }, + "Settings": { + "ZeroTrustAssessment.ReportPath": { "Type": "string", "Default": "", "Description": "Folder or JSON file of an assessment that already ran. When set, the pack reads it and does not run the assessment." }, + "ZeroTrustAssessment.MaxReportAgeDays": { "Type": "int", "Default": 7, "Description": "Refuse a report at ReportPath older than this many days. 0 turns the check off." }, + "ZeroTrustAssessment.EmbedReport": { "Type": "bool", "Default": true, "Description": "Attach the assessment's own HTML report to the Maester report." }, + "ZeroTrustAssessment.WorkshopPlan": { "Type": "bool", "Default": true, "Description": "Add the Zero Trust workshop plan to the Maester report." }, + "ZeroTrustAssessment.ObjectFacts": { "Type": "bool", "Default": true, "Description": "Record the objects each assessment result names as affected objects." }, + "ZeroTrustAssessment.OutputPath": { "Type": "string", "Default": "", "Description": "Folder the assessment writes to. A temporary folder when empty." }, + "ZeroTrustAssessment.Pillar": { "Type": "string", "Default": "All", "AllowedValues": ["All", "Identity", "Devices", "Network", "Data", "Infrastructure", "SecOps", "AI"], "Description": "Run one pillar only." }, + "ZeroTrustAssessment.Tests": { "Type": "string[]", "Default": [], "Description": "Assessment test IDs to run. All tests when empty." }, + "ZeroTrustAssessment.Days": { "Type": "int", "Description": "Days of sign-in logs the assessment reads. The module's default when not set." }, + "ZeroTrustAssessment.ShowLog": { "Type": "bool", "Default": true, "Description": "Show the assessment's log while it runs." }, + "ZeroTrustAssessment.DisableTelemetry": { "Type": "bool", "Default": true, "Description": "The assessment sends the tenant ID to Microsoft unless this is true." }, + "ZeroTrustAssessment.Connect": { "Type": "object", "Description": "Parameters for Connect-ZtAssessment, when the assessment cannot reuse Maester's sign-in." } + }, "Categories": ["Microsoft 365", "Zero Trust", "Identity", "Devices", "Network", "Data"], "Report": { "Logo": "microsoft", diff --git a/powershell/Maester.psm1 b/powershell/Maester.psm1 index f5b0d45188..ff65045908 100644 --- a/powershell/Maester.psm1 +++ b/powershell/Maester.psm1 @@ -19,6 +19,7 @@ $__MtSession = @{ TestResultDetail = @{} NativeTestInfo = @{} # Native tests of the current run: ID -> function name and Markdown NativeReturnValue = @{} # Native tests of the current run: ID -> what the test returned + SettingRead = @{} # Native tests of the current run: ID -> names of the settings read with Get-MtSetting Connections = @() ConnectionConfig = $null # Reference to config discovered by a connector, not an explicit run config. DnsCache = @() diff --git a/powershell/assets/MaesterSettings.psd1 b/powershell/assets/MaesterSettings.psd1 index 5d45e7d347..c5aecd9439 100644 --- a/powershell/assets/MaesterSettings.psd1 +++ b/powershell/assets/MaesterSettings.psd1 @@ -1,15 +1,42 @@ -# Settings registry (Maester 3.0 design, section 7.3). GlobalSettings in the run config may set any key; -# the registry records the type, default and sensitivity of the settings Maester itself reads. Keys that -# are not listed pass through, so test packs can use Namespace.Key. A sensitive setting is redacted in -# the results. +# Settings registry (Maester 3.0 design, section 7.3). It records the type, default and sensitivity of every +# setting Maester itself reads from GlobalSettings in the run config. A pack declares its own settings, named +# Namespace.Key, under Settings in its maester-pack.json; they are added to this registry while the pack runs. +# +# The config is checked against the registry before a run (Test-MtGlobalSetting): a value of the wrong type, +# a value that is not one of AllowedValues or a list item that does not fit Items stops the run, and a key +# without a dot that is not listed here is reported as a likely typo. A Namespace.Key that no pack declares +# passes through, for the settings of custom tests. A sensitive setting is redacted in the results. +# +# Each entry has Type (int, bool, string, string[], object or object[]), Default, Sensitive and Description, +# and may have: +# Kind What a string holds, from MaesterParameterKinds.psd1, so a UI can offer a picker. +# AllowedValues The values a string or string[] setting accepts. +# Role 'Connection' for a setting that a connect command or a data helper reads. A test does not +# bind it, and the test builder does not offer it. +# Items For object[]: Properties (the names an item may have, each with its allowed values or +# $null for any) and RequireAny (an item needs at least one of these). +# +# A test never reads a setting itself. It declares a parameter bound to it, +# [MaesterParameter(Setting = 'ParkedDomains')] [string[]] $ParkedDomains = @() +# and the engine binds the GlobalSettings value when the test's TestSettings row does not set one. The +# parameter's type, default and allowed values must match the entry here, and it takes Kind from here when +# it declares none. A setting holds a fact about the tenant or a choice the organisation makes once (parked +# domains, break-glass accounts), never a value a benchmark sets, which stays a parameter of that test. Name +# a setting after what it holds, never after a test or a suite. A connection or transport setting that a +# connect command or a data helper reads (GitHubOrganization, XspmExternalDataUris) is read with +# Get-MtSetting; the engine records the read on the result of the test that caused it. @{ SchemaVersion = '1.0' Settings = @{ - EmergencyAccessAccounts = @{ Type = 'object[]'; Default = @(); Sensitive = $false; Description = 'Emergency access (break glass) accounts and groups excluded from Conditional Access checks.' } - DataverseEnvironmentUrl = @{ Type = 'string'; Default = ''; Sensitive = $false; Description = 'URL of the Dataverse environment that the Copilot Studio checks read.' } - AzureDevOpsOrganization = @{ Type = 'string'; Default = ''; Sensitive = $false; Description = 'Azure DevOps organization that Connect-Maester -Service AzureDevOps connects to.' } - GitHubOrganization = @{ Type = 'string'; Default = ''; Sensitive = $false; Description = 'GitHub organization that the GitHub checks read.' } - GitHubApiBaseUri = @{ Type = 'string'; Default = 'https://api.github.com'; Sensitive = $false; Description = 'Base URI of the GitHub REST API.' } - GitHubApiVersion = @{ Type = 'string'; Default = '2022-11-28'; Sensitive = $false; Description = 'GitHub REST API version.' } + EmergencyAccessAccounts = @{ Type = 'object[]'; Items = @{ Properties = @{ Id = $null; UserPrincipalName = $null; Type = @('User', 'Group') }; RequireAny = @('Id', 'UserPrincipalName') }; Default = @(); Sensitive = $false; Description = 'Emergency access (break glass) accounts and groups. Checks of Conditional Access, privileged roles and sign-in activity treat them as the exception they are.' } + ParkedDomains = @{ Type = 'string[]'; Kind = 'Entra.Domain'; Default = @(); Sensitive = $false; Description = 'Accepted domains that never send email. The email authentication checks expect them to deny all mail.' } + DefenderEndpointPolicyFiltering = @{ Type = 'string'; AllowedValues = @('All', 'IncludeUnassigned', 'OnlyAssigned'); Default = 'OnlyAssigned'; Sensitive = $false; Description = 'Which Defender for Endpoint policies the Defender checks read: All, IncludeUnassigned or OnlyAssigned.' } + DefenderEndpointComplianceLogic = @{ Type = 'string'; AllowedValues = @('EffectivePolicy', 'AllPolicies', 'AnyPolicy'); Default = 'EffectivePolicy'; Sensitive = $false; Description = 'How the Defender for Endpoint checks combine policies: EffectivePolicy, AllPolicies or AnyPolicy.' } + XspmExternalDataUris = @{ Type = 'object'; Role = 'Connection'; Default = $null; Sensitive = $false; Description = 'HTTPS mirrors of the data sources the XSPM Advanced Hunting queries read: EntraDirectoryRoles, MicrosoftApps, ApiPermissions, ArmApiRequests.' } + DataverseEnvironmentUrl = @{ Type = 'string'; Role = 'Connection'; Default = ''; Sensitive = $false; Description = 'URL of the Dataverse environment that the Copilot Studio checks read.' } + AzureDevOpsOrganization = @{ Type = 'string'; Role = 'Connection'; Default = ''; Sensitive = $false; Description = 'Azure DevOps organization that Connect-Maester -Service AzureDevOps connects to.' } + GitHubOrganization = @{ Type = 'string'; Role = 'Connection'; Default = ''; Sensitive = $false; Description = 'GitHub organization that the GitHub checks read.' } + GitHubApiBaseUri = @{ Type = 'string'; Role = 'Connection'; Default = 'https://api.github.com'; Sensitive = $false; Description = 'Base URI of the GitHub REST API.' } + GitHubApiVersion = @{ Type = 'string'; Role = 'Connection'; Default = '2022-11-28'; Sensitive = $false; Description = 'GitHub REST API version.' } } } diff --git a/powershell/assets/MaesterTestSchema.psd1 b/powershell/assets/MaesterTestSchema.psd1 index fdf7250ec4..ebc16e7e0a 100644 --- a/powershell/assets/MaesterTestSchema.psd1 +++ b/powershell/assets/MaesterTestSchema.psd1 @@ -29,7 +29,7 @@ # ID prefixes that belong to tests shipped with Maester, MP. for Maester Packs, and the codes of the packs # that ship with Maester, whose IDs have no MP. prefix (ZTA. for the Zero Trust Assessment pack). - ReservedPrefixes = @('MT.', 'CISA.', 'CIS.', 'EIDSCA.', 'ORCA.', 'AD-', 'AZDO.', 'MT1060.', 'ASD.', 'MP.', 'ZTA.') + ReservedPrefixes = @('MT.', 'CISA.', 'CIS.', 'EIDSCA.', 'ORCA.', 'AD-', 'AZDO.', 'MT1060.', 'ASD.', 'DISA.', 'MP.', 'ZTA.') # Names reserved for future properties. Adding one later does not break existing tests. ReservedNames = @('OptionalService', 'TimeoutSeconds') @@ -233,10 +233,17 @@ ParameterAttribute = @{ Kind = @{ Type = 'string' - Required = 'Always' + Required = 'No' ValuesFrom = 'ParameterKindRegistry' Pattern = '^[A-Za-z][A-Za-z0-9]*(\.[A-Za-z][A-Za-z0-9]*)+$' - Description = 'Name of an entry in the parameter-kind registry, for example Entra.Group.' + Description = 'Name of an entry in the parameter-kind registry, for example Entra.Group. [MaesterParameter] needs Kind, Setting or both.' + } + Setting = @{ + Type = 'string' + Required = 'No' + ValuesFrom = 'SettingsRegistry' + Pattern = '^[A-Za-z][A-Za-z0-9]*(\.[A-Za-z][A-Za-z0-9]*)*$' + Description = 'Name of a GlobalSettings entry the parameter is bound to, for example ParkedDomains. A pack uses Namespace.Key.' } } } diff --git a/powershell/assets/public_domain_suffix_list.dat b/powershell/assets/public_domain_suffix_list.dat index f1d515ce75..bc17e5dd2a 100644 --- a/powershell/assets/public_domain_suffix_list.dat +++ b/powershell/assets/public_domain_suffix_list.dat @@ -5,8 +5,8 @@ // Please pull this list from, and only from https://publicsuffix.org/list/public_suffix_list.dat, // rather than any other VCS sites. Pulling from any other URL is not guaranteed to be supported. -// VERSION: 2026-10-31_14-17-28_UTC -// COMMIT: 73f8cc701c084fe07d888ec552b2f0b53281a674 +// VERSION: 2026-11-09_10-58-07_UTC +// COMMIT: c682e9e4600a1581e7e58bc21675159d7e713b31 // Instructions on pulling and using this list can be found at https://publicsuffix.org/list/. @@ -6369,9 +6369,13 @@ net.vi org.vi // vn : https://vnnic.vn/en/domain-name-vn/domain-name/cctldvn +// https://vnnic.vn/sites/default/files/vn.cctld.domains.txt +// Submitted by registry 2026-10-05 vn ac.vn +ad.vn ai.vn +ap.vn biz.vn com.vn edu.vn @@ -6383,6 +6387,7 @@ int.vn io.vn name.vn net.vn +on.vn org.vn pro.vn @@ -12388,10 +12393,6 @@ claude.app claudeusercontent.com frame.claudeusercontent.com -// Anysphere Inc : https://cursor.com -// Submitted by Benson Liu -*.cursorusercontent.com - // Apigee : https://apigee.com/ // Submitted by Apigee Security Team apigee.io @@ -12545,6 +12546,10 @@ blackbaudcdn.net // Submitted by Luke Bratch of.je +// BlitzWorks : https://blitz.cloud +// Submitted by BlitzWorks +prod.page + // Block, Inc. : https://block.xyz // Submitted by Jonathan Boice square.site @@ -12603,6 +12608,10 @@ radio.fm cdn.bubble.io bubbleapps.io +// Butterfly Effect Pte. Ltd. : https://manus.im +// Submitted by Manus Security Team +manus.space + // bwCloud-OS : https://bwcloud-os.de/ // Submitted by Klara Mall *.bwcloud-os-instance.de @@ -13046,6 +13055,10 @@ dyn.now heimdns.online ddns.wtf +// Docs Flowy : https://docsflowy.com +// Submitted by Haykel Maaoui +docsflowy.site + // DotArai : https://www.dotarai.com/ // Submitted by Atsadawat Netcharadsang online.th @@ -14542,6 +14555,10 @@ co.technology linkyard-cloud.ch linkyard.cloud +// Linkyhost : https://www.linkyhost.com +// Submitted by Linkyhost Support +linkyhost.page + // Linode : https://linode.com // Submitted by members.linode.com @@ -14591,6 +14608,7 @@ lohmus.me // Lovable : https://lovable.dev // Submitted by Fabian Hedin lovable.app +auth.lovable.app lovableproject.com lovable.run lovable.sh @@ -15318,6 +15336,10 @@ ox.rs // Submitted by Charly Coste oy.lc +// Page Lemon : https://pagelemon.com +// Submitted by Aporia Research Ltd +pagelemon.dev + // Pagefog : https://pagefog.com/ // Submitted by Derek Myers pgfog.com @@ -15717,6 +15739,11 @@ sakura.tv // Submitted by Asheesh Laroia sandcats.io +// Sanity Inc. : https://www.sanity.io/ +// Submitted by Josh Ellis +sanity.run +sanity.studio + // Sav.com, LLC : https://marketing.sav.com/ // Submitted by Mukul Kudegave sav.case @@ -15885,6 +15912,10 @@ vipsinaapp.com // Submitted by Skylar Challand siteleaf.net +// Sliplane GmbH : https://sliplane.io +// Submitted by Jonas Scholz +sliplane.app + // Small Technology Foundation : https://small-tech.org // Submitted by Aral Balkan small-web.org @@ -15947,6 +15978,13 @@ my.de *.nxa.eu nx.gw +// SpaceXSI : https://x.ai/ +// Submitted by Benson Liu +*.apps.grok.bot +*.pages.grok.bot +*.cursorusercontent.com +grok.me + // Spawnbase : https://spawnbase.ai // Submitted by Alexander Zuev spawnbase.app @@ -16478,10 +16516,6 @@ weeklylottery.org.uk wpenginepowered.com js.wpenginepowered.com -// xAI : https://x.ai/ -// Submitted by Asim Shrestha -grok.me - // XenonCloud GbR : https://xenoncloud.net // Submitted by Julian Uphoff *.xenonconnect.de diff --git a/powershell/internal/checks/ad/ad/Get-MtAdCertificateInventory.ps1 b/powershell/internal/checks/ad/ad/Get-MtAdCertificateInventory.ps1 index c0b95aa787..d557f10a55 100644 --- a/powershell/internal/checks/ad/ad/Get-MtAdCertificateInventory.ps1 +++ b/powershell/internal/checks/ad/ad/Get-MtAdCertificateInventory.ps1 @@ -19,12 +19,18 @@ $values = [System.Collections.Generic.List[object]]::new() if ($raw -is [byte[]] -or $raw -is [string]) { $values.Add($raw) + } elseif ($raw -is [array] -and $raw.Count -gt 0 -and @($raw | Where-Object { $_ -isnot [byte] }).Count -eq 0) { + # A single LDAP binary attribute can be projected as an object array of bytes. + $values.Add([byte[]]$raw) } elseif ($null -ne $raw) { foreach ($value in $raw) { $values.Add($value) } } foreach ($value in $values) { if ($null -eq $value) { continue } - $bytes = if ($value -is [byte[]]) { $value } elseif ($value -is [string]) { + $bytes = if ($value -is [byte[]]) { $value } elseif ($value -is [array] -and $value.Count -gt 0 -and @($value | Where-Object { $_ -isnot [byte] }).Count -eq 0) { + # Each value of a multi-valued LDAP binary attribute can also be projected as an object array of bytes. + [byte[]]$value + } elseif ($value -is [string]) { try { [Convert]::FromBase64String($value) } catch { throw "Invalid certificate encoding for $($role.Name) $($entry.Name)." } } else { throw "Unsupported certificate value for $($role.Name) $($entry.Name)." } try { diff --git a/powershell/internal/checks/cisa/entra/Test-MtCisaActivationNotification.ps1 b/powershell/internal/checks/cisa/entra/Test-MtCisaActivationNotification.ps1 index b03def9439..451ab07cfb 100644 --- a/powershell/internal/checks/cisa/entra/Test-MtCisaActivationNotification.ps1 +++ b/powershell/internal/checks/cisa/entra/Test-MtCisaActivationNotification.ps1 @@ -52,21 +52,8 @@ role = $role.displayName activationNotify = $false } - $policySplat = @{ - ApiVersion = "v1.0" - RelativeUri = "policies/roleManagementPolicyAssignments" - Filter = "scopeId eq '/' and scopeType eq 'DirectoryRole' and roleDefinitionId eq '$($role.id)'" - QueryParameters = @{ - expand = "policy(expand=rules)" - } - } - $policy = Invoke-MtGraphRequest @policySplat - - $activationNotify = $policy.policy.rules | Where-Object {` - $_.id -eq "Notification_Admin_EndUser_Assignment" -and ` - $_.notificationRecipients - } - $rolePolicy.activationNotify = -not $null -eq $activationNotify + $recipients = @(Get-MtRoleActivationNotificationRecipient -RoleDefinitionId $role.id) + $rolePolicy.activationNotify = $recipients.Count -gt 0 $rolePolicies += $rolePolicy } diff --git a/powershell/internal/checks/cisa/exchange/Test-MtCisaDmarcReport.ps1 b/powershell/internal/checks/cisa/exchange/Test-MtCisaDmarcReport.ps1 index cd026a75ee..a554314b2b 100644 --- a/powershell/internal/checks/cisa/exchange/Test-MtCisaDmarcReport.ps1 +++ b/powershell/internal/checks/cisa/exchange/Test-MtCisaDmarcReport.ps1 @@ -25,11 +25,7 @@ ) $acceptedDomains = Get-MtExo -Request AcceptedDomain - <# Parked domains should have DMARC with reject policy - $sendingDomains = $acceptedDomains | Where-Object {` - -not $_.SendingFromDomainDisabled - } - #> + # Every accepted domain is checked, a parked domain included: MS.EXO.4.4v1 gives no separate rule for one. $expandedDomains = @() foreach($domain in $acceptedDomains){ #This regex does NOT capture for third level domain scenarios diff --git a/powershell/internal/engine/Invoke-MtNativePlan.ps1 b/powershell/internal/engine/Invoke-MtNativePlan.ps1 index 315207bc31..d9335615d6 100644 --- a/powershell/internal/engine/Invoke-MtNativePlan.ps1 +++ b/powershell/internal/engine/Invoke-MtNativePlan.ps1 @@ -208,6 +208,7 @@ function Clear-MtNativeTestState { ) if ($__MtSession.TestResultDetail -and $__MtSession.TestResultDetail.ContainsKey($Id)) { $null = $__MtSession.TestResultDetail.Remove($Id) } if ($__MtSession.NativeReturnValue -and $__MtSession.NativeReturnValue.ContainsKey($Id)) { $null = $__MtSession.NativeReturnValue.Remove($Id) } + if ($__MtSession.SettingRead -and $__MtSession.SettingRead.ContainsKey($Id)) { $null = $__MtSession.SettingRead.Remove($Id) } } function New-MtNativeWorkItem { @@ -373,7 +374,7 @@ function Expand-MtTestFamily { } if ($ownParameters -is [System.Collections.IDictionary]) { foreach ($k in $ownParameters.Keys) { $configValues[[string]$k] = $ownParameters[$k] } } else { foreach ($prop in $ownParameters.PSObject.Properties) { $configValues[$prop.Name] = $prop.Value } } - $binding = ConvertTo-MtTestParameter -Test $test -ConfigValue $configValues -Override $overrideValues + $binding = ConvertTo-MtTestParameter -Test $test -ConfigValue $configValues -Override $overrideValues -GlobalSetting $RunConfig.GlobalSettings $instanceRow.EffectiveParameters = $binding.Effective if ($binding.Error) { $instanceRow.Disposition = 'Error'; $instanceRow.ReasonCode = 'InvalidConfiguration'; $instanceRow.ReasonDetail = $binding.Error @@ -569,6 +570,9 @@ function ConvertTo-MtNativeRow { ParentId = if ($isInstance -or $test.InstanceSource) { $test.Id } else { $null } InstanceId = if ($isInstance) { $id } else { $null } Parameters = @($PlanRow.EffectiveParameters) + # Settings the test read with Get-MtSetting while it ran, itself or through a helper. A setting it + # receives as a bound parameter is in Parameters instead. + SettingsRead = [string[]]@(if ($RunResult -and $__MtSession.SettingRead -and $__MtSession.SettingRead.ContainsKey($id)) { $__MtSession.SettingRead[$id] | Sort-Object }) Diagnostics = $diagnostics # The pack a test comes from (Maester Packs design, section 5.5); null for every other test. Package = if ($test.PSObject.Properties['Package']) { $test.Package } else { $null } diff --git a/powershell/internal/engine/Read-MtNativeTest.ps1 b/powershell/internal/engine/Read-MtNativeTest.ps1 index 16970d2dfb..f4ce96c53b 100644 --- a/powershell/internal/engine/Read-MtNativeTest.ps1 +++ b/powershell/internal/engine/Read-MtNativeTest.ps1 @@ -381,7 +381,7 @@ function ConvertTo-MtRequiredVersion { function Read-MtTestParameter { <# .SYNOPSIS - Reads one parameter of a test function: type, default, allowed values, range, kind and description. + Reads one parameter of a test function: type, default, allowed values, range, kind, setting and description. #> [CmdletBinding()] [OutputType([pscustomobject])] @@ -398,6 +398,7 @@ function Read-MtTestParameter { $allowed = $null $range = $null $kind = $null + $setting = $null $mandatory = $false foreach ($a in $ParameterAst.Attributes) { if ($a -is [System.Management.Automation.Language.TypeConstraintAst]) { @@ -417,8 +418,16 @@ function Read-MtTestParameter { } { $_ -in 'MaesterParameter', 'MaesterParameterAttribute' } { $k = $a.NamedArguments | Where-Object ArgumentName -EQ 'Kind' | Select-Object -First 1 - if ($k -and $k.Argument -is [System.Management.Automation.Language.StringConstantExpressionAst]) { $kind = $k.Argument.Value } - else { & $OnError 'InvalidMetadata' "Parameter '$name': [MaesterParameter] needs Kind = ''." $line } + $s = $a.NamedArguments | Where-Object ArgumentName -EQ 'Setting' | Select-Object -First 1 + if ($k) { + if ($k.Argument -is [System.Management.Automation.Language.StringConstantExpressionAst]) { $kind = $k.Argument.Value } + else { & $OnError 'InvalidMetadata' "Parameter '$name': [MaesterParameter] Kind must be a constant string." $line } + } + if ($s) { + if ($s.Argument -is [System.Management.Automation.Language.StringConstantExpressionAst]) { $setting = $s.Argument.Value } + else { & $OnError 'InvalidMetadata' "Parameter '$name': [MaesterParameter] Setting must be a constant string." $line } + } + if (-not $k -and -not $s) { & $OnError 'InvalidMetadata' "Parameter '$name': [MaesterParameter] needs Kind = '', Setting = '' or both." $line } } 'Parameter' { $m = $a.NamedArguments | Where-Object ArgumentName -EQ 'Mandatory' | Select-Object -First 1 @@ -432,6 +441,7 @@ function Read-MtTestParameter { { $_ -in 'switch', 'system.management.automation.switchparameter' } { 'switch' } { $_ -in 'string', 'system.string' } { 'string' } { $_ -in 'string[]', 'system.string[]' } { 'string[]' } + { $_ -in 'object[]', 'system.object[]' } { 'object[]' } default { $_ } } @@ -444,8 +454,25 @@ function Read-MtTestParameter { $engineOwned = $name -eq 'Instance' -or $name -like 'Mt*' if (-not $engineOwned) { - if ($typeName -notin 'int', 'bool', 'switch', 'string', 'string[]') { & $OnError 'InvalidMetadata' "Parameter '$name': type '$typeName' is not supported. Use int, bool, switch, string or string[]." $line } + if ($typeName -notin 'int', 'bool', 'switch', 'string', 'string[]', 'object[]') { & $OnError 'InvalidMetadata' "Parameter '$name': type '$typeName' is not supported. Use int, bool, switch, string or string[]." $line } if ($mandatory) { & $OnError 'InvalidMetadata' "Parameter '$name' must not be mandatory: a test must run with an empty configuration." $line } + if ($setting) { + # A setting is a value the whole run shares, declared once in the settings registry. The test's + # parameter must agree with it, and takes the setting's kind when it names none. + $entry = (Get-MtSettingRegistry).Settings[$setting] + if ($entry) { + if ($entry.Type -and $entry.Type -ne $typeName) { & $OnError 'InvalidMetadata' "Parameter '$name': setting '$setting' is a $($entry.Type), but the parameter is a $typeName." $line } + if ($entry.Kind) { + if (-not $kind) { $kind = $entry.Kind } + elseif ($kind -ne $entry.Kind) { & $OnError 'InvalidMetadata' "Parameter '$name': setting '$setting' has kind $($entry.Kind), but the parameter declares $kind." $line } + } + } elseif ($setting -notmatch '^[A-Za-z][A-Za-z0-9]*\.[A-Za-z][A-Za-z0-9.]*$') { + # A pack names its own settings Namespace.Key; a built-in name must be in the registry. + & $OnError 'InvalidMetadata' "Parameter '$name': '$setting' is not a registered setting. Add it to assets/MaesterSettings.psd1, or use a Namespace.Key name for a pack's setting." $line + } + } elseif ($typeName -eq 'object[]') { + & $OnError 'InvalidMetadata' "Parameter '$name': type 'object[]' is only for a parameter bound to a setting, for example [MaesterParameter(Setting = 'EmergencyAccessAccounts')]." $line + } } # Description: a comment directly above the parameter, else .PARAMETER help. @@ -479,6 +506,7 @@ function Read-MtTestParameter { AllowedValues = $allowed Range = $range Kind = $kind + Setting = $setting Description = $description EngineOwned = $engineOwned } @@ -526,6 +554,33 @@ function Get-MtServiceRegistry { $script:__MtLayeredServiceRegistry } +function Get-MtSettingRegistry { + <# + .SYNOPSIS + Returns the settings registry: assets/MaesterSettings.psd1 plus the settings of the packs in the run. + + .DESCRIPTION + A pack declares its settings, named Namespace.Key, under Settings in its maester-pack.json, and + Register-MtPackService adds those of the packs that passed the loader gate. A pack cannot replace a + built-in setting. Cached for the session; the cache is dropped whenever the pack set changes. + #> + [CmdletBinding()] + [OutputType([hashtable])] + param() + if (-not $script:__MtSettingsRegistry) { + $script:__MtSettingsRegistry = Import-PowerShellDataFile -Path (Join-Path $ExecutionContext.SessionState.Module.ModuleBase 'assets/MaesterSettings.psd1') + } + if (-not $script:__MtLayeredSettingRegistry) { + $settings = @{} + foreach ($key in $script:__MtSettingsRegistry.Settings.Keys) { $settings[$key] = $script:__MtSettingsRegistry.Settings[$key] } + if ($script:__MtPackSettings) { + foreach ($key in $script:__MtPackSettings.Keys) { if (-not $settings.ContainsKey($key)) { $settings[$key] = $script:__MtPackSettings[$key] } } + } + $script:__MtLayeredSettingRegistry = @{ SchemaVersion = $script:__MtSettingsRegistry.SchemaVersion; Settings = $settings } + } + $script:__MtLayeredSettingRegistry +} + function Get-MtParameterKindRegistry { <# .SYNOPSIS diff --git a/powershell/internal/engine/Resolve-MtNativePlan.ps1 b/powershell/internal/engine/Resolve-MtNativePlan.ps1 index 428943e92a..2bf4816165 100644 --- a/powershell/internal/engine/Resolve-MtNativePlan.ps1 +++ b/powershell/internal/engine/Resolve-MtNativePlan.ps1 @@ -210,7 +210,7 @@ # Parameter binding. $values = if ($setting -and $setting.PSObject.Properties['Parameters']) { $setting.Parameters } else { $null } $override = if ($ParameterOverride.ContainsKey($t.Id)) { $ParameterOverride[$t.Id] } else { $null } - $binding = ConvertTo-MtTestParameter -Test $t -ConfigValue $values -Override $override + $binding = ConvertTo-MtTestParameter -Test $t -ConfigValue $values -Override $override -GlobalSetting $RunConfig.GlobalSettings $row.EffectiveParameters = $binding.Effective if ($binding.Error) { & $set 'Error' 'InvalidConfiguration' $binding.Error @@ -510,16 +510,20 @@ function ConvertTo-MtTestParameter { Validates parameter values from the config against a test's param() block (design appendix A.5). .DESCRIPTION - Returns Bound (a hashtable to splat), Effective (name, value, source and kind of every parameter) and - Error (a message, or $null). PowerShell's own binder is too lenient for this: it turns 90.5 into 90 - and accepts abbreviated names, so the engine checks names and types itself. + Returns Bound (a hashtable to splat), Effective (name, value, source, kind and setting of every + parameter) and Error (a message, or $null). PowerShell's own binder is too lenient for this: it turns + 90.5 into 90 and accepts abbreviated names, so the engine checks names and types itself. + + The most specific value wins: the run's -Parameter value, then the test's TestSettings row, then the + GlobalSettings entry a parameter names with [MaesterParameter(Setting = ...)], then the default. #> [CmdletBinding()] [OutputType([pscustomobject])] param( [Parameter(Mandatory)] [object] $Test, [Parameter()] [AllowNull()] [object] $ConfigValue, - [Parameter()] [AllowNull()] [object] $Override + [Parameter()] [AllowNull()] [object] $Override, + [Parameter()] [AllowNull()] [object] $GlobalSetting ) $bound = @{} @@ -548,13 +552,32 @@ function ConvertTo-MtTestParameter { $sources[$parameter.Name] = $item.Source } + # A parameter that neither the test's row nor the run sets takes its setting from GlobalSettings. + foreach ($parameter in @($Test.Parameters | Where-Object { $_.PSObject.Properties['Setting'] -and $_.Setting -and -not $_.EngineOwned })) { + if ($bound.ContainsKey($parameter.Name) -or $null -eq $GlobalSetting) { continue } + $hasSetting = if ($GlobalSetting -is [System.Collections.IDictionary]) { $GlobalSetting.Contains($parameter.Setting) } else { $null -ne $GlobalSetting.PSObject.Properties[$parameter.Setting] } + if (-not $hasSetting) { continue } + $value = if ($GlobalSetting -is [System.Collections.IDictionary]) { $GlobalSetting[$parameter.Setting] } else { $GlobalSetting.($parameter.Setting) } + if ($null -eq $value) { continue } + $converted = ConvertTo-MtParameterValue -Parameter $parameter -Value $value -Kinds $kinds + if ($converted.Error) { $errors.Add("Setting '$($parameter.Setting)' (parameter '$($parameter.Name)'): $($converted.Error)"); continue } + $bound[$parameter.Name] = $converted.Value + $sources[$parameter.Name] = 'Setting' + } + + # Effective is what the results record. The value of a parameter bound to a sensitive setting is + # redacted there, wherever it came from; the test still receives the real value in Bound. + $settingRegistry = (Get-MtSettingRegistry).Settings $effective = foreach ($parameter in @($Test.Parameters | Where-Object { -not $_.EngineOwned })) { $hasValue = $bound.ContainsKey($parameter.Name) + $settingName = if ($parameter.PSObject.Properties['Setting']) { $parameter.Setting } else { $null } + $sensitive = $hasValue -and $settingName -and $settingRegistry.ContainsKey($settingName) -and $settingRegistry[$settingName].Sensitive [pscustomobject]@{ - Name = $parameter.Name - Value = if ($hasValue) { $bound[$parameter.Name] } else { $parameter.Default } - Source = if ($hasValue) { $sources[$parameter.Name] } else { 'Default' } - Kind = $parameter.Kind + Name = $parameter.Name + Value = if ($sensitive) { '[redacted]' } elseif ($hasValue) { $bound[$parameter.Name] } else { $parameter.Default } + Source = if ($hasValue) { $sources[$parameter.Name] } else { 'Default' } + Kind = $parameter.Kind + Setting = $settingName } } @@ -612,6 +635,12 @@ function ConvertTo-MtParameterValue { if ($items | Where-Object { $_ -isnot [string] }) { return & $result $null 'expected a string or a list of strings.' } $converted = [string[]]$items } + 'object[]' { + # A list of objects, such as EmergencyAccessAccounts: { "Id": "...", "Type": "group" }. + $items = @(@($Value) | Where-Object { $null -ne $_ }) + if ($items | Where-Object { $_ -isnot [System.Collections.IDictionary] -and $_ -isnot [System.Management.Automation.PSCustomObject] }) { return & $result $null 'expected a list of objects.' } + return & $result ([object[]]@(foreach ($item in $items) { if ($item -is [System.Collections.IDictionary]) { [pscustomobject]$item } else { $item } })) $null + } default { return & $result $null "type '$($Parameter.Type)' cannot be set from the config." } } diff --git a/powershell/internal/engine/Test-MtGlobalSetting.ps1 b/powershell/internal/engine/Test-MtGlobalSetting.ps1 new file mode 100644 index 0000000000..506ae9efa1 --- /dev/null +++ b/powershell/internal/engine/Test-MtGlobalSetting.ps1 @@ -0,0 +1,125 @@ +function Test-MtGlobalSetting { + <# + .SYNOPSIS + Checks GlobalSettings of the run config against the settings registry, once, before a run. + + .DESCRIPTION + Returns Errors and Warnings (lists of messages). + + - A registered setting whose value has the wrong type, is not one of its AllowedValues, does not fit its + Kind, or holds a list item that lacks a required property or has a value its Items does not allow is + an error. A property of a list item that Items does not name is a warning. Without this check a wrong value + is reported once by every test that binds the setting, or not at all by a helper that reads it. + - A key without a dot that is not registered is a warning: built-in settings are all registered and the + settings of packs and custom tests are named Namespace.Key, so it is a typo or a 2.x key of the + user's own tests. The message names the closest registered setting. + - A Namespace.Key that no pack in the run declares passes through. + - A null value means "not set" and is skipped, as the engine skips it when it binds parameters. + + .EXAMPLE + Test-MtGlobalSetting -GlobalSetting $runConfig.GlobalSettings + + Returns the problems of the GlobalSettings section, if any. + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param( + # The GlobalSettings section: an object or a hashtable. + [Parameter()] [AllowNull()] [object] $GlobalSetting + ) + + $errors = [System.Collections.Generic.List[string]]::new() + $warnings = [System.Collections.Generic.List[string]]::new() + $out = { [pscustomobject]@{ Errors = [string[]]$errors; Warnings = [string[]]$warnings } } + if ($null -eq $GlobalSetting) { return & $out } + + $registry = (Get-MtSettingRegistry).Settings + $kinds = Get-MtParameterKindRegistry + $isObject = { param($v) $v -is [System.Collections.IDictionary] -or $v -is [System.Management.Automation.PSCustomObject] } + $read = { + param($object) + if ($object -is [System.Collections.IDictionary]) { foreach ($k in $object.Keys) { [pscustomobject]@{ Name = [string]$k; Value = $object[$k] } } } + else { foreach ($p in $object.PSObject.Properties) { [pscustomobject]@{ Name = $p.Name; Value = $p.Value } } } + } + # Edit distance, to name the setting a mistyped key most likely means. + $distance = { + param([string] $a, [string] $b) + $a = $a.ToLowerInvariant(); $b = $b.ToLowerInvariant() + $previous = 0..$b.Length + for ($i = 1; $i -le $a.Length; $i++) { + $current = @($i) + @(0) * $b.Length + for ($j = 1; $j -le $b.Length; $j++) { + $cost = if ($a[$i - 1] -eq $b[$j - 1]) { 0 } else { 1 } + $current[$j] = [math]::Min([math]::Min($current[$j - 1] + 1, $previous[$j] + 1), $previous[$j - 1] + $cost) + } + $previous = $current + } + $previous[$b.Length] + } + + foreach ($setting in @(& $read $GlobalSetting)) { + $name = $setting.Name + $value = $setting.Value + if (-not $registry.ContainsKey($name)) { + if ($name -notmatch '\.') { + $closest = $registry.Keys | Where-Object { $_ -notmatch '\.' } | + ForEach-Object { [pscustomobject]@{ Name = $_; Distance = (& $distance $name $_) } } | + Where-Object { $_.Distance -le [math]::Max(2, [int]($name.Length / 4)) } | Sort-Object Distance, Name | Select-Object -First 1 + $hint = if ($closest) { " Did you mean '$($closest.Name)'?" } else { '' } + $warnings.Add("GlobalSettings has '$name', which is not a Maester setting, so no built-in test reads it.$hint A setting of your own tests needs a Namespace.Key name, for example Contoso.$name.") + } + continue + } + if ($null -eq $value) { continue } + $entry = $registry[$name] + + if ($entry.Type -eq 'object') { + if (-not (& $isObject $value)) { $errors.Add("GlobalSettings.$name`: expected an object.") } + continue + } + $converted = ConvertTo-MtParameterValue -Kinds $kinds -Value $value -Parameter ([pscustomobject]@{ + Name = $name; Type = $entry.Type; Range = $null + AllowedValues = if ($entry.ContainsKey('AllowedValues')) { $entry.AllowedValues } else { $null } + Kind = if ($entry.ContainsKey('Kind')) { $entry.Kind } else { $null } + }) + if ($converted.Error) { $errors.Add("GlobalSettings.$name`: $($converted.Error)"); continue } + + if ($entry.Type -eq 'object[]' -and $entry.ContainsKey('Items') -and $entry.Items) { + $properties = $entry.Items.Properties + $requireAny = @($entry.Items.RequireAny | Where-Object { $_ }) + $index = 0 + foreach ($item in @($converted.Value)) { + $index++ + $fields = @(& $read $item) + foreach ($field in $fields) { + if ($properties -and -not $properties.ContainsKey($field.Name)) { + $warnings.Add("GlobalSettings.$name, item $index`: '$($field.Name)' is ignored. An item has $(($properties.Keys | Sort-Object) -join ', ').") + } elseif ($properties -and $properties[$field.Name] -and $null -ne $field.Value -and -not ($properties[$field.Name] | Where-Object { $_ -eq $field.Value })) { + $errors.Add("GlobalSettings.$name, item $index`: $($field.Name) '$($field.Value)' is not one of $($properties[$field.Name] -join ', ').") + } + } + if ($requireAny.Count -gt 0 -and -not ($fields | Where-Object { $_.Name -in $requireAny -and -not [string]::IsNullOrWhiteSpace([string]$_.Value) })) { + $errors.Add("GlobalSettings.$name, item $index`: needs $($requireAny -join ' or ').") + } + } + } + } + & $out +} + +function Assert-MtGlobalSetting { + <# + .SYNOPSIS + Writes the warnings of Test-MtGlobalSetting and throws on its errors, naming the config source. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] [object] $RunConfig + ) + $check = Test-MtGlobalSetting -GlobalSetting $RunConfig.GlobalSettings + foreach ($warning in $check.Warnings) { Write-Warning $warning } + if ($check.Errors.Count -gt 0) { + $source = if ($RunConfig.PSObject.Properties['ConfigSource'] -and $RunConfig.ConfigSource) { " ($($RunConfig.ConfigSource))" } else { '' } + throw "The Maester config$source has $($check.Errors.Count) invalid setting$(if ($check.Errors.Count -ne 1) { 's' }): $($check.Errors -join ' ')" + } +} diff --git a/powershell/internal/engine/completion/Get-MtArgumentCompleterTable.ps1 b/powershell/internal/engine/completion/Get-MtArgumentCompleterTable.ps1 index bee45a94a7..bcdd52a408 100644 --- a/powershell/internal/engine/completion/Get-MtArgumentCompleterTable.ps1 +++ b/powershell/internal/engine/completion/Get-MtArgumentCompleterTable.ps1 @@ -62,5 +62,6 @@ & $row 'Get-MtConnector' 'Service' 'Service' & $row 'Get-MtSetting' 'Name' 'Setting' + & $row 'New-MtTest' 'Setting' 'Setting' & $row 'Get-MtRoleMember' 'Role' 'Role' } diff --git a/powershell/internal/packs/Get-MtGitHubCliToken.ps1 b/powershell/internal/packs/Get-MtGitHubCliToken.ps1 new file mode 100644 index 0000000000..105c870d0f --- /dev/null +++ b/powershell/internal/packs/Get-MtGitHubCliToken.ps1 @@ -0,0 +1,25 @@ +function Get-MtGitHubCliToken { + <# + .SYNOPSIS + Asks the GitHub CLI for the github.com token it is signed in with, or returns $null. + + .DESCRIPTION + Runs `gh auth token --hostname github.com` when the gh CLI is installed. The token is returned to the + caller and kept nowhere. Returns $null when gh is not installed, is not signed in, or fails. + #> + [CmdletBinding()] + [OutputType([string])] + param() + + $gh = Get-Command -Name 'gh' -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1 + if (-not $gh) { return $null } + try { + $output = & $gh.Source auth token --hostname github.com 2>$null + if ($LASTEXITCODE -ne 0) { return $null } + $token = ([string]($output | Select-Object -First 1)).Trim() + if ($token) { $token } else { $null } + } catch { + Write-Debug "gh auth token failed: $_" + $null + } +} diff --git a/powershell/internal/packs/Get-MtPackCandidate.ps1 b/powershell/internal/packs/Get-MtPackCandidate.ps1 index 18cd76f3d9..4a3d2d0b1b 100644 --- a/powershell/internal/packs/Get-MtPackCandidate.ps1 +++ b/powershell/internal/packs/Get-MtPackCandidate.ps1 @@ -28,9 +28,14 @@ # Fetch exactly this commit (Restore-MtPack), skipping release selection. [Parameter()] [string] $Commit, # The branch or tag the commit was installed from (the lock file's Ref), which it may be reachable from. - [Parameter()] [string] $CommitRef + [Parameter()] [string] $CommitRef, + # The -Token of the pack command, passed on to Invoke-MtPackGitHubRequest. + [Parameter()] [AllowNull()] [securestring] $Token ) + $auth = @{} + if ($Token) { $auth.Token = $Token } + # Staging is only a temporary copy to read, so it happens under -WhatIf too. $WhatIfPreference = $false $parsed = ConvertFrom-MtPackSource -Source $Source @@ -52,14 +57,14 @@ } 'GitHub' { if ($Commit) { $parsed.Ref = $Commit } - $resolved = Resolve-MtPackGitHubSource -Source $parsed -Version $Version -IncludeRecent:$IncludeRecent -CooldownHours $CooldownHours -ReachableFrom @($CommitRef | Where-Object { $_ }) + $resolved = Resolve-MtPackGitHubSource @auth -Source $parsed -Version $Version -IncludeRecent:$IncludeRecent -CooldownHours $CooldownHours -ReachableFrom @($CommitRef | Where-Object { $_ }) foreach ($p in $resolved.PSObject.Properties) { if ($candidate.Contains($p.Name)) { $candidate[$p.Name] = $p.Value } } $candidate.Source = "github.com/$($resolved.Owner)/$($resolved.Repo)$(if ($resolved.Folder) { "/$($resolved.Folder)" })" $staging = Join-Path ([System.IO.Path]::GetTempPath()) "maester-pack-$([guid]::NewGuid().ToString('n'))" $candidate.Staging = $staging $null = New-Item -Path $staging -ItemType Directory -Force $archive = Join-Path $staging 'archive.zip' - $null = Invoke-MtPackGitHubRequest -Path "repos/$($resolved.Owner)/$($resolved.Repo)/zipball/$($resolved.Commit)" -OutFile $archive + $null = Invoke-MtPackGitHubRequest @auth -Path "repos/$($resolved.Owner)/$($resolved.Repo)/zipball/$($resolved.Commit)" -OutFile $archive $root = Join-Path $staging 'pack' Expand-MtPackArchive -Archive $archive -Destination $root -Folder $resolved.Folder Remove-Item -LiteralPath $archive -Force diff --git a/powershell/internal/packs/Get-MtPackGitHubToken.ps1 b/powershell/internal/packs/Get-MtPackGitHubToken.ps1 new file mode 100644 index 0000000000..2d1c168205 --- /dev/null +++ b/powershell/internal/packs/Get-MtPackGitHubToken.ps1 @@ -0,0 +1,50 @@ +function Get-MtPackGitHubToken { + <# + .SYNOPSIS + Reads the GitHub token one source holds for pack installs, or returns $null. + + .DESCRIPTION + Invoke-MtPackGitHubRequest asks each source in turn, at the moment of a request, and keeps none of the + answers: + + - Parameter: the -Token a person passed to Install-MtPack, Update-MtPack or Restore-MtPack. + - Session: the sign-in Connect-MtGitHub holds for this session. It is used only when that connection is + to https://api.github.com and has not expired, so a token for a GitHub Enterprise Cloud tenant with + data residency (api..ghe.com) is never sent to github.com. + - GitHubCli: `gh auth token`, when the gh CLI is installed and signed in (Get-MtGitHubCliToken). + - GH_TOKEN and GITHUB_TOKEN: the environment variables, which pipelines set. + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory)] + [ValidateSet('Parameter', 'Session', 'GitHubCli', 'GH_TOKEN', 'GITHUB_TOKEN')] + [string] $Source, + + # The -Token parameter of the pack command, for the Parameter source. + [Parameter()] + [AllowNull()] + [securestring] $Token + ) + + switch ($Source) { + 'Parameter' { + if (-not $Token -or $Token.Length -eq 0) { return $null } + return [System.Net.NetworkCredential]::new('', $Token).Password + } + 'Session' { + $connection = $__MtSession.GitHubConnection + $header = $__MtSession.GitHubAuthHeader + if (-not $connection -or -not $connection.Connected -or $header -isnot [System.Collections.IDictionary]) { return $null } + if ([string]$connection.ApiBaseUri -ne 'https://api.github.com') { return $null } + $expires = if ($connection.PSObject.Properties['TokenExpiresAt']) { $connection.TokenExpiresAt } + if ($expires -and ([datetimeoffset]$expires) -le [datetimeoffset]::UtcNow) { return $null } + $value = [string]$header['Authorization'] + if ($value -match '^Bearer\s+(\S+)$') { return $Matches[1] } + return $null + } + 'GitHubCli' { return Get-MtGitHubCliToken } + 'GH_TOKEN' { if ($env:GH_TOKEN) { return $env:GH_TOKEN } return $null } + 'GITHUB_TOKEN' { if ($env:GITHUB_TOKEN) { return $env:GITHUB_TOKEN } return $null } + } +} diff --git a/powershell/internal/packs/Invoke-MtPackGitHubRequest.ps1 b/powershell/internal/packs/Invoke-MtPackGitHubRequest.ps1 index ee11367914..07b59f0163 100644 --- a/powershell/internal/packs/Invoke-MtPackGitHubRequest.ps1 +++ b/powershell/internal/packs/Invoke-MtPackGitHubRequest.ps1 @@ -4,15 +4,28 @@ Calls the GitHub REST API for pack installs (Maester Packs design, section 5.1). .DESCRIPTION - Sends GH_TOKEN or GITHUB_TOKEN, when one is set, to api.github.com only: a private repository needs it, - and it lifts GitHub's limit of 60 anonymous requests an hour. With -OutFile the response is saved to a - file (an archive download); GitHub redirects those to codeload.github.com, which receives no token. + A private repository needs a GitHub token, and a token lifts GitHub's limit of 60 anonymous requests an + hour. The token is read at the moment of the request (Get-MtPackGitHubToken), is sent to api.github.com + only, and is kept nowhere. With -OutFile the response is saved to a file (an archive download); GitHub + redirects those to codeload.github.com, which receives no token. + + With -Token, that token is the only one used. Without it, each source is asked in turn and the first + that can read the repository is used: + + 1. the sign-in Connect-MtGitHub holds for this session, when it is to github.com; + 2. `gh auth token`, when the GitHub CLI is installed and signed in; + 3. the GH_TOKEN environment variable, then GITHUB_TOKEN; + 4. no token. + + A source GitHub answers with 401, 403 or 404 is passed over for the next one, since GitHub answers 404 + for a private repository a token cannot read. Only the name of the source that worked is remembered, for + each repository, so later requests start with it. Returns the parsed JSON, or $null for 404 with -AllowNotFound. Other failures throw with GitHub's message and, when the rate limit was reached, how to raise it. -UsedToken says whether a token was sent. #> [CmdletBinding()] - [OutputType([object], [string])] + [OutputType([object], [object[]], [string])] param( # The path after https://api.github.com/, such as 'repos/contoso/pack'. [Parameter(Mandatory)] @@ -28,35 +41,93 @@ # Receives whether a token was sent (a [ref] to a bool). [Parameter()] - [ref] $UsedToken + [ref] $UsedToken, + + # The -Token of the pack command. When given, no other source is asked. + [Parameter()] + [AllowNull()] + [securestring] $Token ) - $token = if ($env:GH_TOKEN) { $env:GH_TOKEN } elseif ($env:GITHUB_TOKEN) { $env:GITHUB_TOKEN } else { $null } - if ($UsedToken) { $UsedToken.Value = [bool]$token } - $headers = @{ Accept = 'application/vnd.github+json'; 'X-GitHub-Api-Version' = '2022-11-28'; 'User-Agent' = 'Maester' } - if ($token) { $headers['Authorization'] = "Bearer $token" } $uri = "https://api.github.com/$($Path.TrimStart('/'))" - try { - if ($OutFile) { - $null = Invoke-WebRequest -Uri $uri -Headers $headers -OutFile $OutFile -MaximumRedirection 5 -ErrorAction Stop - return $OutFile + $labels = @{ + Parameter = 'the -Token parameter' + Session = 'the Connect-MtGitHub sign-in' + GitHubCli = 'the GitHub CLI (gh auth token)' + GH_TOKEN = 'GH_TOKEN' + GITHUB_TOKEN = 'GITHUB_TOKEN' + } + $explicit = $Token -and $Token.Length -gt 0 + $order = if ($explicit) { @('Parameter') } else { @('Session', 'GitHubCli', 'GH_TOKEN', 'GITHUB_TOKEN', 'Anonymous') } + + # The source that last read this repository goes first. Its name is remembered, never its token. + if (-not $script:__MtPackGitHubTokenSource) { $script:__MtPackGitHubTokenSource = @{} } + $repository = if ($Path.TrimStart('/') -match '^repos/([^/?]+/[^/?]+)') { $Matches[1].ToLowerInvariant() } + $proven = if (-not $explicit -and $repository) { $script:__MtPackGitHubTokenSource[$repository] } + if ($proven) { $order = @($proven) + @($order | Where-Object { $_ -ne $proven }) } + + $sent = [System.Collections.Generic.List[string]]::new() + $tried = [System.Collections.Generic.List[string]]::new() + $failure = $null + foreach ($source in $order) { + $value = $null + if ($source -ne 'Anonymous') { + $value = Get-MtPackGitHubToken -Source $source -Token $Token + # gh answers with GH_TOKEN when it is set, so the same token is not sent twice. + if (-not $value -or $sent.Contains($value)) { continue } + $sent.Add($value) + $tried.Add($labels[$source]) } - Invoke-RestMethod -Uri $uri -Headers $headers -ErrorAction Stop - } catch { - $status = $null - if ($_.Exception.PSObject.Properties['Response'] -and $_.Exception.Response) { $status = [int]$_.Exception.Response.StatusCode } - if ($status -eq 404 -and $AllowNotFound) { return $null } - $message = $_.ErrorDetails.Message - try { if ($message) { $message = ($message | ConvertFrom-Json -ErrorAction Stop).message } } catch { Write-Debug $_ } - if (-not $message) { $message = $_.Exception.Message } - if ($status -in 403, 429 -and $message -match 'rate limit') { - $hint = if ($token) { 'Wait for the limit to reset.' } else { 'Set GH_TOKEN (for example from `gh auth token`) to raise the limit.' } - throw "GitHub's API rate limit was reached while reading $uri. $hint" + $headers = @{ Accept = 'application/vnd.github+json'; 'X-GitHub-Api-Version' = '2022-11-28'; 'User-Agent' = 'Maester' } + if ($value) { $headers['Authorization'] = "Bearer $value" } + try { + if ($OutFile) { + $null = Invoke-WebRequest -Uri $uri -Headers $headers -OutFile $OutFile -MaximumRedirection 5 -ErrorAction Stop + $result = $OutFile + } else { + $result = Invoke-RestMethod -Uri $uri -Headers $headers -ErrorAction Stop + } + } catch { + $status = $null + if ($_.Exception.PSObject.Properties['Response'] -and $_.Exception.Response) { $status = [int]$_.Exception.Response.StatusCode } + $message = $_.ErrorDetails.Message + try { if ($message) { $message = ($message | ConvertFrom-Json -ErrorAction Stop).message } } catch { Write-Debug $_ } + if (-not $message) { $message = $_.Exception.Message } + if ($status -in 403, 429 -and $message -match 'rate limit') { + $hint = if ($value) { 'Wait for the limit to reset.' } else { 'Sign in with `gh auth login` or Connect-MtGitHub, or pass -Token, to raise the limit.' } + throw "GitHub's API rate limit was reached while reading $uri. $hint" + } + $failure = [pscustomobject]@{ Status = $status; Message = $message } + # The source that already read this repository says a path is missing: no other source will find it. + if ($status -eq 404 -and $source -eq $proven) { break } + if ($status -in 401, 403, 404) { + if ($source -eq $proven) { $script:__MtPackGitHubTokenSource.Remove($repository) } + Write-Verbose "GitHub answered $status for $uri with $(if ($value) { $labels[$source] } else { 'no token' })." + continue + } + break + } finally { + $headers.Remove('Authorization') + $value = $null } - if ($status -eq 404) { - $hint = if ($token) { '' } else { ' If it is a private repository, set GH_TOKEN to a token that can read it.' } - throw "GitHub returned 404 Not Found for $uri.$hint" + if ($UsedToken) { $UsedToken.Value = $source -ne 'Anonymous' } + if (-not $explicit -and $repository) { $script:__MtPackGitHubTokenSource[$repository] = $source } + Write-Verbose "Read $uri with $(if ($source -eq 'Anonymous') { 'no token' } else { $labels[$source] })." + if ($result -is [array]) { return , $result } + return $result + } + + if ($UsedToken) { $UsedToken.Value = $tried.Count -gt 0 } + if ($failure.Status -eq 404) { + if ($AllowNotFound) { return $null } + $hint = if ($explicit) { + ' It does not exist, or the token passed to -Token cannot read it. A fine-grained token needs read-only Contents access to the repository.' + } elseif ($tried.Count -gt 0) { + " It does not exist, or it is a private repository that $($tried -join ' and ') cannot read. Pass -Token with a token that can read it." + } else { + ' If it is a private repository, sign in with `gh auth login`, or pass -Token with a token that can read it.' } - throw "GitHub request $uri failed$(if ($status) { " ($status)" }): $message" + throw "GitHub returned 404 Not Found for $uri.$hint" } + throw "GitHub request $uri failed$(if ($failure.Status) { " ($($failure.Status))" }): $($failure.Message)" } diff --git a/powershell/internal/packs/Invoke-MtPackInstall.ps1 b/powershell/internal/packs/Invoke-MtPackInstall.ps1 index d73c8d4fd8..988fb591e3 100644 --- a/powershell/internal/packs/Invoke-MtPackInstall.ps1 +++ b/powershell/internal/packs/Invoke-MtPackInstall.ps1 @@ -38,10 +38,15 @@ # The pack IDs being installed above this one, to refuse cycles. [Parameter()] [string[]] $Stack = @(), # Return -Previous when the fetched files have its digest, without asking again. - [Parameter()] [switch] $SkipUnchanged + [Parameter()] [switch] $SkipUnchanged, + # The -Token of the pack command, used for this pack and the packs it requires. + [Parameter()] [AllowNull()] [securestring] $Token ) - $candidate = Get-MtPackCandidate -Source $Source -Version $Version -IncludeRecent:$IncludeRecent -CooldownHours $Policy.CooldownHours + $auth = @{} + if ($Token) { $auth.Token = $Token } + + $candidate = Get-MtPackCandidate @auth -Source $Source -Version $Version -IncludeRecent:$IncludeRecent -CooldownHours $Policy.CooldownHours try { if ($candidate.Errors.Count -gt 0) { $list = @($candidate.Errors | Select-Object -First 15 | ForEach-Object { " $($_.Code): $(ConvertTo-MtPackSafeText $_.Message -MaxLength 300)" }) -join [Environment]::NewLine @@ -77,7 +82,7 @@ } if (-not ($r.PSObject.Properties['Source'] -and $r.Source)) { throw "The pack $id requires $($r.Id), which is not installed and has no Source to install it from." } Write-Host "The pack $id requires $($r.Id)$(if ($range) { " $range" }); installing it first." - $entry = Invoke-MtPackInstall -Source $r.Source -Lock $Lock -Policy $Policy -AcceptRisk $AcceptRisk -IncludeRecent:$IncludeRecent -Force:$Force -NonInteractive:$NonInteractive -Stack @($Stack + $id) + $entry = Invoke-MtPackInstall @auth -Source $r.Source -Lock $Lock -Policy $Policy -AcceptRisk $AcceptRisk -IncludeRecent:$IncludeRecent -Force:$Force -NonInteractive:$NonInteractive -Stack @($Stack + $id) if ($entry.Id -ne $r.Id) { throw "The pack $id requires $($r.Id) from $($r.Source), but that source holds $($entry.Id)." } if ($range -and -not (Test-MtVersionRange -Range $range -Version $entry.Version)) { throw "The pack $id requires $($r.Id) $range, but $($r.Source) has version $($entry.Version)." } foreach ($s in @($entry.Services)) { $requiredServices.Add($s) } diff --git a/powershell/internal/packs/Read-MtPackManifest.ps1 b/powershell/internal/packs/Read-MtPackManifest.ps1 index 087f1b370e..317c289d79 100644 --- a/powershell/internal/packs/Read-MtPackManifest.ps1 +++ b/powershell/internal/packs/Read-MtPackManifest.ps1 @@ -61,7 +61,7 @@ $topLevel = @('$schema', 'Id', 'Guid', 'Name', 'Description', 'Version', 'Publisher', 'License', 'Homepage', 'Support', 'SecurityContact', 'RequiresMaester', 'Code', 'Suites', 'Helpers', 'Connectors', 'Uses', 'Requires', 'Exports', 'Categories', 'Listed', - 'Deprecated', 'Yanked', 'Icon', 'EnabledByDefault', 'Runtime', 'Catalog', 'Pricing', 'Banner', 'Guide', 'Report') + 'Deprecated', 'Yanked', 'Icon', 'EnabledByDefault', 'Runtime', 'Catalog', 'Pricing', 'Banner', 'Guide', 'Report', 'Settings') $strictKeys = @{ Uses = @('Services', 'GraphScopes', 'TenantWrites', 'Network', 'Modules') Connector = @('Service', 'Platform', 'DisplayName', 'File', 'Connect', 'Test', 'Disconnect', 'Describe', 'Renew', 'OptIn', 'Permissions', 'Environment') @@ -166,6 +166,28 @@ } if ($folders.Suites.Count -eq 0 -and $connectors.Count -eq 0) { & $fail 'The pack has no Suites and no Connectors, so it adds nothing.' } + # Settings: the GlobalSettings keys the pack reads, each named Namespace.Key with a type, so the config is + # checked against them, Get-MtSetting returns their defaults and the pack's page can list them. + $settingTypes = 'int', 'bool', 'string', 'string[]', 'object', 'object[]' + $settingKeys = 'Type', 'Default', 'Description', 'AllowedValues', 'Kind', 'Sensitive' + $settings = [ordered]@{} + if ($manifest.PSObject.Properties['Settings'] -and $null -ne $manifest.Settings) { + if ($manifest.Settings -isnot [pscustomobject]) { & $fail 'Settings must be an object with one entry per setting.' } + else { + foreach ($p in $manifest.Settings.PSObject.Properties) { + $where = "The setting '$($p.Name)'" + if ($p.Name -notmatch '^[A-Za-z][A-Za-z0-9]*(\.[A-Za-z][A-Za-z0-9]*)+$') { & $fail "$where must be named Namespace.Key, for example Contoso.Regions. Names without a dot are Maester's own settings."; continue } + if ($p.Value -isnot [pscustomobject]) { & $fail "$where must be an object with a Type."; continue } + foreach ($key in $p.Value.PSObject.Properties.Name) { if ($key -notin $settingKeys) { $warnings.Add("$where has the unknown key '$key', which is ignored.") } } + $type = if ($p.Value.PSObject.Properties['Type']) { $p.Value.Type } else { $null } + if ($type -isnot [string] -or $type -notin $settingTypes) { & $fail "$where needs a Type: $($settingTypes -join ', ')."; continue } + if ($p.Value.PSObject.Properties['Sensitive'] -and $p.Value.Sensitive -isnot [bool]) { & $fail "$where`: Sensitive must be true or false."; continue } + if ($p.Value.PSObject.Properties['AllowedValues'] -and ($type -notin 'string', 'string[]' -or @($p.Value.AllowedValues | Where-Object { $_ -isnot [string] }).Count -gt 0)) { & $fail "$where`: AllowedValues is a list of strings, for a string or string[] setting."; continue } + $settings[$p.Name] = $p.Value + } + } + } + # What the pack reaches (section 4.2). $uses = $manifest.PSObject.Properties['Uses'] if ($uses -and $null -ne $uses.Value) { @@ -318,6 +340,7 @@ $normalised['Helpers'] = [string[]]@($folders.Helpers | Where-Object { $_ -is [string] }) $normalised['Connectors'] = @($connectors | Where-Object { $_ -is [pscustomobject] }) $normalised['Exports'] = [string[]]@(& $list 'Exports') + $normalised['Settings'] = [pscustomobject]$settings $usesValue = if ($uses -and $uses.Value -is [pscustomobject]) { $uses.Value } else { [pscustomobject]@{} } $normalised['Uses'] = [pscustomobject][ordered]@{ Services = [string[]]@(& $list 'Services' $usesValue) diff --git a/powershell/internal/packs/Register-MtPackService.ps1 b/powershell/internal/packs/Register-MtPackService.ps1 index ae3c707973..8d83060893 100644 --- a/powershell/internal/packs/Register-MtPackService.ps1 +++ b/powershell/internal/packs/Register-MtPackService.ps1 @@ -10,8 +10,12 @@ connector says OptIn), and a test whose pack is missing gets ServiceNotRegistered. The entry also keeps Pack (the pack row), Connector (its manifest entry), DisplayName and Platform. - The registry is rebuilt from the given pack set each time, so a pack that is no longer installed or - allowed loses its services. Returns the service names registered. + The settings those packs declare (Settings in maester-pack.json) are added to the settings registry in the + same way, so the config is checked against them, Get-MtSetting returns their defaults and a pack test can + bind one with [MaesterParameter(Setting = 'Namespace.Key')]. + + Both registries are rebuilt from the given pack set each time, so a pack that is no longer installed or + allowed loses its services and settings. Returns the service names registered. #> [CmdletBinding()] [OutputType([string[]])] @@ -20,7 +24,18 @@ ) $services = @{} + $settings = @{} foreach ($pack in ($PackSet | Where-Object { $_.Status -eq 'Ready' -and $_.Manifest })) { + if ($pack.Manifest.PSObject.Properties['Settings'] -and $pack.Manifest.Settings) { + foreach ($p in $pack.Manifest.Settings.PSObject.Properties) { + if ($settings.ContainsKey($p.Name)) { Write-Warning "The setting $($p.Name) is declared by both $($settings[$p.Name].Pack) and $($pack.Id); the declaration of $($settings[$p.Name].Pack) is used."; continue } + $entry = @{ Pack = [string]$pack.Id } + foreach ($field in $p.Value.PSObject.Properties) { $entry[$field.Name] = $field.Value } + if (-not $entry.ContainsKey('Default')) { $entry['Default'] = $null } + $entry['Sensitive'] = [bool]($entry.ContainsKey('Sensitive') -and $entry['Sensitive']) + $settings[$p.Name] = $entry + } + } foreach ($c in $pack.Manifest.Connectors) { $name = [string]$c.Service if ($services.ContainsKey($name)) { Write-Warning "The service $name is provided by both $($services[$name].Pack.Id) and $($pack.Id); the connector of $($services[$name].Pack.Id) is used."; continue } @@ -39,6 +54,8 @@ } $script:__MtPackServices = $services $script:__MtLayeredServiceRegistry = $null + $script:__MtPackSettings = $settings + $script:__MtLayeredSettingRegistry = $null [string[]]@($services.Keys | Sort-Object) } diff --git a/powershell/internal/packs/Resolve-MtPackGitHubSource.ps1 b/powershell/internal/packs/Resolve-MtPackGitHubSource.ps1 index 5cbaf73b44..a9c4b8ec76 100644 --- a/powershell/internal/packs/Resolve-MtPackGitHubSource.ps1 +++ b/powershell/internal/packs/Resolve-MtPackGitHubSource.ps1 @@ -35,12 +35,17 @@ [Parameter()] [int] $CooldownHours = 72, # More branches or tags a requested commit may be reachable from, such as the ref in the lock file. # Each must be a real branch or tag of the repository; a commit ID is ignored. - [Parameter()] [string[]] $ReachableFrom = @() + [Parameter()] [string[]] $ReachableFrom = @(), + # The -Token of the pack command, passed on to Invoke-MtPackGitHubRequest. + [Parameter()] [AllowNull()] [securestring] $Token ) + $auth = @{} + if ($Token) { $auth.Token = $Token } + $usedToken = $false $repoPath = "repos/$($Source.Owner)/$($Source.Repo)" - $repository = Invoke-MtPackGitHubRequest -Path $repoPath -UsedToken ([ref] $usedToken) + $repository = Invoke-MtPackGitHubRequest @auth -Path $repoPath -UsedToken ([ref] $usedToken) $owner = $Source.Owner $repo = $Source.Repo if ($repository.full_name -and $repository.full_name -ne "$owner/$repo") { @@ -52,12 +57,12 @@ # Invoke-RestMethod writes an empty JSON array as one empty array, not as nothing: enumerate it, so that a # repository without releases has none and installs from its default branch. - $releases = @(Invoke-MtPackGitHubRequest -Path "$repoPath/releases?per_page=30" | ForEach-Object { $_ } | + $releases = @(Invoke-MtPackGitHubRequest @auth -Path "$repoPath/releases?per_page=30" | ForEach-Object { $_ } | Where-Object { $_ -and $_.tag_name -and -not $_.draft -and -not $_.prerelease } | Sort-Object { [datetime]$_.published_at } -Descending) $commitOf = { param($ref) - $commit = Invoke-MtPackGitHubRequest -Path "$repoPath/commits/$([uri]::EscapeDataString($ref))" + $commit = Invoke-MtPackGitHubRequest @auth -Path "$repoPath/commits/$([uri]::EscapeDataString($ref))" [string]$commit.sha } $ageOf = { @@ -77,7 +82,7 @@ @($name.Substring(5)) } else { @("heads/$name", "tags/$name") } foreach ($n in $names) { - $candidateRef = Invoke-MtPackGitHubRequest -Path "$repoPath/git/ref/$([uri]::EscapeDataString($n))" -AllowNotFound + $candidateRef = Invoke-MtPackGitHubRequest @auth -Path "$repoPath/git/ref/$([uri]::EscapeDataString($n))" -AllowNotFound if ($candidateRef -and $candidateRef.ref -ceq "refs/$n") { return $candidateRef } } $null @@ -88,7 +93,7 @@ $newer = $null if ($requested) { $release = $releases | Where-Object { $_.tag_name -eq $requested -or $_.tag_name -eq "v$requested" -or "v$($_.tag_name)" -eq $requested } | Select-Object -First 1 - if (-not $release) { $release = Invoke-MtPackGitHubRequest -Path "$repoPath/releases/tags/$([uri]::EscapeDataString($requested))" -AllowNotFound } + if (-not $release) { $release = Invoke-MtPackGitHubRequest @auth -Path "$repoPath/releases/tags/$([uri]::EscapeDataString($requested))" -AllowNotFound } $ref = if ($release) { [string]$release.tag_name } else { $requested } if ($release) { $commit = & $commitOf "refs/tags/$ref" } else { @@ -106,7 +111,7 @@ if ($extraRef) { $refs += [string]$extraRef.ref } } $refs += @($releases | ForEach-Object { "refs/tags/$($_.tag_name)" }) - if (-not (Test-MtPackCommitReachable -RepositoryPath $repoPath -Commit $commit -Ref $refs)) { + if (-not (Test-MtPackCommitReachable @auth -RepositoryPath $repoPath -Commit $commit -Ref $refs)) { throw "The commit $commit is not on the default branch, a release$(if (@($ReachableFrom | Where-Object { $_ }).Count -gt 0) { ' or the branch or tag it was installed from' }) of $owner/$repo. GitHub serves commits from forks under the original repository's name, so Maester installs only commits that belong to the repository itself." } $release = $releases | Where-Object { $_.target_commitish -eq $commit } | Select-Object -First 1 @@ -168,11 +173,15 @@ function Test-MtPackCommitReachable { param( [Parameter(Mandatory)] [string] $RepositoryPath, [Parameter(Mandatory)] [string] $Commit, - [Parameter(Mandatory)] [AllowEmptyCollection()] [string[]] $Ref + [Parameter(Mandatory)] [AllowEmptyCollection()] [string[]] $Ref, + [Parameter()] [AllowNull()] [securestring] $Token ) + $auth = @{} + if ($Token) { $auth.Token = $Token } + foreach ($r in ($Ref | Where-Object { $_ } | Select-Object -Unique -First 10)) { - $compare = Invoke-MtPackGitHubRequest -Path "$RepositoryPath/compare/$([uri]::EscapeDataString($r))...$Commit" -AllowNotFound + $compare = Invoke-MtPackGitHubRequest @auth -Path "$RepositoryPath/compare/$([uri]::EscapeDataString($r))...$Commit" -AllowNotFound # 'behind' or 'identical': the commit is an ancestor of the ref, or is the ref. if ($compare -and $compare.status -in 'behind', 'identical') { return $true } } diff --git a/powershell/internal/packs/Test-MtPackContent.ps1 b/powershell/internal/packs/Test-MtPackContent.ps1 index d685c3f129..8b0eba56de 100644 --- a/powershell/internal/packs/Test-MtPackContent.ps1 +++ b/powershell/internal/packs/Test-MtPackContent.ps1 @@ -265,7 +265,7 @@ function Get-MtPackReservedTag { [CmdletBinding()] [OutputType([string[]])] param() - [string[]]@('Maester', 'MT', 'CIS', 'CISA', 'EIDSCA', 'ORCA', 'AD', 'ASD', 'AZDO', 'XSPM', 'All', 'Custom') + [string[]]@('Maester', 'MT', 'CIS', 'CISA', 'EIDSCA', 'ORCA', 'AD', 'ASD', 'DISA', 'AZDO', 'XSPM', 'All', 'Custom') } function Test-MtPackScriptFile { diff --git a/powershell/internal/report/ConvertTo-MtMaesterResult.ps1 b/powershell/internal/report/ConvertTo-MtMaesterResult.ps1 index 343a43cab0..f85dafd89e 100644 --- a/powershell/internal/report/ConvertTo-MtMaesterResult.ps1 +++ b/powershell/internal/report/ConvertTo-MtMaesterResult.ps1 @@ -710,13 +710,33 @@ function New-MtResultConfig { ) if ($null -eq $RunConfig) { return $null } - if ($NativeRows.Count -eq 0) { return $RunConfig } - $copy = [pscustomobject]@{} - foreach ($p in $RunConfig.PSObject.Properties) { - if ($p.Name -in 'TestSettings', 'TestSettingsHash') { continue } - $copy | Add-Member -NotePropertyName $p.Name -NotePropertyValue $p.Value + # The result records the config, so the value of a sensitive setting is replaced before it is copied. + $registry = (Get-MtSettingRegistry).Settings + $globalSettings = if ($RunConfig.PSObject.Properties['GlobalSettings']) { $RunConfig.GlobalSettings } else { $null } + if ($globalSettings -and @($globalSettings.PSObject.Properties | Where-Object { $null -ne $_.Value -and $registry.ContainsKey($_.Name) -and $registry[$_.Name].Sensitive }).Count -gt 0) { + $redacted = [pscustomobject]@{} + foreach ($p in $globalSettings.PSObject.Properties) { + $isSensitive = $null -ne $p.Value -and $registry.ContainsKey($p.Name) -and $registry[$p.Name].Sensitive + $redacted | Add-Member -NotePropertyName $p.Name -NotePropertyValue $(if ($isSensitive) { '[redacted]' } else { $p.Value }) + } + $globalSettings = $redacted + } + $withSettings = { + param($skip) + $object = [pscustomobject]@{} + foreach ($p in $RunConfig.PSObject.Properties) { + if ($p.Name -in $skip) { continue } + $object | Add-Member -NotePropertyName $p.Name -NotePropertyValue $(if ($p.Name -eq 'GlobalSettings') { $globalSettings } else { $p.Value }) + } + $object } + if ($NativeRows.Count -eq 0) { + if ([object]::ReferenceEquals($globalSettings, $RunConfig.GlobalSettings)) { return $RunConfig } + return & $withSettings @() + } + + $copy = & $withSettings @('TestSettings', 'TestSettingsHash') $catalog = @{} foreach ($t in @(Get-MtTestCatalog)) { if ($t.Id) { $catalog[$t.Id] = $t } } $settings = foreach ($row in $Rows) { diff --git a/powershell/internal/services/entra/Get-MtActivityBasedTimeout.ps1 b/powershell/internal/services/entra/Get-MtActivityBasedTimeout.ps1 new file mode 100644 index 0000000000..f3eebc95c9 --- /dev/null +++ b/powershell/internal/services/entra/Get-MtActivityBasedTimeout.ps1 @@ -0,0 +1,40 @@ +function Get-MtActivityBasedTimeout { + <# + .SYNOPSIS + Returns the web session idle timeout that the tenant's activity-based timeout policy sets. + + .DESCRIPTION + The idle session timeout in the Microsoft 365 admin center (Settings > Org settings > Security & privacy > + Idle session timeout) is stored as an activity-based timeout policy in Microsoft Entra ID. Its definition is a + JSON string whose WebSessionIdleTimeout value is a time span, such as 03:00:00. + + Returns an object with Timeout (a [timespan], or $null when no policy sets a timeout) and PolicyName (the + display name of the policy that was read, or $null when there is none). + + .EXAMPLE + (Get-MtActivityBasedTimeout).Timeout + + Returns the idle timeout as a time span, or $null when none is set. + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param () + + $policies = @(Invoke-MtGraphRequest -RelativeUri 'policies/activityBasedTimeoutPolicies' | Where-Object { $_ }) + + $timeout = $null + $policyName = $null + if ($policies.Count -gt 0) { + $policyName = $policies[0].displayName + $definition = @($policies[0].definition)[0] | ConvertFrom-Json + $value = $definition.ActivityBasedTimeoutPolicy.ApplicationPolicies[0].WebSessionIdleTimeout + if ($value) { + $timeout = [timespan]::Parse($value) + } + } + + [pscustomobject]@{ + Timeout = $timeout + PolicyName = $policyName + } +} diff --git a/powershell/internal/services/entra/Get-MtDomainPasswordValidity.ps1 b/powershell/internal/services/entra/Get-MtDomainPasswordValidity.ps1 new file mode 100644 index 0000000000..170724c9f5 --- /dev/null +++ b/powershell/internal/services/entra/Get-MtDomainPasswordValidity.ps1 @@ -0,0 +1,37 @@ +function Get-MtDomainPasswordValidity { + <# + .SYNOPSIS + Returns the password expiration period of each domain of the tenant. + + .DESCRIPTION + The password expiration policy is stored per domain, as passwordValidityPeriodInDays. It applies only to + domains that are verified and managed (not federated), so each domain is returned with IsApplicable. + + ValidityDays is the number of days a password is valid. NeverExpires is true when the value is the one + Microsoft Entra ID uses for "never expire" (2147483647). IsSet is false when the domain stores no value; what + applies then is not stated by the API, so each check decides how to report it. + + .EXAMPLE + Get-MtDomainPasswordValidity | Where-Object IsApplicable + + Returns the verified, managed domains with their password expiration period. + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param () + + $neverExpires = [int]::MaxValue + foreach ($domain in @(Invoke-MtGraphRequest -RelativeUri 'domains')) { + $raw = $domain.passwordValidityPeriodInDays + $days = 0 + # A boolean or a value that is not a number means no period is stored. + $isSet = ($null -ne $raw) -and ($raw -isnot [bool]) -and [int]::TryParse($raw.ToString(), [ref]$days) + [pscustomobject]@{ + Id = $domain.id + IsApplicable = ($domain.authenticationType -eq 'Managed') -and ($domain.isVerified -eq $true) + IsSet = $isSet + ValidityDays = if ($isSet) { $days } else { $null } + NeverExpires = $isSet -and $days -eq $neverExpires + } + } +} diff --git a/powershell/internal/services/entra/Get-MtEmergencyAccessAccount.ps1 b/powershell/internal/services/entra/Get-MtEmergencyAccessAccount.ps1 index f5d7805360..e0bd75d1ed 100644 --- a/powershell/internal/services/entra/Get-MtEmergencyAccessAccount.ps1 +++ b/powershell/internal/services/entra/Get-MtEmergencyAccessAccount.ps1 @@ -1,24 +1,29 @@ function Get-MtEmergencyAccessAccount { <# .SYNOPSIS - Returns the emergency access (break-glass) accounts and groups configured in maester-config.json, resolved to directory object IDs. + Resolves emergency access (break-glass) accounts and groups to directory object IDs. .DESCRIPTION - Reads the EmergencyAccessAccounts global setting and resolves each entry - by object Id, or by + Resolves each entry of the EmergencyAccessAccounts setting - by object Id, or by UserPrincipalName / mail - to its directory object id and type (user or group). Returns objects - with ObjectId, DisplayName, and Type. Returns nothing when no emergency access accounts are - configured or none can be resolved. + with ObjectId, DisplayName, and Type. Returns nothing when no accounts are passed. + + A test receives the setting as a parameter, [MaesterParameter(Setting = 'EmergencyAccessAccounts')], + and passes it here, so a test's own TestSettings row can override it. .EXAMPLE - Get-MtEmergencyAccessAccount + Get-MtEmergencyAccessAccount -Account $EmergencyAccessAccounts Returns the resolved emergency access accounts and groups. #> [CmdletBinding()] - param () + param ( + # The entries of the EmergencyAccessAccounts setting: objects with Id or UserPrincipalName, and Type. + [Parameter()] [AllowNull()] [AllowEmptyCollection()] [object[]] $Account = @() + ) - $emergencyAccessAccounts = Get-MtSetting -Name 'EmergencyAccessAccounts' - if (-not $emergencyAccessAccounts) { + $emergencyAccessAccounts = @($Account | Where-Object { $_ }) + if ($emergencyAccessAccounts.Count -eq 0) { return } diff --git a/powershell/internal/services/entra/Get-MtPrivilegedRoleUser.ps1 b/powershell/internal/services/entra/Get-MtPrivilegedRoleUser.ps1 index 68546e4985..392ec2a65c 100644 --- a/powershell/internal/services/entra/Get-MtPrivilegedRoleUser.ps1 +++ b/powershell/internal/services/entra/Get-MtPrivilegedRoleUser.ps1 @@ -12,7 +12,7 @@ roles. The hashtable is empty when nobody holds a privileged role. .EXAMPLE - $privilegedUsers = Get-MtPrivilegedRoleUser -ExcludeEmergencyAccessAccount + $privilegedUsers = Get-MtPrivilegedRoleUser -EmergencyAccessAccounts $EmergencyAccessAccounts $privilegedUsers.Keys Returns the object IDs of the users that hold a privileged directory role, apart from the emergency access accounts. @@ -20,8 +20,8 @@ [CmdletBinding()] [OutputType([hashtable])] param( - # Leave out the emergency access accounts named in the Maester configuration (EmergencyAccessAccounts). - [switch] $ExcludeEmergencyAccessAccount + # Emergency access accounts to leave out: the entries of the EmergencyAccessAccounts setting. + [Parameter()] [AllowNull()] [AllowEmptyCollection()] [object[]] $EmergencyAccessAccounts = @() ) # isPrivileged can be filtered on in beta only; CIS.M365.5.3.1 reads the same list. @@ -29,7 +29,7 @@ foreach ($role in @(Invoke-MtGraphRequest -RelativeUri 'roleManagement/directory/roleDefinitions' -ApiVersion beta -Filter 'isPrivileged eq true')) { $roleName[$role.id] = $role.displayName } - $excluded = if ($ExcludeEmergencyAccessAccount) { @(Get-MtEmergencyAccessAccount | ForEach-Object ObjectId) } else { @() } + $excluded = if (@($EmergencyAccessAccounts | Where-Object { $_ }).Count -gt 0) { @(Get-MtEmergencyAccessAccount -Account $EmergencyAccessAccounts | ForEach-Object ObjectId) } else { @() } $rolesOf = @{} foreach ($assignment in @((Get-MtDirectoryRoleAssignment -ExpandPrincipal).Assignments | Where-Object { $roleName.ContainsKey($_.roleDefinitionId) })) { diff --git a/powershell/internal/services/entra/Get-MtRoleActivationNotificationRecipient.ps1 b/powershell/internal/services/entra/Get-MtRoleActivationNotificationRecipient.ps1 new file mode 100644 index 0000000000..f44b72e249 --- /dev/null +++ b/powershell/internal/services/entra/Get-MtRoleActivationNotificationRecipient.ps1 @@ -0,0 +1,34 @@ +function Get-MtRoleActivationNotificationRecipient { + <# + .SYNOPSIS + Returns the additional recipients of the role activation alert of a directory role. + + .DESCRIPTION + Privileged Identity Management sends a "Role activation alert" to the administrators when an eligible member + activates a role. Its additional recipients are stored in the role's management policy, in the rule + Notification_Admin_EndUser_Assignment (notificationRecipients). Returns those addresses, or nothing when the + role sends the alert to no additional recipient. + + .EXAMPLE + Get-MtRoleActivationNotificationRecipient -RoleDefinitionId '62e90394-69f5-4237-9190-012177145e10' + + Returns the additional recipients of the activation alert of the Global Administrator role. + #> + [CmdletBinding()] + [OutputType([string[]])] + param ( + # The ID of the directory role definition. + [Parameter(Mandatory)] + [string] $RoleDefinitionId + ) + + $policySplat = @{ + ApiVersion = 'v1.0' + RelativeUri = 'policies/roleManagementPolicyAssignments' + Filter = "scopeId eq '/' and scopeType eq 'DirectoryRole' and roleDefinitionId eq '$RoleDefinitionId'" + QueryParameters = @{ expand = 'policy(expand=rules)' } + } + $assignment = Invoke-MtGraphRequest @policySplat + $rule = @($assignment.policy.rules) | Where-Object { $_.id -eq 'Notification_Admin_EndUser_Assignment' } | Select-Object -First 1 + return [string[]]@($rule.notificationRecipients | Where-Object { $_ }) +} diff --git a/powershell/internal/services/entra/Get-MtUserLastSignIn.ps1 b/powershell/internal/services/entra/Get-MtUserLastSignIn.ps1 new file mode 100644 index 0000000000..0c507e8a0f --- /dev/null +++ b/powershell/internal/services/entra/Get-MtUserLastSignIn.ps1 @@ -0,0 +1,37 @@ +function Get-MtUserLastSignIn { + <# + .SYNOPSIS + Returns the time of a user's most recent sign-in, in UTC, from the signInActivity of a user object. + + .DESCRIPTION + Reads the signInActivity that a users request returns when it selects that property. By default the latest of + the interactive and the non-interactive sign-in is returned. With -InteractiveOnly only lastSignInDateTime is + read, as some audit procedures do. + + Returns $null when the user has no recorded sign-in of the kind asked for. + + .EXAMPLE + Get-MtUserLastSignIn -User $user + + Returns the latest interactive or non-interactive sign-in of $user, or $null. + #> + [CmdletBinding()] + [OutputType([datetime])] + param ( + # A user object from Microsoft Graph that includes signInActivity. + [Parameter(Mandatory)] + [object] $User, + + # Read only the interactive sign-in (lastSignInDateTime). + [switch] $InteractiveOnly + ) + + $values = if ($InteractiveOnly) { + @($User.signInActivity.lastSignInDateTime) + } else { + @($User.signInActivity.lastSignInDateTime, $User.signInActivity.lastNonInteractiveSignInDateTime) + } + $signIns = @($values | Where-Object { $_ } | ForEach-Object { ([datetime]$_).ToUniversalTime() }) + if ($signIns.Count -eq 0) { return $null } + return ($signIns | Measure-Object -Maximum).Maximum +} diff --git a/powershell/internal/session/Clear-ModuleVariable.ps1 b/powershell/internal/session/Clear-ModuleVariable.ps1 index 2817a52795..2c4eb15b76 100644 --- a/powershell/internal/session/Clear-ModuleVariable.ps1 +++ b/powershell/internal/session/Clear-ModuleVariable.ps1 @@ -17,6 +17,7 @@ $__MtSession.TestResultDetail = @{} $__MtSession.NativeTestInfo = @{} $__MtSession.NativeReturnValue = @{} + $__MtSession.SettingRead = @{} $__MtSession.MaesterConfig = $null $__MtSession.ConnectionConfig = $null $__MtSession.AdminPortalUrl = @{} diff --git a/powershell/internal/utility/ConvertTo-MtCommandParameterValue.ps1 b/powershell/internal/utility/ConvertTo-MtCommandParameterValue.ps1 new file mode 100644 index 0000000000..394d9da647 --- /dev/null +++ b/powershell/internal/utility/ConvertTo-MtCommandParameterValue.ps1 @@ -0,0 +1,48 @@ +function ConvertTo-MtCommandParameterValue { + <# + .SYNOPSIS + Renders one bound parameter value for the recorded Invoke-Maester command string. + + .DESCRIPTION + Strings are quoted and value types are written as they are. Anything else is rendered as + its type name in angle brackets, never its content: interpolating an arbitrary object calls + that object's own ToString(), and a type supplied by the caller can use that to place its + contents - a connection string, an API key, a token - into a command string that is stored + in the result file and shown in the report. + + A $null element inside an array renders as an empty string, matching what the previous + inline join produced. + + .EXAMPLE + ConvertTo-MtCommandParameterValue -Value 'Entra' + + Returns 'Entra' in quotes. + + .EXAMPLE + ConvertTo-MtCommandParameterValue -Value $config + + Returns rather than whatever $config says about itself. + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter()] + [AllowNull()] + [object] $Value + ) + + if ($null -eq $Value) { return '' } + if ($Value -is [string]) { return "'$Value'" } + if ($Value -is [ValueType]) { return "$Value" } + + if ($Value -is [array]) { + $items = @($Value | ForEach-Object { + if ($null -eq $_) { '' } + elseif ($_ -is [string] -or $_ -is [ValueType]) { "$_" } + else { "<$($_.GetType().Name)>" } + }) + return "@('$($items -join "', '")')" + } + + return "<$($Value.GetType().Name)>" +} diff --git a/powershell/lib/Maester.Engine.dll b/powershell/lib/Maester.Engine.dll index 296cb55a1c..d6b54ac76a 100644 Binary files a/powershell/lib/Maester.Engine.dll and b/powershell/lib/Maester.Engine.dll differ diff --git a/powershell/public/connect/Connect-Maester.ps1 b/powershell/public/connect/Connect-Maester.ps1 index caaf7c4efc..e09e2e5b5d 100644 --- a/powershell/public/connect/Connect-Maester.ps1 +++ b/powershell/public/connect/Connect-Maester.ps1 @@ -669,13 +669,8 @@ try { $adoModule = Get-Module -Name ADOPS $adoAvailable = $adoModule -or (Get-Module -Name ADOPS -ListAvailable) - if ($adoAvailable) { - if (-not $adoModule) { - Import-Module -Name ADOPS -Global -ErrorAction Stop - } - # Reset persisted state before config discovery too: a missing or invalid config - # must not revive the old organization when the next run resets its probe cache. - Disconnect-ADOPS -ErrorAction Stop + if ($adoAvailable -and -not $adoModule) { + Import-Module -Name ADOPS -Global -ErrorAction Stop } # A connector may have discovered config before the tenant was known. Refresh that # config for this tenant, while preserving any config supplied by a test run. @@ -693,12 +688,25 @@ } Add-ConnectionResult -Name 'Azure DevOps' -Status 'Not installed' -Details 'Run: Install-Module ADOPS -Scope CurrentUser' } elseif ([string]::IsNullOrWhiteSpace($organization)) { - $azureDevOpsProblem = @{ - Message = 'No Azure DevOps organization specified. Provide -AzureDevOpsOrganization or set AzureDevOpsOrganization in maester-config.json.' - Category = [System.Management.Automation.ErrorCategory]::InvalidArgument + # Without an organization there is nothing to connect to, so an existing ADOPS session (for example + # from Connect-ADOPS) is kept rather than torn down. Test-MtConnection verifies it the way it does + # for every run, so the summary reports the organization the tests will actually read. + $__MtSession.AzureDevOpsConnectionCache = $null + $existingOrganization = if (Test-MtConnection -Service AzureDevOps) { $__MtSession.AzureDevOpsConnectionCache['Organization'] } + if ($existingOrganization) { + Write-Warning "No Azure DevOps organization specified. Using the existing ADOPS session to '$existingOrganization'. Provide -AzureDevOpsOrganization or set AzureDevOpsOrganization in maester-config.json to connect to a different organization." + Add-ConnectionResult -Name 'Azure DevOps' -Status 'Connected' -Details "$existingOrganization (existing ADOPS session; no organization specified)" + } else { + $azureDevOpsProblem = @{ + Message = 'No Azure DevOps organization specified. Provide -AzureDevOpsOrganization or set AzureDevOpsOrganization in maester-config.json.' + Category = [System.Management.Automation.ErrorCategory]::InvalidArgument + } + Add-ConnectionResult -Name 'Azure DevOps' -Status 'Skipped' -Details 'Provide -AzureDevOpsOrganization or set AzureDevOpsOrganization in maester-config.json' } - Add-ConnectionResult -Name 'Azure DevOps' -Status 'Skipped' -Details 'Provide -AzureDevOpsOrganization or set AzureDevOpsOrganization in maester-config.json' } else { + # ADOPS persists the organization. A failed token request or sign-in must not revive + # the previous organization when Invoke-Maester resets its per-run connection probe. + Disconnect-ADOPS -ErrorAction Stop $connectAdoParams = @{ Organization = $organization; ErrorAction = 'Stop' } if ($TenantId) { $connectAdoParams['TenantId'] = $TenantId diff --git a/powershell/public/packs/Install-MtPack.ps1 b/powershell/public/packs/Install-MtPack.ps1 index a21d673d67..599c95e350 100644 --- a/powershell/public/packs/Install-MtPack.ps1 +++ b/powershell/public/packs/Install-MtPack.ps1 @@ -57,6 +57,16 @@ Answer yes to the approval question. A pack of High risk, or one newer than the cooldown, still needs its code typed unless -AcceptRisk and -IncludeRecent cover it. + .PARAMETER Token + A GitHub token that can read the pack's repository, as a SecureString, for a private or internal + repository. It is used for this command only, is sent to api.github.com only, and is not stored. When it + is given, no other sign-in is tried. Without it, Maester uses the first of these that can read the + repository: the sign-in of Connect-MtGitHub in this session, the GitHub CLI (`gh auth token`, when gh is + installed and signed in), then the GH_TOKEN and GITHUB_TOKEN environment variables. An environment + variable can be read by every process and module in the session, including installed packs, so prefer + the other ways outside a pipeline. A fine-grained token needs only read-only Contents access to the + one repository. + .PARAMETER PassThru Return the lock file entry of the pack. Without it, Install-MtPack writes what was installed and how to run it, and returns nothing. @@ -82,6 +92,11 @@ Installs the demo pack, then runs only its tests, by the pack's code. + .EXAMPLE + Install-MtPack contoso/private-pack -Token (Get-Secret -Name PackReadToken) + + Installs a pack from a private repository with a token read from a secret vault. + .LINK https://maester.dev/docs/commands/Install-MtPack #> @@ -115,7 +130,10 @@ [switch] $Force, [Parameter()] - [switch] $PassThru + [switch] $PassThru, + + [Parameter()] + [securestring] $Token ) $where = Resolve-MtPackLockPath -PackLock $PackLock -Scope $Scope -Path (Get-Location).Path @@ -125,7 +143,7 @@ $quiet = $NonInteractive -or (Test-MtPackNonInteractive) $before = @($lock.Packs | ForEach-Object { $_.Id }) - $entry = Invoke-MtPackInstall -Source $Source -Version $Version -Lock $lock -Policy $policy -AcceptRisk $AcceptRisk -IncludeRecent:$IncludeRecent -Force:$Force -NonInteractive:$quiet -Previous ($lock.Packs | Where-Object { $_.Id -eq $Source -or $_.Source -eq $Source } | Select-Object -First 1) + $entry = Invoke-MtPackInstall -Token $Token -Source $Source -Version $Version -Lock $lock -Policy $policy -AcceptRisk $AcceptRisk -IncludeRecent:$IncludeRecent -Force:$Force -NonInteractive:$quiet -Previous ($lock.Packs | Where-Object { $_.Id -eq $Source -or $_.Source -eq $Source } | Select-Object -First 1) if (-not $entry) { return } Write-MtPackLock -Path $where.LockPath -Lock $lock diff --git a/powershell/public/packs/Restore-MtPack.ps1 b/powershell/public/packs/Restore-MtPack.ps1 index bfe20073e4..bf7b920c7c 100644 --- a/powershell/public/packs/Restore-MtPack.ps1 +++ b/powershell/public/packs/Restore-MtPack.ps1 @@ -20,6 +20,16 @@ The lock file to restore from. By default the one beside the Maester config found from the current folder, else the user's. + .PARAMETER Token + A GitHub token that can read the pack's repository, as a SecureString, for a private or internal + repository. It is used for this command only, is sent to api.github.com only, and is not stored. When it + is given, no other sign-in is tried. Without it, Maester uses the first of these that can read the + repository: the sign-in of Connect-MtGitHub in this session, the GitHub CLI (`gh auth token`, when gh is + installed and signed in), then the GH_TOKEN and GITHUB_TOKEN environment variables. An environment + variable can be read by every process and module in the session, including installed packs, so prefer + the other ways outside a pipeline. A fine-grained token needs only read-only Contents access to the + one repository. + .EXAMPLE Restore-MtPack @@ -30,6 +40,11 @@ Restores, then runs, in a pipeline. + .EXAMPLE + Restore-MtPack -Token (Get-Secret -Name PackReadToken) + + Restores packs from private repositories with a token read from a secret vault. + .LINK https://maester.dev/docs/commands/Restore-MtPack #> @@ -40,7 +55,10 @@ [string[]] $Id, [Parameter()] - [string] $PackLock + [string] $PackLock, + + [Parameter()] + [securestring] $Token ) Write-Verbose "Restore-MtPack: Id=$($Id -join ', ') PackLock=$PackLock" @@ -61,7 +79,7 @@ $Present = $false if (Test-Path -LiteralPath $Target -PathType Container) { $Present = (Get-MtPackDigest -Path $Target).Digest -eq $Entry.Digest } if (-not $Present -and $PSCmdlet.ShouldProcess("$($Entry.Id) $($Entry.Version)", 'Restore the pack')) { - $Candidate = Get-MtPackCandidate -Source $Entry.Source -Commit $Entry.Commit -CommitRef $(if ($Entry.PSObject.Properties['Ref']) { [string]$Entry.Ref }) -IncludeRecent + $Candidate = Get-MtPackCandidate -Token $Token -Source $Entry.Source -Commit $Entry.Commit -CommitRef $(if ($Entry.PSObject.Properties['Ref']) { [string]$Entry.Ref }) -IncludeRecent if ($Candidate.Digest -ne $Entry.Digest) { throw "its files are not the approved files (digest $($Candidate.Digest), the lock file has $($Entry.Digest))." } $null = Save-MtPackToStore -Path $Candidate.Root -Digest $Entry.Digest $Status = 'Restored' diff --git a/powershell/public/packs/Update-MtPack.ps1 b/powershell/public/packs/Update-MtPack.ps1 index 6cf0220fd3..f2c5590f9a 100644 --- a/powershell/public/packs/Update-MtPack.ps1 +++ b/powershell/public/packs/Update-MtPack.ps1 @@ -31,6 +31,16 @@ .PARAMETER Force Answer yes to the approval question. + .PARAMETER Token + A GitHub token that can read the pack's repository, as a SecureString, for a private or internal + repository. It is used for this command only, is sent to api.github.com only, and is not stored. When it + is given, no other sign-in is tried. Without it, Maester uses the first of these that can read the + repository: the sign-in of Connect-MtGitHub in this session, the GitHub CLI (`gh auth token`, when gh is + installed and signed in), then the GH_TOKEN and GITHUB_TOKEN environment variables. An environment + variable can be read by every process and module in the session, including installed packs, so prefer + the other ways outside a pipeline. A fine-grained token needs only read-only Contents access to the + one repository. + .EXAMPLE Update-MtPack @@ -41,6 +51,11 @@ Updates one pack to a given release. + .EXAMPLE + Update-MtPack contoso.private-pack -Token (Get-Secret -Name PackReadToken) + + Updates a pack from a private repository with a token read from a secret vault. + .LINK https://maester.dev/docs/commands/Update-MtPack #> @@ -67,7 +82,10 @@ [switch] $NonInteractive, [Parameter()] - [switch] $Force + [switch] $Force, + + [Parameter()] + [securestring] $Token ) Write-Verbose "Update-MtPack: Id=$($Id -join ', ') Version=$Version" @@ -86,7 +104,7 @@ $source = ($previous.Source -replace '@[^/@]+$', '') if (-not $PSCmdlet.ShouldProcess($previous.Id, 'Update the pack')) { continue } try { - $entry = Invoke-MtPackInstall -Source $source -Version $Version -Lock $lock -Policy $policy -AcceptRisk $AcceptRisk -IncludeRecent:$IncludeRecent -Force:$Force -NonInteractive:$quiet -Previous $previous -SkipUnchanged -Confirm:$false + $entry = Invoke-MtPackInstall -Token $Token -Source $source -Version $Version -Lock $lock -Policy $policy -AcceptRisk $AcceptRisk -IncludeRecent:$IncludeRecent -Force:$Force -NonInteractive:$quiet -Previous $previous -SkipUnchanged -Confirm:$false } catch { Write-Error "The pack $($previous.Id) was not updated: $($_.Exception.Message)" continue diff --git a/powershell/public/run/Get-MtSetting.ps1 b/powershell/public/run/Get-MtSetting.ps1 index 591ad0d87a..88f4ca8410 100644 --- a/powershell/public/run/Get-MtSetting.ps1 +++ b/powershell/public/run/Get-MtSetting.ps1 @@ -4,10 +4,15 @@ Returns a setting from GlobalSettings in the Maester config. .DESCRIPTION - Tests read their tenant-wide settings (for example EmergencyAccessAccounts) through this command. The value comes from GlobalSettings in the run config; when the config does not set it, the default from the settings registry is returned, else the -Default value. + A test that ships with Maester does not call this command for a value it checks against: it declares a + parameter bound to the setting, [MaesterParameter(Setting = 'ParkedDomains')], so the value shows in + Get-MtTest and a TestSettings row can override it. Connect commands, data helpers, packs and custom tests + call it. When a native test is running, the name of each setting read is recorded on that test's result + (SettingsRead), so the result shows every setting the test depended on. + .PARAMETER Name The name of the setting, for example EmergencyAccessAccounts. Test packs can use Namespace.Key names. @@ -35,20 +40,26 @@ [object] $Default ) + $registry = (Get-MtSettingRegistry).Settings + + # Record the read on the native test that is running, so its result names every setting it depended on. + $currentTest = [Maester.Engine.MtSession]::GetCurrentTest() + if ($currentTest -and $__MtSession) { + if (-not $__MtSession.SettingRead) { $__MtSession.SettingRead = @{} } + if (-not $__MtSession.SettingRead.ContainsKey($currentTest)) { $__MtSession.SettingRead[$currentTest] = [System.Collections.Generic.List[string]]::new() } + if ($Name -notin $__MtSession.SettingRead[$currentTest]) { $__MtSession.SettingRead[$currentTest].Add($Name) } + } + $globalSettings = if ($__MtSession -and $__MtSession.MaesterConfig -and $__MtSession.MaesterConfig.PSObject.Properties['GlobalSettings']) { $__MtSession.MaesterConfig.GlobalSettings } else { $null } if ($globalSettings -and $globalSettings.PSObject.Properties[$Name]) { $value = $globalSettings.$Name - Write-Verbose "Maester setting `"$Name`": $($value | ConvertTo-Json -Depth 5 -Compress)" + $shown = if ($registry.ContainsKey($Name) -and $registry[$Name].Sensitive) { '[redacted]' } else { $value | ConvertTo-Json -Depth 5 -Compress } + Write-Verbose "Maester setting `"$Name`": $shown" return $value } - if (-not $script:__MtSettingsRegistry) { - $script:__MtSettingsRegistry = Import-PowerShellDataFile -Path (Join-Path $ExecutionContext.SessionState.Module.ModuleBase 'assets/MaesterSettings.psd1') - } - foreach ($key in $script:__MtSettingsRegistry.Settings.Keys) { - if ($key -eq $Name) { - # Arrays are returned with the comma operator so an empty default stays an empty array. - return , $script:__MtSettingsRegistry.Settings[$key].Default - } + if ($registry.ContainsKey($Name) -and $null -ne $registry[$Name].Default) { + # Arrays are returned with the comma operator so an empty default stays an empty array. + return , $registry[$Name].Default } $Default } diff --git a/powershell/public/run/Invoke-Maester.ps1 b/powershell/public/run/Invoke-Maester.ps1 index 357fa7d1f9..dc2612d80f 100644 --- a/powershell/public/run/Invoke-Maester.ps1 +++ b/powershell/public/run/Invoke-Maester.ps1 @@ -4,9 +4,7 @@ This is the main Maester command that runs the tests and generates a report of the results. .DESCRIPTION - Using Invoke-Maester is the easiest way to run the Pester tests and generate a report of the results. - - For more advanced configuration, you can directly use the Pester module and the Get-MtHtmlReport function. + Invoke-Maester runs the tests against the services you connected to with Connect-Maester and writes a report of the results. By default, Invoke-Maester runs the tests that ship with Maester and the custom tests in the Custom folder of the current directory, except Active Directory tests, preview tests and long-running tests. With -Path, native custom tests (`Test.*.ps1`) are found anywhere under the path and Pester-format custom tests (`*.Tests.ps1`) only in a Custom folder. Folders are searched up to three levels deep. Active Directory tests run only after an explicit Connect-Maester -Service ActiveDirectory call succeeds. @@ -21,7 +19,7 @@ Include tests that can take a long time to run in tenants with a large number of objects. .PARAMETER IncludePreview - Include tests that are still being tested or are dependent on preview APIs. + Include preview tests: new tests that are left out of a default run while they are tried out and feedback on them is gathered. .PARAMETER NoLogo Do not show the Maester logo. @@ -35,84 +33,82 @@ .EXAMPLE Invoke-Maester - Runs the built-in tests and the custom tests in the ./Custom folder (except for Active Directory tests, preview tests and long-running tests) and generates a report of the results in the ./test-results folder. + Runs the tests that ship with Maester and the custom tests in the ./Custom folder, except Active Directory tests, preview tests and long-running tests. Writes the report to the ./test-results folder and opens it in the browser. .EXAMPLE - Invoke-Maester ./maester + Invoke-Maester -TestId MT.1005 - Runs the built-in tests and the custom tests and maester-config.json in the folder ./maester (except for Active Directory tests, preview tests and long-running tests) and generates a report of the results in the default ./test-results folder. + Runs one test. A test named by its exact ID runs even if it is a preview or long-running test. .EXAMPLE - Invoke-Maester -Tag 'CA' -IncludeLongRunning + Invoke-Maester -TestId 'MT.1005', 'CISA.MS.AAD.3.*' - Runs the tests with the tag "CA" and includes long-running tests. Generates a report of the results in the default ./test-results folder. + Runs test MT.1005 and the tests whose ID starts with CISA.MS.AAD.3. IDs are not case-sensitive and '*' is a wildcard. .EXAMPLE - Invoke-Maester -Tag 'CA', 'App' -IncludePreview + Invoke-Maester -ExcludeTestId 'MT.1024.*', 'CIS.M365.1.1.1' - Runs the tests with the tags 'CA' and 'App' and includes preview tests. Generates a report of the results in the default ./test-results folder. + Runs everything a default run does, except the tests with these IDs. -ExcludeTestId wins over -TestId. .EXAMPLE - Invoke-Maester -Product entra -Severity Critical, High + Invoke-Maester -Product entra - Runs the Entra ID tests whose severity is Critical or High. Values of one selector are alternatives; different selectors must all match. + Runs the Microsoft Entra tests: every test whose Product or RelatedProduct is entra. .EXAMPLE - Invoke-Maester -ExcludeProduct exchange + Invoke-Maester -Product entra, exchange -Severity Critical, High - Runs the tests that ship with Maester and the custom tests, except the tests about Exchange Online (a test whose Product or RelatedProduct is exchange). Pester-format custom tests have no product and still run. + Runs the Entra and Exchange Online tests whose severity is Critical or High. The values of one selector are alternatives; different selectors must all match. .EXAMPLE - Invoke-Maester -Suite cisa -Area authentication + Invoke-Maester -ExcludeProduct exchange, teams - Runs the tests of the CISA suite that are about authentication. -Product, -Feature, -Area, -Severity and -Suite select by the typed attributes of the tests and combine with -Tag and -TestId. + Runs everything a default run does, except the tests about Exchange Online and Teams. -ExcludeProduct wins over every selector. Pester-format custom tests have no product and still run. .EXAMPLE - Invoke-Maester -OutputFolder './my-test-results' + Invoke-Maester -Suite cisa -Area authentication - Runs tests and generates a report of the results in the ./my-test-results folder. + Runs the tests of the CISA suite that are about authentication. .EXAMPLE - Invoke-Maester -OutputHtmlFile './test-results/TestResults.html' + Invoke-Maester -Feature conditional-access - Runs the tests and generates a report of the results in the specified file. + Runs the tests about one feature of a product, here Conditional Access. .EXAMPLE - Invoke-Maester -Path ./maester/Custom -SkipBuiltIn + Invoke-Maester -IncludeLongRunning -IncludePreview - Runs only the custom tests in the ./maester/Custom folder. + Adds the long-running tests and the preview tests to the run. .EXAMPLE - Invoke-Maester -MailRecipient john@contoso.com + Invoke-Maester -Product entra -DryRun -PassThru - Runs the tests and sends a report of the results to an email recipient. + Shows what would run, and why every other test would not, without running any test. Each test that would have run is reported as NotRun with reason DryRun. Native tests are only read; Pester-format custom tests still go through Pester discovery, which runs their BeforeDiscovery and Describe-level code. .EXAMPLE - Invoke-Maester -TeamId '00000000-0000-0000-0000-000000000000' -TeamChannelId '19%3A00000000000000000000000000000000%40thread.tacv2' + Invoke-Maester ./maester - Runs the tests and posts a summary of the results to a Teams channel. + Runs the tests that ship with Maester and the custom tests in the ./maester folder, with the maester-config.json found there. .EXAMPLE - Invoke-Maester -TeamChannelWebhookUri 'https://some-url.logic.azure.com/workflows/invoke?api-version=2016-06-01' + Invoke-Maester -Path ./maester/Custom -SkipBuiltIn - Runs the tests and posts a summary of the results to a Teams channel. + Runs only the custom tests in the ./maester/Custom folder. .EXAMPLE - Invoke-Maester -Verbosity Normal + Invoke-Maester -Pack ZTA - Shows results of tests as they are run, including details on failed tests. + Runs the tests that ship with Maester and the Zero Trust Assessment pack, including its long-running test, even though the pack is off by default. Other installed packs do not run. .EXAMPLE - ```powershell - $configuration = New-PesterConfiguration - $configuration.Run.Path = './tests/Custom' - $configuration.Filter.Tag = 'CA' - $configuration.Filter.ExcludeTag = 'App' + Invoke-Maester -Pack ZTA -SkipBuiltIn - Invoke-Maester -PesterConfiguration $configuration - ``` + Runs only the Zero Trust Assessment pack. - Runs the built-in tests and the custom tests in the ./tests/Custom folder that include the 'CA' tag and exclude the 'App' tag. + .EXAMPLE + Invoke-Maester -AllPacks + + Runs the tests that ship with Maester and every installed pack. Without -Pack or -AllPacks, installed packs do not run. .EXAMPLE ```powershell @@ -131,29 +127,49 @@ Explicitly connect to Active Directory, then run the Active Directory tests. They do not use Microsoft Graph, so no Graph connection is needed. .EXAMPLE - Invoke-Maester -Pack ZTA + Invoke-Maester -OutputFolder ./my-test-results - Runs the tests that ship with Maester and the Zero Trust Assessment pack, including its long-running test, even though the pack is off by default. Other installed packs do not run. + Runs the tests and writes the html, markdown and json reports to the ./my-test-results folder. .EXAMPLE - Invoke-Maester -Pack ZTA -SkipBuiltIn + Invoke-Maester -OutputHtmlFile ./test-results/TestResults.html - Runs only the Zero Trust Assessment pack. + Runs the tests and writes only the html report, to the file named. .EXAMPLE - Invoke-Maester -AllPacks + Invoke-Maester -NonInteractive -OutputFolder ./test-results - Runs the tests that ship with Maester and every installed pack. Without -Pack or -AllPacks, installed packs do not run. + Runs unattended, for a scheduled task or a pipeline: no logo, no dashboard, no run summary, and the report is not opened in the browser. .EXAMPLE - Invoke-Maester -TestId 'MT.1005', 'CISA.MS.AAD.3.*' + Invoke-Maester -OutputMode Stream - Runs only test MT.1005 and the tests whose ID starts with CISA.MS.AAD.3. A test named by its exact ID runs even if it is a preview or long-running test. + Writes the console output as lines instead of the full-screen dashboard. This is what a pipeline or redirected output gets without asking; Plain also leaves out colour and symbols. .EXAMPLE - Invoke-Maester -ExcludeTestId 'MT.1024.*' -DryRun -PassThru + Invoke-Maester -Verbosity Normal - Shows what would run, and why every other test would not, without running any test. Each test that would have run is reported as NotRun with reason DryRun. Native tests are only read; Pester-format custom tests still go through Pester discovery, which runs their BeforeDiscovery and Describe-level code. + Writes one line for each finished test, and keeps a two-line status at the bottom of the console instead of the dashboard. + + .EXAMPLE + $results = Invoke-Maester -PassThru -NonInteractive + + Returns the results as an object, for a script that goes on to read $results.FailedCount or $results.Tests. + + .EXAMPLE + Invoke-Maester -MailRecipient john@contoso.com + + Runs the tests and sends a report of the results to an email recipient. + + .EXAMPLE + Invoke-Maester -TeamId '00000000-0000-0000-0000-000000000000' -TeamChannelId '19%3A00000000000000000000000000000000%40thread.tacv2' + + Runs the tests and posts a summary of the results to a Teams channel. + + .EXAMPLE + Invoke-Maester -TeamChannelWebhookUri 'https://some-url.logic.azure.com/workflows/invoke?api-version=2016-06-01' + + Runs the tests and posts a summary of the results to a Teams channel. .EXAMPLE Invoke-Maester -Config ./maester-config.json, @{ Selection = @{ DefaultAction = 'Skip' }; TestSettings = @(@{ Id = 'MT.1005'; Enabled = $true }) } @@ -162,6 +178,9 @@ .LINK https://maester.dev/docs/commands/Invoke-Maester + + .LINK + https://maester.dev/docs/configuration/invoke-maester #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWriteHost', '', Justification = 'Colors are beautiful')] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '', Justification = 'Incorrectly flags ExportCsv and ExportExcel as unused')] @@ -198,7 +217,7 @@ # A severity set for a test in the run configuration is the one that counts. [string[]] $Severity, - # Only run the tests of these suites, for example Maester, CISA, CIS, ASD, EIDSCA, ORCA or AD. '*' wildcards are allowed. + # Only run the tests of these suites, for example Maester, CISA, CIS, ASD, DISA, EIDSCA, ORCA or AD. '*' wildcards are allowed. [string[]] $Suite, # Run these Maester Packs, by pack ID or code, for example ZTA or maester.zero-trust-assessment. @@ -772,6 +791,10 @@ $script:__MtPackSet = @() } + # GlobalSettings is checked once, against the built-in settings and those of the packs in the run, so a + # mistyped key or a wrong value is reported here and not by every test that reads it. + Assert-MtGlobalSetting -RunConfig $runConfig + # Stale copies of 2.x built-in wrappers under the custom root are not run (design section 8). $builtInInventory = $null $customInventory = @() @@ -1017,7 +1040,11 @@ Set-MtConsolePhase 'Results' Write-MtProgress -Activity 'Processing test results' -Status "$(@($pesterResults.Tests).Count + $nativeRows.Count) test(s)" -Force - # Build the Invoke-Maester command string from bound parameters + # Build the Invoke-Maester command string from bound parameters. + # Only strings and value types are written out. Any other object is recorded as its + # type name, because interpolating it calls its own ToString(), and a caller-supplied + # type can use that to place its contents - a connection string, a token - into a + # command string that is then stored in the result and the report. $invokeMaesterCommand = "Invoke-Maester" foreach ($param in $PSBoundParameters.GetEnumerator()) { $paramName = $param.Key @@ -1026,12 +1053,8 @@ if ($paramValue.IsPresent) { $invokeMaesterCommand += " -$paramName" } - } elseif ($paramValue -is [array]) { - $invokeMaesterCommand += " -$paramName @('$($paramValue -join "', '")')" - } elseif ($paramValue -is [string]) { - $invokeMaesterCommand += " -$paramName '$paramValue'" } elseif ($null -ne $paramValue) { - $invokeMaesterCommand += " -$paramName $paramValue" + $invokeMaesterCommand += " -$paramName $(ConvertTo-MtCommandParameterValue -Value $paramValue)" } } diff --git a/powershell/public/run/Invoke-MtTest.ps1 b/powershell/public/run/Invoke-MtTest.ps1 index 5f10fd4923..26875dc2d9 100644 --- a/powershell/public/run/Invoke-MtTest.ps1 +++ b/powershell/public/run/Invoke-MtTest.ps1 @@ -131,6 +131,7 @@ $__MtSession.MaesterConfig = Resolve-MtRunConfig -Path $searchPath -Config $Config -WarningAction SilentlyContinue } $runConfig = $__MtSession.MaesterConfig + if ($ownsConfig) { Assert-MtGlobalSetting -RunConfig $runConfig } $selection = Resolve-MtSelection -RunConfig $runConfig -TestId @($tests | ForEach-Object { $_.Id }) # The caller named the tests: the allow-list and the selectors of the config do not apply. $selection.DefaultAction = 'Run' diff --git a/powershell/public/run/New-MtTest.ps1 b/powershell/public/run/New-MtTest.ps1 index fe86b65386..d27a4a9ee5 100644 --- a/powershell/public/run/New-MtTest.ps1 +++ b/powershell/public/run/New-MtTest.ps1 @@ -46,6 +46,12 @@ .PARAMETER Mitre The MITRE ATT&CK technique IDs the checked control prevents or detects, for example T1110.003, or None. + .PARAMETER Setting + Shared settings the test receives as parameters, for example EmergencyAccessAccounts or ParkedDomains. Each + becomes a parameter bound to the setting with [MaesterParameter(Setting = '...')], with the type, default and + allowed values of the settings registry. An administrator sets the value once under GlobalSettings in + maester-config.json, and the test's TestSettings row can override it. Get-MtSetting -Name completes the names. + .PARAMETER Path The folder to create the files in. Defaults to ./custom (an existing ./Custom folder is reused). @@ -63,6 +69,11 @@ Creates a test with the classification, priority and ATT&CK attributes filled in. The attribute rubric at https://maester.dev/docs/writing-tests/attribute-rubric explains how to choose each value. + .EXAMPLE + New-MtTest -Id CONTOSO.1003 -Title 'Break glass accounts have a passkey' -Setting EmergencyAccessAccounts + + Creates a test with an EmergencyAccessAccounts parameter that the engine fills from the setting of that name. + .LINK https://maester.dev/docs/commands/New-MtTest #> @@ -107,6 +118,9 @@ [ValidatePattern('^(T[0-9]{4}(\.[0-9]{3})?|None)$')] [string[]] $Mitre, + [Parameter()] + [string[]] $Setting, + [Parameter()] [string] $Path = './custom', @@ -146,6 +160,34 @@ Write-Warning "The prefix of '$Id' is reserved for tests shipped with Maester and for Maester Packs. Use your own prefix, for example CONTOSO." } + # One parameter per shared setting, with the type, default and allowed values of the settings registry. + $quoteValue = { param($v) "'" + ([string]$v).Replace("'", "''") + "'" } + $registry = (Get-MtSettingRegistry).Settings + $parameterBlocks = foreach ($name in @($Setting | Where-Object { $_ } | Select-Object -Unique)) { + if (-not $registry.ContainsKey($name)) { + Write-Error "'$name' is not a registered setting. The settings are listed at https://maester.dev/docs/configuration/run-configuration#globalsettings. Add a parameter for a setting of your own by hand: [MaesterParameter(Setting = 'Contoso.Key')]." + return + } + $entry = $registry[$name] + $registeredName = @($registry.Keys | Where-Object { $_ -eq $name })[0] + if ($entry.Type -eq 'object' -or ($entry.ContainsKey('Role') -and $entry.Role -eq 'Connection')) { + Write-Error "'$registeredName' is a connection setting, which a test does not receive as a parameter." + return + } + $default = switch ($entry.Type) { + 'int' { [string][int]$entry.Default } + 'bool' { if ($entry.Default) { '$true' } else { '$false' } } + 'string' { & $quoteValue $entry.Default } + 'string[]' { '@(' + ((@($entry.Default) | Where-Object { $null -ne $_ } | ForEach-Object { & $quoteValue $_ }) -join ', ') + ')' } + default { '@()' } + } + $lines = @(" # $($entry.Description)", " [MaesterParameter(Setting = '$registeredName')]") + if ($entry.ContainsKey('AllowedValues') -and $entry.AllowedValues) { $lines += " [ValidateSet($((@($entry.AllowedValues) | ForEach-Object { & $quoteValue $_ }) -join ', '))]" } + $lines += " [$($entry.Type)] `$$(@($registeredName -split '\.')[-1]) = $default" + $lines -join "`n" + } + $paramBlock = if (@($parameterBlocks).Count -gt 0) { "param(`n" + (@($parameterBlocks) -join ",`n`n") + "`n )" } else { 'param()' } + $functionName = 'Test-' + (($Id -split '[.\-_]' | Where-Object { $_ } | ForEach-Object { $_.Substring(0, 1).ToUpperInvariant() + $_.Substring(1) }) -join '') # The attribute, in the order of the design: identity, classification, priority, mappings, applicability. $quote = { param($v) "'" + ([string]$v).Replace("'", "''") + "'" } @@ -174,7 +216,7 @@ $attributeLines )] [CmdletBinding()] [OutputType([bool])] - param() + $paramBlock # Read the tenant state. The engine has already checked that the services above are connected, # and turns an uncaught error into an Error result, so no connection check or try/catch is needed. diff --git a/powershell/tests/fixtures/golden/selection.json b/powershell/tests/fixtures/golden/selection.json index ce3cdde573..ae970e7cfd 100644 --- a/powershell/tests/fixtures/golden/selection.json +++ b/powershell/tests/fixtures/golden/selection.json @@ -21,7 +21,7 @@ "AD" ] }, - "SelectedCount": 572, + "SelectedCount": 582, "SelectedFamilies": [ "MT.1024", "MT.1059", @@ -314,6 +314,16 @@ "CISA.MS.SHAREPOINT.3.1", "CISA.MS.SHAREPOINT.3.2", "CISA.MS.SHAREPOINT.3.3", + "DISA.V-267314", + "DISA.V-267334", + "DISA.V-267341", + "DISA.V-270208", + "DISA.V-270227", + "DISA.V-270233", + "DISA.V-270335", + "DISA.V-270475", + "DISA.V-273868", + "DISA.V-285327", "EIDSCA.AF01", "EIDSCA.AF02", "EIDSCA.AF03", @@ -761,7 +771,7 @@ "AD" ] }, - "SelectedCount": 528, + "SelectedCount": 538, "SelectedFamilies": [ "MT.1024", "MT.1059", @@ -1054,6 +1064,16 @@ "CISA.MS.SHAREPOINT.3.1", "CISA.MS.SHAREPOINT.3.2", "CISA.MS.SHAREPOINT.3.3", + "DISA.V-267314", + "DISA.V-267334", + "DISA.V-267341", + "DISA.V-270208", + "DISA.V-270227", + "DISA.V-270233", + "DISA.V-270335", + "DISA.V-270475", + "DISA.V-273868", + "DISA.V-285327", "EIDSCA.AP12", "EIDSCA.AP15", "EIDSCA.CR05", @@ -1310,7 +1330,7 @@ "AD" ] }, - "SelectedCount": 588, + "SelectedCount": 598, "SelectedFamilies": [ "MT.1024", "MT.1033", @@ -1606,6 +1626,16 @@ "CISA.MS.SHAREPOINT.3.1", "CISA.MS.SHAREPOINT.3.2", "CISA.MS.SHAREPOINT.3.3", + "DISA.V-267314", + "DISA.V-267334", + "DISA.V-267341", + "DISA.V-270208", + "DISA.V-270227", + "DISA.V-270233", + "DISA.V-270335", + "DISA.V-270475", + "DISA.V-273868", + "DISA.V-285327", "EIDSCA.AF01", "EIDSCA.AF02", "EIDSCA.AF03", @@ -1921,7 +1951,7 @@ "AD" ] }, - "SelectedCount": 590, + "SelectedCount": 609, "SelectedFamilies": [ "MT.1024", "MT.1059", @@ -2215,6 +2245,25 @@ "CISA.MS.SHAREPOINT.3.1", "CISA.MS.SHAREPOINT.3.2", "CISA.MS.SHAREPOINT.3.3", + "DISA.V-267303", + "DISA.V-267309", + "DISA.V-267314", + "DISA.V-267334", + "DISA.V-267341", + "DISA.V-267355", + "DISA.V-270200", + "DISA.V-270204", + "DISA.V-270208", + "DISA.V-270209", + "DISA.V-270227", + "DISA.V-270233", + "DISA.V-270239", + "DISA.V-270255", + "DISA.V-270335", + "DISA.V-270475", + "DISA.V-273867", + "DISA.V-273868", + "DISA.V-285327", "EIDSCA.AF01", "EIDSCA.AF02", "EIDSCA.AF03", @@ -2532,7 +2581,7 @@ "AD" ] }, - "SelectedCount": 620, + "SelectedCount": 639, "SelectedFamilies": [ "MT.1024", "MT.1033", @@ -2829,6 +2878,25 @@ "CISA.MS.SHAREPOINT.3.1", "CISA.MS.SHAREPOINT.3.2", "CISA.MS.SHAREPOINT.3.3", + "DISA.V-267303", + "DISA.V-267309", + "DISA.V-267314", + "DISA.V-267334", + "DISA.V-267341", + "DISA.V-267355", + "DISA.V-270200", + "DISA.V-270204", + "DISA.V-270208", + "DISA.V-270209", + "DISA.V-270227", + "DISA.V-270233", + "DISA.V-270239", + "DISA.V-270255", + "DISA.V-270335", + "DISA.V-270475", + "DISA.V-273867", + "DISA.V-273868", + "DISA.V-285327", "EIDSCA.AF01", "EIDSCA.AF02", "EIDSCA.AF03", @@ -3373,7 +3441,7 @@ "AD" ] }, - "SelectedCount": 528, + "SelectedCount": 538, "SelectedFamilies": [ "MT.1024", "MT.1059", @@ -3666,6 +3734,16 @@ "CISA.MS.SHAREPOINT.3.1", "CISA.MS.SHAREPOINT.3.2", "CISA.MS.SHAREPOINT.3.3", + "DISA.V-267314", + "DISA.V-267334", + "DISA.V-267341", + "DISA.V-270208", + "DISA.V-270227", + "DISA.V-270233", + "DISA.V-270335", + "DISA.V-270475", + "DISA.V-273868", + "DISA.V-285327", "EIDSCA.AP12", "EIDSCA.AP15", "EIDSCA.CR05", @@ -3928,7 +4006,7 @@ "AD" ] }, - "SelectedCount": 576, + "SelectedCount": 595, "SelectedFamilies": [ "MT.1024", "MT.1033", @@ -4225,6 +4303,25 @@ "CISA.MS.SHAREPOINT.3.1", "CISA.MS.SHAREPOINT.3.2", "CISA.MS.SHAREPOINT.3.3", + "DISA.V-267303", + "DISA.V-267309", + "DISA.V-267314", + "DISA.V-267334", + "DISA.V-267341", + "DISA.V-267355", + "DISA.V-270200", + "DISA.V-270204", + "DISA.V-270208", + "DISA.V-270209", + "DISA.V-270227", + "DISA.V-270233", + "DISA.V-270239", + "DISA.V-270255", + "DISA.V-270335", + "DISA.V-270475", + "DISA.V-273867", + "DISA.V-273868", + "DISA.V-285327", "EIDSCA.AP12", "EIDSCA.AP15", "EIDSCA.CR05", diff --git a/powershell/tests/functions/ADCertificateInventoryBatch.Tests.ps1 b/powershell/tests/functions/ADCertificateInventoryBatch.Tests.ps1 index 4093fc2b03..62c6b3da85 100644 --- a/powershell/tests/functions/ADCertificateInventoryBatch.Tests.ps1 +++ b/powershell/tests/functions/ADCertificateInventoryBatch.Tests.ps1 @@ -26,6 +26,54 @@ Describe 'AD configuration inventory batch' { { Get-MtAdCertificateInventory -Configuration $config } | Should -Throw '*Unable to parse public certificate*' } + Context 'LDAP binary projection in the inventory' -ForEach @( + @{ Property = 'EnterpriseCAs'; Role = 'Enterprise CA' } + @{ Property = 'TrustedRootCAs'; Role = 'Trusted root' } + @{ Property = 'IntermediateCAs'; Role = 'Intermediate' } + @{ Property = 'NtAuthCertificates'; Role = 'NTAuth' } + ) { + BeforeEach { + $script:projectionConfiguration = [pscustomobject]@{ + EnterpriseCAs = @(); TrustedRootCAs = @(); IntermediateCAs = @(); NtAuthCertificates = @() + } + } + + It 'accepts a single DER value projected as an object array of bytes' { + $script:projectionConfiguration.$Property = @([pscustomobject]@{ Name = 'Projected CA'; cACertificate = [object[]]$script:certBytes }) + $rows = @(Get-MtAdCertificateInventory -Configuration $script:projectionConfiguration) + $rows.Count | Should -Be 1 + $rows[0].Role | Should -Be $Role + $rows[0].Thumbprint | Should -Not -BeNullOrEmpty + $rows[0].PSObject.Properties.Name | Should -Not -Contain RawData + } + + It 'retains multiple projected DER values on one directory object' { + $values = [Collections.Generic.List[object]]::new() + $values.Add([object[]]$script:certBytes) + $values.Add([object[]]$script:certBytes) + $script:projectionConfiguration.$Property = @([pscustomobject]@{ Name = 'Two certificates'; cACertificate = $values.ToArray() }) + $rows = @(Get-MtAdCertificateInventory -Configuration $script:projectionConfiguration) + $rows.Count | Should -Be 2 + @($rows | Where-Object Role -EQ $Role).Count | Should -Be 2 + } + + It 'rejects non-byte content alongside a valid projected certificate' { + $values = [Collections.Generic.List[object]]::new() + $values.Add([object[]]$script:certBytes) + $values.Add(@([byte]1, 'unexpected value')) + $script:projectionConfiguration.$Property = @([pscustomobject]@{ Name = 'Mixed input'; cACertificate = $values.ToArray() }) + { Get-MtAdCertificateInventory -Configuration $script:projectionConfiguration } | Should -Throw '*Unsupported certificate value*' + } + + It 'rejects malformed DER alongside a valid projected certificate' { + $values = [Collections.Generic.List[object]]::new() + $values.Add([object[]]$script:certBytes) + $values.Add([object[]][byte[]](1, 2, 3)) + $script:projectionConfiguration.$Property = @([pscustomobject]@{ Name = 'Malformed input'; cACertificate = $values.ToArray() }) + { Get-MtAdCertificateInventory -Configuration $script:projectionConfiguration } | Should -Throw '*Unable to parse public certificate*' + } + } + It 'distinguishes missing data from a retrieved empty collection' { $state = [pscustomobject]@{ Configuration = [pscustomobject]@{ SiteLinks = @() } } @(Get-MtAdConfigurationInventory -State $state -Required SiteLinks).Count | Should -Be 1 diff --git a/powershell/tests/functions/ADConfigurationChecks.Tests.ps1 b/powershell/tests/functions/ADConfigurationChecks.Tests.ps1 index c74f61c546..c1e1403b37 100644 --- a/powershell/tests/functions/ADConfigurationChecks.Tests.ps1 +++ b/powershell/tests/functions/ADConfigurationChecks.Tests.ps1 @@ -88,6 +88,16 @@ Describe 'AD configuration, forest and optional-feature checks' { { Test-MtAdOptionalFeatureCount } | Should -Throw '*scopes were not collected*' } + It 'keeps multiple optional-feature scopes readable without raw HTML separators' { + $script:state.OptionalFeatures[0].EnabledScopes = @( + 'CN=Partitions,CN=Configuration,DC=example,DC=test' + 'CN=Partitions,CN=Configuration,DC=other,DC=test' + ) + Test-MtAdOptionalFeatureCount | Should -BeTrue + $script:detail | Should -Match 'DC=example,DC=test; CN=Partitions,CN=Configuration,DC=other,DC=test' + $script:detail | Should -Not -Match '
' + } + It 'fails for zero KDS root keys rather than assuming gMSAs are unused' { $script:state.Configuration.KdsRootKeys = @() Test-MtAdKdsRootKeysCount -KeyInventoryReadAccessConfirmed $true | Should -BeFalse diff --git a/powershell/tests/functions/ADSchemaTrustChecks.Tests.ps1 b/powershell/tests/functions/ADSchemaTrustChecks.Tests.ps1 index b9b381e69a..b2af0d4e93 100644 --- a/powershell/tests/functions/ADSchemaTrustChecks.Tests.ps1 +++ b/powershell/tests/functions/ADSchemaTrustChecks.Tests.ps1 @@ -98,7 +98,7 @@ Describe 'Merged AD schema, RootDSE, service-account and trust checks' { It 'reports a missing KRBTGT account as unavailable and respects a configured password-age threshold' { Test-MtAdKrbtgtPasswordLastSet | Should -BeFalse - Test-MtAdKrbtgtPasswordLastSet -MaxPasswordAgeDays 240 | Should -BeTrue + Test-MtAdKrbtgtPasswordLastSet -MaximumPasswordAgeDays 240 | Should -BeTrue $script:state.Users = @() Test-MtAdKrbtgtPasswordLastSet | Should -BeNullOrEmpty Should -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { $SkippedBecause -eq 'Error' } @@ -130,7 +130,7 @@ Describe 'Merged AD schema, RootDSE, service-account and trust checks' { $script:detail.Text | Should -Match 'no stale-trust assertion can be made' $script:detail.Text | Should -Not -Match 'No stale trusts detected' $script:state.Trusts[0] | Add-Member -NotePropertyName LastValidated -NotePropertyValue (Get-Date).AddDays(-90) -Force - Test-MtAdTrustStaleCount -StaleThresholdDays 60 | Should -BeTrue + Test-MtAdTrustStaleCount -MaximumValidationAgeDays 60 | Should -BeTrue $script:detail.Text | Should -Match 'Stale Trusts \(>60 days\) \| 1' $script:detail.Text | Should -Match 'Unknown Validation Status \| 1' $script:detail.Text | Should -Match 'external.example \| Inbound \| Domain Uplevel \| [0-9]{4}-' diff --git a/powershell/tests/functions/ADSiteOuBatch.Tests.ps1 b/powershell/tests/functions/ADSiteOuBatch.Tests.ps1 index ee55590e68..8f3d8c9de5 100644 --- a/powershell/tests/functions/ADSiteOuBatch.Tests.ps1 +++ b/powershell/tests/functions/ADSiteOuBatch.Tests.ps1 @@ -126,6 +126,22 @@ Describe 'AD site, subnet, OU and printer checks with state' -F $script:detail.Text | Should -Match '1 OU\(s\)' } + It 'keeps typed OU modification dates independent of parsing' -ForEach @( + @{ Culture = 'de-DE' } + @{ Culture = 'en-US' } + ) { + $previousCulture = [Globalization.CultureInfo]::CurrentCulture + try { + [Globalization.CultureInfo]::CurrentCulture = [Globalization.CultureInfo]::new($Culture) + $script:state.OrganizationalUnits[0].Modified = [datetime]::new(2010, 11, 17) + Test-MtAdOuStaleCount -MaximumAgeYears 5 | Should -BeTrue + $script:detail.Text | Should -Match '\| 2010-11-17 \|' + $script:detail.Text | Should -Match '1 OU\(s\)' + } finally { + [Globalization.CultureInfo]::CurrentCulture = $previousCulture + } + } + It 'reports printer name, server, location and description for review' { Test-MtAdPrinterTotalCount | Should -BeTrue $script:detail.Investigate | Should -BeTrue diff --git a/powershell/tests/functions/ActiveDirectoryThreshold.Tests.ps1 b/powershell/tests/functions/ActiveDirectoryThreshold.Tests.ps1 index 696a30073d..fda169187d 100644 --- a/powershell/tests/functions/ActiveDirectoryThreshold.Tests.ps1 +++ b/powershell/tests/functions/ActiveDirectoryThreshold.Tests.ps1 @@ -57,7 +57,7 @@ Describe 'Active Directory Threshold Validation' -Tag 'LabOnly', 'ActiveDirector $connectResult.Status | Should -Be 'Connected' # Invoke the test through its supported entrypoint and assert pass outcome - $testResult = Test-MtAdComputerStaleEnabledCount -StaleThresholdDays 180 + $testResult = Test-MtAdComputerStaleEnabledCount -MaximumInactiveDays 180 $testResult | Should -Be $true -Because 'AD-DCOMP-06 should pass when no stale enabled computers exist' # Diagnostic precondition: verify stale count is 0 @@ -90,7 +90,7 @@ Describe 'Active Directory Threshold Validation' -Tag 'LabOnly', 'ActiveDirector $staleCount = ($staleEnabledComputers | Measure-Object).Count # Invoke the test through its supported entrypoint and assert investigate outcome - $testResult = Test-MtAdComputerStaleEnabledCount -StaleThresholdDays 1 + $testResult = Test-MtAdComputerStaleEnabledCount -MaximumInactiveDays 1 $testResult | Should -Be $null -Because 'AD-DCOMP-06 should investigate when stale enabled computers exist' # With a 1-day threshold in a fresh lab, most or all computers appear stale diff --git a/powershell/tests/functions/AsdChecks.Tests.ps1 b/powershell/tests/functions/AsdChecks.Tests.ps1 index 8e61dece4c..ec59d5f770 100644 --- a/powershell/tests/functions/AsdChecks.Tests.ps1 +++ b/powershell/tests/functions/AsdChecks.Tests.ps1 @@ -58,7 +58,7 @@ Describe 'ASD checks and the tests they run' { ) } } Mock Get-MtGroupMember { @([pscustomobject]@{ '@odata.type' = '#microsoft.graph.user'; id = 'u2' }) } Mock Get-MtEmergencyAccessAccount { @([pscustomobject]@{ ObjectId = 'bg' }) } - $r = Get-MtPrivilegedRoleUser -ExcludeEmergencyAccessAccount + $r = Get-MtPrivilegedRoleUser -EmergencyAccessAccounts @([pscustomobject]@{ Id = 'bg' }) @($r.Keys | Sort-Object) | Should -Be @('u1', 'u2') $r['u2'] | Should -Be @('Global Administrator') @((Get-MtPrivilegedRoleUser).Keys | Sort-Object) | Should -Be @('bg', 'u1', 'u2') diff --git a/powershell/tests/functions/Connect-Maester.Tests.ps1 b/powershell/tests/functions/Connect-Maester.Tests.ps1 index abf3780338..950f319473 100644 --- a/powershell/tests/functions/Connect-Maester.Tests.ps1 +++ b/powershell/tests/functions/Connect-Maester.Tests.ps1 @@ -671,25 +671,124 @@ Describe 'Connect-Maester Azure DevOps' { $script:adoOrganization | Should -BeNullOrEmpty } - It 'Clears the previous organization when configuration is ' -ForEach @( - @{ ConfigProblem = 'missing an organization'; ConfigContent = '{"GlobalSettings":{}}' } - @{ ConfigProblem = 'invalid JSON'; ConfigContent = '{invalid' } - ) { - $ConfigContent | Set-Content ./maester-config.json + It 'Clears the previous organization when token acquisition fails' { + InModuleScope Maester { $__MtSession.AzureDevOpsConnectionCache = @{ Organization = 'old-org' } } $script:adoOrganization = 'old-org' - Mock Get-Module -ModuleName Maester { [pscustomobject]@{ Name = 'ADOPS' } } -ParameterFilter { $Name -contains 'ADOPS' } - Mock Invoke-ADOPSRestMethod -ModuleName Maester { @{} } + Mock Get-AzContext -ModuleName Maester { [pscustomobject]@{ Account = @{ Id = 'user' }; Tenant = @{ Id = 'tenant' } } } + Mock Get-AzAccessToken -ModuleName Maester { throw 'token failed' } Mock Disconnect-ADOPS -ModuleName Maester { $script:adoOrganization = $null } Mock Get-ADOPSConnection -ModuleName Maester { if ($script:adoOrganization) { @{ Organization = $script:adoOrganization } } } + # A surviving session must pass the probe so a request failure cannot hide it. + Mock Invoke-ADOPSRestMethod -ModuleName Maester { @{} } - Connect-Maester -Service AzureDevOps -ErrorAction SilentlyContinue + Connect-Maester -Service AzureDevOps -AzureDevOpsOrganization 'new-org' + $row = $script:connectionSummaryRows | Where-Object Service -eq 'Azure DevOps' + $row.Status | Should -Be 'Failed' + $row.Details | Should -Be 'token failed' + Test-MtConnection -Service AzureDevOps | Should -BeFalse + Should -Invoke Connect-ADOPS -ModuleName Maester -Times 0 -Exactly + # A new run clears the probe cache; neither the probe nor ADOPS may recover the old organization. InModuleScope Maester { $__MtSession.AzureDevOpsConnectionCache = $null } Test-MtConnection -Service AzureDevOps | Should -BeFalse + InModuleScope Maester { Get-ADOPSConnection } | Should -BeNullOrEmpty $script:adoOrganization | Should -BeNullOrEmpty + Should -Invoke Disconnect-ADOPS -ModuleName Maester -Times 1 -Exactly + } + + It 'Keeps a verified ADOPS session when the configuration names no organization' { + # No organization means nothing to connect to, so a session from Connect-ADOPS is kept and reported, + # not torn down. Test-MtConnection verifies it first, so the summary names the organization the tests read. + '{"GlobalSettings":{}}' | Set-Content ./maester-config.json + $script:adoOrganization = 'old-org' + Mock Get-Module -ModuleName Maester { [pscustomobject]@{ Name = 'ADOPS' } } -ParameterFilter { $Name -contains 'ADOPS' } + Mock Invoke-ADOPSRestMethod -ModuleName Maester { @{} } + Mock Disconnect-ADOPS -ModuleName Maester { $script:adoOrganization = $null } + Mock Get-ADOPSConnection -ModuleName Maester { + if ($script:adoOrganization) { @{ Organization = $script:adoOrganization } } + } + + Connect-Maester -Service AzureDevOps -WarningVariable adoWarnings -ErrorVariable adoErrors -ErrorAction SilentlyContinue 3>$null + + $adoErrors | Should -BeNullOrEmpty + ($adoWarnings -join "`n") | Should -Match "existing ADOPS session to 'old-org'" + $row = $script:connectionSummaryRows | Where-Object Service -eq 'Azure DevOps' + $row.Status | Should -Be 'Connected' + $row.Details | Should -Be 'old-org (existing ADOPS session; no organization specified)' + Should -Invoke Disconnect-ADOPS -ModuleName Maester -Times 0 -Exactly + Should -Invoke Connect-ADOPS -ModuleName Maester -Times 0 -Exactly + $script:adoOrganization | Should -Be 'old-org' + # The next run resets the probe cache and still finds the same session. + InModuleScope Maester { $__MtSession.AzureDevOpsConnectionCache = $null } + Test-MtConnection -Service AzureDevOps | Should -BeTrue + } + + It 'Reports an invalid configuration file as a failure without disconnecting ADOPS' { + '{invalid' | Set-Content ./maester-config.json + $script:adoOrganization = 'old-org' + Mock Get-Module -ModuleName Maester { [pscustomobject]@{ Name = 'ADOPS' } } -ParameterFilter { $Name -contains 'ADOPS' } + Mock Invoke-ADOPSRestMethod -ModuleName Maester { @{} } + Mock Disconnect-ADOPS -ModuleName Maester { $script:adoOrganization = $null } + Mock Get-ADOPSConnection -ModuleName Maester { + if ($script:adoOrganization) { @{ Organization = $script:adoOrganization } } + } + + Connect-Maester -Service AzureDevOps -ErrorAction SilentlyContinue + + $row = $script:connectionSummaryRows | Where-Object Service -eq 'Azure DevOps' + $row.Status | Should -Be 'Failed' + $row.Details | Should -Match 'not valid JSON' + Should -Invoke Disconnect-ADOPS -ModuleName Maester -Times 0 -Exactly Should -Invoke Connect-ADOPS -ModuleName Maester -Times 0 -Exactly + $script:adoOrganization | Should -Be 'old-org' + } + + It 'Keeps an existing ADOPS session and connects the other services when no organization is given' { + $script:adoOrganization = 'old-org' + Mock Get-Module -ModuleName Maester { [pscustomobject]@{ Name = 'ADOPS' } } -ParameterFilter { $Name -contains 'ADOPS' } + Mock Invoke-ADOPSRestMethod -ModuleName Maester { @{} } + Mock Get-ADOPSConnection -ModuleName Maester { @{ Organization = $script:adoOrganization } } + + Connect-Maester -Service Graph, AzureDevOps -WarningVariable adoWarnings -ErrorVariable adoErrors 3>$null + + $adoErrors | Should -BeNullOrEmpty + ($adoWarnings -join "`n") | Should -Match 'No Azure DevOps organization specified' + ($script:connectionSummaryRows | Where-Object Service -eq 'Azure DevOps').Status | Should -Be 'Connected' + ($script:connectionSummaryRows | Where-Object Service -eq 'Microsoft Graph').Status | Should -Be 'Connected' + Should -Invoke Disconnect-ADOPS -ModuleName Maester -Times 0 -Exactly + Should -Invoke Connect-ADOPS -ModuleName Maester -Times 0 -Exactly + } + + It 'Skips without disconnecting when no organization is given and the persisted ADOPS session no longer works' { + # Get-ADOPSConnection reads ~/.ADOPS/Config.json, which can name an organization whose token is gone. + Mock Get-Module -ModuleName Maester { [pscustomobject]@{ Name = 'ADOPS' } } -ParameterFilter { $Name -contains 'ADOPS' } + Mock Get-ADOPSConnection -ModuleName Maester { @{ Organization = 'stale-org' } } + Mock Invoke-ADOPSRestMethod -ModuleName Maester { throw 'TF400813: The user is not authorized to access this resource.' } + + Connect-Maester -Service AzureDevOps -ErrorVariable adoErrors -ErrorAction SilentlyContinue + + # The probe's own caught exception is also recorded in -ErrorVariable, so look for the one Connect-Maester writes. + @($adoErrors | Where-Object { "$_" -match 'No Azure DevOps organization specified' }).Count | Should -Be 1 + ($script:connectionSummaryRows | Where-Object Service -eq 'Azure DevOps').Status | Should -Be 'Skipped' + Should -Invoke Disconnect-ADOPS -ModuleName Maester -Times 0 -Exactly + Should -Invoke Connect-ADOPS -ModuleName Maester -Times 0 -Exactly + InModuleScope Maester { $__MtSession.AzureDevOpsConnectionCache | Should -Be 'NotConnected' } + } + + It 'Disconnects the previous ADOPS session only when a new sign-in is attempted' { + $script:adoOrganization = 'old-org' + Mock Disconnect-ADOPS -ModuleName Maester { $script:adoOrganization = $null } + Mock Get-ADOPSConnection -ModuleName Maester { + if ($script:adoOrganization) { @{ Organization = $script:adoOrganization } } + } + + Connect-Maester -Service AzureDevOps -AzureDevOpsOrganization 'new-org' + + Should -Invoke Disconnect-ADOPS -ModuleName Maester -Times 1 -Exactly + Should -Invoke Connect-ADOPS -ModuleName Maester -Times 1 -Exactly -ParameterFilter { $Organization -eq 'new-org' } + $script:adoOrganization | Should -BeNullOrEmpty } It 'Reports the actual failure when is unavailable despite ADOPS being installed' -ForEach @( @@ -736,6 +835,7 @@ Describe 'Connect-Maester Azure DevOps' { $adoErrors.Count | Should -Be 1 "$($adoErrors[0])" | Should -Match 'AzureDevOpsOrganization' Should -Invoke Connect-ADOPS -ModuleName Maester -Times 0 -Exactly + Should -Invoke Disconnect-ADOPS -ModuleName Maester -Times 0 -Exactly ($script:connectionSummaryRows | Where-Object Service -eq 'Azure DevOps').Status | Should -Be 'Skipped' } } diff --git a/powershell/tests/functions/ConvertTo-MtCommandParameterValue.Tests.ps1 b/powershell/tests/functions/ConvertTo-MtCommandParameterValue.Tests.ps1 new file mode 100644 index 0000000000..35a51b0f9e --- /dev/null +++ b/powershell/tests/functions/ConvertTo-MtCommandParameterValue.Tests.ps1 @@ -0,0 +1,52 @@ +BeforeAll { + Import-Module $PSScriptRoot/../../Maester.psd1 -Force + . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" + Use-MtModuleFunction -Name ConvertTo-MtCommandParameterValue + + class MtLeakyParameter { + [string] $ConnectionString = 'Server=db;Password=hunter2' + [string] ToString() { return "Config($($this.ConnectionString))" } + } +} + +Describe 'ConvertTo-MtCommandParameterValue' { + It 'Quotes a string' { + ConvertTo-MtCommandParameterValue -Value 'Entra' | Should -BeExactly "'Entra'" + } + + It 'Writes a as it is' -ForEach @( + @{ Kind = 'number'; Value = 42; Expected = '42' } + @{ Kind = 'boolean'; Value = $true; Expected = 'True' } + ) { + ConvertTo-MtCommandParameterValue -Value $Value | Should -BeExactly $Expected + } + + It 'Renders an arbitrary object as its type name, never its ToString()' { + # The recorded command is written to the result file and shown in the report. Interpolating + # an object calls its own ToString(), so a caller-supplied type could place a secret there. + $result = ConvertTo-MtCommandParameterValue -Value ([MtLeakyParameter]::new()) + + $result | Should -BeExactly '' + $result | Should -Not -Match 'hunter2' + $result | Should -Not -Match 'ConnectionString' + } + + It 'Keeps the array form for a string array' { + ConvertTo-MtCommandParameterValue -Value @('Entra', 'Teams') | Should -BeExactly "@('Entra', 'Teams')" + } + + It 'Renders an object inside an array as its type name too' { + $result = ConvertTo-MtCommandParameterValue -Value @('Entra', [MtLeakyParameter]::new()) + + $result | Should -BeExactly "@('Entra', '')" + $result | Should -Not -Match 'hunter2' + } + + It 'Returns an empty string for null' { + ConvertTo-MtCommandParameterValue -Value $null | Should -BeExactly '' + } + + It 'Renders a null element inside an array as an empty string' { + ConvertTo-MtCommandParameterValue -Value @('Entra', $null) | Should -BeExactly "@('Entra', '')" + } +} diff --git a/powershell/tests/functions/DisaChecks.Tests.ps1 b/powershell/tests/functions/DisaChecks.Tests.ps1 new file mode 100644 index 0000000000..cad4a4141a --- /dev/null +++ b/powershell/tests/functions/DisaChecks.Tests.ps1 @@ -0,0 +1,151 @@ +# The DISA STIG checks, the tests their shims run with DISA's values, and the Entra helpers they read through. Graph is mocked. + +BeforeAll { Import-Module "$PSScriptRoot/../../Maester.psd1" -Force -WarningAction SilentlyContinue } + +Describe 'DISA STIG checks' { + It 'The idle session timeout passes at 15 minutes and fails at an hour or when none is set' { + InModuleScope Maester { + Mock Add-MtTestResultDetail {} + $policy = { param($value) @([pscustomobject]@{ displayName = 'Timeout'; definition = @("{`"ActivityBasedTimeoutPolicy`":{`"Version`":1,`"ApplicationPolicies`":[{`"ApplicationId`":`"default`",`"WebSessionIdleTimeout`":`"$value`"}]}}") }) } + Mock Invoke-MtGraphRequest { & $policy '00:15:00' } -ParameterFilter { $RelativeUri -eq 'policies/activityBasedTimeoutPolicies' } + Test-MtDisaIdleSessionTimeout | Should -BeTrue + Test-MtDisaEntraIdleSessionTimeout | Should -BeTrue + Mock Invoke-MtGraphRequest { & $policy '01:00:00' } -ParameterFilter { $RelativeUri -eq 'policies/activityBasedTimeoutPolicies' } + Test-MtDisaIntuneDesktopIdleSessionTimeout | Should -BeFalse + Test-MtDisaIdleSessionTimeout -MaximumIdleTimeoutMinutes 60 | Should -BeTrue + Mock Invoke-MtGraphRequest { @() } -ParameterFilter { $RelativeUri -eq 'policies/activityBasedTimeoutPolicies' } + Test-MtDisaIdleSessionTimeout | Should -BeFalse + } + } + + It 'The lockout shims need a threshold of 3 and a duration of 900 seconds, and CIS 5.2.3.8 still ignores the duration' { + InModuleScope Maester { + Mock Add-MtTestResultDetail {} + $settings = { param($threshold, $duration) @([pscustomobject]@{ templateId = '5cf42378-d67d-4f36-ba46-e8b86229381d'; values = @( + [pscustomobject]@{ name = 'LockoutThreshold'; value = $threshold } + [pscustomobject]@{ name = 'LockoutDurationInSeconds'; value = $duration } + ) }) } + Mock Invoke-MtGraphRequest { & $settings '3' '900' } + Test-MtDisaEntraLockout | Should -BeTrue + Test-MtDisaIntuneDesktopLockout | Should -BeTrue + Mock Invoke-MtGraphRequest { & $settings '3' '60' } + Test-MtDisaEntraLockout | Should -BeFalse + Test-MtCisSmartLockoutThreshold | Should -BeTrue + Mock Invoke-MtGraphRequest { & $settings '5' '900' } + Test-MtDisaEntraLockout | Should -BeFalse + Mock Invoke-MtGraphRequest { @() } + Test-MtDisaEntraLockout | Should -BeFalse -Because 'the defaults are 10 attempts and 60 seconds' + } + } + + It 'The device wipe approval shim needs a deviceWipe or deviceAction policy, and MT.1096 accepts any policy' { + InModuleScope Maester { + Mock Add-MtTestResultDetail {} + Mock Invoke-MtGraphRequest { @([pscustomobject]@{ displayName = 'Scripts'; policyType = 'script' }) } + Test-MtOperationApprovalPolicies | Should -BeTrue + Test-MtDisaIntuneWipeApproval | Should -BeFalse + Mock Invoke-MtGraphRequest { @([pscustomobject]@{ displayName = 'Wipe'; policyType = 'deviceWipe' }) } + Test-MtDisaIntuneWipeApproval | Should -BeTrue + Mock Invoke-MtGraphRequest { @([pscustomobject]@{ displayName = 'Actions'; policyType = 'unknown'; policySet = [pscustomobject]@{ policyType = 'deviceAction' } }) } + Test-MtDisaIntuneWipeApproval | Should -BeTrue + Mock Invoke-MtGraphRequest { @() } + Test-MtOperationApprovalPolicies | Should -BeFalse + } + } + + It 'The log export shim asks for DISA''s eight categories, where CISA 4.1 asks for more' { + InModuleScope Maester { + Mock Add-MtTestResultDetail {} + $disa = 'SignInLogs', 'AuditLogs', 'ServicePrincipalSignInLogs', 'ManagedIdentitySignInLogs', 'UserRiskEvents', 'RiskyUsers', 'RiskyServicePrincipals', 'ServicePrincipalRiskEvents' + $all = $disa + 'NonInteractiveUserSignInLogs', 'MicrosoftGraphActivityLogs' + Mock Invoke-AzRestMethod { + if ($Path -like '*diagnosticSettingsCategories*') { + [pscustomobject]@{ StatusCode = 200; Content = (@{ value = @($all | ForEach-Object { @{ name = $_; properties = @{ categoryType = 'Logs' } } }) } | ConvertTo-Json -Depth 5) } + } else { + [pscustomobject]@{ StatusCode = 200; Content = (@{ value = @(@{ name = 'sentinel'; properties = @{ logs = @($disa | ForEach-Object { @{ category = $_; enabled = $true } }) } }) } | ConvertTo-Json -Depth 6) } + } + } + Test-MtDisaEntraLogExport | Should -BeTrue + Test-MtCisaDiagnosticSettings | Should -BeFalse + } + } + + It 'The sign-in banner passes with the full or the short banner and fails without branding' { + InModuleScope Maester { + Mock Add-MtTestResultDetail {} + Mock Invoke-MtGraphRequest { @([pscustomobject]@{ id = 'org1' }) } -ParameterFilter { $RelativeUri -eq 'organization' } + Mock Invoke-MtGraphRequest { [pscustomobject]@{ signInPageText = "You are accessing a U.S. Government (USG) Information System (IS) that is provided`nfor USG-authorized use only. By using this IS..." } } -ParameterFilter { $RelativeUri -eq 'organization/org1/branding' } + Test-MtDisaSignInBanner | Should -BeTrue + Mock Invoke-MtGraphRequest { [pscustomobject]@{ signInPageText = "I've read & consent to terms in IS user agreem't." } } -ParameterFilter { $RelativeUri -eq 'organization/org1/branding' } + Test-MtDisaSignInBanner | Should -BeTrue + Mock Invoke-MtGraphRequest { [pscustomobject]@{ signInPageText = 'Welcome to Contoso' } } -ParameterFilter { $RelativeUri -eq 'organization/org1/branding' } + Test-MtDisaSignInBanner | Should -BeFalse + Test-MtDisaSignInBanner -AcceptedBannerTexts 'welcome to CONTOSO' | Should -BeTrue + Mock Invoke-MtGraphRequest { throw 'Response status code does not indicate success: NotFound (Not Found).' } -ParameterFilter { $RelativeUri -eq 'organization/org1/branding' } + Test-MtDisaSignInBanner | Should -BeFalse + } + } + + It 'The password lifetime fails a domain that never expires or exceeds the maximum, and asks for review when none is stored' { + InModuleScope Maester { + $script:details = @() + Mock Add-MtTestResultDetail { $script:details += [pscustomobject]@{ Investigate = [bool]$Investigate } } + $domain = { param($id, $days, $type = 'Managed', $verified = $true) [pscustomobject]@{ id = $id; authenticationType = $type; isVerified = $verified; passwordValidityPeriodInDays = $days } } + Mock Invoke-MtGraphRequest { @((& $domain 'a.mil' 90), (& $domain 'fed.mil' 2147483647 'Federated')) } + Test-MtDisaPasswordLifetime | Should -BeTrue + Test-MtDisaIntuneDesktopPasswordLifetime | Should -BeFalse -Because 'the Intune STIG allows 60 days' + Test-MtCisPasswordExpiry | Should -BeFalse -Because 'CIS asks that passwords never expire' + Mock Invoke-MtGraphRequest { @((& $domain 'a.mil' 2147483647)) } + Test-MtDisaPasswordLifetime | Should -BeFalse + Test-MtCisPasswordExpiry | Should -BeTrue + $script:details = @() + Mock Invoke-MtGraphRequest { @((& $domain 'a.mil' $null)) } + Test-MtDisaPasswordLifetime | Should -BeTrue + $script:details[-1].Investigate | Should -BeTrue + Test-MtCisPasswordExpiry | Should -BeTrue + } + } + + It 'The role activation alert fails a role with no additional recipient, or without a required one' { + InModuleScope Maester { + Mock Add-MtTestResultDetail {} + Mock Get-MtDirectoryRoleAssignment { [pscustomobject]@{ Assignments = @( + [pscustomobject]@{ roleDefinitionId = 'r1'; AssignmentType = 'Active' } + [pscustomobject]@{ roleDefinitionId = 'r2'; AssignmentType = 'Eligible' } + ); EligibleChecked = $true } } + Mock Invoke-MtGraphRequest { @([pscustomobject]@{ id = 'r1'; displayName = 'Role one' }, [pscustomobject]@{ id = 'r2'; displayName = 'Role two' }) } -ParameterFilter { $RelativeUri -eq 'roleManagement/directory/roleDefinitions' } + $policy = { param($recipients) [pscustomobject]@{ policy = [pscustomobject]@{ rules = @([pscustomobject]@{ id = 'Notification_Admin_EndUser_Assignment'; notificationRecipients = $recipients }) } } } + Mock Invoke-MtGraphRequest { & $policy @('isso@contoso.mil', 'sa@contoso.mil') } -ParameterFilter { $RelativeUri -eq 'policies/roleManagementPolicyAssignments' } + Test-MtDisaRoleActivationNotification | Should -BeTrue + Test-MtDisaRoleActivationNotification -RequiredRecipients 'sa@contoso.mil', 'isso@contoso.mil' | Should -BeTrue + Test-MtDisaRoleActivationNotification -RequiredRecipients 'soc@contoso.mil' | Should -BeFalse + Mock Invoke-MtGraphRequest { & $policy @() } -ParameterFilter { $RelativeUri -eq 'policies/roleManagementPolicyAssignments' } + Test-MtDisaRoleActivationNotification | Should -BeFalse + Get-MtRoleActivationNotificationRecipient -RoleDefinitionId 'r1' | Should -BeNullOrEmpty + } + } + + It 'Inactive accounts follow the interactive sign-in and the creation date of accounts that never signed in' { + InModuleScope Maester { + Mock Add-MtTestResultDetail {} + $now = [datetime]::UtcNow + $user = { param($upn, $lastSignIn, $nonInteractive, $created) [pscustomobject]@{ id = $upn; userPrincipalName = $upn; userType = 'Member'; accountEnabled = $true; createdDateTime = $created.ToString('o'); signInActivity = [pscustomobject]@{ lastSignInDateTime = $lastSignIn; lastNonInteractiveSignInDateTime = $nonInteractive } } } + Mock Invoke-MtGraphRequest { @((& $user 'a@contoso.mil' $now.AddDays(-5).ToString('o') $null $now.AddDays(-400)), (& $user 'new@contoso.mil' $null $null $now.AddDays(-2))) } + Test-MtDisaInactiveAccount | Should -BeTrue + Mock Invoke-MtGraphRequest { @((& $user 'b@contoso.mil' $now.AddDays(-40).ToString('o') $now.AddDays(-1).ToString('o') $now.AddDays(-400))) } + Test-MtDisaInactiveAccount | Should -BeFalse -Because 'the STIG audit reads the interactive sign-in only' + Test-MtDisaIntuneDesktopInactiveAccount -MaximumInactiveDays 45 | Should -BeTrue + Mock Invoke-MtGraphRequest { @((& $user 'c@contoso.mil' $null $null $now.AddDays(-100))) } + Test-MtDisaInactiveAccount | Should -BeFalse + } + } + + It 'Get-MtUserLastSignIn returns the latest sign-in in UTC, or nothing' { + InModuleScope Maester { + $u = [pscustomobject]@{ signInActivity = [pscustomobject]@{ lastSignInDateTime = '2026-01-01T00:00:00Z'; lastNonInteractiveSignInDateTime = '2026-02-01T00:00:00Z' } } + (Get-MtUserLastSignIn -User $u).Month | Should -Be 2 + (Get-MtUserLastSignIn -User $u -InteractiveOnly).Month | Should -Be 1 + Get-MtUserLastSignIn -User ([pscustomobject]@{ signInActivity = $null }) | Should -BeNullOrEmpty + } + } +} diff --git a/powershell/tests/functions/Invoke-MtPackGitHubRequest.Tests.ps1 b/powershell/tests/functions/Invoke-MtPackGitHubRequest.Tests.ps1 new file mode 100644 index 0000000000..edba6469da --- /dev/null +++ b/powershell/tests/functions/Invoke-MtPackGitHubRequest.Tests.ps1 @@ -0,0 +1,316 @@ +BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force + + $script:savedGhToken = $env:GH_TOKEN + $script:savedGitHubToken = $env:GITHUB_TOKEN +} + +AfterAll { + $env:GH_TOKEN = $script:savedGhToken + $env:GITHUB_TOKEN = $script:savedGitHubToken + InModuleScope Maester { + $__MtSession.GitHubConnection = $null + $__MtSession.GitHubAuthHeader = $null + $script:__MtPackGitHubTokenSource = $null + } +} + +Describe 'Pack GitHub token: where the token comes from' { + BeforeEach { + $env:GH_TOKEN = $null + $env:GITHUB_TOKEN = $null + InModuleScope Maester { + $__MtSession.GitHubConnection = $null + $__MtSession.GitHubAuthHeader = $null + $script:__MtPackGitHubTokenSource = $null + $script:calls = [System.Collections.Generic.List[object]]::new() + # Tokens GitHub answers 404 for, as it does for a private repository a token cannot read. + $script:cannotRead = @() + $script:anonymousCanRead = $false + + function script:Set-TestGitHubSession { + param([string] $Token = 'session-token', [string] $ApiBaseUri = 'https://api.github.com', $ExpiresAt) + $__MtSession.GitHubAuthHeader = @{ Authorization = "Bearer $Token"; Accept = 'application/vnd.github+json' } + $__MtSession.GitHubConnection = [pscustomobject]@{ Connected = $true; ApiBaseUri = $ApiBaseUri; TokenExpiresAt = $ExpiresAt } + } + + Mock Get-MtGitHubCliToken { $null } + Mock Invoke-RestMethod { + $sent = if ($Headers.ContainsKey('Authorization')) { $Headers['Authorization'] -replace '^Bearer ' } else { $null } + $script:calls.Add([pscustomobject]@{ Uri = [string]$Uri; Token = $sent }) + $refused = if ($sent) { $sent -in $script:cannotRead } else { -not $script:anonymousCanRead } + if ($refused) { + $response = [System.Net.Http.HttpResponseMessage]::new([System.Net.HttpStatusCode]::NotFound) + throw [Microsoft.PowerShell.Commands.HttpResponseException]::new('Not Found', $response) + } + [pscustomobject]@{ full_name = 'contoso/pack' } + } + } + } + + It 'uses -Token before everything else, and nothing else with it' { + $env:GH_TOKEN = 'env-gh' + $env:GITHUB_TOKEN = 'env-github' + InModuleScope Maester { + Set-TestGitHubSession + Mock Get-MtGitHubCliToken { 'cli-token' } + $used = $false + $token = [System.Net.NetworkCredential]::new('', 'parameter-token').SecurePassword + + $null = Invoke-MtPackGitHubRequest -Path 'repos/contoso/pack' -Token $token -UsedToken ([ref] $used) + + $used | Should -BeTrue + $script:calls.Token | Should -Be @('parameter-token') + Should -Invoke Get-MtGitHubCliToken -Times 0 + } + } + + It 'does not fall back to another sign-in when -Token cannot read the repository' { + $env:GH_TOKEN = 'env-gh' + InModuleScope Maester { + Set-TestGitHubSession + Mock Get-MtGitHubCliToken { 'cli-token' } + $script:cannotRead = @('parameter-token') + $token = [System.Net.NetworkCredential]::new('', 'parameter-token').SecurePassword + + { Invoke-MtPackGitHubRequest -Path 'repos/contoso/pack' -Token $token } | Should -Throw '*404*-Token*' + + $script:calls.Token | Should -Be @('parameter-token') + } + } + + It 'uses the Connect-MtGitHub sign-in before the GitHub CLI and the environment' { + $env:GH_TOKEN = 'env-gh' + $env:GITHUB_TOKEN = 'env-github' + InModuleScope Maester { + Set-TestGitHubSession + Mock Get-MtGitHubCliToken { 'cli-token' } + + $null = Invoke-MtPackGitHubRequest -Path 'repos/contoso/pack' + + $script:calls.Token | Should -Be @('session-token') + Should -Invoke Get-MtGitHubCliToken -Times 0 + } + } + + It 'uses the GitHub CLI before the environment when the session has no sign-in' { + $env:GH_TOKEN = 'env-gh' + $env:GITHUB_TOKEN = 'env-github' + InModuleScope Maester { + Mock Get-MtGitHubCliToken { 'cli-token' } + + $null = Invoke-MtPackGitHubRequest -Path 'repos/contoso/pack' + + $script:calls.Token | Should -Be @('cli-token') + } + } + + It 'uses GH_TOKEN before GITHUB_TOKEN' { + $env:GH_TOKEN = 'env-gh' + $env:GITHUB_TOKEN = 'env-github' + InModuleScope Maester { + $null = Invoke-MtPackGitHubRequest -Path 'repos/contoso/pack' + $script:calls.Token | Should -Be @('env-gh') + } + } + + It 'uses GITHUB_TOKEN last' { + $env:GITHUB_TOKEN = 'env-github' + InModuleScope Maester { + $used = $false + $null = Invoke-MtPackGitHubRequest -Path 'repos/contoso/pack' -UsedToken ([ref] $used) + $script:calls.Token | Should -Be @('env-github') + $used | Should -BeTrue + } + } + + It 'sends no token when there is none' { + InModuleScope Maester { + $script:anonymousCanRead = $true + $used = $true + $null = Invoke-MtPackGitHubRequest -Path 'repos/contoso/pack' -UsedToken ([ref] $used) + $script:calls.Count | Should -Be 1 + $script:calls[0].Token | Should -BeNullOrEmpty + $used | Should -BeFalse + } + } + + It 'moves to the next sign-in when one cannot read the repository, in order' { + $env:GH_TOKEN = 'env-gh' + $env:GITHUB_TOKEN = 'env-github' + InModuleScope Maester { + Set-TestGitHubSession + Mock Get-MtGitHubCliToken { 'cli-token' } + $script:cannotRead = @('session-token', 'cli-token', 'env-gh') + + $null = Invoke-MtPackGitHubRequest -Path 'repos/contoso/pack' + + $script:calls.Token | Should -Be @('session-token', 'cli-token', 'env-gh', 'env-github') + } + } + + It 'starts later requests for a repository with the sign-in that read it' { + InModuleScope Maester { + Set-TestGitHubSession + Mock Get-MtGitHubCliToken { 'cli-token' } + $script:cannotRead = @('session-token') + + $null = Invoke-MtPackGitHubRequest -Path 'repos/contoso/pack' + $null = Invoke-MtPackGitHubRequest -Path 'repos/Contoso/Pack/releases?per_page=30' + + $script:calls.Token | Should -Be @('session-token', 'cli-token', 'cli-token') + # The name of the source is remembered, never the token. + $script:__MtPackGitHubTokenSource['contoso/pack'] | Should -Be 'GitHubCli' + } + } + + It 'does not send the same token twice when gh answers with GH_TOKEN' { + $env:GH_TOKEN = 'env-gh' + InModuleScope Maester { + Mock Get-MtGitHubCliToken { 'env-gh' } + $script:cannotRead = @('env-gh') + + { Invoke-MtPackGitHubRequest -Path 'repos/contoso/pack' } | Should -Throw + + @($script:calls | Where-Object Token -EQ 'env-gh').Count | Should -Be 1 + } + } + + It 'does not use a session sign-in to ' -ForEach @( + @{ Case = 'another GitHub host'; ApiBaseUri = 'https://api.contoso.ghe.com'; ExpiresAt = $null } + @{ Case = 'github.com that has expired'; ApiBaseUri = 'https://api.github.com'; ExpiresAt = [datetimeoffset]::UtcNow.AddMinutes(-5) } + ) { + InModuleScope Maester -Parameters @{ ApiBaseUri = $ApiBaseUri; ExpiresAt = $ExpiresAt } { + Set-TestGitHubSession -ApiBaseUri $ApiBaseUri -ExpiresAt $ExpiresAt + $script:anonymousCanRead = $true + + $null = Invoke-MtPackGitHubRequest -Path 'repos/contoso/pack' + + $script:calls.Token | Should -BeNullOrEmpty + } + } + + It 'does not use the sign-in of a session that is not connected' { + InModuleScope Maester { + $__MtSession.GitHubAuthHeader = @{ Authorization = 'Bearer stale-token' } + $__MtSession.GitHubConnection = [pscustomobject]@{ Connected = $false; FailureReason = 'TokenInvalid' } + $script:anonymousCanRead = $true + + $null = Invoke-MtPackGitHubRequest -Path 'repos/contoso/pack' + + $script:calls.Token | Should -BeNullOrEmpty + } + } + + It 'sends every request to api.github.com' { + $env:GH_TOKEN = 'env-gh' + InModuleScope Maester { + Set-TestGitHubSession + $script:cannotRead = @('session-token') + $null = Invoke-MtPackGitHubRequest -Path '/repos/contoso/pack' + $script:calls.Uri | Select-Object -Unique | Should -Be 'https://api.github.com/repos/contoso/pack' + } + } + + It 'returns $null for 404 with -AllowNotFound, without asking other sources once one has read the repository' { + $env:GH_TOKEN = 'env-gh' + InModuleScope Maester { + Set-TestGitHubSession + $null = Invoke-MtPackGitHubRequest -Path 'repos/contoso/pack' + $script:cannotRead = @('session-token') + + Invoke-MtPackGitHubRequest -Path 'repos/contoso/pack/git/ref/tags%2Fv9' -AllowNotFound | Should -BeNullOrEmpty + + $script:calls.Token | Should -Be @('session-token', 'session-token') + } + } + + It 'names what was tried, and not GH_TOKEN, when nothing can read the repository' { + InModuleScope Maester { + Set-TestGitHubSession + $script:cannotRead = @('session-token') + $failure = $null + try { Invoke-MtPackGitHubRequest -Path 'repos/contoso/pack' } catch { $failure = "$_" } + $failure | Should -BeLike '*404 Not Found*the Connect-MtGitHub sign-in*-Token*' + $failure | Should -Not -Match 'set GH_TOKEN' + $failure | Should -Not -Match 'session-token' + } + } + + It 'tells someone with no sign-in how to reach a private repository' { + InModuleScope Maester { + { Invoke-MtPackGitHubRequest -Path 'repos/contoso/pack' } | Should -Throw '*private repository*gh auth login*-Token*' + } + } + + It 'stops at a rate limit instead of trying the next sign-in' { + $env:GH_TOKEN = 'env-gh' + InModuleScope Maester { + Mock Invoke-RestMethod { + $script:calls.Add([pscustomobject]@{ Uri = [string]$Uri; Token = $Headers['Authorization'] }) + $response = [System.Net.Http.HttpResponseMessage]::new([System.Net.HttpStatusCode]::Forbidden) + throw [Microsoft.PowerShell.Commands.HttpResponseException]::new('API rate limit exceeded', $response) + } + Set-TestGitHubSession + + { Invoke-MtPackGitHubRequest -Path 'repos/contoso/pack' } | Should -Throw '*rate limit*Wait for the limit to reset*' + + $script:calls.Count | Should -Be 1 + } + } +} + +Describe 'Pack GitHub token: the -Token parameter' { + It ' takes -Token as a SecureString' -ForEach @( + @{ Command = 'Install-MtPack' } + @{ Command = 'Update-MtPack' } + @{ Command = 'Restore-MtPack' } + ) { + $parameter = (Get-Command $Command).Parameters['Token'] + $parameter | Should -Not -BeNullOrEmpty + $parameter.ParameterType | Should -Be ([securestring]) + } + + It 'is passed to every GitHub request of an install' { + InModuleScope Maester { + $script:tokens = [System.Collections.Generic.List[object]]::new() + Mock Invoke-MtPackGitHubRequest { + $script:tokens.Add($Token) + switch -Wildcard ($Path) { + 'repos/contoso/pack' { [pscustomobject]@{ id = 7; full_name = 'contoso/pack'; default_branch = 'main'; owner = [pscustomobject]@{ id = 9; login = 'contoso' } } } + 'repos/contoso/pack/releases*' { , @() } + 'repos/contoso/pack/commits/*' { [pscustomobject]@{ sha = 'c' * 40 } } + '*/zipball/*' { throw 'stop after the download was asked for' } + } + } + $token = [System.Net.NetworkCredential]::new('', 'parameter-token').SecurePassword + + { Get-MtPackCandidate -Source 'contoso/pack' -Token $token -IncludeRecent } | Should -Throw '*stop after the download*' + + $script:tokens.Count | Should -BeGreaterThan 2 + foreach ($t in $script:tokens) { [object]::ReferenceEquals($t, $token) | Should -BeTrue } + } + } + + It 'is not sent to GitHub requests when it was not given' { + InModuleScope Maester { + Mock Invoke-MtPackGitHubRequest { throw 'stop' } + { Get-MtPackCandidate -Source 'contoso/pack' } | Should -Throw + Should -Invoke Invoke-MtPackGitHubRequest -ParameterFilter { $null -eq $Token } + } + } +} + +Describe 'Pack GitHub token: Get-MtSession' { + It 'does not return the session sign-in the pack commands use' { + InModuleScope Maester { + $__MtSession.GitHubAuthHeader = @{ Authorization = 'Bearer session-token' } + try { + (Get-MtSession).GitHubAuthHeader['Authorization'] | Should -Be '' + (Get-MtSession).Keys | Should -Not -Contain '__MtPackGitHubTokenSource' + } finally { + $__MtSession.GitHubAuthHeader = $null + } + } + } +} diff --git a/powershell/tests/functions/MaesterPacks.Tests.ps1 b/powershell/tests/functions/MaesterPacks.Tests.ps1 index 9166274570..cac9d8829a 100644 --- a/powershell/tests/functions/MaesterPacks.Tests.ps1 +++ b/powershell/tests/functions/MaesterPacks.Tests.ps1 @@ -102,6 +102,25 @@ Describe 'Maester Pack manifest' { @($read.Warnings) -match '6 levels deep' | Should -Not -BeNullOrEmpty } + It 'reads the Settings a pack declares, and refuses ' -ForEach @( + @{ Case = 'a name without a namespace'; Settings = @{ Regions = @{ Type = 'string[]' } }; Message = '*must be named Namespace.Key*' } + @{ Case = 'a setting without a type'; Settings = @{ 'Contoso.Regions' = @{ Default = @() } }; Message = '*needs a Type*' } + @{ Case = 'a type Maester does not know'; Settings = @{ 'Contoso.Regions' = @{ Type = 'datetime' } }; Message = '*needs a Type*' } + @{ Case = 'allowed values for a number'; Settings = @{ 'Contoso.Limit' = @{ Type = 'int'; AllowedValues = @('1') } }; Message = '*AllowedValues is a list of strings*' } + ) { + $pack = Copy-SamplePack -Destination (Join-Path $TestDrive "settings-$([guid]::NewGuid().ToString('n'))") + Set-Manifest -Pack $pack -Change { param($m) $m | Add-Member -NotePropertyName Settings -NotePropertyValue @{ 'Contoso.Regions' = @{ Type = 'string[]'; Default = @('eu'); Description = 'Regions to check.'; Colour = 'red' } } -Force } + $ok = InModuleScope Maester -Parameters @{ Path = $pack } { param($Path) Read-MtPackManifest -Path $Path } + $ok.Errors | Should -BeNullOrEmpty + $ok.Manifest.Settings.'Contoso.Regions'.Type | Should -Be 'string[]' + @($ok.Warnings) -match "unknown key 'Colour'" | Should -Not -BeNullOrEmpty + + Set-Manifest -Pack $pack -Change { param($m) $m | Add-Member -NotePropertyName Settings -NotePropertyValue $Settings -Force } + $bad = InModuleScope Maester -Parameters @{ Path = $pack } { param($Path) Read-MtPackManifest -Path $Path } + @($bad.Errors.Message) -like $Message | Should -Not -BeNullOrEmpty + @($bad.Manifest.Settings.PSObject.Properties).Count | Should -Be 0 + } + It 'accepts the menu of the Zero Trust Assessment pack without a warning' { $read = InModuleScope Maester -Parameters @{ Path = (Join-Path $PSScriptRoot '../../../packs/zero-trust-assessment') } { param($Path) Read-MtPackManifest -Path $Path -Official } $read.Errors | Should -BeNullOrEmpty diff --git a/powershell/tests/functions/Test-MtCaEmergencyAccessExists.Tests.ps1 b/powershell/tests/functions/Test-MtCaEmergencyAccessExists.Tests.ps1 index 39294a07d3..dbd4ccc6fb 100644 --- a/powershell/tests/functions/Test-MtCaEmergencyAccessExists.Tests.ps1 +++ b/powershell/tests/functions/Test-MtCaEmergencyAccessExists.Tests.ps1 @@ -214,7 +214,7 @@ Mock -ModuleName Maester Get-MtConditionalAccessPolicy { return $policy } Mock -ModuleName Maester Get-MtSetting { return $null } - InModuleScope Maester { Test-MtCaEmergencyAccessExists } | Should -BeTrue + InModuleScope Maester -Parameters @{ C = $config } { Test-MtCaEmergencyAccessExists -EmergencyAccessAccounts $C } | Should -BeTrue } It 'Should pass when a group is excluded from all policies (auto-detected)' { @@ -223,7 +223,7 @@ Mock -ModuleName Maester Get-MtConditionalAccessPolicy { return $policy } Mock -ModuleName Maester Get-MtSetting { return $null } - InModuleScope Maester { Test-MtCaEmergencyAccessExists } | Should -BeTrue + InModuleScope Maester -Parameters @{ C = $config } { Test-MtCaEmergencyAccessExists -EmergencyAccessAccounts $C } | Should -BeTrue } } @@ -243,9 +243,8 @@ $config = @(@{ Id = $emergencyUserId1; Type = "User" }) Mock -ModuleName Maester Get-MtConditionalAccessPolicy { return $policy } - Mock -ModuleName Maester Get-MtSetting { return $config } - InModuleScope Maester { Test-MtCaEmergencyAccessExists } | Should -BeTrue + InModuleScope Maester -Parameters @{ C = $config } { Test-MtCaEmergencyAccessExists -EmergencyAccessAccounts $C } | Should -BeTrue } It 'Should fail when configured user is NOT excluded from policy' { @@ -253,9 +252,8 @@ $config = @(@{ Id = $emergencyUserId1; Type = "User" }) Mock -ModuleName Maester Get-MtConditionalAccessPolicy { return $policy } - Mock -ModuleName Maester Get-MtSetting { return $config } - InModuleScope Maester { Test-MtCaEmergencyAccessExists } | Should -BeFalse + InModuleScope Maester -Parameters @{ C = $config } { Test-MtCaEmergencyAccessExists -EmergencyAccessAccounts $C } | Should -BeFalse } It 'Should fail when a different user is excluded but not the configured one' { @@ -263,9 +261,8 @@ $config = @(@{ Id = $emergencyUserId1; Type = "User" }) Mock -ModuleName Maester Get-MtConditionalAccessPolicy { return $policy } - Mock -ModuleName Maester Get-MtSetting { return $config } - InModuleScope Maester { Test-MtCaEmergencyAccessExists } | Should -BeFalse + InModuleScope Maester -Parameters @{ C = $config } { Test-MtCaEmergencyAccessExists -EmergencyAccessAccounts $C } | Should -BeFalse } } @@ -285,9 +282,8 @@ $config = @(@{ Id = $emergencyGroupId1; Type = "Group" }) Mock -ModuleName Maester Get-MtConditionalAccessPolicy { return $policy } - Mock -ModuleName Maester Get-MtSetting { return $config } - InModuleScope Maester { Test-MtCaEmergencyAccessExists } | Should -BeTrue + InModuleScope Maester -Parameters @{ C = $config } { Test-MtCaEmergencyAccessExists -EmergencyAccessAccounts $C } | Should -BeTrue } It 'Should fail when configured group is NOT excluded from policy' { @@ -295,9 +291,8 @@ $config = @(@{ Id = $emergencyGroupId1; Type = "Group" }) Mock -ModuleName Maester Get-MtConditionalAccessPolicy { return $policy } - Mock -ModuleName Maester Get-MtSetting { return $config } - InModuleScope Maester { Test-MtCaEmergencyAccessExists } | Should -BeFalse + InModuleScope Maester -Parameters @{ C = $config } { Test-MtCaEmergencyAccessExists -EmergencyAccessAccounts $C } | Should -BeFalse } It 'Should fail when a different group is excluded but not the configured one' { @@ -305,9 +300,8 @@ $config = @(@{ Id = $emergencyGroupId1; Type = "Group" }) Mock -ModuleName Maester Get-MtConditionalAccessPolicy { return $policy } - Mock -ModuleName Maester Get-MtSetting { return $config } - InModuleScope Maester { Test-MtCaEmergencyAccessExists } | Should -BeFalse + InModuleScope Maester -Parameters @{ C = $config } { Test-MtCaEmergencyAccessExists -EmergencyAccessAccounts $C } | Should -BeFalse } } @@ -333,9 +327,8 @@ ) Mock -ModuleName Maester Get-MtConditionalAccessPolicy { return $policy } - Mock -ModuleName Maester Get-MtSetting { return $config } - InModuleScope Maester { Test-MtCaEmergencyAccessExists } | Should -BeTrue + InModuleScope Maester -Parameters @{ C = $config } { Test-MtCaEmergencyAccessExists -EmergencyAccessAccounts $C } | Should -BeTrue } It 'Should fail when only the user is excluded but not the group' { @@ -346,9 +339,8 @@ ) Mock -ModuleName Maester Get-MtConditionalAccessPolicy { return $policy } - Mock -ModuleName Maester Get-MtSetting { return $config } - InModuleScope Maester { Test-MtCaEmergencyAccessExists } | Should -BeFalse + InModuleScope Maester -Parameters @{ C = $config } { Test-MtCaEmergencyAccessExists -EmergencyAccessAccounts $C } | Should -BeFalse } It 'Should fail when only the group is excluded but not the user' { @@ -359,9 +351,8 @@ ) Mock -ModuleName Maester Get-MtConditionalAccessPolicy { return $policy } - Mock -ModuleName Maester Get-MtSetting { return $config } - InModuleScope Maester { Test-MtCaEmergencyAccessExists } | Should -BeFalse + InModuleScope Maester -Parameters @{ C = $config } { Test-MtCaEmergencyAccessExists -EmergencyAccessAccounts $C } | Should -BeFalse } It 'Should fail when neither user nor group is excluded' { @@ -372,9 +363,8 @@ ) Mock -ModuleName Maester Get-MtConditionalAccessPolicy { return $policy } - Mock -ModuleName Maester Get-MtSetting { return $config } - InModuleScope Maester { Test-MtCaEmergencyAccessExists } | Should -BeFalse + InModuleScope Maester -Parameters @{ C = $config } { Test-MtCaEmergencyAccessExists -EmergencyAccessAccounts $C } | Should -BeFalse } } @@ -400,9 +390,8 @@ ) Mock -ModuleName Maester Get-MtConditionalAccessPolicy { return $policies } - Mock -ModuleName Maester Get-MtSetting { return $config } - InModuleScope Maester { Test-MtCaEmergencyAccessExists } | Should -BeFalse + InModuleScope Maester -Parameters @{ C = $config } { Test-MtCaEmergencyAccessExists -EmergencyAccessAccounts $C } | Should -BeFalse } } @@ -422,9 +411,8 @@ $config = @(@{ UserPrincipalName = "emergency@contoso.com"; Type = "User" }) Mock -ModuleName Maester Get-MtConditionalAccessPolicy { return $policy } - Mock -ModuleName Maester Get-MtSetting { return $config } - InModuleScope Maester { Test-MtCaEmergencyAccessExists } | Should -BeTrue + InModuleScope Maester -Parameters @{ C = $config } { Test-MtCaEmergencyAccessExists -EmergencyAccessAccounts $C } | Should -BeTrue } It 'Should pass when duplicate configured UPN entries resolve to one excluded user' { @@ -435,9 +423,8 @@ ) Mock -ModuleName Maester Get-MtConditionalAccessPolicy { return $policy } - Mock -ModuleName Maester Get-MtSetting { return $config } - InModuleScope Maester { Test-MtCaEmergencyAccessExists } | Should -BeTrue + InModuleScope Maester -Parameters @{ C = $config } { Test-MtCaEmergencyAccessExists -EmergencyAccessAccounts $C } | Should -BeTrue } It 'Should use configured-account result text when emergency access config is present' { @@ -446,13 +433,12 @@ $script:capturedResult = $null Mock -ModuleName Maester Get-MtConditionalAccessPolicy { return $policy } - Mock -ModuleName Maester Get-MtSetting { return $config } Mock -ModuleName Maester Add-MtTestResultDetail { param($Result) $script:capturedResult = $Result } - InModuleScope Maester { Test-MtCaEmergencyAccessExists } | Should -BeFalse + InModuleScope Maester -Parameters @{ C = $config } { Test-MtCaEmergencyAccessExists -EmergencyAccessAccounts $C } | Should -BeFalse $script:capturedResult | Should -BeLike '*Configured emergency access accounts or groups*' $script:capturedResult | Should -Not -BeLike '*Automatically detected emergency access*' } @@ -463,13 +449,12 @@ $script:capturedResult = $null Mock -ModuleName Maester Get-MtConditionalAccessPolicy { return $policy } - Mock -ModuleName Maester Get-MtSetting { return $config } Mock -ModuleName Maester Add-MtTestResultDetail { param($Result) $script:capturedResult = $Result } - InModuleScope Maester { Test-MtCaEmergencyAccessExists -WarningAction SilentlyContinue } | Should -BeFalse + InModuleScope Maester -Parameters @{ C = $config } { Test-MtCaEmergencyAccessExists -EmergencyAccessAccounts $C -WarningAction SilentlyContinue } | Should -BeFalse $script:capturedResult | Should -BeLike '*none could be resolved*' } } @@ -484,7 +469,7 @@ # Returns $false because Agent Identity policies don't apply to users and are filtered out # When all policies are filtered out, there are no policies to check, so no emergency access is detected - InModuleScope Maester { Test-MtCaEmergencyAccessExists } | Should -BeFalse + InModuleScope Maester -Parameters @{ C = $config } { Test-MtCaEmergencyAccessExists -EmergencyAccessAccounts $C } | Should -BeFalse } It 'Should return false (no emergency access detected) when only a Service Principal policy exists (which should be ignored)' { @@ -495,7 +480,7 @@ # Returns $false because Service Principal policies don't apply to users and are filtered out # When all policies are filtered out, there are no policies to check, so no emergency access is detected - InModuleScope Maester { Test-MtCaEmergencyAccessExists } | Should -BeFalse + InModuleScope Maester -Parameters @{ C = $config } { Test-MtCaEmergencyAccessExists -EmergencyAccessAccounts $C } | Should -BeFalse } It 'Should only check user-targeted policies when both Agent Identity and user policies exist' { @@ -508,7 +493,7 @@ Mock -ModuleName Maester Get-MtSetting { return $null } # Should pass because the Agent Identity policy is ignored and the user policy has exclusions - InModuleScope Maester { Test-MtCaEmergencyAccessExists } | Should -BeTrue + InModuleScope Maester -Parameters @{ C = $config } { Test-MtCaEmergencyAccessExists -EmergencyAccessAccounts $C } | Should -BeTrue } } } diff --git a/powershell/tests/functions/Test-MtCisaSpfDirective.Tests.ps1 b/powershell/tests/functions/Test-MtCisaSpfDirective.Tests.ps1 new file mode 100644 index 0000000000..73f6296119 --- /dev/null +++ b/powershell/tests/functions/Test-MtCisaSpfDirective.Tests.ps1 @@ -0,0 +1,121 @@ +BeforeAll { + . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" + # Check functions that became native tests are not exported. + Use-MtModuleFunction -Name Test-MtCisaSpfDirective + + function New-TestSpfRecord { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Test helper that only builds test data.')] + param( + [string]$DomainName, + # The SPF record, or the text the lookup returns when it finds none. + [string]$Record + ) + + $spfRecord = $Record + $spfLookups = @() + if ($Record -like 'v=spf1*') { + $terms = foreach ($term in ($Record -split '\s+' | Select-Object -Skip 1)) { + $isAll = $term -match '^(?[-~?+]?)all$' + [pscustomobject]@{ + directive = $term + qualifier = if ($isAll) { $Matches.qualifier } else { '' } + mechanism = if ($isAll) { 'all' } elseif ($term -like 'include:*') { 'include' } else { '' } + mechanismTarget = if ($term -like 'include:*') { $term.Substring(8) } else { '' } + modifier = if ($term -like 'redirect=*') { 'redirect' } else { '' } + } + } + $spfRecord = [pscustomobject]@{ record = $Record; terms = @($terms) } + $spfLookups = @($terms | Where-Object { $_.mechanism -eq 'include' } | ForEach-Object { + [pscustomobject]@{ SPFSourceDomain = $_.mechanismTarget; Include = $true } + }) + } + + return [pscustomobject]@{ + domain = $DomainName + spfRecord = $spfRecord + spfLookups = $spfLookups + } + } +} + +Describe 'CISA.MS.EXO.2.2 with ParkedDomains' { + BeforeEach { + $script:acceptedDomains = @() + $script:spfRecords = @{} + Mock -ModuleName Maester Get-MtExo { return $script:acceptedDomains } + Mock -ModuleName Maester Get-MailAuthenticationRecord { + return New-TestSpfRecord -DomainName $DomainName -Record $script:spfRecords[$DomainName] + } + Mock -ModuleName Maester Add-MtTestResultDetail { } + } + + It 'checks a domain that cannot send as a sending domain when it is not listed' { + $script:acceptedDomains = @([pscustomobject]@{ DomainName = 'parked.example'; IsCoexistenceDomain = $false; SendingFromDomainDisabled = $true }) + $script:spfRecords['parked.example'] = 'v=spf1 include:spf.example.net -all' + + Test-MtCisaSpfDirective | Should -BeFalse + + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -Times 1 -Exactly -ParameterFilter { $Result -match '\| parked\.example \| ❌ Fail \| No Exchange Online directive \|' } + } + + It 'accepts for a listed parked domain' -ForEach @( + @{ Record = 'v=spf1 -all' } + @{ Record = 'v=spf1 ~all' } + @{ Record = 'v=spf1 include:spf.example.net -all' } + ) { + $script:acceptedDomains = @([pscustomobject]@{ DomainName = 'parked.example'; IsCoexistenceDomain = $false }) + $script:spfRecords['parked.example'] = $Record + + Test-MtCisaSpfDirective -ParkedDomains 'PARKED.example.' | Should -BeTrue + + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -Times 1 -Exactly -ParameterFilter { $Result -match '\| parked\.example \| ✅ Pass \| Parked domain: fails all senders \|' } + } + + It 'fails a listed parked domain that publishes ' -ForEach @( + @{ Record = 'v=spf1 ?all'; Reason = 'policy does not end in -all or ~all' } + @{ Record = 'v=spf1 +all'; Reason = 'policy does not end in -all or ~all' } + @{ Record = 'v=spf1 include:spf.protection.outlook.com'; Reason = 'policy does not end in -all or ~all' } + @{ Record = 'Failure to obtain record'; Reason = 'Failure to obtain record' } + ) { + $script:acceptedDomains = @([pscustomobject]@{ DomainName = 'parked.example'; IsCoexistenceDomain = $false }) + $script:spfRecords['parked.example'] = $Record + + Test-MtCisaSpfDirective -ParkedDomains 'parked.example' | Should -BeFalse + + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -Times 1 -Exactly -ParameterFilter { $Result -match ([regex]::Escape("| parked.example | ❌ Fail | Parked domain: $Reason |")) } + } + + It 'still asks a sending domain for the Exchange Online directive' { + $script:acceptedDomains = @( + [pscustomobject]@{ DomainName = 'contoso.com'; IsCoexistenceDomain = $false } + [pscustomobject]@{ DomainName = 'parked.example'; IsCoexistenceDomain = $false } + ) + $script:spfRecords['contoso.com'] = 'v=spf1 -all' + $script:spfRecords['parked.example'] = 'v=spf1 -all' + + Test-MtCisaSpfDirective -ParkedDomains 'parked.example' | Should -BeFalse + + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -Times 1 -Exactly -ParameterFilter { $Result -match '\| contoso\.com \| ❌ Fail \|' } + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -Times 1 -Exactly -ParameterFilter { $Result -match '\| parked\.example \| ✅ Pass \|' } + } + + It 'passes when the sending domain names Exchange Online and the parked domain fails all senders' { + $script:acceptedDomains = @( + [pscustomobject]@{ DomainName = 'contoso.com'; IsCoexistenceDomain = $false } + [pscustomobject]@{ DomainName = 'parked.example'; IsCoexistenceDomain = $false } + ) + $script:spfRecords['contoso.com'] = 'v=spf1 include:spf.protection.outlook.com -all' + $script:spfRecords['parked.example'] = 'v=spf1 -all' + + Test-MtCisaSpfDirective -ParkedDomains 'parked.example' | Should -BeTrue + } + + It 'is not supported when the only domain is parked and DNS is not available' { + $script:acceptedDomains = @([pscustomobject]@{ DomainName = 'parked.example'; IsCoexistenceDomain = $false }) + $script:spfRecords['parked.example'] = 'Unsupported platform, Resolve-DnsName not available' + + Test-MtCisaSpfDirective -ParkedDomains 'parked.example' | Should -BeNullOrEmpty + + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -Times 1 -Exactly -ParameterFilter { $SkippedBecause -eq 'NotSupported' } + } +} diff --git a/powershell/tests/functions/Test-MtDkim.Tests.ps1 b/powershell/tests/functions/Test-MtDkim.Tests.ps1 index af59d2de3f..fc8387f904 100644 --- a/powershell/tests/functions/Test-MtDkim.Tests.ps1 +++ b/powershell/tests/functions/Test-MtDkim.Tests.ps1 @@ -45,9 +45,11 @@ Describe 'DKIM checks with no signing configuration' -ForEach @( InitialDomain = $false IsCoexistenceDomain = $false SendingFromDomainDisabled = $true + # Test-MtCisaDkim does not read SendingFromDomainDisabled: MS.EXO.3.1v1 asks for DKIM on every + # domain, so a domain that cannot send is checked like any other. ExpectedResultByCommand = @{ 'Test-MtCisDkim' = $null - 'Test-MtCisaDkim' = $null + 'Test-MtCisaDkim' = $false } } @{ diff --git a/powershell/tests/functions/Test-MtEntraAgentMarkdown.Tests.ps1 b/powershell/tests/functions/Test-MtEntraAgentMarkdown.Tests.ps1 new file mode 100644 index 0000000000..3b8b066b81 --- /dev/null +++ b/powershell/tests/functions/Test-MtEntraAgentMarkdown.Tests.ps1 @@ -0,0 +1,174 @@ +BeforeDiscovery { + $checks = @( + @{ Id = 'MT.1200'; Command = 'Test-MtEntraAgentIdentityOrphaned' } + @{ Id = 'MT.1201'; Command = 'Test-MtEntraAgentUserOrphaned' } + @{ Id = 'MT.1203'; Command = 'Test-MtEntraAgentBlueprintOrphaned' } + @{ Id = 'MT.1204'; Command = 'Test-MtEntraAgentOwner' } + @{ Id = 'MT.1205'; Command = 'Test-MtEntraAgentSponsor' } + @{ Id = 'MT.1206'; Command = 'Test-MtEntraAgentInactive' } + @{ Id = 'MT.1207'; Command = 'Test-MtEntraAgentForeignPrivileged' } + @{ Id = 'MT.1208'; Command = 'Test-MtEntraAgentBlueprintCredentialHygiene' } + @{ Id = 'MT.1209'; Command = 'Test-MtEntraAgentDirectoryRoles' } + @{ Id = 'MT.1210'; Command = 'Test-MtEntraAgentUserExcessiveAccess' } + @{ Id = 'MT.1211'; Command = 'Test-MtEntraAgentBlueprintAllAllowedInheritance' } + @{ Id = 'MT.1212'; Command = 'Test-MtEntraAgentBlueprintOpenAccess' } + @{ Id = 'MT.1213'; Command = 'Test-MtEntraAgentBlueprintRedirectUriHygiene' } + @{ Id = 'MT.1223'; Command = 'Test-MtEntraAgentHighRiskGraphPermissions' } + ) + $names = @( + @{ Shape = 'disguised link'; Text = '[Sign in](https://phish.example/login)'; Escaped = '\[Sign in\]\(https\://phish.example/login\)' } + @{ Shape = 'image'; Text = '![beacon](https://phish.example/pixel.png)'; Escaped = '\!\[beacon\]\(https\://phish.example/pixel.png\)' } + @{ Shape = 'formatting'; Text = 'Contoso **admin** _app_ ~test~ \path `code` & Support'; Escaped = 'Contoso \*\*admin\*\* \_app\_ \~test\~ \\path \`code\` <owner> & Support' } + @{ Shape = 'bare URL'; Text = 'https://phish.example/login'; Escaped = 'https\://phish.example/login' } + @{ Shape = 'www URL'; Text = 'www.phish.example/login'; Escaped = 'www\.phish.example/login' } + @{ Shape = 'email'; Text = 'admin@phish.example'; Escaped = 'admin\@phish.example' } + @{ Shape = 'table and line breaks'; Text = "Contoso | Admin`r`nSecond row`rThird row`nFourth"; Escaped = 'Contoso \| Admin Second row Third row Fourth' } + # Keep the existing HTML encoding as well: Markdown decodes a raw © or A. + @{ Shape = 'literal HTML entities'; Text = 'Contoso © A A &'; Escaped = 'Contoso &copy; &#65; &#x41; &amp;' } + ) + $findingCases = foreach ($check in $checks) { + foreach ($name in $names) { $check + $name } + } + $observationCases = foreach ($check in $checks | Where-Object Id -In 'MT.1207', 'MT.1209', 'MT.1210') { + foreach ($name in $names) { $check + $name } + } +} + +Describe 'Entra Agent ID result Markdown' { + BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force + } + + BeforeEach { + $script:AgentMarkdownTest = @{ + Id = ''; Shape = ''; Text = ''; Name = ''; RoleName = 'Global Administrator' + ObserveOnly = $false; Result = $null; SkippedBecause = $null + } + Mock Add-MtTestResultDetail -ModuleName Maester { + $script:AgentMarkdownTest.Result = $Result + $script:AgentMarkdownTest.SkippedBecause = $SkippedBecause + } + Mock Get-MtDirectoryRoleAssignment -ModuleName Maester { + @{ + Assignments = @([pscustomobject]@{ principalId = 'user-1'; roleDefinitionId = 'role-1'; directoryScopeId = '/' }) + EligibleChecked = $true + } + } + Mock Get-MtEntraAgentHighRiskGraphPermissionFinding -ModuleName Maester { + @{ + AgentCount = 1 + Findings = @([pscustomobject]@{ + AgentId = 'agent-1'; DisplayName = $script:AgentMarkdownTest.Name; AppId = 'agent-app' + Permission = 'Policy.ReadWrite.ConditionalAccess'; PermissionType = 'Application'; AttackPath = 'Direct' + }) + } + } + Mock Invoke-MtGraphRequest -ModuleName Maester { + $test = $script:AgentMarkdownTest + switch -Wildcard ($RelativeUri) { + 'organization' { return @([pscustomobject]@{ id = 'local-tenant' }) } + 'servicePrincipals/microsoft.graph.agentIdentity' { + return @([pscustomobject]@{ + id = 'agent-1'; appId = 'agent-app'; displayName = $test.Name + agentIdentityBlueprintId = 'blueprint-app'; accountEnabled = $true; createdDateTime = '2000-01-01T00:00:00Z' + }) + } + 'servicePrincipals/microsoft.graph.agentIdentityBlueprintPrincipal' { + if ($test.Id -eq 'MT.1200') { return @() } + return @([pscustomobject]@{ + id = 'principal-1'; appId = 'blueprint-app'; displayName = $test.Name + appOwnerOrganizationId = 'foreign-tenant'; appRoleAssignmentRequired = $false + appRoles = @([pscustomobject]@{ id = 'app-role'; isEnabled = $true }) + }) + } + 'applications/microsoft.graph.agentIdentityBlueprint' { + if ($test.Id -eq 'MT.1203') { return @() } + return @([pscustomobject]@{ + id = 'blueprint-1'; appId = 'blueprint-app'; displayName = $test.Name + passwordCredentials = @([pscustomobject]@{ keyId = 'secret-1'; startDateTime = '2000-01-01T00:00:00Z'; endDateTime = '2001-01-01T00:00:00Z' }) + keyCredentials = @([pscustomobject]@{ keyId = 'key-1'; startDateTime = '2020-01-01T00:00:00Z'; endDateTime = '2100-01-01T00:00:00Z' }) + web = @{ redirectUris = @('http://phish.example/*') } + }) + } + 'users/microsoft.graph.agentUser' { + return @([pscustomobject]@{ + id = 'user-1'; displayName = $test.Name; userPrincipalName = 'agent_user@phish.example'; identityParentId = 'missing-agent' + }) + } + 'roleManagement/directory/roleAssignments' { + return @( + [pscustomobject]@{ principalId = 'principal-1'; roleDefinitionId = 'role-1'; directoryScopeId = '/' } + [pscustomobject]@{ principalId = 'agent-1'; roleDefinitionId = 'role-1'; directoryScopeId = '/' } + ) + } + 'roleManagement/directory/roleDefinitions' { + return @([pscustomobject]@{ id = 'role-1'; displayName = $test.RoleName }) + } + '*/transitiveMemberOf/microsoft.graph.group' { + if ($test.ObserveOnly) { return @() } + return @([pscustomobject]@{ id = 'group-1'; displayName = $test.Name; isAssignableToRole = $true }) + } + '*/appRoleAssignments' { + if ($test.ObserveOnly) { return @() } + return @([pscustomobject]@{ id = 'assignment-1'; resourceDisplayName = $test.Name }) + } + '*/inheritablePermissions' { + return @([pscustomobject]@{ + resourceAppId = 'resource-app'; inheritableScopes = @{ kind = 'allAllowed' }; inheritableRoles = @{ kind = 'allAllowed' } + }) + } + '*/owners' { return @() } + '*/sponsors' { return @() } + 'reports/*' { return @() } + default { throw "Unexpected Graph request: $RelativeUri" } + } + } + } + + AfterAll { + Remove-Variable -Name AgentMarkdownTest -Scope Script -ErrorAction SilentlyContinue + } + + It ' keeps a literal in findings' -ForEach $findingCases { + $script:AgentMarkdownTest.Id = $Id + $script:AgentMarkdownTest.Shape = $Shape + $script:AgentMarkdownTest.Text = $Text + $script:AgentMarkdownTest.Name = $Text + + $verdict = InModuleScope Maester -Parameters @{ CheckCommand = $Command } { + param($CheckCommand) + & $CheckCommand + } + + $verdict | Should -BeFalse + $script:AgentMarkdownTest.SkippedBecause | Should -BeNullOrEmpty + $script:AgentMarkdownTest.Result | Should -Match ([regex]::Escape($Escaped)) + $script:AgentMarkdownTest.Result | Should -Not -Match ([regex]::Escape($Text)) + if ($Id -in 'MT.1201', 'MT.1210') { + $script:AgentMarkdownTest.Result | Should -Match 'agent\\_user\\@phish\.example' + } + if ($Id -eq 'MT.1213') { + $script:AgentMarkdownTest.Result | Should -Match 'http\\://phish\.example/\\\*' + } + } + + It ' keeps a custom role containing a literal in passing observations' -ForEach $observationCases { + $script:AgentMarkdownTest.Id = $Id + $script:AgentMarkdownTest.Shape = "observation: $Shape" + $script:AgentMarkdownTest.Text = $Text + $script:AgentMarkdownTest.Name = 'Ordinary agent' + $script:AgentMarkdownTest.RoleName = $Text + $script:AgentMarkdownTest.ObserveOnly = $true + + $verdict = InModuleScope Maester -Parameters @{ CheckCommand = $Command } { + param($CheckCommand) + & $CheckCommand + } + + $verdict | Should -BeTrue + $script:AgentMarkdownTest.SkippedBecause | Should -BeNullOrEmpty + $script:AgentMarkdownTest.Result | Should -Match 'Observation:' + $script:AgentMarkdownTest.Result | Should -Match ([regex]::Escape($Escaped)) + $script:AgentMarkdownTest.Result | Should -Not -Match ([regex]::Escape($Text)) + } +} diff --git a/powershell/tests/functions/Test-MtEntraAgentSecurity.Tests.ps1 b/powershell/tests/functions/Test-MtEntraAgentSecurity.Tests.ps1 index e4e691c798..22db1be24c 100644 --- a/powershell/tests/functions/Test-MtEntraAgentSecurity.Tests.ps1 +++ b/powershell/tests/functions/Test-MtEntraAgentSecurity.Tests.ps1 @@ -700,7 +700,7 @@ Test-MtEntraAgentUserExcessiveAccess | Should -BeTrue $script:TestResult | Should -Match 'Custom Agent Role' $script:TestResult | Should -Match 'Agent User 1' - $script:TestResult | Should -Match 'au1@ contoso.com' + $script:TestResult | Should -Match 'au1\\@ contoso.com' $script:TestResult | Should -Not -Match "Agent`nUser 1" $script:TestResult | Should -Not -Match "au1@`r`ncontoso.com" $script:TestResult | Should -Not -Match "Custom`r`nAgent Role" diff --git a/powershell/tests/functions/Test-MtMobileSecurity.Tests.ps1 b/powershell/tests/functions/Test-MtMobileSecurity.Tests.ps1 index 7a55bbfa0b..8715aefc84 100644 --- a/powershell/tests/functions/Test-MtMobileSecurity.Tests.ps1 +++ b/powershell/tests/functions/Test-MtMobileSecurity.Tests.ps1 @@ -640,7 +640,7 @@ } Test-MtAndroidSecurityPatchLevel | Should -BeFalse - Test-MtAndroidSecurityPatchLevel -MaximumPatchLevelAgeInDays 500 | Should -BeTrue + Test-MtAndroidSecurityPatchLevel -MaximumPatchLevelAgeDays 500 | Should -BeTrue } It 'fails when no patch level is configured' { diff --git a/powershell/tests/functions/Test-MtMobileThreatDefenseConnectors.Tests.ps1 b/powershell/tests/functions/Test-MtMobileThreatDefenseConnectors.Tests.ps1 index 78d7329bc1..3a2a14fc1a 100644 --- a/powershell/tests/functions/Test-MtMobileThreatDefenseConnectors.Tests.ps1 +++ b/powershell/tests/functions/Test-MtMobileThreatDefenseConnectors.Tests.ps1 @@ -94,6 +94,14 @@ Describe 'Test-MtMobileThreatDefenseConnectors' { $script:Result | Should -BeLike '*Microsoft Defender for Endpoint*' } + It 'Names the Trellix connector by the ID Intune assigns to it' { + $script:Connector.id = '74873197-ffec-4dfc-9816-db65f34c7cb9' + + Test-MtMobileThreatDefenseConnectors | Should -BeTrue + $script:Result | Should -BeLike '*| Trellix Mobile Security |*' + $script:Result | Should -Not -BeLike '*74873197*' + } + It 'Escapes unknown connector IDs and states in the report table' { $script:Connector.id = '[link](https://example.test) | extra' $script:Connector.partnerState = '**unknown** | extra' diff --git a/powershell/tests/functions/engine/Frameworks.Tests.ps1 b/powershell/tests/functions/engine/Frameworks.Tests.ps1 index 4b296ae1e3..60869cadec 100644 --- a/powershell/tests/functions/engine/Frameworks.Tests.ps1 +++ b/powershell/tests/functions/engine/Frameworks.Tests.ps1 @@ -145,8 +145,8 @@ Describe 'Frameworks of a suite' { } } $keys.Own | Should -Be @('contoso-baseline', 'contoso-cloud') -Because 'the tests shipped with Maester refer to nothing outside their own folder' - $keys.Custom | Should -Be @('cis-github', 'cis-m365', 'cisa-scuba', 'contoso-baseline', 'contoso-cloud', 'essential-eight', 'ism') -Because 'a custom test can also refer to a framework shipped with Maester' - $keys.None | Should -Be @('cis-github', 'cis-m365', 'cisa-scuba', 'essential-eight', 'ism') + $keys.Custom | Should -Be @('cis-github', 'cis-m365', 'cisa-scuba', 'contoso-baseline', 'contoso-cloud', 'disa-stig-entra-id', 'disa-stig-intune-desktop', 'disa-stig-intune-mdm', 'essential-eight', 'ism') -Because 'a custom test can also refer to a framework shipped with Maester' + $keys.None | Should -Be @('cis-github', 'cis-m365', 'cisa-scuba', 'disa-stig-entra-id', 'disa-stig-intune-desktop', 'disa-stig-intune-mdm', 'essential-eight', 'ism') } It 'Reports a key that two suites declare, names both files and keeps the first' { @@ -310,7 +310,7 @@ Describe 'Benchmark of the tests shipped with Maester' { $script:frameworkFiles = @(Get-ChildItem -Path (Join-Path $script:repoRoot 'tests') -Recurse -File -Filter '*.json' | Where-Object { $_.Directory.Name -eq 'frameworks' }) } - It 'Declares the benchmarks of the CIS, CISA and ASD suites in their suite.json' { + It 'Declares the benchmarks of the CIS, CISA, ASD and DISA suites in their suite.json' { $cis = Get-Content (Join-Path $script:repoRoot 'tests/cis/suite.json') -Raw | ConvertFrom-Json @($cis.Frameworks | ForEach-Object { "$($_.Key) $($_.Version)" }) | Should -Be @('cis-m365 7.0.0', 'cis-github 1.2.0') $cisa = Get-Content (Join-Path $script:repoRoot 'tests/cisa/suite.json') -Raw | ConvertFrom-Json @@ -323,10 +323,12 @@ Describe 'Benchmark of the tests shipped with Maester' { # Both come from one ISM OSCAL release, so they carry one version. @($asd.Frameworks.Version | Sort-Object -Unique).Count | Should -Be 1 $asd.Frameworks[0].Version | Should -Not -BeNullOrEmpty + $disa = Get-Content (Join-Path $script:repoRoot 'tests/disa/suite.json') -Raw | ConvertFrom-Json + @($disa.Frameworks | ForEach-Object { "$($_.Key) $($_.Version)" }) | Should -Be @('disa-stig-entra-id V1R2', 'disa-stig-intune-mdm V1R2', 'disa-stig-intune-desktop V1R1') } It 'Has a framework file for every declared framework and no problem in any of them' { - @($script:frameworkFiles.Name | Sort-Object) | Should -Be @('cis-github.json', 'cis-m365.json', 'cisa-scuba.json', 'essential-eight.json', 'ism.json') + @($script:frameworkFiles.Name | Sort-Object) | Should -Be @('cis-github.json', 'cis-m365.json', 'cisa-scuba.json', 'disa-stig-entra-id.json', 'disa-stig-intune-desktop.json', 'disa-stig-intune-mdm.json', 'essential-eight.json', 'ism.json') $problems = @(InModuleScope Maester { Get-MtFrameworkProblem -Test @(Get-MtTestCatalog) -Root (Get-MtMaesterTestFolderPath) }) $problems | Should -BeNullOrEmpty } @@ -336,6 +338,7 @@ Describe 'Benchmark of the tests shipped with Maester' { @{ Prefix = 'CIS.GH.'; Label = 'cis-github'; Framework = 'cis-github'; Version = '1.2.0'; Count = 5 } @{ Prefix = 'CISA.'; Label = 'cisa-scuba'; Framework = 'cisa-scuba'; Version = $null; Count = 79 } @{ Prefix = 'ASD.'; Label = 'essential-eight or ism'; Framework = @('essential-eight', 'ism'); Version = $null; Count = 14 } + @{ Prefix = 'DISA.'; Label = 'a DISA STIG'; Framework = @('disa-stig-entra-id', 'disa-stig-intune-mdm', 'disa-stig-intune-desktop'); Version = $null; Count = 19 } ) { $tests = @($script:builtIn | Where-Object { $_.Id.StartsWith($Prefix) }) $tests.Count | Should -Be $Count @@ -349,8 +352,8 @@ Describe 'Benchmark of the tests shipped with Maester' { } It 'Carries Benchmark as null on every other test' { - $others = @($script:builtIn | Where-Object { $_.Id -notlike 'CIS.*' -and $_.Id -notlike 'CISA.*' -and $_.Id -notlike 'ASD.*' }) - # Consolidation changes catalog counts; this test verifies every remaining non-benchmark row. + $others = @($script:builtIn | Where-Object { $_.Id -notlike 'CIS.*' -and $_.Id -notlike 'CISA.*' -and $_.Id -notlike 'ASD.*' -and $_.Id -notlike 'DISA.*' }) + # Consolidation changes catalog counts; verify every remaining non-benchmark row. $others.Count | Should -BeGreaterThan 0 @($others | Where-Object { -not $_.PSObject.Properties['Benchmark'] -or $null -ne $_.Benchmark } | ForEach-Object Id) | Should -BeNullOrEmpty } @@ -405,7 +408,7 @@ Describe 'Benchmark of the tests shipped with Maester' { $content = Get-Content -LiteralPath $file.FullName -Raw | ConvertFrom-Json foreach ($requirement in $content.Requirements) { foreach ($name in $requirement.PSObject.Properties.Name) { - if ($name -cnotin 'Id', 'Related', 'Level', 'Profile', 'Criticality', 'Upstream', 'Strategy', 'Guideline', 'Section', 'Applicability') { "$($file.Name): requirement $($requirement.Id) has $name" } + if ($name -cnotin 'Id', 'Related', 'Level', 'Profile', 'Criticality', 'Upstream', 'Strategy', 'Guideline', 'Section', 'Applicability', 'Category', 'RuleId', 'StigId') { "$($file.Name): requirement $($requirement.Id) has $name" } } } } @@ -730,7 +733,7 @@ Describe 'Docs export' { } It 'Names every framework the tests use, with its version' { - @($script:export.Frameworks.Key) | Should -Be @('cis-github', 'cis-m365', 'cisa-scuba', 'essential-eight', 'ism') + @($script:export.Frameworks.Key) | Should -Be @('cis-github', 'cis-m365', 'cisa-scuba', 'disa-stig-entra-id', 'disa-stig-intune-desktop', 'disa-stig-intune-mdm', 'essential-eight', 'ism') ($script:export.Frameworks | Where-Object Key -EQ 'cis-m365').Name | Should -Be 'CIS Microsoft 365 Foundations Benchmark' ($script:export.Frameworks | Where-Object Key -EQ 'cis-m365').Version | Should -BeExactly '7.0.0' @($script:export.Tests | Where-Object { $_.Benchmark -and $_.Benchmark.Framework -cnotin $script:export.Frameworks.Key } | ForEach-Object Id) | Should -BeNullOrEmpty diff --git a/powershell/tests/functions/engine/NativeTests.Tests.ps1 b/powershell/tests/functions/engine/NativeTests.Tests.ps1 index d9d7d2a54a..708f622607 100644 --- a/powershell/tests/functions/engine/NativeTests.Tests.ps1 +++ b/powershell/tests/functions/engine/NativeTests.Tests.ps1 @@ -121,6 +121,243 @@ Describe 'Parameter binding (appendix A.5)' { } } +Describe 'Parameters bound to a setting' { + BeforeAll { + $script:bound = [pscustomobject]@{ + Parameters = @( + [pscustomobject]@{ Name = 'ParkedDomains'; Type = 'string[]'; Default = @(); Range = $null; AllowedValues = $null; Kind = 'Entra.Domain'; Setting = 'ParkedDomains'; EngineOwned = $false } + [pscustomobject]@{ Name = 'EmergencyAccessAccounts'; Type = 'object[]'; Default = @(); Range = $null; AllowedValues = $null; Kind = $null; Setting = 'EmergencyAccessAccounts'; EngineOwned = $false } + [pscustomobject]@{ Name = 'PolicyFiltering'; Type = 'string'; Default = 'OnlyAssigned'; Range = $null; AllowedValues = @('All', 'OnlyAssigned'); Kind = $null; Setting = 'DefenderEndpointPolicyFiltering'; EngineOwned = $false } + ) + } + function Get-SettingBinding { + param($Config, $Override, $Global) + InModuleScope Maester -Parameters @{ T = $script:bound; C = $Config; O = $Override; G = $Global } { ConvertTo-MtTestParameter -Test $T -ConfigValue $C -Override $O -GlobalSetting $G } + } + function Get-Source { param($Binding, $Name) ($Binding.Effective | Where-Object Name -EQ $Name).Source } + } + + It 'Binds a parameter from GlobalSettings and records the source and setting' { + $b = Get-SettingBinding -Global ([pscustomobject]@{ ParkedDomains = @('contoso-old.com'); DefenderEndpointPolicyFiltering = 'All' }) + $b.Error | Should -BeNullOrEmpty + $b.Bound.ParkedDomains | Should -Be @('contoso-old.com') + $b.Bound.PolicyFiltering | Should -Be 'All' + Get-Source $b 'ParkedDomains' | Should -Be 'Setting' + ($b.Effective | Where-Object Name -EQ 'PolicyFiltering').Setting | Should -Be 'DefenderEndpointPolicyFiltering' + } + + It 'Lets the test''s TestSettings row override the setting' { + $b = Get-SettingBinding -Config @{ ParkedDomains = @() } -Global @{ ParkedDomains = @('contoso-old.com') } + $b.Bound.ParkedDomains | Should -HaveCount 0 + Get-Source $b 'ParkedDomains' | Should -Be 'Config' + } + + It 'Lets the run''s -Parameter value override the row and the setting' { + $b = Get-SettingBinding -Config @{ PolicyFiltering = 'OnlyAssigned' } -Override @{ PolicyFiltering = 'All' } -Global @{ DefenderEndpointPolicyFiltering = 'OnlyAssigned' } + $b.Bound.PolicyFiltering | Should -Be 'All' + Get-Source $b 'PolicyFiltering' | Should -Be 'Parameter' + } + + It 'Keeps the default when the setting is not set or is null' { + $b = Get-SettingBinding -Global @{ ParkedDomains = $null } + $b.Bound.ContainsKey('ParkedDomains') | Should -BeFalse + Get-Source $b 'ParkedDomains' | Should -Be 'Default' + } + + It 'Binds a list of objects' { + $b = Get-SettingBinding -Global @{ EmergencyAccessAccounts = @(@{ Id = '00000000-0000-0000-0000-0000000000b1'; Type = 'Group' }, [pscustomobject]@{ UserPrincipalName = 'bg@contoso.com' }) } + $b.Error | Should -BeNullOrEmpty + $b.Bound.EmergencyAccessAccounts | Should -HaveCount 2 + $b.Bound.EmergencyAccessAccounts[0].Type | Should -Be 'Group' + $b.Bound.EmergencyAccessAccounts[1].UserPrincipalName | Should -Be 'bg@contoso.com' + } + + It 'Rejects a setting value that does not fit the parameter: ' -ForEach @( + @{ Case = 'outside ValidateSet'; Global = @{ DefenderEndpointPolicyFiltering = 'Some' } } + @{ Case = 'not a domain'; Global = @{ ParkedDomains = @('not a domain') } } + @{ Case = 'strings for a list of objects'; Global = @{ EmergencyAccessAccounts = @('bg@contoso.com') } } + ) { + (Get-SettingBinding -Global $Global).Error | Should -BeLike "Setting '*" + } + + It 'Reads Setting and takes the kind from the settings registry' { + $file = New-NativeTestFile -Folder (Join-Path $TestDrive 'setting') -Id 'SET.1' -Param @' + [MaesterParameter(Setting = 'ParkedDomains')] + [string[]] $ParkedDomains = @() +'@ + $t = InModuleScope Maester -Parameters @{ File = $file } { Read-MtNativeTest -Path $File } + $t.Errors | Should -HaveCount 0 + $t.Parameters[0].Setting | Should -Be 'ParkedDomains' + $t.Parameters[0].Kind | Should -Be 'Entra.Domain' + } + + It 'Reports ' -ForEach @( + @{ Case = 'an unregistered setting'; Param = "[MaesterParameter(Setting = 'NoSuchSetting')] [string[]] `$Domains = @()"; Message = '*not a registered setting*' } + @{ Case = 'a type that differs from the setting'; Param = "[MaesterParameter(Setting = 'ParkedDomains')] [string] `$ParkedDomains = ''"; Message = '*is a string`[`]*' } + @{ Case = 'a kind that differs from the setting'; Param = "[MaesterParameter(Kind = 'Entra.Group', Setting = 'ParkedDomains')] [string[]] `$ParkedDomains = @()"; Message = '*has kind Entra.Domain*' } + @{ Case = 'a list of objects without a setting'; Param = '[object[]] $Accounts = @()'; Message = '*only for a parameter bound to a setting*' } + ) { + $file = New-NativeTestFile -Folder (Join-Path $TestDrive ('bad' + [guid]::NewGuid().ToString('n'))) -Id 'BAD.1' -Param $Param + (InModuleScope Maester -Parameters @{ File = $file } { Read-MtNativeTest -Path $File }).Errors.Message | Should -BeLike $Message + } + + It 'Accepts a pack''s own Namespace.Key setting' { + $file = New-NativeTestFile -Folder (Join-Path $TestDrive 'packsetting') -Id 'PACK.1' -Param "[MaesterParameter(Setting = 'Contoso.Regions')] [string[]] `$Regions = @()" + (InModuleScope Maester -Parameters @{ File = $file } { Read-MtNativeTest -Path $File }).Errors | Should -HaveCount 0 + } +} + +Describe 'GlobalSettings checked against the settings registry' { + BeforeAll { + function Test-Setting { param($Global) InModuleScope Maester -Parameters @{ G = $Global } { Test-MtGlobalSetting -GlobalSetting $G } } + } + + It 'Accepts the shipped config and valid values' { + $check = Test-Setting ([pscustomobject]@{ + EmergencyAccessAccounts = @(@{ UserPrincipalName = 'bg@contoso.com'; Type = 'user' }, [pscustomobject]@{ Id = '00000000-0000-0000-0000-0000000000b1'; Type = 'Group' }) + ParkedDomains = @('contoso-old.com'); DefenderEndpointPolicyFiltering = 'All'; GitHubOrganization = '' + XspmExternalDataUris = @{ MicrosoftApps = 'https://contoso.com/apps.json' }; DataverseEnvironmentUrl = $null + }) + $check.Errors | Should -BeNullOrEmpty + $check.Warnings | Should -BeNullOrEmpty + (Test-Setting $null).Errors | Should -BeNullOrEmpty + } + + It 'Reports ' -ForEach @( + @{ Case = 'a value of the wrong type'; Global = @{ ParkedDomains = 5 }; Message = 'GlobalSettings.ParkedDomains: expected a string*' } + @{ Case = 'a value that is not allowed'; Global = @{ DefenderEndpointComplianceLogic = 'Some' }; Message = "*'Some' is not one of EffectivePolicy*" } + @{ Case = 'a value that does not fit the kind'; Global = @{ ParkedDomains = @('not a domain') }; Message = '*not a valid Entra.Domain*' } + @{ Case = 'a list item without an identifier'; Global = @{ EmergencyAccessAccounts = @(@{ Type = 'User' }) }; Message = '*item 1: needs Id or UserPrincipalName*' } + @{ Case = 'a list item with a value that is not allowed'; Global = @{ EmergencyAccessAccounts = @(@{ Id = 'x'; Type = 'Robot' }) }; Message = "*Type 'Robot' is not one of User, Group*" } + @{ Case = 'a string where an object is expected'; Global = @{ XspmExternalDataUris = 'https://contoso.com' }; Message = '*XspmExternalDataUris: expected an object*' } + ) { + (Test-Setting $Global).Errors | Should -BeLike $Message + } + + It 'Warns about a mistyped key and names the setting it is closest to' { + $check = Test-Setting @{ ParkedDomain = @('contoso-old.com') } + $check.Errors | Should -BeNullOrEmpty + $check.Warnings | Should -BeLike "*'ParkedDomain'*Did you mean 'ParkedDomains'?*" + } + + It 'Warns about an unknown key without a dot, and about an unknown property of a list item' { + (Test-Setting @{ MyOwnThing = 1 }).Warnings | Should -BeLike "*'MyOwnThing'*Namespace.Key*" + (Test-Setting @{ EmergencyAccessAccounts = @(@{ Id = 'x'; Note = 'y' }) }).Warnings | Should -BeLike "*'Note' is ignored*" + } + + It 'Passes a Namespace.Key that no pack declares' { + $check = Test-Setting @{ 'Contoso.Regions' = 5 } + $check.Errors | Should -BeNullOrEmpty + $check.Warnings | Should -BeNullOrEmpty + } + + It 'Stops a run that has an invalid setting' { + $file = New-NativeTestFile -Folder (Join-Path $TestDrive 'badsetting') -Id 'SET.2' + { Invoke-MtTest -Path $file -Config @{ GlobalSettings = @{ DefenderEndpointPolicyFiltering = 'Some' } } 6>$null } | Should -Throw '*1 invalid setting*DefenderEndpointPolicyFiltering*' + } +} + +Describe 'Settings a pack declares' { + BeforeAll { + function Register-PackSetting { + param([hashtable] $Settings) + InModuleScope Maester -Parameters @{ S = $Settings } { + $manifest = [pscustomobject]@{ Connectors = @(); Settings = ($S | ConvertTo-Json -Depth 5 | ConvertFrom-Json) } + $null = Register-MtPackService -PackSet @([pscustomobject]@{ Id = 'contoso.sample'; Status = 'Ready'; Manifest = $manifest }) + } + } + } + AfterEach { InModuleScope Maester { $null = Register-MtPackService -PackSet @() } } + + It 'Checks the config against them and returns their defaults' { + Register-PackSetting @{ 'Contoso.Regions' = @{ Type = 'string[]'; Default = @('eu'); AllowedValues = @('eu', 'us') }; 'Contoso.Limit' = @{ Type = 'int' } } + InModuleScope Maester { + (Test-MtGlobalSetting -GlobalSetting @{ 'Contoso.Regions' = @('asia') }).Errors | Should -BeLike "*'asia' is not one of eu, us*" + (Test-MtGlobalSetting -GlobalSetting @{ 'Contoso.Limit' = 'ten' }).Errors | Should -BeLike '*Contoso.Limit: expected a whole number*' + Get-MtSetting -Name 'Contoso.Regions' | Should -Be @('eu') + Get-MtSetting -Name 'Contoso.Limit' -Default 3 | Should -Be 3 + } + } + + It 'Forgets them when the pack is no longer in the run' { + Register-PackSetting @{ 'Contoso.Limit' = @{ Type = 'int' } } + InModuleScope Maester { + $null = Register-MtPackService -PackSet @() + (Test-MtGlobalSetting -GlobalSetting @{ 'Contoso.Limit' = 'ten' }).Errors | Should -BeNullOrEmpty + } + } + + It 'Checks the type of a test parameter bound to one' { + Register-PackSetting @{ 'Contoso.Regions' = @{ Type = 'string[]' } } + $file = New-NativeTestFile -Folder (Join-Path $TestDrive 'packtype') -Id 'PACK.2' -Param "[MaesterParameter(Setting = 'Contoso.Regions')] [string] `$Regions = ''" + (InModuleScope Maester -Parameters @{ File = $file } { Read-MtNativeTest -Path $File }).Errors.Message | Should -BeLike '*is a string`[`]*' + } + + It 'Redacts a sensitive setting in the recorded parameters and config, and gives the test the value' { + Register-PackSetting @{ 'Contoso.ApiKey' = @{ Type = 'string'; Sensitive = $true } } + InModuleScope Maester { + $test = [pscustomobject]@{ Parameters = @([pscustomobject]@{ Name = 'ApiKey'; Type = 'string'; Default = ''; Range = $null; AllowedValues = $null; Kind = $null; Setting = 'Contoso.ApiKey'; EngineOwned = $false }) } + $fromSetting = ConvertTo-MtTestParameter -Test $test -GlobalSetting @{ 'Contoso.ApiKey' = 'secret' } + $fromSetting.Bound.ApiKey | Should -Be 'secret' + $fromSetting.Effective[0].Value | Should -Be '[redacted]' + $fromSetting.Effective[0].Source | Should -Be 'Setting' + (ConvertTo-MtTestParameter -Test $test -ConfigValue @{ ApiKey = 'row' }).Effective[0].Value | Should -Be '[redacted]' + (ConvertTo-MtTestParameter -Test $test).Effective[0].Value | Should -Be '' + + $runConfig = [pscustomobject]@{ GlobalSettings = [pscustomobject]@{ 'Contoso.ApiKey' = 'secret'; ParkedDomains = @('contoso-old.com') }; TestSettings = @() } + $recorded = New-MtResultConfig -RunConfig $runConfig + $recorded.GlobalSettings.'Contoso.ApiKey' | Should -Be '[redacted]' + $recorded.GlobalSettings.ParkedDomains | Should -Be @('contoso-old.com') + $runConfig.GlobalSettings.'Contoso.ApiKey' | Should -Be 'secret' + } + } +} + +Describe 'New-MtTest -Setting' { + It 'Writes a parameter bound to each setting, with the type, default and allowed values of the registry' { + $folder = Join-Path $TestDrive 'scaffold-setting' + $null = New-MtTest -Id CONTOSO.2001 -Title 'Example check' -Service None -Setting EmergencyAccessAccounts, parkeddomains, DefenderEndpointComplianceLogic -Path $folder + $text = Get-Content (Join-Path $folder 'Test.CONTOSO.2001.ps1') -Raw + $text | Should -Match "\[ValidateSet\('EffectivePolicy', 'AllPolicies', 'AnyPolicy'\)\]\s+\[string\] \`$DefenderEndpointComplianceLogic = 'EffectivePolicy'" + $test = Get-MtTest -Path $folder + $test.IsValid | Should -BeTrue + $test.Parameters.Name | Should -Be @('EmergencyAccessAccounts', 'ParkedDomains', 'DefenderEndpointComplianceLogic') + $test.Parameters.Setting | Should -Be @('EmergencyAccessAccounts', 'ParkedDomains', 'DefenderEndpointComplianceLogic') + $test.Parameters.Type | Should -Be @('object[]', 'string[]', 'string') + ($test.Parameters | Where-Object Name -EQ 'ParkedDomains').Kind | Should -Be 'Entra.Domain' + @($test.Parameters | Where-Object { -not $_.Description }) | Should -HaveCount 0 + } + + It 'Refuses and writes no file' -ForEach @( + @{ Case = 'a setting that is not registered'; Setting = 'NoSuchSetting'; Message = '*not a registered setting*' } + @{ Case = 'a connection setting'; Setting = 'GitHubOrganization'; Message = '*connection setting*' } + @{ Case = 'a setting a parameter cannot hold'; Setting = 'XspmExternalDataUris'; Message = '*connection setting*' } + ) { + $folder = Join-Path $TestDrive ('scaffold-bad-' + [guid]::NewGuid().ToString('n')) + $null = New-MtTest -Id CONTOSO.2002 -Title 'Example check' -Service None -Setting $Setting -Path $folder -ErrorVariable problems -ErrorAction SilentlyContinue + "$problems" | Should -BeLike $Message + Test-Path (Join-Path $folder 'Test.CONTOSO.2002.ps1') | Should -BeFalse + } +} + +Describe 'Settings a test reads while it runs' { + It 'Records the settings read with Get-MtSetting on the result' { + $file = New-NativeTestFile -Folder (Join-Path $TestDrive 'reads') -Id 'READ.1' -Body "`$null = Get-MtSetting -Name 'GitHubOrganization'; `$null = Get-MtSetting 'Contoso.Regions' -Default @(); `$null = Get-MtSetting -Name 'GitHubOrganization'; `$true" + $row = Invoke-MtTest -Path $file -Config @{} 6>$null + $row.SettingsRead | Should -Be @('Contoso.Regions', 'GitHubOrganization') + } + + It 'Records nothing for a test that reads no setting, or outside a test' { + $file = New-NativeTestFile -Folder (Join-Path $TestDrive 'noreads') -Id 'READ.2' + (Invoke-MtTest -Path $file -Config @{} 6>$null).SettingsRead | Should -HaveCount 0 + InModuleScope Maester { + $before = @($__MtSession.SettingRead.Keys).Count + $null = Get-MtSetting -Name 'GitHubOrganization' + @($__MtSession.SettingRead.Keys).Count | Should -Be $before + } + } +} + Describe 'Licence requirements' { It 'Matches against plans : ' -ForEach @( @{ Requirement = @('AAD_PREMIUM'); Plans = @('41781fb2-bc02-4b7c-bd55-b576c07bb09d'); Expected = $true } diff --git a/powershell/tests/functions/engine/Resolve-MtTestSource.Tests.ps1 b/powershell/tests/functions/engine/Resolve-MtTestSource.Tests.ps1 index f1e170a5b3..5a81557ff4 100644 --- a/powershell/tests/functions/engine/Resolve-MtTestSource.Tests.ps1 +++ b/powershell/tests/functions/engine/Resolve-MtTestSource.Tests.ps1 @@ -222,7 +222,7 @@ Describe 'Get-MtTestFileOrigin' { foreach ($folder in Get-ChildItem $root -Directory | Where-Object Name -NE 'Custom') { $manifest = Join-Path $folder.FullName 'suite.json' $manifest | Should -Exist -Because $folder.Name - (Get-Content $manifest -Raw | ConvertFrom-Json).Source | Should -BeIn @('Maester', 'CISA', 'CIS', 'EIDSCA', 'ORCA', 'ASD') -Because $folder.Name + (Get-Content $manifest -Raw | ConvertFrom-Json).Source | Should -BeIn @('Maester', 'CISA', 'CIS', 'EIDSCA', 'ORCA', 'ASD', 'DISA') -Because $folder.Name } } } diff --git a/powershell/tests/general/NativeTestAttributes.Tests.ps1 b/powershell/tests/general/NativeTestAttributes.Tests.ps1 index 132a1473a9..3b826f7325 100644 --- a/powershell/tests/general/NativeTestAttributes.Tests.ps1 +++ b/powershell/tests/general/NativeTestAttributes.Tests.ps1 @@ -164,8 +164,8 @@ Describe 'Attributes of the built-in tests' { } It 'Finds the suites that declare frameworks' { - @($script:frameworkSuites.Id | Sort-Object) | Should -Be @('ASD', 'CIS', 'CISA') - @($script:requirementsOf.Keys | Sort-Object) | Should -Be @('cis-github', 'cis-m365', 'cisa-scuba', 'essential-eight', 'ism') + @($script:frameworkSuites.Id | Sort-Object) | Should -Be @('ASD', 'CIS', 'CISA', 'DISA') + @($script:requirementsOf.Keys | Sort-Object) | Should -Be @('cis-github', 'cis-m365', 'cisa-scuba', 'disa-stig-entra-id', 'disa-stig-intune-desktop', 'disa-stig-intune-mdm', 'essential-eight', 'ism') } It 'Names an existing requirement when a Control refers to a framework shipped with Maester' { diff --git a/powershell/tests/general/NativeTestLint.Tests.ps1 b/powershell/tests/general/NativeTestLint.Tests.ps1 index 8fa91a31a5..ce59de3242 100644 --- a/powershell/tests/general/NativeTestLint.Tests.ps1 +++ b/powershell/tests/general/NativeTestLint.Tests.ps1 @@ -137,7 +137,7 @@ Describe 'Product of the built-in tests' { $script:builtIn = @(Get-MtTest | Where-Object BuiltIn) # The product of every test in a folder that is named after a service or a suite of one product. - # tests/cis is one folder for many products, so it is only checked against the list. + # tests/cis and tests/disa are one folder for many products, so they are only checked against the list. $script:folderProduct = [ordered]@{ 'maester/azure' = 'azure' 'maester/azure-devops' = 'azure-devops' @@ -224,7 +224,7 @@ Describe 'Product of the built-in tests' { It 'Has a product in the folder map for every service folder' { $missing = $script:builtIn | ForEach-Object { Get-TestFolder -File $_.File } | Select-Object -Unique | - Where-Object { $_ -ne 'cis' -and -not $script:folderProduct.Contains($_) -and -not $script:folderProduct.Contains(($_ -split '/')[0]) } + Where-Object { $_ -notin 'cis', 'disa' -and -not $script:folderProduct.Contains($_) -and -not $script:folderProduct.Contains(($_ -split '/')[0]) } $missing | Should -BeNullOrEmpty -Because 'a new test folder needs its product in the folder map of this test' } } diff --git a/powershell/tests/general/RepositoryLayout.Tests.ps1 b/powershell/tests/general/RepositoryLayout.Tests.ps1 index 99a8bd081f..bd5c5fc8cd 100644 --- a/powershell/tests/general/RepositoryLayout.Tests.ps1 +++ b/powershell/tests/general/RepositoryLayout.Tests.ps1 @@ -22,7 +22,7 @@ BeforeAll { ) # Areas of the maester suite that are not a service. $script:MaesterAreas = @('drift') - $script:Suites = @('ad', 'asd', 'cis', 'cisa', 'custom', 'eidsca', 'maester', 'orca') + $script:Suites = @('ad', 'asd', 'cis', 'cisa', 'custom', 'disa', 'eidsca', 'maester', 'orca') $script:PublicGroups = @('app', 'connect', 'packs', 'report', 'run', 'services') $script:InternalGroups = @('app', 'checks', 'connect', 'engine', 'generated', 'packs', 'report', 'services', 'session', 'utility') $script:KebabCase = '^[a-z0-9]+(-[a-z0-9]+)*$' diff --git a/powershell/tests/general/TestBuilderData.Tests.ps1 b/powershell/tests/general/TestBuilderData.Tests.ps1 index 199ac00a0e..f0d9393a4f 100644 --- a/powershell/tests/general/TestBuilderData.Tests.ps1 +++ b/powershell/tests/general/TestBuilderData.Tests.ps1 @@ -9,6 +9,20 @@ Describe 'Test builder data' { $code | Should -Match ([regex]::Escape("const CONTROL_PATTERN = /$($schema.Properties.Control.Pattern)/;")) } + It 'offers every setting a test can bind, and no connection setting' { + $root = (Resolve-Path "$PSScriptRoot/../../..").Path + $data = Get-Content (Join-Path $root 'website/src/data/test-builder.json') -Raw | ConvertFrom-Json + $registry = (Import-PowerShellDataFile (Join-Path $root 'powershell/assets/MaesterSettings.psd1')).Settings + @($data.settings.name | Sort-Object) | Should -Be @($registry.Keys | Sort-Object) + $offered = @($data.settings | Where-Object { -not $_.connection -and $_.type -ne 'object' } | ForEach-Object name) + # Every setting a built-in test binds is one the page offers. + $bound = @(Get-ChildItem (Join-Path $root 'tests') -Recurse -Filter 'Test.*.ps1' | Select-String -Pattern "MaesterParameter\([^)]*Setting\s*=\s*'([^']+)'" -AllMatches | + ForEach-Object { $_.Matches } | ForEach-Object { $_.Groups[1].Value } | Sort-Object -Unique) + $bound | Should -Not -BeNullOrEmpty + @($bound | Where-Object { $_ -notin $offered }) | Should -BeNullOrEmpty + @($data.parameterNames | Where-Object name -EQ 'MaximumInactiveDays').type | Should -Be 'int' + } + It 'is up to date with the schema, the registries and the rubric' { $root = (Resolve-Path "$PSScriptRoot/../../..").Path $fresh = Join-Path ([System.IO.Path]::GetTempPath()) "test-builder-$([guid]::NewGuid()).json" diff --git a/powershell/tests/general/TestParameterNames.Tests.ps1 b/powershell/tests/general/TestParameterNames.Tests.ps1 new file mode 100644 index 0000000000..f72734c873 --- /dev/null +++ b/powershell/tests/general/TestParameterNames.Tests.ps1 @@ -0,0 +1,171 @@ +# The mechanical half of the parameter naming rules ("Parameter names" in website/docs/writing-tests/attribute-rubric.md): every +# parameter of a built-in test or a pack that ships with Maester follows one convention, so an admin who +# sets a value in TestSettings can guess its name. Whether a name says what it measures is a judgement; the +# attribute-review workflow and the reviewer check that. Custom tests are not checked here. +# +# It also checks how settings are read: a built-in test receives a setting as a bound parameter and never +# calls Get-MtSetting, a helper never reads a setting that tests bind, and every setting the module or a +# shipped pack reads is declared. + +BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force -WarningAction SilentlyContinue + $script:repoRoot = (Resolve-Path "$PSScriptRoot/../../..").Path + + $files = @(Get-ChildItem -Path (Join-Path $script:repoRoot 'tests'), (Join-Path $script:repoRoot 'packs') -Recurse -File -Filter 'Test.*.ps1' | + Where-Object { $_.FullName -notmatch '[\\/]custom[\\/]' }) + $script:files = $files + $tests = @(InModuleScope Maester -Parameters @{ Files = $files.FullName } { + foreach ($file in $Files) { [pscustomobject](Read-MtNativeTest -Path $file -BuiltIn) } + }) + $script:parameters = @(foreach ($t in $tests) { + foreach ($p in @($t.Parameters | Where-Object { -not $_.EngineOwned })) { + [pscustomobject]@{ Id = $t.Id; Name = $p.Name; Type = $p.Type; Setting = $p.Setting; Default = $p.Default; AllowedValues = $p.AllowedValues } + } + }) + $script:settings = InModuleScope Maester { (Get-MtSettingRegistry).Settings } + + $script:moduleFiles = @(Get-ChildItem -Path (Join-Path $script:repoRoot 'powershell/internal'), (Join-Path $script:repoRoot 'powershell/public') -Recurse -File -Filter '*.ps1') + + # The Get-MtSetting calls of a file that name the setting with a constant: Name and Line. + $script:findSettingCall = { + param([string] $Path) + $ast = [System.Management.Automation.Language.Parser]::ParseFile($Path, [ref]$null, [ref]$null) + $calls = $ast.FindAll({ param($node) $node -is [System.Management.Automation.Language.CommandAst] -and $node.GetCommandName() -in 'Get-MtSetting', 'Get-MtMaesterConfigGlobalSetting' }, $true) + foreach ($call in $calls) { + $elements = @($call.CommandElements | Select-Object -Skip 1) + $name = $null + for ($i = 0; $i -lt $elements.Count; $i++) { + $element = $elements[$i] + if ($element -is [System.Management.Automation.Language.CommandParameterAst]) { + if ($element.ParameterName -in 'Name', 'SettingName' -and $i + 1 -lt $elements.Count -and $elements[$i + 1] -is [System.Management.Automation.Language.StringConstantExpressionAst]) { $name = $elements[$i + 1].Value; break } + if ($element.ParameterName -in 'Name', 'SettingName', 'Default') { $i++ } + continue + } + if ($element -is [System.Management.Automation.Language.StringConstantExpressionAst]) { $name = $element.Value; break } + } + if ($name) { [pscustomobject]@{ Name = $name; Line = $call.Extent.StartLineNumber } } + } + } + + # Reports offenders as "ID: Name - detail" so a failure names every parameter to rename. + function Get-Offender { + param([scriptblock] $Where, [scriptblock] $Detail) + @($script:parameters | Where-Object $Where | ForEach-Object { "$($_.Id): $($_.Name) - $(& $Detail $_)" } | Sort-Object -Unique) + } +} + +Describe 'Names of test parameters' { + It 'Finds the parameters of the built-in tests' { + $script:parameters.Count | Should -BeGreaterThan 100 + } + + It 'Uses PascalCase' { + $offenders = Get-Offender { $_.Name -cnotmatch '^[A-Z][A-Za-z0-9]*$' } { 'start with a capital letter and use letters and digits only' } + $offenders | Should -BeNullOrEmpty -Because 'parameter names are PascalCase, like PowerShell parameters' + } + + It 'Spells out Maximum and Minimum' { + $offenders = Get-Offender { $_.Name -cmatch '^(Max|Min)(?!imum)' } { + param($p) "rename to $($p.Name -creplace '^Max(?!imum)', 'Maximum' -creplace '^Min(?!imum)', 'Minimum')" + } + $offenders | Should -BeNullOrEmpty -Because 'a limit is named Maximum or Minimum, never Max or Min' + } + + It 'Ends a unit with a plain suffix' { + $offenders = Get-Offender { $_.Name -cmatch 'In(Days|Hours|Minutes|Seconds)$' } { + param($p) "rename to $($p.Name -creplace 'In(Days|Hours|Minutes|Seconds)$', '$1')" + } + $offenders | Should -BeNullOrEmpty -Because 'a unit is a plain suffix: MaximumLifetimeDays, not MaximumLifetimeInDays' + } + + It 'Names a list in the plural' { + $offenders = Get-Offender { $_.Type -in 'string[]', 'object[]' -and $_.Name -cnotmatch 's$' } { 'a list takes a plural name, for example ParkedDomains' } + $offenders | Should -BeNullOrEmpty -Because 'a string[] or object[] parameter holds several values, so its name is plural' + } + + It 'Avoids the names of PowerShell common parameters' { + $reserved = 'Force', 'Confirm', 'WhatIf', 'PassThru' + $offenders = Get-Offender { $_.Name -in $reserved } { 'name what turning it on does, for example AllDomains' } + $offenders | Should -BeNullOrEmpty -Because 'these names mean something else in PowerShell' + } + + It 'Gives one name one type' { + $offenders = @($script:parameters | Group-Object Name | Where-Object { @($_.Group.Type | Sort-Object -Unique).Count -gt 1 } | ForEach-Object { + "$($_.Name): $(($_.Group | ForEach-Object { "$($_.Id) ($($_.Type))" }) -join ', ')" + }) + $offenders | Should -BeNullOrEmpty -Because 'a name that holds a number on one test and a list on another means two different things; rename one' + } + + It 'Binds one name to one setting' { + # A test may give a bound name a value of its own, but two tests that share a name and bind it must bind the same setting. + $offenders = @($script:parameters | Where-Object Setting | Group-Object Name | Where-Object { @($_.Group.Setting | Sort-Object -Unique).Count -gt 1 } | ForEach-Object { + "$($_.Name): $(($_.Group | ForEach-Object { "$($_.Id) ($($_.Setting))" }) -join ', ')" + }) + $offenders | Should -BeNullOrEmpty -Because 'one parameter name has one meaning wherever it is bound' + } +} + +Describe 'Settings that tests receive as parameters' { + It 'Binds only registered settings or a pack''s own Namespace.Key settings' { + $offenders = Get-Offender { $_.Setting -and -not $script:settings.ContainsKey($_.Setting) -and $_.Setting -notmatch '\.' } { "'$($_.Setting)' is not in assets/MaesterSettings.psd1" } + $offenders | Should -BeNullOrEmpty + } + + It 'Gives a bound parameter the default and the allowed values of its setting' { + # The registry is where the config is checked, so a test must not accept or default to anything else. + $text = { param($v) @($v | Where-Object { $null -ne $_ } | ForEach-Object { "$_" } | Sort-Object) -join ', ' } + $offenders = foreach ($p in @($script:parameters | Where-Object { $_.Setting -and $script:settings.ContainsKey($_.Setting) })) { + $entry = $script:settings[$p.Setting] + if ((& $text $p.Default) -cne (& $text $entry.Default)) { "$($p.Id): $($p.Name) defaults to '$(& $text $p.Default)', setting $($p.Setting) to '$(& $text $entry.Default)'" } + if ((& $text $p.AllowedValues) -cne (& $text $entry.AllowedValues)) { "$($p.Id): $($p.Name) allows '$(& $text $p.AllowedValues)', setting $($p.Setting) '$(& $text $entry.AllowedValues)'" } + } + @($offenders) | Should -BeNullOrEmpty + } + + It 'Never reads a setting inside a built-in test' { + # A test that calls Get-MtSetting hides the value from Get-MtTest, and a TestSettings row cannot + # override it. A test declares [MaesterParameter(Setting = '...')] and passes the value to its helpers. + $offenders = foreach ($file in @($script:files | Where-Object { $_.FullName.StartsWith((Join-Path $script:repoRoot 'tests')) })) { + foreach ($call in @(& $script:findSettingCall $file.FullName)) { "$($file.Name): reads '$($call.Name)' with Get-MtSetting; declare [MaesterParameter(Setting = '$($call.Name)')] instead" } + } + @($offenders) | Should -BeNullOrEmpty + } + + It 'Never reads a setting that tests bind inside a helper' { + # A helper that reads the setting itself ignores the value the test was given, so a TestSettings row + # or -Parameter would change what the result records but not what the helper does. + $bound = @($script:parameters | Where-Object Setting | ForEach-Object Setting | Sort-Object -Unique) + $offenders = foreach ($file in $script:moduleFiles) { + foreach ($call in @(& $script:findSettingCall $file.FullName)) { + if ($call.Name -in $bound) { "$($file.Name): reads '$($call.Name)' with Get-MtSetting; take it as a parameter from the test instead" } + } + } + @($offenders) | Should -BeNullOrEmpty + } + + It 'Reads only registered settings in the module' { + # An unregistered setting has no type, no default and no documentation, and the config check + # reports it to the user as a likely typo. + $offenders = foreach ($file in $script:moduleFiles) { + foreach ($call in @(& $script:findSettingCall $file.FullName)) { + if (-not $script:settings.ContainsKey($call.Name)) { "$($file.Name): '$($call.Name)' is not in assets/MaesterSettings.psd1" } + } + } + @($offenders) | Should -BeNullOrEmpty + } + + It 'Declares the settings a pack reads in its maester-pack.json' { + $offenders = foreach ($pack in @(Get-ChildItem -Path (Join-Path $script:repoRoot 'packs') -Directory)) { + $manifestPath = Join-Path $pack.FullName 'maester-pack.json' + if (-not (Test-Path $manifestPath)) { continue } + $manifest = Get-Content -Path $manifestPath -Raw | ConvertFrom-Json + $declared = if ($manifest.PSObject.Properties['Settings']) { @($manifest.Settings.PSObject.Properties.Name) } else { @() } + foreach ($file in @(Get-ChildItem -Path $pack.FullName -Recurse -File -Filter '*.ps1')) { + foreach ($call in @(& $script:findSettingCall $file.FullName)) { + if ($call.Name -notin $declared -and -not $script:settings.ContainsKey($call.Name)) { "$($pack.Name)/$($file.Name): '$($call.Name)' is not under Settings in maester-pack.json" } + } + } + } + @($offenders) | Should -BeNullOrEmpty + } +} diff --git a/powershell/tests/general/TestShims.Tests.ps1 b/powershell/tests/general/TestShims.Tests.ps1 index b8b900523e..19c446cea7 100644 --- a/powershell/tests/general/TestShims.Tests.ps1 +++ b/powershell/tests/general/TestShims.Tests.ps1 @@ -80,6 +80,20 @@ Describe 'Built-in tests that call another suite''s test' { @($offenders) | Should -BeNullOrEmpty } + It 'Declares and passes on the settings of the test it calls' { + # The engine binds the parameters of the test it runs, the shim. The function the shim calls is an + # ordinary call, so a setting it does not receive from the shim is silently its default: the shim + # would ignore the tenant's emergency access accounts or parked domains. + $offenders = foreach ($shim in $script:shims) { + foreach ($parameter in @($shim.Target.Parameters | Where-Object { $_.Setting -and -not $_.EngineOwned })) { + $own = $shim.Test.Parameters | Where-Object { $_.Name -eq $parameter.Name -and $_.Setting -eq $parameter.Setting } + if (-not $own) { "$($shim.Test.Id): declare [MaesterParameter(Setting = '$($parameter.Setting)')] `$$($parameter.Name), as $($shim.Target.Id) does" } + elseif ($parameter.Name -notin $shim.Parameters) { "$($shim.Test.Id): pass -$($parameter.Name) `$$($parameter.Name) to $($shim.Command)" } + } + } + @($offenders) | Should -BeNullOrEmpty + } + It 'Leaves its own requirement off the test it calls' { # The requirement a shim implements, its first Control, is claimed once, by the shim, so a run does not # report it twice. Supporting controls such as NIST SP 800-53 may be on both. diff --git a/report/package-lock.json b/report/package-lock.json index f0b5673793..ab1cbbefc6 100644 --- a/report/package-lock.json +++ b/report/package-lock.json @@ -10,22 +10,22 @@ "dependencies": { "clsx": "^2.1.1", "dompurify": "^3.4.17", - "lucide-react": "^1.66.0", + "lucide-react": "^1.70.0", "marked": "^18.1.3", - "preact": "^11.1.1", + "preact": "^11.2.0", "react": "npm:@preact/compat@^18.3.2", "react-dom": "npm:@preact/compat@^18.3.2", "tailwind-merge": "^3.7.0" }, "devDependencies": { "@preact/preset-vite": "^2.10.6", - "@tailwindcss/postcss": "^4.3.3", + "@tailwindcss/postcss": "^4.3.5", "@types/node": "^26.6.6", "@types/react": "^19.3.0", "@types/react-dom": "^19.3.0", "tailwindcss": "~4.3.3", "typescript": "^7.0.2", - "vite": "^8.3.5", + "vite": "^8.3.6", "vite-plugin-singlefile": "^2.3.4" }, "engines": { @@ -411,9 +411,9 @@ } }, "node_modules/@oxc-project/types": { - "version": "0.154.0", - "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.154.0.tgz", - "integrity": "sha512-KYOUGQFlLWR+s4QMV2Q9ko38TZm7EdO87Qm7rvZLqk/webse/cDjtyxKhg/47l0byCbs/k46LT8qc4PKjAikzA==", + "version": "0.156.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.156.0.tgz", + "integrity": "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==", "dev": true, "license": "MIT", "funding": { @@ -513,9 +513,9 @@ } }, "node_modules/@rolldown/binding-android-arm-eabi": { - "version": "1.2.14", - "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.14.tgz", - "integrity": "sha512-aWR+XKH9+rW7m5fWq/5360J3mHycrx/o6xZM2DQFdJnTMdyP7/WzxPjhtLbVWdKo2y612/4U1bWqb3HQhiF7vg==", + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.16.tgz", + "integrity": "sha512-ia3DwAs0OsMGS7+IConptSiyk9pEXkOx/AbJ2n/lAGxH3QkWQus1t8d7gnAT38FCU2sQu8lUbeR6AiZFv4JxaA==", "cpu": [ "arm" ], @@ -530,9 +530,9 @@ } }, "node_modules/@rolldown/binding-android-arm64": { - "version": "1.2.14", - "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.14.tgz", - "integrity": "sha512-QiVxHofl6A8lQU7WAtOUY4QMVZXohxwz7WJJoeh8NBEUyKfIkMRKhYyq8az/1RypNiIXzNTtiS6KwHz0erxYRQ==", + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.16.tgz", + "integrity": "sha512-kx5wBiMB6E7TEvpl2B9gjLU004BkvEm2Dr941BFjx/SontPwSzNuQUIoVKxHHoSjpFIfHMmcguyLOtyn0hObRg==", "cpu": [ "arm64" ], @@ -547,9 +547,9 @@ } }, "node_modules/@rolldown/binding-darwin-arm64": { - "version": "1.2.14", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.14.tgz", - "integrity": "sha512-lTQOzHuBIooh3jIr5XINQkjPGEuGy+Dsy0meXDr6Sjty0b99kYgGh4uBC/8mJX1T0kC8d6S0aPP1Y+bHkh6aBw==", + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.16.tgz", + "integrity": "sha512-qslZrXnKJU4cUpjoAmtAo/KQM9e2IRMlmpig6Zpwj+8KWxW8v+nkAf9216Bsek9lOC1jvg2yCjygCFo2f83msQ==", "cpu": [ "arm64" ], @@ -564,9 +564,9 @@ } }, "node_modules/@rolldown/binding-darwin-x64": { - "version": "1.2.14", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.14.tgz", - "integrity": "sha512-hyMKEGatjmBYCs/Q4sbIcL/GqpFEqsX3wc+HYVQ/85A4rxc1o7rPm4DUI4GV4k/h0ITddwFSGpqQunI14GXjTA==", + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.16.tgz", + "integrity": "sha512-FdF+y48ND13eAyM2mQn+85kvAqNlvRWROy2rhgA463X/0Gv4vGtazZtfaF1mRBLscYvtOlh4QnLjOWiFzX69OQ==", "cpu": [ "x64" ], @@ -581,9 +581,9 @@ } }, "node_modules/@rolldown/binding-freebsd-x64": { - "version": "1.2.14", - "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.14.tgz", - "integrity": "sha512-u371GbXoVXrEgP20PwzoGNOdAOqAMhzo19JzzY+V4YmmnC+DTOoqdbMu+O+54emM59Mik/UdrtWgcuEDKWRPKA==", + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.16.tgz", + "integrity": "sha512-ddjqFM5e95AgLbUPtKIS7V1KTVlA0RUgCVr5mn+/IEhsdy3pr+Vuj/HZ7nlMN2FyxIwUktOH1LEPIQXO1v9y1Q==", "cpu": [ "x64" ], @@ -598,9 +598,9 @@ } }, "node_modules/@rolldown/binding-linux-arm-gnueabihf": { - "version": "1.2.14", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.14.tgz", - "integrity": "sha512-BqwKsdZQf6EqVWr8fv2MrDYzAvOZ7+NYFSJESRGs87fkseEhs0TU9TXgRJTkZoRRkxTizyEg1LKUXfU3/78uqg==", + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.16.tgz", + "integrity": "sha512-tHdKWbFkFBI687iim3LIyIvyL7j66VvQYkDPss5Stn/qyE2tWkR1YD0dXmXPFKKqT/o5ZEJVsaRsWS2meQwGOA==", "cpu": [ "arm" ], @@ -615,13 +615,16 @@ } }, "node_modules/@rolldown/binding-linux-arm64-gnu": { - "version": "1.2.14", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.14.tgz", - "integrity": "sha512-SD9kY8M009x/7s57Z1dgUVlP5+uYBgKQK0Tkr1WIWngrtUJmRCW1RJFMY7QDla2khXhmg2i5Io7MUjcmZNZ/KQ==", + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.16.tgz", + "integrity": "sha512-FJiLGAblPBMlBEdbOqw6kW6QcXDWAf/oJu7gYs9ZJZwmg+K+/zjFLxPTIY9izJUzxzc24FHvmseyA0IvJSl17w==", "cpu": [ "arm64" ], "dev": true, + "libc": [ + "glibc" + ], "license": "MIT", "optional": true, "os": [ @@ -632,13 +635,16 @@ } }, "node_modules/@rolldown/binding-linux-arm64-musl": { - "version": "1.2.14", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.14.tgz", - "integrity": "sha512-BJ2CL19M6uuWesMgnqJzgxoI+N+eV7b0A9O9vLV42y+gitC41fNa8KElau1tHVzuLWX5GzEuxMPhAO0tQXQMkg==", + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.16.tgz", + "integrity": "sha512-hrJpblMsrQ58U9veWpbXzkhV5zStunds6HWLprqq1qauvgBr1E6P+24kLj6lSLI9vjRn/RYpjprhkHQPKGWpNg==", "cpu": [ "arm64" ], "dev": true, + "libc": [ + "musl" + ], "license": "MIT", "optional": true, "os": [ @@ -649,13 +655,16 @@ } }, "node_modules/@rolldown/binding-linux-ppc64-gnu": { - "version": "1.2.14", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.14.tgz", - "integrity": "sha512-4+Kl8daPV8NDHaD7mfCcc1pRM+Qg7ab8DyMm5FG5WoZgv4h2i3KFN1CybYBNbQqmuYm7ftJLvmMI1eHYJ22S/Q==", + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.16.tgz", + "integrity": "sha512-qJd/dC6j6CwLG9/s/RP2nb1RZ0GIgj7Ioj7x/SYa3RzjVrlzrmH0fhIOpfvqQDeIsdP0loi+kHaMhJzY1PBIaA==", "cpu": [ "ppc64" ], "dev": true, + "libc": [ + "glibc" + ], "license": "MIT", "optional": true, "os": [ @@ -666,13 +675,16 @@ } }, "node_modules/@rolldown/binding-linux-s390x-gnu": { - "version": "1.2.14", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.14.tgz", - "integrity": "sha512-V/h8ePq1fKDrmtFMz6xcCN3DKvuvMRrwwD1q0PkBeeo4DpK64biaKvqWGVxqCeYKqeRk7gE7/iKPxLCn08O97A==", + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.16.tgz", + "integrity": "sha512-Vx7Xg5uUJuNcujJjI70OICaH0EYj80BtOLZTSN7uOYg8QOLlyKnaG0IW7Fn/J0IpJsaKzmDKMhOQv1JBM9m9vg==", "cpu": [ "s390x" ], "dev": true, + "libc": [ + "glibc" + ], "license": "MIT", "optional": true, "os": [ @@ -683,13 +695,16 @@ } }, "node_modules/@rolldown/binding-linux-x64-gnu": { - "version": "1.2.14", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.14.tgz", - "integrity": "sha512-WxalXzgrLVpKC93xfpaJ3gCXUWzeCr+FRCbDVD2mUAy4L6Vo3lNVz0epUEUpxPWJkLNYUwM4OSIikv36OJ9mLg==", + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.16.tgz", + "integrity": "sha512-TNKhgE3uJTsTzatUSSYt0Kgo+Oa2uSlSjz4r1aEIea7HX6ULBym4fAlYUhG1i6pjNf2njfCUAfKwr6C3E9Xg1w==", "cpu": [ "x64" ], "dev": true, + "libc": [ + "glibc" + ], "license": "MIT", "optional": true, "os": [ @@ -700,13 +715,16 @@ } }, "node_modules/@rolldown/binding-linux-x64-musl": { - "version": "1.2.14", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.14.tgz", - "integrity": "sha512-3G3tnAmTpdk9jO3GQtyHXqeFD2SlecfTws/Y3M2mmj9nMBwwuLT4kur8sZKeu7ENUHSpVO3cIsm5A52LEWWwlg==", + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.16.tgz", + "integrity": "sha512-7chXdpjXZ8qG0+mIxECN3cT9kvhZ3/oZhMX6Pp876P7CDrIy8nJswva6Mq357JR7eYXfuskwZxMeV1SzoZdHrA==", "cpu": [ "x64" ], "dev": true, + "libc": [ + "musl" + ], "license": "MIT", "optional": true, "os": [ @@ -717,9 +735,9 @@ } }, "node_modules/@rolldown/binding-openharmony-arm64": { - "version": "1.2.14", - "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.14.tgz", - "integrity": "sha512-qyr5XiNGxm2ytx17vvtcJ9nXn6v1gENETi503bJx3OGwZ1tSonj7BosxbMa/xeAfSl5iS9X6KjEWYXLu6v1L7Q==", + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.16.tgz", + "integrity": "sha512-Kwjt+7uNTJK5/MDkGWGVO2KQPnj8yAV75dMpfwyHZrJSXWHrniOB0aUEWlVYf3H1hOqFLIStLdM5QXq6bnKmOQ==", "cpu": [ "arm64" ], @@ -734,9 +752,9 @@ } }, "node_modules/@rolldown/binding-win32-arm64-msvc": { - "version": "1.2.14", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.14.tgz", - "integrity": "sha512-oA4o5o0S2yB199YyYXDzKUv1Z56Rc+mgOjwm7Z/vJ9Z8igiDPYvoOuDyo6g7AK/ZaF09nPhDKVnGBcYHO11GXA==", + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.16.tgz", + "integrity": "sha512-/LH6WfjDRXXJz/p5xl4TmU+jpcnwcxbKEQBW/GZE0JHfN0lGIyTtsUEGaQ/q/GikkGJ2yLKe6pwm7AnEWO8pdw==", "cpu": [ "arm64" ], @@ -751,9 +769,9 @@ } }, "node_modules/@rolldown/binding-win32-x64-msvc": { - "version": "1.2.14", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.14.tgz", - "integrity": "sha512-9mE94bf2GZUaR/fUSXCMpBoWkctu421Mi0ORpm4zqfbkjKep7RxzPFa5etcGs5h+2KApoWBOA/hAJa/7saGgEQ==", + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.16.tgz", + "integrity": "sha512-1lv1KvX0Z871zfk7vw+dnXMMnHNyDwMzWG8Kv3HxDXMOhzCX4SHc7HK319fInP0i+0p9D8brkfzL7pJOaGl+tw==", "cpu": [ "x64" ], @@ -798,310 +816,59 @@ } }, "node_modules/@tailwindcss/node": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.3.3.tgz", - "integrity": "sha512-/T8IKEsf9VTU6tLjgC7+sv2mOPtQxzE2jMw7u4Tt40Tx+QSZxpzh95/H6cMKoja9XuW7iMdLJYBB0o9G1CaAgg==", + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.3.5.tgz", + "integrity": "sha512-yT53FzV4ke0cr/BguDxhWMpm5MJu1O2muzk+tKw6lKHjODAsYArBbWwFbJiaksfzFv1tpkO9QHGzmfs1hJT66g==", "dev": true, "license": "MIT", "dependencies": { "@jridgewell/remapping": "^2.3.5", - "enhanced-resolve": "^5.24.1", + "enhanced-resolve": "^5.24.5", "jiti": "^2.7.0", - "lightningcss": "1.32.0", - "magic-string": "^0.30.21", + "lightningcss": "1.33.0", + "magic-string": "^1.1.0", "source-map-js": "^1.2.1", - "tailwindcss": "4.3.3" + "tailwindcss": "4.3.5" } }, - "node_modules/@tailwindcss/node/node_modules/lightningcss": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz", - "integrity": "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==", + "node_modules/@tailwindcss/node/node_modules/magic-string": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz", + "integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==", "dev": true, - "license": "MPL-2.0", + "license": "MIT", "dependencies": { - "detect-libc": "^2.0.3" - }, - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - }, - "optionalDependencies": { - "lightningcss-android-arm64": "1.32.0", - "lightningcss-darwin-arm64": "1.32.0", - "lightningcss-darwin-x64": "1.32.0", - "lightningcss-freebsd-x64": "1.32.0", - "lightningcss-linux-arm-gnueabihf": "1.32.0", - "lightningcss-linux-arm64-gnu": "1.32.0", - "lightningcss-linux-arm64-musl": "1.32.0", - "lightningcss-linux-x64-gnu": "1.32.0", - "lightningcss-linux-x64-musl": "1.32.0", - "lightningcss-win32-arm64-msvc": "1.32.0", - "lightningcss-win32-x64-msvc": "1.32.0" - } - }, - "node_modules/@tailwindcss/node/node_modules/lightningcss-android-arm64": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.32.0.tgz", - "integrity": "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/@tailwindcss/node/node_modules/lightningcss-darwin-arm64": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.32.0.tgz", - "integrity": "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/@tailwindcss/node/node_modules/lightningcss-darwin-x64": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.32.0.tgz", - "integrity": "sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/@tailwindcss/node/node_modules/lightningcss-freebsd-x64": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.32.0.tgz", - "integrity": "sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/@tailwindcss/node/node_modules/lightningcss-linux-arm-gnueabihf": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.32.0.tgz", - "integrity": "sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/@tailwindcss/node/node_modules/lightningcss-linux-arm64-gnu": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.32.0.tgz", - "integrity": "sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/@tailwindcss/node/node_modules/lightningcss-linux-arm64-musl": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.32.0.tgz", - "integrity": "sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/@tailwindcss/node/node_modules/lightningcss-linux-x64-gnu": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.32.0.tgz", - "integrity": "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/@tailwindcss/node/node_modules/lightningcss-linux-x64-musl": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.32.0.tgz", - "integrity": "sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/@tailwindcss/node/node_modules/lightningcss-win32-arm64-msvc": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.32.0.tgz", - "integrity": "sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/@tailwindcss/node/node_modules/lightningcss-win32-x64-msvc": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.32.0.tgz", - "integrity": "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" + "@jridgewell/sourcemap-codec": "^1.6.0" } }, "node_modules/@tailwindcss/oxide": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide/-/oxide-4.3.3.tgz", - "integrity": "sha512-krXjAikiaFSPaK/FkAQT5UTx3VormQaiZ5hBFlJZ9UFQGB/rwg1MZIhHAG9smMQRTdyJxP6Qt5MwMtdyU5FWrA==", + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide/-/oxide-4.3.5.tgz", + "integrity": "sha512-PynqGLZsZvwM9tqD/CUxkOIfyd6K5elZ2MooauzJryP/UqXYgi3yYbtt3N0Xe+MHV/eFKPFQCEfIKAqlAS1CBg==", "dev": true, "license": "MIT", "engines": { "node": ">= 20" }, "optionalDependencies": { - "@tailwindcss/oxide-android-arm64": "4.3.3", - "@tailwindcss/oxide-darwin-arm64": "4.3.3", - "@tailwindcss/oxide-darwin-x64": "4.3.3", - "@tailwindcss/oxide-freebsd-x64": "4.3.3", - "@tailwindcss/oxide-linux-arm-gnueabihf": "4.3.3", - "@tailwindcss/oxide-linux-arm64-gnu": "4.3.3", - "@tailwindcss/oxide-linux-arm64-musl": "4.3.3", - "@tailwindcss/oxide-linux-x64-gnu": "4.3.3", - "@tailwindcss/oxide-linux-x64-musl": "4.3.3", - "@tailwindcss/oxide-wasm32-wasi": "4.3.3", - "@tailwindcss/oxide-win32-arm64-msvc": "4.3.3", - "@tailwindcss/oxide-win32-x64-msvc": "4.3.3" + "@tailwindcss/oxide-android-arm64": "4.3.5", + "@tailwindcss/oxide-darwin-arm64": "4.3.5", + "@tailwindcss/oxide-darwin-x64": "4.3.5", + "@tailwindcss/oxide-freebsd-x64": "4.3.5", + "@tailwindcss/oxide-linux-arm-gnueabihf": "4.3.5", + "@tailwindcss/oxide-linux-arm64-gnu": "4.3.5", + "@tailwindcss/oxide-linux-arm64-musl": "4.3.5", + "@tailwindcss/oxide-linux-x64-gnu": "4.3.5", + "@tailwindcss/oxide-linux-x64-musl": "4.3.5", + "@tailwindcss/oxide-wasm32-wasi": "4.3.5", + "@tailwindcss/oxide-win32-arm64-msvc": "4.3.5", + "@tailwindcss/oxide-win32-x64-msvc": "4.3.5" } }, "node_modules/@tailwindcss/oxide-android-arm64": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-android-arm64/-/oxide-android-arm64-4.3.3.tgz", - "integrity": "sha512-Y85A2gmPSkl5Ve5qR86GL4HT509cFqQh1aes9p3sSkyTPwt0Pppf3GkwGe4JPACcRYjgJIEhQgM6dBClnr0NYw==", + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-android-arm64/-/oxide-android-arm64-4.3.5.tgz", + "integrity": "sha512-Se0z5xMqcSQanJD1IYmO0cGpK3iv0fp3ZsIT7xRJZ1Da5PghvNoc46zz4jIQn+aan3dV9T8AermFNN9QPmsh0Q==", "cpu": [ "arm64" ], @@ -1116,9 +883,9 @@ } }, "node_modules/@tailwindcss/oxide-darwin-arm64": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-arm64/-/oxide-darwin-arm64-4.3.3.tgz", - "integrity": "sha512-BiaWatpBcERQFDlOjRDpIVXuFK5PJez5SA4JMg6VYZdBYU+qKfV/vqjcIs+IYmtitf1xYQZTwXvU/8y4lfZUGw==", + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-arm64/-/oxide-darwin-arm64-4.3.5.tgz", + "integrity": "sha512-UPrgTDuUbvmqGMZuCnmI3FKee/tYKzKdp00/kuB4oSGB213VYg8QTdF7lVhnPoBXq/mIfJ+ILoBFqNOboWcMwQ==", "cpu": [ "arm64" ], @@ -1133,9 +900,9 @@ } }, "node_modules/@tailwindcss/oxide-darwin-x64": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-x64/-/oxide-darwin-x64-4.3.3.tgz", - "integrity": "sha512-fAeUqfV5ndhxRwai8cXGzdLvul9utWOmeTkv69unv4ZXixjn61Z+p9lCWdwOwA3TYboG3BwdVuN/RDjhBRl0mw==", + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-x64/-/oxide-darwin-x64-4.3.5.tgz", + "integrity": "sha512-E+p7HEtjI0b8D7kbbWxH067cGui6d4c79COGko9fAPVE3rwc1E7ld2HFCbaG86AOGWS5VKQYqZOaf38ya4uxTQ==", "cpu": [ "x64" ], @@ -1150,9 +917,9 @@ } }, "node_modules/@tailwindcss/oxide-freebsd-x64": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-freebsd-x64/-/oxide-freebsd-x64-4.3.3.tgz", - "integrity": "sha512-iyf5bV6+wnAlflVeEy7R25dupxTNECZN5QMI0qNT6eT+EgaGdZcKhGkr5SdoaWiLJ3spLqIY9VCeSGrwmtg4kw==", + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-freebsd-x64/-/oxide-freebsd-x64-4.3.5.tgz", + "integrity": "sha512-yWEWcWyAG7rWOcTpJTjdhQ3pcaFY2h+0bqTRfgU3G2fz87ZU3AKdvdZKhslD+kyHnjBUWKvNdRYwIYC5dI1tIg==", "cpu": [ "x64" ], @@ -1167,9 +934,9 @@ } }, "node_modules/@tailwindcss/oxide-linux-arm-gnueabihf": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm-gnueabihf/-/oxide-linux-arm-gnueabihf-4.3.3.tgz", - "integrity": "sha512-aAYUprJAJQWWbRrPvtjdroZ56Md+JM8pMiopS6xGEwDfLhqj+2ver2p4nU4Mb3CRqcMmNBjo8KkUgcxhkzVQGQ==", + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm-gnueabihf/-/oxide-linux-arm-gnueabihf-4.3.5.tgz", + "integrity": "sha512-WmeVjtJhZlr+smpqcdR2kQkkn6arHIJnUIBxTO2EJcTLGY1ecVXNo2hbSn8xc0IH2aEtys936iMWKGyj0GaKnA==", "cpu": [ "arm" ], @@ -1184,13 +951,16 @@ } }, "node_modules/@tailwindcss/oxide-linux-arm64-gnu": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-gnu/-/oxide-linux-arm64-gnu-4.3.3.tgz", - "integrity": "sha512-nDxldcEENOxZRzC2uu9jrutZdAAQtb+8WWDCSnWL1zvBk1+FN+x6MtDViPB5AJMfttVCUhehGWus3XBPgatM/w==", + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-gnu/-/oxide-linux-arm64-gnu-4.3.5.tgz", + "integrity": "sha512-DTCSyucc6ShMp1QMqV5R94Z7xlgNgUzkGmFF1rL5HH2Qjy4eSmEqy+YLGkqqYvWa4sILtgrBt1JjRKbneQtiFQ==", "cpu": [ "arm64" ], "dev": true, + "libc": [ + "glibc" + ], "license": "MIT", "optional": true, "os": [ @@ -1201,13 +971,16 @@ } }, "node_modules/@tailwindcss/oxide-linux-arm64-musl": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-musl/-/oxide-linux-arm64-musl-4.3.3.tgz", - "integrity": "sha512-Md44bD6veX/PC5iyF8cDVnw4HBIANZepRZZ7a8DQOvkfo5WUBwcp6iAuCUz23u+4SUkhJlD3eL7hNdW8ezd/kA==", + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-musl/-/oxide-linux-arm64-musl-4.3.5.tgz", + "integrity": "sha512-H9lsvO4x9E4nE4Hi8h7NHHw0O/kcVSu+iOyFHNGdYzazGgDjFHZbE6S3hQ8kMcbNXSBlMdNi67LV5EVqtpaJtw==", "cpu": [ "arm64" ], "dev": true, + "libc": [ + "musl" + ], "license": "MIT", "optional": true, "os": [ @@ -1218,13 +991,16 @@ } }, "node_modules/@tailwindcss/oxide-linux-x64-gnu": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-gnu/-/oxide-linux-x64-gnu-4.3.3.tgz", - "integrity": "sha512-tx7us1muwOKAKWao2v/GaafFeQboE6aj88vC6ziN2NCGcRm8gWUhwjzg+YdVB1e4boAtdtma4L43onunI6NS4w==", + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-gnu/-/oxide-linux-x64-gnu-4.3.5.tgz", + "integrity": "sha512-4uxQvtBvPuIdl13WfUBj9xMZHH14PtHZ8OZdtLmdyDtG66sCa1t599NZT+jagkUzRtWhuul1qRZQ1nAJscXN5g==", "cpu": [ "x64" ], "dev": true, + "libc": [ + "glibc" + ], "license": "MIT", "optional": true, "os": [ @@ -1235,13 +1011,16 @@ } }, "node_modules/@tailwindcss/oxide-linux-x64-musl": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-musl/-/oxide-linux-x64-musl-4.3.3.tgz", - "integrity": "sha512-SJxX60smvHgasZoBy11dX6YRjXJFovwWBoedhbQPOBzgFWBHGB+TVPWB9BxzR7TTxU8FQZAI2AyiNCMzFm8Img==", + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-musl/-/oxide-linux-x64-musl-4.3.5.tgz", + "integrity": "sha512-0JQAzs7jwbA7O6+z/adU+Jk3AXwsu3npAhtr5escXS7TqEqWcaDV7qHuI+0Vy/KQRuVGnLQREcSJWYauyV3oqg==", "cpu": [ "x64" ], "dev": true, + "libc": [ + "musl" + ], "license": "MIT", "optional": true, "os": [ @@ -1252,9 +1031,9 @@ } }, "node_modules/@tailwindcss/oxide-wasm32-wasi": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-wasm32-wasi/-/oxide-wasm32-wasi-4.3.3.tgz", - "integrity": "sha512-jx1+rPhY/5Ympkktd656HBWEBLxP7dH06losBLjjf5vgCODXvi9KhtftWcMIwTFIDqBr7cRnQkdLnAG+IOlGvQ==", + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-wasm32-wasi/-/oxide-wasm32-wasi-4.3.5.tgz", + "integrity": "sha512-OJhFmlEfdzMr+avACdi40RPtnkW0B6hXyxL/8r+tnEHBWZji36CYRjEXrrvgBmaYsD3oEOBqwYFRKsYvzFe7Bw==", "bundleDependencies": [ "@napi-rs/wasm-runtime", "@emnapi/core", @@ -1263,37 +1042,34 @@ "@emnapi/wasi-threads", "tslib" ], - "cpu": [ - "wasm32" - ], "dev": true, "license": "MIT", "optional": true, "dependencies": { - "@emnapi/core": "^1.11.1", - "@emnapi/runtime": "^1.11.1", - "@emnapi/wasi-threads": "^1.2.2", - "@napi-rs/wasm-runtime": "^1.1.4", - "@tybys/wasm-util": "^0.10.2", + "@emnapi/core": "^1.11.3", + "@emnapi/runtime": "^1.11.3", + "@emnapi/wasi-threads": "^1.2.3", + "@napi-rs/wasm-runtime": "^1.2.2", + "@tybys/wasm-util": "^0.10.3", "tslib": "^2.8.1" }, "engines": { - "node": ">=14.0.0" + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" } }, "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core": { - "version": "1.11.1", + "version": "1.11.3", "dev": true, "inBundle": true, "license": "MIT", "optional": true, "dependencies": { - "@emnapi/wasi-threads": "1.2.2", + "@emnapi/wasi-threads": "1.2.3", "tslib": "^2.4.0" } }, "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime": { - "version": "1.11.1", + "version": "1.11.3", "dev": true, "inBundle": true, "license": "MIT", @@ -1303,7 +1079,7 @@ } }, "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads": { - "version": "1.2.2", + "version": "1.2.3", "dev": true, "inBundle": true, "license": "MIT", @@ -1313,25 +1089,28 @@ } }, "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime": { - "version": "1.1.4", + "version": "1.2.2", "dev": true, "inBundle": true, "license": "MIT", "optional": true, "dependencies": { - "@tybys/wasm-util": "^0.10.1" + "@tybys/wasm-util": "^0.10.3" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" }, "funding": { "type": "github", "url": "https://github.com/sponsors/Brooooooklyn" }, "peerDependencies": { - "@emnapi/core": "^1.7.1", - "@emnapi/runtime": "^1.7.1" + "@emnapi/core": "^1.7.1 || ^2.0.0-alpha.3", + "@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.3" } }, "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util": { - "version": "0.10.2", + "version": "0.10.3", "dev": true, "inBundle": true, "license": "MIT", @@ -1348,9 +1127,9 @@ "optional": true }, "node_modules/@tailwindcss/oxide-win32-arm64-msvc": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.3.3.tgz", - "integrity": "sha512-3rc292Ca2ceK6Ulcc/bAVnTs/3nDtoPhyEKlgPv+yQJQi/JS/AMJlqzxvlDacL1nekbrcf6bTqp/jV4qgnPxNQ==", + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.3.5.tgz", + "integrity": "sha512-9o8jgthi+QE5eandnboiJT64VQfnIArfZzSTdgbhEK5aafdiu2jTW9Honi/mwYHxBZuH1vAC57IFyrh+0iK5Gg==", "cpu": [ "arm64" ], @@ -1365,9 +1144,9 @@ } }, "node_modules/@tailwindcss/oxide-win32-x64-msvc": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-x64-msvc/-/oxide-win32-x64-msvc-4.3.3.tgz", - "integrity": "sha512-yJ0pwIVc/nYeGoV02WtsN8KYyLQv7kyI2wDnkezyJlGGjkd4QLwDGAwl47YpPJeuI0M0ObaXGSPjvWDPeTPggw==", + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-x64-msvc/-/oxide-win32-x64-msvc-4.3.5.tgz", + "integrity": "sha512-XiKFfIy1RWe7qK4WqByxNW7Oz1/nkOy8o/BWhHminyV1PmpUd8Eedj5v2A8h2kpqeVlz6xRnwk9Fr/ZXNLcZfg==", "cpu": [ "x64" ], @@ -1382,17 +1161,17 @@ } }, "node_modules/@tailwindcss/postcss": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@tailwindcss/postcss/-/postcss-4.3.3.tgz", - "integrity": "sha512-JTSZZGQi1AyKirbLN3azmjVzef92tcX7h+iSqPdaeStyFpGpDlKvvpxeOE8njhbUanbRwr3z8DyzhICWnMtQeg==", + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/postcss/-/postcss-4.3.5.tgz", + "integrity": "sha512-FAV37Tlx9wBiT/hkfgVD0Q6CWsP2oUX3lf28nrfjW8+ksILjnpuFulUqWDfNR4/ZiEHHDRBX8DUTzD1Rys687A==", "dev": true, "license": "MIT", "dependencies": { "@alloc/quick-lru": "^5.2.0", - "@tailwindcss/node": "4.3.3", - "@tailwindcss/oxide": "4.3.3", - "postcss": "^8.5.16", - "tailwindcss": "4.3.3" + "@tailwindcss/node": "4.3.5", + "@tailwindcss/oxide": "4.3.5", + "postcss": "^8.5.25", + "tailwindcss": "4.3.5" } }, "node_modules/@types/estree": { @@ -2021,9 +1800,9 @@ "license": "ISC" }, "node_modules/enhanced-resolve": { - "version": "5.24.5", - "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.24.5.tgz", - "integrity": "sha512-L1l8TNvomm6UVW5B253AGxQagSQr+vGwhMlrrfRS2qmhx46AMpMVJKQYLvWYbysTMY8VoicOvzHzoHMbyzB+4A==", + "version": "5.26.1", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.26.1.tgz", + "integrity": "sha512-PPnnSJq3azKOIewXR/uppBV/6h98dprBJ/WaQ9Qgj10xX1lJLNfg+XShpbsrSqcDSy2yYYyhfXM1wWhftqgyzw==", "dev": true, "license": "MIT", "dependencies": { @@ -2446,9 +2225,9 @@ } }, "node_modules/lucide-react": { - "version": "1.66.0", - "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.66.0.tgz", - "integrity": "sha512-8zjbi/Us+ETXqfBwmXF/FHrWGIqOdE6zT1yUdRJLQVoptomSkB0zdFWVIM667t9K8djWDaXdkBkqi2qVTuDNiw==", + "version": "1.70.0", + "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.70.0.tgz", + "integrity": "sha512-gCTPPN1MlQUBtUgdsUv+0CAUj+X8hifRUiRBw4E5v7lvDIOIpx0EZezdGQMSimS8pKA6esvullJub4GYr0mCHA==", "license": "ISC", "peerDependencies": { "@types/react": "*", @@ -2563,9 +2342,9 @@ } }, "node_modules/postcss": { - "version": "8.5.30", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.30.tgz", - "integrity": "sha512-zkd+e9S1AQHhmaBKye9zlFHWjOwVgqXl1q3ECYy8561K7qxR2cREf/STLskulBFd78k6AOFeA+ff1TtEzk9bAA==", + "version": "8.5.32", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.32.tgz", + "integrity": "sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==", "dev": true, "funding": [ { @@ -2592,9 +2371,9 @@ } }, "node_modules/preact": { - "version": "11.1.1", - "resolved": "https://registry.npmjs.org/preact/-/preact-11.1.1.tgz", - "integrity": "sha512-vpFVfai437pbuLri7XVeslCPfrEZX6Z1S2gV+MOFrA/kji+NKUXvH7y01EnVjA1guLigfkVp77Sqipd4SIllCg==", + "version": "11.2.0", + "resolved": "https://registry.npmjs.org/preact/-/preact-11.2.0.tgz", + "integrity": "sha512-/HfHI/7N84e6GrWBJ3J280z3mLaRJiDcSvj/A+y/4AbLnND/1UlGHe1sR6oYuTGwId0nP7dqDU9OnLxMPZ7xBg==", "license": "MIT", "funding": { "type": "opencollective", @@ -2630,13 +2409,13 @@ } }, "node_modules/rolldown": { - "version": "1.2.14", - "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.14.tgz", - "integrity": "sha512-eTBTTqMR6uHKLgcUqpJP8ntzDI6V4LYA8negAMBEI7gkgVvOdrx6VsvS2Ym+83KhOPdLCHWJu0w7UQFJZhHKNw==", + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.16.tgz", + "integrity": "sha512-bWvlMpFKiTfDKfnK7FC2MPgPeWCf/Kpwsq49ApdW+FQaBZb6O6dZ4MAPbPUjp7hYQrw/RobqCzn64BRrQecGHw==", "dev": true, "license": "MIT", "dependencies": { - "@oxc-project/types": "=0.154.0", + "@oxc-project/types": "=0.156.0", "@rolldown/pluginutils": "^1.0.0" }, "bin": { @@ -2646,21 +2425,21 @@ "node": "^20.19.0 || >=22.12.0" }, "optionalDependencies": { - "@rolldown/binding-android-arm-eabi": "1.2.14", - "@rolldown/binding-android-arm64": "1.2.14", - "@rolldown/binding-darwin-arm64": "1.2.14", - "@rolldown/binding-darwin-x64": "1.2.14", - "@rolldown/binding-freebsd-x64": "1.2.14", - "@rolldown/binding-linux-arm-gnueabihf": "1.2.14", - "@rolldown/binding-linux-arm64-gnu": "1.2.14", - "@rolldown/binding-linux-arm64-musl": "1.2.14", - "@rolldown/binding-linux-ppc64-gnu": "1.2.14", - "@rolldown/binding-linux-s390x-gnu": "1.2.14", - "@rolldown/binding-linux-x64-gnu": "1.2.14", - "@rolldown/binding-linux-x64-musl": "1.2.14", - "@rolldown/binding-openharmony-arm64": "1.2.14", - "@rolldown/binding-win32-arm64-msvc": "1.2.14", - "@rolldown/binding-win32-x64-msvc": "1.2.14" + "@rolldown/binding-android-arm-eabi": "1.2.16", + "@rolldown/binding-android-arm64": "1.2.16", + "@rolldown/binding-darwin-arm64": "1.2.16", + "@rolldown/binding-darwin-x64": "1.2.16", + "@rolldown/binding-freebsd-x64": "1.2.16", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.16", + "@rolldown/binding-linux-arm64-gnu": "1.2.16", + "@rolldown/binding-linux-arm64-musl": "1.2.16", + "@rolldown/binding-linux-ppc64-gnu": "1.2.16", + "@rolldown/binding-linux-s390x-gnu": "1.2.16", + "@rolldown/binding-linux-x64-gnu": "1.2.16", + "@rolldown/binding-linux-x64-musl": "1.2.16", + "@rolldown/binding-openharmony-arm64": "1.2.16", + "@rolldown/binding-win32-arm64-msvc": "1.2.16", + "@rolldown/binding-win32-x64-msvc": "1.2.16" } }, "node_modules/semver": { @@ -2724,9 +2503,9 @@ } }, "node_modules/tailwindcss": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.3.3.tgz", - "integrity": "sha512-gOhV3P7ufE62QDGg1zVaTgCR+EtPv92k2nIhVcVKcLmxT1sUBsQGhnZj175j+MqRt4zLF7ic+sCYjfhxMxj7YQ==", + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.3.5.tgz", + "integrity": "sha512-FcQk9BuffmEHJP2G0XmB2SplU1aLTI7j07Kunk+U74Ny+XiWOtzXz9aujFZ/avntw1e2cOv/3PkgzflQ7gX2vQ==", "dev": true, "license": "MIT" }, @@ -2835,16 +2614,16 @@ } }, "node_modules/vite": { - "version": "8.3.5", - "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.5.tgz", - "integrity": "sha512-z1YpjieJ9g0ebTmQpLBv/oq9E3F9EIlOe+7LahW8SrE3LTiG3udBRUXQOlYXP9b+IC2q2phHeVxj9xGlw34OEQ==", + "version": "8.3.6", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.6.tgz", + "integrity": "sha512-UI7dK29NnS54Fk+mmo7o+jI6U8Fp7hDl+X5Q1k45WH+d4dSlbLVUETGQ+hfkNgvLQGyoElPj837nZyv4MBc0VA==", "dev": true, "license": "MIT", "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.7", - "postcss": "^8.5.30", - "rolldown": "~1.2.14", + "postcss": "^8.5.32", + "rolldown": "~1.2.16", "tinyglobby": "^0.2.17" }, "bin": { diff --git a/report/package.json b/report/package.json index 76619b3631..c7b711ef00 100644 --- a/report/package.json +++ b/report/package.json @@ -11,22 +11,22 @@ "dependencies": { "clsx": "^2.1.1", "dompurify": "^3.4.17", - "lucide-react": "^1.66.0", + "lucide-react": "^1.70.0", "marked": "^18.1.3", - "preact": "^11.1.1", + "preact": "^11.2.0", "react": "npm:@preact/compat@^18.3.2", "react-dom": "npm:@preact/compat@^18.3.2", "tailwind-merge": "^3.7.0" }, "devDependencies": { "@preact/preset-vite": "^2.10.6", - "@tailwindcss/postcss": "^4.3.3", + "@tailwindcss/postcss": "^4.3.5", "@types/node": "^26.6.6", "@types/react": "^19.3.0", "@types/react-dom": "^19.3.0", "tailwindcss": "~4.3.3", "typescript": "^7.0.2", - "vite": "^8.3.5", + "vite": "^8.3.6", "vite-plugin-singlefile": "^2.3.4" }, "engines": { diff --git a/report/src/components/report/ReportContext.tsx b/report/src/components/report/ReportContext.tsx index e357e388d0..ae456cb363 100644 --- a/report/src/components/report/ReportContext.tsx +++ b/report/src/components/report/ReportContext.tsx @@ -8,11 +8,14 @@ import { createContext, useCallback, useContext, useMemo, useState, type ReactNo import { useTenant } from "@/context/TenantContext" import { useLocation, useNavigate } from "@/lib/router" import { buildModel, sortTests, type Model } from "@/lib/model" +import { STANDARD_COLUMNS } from "./lists" export interface Explorer { q: string filters: Record group: string + /** The column the list is sorted by, "-" first for descending; empty for the usual order. */ + sort: string } interface ReportContextValue { @@ -34,8 +37,13 @@ interface ReportContextValue { setExplorer: (patch: Partial) => void tab: string setTab: (tab: string) => void + /** The optional columns test lists show, in every list; the reader's browser remembers them. */ + columns: string[] + setColumns: (keys: string[] | ((current: string[]) => string[])) => void } +const COLUMNS_KEY = "maester.report.columns" + const ReportContext = createContext(null) function decode(value: string) { @@ -48,8 +56,22 @@ export function ReportProvider({ children }: { children: ReactNode }) { const model = models[selectedIndex] ?? models[0] const location = useLocation() const navigate = useNavigate() - const [explorer, setExplorerState] = useState({ q: "", filters: {}, group: "none" }) + const [explorer, setExplorerState] = useState({ q: "", filters: {}, group: "none", sort: "" }) const [tab, setTab] = useState("finding") + const [columns, setColumnsState] = useState(() => { + try { + const saved = JSON.parse(localStorage.getItem(COLUMNS_KEY) || "null") + if (Array.isArray(saved) && saved.every((k) => typeof k === "string")) return saved + } catch { /* no storage: the standard columns */ } + return STANDARD_COLUMNS + }) + const setColumns = useCallback((keys: string[] | ((current: string[]) => string[])) => { + setColumnsState((current) => { + const next = typeof keys === "function" ? keys(current) : keys + try { localStorage.setItem(COLUMNS_KEY, JSON.stringify(next)) } catch { /* not remembered */ } + return next + }) + }, []) const [list, setList] = useState([]) const fromHash = location.hash.length > 1 ? decode(location.hash.slice(1)) : null @@ -73,13 +95,13 @@ export function ReportProvider({ children }: { children: ReactNode }) { }, [navigate, setSelectedIndex]) const setExplorer = useCallback((patch: Partial) => setExplorerState((e) => ({ ...e, ...patch })), []) const explore = useCallback((patch: Partial) => { - setExplorerState({ q: "", filters: {}, group: "none", ...patch }) + setExplorerState({ q: "", filters: {}, group: "none", sort: "", ...patch }) navigate("/tests") }, [navigate]) const value = useMemo( - () => ({ model, models, multi: models.length > 1, tenantIndex: selectedIndex, selectTenant, openId, openTest, sequence, closeTest, explorer, explore, setExplorer, tab, setTab }), - [model, models, selectedIndex, selectTenant, openId, openTest, sequence, closeTest, explorer, explore, setExplorer, tab], + () => ({ model, models, multi: models.length > 1, tenantIndex: selectedIndex, selectTenant, openId, openTest, sequence, closeTest, explorer, explore, setExplorer, tab, setTab, columns, setColumns }), + [model, models, selectedIndex, selectTenant, openId, openTest, sequence, closeTest, explorer, explore, setExplorer, tab, columns, setColumns], ) return {children} } diff --git a/report/src/components/report/lists.tsx b/report/src/components/report/lists.tsx index 6265037834..1ec02688f7 100644 --- a/report/src/components/report/lists.tsx +++ b/report/src/components/report/lists.tsx @@ -1,9 +1,10 @@ // Lists of tests: the table every view uses, with optional grouping, and the ranked "fix these first" list. -import { RESULT_LABEL, isQuickWin, maesterVersion, sortTests, tally, type Model, type Row } from "@/lib/model" +import { useEffect, useRef, useState, type ReactNode } from "react" +import { RESULT_LABEL, RESULT_ORDER, SEVERITIES, isQuickWin, maesterVersion, sortTests, tally, type Model, type Row } from "@/lib/model" import { reportHeading } from "@/lib/runSubject" import { useReport } from "./ReportContext" -import { FeatureMark, Pill, ProductMark, Sev } from "./ui" +import { FeatureMark, Icon, Pill, ProductMark, Sev } from "./ui" export const GROUPS: Record = { none: "No grouping", product: "Product", area: "Area", feature: "Feature", severity: "Severity", source: "Source", result: "Result" } @@ -12,6 +13,135 @@ export function sourceLabel(model: Model, t: Row) { return pack ? pack.Name : t.Suite || t.Source || "" } +const rank = (order: string[], value: string) => { const i = order.indexOf(value); return i === -1 ? order.length : i } +const text = (a: string, b: string) => a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }) +const LEVELS = ["Low", "Medium", "High"] + +interface Column { + key: string + label: string + /** Always shown: the result and the test. */ + fixed?: boolean + /** Shown until the reader picks other columns. */ + standard?: boolean + /** Hidden on narrow screens. */ + wide?: boolean + /** The text a column sorts by; empty when the test has none. */ + value: (model: Model, t: Row) => string + compare?: (a: string, b: string) => number + cell: (model: Model, t: Row) => ReactNode +} + +const plain = (v: string | null | undefined) => (v ? {v} : —) +const codes = (list: string[]) => list.length ? {list.slice(0, 2).join(", ")}{list.length > 2 && +{list.length - 2}} : — + +// The columns a test list can show and sort by. Ascending is the order a reader looks for first: failures first, +// the most severe first, the least effort first, A to Z. A second click on a column reverses it, a third goes back +// to the usual order. +export const COLUMNS: Column[] = [ + { key: "result", label: "Result", fixed: true, value: (_, t) => t.Result, compare: (a, b) => rank(RESULT_ORDER, a) - rank(RESULT_ORDER, b), cell: (_, t) => }, + { key: "id", label: "Test", fixed: true, value: (_, t) => t.Id, compare: (a, b) => a.localeCompare(b, undefined, { numeric: true }), + cell: (_, t) =>
{t.Title}{t.Id}
}, + { key: "product", label: "Product", standard: true, wide: true, value: (m, t) => (t.Product ? m.productName(t.Product) : ""), + cell: (m, t) => {m.productName(t.Product)} }, + { key: "feature", label: "Feature", wide: true, value: (m, t) => (t.Feature ? m.featureName(t) : ""), + cell: (m, t) => (t.Feature ? {m.featureName(t)} : plain(null)) }, + { key: "area", label: "Area", wide: true, value: (m, t) => (t.Area ? m.areaName(t.Area) : ""), cell: (m, t) => plain(t.Area ? m.areaName(t.Area) : null) }, + { key: "severity", label: "Severity", standard: true, value: (_, t) => (SEVERITIES.includes(t.Severity) ? t.Severity : ""), compare: (a, b) => rank(SEVERITIES, a) - rank(SEVERITIES, b), cell: (_, t) => }, + { key: "impact", label: "User impact", wide: true, value: (_, t) => t.UserImpact || "", compare: (a, b) => rank(LEVELS, a) - rank(LEVELS, b), cell: (_, t) => plain(t.UserImpact) }, + { key: "effort", label: "Effort", wide: true, value: (_, t) => t.ImplementationCost || "", compare: (a, b) => rank(LEVELS, a) - rank(LEVELS, b), cell: (_, t) => plain(t.ImplementationCost) }, + { key: "resource", label: "Resource", wide: true, value: (_, t) => t.ResourceType || "", cell: (_, t) => plain(t.ResourceType) }, + { key: "mitre", label: "ATT&CK", wide: true, value: (_, t) => t.Mitre.join(", "), cell: (_, t) => codes(t.Mitre) }, + { key: "control", label: "Controls", wide: true, value: (_, t) => t.Control.join(", "), cell: (_, t) => codes(t.Control) }, + { key: "source", label: "Source", standard: true, wide: true, value: (m, t) => sourceLabel(m, t), cell: (m, t) => {sourceLabel(m, t)} }, + { key: "duration", label: "Duration", wide: true, value: (_, t) => t.Duration || "", cell: (_, t) => {t.Duration || "—"} }, +] + +export const STANDARD_COLUMNS = COLUMNS.filter((c) => c.standard).map((c) => c.key) + +/** The rows in the order of a sort ("severity", "-id"), or the usual order when there is none. Rows without a value + * (no severity, no product) stay last either way; ties keep the usual order. */ +export function sortRows(model: Model, rows: Row[], sort: string) { + const usual = sortTests(rows) + const column = COLUMNS.find((c) => c.key === sort.replace(/^-/, "")) + if (!column) return usual + const compare = column.compare ?? text + const dir = sort.startsWith("-") ? -1 : 1 + return usual.sort((a, b) => { + const x = column.value(model, a), y = column.value(model, b) + return !x || !y ? Number(!x) - Number(!y) : dir * compare(x, y) + }) +} + +/** The optional columns a report can show (those some test has a value for) and the columns a list shows. */ +export function visibleColumns(model: Model, chosen: string[]) { + const available = COLUMNS.filter((c) => !c.fixed && (c.standard || model.rows.some((t) => c.value(model, t)))) + const shown = COLUMNS.filter((c) => c.fixed || (chosen.includes(c.key) && available.includes(c))) + return { available, shown } +} + +/** The sort, or none when its column is not shown. */ +export const shownSort = (shown: Column[], sort: string) => (shown.some((c) => c.key === sort.replace(/^-/, "")) ? sort : "") + +/** The rows of a list in the order it shows them: sorted, then gathered into groups when it is grouped. */ +export function groupRows(model: Model, rows: Row[], group: string, sort: string) { + const sorted = sortRows(model, rows, sort) + let groups: [string, Row[]][] = [] + if (group !== "none") { + const byKey = new Map() + for (const t of sorted) { const k = groupKey(model, group, t); if (!byKey.has(k)) byKey.set(k, []); byKey.get(k)!.push(t) } + // Sorted by the column the list is grouped by, the groups follow the sort (the rows are already in its order, + // tests without a value last); otherwise the groups with the most failures come first. A pack's own field can + // share a column's name (id) without being that column, so only Maester's groupings count. + groups = group in GROUPS && sort.replace(/^-/, "") === group ? [...byKey.entries()] : [...byKey.entries()].sort((a, b) => tally(b[1]).Failed - tally(a[1]).Failed) + } + return { sorted, groups, ordered: group === "none" ? sorted : groups.flatMap(([, list]) => list) } +} + +/** The button that picks the columns a test list shows, for every list in the report. */ +function ColumnPicker({ chosen, onChange, available }: { chosen: string[]; onChange: (keys: string[] | ((current: string[]) => string[])) => void; available: Column[] }) { + const [open, setOpen] = useState(false) + const [at, setAt] = useState({ top: 0, right: 0 }) + const root = useRef(null) + // The list is placed against the window: the table's scrolling box would clip it. + const place = () => { + const r = root.current?.getBoundingClientRect() + if (r) setAt({ top: r.bottom + 6, right: Math.max(8, window.innerWidth - r.right) }) + } + useEffect(() => { + if (!open) return + const close = () => { setOpen(false) } + window.addEventListener("scroll", close, true) + window.addEventListener("resize", close) + const away = (e: MouseEvent) => { if (!root.current?.contains(e.target as Node)) setOpen(false) } + const esc = (e: KeyboardEvent) => { if (e.key === "Escape") { e.stopPropagation(); setOpen(false); root.current?.querySelector("button")?.focus() } } + document.addEventListener("mousedown", away) + document.addEventListener("keydown", esc, true) + return () => { document.removeEventListener("mousedown", away); document.removeEventListener("keydown", esc, true); window.removeEventListener("scroll", close, true); window.removeEventListener("resize", close) } + }, [open]) + const showColumn = (key: string, on: boolean) => { onChange((current) => COLUMNS.filter((c) => !c.fixed && (c.key === key ? on : current.includes(c.key))).map((c) => c.key)) } + return ( +
+ + {open && ( +
+
Columns
+ {available.map((c) => ( + + ))} + +
+ )} +
+ ) +} + +const nextSort = (sort: string, key: string) => (sort === key ? `-${key}` : sort === `-${key}` ? "" : key) + function groupKey(model: Model, group: string, t: Row): string { switch (group) { case "product": return model.productName(t.Product) @@ -28,24 +158,22 @@ function groupKey(model: Model, group: string, t: Row): string { } } -export function TestTable({ rows, group = "none", empty = "No tests match these filters." }: { rows: Row[]; group?: string; empty?: string }) { - const { model, openTest } = useReport() - const sorted = sortTests(rows) - let groups: [string, Row[]][] = [] - if (group !== "none") { - const byKey = new Map() - for (const t of sorted) { const k = groupKey(model, group, t); if (!byKey.has(k)) byKey.set(k, []); byKey.get(k)!.push(t) } - groups = [...byKey.entries()].sort((a, b) => tally(b[1]).Failed - tally(a[1]).Failed) - } - const order = (group === "none" ? sorted : groups.flatMap(([, list]) => list)).map((t) => t.Id) +export function TestTable({ rows, group = "none", empty = "No tests match these filters.", sort: sortProp, onSort }: { rows: Row[]; group?: string; empty?: string; sort?: string; onSort?: (sort: string) => void }) { + const { model, openTest, columns: chosen, setColumns } = useReport() + // Columns no test in the report has a value for are left out of the table and the picker. + const { available, shown } = visibleColumns(model, chosen) + // A list keeps its own sort unless the page holds it (the All tests page keeps it with its filters). + const [ownSort, setOwnSort] = useState("") + const sort = sortProp ?? ownSort + const setSort = onSort ?? setOwnSort + // A sort by a column the reader has hidden is ignored: the order would have no header to show it or undo it. + const { sorted, groups, ordered } = groupRows(model, rows, group, shownSort(shown, sort)) + const order = ordered.map((t) => t.Id) const open = (id: string) => openTest(id, order) const row = (t: Row) => ( open(t.Id)} onKeyDown={(e) => { if (e.key === "Enter") open(t.Id) }}> - -
{t.Title}{t.Id}
- {model.productName(t.Product)} - - {sourceLabel(model, t)} + {shown.map((c) => {c.cell(model, t)})} + ) let body @@ -53,14 +181,23 @@ export function TestTable({ rows, group = "none", empty = "No tests match these else { body = groups.flatMap(([k, list]) => { const c = tally(list) - return [{group === "feature" && }{group === "product" && }{k} · {c.Failed} failed of {c.total}, ...list.map(row)] + return [{group === "feature" && }{group === "product" && }{k} · {c.Failed} failed of {c.total}, ...list.map(row)] }) } return (
- - {rows.length ? body : } + {shown.map((c) => { + const dir = sort === c.key ? "ascending" : sort === `-${c.key}` ? "descending" : undefined + return ( + + ) + })} + {rows.length ? body : }
ResultTestProductSeveritySource
{empty}
+ +
{empty}
) diff --git a/report/src/components/report/ui.tsx b/report/src/components/report/ui.tsx index bf519e5306..6478727f8e 100644 --- a/report/src/components/report/ui.tsx +++ b/report/src/components/report/ui.tsx @@ -66,6 +66,7 @@ const ICON: Record = { report: "M6 3h9l4 4v14H6zM14 3v5h5M9 13h7M9 17h5", tenant: "M4 21V6l8-3 8 3v15M9 9h1M14 9h1M9 13h1M14 13h1M10 21v-4h4v4", chevron: "M6 9l6 6 6-6", + columns: "M4 4h16v16H4zM9.5 4v16M14.5 4v16", prev: "M15 6l-6 6 6 6", home: "M3 11l9-7 9 7M5 10v10h14V10M10 20v-5h4v5", check: "M5 12l5 5 9-10", diff --git a/report/src/lib/model.ts b/report/src/lib/model.ts index 36989bd06a..a8a116e8c8 100644 --- a/report/src/lib/model.ts +++ b/report/src/lib/model.ts @@ -51,10 +51,11 @@ export const TACTICS: [string, string][] = [ export const FRAMEWORK_LABEL: Record = { "cis-m365": "CIS Microsoft 365", "cis-github": "CIS GitHub", "cisa-scuba": "CISA SCuBA", "essential-eight": "Essential Eight", ism: "ASD ISM", "nist-800-53-r5": "NIST SP 800-53", + "disa-stig-entra-id": "DISA STIG Entra ID", "disa-stig-intune-mdm": "DISA STIG Intune MDM", "disa-stig-intune-desktop": "DISA STIG Intune Desktop", } -// The order frameworks are listed in everywhere: NIST, CISA, CIS, then ASD's ISM and Essential Eight, then any other. -const FRAMEWORK_ORDER = ["nist-800-53-r5", "cisa-scuba", "cis-m365", "cis-github", "ism", "essential-eight"] +// The order frameworks are listed in everywhere: NIST, CISA, CIS, then ASD's ISM and Essential Eight, then the DISA STIGs, then any other. +const FRAMEWORK_ORDER = ["nist-800-53-r5", "cisa-scuba", "cis-m365", "cis-github", "ism", "essential-eight", "disa-stig-entra-id", "disa-stig-intune-mdm", "disa-stig-intune-desktop"] export const frameworkRank = (key: string) => (FRAMEWORK_ORDER.indexOf(key) + 1 || FRAMEWORK_ORDER.length + 1) // Why a test did not run, as a heading and what to do about it. Codes: website/docs/configuration/applicability.md. diff --git a/report/src/pages/report/FrameworkPage.tsx b/report/src/pages/report/FrameworkPage.tsx index ec0fc9a1ea..72ea81b775 100644 --- a/report/src/pages/report/FrameworkPage.tsx +++ b/report/src/pages/report/FrameworkPage.tsx @@ -11,13 +11,14 @@ import { Segmented } from "./ProductPage" const CIS_SECTIONS: Record = { 1: "Microsoft 365 admin center", 2: "Microsoft 365 Defender", 3: "Microsoft Purview", 4: "Microsoft Intune", 5: "Microsoft Entra admin center", 6: "Exchange admin center", 7: "SharePoint admin center", 8: "Microsoft Teams admin center", 9: "Microsoft Fabric" } const CISA_SERVICES: Record = { "MS.AAD": "Entra ID", "MS.DEFENDER": "Defender", "MS.EXO": "Exchange Online", "MS.POWERBI": "Power BI", "MS.POWERPLATFORM": "Power Platform", "MS.SHAREPOINT": "SharePoint", "MS.TEAMS": "Teams", "MS.SECURITYSUITE": "Security suite" } -// The framework's own structure: CIS sections, CISA services, Essential Eight strategies, ISM guidelines, NIST families. +// The framework's own structure: CIS sections, CISA services, Essential Eight strategies, ISM guidelines, DISA STIG categories, NIST families. function sectionOf(key: string, r: Record): string { const id = String(r.Id) if (key.startsWith("cis-")) { const s = id.split(".")[0]; return CIS_SECTIONS[s] ? `${s} · ${CIS_SECTIONS[s]}` : s } if (key === "cisa-scuba") { const s = id.split(".").slice(0, 2).join("."); return CISA_SERVICES[s] ? `${s} · ${CISA_SERVICES[s]}` : s } if (key === "essential-eight") return (Array.isArray(r.Strategy) ? r.Strategy[0] : r.Strategy) as string || "Other" if (key === "ism") return (r.Guideline as string) || "Other" + if (key.startsWith("disa-stig-")) return (r.Category as string) || "Other" if (key.startsWith("nist")) return (r.Family as string) || id.split("-")[0] return "Requirements" } @@ -28,8 +29,8 @@ export default function FrameworkPage({ frameworkKey }: { frameworkKey: string } const [show, setShow] = useState("all") const f = model.frameworks.find((x) => x.Key === frameworkKey) if (!f) return

No tests map to this framework

- const levels = ["All", ...new Set(f.Requirements.map((r) => String(r.Level || r.Criticality || "")).filter(Boolean))].sort((a, b) => (a === "All" ? -1 : b === "All" ? 1 : a.localeCompare(b))) - const requirements = f.Requirements.filter((r) => level === "All" || r.Level === level || r.Criticality === level) + const levels = ["All", ...new Set(f.Requirements.map((r) => String(r.Level || r.Criticality || r.Category || "")).filter(Boolean))].sort((a, b) => (a === "All" ? -1 : b === "All" ? 1 : a.localeCompare(b))) + const requirements = f.Requirements.filter((r) => level === "All" || r.Level === level || r.Criticality === level || r.Category === level) const c = frameworkTally(model, f, requirements) const sections = new Map() for (const r of requirements) { const s = sectionOf(f.Key, r); if (!sections.has(s)) sections.set(s, []); sections.get(s)!.push(r) } diff --git a/report/src/pages/report/TestsPage.tsx b/report/src/pages/report/TestsPage.tsx index ea4a66e18f..9d788df841 100644 --- a/report/src/pages/report/TestsPage.tsx +++ b/report/src/pages/report/TestsPage.tsx @@ -3,7 +3,7 @@ import { useMemo } from "react" import { RESULT_LABEL, RESULT_ORDER, SEVERITIES, frameworkLabel, frameworkRank, requirementsOf, type Row } from "@/lib/model" import { useReport } from "@/components/report/ReportContext" -import { Footer, GROUPS, TestTable, sourceLabel } from "@/components/report/lists" +import { Footer, GROUPS, TestTable, groupRows, shownSort, sourceLabel, visibleColumns } from "@/components/report/lists" import { Dropdown, FeatureMark, Icon, ProductMark, copyText, type IconName } from "@/components/report/ui" const GROUP_ICON: Record = { product: "product", area: "area", feature: "feature", severity: "severity", source: "source", result: "result" } @@ -11,8 +11,8 @@ const GROUP_ICON: Record = { product: "product", area: "area", interface Dimension { key: string; icon: IconName; values: (t: Row) => string[]; label: (v: string) => string; order?: string[]; rank?: (v: string) => number } export default function TestsPage() { - const { model, explorer, setExplorer } = useReport() - const { q, filters, group } = explorer + const { model, explorer, setExplorer, columns } = useReport() + const { q, filters, group, sort } = explorer const dims: Dimension[] = useMemo(() => ([ { key: "Result", icon: "result", values: (t) => [t.Result], label: (v) => RESULT_LABEL[v] || v, order: RESULT_ORDER }, { key: "Severity", icon: "severity", values: (t) => (SEVERITIES.includes(t.Severity) ? [t.Severity] : model.rated.severity ? ["Not rated"] : []), label: (v) => v, order: [...SEVERITIES, "Not rated"] }, @@ -34,9 +34,9 @@ export default function TestsPage() { if (on) set.add(value); else set.delete(value) setExplorer({ filters: { ...filters, [key]: [...set] } }) } - // Every cell is escaped: an ID can come from a Pester test name, which may hold a pipe or a line break. + // The rows in the order the table shows them, groups included. Every cell is escaped: an ID can come from a Pester test name, which may hold a pipe or a line break. const cell = (v: unknown) => String(v ?? "").replace(/[\\|]/g, "\\$&").replace(/\r?\n/g, " ") - const copyRows = () => copyText(["| Result | ID | Title | Severity | Product |", "| --- | --- | --- | --- | --- |", ...rows.map((t) => `| ${[t.Result, t.Id, t.Title, t.Severity, model.productName(t.Product)].map(cell).join(" | ")} |`)].join("\n"), `Copied ${rows.length} rows`) + const copyRows = () => copyText(["| Result | ID | Title | Severity | Product |", "| --- | --- | --- | --- | --- |", ...groupRows(model, rows, group, shownSort(visibleColumns(model, columns).shown, sort)).ordered.map((t) => `| ${[t.Result, t.Id, t.Title, t.Severity, model.productName(t.Product)].map(cell).join(" | ")} |`)].join("\n"), `Copied ${rows.length} rows`) const groups = Object.keys(GROUPS).filter((g) => g !== "feature" || model.hasAttributes) return ( @@ -71,7 +71,7 @@ export default function TestsPage() { options={groups.map((g) => ({ value: g, label: GROUPS[g], icon: GROUP_ICON[g] ? : undefined }))} /> {filtered && } - + setExplorer({ sort: s })} />