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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -79,21 +79,32 @@ jobs:
runs-on: ubuntu-latest
environment: release
env:
INPUT_VERSION: ${{ inputs.version }}
INPUT_GEMSPEC_PATH: ${{ inputs.gemspec }}
DEFAULT_BRANCH: ${{ github.event.repository.default_branch }}
GIT_USER_NAME: ${{ inputs.git-user-name }}
GIT_USER_EMAIL: ${{ inputs.git-user-email }}
RUBYGEMS_OWNER_ID: ${{ inputs.rubygems-owner }}
TZ: ${{ inputs.timezone }}
steps:
- uses: actions/checkout@v7
id: checkout
with:
persist-credentials: false
fetch-depth: 0
- uses: ruby/setup-ruby@v1
id: setup_ruby
with:
ruby-version: ${{ inputs.ruby-version }}
bundler-cache: true
- name: Capture Release Context
id: capture_release_context
env:
RELEASE_STEP_ID: capture_release_context
run: bundle exec rake release:workflow:capture
- name: Check Release Prerequisites
id: check_release_prerequisites
env:
GH_TOKEN: ${{ github.token }}
RELEASE_STEP_ID: check_release_prerequisites
run: bundle exec rake release:workflow:preflight
release:
Expand Down Expand Up @@ -135,6 +146,7 @@ jobs:
- name: Check Release Prerequisites
id: check_release_prerequisites
env:
GH_TOKEN: ${{ github.token }}
RELEASE_STEP_ID: check_release_prerequisites
run: bundle exec rake release:workflow:preflight
- name: Validate Release
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
- [#82](https://github.com/dblock/ruby-gem-release/pull/82): Create the default package and Git temporary directories only when release data is first used, so loading a workflow leaves none behind - [@dblock](https://github.com/dblock).
- [#83](https://github.com/dblock/ruby-gem-release/pull/83): Name Intridea subsections with `sections:`, dropping sections without notes from a release and starting every Next section with all of them - [@dblock](https://github.com/dblock).
- [#85](https://github.com/dblock/ruby-gem-release/pull/85): Verify RubyGems Trusted Publishing before every release with a `release:workflow:preflight` task, add a `dry-run` workflow input that runs only that check, and name the token claims in rejected exchanges - [@dblock](https://github.com/dblock).
- [#86](https://github.com/dblock/ruby-gem-release/pull/86): Check that the release token can push to the default branch and that no repository rules would reject the release commit or tag before every release - [@dblock](https://github.com/dblock).
- Your contribution here.

## 0.7.0 (2026/11/20)
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ Collaborators with write access can dispatch releases after this setup, without

### 4. Make a Release

Your branch rules must permit release commits and tags to be pushed; see [branch permissions](RELEASING.md#one-time-setup). Dispatching starts a publishing run; when required reviewers are configured, the release job waits for approval from a designated maintainer. Run your project's tests and build checks, review the changes, and dispatch from your default branch:
Your branch rules must permit release commits and tags to be pushed; see [branch permissions](RELEASING.md#one-time-setup). Each release checks this before publishing. Dispatching starts a publishing run; when required reviewers are configured, the release job waits for approval from a designated maintainer. Run your project's tests and build checks, review the changes, and dispatch from your default branch:

**First release:** Pass the numeric RubyGems account ID shown on the Pending Trusted Publishers page as `rubygems-owner`. This declares the account that will own the gem on its first publication. Replace `YOUR_ACCOUNT_ID` below with that ID:

Expand Down
1 change: 1 addition & 0 deletions action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ runs:
id: check_release_prerequisites
shell: bash
env:
GH_TOKEN: ${{ github.token }}
RELEASE_STEP_ID: check_release_prerequisites
run: bundle exec rake release:workflow:preflight
- name: Validate Release
Expand Down
2 changes: 1 addition & 1 deletion docs/actions/action.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ Register a RubyGems trusted publisher for the calling repository, its own workfl

For maintainer-only publication, protect the caller job's `release` environment using [Maintainer-Approved Publication](../../RELEASING.md#maintainer-approved-publication). Other repository writers can dispatch, but publication waits for a designated maintainer to approve. Environments do not restrict who can dispatch, and an environment without protection rules does not restrict release access.

The action checks [release prerequisites](release.md#release-prerequisites), including the trusted publisher, after context capture and before validation, edits, or publication. To check without releasing, run `bundle exec rake release:workflow:preflight` in a job of the same workflow file, in the `release` environment, with `id-token: write`. RubyGems matches the workflow file and environment, so a check from another workflow or environment does not prove the release job's configuration. The composite action has no dry-run input.
The action checks [release prerequisites](release.md#release-prerequisites), including the trusted publisher and the token's ability to push the release commit and tag, after context capture and before validation, edits, or publication. To check without releasing, run `bundle exec rake release:workflow:preflight` in a job of the same workflow file, in the `release` environment, with `id-token: write`. RubyGems matches the workflow file and environment, so a check from another workflow or environment does not prove the release job's configuration. The composite action has no dry-run input.

For first publication, register a pending trusted publisher and supply its numeric account ID through `rubygems-owner`. Later publications can omit that input. The default `release:publish` task authenticates through the configured destination before invoking its publication callback; no separate YAML authentication step is needed. The RubyGems destination uses the [Ruby credentials helper](../workflow/ruby_gems_credentials.md) without a stored API key. It exports environment variables and does not create or modify `~/.gem/credentials`. Command overrides that bypass the task must own authentication as well as publication.

Expand Down
4 changes: 3 additions & 1 deletion docs/actions/release.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,11 @@ Identity values must be nonempty and contain no line breaks. They change commit

Every release runs `bundle exec rake release:workflow:preflight` after context capture, before validation, edits, or publication, so missing permissions fail before anything is pushed or published. The preflight requests the job's OIDC token and exchanges it at RubyGems exactly as publication does, passing `rubygems-owner` when set. Success proves that the caller granted `id-token: write` and that a trusted publisher matches the repository, workflow, and environment in the token. The job reports those claims and the credential's scopes; on failure, the error names the claims RubyGems rejected. The exchanged credential is masked, expires after 15 minutes, and is never exported or used; publication performs its own exchange. RubyGems does not report which gems a publisher is attached to, so the preflight cannot confirm that the publisher belongs to this gem, or that RubyGems would accept the package.

On GitHub Actions, the preflight also checks that the job's token can push the release. `git push --dry-run` to the default branch fails without `contents: write`; GitHub requires push access to start a push, and a dry run sends no objects and changes no refs. It then reads the [repository rules](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-rulesets/about-rulesets) that apply to the default branch and to the `vVERSION` release tag. Branch rules requiring pull requests, status checks, signed commits, deployments, a merge queue, or restricting updates, and tag rules restricting creation or requiring signatures, fail the preflight unless the ruleset reports that the token can bypass it. Classic branch protection rules are not readable without admin access, so a protected default branch produces a warning instead.

### Dry Run

Set `dry-run: true` to run only the release prerequisites. A separate `preflight` job runs instead of the `release` job, in the same `release` environment, so required reviewers still approve it. It checks out the caller without persisted credentials, installs the bundle, and runs the same [prerequisite checks](#release-prerequisites). It never edits files, commits, tags, pushes, builds, or publishes.
Set `dry-run: true` to run only the release prerequisites. A separate `preflight` job runs instead of the `release` job, in the same `release` environment, so required reviewers still approve it. It checks out the caller, installs the bundle, captures the release context, and runs the same [prerequisite checks](#release-prerequisites). It never edits files, commits, tags, pushes, builds, or publishes.

To dispatch dry runs, add a boolean input to the caller and pass it through:

Expand Down
2 changes: 1 addition & 1 deletion docs/tasks.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,6 @@ The [Detailed Usage example](usage.md#custom-callbacks) commits, builds, tags, p

## Workflow Credentials

`release:workflow:preflight` checks release prerequisites without editing files, pushing, or publishing. With a RubyGems destination it verifies Trusted Publishing through [`Workflow::RubyGemsCredentials#check!`](workflow/ruby_gems_credentials.md#check) with optional `RUBYGEMS_OWNER_ID`; other destinations skip that check. Both Actions interfaces run it in every release after context capture, and the reusable workflow runs only it for [dry runs](actions/release.md#dry-run).
`release:workflow:preflight` checks release prerequisites without editing files, pushing, or publishing. With a RubyGems destination it verifies Trusted Publishing through [`Workflow::RubyGemsCredentials#check!`](workflow/ruby_gems_credentials.md#check) with optional `RUBYGEMS_OWNER_ID`; other destinations skip that check. On GitHub Actions it also checks that the token can push to `DEFAULT_BRANCH` and that no repository rules it cannot bypass would reject the release commit or `vVERSION` tag, using `INPUT_VERSION` or the captured `GEMSPEC_VERSION`; elsewhere it skips that check. Both Actions interfaces run it in every release after context capture, and the reusable workflow runs only it for [dry runs](actions/release.md#dry-run).

`release:workflow:credentials` directly invokes [`Workflow::RubyGemsCredentials`](workflow/ruby_gems_credentials.md) with optional `RUBYGEMS_OWNER_ID`. It remains available for custom RubyGems commands, but neither Actions interface calls a separate authentication task. Normal authentication belongs to `release:publish` through the configured destination.
91 changes: 91 additions & 0 deletions lib/ruby-gem-release/workflow/github_permissions.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
# frozen_string_literal: true

require_relative '../github_api'
require_relative '../source_control/git'

module RubyGemRelease
module Workflow
# Checks that the job's GitHub token can push release commits and tags,
# without sending any objects or changing refs.
class GitHubPermissions
BRANCH_BLOCKERS = %w[pull_request required_status_checks required_signatures update required_deployments merge_queue].freeze
TAG_BLOCKERS = %w[creation required_signatures].freeze
BYPASS = %w[always exempt].freeze

def initialize(branch:, tag: nil, api: GitHubAPI.new, remote: 'origin')
raise ArgumentError, 'a default branch is required to check GitHub permissions' if branch.to_s.empty?

@branch = branch
@tag = tag
@api = api
@remote = remote
end

def check!
check_push!
failures = blocked_branch_rules + blocked_tag_rules
raise "GitHub rules would reject the release push: #{failures.join('; ')}" unless failures.empty?

["Verified GitHub push access to #{@branch}#{" and tag #{@tag}" if @tag}", *warnings]
end

private

def check_push!
SourceControl::Git.command('push', '--dry-run', '--porcelain', @remote, "HEAD:refs/heads/#{@branch}")
rescue RuntimeError => e
raise "GitHub token cannot push to #{@branch}; grant contents: write. #{e.message}"
end

def blocked_branch_rules
rules = Array(@api.get("rules/branches/#{@branch}")).select { |rule| BRANCH_BLOCKERS.include?(rule['type']) }
rules.group_by { |rule| rule['ruleset_id'] }.filter_map do |id, matched|
ruleset = ruleset(id)
blocked(ruleset, id, "branch #{@branch}", matched.map { |rule| rule['type'] }.uniq) unless bypass?(ruleset)
end
end

def blocked_tag_rules
return [] unless @tag

Array(@api.get('rulesets?includes_parents=true&targets=tag')).filter_map do |summary|
ruleset = ruleset(summary['id'])
types = tag_blockers(ruleset)
blocked(ruleset, summary['id'], "tag #{@tag}", types) unless types.empty? || bypass?(ruleset)
end
end

def tag_blockers(ruleset)
return [] unless ruleset && ruleset['enforcement'] == 'active' && matches?(ruleset, "refs/tags/#{@tag}")

Array(ruleset['rules']).map { |rule| rule['type'] } & TAG_BLOCKERS
end

def ruleset(id)
@api.get("rulesets/#{id}?includes_parents=true")
end

def bypass?(ruleset)
ruleset && BYPASS.include?(ruleset['current_user_can_bypass'])
end

def matches?(ruleset, ref)
names = ruleset.dig('conditions', 'ref_name') || {}
included = Array(names['include']).any? { |pattern| pattern == '~ALL' || File.fnmatch?(pattern, ref) }
included && Array(names['exclude']).none? { |pattern| File.fnmatch?(pattern, ref) }
end

def blocked(ruleset, id, ref, types)
name = ruleset && ruleset['name']
"#{ref}: #{name ? "ruleset #{name.inspect}" : "ruleset #{id}"} requires #{types.join(', ')}"
end

def warnings
branch = @api.get("branches/#{@branch}")
return [] unless branch.is_a?(Hash) && branch['protected']

["Warning: #{@branch} has branch protection; its push restrictions are not readable without admin access, so confirm the release token may push to it"]
end
end
end
end
18 changes: 17 additions & 1 deletion lib/ruby-gem-release/workflow/preflight.rb
Original file line number Diff line number Diff line change
@@ -1,24 +1,40 @@
# frozen_string_literal: true

require_relative '../execution_provider'
require_relative '../execution_provider/github'
require_relative 'ruby_gems_credentials'
require_relative 'github_permissions'

module RubyGemRelease
module Workflow
# Checks release prerequisites without editing files, pushing, or publishing.
class Preflight
def initialize(destination:, provider: ExecutionProvider.current, output: $stdout)
def initialize(destination:, provider: ExecutionProvider.current, output: $stdout, github: nil)
@destination = destination
@provider = provider
@output = output
@github = github
end

def check!
@output.puts(trusted_publishing)
@output.puts(github_permissions)
end

private

def github_permissions
return 'Skipped GitHub permissions: not running on GitHub Actions' unless @github || @provider.is_a?(ExecutionProvider::GitHub)

(@github || GitHubPermissions.new(branch: @provider.fetch('DEFAULT_BRANCH', ''), tag: release_tag,
api: GitHubAPI.new(repository: @provider.fetch('GITHUB_REPOSITORY', nil)))).check!
end

def release_tag
version = [@provider.fetch('INPUT_VERSION', ''), @provider.fetch('GEMSPEC_VERSION', '')].find { |value| !value.empty? }
"v#{version}" if version
end

def trusted_publishing
return 'Skipped RubyGems Trusted Publishing: the destination does not use RubyGems authentication' unless @destination.authentication == 'rubygems'

Expand Down
2 changes: 1 addition & 1 deletion spec/fixtures/github_release_examples.rb
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ def capture3(*command)
endpoint = command.last
raise 'Unexpected artifact discovery' if endpoint.include?('/actions/')
path = File.join(service, 'hosting.json')
data = File.file?(path) ? JSON.parse(File.read(path)) : nil
data = File.file?(path) && endpoint.include?('/releases/') ? JSON.parse(File.read(path)) : nil
code = data ? '200 OK' : '404 Not Found'
return ["HTTP/2.0 " + code + "\\n\\n" + JSON.generate(data), '', Struct.new(:success?).new(true)]
end
Expand Down
68 changes: 68 additions & 0 deletions spec/ruby_gem_release/workflow/git_hub_permissions_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# frozen_string_literal: true

require 'spec_helper'
require 'ruby-gem-release/workflow/github_permissions'

RSpec.describe RubyGemRelease::Workflow::GitHubPermissions do
let(:responses) { {} }
let(:api) { instance_double(RubyGemRelease::GitHubAPI) }
let(:permissions) { described_class.new(branch: 'main', tag: 'v1.2.3', api: api) }

before do
allow(api).to receive(:get) { |path| responses[path] }
allow(RubyGemRelease::SourceControl::Git).to receive(:command).and_return('')
end

def ruleset(id, bypass: 'never', **attributes)
responses["rulesets/#{id}?includes_parents=true"] = { 'id' => id, 'name' => "Rules #{id}", 'current_user_can_bypass' => bypass, **attributes.transform_keys(&:to_s) }
end

it 'verifies push access without sending objects when no rules block the release' do
expect(permissions.check!).to eq(['Verified GitHub push access to main and tag v1.2.3'])
expect(RubyGemRelease::SourceControl::Git).to have_received(:command).with('push', '--dry-run', '--porcelain', 'origin', 'HEAD:refs/heads/main')
end

it 'explains a token without write access' do
allow(RubyGemRelease::SourceControl::Git).to receive(:command).and_raise(RuntimeError, 'Git command failed: Permission denied (403)')
expect { permissions.check! }.to raise_error(/cannot push to main; grant contents: write. Git command failed: Permission denied/)
end

it 'rejects branch rules the token cannot bypass and ignores rules it can bypass or that allow the push', :aggregate_failures do
responses['rules/branches/main'] = [
{ 'type' => 'pull_request', 'ruleset_id' => 1 }, { 'type' => 'required_signatures', 'ruleset_id' => 1 },
{ 'type' => 'required_status_checks', 'ruleset_id' => 2 }, { 'type' => 'deletion', 'ruleset_id' => 3 },
{ 'type' => 'update', 'ruleset_id' => 4 }
]
ruleset(1)
ruleset(2, bypass: 'always')
expect { permissions.check! }.to raise_error(
'GitHub rules would reject the release push: branch main: ruleset "Rules 1" requires pull_request, required_signatures; ' \
'branch main: ruleset 4 requires update'
)
end

it 'rejects active tag rulesets matching the release tag unless bypassed or excluded', :aggregate_failures do
responses['rulesets?includes_parents=true&targets=tag'] = [1, 2, 3, 4, 5].map { |id| { 'id' => id } }
matching = { 'conditions' => { 'ref_name' => { 'include' => ['refs/tags/v*'], 'exclude' => [] } }, 'enforcement' => 'active', 'rules' => [{ 'type' => 'creation' }] }
ruleset(1, **matching)
ruleset(2, **matching, bypass: 'exempt')
ruleset(3, **matching, enforcement: 'evaluate')
ruleset(4, **matching, conditions: { 'ref_name' => { 'include' => ['~ALL'], 'exclude' => ['refs/tags/v1.*'] } })
ruleset(5, **matching, rules: [{ 'type' => 'deletion' }])
expect { permissions.check! }.to raise_error('GitHub rules would reject the release push: tag v1.2.3: ruleset "Rules 1" requires creation')
end

it 'skips tag rules when the release tag is unknown' do
expect(described_class.new(branch: 'main', api: api).check!).to eq(['Verified GitHub push access to main'])
expect(api).not_to have_received(:get).with('rulesets?includes_parents=true&targets=tag')
end

it 'warns about branch protection it cannot inspect' do
responses['branches/main'] = { 'name' => 'main', 'protected' => true }
expect(permissions.check!.last).to start_with('Warning: main has branch protection')
end

it 'requires a default branch' do
expect { described_class.new(branch: '', api: api) }.to raise_error(ArgumentError, /default branch/)
end
end
Loading
Loading