Module: Dependabot::SharedHelpers

Defined in:
lib/dependabot/shared_helpers.rb

Defined Under Namespace

Classes: HelperSubprocessFailed

Constant Summary collapse

GIT_CONFIG_GLOBAL_PATH =
File.expand_path(".gitconfig", Utils::BUMP_TMP_DIR_PATH)
USER_AGENT =
"dependabot-core/#{Dependabot::VERSION} " \
"#{Excon::USER_AGENT} ruby/#{RUBY_VERSION} " \
"(#{RUBY_PLATFORM}) " \
"(+https://github.com/dependabot/dependabot-core)".freeze
SIGKILL =
9

Class Method Summary collapse

Class Method Details

.check_out_of_memory_error(stderr, error_context) ⇒ Object

rubocop:enable Metrics/MethodLength



147
148
149
150
151
152
153
154
155
# File 'lib/dependabot/shared_helpers.rb', line 147

def self.check_out_of_memory_error(stderr, error_context)
  return unless stderr&.include?("JavaScript heap out of memory")

  raise HelperSubprocessFailed.new(
    message: "JavaScript heap out of memory",
    error_class: "Dependabot::OutOfMemoryError",
    error_context: error_context
  )
end

.configure_git_to_use_https(host) ⇒ Object

rubocop:enable Metrics/AbcSize rubocop:enable Metrics/PerceivedComplexity



277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
# File 'lib/dependabot/shared_helpers.rb', line 277

def self.configure_git_to_use_https(host)
  # NOTE: we use --global here (rather than --system) so that Dependabot
  # can be run without privileged access
  run_shell_command(
    "git config --global --replace-all url.https://#{host}/." \
    "insteadOf ssh://git@#{host}/"
  )
  run_shell_command(
    "git config --global --add url.https://#{host}/." \
    "insteadOf ssh://git@#{host}:"
  )
  run_shell_command(
    "git config --global --add url.https://#{host}/." \
    "insteadOf git@#{host}:"
  )
  run_shell_command(
    "git config --global --add url.https://#{host}/." \
    "insteadOf git@#{host}/"
  )
  run_shell_command(
    "git config --global --add url.https://#{host}/." \
    "insteadOf git://#{host}/"
  )
end

.configure_git_to_use_https_with_credentials(credentials, safe_directories) ⇒ Object

rubocop:disable Metrics/AbcSize rubocop:disable Metrics/PerceivedComplexity



218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# File 'lib/dependabot/shared_helpers.rb', line 218

def self.configure_git_to_use_https_with_credentials(credentials, safe_directories)
  File.open(GIT_CONFIG_GLOBAL_PATH, "w") do |file|
    file << "# Generated by dependabot/dependabot-core"
  end

  # Then add a file-based credential store that loads a file in this repo.
  # Under the hood this uses git credential-store, but it's invoked through
  # a wrapper binary that only allows non-mutating commands. Without this,
  # whenever the credentials are deemed to be invalid, they're erased.
  run_shell_command(
    "git config --global credential.helper " \
    "'!#{credential_helper_path} --file #{Dir.pwd}/git.store'",
    allow_unsafe_shell_command: true,
    fingerprint: "git config --global credential.helper '<helper_command>'"
  )

  # see https://github.blog/2022-04-12-git-security-vulnerability-announced/
  safe_directories.each do |path|
    run_shell_command("git config --global --add safe.directory #{path}")
  end

  github_credentials = credentials
                       .select { |c| c["type"] == "git_source" }
                       .select { |c| c["host"] == "github.com" }
                       .select { |c| c["password"] && c["username"] }

  # If multiple credentials are specified for github.com, pick the one that
  # *isn't* just an app token (since it must have been added deliberately)
  github_credential =
    github_credentials.find { |c| !c["password"]&.start_with?("v1.") } ||
    github_credentials.first

  # Make sure we always have https alternatives for github.com.
  configure_git_to_use_https("github.com") if github_credential.nil?

  deduped_credentials = credentials -
                        github_credentials +
                        [github_credential].compact

  # Build the content for our credentials file
  git_store_content = ""
  deduped_credentials.each do |cred|
    next unless cred["type"] == "git_source"
    next unless cred["username"] && cred["password"]

    authenticated_url =
      "https://#{cred.fetch('username')}:#{cred.fetch('password')}" \
      "@#{cred.fetch('host')}"

    git_store_content += authenticated_url + "\n"
    configure_git_to_use_https(cred.fetch("host"))
  end

  # Save the file
  File.write("git.store", git_store_content)
