Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/rubygems/compact_index_client/cache.rb
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ def info_etag_path(name)
# validated, so refuse anything that would escape the cache
# directory when used as a path component.
def validate_name!(name)
return if File.basename(name) == name
return unless name.empty? || name.include?("\0") || name == "." || name == ".." || File.basename(name) != name

raise Gem::Exception, "malformed gem name: #{name.inspect}"
end
Expand Down
26 changes: 21 additions & 5 deletions lib/rubygems/compact_index_client/http_fetcher.rb
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,13 @@ def fetch(uri, headers, redirects_remaining)
response = request(uri, headers)

case response
when Gem::Net::HTTPSuccess, Gem::Net::HTTPNotModified
when Gem::Net::HTTPNotModified
response
when Gem::Net::HTTPSuccess
# The callers write the body into the cache, so a body-less success
# such as 204 would truncate the cached file.
raise bad_response(response, uri) unless response.class.body_permitted?

response
when Gem::Net::HTTPMovedPermanently, Gem::Net::HTTPFound, Gem::Net::HTTPSeeOther,
Gem::Net::HTTPTemporaryRedirect, Gem::Net::HTTPPermanentRedirect
Expand All @@ -42,15 +48,20 @@ def fetch(uri, headers, redirects_remaining)
if https?(uri) && !https?(redirect)
raise Gem::RemoteFetcher::FetchError.new("redirecting to non-https resource: #{Gem::Uri.redact(redirect)}", uri)
end
# An absolute Location on the same host drops the credentials that a
# relative one would have kept.
redirect.userinfo = uri.userinfo if redirect.host == uri.host && !redirect.userinfo

fetch(redirect, headers, redirects_remaining - 1)
when Gem::Net::HTTPRangeNotSatisfiable
raise Gem::RemoteFetcher::FetchError.new("bad response #{response.message} #{response.code}", uri) unless headers.key?("Range")
raise bad_response(response, uri) unless headers.key?("Range")

# The local cache is longer than the remote file, refetch it whole.
fetch(uri, headers.except("Range"), redirects_remaining)
# The local cache is longer than the remote file, refetch it whole. A
# matching ETag would otherwise turn the retry into a 304 and keep the
# oversized cache.
fetch(uri, headers.except("Range", "If-None-Match"), redirects_remaining)
else
raise Gem::RemoteFetcher::FetchError.new("bad response #{response.message} #{response.code}", uri)
raise bad_response(response, uri)
end
end

Expand All @@ -65,6 +76,11 @@ def request(uri, headers)
raise Gem::RemoteFetcher::FetchError.new("#{e.class}: #{e}", uri)
end

def bad_response(response, uri)
detail = response["X-Error-Message"] || response.message
Gem::RemoteFetcher::FetchError.new("bad response #{detail} #{response.code}", uri)
end

def https?(uri)
uri.scheme == "https"
end
Expand Down
36 changes: 36 additions & 0 deletions test/rubygems/test_gem_compact_index_client_cache.rb
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,22 @@ def test_fetch_info_rejects_name_escaping_cache_directory
assert_empty fetcher.requests
end

def test_info_rejects_dot_dot_name
assert_rejects_malformed_name ".."
end

def test_info_rejects_dot_name
assert_rejects_malformed_name "."
end

def test_info_rejects_empty_name
assert_rejects_malformed_name ""
end

def test_info_rejects_name_with_null_byte
assert_rejects_malformed_name "a\0b"
end

def test_info_with_special_characters_uses_hashed_path
fetcher = FakeFetcher.new("1.0.0\n")
cache = Gem::CompactIndexClient::Cache.new(@dir, fetcher)
Expand All @@ -146,4 +162,24 @@ def test_info_with_special_characters_uses_hashed_path
assert_equal "1.0.0\n", @dir.join("info-special-characters", hashed).read
refute @dir.join("info", "Rails").exist?
end

private

def assert_rejects_malformed_name(name)
fetcher = FakeFetcher.new("1.0.0\n")
cache = Gem::CompactIndexClient::Cache.new(@dir, fetcher)
before = Dir.glob("**/*", File::FNM_DOTMATCH, base: @tempdir).sort

e = assert_raise Gem::Exception do
cache.info(name, "no-match")
end
assert_includes e.message, "malformed gem name"

assert_raise Gem::Exception do
cache.fetch_info(name)
end

assert_empty fetcher.requests
assert_equal before, Dir.glob("**/*", File::FNM_DOTMATCH, base: @tempdir).sort
end
end
54 changes: 50 additions & 4 deletions test/rubygems/test_gem_compact_index_client_http_fetcher.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,15 @@ def initialize(location)
end

class FakeNotFound < Gem::Net::HTTPNotFound
def initialize
def initialize(error_message = nil)
super("1.1", "404", "Not Found")
self["X-Error-Message"] = error_message if error_message
end
end

class FakeNoContent < Gem::Net::HTTPNoContent
def initialize
super("1.1", "204", "No Content")
end
end

Expand Down Expand Up @@ -223,6 +230,17 @@ def test_call_keeps_credentials_on_an_accepted_redirect
assert_equal "s3cr3t", remote.requests.last.first.password
end

def test_call_keeps_credentials_on_an_absolute_same_host_redirect
remote = FakeRemoteFetcher.new(
"https://user:s3cr3t@index.example/versions" => FakeRedirect.new("https://index.example/v2/versions"),
"https://user:s3cr3t@index.example/v2/versions" => FakeResponse.new("data")
)
fetcher = Gem::CompactIndexClient::HTTPFetcher.new("https://user:s3cr3t@index.example", remote)

assert_equal "data", fetcher.call("versions").body
assert_equal "s3cr3t", remote.requests.last.first.password
end

def test_call_drops_credentials_on_a_cross_host_redirect
remote = FakeRemoteFetcher.new(
"https://user:s3cr3t@index.example/versions" => FakeRedirect.new("https://mirror.example/versions"),
Expand All @@ -246,14 +264,20 @@ def test_call_raises_after_too_many_redirects
assert_match(/too many redirects/, error.message)
end

def test_call_retries_without_range_on_range_not_satisfiable
def test_call_retries_without_range_and_etag_on_range_not_satisfiable
requests = []
remote = Object.new
remote.define_singleton_method(:request) do |uri, request_class, &block|
request = request_class.new(uri)
block&.call(request)
requests << request
request["Range"] ? FakeRangeNotSatisfiable.new : FakeResponse.new("full data")
if request["Range"]
FakeRangeNotSatisfiable.new
elsif request["If-None-Match"]
Gem::Net::HTTPNotModified.new("1.1", "304", "Not Modified")
else
FakeResponse.new("full data")
end
end

fetcher = Gem::CompactIndexClient::HTTPFetcher.new("https://index.example", remote)
Expand All @@ -262,7 +286,7 @@ def test_call_retries_without_range_on_range_not_satisfiable
assert_equal "full data", response.body
assert_equal 2, requests.size
assert_nil requests.last["Range"]
assert_equal '"abc"', requests.last["If-None-Match"]
assert_nil requests.last["If-None-Match"]
end

def test_call_raises_on_range_not_satisfiable_without_range
Expand All @@ -275,6 +299,16 @@ def test_call_raises_on_range_not_satisfiable_without_range
assert_match(/bad response Range Not Satisfiable 416/, error.message)
end

def test_call_raises_fetch_error_on_no_content
fetcher, _remote = fetcher_for("https://index.example/versions" => FakeNoContent.new)

error = assert_raise Gem::RemoteFetcher::FetchError do
fetcher.call("versions")
end

assert_match(/bad response No Content 204/, error.message)
end

def test_call_raises_fetch_error_on_failure_response
fetcher, _remote = fetcher_for("https://index.example/versions" => FakeNotFound.new)

Expand All @@ -284,4 +318,16 @@ def test_call_raises_fetch_error_on_failure_response

assert_match(/bad response Not Found 404/, error.message)
end

def test_call_includes_x_error_message_in_fetch_error
fetcher, _remote = fetcher_for(
"https://index.example/versions" => FakeNotFound.new("blocked by corporate proxy policy")
)

error = assert_raise Gem::RemoteFetcher::FetchError do
fetcher.call("versions")
end

assert_match(/bad response blocked by corporate proxy policy 404/, error.message)
end
end