A platform for community discussion. Free, open, simple.
DEV: Update `stage_security_fixes` rake task (#37346)
David Taylor0f1c9574f20d
diff --git a/Gemfile b/Gemfileindex 72ab08f3c4b..18ecc0c61e5 100644--- a/Gemfile+++ b/Gemfile@@ -290,6 +290,7 @@ endgem "dry-initializer", "~> 3.1"gem "parallel"+gem "tty-prompt", require: false# for discourse-zendesk-plugingem "inflection", require: falsediff --git a/Gemfile.lock b/Gemfile.lockindex cd95b00fd92..ce830c63efe 100644--- a/Gemfile.lock+++ b/Gemfile.lock@@ -394,6 +394,8 @@ GEMparser (3.3.10.0)ast (~> 2.4.1)racc+ pastel (0.8.0)+ tty-color (~> 0.5)pdf-reader (2.15.0)Ascii85 (>= 1.0, < 3.0, != 2.0.0)afm (>= 0.2.1, < 2)@@ -689,6 +691,16 @@ GEMtsort (0.2.0)ttfunk (1.8.0)bigdecimal (~> 3.1)+ tty-color (0.6.0)+ tty-cursor (0.7.1)+ tty-prompt (0.23.1)+ pastel (~> 0.8)+ tty-reader (~> 0.8)+ tty-reader (0.9.0)+ tty-cursor (~> 0.7)+ tty-screen (~> 0.8)+ wisper (~> 2.0)+ tty-screen (0.8.2)tzinfo (2.0.6)concurrent-ruby (~> 1.0)tzinfo-data (1.2025.2)@@ -712,6 +724,7 @@ GEMcrack (>= 0.3.2)hashdiff (>= 0.4.0, < 2.0.0)webrick (1.9.2)+ wisper (2.0.1)xpath (3.2.0)nokogiri (~> 1.8)yaml-lint (0.1.2)@@ -896,6 +909,7 @@ DEPENDENCIEStokenizerstrilogyttfunk+ tty-prompttzinfo-dataunfunicorn@@ -1096,6 +1110,7 @@ CHECKSUMSparallel (1.27.0) sha256=4ac151e1806b755fb4e2dc2332cbf0e54f2e24ba821ff2d3dcf86bf6dc4ae130parallel_tests (5.5.0) sha256=783c1e4da27c4096a7b360f080ae03cf1122cb0dfdb4fe827013e0521642f666parser (3.3.10.0) sha256=ce3587fa5cc55a88c4ba5b2b37621b3329aadf5728f9eafa36bbd121462aabd6+ pastel (0.8.0) sha256=481da9fb7d2f6e6b1a08faf11fa10363172dc40fd47848f096ae21209f805a75pdf-reader (2.15.0) sha256=c5025750bec8de7b11cfd1d1ccc2b944d2782c3638cd15b5ee1531d1206c0886pg (1.6.2) sha256=58614afd405cc9c2c9e15bffe8432e0d6cfc58b722344ad4a47c73a85189c875pg (1.6.2-aarch64-linux) sha256=0503c6be5b0ca5ca3aaf91f2ed638f90843313cb81e8e7d7b60ad4bb62c3d131@@ -1235,6 +1250,11 @@ CHECKSUMStrilogy (2.9.0) sha256=a2d63b663ba68a4758e15d1f9afb228f5d16efc7fe7cea68699e1c106ef6067ftsort (0.2.0) sha256=9650a793f6859a43b6641671278f79cfead60ac714148aabe4e3f0060480089fttfunk (1.8.0) sha256=a7cbc7e489cc46e979dde04d34b5b9e4f5c8f1ee5fc6b1a7be39b829919d20ca+ tty-color (0.6.0) sha256=6f9c37ca3a4e2367fb2e6d09722762647d6f455c111f05b59f35730eeb24332a+ tty-cursor (0.7.1) sha256=79534185e6a777888d88628b14b6a1fdf5154a603f285f80b1753e1908e0bf48+ tty-prompt (0.23.1) sha256=fcdbce905238993f27eecfdf67597a636bc839d92192f6a0eef22b8166449ec8+ tty-reader (0.9.0) sha256=c62972c985c0b1566f0e56743b6a7882f979d3dc32ff491ed490a076f899c2b1+ tty-screen (0.8.2) sha256=c090652115beae764336c28802d633f204fb84da93c6a968aa5d8e319e819b50tzinfo (2.0.6) sha256=8daf828cc77bcf7d63b0e3bdb6caa47e2272dcfaf4fbfe46f8c3a9df087a829btzinfo-data (1.2025.2) sha256=a92375a1fbb47d38fe88fd514c40a38cc8f97d168da2a6479f15185e86470939unf (0.2.0) sha256=e6bcc2e101d80e3f9459753db747d5926aada1aaaf61e629e93359da9a5b04ab@@ -1248,6 +1268,7 @@ CHECKSUMSweb-push (3.0.1) sha256=5b4dd2f2bba3bd8951da6416492fe920a6f203d14d3080f943c5d01c0cc4b18dwebmock (3.25.1) sha256=ab9d5d9353bcbe6322c83e1c60a7103988efc7b67cd72ffb9012629c3d396323webrick (1.9.2) sha256=beb4a15fc474defed24a3bda4ffd88a490d517c9e4e6118c3edce59e45864131+ wisper (2.0.1) sha256=ce17bc5c3a166f241a2e6613848b025c8146fce2defba505920c1d1f3f88fae6xpath (3.2.0) sha256=6dfda79d91bb3b949b947ecc5919f042ef2f399b904013eb3ef6d20dd3a4082eyaml-lint (0.1.2) sha256=e3960b171766ae187338a169815e99fe10fcb0d9c22b1c539e8d57e114324c8ayard (0.9.38) sha256=721fb82afb10532aa49860655f6cc2eaa7130889df291b052e1e6b268283010fdiff --git a/lib/tasks/release.rake b/lib/tasks/release.rakeindex 7a13b765179..e205ea9a23c 100644--- a/lib/tasks/release.rake+++ b/lib/tasks/release.rake@@ -1,5 +1,7 @@# frozen_string_literal: true+require "tty-prompt"+module ReleaseUtilsPRIMARY_RELEASE_TAG = "release"RELEASE_TAGS = [PRIMARY_RELEASE_TAG, "beta", "latest-release"].freeze@@ -109,17 +111,54 @@ module ReleaseUtilsfalseend- def self.make_pr(base:, branch:)- title_and_body = [- "--title",- git("log", "-1", branch, "--pretty=%s").strip,- "--body",- git("log", "-1", branch, "--pretty=%b").strip,- ]+ def self.confirm(msg)+ return if test_mode?+ prompt = TTY::Prompt.new+ raise "Aborted" unless prompt.yes?(msg)+ end++ def self.merge_pr(base:, branch:)+ if dry_run?+ puts "[DRY RUN] Skipping merge of #{branch}"+ return+ end++ loop do+ confirm "Ready to merge #{branch}?"++ if test_mode?+ git "push", "origin", "#{branch}:#{base}"+ break+ else+ success = gh("pr", "merge", branch, "--rebase", "--delete-branch")+ break if success+ puts "Merge failed. Maybe the PR isn't approved yet, or there's a conflict."+ end+ end++ puts "Merge successful"+ end++ def self.make_pr(base:, branch:, title: nil, body: nil, draft: false)+ title ||= git("log", "-1", branch, "--pretty=%s").strip+ body ||= git("log", "-1", branch, "--pretty=%b").strip++ title_and_body = ["--title", title, "--body", body]+ draft_flag = draft ? ["--draft"] : []success =- gh("pr", "create", "--base", base, "--head", branch, *title_and_body, "--label", PR_LABEL) ||- gh("pr", "edit", branch, *title_and_body, "--add-label", PR_LABEL)+ gh(+ "pr",+ "create",+ "--base",+ base,+ "--head",+ branch,+ *title_and_body,+ *draft_flag,+ "--label",+ PR_LABEL,+ ) || gh("pr", "edit", branch, *title_and_body, "--add-label", PR_LABEL)raise "Failed to create or update PR" unless successend@@ -362,4 +401,96 @@ namespace :release doputs "Done! Branch #{pr_branch_name} has been pushed to origin and a pull request has been created."end++ desc <<~DESC+ Stage security fixes from private-mirror PRs into a single branch for review/merge.+ Fetches open PRs from private-mirror and presents an interactive selection.+ e.g.+ bin/rake "release:stage_security_fixes[main]"+ bin/rake "release:stage_security_fixes[release/2025.11]"+ DESC+ task "stage_security_fixes", [:base] do |t, args|+ base = args[:base]+ if !base.start_with?("release/") && !%w[stable main].include?(base)+ raise "Unknown base: #{base.inspect}"+ end++ fix_refs = ENV["SECURITY_FIX_REFS"]&.split(",")&.map(&:strip)++ if fix_refs.nil? || fix_refs.empty?+ json_output, status =+ Open3.capture2(+ "gh",+ "pr",+ "list",+ "--repo",+ "discourse/discourse-private-mirror",+ "--base",+ base,+ "--state",+ "open",+ "--json",+ "number,title,headRefName",+ "--limit",+ "100",+ )+ raise "Failed to fetch PRs from private-mirror" if !status.success?++ prs = JSON.parse(json_output)+ raise "No open PRs found targeting #{base} on private-mirror" if prs.empty?++ prompt = TTY::Prompt.new+ choices =+ prs.map { |pr| { name: "##{pr["number"]}: #{pr["title"]}", value: pr["headRefName"] } }++ selected =+ prompt.multi_select(+ "Select security fix PRs to include (space to toggle, enter to finish):",+ choices,+ default: [],+ per_page: choices.size,+ )+ raise "No PRs selected" if selected.empty?++ fix_refs = selected.map { |branch| "privatemirror/#{branch}" }+ end++ puts "Staging security fixes for #{base} branch: #{fix_refs.inspect}"++ branch = "security/#{base}-security-fixes"++ ReleaseUtils.with_clean_worktree(base) do+ ReleaseUtils.git "branch", "-D", branch if ReleaseUtils.ref_exists?(branch)+ ReleaseUtils.git "checkout", "-b", branch++ fix_refs.each do |ref|+ origin, origin_branch = ref.split("/", 2)+ ReleaseUtils.git "fetch", origin, origin_branch++ first_commit_on_branch =+ ReleaseUtils.git("log", "--format=%H", "origin/#{base}..#{ref}").lines.last.strip+ ReleaseUtils.git "cherry-pick", "#{first_commit_on_branch}^..#{ref}"+ end++ puts "Finished merging commits into a locally-staged #{branch} branch. Git log is:"+ puts ReleaseUtils.git("log", "origin/#{base}..#{branch}")++ ReleaseUtils.confirm "Check the log above. Ready to push this branch to the origin and create a PR?"+ ReleaseUtils.git("push", "-f", "--set-upstream", "origin", branch)++ ReleaseUtils.make_pr(+ base: base,+ branch: branch,+ title: "Security fixes for #{base}",+ body: <<~MD,+ > :warning: This PR should not be merged via the GitHub web interface+ >+ > It should only be merged using the associated `bin/rake release:stage_security_fixes` task.+ MD+ draft: true,+ )+ puts "Do not merge the PR via the GitHub web interface. Get it approved, then come back here to continue."+ ReleaseUtils.merge_pr(base: base, branch: branch)+ end+ endenddiff --git a/lib/tasks/version_bump.rake b/lib/tasks/version_bump.rakedeleted file mode 100644index b2ea1b44b52..00000000000--- a/lib/tasks/version_bump.rake+++ /dev/null@@ -1,237 +0,0 @@-# frozen_string_literal: true--def dry_run?- !!ENV["DRY_RUN"]-end--def test_mode?- ENV["RUNNING_VERSION_BUMP_IN_RSPEC_TESTS"] == "1"-end--class PlannedTag- attr_reader :name, :message-- def initialize(name:, message:)- @name = name- @message = message- end-end--class PlannedCommit- attr_reader :version, :tags, :ref-- def initialize(version:, tags: [])- @version = version- @tags = tags- end-- def perform!- write_version(@version)- git "add", "lib/version.rb"- git "commit", "-m", "Bump version to v#{@version}"- @ref = git("rev-parse", "HEAD").strip- end-end--def read_version_rb- File.read("lib/version.rb")-end--def parse_current_version- version = read_version_rb[/STRING = "(.*)"/, 1]- raise "Unable to parse current version" if version.nil?- puts "Parsed current version: #{version.inspect}"- version-end--def write_version(version)- File.write("lib/version.rb", read_version_rb.sub(/STRING = ".*"/, "STRING = \"#{version}\""))-end--def git(*args, allow_failure: false, silent: false)- puts "> git #{args.inspect}" unless silent- args.prepend(*%w[-c commit.gpgsign=false]) if test_mode?- stdout, stderr, status = Open3.capture3({ "LEFTHOOK" => "0" }, "git", *args)- if !status.success? && !allow_failure- raise "Command failed: git #{args.inspect}\n#{stdout.indent(2)}\n#{stderr.indent(2)}"- end- stdout-end--def ref_exists?(ref)- git "rev-parse", "--verify", ref- true-rescue StandardError- false-end--def confirm(msg)- loop do- print "#{msg} (yes/no)..."- break if test_mode?-- response = $stdin.gets.strip-- case response.downcase- when "no"- raise "Aborted"- when "yes"- break- else- puts "unknown response: #{response}"- end- end-end--def make_commits(commits:, branch:, base:)- raise "You have other staged changes. Aborting." if !git("diff", "--cached").empty?-- git "branch", "-D", branch if ref_exists?(branch)- git "checkout", "-b", branch-- commits.each(&:perform!)-- git("push", "-f", "--set-upstream", "origin", branch)-- make_pr(- base: base,- branch: branch,- title:- "Version bump#{"s" if commits.length > 1} for #{base}: #{commits.map { |c| "v#{c.version}" }.join(", ")}",- )-end--def make_pr(base:, branch:, title:)- params = { expand: 1, title: title, body: <<~MD }- > :warning: This PR should not be merged via the GitHub web interface- >- > It should only be merged (via fast-forward) using the associated `bin/rake version_bump:*` task.- MD-- if !test_mode?- open_command =- case RbConfig::CONFIG["host_os"]- when /darwin|mac os/- "open"- when /linux|solaris|bsd/- "xdg-open"- when /mswin|msys|mingw|cygwin|bccwin|wince|emc/- "start"- else- raise "Unsupported OS"- end-- system(- open_command,- "https://github.com/discourse/discourse/compare/#{base}...#{branch}?#{params.to_query}",- exception: true,- )- end-- puts "Do not merge the PR via the GitHub web interface. Get it approved, then come back here to continue."-end--def fastforward(base:, branch:)- if dry_run?- puts "[DRY RUN] Skipping fastforward of #{base}"- return- end-- confirm "Ready to merge? This will fast-forward #{base} to #{branch}"- begin- git "push", "origin", "#{branch}:#{base}"- rescue => e- raise <<~MSG- #{e.message}- Error occured during fastforward. Maybe another commit was added to `#{base}` since the PR was created, or maybe the PR wasn't approved.- Don't worry, this is not unusual. To update the branch and try again, rerun this script again. The existing PR and approval will be reused.- MSG- end- puts "Merge successful"-end--def stage_tags(commits)- puts "Staging tags locally..."- commits.each do |commit|- commit.tags.each { |tag| git "tag", "-f", "-a", tag.name, "-m", tag.message, commit.ref }- end-end--def push_tags(commits)- tag_names = commits.flat_map { |commit| commit.tags.map(&:name) }-- if dry_run?- puts "[DRY RUN] Skipping pushing tags to origin (#{tag_names.join(", ")})"- return- end-- confirm "Ready to push tags #{tag_names.join(", ")} to origin?"- tag_names.each { |tag_name| git "push", "-f", "origin", "refs/tags/#{tag_name}" }-end--def with_clean_worktree(origin_branch)- origin_url = git("remote", "get-url", "origin").strip-- if !test_mode? && !origin_url.include?("discourse/discourse")- raise "Expected 'origin' remote to point to discourse/discourse (got #{origin_url})"- end-- git "fetch", "origin", origin_branch- path = "#{Rails.root}/tmp/version-bump-worktree-#{SecureRandom.hex}"- begin- FileUtils.mkdir_p(path)- git "worktree", "add", path, "origin/#{origin_branch}"- Dir.chdir(path) { yield } # rubocop:disable Discourse/NoChdir- ensure- puts "Cleaning up temporary worktree..."- git "worktree", "remove", "--force", path, silent: true, allow_failure: true- FileUtils.rm_rf(path)- end-end--desc <<~DESC- squash-merge many security fixes into a single branch for review/merge.- Pass a list of comma-separated branches in the SECURITY_FIX_REFS env var, including the remote name.- Pass the name of the destination branch as the argument of the rake task.- e.g.- SECURITY_FIX_REFS='privatemirror/mybranch1,privatemirror/mybranch2' bin/rake "version_bump:stage_security_fixes[main]"-DESC-task "version_bump:stage_security_fixes", [:base] do |t, args|- base = args[:base]- raise "Unknown base: #{base.inspect}" if %w[stable main].exclude?(base)-- fix_refs = ENV["SECURITY_FIX_REFS"]&.split(",")&.map(&:strip)- raise "No branches specified in SECURITY_FIX_REFS env" if fix_refs.nil? || fix_refs.empty?-- fix_refs.each do |ref|- if !ref.include?("/")- raise "Ref #{ref} did not specify an origin. Please specify the origin, e.g. privatemirror/mybranch"- end- end-- puts "Staging security fixes for #{base} branch: #{fix_refs.inspect}"-- branch = "security/#{base}-security-fixes"-- with_clean_worktree(base) do- git "branch", "-D", branch if ref_exists?(branch)- git "checkout", "-b", branch-- fix_refs.each do |ref|- origin, origin_branch = ref.split("/", 2)- git "fetch", origin, origin_branch-- first_commit_on_branch = git("log", "--format=%H", "origin/#{base}..#{ref}").lines.last.strip- git "cherry-pick", "#{first_commit_on_branch}^..#{ref}"- end-- puts "Finished merging commits into a locally-staged #{branch} branch. Git log is:"- puts git("log", "origin/#{base}..#{branch}")-- confirm "Check the log above. Ready to push this branch to the origin and create a PR?"- git("push", "-f", "--set-upstream", "origin", branch)-- make_pr(base: base, branch: branch, title: "Security fixes for #{base}")- fastforward(base: base, branch: branch)- end-enddiff --git a/spec/tasks/release_spec.rb b/spec/tasks/release_spec.rbindex 09e7e57a2d1..b073f840b26 100644--- a/spec/tasks/release_spec.rb+++ b/spec/tasks/release_spec.rb@@ -458,4 +458,49 @@ RSpec.describe "tasks/version_bump" do)endend++ describe "release:stage_security_fixes" do+ it "stages a PR of multiple security fixes" do+ Dir.chdir(origin_path) do+ run "git", "checkout", "-b", "security-fix-one"++ File.write("firstfile.txt", "contents")+ run "git", "add", "firstfile.txt"+ run "git", "-c", "commit.gpgsign=false", "commit", "-m", "security fix one, commit one"+ File.write("secondfile.txt", "contents")+ run "git", "add", "secondfile.txt"+ run "git", "-c", "commit.gpgsign=false", "commit", "-m", "security fix one, commit two"++ run "git", "checkout", "main"+ run "git", "checkout", "-b", "security-fix-two"+ File.write("somefile.txt", "contents")+ run "git", "add", "somefile.txt"+ run "git", "-c", "commit.gpgsign=false", "commit", "-m", "security fix two"+ end++ Dir.chdir(local_path) do+ capture_stdout do+ ENV["SECURITY_FIX_REFS"] = "origin/security-fix-one,origin/security-fix-two"+ invoke_rake_task("release:stage_security_fixes", "main")+ ensure+ ENV.delete("SECURITY_FIX_REFS")+ end+ end++ Dir.chdir(origin_path) do+ expect(run("git", "log", "--pretty=%s", "main").lines.map(&:strip)).to eq(+ [+ "security fix two",+ "security fix one, commit two",+ "security fix one, commit one",+ "Initial commit",+ ],+ )++ expect(run("git", "show", "main:somefile.txt")).to eq("contents")+ expect(run("git", "show", "main:firstfile.txt")).to eq("contents")+ expect(run("git", "show", "main:secondfile.txt")).to eq("contents")+ end+ end+ endenddiff --git a/spec/tasks/version_bump_spec.rb b/spec/tasks/version_bump_spec.rbdeleted file mode 100644index 068375126f5..00000000000--- a/spec/tasks/version_bump_spec.rb+++ /dev/null@@ -1,100 +0,0 @@-# frozen_string_literal: true--def run(*args)- out, err, status = Open3.capture3(*args)- raise "Command failed: #{args.inspect}\n#{out}\n#{err}" unless status.success?- out-end--def fake_version_rb(version)- File.read("#{Rails.root}/lib/version.rb").sub(/STRING = ".*"/, "STRING = \"#{version}\"")-end--RSpec.describe "tasks/version_bump" do- let(:tmpdir) { Dir.mktmpdir }- let(:origin_path) { "#{tmpdir}/origin-repo" }- let(:local_path) { "#{tmpdir}/local-repo" }-- before do- ENV["RUNNING_VERSION_BUMP_IN_RSPEC_TESTS"] = "1"-- Rake::Task.clear- Discourse::Application.load_tasks-- FileUtils.mkdir_p origin_path-- Dir.chdir(origin_path) do- FileUtils.mkdir_p "lib"- FileUtils.mkdir_p "tmp"-- File.write(".gitignore", "tmp\n")- File.write("lib/version.rb", fake_version_rb("3.2.0.beta1-latest"))-- run "git", "init"- run "git", "checkout", "-b", "main"- run "git", "add", "."- run "git", "-c", "commit.gpgsign=false", "commit", "-m", "Initial commit"-- run "git", "checkout", "-b", "stable"- File.write("#{origin_path}/lib/version.rb", fake_version_rb("3.1.2"))- run "git", "add", "."- run "git", "-c", "commit.gpgsign=false", "commit", "-m", "Previous stable version bump"-- run "git", "checkout", "main"- run "git", "config", "receive.denyCurrentBranch", "ignore"- end-- run "git", "clone", "-b", "main", origin_path, local_path- end-- after do- FileUtils.remove_entry(tmpdir)- ENV.delete("RUNNING_VERSION_BUMP_IN_RSPEC_TESTS")- end-- it "can stage a PR of multiple security fixes using version_bump:stage_security_fixes" do- Dir.chdir(origin_path) do- run "git", "checkout", "-b", "security-fix-one"-- File.write("firstfile.txt", "contents")- run "git", "add", "firstfile.txt"- run "git", "-c", "commit.gpgsign=false", "commit", "-m", "security fix one, commit one"- File.write("secondfile.txt", "contents")- run "git", "add", "secondfile.txt"- run "git", "-c", "commit.gpgsign=false", "commit", "-m", "security fix one, commit two"-- run "git", "checkout", "main"- run "git", "checkout", "-b", "security-fix-two"- File.write("somefile.txt", "contents")- run "git", "add", "somefile.txt"- run "git", "-c", "commit.gpgsign=false", "commit", "-m", "security fix two"- end-- Dir.chdir(local_path) do- output =- capture_stdout do- ENV["SECURITY_FIX_REFS"] = "origin/security-fix-one,origin/security-fix-two"- invoke_rake_task("version_bump:stage_security_fixes", "main")- ensure- ENV.delete("SECURITY_FIX_REFS")- end- end-- Dir.chdir(origin_path) do- # Check each fix has been added as a single commit, with the message matching the first commit on the branch- expect(run("git", "log", "--pretty=%s", "main").lines.map(&:strip)).to eq(- [- "security fix two",- "security fix one, commit two",- "security fix one, commit one",- "Initial commit",- ],- )-- # Check all the files from both fixes are present- expect(run("git", "show", "main:somefile.txt")).to eq("contents")- expect(run("git", "show", "main:firstfile.txt")).to eq("contents")- expect(run("git", "show", "main:secondfile.txt")).to eq("contents")- end- end-end