end

.credential_helper_pathObject



212
213
214
# File 'lib/dependabot/shared_helpers.rb', line 212

def self.credential_helper_path
  File.join(__dir__, "../../bin/git-credential-store-immutable")
end

.escape_command(command) ⇒ Object

Escapes all special characters, e.g. = & | <>



79
80
81
82
# File 'lib/dependabot/shared_helpers.rb', line 79

def self.escape_command(command)
  command_parts = command.split.map(&:strip).reject(&:empty?)
  Shellwords.join(command_parts)
end

.excon_defaults(options = nil) ⇒ Object



170
171
172
173
174
175
176
177
178
179
180
181
182
183
# File 'lib/dependabot/shared_helpers.rb', line 170

def self.excon_defaults(options = nil)
  options ||= {}
  headers = options.delete(:headers)
  {
    instrumentor: Dependabot::SimpleInstrumentor,
    connect_timeout: 5,
    write_timeout: 5,
    read_timeout: 20,
    retry_limit: 4, # Excon defaults to four retries, but let's set it explicitly for clarity
    omit_default_port: true,
    middlewares: excon_middleware,
    headers: excon_headers(headers)
  }.merge(options)
end

.excon_headers(headers = nil) ⇒ Object



163
164
165
166
167
168
# File 'lib/dependabot/shared_helpers.rb', line 163

def self.excon_headers(headers = nil)
  headers ||= {}
  {
    "User-Agent" => USER_AGENT
  }.merge(headers)
end

.excon_middlewareObject



157
158
159
160
161
# File 'lib/dependabot/shared_helpers.rb', line 157

def self.excon_middleware
  Excon.defaults[:middlewares] +
    [Excon::Middleware::Decompress] +
    [Excon::Middleware::RedirectFollower]
end

.find_safe_directoriesObject



309
310
311
312
313
314
315
# File 'lib/dependabot/shared_helpers.rb', line 309

def self.find_safe_directories
  # to preserve safe directories from global .gitconfig
  output, process = Open3.capture2("git config --global --get-all safe.directory")
  safe_directories = []
  safe_directories = output.split("\n").compact if process.success?
  safe_directories
end

.in_a_temporary_directory(directory = "/") ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/dependabot/shared_helpers.rb', line 49

def self.in_a_temporary_directory(directory = "/")
  FileUtils.mkdir_p(Utils::BUMP_TMP_DIR_PATH)
  tmp_dir = Dir.mktmpdir(Utils::BUMP_TMP_FILE_PREFIX, Utils::BUMP_TMP_DIR_PATH)

  begin
    path = Pathname.new(File.join(tmp_dir, directory)).expand_path
    FileUtils.mkpath(path)
    Dir.chdir(path) { yield(path) }
  ensure
    FileUtils.rm_rf(tmp_dir)
  end
end

.in_a_temporary_repo_directory(directory = "/", repo_contents_path = nil, &block) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/dependabot/shared_helpers.rb', line 28

def self.in_a_temporary_repo_directory(directory = "/", repo_contents_path = nil, &block)
  if repo_contents_path
    # If a workspace has been defined to allow orcestration of the git repo
    # by the runtime we should defer to it, otherwise we prepare the folder
    # for direct use and yield.
    if Dependabot::Workspace.active_workspace
      Dependabot::Workspace.active_workspace.change(&block)
    else
      path = Pathname.new(File.join(repo_contents_path, directory)).expand_path
      reset_git_repo(repo_contents_path)
      # Handle missing directories by creating an empty one and relying on the
      # file fetcher to raise a DependencyFileNotFound error
      FileUtils.mkdir_p(path)

      Dir.chdir(path) { yield(path) }
    end
  else
    in_a_temporary_directory(directory, &block)
  end
end

.reset_git_repo(path) ⇒ Object



302
303
304
305
306
307
# File 'lib/dependabot/shared_helpers.rb', line 302

def self.reset_git_repo(path)
  Dir.chdir(path) do
    run_shell_command("git reset HEAD --hard")
    run_shell_command("git clean -fx")
  end
end

.run_helper_subprocess(command:, function:, args:, env: nil, stderr_to_stdout: false, allow_unsafe_shell_command: false) ⇒ Object

