From 2e51b2f32fc62b60691ffc20d69489842ff58d5c Mon Sep 17 00:00:00 2001 From: Jean-Paul van Ravensberg <14926452+DevSecNinja@users.noreply.github.com> Date: Sat, 14 Nov 2026 12:20:33 +0100 Subject: [PATCH 1/2] fix(github): align the repo baseline ruleset with steward-default-branch Rename the baseline default-branch ruleset from Default to steward-default-branch, the one repo-steward manages, so remediation updates it in place instead of creating a competing ruleset. Mirror repo-steward's policy/baseline.toml [protection]: deletion, non_fast_forward, required_linear_history and required_signatures, with forks keeping only deletion and non_fast_forward, and the owner bypass (RepositoryRole 5, always). PR-only (steward-pull-request) and release-tag protection (steward-release-tags) stay with repo-steward, so pull_request is no longer managed here; like status checks and Copilot review, it is carried over untouched. Closes #1044 Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/github-repo-config.md | 70 +++++---- .../Public/GitHubRepoConfig.ps1 | 69 ++++----- .../DotfilesHelpers/Public/GitHubRuleset.ps1 | 103 +++++++------ tests/powershell/GitHubApi.Tests.ps1 | 13 +- .../GitHubCredentialPlacement.Tests.ps1 | 13 +- tests/powershell/GitHubRepoConfig.Tests.ps1 | 137 ++++++++---------- tests/powershell/GitHubRuleset.Tests.ps1 | 87 +++++++---- .../OnePasswordCredential.Tests.ps1 | 13 +- tests/powershell/Profile.Tests.ps1 | 1 + 9 files changed, 258 insertions(+), 248 deletions(-) diff --git a/docs/github-repo-config.md b/docs/github-repo-config.md index 239c8a44..787dd31c 100644 --- a/docs/github-repo-config.md +++ b/docs/github-repo-config.md @@ -130,50 +130,56 @@ audit and the remediation read from it, so an edit propagates to both. Protects the default branch while keeping **you** able to bypass it. -| Setting | Value | -| -------------------------- | --------- | -| `Name` | `Default` | -| `RequirePullRequest` | `true` | -| `RequiredApprovingReviews` | `0` | -| `BlockDeletion` | `true` | -| `BlockForcePush` | `true` | -| `AllowedMergeMethods` | `squash` | -| `AdminCanBypass` | `true` | - -The name matches what GitHub's own UI creates, so a repository that already has -a ruleset is updated in place rather than gaining a second, competing one. If -yours is named differently, override it: - -```powershell -Get-GitHubRepoConfig -All -Baseline @{ Ruleset = @{ Name = 'Protect main branch' } } -``` +!!! note "repo-steward is the reference" + + This section mirrors `[protection]` in + [DevSecNinja/repo-steward](https://github.com/DevSecNinja/repo-steward)'s + `policy/baseline.toml`, which manages the same ruleset. If the steward + policy changes, change this baseline to match, or the two tools will keep + undoing each other. + +| Setting | Value | +| ---------------- | -------------------------------------------------------------------------------- | +| `Name` | `steward-default-branch` | +| `Enforcement` | `active` | +| `Rules` | `deletion`, `non_fast_forward`, `required_linear_history`, `required_signatures` | +| `ForkRules` | `deletion`, `non_fast_forward` | +| `AdminCanBypass` | `true` | + +The name is the one repo-steward manages, so an existing +`steward-default-branch` ruleset is updated in place rather than joined by a +second, competing one. + +Forks get `ForkRules` instead of `Rules`. GitHub's **Sync fork** pushes upstream +commits straight to the fork's default branch, and those are neither signed nor +guaranteed to be linear. On a fork, linear history and required signatures are +reported as drift and removed when remediating. `AdminCanBypass` adds the **Repository admin** role (`actor_id: 5`) as a `bypass_mode: always` actor. On a personal account that is you, so you keep the -ability to push directly to `main` and merge without a PR. +ability to push directly to `main`. Automation does **not** get that bypass, and that is the point: it means `contents: write` held by a workflow — or a leaked GitHub App key — stops being equivalent to "push straight to `main`". -Set `RequiredApprovingReviews` above zero only if someone other than you -reviews; on a solo repository a required approval you cannot self-grant will -block your own PRs. +!!! info "PR-only and tag protection belong to repo-steward" + + repo-steward keeps the PR-only rule in a separate `steward-pull-request` + ruleset (so one repository can be exempted from it alone), and protects + `v*` tags with `steward-release-tags`. This baseline manages neither. A + `pull_request` rule found on `steward-default-branch` is preserved as-is, + not judged or rewritten. ### Existing rules are preserved The rulesets API replaces the whole object on update, which makes a naive PUT -destructive. When updating in place, only the rules and parameters this baseline -owns are replaced. Everything else is carried over verbatim: +destructive. When updating in place, only the rules this baseline owns are +replaced. Everything else is carried over verbatim: - `required_status_checks` keeps its full context list -- `copilot_code_review` and any other rule type is left alone -- Within `pull_request`, only `allowed_merge_methods` and - `required_approving_review_count` are set. `require_code_owner_review`, - `dismiss_stale_reviews_on_push`, `require_last_push_approval`, - `required_review_thread_resolution` and any parameter GitHub adds later are - inherited from the existing rule, so fixing a merge-method drift never - silently switches stricter review settings off +- `pull_request`, `copilot_code_review`, `code_scanning` and any other rule type + are left alone, parameters included - Existing bypass actors (GitHub Apps, teams) are kept; the admin role is added only if it is missing - A custom `ref_name` condition is preserved. The one exception is a condition @@ -198,8 +204,8 @@ override does not discard the rest: # Permit wikis everywhere Get-GitHubRepoConfig -All -Baseline @{ Settings = @{ has_wiki = $true } } -# Require one approving review -Get-GitHubRepoConfig -All -Baseline @{ Ruleset = @{ RequiredApprovingReviews = 1 } } +# Protect the default branch without requiring linear history or signed commits +Get-GitHubRepoConfig -All -Baseline @{ Ruleset = @{ Rules = @('deletion', 'non_fast_forward') } } ``` ## Scoping a run diff --git a/home/dot_config/powershell/modules/DotfilesHelpers/Public/GitHubRepoConfig.ps1 b/home/dot_config/powershell/modules/DotfilesHelpers/Public/GitHubRepoConfig.ps1 index acbf3b0a..bbd687b0 100644 --- a/home/dot_config/powershell/modules/DotfilesHelpers/Public/GitHubRepoConfig.ps1 +++ b/home/dot_config/powershell/modules/DotfilesHelpers/Public/GitHubRepoConfig.ps1 @@ -73,12 +73,19 @@ function Get-GitHubRepoBaseline { `environment:`, and the caller job does not either - so an environment secret would read as empty and silently disable deploys. - - The Ruleset name matches what GitHub's UI creates ('Default'), so - a repository that already has one is updated in place instead of - gaining a second, competing ruleset. Override Name if yours differs. + - The Ruleset mirrors the `[protection]` section of repo-steward's + policy/baseline.toml (DevSecNinja/repo-steward), which is the + reference; keep the two in sync. Its name, steward-default-branch, + is the one repo-steward manages, so an existing ruleset is updated + in place instead of gaining a second, competing one. Rules lists the + required rules, and ForkRules the subset that forks keep: GitHub's + "Sync fork" pushes upstream commits that are neither signed nor + linear. PR-only (steward-pull-request) and release-tag protection + (steward-release-tags) are separate rulesets owned by repo-steward; + a pull_request rule found on this ruleset is preserved, not managed. - The Ruleset section protects the default branch while listing the repository admin role as a bypass actor, so you keep the ability to - push directly or merge without a PR. Automation does not get that + push directly to the default branch. Automation does not get that bypass, which is the point: `contents: write` held by a workflow or a leaked App key stops being equivalent to "push to main". @@ -99,9 +106,10 @@ function Get-GitHubRepoBaseline { Return the baseline with wikis permitted. .EXAMPLE - Get-GitHubRepoBaseline -Override @{ Ruleset = @{ RequiredApprovingReviews = 1 } } + Get-GitHubRepoBaseline -Override @{ Ruleset = @{ Rules = @('deletion', 'non_fast_forward') } } - Require one approving review on the default branch. + Protect the default branch without requiring linear history or signed + commits. .OUTPUTS System.Collections.Hashtable @@ -135,14 +143,11 @@ function Get-GitHubRepoBaseline { can_approve_pull_request_reviews = $false } Ruleset = [ordered]@{ - Name = 'Default' - Enforcement = 'active' - RequirePullRequest = $true - RequiredApprovingReviews = 0 - BlockDeletion = $true - BlockForcePush = $true - AllowedMergeMethods = @('squash') - AdminCanBypass = $true + Name = 'steward-default-branch' + Enforcement = 'active' + Rules = @('deletion', 'non_fast_forward', 'required_linear_history', 'required_signatures') + ForkRules = @('deletion', 'non_fast_forward') + AdminCanBypass = $true } AppCredential = [ordered]@{ VariableName = 'AUTOMATION_APP_ID' @@ -451,16 +456,17 @@ function Get-GitHubRepoConfig { $drift.Add((New-GitHubConfigDrift -Category 'Ruleset' -Setting 'ruleset_enforcement' -Current $detail.enforcement -Desired $wanted.Enforcement)) } - $expectedRules = [ordered]@{ - pull_request = [bool]$wanted.RequirePullRequest - deletion = [bool]$wanted.BlockDeletion - non_fast_forward = [bool]$wanted.BlockForcePush - } - foreach ($ruleType in $expectedRules.Keys) { + # Every managed rule type is checked both ways: a + # wanted rule that is missing, and an unwanted one + # (linear history or signatures on a fork) that is + # present. Other rule types are not this baseline's. + $wantedRuleTypes = Get-GitHubRulesetDesiredRule -Ruleset $wanted -IsFork ([bool]$repo.fork) + foreach ($ruleType in $script:GitHubManagedBranchRuleTypes) { $present = $ruleTypes -contains $ruleType + $desiredPresent = $wantedRuleTypes -contains $ruleType $current["ruleset_$ruleType"] = $present - if ($present -ne $expectedRules[$ruleType]) { - $drift.Add((New-GitHubConfigDrift -Category 'Ruleset' -Setting "ruleset_$ruleType" -Current $present -Desired $expectedRules[$ruleType])) + if ($present -ne $desiredPresent) { + $drift.Add((New-GitHubConfigDrift -Category 'Ruleset' -Setting "ruleset_$ruleType" -Current $present -Desired $desiredPresent)) } } @@ -489,23 +495,6 @@ function Get-GitHubRepoConfig { if ($hasAdminBypass -ne [bool]$wanted.AdminCanBypass) { $drift.Add((New-GitHubConfigDrift -Category 'Ruleset' -Setting 'ruleset_admin_bypass' -Current $hasAdminBypass -Desired ([bool]$wanted.AdminCanBypass))) } - - if ($wanted.RequirePullRequest -and ($ruleTypes -contains 'pull_request')) { - $prRule = @($detail.rules | Where-Object { $_.type -eq 'pull_request' })[0] - - $currentReviews = $prRule.parameters.required_approving_review_count - $current['ruleset_required_approving_review_count'] = $currentReviews - if ($currentReviews -ne $wanted.RequiredApprovingReviews) { - $drift.Add((New-GitHubConfigDrift -Category 'Ruleset' -Setting 'ruleset_required_approving_review_count' -Current $currentReviews -Desired $wanted.RequiredApprovingReviews)) - } - - $currentMethods = @($prRule.parameters.allowed_merge_methods) | Sort-Object - $wantedMethods = @($wanted.AllowedMergeMethods) | Sort-Object - $current['ruleset_allowed_merge_methods'] = ($currentMethods -join ',') - if (($currentMethods -join ',') -ne ($wantedMethods -join ',')) { - $drift.Add((New-GitHubConfigDrift -Category 'Ruleset' -Setting 'ruleset_allowed_merge_methods' -Current ($currentMethods -join ',') -Desired ($wantedMethods -join ','))) - } - } } } } @@ -854,7 +843,7 @@ function Set-GitHubRepoConfig { # --- Default-branch ruleset: created or replaced wholesale --- $rulesetDrift = @($drift | Where-Object { $_.Category -eq 'Ruleset' }) if ($rulesetDrift.Count -gt 0) { - $payloadArgs = @{ Ruleset = $config.Baseline.Ruleset } + $payloadArgs = @{ Ruleset = $config.Baseline.Ruleset; IsFork = [bool]$config.IsFork } if ($null -ne $config.RulesetDetail) { $payloadArgs['ExistingRuleset'] = $config.RulesetDetail } diff --git a/home/dot_config/powershell/modules/DotfilesHelpers/Public/GitHubRuleset.ps1 b/home/dot_config/powershell/modules/DotfilesHelpers/Public/GitHubRuleset.ps1 index 021a5a19..86df02bd 100644 --- a/home/dot_config/powershell/modules/DotfilesHelpers/Public/GitHubRuleset.ps1 +++ b/home/dot_config/powershell/modules/DotfilesHelpers/Public/GitHubRuleset.ps1 @@ -13,6 +13,47 @@ # 5 = Repository admin, i.e. the repository owner on a personal account. $script:GitHubRepositoryRoleAdmin = 5 +# Parameterless branch rule types this baseline manages, mirroring repo-steward's +# policy/baseline.toml [protection]. A managed type is added when the baseline +# wants it and removed when it does not; every other rule type on an existing +# ruleset (status checks, pull_request, Copilot review, code scanning, ...) is +# carried over untouched. +$script:GitHubManagedBranchRuleTypes = @('deletion', 'non_fast_forward', 'required_linear_history', 'required_signatures') + +function Get-GitHubRulesetDesiredRule { + <# + .SYNOPSIS + Return the branch rule types the baseline wants on a repository. + .DESCRIPTION + Forks get ForkRules instead of Rules: GitHub's "Sync fork" pushes + upstream commits straight to the default branch, and those are neither + signed nor guaranteed linear, so the stricter rules would block it. + .PARAMETER Ruleset + The Ruleset section of a baseline hashtable. + .PARAMETER IsFork + Whether the repository is a fork. + #> + [CmdletBinding()] + [OutputType([string[]])] + param( + [Parameter(Mandatory = $true)] + $Ruleset, + + [Parameter(Mandatory = $false)] + [bool]$IsFork + ) + + $wanted = if ($IsFork) { @($Ruleset.ForkRules) } else { @($Ruleset.Rules) } + $wanted = @($wanted | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }) + + $unknown = @($wanted | Where-Object { $script:GitHubManagedBranchRuleTypes -notcontains $_ }) + if ($unknown.Count -gt 0) { + throw "Unsupported ruleset rule type(s): $($unknown -join ', '). Supported: $($script:GitHubManagedBranchRuleTypes -join ', ')." + } + + return , [string[]]$wanted +} + function New-GitHubRulesetPayload { [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Builds and returns a hashtable; does not change system state.')] <# @@ -26,14 +67,17 @@ function New-GitHubRulesetPayload { That same replace-everything behaviour makes updates destructive, so when -ExistingRuleset is supplied any rule this baseline does not manage - (required_status_checks and its context list, copilot_code_review, and - so on) is carried over verbatim, and existing bypass actors are kept. - Only the managed rules - deletion, non_fast_forward and pull_request - - are replaced. + (required_status_checks and its context list, pull_request, + copilot_code_review, code_scanning and so on) is carried over verbatim, + and existing bypass actors are kept. Only the managed parameterless + rules - deletion, non_fast_forward, required_linear_history and + required_signatures - are replaced. .PARAMETER Ruleset The Ruleset section of a baseline hashtable. .PARAMETER ExistingRuleset The current ruleset as returned by the API, when updating in place. + .PARAMETER IsFork + Apply the fork rule set (ForkRules) instead of Rules. #> [CmdletBinding()] [OutputType([hashtable])] @@ -42,59 +86,26 @@ function New-GitHubRulesetPayload { $Ruleset, [Parameter(Mandatory = $false)] - $ExistingRuleset + $ExistingRuleset, + + [Parameter(Mandatory = $false)] + [bool]$IsFork ) - # Rule types this baseline owns. Anything else found on an existing ruleset - # is preserved untouched. - $managedRuleTypes = @('deletion', 'non_fast_forward', 'pull_request') + $wantedRuleTypes = Get-GitHubRulesetDesiredRule -Ruleset $Ruleset -IsFork $IsFork $rules = [System.Collections.Generic.List[object]]::new() - $existingPullRequest = $null if ($null -ne $ExistingRuleset -and $null -ne $ExistingRuleset.rules) { foreach ($rule in $ExistingRuleset.rules) { - if ($managedRuleTypes -notcontains $rule.type) { + if ($script:GitHubManagedBranchRuleTypes -notcontains $rule.type) { $rules.Add($rule) } - elseif ($rule.type -eq 'pull_request') { - $existingPullRequest = $rule - } } } - if ($Ruleset.BlockDeletion) { - $rules.Add(@{ type = 'deletion' }) - } - - if ($Ruleset.BlockForcePush) { - $rules.Add(@{ type = 'non_fast_forward' }) - } - - if ($Ruleset.RequirePullRequest) { - # Only two pull_request parameters belong to this baseline. Everything - # else - code-owner review, stale-review dismissal, last-push approval, - # thread resolution, and any parameter GitHub adds later - is carried - # over from the existing rule, so remediating a merge-method drift never - # silently switches someone's stricter review settings off. - $prParameters = [ordered]@{} - if ($null -ne $existingPullRequest -and $null -ne $existingPullRequest.parameters) { - foreach ($property in $existingPullRequest.parameters.PSObject.Properties) { - $prParameters[$property.Name] = $property.Value - } - } - else { - # No existing rule to inherit from: start from GitHub's defaults. - $prParameters['dismiss_stale_reviews_on_push'] = $false - $prParameters['require_code_owner_review'] = $false - $prParameters['require_last_push_approval'] = $false - $prParameters['required_review_thread_resolution'] = $false - } - - $prParameters['allowed_merge_methods'] = @($Ruleset.AllowedMergeMethods) - $prParameters['required_approving_review_count'] = $Ruleset.RequiredApprovingReviews - - $rules.Add(@{ type = 'pull_request'; parameters = $prParameters }) + foreach ($type in $wantedRuleTypes) { + $rules.Add(@{ type = $type }) } $bypassActors = [System.Collections.Generic.List[object]]::new() @@ -112,7 +123,7 @@ function New-GitHubRulesetPayload { if ($Ruleset.AdminCanBypass -and -not $hasAdminBypass) { # Lets the repository admin (you) push directly to the default branch - # and merge without a PR when needed, while everything else - including + # when needed, while everything else - including # GitHub Actions - stays subject to the rules. $bypassActors.Add(@{ actor_id = $script:GitHubRepositoryRoleAdmin diff --git a/tests/powershell/GitHubApi.Tests.ps1 b/tests/powershell/GitHubApi.Tests.ps1 index df61e4c5..4474f688 100644 --- a/tests/powershell/GitHubApi.Tests.ps1 +++ b/tests/powershell/GitHubApi.Tests.ps1 @@ -67,7 +67,7 @@ BeforeAll { function script:New-CompliantRulesetDetail { return [PSCustomObject]@{ id = 42 - name = 'Default' + name = 'steward-default-branch' target = 'branch' source_type = 'Repository' enforcement = 'active' @@ -80,13 +80,8 @@ BeforeAll { rules = @( [PSCustomObject]@{ type = 'deletion' } [PSCustomObject]@{ type = 'non_fast_forward' } - [PSCustomObject]@{ - type = 'pull_request' - parameters = [PSCustomObject]@{ - allowed_merge_methods = @('squash') - required_approving_review_count = 0 - } - } + [PSCustomObject]@{ type = 'required_linear_history' } + [PSCustomObject]@{ type = 'required_signatures' } ) } } @@ -95,7 +90,7 @@ BeforeAll { function script:New-RulesetListPresent { return [PSCustomObject]@{ Available = $true - Rulesets = @([PSCustomObject]@{ id = 42; name = 'Default'; target = 'branch'; source_type = 'Repository' }) + Rulesets = @([PSCustomObject]@{ id = 42; name = 'steward-default-branch'; target = 'branch'; source_type = 'Repository' }) } } diff --git a/tests/powershell/GitHubCredentialPlacement.Tests.ps1 b/tests/powershell/GitHubCredentialPlacement.Tests.ps1 index 82ae3a51..cd0a069c 100644 --- a/tests/powershell/GitHubCredentialPlacement.Tests.ps1 +++ b/tests/powershell/GitHubCredentialPlacement.Tests.ps1 @@ -67,7 +67,7 @@ BeforeAll { function script:New-CompliantRulesetDetail { return [PSCustomObject]@{ id = 42 - name = 'Default' + name = 'steward-default-branch' target = 'branch' source_type = 'Repository' enforcement = 'active' @@ -80,13 +80,8 @@ BeforeAll { rules = @( [PSCustomObject]@{ type = 'deletion' } [PSCustomObject]@{ type = 'non_fast_forward' } - [PSCustomObject]@{ - type = 'pull_request' - parameters = [PSCustomObject]@{ - allowed_merge_methods = @('squash') - required_approving_review_count = 0 - } - } + [PSCustomObject]@{ type = 'required_linear_history' } + [PSCustomObject]@{ type = 'required_signatures' } ) } } @@ -95,7 +90,7 @@ BeforeAll { function script:New-RulesetListPresent { return [PSCustomObject]@{ Available = $true - Rulesets = @([PSCustomObject]@{ id = 42; name = 'Default'; target = 'branch'; source_type = 'Repository' }) + Rulesets = @([PSCustomObject]@{ id = 42; name = 'steward-default-branch'; target = 'branch'; source_type = 'Repository' }) } } diff --git a/tests/powershell/GitHubRepoConfig.Tests.ps1 b/tests/powershell/GitHubRepoConfig.Tests.ps1 index 6c865416..6f495ed9 100644 --- a/tests/powershell/GitHubRepoConfig.Tests.ps1 +++ b/tests/powershell/GitHubRepoConfig.Tests.ps1 @@ -67,7 +67,7 @@ BeforeAll { function script:New-CompliantRulesetDetail { return [PSCustomObject]@{ id = 42 - name = 'Default' + name = 'steward-default-branch' target = 'branch' source_type = 'Repository' enforcement = 'active' @@ -80,13 +80,8 @@ BeforeAll { rules = @( [PSCustomObject]@{ type = 'deletion' } [PSCustomObject]@{ type = 'non_fast_forward' } - [PSCustomObject]@{ - type = 'pull_request' - parameters = [PSCustomObject]@{ - allowed_merge_methods = @('squash') - required_approving_review_count = 0 - } - } + [PSCustomObject]@{ type = 'required_linear_history' } + [PSCustomObject]@{ type = 'required_signatures' } ) } } @@ -95,7 +90,7 @@ BeforeAll { function script:New-RulesetListPresent { return [PSCustomObject]@{ Available = $true - Rulesets = @([PSCustomObject]@{ id = 42; name = 'Default'; target = 'branch'; source_type = 'Repository' }) + Rulesets = @([PSCustomObject]@{ id = 42; name = 'steward-default-branch'; target = 'branch'; source_type = 'Repository' }) } } @@ -207,8 +202,8 @@ Describe "Get-GitHubRepoBaseline" -Tag "Unit" { (Get-GitHubRepoBaseline).Ruleset.AdminCanBypass | Should -BeTrue } - It "requires a pull request on the default branch" { - (Get-GitHubRepoBaseline).Ruleset.RequirePullRequest | Should -BeTrue + It "manages repo-steward's steward-default-branch ruleset rather than a competing one" { + (Get-GitHubRepoBaseline).Ruleset.Name | Should -Be 'steward-default-branch' } It "merges an override into a single section without discarding the rest" { @@ -219,8 +214,9 @@ Describe "Get-GitHubRepoBaseline" -Tag "Unit" { } It "merges an override into the Ruleset section" { - $baseline = Get-GitHubRepoBaseline -Override @{ Ruleset = @{ RequiredApprovingReviews = 1 } } - $baseline.Ruleset.RequiredApprovingReviews | Should -Be 1 + $baseline = Get-GitHubRepoBaseline -Override @{ Ruleset = @{ Rules = @('deletion') } } + $baseline.Ruleset.Rules | Should -Be @('deletion') + $baseline.Ruleset.ForkRules | Should -Be @('deletion', 'non_fast_forward') $baseline.Ruleset.AdminCanBypass | Should -BeTrue } @@ -363,12 +359,14 @@ Describe "Get-GitHubRepoConfig" -Tag "Unit" { } } - Context "when the ruleset allows merge methods outside the baseline" { + Context "when the ruleset is missing a steward rule" { BeforeEach { Mock -ModuleName DotfilesHelpers Get-GitHubRulesetList { script:New-RulesetListPresent } Mock -ModuleName DotfilesHelpers Invoke-GitHubApi { $detail = script:New-CompliantRulesetDetail - $detail.rules[2].parameters.allowed_merge_methods = @('merge', 'squash', 'rebase') + $detail.rules = @($detail.rules | Where-Object { $_.type -ne 'required_signatures' }) + @( + [PSCustomObject]@{ type = 'pull_request'; parameters = [PSCustomObject]@{ allowed_merge_methods = @('merge') } } + ) script:Get-MockApiResponse -Endpoint $Endpoint ` -Repo (script:New-CompliantRepoResponse) ` -Actions (script:New-CompliantActionsResponse) ` @@ -376,9 +374,37 @@ Describe "Get-GitHubRepoConfig" -Tag "Unit" { } } - It "flags the merge methods as drifted" { + It "flags the missing rule" { + $drift = @((Get-GitHubRepoConfig -Repository 'compliant').Drift) + $missing = @($drift | Where-Object { $_.Setting -eq 'ruleset_required_signatures' }) + $missing.Count | Should -Be 1 + $missing[0].Desired | Should -BeTrue + } + + It "does not judge a pull_request rule that repo-steward owns elsewhere" { + $drift = @((Get-GitHubRepoConfig -Repository 'compliant').Drift) + @($drift | Where-Object { $_.Setting -match 'pull_request|merge_methods|review' }).Count | Should -Be 0 + } + } + + Context "when a fork carries the full steward rule set" { + BeforeEach { + Mock -ModuleName DotfilesHelpers Get-GitHubRulesetList { script:New-RulesetListPresent } + Mock -ModuleName DotfilesHelpers Invoke-GitHubApi { + $repo = script:New-CompliantRepoResponse + $repo | Add-Member -NotePropertyName fork -NotePropertyValue $true + script:Get-MockApiResponse -Endpoint $Endpoint ` + -Repo $repo ` + -Actions (script:New-CompliantActionsResponse) ` + -RulesetDetail (script:New-CompliantRulesetDetail) + } + } + + It "flags linear history and signatures as unwanted, since they block Sync fork" { $drift = @((Get-GitHubRepoConfig -Repository 'compliant').Drift) - @($drift | Where-Object { $_.Setting -eq 'ruleset_allowed_merge_methods' }).Count | Should -Be 1 + @($drift | ForEach-Object Setting) | Sort-Object | + Should -Be @('ruleset_required_linear_history', 'ruleset_required_signatures') + @($drift | Where-Object { $_.Desired -ne $false }).Count | Should -Be 0 } } @@ -1097,76 +1123,35 @@ Describe "Skipped check reporting" -Tag "Unit" { } Describe "Rubber-duck regressions" -Tag "Unit" { - Context "pull_request parameters the baseline does not own" { - It "preserves require_code_owner_review when remediating merge methods" { - InModuleScope DotfilesHelpers { - $existing = [PSCustomObject]@{ - rules = @( - [PSCustomObject]@{ - type = 'pull_request' - parameters = [PSCustomObject]@{ - allowed_merge_methods = @('merge', 'squash', 'rebase') - required_approving_review_count = 0 - require_code_owner_review = $true - dismiss_stale_reviews_on_push = $true - require_last_push_approval = $true - required_review_thread_resolution = $true - } - } - ) - } - - $payload = New-GitHubRulesetPayload -Ruleset (Get-GitHubRepoBaseline).Ruleset -ExistingRuleset $existing - $pr = @($payload.rules | Where-Object { $_.type -eq 'pull_request' })[0] - - $pr.parameters['require_code_owner_review'] | Should -BeTrue - $pr.parameters['dismiss_stale_reviews_on_push'] | Should -BeTrue - $pr.parameters['require_last_push_approval'] | Should -BeTrue - $pr.parameters['required_review_thread_resolution'] | Should -BeTrue - # ...while the two the baseline owns are still applied. - $pr.parameters['allowed_merge_methods'] | Should -Be @('squash') + Context "fork remediation" { + It "writes only the fork rules when remediating a fork" { + Mock -ModuleName DotfilesHelpers Test-GitHubCliReady { } + Mock -ModuleName DotfilesHelpers Get-GitHubCurrentOwner { 'DevSecNinja' } + Mock -ModuleName DotfilesHelpers Get-GitHubRulesetList { script:New-RulesetListEmpty } + Mock -ModuleName DotfilesHelpers Invoke-GitHubApi { + $repo = script:New-CompliantRepoResponse + $repo | Add-Member -NotePropertyName fork -NotePropertyValue $true + script:Get-MockApiResponse -Endpoint $Endpoint -Repo $repo } - } - It "carries over a parameter the baseline has never heard of" { - InModuleScope DotfilesHelpers { - $existing = [PSCustomObject]@{ - rules = @( - [PSCustomObject]@{ - type = 'pull_request' - parameters = [PSCustomObject]@{ - allowed_merge_methods = @('merge') - some_future_github_setting = 'keep-me' - } - } - ) - } - - $payload = New-GitHubRulesetPayload -Ruleset (Get-GitHubRepoBaseline).Ruleset -ExistingRuleset $existing - $pr = @($payload.rules | Where-Object { $_.type -eq 'pull_request' })[0] - $pr.parameters['some_future_github_setting'] | Should -Be 'keep-me' - } - } + Get-GitHubRepoConfig -Repository 'forked' -Check Ruleset | + Set-GitHubRepoConfig -Confirm:$false - It "falls back to GitHub defaults when there is no existing rule" { - InModuleScope DotfilesHelpers { - $payload = New-GitHubRulesetPayload -Ruleset (Get-GitHubRepoBaseline).Ruleset - $pr = @($payload.rules | Where-Object { $_.type -eq 'pull_request' })[0] - $pr.parameters['require_code_owner_review'] | Should -BeFalse - $pr.parameters['required_approving_review_count'] | Should -Be 0 + Should -Invoke -ModuleName DotfilesHelpers Invoke-GitHubApi -Times 1 -Exactly -ParameterFilter { + $Method -eq 'POST' -and $Endpoint -like '*/rulesets' -and + (@($Body['rules'] | ForEach-Object { $_.type }) | Sort-Object) -join ',' -eq 'deletion,non_fast_forward' } } } - Context "ruleset identity" { It "ignores a tag ruleset that shares the baseline name" { InModuleScope DotfilesHelpers { $list = [PSCustomObject]@{ Available = $true - Rulesets = @([PSCustomObject]@{ id = 9; name = 'Default'; target = 'tag'; source_type = 'Repository' }) + Rulesets = @([PSCustomObject]@{ id = 9; name = 'steward-default-branch'; target = 'tag'; source_type = 'Repository' }) } @($list.Rulesets | Where-Object { - $_.name -eq 'Default' -and $_.target -eq 'branch' -and + $_.name -eq 'steward-default-branch' -and $_.target -eq 'branch' -and ($null -eq $_.source_type -or $_.source_type -eq 'Repository') }).Count | Should -Be 0 } @@ -1174,9 +1159,9 @@ Describe "Rubber-duck regressions" -Tag "Unit" { It "ignores an organisation-inherited ruleset that shares the name" { InModuleScope DotfilesHelpers { - $rulesets = @([PSCustomObject]@{ id = 9; name = 'Default'; target = 'branch'; source_type = 'Organization' }) + $rulesets = @([PSCustomObject]@{ id = 9; name = 'steward-default-branch'; target = 'branch'; source_type = 'Organization' }) @($rulesets | Where-Object { - $_.name -eq 'Default' -and $_.target -eq 'branch' -and + $_.name -eq 'steward-default-branch' -and $_.target -eq 'branch' -and ($null -eq $_.source_type -or $_.source_type -eq 'Repository') }).Count | Should -Be 0 } diff --git a/tests/powershell/GitHubRuleset.Tests.ps1 b/tests/powershell/GitHubRuleset.Tests.ps1 index ce045c5c..93973bef 100644 --- a/tests/powershell/GitHubRuleset.Tests.ps1 +++ b/tests/powershell/GitHubRuleset.Tests.ps1 @@ -67,7 +67,7 @@ BeforeAll { function script:New-CompliantRulesetDetail { return [PSCustomObject]@{ id = 42 - name = 'Default' + name = 'steward-default-branch' target = 'branch' source_type = 'Repository' enforcement = 'active' @@ -80,13 +80,8 @@ BeforeAll { rules = @( [PSCustomObject]@{ type = 'deletion' } [PSCustomObject]@{ type = 'non_fast_forward' } - [PSCustomObject]@{ - type = 'pull_request' - parameters = [PSCustomObject]@{ - allowed_merge_methods = @('squash') - required_approving_review_count = 0 - } - } + [PSCustomObject]@{ type = 'required_linear_history' } + [PSCustomObject]@{ type = 'required_signatures' } ) } } @@ -95,7 +90,7 @@ BeforeAll { function script:New-RulesetListPresent { return [PSCustomObject]@{ Available = $true - Rulesets = @([PSCustomObject]@{ id = 42; name = 'Default'; target = 'branch'; source_type = 'Repository' }) + Rulesets = @([PSCustomObject]@{ id = 42; name = 'steward-default-branch'; target = 'branch'; source_type = 'Repository' }) } } @@ -165,35 +160,35 @@ Describe "New-GitHubRulesetPayload" -Tag "Unit" { } } - It "emits the deletion, non_fast_forward and pull_request rules" { + It "emits the four steward-default-branch rules and no pull_request rule" { InModuleScope DotfilesHelpers { $payload = New-GitHubRulesetPayload -Ruleset (Get-GitHubRepoBaseline).Ruleset - $types = @($payload.rules | ForEach-Object { $_.type }) - $types | Should -Contain 'deletion' - $types | Should -Contain 'non_fast_forward' - $types | Should -Contain 'pull_request' + $payload.name | Should -Be 'steward-default-branch' + $types = @($payload.rules | ForEach-Object { $_.type }) | Sort-Object + $types | Should -Be @('deletion', 'non_fast_forward', 'required_linear_history', 'required_signatures') } } - It "drops rules that the baseline disables" { + It "keeps only deletion and non_fast_forward on a fork" { InModuleScope DotfilesHelpers { - $ruleset = (Get-GitHubRepoBaseline -Override @{ - Ruleset = @{ BlockDeletion = $false; RequirePullRequest = $false } - }).Ruleset - $payload = New-GitHubRulesetPayload -Ruleset $ruleset - $types = @($payload.rules | ForEach-Object { $_.type }) - $types | Should -Not -Contain 'deletion' - $types | Should -Not -Contain 'pull_request' - $types | Should -Contain 'non_fast_forward' + $payload = New-GitHubRulesetPayload -Ruleset (Get-GitHubRepoBaseline).Ruleset -IsFork $true + $types = @($payload.rules | ForEach-Object { $_.type }) | Sort-Object + $types | Should -Be @('deletion', 'non_fast_forward') } } - It "carries the required approving review count into the pull_request rule" { + It "drops rules that the baseline does not list" { InModuleScope DotfilesHelpers { - $ruleset = (Get-GitHubRepoBaseline -Override @{ Ruleset = @{ RequiredApprovingReviews = 2 } }).Ruleset + $ruleset = (Get-GitHubRepoBaseline -Override @{ Ruleset = @{ Rules = @('non_fast_forward') } }).Ruleset $payload = New-GitHubRulesetPayload -Ruleset $ruleset - $prRule = @($payload.rules | Where-Object { $_.type -eq 'pull_request' })[0] - $prRule.parameters.required_approving_review_count | Should -Be 2 + @($payload.rules | ForEach-Object { $_.type }) | Should -Be @('non_fast_forward') + } + } + + It "rejects a rule type it cannot manage" { + InModuleScope DotfilesHelpers { + $ruleset = (Get-GitHubRepoBaseline -Override @{ Ruleset = @{ Rules = @('deletion', 'pull_request') } }).Ruleset + { New-GitHubRulesetPayload -Ruleset $ruleset } | Should -Throw -ExpectedMessage '*Unsupported ruleset rule type(s): pull_request*' } } @@ -260,12 +255,50 @@ Describe "New-GitHubRulesetPayload" -Tag "Unit" { rules = @( [PSCustomObject]@{ type = 'deletion' } [PSCustomObject]@{ type = 'non_fast_forward' } + [PSCustomObject]@{ type = 'required_signatures' } ) } $payload = New-GitHubRulesetPayload -Ruleset (Get-GitHubRepoBaseline).Ruleset -ExistingRuleset $existing @($payload.rules | Where-Object { $_.type -eq 'deletion' }).Count | Should -Be 1 @($payload.rules | Where-Object { $_.type -eq 'non_fast_forward' }).Count | Should -Be 1 + @($payload.rules | Where-Object { $_.type -eq 'required_signatures' }).Count | Should -Be 1 + } + } + + It "carries an existing pull_request rule over verbatim" { + InModuleScope DotfilesHelpers { + $prRule = [PSCustomObject]@{ + type = 'pull_request' + parameters = [PSCustomObject]@{ + allowed_merge_methods = @('merge', 'squash') + required_approving_review_count = 1 + require_code_owner_review = $true + } + } + $existing = [PSCustomObject]@{ rules = @($prRule) } + + $payload = New-GitHubRulesetPayload -Ruleset (Get-GitHubRepoBaseline).Ruleset -ExistingRuleset $existing + $kept = @($payload.rules | Where-Object { $_.type -eq 'pull_request' }) + $kept.Count | Should -Be 1 + $kept[0] | Should -Be $prRule + } + } + + It "removes linear history and signatures from a fork's ruleset" { + InModuleScope DotfilesHelpers { + $existing = [PSCustomObject]@{ + rules = @( + [PSCustomObject]@{ type = 'deletion' } + [PSCustomObject]@{ type = 'required_linear_history' } + [PSCustomObject]@{ type = 'required_signatures' } + [PSCustomObject]@{ type = 'copilot_code_review' } + ) + } + + $payload = New-GitHubRulesetPayload -Ruleset (Get-GitHubRepoBaseline).Ruleset -ExistingRuleset $existing -IsFork $true + $types = @($payload.rules | ForEach-Object { $_.type }) | Sort-Object + $types | Should -Be @('copilot_code_review', 'deletion', 'non_fast_forward') } } diff --git a/tests/powershell/OnePasswordCredential.Tests.ps1 b/tests/powershell/OnePasswordCredential.Tests.ps1 index 996a2130..779a220e 100644 --- a/tests/powershell/OnePasswordCredential.Tests.ps1 +++ b/tests/powershell/OnePasswordCredential.Tests.ps1 @@ -67,7 +67,7 @@ BeforeAll { function script:New-CompliantRulesetDetail { return [PSCustomObject]@{ id = 42 - name = 'Default' + name = 'steward-default-branch' target = 'branch' source_type = 'Repository' enforcement = 'active' @@ -80,13 +80,8 @@ BeforeAll { rules = @( [PSCustomObject]@{ type = 'deletion' } [PSCustomObject]@{ type = 'non_fast_forward' } - [PSCustomObject]@{ - type = 'pull_request' - parameters = [PSCustomObject]@{ - allowed_merge_methods = @('squash') - required_approving_review_count = 0 - } - } + [PSCustomObject]@{ type = 'required_linear_history' } + [PSCustomObject]@{ type = 'required_signatures' } ) } } @@ -95,7 +90,7 @@ BeforeAll { function script:New-RulesetListPresent { return [PSCustomObject]@{ Available = $true - Rulesets = @([PSCustomObject]@{ id = 42; name = 'Default'; target = 'branch'; source_type = 'Repository' }) + Rulesets = @([PSCustomObject]@{ id = 42; name = 'steward-default-branch'; target = 'branch'; source_type = 'Repository' }) } } diff --git a/tests/powershell/Profile.Tests.ps1 b/tests/powershell/Profile.Tests.ps1 index 3ac4b6c6..dbe74239 100644 --- a/tests/powershell/Profile.Tests.ps1 +++ b/tests/powershell/Profile.Tests.ps1 @@ -316,6 +316,7 @@ Describe "DotfilesHelpers Module" { 'Get-GitHubCurrentOwner' 'ConvertFrom-DotfilesSecureString' 'New-GitHubRulesetPayload' + 'Get-GitHubRulesetDesiredRule' 'New-GitHubConfigDrift' 'Test-GitHubPagesWorkflow' 'Get-GitHubCredentialScope' From 2c8a04f7cfb0d33cf975b379a08ae7589bb36b92 Mon Sep 17 00:00:00 2001 From: Jean-Paul van Ravensberg <14926452+DevSecNinja@users.noreply.github.com> Date: Sat, 14 Nov 2026 12:33:08 +0100 Subject: [PATCH 2/2] fix(github): send canonical ruleset rule types Rule-type validation is case-insensitive, but GitHub's rule-type enum is not. Return the canonical lower-case names so an override such as 'DELETION' no longer reaches the API as-is. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../modules/DotfilesHelpers/Public/GitHubRuleset.ps1 | 6 +++++- tests/powershell/GitHubRuleset.Tests.ps1 | 8 ++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/home/dot_config/powershell/modules/DotfilesHelpers/Public/GitHubRuleset.ps1 b/home/dot_config/powershell/modules/DotfilesHelpers/Public/GitHubRuleset.ps1 index 86df02bd..44d1217a 100644 --- a/home/dot_config/powershell/modules/DotfilesHelpers/Public/GitHubRuleset.ps1 +++ b/home/dot_config/powershell/modules/DotfilesHelpers/Public/GitHubRuleset.ps1 @@ -51,7 +51,11 @@ function Get-GitHubRulesetDesiredRule { throw "Unsupported ruleset rule type(s): $($unknown -join ', '). Supported: $($script:GitHubManagedBranchRuleTypes -join ', ')." } - return , [string[]]$wanted + # -contains is case-insensitive but GitHub's rule-type enum is not, so + # return the canonical spelling rather than whatever the override used. + $canonical = @($script:GitHubManagedBranchRuleTypes | Where-Object { $wanted -contains $_ }) + + return , [string[]]$canonical } function New-GitHubRulesetPayload { diff --git a/tests/powershell/GitHubRuleset.Tests.ps1 b/tests/powershell/GitHubRuleset.Tests.ps1 index 93973bef..0ef1ca80 100644 --- a/tests/powershell/GitHubRuleset.Tests.ps1 +++ b/tests/powershell/GitHubRuleset.Tests.ps1 @@ -192,6 +192,14 @@ Describe "New-GitHubRulesetPayload" -Tag "Unit" { } } + It "sends the canonical lower-case rule type whatever the override's casing" { + InModuleScope DotfilesHelpers { + $ruleset = (Get-GitHubRepoBaseline -Override @{ Ruleset = @{ Rules = @('DELETION', 'Non_Fast_Forward') } }).Ruleset + $payload = New-GitHubRulesetPayload -Ruleset $ruleset + @($payload.rules | ForEach-Object { $_.type }) | Should -BeExactly @('deletion', 'non_fast_forward') + } + } + It "serialises to JSON that GitHub's rulesets API accepts" { InModuleScope DotfilesHelpers { $payload = New-GitHubRulesetPayload -Ruleset (Get-GitHubRepoBaseline).Ruleset