Module: Dependabot::SharedHelpers

Extended by:
T::Sig
Defined in:
lib/dependabot/shared_helpers.rb

Overview

rubocop:disable Metrics/ModuleLength

Defined Under Namespace

Classes: HelperSubprocessFailed

Constant Summary collapse

Command =
T.type_alias { T.any(String, T::Array[String]) }
CommandArguments =
T.type_alias { T::Array[T.any(String, T::Array[String])] }
ErrorContext =
T.type_alias { T::Hash[Symbol, Object] }
ExconOptions =
T.type_alias { T::Hash[Symbol, Object] }
HelperResponse =
T.type_alias { T::Hash[String, Object] }
USER_AGENT =
T.let(
  "dependabot-core/#{Dependabot::VERSION} " \
  "#{Excon::USER_AGENT} ruby/#{RUBY_VERSION} " \
  "(#{RUBY_PLATFORM}) " \
  "(+https://github.com/dependabot/dependabot-core)".freeze,
  String
)
SIGKILL =
9

Class Method Summary collapse

Class Method Details

.check_out_of_disk_memory_error(stderr, error_context) ⇒ Object



598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
# File 'lib/dependabot/shared_helpers.rb', line 598

def self.check_out_of_disk_memory_error(stderr, error_context)
  if stderr&.include?("No space left on device") || stderr&.include?("Out of diskspace")
    raise HelperSubprocessFailed.new(
      message: "No space left on device",
      error_class: "Dependabot::OutOfDisk",
      error_context: error_context
    )
  elsif stderr&.include?("MemoryError")
    raise HelperSubprocessFailed.new(
      message: "MemoryError",
      error_class: "Dependabot::OutOfMemory",
      error_context: error_context
    )
  end
end

.check_out_of_memory_error(stderr, error_context, error_class) ⇒ Object

Raises:

  • (error_class)


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

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

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

.configure_git_to_use_https(host) ⇒ Object



489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
# File 'lib/dependabot/shared_helpers.rb', line 489

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, git_config_global_path, git_store_path) ⇒ Object



414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
# File 'lib/dependabot/shared_helpers.rb', line 414

def self.configure_git_to_use_https_with_credentials(
  credentials,
  safe_directories,
  git_config_global_path,
  git_store_path
)
  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 #{git_store_path}'",
    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

  File.write(git_store_path, git_store_content(deduped_credentials))
end

.credential_helper_pathObject



402
403
404
# File 'lib/dependabot/shared_helpers.rb', line 402

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

.escape_command(command) ⇒ Object



130
131
132
# File 'lib/dependabot/shared_helpers.rb', line 130

def self.escape_command(command)
  CommandHelpers.escape_command(command)
end

.excon_defaults(options = nil) ⇒ Object



336
337
338
339
340
341
342
343
344
345
346
347
348
349
# File 'lib/dependabot/shared_helpers.rb', line 336

def self.excon_defaults(options = nil)
  options ||= {}
  headers = T.cast(options.delete(:headers), T.nilable(T::Hash[String, String]))
  {
    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



328
329
330
331
332
333
# File 'lib/dependabot/shared_helpers.rb', line 328

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

.excon_middlewareObject



321
322
323
324
325
# File 'lib/dependabot/shared_helpers.rb', line 321

def self.excon_middleware
  T.must(T.cast(Excon.defaults, T::Hash[Symbol, T::Array[T.class_of(Excon::Middleware::Base)]])[:middlewares]) +
    [Excon::Middleware::Decompress] +
    [Excon::Middleware::RedirectFollower]
end

.find_safe_directoriesObject



523
524
525
526
527
528
529
# File 'lib/dependabot/shared_helpers.rb', line 523

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

.handle_json_parse_error(stdout, stderr, error_context, error_class) ⇒ Object



285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
# File 'lib/dependabot/shared_helpers.rb', line 285

def self.handle_json_parse_error(stdout, stderr, error_context, error_class)
  # If the JSON is invalid, the helper has likely failed
  # We should raise a more helpful error message
  message = if !stdout.strip.empty?
              stdout
            elsif !stderr.strip.empty?
              stderr
            else
              "No output from command"
            end
  error_class.new(
    message: message,
    error_class: "JSON::ParserError",
    error_context: error_context
  )
end

.in_a_temporary_directory(directory = "/", &_block) ⇒ Object



78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/dependabot/shared_helpers.rb', line 78

def self.in_a_temporary_directory(directory = "/", &_block)
  FileUtils.mkdir_p(Utils::BUMP_TMP_DIR_PATH)
  tmp_dir = Dir.mktmpdir(Utils::BUMP_TMP_FILE_PREFIX, Utils::BUMP_TMP_DIR_PATH)
  path = Pathname.new(File.join(tmp_dir, directory)).expand_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



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/dependabot/shared_helpers.rb', line 49

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
      T.must(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



515
516
517
518
519
520
# File 'lib/dependabot/shared_helpers.rb', line 515

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, error_class: HelperSubprocessFailed, timeout: CommandHelpers::TIMEOUTS::DEFAULT) ⇒ Object



169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
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
# File 'lib/dependabot/shared_helpers.rb', line 169

def self.run_helper_subprocess(
  command:,
  function:,
  args:,
  env: nil,
  stderr_to_stdout: false,
  allow_unsafe_shell_command: false,
  error_class: HelperSubprocessFailed,
  timeout: CommandHelpers::TIMEOUTS::DEFAULT
)
  start = Time.now
  stdin_data = T.cast(JSON.dump(function: function, args: args), String)
  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
    require "debug"
    binding.break # rubocop:disable Lint/Debugger
  end

  env_cmd = [env, cmd].compact
  raw_stdout, raw_stderr, process = CommandHelpers.capture3_with_timeout(
    env_cmd,
    stdin_data: stdin_data,
    timeout: timeout
  )
  stdout = T.let(raw_stdout || "", String)
  stderr = T.let(raw_stderr || "", String)
  time_taken = Time.now - start

  if ENV["DEBUG_HELPERS"] == "true"
    sanitized_env_cmd = [sanitize_env_for_logging(env), cmd].compact
    puts sanitized_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[0..50_000], # Truncate to ~100kb
    process_exit_value: process.to_s,
    process_termsig: process&.termsig
  }

  check_out_of_memory_error(stderr, error_context, error_class)

  begin
    response = parse_helper_response(stdout)
    return response["result"] if process&.success?

    message, helper_error_class, trace = parse_helper_error(response)

    raise error_class.new(
      message: message,
      error_class: helper_error_class,
      error_context: error_context,
      trace: trace
    )
  rescue JSON::ParserError
    raise handle_json_parse_error(stdout, stderr, error_context, error_class)
  rescue TypeError => e
    raise error_class.new(
      message: e.message,
      error_class: e.class.name,
      error_context: error_context
    )
  end
