secupdater 0.8.0 → 0.9.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.
Files changed (35) hide show
  1. checksums.yaml +4 -4
  2. data/.release-please-manifest.json +1 -1
  3. data/CHANGELOG.md +16 -0
  4. data/examples/central-project/.gitlab-ci.yml +87 -33
  5. data/lib/secupdater/cli.rb +1 -1
  6. data/lib/secupdater/ecosystem/rubygems.rb +7 -0
  7. data/lib/secupdater/ecosystem.rb +34 -4
  8. data/lib/secupdater/executor.rb +10 -8
  9. data/lib/secupdater/publisher/gitlab.rb +29 -11
  10. data/lib/secupdater/publisher.rb +7 -8
  11. data/lib/secupdater/update.rb +3 -5
  12. data/lib/secupdater/version.rb +1 -1
  13. data/lib/secupdater/yarn_support/audit.rb +86 -0
  14. data/lib/secupdater/yarn_support/lockfile.rb +79 -0
  15. data/lib/secupdater/yarn_support/package_name.rb +14 -0
  16. data/lib/secupdater/yarn_support/range.rb +152 -0
  17. data/lib/secupdater/yarn_support/version.rb +65 -0
  18. data/lib/secupdater.rb +4 -2
  19. data/spec/fixtures/yarn/audit.ndjson +9 -0
  20. data/spec/fixtures/yarn/protocols.yarn.lock +99 -0
  21. data/spec/fixtures/yarn/yarn.lock +265 -0
  22. data/spec/fixtures/yarn/yarn1.lock +8 -0
  23. data/spec/secupdater/cli_spec.rb +11 -0
  24. data/spec/secupdater/ecosystem/rubygems_spec.rb +40 -0
  25. data/spec/secupdater/ecosystem_spec.rb +71 -0
  26. data/spec/secupdater/executor_spec.rb +23 -5
  27. data/spec/secupdater/publisher/gitlab_spec.rb +85 -14
  28. data/spec/secupdater/update_spec.rb +22 -9
  29. data/spec/secupdater/yarn_support/audit_spec.rb +144 -0
  30. data/spec/secupdater/yarn_support/lockfile_spec.rb +171 -0
  31. data/spec/secupdater/yarn_support/package_name_spec.rb +40 -0
  32. data/spec/secupdater/yarn_support/range_spec.rb +158 -0
  33. data/spec/secupdater/yarn_support/version_spec.rb +61 -0
  34. data/spec/secupdater_spec.rb +9 -0
  35. metadata +15 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 193eaa1dbaeff56dd50e023bfb1b70357db13581d61308ce61ec1114878cf869
4
- data.tar.gz: d59ec086126b2f4cfaaf2f6efc9167cd6bc4357cce0fad9fb3b341666e0cf4de
3
+ metadata.gz: 1ac6fafa5e529dcabea559759f8954a8a81456d89d0571396f612e782f10b777
4
+ data.tar.gz: 2816a48b20f9500e73afcf7ab8fb0843a2acca7304b57f8ee53d4adc9ef0f48d
5
5
  SHA512:
6
- metadata.gz: 655cfde4d58e0d366e005db6a63b3432c83ecc48cf291c055d4799cff7092173c8a98d86c18359d48817f91cb8bc794f6aefcc43e2952f15c138d7a89909b592
7
- data.tar.gz: e33962f75fb8606738635446f8c84c3dffcc5dd85245d7b29c3f437242da93a4ebd193979b4204019f939f0172f93407f184f449ccdd3530f19fc2bf0f37ea5c
6
+ metadata.gz: 8420dfbaea573269919c9337ea443e426f2fcb8dd96c95866788626a709e593d7e99e64e758345ce413f70b6c59ee2706190965c726ce960dd80cca69b31fa3b
7
+ data.tar.gz: ddb0053a0937dcad82224ada7486a7dc8c51d8c60b10499b409c1eabe7a0a051e51d653ea2c760c4a0aee6de8fbadd0f32531c64048f5eaa81a4d57d7765c0c7
@@ -1,3 +1,3 @@
1
1
  {
2
- ".": "0.8.0"
2
+ ".": "0.9.0"
3
3
  }
