Module: GitHub::API

Extended by:
SystemCommand::Mixin, Utils::Output::Mixin
Defined in:
utils/github/api.rb

Overview

This module is part of an internal API. This module may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this module if possible, as it may be removed or changed without warning.

Helper functions for accessing the GitHub API.

Defined Under Namespace

Classes: AuthenticationFailedError, Error, GitRepositoryIsEmptyError, HTTPNotFoundError, MissingAuthenticationError, RateLimitExceededError, ValidationFailedError

Constant Summary collapse

GITHUB_IP_ALLOWLIST_ERROR =

This constant is part of an internal API. This constant may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

Regexp.new(
  "Although you appear to have the correct authorization credentials, " \
  "the `.+` organization has an IP allow list enabled, " \
  "and your IP address is not permitted to access this resource",
).freeze
NO_CREDENTIALS_MESSAGE =

This constant is part of an internal API. This constant may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

T.let(<<~MESSAGE.freeze, String)
  No GitHub credentials found in macOS Keychain, GitHub CLI or the environment.
  #{GitHub.pat_blurb}
MESSAGE
ERRORS =

This constant is part of an internal API. This constant may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

[
  AuthenticationFailedError,
  GitRepositoryIsEmptyError,
  HTTPNotFoundError,
  RateLimitExceededError,
  Error,
  JSON::ParserError,
].freeze
CREDENTIAL_NAMES =

This constant is part of an internal API. This constant may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

T.let({
  env_token:                  "HOMEBREW_GITHUB_API_TOKEN",
  github_cli_token:           "GitHub CLI login",
  keychain_username_password: "macOS Keychain GitHub",
  none:                       "none",
}.freeze, T::Hash[Symbol, String])

Class Method Summary collapse

Methods included from SystemCommand::Mixin

command_sandbox, system_command, system_command!

Methods included from Utils::Output::Mixin

issue_reporting_message, odebug, odeprecated, odie, odisabled, ofail, oh1, oh1_title, ohai, ohai_title, onoe, opoo, opoo_once, opoo_outside_github_actions, opoo_without_github_actions_annotation, pretty_cannot_install, pretty_deprecated, pretty_disabled, pretty_duration, pretty_install_status, pretty_installed, pretty_removed, pretty_uninstalled, pretty_unmarked, pretty_upgradable, pretty_warning

Class Method Details

.commit(user, repo, branch: "main") ⇒ Hash{String => T.untyped}

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

Returns:



376
377
378
# File 'utils/github/api.rb', line 376

def self.commit(user, repo, branch: "main")
  open_rest("#{API_URL}/repos/#{user}/#{repo}/commits/#{URI.encode_uri_component(branch)}", request_method: :GET)
end

.credentials ⇒ String?

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:



224
225
226
227
228
229
# File 'utils/github/api.rb', line 224

def self.credentials
  @credentials ||= T.let(nil, T.nilable(String))
  @credentials ||= Homebrew::EnvConfig.github_api_token.presence
  @credentials ||= github_cli_token
  @credentials ||= keychain_username_password
end

.credentials_curl_args ⇒ Array<String>

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

curl arguments to authenticate a GitHub API request, if credentials are available.

Returns:



233
234
235
236
237
# File 'utils/github/api.rb', line 233

def self.credentials_curl_args
  return [] if credentials_type == :none

  ["--header", "Authorization: token #{credentials}"]
end

.credentials_error_message(response_headers, needed_scopes) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Given an API response from GitHub, warn the user if their credentials have insufficient permissions.

Parameters:



262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
# File 'utils/github/api.rb', line 262

def self.credentials_error_message(response_headers, needed_scopes)
  return if response_headers.empty?

  scopes = response_headers["x-accepted-oauth-scopes"].to_s.split(", ").presence
  needed_scopes = Set.new(scopes || needed_scopes)
  credentials_scopes = response_headers["x-oauth-scopes"]
  return if needed_scopes.subset?(Set.new(credentials_scopes.to_s.split(", ")))

  github_permission_link = GitHub.pat_blurb(needed_scopes.to_a)
  needed_scopes = needed_scopes.to_a.join(", ").presence || "none"
  credentials_scopes = "none" if credentials_scopes.blank?

  what = CREDENTIAL_NAMES.fetch(credentials_type)
  @credentials_error_message ||= T.let(begin
    error_message = <<~EOS
      Your #{what} credentials do not have sufficient scope!
      Scopes required: #{needed_scopes}
      Scopes present:  #{credentials_scopes}
      #{github_permission_link}
    EOS
    onoe error_message
    error_message
  end, T.nilable(String))
end

.credentials_type ⇒ Symbol

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:



240
241
242
243
244
245
246
247
248
249
250
# File 'utils/github/api.rb', line 240

def self.credentials_type
  if Homebrew::EnvConfig.github_api_token.present?
    :env_token
  elsif github_cli_token.present?
    :github_cli_token
  elsif keychain_username_password.present?
    :keychain_username_password
  else
    :none
  end
end

.github_cli_token(executable: "gh", timeout: nil) ⇒ String?

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Gets the token from the GitHub CLI for github.com.