rubocop:disable Metrics/MethodLength



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/dependabot/shared_helpers.rb', line 85

def self.run_helper_subprocess(command:, function:, args:, env: nil,
                               stderr_to_stdout: false,
                               allow_unsafe_shell_command: false)
  start = Time.now
  stdin_data = JSON.dump(function: function, args: args)
  cmd = allow_unsafe_shell_command ? command : escape_command(command)

  # NOTE: For debugging native helpers in specs and dry-run: outputs the
  # bash command to run in the tmp directory created by
  # in_a_temporary_directory
  if ENV["DEBUG_FUNCTION"] == function
    puts helper_subprocess_bash_command(stdin_data: stdin_data, command: cmd, env: env)
    # Pause execution so we can run helpers inside the temporary directory
    debugger # rubocop:disable Lint/Debugger
  end

  env_cmd = [env, cmd].compact
  stdout, stderr, process = Open3.capture3(*env_cmd, stdin_data: stdin_data)
  time_taken = Time.now - start

  if ENV["DEBUG_HELPERS"] == "true"
    puts env_cmd
    puts function
    puts stdout
    puts stderr
  end

  # Some package managers output useful stuff to stderr instead of stdout so
  # we want to parse this, most package manager will output garbage here so
  # would mess up json response from stdout
  stdout = "#{stderr}\n#{stdout}" if stderr_to_stdout

  error_context = {
    command: command,
    function: function,
    args: args,
    time_taken: time_taken,
    stderr_output: stderr ? stderr[0..50_000] : "", # Truncate to ~100kb
    process_exit_value: process.to_s,
    process_termsig: process.termsig
  }

  check_out_of_memory_error(stderr, error_context)

  response = JSON.parse(stdout)
  return response["result"] if process.success?

  raise HelperSubprocessFailed.new(
    message: response["error"],
    error_class: response["error_class"],
    error_context: error_context,
    trace: response["trace"]
  )
rescue JSON::ParserError
  raise HelperSubprocessFailed.new(
    message: stdout || "No output from command",
    error_class: "JSON::ParserError",
    error_context: error_context
  )
end

.run_shell_command(command, allow_unsafe_shell_command: false, env: {}, fingerprint: nil, stderr_to_stdout: true) ⇒ Object



317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
# File 'lib/dependabot/shared_helpers.rb', line 317

def self.run_shell_command(command,
                           allow_unsafe_shell_command: false,
                           env: {},
                           fingerprint: nil,
                           stderr_to_stdout: true)
  start = Time.now
  cmd = allow_unsafe_shell_command ? command : escape_command(command)

  if stderr_to_stdout
    stdout, process = Open3.capture2e(env || {}, cmd)
  else
    stdout, stderr, process = Open3.capture3(env || {}, cmd)
  end

  time_taken = Time.now - start

  # Raise an error with the output from the shell session if the
  # command returns a non-zero status
  return stdout if process.success?

  error_context = {
    command: cmd,
    fingerprint: fingerprint,
    time_taken: time_taken,
    process_exit_value: process.to_s
  }

  raise SharedHelpers::HelperSubprocessFailed.new(
    message: stderr_to_stdout ? stdout : "#{stderr}\n#{stdout}",
    error_context: error_context
  )
end

.scp_to_standard(uri) ⇒ Object

Handle SCP-style git URIs



206
207
208
209
210
# File 'lib/dependabot/shared_helpers.rb', line 206

def self.scp_to_standard(uri)
  return uri unless uri.start_with?("git@")

  "https://#{uri.split('git@').last.sub(%r{:/?}, '/')}"
end

.with_git_configured(credentials:) ⇒ Object



185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/dependabot/shared_helpers.rb', line 185

def self.with_git_configured(credentials:)
  safe_directories = find_safe_directories

  FileUtils.mkdir_p(Utils::BUMP_TMP_DIR_PATH)

  previous_config = ENV.fetch("GIT_CONFIG_GLOBAL", nil)

  begin
    ENV["GIT_CONFIG_GLOBAL"] = GIT_CONFIG_GLOBAL_PATH
    configure_git_to_use_https_with_credentials(credentials, safe_directories)
    yield
  ensure
    ENV["GIT_CONFIG_GLOBAL"] = previous_config
  end
rescue Errno::ENOSPC => e
  raise Dependabot::OutOfDisk, e.message
ensure
  FileUtils.rm_f(GIT_CONFIG_GLOBAL_PATH)
end