module SafeCookies::CookiePathFix

Public Instance Methods

delete_cookies_on_bad_path() click to toggle source

Previously, the SafeCookies gem would not set a path when rewriting cookies. Browsers then would assume and store the current “directory” (see below), leading to multiple cookies per domain.

If the cookies were secured before the configured datetime, this method instructs the client to delete all cookies it sent with the request and that we are able to rewrite, plus the SECURED_COOKIE_NAME helper cookie.

The middleware still sees the request cookies and will rewrite them as if it hadn't seen them before, setting them on the correct path (root, by default).

# File lib/safe_cookies/cookie_path_fix.rb, line 15
def delete_cookies_on_bad_path
  rewritable_request_cookies.keys.each &method(:delete_cookie_for_current_directory)
  delete_cookie_for_current_directory(SafeCookies::SECURED_COOKIE_NAME)

  # Delete this cookie here, so the middleware believes it hasn't secured
  # the cookies yet.
  @request.cookies.delete(SafeCookies::SECURED_COOKIE_NAME)
end

Private Instance Methods

current_directory_is_root?() click to toggle source
# File lib/safe_cookies/cookie_path_fix.rb, line 51
def current_directory_is_root?
  # in words: "there are not three slashes before any query params"
  !@request.path[%r(^/[^/]+/[^\?]+), 0]
end
secured_old_cookies_timestamp() click to toggle source
# File lib/safe_cookies/cookie_path_fix.rb, line 56
def secured_old_cookies_timestamp
  @request.cookies.has_key?(SafeCookies::SECURED_COOKIE_NAME) or return nil

  Time.rfc2822(@request.cookies[SafeCookies::SECURED_COOKIE_NAME])
rescue ArgumentError
  # If we cannot parse the secured_old_cookies time,
  # assume it was before we noticed the bug to ensure
  # broken cookie paths will be fixed.
  #
  # One reason to get here is that Rack::Utils.rfc2822 produces an invalid
  # datetime string in Rack v1.1, writing the date with dashes
  # (e.g. '04-Nov-2013').
  Time.parse "2013-08-25 00:00"
end