From 75a121a2c5470e2bfc7347567a8dc5f89b3812ca Mon Sep 17 00:00:00 2001 From: eileencodes Date: Tue, 1 Sep 2015 04:20:32 -0400 Subject: [PATCH] Fix bug where cookies mutated by request were not persisted With changes made in 8363b8 and ae29142 cookies that are mutated on the request like `cookies.signed = x` were not retained in subsequent tests, breaking cookie authentiation in controller tests. The test added demonstrates the issue. The reason we need to select from non-deleted cookies is because without checking the `@delete_cookies` the `cookie_jar` `@cookies` will send the wrong cookies to be updated. The code must check for `@deleted_cookies` before sending an `#update` with the requests cookie_jar cookies. This follows how the cookie_jar cookies from the request were updated before these changes. --- actionpack/lib/action_controller/test_case.rb | 1 + actionpack/lib/action_dispatch/middleware/cookies.rb | 7 +++++++ actionpack/test/dispatch/cookies_test.rb | 9 +++++++++ 3 files changed, 17 insertions(+) diff --git a/actionpack/lib/action_controller/test_case.rb b/actionpack/lib/action_controller/test_case.rb index 39cbc0cd70..ebb4ebdd46 100644 --- a/actionpack/lib/action_controller/test_case.rb +++ b/actionpack/lib/action_controller/test_case.rb @@ -476,6 +476,7 @@ module ActionController end self.cookies.update @request.cookies + self.cookies.update_cookies_from_jar @request.set_header 'HTTP_COOKIE', cookies.to_header @request.delete_header 'action_dispatch.cookies' diff --git a/actionpack/lib/action_dispatch/middleware/cookies.rb b/actionpack/lib/action_dispatch/middleware/cookies.rb index 6d0387cf74..f958a88e4b 100644 --- a/actionpack/lib/action_dispatch/middleware/cookies.rb +++ b/actionpack/lib/action_dispatch/middleware/cookies.rb @@ -319,6 +319,13 @@ module ActionDispatch self end + def update_cookies_from_jar + request_jar = @request.cookie_jar.instance_variable_get(:@cookies) + set_cookies = request_jar.reject { |k,_| @delete_cookies.key?(k) } + + @cookies.update set_cookies if set_cookies + end + def to_header @cookies.map { |k,v| "#{k}=#{v}" }.join ';' end diff --git a/actionpack/test/dispatch/cookies_test.rb b/actionpack/test/dispatch/cookies_test.rb index 3454e60697..e9b2fe3214 100644 --- a/actionpack/test/dispatch/cookies_test.rb +++ b/actionpack/test/dispatch/cookies_test.rb @@ -653,6 +653,15 @@ class CookiesTest < ActionController::TestCase end end + def test_cookie_jar_mutated_by_request_persists_on_future_requests + get :authenticate + cookie_jar = @request.cookie_jar + cookie_jar.signed[:user_id] = 123 + assert_equal ["user_name", "user_id"], @request.cookie_jar.instance_variable_get(:@cookies).keys + get :get_signed_cookie + assert_equal ["user_name", "user_id"], @request.cookie_jar.instance_variable_get(:@cookies).keys + end + def test_raises_argument_error_if_missing_secret assert_raise(ArgumentError, nil.inspect) { @request.env["action_dispatch.key_generator"] = ActiveSupport::LegacyKeyGenerator.new(nil)