Skip to content

Commit 2e74b81

Browse files
committed
parse the cookie to determine existing flags
1 parent 754055b commit 2e74b81

File tree

2 files changed

+27
-7
lines changed

2 files changed

+27
-7
lines changed

lib/secure_headers/headers/cookie.rb

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,6 @@ class Cookie
99
SAMESITE_LAX_REGEXP =/;\s*SameSite=Lax\s*(;|$)/i.freeze
1010
SAMESITE_STRICT_REGEXP =/;\s*SameSite=Strict\s*(;|$)/i.freeze
1111

12-
REGEXES = {
13-
secure: SECURE_REGEXP,
14-
httponly: HTTPONLY_REGEXP,
15-
samesite: SAMESITE_REGEXP,
16-
}
17-
1812
class << self
1913
def validate_config!(config)
2014
return if config.nil? || config == OPT_OUT
@@ -84,6 +78,13 @@ def validate_config!(config)
8478
def initialize(cookie, config)
8579
@raw_cookie = cookie
8680
@config = config
81+
@attributes = {
82+
"secure" => nil,
83+
"httponly" => nil,
84+
"samesite" => nil,
85+
}
86+
87+
parse(cookie)
8788
end
8889

8990
def to_s
@@ -113,7 +114,7 @@ def parsed_cookie
113114
end
114115

115116
def already_flagged?(attribute)
116-
raw_cookie =~ REGEXES[attribute]
117+
@attributes[attribute.to_s]
117118
end
118119

119120
def flag_cookie?(attribute)
@@ -169,5 +170,18 @@ def flag_samesite_enforcement?(mode)
169170
false
170171
end
171172
end
173+
174+
def parse(cookie)
175+
return unless cookie
176+
177+
cookie.split(/[;,]\s?/).each do |pairs|
178+
name, values = pairs.split('=',2)
179+
name = CGI.unescape(name)
180+
181+
if @attributes.has_key?(name.downcase)
182+
@attributes[name.downcase] = values || true
183+
end
184+
end
185+
end
172186
end
173187
end

spec/lib/secure_headers/cookie_spec.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,12 @@ module SecureHeaders
9797
cookie = Cookie.new(raw_cookie, samesite: { strict: { only: ["_session"] }, lax: { only: ["_additional_session"] } })
9898
expect(cookie.to_s).to match(Cookie::SAMESITE_STRICT_REGEXP)
9999
end
100+
101+
it "ignores configuration if the cookie is already flagged" do
102+
raw_cookie = "_session=thisisatest; SameSite=Strict"
103+
cookie = Cookie.new(raw_cookie, samesite: { lax: true })
104+
expect(cookie.to_s).to eq(raw_cookie)
105+
end
100106
end
101107
end
102108

0 commit comments

Comments
 (0)