Class: Greed::Cookie::DomainHandler

Inherits:
Object
  • Object
show all
Defined in:
lib/greed/cookie/domain_handler.rb

Instance Method Summary collapse

Instance Method Details

#determine_domain(document_domain, cookie_domain) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/greed/cookie/domain_handler.rb', line 16

def determine_domain(document_domain, cookie_domain)
  document_domain = document_domain.downcase
  unless cookie_domain.present?
    return {
      domain: document_domain, # cookie domain not present
      include_subdomains: false
    }
  end
  document_ip_address = begin
    ::IPAddr.new(document_domain)
  rescue ::IPAddr::Error
    nil
  end
  if document_ip_address
    # handles IP Addresses
    cookie_ip_address = begin
      ::IPAddr.new(cookie_domain)
    rescue ::IPAddr::Error
      raise CrossDomainViolation
    end
    raise CrossDomainViolation unless cookie_ip_address == document_ip_address
    return {
      domain: cookie_ip_address.to_s, # normalized
      include_subdomains: false
    }
  end
  cookie_domain = cookie_domain.downcase
  # ignore leading dot
  matched_data = /\A\s*\.?(?!\.)(\S+)\s*\z/.match(cookie_domain)
  raise MalformedCookieDomain unless matched_data
  cookie_domain = matched_data[1]
  if document_domain == cookie_domain
    # exact domain matched
    return {
      domain: document_domain,
      include_subdomains: true
    }
  end
  # prevent setting cookie on a top level domain
  # "localhost" use cases should already ruled out with the exact domain match condition
  raise CrossDomainViolation unless ::PublicSuffix.valid?(cookie_domain, ignore_private: true)
  # prevent parent domain from setting cookie of a subdomain
  raise CrossDomainViolation unless (document_domain[
    document_domain.size - cookie_domain.size,
    cookie_domain.size
  ] == cookie_domain) && \
  (document_domain[
    document_domain.size - cookie_domain.size - 1
  ] == ?.)
  {
    domain: cookie_domain, # set cookie for its parent domain
    include_subdomains: true
  }
end