From 403ff4064a1a1ffae401929ccf62a8fe6f7ae11d Mon Sep 17 00:00:00 2001 From: Travis McDade Date: Sat, 24 Oct 2026 01:50:37 -0400 Subject: [PATCH 01/15] fix(github): preserve indeterminate CIS evidence Validate decisive organization settings before producing configuration verdicts. Keep valid deletion evidence as partial Investigate results and clarify the remaining CIS human review. Update companion guidance and exercise the real parser and native result path in regression tests. --- ...-MtCisGitHubOrganizationSettings.Tests.ps1 | 312 +++++++++++++++++- tests/cis/Test.CIS.GH.1.2.2.md | 17 +- tests/cis/Test.CIS.GH.1.2.2.ps1 | 15 +- tests/cis/Test.CIS.GH.1.2.3.md | 20 +- tests/cis/Test.CIS.GH.1.2.3.ps1 | 22 +- tests/cis/Test.CIS.GH.1.2.4.md | 20 +- tests/cis/Test.CIS.GH.1.2.4.ps1 | 22 +- tests/cis/Test.CIS.GH.1.3.2.md | 17 +- tests/cis/Test.CIS.GH.1.3.2.ps1 | 14 +- tests/cis/Test.CIS.GH.1.3.8.md | 17 +- tests/cis/Test.CIS.GH.1.3.8.ps1 | 17 +- 11 files changed, 436 insertions(+), 57 deletions(-) diff --git a/powershell/tests/functions/Test-MtCisGitHubOrganizationSettings.Tests.ps1 b/powershell/tests/functions/Test-MtCisGitHubOrganizationSettings.Tests.ps1 index 701d1bc289..a59d11cd3e 100644 --- a/powershell/tests/functions/Test-MtCisGitHubOrganizationSettings.Tests.ps1 +++ b/powershell/tests/functions/Test-MtCisGitHubOrganizationSettings.Tests.ps1 @@ -124,7 +124,7 @@ Describe 'CIS GitHub organization setting tests' { @{ Function = 'Test-MtCisGitHubRepositoryDeletionLimited' Id = 'CIS.GH.1.2.3' - ExpectedRows = @('\| `members_can_delete_repositories` \| `False` \| `False` \|') + ExpectedRows = @('\| `members_can_delete_repositories` \| `False` \|') HasLegacyFooter = $false HasInternalNote = $false IsInvestigate = $true @@ -132,7 +132,7 @@ Describe 'CIS GitHub organization setting tests' { @{ Function = 'Test-MtCisGitHubIssueDeletionLimited' Id = 'CIS.GH.1.2.4' - ExpectedRows = @('\| `members_can_delete_issues` \| `False` \| `False` \|') + ExpectedRows = @('\| `members_can_delete_issues` \| `False` \|') HasLegacyFooter = $false HasInternalNote = $false IsInvestigate = $true @@ -165,8 +165,10 @@ Describe 'CIS GitHub organization setting tests' { Should -Invoke Add-MtTestResultDetail -ModuleName Maester -Exactly -Times 1 -ParameterFilter { $Result -match "$Id automated evidence from ``GET /orgs/\{org\}``\." -and - $Result -match '\| Field \| Actual \| Expected \|' -and - $Result -match '\| --- \| --- \| --- \|' -and + (($IsInvestigate -and $Result -match '\| Field \| Actual \|' -and $Result -notmatch '\| Expected \|') -or + (-not $IsInvestigate -and $Result -match '\| Field \| Actual \| Expected \|')) -and + (($IsInvestigate -and $Result -match '\| --- \| --- \|') -or + (-not $IsInvestigate -and $Result -match '\| --- \| --- \| --- \|')) -and (($IsInvestigate -and $Investigate -eq $true) -or (-not $IsInvestigate -and -not $Investigate)) } @@ -247,8 +249,10 @@ Describe 'CIS GitHub organization setting tests' { -not $SkippedCustomReason -and $Investigate -eq $true -and $Result -match 'Manual review required' -and - $Result -match 'organization owners are trusted and qualified' -and - $Result -match '\| `members_can_delete_repositories` \| `False` \| `False` \|' + $Result -match 'few' -and + $Result -match 'trusted and qualified' -and + $Result -match 'organization owners' -and + $Result -match '\| `members_can_delete_repositories` \| `False` \|' } } @@ -262,8 +266,10 @@ Describe 'CIS GitHub organization setting tests' { -not $SkippedCustomReason -and $Investigate -eq $true -and $Result -match 'Manual review required' -and - $Result -match 'repository admin members are trusted and qualified' -and - $Result -match '\| `members_can_delete_repositories` \| `True` \| `False` \|' + $Result -match 'exactly two' -and + $Result -match 'trusted and qualified' -and + $Result -match 'every repository' -and + $Result -match '\| `members_can_delete_repositories` \| `True` \|' } } @@ -275,8 +281,10 @@ Describe 'CIS GitHub organization setting tests' { -not $SkippedCustomReason -and $Investigate -eq $true -and $Result -match 'Manual review required' -and - $Result -match 'organization owners are trusted and qualified' -and - $Result -match '\| `members_can_delete_issues` \| `False` \| `False` \|' + $Result -match 'few' -and + $Result -match 'trusted and qualified' -and + $Result -match 'organization owners' -and + $Result -match '\| `members_can_delete_issues` \| `False` \|' } } @@ -290,8 +298,10 @@ Describe 'CIS GitHub organization setting tests' { -not $SkippedCustomReason -and $Investigate -eq $true -and $Result -match 'Manual review required' -and - $Result -match 'repository admin members are trusted and qualified' -and - $Result -match '\| `members_can_delete_issues` \| `True` \| `False` \|' + $Result -match 'exactly two' -and + $Result -match 'trusted and qualified' -and + $Result -match 'every repository' -and + $Result -match '\| `members_can_delete_issues` \| `True` \|' } } } @@ -382,3 +392,281 @@ Describe 'CIS GitHub organization setting tests' { } } } + +Describe 'CIS GitHub evidence through the native transport and parser path' { + BeforeAll { + $script:validBody = '{"members_can_create_public_repositories":false,"members_can_create_private_repositories":false,"members_can_create_internal_repositories":false,"members_can_delete_repositories":false,"members_can_delete_issues":false,"members_can_create_teams":false,"default_repository_permission":"read"}' + } + + BeforeEach { + $script:rawBody = $script:validBody + $script:expectedUri = 'https://api.github.com/orgs/synthetic-org' + InModuleScope Maester { + $__MtSession.GitHubConnection = [PSCustomObject]@{ + Connected = $true + Organization = 'synthetic-org' + ApiBaseUri = 'https://api.github.com' + ApiVersion = '2026-03-10' + } + $__MtSession.GitHubAuthHeader = @{ 'X-GitHub-Api-Version' = '2026-03-10' } + $__MtSession.GitHubCache = @{} + } + # Only replace transport: real JSON parsing, request cache, native check and result collector run. + Mock Invoke-WebRequest -ModuleName Maester { + if ($Uri -ne $script:expectedUri -or $Method -ne 'GET') { + throw 'Unexpected transport request blocked by fixture.' + } + [PSCustomObject]@{ Content = $script:rawBody; Headers = @{} } + } + } + + AfterEach { + InModuleScope Maester { + $__MtSession.GitHubConnection = $null + $__MtSession.GitHubAuthHeader = $null + $__MtSession.GitHubCache = @{} + $__MtSession.MaesterConfig = $null + } + } + + $checkCases = @( + @{ Id = 'CIS.GH.1.2.2' } + @{ Id = 'CIS.GH.1.2.3' } + @{ Id = 'CIS.GH.1.2.4' } + @{ Id = 'CIS.GH.1.3.2' } + @{ Id = 'CIS.GH.1.3.8' } + ) + + It 'Discovers exactly the five intended valid native checks' { + $expected = @('CIS.GH.1.2.2', 'CIS.GH.1.2.3', 'CIS.GH.1.2.4', 'CIS.GH.1.3.2', 'CIS.GH.1.3.8') + $actual = @(Get-MtTest -Id 'CIS.GH.*') + $actual.Count | Should -Be 5 + Compare-Object ($expected | Sort-Object) ($actual.Id | Sort-Object) | Should -BeNullOrEmpty + foreach ($test in $actual) { + $test.IsValid | Should -BeTrue + $test.Errors | Should -BeNullOrEmpty + } + Should -Invoke Invoke-WebRequest -ModuleName Maester -Times 0 -Exactly + } + + Context 'Known configuration evidence' { + $creationCases = foreach ($public in $false, $true) { + foreach ($private in $false, $true) { + @{ Public = $public; Private = $private; Expected = $(if ($public -or $private) { 'Failed' } else { 'Passed' }) } + } + } + It 'Evaluates public=, private= independently of the deprecated umbrella field' -ForEach $creationCases { + $script:rawBody = '{"members_can_create_public_repositories":' + "$Public".ToLowerInvariant() + ',"members_can_create_private_repositories":' + "$Private".ToLowerInvariant() + ',"members_allowed_repository_creation_type":"' + $(if ($Expected -eq 'Passed') { 'all' } else { 'none' }) + '"}' + $row = @(Invoke-MtTest -Id 'CIS.GH.1.2.2') + $row.Count | Should -Be 1 + $row[0].Result | Should -Be $Expected + } + + It 'Keeps internal creation informational when it is ' -ForEach @(@{ Internal = 'true' }, @{ Internal = 'false' }) { + $script:rawBody = $script:validBody.Replace('"members_can_create_internal_repositories":false', '"members_can_create_internal_repositories":' + $Internal) + (Invoke-MtTest -Id 'CIS.GH.1.2.2').Result | Should -Be 'Passed' + } + + It 'Evaluates team creation as ' -ForEach @( + @{ Json = 'false'; Expected = 'Passed' } + @{ Json = 'true'; Expected = 'Failed' } + ) { + $script:rawBody = '{"members_can_create_teams":' + $Json + '}' + (Invoke-MtTest -Id 'CIS.GH.1.3.2').Result | Should -Be $Expected + } + + It 'Evaluates base permission as ' -ForEach @( + @{ Value = 'none'; Expected = 'Passed' } + @{ Value = 'read'; Expected = 'Passed' } + @{ Value = 'Read'; Expected = 'Passed' } + @{ Value = 'write'; Expected = 'Failed' } + @{ Value = 'admin'; Expected = 'Failed' } + ) { + $script:rawBody = '{"default_repository_permission":"' + $Value + '"}' + (Invoke-MtTest -Id 'CIS.GH.1.3.8').Result | Should -Be $Expected + } + } + + Context 'Deletion evidence remains partial' { + $deletionCases = foreach ($check in @( + @{ Id = 'CIS.GH.1.2.3'; Field = 'members_can_delete_repositories' } + @{ Id = 'CIS.GH.1.2.4'; Field = 'members_can_delete_issues' } + )) { + foreach ($value in 'true', 'false') { @{ Id = $check.Id; Field = $check.Field; Json = $value } } + } + It 'Keeps Investigate for and reports the remaining CIS review' -ForEach $deletionCases { + $script:rawBody = '{"' + $Field + '":' + $Json + '}' + $row = @(Invoke-MtTest -Id $Id) + $row.Count | Should -Be 1 + $row[0].Result | Should -Be 'Investigate' + $detail = $row[0].ResultDetail.TestResult + $detail | Should -Match 'partial' + $detail | Should -Not -Match '\| Expected \|' + $detail | Should -Match ([regex]::Escape('`' + $Field + '` | `' + $Json + '`')) + if ($Json -eq 'true') { + $detail | Should -Match 'exactly two' + $detail | Should -Match 'every repository' + $detail | Should -Match 'trusted and qualified' + } else { + $detail | Should -Match 'few' + $detail | Should -Match 'organization owners' + $detail | Should -Match 'trusted and qualified' + } + } + } + + Context 'Unusable field evidence is indeterminate' { + $booleanCases = foreach ($check in @( + @{ Id = 'CIS.GH.1.2.2'; Field = 'members_can_create_public_repositories' } + @{ Id = 'CIS.GH.1.2.2'; Field = 'members_can_create_private_repositories' } + @{ Id = 'CIS.GH.1.2.3'; Field = 'members_can_delete_repositories' } + @{ Id = 'CIS.GH.1.2.4'; Field = 'members_can_delete_issues' } + @{ Id = 'CIS.GH.1.3.2'; Field = 'members_can_create_teams' } + )) { + # These invalid values are defensive fixtures, not documented GitHub Boolean contracts. + foreach ($json in 'null', '"false"', '0', '[]', '[false]', '{}') { + @{ Id = $check.Id; Field = $check.Field; Json = $json } + } + } + It 'Skips when contains unusable ' -ForEach $booleanCases { + $script:rawBody = $script:validBody.Replace('"' + $Field + '":false', '"' + $Field + '":' + $Json) + $row = @(Invoke-MtTest -Id $Id) + $row.Count | Should -Be 1 + $row[0].Result | Should -Be 'Skipped' + $row[0].ReasonCode | Should -Be 'TestSkipped' + $row[0].ReasonDetail | Should -Match 'Indeterminate' + $row[0].ReasonDetail | Should -Match $Field + } + + It 'Skips nullable or unrecognized base permission ' -ForEach @( + @{ Json = 'null' } + @{ Json = '""' } + @{ Json = '" "' } + @{ Json = '"unknown-permission"' } + @{ Json = 'false' } + @{ Json = '0' } + @{ Json = '["read"]' } + @{ Json = '{}' } + ) { + $script:rawBody = '{"default_repository_permission":' + $Json + '}' + $row = Invoke-MtTest -Id 'CIS.GH.1.3.8' + $row.Result | Should -Be 'Skipped' + $row.ReasonCode | Should -Be 'TestSkipped' + $row.ReasonDetail | Should -Match 'Indeterminate' + $row.ReasonDetail | Should -Match 'default_repository_permission' + $row.ReasonDetail | Should -Not -Match 'unknown-permission' + } + + It 'Skips for missing required organization evidence' -ForEach $checkCases { + $script:rawBody = '{}' + $row = Invoke-MtTest -Id $Id + $row.Result | Should -Be 'Skipped' + $row.ReasonCode | Should -Be 'TestSkipped' + $row.ReasonDetail | Should -Match 'Indeterminate' + } + } + + Context 'Shapes still visible after existing normalization' { + $shapeCases = foreach ($check in $checkCases) { + foreach ($body in '', 'null', '[]', 'false', '0', '"text"', '[{},{}]') { + @{ Id = $check.Id; Body = $body } + } + } + It 'Skips for unusable response body ' -ForEach $shapeCases { + $script:rawBody = $Body + $row = Invoke-MtTest -Id $Id + $row.Result | Should -Be 'Skipped' + $row.ReasonCode | Should -Be 'TestSkipped' + $row.ReasonDetail | Should -Match 'Indeterminate' + } + } + + It 'Requires both public and private evidence when only is returned' -ForEach @( + @{ Field = 'members_can_create_public_repositories' } + @{ Field = 'members_can_create_private_repositories' } + ) { + $script:rawBody = '{"' + $Field + '":false}' + $row = Invoke-MtTest -Id 'CIS.GH.1.2.2' + $row.Result | Should -Be 'Skipped' + $row.ReasonCode | Should -Be 'TestSkipped' + $row.ReasonDetail | Should -Match 'Indeterminate' + } + + It 'Uses check-visible evidence on configured host , with missing fields still indeterminate' -ForEach @( + @{ BaseUri = 'https://api.github.com' } + @{ BaseUri = 'https://api.synthetic.ghe.com' } + ) { + # A synthetic connected session tests request routing, not device-flow or live-platform qualification. + InModuleScope Maester -Parameters @{ BaseUri = $BaseUri } { + $__MtSession.GitHubConnection.ApiBaseUri = $BaseUri + } + $script:expectedUri = "$BaseUri/orgs/synthetic-org" + (Invoke-MtTest -Id 'CIS.GH.1.2.2').Result | Should -Be 'Passed' + InModuleScope Maester { $__MtSession.GitHubCache = @{} } + $script:rawBody = '{"members_can_create_private_repositories":false}' + $row = Invoke-MtTest -Id 'CIS.GH.1.2.2' + $row.Result | Should -Be 'Skipped' + $row.ReasonDetail | Should -Match 'Indeterminate' + Should -Invoke Invoke-WebRequest -ModuleName Maester -Times 2 -Exactly + } + + Context 'Existing singleton-array normalization limitation (characterization only)' { + # Array-wrapped organization objects are NOT an endorsed GitHub response contract. + # Current parsing/pipeline enumeration can erase their wrappers before a check sees them. + # Future parser rejection is allowed: these fixtures must not require preserving that limitation. + It 'Characterizes an array wrapper without promising complete raw-schema validation: ' -ForEach @( + @{ Wrapper = 'single' } + @{ Wrapper = 'nested' } + ) { + $script:rawBody = if ($Wrapper -eq 'single') { '[' + $script:validBody + ']' } else { '[[' + $script:validBody + ']]' } + $row = Invoke-MtTest -Id 'CIS.GH.1.3.2' + $row.Result | Should -BeIn @('Passed', 'Skipped', 'Error') + if ($row.Result -eq 'Passed') { + $parsed = InModuleScope Maester { Get-MtGitHubOrganization } + ($parsed -is [System.Array]) | Should -BeFalse + $parsed.members_can_create_teams | Should -BeOfType [bool] + $parsed.members_can_create_teams | Should -BeFalse + } + } + } + + Context 'Transport and parsing failures retain Error' { + It 'Reports malformed JSON as Error for ' -ForEach $checkCases { + $script:rawBody = '{' + $row = Invoke-MtTest -Id $Id + $row.Result | Should -Be 'Error' + $row.ReasonCode | Should -Be 'TestError' + } + + $httpCases = foreach ($check in $checkCases) { + foreach ($status in 401, 403, 404, 429, 500, 503) { @{ Id = $check.Id; Status = $status } } + } + It 'Reports HTTP as Error for ' -ForEach $httpCases { + Mock Invoke-WebRequest -ModuleName Maester { + $response = [System.Net.Http.HttpResponseMessage]::new([System.Net.HttpStatusCode]$Status) + throw [Microsoft.PowerShell.Commands.HttpResponseException]::new('Synthetic GitHub HTTP failure', $response) + } + $row = Invoke-MtTest -Id $Id + $row.Result | Should -Be 'Error' + $row.ReasonCode | Should -Be 'TestError' + Should -Invoke Invoke-WebRequest -ModuleName Maester -Times 1 -Exactly + } + } + + It 'Routes requested version and stores its version-qualified cache key' -ForEach @( + @{ Version = '2022-11-28' } + @{ Version = '2026-03-10' } + ) { + InModuleScope Maester -Parameters @{ Version = $Version } { + $__MtSession.GitHubConnection.ApiVersion = $Version + $__MtSession.GitHubAuthHeader['X-GitHub-Api-Version'] = $Version + } + (Invoke-MtTest -Id 'CIS.GH.1.3.2').Result | Should -Be 'Passed' + Should -Invoke Invoke-WebRequest -ModuleName Maester -Times 1 -Exactly -ParameterFilter { + $Headers['X-GitHub-Api-Version'] -eq $Version + } + InModuleScope Maester -Parameters @{ Version = $Version } { + $__MtSession.GitHubCache.ContainsKey("$Version|https://api.github.com/orgs/synthetic-org") | Should -BeTrue + } + } +} diff --git a/tests/cis/Test.CIS.GH.1.2.2.md b/tests/cis/Test.CIS.GH.1.2.2.md index 4c9a7d3048..c87b799c8c 100644 --- a/tests/cis/Test.CIS.GH.1.2.2.md +++ b/tests/cis/Test.CIS.GH.1.2.2.md @@ -29,24 +29,31 @@ Evidence fields: - `members_can_create_internal_repositories` when returned, shown as informational - `members_allowed_repository_creation_type` is displayed when returned, but is not decisive -The test passes when public and private repository creation are `false`. Internal repository creation is shown as additional enterprise/GHEC context only because the CIS GH 1.2.2 literal audit covers public and private repository creation. +Both decisive fields must be Boolean values. The test passes when both are `false` and fails when either is `true`. Internal repository creation is shown as additional enterprise/GHEC context only because the CIS GH 1.2.2 literal audit covers public and private repository creation. #### Permissions required -GitHub requires organization-owner visibility for full organization details. Use `Connect-MtGitHub` with a classic PAT that has `admin:org`, or a fine-grained PAT with organization Members read and Administration read permissions. +For full organization settings, GitHub documents an organization owner using a classic PAT or OAuth token with `admin:org`. `Connect-MtGitHub` checks active organization membership; fine-grained PATs require organization Members read permission for that probe. Its separate Actions-permission probe uses organization Administration read permission, but neither that probe nor a successful connection guarantees that the required settings are returned. -#### Remediation summary +Use the API host and token appropriate to the deployment. GHE.com requires an authenticated request to `api.SUBDOMAIN.ghe.com`; use a host-appropriate manual token rather than assuming the github.com device flow applies. Missing required evidence remains indeterminate on standard GHEC, Enterprise Managed Users, and GHE.com. -In the organization settings, open **Member privileges** and clear the public and private repository creation options for members. For GHEC organizations associated with an enterprise, review internal repository creation separately as an enterprise governance decision. +#### Remediation action + +1. On github.com, open [your organizations](https://github.com/settings/organizations), select the organization, then open **Settings** > **Access** > **Member privileges**; see [GitHub's repository-creation guidance](https://docs.github.com/en/enterprise-cloud@latest/organizations/managing-organization-settings/restricting-repository-creation-in-your-organization). +2. Clear the public and private repository-creation options for members, then save the changes. If an enterprise policy controls the options, coordinate the change with an enterprise owner. +3. Review internal repository creation separately as an enterprise governance decision; its returned flag does not decide this check. #### Known limitations +Only the connected organization's returned settings are assessed; this test does not enumerate every organization in an enterprise or reconstruct inherited policies. Required fields must be present and usable. Missing, null, or invalid evidence produces an explicit indeterminate Skipped result, while request and JSON parsing failures remain Error results. Missing data does not establish that a setting is disabled or that the recommendation is not applicable. Validation applies to fields available after shared JSON parsing; it is not complete raw-response schema validation. + This test uses the granular repository creation fields because GitHub is replacing the legacy `members_allowed_repository_creation_type` umbrella field. That umbrella value is displayed when returned, but is not decisive. If required granular fields are not returned, the test skips with a field-specific reason. #### Related links * [CIS GitHub Benchmark v1.2.0 - Section 1.2.2](https://www.cisecurity.org/benchmark/github) -* [GitHub REST API: Get an organization](https://docs.github.com/en/rest/orgs/orgs#get-an-organization) +* [GitHub REST API: Get an organization](https://docs.github.com/en/enterprise-cloud@latest/rest/orgs/orgs?apiVersion=2026-03-10#get-an-organization) +* [GitHub: Restricting repository creation](https://docs.github.com/en/enterprise-cloud@latest/organizations/managing-organization-settings/restricting-repository-creation-in-your-organization) %TestResult% diff --git a/tests/cis/Test.CIS.GH.1.2.2.ps1 b/tests/cis/Test.CIS.GH.1.2.2.ps1 index 0702f8b701..2eb7b17453 100644 --- a/tests/cis/Test.CIS.GH.1.2.2.ps1 +++ b/tests/cis/Test.CIS.GH.1.2.2.ps1 @@ -43,7 +43,13 @@ $missingFields = @($requiredFields | Where-Object { -not (Test-MtGitHubObjectProperty -InputObject $org -PropertyName $_) }) if ($missingFields.Count -gt 0) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "GitHub organization response did not include required field(s): $($missingFields -join ', '). These fields are required to evaluate CIS.GH.1.2.2 and may be missing because of permissions, plan, API version, or organization type." + Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Indeterminate: GitHub organization response did not include required field(s): $($missingFields -join ', '). These fields are required to evaluate CIS.GH.1.2.2 and may be missing because of permissions, plan, API version, or organization type." + return $null + } + + $invalidFields = @($requiredFields | Where-Object { $org.$_ -isnot [bool] }) + if ($invalidFields.Count -gt 0) { + Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Indeterminate: GitHub organization field(s) must be Boolean values to evaluate CIS.GH.1.2.2: $($invalidFields -join ', '). No configuration verdict was produced." return $null } @@ -87,7 +93,14 @@ "Deprecated umbrella field ``members_allowed_repository_creation_type`` was not returned. The granular fields above are the decisive checks." } + $resultSummary = if ($result) { + 'Well done. Members cannot create public or private repositories.' + } else { + 'Members can create public or private repositories. Disable both member repository-creation options in organization Member privileges.' + } $resultMarkdown = @" +$resultSummary + CIS.GH.1.2.2 automated evidence from ``GET /orgs/{org}``. | Field | Actual | Expected | diff --git a/tests/cis/Test.CIS.GH.1.2.3.md b/tests/cis/Test.CIS.GH.1.2.3.md index bbfd690252..d7ebcc7592 100644 --- a/tests/cis/Test.CIS.GH.1.2.3.md +++ b/tests/cis/Test.CIS.GH.1.2.3.md @@ -16,7 +16,7 @@ Members without the required repository or organization role will not be able to CIS marks this recommendation as Manual. This Maester test collects the organization setting evidence that maps to CIS GH 1.2.3, then reports Investigate because CIS still requires a human trust review. -When `members_can_delete_repositories` is `true`, CIS requires verifying that repository admin members are trusted and qualified. When it is `false`, CIS still requires verifying that organization owners are trusted and qualified. +When `members_can_delete_repositories` is `true`, the CIS review requires exactly two trusted and qualified administrators in every repository. When it is `false`, the CIS review requires only a few organization owners, all trusted and qualified; it does not set a numeric owner limit. These are the benchmark's remaining human-review branches, not a complete authorization model derived from this flag. #### API evidence @@ -24,24 +24,32 @@ Endpoint: `GET /orgs/{org}` Evidence field: `members_can_delete_repositories` -When this field is returned, the test records the actual value and returns Investigate so the remaining CIS manual review path is visible in Maester results. +An actual Boolean value is recorded as partial evidence and produces Investigate for either value. The result does not declare CIS compliance or noncompliance. A missing, null, or non-Boolean value instead produces an explicit indeterminate Skipped result. #### Permissions required -GitHub requires organization-owner visibility for full organization details. Use `Connect-MtGitHub` with a classic PAT that has `admin:org`, or a fine-grained PAT with organization Members read and Administration read permissions. +For full organization settings, GitHub documents an organization owner using a classic PAT or OAuth token with `admin:org`. `Connect-MtGitHub` checks active organization membership; fine-grained PATs require organization Members read permission for that probe. Its separate Actions-permission probe uses organization Administration read permission, but neither that probe nor a successful connection guarantees that the required settings are returned. -#### Remediation summary +Use the API host and token appropriate to the deployment. GHE.com requires an authenticated request to `api.SUBDOMAIN.ghe.com`; use a host-appropriate manual token rather than assuming the github.com device flow applies. Missing required evidence remains indeterminate on standard GHEC, Enterprise Managed Users, and GHE.com. -In the organization settings, open **Member privileges** and disable the option that allows members to delete or transfer repositories for the organization. If the setting remains enabled, manually verify that repository administrators are limited to trusted users and document the review. If the setting is disabled, verify that organization owners are limited to trusted users and document the review. +#### Remediation action + +1. On github.com, open [your organizations](https://github.com/settings/organizations), select the organization, then open **Settings** > **Access** > **Member privileges** and review **Repository deletion and transfer**; see [GitHub's deletion-permission guidance](https://docs.github.com/en/enterprise-cloud@latest/organizations/managing-organization-settings/setting-permissions-for-deleting-or-transferring-repositories). +2. If member deletion is enabled, review **Settings** > **Collaborators & teams** in every repository. Review and adjust administrator access so that exactly two repository administrators remain, both trusted and qualified. +3. If member deletion is disabled, review the organization's **People** page filtered to **Owners**. Review and adjust access so only a few trusted and qualified owners remain; CIS does not specify a numeric owner limit. +4. Document the population and trust review for the applicable branch. Changing the checkbox alone does not complete this assessment; disabling member deletion is not the only CIS-permitted remediation. #### Known limitations +Only the connected organization's returned settings are assessed; this test does not enumerate every organization in an enterprise or reconstruct inherited policies. Required fields must be present and usable. Missing, null, or invalid evidence produces an explicit indeterminate Skipped result, while request and JSON parsing failures remain Error results. Missing data does not establish that a setting is disabled or that the recommendation is not applicable. Validation applies to fields available after shared JSON parsing; it is not complete raw-response schema validation. + This test verifies the organization setting only. It does not enumerate repository administrators, organization owners, or decide whether those users are trusted. #### Related links * [CIS GitHub Benchmark v1.2.0 - Section 1.2.3](https://www.cisecurity.org/benchmark/github) -* [GitHub REST API: Get an organization](https://docs.github.com/en/rest/orgs/orgs#get-an-organization) +* [GitHub REST API: Get an organization](https://docs.github.com/en/enterprise-cloud@latest/rest/orgs/orgs?apiVersion=2026-03-10#get-an-organization) +* [GitHub: Repository deletion and transfer permissions](https://docs.github.com/en/enterprise-cloud@latest/organizations/managing-organization-settings/setting-permissions-for-deleting-or-transferring-repositories) %TestResult% diff --git a/tests/cis/Test.CIS.GH.1.2.3.ps1 b/tests/cis/Test.CIS.GH.1.2.3.ps1 index 3b33732a3b..31f571d246 100644 --- a/tests/cis/Test.CIS.GH.1.2.3.ps1 +++ b/tests/cis/Test.CIS.GH.1.2.3.ps1 @@ -13,7 +13,8 @@ .EXAMPLE Test-MtCisGitHubRepositoryDeletionLimited - Returns Investigate when the GitHub organization setting is available. + Returns Investigate when the GitHub organization setting is a Boolean; + unusable evidence is indeterminate. .LINK https://maester.dev/docs/commands/Test-MtCisGitHubRepositoryDeletionLimited @@ -41,27 +42,34 @@ $org = Get-MtGitHubOrganization $field = 'members_can_delete_repositories' if (-not (Test-MtGitHubObjectProperty -InputObject $org -PropertyName $field)) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "GitHub organization response did not include required field '$field'. This field is required to evaluate CIS.GH.1.2.3 and may be missing because of permissions, plan, API version, or organization type." + Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Indeterminate: GitHub organization response did not include required field '$field'. This field is required to evaluate CIS.GH.1.2.3 and may be missing because of permissions, plan, API version, or organization type." + return $null + } + + if ($org.$field -isnot [bool]) { + Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Indeterminate: GitHub organization field '$field' must be a Boolean to evaluate CIS.GH.1.2.3. No configuration verdict was produced." return $null } $resultMarkdown = @" CIS.GH.1.2.3 automated evidence from ``GET /orgs/{org}``. -| Field | Actual | Expected | -| --- | --- | --- | -| ``$field`` | ``$($org.$field)`` | ``False`` | +| Field | Actual | +| --- | --- | +| ``$field`` | ``$($org.$field)`` | + +Partial evidence only: this setting does not establish CIS compliance. The administrator/owner population and trust review below remains unassessed. "@ if ($org.$field -eq $true) { $resultMarkdown += @" -Manual review required - ``members_can_delete_repositories`` is true. CIS GH 1.2.3 audit requires verifying repository admin members are trusted and qualified; document the review. +Manual review required - ``members_can_delete_repositories`` is true. For CIS GH 1.2.3, verify that every repository has exactly two repository administrators, both trusted and qualified; document the population and trust review. "@ } else { $resultMarkdown += @" -Manual review required - ``members_can_delete_repositories`` is false. CIS GH 1.2.3 audit still requires verifying organization owners are trusted and qualified; document the review. +Manual review required - ``members_can_delete_repositories`` is false. For CIS GH 1.2.3, verify that there are only a few organization owners, all trusted and qualified; document the population and trust review. CIS does not specify a numeric owner limit. "@ } diff --git a/tests/cis/Test.CIS.GH.1.2.4.md b/tests/cis/Test.CIS.GH.1.2.4.md index 39ec355518..2c4e7d4cd3 100644 --- a/tests/cis/Test.CIS.GH.1.2.4.md +++ b/tests/cis/Test.CIS.GH.1.2.4.md @@ -16,7 +16,7 @@ Members without the required repository or organization role will not be able to CIS marks this recommendation as Manual. This Maester test collects the organization setting evidence that maps to CIS GH 1.2.4, then reports Investigate because CIS still requires a human trust review. -When `members_can_delete_issues` is `true`, CIS requires verifying that repository admin members are trusted and qualified. When it is `false`, CIS still requires verifying that organization owners are trusted and qualified. +When `members_can_delete_issues` is `true`, the CIS review requires exactly two trusted and qualified administrators in every repository. When it is `false`, the CIS review requires only a few organization owners, all trusted and qualified; it does not set a numeric owner limit. These are the benchmark's remaining human-review branches, not a complete authorization model derived from this flag. #### API evidence @@ -24,24 +24,32 @@ Endpoint: `GET /orgs/{org}` Evidence field: `members_can_delete_issues` -When this field is returned, the test records the actual value and returns Investigate so the remaining CIS manual review path is visible in Maester results. +An actual Boolean value is recorded as partial evidence and produces Investigate for either value. The result does not declare CIS compliance or noncompliance. A missing, null, or non-Boolean value instead produces an explicit indeterminate Skipped result. #### Permissions required -GitHub requires organization-owner visibility for full organization details. Use `Connect-MtGitHub` with a classic PAT that has `admin:org`, or a fine-grained PAT with organization Members read and Administration read permissions. +For full organization settings, GitHub documents an organization owner using a classic PAT or OAuth token with `admin:org`. `Connect-MtGitHub` checks active organization membership; fine-grained PATs require organization Members read permission for that probe. Its separate Actions-permission probe uses organization Administration read permission, but neither that probe nor a successful connection guarantees that the required settings are returned. -#### Remediation summary +Use the API host and token appropriate to the deployment. GHE.com requires an authenticated request to `api.SUBDOMAIN.ghe.com`; use a host-appropriate manual token rather than assuming the github.com device flow applies. Missing required evidence remains indeterminate on standard GHEC, Enterprise Managed Users, and GHE.com. -In the organization settings, open **Member privileges** and disable the option that allows members to delete issues for the organization. If the setting remains enabled, manually verify that repository administrators are limited to trusted users and document the review. If the setting is disabled, verify that organization owners are limited to trusted users and document the review. +#### Remediation action + +1. On github.com, open [your organizations](https://github.com/settings/organizations), select the organization, then open **Settings** > **Access** > **Member privileges** and review **Issue deletion**; see [GitHub's issue-deletion guidance](https://docs.github.com/en/enterprise-cloud@latest/organizations/managing-organization-settings/allowing-people-to-delete-issues-in-your-organization). +2. If member deletion is enabled, review **Settings** > **Collaborators & teams** in every repository. Review and adjust administrator access so that exactly two repository administrators remain, both trusted and qualified. +3. If member deletion is disabled, follow the CIS review branch by reviewing the organization's **People** page filtered to **Owners**. Review and adjust access so only a few trusted and qualified owners remain; CIS does not specify a numeric owner limit. +4. Document the population and trust review for the applicable branch. Changing the checkbox alone does not complete this assessment; disabling member deletion is not the only CIS-permitted remediation. #### Known limitations +Only the connected organization's returned settings are assessed; this test does not enumerate every organization in an enterprise or reconstruct inherited policies. Required fields must be present and usable. Missing, null, or invalid evidence produces an explicit indeterminate Skipped result, while request and JSON parsing failures remain Error results. Missing data does not establish that a setting is disabled or that the recommendation is not applicable. Validation applies to fields available after shared JSON parsing; it is not complete raw-response schema validation. + This test verifies the organization setting only. It does not enumerate repository administrators, organization owners, or decide whether those users are trusted. #### Related links * [CIS GitHub Benchmark v1.2.0 - Section 1.2.4](https://www.cisecurity.org/benchmark/github) -* [GitHub REST API: Get an organization](https://docs.github.com/en/rest/orgs/orgs#get-an-organization) +* [GitHub REST API: Get an organization](https://docs.github.com/en/enterprise-cloud@latest/rest/orgs/orgs?apiVersion=2026-03-10#get-an-organization) +* [GitHub: Issue deletion permissions](https://docs.github.com/en/enterprise-cloud@latest/organizations/managing-organization-settings/allowing-people-to-delete-issues-in-your-organization) %TestResult% diff --git a/tests/cis/Test.CIS.GH.1.2.4.ps1 b/tests/cis/Test.CIS.GH.1.2.4.ps1 index 6debaebf70..8ab7bb63b0 100644 --- a/tests/cis/Test.CIS.GH.1.2.4.ps1 +++ b/tests/cis/Test.CIS.GH.1.2.4.ps1 @@ -13,7 +13,8 @@ .EXAMPLE Test-MtCisGitHubIssueDeletionLimited - Returns Investigate when the GitHub organization setting is available. + Returns Investigate when the GitHub organization setting is a Boolean; + unusable evidence is indeterminate. .LINK https://maester.dev/docs/commands/Test-MtCisGitHubIssueDeletionLimited @@ -41,27 +42,34 @@ $org = Get-MtGitHubOrganization $field = 'members_can_delete_issues' if (-not (Test-MtGitHubObjectProperty -InputObject $org -PropertyName $field)) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "GitHub organization response did not include required field '$field'. This field is required to evaluate CIS.GH.1.2.4 and may be missing because of permissions, plan, API version, or organization type." + Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Indeterminate: GitHub organization response did not include required field '$field'. This field is required to evaluate CIS.GH.1.2.4 and may be missing because of permissions, plan, API version, or organization type." + return $null + } + + if ($org.$field -isnot [bool]) { + Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Indeterminate: GitHub organization field '$field' must be a Boolean to evaluate CIS.GH.1.2.4. No configuration verdict was produced." return $null } $resultMarkdown = @" CIS.GH.1.2.4 automated evidence from ``GET /orgs/{org}``. -| Field | Actual | Expected | -| --- | --- | --- | -| ``$field`` | ``$($org.$field)`` | ``False`` | +| Field | Actual | +| --- | --- | +| ``$field`` | ``$($org.$field)`` | + +Partial evidence only: this setting does not establish CIS compliance. The administrator/owner population and trust review below remains unassessed. "@ if ($org.$field -eq $true) { $resultMarkdown += @" -Manual review required - ``members_can_delete_issues`` is true. CIS GH 1.2.4 audit requires verifying repository admin members are trusted and qualified; document the review. +Manual review required - ``members_can_delete_issues`` is true. For CIS GH 1.2.4, verify that every repository has exactly two repository administrators, both trusted and qualified; document the population and trust review. "@ } else { $resultMarkdown += @" -Manual review required - ``members_can_delete_issues`` is false. CIS GH 1.2.4 audit still requires verifying organization owners are trusted and qualified; document the review. +Manual review required - ``members_can_delete_issues`` is false. For CIS GH 1.2.4, verify that there are only a few organization owners, all trusted and qualified; document the population and trust review. CIS does not specify a numeric owner limit. "@ } diff --git a/tests/cis/Test.CIS.GH.1.3.2.md b/tests/cis/Test.CIS.GH.1.3.2.md index 6c899eec3b..26796aae7e 100644 --- a/tests/cis/Test.CIS.GH.1.3.2.md +++ b/tests/cis/Test.CIS.GH.1.3.2.md @@ -22,24 +22,31 @@ Endpoint: `GET /orgs/{org}` Evidence field: `members_can_create_teams` -The test passes when `members_can_create_teams` is `false`. +The field must be a Boolean value. The test passes when it is `false` and fails when it is `true`. #### Permissions required -GitHub requires organization-owner visibility for full organization details. Use `Connect-MtGitHub` with a classic PAT that has `admin:org`, or a fine-grained PAT with organization Members read and Administration read permissions. +For full organization settings, GitHub documents an organization owner using a classic PAT or OAuth token with `admin:org`. `Connect-MtGitHub` checks active organization membership; fine-grained PATs require organization Members read permission for that probe. Its separate Actions-permission probe uses organization Administration read permission, but neither that probe nor a successful connection guarantees that the required settings are returned. -#### Remediation summary +Use the API host and token appropriate to the deployment. GHE.com requires an authenticated request to `api.SUBDOMAIN.ghe.com`; use a host-appropriate manual token rather than assuming the github.com device flow applies. Missing required evidence remains indeterminate on standard GHEC, Enterprise Managed Users, and GHE.com. -In the organization settings, open **Member privileges** and disable **Allow members to create teams**. +#### Remediation action + +1. On github.com, open [your organizations](https://github.com/settings/organizations), select the organization, then open **Settings** > **Access** > **Member privileges**; see [GitHub's team-creation guidance](https://docs.github.com/en/enterprise-cloud@latest/organizations/managing-organization-settings/setting-team-creation-permissions-in-your-organization). +2. Under **Team creation rules**, clear **Allow members to create teams**. +3. Save the change and use the organization's approved process for new-team requests. #### Known limitations +Only the connected organization's returned settings are assessed; this test does not enumerate every organization in an enterprise or reconstruct inherited policies. Required fields must be present and usable. Missing, null, or invalid evidence produces an explicit indeterminate Skipped result, while request and JSON parsing failures remain Error results. Missing data does not establish that a setting is disabled or that the recommendation is not applicable. Validation applies to fields available after shared JSON parsing; it is not complete raw-response schema validation. + This test verifies the organization-level team creation setting. It does not review custom operational processes for who may request or approve new teams. #### Related links * [CIS GitHub Benchmark v1.2.0 - Section 1.3.2](https://www.cisecurity.org/benchmark/github) -* [GitHub REST API: Get an organization](https://docs.github.com/en/rest/orgs/orgs#get-an-organization) +* [GitHub REST API: Get an organization](https://docs.github.com/en/enterprise-cloud@latest/rest/orgs/orgs?apiVersion=2026-03-10#get-an-organization) +* [GitHub: Team creation permissions](https://docs.github.com/en/enterprise-cloud@latest/organizations/managing-organization-settings/setting-team-creation-permissions-in-your-organization) %TestResult% diff --git a/tests/cis/Test.CIS.GH.1.3.2.ps1 b/tests/cis/Test.CIS.GH.1.3.2.ps1 index a98cded8fd..44b1c65c1d 100644 --- a/tests/cis/Test.CIS.GH.1.3.2.ps1 +++ b/tests/cis/Test.CIS.GH.1.3.2.ps1 @@ -40,12 +40,24 @@ $org = Get-MtGitHubOrganization $field = 'members_can_create_teams' if (-not (Test-MtGitHubObjectProperty -InputObject $org -PropertyName $field)) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "GitHub organization response did not include required field '$field'. This field is required to evaluate CIS.GH.1.3.2 and may be missing because of permissions, plan, API version, or organization type." + Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Indeterminate: GitHub organization response did not include required field '$field'. This field is required to evaluate CIS.GH.1.3.2 and may be missing because of permissions, plan, API version, or organization type." + return $null + } + + if ($org.$field -isnot [bool]) { + Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Indeterminate: GitHub organization field '$field' must be a Boolean to evaluate CIS.GH.1.3.2. No configuration verdict was produced." return $null } $result = $org.$field -eq $false + $resultSummary = if ($result) { + 'Well done. Members cannot create teams.' + } else { + 'Members can create teams. Disable Allow members to create teams in organization Member privileges.' + } $resultMarkdown = @" +$resultSummary + CIS.GH.1.3.2 automated evidence from ``GET /orgs/{org}``. | Field | Actual | Expected | diff --git a/tests/cis/Test.CIS.GH.1.3.8.md b/tests/cis/Test.CIS.GH.1.3.8.md index b5405218b5..298cd791d3 100644 --- a/tests/cis/Test.CIS.GH.1.3.8.md +++ b/tests/cis/Test.CIS.GH.1.3.8.md @@ -22,24 +22,31 @@ Endpoint: `GET /orgs/{org}` Evidence field: `default_repository_permission` -The test passes when `default_repository_permission` is `none` or `read`. It fails when the value is `write` or `admin`. +The field must be a recognized string value. The test passes for `none` or `read` and fails for `write` or `admin`, retaining case-insensitive matching. Null, empty, unrecognized, or non-string values are indeterminate rather than evidence of excessive access. #### Permissions required -GitHub requires organization-owner visibility for full organization details. Use `Connect-MtGitHub` with a classic PAT that has `admin:org`, or a fine-grained PAT with organization Members read and Administration read permissions. +For full organization settings, GitHub documents an organization owner using a classic PAT or OAuth token with `admin:org`. `Connect-MtGitHub` checks active organization membership; fine-grained PATs require organization Members read permission for that probe. Its separate Actions-permission probe uses organization Administration read permission, but neither that probe nor a successful connection guarantees that the required settings are returned. -#### Remediation summary +Use the API host and token appropriate to the deployment. GHE.com requires an authenticated request to `api.SUBDOMAIN.ghe.com`; use a host-appropriate manual token rather than assuming the github.com device flow applies. Missing required evidence remains indeterminate on standard GHEC, Enterprise Managed Users, and GHE.com. -In the organization settings, open **Member privileges** and set **Base permissions** to **None** or **Read**. +#### Remediation action + +1. Plan explicit repository or team access for members who need to contribute after the default changes. Coordinate those grants with the relevant repository owners. +2. On github.com, open [your organizations](https://github.com/settings/organizations), select the organization, then open **Settings** > **Access** > **Member privileges**; see [GitHub's base-permission guidance](https://docs.github.com/en/enterprise-cloud@latest/organizations/managing-user-access-to-your-organizations-repositories/managing-repository-roles/setting-base-permissions-for-an-organization). +3. Set **Base permissions** to **None** or **Read**, review the changes, and confirm the default-permission change. #### Known limitations +Only the connected organization's returned settings are assessed; this test does not enumerate every organization in an enterprise or reconstruct inherited policies. Required fields must be present and usable. Missing, null, or invalid evidence produces an explicit indeterminate Skipped result, while request and JSON parsing failures remain Error results. Missing data does not establish that a setting is disabled or that the recommendation is not applicable. Validation applies to fields available after shared JSON parsing; it is not complete raw-response schema validation. + This test verifies the organization default repository permission only. It does not review per-repository collaborators, teams, or custom access grants. #### Related links * [CIS GitHub Benchmark v1.2.0 - Section 1.3.8](https://www.cisecurity.org/benchmark/github) -* [GitHub REST API: Get an organization](https://docs.github.com/en/rest/orgs/orgs#get-an-organization) +* [GitHub REST API: Get an organization](https://docs.github.com/en/enterprise-cloud@latest/rest/orgs/orgs?apiVersion=2026-03-10#get-an-organization) +* [GitHub: Organization base permissions](https://docs.github.com/en/enterprise-cloud@latest/organizations/managing-user-access-to-your-organizations-repositories/managing-repository-roles/setting-base-permissions-for-an-organization) %TestResult% diff --git a/tests/cis/Test.CIS.GH.1.3.8.ps1 b/tests/cis/Test.CIS.GH.1.3.8.ps1 index 179ce4216a..b25d68debb 100644 --- a/tests/cis/Test.CIS.GH.1.3.8.ps1 +++ b/tests/cis/Test.CIS.GH.1.3.8.ps1 @@ -39,14 +39,27 @@ $org = Get-MtGitHubOrganization $field = 'default_repository_permission' if (-not (Test-MtGitHubObjectProperty -InputObject $org -PropertyName $field)) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "GitHub organization response did not include required field '$field'. This field is required to evaluate CIS.GH.1.3.8 and may be missing because of permissions, plan, API version, or organization type." + Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Indeterminate: GitHub organization response did not include required field '$field'. This field is required to evaluate CIS.GH.1.3.8 and may be missing because of permissions, plan, API version, or organization type." + return $null + } + + $actual = $org.$field + $recognizedValues = @('none', 'read', 'write', 'admin') + if ($actual -isnot [string] -or $recognizedValues -notcontains $actual) { + Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Indeterminate: GitHub organization field '$field' must be a recognized permission string (none, read, write, or admin) to evaluate CIS.GH.1.3.8. No configuration verdict was produced." return $null } $allowedValues = @('none', 'read') - $actual = [string]$org.$field $result = $allowedValues -contains $actual + $resultSummary = if ($result) { + 'Well done. Organization base permissions are limited to none or read.' + } else { + 'Organization base permissions grant write or administrator access. Set Base permissions to None or Read and review explicit access grants.' + } $resultMarkdown = @" +$resultSummary + CIS.GH.1.3.8 automated evidence from ``GET /orgs/{org}``. | Field | Actual | Expected | From 50c2872eefae396b6acb4b9d43034dacc64a5cd8 Mon Sep 17 00:00:00 2001 From: Travis McDade Date: Thu, 29 Oct 2026 22:30:23 -0400 Subject: [PATCH 02/15] fix(github): assess deletion populations against approved users --- powershell/assets/MaesterSettings.psd1 | 1 + .../Get-MtCisGitHubDeletionPolicyGap.ps1 | 55 +++ .../github/Get-MtCisGitHubDeletionRoleGap.ps1 | 37 ++ .../github/Resolve-MtGitHubDeletionPolicy.ps1 | 45 +++ .../cis/github/Test-MtCisGitHubDeletion.ps1 | 117 +++++++ .../report/ConvertTo-MtMaesterResult.ps1 | 19 +- .../github/Get-MtGitHubErrorStatusCode.ps1 | 1 + .../github/Get-MtGitHubIdentityCollection.ps1 | 22 ++ .../services/github/Get-MtGitHubRateLimit.ps1 | 65 ++++ .../github/Get-MtGitHubRateLimitMessage.ps1 | 77 +---- .../Get-MtGitHubRepositoryInventory.ps1 | 26 ++ .../github/Invoke-MtGitHubGraphQLRequest.ps1 | 56 +++ .../github/Invoke-MtGitHubRateLimitGuard.ps1 | 47 +++ .../github/Invoke-MtGitHubRequest.ps1 | 162 +++++++-- .../internal/session/Clear-ModuleVariable.ps1 | 3 +- .../public/connect/Connect-MtGitHub.ps1 | 27 +- .../public/connect/Disconnect-MtGitHub.ps1 | 1 + .../functions/GitHubDeletionNative.Tests.ps1 | 118 +++++++ .../tests/functions/GitHubRateLimit.Tests.ps1 | 221 ++++++++++++ .../Invoke-MtGitHubGraphQLRequest.Tests.ps1 | 122 +++++++ .../Invoke-MtGitHubRequest.Tests.ps1 | 147 +++++++- .../functions/ResultConfigRedaction.Tests.ps1 | 84 +++++ .../Test-MtCisGitHubDeletion.Tests.ps1 | 326 ++++++++++++++++++ ...-MtCisGitHubOrganizationSettings.Tests.ps1 | 115 +----- tests/cis/Test.CIS.GH.1.2.3.md | 42 +-- tests/cis/Test.CIS.GH.1.2.3.ps1 | 57 +-- tests/cis/Test.CIS.GH.1.2.4.md | 42 +-- tests/cis/Test.CIS.GH.1.2.4.ps1 | 57 +-- .../configuration/github-deletion-policy.md | 101 ++++++ 29 files changed, 1848 insertions(+), 345 deletions(-) create mode 100644 powershell/internal/checks/cis/github/Get-MtCisGitHubDeletionPolicyGap.ps1 create mode 100644 powershell/internal/checks/cis/github/Get-MtCisGitHubDeletionRoleGap.ps1 create mode 100644 powershell/internal/checks/cis/github/Resolve-MtGitHubDeletionPolicy.ps1 create mode 100644 powershell/internal/checks/cis/github/Test-MtCisGitHubDeletion.ps1 create mode 100644 powershell/internal/services/github/Get-MtGitHubIdentityCollection.ps1 create mode 100644 powershell/internal/services/github/Get-MtGitHubRateLimit.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/internal/services/github/Invoke-MtGitHubRateLimitGuard.ps1 create mode 100644 powershell/tests/functions/GitHubDeletionNative.Tests.ps1 create mode 100644 powershell/tests/functions/GitHubRateLimit.Tests.ps1 create mode 100644 powershell/tests/functions/Invoke-MtGitHubGraphQLRequest.Tests.ps1 create mode 100644 powershell/tests/functions/ResultConfigRedaction.Tests.ps1 create mode 100644 powershell/tests/functions/Test-MtCisGitHubDeletion.Tests.ps1 create mode 100644 website/docs/configuration/github-deletion-policy.md diff --git a/powershell/assets/MaesterSettings.psd1 b/powershell/assets/MaesterSettings.psd1 index 48f21d5a73..e8331b09a5 100644 --- a/powershell/assets/MaesterSettings.psd1 +++ b/powershell/assets/MaesterSettings.psd1 @@ -9,6 +9,7 @@ DataverseEnvironmentUrl = @{ Type = 'string'; Default = ''; Sensitive = $false; Description = 'URL of the Dataverse environment that the Copilot Studio checks read.' } GitHubOrganization = @{ Type = 'string'; Default = ''; Sensitive = $false; Description = 'GitHub organization that the GitHub checks read.' } GitHubApiBaseUri = @{ Type = 'string'; Default = 'https://api.github.com'; Sensitive = $false; Description = 'Base URI of the GitHub REST API.' } + GitHubDeletionPolicy = @{ Type = 'object'; Default = @{}; Sensitive = $true; Description = 'Host and organization-bound approved owner and repository administrator IDs for GitHub deletion assessments.' } GitHubApiVersion = @{ Type = 'string'; Default = '2022-11-28'; Sensitive = $false; Description = 'GitHub REST API version.' } } } diff --git a/powershell/internal/checks/cis/github/Get-MtCisGitHubDeletionPolicyGap.ps1 b/powershell/internal/checks/cis/github/Get-MtCisGitHubDeletionPolicyGap.ps1 new file mode 100644 index 0000000000..698f69ca1f --- /dev/null +++ b/powershell/internal/checks/cis/github/Get-MtCisGitHubDeletionPolicyGap.ps1 @@ -0,0 +1,55 @@ +function Get-MtCisGitHubDeletionPolicyGap { + <# + .SYNOPSIS + Internal: Checks for restrictive repository policies before failing an administrator baseline. + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory)] [string] $Organization, + [Parameter(Mandatory)] [string] $Repository, + [Parameter(Mandatory)] [string] $RepositoryId + ) + $query = @' +query DeletionPolicies($org:String!,$repo:String!,$after:String){ + repository(owner:$org,name:$repo){databaseId rulesets(first:100,after:$after,includeParents:true,targets:[REPOSITORY]){ + totalCount pageInfo{hasNextPage endCursor} nodes{ + id target enforcement + } + }} +} +'@ + $cursor = $null + $seenCursors = [System.Collections.Generic.HashSet[string]]::new() + $count = 0 + $seenPolicies = [System.Collections.Generic.HashSet[string]]::new() + $expected = $null + for ($page = 0; $page -lt 100; $page++) { + try { + $response = Invoke-MtGitHubGraphQLRequest -Query $query -OperationName DeletionPolicies -Variables @{ org = $Organization; repo = $Repository; after = $cursor } + } catch { + if ($_.Exception.Data['GitHubRateLimit']) { throw } + if ((Get-MtGitHubErrorStatusCode -ErrorRecord $_) -in 403, 404) { return 'Applicable repository-policy evidence is not visible; a restrictive alternative cannot be ruled out.' } + throw + } + $connection = $response.Data.repository.rulesets + $databaseId = $response.Data.repository.databaseId + if ($response.Errors.Count -gt 0 -or ($databaseId -isnot [int] -and $databaseId -isnot [long] -and $databaseId -isnot [bigint]) -or $databaseId -le 0 -or [string]$databaseId -cne $RepositoryId -or $null -eq $connection -or $connection.nodes -isnot [array] -or $connection.pageInfo.hasNextPage -isnot [bool] -or ($connection.totalCount -isnot [int] -and $connection.totalCount -isnot [long]) -or $connection.totalCount -lt 0) { return 'Applicable repository-policy evidence is unavailable or incomplete; a restrictive alternative cannot be ruled out.' } + if ($null -eq $expected) { $expected = $connection.totalCount } + if ($expected -ne $connection.totalCount) { return 'Applicable repository-policy population changed during collection.' } + foreach ($policy in $connection.nodes) { + if ($policy.id -isnot [string] -or [string]::IsNullOrWhiteSpace($policy.id) -or -not $seenPolicies.Add($policy.id) -or $policy.target -cne 'REPOSITORY') { return 'Applicable repository-policy identity or target is unusable.' } + if ($policy.enforcement -cnotin 'ACTIVE', 'DISABLED', 'EVALUATE') { return 'Applicable repository-policy enforcement is unavailable or unknown.' } + if ($policy.enforcement -cne 'ACTIVE') { continue } + return 'An active repository-target policy may restrict deletion; its effective restrictions, bypass membership and stronger-policy equivalence need review.' + } + $count += $connection.nodes.Count + if (-not $connection.pageInfo.hasNextPage) { + if ($count -ne $expected) { return 'Applicable repository-policy total does not match collected items.' } + return $null + } + $cursor = $connection.pageInfo.endCursor + if ($cursor -isnot [string] -or [string]::IsNullOrWhiteSpace($cursor) -or -not $seenCursors.Add($cursor)) { return 'Applicable repository-policy pagination cursor is unusable.' } + } + return 'Applicable repository-policy pagination reached the page cap.' +} diff --git a/powershell/internal/checks/cis/github/Get-MtCisGitHubDeletionRoleGap.ps1 b/powershell/internal/checks/cis/github/Get-MtCisGitHubDeletionRoleGap.ps1 new file mode 100644 index 0000000000..a5dae26cee --- /dev/null +++ b/powershell/internal/checks/cis/github/Get-MtCisGitHubDeletionRoleGap.ps1 @@ -0,0 +1,37 @@ +function Get-MtCisGitHubDeletionRoleGap { + <# + .SYNOPSIS + Internal: Qualifies whether custom role definitions extend issue deletion beyond administrators. + #> + [CmdletBinding()] + [OutputType([string])] + param([Parameter(Mandatory)] [string] $Organization) + + $encoded = [uri]::EscapeDataString($Organization) + foreach ($catalog in @(@{ Path = 'custom-repository-roles'; Key = 'custom_roles' }, @{ Path = 'organization-roles'; Key = 'roles' })) { + try { + $evidence = Invoke-MtGitHubRequest -RelativeUri "/orgs/$encoded/$($catalog.Path)" -IncludeMetadata -ApiVersion '2026-03-10' + } catch { + if ($_.Exception.Data['GitHubRateLimit']) { throw } + if ((Get-MtGitHubErrorStatusCode -ErrorRecord $_) -in 403, 404) { return 'Issue-deletion custom-role catalog is not visible to the connected account.' } + throw + } + $data = $evidence.Data + $roles = $data.($catalog.Key) + if (-not $evidence.CollectionIntegrityValid -or $evidence.ContentKind -ne 'Object' -or $roles -isnot [array] -or ($data.total_count -isnot [int] -and $data.total_count -isnot [long]) -or $data.total_count -ne $roles.Count) { + return 'Issue-deletion custom-role catalog is incomplete or has an unexpected API shape.' + } + $seen = [System.Collections.Generic.HashSet[string]]::new() + foreach ($role in $roles) { + if ($role -isnot [pscustomobject] -or ($role.id -isnot [int] -and $role.id -isnot [long] -and $role.id -isnot [bigint]) -or $role.id -le 0 -or -not $seen.Add([string]$role.id) -or $role.permissions -isnot [array] -or @($role.permissions | Where-Object { $_ -isnot [string] -or [string]::IsNullOrWhiteSpace($_) }).Count) { return 'Issue-deletion custom-role permissions or identities are unavailable or malformed.' } + if ($catalog.Key -eq 'custom_roles') { + if ($role.base_role -isnot [string] -or $role.base_role -cnotin 'read', 'triage', 'write', 'maintain') { return 'Issue-deletion custom repository role has an unavailable or unknown base role.' } + } elseif ($null -ne $role.base_role -and ($role.base_role -isnot [string] -or $role.base_role -cnotin 'none', 'read', 'triage', 'write', 'maintain', 'admin')) { + return 'Issue-deletion organization role has an unknown base role.' + } + # Additional issue-deletion grants require assignment evidence beyond the administrator population. + if (@($role.permissions | Where-Object { $_ -match '(?i)(delete.*issue|issue.*delete)' }).Count) { return 'A custom role can grant issue deletion; its effective assignments and policy restrictions need review.' } + } + } + return $null +} diff --git a/powershell/internal/checks/cis/github/Resolve-MtGitHubDeletionPolicy.ps1 b/powershell/internal/checks/cis/github/Resolve-MtGitHubDeletionPolicy.ps1 new file mode 100644 index 0000000000..977b3b2fd3 --- /dev/null +++ b/powershell/internal/checks/cis/github/Resolve-MtGitHubDeletionPolicy.ps1 @@ -0,0 +1,45 @@ +function Resolve-MtGitHubDeletionPolicy { + <# + .SYNOPSIS + Internal: Validates the assessor's GitHub deletion approval configuration and target binding. + #> + [CmdletBinding()] + param([Parameter(Mandatory)] [object] $Organization) + + $policy = Get-MtSetting -Name GitHubDeletionPolicy -Verbose:$false + if ($null -eq $policy -or ($policy -is [System.Collections.IDictionary] -and $policy.Count -eq 0) -or ($policy -is [pscustomobject] -and @($policy.PSObject.Properties).Count -eq 0)) { return $null } + if ($policy -isnot [pscustomobject]) { throw 'GitHubDeletionPolicy must be a JSON object.' } + $allowed = 'ApiBaseUri', 'OrganizationId', 'ApprovedOwnerIds', 'CompleteRepositoryInventory', 'Repositories' + foreach ($property in $policy.PSObject.Properties.Name) { + if ($property -notin $allowed) { throw 'GitHubDeletionPolicy contains an unknown property.' } + } + $base = $__MtSession.GitHubConnection.ApiBaseUri.TrimEnd('/') + if ($policy.ApiBaseUri -isnot [string] -or $policy.ApiBaseUri.TrimEnd('/') -cne $base) { throw 'GitHubDeletionPolicy.ApiBaseUri must match the connected API base URI.' } + $idPattern = '^[1-9][0-9]*$' + if ($policy.OrganizationId -isnot [string] -or $policy.OrganizationId -cnotmatch $idPattern) { throw 'GitHubDeletionPolicy.OrganizationId must be a positive decimal ID string.' } + if (($Organization.id -isnot [int] -and $Organization.id -isnot [long] -and $Organization.id -isnot [bigint]) -or $Organization.id -le 0) { throw 'GitHub organization identity is unavailable or unusable.' } + if ($policy.OrganizationId -cne [string]$Organization.id) { throw 'GitHubDeletionPolicy.OrganizationId does not match the connected organization.' } + foreach ($name in 'ApprovedOwnerIds') { + if (-not $policy.PSObject.Properties[$name]) { continue } + if ($policy.$name -isnot [array]) { throw "GitHubDeletionPolicy.$name must be an array of positive decimal ID strings." } + $seen = [System.Collections.Generic.HashSet[string]]::new() + foreach ($id in $policy.$name) { + if ($id -isnot [string] -or $id -cnotmatch $idPattern -or -not $seen.Add($id)) { throw "GitHubDeletionPolicy.$name contains an invalid or duplicate ID." } + } + } + if ($policy.PSObject.Properties['CompleteRepositoryInventory'] -and $policy.CompleteRepositoryInventory -isnot [bool]) { throw 'GitHubDeletionPolicy.CompleteRepositoryInventory must be Boolean.' } + if ($policy.PSObject.Properties['Repositories']) { + if ($policy.Repositories -isnot [array]) { throw 'GitHubDeletionPolicy.Repositories must be an array.' } + $seenRepositories = [System.Collections.Generic.HashSet[string]]::new() + foreach ($repository in $policy.Repositories) { + if ($repository -isnot [pscustomobject] -or $repository.Id -isnot [string] -or $repository.Id -cnotmatch $idPattern -or -not $seenRepositories.Add($repository.Id)) { throw 'GitHubDeletionPolicy.Repositories contains an invalid or duplicate repository ID.' } + if (@($repository.PSObject.Properties.Name | Where-Object { $_ -notin 'Id', 'ApprovedAdministratorIds' }).Count) { throw 'A GitHubDeletionPolicy repository contains an unknown property.' } + if ($repository.ApprovedAdministratorIds -isnot [array]) { throw 'Each GitHubDeletionPolicy repository needs ApprovedAdministratorIds as an array.' } + $seenUsers = [System.Collections.Generic.HashSet[string]]::new() + foreach ($id in $repository.ApprovedAdministratorIds) { + if ($id -isnot [string] -or $id -cnotmatch $idPattern -or -not $seenUsers.Add($id)) { throw 'ApprovedAdministratorIds contains an invalid or duplicate ID.' } + } + } + } + return $policy +} diff --git a/powershell/internal/checks/cis/github/Test-MtCisGitHubDeletion.ps1 b/powershell/internal/checks/cis/github/Test-MtCisGitHubDeletion.ps1 new file mode 100644 index 0000000000..a53bb4edd9 --- /dev/null +++ b/powershell/internal/checks/cis/github/Test-MtCisGitHubDeletion.ps1 @@ -0,0 +1,117 @@ +function Test-MtCisGitHubDeletion { + <# + .SYNOPSIS + Internal: Assesses the configured owner or repository-administrator deletion branch. + #> + [CmdletBinding()] + [OutputType([bool])] + param( + [Parameter(Mandatory)] [ValidateSet('Repository', 'Issue')] [string] $Kind, + [ValidateRange(1, 3)] [int] $MaximumOrganizationOwners = 3 + ) + if (-not $__MtSession.GitHubConnection -or $__MtSession.GitHubConnection.Connected -ne $true) { throw 'Not connected to GitHub. Call Connect-MtGitHub first.' } + $organization = $__MtSession.GitHubConnection.Organization + $encoded = [uri]::EscapeDataString($organization) + $evidence = Invoke-MtGitHubRequest -RelativeUri "/orgs/$encoded" -IncludeMetadata -ApiVersion '2026-03-10' + $org = $evidence.Data + $field = if ($Kind -eq 'Repository') { 'members_can_delete_repositories' } else { 'members_can_delete_issues' } + if (-not $evidence.CollectionIntegrityValid -or $evidence.ContentKind -ne 'Object' -or $org -isnot [pscustomobject] -or $org.$field -isnot [bool]) { + Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Indeterminate: required GitHub organization field '$field' is unavailable, incomplete or not Boolean." + return $null + } + if (($org.id -isnot [int] -and $org.id -isnot [long] -and $org.id -isnot [bigint]) -or $org.id -le 0) { + Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason 'Indeterminate: required GitHub organization identity is unavailable or unusable.' + return $null + } + $policy = Resolve-MtGitHubDeletionPolicy -Organization $org + if ($null -eq $policy) { + Add-MtTestResultDetail -Investigate -Result "Configure GlobalSettings.GitHubDeletionPolicy with the users approved as trusted and qualified. The observed $field value is $($org.$field); no approval population was supplied." + return $null + } + $heading = "Organization setting ``$field``: ``$($org.$field)``.`n`n" + if (-not $org.$field) { + if (-not $policy.PSObject.Properties['ApprovedOwnerIds'] -or $policy.ApprovedOwnerIds.Count -eq 0) { + Add-MtTestResultDetail -Investigate -Result ($heading + 'Configure ApprovedOwnerIds for the organization-owner branch.') + return $null + } + $owners = Get-MtGitHubIdentityCollection -RelativeUri "/orgs/$encoded/members?role=admin" -Label 'Organization owner' + if (-not $owners.Complete -or $owners.Items.Count -eq 0) { + $reason = if (-not $owners.Complete) { $owners.Gap } else { 'The organization-owner collection is unexpectedly empty.' } + Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason ("Indeterminate: " + $reason) + return $null + } + $unapproved = @($owners.Items | Where-Object { [string]$_.id -cnotin $policy.ApprovedOwnerIds }) + $result = $owners.Items.Count -le $MaximumOrganizationOwners -and $unapproved.Count -eq 0 + $message = if ($result) { 'Well done. The complete organization-owner population is within the configured maximum and every owner is approved as trusted and qualified.' } else { 'Review organization owners: remove unnecessary owner assignments or explicitly approve trusted and qualified owners. Keep the live population within the configured maximum.' } + $details = "| Live owners | Maximum | Unapproved owners |`n| --- | --- | --- |`n| $($owners.Items.Count) | $MaximumOrganizationOwners | $($unapproved.Count) |" + if ($unapproved.Count) { $details += "`n`nUnapproved observed owner IDs: " + (($unapproved | ForEach-Object { [string]$_.id }) -join ', ') + '.' } + Add-MtTestResultDetail -Result ($message + "`n`n" + $heading + $details + "`n`nThe maximum is a Maester policy choice (default 3, configurable from 1 to 3); CIS does not define a numeric value for 'few'. Unassigned approval entries do not affect the live count.") + return $result + } + if ($policy.CompleteRepositoryInventory -ne $true -or -not $policy.PSObject.Properties['Repositories']) { + Add-MtTestResultDetail -Investigate -Result ($heading + 'Declare CompleteRepositoryInventory and approve administrators for every organization repository before assessing the administrator branch.') + return $null + } + $inventory = Get-MtGitHubRepositoryInventory + if ($inventory.Issues.Count -gt 0) { + Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason ('Indeterminate: organization repository inventory. ' + ($inventory.Issues -join ' ')) + return $null + } + if ($inventory.Repositories.Count -eq 0) { + Add-MtTestResultDetail -Investigate -Result ($heading + 'No repositories were visible. This does not establish a complete organization inventory or a not-applicable result.') + return $null + } + $declared = @{} + foreach ($entry in $policy.Repositories) { $declared[$entry.Id] = $entry } + $liveIds = @($inventory.Repositories | ForEach-Object { [string]$_.id }) + if (@($liveIds | Where-Object { -not $declared.ContainsKey($_) }).Count -or @($declared.Keys | Where-Object { $_ -cnotin $liveIds }).Count) { + Add-MtTestResultDetail -Investigate -Result ($heading + 'The declared repository IDs and the complete live inventory do not match. Reconcile missing, inaccessible, newly created or removed repositories; no exclusions are supported.') + return $null + } + if (@($policy.Repositories | Where-Object { $_.ApprovedAdministratorIds.Count -eq 0 }).Count) { + Add-MtTestResultDetail -Investigate -Result ($heading + 'Configure a nonempty ApprovedAdministratorIds roster for every repository. Empty approval rosters do not establish an assessed trust decision.') + return $null + } + $rows = [System.Collections.Generic.List[string]]::new() + $violations = [System.Collections.Generic.List[object]]::new() + foreach ($repository in $inventory.Repositories) { + $name = [uri]::EscapeDataString($repository.name) + $collaborators = Get-MtGitHubIdentityCollection -RelativeUri "/repos/$encoded/$name/collaborators?affiliation=all" -Label 'Repository collaborator' + if (-not $collaborators.Complete -or $collaborators.Items.Count -eq 0 -or @($collaborators.Items | Where-Object { $_.permissions.admin -isnot [bool] }).Count) { + $reason = if (-not $collaborators.Complete) { $collaborators.Gap } elseif ($collaborators.Items.Count -eq 0) { 'The effective collaborator collection is unexpectedly empty; organization-owner access should be represented.' } else { 'Required collaborator permissions.admin is missing or not Boolean.' } + Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason ("Indeterminate: " + $reason) + return $null + } + $administrators = @($collaborators.Items | Where-Object { $_.permissions.admin -eq $true }) + $unapproved = @($administrators | Where-Object { [string]$_.id -cnotin $declared[[string]$repository.id].ApprovedAdministratorIds }) + $conforms = $administrators.Count -eq 2 -and $unapproved.Count -eq 0 + $unapprovedIds = ($unapproved | ForEach-Object { [string]$_.id }) -join ', ' + $rows.Add("| $(Get-MtSafeMarkdown $repository.name) | $($administrators.Count) | $($unapproved.Count) | $unapprovedIds | $(if ($conforms) { 'Meets baseline' } else { 'Needs review' }) |") + if (-not $conforms) { $violations.Add($repository) } + } + $table = "| Repository | Effective administrators | Unapproved | Unapproved observed user IDs | Assessment |`n| --- | --- | --- | --- | --- |`n" + ($rows -join "`n") + if ($Kind -eq 'Issue' -and $violations.Count -eq 0) { + $roleGap = Get-MtCisGitHubDeletionRoleGap -Organization $organization + if ($roleGap) { + Add-MtTestResultDetail -Investigate -Result ($heading + $table + "`n`n" + $roleGap) + return $null + } + } + $policyGaps = [System.Collections.Generic.List[string]]::new() + $confirmedViolations = 0 + if ($Kind -eq 'Repository') { + foreach ($repository in $violations) { + $gap = Get-MtCisGitHubDeletionPolicyGap -Organization $organization -Repository $repository.name -RepositoryId ([string]$repository.id) + if ($gap) { $policyGaps.Add("$(Get-MtSafeMarkdown $repository.name): $gap") } else { $confirmedViolations++ } + } + if ($violations.Count -gt 0 -and $confirmedViolations -eq 0) { + Add-MtTestResultDetail -Investigate -Result ($heading + $table + "`n`n" + (($policyGaps | Select-Object -Unique) -join "`n`n")) + return $null + } + } + $result = $violations.Count -eq 0 + $message = if ($result) { 'Well done. Every repository in the declared complete organization inventory has exactly two effective administrators, both approved as trusted and qualified.' } else { 'Review repository administrator access: at least one repository does not have exactly two effective administrators, both approved as trusted and qualified.' } + $coverage = if ($policyGaps.Count) { "`n`nAdditional repositories remain unresolved: " + (($policyGaps | Select-Object -Unique) -join ' ') } else { '' } + Add-MtTestResultDetail -Result ($message + "`n`n" + $heading + $table + $coverage + "`n`nEffective administrator permissions include inherited grants. This assessment uses the configured approvals; it does not independently determine a person’s trust or qualifications. No issue was deleted or sampled.") + return $result +} diff --git a/powershell/internal/report/ConvertTo-MtMaesterResult.ps1 b/powershell/internal/report/ConvertTo-MtMaesterResult.ps1 index 1b31405b4a..6059781ddd 100644 --- a/powershell/internal/report/ConvertTo-MtMaesterResult.ps1 +++ b/powershell/internal/report/ConvertTo-MtMaesterResult.ps1 @@ -674,10 +674,23 @@ function New-MtResultConfig { ) if ($null -eq $RunConfig) { return $null } - if ($NativeRows.Count -eq 0) { return $RunConfig } + # Configuration is JSON-shaped, as normalized by Resolve-MtRunConfig. Detach every nested value + # before redaction so reporting cannot change caller input or settings still used by checks. + $detached = $RunConfig | ConvertTo-Json -Depth 100 | ConvertFrom-Json -NoEnumerate + if (-not $script:__MtSettingsRegistry) { + $script:__MtSettingsRegistry = Import-PowerShellDataFile -Path (Join-Path $ExecutionContext.SessionState.Module.ModuleBase 'assets/MaesterSettings.psd1') + } + if ($detached.PSObject.Properties['GlobalSettings'] -and $null -ne $detached.GlobalSettings) { + foreach ($key in $script:__MtSettingsRegistry.Settings.Keys) { + if ($script:__MtSettingsRegistry.Settings[$key].Sensitive -and $detached.GlobalSettings.PSObject.Properties[$key]) { + $detached.GlobalSettings.$key = '' + } + } + } + if ($NativeRows.Count -eq 0) { return $detached } $copy = [pscustomobject]@{} - foreach ($p in $RunConfig.PSObject.Properties) { + foreach ($p in $detached.PSObject.Properties) { if ($p.Name -in 'TestSettings', 'TestSettingsHash') { continue } $copy | Add-Member -NotePropertyName $p.Name -NotePropertyValue $p.Value } @@ -687,7 +700,7 @@ function New-MtResultConfig { $entry = [ordered]@{ Id = $row.Id; Title = $row.Title; Severity = $row.Severity } $default = if ($row.ParentId -and $catalog.ContainsKey($row.ParentId)) { $catalog[$row.ParentId].Severity } elseif ($catalog.ContainsKey($row.Id)) { $catalog[$row.Id].Severity } else { $null } if ($default) { $entry.DefaultSeverity = $default } - $user = if ($RunConfig.TestSettingsHash -and $RunConfig.TestSettingsHash.ContainsKey($row.Id)) { $RunConfig.TestSettingsHash[$row.Id] } else { $null } + $user = if ($detached.TestSettingsHash) { $detached.TestSettingsHash.PSObject.Properties[$row.Id].Value } else { $null } if ($user) { foreach ($p in $user.PSObject.Properties) { if ($p.Name -notin 'Id', 'Title', 'Severity') { $entry[$p.Name] = $p.Value } } } diff --git a/powershell/internal/services/github/Get-MtGitHubErrorStatusCode.ps1 b/powershell/internal/services/github/Get-MtGitHubErrorStatusCode.ps1 index d1769dfc2a..32a3ade15a 100644 --- a/powershell/internal/services/github/Get-MtGitHubErrorStatusCode.ps1 +++ b/powershell/internal/services/github/Get-MtGitHubErrorStatusCode.ps1 @@ -8,6 +8,7 @@ $null for transport failures where no HTTP response was produced. #> param([Parameter(Mandatory)] $ErrorRecord) + if ($ErrorRecord.Exception.Data['GitHubRateLimit']) { return $ErrorRecord.Exception.Data['GitHubRateLimit'].HttpStatus } try { if ($ErrorRecord.Exception.Response -and $ErrorRecord.Exception.Response.StatusCode) { return [int]$ErrorRecord.Exception.Response.StatusCode diff --git a/powershell/internal/services/github/Get-MtGitHubIdentityCollection.ps1 b/powershell/internal/services/github/Get-MtGitHubIdentityCollection.ps1 new file mode 100644 index 0000000000..6461fd8de4 --- /dev/null +++ b/powershell/internal/services/github/Get-MtGitHubIdentityCollection.ps1 @@ -0,0 +1,22 @@ +function Get-MtGitHubIdentityCollection { + <# + .SYNOPSIS + Internal: Collects and validates a bounded GitHub REST identity collection. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] [string] $RelativeUri, + [Parameter(Mandatory)] [string] $Label + ) + $evidence = Invoke-MtGitHubRequest -RelativeUri $RelativeUri -Paginate -IncludeMetadata -ApiVersion '2026-03-10' -MaxPages 100 + if (-not $evidence.CollectionIntegrityValid -or -not $evidence.PaginationComplete -or $evidence.ContentKind -ne 'Array' -or $evidence.Data -isnot [array]) { + return [pscustomobject]@{ Complete = $false; Items = @(); Gap = "$Label collection is incomplete or has an unexpected API shape." } + } + $seen = [System.Collections.Generic.HashSet[string]]::new() + foreach ($item in $evidence.Data) { + if ($item -isnot [pscustomobject] -or ($item.id -isnot [int] -and $item.id -isnot [long] -and $item.id -isnot [bigint]) -or $item.id -le 0 -or -not $seen.Add([string]$item.id)) { + return [pscustomobject]@{ Complete = $false; Items = @(); Gap = "$Label collection contains an invalid or duplicate identity." } + } + } + return [pscustomobject]@{ Complete = $true; Items = $evidence.Data; Gap = $null } +} diff --git a/powershell/internal/services/github/Get-MtGitHubRateLimit.ps1 b/powershell/internal/services/github/Get-MtGitHubRateLimit.ps1 new file mode 100644 index 0000000000..064823f1b3 --- /dev/null +++ b/powershell/internal/services/github/Get-MtGitHubRateLimit.ps1 @@ -0,0 +1,65 @@ +function Get-MtGitHubRateLimit { + <# + .SYNOPSIS + Internal: Classifies GitHub primary/secondary limits without parsing Maester diagnostic text. + .DESCRIPTION + Primary REST and GraphQL quotas are separate. Secondary limits can be shared across both APIs. + Uses response headers, documented API error messages and GraphQL RATE_LIMITED errors. + An unknown primary reset requires a new connection; no retry time is invented for it. + #> + [CmdletBinding()] + param( + [object] $ErrorRecord, + [AllowNull()] [object] $Headers, + [int] $StatusCode = 200, + [ValidateSet('REST', 'GraphQL')] [string] $Api = 'REST', + [switch] $GraphQLRateLimited, + [string] $Message + ) + if ($ErrorRecord) { + if ($ErrorRecord.Exception.Data['GitHubRateLimit']) { return $ErrorRecord.Exception.Data['GitHubRateLimit'] } + $StatusCode = Get-MtGitHubErrorStatusCode -ErrorRecord $ErrorRecord + if ($StatusCode -notin 403, 429) { return $null } + $Headers = $ErrorRecord.Exception.Response.Headers + $Message = Get-MtGitHubErrorMessage -ErrorRecord $ErrorRecord + } + $remaining = Get-MtGitHubResponseHeaderValue -Headers $Headers -Name 'x-ratelimit-remaining' + $remainingValue = 0 + $primary = $null -ne $remaining -and [int]::TryParse([string]$remaining, [ref]$remainingValue) -and $remainingValue -eq 0 + $retryAfter = Get-MtGitHubResponseHeaderValue -Headers $Headers -Name 'retry-after' + $secondary = $Message -match '(?i)secondary\s+rate\s+limit|abuse\s+detection' -or ($StatusCode -in 403, 429 -and $null -ne $retryAfter) + if (-not $primary -and -not $secondary -and $StatusCode -ne 429 -and -not $GraphQLRateLimited) { return $null } + if ($StatusCode -notin 200, 403, 429) { return $null } + + $now = [DateTimeOffset]::UtcNow + $reset = Get-MtGitHubResponseHeaderValue -Headers $Headers -Name 'x-ratelimit-reset' + $resetSeconds = 0L + $resetUtc = $null + if ($null -ne $reset -and [long]::TryParse([string]$reset, [ref]$resetSeconds)) { + try { $resetUtc = [DateTimeOffset]::FromUnixTimeSeconds($resetSeconds) } catch { Write-Debug 'GitHub returned an out-of-range reset epoch.' } + } + $retrySeconds = 0L + $retryUtc = $null + if ($null -ne $retryAfter -and [long]::TryParse([string]$retryAfter, [ref]$retrySeconds) -and $retrySeconds -ge 0) { + try { $retryUtc = $now.AddSeconds($retrySeconds) } catch { Write-Debug 'GitHub returned an out-of-range retry interval.' } + } + $kind = if ($secondary -or -not $primary) { 'Secondary' } else { 'Primary' } + $scope = if ($kind -eq 'Secondary') { 'All' } else { $Api } + # Respect both server deadlines when both are present. A missing primary reset cannot be safely timed. + $resumeUtc = if ($primary -and $null -eq $resetUtc) { [DateTimeOffset]::MaxValue } + elseif ($primary -and $resetUtc -lt [DateTimeOffset]::MaxValue.AddSeconds(-1)) { $resetUtc.AddSeconds(1) } + elseif ($primary) { [DateTimeOffset]::MaxValue } + elseif ($retryUtc) { $retryUtc } + else { $now.AddSeconds(60) } + if ($retryUtc -and $retryUtc -gt $resumeUtc) { $resumeUtc = $retryUtc } + $resetText = if ($resetUtc) { $resetUtc.LocalDateTime } else { 'unknown' } + $diagnostic = if ($kind -eq 'Primary') { "GitHub API rate limit encountered (HTTP $StatusCode). Resets at: $resetText" } + elseif ($retryUtc) { "GitHub secondary rate limit encountered (HTTP $StatusCode). Retry after: ${retrySeconds}s" } + else { "GitHub secondary rate limit encountered (HTTP $StatusCode). Retry after at least 60s." } + [pscustomobject]@{ + Kind = $kind; Scope = $scope; HttpStatus = $StatusCode + Resource = Get-MtGitHubResponseHeaderValue -Headers $Headers -Name 'x-ratelimit-resource' + RetryAfterSeconds = $(if ($retryUtc) { $retrySeconds } else { $null }) + ResetUtc = $resetUtc; ResumeUtc = $resumeUtc; Message = $diagnostic + } +} diff --git a/powershell/internal/services/github/Get-MtGitHubRateLimitMessage.ps1 b/powershell/internal/services/github/Get-MtGitHubRateLimitMessage.ps1 index f55609689d..3ed875be55 100644 --- a/powershell/internal/services/github/Get-MtGitHubRateLimitMessage.ps1 +++ b/powershell/internal/services/github/Get-MtGitHubRateLimitMessage.ps1 @@ -1,75 +1,12 @@ -function Get-MtGitHubRateLimitMessage { +function Get-MtGitHubRateLimitMessage { <# .SYNOPSIS - Internal: Returns a GitHub rate-limit message for an ErrorRecord, or $null when the - error is not a rate-limit response. - + Internal: Returns a GitHub rate-limit diagnostic, or null for ordinary HTTP errors. .DESCRIPTION - Mirrors the rate-limit detection in Invoke-MtGitHubRequest so that bootstrap callers - (Connect-MtGitHub) can distinguish HTTP 403/429 caused by rate limiting from - permission, token, or org-access failures. - - Returns: - - "GitHub API rate limit encountered (HTTP ). Resets at: