secupdater 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 4f19feed6401e9c35fd600135fcd76372d6f2b1146648996958119ac0063d5e3
4
- data.tar.gz: 7fa86bc7f193bbe245dd672f9b1b362e3227917ebd92a78e28792cd810dbae4d
3
+ metadata.gz: 5ed9ba8653acb0daf90dc07f3b0deb0e7be9c7ed8620bd876f86f1c378f82454
4
+ data.tar.gz: 1fb043a7cbaf67de3c0acda6fe4f30526da35604158b6f44587dfb4b3b9e554d
5
5
  SHA512:
6
- metadata.gz: c0577d54657596f3fd338660330dde5da2dbee749a2c1349570ee64706583663850b4c080b8caccb275e63e1bd439ac3576ae7b43570498f1d7f4f82de3339ca
7
- data.tar.gz: 4e07f424812cd76787ffd12226fc15a26c1c2ccc2c1b1075da706e28d3496f9acaccfc39a90b1a48910502723355a2e6b28be7910c7f6c4ad7fb48143406c86c
6
+ metadata.gz: d02a837690cb83ce6f043f7e30fd65bb37185fa0ffc1295520e973352a329b4139d0860c98807c6c9c0a008028afbd64d6e5fee2232d5885a1f2179274c1bfc6
7
+ data.tar.gz: e679ccffe1c7bbdd76efa4238954dfb753baa36715535b121e30ec24316a6c3f751dd41df8760bfe8e48808535e9c87da5b7453b51b359ab49b1138c5e7b2a70
@@ -0,0 +1,95 @@
1
+ # Runs secupdater from one central GitLab project against every project in a
2
+ # group that has opted in by adding the `secupdater` topic (Settings > General >
3
+ # Topics).
4
+ #
5
+ # Setup:
6
+ # 1. Create a group access token on the group with the Developer role and the
7
+ # `api` scope, and add it to this project as a masked CI/CD variable called
8
+ # SECUPDATER_GITLAB_TOKEN.
9
+ # 2. Set SECUPDATER_GROUP and SECUPDATER_VERSION below.
10
+ # 3. Add a pipeline schedule (e.g. hourly) to this project.
11
+ #
12
+ # The discover job audits every opted-in project's Gemfile.lock. The update job
13
+ # then runs secupdater, in a container on that project's own Ruby, for each one
14
+ # with advisories or with open secupdater MRs (so it can close the ones that are
15
+ # no longer needed).
16
+ #
17
+ # Anyone who can push to an opted-in project's default branch can change the
18
+ # Gemfile that `bundle lock` evaluates here. secupdater keeps the token out of
19
+ # that process's environment and out of the clone's git config, but treat
20
+ # opting in as trusting that project with the token.
21
+
22
+ variables:
23
+ SECUPDATER_GROUP: delivereasy
24
+ SECUPDATER_TOPIC: secupdater
25
+ SECUPDATER_VERSION: "0.5.0" # the first release with `secupdater discover`
26
+
27
+ workflow:
28
+ rules:
29
+ - if: $CI_PIPELINE_SOURCE == "schedule" || $CI_PIPELINE_SOURCE == "web"
30
+
31
+ discover:
32
+ image: ruby:3.4
33
+ script:
34
+ - gem install secupdater -v "$SECUPDATER_VERSION" --no-document
35
+ - gem install bundler-audit --no-document
36
+ - bundle-audit update
37
+ # Writes projects/<id>/Gemfile.lock (and .bundler-audit.yml) and projects/projects.txt.
38
+ # Exits non-zero if any project couldn't be checked, after listing the rest,
39
+ # so carry on and fail at the end.
40
+ - secupdater discover --verbose --group="$SECUPDATER_GROUP" --topic="$SECUPDATER_TOPIC" projects || failed=1
41
+ - |
42
+ : > projects/run.txt
43
+ while read -r id path branch ruby open_mrs url; do
44
+ # Bundler won't parse a lockfile with path: gems without a Gemfile to
45
+ # resolve them from, so give it an empty one. bundle-audit exits 1 when it
46
+ # finds advisories, so check it wrote a report instead.
47
+ touch "projects/$id/Gemfile"
48
+ BUNDLE_GEMFILE="$PWD/projects/$id/Gemfile" \
49
+ bundle-audit check "projects/$id" --format json --output "projects/$id/audit.json" || true
50
+ if [ ! -s "projects/$id/audit.json" ]; then
51
+ echo "$path: bundle-audit failed"
52
+ failed=1
53
+ continue
54
+ fi
55
+
56
+ findings=$(ruby -rjson -e 'puts JSON.parse(File.read(ARGV[0]))["results"].size' "projects/$id/audit.json")
57
+ echo "$path: $findings advisories, $open_mrs open secupdater MRs"
58
+ if [ "$findings" -gt 0 ] || [ "$open_mrs" -gt 0 ]; then
59
+ echo "$id $path $branch $ruby $url" >> projects/run.txt
60
+ fi
61
+ done < projects/projects.txt
62
+ - exit "${failed:-0}"
63
+ artifacts:
64
+ when: always
65
+ paths: [projects/]
66
+ expire_in: 1 day
67
+
68
+ update:
69
+ image: docker:27
70
+ services: [docker:27-dind]
71
+ variables:
72
+ DOCKER_TLS_CERTDIR: "/certs"
73
+ needs: [discover]
74
+ # Still update the projects discover could check when it couldn't check them all
75
+ when: always
76
+ script:
77
+ - |
78
+ failed=0
79
+ while read -r id path branch ruby url; do
80
+ echo "== $path (Ruby $ruby)"
81
+ # The report goes in on stdin, as the dind daemon can't see this job's files
82
+ docker run --rm -i \
83
+ -e SECUPDATER_GITLAB_TOKEN -e SECUPDATER_VERSION \
84
+ -e SECUPDATER_PROJECT_ID="$id" -e SECUPDATER_TARGET_BRANCH="$branch" -e CLONE_URL="$url" \
85
+ "ruby:$ruby" sh -euc '
86
+ cat > /tmp/audit.json
87
+ git clone --quiet --depth 1 --branch "$SECUPDATER_TARGET_BRANCH" \
88
+ "https://oauth2:${SECUPDATER_GITLAB_TOKEN}@${CLONE_URL#https://}" /repo
89
+ cd /repo
90
+ git remote remove origin # takes the token out of .git/config
91
+ gem install secupdater -v "$SECUPDATER_VERSION" --no-document --silent
92
+ secupdater run --ecosystem=rubygems --verbose /tmp/audit.json
93
+ ' < "projects/$id/audit.json" || failed=1
94
+ done < projects/run.txt
95
+ exit $failed
@@ -33,7 +33,11 @@ module Secupdater
33
33
  def publisher
34
34
  return unless ENV["SECUPDATER_GITLAB_TOKEN"]
35
35
 
36
- Publisher::Gitlab.new(ENV["SECUPDATER_GITLAB_TOKEN"], ENV.fetch("CI_PROJECT_ID"), ENV.fetch("CI_DEFAULT_BRANCH"), head_commit)
36
+ # SECUPDATER_* for when it runs from another project's pipeline (see secupdater discover)
37
+ project_id = ENV["SECUPDATER_PROJECT_ID"] || ENV.fetch("CI_PROJECT_ID")
38
+ target_branch = ENV["SECUPDATER_TARGET_BRANCH"] || ENV.fetch("CI_DEFAULT_BRANCH")
39
+
40
+ Publisher::Gitlab.new(ENV["SECUPDATER_GITLAB_TOKEN"], project_id, target_branch, head_commit)
37
41
  rescue KeyError => e
38
42
  raise Secupdater::Error, "SECUPDATER_GITLAB_TOKEN is set but #{e.key} isn't"
39
43
  end
@@ -48,7 +52,34 @@ module Secupdater
48
52
  end
49
53
  end
50
54
 
55
+ class Discover < Dry::CLI::Command
56
+ desc "Find the GitLab projects in a group that have opted in with a topic, for running secupdater from a central project"
57
+
58
+ option :group, required: true, desc: "GitLab group (ID or path) to look in, including its subgroups"
59
+ option :topic, default: "secupdater", desc: "Topic a project needs to be included"
60
+ option :verbose, type: :boolean, default: false
61
+
62
+ argument :output, required: true, desc: "Directory to write each project's files and projects.txt to"
63
+
64
+ def call(output:, topic:, verbose:, group: nil, **)
65
+ # dry-cli doesn't enforce required options
66
+ raise Secupdater::Error, "--group is required, e.g. --group=my-group" unless group
67
+
68
+ token = ENV.fetch("SECUPDATER_GITLAB_TOKEN") { raise Secupdater::Error, "SECUPDATER_GITLAB_TOKEN isn't set" }
69
+ logger = Secupdater.build_logger(log_level: verbose ? :info : :warn)
70
+
71
+ discovery = Discovery::Gitlab.new(token, group:, topic:, logger:)
72
+ discovery.call(output)
73
+
74
+ exit(1) if discovery.failures.any?
75
+ rescue Secupdater::Error => e
76
+ err.puts e.message
77
+ exit(1)
78
+ end
79
+ end
80
+
51
81
  register "run", Run
82
+ register "discover", Discover
52
83
  end
53
84
  end
54
85
  end
@@ -0,0 +1,136 @@
1
+ require "fileutils"
2
+ require "net/http"
3
+ require "json"
4
+
5
+ module Secupdater
6
+ module Discovery
7
+ # Finds the projects in a GitLab group that have opted in to secupdater with a
8
+ # topic, so one central pipeline can audit and update them all. For each one
9
+ # it writes, to <output>/<project id>/, the files bundle-audit needs:
10
+ # Gemfile.lock, and .bundler-audit.yml if the project has one (so its ignored
11
+ # advisories stay ignored). Then <output>/projects.txt lists them, a line each:
12
+ #
13
+ # <id> <path> <default branch> <Ruby version> <open secupdater MRs> <clone URL>
14
+ #
15
+ # None of those fields can contain spaces.
16
+ class Gitlab
17
+ Project = Struct.new(:id, :path, :default_branch, :ruby_version, :open_merge_requests, :clone_url, keyword_init: true) do
18
+ def to_line = [id, path, default_branch, ruby_version, open_merge_requests, clone_url].join(" ")
19
+ end
20
+
21
+ # secupdater uses `it` block parameters
22
+ MINIMUM_RUBY = Gem::Version.new("3.4")
23
+
24
+ # As Publisher::Gitlab::LABEL
25
+ LABEL = "secupdater"
26
+
27
+ attr_reader :access_token, :group, :topic, :logger, :failures
28
+
29
+ def initialize(access_token, group:, topic:, logger:)
30
+ @access_token = access_token
31
+ @group = group
32
+ @topic = topic
33
+ @logger = logger
34
+ @failures = []
35
+ end
36
+
37
+ # Returns the projects it listed. Projects it couldn't check are logged and
38
+ # left out, and recorded in #failures.
39
+ def call(output)
40
+ FileUtils.mkdir_p(output)
41
+
42
+ projects = Net::HTTP.start("gitlab.com", 443, use_ssl: true) do |http|
43
+ group_projects(http).filter_map do |project|
44
+ discover(http, project, output)
45
+ rescue Secupdater::Error => e
46
+ logger.error "#{project["path_with_namespace"]}: #{e.message}"
47
+ failures << project["path_with_namespace"]
48
+ nil
49
+ end
50
+ end
51
+
52
+ File.write(File.join(output, "projects.txt"), projects.map { "#{it.to_line}\n" }.join)
53
+ projects
54
+ end
55
+
56
+ private
57
+
58
+ def discover(http, project, output)
59
+ path = project["path_with_namespace"]
60
+ branch = project["default_branch"]
61
+ return skip(:info, "#{path}: skipped, it has no default branch (empty repository?)") unless branch
62
+
63
+ lockfile = file(http, project, "Gemfile.lock")
64
+ return skip(:info, "#{path}: skipped, it has no Gemfile.lock") unless lockfile
65
+
66
+ ruby_version = ruby_version(http, project)
67
+ unless ruby_version
68
+ return skip(:warn, "#{path}: skipped, its Ruby version can't be found in .tool-versions or .ruby-version")
69
+ end
70
+ if Gem::Version.new(ruby_version) < MINIMUM_RUBY
71
+ return skip(:warn, "#{path}: skipped, secupdater needs Ruby #{MINIMUM_RUBY} or later, and it uses #{ruby_version}")
72
+ end
73
+
74
+ dir = File.join(output, project["id"].to_s)
75
+ FileUtils.mkdir_p(dir)
76
+ File.write(File.join(dir, "Gemfile.lock"), lockfile)
77
+ audit_config = file(http, project, ".bundler-audit.yml")
78
+ File.write(File.join(dir, ".bundler-audit.yml"), audit_config) if audit_config
79
+
80
+ Project.new(
81
+ id: project["id"],
82
+ path:,
83
+ default_branch: branch,
84
+ ruby_version:,
85
+ open_merge_requests: open_merge_requests(http, project),
86
+ clone_url: project["http_url_to_repo"]
87
+ ).tap { logger.info "#{path}: found, Ruby #{ruby_version}, #{it.open_merge_requests} open secupdater MRs" }
88
+ end
89
+
90
+ def skip(level, message)
91
+ logger.public_send(level, message)
92
+ nil
93
+ end
94
+
95
+ # The group's own projects (not ones shared into it) with the topic. The
96
+ # topic is checked here as well as in the query, so a GitLab that ignores
97
+ # the query parameter can't widen it.
98
+ def group_projects(http)
99
+ (1..).lazy.map do |page|
100
+ query = URI.encode_www_form(include_subgroups: true, with_shared: false, archived: false, topic:, per_page: 100, page:)
101
+ JSON.parse(get(http, "groups/#{URI.encode_www_form_component(group)}/projects?#{query}").body)
102
+ end.take_while(&:any?).flat_map { it }.select { it["topics"].to_a.include?(topic) }.to_a
103
+ end
104
+
105
+ def file(http, project, name)
106
+ query = URI.encode_www_form(ref: project["default_branch"])
107
+ get(http, "projects/#{project["id"]}/repository/files/#{URI.encode_www_form_component(name)}/raw?#{query}", allow_missing: true)&.body
108
+ end
109
+
110
+ VERSION_PATTERN = /\A\d+\.\d+(\.\d+)?\z/
111
+
112
+ def ruby_version(http, project)
113
+ version = file(http, project, ".tool-versions")&.then { it[/^ruby\s+(\S+)/, 1] }
114
+ version ||= file(http, project, ".ruby-version")&.strip&.delete_prefix("ruby-")
115
+ version if version&.match?(VERSION_PATTERN)
116
+ end
117
+
118
+ # Up to 100, which is plenty to know whether it has any
119
+ def open_merge_requests(http, project)
120
+ query = URI.encode_www_form(state: "opened", labels: LABEL, target_branch: project["default_branch"], per_page: 100)
121
+ JSON.parse(get(http, "projects/#{project["id"]}/merge_requests?#{query}").body).size
122
+ end
123
+
124
+ def get(http, path, allow_missing: false)
125
+ req = Net::HTTP::Get.new("/api/v4/#{path}", "PRIVATE-TOKEN" => access_token)
126
+ res = http.request(req)
127
+
128
+ return if allow_missing && res.is_a?(Net::HTTPNotFound)
129
+
130
+ raise Secupdater::Error, "GitLab GET #{req.path} returned #{res.code}: #{res.body}" unless res.is_a?(Net::HTTPSuccess)
131
+
132
+ res
133
+ end
134
+ end
135
+ end
136
+ end
@@ -101,6 +101,10 @@ module Secupdater
101
101
  # entrypoint is `bundle exec`), undo what that set up so bundle lock works on
102
102
  # the Gemfile and Gemfile.lock here. PATH is left alone, as callers may have
103
103
  # changed it since.
104
+ #
105
+ # bundle lock evaluates the Gemfile, which is Ruby from the repo being
106
+ # updated, so it doesn't get the GitLab token (which, run centrally, can
107
+ # reach every opted-in project).
104
108
  def bundle_env
105
109
  original = Bundler.original_env
106
110
  rubyopt = original["RUBYOPT"]&.gsub(%r{-r\S*bundler/setup\S*}, "")&.strip
@@ -109,7 +113,8 @@ module Secupdater
109
113
  "BUNDLE_FROZEN" => "false",
110
114
  "BUNDLE_GEMFILE" => File.expand_path("Gemfile"),
111
115
  "BUNDLE_LOCKFILE" => nil,
112
- "RUBYOPT" => rubyopt.nil? || rubyopt.empty? ? nil : rubyopt
116
+ "RUBYOPT" => rubyopt.nil? || rubyopt.empty? ? nil : rubyopt,
117
+ "SECUPDATER_GITLAB_TOKEN" => nil
113
118
  )
114
119
  end
115
120
  end
@@ -39,6 +39,7 @@ module Secupdater
39
39
  else
40
40
  commit(http)
41
41
  end
42
+ committed = !up_to_date
42
43
 
43
44
  if open_merge_request
44
45
  remember(open_merge_request)
@@ -46,13 +47,18 @@ module Secupdater
46
47
  # e.g. when this update has since absorbed another dependency's advisories
47
48
  described = open_merge_request["description"] == description
48
49
  request(http, Net::HTTP::Put, "merge_requests/#{open_merge_request["iid"]}", { description: description }) unless described
49
-
50
- return [:up_to_date, nil] if up_to_date && described
51
50
  else
52
- remember(JSON.parse(create_merge_request(http).body))
51
+ open_merge_request = JSON.parse(create_merge_request(http).body)
52
+ remember(open_merge_request)
53
53
  end
54
54
 
55
- [:published, nil]
55
+ # A commit cancels auto-merge, and its pipeline won't have started
56
+ # yet, so a run that commits leaves auto-merge to the next run
57
+ message = enable_auto_merge(http, open_merge_request["iid"]) unless committed
58
+
59
+ return [:up_to_date, message] if up_to_date && described
60
+
61
+ [:published, message]
56
62
  end
57
63
  end
58
64
 
@@ -125,6 +131,25 @@ module Secupdater
125
131
  request(http, Net::HTTP::Post, notes_path, { body: })
126
132
  end
127
133
 
134
+ # GitLab doesn't document what auto-merge does without a pipeline, so it
135
+ # is only set once the branch's head commit has a pipeline that can still
136
+ # pass. Returns a message if GitLab won't set it (e.g. the MR can't merge).
137
+ def enable_auto_merge(http, iid)
138
+ merge_request = JSON.parse(request(http, Net::HTTP::Get, "merge_requests/#{iid}").body)
139
+ return if merge_request["merge_when_pipeline_succeeds"] || merge_request["draft"]
140
+
141
+ pipeline = merge_request["head_pipeline"]
142
+ return unless pipeline && pipeline["sha"] == merge_request["sha"]
143
+ return if %w[failed canceled skipped].include?(pipeline["status"])
144
+
145
+ # sha makes GitLab refuse (409) if the branch has moved on since
146
+ data = { auto_merge: true, sha: merge_request["sha"], should_remove_source_branch: true }
147
+ res = request(http, Net::HTTP::Put, "merge_requests/#{iid}/merge", data, tolerate: [405, 406, 409, 422])
148
+ return if res.is_a?(Net::HTTPSuccess)
149
+
150
+ "#{reference}: couldn't set !#{iid} to auto-merge, GitLab returned #{res.code}: #{res.body}"
151
+ end
152
+
128
153
  def close_merge_request(http, iid, reason)
129
154
  request(http, Net::HTTP::Post, "merge_requests/#{iid}/notes", { body: reason })
130
155
  request(http, Net::HTTP::Put, "merge_requests/#{iid}", { state_event: "close" })
@@ -188,11 +213,12 @@ module Secupdater
188
213
  diffs.any? { ecosystem.manifest_paths.intersect?(it.values_at("old_path", "new_path")) }
189
214
  end
190
215
 
191
- def request(http, type, path, data = nil, allow_missing: false)
192
- api_request(http, type, "projects/#{URI.encode_www_form_component(project_id)}/#{path}", data, allow_missing:)
216
+ def request(http, type, path, data = nil, allow_missing: false, tolerate: [])
217
+ api_request(http, type, "projects/#{URI.encode_www_form_component(project_id)}/#{path}", data, allow_missing:, tolerate:)
193
218
  end
194
219
 
195
- def api_request(http, type, path, data = nil, allow_missing: false)
220
+ # tolerate: status codes to return the response for instead of raising
221
+ def api_request(http, type, path, data = nil, allow_missing: false, tolerate: [])
196
222
  req = type.new(
197
223
  "/api/v4/#{path}",
198
224
  "PRIVATE-TOKEN" => access_token,
@@ -203,6 +229,7 @@ module Secupdater
203
229
  res = http.request(req)
204
230
 
205
231
  return if allow_missing && res.is_a?(Net::HTTPNotFound)
232
+ return res if tolerate.include?(res.code.to_i)
206
233
 
207
234
  unless res.is_a?(Net::HTTPSuccess)
208
235
  raise Secupdater::PublishFailed, "GitLab #{req.method} #{req.path} returned #{res.code}: #{res.body}"
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Secupdater
4
- VERSION = "0.4.0"
4
+ VERSION = "0.5.0"
5
5
  end
data/lib/secupdater.rb CHANGED
@@ -9,6 +9,7 @@ require_relative "secupdater/runner"
9
9
  require_relative "secupdater/update"
10
10
  require_relative "secupdater/publisher"
11
11
  require_relative "secupdater/publisher/gitlab"
12
+ require_relative "secupdater/discovery/gitlab"
12
13
 
13
14
  module Secupdater
14
15
  SecurityAdvisory = Struct.new(:name, :report_id, :patched_versions) do
@@ -61,6 +61,18 @@ RSpec.describe Secupdater::CLI::Commands::Run do
61
61
  ))
62
62
  end
63
63
 
64
+ context "with SECUPDATER_PROJECT_ID and SECUPDATER_TARGET_BRANCH too (e.g. run from a central project)" do
65
+ let(:env) { super().merge("SECUPDATER_PROJECT_ID" => "456", "SECUPDATER_TARGET_BRANCH" => "trunk") }
66
+
67
+ it "publishes to that project and branch instead" do
68
+ run_cli("--ecosystem=rubygems", "audit.json")
69
+
70
+ expect(Secupdater::Runner).to have_received(:new).with(hash_including(
71
+ publisher: have_attributes(project_id: "456", target_branch: "trunk")
72
+ ))
73
+ end
74
+ end
75
+
64
76
  context "outside a git checkout" do
65
77
  let(:git_head) { ["fatal: not a git repository\n", instance_double(Process::Status, success?: false)] }
66
78
 
@@ -120,3 +132,65 @@ RSpec.describe Secupdater::CLI::Commands::Run do
120
132
  end
121
133
  end
122
134
  end
