secupdater 0.1.0 → 0.2.0alpha2

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: 5bc574d1914c88ba5bb0c0624e0be6be31af1797d27beafa08edd8ea558cf7e4
4
- data.tar.gz: 19900eeb514d8dbd6572a8d7f80ee678a7564361302e253f99d219f5603ffc2b
3
+ metadata.gz: 9370b2774586510cf198499d82567825da267bb6c616ebcbfe5a97b0f2df17b6
4
+ data.tar.gz: 17b9536a5abdb0f73f18e76a3d91dca0d0921560e14468d98cb6c7b611808ab2
5
5
  SHA512:
6
- metadata.gz: b156d7d68800aee0a99556b14ecfd8932aedb4e62b8afc4d6c40f49473a3907d809e4c7100ed565b07e825e30ffabb840c960862cd6b71dbb239326aa95a7788
7
- data.tar.gz: 21c55f8f8f74c4e8589529bcf93a70832e1b4ec09e456b494c44ec66a8a7e002359c3a8a9fcc310d3c0669e568f166db6b969d2eec0ef83d83562a176b64caad
6
+ metadata.gz: 06345b62279096ca6cf5226a16b67da136ea4a300dba9d9b573f6500dca9d3201cc427738be31ba20bb6f1a756c97affc40e22fe2a3194051f752f92914a3d01
7
+ data.tar.gz: 326e8beccaa4ea2fbb74fb3d388a94e0dd8ec61d765c0a14701440b12faa6671ecdde8ec7c4bad5e2db452d529880877d60fc241ffb97faa5e3e48f3102b6ec2
@@ -1,4 +1,5 @@
1
1
  require "dry/cli"
2
+ require "open3"
2
3
 
3
4
  module Secupdater
4
5
  module CLI
@@ -32,10 +33,19 @@ module Secupdater
32
33
  def publisher
33
34
  return unless ENV["SECUPDATER_GITLAB_TOKEN"]
34
35
 
35
- Publisher::Gitlab.new(ENV["SECUPDATER_GITLAB_TOKEN"], ENV.fetch("CI_PROJECT_ID"), ENV.fetch("CI_DEFAULT_BRANCH"))
36
+ Publisher::Gitlab.new(ENV["SECUPDATER_GITLAB_TOKEN"], ENV.fetch("CI_PROJECT_ID"), ENV.fetch("CI_DEFAULT_BRANCH"), head_commit)
36
37
  rescue KeyError => e
37
38
  raise Secupdater::Error, "SECUPDATER_GITLAB_TOKEN is set but #{e.key} isn't"
38
39
  end
40
+
41
+ # Update branches start from the commit the lockfile was read from, so
42
+ # their diff is only the bump, even if the target branch has moved on
43
+ def head_commit
44
+ output, status = Open3.capture2e("git", "rev-parse", "--verify", "HEAD")
45
+ raise Secupdater::Error, "Can't find the current git commit to base updates on: #{output}" unless status.success?
46
+
47
+ output.strip
48
+ end
39
49
  end
40
50
 
41
51
  register "run", Run
@@ -5,6 +5,8 @@ require "bundler"
5
5
  module Secupdater
6
6
  class Ecosystem
7
7
  class Rubygems < Secupdater::Ecosystem
8
+ FROZEN_EXIT_CODE = 16
9
+
8
10
  def self.ecosystem_name = "RubyGems"
9
11
 
10
12
  def manifest_paths = ["Gemfile.lock"]
@@ -30,7 +32,11 @@ module Secupdater
30
32
  end
31
33
 
32
34
  def run_update(names, level)
33
- output, status = Open3.capture2e("bundle", "update", *Array(names), "--conservative", "--#{level}", "--strict")
35
+ output, status = Open3.capture2e({ "BUNDLE_FROZEN" => "false" }, "bundle", "update", *Array(names), "--conservative", "--#{level}", "--strict")
36
+
37
+ if status.exitstatus == FROZEN_EXIT_CODE
38
+ raise Secupdater::Error, "bundle update can't change Gemfile.lock (is BUNDLE_DEPLOYMENT set?)\n#{output}"
39
+ end
34
40
 
35
41
  unless status.success?
