diff --git a/docs/github-repo-config.md b/docs/github-repo-config.md index 239c8a44..8a34f628 100644 --- a/docs/github-repo-config.md +++ b/docs/github-repo-config.md @@ -6,12 +6,12 @@ drift apart across dozens of repos. Four functions in the `DotfilesHelpers` module: -| Function | Purpose | -| ------------------------- | ------------------------------------------------------ | -| `Get-GitHubRepoBaseline` | The desired state — a single, editable source of truth | -| `Get-GitHubRepoConfig` | Read-only audit of one, several or all repositories | -| `Set-GitHubRepoConfig` | Remediation, with `-WhatIf` dry runs | -| `Get-GitHubAppCredential` | Reads a GitHub App ID and private key from 1Password | +| Function | Purpose | +| ------------------------- | ----------------------------------------------------------------- | +| `Get-GitHubRepoBaseline` | The desired state — a single, editable source of truth | +| `Get-GitHubRepoConfig` | Read-only audit of one, several or all repositories | +| `Set-GitHubRepoConfig` | Remediation, with `-WhatIf` dry runs | +| `Get-GitHubAppCredential` | Reads a GitHub App ID and private key from 1Password or PEM file | ## Requirements @@ -19,7 +19,8 @@ Four functions in the `DotfilesHelpers` module: `gh auth login`. All authentication is delegated to `gh`; no token is read, stored or logged by these functions. - The [1Password CLI](https://developer.1password.com/docs/cli/) (`op`), only - when rolling out GitHub App credentials. + when rolling out GitHub App credentials from 1Password. Not needed when the + key is read from a file with `-PrivateKeyPath`. Your `gh` token needs these fine-grained permissions: @@ -236,6 +237,50 @@ Unlike archived repositories — which reject writes and are therefore excluded by default — forks are perfectly writable, so excluding them is a judgement call rather than a technical constraint. +### Repositories that publish releases + +`-HasRelease` keeps only the active, non-fork repositories that cut releases — +the ones that need the Automation App credential for the shared release-please +workflow. A repository qualifies when it has either: + +- a root `release-please-config.json`, or +- at least one published (non-draft) release whose tag looks like a version + (`^v?\d+\.\d+`, so `v1.2.0` and `1.2` but not `v1`) + +Data or state snapshots stored as releases, such as `db-2026-01-01` or +`news-state`, do not count. Each result records why it qualified on +`ReleaseEvidence`, and the number of repositories kept is reported on the +information stream: + +```powershell +Get-GitHubRepoConfig -All -HasRelease -Check AppCredential | + Select-Object Repository, ReleaseEvidence, DriftCount +``` + +`-HasRelease` cannot be combined with `-IncludeArchived`. A repository whose +release list cannot be read (token, network or rate-limit trouble) is left out +with a warning and counted in the filter summary, never dropped silently. + +### Logging + +`Set-GitHubRepoConfig` writes one line per repository (what was applied, +previewed or skipped, by setting name) and a closing summary to the PowerShell +information stream. It is shown by default; silence it with +`-InformationAction SilentlyContinue` or capture it with +`-InformationVariable log`. Secret values are never logged — only the names of +the variables and secrets that were written. `-Verbose` adds per-step detail. + +```text +DevSecNinja/docker: applied 2 of 2 change(s) [AppCredential/AUTOMATION_APP_ID, AppCredential/AUTOMATION_APP_PRIVATE_KEY] +DevSecNinja/blog: already compliant +Summary: 2 repositories, 1 already compliant, 0 not fully evaluated, 0 archived, 1 changed (2 change(s) applied), 0 item(s) skipped. +``` + +A repository with no drift in the categories that could be read, but with a +category that could not (`SkippedChecks`), is reported as `no drift found; not +evaluated [...]` rather than as compliant. Under `-WhatIf`, items skipped for +want of a credential are listed as skipped, not counted as previewed. + `-Check` selects what to audit; `-Category` selects what to remediate. Repository names may be bare (`docker`), qualified (`DevSecNinja/docker`) or a full URL. Bare names are qualified with `-Owner`, which defaults to @@ -287,6 +332,29 @@ $env:OP_GITHUB_APP_ID_REF = 'op://Work/Bot/app-id' $env:OP_GITHUB_APP_KEY_REF = 'op://Work/Bot/private-key' ``` +### Reading the key from a file + +Without 1Password, or for a one-off rotation, read the key straight from the +file GitHub issues (App settings → **General** → **Private keys** → +**Generate a private key**) and pass the App ID explicitly: + +```powershell +$cred = Get-GitHubAppCredential -AppId 3563533 -PrivateKeyPath ~/Downloads/automation-app.2026-11-14.private-key.pem +``` + +The file must hold exactly one unencrypted RSA private key, in PKCS#1 +(`-----BEGIN RSA PRIVATE KEY-----`, what GitHub issues) or PKCS#8 +(`-----BEGIN PRIVATE KEY-----`) form; the extension does not matter. The key is +parsed, not just pattern-matched, so a block with a garbled or non-RSA body is +rejected too. A +certificate (`-----BEGIN CERTIFICATE-----`), a passphrase-protected key, an +empty file or anything else is rejected with a message saying why. Errors name +the file, never its contents. + +The key is converted to a `SecureString` as soon as it is validated, exactly as +with 1Password, and only the key block is kept. Delete the downloaded file once +the rollout is done. + ### Where the credential is stored By default the credential goes into a GitHub Actions **environment** named @@ -339,6 +407,16 @@ $cred = Get-GitHubAppCredential Get-GitHubRepoConfig -All -Check AppCredential | Set-GitHubRepoConfig -AppCredential $cred -WhatIf ``` +To roll the key out to just the repositories that publish releases, from a +downloaded key file: + +```powershell +Get-GitHubRepoConfig -All -HasRelease -Check AppCredential | + Set-GitHubRepoConfig -AppCredential (Get-GitHubAppCredential -AppId 3563533 -PrivateKeyPath ) -WhatIf +``` + +Drop `-WhatIf` once the preview looks right. + Remediation creates the environment, enables custom branch policies, pins it to the default branch, then writes the variable and secret into it — in that order, since each step depends on the previous one. diff --git a/home/dot_config/powershell/modules/DotfilesHelpers/Public/GitHubCredentialPlacement.ps1 b/home/dot_config/powershell/modules/DotfilesHelpers/Public/GitHubCredentialPlacement.ps1 index 381111aa..fa412a36 100644 --- a/home/dot_config/powershell/modules/DotfilesHelpers/Public/GitHubCredentialPlacement.ps1 +++ b/home/dot_config/powershell/modules/DotfilesHelpers/Public/GitHubCredentialPlacement.ps1 @@ -161,6 +161,67 @@ function Test-GitHubPagesWorkflow { return $false } +function Get-GitHubReleaseEvidence { + <# + .SYNOPSIS + Explain why a repository counts as one that publishes releases. + .DESCRIPTION + The Automation App credential is needed by repositories that cut + releases through the shared release-please workflow. A repository + qualifies when it has a root release-please-config.json, or at least + one published release whose tag looks like a version (v1.2, 1.2.3). + + Data or state snapshots stored as GitHub releases - tags such as + db-2026-01-01 or news-state - do not look like versions, so they do + not qualify a repository on their own. + + The config file is checked first because it is one cheap call and is + conclusive. Releases are then read a page of 100 at a time, newest + first, stopping at the first versioned one, so a repository whose + version release sits behind many data releases still qualifies. + .PARAMETER Repository + Repository in 'owner/name' form. + .PARAMETER VersionPattern + Regex a release tag must match to count as a version release. + .OUTPUTS + String describing the evidence, or $null when there is none. Throws + when the release list cannot be read, so an API, network or rate-limit + failure is never mistaken for "no releases". + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory = $true)][string]$Repository, + + [Parameter(Mandatory = $false)] + [string]$VersionPattern = '^v?\d+\.\d+' + ) + + $config = Invoke-GitHubApi -Endpoint "repos/$Repository/contents/release-please-config.json" -AllowFailure + if ($null -ne $config) { + return 'release-please-config.json' + } + + $pageSize = 100 + for ($page = 1; ; $page++) { + $releases = Invoke-GitHubApi -Endpoint "repos/$Repository/releases?per_page=$pageSize&page=$page" -AllowFailure + if ($null -eq $releases) { + throw "Could not list releases for $Repository (page $page). Check the gh token, network access and API rate limit." + } + $releases = @($releases) + + $versioned = @($releases | Where-Object { + $null -ne $_ -and -not $_.draft -and [string]$_.tag_name -match $VersionPattern + }) + if ($versioned.Count -gt 0) { + return "release $($versioned[0].tag_name)" + } + if ($releases.Count -lt $pageSize) { + return $null + } + } +} + # SIG # Begin signature block # MIIfEQYJKoZIhvcNAQcCoIIfAjCCHv4CAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG diff --git a/home/dot_config/powershell/modules/DotfilesHelpers/Public/GitHubRepoConfig.ps1 b/home/dot_config/powershell/modules/DotfilesHelpers/Public/GitHubRepoConfig.ps1 index acbf3b0a..80cc6b9d 100644 --- a/home/dot_config/powershell/modules/DotfilesHelpers/Public/GitHubRepoConfig.ps1 +++ b/home/dot_config/powershell/modules/DotfilesHelpers/Public/GitHubRepoConfig.ps1 @@ -238,6 +238,15 @@ function Get-GitHubRepoConfig { this to leave upstream clones alone. Every result carries an IsFork property, so forks can also be filtered after the fact. + .PARAMETER HasRelease + Keep only repositories that publish releases, when used with -All: + non-archived, non-fork repositories with a root + release-please-config.json or at least one published release whose + tag looks like a version (^v?\d+\.\d+). Data or state releases such as + db-2026-01-01 or news-state do not count. Use it to scope the + Automation App credential rollout to the repositories that need it. + Each result records why it qualified on ReleaseEvidence. + .PARAMETER Check Categories to audit. Defaults to Settings, Actions and Ruleset. AppCredential is opt-in because listing secrets needs extra token @@ -278,6 +287,13 @@ function Get-GitHubRepoConfig { Audit only the forks. + .EXAMPLE + Get-GitHubRepoConfig -All -HasRelease -Check AppCredential + + Audit the App credential on the repositories that publish releases. + The number of repositories kept by the filter is reported on the + information stream. + .NOTES A category that cannot be evaluated - a missing token permission, or a plan limitation such as rulesets on a private repository - is reported @@ -315,6 +331,9 @@ function Get-GitHubRepoConfig { [Parameter(Mandatory = $false, ParameterSetName = 'All')] [switch]$ExcludeForks, + [Parameter(Mandatory = $false, ParameterSetName = 'All')] + [switch]$HasRelease, + [Parameter(Mandatory = $false)] [ValidateSet('Settings', 'Actions', 'Ruleset', 'AppCredential', 'CloudflareCredential')] [string[]]$Check = @('Settings', 'Actions', 'Ruleset'), @@ -326,6 +345,17 @@ function Get-GitHubRepoConfig { begin { Test-GitHubCliReady + if ($HasRelease -and $IncludeArchived) { + throw "-HasRelease only selects active repositories; it cannot be combined with -IncludeArchived." + } + + # The release filter summary goes to the information stream, shown by + # default; -InformationAction SilentlyContinue mutes it. + if (-not $PSBoundParameters.ContainsKey('InformationAction')) { + $InformationPreference = 'Continue' + } + + $releaseEvidence = @{} $desired = if ($PSBoundParameters.ContainsKey('Baseline')) { Get-GitHubRepoBaseline -Override $Baseline } @@ -348,12 +378,43 @@ function Get-GitHubRepoConfig { Write-Verbose "Skipping archived repository $($repo.nameWithOwner)" continue } - if ($repo.isFork -and $ExcludeForks) { + if ($repo.isFork -and ($ExcludeForks -or $HasRelease)) { Write-Verbose "Skipping fork $($repo.nameWithOwner)" continue } $targets.Add($repo.nameWithOwner) } + + if ($HasRelease) { + $listedCount = $targets.Count + $unreadable = 0 + $releaseTargets = [System.Collections.Generic.List[string]]::new() + foreach ($candidate in $targets) { + try { + $evidence = Get-GitHubReleaseEvidence -Repository $candidate + } + catch { + # Leaving it out is the safe default for a rollout, + # but it must be visible rather than silent. + Write-Warning "Release filter could not check ${candidate}, so it is left out of this run: $($_.Exception.Message)" + $unreadable++ + continue + } + if ($null -eq $evidence) { + Write-Verbose "Skipping ${candidate}: no release-please-config.json and no versioned release" + continue + } + Write-Verbose "Keeping ${candidate}: $evidence" + $releaseEvidence[$candidate] = $evidence + $releaseTargets.Add($candidate) + } + $targets = $releaseTargets + $message = "Release filter: $($targets.Count) of $listedCount active, non-fork repositories in $Owner publish releases." + if ($unreadable -gt 0) { + $message += " $unreadable could not be checked and were left out; see the warnings." + } + Write-Information -MessageData $message -Tags 'GitHubRepoConfig' + } } } @@ -643,6 +704,7 @@ function Get-GitHubRepoConfig { ExtraBranchPolicies = $extraBranchPolicies DefaultBranch = $repo.default_branch UsesPagesWorkflow = $usesPagesWorkflow + ReleaseEvidence = $releaseEvidence[$target] } } } @@ -660,6 +722,12 @@ function Set-GitHubRepoConfig { Supports -WhatIf for a dry run: every change is printed, nothing is sent. This is the recommended way to preview a bulk change. + A line per repository (what was applied or skipped) and a run summary + are written to the information stream and shown by default. Mute them + with -InformationAction SilentlyContinue, or capture them with + -InformationVariable. Only setting and secret names are logged, never + secret values. + Authentication is delegated to the `gh` CLI. Writing repository settings requires a token with the fine-grained `administration:write` permission; writing the App credential additionally requires @@ -774,6 +842,11 @@ function Set-GitHubRepoConfig { begin { Test-GitHubCliReady $pending = [System.Collections.Generic.List[PSObject]]::new() + + if (-not $PSBoundParameters.ContainsKey('InformationAction')) { + $InformationPreference = 'Continue' + } + $summary = [ordered]@{ Repositories = 0; Compliant = 0; Unevaluated = 0; Archived = 0; Changed = 0; Applied = 0; Previewed = 0; Skipped = 0 } } process { @@ -794,19 +867,35 @@ function Set-GitHubRepoConfig { end { foreach ($config in $pending) { $target = $config.Repository + $summary.Repositories++ if ($config.IsArchived) { Write-Warning "Skipping $target because it is archived and rejects writes." + $summary.Archived++ continue } $drift = @($config.Drift) + # A category the audit could not read has no drift recorded, which + # must not be mistaken for compliance. + $unevaluated = @($config.SkippedChecks | Select-Object -Unique) if ($PSBoundParameters.ContainsKey('Category')) { $drift = @($drift | Where-Object { $Category -contains $_.Category }) + $unevaluated = @($unevaluated | Where-Object { $Category -contains $_ }) } + $notEvaluated = if ($unevaluated.Count -gt 0) { "; not evaluated [$($unevaluated -join ', ')]" } else { '' } + if ($unevaluated.Count -gt 0) { $summary.Unevaluated++ } if ($drift.Count -eq 0) { - Write-Verbose "$target is already compliant; nothing to do." + if ($unevaluated.Count -gt 0) { + Write-Verbose "$target has no drift in the evaluated categories; nothing to do." + Write-Information -MessageData "${target}: no drift found$notEvaluated" -Tags 'GitHubRepoConfig' + } + else { + Write-Verbose "$target is already compliant; nothing to do." + Write-Information -MessageData "${target}: already compliant" -Tags 'GitHubRepoConfig' + $summary.Compliant++ + } if ($PassThru) { [PSCustomObject]@{ PSTypeName = 'Dotfiles.GitHubRepoConfigResult' @@ -952,6 +1041,13 @@ function Set-GitHubRepoConfig { } } + if ($needsPin -and $WhatIfPreference) { + # A dry run cannot create the pin, but the preview should + # still list the writes that would follow it. Nothing is + # written: every later step is behind ShouldProcess too. + $environmentReady = $true + } + if ($useEnv -and -not $environmentReady) { Write-Warning "Not writing the App credential to ${target}: environment '$envName' is not pinned to the default branch, so an environment secret there would be no safer than a repository secret." foreach ($item in $credentialDrift) { @@ -1043,6 +1139,26 @@ function Set-GitHubRepoConfig { } } + $changes = @($drift | ForEach-Object { "$($_.Category)/$($_.Setting)" }) + $skippedNote = if ($skipped.Count -gt 0) { "; skipped [$($skipped -join ', ')]" } else { '' } + $summary.Skipped += $skipped.Count + if ($WhatIfPreference) { + # Items skipped before ShouldProcess (a missing credential, an + # environment that cannot be pinned) would not be written either. + $previewed = @($changes | Where-Object { $skipped -notcontains $_ }) + $summary.Previewed += $previewed.Count + $message = "${target}: $($previewed.Count) change(s) previewed, none applied" + if ($previewed.Count -gt 0) { $message += " [$($previewed -join ', ')]" } + Write-Information -MessageData ($message + $skippedNote + $notEvaluated) -Tags 'GitHubRepoConfig' + } + else { + $summary.Applied += $applied.Count + if ($applied.Count -gt 0) { $summary.Changed++ } + $message = "${target}: applied $($applied.Count) of $($changes.Count) change(s)" + if ($applied.Count -gt 0) { $message += " [$($applied -join ', ')]" } + Write-Information -MessageData ($message + $skippedNote + $notEvaluated) -Tags 'GitHubRepoConfig' + } + if ($PassThru) { [PSCustomObject]@{ PSTypeName = 'Dotfiles.GitHubRepoConfigResult' @@ -1052,6 +1168,15 @@ function Set-GitHubRepoConfig { } } } + + $message = "Summary: $($summary.Repositories) repositories, $($summary.Compliant) already compliant, $($summary.Unevaluated) not fully evaluated, $($summary.Archived) archived" + if ($WhatIfPreference) { + $message += ", $($summary.Previewed) change(s) previewed, $($summary.Skipped) item(s) skipped. WhatIf: nothing was written." + } + else { + $message += ", $($summary.Changed) changed ($($summary.Applied) change(s) applied), $($summary.Skipped) item(s) skipped." + } + Write-Information -MessageData $message -Tags 'GitHubRepoConfig' } } diff --git a/home/dot_config/powershell/modules/DotfilesHelpers/Public/OnePasswordCredential.ps1 b/home/dot_config/powershell/modules/DotfilesHelpers/Public/OnePasswordCredential.ps1 index aa29543e..63e7256d 100644 --- a/home/dot_config/powershell/modules/DotfilesHelpers/Public/OnePasswordCredential.ps1 +++ b/home/dot_config/powershell/modules/DotfilesHelpers/Public/OnePasswordCredential.ps1 @@ -9,6 +9,10 @@ # entry fails immediately with a message naming what to create, rather # than surfacing as an empty secret partway through a bulk rollout. # +# The GitHub App key can alternatively be read from the downloaded +# `.private-key.pem` file (Get-GitHubAppCredential -PrivateKeyPath), for +# machines without 1Password or for a one-off key rotation. +# # Part of the GitHub repository configuration tooling; see # GitHubRepoConfig.ps1 for the public commands and docs/github-repo-config.md # for the user-facing guide. @@ -205,18 +209,206 @@ function ConvertFrom-DotfilesSecureString { } } +function Test-GitHubAppPrivateKeyDer { + <# + .SYNOPSIS + Structurally check that DER bytes encode an RSA private key. + .DESCRIPTION + Fallback for Windows PowerShell 5.1, whose .NET Framework cannot import + PEM keys. Verifies that the outer SEQUENCE spans the whole payload and + starts with version INTEGER 0, then that a PKCS#1 key continues with the + modulus INTEGER and a PKCS#8 key names the rsaEncryption algorithm. Not + a full parse, but it rejects empty bodies, base64-encoded text and + non-RSA keys. + .PARAMETER Der + The decoded PEM body. + .PARAMETER Label + The PEM label: 'RSA PRIVATE KEY' (PKCS#1) or 'PRIVATE KEY' (PKCS#8). + #> + [CmdletBinding()] + [OutputType([bool])] + param( + [Parameter(Mandatory = $true)] + [AllowEmptyCollection()] + [byte[]]$Der, + + [Parameter(Mandatory = $true)] + [ValidateSet('RSA PRIVATE KEY', 'PRIVATE KEY')] + [string]$Label + ) + + if ($Der.Length -lt 16 -or $Der[0] -ne 0x30) { return $false } + + $offset = 2 + $length = [long]$Der[1] + if ($length -ge 0x80) { + $count = $length - 0x80 + if ($count -lt 1 -or $count -gt 4) { return $false } + $length = 0 + for ($i = 0; $i -lt $count; $i++) { $length = ($length * 256) + $Der[2 + $i] } + $offset = 2 + $count + } + if ($offset + $length -ne $Der.Length) { return $false } + + if ($Der[$offset] -ne 0x02 -or $Der[$offset + 1] -ne 0x01 -or $Der[$offset + 2] -ne 0x00) { return $false } + $next = $offset + 3 + + if ($Label -eq 'RSA PRIVATE KEY') { + return ($Der[$next] -eq 0x02) + } + + # AlgorithmIdentifier SEQUENCE { OID 1.2.840.113549.1.1.1 (rsaEncryption), NULL } + $rsaOid = [byte[]](0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01) + if ($Der[$next] -ne 0x30 -or $Der.Length -lt ($next + 2 + $rsaOid.Length)) { return $false } + for ($i = 0; $i -lt $rsaOid.Length; $i++) { + if ($Der[$next + 2 + $i] -ne $rsaOid[$i]) { return $false } + } + return $true +} + +function Test-GitHubAppPrivateKeyBlock { + <# + .SYNOPSIS + Is this PEM block a usable RSA private key? + .DESCRIPTION + A block can carry the right header and still hold garbage - an empty + body or base64-encoded text - which would roll out as an unusable + secret. On PowerShell 7 the key is imported with .NET, which fully + validates it; Windows PowerShell 5.1 falls back to a structural DER + check. Returns a boolean and never surfaces the key or the parser's + message. + .PARAMETER Block + The PEM block, BEGIN and END lines included. + .PARAMETER Label + The PEM label: 'RSA PRIVATE KEY' or 'PRIVATE KEY'. + #> + [CmdletBinding()] + [OutputType([bool])] + param( + [Parameter(Mandatory = $true)][string]$Block, + [Parameter(Mandatory = $true)][string]$Label + ) + + $rsa = [System.Security.Cryptography.RSA]::Create() + $der = $null + try { + if ($null -ne $rsa.PSObject.Methods['ImportFromPem']) { + $rsa.ImportFromPem($Block) + return $true + } + + $body = ($Block -replace '-----(BEGIN|END) [A-Z ]+-----', '') -replace '\s', '' + $der = [System.Convert]::FromBase64String($body) + return (Test-GitHubAppPrivateKeyDer -Der $der -Label $Label) + } + catch { + return $false + } + finally { + if ($null -ne $der) { [Array]::Clear($der, 0, $der.Length) } + $rsa.Dispose() + } +} + +function Read-GitHubAppPrivateKeyFile { + <# + .SYNOPSIS + Read and validate a GitHub App private key from a PEM file. + .DESCRIPTION + GitHub Apps authenticate with an RSA private key, which the App's + settings page issues as `..private-key.pem`. Both the PKCS#1 + (`BEGIN RSA PRIVATE KEY`) and PKCS#8 (`BEGIN PRIVATE KEY`) encodings + are accepted; certificates, encrypted keys, empty files and anything + else are rejected before a value is returned, and the block itself must + parse as an RSA key (Test-GitHubAppPrivateKeyBlock). + + Error messages name the path and the problem but never echo the file + contents, so a wrong file cannot leak a key into the console, a + transcript or a log. Only the private-key block itself is kept. + .PARAMETER Path + Path to the PEM file. The extension does not matter. + .OUTPUTS + System.Security.SecureString + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingConvertToSecureStringWithPlainText', '', Justification = 'The PEM is read from disk as plain text; converting it to a SecureString immediately is the hardening step, not a weakness.')] + [CmdletBinding()] + [OutputType([System.Security.SecureString])] + param( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$Path + ) + + $howToGetOne = "Generate one on the GitHub App's settings page (General -> Private keys); the download is named like '..private-key.pem'." + + if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { + throw "GitHub App private key file '$Path' was not found. $howToGetOne" + } + + $resolved = (Resolve-Path -LiteralPath $Path).ProviderPath + $text = $null + $keys = $null + + try { + try { + $text = [System.IO.File]::ReadAllText($resolved) + } + catch { + throw "GitHub App private key file '$resolved' could not be read: $($_.Exception.Message)" + } + + if ([string]::IsNullOrWhiteSpace($text)) { + throw "GitHub App private key file '$resolved' is empty. $howToGetOne" + } + + # [regex]::IsMatch rather than -match, so $Matches never holds any of + # the file contents. + if ([regex]::IsMatch($text, '-----BEGIN [A-Z0-9 ]*CERTIFICATE-----')) { + throw "'$resolved' contains a certificate, not a private key. GitHub Apps authenticate with the App's private key ('-----BEGIN RSA PRIVATE KEY-----'). $howToGetOne" + } + + if ([regex]::IsMatch($text, '-----BEGIN ENCRYPTED PRIVATE KEY-----|Proc-Type:\s*4,ENCRYPTED')) { + throw "'$resolved' holds a passphrase-protected private key. GitHub Actions needs the key unencrypted, exactly as GitHub issued it." + } + + $keys = [regex]::Matches($text, '-----BEGIN (RSA PRIVATE KEY|PRIVATE KEY)-----\s+[A-Za-z0-9+/=\s]+?-----END \1-----') + if ($keys.Count -eq 0) { + throw "'$resolved' does not contain a PEM private key. Expected a '-----BEGIN RSA PRIVATE KEY-----' or '-----BEGIN PRIVATE KEY-----' block. $howToGetOne" + } + if ($keys.Count -gt 1) { + throw "'$resolved' contains $($keys.Count) private keys. Pass a file that holds exactly one." + } + + $label = $keys[0].Groups[1].Value + if (-not (Test-GitHubAppPrivateKeyBlock -Block $keys[0].Value -Label $label)) { + throw "'$resolved' has a '-----BEGIN $label-----' block, but it does not hold a valid RSA private key. GitHub Apps sign with RSA keys. $howToGetOne" + } + + return (ConvertTo-SecureString -String $keys[0].Value -AsPlainText -Force) + } + finally { + $text = $null + $keys = $null + } +} + function Get-GitHubAppCredential { <# .SYNOPSIS - Read a GitHub App ID and private key from 1Password. + Read a GitHub App ID and private key from 1Password or a PEM file. .DESCRIPTION - Resolves two 1Password secret references with `op read` and returns - them as an object. The private key is returned as a SecureString so it - is not left as a plain string in the session; the App ID is returned as - plain text because it is a non-secret identifier. + By default, resolves two 1Password secret references with `op read` + and returns them as an object. With -PrivateKeyPath, the key is read + from a local PEM file instead and the App ID is taken from -AppId, so + 1Password is not needed at all. + + Either way the private key is returned as a SecureString so it is not + left as a plain string in the session; the App ID is returned as plain + text because it is a non-secret identifier. The key is never written to + any output stream. - Before reading anything, the 1Password CLI is checked for being + When reading from 1Password, the CLI is first checked for being installed and unlocked, and both the item and the fields are verified to exist. A missing entry therefore fails immediately with a message naming exactly what to create, rather than surfacing as an empty value partway @@ -234,6 +426,11 @@ function Get-GitHubAppCredential { variables. Secret references are non-secret identifiers, useless without authenticating to 1Password. + The PEM file passed to -PrivateKeyPath must hold exactly one unencrypted + private key, in PKCS#1 ('-----BEGIN RSA PRIVATE KEY-----') or PKCS#8 + ('-----BEGIN PRIVATE KEY-----') form. A certificate, an encrypted key, + an empty file or any other content is rejected with an explanation. + .PARAMETER AppIdReference 1Password secret reference for the App ID, in `op://Vault/Item/field` form. Defaults to $env:OP_GITHUB_APP_ID_REF, then to @@ -244,6 +441,15 @@ function Get-GitHubAppCredential { $env:OP_GITHUB_APP_KEY_REF, then to 'op://Private/GitHub Automation App/private-key'. + .PARAMETER AppId + The numeric App ID from the App's settings page. Required with + -PrivateKeyPath. + + .PARAMETER PrivateKeyPath + Path to the App's private key file, such as the downloaded + '..private-key.pem'. Reads the key from disk instead of from + 1Password. + .EXAMPLE Get-GitHubAppCredential @@ -260,21 +466,52 @@ function Get-GitHubAppCredential { Read the credential from a different vault or item. + .EXAMPLE + $cred = Get-GitHubAppCredential -AppId 3563533 -PrivateKeyPath ~/Downloads/automation-app.2026-11-14.private-key.pem + Get-GitHubRepoConfig -All -HasRelease -Check AppCredential | Set-GitHubRepoConfig -AppCredential $cred -WhatIf + + Read the key from the downloaded file and preview rolling it out to the + repositories that publish releases. + .OUTPUTS PSCustomObject with AppId (string) and PrivateKey (SecureString). #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Read-only; does not change system state.')] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingConvertToSecureStringWithPlainText', '', Justification = 'The 1Password CLI returns the PEM as plain text; converting it to a SecureString immediately is the hardening step, not a weakness.')] - [CmdletBinding()] + [CmdletBinding(DefaultParameterSetName = 'OnePassword')] [OutputType([PSCustomObject])] param( - [Parameter(Mandatory = $false)] + [Parameter(Mandatory = $false, ParameterSetName = 'OnePassword')] [string]$AppIdReference, - [Parameter(Mandatory = $false)] - [string]$PrivateKeyReference + [Parameter(Mandatory = $false, ParameterSetName = 'OnePassword')] + [string]$PrivateKeyReference, + + [Parameter(Mandatory = $true, ParameterSetName = 'File')] + [string]$AppId, + + [Parameter(Mandatory = $true, ParameterSetName = 'File')] + [ValidateNotNullOrEmpty()] + [string]$PrivateKeyPath ) + if ($PSCmdlet.ParameterSetName -eq 'File') { + $AppId = $AppId.Trim() + if ($AppId -notmatch '^\d+$') { + throw "'$AppId' is not a numeric GitHub App ID. Use the 'App ID' from the App's settings page, not the client ID or slug." + } + + Write-Verbose "Reading GitHub App private key from file '$PrivateKeyPath'" + $secure = Read-GitHubAppPrivateKeyFile -Path $PrivateKeyPath + Write-Verbose "Private key file validated for App ID $AppId" + + return [PSCustomObject]@{ + PSTypeName = 'Dotfiles.GitHubAppCredential' + AppId = $AppId + PrivateKey = $secure + } + } + if ([string]::IsNullOrWhiteSpace($AppIdReference)) { $AppIdReference = $env:OP_GITHUB_APP_ID_REF } diff --git a/tests/powershell/GitHubRepoConfig.Tests.ps1 b/tests/powershell/GitHubRepoConfig.Tests.ps1 index 6c865416..67764e98 100644 --- a/tests/powershell/GitHubRepoConfig.Tests.ps1 +++ b/tests/powershell/GitHubRepoConfig.Tests.ps1 @@ -22,6 +22,10 @@ BeforeAll { Get-Module DotfilesHelpers -All | Remove-Module -Force -ErrorAction SilentlyContinue Import-Module $modulePath -Force -DisableNameChecking + # Set-GitHubRepoConfig logs to the information stream by default; keep the + # test output quiet. Tests that assert on the log use -InformationVariable. + $global:PSDefaultParameterValues['Set-GitHubRepoConfig:InformationAction'] = 'SilentlyContinue' + # A repository whose settings already match the baseline exactly. function script:New-CompliantRepoResponse { return [PSCustomObject]@{ @@ -138,6 +142,10 @@ BeforeAll { } } +AfterAll { + $global:PSDefaultParameterValues.Remove('Set-GitHubRepoConfig:InformationAction') +} + Describe "GitHub repo config command availability" -Tag "Unit" { It "exports <_>" -ForEach @( 'Get-GitHubRepoBaseline' @@ -1251,6 +1259,459 @@ Describe "Rubber-duck regressions" -Tag "Unit" { } } +Describe "Get-GitHubAppCredential -PrivateKeyPath" -Tag "Unit" { + BeforeAll { + # Genuine throwaway keys generated per run, never written outside + # TestDrive. KeyMarker is a slice of the key material used to detect + # any leak into an output stream. + $rsa = [System.Security.Cryptography.RSA]::Create(2048) + $script:RsaPem = $rsa.ExportRSAPrivateKeyPem() + $script:Pkcs8Pem = $rsa.ExportPkcs8PrivateKeyPem() + $script:EcPem = [System.Security.Cryptography.ECDsa]::Create().ExportPkcs8PrivateKeyPem() + $script:KeyMarker = ($script:RsaPem -split "`n")[2].Substring(0, 40) + $rsa.Dispose() + + function script:New-KeyFile { + param([string]$Content, [string]$Name = 'automation-app.2026-11-14.private-key.pem') + $path = Join-Path $TestDrive $Name + [System.IO.File]::WriteAllText($path, $Content) + return $path + } + + function script:ConvertFrom-TestSecureString { + param([System.Security.SecureString]$SecureString) + InModuleScope DotfilesHelpers -Parameters @{ S = $SecureString } { + param($S) + ConvertFrom-DotfilesSecureString -SecureString $S + } + } + } + + Context "valid keys" { + It "reads a key into a SecureString" -ForEach @( + @{ Kind = 'PKCS#1 RSA' } + @{ Kind = 'PKCS#8' } + @{ Kind = 'CRLF' } + ) { + $pem = switch ($Kind) { + 'PKCS#1 RSA' { $script:RsaPem } + 'PKCS#8' { $script:Pkcs8Pem } + 'CRLF' { $script:RsaPem -replace "`n", "`r`n" } + } + $path = script:New-KeyFile -Content "$pem`n" + + $cred = Get-GitHubAppCredential -AppId 3563533 -PrivateKeyPath $path + + $cred.AppId | Should -Be '3563533' + $cred.PrivateKey | Should -BeOfType [System.Security.SecureString] + script:ConvertFrom-TestSecureString -SecureString $cred.PrivateKey | Should -Be $pem + } + + It "accepts the '.private-key' extension" { + $path = script:New-KeyFile -Content $script:RsaPem -Name 'automation-app.private-key' + (Get-GitHubAppCredential -AppId 1 -PrivateKeyPath $path).AppId | Should -Be '1' + } + + It "keeps only the key block, dropping text around it" { + $path = script:New-KeyFile -Content "Bag Attributes`n localKeyID: 01`n$($script:RsaPem)`n`n" + $cred = Get-GitHubAppCredential -AppId 1 -PrivateKeyPath $path + script:ConvertFrom-TestSecureString -SecureString $cred.PrivateKey | Should -Be $script:RsaPem + } + + It "does not touch 1Password" { + Mock -ModuleName DotfilesHelpers Invoke-OnePasswordCli { throw 'op must not be called' } + $path = script:New-KeyFile -Content $script:Pkcs8Pem + + $null = Get-GitHubAppCredential -AppId 1 -PrivateKeyPath $path + + Should -Invoke -ModuleName DotfilesHelpers Invoke-OnePasswordCli -Times 0 -Exactly + } + } + + Context "rejected files" { + It "rejects " -ForEach @( + @{ Case = 'a certificate'; Content = "-----BEGIN CERTIFICATE-----`nMIIDcertificateSentinelBody==`n-----END CERTIFICATE-----"; Message = '*contains a certificate, not a private key*' } + @{ Case = 'a certificate bundled with a key'; Content = "-----BEGIN CERTIFICATE-----`nMIIDcert==`n-----END CERTIFICATE-----`n-----BEGIN RSA PRIVATE KEY-----`nMIIE==`n-----END RSA PRIVATE KEY-----"; Message = '*contains a certificate*' } + @{ Case = 'an empty file'; Content = ''; Message = '*is empty*' } + @{ Case = 'a whitespace-only file'; Content = " `n`t`n"; Message = '*is empty*' } + @{ Case = 'arbitrary text'; Content = 'not a key at all'; Message = '*does not contain a PEM private key*' } + @{ Case = 'a public key'; Content = "-----BEGIN PUBLIC KEY-----`nMIIBIjAN==`n-----END PUBLIC KEY-----"; Message = '*does not contain a PEM private key*' } + @{ Case = 'mismatched BEGIN/END lines'; Content = "-----BEGIN RSA PRIVATE KEY-----`nMIIE==`n-----END PRIVATE KEY-----"; Message = '*does not contain a PEM private key*' } + @{ Case = 'an encrypted PKCS#8 key'; Content = "-----BEGIN ENCRYPTED PRIVATE KEY-----`nMIIE==`n-----END ENCRYPTED PRIVATE KEY-----"; Message = '*passphrase-protected*' } + @{ Case = 'an encrypted PKCS#1 key'; Content = "-----BEGIN RSA PRIVATE KEY-----`nProc-Type: 4,ENCRYPTED`nDEK-Info: AES-128-CBC,00`n`nMIIE==`n-----END RSA PRIVATE KEY-----"; Message = '*passphrase-protected*' } + @{ Case = 'two keys'; Content = "-----BEGIN RSA PRIVATE KEY-----`nMIIE==`n-----END RSA PRIVATE KEY-----`n-----BEGIN PRIVATE KEY-----`nMIIE==`n-----END PRIVATE KEY-----"; Message = '*contains 2 private keys*' } + @{ Case = 'a whitespace-only key body'; Content = "-----BEGIN RSA PRIVATE KEY-----`n `n-----END RSA PRIVATE KEY-----"; Message = '*does not hold a valid RSA private key*' } + @{ Case = 'base64-encoded text'; Content = "-----BEGIN RSA PRIVATE KEY-----`naGVsbG8gd29ybGQsIHRoaXMgaXMgbm90IGEga2V5`n-----END RSA PRIVATE KEY-----"; Message = '*does not hold a valid RSA private key*' } + @{ Case = 'a truncated key'; Content = "-----BEGIN PRIVATE KEY-----`nMIIEvQIBADANBgkqhkiG9w0BAQEFAASC`n-----END PRIVATE KEY-----"; Message = '*does not hold a valid RSA private key*' } + @{ Case = 'a minimal AAAA body'; Content = "-----BEGIN RSA PRIVATE KEY-----`nAAAA`n-----END RSA PRIVATE KEY-----"; Message = '*does not hold a valid RSA private key*' } + ) { + $path = script:New-KeyFile -Content $Content + { Get-GitHubAppCredential -AppId 1 -PrivateKeyPath $path } | Should -Throw -ExpectedMessage $Message + } + + It "rejects a non-RSA (EC) PKCS#8 key" { + $path = script:New-KeyFile -Content $script:EcPem + { Get-GitHubAppCredential -AppId 1 -PrivateKeyPath $path } | + Should -Throw -ExpectedMessage '*does not hold a valid RSA private key*' + } + + It "rejects a missing file" { + { Get-GitHubAppCredential -AppId 1 -PrivateKeyPath (Join-Path $TestDrive 'missing.pem') } | + Should -Throw -ExpectedMessage '*was not found*' + } + + It "rejects a directory" { + { Get-GitHubAppCredential -AppId 1 -PrivateKeyPath $TestDrive } | + Should -Throw -ExpectedMessage '*was not found*' + } + + It "rejects an App ID that is not numeric" { + $path = script:New-KeyFile -Content $script:RsaPem + { Get-GitHubAppCredential -AppId 'Iv1.abc123' -PrivateKeyPath $path } | + Should -Throw -ExpectedMessage '*not a numeric GitHub App ID*' + } + + It "cannot mix a file with 1Password references" { + $path = script:New-KeyFile -Content $script:RsaPem + { Get-GitHubAppCredential -AppId 1 -PrivateKeyPath $path -PrivateKeyReference 'op://a/b/c' } | Should -Throw + } + } + + Context "secrecy" { + It "writes no key material to any output stream" { + $path = script:New-KeyFile -Content $script:RsaPem + $info = @() + + $streams = Get-GitHubAppCredential -AppId 1 -PrivateKeyPath $path -Verbose -InformationVariable info *>&1 + + ($streams | Out-String).Contains($script:KeyMarker) | Should -BeFalse + ($info | Out-String).Contains($script:KeyMarker) | Should -BeFalse + } + + It "does not echo file contents in validation errors for " -ForEach @( + @{ Case = 'a certificate'; Content = "-----BEGIN CERTIFICATE-----`nMIIDcertificateSentinelBody==`n-----END CERTIFICATE-----" } + @{ Case = 'an invalid key body'; Content = "-----BEGIN RSA PRIVATE KEY-----`nMIIEkeySentinelBodyNotAKey==`n-----END RSA PRIVATE KEY-----" } + ) { + $path = script:New-KeyFile -Content $Content + $message = try { Get-GitHubAppCredential -AppId 1 -PrivateKeyPath $path; '' } catch { $_.Exception.Message } + $message | Should -Not -BeNullOrEmpty + $message | Should -Not -Match 'Sentinel' + } + } + + Context "Windows PowerShell 5.1 structural fallback" { + BeforeAll { + function script:Test-DerFromBase64 { + param([string]$Base64, [string]$Label) + InModuleScope DotfilesHelpers -Parameters @{ Base64 = $Base64; Label = $Label } { + param($Base64, $Label) + Test-GitHubAppPrivateKeyDer -Der ([System.Convert]::FromBase64String($Base64)) -Label $Label + } + } + function script:Get-PemBase64 { + param([string]$Pem) + ($Pem -replace '-----[A-Z ]+-----', '') -replace '\s', '' + } + } + + It "accepts a genuine