Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 16 additions & 24 deletions powershell/internal/report/ConvertTo-MtMaesterResult.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -710,40 +710,32 @@ function New-MtResultConfig {
)

if ($null -eq $RunConfig) { return $null }

# The result records the config, so the value of a sensitive setting is replaced before it is copied.
# 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
$registry = (Get-MtSettingRegistry).Settings
$globalSettings = if ($RunConfig.PSObject.Properties['GlobalSettings']) { $RunConfig.GlobalSettings } else { $null }
if ($globalSettings -and @($globalSettings.PSObject.Properties | Where-Object { $null -ne $_.Value -and $registry.ContainsKey($_.Name) -and $registry[$_.Name].Sensitive }).Count -gt 0) {
$redacted = [pscustomobject]@{}
foreach ($p in $globalSettings.PSObject.Properties) {
$isSensitive = $null -ne $p.Value -and $registry.ContainsKey($p.Name) -and $registry[$p.Name].Sensitive
$redacted | Add-Member -NotePropertyName $p.Name -NotePropertyValue $(if ($isSensitive) { '[redacted]' } else { $p.Value })
}
$globalSettings = $redacted
}
$withSettings = {
param($skip)
$object = [pscustomobject]@{}
foreach ($p in $RunConfig.PSObject.Properties) {
if ($p.Name -in $skip) { continue }
$object | Add-Member -NotePropertyName $p.Name -NotePropertyValue $(if ($p.Name -eq 'GlobalSettings') { $globalSettings } else { $p.Value })
if ($detached.PSObject.Properties['GlobalSettings'] -and $null -ne $detached.GlobalSettings) {
foreach ($property in $detached.GlobalSettings.PSObject.Properties) {
if ($null -ne $property.Value -and $registry.ContainsKey($property.Name) -and $registry[$property.Name].Sensitive) {
$property.Value = '[redacted]'
}
}
$object
}
if ($NativeRows.Count -eq 0) {
if ([object]::ReferenceEquals($globalSettings, $RunConfig.GlobalSettings)) { return $RunConfig }
return & $withSettings @()
}
if ($NativeRows.Count -eq 0) { return $detached }

$copy = & $withSettings @('TestSettings', 'TestSettingsHash')
$copy = [pscustomobject]@{}
foreach ($p in $detached.PSObject.Properties) {
if ($p.Name -in 'TestSettings', 'TestSettingsHash') { continue }
$copy | Add-Member -NotePropertyName $p.Name -NotePropertyValue $p.Value
}
$catalog = @{}
foreach ($t in @(Get-MtTestCatalog)) { if ($t.Id) { $catalog[$t.Id] = $t } }
$settings = foreach ($row in $Rows) {
$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 }
$userProperty = if ($detached.TestSettingsHash) { $detached.TestSettingsHash.PSObject.Properties[$row.Id] } else { $null }
$user = if ($null -ne $userProperty) { $userProperty.Value } else { $null }
if ($user) {
foreach ($p in $user.PSObject.Properties) { if ($p.Name -notin 'Id', 'Title', 'Severity') { $entry[$p.Name] = $p.Value } }
}
Expand Down
62 changes: 62 additions & 0 deletions powershell/internal/report/ConvertTo-MtRedactedResult.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
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. Missing, blank or non-string alternatives also fall
back to generic replacement, which can redact only identities in ReplacementMap.
#>
[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
}
11 changes: 9 additions & 2 deletions powershell/internal/report/Get-MtMarkdownReport.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,15 @@
# make sure we do not execute the code in the script block!
$cleanedScriptBlock = $test.ScriptBlock.ToString() -replace '%\w+%', '' -replace '\$_', '€_' # or show me how I can make it not execute the $_ thing
[void]$details.Append("#### Overview`n`n``````ps1`n$cleanedScriptBlock`n```````n`n")
if (![string]::IsNullOrEmpty($test.ErrorRecord)) {
[void]$details.Append("#### Reason for failure`n`n$($test.ErrorRecord)`n`n")
# Redacted exports carry deserialized error records, whose string conversion loses the message.
# Read the prepared records so diagnostics remain redacted and caller objects stay unchanged.
$errorMessages = @(foreach ($record in $test.ErrorRecord) {
if ($record.ErrorDetails.Message) { $record.ErrorDetails.Message }
elseif ($record.Exception.Message) { $record.Exception.Message }
elseif ($record -is [string] -and -not [string]::IsNullOrWhiteSpace($record)) { $record }
})
if ($errorMessages.Count -gt 0) {
[void]$details.Append("#### Reason for failure`n`n$($errorMessages -join "`n`n")`n`n")
}
}

Expand Down
7 changes: 2 additions & 5 deletions powershell/public/report/Get-MtHtmlReport.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@
$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. Generate affected objects with Invoke-Maester -IncludeAffectedObjects."
}
}
}
Expand Down Expand Up @@ -207,12 +207,9 @@
Write-Warning "RedactUserIdentity: the HTML reports added with Add-MtReportAttachment are left out of the HTML report, because they cannot be redacted."
}

$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
# Redact the JSON text before it is compressed.
if ($RedactUserIdentity -ne 'None') {
$json = ConvertTo-MtRedactedReportContent -Content $json -ReplacementMap $replacements -JsonEncoded
}

# The results are written gzip-compressed and Base64-encoded, as attachments are: the guides and
# results are text that compresses to about a fifth. Base64 text cannot end the script element.
Expand Down
18 changes: 17 additions & 1 deletion powershell/public/run/Add-MtTestResultDetail.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,17 @@
# 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.
# When Description is omitted, the static result template is applied to both result variants.
# With an explicit Description, supply complete content for both Result and RedactedResult.
# 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
Expand Down Expand Up @@ -156,6 +166,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 {
Expand Down Expand Up @@ -236,6 +249,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
Expand Down
48 changes: 16 additions & 32 deletions powershell/public/run/Invoke-Maester.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -1081,12 +1081,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'

Expand All @@ -1103,55 +1098,43 @@

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 '; ' } },
@{ Name = 'Facts'; Expression = { @($_.Facts | Where-Object { $_ } | ForEach-Object { "$($_.Name): $($_.Value)" }) -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
}
# Redaction can JSON-round-trip the version object. Normalize only the Markdown copy,
# preserving the result schema in JSON and the original object returned by PassThru.
$markdownResults = $exportResults | Select-Object -Property *
$markdownResults.CurrentVersion = [string]$maesterResults.CurrentVersion
$output = Get-MtMarkdownReport -MaesterResults $markdownResults
$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
}

Expand All @@ -1167,6 +1150,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

Expand Down
Loading
Loading