From 6660fe91979ce1cd3f08d0c6c746ab951a83f2ec Mon Sep 17 00:00:00 2001 From: Marius Storhaug Date: Wed, 4 Nov 2026 13:56:36 +0100 Subject: [PATCH 01/10] Use pull_request in the release workflow example --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9bcd513..36bfaed 100644 --- a/README.md +++ b/README.md @@ -83,7 +83,7 @@ Add a workflow in your repository using the following example: name: Release-GHRepository on: - pull_request_target: + pull_request: branches: - main types: From 2b77b27ef666cbbda8c5148f0538bcff4bd4b018 Mon Sep 17 00:00:00 2001 From: Marius Storhaug Date: Mon, 16 Nov 2026 13:56:19 +0100 Subject: [PATCH 02/10] Lock release dependencies and enforce trusted publication --- action.yml | 6 +- src/Release-GHRepository.Dependencies.psd1 | 14 + src/Release-GHRepository.Helpers.psm1 | 345 +++++++++++++++++++++ src/main.ps1 | 155 ++++++--- tests/Release-GHRepository.Tests.ps1 | 340 ++++++++++++++++++++ 5 files changed, 809 insertions(+), 51 deletions(-) create mode 100644 src/Release-GHRepository.Dependencies.psd1 create mode 100644 src/Release-GHRepository.Helpers.psm1 create mode 100644 tests/Release-GHRepository.Tests.ps1 diff --git a/action.yml b/action.yml index bd28559..61749a1 100644 --- a/action.yml +++ b/action.yml @@ -35,7 +35,7 @@ inputs: required: false default: NoRelease IncrementalPrerelease: - description: Control whether to automatically increment the prerelease number. If disabled, the action will ensure only one prerelease exists for a given branch. + description: Control whether to automatically increment the prerelease number. If disabled, the action replaces the prerelease for the pull request. required: false default: 'true' MajorLabels: @@ -67,7 +67,7 @@ inputs: required: false default: v WhatIf: - description: If specified, the action will only log the changes it would make, but will not actually create or delete any releases or tags. + description: Simulate release and tag changes. Always enabled for pull_request checks. A true input cannot be disabled by the configuration file. required: false default: 'false' Debug: @@ -81,6 +81,7 @@ inputs: Version: description: Specifies the version of the GitHub module to be installed. Accepts an exact version or a NuGet version range (for example '[1.2.0, 2.0.0)'). required: false + default: '[0.43.1]' Prerelease: description: Allow prerelease versions if available. required: false @@ -117,6 +118,7 @@ runs: Prerelease: ${{ inputs.Prerelease }} Verbose: ${{ inputs.Verbose }} Version: ${{ inputs.Version }} + PreserveCredentials: false Name: Release-GHRepository WorkingDirectory: ${{ inputs.WorkingDirectory }} Script: | diff --git a/src/Release-GHRepository.Dependencies.psd1 b/src/Release-GHRepository.Dependencies.psd1 new file mode 100644 index 0000000..032d089 --- /dev/null +++ b/src/Release-GHRepository.Dependencies.psd1 @@ -0,0 +1,14 @@ +@{ + Modules = @( + @{ + Name = 'powershell-yaml' + Version = '0.4.12' + SHA256 = 'D4602BC7A4A093766520422D53CA8B09ACDE162286FAE11E2EE6C8EDFEA07810' + } + @{ + Name = 'PSSemVer' + Version = '1.1.10' + SHA256 = '49E79D95C31C3D756A2378634128A360FC8EFAE4CE7409E3F16A55AA94AC5820' + } + ) +} diff --git a/src/Release-GHRepository.Helpers.psm1 b/src/Release-GHRepository.Helpers.psm1 new file mode 100644 index 0000000..44ab3ae --- /dev/null +++ b/src/Release-GHRepository.Helpers.psm1 @@ -0,0 +1,345 @@ +#Requires -Version 7.0 + +$ErrorActionPreference = 'Stop' + +function Import-VerifiedReleaseModule { + <# + .SYNOPSIS + Verify a package before extracting and importing its module. + + .DESCRIPTION + Check the package SHA256 and module version. Import the verified manifest by path, + so a same-name module elsewhere on the runner cannot replace it. + + .EXAMPLE + Import-VerifiedReleaseModule -Path $package -DestinationPath $directory -Name $name -RequiredVersion $version -SHA256 $hash + + .INPUTS + None + + You can't pipe objects to Import-VerifiedReleaseModule. + + .OUTPUTS + System.Management.Automation.PSModuleInfo + + The imported module. + #> + [OutputType([System.Management.Automation.PSModuleInfo])] + [CmdletBinding(SupportsShouldProcess)] + param( + # The downloaded package. + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $Path, + + # A new directory for the verified module files. + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [ValidateScript({ [System.IO.Path]::IsPathFullyQualified($_) })] + [string] $DestinationPath, + + # The module name declared in the dependency lock. + [Parameter(Mandatory)] + [ValidatePattern('^[A-Za-z0-9_.-]+$')] + [string] $Name, + + # The exact reviewed module version. + [Parameter(Mandatory)] + [version] $RequiredVersion, + + # The reviewed package digest. + [Parameter(Mandatory)] + [ValidatePattern('^[A-Fa-f0-9]{64}$')] + [string] $SHA256 + ) + + $packagePath = (Resolve-Path -LiteralPath $Path -ErrorAction Stop).ProviderPath + $actualHash = (Get-FileHash -LiteralPath $packagePath -Algorithm SHA256 -ErrorAction Stop).Hash + if ($actualHash -ne $SHA256) { + throw "SHA256 verification failed for [$Name $RequiredVersion]. Do not import this package." + } + if (Test-Path -LiteralPath $DestinationPath) { + throw "The verified module directory already exists: [$DestinationPath]. Use a new directory." + } + + if ($PSCmdlet.ShouldProcess("$Name $RequiredVersion", 'Import verified module')) { + [System.IO.Compression.ZipFile]::ExtractToDirectory($packagePath, $DestinationPath) + $manifestPath = Join-Path $DestinationPath "$Name.psd1" + $manifest = Import-PowerShellDataFile -LiteralPath $manifestPath -ErrorAction Stop + if ([version] $manifest.ModuleVersion -ne $RequiredVersion) { + throw "The package does not contain [$Name] at the required version [$RequiredVersion]." + } + + $moduleSpecification = @{ + ModuleName = $manifestPath + RequiredVersion = $RequiredVersion + } + Import-Module -FullyQualifiedName $moduleSpecification -Global -Force -PassThru -ErrorAction Stop + } +} + +function Assert-ReleasePullRequest { + <# + .SYNOPSIS + Validate PR metadata before privileged publication. + + .DESCRIPTION + Require successful PR checks from this repository and the default branch. + Bind the live PR to the checked commit and reject stale or ambiguous metadata. + + .EXAMPLE + Assert-ReleasePullRequest -PullRequest $pr -WorkflowRun $run -Repository 'owner/repo' -DefaultBranch 'main' + + .INPUTS + None + + You can't pipe objects to Assert-ReleasePullRequest. + + .OUTPUTS + None + + This function throws when the publication metadata is invalid. + #> + [OutputType([void])] + [CmdletBinding()] + param( + # The live PR returned by the repository API. + [Parameter(Mandatory)] + [ValidateNotNull()] + [pscustomobject] $PullRequest, + + # The workflow_run event's run metadata. + [Parameter(Mandatory)] + [ValidateNotNull()] + [pscustomobject] $WorkflowRun, + + # The repository that owns the publishing workflow. + [Parameter(Mandatory)] + [ValidatePattern('^[^/]+/[^/]+$')] + [string] $Repository, + + # The repository's default branch. + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $DefaultBranch, + + # API associations for runs whose PR list is empty, including merged PRs. + [Parameter()] + [pscustomobject[]] $CommitPullRequests = @() + ) + + if ($WorkflowRun.event -ne 'pull_request' -or $WorkflowRun.conclusion -ne 'success') { + throw 'Publication requires a successful pull_request check run.' + } + if ($WorkflowRun.repository.full_name -ne $Repository -or $PullRequest.base.repo.full_name -ne $Repository -or + $WorkflowRun.head_repository.full_name -notin @($Repository, $PullRequest.head.repo.full_name)) { + throw "Publication metadata does not belong to repository [$Repository]." + } + + $associatedPullRequests = @($WorkflowRun.pull_requests) + if ($associatedPullRequests.Count -eq 0) { + $associatedPullRequests = @($CommitPullRequests) + } + if ($associatedPullRequests.Count -ne 1) { + throw 'Publication requires exactly one associated pull request.' + } + $associatedPullRequest = $associatedPullRequests[0] + if ($associatedPullRequest.number -ne $PullRequest.number -or $PullRequest.number -lt 1 -or + $associatedPullRequest.base.repo.id -ne $PullRequest.base.repo.id) { + throw 'Publication metadata does not match the associated pull request.' + } + if ($PullRequest.base.ref -ne $DefaultBranch -or $associatedPullRequest.base.ref -ne $DefaultBranch) { + throw "Publication requires a pull request targeting the default branch [$DefaultBranch]." + } + if (-not $PullRequest.merged -and $PullRequest.head.repo.full_name -ne $Repository) { + throw 'Open-PR prereleases require a branch in this repository.' + } + if ($PullRequest.head.sha -cnotmatch '^[a-f0-9]{40}$' -or + ($PullRequest.merged -and $PullRequest.merge_commit_sha -cnotmatch '^[a-f0-9]{40}$')) { + throw 'Publication requires a valid commit SHA.' + } + if ($associatedPullRequest.head.sha -cne $PullRequest.head.sha) { + throw 'The pull request changed since its checks. Run checks on the latest commit.' + } + if ($WorkflowRun.head_sha -cne $PullRequest.head.sha -and + (-not $PullRequest.merged -or $WorkflowRun.head_sha -cne $PullRequest.merge_commit_sha)) { + throw 'The check run does not identify the PR head or merge commit.' + } + if ($PullRequest.state -eq 'closed') { + if ([string]::IsNullOrWhiteSpace($WorkflowRun.created_at) -or [string]::IsNullOrWhiteSpace($PullRequest.closed_at)) { + throw 'Closed-PR publication requires the check and closure timestamps.' + } + if ([datetimeoffset] $WorkflowRun.created_at -lt [datetimeoffset] $PullRequest.closed_at) { + throw 'The check run predates PR closure. Wait for the closed-PR checks.' + } + } +} + +function Test-ReleasePreview { + <# + .SYNOPSIS + Select preview mode without allowing configuration to enable PR writes. + + .DESCRIPTION + Force previews for regular PR events or an explicit preview request. + Permit writes only in a workflow_run publisher that has passed metadata validation. + + .EXAMPLE + Test-ReleasePreview -EventName 'pull_request' -Configured + + .INPUTS + None + + You can't pipe objects to Test-ReleasePreview. + + .OUTPUTS + System.Boolean + + True when release changes must be simulated. + #> + [OutputType([bool])] + [CmdletBinding()] + param( + # The GitHub Actions event name. + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $EventName, + + # An explicit WhatIf input from the caller. + [Parameter()] + [switch] $Requested, + + # The WhatIf setting from the trusted configuration. + [Parameter()] + [switch] $Configured + ) + + if ($Requested -or $Configured -or $EventName -eq 'pull_request') { + $true + } elseif ($EventName -eq 'workflow_run') { + $false + } else { + throw 'Write operations require a trusted workflow_run publisher. Use WhatIf for other events.' + } +} + +function Get-ReleasePrerelease { + <# + .SYNOPSIS + Select only prereleases in one PR's tag namespace. + + .DESCRIPTION + Exclude stable releases and tags for other PRs before cleanup or replacement. + + .EXAMPLE + Get-ReleasePrerelease -Release $releases -PullRequestNumber 7 -VersionPrefix 'v' + + .INPUTS + None + + You can't pipe objects to Get-ReleasePrerelease. + + .OUTPUTS + System.Management.Automation.PSCustomObject + + The matching prerelease records. + #> + [OutputType([pscustomobject])] + [CmdletBinding()] + param( + # Release records returned by the repository API. + [Parameter(Mandatory)] + [AllowEmptyCollection()] + [pscustomobject[]] $Release, + + # The PR that owns these prerelease tags. + [Parameter(Mandatory)] + [ValidateRange(1, [int]::MaxValue)] + [int] $PullRequestNumber, + + # The configured prefix, including an empty prefix. + [Parameter(Mandatory)] + [AllowEmptyString()] + [string] $VersionPrefix + ) + + $pattern = '^{0}[0-9]+\.[0-9]+\.[0-9]+-pr{1}(?:\.[0-9A-Za-z-]+)*(?:\+[0-9A-Za-z.-]+)?$' -f + [regex]::Escape($VersionPrefix), $PullRequestNumber + $Release | Where-Object { $_.isPrerelease -eq $true -and $_.tagName -cmatch $pattern } +} + +function Set-ReleaseTag { + <# + .SYNOPSIS + Point one release tag at its immutable release commit. + + .DESCRIPTION + Create or update only the requested tag through the repository API. + Do not persist Git credentials or push unrelated local tags. + + .EXAMPLE + Set-ReleaseTag -Repository 'owner/repo' -Name 'v1' -CommitSha $releaseCommit + + .INPUTS + None + + You can't pipe objects to Set-ReleaseTag. + + .OUTPUTS + None + + This function updates the repository tag. + #> + [OutputType([void])] + [CmdletBinding(SupportsShouldProcess)] + param( + # The repository that owns the release. + [Parameter(Mandatory)] + [ValidatePattern('^[^/]+/[^/]+$')] + [string] $Repository, + + # The release tag to create or update. + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $Name, + + # The stable release's merge commit. + [Parameter(Mandatory)] + [ValidatePattern('^[a-f0-9]{40}$')] + [string] $CommitSha + ) + + git check-ref-format "refs/tags/$Name" + if ($LASTEXITCODE -ne 0) { + throw "Invalid release tag name: [$Name]." + } + if ($PSCmdlet.ShouldProcess("$Repository tag $Name", "Point tag at $CommitSha")) { + $encodedName = [uri]::EscapeDataString($Name) + $referencesJson = gh api "repos/$Repository/git/matching-refs/tags/$encodedName" + if ($LASTEXITCODE -ne 0) { + throw "Failed to list tag references for [$Name]." + } + $references = $referencesJson | ConvertFrom-Json -NoEnumerate + if ($references -isnot [array]) { + throw "Failed to list tag references for [$Name]: the API response is not an array." + } + $reference = $references | Where-Object { $_.ref -ceq "refs/tags/$Name" } + if ($reference) { + $arguments = @( + 'api', '--method', 'PATCH', "repos/$Repository/git/refs/tags/$encodedName", + '-f', "sha=$CommitSha", '-F', 'force=true' + ) + } else { + $arguments = @( + 'api', '--method', 'POST', "repos/$Repository/git/refs", + '-f', "ref=refs/tags/$Name", '-f', "sha=$CommitSha" + ) + } + $null = gh @arguments + if ($LASTEXITCODE -ne 0) { + throw "Failed to set release tag [$Name] to [$CommitSha]." + } + } +} + +Export-ModuleMember -Function Import-VerifiedReleaseModule, Assert-ReleasePullRequest, Test-ReleasePreview, Get-ReleasePrerelease, Set-ReleaseTag diff --git a/src/main.ps1 b/src/main.ps1 index 089a75f..16f1d90 100644 --- a/src/main.ps1 +++ b/src/main.ps1 @@ -8,26 +8,34 @@ [CmdletBinding()] param() +$ErrorActionPreference = 'Stop' +Import-Module -Name (Join-Path $PSScriptRoot 'Release-GHRepository.Helpers.psm1') -Force + LogGroup 'Loading libraries' { - 'powershell-yaml', 'PSSemVer' | ForEach-Object { - $name = $_ - Write-Output "Installing module: $name" - $count = 5 - $delay = 10 - for ($i = 1; $i -le $count; $i++) { - try { - Install-PSResource -Name $name -WarningAction SilentlyContinue -TrustRepository -Repository PSGallery - break - } catch { - Write-Warning "Installation of $name failed with error: $_" - if ($i -eq $count) { - throw $_ - } - Write-Warning "Retrying in $delay seconds..." - Start-Sleep -Seconds $delay - } + $dependencies = Import-PowerShellDataFile -LiteralPath (Join-Path $PSScriptRoot 'Release-GHRepository.Dependencies.psd1') + $dependencyDirectory = Join-Path ([System.IO.Path]::GetTempPath()) "Release-GHRepository-$([guid]::NewGuid())" + $null = New-Item -Path $dependencyDirectory -ItemType Directory + foreach ($dependency in $dependencies.Modules) { + $name = $dependency.Name + $version = $dependency.Version + Write-Output "Downloading locked module: [$name $version]" + $packagePath = Join-Path $dependencyDirectory "$name.$version.nupkg" + $downloadParameters = @{ + Uri = "https://www.powershellgallery.com/api/v2/package/$name/$version" + OutFile = $packagePath + MaximumRetryCount = 4 + RetryIntervalSec = 10 + ErrorAction = 'Stop' } - Import-Module -Name $name + Invoke-WebRequest @downloadParameters + $importParameters = @{ + Path = $packagePath + DestinationPath = Join-Path $dependencyDirectory "$name.$version" + Name = $name + RequiredVersion = $version + SHA256 = $dependency.SHA256 + } + $null = Import-VerifiedReleaseModule @importParameters -Confirm:$false } } @@ -49,7 +57,12 @@ LogGroup 'Set configuration' { $usePRTitleAsReleaseName = ![string]::IsNullOrEmpty($configuration.UsePRTitleAsReleaseName) ? $configuration.UsePRTitleAsReleaseName -eq 'true' : $env:PSMODULE_AUTO_RELEASE_INPUT_UsePRTitleAsReleaseName -eq 'true' $usePRTitleAsNotesHeading = ![string]::IsNullOrEmpty($configuration.UsePRTitleAsNotesHeading) ? $configuration.UsePRTitleAsNotesHeading -eq 'true' : $env:PSMODULE_AUTO_RELEASE_INPUT_UsePRTitleAsNotesHeading -eq 'true' $versionPrefix = ![string]::IsNullOrEmpty($configuration.VersionPrefix) ? $configuration.VersionPrefix : $env:PSMODULE_AUTO_RELEASE_INPUT_VersionPrefix - $whatIf = ![string]::IsNullOrEmpty($configuration.WhatIf) ? $configuration.WhatIf -eq 'true' : $env:PSMODULE_AUTO_RELEASE_INPUT_WhatIf -eq 'true' + $previewParameters = @{ + EventName = $env:GITHUB_EVENT_NAME + Requested = $env:PSMODULE_AUTO_RELEASE_INPUT_WhatIf -eq 'true' + Configured = $configuration.WhatIf -eq 'true' + } + $whatIf = Test-ReleasePreview @previewParameters $ignoreLabels = (![string]::IsNullOrEmpty($configuration.IgnoreLabels) ? $configuration.IgnoreLabels : $env:PSMODULE_AUTO_RELEASE_INPUT_IgnoreLabels) -split ',' | ForEach-Object { $_.Trim() } $majorLabels = (![string]::IsNullOrEmpty($configuration.MajorLabels) ? $configuration.MajorLabels : $env:PSMODULE_AUTO_RELEASE_INPUT_MajorLabels) -split ',' | ForEach-Object { $_.Trim() } @@ -83,16 +96,62 @@ LogGroup 'Event information - JSON' { LogGroup 'Event information - Object' { $githubEvent = $githubEventJson | ConvertFrom-Json - if (-not $githubEvent.pull_request) { + $workflowRun = $githubEvent.workflow_run + $commitPullRequests = @() + if ($workflowRun) { + if ($env:GITHUB_EVENT_NAME -ne 'workflow_run' -or + $workflowRun.event -ne 'pull_request' -or $workflowRun.conclusion -ne 'success' -or + $workflowRun.head_sha -cnotmatch '^[a-f0-9]{40}$') { + throw 'Publication requires a successful pull_request workflow_run with a valid commit SHA.' + } + $associatedPullRequests = @($workflowRun.pull_requests) + if ($associatedPullRequests.Count -eq 0) { + Write-Output 'Resolving the checked commit through the pull request association API.' + $associationJson = gh api "repos/$env:GITHUB_REPOSITORY/commits/$($workflowRun.head_sha)/pulls" + if ($LASTEXITCODE -ne 0) { + throw 'Failed to find pull requests associated with the checked commit.' + } + $commitPullRequests = @($associationJson | ConvertFrom-Json) + $associatedPullRequests = $commitPullRequests + } + if ($associatedPullRequests.Count -ne 1 -or $associatedPullRequests[0].number -lt 1) { + throw 'Publication requires exactly one associated pull request.' + } + $pullRequestNumber = $associatedPullRequests[0].number + $pullRequestJson = gh api "repos/$env:GITHUB_REPOSITORY/pulls/$pullRequestNumber" + if ($LASTEXITCODE -ne 0) { + throw "Failed to read pull request [$pullRequestNumber]." + } + $pull_request = $pullRequestJson | ConvertFrom-Json + if (-not $pull_request.merged -and $pull_request.head.repo.full_name -ne $env:GITHUB_REPOSITORY) { + Write-GitHubWarning 'Fork PR prereleases are not published. Publication runs after the PR is merged.' + exit + } + } elseif ($githubEvent.pull_request) { + $pull_request = $githubEvent.pull_request + } else { Write-GitHubWarning 'This is not run for a pull request. Exiting.' exit } - $pull_request = $githubEvent.pull_request $githubEvent | Format-List | Out-String } -$defaultBranchName = (gh repo view --json defaultBranchRef | ConvertFrom-Json | Select-Object -ExpandProperty defaultBranchRef).name -$isPullRequest = $githubEvent.PSObject.Properties.Name -Contains 'pull_request' +$repositoryJson = gh repo view --repo $env:GITHUB_REPOSITORY --json defaultBranchRef +if ($LASTEXITCODE -ne 0) { + throw 'Failed to read the repository default branch.' +} +$defaultBranchName = ($repositoryJson | ConvertFrom-Json).defaultBranchRef.name +if ($workflowRun) { + $validationParameters = @{ + PullRequest = $pull_request + WorkflowRun = $workflowRun + Repository = $env:GITHUB_REPOSITORY + DefaultBranch = $defaultBranchName + CommitPullRequests = $commitPullRequests + } + Assert-ReleasePullRequest @validationParameters +} +$isPullRequest = $null -ne $pull_request if (-not ($isPullRequest -or $whatIf)) { Write-Warning '⚠️ A release should not be created in this context. Exiting.' exit @@ -103,6 +162,10 @@ $prIsClosed = $pull_request.state -eq 'closed' $prBaseRef = $pull_request.base.ref $prHeadRef = $pull_request.head.ref $targetIsDefaultBranch = $pull_request.base.ref -eq $defaultBranchName +$releaseCommit = $pull_request.head.sha +if ($isMerged) { + $releaseCommit = $pull_request.merge_commit_sha +} Write-Output '-------------------------------------------------' Write-Output "Default branch: [$defaultBranchName]" @@ -128,7 +191,7 @@ LogGroup 'Pull request - Labels' { $createRelease = $isMerged -and $targetIsDefaultBranch $closedPullRequest = $prIsClosed -and -not $isMerged $createPrerelease = $labels -Contains 'prerelease' -and -not $createRelease -and -not $closedPullRequest -$prereleaseName = $prHeadRef -replace '[^a-zA-Z0-9]' +$prereleaseName = "pr$($pull_request.number)" $ignoreRelease = ($labels | Where-Object { $ignoreLabels -contains $_ }).Count -gt 0 if ($ignoreRelease) { @@ -209,6 +272,9 @@ if ($createPrerelease -or $createRelease -or $whatIf) { if ($incrementalPrerelease) { $newVersion.BumpPrereleaseNumber() + while ($releases.tagName -contains $newVersion.ToString()) { + $newVersion.BumpPrereleaseNumber() + } } } } @@ -220,6 +286,10 @@ if ($createPrerelease -or $createRelease -or $whatIf) { if ($createPrerelease) { $releaseExists = $releases.tagName -Contains $newVersion if ($releaseExists -and -not $incrementalPrerelease) { + $existingRelease = $releases | Where-Object { $_.tagName -ceq $newVersion.ToString() } + if ($existingRelease.isPrerelease -ne $true) { + throw "Refusing to replace non-prerelease [$newVersion]." + } Write-Output 'Release already exists, recreating.' if ($whatIf) { Write-Output "WhatIf: gh release delete $newVersion --cleanup-tag --yes" @@ -262,7 +332,7 @@ if ($createPrerelease -or $createRelease -or $whatIf) { } # Add remaining parameters - $releaseCreateCommand += @('--target', $prHeadRef, '--prerelease') + $releaseCreateCommand += @('--target', $releaseCommit, '--prerelease') Write-Output "gh $($releaseCreateCommand -join ' ')" if (-not $whatIf) { @@ -285,7 +355,7 @@ if ($createPrerelease -or $createRelease -or $whatIf) { } } else { # Build release creation command with options - $releaseCreateCommand = @('release', 'create', "$newVersion") + $releaseCreateCommand = @('release', 'create', "$newVersion", '--target', $releaseCommit) # Add title parameter if ($usePRTitleAsReleaseName) { @@ -325,36 +395,18 @@ if ($createPrerelease -or $createRelease -or $whatIf) { if ($createMajorTag) { $majorTag = ('{0}{1}' -f $newVersion.Prefix, $newVersion.Major) if ($whatIf) { - Write-Output "WhatIf: git tag -f $majorTag 'main'" + Write-Output "WhatIf: point tag [$majorTag] at [$releaseCommit]" } else { - git tag -f $majorTag 'main' - if ($LASTEXITCODE -ne 0) { - Write-Error "Failed to create major tag [$majorTag]." - exit $LASTEXITCODE - } + Set-ReleaseTag -Repository $env:GITHUB_REPOSITORY -Name $majorTag -CommitSha $releaseCommit -Confirm:$false } } if ($createMinorTag) { $minorTag = ('{0}{1}.{2}' -f $newVersion.Prefix, $newVersion.Major, $newVersion.Minor) if ($whatIf) { - Write-Output "WhatIf: git tag -f $minorTag 'main'" + Write-Output "WhatIf: point tag [$minorTag] at [$releaseCommit]" } else { - git tag -f $minorTag 'main' - if ($LASTEXITCODE -ne 0) { - Write-Error "Failed to create minor tag [$minorTag]." - exit $LASTEXITCODE - } - } - } - - if ($whatIf) { - Write-Output 'WhatIf: git push origin --tags --force' - } else { - git push origin --tags --force - if ($LASTEXITCODE -ne 0) { - Write-Error 'Failed to push tags.' - exit $LASTEXITCODE + Set-ReleaseTag -Repository $env:GITHUB_REPOSITORY -Name $minorTag -CommitSha $releaseCommit -Confirm:$false } } } @@ -365,7 +417,12 @@ if ($createPrerelease -or $createRelease -or $whatIf) { } LogGroup 'List prereleases using the same name' { - $prereleasesToCleanup = $releases | Where-Object { $_.tagName -like "*$prereleaseName*" } + $selectionParameters = @{ + Release = @($releases) + PullRequestNumber = $pull_request.number + VersionPrefix = $versionPrefix + } + $prereleasesToCleanup = Get-ReleasePrerelease @selectionParameters $prereleasesToCleanup | Select-Object -Property name, publishedAt, isPrerelease, isLatest | Format-Table | Out-String } diff --git a/tests/Release-GHRepository.Tests.ps1 b/tests/Release-GHRepository.Tests.ps1 new file mode 100644 index 0000000..419dab4 --- /dev/null +++ b/tests/Release-GHRepository.Tests.ps1 @@ -0,0 +1,340 @@ +[Diagnostics.CodeAnalysis.SuppressMessageAttribute( + 'PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Pester shares setup variables with test script blocks.' +)] +param() + +BeforeAll { + $helperPath = Join-Path $PSScriptRoot '..\src\Release-GHRepository.Helpers.psm1' + Import-Module -Name $helperPath -Force +} + +Describe 'Verified release modules' { + BeforeEach { + $fixtureRoot = Join-Path $TestDrive ([guid]::NewGuid().ToString()) + $moduleDirectory = Join-Path $fixtureRoot 'source' + $null = New-Item -Path $moduleDirectory -ItemType Directory + $manifestPath = Join-Path $moduleDirectory 'ReleaseSecurityFixture.psd1' + New-ModuleManifest -Path $manifestPath -RootModule 'ReleaseSecurityFixture.psm1' -ModuleVersion '1.0.0' + $modulePath = Join-Path $moduleDirectory 'ReleaseSecurityFixture.psm1' + $markerPath = Join-Path $fixtureRoot 'imported.txt' + $moduleContent = @' +$null = New-Item -Path '__MARKER__' -ItemType File -Force +function Get-ReleaseSecurityFixtureValue { 'verified package' } +Export-ModuleMember -Function Get-ReleaseSecurityFixtureValue +'@ + $moduleContent.Replace('__MARKER__', $markerPath.Replace("'", "''")) | Set-Content -LiteralPath $modulePath + $packagePath = Join-Path $fixtureRoot 'package.nupkg' + [System.IO.Compression.ZipFile]::CreateFromDirectory($moduleDirectory, $packagePath) + $packageHash = (Get-FileHash -LiteralPath $packagePath -Algorithm SHA256).Hash + $destinationPath = Join-Path $fixtureRoot 'verified' + $importParameters = @{ + Path = $packagePath + DestinationPath = $destinationPath + Name = 'ReleaseSecurityFixture' + RequiredVersion = '1.0.0' + SHA256 = $packageHash + } + } + + AfterEach { + Get-Module -Name ReleaseSecurityFixture | Remove-Module -Force + } + + It 'loads the verified package and exact module version' { + $module = Import-VerifiedReleaseModule @importParameters + + $module.Version | Should -Be ([version] '1.0.0') + Get-ReleaseSecurityFixtureValue | Should -Be 'verified package' + } + + It 'rejects changed package bytes before extraction or module execution' { + $archive = [System.IO.Compression.ZipFile]::Open($packagePath, 'Update') + try { + $archive.GetEntry('ReleaseSecurityFixture.psm1').Delete() + $entry = $archive.CreateEntry('ReleaseSecurityFixture.psm1') + $writer = [System.IO.StreamWriter]::new($entry.Open()) + try { + $tamperedContent = "`$null = New-Item -Path '$($markerPath.Replace("'", "''"))' -ItemType File" + $writer.Write($tamperedContent) + } finally { + $writer.Dispose() + } + } finally { + $archive.Dispose() + } + + { Import-VerifiedReleaseModule @importParameters } | Should -Throw -ExpectedMessage '*SHA256*' + Test-Path -LiteralPath $markerPath | Should -BeFalse + Test-Path -LiteralPath $destinationPath | Should -BeFalse + } + + It 'rejects a different module version before module execution' { + $importParameters.RequiredVersion = '2.0.0' + + { Import-VerifiedReleaseModule @importParameters } | Should -Throw -ExpectedMessage '*2.0.0*' + Test-Path -LiteralPath $markerPath | Should -BeFalse + } + + It 'does not select a same-name module from another directory' { + $shadowDirectory = Join-Path $fixtureRoot 'shadow' + $null = New-Item -Path $shadowDirectory -ItemType Directory + $shadowPath = Join-Path $shadowDirectory 'ReleaseSecurityFixture.psm1' + "function Get-ReleaseSecurityFixtureValue { 'unverified module' }" | Set-Content -LiteralPath $shadowPath + Import-Module -Name $shadowPath -Global + + $null = Import-VerifiedReleaseModule @importParameters + + Get-ReleaseSecurityFixtureValue | Should -Be 'verified package' + } +} + +Describe 'Pull request publication trust boundary' { + BeforeEach { + $repository = 'PSModule/Release-GHRepository' + $headSha = '1111111111111111111111111111111111111111' + $mergeSha = '2222222222222222222222222222222222222222' + $pullRequest = [pscustomobject] @{ + number = 7 + state = 'open' + merged = $false + closed_at = $null + merge_commit_sha = $null + base = [pscustomobject] @{ + ref = 'main' + repo = [pscustomobject] @{ id = 123; full_name = $repository } + } + head = [pscustomobject] @{ + sha = $headSha + repo = [pscustomobject] @{ id = 123; full_name = $repository } + } + } + $workflowRun = [pscustomobject] @{ + event = 'pull_request' + conclusion = 'success' + created_at = '2026-11-16T12:00:01Z' + head_sha = $headSha + repository = [pscustomobject] @{ id = 123; full_name = $repository } + head_repository = [pscustomobject] @{ id = 123; full_name = $repository } + pull_requests = @( + [pscustomobject] @{ + number = 7 + head = [pscustomobject] @{ sha = $headSha } + base = [pscustomobject] @{ ref = 'main'; repo = [pscustomobject] @{ id = 123 } } + } + ) + } + $validationParameters = @{ + PullRequest = $pullRequest + WorkflowRun = $workflowRun + Repository = $repository + DefaultBranch = 'main' + } + } + + It 'accepts an open PR at the checked commit' { + { Assert-ReleasePullRequest @validationParameters } | Should -Not -Throw + } + + It 'accepts a merged PR whose merge commit was checked' { + $pullRequest.state = 'closed' + $pullRequest.merged = $true + $pullRequest.closed_at = '2026-11-16T12:00:00Z' + $pullRequest.merge_commit_sha = $mergeSha + $workflowRun.head_sha = $mergeSha + + { Assert-ReleasePullRequest @validationParameters } | Should -Not -Throw + } + + It 'resolves a merged PR from its commit API association when the run PR list is empty' { + $pullRequest.state = 'closed' + $pullRequest.merged = $true + $pullRequest.closed_at = '2026-11-16T12:00:00Z' + $pullRequest.merge_commit_sha = $mergeSha + $validationParameters.CommitPullRequests = @($pullRequest) + $workflowRun.pull_requests = @() + + { Assert-ReleasePullRequest @validationParameters } | Should -Not -Throw + } + + It 'accepts a merged fork PR without running its code' { + $pullRequest.state = 'closed' + $pullRequest.merged = $true + $pullRequest.closed_at = '2026-11-16T12:00:00Z' + $pullRequest.merge_commit_sha = $mergeSha + $pullRequest.head.repo.full_name = 'contributor/fork' + $workflowRun.head_repository.full_name = 'contributor/fork' + + { Assert-ReleasePullRequest @validationParameters } | Should -Not -Throw + } + + It 'rejects ' -ForEach @( + @{ + Name = 'failed checks' + Change = { $workflowRun.conclusion = 'failure' } + Message = '*successful pull_request*' + } + @{ + Name = 'a non-PR workflow run' + Change = { $workflowRun.event = 'push' } + Message = '*successful pull_request*' + } + @{ + Name = 'checks from another repository' + Change = { $workflowRun.repository.full_name = 'other/repository' } + Message = '*repository*' + } + @{ + Name = 'an open fork PR' + Change = { + $pullRequest.head.repo.full_name = 'contributor/fork' + $workflowRun.head_repository.full_name = 'contributor/fork' + } + Message = '*branch in this repository*' + } + @{ + Name = 'an unassociated PR' + Change = { $workflowRun.pull_requests = @() } + Message = '*one associated pull request*' + } + @{ + Name = 'an ambiguous PR association' + Change = { $workflowRun.pull_requests += $workflowRun.pull_requests[0] } + Message = '*one associated pull request*' + } + @{ + Name = 'a different PR number' + Change = { $workflowRun.pull_requests[0].number = 8 } + Message = '*associated pull request*' + } + @{ + Name = 'a PR changed since its checks' + Change = { $pullRequest.head.sha = '3333333333333333333333333333333333333333' } + Message = '*changed since*' + } + @{ + Name = 'a different target branch' + Change = { $pullRequest.base.ref = 'other-branch' } + Message = '*default branch*' + } + @{ + Name = 'an invalid publication commit' + Change = { + $pullRequest.head.sha = '--unexpected-option' + $workflowRun.head_sha = '--unexpected-option' + $workflowRun.pull_requests[0].head.sha = '--unexpected-option' + } + Message = '*commit SHA*' + } + @{ + Name = 'a pre-merge run completing after closure' + Change = { + $pullRequest.state = 'closed' + $pullRequest.merged = $true + $pullRequest.closed_at = '2026-11-16T12:00:02Z' + $pullRequest.merge_commit_sha = $mergeSha + } + Message = '*predates PR closure*' + } + ) { + . $Change + + { Assert-ReleasePullRequest @validationParameters } | Should -Throw -ExpectedMessage $Message + } +} + +Describe 'Prerelease cleanup ownership' { + It 'selects only this PR prereleases and excludes stable releases and prefix collisions' { + $releases = @( + [pscustomobject] @{ tagName = 'v1.2.3-pr7.1'; isPrerelease = $true } + [pscustomobject] @{ tagName = 'v1.2.3-pr7'; isPrerelease = $true } + [pscustomobject] @{ tagName = 'v1.2.3-pr7.2'; isPrerelease = $false } + [pscustomobject] @{ tagName = 'v1.2.3-pr70.1'; isPrerelease = $true } + [pscustomobject] @{ tagName = 'v1.2.3-otherpr7.1'; isPrerelease = $true } + [pscustomobject] @{ tagName = 'v1.2.3'; isPrerelease = $false } + ) + + $selected = @(Get-ReleasePrerelease -Release $releases -PullRequestNumber 7 -VersionPrefix 'v') + + $selected.tagName | Should -Be @('v1.2.3-pr7.1', 'v1.2.3-pr7') + } + + It 'supports an empty version prefix' { + $releases = @([pscustomobject] @{ tagName = '1.2.3-pr7.1'; isPrerelease = $true }) + + @(Get-ReleasePrerelease -Release $releases -PullRequestNumber 7 -VersionPrefix '').Count | Should -Be 1 + } +} + +Describe 'Read-only pull request checks' { + It 'does not let configuration enable writes during pull_request checks' { + Test-ReleasePreview -EventName 'pull_request' | Should -BeTrue + } + + It 'does not let configuration disable an explicit preview request' { + Test-ReleasePreview -EventName 'workflow_run' -Requested | Should -BeTrue + } + + It 'honors a configured preview in the trusted publisher' { + Test-ReleasePreview -EventName 'workflow_run' -Configured | Should -BeTrue + } + + It 'permits publication only in the trusted publisher' { + Test-ReleasePreview -EventName 'workflow_run' | Should -BeFalse + } + + It 'rejects publication on other events' { + { Test-ReleasePreview -EventName 'workflow_dispatch' } | Should -Throw -ExpectedMessage '*workflow_run*' + } +} + +Describe 'Scoped release tag updates' { + BeforeEach { + $repository = 'PSModule/Release-GHRepository' + $commitSha = '2222222222222222222222222222222222222222' + Mock gh -ModuleName Release-GHRepository.Helpers { + $global:LASTEXITCODE = 0 + '[]' + } + } + + It 'creates only the requested tag at the release commit' { + Set-ReleaseTag -Repository $repository -Name 'v1' -CommitSha $commitSha -Confirm:$false + + Should -Invoke gh -ModuleName Release-GHRepository.Helpers -Exactly -Times 1 -ParameterFilter { + $args -contains 'POST' -and + $args -contains 'ref=refs/tags/v1' -and + $args -contains "sha=$commitSha" + } + } + + It 'updates only the matching tag at the release commit' { + Mock gh -ModuleName Release-GHRepository.Helpers { + $global:LASTEXITCODE = 0 + '[{"ref":"refs/tags/v1"},{"ref":"refs/tags/v10"}]' + } + + Set-ReleaseTag -Repository $repository -Name 'v1' -CommitSha $commitSha -Confirm:$false + + Should -Invoke gh -ModuleName Release-GHRepository.Helpers -Exactly -Times 1 -ParameterFilter { + $args -contains 'PATCH' -and + $args -contains "repos/$repository/git/refs/tags/v1" -and + $args -contains "sha=$commitSha" + } + Should -Invoke gh -ModuleName Release-GHRepository.Helpers -Exactly -Times 0 -ParameterFilter { + $args -contains 'POST' + } + } + + It 'does not write a tag when its lookup fails' { + Mock gh -ModuleName Release-GHRepository.Helpers { + $global:LASTEXITCODE = 1 + } + + { Set-ReleaseTag -Repository $repository -Name 'v1' -CommitSha $commitSha -Confirm:$false } | + Should -Throw -ExpectedMessage '*list*' + + Should -Invoke gh -ModuleName Release-GHRepository.Helpers -Exactly -Times 0 -ParameterFilter { + $args -contains 'POST' -or $args -contains 'PATCH' + } + } +} From 4b9516dde0adb82a7f445b456ad906d1e611dfdf Mon Sep 17 00:00:00 2001 From: Marius Storhaug Date: Mon, 16 Nov 2026 13:59:20 +0100 Subject: [PATCH 03/10] Reload verified modules without retaining prior aliases --- src/Release-GHRepository.Helpers.psm1 | 1 + src/main.ps1 | 6 +++++- tests/Release-GHRepository.Tests.ps1 | 13 ++++++++++++- 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/src/Release-GHRepository.Helpers.psm1 b/src/Release-GHRepository.Helpers.psm1 index 44ab3ae..f87b909 100644 --- a/src/Release-GHRepository.Helpers.psm1 +++ b/src/Release-GHRepository.Helpers.psm1 @@ -74,6 +74,7 @@ function Import-VerifiedReleaseModule { ModuleName = $manifestPath RequiredVersion = $RequiredVersion } + Get-Module -Name $Name | Remove-Module -Force -ErrorAction Stop Import-Module -FullyQualifiedName $moduleSpecification -Global -Force -PassThru -ErrorAction Stop } } diff --git a/src/main.ps1 b/src/main.ps1 index 16f1d90..7d081b6 100644 --- a/src/main.ps1 +++ b/src/main.ps1 @@ -411,7 +411,11 @@ if ($createPrerelease -or $createRelease -or $whatIf) { } } } - Write-GitHubNotice -Title 'Release created' -Message $newVersion + if ($whatIf) { + Write-GitHubNotice -Title 'Release preview' -Message $newVersion + } else { + Write-GitHubNotice -Title 'Release created' -Message $newVersion + } } else { Write-Output 'Skipping release creation.' } diff --git a/tests/Release-GHRepository.Tests.ps1 b/tests/Release-GHRepository.Tests.ps1 index 419dab4..33f7067 100644 --- a/tests/Release-GHRepository.Tests.ps1 +++ b/tests/Release-GHRepository.Tests.ps1 @@ -20,7 +20,8 @@ Describe 'Verified release modules' { $moduleContent = @' $null = New-Item -Path '__MARKER__' -ItemType File -Force function Get-ReleaseSecurityFixtureValue { 'verified package' } -Export-ModuleMember -Function Get-ReleaseSecurityFixtureValue +New-Alias -Name releaseFixtureAlias -Value Get-ReleaseSecurityFixtureValue +Export-ModuleMember -Function Get-ReleaseSecurityFixtureValue -Alias releaseFixtureAlias '@ $moduleContent.Replace('__MARKER__', $markerPath.Replace("'", "''")) | Set-Content -LiteralPath $modulePath $packagePath = Join-Path $fixtureRoot 'package.nupkg' @@ -86,6 +87,16 @@ Export-ModuleMember -Function Get-ReleaseSecurityFixtureValue Get-ReleaseSecurityFixtureValue | Should -Be 'verified package' } + + It 'reloads a verified module even when its exported aliases are already loaded' { + $null = Import-VerifiedReleaseModule @importParameters + $importParameters.DestinationPath = Join-Path $fixtureRoot 'verified-again' + + $importResult = @(Import-VerifiedReleaseModule @importParameters 2>&1) + + @($importResult | Where-Object { $_ -is [System.Management.Automation.ErrorRecord] }).Count | Should -Be 0 + Get-ReleaseSecurityFixtureValue | Should -Be 'verified package' + } } Describe 'Pull request publication trust boundary' { From a994b3b9d67811e609c2048ab2bd0a6f9a6ca9a6 Mon Sep 17 00:00:00 2001 From: Marius Storhaug Date: Mon, 16 Nov 2026 14:01:03 +0100 Subject: [PATCH 04/10] Separate trusted publishing and harden workflow examples --- .github/actions/linter/Dockerfile | 1 + .github/actions/linter/action.yml | 5 + .github/dependabot.yml | 9 ++ .github/linters/actionlint.yml | 6 ++ .github/workflows/Action-Test.yml | 15 ++- .github/workflows/Linter.yml | 12 +-- .github/workflows/Publish-Release.yml | 37 ++++++++ .github/workflows/Release.yml | 13 ++- README.md | 129 ++++++++++++++++++++++---- 9 files changed, 197 insertions(+), 30 deletions(-) create mode 100644 .github/actions/linter/Dockerfile create mode 100644 .github/actions/linter/action.yml create mode 100644 .github/linters/actionlint.yml create mode 100644 .github/workflows/Publish-Release.yml diff --git a/.github/actions/linter/Dockerfile b/.github/actions/linter/Dockerfile new file mode 100644 index 0000000..5ecb440 --- /dev/null +++ b/.github/actions/linter/Dockerfile @@ -0,0 +1 @@ +FROM ghcr.io/super-linter/super-linter:v8.7.0@sha256:c05768164eed53bac7c82aade7a14a76955206d4962cd41be97118db96fa5996 diff --git a/.github/actions/linter/action.yml b/.github/actions/linter/action.yml new file mode 100644 index 0000000..cb1c0e4 --- /dev/null +++ b/.github/actions/linter/action.yml @@ -0,0 +1,5 @@ +name: Lint repository +description: Run the reviewed Super-Linter container. +runs: + using: docker + image: Dockerfile diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 0da2fac..d488f1e 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -14,3 +14,12 @@ updates: interval: daily cooldown: default-days: 7 + - package-ecosystem: docker + directory: /.github/actions/linter + labels: + - dependencies + - docker + schedule: + interval: daily + cooldown: + default-days: 7 diff --git a/.github/linters/actionlint.yml b/.github/linters/actionlint.yml new file mode 100644 index 0000000..3a2bd0f --- /dev/null +++ b/.github/linters/actionlint.yml @@ -0,0 +1,6 @@ +paths: + .github/workflows/Publish-Release.yml: + ignore: + # GitHub supports queue: max; actionlint 1.7.12 does not recognize it yet. + # https://docs.github.com/en/actions/how-tos/write-workflows/choose-when-workflows-run/control-workflow-concurrency + - '^unexpected key "queue" for "concurrency" section\. expected one of "cancel-in-progress", "group"$' diff --git a/.github/workflows/Action-Test.yml b/.github/workflows/Action-Test.yml index b2a7d72..7c70ad7 100644 --- a/.github/workflows/Action-Test.yml +++ b/.github/workflows/Action-Test.yml @@ -12,20 +12,29 @@ concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true -permissions: - contents: read - pull-requests: read +permissions: {} jobs: ActionTestDefault: name: Action-Test - [Default] runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: read steps: - name: Checkout repo uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: persist-credentials: false + - name: Run security regression tests + shell: pwsh + run: | + $ErrorActionPreference = 'Stop' + Install-PSResource -Name Pester -Version '[6.1.0]' -Repository PSGallery -TrustRepository + Import-Module -Name Pester -RequiredVersion 6.1.0 + Invoke-Pester -Path (Join-Path $env:GITHUB_WORKSPACE 'tests') -CI + - name: Action-Test uses: ./ with: diff --git a/.github/workflows/Linter.yml b/.github/workflows/Linter.yml index 68ffc08..f295206 100644 --- a/.github/workflows/Linter.yml +++ b/.github/workflows/Linter.yml @@ -8,15 +8,14 @@ concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true -permissions: - contents: read - packages: read - statuses: write +permissions: {} jobs: Lint: name: Lint code base runs-on: ubuntu-latest + permissions: + contents: read steps: - name: Checkout repo uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 @@ -25,9 +24,10 @@ jobs: fetch-depth: 0 - name: Lint code base - uses: super-linter/super-linter@4ce20838b8ab83717e78138c5b3a1407148e0918 # v8.7.0 + uses: ./.github/actions/linter env: - GITHUB_TOKEN: ${{ github.token }} + MULTI_STATUS: false + ENABLE_GITHUB_PULL_REQUEST_SUMMARY_COMMENT: false VALIDATE_BIOME_FORMAT: false VALIDATE_JSCPD: false VALIDATE_JSON_PRETTIER: false diff --git a/.github/workflows/Publish-Release.yml b/.github/workflows/Publish-Release.yml new file mode 100644 index 0000000..37edaf0 --- /dev/null +++ b/.github/workflows/Publish-Release.yml @@ -0,0 +1,37 @@ +name: Publish Release + +run-name: "Publish Release - check run #${{ github.event.workflow_run.id }}" + +on: + # Executes only default-branch code; PR data is read from the API, never from artifacts. + workflow_run: # zizmor: ignore[dangerous-triggers] + workflows: + - Release + types: + - completed + +permissions: {} + +concurrency: + group: ${{ github.workflow }}-${{ github.repository }} + queue: max + cancel-in-progress: false + +jobs: + Publish: + if: >- + github.event.workflow_run.event == 'pull_request' && + github.event.workflow_run.conclusion == 'success' + runs-on: ubuntu-latest + permissions: + contents: write + pull-requests: write + steps: + - name: Checkout trusted code + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + ref: ${{ github.sha }} + persist-credentials: false + + - name: Publish release + uses: ./ diff --git a/.github/workflows/Release.yml b/.github/workflows/Release.yml index fd81eb0..18e9940 100644 --- a/.github/workflows/Release.yml +++ b/.github/workflows/Release.yml @@ -17,21 +17,24 @@ on: - 'src/**' concurrency: - group: ${{ github.workflow }}-${{ github.ref }} + group: ${{ github.workflow }}-${{ github.event.pull_request.number }} cancel-in-progress: true -permissions: - contents: write # Required to create releases - pull-requests: write # Required to create comments on the PRs +permissions: {} jobs: Release: runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: read steps: - name: Checkout repo uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: persist-credentials: false - - name: Release + - name: Check release uses: ./ + with: + WhatIf: true diff --git a/README.md b/README.md index 36bfaed..b340cd3 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,9 @@ Release-GHRepository follows: ## How it works -The workflow will trigger on pull requests to the main branch. +The check workflow runs on regular `pull_request` events for the main branch. It uses read-only permissions and simulates release changes. +A separate `workflow_run` publisher runs after a successful check. The publisher executes only code and configuration from the default branch. +It reads PR metadata from the GitHub API. It does not check out PR code or download PR artifacts. The following labels will inform the action what kind of release to create: - For a major release, and increasing the first number in the version use: @@ -26,7 +28,14 @@ The following labels will inform the action what kind of release to create: - `patch` - `fix` -When a pull request is closed, the action will create a release based on the labels and clean up any previous prereleases that were created. +Add the `prerelease` label to create prereleases while a same-repository PR is open. +Prereleases use the checked head commit and a PR-specific tag, such as `v1.2.3-pr42.1`. +When the PR is merged, the publisher creates a stable release at its merge commit. Closing an unmerged PR does not create a stable release. +With `AutoCleanup` enabled, closing or merging the PR removes only prereleases in that PR's tag namespace. +Other prereleases are left unchanged. + +Fork PR checks remain read-only. The publisher skips fork prereleases and can publish a stable release after the PR is merged. +Do not enable write tokens for fork checks. > [!NOTE] > The labels can be configured using the `MajorLabels`, `MinorLabels` and `PatchLabels` parameters/settings in the configuration file to trigger @@ -46,7 +55,7 @@ The action can be configured using the following settings: | `CreateMinorTag` | Control whether to create a tag for minor releases. | `true` | false | | `DatePrereleaseFormat` | The format to use for the prerelease number using [.NET DateTime format strings](https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings). | `''` | false | | `IgnoreLabels` | A comma separated list of labels that do not trigger a release. | `NoRelease` | false | -| `IncrementalPrerelease` | Control whether to automatically increment the prerelease number. If disabled, the action will ensure only one prerelease exists for a given branch. | `true` | false | +| `IncrementalPrerelease` | Control whether to automatically increment the prerelease number. If disabled, the action replaces the prerelease for the pull request. | `true` | false | | `MajorLabels` | A comma separated list of labels that trigger a major release. | `major, breaking` | false | | `MinorLabels` | A comma separated list of labels that trigger a minor release. | `minor, feature` | false | | `PatchLabels` | A comma separated list of labels that trigger a patch release. | `patch, fix` | false | @@ -54,10 +63,10 @@ The action can be configured using the following settings: | `UsePRBodyAsReleaseNotes` | When enabled, uses the pull request body as the release notes for the GitHub release. | `true` | false | | `UsePRTitleAsNotesHeading` | When enabled, the release notes will begin with the pull request title as a H1 heading followed by the pull request body. The title will include a reference to the PR number. | `true` | false | | `VersionPrefix` | The prefix to use for the version number. | `v` | false | -| `WhatIf` | Control whether to simulate the action. If enabled, the action will not create any releases. Used for testing. | `false` | false | +| `WhatIf` | Simulate release and tag changes. Always enabled for `pull_request` checks. A true input cannot be disabled by the configuration file. | `false` | false | | `Debug` | Enable debug output. | `'false'` | false | | `Verbose` | Enable verbose output. | `'false'` | false | -| `Version` | Specifies the version of the GitHub module to install. Accepts an exact version or a NuGet version range (for example `[1.2.0, 2.0.0)`). | | false | +| `Version` | Specifies the version of the GitHub module to install. Accepts an exact version or a NuGet version range (for example `[1.2.0, 2.0.0)`). | `[0.43.1]` | false | | `Prerelease` | Allow prerelease versions if available. | `'false'` | false | | `WorkingDirectory` | The working directory where the script runs. | `${{ github.workspace }}` | false | @@ -66,6 +75,8 @@ The action can be configured using the following settings: The configuration file is a YAML file that can be used to configure the action. By default, the configuration file is expected at `.github\auto-release.yml`, which can be changed using the `ConfigurationFile` setting. The action's configuration can be changed by altering the settings in the configuration file. +The publisher reads this file from its trusted default-branch checkout, not from the PR branch. +Configuration cannot turn off an explicit `WhatIf: true` input or enable writes during a regular PR check. ```yaml DatePrereleaseFormat: 'yyyyMMddHHmm' @@ -77,10 +88,15 @@ This example uses the date format for the prerelease, disables the incremental p ## Example -Add a workflow in your repository using the following example: +Add both workflows to your default branch. The publisher starts only after its workflow file exists on that branch. +These examples use GitHub-hosted Ubuntu runners. + +### Read-only PR checks + +Save this workflow as `.github/workflows/Release.yml`: ```yaml -name: Release-GHRepository +name: Release on: pull_request: @@ -94,25 +110,106 @@ on: - labeled concurrency: - group: ${{ github.workflow }}-${{ github.ref }} + group: ${{ github.workflow }}-${{ github.event.pull_request.number }} + cancel-in-progress: true + +permissions: {} jobs: - Release-GHRepository: + Check: runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: read steps: - - name: Checkout Code - uses: actions/checkout@v4 + - name: Checkout code + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + persist-credentials: false + + - name: Check release + uses: PSModule/Release-GHRepository@4b9516dde0adb82a7f445b456ad906d1e611dfdf # Trusted publisher and dependency verification + with: + WhatIf: true +``` + +### Trusted publication + +Save this workflow as `.github/workflows/Publish-Release.yml`. Keep `workflows: [Release]` equal to the check workflow's `name`. +The publisher has write access because it creates releases, updates release tags, and posts PR comments. +Only trusted default-branch code runs with this token. + +```yaml +name: Publish Release + +on: + workflow_run: + workflows: [Release] + types: [completed] + +permissions: {} + +concurrency: + group: ${{ github.workflow }}-${{ github.repository }} + queue: max + cancel-in-progress: false - - name: Release-GHRepository - uses: PSModule/Release-GHRepository@v1 +jobs: + Publish: + if: >- + github.event.workflow_run.event == 'pull_request' && + github.event.workflow_run.conclusion == 'success' + runs-on: ubuntu-latest + permissions: + contents: write + pull-requests: write + steps: + - name: Checkout trusted configuration + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + ref: ${{ github.sha }} + persist-credentials: false + + - name: Publish release + uses: PSModule/Release-GHRepository@4b9516dde0adb82a7f445b456ad906d1e611dfdf # Trusted publisher and dependency verification ``` +Do not replace the publisher's checkout ref with the PR head, `workflow_run.head_sha`, or an artifact from the check run. +The action validates the PR association and checked commit before publication. A stale run fails instead of publishing a later, unchecked commit. +Major and minor tags are updated through the GitHub API. Checkout credentials are not required. + +Use reviewed commit SHAs for external actions. Enable GitHub Actions dependency updates in the consuming repository to keep these pins current. + ## Permissions -If running the action in a restrictive mode, the following permissions needs to be granted to the action: +Set permissions explicitly for each job. Checks need only `contents: read` and `pull-requests: read`. +The trusted publishing job needs these scopes: ```yaml permissions: - contents: write # Required to create releases - pull-requests: write # Required to create comments on the PRs + contents: write # Create releases and update release tags + pull-requests: write # Post release comments on PRs +``` + +The examples use the short-lived, repository-scoped `GITHUB_TOKEN` supported by this action. They do not need a personal access token. +Requested write permissions do not override the read-only restriction for normal fork PR checks. + +## Dependency maintenance + +`src/Release-GHRepository.Dependencies.psd1` locks the `powershell-yaml` and `PSSemVer` package versions and SHA256 hashes. +The action checks each downloaded package before extraction or import and imports the verified module by its full path. +Update a version and its hash together in a reviewed PR. Do not change a hash only to make a failed verification pass. + +The repository linter uses a local Docker action with a digest-pinned base image. +Dependabot checks that Dockerfile for image updates and checks workflow action pins separately. + +## Local checks + +With PowerShell 7 and Pester 6.1.0 installed, run: + +```powershell +Invoke-Pester -Path .\tests -CI ``` + +These tests need no GitHub credentials and do not publish releases. +Tag API failures use test doubles to avoid production writes; those tests do not establish that live publication succeeds. From a937f4db5d320c01ecc1f934a6cdf28f5a6cc575 Mon Sep 17 00:00:00 2001 From: Marius Storhaug Date: Mon, 16 Nov 2026 14:05:43 +0100 Subject: [PATCH 05/10] Use the supported repository argument for default-branch lookup --- src/main.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.ps1 b/src/main.ps1 index 7d081b6..bfa0974 100644 --- a/src/main.ps1 +++ b/src/main.ps1 @@ -136,7 +136,7 @@ LogGroup 'Event information - Object' { $githubEvent | Format-List | Out-String } -$repositoryJson = gh repo view --repo $env:GITHUB_REPOSITORY --json defaultBranchRef +$repositoryJson = gh repo view $env:GITHUB_REPOSITORY --json defaultBranchRef if ($LASTEXITCODE -ne 0) { throw 'Failed to read the repository default branch.' } From 305b064880775b62d53b58b330500afd4b364f0e Mon Sep 17 00:00:00 2001 From: Marius Storhaug Date: Mon, 16 Nov 2026 14:06:53 +0100 Subject: [PATCH 06/10] Scope container-action scanner exceptions to the linter --- .github/linters/trivy-ignore.yml | 14 ++++++++++++++ .github/workflows/Linter.yml | 1 + README.md | 4 ++-- 3 files changed, 17 insertions(+), 2 deletions(-) create mode 100644 .github/linters/trivy-ignore.yml diff --git a/.github/linters/trivy-ignore.yml b/.github/linters/trivy-ignore.yml new file mode 100644 index 0000000..f642a15 --- /dev/null +++ b/.github/linters/trivy-ignore.yml @@ -0,0 +1,14 @@ +misconfigurations: + - id: AVD-DS-0002 + paths: + - .github/actions/linter/Dockerfile + statement: >- + GitHub Docker actions require the default root user for the mounted workspace. + The linter job has read-only permissions and receives no GitHub token. + https://docs.github.com/en/actions/reference/workflows-and-actions/dockerfile-support#user + - id: AVD-DS-0026 + paths: + - .github/actions/linter/Dockerfile + statement: >- + This one-shot linter exits after its checks. It is not a long-running service + and has no health endpoint. diff --git a/.github/workflows/Linter.yml b/.github/workflows/Linter.yml index f295206..ab183fb 100644 --- a/.github/workflows/Linter.yml +++ b/.github/workflows/Linter.yml @@ -28,6 +28,7 @@ jobs: env: MULTI_STATUS: false ENABLE_GITHUB_PULL_REQUEST_SUMMARY_COMMENT: false + TRIVY_IGNOREFILE: .github/linters/trivy-ignore.yml VALIDATE_BIOME_FORMAT: false VALIDATE_JSCPD: false VALIDATE_JSON_PRETTIER: false diff --git a/README.md b/README.md index b340cd3..6ab626d 100644 --- a/README.md +++ b/README.md @@ -128,7 +128,7 @@ jobs: persist-credentials: false - name: Check release - uses: PSModule/Release-GHRepository@4b9516dde0adb82a7f445b456ad906d1e611dfdf # Trusted publisher and dependency verification + uses: PSModule/Release-GHRepository@a937f4db5d320c01ecc1f934a6cdf28f5a6cc575 # Trusted publisher and dependency verification with: WhatIf: true ``` @@ -171,7 +171,7 @@ jobs: persist-credentials: false - name: Publish release - uses: PSModule/Release-GHRepository@4b9516dde0adb82a7f445b456ad906d1e611dfdf # Trusted publisher and dependency verification + uses: PSModule/Release-GHRepository@a937f4db5d320c01ecc1f934a6cdf28f5a6cc575 # Trusted publisher and dependency verification ``` Do not replace the publisher's checkout ref with the PR head, `workflow_run.head_sha`, or an artifact from the check run. From bee1a2c437920824370c8b42a8cb6a2916cc2cb4 Mon Sep 17 00:00:00 2001 From: Marius Storhaug Date: Mon, 16 Nov 2026 18:16:40 +0100 Subject: [PATCH 07/10] Restore direct publication on regular pull request events --- action.yml | 2 +- src/Release-GHRepository.Helpers.psm1 | 73 +++++--------- src/main.ps1 | 51 +++------- tests/Release-GHRepository.Tests.ps1 | 136 +++++++++----------------- 4 files changed, 88 insertions(+), 174 deletions(-) diff --git a/action.yml b/action.yml index 61749a1..a953f58 100644 --- a/action.yml +++ b/action.yml @@ -67,7 +67,7 @@ inputs: required: false default: v WhatIf: - description: Simulate release and tag changes. Always enabled for pull_request checks. A true input cannot be disabled by the configuration file. + description: Simulate release and tag changes. A true input cannot be disabled by the configuration file. required: false default: 'false' Debug: diff --git a/src/Release-GHRepository.Helpers.psm1 b/src/Release-GHRepository.Helpers.psm1 index f87b909..c2dfb14 100644 --- a/src/Release-GHRepository.Helpers.psm1 +++ b/src/Release-GHRepository.Helpers.psm1 @@ -85,11 +85,11 @@ function Assert-ReleasePullRequest { Validate PR metadata before privileged publication. .DESCRIPTION - Require successful PR checks from this repository and the default branch. - Bind the live PR to the checked commit and reject stale or ambiguous metadata. + Require a same-repository PR targeting the default branch. + Compare the event with live PR metadata before publishing its immutable commit. .EXAMPLE - Assert-ReleasePullRequest -PullRequest $pr -WorkflowRun $run -Repository 'owner/repo' -DefaultBranch 'main' + Assert-ReleasePullRequest -PullRequest $eventPr -CurrentPullRequest $livePr -Repository 'owner/repo' -DefaultBranch 'main' .INPUTS None @@ -104,15 +104,15 @@ function Assert-ReleasePullRequest { [OutputType([void])] [CmdletBinding()] param( - # The live PR returned by the repository API. + # The PR metadata from the pull_request event. [Parameter(Mandatory)] [ValidateNotNull()] [pscustomobject] $PullRequest, - # The workflow_run event's run metadata. + # The current PR returned by the repository API. [Parameter(Mandatory)] [ValidateNotNull()] - [pscustomobject] $WorkflowRun, + [pscustomobject] $CurrentPullRequest, # The repository that owns the publishing workflow. [Parameter(Mandatory)] @@ -122,34 +122,19 @@ function Assert-ReleasePullRequest { # The repository's default branch. [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] - [string] $DefaultBranch, - - # API associations for runs whose PR list is empty, including merged PRs. - [Parameter()] - [pscustomobject[]] $CommitPullRequests = @() + [string] $DefaultBranch ) - if ($WorkflowRun.event -ne 'pull_request' -or $WorkflowRun.conclusion -ne 'success') { - throw 'Publication requires a successful pull_request check run.' - } - if ($WorkflowRun.repository.full_name -ne $Repository -or $PullRequest.base.repo.full_name -ne $Repository -or - $WorkflowRun.head_repository.full_name -notin @($Repository, $PullRequest.head.repo.full_name)) { + if ($PullRequest.base.repo.full_name -ne $Repository -or $CurrentPullRequest.base.repo.full_name -ne $Repository) { throw "Publication metadata does not belong to repository [$Repository]." } - - $associatedPullRequests = @($WorkflowRun.pull_requests) - if ($associatedPullRequests.Count -eq 0) { - $associatedPullRequests = @($CommitPullRequests) - } - if ($associatedPullRequests.Count -ne 1) { - throw 'Publication requires exactly one associated pull request.' + if ($PullRequest.head.repo.full_name -ne $Repository -or $CurrentPullRequest.head.repo.full_name -ne $Repository) { + throw 'Publication requires a same-repository pull request. Fork tokens are read-only.' } - $associatedPullRequest = $associatedPullRequests[0] - if ($associatedPullRequest.number -ne $PullRequest.number -or $PullRequest.number -lt 1 -or - $associatedPullRequest.base.repo.id -ne $PullRequest.base.repo.id) { - throw 'Publication metadata does not match the associated pull request.' + if ($PullRequest.number -lt 1 -or $CurrentPullRequest.number -ne $PullRequest.number) { + throw 'Publication metadata does not match the pull request.' } - if ($PullRequest.base.ref -ne $DefaultBranch -or $associatedPullRequest.base.ref -ne $DefaultBranch) { + if ($PullRequest.base.ref -ne $DefaultBranch) { throw "Publication requires a pull request targeting the default branch [$DefaultBranch]." } if (-not $PullRequest.merged -and $PullRequest.head.repo.full_name -ne $Repository) { @@ -159,31 +144,23 @@ function Assert-ReleasePullRequest { ($PullRequest.merged -and $PullRequest.merge_commit_sha -cnotmatch '^[a-f0-9]{40}$')) { throw 'Publication requires a valid commit SHA.' } - if ($associatedPullRequest.head.sha -cne $PullRequest.head.sha) { - throw 'The pull request changed since its checks. Run checks on the latest commit.' - } - if ($WorkflowRun.head_sha -cne $PullRequest.head.sha -and - (-not $PullRequest.merged -or $WorkflowRun.head_sha -cne $PullRequest.merge_commit_sha)) { - throw 'The check run does not identify the PR head or merge commit.' - } - if ($PullRequest.state -eq 'closed') { - if ([string]::IsNullOrWhiteSpace($WorkflowRun.created_at) -or [string]::IsNullOrWhiteSpace($PullRequest.closed_at)) { - throw 'Closed-PR publication requires the check and closure timestamps.' - } - if ([datetimeoffset] $WorkflowRun.created_at -lt [datetimeoffset] $PullRequest.closed_at) { - throw 'The check run predates PR closure. Wait for the closed-PR checks.' - } + if ($CurrentPullRequest.head.sha -cne $PullRequest.head.sha -or + $CurrentPullRequest.base.ref -ne $PullRequest.base.ref -or + $CurrentPullRequest.state -ne $PullRequest.state -or + $CurrentPullRequest.merged -ne $PullRequest.merged -or + ($PullRequest.merged -and $CurrentPullRequest.merge_commit_sha -cne $PullRequest.merge_commit_sha)) { + throw 'The pull request changed since this event. Run publication for the current PR state.' } } function Test-ReleasePreview { <# .SYNOPSIS - Select preview mode without allowing configuration to enable PR writes. + Select preview mode without allowing configuration to override the caller. .DESCRIPTION - Force previews for regular PR events or an explicit preview request. - Permit writes only in a workflow_run publisher that has passed metadata validation. + Honor an explicit preview request or configuration setting. + Permit publication only for regular pull_request events. .EXAMPLE Test-ReleasePreview -EventName 'pull_request' -Configured @@ -215,12 +192,12 @@ function Test-ReleasePreview { [switch] $Configured ) - if ($Requested -or $Configured -or $EventName -eq 'pull_request') { + if ($Requested -or $Configured) { $true - } elseif ($EventName -eq 'workflow_run') { + } elseif ($EventName -eq 'pull_request') { $false } else { - throw 'Write operations require a trusted workflow_run publisher. Use WhatIf for other events.' + throw 'Write operations require a regular pull_request event. Use WhatIf for other events.' } } diff --git a/src/main.ps1 b/src/main.ps1 index bfa0974..a7d109d 100644 --- a/src/main.ps1 +++ b/src/main.ps1 @@ -96,58 +96,35 @@ LogGroup 'Event information - JSON' { LogGroup 'Event information - Object' { $githubEvent = $githubEventJson | ConvertFrom-Json - $workflowRun = $githubEvent.workflow_run - $commitPullRequests = @() - if ($workflowRun) { - if ($env:GITHUB_EVENT_NAME -ne 'workflow_run' -or - $workflowRun.event -ne 'pull_request' -or $workflowRun.conclusion -ne 'success' -or - $workflowRun.head_sha -cnotmatch '^[a-f0-9]{40}$') { - throw 'Publication requires a successful pull_request workflow_run with a valid commit SHA.' - } - $associatedPullRequests = @($workflowRun.pull_requests) - if ($associatedPullRequests.Count -eq 0) { - Write-Output 'Resolving the checked commit through the pull request association API.' - $associationJson = gh api "repos/$env:GITHUB_REPOSITORY/commits/$($workflowRun.head_sha)/pulls" - if ($LASTEXITCODE -ne 0) { - throw 'Failed to find pull requests associated with the checked commit.' - } - $commitPullRequests = @($associationJson | ConvertFrom-Json) - $associatedPullRequests = $commitPullRequests - } - if ($associatedPullRequests.Count -ne 1 -or $associatedPullRequests[0].number -lt 1) { - throw 'Publication requires exactly one associated pull request.' - } - $pullRequestNumber = $associatedPullRequests[0].number - $pullRequestJson = gh api "repos/$env:GITHUB_REPOSITORY/pulls/$pullRequestNumber" - if ($LASTEXITCODE -ne 0) { - throw "Failed to read pull request [$pullRequestNumber]." - } - $pull_request = $pullRequestJson | ConvertFrom-Json - if (-not $pull_request.merged -and $pull_request.head.repo.full_name -ne $env:GITHUB_REPOSITORY) { - Write-GitHubWarning 'Fork PR prereleases are not published. Publication runs after the PR is merged.' - exit - } - } elseif ($githubEvent.pull_request) { - $pull_request = $githubEvent.pull_request - } else { + if (-not $githubEvent.pull_request) { Write-GitHubWarning 'This is not run for a pull request. Exiting.' exit } + $pull_request = $githubEvent.pull_request $githubEvent | Format-List | Out-String } +if (-not $whatIf -and $pull_request.head.repo.full_name -ne $env:GITHUB_REPOSITORY) { + Write-GitHubWarning 'Fork PR publication is skipped because regular fork PR tokens are read-only.' + return +} + $repositoryJson = gh repo view $env:GITHUB_REPOSITORY --json defaultBranchRef if ($LASTEXITCODE -ne 0) { throw 'Failed to read the repository default branch.' } $defaultBranchName = ($repositoryJson | ConvertFrom-Json).defaultBranchRef.name -if ($workflowRun) { +if (-not $whatIf) { + $pullRequestNumber = $pull_request.number + $currentPullRequestJson = gh api "repos/$env:GITHUB_REPOSITORY/pulls/$pullRequestNumber" + if ($LASTEXITCODE -ne 0) { + throw "Failed to read pull request [$pullRequestNumber]." + } $validationParameters = @{ PullRequest = $pull_request - WorkflowRun = $workflowRun + CurrentPullRequest = $currentPullRequestJson | ConvertFrom-Json Repository = $env:GITHUB_REPOSITORY DefaultBranch = $defaultBranchName - CommitPullRequests = $commitPullRequests } Assert-ReleasePullRequest @validationParameters } diff --git a/tests/Release-GHRepository.Tests.ps1 b/tests/Release-GHRepository.Tests.ps1 index 33f7067..f535583 100644 --- a/tests/Release-GHRepository.Tests.ps1 +++ b/tests/Release-GHRepository.Tests.ps1 @@ -119,107 +119,64 @@ Describe 'Pull request publication trust boundary' { repo = [pscustomobject] @{ id = 123; full_name = $repository } } } - $workflowRun = [pscustomobject] @{ - event = 'pull_request' - conclusion = 'success' - created_at = '2026-11-16T12:00:01Z' - head_sha = $headSha - repository = [pscustomobject] @{ id = 123; full_name = $repository } - head_repository = [pscustomobject] @{ id = 123; full_name = $repository } - pull_requests = @( - [pscustomobject] @{ - number = 7 - head = [pscustomobject] @{ sha = $headSha } - base = [pscustomobject] @{ ref = 'main'; repo = [pscustomobject] @{ id = 123 } } - } - ) - } + $currentPullRequest = $pullRequest | ConvertTo-Json -Depth 8 | ConvertFrom-Json $validationParameters = @{ - PullRequest = $pullRequest - WorkflowRun = $workflowRun - Repository = $repository - DefaultBranch = 'main' + PullRequest = $pullRequest + CurrentPullRequest = $currentPullRequest + Repository = $repository + DefaultBranch = 'main' } } - It 'accepts an open PR at the checked commit' { + It 'accepts an open same-repository PR at the event commit' { { Assert-ReleasePullRequest @validationParameters } | Should -Not -Throw } - It 'accepts a merged PR whose merge commit was checked' { + It 'accepts a merged same-repository PR at the event merge commit' { $pullRequest.state = 'closed' $pullRequest.merged = $true - $pullRequest.closed_at = '2026-11-16T12:00:00Z' $pullRequest.merge_commit_sha = $mergeSha - $workflowRun.head_sha = $mergeSha - - { Assert-ReleasePullRequest @validationParameters } | Should -Not -Throw - } - - It 'resolves a merged PR from its commit API association when the run PR list is empty' { - $pullRequest.state = 'closed' - $pullRequest.merged = $true - $pullRequest.closed_at = '2026-11-16T12:00:00Z' - $pullRequest.merge_commit_sha = $mergeSha - $validationParameters.CommitPullRequests = @($pullRequest) - $workflowRun.pull_requests = @() - - { Assert-ReleasePullRequest @validationParameters } | Should -Not -Throw - } - - It 'accepts a merged fork PR without running its code' { - $pullRequest.state = 'closed' - $pullRequest.merged = $true - $pullRequest.closed_at = '2026-11-16T12:00:00Z' - $pullRequest.merge_commit_sha = $mergeSha - $pullRequest.head.repo.full_name = 'contributor/fork' - $workflowRun.head_repository.full_name = 'contributor/fork' + $currentPullRequest.state = 'closed' + $currentPullRequest.merged = $true + $currentPullRequest.merge_commit_sha = $mergeSha { Assert-ReleasePullRequest @validationParameters } | Should -Not -Throw } It 'rejects ' -ForEach @( @{ - Name = 'failed checks' - Change = { $workflowRun.conclusion = 'failure' } - Message = '*successful pull_request*' - } - @{ - Name = 'a non-PR workflow run' - Change = { $workflowRun.event = 'push' } - Message = '*successful pull_request*' + Name = 'an event for another repository' + Change = { $pullRequest.base.repo.full_name = 'other/repository' } + Message = '*repository*' } @{ - Name = 'checks from another repository' - Change = { $workflowRun.repository.full_name = 'other/repository' } + Name = 'live metadata from another repository' + Change = { $currentPullRequest.base.repo.full_name = 'other/repository' } Message = '*repository*' } @{ Name = 'an open fork PR' + Change = { $pullRequest.head.repo.full_name = 'contributor/fork' } + Message = '*same-repository*' + } + @{ + Name = 'a merged fork PR' Change = { + $pullRequest.state = 'closed' + $pullRequest.merged = $true + $pullRequest.merge_commit_sha = $mergeSha $pullRequest.head.repo.full_name = 'contributor/fork' - $workflowRun.head_repository.full_name = 'contributor/fork' } - Message = '*branch in this repository*' - } - @{ - Name = 'an unassociated PR' - Change = { $workflowRun.pull_requests = @() } - Message = '*one associated pull request*' - } - @{ - Name = 'an ambiguous PR association' - Change = { $workflowRun.pull_requests += $workflowRun.pull_requests[0] } - Message = '*one associated pull request*' + Message = '*same-repository*' } @{ Name = 'a different PR number' - Change = { $workflowRun.pull_requests[0].number = 8 } - Message = '*associated pull request*' + Change = { $currentPullRequest.number = 8 } + Message = '*pull request*' } @{ - Name = 'a PR changed since its checks' - Change = { $pullRequest.head.sha = '3333333333333333333333333333333333333333' } + Name = 'a PR changed since the event' + Change = { $currentPullRequest.head.sha = '3333333333333333333333333333333333333333' } Message = '*changed since*' } @{ @@ -229,22 +186,25 @@ Describe 'Pull request publication trust boundary' { } @{ Name = 'an invalid publication commit' - Change = { - $pullRequest.head.sha = '--unexpected-option' - $workflowRun.head_sha = '--unexpected-option' - $workflowRun.pull_requests[0].head.sha = '--unexpected-option' - } + Change = { $pullRequest.head.sha = '--unexpected-option' } Message = '*commit SHA*' } @{ - Name = 'a pre-merge run completing after closure' + Name = 'an old open-PR event after closure' + Change = { $currentPullRequest.state = 'closed' } + Message = '*changed since*' + } + @{ + Name = 'a different merge commit' Change = { $pullRequest.state = 'closed' $pullRequest.merged = $true - $pullRequest.closed_at = '2026-11-16T12:00:02Z' $pullRequest.merge_commit_sha = $mergeSha + $currentPullRequest.state = 'closed' + $currentPullRequest.merged = $true + $currentPullRequest.merge_commit_sha = '3333333333333333333333333333333333333333' } - Message = '*predates PR closure*' + Message = '*changed since*' } ) { . $Change @@ -276,25 +236,25 @@ Describe 'Prerelease cleanup ownership' { } } -Describe 'Read-only pull request checks' { - It 'does not let configuration enable writes during pull_request checks' { - Test-ReleasePreview -EventName 'pull_request' | Should -BeTrue +Describe 'Pull request preview controls' { + It 'allows regular pull_request publication when no preview is requested' { + Test-ReleasePreview -EventName 'pull_request' | Should -BeFalse } It 'does not let configuration disable an explicit preview request' { - Test-ReleasePreview -EventName 'workflow_run' -Requested | Should -BeTrue + Test-ReleasePreview -EventName 'pull_request' -Requested | Should -BeTrue } - It 'honors a configured preview in the trusted publisher' { - Test-ReleasePreview -EventName 'workflow_run' -Configured | Should -BeTrue + It 'honors a configured preview' { + Test-ReleasePreview -EventName 'pull_request' -Configured | Should -BeTrue } - It 'permits publication only in the trusted publisher' { - Test-ReleasePreview -EventName 'workflow_run' | Should -BeFalse + It 'allows read-only scheduled checks' { + Test-ReleasePreview -EventName 'schedule' -Requested | Should -BeTrue } It 'rejects publication on other events' { - { Test-ReleasePreview -EventName 'workflow_dispatch' } | Should -Throw -ExpectedMessage '*workflow_run*' + { Test-ReleasePreview -EventName 'push' } | Should -Throw -ExpectedMessage '*pull_request*' } } From 069044f61f55aaac3954ba6cf35186fd00a72ab2 Mon Sep 17 00:00:00 2001 From: Marius Storhaug Date: Mon, 16 Nov 2026 18:20:34 +0100 Subject: [PATCH 08/10] Use one pull request workflow with a pinned publisher --- .github/linters/actionlint.yml | 2 +- .github/workflows/Publish-Release.yml | 37 ----------- .github/workflows/Release.yml | 22 +++--- README.md | 96 ++++++++------------------- 4 files changed, 39 insertions(+), 118 deletions(-) delete mode 100644 .github/workflows/Publish-Release.yml diff --git a/.github/linters/actionlint.yml b/.github/linters/actionlint.yml index 3a2bd0f..1a0f105 100644 --- a/.github/linters/actionlint.yml +++ b/.github/linters/actionlint.yml @@ -1,5 +1,5 @@ paths: - .github/workflows/Publish-Release.yml: + .github/workflows/Release.yml: ignore: # GitHub supports queue: max; actionlint 1.7.12 does not recognize it yet. # https://docs.github.com/en/actions/how-tos/write-workflows/choose-when-workflows-run/control-workflow-concurrency diff --git a/.github/workflows/Publish-Release.yml b/.github/workflows/Publish-Release.yml deleted file mode 100644 index 37edaf0..0000000 --- a/.github/workflows/Publish-Release.yml +++ /dev/null @@ -1,37 +0,0 @@ -name: Publish Release - -run-name: "Publish Release - check run #${{ github.event.workflow_run.id }}" - -on: - # Executes only default-branch code; PR data is read from the API, never from artifacts. - workflow_run: # zizmor: ignore[dangerous-triggers] - workflows: - - Release - types: - - completed - -permissions: {} - -concurrency: - group: ${{ github.workflow }}-${{ github.repository }} - queue: max - cancel-in-progress: false - -jobs: - Publish: - if: >- - github.event.workflow_run.event == 'pull_request' && - github.event.workflow_run.conclusion == 'success' - runs-on: ubuntu-latest - permissions: - contents: write - pull-requests: write - steps: - - name: Checkout trusted code - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 - with: - ref: ${{ github.sha }} - persist-credentials: false - - - name: Publish release - uses: ./ diff --git a/.github/workflows/Release.yml b/.github/workflows/Release.yml index 18e9940..e7b20aa 100644 --- a/.github/workflows/Release.yml +++ b/.github/workflows/Release.yml @@ -16,25 +16,25 @@ on: - 'action.yml' - 'src/**' -concurrency: - group: ${{ github.workflow }}-${{ github.event.pull_request.number }} - cancel-in-progress: true - permissions: {} jobs: Release: + if: github.event.pull_request.head.repo.full_name == github.repository runs-on: ubuntu-latest permissions: - contents: read - pull-requests: read + contents: write + pull-requests: write + concurrency: + group: ${{ github.workflow }}-${{ github.repository }} + queue: max + cancel-in-progress: false steps: - - name: Checkout repo + - name: Checkout trusted configuration uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: + ref: ${{ github.event.pull_request.merged && github.event.pull_request.merge_commit_sha || github.event.pull_request.base.sha }} persist-credentials: false - - name: Check release - uses: ./ - with: - WhatIf: true + - name: Release + uses: PSModule/Release-GHRepository@bee1a2c437920824370c8b42a8cb6a2916cc2cb4 # Verified dependencies and direct PR publication diff --git a/README.md b/README.md index 6ab626d..d5b18fd 100644 --- a/README.md +++ b/README.md @@ -13,9 +13,9 @@ Release-GHRepository follows: ## How it works -The check workflow runs on regular `pull_request` events for the main branch. It uses read-only permissions and simulates release changes. -A separate `workflow_run` publisher runs after a successful check. The publisher executes only code and configuration from the default branch. -It reads PR metadata from the GitHub API. It does not check out PR code or download PR artifacts. +One release workflow runs on regular `pull_request` events for the main branch. +It calls an action pinned to a reviewed commit and reads configuration from a trusted checkout. +It does not execute the PR's local action or scripts. The following labels will inform the action what kind of release to create: - For a major release, and increasing the first number in the version use: @@ -29,12 +29,12 @@ The following labels will inform the action what kind of release to create: - `fix` Add the `prerelease` label to create prereleases while a same-repository PR is open. -Prereleases use the checked head commit and a PR-specific tag, such as `v1.2.3-pr42.1`. -When the PR is merged, the publisher creates a stable release at its merge commit. Closing an unmerged PR does not create a stable release. +Prereleases use the PR head commit and a PR-specific tag, such as `v1.2.3-pr42.1`. +When the PR is merged, the action creates a stable release at its merge commit. Closing an unmerged PR does not create a stable release. With `AutoCleanup` enabled, closing or merging the PR removes only prereleases in that PR's tag namespace. Other prereleases are left unchanged. -Fork PR checks remain read-only. The publisher skips fork prereleases and can publish a stable release after the PR is merged. +Fork PR checks remain read-only. The release workflow skips fork PRs, including their merge events, because their regular PR tokens cannot publish. Do not enable write tokens for fork checks. > [!NOTE] @@ -63,7 +63,7 @@ The action can be configured using the following settings: | `UsePRBodyAsReleaseNotes` | When enabled, uses the pull request body as the release notes for the GitHub release. | `true` | false | | `UsePRTitleAsNotesHeading` | When enabled, the release notes will begin with the pull request title as a H1 heading followed by the pull request body. The title will include a reference to the PR number. | `true` | false | | `VersionPrefix` | The prefix to use for the version number. | `v` | false | -| `WhatIf` | Simulate release and tag changes. Always enabled for `pull_request` checks. A true input cannot be disabled by the configuration file. | `false` | false | +| `WhatIf` | Simulate release and tag changes. Set this input to `true` for read-only checks. A true input cannot be disabled by the configuration file. | `false` | false | | `Debug` | Enable debug output. | `'false'` | false | | `Verbose` | Enable verbose output. | `'false'` | false | | `Version` | Specifies the version of the GitHub module to install. Accepts an exact version or a NuGet version range (for example `[1.2.0, 2.0.0)`). | `[0.43.1]` | false | @@ -75,8 +75,9 @@ The action can be configured using the following settings: The configuration file is a YAML file that can be used to configure the action. By default, the configuration file is expected at `.github\auto-release.yml`, which can be changed using the `ConfigurationFile` setting. The action's configuration can be changed by altering the settings in the configuration file. -The publisher reads this file from its trusted default-branch checkout, not from the PR branch. -Configuration cannot turn off an explicit `WhatIf: true` input or enable writes during a regular PR check. +The example reads this file from the PR base commit while the PR is open and from the approved merge commit after merge. +It does not read configuration changes from an unmerged PR. +Configuration cannot turn off an explicit `WhatIf: true` input. ```yaml DatePrereleaseFormat: 'yyyyMMddHHmm' @@ -88,12 +89,8 @@ This example uses the date format for the prerelease, disables the incremental p ## Example -Add both workflows to your default branch. The publisher starts only after its workflow file exists on that branch. -These examples use GitHub-hosted Ubuntu runners. - -### Read-only PR checks - -Save this workflow as `.github/workflows/Release.yml`: +Save this single workflow as `.github/workflows/Release.yml`. The example uses a GitHub-hosted Ubuntu runner. +The release job has write permissions, so it calls a pinned action instead of running the PR's local `./` action. ```yaml name: Release @@ -109,81 +106,42 @@ on: - synchronize - labeled -concurrency: - group: ${{ github.workflow }}-${{ github.event.pull_request.number }} - cancel-in-progress: true - permissions: {} jobs: - Check: - runs-on: ubuntu-latest - permissions: - contents: read - pull-requests: read - steps: - - name: Checkout code - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 - with: - persist-credentials: false - - - name: Check release - uses: PSModule/Release-GHRepository@a937f4db5d320c01ecc1f934a6cdf28f5a6cc575 # Trusted publisher and dependency verification - with: - WhatIf: true -``` - -### Trusted publication - -Save this workflow as `.github/workflows/Publish-Release.yml`. Keep `workflows: [Release]` equal to the check workflow's `name`. -The publisher has write access because it creates releases, updates release tags, and posts PR comments. -Only trusted default-branch code runs with this token. - -```yaml -name: Publish Release - -on: - workflow_run: - workflows: [Release] - types: [completed] - -permissions: {} - -concurrency: - group: ${{ github.workflow }}-${{ github.repository }} - queue: max - cancel-in-progress: false - -jobs: - Publish: - if: >- - github.event.workflow_run.event == 'pull_request' && - github.event.workflow_run.conclusion == 'success' + Release: + if: github.event.pull_request.head.repo.full_name == github.repository runs-on: ubuntu-latest permissions: contents: write pull-requests: write + concurrency: + group: ${{ github.workflow }}-${{ github.repository }} + queue: max + cancel-in-progress: false steps: - name: Checkout trusted configuration uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: - ref: ${{ github.sha }} + ref: ${{ github.event.pull_request.merged && github.event.pull_request.merge_commit_sha || github.event.pull_request.base.sha }} persist-credentials: false - - name: Publish release - uses: PSModule/Release-GHRepository@a937f4db5d320c01ecc1f934a6cdf28f5a6cc575 # Trusted publisher and dependency verification + - name: Release + uses: PSModule/Release-GHRepository@bee1a2c437920824370c8b42a8cb6a2916cc2cb4 # Verified dependencies and direct PR publication ``` -Do not replace the publisher's checkout ref with the PR head, `workflow_run.head_sha`, or an artifact from the check run. -The action validates the PR association and checked commit before publication. A stale run fails instead of publishing a later, unchecked commit. +Do not replace the trusted checkout ref with the PR head or add steps that execute files from an unmerged PR in this write-capable job. +Keep the action pin under review when changing the publisher. Use `WhatIf: true` with read-only permissions to test proposed local action changes. +The action checks live PR metadata before writing. A stale event fails instead of publishing a later commit or a changed PR state. Major and minor tags are updated through the GitHub API. Checkout credentials are not required. Use reviewed commit SHAs for external actions. Enable GitHub Actions dependency updates in the consuming repository to keep these pins current. +This setup trusts contributors who can change workflows in the repository. Any additional publication approval boundary must be enforced by repository or organization policy. ## Permissions -Set permissions explicitly for each job. Checks need only `contents: read` and `pull-requests: read`. -The trusted publishing job needs these scopes: +Set permissions explicitly for each job. Read-only checks need only `contents: read` and `pull-requests: read`, with `WhatIf: true`. +The release job needs these scopes: ```yaml permissions: From 330453003f36f18ec3748c48718ce2ca3a4cc34f Mon Sep 17 00:00:00 2001 From: Marius Storhaug Date: Mon, 16 Nov 2026 22:26:06 +0100 Subject: [PATCH 09/10] Use the upstream Super-Linter action pinned by commit --- .github/actions/linter/Dockerfile | 1 - .github/actions/linter/action.yml | 5 ----- .github/dependabot.yml | 9 --------- .github/linters/trivy-ignore.yml | 14 -------------- .github/workflows/Linter.yml | 3 +-- README.md | 5 +++-- 6 files changed, 4 insertions(+), 33 deletions(-) delete mode 100644 .github/actions/linter/Dockerfile delete mode 100644 .github/actions/linter/action.yml delete mode 100644 .github/linters/trivy-ignore.yml diff --git a/.github/actions/linter/Dockerfile b/.github/actions/linter/Dockerfile deleted file mode 100644 index 5ecb440..0000000 --- a/.github/actions/linter/Dockerfile +++ /dev/null @@ -1 +0,0 @@ -FROM ghcr.io/super-linter/super-linter:v8.7.0@sha256:c05768164eed53bac7c82aade7a14a76955206d4962cd41be97118db96fa5996 diff --git a/.github/actions/linter/action.yml b/.github/actions/linter/action.yml deleted file mode 100644 index cb1c0e4..0000000 --- a/.github/actions/linter/action.yml +++ /dev/null @@ -1,5 +0,0 @@ -name: Lint repository -description: Run the reviewed Super-Linter container. -runs: - using: docker - image: Dockerfile diff --git a/.github/dependabot.yml b/.github/dependabot.yml index d488f1e..0da2fac 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -14,12 +14,3 @@ updates: interval: daily cooldown: default-days: 7 - - package-ecosystem: docker - directory: /.github/actions/linter - labels: - - dependencies - - docker - schedule: - interval: daily - cooldown: - default-days: 7 diff --git a/.github/linters/trivy-ignore.yml b/.github/linters/trivy-ignore.yml deleted file mode 100644 index f642a15..0000000 --- a/.github/linters/trivy-ignore.yml +++ /dev/null @@ -1,14 +0,0 @@ -misconfigurations: - - id: AVD-DS-0002 - paths: - - .github/actions/linter/Dockerfile - statement: >- - GitHub Docker actions require the default root user for the mounted workspace. - The linter job has read-only permissions and receives no GitHub token. - https://docs.github.com/en/actions/reference/workflows-and-actions/dockerfile-support#user - - id: AVD-DS-0026 - paths: - - .github/actions/linter/Dockerfile - statement: >- - This one-shot linter exits after its checks. It is not a long-running service - and has no health endpoint. diff --git a/.github/workflows/Linter.yml b/.github/workflows/Linter.yml index ab183fb..7156cf6 100644 --- a/.github/workflows/Linter.yml +++ b/.github/workflows/Linter.yml @@ -24,11 +24,10 @@ jobs: fetch-depth: 0 - name: Lint code base - uses: ./.github/actions/linter + uses: super-linter/super-linter@4ce20838b8ab83717e78138c5b3a1407148e0918 # v8.7.0 env: MULTI_STATUS: false ENABLE_GITHUB_PULL_REQUEST_SUMMARY_COMMENT: false - TRIVY_IGNOREFILE: .github/linters/trivy-ignore.yml VALIDATE_BIOME_FORMAT: false VALIDATE_JSCPD: false VALIDATE_JSON_PRETTIER: false diff --git a/README.md b/README.md index d5b18fd..a750157 100644 --- a/README.md +++ b/README.md @@ -158,8 +158,9 @@ Requested write permissions do not override the read-only restriction for normal The action checks each downloaded package before extraction or import and imports the verified module by its full path. Update a version and its hash together in a reviewed PR. Do not change a hash only to make a failed verification pass. -The repository linter uses a local Docker action with a digest-pinned base image. -Dependabot checks that Dockerfile for image updates and checks workflow action pins separately. +The repository linter uses the upstream Super-Linter action pinned to a full commit SHA. +Dependabot checks workflow action pins for updates. +The upstream action selects its container image by version tag, so the action SHA does not lock the container image digest. ## Local checks From 5ed1de63659ae29d677785befc12e6b96e685683 Mon Sep 17 00:00:00 2001 From: Marius Storhaug Date: Mon, 16 Nov 2026 23:22:39 +0100 Subject: [PATCH 10/10] Limit the pull request to the original trigger example change --- .github/linters/actionlint.yml | 6 - .github/workflows/Action-Test.yml | 15 +- .github/workflows/Linter.yml | 10 +- .github/workflows/Release.yml | 21 +- README.md | 92 ++---- action.yml | 6 +- src/Release-GHRepository.Dependencies.psd1 | 14 - src/Release-GHRepository.Helpers.psm1 | 323 --------------------- src/main.ps1 | 134 +++------ tests/Release-GHRepository.Tests.ps1 | 311 -------------------- 10 files changed, 85 insertions(+), 847 deletions(-) delete mode 100644 .github/linters/actionlint.yml delete mode 100644 src/Release-GHRepository.Dependencies.psd1 delete mode 100644 src/Release-GHRepository.Helpers.psm1 delete mode 100644 tests/Release-GHRepository.Tests.ps1 diff --git a/.github/linters/actionlint.yml b/.github/linters/actionlint.yml deleted file mode 100644 index 1a0f105..0000000 --- a/.github/linters/actionlint.yml +++ /dev/null @@ -1,6 +0,0 @@ -paths: - .github/workflows/Release.yml: - ignore: - # GitHub supports queue: max; actionlint 1.7.12 does not recognize it yet. - # https://docs.github.com/en/actions/how-tos/write-workflows/choose-when-workflows-run/control-workflow-concurrency - - '^unexpected key "queue" for "concurrency" section\. expected one of "cancel-in-progress", "group"$' diff --git a/.github/workflows/Action-Test.yml b/.github/workflows/Action-Test.yml index 7c70ad7..b2a7d72 100644 --- a/.github/workflows/Action-Test.yml +++ b/.github/workflows/Action-Test.yml @@ -12,29 +12,20 @@ concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true -permissions: {} +permissions: + contents: read + pull-requests: read jobs: ActionTestDefault: name: Action-Test - [Default] runs-on: ubuntu-latest - permissions: - contents: read - pull-requests: read steps: - name: Checkout repo uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: persist-credentials: false - - name: Run security regression tests - shell: pwsh - run: | - $ErrorActionPreference = 'Stop' - Install-PSResource -Name Pester -Version '[6.1.0]' -Repository PSGallery -TrustRepository - Import-Module -Name Pester -RequiredVersion 6.1.0 - Invoke-Pester -Path (Join-Path $env:GITHUB_WORKSPACE 'tests') -CI - - name: Action-Test uses: ./ with: diff --git a/.github/workflows/Linter.yml b/.github/workflows/Linter.yml index 7156cf6..68ffc08 100644 --- a/.github/workflows/Linter.yml +++ b/.github/workflows/Linter.yml @@ -8,14 +8,15 @@ concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true -permissions: {} +permissions: + contents: read + packages: read + statuses: write jobs: Lint: name: Lint code base runs-on: ubuntu-latest - permissions: - contents: read steps: - name: Checkout repo uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 @@ -26,8 +27,7 @@ jobs: - name: Lint code base uses: super-linter/super-linter@4ce20838b8ab83717e78138c5b3a1407148e0918 # v8.7.0 env: - MULTI_STATUS: false - ENABLE_GITHUB_PULL_REQUEST_SUMMARY_COMMENT: false + GITHUB_TOKEN: ${{ github.token }} VALIDATE_BIOME_FORMAT: false VALIDATE_JSCPD: false VALIDATE_JSON_PRETTIER: false diff --git a/.github/workflows/Release.yml b/.github/workflows/Release.yml index e7b20aa..fd81eb0 100644 --- a/.github/workflows/Release.yml +++ b/.github/workflows/Release.yml @@ -16,25 +16,22 @@ on: - 'action.yml' - 'src/**' -permissions: {} +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: write # Required to create releases + pull-requests: write # Required to create comments on the PRs jobs: Release: - if: github.event.pull_request.head.repo.full_name == github.repository runs-on: ubuntu-latest - permissions: - contents: write - pull-requests: write - concurrency: - group: ${{ github.workflow }}-${{ github.repository }} - queue: max - cancel-in-progress: false steps: - - name: Checkout trusted configuration + - name: Checkout repo uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: - ref: ${{ github.event.pull_request.merged && github.event.pull_request.merge_commit_sha || github.event.pull_request.base.sha }} persist-credentials: false - name: Release - uses: PSModule/Release-GHRepository@bee1a2c437920824370c8b42a8cb6a2916cc2cb4 # Verified dependencies and direct PR publication + uses: ./ diff --git a/README.md b/README.md index a750157..36bfaed 100644 --- a/README.md +++ b/README.md @@ -13,9 +13,7 @@ Release-GHRepository follows: ## How it works -One release workflow runs on regular `pull_request` events for the main branch. -It calls an action pinned to a reviewed commit and reads configuration from a trusted checkout. -It does not execute the PR's local action or scripts. +The workflow will trigger on pull requests to the main branch. The following labels will inform the action what kind of release to create: - For a major release, and increasing the first number in the version use: @@ -28,14 +26,7 @@ The following labels will inform the action what kind of release to create: - `patch` - `fix` -Add the `prerelease` label to create prereleases while a same-repository PR is open. -Prereleases use the PR head commit and a PR-specific tag, such as `v1.2.3-pr42.1`. -When the PR is merged, the action creates a stable release at its merge commit. Closing an unmerged PR does not create a stable release. -With `AutoCleanup` enabled, closing or merging the PR removes only prereleases in that PR's tag namespace. -Other prereleases are left unchanged. - -Fork PR checks remain read-only. The release workflow skips fork PRs, including their merge events, because their regular PR tokens cannot publish. -Do not enable write tokens for fork checks. +When a pull request is closed, the action will create a release based on the labels and clean up any previous prereleases that were created. > [!NOTE] > The labels can be configured using the `MajorLabels`, `MinorLabels` and `PatchLabels` parameters/settings in the configuration file to trigger @@ -55,7 +46,7 @@ The action can be configured using the following settings: | `CreateMinorTag` | Control whether to create a tag for minor releases. | `true` | false | | `DatePrereleaseFormat` | The format to use for the prerelease number using [.NET DateTime format strings](https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings). | `''` | false | | `IgnoreLabels` | A comma separated list of labels that do not trigger a release. | `NoRelease` | false | -| `IncrementalPrerelease` | Control whether to automatically increment the prerelease number. If disabled, the action replaces the prerelease for the pull request. | `true` | false | +| `IncrementalPrerelease` | Control whether to automatically increment the prerelease number. If disabled, the action will ensure only one prerelease exists for a given branch. | `true` | false | | `MajorLabels` | A comma separated list of labels that trigger a major release. | `major, breaking` | false | | `MinorLabels` | A comma separated list of labels that trigger a minor release. | `minor, feature` | false | | `PatchLabels` | A comma separated list of labels that trigger a patch release. | `patch, fix` | false | @@ -63,10 +54,10 @@ The action can be configured using the following settings: | `UsePRBodyAsReleaseNotes` | When enabled, uses the pull request body as the release notes for the GitHub release. | `true` | false | | `UsePRTitleAsNotesHeading` | When enabled, the release notes will begin with the pull request title as a H1 heading followed by the pull request body. The title will include a reference to the PR number. | `true` | false | | `VersionPrefix` | The prefix to use for the version number. | `v` | false | -| `WhatIf` | Simulate release and tag changes. Set this input to `true` for read-only checks. A true input cannot be disabled by the configuration file. | `false` | false | +| `WhatIf` | Control whether to simulate the action. If enabled, the action will not create any releases. Used for testing. | `false` | false | | `Debug` | Enable debug output. | `'false'` | false | | `Verbose` | Enable verbose output. | `'false'` | false | -| `Version` | Specifies the version of the GitHub module to install. Accepts an exact version or a NuGet version range (for example `[1.2.0, 2.0.0)`). | `[0.43.1]` | false | +| `Version` | Specifies the version of the GitHub module to install. Accepts an exact version or a NuGet version range (for example `[1.2.0, 2.0.0)`). | | false | | `Prerelease` | Allow prerelease versions if available. | `'false'` | false | | `WorkingDirectory` | The working directory where the script runs. | `${{ github.workspace }}` | false | @@ -75,9 +66,6 @@ The action can be configured using the following settings: The configuration file is a YAML file that can be used to configure the action. By default, the configuration file is expected at `.github\auto-release.yml`, which can be changed using the `ConfigurationFile` setting. The action's configuration can be changed by altering the settings in the configuration file. -The example reads this file from the PR base commit while the PR is open and from the approved merge commit after merge. -It does not read configuration changes from an unmerged PR. -Configuration cannot turn off an explicit `WhatIf: true` input. ```yaml DatePrereleaseFormat: 'yyyyMMddHHmm' @@ -89,11 +77,10 @@ This example uses the date format for the prerelease, disables the incremental p ## Example -Save this single workflow as `.github/workflows/Release.yml`. The example uses a GitHub-hosted Ubuntu runner. -The release job has write permissions, so it calls a pinned action instead of running the PR's local `./` action. +Add a workflow in your repository using the following example: ```yaml -name: Release +name: Release-GHRepository on: pull_request: @@ -106,69 +93,26 @@ on: - synchronize - labeled -permissions: {} +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} jobs: - Release: - if: github.event.pull_request.head.repo.full_name == github.repository + Release-GHRepository: runs-on: ubuntu-latest - permissions: - contents: write - pull-requests: write - concurrency: - group: ${{ github.workflow }}-${{ github.repository }} - queue: max - cancel-in-progress: false steps: - - name: Checkout trusted configuration - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 - with: - ref: ${{ github.event.pull_request.merged && github.event.pull_request.merge_commit_sha || github.event.pull_request.base.sha }} - persist-credentials: false - - - name: Release - uses: PSModule/Release-GHRepository@bee1a2c437920824370c8b42a8cb6a2916cc2cb4 # Verified dependencies and direct PR publication -``` + - name: Checkout Code + uses: actions/checkout@v4 -Do not replace the trusted checkout ref with the PR head or add steps that execute files from an unmerged PR in this write-capable job. -Keep the action pin under review when changing the publisher. Use `WhatIf: true` with read-only permissions to test proposed local action changes. -The action checks live PR metadata before writing. A stale event fails instead of publishing a later commit or a changed PR state. -Major and minor tags are updated through the GitHub API. Checkout credentials are not required. - -Use reviewed commit SHAs for external actions. Enable GitHub Actions dependency updates in the consuming repository to keep these pins current. -This setup trusts contributors who can change workflows in the repository. Any additional publication approval boundary must be enforced by repository or organization policy. + - name: Release-GHRepository + uses: PSModule/Release-GHRepository@v1 +``` ## Permissions -Set permissions explicitly for each job. Read-only checks need only `contents: read` and `pull-requests: read`, with `WhatIf: true`. -The release job needs these scopes: +If running the action in a restrictive mode, the following permissions needs to be granted to the action: ```yaml permissions: - contents: write # Create releases and update release tags - pull-requests: write # Post release comments on PRs + contents: write # Required to create releases + pull-requests: write # Required to create comments on the PRs ``` - -The examples use the short-lived, repository-scoped `GITHUB_TOKEN` supported by this action. They do not need a personal access token. -Requested write permissions do not override the read-only restriction for normal fork PR checks. - -## Dependency maintenance - -`src/Release-GHRepository.Dependencies.psd1` locks the `powershell-yaml` and `PSSemVer` package versions and SHA256 hashes. -The action checks each downloaded package before extraction or import and imports the verified module by its full path. -Update a version and its hash together in a reviewed PR. Do not change a hash only to make a failed verification pass. - -The repository linter uses the upstream Super-Linter action pinned to a full commit SHA. -Dependabot checks workflow action pins for updates. -The upstream action selects its container image by version tag, so the action SHA does not lock the container image digest. - -## Local checks - -With PowerShell 7 and Pester 6.1.0 installed, run: - -```powershell -Invoke-Pester -Path .\tests -CI -``` - -These tests need no GitHub credentials and do not publish releases. -Tag API failures use test doubles to avoid production writes; those tests do not establish that live publication succeeds. diff --git a/action.yml b/action.yml index a953f58..bd28559 100644 --- a/action.yml +++ b/action.yml @@ -35,7 +35,7 @@ inputs: required: false default: NoRelease IncrementalPrerelease: - description: Control whether to automatically increment the prerelease number. If disabled, the action replaces the prerelease for the pull request. + description: Control whether to automatically increment the prerelease number. If disabled, the action will ensure only one prerelease exists for a given branch. required: false default: 'true' MajorLabels: @@ -67,7 +67,7 @@ inputs: required: false default: v WhatIf: - description: Simulate release and tag changes. A true input cannot be disabled by the configuration file. + description: If specified, the action will only log the changes it would make, but will not actually create or delete any releases or tags. required: false default: 'false' Debug: @@ -81,7 +81,6 @@ inputs: Version: description: Specifies the version of the GitHub module to be installed. Accepts an exact version or a NuGet version range (for example '[1.2.0, 2.0.0)'). required: false - default: '[0.43.1]' Prerelease: description: Allow prerelease versions if available. required: false @@ -118,7 +117,6 @@ runs: Prerelease: ${{ inputs.Prerelease }} Verbose: ${{ inputs.Verbose }} Version: ${{ inputs.Version }} - PreserveCredentials: false Name: Release-GHRepository WorkingDirectory: ${{ inputs.WorkingDirectory }} Script: | diff --git a/src/Release-GHRepository.Dependencies.psd1 b/src/Release-GHRepository.Dependencies.psd1 deleted file mode 100644 index 032d089..0000000 --- a/src/Release-GHRepository.Dependencies.psd1 +++ /dev/null @@ -1,14 +0,0 @@ -@{ - Modules = @( - @{ - Name = 'powershell-yaml' - Version = '0.4.12' - SHA256 = 'D4602BC7A4A093766520422D53CA8B09ACDE162286FAE11E2EE6C8EDFEA07810' - } - @{ - Name = 'PSSemVer' - Version = '1.1.10' - SHA256 = '49E79D95C31C3D756A2378634128A360FC8EFAE4CE7409E3F16A55AA94AC5820' - } - ) -} diff --git a/src/Release-GHRepository.Helpers.psm1 b/src/Release-GHRepository.Helpers.psm1 deleted file mode 100644 index c2dfb14..0000000 --- a/src/Release-GHRepository.Helpers.psm1 +++ /dev/null @@ -1,323 +0,0 @@ -#Requires -Version 7.0 - -$ErrorActionPreference = 'Stop' - -function Import-VerifiedReleaseModule { - <# - .SYNOPSIS - Verify a package before extracting and importing its module. - - .DESCRIPTION - Check the package SHA256 and module version. Import the verified manifest by path, - so a same-name module elsewhere on the runner cannot replace it. - - .EXAMPLE - Import-VerifiedReleaseModule -Path $package -DestinationPath $directory -Name $name -RequiredVersion $version -SHA256 $hash - - .INPUTS - None - - You can't pipe objects to Import-VerifiedReleaseModule. - - .OUTPUTS - System.Management.Automation.PSModuleInfo - - The imported module. - #> - [OutputType([System.Management.Automation.PSModuleInfo])] - [CmdletBinding(SupportsShouldProcess)] - param( - # The downloaded package. - [Parameter(Mandatory)] - [ValidateNotNullOrEmpty()] - [string] $Path, - - # A new directory for the verified module files. - [Parameter(Mandatory)] - [ValidateNotNullOrEmpty()] - [ValidateScript({ [System.IO.Path]::IsPathFullyQualified($_) })] - [string] $DestinationPath, - - # The module name declared in the dependency lock. - [Parameter(Mandatory)] - [ValidatePattern('^[A-Za-z0-9_.-]+$')] - [string] $Name, - - # The exact reviewed module version. - [Parameter(Mandatory)] - [version] $RequiredVersion, - - # The reviewed package digest. - [Parameter(Mandatory)] - [ValidatePattern('^[A-Fa-f0-9]{64}$')] - [string] $SHA256 - ) - - $packagePath = (Resolve-Path -LiteralPath $Path -ErrorAction Stop).ProviderPath - $actualHash = (Get-FileHash -LiteralPath $packagePath -Algorithm SHA256 -ErrorAction Stop).Hash - if ($actualHash -ne $SHA256) { - throw "SHA256 verification failed for [$Name $RequiredVersion]. Do not import this package." - } - if (Test-Path -LiteralPath $DestinationPath) { - throw "The verified module directory already exists: [$DestinationPath]. Use a new directory." - } - - if ($PSCmdlet.ShouldProcess("$Name $RequiredVersion", 'Import verified module')) { - [System.IO.Compression.ZipFile]::ExtractToDirectory($packagePath, $DestinationPath) - $manifestPath = Join-Path $DestinationPath "$Name.psd1" - $manifest = Import-PowerShellDataFile -LiteralPath $manifestPath -ErrorAction Stop - if ([version] $manifest.ModuleVersion -ne $RequiredVersion) { - throw "The package does not contain [$Name] at the required version [$RequiredVersion]." - } - - $moduleSpecification = @{ - ModuleName = $manifestPath - RequiredVersion = $RequiredVersion - } - Get-Module -Name $Name | Remove-Module -Force -ErrorAction Stop - Import-Module -FullyQualifiedName $moduleSpecification -Global -Force -PassThru -ErrorAction Stop - } -} - -function Assert-ReleasePullRequest { - <# - .SYNOPSIS - Validate PR metadata before privileged publication. - - .DESCRIPTION - Require a same-repository PR targeting the default branch. - Compare the event with live PR metadata before publishing its immutable commit. - - .EXAMPLE - Assert-ReleasePullRequest -PullRequest $eventPr -CurrentPullRequest $livePr -Repository 'owner/repo' -DefaultBranch 'main' - - .INPUTS - None - - You can't pipe objects to Assert-ReleasePullRequest. - - .OUTPUTS - None - - This function throws when the publication metadata is invalid. - #> - [OutputType([void])] - [CmdletBinding()] - param( - # The PR metadata from the pull_request event. - [Parameter(Mandatory)] - [ValidateNotNull()] - [pscustomobject] $PullRequest, - - # The current PR returned by the repository API. - [Parameter(Mandatory)] - [ValidateNotNull()] - [pscustomobject] $CurrentPullRequest, - - # The repository that owns the publishing workflow. - [Parameter(Mandatory)] - [ValidatePattern('^[^/]+/[^/]+$')] - [string] $Repository, - - # The repository's default branch. - [Parameter(Mandatory)] - [ValidateNotNullOrEmpty()] - [string] $DefaultBranch - ) - - if ($PullRequest.base.repo.full_name -ne $Repository -or $CurrentPullRequest.base.repo.full_name -ne $Repository) { - throw "Publication metadata does not belong to repository [$Repository]." - } - if ($PullRequest.head.repo.full_name -ne $Repository -or $CurrentPullRequest.head.repo.full_name -ne $Repository) { - throw 'Publication requires a same-repository pull request. Fork tokens are read-only.' - } - if ($PullRequest.number -lt 1 -or $CurrentPullRequest.number -ne $PullRequest.number) { - throw 'Publication metadata does not match the pull request.' - } - if ($PullRequest.base.ref -ne $DefaultBranch) { - throw "Publication requires a pull request targeting the default branch [$DefaultBranch]." - } - if (-not $PullRequest.merged -and $PullRequest.head.repo.full_name -ne $Repository) { - throw 'Open-PR prereleases require a branch in this repository.' - } - if ($PullRequest.head.sha -cnotmatch '^[a-f0-9]{40}$' -or - ($PullRequest.merged -and $PullRequest.merge_commit_sha -cnotmatch '^[a-f0-9]{40}$')) { - throw 'Publication requires a valid commit SHA.' - } - if ($CurrentPullRequest.head.sha -cne $PullRequest.head.sha -or - $CurrentPullRequest.base.ref -ne $PullRequest.base.ref -or - $CurrentPullRequest.state -ne $PullRequest.state -or - $CurrentPullRequest.merged -ne $PullRequest.merged -or - ($PullRequest.merged -and $CurrentPullRequest.merge_commit_sha -cne $PullRequest.merge_commit_sha)) { - throw 'The pull request changed since this event. Run publication for the current PR state.' - } -} - -function Test-ReleasePreview { - <# - .SYNOPSIS - Select preview mode without allowing configuration to override the caller. - - .DESCRIPTION - Honor an explicit preview request or configuration setting. - Permit publication only for regular pull_request events. - - .EXAMPLE - Test-ReleasePreview -EventName 'pull_request' -Configured - - .INPUTS - None - - You can't pipe objects to Test-ReleasePreview. - - .OUTPUTS - System.Boolean - - True when release changes must be simulated. - #> - [OutputType([bool])] - [CmdletBinding()] - param( - # The GitHub Actions event name. - [Parameter(Mandatory)] - [ValidateNotNullOrEmpty()] - [string] $EventName, - - # An explicit WhatIf input from the caller. - [Parameter()] - [switch] $Requested, - - # The WhatIf setting from the trusted configuration. - [Parameter()] - [switch] $Configured - ) - - if ($Requested -or $Configured) { - $true - } elseif ($EventName -eq 'pull_request') { - $false - } else { - throw 'Write operations require a regular pull_request event. Use WhatIf for other events.' - } -} - -function Get-ReleasePrerelease { - <# - .SYNOPSIS - Select only prereleases in one PR's tag namespace. - - .DESCRIPTION - Exclude stable releases and tags for other PRs before cleanup or replacement. - - .EXAMPLE - Get-ReleasePrerelease -Release $releases -PullRequestNumber 7 -VersionPrefix 'v' - - .INPUTS - None - - You can't pipe objects to Get-ReleasePrerelease. - - .OUTPUTS - System.Management.Automation.PSCustomObject - - The matching prerelease records. - #> - [OutputType([pscustomobject])] - [CmdletBinding()] - param( - # Release records returned by the repository API. - [Parameter(Mandatory)] - [AllowEmptyCollection()] - [pscustomobject[]] $Release, - - # The PR that owns these prerelease tags. - [Parameter(Mandatory)] - [ValidateRange(1, [int]::MaxValue)] - [int] $PullRequestNumber, - - # The configured prefix, including an empty prefix. - [Parameter(Mandatory)] - [AllowEmptyString()] - [string] $VersionPrefix - ) - - $pattern = '^{0}[0-9]+\.[0-9]+\.[0-9]+-pr{1}(?:\.[0-9A-Za-z-]+)*(?:\+[0-9A-Za-z.-]+)?$' -f - [regex]::Escape($VersionPrefix), $PullRequestNumber - $Release | Where-Object { $_.isPrerelease -eq $true -and $_.tagName -cmatch $pattern } -} - -function Set-ReleaseTag { - <# - .SYNOPSIS - Point one release tag at its immutable release commit. - - .DESCRIPTION - Create or update only the requested tag through the repository API. - Do not persist Git credentials or push unrelated local tags. - - .EXAMPLE - Set-ReleaseTag -Repository 'owner/repo' -Name 'v1' -CommitSha $releaseCommit - - .INPUTS - None - - You can't pipe objects to Set-ReleaseTag. - - .OUTPUTS - None - - This function updates the repository tag. - #> - [OutputType([void])] - [CmdletBinding(SupportsShouldProcess)] - param( - # The repository that owns the release. - [Parameter(Mandatory)] - [ValidatePattern('^[^/]+/[^/]+$')] - [string] $Repository, - - # The release tag to create or update. - [Parameter(Mandatory)] - [ValidateNotNullOrEmpty()] - [string] $Name, - - # The stable release's merge commit. - [Parameter(Mandatory)] - [ValidatePattern('^[a-f0-9]{40}$')] - [string] $CommitSha - ) - - git check-ref-format "refs/tags/$Name" - if ($LASTEXITCODE -ne 0) { - throw "Invalid release tag name: [$Name]." - } - if ($PSCmdlet.ShouldProcess("$Repository tag $Name", "Point tag at $CommitSha")) { - $encodedName = [uri]::EscapeDataString($Name) - $referencesJson = gh api "repos/$Repository/git/matching-refs/tags/$encodedName" - if ($LASTEXITCODE -ne 0) { - throw "Failed to list tag references for [$Name]." - } - $references = $referencesJson | ConvertFrom-Json -NoEnumerate - if ($references -isnot [array]) { - throw "Failed to list tag references for [$Name]: the API response is not an array." - } - $reference = $references | Where-Object { $_.ref -ceq "refs/tags/$Name" } - if ($reference) { - $arguments = @( - 'api', '--method', 'PATCH', "repos/$Repository/git/refs/tags/$encodedName", - '-f', "sha=$CommitSha", '-F', 'force=true' - ) - } else { - $arguments = @( - 'api', '--method', 'POST', "repos/$Repository/git/refs", - '-f', "ref=refs/tags/$Name", '-f', "sha=$CommitSha" - ) - } - $null = gh @arguments - if ($LASTEXITCODE -ne 0) { - throw "Failed to set release tag [$Name] to [$CommitSha]." - } - } -} - -Export-ModuleMember -Function Import-VerifiedReleaseModule, Assert-ReleasePullRequest, Test-ReleasePreview, Get-ReleasePrerelease, Set-ReleaseTag diff --git a/src/main.ps1 b/src/main.ps1 index a7d109d..089a75f 100644 --- a/src/main.ps1 +++ b/src/main.ps1 @@ -8,34 +8,26 @@ [CmdletBinding()] param() -$ErrorActionPreference = 'Stop' -Import-Module -Name (Join-Path $PSScriptRoot 'Release-GHRepository.Helpers.psm1') -Force - LogGroup 'Loading libraries' { - $dependencies = Import-PowerShellDataFile -LiteralPath (Join-Path $PSScriptRoot 'Release-GHRepository.Dependencies.psd1') - $dependencyDirectory = Join-Path ([System.IO.Path]::GetTempPath()) "Release-GHRepository-$([guid]::NewGuid())" - $null = New-Item -Path $dependencyDirectory -ItemType Directory - foreach ($dependency in $dependencies.Modules) { - $name = $dependency.Name - $version = $dependency.Version - Write-Output "Downloading locked module: [$name $version]" - $packagePath = Join-Path $dependencyDirectory "$name.$version.nupkg" - $downloadParameters = @{ - Uri = "https://www.powershellgallery.com/api/v2/package/$name/$version" - OutFile = $packagePath - MaximumRetryCount = 4 - RetryIntervalSec = 10 - ErrorAction = 'Stop' - } - Invoke-WebRequest @downloadParameters - $importParameters = @{ - Path = $packagePath - DestinationPath = Join-Path $dependencyDirectory "$name.$version" - Name = $name - RequiredVersion = $version - SHA256 = $dependency.SHA256 + 'powershell-yaml', 'PSSemVer' | ForEach-Object { + $name = $_ + Write-Output "Installing module: $name" + $count = 5 + $delay = 10 + for ($i = 1; $i -le $count; $i++) { + try { + Install-PSResource -Name $name -WarningAction SilentlyContinue -TrustRepository -Repository PSGallery + break + } catch { + Write-Warning "Installation of $name failed with error: $_" + if ($i -eq $count) { + throw $_ + } + Write-Warning "Retrying in $delay seconds..." + Start-Sleep -Seconds $delay + } } - $null = Import-VerifiedReleaseModule @importParameters -Confirm:$false + Import-Module -Name $name } } @@ -57,12 +49,7 @@ LogGroup 'Set configuration' { $usePRTitleAsReleaseName = ![string]::IsNullOrEmpty($configuration.UsePRTitleAsReleaseName) ? $configuration.UsePRTitleAsReleaseName -eq 'true' : $env:PSMODULE_AUTO_RELEASE_INPUT_UsePRTitleAsReleaseName -eq 'true' $usePRTitleAsNotesHeading = ![string]::IsNullOrEmpty($configuration.UsePRTitleAsNotesHeading) ? $configuration.UsePRTitleAsNotesHeading -eq 'true' : $env:PSMODULE_AUTO_RELEASE_INPUT_UsePRTitleAsNotesHeading -eq 'true' $versionPrefix = ![string]::IsNullOrEmpty($configuration.VersionPrefix) ? $configuration.VersionPrefix : $env:PSMODULE_AUTO_RELEASE_INPUT_VersionPrefix - $previewParameters = @{ - EventName = $env:GITHUB_EVENT_NAME - Requested = $env:PSMODULE_AUTO_RELEASE_INPUT_WhatIf -eq 'true' - Configured = $configuration.WhatIf -eq 'true' - } - $whatIf = Test-ReleasePreview @previewParameters + $whatIf = ![string]::IsNullOrEmpty($configuration.WhatIf) ? $configuration.WhatIf -eq 'true' : $env:PSMODULE_AUTO_RELEASE_INPUT_WhatIf -eq 'true' $ignoreLabels = (![string]::IsNullOrEmpty($configuration.IgnoreLabels) ? $configuration.IgnoreLabels : $env:PSMODULE_AUTO_RELEASE_INPUT_IgnoreLabels) -split ',' | ForEach-Object { $_.Trim() } $majorLabels = (![string]::IsNullOrEmpty($configuration.MajorLabels) ? $configuration.MajorLabels : $env:PSMODULE_AUTO_RELEASE_INPUT_MajorLabels) -split ',' | ForEach-Object { $_.Trim() } @@ -104,31 +91,8 @@ LogGroup 'Event information - Object' { $githubEvent | Format-List | Out-String } -if (-not $whatIf -and $pull_request.head.repo.full_name -ne $env:GITHUB_REPOSITORY) { - Write-GitHubWarning 'Fork PR publication is skipped because regular fork PR tokens are read-only.' - return -} - -$repositoryJson = gh repo view $env:GITHUB_REPOSITORY --json defaultBranchRef -if ($LASTEXITCODE -ne 0) { - throw 'Failed to read the repository default branch.' -} -$defaultBranchName = ($repositoryJson | ConvertFrom-Json).defaultBranchRef.name -if (-not $whatIf) { - $pullRequestNumber = $pull_request.number - $currentPullRequestJson = gh api "repos/$env:GITHUB_REPOSITORY/pulls/$pullRequestNumber" - if ($LASTEXITCODE -ne 0) { - throw "Failed to read pull request [$pullRequestNumber]." - } - $validationParameters = @{ - PullRequest = $pull_request - CurrentPullRequest = $currentPullRequestJson | ConvertFrom-Json - Repository = $env:GITHUB_REPOSITORY - DefaultBranch = $defaultBranchName - } - Assert-ReleasePullRequest @validationParameters -} -$isPullRequest = $null -ne $pull_request +$defaultBranchName = (gh repo view --json defaultBranchRef | ConvertFrom-Json | Select-Object -ExpandProperty defaultBranchRef).name +$isPullRequest = $githubEvent.PSObject.Properties.Name -Contains 'pull_request' if (-not ($isPullRequest -or $whatIf)) { Write-Warning '⚠️ A release should not be created in this context. Exiting.' exit @@ -139,10 +103,6 @@ $prIsClosed = $pull_request.state -eq 'closed' $prBaseRef = $pull_request.base.ref $prHeadRef = $pull_request.head.ref $targetIsDefaultBranch = $pull_request.base.ref -eq $defaultBranchName -$releaseCommit = $pull_request.head.sha -if ($isMerged) { - $releaseCommit = $pull_request.merge_commit_sha -} Write-Output '-------------------------------------------------' Write-Output "Default branch: [$defaultBranchName]" @@ -168,7 +128,7 @@ LogGroup 'Pull request - Labels' { $createRelease = $isMerged -and $targetIsDefaultBranch $closedPullRequest = $prIsClosed -and -not $isMerged $createPrerelease = $labels -Contains 'prerelease' -and -not $createRelease -and -not $closedPullRequest -$prereleaseName = "pr$($pull_request.number)" +$prereleaseName = $prHeadRef -replace '[^a-zA-Z0-9]' $ignoreRelease = ($labels | Where-Object { $ignoreLabels -contains $_ }).Count -gt 0 if ($ignoreRelease) { @@ -249,9 +209,6 @@ if ($createPrerelease -or $createRelease -or $whatIf) { if ($incrementalPrerelease) { $newVersion.BumpPrereleaseNumber() - while ($releases.tagName -contains $newVersion.ToString()) { - $newVersion.BumpPrereleaseNumber() - } } } } @@ -263,10 +220,6 @@ if ($createPrerelease -or $createRelease -or $whatIf) { if ($createPrerelease) { $releaseExists = $releases.tagName -Contains $newVersion if ($releaseExists -and -not $incrementalPrerelease) { - $existingRelease = $releases | Where-Object { $_.tagName -ceq $newVersion.ToString() } - if ($existingRelease.isPrerelease -ne $true) { - throw "Refusing to replace non-prerelease [$newVersion]." - } Write-Output 'Release already exists, recreating.' if ($whatIf) { Write-Output "WhatIf: gh release delete $newVersion --cleanup-tag --yes" @@ -309,7 +262,7 @@ if ($createPrerelease -or $createRelease -or $whatIf) { } # Add remaining parameters - $releaseCreateCommand += @('--target', $releaseCommit, '--prerelease') + $releaseCreateCommand += @('--target', $prHeadRef, '--prerelease') Write-Output "gh $($releaseCreateCommand -join ' ')" if (-not $whatIf) { @@ -332,7 +285,7 @@ if ($createPrerelease -or $createRelease -or $whatIf) { } } else { # Build release creation command with options - $releaseCreateCommand = @('release', 'create', "$newVersion", '--target', $releaseCommit) + $releaseCreateCommand = @('release', 'create', "$newVersion") # Add title parameter if ($usePRTitleAsReleaseName) { @@ -372,38 +325,47 @@ if ($createPrerelease -or $createRelease -or $whatIf) { if ($createMajorTag) { $majorTag = ('{0}{1}' -f $newVersion.Prefix, $newVersion.Major) if ($whatIf) { - Write-Output "WhatIf: point tag [$majorTag] at [$releaseCommit]" + Write-Output "WhatIf: git tag -f $majorTag 'main'" } else { - Set-ReleaseTag -Repository $env:GITHUB_REPOSITORY -Name $majorTag -CommitSha $releaseCommit -Confirm:$false + git tag -f $majorTag 'main' + if ($LASTEXITCODE -ne 0) { + Write-Error "Failed to create major tag [$majorTag]." + exit $LASTEXITCODE + } } } if ($createMinorTag) { $minorTag = ('{0}{1}.{2}' -f $newVersion.Prefix, $newVersion.Major, $newVersion.Minor) if ($whatIf) { - Write-Output "WhatIf: point tag [$minorTag] at [$releaseCommit]" + Write-Output "WhatIf: git tag -f $minorTag 'main'" } else { - Set-ReleaseTag -Repository $env:GITHUB_REPOSITORY -Name $minorTag -CommitSha $releaseCommit -Confirm:$false + git tag -f $minorTag 'main' + if ($LASTEXITCODE -ne 0) { + Write-Error "Failed to create minor tag [$minorTag]." + exit $LASTEXITCODE + } + } + } + + if ($whatIf) { + Write-Output 'WhatIf: git push origin --tags --force' + } else { + git push origin --tags --force + if ($LASTEXITCODE -ne 0) { + Write-Error 'Failed to push tags.' + exit $LASTEXITCODE } } } } - if ($whatIf) { - Write-GitHubNotice -Title 'Release preview' -Message $newVersion - } else { - Write-GitHubNotice -Title 'Release created' -Message $newVersion - } + Write-GitHubNotice -Title 'Release created' -Message $newVersion } else { Write-Output 'Skipping release creation.' } LogGroup 'List prereleases using the same name' { - $selectionParameters = @{ - Release = @($releases) - PullRequestNumber = $pull_request.number - VersionPrefix = $versionPrefix - } - $prereleasesToCleanup = Get-ReleasePrerelease @selectionParameters + $prereleasesToCleanup = $releases | Where-Object { $_.tagName -like "*$prereleaseName*" } $prereleasesToCleanup | Select-Object -Property name, publishedAt, isPrerelease, isLatest | Format-Table | Out-String } diff --git a/tests/Release-GHRepository.Tests.ps1 b/tests/Release-GHRepository.Tests.ps1 deleted file mode 100644 index f535583..0000000 --- a/tests/Release-GHRepository.Tests.ps1 +++ /dev/null @@ -1,311 +0,0 @@ -[Diagnostics.CodeAnalysis.SuppressMessageAttribute( - 'PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Pester shares setup variables with test script blocks.' -)] -param() - -BeforeAll { - $helperPath = Join-Path $PSScriptRoot '..\src\Release-GHRepository.Helpers.psm1' - Import-Module -Name $helperPath -Force -} - -Describe 'Verified release modules' { - BeforeEach { - $fixtureRoot = Join-Path $TestDrive ([guid]::NewGuid().ToString()) - $moduleDirectory = Join-Path $fixtureRoot 'source' - $null = New-Item -Path $moduleDirectory -ItemType Directory - $manifestPath = Join-Path $moduleDirectory 'ReleaseSecurityFixture.psd1' - New-ModuleManifest -Path $manifestPath -RootModule 'ReleaseSecurityFixture.psm1' -ModuleVersion '1.0.0' - $modulePath = Join-Path $moduleDirectory 'ReleaseSecurityFixture.psm1' - $markerPath = Join-Path $fixtureRoot 'imported.txt' - $moduleContent = @' -$null = New-Item -Path '__MARKER__' -ItemType File -Force -function Get-ReleaseSecurityFixtureValue { 'verified package' } -New-Alias -Name releaseFixtureAlias -Value Get-ReleaseSecurityFixtureValue -Export-ModuleMember -Function Get-ReleaseSecurityFixtureValue -Alias releaseFixtureAlias -'@ - $moduleContent.Replace('__MARKER__', $markerPath.Replace("'", "''")) | Set-Content -LiteralPath $modulePath - $packagePath = Join-Path $fixtureRoot 'package.nupkg' - [System.IO.Compression.ZipFile]::CreateFromDirectory($moduleDirectory, $packagePath) - $packageHash = (Get-FileHash -LiteralPath $packagePath -Algorithm SHA256).Hash - $destinationPath = Join-Path $fixtureRoot 'verified' - $importParameters = @{ - Path = $packagePath - DestinationPath = $destinationPath - Name = 'ReleaseSecurityFixture' - RequiredVersion = '1.0.0' - SHA256 = $packageHash - } - } - - AfterEach { - Get-Module -Name ReleaseSecurityFixture | Remove-Module -Force - } - - It 'loads the verified package and exact module version' { - $module = Import-VerifiedReleaseModule @importParameters - - $module.Version | Should -Be ([version] '1.0.0') - Get-ReleaseSecurityFixtureValue | Should -Be 'verified package' - } - - It 'rejects changed package bytes before extraction or module execution' { - $archive = [System.IO.Compression.ZipFile]::Open($packagePath, 'Update') - try { - $archive.GetEntry('ReleaseSecurityFixture.psm1').Delete() - $entry = $archive.CreateEntry('ReleaseSecurityFixture.psm1') - $writer = [System.IO.StreamWriter]::new($entry.Open()) - try { - $tamperedContent = "`$null = New-Item -Path '$($markerPath.Replace("'", "''"))' -ItemType File" - $writer.Write($tamperedContent) - } finally { - $writer.Dispose() - } - } finally { - $archive.Dispose() - } - - { Import-VerifiedReleaseModule @importParameters } | Should -Throw -ExpectedMessage '*SHA256*' - Test-Path -LiteralPath $markerPath | Should -BeFalse - Test-Path -LiteralPath $destinationPath | Should -BeFalse - } - - It 'rejects a different module version before module execution' { - $importParameters.RequiredVersion = '2.0.0' - - { Import-VerifiedReleaseModule @importParameters } | Should -Throw -ExpectedMessage '*2.0.0*' - Test-Path -LiteralPath $markerPath | Should -BeFalse - } - - It 'does not select a same-name module from another directory' { - $shadowDirectory = Join-Path $fixtureRoot 'shadow' - $null = New-Item -Path $shadowDirectory -ItemType Directory - $shadowPath = Join-Path $shadowDirectory 'ReleaseSecurityFixture.psm1' - "function Get-ReleaseSecurityFixtureValue { 'unverified module' }" | Set-Content -LiteralPath $shadowPath - Import-Module -Name $shadowPath -Global - - $null = Import-VerifiedReleaseModule @importParameters - - Get-ReleaseSecurityFixtureValue | Should -Be 'verified package' - } - - It 'reloads a verified module even when its exported aliases are already loaded' { - $null = Import-VerifiedReleaseModule @importParameters - $importParameters.DestinationPath = Join-Path $fixtureRoot 'verified-again' - - $importResult = @(Import-VerifiedReleaseModule @importParameters 2>&1) - - @($importResult | Where-Object { $_ -is [System.Management.Automation.ErrorRecord] }).Count | Should -Be 0 - Get-ReleaseSecurityFixtureValue | Should -Be 'verified package' - } -} - -Describe 'Pull request publication trust boundary' { - BeforeEach { - $repository = 'PSModule/Release-GHRepository' - $headSha = '1111111111111111111111111111111111111111' - $mergeSha = '2222222222222222222222222222222222222222' - $pullRequest = [pscustomobject] @{ - number = 7 - state = 'open' - merged = $false - closed_at = $null - merge_commit_sha = $null - base = [pscustomobject] @{ - ref = 'main' - repo = [pscustomobject] @{ id = 123; full_name = $repository } - } - head = [pscustomobject] @{ - sha = $headSha - repo = [pscustomobject] @{ id = 123; full_name = $repository } - } - } - $currentPullRequest = $pullRequest | ConvertTo-Json -Depth 8 | ConvertFrom-Json - $validationParameters = @{ - PullRequest = $pullRequest - CurrentPullRequest = $currentPullRequest - Repository = $repository - DefaultBranch = 'main' - } - } - - It 'accepts an open same-repository PR at the event commit' { - { Assert-ReleasePullRequest @validationParameters } | Should -Not -Throw - } - - It 'accepts a merged same-repository PR at the event merge commit' { - $pullRequest.state = 'closed' - $pullRequest.merged = $true - $pullRequest.merge_commit_sha = $mergeSha - $currentPullRequest.state = 'closed' - $currentPullRequest.merged = $true - $currentPullRequest.merge_commit_sha = $mergeSha - - { Assert-ReleasePullRequest @validationParameters } | Should -Not -Throw - } - - It 'rejects ' -ForEach @( - @{ - Name = 'an event for another repository' - Change = { $pullRequest.base.repo.full_name = 'other/repository' } - Message = '*repository*' - } - @{ - Name = 'live metadata from another repository' - Change = { $currentPullRequest.base.repo.full_name = 'other/repository' } - Message = '*repository*' - } - @{ - Name = 'an open fork PR' - Change = { $pullRequest.head.repo.full_name = 'contributor/fork' } - Message = '*same-repository*' - } - @{ - Name = 'a merged fork PR' - Change = { - $pullRequest.state = 'closed' - $pullRequest.merged = $true - $pullRequest.merge_commit_sha = $mergeSha - $pullRequest.head.repo.full_name = 'contributor/fork' - } - Message = '*same-repository*' - } - @{ - Name = 'a different PR number' - Change = { $currentPullRequest.number = 8 } - Message = '*pull request*' - } - @{ - Name = 'a PR changed since the event' - Change = { $currentPullRequest.head.sha = '3333333333333333333333333333333333333333' } - Message = '*changed since*' - } - @{ - Name = 'a different target branch' - Change = { $pullRequest.base.ref = 'other-branch' } - Message = '*default branch*' - } - @{ - Name = 'an invalid publication commit' - Change = { $pullRequest.head.sha = '--unexpected-option' } - Message = '*commit SHA*' - } - @{ - Name = 'an old open-PR event after closure' - Change = { $currentPullRequest.state = 'closed' } - Message = '*changed since*' - } - @{ - Name = 'a different merge commit' - Change = { - $pullRequest.state = 'closed' - $pullRequest.merged = $true - $pullRequest.merge_commit_sha = $mergeSha - $currentPullRequest.state = 'closed' - $currentPullRequest.merged = $true - $currentPullRequest.merge_commit_sha = '3333333333333333333333333333333333333333' - } - Message = '*changed since*' - } - ) { - . $Change - - { Assert-ReleasePullRequest @validationParameters } | Should -Throw -ExpectedMessage $Message - } -} - -Describe 'Prerelease cleanup ownership' { - It 'selects only this PR prereleases and excludes stable releases and prefix collisions' { - $releases = @( - [pscustomobject] @{ tagName = 'v1.2.3-pr7.1'; isPrerelease = $true } - [pscustomobject] @{ tagName = 'v1.2.3-pr7'; isPrerelease = $true } - [pscustomobject] @{ tagName = 'v1.2.3-pr7.2'; isPrerelease = $false } - [pscustomobject] @{ tagName = 'v1.2.3-pr70.1'; isPrerelease = $true } - [pscustomobject] @{ tagName = 'v1.2.3-otherpr7.1'; isPrerelease = $true } - [pscustomobject] @{ tagName = 'v1.2.3'; isPrerelease = $false } - ) - - $selected = @(Get-ReleasePrerelease -Release $releases -PullRequestNumber 7 -VersionPrefix 'v') - - $selected.tagName | Should -Be @('v1.2.3-pr7.1', 'v1.2.3-pr7') - } - - It 'supports an empty version prefix' { - $releases = @([pscustomobject] @{ tagName = '1.2.3-pr7.1'; isPrerelease = $true }) - - @(Get-ReleasePrerelease -Release $releases -PullRequestNumber 7 -VersionPrefix '').Count | Should -Be 1 - } -} - -Describe 'Pull request preview controls' { - It 'allows regular pull_request publication when no preview is requested' { - Test-ReleasePreview -EventName 'pull_request' | Should -BeFalse - } - - It 'does not let configuration disable an explicit preview request' { - Test-ReleasePreview -EventName 'pull_request' -Requested | Should -BeTrue - } - - It 'honors a configured preview' { - Test-ReleasePreview -EventName 'pull_request' -Configured | Should -BeTrue - } - - It 'allows read-only scheduled checks' { - Test-ReleasePreview -EventName 'schedule' -Requested | Should -BeTrue - } - - It 'rejects publication on other events' { - { Test-ReleasePreview -EventName 'push' } | Should -Throw -ExpectedMessage '*pull_request*' - } -} - -Describe 'Scoped release tag updates' { - BeforeEach { - $repository = 'PSModule/Release-GHRepository' - $commitSha = '2222222222222222222222222222222222222222' - Mock gh -ModuleName Release-GHRepository.Helpers { - $global:LASTEXITCODE = 0 - '[]' - } - } - - It 'creates only the requested tag at the release commit' { - Set-ReleaseTag -Repository $repository -Name 'v1' -CommitSha $commitSha -Confirm:$false - - Should -Invoke gh -ModuleName Release-GHRepository.Helpers -Exactly -Times 1 -ParameterFilter { - $args -contains 'POST' -and - $args -contains 'ref=refs/tags/v1' -and - $args -contains "sha=$commitSha" - } - } - - It 'updates only the matching tag at the release commit' { - Mock gh -ModuleName Release-GHRepository.Helpers { - $global:LASTEXITCODE = 0 - '[{"ref":"refs/tags/v1"},{"ref":"refs/tags/v10"}]' - } - - Set-ReleaseTag -Repository $repository -Name 'v1' -CommitSha $commitSha -Confirm:$false - - Should -Invoke gh -ModuleName Release-GHRepository.Helpers -Exactly -Times 1 -ParameterFilter { - $args -contains 'PATCH' -and - $args -contains "repos/$repository/git/refs/tags/v1" -and - $args -contains "sha=$commitSha" - } - Should -Invoke gh -ModuleName Release-GHRepository.Helpers -Exactly -Times 0 -ParameterFilter { - $args -contains 'POST' - } - } - - It 'does not write a tag when its lookup fails' { - Mock gh -ModuleName Release-GHRepository.Helpers { - $global:LASTEXITCODE = 1 - } - - { Set-ReleaseTag -Repository $repository -Name 'v1' -CommitSha $commitSha -Confirm:$false } | - Should -Throw -ExpectedMessage '*list*' - - Should -Invoke gh -ModuleName Release-GHRepository.Helpers -Exactly -Times 0 -ParameterFilter { - $args -contains 'POST' -or $args -contains 'PATCH' - } - } -}