From b67d20b15723ddae54adc3d4afeed9420ee61527 Mon Sep 17 00:00:00 2001 From: Kanezoh Date: Fri, 6 Aug 2021 15:11:20 +0900 Subject: [PATCH] add subdomain cookie test --- spec/cookie_spec.cr | 13 +++++++++++++ src/mechanize/http/agent.cr | 4 ++-- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/spec/cookie_spec.cr b/spec/cookie_spec.cr index 194c7d8..b5184ed 100644 --- a/spec/cookie_spec.cr +++ b/spec/cookie_spec.cr @@ -1,8 +1,10 @@ require "./spec_helper" WebMock.stub(:get, "example.com/cookies1").to_return(headers: {"Set-Cookie" => "id=123"}) +WebMock.stub(:get, "example.com/cookies1_domain").to_return(headers: {"Set-Cookie" => "id=123; Domain=example.com"}) WebMock.stub(:get, "example.com/cookies2").to_return(headers: {"Set-Cookie" => "name=kanezoh"}) WebMock.stub(:get, "example.com/cookies3").to_return(headers: {"Set-Cookie" => "id=456"}) +WebMock.stub(:get, "www.example.com").to_return() WebMock.stub(:get, "example.com/meta_cookie").to_return(body: <<-BODY @@ -61,4 +63,15 @@ describe "Mechanize Cookie test" do agent.get("http://another_domain.com/") agent.request_headers.has_key?("Cookie").should eq false end + + it "sends cookie to subdomain if domain attribute is set" do + agent = Mechanize.new + agent.get("http://example.com/cookies1") + agent.get("http://www.example.com/") + agent.request_headers.has_key?("Cookie").should eq false + + agent.get("http://example.com/cookies1_domain") + agent.get("http://www.example.com/") + agent.request_headers.has_key?("Cookie").should eq true + end end diff --git a/src/mechanize/http/agent.cr b/src/mechanize/http/agent.cr index a6ac288..ae4039d 100644 --- a/src/mechanize/http/agent.cr +++ b/src/mechanize/http/agent.cr @@ -130,8 +130,8 @@ module MechanizeCr private def valid_cookies(uri) host = uri.host valid_cookies = ::HTTP::Cookies.new - request_cookies.select do |cookie| - valid_cookies << cookie if cookie.origin == host || cookie.domain.try &.=~(/.*#{host}/) + request_cookies.each do |cookie| + valid_cookies << cookie if cookie.origin == host || (cookie.domain && host.try &.=~(/.*#{cookie.domain.try &.gsub(".", "\.")}$/)) end valid_cookies end