From d8c84299f0eeccf618ccc5328d2e17440a046bda Mon Sep 17 00:00:00 2001 From: Travis McDade Date: Sat, 24 Oct 2026 14:20:06 -0400 Subject: [PATCH 01/23] feat(github): add remaining direct CIS GitHub v1.2.0 checks Add fourteen native assessments with explicit evidence and scope contracts, control-specific collection, and transport-to-native-result regressions. Preserve the original five GitHub checks and update framework inventories, selection fixtures, and configuration guidance for nineteen valid IDs. Depends on #2525; inherited baseline: 403ff4064a1a1ffae401929ccf62a8fe6f7ae11d --- powershell/assets/MaesterSettings.psd1 | 3 + powershell/assets/MaesterTaxonomy.psd1 | 2 + .../github/Get-MtCisGitHubBranchEvidence.ps1 | 44 +++ .../Resolve-MtCisGitHubRepositoryScope.ps1 | 57 ++++ .../github/Test-MtCisGitHubBranchEvidence.ps1 | 153 +++++++++ .../github/Get-MtGitHubEnterprise.ps1 | 58 ++++ .../github/Get-MtGitHubOrganization.ps1 | 10 +- .../Get-MtGitHubOrganizationVerification.ps1 | 31 ++ .../Get-MtGitHubRepositoryInventory.ps1 | 26 ++ .../github/Invoke-MtGitHubGraphQLRequest.ps1 | 48 +++ .../github/Invoke-MtGitHubRequest.ps1 | 103 +++++- .../public/connect/Connect-MtGitHub.ps1 | 10 +- .../tests/fixtures/golden/selection.json | 112 ++++++- .../Invoke-MtGitHubGraphQLRequest.Tests.ps1 | 122 +++++++ .../Invoke-MtGitHubRequest.Tests.ps1 | 138 ++++++++ .../Test-MtCisGitHubAuthentication.Tests.ps1 | 93 +++++ .../Test-MtCisGitHubBranchSettings.Tests.ps1 | 317 ++++++++++++++++++ ...st-MtCisGitHubEnterpriseSettings.Tests.ps1 | 128 +++++++ ...-MtCisGitHubOrganizationSettings.Tests.ps1 | 12 +- .../functions/engine/Frameworks.Tests.ps1 | 6 +- tests/cis/Test.CIS.GH.1.1.10.md | 52 +++ tests/cis/Test.CIS.GH.1.1.10.ps1 | 52 +++ tests/cis/Test.CIS.GH.1.1.11.md | 52 +++ tests/cis/Test.CIS.GH.1.1.11.ps1 | 52 +++ tests/cis/Test.CIS.GH.1.1.12.md | 52 +++ tests/cis/Test.CIS.GH.1.1.12.ps1 | 52 +++ tests/cis/Test.CIS.GH.1.1.14.md | 52 +++ tests/cis/Test.CIS.GH.1.1.14.ps1 | 52 +++ tests/cis/Test.CIS.GH.1.1.16.md | 52 +++ tests/cis/Test.CIS.GH.1.1.16.ps1 | 52 +++ tests/cis/Test.CIS.GH.1.1.17.md | 52 +++ tests/cis/Test.CIS.GH.1.1.17.ps1 | 52 +++ tests/cis/Test.CIS.GH.1.1.20.md | 52 +++ tests/cis/Test.CIS.GH.1.1.20.ps1 | 52 +++ tests/cis/Test.CIS.GH.1.1.4.md | 50 +++ tests/cis/Test.CIS.GH.1.1.4.ps1 | 52 +++ tests/cis/Test.CIS.GH.1.1.7.md | 52 +++ tests/cis/Test.CIS.GH.1.1.7.ps1 | 52 +++ tests/cis/Test.CIS.GH.1.1.9.md | 52 +++ tests/cis/Test.CIS.GH.1.1.9.ps1 | 52 +++ tests/cis/Test.CIS.GH.1.3.10.md | 45 +++ tests/cis/Test.CIS.GH.1.3.10.ps1 | 52 +++ tests/cis/Test.CIS.GH.1.3.4.md | 43 +++ tests/cis/Test.CIS.GH.1.3.4.ps1 | 103 ++++++ tests/cis/Test.CIS.GH.1.3.5.md | 43 +++ tests/cis/Test.CIS.GH.1.3.5.ps1 | 103 ++++++ tests/cis/Test.CIS.GH.1.3.9.md | 43 +++ tests/cis/Test.CIS.GH.1.3.9.ps1 | 52 +++ tests/cis/frameworks/cis-github.json | 24 +- website/docs/configuration/github-cis.md | 187 +++++++++++ .../docs/configuration/run-configuration.md | 3 + website/src/data/test-builder.json | 106 ++++++ 52 files changed, 3288 insertions(+), 27 deletions(-) create mode 100644 powershell/internal/checks/cis/github/Get-MtCisGitHubBranchEvidence.ps1 create mode 100644 powershell/internal/checks/cis/github/Resolve-MtCisGitHubRepositoryScope.ps1 create mode 100644 powershell/internal/checks/cis/github/Test-MtCisGitHubBranchEvidence.ps1 create mode 100644 powershell/internal/services/github/Get-MtGitHubEnterprise.ps1 create mode 100644 powershell/internal/services/github/Get-MtGitHubOrganizationVerification.ps1 create mode 100644 powershell/internal/services/github/Get-MtGitHubRepositoryInventory.ps1 create mode 100644 powershell/internal/services/github/Invoke-MtGitHubGraphQLRequest.ps1 create mode 100644 powershell/tests/functions/Invoke-MtGitHubGraphQLRequest.Tests.ps1 create mode 100644 powershell/tests/functions/Test-MtCisGitHubAuthentication.Tests.ps1 create mode 100644 powershell/tests/functions/Test-MtCisGitHubBranchSettings.Tests.ps1 create mode 100644 powershell/tests/functions/Test-MtCisGitHubEnterpriseSettings.Tests.ps1 create mode 100644 tests/cis/Test.CIS.GH.1.1.10.md create mode 100644 tests/cis/Test.CIS.GH.1.1.10.ps1 create mode 100644 tests/cis/Test.CIS.GH.1.1.11.md create mode 100644 tests/cis/Test.CIS.GH.1.1.11.ps1 create mode 100644 tests/cis/Test.CIS.GH.1.1.12.md create mode 100644 tests/cis/Test.CIS.GH.1.1.12.ps1 create mode 100644 tests/cis/Test.CIS.GH.1.1.14.md create mode 100644 tests/cis/Test.CIS.GH.1.1.14.ps1 create mode 100644 tests/cis/Test.CIS.GH.1.1.16.md create mode 100644 tests/cis/Test.CIS.GH.1.1.16.ps1 create mode 100644 tests/cis/Test.CIS.GH.1.1.17.md create mode 100644 tests/cis/Test.CIS.GH.1.1.17.ps1 create mode 100644 tests/cis/Test.CIS.GH.1.1.20.md create mode 100644 tests/cis/Test.CIS.GH.1.1.20.ps1 create mode 100644 tests/cis/Test.CIS.GH.1.1.4.md create mode 100644 tests/cis/Test.CIS.GH.1.1.4.ps1 create mode 100644 tests/cis/Test.CIS.GH.1.1.7.md create mode 100644 tests/cis/Test.CIS.GH.1.1.7.ps1 create mode 100644 tests/cis/Test.CIS.GH.1.1.9.md create mode 100644 tests/cis/Test.CIS.GH.1.1.9.ps1 create mode 100644 tests/cis/Test.CIS.GH.1.3.10.md create mode 100644 tests/cis/Test.CIS.GH.1.3.10.ps1 create mode 100644 tests/cis/Test.CIS.GH.1.3.4.md create mode 100644 tests/cis/Test.CIS.GH.1.3.4.ps1 create mode 100644 tests/cis/Test.CIS.GH.1.3.5.md create mode 100644 tests/cis/Test.CIS.GH.1.3.5.ps1 create mode 100644 tests/cis/Test.CIS.GH.1.3.9.md create mode 100644 tests/cis/Test.CIS.GH.1.3.9.ps1 create mode 100644 website/docs/configuration/github-cis.md diff --git a/powershell/assets/MaesterSettings.psd1 b/powershell/assets/MaesterSettings.psd1 index 48f21d5a73..dc0f12a41d 100644 --- a/powershell/assets/MaesterSettings.psd1 +++ b/powershell/assets/MaesterSettings.psd1 @@ -10,5 +10,8 @@ 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.' } GitHubApiVersion = @{ Type = 'string'; Default = '2022-11-28'; Sensitive = $false; Description = 'GitHub REST API version.' } + GitHubAccountModel = @{ Type = 'string'; 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 485f866384..ee8fdb62e1 100644 --- a/powershell/assets/MaesterTaxonomy.psd1 +++ b/powershell/assets/MaesterTaxonomy.psd1 @@ -172,6 +172,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-MtCisGitHubBranchEvidence.ps1 b/powershell/internal/checks/cis/github/Get-MtCisGitHubBranchEvidence.ps1 new file mode 100644 index 0000000000..017d6e78a5 --- /dev/null +++ b/powershell/internal/checks/cis/github/Get-MtCisGitHubBranchEvidence.ps1 @@ -0,0 +1,44 @@ +function Get-MtCisGitHubBranchEvidence { + <# + .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', 'Signatures', 'Branch', 'Rules', 'Repository', 'Branches')] [string] $Kind, + [string] $Branch + ) + $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/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/Test-MtCisGitHubBranchEvidence.ps1 b/powershell/internal/checks/cis/github/Test-MtCisGitHubBranchEvidence.ps1 new file mode 100644 index 0000000000..216b5c99f8 --- /dev/null +++ b/powershell/internal/checks/cis/github/Test-MtCisGitHubBranchEvidence.ps1 @@ -0,0 +1,153 @@ +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') } + { $_ -in '1.1.9', '1.1.10' } { @('required_status_checks', 'workflows', 'merge_queue', '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) } + 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-MtCisGitHubBranchEvidence -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-MtCisGitHubBranchEvidence -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 }) + continue + } + foreach ($branch in $branches) { + $verdict = 'Indeterminate' + $reason = 'Required policy evidence is absent or unusable.' + $evidence = $null + try { + $evidence = Get-MtCisGitHubBranchEvidence -Repository $repository -Branch $branch -Kind $kind + $policy = $evidence.Data + $conforming = $null + 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) { + $conforming = ($policy.contexts.Count + $policy.checks.Count) -gt 0 + if ($Control -eq '1.1.10') { $conforming = $conforming -and $policy.strict } + $reason = "Required contexts=$($policy.contexts.Count); checks=$($policy.checks.Count)" + if ($Control -eq '1.1.10') { $reason += "; strict=$($policy.strict)" } + } + } + '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 ($null -ne $conforming -and $conforming) { + $verdict = 'Passed' + } elseif ($null -ne $conforming -or $evidence.State -eq 'NotFoundOrNotVisible') { + $absent = $false + if ($evidence.State -eq 'NotFoundOrNotVisible') { + $state = Get-MtCisGitHubBranchEvidence -Repository $repository -Branch $branch -Kind Branch + if ($state.State -eq 'Available' -and $state.Data.name -ceq $branch -and $state.Data.protected -is [bool] -and -not $state.Data.protected) { $absent = $true } + else { $reason = 'HTTP 404 is ambiguous or protection may be supplied by rulesets.' } + } + if ($absent) { $verdict = 'Failed'; $reason = 'An accessible existing branch is unprotected.' } + elseif ($null -ne $conforming) { + $rules = Get-MtCisGitHubBranchEvidence -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.' + } + $rows.Add([pscustomobject]@{ Repository = $repository.full_name; Branch = $branch; Verdict = $verdict; Reason = $reason; StartedUtc = $evidence.StartedUtc; CompletedUtc = $evidence.CompletedUtc }) + } + } + $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) } + $detail += "| $repoText | $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/services/github/Get-MtGitHubEnterprise.ps1 b/powershell/internal/services/github/Get-MtGitHubEnterprise.ps1 new file mode 100644 index 0000000000..18929f80aa --- /dev/null +++ b/powershell/internal/services/github/Get-MtGitHubEnterprise.ps1 @@ -0,0 +1,58 @@ +function Get-MtGitHubEnterprise { + <# + .SYNOPSIS + Internal: Reads the explicitly targeted enterprise notification policy or a 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') { + $query = 'query MaesterCisNotifications($slug:String!){enterprise(slug:$slug){id slug ownerInfo{notificationDeliveryRestrictionEnabledSetting}}}' + $evidence = Invoke-MtGitHubGraphQLRequest -Query $query -Variables @{ slug = $slug } -OperationName MaesterCisNotifications + $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.' } + $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}}}}' + $cursor = $null + $visited = [System.Collections.Generic.HashSet[string]]::new() + do { + $evidence = Invoke-MtGitHubGraphQLRequest -Query $query -Variables @{ slug = $slug; login = $OrganizationLogin; after = $cursor } -OperationName MaesterCisAssociation + $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/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..2869516c96 --- /dev/null +++ b/powershell/internal/services/github/Get-MtGitHubOrganizationVerification.ps1 @@ -0,0 +1,31 @@ +function Get-MtGitHubOrganizationVerification { + <# + .SYNOPSIS + Internal: Reads 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.' } } + $query = 'query MaesterCisVerification($login:String!){organization(login:$login){id login isVerified}}' + $evidence = Invoke-MtGitHubGraphQLRequest -Query $query -Variables @{ login = $login } -OperationName MaesterCisVerification + $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 = Get-MtGitHubEnterprise -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/services/github/Get-MtGitHubRepositoryInventory.ps1 b/powershell/internal/services/github/Get-MtGitHubRepositoryInventory.ps1 new file mode 100644 index 0000000000..d9785a0b33 --- /dev/null +++ b/powershell/internal/services/github/Get-MtGitHubRepositoryInventory.ps1 @@ -0,0 +1,26 @@ +function Get-MtGitHubRepositoryInventory { + <# + .SYNOPSIS + Internal: Enumerates organization repositories without visibility or archived-state filtering. + #> + [CmdletBinding()] + param() + $organization = $__MtSession.GitHubConnection.Organization + $encoded = [uri]::EscapeDataString($organization) + $evidence = Invoke-MtGitHubRequest -RelativeUri "/orgs/$encoded/repos?type=all" -Paginate -ApiVersion '2026-03-10' -IncludeMetadata + $issues = [System.Collections.Generic.List[string]]::new() + foreach ($issue in $evidence.Issues) { $issues.Add($issue) } + if (-not $evidence.PaginationComplete) { $issues.Add('Repository pagination is incomplete.') } + $repositories = [System.Collections.Generic.List[object]]::new() + $seen = [System.Collections.Generic.HashSet[string]]::new() + foreach ($repository in $evidence.Data) { + $id = $repository.id + $numeric = $id -is [int] -or $id -is [long] -or $id -is [bigint] + if (($null -eq $repository -or $repository.GetType() -ne [System.Management.Automation.PSCustomObject]) -or -not $numeric -or $id -le 0 -or $repository.name -isnot [string] -or [string]::IsNullOrWhiteSpace($repository.name) -or $null -eq $repository.owner -or $repository.owner.GetType() -ne [System.Management.Automation.PSCustomObject] -or $repository.owner.login -isnot [string] -or $repository.owner.login -ne $organization -or $repository.full_name -isnot [string] -or $repository.full_name -ne "$organization/$($repository.name)") { + $issues.Add('Repository inventory contains an unusable identity.'); continue + } + if (-not $seen.Add([string]$id)) { $issues.Add('Repository inventory contains a duplicate ID.'); continue } + $repositories.Add($repository) + } + return [pscustomobject]@{ Repositories = $repositories.ToArray(); Issues = $issues.ToArray(); StartedUtc = $evidence.StartedUtc; CompletedUtc = $evidence.CompletedUtc } +} diff --git a/powershell/internal/services/github/Invoke-MtGitHubGraphQLRequest.ps1 b/powershell/internal/services/github/Invoke-MtGitHubGraphQLRequest.ps1 new file mode 100644 index 0000000000..c87996e7be --- /dev/null +++ b/powershell/internal/services/github/Invoke-MtGitHubGraphQLRequest.ps1 @@ -0,0 +1,48 @@ +function Invoke-MtGitHubGraphQLRequest { + <# + .SYNOPSIS + Internal: Runs a static GitHub GraphQL read query with session-isolated evidence caching. + .DESCRIPTION + GraphQL is not versioned by X-GitHub-Api-Version. Error and partial responses are never cached. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] [string] $Query, + [Parameter(Mandatory)] [hashtable] $Variables, + [Parameter(Mandatory)] [string] $OperationName, + [switch] $DisableCache + ) + if (-not $__MtSession.GitHubConnection -or $__MtSession.GitHubConnection.Connected -ne $true) { + throw 'Not connected to GitHub. Call Connect-MtGitHub first.' + } + if ($Query -notmatch '^\s*query\s' -or $Query -match '\bmutation\b') { throw 'Only static read queries are supported.' } + $uri = "$($__MtSession.GitHubConnection.ApiBaseUri.TrimEnd('/'))/graphql" + $payload = @{ query = $Query; variables = $Variables; operationName = $OperationName } | ConvertTo-Json -Depth 20 -Compress + $digest = [Convert]::ToHexString([System.Security.Cryptography.SHA256]::HashData([Text.Encoding]::UTF8.GetBytes($payload))) + $key = "GraphQL|$uri|$digest" + if (-not $DisableCache -and $__MtSession.GitHubCache.ContainsKey($key)) { + $cached = $__MtSession.GitHubCache[$key] + if (([DateTimeOffset]::UtcNow - $cached.CompletedUtc).TotalMinutes -lt 5) { return $cached } + $__MtSession.GitHubCache.Remove($key) + } + $headers = @{} + $__MtSession.GitHubAuthHeader + $headers.Remove('X-GitHub-Api-Version') + $started = [DateTimeOffset]::UtcNow + $response = Invoke-WebRequest -Uri $uri -Method POST -Headers $headers -ContentType 'application/json' -Body $payload -ErrorAction Stop + $parsed = ConvertFrom-Json -InputObject $response.Content -NoEnumerate -ErrorAction Stop + $codes = [System.Collections.Generic.List[string]]::new() + if (($null -ne $parsed -and $parsed.GetType() -eq [System.Management.Automation.PSCustomObject]) -and (Test-MtGitHubObjectProperty -InputObject $parsed -PropertyName errors)) { + if ($parsed.errors -isnot [array]) { throw 'GitHub GraphQL error collection is unusable.' } + foreach ($errorItem in $parsed.errors) { + if ($null -eq $errorItem -or $errorItem.GetType() -ne [System.Management.Automation.PSCustomObject]) { throw 'GitHub GraphQL error collection is unusable.' } + $code = if ($errorItem.type) { $errorItem.type } elseif ($errorItem.extensions.code) { $errorItem.extensions.code } else { 'UNKNOWN' } + if ($code -cnotin 'FORBIDDEN', 'NOT_FOUND', 'INSUFFICIENT_SCOPES') { throw 'GitHub GraphQL execution failed; no configuration verdict was produced.' } + $codes.Add($code) + } + } + $data = $null + if ($null -ne $parsed -and $parsed.GetType() -eq [System.Management.Automation.PSCustomObject] -and $null -ne $parsed.data -and $parsed.data.GetType() -eq [System.Management.Automation.PSCustomObject]) { $data = $parsed.data } + $result = [pscustomobject]@{ Data = $data; Errors = $codes.ToArray(); StartedUtc = $started; CompletedUtc = [DateTimeOffset]::UtcNow } + if (-not $DisableCache -and $codes.Count -eq 0 -and ($null -ne $data -and $data.GetType() -eq [System.Management.Automation.PSCustomObject])) { $__MtSession.GitHubCache[$key] = $result } + return $result +} diff --git a/powershell/internal/services/github/Invoke-MtGitHubRequest.ps1 b/powershell/internal/services/github/Invoke-MtGitHubRequest.ps1 index fa3cb7e852..396929fa3f 100644 --- a/powershell/internal/services/github/Invoke-MtGitHubRequest.ps1 +++ b/powershell/internal/services/github/Invoke-MtGitHubRequest.ps1 @@ -17,6 +17,12 @@ .PARAMETER Paginate Follows Link header rel="next" and appends per_page=100. Use for list endpoints only. + .PARAMETER ApiVersion + Optional per-call REST version. Does not change the connection default. + + .PARAMETER IncludeMetadata + Returns evidence timestamps and pre-aggregation collection integrity. Legacy body callers are unchanged. + .PARAMETER DisableCache Bypasses session cache; makes a live API call. #> @@ -25,7 +31,10 @@ [Parameter(Mandatory = $true, Position = 0)] [string] $RelativeUri, [switch] $Paginate, - [switch] $DisableCache + [switch] $DisableCache, + [ValidatePattern('^\d{4}-\d{2}-\d{2}$')] + [string] $ApiVersion, + [switch] $IncludeMetadata ) if ($null -eq $__MtSession.GitHubConnection -or @@ -34,8 +43,12 @@ } $baseUri = $__MtSession.GitHubConnection.ApiBaseUri - $version = $__MtSession.GitHubConnection.ApiVersion + $version = if ($ApiVersion) { $ApiVersion } else { $__MtSession.GitHubConnection.ApiVersion } $headers = $__MtSession.GitHubAuthHeader + if ($ApiVersion) { + $headers = @{} + $__MtSession.GitHubAuthHeader + $headers['X-GitHub-Api-Version'] = $ApiVersion + } $absUri = "$baseUri/$($RelativeUri.TrimStart('/'))" if ($Paginate -and $absUri -notmatch '[?&]per_page=') { @@ -43,7 +56,15 @@ $absUri = "${absUri}${sep}per_page=100" } - $cacheKey = Get-MtGitHubCacheKey -ApiVersion $version -AbsoluteUri $absUri + $cacheKey = if ($IncludeMetadata) { + "Metadata|GET|$version|$absUri|Paginate=$($Paginate.IsPresent)" + } else { Get-MtGitHubCacheKey -ApiVersion $version -AbsoluteUri $absUri } + if ($IncludeMetadata -and -not $DisableCache -and $__MtSession.GitHubCache.ContainsKey($cacheKey)) { + $cached = $__MtSession.GitHubCache[$cacheKey] + if ($cached.CompletedUtc -isnot [DateTimeOffset] -or ([DateTimeOffset]::UtcNow - $cached.CompletedUtc).TotalMinutes -ge 5) { + $__MtSession.GitHubCache.Remove($cacheKey) + } + } if (-not $DisableCache -and $__MtSession.GitHubCache.ContainsKey($cacheKey)) { Write-Verbose "GitHub cache hit: $absUri" return $__MtSession.GitHubCache[$cacheKey] @@ -53,7 +74,16 @@ try { $wr = Invoke-WebRequest -Uri $Uri -Headers $headers -Method GET -UseBasicParsing -ErrorAction Stop - $body = if (-not [string]::IsNullOrWhiteSpace($wr.Content)) { + $kind = 'Empty' + $limited = $false + $body = if ($IncludeMetadata) { + if (-not [string]::IsNullOrWhiteSpace($wr.Content)) { + # Preserve array shape and null members before any collection aggregation. + $parsed = ConvertFrom-Json -InputObject $wr.Content -NoEnumerate -ErrorAction Stop + $kind = if ($null -eq $parsed) { 'Null' } elseif ($parsed -is [array]) { 'Array' } elseif ($null -ne $parsed -and $parsed.GetType() -eq [System.Management.Automation.PSCustomObject]) { 'Object' } else { 'Scalar' } + $parsed + } + } elseif (-not [string]::IsNullOrWhiteSpace($wr.Content)) { # ConvertFrom-Json '[]' yields $null because it enumerates the (empty) # array, so pagination can't distinguish "no items" from "one null item" # without short-circuiting the empty-array case here. @@ -66,6 +96,12 @@ $null } + if ($IncludeMetadata -and $kind -eq 'Array') { $body = $parsed } + if ($IncludeMetadata) { + $sso = Get-MtGitHubResponseHeaderValue -Headers $wr.Headers -Name 'X-GitHub-SSO' + $limited = $null -ne $sso -and $sso -match '(?i)partial-results|required' + } + # Rate-limit warning on successful response — do NOT throw; the response body is valid. # TryParse rather than [int] cast: a malformed header (e.g. an upstream proxy # rewriting the value) must not raise a parse exception that masks a successful response. @@ -89,7 +125,7 @@ } $linkHeader = Get-MtGitHubResponseHeaderValue -Headers $wr.Headers -Name 'Link' - return [PSCustomObject]@{ Body = $body; Link = $linkHeader } + return [PSCustomObject]@{ Body = $body; Link = $linkHeader; ContentKind = $kind; AccessLimited = $limited } } catch { $rateLimitMessage = Get-MtGitHubRateLimitMessage -ErrorRecord $_ if ($rateLimitMessage) { throw $rateLimitMessage } @@ -122,8 +158,65 @@ return $nextPath -eq $basePath -or $nextPath.StartsWith("$basePath/", [System.StringComparison]::Ordinal) } + $started = [DateTimeOffset]::UtcNow $first = Invoke-Page $absUri + if ($IncludeMetadata) { + $items = [System.Collections.Generic.List[object]]::new() + $issues = [System.Collections.Generic.List[string]]::new() + $visited = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::Ordinal) + $null = $visited.Add($absUri) + $pageCount = 0 + $accessLimited = $false + $page = $first + do { + $pageCount++ + if ($page.AccessLimited) { $accessLimited = $true } + if ($Paginate) { + if ($page.ContentKind -ne 'Array') { + $issues.Add("Page $pageCount is $($page.ContentKind), not a collection array.") + } else { + $index = 0 + foreach ($item in $page.Body) { + if (($null -eq $item -or $item.GetType() -ne [System.Management.Automation.PSCustomObject])) { $issues.Add("Page $pageCount item $index is not an object.") } + $items.Add($item) + $index++ + } + } + } elseif ($page.ContentKind -eq 'Array') { + $index = 0 + foreach ($item in $page.Body) { + if ($null -eq $item -or $item.GetType() -ne [System.Management.Automation.PSCustomObject]) { $issues.Add("Page $pageCount item $index is not an object.") } + $index++ + } + } elseif ($page.ContentKind -ne 'Object') { + $issues.Add("Response is $($page.ContentKind), not an object or array.") + } + $next = Get-NextLink $page.Link + if (-not $Paginate -or $null -eq $next) { break } + if (-not (Test-NextLinkSameOrigin -NextUri $next -BaseUri $baseUri)) { throw 'GitHub pagination refused a foreign next link.' } + if (-not $visited.Add($next)) { throw 'GitHub pagination cycle detected.' } + $page = Invoke-Page $next + } while ($true) + if ($accessLimited) { $issues.Add('GitHub reported limited authentication or partial SSO results.') } + $result = [pscustomobject]@{ + Data = $(if ($Paginate) { $items.ToArray() } else { $first.Body }) + ContentKind = $first.ContentKind + StartedUtc = $started + CompletedUtc = [DateTimeOffset]::UtcNow + PageCount = $pageCount + TraversalMode = $(if ($Paginate) { 'AllPages' } else { 'SinglePage' }) + PaginationComplete = $Paginate.IsPresent -and $null -eq $next + CollectionIntegrityValid = $issues.Count -eq 0 + AccessLimited = $accessLimited + Issues = $issues.ToArray() + } + # Assignment expressions also enumerate singleton arrays; the envelope retains the exact array. + if ($Paginate) { $result.Data = $items.ToArray() } else { $result.Data = $first.Body } + if (-not $DisableCache -and $result.CollectionIntegrityValid) { $__MtSession.GitHubCache[$cacheKey] = $result } + return $result + } + if (-not $Paginate) { $result = $first.Body } else { diff --git a/powershell/public/connect/Connect-MtGitHub.ps1 b/powershell/public/connect/Connect-MtGitHub.ps1 index ef987aa677..45c43837a9 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/tests/fixtures/golden/selection.json b/powershell/tests/fixtures/golden/selection.json index f1650a1bab..6f20952ec0 100644 --- a/powershell/tests/fixtures/golden/selection.json +++ b/powershell/tests/fixtures/golden/selection.json @@ -21,7 +21,7 @@ "AD" ] }, - "SelectedCount": 496, + "SelectedCount": 510, "SelectedFamilies": [ "MT.1024", "MT.1059", @@ -73,11 +73,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.2.1", @@ -685,7 +699,7 @@ "AD" ] }, - "SelectedCount": 452, + "SelectedCount": 466, "SelectedFamilies": [ "MT.1024", "MT.1059", @@ -737,11 +751,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.2.1", @@ -1158,7 +1186,7 @@ "AD" ] }, - "SelectedCount": 511, + "SelectedCount": 525, "SelectedFamilies": [ "MT.1024", "MT.1033", @@ -1212,11 +1240,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.2.1", @@ -1692,7 +1734,7 @@ "AD" ] }, - "SelectedCount": 512, + "SelectedCount": 526, "SelectedFamilies": [ "MT.1024", "MT.1059", @@ -1745,11 +1787,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.2.1", @@ -2225,7 +2281,7 @@ "AD" ] }, - "SelectedCount": 540, + "SelectedCount": 554, "SelectedFamilies": [ "MT.1024", "MT.1033", @@ -2280,11 +2336,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.2.1", @@ -2986,7 +3056,7 @@ "AD" ] }, - "SelectedCount": 452, + "SelectedCount": 466, "SelectedFamilies": [ "MT.1024", "MT.1059", @@ -3038,11 +3108,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.2.1", @@ -3465,7 +3549,7 @@ "AD" ] }, - "SelectedCount": 496, + "SelectedCount": 510, "SelectedFamilies": [ "MT.1024", "MT.1033", @@ -3520,11 +3604,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.2.1", diff --git a/powershell/tests/functions/Invoke-MtGitHubGraphQLRequest.Tests.ps1 b/powershell/tests/functions/Invoke-MtGitHubGraphQLRequest.Tests.ps1 new file mode 100644 index 0000000000..edefe45454 --- /dev/null +++ b/powershell/tests/functions/Invoke-MtGitHubGraphQLRequest.Tests.ps1 @@ -0,0 +1,122 @@ +BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force +} + +Describe 'GitHub GraphQL read transport' { + BeforeEach { + $script:gqlBody = '{"data":{"viewer":{"login":"fixture-user"}}}' + InModuleScope Maester { + $__MtSession.GitHubConnection = [pscustomobject]@{ Connected = $true; Organization = 'fixture-org'; ApiBaseUri = 'https://api.github.com'; ApiVersion = '2022-11-28' } + $__MtSession.GitHubAuthHeader = @{ Authorization = 'Bearer synthetic'; 'X-GitHub-Api-Version' = '2022-11-28' } + $__MtSession.GitHubCache = @{} + $__MtSession.MaesterConfig = [pscustomobject]@{ GlobalSettings = [pscustomobject]@{} } + } + Mock Invoke-WebRequest -ModuleName Maester { [pscustomobject]@{ Content = $script:gqlBody; Headers = @{} } } + } + AfterEach { + InModuleScope Maester { $__MtSession.GitHubConnection = $null; $__MtSession.GitHubAuthHeader = $null; $__MtSession.GitHubCache = @{}; $__MtSession.MaesterConfig = $null } + } + It 'Posts a query with variables and does not apply REST version headers' { + InModuleScope Maester { Invoke-MtGitHubGraphQLRequest -Query 'query Fixture($id:String!){viewer{login}}' -Variables @{ id = 'fixture' } -OperationName Fixture | Out-Null } + Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 1 -ParameterFilter { + $Uri -eq 'https://api.github.com/graphql' -and $Method -eq 'POST' -and + -not $Headers.ContainsKey('X-GitHub-Api-Version') -and ($Body | ConvertFrom-Json).variables.id -eq 'fixture' + } + InModuleScope Maester { $__MtSession.GitHubAuthHeader['X-GitHub-Api-Version'] } | Should -Be '2022-11-28' + } + It 'Isolates query text, variables, cursor and operation name' { + InModuleScope Maester { + Invoke-MtGitHubGraphQLRequest -Query 'query Fixture{viewer{login}}' -Variables @{ slug = 'one'; after = $null } -OperationName Fixture | Out-Null + Invoke-MtGitHubGraphQLRequest -Query 'query Fixture{viewer{login}}' -Variables @{ slug = 'one'; after = $null } -OperationName Fixture | Out-Null + Invoke-MtGitHubGraphQLRequest -Query 'query Fixture{viewer{login}}' -Variables @{ slug = 'two'; after = $null } -OperationName Fixture | Out-Null + Invoke-MtGitHubGraphQLRequest -Query 'query Fixture{viewer{login}}' -Variables @{ slug = 'two'; after = 'next' } -OperationName Fixture | Out-Null + Invoke-MtGitHubGraphQLRequest -Query 'query Other{viewer{login}}' -Variables @{ slug = 'two'; after = 'next' } -OperationName Other | Out-Null + } + Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 4 + } + It 'Routes to the connected GHE.com host and isolates its cache' { + InModuleScope Maester { + Invoke-MtGitHubGraphQLRequest -Query 'query Fixture{viewer{login}}' -Variables @{} -OperationName Fixture | Out-Null + $__MtSession.GitHubConnection.ApiBaseUri = 'https://api.fixture.ghe.com' + Invoke-MtGitHubGraphQLRequest -Query 'query Fixture{viewer{login}}' -Variables @{} -OperationName Fixture | Out-Null + } + Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 1 -ParameterFilter { $Uri -eq 'https://api.fixture.ghe.com/graphql' } + Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 2 + } + It 'Retains original times and refreshes expired evidence' { + InModuleScope Maester { + $first = Invoke-MtGitHubGraphQLRequest -Query 'query Fixture{viewer{login}}' -Variables @{} -OperationName Fixture + $hit = Invoke-MtGitHubGraphQLRequest -Query 'query Fixture{viewer{login}}' -Variables @{} -OperationName Fixture + $hit.StartedUtc | Should -Be $first.StartedUtc + $hit.CompletedUtc | Should -Be $first.CompletedUtc + $first.CompletedUtc = [DateTimeOffset]::UtcNow.AddMinutes(-6) + $fresh = Invoke-MtGitHubGraphQLRequest -Query 'query Fixture{viewer{login}}' -Variables @{} -OperationName Fixture + $fresh.CompletedUtc | Should -BeGreaterThan $first.CompletedUtc + } + Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 2 + } + It 'Does not cache known field-access errors with partial data' { + $script:gqlBody = '{"data":{"enterprise":{"ownerInfo":null}},"errors":[{"type":"FORBIDDEN","path":["enterprise","ownerInfo"]}]}' + $out = InModuleScope Maester { + $result = Invoke-MtGitHubGraphQLRequest -Query 'query Fixture{enterprise(slug:"fixture"){ownerInfo{notificationDeliveryRestrictionEnabledSetting}}}' -Variables @{} -OperationName Fixture + $__MtSession.GitHubCache.Count | Should -Be 0 + $result + } + $out.Errors | Should -Contain 'FORBIDDEN' + } + It 'Does not cache defensive malformed root shapes ' -ForEach @( + @{ Body = '[]' }, @{ Body = '[{"data":{}}]' }, @{ Body = 'null' }, @{ Body = '{"data":null}' } + ) { + $script:gqlBody = $Body + InModuleScope Maester { + Invoke-MtGitHubGraphQLRequest -Query 'query Fixture{viewer{login}}' -Variables @{} -OperationName Fixture | Out-Null + $__MtSession.GitHubCache.Count | Should -Be 0 + } + } + It 'Throws for unexpected GraphQL errors including throttling' { + $script:gqlBody = '{"errors":[{"type":"RATE_LIMITED","message":"synthetic"}],"data":null}' + { InModuleScope Maester { Invoke-MtGitHubGraphQLRequest -Query 'query Fixture{viewer{login}}' -Variables @{} -OperationName Fixture } } | Should -Throw '*execution failed*' + } + It 'Throws for invalid JSON' { + $script:gqlBody = '{bad' + { InModuleScope Maester { Invoke-MtGitHubGraphQLRequest -Query 'query Fixture{viewer{login}}' -Variables @{} -OperationName Fixture } } | Should -Throw + } + It 'Rejects mutation and disconnected use before transport' { + { InModuleScope Maester { Invoke-MtGitHubGraphQLRequest -Query 'mutation Fixture{noop}' -Variables @{} -OperationName Fixture } } | Should -Throw '*read queries*' + InModuleScope Maester { $__MtSession.GitHubConnection = $null } + { InModuleScope Maester { Invoke-MtGitHubGraphQLRequest -Query 'query Fixture{viewer{login}}' -Variables @{} -OperationName Fixture } } | Should -Throw '*Connect-MtGitHub*' + Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 0 + } + It 'Bypasses cache reads and writes when requested' { + InModuleScope Maester { + Invoke-MtGitHubGraphQLRequest -Query 'query Fixture{viewer{login}}' -Variables @{} -OperationName Fixture -DisableCache | Out-Null + Invoke-MtGitHubGraphQLRequest -Query 'query Fixture{viewer{login}}' -Variables @{} -OperationName Fixture -DisableCache | Out-Null + $__MtSession.GitHubCache.Count | Should -Be 0 + } + Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 2 + } + It 'Clears cached evidence through actual disconnect and reconnect paths' { + Mock Invoke-WebRequest -ModuleName Maester -ParameterFilter { $Method -eq 'GET' -and $Uri -match '/user$' } { [pscustomobject]@{ Content = '{"login":"fixture-user"}'; Headers = @{} } } + Mock Invoke-WebRequest -ModuleName Maester -ParameterFilter { $Method -eq 'GET' -and $Uri -match '/orgs/fixture-org$' } { [pscustomobject]@{ Content = '{"login":"fixture-org","plan":{"name":"enterprise"}}'; Headers = @{} } } + Mock Invoke-WebRequest -ModuleName Maester -ParameterFilter { $Method -eq 'GET' -and $Uri -match '/memberships/orgs/' } { [pscustomobject]@{ Content = '{"state":"active","role":"admin"}'; Headers = @{} } } + Mock Invoke-WebRequest -ModuleName Maester -ParameterFilter { $Method -eq 'GET' -and $Uri -match '/actions/permissions' } { [pscustomobject]@{ Content = '{"enabled_repositories":"all"}'; Headers = @{} } } + InModuleScope Maester { + Invoke-MtGitHubGraphQLRequest -Query 'query Fixture{viewer{login}}' -Variables @{} -OperationName Fixture | Out-Null + Disconnect-MtGitHub + $__MtSession.GitHubCache.Count | Should -Be 0 + $token = [System.Security.SecureString]::new() + $token.AppendChar('x') + Connect-MtGitHub -Organization fixture-org -Token $token -ApiBaseUri https://api.github.com -ApiVersion '2022-11-28' + $__MtSession.GitHubConnection.Connected | Should -BeTrue + Invoke-MtGitHubGraphQLRequest -Query 'query Fixture{viewer{login}}' -Variables @{} -OperationName Fixture | Out-Null + } + Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 2 -ParameterFilter { $Method -eq 'POST' } + } + It 'Does not ignore a defensive malformed errors collection ' -ForEach @( + @{Errors='false'},@{Errors='null'},@{Errors='"FORBIDDEN"'},@{Errors='[null]'} + ) { + $script:gqlBody='{"data":{"viewer":{"login":"fixture-user"}},"errors":'+$Errors+'}' + {InModuleScope Maester {Invoke-MtGitHubGraphQLRequest -Query 'query Fixture{viewer{login}}' -Variables @{} -OperationName Fixture}} | Should -Throw '*error collection*' + } + +} diff --git a/powershell/tests/functions/Invoke-MtGitHubRequest.Tests.ps1 b/powershell/tests/functions/Invoke-MtGitHubRequest.Tests.ps1 index b2df6f5690..a175906345 100644 --- a/powershell/tests/functions/Invoke-MtGitHubRequest.Tests.ps1 +++ b/powershell/tests/functions/Invoke-MtGitHubRequest.Tests.ps1 @@ -334,3 +334,141 @@ Describe 'Invoke-MtGitHubRequest' { } } } + + +Describe 'Opt-in GitHub REST evidence metadata' { + BeforeEach { + $script:metadataBody = '{"value":true}' + $script:metadataHeaders = @{} + InModuleScope Maester { + $__MtSession.GitHubConnection = [pscustomobject]@{ Connected = $true; Organization = 'fixture-org'; ApiBaseUri = 'https://api.github.com'; ApiVersion = '2022-11-28' } + $__MtSession.GitHubAuthHeader = @{ Authorization = 'Bearer synthetic'; 'X-GitHub-Api-Version' = '2022-11-28' } + $__MtSession.GitHubCache = @{} + } + Mock Invoke-WebRequest -ModuleName Maester { [pscustomobject]@{ Content = $script:metadataBody; Headers = $script:metadataHeaders } } + } + AfterEach { + InModuleScope Maester { $__MtSession.GitHubConnection = $null; $__MtSession.GitHubAuthHeader = $null; $__MtSession.GitHubCache = @{} } + } + It 'Separates documented empty arrays from defensive unusable ' -ForEach @( + @{ Body = '[]'; Valid = $true; Count = 0 } + @{ Body = '[ ]'; Valid = $true; Count = 0 } + @{ Body = '[{"name":"main"}]'; Valid = $true; Count = 1 } + @{ Body = '[null]'; Valid = $false; Count = 1 } + @{ Body = '[null,{"name":"main"}]'; Valid = $false; Count = 2 } + @{ Body = '[[{"name":"main"}]]'; Valid = $false; Count = 1 } + @{ Body = '[1]'; Valid = $false; Count = 1 } + @{ Body = 'null'; Valid = $false; Count = 0 } + @{ Body = ''; Valid = $false; Count = 0 } + @{ Body = '{}'; Valid = $false; Count = 0 } + ) { + $script:metadataBody = $Body + $out = InModuleScope Maester { Invoke-MtGitHubRequest '/repos/fixture-org/repo/branches' -Paginate -IncludeMetadata -ApiVersion '2026-03-10' } + $out.CollectionIntegrityValid | Should -Be $Valid + $out.Data.Count | Should -Be $Count + $out.PaginationComplete | Should -BeTrue + if (-not $Valid) { InModuleScope Maester { $__MtSession.GitHubCache.Count } | Should -Be 0 } + } + It 'Does not upgrade an existing legacy cached body into evidence metadata' { + $out = InModuleScope Maester { + Invoke-MtGitHubRequest '/orgs/fixture-org' | Out-Null + $metadata = Invoke-MtGitHubRequest '/orgs/fixture-org' -IncludeMetadata + $legacy = Invoke-MtGitHubRequest '/orgs/fixture-org' + [pscustomobject]@{ Metadata = $metadata; Legacy = $legacy } + } + $out.Metadata.StartedUtc | Should -BeOfType DateTimeOffset + $out.Legacy.PSObject.Properties.Name | Should -Not -Contain 'StartedUtc' + Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 2 + } + It 'Isolates version override and leaves the session header unchanged' { + InModuleScope Maester { + Invoke-MtGitHubRequest '/orgs/fixture-org' -IncludeMetadata -ApiVersion '2026-03-10' | Out-Null + Invoke-MtGitHubRequest '/orgs/fixture-org' -IncludeMetadata | Out-Null + $__MtSession.GitHubAuthHeader['X-GitHub-Api-Version'] | Should -Be '2022-11-28' + } + Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 1 -ParameterFilter { $Headers['X-GitHub-Api-Version'] -eq '2026-03-10' } + Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 2 + } + It 'Separates explicit single-page and paginated modes with the same URL' { + $script:metadataBody = '[{"name":"main"}]' + $out = InModuleScope Maester { + $single = Invoke-MtGitHubRequest '/branches?per_page=100' -IncludeMetadata + $all = Invoke-MtGitHubRequest '/branches?per_page=100' -IncludeMetadata -Paginate + Invoke-MtGitHubRequest '/branches?per_page=100' -IncludeMetadata -Paginate | Out-Null + @($single, $all) + } + $out[0].PaginationComplete | Should -BeFalse + $out[1].PaginationComplete | Should -BeTrue + Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 2 + } + It 'Keeps original timestamps on hits and replaces expired evidence' { + InModuleScope Maester { + $first = Invoke-MtGitHubRequest '/orgs/fixture-org' -IncludeMetadata + $next = Invoke-MtGitHubRequest '/orgs/fixture-org' -IncludeMetadata + $next.StartedUtc | Should -Be $first.StartedUtc + $next.CompletedUtc | Should -Be $first.CompletedUtc + $next.CompletedUtc = [DateTimeOffset]::UtcNow.AddMinutes(-6) + $fresh = Invoke-MtGitHubRequest '/orgs/fixture-org' -IncludeMetadata + $fresh.CompletedUtc | Should -BeGreaterThan $next.CompletedUtc + } + Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 2 + } + It 'Does not cache partial SSO evidence' { + $script:metadataBody = '[]' + $script:metadataHeaders = @{ 'X-GitHub-SSO' = 'partial-results; organizations=1' } + $out = InModuleScope Maester { Invoke-MtGitHubRequest '/branches' -IncludeMetadata -Paginate } + $out.AccessLimited | Should -BeTrue + $out.CollectionIntegrityValid | Should -BeFalse + InModuleScope Maester { $__MtSession.GitHubCache.Count } | Should -Be 0 + } + It 'Follows a valid empty intermediate page and retains invalid members from later pages' { + Mock Invoke-WebRequest -ModuleName Maester -ParameterFilter { $Uri -notmatch '[?&]page=2' } { + [pscustomobject]@{ Content = '[]'; Headers = @{ Link = '; rel="next"' } } + } + Mock Invoke-WebRequest -ModuleName Maester -ParameterFilter { $Uri -match '[?&]page=2' } { [pscustomobject]@{ Content = '[null,{"name":"main"}]'; Headers = @{} } } + $out = InModuleScope Maester { Invoke-MtGitHubRequest '/branches' -IncludeMetadata -Paginate } + $out.PageCount | Should -Be 2 + $out.Data.Count | Should -Be 2 + $out.CollectionIntegrityValid | Should -BeFalse + } + It 'Rejects foreign pagination links without forwarding credentials' { + $script:metadataBody = '[]' + $script:metadataHeaders = @{ Link = '; rel="next"' } + { InModuleScope Maester { Invoke-MtGitHubRequest '/branches' -IncludeMetadata -Paginate } } | Should -Throw '*foreign*' + Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 1 + } + It 'Rejects a pagination cycle and never caches the incomplete traversal' { + $script:metadataBody = '[]' + $script:metadataHeaders = @{ Link = '; rel="next"' } + { InModuleScope Maester { Invoke-MtGitHubRequest '/branches' -IncludeMetadata -Paginate } } | Should -Throw '*cycle*' + InModuleScope Maester { $__MtSession.GitHubCache.Count } | Should -Be 0 + } + It 'Preserves DisableCache read/write bypass for metadata' { + InModuleScope Maester { + Invoke-MtGitHubRequest '/orgs/fixture-org' -IncludeMetadata -DisableCache | Out-Null + Invoke-MtGitHubRequest '/orgs/fixture-org' -IncludeMetadata -DisableCache | Out-Null + $__MtSession.GitHubCache.Count | Should -Be 0 + } + Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 2 + } + It 'Inspects single-page array items without claiming complete enumeration' { + $script:metadataBody='[null,{"name":"main"}]' + $out=InModuleScope Maester {Invoke-MtGitHubRequest '/branches' -IncludeMetadata} + $out.Data.Count | Should -Be 2 + $out.CollectionIntegrityValid | Should -BeFalse + $out.PaginationComplete | Should -BeFalse + InModuleScope Maester {$__MtSession.GitHubCache.Count} | Should -Be 0 + } + It 'Does not remove an expired metadata entry when DisableCache bypasses reads and writes' { + InModuleScope Maester { + $first=Invoke-MtGitHubRequest '/orgs/fixture-org' -IncludeMetadata + $expired=[DateTimeOffset]::UtcNow.AddMinutes(-6) + $first.CompletedUtc=$expired + Invoke-MtGitHubRequest '/orgs/fixture-org' -IncludeMetadata -DisableCache | Out-Null + $__MtSession.GitHubCache.Count | Should -Be 1 + $__MtSession.GitHubCache['Metadata|GET|2022-11-28|https://api.github.com/orgs/fixture-org|Paginate=False'].CompletedUtc | Should -Be $expired + } + Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 2 + } + +} diff --git a/powershell/tests/functions/Test-MtCisGitHubAuthentication.Tests.ps1 b/powershell/tests/functions/Test-MtCisGitHubAuthentication.Tests.ps1 new file mode 100644 index 0000000000..ec95832928 --- /dev/null +++ b/powershell/tests/functions/Test-MtCisGitHubAuthentication.Tests.ps1 @@ -0,0 +1,93 @@ +BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force +} + +Describe 'CIS GitHub MFA through configuration, transport and native results' { + BeforeEach { + $script:mfaBody = '{"login":"fixture-org","two_factor_requirement_enabled":true}' + $script:mfaHeaders = @{} + InModuleScope Maester { + $__MtSession.GitHubConnection = [pscustomobject]@{ Connected = $true; Organization = 'fixture-org'; ApiBaseUri = 'https://api.github.com'; ApiVersion = '2022-11-28' } + $__MtSession.GitHubAuthHeader = @{ 'X-GitHub-Api-Version' = '2022-11-28' } + $__MtSession.GitHubCache = @{} + $__MtSession.MaesterConfig = $null + } + Mock Invoke-WebRequest -ModuleName Maester { + if ($Uri -ne 'https://api.github.com/orgs/fixture-org' -or $Method -ne 'GET') { throw 'Unexpected fixture request.' } + [pscustomobject]@{ Content = $script:mfaBody; Headers = $script:mfaHeaders } + } + } + AfterEach { InModuleScope Maester { $__MtSession.GitHubConnection = $null; $__MtSession.GitHubAuthHeader = $null; $__MtSession.GitHubCache = @{}; $__MtSession.MaesterConfig = $null } } + + It ' evaluates documented Boolean as ' -ForEach @( + @{ Id = 'CIS.GH.1.3.4'; Value = 'true'; Expected = 'Passed' } + @{ Id = 'CIS.GH.1.3.4'; Value = 'false'; Expected = 'Failed' } + @{ Id = 'CIS.GH.1.3.5'; Value = 'true'; Expected = 'Passed' } + @{ Id = 'CIS.GH.1.3.5'; Value = 'false'; Expected = 'Failed' } + ) { + $script:mfaBody = '{"two_factor_requirement_enabled":' + $Value + '}' + $row = @(Invoke-MtTest -Id $Id -Config @{ GlobalSettings = @{ GitHubAccountModel = 'PersonalAccounts' } }) + $row.Count | Should -Be 1 + $row[0].Result | Should -Be $Expected + $row[0].ResultDetail.TestResult | Should -Match 'fixture-org' + Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 1 -ParameterFilter { $Headers['X-GitHub-Api-Version'] -eq '2026-03-10' } + } + It 'Keeps missing/nullable and defensive unusable indeterminate for ' -ForEach @( + foreach ($id in 'CIS.GH.1.3.4', 'CIS.GH.1.3.5') { + foreach ($body in '{}','{"two_factor_requirement_enabled":null}','{"two_factor_requirement_enabled":"true"}','{"two_factor_requirement_enabled":1}','{"two_factor_requirement_enabled":[]}','[{"two_factor_requirement_enabled":true}]','null','true','') { @{ Id = $id; Body = $body } } + } + ) { + $script:mfaBody = $Body + $row = Invoke-MtTest -Id $Id -Config @{ GlobalSettings = @{ GitHubAccountModel = 'PersonalAccounts' } } + $row.Result | Should -Be 'Skipped' + $row.ReasonCode | Should -Be 'TestSkipped' + $row.ResultDetail.TestResult | Should -Match 'Indeterminate' + } + It 'Does not turn a partial SSO body into a pass' { + $script:mfaHeaders = @{ 'X-GitHub-SSO' = 'partial-results; organizations=1' } + (Invoke-MtTest -Id CIS.GH.1.3.5 -Config @{ GlobalSettings = @{ GitHubAccountModel = 'PersonalAccounts' } }).Result | Should -Be 'Skipped' + } + It 'Requires relevant account context before collection' -ForEach @( + @{ Model = 'Unknown' }, @{ Model = 'EnterpriseManagedUsers' } + ) { + $row = Invoke-MtTest -Id CIS.GH.1.3.4 -Config @{ GlobalSettings = @{ GitHubAccountModel = $Model } } + $row.Result | Should -Be 'Skipped' + $row.ReasonCode | Should -Not -Be 'NotApplicable' + Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 0 + } + It 'Does not infer MFA from a GHE.com organization flag' { + InModuleScope Maester { $__MtSession.GitHubConnection.ApiBaseUri = 'https://api.fixture.ghe.com' } + (Invoke-MtTest -Id CIS.GH.1.3.5 -Config @{ GlobalSettings = @{ GitHubAccountModel = 'PersonalAccounts' } }).Result | Should -Be 'Skipped' + Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 0 + } + It 'Reports malformed configured account model as Error' -ForEach @( + @{ Model = $true }, @{ Model = 'Other' }, @{ Model = @('PersonalAccounts') }, @{ Model = $null } + ) { + (Invoke-MtTest -Id CIS.GH.1.3.5 -Config @{ GlobalSettings = @{ GitHubAccountModel = $Model } }).Result | Should -Be 'Error' + } + It 'Rejects a configured organization mismatch without relabeling the connection' { + (Invoke-MtTest -Id CIS.GH.1.3.5 -Config @{ GlobalSettings = @{ GitHubAccountModel = 'PersonalAccounts'; GitHubOrganization = 'other-org' } }).Result | Should -Be 'Error' + Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 0 + } + It 'Recomputes account applicability after a configuration change despite cached raw evidence' { + (Invoke-MtTest -Id CIS.GH.1.3.5 -Config @{ GlobalSettings = @{ GitHubAccountModel = 'PersonalAccounts' } }).Result | Should -Be 'Passed' + (Invoke-MtTest -Id CIS.GH.1.3.5 -Config @{ GlobalSettings = @{ GitHubAccountModel = 'EnterpriseManagedUsers' } }).Result | Should -Be 'Skipped' + InModuleScope Maester { $__MtSession.MaesterConfig } | Should -BeNullOrEmpty + Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 1 + } + It 'Uses an actual JSON configuration file and ignores unrelated malformed scope fields' { + $file = Join-Path $TestDrive 'mfa.json' + '{"GlobalSettings":{"GitHubAccountModel":"PersonalAccounts","GitHubCisRepositoryScope":false}}' | Set-Content $file + (Invoke-MtTest -Id CIS.GH.1.3.5 -Config $file).Result | Should -Be 'Passed' + } + It 'Reports request HTTP as Error, not disabled or not-applicable' -ForEach @( + @{ Status = 401 }, @{ Status = 403 }, @{ Status = 404 }, @{ Status = 429 }, @{ Status = 500 } + ) { + Mock Invoke-WebRequest -ModuleName Maester { throw [Microsoft.PowerShell.Commands.HttpResponseException]::new('Synthetic HTTP failure', [System.Net.Http.HttpResponseMessage]::new([System.Net.HttpStatusCode]$Status)) } + (Invoke-MtTest -Id CIS.GH.1.3.5 -Config @{ GlobalSettings = @{ GitHubAccountModel = 'PersonalAccounts' } }).Result | Should -Be 'Error' + } + It 'Keeps invalid JSON as an execution error' { + $script:mfaBody = '{bad' + (Invoke-MtTest -Id CIS.GH.1.3.5 -Config @{ GlobalSettings = @{ GitHubAccountModel = 'PersonalAccounts' } }).Result | Should -Be 'Error' + } +} diff --git a/powershell/tests/functions/Test-MtCisGitHubBranchSettings.Tests.ps1 b/powershell/tests/functions/Test-MtCisGitHubBranchSettings.Tests.ps1 new file mode 100644 index 0000000000..1c081782a9 --- /dev/null +++ b/powershell/tests/functions/Test-MtCisGitHubBranchSettings.Tests.ps1 @@ -0,0 +1,317 @@ +BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force + function Get-CisBranchFixtureConfig { + param([string[]] $Main = @('main'), [object[]] $Entries) + if (-not $PSBoundParameters.ContainsKey('Entries')) { $Entries = @(@{ Id = 101; InUse = $true; MainBranches = $Main; LongStandingBranches = @() }) } + @{ GlobalSettings = @{ GitHubCisRepositoryScope = @{ Organization = 'fixture-org'; Complete = $true; Repositories = $Entries } } } + } +} + +Describe 'CIS GitHub branch audits through production evidence and native results' { + BeforeEach { + $script:repoBody = '[{"id":101,"name":"repo","full_name":"fixture-org/repo","owner":{"login":"fixture-org"},"visibility":"private","archived":false,"disabled":false}]' + $script:branchBody = '[{"name":"main","protected":true}]' + $script:policyBody = '{"url":"https://api.github.com/repos/fixture-org/repo/branches/main/protection","required_pull_request_reviews":{"dismiss_stale_reviews":true,"require_code_owner_reviews":true},"required_conversation_resolution":{"enabled":true},"enforce_admins":{"enabled":true},"allow_force_pushes":{"enabled":false},"allow_deletions":{"enabled":false}}' + $script:statusBody = '{"strict":true,"contexts":["ci"],"checks":[{"context":"ci","app_id":null}]}' + $script:signatureBody = '{"enabled":true}' + $script:rulesBody = '[]' + $script:defaultBody = '{"id":101,"default_branch":"main"}' + $script:branchStateBody = '{"name":"main","protected":true}' + $script:policyStatus = 200 + $script:otherPolicyBody = $null + $script:otherStatus = 200 + $script:signatureStatus = 200 + $script:repoHeaders = @{} + InModuleScope Maester { + $__MtSession.GitHubConnection = [pscustomobject]@{ Connected = $true; Organization = 'fixture-org'; ApiBaseUri = 'https://api.github.com'; ApiVersion = '2022-11-28' } + $__MtSession.GitHubAuthHeader = @{ 'X-GitHub-Api-Version' = '2022-11-28' } + $__MtSession.GitHubCache = @{} + $__MtSession.MaesterConfig = $null + } + Mock Invoke-WebRequest -ModuleName Maester { + if ($Method -ne 'GET' -or $Uri -notlike 'https://api.github.com/*') { throw 'Unexpected fixture request.' } + $path = ([uri]$Uri).AbsolutePath + $headers = @{} + $status = 200 + $body = switch -Regex ($path) { + '^/orgs/fixture-org/repos$' { $headers = $script:repoHeaders; $script:repoBody; break } + '^/repos/fixture-org/repo$' { $script:defaultBody; break } + '^/repos/fixture-org/repo/branches$' { $script:branchBody; break } + '/protection/required_status_checks$' { $script:statusBody; break } + '/protection/required_signatures$' { $status = $script:signatureStatus; $script:signatureBody; break } + '/branches/other/protection$' { $status = $script:otherStatus; $(if ($null -ne $script:otherPolicyBody) { $script:otherPolicyBody } else { $script:policyBody }); break } + '/protection$' { $status = $script:policyStatus; $script:policyBody; break } + '/rules/branches/' { $script:rulesBody; break } + '^/repos/fixture-org/repo/branches/[^/]+$' { $script:branchStateBody; break } + default { throw 'Unexpected fixture URI.' } + } + if ($status -ne 200) { throw [Microsoft.PowerShell.Commands.HttpResponseException]::new('Synthetic HTTP failure', [System.Net.Http.HttpResponseMessage]::new([System.Net.HttpStatusCode]$status)) } + [pscustomobject]@{ Content = $body; Headers = $headers } + } + } + AfterEach { InModuleScope Maester { $__MtSession.GitHubConnection = $null; $__MtSession.GitHubAuthHeader = $null; $__MtSession.GitHubCache = @{}; $__MtSession.MaesterConfig = $null } } + + It 'Passes the full named configuration audit without unrelated reads' -ForEach @( + foreach ($id in '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') { @{ Id = "CIS.GH.$id" } } + ) { + $row = @(Invoke-MtTest -Id $Id -Config (Get-CisBranchFixtureConfig)) + $row.Count | Should -Be 1 + $row[0].Result | Should -Be 'Passed' + $row[0].ResultDetail.TestResult | Should -Match 'complete declared applicable population' + Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 0 -ParameterFilter { $Uri -match '/rules/' } + if ($Id -ne 'CIS.GH.1.1.12') { Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 0 -ParameterFilter { $Uri -match '/required_signatures$|/branches\?per_page=' } } + } + It 'Fails a documented nonconforming classic value for ' -ForEach @( + @{ Id='CIS.GH.1.1.4'; Parent='required_pull_request_reviews'; Field='dismiss_stale_reviews'; Value=$false } + @{ Id='CIS.GH.1.1.7'; Parent='required_pull_request_reviews'; Field='require_code_owner_reviews'; Value=$false } + @{ Id='CIS.GH.1.1.11'; Parent='required_conversation_resolution'; Field='enabled'; Value=$false } + @{ Id='CIS.GH.1.1.14'; Parent='enforce_admins'; Field='enabled'; Value=$false } + @{ Id='CIS.GH.1.1.16'; Parent='allow_force_pushes'; Field='enabled'; Value=$true } + @{ Id='CIS.GH.1.1.17'; Parent='allow_deletions'; Field='enabled'; Value=$true } + ) { + $policy = $script:policyBody | ConvertFrom-Json + $policy.$Parent.$Field = $Value + $script:policyBody = $policy | ConvertTo-Json -Depth 8 -Compress + (Invoke-MtTest -Id $Id -Config (Get-CisBranchFixtureConfig)).Result | Should -Be 'Failed' + } + It 'Keeps absent/null/defensive wrong-type parent or flag indeterminate for /' -ForEach @( + foreach ($case in @( + @{Id='CIS.GH.1.1.4';Parent='required_pull_request_reviews';Field='dismiss_stale_reviews'}, + @{Id='CIS.GH.1.1.7';Parent='required_pull_request_reviews';Field='require_code_owner_reviews'}, + @{Id='CIS.GH.1.1.11';Parent='required_conversation_resolution';Field='enabled'}, + @{Id='CIS.GH.1.1.14';Parent='enforce_admins';Field='enabled'}, + @{Id='CIS.GH.1.1.16';Parent='allow_force_pushes';Field='enabled'}, + @{Id='CIS.GH.1.1.17';Parent='allow_deletions';Field='enabled'} + )) { + foreach ($json in 'null','"true"','1','[]','[{}]') { @{Id=$case.Id;Parent=$case.Parent;Field=$case.Field;Json=$json} } + } + ) { + $script:policyBody = '{"' + $Parent + '":{"' + $Field + '":' + $Json + '}}' + (Invoke-MtTest -Id $Id -Config (Get-CisBranchFixtureConfig)).Result | Should -Be 'Skipped' + } + It 'Rejects defensive singleton-array policy parents for /' -ForEach @( + @{Id='CIS.GH.1.1.4';Parent='required_pull_request_reviews';Fields='"dismiss_stale_reviews":true'} + @{Id='CIS.GH.1.1.7';Parent='required_pull_request_reviews';Fields='"require_code_owner_reviews":true'} + @{Id='CIS.GH.1.1.11';Parent='required_conversation_resolution';Fields='"enabled":true'} + @{Id='CIS.GH.1.1.14';Parent='enforce_admins';Fields='"enabled":true'} + @{Id='CIS.GH.1.1.16';Parent='allow_force_pushes';Fields='"enabled":false'} + @{Id='CIS.GH.1.1.17';Parent='allow_deletions';Fields='"enabled":false'} + ) { + $script:policyBody = '{"' + $Parent + '":[{' + $Fields + '}]}' + (Invoke-MtTest -Id $Id -Config (Get-CisBranchFixtureConfig)).Result | Should -Be 'Skipped' + } + It 'Fails for a complete policy requiring no status checks' -ForEach @(@{Id='CIS.GH.1.1.9'},@{Id='CIS.GH.1.1.10'}) { + $script:statusBody = '{"strict":true,"contexts":[],"checks":[]}' + (Invoke-MtTest -Id $Id -Config (Get-CisBranchFixtureConfig)).Result | Should -Be 'Failed' + } + It 'Requires strict freshness only for 1.1.10' { + $script:statusBody = '{"strict":false,"contexts":["ci"],"checks":[]}' + (Invoke-MtTest -Id CIS.GH.1.1.9 -Config (Get-CisBranchFixtureConfig)).Result | Should -Be 'Passed' + (Invoke-MtTest -Id CIS.GH.1.1.10 -Config (Get-CisBranchFixtureConfig)).Result | Should -Be 'Failed' + } + It 'Rejects unusable status policy ' -ForEach @( + @{Body='{"strict":true,"contexts":null,"checks":[]}'} + @{Body='{"strict":true,"contexts":[],"checks":[{"context":"ci"}]}'} + @{Body='{"strict":true,"contexts":[],"checks":[{"context":"ci","app_id":"1"}]}'} + @{Body='{"strict":true,"contexts":[null],"checks":[]}'} + @{Body='{"strict":"true","contexts":["ci"],"checks":[]}'} + ) { + $script:statusBody = $Body + (Invoke-MtTest -Id CIS.GH.1.1.10 -Config (Get-CisBranchFixtureConfig)).Result | Should -Be 'Skipped' + } + It 'Evaluates every existing branch, including a later page with an unsigned branch' { + $script:branchBody = '[{"name":"main","protected":true}]' + Mock Invoke-WebRequest -ModuleName Maester -ParameterFilter { $Uri -eq 'https://api.github.com/repos/fixture-org/repo/branches?per_page=100' } { [pscustomobject]@{ Content=$script:branchBody;Headers=@{Link='; rel="next"'} } } + Mock Invoke-WebRequest -ModuleName Maester -ParameterFilter { $Uri -match '/branches\?page=2$' } { [pscustomobject]@{Content='[{"name":"feature/a","protected":true}]';Headers=@{}} } + Mock Invoke-WebRequest -ModuleName Maester -ParameterFilter { $Uri -match '/feature%2Fa/protection/required_signatures$' } { [pscustomobject]@{Content='{"enabled":false}';Headers=@{}} } + $config=Get-CisBranchFixtureConfig + $config.GlobalSettings.GitHubCisRepositoryScope.Repositories[0].Remove('MainBranches') + $config.GlobalSettings.GitHubCisRepositoryScope.Repositories[0].Remove('LongStandingBranches') + (Invoke-MtTest -Id CIS.GH.1.1.12 -Config $config).Result | Should -Be 'Failed' + Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 1 -ParameterFilter { $Uri -match '/feature%2Fa/protection/required_signatures$' } + } + It 'Never turns defensive unusable branch populations into complete success' -ForEach @( + @{Body='[null,{"name":"main"}]'},@{Body='[null]'},@{Body='[]'},@{Body='null'},@{Body=''},@{Body='[[{"name":"main"}]]'},@{Body='[{"name":null}]'},@{Body='[{"name":"main"},{"name":"main"}]'} + ) { + $script:branchBody=$Body + (Invoke-MtTest -Id CIS.GH.1.1.12 -Config (Get-CisBranchFixtureConfig)).Result | Should -Be 'Skipped' + } + It 'Keeps a real violation alongside missing evidence Failed with coverage disclosure' { + $script:policyBody=$script:policyBody.Replace('"dismiss_stale_reviews":true','"dismiss_stale_reviews":false') + $script:otherPolicyBody='{}' + $row=Invoke-MtTest -Id CIS.GH.1.1.4 -Config (Get-CisBranchFixtureConfig -Main @('main','other')) + $row.Result | Should -Be 'Failed' + $row.ResultDetail.TestResult | Should -Match 'Indeterminate' + } + It 'Gives required collection Error precedence while retaining confirmed violation detail' { + $script:policyBody=$script:policyBody.Replace('"dismiss_stale_reviews":true','"dismiss_stale_reviews":false') + $script:otherStatus=403 + $row=Invoke-MtTest -Id CIS.GH.1.1.4 -Config (Get-CisBranchFixtureConfig -Main @('main','other')) + $row.Result | Should -Be 'Error' + $row.ResultDetail.TestResult | Should -Match 'Failed' + } + It 'Does not let signature-specific permission failure invalidate independent classic evidence' { + $script:signatureStatus=403 + $rows=@(Invoke-MtTest -Id CIS.GH.1.1.4,CIS.GH.1.1.12 -Config (Get-CisBranchFixtureConfig)) + ($rows|Where-Object Id -EQ CIS.GH.1.1.4).Result | Should -Be 'Passed' + ($rows|Where-Object Id -EQ CIS.GH.1.1.12).Result | Should -Be 'Error' + } + It 'Does not require unrelated classifications for the all-branch assessment' { + $config=Get-CisBranchFixtureConfig + $config.GlobalSettings.GitHubCisRepositoryScope.Repositories[0].MainBranches='irrelevant malformed classification' + $config.GlobalSettings.GitHubCisRepositoryScope.Repositories[0].LongStandingBranches=$false + (Invoke-MtTest -Id CIS.GH.1.1.12 -Config $config).Result | Should -Be 'Passed' + } + It 'Requires long-standing declarations only for 1.1.16' { + $config=Get-CisBranchFixtureConfig + $config.GlobalSettings.GitHubCisRepositoryScope.Repositories[0].Remove('LongStandingBranches') + (Invoke-MtTest -Id CIS.GH.1.1.4 -Config $config).Result | Should -Be 'Passed' + (Invoke-MtTest -Id CIS.GH.1.1.16 -Config $config).Result | Should -Be 'Skipped' + } + It 'Does not reject nonempty bypass context or read additional rulesets for conforming classic settings' { + $policy=$script:policyBody|ConvertFrom-Json + $policy.required_pull_request_reviews|Add-Member bypass_pull_request_allowances ([pscustomobject]@{users=@([pscustomobject]@{login='fixture-user'})}) + $script:policyBody=$policy|ConvertTo-Json -Depth 10 -Compress + Mock Invoke-WebRequest -ModuleName Maester -ParameterFilter { $Uri -match '/rules/' } { throw 'An unnecessary rules request was made.' } + (Invoke-MtTest -Id CIS.GH.1.1.14 -Config (Get-CisBranchFixtureConfig)).Result | Should -Be 'Passed' + (Invoke-MtTest -Id CIS.GH.1.1.4 -Config (Get-CisBranchFixtureConfig)).Result | Should -Be 'Passed' + Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 0 -ParameterFilter { $Uri -match '/rules/' } + } + It 'Does not credit potentially compensating or unrecognized rules ' -ForEach @( + @{Type='pull_request'},@{Type='PULL_REQUEST'},@{Type='future_rule'} + ) { + $script:policyBody=$script:policyBody.Replace('"dismiss_stale_reviews":true','"dismiss_stale_reviews":false') + $script:rulesBody='[{"type":"'+$Type+'","ruleset_source_type":"Enterprise","ruleset_id":1}]' + (Invoke-MtTest -Id CIS.GH.1.1.4 -Config (Get-CisBranchFixtureConfig)).Result | Should -Be 'Skipped' + } + It 'Does not credit an unrelated active rule as review protection' { + $script:policyBody=$script:policyBody.Replace('"dismiss_stale_reviews":true','"dismiss_stale_reviews":false') + $script:rulesBody='[{"type":"required_signatures"}]' + (Invoke-MtTest -Id CIS.GH.1.1.4 -Config (Get-CisBranchFixtureConfig)).Result | Should -Be 'Failed' + } + It 'Contextualizes policy 404 as ambiguous until an accessible branch proves absence' { + $script:policyStatus=404 + (Invoke-MtTest -Id CIS.GH.1.1.4 -Config (Get-CisBranchFixtureConfig)).Result | Should -Be 'Skipped' + InModuleScope Maester {$__MtSession.GitHubCache=@{}} + $script:branchStateBody='{"name":"main","protected":false}' + (Invoke-MtTest -Id CIS.GH.1.1.4 -Config (Get-CisBranchFixtureConfig)).Result | Should -Be 'Failed' + } + It 'Retains archived/disabled repositories and all visibility classes' -ForEach @(@{Visibility='public'},@{Visibility='internal'},@{Visibility='private'}) { + $script:repoBody=$script:repoBody.Replace('"private"','"'+$Visibility+'"').Replace('"archived":false','"archived":true').Replace('"disabled":false','"disabled":true') + (Invoke-MtTest -Id CIS.GH.1.1.4 -Config (Get-CisBranchFixtureConfig)).Result | Should -Be 'Passed' + Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 1 -ParameterFilter {$Uri -match '/repos\?type=all&per_page=100$'} + } + It 'Does not hide null or inaccessible repository inventory members' { + $script:repoBody=$script:repoBody.Replace('[{','[null,{') + (Invoke-MtTest -Id CIS.GH.1.1.4 -Config (Get-CisBranchFixtureConfig)).Result | Should -Be 'Skipped' + } + It 'Rejects unusable or duplicate repository identities ' -ForEach @( + @{Body='[{"id":"101","name":"repo","full_name":"fixture-org/repo","owner":{"login":"fixture-org"}}]'} + @{Body='[{"id":101,"name":"repo","full_name":"fixture-org/repo","owner":[{"login":"fixture-org"}]}]'} + @{Body='[{"id":101,"name":"repo","full_name":"fixture-org/repo","owner":{"login":"fixture-org"}},{"id":101,"name":"repo","full_name":"fixture-org/repo","owner":{"login":"fixture-org"}}]'} + ) { + $script:repoBody=$Body + (Invoke-MtTest -Id CIS.GH.1.1.4 -Config (Get-CisBranchFixtureConfig)).Result | Should -Be 'Skipped' + } + It 'Requires typed default-branch correlation and actual protection for the default branch' { + $script:defaultBody='{"id":"101","default_branch":"main"}' + (Invoke-MtTest -Id CIS.GH.1.1.20 -Config (Get-CisBranchFixtureConfig)).Result | Should -Be 'Skipped' + } + It 'Uses NotApplicable only for complete justified exclusions and preserves their detail' { + $row=Invoke-MtTest -Id CIS.GH.1.1.4 -Config (Get-CisBranchFixtureConfig -Entries @(@{Id=101;InUse=$false;ExclusionReason='Fixture repository no longer used'})) + $row.Result | Should -Be 'Skipped' + $row.ReasonCode | Should -Be 'NotApplicable' + $row.ResultDetail.TestResult | Should -Match 'Fixture repository no longer used' + } + It 'Does not treat an unexplained empty inventory as NotApplicable' { + $script:repoBody='[]' + $row=Invoke-MtTest -Id CIS.GH.1.1.4 -Config (Get-CisBranchFixtureConfig -Entries @()) + $row.Result | Should -Be 'Skipped' + $row.ReasonCode | Should -Not -Be 'NotApplicable' + } + It 'Re-resolves scope between invocations without reusing an earlier verdict' { + (Invoke-MtTest -Id CIS.GH.1.1.4 -Config (Get-CisBranchFixtureConfig)).Result | Should -Be 'Passed' + $script:otherPolicyBody='{}' + (Invoke-MtTest -Id CIS.GH.1.1.4 -Config (Get-CisBranchFixtureConfig -Main @('other'))).Result | Should -Be 'Skipped' + InModuleScope Maester {$__MtSession.MaesterConfig} | Should -BeNullOrEmpty + Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 1 -ParameterFilter {$Uri -match '/branches/other/protection$'} + } + It 'Honors real layered configuration replacement including empty branch arrays' { + $file=Join-Path $TestDrive 'branch.json' + Get-CisBranchFixtureConfig | ConvertTo-Json -Depth 12 | Set-Content $file + $overlay=@{GlobalSettings=@{GitHubCisRepositoryScope=@{Repositories=@(@{Id=101;InUse=$true;MainBranches=@();LongStandingBranches=@()})}}} + (Invoke-MtTest -Id CIS.GH.1.1.4 -Config @($file,$overlay)).Result | Should -Be 'Skipped' + } + It 'Rejects malformed Complete types through actual configuration resolution' { + $config=Get-CisBranchFixtureConfig + $config.GlobalSettings.GitHubCisRepositoryScope.Complete='true' + (Invoke-MtTest -Id CIS.GH.1.1.4 -Config $config).Result | Should -Be 'Error' + } + It 'Rejects a singleton array supplied as the scope object' { + $config=Get-CisBranchFixtureConfig + $config.GlobalSettings.GitHubCisRepositoryScope=@($config.GlobalSettings.GitHubCisRepositoryScope) + (Invoke-MtTest -Id CIS.GH.1.1.4 -Config $config).Result | Should -Be 'Error' + } + It 'Rejects unavailable and defensive invalid signature fields ' -ForEach @( + @{Body='{}'},@{Body='{"enabled":null}'},@{Body='{"enabled":"true"}'},@{Body='[{"enabled":true}]'} + ) { + $script:signatureBody=$Body + (Invoke-MtTest -Id CIS.GH.1.1.12 -Config (Get-CisBranchFixtureConfig)).Result | Should -Be 'Skipped' + } + It 'Assesses the actual default branch when it differs from the classified main branch' { + $script:defaultBody='{"id":101,"default_branch":"release"}' + Mock Invoke-WebRequest -ModuleName Maester -ParameterFilter {$Uri -match '/branches/release/protection$'} { + throw [Microsoft.PowerShell.Commands.HttpResponseException]::new('Synthetic missing protection',[System.Net.Http.HttpResponseMessage]::new([System.Net.HttpStatusCode]404)) + } + Mock Invoke-WebRequest -ModuleName Maester -ParameterFilter {$Uri -match '/branches/release$'} { [pscustomobject]@{Content='{"name":"release","protected":false}';Headers=@{}} } + (Invoke-MtTest -Id CIS.GH.1.1.20 -Config (Get-CisBranchFixtureConfig)).Result | Should -Be 'Failed' + Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 1 -ParameterFilter {$Uri -match '/branches/release/protection$'} + } + It 'Reconciles every repository page including an explicitly excluded archived repository' { + Mock Invoke-WebRequest -ModuleName Maester -ParameterFilter {$Uri -eq 'https://api.github.com/orgs/fixture-org/repos?type=all&per_page=100'} { + [pscustomobject]@{Content=$script:repoBody;Headers=@{Link='; rel="next"'}} + } + Mock Invoke-WebRequest -ModuleName Maester -ParameterFilter {$Uri -match 'type=all&page=2$'} { + [pscustomobject]@{Content='[{"id":102,"name":"old","full_name":"fixture-org/old","owner":{"login":"fixture-org"},"archived":true}]';Headers=@{}} + } + $config=Get-CisBranchFixtureConfig -Entries @(@{Id=101;InUse=$true;MainBranches=@('main')},@{Id=102;InUse=$false;ExclusionReason='Retired fixture repository'}) + (Invoke-MtTest -Id CIS.GH.1.1.4 -Config $config).Result | Should -Be 'Passed' + Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 1 -ParameterFilter {$Uri -match 'type=all&page=2$'} + } + It 'Treats a required repository page error as Error rather than a complete visible-only pass' { + Mock Invoke-WebRequest -ModuleName Maester -ParameterFilter {$Uri -eq 'https://api.github.com/orgs/fixture-org/repos?type=all&per_page=100'} { + [pscustomobject]@{Content=$script:repoBody;Headers=@{Link='; rel="next"'}} + } + Mock Invoke-WebRequest -ModuleName Maester -ParameterFilter {$Uri -match 'type=all&page=2$'} { + throw [Microsoft.PowerShell.Commands.HttpResponseException]::new('Synthetic forbidden page',[System.Net.Http.HttpResponseMessage]::new([System.Net.HttpStatusCode]403)) + } + (Invoke-MtTest -Id CIS.GH.1.1.4 -Config (Get-CisBranchFixtureConfig)).Result | Should -Be 'Error' + } + It 'Honors the actual MAESTER_CONFIG resolution path' { + $old=$env:MAESTER_CONFIG + try { + $file=Join-Path $TestDrive 'environment.json' + Get-CisBranchFixtureConfig|ConvertTo-Json -Depth 12|Set-Content $file + $env:MAESTER_CONFIG=$file + (Invoke-MtTest -Id CIS.GH.1.1.4).Result | Should -Be 'Passed' + } finally { $env:MAESTER_CONFIG=$old } + } + + It 'Does not correlate protection for a differently cased branch name' { + (Invoke-MtTest -Id CIS.GH.1.1.20 -Config (Get-CisBranchFixtureConfig -Main @('Main'))).Result | Should -Be 'Skipped' + } + It 'Preserves case-insensitive URI host semantics in protection correlation' { + InModuleScope Maester {$__MtSession.GitHubConnection.ApiBaseUri='https://API.GITHUB.COM'} + (Invoke-MtTest -Id CIS.GH.1.1.20 -Config (Get-CisBranchFixtureConfig)).Result | Should -Be 'Passed' + } + + It 'Evaluates beyond the presentation limit and displays violating branches first' { + $script:branchBody=@(0..100|ForEach-Object {@{name=('b{0:d3}' -f $_)}})|ConvertTo-Json -Compress + Mock Invoke-WebRequest -ModuleName Maester -ParameterFilter {$Uri -match '/branches/b100/protection/required_signatures$'} { [pscustomobject]@{Content='{"enabled":false}';Headers=@{}} } + $row=Invoke-MtTest -Id CIS.GH.1.1.12 -Config (Get-CisBranchFixtureConfig) + $row.Result | Should -Be 'Failed' + $row.ResultDetail.TestResult | Should -Match 'b100' + $row.ResultDetail.TestResult | Should -Match 'Evaluated branch findings: 101; displayed: 100' + } + +} diff --git a/powershell/tests/functions/Test-MtCisGitHubEnterpriseSettings.Tests.ps1 b/powershell/tests/functions/Test-MtCisGitHubEnterpriseSettings.Tests.ps1 new file mode 100644 index 0000000000..4eb19e9269 --- /dev/null +++ b/powershell/tests/functions/Test-MtCisGitHubEnterpriseSettings.Tests.ps1 @@ -0,0 +1,128 @@ +BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force +} + +Describe 'CIS GitHub enterprise-dependent native assessments' { + BeforeEach { + $script:verificationBody = '{"data":{"organization":{"id":"O_1","login":"fixture-org","isVerified":true}}}' + $script:associationBody = '{"data":{"enterprise":{"id":"E_1","slug":"fixture-enterprise","organizations":{"nodes":[{"id":"O_1","login":"fixture-org"}],"pageInfo":{"hasNextPage":false,"endCursor":null}}}}}' + $script:notificationBody = '{"data":{"enterprise":{"id":"E_1","slug":"fixture-enterprise","ownerInfo":{"notificationDeliveryRestrictionEnabledSetting":"ENABLED"}}}}' + InModuleScope Maester { + $__MtSession.GitHubConnection = [pscustomobject]@{ Connected = $true; Organization = 'fixture-org'; ApiBaseUri = 'https://api.github.com'; ApiVersion = '2022-11-28' } + $__MtSession.GitHubAuthHeader = @{} + $__MtSession.GitHubCache = @{} + $__MtSession.MaesterConfig = $null + } + Mock Invoke-WebRequest -ModuleName Maester { + if ($Method -ne 'POST' -or $Uri -notmatch '/graphql$') { throw 'Unexpected fixture request.' } + $request = $Body | ConvertFrom-Json + $content = switch ($request.operationName) { + MaesterCisVerification { $script:verificationBody } + MaesterCisAssociation { $script:associationBody } + MaesterCisNotifications { $script:notificationBody } + default { throw 'Unexpected GraphQL operation.' } + } + [pscustomobject]@{ Content = $content; Headers = @{} } + } + } + AfterEach { InModuleScope Maester { $__MtSession.GitHubConnection = $null; $__MtSession.GitHubAuthHeader = $null; $__MtSession.GitHubCache = @{}; $__MtSession.MaesterConfig = $null } } + + It 'Assesses profile verification as without ownerInfo' -ForEach @( + @{ Value = 'true'; Expected = 'Passed' }, @{ Value = 'false'; Expected = 'Failed' } + ) { + $script:verificationBody = '{"data":{"organization":{"id":"O_1","login":"fixture-org","isVerified":' + $Value + '}}}' + $row = Invoke-MtTest -Id CIS.GH.1.3.9 -Config @{ GlobalSettings = @{ GitHubEnterprise = 'fixture-enterprise' } } + $row.Result | Should -Be $Expected + Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 0 -ParameterFilter { ($Body | ConvertFrom-Json).query -match 'ownerInfo' } + } + It 'Rejects unavailable/defensive profile shape ' -ForEach @( + @{ Body = '{"data":{"organization":null}}' } + @{ Body = '{"data":{"organization":{"id":"O_1","login":"fixture-org","isVerified":null}}}' } + @{ Body = '{"data":{"organization":{"id":"O_1","login":"fixture-org","isVerified":"true"}}}' } + @{ Body = '{"data":{"organization":[{"id":"O_1","login":"fixture-org","isVerified":true}]}}' } + @{ Body = '{"data":[{"organization":{"id":"O_1","login":"fixture-org","isVerified":true}}]}' } + ) { + $script:verificationBody = $Body + (Invoke-MtTest -Id CIS.GH.1.3.9 -Config @{ GlobalSettings = @{ GitHubEnterprise = 'fixture-enterprise' } }).Result | Should -Be 'Skipped' + } + It 'Requires a positive identity association rather than a matching name alone' { + $script:associationBody = $script:associationBody.Replace('O_1','O_2') + (Invoke-MtTest -Id CIS.GH.1.3.9 -Config @{ GlobalSettings = @{ GitHubEnterprise = 'fixture-enterprise' } }).Result | Should -Be 'Skipped' + } + It 'Does not call a field unavailable to the verification control' { + $script:associationBody = '{"data":{"enterprise":{"id":"E_1","slug":"fixture-enterprise","organizations":{"nodes":[{"id":"O_1","login":"fixture-org"}]}}}}' + (Invoke-MtTest -Id CIS.GH.1.3.9 -Config @{ GlobalSettings = @{ GitHubEnterprise = 'fixture-enterprise' } }).Result | Should -Be 'Passed' + } + It 'Follows association cursors until a positive match is found' { + $script:associationBody = '{"data":{"enterprise":{"id":"E_1","slug":"fixture-enterprise","organizations":{"nodes":[],"pageInfo":{"hasNextPage":true,"endCursor":"next"}}}}}' + Mock Invoke-WebRequest -ModuleName Maester -ParameterFilter { ($Body | ConvertFrom-Json).operationName -eq 'MaesterCisAssociation' -and ($Body | ConvertFrom-Json).variables.after -eq 'next' } { + [pscustomobject]@{ Content = '{"data":{"enterprise":{"id":"E_1","slug":"fixture-enterprise","organizations":{"nodes":[{"id":"O_1","login":"fixture-org"}],"pageInfo":{"hasNextPage":false,"endCursor":null}}}}}'; Headers = @{} } + } + (Invoke-MtTest -Id CIS.GH.1.3.9 -Config @{ GlobalSettings = @{ GitHubEnterprise = 'fixture-enterprise' } }).Result | Should -Be 'Passed' + Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 2 -ParameterFilter { ($Body | ConvertFrom-Json).operationName -eq 'MaesterCisAssociation' } + } + It 'Treats an association cursor cycle as an execution error' { + $script:associationBody = '{"data":{"enterprise":{"id":"E_1","slug":"fixture-enterprise","organizations":{"nodes":[],"pageInfo":{"hasNextPage":true,"endCursor":"repeat"}}}}}' + (Invoke-MtTest -Id CIS.GH.1.3.9 -Config @{ GlobalSettings = @{ GitHubEnterprise = 'fixture-enterprise' } }).Result | Should -Be 'Error' + } + It 'Assesses independent enterprise notification as ' -ForEach @( + @{ Value = 'ENABLED'; Expected = 'Passed' }, @{ Value = 'DISABLED'; Expected = 'Failed' } + ) { + $script:notificationBody = $script:notificationBody.Replace('ENABLED',$Value) + $row = Invoke-MtTest -Id CIS.GH.1.3.10 -Config @{ GlobalSettings = @{ GitHubEnterprise = 'fixture-enterprise'; GitHubCisRepositoryScope = $false } } + $row.Result | Should -Be $Expected + $row.ResultDetail.TestResult | Should -Match 'independently targeted enterprise-setting audit' + $row.ResultDetail.TestResult | Should -Match 'fixture-enterprise' + $row.ResultDetail.TestResult | Should -Not -Match 'fixture-org' + Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 1 + Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 0 -ParameterFilter { ($Body | ConvertFrom-Json).query -match 'organizations|isVerified' } + } + It 'Does not substitute missing, nullable or malformed notification evidence ' -ForEach @( + @{ Body = '{"data":{"enterprise":null}}' } + @{ Body = '{"data":{"enterprise":{"id":"E_1","slug":"fixture-enterprise","ownerInfo":null}}}' } + @{ Body = '{"data":{"enterprise":{"id":"E_1","slug":"fixture-enterprise","ownerInfo":{"notificationDeliveryRestrictionEnabledSetting":null}}}}' } + @{ Body = '{"data":{"enterprise":{"id":"E_1","slug":"fixture-enterprise","ownerInfo":{"notificationDeliveryRestrictionEnabledSetting":"enabled"}}}}' } + @{ Body = '{"data":{"enterprise":{"id":"E_1","slug":"fixture-enterprise","ownerInfo":[{"notificationDeliveryRestrictionEnabledSetting":"ENABLED"}]}}}' } + @{ Body = '{"data":{"enterprise":[{"id":"E_1","slug":"fixture-enterprise","ownerInfo":{"notificationDeliveryRestrictionEnabledSetting":"ENABLED"}}]}}' } + @{ Body = '{"data":{"enterprise":{"id":"E_1","slug":"different","ownerInfo":{"notificationDeliveryRestrictionEnabledSetting":"ENABLED"}}}}' } + ) { + $script:notificationBody = $Body + (Invoke-MtTest -Id CIS.GH.1.3.10 -Config @{ GlobalSettings = @{ GitHubEnterprise = 'fixture-enterprise' } }).Result | Should -Be 'Skipped' + } + It 'Retains unknown rather than inferring non-applicability when enterprise context is absent' { + $row = Invoke-MtTest -Id CIS.GH.1.3.10 -Config @{} + $row.Result | Should -Be 'Skipped' + $row.ReasonCode | Should -Not -Be 'NotApplicable' + Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 0 + } + It 'Rejects a malformed configured enterprise target' { + (Invoke-MtTest -Id CIS.GH.1.3.10 -Config @{ GlobalSettings = @{ GitHubEnterprise = @('fixture-enterprise') } }).Result | Should -Be 'Error' + } + It 'Keeps field-access errors indeterminate and uncached' { + $script:notificationBody = '{"data":{"enterprise":{"id":"E_1","slug":"fixture-enterprise","ownerInfo":null}},"errors":[{"type":"FORBIDDEN"}]}' + (Invoke-MtTest -Id CIS.GH.1.3.10 -Config @{ GlobalSettings = @{ GitHubEnterprise = 'fixture-enterprise' } }).Result | Should -Be 'Skipped' + InModuleScope Maester { $__MtSession.GitHubCache.Count } | Should -Be 0 + } + It 'Uses changed enterprise targets on subsequent real configuration resolutions' { + (Invoke-MtTest -Id CIS.GH.1.3.10 -Config @{ GlobalSettings = @{ GitHubEnterprise = 'fixture-enterprise' } }).Result | Should -Be 'Passed' + $script:notificationBody = $script:notificationBody.Replace('fixture-enterprise','second-enterprise').Replace('ENABLED','DISABLED') + (Invoke-MtTest -Id CIS.GH.1.3.10 -Config @{ GlobalSettings = @{ GitHubEnterprise = 'second-enterprise' } }).Result | Should -Be 'Failed' + Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 2 + } + It 'Does not render unrecognized enum data as raw Markdown' { + $script:notificationBody = $script:notificationBody.Replace('ENABLED','