diff --git a/rack-protection/lib/rack/protection/base.rb b/rack-protection/lib/rack/protection/base.rb index ab5d85a9..09d3ff9f 100755 --- a/rack-protection/lib/rack/protection/base.rb +++ b/rack-protection/lib/rack/protection/base.rb @@ -92,6 +92,7 @@ module Rack ref = env['HTTP_REFERER'].to_s return if !options[:allow_empty_referrer] and ref.empty? URI.parse(ref).host || Request.new(env).host + rescue URI::InvalidURIError end def origin(env) diff --git a/rack-protection/spec/base_spec.rb b/rack-protection/spec/base_spec.rb index dea7a6a0..434e611b 100644 --- a/rack-protection/spec/base_spec.rb +++ b/rack-protection/spec/base_spec.rb @@ -6,4 +6,33 @@ describe Rack::Protection::Base do described_class.new(lambda {}).random_string.length.should == 32 end end + + describe "#referrer" do + it "Reads referrer from Referrer header" do + env = {"HTTP_HOST" => "foo.com", "HTTP_REFERER" => "http://bar.com/valid"} + described_class.new(lambda {}).referrer(env).should == "bar.com" + end + + it "Reads referrer from Host header when Referrer header is relative" do + env = {"HTTP_HOST" => "foo.com", "HTTP_REFERER" => "/valid"} + described_class.new(lambda {}).referrer(env).should == "foo.com" + end + + it "Reads referrer from Host header when Referrer header is missing" do + env = {"HTTP_HOST" => "foo.com"} + described_class.new(lambda {}).referrer(env).should == "foo.com" + end + + it "Returns nil when Referrer header is missing and allow_empty_referrer is false" do + env = {"HTTP_HOST" => "foo.com"} + base = described_class.new(lambda {}, :allow_empty_referrer => false) + base.referrer(env).should be_nil + end + + it "Returns nil when Referrer header is invalid" do + env = {"HTTP_HOST" => "foo.com", "HTTP_REFERER" => "http://bar.com/bad|uri"} + base = described_class.new(lambda {}) + base.referrer(env).should be_nil + end + end end