end

.run_shell_command(command, allow_unsafe_shell_command: false, cwd: nil, env: {}, fingerprint: nil, stderr_to_stdout: true, timeout: CommandHelpers::TIMEOUTS::DEFAULT, output_observer: nil) ⇒ Object



543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
# File 'lib/dependabot/shared_helpers.rb', line 543

def self.run_shell_command(
  command,
  allow_unsafe_shell_command: false,
  cwd: nil,
  env: {},
  fingerprint: nil,
  stderr_to_stdout: true,
  timeout: CommandHelpers::TIMEOUTS::DEFAULT,
  output_observer: nil
)
  start = Time.now
  command_args, command_for_output = prepare_command(
    command,
    allow_unsafe_shell_command: allow_unsafe_shell_command
  )

  puts command_for_output if ENV["DEBUG_HELPERS"] == "true"

  opts = {}
  opts[:chdir] = cwd if cwd

  env_cmd = [env || {}, *command_args, opts].compact
  kwargs = {
    stderr_to_stdout: stderr_to_stdout,
    timeout: timeout
  }
  kwargs[:output_observer] = output_observer if output_observer

  stdout, stderr, process = CommandHelpers.capture3_with_timeout(
    env_cmd,
    **kwargs
  )

  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: command_for_output,
    fingerprint: fingerprint,
    time_taken: time_taken,
    process_exit_value: process.to_s
  }

  check_out_of_disk_memory_error(stderr, error_context)

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

.sanitize_env_for_logging(env) ⇒ Object



623
624
625
626
627
628
629
630
631
632
633
634
# File 'lib/dependabot/shared_helpers.rb', line 623

def self.sanitize_env_for_logging(env)
  return nil if env.nil?

  env.transform_keys(&:to_s).each_with_object({}) do |(key, value), result|
    # Only redact if the key contains "TOKEN" (case-insensitive)
    result[key] = if key.match?(/TOKEN/i)
                    "<redacted>"
                  else
                    value
                  end
  end
end

.scp_to_standard(uri) ⇒ Object



395
396
397
398
399
# File 'lib/dependabot/shared_helpers.rb', line 395

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

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

.with_git_configured(credentials:, &_block) ⇒ Object



359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
# File 'lib/dependabot/shared_helpers.rb', line 359

def self.with_git_configured(credentials:, &_block)
  safe_directories = find_safe_directories

  FileUtils.mkdir_p(Utils::BUMP_TMP_DIR_PATH)

  previous_config = ENV.fetch("GIT_CONFIG_GLOBAL", nil)
  # adding a random suffix to avoid conflicts when running in parallel
  # some package managers like bundler will modify the global git config
  random_suffix = SecureRandom.hex(16)
  git_config_global_path = File.expand_path("#{random_suffix}.gitconfig", Utils::BUMP_TMP_DIR_PATH)
  git_store_path = File.join(Dir.pwd, "#{random_suffix}.git.store")
  previous_terminal_prompt = ENV.fetch("GIT_TERMINAL_PROMPT", nil)

  begin
    ENV["GIT_CONFIG_GLOBAL"] = git_config_global_path
    ENV["GIT_TERMINAL_PROMPT"] = "false"
    configure_git_to_use_https_with_credentials(
      credentials,
      safe_directories,
      git_config_global_path,
      git_store_path
    )
    yield
  ensure
    ENV["GIT_CONFIG_GLOBAL"] = previous_config
    ENV["GIT_TERMINAL_PROMPT"] = previous_terminal_prompt
  end
rescue Errno::ENOSPC => e
  raise Dependabot::OutOfDisk, e.message
ensure
  FileUtils.rm_f(T.must(git_config_global_path))
  FileUtils.rm_f(T.must(git_store_path))
end