data/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.9.0](https://github.com/bagedevimo/secupdater/compare/v0.8.0...v0.9.0) (2026-12-02)
4
+
5
+
6
+ ### ⚠ BREAKING CHANGES
7
+
8
+ * only set MRs to auto-merge when they need approval, so they never merge unreviewed
9
+
10
+ ### Features
11
+
12
+ * only set MRs to auto-merge when they need approval, so they never merge unreviewed ([a2392da](https://github.com/bagedevimo/secupdater/commit/a2392da318213f4d21e7c98d20f23e70c5a153e4))
13
+
14
+
15
+ ### Bug Fixes
16
+
17
+ * warn instead of failing the run when the token isn't allowed to merge an MR ([a2392da](https://github.com/bagedevimo/secupdater/commit/a2392da318213f4d21e7c98d20f23e70c5a153e4))
18
+
3
19
  ## [0.8.0](https://github.com/bagedevimo/secupdater/compare/v0.7.0...v0.8.0) (2026-12-02)
4
20
 
5
21
 
@@ -16,23 +16,31 @@
16
16
  # 4. Add a pipeline schedule (e.g. hourly) to this project.
17
17
  #
18
18
  # The discover job audits every opted-in project's Gemfile.lock. The update job
19
- # then runs secupdater, in a container on that project's own Ruby, for each one
20
- # with advisories or with open secupdater MRs (so it can close the ones that are
21
- # no longer needed).
19
+ # then runs secupdater for each one with advisories or with open secupdater MRs
20
+ # (so it can close the ones that are no longer needed).
22
21
  #
23
22
  # The dashboard job then keeps a confidential issue in this project (labelled
24
23
  # secupdater-dashboard) up to date with every opted-in project, its advisories
25
24
  # and its open secupdater MRs.
26
25
  #
27
26
  # Anyone who can push to an opted-in project's default branch can change the
28
- # Gemfile that `bundle lock` evaluates here. secupdater keeps the token out of
29
- # that process's environment and out of the clone's git config, but treat
30
- # opting in as trusting that project with the token.
27
+ # Gemfile that `bundle lock` evaluates here, and so run code in this job. So the
28
+ # update job runs secupdater (with SECUPDATER_GITLAB_TOKEN) in one container,
29
+ # and the project's bundle commands in a second one on the project's own Ruby,
30
+ # with no GitLab token, no Docker socket and all capabilities dropped. The
31
+ # Gemfile's code can still:
32
+ # - read SECUPDATER_CLONE_TOKEN, if it's set
33
+ # - reach the network
34
+ # - change any file in the clone, which secupdater then reads and turns into
35
+ # an MR, so review secupdater MRs like any other (the job removes .git
36
+ # first, so there's no git config to plant)
37
+ # - attack the runner host's kernel, as containers share it
38
+ # so opting in still means trusting that project with the runner.
31
39
 
32
40
  variables:
33
41
  SECUPDATER_GROUP: delivereasy
34
42
  SECUPDATER_TOPIC: secupdater
35
- SECUPDATER_VERSION: "0.6.0" # the first release with `secupdater dashboard`
43
+ SECUPDATER_VERSION: "0.8.0" # the first release with `secupdater run --executor`
36
44
  # Most secupdater MRs to have open in each project at once. Past it, new ones
37
45
  # wait (most severe first) while existing ones still get kept up to date.
38
46
  SECUPDATER_MAX_OPEN_MRS: "3"
@@ -79,40 +87,86 @@ discover:
79
87
  expire_in: 1 day
80
88
 
81
89
  update:
82
- image: docker:27
83
- services: [docker:27-dind]
90
+ # Needs the runner host's Docker daemon, not Docker-in-Docker: secupdater runs
91
+ # in its own container and has to reach the same daemon to run the bundle
92
+ # commands. Mount the host's socket into this job (e.g. `volumes =
93
+ # ["/var/run/docker.sock:/var/run/docker.sock"]` in the runner's config.toml).
94
+ image: docker:29-cli
84
95
  variables:
85
- DOCKER_TLS_CERTDIR: "/certs"
96
+ DOCKER_HOST: unix:///var/run/docker.sock
97
+ # The socket's path on the host, which is what the secupdater container
98
+ # mounts, as the host's daemon resolves bind mounts. Only differs from
99
+ # DOCKER_HOST's path if the runner mounts it somewhere else in this job.
100
+ HOST_DOCKER_SOCKET: /var/run/docker.sock
86
101
  needs: [discover]
102
+ # One at a time, as overlapping pipelines would race each other on the same
103
+ # MRs and on SECUPDATER_MAX_OPEN_MRS
104
+ resource_group: secupdater
87
105
  # Still update the projects discover could check when it couldn't check them all
88
106
  when: always
89
107
  script:
108
+ # Fails fast if the Docker socket isn't there, even when there's nothing to update
109
+ - docker version --format 'Docker {{.Server.Version}}'
110
+ # resource_group means no other update job is running, so these are a dead job's leftovers
111
+ - docker ps --all --quiet --filter label=secupdater.central=1 | xargs -r docker rm -f
112
+ - docker volume ls --quiet --filter label=secupdater.central=1 | xargs -r docker volume rm
90
113
  - |
91
114
  failed=0
92
- while read -r id path branch ruby url; do
115
+ # run.txt on fd 3, so nothing in the loop can read the rest of it
116
+ while read -r id path branch ruby url <&3; do
93
117
  echo "== $path (Ruby $ruby)"
94
- # The report goes in on stdin, as the dind daemon can't see this job's files
95
- docker run --rm -i \
96
- -e SECUPDATER_GITLAB_TOKEN -e SECUPDATER_CLONE_TOKEN -e SECUPDATER_VERSION \
97
- -e SECUPDATER_MAX_OPEN_MRS \
98
- -e SECUPDATER_PROJECT_ID="$id" -e SECUPDATER_TARGET_BRANCH="$branch" -e CLONE_URL="$url" \
99
- "ruby:$ruby" sh -euc '
100
- cat > /tmp/audit.json
101
- git clone --quiet --depth 1 --branch "$SECUPDATER_TARGET_BRANCH" \
102
- "https://oauth2:${SECUPDATER_GITLAB_TOKEN}@${CLONE_URL#https://}" /repo
103
- cd /repo
104
- git remote remove origin # takes the token out of .git/config
105
- if [ -n "${SECUPDATER_CLONE_TOKEN:-}" ]; then
106
- # Lets bundle lock fetch git gems from private GitLab repositories,
107
- # over HTTPS with the read-only clone token
108
- git config --global url."https://gitlab.com/".insteadOf "git@gitlab.com:"
109
- git config --global credential.https://gitlab.com.username oauth2
110
- git config --global credential.https://gitlab.com.helper "!f() { echo password=\$SECUPDATER_CLONE_TOKEN; }; f"
111
- fi
112
- gem install secupdater -v "$SECUPDATER_VERSION" --no-document --silent
113
- secupdater run --ecosystem=rubygems --verbose /tmp/audit.json
114
- ' < "projects/$id/audit.json" || failed=1
115
- done < projects/run.txt
118
+ # The job ID keeps these names from clashing with any other job's
119
+ name="secupdater-$CI_JOB_ID-$id"
120
+ # In a subshell, so the trap removes this project's containers when it's
121
+ # done. `|| exit` because set -e doesn't apply in a subshell before `||`.
122
+ (
123
+ cleanup() {
124
+ docker rm -f "$name-ruby" > /dev/null 2>&1
125
+ docker volume rm "$name" > /dev/null 2>&1
126
+ true
127
+ }
128
+ trap cleanup EXIT
129
+
130
+ docker volume create --label secupdater.central=1 "$name" > /dev/null || exit
131
+ # Runs the project's bundle commands, so its Gemfile. No GitLab token
132
+ # or Docker socket, and the clone at the same path as secupdater's.
133
+ docker run --detach --name "$name-ruby" --label secupdater.central=1 --cap-drop ALL --security-opt no-new-privileges \
134
+ --volume "$name:/repo" --workdir /repo "ruby:$ruby" sleep infinity > /dev/null || exit
135
+ if [ -n "${SECUPDATER_CLONE_TOKEN:-}" ]; then
136
+ # Lets bundle lock fetch git gems from private GitLab repositories,
137
+ # over HTTPS with the read-only clone token
138
+ docker exec --env SECUPDATER_CLONE_TOKEN "$name-ruby" sh -euc '
139
+ url="https://oauth2:${SECUPDATER_CLONE_TOKEN}@gitlab.com/"
140
+ git config --global url."$url".insteadOf "git@gitlab.com:"
141
+ git config --global --add url."$url".insteadOf "https://gitlab.com/"
142
+ ' || exit
143
+ fi
144
+
145
+ # Runs secupdater, which runs the bundle commands with `docker exec` in
146
+ # the Ruby container. The report goes in on stdin, as the host's
147
+ # Docker daemon can't see this job's files.
148
+ docker run --rm --interactive \
149
+ --volume "$HOST_DOCKER_SOCKET:/var/run/docker.sock" --volume "$name:/repo" \
150
+ --env SECUPDATER_GITLAB_TOKEN --env SECUPDATER_VERSION --env SECUPDATER_MAX_OPEN_MRS \
151
+ --env SECUPDATER_PROJECT_ID="$id" --env SECUPDATER_TARGET_BRANCH="$branch" --env CLONE_URL="$url" \
152
+ --env SECUPDATER_RUBY_CONTAINER="$name-ruby" \
153
+ docker:29-cli sh -euc '
154
+ cat > /tmp/audit.json
155
+ # secupdater needs Bundler to read Gemfile.lock
156
+ apk add --no-cache --quiet ruby ruby-bundler git
157
+ git clone --quiet --depth 1 --branch "$SECUPDATER_TARGET_BRANCH" \
158
+ "https://oauth2:${SECUPDATER_GITLAB_TOKEN}@${CLONE_URL#https://}" /repo
159
+ cd /repo
160
+ # Records the commit, then removes .git (and the token in its
161
+ # config): the Ruby container can write to the clone, so could
162
+ # plant git config that runs here, next to the token, on any git command
163
+ export SECUPDATER_HEAD_COMMIT="$(git rev-parse --verify HEAD)"
164
+ rm -rf .git
165
+ gem install secupdater -v "$SECUPDATER_VERSION" --no-document --silent
166
+ secupdater run --executor=docker --ecosystem=rubygems --verbose /tmp/audit.json
167
+ ' < "projects/$id/audit.json"
168
+ ) || failed=1
169
+ done 3< projects/run.txt
116
170
  exit $failed
117
171
 
118
172
  dashboard:
@@ -31,7 +31,7 @@ module Secupdater
31
31
  def call(ecosystem:, advisories:, executor:, verbose:, debug:, max_open_mrs: nil, **)
32
32
  log_level = if debug then :debug elsif verbose then :info else :warn end
33
33
  max_open_mrs = parse_max_open_mrs(max_open_mrs || ENV.fetch("SECUPDATER_MAX_OPEN_MRS", DEFAULT_MAX_OPEN_MRS.to_s))
34
- executor = Executor.resolve(executor, ENV)
34
+ executor = Executor.resolve(executor, ENV, runtimes: Ecosystem.class_for(ecosystem).runtimes)
35
35
  results = Runner.new(ecosystem: ecosystem, log_level: log_level, publisher: publisher, max_open_mrs:, executor:).call(advisories)
36
36
 
37
37
  exit(1) if results.value?(:failed)
@@ -10,9 +10,16 @@ module Secupdater
10
10
  UNRETRYABLE_EXIT_CODES = [10, 11, 13, 14, 17, 18].freeze
11
11
 
12
12
  def self.ecosystem_name = "RubyGems"
13
+ def self.runtimes = [:ruby]
13
14
 
14
15
  def manifest_paths = ["Gemfile.lock"]
15
16
 
17
+ # Without a kind, as before there were other ecosystems, so their open
18
+ # MRs are still recognised. Gem names never contain "/", which keeps
19
+ # other ecosystems' security/<kind>/ branches out.
20
+ def branch_prefix = "security/"
21
+ def branch_pattern = %r{\Asecurity/(?<name>[^/]+)-(?<version>[^-]+)\z}
22
+
16
23
  def snapshot
17
24
  Bundler::LockfileParser.new(lockfile)
18
25
  .specs
@@ -3,6 +3,9 @@ module Secupdater
3
3
  def self.ecosystem_name = raise NotImplementedError
4
4
  def ecosystem_name = self.class.ecosystem_name
5
5
 
6
+ # What the executor runs commands with (keys of Executor::Docker::CONTAINER_VARIABLES)
7
+ def self.runtimes = raise NotImplementedError
8
+
6
9
  def manifest_paths = raise NotImplementedError
7
10
  def run_update(names, level) = raise NotImplementedError
8
11
  def snapshot = raise NotImplementedError
@@ -12,6 +15,32 @@ module Secupdater
12
15
 
13
16
  def update_levels = [:patch, :minor, :major]
14
17
 
18
+ # Whether the version an update locked the dependency at fixes the
19
+ # advisory. version is whatever diff_snapshot gave as the dependency's
20
+ # new version, which needn't be a single version.
21
+ def fixes?(version, advisory)
22
+ advisory.patched_versions.any? { satisfies_requirement?(version, it) }
23
+ end
24
+
25
+ # MR branches are security/<kind>/<name>-<version>, so each ecosystem's
26
+ # runs only touch their own MRs
27
+ def branch_prefix = "security/#{ecosystem_name.downcase}/"
28
+
29
+ # The version a branch names, e.g. one of several locked at once
30
+ def branch_version(version) = version.to_s
31
+
32
+ def branch_name(name, version) = "#{branch_prefix}#{name}-#{branch_version(version)}"
33
+
34
+ # The dependency a branch from #branch_name is for, or nil if it isn't one
35
+ def dependency_from_branch(branch) = branch[branch_pattern, :name]
36
+
37
+ # npm-style names, which may have an @scope/, and semver versions, which
38
+ # may contain "-" too (e.g. 1.0.0-beta.1), so it's the version that has to
39
+ # match exactly
40
+ def branch_pattern
41
+ %r{\A#{Regexp.escape(branch_prefix)}(?<name>(?:@[^/]+/)?[^/@]+)-(?<version>\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]*)?)\z}
42
+ end
43
+
15
44
  # Runs anything that executes the repo's code
16
45
  attr_reader :executor
17
46
 
@@ -19,10 +48,11 @@ module Secupdater
19
48
  @executor = executor
20
49
  end
21
50
 
22
- def self.resolve(name, executor: Executor::Local.new)
23
- klass = self.subclasses.detect { it.ecosystem_name.downcase == name.downcase }
24
- raise Secupdater::Error, "Unknown ecosystem: #{name}" unless klass
25
- klass.new(executor:)
51
+ def self.resolve(name, executor: Executor::Local.new) = class_for(name).new(executor:)
52
+
53
+ # Without building one, e.g. to check the executor can run its runtimes first
54
+ def self.class_for(name)
55
+ subclasses.detect { it.ecosystem_name.downcase == name.downcase } or raise Secupdater::Error, "Unknown ecosystem: #{name}"
26
56
  end
27
57
 
28
58
  def try_update(names, level:)
@@ -7,10 +7,11 @@ module Secupdater
7
7
  # [output, status] like Open3.capture2e, keeping the command's exit code. A
8
8
  # nil env value means unset.
9
9
  module Executor
10
- def self.resolve(name, env)
10
+ # runtimes: those the ecosystem runs commands with (see Ecosystem.runtimes)
11
+ def self.resolve(name, env, runtimes:)
11
12
  case name
12
13
  when "local" then Local.new
13
- when "docker" then Docker.from_env(env)
14
+ when "docker" then Docker.from_env(env, runtimes:)
14
15
  else raise Secupdater::Error, "Unknown executor: #{name}"
15
16
  end
16
17
  end
@@ -43,17 +44,18 @@ module Secupdater
43
44
  # have the repo mounted at the same path as here, and neither the GitLab
44
45
  # token nor the Docker socket. They get only the env given, never ours.
45
46
  class Docker
46
- CONTAINER_VARIABLES = { ruby: "SECUPDATER_RUBY_CONTAINER" }.freeze
47
+ CONTAINER_VARIABLES = { ruby: "SECUPDATER_RUBY_CONTAINER", node: "SECUPDATER_NODE_CONTAINER" }.freeze
47
48
 
48
49
  attr_reader :containers
49
50
 
50
51
  # Each runtime's container is only checked when a command needs it, but
51
- # one with none at all is misconfigured even if there's nothing to update.
52
- # CI expands an undefined variable to "", so that's unset too.
53
- def self.from_env(env)
52
+ # missing one the ecosystem runs is misconfigured even if there's nothing
53
+ # to update. CI expands an undefined variable to "", so that's unset too.
54
+ def self.from_env(env, runtimes:)
54
55
  containers = CONTAINER_VARIABLES.transform_values { env[it] }.reject { |_, name| name.to_s.empty? }
55
- if containers.empty?
56
- raise Secupdater::Error, "--executor=docker needs #{CONTAINER_VARIABLES.values.join(" or ")} set to a running container"
56
+ missing = runtimes.reject { containers.key?(it) }.map { CONTAINER_VARIABLES.fetch(it) }
57
+ if missing.any?
58
+ raise Secupdater::Error, "--executor=docker needs #{missing.join(" and ")} set to a running container"
57
59
  end
58
60
 
59
61
  new(containers:)
@@ -21,7 +21,7 @@ module Secupdater
21
21
  def footer
22
22
  <<~MARKDOWN.chomp
23
23
  ---
24
- Opened by secupdater, which keeps this MR up to date with `#{target_branch}` and sets it to merge once its pipeline passes. \
24
+ Opened by secupdater, which keeps this MR up to date with `#{target_branch}` and, if it needs approval, sets it to merge once it's approved and its pipeline passes. \
25
25
  Closing it declines #{bump.dependency.name} #{bump.to}; reopen it or remove its `#{LABEL}` label to have it updated again.
26
26
  MARKDOWN
27
27
  end
@@ -72,11 +72,12 @@ module Secupdater
72
72
 
73
73
  # Any open MR for the branch, labelled or not, as that's what #run updates,
74
74
  # or an open secupdater MR for another version of the dependency, as
75
- # #finish closes it once this one is published
76
- def merge_request_open_for?(dependency_bump)
75
+ # #finish closes it once this one is published. Only the ecosystem's own
76
+ # branches, as another's dependency can have the same name.
77
+ def merge_request_open_for?(ecosystem, dependency_bump)
77
78
  Net::HTTP.start("gitlab.com", 443, use_ssl: true) do |http|
78
- find_merge_requests(http, reference(dependency_bump)).any? { it["state"] == "opened" } ||
79
- find_open_secupdater_merge_requests(http).any? { it["source_branch"][REFERENCE_PATTERN, :name] == dependency_bump.dependency.name }
79
+ find_merge_requests(http, reference(dependency_bump, ecosystem:)).any? { it["state"] == "opened" } ||
80
+ find_open_secupdater_merge_requests(http).any? { ecosystem.dependency_from_branch(it["source_branch"]) == dependency_bump.dependency.name }
80
81
  end
81
82
  end
82
83
 
@@ -86,16 +87,19 @@ module Secupdater
86
87
 
87
88
  # Closes open secupdater MRs for a dependency that this run opened or kept a
88
89
  # different MR for, or that no longer has any advisories. MRs for
89
- # dependencies this run couldn't update are left alone.
90
- def finish(vulnerable_names)
90
+ # dependencies this run couldn't update, or for other ecosystems, are left
91
+ # alone.
92
+ def finish(ecosystem, vulnerable_names)
91
93
  Net::HTTP.start("gitlab.com", 443, use_ssl: true) do |http|
92
94
  find_open_secupdater_merge_requests(http).filter_map do |merge_request|
93
- name = merge_request["source_branch"][REFERENCE_PATTERN, :name]
95
+ name = ecosystem.dependency_from_branch(merge_request["source_branch"])
96
+ next unless name
97
+
94
98
  current = @current_merge_requests[name]
95
99
 
96
100
  reason = if current && current != merge_request["iid"]
97
101
  "Superseded by !#{current}."
98
- elsif name && !vulnerable_names.include?(name)
102
+ elsif !vulnerable_names.include?(name)
99
103
  "#{name} no longer has any security advisories on #{target_branch}, so this is no longer needed."
100
104
  end
101
105
  next unless reason
@@ -155,7 +159,8 @@ module Secupdater
155
159
 
156
160
  # GitLab doesn't document what auto-merge does without a pipeline, so it
157
161
  # is only set once the branch's head commit has a pipeline that can still
158
- # pass. Returns a message if GitLab won't set it (e.g. the MR can't merge).
162
+ # pass. Returns a message if GitLab won't set it (e.g. the MR can't merge,
163
+ # or the token isn't allowed to merge into the target branch).
159
164
  def enable_auto_merge(http, iid)
160
165
  merge_request = JSON.parse(request(http, Net::HTTP::Get, "merge_requests/#{iid}").body)
161
166
  return if merge_request["merge_when_pipeline_succeeds"] || merge_request["draft"]
@@ -164,14 +169,27 @@ module Secupdater
164
169
  return unless pipeline && pipeline["sha"] == merge_request["sha"]
165
170
  return if %w[failed canceled skipped].include?(pipeline["status"])
166
171
 
172
+ # Auto-merge then still waits for someone to approve the MR. Without
173
+ # required approvals it would merge unreviewed, so it's left for
174
+ # someone to merge by hand.
175
+ return unless approval_required?(http, iid)
176
+
167
177
  # sha makes GitLab refuse (409) if the branch has moved on since
168
178
  data = { auto_merge: true, sha: merge_request["sha"], should_remove_source_branch: true }
169
- res = request(http, Net::HTTP::Put, "merge_requests/#{iid}/merge", data, tolerate: [405, 406, 409, 422])
179
+ # GitLab returns 401, not 403, when the token can't merge into the target branch
180
+ res = request(http, Net::HTTP::Put, "merge_requests/#{iid}/merge", data, tolerate: [401, 405, 406, 409, 422])
170
181
  return if res.is_a?(Net::HTTPSuccess)
171
182
 
172
183
  "#{reference}: couldn't set !#{iid} to auto-merge, GitLab returned #{res.code}: #{res.body}"
173
184
  end
174
185
 
186
+ # From the MR's approval rules, so it counts rules scoped to the target
187
+ # branch and code owners as well as the project's own
188
+ def approval_required?(http, iid)
189
+ approvals = JSON.parse(request(http, Net::HTTP::Get, "merge_requests/#{iid}/approvals").body)
190
+ approvals["approvals_required"].to_i.positive?
191
+ end
192
+
175
193
  def close_merge_request(http, iid, reason)
176
194
  request(http, Net::HTTP::Post, "merge_requests/#{iid}/notes", { body: reason })
177
195
  request(http, Net::HTTP::Put, "merge_requests/#{iid}", { state_event: "close" })
@@ -21,22 +21,21 @@ module Secupdater
21
21
  run
22
22
  end
23
23
 
24
- # Called once every dependency has been through #call, with the names of all
25
- # the dependencies that have advisories. Returns messages about anything it
24
+ # Called once every dependency has been through #call, with the ecosystem
25
+ # and the names of all its dependencies that have advisories, so it only
26
+ # tidies up that ecosystem's MRs. Returns messages about anything it
26
27
  # tidied up.
27
- def finish(vulnerable_names) = []
28
+ def finish(ecosystem, vulnerable_names) = []
28
29
 
29
30
  # Whether #call would update or replace an MR that's already open for this
30
31
  # bump's dependency, rather than add one, so it doesn't count towards a cap
31
- # on open MRs
32
- def merge_request_open_for?(dependency_bump) = raise NotImplementedError
32
+ # on open MRs. Takes the ecosystem as it can come before any #call.
33
+ def merge_request_open_for?(ecosystem, dependency_bump) = raise NotImplementedError
33
34
 
34
35
  # How many MRs secupdater has open in the project, of any kind
35
36
  def open_merge_request_count = raise NotImplementedError
36
37
 
37
- REFERENCE_PATTERN = %r{\Asecurity/(?<name>.+)-(?<version>[^-]+)\z}
38
-
39
- def reference(dependency_bump = bump) = "security/#{dependency_bump.dependency.name}-#{dependency_bump.to}"
38
+ def reference(dependency_bump = bump, ecosystem: self.ecosystem) = ecosystem.branch_name(dependency_bump.dependency.name, dependency_bump.to)
40
39
 
41
40
  def title = "Upgrade #{ecosystem.ecosystem_name} dependency #{bump.dependency.name} to version #{bump.to}"
42
41
 
@@ -35,7 +35,7 @@ module Secupdater
35
35
 
36
36
  results = publish(candidates)
37
37
 
38
- publisher&.finish(deps_needing_checking.keys)&.each { logger.info it }
38
+ publisher&.finish(ecosystem, deps_needing_checking.keys)&.each { logger.info it }
39
39
 
40
40
  deps_needing_checking.keys.to_h { [it, results.fetch(it)] }
41
41
  end
@@ -154,9 +154,7 @@ module Secupdater
154
154
  end
155
155
 
156
156
  def fixes?(bump, advisories)
157
- advisories.all? do |advisory|
158
- advisory.patched_versions.any? { ecosystem.satisfies_requirement?(bump.to, it) }
159
- end
157
+ advisories.all? { ecosystem.fixes?(bump.to, it) }
160
158
  end
161
159
 
162
160
  def publish_candidate(candidate, covered)
@@ -174,7 +172,7 @@ module Secupdater
174
172
  return :resolved unless publisher
175
173
 
176
174
  # Updating or replacing an MR that's already open never counts towards the cap
177
- new_merge_request = max_open_mrs && !publisher.merge_request_open_for?(candidate.bump)
175
+ new_merge_request = max_open_mrs && !publisher.merge_request_open_for?(ecosystem, candidate.bump)
178
176
  if new_merge_request && open_slots <= 0
179
177
  logger.warn "#{candidate.name}: deferred, it'll open once fewer than #{max_open_mrs} secupdater MRs are open"
180
178
  return :deferred
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Secupdater
4
- VERSION = "0.8.0"
4
+ VERSION = "0.9.0"
5
5
  end
@@ -0,0 +1,86 @@
1
+ require "json"
2
+ require_relative "range"
3
+ require_relative "package_name"
4
+
5
+ module Secupdater
6
+ module YarnSupport
7
+ # vulnerable_versions is an npm range string, see Range
8
+ Finding = Struct.new(:name, :report_id, :title, :url, :severity, :vulnerable_versions)
9
+
10
+ # Reads `yarn npm audit --all --recursive --json` output: one JSON object per line
11
+ module Audit
12
+ SEVERITIES = %w[info low moderate high critical].freeze
13
+ GHSA_ID = /\AGHSA(?:-[0-9a-z]{4}){3}\z/
14
+
15
+ def self.parse(io)
16
+ findings = {}
17
+ ranges = Hash.new { |hash, key| hash[key] = [] }
18
+
19
+ io.each_line.with_index(1) do |line, number|
20
+ line = line.dup.force_encoding(Encoding::UTF_8)
21
+ raise Secupdater::Error, "yarn npm audit line #{number} isn't valid UTF-8" unless line.valid_encoding?
22
+ next if line.strip.empty?
23
+
24
+ finding = finding(line, number)
25
+ key = [finding.name, finding.report_id]
26
+ ranges[key] << finding.vulnerable_versions
27
+
28
+ # Yarn reports an advisory once per vulnerable version line it affects, e.g. minimist 0.x and 1.x
29
+ findings[key] = findings.key?(key) ? highest_severity(findings[key], finding) : finding
30
+ end
31
+
32
+ findings.map do |key, finding|
33
+ # A blank range means any version, so it mustn't vanish from the joined string
34
+ finding.vulnerable_versions = ranges[key].map { it.strip.empty? ? "*" : it }.uniq.join(" || ")
35
+ finding
36
+ end
37
+ end
38
+
39
+ def self.finding(line, number)
40
+ entry = begin
41
+ JSON.parse(line)
42
+ rescue JSON::ParserError
43
+ raise Secupdater::Error, "yarn npm audit line #{number} isn't JSON: #{line.strip[0, 200]}"
44
+ end
45
+
46
+ unless entry.is_a?(Hash) && entry["value"] && entry["children"].is_a?(Hash)
47
+ raise Secupdater::Error, "yarn npm audit line #{number} has no value or children: #{line.strip[0, 200]}"
48
+ end
49
+
50
+ children = entry["children"]
51
+
52
+ Finding.new(
53
+ YarnSupport.check_name!(entry["value"]),
54
+ report_id(children),
55
+ children["Issue"],
56
+ children["URL"],
57
+ severity(children["Severity"]),
58
+ Range.new(children["Vulnerable Versions"]).to_s,
59
+ )
60
+ end
61
+
62
+ # The GHSA id from the advisory URL, which stays the same across a package's version lines
63
+ def self.report_id(children)
64
+ ghsa = children["URL"].to_s.split("/").last
65
+ return ghsa if ghsa&.match?(GHSA_ID)
66
+
67
+ id = children["ID"].to_s
68
+ raise Secupdater::Error, "yarn npm audit advisory has no GHSA id or numeric ID: #{children.inspect[0, 200]}" unless id.match?(/\A\d+\z/)
69
+
70
+ id
71
+ end
72
+
73
+ def self.severity(severity)
74
+ raise Secupdater::Error, "unknown yarn npm audit severity #{severity.inspect}" unless SEVERITIES.include?(severity)
75
+
76
+ severity
77
+ end
78
+
79
+ def self.highest_severity(finding, other)
80
+ SEVERITIES.index(other.severity) > SEVERITIES.index(finding.severity) ? finding.dup.tap { it.severity = other.severity } : finding
81
+ end
82
+
83
+ private_class_method :finding, :report_id, :severity, :highest_severity
84
+ end
85
+ end
86
+ end
@@ -0,0 +1,79 @@
1
+ require "yaml"
2
+ require_relative "version"
3
+ require_relative "package_name"
4
+
5
+ module Secupdater
6
+ module YarnSupport
7
+ # A Yarn Berry (2+) yarn.lock: npm packages with their locked versions, and the project's workspaces
8
+ class Lockfile
9
+ # { name => [version strings, ascending] } for packages from the npm registry
10
+ attr_reader :versions
11
+ # Workspace paths relative to the project root, "." for the root itself
12
+ attr_reader :workspaces
13
+
14
+ def self.parse(text)
15
+ data = begin
16
+ YAML.safe_load(text)
17
+ rescue Psych::Exception => e
18
+ raise Secupdater::Error, "yarn.lock isn't valid YAML: #{e.message}"
19
+ end
20
+
21
+ unless data.is_a?(Hash) && data.key?("__metadata")
22
+ raise Secupdater::Error, "yarn.lock isn't a Yarn Berry lockfile (no __metadata; Yarn 1 isn't supported)"
23
+ end
24
+
25
+ new(data.except("__metadata"))
26
+ end
27
+
28
+ def initialize(entries)
29
+ versions = Hash.new { |hash, name| hash[name] = [] }
30
+ workspaces = []
31
+
32
+ entries.each do |key, entry|
33
+ unless entry.is_a?(Hash) && entry["resolution"].is_a?(String)
34
+ raise Secupdater::Error, "yarn.lock entry #{key.inspect} has no resolution"
35
+ end
36
+
37
+ name, reference = split_locator(entry["resolution"])
38
+
39
+ if reference.start_with?("workspace:")
40
+ workspaces << workspace_path(reference.delete_prefix("workspace:"))
41
+ elsif npm?(reference)
42
+ versions[YarnSupport.check_name!(name)] << Version.parse(entry["version"])
43
+ end
44
+ # git, file, link, portal, exec and tarball URLs aren't from the registry, so there's no advisory to fix
45
+ end
46
+
47
+ @versions = versions.sort.to_h { |name, list| [name, list.uniq(&:to_s).sort.map(&:to_s)] }
48
+ @workspaces = workspaces.uniq.sort
49
+ end
50
+
51
+ private
52
+
53
+ # "@scope/name@npm:1.0.0" => ["@scope/name", "npm:1.0.0"]; the @ of a scope is at index 0
54
+ def split_locator(locator)
55
+ at = locator.index("@", 1)
56
+ raise Secupdater::Error, "unrecognised yarn.lock resolution #{locator.inspect}" unless at
57
+
58
+ [locator[0...at], locator[(at + 1)..]]
59
+ end
60
+
61
+ # A patch keeps the patched package's version, e.g. "patch:left-pad@npm%3A1.3.0#~/.yarn/patches/..."
62
+ def npm?(reference)
63
+ return true if reference.start_with?("npm:")
64
+ return false unless reference.start_with?("patch:")
65
+
66
+ source = reference.delete_prefix("patch:").split("#", 2).first.gsub(/%3A/i, ":")
67
+ npm?(split_locator(source).last)
68
+ end
69
+
70
+ def workspace_path(path)
71
+ unless path.match?(%r{\A[^/\x00-\x1f-][^\x00-\x1f]*\z}) && !path.split("/").include?("..")
72
+ raise Secupdater::Error, "unexpected yarn.lock workspace path #{path.inspect}"
73
+ end
74
+
75
+ path
76
+ end
77
+ end
78
+ end
79
+ end