135
+
136
+ RSpec.describe Secupdater::CLI::Commands::Discover do
137
+ let(:out) { StringIO.new }
138
+ let(:err) { StringIO.new }
139
+ let(:env) { { "SECUPDATER_GITLAB_TOKEN" => "token" } }
140
+ let(:failures) { [] }
141
+ let(:discovery) { instance_double(Secupdater::Discovery::Gitlab, call: [], failures:) }
142
+
143
+ def run_cli(*arguments)
144
+ Dry::CLI.new(Secupdater::CLI::Commands).call(arguments: ["discover", *arguments], out: out, err: err)
145
+ end
146
+
147
+ def expect_exit(status, &block)
148
+ expect(&block).to raise_error(SystemExit) { expect(it.status).to eq(status) }
149
+ end
150
+
151
+ before do
152
+ stub_const("ENV", env)
153
+ allow(Secupdater::Discovery::Gitlab).to receive(:new).and_return(discovery)
154
+ end
155
+
156
+ it "discovers the group's projects with the secupdater topic into the output directory" do
157
+ run_cli("--group=delivereasy", "projects")
158
+
159
+ expect(Secupdater::Discovery::Gitlab).to have_received(:new).with("token", group: "delivereasy", topic: "secupdater", logger: anything)
160
+ expect(discovery).to have_received(:call).with("projects")
161
+ end
162
+
163
+ it "takes another topic" do
164
+ run_cli("--group=delivereasy", "--topic=deps", "projects")
165
+
166
+ expect(Secupdater::Discovery::Gitlab).to have_received(:new).with("token", hash_including(topic: "deps"))
167
+ end
168
+
169
+ context "when a project couldn't be checked" do
170
+ let(:failures) { ["delivereasy/api"] }
171
+
172
+ it "exits non-zero, after writing the rest" do
173
+ expect_exit(1) { run_cli("--group=delivereasy", "projects") }
174
+
175
+ expect(discovery).to have_received(:call)
176
+ end
177
+ end
178
+
179
+ context "without a group" do
180
+ it "prints usage and exits non-zero" do
181
+ expect_exit(1) { run_cli("projects") }
182
+
183
+ expect(err.string).to include("--group")
184
+ end
185
+ end
186
+
187
+ context "without SECUPDATER_GITLAB_TOKEN" do
188
+ let(:env) { {} }
189
+
190
+ it "says so and exits non-zero" do
191
+ expect_exit(1) { run_cli("--group=delivereasy", "projects") }
192
+
193
+ expect(err.string).to eq("SECUPDATER_GITLAB_TOKEN isn't set\n")
194
+ end
195
+ end
196
+ end
@@ -0,0 +1,205 @@
1
+ require "secupdater"
2
+ require "tmpdir"
3
+
4
+ RSpec.describe Secupdater::Discovery::Gitlab do
5
+ subject(:discovery) { described_class.new("access_token", group: "delivereasy", topic: "secupdater", logger:) }
6
+
7
+ let(:log) { StringIO.new }
8
+ let(:logger) { Dry.Logger(:test, stream: log, template: "[%<severity>s] %<message>s", level: :info) }
9
+
10
+ let(:api) { "https://gitlab.com/api/v4" }
11
+ let(:headers) { { "PRIVATE-TOKEN" => "access_token" } }
12
+
13
+ let(:core) do
14
+ {
15
+ id: 11,
16
+ path_with_namespace: "delivereasy/core",
17
+ default_branch: "main",
18
+ topics: ["secupdater", "rails"],
19
+ http_url_to_repo: "https://gitlab.com/delivereasy/core.git"
20
+ }
21
+ end
22
+ let(:projects) { [core] }
23
+
24
+ let!(:group_projects_stub) do
25
+ stub_request(:get, "#{api}/groups/delivereasy/projects")
26
+ .with(query: { include_subgroups: "true", with_shared: "false", archived: "false", topic: "secupdater", per_page: "100", page: "1" }, headers:)
27
+ .to_return(status: 200, body: projects.to_json)
28
+ end
29
+
30
+ let!(:last_page_stub) do
31
+ stub_request(:get, "#{api}/groups/delivereasy/projects")
32
+ .with(query: hash_including(page: "2"))
33
+ .to_return(status: 200, body: "[]")
34
+ end
35
+
36
+ let(:files) do
37
+ {
38
+ "Gemfile.lock" => "GEM\n specs:\n",
39
+ ".tool-versions" => "nodejs 22.1.0\nruby 3.4.2\n"
40
+ }
41
+ end
42
+
43
+ before do
44
+ # Every file that isn't in `files` is missing
45
+ stub_request(:get, %r{\A#{api}/projects/\d+/repository/files/[^/]+/raw\?ref=main\z})
46
+ .with(headers:)
47
+ .to_return do |request|
48
+ name = URI.decode_www_form_component(request.uri.path[%r{files/([^/]+)/raw}, 1])
49
+ files.key?(name) ? { status: 200, body: files[name] } : { status: 404, body: '{"message":"404 File Not Found"}' }
50
+ end
51
+ end
52
+
53
+ let(:open_merge_requests) { [] }
54
+
55
+ let!(:open_merge_requests_stub) do
56
+ stub_request(:get, "#{api}/projects/11/merge_requests")
57
+ .with(query: { state: "opened", labels: "secupdater", target_branch: "main", per_page: "100" }, headers:)
58
+ .to_return(status: 200, body: open_merge_requests.to_json)
59
+ end
60
+
61
+ around { |example| Dir.mktmpdir { |dir| @output = dir; example.run } }
62
+
63
+ attr_reader :output
64
+
65
+ def discover = discovery.call(output)
66
+ def projects_txt = File.read(File.join(output, "projects.txt"))
67
+
68
+ describe "#call(output)" do
69
+ it "lists an opted-in project with its Ruby version, and writes its Gemfile.lock" do
70
+ discover
71
+
72
+ expect(projects_txt).to eq("11 delivereasy/core main 3.4.2 0 https://gitlab.com/delivereasy/core.git\n")
73
+ expect(File.read(File.join(output, "11", "Gemfile.lock"))).to eq("GEM\n specs:\n")
74
+ expect(discovery.failures).to be_empty
75
+ end
76
+
77
+ context "with open secupdater MRs" do
78
+ let(:open_merge_requests) { [{ iid: 4 }, { iid: 5 }] }
79
+
80
+ it "counts them, so the project still gets a run to close any no longer needed" do
81
+ discover
82
+
83
+ expect(projects_txt).to start_with("11 delivereasy/core main 3.4.2 2 ")
84
+ end
85
+ end
86
+
87
+ context "with a .bundler-audit.yml" do
88
+ let(:files) { super().merge(".bundler-audit.yml" => "ignore:\n - CVE-2024-0001\n") }
89
+
90
+ it "writes it next to the Gemfile.lock, so the audit still ignores what the project ignores" do
91
+ discover
92
+
93
+ expect(File.read(File.join(output, "11", ".bundler-audit.yml"))).to eq("ignore:\n - CVE-2024-0001\n")
94
+ end
95
+ end
96
+
97
+ context "with the Ruby version in .ruby-version instead" do
98
+ let(:files) { { "Gemfile.lock" => "GEM\n", ".ruby-version" => "ruby-3.4.1\n" } }
99
+
100
+ it "uses that" do
101
+ discover
102
+
103
+ expect(projects_txt).to start_with("11 delivereasy/core main 3.4.1 ")
104
+ end
105
+ end
106
+
107
+ context "without a Ruby version" do
108
+ let(:files) { { "Gemfile.lock" => "GEM\n" } }
109
+
110
+ it "skips it and says why" do
111
+ discover
112
+
113
+ expect(projects_txt).to eq("")
114
+ expect(log.string).to include("delivereasy/core: skipped, its Ruby version can't be found")
115
+ end
116
+ end
117
+
118
+ context "on a Ruby older than secupdater supports" do
119
+ let(:files) { super().merge(".tool-versions" => "ruby 3.3.6\n") }
120
+
121
+ it "skips it and says why" do
122
+ discover
123
+
124
+ expect(projects_txt).to eq("")
125
+ expect(log.string).to include("delivereasy/core: skipped, secupdater needs Ruby 3.4 or later, and it uses 3.3.6")
126
+ end
127
+ end
128
+
129
+ context "without a Gemfile.lock" do
130
+ let(:files) { { ".tool-versions" => "ruby 3.4.2\n" } }
131
+
132
+ it "skips it" do
133
+ discover
134
+
135
+ expect(projects_txt).to eq("")
136
+ expect(open_merge_requests_stub).not_to have_been_requested
137
+ end
138
+ end
139
+
140
+ context "with an empty repository" do
141
+ let(:core) { super().merge(default_branch: nil) }
142
+
143
+ it "skips it" do
144
+ expect(discover).to eq([])
145
+ end
146
+ end
147
+
148
+ context "when GitLab ignores the topic filter" do
149
+ let(:projects) { [core, core.merge(id: 12, path_with_namespace: "delivereasy/website", topics: [])] }
150
+
151
+ it "still only lists projects with the topic" do
152
+ discover
153
+
154
+ expect(projects_txt.lines.map { it.split.first }).to eq(["11"])
155
+ end
156
+ end
157
+
158
+ context "with more than one page of projects" do
159
+ let!(:last_page_stub) do
160
+ stub_request(:get, "#{api}/groups/delivereasy/projects")
161
+ .with(query: hash_including(page: "2"))
162
+ .to_return(status: 200, body: [core.merge(id: 13, path_with_namespace: "delivereasy/api")].to_json)
163
+ end
164
+
165
+ before do
166
+ stub_request(:get, "#{api}/groups/delivereasy/projects").with(query: hash_including(page: "3")).to_return(status: 200, body: "[]")
167
+ stub_request(:get, "#{api}/projects/13/merge_requests").with(query: hash_including({})).to_return(status: 200, body: "[]")
168
+ end
169
+
170
+ it "lists projects from every page" do
171
+ discover
172
+
173
+ expect(projects_txt.lines.map { it.split.first }).to eq(["11", "13"])
174
+ end
175
+ end
176
+
177
+ context "when one project can't be checked" do
178
+ let(:projects) { [core.merge(id: 13, path_with_namespace: "delivereasy/api"), core] }
179
+
180
+ before do
181
+ stub_request(:get, "#{api}/projects/13/merge_requests")
182
+ .with(query: hash_including({}))
183
+ .to_return(status: 500, body: "oops")
184
+ end
185
+
186
+ it "lists the others, and records the failure" do
187
+ discover
188
+
189
+ expect(projects_txt.lines.map { it.split.first }).to eq(["11"])
190
+ expect(discovery.failures).to eq(["delivereasy/api"])
191
+ expect(log.string).to include("delivereasy/api: GitLab GET", "returned 500")
192
+ end
193
+ end
194
+
195
+ context "when the group can't be listed" do
196
+ let!(:group_projects_stub) do
197
+ stub_request(:get, "#{api}/groups/delivereasy/projects").with(query: hash_including({})).to_return(status: 404, body: '{"message":"404 Group Not Found"}')
198
+ end
199
+
200
+ it "raises" do
201
+ expect { discover }.to raise_error(Secupdater::Error, /404 Group Not Found/)
202
+ end
203
+ end
204
+ end
205
+ end
@@ -156,7 +156,8 @@ RSpec.describe Secupdater::Ecosystem::Rubygems do
156
156
  "GEM_PATH" => nil,
157
157
  "RB_USER_INSTALL" => nil,
158
158
  "RUBYLIB" => nil,
159
- "RUBYOPT" => nil
159
+ "RUBYOPT" => nil,
160
+ "SECUPDATER_GITLAB_TOKEN" => nil # unset, so the repo's Gemfile can't read it
160
161
  }
161
162
  end
162
163
 
@@ -97,6 +97,23 @@ RSpec.describe Secupdater::Publisher::Gitlab do
97
97
  .to_return(status: 201, body: { iid: 9 }.to_json)
98
98
  end
99
99
 
100
+ let(:head_pipeline) { nil }
101
+ let(:merge_request_details) do
102
+ { sha: "def456", draft: false, merge_when_pipeline_succeeds: false, head_pipeline: }
103
+ end
104
+
105
+ let!(:get_merge_request_stub) do
106
+ stub_request(:get, %r{\A#{project_api}/merge_requests/\d+\z})
107
+ .with(headers: headers)
108
+ .to_return(status: 200, body: merge_request_details.to_json)
109
+ end
110
+
111
+ let!(:auto_merge_stub) do
112
+ stub_request(:put, %r{\A#{project_api}/merge_requests/\d+/merge\z})
113
+ .with(body: { auto_merge: true, sha: "def456", should_remove_source_branch: true }, headers: headers)
114
+ .to_return(status: 200, body: "{}")
115
+ end
116
+
100
117
  def publish = gitlab.call(ecosystem, bump, advisories, changes)
101
118
 
102
119
  describe "#call(ecosystem, bump, advisories, changes)" do
@@ -107,6 +124,13 @@ RSpec.describe Secupdater::Publisher::Gitlab do
107
124
  expect(create_commit_stub).to have_been_requested
108
125
  expect(create_mr_stub).to have_been_requested
109
126
  end
127
+
128
+ it "leaves auto-merge to the next run, as the commit has no pipeline yet" do
129
+ publish
130
+
131
+ expect(get_merge_request_stub).not_to have_been_requested
132
+ expect(auto_merge_stub).not_to have_been_requested
133
+ end
110
134
  end
111
135
 
112
136
  context "with advisories for other gems the update also fixes" do
@@ -234,6 +258,91 @@ RSpec.describe Secupdater::Publisher::Gitlab do
234
258
  expect(a_request(:post, //)).not_to have_been_made
235
259
  end
236
260
 
261
+ describe "auto-merge" do
262
+ context "with a pipeline running for the branch's head commit" do
263
+ let(:head_pipeline) { { sha: "def456", status: "running" } }
264
+
265
+ it "sets the MR to auto-merge, pinned to that commit" do
266
+ expect(publish).to eq([:up_to_date, nil])
267
+
268
+ expect(a_request(:put, "#{project_api}/merge_requests/7/merge")).to have_been_made
269
+ end
270
+
271
+ context "already set to auto-merge" do
272
+ let(:merge_request_details) { super().merge(merge_when_pipeline_succeeds: true) }
273
+
274
+ it "doesn't set it again" do
275
+ publish
276
+
277
+ expect(auto_merge_stub).not_to have_been_requested
278
+ end
279
+ end
280
+
281
+ context "on a draft MR" do
282
+ let(:merge_request_details) { super().merge(draft: true) }
283
+
284
+ it "leaves it for whoever marked it draft" do
285
+ publish
286
+
287
+ expect(auto_merge_stub).not_to have_been_requested
288
+ end
289
+ end
290
+
291
+ context "that GitLab won't merge (e.g. it has conflicts)" do
292
+ let!(:auto_merge_stub) do
293
+ stub_request(:put, "#{project_api}/merge_requests/7/merge")
294
+ .to_return(status: 405, body: '{"message":"405 Method Not Allowed"}')
295
+ end
296
+
297
+ it "says so, without failing the update" do
298
+ expect(publish).to eq([:up_to_date, "security/css_parser-1.1.0: couldn't set !7 to auto-merge, GitLab returned 405: {\"message\":\"405 Method Not Allowed\"}"])
299
+ end
300
+ end
301
+
302
+ context "when the token isn't allowed to merge" do
303
+ let!(:auto_merge_stub) do
304
+ stub_request(:put, "#{project_api}/merge_requests/7/merge")
305
+ .to_return(status: 401, body: '{"message":"401 Unauthorized"}')
306
+ end
307
+
308
+ it "fails the update" do
309
+ expect { publish }.to raise_error(Secupdater::PublishFailed, /401/)
310
+ end
311
+ end
312
+ end
313
+
314
+ context "without a pipeline" do
315
+ it "waits for one" do
316
+ publish
317
+
318
+ expect(get_merge_request_stub).to have_been_requested
319
+ expect(auto_merge_stub).not_to have_been_requested
320
+ end
321
+ end
322
+
323
+ context "with a pipeline for an older commit" do
324
+ let(:head_pipeline) { { sha: "abc000", status: "success" } }
325
+
326
+ it "waits for one for the head commit" do
327
+ publish
328
+
329
+ expect(auto_merge_stub).not_to have_been_requested
330
+ end
331
+ end
332
+
333
+ %w[failed canceled skipped].each do |status|
334
+ context "with a #{status} pipeline" do
335
+ let(:head_pipeline) { { sha: "def456", status: } }
336
+
337
+ it "doesn't set it, as the pipeline can't pass" do
338
+ publish
339
+
340
+ expect(auto_merge_stub).not_to have_been_requested
341
+ end
342
+ end
343
+ end
344
+ end
345
+
237
346
  context "but main has changed other files since the branch was cut" do
238
347
  let(:target_diffs_since_branch) { [{ old_path: "app/models/user.rb", new_path: "app/models/user.rb" }] }
239
348
 
@@ -263,6 +372,16 @@ RSpec.describe Secupdater::Publisher::Gitlab do
263
372
  expect(force_commit_stub).to have_been_requested
264
373
  expect(create_mr_stub).not_to have_been_requested
265
374
  end
375
+
376
+ context "with a pipeline for the replaced commit" do
377
+ let(:head_pipeline) { { sha: "def456", status: "running" } }
378
+
379
+ it "leaves auto-merge to the next run, once the new commit has a pipeline" do
380
+ publish
381
+
382
+ expect(auto_merge_stub).not_to have_been_requested
383
+ end
384
+ end
266
385
  end
267
386
 
268
387
  context "whose branch has a commit from someone else" do
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: secupdater
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.4.0
4
+ version: 0.5.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Ben Anderson
@@ -79,8 +79,10 @@ files:
79
79
  - README.md
80
80
  - Rakefile
81
81
  - bin/secupdater
82
+ - examples/central-project/.gitlab-ci.yml
82
83
  - lib/secupdater.rb
83
84
  - lib/secupdater/cli.rb
85
+ - lib/secupdater/discovery/gitlab.rb
84
86
  - lib/secupdater/ecosystem.rb
85
87
  - lib/secupdater/ecosystem/rubygems.rb
86
88
  - lib/secupdater/publisher.rb
@@ -91,6 +93,7 @@ files:
91
93
  - sig/secupdater.rbs
92
94
  - spec/e2e/secupdater_spec.rb
93
95
  - spec/secupdater/cli_spec.rb
96
+ - spec/secupdater/discovery/gitlab_spec.rb
94
97
  - spec/secupdater/ecosystem/rubygems_spec.rb
95
98
  - spec/secupdater/ecosystem_spec.rb
96
99
  - spec/secupdater/publisher/gitlab_spec.rb