Merge pull request #17262 from Homebrew/github-auth-seteuid

utils/github/api: use real UID for auth fetching
This commit is contained in:
Mike McQuaid 2024-05-09 12:19:44 +01:00 committed by GitHub
commit 78a812b234
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 49 additions and 21 deletions

View File

@ -5,6 +5,7 @@ require "system_command"
require "tempfile"
require "utils/shell"
require "utils/formatter"
require "utils/uid"
module GitHub
def self.pat_blurb(scopes = ALL_SCOPES)
@ -138,8 +139,12 @@ module GitHub
# Gets the token from the GitHub CLI for github.com.
sig { returns(T.nilable(String)) }
def self.github_cli_token
Utils::UID.drop_euid do
# Avoid `Formula["gh"].opt_bin` so this method works even with `HOMEBREW_DISABLE_LOAD_FORMULA`.
env = { "PATH" => PATH.new(HOMEBREW_PREFIX/"opt/gh/bin", ENV.fetch("PATH")) }
env = {
"PATH" => PATH.new(HOMEBREW_PREFIX/"opt/gh/bin", ENV.fetch("PATH")),
"HOME" => Etc.getpwuid(Process.uid)&.dir,
}
gh_out, _, result = system_command "gh",
args: ["auth", "token", "--hostname", "github.com"],
env:,
@ -148,14 +153,17 @@ module GitHub
gh_out.chomp
end
end
# Gets the password field from `git-credential-osxkeychain` for github.com,
# but only if that password looks like a GitHub Personal Access Token.
sig { returns(T.nilable(String)) }
def self.keychain_username_password
Utils::UID.drop_euid do
git_credential_out, _, result = system_command "git",
args: ["credential-osxkeychain", "get"],
input: ["protocol=https\n", "host=github.com\n"],
env: { "HOME" => Etc.getpwuid(Process.uid)&.dir },
print_stderr: false
return unless result.success?
@ -170,6 +178,7 @@ module GitHub
github_password
end
end
def self.credentials
@credentials ||= Homebrew::EnvConfig.github_api_token || github_cli_token || keychain_username_password

View File

@ -0,0 +1,19 @@
# typed: strict
# frozen_string_literal: true
module Utils
module UID
sig { type_parameters(:U).params(_block: T.proc.returns(T.type_parameter(:U))).returns(T.type_parameter(:U)) }
def self.drop_euid(&_block)
return yield if Process.euid == Process.uid
original_euid = Process.euid
begin
Process::Sys.seteuid(Process.uid)
yield
ensure
Process::Sys.seteuid(original_euid)
end
end
end
end