From 88e2098d6523770d2749e340517151c308c86fa8 Mon Sep 17 00:00:00 2001 From: Denny Abraham Cheriyan Date: Sun, 12 Feb 2017 15:55:32 -0800 Subject: [PATCH] Handle protocol relative urls --- lib/fastimage.rb | 8 +++++++- test/test.rb | 6 ++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/lib/fastimage.rb b/lib/fastimage.rb index 5d0b1e4..c85b283 100644 --- a/lib/fastimage.rb +++ b/lib/fastimage.rb @@ -239,7 +239,9 @@ class FastImage begin newly_parsed_uri = Addressable::URI.parse(res['Location']) # The new location may be relative - check for that - if newly_parsed_uri.scheme != "http" && newly_parsed_uri.scheme != "https" + if protocol_relative_url?(res['Location']) + @parsed_uri = newly_parsed_uri.tap { |obj| obj.scheme = @parsed_uri.scheme } + elsif newly_parsed_uri.scheme != "http" && newly_parsed_uri.scheme != "https" @parsed_uri.path = res['Location'] else @parsed_uri = newly_parsed_uri @@ -282,6 +284,10 @@ class FastImage end end + def protocol_relative_url?(url) + url.start_with?("//") + end + def proxy_uri begin if @options[:proxy] diff --git a/test/test.rb b/test/test.rb index 2da6c98..e578d4a 100644 --- a/test/test.rb +++ b/test/test.rb @@ -232,6 +232,12 @@ class FastImageTest < Test::Unit::TestCase assert_equal GoodFixtures[GoodFixtures.keys.first][1], FastImage.size(url, :raise_on_failure=>true) end + def test_should_handle_permanent_redirect_with_protocol_relative_url + url = "http://example.nowhere/foo.jpeg" + register_redirect(url, "//example.nowhere/" + GoodFixtures.keys.first) + assert_equal GoodFixtures[GoodFixtures.keys.first][1], FastImage.size(url, :raise_on_failure=>true) + end + def register_redirect(from, to) resp = Net::HTTPMovedPermanently.new(1.0, 302, "Moved") resp['Location'] = to