cookies.py 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169
  1. """Parse, manipulate and render cookies in a convenient way.
  2. Copyright (c) 2011-2014, Sasha Hart.
  3. Permission is hereby granted, free of charge, to any person obtaining a copy of
  4. this software and associated documentation files (the "Software"), to deal in
  5. the Software without restriction, including without limitation the rights to
  6. use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  7. of the Software, and to permit persons to whom the Software is furnished to do
  8. so, subject to the following conditions:
  9. The above copyright notice and this permission notice shall be included in all
  10. copies or substantial portions of the Software.
  11. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  12. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  13. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  14. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  15. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  17. SOFTWARE.
  18. """
  19. __version__ = "2.2.1"
  20. import re
  21. import datetime
  22. import logging
  23. import sys
  24. from unicodedata import normalize
  25. if sys.version_info >= (3, 0, 0): # pragma: no cover
  26. from urllib.parse import (
  27. quote as _default_quote, unquote as _default_unquote)
  28. basestring = str
  29. long = int
  30. else: # pragma: no cover
  31. from urllib import (
  32. quote as _default_quote, unquote as _default_unquote)
  33. def _total_seconds(td):
  34. """Wrapper to work around lack of .total_seconds() method in Python 3.1.
  35. """
  36. if hasattr(td, "total_seconds"):
  37. return td.total_seconds()
  38. return td.days * 3600 * 24 + td.seconds + td.microseconds / 100000.0
  39. # see test_encoding_assumptions for how these magical safe= parms were figured
  40. # out. the differences are because of what cookie-octet may contain
  41. # vs the more liberal spec for extension-av
  42. default_cookie_quote = lambda item: _default_quote(
  43. item, safe='!#$%&\'()*+/:<=>?@[]^`{|}~')
  44. default_extension_quote = lambda item: _default_quote(
  45. item, safe=' !"#$%&\'()*+,/:<=>?@[\\]^`{|}~')
  46. default_unquote = _default_unquote
  47. def _report_invalid_cookie(data):
  48. "How this module logs a bad cookie when exception suppressed"
  49. logging.error("invalid Cookie: %r", data)
  50. def _report_unknown_attribute(name):
  51. "How this module logs an unknown attribute when exception suppressed"
  52. logging.error("unknown Cookie attribute: %r", name)
  53. def _report_invalid_attribute(name, value, reason):
  54. "How this module logs a bad attribute when exception suppressed"
  55. logging.error("invalid Cookie attribute (%s): %r=%r", reason, name, value)
  56. class CookieError(Exception):
  57. """Base class for this module's exceptions, so you can catch them all if
  58. you want to.
  59. """
  60. def __init__(self):
  61. Exception.__init__(self)
  62. class InvalidCookieError(CookieError):
  63. """Raised when attempting to parse or construct a cookie which is
  64. syntactically invalid (in any way that has possibly serious implications).
  65. """
  66. def __init__(self, data=None, message=""):
  67. CookieError.__init__(self)
  68. self.data = data
  69. self.message = message
  70. def __str__(self):
  71. return '%r %r' % (self.message, self.data)
  72. class InvalidCookieAttributeError(CookieError):
  73. """Raised when setting an invalid attribute on a Cookie.
  74. """
  75. def __init__(self, name, value, reason=None):
  76. CookieError.__init__(self)
  77. self.name = name
  78. self.value = value
  79. self.reason = reason
  80. def __str__(self):
  81. prefix = ("%s: " % self.reason) if self.reason else ""
  82. if self.name is None:
  83. return '%s%r' % (prefix, self.value)
  84. return '%s%r = %r' % (prefix, self.name, self.value)
  85. class Definitions(object):
  86. """Namespace to hold definitions used in cookie parsing (mostly pieces of
  87. regex).
  88. These are separated out for individual testing against examples and RFC
  89. grammar, and kept here to avoid cluttering other namespaces.
  90. """
  91. # Most of the following are set down or cited in RFC 6265 4.1.1
  92. # This is the grammar's 'cookie-name' defined as 'token' per RFC 2616 2.2.
  93. COOKIE_NAME = r"!#$%&'*+\-.0-9A-Z^_`a-z|~"
  94. # 'cookie-octet' - as used twice in definition of 'cookie-value'
  95. COOKIE_OCTET = r"\x21\x23-\x2B\--\x3A\x3C-\x5B\]-\x7E"
  96. # extension-av - also happens to be a superset of cookie-av and path-value
  97. EXTENSION_AV = """ !"#$%&\\\\'()*+,\-./0-9:<=>?@A-Z[\\]^_`a-z{|}~"""
  98. # This is for the first pass parse on a Set-Cookie: response header. It
  99. # includes cookie-value, cookie-pair, set-cookie-string, cookie-av.
  100. # extension-av is used to extract the chunk containing variable-length,
  101. # unordered attributes. The second pass then uses ATTR to break out each
  102. # attribute and extract it appropriately.
  103. # As compared with the RFC production grammar, it is must more liberal with
  104. # space characters, in order not to break on data made by barbarians.
  105. SET_COOKIE_HEADER = """(?x) # Verbose mode
  106. ^(?:Set-Cookie:[ ]*)?
  107. (?P<name>[{name}:]+)
  108. [ ]*=[ ]*
  109. # Accept anything in quotes - this is not RFC 6265, but might ease
  110. # working with older code that half-heartedly works with 2965. Accept
  111. # spaces inside tokens up front, so we can deal with that error one
  112. # cookie at a time, after this first pass.
  113. (?P<value>(?:"{value}*")|(?:[{cookie_octet} ]*))
  114. [ ]*
  115. # Extract everything up to the end in one chunk, which will be broken
  116. # down in the second pass. Don't match if there's any unexpected
  117. # garbage at the end (hence the \Z; $ matches before newline).
  118. (?P<attrs>(?:;[ ]*[{cookie_av}]+)*)
  119. """.format(name=COOKIE_NAME, cookie_av=EXTENSION_AV + ";",
  120. cookie_octet=COOKIE_OCTET, value="[^;]")
  121. # Now we specify the individual patterns for the attribute extraction pass
  122. # of Set-Cookie parsing (mapping to *-av in the RFC grammar). Things which
  123. # don't match any of these but are in extension-av are simply ignored;
  124. # anything else should be rejected in the first pass (SET_COOKIE_HEADER).
  125. # Max-Age attribute. These are digits, they are expressed this way
  126. # because that is how they are expressed in the RFC.
  127. MAX_AGE_AV = "Max-Age=(?P<max_age>[\x30-\x39]+)"
  128. # Domain attribute; a label is one part of the domain
  129. LABEL = '{let_dig}(?:(?:{let_dig_hyp}+)?{let_dig})?'.format(
  130. let_dig="[A-Za-z0-9]", let_dig_hyp="[0-9A-Za-z\-]")
  131. DOMAIN = "\.?(?:{label}\.)*(?:{label})".format(label=LABEL)
  132. # Parse initial period though it's wrong, as RFC 6265 4.1.2.3
  133. DOMAIN_AV = "Domain=(?P<domain>{domain})".format(domain=DOMAIN)
  134. # Path attribute. We don't take special care with quotes because
  135. # they are hardly used, they don't allow invalid characters per RFC 6265,
  136. # and " is a valid character to occur in a path value anyway.
  137. PATH_AV = 'Path=(?P<path>[%s]+)' % EXTENSION_AV
  138. # Expires attribute. This gets big because of date parsing, which needs to
  139. # support a large range of formats, so it's broken down into pieces.
  140. # Generate a mapping of months to use in render/parse, to avoid
  141. # localizations which might be produced by strftime (e.g. %a -> Mayo)
  142. month_list = ["January", "February", "March", "April", "May", "June",
  143. "July", "August", "September", "October", "November",
  144. "December"]
  145. month_abbr_list = [item[:3] for item in month_list]
  146. month_numbers = {}
  147. for index, name in enumerate(month_list):
  148. name = name.lower()
  149. month_numbers[name[:3]] = index + 1
  150. month_numbers[name] = index + 1
  151. # Use the same list to create regexps for months.
  152. MONTH_SHORT = "(?:" + "|".join(item[:3] for item in month_list) + ")"
  153. MONTH_LONG = "(?:" + "|".join(item for item in month_list) + ")"
  154. # Same drill with weekdays, for the same reason.
  155. weekday_list = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
  156. "Saturday", "Sunday"]
  157. weekday_abbr_list = [item[:3] for item in weekday_list]
  158. WEEKDAY_SHORT = "(?:" + "|".join(item[:3] for item in weekday_list) + ")"
  159. WEEKDAY_LONG = "(?:" + "|".join(item for item in weekday_list) + ")"
  160. # This regexp tries to exclude obvious nonsense in the first pass.
  161. DAY_OF_MONTH = "(?:[0 ]?[1-9]|[12][0-9]|[3][01])(?!\d)"
  162. # Here is the overall date format; ~99% of cases fold into one generalized
  163. # syntax like RFC 1123, and many of the rest use asctime-like formats.
  164. # (see test_date_formats for a full exegesis)
  165. DATE = """(?ix) # Case-insensitive mode, verbose mode
  166. (?:
  167. (?P<weekday>(?:{wdy}|{weekday}),[ ])?
  168. (?P<day>{day})
  169. [ \-]
  170. (?P<month>{mon}|{month})
  171. [ \-]
  172. # This does not support 3-digit years, which are rare and don't
  173. # seem to have one canonical interpretation.
  174. (?P<year>(?:\d{{2}}|\d{{4}}))
  175. [ ]
  176. # HH:MM[:SS] GMT
  177. (?P<hour>(?:[ 0][0-9]|[01][0-9]|2[0-3]))
  178. :(?P<minute>(?:0[0-9]|[1-5][0-9]))
  179. (?::(?P<second>\d{{2}}))?
  180. [ ]GMT
  181. |
  182. # Support asctime format, e.g. 'Sun Nov 6 08:49:37 1994'
  183. (?P<weekday2>{wdy})[ ]
  184. (?P<month2>{mon})[ ]
  185. (?P<day2>[ ]\d|\d\d)[ ]
  186. (?P<hour2>\d\d):
  187. (?P<minute2>\d\d)
  188. (?::(?P<second2>\d\d)?)[ ]
  189. (?P<year2>\d\d\d\d)
  190. (?:[ ]GMT)? # GMT (Amazon)
  191. )
  192. """
  193. DATE = DATE.format(wdy=WEEKDAY_SHORT, weekday=WEEKDAY_LONG,
  194. day=DAY_OF_MONTH, mon=MONTH_SHORT, month=MONTH_LONG)
  195. EXPIRES_AV = "Expires=(?P<expires>%s)" % DATE
  196. # Now we're ready to define a regexp which can match any number of attrs
  197. # in the variable portion of the Set-Cookie header (like the unnamed latter
  198. # part of set-cookie-string in the grammar). Each regexp of any complexity
  199. # is split out for testing by itself.
  200. ATTR = """(?ix) # Case-insensitive mode, verbose mode
  201. # Always start with start or semicolon and any number of spaces
  202. (?:^|;)[ ]*(?:
  203. # Big disjunction of attribute patterns (*_AV), with named capture
  204. # groups to extract everything in one pass. Anything unrecognized
  205. # goes in the 'unrecognized' capture group for reporting.
  206. {expires}
  207. |{max_age}
  208. |{domain}
  209. |{path}
  210. |(?P<secure>Secure=?)
  211. |(?P<httponly>HttpOnly=?)
  212. |Version=(?P<version>[{stuff}]+)
  213. |Comment=(?P<comment>[{stuff}]+)
  214. |(?P<unrecognized>[{stuff}]+)
  215. )
  216. # End with any number of spaces not matched by the preceding (up to the
  217. # next semicolon) - but do not capture these.
  218. [ ]*
  219. """.format(expires=EXPIRES_AV, max_age=MAX_AGE_AV, domain=DOMAIN_AV,
  220. path=PATH_AV, stuff=EXTENSION_AV)
  221. # For request data ("Cookie: ") parsing, with finditer cf. RFC 6265 4.2.1
  222. COOKIE = """(?x) # Verbose mode
  223. (?: # Either something close to valid...
  224. # Match starts at start of string, or at separator.
  225. # Split on comma for the sake of legacy code (RFC 2109/2965),
  226. # and since it only breaks when invalid commas are put in values.
  227. # see http://bugs.python.org/issue1210326
  228. (?:^Cookie:|^|;|,)
  229. # 1 or more valid token characters making up the name (captured)
  230. # with colon added to accommodate users of some old Java apps, etc.
  231. [ ]*
  232. (?P<name>[{name}:]+)
  233. [ ]*
  234. =
  235. [ ]*
  236. # While 6265 provides only for cookie-octet, this allows just about
  237. # anything in quotes (like in RFC 2616); people stuck on RFC
  238. # 2109/2965 will expect it to work this way. The non-quoted token
  239. # allows interior spaces ('\x20'), which is not valid. In both
  240. # cases, the decision of whether to allow these is downstream.
  241. (?P<value>
  242. ["][^\00-\31"]*["]
  243. |
  244. [{value}]
  245. |
  246. [{value}][{value} ]*[{value}]+
  247. |
  248. )
  249. # ... Or something way off-spec - extract to report and move on
  250. |
  251. (?P<invalid>[^;]+)
  252. )
  253. # Trailing spaces after value
  254. [ ]*
  255. # Must end with ; or be at end of string (don't consume this though,
  256. # so use the lookahead assertion ?=
  257. (?=;|\Z)
  258. """.format(name=COOKIE_NAME, value=COOKIE_OCTET)
  259. # Precompile externally useful definitions into re objects.
  260. COOKIE_NAME_RE = re.compile("^([%s:]+)\Z" % COOKIE_NAME)
  261. COOKIE_RE = re.compile(COOKIE)
  262. SET_COOKIE_HEADER_RE = re.compile(SET_COOKIE_HEADER)
  263. ATTR_RE = re.compile(ATTR)
  264. DATE_RE = re.compile(DATE)
  265. DOMAIN_RE = re.compile(DOMAIN)
  266. PATH_RE = re.compile('^([%s]+)\Z' % EXTENSION_AV)
  267. EOL = re.compile("(?:\r\n|\n)")
  268. def strip_spaces_and_quotes(value):
  269. """Remove invalid whitespace and/or single pair of dquotes and return None
  270. for empty strings.
  271. Used to prepare cookie values, path, and domain attributes in a way which
  272. tolerates simple formatting mistakes and standards variations.
  273. """
  274. value = value.strip() if value else ""
  275. if value and len(value) > 1 and (value[0] == value[-1] == '"'):
  276. value = value[1:-1]
  277. if not value:
  278. value = ""
  279. return value
  280. def parse_string(data, unquote=default_unquote):
  281. """Decode URL-encoded strings to UTF-8 containing the escaped chars.
  282. """
  283. if data is None:
  284. return None
  285. # We'll soon need to unquote to recover our UTF-8 data.
  286. # In Python 2, unquote crashes on chars beyond ASCII. So encode functions
  287. # had better not include anything beyond ASCII in data.
  288. # In Python 3, unquote crashes on bytes objects, requiring conversion to
  289. # str objects (unicode) using decode().
  290. # But in Python 2, the same decode causes unquote to butcher the data.
  291. # So in that case, just leave the bytes.
  292. if isinstance(data, bytes):
  293. if sys.version_info > (3, 0, 0): # pragma: no cover
  294. data = data.decode('ascii')
  295. # Recover URL encoded data
  296. unquoted = unquote(data)
  297. # Without this step, Python 2 may have good URL decoded *bytes*,
  298. # which will therefore not normalize as unicode and not compare to
  299. # the original.
  300. if isinstance(unquoted, bytes):
  301. unquoted = unquoted.decode('utf-8')
  302. return unquoted
  303. def parse_date(value):
  304. """Parse an RFC 1123 or asctime-like format date string to produce
  305. a Python datetime object (without a timezone).
  306. """
  307. # Do the regex magic; also enforces 2 or 4 digit years
  308. match = Definitions.DATE_RE.match(value) if value else None
  309. if not match:
  310. return None
  311. # We're going to extract and prepare captured data in 'data'.
  312. data = {}
  313. captured = match.groupdict()
  314. fields = ['year', 'month', 'day', 'hour', 'minute', 'second']
  315. # If we matched on the RFC 1123 family format
  316. if captured['year']:
  317. for field in fields:
  318. data[field] = captured[field]
  319. # If we matched on the asctime format, use year2 etc.
  320. else:
  321. for field in fields:
  322. data[field] = captured[field + "2"]
  323. year = data['year']
  324. # Interpret lame 2-digit years - base the cutoff on UNIX epoch, in case
  325. # someone sets a '70' cookie meaning 'distant past'. This won't break for
  326. # 58 years and people who use 2-digit years are asking for it anyway.
  327. if len(year) == 2:
  328. if int(year) < 70:
  329. year = "20" + year
  330. else:
  331. year = "19" + year
  332. year = int(year)
  333. # Clamp to [1900, 9999]: strftime has min 1900, datetime has max 9999
  334. data['year'] = max(1900, min(year, 9999))
  335. # Other things which are numbers should convert to integer
  336. for field in ['day', 'hour', 'minute', 'second']:
  337. if data[field] is None:
  338. data[field] = 0
  339. data[field] = int(data[field])
  340. # Look up the number datetime needs for the named month
  341. data['month'] = Definitions.month_numbers[data['month'].lower()]
  342. return datetime.datetime(**data)
  343. def parse_domain(value):
  344. """Parse and validate an incoming Domain attribute value.
  345. """
  346. value = strip_spaces_and_quotes(value)
  347. if value:
  348. assert valid_domain(value)
  349. return value
  350. def parse_path(value):
  351. """Parse and validate an incoming Path attribute value.
  352. """
  353. value = strip_spaces_and_quotes(value)
  354. assert valid_path(value)
  355. return value
  356. def parse_value(value, allow_spaces=True, unquote=default_unquote):
  357. "Process a cookie value"
  358. if value is None:
  359. return None
  360. value = strip_spaces_and_quotes(value)
  361. value = parse_string(value, unquote=unquote)
  362. if not allow_spaces:
  363. assert ' ' not in value
  364. return value
  365. def valid_name(name):
  366. "Validate a cookie name string"
  367. if isinstance(name, bytes):
  368. name = name.decode('ascii')
  369. if not Definitions.COOKIE_NAME_RE.match(name):
  370. return False
  371. # This module doesn't support $identifiers, which are part of an obsolete
  372. # and highly complex standard which is never used.
  373. if name[0] == "$":
  374. return False
  375. return True
  376. def valid_value(value, quote=default_cookie_quote, unquote=default_unquote):
  377. """Validate a cookie value string.
  378. This is generic across quote/unquote functions because it directly verifies
  379. the encoding round-trip using the specified quote/unquote functions.
  380. So if you use different quote/unquote functions, use something like this
  381. as a replacement for valid_value::
  382. my_valid_value = lambda value: valid_value(value, quote=my_quote,
  383. unquote=my_unquote)
  384. """
  385. if value is None:
  386. return False
  387. # Put the value through a round trip with the given quote and unquote
  388. # functions, so we will know whether data will get lost or not in the event
  389. # that we don't complain.
  390. encoded = encode_cookie_value(value, quote=quote)
  391. decoded = parse_string(encoded, unquote=unquote)
  392. # If the original string made the round trip, this is a valid value for the
  393. # given quote and unquote functions. Since the round trip can generate
  394. # different unicode forms, normalize before comparing, so we can ignore
  395. # trivial inequalities.
  396. decoded_normalized = (normalize("NFKD", decoded)
  397. if not isinstance(decoded, bytes) else decoded)
  398. value_normalized = (normalize("NFKD", value)
  399. if not isinstance(value, bytes) else value)
  400. if decoded_normalized == value_normalized:
  401. return True
  402. return False
  403. def valid_date(date):
  404. "Validate an expires datetime object"
  405. # We want something that acts like a datetime. In particular,
  406. # strings indicate a failure to parse down to an object and ints are
  407. # nonstandard and ambiguous at best.
  408. if not hasattr(date, 'tzinfo'):
  409. return False
  410. # Relevant RFCs define UTC as 'close enough' to GMT, and the maximum
  411. # difference between UTC and GMT is often stated to be less than a second.
  412. if date.tzinfo is None or _total_seconds(date.utcoffset()) < 1.1:
  413. return True
  414. return False
  415. def valid_domain(domain):
  416. "Validate a cookie domain ASCII string"
  417. # Using encoding on domain would confuse browsers into not sending cookies.
  418. # Generate UnicodeDecodeError up front if it can't store as ASCII.
  419. domain.encode('ascii')
  420. # Domains starting with periods are not RFC-valid, but this is very common
  421. # in existing cookies, so they should still parse with DOMAIN_AV.
  422. if Definitions.DOMAIN_RE.match(domain):
  423. return True
  424. return False
  425. def valid_path(value):
  426. "Validate a cookie path ASCII string"
  427. # Generate UnicodeDecodeError if path can't store as ASCII.
  428. value.encode("ascii")
  429. # Cookies without leading slash will likely be ignored, raise ASAP.
  430. if not (value and value[0] == "/"):
  431. return False
  432. if not Definitions.PATH_RE.match(value):
  433. return False
  434. return True
  435. def valid_max_age(number):
  436. "Validate a cookie Max-Age"
  437. if isinstance(number, basestring):
  438. try:
  439. number = long(number)
  440. except (ValueError, TypeError):
  441. return False
  442. if number >= 0 and number % 1 == 0:
  443. return True
  444. return False
  445. def encode_cookie_value(data, quote=default_cookie_quote):
  446. """URL-encode strings to make them safe for a cookie value.
  447. By default this uses urllib quoting, as used in many other cookie
  448. implementations and in other Python code, instead of an ad hoc escaping
  449. mechanism which includes backslashes (these also being illegal chars in RFC
  450. 6265).
  451. """
  452. if data is None:
  453. return None
  454. # encode() to ASCII bytes so quote won't crash on non-ASCII.
  455. # but doing that to bytes objects is nonsense.
  456. # On Python 2 encode crashes if s is bytes containing non-ASCII.
  457. # On Python 3 encode crashes on all byte objects.
  458. if not isinstance(data, bytes):
  459. data = data.encode("utf-8")
  460. # URL encode data so it is safe for cookie value
  461. quoted = quote(data)
  462. # Don't force to bytes, so that downstream can use proper string API rather
  463. # than crippled bytes, and to encourage encoding to be done just once.
  464. return quoted
  465. def encode_extension_av(data, quote=default_extension_quote):
  466. """URL-encode strings to make them safe for an extension-av
  467. (extension attribute value): <any CHAR except CTLs or ";">
  468. """
  469. if not data:
  470. return ''
  471. return quote(data)
  472. def render_date(date):
  473. """Render a date (e.g. an Expires value) per RFCs 6265/2616/1123.
  474. Don't give this localized (timezone-aware) datetimes. If you use them,
  475. convert them to GMT before passing them to this. There are too many
  476. conversion corner cases to handle this universally.
  477. """
  478. if not date:
  479. return None
  480. assert valid_date(date)
  481. # Avoid %a and %b, which can change with locale, breaking compliance
  482. weekday = Definitions.weekday_abbr_list[date.weekday()]
  483. month = Definitions.month_abbr_list[date.month - 1]
  484. return date.strftime("{day}, %d {month} %Y %H:%M:%S GMT"
  485. ).format(day=weekday, month=month)
  486. def render_domain(domain):
  487. if not domain:
  488. return None
  489. if domain[0] == '.':
  490. return domain[1:]
  491. return domain
  492. def _parse_request(header_data, ignore_bad_cookies=False):
  493. """Turn one or more lines of 'Cookie:' header data into a dict mapping
  494. cookie names to cookie values (raw strings).
  495. """
  496. cookies_dict = {}
  497. for line in Definitions.EOL.split(header_data.strip()):
  498. matches = Definitions.COOKIE_RE.finditer(line)
  499. matches = [item for item in matches]
  500. for match in matches:
  501. invalid = match.group('invalid')
  502. if invalid:
  503. if not ignore_bad_cookies:
  504. raise InvalidCookieError(data=invalid)
  505. _report_invalid_cookie(invalid)
  506. continue
  507. name = match.group('name')
  508. values = cookies_dict.get(name)
  509. value = match.group('value').strip('"')
  510. if values:
  511. values.append(value)
  512. else:
  513. cookies_dict[name] = [value]
  514. if not matches:
  515. if not ignore_bad_cookies:
  516. raise InvalidCookieError(data=line)
  517. _report_invalid_cookie(line)
  518. return cookies_dict
  519. def parse_one_response(line, ignore_bad_cookies=False,
  520. ignore_bad_attributes=True):
  521. """Turn one 'Set-Cookie:' line into a dict mapping attribute names to
  522. attribute values (raw strings).
  523. """
  524. cookie_dict = {}
  525. # Basic validation, extract name/value/attrs-chunk
  526. match = Definitions.SET_COOKIE_HEADER_RE.match(line)
  527. if not match:
  528. if not ignore_bad_cookies:
  529. raise InvalidCookieError(data=line)
  530. _report_invalid_cookie(line)
  531. return None
  532. cookie_dict.update({
  533. 'name': match.group('name'),
  534. 'value': match.group('value')})
  535. # Extract individual attrs from the attrs chunk
  536. for match in Definitions.ATTR_RE.finditer(match.group('attrs')):
  537. captured = dict((k, v) for (k, v) in match.groupdict().items() if v)
  538. unrecognized = captured.get('unrecognized', None)
  539. if unrecognized:
  540. if not ignore_bad_attributes:
  541. raise InvalidCookieAttributeError(None, unrecognized,
  542. "unrecognized")
  543. _report_unknown_attribute(unrecognized)
  544. continue
  545. # for unary flags
  546. for key in ('secure', 'httponly'):
  547. if captured.get(key):
  548. captured[key] = True
  549. # ignore subcomponents of expires - they're still there to avoid doing
  550. # two passes
  551. timekeys = ('weekday', 'month', 'day', 'hour', 'minute', 'second',
  552. 'year')
  553. if 'year' in captured:
  554. for key in timekeys:
  555. del captured[key]
  556. elif 'year2' in captured:
  557. for key in timekeys:
  558. del captured[key + "2"]
  559. cookie_dict.update(captured)
  560. return cookie_dict
  561. def _parse_response(header_data, ignore_bad_cookies=False,
  562. ignore_bad_attributes=True):
  563. """Turn one or more lines of 'Set-Cookie:' header data into a list of dicts
  564. mapping attribute names to attribute values (as plain strings).
  565. """
  566. cookie_dicts = []
  567. for line in Definitions.EOL.split(header_data.strip()):
  568. if not line:
  569. break
  570. cookie_dict = parse_one_response(
  571. line, ignore_bad_cookies=ignore_bad_cookies,
  572. ignore_bad_attributes=ignore_bad_attributes)
  573. if not cookie_dict:
  574. continue
  575. cookie_dicts.append(cookie_dict)
  576. if not cookie_dicts:
  577. if not ignore_bad_cookies:
  578. raise InvalidCookieError(data=header_data)
  579. _report_invalid_cookie(header_data)
  580. return cookie_dicts
  581. class Cookie(object):
  582. """Provide a simple interface for creating, modifying, and rendering
  583. individual HTTP cookies.
  584. Cookie attributes are represented as normal Python object attributes.
  585. Parsing, rendering and validation are reconfigurable per-attribute. The
  586. default behavior is intended to comply with RFC 6265, URL-encoding illegal
  587. characters where necessary. For example: the default behavior for the
  588. Expires attribute is to parse strings as datetimes using parse_date,
  589. validate that any set value is a datetime, and render the attribute per the
  590. preferred date format in RFC 1123.
  591. """
  592. def __init__(self, name, value, **kwargs):
  593. # If we don't have or can't set a name value, we don't want to return
  594. # junk, so we must break control flow. And we don't want to use
  595. # InvalidCookieAttributeError, because users may want to catch that to
  596. # suppress all complaining about funky attributes.
  597. try:
  598. self.name = name
  599. except InvalidCookieAttributeError:
  600. raise InvalidCookieError(message="invalid name for new Cookie",
  601. data=name)
  602. value = value or ''
  603. try:
  604. self.value = value
  605. except InvalidCookieAttributeError:
  606. raise InvalidCookieError(message="invalid value for new Cookie",
  607. data=value)
  608. if kwargs:
  609. self._set_attributes(kwargs, ignore_bad_attributes=False)
  610. def _set_attributes(self, attrs, ignore_bad_attributes=False):
  611. for attr_name, attr_value in attrs.items():
  612. if not attr_name in self.attribute_names:
  613. if not ignore_bad_attributes:
  614. raise InvalidCookieAttributeError(
  615. attr_name, attr_value,
  616. "unknown cookie attribute '%s'" % attr_name)
  617. _report_unknown_attribute(attr_name)
  618. try:
  619. setattr(self, attr_name, attr_value)
  620. except InvalidCookieAttributeError as error:
  621. if not ignore_bad_attributes:
  622. raise
  623. _report_invalid_attribute(attr_name, attr_value, error.reason)
  624. continue
  625. @classmethod
  626. def from_dict(cls, cookie_dict, ignore_bad_attributes=True):
  627. """Construct an instance from a dict of strings to parse.
  628. The main difference between this and Cookie(name, value, **kwargs) is
  629. that the values in the argument to this method are parsed.
  630. If ignore_bad_attributes=True (default), values which did not parse
  631. are set to '' in order to avoid passing bad data.
  632. """
  633. name = cookie_dict.get('name', None)
  634. if not name:
  635. raise InvalidCookieError("Cookie must have name")
  636. raw_value = cookie_dict.get('value', '')
  637. # Absence or failure of parser here is fatal; errors in present name
  638. # and value should be found by Cookie.__init__.
  639. value = cls.attribute_parsers['value'](raw_value)
  640. cookie = cls(name, value)
  641. # Parse values from serialized formats into objects
  642. parsed = {}
  643. for key, value in cookie_dict.items():
  644. # Don't want to pass name/value to _set_attributes
  645. if key in ('name', 'value'):
  646. continue
  647. parser = cls.attribute_parsers.get(key)
  648. if not parser:
  649. # Don't let totally unknown attributes pass silently
  650. if not ignore_bad_attributes:
  651. raise InvalidCookieAttributeError(
  652. key, value, "unknown cookie attribute '%s'" % key)
  653. _report_unknown_attribute(key)
  654. continue
  655. try:
  656. parsed_value = parser(value)
  657. except Exception as e:
  658. reason = "did not parse with %r: %r" % (parser, e)
  659. if not ignore_bad_attributes:
  660. raise InvalidCookieAttributeError(
  661. key, value, reason)
  662. _report_invalid_attribute(key, value, reason)
  663. parsed_value = ''
  664. parsed[key] = parsed_value
  665. # Set the parsed objects (does object validation automatically)
  666. cookie._set_attributes(parsed, ignore_bad_attributes)
  667. return cookie
  668. @classmethod
  669. def from_string(cls, line, ignore_bad_cookies=False,
  670. ignore_bad_attributes=True):
  671. "Construct a Cookie object from a line of Set-Cookie header data."
  672. cookie_dict = parse_one_response(
  673. line, ignore_bad_cookies=ignore_bad_cookies,
  674. ignore_bad_attributes=ignore_bad_attributes)
  675. if not cookie_dict:
  676. return None
  677. return cls.from_dict(
  678. cookie_dict, ignore_bad_attributes=ignore_bad_attributes)
  679. def to_dict(self):
  680. this_dict = {'name': self.name, 'value': self.value}
  681. this_dict.update(self.attributes())
  682. return this_dict
  683. def validate(self, name, value):
  684. """Validate a cookie attribute with an appropriate validator.
  685. The value comes in already parsed (for example, an expires value
  686. should be a datetime). Called automatically when an attribute
  687. value is set.
  688. """
  689. validator = self.attribute_validators.get(name, None)
  690. if validator:
  691. return True if validator(value) else False
  692. return True
  693. def __setattr__(self, name, value):
  694. """Attributes mentioned in attribute_names get validated using
  695. functions in attribute_validators, raising an exception on failure.
  696. Others get left alone.
  697. """
  698. if name in self.attribute_names or name in ("name", "value"):
  699. if name == 'name' and not value:
  700. raise InvalidCookieError(message="Cookies must have names")
  701. # Ignore None values indicating unset attr. Other invalids should
  702. # raise error so users of __setattr__ can learn.
  703. if value is not None:
  704. if not self.validate(name, value):
  705. raise InvalidCookieAttributeError(
  706. name, value, "did not validate with " +
  707. repr(self.attribute_validators.get(name)))
  708. object.__setattr__(self, name, value)
  709. def __getattr__(self, name):
  710. """Provide for acting like everything in attribute_names is
  711. automatically set to None, rather than having to do so explicitly and
  712. only at import time.
  713. """
  714. if name in self.attribute_names:
  715. return None
  716. raise AttributeError(name)
  717. def attributes(self):
  718. """Export this cookie's attributes as a dict of encoded values.
  719. This is an important part of the code for rendering attributes, e.g.
  720. render_response().
  721. """
  722. dictionary = {}
  723. # Only look for attributes registered in attribute_names.
  724. for python_attr_name, cookie_attr_name in self.attribute_names.items():
  725. value = getattr(self, python_attr_name)
  726. renderer = self.attribute_renderers.get(python_attr_name, None)
  727. if renderer:
  728. value = renderer(value)
  729. # If renderer returns None, or it's just natively none, then the
  730. # value is suppressed entirely - does not appear in any rendering.
  731. if not value:
  732. continue
  733. dictionary[cookie_attr_name] = value
  734. return dictionary
  735. def render_request(self):
  736. """Render as a string formatted for HTTP request headers
  737. (simple 'Cookie: ' style).
  738. """
  739. # Use whatever renderers are defined for name and value.
  740. name, value = self.name, self.value
  741. renderer = self.attribute_renderers.get('name', None)
  742. if renderer:
  743. name = renderer(name)
  744. renderer = self.attribute_renderers.get('value', None)
  745. if renderer:
  746. value = renderer(value)
  747. return ''.join((name, "=", value))
  748. def render_response(self):
  749. """Render as a string formatted for HTTP response headers
  750. (detailed 'Set-Cookie: ' style).
  751. """
  752. # Use whatever renderers are defined for name and value.
  753. # (.attributes() is responsible for all other rendering.)
  754. name, value = self.name, self.value
  755. renderer = self.attribute_renderers.get('name', None)
  756. if renderer:
  757. name = renderer(name)
  758. renderer = self.attribute_renderers.get('value', None)
  759. if renderer:
  760. value = renderer(value)
  761. return '; '.join(
  762. ['{0}={1}'.format(name, value)] +
  763. [key if isinstance(val, bool) else '='.join((key, val))
  764. for key, val in self.attributes().items()]
  765. )
  766. def __eq__(self, other):
  767. attrs = ['name', 'value'] + list(self.attribute_names.keys())
  768. for attr in attrs:
  769. mine = getattr(self, attr, None)
  770. his = getattr(other, attr, None)
  771. if isinstance(mine, bytes):
  772. mine = mine.decode('utf-8')
  773. if isinstance(his, bytes):
  774. his = his.decode('utf-8')
  775. if attr == 'domain':
  776. if mine and mine[0] == '.':
  777. mine = mine[1:]
  778. if his and his[0] == '.':
  779. his = his[1:]
  780. if mine != his:
  781. return False
  782. return True
  783. def __ne__(self, other):
  784. return not self.__eq__(other)
  785. # Add a name and its proper rendering to this dict to register an attribute
  786. # as exportable. The key is the name of the Cookie object attribute in
  787. # Python, and it is mapped to the name you want in the output.
  788. # 'name' and 'value' should not be here.
  789. attribute_names = {
  790. 'expires': 'Expires',
  791. 'max_age': 'Max-Age',
  792. 'domain': 'Domain',
  793. 'path': 'Path',
  794. 'comment': 'Comment',
  795. 'version': 'Version',
  796. 'secure': 'Secure',
  797. 'httponly': 'HttpOnly',
  798. }
  799. # Register single-parameter functions in this dictionary to have them
  800. # used for encoding outgoing values (e.g. as RFC compliant strings,
  801. # as base64, encrypted stuff, etc.)
  802. # These are called by the property generated by cookie_attribute().
  803. # Usually it would be wise not to define a renderer for name, but it is
  804. # supported in case there is ever a real need.
  805. attribute_renderers = {
  806. 'value': encode_cookie_value,
  807. 'domain': render_domain,
  808. 'expires': render_date,
  809. 'max_age': lambda item: str(item) if item is not None else None,
  810. 'secure': lambda item: True if item else False,
  811. 'httponly': lambda item: True if item else False,
  812. 'comment': encode_extension_av,
  813. 'version': lambda item: (str(item) if isinstance(item, int)
  814. else encode_extension_av(item)),
  815. }
  816. # Register single-parameter functions in this dictionary to have them used
  817. # for decoding incoming values for use in the Python API (e.g. into nice
  818. # objects, numbers, unicode strings, etc.)
  819. # These are called by the property generated by cookie_attribute().
  820. attribute_parsers = {
  821. 'value': parse_value,
  822. 'expires': parse_date,
  823. 'domain': parse_domain,
  824. 'path': parse_path,
  825. 'max_age': lambda item: long(strip_spaces_and_quotes(item)),
  826. 'comment': parse_string,
  827. 'version': lambda item: int(strip_spaces_and_quotes(item)),
  828. 'secure': lambda item: True if item else False,
  829. 'httponly': lambda item: True if item else False,
  830. }
  831. # Register single-parameter functions which return a true value for
  832. # acceptable values, and a false value for unacceptable ones. An
  833. # attribute's validator is run after it is parsed or when it is directly
  834. # set, and InvalidCookieAttribute is raised if validation fails (and the
  835. # validator doesn't raise a different exception prior)
  836. attribute_validators = {
  837. 'name': valid_name,
  838. 'value': valid_value,
  839. 'expires': valid_date,
  840. 'domain': valid_domain,
  841. 'path': valid_path,
  842. 'max_age': valid_max_age,
  843. 'comment': valid_value,
  844. 'version': lambda number: re.match("^\d+\Z", str(number)),
  845. 'secure': lambda item: item is True or item is False,
  846. 'httponly': lambda item: item is True or item is False,
  847. }
  848. class Cookies(dict):
  849. """Represent a set of cookies indexed by name.
  850. This class bundles together a set of Cookie objects and provides
  851. a convenient interface to them. for parsing and producing cookie headers.
  852. In basic operation it acts just like a dict of Cookie objects, but it adds
  853. additional convenience methods for the usual cookie tasks: add cookie
  854. objects by their names, create new cookie objects under specified names,
  855. parse HTTP request or response data into new cookie objects automatically
  856. stored in the dict, and render the set in formats suitable for HTTP request
  857. or response headers.
  858. """
  859. DEFAULT_COOKIE_CLASS = Cookie
  860. def __init__(self, *args, **kwargs):
  861. dict.__init__(self)
  862. self.all_cookies = []
  863. self.cookie_class = kwargs.get(
  864. "_cookie_class", self.DEFAULT_COOKIE_CLASS)
  865. self.add(*args, **kwargs)
  866. def add(self, *args, **kwargs):
  867. """Add Cookie objects by their names, or create new ones under
  868. specified names.
  869. Any unnamed arguments are interpreted as existing cookies, and
  870. are added under the value in their .name attribute. With keyword
  871. arguments, the key is interpreted as the cookie name and the
  872. value as the UNENCODED value stored in the cookie.
  873. """
  874. # Only the first one is accessible through the main interface,
  875. # others accessible through get_all (all_cookies).
  876. for cookie in args:
  877. self.all_cookies.append(cookie)
  878. if cookie.name in self:
  879. continue
  880. self[cookie.name] = cookie
  881. for key, value in kwargs.items():
  882. cookie = self.cookie_class(key, value)
  883. self.all_cookies.append(cookie)
  884. if key in self:
  885. continue
  886. self[key] = cookie
  887. def get_all(self, key):
  888. return [cookie for cookie in self.all_cookies
  889. if cookie.name == key]
  890. def parse_request(self, header_data, ignore_bad_cookies=False):
  891. """Parse 'Cookie' header data into Cookie objects, and add them to
  892. this Cookies object.
  893. :arg header_data: string containing only 'Cookie:' request headers or
  894. header values (as in CGI/WSGI HTTP_COOKIE); if more than one, they must
  895. be separated by CRLF (\\r\\n).
  896. :arg ignore_bad_cookies: if set, will log each syntactically invalid
  897. cookie (at the granularity of semicolon-delimited blocks) rather than
  898. raising an exception at the first bad cookie.
  899. :returns: a Cookies instance containing Cookie objects parsed from
  900. header_data.
  901. .. note::
  902. If you want to parse 'Set-Cookie:' response headers, please use
  903. parse_response instead. parse_request will happily turn 'expires=frob'
  904. into a separate cookie without complaining, according to the grammar.
  905. """
  906. cookies_dict = _parse_request(
  907. header_data, ignore_bad_cookies=ignore_bad_cookies)
  908. cookie_objects = []
  909. for name, values in cookies_dict.items():
  910. for value in values:
  911. # Use from_dict to check name and parse value
  912. cookie_dict = {'name': name, 'value': value}
  913. try:
  914. cookie = self.cookie_class.from_dict(cookie_dict)
  915. except InvalidCookieError:
  916. if not ignore_bad_cookies:
  917. raise
  918. else:
  919. cookie_objects.append(cookie)
  920. try:
  921. self.add(*cookie_objects)
  922. except InvalidCookieError:
  923. if not ignore_bad_cookies:
  924. raise
  925. _report_invalid_cookie(header_data)
  926. return self
  927. def parse_response(self, header_data, ignore_bad_cookies=False,
  928. ignore_bad_attributes=True):
  929. """Parse 'Set-Cookie' header data into Cookie objects, and add them to
  930. this Cookies object.
  931. :arg header_data: string containing only 'Set-Cookie:' request headers
  932. or their corresponding header values; if more than one, they must be
  933. separated by CRLF (\\r\\n).
  934. :arg ignore_bad_cookies: if set, will log each syntactically invalid
  935. cookie rather than raising an exception at the first bad cookie. (This
  936. includes cookies which have noncompliant characters in the attribute
  937. section).
  938. :arg ignore_bad_attributes: defaults to True, which means to log but
  939. not raise an error when a particular attribute is unrecognized. (This
  940. does not necessarily mean that the attribute is invalid, although that
  941. would often be the case.) if unset, then an error will be raised at the
  942. first semicolon-delimited block which has an unknown attribute.
  943. :returns: a Cookies instance containing Cookie objects parsed from
  944. header_data, each with recognized attributes populated.
  945. .. note::
  946. If you want to parse 'Cookie:' headers (i.e., data like what's sent
  947. with an HTTP request, which has only name=value pairs and no
  948. attributes), then please use parse_request instead. Such lines often
  949. contain multiple name=value pairs, and parse_response will throw away
  950. the pairs after the first one, which will probably generate errors or
  951. confusing behavior. (Since there's no perfect way to automatically
  952. determine which kind of parsing to do, you have to tell it manually by
  953. choosing correctly from parse_request between part_response.)
  954. """
  955. cookie_dicts = _parse_response(
  956. header_data,
  957. ignore_bad_cookies=ignore_bad_cookies,
  958. ignore_bad_attributes=ignore_bad_attributes)
  959. cookie_objects = []
  960. for cookie_dict in cookie_dicts:
  961. cookie = self.cookie_class.from_dict(cookie_dict)
  962. cookie_objects.append(cookie)
  963. self.add(*cookie_objects)
  964. return self
  965. @classmethod
  966. def from_request(cls, header_data, ignore_bad_cookies=False):
  967. "Construct a Cookies object from request header data."
  968. cookies = cls()
  969. cookies.parse_request(
  970. header_data, ignore_bad_cookies=ignore_bad_cookies)
  971. return cookies
  972. @classmethod
  973. def from_response(cls, header_data, ignore_bad_cookies=False,
  974. ignore_bad_attributes=True):
  975. "Construct a Cookies object from response header data."
  976. cookies = cls()
  977. cookies.parse_response(
  978. header_data,
  979. ignore_bad_cookies=ignore_bad_cookies,
  980. ignore_bad_attributes=ignore_bad_attributes)
  981. return cookies
  982. def render_request(self, sort=True):
  983. """Render the dict's Cookie objects into a string formatted for HTTP
  984. request headers (simple 'Cookie: ' style).
  985. """
  986. if not sort:
  987. return ("; ".join(
  988. cookie.render_request() for cookie in self.values()))
  989. return ("; ".join(sorted(
  990. cookie.render_request() for cookie in self.values())))
  991. def render_response(self, sort=True):
  992. """Render the dict's Cookie objects into list of strings formatted for
  993. HTTP response headers (detailed 'Set-Cookie: ' style).
  994. """
  995. rendered = [cookie.render_response() for cookie in self.values()]
  996. return rendered if not sort else sorted(rendered)
  997. def __repr__(self):
  998. return "Cookies(%s)" % ', '.join("%s=%r" % (name, cookie.value) for
  999. (name, cookie) in self.items())
  1000. def __eq__(self, other):
  1001. """Test if a Cookies object is globally 'equal' to another one by
  1002. seeing if it looks like a dict such that d[k] == self[k]. This depends
  1003. on each Cookie object reporting its equality correctly.
  1004. """
  1005. if not hasattr(other, "keys"):
  1006. return False
  1007. try:
  1008. keys = sorted(set(self.keys()) | set(other.keys()))
  1009. for key in keys:
  1010. if not key in self:
  1011. return False
  1012. if not key in other:
  1013. return False
  1014. if self[key] != other[key]:
  1015. return False
  1016. except (TypeError, KeyError):
  1017. raise
  1018. return True
  1019. def __ne__(self, other):
  1020. return not self.__eq__(other)