From 8cc4ecb028db96698c8eac16a6c3f0406d631e4c Mon Sep 17 00:00:00 2001 From: Jim Myhrberg Date: Mon, 16 Nov 2026 18:34:38 +0000 Subject: [PATCH 1/2] ci(release): prepare installation guides on minor release PRs After Release Please runs on main, find the open release PR, read its head as data from a trusted main checkout, and commit any guide changes that release:prepare would make through GraphQL createCommitOnBranch with the release App token. GitHub signs the commit, expectedHeadOid makes a moved branch fail instead of being overwritten, and a rebuild that drops the commit gets it back in the same run. Patch releases and runs without an open release PR change nothing. Closes #90 --- .github/workflows/release-please.yml | 54 ++++++- docs/releasing.md | 69 ++++++--- mise.toml | 4 + scripts/release.rb | 14 +- scripts/release_preparation.rb | 104 +++++++++++++ scripts/release_train.rb | 10 +- spec/release_preparation_spec.rb | 218 +++++++++++++++++++++++++++ spec/release_train_spec.rb | 40 +++++ 8 files changed, 489 insertions(+), 24 deletions(-) create mode 100644 scripts/release_preparation.rb create mode 100644 spec/release_preparation_spec.rb diff --git a/.github/workflows/release-please.yml b/.github/workflows/release-please.yml index dc7814f6..baf96add 100644 --- a/.github/workflows/release-please.yml +++ b/.github/workflows/release-please.yml @@ -1,7 +1,8 @@ name: Release Please # Opens and updates the release PR. Merging it tags the commit and creates -# a draft GitHub release; release.yml publishes from that tag. +# a draft GitHub release; release.yml publishes from that tag. A minor release +# PR then gets a signed App commit with its prepared installation guides. on: push: branches: [main] @@ -13,6 +14,10 @@ concurrency: group: release-please-main cancel-in-progress: false +env: + MISE_ENV: ci + MISE_LOCKED: "1" + jobs: release-please: if: github.ref == 'refs/heads/main' @@ -43,3 +48,50 @@ jobs: token: ${{ steps.app-token.outputs.token }} config-file: .github/release-please-config.json manifest-file: .github/.release-please-manifest.json + # Looked up independently: Release Please reports no PR when its body is + # unchanged, and the owner-qualified head filter excludes forks. + - id: release-pr + name: Find the release PR + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} + RELEASE_BRANCH: release-please--branches--main--components--connectrpc + run: | + sha="$(gh api "repos/$GITHUB_REPOSITORY/pulls?state=open&base=main&head=$GITHUB_REPOSITORY_OWNER:$RELEASE_BRANCH" --jq '.[0].head.sha // empty')" + echo "sha=$sha" >> "$GITHUB_OUTPUT" + # Tooling comes from main. The release PR head is only read as data, so + # release-branch code never runs with the App token. + - name: Check out main tooling + if: steps.release-pr.outputs.sha != '' + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + token: ${{ steps.app-token.outputs.token }} + persist-credentials: false + - name: Check out the release PR head as data + if: steps.release-pr.outputs.sha != '' + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ steps.release-pr.outputs.sha }} + path: release-pr + token: ${{ steps.app-token.outputs.token }} + persist-credentials: false + - if: steps.release-pr.outputs.sha != '' + uses: ruby/setup-ruby@7f797815d8adceb1c412e7abefdd1ab4abc47a5f # v1.335.0 + with: + ruby-version: "3.4.12" + bundler: "4.0.23" + - if: steps.release-pr.outputs.sha != '' + uses: jdx/mise-action@82a612c5ab8bcda7cc5db6b7e81a8e7584c3dc6e # v5.2.3 + with: + version: "2026.10.19" + add_shims_to_path: false + env: false + export_path: false + install: false + cache: false + - name: Prepare and commit installation guides + if: steps.release-pr.outputs.sha != '' + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} + RELEASE_HEAD: ${{ steps.release-pr.outputs.sha }} + RELEASE_ROOT: release-pr + run: mise run release:prepare:pr diff --git a/docs/releasing.md b/docs/releasing.md index 979997ba..1f458482 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -10,7 +10,8 @@ It remains experimental and does not adopt the stronger The pipeline has three stages: 1. Every push to main runs Release Please, which opens or updates one release - PR for the whole train. + PR for the whole train. For a minor release, the same run then commits the + prepared installation guides to that PR. 2. Merging that PR makes Release Please push a `vX.Y.Z` tag and create a draft GitHub release with the changelog. 3. The tag starts the [release workflow](../.github/workflows/release.yml). It @@ -65,6 +66,26 @@ draft release until it is published, and without the tag Release Please cannot find the previous release. This workflow has no publishing job or OIDC permission. +After Release Please, the same job prepares the open release PR: + +1. It looks up the open PR from the + `release-please--branches--main--components--connectrpc` branch of this + repository into main. Release Please reports no PR when the body is + unchanged, so the lookup does not depend on its output. Forks are excluded. +2. It checks out main for tooling, then the PR head SHA into `release-pr` as + data. Nothing from the release branch runs: `mise run release:prepare:pr` + reads only the release tree's core version file and installation guides as + text, and applies the same transformation as `release:prepare`. +3. If any guide changes, it commits exactly those guides to the release branch + through the GraphQL `createCommitOnBranch` mutation with the App token, so + GitHub signs the commit as the App. `expectedHeadOid` is the checked-out + SHA, so a branch that moved since the lookup fails the run instead of being + overwritten. + +Patch releases and runs without an open release PR change nothing. A failed +preparation is retried by the next push to main, or by manually dispatching the +workflow from main. The App-token push starts the PR's normal CI. + The job runs in the `release-please` environment, whose deployment branch policy allows only `main`. The existing release GitHub App needs these references, as in the pinned @@ -77,10 +98,11 @@ references, as in the pinned | App installation | Installation access to `jimeh/connectrpc-ruby`, with contents, issues and pull requests write permissions. | The workflow requests an installation token scoped to the current repository -and those three permissions. Its `GITHUB_TOKEN` has no permissions. App-created -PRs can trigger normal downstream CI. Missing references fail the run with an -actionable error; there is no fallback token. Do not print, copy into the -checkout, or ask for private-key values in chat. +and those three permissions. Contents write also covers the guide preparation +commit, so it needs no new permission. Its `GITHUB_TOKEN` has no permissions. +App-created PRs can trigger normal downstream CI. Missing references fail the +run with an actionable error; there is no fallback token. Do not print, copy +into the checkout, or ask for private-key values in chat. Both reference names were listed in the `release-please` environment on 2026-11-14. App installation and token permissions are verified only by the @@ -100,21 +122,23 @@ For each release PR: 2. A patch release needs no preparation: the bot's version files, manifest and changelog are the whole change, and `release:check` accepts them. A minor (breaking) release changes the internal `~> M.m.0` requirement that the - installation guides quote, so `release:check` fails until you check out the - release branch, run `mise run release:prepare`, review the guide diff and - commit it with the existing signing configuration. Preparation does not - resolve dependencies or download anything. + installation guides quote. The workflow commits that guide update + automatically; review its diff. If the workflow cannot, dispatch it again or + use the local fallback: check out the release branch, run + `mise run release:prepare`, review the guide diff and commit it with the + existing signing configuration. Preparation does not resolve dependencies or + download anything. 3. Run `mise run release:check`, focused tests and the candidate procedure below. Capture the exact head and CI/review evidence after the final bot update. 4. Merge the PR once the release decision is made. The release workflow then waits for any `release` environment approval. -**Re-run preparation after every bot regeneration of a minor release.** Release -Please rebuilds its branch from main when its generated body changes. It can -discard signed preparation commits and hand edits in the release PR. Finish the -bot update, then prepare and validate its final head; a quiet main during that -window helps. Do not present earlier CI/review evidence as covering a later -regenerated head. +**Validate the final head after every bot regeneration of a minor release.** +Release Please rebuilds its branch from main when its generated body changes, +which drops the preparation commit; the same workflow run then commits it +again. Hand edits in the release PR are still discarded. Wait for the run to +finish, then validate the final head; a quiet main during that window helps. Do +not present earlier CI/review evidence as covering a later regenerated head. ## Validate a local candidate @@ -123,7 +147,8 @@ Use `mise tasks` for the task index: | Task | Evidence and writes | | --- | --- | | `release:check` | Offline version, configuration, guard and installation-guide checks. No writes or setup dependencies. | -| `release:prepare` | Deterministic installation-guide requirement updates, needed only for a minor release. No registry resolution. | +| `release:prepare` | Deterministic installation-guide requirement updates, needed only for a minor release. No registry resolution. Local fallback for the workflow. | +| `release:prepare:pr` | CI only. Refuses to run outside `release-please.yml` on main. Commits the prepared guides of the checked-out release PR as the App. | | `release:build` | Eleven canonical archives, two-build hash comparison and `candidate.json`. No installation or publication. | | `release:candidate` | Existing installed-package/generation/RBS checks followed by the canonical archive build. Uses normal scoped setup prerequisites. | | `release:tools` | Installs the frozen Sigstore signing bundle (`release/Gemfile`) into `vendor/sigstore`. | @@ -133,7 +158,7 @@ Run the focused release specs and workflow checks first: ```sh mise run release:check -mise run test -- spec/release_train_spec.rb spec/release_publisher_spec.rb spec/package_build_spec.rb spec/ci_runtime_spec.rb +mise run test -- spec/release_train_spec.rb spec/release_preparation_spec.rb spec/release_publisher_spec.rb spec/package_build_spec.rb spec/ci_runtime_spec.rb mise run lint:workflows ``` @@ -301,8 +326,11 @@ published, the retained bytes are the only valid candidate. An interrupted uploa safe to delete. When repair requires a new version, release a new whole-train version and document the partial train and migration implications. -Release Please creates its commits and tags through the GitHub API as the App, -not with a local GPG key. Normal source commits stay signed. +Release Please creates its commits and tags, and the workflow creates the +guide preparation commit, through the GitHub API as the App, not with a local +GPG key. GitHub signs App commits made without a custom author or committer. +Normal source commits, including a local `release:prepare` fallback, stay +signed. ## Primary references @@ -315,3 +343,6 @@ not with a local GPG key. Normal source commits stay signed. - [RubyGems owner assertion for new gems](https://github.com/rubygems/rubygems.org/blob/master/app/models/pusher.rb) (`notify_missing_pending_owner`). - [Sigstore Ruby CLI](https://github.com/sigstore/sigstore-ruby/tree/v0.2.3). - [GitHub immutable releases](https://docs.github.com/en/code-security/supply-chain-security/understanding-your-software-supply-chain/immutable-releases). +- [GraphQL `createCommitOnBranch`](https://docs.github.com/en/graphql/reference/mutations#createcommitonbranch). +- [Signature verification for bots](https://docs.github.com/en/authentication/managing-commit-signature-verification/about-commit-signature-verification#signature-verification-for-bots). +- [Triggering a workflow from a workflow](https://docs.github.com/en/actions/how-tos/write-workflows/choose-when-workflows-run/trigger-a-workflow#triggering-a-workflow-from-a-workflow). diff --git a/mise.toml b/mise.toml index dc575a62..b325bd0f 100644 --- a/mise.toml +++ b/mise.toml @@ -1019,6 +1019,10 @@ run = "mise exec -- ruby scripts/release.rb check" description = "Refresh installation guide requirements after a minor (breaking) release version update" run = "mise exec -- ruby scripts/release.rb prepare" +[tasks."release:prepare:pr"] +description = "CI only (release-please.yml on main): commit prepared installation guides to the release PR branch as the release App" +run = "mise exec -- ruby scripts/release.rb prepare-pr" + [tasks."release:build"] description = "Build and compare eleven canonical candidate archives from a clean Ruby 3.4.12 checkout" run = "mise exec -- ruby scripts/release.rb build" diff --git a/scripts/release.rb b/scripts/release.rb index ea106ec9..11b88ff1 100644 --- a/scripts/release.rb +++ b/scripts/release.rb @@ -10,6 +10,18 @@ when ["prepare"] train.prepare! puts "Prepared installation guides for #{train.version}; review and sign the diff" +when ["prepare-pr"] + require_relative "release_preparation" + # The App-token commit only runs from the Release Please workflow on main. + workflow = ENV.fetch("GITHUB_WORKFLOW_REF", "") + unless ENV["GITHUB_ACTIONS"] == "true" && workflow.include?("/.github/workflows/release-please.yml@refs/heads/main") + abort "release:prepare:pr only runs in .github/workflows/release-please.yml on main" + end + + ReleasePreparation.new( + train: ReleaseTrain.new(ENV.fetch("RELEASE_ROOT")), repository: ENV.fetch("GITHUB_REPOSITORY"), + head: ENV.fetch("RELEASE_HEAD"), github: ReleasePreparation::GitHub.new + ).commit! when ["build"] require_relative "release_candidate" puts "Candidate archives: #{ReleaseCandidate.new(train).build_from_git!}" @@ -38,5 +50,5 @@ ).publish! end else - abort "Usage: ruby scripts/release.rb check|prepare|build|tools|publish" + abort "Usage: ruby scripts/release.rb check|prepare|prepare-pr|build|tools|publish" end diff --git a/scripts/release_preparation.rb b/scripts/release_preparation.rb new file mode 100644 index 00000000..053b297d --- /dev/null +++ b/scripts/release_preparation.rb @@ -0,0 +1,104 @@ +# frozen_string_literal: true + +require "json" +require "open3" +require_relative "release_train" + +# Commits prepared installation guides to the open release PR as the release +# App. The release checkout is data: its version file and guides are read as +# text and nothing from it runs while the App token is in the environment. +class ReleasePreparation + BRANCH = "release-please--branches--main--components--connectrpc" + + def initialize(train:, repository:, head:, github:, log: $stdout) + @train = train + @repository = repository + @head = head + @github = github + @log = log + end + + def commit! + verify_head! + changes = changed_guides + if changes.empty? + @log.puts "Installation guides already quote #{@train.requirement}; nothing to commit" + return + end + + oid = @github.create_commit(commit_input(changes)) + @log.puts "Committed #{changes.size} prepared installation guides for #{@train.version} to #{BRANCH}: #{oid}" + oid + end + + private + + def verify_head! + revision, error, status = Open3.capture3("git", "rev-parse", "HEAD", chdir: @train.root) + raise "Cannot read the release checkout HEAD: #{error}" unless status.success? + return if revision.strip == @head + + raise "Release checkout is at #{revision.strip}, expected #{@head}" + end + + def changed_guides + root = File.realpath(@train.root) + ReleaseTrain::GUIDES.sort.each_with_object({}) do |file, changes| + current = guide(root, file) + next unless current + + prepared = @train.prepared_guide(current) + changes[file] = prepared unless prepared == current + end + end + + # Main may list a guide that an older release branch lacks. + def guide(root, file) + path = File.join(root, file) + unless File.exist?(path) + @log.puts "Skipping #{file}: not in the release tree" + return + end + # A symlink could make the commit carry runner files instead of guide text. + unless File.file?(path) && File.realpath(path) == path + raise "Refusing #{file}: not a regular file inside the release tree" + end + + File.read(path) + end + + def commit_input(changes) + { + branch: { repositoryNameWithOwner: @repository, branchName: BRANCH }, + expectedHeadOid: @head, + message: { headline: "chore: prepare installation guides for #{@train.version}" }, + # pack("m0") is strict Base64; the base64 gem is no longer a default gem on Ruby 3.4. + fileChanges: { additions: changes.map { |path, text| { path: path, contents: [text].pack("m0") } } } + } + end + + # GraphQL createCommitOnBranch through the preinstalled gh CLI. An App + # installation token makes GitHub sign the commit, and a stale + # expectedHeadOid fails the mutation instead of overwriting the branch. + class GitHub + MUTATION = <<~GRAPHQL + mutation($input: CreateCommitOnBranchInput!) { + createCommitOnBranch(input: $input) { commit { oid url } } + } + GRAPHQL + + def create_commit(input) + body = JSON.generate(query: MUTATION, variables: { input: input }) + output, error, status = Open3.capture3("gh", "api", "graphql", "--input", "-", stdin_data: body) + raise "gh api graphql failed: #{error}#{output}" unless status.success? + + response = JSON.parse(output) + raise "createCommitOnBranch failed: #{JSON.generate(response['errors'])}" if response["errors"] + + oid = response.dig("data", "createCommitOnBranch", "commit", "oid") + raise "createCommitOnBranch returned no commit: #{output}" unless oid + + oid + end + end +end diff --git a/scripts/release_train.rb b/scripts/release_train.rb index 41314959..9731d719 100644 --- a/scripts/release_train.rb +++ b/scripts/release_train.rb @@ -76,9 +76,13 @@ def check_versions! # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplex # Installation guides name the internal `~> M.m.0` requirement, which changes # only on a minor (breaking) release. Versions and changelog need nothing else. def prepared_files - GUIDES.to_h do |file| - [file, read(file).gsub(/(connectrpc(?:-[a-z]+)*["`, ]+)~> 0\.\d+\.\d+/, "\\1#{requirement}")] - end + GUIDES.to_h { |file| [file, prepared_guide(read(file))] } + end + + # Pure text transformation, so callers can prepare guides read from a tree + # they must not execute. + def prepared_guide(content) + content.gsub(/(connectrpc(?:-[a-z]+)*["`, ]+)~> 0\.\d+\.\d+/, "\\1#{requirement}") end def check_configuration! # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity diff --git a/spec/release_preparation_spec.rb b/spec/release_preparation_spec.rb new file mode 100644 index 00000000..5c2b023a --- /dev/null +++ b/spec/release_preparation_spec.rb @@ -0,0 +1,218 @@ +# frozen_string_literal: true + +require "fileutils" +require "json" +require "open3" +require "rbconfig" +require "stringio" +require "tmpdir" +require_relative "../scripts/release_preparation" + +module ReleasePreparationFakes + # GitHub is the external boundary; the fake records each commit input. + class FakeGitHub + attr_reader :inputs + + def initialize + @inputs = [] + end + + def create_commit(input) + @inputs << input + "c" * 40 + end + end +end + +RSpec.describe ReleasePreparation do + let(:github) { ReleasePreparationFakes::FakeGitHub.new } + let(:log) { StringIO.new } + + def git(root, *arguments) + output, error, status = Open3.capture3("git", "-c", "user.name=Release Spec", "-c", + "user.email=spec@example.invalid", "-c", "commit.gpgsign=false", + "-c", "core.hooksPath=/dev/null", *arguments, chdir: root) + raise "git #{arguments.first} failed: #{error}" unless status.success? + + output.strip + end + + def commit_all(root, message) + git(root, "add", "--all") + git(root, "commit", "--quiet", "--no-verify", "-m", message) + git(root, "rev-parse", "HEAD") + end + + # A Release Please branch at a proposed version: the same inputs as the + # captured release train, committed in a throwaway repository. + def release_branch(bump) + Dir.mktmpdir("connectrpc-preparation-spec-") do |root| + source = File.expand_path("..", __dir__) + owners = ReleaseTrain::NAMES.map { |name| name == "connectrpc" ? "connectrpc.gemspec" : "gems/#{name}/#{name}.gemspec" } + [*owners, *ReleaseTrain::VERSION_FILES.values, *ReleaseTrain::GUIDES, + ".github/release-please-config.json", ".github/.release-please-manifest.json"].each do |file| + FileUtils.mkdir_p(File.dirname(File.join(root, file))) + FileUtils.cp(File.join(source, file), File.join(root, file)) + end + git(root, "init", "--quiet") + commit_all(root, "chore: base") + train = ReleaseTrain.new(root) + version = propose_version(train, bump) + yield train, commit_all(root, "chore(main): release #{version}"), version + end + end + + def propose_version(train, bump) + major, minor, patch = train.version.split(".").map(&:to_i) + version = bump == :patch ? "#{major}.#{minor}.#{patch + 1}" : "#{major}.#{minor + 1}.0" + config = JSON.parse(train.read(".github/release-please-config.json")).fetch("packages").fetch(".") + [config.fetch("version-file"), *config.fetch("extra-files")].each do |file| + path = File.join(train.root, file) + File.write(path, File.read(path).sub(/((?:VERSION|spec.version) = ")[^"]+/, "\\1#{version}")) + end + File.write(File.join(train.root, ".github/.release-please-manifest.json"), JSON.generate({ "." => version })) + version + end + + # The local release:prepare result for the same tree, from a separate copy. + def locally_prepared(train) + Dir.mktmpdir("connectrpc-preparation-reference-") do |copy| + FileUtils.cp_r("#{train.root}/.", copy) + ReleaseTrain.new(copy).prepare! + ReleaseTrain::GUIDES.to_h { |file| [file, File.read(File.join(copy, file))] } + .reject { |file, text| File.exist?(File.join(train.root, file)) && text == train.read(file) } + end + end + + def preparation(train, head) + described_class.new(train: train, repository: "owner/repo", head: head, github: github, log: log) + end + + def decoded_additions(input) + input.dig(:fileChanges, :additions).to_h do |addition| + [addition.fetch(:path), addition.fetch(:contents).unpack1("m0")] + end + end + + it "commits exactly the guides release:prepare would change for a minor release, against the checked-out head" do + release_branch(:minor) do |train, _head, version| + expected = locally_prepared(train) + # A guide that already quotes the new requirement is left out of the commit. + File.write(File.join(train.root, "docs/design.md"), expected.delete("docs/design.md")) + head = commit_all(train.root, "docs: prepare one guide by hand") + allow(Gem::Specification).to receive(:load).and_call_original + + expect(preparation(train, head).commit!).to eq("c" * 40) + + expect(github.inputs.size).to eq(1) + input = github.inputs.first + expect(input.fetch(:branch)).to eq(repositoryNameWithOwner: "owner/repo", + branchName: "release-please--branches--main--components--connectrpc") + expect(input.fetch(:expectedHeadOid)).to eq(head) + expect(input.dig(:message, :headline)).to eq("chore: prepare installation guides for #{version}") + expect(expected.size).to eq(ReleaseTrain::GUIDES.size - 1) + expect(decoded_additions(input)).to eq(expected) + expect(input.dig(:fileChanges, :additions).map { |addition| addition.fetch(:path) }).to eq(expected.keys.sort) + # Nothing from the release tree is evaluated or written. + expect(Gem::Specification).not_to have_received(:load) + expect(git(train.root, "status", "--porcelain")).to be_empty + expect(git(train.root, "rev-parse", "HEAD")).to eq(head) + end + end + + it "makes no API call for a patch release" do + release_branch(:patch) do |train, head, _version| + expect(preparation(train, head).commit!).to be_nil + expect(github.inputs).to be_empty + expect(log.string).to include("nothing to commit") + end + end + + it "refuses a checkout that is not the expected head before calling GitHub" do + release_branch(:minor) do |train, _head, _version| + expect { preparation(train, "0" * 40).commit! }.to raise_error(/Release checkout is at \h{40}, expected 0{40}/) + expect(github.inputs).to be_empty + end + end + + it "skips a guide that main lists but the release branch lacks" do + release_branch(:minor) do |train, _head, _version| + missing = "gems/connectrpc-sentry/README.md" + expected = locally_prepared(train) + expect(expected).to include(missing) + git(train.root, "rm", "--quiet", missing) + head = commit_all(train.root, "chore: drop a guide") + + preparation(train, head).commit! + + expect(decoded_additions(github.inputs.first)).to eq(expected.except(missing)) + expect(log.string).to include("Skipping #{missing}: not in the release tree") + end + end + + it "refuses a guide symlinked outside the release tree before calling GitHub" do + release_branch(:minor) do |train, _head, _version| + Dir.mktmpdir("connectrpc-preparation-outside-") do |runner| + outside = File.join(runner, "secret.md") + File.write(outside, "gem \"connectrpc\", \"~> 0.0.1\"\n") + FileUtils.rm(File.join(train.root, "docs/unary.md")) + File.symlink(outside, File.join(train.root, "docs/unary.md")) + head = commit_all(train.root, "chore: link a guide") + + expect { preparation(train, head).commit! }.to raise_error(%r{Refusing docs/unary.md: not a regular file}) + expect(github.inputs).to be_empty + end + end + end + + it "refuses to run outside the Release Please workflow on main" do + script = File.expand_path("../scripts/release.rb", __dir__) + { + "local" => {}, + "release tag" => { "GITHUB_ACTIONS" => "true", + "GITHUB_WORKFLOW_REF" => "o/r/.github/workflows/release.yml@refs/tags/v0.2.0" }, + "other branch" => { "GITHUB_ACTIONS" => "true", + "GITHUB_WORKFLOW_REF" => "o/r/.github/workflows/release-please.yml@refs/heads/topic" } + }.each do |label, environment| + cleared = { "GITHUB_ACTIONS" => nil, "GITHUB_WORKFLOW_REF" => nil, "GH_TOKEN" => nil } + _stdout, stderr, status = Open3.capture3(cleared.merge(environment), RbConfig.ruby, script, "prepare-pr") + expect(status.success?).to be(false), label + expect(stderr).to include("release:prepare:pr only runs in .github/workflows/release-please.yml on main"), label + end + end +end + +RSpec.describe ReleasePreparation::GitHub do + let(:input) { { branch: { repositoryNameWithOwner: "owner/repo", branchName: "branch" }, expectedHeadOid: "a" * 40 } } + + def status(success) + instance_double(Process::Status, success?: success) + end + + it "sends the mutation and its input to gh on stdin and returns the new commit" do + response = { data: { createCommitOnBranch: { commit: { oid: "b" * 40, url: "https://github.invalid/c" } } } } + allow(Open3).to receive(:capture3).and_return([JSON.generate(response), "", status(true)]) + + expect(described_class.new.create_commit(input)).to eq("b" * 40) + expect(Open3).to have_received(:capture3) do |*command, stdin_data:| + expect(command).to eq(%w[gh api graphql --input -]) + body = JSON.parse(stdin_data) + expect(body.keys).to eq(%w[query variables]) + expect(body.fetch("query")).to include("createCommitOnBranch(input: $input)") + expect(body.fetch("variables")).to eq("input" => JSON.parse(JSON.generate(input))) + end + end + + { + "a failed gh call" => [["", "HTTP 401: Bad credentials", false], /gh api graphql failed: HTTP 401/], + "a GraphQL error" => [[JSON.generate(errors: [{ type: "STALE_DATA", message: "Expected head" }]), "", true], + /createCommitOnBranch failed: .*STALE_DATA/], + "a response without a commit" => [[JSON.generate(data: { createCommitOnBranch: nil }), "", true], + /createCommitOnBranch returned no commit/] + }.each do |label, ((stdout, stderr, success), failure)| + it "raises on #{label}" do + allow(Open3).to receive(:capture3).and_return([stdout, stderr, status(success)]) + expect { described_class.new.create_commit(input) }.to raise_error(failure) + end + end +end diff --git a/spec/release_train_spec.rb b/spec/release_train_spec.rb index 0698cd3e..c0be62a0 100644 --- a/spec/release_train_spec.rb +++ b/spec/release_train_spec.rb @@ -8,6 +8,7 @@ require "yaml" require_relative "../scripts/release_train" require_relative "../scripts/release_candidate" +require_relative "../scripts/release_preparation" RSpec.describe ReleaseTrain do def captured_train @@ -192,6 +193,45 @@ def load_workflow(name) permission-pull-requests]) end + # The App token and the release PR head meet only as data: tooling comes from + # main and nothing runs from the release-pr checkout. + it "prepares the open release PR from main tooling after Release Please" do + workflow, = load_workflow("release-please.yml") + expect(workflow.fetch("env")).to eq("MISE_ENV" => "ci", "MISE_LOCKED" => "1") + steps = workflow.fetch("jobs").fetch("release-please").fetch("steps") + release = steps.index { |step| step.fetch("uses", "").start_with?("googleapis/release-please-action@") } + find, main, data, ruby, mise, prepare = steps.drop(release + 1) + expect(steps.size).to eq(release + 7) + + token = "${{ steps.app-token.outputs.token }}" + head = "${{ steps.release-pr.outputs.sha }}" + expect(find).to include("id" => "release-pr") + expect(find).not_to have_key("if") + expect(find.fetch("env")).to eq("GH_TOKEN" => token, "RELEASE_BRANCH" => ReleasePreparation::BRANCH) + expect(find.fetch("run")).to include("pulls?state=open&base=main&head=$GITHUB_REPOSITORY_OWNER:$RELEASE_BRANCH") + .and include('"sha=$sha" >> "$GITHUB_OUTPUT"') + expect([main, data, ruby, mise, prepare].map { |step| step["if"] }).to all(eq("steps.release-pr.outputs.sha != ''")) + + checkout = steps.find { |step| step.fetch("uses", "").start_with?("actions/checkout@") }.fetch("uses") + expect([main, data].map { |step| step.fetch("uses") }).to eq([checkout, checkout]) + expect(main.fetch("with")).to eq("token" => token, "persist-credentials" => false) + expect(data.fetch("with")).to eq("ref" => head, "path" => "release-pr", "token" => token, + "persist-credentials" => false) + + # Runtime setup matches the release workflow exactly, with no caches. + published = load_workflow("release.yml").first.fetch("jobs").fetch("publish").fetch("steps") + [ruby, mise].each do |step| + expect(published).to include(step.except("if")) + end + expect(prepare.fetch("run")).to eq("mise run release:prepare:pr") + expect(prepare.fetch("env")).to eq("GH_TOKEN" => token, "RELEASE_HEAD" => head, "RELEASE_ROOT" => "release-pr") + + expect(steps.filter_map { |step| step["run"] && step.fetch("name") }) + .to eq(["Check App references", find.fetch("name"), prepare.fetch("name")]) + expect(steps.select { |step| step.key?("working-directory") }).to be_empty + expect(steps.select { |step| step.fetch("env", {}).value?(token) }).to eq([find, prepare]) + end + # RubyGems.org trusted publishers match this exact filename and environment. it "publishes only from v* tags in the release environment with job-scoped OIDC" do workflow, triggers = load_workflow("release.yml") From a7121749b7304feede60b8e79e420aacb4b79c2c Mon Sep 17 00:00:00 2001 From: Jim Myhrberg Date: Mon, 16 Nov 2026 18:45:13 +0000 Subject: [PATCH 2/2] fix(release): read the release branch ref and match the workflow ref exactly Take the prepared head from the branch ref that createCommitOnBranch compares against, since a PR's head.sha can lag the push that just rebuilt the branch. Require the exact Release Please workflow ref on main instead of a substring that also matched branches such as maintenance, and cover the prepare-pr command end to end through a stub gh. --- .github/workflows/release-please.yml | 10 +++++-- scripts/release.rb | 4 +-- spec/release_preparation_spec.rb | 43 ++++++++++++++++++++++++---- spec/release_train_spec.rb | 1 + 4 files changed, 49 insertions(+), 9 deletions(-) diff --git a/.github/workflows/release-please.yml b/.github/workflows/release-please.yml index baf96add..e13c38d7 100644 --- a/.github/workflows/release-please.yml +++ b/.github/workflows/release-please.yml @@ -49,14 +49,20 @@ jobs: config-file: .github/release-please-config.json manifest-file: .github/.release-please-manifest.json # Looked up independently: Release Please reports no PR when its body is - # unchanged, and the owner-qualified head filter excludes forks. + # unchanged, and the owner-qualified head filter excludes forks. The SHA + # comes from the branch ref that createCommitOnBranch compares against; + # a PR's head.sha can lag a push that just rebuilt the branch. - id: release-pr name: Find the release PR env: GH_TOKEN: ${{ steps.app-token.outputs.token }} RELEASE_BRANCH: release-please--branches--main--components--connectrpc run: | - sha="$(gh api "repos/$GITHUB_REPOSITORY/pulls?state=open&base=main&head=$GITHUB_REPOSITORY_OWNER:$RELEASE_BRANCH" --jq '.[0].head.sha // empty')" + number="$(gh api "repos/$GITHUB_REPOSITORY/pulls?state=open&base=main&head=$GITHUB_REPOSITORY_OWNER:$RELEASE_BRANCH" --jq '.[0].number // empty')" + sha="" + if [ -n "$number" ]; then + sha="$(gh api "repos/$GITHUB_REPOSITORY/git/ref/heads/$RELEASE_BRANCH" --jq '.object.sha')" + fi echo "sha=$sha" >> "$GITHUB_OUTPUT" # Tooling comes from main. The release PR head is only read as data, so # release-branch code never runs with the App token. diff --git a/scripts/release.rb b/scripts/release.rb index 11b88ff1..3789797b 100644 --- a/scripts/release.rb +++ b/scripts/release.rb @@ -13,8 +13,8 @@ when ["prepare-pr"] require_relative "release_preparation" # The App-token commit only runs from the Release Please workflow on main. - workflow = ENV.fetch("GITHUB_WORKFLOW_REF", "") - unless ENV["GITHUB_ACTIONS"] == "true" && workflow.include?("/.github/workflows/release-please.yml@refs/heads/main") + workflow = "#{ENV.fetch('GITHUB_REPOSITORY', '')}/.github/workflows/release-please.yml@refs/heads/main" + unless ENV["GITHUB_ACTIONS"] == "true" && ENV["GITHUB_WORKFLOW_REF"] == workflow abort "release:prepare:pr only runs in .github/workflows/release-please.yml on main" end diff --git a/spec/release_preparation_spec.rb b/spec/release_preparation_spec.rb index 5c2b023a..c7cc7a92 100644 --- a/spec/release_preparation_spec.rb +++ b/spec/release_preparation_spec.rb @@ -165,16 +165,49 @@ def decoded_additions(input) end end + let(:script) { File.expand_path("../scripts/release.rb", __dir__) } + let(:workflow_ref) { "o/r/.github/workflows/release-please.yml@refs/heads/main" } + + it "commits through gh when run from the Release Please workflow on main" do + release_branch(:minor) do |train, head, _version| + Dir.mktmpdir("connectrpc-preparation-gh-") do |bin| + body = File.join(bin, "body.json") + File.write(File.join(bin, "gh"), <<~SH) + #!/bin/sh + cat > "#{body}" + echo '{"data":{"createCommitOnBranch":{"commit":{"oid":"#{'d' * 40}"}}}}' + SH + File.chmod(0o755, File.join(bin, "gh")) + environment = { "GITHUB_ACTIONS" => "true", "GITHUB_REPOSITORY" => "o/r", "GITHUB_WORKFLOW_REF" => workflow_ref, + "RELEASE_ROOT" => train.root, "RELEASE_HEAD" => head, + "PATH" => "#{bin}:#{ENV.fetch('PATH')}" } + + stdout, stderr, status = Open3.capture3(environment, RbConfig.ruby, script, "prepare-pr") + + expect(status.success?).to be(true), stderr + expect(stdout).to include("d" * 40) + input = JSON.parse(File.read(body)).dig("variables", "input") + expect(input.fetch("branch")).to eq("repositoryNameWithOwner" => "o/r", "branchName" => described_class::BRANCH) + expect(input.fetch("expectedHeadOid")).to eq(head) + expect(input.dig("fileChanges", "additions").map { |addition| addition.fetch("path") }) + .to eq(locally_prepared(train).keys.sort) + end + end + end + it "refuses to run outside the Release Please workflow on main" do - script = File.expand_path("../scripts/release.rb", __dir__) { "local" => {}, - "release tag" => { "GITHUB_ACTIONS" => "true", + "release tag" => { "GITHUB_ACTIONS" => "true", "GITHUB_REPOSITORY" => "o/r", "GITHUB_WORKFLOW_REF" => "o/r/.github/workflows/release.yml@refs/tags/v0.2.0" }, - "other branch" => { "GITHUB_ACTIONS" => "true", - "GITHUB_WORKFLOW_REF" => "o/r/.github/workflows/release-please.yml@refs/heads/topic" } + "other branch" => { "GITHUB_ACTIONS" => "true", "GITHUB_REPOSITORY" => "o/r", + "GITHUB_WORKFLOW_REF" => "o/r/.github/workflows/release-please.yml@refs/heads/topic" }, + "branch prefixed with main" => { "GITHUB_ACTIONS" => "true", "GITHUB_REPOSITORY" => "o/r", + "GITHUB_WORKFLOW_REF" => "#{workflow_ref}tenance" }, + "other repository" => { "GITHUB_ACTIONS" => "true", "GITHUB_REPOSITORY" => "o/r", + "GITHUB_WORKFLOW_REF" => workflow_ref.sub("o/r", "x/y") } }.each do |label, environment| - cleared = { "GITHUB_ACTIONS" => nil, "GITHUB_WORKFLOW_REF" => nil, "GH_TOKEN" => nil } + cleared = { "GITHUB_ACTIONS" => nil, "GITHUB_REPOSITORY" => nil, "GITHUB_WORKFLOW_REF" => nil, "GH_TOKEN" => nil } _stdout, stderr, status = Open3.capture3(cleared.merge(environment), RbConfig.ruby, script, "prepare-pr") expect(status.success?).to be(false), label expect(stderr).to include("release:prepare:pr only runs in .github/workflows/release-please.yml on main"), label diff --git a/spec/release_train_spec.rb b/spec/release_train_spec.rb index c0be62a0..5e7cda11 100644 --- a/spec/release_train_spec.rb +++ b/spec/release_train_spec.rb @@ -209,6 +209,7 @@ def load_workflow(name) expect(find).not_to have_key("if") expect(find.fetch("env")).to eq("GH_TOKEN" => token, "RELEASE_BRANCH" => ReleasePreparation::BRANCH) expect(find.fetch("run")).to include("pulls?state=open&base=main&head=$GITHUB_REPOSITORY_OWNER:$RELEASE_BRANCH") + .and include("git/ref/heads/$RELEASE_BRANCH\" --jq '.object.sha'") .and include('"sha=$sha" >> "$GITHUB_OUTPUT"') expect([main, data, ruby, mise, prepare].map { |step| step["if"] }).to all(eq("steps.release-pr.outputs.sha != ''"))