From 9a27c3c173c1f9435072f49c16b464c766ec8dc1 Mon Sep 17 00:00:00 2001 From: "Daniel (dB.) Doubrovkine" Date: Fri, 20 Nov 2026 17:47:12 -0500 Subject: [PATCH] Check RubyGems Trusted Publishing before every release Add RubyGemsCredentials#check!, which performs the real OIDC token request and exchange, verifies push_rubygem scope, and reports the matched repository, workflow, and environment claims without exporting the short-lived credential. Rejected exchanges now name those claims. A Workflow::Preflight runner and release:workflow:preflight task run the check, skipping it for non-RubyGems destinations. Both Actions interfaces run it after context capture, before validation, edits, or publication, so a missing publisher or id-token permission fails before anything is pushed or published. The reusable workflow's dry-run input runs only the preflight in the release environment; the self-release caller passes it through. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011Gr21hZDQo5axDMuFgzL6s --- .github/workflows/publish.yml | 5 ++ .github/workflows/release.yml | 32 +++++++++ CHANGELOG.md | 1 + README.md | 2 + RELEASING.md | 2 +- action.yml | 6 ++ docs/actions/action.md | 2 + docs/actions/release.md | 66 ++++++++++++++----- docs/tasks.md | 2 + docs/workflow/ruby_gems_credentials.md | 6 ++ lib/ruby-gem-release/tasks.rb | 8 +++ lib/ruby-gem-release/workflow/preflight.rb | 31 +++++++++ .../workflow/ruby_gems_credentials.rb | 44 +++++++++++-- .../workflow/preflight_spec.rb | 34 ++++++++++ .../workflow/ruby_gems_credentials_spec.rb | 50 ++++++++++++++ spec/workflow_interfaces_spec.rb | 25 +++++++ 16 files changed, 290 insertions(+), 26 deletions(-) create mode 100644 lib/ruby-gem-release/workflow/preflight.rb create mode 100644 spec/ruby_gem_release/workflow/preflight_spec.rb diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index ea44954..48a9365 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -7,6 +7,10 @@ on: description: Optional release version overriding the checked-in version. type: string required: false + dry-run: + description: Check release prerequisites without editing files, pushing, or publishing. + type: boolean + default: false permissions: contents: write @@ -20,3 +24,4 @@ jobs: version: ${{ inputs.version }} timezone: America/New_York rubygems-owner: ${{ vars.RUBYGEMS_OWNER_ID }} + dry-run: ${{ inputs.dry-run }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 51f31e6..f984734 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -64,13 +64,40 @@ on: description: Command to run after a release job failure. type: string default: bundle exec rake release:failure + dry-run: + description: Check release prerequisites, such as RubyGems Trusted Publishing, without editing files, pushing, or publishing. + type: boolean + default: false concurrency: group: ruby-gem-release-${{ github.repository }} cancel-in-progress: false jobs: + preflight: + if: ${{ inputs.dry-run }} + runs-on: ubuntu-latest + environment: release + env: + DEFAULT_BRANCH: ${{ github.event.repository.default_branch }} + RUBYGEMS_OWNER_ID: ${{ inputs.rubygems-owner }} + steps: + - uses: actions/checkout@v7 + id: checkout + with: + persist-credentials: false + - uses: ruby/setup-ruby@v1 + id: setup_ruby + with: + ruby-version: ${{ inputs.ruby-version }} + bundler-cache: true + - name: Check Release Prerequisites + id: check_release_prerequisites + env: + RELEASE_STEP_ID: check_release_prerequisites + run: bundle exec rake release:workflow:preflight release: + if: ${{ !inputs.dry-run }} runs-on: ubuntu-latest environment: release env: @@ -105,6 +132,11 @@ jobs: env: RELEASE_STEP_ID: capture_release_context run: bundle exec rake release:workflow:capture + - name: Check Release Prerequisites + id: check_release_prerequisites + env: + RELEASE_STEP_ID: check_release_prerequisites + run: bundle exec rake release:workflow:preflight - name: Validate Release id: validate_release env: diff --git a/CHANGELOG.md b/CHANGELOG.md index 1ab56df..5b10cd4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ - [#80](https://github.com/dblock/ruby-gem-release/pull/80): Skip posting empty Danger report comments - [@dblock](https://github.com/dblock). - [#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). - Your contribution here. ## 0.7.0 (2026/11/20) diff --git a/README.md b/README.md index 280f756..68637ef 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,8 @@ gh api --method PUT repos/{owner}/{repo}/environments/release For a new gem, open the [pending trusted publishers page](https://rubygems.org/profile/oidc/pending_trusted_publishers). For an existing gem, open your existing gem's **Trusted publishers** page (e.g. `https://rubygems.org/gems/example/trusted_publishers`). Create a [trusted publisher](https://guides.rubygems.org/trusted-publishing/#using-reusable-workflows). Set the repository fields to your gem's repository, the workflow filename to `release.yml`, and the environment to `release`. Set the separate workflow repository fields to `dblock` and `ruby-gem-release`; these identify the reusable workflow RubyGems verifies in the OIDC token. +To verify this setup without releasing, dispatch a [dry run](docs/actions/release.md#dry-run). + Collaborators with write access can dispatch releases after this setup, without repository admin access or their own RubyGems credentials. Creating the environment alone does not restrict publication. Configure [required maintainer approval and deployment branches](RELEASING.md#maintainer-approved-publication) to control who approves publication. ### 4. Make a Release diff --git a/RELEASING.md b/RELEASING.md index 55aaa08..d02fa7c 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -40,7 +40,7 @@ bundle exec rake build The manual **Release** caller is [`.github/workflows/publish.yml`](.github/workflows/publish.yml). Merges and schedules do not publish. It uses Ruby 4.0, the root Rakefile, and `America/New_York` for release dates and Git timestamp offsets. -Verify the existing RubyGems trusted publisher before dispatch. The caller passes the non-secret `RUBYGEMS_OWNER_ID` repository variable when set; this identifies an account, not an API key. Pending publishers need it for first publication. +Verify the existing RubyGems trusted publisher before dispatch with a [dry run](docs/actions/release.md#dry-run), which exchanges credentials without releasing: `gh workflow run publish.yml --ref master -f dry-run=true`. The caller passes the non-secret `RUBYGEMS_OWNER_ID` repository variable when set; this identifies an account, not an API key. Pending publishers need it for first publication. Only after explicit authorization, successful validation, and confirmed setup: diff --git a/action.yml b/action.yml index 9b506e6..fac49f1 100644 --- a/action.yml +++ b/action.yml @@ -96,6 +96,12 @@ runs: env: RELEASE_STEP_ID: capture_release_context run: bundle exec rake release:workflow:capture + - name: Check Release Prerequisites + id: check_release_prerequisites + shell: bash + env: + RELEASE_STEP_ID: check_release_prerequisites + run: bundle exec rake release:workflow:preflight - name: Validate Release id: validate_release shell: bash diff --git a/docs/actions/action.md b/docs/actions/action.md index f535bf9..db1a32d 100644 --- a/docs/actions/action.md +++ b/docs/actions/action.md @@ -68,6 +68,8 @@ 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. + 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. ## Release and Recovery diff --git a/docs/actions/release.md b/docs/actions/release.md index 463ec2b..978c66d 100644 --- a/docs/actions/release.md +++ b/docs/actions/release.md @@ -8,27 +8,57 @@ For a step-based interface with caller-owned job settings, see the [Composite Ac Set these under the calling job's `with:` mapping. Only `ruby-version` is required. -| Input | Type | Default | Behavior | -| --- | --- | --- | --- | -| `ruby-version` | String | Required | Ruby version used for validation and building. | -| `version` | String | Empty | Selected numeric `MAJOR.MINOR.PATCH` release version, without leading zeros. Overrides the checked-in version in standard preparation. | -| `gemspec` | String | Empty | Specification path, defaulting to the only root gemspec. Missing or ambiguous specifications fail. | -| `rubygems-owner` | String | Empty | Numeric RubyGems account ID required for a new gem's pending trusted publisher to create it. | -| `timezone` | String | `UTC` | Installed timezone identifier for the release calendar date and Git timestamp offsets. | -| `prepare-artifacts` | String | Empty | Trusted command preparing explicitly selected input archives after setup, before capture. | -| `artifacts` | String | Empty | Additional newline-separated artifact paths preserved before publication, alongside default paths. | -| `validate` | String | `bundle exec rake release:validate` | Check release preconditions before edits; exit nonzero on failure. | -| `prepare` | String | `bundle exec rake release:prepare` | Prepare release files before version resolution and testing. | -| `test` | String | `bundle exec rake` | Test prepared release files before publication. | -| `publish` | String | `bundle exec rake release:publish` | Commit, build, tag, publish to RubyGems, push atomically, and create a GitHub Release through the configured callback. | -| `bump` | String | `bundle exec rake release:bump` | Prepare, commit, and push the next development iteration through the configured callback. | -| `success` | String | `bundle exec rake release:success` | Run after publication and the next development iteration succeed. | -| `failure` | String | `bundle exec rake release:failure` | Run after a release job failure, after Ruby setup. | -| `git-user-name` | String | `github-actions[bot]` | Checkout-local author name for release and next development iteration commits. | -| `git-user-email` | String | `github-actions[bot]@users.noreply.github.com` | Checkout-local author email for release and next development iteration commits. | +| Input | Type | Default | Behavior | +| --- | --- | --- | --- | +| `ruby-version` | String | Required | Ruby version used for validation and building. | +| `version` | String | Empty | Selected numeric `MAJOR.MINOR.PATCH` release version, without leading zeros. Overrides the checked-in version in standard preparation. | +| `gemspec` | String | Empty | Specification path, defaulting to the only root gemspec. Missing or ambiguous specifications fail. | +| `rubygems-owner` | String | Empty | Numeric RubyGems account ID required for a new gem's pending trusted publisher to create it. | +| `timezone` | String | `UTC` | Installed timezone identifier for the release calendar date and Git timestamp offsets. | +| `prepare-artifacts` | String | Empty | Trusted command preparing explicitly selected input archives after setup, before capture. | +| `artifacts` | String | Empty | Additional newline-separated artifact paths preserved before publication, alongside default paths. | +| `validate` | String | `bundle exec rake release:validate` | Check release preconditions before edits; exit nonzero on failure. | +| `prepare` | String | `bundle exec rake release:prepare` | Prepare release files before version resolution and testing. | +| `test` | String | `bundle exec rake` | Test prepared release files before publication. | +| `publish` | String | `bundle exec rake release:publish` | Commit, build, tag, publish to RubyGems, push atomically, and create a GitHub Release through the configured callback. | +| `bump` | String | `bundle exec rake release:bump` | Prepare, commit, and push the next development iteration through the configured callback. | +| `success` | String | `bundle exec rake release:success` | Run after publication and the next development iteration succeed. | +| `failure` | String | `bundle exec rake release:failure` | Run after a release job failure, after Ruby setup. | +| `git-user-name` | String | `github-actions[bot]` | Checkout-local author name for release and next development iteration commits. | +| `git-user-email` | String | `github-actions[bot]@users.noreply.github.com` | Checkout-local author email for release and next development iteration commits. | +| `dry-run` | Boolean | `false` | Check release prerequisites, such as RubyGems Trusted Publishing, without editing files, pushing, or publishing. See [Dry Run](#dry-run). | Identity values must be nonempty and contain no line breaks. They change commit attribution, not authentication or push permissions. +### Release Prerequisites + +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. + +### 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. + +To dispatch dry runs, add a boolean input to the caller and pass it through: + +```yaml +on: + workflow_dispatch: + inputs: + dry-run: + description: Check release prerequisites without releasing. + type: boolean + default: false + +jobs: + release: + uses: dblock/ruby-gem-release/.github/workflows/release.yml@v0.7.0 + with: + ruby-version: '3.3' + dry-run: ${{ inputs.dry-run }} +``` + +Then run `gh workflow run release.yml -f dry-run=true`. + ### Release Validation Validation runs after context capture, before preparation edits. Empty pending notes fail unless the selected release already has a changelog heading, allowing repetition. Malformed content also fails. With no changelog, validation passes. Custom changelog objects implement `pending?` and `released?(version)` or supply a `validate:` callback. diff --git a/docs/tasks.md b/docs/tasks.md index 0fafe42..64ed901 100644 --- a/docs/tasks.md +++ b/docs/tasks.md @@ -62,4 +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: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. diff --git a/docs/workflow/ruby_gems_credentials.md b/docs/workflow/ruby_gems_credentials.md index 9369491..12ed6de 100644 --- a/docs/workflow/ruby_gems_credentials.md +++ b/docs/workflow/ruby_gems_credentials.md @@ -14,6 +14,12 @@ For first publication, find the ID on your Pending Trusted Publishers page. The The direct task `release:workflow:credentials` remains available for custom commands and reads optional `RUBYGEMS_OWNER_ID` through its configured provider. GitHub Actions supplies `ACTIONS_ID_TOKEN_REQUEST_URL`, `ACTIONS_ID_TOKEN_REQUEST_TOKEN`, and `GITHUB_ENV`; the caller must grant `id-token: write`. Another provider must supply its own identity-token acquisition and export behavior; this does not add another platform's Trusted Publishing support. +## Check + +`check!` performs the same token request and exchange as `configure!`, masks both credentials, and returns the token's `repository`, `job_workflow_ref`, and `environment` claims with the credential's `scopes`, `expires_at`, and asserted `owner` when present. It raises unless the credential grants `push_rubygem`. It exports nothing and discards the credential, which expires after 15 minutes. RubyGems does not report the publisher's gems, so a successful check does not prove that the publisher is attached to a particular gem. + +A rejected exchange from either method names the decoded `repository`, `job_workflow_ref`, and `environment` claims RubyGems matched against, without the token or response body. A token whose claims cannot be decoded produces the generic message. + ## Custom Publication Commands Authentication is environment-only: the helper neither creates nor modifies `~/.gem/credentials`. This differs from the replaced `rubygems/configure-rubygems-credentials` action, which also wrote that file. Existing credential files are left untouched. diff --git a/lib/ruby-gem-release/tasks.rb b/lib/ruby-gem-release/tasks.rb index 6fb5989..f4ddc98 100644 --- a/lib/ruby-gem-release/tasks.rb +++ b/lib/ruby-gem-release/tasks.rb @@ -8,6 +8,7 @@ require_relative 'workflow/environment' require_relative 'workflow/failure' require_relative 'workflow/ruby_gems_credentials' +require_relative 'workflow/preflight' require_relative 'destination/ruby_gems' module RubyGemRelease @@ -98,6 +99,7 @@ def install_workflow_tasks namespace :workflow do install_workflow_context_tasks task(:failure_phase) { Workflow::Failure.phase!(provider: @provider) } + install_preflight_task task(:credentials) do with_failure_capture('release:workflow:credentials') do Workflow::RubyGemsCredentials.new(owner: @provider.fetch('RUBYGEMS_OWNER_ID', ''), provider: @provider).configure! @@ -106,6 +108,12 @@ def install_workflow_tasks end end + def install_preflight_task + task(:preflight) do + with_failure_capture('release:workflow:preflight') { Workflow::Preflight.new(destination: @destination, provider: @provider).check! } + end + end + def install_workflow_context_tasks install_checkpoint_task install_capture_task diff --git a/lib/ruby-gem-release/workflow/preflight.rb b/lib/ruby-gem-release/workflow/preflight.rb new file mode 100644 index 0000000..3678f1b --- /dev/null +++ b/lib/ruby-gem-release/workflow/preflight.rb @@ -0,0 +1,31 @@ +# frozen_string_literal: true + +require_relative '../execution_provider' +require_relative 'ruby_gems_credentials' + +module RubyGemRelease + module Workflow + # Checks release prerequisites without editing files, pushing, or publishing. + class Preflight + def initialize(destination:, provider: ExecutionProvider.current, output: $stdout) + @destination = destination + @provider = provider + @output = output + end + + def check! + @output.puts(trusted_publishing) + end + + private + + def trusted_publishing + return 'Skipped RubyGems Trusted Publishing: the destination does not use RubyGems authentication' unless @destination.authentication == 'rubygems' + + summary = RubyGemsCredentials.new(owner: @provider.fetch('RUBYGEMS_OWNER_ID', ''), provider: @provider).check! + details = summary.except('scopes').map { |name, value| "#{name} #{value}" } + "Verified RubyGems Trusted Publishing: #{[*details, "scopes #{summary.fetch('scopes').join(', ')}"].join('; ')}" + end + end + end +end diff --git a/lib/ruby-gem-release/workflow/ruby_gems_credentials.rb b/lib/ruby-gem-release/workflow/ruby_gems_credentials.rb index ed3cde0..7db275e 100644 --- a/lib/ruby-gem-release/workflow/ruby_gems_credentials.rb +++ b/lib/ruby-gem-release/workflow/ruby_gems_credentials.rb @@ -15,17 +15,41 @@ def initialize(owner: nil, provider: ExecutionProvider.current) @provider = provider end + CLAIMS = %w[repository job_workflow_ref environment].freeze + def configure! + key, = exchange! + @provider.export(%w[RUBYGEMS_API_KEY BUNDLE_GEM__PUSH_KEY GEM_HOST_API_KEY].to_h { |name| [name, key] }) + end + + def check! + _key, body, claims = exchange! + scopes = body['scopes'] + raise 'Trusted publisher credential does not grant push_rubygem' unless scopes.is_a?(Array) && scopes.include?('push_rubygem') + + claims.merge('scopes' => scopes, 'expires_at' => body['expires_at'], 'owner' => body['owner']).compact + end + + private + + def exchange! token = @provider.oidc_token(audience: 'rubygems.org') @provider.mask(token) - key = exchange_token(token) + claims = token_claims(token) + body = exchange_token(token, claims) + key = credential(body, 'rubygems_api_key') @provider.mask(key) - @provider.export(%w[RUBYGEMS_API_KEY BUNDLE_GEM__PUSH_KEY GEM_HOST_API_KEY].to_h { |name| [name, key] }) + [key, body, claims] end - private + def token_claims(token) + payload = JSON.parse(token.split('.')[1].to_s.tr('-_', '+/').unpack1('m')) + payload.is_a?(Hash) ? payload.slice(*CLAIMS).select { |_name, value| value.is_a?(String) && !value.match?(/[\r\n]/) } : {} + rescue JSON::ParserError + {} + end - def exchange_token(token) + def exchange_token(token, claims) uri = URI('https://rubygems.org/api/v1/oidc/trusted_publisher/exchange_token') request = Net::HTTP::Post.new(uri) request['Content-Type'] = 'application/json' @@ -33,20 +57,26 @@ def exchange_token(token) body = { jwt: token } body[:owner] = @owner unless @owner.empty? request.body = JSON.generate(body) - credential(response(uri, request), 'rubygems_api_key') + response(uri, request, claims) end - def response(uri, request) + def response(uri, request, claims) result = Net::HTTP.start(uri.host, uri.port, use_ssl: true, open_timeout: 10, read_timeout: 30, max_retries: 0) do |http| http.request(request) end - raise "Credential request failed (HTTP #{result.code}); verify trusted publisher configuration and owner ID if supplied" unless result.is_a?(Net::HTTPSuccess) + raise "Credential request failed (HTTP #{result.code}); #{publisher_hint(claims)}" unless result.is_a?(Net::HTTPSuccess) JSON.parse(result.body) rescue JSON::ParserError raise 'Credential response was not valid JSON' end + def publisher_hint(claims) + expected = claims.map { |name, value| "#{name} #{value}" }.join(', ') + hint = 'verify trusted publisher configuration and owner ID if supplied' + expected.empty? ? hint : "#{hint}; the token presented #{expected}" + end + def credential(body, name) value = body[name] if body.is_a?(Hash) raise 'Credential response did not contain a valid token' unless value.is_a?(String) && !value.empty? && !value.match?(/[\r\n]/) diff --git a/spec/ruby_gem_release/workflow/preflight_spec.rb b/spec/ruby_gem_release/workflow/preflight_spec.rb new file mode 100644 index 0000000..7fd466a --- /dev/null +++ b/spec/ruby_gem_release/workflow/preflight_spec.rb @@ -0,0 +1,34 @@ +# frozen_string_literal: true + +require 'spec_helper' +require 'stringio' +require 'ruby-gem-release/workflow/preflight' +require 'ruby-gem-release/destination/ruby_gems' + +RSpec.describe RubyGemRelease::Workflow::Preflight do + let(:output) { StringIO.new } + let(:provider) { RubyGemRelease::ExecutionProvider.new(environment: { 'RUBYGEMS_OWNER_ID' => '123' }) } + let(:credentials) { instance_double(RubyGemRelease::Workflow::RubyGemsCredentials) } + + it 'verifies RubyGems Trusted Publishing with the configured owner and reports what matched' do + allow(RubyGemRelease::Workflow::RubyGemsCredentials).to receive(:new).with(owner: '123', provider: provider).and_return(credentials) + allow(credentials).to receive(:check!).and_return('repository' => 'owner/example', 'environment' => 'release', 'scopes' => ['push_rubygem']) + described_class.new(destination: RubyGemRelease::Destination::RubyGems.new, provider: provider, output: output).check! + expect(output.string).to eq("Verified RubyGems Trusted Publishing: repository owner/example; environment release; scopes push_rubygem\n") + end + + it 'skips the check for destinations without RubyGems authentication' do + allow(RubyGemRelease::Workflow::RubyGemsCredentials).to receive(:new) + described_class.new(destination: RubyGemRelease::Destination.new, provider: provider, output: output).check! + expect(output.string).to eq("Skipped RubyGems Trusted Publishing: the destination does not use RubyGems authentication\n") + expect(RubyGemRelease::Workflow::RubyGemsCredentials).not_to have_received(:new) + end + + it 'propagates a failed check' do + allow(RubyGemRelease::Workflow::RubyGemsCredentials).to receive(:new).and_return(credentials) + allow(credentials).to receive(:check!).and_raise('Credential request failed (HTTP 404)') + expect { described_class.new(destination: RubyGemRelease::Destination::RubyGems.new, provider: provider, output: output).check! } + .to raise_error(/HTTP 404/) + expect(output.string).to eq('') + end +end diff --git a/spec/ruby_gem_release/workflow/ruby_gems_credentials_spec.rb b/spec/ruby_gem_release/workflow/ruby_gems_credentials_spec.rb index aa6643d..eaed261 100644 --- a/spec/ruby_gem_release/workflow/ruby_gems_credentials_spec.rb +++ b/spec/ruby_gem_release/workflow/ruby_gems_credentials_spec.rb @@ -96,6 +96,12 @@ def success(body) expect(File).not_to exist(ENV.fetch('GITHUB_ENV')) end + it 'rejects a non-JSON exchange response without exporting credentials', :aggregate_failures do + responses[1] = Net::HTTPOK.new('1.1', '200', 'OK').tap { |result| allow(result).to receive(:body).and_return('') } + expect { described_class.new.configure! }.to raise_error('Credential response was not valid JSON') + expect(File).not_to exist(ENV.fetch('GITHUB_ENV')) + end + it 'does not export credentials when the exchange is rejected', :aggregate_failures do responses[1] = Net::HTTPForbidden.new('1.1', '403', 'Forbidden') expect { described_class.new(owner: '123').configure! }.to raise_error(/HTTP 403/) @@ -114,4 +120,48 @@ def success(body) expect(values).to include('GEM_HOST_API_KEY' => 'custom-api-key') expect(File).not_to exist(ENV.fetch('GITHUB_ENV')) end + + describe '#check!' do + let(:claims) do + { 'repository' => 'owner/example', 'job_workflow_ref' => 'dblock/ruby-gem-release/.github/workflows/release.yml@refs/tags/v0.8.0', + 'environment' => 'release', 'sub' => 'repo:owner/example:environment:release' } + end + let(:jwt) { ['header', [JSON.generate(claims)].pack('m0').tr('+/', '-_').delete('='), 'signature'].join('.') } + let(:responses) do + [success('value' => jwt), success('rubygems_api_key' => 'test-api-key', 'scopes' => ['push_rubygem'], 'expires_at' => '2026-11-20T20:15:00Z')] + end + + it 'exchanges and masks credentials, reports the matched claims, and exports nothing', :aggregate_failures do + summary = nil + expect { summary = described_class.new.check! }.to output("::add-mask::#{jwt}\n::add-mask::test-api-key\n").to_stdout + expect(summary).to eq(claims.except('sub').merge('scopes' => ['push_rubygem'], 'expires_at' => '2026-11-20T20:15:00Z')) + expect(requests.last.path).to eq('/api/v1/oidc/trusted_publisher/exchange_token') + expect(File).not_to exist(ENV.fetch('GITHUB_ENV')) + expect(ENV).not_to include('GEM_HOST_API_KEY') + end + + it 'reports the asserted owner for a pending trusted publisher' do + responses[1] = success('rubygems_api_key' => 'test-api-key', 'scopes' => ['push_rubygem'], 'owner' => 'maintainer') + expect(described_class.new(owner: '123').check!).to include('owner' => 'maintainer') + expect(JSON.parse(requests.last.body)).to include('owner' => '123') + end + + it 'rejects a credential without push access' do + responses[1] = success('rubygems_api_key' => 'test-api-key', 'scopes' => ['show_dashboard']) + expect { described_class.new.check! }.to raise_error(/does not grant push_rubygem/) + end + + it 'names the token claims RubyGems matched against when no trusted publisher accepts them' do + responses[1] = Net::HTTPNotFound.new('1.1', '404', 'Not Found') + expect { described_class.new.check! }.to raise_error( + 'Credential request failed (HTTP 404); verify trusted publisher configuration and owner ID if supplied; the token presented ' \ + 'repository owner/example, job_workflow_ref dblock/ruby-gem-release/.github/workflows/release.yml@refs/tags/v0.8.0, environment release' + ) + end + + it 'omits claims it cannot decode from the failure' do + responses.replace([success('value' => 'opaque-token'), Net::HTTPNotFound.new('1.1', '404', 'Not Found')]) + expect { described_class.new.check! }.to raise_error('Credential request failed (HTTP 404); verify trusted publisher configuration and owner ID if supplied') + end + end end diff --git a/spec/workflow_interfaces_spec.rb b/spec/workflow_interfaces_spec.rb index 2187b2a..b46db9f 100644 --- a/spec/workflow_interfaces_spec.rb +++ b/spec/workflow_interfaces_spec.rb @@ -21,6 +21,15 @@ end end + it 'checks release prerequisites after capture, before validation, edits, or publication' do + preflight = steps.find { |step| step['id'] == 'check_release_prerequisites' } + expect(preflight.fetch('run')).to eq('bundle exec rake release:workflow:preflight') + expect(preflight.dig('env', 'RELEASE_STEP_ID')).to eq('check_release_prerequisites') + expect(preflight.fetch('if', '${{ success() }}')).to eq('${{ success() }}') + expect(steps.index(preflight)).to be > steps.index { |step| step['id'] == 'capture_release_context' } + expect(steps.index(preflight)).to be < steps.index { |step| step['id'] == 'validate_release' } + end + it 'transports enclosing step identities and observed history to configurable commands' do steps.select { |step| step.dig('env', 'RELEASE_COMMAND') }.each do |step| expect(step.dig('env', 'RELEASE_STEP_ID')).to eq(step.fetch('id')) @@ -119,6 +128,22 @@ def run_step(id, directory:, command: '') it 'passes the configured timezone to the release job' do expect(workflow.dig('jobs', 'release', 'env', 'TZ')).to eq('${{ inputs.timezone }}') end + + it 'runs only the prerequisite checks in the release environment for a dry run', :aggregate_failures do + expect(workflow.dig(true, 'workflow_call', 'inputs', 'dry-run')).to include('type' => 'boolean', 'default' => false) + expect(workflow.dig('jobs', 'release', 'if')).to eq('${{ !inputs.dry-run }}') + preflight = workflow.dig('jobs', 'preflight') + expect(preflight).to include('if' => '${{ inputs.dry-run }}', 'environment' => 'release') + expect(preflight.dig('env', 'RUBYGEMS_OWNER_ID')).to eq('${{ inputs.rubygems-owner }}') + expect(preflight.fetch('steps').map { |step| step['run'] }.compact).to eq(['bundle exec rake release:workflow:preflight']) + expect(preflight.fetch('steps').first.dig('with', 'persist-credentials')).to be(false) + end + + it 'lets this repository dispatch a dry run of its own release' do + caller = YAML.load_file('.github/workflows/publish.yml') + expect(caller.dig(true, 'workflow_dispatch', 'inputs', 'dry-run')).to include('type' => 'boolean', 'default' => false) + expect(caller.dig('jobs', 'release', 'with', 'dry-run')).to eq('${{ inputs.dry-run }}') + end end context 'with the composite action' do