Skip to content

Commit cec8579

Browse files
committed
Use env var to set api key on install
This commit allows setting the authorization header for `gem install` commands using the GEM_HOST_API_KEY environment variable. This is useful when working with private registries using short lived api tokens (e.g., OIDC tokens). For example: ``` GEM_HOST_API_KEY="secret_token" gem install private_gem --clear-sources \ --source https://private.repo.com ``` The GEM_HOST_API_KEY environment variable can already be used by the `gem push` command. I'm simply extending it's usage to `gem install` as well.
1 parent b229140 commit cec8579

File tree

3 files changed

+26
-0
lines changed

3 files changed

+26
-0
lines changed

lib/rubygems/commands/install_command.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,10 @@ def execute
159159

160160
load_hooks
161161

162+
if ENV["GEM_HOST_API_KEY"]
163+
Gem::RemoteFetcher.fetcher.headers[:authorization] = ENV["GEM_HOST_API_KEY"]
164+
end
165+
162166
exit_code = install_gems
163167

164168
show_installed

test/rubygems/test_gem_commands_install_command.rb

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,10 @@ def teardown
2828
Gem::Command.build_args = @orig_args
2929
File.unlink @gemdeps if File.file? @gemdeps
3030
File.unlink "#{@gemdeps}.lock" if File.file? "#{@gemdeps}.lock"
31+
32+
if defined? Gem::RemoteFetcher
33+
Gem::RemoteFetcher.fetcher = nil
34+
end
3135
end
3236

3337
def test_execute_exclude_prerelease
@@ -760,6 +764,22 @@ def test_execute_remote
760764
assert_match "1 gem installed", @ui.output
761765
end
762766

767+
def test_execute_remote_gem_host_api_key
768+
Gem::RemoteFetcher.fetcher = @fetcher = Gem::FakeFetcher.new
769+
@a1, @a1_gem = util_gem "a", "1"
770+
util_setup_spec_fetcher @a1
771+
@fetcher.data["http://gems.example.com/gems/a-1.gem"] = Gem.read_binary(@a1_gem)
772+
773+
ENV["GEM_HOST_API_KEY"] = "temporary_secret_key"
774+
@cmd.options[:args] = %w[a]
775+
use_ui @stub_ui do
776+
@cmd.execute
777+
end
778+
779+
assert_match "1 gem installed", @ui.output
780+
assert_equal "temporary_secret_key", @fetcher.headers[:authorization]
781+
end
782+
763783
def test_execute_with_invalid_gem_file
764784
FileUtils.touch("a.gem")
765785

test/rubygems/utilities.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,11 +31,13 @@
3131

3232
class Gem::FakeFetcher
3333
attr_reader :data
34+
attr_reader :headers
3435
attr_reader :last_request
3536
attr_accessor :paths
3637

3738
def initialize
3839
@data = {}
40+
@headers = {}
3941
@paths = []
4042
end
4143

0 commit comments

Comments
 (0)