36
42
  raise Secupdater::UpdateCommandFailed.new(
@@ -4,12 +4,13 @@ require "json"
4
4
  module Secupdater
5
5
  class Publisher
6
6
  class Gitlab < Secupdater::Publisher
7
- attr_reader :access_token, :project_id, :target_branch
7
+ attr_reader :access_token, :project_id, :target_branch, :start_sha
8
8
 
9
- def initialize(access_token, project_id, target_branch)
9
+ def initialize(access_token, project_id, target_branch, start_sha)
10
10
  @access_token = access_token
11
11
  @project_id = project_id
12
12
  @target_branch = target_branch
13
+ @start_sha = start_sha
13
14
  end
14
15
 
15
16
  def run
@@ -18,7 +19,7 @@ module Secupdater
18
19
 
19
20
  data = {
20
21
  branch: reference,
21
- start_branch: target_branch,
22
+ start_sha: start_sha,
22
23
  commit_message: title,
23
24
  actions: changes.map { { action: it.type, file_path: it.filename, content: it.content }.compact }
24
25
  }
@@ -57,7 +58,7 @@ module Secupdater
57
58
  res = http.request(req)
58
59
 
59
60
  unless res.is_a?(Net::HTTPSuccess)
60
- raise Secupdater::Error, "GitLab #{req.method} #{req.path} returned #{res.code}: #{res.body}"
61
+ raise Secupdater::PublishFailed, "GitLab #{req.method} #{req.path} returned #{res.code}: #{res.body}"
61
62
  end
62
63
 
63
64
  res
@@ -26,11 +26,13 @@ module Secupdater
26
26
 
27
27
  status = message = nil
28
28
 
29
- ecosystem.update_levels.each do |level|
29
+ levels = ecosystem.update_levels
30
+
31
+ levels.each do |level|
30
32
  status, message = attempt_update(dep, advisories, level)
31
33
  return status unless message
32
34
 
33
- logger.debug "#{level} update: #{message}"
35
+ logger.debug "#{level} update: #{message}" unless level == levels.last
34
36
  end
35
37
 
36
38
  if status == :failed
@@ -40,6 +42,9 @@ module Secupdater
40
42
  end
41
43
 
42
44
  status
45
+ rescue Secupdater::PublishFailed => e
46
+ logger.error "#{dep.name}: #{e.message}"
47
+ :failed
43
48
  end
44
49
 
45
50
  private
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Secupdater
4
- VERSION = "0.1.0"
4
+ VERSION = "0.2.0alpha2"
5
5
  end
data/lib/secupdater.rb CHANGED
@@ -33,9 +33,12 @@ module Secupdater
33
33
  end
34
34
  end
35
35
 
36
+ class PublishFailed < Error; end
37
+
36
38
  def self.build_logger(log_level: :warn)
37
39
  Dry.Logger(
38
40
  :secupdater,
41
+ stream: $stderr,
39
42
  template: "[%<severity>s] %<message>s",
40
43
  level: log_level
41
44
  )
@@ -55,6 +55,8 @@ RSpec.describe "secupdater end to end" do
55
55
  File.write("bin/bundle", "#!/bin/sh\ncp Gemfile.lock.after Gemfile.lock\n")
56
56
  File.chmod(0o755, "bin/bundle")
57
57
 
58
+ system("git init -q && git add Gemfile.lock && git -c user.name=test -c user.email=test@example.com commit -qm init", exception: true)
59
+
58
60
  ENV.delete("SECUPDATER_GITLAB_TOKEN")
59
61
  ENV.update(env.merge("PATH" => "#{dir}/bin:#{ENV['PATH']}"))
60
62
  example.run
@@ -76,6 +78,7 @@ RSpec.describe "secupdater end to end" do
76
78
  stub_request(:post, "https://gitlab.com/api/v4/projects/123/repository/commits")
77
79
  .with(body: hash_including(
78
80
  branch: "security/css_parser-1.1.0",
81
+ start_sha: `git rev-parse HEAD`.strip,
79
82
  actions: [{ action: "update", file_path: "Gemfile.lock", content: lockfile("1.1.0") }]
80
83
  ))
81
84
  .to_return(status: 201, body: "{}")
@@ -99,7 +102,7 @@ RSpec.describe "secupdater end to end" do
99
102
 
100
103
  context "same fixture project without GitLab configuration (dry run)" do
101
104
  it "exits 0, reports what would be updated and makes no HTTP requests" do
102
- expect { run_cli("--verbose") }.to output(/css_parser from 1\.0\.0 to 1\.1\.0 \(patch\) would resolve/).to_stdout
105
+ expect { run_cli("--verbose") }.to output(/css_parser from 1\.0\.0 to 1\.1\.0 \(patch\) would resolve/).to_stderr
103
106
 
104
107
  expect(a_request(:any, //)).not_to have_been_made
105
108
  expect(File.read("Gemfile.lock")).to eq(lockfile("1.0.0"))
@@ -6,6 +6,7 @@ RSpec.describe Secupdater::CLI::Commands::Run do
6
6
  let(:err) { StringIO.new }
7
7
  let(:runner) { instance_double(Secupdater::Runner, call: { "rack" => :published }) }
8
8
  let(:env) { {} }
9
+ let(:git_head) { ["abc123\n", instance_double(Process::Status, success?: true)] }
9
10
 
10
11
  def run_cli(*arguments)
11
12
  Dry::CLI.new(Secupdater::CLI::Commands).call(arguments: ["run", *arguments], out: out, err: err)
@@ -18,6 +19,7 @@ RSpec.describe Secupdater::CLI::Commands::Run do
18
19
  before do
19
20
  stub_const("ENV", env)
20
21
  allow(Secupdater::Runner).to receive(:new).and_return(runner)
22
+ allow(Open3).to receive(:capture2e).with("git", "rev-parse", "--verify", "HEAD").and_return(git_head)
21
23
  end
22
24
 
23
25
  describe "#call" do
@@ -49,15 +51,26 @@ RSpec.describe Secupdater::CLI::Commands::Run do
49
51
  context "with SECUPDATER_GITLAB_TOKEN set" do
50
52
  let(:env) { { "SECUPDATER_GITLAB_TOKEN" => "token", "CI_PROJECT_ID" => "123", "CI_DEFAULT_BRANCH" => "main" } }
51
53
 
52
- it "publishes to GitLab using the CI project and default branch" do
54
+ it "publishes to GitLab using the CI project and default branch, starting from the checked out commit" do
53
55
  run_cli("--ecosystem=rubygems", "audit.json")
54
56
 
55
57
  expect(Secupdater::Runner).to have_received(:new).with(hash_including(
56
58
  publisher: an_instance_of(Secupdater::Publisher::Gitlab).and(
57
- have_attributes(access_token: "token", project_id: "123", target_branch: "main")
59
+ have_attributes(access_token: "token", project_id: "123", target_branch: "main", start_sha: "abc123")
58
60
  )
59
61
  ))
60
62
  end
63
+
64
+ context "outside a git checkout" do
65
+ let(:git_head) { ["fatal: not a git repository\n", instance_double(Process::Status, success?: false)] }
66
+
67
+ it "prints why and exits non-zero" do
68
+ expect_exit(1) { run_cli("--ecosystem=rubygems", "audit.json") }
69
+
70
+ expect(err.string).to include("Can't find the current git commit", "not a git repository")
71
+ expect(Secupdater::Runner).not_to have_received(:new)
72
+ end
73
+ end
61
74
  end
62
75
 
63
76
  context "with SECUPDATER_GITLAB_TOKEN set but no CI_PROJECT_ID" do
@@ -137,10 +137,10 @@ RSpec.describe Secupdater::Ecosystem::Rubygems do
137
137
  end
138
138
  end
139
139
 
140
- it "runs a strict, conservative bundle update at the given level" do
140
+ it "runs a strict, conservative, unfrozen bundle update at the given level" do
141
141
  rubygems.try_update("css_parser", level: :minor)
142
142
 
143
- expect(Open3).to have_received(:capture2e).with("bundle", "update", "css_parser", "--conservative", "--minor", "--strict")
143
+ expect(Open3).to have_received(:capture2e).with({ "BUNDLE_FROZEN" => "false" }, "bundle", "update", "css_parser", "--conservative", "--minor", "--strict")
144
144
  end
145
145
 
146
146
  it "returns the lockfile change with its new and original content" do
@@ -164,7 +164,7 @@ RSpec.describe Secupdater::Ecosystem::Rubygems do
164
164
  it "passes it as a single argument without going through a shell" do
165
165
  rubygems.try_update("css_parser; touch pwned", level: :patch)
166
166
 
167
- expect(Open3).to have_received(:capture2e).with("bundle", "update", "css_parser; touch pwned", "--conservative", "--patch", "--strict")
167
+ expect(Open3).to have_received(:capture2e).with({ "BUNDLE_FROZEN" => "false" }, "bundle", "update", "css_parser; touch pwned", "--conservative", "--patch", "--strict")
168
168
  end
169
169
  end
170
170
 
@@ -180,5 +180,18 @@ RSpec.describe Secupdater::Ecosystem::Rubygems do
180
180
  end
181
181
  end
182
182
  end
183
+
184
+ context "command exits 16 (frozen lockfile)" do
185
+ let(:status) { instance_double(Process::Status, success?: false, exitstatus: 16) }
186
+
187
+ before { allow(Open3).to receive(:capture2e).and_return(["frozen mode is set", status]) }
188
+
189
+ it "raises Secupdater::Error rather than UpdateCommandFailed, so the run stops" do
190
+ expect { rubygems.try_update("css_parser", level: :patch) }.to raise_error(Secupdater::Error) do
191
+ expect(it).not_to be_a(Secupdater::UpdateCommandFailed)
192
+ expect(it.message).to include("frozen mode is set")
193
+ end
194
+ end
195
+ end
183
196
  end
184
197
  end
@@ -3,7 +3,7 @@ require "secupdater/publisher"
3
3
  require "secupdater/publisher/gitlab"
4
4
 
5
5
  RSpec.describe Secupdater::Publisher::Gitlab do
6
- subject(:gitlab) { described_class.new("access_token", "123", "main") }
6
+ subject(:gitlab) { described_class.new("access_token", "123", "main", "abc123") }
7
7
 
8
8
  let(:ecosystem) { Secupdater::Ecosystem::Rubygems.new }
9
9
  let(:dep) { Secupdater::DependencySpec.new("css_parser", "ruby", Gem::Version.new("1.0.0")) }
@@ -31,7 +31,7 @@ RSpec.describe Secupdater::Publisher::Gitlab do
31
31
  .with(
32
32
  body: {
33
33
  branch: "security/css_parser-1.1.0",
34
- start_branch: "main",
34
+ start_sha: "abc123",
35
35
  commit_message: "Upgrade RubyGems dependency css_parser to version 1.1.0",
36
36
  actions: [{ action: "update", file_path: "Gemfile.lock", content: "abc" }]
37
37
  },
@@ -83,9 +83,9 @@ RSpec.describe Secupdater::Publisher::Gitlab do
83
83
  .to_return(status: 400, body: '{"message":"A branch called security/css_parser-1.1.0 already exists"}')
84
84
  end
85
85
 
86
- it "raises Secupdater::Error including the response body" do
86
+ it "raises Secupdater::PublishFailed including the response body" do
87
87
  expect { gitlab.call(ecosystem, bump, advisories, changes) }
88
- .to raise_error(Secupdater::Error, /400.*already exists/)
88
+ .to raise_error(Secupdater::PublishFailed, /400.*already exists/)
89
89
 
90
90
  expect(create_mr_stub).not_to have_been_requested
91
91
  end
@@ -5,7 +5,7 @@ require "stringio"
5
5
  require "tmpdir"
6
6
 
7
7
  module UpdateSpec
8
- # outcomes: gem name => version try_update moves it to, :unchanged or :fail, or a hash of those by level
8
+ # outcomes: gem name => version try_update moves it to, :unchanged, :fail or :abort, or a hash of those by level
9
9
  class FakeEcosystem
10
10
  LOCKFILE = "Gemfile.lock"
11
11
 
@@ -40,6 +40,8 @@ module UpdateSpec
40
40
  case outcome
41
41
  when :fail
42
42
  raise Secupdater::UpdateCommandFailed.new("bundle update failed", 1, "could not resolve #{name}")
43
+ when :abort
44
+ raise Secupdater::Error, "lockfile is frozen"
43
45
  when :unchanged
44
46
  []
45
47
  else
@@ -241,6 +243,67 @@ RSpec.describe Secupdater::Update do
241
243
  expect(update.call([advisory("rack", "cve/1")])).to eq("rack" => :failed)
242
244
  expect(ecosystem.attempts.map(&:last)).to eq([:patch, :minor, :major])
243
245
  end
246
+
247
+ it "logs the last level's failure once, as an error" do
248
+ update.call([advisory("rack", "cve/1")])
249
+
250
+ expect(log.string.scan(/could not resolve rack/).length).to eq(3)
251
+ expect(log.string).not_to include("major update:")
252
+ end
253
+ end
254
+
255
+ context "publishing fails for the first gem" do
256
+ let(:outcomes) { { "rack" => "2.1", "nokogiri" => "2.0" } }
257
+
258
+ before do
259
+ allow(publisher).to receive(:call) do |_, bump, *|
260
+ raise Secupdater::PublishFailed, "branch already exists" if bump.dependency.name == "rack"
261
+
262
+ published << bump
263
+ end
264
+ end
265
+
266
+ it "returns :failed for that gem and continues to the next gem" do
267
+ results = update.call([advisory("rack", "cve/1"), advisory("nokogiri", "cve/2")])
268
+
269
+ expect(results).to eq("rack" => :failed, "nokogiri" => :published)
270
+ expect(published.map { it.dependency.name }).to eq(["nokogiri"])
271
+ end
272
+
273
+ it "doesn't try the other levels" do
274
+ update.call([advisory("rack", "cve/1")])
275
+
276
+ expect(ecosystem.attempts).to eq([["rack", :patch]])
277
+ end
278
+
279
+ it "logs the failure as an error" do
280
+ update.call([advisory("rack", "cve/1")])
281
+
282
+ expect(log.string).to match(/^ERROR rack: branch already exists/)
283
+ end
284
+
285
+ it "leaves the lockfile as it found it" do
286
+ update.call([advisory("rack", "cve/1")])
287
+
288
+ expect(lockfile_on_disk).to eq(lockfile)
289
+ end
290
+ end
291
+
292
+ context "an error that isn't an update failure" do
293
+ let(:outcomes) { { "rack" => :abort, "nokogiri" => "2.0" } }
294
+
295
+ it "stops the run without trying other levels or gems" do
296
+ expect { update.call([advisory("rack", "cve/1"), advisory("nokogiri", "cve/2")]) }
297
+ .to raise_error(Secupdater::Error, "lockfile is frozen")
298
+
299
+ expect(ecosystem.attempts).to eq([["rack", :patch]])
300
+ end
301
+
302
+ it "leaves the lockfile as it found it" do
303
+ expect { update.call([advisory("rack", "cve/1")]) }.to raise_error(Secupdater::Error)
304
+
305
+ expect(lockfile_on_disk).to eq(lockfile)
306
+ end
244
307
  end
245
308
 
246
309
  context "a mix of outcomes" do
@@ -0,0 +1,9 @@
1
+ require "secupdater"
2
+
3
+ RSpec.describe Secupdater do
4
+ describe ".build_logger" do
5
+ it "logs to stderr, so log lines stay in order with errors when stdout is buffered" do
6
+ expect { Secupdater.build_logger.warn("hello") }.to output("[WARN] hello\n").to_stderr
7
+ end
8
+ end
9
+ end
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.1.0
4
+ version: 0.2.0alpha2
5
5
  platform: ruby
6
6
  authors:
7
7
  - Ben Anderson
@@ -97,6 +97,7 @@ files:
97
97
  - spec/secupdater/publisher_spec.rb
98
98
  - spec/secupdater/runner_spec.rb
99
99
  - spec/secupdater/update_spec.rb
100
+ - spec/secupdater_spec.rb
100
101
  - spec/spec_helper.rb
101
102
  homepage: https://github.com/bagedevimo/secupdater
102
103
  licenses: