Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 38 additions & 32 deletions docs/github-repo-config.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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".

Expand All @@ -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
Expand Down Expand Up @@ -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'
Expand Down Expand Up @@ -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))
}
}

Expand Down Expand Up @@ -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 ',')))
}
}
}
}
}
Expand Down Expand Up @@ -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
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,51 @@
# 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 ', ')."
}

# -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 {
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Builds and returns a hashtable; does not change system state.')]
<#
Expand All @@ -26,14 +71,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])]
Expand All @@ -42,59 +90,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()
Expand All @@ -112,7 +127,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
Expand Down
Loading
Loading