From 3910fd79cab2558f0643f25e5b6d51f350109694 Mon Sep 17 00:00:00 2001 From: Roy Klooster <76492458+royklo@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:37:12 +0100 Subject: [PATCH 1/8] feat: one tenant read for several -Baseline, and documents show every configured setting Export-InforcerTenantDocumentation -Baseline takes several baselines and reads the tenant once; 22 Blueprint baselines took 48 s instead of about 34 min. Readability fixes, found by reading every per-baseline document of the inforcer Blueprint Library: - settings nested more than two objects deep rendered as empty rows (CA device filter rules, guest user types, passkey migration opt-out); - a dotted @odata.type setting was dropped (Entra device registration); - list items showed only "N items" (authentication method Include Targets); - authentication strength combinations were split into single methods. Release 1.1.0 (MINOR: new capability). Tests: Fix.DocReadability.Tests.ps1, 14 tests; 12 fail on main for the reason they name, 2 guard existing behaviour. Full suite 863 passed, 1 environment-dependent failure also on main. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 15 + Tests/Fix.DocReadability.Tests.ps1 | 152 ++++++++++ docs/CMDLET-REFERENCE.md | 2 +- module/InforcerCommunity.psd1 | 4 +- module/Private/ConvertTo-InforcerDocModel.ps1 | 10 +- .../Private/ConvertTo-InforcerSettingRows.ps1 | 92 +++--- .../Export-InforcerTenantDocumentation.ps1 | 276 ++++++++++-------- 7 files changed, 384 insertions(+), 167 deletions(-) create mode 100644 Tests/Fix.DocReadability.Tests.ps1 diff --git a/CHANGELOG.md b/CHANGELOG.md index 0282a12..a193d5e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,21 @@ All notable changes to this project will be documented in this file. The format follows [Conventional Commits](https://www.conventionalcommits.org/) and [Semantic Versioning](https://semver.org/): a new feature or capability bumps MINOR, a bug fix or performance change that leaves the public surface alone bumps PATCH, and docs/tests/chore-only commits don't bump. While the module is pre-1.0 a breaking change also bumps MINOR and is called out under a **Breaking Changes** heading — 1.0.0 is reserved for the point the public surface is declared stable, after which breaking changes bump MAJOR. There is intentionally no `[Unreleased]` section — every entry is dated at ship time. +## [1.1.0] - 2026-11-16 + +### Features + +- **`Export-InforcerTenantDocumentation -Baseline` takes several baselines** and reads the tenant once. The policy list is the slow call (20 to 40 s on a large tenant) and every `-Baseline` call used to repeat it; a baseline's membership takes a fraction of a second. Without `-OutputPath` it returns one DocModel per baseline; with a directory it writes one `{TenantName}-{Baseline}-Documentation` file per baseline (a single baseline keeps the old `{TenantName}-Documentation` name). A baseline that does not resolve is a `BaselineFilterFailed` error and the others are still exported. A file `-OutputPath` with several baselines is refused (`OutputPathIsFileForSeveralBaselines`). Measured on the inforcer Blueprint Library: 22 baselines in 48 s, previously about 34 minutes. Graph names (`-FetchGraphData`) and the Settings Catalog are resolved once for all of them. + +### Bug Fixes + +Found by reading every per-baseline document of the inforcer Blueprint Library. + +- **Settings nested more than two objects deep rendered as empty rows.** Below two levels an object fell through to `ToString()`, which is empty for a `PSCustomObject`. Conditional Access device filter rules, guest and external user types and Entra's passkey migration opt-out showed nothing. The limit is now 10 and exists only to stop runaway recursion. +- **A setting stored as a dotted `@odata.type` was dropped.** Entra's device registration setting is `azureADRegistration.allowedToRegister.@odata.type = #microsoft.graph.allDeviceRegistrationMembership`, so "Users may register their devices" showed no setting. A dotted path ending in `@odata.type` is now rendered as that setting ("All Device Registration Membership"). Every other `@odata` key is still skipped. +- **List items showed only "N items".** An item without a display name or name was dropped, and the fields of named items were never shown, so an authentication method's Include Targets read "1 items" and nothing else. Each item now lists its fields ("Item 1", Target Type group, ID all_users). A single-field item is one row, and an id is never used as a label, so it stays a value that Graph resolution can reach. +- **Authentication strength combinations fell apart.** `allowedCombinations` items such as `password,softwareOath` were joined with commas and split again, giving "…, password, Software OATH Token, password, …". A list whose items contain a comma is now joined with `; `, and each combination reads "Password + Software OATH Token". + ## [1.0.1] - 2026-11-16 ### Bug Fixes diff --git a/Tests/Fix.DocReadability.Tests.ps1 b/Tests/Fix.DocReadability.Tests.ps1 new file mode 100644 index 0000000..e027aea --- /dev/null +++ b/Tests/Fix.DocReadability.Tests.ps1 @@ -0,0 +1,152 @@ +# Fix.DocReadability.Tests.ps1 +# Export-InforcerTenantDocumentation readability, found by reading every per-baseline document of the +# inforcer Blueprint Library (2026-11-16): settings below two levels rendered empty, a dotted +# @odata.type setting was dropped, list items showed only "N items", authentication strength +# combinations fell apart, and every -Baseline re-read the whole tenant. Fixtures are synthetic. + +BeforeAll { + Remove-Module -Name 'InforcerCommunity' -ErrorAction SilentlyContinue + Import-Module (Join-Path $PSScriptRoot '../module/InforcerCommunity.psd1') -Force + $script:M = Get-Module InforcerCommunity + + function global:Get-ReadabilityRows([object]$PolicyData) { + & $script:M { param($pd) ConvertTo-FlatSettingRows -PolicyData $pd } $PolicyData + } +} + +AfterAll { + Remove-Item function:global:Get-ReadabilityRows -ErrorAction SilentlyContinue +} + +Describe 'ConvertTo-FlatSettingRows shows what the policy configures' { + It 'renders a setting nested three objects deep instead of an empty row' { + $rows = Get-ReadabilityRows ([pscustomobject]@{ data = [pscustomobject]@{ PasskeyMigrationOptOut = [pscustomobject]@{ + optOutSettings = [pscustomobject]@{ passkeyDynamicMigration = $true } } } }) + $leaf = @($rows | Where-Object { $_.Value -eq 'True' }) + $leaf.Count | Should -Be 1 + $leaf[0].Name | Should -Match 'Passkey Dynamic Migration' + $leaf[0].Indent | Should -Be 3 + } + + It 'renders a Conditional Access device filter rule' { + $rows = Get-ReadabilityRows ([pscustomobject]@{ conditions = [pscustomobject]@{ devices = [pscustomobject]@{ + deviceFilter = [pscustomobject]@{ mode = 'exclude'; rule = 'device.isCompliant -eq True' } } } }) + @($rows | Where-Object { $_.Value -eq 'device.isCompliant -eq True' }).Count | Should -Be 1 + } + + It 'turns a dotted path ending in @odata.type into the setting it names' { + $rows = Get-ReadabilityRows ([pscustomobject]@{ data = [pscustomobject]@{ UserAllowedToRegister = [pscustomobject]@{ + 'azureADRegistration.allowedToRegister.@odata.type' = '#microsoft.graph.allDeviceRegistrationMembership' } } }) + $leaf = @($rows | Where-Object { $_.Value -match 'Registration Membership' }) + $leaf.Count | Should -Be 1 + $leaf[0].Value | Should -Not -Match 'microsoft\.graph|#' + } + + It 'still drops @odata.type and other @odata keys that are serialisation metadata' { + $rows = Get-ReadabilityRows ([pscustomobject]@{ '@odata.type' = '#microsoft.graph.x'; '_value@odata.type' = '#Guid' + 'grant@odata.context' = 'https://graph.microsoft.com/x'; state = 'enabled' }) + @($rows).Count | Should -Be 1 + $rows[0].Value | Should -Be 'enabled' + } + + It 'lists every field of a list item that has no name' { + $rows = @(Get-ReadabilityRows ([pscustomobject]@{ includeTargets = @([pscustomobject]@{ targetType = 'group'; id = 'all_users' }) })) + $rows[0].Value | Should -Be '1 items' + $rows[1].Name | Should -Be 'Item 1' + @($rows | Where-Object { $_.Value -eq 'group' -and $_.Indent -eq 2 }).Count | Should -Be 1 + @($rows | Where-Object { $_.Value -eq 'all_users' -and $_.Indent -eq 2 }).Count | Should -Be 1 + } + + It 'labels a named list item by its name and keeps its id out of the label' { + $rows = @(Get-ReadabilityRows ([pscustomobject]@{ passkeyProfiles = @([pscustomobject]@{ + id = '00000000-0000-0000-0000-000000000001'; name = 'Default passkey profile'; passkeyTypes = 'deviceBound' }) })) + $rows[1].Name | Should -Be 'Default passkey profile' + @($rows | Where-Object { $_.Value -eq 'deviceBound' }).Count | Should -Be 1 + @($rows | Where-Object { "$($_.Name)$($_.Value)" -match '00000000-0000' }).Count | Should -Be 0 + } + + It 'gives a list item with a single field one row' { + $rows = @(Get-ReadabilityRows ([pscustomobject]@{ excludeTargets = @([pscustomobject]@{ id = '00000000-0000-0000-0000-0000000000a1' }) })) + $rows.Count | Should -Be 2 + $rows[1].Value | Should -Be '00000000-0000-0000-0000-0000000000a1' -Because 'as a value, GUID resolution and masking can reach it' + } + + It 'keeps list entries that hold a comma apart' { + $rows = Get-ReadabilityRows ([pscustomobject]@{ allowedCombinations = @('fido2', 'password,softwareOath') }) + $rows[0].Value | Should -Be 'fido2; password,softwareOath' + (Get-ReadabilityRows ([pscustomobject]@{ x = @('a', 'b') }))[0].Value | Should -Be 'a, b' + } +} + +Describe 'Authentication strength combinations read as combinations' { + It 'names each combination once, with its methods joined by +' { + $model = & $script:M { + ConvertTo-InforcerDocModel -DocData @{ + Tenant = [pscustomobject]@{ tenantFriendlyName = 'T'; msTenantId = '00000000-0000-0000-0000-000000000001' } + TenantId = 1; CollectedAt = [datetime]::UtcNow; Baselines = @() + Policies = @([pscustomobject]@{ id = 'p1'; displayName = 'CA'; policyTypeId = 1; product = 'Entra' + primaryGroup = 'Conditional Access'; secondaryGroup = 'Policies' + policyData = [pscustomobject]@{ grantControls = [pscustomobject]@{ authenticationStrength = [pscustomobject]@{ + allowedCombinations = @('fido2', 'password,softwareOath', 'password,microsoftAuthenticatorPush') } } } }) + } + } + $row = foreach ($p in $model.Products.Values) { foreach ($c in $p.Categories.Values) { foreach ($pol in $c) { $pol.Settings | Where-Object { $_.Name -eq 'Allowed Combinations' } } } } + $row.Value | Should -Be 'FIDO2 Security Key; Password + Software OATH Token; Password + Microsoft Authenticator' + } +} + +Describe 'Export-InforcerTenantDocumentation with several baselines' { + BeforeEach { + Mock -ModuleName InforcerCommunity Test-InforcerSession { $true } + Mock -ModuleName InforcerCommunity Resolve-InforcerTenantId { 1 } + Mock -ModuleName InforcerCommunity Write-Host { } + Mock -ModuleName InforcerCommunity Import-InforcerSettingsCatalog { } + Mock -ModuleName InforcerCommunity Get-InforcerDocData { + @{ TenantId = 1; Baselines = @(); CollectedAt = [datetime]::UtcNow + Tenant = [pscustomobject]@{ tenantFriendlyName = 'Contoso'; msTenantId = '00000000-0000-0000-0000-000000000001' } + Policies = @( + [pscustomobject]@{ id = 'a'; displayName = 'Policy A'; policyTypeId = 1; product = 'Entra'; primaryGroup = 'G'; secondaryGroup = 'S'; policyData = [pscustomobject]@{ state = 'enabled' } } + [pscustomobject]@{ id = 'b'; displayName = 'Policy B'; policyTypeId = 1; product = 'Entra'; primaryGroup = 'G'; secondaryGroup = 'S'; policyData = [pscustomobject]@{ state = 'disabled' } } + ) } + } + # Keeps the policy whose id is the baseline name's last letter; 'Broken' does not resolve. + Mock -ModuleName InforcerCommunity Select-InforcerBaselinePolicies { + if ($BaselineId -eq 'Broken') { Write-Warning 'No baseline found with name: Broken'; return $null } + $keep = $BaselineId.Substring($BaselineId.Length - 1).ToLower() + $DocData.Policies = @($DocData.Policies | Where-Object { $_.id -eq $keep }) + $BaselineId + } + } + + It 'reads the tenant once and returns one document per baseline, each with only its policies' { + $models = @(Export-InforcerTenantDocumentation -TenantId 1 -Baseline 'Baseline A', 'Baseline B') + Should -Invoke -ModuleName InforcerCommunity Get-InforcerDocData -Times 1 -Exactly + $models.Count | Should -Be 2 + $models[0].FilterBaseline | Should -Be 'Baseline A' + @($models[0].Products['Entra'].Categories.Values | ForEach-Object { $_ } | ForEach-Object { $_.Basics.Name }) | Should -Be @('Policy A') + @($models[1].Products['Entra'].Categories.Values | ForEach-Object { $_ } | ForEach-Object { $_.Basics.Name }) | Should -Be @('Policy B') + } + + It 'reports a baseline that does not resolve and still documents the others' { + $models = @(Export-InforcerTenantDocumentation -TenantId 1 -Baseline 'Broken', 'Baseline B' -ErrorVariable e -ErrorAction SilentlyContinue -WarningAction SilentlyContinue) + $models.Count | Should -Be 1 + $models[0].FilterBaseline | Should -Be 'Baseline B' + @($e | Where-Object { "$($_.FullyQualifiedErrorId)" -match '^BaselineFilterFailed' }).Count | Should -Be 1 + } + + It 'writes one file per baseline, named after it' { + $dir = Join-Path $TestDrive 'out' + $files = @(Export-InforcerTenantDocumentation -TenantId 1 -Baseline 'Baseline A', 'Baseline B' -Format Markdown -OutputPath $dir -Show:$false) + @($files.Name | Sort-Object) | Should -Be @('Contoso-Baseline-A-Documentation.md', 'Contoso-Baseline-B-Documentation.md') + } + + It 'refuses a file -OutputPath for several baselines' { + { Export-InforcerTenantDocumentation -TenantId 1 -Baseline 'Baseline A', 'Baseline B' -Format Html -OutputPath (Join-Path $TestDrive 'one.html') -Show:$false } | + Should -Throw -ErrorId 'OutputPathIsFileForSeveralBaselines*' + } + + It 'keeps the single-baseline file name as it was' { + $files = @(Export-InforcerTenantDocumentation -TenantId 1 -Baseline 'Baseline A' -Format Markdown -OutputPath (Join-Path $TestDrive 'single') -Show:$false) + $files[0].Name | Should -Be 'Contoso-Documentation.md' + } +} diff --git a/docs/CMDLET-REFERENCE.md b/docs/CMDLET-REFERENCE.md index 618032f..b325b15 100644 --- a/docs/CMDLET-REFERENCE.md +++ b/docs/CMDLET-REFERENCE.md @@ -776,7 +776,7 @@ The HTML output features a modern admin dashboard design with a collapsible side | **Show** | Switch | No | Open the generated HTML in the default browser, each file once per call (also when tenants are piped). Requires `-OutputPath` and `-Format Html`. **Defaults to on interactively, off in CI** (`CI`, `TF_BUILD`, `GITHUB_ACTIONS`, `GITLAB_CI`, `JENKINS_URL`, `TEAMCITY_VERSION`, `BUILDKITE`). `-Show` forces it, `-Show:$false` suppresses it; an explicit value always wins. | | **SettingsCatalogPath** | String | No | Path to a local `settings.json` for Intune Settings Catalog name resolution. When omitted, the latest data is downloaded from the [IntuneSettingsCatalogData](https://github.com/royklo/IntuneSettingsCatalogData) GitHub release and cached at `~/.inforcercommunity/data/settings.json` (~65 MB). The cache is used as is for 24 hours; after that the module checks the release and downloads only when a newer catalog exists. A download replaces the cache only when it is a valid catalog of at most 512 MB. Offline, the cached copy is used, or raw setting IDs when there is none. | | **FetchGraphData** | Switch | No | Signs in to Microsoft Graph interactively for the exported tenant (or reuses an existing Graph session for that tenant that already has the scopes), then resolves IDs to names: assignment groups and filters, scope tags, and the groups, directory roles, named locations and applications in Conditional Access policies. Requests `Directory.Read.All`, `Policy.Read.All` and `DeviceManagementConfiguration.Read.All`. Requires the `Microsoft.Graph.Authentication` module; without it, or when sign-in fails, raw IDs are kept with a warning. See [Graph integration](#graph-integration--fetchgraphdata). | -| **Baseline** | String | No | Filter to policies belonging to a specific baseline (name or ID). Policies are matched by id, by name only when there is no id. A same-named policy whose product, category or description differs is not used in its place, and one that still matches several is left out; both are named in a warning. A baseline that cannot be resolved or holds no policies is an error (`BaselineFilterFailed`) and nothing is exported. | +| **Baseline** | String[] | No | Filter to policies belonging to one or more baselines (names or IDs). Several baselines read the tenant once and produce one DocModel, or one `{TenantName}-{Baseline}-Documentation` file, per baseline. Policies are matched by id, by name only when there is no id. A same-named policy whose product, category or description differs is not used in its place, and one that still matches several is left out; both are named in a warning. A baseline that cannot be resolved or holds no policies is an error (`BaselineFilterFailed`); the other baselines are still exported. | | **Tag** | String | No | Filter to policies with a specific inforcer tag (case-insensitive). | ### Examples diff --git a/module/InforcerCommunity.psd1 b/module/InforcerCommunity.psd1 index ef101db..0c3d210 100644 --- a/module/InforcerCommunity.psd1 +++ b/module/InforcerCommunity.psd1 @@ -1,6 +1,6 @@ @{ RootModule = 'InforcerCommunity.psm1' - ModuleVersion = '1.0.1' + ModuleVersion = '1.1.0' GUID = 'a1b2c3d4-e5f6-7890-abcd-ef1234567890' Author = 'Roy Klooster' Description = 'Community PowerShell module for the Inforcer API. Created by Roy Klooster. Not owned or officially maintained by Inforcer.' @@ -38,7 +38,7 @@ PSData = @{ ProjectUri = 'https://github.com/royklo/InforcerCommunity' LicenseUri = 'https://github.com/royklo/InforcerCommunity/blob/main/LICENSE' - ReleaseNotes = 'v1.0.1: Export-InforcerTenantDocumentation -Baseline documents exactly the baseline''s policies (same-named policies no longer leak in); a -Baseline that does not resolve or holds no policies is an error (BaselineFilterFailed) instead of exporting the whole tenant; name/value settings keep their values; -FetchGraphData reuses an app-only Graph session instead of opening a browser. See CHANGELOG.md.' + ReleaseNotes = 'v1.1.0: Export-InforcerTenantDocumentation -Baseline takes several baselines and reads the tenant once (22 baselines: 34 min -> 48 s). Documents now show settings nested more than two levels deep, list items with their fields, Entra settings stored as a dotted @odata.type, and authentication strength combinations intact. See CHANGELOG.md.''s policies (same-named policies no longer leak in); a -Baseline that does not resolve or holds no policies is an error (BaselineFilterFailed) instead of exporting the whole tenant; name/value settings keep their values; -FetchGraphData reuses an app-only Graph session instead of opening a browser. See CHANGELOG.md.' Tags = @('Inforcer', 'API', 'Community') } } diff --git a/module/Private/ConvertTo-InforcerDocModel.ps1 b/module/Private/ConvertTo-InforcerDocModel.ps1 index 420f9b9..5ccfa44 100644 --- a/module/Private/ConvertTo-InforcerDocModel.ps1 +++ b/module/Private/ConvertTo-InforcerDocModel.ps1 @@ -419,7 +419,15 @@ function ConvertTo-InforcerDocModel { $val = $row.Value # Resolve camelCase values (e.g. allowedCombinations like "password,softwareOath") $val = $row.Value - if (-not [string]::IsNullOrWhiteSpace($val) -and $val -is [string]) { + if (-not [string]::IsNullOrWhiteSpace($val) -and $val -is [string] -and $val.Contains(';')) { + # A list whose items hold commas is joined with '; ' (ConvertTo-FlatSettingRows), so + # each item is one combination: "password,softwareOath" -> "Password + Software OATH Token". + $row.Value = @(foreach ($item in $val -split ';') { + $it = (($item -split ',') | ForEach-Object { $_.Trim() }) -join ',' + if ($caFriendlyValues.ContainsKey($it)) { $caFriendlyValues[$it] } + else { @(foreach ($p in $it -split ',') { if ($caFriendlyValues.ContainsKey($p)) { $caFriendlyValues[$p] } else { $p } }) -join ' + ' } + }) -join '; ' + } elseif (-not [string]::IsNullOrWhiteSpace($val) -and $val -is [string]) { # Try full value first (handles combo keys like "password,microsoftAuthenticatorPush") $trimmedVal = $val.Trim() $normalizedVal = (($trimmedVal -split ',') | ForEach-Object { $_.Trim() }) -join ',' diff --git a/module/Private/ConvertTo-InforcerSettingRows.ps1 b/module/Private/ConvertTo-InforcerSettingRows.ps1 index 9698d59..b452d38 100644 --- a/module/Private/ConvertTo-InforcerSettingRows.ps1 +++ b/module/Private/ConvertTo-InforcerSettingRows.ps1 @@ -251,14 +251,24 @@ function ConvertTo-FlatSettingRows { 'policyGuid' ) + # Only a guard against runaway recursion. It was 2, and below that an object fell through to + # ToString(), which is empty for a PSCustomObject: a Conditional Access device filter rule, the + # guest user types and Entra's passkey migration opt-out rendered as empty rows. + $maxDepth = 10 + foreach ($prop in $PolicyData.PSObject.Properties) { if ($prop.Name -in $skip) { continue } - if ($prop.Name -match '@odata') { continue } + # A dotted path ending in @odata.type is the setting itself, e.g. Entra's + # azureADRegistration.allowedToRegister.@odata.type = #microsoft.graph.allDeviceRegistrationMembership + # ("all users may register"). Every other @odata key is serialisation metadata. + if ($prop.Name -match '^(?.+)\.@odata\.type$' -and $prop.Value -is [string]) { + $prop = [PSCustomObject]@{ Name = $Matches.path; Value = (ConvertTo-FriendlySettingName -Name ($prop.Value -replace '^#?microsoft\.graph\.', '')) } + } elseif ($prop.Name -match '@odata') { continue } # Skip internal flags (but keep linkedComplianceScript — it's rendered by MR card) if ($prop.Name -eq '_claimedByCompliancePolicy') { continue } if ($prop.Name -eq 'Length' -and $prop.Value -is [int]) { continue } $val = $prop.Value - if ($val -is [PSObject] -and $val.PSObject.Properties.Count -gt 0 -and $Depth -lt 2) { + if ($val -is [PSObject] -and $val.PSObject.Properties.Count -gt 0 -and $Depth -lt $maxDepth) { [void]$rows.Add([PSCustomObject]@{ Name = (ConvertTo-FriendlySettingName -Name $prop.Name) Value = '' @@ -268,7 +278,7 @@ function ConvertTo-FlatSettingRows { foreach ($r in (ConvertTo-FlatSettingRows -PolicyData $val -Depth ($Depth + 1))) { [void]$rows.Add($r) } - } elseif ($val -is [array] -and $val.Count -gt 0 -and $val[0] -is [PSObject] -and $Depth -lt 2) { + } elseif ($val -is [array] -and $val.Count -gt 0 -and $val[0] -is [PSObject] -and $Depth -lt $maxDepth) { # Array of objects — show count + extract display names (original behavior) # Special handling: recurse into scheduledActionConfigurations for compliance rules $propLower = $prop.Name.ToLowerInvariant() @@ -294,47 +304,59 @@ function ConvertTo-FlatSettingRows { Indent = $Depth IsConfigured = $true }) + $itemNumber = 0 foreach ($item in $val) { - if ($item -is [PSObject]) { - $itemName = $null - foreach ($nameField in @('displayName', 'name', 'id', 'bundleId', 'packageId')) { - $nv = $item.PSObject.Properties[$nameField] - if ($nv -and $nv.Value) { $itemName = $nv.Value.ToString(); break } - } - # Fallback: check nested mobileAppIdentifier (MAM app protection policies) - if (-not $itemName) { - $mai = $item.PSObject.Properties['mobileAppIdentifier'] - if ($mai -and $mai.Value -is [PSObject]) { - foreach ($nameField in @('bundleId', 'packageId')) { - $nv2 = $mai.Value.PSObject.Properties[$nameField] - if ($nv2 -and $nv2.Value) { $itemName = $nv2.Value.ToString(); break } - } + if ($item -isnot [PSObject]) { continue } + $itemNumber++ + # The label is a human-readable field. An id is not: it stays a value row, + # where GUID resolution and masking can reach it. + $itemName = $null; $labelField = $null + foreach ($nameField in @('displayName', 'name', 'bundleId', 'packageId')) { + $nv = $item.PSObject.Properties[$nameField] + if ($nv -and $nv.Value) { $itemName = $nv.Value.ToString(); $labelField = $nameField; break } + } + # Fallback: check nested mobileAppIdentifier (MAM app protection policies) + if (-not $itemName) { + $mai = $item.PSObject.Properties['mobileAppIdentifier'] + if ($mai -and $mai.Value -is [PSObject]) { + foreach ($nameField in @('bundleId', 'packageId')) { + $nv2 = $mai.Value.PSObject.Properties[$nameField] + if ($nv2 -and $nv2.Value) { $itemName = $nv2.Value.ToString(); break } } } - # A name/value pair (Entra directory setting templates such as Password - # Protection) carries its setting in 'value'. It used to be dropped, so - # "Lockout Threshold" rendered empty while the policy set it to 10. - $itemValue = '' - $vp = $item.PSObject.Properties['value'] - if ($itemName -and $vp -and ($vp.Value -is [string] -or $vp.Value -is [ValueType])) { - $itemValue = $vp.Value.ToString() - $itemName = ConvertTo-FriendlySettingName -Name $itemName - } - if ($itemName) { - [void]$rows.Add([PSCustomObject]@{ - Name = $itemName - Value = $itemValue - Indent = $Depth + 1 - IsConfigured = $true - }) - } + } + # A name/value pair (Entra directory setting templates such as Password + # Protection) carries its setting in 'value'. + $vp = $item.PSObject.Properties['value'] + if ($itemName -and $vp -and ($vp.Value -is [string] -or $vp.Value -is [ValueType])) { + [void]$rows.Add([PSCustomObject]@{ Name = (ConvertTo-FriendlySettingName -Name $itemName); Value = $vp.Value.ToString(); Indent = $Depth + 1; IsConfigured = $true }) + continue + } + # Every other scalar field of the item. They used to be dropped, so a list such + # as an authentication method's Include Targets showed "1 items" and nothing else. + $fields = @(foreach ($ip in $item.PSObject.Properties) { + if ($ip.Name -match '@odata' -or $ip.Name -eq $labelField -or ($itemName -and $ip.Name -eq 'id')) { continue } + $iv = $ip.Value + if (($iv -is [string] -or $iv -is [ValueType]) -and "$iv" -ne '') { $ip } + }) + if (-not $itemName -and $fields.Count -eq 1) { + [void]$rows.Add([PSCustomObject]@{ Name = (ConvertTo-FriendlySettingName -Name $fields[0].Name); Value = $fields[0].Value.ToString(); Indent = $Depth + 1; IsConfigured = $true }) + continue + } + if (-not $itemName -and $fields.Count -eq 0) { continue } + [void]$rows.Add([PSCustomObject]@{ Name = $(if ($itemName) { $itemName } else { "Item $itemNumber" }); Value = ''; Indent = $Depth + 1; IsConfigured = $true }) + foreach ($f in $fields) { + [void]$rows.Add([PSCustomObject]@{ Name = (ConvertTo-FriendlySettingName -Name $f.Name); Value = $f.Value.ToString(); Indent = $Depth + 2; IsConfigured = $true }) } } } } else { $strVal = if ($null -eq $val) { '' } elseif ($val -is [array]) { - $joined = @($val | ForEach-Object { if ($_ -is [string] -or $_ -is [ValueType]) { $_.ToString() } }) -join ', ' + $items = @($val | ForEach-Object { if ($_ -is [string] -or $_ -is [ValueType]) { $_.ToString() } }) + # An item that holds a comma itself (authentication strength combinations + # such as "password,softwareOath") would merge into its neighbours. + $joined = $items -join $(if (@($items | Where-Object { $_.Contains(',') }).Count) { '; ' } else { ', ' }) if ([string]::IsNullOrWhiteSpace($joined) -and $val.Count -gt 0) { "$($val.Count) items" } else { $joined } } else { $val.ToString() } # hashedScriptContent matches this pattern too, but the helper rejects digests. diff --git a/module/Public/Export-InforcerTenantDocumentation.ps1 b/module/Public/Export-InforcerTenantDocumentation.ps1 index bd1b064..f954987 100644 --- a/module/Public/Export-InforcerTenantDocumentation.ps1 +++ b/module/Public/Export-InforcerTenantDocumentation.ps1 @@ -65,14 +65,17 @@ Microsoft.Graph.Authentication module. If Graph cannot be reached, or refuses a call for a missing permission, the affected names stay as raw IDs with a warning. .PARAMETER Baseline - Filter to only policies that belong to a specific baseline. Accepts a baseline GUID or - friendly name (e.g., "Inforcer Blueprint Baseline - Tier 1 - Foundations"). Uses the + Filter to only policies that belong to a baseline. Accepts one or more baseline GUIDs or + friendly names (e.g., "Inforcer Blueprint Baseline - Tier 1 - Foundations"). Uses the Inforcer alignment details API to retrieve the list of policies in the baseline, then filters the documentation to only those policies. The baseline name is shown in the header. + Several baselines read the tenant once and produce one DocModel, or with -OutputPath one + {TenantName}-{Baseline}-Documentation file, per baseline. Each baseline policy is matched by id; by name only when it has no id the tenant knows. A same-named policy whose product, category or description differs is a different policy and is - not used in its place; one that still matches several is left out. Both are named in a warning. A baseline that cannot be resolved, or holds no - policies, is an error (BaselineFilterFailed) and nothing is exported. + not used in its place; one that still matches several is left out. Both are named in a + warning. A baseline that cannot be resolved, or holds no policies, is an error + (BaselineFilterFailed); nothing is exported for it and the other baselines still are. .PARAMETER Tag Filter to only policies that have a specific Inforcer tag (e.g., "IAM - Core", "Tier 1"). Matches against the tag name property on each policy (case-insensitive, contains match). @@ -130,7 +133,7 @@ param( [switch]$FetchGraphData, [Parameter(Mandatory = $false)] - [string]$Baseline, + [string[]]$Baseline, [Parameter(Mandatory = $false)] [string]$Tag @@ -144,6 +147,11 @@ begin { process { $tenantCount++ +if (@($Baseline).Count -gt 1 -and $Format.Count -eq 1 -and $OutputPath -and [System.IO.Path]::HasExtension($OutputPath)) { + throw [System.Management.Automation.ErrorRecord]::new( + [System.ArgumentException]::new("-OutputPath '$OutputPath' is a file, so each baseline would overwrite the last. Pass a directory; each baseline gets its own {TenantName}-{Baseline}-Documentation file."), + 'OutputPathIsFileForSeveralBaselines', [System.Management.Automation.ErrorCategory]::InvalidArgument, $OutputPath) +} if ($tenantCount -gt 1 -and $Format.Count -eq 1 -and $OutputPath -and [System.IO.Path]::HasExtension($OutputPath)) { throw [System.Management.Automation.ErrorRecord]::new( [System.ArgumentException]::new("-OutputPath '$OutputPath' is a file, so a second tenant would overwrite the first. Pass a directory when piping several tenants; each gets its own {TenantName}-Documentation file."), @@ -175,61 +183,7 @@ if (-not [string]::IsNullOrEmpty($resolvedCatalogPath)) { $docData = Get-InforcerDocData @docDataParams if ($null -eq $docData) { return } -# Filter to baseline policies if -Baseline specified -$baselineFilterName = $null -if (-not [string]::IsNullOrWhiteSpace($Baseline)) { - Write-Host "Filtering to baseline: $Baseline" -ForegroundColor Cyan - $baselineFilterName = Select-InforcerBaselinePolicies -DocData $docData -BaselineId $Baseline -WarningVariable selectWarnings - # This used to warn and export every policy in the tenant, under the baseline's name: a - # document that claims to be one baseline and is the whole estate. Compare treats the same - # failure as an error (SourceBaselineFilterFailed); so does Export now. - if ($null -eq $baselineFilterName) { - $why = if ($selectWarnings) { " $(@($selectWarnings)[-1])" } else { '' } - Write-Error -Message "Could not filter to baseline '$Baseline', so nothing was exported.$why" ` - -ErrorId 'BaselineFilterFailed' -Category InvalidResult - return - } -} - -# Filter by tag if -Tag specified -if (-not [string]::IsNullOrWhiteSpace($Tag)) { - Write-Host "Filtering to tag: $Tag" -ForegroundColor Cyan - $originalCount = @($docData.Policies).Count - - # Collected before the filter so a no-match can name the tags that do exist. - $availableTags = [System.Collections.Generic.SortedSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) - foreach ($pol in @($docData.Policies)) { - foreach ($t in @($pol.tags)) { - if ($null -eq $t) { continue } - $n = if ($t -is [PSObject] -and $t.PSObject.Properties['name']) { $t.name } else { $t.ToString() } - if (-not [string]::IsNullOrWhiteSpace($n)) { [void]$availableTags.Add($n) } - } - } - - $docData.Policies = @($docData.Policies | Where-Object { - $policyTags = $_.tags - if ($null -eq $policyTags -or @($policyTags).Count -eq 0) { return $false } - foreach ($t in @($policyTags)) { - $tagName = if ($t -is [PSObject] -and $t.PSObject.Properties['name']) { $t.name } else { $t.ToString() } - if ($tagName -and $tagName.IndexOf($Tag, [System.StringComparison]::OrdinalIgnoreCase) -ge 0) { return $true } - } - return $false - }) - Write-Host " Filtered to $(@($docData.Policies).Count) of $originalCount policies with tag '$Tag'" -ForegroundColor Gray - - # No match used to render anyway: a 0.1 KB document and exit 0, which reads as "nothing in - # this tenant is tagged that way" when the likelier cause is a tag name that does not exist. - # Naming the real tags is the difference between a dead end and a correctable mistake. - if (@($docData.Policies).Count -eq 0) { - $known = if ($availableTags.Count -gt 0) { $availableTags -join "', '" } else { $null } - $detail = if ($known) { "Tags present in this tenant: '$known'." } else { 'No policy in this tenant carries any tag.' } - Write-Error -Message "No policy matched tag '$Tag', so there is nothing to document. $detail" ` - -ErrorId 'TagMatchedNothing' -Category ObjectNotFound - return - } -} - -# Load Settings Catalog only if there are Settings Catalog policies (policyTypeId 10) +# Load Settings Catalog only if the tenant has Settings Catalog policies (policyTypeId 10) $hasCatalogPolicies = @($docData.Policies | Where-Object { $_.policyTypeId -eq 10 }).Count -gt 0 if ($hasCatalogPolicies) { $catalogParams = @{} @@ -241,7 +195,8 @@ if ($hasCatalogPolicies) { Write-Host ' No Intune/Defender policies found, skipping Settings Catalog load' -ForegroundColor Gray } -# Graph maps are built fresh for this tenant only; nothing carries over between piped tenants or calls. +# Graph maps are built fresh for this tenant only, once for all its baselines; nothing carries over +# between piped tenants or calls. $graphMaps = @{} if ($FetchGraphData) { $tenantLabel = if ($docData.Tenant -and $docData.Tenant.tenantFriendlyName) { " for $($docData.Tenant.tenantFriendlyName)" } else { '' } @@ -249,86 +204,151 @@ if ($FetchGraphData) { $graphMaps = Resolve-InforcerGraphEnrichment -DocData $docData -ConditionalAccess } -Write-Host 'Building documentation model...' -ForegroundColor Cyan -$docModelParams = @{ DocData = $docData } -foreach ($key in 'GroupNameMap', 'FilterMap', 'RoleNameMap', 'LocationNameMap', 'AppNameMap', 'ScopeTagMap') { - if ($graphMaps[$key]) { $docModelParams[$key] = $graphMaps[$key] } -} -$docModel = ConvertTo-InforcerDocModel @docModelParams -if ($null -eq $docModel) { return } +# One tenant read serves every -Baseline: the policy list is the slow call (20-40 s on a large +# tenant), a baseline's membership is a fraction of a second. Each pass starts from the full list. +$allPolicies = @($docData.Policies) +$baselineTargets = @(if ($Baseline) { $Baseline } else { $null }) +foreach ($baselineTarget in $baselineTargets) { + $docData.Policies = $allPolicies + + # Filter to baseline policies if -Baseline specified + $baselineFilterName = $null + if ($baselineTarget) { + Write-Host "Filtering to baseline: $baselineTarget" -ForegroundColor Cyan + $baselineFilterName = Select-InforcerBaselinePolicies -DocData $docData -BaselineId $baselineTarget -WarningVariable selectWarnings + # This used to warn and export every policy in the tenant, under the baseline's name: a + # document that claims to be one baseline and is the whole estate. Compare treats the same + # failure as an error (SourceBaselineFilterFailed); so does Export now. + if ($null -eq $baselineFilterName) { + $why = if ($selectWarnings) { " $(@($selectWarnings)[-1])" } else { '' } + Write-Error -Message "Could not filter to baseline '$baselineTarget', so nothing was exported.$why" ` + -ErrorId 'BaselineFilterFailed' -Category InvalidResult + continue + } + } -# Add filter metadata so renderers can show what's active -if ($baselineFilterName) { $docModel['FilterBaseline'] = $baselineFilterName } -if (-not [string]::IsNullOrWhiteSpace($Tag)) { $docModel['FilterTag'] = $Tag } + # Filter by tag if -Tag specified + if (-not [string]::IsNullOrWhiteSpace($Tag)) { + Write-Host "Filtering to tag: $Tag" -ForegroundColor Cyan + $originalCount = @($docData.Policies).Count + + # Collected before the filter so a no-match can name the tags that do exist. + $availableTags = [System.Collections.Generic.SortedSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) + foreach ($pol in @($docData.Policies)) { + foreach ($t in @($pol.tags)) { + if ($null -eq $t) { continue } + $n = if ($t -is [PSObject] -and $t.PSObject.Properties['name']) { $t.name } else { $t.ToString() } + if (-not [string]::IsNullOrWhiteSpace($n)) { [void]$availableTags.Add($n) } + } + } -$policyCount = 0 -foreach ($product in $docModel.Products.Values) { - foreach ($policies in $product.Categories.Values) { $policyCount += @($policies).Count } -} -Write-Host " Found $policyCount policies across $($docModel.Products.Count) products" -ForegroundColor Gray - -# ── No -OutputPath: hand back the DocModel and touch nothing ─────────────────── -# Writing is opt-in even here, where the verb promises a file. The old default put documents in -# whatever directory you happened to be standing in and opened a browser for them, which is -# wrong in a pipeline and wrong for a caller that only wants the model to read. -if ([string]::IsNullOrWhiteSpace($OutputPath)) { - Write-Host 'Done. Pass -OutputPath to write files.' -ForegroundColor Cyan - return $docModel -} + $docData.Policies = @($docData.Policies | Where-Object { + $policyTags = $_.tags + if ($null -eq $policyTags -or @($policyTags).Count -eq 0) { return $false } + foreach ($t in @($policyTags)) { + $tagName = if ($t -is [PSObject] -and $t.PSObject.Properties['name']) { $t.name } else { $t.ToString() } + if ($tagName -and $tagName.IndexOf($Tag, [System.StringComparison]::OrdinalIgnoreCase) -ge 0) { return $true } + } + return $false + }) + Write-Host " Filtered to $(@($docData.Policies).Count) of $originalCount policies with tag '$Tag'" -ForegroundColor Gray + + # No match used to render anyway: a 0.1 KB document and exit 0, which reads as "nothing in + # this tenant is tagged that way" when the likelier cause is a tag name that does not exist. + # Naming the real tags is the difference between a dead end and a correctable mistake. + if (@($docData.Policies).Count -eq 0) { + $known = if ($availableTags.Count -gt 0) { $availableTags -join "', '" } else { $null } + $detail = if ($known) { "Tags present in this tenant: '$known'." } else { 'No policy in this tenant carries any tag.' } + Write-Error -Message "No policy matched tag '$Tag', so there is nothing to document. $detail" ` + -ErrorId 'TagMatchedNothing' -Category ObjectNotFound + continue + } + } -# Render each requested format and write to disk -$extensionMap = @{ Html = 'html'; Markdown = 'md'; Excel = 'xlsx' } -$formatIndex = 0 -$htmlFile = $null -$safeName = $docModel.TenantName -replace '[^\w\-]', '-' + Write-Host 'Building documentation model...' -ForegroundColor Cyan + $docModelParams = @{ DocData = $docData } + foreach ($key in 'GroupNameMap', 'FilterMap', 'RoleNameMap', 'LocationNameMap', 'AppNameMap', 'ScopeTagMap') { + if ($graphMaps[$key]) { $docModelParams[$key] = $graphMaps[$key] } + } + $docModel = ConvertTo-InforcerDocModel @docModelParams + if ($null -eq $docModel) { continue } -foreach ($fmt in $Format) { - $formatIndex++ - $ext = $extensionMap[$fmt] + # Add filter metadata so renderers can show what's active + if ($baselineFilterName) { $docModel['FilterBaseline'] = $baselineFilterName } + if (-not [string]::IsNullOrWhiteSpace($Tag)) { $docModel['FilterTag'] = $Tag } - if ($Format.Count -eq 1 -and [System.IO.Path]::HasExtension($OutputPath)) { - $filePath = $OutputPath - } else { - $filePath = Join-Path $OutputPath "$safeName-Documentation.$ext" + $policyCount = 0 + foreach ($product in $docModel.Products.Values) { + foreach ($policies in $product.Categories.Values) { $policyCount += @($policies).Count } } - - $parentDir = Split-Path -Parent $filePath - if (-not [string]::IsNullOrEmpty($parentDir) -and -not (Test-Path -LiteralPath $parentDir)) { - [void](New-Item -ItemType Directory -Force -Path $parentDir) + Write-Host " Found $policyCount policies across $($docModel.Products.Count) products" -ForegroundColor Gray + + # ── No -OutputPath: hand back the DocModel and touch nothing ─────────────────── + # Writing is opt-in even here, where the verb promises a file. The old default put documents in + # whatever directory you happened to be standing in and opened a browser for them, which is + # wrong in a pipeline and wrong for a caller that only wants the model to read. + if ([string]::IsNullOrWhiteSpace($OutputPath)) { + Write-Host 'Done. Pass -OutputPath to write files.' -ForegroundColor Cyan + $docModel + continue } - Write-Host "Rendering $fmt ($formatIndex/$($Format.Count))..." -ForegroundColor Cyan + # Render each requested format and write to disk + $extensionMap = @{ Html = 'html'; Markdown = 'md'; Excel = 'xlsx' } + $formatIndex = 0 + $htmlFile = $null + $safeName = $docModel.TenantName -replace '[^\w\-]', '-' + # Several baselines in one call each get their own file. + if ($baselineTargets.Count -gt 1) { $safeName += '-' + ($baselineFilterName -replace '[^\w\-]', '-') } + + foreach ($fmt in $Format) { + $formatIndex++ + $ext = $extensionMap[$fmt] + + if ($Format.Count -eq 1 -and [System.IO.Path]::HasExtension($OutputPath)) { + $filePath = $OutputPath + } else { + $filePath = Join-Path $OutputPath "$safeName-Documentation.$ext" + } - if ($fmt -eq 'Excel') { - # Excel writes directly to disk via ImportExcel - Export-InforcerDocExcel -DocModel $docModel -FilePath $filePath - if (-not (Test-Path -LiteralPath $filePath)) { continue } - } else { - $content = switch ($fmt) { - 'Html' { ConvertTo-InforcerHtml -DocModel $docModel } - 'Markdown' { ConvertTo-InforcerMarkdown -DocModel $docModel } + $parentDir = Split-Path -Parent $filePath + if (-not [string]::IsNullOrEmpty($parentDir) -and -not (Test-Path -LiteralPath $parentDir)) { + [void](New-Item -ItemType Directory -Force -Path $parentDir) } - Set-Content -Path $filePath -Value $content -Encoding UTF8 - if ($fmt -eq 'Html') { $htmlFile = $filePath } - } - $fileInfo = Get-Item -LiteralPath $filePath - $sizeKb = [math]::Round($fileInfo.Length / 1KB, 1) - Write-Host " Exported: $filePath ($sizeKb KB)" -ForegroundColor Green - $fileInfo -} + Write-Host "Rendering $fmt ($formatIndex/$($Format.Count))..." -ForegroundColor Cyan + + if ($fmt -eq 'Excel') { + # Excel writes directly to disk via ImportExcel + Export-InforcerDocExcel -DocModel $docModel -FilePath $filePath + if (-not (Test-Path -LiteralPath $filePath)) { continue } + } else { + $content = switch ($fmt) { + 'Html' { ConvertTo-InforcerHtml -DocModel $docModel } + 'Markdown' { ConvertTo-InforcerMarkdown -DocModel $docModel } + } + Set-Content -Path $filePath -Value $content -Encoding UTF8 + if ($fmt -eq 'Html') { $htmlFile = $filePath } + } -# -Show defaults to on interactively and off in CI (Test-InforcerInteractiveHost), so a human -# who asked for a report sees it while a build agent is never handed a browser to open. -if ($Show -and $htmlFile -and (Test-Path -LiteralPath $htmlFile)) { - $fullHtmlPath = (Resolve-Path -LiteralPath $htmlFile).Path - if ($openedHtml.Add($fullHtmlPath)) { - if ($IsMacOS) { Start-Process 'open' -ArgumentList $fullHtmlPath } - elseif ($IsWindows) { Start-Process $fullHtmlPath } - elseif ($IsLinux) { Start-Process 'xdg-open' -ArgumentList $fullHtmlPath } + $fileInfo = Get-Item -LiteralPath $filePath + $sizeKb = [math]::Round($fileInfo.Length / 1KB, 1) + Write-Host " Exported: $filePath ($sizeKb KB)" -ForegroundColor Green + $fileInfo } -} -Write-Host "Done. $($Format.Count) file(s) exported for tenant '$($docModel.TenantName)'." -ForegroundColor Cyan + # -Show defaults to on interactively and off in CI (Test-InforcerInteractiveHost), so a human + # who asked for a report sees it while a build agent is never handed a browser to open. + if ($Show -and $htmlFile -and (Test-Path -LiteralPath $htmlFile)) { + $fullHtmlPath = (Resolve-Path -LiteralPath $htmlFile).Path + if ($openedHtml.Add($fullHtmlPath)) { + if ($IsMacOS) { Start-Process 'open' -ArgumentList $fullHtmlPath } + elseif ($IsWindows) { Start-Process $fullHtmlPath } + elseif ($IsLinux) { Start-Process 'xdg-open' -ArgumentList $fullHtmlPath } + } + } + + Write-Host "Done. $($Format.Count) file(s) exported for tenant '$($docModel.TenantName)'." -ForegroundColor Cyan +} } } From bda818a0a58d52654a9d9cd55a8da6a9a11687e7 Mon Sep 17 00:00:00 2001 From: Roy Klooster <76492458+royklo@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:49:08 +0100 Subject: [PATCH 2/8] fix: Copilot round 1 on #54 - Authentication combinations are resolved only on Allowed Combinations. Any value with a semicolon was rewritten, so a Chrome extension list or a script holding ";" and a method name ("sms") was changed in the document. - Baselines whose names make the same file name (Tier 1, Tier-1) get their own file instead of overwriting each other. - A list and an item label with fields under it are headers (IsConfigured $false), so comparisons keep them in the setting path, and the module's HTML shows an empty header instead of hiding it as an empty setting. A name-only item stays a setting. - Objects and lists nested inside a list item are rendered (a passkey profile's Key Restrictions). Each fix has a test that fails without it. Full suite 868 passed, 1 environment-dependent failure also on main. Co-Authored-By: Claude Opus 5.5 --- Tests/Fix.DocReadability.Tests.ps1 | 46 +++++++++++++++++++ module/Private/ConvertTo-InforcerDocModel.ps1 | 3 +- module/Private/ConvertTo-InforcerHtml.ps1 | 4 ++ .../Private/ConvertTo-InforcerSettingRows.ps1 | 34 ++++++++------ .../Export-InforcerTenantDocumentation.ps1 | 4 ++ 5 files changed, 77 insertions(+), 14 deletions(-) diff --git a/Tests/Fix.DocReadability.Tests.ps1 b/Tests/Fix.DocReadability.Tests.ps1 index e027aea..8c38e80 100644 --- a/Tests/Fix.DocReadability.Tests.ps1 +++ b/Tests/Fix.DocReadability.Tests.ps1 @@ -71,6 +71,27 @@ Describe 'ConvertTo-FlatSettingRows shows what the policy configures' { $rows[1].Value | Should -Be '00000000-0000-0000-0000-0000000000a1' -Because 'as a value, GUID resolution and masking can reach it' } + It 'marks a list and its item labels as headers, so comparisons keep their context' { + $rows = @(Get-ReadabilityRows ([pscustomobject]@{ includeTargets = @([pscustomobject]@{ targetType = 'group'; id = 'all_users' }) })) + $rows[0].IsConfigured | Should -BeFalse -Because 'the list is a parent in the setting path' + $rows[1].IsConfigured | Should -BeFalse -Because 'Item 1 is a parent of its fields' + @($rows | Where-Object { $_.Value -eq 'all_users' })[0].IsConfigured | Should -BeTrue + } + + It 'keeps a name-only list item a setting' { + $rows = @(Get-ReadabilityRows ([pscustomobject]@{ apps = @([pscustomobject]@{ bundleId = 'com.example.app' }) })) + @($rows | Where-Object { $_.Name -eq 'com.example.app' })[0].IsConfigured | Should -BeTrue + } + + It 'renders objects and lists nested inside a list item' { + $rows = @(Get-ReadabilityRows ([pscustomobject]@{ profiles = @([pscustomobject]@{ name = 'P1' + options = [pscustomobject]@{ enabled = $true }; types = @('a', 'b') }) })) + $enabled = @($rows | Where-Object { $_.Name -match 'Enabled' -and $_.Value -eq 'True' }) + $enabled.Count | Should -Be 1 + $enabled[0].Indent | Should -Be 3 + @($rows | Where-Object { $_.Value -eq 'a, b' }).Count | Should -Be 1 + } + It 'keeps list entries that hold a comma apart' { $rows = Get-ReadabilityRows ([pscustomobject]@{ allowedCombinations = @('fido2', 'password,softwareOath') }) $rows[0].Value | Should -Be 'fido2; password,softwareOath' @@ -95,6 +116,24 @@ Describe 'Authentication strength combinations read as combinations' { } } +Describe 'Only Allowed Combinations is read as authentication combinations' { + It 'leaves other values with semicolons and commas exactly as configured' { + $model = & $script:M { + ConvertTo-InforcerDocModel -DocData @{ + Tenant = [pscustomobject]@{ tenantFriendlyName = 'T'; msTenantId = '00000000-0000-0000-0000-000000000001' } + TenantId = 1; CollectedAt = [datetime]::UtcNow; Baselines = @() + Policies = @([pscustomobject]@{ id = 'p1'; displayName = 'Chrome'; policyTypeId = 3; product = 'Intune' + primaryGroup = 'Windows'; secondaryGroup = 'Configuration' + policyData = [pscustomobject]@{ extensionList = 'abc;https://clients2.google.com/crx, def;sms' + scriptContent = 'Write-Output sms,voice; Write-Output fido2' } }) + } + } + $rows = foreach ($p in $model.Products.Values) { foreach ($c in $p.Categories.Values) { foreach ($pol in $c) { $pol.Settings } } } + @($rows | Where-Object { $_.Value -eq 'abc;https://clients2.google.com/crx, def;sms' }).Count | Should -Be 1 + @($rows | Where-Object { "$($_.Value)" -match '\+' }).Count | Should -Be 0 + } +} + Describe 'Export-InforcerTenantDocumentation with several baselines' { BeforeEach { Mock -ModuleName InforcerCommunity Test-InforcerSession { $true } @@ -140,6 +179,13 @@ Describe 'Export-InforcerTenantDocumentation with several baselines' { @($files.Name | Sort-Object) | Should -Be @('Contoso-Baseline-A-Documentation.md', 'Contoso-Baseline-B-Documentation.md') } + It 'gives baselines whose names make the same file name their own file' { + $dir = Join-Path $TestDrive 'collide' + $files = @(Export-InforcerTenantDocumentation -TenantId 1 -Baseline 'Tier A', 'Tier-A' -Format Markdown -OutputPath $dir -Show:$false) + @($files.FullName | Sort-Object -Unique).Count | Should -Be 2 + @(Get-ChildItem $dir).Count | Should -Be 2 + } + It 'refuses a file -OutputPath for several baselines' { { Export-InforcerTenantDocumentation -TenantId 1 -Baseline 'Baseline A', 'Baseline B' -Format Html -OutputPath (Join-Path $TestDrive 'one.html') -Show:$false } | Should -Throw -ErrorId 'OutputPathIsFileForSeveralBaselines*' diff --git a/module/Private/ConvertTo-InforcerDocModel.ps1 b/module/Private/ConvertTo-InforcerDocModel.ps1 index 5ccfa44..5c69ba6 100644 --- a/module/Private/ConvertTo-InforcerDocModel.ps1 +++ b/module/Private/ConvertTo-InforcerDocModel.ps1 @@ -419,7 +419,8 @@ function ConvertTo-InforcerDocModel { $val = $row.Value # Resolve camelCase values (e.g. allowedCombinations like "password,softwareOath") $val = $row.Value - if (-not [string]::IsNullOrWhiteSpace($val) -and $val -is [string] -and $val.Contains(';')) { + if ($name -eq 'Allowed Combinations' -and $val -is [string] -and $val.Contains(';')) { + # Only this setting: other values hold semicolons too (scripts, extension lists). # A list whose items hold commas is joined with '; ' (ConvertTo-FlatSettingRows), so # each item is one combination: "password,softwareOath" -> "Password + Software OATH Token". $row.Value = @(foreach ($item in $val -split ';') { diff --git a/module/Private/ConvertTo-InforcerHtml.ps1 b/module/Private/ConvertTo-InforcerHtml.ps1 index 39efe9b..fa577c0 100644 --- a/module/Private/ConvertTo-InforcerHtml.ps1 +++ b/module/Private/ConvertTo-InforcerHtml.ps1 @@ -999,6 +999,10 @@ tr:hover td { background: var(--row-hover); } elseif ($trimmed -match '^\s*#!/') { $codeClass = 'sh-code'; $summaryClass = 'sh-code-summary'; $label = 'View script' } else { $codeClass = 'ps-code'; $summaryClass = 'ps-code-summary'; $label = 'View script' } $settingVal = "
$label
$encCode
" + } elseif ($setting.IsConfigured -eq $false -and [string]::IsNullOrWhiteSpace("$($setting.Value)")) { + # A header: left blank rather than marked empty, so hide-empty keeps it visible + # and the rows under it keep their context. + $settingVal = '' } else { $settingVal = ConvertTo-SafeHtmlValue -Value $setting.Value -AllowMultiValue } diff --git a/module/Private/ConvertTo-InforcerSettingRows.ps1 b/module/Private/ConvertTo-InforcerSettingRows.ps1 index b452d38..a35284a 100644 --- a/module/Private/ConvertTo-InforcerSettingRows.ps1 +++ b/module/Private/ConvertTo-InforcerSettingRows.ps1 @@ -298,11 +298,13 @@ function ConvertTo-FlatSettingRows { } } } else { + # A header (IsConfigured $false): the items below it are the settings, and a + # comparison needs the list in their path to tell two lists' items apart. [void]$rows.Add([PSCustomObject]@{ Name = (ConvertTo-FriendlySettingName -Name $prop.Name) Value = "$($val.Count) items" Indent = $Depth - IsConfigured = $true + IsConfigured = $false }) $itemNumber = 0 foreach ($item in $val) { @@ -332,22 +334,28 @@ function ConvertTo-FlatSettingRows { [void]$rows.Add([PSCustomObject]@{ Name = (ConvertTo-FriendlySettingName -Name $itemName); Value = $vp.Value.ToString(); Indent = $Depth + 1; IsConfigured = $true }) continue } - # Every other scalar field of the item. They used to be dropped, so a list such - # as an authentication method's Include Targets showed "1 items" and nothing else. - $fields = @(foreach ($ip in $item.PSObject.Properties) { + # Every other field of the item: scalars as rows, objects and lists through the same + # rendering as any setting. They used to be dropped, so an authentication method's + # Include Targets showed "1 items" and nothing else. + $fieldRows = [System.Collections.Generic.List[object]]::new() + foreach ($ip in $item.PSObject.Properties) { if ($ip.Name -match '@odata' -or $ip.Name -eq $labelField -or ($itemName -and $ip.Name -eq 'id')) { continue } $iv = $ip.Value - if (($iv -is [string] -or $iv -is [ValueType]) -and "$iv" -ne '') { $ip } - }) - if (-not $itemName -and $fields.Count -eq 1) { - [void]$rows.Add([PSCustomObject]@{ Name = (ConvertTo-FriendlySettingName -Name $fields[0].Name); Value = $fields[0].Value.ToString(); Indent = $Depth + 1; IsConfigured = $true }) - continue + if ($iv -is [string] -or $iv -is [ValueType]) { + if ("$iv" -ne '') { $fieldRows.Add([PSCustomObject]@{ Name = (ConvertTo-FriendlySettingName -Name $ip.Name); Value = "$iv"; Indent = $Depth + 2; IsConfigured = $true }) } + } elseif ($null -ne $iv) { + foreach ($r in (ConvertTo-FlatSettingRows -PolicyData ([PSCustomObject]@{ $ip.Name = $iv }) -Depth ($Depth + 2))) { $fieldRows.Add($r) } + } } - if (-not $itemName -and $fields.Count -eq 0) { continue } - [void]$rows.Add([PSCustomObject]@{ Name = $(if ($itemName) { $itemName } else { "Item $itemNumber" }); Value = ''; Indent = $Depth + 1; IsConfigured = $true }) - foreach ($f in $fields) { - [void]$rows.Add([PSCustomObject]@{ Name = (ConvertTo-FriendlySettingName -Name $f.Name); Value = $f.Value.ToString(); Indent = $Depth + 2; IsConfigured = $true }) + if (-not $itemName -and $fieldRows.Count -eq 1 -and $fieldRows[0].IsConfigured) { + $fieldRows[0].Indent = $Depth + 1 + [void]$rows.Add($fieldRows[0]) + continue } + if (-not $itemName -and $fieldRows.Count -eq 0) { continue } + # The label is a header over its fields; a name-only item is itself the setting. + [void]$rows.Add([PSCustomObject]@{ Name = $(if ($itemName) { $itemName } else { "Item $itemNumber" }); Value = ''; Indent = $Depth + 1; IsConfigured = ($fieldRows.Count -eq 0) }) + foreach ($r in $fieldRows) { [void]$rows.Add($r) } } } } else { diff --git a/module/Public/Export-InforcerTenantDocumentation.ps1 b/module/Public/Export-InforcerTenantDocumentation.ps1 index f954987..7b2a0e2 100644 --- a/module/Public/Export-InforcerTenantDocumentation.ps1 +++ b/module/Public/Export-InforcerTenantDocumentation.ps1 @@ -208,6 +208,8 @@ if ($FetchGraphData) { # tenant), a baseline's membership is a fraction of a second. Each pass starts from the full list. $allPolicies = @($docData.Policies) $baselineTargets = @(if ($Baseline) { $Baseline } else { $null }) +# 'Tier 1' and 'Tier-1' make the same file name; the second would overwrite the first. +$usedFileStems = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) foreach ($baselineTarget in $baselineTargets) { $docData.Policies = $allPolicies @@ -300,6 +302,8 @@ foreach ($baselineTarget in $baselineTargets) { $safeName = $docModel.TenantName -replace '[^\w\-]', '-' # Several baselines in one call each get their own file. if ($baselineTargets.Count -gt 1) { $safeName += '-' + ($baselineFilterName -replace '[^\w\-]', '-') } + $stem = $safeName; $n = 2 + while (-not $usedFileStems.Add($safeName)) { $safeName = "$stem-$n"; $n++ } foreach ($fmt in $Format) { $formatIndex++ From 82c0e7ea91e22cc93535ca08bbfec0c927963abf Mon Sep 17 00:00:00 2001 From: Roy Klooster <76492458+royklo@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:58:43 +0100 Subject: [PATCH 3/8] fix: Copilot round 2 on #54 - List item fields go through ConvertTo-FlatSettingRows like any setting, so an encoded payload or script inside an item is decoded and marked as code. The item's id (when it has no label) and description are added explicitly, since the renderer skips both as policy metadata; empty fields and app version hashes no longer render. - Dotted-parent deduplication is per object instead of per policy, so two list items with the same dotted keys each keep the parent row in their path. Checked over all 293 policies of the Blueprint Library: no configured value is lost, only empty rows and MAM app version hashes. Full suite 871 passed, 1 environment-dependent failure also on main. Co-Authored-By: Claude Opus 5.5 --- Tests/Fix.DocReadability.Tests.ps1 | 18 ++++++++++ .../Private/ConvertTo-InforcerSettingRows.ps1 | 34 +++++++++++-------- 2 files changed, 38 insertions(+), 14 deletions(-) diff --git a/Tests/Fix.DocReadability.Tests.ps1 b/Tests/Fix.DocReadability.Tests.ps1 index 8c38e80..400f333 100644 --- a/Tests/Fix.DocReadability.Tests.ps1 +++ b/Tests/Fix.DocReadability.Tests.ps1 @@ -92,6 +92,24 @@ Describe 'ConvertTo-FlatSettingRows shows what the policy configures' { @($rows | Where-Object { $_.Value -eq 'a, b' }).Count | Should -Be 1 } + It 'decodes an encoded payload inside a list item like any other payload' { + $b64 = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes('')) + $rows = @(Get-ReadabilityRows ([pscustomobject]@{ profiles = @([pscustomobject]@{ name = 'P1'; payload = $b64 }) })) + @($rows | Where-Object { "$($_.Value)" -like '__SCRIPT_CODE__ Date: Mon, 16 Nov 2026 18:04:33 +0100 Subject: [PATCH 4/8] fix: keep a dotted @odata.type setting inside a list item Copilot's verdict on 82c0e7e: the list-item path dropped every @odata key before the renderer saw it, so a dotted @odata.type setting (the shape this PR makes visible at policy level) was still lost inside an item. The renderer already keeps that shape and skips the rest; the item path now leaves @odata keys to it. No change on the Blueprint Library's 293 policies. Co-Authored-By: Claude Opus 5.5 --- Tests/Fix.DocReadability.Tests.ps1 | 7 +++++++ module/Private/ConvertTo-InforcerSettingRows.ps1 | 3 ++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/Tests/Fix.DocReadability.Tests.ps1 b/Tests/Fix.DocReadability.Tests.ps1 index 400f333..ef54d43 100644 --- a/Tests/Fix.DocReadability.Tests.ps1 +++ b/Tests/Fix.DocReadability.Tests.ps1 @@ -103,6 +103,13 @@ Describe 'ConvertTo-FlatSettingRows shows what the policy configures' { @($rows | Where-Object { $_.Name -eq 'Description' -and $_.Value -eq 'Shadow AI' }).Count | Should -Be 1 } + It 'keeps a dotted @odata.type setting inside a list item' { + $rows = @(Get-ReadabilityRows ([pscustomobject]@{ items = @([pscustomobject]@{ name = 'P1' + '@odata.type' = '#microsoft.graph.x'; 'registration.allowed.@odata.type' = '#microsoft.graph.allDeviceRegistrationMembership' }) })) + @($rows | Where-Object { $_.Value -eq 'All Device Registration Membership' }).Count | Should -Be 1 + @($rows | Where-Object { "$($_.Value)" -match 'microsoft\.graph' }).Count | Should -Be 0 + } + It 'gives every list item its own dotted headers' { $rows = @(Get-ReadabilityRows ([pscustomobject]@{ profiles = @( [pscustomobject]@{ name = 'P1'; options = [pscustomobject]@{ 'mode.level' = 1 } } diff --git a/module/Private/ConvertTo-InforcerSettingRows.ps1 b/module/Private/ConvertTo-InforcerSettingRows.ps1 index d2510f6..9325abd 100644 --- a/module/Private/ConvertTo-InforcerSettingRows.ps1 +++ b/module/Private/ConvertTo-InforcerSettingRows.ps1 @@ -338,7 +338,8 @@ function ConvertTo-FlatSettingRows { # Include Targets showed "1 items" and nothing else. $fields = [ordered]@{} foreach ($ip in $item.PSObject.Properties) { - if ($ip.Name -match '@odata' -or $ip.Name -eq $labelField -or ($itemName -and $ip.Name -eq 'id')) { continue } + # @odata keys are left to the renderer, which keeps a dotted @odata.type setting. + if ($ip.Name -eq $labelField -or ($itemName -and $ip.Name -eq 'id')) { continue } $fields[$ip.Name] = $ip.Value } $fieldRows = [System.Collections.Generic.List[object]]::new() From f24f541c0452d0fe52bc2410156d06e56303ad43 Mon Sep 17 00:00:00 2001 From: Roy Klooster <76492458+royklo@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:08:40 +0100 Subject: [PATCH 5/8] docs: CHANGELOG 1.1.0 covers the review-round changes Headers stay visible in the HTML, list item objects/payloads/descriptions, list headers in Compare paths, and the -2 suffix for colliding file names. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a193d5e..38c02f0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,7 @@ The format follows [Conventional Commits](https://www.conventionalcommits.org/) ### Features -- **`Export-InforcerTenantDocumentation -Baseline` takes several baselines** and reads the tenant once. The policy list is the slow call (20 to 40 s on a large tenant) and every `-Baseline` call used to repeat it; a baseline's membership takes a fraction of a second. Without `-OutputPath` it returns one DocModel per baseline; with a directory it writes one `{TenantName}-{Baseline}-Documentation` file per baseline (a single baseline keeps the old `{TenantName}-Documentation` name). A baseline that does not resolve is a `BaselineFilterFailed` error and the others are still exported. A file `-OutputPath` with several baselines is refused (`OutputPathIsFileForSeveralBaselines`). Measured on the inforcer Blueprint Library: 22 baselines in 48 s, previously about 34 minutes. Graph names (`-FetchGraphData`) and the Settings Catalog are resolved once for all of them. +- **`Export-InforcerTenantDocumentation -Baseline` takes several baselines** and reads the tenant once. The policy list is the slow call (20 to 40 s on a large tenant) and every `-Baseline` call used to repeat it; a baseline's membership takes a fraction of a second. Without `-OutputPath` it returns one DocModel per baseline; with a directory it writes one `{TenantName}-{Baseline}-Documentation` file per baseline (a single baseline keeps the old `{TenantName}-Documentation` name; two baseline names that make the same file name get `-2`). A baseline that does not resolve is a `BaselineFilterFailed` error and the others are still exported. A file `-OutputPath` with several baselines is refused (`OutputPathIsFileForSeveralBaselines`). Measured on the inforcer Blueprint Library: 22 baselines in 48 s, previously about 34 minutes. Graph names (`-FetchGraphData`) and the Settings Catalog are resolved once for all of them. ### Bug Fixes @@ -16,7 +16,8 @@ Found by reading every per-baseline document of the inforcer Blueprint Library. - **Settings nested more than two objects deep rendered as empty rows.** Below two levels an object fell through to `ToString()`, which is empty for a `PSCustomObject`. Conditional Access device filter rules, guest and external user types and Entra's passkey migration opt-out showed nothing. The limit is now 10 and exists only to stop runaway recursion. - **A setting stored as a dotted `@odata.type` was dropped.** Entra's device registration setting is `azureADRegistration.allowedToRegister.@odata.type = #microsoft.graph.allDeviceRegistrationMembership`, so "Users may register their devices" showed no setting. A dotted path ending in `@odata.type` is now rendered as that setting ("All Device Registration Membership"). Every other `@odata` key is still skipped. -- **List items showed only "N items".** An item without a display name or name was dropped, and the fields of named items were never shown, so an authentication method's Include Targets read "1 items" and nothing else. Each item now lists its fields ("Item 1", Target Type group, ID all_users). A single-field item is one row, and an id is never used as a label, so it stays a value that Graph resolution can reach. +- **List items showed only "N items".** An item without a display name or name was dropped, and the fields of named items were never shown, so an authentication method's Include Targets read "1 items" and nothing else. Each item now lists its fields ("Item 1", Target Type group, ID all_users). A single-field item is one row, and an id is never used as a label, so it stays a value that Graph resolution can reach. Objects, lists and encoded payloads inside an item render like any other setting, and an item's description is kept. A list and an item label with fields under it are headers, so `Compare-InforcerEnvironments` keeps them in the setting path. +- **The HTML hid section headers.** With "hide empty" on (the default), a header row with no value was hidden like an empty setting, so the rows under it lost their context. Headers now stay visible. - **Authentication strength combinations fell apart.** `allowedCombinations` items such as `password,softwareOath` were joined with commas and split again, giving "…, password, Software OATH Token, password, …". A list whose items contain a comma is now joined with `; `, and each combination reads "Password + Software OATH Token". ## [1.0.1] - 2026-11-16 From 957f1c56a8528936840cae7e0236e9305b117e8a Mon Sep 17 00:00:00 2001 From: Roy Klooster <76492458+royklo@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:15:28 +0100 Subject: [PATCH 6/8] fix: a blank -Baseline entry never exports the whole tenant Copilot's verdict on f24f541: -Baseline 'A', '' ran the blank entry without a filter and wrote a whole-tenant document beside A. Blank entries are skipped; only an omitted or all-blank -Baseline documents the whole tenant, as before. The test failed before the fix (3 documents for 1 baseline). Co-Authored-By: Claude Opus 5.5 --- Tests/Fix.DocReadability.Tests.ps1 | 6 ++++++ module/Public/Export-InforcerTenantDocumentation.ps1 | 5 ++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/Tests/Fix.DocReadability.Tests.ps1 b/Tests/Fix.DocReadability.Tests.ps1 index ef54d43..2b9d94d 100644 --- a/Tests/Fix.DocReadability.Tests.ps1 +++ b/Tests/Fix.DocReadability.Tests.ps1 @@ -211,6 +211,12 @@ Describe 'Export-InforcerTenantDocumentation with several baselines' { @(Get-ChildItem $dir).Count | Should -Be 2 } + It 'never turns a blank entry in the list into a whole-tenant document' { + $models = @(Export-InforcerTenantDocumentation -TenantId 1 -Baseline 'Baseline A', '', ' ') + $models.Count | Should -Be 1 + $models[0].FilterBaseline | Should -Be 'Baseline A' + } + It 'refuses a file -OutputPath for several baselines' { { Export-InforcerTenantDocumentation -TenantId 1 -Baseline 'Baseline A', 'Baseline B' -Format Html -OutputPath (Join-Path $TestDrive 'one.html') -Show:$false } | Should -Throw -ErrorId 'OutputPathIsFileForSeveralBaselines*' diff --git a/module/Public/Export-InforcerTenantDocumentation.ps1 b/module/Public/Export-InforcerTenantDocumentation.ps1 index 7b2a0e2..427b2f6 100644 --- a/module/Public/Export-InforcerTenantDocumentation.ps1 +++ b/module/Public/Export-InforcerTenantDocumentation.ps1 @@ -207,7 +207,10 @@ if ($FetchGraphData) { # One tenant read serves every -Baseline: the policy list is the slow call (20-40 s on a large # tenant), a baseline's membership is a fraction of a second. Each pass starts from the full list. $allPolicies = @($docData.Policies) -$baselineTargets = @(if ($Baseline) { $Baseline } else { $null }) +# A blank entry is skipped, never read as "no filter": that would put the whole tenant in a +# document beside the baselines asked for. Only an omitted or all-blank -Baseline means everything. +$named = @($Baseline | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }) +$baselineTargets = @(if ($named.Count) { $named } else { $null }) # 'Tier 1' and 'Tier-1' make the same file name; the second would overwrite the first. $usedFileStems = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) foreach ($baselineTarget in $baselineTargets) { From 05f0729ee099600003ed40677c066e552f4069df Mon Sep 17 00:00:00 2001 From: Roy Klooster <76492458+royklo@users.noreply.github.com> Date: Mon, 16 Nov 2026 20:29:56 +0100 Subject: [PATCH 7/8] fix: a field every list item shares is shown once, and a MAM app is one row again Red/blue/green on #54. Defender's custom indicators (492 Shadow AI domains) repeated twelve identical fields per domain: one policy went from 495 to 8,400 rows (Markdown 17 KB to 358 KB). A top-level field with the same value on every item now shows once under 'All items', and a field repeating the item's label is left out: 1,983 rows, 89 KB. A MAM app labelled from mobileAppIdentifier no longer repeats its package id under itself. Mutation testing found four behaviours nothing asserted (empty item fields dropped, empty unlabelled items skipped, unknown combination methods joined with +, HTML header left blank); the tests now cover them. 41/41 mutations caught. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- Tests/Fix.DocReadability.Tests.ps1 | 62 +++++++++++++++++-- .../Private/ConvertTo-InforcerSettingRows.ps1 | 33 ++++++++-- 3 files changed, 87 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 38c02f0..bfb4953 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,7 +16,7 @@ Found by reading every per-baseline document of the inforcer Blueprint Library. - **Settings nested more than two objects deep rendered as empty rows.** Below two levels an object fell through to `ToString()`, which is empty for a `PSCustomObject`. Conditional Access device filter rules, guest and external user types and Entra's passkey migration opt-out showed nothing. The limit is now 10 and exists only to stop runaway recursion. - **A setting stored as a dotted `@odata.type` was dropped.** Entra's device registration setting is `azureADRegistration.allowedToRegister.@odata.type = #microsoft.graph.allDeviceRegistrationMembership`, so "Users may register their devices" showed no setting. A dotted path ending in `@odata.type` is now rendered as that setting ("All Device Registration Membership"). Every other `@odata` key is still skipped. -- **List items showed only "N items".** An item without a display name or name was dropped, and the fields of named items were never shown, so an authentication method's Include Targets read "1 items" and nothing else. Each item now lists its fields ("Item 1", Target Type group, ID all_users). A single-field item is one row, and an id is never used as a label, so it stays a value that Graph resolution can reach. Objects, lists and encoded payloads inside an item render like any other setting, and an item's description is kept. A list and an item label with fields under it are headers, so `Compare-InforcerEnvironments` keeps them in the setting path. +- **List items showed only "N items".** An item without a display name or name was dropped, and the fields of named items were never shown, so an authentication method's Include Targets read "1 items" and nothing else. Each item now lists its fields ("Item 1", Target Type group, ID all_users). A single-field item is one row, and an id is never used as a label, so it stays a value that Graph resolution can reach. Objects, lists and encoded payloads inside an item render like any other setting, and an item's description is kept. A list and an item label with fields under it are headers, so `Compare-InforcerEnvironments` keeps them in the setting path. A field with the same value on every item of a list is shown once, under "All items", and a field that repeats the item's label is left out: Defender's custom indicators (492 Shadow AI domains) would otherwise repeat twelve identical fields per domain, about 8,400 rows for one policy, where it is now about 2,000. A MAM app is one row again, labelled by its package id. - **The HTML hid section headers.** With "hide empty" on (the default), a header row with no value was hidden like an empty setting, so the rows under it lost their context. Headers now stay visible. - **Authentication strength combinations fell apart.** `allowedCombinations` items such as `password,softwareOath` were joined with commas and split again, giving "…, password, Software OATH Token, password, …". A list whose items contain a comma is now joined with `; `, and each combination reads "Password + Software OATH Token". diff --git a/Tests/Fix.DocReadability.Tests.ps1 b/Tests/Fix.DocReadability.Tests.ps1 index 2b9d94d..c25f793 100644 --- a/Tests/Fix.DocReadability.Tests.ps1 +++ b/Tests/Fix.DocReadability.Tests.ps1 @@ -50,9 +50,10 @@ Describe 'ConvertTo-FlatSettingRows shows what the policy configures' { } It 'lists every field of a list item that has no name' { - $rows = @(Get-ReadabilityRows ([pscustomobject]@{ includeTargets = @([pscustomobject]@{ targetType = 'group'; id = 'all_users' }) })) - $rows[0].Value | Should -Be '1 items' + $rows = @(Get-ReadabilityRows ([pscustomobject]@{ includeTargets = @([pscustomobject]@{ targetType = 'group'; id = 'all_users' }; [pscustomobject]@{ id = $null }) })) + $rows[0].Value | Should -Be '2 items' $rows[1].Name | Should -Be 'Item 1' + @($rows | Where-Object { $_.Name -eq 'Item 2' }).Count | Should -Be 0 -Because 'an item with nothing set has nothing to show' @($rows | Where-Object { $_.Value -eq 'group' -and $_.Indent -eq 2 }).Count | Should -Be 1 @($rows | Where-Object { $_.Value -eq 'all_users' -and $_.Indent -eq 2 }).Count | Should -Be 1 } @@ -122,6 +123,46 @@ Describe 'ConvertTo-FlatSettingRows shows what the policy configures' { $rows[0].Value | Should -Be 'fido2; password,softwareOath' (Get-ReadabilityRows ([pscustomobject]@{ x = @('a', 'b') }))[0].Value | Should -Be 'a, b' } + + It 'does not repeat a MAM app''s package id under its own label' { + $rows = @(Get-ReadabilityRows ([pscustomobject]@{ apps = @([pscustomobject]@{ id = 'com.example.app.android' + mobileAppIdentifier = [pscustomobject]@{ '@odata.type' = '#microsoft.graph.androidMobileAppIdentifier'; packageId = 'com.example.app' } }) })) + $rows.Count | Should -Be 2 + $rows[1].Name | Should -Be 'com.example.app' + $rows[1].IsConfigured | Should -BeTrue + } + + It 'shows a field every item shares once, and only what differs per item' { + # Shape of Defender's custom indicators: 492 domains that differ only in name, type and timestamps. + $items = @(foreach ($d in 'a.example', 'b.example', 'c.example') { + [pscustomobject]@{ displayName = $d; title = $d; indicatorValue = $d; action = 'Block'; severity = 'Informational'; application = $null; educateUrl = '' + indicatorType = $(if ($d -eq 'c.example') { 'Url' } else { 'DomainName' }) } }) + $rows = @(Get-ReadabilityRows ([pscustomobject]@{ indicators = $items })) + $all = @($rows | Where-Object { $_.Name -eq 'All items' }) + $all.Count | Should -Be 1 + $all[0].Indent | Should -Be 1 + $all[0].IsConfigured | Should -BeFalse + @($rows | Where-Object { $_.Name -eq 'Action' }).Count | Should -Be 1 + @($rows | Where-Object { $_.Name -eq 'Severity' }).Count | Should -Be 1 + @($rows | Where-Object { $_.Name -eq 'Indicator Type' }).Count | Should -Be 3 -Because 'it differs, so it stays per item' + @($rows | Where-Object { $_.Value -in 'a.example', 'b.example', 'c.example' }).Count | Should -Be 0 -Because 'title and value repeat the label' + @($rows | Where-Object { $_.Name -eq 'b.example' })[0].IsConfigured | Should -BeFalse + @($rows | Where-Object { $_.IsConfigured -and "$($_.Value)" -eq '' }).Count | Should -Be 0 -Because 'a field left empty is not a setting' + } + + It 'keeps a nested setting under its own item even when every item has it' { + $rows = @(Get-ReadabilityRows ([pscustomobject]@{ profiles = @( + [pscustomobject]@{ name = 'P1'; options = [pscustomobject]@{ enabled = $true } } + [pscustomobject]@{ name = 'P2'; options = [pscustomobject]@{ enabled = $true } }) })) + @($rows | Where-Object { $_.Name -eq 'All items' }).Count | Should -Be 0 -Because 'a nested row has no place there without its parent' + @($rows | Where-Object { $_.Name -match 'Enabled' }).Count | Should -Be 2 + } + + It 'keeps a single item''s fields with the item' { + $rows = @(Get-ReadabilityRows ([pscustomobject]@{ includeTargets = @([pscustomobject]@{ displayName = 'G'; targetType = 'group' }) })) + @($rows | Where-Object { $_.Name -eq 'All items' }).Count | Should -Be 0 + @($rows | Where-Object { $_.Value -eq 'group' })[0].Indent | Should -Be 2 + } } Describe 'Authentication strength combinations read as combinations' { @@ -133,11 +174,11 @@ Describe 'Authentication strength combinations read as combinations' { Policies = @([pscustomobject]@{ id = 'p1'; displayName = 'CA'; policyTypeId = 1; product = 'Entra' primaryGroup = 'Conditional Access'; secondaryGroup = 'Policies' policyData = [pscustomobject]@{ grantControls = [pscustomobject]@{ authenticationStrength = [pscustomobject]@{ - allowedCombinations = @('fido2', 'password,softwareOath', 'password,microsoftAuthenticatorPush') } } } }) + allowedCombinations = @('fido2', 'password,softwareOath', 'password,microsoftAuthenticatorPush', 'password,futureMethod') } } } }) } } $row = foreach ($p in $model.Products.Values) { foreach ($c in $p.Categories.Values) { foreach ($pol in $c) { $pol.Settings | Where-Object { $_.Name -eq 'Allowed Combinations' } } } } - $row.Value | Should -Be 'FIDO2 Security Key; Password + Software OATH Token; Password + Microsoft Authenticator' + $row.Value | Should -Be 'FIDO2 Security Key; Password + Software OATH Token; Password + Microsoft Authenticator; Password + futureMethod' } } @@ -227,3 +268,16 @@ Describe 'Export-InforcerTenantDocumentation with several baselines' { $files[0].Name | Should -Be 'Contoso-Documentation.md' } } + +Describe 'The HTML keeps section headers visible' { + It 'leaves a header''s value blank instead of marking it empty, so hide-empty keeps it' { + $html = & $script:M { + $settings = @([pscustomobject]@{ Name = 'Include Targets'; Value = ''; Indent = 0; IsConfigured = $false } + [pscustomobject]@{ Name = 'Target Type'; Value = 'group'; Indent = 1; IsConfigured = $true }) + ConvertTo-InforcerHtml -DocModel @{ TenantName = 'T'; TenantId = 't'; GeneratedAt = [datetime]::UtcNow + Products = [ordered]@{ Entra = @{ Categories = [ordered]@{ C = @(@{ Basics = @{ Name = 'P'; Description = '' }; Settings = $settings; Assignments = @() }) } } } } + } + $html | Should -Match 'Include Targets' + ([regex]::Matches($html, '')).Count | Should -Be 0 + } +} diff --git a/module/Private/ConvertTo-InforcerSettingRows.ps1 b/module/Private/ConvertTo-InforcerSettingRows.ps1 index 9325abd..db93238 100644 --- a/module/Private/ConvertTo-InforcerSettingRows.ps1 +++ b/module/Private/ConvertTo-InforcerSettingRows.ps1 @@ -306,6 +306,7 @@ function ConvertTo-FlatSettingRows { IsConfigured = $false }) $itemNumber = 0 + $entries = [System.Collections.Generic.List[object]]::new() foreach ($item in $val) { if ($item -isnot [PSObject]) { continue } $itemNumber++ @@ -322,7 +323,7 @@ function ConvertTo-FlatSettingRows { if ($mai -and $mai.Value -is [PSObject]) { foreach ($nameField in @('bundleId', 'packageId')) { $nv2 = $mai.Value.PSObject.Properties[$nameField] - if ($nv2 -and $nv2.Value) { $itemName = $nv2.Value.ToString(); break } + if ($nv2 -and $nv2.Value) { $itemName = $nv2.Value.ToString(); $labelField = 'mobileAppIdentifier'; break } } } } @@ -330,7 +331,7 @@ function ConvertTo-FlatSettingRows { # Protection) carries its setting in 'value'. $vp = $item.PSObject.Properties['value'] if ($itemName -and $vp -and ($vp.Value -is [string] -or $vp.Value -is [ValueType])) { - [void]$rows.Add([PSCustomObject]@{ Name = (ConvertTo-FriendlySettingName -Name $itemName); Value = $vp.Value.ToString(); Indent = $Depth + 1; IsConfigured = $true }) + $entries.Add(@{ Row = [PSCustomObject]@{ Name = (ConvertTo-FriendlySettingName -Name $itemName); Value = $vp.Value.ToString(); Indent = $Depth + 1; IsConfigured = $true } }) continue } # Every other field of the item, through the same rendering as any setting (decoding, @@ -352,16 +353,38 @@ function ConvertTo-FlatSettingRows { } foreach ($r in (ConvertTo-FlatSettingRows -PolicyData ([PSCustomObject]$fields) -Depth ($Depth + 2))) { if ($r.IsConfigured -and [string]::IsNullOrEmpty("$($r.Value)")) { continue } + # A field that repeats the label (an indicator's title and value) says nothing new. + if ($itemName -and $r.Indent -eq $Depth + 2 -and $r.IsConfigured -and "$($r.Value)" -eq $itemName) { continue } $fieldRows.Add($r) } - if (-not $itemName -and $fieldRows.Count -eq 1 -and $fieldRows[0].IsConfigured) { + $keys = [System.Collections.Generic.HashSet[string]]::new() + foreach ($r in $fieldRows) { if ($r.IsConfigured -and $r.Indent -eq $Depth + 2) { [void]$keys.Add("$($r.Name)`0$($r.Value)") } } + $entries.Add(@{ Name = $itemName; Number = $itemNumber; Fields = $fieldRows; Keys = $keys }) + } + # A top-level field with the same value on every item is shown once, under "All items": + # Defender's 492 Shadow AI indicators differ only in domain, type and timestamps, and + # repeating the other twelve fields per domain made one policy 8,000 rows. + $itemEntries = @($entries | Where-Object { $_.Fields }) + $shared = [System.Collections.Generic.HashSet[string]]::new() + if ($itemEntries.Count -gt 1) { + $shared.UnionWith($itemEntries[0].Keys) + foreach ($e in $itemEntries) { $shared.IntersectWith($e.Keys) } + } + if ($shared.Count) { + [void]$rows.Add([PSCustomObject]@{ Name = 'All items'; Value = ''; Indent = $Depth + 1; IsConfigured = $false }) + foreach ($r in $itemEntries[0].Fields) { if ($r.IsConfigured -and $r.Indent -eq $Depth + 2 -and $shared.Contains("$($r.Name)`0$($r.Value)")) { [void]$rows.Add($r) } } + } + foreach ($e in $entries) { + if ($e.Row) { [void]$rows.Add($e.Row); continue } + $fieldRows = @($e.Fields | Where-Object { -not ($_.IsConfigured -and $_.Indent -eq $Depth + 2 -and $shared.Contains("$($_.Name)`0$($_.Value)")) }) + if (-not $e.Name -and $fieldRows.Count -eq 1 -and $fieldRows[0].IsConfigured) { $fieldRows[0].Indent = $Depth + 1 [void]$rows.Add($fieldRows[0]) continue } - if (-not $itemName -and $fieldRows.Count -eq 0) { continue } + if (-not $e.Name -and $fieldRows.Count -eq 0) { continue } # The label is a header over its fields; a name-only item is itself the setting. - [void]$rows.Add([PSCustomObject]@{ Name = $(if ($itemName) { $itemName } else { "Item $itemNumber" }); Value = ''; Indent = $Depth + 1; IsConfigured = ($fieldRows.Count -eq 0) }) + [void]$rows.Add([PSCustomObject]@{ Name = $(if ($e.Name) { $e.Name } else { "Item $($e.Number)" }); Value = ''; Indent = $Depth + 1; IsConfigured = ($fieldRows.Count -eq 0) }) foreach ($r in $fieldRows) { [void]$rows.Add($r) } } } From 105fa60b3633067a62bfede7164e9c1b6f88adac Mon Sep 17 00:00:00 2001 From: Roy Klooster <76492458+royklo@users.noreply.github.com> Date: Mon, 16 Nov 2026 20:38:15 +0100 Subject: [PATCH 8/8] fix: All items only holds what every item has, and comparisons keep per-item fields Copilot on 05f0729. An item without the field was left out of the intersection, so All items could claim Block for an item that does not block; every entry now takes part, and a list with a name/value item is never hoisted. Compare-InforcerEnvironments builds its models with -ComparisonMode, which now reaches ConvertTo-FlatSettingRows and keeps each item's fields under it: with hoisting, one changed item moved the shared fields of the others and turned unchanged items into additions and removals. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- Tests/Fix.DocReadability.Tests.ps1 | 50 +++++++++++++++++++ module/Private/ConvertTo-InforcerDocModel.ps1 | 2 +- .../Private/ConvertTo-InforcerSettingRows.ps1 | 26 ++++++---- 4 files changed, 68 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bfb4953..f5aeb6d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,7 +16,7 @@ Found by reading every per-baseline document of the inforcer Blueprint Library. - **Settings nested more than two objects deep rendered as empty rows.** Below two levels an object fell through to `ToString()`, which is empty for a `PSCustomObject`. Conditional Access device filter rules, guest and external user types and Entra's passkey migration opt-out showed nothing. The limit is now 10 and exists only to stop runaway recursion. - **A setting stored as a dotted `@odata.type` was dropped.** Entra's device registration setting is `azureADRegistration.allowedToRegister.@odata.type = #microsoft.graph.allDeviceRegistrationMembership`, so "Users may register their devices" showed no setting. A dotted path ending in `@odata.type` is now rendered as that setting ("All Device Registration Membership"). Every other `@odata` key is still skipped. -- **List items showed only "N items".** An item without a display name or name was dropped, and the fields of named items were never shown, so an authentication method's Include Targets read "1 items" and nothing else. Each item now lists its fields ("Item 1", Target Type group, ID all_users). A single-field item is one row, and an id is never used as a label, so it stays a value that Graph resolution can reach. Objects, lists and encoded payloads inside an item render like any other setting, and an item's description is kept. A list and an item label with fields under it are headers, so `Compare-InforcerEnvironments` keeps them in the setting path. A field with the same value on every item of a list is shown once, under "All items", and a field that repeats the item's label is left out: Defender's custom indicators (492 Shadow AI domains) would otherwise repeat twelve identical fields per domain, about 8,400 rows for one policy, where it is now about 2,000. A MAM app is one row again, labelled by its package id. +- **List items showed only "N items".** An item without a display name or name was dropped, and the fields of named items were never shown, so an authentication method's Include Targets read "1 items" and nothing else. Each item now lists its fields ("Item 1", Target Type group, ID all_users). A single-field item is one row, and an id is never used as a label, so it stays a value that Graph resolution can reach. Objects, lists and encoded payloads inside an item render like any other setting, and an item's description is kept. A list and an item label with fields under it are headers, so `Compare-InforcerEnvironments` keeps them in the setting path. A field with the same value on every item of a list is shown once, under "All items", and a field that repeats the item's label is left out: Defender's custom indicators (492 Shadow AI domains) would otherwise repeat twelve identical fields per domain, about 8,400 rows for one policy, where it is now about 2,000. A field goes under "All items" only when every item has it with that value, and `Compare-InforcerEnvironments` keeps every item's own fields, so one changed item never moves the rest. A MAM app is one row again, labelled by its package id. - **The HTML hid section headers.** With "hide empty" on (the default), a header row with no value was hidden like an empty setting, so the rows under it lost their context. Headers now stay visible. - **Authentication strength combinations fell apart.** `allowedCombinations` items such as `password,softwareOath` were joined with commas and split again, giving "…, password, Software OATH Token, password, …". A list whose items contain a comma is now joined with `; `, and each combination reads "Password + Software OATH Token". diff --git a/Tests/Fix.DocReadability.Tests.ps1 b/Tests/Fix.DocReadability.Tests.ps1 index c25f793..f92ebe2 100644 --- a/Tests/Fix.DocReadability.Tests.ps1 +++ b/Tests/Fix.DocReadability.Tests.ps1 @@ -158,6 +158,23 @@ Describe 'ConvertTo-FlatSettingRows shows what the policy configures' { @($rows | Where-Object { $_.Name -match 'Enabled' }).Count | Should -Be 2 } + It 'never puts a field under All items when one item lacks it' { + $rows = @(Get-ReadabilityRows ([pscustomobject]@{ profiles = @( + [pscustomobject]@{ name = 'P1'; action = 'Block' } + [pscustomobject]@{ name = 'P2'; action = 'Block' } + [pscustomobject]@{ name = 'P3' }) })) + @($rows | Where-Object { $_.Name -eq 'All items' }).Count | Should -Be 0 -Because 'P3 does not block' + @($rows | Where-Object { $_.Name -eq 'Action' }).Count | Should -Be 2 + } + + It 'never puts a field under All items beside a name/value item' { + $rows = @(Get-ReadabilityRows ([pscustomobject]@{ values = @( + [pscustomobject]@{ name = 'A'; value = 'x' } + [pscustomobject]@{ name = 'B'; mode = 'on' } + [pscustomobject]@{ name = 'C'; mode = 'on' }) })) + @($rows | Where-Object { $_.Name -eq 'All items' }).Count | Should -Be 0 + } + It 'keeps a single item''s fields with the item' { $rows = @(Get-ReadabilityRows ([pscustomobject]@{ includeTargets = @([pscustomobject]@{ displayName = 'G'; targetType = 'group' }) })) @($rows | Where-Object { $_.Name -eq 'All items' }).Count | Should -Be 0 @@ -281,3 +298,36 @@ Describe 'The HTML keeps section headers visible' { ([regex]::Matches($html, '')).Count | Should -Be 0 } } + +Describe 'A comparison sees every list item''s own fields' { + It 'reports only the item that changed when the others share its old value' { + $result = & $script:M { + $model = { + param($p2Action) + ConvertTo-InforcerDocModel -ComparisonMode -DocData @{ + Tenant = [pscustomobject]@{ tenantFriendlyName = 'T'; msTenantId = '00000000-0000-0000-0000-000000000001' } + TenantId = 1; CollectedAt = [datetime]::UtcNow; Baselines = @() + Policies = @([pscustomobject]@{ id = 'p1'; displayName = 'Indicators'; policyTypeId = 3; product = 'Defender' + primaryGroup = 'Endpoint'; secondaryGroup = 'Indicators' + policyData = [pscustomobject]@{ indicators = @( + [pscustomobject]@{ displayName = 'a.example'; action = 'Block' } + [pscustomobject]@{ displayName = 'b.example'; action = $p2Action }) } }) + } + } + Compare-InforcerDocModels -SourceModel (& $model 'Block') -DestinationModel (& $model 'Allow') + } + $result.Counters.Conflicting | Should -Be 1 -Because 'only b.example changed' + $result.Counters.SourceOnly | Should -Be 0 + $result.Counters.DestOnly | Should -Be 0 + } + + It 'keeps item fields per item in lists nested inside objects and items too' { + $pd = [pscustomobject]@{ outer = [pscustomobject]@{ profiles = @([pscustomobject]@{ name = 'P1'; targets = @( + [pscustomobject]@{ displayName = 'a'; mode = 'on' } + [pscustomobject]@{ displayName = 'b'; mode = 'on' }) }) } } + $rows = @(& $script:M { param($pd) ConvertTo-FlatSettingRows -PolicyData $pd -ComparisonMode } $pd) + @($rows | Where-Object { $_.Name -eq 'All items' }).Count | Should -Be 0 + @($rows | Where-Object { $_.Name -eq 'Mode' }).Count | Should -Be 2 + @(Get-ReadabilityRows $pd | Where-Object { $_.Name -eq 'All items' }).Count | Should -Be 1 -Because 'a document still shows it once' + } +} diff --git a/module/Private/ConvertTo-InforcerDocModel.ps1 b/module/Private/ConvertTo-InforcerDocModel.ps1 index 5c69ba6..a6229f0 100644 --- a/module/Private/ConvertTo-InforcerDocModel.ps1 +++ b/module/Private/ConvertTo-InforcerDocModel.ps1 @@ -374,7 +374,7 @@ function ConvertTo-InforcerDocModel { } } elseif ($null -ne $policy.policyData) { # Non-catalog -- use ConvertTo-FlatSettingRows (per D-07) - foreach ($row in (ConvertTo-FlatSettingRows -PolicyData $policy.policyData)) { + foreach ($row in (ConvertTo-FlatSettingRows -PolicyData $policy.policyData -ComparisonMode:$ComparisonMode)) { [void]$settings.Add($row) } } diff --git a/module/Private/ConvertTo-InforcerSettingRows.ps1 b/module/Private/ConvertTo-InforcerSettingRows.ps1 index db93238..55a4868 100644 --- a/module/Private/ConvertTo-InforcerSettingRows.ps1 +++ b/module/Private/ConvertTo-InforcerSettingRows.ps1 @@ -224,6 +224,9 @@ function ConvertTo-FlatSettingRows { The policyData object from a non-catalog policy. May be $null (returns empty list). .PARAMETER Depth Current nesting depth (recursion accumulator). Default 0. + .PARAMETER ComparisonMode + Keep every list item's fields under that item. A document shows a field shared by every + item once; a comparison needs each item's own path, or one changed item moves the rest. .EXAMPLE ConvertTo-FlatSettingRows -PolicyData $policy.policyData #> @@ -233,7 +236,10 @@ function ConvertTo-FlatSettingRows { $PolicyData, [Parameter()] - [int]$Depth = 0 + [int]$Depth = 0, + + [Parameter()] + [switch]$ComparisonMode ) $rows = [System.Collections.Generic.List[object]]::new() @@ -274,7 +280,7 @@ function ConvertTo-FlatSettingRows { Indent = $Depth IsConfigured = $false }) - foreach ($r in (ConvertTo-FlatSettingRows -PolicyData $val -Depth ($Depth + 1))) { + foreach ($r in (ConvertTo-FlatSettingRows -PolicyData $val -Depth ($Depth + 1) -ComparisonMode:$ComparisonMode)) { [void]$rows.Add($r) } } elseif ($val -is [array] -and $val.Count -gt 0 -and $val[0] -is [PSObject] -and $Depth -lt $maxDepth) { @@ -291,7 +297,7 @@ function ConvertTo-FlatSettingRows { }) foreach ($item in $val) { if ($item -is [PSObject]) { - foreach ($r in (ConvertTo-FlatSettingRows -PolicyData $item -Depth ($Depth + 1))) { + foreach ($r in (ConvertTo-FlatSettingRows -PolicyData $item -Depth ($Depth + 1) -ComparisonMode:$ComparisonMode)) { [void]$rows.Add($r) } } @@ -351,10 +357,10 @@ function ConvertTo-FlatSettingRows { $fieldRows.Add([PSCustomObject]@{ Name = $own.Name; Value = "$($fields[$own.Key])"; Indent = $Depth + 2; IsConfigured = $true }) } } - foreach ($r in (ConvertTo-FlatSettingRows -PolicyData ([PSCustomObject]$fields) -Depth ($Depth + 2))) { + foreach ($r in (ConvertTo-FlatSettingRows -PolicyData ([PSCustomObject]$fields) -Depth ($Depth + 2) -ComparisonMode:$ComparisonMode)) { if ($r.IsConfigured -and [string]::IsNullOrEmpty("$($r.Value)")) { continue } # A field that repeats the label (an indicator's title and value) says nothing new. - if ($itemName -and $r.Indent -eq $Depth + 2 -and $r.IsConfigured -and "$($r.Value)" -eq $itemName) { continue } + if (-not $ComparisonMode -and $itemName -and $r.Indent -eq $Depth + 2 -and $r.IsConfigured -and "$($r.Value)" -eq $itemName) { continue } $fieldRows.Add($r) } $keys = [System.Collections.Generic.HashSet[string]]::new() @@ -364,15 +370,15 @@ function ConvertTo-FlatSettingRows { # A top-level field with the same value on every item is shown once, under "All items": # Defender's 492 Shadow AI indicators differ only in domain, type and timestamps, and # repeating the other twelve fields per domain made one policy 8,000 rows. - $itemEntries = @($entries | Where-Object { $_.Fields }) + # Every entry takes part, so "All items" never claims a field one of them lacks. $shared = [System.Collections.Generic.HashSet[string]]::new() - if ($itemEntries.Count -gt 1) { - $shared.UnionWith($itemEntries[0].Keys) - foreach ($e in $itemEntries) { $shared.IntersectWith($e.Keys) } + if (-not $ComparisonMode -and $entries.Count -gt 1 -and -not @($entries | Where-Object { $_.Row })) { + $shared.UnionWith($entries[0].Keys) + foreach ($e in $entries) { $shared.IntersectWith($e.Keys) } } if ($shared.Count) { [void]$rows.Add([PSCustomObject]@{ Name = 'All items'; Value = ''; Indent = $Depth + 1; IsConfigured = $false }) - foreach ($r in $itemEntries[0].Fields) { if ($r.IsConfigured -and $r.Indent -eq $Depth + 2 -and $shared.Contains("$($r.Name)`0$($r.Value)")) { [void]$rows.Add($r) } } + foreach ($r in $entries[0].Fields) { if ($r.IsConfigured -and $r.Indent -eq $Depth + 2 -and $shared.Contains("$($r.Name)`0$($r.Value)")) { [void]$rows.Add($r) } } } foreach ($e in $entries) { if ($e.Row) { [void]$rows.Add($e.Row); continue }