"Subdomain shared cookies in Merb's specs"

November 13, 2009

I’m currently working on Merb app which makes use of subdomains for user accounts. In order to have user authenticated on both base domain and subdomains I set cookie domain like this in init.rb:

 Merb::Config.use do |c|
    c[:default_cookie_domain] = ".mydomain.com"
  end

Dot at the start of domain name specifies that the cookie will be set for “mydomain.com” and all its subdomains. This works perfectly in browser(s) but I’ve encountered a problem in my request specs. After authenticating at “mydomain.com” app redirects to “username.mydomain.com”. But next request to either “mydomain.com” or “username.mydomain.com” shows that session is no longer authenticated. After some reading through merb-core sources I’ve found that Merb::Test::Cookie can’t properly handle cookies with domain set to ‘.foo.com’ (with dot at the start).

This is because Merb::Test::Cookie#valid? makes some regexp check comparing current request domain with domain from cookie, which fails for cookie domain set to ‘.foo.com’. I’ve created a fix and spec for this scenario. Patch can be found in this commit.

Until it gets merged and released with new Merb version (I hope in 1.1) It was already merged into Merb master branch, but until the 1.1 release the simplest workaround is to monkey patch Merb::Test::Cookie class, ie. in spec_helper.rb like this:

class Merb::Test::Cookie
  def valid?(uri)
    domain_ = domain.start_with?('.') ? domain[1..-1] : domain
    uri_path = uri.path.blank? ? "/" : uri.path
    uri.host =~ Regexp.new("#{Regexp.escape(domain_)}$") &&
    uri_path =~ Regexp.new("^#{Regexp.escape(path)}")
  end
end
Read more about merb, ruby.
blog comments powered by Disqus