cookiejar-future 0.1.0
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +7 -0
- data/.gitignore +7 -0
- data/.rspec +2 -0
- data/.travis.yml +17 -0
- data/Gemfile +2 -0
- data/LICENSE +10 -0
- data/README.markdown +31 -0
- data/Rakefile +30 -0
- data/_config.yml +1 -0
- data/contributors.json +14 -0
- data/cookiejar.gemspec +23 -0
- data/lib/cookiejar.rb +3 -0
- data/lib/cookiejar/cookie.rb +257 -0
- data/lib/cookiejar/cookie_validation.rb +410 -0
- data/lib/cookiejar/jar.rb +314 -0
- data/lib/cookiejar/version.rb +4 -0
- data/spec/cookie_spec.rb +176 -0
- data/spec/cookie_validation_spec.rb +236 -0
- data/spec/jar_spec.rb +232 -0
- data/spec/spec_helper.rb +5 -0
- metadata +142 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA256:
|
3
|
+
metadata.gz: b3b9617f11aac76564527e7eb4cb017f6e48bc010512dfab0ba2c3f5361ffd54
|
4
|
+
data.tar.gz: b3c00721f4b0b6aa301fed8800a56fa7184b8d6e0c447c4fa7b64dc0442ab872
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: 27f534c4d2cae32028dc057d61bcf7a166ab761dc1a38acc40b654566dad96870b56bb1584197deef14fc4c67900033a5cc8733ccdd4545c5e695fbcf486d8c8
|
7
|
+
data.tar.gz: 5a58a23e564c060ea2ab18ce44a42ad835a951cba14ca01a15c3447fd8a3e17339a8099c21574a595559e4e4c00d890d6a49b2d23649144af3951e8df4577ad2
|
data/.gitignore
ADDED
data/.rspec
ADDED
data/.travis.yml
ADDED
data/Gemfile
ADDED
data/LICENSE
ADDED
@@ -0,0 +1,10 @@
|
|
1
|
+
Copyright (c) 2009 - 2018, David Waite and Other Contributors
|
2
|
+
All rights reserved.
|
3
|
+
|
4
|
+
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
5
|
+
|
6
|
+
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
7
|
+
|
8
|
+
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
9
|
+
|
10
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
data/README.markdown
ADDED
@@ -0,0 +1,31 @@
|
|
1
|
+
Ruby CookieJar
|
2
|
+
==============
|
3
|
+
|
4
|
+
**Git**: [http://github.com/dwaite/cookiejar](http://github.com/dwaite/cookiejar)
|
5
|
+
|
6
|
+
**Author**: David Waite
|
7
|
+
|
8
|
+
[![Build Status](https://travis-ci.org/dwaite/cookiejar.svg?branch=master)](https://travis-ci.org/dwaite/cookiejar)
|
9
|
+
|
10
|
+
Synopsis
|
11
|
+
--------
|
12
|
+
|
13
|
+
The Ruby CookieJar is a library to help manage client-side cookies in pure Ruby. It enables parsing and setting of cookie headers, alternating between multiple 'jars' of cookies at one time (such as having a set of cookies for each browser or thread), and supports persistence of the cookies in a JSON string.
|
14
|
+
|
15
|
+
Both Netscape/RFC 2109 cookies and RFC 2965 cookies are supported.
|
16
|
+
|
17
|
+
Roadmap
|
18
|
+
-------
|
19
|
+
|
20
|
+
For the Next major release, I would like to accomplish:
|
21
|
+
|
22
|
+
1. Check against [RFC 6265 - HTTP State Management Mechanism][rfc6265], the latest cookie spec which came out after the initial release of cookiejar
|
23
|
+
2. Determine better code structure to encourage alternate persistence mechanisms for cookie jars
|
24
|
+
|
25
|
+
[rfc6265]: http://tools.ietf.org/html/rfc6265
|
26
|
+
COPYRIGHT
|
27
|
+
---------
|
28
|
+
The Ruby CookieJar is Copyright © 2009-2014 David Waite, with [additional contributions from various authors][contributions]. Licensing terms are given within the [LICENSE file][LICENSE].
|
29
|
+
|
30
|
+
[contributions]: ./contributors.json
|
31
|
+
[LICENSE]: ./LICENSE
|
data/Rakefile
ADDED
@@ -0,0 +1,30 @@
|
|
1
|
+
require 'bundler/gem_tasks'
|
2
|
+
|
3
|
+
require 'rake'
|
4
|
+
|
5
|
+
require 'rake/clean'
|
6
|
+
require 'yard'
|
7
|
+
require 'yard/rake/yardoc_task'
|
8
|
+
|
9
|
+
CLEAN << Rake::FileList['doc/**', '.yardoc']
|
10
|
+
# Yard
|
11
|
+
YARD::Rake::YardocTask.new do |t|
|
12
|
+
t.files = ['lib/**/*.rb'] # optional
|
13
|
+
t.options = ['--title', 'CookieJar, a HTTP Client Cookie Parsing Library',
|
14
|
+
'--main', 'README.markdown', '--files', 'LICENSE']
|
15
|
+
end
|
16
|
+
|
17
|
+
begin
|
18
|
+
require 'rspec/core/rake_task'
|
19
|
+
|
20
|
+
RSpec::Core::RakeTask.new do |t|
|
21
|
+
t.ruby_opts = %w(-w)
|
22
|
+
t.pattern = 'spec/**/*_spec.rb'
|
23
|
+
end
|
24
|
+
task test: :spec
|
25
|
+
rescue LoadError
|
26
|
+
puts 'Warning: unable to load rspec tasks'
|
27
|
+
end
|
28
|
+
|
29
|
+
# Default Rake task is to run all tests
|
30
|
+
task default: :test
|
data/_config.yml
ADDED
@@ -0,0 +1 @@
|
|
1
|
+
theme: jekyll-theme-tactile
|
data/contributors.json
ADDED
@@ -0,0 +1,14 @@
|
|
1
|
+
[
|
2
|
+
{
|
3
|
+
"author": {
|
4
|
+
"github": "http://github.com/secobarbital",
|
5
|
+
"name": "Seggy Umboh"
|
6
|
+
},
|
7
|
+
"contributions": [
|
8
|
+
"widen supported IP addresses",
|
9
|
+
"fix case-sensitivity issue with HTTP headers",
|
10
|
+
"correct issue when running under Ruby 1.8.x",
|
11
|
+
"made Jar act more like a browser (dropping cookies w/o exception)"
|
12
|
+
]
|
13
|
+
}
|
14
|
+
]
|
data/cookiejar.gemspec
ADDED
@@ -0,0 +1,23 @@
|
|
1
|
+
# -*- encoding: utf-8 -*-
|
2
|
+
|
3
|
+
lib = File.expand_path('../lib', __FILE__)
|
4
|
+
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
|
5
|
+
|
6
|
+
Gem::Specification.new do |s|
|
7
|
+
s.name = 'cookiejar-future'
|
8
|
+
s.version = '0.1.0'
|
9
|
+
s.authors = ['David Waite']
|
10
|
+
s.description = 'Allows for parsing and returning cookies in Ruby HTTP client code'
|
11
|
+
s.summary = 'Client-side HTTP Cookie library'
|
12
|
+
|
13
|
+
s.files = `git ls-files`.split($INPUT_RECORD_SEPARATOR)
|
14
|
+
s.test_files = s.files.grep(%r{^(spec)/})
|
15
|
+
s.rdoc_options = ['--title', 'CookieJar -- Client-side HTTP Cookies']
|
16
|
+
s.require_paths = ['lib']
|
17
|
+
|
18
|
+
s.add_development_dependency 'rake', '>= 10.0', '< 13'
|
19
|
+
s.add_development_dependency 'rspec-collection_matchers', '~> 1.0'
|
20
|
+
s.add_development_dependency 'rspec', '~> 3.0'
|
21
|
+
s.add_development_dependency 'yard', '~> 0.9.20'
|
22
|
+
s.add_development_dependency 'bundler', '>= 0.9.3'
|
23
|
+
end
|
data/lib/cookiejar.rb
ADDED
@@ -0,0 +1,257 @@
|
|
1
|
+
require 'time'
|
2
|
+
require 'uri'
|
3
|
+
require 'cookiejar/cookie_validation'
|
4
|
+
|
5
|
+
module CookieJar
|
6
|
+
# Cookie is an immutable object which defines the data model of a HTTP Cookie.
|
7
|
+
# The data values within the cookie may be different from the
|
8
|
+
# values described in the literal cookie declaration.
|
9
|
+
# Specifically, the 'domain' and 'path' values may be set to defaults
|
10
|
+
# based on the requested resource that resulted in the cookie being set.
|
11
|
+
class Cookie
|
12
|
+
# [String] The name of the cookie.
|
13
|
+
attr_reader :name
|
14
|
+
# [String] The value of the cookie, without any attempts at decoding.
|
15
|
+
attr_reader :value
|
16
|
+
|
17
|
+
# [String] The domain scope of the cookie. Follows the RFC 2965
|
18
|
+
# 'effective host' rules. A 'dot' prefix indicates that it applies both
|
19
|
+
# to the non-dotted domain and child domains, while no prefix indicates
|
20
|
+
# that only exact matches of the domain are in scope.
|
21
|
+
attr_reader :domain
|
22
|
+
|
23
|
+
# [String] The path scope of the cookie. The cookie applies to URI paths
|
24
|
+
# that prefix match this value.
|
25
|
+
attr_reader :path
|
26
|
+
|
27
|
+
# [Boolean] The secure flag is set to indicate that the cookie should
|
28
|
+
# only be sent securely. Nearly all HTTP User Agent implementations assume
|
29
|
+
# this to mean that the cookie should only be sent over a
|
30
|
+
# SSL/TLS-protected connection
|
31
|
+
attr_reader :secure
|
32
|
+
|
33
|
+
# [Boolean] Popular browser extension to mark a cookie as invisible
|
34
|
+
# to code running within the browser, such as JavaScript
|
35
|
+
attr_reader :http_only
|
36
|
+
|
37
|
+
# [Fixnum] Version indicator, currently either
|
38
|
+
# * 0 for netscape cookies
|
39
|
+
# * 1 for RFC 2965 cookies
|
40
|
+
attr_reader :version
|
41
|
+
# [String] RFC 2965 field for indicating comment (or a location)
|
42
|
+
# describing the cookie to a usesr agent.
|
43
|
+
attr_reader :comment, :comment_url
|
44
|
+
# [Boolean] RFC 2965 field for indicating session lifetime for a cookie
|
45
|
+
attr_reader :discard
|
46
|
+
# [Array<FixNum>, nil] RFC 2965 port scope for the cookie. If not nil,
|
47
|
+
# indicates specific ports on the HTTP server which should receive this
|
48
|
+
# cookie if contacted.
|
49
|
+
attr_reader :ports
|
50
|
+
# [Time] Time when this cookie was first evaluated and created.
|
51
|
+
attr_reader :created_at
|
52
|
+
|
53
|
+
# Evaluate when this cookie will expire. Uses the original cookie fields
|
54
|
+
# for a max age or expires
|
55
|
+
#
|
56
|
+
# @return [Time, nil] Time of expiry, if this cookie has an expiry set
|
57
|
+
def expires_at
|
58
|
+
if @expiry.nil? || @expiry.is_a?(Time)
|
59
|
+
@expiry
|
60
|
+
else
|
61
|
+
@created_at + @expiry
|
62
|
+
end
|
63
|
+
end
|
64
|
+
|
65
|
+
# Indicates whether the cookie is currently considered valid
|
66
|
+
#
|
67
|
+
# @param [Time] time to compare against, or 'now' if omitted
|
68
|
+
# @return [Boolean]
|
69
|
+
def expired?(time = Time.now)
|
70
|
+
!expires_at.nil? && time > expires_at
|
71
|
+
end
|
72
|
+
|
73
|
+
# Indicates whether the cookie will be considered invalid after the end
|
74
|
+
# of the current user session
|
75
|
+
# @return [Boolean]
|
76
|
+
def session?
|
77
|
+
@expiry.nil? || @discard
|
78
|
+
end
|
79
|
+
|
80
|
+
# Create a cookie based on an absolute URI and the string value of a
|
81
|
+
# 'Set-Cookie' header.
|
82
|
+
#
|
83
|
+
# @param request_uri [String, URI] HTTP/HTTPS absolute URI of request.
|
84
|
+
# This is used to fill in domain and port if missing from the cookie,
|
85
|
+
# and to perform appropriate validation.
|
86
|
+
# @param set_cookie_value [String] HTTP value for the Set-Cookie header.
|
87
|
+
# @return [Cookie] created from the header string and request URI
|
88
|
+
# @raise [InvalidCookieError] on validation failure(s)
|
89
|
+
def self.from_set_cookie(request_uri, set_cookie_value)
|
90
|
+
args = CookieJar::CookieValidation.parse_set_cookie set_cookie_value
|
91
|
+
args[:domain] = CookieJar::CookieValidation
|
92
|
+
.determine_cookie_domain request_uri, args[:domain]
|
93
|
+
args[:path] = CookieJar::CookieValidation
|
94
|
+
.determine_cookie_path request_uri, args[:path]
|
95
|
+
cookie = Cookie.new args
|
96
|
+
CookieJar::CookieValidation.validate_cookie request_uri, cookie
|
97
|
+
cookie
|
98
|
+
end
|
99
|
+
|
100
|
+
# Create a cookie based on an absolute URI and the string value of a
|
101
|
+
# 'Set-Cookie2' header.
|
102
|
+
#
|
103
|
+
# @param request_uri [String, URI] HTTP/HTTPS absolute URI of request.
|
104
|
+
# This is used to fill in domain and port if missing from the cookie,
|
105
|
+
# and to perform appropriate validation.
|
106
|
+
# @param set_cookie_value [String] HTTP value for the Set-Cookie2 header.
|
107
|
+
# @return [Cookie] created from the header string and request URI
|
108
|
+
# @raise [InvalidCookieError] on validation failure(s)
|
109
|
+
def self.from_set_cookie2(request_uri, set_cookie_value)
|
110
|
+
args = CookieJar::CookieValidation.parse_set_cookie2 set_cookie_value
|
111
|
+
args[:domain] = CookieJar::CookieValidation
|
112
|
+
.determine_cookie_domain request_uri, args[:domain]
|
113
|
+
args[:path] = CookieJar::CookieValidation
|
114
|
+
.determine_cookie_path request_uri, args[:path]
|
115
|
+
cookie = Cookie.new args
|
116
|
+
CookieJar::CookieValidation.validate_cookie request_uri, cookie
|
117
|
+
cookie
|
118
|
+
end
|
119
|
+
|
120
|
+
# Returns cookie in a format appropriate to send to a server.
|
121
|
+
#
|
122
|
+
# @param [FixNum] 0 version, 0 for Netscape-style cookies, 1 for
|
123
|
+
# RFC2965-style.
|
124
|
+
# @param [Boolean] true prefix, for RFC2965, whether to prefix with
|
125
|
+
# "$Version=<version>;". Ignored for Netscape-style cookies
|
126
|
+
def to_s(ver = 0, prefix = true)
|
127
|
+
return "#{name}=#{value}" if ver == 0
|
128
|
+
|
129
|
+
# we do not need to encode path; the only characters required to be
|
130
|
+
# quoted must be escaped in URI
|
131
|
+
str = prefix ? "$Version=#{version};" : ''
|
132
|
+
str << "#{name}=#{value};$Path=\"#{path}\""
|
133
|
+
str << ";$Domain=#{domain}" if domain.start_with? '.'
|
134
|
+
str << ";$Port=\"#{ports.join ','}\"" if ports
|
135
|
+
str
|
136
|
+
end
|
137
|
+
|
138
|
+
# Return a hash representation of the cookie.
|
139
|
+
|
140
|
+
def to_hash
|
141
|
+
result = {
|
142
|
+
name: @name,
|
143
|
+
value: @value,
|
144
|
+
domain: @domain,
|
145
|
+
path: @path,
|
146
|
+
created_at: @created_at
|
147
|
+
}
|
148
|
+
{
|
149
|
+
expiry: @expiry,
|
150
|
+
secure: (true if @secure),
|
151
|
+
http_only: (true if @http_only),
|
152
|
+
version: (@version if version != 0),
|
153
|
+
comment: @comment,
|
154
|
+
comment_url: @comment_url,
|
155
|
+
discard: (true if @discard),
|
156
|
+
ports: @ports
|
157
|
+
}.each do |name, value|
|
158
|
+
result[name] = value if value
|
159
|
+
end
|
160
|
+
|
161
|
+
result
|
162
|
+
end
|
163
|
+
|
164
|
+
# Determine if a cookie should be sent given a request URI along with
|
165
|
+
# other options.
|
166
|
+
#
|
167
|
+
# This currently ignores domain.
|
168
|
+
#
|
169
|
+
# @param uri [String, URI] the requested page which may need to receive
|
170
|
+
# this cookie
|
171
|
+
# @param script [Boolean] indicates that cookies with the 'httponly'
|
172
|
+
# extension should be ignored
|
173
|
+
# @return [Boolean] whether this cookie should be sent to the server
|
174
|
+
def should_send?(request_uri, script)
|
175
|
+
uri = CookieJar::CookieValidation.to_uri request_uri
|
176
|
+
# cookie path must start with the uri, it must not be a secure cookie
|
177
|
+
# being sent over http, and it must not be a http_only cookie sent to
|
178
|
+
# a script
|
179
|
+
path = if uri.path == ''
|
180
|
+
'/'
|
181
|
+
else
|
182
|
+
uri.path
|
183
|
+
end
|
184
|
+
path_match = path.start_with? @path
|
185
|
+
secure_match = !(@secure && uri.scheme == 'http')
|
186
|
+
script_match = !(script && @http_only)
|
187
|
+
expiry_match = !expired?
|
188
|
+
ports_match = ports.nil? || (ports.include? uri.port)
|
189
|
+
path_match && secure_match && script_match && expiry_match && ports_match
|
190
|
+
end
|
191
|
+
|
192
|
+
def decoded_value
|
193
|
+
CookieJar::CookieValidation.decode_value value
|
194
|
+
end
|
195
|
+
|
196
|
+
# Return a JSON 'object' for the various data values. Allows for
|
197
|
+
# persistence of the cookie information
|
198
|
+
#
|
199
|
+
# @param [Array] a options controlling output JSON text
|
200
|
+
# (usually a State and a depth)
|
201
|
+
# @return [String] JSON representation of object data
|
202
|
+
def to_json(*a)
|
203
|
+
to_hash.merge(json_class: self.class.name).to_json(*a)
|
204
|
+
end
|
205
|
+
|
206
|
+
# Given a Hash representation of a JSON document, create a local cookie
|
207
|
+
# from the included data.
|
208
|
+
#
|
209
|
+
# @param [Hash] o JSON object of array data
|
210
|
+
# @return [Cookie] cookie formed from JSON data
|
211
|
+
def self.json_create(o)
|
212
|
+
params = o.inject({}) do |hash, (key, value)|
|
213
|
+
hash[key.to_sym] = value
|
214
|
+
hash
|
215
|
+
end
|
216
|
+
params[:version] ||= 0
|
217
|
+
params[:created_at] = Time.parse params[:created_at]
|
218
|
+
if params[:expiry].is_a? String
|
219
|
+
params[:expires_at] = Time.parse params[:expiry]
|
220
|
+
else
|
221
|
+
params[:max_age] = params[:expiry]
|
222
|
+
end
|
223
|
+
params.delete :expiry
|
224
|
+
|
225
|
+
new params
|
226
|
+
end
|
227
|
+
|
228
|
+
# Compute the cookie search domains for a given request URI
|
229
|
+
# This will be the effective host of the request uri, along with any
|
230
|
+
# possibly matching dot-prefixed domains
|
231
|
+
#
|
232
|
+
# @param request_uri [String, URI] address being requested
|
233
|
+
# @return [Array<String>] String domain matches
|
234
|
+
def self.compute_search_domains(request_uri)
|
235
|
+
CookieValidation.compute_search_domains request_uri
|
236
|
+
end
|
237
|
+
|
238
|
+
protected
|
239
|
+
|
240
|
+
# Call {from_set_cookie} to create a new Cookie instance
|
241
|
+
def initialize(args)
|
242
|
+
@created_at, @name, @value, @domain, @path, @secure,
|
243
|
+
@http_only, @version, @comment, @comment_url, @discard, @ports \
|
244
|
+
= args.values_at \
|
245
|
+
:created_at, :name, :value, :domain, :path, :secure,
|
246
|
+
:http_only, :version, :comment, :comment_url, :discard, :ports
|
247
|
+
|
248
|
+
@created_at ||= Time.now
|
249
|
+
@expiry = args[:max_age] || args[:expires_at]
|
250
|
+
@secure ||= false
|
251
|
+
@http_only ||= false
|
252
|
+
@discard ||= false
|
253
|
+
|
254
|
+
@ports = [@ports] if @ports.is_a? Integer
|
255
|
+
end
|
256
|
+
end
|
257
|
+
end
|
@@ -0,0 +1,410 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
require 'cgi'
|
3
|
+
require 'uri'
|
4
|
+
|
5
|
+
module CookieJar
|
6
|
+
# Represents a set of cookie validation errors
|
7
|
+
class InvalidCookieError < StandardError
|
8
|
+
# [Array<String>] the specific validation issues encountered
|
9
|
+
attr_reader :messages
|
10
|
+
|
11
|
+
# Create a new instance
|
12
|
+
# @param [String, Array<String>] the validation issue(s) encountered
|
13
|
+
def initialize(message)
|
14
|
+
if message.is_a? Array
|
15
|
+
@messages = message
|
16
|
+
message = message.join ', '
|
17
|
+
else
|
18
|
+
@messages = [message]
|
19
|
+
end
|
20
|
+
super message
|
21
|
+
end
|
22
|
+
end
|
23
|
+
|
24
|
+
# Contains logic to parse and validate cookie headers
|
25
|
+
module CookieValidation
|
26
|
+
# REGEX cookie matching
|
27
|
+
module PATTERN
|
28
|
+
include URI::REGEXP::PATTERN
|
29
|
+
|
30
|
+
TOKEN = '[^(),\/<>@;:\\\"\[\]?={}\s]+'.freeze
|
31
|
+
VALUE1 = '([^;]*)'.freeze
|
32
|
+
IPADDR = "#{IPV4ADDR}|#{IPV6ADDR}".freeze
|
33
|
+
BASE_HOSTNAME = "(?:#{DOMLABEL}\\.)(?:((?:(?:#{DOMLABEL}\\.)+(?:#{TOPLABEL}\\.?))|local))".freeze
|
34
|
+
|
35
|
+
QUOTED_PAIR = '\\\\[\\x00-\\x7F]'.freeze
|
36
|
+
LWS = '\\r\\n(?:[ \\t]+)'.freeze
|
37
|
+
# TEXT="[\\t\\x20-\\x7E\\x80-\\xFF]|(?:#{LWS})"
|
38
|
+
QDTEXT = "[\\t\\x20-\\x21\\x23-\\x7E\\x80-\\xFF]|(?:#{LWS})".freeze
|
39
|
+
QUOTED_TEXT = "\\\"(?:#{QDTEXT}|#{QUOTED_PAIR})*\\\"".freeze
|
40
|
+
VALUE2 = "#{TOKEN}|#{QUOTED_TEXT}".freeze
|
41
|
+
end
|
42
|
+
BASE_HOSTNAME = /#{PATTERN::BASE_HOSTNAME}/
|
43
|
+
BASE_PATH = %r{\A((?:[^/?#]*/)*)}
|
44
|
+
IPADDR = /\A#{PATTERN::IPV4ADDR}\Z|\A#{PATTERN::IPV6ADDR}\Z/
|
45
|
+
HDN = /\A#{PATTERN::HOSTNAME}\Z/
|
46
|
+
TOKEN = /\A#{PATTERN::TOKEN}\Z/
|
47
|
+
PARAM1 = /\A(#{PATTERN::TOKEN})(?:=#{PATTERN::VALUE1})?\Z/
|
48
|
+
PARAM2 = Regexp.new "(#{PATTERN::TOKEN})(?:=(#{PATTERN::VALUE2}))?(?:\\Z|;)", '', 'n'
|
49
|
+
# TWO_DOT_DOMAINS = /\A\.(com|edu|net|mil|gov|int|org)\Z/
|
50
|
+
|
51
|
+
# Converts the input object to a URI (if not already a URI)
|
52
|
+
#
|
53
|
+
# @param [String, URI] request_uri URI we are normalizing
|
54
|
+
# @param [URI] URI representation of input string, or original URI
|
55
|
+
def self.to_uri(request_uri)
|
56
|
+
(request_uri.is_a? URI) ? request_uri : (URI.parse request_uri)
|
57
|
+
end
|
58
|
+
|
59
|
+
# Converts an input cookie or uri to a string representing the path.
|
60
|
+
# Assume strings are already paths
|
61
|
+
#
|
62
|
+
# @param [String, URI, Cookie] object containing the path
|
63
|
+
# @return [String] path information
|
64
|
+
def self.to_path(uri_or_path)
|
65
|
+
if (uri_or_path.is_a? URI) || (uri_or_path.is_a? Cookie)
|
66
|
+
uri_or_path.path
|
67
|
+
else
|
68
|
+
uri_or_path
|
69
|
+
end
|
70
|
+
end
|
71
|
+
|
72
|
+
# Converts an input cookie or uri to a string representing the domain.
|
73
|
+
# Assume strings are already domains. Value may not be an effective host.
|
74
|
+
#
|
75
|
+
# @param [String, URI, Cookie] object containing the domain
|
76
|
+
# @return [String] domain information.
|
77
|
+
def self.to_domain(uri_or_domain)
|
78
|
+
if uri_or_domain.is_a? URI
|
79
|
+
uri_or_domain.host
|
80
|
+
elsif uri_or_domain.is_a? Cookie
|
81
|
+
uri_or_domain.domain
|
82
|
+
else
|
83
|
+
uri_or_domain
|
84
|
+
end
|
85
|
+
end
|
86
|
+
|
87
|
+
# Compare a tested domain against the base domain to see if they match, or
|
88
|
+
# if the base domain is reachable.
|
89
|
+
#
|
90
|
+
# @param [String] tested_domain domain to be tested against
|
91
|
+
# @param [String] base_domain new domain being tested
|
92
|
+
# @return [String,nil] matching domain on success, nil on failure
|
93
|
+
def self.domains_match(tested_domain, base_domain)
|
94
|
+
base = effective_host base_domain
|
95
|
+
search_domains = compute_search_domains_for_host base
|
96
|
+
search_domains.find do |domain|
|
97
|
+
domain == tested_domain
|
98
|
+
end
|
99
|
+
end
|
100
|
+
|
101
|
+
# Compute the reach of a hostname (RFC 2965, section 1)
|
102
|
+
# Determines the next highest superdomain
|
103
|
+
#
|
104
|
+
# @param [String,URI,Cookie] hostname hostname, or object holding hostname
|
105
|
+
# @return [String,nil] next highest hostname, or nil if none
|
106
|
+
def self.hostname_reach(hostname)
|
107
|
+
host = to_domain hostname
|
108
|
+
host = host.downcase
|
109
|
+
match = BASE_HOSTNAME.match host
|
110
|
+
match[1] if match
|
111
|
+
end
|
112
|
+
|
113
|
+
# Compute the base of a path, for default cookie path assignment
|
114
|
+
#
|
115
|
+
# @param [String, URI, Cookie] path, or object holding path
|
116
|
+
# @return base path (all characters up to final '/')
|
117
|
+
def self.cookie_base_path(path)
|
118
|
+
BASE_PATH.match(to_path(path))[1]
|
119
|
+
end
|
120
|
+
|
121
|
+
# Processes cookie path data using the following rules:
|
122
|
+
# Paths are separated by '/' characters, and accepted values are truncated
|
123
|
+
# to the last '/' character. If no path is specified in the cookie, a path
|
124
|
+
# value will be taken from the request URI which was used for the site.
|
125
|
+
#
|
126
|
+
# Note that this will not attempt to detect a mismatch of the request uri
|
127
|
+
# domain and explicitly specified cookie path
|
128
|
+
#
|
129
|
+
# @param [String,URI] request URI yielding this cookie
|
130
|
+
# @param [String] path on cookie
|
131
|
+
def self.determine_cookie_path(request_uri, cookie_path)
|
132
|
+
uri = to_uri request_uri
|
133
|
+
cookie_path = to_path cookie_path
|
134
|
+
|
135
|
+
if cookie_path.nil? || cookie_path.empty?
|
136
|
+
cookie_path = cookie_base_path uri.path
|
137
|
+
end
|
138
|
+
cookie_path
|
139
|
+
end
|
140
|
+
|
141
|
+
# Given a URI, compute the relevant search domains for pre-existing
|
142
|
+
# cookies. This includes all the valid dotted forms for a named or IP
|
143
|
+
# domains.
|
144
|
+
#
|
145
|
+
# @param [String, URI] request_uri requested uri
|
146
|
+
# @return [Array<String>] all cookie domain values which would match the
|
147
|
+
# requested uri
|
148
|
+
def self.compute_search_domains(request_uri)
|
149
|
+
uri = to_uri request_uri
|
150
|
+
return nil unless uri.is_a? URI::HTTP
|
151
|
+
host = uri.host
|
152
|
+
compute_search_domains_for_host host
|
153
|
+
end
|
154
|
+
|
155
|
+
# Given a host, compute the relevant search domains for pre-existing
|
156
|
+
# cookies
|
157
|
+
#
|
158
|
+
# @param [String] host host being requested
|
159
|
+
# @return [Array<String>] all cookie domain values which would match the
|
160
|
+
# requested uri
|
161
|
+
def self.compute_search_domains_for_host(host)
|
162
|
+
host = effective_host host
|
163
|
+
result = [host]
|
164
|
+
unless host =~ IPADDR
|
165
|
+
result << ".#{host}"
|
166
|
+
base = hostname_reach host
|
167
|
+
result << ".#{base}" if base
|
168
|
+
end
|
169
|
+
result
|
170
|
+
end
|
171
|
+
|
172
|
+
# Processes cookie domain data using the following rules:
|
173
|
+
# Domains strings of the form .foo.com match 'foo.com' and all immediate
|
174
|
+
# subdomains of 'foo.com'. Domain strings specified of the form 'foo.com'
|
175
|
+
# are modified to '.foo.com', and as such will still apply to subdomains.
|
176
|
+
#
|
177
|
+
# Cookies without an explicit domain will have their domain value taken
|
178
|
+
# directly from the URL, and will _NOT_ have any leading dot applied. For
|
179
|
+
# example, a request to http://foo.com/ will cause an entry for 'foo.com'
|
180
|
+
# to be created - which applies to foo.com but no subdomain.
|
181
|
+
#
|
182
|
+
# Note that this will not attempt to detect a mismatch of the request uri
|
183
|
+
# domain and explicitly specified cookie domain
|
184
|
+
#
|
185
|
+
# @param [String, URI] request_uri originally requested URI
|
186
|
+
# @param [String] cookie domain value
|
187
|
+
# @return [String] effective host
|
188
|
+
def self.determine_cookie_domain(request_uri, cookie_domain)
|
189
|
+
uri = to_uri request_uri
|
190
|
+
domain = to_domain cookie_domain
|
191
|
+
|
192
|
+
return effective_host(uri.host) if domain.nil? || domain.empty?
|
193
|
+
domain = domain.downcase
|
194
|
+
if domain =~ IPADDR || domain.start_with?('.')
|
195
|
+
domain
|
196
|
+
else
|
197
|
+
".#{domain}"
|
198
|
+
end
|
199
|
+
end
|
200
|
+
|
201
|
+
# Compute the effective host (RFC 2965, section 1)
|
202
|
+
#
|
203
|
+
# Has the added additional logic of searching for interior dots
|
204
|
+
# specifically, and matches colons to prevent .local being suffixed on
|
205
|
+
# IPv6 addresses
|
206
|
+
#
|
207
|
+
# @param [String, URI] host_or_uridomain name, or absolute URI
|
208
|
+
# @return [String] effective host per RFC rules
|
209
|
+
def self.effective_host(host_or_uri)
|
210
|
+
hostname = to_domain host_or_uri
|
211
|
+
hostname = hostname.downcase
|
212
|
+
|
213
|
+
if /.[\.:]./.match(hostname) || hostname == '.local'
|
214
|
+
hostname
|
215
|
+
else
|
216
|
+
hostname + '.local'
|
217
|
+
end
|
218
|
+
end
|
219
|
+
|
220
|
+
# Check whether a cookie meets all of the rules to be created, based on
|
221
|
+
# its internal settings and the URI it came from.
|
222
|
+
#
|
223
|
+
# @param [String,URI] request_uri originally requested URI
|
224
|
+
# @param [Cookie] cookie object
|
225
|
+
# @param [true] will always return true on success
|
226
|
+
# @raise [InvalidCookieError] on failures, containing all validation errors
|
227
|
+
def self.validate_cookie(request_uri, cookie)
|
228
|
+
uri = to_uri request_uri
|
229
|
+
request_path = uri.path
|
230
|
+
cookie_host = cookie.domain
|
231
|
+
cookie_path = cookie.path
|
232
|
+
|
233
|
+
errors = []
|
234
|
+
|
235
|
+
# From RFC 2965, Section 3.3.2 Rejecting Cookies
|
236
|
+
|
237
|
+
# A user agent rejects (SHALL NOT store its information) if the
|
238
|
+
# Version attribute is missing. Note that the legacy Set-Cookie
|
239
|
+
# directive will result in an implicit version 0.
|
240
|
+
errors << 'Version missing' unless cookie.version
|
241
|
+
|
242
|
+
# The value for the Path attribute is not a prefix of the request-URI
|
243
|
+
|
244
|
+
# If the initial request path is empty then this will always fail
|
245
|
+
# so check if it is empty and if so then set it to /
|
246
|
+
request_path = '/' if request_path == ''
|
247
|
+
|
248
|
+
unless request_path.start_with? cookie_path
|
249
|
+
errors << 'Path is not a prefix of the request uri path'
|
250
|
+
end
|
251
|
+
|
252
|
+
unless cookie_host =~ IPADDR || # is an IPv4 or IPv6 address
|
253
|
+
cookie_host =~ /.\../ || # contains an embedded dot
|
254
|
+
cookie_host == '.local' # is the domain cookie for local addresses
|
255
|
+
errors << 'Domain format is illegal'
|
256
|
+
end
|
257
|
+
|
258
|
+
# The effective host name that derives from the request-host does
|
259
|
+
# not domain-match the Domain attribute.
|
260
|
+
#
|
261
|
+
# The request-host is a HDN (not IP address) and has the form HD,
|
262
|
+
# where D is the value of the Domain attribute, and H is a string
|
263
|
+
# that contains one or more dots.
|
264
|
+
unless domains_match cookie_host, uri
|
265
|
+
errors << 'Domain is inappropriate based on request URI hostname'
|
266
|
+
end
|
267
|
+
|
268
|
+
# The Port attribute has a "port-list", and the request-port was
|
269
|
+
# not in the list.
|
270
|
+
unless cookie.ports.nil? || !cookie.ports.empty?
|
271
|
+
unless cookie.ports.find_index uri.port
|
272
|
+
errors << 'Ports list does not contain request URI port'
|
273
|
+
end
|
274
|
+
end
|
275
|
+
|
276
|
+
fail InvalidCookieError, errors unless errors.empty?
|
277
|
+
|
278
|
+
# Note: 'secure' is not explicitly defined as an SSL channel, and no
|
279
|
+
# test is defined around validity and the 'secure' attribute
|
280
|
+
true
|
281
|
+
end
|
282
|
+
|
283
|
+
# Break apart a traditional (non RFC 2965) cookie value into its core
|
284
|
+
# components. This does not do any validation, or defaulting of values
|
285
|
+
# based on requested URI
|
286
|
+
#
|
287
|
+
# @param [String] set_cookie_value a Set-Cookie header formatted cookie
|
288
|
+
# definition
|
289
|
+
# @return [Hash] Contains the parsed values of the cookie
|
290
|
+
def self.parse_set_cookie(set_cookie_value)
|
291
|
+
args = {}
|
292
|
+
params = set_cookie_value.split(/;\s*/)
|
293
|
+
|
294
|
+
first = true
|
295
|
+
params.each do |param|
|
296
|
+
result = PARAM1.match param
|
297
|
+
unless result
|
298
|
+
fail InvalidCookieError,
|
299
|
+
"Invalid cookie parameter in cookie '#{set_cookie_value}'"
|
300
|
+
end
|
301
|
+
key = result[1].downcase.to_sym
|
302
|
+
keyvalue = result[2]
|
303
|
+
if first
|
304
|
+
args[:name] = result[1]
|
305
|
+
args[:value] = keyvalue
|
306
|
+
first = false
|
307
|
+
else
|
308
|
+
case key
|
309
|
+
when :expires
|
310
|
+
begin
|
311
|
+
args[:expires_at] = Time.parse keyvalue
|
312
|
+
rescue ArgumentError
|
313
|
+
raise unless $ERROR_INFO.message == 'time out of range'
|
314
|
+
args[:expires_at] = Time.at(0x7FFFFFFF)
|
315
|
+
end
|
316
|
+
when :"max-age"
|
317
|
+
args[:max_age] = keyvalue.to_i
|
318
|
+
when :domain, :path
|
319
|
+
args[key] = keyvalue
|
320
|
+
when :secure
|
321
|
+
args[:secure] = true
|
322
|
+
when :httponly
|
323
|
+
args[:http_only] = true
|
324
|
+
when :samesite
|
325
|
+
args[:samesite] = keyvalue.downcase
|
326
|
+
else
|
327
|
+
fail InvalidCookieError, "Unknown cookie parameter '#{key}'"
|
328
|
+
end
|
329
|
+
end
|
330
|
+
end
|
331
|
+
args[:version] = 0
|
332
|
+
args
|
333
|
+
end
|
334
|
+
|
335
|
+
# Parse a RFC 2965 value and convert to a literal string
|
336
|
+
def self.value_to_string(value)
|
337
|
+
if /\A"(.*)"\Z/ =~ value
|
338
|
+
value = Regexp.last_match(1)
|
339
|
+
value.gsub(/\\(.)/, '\1')
|
340
|
+
else
|
341
|
+
value
|
342
|
+
end
|
343
|
+
end
|
344
|
+
|
345
|
+
# Attempt to decipher a partially decoded version of text cookie values
|
346
|
+
def self.decode_value(value)
|
347
|
+
if /\A"(.*)"\Z/ =~ value
|
348
|
+
value_to_string value
|
349
|
+
else
|
350
|
+
CGI.unescape value
|
351
|
+
end
|
352
|
+
end
|
353
|
+
|
354
|
+
# Break apart a RFC 2965 cookie value into its core components.
|
355
|
+
# This does not do any validation, or defaulting of values
|
356
|
+
# based on requested URI
|
357
|
+
#
|
358
|
+
# @param [String] set_cookie_value a Set-Cookie2 header formatted cookie
|
359
|
+
# definition
|
360
|
+
# @return [Hash] Contains the parsed values of the cookie
|
361
|
+
def self.parse_set_cookie2(set_cookie_value)
|
362
|
+
args = {}
|
363
|
+
first = true
|
364
|
+
index = 0
|
365
|
+
begin
|
366
|
+
md = PARAM2.match set_cookie_value[index..-1]
|
367
|
+
if md.nil? || md.offset(0).first != 0
|
368
|
+
fail InvalidCookieError,
|
369
|
+
"Invalid Set-Cookie2 header '#{set_cookie_value}'"
|
370
|
+
end
|
371
|
+
index += md.offset(0)[1]
|
372
|
+
|
373
|
+
key = md[1].downcase.to_sym
|
374
|
+
keyvalue = md[2] || md[3]
|
375
|
+
if first
|
376
|
+
args[:name] = md[1]
|
377
|
+
args[:value] = keyvalue
|
378
|
+
first = false
|
379
|
+
else
|
380
|
+
keyvalue = value_to_string keyvalue
|
381
|
+
case key
|
382
|
+
when :comment, :commenturl, :domain, :path
|
383
|
+
args[key] = keyvalue
|
384
|
+
when :discard, :secure
|
385
|
+
args[key] = true
|
386
|
+
when :httponly
|
387
|
+
args[:http_only] = true
|
388
|
+
when :"max-age"
|
389
|
+
args[:max_age] = keyvalue.to_i
|
390
|
+
when :version
|
391
|
+
args[:version] = keyvalue.to_i
|
392
|
+
when :port
|
393
|
+
# must be in format '"port,port"'
|
394
|
+
ports = keyvalue.split(/,\s*/)
|
395
|
+
args[:ports] = ports.map(&:to_i)
|
396
|
+
else
|
397
|
+
fail InvalidCookieError, "Unknown cookie parameter '#{key}'"
|
398
|
+
end
|
399
|
+
end
|
400
|
+
end until md.post_match.empty?
|
401
|
+
# if our last match in the scan failed
|
402
|
+
if args[:version] != 1
|
403
|
+
fail InvalidCookieError,
|
404
|
+
'Set-Cookie2 declares a non RFC2965 version cookie'
|
405
|
+
end
|
406
|
+
|
407
|
+
args
|
408
|
+
end
|
409
|
+
end
|
410
|
+
end
|