diff --git a/powershell/assets/MaesterSettings.psd1 b/powershell/assets/MaesterSettings.psd1 index c5aecd9439..93779947fd 100644 --- a/powershell/assets/MaesterSettings.psd1 +++ b/powershell/assets/MaesterSettings.psd1 @@ -37,6 +37,7 @@ AzureDevOpsOrganization = @{ Type = 'string'; Role = 'Connection'; Default = ''; Sensitive = $false; Description = 'Azure DevOps organization that Connect-Maester -Service AzureDevOps connects to.' } GitHubOrganization = @{ Type = 'string'; Role = 'Connection'; Default = ''; Sensitive = $false; Description = 'GitHub organization that the GitHub checks read.' } GitHubApiBaseUri = @{ Type = 'string'; Role = 'Connection'; Default = 'https://api.github.com'; Sensitive = $false; Description = 'Base URI of the GitHub REST API.' } + GitHubDeletionPolicy = @{ Type = 'object'; Default = @{}; Sensitive = $true; Description = 'Host and organization-bound approved owner and repository administrator IDs for GitHub deletion assessments.' } GitHubApiVersion = @{ Type = 'string'; Role = 'Connection'; Default = '2022-11-28'; Sensitive = $false; Description = 'GitHub REST API version.' } } } diff --git a/powershell/internal/checks/cis/github/Get-MtCisGitHubDeletionPolicyGap.ps1 b/powershell/internal/checks/cis/github/Get-MtCisGitHubDeletionPolicyGap.ps1 new file mode 100644 index 0000000000..698f69ca1f --- /dev/null +++ b/powershell/internal/checks/cis/github/Get-MtCisGitHubDeletionPolicyGap.ps1 @@ -0,0 +1,55 @@ +function Get-MtCisGitHubDeletionPolicyGap { + <# + .SYNOPSIS + Internal: Checks for restrictive repository policies before failing an administrator baseline. + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory)] [string] $Organization, + [Parameter(Mandatory)] [string] $Repository, + [Parameter(Mandatory)] [string] $RepositoryId + ) + $query = @' +query DeletionPolicies($org:String!,$repo:String!,$after:String){ + repository(owner:$org,name:$repo){databaseId rulesets(first:100,after:$after,includeParents:true,targets:[REPOSITORY]){ + totalCount pageInfo{hasNextPage endCursor} nodes{ + id target enforcement + } + }} +} +'@ + $cursor = $null + $seenCursors = [System.Collections.Generic.HashSet[string]]::new() + $count = 0 + $seenPolicies = [System.Collections.Generic.HashSet[string]]::new() + $expected = $null + for ($page = 0; $page -lt 100; $page++) { + try { + $response = Invoke-MtGitHubGraphQLRequest -Query $query -OperationName DeletionPolicies -Variables @{ org = $Organization; repo = $Repository; after = $cursor } + } catch { + if ($_.Exception.Data['GitHubRateLimit']) { throw } + if ((Get-MtGitHubErrorStatusCode -ErrorRecord $_) -in 403, 404) { return 'Applicable repository-policy evidence is not visible; a restrictive alternative cannot be ruled out.' } + throw + } + $connection = $response.Data.repository.rulesets + $databaseId = $response.Data.repository.databaseId + if ($response.Errors.Count -gt 0 -or ($databaseId -isnot [int] -and $databaseId -isnot [long] -and $databaseId -isnot [bigint]) -or $databaseId -le 0 -or [string]$databaseId -cne $RepositoryId -or $null -eq $connection -or $connection.nodes -isnot [array] -or $connection.pageInfo.hasNextPage -isnot [bool] -or ($connection.totalCount -isnot [int] -and $connection.totalCount -isnot [long]) -or $connection.totalCount -lt 0) { return 'Applicable repository-policy evidence is unavailable or incomplete; a restrictive alternative cannot be ruled out.' } + if ($null -eq $expected) { $expected = $connection.totalCount } + if ($expected -ne $connection.totalCount) { return 'Applicable repository-policy population changed during collection.' } + foreach ($policy in $connection.nodes) { + if ($policy.id -isnot [string] -or [string]::IsNullOrWhiteSpace($policy.id) -or -not $seenPolicies.Add($policy.id) -or $policy.target -cne 'REPOSITORY') { return 'Applicable repository-policy identity or target is unusable.' } + if ($policy.enforcement -cnotin 'ACTIVE', 'DISABLED', 'EVALUATE') { return 'Applicable repository-policy enforcement is unavailable or unknown.' } + if ($policy.enforcement -cne 'ACTIVE') { continue } + return 'An active repository-target policy may restrict deletion; its effective restrictions, bypass membership and stronger-policy equivalence need review.' + } + $count += $connection.nodes.Count + if (-not $connection.pageInfo.hasNextPage) { + if ($count -ne $expected) { return 'Applicable repository-policy total does not match collected items.' } + return $null + } + $cursor = $connection.pageInfo.endCursor + if ($cursor -isnot [string] -or [string]::IsNullOrWhiteSpace($cursor) -or -not $seenCursors.Add($cursor)) { return 'Applicable repository-policy pagination cursor is unusable.' } + } + return 'Applicable repository-policy pagination reached the page cap.' +} diff --git a/powershell/internal/checks/cis/github/Get-MtCisGitHubDeletionResult.ps1 b/powershell/internal/checks/cis/github/Get-MtCisGitHubDeletionResult.ps1 new file mode 100644 index 0000000000..dc4fc917fb --- /dev/null +++ b/powershell/internal/checks/cis/github/Get-MtCisGitHubDeletionResult.ps1 @@ -0,0 +1,52 @@ +function Get-MtCisGitHubDeletionResult { + <# + .SYNOPSIS + Internal: Renders raw or pseudonymized deletion results from the same evidence. + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory)] [System.Collections.IDictionary] $Evidence, + [switch] $RedactUserIdentity + ) + + $userId = { + param($Id) + if ($RedactUserIdentity) { + # User database IDs are host-scoped. Normalize the API authority, including a + # non-default port, without adding numeric IDs to the global replacement map. + $authority = ([uri]$Evidence.ApiAuthority).GetLeftPart([UriPartial]::Authority).ToLowerInvariant() + Get-MtAffectedObjectUniqueId -System 'GitHub' -Type 'User' -Id "$authority/users/$Id" + } else { [string]$Id } + } + $result = $Evidence.Message + "`n`nOrganization setting ``$($Evidence.Field)``: ``$($Evidence.Setting)``.`n`n" + if ($Evidence.OwnerBranch) { + $rows = [System.Collections.Generic.List[string]]::new() + $unapproved = 0 + foreach ($owner in $Evidence.Owners) { + $id = & $userId $owner.id + $login = if ($RedactUserIdentity) { $id } elseif ($owner.login -is [string] -and -not [string]::IsNullOrWhiteSpace($owner.login)) { Get-MtSafeMarkdown $owner.login } else { 'Unavailable' } + $approval = if (-not $Evidence.ApprovalsConfigured) { 'Not configured' } elseif ([string]$owner.id -cin $Evidence.ApprovedOwnerIds) { 'Approved' } else { 'Not approved' } + if ($approval -eq 'Not approved') { $unapproved++ } + $rows.Add("| $login | $id | $approval |") + } + $coverage = if ($Evidence.OwnerComplete) { 'Complete' } else { 'Incomplete / partial; total owner count unknown; observed count is a lower bound' } + $unapprovedCount = if ($Evidence.ApprovalsConfigured) { [string]$unapproved } else { 'Not configured' } + $result += "Organization ID: ``$($Evidence.OrganizationId)``.`n`n| Observed owners | Maximum | Unapproved owners | Evidence |`n| --- | --- | --- | --- |`n| $($rows.Count) | $($Evidence.MaximumOrganizationOwners) | $unapprovedCount | $coverage |`n`n| Owner login | User ID | Approval |`n| --- | --- | --- |`n" + ($rows -join "`n") + if ($rows.Count -eq 0) { $result += "`nNo validated owner rows were available. This does not establish that the organization has no owners." } + $result += "`n`nThe maximum is a Maester policy choice (default 3, configurable as a positive integer); CIS does not define a numeric value for 'few'. Unassigned approval entries do not affect the live count." + } else { + $rows = foreach ($repository in $Evidence.Repositories) { + $ids = @($repository.UnapprovedIds | ForEach-Object { & $userId $_ }) -join ', ' + $notAssessed = $repository.Assessment -eq 'Not assessed' + $unapprovedCount = if (-not $repository.ApprovalsConfigured) { 'Not configured' } elseif ($notAssessed) { 'Not assessed' } else { [string]@($repository.UnapprovedIds).Count } + $administratorCount = if ($notAssessed) { 'Not assessed' } else { [string]$repository.AdministratorCount } + $coverage = if ($notAssessed) { 'Not collected' } elseif ($repository.Complete) { 'Complete' } else { 'Incomplete / partial; observed count is a lower bound' } + "| $(Get-MtSafeMarkdown $repository.Name) | $administratorCount | $unapprovedCount | $ids | $($repository.Assessment) | $coverage |" + } + $result += "| Repository | Effective administrators | Unapproved | Unapproved observed user IDs | Assessment | Evidence |`n| --- | --- | --- | --- | --- | --- |`n" + ($rows -join "`n") + $result += "`n`nEffective administrator permissions include inherited grants. This assessment uses the configured approvals; it does not independently determine a person's trust or qualifications. No issue was deleted or sampled." + } + if ($Evidence.Gaps.Count) { $result += "`n`n" + ($Evidence.Gaps -join "`n`n") } + return $result +} diff --git a/powershell/internal/checks/cis/github/Get-MtCisGitHubDeletionRoleGap.ps1 b/powershell/internal/checks/cis/github/Get-MtCisGitHubDeletionRoleGap.ps1 new file mode 100644 index 0000000000..a5dae26cee --- /dev/null +++ b/powershell/internal/checks/cis/github/Get-MtCisGitHubDeletionRoleGap.ps1 @@ -0,0 +1,37 @@ +function Get-MtCisGitHubDeletionRoleGap { + <# + .SYNOPSIS + Internal: Qualifies whether custom role definitions extend issue deletion beyond administrators. + #> + [CmdletBinding()] + [OutputType([string])] + param([Parameter(Mandatory)] [string] $Organization) + + $encoded = [uri]::EscapeDataString($Organization) + foreach ($catalog in @(@{ Path = 'custom-repository-roles'; Key = 'custom_roles' }, @{ Path = 'organization-roles'; Key = 'roles' })) { + try { + $evidence = Invoke-MtGitHubRequest -RelativeUri "/orgs/$encoded/$($catalog.Path)" -IncludeMetadata -ApiVersion '2026-03-10' + } catch { + if ($_.Exception.Data['GitHubRateLimit']) { throw } + if ((Get-MtGitHubErrorStatusCode -ErrorRecord $_) -in 403, 404) { return 'Issue-deletion custom-role catalog is not visible to the connected account.' } + throw + } + $data = $evidence.Data + $roles = $data.($catalog.Key) + if (-not $evidence.CollectionIntegrityValid -or $evidence.ContentKind -ne 'Object' -or $roles -isnot [array] -or ($data.total_count -isnot [int] -and $data.total_count -isnot [long]) -or $data.total_count -ne $roles.Count) { + return 'Issue-deletion custom-role catalog is incomplete or has an unexpected API shape.' + } + $seen = [System.Collections.Generic.HashSet[string]]::new() + foreach ($role in $roles) { + if ($role -isnot [pscustomobject] -or ($role.id -isnot [int] -and $role.id -isnot [long] -and $role.id -isnot [bigint]) -or $role.id -le 0 -or -not $seen.Add([string]$role.id) -or $role.permissions -isnot [array] -or @($role.permissions | Where-Object { $_ -isnot [string] -or [string]::IsNullOrWhiteSpace($_) }).Count) { return 'Issue-deletion custom-role permissions or identities are unavailable or malformed.' } + if ($catalog.Key -eq 'custom_roles') { + if ($role.base_role -isnot [string] -or $role.base_role -cnotin 'read', 'triage', 'write', 'maintain') { return 'Issue-deletion custom repository role has an unavailable or unknown base role.' } + } elseif ($null -ne $role.base_role -and ($role.base_role -isnot [string] -or $role.base_role -cnotin 'none', 'read', 'triage', 'write', 'maintain', 'admin')) { + return 'Issue-deletion organization role has an unknown base role.' + } + # Additional issue-deletion grants require assignment evidence beyond the administrator population. + if (@($role.permissions | Where-Object { $_ -match '(?i)(delete.*issue|issue.*delete)' }).Count) { return 'A custom role can grant issue deletion; its effective assignments and policy restrictions need review.' } + } + } + return $null +} diff --git a/powershell/internal/checks/cis/github/Resolve-MtGitHubDeletionPolicy.ps1 b/powershell/internal/checks/cis/github/Resolve-MtGitHubDeletionPolicy.ps1 new file mode 100644 index 0000000000..977b3b2fd3 --- /dev/null +++ b/powershell/internal/checks/cis/github/Resolve-MtGitHubDeletionPolicy.ps1 @@ -0,0 +1,45 @@ +function Resolve-MtGitHubDeletionPolicy { + <# + .SYNOPSIS + Internal: Validates the assessor's GitHub deletion approval configuration and target binding. + #> + [CmdletBinding()] + param([Parameter(Mandatory)] [object] $Organization) + + $policy = Get-MtSetting -Name GitHubDeletionPolicy -Verbose:$false + if ($null -eq $policy -or ($policy -is [System.Collections.IDictionary] -and $policy.Count -eq 0) -or ($policy -is [pscustomobject] -and @($policy.PSObject.Properties).Count -eq 0)) { return $null } + if ($policy -isnot [pscustomobject]) { throw 'GitHubDeletionPolicy must be a JSON object.' } + $allowed = 'ApiBaseUri', 'OrganizationId', 'ApprovedOwnerIds', 'CompleteRepositoryInventory', 'Repositories' + foreach ($property in $policy.PSObject.Properties.Name) { + if ($property -notin $allowed) { throw 'GitHubDeletionPolicy contains an unknown property.' } + } + $base = $__MtSession.GitHubConnection.ApiBaseUri.TrimEnd('/') + if ($policy.ApiBaseUri -isnot [string] -or $policy.ApiBaseUri.TrimEnd('/') -cne $base) { throw 'GitHubDeletionPolicy.ApiBaseUri must match the connected API base URI.' } + $idPattern = '^[1-9][0-9]*$' + if ($policy.OrganizationId -isnot [string] -or $policy.OrganizationId -cnotmatch $idPattern) { throw 'GitHubDeletionPolicy.OrganizationId must be a positive decimal ID string.' } + if (($Organization.id -isnot [int] -and $Organization.id -isnot [long] -and $Organization.id -isnot [bigint]) -or $Organization.id -le 0) { throw 'GitHub organization identity is unavailable or unusable.' } + if ($policy.OrganizationId -cne [string]$Organization.id) { throw 'GitHubDeletionPolicy.OrganizationId does not match the connected organization.' } + foreach ($name in 'ApprovedOwnerIds') { + if (-not $policy.PSObject.Properties[$name]) { continue } + if ($policy.$name -isnot [array]) { throw "GitHubDeletionPolicy.$name must be an array of positive decimal ID strings." } + $seen = [System.Collections.Generic.HashSet[string]]::new() + foreach ($id in $policy.$name) { + if ($id -isnot [string] -or $id -cnotmatch $idPattern -or -not $seen.Add($id)) { throw "GitHubDeletionPolicy.$name contains an invalid or duplicate ID." } + } + } + if ($policy.PSObject.Properties['CompleteRepositoryInventory'] -and $policy.CompleteRepositoryInventory -isnot [bool]) { throw 'GitHubDeletionPolicy.CompleteRepositoryInventory must be Boolean.' } + if ($policy.PSObject.Properties['Repositories']) { + if ($policy.Repositories -isnot [array]) { throw 'GitHubDeletionPolicy.Repositories must be an array.' } + $seenRepositories = [System.Collections.Generic.HashSet[string]]::new() + foreach ($repository in $policy.Repositories) { + if ($repository -isnot [pscustomobject] -or $repository.Id -isnot [string] -or $repository.Id -cnotmatch $idPattern -or -not $seenRepositories.Add($repository.Id)) { throw 'GitHubDeletionPolicy.Repositories contains an invalid or duplicate repository ID.' } + if (@($repository.PSObject.Properties.Name | Where-Object { $_ -notin 'Id', 'ApprovedAdministratorIds' }).Count) { throw 'A GitHubDeletionPolicy repository contains an unknown property.' } + if ($repository.ApprovedAdministratorIds -isnot [array]) { throw 'Each GitHubDeletionPolicy repository needs ApprovedAdministratorIds as an array.' } + $seenUsers = [System.Collections.Generic.HashSet[string]]::new() + foreach ($id in $repository.ApprovedAdministratorIds) { + if ($id -isnot [string] -or $id -cnotmatch $idPattern -or -not $seenUsers.Add($id)) { throw 'ApprovedAdministratorIds contains an invalid or duplicate ID.' } + } + } + } + return $policy +} diff --git a/powershell/internal/checks/cis/github/Test-MtCisGitHubDeletion.ps1 b/powershell/internal/checks/cis/github/Test-MtCisGitHubDeletion.ps1 new file mode 100644 index 0000000000..8d49a8d7c0 --- /dev/null +++ b/powershell/internal/checks/cis/github/Test-MtCisGitHubDeletion.ps1 @@ -0,0 +1,174 @@ +function Test-MtCisGitHubDeletion { + <# + .SYNOPSIS + Internal: Assesses the configured owner or repository-administrator deletion branch. + #> + [CmdletBinding()] + [OutputType([bool])] + param( + [Parameter(Mandatory)] [ValidateSet('Repository', 'Issue')] [string] $Kind, + [ValidateRange(1, 2147483647)] [int] $MaximumOrganizationOwners = 3 + ) + if (-not $__MtSession.GitHubConnection -or $__MtSession.GitHubConnection.Connected -ne $true) { throw 'Not connected to GitHub. Call Connect-MtGitHub first.' } + $organization = $__MtSession.GitHubConnection.Organization + $encoded = [uri]::EscapeDataString($organization) + $evidence = Invoke-MtGitHubRequest -RelativeUri "/orgs/$encoded" -IncludeMetadata -ApiVersion '2026-03-10' + $org = $evidence.Data + $field = if ($Kind -eq 'Repository') { 'members_can_delete_repositories' } else { 'members_can_delete_issues' } + if (-not $evidence.CollectionIntegrityValid -or $evidence.ContentKind -ne 'Object' -or $org -isnot [pscustomobject] -or $org.$field -isnot [bool]) { + Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Indeterminate: required GitHub organization field '$field' is unavailable, incomplete or not Boolean." + return $null + } + if (($org.id -isnot [int] -and $org.id -isnot [long] -and $org.id -isnot [bigint]) -or $org.id -le 0) { + Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason 'Indeterminate: required GitHub organization identity is unavailable or unusable.' + return $null + } + $policy = Resolve-MtGitHubDeletionPolicy -Organization $org + $report = @{ + Kind = $Kind; Field = $field; Setting = $org.$field; OrganizationId = $org.id + ApiAuthority = ([uri]$__MtSession.GitHubConnection.ApiBaseUri).GetLeftPart([UriPartial]::Authority).ToLowerInvariant() + MaximumOrganizationOwners = $MaximumOrganizationOwners; OwnerBranch = -not $org.$field + Owners = @(); Repositories = @(); Gaps = @(); Message = '' + } + if (-not $org.$field) { + $owners = Get-MtGitHubIdentityCollection -RelativeUri "/orgs/$encoded/members?role=admin" -Label 'Organization owner' + $approvalsConfigured = $null -ne $policy -and $null -ne $policy.PSObject.Properties['ApprovedOwnerIds'] -and $policy.ApprovedOwnerIds.Count -gt 0 + $report.Owners = $owners.Items + $report.ApprovalsConfigured = $approvalsConfigured + $report.ApprovedOwnerIds = $policy.ApprovedOwnerIds + $report.OwnerComplete = $owners.Complete -and $owners.Items.Count -gt 0 + if (-not $report.OwnerComplete) { + $report.Gaps += if (-not $owners.Complete) { $owners.Gap } else { 'The organization-owner collection is unexpectedly empty.' } + } + if (-not $approvalsConfigured) { + $report.Gaps += 'Configure a nonempty ApprovedOwnerIds roster in GlobalSettings.GitHubDeletionPolicy. Observed membership does not approve a user as trusted and qualified.' + } + if ($owners.ExecutionError) { + $report.Message = 'The owner collection request failed. Retained rows are partial evidence; this assessment remains an execution error.' + Add-MtTestResultDetail -Result (Get-MtCisGitHubDeletionResult -Evidence $report) -RedactedResult (Get-MtCisGitHubDeletionResult -Evidence $report -RedactUserIdentity) + throw $owners.ExecutionError + } + $unapproved = @($owners.Items | Where-Object { $approvalsConfigured -and [string]$_.id -cnotin $policy.ApprovedOwnerIds }) + # Counts from partial collections are lower bounds: enough to disprove the maximum, + # but never enough to establish compliance or infer that an unseen user is approved. + if ($approvalsConfigured -and ($owners.Items.Count -gt $MaximumOrganizationOwners -or $unapproved.Count -gt 0)) { + $report.Message = 'Review organization owners: the validated population exceeds the configured Maester maximum or includes an owner outside the configured approval roster. Remove unnecessary assignments or explicitly approve trusted and qualified owners within the maximum. Any additional evidence gaps do not negate this observed violation.' + Add-MtTestResultDetail -Result (Get-MtCisGitHubDeletionResult -Evidence $report) -RedactedResult (Get-MtCisGitHubDeletionResult -Evidence $report -RedactUserIdentity) + return $false + } + if (-not $report.OwnerComplete) { + $report.Message = 'Indeterminate: the complete organization-owner population could not be established.' + Add-MtTestResultDetail -Result (Get-MtCisGitHubDeletionResult -Evidence $report) -RedactedResult (Get-MtCisGitHubDeletionResult -Evidence $report -RedactUserIdentity) -SkippedBecause Custom -SkippedCustomReason ('Indeterminate: ' + ($report.Gaps -join ' ')) + return $null + } + if (-not $approvalsConfigured) { + $report.Message = 'Organization owners have been collected, but approvals have not been configured. Configure approvals before assessing owner counts and access.' + Add-MtTestResultDetail -Investigate -Result (Get-MtCisGitHubDeletionResult -Evidence $report) -RedactedResult (Get-MtCisGitHubDeletionResult -Evidence $report -RedactUserIdentity) + return $null + } + $report.Message = 'Well done. The complete organization-owner population is within the configured maximum and every owner is approved as trusted and qualified.' + Add-MtTestResultDetail -Result (Get-MtCisGitHubDeletionResult -Evidence $report) -RedactedResult (Get-MtCisGitHubDeletionResult -Evidence $report -RedactUserIdentity) + return $true + } + $rows = [System.Collections.Generic.List[object]]::new() + $violations = [System.Collections.Generic.List[object]]::new() + $collectionGaps = [System.Collections.Generic.List[string]]::new() + $scopeGaps = [System.Collections.Generic.List[string]]::new() + $policyGaps = [System.Collections.Generic.List[string]]::new() + $declared = @{} + foreach ($entry in $policy.Repositories) { $declared[$entry.Id] = $entry } + if ($null -eq $policy) { + $scopeGaps.Add('Configure GlobalSettings.GitHubDeletionPolicy with a complete repository inventory and users approved as trusted and qualified. No approval population was supplied.') + } else { + if ($policy.CompleteRepositoryInventory -ne $true) { $scopeGaps.Add('Declare CompleteRepositoryInventory to confirm that the assessor has accounted for every organization repository.') } + if (-not $policy.PSObject.Properties['Repositories']) { $scopeGaps.Add('Declare Repositories and approve administrators for every organization repository.') } + } + $confirmedViolations = 0 + try { + $inventory = Get-MtGitHubRepositoryInventory -RetainPartialOnError + foreach ($issue in $inventory.Issues) { $collectionGaps.Add("Organization repository inventory: $issue") } + if ($inventory.Repositories.Count -eq 0 -and $inventory.Issues.Count -eq 0) { + $scopeGaps.Add('No repositories were visible. This does not establish a complete organization inventory or a not-applicable result.') + } + $liveIds = @($inventory.Repositories | ForEach-Object { [string]$_.id }) + if ($null -ne $policy -and $policy.PSObject.Properties['Repositories'] -and (@($liveIds | Where-Object { -not $declared.ContainsKey($_) }).Count -or @($declared.Keys | Where-Object { $_ -cnotin $liveIds }).Count)) { + $scopeGaps.Add('The declared repository IDs and the observed inventory do not match. Reconcile missing, inaccessible, newly created or removed repositories; no exclusions are supported.') + } + foreach ($repository in $inventory.Repositories) { + $approvalsConfigured = $declared.ContainsKey([string]$repository.id) -and $declared[[string]$repository.id].ApprovedAdministratorIds.Count -gt 0 + if (-not $approvalsConfigured -or $inventory.ExecutionError) { + if (-not $approvalsConfigured) { $scopeGaps.Add("$(Get-MtSafeMarkdown $repository.name): Configure a nonempty ApprovedAdministratorIds roster before assessing administrator access.") } + # An inventory execution error stops all follow-on requests, even for configured + # repositories. Retain their names without inventing administrator observations. + $rows.Add([pscustomobject]@{ + Name = $repository.name; AdministratorCount = $null; UnapprovedIds = @() + Complete = $null; ApprovalsConfigured = $approvalsConfigured; Assessment = 'Not assessed' + }) + continue + } + $name = [uri]::EscapeDataString($repository.name) + $collaborators = Get-MtGitHubIdentityCollection -RelativeUri "/repos/$encoded/$name/collaborators?affiliation=all" -Label 'Repository collaborator' + $complete = $collaborators.Complete -and $collaborators.Items.Count -gt 0 -and @($collaborators.Items | Where-Object { $_.permissions.admin -isnot [bool] }).Count -eq 0 + if (-not $complete) { + $reason = if (-not $collaborators.Complete) { $collaborators.Gap } elseif ($collaborators.Items.Count -eq 0) { 'The effective collaborator collection is unexpectedly empty; organization-owner access should be represented.' } else { 'Required collaborator permissions.admin is missing or not Boolean.' } + $collectionGaps.Add("$(Get-MtSafeMarkdown $repository.name): $reason") + } + $administrators = @($collaborators.Items | Where-Object { $_.permissions.admin -is [bool] -and $_.permissions.admin -eq $true -and [string]$_.id -cnotin $collaborators.ConflictingAdministratorIds }) + $unapproved = @($administrators | Where-Object { $approvalsConfigured -and [string]$_.id -cnotin $declared[[string]$repository.id].ApprovedAdministratorIds }) + $violation = $administrators.Count -gt 2 -or $unapproved.Count -gt 0 -or ($complete -and $administrators.Count -lt 2) + $rows.Add([pscustomobject]@{ + Name = $repository.name; AdministratorCount = $administrators.Count + UnapprovedIds = @($unapproved | ForEach-Object { [string]$_.id }); Complete = $complete; ApprovalsConfigured = $approvalsConfigured + Assessment = if ($violation) { 'Needs review' } elseif (-not $complete) { 'Indeterminate' } elseif (-not $approvalsConfigured) { 'Approvals not configured' } else { 'Meets baseline' } + }) + if ($violation) { $violations.Add($repository) } + if ($collaborators.ExecutionError) { throw $collaborators.ExecutionError } + } + if ($inventory.ExecutionError) { throw $inventory.ExecutionError } + if ($Kind -eq 'Repository') { + foreach ($repository in $violations) { + $gap = Get-MtCisGitHubDeletionPolicyGap -Organization $organization -Repository $repository.name -RepositoryId ([string]$repository.id) + if ($gap) { $policyGaps.Add("$(Get-MtSafeMarkdown $repository.name): $gap") } else { $confirmedViolations++ } + } + } else { + $confirmedViolations = $violations.Count + # Additive issue permissions cannot remove an already validated violation. Do not + # traverse optional catalogs to look past unusable required population evidence. + if ($violations.Count -eq 0 -and $collectionGaps.Count -eq 0 -and $scopeGaps.Count -eq 0) { + $roleGap = Get-MtCisGitHubDeletionRoleGap -Organization $organization + if ($roleGap) { $policyGaps.Add($roleGap) } + } + } + } catch { + $report.Repositories = $rows.ToArray() + $report.Gaps = @($collectionGaps.ToArray()) + @($scopeGaps.ToArray()) + @($policyGaps.ToArray()) + $report.Message = 'A GitHub evidence request or parsing operation failed. Collected repository observations are retained, but this assessment remains an execution error.' + Add-MtTestResultDetail -Result (Get-MtCisGitHubDeletionResult -Evidence $report) -RedactedResult (Get-MtCisGitHubDeletionResult -Evidence $report -RedactUserIdentity) + # Do not expose an original exception's partial response, raw user IDs or arbitrary + # server text through ErrorRecord, ReasonDetail or alternative report metadata. + $message = if ($_.Exception.Data['GitHubRateLimit'] -or $_.Exception.Message -in 'GitHub rate limit stopped identity collection.', 'GitHub rate limit stopped repository inventory collection.') { 'GitHub rate limit stopped deletion assessment.' } else { 'GitHub deletion evidence request or JSON parsing failed.' } + throw [System.InvalidOperationException]::new($message) + } + $report.Repositories = $rows.ToArray() + $report.Gaps = @($collectionGaps.ToArray()) + @($scopeGaps.ToArray()) + @($policyGaps.ToArray()) + if ($confirmedViolations -gt 0) { + $report.Message = 'Review repository administrator access: at least one repository has a confirmed count or approval violation. Require exactly two effective administrators, both approved as trusted and qualified. Additional evidence gaps do not negate the confirmed violation.' + Add-MtTestResultDetail -Result (Get-MtCisGitHubDeletionResult -Evidence $report) -RedactedResult (Get-MtCisGitHubDeletionResult -Evidence $report -RedactUserIdentity) + return $false + } + # Without a confirmed violation, incomplete required populations retain Skipped + # even when optional policy uncertainty also remains. All gaps stay in the report. + if ($collectionGaps.Count -gt 0) { + $report.Message = 'Indeterminate: a usable complete repository inventory or effective administrator population could not be established.' + Add-MtTestResultDetail -Result (Get-MtCisGitHubDeletionResult -Evidence $report) -RedactedResult (Get-MtCisGitHubDeletionResult -Evidence $report -RedactUserIdentity) -SkippedBecause Custom -SkippedCustomReason ('Indeterminate: ' + ($collectionGaps -join ' ')) + return $null + } + if ($scopeGaps.Count -gt 0 -or $policyGaps.Count -gt 0) { + $report.Message = 'Investigate the outstanding repository inventory, approval or permission-policy gaps before determining compliance.' + Add-MtTestResultDetail -Investigate -Result (Get-MtCisGitHubDeletionResult -Evidence $report) -RedactedResult (Get-MtCisGitHubDeletionResult -Evidence $report -RedactUserIdentity) + return $null + } + $report.Message = 'Well done. Every repository in the declared complete organization inventory has exactly two effective administrators, both approved as trusted and qualified.' + Add-MtTestResultDetail -Result (Get-MtCisGitHubDeletionResult -Evidence $report) -RedactedResult (Get-MtCisGitHubDeletionResult -Evidence $report -RedactUserIdentity) + return $true +} diff --git a/powershell/internal/report/ConvertTo-MtMaesterResult.ps1 b/powershell/internal/report/ConvertTo-MtMaesterResult.ps1 index f85dafd89e..0d4e570b08 100644 --- a/powershell/internal/report/ConvertTo-MtMaesterResult.ps1 +++ b/powershell/internal/report/ConvertTo-MtMaesterResult.ps1 @@ -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 } } } diff --git a/powershell/internal/report/ConvertTo-MtRedactedResult.ps1 b/powershell/internal/report/ConvertTo-MtRedactedResult.ps1 new file mode 100644 index 0000000000..37466e1ae1 --- /dev/null +++ b/powershell/internal/report/ConvertTo-MtRedactedResult.ps1 @@ -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 +} diff --git a/powershell/internal/report/Get-MtMarkdownReport.ps1 b/powershell/internal/report/Get-MtMarkdownReport.ps1 index 2930e6f90e..b2e963bfcb 100644 --- a/powershell/internal/report/Get-MtMarkdownReport.ps1 +++ b/powershell/internal/report/Get-MtMarkdownReport.ps1 @@ -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") } } diff --git a/powershell/internal/services/github/Get-MtGitHubIdentityCollection.ps1 b/powershell/internal/services/github/Get-MtGitHubIdentityCollection.ps1 new file mode 100644 index 0000000000..2295103cf5 --- /dev/null +++ b/powershell/internal/services/github/Get-MtGitHubIdentityCollection.ps1 @@ -0,0 +1,57 @@ +function Get-MtGitHubIdentityCollection { + <# + .SYNOPSIS + Internal: Collects validated distinct identities without discarding usable partial evidence. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] [string] $RelativeUri, + [Parameter(Mandatory)] [string] $Label + ) + $executionError = $null + try { + $evidence = Invoke-MtGitHubRequest -RelativeUri $RelativeUri -Paginate -IncludeMetadata -ApiVersion '2026-03-10' -MaxPages 100 + } catch { + # The transport keeps earlier pages on errors. Retain their validated identities in the + # result Markdown, but never attach the raw response or server text to exported errors. + $partial = $_.Exception.Data['GitHubPartialResponse'] + $evidence = [pscustomobject]@{ Data = $partial.Data; ContentKind = 'Array'; CollectionIntegrityValid = $false; PaginationComplete = $false } + $message = if ($_.Exception.Data['GitHubRateLimit']) { 'GitHub rate limit stopped identity collection.' } else { 'GitHub identity collection request or JSON parsing failed.' } + $executionError = [System.InvalidOperationException]::new($message) + } + $gaps = [System.Collections.Generic.List[string]]::new() + if (-not $evidence.CollectionIntegrityValid -or -not $evidence.PaginationComplete -or $evidence.ContentKind -ne 'Array' -or $evidence.Data -isnot [array]) { + $gaps.Add("$Label collection is incomplete or has an unexpected API shape.") + } + $items = [System.Collections.Generic.List[object]]::new() + $seen = @{} + $conflicts = [System.Collections.Generic.HashSet[string]]::new() + if ($evidence.Data -is [array]) { + foreach ($item in $evidence.Data) { + if ($item -isnot [pscustomobject] -or ($item.id -isnot [int] -and $item.id -isnot [long] -and $item.id -isnot [bigint]) -or $item.id -le 0) { + $gaps.Add("$Label collection contains an invalid identity.") + continue + } + $id = [string]$item.id + if ($seen.ContainsKey($id)) { + $gaps.Add("$Label collection contains a duplicate identity.") + $previous = $seen[$id] + # A duplicate cannot increase the population. Conflicting or unusable permission + # observations for the same ID cannot establish an effective administrator either. + if ($previous.permissions.admin -isnot [bool] -or $item.permissions.admin -isnot [bool] -or $previous.permissions.admin -ne $item.permissions.admin) { + $null = $conflicts.Add($id) + } + continue + } + $seen[$id] = $item + $items.Add($item) + } + } + return [pscustomobject]@{ + Complete = $gaps.Count -eq 0 + Items = $items.ToArray() + ConflictingAdministratorIds = @($conflicts) + Gap = ($gaps | Select-Object -Unique) -join ' ' + ExecutionError = $executionError + } +} diff --git a/powershell/internal/services/github/Get-MtGitHubRepositoryInventory.ps1 b/powershell/internal/services/github/Get-MtGitHubRepositoryInventory.ps1 index 567316abe4..2bd7698eb7 100644 --- a/powershell/internal/services/github/Get-MtGitHubRepositoryInventory.ps1 +++ b/powershell/internal/services/github/Get-MtGitHubRepositoryInventory.ps1 @@ -2,12 +2,30 @@ <# .SYNOPSIS Internal: Enumerates organization repositories without visibility or archived-state filtering. + .DESCRIPTION + With RetainPartialOnError, returns validated partial identities and ExecutionError after a + request fails. The caller must report the rows and propagate the error without further requests. + By default, request failures still throw. #> [CmdletBinding()] - param() + param([switch] $RetainPartialOnError) $organization = $__MtSession.GitHubConnection.Organization $encoded = [uri]::EscapeDataString($organization) - $evidence = Invoke-MtGitHubRequest -RelativeUri "/orgs/$encoded/repos?type=all" -Paginate -ApiVersion '2026-03-10' -IncludeMetadata -MaxPages 100 + $executionError = $null + try { + $evidence = Invoke-MtGitHubRequest -RelativeUri "/orgs/$encoded/repos?type=all" -Paginate -ApiVersion '2026-03-10' -IncludeMetadata -MaxPages 100 + } catch { + if (-not $RetainPartialOnError) { throw } + # Apply the same identity validation to earlier pages, without carrying raw server + # text or response data into the exception that consumers may export. + $partial = $_.Exception.Data['GitHubPartialResponse'] + $evidence = [pscustomobject]@{ + Data = $partial.Data; ContentKind = 'Array'; CollectionIntegrityValid = $false; PaginationComplete = $false + StartedUtc = $partial.StartedUtc; CompletedUtc = $partial.CompletedUtc + } + $message = if ($_.Exception.Data['GitHubRateLimit']) { 'GitHub rate limit stopped repository inventory collection.' } else { 'GitHub repository inventory request or JSON parsing failed.' } + $executionError = [System.InvalidOperationException]::new($message) + } $issues = [System.Collections.Generic.List[string]]::new() foreach ($issue in $evidence.Issues) { $issues.Add($issue) } if (-not $evidence.CollectionIntegrityValid -or $evidence.ContentKind -ne 'Array' -or $evidence.Data -isnot [array]) { $issues.Add('Repository inventory is incomplete or has an unexpected API shape.') } @@ -48,5 +66,10 @@ $seenIds[$key] = $path $repositories.Add($repository) } - return [pscustomobject]@{ Repositories = @($repositories | Where-Object { [string]$_.id -cnotin $conflictingIds }); Issues = @($issues | Select-Object -Unique); StartedUtc = $evidence.StartedUtc; CompletedUtc = $evidence.CompletedUtc } + return [pscustomobject]@{ + Repositories = @($repositories | Where-Object { [string]$_.id -cnotin $conflictingIds }) + Issues = @($issues | Select-Object -Unique) + StartedUtc = $evidence.StartedUtc; CompletedUtc = $evidence.CompletedUtc + ExecutionError = $executionError + } } diff --git a/powershell/public/report/Get-MtHtmlReport.ps1 b/powershell/public/report/Get-MtHtmlReport.ps1 index 6e331ffec7..de6edab78c 100644 --- a/powershell/public/report/Get-MtHtmlReport.ps1 +++ b/powershell/public/report/Get-MtHtmlReport.ps1 @@ -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." } } } @@ -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. diff --git a/powershell/public/run/Add-MtTestResultDetail.ps1 b/powershell/public/run/Add-MtTestResultDetail.ps1 index 3f4fa78dba..85355120ab 100644 --- a/powershell/public/run/Add-MtTestResultDetail.ps1 +++ b/powershell/public/run/Add-MtTestResultDetail.ps1 @@ -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 @@ -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 { @@ -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 diff --git a/powershell/public/run/Invoke-Maester.ps1 b/powershell/public/run/Invoke-Maester.ps1 index dc2612d80f..597281dde6 100644 --- a/powershell/public/run/Invoke-Maester.ps1 +++ b/powershell/public/run/Invoke-Maester.ps1 @@ -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' @@ -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 } @@ -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 diff --git a/powershell/tests/functions/Get-MtGitHubRepositoryInventory.Tests.ps1 b/powershell/tests/functions/Get-MtGitHubRepositoryInventory.Tests.ps1 index ec634591ab..0fbc8a5047 100644 --- a/powershell/tests/functions/Get-MtGitHubRepositoryInventory.Tests.ps1 +++ b/powershell/tests/functions/Get-MtGitHubRepositoryInventory.Tests.ps1 @@ -77,6 +77,11 @@ Describe 'Validated GitHub repository inventory identities' { $actual.Issues.Count | Should -BeGreaterThan 0 } + It 'Preserves throwing on request errors unless partial retention is explicitly requested' { + Mock Invoke-MtGitHubRequest -ModuleName Maester { throw 'Synthetic inventory failure' } + { Get-MtGitHubRepositoryInventory } | Should -Throw '*Synthetic inventory failure*' + } + It 'Retains a successful empty inventory without inventing identities or retrieval gaps' { $actual = Get-MtGitHubRepositoryInventory $actual.Repositories.Count | Should -Be 0 diff --git a/powershell/tests/functions/Get-MtMarkdownReport.Tests.ps1 b/powershell/tests/functions/Get-MtMarkdownReport.Tests.ps1 new file mode 100644 index 0000000000..39d8283cea --- /dev/null +++ b/powershell/tests/functions/Get-MtMarkdownReport.Tests.ps1 @@ -0,0 +1,74 @@ +BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force +} + +Describe 'Markdown failure messages' { + It 'Renders every error without changing its records' -ForEach @( + @{ Shape = 'original' }, @{ Shape = 'deserialized' } + ) { + $first = [System.Management.Automation.ErrorRecord]::new([System.Exception]::new('Underlying exception'), 'Fixture', 'NotSpecified', $null) + $first.ErrorDetails = [System.Management.Automation.ErrorDetails]::new('Detailed failure') + $second = [System.Management.Automation.ErrorRecord]::new([System.Exception]::new('Second failure'), 'Fixture', 'NotSpecified', $null) + $errors = @($first, $second) + if ($Shape -eq 'deserialized') { $errors = $errors | ConvertTo-Json -Depth 5 | ConvertFrom-Json } + $source = [pscustomobject]@{ Tests = @([pscustomobject]@{ Name = 'Fixture'; Result = 'Failed'; ScriptBlock = 'Invoke-Fixture'; ErrorRecord = $errors }) } + $before = $source | ConvertTo-Json -Depth 10 + $markdown = InModuleScope Maester -Parameters @{ Source = $source } { Get-MtMarkdownReport -MaesterResults $Source } + $markdown | Should -Match '#### Reason for failure\s+Detailed failure\s+Second failure' + $markdown | Should -Not -Match 'Underlying exception|System.Management.Automation|@\{' + ($source | ConvertTo-Json -Depth 10) | Should -BeExactly $before + } +} + +Describe 'Pester failure Markdown through Invoke-Maester' { + BeforeAll { + $fixture = Join-Path $TestDrive 'suite/Custom' + $null = New-Item $fixture -ItemType Directory -Force + @' +BeforeAll { $script:failureMessage = 'Runtime failure for RAW_FIXTURE_USER' } +Describe 'Export fixture' { + It 'Custom.Failure: reports the runtime error' { throw $script:failureMessage } +} +'@ | Set-Content (Join-Path $fixture 'Failure.Tests.ps1') + # A child process keeps the custom Pester run separate from this unit-test run. + $runner = Join-Path $TestDrive 'run.ps1' + @' +param($Manifest, $PesterManifest, $Fixture, $OutputRoot) +$ErrorActionPreference = 'Stop' +Import-Module $PesterManifest +Import-Module $Manifest +& (Get-Module Maester) { function script:Get-MtUserIdentityReplacementMap { @{ RAW_FIXTURE_USER = 'SAFE_FIXTURE_USER' } } } +foreach ($mode in 'None', 'HtmlOnly', 'AllOutputs') { + $folder = Join-Path $OutputRoot $mode + $result = Invoke-Maester -Path $Fixture -Config @{ GlobalSettings = @{} } -SkipBuiltIn -SkipPack -SkipGraphConnect -PassThru -NonInteractive -DisableTelemetry -SkipVersionCheck -NoLogo -RedactUserIdentity $mode -OutputFolder $folder -OutputFolderFileName result + $row = $result.Tests | Where-Object Id -EQ 'Custom.Failure' + [pscustomobject]@{ Result = $row.Result; ErrorType = $row.ErrorRecord[0].GetType().FullName; Message = $row.ErrorRecord[0].Exception.Message } | + ConvertTo-Json | Set-Content (Join-Path $folder 'passthru.json') +} +'@ | Set-Content $runner + $manifest = (Resolve-Path "$PSScriptRoot/../../Maester.psd1").Path + $pesterManifest = Join-Path (Get-Module Pester).ModuleBase 'Pester.psd1' + $output = & pwsh -NoProfile -NonInteractive -File $runner -Manifest $manifest -PesterManifest $pesterManifest -Fixture $fixture -OutputRoot $TestDrive 2>&1 + if ($LASTEXITCODE -ne 0) { throw "Export fixture failed: $output" } + } + + It 'Keeps readable failure evidence and caller records in mode' -ForEach @( + @{ Mode = 'None' }, @{ Mode = 'HtmlOnly' }, @{ Mode = 'AllOutputs' } + ) { + $folder = Join-Path $TestDrive $Mode + $markdown = Get-Content (Join-Path $folder 'result.md') -Raw + $json = Get-Content (Join-Path $folder 'result.json') -Raw + $expected = if ($Mode -eq 'AllOutputs') { 'SAFE_FIXTURE_USER' } else { 'RAW_FIXTURE_USER' } + $markdown | Should -Match "#### Reason for failure\s+Runtime failure for $expected" + $saved = $json | ConvertFrom-Json + $saved.Tests[0].ErrorRecord[0].Exception.Message | Should -Be "Runtime failure for $expected" + if ($Mode -eq 'AllOutputs') { + $markdown | Should -Not -Match 'RAW_FIXTURE_USER' + $json | Should -Not -Match 'RAW_FIXTURE_USER' + } + $original = Get-Content (Join-Path $folder 'passthru.json') -Raw | ConvertFrom-Json + $original.Result | Should -Be 'Error' + $original.ErrorType | Should -Be 'System.Management.Automation.ErrorRecord' + $original.Message | Should -Be 'Runtime failure for RAW_FIXTURE_USER' + } +} diff --git a/powershell/tests/functions/GitHubDeletionNative.Tests.ps1 b/powershell/tests/functions/GitHubDeletionNative.Tests.ps1 new file mode 100644 index 0000000000..b18b859205 --- /dev/null +++ b/powershell/tests/functions/GitHubDeletionNative.Tests.ps1 @@ -0,0 +1,482 @@ +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '', Justification = 'Pester supplies this container parameter to BeforeAll for source and built-module validation.')] +[CmdletBinding()] +param([string] $ModulePath = "$PSScriptRoot/../../Maester.psd1") + +BeforeAll { + Import-Module $ModulePath -Force + + # Reads the results Get-MtHtmlReport embeds: gzip-compressed, Base64-encoded JSON in the data element. + function Get-ReportDataText([string] $Html) { + $match = [regex]::Match($Html, '') + if (-not $match.Success) { throw 'The report has no compressed maester-report-data element.' } + $stream = [System.IO.MemoryStream]::new([System.Convert]::FromBase64String($match.Groups[1].Value)) + $reader = [System.IO.StreamReader]::new([System.IO.Compression.GZipStream]::new($stream, [System.IO.Compression.CompressionMode]::Decompress)) + try { $reader.ReadToEnd() } finally { $reader.Dispose() } + } +} + +Describe 'Partial repository coverage through native execution and exports' { + BeforeEach { + $script:requestPaths = [System.Collections.Generic.List[string]]::new() + $script:timeoutPath = $null + $script:activePolicy = $false + $script:repositoryResponses = @{ + '/orgs/fixture-org' = @{ id = 100; members_can_delete_repositories = $true; members_can_delete_issues = $true } + '/orgs/fixture-org/repos?type=all&per_page=100' = @( + @{ id = 200; name = 'fixture-repo'; full_name = 'fixture-org/fixture-repo'; owner = @{ login = 'fixture-org' } }, + @{ id = 201; name = 'other-repo'; full_name = 'fixture-org/other-repo'; owner = @{ login = 'fixture-org' } } + ) + '/repos/fixture-org/fixture-repo/collaborators?affiliation=all&per_page=100' = @(@{ id = 1; permissions = @{ admin = $true } }, @{ id = 2; permissions = @{ admin = $true } }) + '/repos/fixture-org/other-repo/collaborators?affiliation=all&per_page=100' = @(@{ id = 1; permissions = @{ admin = $true } }, @{ id = 2; permissions = @{ admin = $true } }) + } + $script:repositoryConfig = @{ GlobalSettings = @{ GitHubDeletionPolicy = @{ + ApiBaseUri = 'https://api.github.com'; OrganizationId = '100'; CompleteRepositoryInventory = $true + Repositories = @(@{ Id = '200'; ApprovedAdministratorIds = @('1', '2', '9876543210123') }) + } } } + InModuleScope Maester { + $__MtSession.GitHubConnection = [pscustomobject]@{ Connected = $true; Organization = 'fixture-org'; ApiBaseUri = 'https://api.github.com'; ApiVersion = '2022-11-28' } + $__MtSession.GitHubAuthHeader = @{ Authorization = 'Bearer synthetic-never-network'; 'X-GitHub-Api-Version' = '2022-11-28' } + $__MtSession.GitHubCache = @{} + $__MtSession.GitHubRateLimits = $null + $__MtSession.MaesterConfig = $null + } + Mock Invoke-WebRequest -ModuleName Maester { + if ($Uri -notlike 'https://api.github.com/*' -or $ConnectionTimeoutSeconds -ne 30 -or $OperationTimeoutSeconds -ne 30) { throw 'Unexpected native transport options.' } + $path = ([uri]$Uri).PathAndQuery + $script:requestPaths.Add($path) + if ($path -eq $script:timeoutPath) { throw [System.TimeoutException]::new('Sensitive server text: 90123456789 synthetic-never-network') } + if ($path -eq '/graphql') { + if ($Method -ne 'POST' -or $Headers.ContainsKey('X-GitHub-Api-Version')) { throw 'Unexpected GraphQL transport options.' } + $request = $Body | ConvertFrom-Json + if ($request.operationName -ne 'DeletionPolicies' -or $request.variables.repo -ne 'fixture-repo') { throw 'Unexpected policy request; network is forbidden.' } + $nodes = @(if ($script:activePolicy) { @{ id = 'fixture-policy'; target = 'REPOSITORY'; enforcement = 'ACTIVE' } }) + $data = @{ data = @{ repository = @{ databaseId = 200; rulesets = @{ totalCount = $nodes.Count; nodes = $nodes; pageInfo = @{ hasNextPage = $false; endCursor = $null } } } } } + } else { + if ($Method -ne 'GET' -or $Headers['X-GitHub-Api-Version'] -ne '2026-03-10' -or -not $script:repositoryResponses.ContainsKey($path)) { throw 'Unexpected fixture endpoint; network is forbidden.' } + $data = $script:repositoryResponses[$path] + } + [pscustomobject]@{ Content = ConvertTo-Json -InputObject $data -Depth 12 -Compress; Headers = @{} } + } + } + AfterEach { + InModuleScope Maester { + $__MtSession.GitHubConnection = $null + $__MtSession.GitHubAuthHeader = $null + $__MtSession.GitHubCache = @{} + $__MtSession.GitHubRateLimits = $null + $__MtSession.MaesterConfig = $null + } + } + + It 'Avoids administrator reads for without a policy despite fixture administrators' -ForEach @( + @{ Id = 'CIS.GH.1.2.3'; Count = 2; Expected = 'Investigate' }, + @{ Id = 'CIS.GH.1.2.4'; Count = 2; Expected = 'Investigate' }, + @{ Id = 'CIS.GH.1.2.3'; Count = 3; Expected = 'Investigate' }, + @{ Id = 'CIS.GH.1.2.4'; Count = 3; Expected = 'Investigate' } + ) { + if ($Count -eq 3) { $script:repositoryResponses['/repos/fixture-org/fixture-repo/collaborators?affiliation=all&per_page=100'] += @{ id = 90123456789; permissions = @{ admin = $true } } } + $row = Invoke-MtTest -Id $Id -Config @{ GlobalSettings = @{} } + $row.Result | Should -Be $Expected + $row.ResultDetail.TestResult | Should -Match '\| fixture-repo \| Not assessed \| Not configured \| \| Not assessed \| Not collected \|' + $row.ResultDetail.TestResult | Should -Not -Match 'Meets baseline|90123456789' + $script:requestPaths.Count | Should -Be 2 + @($script:requestPaths | Where-Object { $_ -match 'collaborators|graphql|roles' }).Count | Should -Be 0 + $script:requestPaths | Should -Not -Contain '/orgs/fixture-org/custom-repository-roles' + } + + It 'Assesses only the configured repository and retains its confirmed failure ()' -ForEach @( + @{ Id = 'CIS.GH.1.2.3' }, @{ Id = 'CIS.GH.1.2.4' } + ) { + $script:repositoryResponses['/repos/fixture-org/fixture-repo/collaborators?affiliation=all&per_page=100'] += @{ id = 3; permissions = @{ admin = $true } } + $row = Invoke-MtTest -Id $Id -Config $script:repositoryConfig + $row.Result | Should -Be 'Failed' + $row.ResultDetail.TestResult | Should -Match '\| fixture-repo \| 3 \|' + $row.ResultDetail.TestResult | Should -Match '\| other-repo \| Not assessed \| Not configured \| \| Not assessed \| Not collected \|' + @($script:requestPaths | Where-Object { $_ -match '/other-repo/' }).Count | Should -Be 0 + @($script:requestPaths | Where-Object { $_ -match 'collaborators' }).Count | Should -Be 1 + @($script:requestPaths | Where-Object { $_ -match 'roles' }).Count | Should -Be 0 + } + + It 'Does not request collaborators for empty applicable rosters ()' -ForEach @( + @{ Id = 'CIS.GH.1.2.3' }, @{ Id = 'CIS.GH.1.2.4' } + ) { + $script:repositoryConfig.GlobalSettings.GitHubDeletionPolicy.Repositories[0].ApprovedAdministratorIds = @() + $row = Invoke-MtTest -Id $Id -Config $script:repositoryConfig + $row.Result | Should -Be 'Investigate' + $script:requestPaths.Count | Should -Be 2 + $row.ResultDetail.TestResult | Should -Match 'Not assessed.*Not collected' + } + + It 'Keeps a candidate violation indeterminate when restrictive policy is active despite a scope gap' { + $script:repositoryResponses['/repos/fixture-org/fixture-repo/collaborators?affiliation=all&per_page=100'] += @{ id = 90123456789; permissions = @{ admin = $true } } + $script:activePolicy = $true + $row = Invoke-MtTest -Id CIS.GH.1.2.3 -Config $script:repositoryConfig + $row.Result | Should -Be 'Investigate' + $row.ResultDetail.TestResult | Should -Match 'active repository-target policy' + $row.ResultDetail.TestResult | Should -Match 'do not match' + } + + It 'Sanitizes an inventory timeout and makes no follow-on requests' { + $script:timeoutPath = '/orgs/fixture-org/repos?type=all&per_page=100' + $row = Invoke-MtTest -Id CIS.GH.1.2.4 -Config $script:repositoryConfig + $row.Result | Should -Be 'Error' + $row.ReasonDetail | Should -Not -Match 'Sensitive server text|90123456789|synthetic-never-network' + ($row.ErrorRecord | ConvertTo-Json -Depth 30) | Should -Not -Match 'Sensitive server text|90123456789|synthetic-never-network' + $script:requestPaths.Count | Should -Be 2 + } + + It 'Retains validated inventory after a later-page error without assessing access ()' -ForEach @( + @{ Failure = 'Timeout'; Id = 'CIS.GH.1.2.3' }, @{ Failure = 'JSON'; Id = 'CIS.GH.1.2.3' }, @{ Failure = 'Rate limit'; Id = 'CIS.GH.1.2.3' }, + @{ Failure = 'Timeout'; Id = 'CIS.GH.1.2.4' }, @{ Failure = 'JSON'; Id = 'CIS.GH.1.2.4' }, @{ Failure = 'Rate limit'; Id = 'CIS.GH.1.2.4' } + ) { + Mock Invoke-WebRequest -ModuleName Maester { + $path = ([uri]$Uri).PathAndQuery + $script:requestPaths.Add($path) + if ($path -eq '/orgs/fixture-org') { + return @{ Content = '{"id":100,"members_can_delete_repositories":true,"members_can_delete_issues":true}'; Headers = @{} } + } + if ($path -eq '/orgs/fixture-org/repos?type=all&per_page=100&page=2') { + if ($Failure -eq 'JSON') { return @{ Content = '{"sensitive-server-text":'; Headers = @{} } } + if ($Failure -eq 'Rate limit') { + $response = [System.Net.Http.HttpResponseMessage]::new([System.Net.HttpStatusCode]::TooManyRequests) + $null = $response.Headers.TryAddWithoutValidation('Retry-After', '60') + throw [Microsoft.PowerShell.Commands.HttpResponseException]::new('sensitive-server-text', $response) + } + throw [System.TimeoutException]::new('sensitive-server-text') + } + if ($path -ne '/orgs/fixture-org/repos?type=all&per_page=100') { throw 'Unexpected endpoint; network is forbidden.' } + $items = @($script:repositoryResponses[$path]) + @( + @{ id = 202; name = 'unusable-repository' }, + @{ id = 203; name = 'conflicting-repository'; full_name = 'fixture-org/conflicting-repository'; owner = @{ login = 'fixture-org' } }, + @{ id = 203; name = 'conflicting-repository'; full_name = 'foreign-org/conflicting-repository'; owner = @{ login = 'foreign-org' } } + ) + return @{ + Content = ConvertTo-Json -InputObject $items -Depth 10 -Compress + Headers = @{ Link = '; rel="next"' } + } + } + $row = Invoke-MtTest -Id $Id -Config $script:repositoryConfig + $row.Result | Should -Be 'Error' + $row.ReasonCode | Should -Be 'TestError' + $row.ResultDetail.TestResult | Should -Match '\| fixture-repo \| Not assessed \| Not assessed \| \| Not assessed \| Not collected \|' + $row.ResultDetail.TestResult | Should -Match '\| other-repo \| Not assessed \| Not configured \| \| Not assessed \| Not collected \|' + $row.ResultDetail.TestResult | Should -Match 'inventory.*incomplete|pagination is incomplete' + $row.ResultDetail.TestResultRedacted | Should -Match 'fixture-repo.*Not assessed.*Not collected' + $row.ResultDetail.TestResult | Should -Not -Match 'unusable-repository|conflicting-repository|sensitive-server-text|9876543210123' + $row.ReasonDetail | Should -Not -Match 'fixture-repo|other-repo|sensitive-server-text|GitHubPartialResponse' + ($row.ErrorRecord | ConvertTo-Json -Depth 30) | Should -Not -Match 'fixture-repo|other-repo|sensitive-server-text|GitHubPartialResponse' + if ($Failure -eq 'Rate limit') { $row.ReasonDetail | Should -Match 'rate limit stopped deletion assessment' } + $script:requestPaths.Count | Should -Be 3 + @($script:requestPaths | Where-Object { $_ -match 'collaborators|graphql|roles' }).Count | Should -Be 0 + } + + It 'Exports retained findings and gaps with redaction after ' -ForEach @( + @{ Mode = 'None'; Outcome = 'Failed' }, @{ Mode = 'HtmlOnly'; Outcome = 'Failed' }, @{ Mode = 'AllOutputs'; Outcome = 'Failed' }, + @{ Mode = 'None'; Outcome = 'Error' }, @{ Mode = 'HtmlOnly'; Outcome = 'Error' }, @{ Mode = 'AllOutputs'; Outcome = 'Error' } + ) { + Mock Get-MtUserIdentityReplacementMap -ModuleName Maester { @{} } + $script:excelInput = $null + Mock Convert-MtResultsToFlatObject -ModuleName Maester -ParameterFilter { $ExcelFilePath } { $script:excelInput = $InputObject } + $script:repositoryResponses['/repos/fixture-org/fixture-repo/collaborators?affiliation=all&per_page=100'] += @{ id = 90123456789; permissions = @{ admin = $true } } + if ($Outcome -eq 'Error') { + $script:repositoryConfig.GlobalSettings.GitHubDeletionPolicy.Repositories += @{ Id = '201'; ApprovedAdministratorIds = @('1', '2') }, @{ Id = '202'; ApprovedAdministratorIds = @('1', '2') } + $script:timeoutPath = '/repos/fixture-org/other-repo/collaborators?affiliation=all&per_page=100' + } + $folder = Join-Path $TestDrive "$Outcome-$Mode" + $xmlPath = Join-Path $TestDrive "$Outcome-$Mode.xml" + $script:repositoryConfig.Output = @{ TestResult = @{ Path = $xmlPath; Format = 'JUnitXml' } } + $result = Invoke-Maester -Config $script:repositoryConfig -TestId CIS.GH.1.2.4 -PassThru -SkipGraphConnect -NonInteractive -DisableTelemetry -SkipVersionCheck -NoLogo -OutputFolder $folder -OutputFolderFileName result -ExportCsv -ExportExcel -RedactUserIdentity $Mode + $row = $result.Tests | Where-Object Id -EQ 'CIS.GH.1.2.4' + $row.Result | Should -Be $Outcome + $row.ResultDetail.TestResult | Should -Match '\| fixture-repo \| 3 \| 1 \| 90123456789 \|' + foreach ($extension in 'json', 'html', 'md', 'csv') { + $content = Get-Content (Join-Path $folder "result.$extension") -Raw + if ($extension -eq 'html') { $content = Get-ReportDataText $content } + ($content -match 'fixture-repo|other-repo') | Should -BeTrue + ($content -match 'do not match') | Should -BeTrue + ($content -match 'Sensitive server text|synthetic-never-network|9876543210123|GitHubPartialResponse') | Should -BeFalse + if ($Mode -eq 'AllOutputs' -or ($Mode -eq 'HtmlOnly' -and $extension -eq 'html')) { + ($content -match '90123456789|TestResultRedacted') | Should -BeFalse + ($content -match 'object-[a-f0-9]{16}') | Should -BeTrue + } else { ($content -match '90123456789') | Should -BeTrue } + } + Should -Invoke Convert-MtResultsToFlatObject -ModuleName Maester -Times 1 -Exactly -ParameterFilter { $ExcelFilePath } + $excelJson = $script:excelInput | ConvertTo-Json -Depth 30 + if ($Mode -eq 'AllOutputs') { ($excelJson -match '90123456789|TestResultRedacted') | Should -BeFalse } + else { ($excelJson -match '90123456789') | Should -BeTrue } + ($excelJson -match 'Sensitive server text|synthetic-never-network|9876543210123|GitHubPartialResponse') | Should -BeFalse + ((Get-Content $xmlPath -Raw) -match '90123456789|Sensitive server text|synthetic-never-network|9876543210123') | Should -BeFalse + if ($Outcome -eq 'Error') { $script:requestPaths.Count | Should -Be 4 } + } +} + +Describe 'GitHub deletion verdicts through the native engine and HTTP fixtures' { + BeforeEach { + $script:apiBase = 'https://api.github.com' + $script:owners = @(@{ id = 1; login = 'fixture-owner-one' }, @{ id = 2; login = 'fixture-owner-two' }) + $script:responseHeaders = @{} + $script:status = 200 + $script:partialError = $false + $script:config = @{ + GlobalSettings = @{ + GitHubDeletionPolicy = @{ + ApiBaseUri = $script:apiBase + OrganizationId = '100' + ApprovedOwnerIds = @('1', '2', '3', '4', '9876543210123') + } + } + } + InModuleScope Maester { + $__MtSession.GitHubConnection = [pscustomobject]@{ Connected = $true; Organization = 'fixture-org'; ApiBaseUri = 'https://api.github.com'; ApiVersion = '2022-11-28' } + $__MtSession.GitHubAuthHeader = @{ Authorization = 'Bearer synthetic-never-network'; 'X-GitHub-Api-Version' = '2022-11-28' } + $__MtSession.GitHubCache = @{} + $__MtSession.GitHubRateLimits = $null + $__MtSession.MaesterConfig = $null + } + Mock Invoke-WebRequest -ModuleName Maester { + if ($Method -ne 'GET' -or $Headers['X-GitHub-Api-Version'] -ne '2026-03-10' -or $Uri -notlike "$script:apiBase/*") { throw 'Unexpected native fixture request.' } + $path = ([uri]$Uri).PathAndQuery + if ($path -eq '/orgs/fixture-org') { + return [pscustomobject]@{ Content = '{"id":100,"login":"fixture-org","members_can_delete_repositories":false,"members_can_delete_issues":false}'; Headers = @{} } + } + if ($script:partialError -and $path -like '*page=2*') { throw 'fixture-owner-one: 90123456789 parsing failure' } + if ($path -ne '/orgs/fixture-org/members?role=admin&per_page=100') { throw 'Unrecognized fixture endpoint; network is forbidden.' } + if ($script:status -ne 200) { + $response = [System.Net.Http.HttpResponseMessage]::new([System.Net.HttpStatusCode]$script:status) + foreach ($key in $script:responseHeaders.Keys) { $null = $response.Headers.TryAddWithoutValidation($key, [string]$script:responseHeaders[$key]) } + throw [Microsoft.PowerShell.Commands.HttpResponseException]::new('Synthetic owner collection failure', $response) + } + if ($script:partialError) { $script:responseHeaders.Link = '; rel="next"' } + return [pscustomobject]@{ Content = ConvertTo-Json -InputObject $script:owners -Compress; Headers = $script:responseHeaders } + } + } + AfterEach { + InModuleScope Maester { + $__MtSession.GitHubConnection = $null + $__MtSession.GitHubAuthHeader = $null + $__MtSession.GitHubCache = @{} + $__MtSession.GitHubRateLimits = $null + $__MtSession.MaesterConfig = $null + } + } + + It 'Returns Passed for both existing checks with a longer approved list and two actual owners' { + $rows = @(Invoke-MtTest -Id 'CIS.GH.1.2.3', 'CIS.GH.1.2.4' -Config $script:config) + $rows.Count | Should -Be 2 + @($rows | Where-Object Result -NE 'Passed').Count | Should -Be 0 + ($rows.ResultDetail.TestResult -join '') | Should -Not -Match '9876543210123|synthetic-never-network' + Should -Invoke Invoke-WebRequest -ModuleName Maester -Times 2 -Exactly + } + + It 'Returns Failed for four live approved owners despite a five-entry approval list' { + $script:owners += @{ id = 3 }, @{ id = 4 } + $row = Invoke-MtTest -Id 'CIS.GH.1.2.3' -Config $script:config + $row.Result | Should -Be 'Failed' + $row.ResultDetail.TestResult | Should -Match '\| 4 \| 3 \| 0 \|' + $row.ResultDetail.TestResult | Should -Not -Match '9876543210123' + } + + It 'Keeps four owners Investigate before approvals are configured ()' -ForEach @( + @{ Id = 'CIS.GH.1.2.3' }, @{ Id = 'CIS.GH.1.2.4' } + ) { + $script:owners += @{ id = 3 }, @{ id = 4 } + $row = Invoke-MtTest -Id $Id -Config @{ GlobalSettings = @{} } + $row.Result | Should -Be 'Investigate' + $row.ResultDetail.TestResult | Should -Match '\| 4 \| 3 \| Not configured \|' + $row.ResultDetail.TestResult | Should -Not -Match 'within the configured maximum' + Should -Invoke Invoke-WebRequest -ModuleName Maester -Times 2 -Exactly + } + + It 'Accepts an assessor-selected owner maximum above three ()' -ForEach @( + @{ Id = 'CIS.GH.1.2.3' }, @{ Id = 'CIS.GH.1.2.4' } + ) { + $script:owners += @{ id = 3 }, @{ id = 4 } + $row = Invoke-MtTest -Id $Id -Config $script:config -Parameter @{ MaximumOrganizationOwners = 4 } + $row.Result | Should -Be 'Passed' + $row.ResultDetail.TestResult | Should -Match '\| 4 \| 4 \| 0 \|' + } + + It 'Keeps partial SSO owner visibility indeterminate' { + $script:responseHeaders = @{ 'X-GitHub-SSO' = 'partial-results; organizations=100' } + $row = Invoke-MtTest -Id 'CIS.GH.1.2.4' -Config $script:config + $row.Result | Should -Be 'Skipped' + $row.ReasonDetail | Should -Match 'Indeterminate' + } + + It 'Rejects an approval policy for a different organization through the engine' { + $script:config.GlobalSettings.GitHubDeletionPolicy.OrganizationId = '101' + $row = Invoke-MtTest -Id 'CIS.GH.1.2.3' -Config $script:config + $row.Result | Should -Be 'Error' + Should -Invoke Invoke-WebRequest -ModuleName Maester -Times 1 -Exactly + } + + It 'Routes GHE.com evidence and validates the matching host-bound policy' { + $script:apiBase = 'https://api.fixture.ghe.com' + $script:config.GlobalSettings.GitHubDeletionPolicy.ApiBaseUri = $script:apiBase + InModuleScope Maester { $__MtSession.GitHubConnection.ApiBaseUri = 'https://api.fixture.ghe.com' } + (Invoke-MtTest -Id 'CIS.GH.1.2.3' -Config $script:config).Result | Should -Be 'Passed' + Should -Invoke Invoke-WebRequest -ModuleName Maester -Times 2 -Exactly -ParameterFilter { $Uri -like 'https://api.fixture.ghe.com/*' } + } + + It 'Stops requests across the two native checks after a shared secondary limit' { + $script:status = 429 + $script:responseHeaders = @{ 'retry-after' = '120' } + $rows = @(Invoke-MtTest -Id 'CIS.GH.1.2.3', 'CIS.GH.1.2.4' -Config $script:config) + $rows.Count | Should -Be 2 + @($rows | Where-Object Result -NE 'Error').Count | Should -Be 0 + Should -Invoke Invoke-WebRequest -ModuleName Maester -Times 2 -Exactly + } + + It 'Retains required owner-access denials as Error rather than zero owners' { + $script:status = 403 + (Invoke-MtTest -Id 'CIS.GH.1.2.4' -Config $script:config).Result | Should -Be 'Error' + } + + It 'Exports both observed owner rosters through Invoke-Maester without approval configuration' { + $jsonPath = Join-Path $TestDrive 'unconfigured.json' + $htmlPath = Join-Path $TestDrive 'unconfigured.html' + $result = Invoke-Maester -Config @{ GlobalSettings = @{} } -TestId CIS.GH.1.2.3, CIS.GH.1.2.4 -PassThru -SkipGraphConnect -NonInteractive -DisableTelemetry -SkipVersionCheck -NoLogo -OutputJsonFile $jsonPath -OutputHtmlFile $htmlPath + $rows = @($result.Tests | Where-Object Id -In 'CIS.GH.1.2.3', 'CIS.GH.1.2.4') + $rows.Count | Should -Be 2 + @($rows | Where-Object Result -NE 'Investigate').Count | Should -Be 0 + foreach ($row in $rows) { + $row.ResultDetail.TestResult | Should -Match ([regex]::Escape('| fixture-owner-one | 1 | Not configured |')) + $row.ResultDetail.TestResult | Should -Match ([regex]::Escape('| fixture-owner-two | 2 | Not configured |')) + } + $export = Get-Content $jsonPath -Raw | ConvertFrom-Json + $exportRows = @($export.Tests | Where-Object Id -In 'CIS.GH.1.2.3', 'CIS.GH.1.2.4') + $exportRows.Count | Should -Be 2 + foreach ($row in $exportRows) { + $row.Result | Should -Be 'Investigate' + $row.ResultDetail.TestResult | Should -Match 'fixture-owner-one|fixture-owner-two' + } + foreach ($path in $jsonPath, $htmlPath) { + $content = Get-Content $path -Raw + if ($path -eq $htmlPath) { $content = Get-ReportDataText $content } + $content.Contains('fixture-owner-one') | Should -BeTrue + $content.Contains('fixture-owner-two') | Should -BeTrue + $content | Should -Not -Match '9876543210123|synthetic-never-network' + } + } + + It 'Protects displayed identities in exports with an empty generic map' -ForEach @( + @{ Mode = 'None' }, @{ Mode = 'HtmlOnly' }, @{ Mode = 'AllOutputs' } + ) { + Mock Get-MtUserIdentityReplacementMap -ModuleName Maester { @{} } + $script:excelInput = $null + Mock Convert-MtResultsToFlatObject -ModuleName Maester -ParameterFilter { $ExcelFilePath } { $script:excelInput = $InputObject } + $folder = Join-Path $TestDrive $Mode + $xmlPath = Join-Path $TestDrive "$Mode.xml" + $script:config.Output = @{ TestResult = @{ Path = $xmlPath; Format = 'JUnitXml' } } + $result = Invoke-Maester -Config $script:config -TestId CIS.GH.1.2.3, CIS.GH.1.2.4 -PassThru -SkipGraphConnect -NonInteractive -DisableTelemetry -SkipVersionCheck -NoLogo -OutputFolder $folder -OutputFolderFileName result -ExportCsv -ExportExcel -RedactUserIdentity $Mode -IncludeAffectedObjects + $rows = @($result.Tests | Where-Object Id -In 'CIS.GH.1.2.3', 'CIS.GH.1.2.4') + @($rows | Where-Object Result -NE 'Passed').Count | Should -Be 0 + ($rows.ResultDetail.TestResult -join '') | Should -Match 'fixture-owner-one' + $result.AffectedObjects.Type | Should -Contain 'GitHubOrganization' + foreach ($extension in 'json', 'html', 'md', 'csv') { + $content = Get-Content (Join-Path $folder "result.$extension") -Raw + if ($extension -eq 'html') { $content = Get-ReportDataText $content } + if ($Mode -eq 'AllOutputs' -or ($Mode -eq 'HtmlOnly' -and $extension -eq 'html')) { + $content | Should -Not -Match 'fixture-owner-one|fixture-owner-two|TestResultRedacted' + $content | Should -Match 'object-[a-f0-9]{16}' + } else { + $content | Should -Match 'fixture-owner-one' + } + } + Should -Invoke Convert-MtResultsToFlatObject -ModuleName Maester -Times 1 -Exactly -ParameterFilter { $ExcelFilePath } + $excelJson = $script:excelInput | ConvertTo-Json -Depth 15 + if ($Mode -eq 'AllOutputs') { $excelJson | Should -Not -Match 'fixture-owner-one|fixture-owner-two|TestResultRedacted' } + else { $excelJson | Should -Match 'fixture-owner-one' } + ([xml](Get-Content $xmlPath -Raw)).testsuites | Should -Not -BeNullOrEmpty + $xml = Get-Content $xmlPath -Raw + $xml | Should -Not -Match 'fixture-owner-one|fixture-owner-two' + $export = Get-Content (Join-Path $folder 'result.json') -Raw | ConvertFrom-Json + $exportRows = @($export.Tests | Where-Object Id -In 'CIS.GH.1.2.3', 'CIS.GH.1.2.4') + @($exportRows | Where-Object Result -NE 'Passed').Count | Should -Be 0 + foreach ($row in $exportRows) { $row.ResultDetail.TestResult | Should -Match '\| 2 \| 3 \| 0 \| Complete' } + $before = $export | ConvertTo-Json -Depth 15 + # In-memory results retain the alternative for later redaction, even with an empty map. + $standalone = Get-MtHtmlReport -MaesterResults $result -RedactUserIdentity HtmlOnly -UserIdentityReplacementMap @{} + $standalone | Should -Not -Match 'fixture-owner-one|fixture-owner-two|TestResultRedacted' + # Saved unredacted JSON omits the alternative; imported results use generic replacement. + $imported = Get-MtHtmlReport -MaesterResults $export -RedactUserIdentity HtmlOnly -UserIdentityReplacementMap @{ 'fixture-owner-one' = 'object-imported-one'; 'fixture-owner-two' = 'object-imported-two' } + $imported | Should -Not -Match 'fixture-owner-one|fixture-owner-two|TestResultRedacted' + ($export | ConvertTo-Json -Depth 15) | Should -BeExactly $before + } + + It 'Retains partial owner evidence on Error without leaking identities through error metadata' { + $script:partialError = $true + $script:owners = @(@{ id = 90123456789; login = 'fixture-owner-one' }) + Mock Get-MtUserIdentityReplacementMap -ModuleName Maester { @{} } + $folder = Join-Path $TestDrive 'error' + $script:config.Output = @{ TestResult = @{ Path = (Join-Path $TestDrive 'error.xml'); Format = 'JUnitXml' } } + $result = Invoke-Maester -Config $script:config -TestId CIS.GH.1.2.3 -PassThru -SkipGraphConnect -NonInteractive -DisableTelemetry -SkipVersionCheck -NoLogo -OutputFolder $folder -OutputFolderFileName result -ExportCsv -RedactUserIdentity AllOutputs + $row = $result.Tests | Where-Object Id -EQ 'CIS.GH.1.2.3' + $row.Result | Should -Be 'Error' + $row.ResultDetail.TestResult | Should -Match 'fixture-owner-one' + foreach ($extension in 'json', 'html', 'md', 'csv') { + $content = Get-Content (Join-Path $folder "result.$extension") -Raw + if ($extension -eq 'html') { $content = Get-ReportDataText $content } + $content | Should -Not -Match 'fixture-owner-one|90123456789|GitHubPartialResponse|TestResultRedacted' + $content | Should -Match 'object-[a-f0-9]{16}' + } + (Get-Content (Join-Path $TestDrive 'error.xml') -Raw) | Should -Not -Match 'fixture-owner-one|90123456789' + } + + It 'Applies the generic map once across AllOutputs JSON and HTML' { + Mock Get-MtUserIdentityReplacementMap -ModuleName Maester { @{ 'fixture-org' = 'object-first'; 'object-first' = 'object-second' } } + $folder = Join-Path $TestDrive 'once' + $null = Invoke-Maester -Config $script:config -TestId CIS.GH.1.2.3 -SkipGraphConnect -NonInteractive -DisableTelemetry -SkipVersionCheck -NoLogo -OutputFolder $folder -OutputFolderFileName result -RedactUserIdentity AllOutputs -IncludeAffectedObjects + foreach ($extension in 'json', 'html') { + $content = Get-Content (Join-Path $folder "result.$extension") -Raw + if ($extension -eq 'html') { $content = Get-ReportDataText $content } + $content | Should -Match 'object-first' + $content | Should -Not -Match 'object-second' + } + } + + It 'Redacts unapproved administrator IDs while preserving numeric counts through native exports' { + Mock Get-MtUserIdentityReplacementMap -ModuleName Maester { @{} } + Mock Invoke-WebRequest -ModuleName Maester { + if ($Method -ne 'GET' -or $Headers['X-GitHub-Api-Version'] -ne '2026-03-10') { throw 'Unexpected administrator fixture request.' } + $data = switch (([uri]$Uri).PathAndQuery) { + '/orgs/fixture-org' { @{ id = 100; members_can_delete_issues = $true } } + '/orgs/fixture-org/repos?type=all&per_page=100' { ,@(@{ id = 200; name = 'fixture-repo'; full_name = 'fixture-org/fixture-repo'; owner = @{ login = 'fixture-org' } }) } + '/repos/fixture-org/fixture-repo/collaborators?affiliation=all&per_page=100' { ,@(1..3 | ForEach-Object { @{ id = $_; permissions = @{ admin = $true } } }) } + default { throw 'Unexpected fixture endpoint; network is forbidden.' } + } + [pscustomobject]@{ Content = ConvertTo-Json -InputObject $data -Depth 8 -Compress; Headers = @{} } + } + $script:config.GlobalSettings.GitHubDeletionPolicy.CompleteRepositoryInventory = $true + $script:config.GlobalSettings.GitHubDeletionPolicy.Repositories = @(@{ Id = '200'; ApprovedAdministratorIds = @('1', '2') }) + $folder = Join-Path $TestDrive 'administrators' + $result = Invoke-Maester -Config $script:config -TestId CIS.GH.1.2.4 -PassThru -SkipGraphConnect -NonInteractive -DisableTelemetry -SkipVersionCheck -NoLogo -OutputFolder $folder -OutputFolderFileName result -ExportCsv -RedactUserIdentity AllOutputs + $row = $result.Tests | Where-Object Id -EQ 'CIS.GH.1.2.4' + $row.Result | Should -Be 'Failed' + $row.ResultDetail.TestResult | Should -Match '\| fixture-repo \| 3 \| 1 \| 3 \|' + foreach ($extension in 'json', 'html', 'md', 'csv') { + $content = Get-Content (Join-Path $folder "result.$extension") -Raw + if ($extension -eq 'html') { $content = Get-ReportDataText $content } + $content | Should -Not -Match '\| fixture-repo \| 3 \| 1 \| 3 \||TestResultRedacted' + $content | Should -Match '\| fixture-repo \| 3 \| 1 \| object-[a-f0-9]{16} \|' + } + } + + It 'Exports an executed Passed result without unused approvals in JSON, HTML or verbose output' { + $jsonPath = Join-Path $TestDrive 'executed.json' + $htmlPath = Join-Path $TestDrive 'executed.html' + $captured = @(Invoke-Maester -Config $script:config -TestId CIS.GH.1.2.3 -PassThru -SkipGraphConnect -NonInteractive -DisableTelemetry -SkipVersionCheck -NoLogo -OutputJsonFile $jsonPath -OutputHtmlFile $htmlPath -Verbose 4>&1) + $result = $captured | Where-Object { $_.PSObject.Properties['Tests'] } | Select-Object -Last 1 + ($result.Tests | Where-Object Id -EQ 'CIS.GH.1.2.3').Result | Should -Be 'Passed' + ($captured | Out-String) | Should -Not -Match '9876543210123|synthetic-never-network' + foreach ($path in $jsonPath, $htmlPath) { + $content = Get-Content $path -Raw + if ($path -eq $htmlPath) { $content = Get-ReportDataText $content } + $content | Should -Not -Match '9876543210123|synthetic-never-network' + $content | Should -Match 'GitHubDeletionPolicy' + $content | Should -Match 'redacted' + $content.Contains('fixture-owner-one') | Should -BeTrue + $content.Contains('fixture-owner-two') | Should -BeTrue + } + } +} diff --git a/powershell/tests/functions/RedactedResult.Tests.ps1 b/powershell/tests/functions/RedactedResult.Tests.ps1 new file mode 100644 index 0000000000..bf9e403cd5 --- /dev/null +++ b/powershell/tests/functions/RedactedResult.Tests.ps1 @@ -0,0 +1,215 @@ +BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force + + # Reads the results Get-MtHtmlReport embeds: gzip-compressed, Base64-encoded JSON in the data element. + function Get-ReportDataText([string] $Html) { + $match = [regex]::Match($Html, '') + if (-not $match.Success) { throw 'The report has no compressed maester-report-data element.' } + $stream = [System.IO.MemoryStream]::new([System.Convert]::FromBase64String($match.Groups[1].Value)) + $reader = [System.IO.StreamReader]::new([System.IO.Compression.GZipStream]::new($stream, [System.IO.Compression.CompressionMode]::Decompress)) + try { $reader.ReadToEnd() } finally { $reader.Dispose() } + } +} + +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 'Keeps both complete result variants when Description is explicit' { + Add-MtTestResultDetail -TestName 'fixture' -Description 'Explicit guide' -Result 'Raw body' -RedactedResult 'Safe body' + $detail = InModuleScope Maester { $__MtSession.TestResultDetail.fixture } + $detail.TestDescription | Should -Be 'Explicit guide' + $detail.TestResult | Should -Be 'Raw body' + $detail.TestResultRedacted | Should -Be 'Safe body' + Should -Invoke Get-MtTestResultTemplate -ModuleName Maester -Times 0 -Exactly + } + 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: