From 6f44e090cdf5f22c8f8df4fd3b10b3c7301bb161 Mon Sep 17 00:00:00 2001 From: Travis McDade Date: Sat, 31 Oct 2026 18:36:40 -0400 Subject: [PATCH 1/5] feat(report): prepare scoped redacted result exports --- .../report/ConvertTo-MtMaesterResult.ps1 | 19 ++- .../report/ConvertTo-MtRedactedResult.ps1 | 61 +++++++++ powershell/public/report/Get-MtHtmlReport.ps1 | 10 +- .../public/run/Add-MtTestResultDetail.ps1 | 16 ++- powershell/public/run/Invoke-Maester.ps1 | 44 ++----- .../tests/functions/RedactedResult.Tests.ps1 | 116 ++++++++++++++++++ .../functions/ResultConfigRedaction.Tests.ps1 | 89 ++++++++++++++ 7 files changed, 314 insertions(+), 41 deletions(-) create mode 100644 powershell/internal/report/ConvertTo-MtRedactedResult.ps1 create mode 100644 powershell/tests/functions/RedactedResult.Tests.ps1 create mode 100644 powershell/tests/functions/ResultConfigRedaction.Tests.ps1 diff --git a/powershell/internal/report/ConvertTo-MtMaesterResult.ps1 b/powershell/internal/report/ConvertTo-MtMaesterResult.ps1 index 1b31405b4a..6059781ddd 100644 --- a/powershell/internal/report/ConvertTo-MtMaesterResult.ps1 +++ b/powershell/internal/report/ConvertTo-MtMaesterResult.ps1 @@ -674,10 +674,23 @@ function New-MtResultConfig { ) if ($null -eq $RunConfig) { return $null } - if ($NativeRows.Count -eq 0) { return $RunConfig } + # Configuration is JSON-shaped, as normalized by Resolve-MtRunConfig. Detach every nested value + # before redaction so reporting cannot change caller input or settings still used by checks. + $detached = $RunConfig | ConvertTo-Json -Depth 100 | ConvertFrom-Json -NoEnumerate + if (-not $script:__MtSettingsRegistry) { + $script:__MtSettingsRegistry = Import-PowerShellDataFile -Path (Join-Path $ExecutionContext.SessionState.Module.ModuleBase 'assets/MaesterSettings.psd1') + } + if ($detached.PSObject.Properties['GlobalSettings'] -and $null -ne $detached.GlobalSettings) { + foreach ($key in $script:__MtSettingsRegistry.Settings.Keys) { + if ($script:__MtSettingsRegistry.Settings[$key].Sensitive -and $detached.GlobalSettings.PSObject.Properties[$key]) { + $detached.GlobalSettings.$key = '' + } + } + } + if ($NativeRows.Count -eq 0) { return $detached } $copy = [pscustomobject]@{} - foreach ($p in $RunConfig.PSObject.Properties) { + foreach ($p in $detached.PSObject.Properties) { if ($p.Name -in 'TestSettings', 'TestSettingsHash') { continue } $copy | Add-Member -NotePropertyName $p.Name -NotePropertyValue $p.Value } @@ -687,7 +700,7 @@ function New-MtResultConfig { $entry = [ordered]@{ Id = $row.Id; Title = $row.Title; Severity = $row.Severity } $default = if ($row.ParentId -and $catalog.ContainsKey($row.ParentId)) { $catalog[$row.ParentId].Severity } elseif ($catalog.ContainsKey($row.Id)) { $catalog[$row.Id].Severity } else { $null } if ($default) { $entry.DefaultSeverity = $default } - $user = if ($RunConfig.TestSettingsHash -and $RunConfig.TestSettingsHash.ContainsKey($row.Id)) { $RunConfig.TestSettingsHash[$row.Id] } else { $null } + $user = if ($detached.TestSettingsHash) { $detached.TestSettingsHash.PSObject.Properties[$row.Id].Value } else { $null } if ($user) { foreach ($p in $user.PSObject.Properties) { if ($p.Name -notin 'Id', 'Title', 'Severity') { $entry[$p.Name] = $p.Value } } } diff --git a/powershell/internal/report/ConvertTo-MtRedactedResult.ps1 b/powershell/internal/report/ConvertTo-MtRedactedResult.ps1 new file mode 100644 index 0000000000..62b5de33bc --- /dev/null +++ b/powershell/internal/report/ConvertTo-MtRedactedResult.ps1 @@ -0,0 +1,61 @@ +function ConvertTo-MtRedactedResult { + <# + .SYNOPSIS + Copies results and prepares result Markdown before export. + + .DESCRIPTION + Handles single-tenant and merged results without changing the caller's objects. + The optional alternative covers TestResult only. Other fields retain the existing + best-effort identity replacement behavior. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] [psobject] $MaesterResults, + [hashtable] $ReplacementMap = @{}, + [switch] $KeepUserIdentity + ) + + $copyObject = { + param($Object) + $copy = [ordered]@{} + if ($Object -is [System.Collections.IDictionary]) { + foreach ($key in $Object.Keys) { $copy[$key] = $Object[$key] } + } else { + foreach ($property in $Object.PSObject.Properties) { $copy[$property.Name] = $property.Value } + } + $copy + } + $prepare = { + param($Source) + $copy = & $copyObject $Source + if ($null -ne $copy.Tests) { + $copy.Tests = @(foreach ($sourceTest in $copy.Tests) { + $test = & $copyObject $sourceTest + if ($null -ne $test.ResultDetail) { + $detail = & $copyObject $test.ResultDetail + if ($detail.Contains('TestResultRedacted')) { + # Imported alternatives are optional; unusable values use generic redaction. + if (-not $KeepUserIdentity -and $detail.TestResultRedacted -is [string] -and -not [string]::IsNullOrWhiteSpace($detail.TestResultRedacted)) { + $detail.TestResult = $detail.TestResultRedacted + } + $detail.Remove('TestResultRedacted') + } + $test.ResultDetail = [pscustomobject]$detail + } + [pscustomobject]$test + }) + } + if ($null -ne $copy.Tenants) { + $copy.Tenants = @(foreach ($tenant in $copy.Tenants) { & $prepare $tenant }) + } + [pscustomobject]$copy + } + $prepared = & $prepare $MaesterResults + if (-not $KeepUserIdentity -and $ReplacementMap.Count -gt 0) { + # Preserve the existing generic replacement for fields outside scoped result Markdown. + $depth = if ($prepared.PSObject.Properties['Tenants']) { 7 } else { 5 } + return $prepared | ConvertTo-Json -Depth $depth -WarningAction SilentlyContinue | + ConvertTo-MtRedactedReportContent -ReplacementMap $ReplacementMap -JsonEncoded | ConvertFrom-Json + } + return $prepared +} diff --git a/powershell/public/report/Get-MtHtmlReport.ps1 b/powershell/public/report/Get-MtHtmlReport.ps1 index 67d2ee200c..46c2a7302f 100644 --- a/powershell/public/report/Get-MtHtmlReport.ps1 +++ b/powershell/public/report/Get-MtHtmlReport.ps1 @@ -142,9 +142,7 @@ Write-Warning "RedactUserIdentity: the reports added with Add-MtReportAttachment are left out of the HTML report, because they cannot be redacted." } - Write-Verbose "Generating HTML report." - $json = $reportResults | ConvertTo-Json -Depth $depth -Compress -WarningAction Ignore - # Redact before escaping: escaped & < > would no longer match the replacement values. + $replacements = @{} if ($RedactUserIdentity -ne 'None') { if ($PSBoundParameters.ContainsKey('UserIdentityReplacementMap')) { $replacements = $UserIdentityReplacementMap @@ -153,11 +151,13 @@ $hasInventory = @($MaesterResults) + @($MaesterResults.Tenants) | Where-Object { $_ -and $_.PSObject.Properties.Name -contains 'AffectedObjects' } if (-not $hasInventory) { - Write-Warning "RedactUserIdentity: the results carry no AffectedObjects, so no user identities can be redacted. Generate them with Invoke-Maester -IncludeAffectedObjects." + Write-Warning "RedactUserIdentity: the results carry no AffectedObjects. Only supplied redacted result Markdown and identities in the replacement map can be redacted." } } - $json = ConvertTo-MtRedactedReportContent -Content $json -ReplacementMap $replacements -JsonEncoded } + $reportResults = ConvertTo-MtRedactedResult -MaesterResults $reportResults -ReplacementMap $replacements -KeepUserIdentity:($RedactUserIdentity -eq 'None') + Write-Verbose "Generating HTML report." + $json = $reportResults | ConvertTo-Json -Depth $depth -Compress -WarningAction Ignore # Prevent values from terminating the script element while preserving them when JavaScript parses the JSON. $json = $json.Replace('&', '\u0026').Replace('<', '\u003c').Replace('>', '\u003e') diff --git a/powershell/public/run/Add-MtTestResultDetail.ps1 b/powershell/public/run/Add-MtTestResultDetail.ps1 index 3f4fa78dba..21d32c7f1e 100644 --- a/powershell/public/run/Add-MtTestResultDetail.ps1 +++ b/powershell/public/run/Add-MtTestResultDetail.ps1 @@ -98,7 +98,15 @@ # Severity level of the test result. Leave empty if no Severity is defined yet. [Parameter(Mandatory = $false)] [ValidateSet('Critical', 'High', 'Medium', 'Low', 'Info', '')] - [string] $Severity + [string] $Severity, + + # Complete pseudonymized result Markdown, used when user identity redaction is enabled. + # The static result template is applied, but GraphObjects are never inserted into this alternative. + # Protects result Markdown only, not arbitrary titles, descriptions, skip reasons or errors. + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [ValidateScript({ -not [string]::IsNullOrWhiteSpace($_) })] + [string] $RedactedResult ) # Under the native engine (Maester 3.0) the engine tells us which test is running; under Pester the @@ -156,6 +164,9 @@ if ($metadata) { $mdResult = $metadata.Result + if ($PSBoundParameters.ContainsKey('RedactedResult') -and $mdResult -match '%TestResult%') { + $RedactedResult = $mdResult.Replace('%TestResult%', $RedactedResult) + } if (![string]::IsNullOrEmpty($Result)) { # If a result was provided in the parameter insert it into the markdown content try { @@ -236,6 +247,9 @@ Severity = $Severity Service = $Service } + if ($PSBoundParameters.ContainsKey('RedactedResult')) { + $testInfo.TestResultRedacted = $RedactedResult + } # Only present when the run collects the affected objects, so results of runs that do not opt in are unchanged. if ($__MtSession.IncludeAffectedObjects) { $testInfo.RelatedObjects = $relatedObjects diff --git a/powershell/public/run/Invoke-Maester.ps1 b/powershell/public/run/Invoke-Maester.ps1 index 6fe6e0be97..0c0348190b 100644 --- a/powershell/public/run/Invoke-Maester.ps1 +++ b/powershell/public/run/Invoke-Maester.ps1 @@ -1026,12 +1026,7 @@ # Csv and Excel are produced by Convert-MtResultsToFlatObject, which writes the file # itself, so redaction has to happen on a copy of the results rather than on the output. - $exportResults = $maesterResults - if ($redactNonHtml -and $userIdentityReplacements.Count -gt 0) { - $exportResults = $maesterResults | ConvertTo-Json -Depth 5 -WarningAction SilentlyContinue | - ConvertTo-MtRedactedReportContent -ReplacementMap $userIdentityReplacements -JsonEncoded | - ConvertFrom-Json - } + $exportResults = ConvertTo-MtRedactedResult -MaesterResults $maesterResults -ReplacementMap $userIdentityReplacements -KeepUserIdentity:(-not $redactNonHtml) Set-MtConsolePhase 'Reports' @@ -1048,54 +1043,38 @@ if (![string]::IsNullOrEmpty($out.OutputJsonFile)) { # Attachments keep their name and size: their content is another tool's report, embedded only in the HTML report. - $jsonResults = $maesterResults - if ($maesterResults.PSObject.Properties['Attachments']) { - $jsonResults = $maesterResults | Select-Object -Property * -ExcludeProperty Attachments - $jsonResults | Add-Member -MemberType NoteProperty -Name 'Attachments' -Value @($maesterResults.Attachments | Select-Object -Property * -ExcludeProperty Content) + $jsonResults = $exportResults + if ($exportResults.PSObject.Properties['Attachments']) { + $jsonResults = $exportResults | Select-Object -Property * -ExcludeProperty Attachments + $jsonResults | Add-Member -MemberType NoteProperty -Name 'Attachments' -Value @($exportResults.Attachments | Select-Object -Property * -ExcludeProperty Content) } $output = $jsonResults | ConvertTo-Json -Depth 5 -WarningAction SilentlyContinue - if ($redactNonHtml) { - $output = ConvertTo-MtRedactedReportContent -Content $output -ReplacementMap $userIdentityReplacements -JsonEncoded - } $output | Out-File -FilePath $out.OutputJsonFile -Encoding UTF8 } - if (![string]::IsNullOrEmpty($out.OutputAffectedObjectsJsonFile) -and $maesterResults.AffectedObjects) { + if (![string]::IsNullOrEmpty($out.OutputAffectedObjectsJsonFile) -and $exportResults.AffectedObjects) { Write-MtProgress -Activity 'Creating affected objects' - $output = ConvertTo-Json -InputObject @($maesterResults.AffectedObjects) -Depth 5 -WarningAction SilentlyContinue - if ($redactNonHtml) { - $output = ConvertTo-MtRedactedReportContent -Content $output -ReplacementMap $userIdentityReplacements -JsonEncoded - } + $output = ConvertTo-Json -InputObject @($exportResults.AffectedObjects) -Depth 5 -WarningAction SilentlyContinue $output | Out-File -FilePath $out.OutputAffectedObjectsJsonFile -Encoding UTF8 } - if (![string]::IsNullOrEmpty($out.OutputAffectedObjectsCsvFile) -and $maesterResults.AffectedObjects) { - $output = $maesterResults.AffectedObjects | Select-Object System, AnchorKind, Type, Id, UniqueId, DisplayName, UserPrincipalName, PortalLink, + if (![string]::IsNullOrEmpty($out.OutputAffectedObjectsCsvFile) -and $exportResults.AffectedObjects) { + $output = $exportResults.AffectedObjects | Select-Object System, AnchorKind, Type, Id, UniqueId, DisplayName, UserPrincipalName, PortalLink, @{ Name = 'Tests'; Expression = { $_.Tests -join '; ' } }, @{ Name = 'Sources'; Expression = { $_.Sources -join '; ' } } | ConvertTo-Csv -NoTypeInformation - if ($redactNonHtml) { - # Piped so the replacement regex is built once, not once per row. - $output = @($output | ConvertTo-MtRedactedReportContent -ReplacementMap $userIdentityReplacements) - } $output | Out-File -FilePath $out.OutputAffectedObjectsCsvFile -Encoding UTF8 } if (![string]::IsNullOrEmpty($out.OutputMarkdownFile)) { Write-MtProgress -Activity 'Creating markdown report' - $output = Get-MtMarkdownReport -MaesterResults $maesterResults - if ($redactNonHtml) { - $output = ConvertTo-MtRedactedReportContent -Content $output -ReplacementMap $userIdentityReplacements - } + $output = Get-MtMarkdownReport -MaesterResults $exportResults $output | Out-File -FilePath $out.OutputMarkdownFile -Encoding UTF8 } if (![string]::IsNullOrEmpty($out.OutputMarkdownSummaryFile)) { Write-MtProgress -Activity 'Creating markdown summary report' - $output = Get-MtMarkdownSummaryReport -MaesterResults $maesterResults - if ($redactNonHtml) { - $output = ConvertTo-MtRedactedReportContent -Content $output -ReplacementMap $userIdentityReplacements - } + $output = Get-MtMarkdownSummaryReport -MaesterResults $exportResults $output | Out-File -FilePath $out.OutputMarkdownSummaryFile -Encoding UTF8 } @@ -1111,6 +1090,7 @@ if (![string]::IsNullOrEmpty($out.OutputHtmlFile)) { Write-MtProgress -Activity 'Creating html report' + # Prepare HTML independently so HtmlOnly can still select its alternative. $output = Get-MtHtmlReport -MaesterResults $maesterResults -RedactUserIdentity $RedactUserIdentity -UserIdentityReplacementMap $userIdentityReplacements $output | Out-File -FilePath $out.OutputHtmlFile -Encoding UTF8 diff --git a/powershell/tests/functions/RedactedResult.Tests.ps1 b/powershell/tests/functions/RedactedResult.Tests.ps1 new file mode 100644 index 0000000000..9aa6d0e045 --- /dev/null +++ b/powershell/tests/functions/RedactedResult.Tests.ps1 @@ -0,0 +1,116 @@ +BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force +} + +Describe 'Scoped redacted result Markdown' { + BeforeEach { + InModuleScope Maester { $__MtSession.TestResultDetail = @{} } + Mock Get-MtTestResultTemplate -ModuleName Maester { @{ Description = 'Static guide'; Result = 'Static wrapper: %TestResult%' } } + Mock Get-GraphObjectMarkdown -ModuleName Maester { 'RAW_GRAPH_IDENTITY' } + } + It 'Applies the static template to both variants without putting GraphObjects into the alternative' { + Add-MtTestResultDetail -TestName 'fixture' -Result 'Raw: %TestResult%' -RedactedResult 'Safe: object-test' -GraphObjects @(@{ id = '1' }) -GraphObjectType Users + $detail = InModuleScope Maester { $__MtSession.TestResultDetail.fixture } + $detail.TestResult | Should -Be 'Static wrapper: Raw: RAW_GRAPH_IDENTITY' + $detail.TestResultRedacted | Should -Be 'Static wrapper: Safe: object-test' + } + It 'Preserves the positional binding of existing parameters' { + $command = Get-Command Add-MtTestResultDetail + ($command.ParameterSets[0].Parameters | Where-Object Name -EQ 'GraphObjects').Position | Should -Contain 2 + ($command.ParameterSets[0].Parameters | Where-Object Name -EQ 'Severity').Position | Should -Contain 9 + } + It 'Does not add optional metadata for existing callers' { + Add-MtTestResultDetail -TestName 'fixture' -Result 'Raw' + InModuleScope Maester { $__MtSession.TestResultDetail.fixture.ContainsKey('TestResultRedacted') } | Should -BeFalse + } + It 'Rejects an explicitly supplied blank alternative: