secupdater 0.3.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.
@@ -1,5 +1,12 @@
1
1
  module Secupdater
2
2
  class Update
3
+ # What updating one vulnerable dependency on its own came to, before anything
4
+ # is published. diff is every dependency the update moved, not just this one.
5
+ Candidate = Struct.new(:dependency, :advisories, :status, :message, :level, :bump, :diff, :file_changes, keyword_init: true) do
6
+ def name = dependency.name
7
+ def resolved? = status == :resolved
8
+ end
9
+
3
10
  attr_reader :logger, :ecosystem, :publisher, :original
4
11
 
5
12
  def initialize(logger, ecosystem, publisher: nil)
@@ -16,75 +23,148 @@ module Secupdater
16
23
  missing = deps_needing_checking.keys - original.keys
17
24
  raise Secupdater::Error, "Advisories for dependencies not in the lockfile: #{missing.join(', ')}" if missing.any?
18
25
 
19
- results = deps_needing_checking.to_h do |name, dep_advisories|
20
- [name, update_dependency(original[name], dep_advisories)]
26
+ candidates = deps_needing_checking.to_h do |name, dep_advisories|
27
+ [name, try_update(original[name], dep_advisories)]
21
28
  end
22
29
 
30
+ results = publish(candidates)
31
+
23
32
  publisher&.finish(deps_needing_checking.keys)&.each { logger.info it }
24
33
 
25
- results
34
+ deps_needing_checking.keys.to_h { [it, results.fetch(it)] }
26
35
  end
27
36
 
28
- def update_dependency(dep, advisories)
29
- logger.info("starting update for #{dep.name}, #{advisories.length} advisories")
37
+ private
30
38
 
31
- status = message = nil
39
+ def try_update(dep, advisories)
40
+ logger.info("starting update for #{dep.name}, #{advisories.length} advisories")
32
41
 
33
42
  levels = ecosystem.update_levels
43
+ candidate = nil
34
44
 
35
45
  levels.each do |level|
36
- status, message = attempt_update(dep, advisories, level)
37
- return status unless message
46
+ candidate = attempt_update(dep, advisories, level)
47
+ return candidate if candidate.resolved?
38
48
 
39
- logger.debug "#{level} update: #{message}" unless level == levels.last
49
+ logger.debug "#{level} update: #{candidate.message}" unless level == levels.last
40
50
  end
41
51
 
42
- if status == :failed
43
- logger.error message
44
- else
45
- logger.warn message
46
- end
47
-
48
- status
52
+ candidate
49
53
  rescue Secupdater::UnretryableUpdateFailed => e
50
- logger.error "#{dep.name}: #{e.message}\n#{e.output}"
51
- :failed
52
- rescue Secupdater::PublishFailed => e
53
- logger.error "#{dep.name}: #{e.message}"
54
- :failed
54
+ Candidate.new(dependency: dep, advisories:, status: :failed, message: "#{dep.name}: #{e.message}\n#{e.output}")
55
55
  end
56
56
 
57
- private
58
-
59
57
  def attempt_update(dep, advisories, level)
60
58
  file_changes = ecosystem.try_update(dep.name, level:)
61
- bump = ecosystem.diff_snapshot(original, ecosystem.snapshot).detect { it.dependency.name == dep.name }
59
+ diff = ecosystem.diff_snapshot(original, ecosystem.snapshot)
60
+ bump = diff.detect { it.dependency.name == dep.name }
61
+ attempt = { dependency: dep, advisories:, level:, bump:, diff:, file_changes: }
62
62
 
63
- return [:unchanged, "#{dep.name} didn't update (stuck at #{dep.version})"] unless bump
63
+ return Candidate.new(**attempt, status: :unchanged, message: "#{dep.name} didn't update (stuck at #{dep.version})") unless bump
64
64
 
65
- resolved = advisories.all? do |advisory|
66
- advisory.patched_versions.any? { ecosystem.satisfies_requirement?(bump.to, it) }
65
+ unless fixes?(bump, advisories)
66
+ return Candidate.new(**attempt, status: :unresolved, message: "#{dep.name} didn't update to a version that resolves the security warnings (went from #{bump.from} to #{bump.to})")
67
+ end
68
+
69
+ Candidate.new(**attempt, status: :resolved)
70
+ rescue Secupdater::UnretryableUpdateFailed
71
+ raise
72
+ rescue Secupdater::UpdateCommandFailed => e
73
+ Candidate.new(dependency: dep, advisories:, level:, status: :failed, message: "#{dep.name}: #{e.message}\n#{e.output}")
74
+ ensure
75
+ restore(file_changes)
76
+ end
77
+
78
+ # Publishes each update, with the advisories of any dependencies it absorbs.
79
+ # If an absorbing update is declined, the dependencies it absorbed are
80
+ # published without it (absorbing each other where they can).
81
+ def publish(candidates)
82
+ absorbed = absorptions(candidates)
83
+ results = {}
84
+
85
+ candidates.each_value do |candidate|
86
+ next if absorbed.key?(candidate.name)
87
+
88
+ covered = absorbed.filter_map { |name, absorber| candidates[name] if absorber == candidate.name }
89
+ results[candidate.name] = publish_candidate(candidate, covered)
90
+ next if covered.empty?
91
+
92
+ if results[candidate.name] == :declined
93
+ logger.info "#{candidate.name}'s update was declined, so updating #{covered.map(&:name).join(', ')} without it"
94
+ results.merge!(publish(covered.to_h { [it.name, it] }))
95
+ else
96
+ covered.each { results[it.name] = :absorbed }
97
+ end
67
98
  end