Parameters:

Returns:



189
190
191
192
193
194
195
196
197
198
# File 'utils/github/api.rb', line 189

def self.github_cli_token(executable: "gh", timeout: nil)
  # Avoid `Formula["gh"].opt_bin` so this method works even with `HOMEBREW_DISABLE_LOAD_FORMULA`.
  gh_out, _, result = system_command(executable,
                                     args:         ["auth", "token", "--hostname", "github.com"],
                                     env:          Utils::Path.formula_opt_bin_env("gh"),
                                     timeout:, print_stderr: false, debug: false, verbose: false).to_a
  return unless result.success?

  gh_out.chomp.presence
end

.keychain_username_password ⇒ String?

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Gets the password field from git-credential-osxkeychain for github.com, but only if that password looks like a GitHub access token.

Returns:



203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'utils/github/api.rb', line 203

def self.keychain_username_password
  git_credential_out, _, result = system_command("git",
                                                 args:         ["credential-osxkeychain", "get"],
                                                 input:        ["protocol=https\n", "host=github.com\n"],
                                                 print_stderr: false).to_a
  return unless result.success?

  git_credential_out.force_encoding("ASCII-8BIT")
  github_username = git_credential_out[/^username=(.+)/, 1]
  github_password = git_credential_out[/^password=(.+)/, 1]
  return unless github_username

  # Don't use passwords from the keychain unless they look like
  # GitHub access tokens:
  #   https://github.com/Homebrew/brew/issues/6862#issuecomment-572610344
  return unless GITHUB_ACCESS_TOKEN_REGEX.match?(github_password)

  github_password.presence
end

.open_graphql(query, variables: {}, scopes: [].freeze, raise_errors: true) ⇒ T.untyped

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

  • query (String)
  • variables (Hash{Symbol => T.untyped}) (defaults to: {})
  • scopes (Array<String>) (defaults to: [].freeze)
  • raise_errors (Boolean) (defaults to: true)

Returns:

  • (T.untyped)


418
419
420
421
422
423
424
425
426
427
428
429
# File 'utils/github/api.rb', line 418

def self.open_graphql(query, variables: {}, scopes: [].freeze, raise_errors: true)
  data = { query:, variables: }
  result = open_rest("#{API_URL}/graphql", scopes:, data:, request_method: :POST)

  if raise_errors
    raise Error, result["errors"].map { |e| e["message"] }.join("\n") if result["errors"].present?

    result["data"]
  else
    result
  end
end

.open_rest(url, data: nil, data_binary_path: nil, request_method: nil, scopes: [].freeze, parse_json: true, return_headers: false, &_block) ⇒ T.untyped

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

  • url (String, URI::Generic)
  • data (Hash{Symbol => T.untyped}, nil) (defaults to: nil)
  • data_binary_path (String, nil) (defaults to: nil)
  • request_method (Symbol, nil) (defaults to: nil)
  • scopes (Array<String>) (defaults to: [].freeze)
  • parse_json (Boolean) (defaults to: true)
  • return_headers (Boolean) (defaults to: false)
  • _block (T.proc.params(data: T::Hash[String, T.untyped]).returns(T.untyped), nil)

Returns:

  • (T.untyped)


299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
# File 'utils/github/api.rb', line 299

def self.open_rest(url, data: nil, data_binary_path: nil, request_method: nil,
                   scopes: [].freeze, parse_json: true, return_headers: false, &_block)
  # This is a no-op if the user is opting out of using the GitHub API.
  return block_given? ? yield({}) : {} if Homebrew::EnvConfig.no_github_api?

  # This is a Curl format token, not a Ruby one.
  # rubocop:disable Style/FormatStringToken
  args = ["--header", "Accept: application/vnd.github+json", "--write-out", "\n%{http_code}"]
  # rubocop:enable Style/FormatStringToken

  token = credentials
  args += credentials_curl_args
  args += ["--header", "X-GitHub-Api-Version:2022-11-28"]

  require "tempfile"
  data_tmpfile = nil
  if data
    begin
      data = JSON.pretty_generate data
      data_tmpfile = Tempfile.new("github_api_post", HOMEBREW_TEMP)
    rescue JSON::ParserError => e
      raise Error, "Failed to parse JSON request:\n#{e.message}\n#{data}", e.backtrace
    end
  end

  if data_binary_path.present?
    args += ["--data-binary", "@#{data_binary_path}"]
    args += ["--header", "Content-Type: application/gzip"]
  end

  headers_tmpfile = Tempfile.create("github_api_headers", HOMEBREW_TEMP)
  begin
    if data_tmpfile
      data_tmpfile.write data
      data_tmpfile.close
      args += ["--data", "@#{data_tmpfile.path}"]

      args += ["--request", request_method.to_s] if request_method
    end

    args += ["--dump-header", headers_tmpfile.path]

    require "utils/curl"
    result = Utils::Curl.curl_output("--location", url.to_s, *args, secrets: token ? [token] : [])
    output, _, http_code = result.stdout.rpartition("\n")
    output, _, http_code = output.rpartition("\n") if http_code == "000"
    headers = headers_tmpfile.read
  ensure
    if data_tmpfile
      data_tmpfile.close
      data_tmpfile.unlink
    end
    headers_tmpfile.close
    File.unlink(headers_tmpfile.path)
  end

  begin
    if !http_code.start_with?("2") || !result.status.success?
      raise_error(output, result.stderr, http_code, headers, scopes)
    end

    return if http_code == "204" # No Content

    output = JSON.parse output if parse_json
    if return_headers
      [output, headers]
    elsif block_given?
      yield output
    else
      output
    end
  rescue JSON::ParserError => e
    raise Error, "Failed to parse JSON response\n#{e.message}", e.backtrace
  end
