Skip to content

Commit

Permalink
Preserve quotes when parsing server cookie sparklemotion#11
Browse files Browse the repository at this point in the history
We keep track of the original quoted value when it is already quoted,
and we avoid consider values to be quoted if they start with a quote.
  • Loading branch information
lacostej committed Apr 2, 2016
1 parent 1c4a7bb commit a238d18
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 6 deletions.
10 changes: 9 additions & 1 deletion lib/http/cookie.rb
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,13 @@ def value= value
# RFC 6265 4.1.1
# cookie-name may not match:
# /[^\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]/
orig = value
if m = value.match(/^"(.*)"$/)
@raw_value = value
value = m[1]
else
@raw_value = nil
end
@value = value
end

Expand Down Expand Up @@ -594,7 +601,8 @@ def valid_for_uri?(uri)
# Returns a string for use in the Cookie header, i.e. `name=value`
# or `name="value"`.
def cookie_value
"#{@name}=#{Scanner.quote(@value)}"
v = ( @raw_value.nil? ? Scanner.quote(@value) : @raw_value )
"#{@name}=#{v}"
end
alias to_s cookie_value

Expand Down
12 changes: 8 additions & 4 deletions lib/http/cookie/scanner.rb
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,14 @@ def scan_value
case
when scan(/[^,;"]+/)
s << matched
when skip(/"/)
# RFC 6265 2.2
# A cookie-value may be DQUOTE'd.
s << scan_dquoted
when scan(/"/)
if s.length == 0
# RFC 6265 2.2
# A cookie-value may be DQUOTE'd.
s << '"' << scan_dquoted << '"'
else
s << matched
end
when check(/;|#{RE_COOKIE_COMMA}/o)
break
else
Expand Down
12 changes: 11 additions & 1 deletion test/test_http_cookie.rb
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ def test_parse_quoted
assert_equal 1, HTTP::Cookie.parse(cookie_str, uri) { |cookie|
assert_equal 'quoted', cookie.name
assert_equal 'value', cookie.value
assert_equal 'quoted="value"', cookie.cookie_value
}.size
end

Expand Down Expand Up @@ -430,7 +431,10 @@ def test_cookie_with_secure
def test_cookie_value
[
['foo="bar baz"', 'bar baz'],
['foo="bar baz"', '"bar baz"'],
['foo="bar\"; \"baz"', 'bar"; "baz'],
['foo="bar\"; \"baz"', '"bar\"; \"baz"'],
['foo="ba\"r baz"', '"ba\"r baz"'],
].each { |cookie_value, value|
cookie = HTTP::Cookie.new('foo', value)
assert_equal(cookie_value, cookie.cookie_value)
Expand All @@ -453,8 +457,14 @@ def test_cookie_value

assert_equal 3, hash.size

parsed_pairs = [
['Foo', 'value1'],
['Bar', '"value 2"'],
['Baz', 'value3'],
]

hash.each_pair { |name, value|
_, pvalue = pairs.assoc(name)
_, pvalue = parsed_pairs.assoc(name)
assert_equal pvalue, value
}
end
Expand Down

0 comments on commit a238d18

Please sign in to comment.