68
99
 
69
- unless resolved
70
- return [:unresolved, "#{dep.name} didn't update to a version that resolves the security warnings (went from #{bump.from} to #{bump.to})"]
100
+ results
101
+ end
102
+
103
+ # Which dependencies' updates go into another's MR, as { absorbed => absorber }.
104
+ # A absorbs B when A's update also moves B to a version that fixes all of B's
105
+ # advisories. The updates that cover the most go first, then by name so runs
106
+ # agree, and each dependency ends up in only one MR.
107
+ def absorptions(candidates)
108
+ resolved = candidates.values.select(&:resolved?)
109
+ covers = resolved.to_h do |candidate|
110
+ [candidate.name, candidates.values.select { it != candidate && covers?(candidate, it) }.map(&:name)]
111
+ end
112
+
113
+ absorbed = {}
114
+ covers.sort_by { |name, names| [-names.length, name] }.each do |name, names|
115
+ next if absorbed.key?(name)
116
+
117
+ names.each do |other|
118
+ absorbed[other] = name unless absorbed.key?(other) || absorbed.value?(other)
119
+ end
71
120
  end
121
+ absorbed
122
+ end
72
123
 
73
- advisories.each do |advisory|
74
- logger.info "upgrading #{dep.name} from #{bump.from} to #{bump.to} (#{level}) would resolve #{advisory}"
124
+ def covers?(candidate, other)
125
+ bump = candidate.diff.detect { it.dependency.name == other.name }
126
+ bump && (bump.to.nil? || fixes?(bump, other.advisories))
127
+ end
128
+
129
+ def fixes?(bump, advisories)
130
+ advisories.all? do |advisory|
131
+ advisory.patched_versions.any? { ecosystem.satisfies_requirement?(bump.to, it) }
132
+ end
133
+ end
134
+
135
+ def publish_candidate(candidate, covered)
136
+ unless candidate.resolved?
137
+ if candidate.status == :failed
138
+ logger.error candidate.message
139
+ else
140
+ logger.warn candidate.message
141
+ end
142
+ return candidate.status
75
143
  end
76
144
 
77
- return [:resolved, nil] unless publisher
145
+ log_resolution(candidate, covered)
146
+
147
+ return :resolved unless publisher
78
148
 
79
- status, message = publisher.call(ecosystem, bump, advisories, file_changes)
149
+ status, message = publisher.call(ecosystem, candidate.bump, candidate.advisories + covered.flat_map(&:advisories), candidate.file_changes)
80
150
  logger.warn message if message
81
- [status, nil]
82
- rescue Secupdater::UnretryableUpdateFailed
83
- raise
84
- rescue Secupdater::UpdateCommandFailed => e
85
- [:failed, "#{dep.name}: #{e.message}\n#{e.output}"]
86
- ensure
87
- restore(file_changes)
151
+ status
152
+ rescue Secupdater::PublishFailed => e
153
+ logger.error "#{candidate.name}: #{e.message}"
154
+ :failed
155
+ end
156
+
157
+ def log_resolution(candidate, covered)
158
+ bump = candidate.bump
159
+ upgrade = "upgrading #{candidate.name} from #{bump.from} to #{bump.to} (#{candidate.level})"
160
+
161
+ candidate.advisories.each { logger.info "#{upgrade} would resolve #{it}" }
162
+
163
+ covered.each do |other|
164
+ other_bump = candidate.diff.detect { it.dependency.name == other.name }
165
+ moves = other_bump.to ? "moves #{other.name} from #{other_bump.from} to #{other_bump.to}" : "removes #{other.name}"
166
+ other.advisories.each { logger.info "#{upgrade} #{moves}, which would resolve #{it}" }
167
+ end
88
168
  end
89
169
 
90
170
  def restore(file_changes)
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Secupdater
4
- VERSION = "0.3.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
@@ -75,6 +75,21 @@ RSpec.describe Secupdater::Ecosystem::Rubygems do
75
75
  expect(rubygems.parse_advisories(StringIO.new(report.to_json)).map(&:report_id)).to eq(["RUBYSEC-2024-1"])
76
76
  end
77
77
  end
78
+
79
+ context "the same advisory reported once per platform the gem is locked for" do
80
+ let(:result) do
81
+ {
82
+ type: "unpatched_gem",
83
+ gem: { name: "nokogiri", version: "1.19.4" },
84
+ advisory: { id: "GHSA-3w22-6jfg-527w", ghsa: "3w22-6jfg-527w", patched_versions: [">= 1.19.5"] }
85
+ }
86
+ end
87
+ let(:report) { { results: [result, result] } }
88
+
89
+ it "returns it once" do
90
+ expect(rubygems.parse_advisories(StringIO.new(report.to_json)).map(&:report_id)).to eq(["ghsa/3w22-6jfg-527w"])
91
+ end
92
+ end
78
93
  end
79
94
 
80
95
  describe "#snapshot" do
@@ -141,7 +156,8 @@ RSpec.describe Secupdater::Ecosystem::Rubygems do
141
156
  "GEM_PATH" => nil,
142
157
  "RB_USER_INSTALL" => nil,
143
158
  "RUBYLIB" => nil,
144
- "RUBYOPT" => nil
159
+ "RUBYOPT" => nil,
160
+ "SECUPDATER_GITLAB_TOKEN" => nil # unset, so the repo's Gemfile can't read it
145
161
  }
146
162
  end
147
163