end

.paginate_graphql(query, variables: {}, scopes: [].freeze, raise_errors: true, &_block) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Parameters:

  • query (String)
  • variables (Hash{Symbol => T.untyped}) (defaults to: {})
  • scopes (Array<String>) (defaults to: [].freeze)
  • raise_errors (Boolean) (defaults to: true)
  • _block (T.proc.params(data: T::Hash[String, T.untyped]).returns(T.untyped))


440
441
442
443
444
445
446
447
448
449
450
451
452
# File 'utils/github/api.rb', line 440

def self.paginate_graphql(query, variables: {}, scopes: [].freeze, raise_errors: true, &_block)
  result = API.open_graphql(query, variables:, scopes:, raise_errors:)

  has_next_page = T.let(true, T::Boolean)
  while has_next_page
    page_info = yield result
    has_next_page = page_info["hasNextPage"]
    if has_next_page
      variables[:after] = page_info["endCursor"]
      result = API.open_graphql(query, variables:, scopes:, raise_errors:)
    end
  end
end

.paginate_rest(url, additional_query_params: nil, per_page: 100, scopes: [].freeze, &_block) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Parameters:

  • url (String, URI::Generic)
  • additional_query_params (String, nil) (defaults to: nil)
  • per_page (Integer) (defaults to: 100)
  • scopes (Array<String>) (defaults to: [].freeze)
  • _block (T.proc .params(result: T.untyped, page: Integer) .returns(T.untyped))


391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
# File 'utils/github/api.rb', line 391

def self.paginate_rest(url, additional_query_params: nil, per_page: 100, scopes: [].freeze, &_block)
  (1..API_MAX_PAGES).each do |page|
    retry_count = 1
    result = begin
      API.open_rest("#{url}?per_page=#{per_page}&page=#{page}&#{additional_query_params}", scopes:)
    rescue Error
      if retry_count < PAGINATE_RETRY_COUNT
        retry_count += 1
        retry
      end

      raise
    end
    break if result.blank?

    yield(result, page)
  end
end

.raise_error(output, errors, http_code, headers, scopes) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Parameters:



463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
# File 'utils/github/api.rb', line 463

def self.raise_error(output, errors, http_code, headers, scopes)
  json = begin
    JSON.parse(output)
  rescue
    nil
  end
  message = json&.[]("message") || "curl failed! #{errors}"

  meta = {}
  headers.lines.each do |l|
    key, _, value = l.delete(":").partition(" ")
    key = key.downcase.strip
    next if key.empty?

    meta[key] = value.strip
  end

  credentials_error_message(meta, scopes)

  case http_code
  when "401"
    raise AuthenticationFailedError.new(credentials_type, message)
  when "403", "429"
    if meta.fetch("x-ratelimit-remaining", 1).to_i <= 0
      reset = [meta.fetch("x-ratelimit-reset").to_i,
               Time.now.to_i + meta.fetch("retry-after", 0).to_i].max
      resource = meta.fetch("x-ratelimit-resource")
      limit = meta.fetch("x-ratelimit-limit").to_i
      raise RateLimitExceededError.new(message, reset:, resource:, limit:)
    end

    if http_code == "429" || meta.key?("retry-after") || message.downcase.include?("secondary rate limit")
      reset = Time.now.to_i + [meta.fetch("retry-after", 60).to_i, 60].max
      raise RateLimitExceededError.new(message, reset:, resource: "secondary", limit: nil)
    end

    raise AuthenticationFailedError.new(credentials_type, message)
  when "404"
    raise MissingAuthenticationError if credentials_type == :none && scopes.present?

    raise HTTPNotFoundError, message
  when "409"
    raise GitRepositoryIsEmptyError, message if message.downcase.include? "git repository is empty"

    raise Error, message
  when "422"
    errors = json&.[]("errors") || []
    raise ValidationFailedError.new(message, errors)
  else
    raise Error, message
  end
end

.sleep_for_rate_limit(exception, minimum: 1) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Sleeps until the rate limit from the given exception has reset.

Parameters:



178
179
180
181
182
# File 'utils/github/api.rb', line 178

def self.sleep_for_rate_limit(exception, minimum: 1)
  sleep_seconds = [exception.reset - Time.now.to_i, minimum].max
  opoo "GitHub rate limit exceeded, sleeping for #{sleep_seconds} seconds..."
  sleep sleep_seconds
end