api: don't download files as root when Homebrew's not owned by root.

This was mentioned in a random comment. While we're here, make some
helper functions to query this a bit more nicely elsewhere when we do
it.
This commit is contained in:
Mike McQuaid 2023-02-23 10:04:50 +00:00
parent 53c3db5df7
commit 2884b1649b
No known key found for this signature in database
GPG Key ID: 3338A31AFDB1D829
3 changed files with 24 additions and 5 deletions

View File

@ -41,6 +41,11 @@ module Homebrew
url = "#{Homebrew::EnvConfig.api_domain}/#{endpoint}"
default_url = "#{HOMEBREW_API_DEFAULT_DOMAIN}/#{endpoint}"
if Homebrew.running_as_root_but_not_owned_by_root? &&
(!target.exist? || target.empty?)
odie "Need to download #{url} but cannot as root! Try again without `sudo`."
end
# TODO: consider using more of Utils::Curl
curl_args = %W[
--compressed
@ -55,6 +60,7 @@ module Homebrew
!target.empty? &&
(Homebrew::EnvConfig.no_auto_update? ||
((Time.now - Homebrew::EnvConfig.api_auto_update_secs.to_i) < target.mtime))
skip_download ||= Homebrew.running_as_root_but_not_owned_by_root?
json_data = begin
begin

View File

@ -120,12 +120,12 @@ begin
# Unset HOMEBREW_HELP to avoid confusing the tap
with_env HOMEBREW_HELP: nil do
tap_commands = []
if File.exist?("/.dockerenv") ||
Process.uid.zero? ||
if (File.exist?("/.dockerenv") ||
Homebrew.running_as_root? ||
((cgroup = Utils.popen_read("cat", "/proc/1/cgroup").presence) &&
%w[azpl_job actions_job docker garden kubepods].none? { |type| cgroup.include?(type) })
brew_uid = HOMEBREW_BREW_FILE.stat.uid
tap_commands += %W[/usr/bin/sudo -u ##{brew_uid}] if Process.uid.zero? && !brew_uid.zero?
%w[azpl_job actions_job docker garden kubepods].none? { |type| cgroup.include?(type) })) &&
Homebrew.running_as_root_but_not_owned_by_root?
tap_commands += %W[/usr/bin/sudo -u ##{Homebrew.owner_uid}]
end
quiet_arg = args.quiet? ? "--quiet" : nil
tap_commands += [HOMEBREW_BREW_FILE, "tap", *quiet_arg, possible_tap.name]

View File

@ -111,6 +111,19 @@ module Homebrew
def auditing?
@auditing == true
end
def running_as_root?
@process_uid ||= Process.uid
@process_uid.zero?
end
def owner_uid
@owner_uid ||= HOMEBREW_BREW_FILE.stat.uid
end
def running_as_root_but_not_owned_by_root?
running_as_root? && !owner_uid.zero?
end
end
end