diff --git a/powershell/Maester.psm1 b/powershell/Maester.psm1 index f5b0d45188..4f8d9fc31a 100644 --- a/powershell/Maester.psm1 +++ b/powershell/Maester.psm1 @@ -30,6 +30,7 @@ $__MtSession = @{ DataverseResourceUrl = $null # Dataverse resource URL for token acquisition (e.g. https://org123.crm.dynamics.com) DataverseEnvironmentId = $null # Environment identifier for display (e.g. org123.crm.dynamics.com) SpoCache = @{} # Cache for SharePoint Online tenant settings retrieved via PnP + GitHubRateLimits = $null # Connection/host cooldowns; preserved across Invoke-Maester runs FabricCache = @{} # Fabric admin API data cached for the current test run GitHubCache = @{} # Per-session REST response cache; cleared each Invoke-Maester run ADCache = @{} # Active Directory data cache diff --git a/powershell/assets/MaesterSettings.psd1 b/powershell/assets/MaesterSettings.psd1 index 5d45e7d347..878a95388e 100644 --- a/powershell/assets/MaesterSettings.psd1 +++ b/powershell/assets/MaesterSettings.psd1 @@ -10,6 +10,10 @@ AzureDevOpsOrganization = @{ Type = 'string'; Default = ''; Sensitive = $false; Description = 'Azure DevOps organization that Connect-Maester -Service AzureDevOps connects to.' } GitHubOrganization = @{ Type = 'string'; Default = ''; Sensitive = $false; Description = 'GitHub organization that the GitHub checks read.' } GitHubApiBaseUri = @{ Type = 'string'; Default = 'https://api.github.com'; Sensitive = $false; Description = 'Base URI of the GitHub REST API.' } + GitHubDeletionPolicy = @{ Type = 'object'; Default = @{}; Sensitive = $true; Description = 'Host and organization-bound approved owner and repository administrator IDs for GitHub deletion assessments.' } GitHubApiVersion = @{ Type = 'string'; Default = '2022-11-28'; Sensitive = $false; Description = 'GitHub REST API version.' } + GitHubAccountModel = @{ Type = 'string'; AllowedValues = @('Unknown', 'PersonalAccounts', 'EnterpriseManagedUsers'); Default = 'Unknown'; Sensitive = $false; Description = 'GitHub identity model: Unknown, PersonalAccounts, or EnterpriseManagedUsers.' } + GitHubEnterprise = @{ Type = 'string'; Default = ''; Sensitive = $true; Description = 'Explicit enterprise slug for GitHub CIS enterprise-dependent assessments.' } + GitHubCisRepositoryScope = @{ Type = 'object'; Default = @{}; Sensitive = $true; Description = 'Complete organization repository applicability inventory and control-specific branch declarations for GitHub CIS checks.' } } } diff --git a/powershell/assets/MaesterTaxonomy.psd1 b/powershell/assets/MaesterTaxonomy.psd1 index 1c0373c93f..25b6e85d06 100644 --- a/powershell/assets/MaesterTaxonomy.psd1 +++ b/powershell/assets/MaesterTaxonomy.psd1 @@ -188,6 +188,8 @@ Aliases = @('GitHub') Features = @( @{ Key = 'organization-settings'; Name = 'Organization settings' } + @{ Key = 'branch-protection'; Name = 'Branch protection' } + @{ Key = 'enterprise-settings'; Name = 'Enterprise settings' } ) } @{ 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-MtCisGitHubRepositoryScope.ps1 b/powershell/internal/checks/cis/github/Resolve-MtCisGitHubRepositoryScope.ps1 new file mode 100644 index 0000000000..1a0e234430 --- /dev/null +++ b/powershell/internal/checks/cis/github/Resolve-MtCisGitHubRepositoryScope.ps1 @@ -0,0 +1,57 @@ +function Resolve-MtCisGitHubRepositoryScope { + <# + .SYNOPSIS + Internal: Reconciles explicit CIS applicability with the complete readable organization inventory. + .DESCRIPTION + Validates only classifications the selected control needs. The declaration is not proof of permission completeness. + #> + [CmdletBinding()] + param([Parameter(Mandatory)] [string] $Control) + $provided = $__MtSession.MaesterConfig.GlobalSettings.PSObject.Properties['GitHubCisRepositoryScope'] + if ($provided -and $null -ne $provided.Value -and $provided.Value.GetType() -ne [System.Management.Automation.PSCustomObject]) { throw 'GitHubCisRepositoryScope must be a configuration object.' } + $scope = Get-MtSetting -Name GitHubCisRepositoryScope -Verbose:$false + $issues = [System.Collections.Generic.List[string]]::new() + $repositories = [System.Collections.Generic.List[object]]::new() + if ($null -eq $scope -or ($scope -is [System.Collections.IDictionary] -and $scope.Count -eq 0) -or ($scope -is [pscustomobject] -and @($scope.PSObject.Properties).Count -eq 0)) { + return [pscustomobject]@{ Repositories = @(); Issues = @('Configure a complete GitHubCisRepositoryScope applicability declaration.'); ExcludedCount = 0; Exclusions = @(); StartedUtc = $null; CompletedUtc = $null } + } + if (($null -eq $scope -or $scope.GetType() -ne [System.Management.Automation.PSCustomObject])) { throw 'GitHubCisRepositoryScope must be a configuration object.' } + $organization = $__MtSession.GitHubConnection.Organization + if ($scope.Organization -isnot [string] -or $scope.Organization -ne $organization) { throw 'GitHubCisRepositoryScope.Organization must match the connected organization.' } + if ($scope.Complete -isnot [bool]) { throw 'GitHubCisRepositoryScope.Complete must be Boolean.' } + if (-not $scope.Complete) { $issues.Add('The assessor has not declared this repository scope complete.') } + if ($scope.Repositories -isnot [array]) { throw 'GitHubCisRepositoryScope.Repositories must be an array.' } + $inventory = Get-MtGitHubRepositoryInventory + foreach ($issue in $inventory.Issues) { $issues.Add($issue) } + $byId = @{} + foreach ($item in $inventory.Repositories) { $byId[[string]$item.id] = $item } + $seen = [System.Collections.Generic.HashSet[string]]::new() + $excluded = 0 + $exclusions = [System.Collections.Generic.List[object]]::new() + foreach ($entry in $scope.Repositories) { + if (($null -eq $entry -or $entry.GetType() -ne [System.Management.Automation.PSCustomObject]) -or ($entry.Id -isnot [int] -and $entry.Id -isnot [long] -and $entry.Id -isnot [bigint]) -or $entry.Id -le 0 -or $entry.InUse -isnot [bool]) { throw 'Every scope repository needs a numeric positive Id and Boolean InUse.' } + $id = [string]$entry.Id + if (-not $seen.Add($id)) { throw 'GitHubCisRepositoryScope contains a duplicate repository Id.' } + if (-not $byId.ContainsKey($id)) { $issues.Add('A declared repository is missing or inaccessible in the live inventory.'); continue } + if (-not $entry.InUse) { + if ($entry.ExclusionReason -isnot [string] -or [string]::IsNullOrWhiteSpace($entry.ExclusionReason)) { throw 'Every excluded repository needs an ExclusionReason.' } + $exclusions.Add([pscustomobject]@{ Repository = $byId[$id].full_name; Reason = $entry.ExclusionReason }) + $excluded++; continue + } + $branches = [System.Collections.Generic.List[string]]::new() + foreach ($field in @($(if ($Control -ne '1.1.12') { 'MainBranches' }), $(if ($Control -eq '1.1.16') { 'LongStandingBranches' }))) { + if (-not $field) { continue } + if (-not (Test-MtGitHubObjectProperty -InputObject $entry -PropertyName $field)) { $issues.Add("A required $field declaration is missing."); continue } + if ($entry.$field -isnot [array]) { throw "GitHubCisRepositoryScope.$field must be an array." } + if ($field -eq 'MainBranches' -and $entry.$field.Count -eq 0) { $issues.Add('An in-use repository has no main-branch classification.') } + foreach ($branch in $entry.$field) { + if ($branch -isnot [string] -or [string]::IsNullOrWhiteSpace($branch)) { throw "GitHubCisRepositoryScope.$field must contain nonempty branch-name strings." } + if (-not $branches.Contains($branch)) { $branches.Add($branch) } + } + } + $repositories.Add([pscustomobject]@{ Repository = $byId[$id]; Branches = $branches.ToArray() }) + } + foreach ($id in $byId.Keys) { if (-not $seen.Contains($id)) { $issues.Add('A live repository has no applicability classification.') } } + if ($inventory.Repositories.Count -eq 0) { $issues.Add('Empty repository inventory does not establish complete visibility or non-applicability.') } + return [pscustomobject]@{ Repositories = $repositories.ToArray(); Issues = $issues.ToArray(); ExcludedCount = $excluded; Exclusions = $exclusions.ToArray(); StartedUtc = $inventory.StartedUtc; CompletedUtc = $inventory.CompletedUtc } +} 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-MtCisGitHubBranchEvidence.ps1 b/powershell/internal/checks/cis/github/Test-MtCisGitHubBranchEvidence.ps1 new file mode 100644 index 0000000000..4654fdc2cb --- /dev/null +++ b/powershell/internal/checks/cis/github/Test-MtCisGitHubBranchEvidence.ps1 @@ -0,0 +1,181 @@ +function Test-MtCisGitHubBranchEvidence { + <# + .SYNOPSIS + Internal: Evaluates one CIS GitHub classic-configuration audit over its explicit population. + .DESCRIPTION + Evidence dependencies are lazy. Error takes precedence over Failed, then indeterminate. Rulesets receive no equivalence credit. + #> + [CmdletBinding()] + param([Parameter(Mandatory)] [ValidateSet('1.1.4', '1.1.7', '1.1.9', '1.1.10', '1.1.11', '1.1.12', '1.1.14', '1.1.16', '1.1.17', '1.1.20')] [string] $Control) + $rows = [System.Collections.Generic.List[object]]::new() + $issues = [System.Collections.Generic.List[string]]::new() + $kind = if ($Control -eq '1.1.12') { 'Signatures' } elseif ($Control -in '1.1.9', '1.1.10') { 'StatusChecks' } else { 'Protection' } + $knownRuleTypes = @('creation', 'update', 'deletion', 'required_linear_history', 'merge_queue', 'required_deployments', 'required_signatures', 'pull_request', 'required_status_checks', 'non_fast_forward', 'commit_message_pattern', 'commit_author_email_pattern', 'committer_email_pattern', 'branch_name_pattern', 'tag_name_pattern', 'workflows', 'code_scanning', 'code_quality', 'code_coverage', 'copilot_code_review', 'license_compliance_scanning', 'file_path_restriction', 'max_file_path_length', 'file_extension_restriction', 'max_file_size') + $candidateTypes = switch ($Control) { + { $_ -in '1.1.4', '1.1.7', '1.1.11' } { @('pull_request', 'update') } + '1.1.12' { @('required_signatures', 'update') } + '1.1.16' { @('non_fast_forward', 'update') } + '1.1.17' { @('deletion') } + default { $knownRuleTypes } + } + try { $scope = Resolve-MtCisGitHubRepositoryScope -Control $Control } catch { + $message = if ($_.Exception.Message -match '^(GitHubCisRepositoryScope|Every scope|Every excluded)') { $_.Exception.Message } else { 'Required repository inventory collection or parsing failed.' } + return [pscustomobject]@{ Verdict = 'Error'; Detail = $message } + } + foreach ($issue in $scope.Issues) { $issues.Add($issue) } + :repositories foreach ($entry in $scope.Repositories) { + $repository = $entry.Repository + $branches = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::Ordinal) + foreach ($branch in $entry.Branches) { $null = $branches.Add($branch) } + try { + if ($Control -eq '1.1.12') { + $population = Get-MtGitHubBranchEvidence -Repository $repository -Kind Branches + if ($population.State -ne 'Available') { $issues.Add('Existing-branch enumeration contains incomplete or unusable evidence.') } + foreach ($branch in $population.Data) { + if (($null -eq $branch -or $branch.GetType() -ne [System.Management.Automation.PSCustomObject]) -or $branch.name -isnot [string] -or [string]::IsNullOrWhiteSpace($branch.name)) { $issues.Add('A branch item has no usable identity.'); continue } + if (-not $branches.Add($branch.name)) { $issues.Add('Existing-branch enumeration contains a duplicate name.') } + } + if ($branches.Count -eq 0) { $issues.Add('An in-use repository returned no existing branches; applicability is unresolved.') } + } + if ($Control -eq '1.1.20') { + $current = Get-MtGitHubBranchEvidence -Repository $repository -Kind Repository + if ($current.State -ne 'Available' -or ($current.Data.id -isnot [int] -and $current.Data.id -isnot [long]) -or $current.Data.id -ne $repository.id -or $current.Data.default_branch -isnot [string] -or [string]::IsNullOrWhiteSpace($current.Data.default_branch)) { + $issues.Add('The actual default branch could not be established.') + } else { $null = $branches.Add($current.Data.default_branch) } + } + } catch { + $rows.Add([pscustomobject]@{ Repository = $repository.full_name; Branch = '(population)'; Verdict = 'Error'; Reason = 'Required population request failed.'; StartedUtc = $null; CompletedUtc = $null }) + if ($_.Exception.Data['GitHubRateLimit']) { $issues.Add('Collection stopped for rate limiting; remaining objects were not assessed.'); break repositories } + continue + } + foreach ($branch in $branches) { + $verdict = 'Indeterminate' + $reason = 'Required policy evidence is absent or unusable.' + $evidence = $null + $rateLimited = $false + try { + $evidence = Get-MtGitHubBranchEvidence -Repository $repository -Branch $branch -Kind $kind + $policy = $evidence.Data + $conforming = $null + $readStatusRule = $false + if ($evidence.State -eq 'Available') { + switch ($Control) { + '1.1.4' { if (($null -ne $policy.required_pull_request_reviews -and $policy.required_pull_request_reviews.GetType() -eq [System.Management.Automation.PSCustomObject]) -and $policy.required_pull_request_reviews.dismiss_stale_reviews -is [bool]) { $conforming = $policy.required_pull_request_reviews.dismiss_stale_reviews; $reason = "dismiss_stale_reviews=$conforming" } } + '1.1.7' { if (($null -ne $policy.required_pull_request_reviews -and $policy.required_pull_request_reviews.GetType() -eq [System.Management.Automation.PSCustomObject]) -and $policy.required_pull_request_reviews.require_code_owner_reviews -is [bool]) { $conforming = $policy.required_pull_request_reviews.require_code_owner_reviews; $reason = "require_code_owner_reviews=$conforming" } } + { $_ -in '1.1.9', '1.1.10' } { + $usable = $policy.contexts -is [array] -and $policy.checks -is [array] + foreach ($context in $policy.contexts) { if ($context -isnot [string] -or [string]::IsNullOrWhiteSpace($context)) { $usable = $false } } + foreach ($check in $policy.checks) { + if (($null -eq $check -or $check.GetType() -ne [System.Management.Automation.PSCustomObject]) -or $check.context -isnot [string] -or [string]::IsNullOrWhiteSpace($check.context) -or -not (Test-MtGitHubObjectProperty -InputObject $check -PropertyName app_id) -or ($null -ne $check.app_id -and $check.app_id -isnot [int] -and $check.app_id -isnot [long])) { $usable = $false } + } + if ($Control -eq '1.1.10' -and $policy.strict -isnot [bool]) { $usable = $false } + if ($usable) { + $hasChecks = ($policy.contexts.Count + $policy.checks.Count) -gt 0 + $reason = "Required contexts=$($policy.contexts.Count); checks=$($policy.checks.Count)" + if ($Control -eq '1.1.10') { $reason += "; strict=$($policy.strict)" } + if (-not $hasChecks) { $reason += '; no predefined checks were returned.' } + if ($Control -eq '1.1.10' -and -not $policy.strict) { $conforming = $false } + elseif ($hasChecks) { $conforming = $true } + else { $readStatusRule = $true } + } + } + '1.1.11' { if ($null -ne $policy.required_conversation_resolution -and $policy.required_conversation_resolution.GetType() -eq [System.Management.Automation.PSCustomObject] -and $policy.required_conversation_resolution.enabled -is [bool]) { $conforming = $policy.required_conversation_resolution.enabled; $reason = "required_conversation_resolution.enabled=$conforming" } } + '1.1.12' { if ($policy.enabled -is [bool]) { $conforming = $policy.enabled; $reason = "required_signatures.enabled=$conforming" } } + '1.1.14' { if ($null -ne $policy.enforce_admins -and $policy.enforce_admins.GetType() -eq [System.Management.Automation.PSCustomObject] -and $policy.enforce_admins.enabled -is [bool]) { $conforming = $policy.enforce_admins.enabled; $reason = "enforce_admins.enabled=$conforming" } } + '1.1.16' { if ($null -ne $policy.allow_force_pushes -and $policy.allow_force_pushes.GetType() -eq [System.Management.Automation.PSCustomObject] -and $policy.allow_force_pushes.enabled -is [bool]) { $conforming = -not $policy.allow_force_pushes.enabled; $reason = "allow_force_pushes.enabled=$($policy.allow_force_pushes.enabled)" } } + '1.1.17' { if ($null -ne $policy.allow_deletions -and $policy.allow_deletions.GetType() -eq [System.Management.Automation.PSCustomObject] -and $policy.allow_deletions.enabled -is [bool]) { $conforming = -not $policy.allow_deletions.enabled; $reason = "allow_deletions.enabled=$($policy.allow_deletions.enabled)" } } + '1.1.20' { + $expected = "$($__MtSession.GitHubConnection.ApiBaseUri)/repos/$([uri]::EscapeDataString($repository.owner.login))/$([uri]::EscapeDataString($repository.name))/branches/$([uri]::EscapeDataString($branch))/protection" + $actualUri = $null + $expectedUri = [uri]$expected + if ($policy.url -is [string] -and [uri]::TryCreate($policy.url, [UriKind]::Absolute, [ref]$actualUri) -and + $actualUri.Scheme -eq $expectedUri.Scheme -and $actualUri.Host -eq $expectedUri.Host -and $actualUri.Port -eq $expectedUri.Port -and + [uri]::UnescapeDataString($actualUri.AbsolutePath) -ceq [uri]::UnescapeDataString($expectedUri.AbsolutePath) -and + [string]::IsNullOrEmpty($actualUri.Query) -and [string]::IsNullOrEmpty($actualUri.Fragment) -and [string]::IsNullOrEmpty($actualUri.UserInfo)) { + $conforming = $true; $reason = 'An applicable classic branch protection object was returned.' + } + } + } + } + if ($evidence.State -eq 'NotFoundOrNotVisible') { + $state = Get-MtGitHubBranchEvidence -Repository $repository -Branch $branch -Kind Branch + $reason = 'HTTP 404 is ambiguous or protection may be supplied by rulesets.' + if ($state.State -eq 'Available' -and $state.Data.name -ceq $branch -and $state.Data.protected -is [bool]) { + if (-not $state.Data.protected) { + $verdict = 'Failed' + $reason = 'An accessible existing branch is unprotected.' + } elseif ($kind -eq 'StatusChecks') { $readStatusRule = $true } + } + } + if ($readStatusRule) { + $evidence = Get-MtGitHubBranchEvidence -Repository $repository -Branch $branch -Kind StatusCheckRule + $rule = $evidence.Data + if ($evidence.State -ne 'Available' -or $rule.requiresStatusChecks -isnot [bool] -or + ($Control -eq '1.1.10' -and $rule.requiresStrictStatusChecks -isnot [bool])) { + $reason += ' The status settings on the matching classic rule are unavailable.' + } elseif ($Control -eq '1.1.10' -and $policy.strict -is [bool] -and $policy.strict -ne $rule.requiresStrictStatusChecks) { + $reason += ' REST and GraphQL disagree about strict status checks.' + } else { + $conforming = $rule.requiresStatusChecks + $reason += " requiresStatusChecks=$conforming" + if ($Control -eq '1.1.10') { + $conforming = $conforming -and $rule.requiresStrictStatusChecks + $reason += "; requiresStrictStatusChecks=$($rule.requiresStrictStatusChecks)" + } + } + } + if ($null -ne $conforming) { + if ($conforming) { $verdict = 'Passed' } + elseif ($kind -eq 'StatusChecks') { $verdict = 'Failed' } + else { + $rules = Get-MtGitHubBranchEvidence -Repository $repository -Branch $branch -Kind Rules + $potential = $rules.State -ne 'Available' + foreach ($rule in $rules.Data) { + if ($rule.type -isnot [string] -or $rule.type -cnotin $knownRuleTypes -or $rule.type -cin $candidateTypes) { $potential = $true } + } + if ($potential) { $reason += '; alternative ruleset enforcement is unresolved.' } + else { $verdict = 'Failed' } + } + } + } catch { + $verdict = 'Error'; $reason = 'A required GitHub evidence request or JSON parse failed.' + $rateLimited = $null -ne $_.Exception.Data['GitHubRateLimit'] + } + $rows.Add([pscustomobject]@{ Repository = $repository.full_name; Branch = $branch; Verdict = $verdict; Reason = $reason; StartedUtc = $evidence.StartedUtc; CompletedUtc = $evidence.CompletedUtc }) + if ($rateLimited) { $issues.Add('Collection stopped for rate limiting; remaining objects were not assessed.'); break repositories } + } + } + $verdict = if (@($rows | Where-Object Verdict -EQ 'Error').Count) { 'Error' } + elseif (@($rows | Where-Object Verdict -EQ 'Failed').Count) { 'Failed' } + elseif ($issues.Count -gt 0 -or @($rows | Where-Object Verdict -EQ 'Indeterminate').Count) { 'Indeterminate' } + elseif ($rows.Count -eq 0) { 'NotApplicable' } else { 'Passed' } + $summary = switch ($verdict) { + Passed { 'Well done. The CIS configuration audit is satisfied for the complete declared applicable population.' } + Failed { 'Correct the nonconforming branch settings listed below. Any coverage gaps remain unresolved.' } + Error { 'A required evidence operation failed. Retained findings do not establish a complete assessment.' } + NotApplicable { 'No applicable repositories remain after complete applicability reconciliation.' } + default { 'Indeterminate: complete usable evidence for this configuration audit is unavailable.' } + } + $target = [System.Net.WebUtility]::HtmlEncode([string]$__MtSession.GitHubConnection.Organization).Replace('|', '|').Replace('`', '`') -replace '[\r\n]', ' ' + if ($target.Length -gt 160) { $target = $target.Substring(0, 160) } + $detail = "$summary`n`nCIS.GH.$Control; organization ``$target`` at ``$($__MtSession.GitHubConnection.ApiBaseUri)``. Excluded repositories: $($scope.ExcludedCount).`n`nRepository inventory observed UTC: $($scope.StartedUtc) through $($scope.CompletedUtc).`n`n| Repository | Branch | Finding | Evidence | UTC interval |`n| --- | --- | --- | --- | --- |`n" + # Encode untrusted identifiers and cap presentation without dropping any finding from evaluation. + $rank = @{ Error = 0; Failed = 1; Indeterminate = 2; Passed = 3 } + foreach ($row in @($rows | Sort-Object { $rank[$_.Verdict] } | Select-Object -First 100)) { + $repoText = [System.Net.WebUtility]::HtmlEncode([string]$row.Repository).Replace('|', '|').Replace('`', '`').Replace("`n", ' ').Replace("`r", ' ') + $branchText = [System.Net.WebUtility]::HtmlEncode([string]$row.Branch).Replace('|', '|').Replace('`', '`').Replace("`n", ' ').Replace("`r", ' ') + if ($repoText.Length -gt 160) { $repoText = $repoText.Substring(0, 160) } + if ($branchText.Length -gt 160) { $branchText = $branchText.Substring(0, 160) } + # Escape Markdown after capping the display text so truncation cannot split an escape. + $detail += "| $(Get-MtSafeMarkdown $repoText) | $(Get-MtSafeMarkdown $branchText) | $($row.Verdict) | $($row.Reason) | $($row.StartedUtc) - $($row.CompletedUtc) |`n" + } + foreach ($state in 'Passed', 'Failed', 'Indeterminate', 'Error') { $detail += "`n$state findings: $(@($rows | Where-Object Verdict -EQ $state).Count)." } + $detail += "`nEvaluated branch findings: $($rows.Count); displayed: $([Math]::Min(100, $rows.Count)). This is the named configuration audit, not proof of historical merges or enforcement against every actor. Bypass lists are not required to be empty.`n" + foreach ($exclusion in @($scope.Exclusions | Select-Object -First 20)) { + $exclusionText = [System.Net.WebUtility]::HtmlEncode("$($exclusion.Repository): $($exclusion.Reason)").Replace('|', '|').Replace('`', '`') -replace '[\r\n]', ' ' + if ($exclusionText.Length -gt 300) { $exclusionText = $exclusionText.Substring(0, 300) } + $detail += "`nExcluded by applicability declaration: $exclusionText`n" + } + if ($issues.Count) { $detail += "`nCoverage: " + (($issues | Select-Object -Unique | Select-Object -First 20) -join ' ') } + return [pscustomobject]@{ Verdict = $verdict; Detail = $detail } +} 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/checks/cis/github/Test-MtCisGitHubEnterprise.ps1 b/powershell/internal/checks/cis/github/Test-MtCisGitHubEnterprise.ps1 new file mode 100644 index 0000000000..34fcb2e302 --- /dev/null +++ b/powershell/internal/checks/cis/github/Test-MtCisGitHubEnterprise.ps1 @@ -0,0 +1,56 @@ +function Test-MtCisGitHubEnterprise { + <# + .SYNOPSIS + Internal: Assesses the CIS enterprise notification setting or positive organization association. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] [ValidateSet('Notification', 'Association')] [string] $Purpose, + [string] $OrganizationId, + [string] $OrganizationLogin + ) + $provided = $__MtSession.MaesterConfig.GlobalSettings.PSObject.Properties['GitHubEnterprise'] + if ($provided -and $null -ne $provided.Value -and $provided.Value -isnot [string]) { throw 'GitHubEnterprise must be an enterprise slug string.' } + $slug = Get-MtSetting -Name GitHubEnterprise -Verbose:$false + if ($null -ne $slug -and $slug -isnot [string]) { throw 'GitHubEnterprise must be an enterprise slug string.' } + if ([string]::IsNullOrWhiteSpace($slug)) { return [pscustomobject]@{ Verdict = 'Indeterminate'; Detail = 'Indeterminate: configure the explicit GitHubEnterprise target.' } } + $hostUri = $__MtSession.GitHubConnection.ApiBaseUri + $displaySlug = [System.Net.WebUtility]::HtmlEncode($slug).Replace('|', '|').Replace('`', '`') -replace '[\r\n]', ' ' + if ($displaySlug.Length -gt 160) { $displaySlug = $displaySlug.Substring(0, 160) } + if ($Purpose -eq 'Notification') { + $evidence = Get-MtGitHubEnterprise -Slug $slug -Purpose Notification + $enterprise = $evidence.Data.enterprise + $value = $enterprise.ownerInfo.notificationDeliveryRestrictionEnabledSetting + $identityValid = $null -ne $enterprise -and $enterprise.GetType() -eq [System.Management.Automation.PSCustomObject] -and $null -ne $enterprise.ownerInfo -and $enterprise.ownerInfo.GetType() -eq [System.Management.Automation.PSCustomObject] -and $enterprise.id -is [string] -and -not [string]::IsNullOrWhiteSpace($enterprise.id) -and $enterprise.slug -is [string] -and $enterprise.slug -eq $slug + $verdict = if ($evidence.Errors.Count -gt 0 -or -not $identityValid -or $value -isnot [string] -or $value -cnotin 'ENABLED', 'DISABLED') { 'Indeterminate' } elseif ($value -ceq 'ENABLED') { 'Passed' } else { 'Failed' } + $summary = switch ($verdict) { + Passed { 'Well done. The selected enterprise restricts notification delivery to approved or verified domains.' } + Failed { 'Enable notification restrictions for the selected enterprise.' } + default { 'Indeterminate: the selected enterprise identity or owner-only notification field is unavailable or unusable.' } + } + $displayId = [System.Net.WebUtility]::HtmlEncode([string]$enterprise.id).Replace('|', '|').Replace('`', '`') -replace '[\r\n]', ' ' + if ($displayId.Length -gt 160) { $displayId = $displayId.Substring(0, 160) } + $displayValue = if ($value -is [string] -and $value -cin 'ENABLED', 'DISABLED') { $value } else { 'unavailable' } + $detail = "$summary`n`nAssessment target: enterprise ``$displaySlug`` at ``$hostUri``; returned enterprise ID: ``$displayId``.`n`nNotification setting: ``$displayValue``.`n`nObserved UTC: $($evidence.StartedUtc.ToString('o')) through $($evidence.CompletedUtc.ToString('o')).`n`nThis is an independently targeted enterprise-setting audit. Organization ownership and per-message delivery are not assessed. Organization restrictions can disable when no eligible domains remain." + return [pscustomobject]@{ Verdict = $verdict; Detail = $detail } + } + if ([string]::IsNullOrWhiteSpace($OrganizationId) -or [string]::IsNullOrWhiteSpace($OrganizationLogin)) { throw 'Association requires an organization identity.' } + $cursor = $null + $visited = [System.Collections.Generic.HashSet[string]]::new() + do { + $evidence = Get-MtGitHubEnterprise -Slug $slug -Purpose Association -OrganizationLogin $OrganizationLogin -After $cursor + $enterprise = $evidence.Data.enterprise + $connection = $enterprise.organizations + if ($evidence.Errors.Count -gt 0 -or $null -eq $enterprise -or $enterprise.GetType() -ne [System.Management.Automation.PSCustomObject] -or $null -eq $connection -or $connection.GetType() -ne [System.Management.Automation.PSCustomObject] -or $connection.nodes -isnot [array] -or $enterprise.slug -isnot [string] -or $enterprise.slug -ne $slug -or $enterprise.id -isnot [string] -or [string]::IsNullOrWhiteSpace($enterprise.id)) { break } + foreach ($organization in $connection.nodes) { + if ($null -ne $organization -and $organization.GetType() -eq [System.Management.Automation.PSCustomObject] -and $organization.id -is [string] -and $organization.id -ceq $OrganizationId -and $organization.login -is [string] -and $organization.login -eq $OrganizationLogin) { + return [pscustomobject]@{ Verdict = 'Passed'; Detail = "Positive association with enterprise ``$displaySlug`` established by organization node ID. Association observed UTC: $($evidence.StartedUtc.ToString('o')) through $($evidence.CompletedUtc.ToString('o'))." } + } + } + if ($connection.pageInfo.hasNextPage -isnot [bool] -or -not $connection.pageInfo.hasNextPage) { break } + $cursor = $connection.pageInfo.endCursor + if ($cursor -isnot [string] -or [string]::IsNullOrWhiteSpace($cursor)) { break } + if (-not $visited.Add($cursor)) { throw 'GitHub enterprise association pagination cycle detected.' } + } while ($true) + return [pscustomobject]@{ Verdict = 'Indeterminate'; Detail = 'Indeterminate: a positive association with the selected enterprise could not be established. Absence from visible results is not proof of non-applicability.' } +} diff --git a/powershell/internal/checks/cis/github/Test-MtCisGitHubOrganizationVerification.ps1 b/powershell/internal/checks/cis/github/Test-MtCisGitHubOrganizationVerification.ps1 new file mode 100644 index 0000000000..3f7dd3738c --- /dev/null +++ b/powershell/internal/checks/cis/github/Test-MtCisGitHubOrganizationVerification.ps1 @@ -0,0 +1,30 @@ +function Test-MtCisGitHubOrganizationVerification { + <# + .SYNOPSIS + Internal: Assesses CIS organization profile verification with positive enterprise applicability evidence. + #> + [CmdletBinding()] + param() + $login = $__MtSession.GitHubConnection.Organization + $provided = $__MtSession.MaesterConfig.GlobalSettings.PSObject.Properties['GitHubOrganization'] + if ($provided -and $provided.Value -isnot [string]) { throw 'GitHubOrganization must be a string.' } + $configured = Get-MtSetting -Name GitHubOrganization -Verbose:$false + if ($configured -isnot [string] -or (-not [string]::IsNullOrWhiteSpace($configured) -and $configured -ne $login)) { throw 'GitHubOrganization must match the connected organization.' } + $enterpriseSetting = $__MtSession.MaesterConfig.GlobalSettings.PSObject.Properties['GitHubEnterprise'] + if ($enterpriseSetting -and $null -ne $enterpriseSetting.Value -and $enterpriseSetting.Value -isnot [string]) { throw 'GitHubEnterprise must be an enterprise slug string.' } + if ([string]::IsNullOrWhiteSpace((Get-MtSetting -Name GitHubEnterprise -Verbose:$false))) { return [pscustomobject]@{ Verdict = 'Indeterminate'; Detail = 'Indeterminate: configure the explicit GitHubEnterprise applicability context.' } } + $evidence = Get-MtGitHubOrganizationVerification -Login $login + $organization = $evidence.Data.organization + if ($evidence.Errors.Count -gt 0 -or $null -eq $organization -or $organization.GetType() -ne [System.Management.Automation.PSCustomObject] -or $organization.id -isnot [string] -or [string]::IsNullOrWhiteSpace($organization.id) -or $organization.login -isnot [string] -or $organization.login -ne $login -or $organization.isVerified -isnot [bool]) { + return [pscustomobject]@{ Verdict = 'Indeterminate'; Detail = 'Indeterminate: organization profile verification evidence is unavailable or unusable.' } + } + $association = Test-MtCisGitHubEnterprise -Purpose Association -OrganizationId $organization.id -OrganizationLogin $login + if ($association.Verdict -ne 'Passed') { return $association } + $displayLogin = [System.Net.WebUtility]::HtmlEncode([string]$login).Replace('|', '|').Replace('`', '`') -replace '[\r\n]', ' ' + if ($displayLogin.Length -gt 160) { $displayLogin = $displayLogin.Substring(0, 160) } + $summary = if ($organization.isVerified) { 'Well done. The organization has verified its profile email and website.' } else { 'Verify the organization profile domains to obtain its Verified badge.' } + return [pscustomobject]@{ + Verdict = $(if ($organization.isVerified) { 'Passed' } else { 'Failed' }) + Detail = "$summary`n`nOrganization: ``$displayLogin`` at ``$($__MtSession.GitHubConnection.ApiBaseUri)``. isVerified: ``$($organization.isVerified)``.`n`n$($association.Detail)`n`nProfile observed UTC: $($evidence.StartedUtc.ToString('o')) through $($evidence.CompletedUtc.ToString('o')). Only this organization is assessed; no enterprise-wide coverage is claimed." + } +} diff --git a/powershell/internal/report/ConvertTo-MtMaesterResult.ps1 b/powershell/internal/report/ConvertTo-MtMaesterResult.ps1 index 343a43cab0..1c453ec878 100644 --- a/powershell/internal/report/ConvertTo-MtMaesterResult.ps1 +++ b/powershell/internal/report/ConvertTo-MtMaesterResult.ps1 @@ -710,10 +710,23 @@ function New-MtResultConfig { ) if ($null -eq $RunConfig) { return $null } - if ($NativeRows.Count -eq 0) { return $RunConfig } + # Configuration is JSON-shaped, as normalized by Resolve-MtRunConfig. Detach every nested value + # before redaction so reporting cannot change caller input or settings still used by checks. + $detached = $RunConfig | ConvertTo-Json -Depth 100 | ConvertFrom-Json -NoEnumerate + if (-not $script:__MtSettingsRegistry) { + $script:__MtSettingsRegistry = Import-PowerShellDataFile -Path (Join-Path $ExecutionContext.SessionState.Module.ModuleBase 'assets/MaesterSettings.psd1') + } + if ($detached.PSObject.Properties['GlobalSettings'] -and $null -ne $detached.GlobalSettings) { + foreach ($key in $script:__MtSettingsRegistry.Settings.Keys) { + if ($script:__MtSettingsRegistry.Settings[$key].Sensitive -and $detached.GlobalSettings.PSObject.Properties[$key]) { + $detached.GlobalSettings.$key = '' + } + } + } + if ($NativeRows.Count -eq 0) { return $detached } $copy = [pscustomobject]@{} - foreach ($p in $RunConfig.PSObject.Properties) { + foreach ($p in $detached.PSObject.Properties) { if ($p.Name -in 'TestSettings', 'TestSettingsHash') { continue } $copy | Add-Member -NotePropertyName $p.Name -NotePropertyValue $p.Value } @@ -723,7 +736,7 @@ function New-MtResultConfig { $entry = [ordered]@{ Id = $row.Id; Title = $row.Title; Severity = $row.Severity } $default = if ($row.ParentId -and $catalog.ContainsKey($row.ParentId)) { $catalog[$row.ParentId].Severity } elseif ($catalog.ContainsKey($row.Id)) { $catalog[$row.Id].Severity } else { $null } if ($default) { $entry.DefaultSeverity = $default } - $user = if ($RunConfig.TestSettingsHash -and $RunConfig.TestSettingsHash.ContainsKey($row.Id)) { $RunConfig.TestSettingsHash[$row.Id] } else { $null } + $user = if ($detached.TestSettingsHash) { $detached.TestSettingsHash.PSObject.Properties[$row.Id].Value } else { $null } if ($user) { foreach ($p in $user.PSObject.Properties) { if ($p.Name -notin 'Id', 'Title', 'Severity') { $entry[$p.Name] = $p.Value } } } diff --git a/powershell/internal/report/ConvertTo-MtRedactedResult.ps1 b/powershell/internal/report/ConvertTo-MtRedactedResult.ps1 new file mode 100644 index 0000000000..7be8cba1f2 --- /dev/null +++ b/powershell/internal/report/ConvertTo-MtRedactedResult.ps1 @@ -0,0 +1,61 @@ +function ConvertTo-MtRedactedResult { + <# + .SYNOPSIS + Copies results and prepares result Markdown before export. + + .DESCRIPTION + Handles single-tenant and merged results without changing the caller's objects. + The optional alternative covers TestResult only. Other fields retain the existing + best-effort identity replacement behavior. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] [psobject] $MaesterResults, + [hashtable] $ReplacementMap = @{}, + [switch] $KeepUserIdentity + ) + + $copyObject = { + param($Object) + $copy = [ordered]@{} + if ($Object -is [System.Collections.IDictionary]) { + foreach ($key in $Object.Keys) { $copy[$key] = $Object[$key] } + } else { + foreach ($property in $Object.PSObject.Properties) { $copy[$property.Name] = $property.Value } + } + $copy + } + $prepare = { + param($Source) + $copy = & $copyObject $Source + if ($null -ne $copy.Tests) { + $copy.Tests = @(foreach ($sourceTest in $copy.Tests) { + $test = & $copyObject $sourceTest + if ($null -ne $test.ResultDetail) { + $detail = & $copyObject $test.ResultDetail + if ($detail.Contains('TestResultRedacted')) { + # Imported alternatives are optional; unusable values use generic redaction. + if (-not $KeepUserIdentity -and $detail.TestResultRedacted -is [string] -and -not [string]::IsNullOrWhiteSpace($detail.TestResultRedacted)) { + $detail.TestResult = $detail.TestResultRedacted + } + $detail.Remove('TestResultRedacted') + } + $test.ResultDetail = [pscustomobject]$detail + } + [pscustomobject]$test + }) + } + if ($null -ne $copy.Tenants) { + $copy.Tenants = @(foreach ($tenant in $copy.Tenants) { & $prepare $tenant }) + } + [pscustomobject]$copy + } + $prepared = & $prepare $MaesterResults + if (-not $KeepUserIdentity -and $ReplacementMap.Count -gt 0) { + # Preserve the existing generic replacement for fields outside scoped result Markdown. + $depth = if ($prepared.PSObject.Properties['Tenants']) { 7 } else { 5 } + return $prepared | ConvertTo-Json -Depth $depth -WarningAction SilentlyContinue | + ConvertTo-MtRedactedReportContent -ReplacementMap $ReplacementMap -JsonEncoded | ConvertFrom-Json + } + return $prepared +} diff --git a/powershell/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-MtGitHubBranchEvidence.ps1 b/powershell/internal/services/github/Get-MtGitHubBranchEvidence.ps1 new file mode 100644 index 0000000000..a464bd1494 --- /dev/null +++ b/powershell/internal/services/github/Get-MtGitHubBranchEvidence.ps1 @@ -0,0 +1,61 @@ +function Get-MtGitHubBranchEvidence { + <# + .SYNOPSIS + Internal: Reads one independently usable branch evidence dependency. + .DESCRIPTION + Only policy/branch 404 responses are contextualized. Other transport failures propagate to the selected check. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] [object] $Repository, + [Parameter(Mandatory)] [ValidateSet('Protection', 'StatusChecks', 'StatusCheckRule', 'Signatures', 'Branch', 'Rules', 'Repository', 'Branches')] [string] $Kind, + [string] $Branch + ) + if ($Kind -eq 'StatusCheckRule') { + $query = 'query MaesterCisStatusRule($owner:String!,$name:String!,$ref:String!){repository(owner:$owner,name:$name){id ref(qualifiedName:$ref){name prefix branchProtectionRule{requiresStatusChecks requiresStrictStatusChecks}}}}' + $variables = @{ owner = $Repository.owner.login; name = $Repository.name; ref = "refs/heads/$Branch" } + $response = Invoke-MtGitHubGraphQLRequest -Query $query -Variables $variables -OperationName MaesterCisStatusRule + $repo = $response.Data.repository + $ref = $repo.ref + $rule = $ref.branchProtectionRule + $matched = $response.Errors.Count -eq 0 -and $null -ne $repo -and $repo.GetType() -eq [System.Management.Automation.PSCustomObject] -and + $repo.id -is [string] -and -not [string]::IsNullOrWhiteSpace($repo.id) -and $repo.id -ceq $Repository.node_id -and + $null -ne $ref -and $ref.GetType() -eq [System.Management.Automation.PSCustomObject] -and + $ref.name -is [string] -and $ref.name -ceq $Branch -and $ref.prefix -is [string] -and $ref.prefix -ceq 'refs/heads/' -and + $null -ne $rule -and $rule.GetType() -eq [System.Management.Automation.PSCustomObject] + return [pscustomobject]@{ + State = $(if ($matched) { 'Available' } else { 'Indeterminate' }) + Data = $rule; StartedUtc = $response.StartedUtc; CompletedUtc = $response.CompletedUtc + } + } + $owner = [uri]::EscapeDataString($Repository.owner.login) + $name = [uri]::EscapeDataString($Repository.name) + $prefix = "/repos/$owner/$name" + $encodedBranch = [uri]::EscapeDataString($Branch) + $path = switch ($Kind) { + Protection { "$prefix/branches/$encodedBranch/protection" } + StatusChecks { "$prefix/branches/$encodedBranch/protection/required_status_checks" } + Signatures { "$prefix/branches/$encodedBranch/protection/required_signatures" } + Branch { "$prefix/branches/$encodedBranch" } + Rules { "$prefix/rules/branches/$encodedBranch" } + Repository { $prefix } + Branches { "$prefix/branches" } + } + try { + $evidence = Invoke-MtGitHubRequest -RelativeUri $path -Paginate:($Kind -in 'Rules', 'Branches') -ApiVersion '2026-03-10' -IncludeMetadata + } catch { + if ($Kind -in 'Protection', 'StatusChecks', 'Signatures', 'Branch' -and $_.Exception.Response -and [int]$_.Exception.Response.StatusCode -eq 404) { + return [pscustomobject]@{ State = 'NotFoundOrNotVisible'; Data = $null; Detail = 'HTTP 404 does not distinguish absent policy, changed branch, or unavailable access.'; StartedUtc = $null; CompletedUtc = $null } + } + throw + } + $valid = $evidence.CollectionIntegrityValid -and -not $evidence.AccessLimited + if ($Kind -in 'Rules', 'Branches') { $valid = $valid -and $evidence.PaginationComplete } else { $valid = $valid -and $evidence.ContentKind -eq 'Object' } + return [pscustomobject]@{ + State = $(if ($valid) { 'Available' } else { 'Indeterminate' }) + Data = $evidence.Data + Detail = $evidence.Issues -join ' ' + StartedUtc = $evidence.StartedUtc + CompletedUtc = $evidence.CompletedUtc + } +} diff --git a/powershell/internal/services/github/Get-MtGitHubEnterprise.ps1 b/powershell/internal/services/github/Get-MtGitHubEnterprise.ps1 new file mode 100644 index 0000000000..a28722b324 --- /dev/null +++ b/powershell/internal/services/github/Get-MtGitHubEnterprise.ps1 @@ -0,0 +1,24 @@ +function Get-MtGitHubEnterprise { + <# + .SYNOPSIS + Internal: Reads enterprise notification settings or one page of matching organizations. + .DESCRIPTION + Returns the GraphQL evidence envelope through the session cache. The caller supplies + the enterprise slug and handles applicability, pagination and assessment. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] [string] $Slug, + [Parameter(Mandatory)] [ValidateSet('Notification', 'Association')] [string] $Purpose, + [string] $OrganizationLogin, + [AllowNull()] [object] $After = $null + ) + + if ($Purpose -eq 'Notification') { + $query = 'query MaesterCisNotifications($slug:String!){enterprise(slug:$slug){id slug ownerInfo{notificationDeliveryRestrictionEnabledSetting}}}' + return Invoke-MtGitHubGraphQLRequest -Query $query -Variables @{ slug = $Slug } -OperationName MaesterCisNotifications + } + + $query = 'query MaesterCisAssociation($slug:String!,$login:String!,$after:String){enterprise(slug:$slug){id slug organizations(first:100,query:$login,after:$after){nodes{id login} pageInfo{hasNextPage endCursor}}}}' + return Invoke-MtGitHubGraphQLRequest -Query $query -Variables @{ slug = $Slug; login = $OrganizationLogin; after = $After } -OperationName MaesterCisAssociation +} 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-MtGitHubOrganization.ps1 b/powershell/internal/services/github/Get-MtGitHubOrganization.ps1 index fcbaa2e0d0..4fd5a1c2b9 100644 --- a/powershell/internal/services/github/Get-MtGitHubOrganization.ps1 +++ b/powershell/internal/services/github/Get-MtGitHubOrganization.ps1 @@ -4,7 +4,10 @@ Internal: Gets the connected GitHub organization object using the session cache. #> [CmdletBinding()] - param() + param( + [string] $ApiVersion, + [switch] $IncludeMetadata + ) if ($null -eq $__MtSession.GitHubConnection -or $__MtSession.GitHubConnection.Connected -ne $true) { @@ -13,5 +16,8 @@ # Connect-MtGitHub stores the raw organization login; encode it here for the path segment. $encodedOrg = [System.Uri]::EscapeDataString($__MtSession.GitHubConnection.Organization) - Invoke-MtGitHubRequest -RelativeUri "/orgs/$encodedOrg" + $options = @{} + if ($ApiVersion) { $options.ApiVersion = $ApiVersion } + if ($IncludeMetadata) { $options.IncludeMetadata = $true } + Invoke-MtGitHubRequest -RelativeUri "/orgs/$encodedOrg" @options } diff --git a/powershell/internal/services/github/Get-MtGitHubOrganizationVerification.ps1 b/powershell/internal/services/github/Get-MtGitHubOrganizationVerification.ps1 new file mode 100644 index 0000000000..caadb9588d --- /dev/null +++ b/powershell/internal/services/github/Get-MtGitHubOrganizationVerification.ps1 @@ -0,0 +1,16 @@ +function Get-MtGitHubOrganizationVerification { + <# + .SYNOPSIS + Internal: Reads organization identity and profile verification evidence. + .DESCRIPTION + Returns the GraphQL evidence envelope through the session cache. The caller supplies + the organization login and handles applicability and assessment. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] [string] $Login + ) + + $query = 'query MaesterCisVerification($login:String!){organization(login:$login){id login isVerified}}' + return Invoke-MtGitHubGraphQLRequest -Query $query -Variables @{ login = $Login } -OperationName MaesterCisVerification +} 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/connect/Connect-MtGitHub.ps1 b/powershell/public/connect/Connect-MtGitHub.ps1 index 1a428bc90c..80ad41dc42 100644 --- a/powershell/public/connect/Connect-MtGitHub.ps1 +++ b/powershell/public/connect/Connect-MtGitHub.ps1 @@ -6,9 +6,13 @@ .DESCRIPTION Establishes a GitHub Enterprise Cloud organization REST API session for Maester CIS benchmark tests. This is an organization-scoped session, not a full enterprise-admin - session: enterprise-admin endpoints under /enterprises/{enterprise} are not verified - by this command and would require a future enterprise-access probe if CIS controls - need them. + session. Connection success does not establish complete repository visibility or + enterprise access. New GitHub CIS assessments use explicit GitHubAccountModel, + GitHubEnterprise and GitHubCisRepositoryScope run settings where relevant. Enterprise + checks validate their own required readable evidence without changing this command's + authentication flow; notification results identify the independently selected enterprise. + New collectors explicitly request REST 2026-03-10 while this connection's default + remains 2022-11-28. See the GitHub CIS configuration guide on maester.dev. If no explicit token is provided, Maester signs in with the Maester CLI GitHub App using GitHub device flow. If the app is not installed or approved for the requested 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 fa65675ee3..77959be1c5 100644 --- a/powershell/public/run/Invoke-Maester.ps1 +++ b/powershell/public/run/Invoke-Maester.ps1 @@ -1058,12 +1058,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' @@ -1080,55 +1075,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 } @@ -1144,6 +1127,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/fixtures/golden/selection.json b/powershell/tests/fixtures/golden/selection.json index ae970e7cfd..b7cf4e2571 100644 --- a/powershell/tests/fixtures/golden/selection.json +++ b/powershell/tests/fixtures/golden/selection.json @@ -21,7 +21,7 @@ "AD" ] }, - "SelectedCount": 582, + "SelectedCount": 596, "SelectedFamilies": [ "MT.1024", "MT.1059", @@ -87,11 +87,25 @@ "AZDO.1042", "AZDO.1043", "AZDO.1044", + "CIS.GH.1.1.10", + "CIS.GH.1.1.11", + "CIS.GH.1.1.12", + "CIS.GH.1.1.14", + "CIS.GH.1.1.16", + "CIS.GH.1.1.17", + "CIS.GH.1.1.20", + "CIS.GH.1.1.4", + "CIS.GH.1.1.7", + "CIS.GH.1.1.9", "CIS.GH.1.2.2", "CIS.GH.1.2.3", "CIS.GH.1.2.4", + "CIS.GH.1.3.10", "CIS.GH.1.3.2", + "CIS.GH.1.3.4", + "CIS.GH.1.3.5", "CIS.GH.1.3.8", + "CIS.GH.1.3.9", "CIS.M365.1.1.1", "CIS.M365.1.1.3", "CIS.M365.1.1.4", @@ -771,7 +785,7 @@ "AD" ] }, - "SelectedCount": 538, + "SelectedCount": 552, "SelectedFamilies": [ "MT.1024", "MT.1059", @@ -837,11 +851,25 @@ "AZDO.1042", "AZDO.1043", "AZDO.1044", + "CIS.GH.1.1.10", + "CIS.GH.1.1.11", + "CIS.GH.1.1.12", + "CIS.GH.1.1.14", + "CIS.GH.1.1.16", + "CIS.GH.1.1.17", + "CIS.GH.1.1.20", + "CIS.GH.1.1.4", + "CIS.GH.1.1.7", + "CIS.GH.1.1.9", "CIS.GH.1.2.2", "CIS.GH.1.2.3", "CIS.GH.1.2.4", + "CIS.GH.1.3.10", "CIS.GH.1.3.2", + "CIS.GH.1.3.4", + "CIS.GH.1.3.5", "CIS.GH.1.3.8", + "CIS.GH.1.3.9", "CIS.M365.1.1.1", "CIS.M365.1.1.3", "CIS.M365.1.1.4", @@ -1330,7 +1358,7 @@ "AD" ] }, - "SelectedCount": 598, + "SelectedCount": 612, "SelectedFamilies": [ "MT.1024", "MT.1033", @@ -1398,11 +1426,25 @@ "AZDO.1042", "AZDO.1043", "AZDO.1044", + "CIS.GH.1.1.10", + "CIS.GH.1.1.11", + "CIS.GH.1.1.12", + "CIS.GH.1.1.14", + "CIS.GH.1.1.16", + "CIS.GH.1.1.17", + "CIS.GH.1.1.20", + "CIS.GH.1.1.4", + "CIS.GH.1.1.7", + "CIS.GH.1.1.9", "CIS.GH.1.2.2", "CIS.GH.1.2.3", "CIS.GH.1.2.4", + "CIS.GH.1.3.10", "CIS.GH.1.3.2", + "CIS.GH.1.3.4", + "CIS.GH.1.3.5", "CIS.GH.1.3.8", + "CIS.GH.1.3.9", "CIS.M365.1.1.1", "CIS.M365.1.1.3", "CIS.M365.1.1.4", @@ -1951,7 +1993,7 @@ "AD" ] }, - "SelectedCount": 609, + "SelectedCount": 623, "SelectedFamilies": [ "MT.1024", "MT.1059", @@ -2018,11 +2060,25 @@ "AZDO.1043", "AZDO.1044", "AZDO.1045", + "CIS.GH.1.1.10", + "CIS.GH.1.1.11", + "CIS.GH.1.1.12", + "CIS.GH.1.1.14", + "CIS.GH.1.1.16", + "CIS.GH.1.1.17", + "CIS.GH.1.1.20", + "CIS.GH.1.1.4", + "CIS.GH.1.1.7", + "CIS.GH.1.1.9", "CIS.GH.1.2.2", "CIS.GH.1.2.3", "CIS.GH.1.2.4", + "CIS.GH.1.3.10", "CIS.GH.1.3.2", + "CIS.GH.1.3.4", + "CIS.GH.1.3.5", "CIS.GH.1.3.8", + "CIS.GH.1.3.9", "CIS.M365.1.1.1", "CIS.M365.1.1.3", "CIS.M365.1.1.4", @@ -2581,7 +2637,7 @@ "AD" ] }, - "SelectedCount": 639, + "SelectedCount": 653, "SelectedFamilies": [ "MT.1024", "MT.1033", @@ -2650,11 +2706,25 @@ "AZDO.1043", "AZDO.1044", "AZDO.1045", + "CIS.GH.1.1.10", + "CIS.GH.1.1.11", + "CIS.GH.1.1.12", + "CIS.GH.1.1.14", + "CIS.GH.1.1.16", + "CIS.GH.1.1.17", + "CIS.GH.1.1.20", + "CIS.GH.1.1.4", + "CIS.GH.1.1.7", + "CIS.GH.1.1.9", "CIS.GH.1.2.2", "CIS.GH.1.2.3", "CIS.GH.1.2.4", + "CIS.GH.1.3.10", "CIS.GH.1.3.2", + "CIS.GH.1.3.4", + "CIS.GH.1.3.5", "CIS.GH.1.3.8", + "CIS.GH.1.3.9", "CIS.M365.1.1.1", "CIS.M365.1.1.3", "CIS.M365.1.1.4", @@ -3441,7 +3511,7 @@ "AD" ] }, - "SelectedCount": 538, + "SelectedCount": 552, "SelectedFamilies": [ "MT.1024", "MT.1059", @@ -3507,11 +3577,25 @@ "AZDO.1042", "AZDO.1043", "AZDO.1044", + "CIS.GH.1.1.10", + "CIS.GH.1.1.11", + "CIS.GH.1.1.12", + "CIS.GH.1.1.14", + "CIS.GH.1.1.16", + "CIS.GH.1.1.17", + "CIS.GH.1.1.20", + "CIS.GH.1.1.4", + "CIS.GH.1.1.7", + "CIS.GH.1.1.9", "CIS.GH.1.2.2", "CIS.GH.1.2.3", "CIS.GH.1.2.4", + "CIS.GH.1.3.10", "CIS.GH.1.3.2", + "CIS.GH.1.3.4", + "CIS.GH.1.3.5", "CIS.GH.1.3.8", + "CIS.GH.1.3.9", "CIS.M365.1.1.1", "CIS.M365.1.1.3", "CIS.M365.1.1.4", @@ -4006,7 +4090,7 @@ "AD" ] }, - "SelectedCount": 595, + "SelectedCount": 609, "SelectedFamilies": [ "MT.1024", "MT.1033", @@ -4075,11 +4159,25 @@ "AZDO.1043", "AZDO.1044", "AZDO.1045", + "CIS.GH.1.1.10", + "CIS.GH.1.1.11", + "CIS.GH.1.1.12", + "CIS.GH.1.1.14", + "CIS.GH.1.1.16", + "CIS.GH.1.1.17", + "CIS.GH.1.1.20", + "CIS.GH.1.1.4", + "CIS.GH.1.1.7", + "CIS.GH.1.1.9", "CIS.GH.1.2.2", "CIS.GH.1.2.3", "CIS.GH.1.2.4", + "CIS.GH.1.3.10", "CIS.GH.1.3.2", + "CIS.GH.1.3.4", + "CIS.GH.1.3.5", "CIS.GH.1.3.8", + "CIS.GH.1.3.9", "CIS.M365.1.1.1", "CIS.M365.1.1.3", "CIS.M365.1.1.4", 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/GitHubRateLimit.Tests.ps1 b/powershell/tests/functions/GitHubRateLimit.Tests.ps1 index 9d4cdd9b3e..65dd10d686 100644 --- a/powershell/tests/functions/GitHubRateLimit.Tests.ps1 +++ b/powershell/tests/functions/GitHubRateLimit.Tests.ps1 @@ -2,7 +2,7 @@ Import-Module "$PSScriptRoot/../../Maester.psd1" -Force } -Describe 'GitHub shared transport rate-limit boundaries' { +Describe 'GitHub rate limits through transport and native checks' { BeforeEach { $script:policyCalls = 0 $script:limitStatus = 429 @@ -39,6 +39,38 @@ Describe 'GitHub shared transport rate-limit boundaries' { InModuleScope Maester { $__MtSession.GitHubConnection = $null; $__MtSession.GitHubAuthHeader = $null; $__MtSession.GitHubCache = @{}; $__MtSession.MaesterConfig = $null } } + It 'Stops traffic across branches, repositories and two native checks for ' -ForEach @( + @{ Kind = '429 Retry-After'; Status = 429; Primary = $false } + @{ Kind = '403 primary exhaustion'; Status = 403; Primary = $true } + ) { + $script:limitStatus = $Status + if ($Primary) { $script:limitHeaders = @{ 'x-ratelimit-remaining' = '0'; 'x-ratelimit-reset' = [DateTimeOffset]::UtcNow.AddMinutes(10).ToUnixTimeSeconds(); 'x-ratelimit-resource' = 'core' }; $script:limitBody = '{"message":"API rate limit exceeded"}' } + $rows = @(Invoke-MtTest -Id 'CIS.GH.1.1.4', 'CIS.GH.1.1.7' -Config $script:scopeConfig) + $rows.Count | Should -Be 2 + @($rows | Where-Object Result -NE 'Error').Count | Should -Be 0 + $script:policyCalls | Should -Be 1 + Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 2 + } + + It 'Stops native branch-population enumeration and subsequent checks after rate limiting' { + $rows = @(Invoke-MtTest -Id 'CIS.GH.1.1.12', 'CIS.GH.1.1.4' -Config $script:scopeConfig) + $rows.Count | Should -Be 2 + @($rows | Where-Object Result -NE 'Error').Count | Should -Be 0 + $script:policyCalls | Should -Be 1 + Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 2 + Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 0 -ParameterFilter { $Uri -match '/protection' } + } + + It 'Retains completed branch findings and does not count unvisited branches as evaluated' { + $script:successfulPolicies = 1 + $row = Invoke-MtTest -Id 'CIS.GH.1.1.4' -Config $script:scopeConfig + $row.Result | Should -Be 'Error' + $row.ResultDetail.TestResult | Should -Match 'Passed findings: 1' + $row.ResultDetail.TestResult | Should -Match 'Evaluated branch findings: 2;' + $row.ResultDetail.TestResult | Should -Match 'not assessed' + $script:policyCalls | Should -Be 2 + } + It 'Preserves structured retry metadata, blocks DisableCache and expires without waiting' { InModuleScope Maester { $caught = $null @@ -58,6 +90,15 @@ Describe 'GitHub shared transport rate-limit boundaries' { Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 2 } + It 'Keeps ordinary permission 403 separate and continues other objects' { + $script:limitStatus = 403 + $script:limitHeaders = @{} + $script:limitBody = '{"message":"Resource not accessible by integration"}' + $rows = @(Invoke-MtTest -Id 'CIS.GH.1.1.4', 'CIS.GH.1.1.7' -Config $script:scopeConfig) + @($rows | Where-Object Result -NE 'Error').Count | Should -Be 0 + $script:policyCalls | Should -Be 202 + } + It 'Shares secondary limits with GraphQL while preserving separate primary quotas' -ForEach @(@{ Primary = $true }, @{ Primary = $false }) { if ($Primary) { $script:limitStatus = 403; $script:limitHeaders = @{ 'x-ratelimit-remaining' = '0'; 'x-ratelimit-reset' = [DateTimeOffset]::UtcNow.AddMinutes(10).ToUnixTimeSeconds() }; $script:limitBody = '{"message":"API rate limit exceeded"}' } InModuleScope Maester -Parameters @{ Primary = $Primary } { @@ -180,6 +221,19 @@ Describe 'GraphQL and bootstrap rate-limit boundaries' { Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times $(if ($Primary) { 2 } else { 1 }) } + It 'Retains successful GraphQL data at primary exhaustion and stops the next association cursor' { + Mock Invoke-WebRequest -ModuleName Maester { + [pscustomobject]@{ Content = '{"data":{"enterprise":{"id":"E_fixture","slug":"fixture-enterprise","organizations":{"nodes":[],"pageInfo":{"hasNextPage":true,"endCursor":"next"}}}}}'; Headers = @{ 'x-ratelimit-remaining' = '0'; 'x-ratelimit-reset' = [DateTimeOffset]::UtcNow.AddMinutes(10).ToUnixTimeSeconds() } } + } + InModuleScope Maester { + $__MtSession.MaesterConfig = [pscustomobject]@{ GlobalSettings = [pscustomobject]@{ GitHubEnterprise = 'fixture-enterprise' } } + { Test-MtCisGitHubEnterprise -Purpose Association -OrganizationId O_fixture -OrganizationLogin fixture-org } | Should -Throw '*rate limit*' + $__MtSession.GitHubCache.Count | Should -Be 1 + @($__MtSession.GitHubCache.Values)[0].Data.enterprise.id | Should -Be 'E_fixture' + } + Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 1 + } + It 'Shares an HTTP secondary limit received by GraphQL with REST' { Mock Invoke-WebRequest -ModuleName Maester { $response = [System.Net.Http.HttpResponseMessage]::new([System.Net.HttpStatusCode]::TooManyRequests) 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: