Debian Codegraph @

ipapython/cookie.py

raw
1 # Authors:
2 # John Dennis <[email protected]>
3 #
4 # Copyright (C) 2012 Red Hat
5 # see file 'COPYING' for use and warranty information
6 #
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19
20 import re
21 import datetime
22 import email.utils
23 from calendar import timegm
24 from urllib.parse import urlparse
25 from ipapython.ipautil import datetime_from_utctimestamp
26
27
28 '''
29 Core Python has two cookie libraries, Cookie.py targeted to server
30 side and cookielib.py targeted to client side. So why this module and
31 not use the standard libraries?
32
33 Cookie.py has some serious bugs, it cannot correctly parse the
34 HttpOnly, Secure, and Expires cookie attributes (more of a client side
35 need and not what it was designed for). Since we utilize those
36 attributes that makes Cookie.py a non-starter. Plus it's API awkard
37 and limited (we would have to build more on top of it).
38
39 The Cookie.py bug reports are:
40
41 http://bugs.python.org/issue3073
42 http://bugs.python.org/issue16611
43
44 cookielib.py has a lot of good featuress, a nice API and covers all
45 the relevant RFC's as well as actual practice in the field. However
46 cookielib.py is tighly integrated with urllib2 and it's not possible
47 to use most of the features of cookielib without simultaneously using
48 urllib2. Unfortunataely we only use httplib because of our dependency
49 on xmlrpc.client. Without urllib2 cookielib is a non-starter.
50
51 This module is a minimal implementation of Netscape cookies which
52 works equally well on either the client or server side. It's API is
53 easy to use with cookie attributes as class properties which can be
54 read or set easily. The Cookie object automatically converts Expires
55 and Max-Age attributes into datetime objects for easy time
56 comparision. Cookies in strings can easily be parsed, including
57 multiple cookies in the HTTP_COOKIE envionment variable.
58
59 The cookie RFC is silent on any escaping requirements for cookie
60 contents as such this module does not provide any automated support
61 escaping and unescapin.
62
63 '''
64
65 #-------------------------------------------------------------------------------
66
67
68 class Cookie:
69 '''
70 A Cookie object has the following attributes:
71
72 key
73 The name of the cookie
74 value
75 The value of the cookie
76
77 A Cookie also supports these predefined optional attributes. If an
78 optional attribute is not set on the cookie it's value is None.
79
80 domain
81 Restrict cookie usage to this domain
82 path
83 Restrict cookie usage to this path or below
84 expires
85 Cookie is invalid after this UTC timestamp
86 max_age
87 Cookie is invalid this many seconds in the future.
88 Has precedence over the expires attribute.
89 secure
90 Cookie should only be returned on secure (i.e. SSL/TLS)
91 connections.
92 httponly
93 Cookie is intended only for HTTP communication, it can
94 never be utilized in any other context (e.g. browser
95 Javascript).
96
97 See the documentation of get_expiration() for an explanation of
98 how the expires and max-age attributes interact as well as the
99 role of the timestamp attribute. Expiration values are stored as
100 datetime objects for easy manipulation and comparision.
101
102 There are two ways to instantiate a Cookie object. Either directly
103 via the constructor or by calling the class function parse() which
104 returns a list of Cookie objects found in a string.
105
106 To create a cookie to sent to a client:
107
108 Example:
109
110 cookie = Cookie('session', session_id,
111 domain=my_domain, path=mypath,
112 httponly=True, secure=True, expires=expiration)
113 headers.append(('Set-Cookie', str(cookie)))
114
115
116 To receive cookies from a request:
117
118 Example:
119
120 cookies = Cookie.parse(response.getheader('Set-Cookie'), request_url)
121
122 '''
123
124 class Expired(ValueError):
125 pass
126
127 class URLMismatch(ValueError):
128 pass
129
130 # regexp to split fields at a semi-colon
131 field_re = re.compile(r';\s*')
132
133 # regexp to locate a key/value pair
134 kv_pair_re = re.compile(r'^\s*([a-zA-Z0-9\!\#\$\%\&\'\*\+\-\.\^\_\`\|\~]+)\s*=\s*(.*?)\s*$', re.IGNORECASE)
135
136 # Reserved attribute names, maps from lower case protocol name to
137 # object attribute name
138 attrs = {'domain' : 'domain',
139 'path' : 'path',
140 'max-age' : 'max_age',
141 'expires' : 'expires',
142 'secure' : 'secure',
143 'httponly' : 'httponly'}
144
145 @classmethod
146 def datetime_to_time(cls, dt):
147 '''
148 Timestamps (timestamp & expires) are stored as datetime
149 objects in UTC. It's non-obvious how to convert a naive UTC
150 datetime into a unix time value (seconds since the epoch
151 UTC). That functionality is oddly missing from the datetime
152 and time modules. This utility provides that missing
153 functionality.
154 '''
155 # Use timegm from the calendar module
156 return timegm(dt.utctimetuple())
157
158 @classmethod
159 def datetime_to_string(cls, dt=None):
160 '''
161 Given a datetime object in UTC generate RFC 1123 date string.
162 '''
163
164 # Try to verify dt is specified as UTC. If utcoffset is not
165 # available we'll just have to assume the caller is using the
166 # correct timezone.
167 utcoffset = dt.utcoffset()
168 if utcoffset is not None and utcoffset.total_seconds() != 0.0:
169 raise ValueError("timezone is not UTC")
170
171 # Do not use strftime because it respects the locale, instead
172 # use the RFC 1123 formatting function which uses only English
173
174 return email.utils.formatdate(cls.datetime_to_time(dt), usegmt=True)
175
176 @classmethod
177 def parse_datetime(cls, s):
178 '''
179 Parse a RFC 822, RFC 1123 date string, return a datetime naive object in UTC.
180 '''
181
182 s = s.strip()
183
184 # Do not use strptime because it respects the locale, instead
185 # use the RFC 1123 parsing function which uses only English
186
187 try:
188 dt = email.utils.parsedate_to_datetime(s)
189 except Exception as e:
190 raise ValueError("unable to parse expires datetime '%s': %s" % (s, e))
191
192 return dt
193
194 @classmethod
195 def normalize_url_path(cls, url_path):
196 '''
197 Given a URL path, possibly empty, return a path consisting
198 only of directory components. The URL path must end with a
199 trailing slash for the last path element to be considered a
200 directory. Also the URL path must begin with a slash. Empty
201 input returns '/'.
202
203 Examples:
204
205 '' -> '/'
206 '/' -> '/'
207 'foo' -> '/'
208 'foo/' -> '/'
209 '/foo -> '/'
210 '/foo/' -> '/foo'
211 '/foo/bar' -> '/foo'
212 '/foo/bar/' -> '/foo/bar'
213 '''
214 url_path = url_path.lower()
215
216 if not url_path:
217 return '/'
218
219 if not url_path.startswith('/'):
220 return '/'
221
222 if url_path.count('/') <= 1:
223 return '/'
224
225 return url_path[:url_path.rindex('/')]
226
227
228 @classmethod
229 def parse(cls, cookie_string, request_url=None):
230 '''
231 Given a string containing one or more cookies (the
232 HTTP_COOKIES environment variable typically contains multiple
233 cookies) parse the string and return a list of Cookie objects
234 found in the string.
235 '''
236
237 # Our list of returned cookies
238 cookies = []
239
240 # Split the input string at semi-colon boundaries, we call this a
241 # field. A field may either be a single keyword or a key=value
242 # pair.
243 fields = Cookie.field_re.split(cookie_string)
244
245 # The input string may have multiple cookies inside it. This is
246 # common when the string comes from a HTTP_COOKIE environment
247 # variable. All the cookies will be contenated, separated by a
248 # semi-colon. Semi-colons are also the separator between
249 # attributes in a cookie.
250 #
251 # To distinguish between two adjacent cookies in a string we
252 # have to locate the key=value pair at the start of a
253 # cookie. Unfortunately cookies have attributes that also look
254 # like key/value pairs, the only way to distinguish a cookie
255 # attribute from a cookie is the fact the attribute names are
256 # reserved. A cookie attribute may either be a key/value pair
257 # or a single key (e.g. HttpOnly). As we scan the cookie we
258 # first identify the key=value (cookie name, cookie
259 # value). Then we continue scanning, if a bare key or
260 # key/value pair follows and is a known reserved keyword than
261 # that's an attribute belonging to the current cookie. As soon
262 # as we see a key/value pair whose key is not reserved we know
263 # we've found a new cookie. Bare keys (no value) can never
264 # start a new cookie.
265
266 # Iterate over all the fields and emit a new cookie whenever the
267 # next field is not a known attribute.
268 cookie = None
269 for field in fields:
270 match = Cookie.kv_pair_re.search(field)
271 if match:
272 key = match.group(1)
273 value = match.group(2)
274
275 # Double quoted value?
276 if value and value[0] == '"':
277 if value[-1] == '"':
278 value = value[1:-1]
279 else:
280 raise ValueError("unterminated quote in '%s'" % value)
281 kv_pair = True
282 else:
283 key = field
284 value = True # True because bare keys are boolean flags
285 kv_pair = False
286
287 is_attribute = key.lower() in Cookie.attrs
288
289 # First cookie found, create new cookie object
290 if cookie is None and kv_pair and not is_attribute:
291 cookie = Cookie(key, value)
292
293 # If start of new cookie then flush previous cookie and create
294 # a new one (it's a new cookie because it's a key/value pair
295 # whose key is not a reserved keyword).
296 elif cookie and kv_pair and not is_attribute:
297 if request_url is not None:
298 cookie.normalize(request_url)
299 cookies.append(cookie)
300 cookie = Cookie(key, value)
301
302 # If it's a reserved keyword add that as an attribute to the
303 # current cookie being scanned.
304 elif cookie and is_attribute:
305 cookie.__set_attr(key, value)
306 # If we've found a non-empty single token that's not a
307 # reserved keyword it's an error. An empty token can occur
308 # when there are two adjacent semi-colons (i.e. "; ;").
309 # We don't consider empty tokens an error.
310 elif key:
311 raise ValueError("unknown cookie token '%s'" % key)
312
313 # Flush out final cookie
314 if cookie:
315 if request_url is not None:
316 cookie.normalize(request_url)
317 cookies.append(cookie)
318
319 return cookies
320
321 @classmethod
322 def get_named_cookie_from_string(cls, cookie_string, cookie_name,
323 request_url=None, timestamp=None):
324 '''
325 A cookie string may contain multiple cookies, parse the cookie
326 string and return the last cookie in the string matching the
327 cookie name or None if not found.
328
329 This is basically a utility wrapper around the parse() class
330 method which iterates over what parse() returns looking for
331 the specific cookie.
332
333 When cookie_name appears more than once the last instance is
334 returned rather than the first because the ordering sequence
335 makes the last instance the current value.
336 '''
337
338 target_cookie = None
339
340 cookies = cls.parse(cookie_string)
341 for cookie in cookies:
342 if cookie.key == cookie_name:
343 target_cookie = cookie
344
345 if timestamp is not None:
346 target_cookie.timestamp = timestamp
347 if request_url is not None:
348 target_cookie.normalize(request_url)
349 return target_cookie
350
351
352 def __init__(self, key, value, domain=None, path=None, max_age=None, expires=None,
353 secure=None, httponly=None, timestamp=None):
354 self.key = key
355 self.value = value
356 self.domain = domain
357 self.path = path
358 self.max_age = max_age
359 self.expires = expires
360 self.secure = secure
361 self.httponly = httponly
362 self.timestamp = timestamp
363
364 @property
365 def timestamp(self):
366 '''
367 The UTC moment at which cookie was received for purposes of
368 computing the expiration given a Max-Age offset. The
369 expiration will be timestamp + max_age. The timestamp value
370 will aways be a datetime object.
371
372 By default the timestamp will be the moment the Cookie object
373 is created as this often corresponds to the moment the cookie
374 is received (the intent of the Max-Age attribute). But becuase
375 it's sometimes desirable to force a specific moment for
376 purposes of computing the expiration from the Max-Age the
377 Cookie timestamp can be updated.
378
379 Setting a value of None causes the timestamp to be set to the
380 current UTC time (now). You may also assign with a numeric
381 UNIX timestamp (seconds since the epoch UTC) or a formatted time
382 sting, in all cases the value will be converted to a datetime
383 object.
384 '''
385 return self._timestamp
386
387 @timestamp.setter
388 def timestamp(self, value):
389 if value is None:
390 self._timestamp = None
391 elif isinstance(value, datetime.datetime):
392 self._timestamp = value
393 elif isinstance(value, (int, float)):
394 self._timestamp = datetime_from_utctimestamp(value, units=1)
395 elif isinstance(value, str):
396 self._timestamp = Cookie.parse_datetime(value)
397 else:
398 raise TypeError('value must be datetime, int, long, float, basestring or None, not %s' % \
399 value.__class__.__name__)
400
401 @property
402 def expires(self):
403 '''
404 The expiration timestamp (in UTC) as a datetime object for the
405 cookie, or None if not set.
406
407 You may assign a value of None, a datetime object, a numeric
408 UNIX timestamp (seconds since the epoch UTC) or formatted time
409 string (the latter two will be converted to a datetime object.
410 '''
411 return self._expires
412
413 @expires.setter
414 def expires(self, value):
415 if value is None:
416 self._expires = None
417 elif isinstance(value, datetime.datetime):
418 self._expires = value
419 if self._expires.tzinfo is None:
420 self._expires.replace(tzinfo=datetime.timezone.utc)
421 elif isinstance(value, (int, float)):
422 self._expires = datetime_from_utctimestamp(value, units=1)
423 elif isinstance(value, str):
424 self._expires = Cookie.parse_datetime(value)
425 else:
426 raise TypeError('value must be datetime, int, long, float, basestring or None, not %s' % \
427 value.__class__.__name__)
428
429 @property
430 def max_age(self):
431 '''
432 The lifetime duration of the cookie. Computed as an offset
433 from the cookie's timestamp.
434 '''
435 return self._max_age
436
437 @max_age.setter
438 def max_age(self, value):
439 if value is None:
440 self._max_age = None
441 else:
442 try:
443 self._max_age = int(value)
444 except Exception:
445 raise ValueError("Max-Age value '%s' not convertable to integer" % value)
446
447 def __set_attr(self, name, value): # pylint: disable=unused-private-member
448 '''
449 Sets one of the predefined cookie attributes.
450 '''
451 attr_name = Cookie.attrs.get(name.lower(), None)
452 if attr_name is None:
453 raise ValueError("unknown cookie attribute '%s'" % name)
454 setattr(self, attr_name, value)
455
456 def __str__(self):
457 components = []
458
459 components.append("%s=%s" % (self.key, self.value))
460
461 if self.domain is not None:
462 components.append("Domain=%s" % self.domain)
463
464 if self.path is not None:
465 components.append("Path=%s" % self.path)
466
467 if self.max_age is not None:
468 components.append("Max-Age=%s" % self.max_age)
469
470 if self.expires is not None:
471 components.append("Expires=%s" % Cookie.datetime_to_string(self.expires))
472
473 if self.secure:
474 components.append("Secure")
475
476 if self.httponly:
477 components.append("HttpOnly")
478
479 return '; '.join(components)
480
481 def get_expiration(self):
482 '''
483 Return the effective expiration of the cookie as a datetime
484 object or None if no expiration is defined. Expiration may be
485 defined either by the "Expires" timestamp attribute or the
486 "Max-Age" duration attribute. If both are set "Max-Age" takes
487 precedence. If neither is set the cookie has no expiration and
488 None will be returned.
489
490 "Max-Age" specifies the number of seconds in the future from when the
491 cookie is received until it expires. Effectively it means
492 adding "Max-Age" seconds to a timestamp to arrive at an
493 expiration. By default the timestamp used to mark the arrival
494 of the cookie is set to the moment the cookie object is
495 created. However sometimes it is desirable to adjust the
496 received timestamp to something other than the moment of
497 object creation, therefore you can explicitly set the arrival
498 timestamp used in the "Max-Age" calculation.
499
500 "Expires" specifies an explicit timestamp.
501
502 If "Max-Age" is set a datetime object is returned which is the
503 sum of the arrival timestamp and "Max-Age".
504
505 If "Expires" is set a datetime object is returned matching the
506 timestamp specified as the "Expires" value.
507
508 If neither is set None is returned.
509 '''
510
511 if self.max_age is not None:
512 return self.timestamp + datetime.timedelta(seconds=self.max_age)
513
514 if self.expires is not None:
515 return self.expires
516
517 return None
518
519 def normalize_expiration(self):
520 '''
521 An expiration may be specified either with an explicit
522 timestamp in the "Expires" attribute or via an offset
523 specified witht the "Max-Age" attribute. The "Max-Age"
524 attribute has precedence over "Expires" if both are
525 specified.
526
527 This method normalizes the expiration of the cookie such that
528 only a "Expires" attribute remains after consideration of the
529 "Max-Age" attribute. This is useful when storing the cookie
530 for future reference.
531 '''
532
533 self.expires = self.get_expiration()
534 self.max_age = None
535 return self.expires
536
537 def set_defaults_from_url(self, url):
538 '''
539 If cookie domain and path attributes are not specified then
540 they assume defaults from the request url the cookie was
541 received from.
542 '''
543
544 _scheme, domain, path, _params, _query, _fragment = urlparse(url)
545
546 if self.domain is None:
547 self.domain = domain.lower()
548
549 if self.path is None:
550 self.path = self.normalize_url_path(path)
551
552
553 def normalize(self, url):
554 '''
555 Missing cookie attributes will receive default values derived
556 from the request URL. The expiration value is normalized.
557 '''
558
559 self.set_defaults_from_url(url)
560 self.normalize_expiration()
561
562 def http_cookie(self):
563 '''
564 Return a string with just the key and value (no attributes).
565 This is appropriate for including in a HTTP Cookie header.
566 '''
567 return '%s=%s;' % (self.key, self.value)
568
569 def http_return_ok(self, url):
570 '''
571 Tests to see if a cookie should be returned when a request is
572 sent to a specific URL.
573
574 * The request url's host must match the cookie's doman
575 otherwise raises Cookie.URLMismatch.
576
577 * The path in the request url must contain the cookie's path
578 otherwise raises Cookie.URLMismatch.
579
580 * If the cookie defines an expiration date then the current
581 time must be less or equal to the cookie's expiration
582 timestamp. Will raise Cookie.Expired if a defined expiration
583 is not valid.
584
585 If the test fails Cookie.Expired or Cookie.URLMismatch will be raised,
586 otherwise True is returned.
587
588 '''
589
590 def domain_valid(url_domain, cookie_domain):
591 '''
592 Compute domain component and perform test per
593 RFC 6265, Section 5.1.3. "Domain Matching"
594 '''
595 # FIXME: At the moment we can't import from ipalib at the
596 # module level because of a dependency loop (cycle) in the
597 # import. Our module layout needs to be refactored.
598 # pylint: disable=ipa-forbidden-import
599 from ipalib.util import validate_domain_name
600 # pylint: enable=ipa-forbidden-import
601 try:
602 validate_domain_name(url_domain)
603 except Exception:
604 return False
605
606 if cookie_domain is None:
607 return True
608
609 url_domain = url_domain.lower()
610 cookie_domain = cookie_domain.lower()
611
612 if url_domain == cookie_domain:
613 return True
614
615 if url_domain.endswith(cookie_domain):
616 if cookie_domain.startswith('.'):
617 return True
618
619 return False
620
621 def path_valid(url_path, cookie_path):
622 '''
623 Compute path component and perform test per
624 RFC 6265, Section 5.1.4. "Paths and Path-Match"
625 '''
626
627 if cookie_path is None:
628 return True
629
630 cookie_path = cookie_path.lower()
631 request_path = self.normalize_url_path(url_path)
632
633 if cookie_path == request_path:
634 return True
635
636 if cookie_path and request_path.startswith(cookie_path):
637 if cookie_path.endswith('/'):
638 return True
639
640 tail = request_path[len(cookie_path):]
641 if tail.startswith('/'):
642 return True
643
644 return False
645
646 cookie_name = self.key
647
648 (
649 url_scheme, url_domain, url_path,
650 _url_params, _url_query, _url_fragment
651 ) = urlparse(url)
652
653 cookie_expiration = self.get_expiration()
654 if cookie_expiration is not None:
655 now = datetime.datetime.now(tz=datetime.timezone.utc)
656 if cookie_expiration < now:
657 raise Cookie.Expired("cookie named '%s'; expired at %s'" % \
658 (cookie_name,
659 self.datetime_to_string(cookie_expiration)))
660
661 if not domain_valid(url_domain, self.domain):
662 raise Cookie.URLMismatch("cookie named '%s'; it's domain '%s' does not match URL domain '%s'" % \
663 (cookie_name, self.domain, url_domain))
664
665 if not path_valid(url_path, self.path):
666 raise Cookie.URLMismatch("cookie named '%s'; it's path '%s' does not contain the URL path '%s'" % \
667 (cookie_name, self.path, url_path))
668
669 url_scheme = url_scheme.lower()
670
671 if self.httponly:
672 if url_scheme not in ('http', 'https'):
673 raise Cookie.URLMismatch("cookie named '%s'; is restricted to HTTP but it's URL scheme is '%s'" % \
674 (cookie_name, url_scheme))
675
676 if self.secure:
677 if url_scheme not in ('https',):
678 raise Cookie.URLMismatch("cookie named '%s'; is restricted to secure transport but it's URL scheme is '%s'" % \
679 (cookie_name, url_scheme))
680
681
682 return True