From 699f4d7f9e7d069d8f15c397d50461044a15dec8 Mon Sep 17 00:00:00 2001 From: "Daniel (dB.) Doubrovkine" Date: Fri, 20 Nov 2026 16:33:44 -0500 Subject: [PATCH] Publish from a job that runs no project code Add an opt-in isolated reusable workflow. A read-only build job runs the project's capture, validation, preparation, tests, and checkpoint, then `release:workflow:seal` commits the next development iteration locally and preserves a Git bundle and `publication.json` handoff with the gem. An environment-gated publish job checks out the library at the reusable workflow's own commit and publishes with plain Ruby, never loading the project's bundle, Rakefile, or gemspec. It verifies the handoff against the dispatched commit, then pushes the release commit before the gem, so a branch that rejects the release token fails before publication. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011Gr21j6KD4oksnhmZ5u3pr --- .github/actionlint.yaml | 7 + .github/workflows/isolated-release.yml | 167 +++++++++++++ .spellcheck.txt | 2 + AGENTS.md | 2 +- CHANGELOG.md | 1 + DESIGN.md | 2 + README.md | 1 + docs/actions/isolated_release.md | 69 ++++++ docs/actions/release.md | 2 +- docs/testing.md | 2 + .../.github/workflows/isolated-release.yml | 27 +++ .../hosting/github_release.rb | 2 + lib/ruby-gem-release/rspec/project.rb | 33 +++ lib/ruby-gem-release/tasks.rb | 11 + .../workflow/isolated_publication.rb | 224 ++++++++++++++++++ lib/ruby-gem-release/workflow/ruby_gem.rb | 23 +- .../workflow/semantic_ruby_gem.rb | 8 + .../consumer/isolated_release_spec.rb | 128 ++++++++++ spec/release_version_spec.rb | 5 +- .../workflow/isolated_publication_spec.rb | 79 ++++++ .../workflow/ruby_gem_spec.rb | 6 + spec/workflow_interfaces_spec.rb | 32 +++ tasks/release_version.rb | 2 +- 23 files changed, 828 insertions(+), 7 deletions(-) create mode 100644 .github/actionlint.yaml create mode 100644 .github/workflows/isolated-release.yml create mode 100644 docs/actions/isolated_release.md create mode 100644 examples/.github/workflows/isolated-release.yml create mode 100644 lib/ruby-gem-release/workflow/isolated_publication.rb create mode 100644 spec/integration/consumer/isolated_release_spec.rb create mode 100644 spec/ruby_gem_release/workflow/isolated_publication_spec.rb diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml new file mode 100644 index 0000000..cadfbcc --- /dev/null +++ b/.github/actionlint.yaml @@ -0,0 +1,7 @@ +# GitHub documents job.workflow_repository and job.workflow_sha, which the isolated +# publish job uses to check out its own library source; actionlint 1.7.12 does not +# know them yet (https://github.com/rhysd/actionlint/pull/707). +paths: + .github/workflows/isolated-release.yml: + ignore: + - 'property "workflow_(repository|sha)" is not defined in object type' diff --git a/.github/workflows/isolated-release.yml b/.github/workflows/isolated-release.yml new file mode 100644 index 0000000..8c6b550 --- /dev/null +++ b/.github/workflows/isolated-release.yml @@ -0,0 +1,167 @@ +name: Isolated Release Gem + +on: + workflow_call: + inputs: + version: + description: Optional release version overriding the checked-in version in the standard workflow. + type: string + gemspec: + description: Optional gemspec path; defaults to the only root gemspec. + type: string + rubygems-owner: + description: Optional RubyGems account ID for first publication with a pending trusted publisher. + type: string + git-user-name: + description: Author name for release and next development iteration commits. + type: string + default: github-actions[bot] + git-user-email: + description: Author email for release and next development iteration commits. + type: string + default: github-actions[bot]@users.noreply.github.com + ruby-version: + description: Ruby version used to validate, build, and publish. + type: string + required: true + timezone: + description: Timezone for release dates and Git timestamps. + type: string + default: UTC + validate: + description: Unprivileged command validating release preconditions; must exit nonzero on failure. + type: string + default: bundle exec rake release:validate + prepare: + description: Unprivileged command to prepare release files; INPUT_VERSION is the selected release version. + type: string + default: bundle exec rake release:prepare + test: + description: Unprivileged command to test the prepared release. + type: string + default: bundle exec rake + +concurrency: + group: ruby-gem-release-${{ github.repository }} + cancel-in-progress: false + +jobs: + build: + runs-on: ubuntu-latest + permissions: + contents: read + outputs: + artifact: ${{ steps.name_release_artifact.outputs.artifact }} + 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 }} + TZ: ${{ inputs.timezone }} + steps: + - uses: actions/checkout@v7 + id: checkout + with: + fetch-depth: 0 + persist-credentials: false + - 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: Validate Release + id: validate_release + env: + RELEASE_COMMAND: ${{ inputs.validate }} + RELEASE_STEP_ID: validate_release + RELEASE_STEPS_JSON: ${{ toJSON(steps) }} + run: bash -euo pipefail -c "$RELEASE_COMMAND" + - name: Prepare Release + id: prepare_release + env: + RELEASE_COMMAND: ${{ inputs.prepare }} + RELEASE_STEP_ID: prepare_release + RELEASE_STEPS_JSON: ${{ toJSON(steps) }} + run: bash -euo pipefail -c "$RELEASE_COMMAND" + - name: Resolve Prepared Version + id: resolve_prepared_version + env: + RELEASE_STEP_ID: resolve_prepared_version + run: bundle exec rake release:workflow:resolve + - name: Test Release + id: test_release + env: + RELEASE_COMMAND: ${{ inputs.test }} + RELEASE_STEP_ID: test_release + RELEASE_STEPS_JSON: ${{ toJSON(steps) }} + run: bash -euo pipefail -c "$RELEASE_COMMAND" + - name: Checkpoint Release + id: checkpoint_release + env: + RELEASE_STEP_ID: checkpoint_release + run: bundle exec rake release:workflow:checkpoint + - name: Seal Release + id: seal_release + env: + RELEASE_STEP_ID: seal_release + run: bundle exec rake release:workflow:seal + - name: Name Release Artifact + id: name_release_artifact + run: echo "artifact=release-gem-$RELEASE_VERSION-${{ github.run_id }}-${{ github.run_attempt }}" >> "$GITHUB_OUTPUT" + - name: Preserve Release Artifacts + id: preserve_release_artifacts + uses: actions/upload-artifact@v7 + with: + name: ${{ steps.name_release_artifact.outputs.artifact }} + path: | + ${{ runner.temp }}/release.gem + ${{ runner.temp }}/release.json + ${{ runner.temp }}/release.bundle + ${{ runner.temp }}/publication.json + if-no-files-found: error + retention-days: 30 + publish: + needs: build + runs-on: ubuntu-latest + environment: release + permissions: + contents: write + id-token: write + env: + DEFAULT_BRANCH: ${{ github.event.repository.default_branch }} + RELEASE_AUTH_MODE: rubygems + RUBYGEMS_OWNER_ID: ${{ inputs.rubygems-owner }} + GH_TOKEN: ${{ github.token }} + steps: + - uses: actions/checkout@v7 + id: checkout + with: + path: source + fetch-depth: 0 + - uses: actions/checkout@v7 + id: checkout_library + with: + repository: ${{ job.workflow_repository }} + ref: ${{ job.workflow_sha }} + path: library + persist-credentials: false + - uses: ruby/setup-ruby@v1 + id: setup_ruby + with: + ruby-version: ${{ inputs.ruby-version }} + bundler: none + - uses: actions/download-artifact@v8 + id: download_release_artifacts + with: + name: ${{ needs.build.outputs.artifact }} + path: ${{ runner.temp }} + - name: Publish Release + id: publish_release + working-directory: source + run: ruby --disable-gems -rrubygems -I ../library/lib -rruby-gem-release/workflow/isolated_publication -e 'RubyGemRelease::Workflow::IsolatedPublication.new.publish!' diff --git a/.spellcheck.txt b/.spellcheck.txt index 7e3b6b9..9f7f57b 100644 --- a/.spellcheck.txt +++ b/.spellcheck.txt @@ -14,6 +14,7 @@ gemspecs Gemfile GitLab GPG +handoff HTTPS idempotence Intridea @@ -48,6 +49,7 @@ rulesets RSpec RuboCop RubyGems +SHA strftime subclasses subprocess diff --git a/AGENTS.md b/AGENTS.md index ea93ca6..a3bd50d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,7 +12,7 @@ Keep orchestration permutations and YAML assertions in focused source specs (`bu Keep semantic releases opt-in. Calculate from reachable released tags, not development versions; persist one immutable decision across processes, preserve it when recording the next version, and never reanalyze during preparation or publication. Preserve manual workflow defaults and publication guards. Semantic consumer fixtures must verify success, publication failure, and empty-release rejection against the installed artifact without real publication. -The root `action.yml` exposes the same Ruby tasks as a composite action. Keep both interfaces consistent without making version-pinned workflows depend on moving action references. Action callers own job permissions, runner, environment, and concurrency. Preserve authentication selection and failure-aware artifact preservation; run installed-artifact consumer CI and `actionlint .github/workflows/*.yml examples/.github/workflows/*.yml` when changing YAML interfaces. +The root `action.yml` exposes the same Ruby tasks as a composite action. Keep both interfaces consistent without making version-pinned workflows depend on moving action references. Action callers own job permissions, runner, environment, and concurrency. Preserve authentication selection and failure-aware artifact preservation; run installed-artifact consumer CI and `actionlint .github/workflows/*.yml examples/.github/workflows/*.yml` when changing YAML interfaces. The isolated workflow's publish job must never install or load the project's bundle, Rakefile, gemspec, or commands; `Workflow::IsolatedPublication` and everything it requires must load with plain `ruby -I lib` and only the standard library. Run `bundle exec rake` locally for specs and RuboCop before every push, and `bundle exec rake build` for package construction when applicable. Danger checks the changelog in PR CI, not as a routine local command. Document user-visible changes in `CHANGELOG.md`, listing entries within each release chronologically and keeping `- Your contribution here.` as the last entry in the next-release section; keep Markdown paragraphs on one source line. diff --git a/CHANGELOG.md b/CHANGELOG.md index 1c39753..3d12235 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ - [#79](https://github.com/dblock/ruby-gem-release/pull/79): Select the next development version part with `next_version: :minor` or `:major` on `Workflow::RubyGem` and `Workflow::SemanticRubyGem` - [@dblock](https://github.com/dblock). - [#80](https://github.com/dblock/ruby-gem-release/pull/80): Skip posting empty Danger report comments - [@dblock](https://github.com/dblock). +- [#81](https://github.com/dblock/ruby-gem-release/pull/81): Add an opt-in isolated reusable workflow that builds and tests without credentials and publishes from a separate environment-gated job that runs no project code, pushing the release commit before the gem - [@dblock](https://github.com/dblock). - Your contribution here. ## 0.7.0 (2026/11/20) diff --git a/DESIGN.md b/DESIGN.md index f593b4d..38529e5 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -28,6 +28,8 @@ The checkpoint task commits prepared edits, builds reproducibly, tags locally, a Every release action must be idempotent for the same checkout and inputs, without recovery flags, artifact discovery, restored context, or a completion journal. Tasks reconcile their own outputs; a fresh workflow uses its current checkout and inputs rather than discovering an older unfinished release. Registry publication and Git pushes cannot be atomic together, so both interfaces preserve artifacts before publication for manual inspection. See [rerunning releases](RELEASING.md#verify-and-recover). +The opt-in isolated workflow runs the same tasks through the checkpoint in a read-only build job, then seals the release: it commits the next development iteration locally and preserves a Git bundle and `publication.json` handoff with the gem. Its environment-gated publish job checks out the library at the reusable workflow's own commit and publishes with plain Ruby, never loading the project's bundle, Rakefile, or gemspec. It verifies the handoff against the dispatched commit, then pushes the release commit, publishes the gem, pushes the tag, creates the hosted release, and pushes the development commit, so a branch that rejects the release token fails before publication. Sealing rejects components and publication-stage hooks the publish job cannot reproduce. See the [isolated workflow reference](docs/actions/isolated_release.md). + Keep both YAML interfaces thin and consistent. The reusable workflow does not depend on a moving composite-action reference: a pinned release must remain independent of later action versions. Composite callers own permissions, runner, environment protection, and concurrency. Commands run with release privileges and must be trusted. ## Preparation and Artifact Guards diff --git a/README.md b/README.md index 280f756..2c4a265 100644 --- a/README.md +++ b/README.md @@ -103,6 +103,7 @@ Replace only what you need. The [standard workflow](docs/workflow/ruby_gem.md) p - **Packages and registries:** Override [package construction](docs/package/ruby_gem.md) or supply a [registry destination](docs/destination.md) independently of hosted releases. - **Release hosting:** Replace or disable [GitHub Release creation](docs/workflow/ruby_gem.md#hosting) without changing package publication or Git operations. - **Execution platforms:** Supply an [execution provider](docs/execution_provider.md) for environment transport, metadata, temporary storage, and authentication services. GitHub Actions is the only built-in external platform; another platform needs its own adapter and pipeline. +- **Isolated publication:** Use the [isolated workflow](docs/actions/isolated_release.md) to build and test without credentials and publish from a separate environment-gated job that runs no project code. - **Actions integration:** Override commands, inputs, and timezone through the [Actions Reference](docs/actions/release.md), or use the [Composite Action](docs/actions/action.md) inside a caller-owned job. - **Testing customizations:** Use optional [RSpec helpers and local publication adapters](docs/testing.md) to verify project-specific release behavior and catch regressions in release-managed files. diff --git a/docs/actions/isolated_release.md b/docs/actions/isolated_release.md new file mode 100644 index 0000000..d3cfdcf --- /dev/null +++ b/docs/actions/isolated_release.md @@ -0,0 +1,69 @@ +# Isolated Release Workflow + +Reference for [`.github/workflows/isolated-release.yml`](../../.github/workflows/isolated-release.yml), an opt-in reusable workflow that keeps publication credentials away from project code. The [standard workflow](release.md) runs everything in one job holding `id-token: write` and `contents: write`, so any gem in the project's development bundle, and any code its tests run, could request a publishing token. The isolated workflow splits the release into two jobs: + +- **Build** runs with `contents: read`, outside the `release` environment. It installs the project bundle and runs capture, validation, preparation, resolution, tests, and the checkpoint exactly as the standard workflow does, then seals the release: it prepares and commits the next development iteration locally, running preparation hooks such as README updates, and preserves the gem, its manifest, a Git bundle with the release tag and both commits, and a `publication.json` handoff as the recovery artifact. +- **Publish** runs in the `release` environment with `id-token: write` and `contents: write`. It checks out the caller at the dispatched commit and this library at the reusable workflow's own commit (`job.workflow_sha`), installs no bundle, and publishes with plain Ruby. Project code, including its Gemfile, Rakefile, and gemspec, never runs while publication credentials are available. + +## Usage + +Add `.github/workflows/release.yml` using the [sample workflow](../../examples/.github/workflows/isolated-release.yml), pinning the reusable workflow by commit SHA: + +```yaml +name: Release + +on: + workflow_dispatch: + inputs: + version: + description: Optional release version overriding the checked-in version. + type: string + required: false + +permissions: + contents: read + +jobs: + release: + uses: dblock/ruby-gem-release/.github/workflows/isolated-release.yml@v0.8.0 + permissions: + contents: write + id-token: write + with: + ruby-version: '3.3' + version: ${{ inputs.version }} +``` + +Configure the RubyGems trusted publisher as described in [Usage](../../README.md#3-enable-trusted-publishing), with workflow filename `isolated-release.yml`: RubyGems matches the filename of the reusable workflow, not the caller's. A trusted publisher for `isolated-release.yml` cannot be used by the single-job workflow. RubyGems accepts any ref of the workflow repository, so pin the `uses:` line to the full commit SHA of a release tag, with the tag in a trailing comment. + +Keep `ruby-gem-release` in your development Gemfile at the same version as the pinned workflow. The build job runs the gem's Rake tasks from your bundle; the publish job runs the library from the workflow commit and rejects a handoff format it does not support. + +## Inputs + +`version`, `gemspec`, `rubygems-owner`, `git-user-name`, `git-user-email`, `ruby-version`, and `timezone` behave as in the [standard workflow](release.md#inputs). The `validate`, `prepare`, and `test` commands run only in the unprivileged build job. There are no `publish`, `bump`, `success`, `failure`, `prepare-artifacts`, or `artifacts` inputs: publication runs no project commands. + +## Requirements + +Sealing fails in the build job, before anything is published, unless the workflow uses the default package, RubyGems destination, Git source control, and either the default GitHub Release hosting for the calling repository or `hosting: nil`. Hooks for `authenticate`, `publish_registry`, `push_release`, `publish_hosted_release`, `push_next`, `success`, or `failure`, and `success:` or `failure:` callbacks, are rejected because the publish job cannot run them. Hooks for earlier stages, including `prepare_release`, `prepare_next`, and `commit_next`, run in the build job. [`Workflow::RubyGem`](../workflow/ruby_gem.md) and [`Workflow::SemanticRubyGem`](../workflow/semantic_ruby_gem.md) are supported; semantic releases carry their generated notes and seal no development iteration unless `bump: true`. + +The [composite action](action.md) has no isolated mode, because a composite action runs inside one caller-owned job. The `job.workflow_*` contexts the publish job uses are unavailable on GitHub Enterprise Server. + +## Publication Order + +The publish job verifies the handoff before any push: the run must be on the default branch, the release commit must have the dispatched commit as its only parent, the tag must be a lightweight tag at the release commit, the development commit must have the release commit as its only parent, and the gem must match its manifest checksum and identity. It then: + +1. Pushes the release commit to the default branch without the tag. A branch rule that rejects the release token fails here, before the gem is published. +2. Publishes the gem to RubyGems, authenticating through Trusted Publishing only if that exact gem is not already published. +3. Pushes the release tag. +4. Creates or updates the GitHub Release with the gem attached. +5. Pushes the next development commit. + +Branch rules must still permit the Actions token to push commits and tags; see [branch permissions](../../RELEASING.md#one-time-setup). If the default branch moves after the build, publication stops with `Default branch advanced; start a new release`. + +## Recovery + +Every publication step reconciles existing state, so **Re-run failed jobs** on the same workflow run resumes from the first incomplete step, reusing the build job's artifact for its 30-day retention. If the release commit was pushed but the gem was not, the branch contains a release commit without a tag until the rerun completes. See [rerunning releases](../../RELEASING.md#verify-and-recover) before starting a new dispatch after a partial publication. + +## Security Notes + +Isolation protects the credential, not the build: a compromised dependency in the build job can still alter the gem or the sealed commits it hands off, and publication verifies their structure, not their contents. Required environment reviewers approve the publish job after the build job and its tests have finished, so reviewers can inspect the build log and preserved artifact before approving. diff --git a/docs/actions/release.md b/docs/actions/release.md index 463ec2b..4d31e53 100644 --- a/docs/actions/release.md +++ b/docs/actions/release.md @@ -2,7 +2,7 @@ Reference for [`.github/workflows/release.yml`](../../.github/workflows/release.yml), invoked with `workflow_call`. See [Usage](../../README.md#usage) for a caller example and [Detailed Usage](../usage.md#configuration) for customization. See [RELEASING.md](../../RELEASING.md#one-time-setup) for branch permissions. Trusted Publishing is required setup in [Usage](../../README.md#3-enable-trusted-publishing). -For a step-based interface with caller-owned job settings, see the [Composite Action](action.md). Both interfaces invoke the same Ruby release tasks; the reusable workflow keeps its own runner, environment, permissions contract, and concurrency group. +For a step-based interface with caller-owned job settings, see the [Composite Action](action.md). Both interfaces invoke the same Ruby release tasks; the reusable workflow keeps its own runner, environment, permissions contract, and concurrency group. To publish from a separate job that runs no project code, see the [Isolated Release Workflow](isolated_release.md). ## Inputs diff --git a/docs/testing.md b/docs/testing.md index 49a6251..ce968fc 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -32,6 +32,8 @@ See the [complete spec](../examples/lifecycle_hooks/spec/release_spec.rb) for al `release!` runs capture, validation, preparation, resolution, checkpoint, publication, development bump, and success in separate Rake processes. Pass `test_task: 'verify_release'` to run a fixture-specific check after resolution; the default skips the project's test suite to avoid recursively running this spec. Use `run_task('release:prepare')` for individual tasks and `git(...)` or `remote_file(ref, path)` to inspect results. +For the [isolated workflow](actions/isolated_release.md), `isolated_release!` runs the build job's tasks through `release:workflow:seal`, then `publish_isolated!` publishes from a fresh clone at the source commit in a separate Ruby process without the project bundle, using the same local adapters. Call `publish_isolated!` again to verify that publication resumes after a failure or repeats without changes. + The child processes retain Ruby/Bundler paths but do not inherit Actions variables, credentials, Git overrides, or outer release state. `project.environment` lets you add explicit fixture inputs. The helper uses the currently loaded release gem and parent bundle. ## Copy Fixture Files diff --git a/examples/.github/workflows/isolated-release.yml b/examples/.github/workflows/isolated-release.yml new file mode 100644 index 0000000..9ecaacf --- /dev/null +++ b/examples/.github/workflows/isolated-release.yml @@ -0,0 +1,27 @@ +name: Release + +on: + workflow_dispatch: + inputs: + version: + description: Optional release version overriding the checked-in version. + type: string + required: false + rubygems-owner: + description: RubyGems account ID for first publication; omit for an existing gem. + type: string + required: false + +permissions: + contents: read + +jobs: + release: + uses: dblock/ruby-gem-release/.github/workflows/isolated-release.yml@v0.8.0 + permissions: + contents: write + id-token: write + with: + ruby-version: '3.3' + version: ${{ inputs.version }} + rubygems-owner: ${{ inputs.rubygems-owner }} diff --git a/lib/ruby-gem-release/hosting/github_release.rb b/lib/ruby-gem-release/hosting/github_release.rb index 197867d..2d47ec9 100644 --- a/lib/ruby-gem-release/hosting/github_release.rb +++ b/lib/ruby-gem-release/hosting/github_release.rb @@ -7,6 +7,8 @@ module RubyGemRelease module Hosting class GitHubRelease + attr_reader :repository, :latest + def initialize(repository: nil, latest: nil) repository ||= ENV.fetch('GITHUB_REPOSITORY', nil) raise ArgumentError, 'repository must be OWNER/REPO' unless repository.nil? || (repository.is_a?(String) && %r{\A[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+\z}.match?(repository)) diff --git a/lib/ruby-gem-release/rspec/project.rb b/lib/ruby-gem-release/rspec/project.rb index ea18ebb..57b4bf7 100644 --- a/lib/ruby-gem-release/rspec/project.rb +++ b/lib/ruby-gem-release/rspec/project.rb @@ -91,6 +91,39 @@ def release!(version: '', test_task: nil) %w[release:workflow:checkpoint release:publish release:bump release:success].each { |name| run_task(name) } end + # Runs the isolated build job's tasks, then publishes from a fresh clone at + # the source commit in a separate Ruby process without the project bundle. + def isolated_release!(version: '', test_task: nil) + @environment['INPUT_VERSION'] = version + %w[release:workflow:capture release:validate release:prepare release:workflow:resolve].each { |name| run_task(name) } + run_task(test_task) if test_task + %w[release:workflow:checkpoint release:workflow:seal].each { |name| run_task(name) } + publish_isolated! + end + + def publish_isolated! + source = File.join(@directory, 'publication') + FileUtils.rm_rf(source) + git('clone', '--quiet', @remote, source) + git('-C', source, 'checkout', '--quiet', '--detach', @environment.fetch('SOURCE_COMMIT')) + environment = @environment.except('BUNDLE_GEMFILE').merge('GITHUB_SHA' => @environment.fetch('SOURCE_COMMIT')) + output, error, status = Open3.capture3(environment, Gem.ruby, '-I', File.expand_path('../..', __dir__), '-e', ISOLATED_PUBLICATION, chdir: source, unsetenv_others: true) + raise "#{output}\n#{error}" unless status.success? + + output + end + + ISOLATED_PUBLICATION = <<~RUBY + require 'ruby-gem-release/workflow/isolated_publication' + require 'ruby-gem-release/rspec/provider' + require 'ruby-gem-release/rspec/publication' + RubyGemRelease::Workflow::IsolatedPublication.new( + provider: RubyGemRelease::RSpec::Provider.new, + destination: RubyGemRelease::RSpec::Destination.new, + hosting: RubyGemRelease::RSpec::Hosting.new + ).publish! + RUBY + private def workflow_source(path) diff --git a/lib/ruby-gem-release/tasks.rb b/lib/ruby-gem-release/tasks.rb index 6fb5989..d77940b 100644 --- a/lib/ruby-gem-release/tasks.rb +++ b/lib/ruby-gem-release/tasks.rb @@ -108,6 +108,7 @@ def install_workflow_tasks def install_workflow_context_tasks install_checkpoint_task + install_seal_task install_capture_task install_resolve_task task(:configure) { with_failure_capture('release:workflow:configure') { Workflow::Environment.new(provider: @provider).configure! } } @@ -134,6 +135,16 @@ def install_resolve_task end end + def install_seal_task + task(:seal) do + with_failure_capture('release:workflow:seal') do + raise 'Workflow must implement seal! for isolated publication' unless @workflow.respond_to?(:seal!) + + @workflow.seal!(context('release:workflow:seal')) + end + end + end + def install_checkpoint_task task(:checkpoint) do with_failure_capture('release:workflow:checkpoint') do diff --git a/lib/ruby-gem-release/workflow/isolated_publication.rb b/lib/ruby-gem-release/workflow/isolated_publication.rb new file mode 100644 index 0000000..0b1c5e7 --- /dev/null +++ b/lib/ruby-gem-release/workflow/isolated_publication.rb @@ -0,0 +1,224 @@ +# frozen_string_literal: true + +require 'date' +require 'fileutils' +require 'json' +require 'open3' +require 'rubygems/name_tuple' +require_relative '../release' +require_relative '../execution_provider' +require_relative '../package/prebuilt' +require_relative '../destination/ruby_gems' +require_relative '../hosting/github_release' + +module RubyGemRelease + module Workflow + # Publishes a release sealed by an unprivileged build job. Loads only the + # standard library and this gem, never the project's bundle or Rakefile, so + # project code does not run while publication credentials are available. + class IsolatedPublication + FORMAT = 1 + FILE = 'publication.json' + PUBLICATION_STAGES = %i[authenticate publish_registry push_release publish_hosted_release push_next success failure].freeze + SHA = /\A[0-9a-f]{40}\z/ + + # Build job: rejects components and hooks the publish job cannot reproduce. + def self.check!(workflow, callbacks:) + check_components!(workflow) + raise ArgumentError, 'isolated publication runs no project success or failure callbacks' if callbacks + + stages = PUBLICATION_STAGES.select { |stage| workflow.hooks?(stage) } + raise ArgumentError, "isolated publication runs no project hooks for #{stages.join(', ')}" unless stages.empty? + end + + def self.check_components!(workflow) + { package: Package::RubyGem, destination: Destination::RubyGems, git: SourceControl::Git }.each do |name, klass| + object = workflow.public_send(name) + raise ArgumentError, "isolated publication requires the default #{name}" unless object.instance_of?(klass) || local_adapter?(object) + end + repository = workflow.provider.fetch('GITHUB_REPOSITORY', nil) + raise ArgumentError, 'isolated publication requires the default GitHub Release hosting or hosting: nil' unless reproducible_hosting?(workflow.hosting, repository) + end + + # The publish job creates releases in the calling repository, which the + # default hosting also selects from GITHUB_REPOSITORY. + def self.reproducible_hosting?(hosting, repository) + hosting.nil? || local_adapter?(hosting) || (hosting.instance_of?(Hosting::GitHubRelease) && [nil, repository].include?(hosting.repository)) + end + + # The RSpec helpers' local adapters stand in for RubyGems and GitHub + # Releases, and the helper's publish process supplies them again. + def self.local_adapter?(object) + defined?(RubyGemRelease::RSpec::Destination) && [RubyGemRelease::RSpec::Destination, RubyGemRelease::RSpec::Hosting].any? { |klass| object.instance_of?(klass) } + end + + # Build job: preserves the release and next development commits and the + # values the publish job needs, alongside the gem built at the checkpoint. + def self.seal!(workflow:, release:, provider:) + workflow.git.write_bundle(release) + path = File.join(provider.directory, FILE) + File.write(path, JSON.generate(handoff(workflow, release, provider))) + path + end + + def self.handoff(workflow, release, provider) + git = workflow.git + { 'format' => FORMAT, 'version' => release.version, 'gemspec_version' => release.gemspec_version, 'date' => release.date.iso8601, + 'notes' => release.notes, 'next_version' => release.next_version, 'branch' => provider.fetch('DEFAULT_BRANCH'), + 'source_commit' => provider.fetch('SOURCE_COMMIT'), 'release_commit' => git.tag_commit(release.version), + 'next_commit' => release.next_version && git.head, 'hosting' => hosting_options(workflow.hosting) } + end + + def self.hosting_options(hosting) + hosting && { 'latest' => hosting.respond_to?(:latest) ? hosting.latest : nil } + end + + def initialize(provider: ExecutionProvider.current, destination: Destination::RubyGems.new, hosting: nil, remote: 'origin') + @provider = provider + @destination = destination + @hosting = hosting + @remote = remote + end + + # Publish job: pushes the release commit before the gem, so a branch that + # rejects the release token fails before anything is published. + def publish! + load_handoff! + verify_source! + push_release_commit! + publish_package! + push_tag! + hosting&.publish!(@release, package: @package) + push_next_commit! + @release + end + + private + + def load_handoff! + @data = JSON.parse(File.read(File.join(directory, FILE))) + raise ArgumentError, 'unsupported isolated publication format' unless @data.is_a?(Hash) && @data['format'] == FORMAT + + @branch = @data.fetch('branch') + @release = Release.new(version: @data.fetch('version'), gemspec_version: @data.fetch('gemspec_version'), date: Date.iso8601(@data.fetch('date')), + next_version: @data['next_version'], notes: @data['notes']) + @package = prebuilt_package + end + + def prebuilt_package + manifest = JSON.parse(File.read(File.join(directory, 'release.json'))) + name, version = manifest.values_at('name', 'version') + platform = manifest.fetch('platform', 'ruby') + raise 'Package manifest does not match the sealed release' unless version == @release.version + + Package::Prebuilt.new(path: named_archive(name, version, platform), sha256: manifest.fetch('sha256'), name: name, version: version, platform: platform) + .tap { |package| package.artifact(@release) } + end + + # Prebuilt packages and hosted assets use the gem's own filename. + def named_archive(name, version, platform) + path = File.join(directory, "#{Gem::NameTuple.new(name, Gem::Version.new(version), platform).full_name}.gem") + FileUtils.cp(File.join(directory, 'release.gem'), path) + path + end + + def verify_source! + verify_dispatch! + import_bundle! + raise 'Release bundle does not contain the sealed commits' unless git('rev-parse', 'refs/ruby-gem-release/sealed') == (next_commit || release_commit) + raise 'Sealed release tag does not point at the release commit' unless git('cat-file', '-t', tag_ref) == 'commit' && git('rev-parse', tag_ref) == release_commit + + verify_parents! + end + + def verify_parents! + raise 'Sealed release commit must have the dispatched commit as its only parent' unless parents(release_commit) == [source_commit] + raise 'Sealed development commit must have the release commit as its only parent' if next_commit && parents(next_commit) != [release_commit] + end + + def verify_dispatch! + commits = @data.values_at('source_commit', 'release_commit', 'next_commit').compact + raise ArgumentError, 'sealed commits must be full SHA-1 object names' unless commits.all? { |commit| SHA.match?(commit) } + raise 'Releases must run from the default branch' unless @branch == @provider.fetch('DEFAULT_BRANCH') && @provider.ref == "refs/heads/#{@branch}" + raise 'Sealed release was not built from the dispatched commit' unless source_commit == @provider.fetch('GITHUB_SHA') + end + + def import_bundle! + bundle = File.join(directory, 'release.bundle') + git('bundle', 'verify', bundle) + git('fetch', '--no-tags', bundle, "+#{tag_ref}:#{tag_ref}", '+HEAD:refs/ruby-gem-release/sealed') + end + + def push_release_commit! + head = remote_head + return if [release_commit, next_commit].include?(head) || ancestor?(release_commit, head) + raise 'Default branch advanced; start a new release' unless head == source_commit + + git('push', @remote, "#{release_commit}:refs/heads/#{@branch}") + end + + def publish_package! + return if @destination.published?(@release, package: @package) + + @destination.authenticate!(provider: @provider) + @destination.publish!(@release, package: @package) + end + + def push_tag! + existing = git('ls-remote', '--tags', @remote, tag_ref, "#{tag_ref}^{}").lines.map(&:split).to_h { |sha, ref| [ref, sha] } + remote = existing["#{tag_ref}^{}"] || existing[tag_ref] + raise 'Remote release tag points at another commit' if remote && remote != release_commit + + git('push', @remote, tag_ref) unless remote + end + + def push_next_commit! + return unless next_commit + + head = remote_head + return if ancestor?(next_commit, head) + raise 'Default branch advanced; start a new release' unless head == release_commit + + git('push', @remote, "#{next_commit}:refs/heads/#{@branch}") + end + + def hosting + return unless @data['hosting'] + + @hosting || Hosting::GitHubRelease.new(latest: @data['hosting']['latest']) + end + + def remote_head + git('fetch', '--no-tags', @remote, "+refs/heads/#{@branch}:refs/remotes/#{@remote}/#{@branch}") + git('rev-parse', "refs/remotes/#{@remote}/#{@branch}") + end + + def parents(commit) + git('rev-list', '--parents', '-n', '1', commit).split.drop(1) + end + + def ancestor?(commit, descendant) + _output, error, status = Open3.capture3('git', 'merge-base', '--is-ancestor', commit, descendant) + raise "Cannot inspect Git ancestry: #{error}" unless [0, 1].include?(status.exitstatus) + + status.success? + end + + def source_commit = @data.fetch('source_commit') + def release_commit = @data.fetch('release_commit') + def next_commit = @data['next_commit'] + def tag_ref = "refs/tags/v#{@release.version}" + + def directory + @provider.directory or raise ArgumentError, 'isolated publication requires a release data directory' + end + + def git(*) + output, error, status = Open3.capture3('git', *) + raise "Git command failed: #{error.strip}\n#{output.strip}" unless status.success? + + output.strip + end + end + end +end diff --git a/lib/ruby-gem-release/workflow/ruby_gem.rb b/lib/ruby-gem-release/workflow/ruby_gem.rb index 9091aba..39d9b47 100644 --- a/lib/ruby-gem-release/workflow/ruby_gem.rb +++ b/lib/ruby-gem-release/workflow/ruby_gem.rb @@ -6,6 +6,7 @@ require_relative '../source_control/git' require_relative '../hosting/github_release' require_relative '../version/interface' +require_relative 'isolated_publication' module RubyGemRelease module Workflow @@ -37,6 +38,15 @@ def environment Environment.new(provider: @provider) end + # Isolated build job: commits the next development iteration locally and + # seals the checkpoint release for a publish job that runs no project code. + def seal!(ctx) + IsolatedPublication.check!(self, callbacks: !(@success || @failure).nil?) + release = next_iteration? ? commit_next_iteration!(ctx).release : ctx.release + ctx.record_next_version!(release.next_version) if release.next_version + IsolatedPublication.seal!(workflow: self, release: release, provider: @provider) + end + private def configure_version!(version, next_version) @@ -98,12 +108,21 @@ def publish(ctx) end def prepare_next(ctx) - next_ctx = stage_next!(ctx) - run_stage(:commit_next, next_ctx) { @git.commit_next!(next_ctx.release) } + next_ctx = commit_next_iteration!(ctx) run_stage(:push_next, next_ctx) { @git.push! } ctx.record_next_version!(next_ctx.release.next_version) end + def next_iteration? + true + end + + def commit_next_iteration!(ctx) + next_ctx = stage_next!(ctx) + run_stage(:commit_next, next_ctx) { @git.commit_next!(next_ctx.release) } + next_ctx + end + def stage_next!(ctx) next_ctx = ctx @git.stage_changes! do diff --git a/lib/ruby-gem-release/workflow/semantic_ruby_gem.rb b/lib/ruby-gem-release/workflow/semantic_ruby_gem.rb index d75fec3..b8d9f5c 100644 --- a/lib/ruby-gem-release/workflow/semantic_ruby_gem.rb +++ b/lib/ruby-gem-release/workflow/semantic_ruby_gem.rb @@ -17,8 +17,16 @@ def initialize(semantic_release: SemanticRelease.new, changelog: Changelog::Gene super(changelog: changelog, **) end + def seal!(ctx) + with_decision(ctx) { super } + end + private + def next_iteration? + @bump + end + def install_callbacks(tasks) tasks.validate { |ctx| validate_with_hooks(ctx) } tasks.prepare { |ctx| prepare_release(ctx) } diff --git a/spec/integration/consumer/isolated_release_spec.rb b/spec/integration/consumer/isolated_release_spec.rb new file mode 100644 index 0000000..88a28a3 --- /dev/null +++ b/spec/integration/consumer/isolated_release_spec.rb @@ -0,0 +1,128 @@ +# frozen_string_literal: true + +require 'spec_helper' +require 'json' +require 'ruby-gem-release/rspec' + +RSpec.describe 'Isolated release publication' do + include RubyGemRelease::RSpec + + let(:gemspec) do + <<~RUBY + require_relative 'lib/example/version' + Gem::Specification.new do |spec| + spec.name = 'example' + spec.version = VERSION + spec.authors = ['Fixture'] + spec.summary = 'Release test fixture' + spec.files = ['lib/example/version.rb', 'README.md'] + end + RUBY + end + + def prepare_project(project, builder: 'ProjectReleaseWorkflow.build') + project.copy_files(path: File.expand_path('../../../examples/lifecycle_hooks', __dir__), files: %w[*.rb README.md]) + project.configure_workflow(require: 'release_workflow', builder: builder) + project.write('example.gemspec', gemspec) + project.write('lib/example/version.rb', "VERSION = '0.1.0'\n") + project.write('CHANGELOG.md', "# Changelog\n\n## [Unreleased]\n\n- A change.\n") + project.commit! + end + + def artifacts(project) + project.environment.fetch('RELEASE_DATA_DIR') + end + + def published?(project) + %w[registry hosting].map { |adapter| File.file?(File.join(artifacts(project), adapter, '0.2.0.gem')) } + end + + def reject_branch_pushes(project) + hook = File.join(project.remote, 'hooks', 'pre-receive') + File.write(hook, "#!/bin/sh\nwhile read old new ref; do [ \"$ref\" = refs/heads/master ] && { echo 'protected branch' >&2; exit 1; }; done\nexit 0\n") + File.chmod(0o755, hook) + hook + end + + it 'publishes the sealed release, then the next development commit, from a separate process' do + with_release_project do |project| + prepare_project(project) + source = project.git('rev-parse', 'HEAD') + + project.isolated_release!(version: '0.2.0') + + expect(project.remote_file('v0.2.0', 'README.md')).to include('stable release of the project, 0.2.0') + expect(project.remote_file('master', 'README.md')).to include('next release of the project, which should be 0.2.1') + release = project.git('--git-dir', project.remote, 'rev-parse', 'v0.2.0^{commit}') + expect(project.git('--git-dir', project.remote, 'rev-list', '--parents', '-n', '1', release).split.drop(1)).to eq([source]) + expect(project.git('--git-dir', project.remote, 'rev-list', '--parents', '-n', '1', 'master').split.drop(1)).to eq([release]) + archive = File.binread(File.join(artifacts(project), 'release.gem')) + %w[registry hosting].each { |adapter| expect(File.binread(File.join(artifacts(project), adapter, '0.2.0.gem'))).to eq(archive) } + expect(JSON.parse(File.read(File.join(artifacts(project), 'publication.json')))).to include('version' => '0.2.0', 'next_version' => '0.2.1', 'source_commit' => source) + + project.publish_isolated! + expect(project.git('--git-dir', project.remote, 'rev-parse', 'v0.2.0^{commit}')).to eq(release) + end + end + + it 'fails before publishing the gem when the branch rejects the release commit, and resumes once permitted' do + with_release_project do |project| + prepare_project(project) + hook = reject_branch_pushes(project) + + expect { project.isolated_release!(version: '0.2.0') }.to raise_error(RuntimeError, /protected branch/) + expect(published?(project)).to eq([false, false]) + expect(project.git('--git-dir', project.remote, 'tag', '--list')).to eq('') + + File.delete(hook) + project.publish_isolated! + expect(published?(project)).to eq([true, true]) + expect(project.remote_file('master', 'README.md')).to include('which should be 0.2.1') + end + end + + it 'refuses publication when the default branch advanced after the build' do + with_release_project do |project| + prepare_project(project) + %w[release:workflow:capture release:validate release:prepare release:workflow:resolve release:workflow:checkpoint release:workflow:seal].each { |task| project.run_task(task) } + other = File.join(project.directory, 'other') + project.git('clone', '--quiet', project.remote, other) + project.git('-C', other, '-c', 'user.name=Other', '-c', 'user.email=other@example.com', 'commit', '--quiet', '--allow-empty', '-m', 'Concurrent change') + project.git('-C', other, 'push', '--quiet', 'origin', 'master') + + expect { project.publish_isolated! }.to raise_error(RuntimeError, /Default branch advanced/) + expect(published?(project)).to eq([false, false]) + end + end + + it 'refuses a handoff that does not match the dispatched commit' do + with_release_project do |project| + prepare_project(project) + %w[release:workflow:capture release:validate release:prepare release:workflow:resolve release:workflow:checkpoint release:workflow:seal].each { |task| project.run_task(task) } + path = File.join(artifacts(project), 'publication.json') + File.write(path, JSON.generate(JSON.parse(File.read(path)).merge('source_commit' => 'f' * 40))) + + expect { project.publish_isolated! }.to raise_error(RuntimeError, /not built from the dispatched commit/) + expect(published?(project)).to eq([false, false]) + end + end + + it 'rejects publication-stage hooks while sealing, before any publication' do + with_release_project do |project| + project.write('publication_hook.rb', <<~RUBY) + require_relative 'release_workflow' + module PublicationHookWorkflow + def self.build(**) + ProjectReleaseWorkflow.build(**).after(:publish_registry) { |_ctx| nil } + end + end + RUBY + prepare_project(project, builder: 'PublicationHookWorkflow.build') + project.configure_workflow(require: 'publication_hook', builder: 'PublicationHookWorkflow.build') + project.commit!('Use a publication hook') + + expect { project.isolated_release!(version: '0.2.0') }.to raise_error(RuntimeError, /runs no project hooks for publish_registry/) + expect(File).not_to exist(File.join(artifacts(project), 'publication.json')) + end + end +end diff --git a/spec/release_version_spec.rb b/spec/release_version_spec.rb index 0e7fb9d..25d8db8 100644 --- a/spec/release_version_spec.rb +++ b/spec/release_version_spec.rb @@ -12,6 +12,7 @@ let(:readme) do <<~MARKDOWN workflow: dblock/ruby-gem-release/.github/workflows/release.yml@v0.2.0 + isolated: dblock/ruby-gem-release/.github/workflows/isolated-release.yml@v0.2.0 action: dblock/ruby-gem-release@v0.2.0 other: another/action@v0.2.0 MARKDOWN @@ -29,7 +30,7 @@ end it 'increments the version while pinning only this action and workflow to the released version', :aggregate_failures do - expected = readme.sub('release.yml@v0.2.0', 'release.yml@v1.2.3').sub('ruby-gem-release@v0.2.0', 'ruby-gem-release@v1.2.3') + expected = readme.gsub('release.yml@v0.2.0', 'release.yml@v1.2.3').sub('ruby-gem-release@v0.2.0', 'ruby-gem-release@v1.2.3') expect(version.increment!).to eq('1.2.4') expect(version.read).to eq('1.2.4') expect(File.read(readme_file)).to eq(expected) @@ -43,7 +44,7 @@ it 'updates every documentation Markdown file without changing other references or files', :aggregate_failures do FileUtils.mkdir_p(%w[docs/nested examples]) %w[docs/action.md docs/nested/workflow.md docs/notes.txt examples/guide.md].each { |path| File.write(path, readme) } - expected = readme.sub('release.yml@v0.2.0', 'release.yml@v2.0.0').sub('ruby-gem-release@v0.2.0', 'ruby-gem-release@v2.0.0') + expected = readme.gsub('release.yml@v0.2.0', 'release.yml@v2.0.0').sub('ruby-gem-release@v0.2.0', 'ruby-gem-release@v2.0.0') expect(version.increment!(from: '2.0.0')).to eq('2.0.1') expect(File.read('docs/action.md')).to eq(expected) expect(File.read('docs/nested/workflow.md')).to eq(expected) diff --git a/spec/ruby_gem_release/workflow/isolated_publication_spec.rb b/spec/ruby_gem_release/workflow/isolated_publication_spec.rb new file mode 100644 index 0000000..11e5904 --- /dev/null +++ b/spec/ruby_gem_release/workflow/isolated_publication_spec.rb @@ -0,0 +1,79 @@ +# frozen_string_literal: true + +require 'spec_helper' +require 'tmpdir' +require 'ruby-gem-release/workflow/semantic_ruby_gem' + +RSpec.describe RubyGemRelease::Workflow::IsolatedPublication do + let(:directory) { Dir.mktmpdir } + let(:components) do + { package: RubyGemRelease::Package::RubyGem.allocate, destination: RubyGemRelease::Destination::RubyGems.new, + git: RubyGemRelease::SourceControl::Git.new(directory: directory), hosting: RubyGemRelease::Hosting::GitHubRelease.new(repository: nil) } + end + let(:hooks) { [] } + let(:provider) { RubyGemRelease::ExecutionProvider.new(environment: { 'GITHUB_REPOSITORY' => 'owner/project' }) } + let(:workflow) do + Struct.new(:package, :destination, :git, :hosting, :registered, :provider) do + def hooks?(stage) = registered.include?(stage) + end.new(*components.values_at(:package, :destination, :git, :hosting), hooks, provider) + end + + # Actions sets GITHUB_REPOSITORY, which the default hosting also reads. + around do |example| + original = ENV.fetch('GITHUB_REPOSITORY', nil) + ENV['GITHUB_REPOSITORY'] = 'owner/project' + example.run + ensure + original ? ENV['GITHUB_REPOSITORY'] = original : ENV.delete('GITHUB_REPOSITORY') + FileUtils.rm_rf(directory) + end + + it 'accepts the default components, disabled hosting, and build-stage hooks' do + hooks.push(:prepare_release, :prepare_next, :commit_next) + expect { described_class.check!(workflow, callbacks: false) }.not_to raise_error + workflow.hosting = nil + expect { described_class.check!(workflow, callbacks: false) }.not_to raise_error + end + + it 'rejects components the publish job cannot reproduce', :aggregate_failures do + { package: Object.new, destination: Class.new(RubyGemRelease::Destination::RubyGems).new, git: Object.new }.each do |name, replacement| + original = workflow[name] + workflow[name] = replacement + expect { described_class.check!(workflow, callbacks: false) }.to raise_error(ArgumentError, "isolated publication requires the default #{name}") + workflow[name] = original + end + workflow.hosting = RubyGemRelease::Hosting::GitHubRelease.new(repository: 'owner/project') + expect { described_class.check!(workflow, callbacks: false) }.not_to raise_error + workflow.hosting = RubyGemRelease::Hosting::GitHubRelease.new(repository: 'other/repository') + expect { described_class.check!(workflow, callbacks: false) }.to raise_error(ArgumentError, /default GitHub Release hosting/) + end + + it 'rejects project callbacks and publication-stage hooks', :aggregate_failures do + expect { described_class.check!(workflow, callbacks: true) }.to raise_error(ArgumentError, /no project success or failure callbacks/) + hooks.push(:push_release, :success) + expect { described_class.check!(workflow, callbacks: false) }.to raise_error(ArgumentError, 'isolated publication runs no project hooks for push_release, success') + end + + it 'refuses an unsupported handoff format before any Git or registry operation' do + File.write(File.join(directory, described_class::FILE), JSON.generate('format' => 2)) + provider = RubyGemRelease::ExecutionProvider.new(environment: { 'RELEASE_DATA_DIR' => directory }) + destination = instance_double(RubyGemRelease::Destination::RubyGems) + expect { described_class.new(provider: provider, destination: destination).publish! }.to raise_error(ArgumentError, /unsupported isolated publication format/) + end + + it 'seals semantic releases without a development iteration unless bumping is enabled' do + allow(described_class).to receive(:check!) + allow(described_class).to receive(:seal!) { |release:, **| release } + values = { 'INPUT_VERSION' => '', 'SOURCE_COMMIT' => 'a' * 40, 'GEMSPEC_VERSION' => '1.2.3', 'RELEASE_VERSION' => '1.3.0', 'RELEASE_DATE' => '2026-11-20' } + provider = RubyGemRelease::ExecutionProvider.new(environment: values) + decision = RubyGemRelease::SemanticRelease::Decision.new(head: 'a' * 40, last_release: nil, commits: [], release_type: 'minor', version: '1.3.0', notes: 'Notes.') + version = instance_double(RubyGemRelease::Version::RubyConstant, read: '1.3.0', set!: nil, increment!: '1.3.1') + workflow = RubyGemRelease::Workflow::SemanticRubyGem.new(version: version, provider: provider, **components.slice(:package, :destination, :git)) + state = RubyGemRelease::Workflow::State.new + state.record_analysis!(decision) + release = RubyGemRelease::Release.new(version: '1.3.0', gemspec_version: '1.2.3', date: Date.new(2026, 11, 20), notes: 'Notes.') + sealed = workflow.seal!(provider.context(release: release, task: 'release:workflow:seal', state: state, workflow: workflow, analysis: decision)) + expect(sealed).to have_attributes(version: '1.3.0', next_version: nil, notes: 'Notes.') + expect(version).not_to have_received(:increment!) + end +end diff --git a/spec/ruby_gem_release/workflow/ruby_gem_spec.rb b/spec/ruby_gem_release/workflow/ruby_gem_spec.rb index 4ca4f6d..e7eaa7e 100644 --- a/spec/ruby_gem_release/workflow/ruby_gem_spec.rb +++ b/spec/ruby_gem_release/workflow/ruby_gem_spec.rb @@ -134,6 +134,12 @@ def increment!(from:) = from end end + it 'rejects isolated sealing without a workflow that implements it' do + RubyGemRelease::Tasks.install + expect { Rake::Task['release:workflow:seal'].invoke }.to raise_error(/must implement seal!/) + expect(events).to be_empty + end + it 'rejects an Actions checkpoint without a configured workflow' do RubyGemRelease::Tasks.install expect { Rake::Task['release:workflow:checkpoint'].invoke }.to raise_error(/must implement checkpoint!/) diff --git a/spec/workflow_interfaces_spec.rb b/spec/workflow_interfaces_spec.rb index 2187b2a..bc2e7ec 100644 --- a/spec/workflow_interfaces_spec.rb +++ b/spec/workflow_interfaces_spec.rb @@ -121,6 +121,38 @@ def run_step(id, directory:, command: '') end end + context 'with the isolated reusable workflow' do + let(:workflow) { YAML.load_file('.github/workflows/isolated-release.yml') } + let(:build) { workflow.dig('jobs', 'build') } + let(:publish) { workflow.dig('jobs', 'publish') } + let(:steps) { build.fetch('steps') } + + it 'runs project commands only in a read-only build job without the release environment' do + expect(build.fetch('permissions')).to eq('contents' => 'read') + expect(build).not_to have_key('environment') + expect(steps.first.dig('with', 'persist-credentials')).to be(false) + ids = steps.map { |step| step['id'] } + expect(ids.index('seal_release')).to be > ids.index('checkpoint_release') + expect(ids.index('preserve_release_artifacts')).to be > ids.index('seal_release') + expect(steps.find { |step| step['id'] == 'preserve_release_artifacts' }.dig('with', 'path')).to include('${{ runner.temp }}/publication.json') + end + + it 'publishes in a separate environment-gated job that installs no project bundle and runs no project commands', :aggregate_failures do + expect(publish.fetch('needs')).to eq('build') + expect(publish.fetch('environment')).to eq('release') + expect(publish.fetch('permissions')).to eq('contents' => 'write', 'id-token' => 'write') + steps = publish.fetch('steps') + expect(steps.map { |step| step['uses'] || step['id'] }).to eq(%w[actions/checkout@v7 actions/checkout@v7 ruby/setup-ruby@v1 actions/download-artifact@v8 publish_release]) + library = steps.find { |step| step['id'] == 'checkout_library' } + expect(library.fetch('with')).to include('repository' => '${{ job.workflow_repository }}', 'ref' => '${{ job.workflow_sha }}', 'persist-credentials' => false) + expect(steps.find { |step| step['id'] == 'setup_ruby' }.dig('with', 'bundler')).to eq('none') + run = steps.find { |step| step['id'] == 'publish_release' }.fetch('run') + expect(run).to start_with('ruby --disable-gems -rrubygems -I ../library/lib ') + expect(run).not_to match(/bundle|rake|RELEASE_COMMAND/) + expect(workflow.fetch(true).dig('workflow_call', 'inputs').keys).not_to include('publish', 'bump', 'success', 'failure', 'prepare-artifacts') + end + end + context 'with the composite action' do let(:workflow) { YAML.load_file('action.yml') } let(:steps) { workflow.fetch('runs').fetch('steps') } diff --git a/tasks/release_version.rb b/tasks/release_version.rb index 8529ee9..e00cb88 100644 --- a/tasks/release_version.rb +++ b/tasks/release_version.rb @@ -5,7 +5,7 @@ module ReleaseVersion def self.build(path:, constant:, readme_path:) - patterns = [%r{dblock/ruby-gem-release(?:/\.github/workflows/release\.yml)?@v(?\d+\.\d+\.\d+)(?![\w.+-])}] + patterns = [%r{dblock/ruby-gem-release(?:/\.github/workflows/(?:isolated-)?release\.yml)?@v(?\d+\.\d+\.\d+)(?![\w.+-])}] RubyGemRelease::Version::References.new( version: RubyGemRelease::Version::RubyConstant.new(path: path, constant: constant), references: { readme_path => patterns, 'docs/**/*.md' => patterns }