Debian Codegraph @

Lib/test/test_http_cookiejar.py

raw
1 """Tests for http/cookiejar.py."""
2
3 import os
4 import stat
5 import sys
6 import re
7 from test import support
8 from test.support import os_helper
9 from test.support import warnings_helper
10 from test.support.testcase import ExtraAssertions
11 import time
12 import unittest
13 import urllib.request
14
15 from http.cookiejar import (time2isoz, http2time, iso2time, time2netscape,
16 parse_ns_headers, join_header_words, split_header_words, Cookie,
17 CookieJar, DefaultCookiePolicy, LWPCookieJar, MozillaCookieJar,
18 LoadError, lwp_cookie_str, DEFAULT_HTTP_PORT, escape_path,
19 reach, is_HDN, domain_match, user_domain_match, request_path,
20 request_port, request_host)
21
22 mswindows = (sys.platform == "win32")
23
24 class DateTimeTests(unittest.TestCase):
25
26 def test_time2isoz(self):
27 base = 1019227000
28 day = 24*3600
29 self.assertEqual(time2isoz(base), "2002-04-19 14:36:40Z")
30 self.assertEqual(time2isoz(base+day), "2002-04-20 14:36:40Z")
31 self.assertEqual(time2isoz(base+2*day), "2002-04-21 14:36:40Z")
32 self.assertEqual(time2isoz(base+3*day), "2002-04-22 14:36:40Z")
33
34 az = time2isoz()
35 bz = time2isoz(500000)
36 for text in (az, bz):
37 self.assertRegex(text, r"^\d{4}-\d\d-\d\d \d\d:\d\d:\d\dZ$",
38 "bad time2isoz format: %s %s" % (az, bz))
39
40 def test_time2netscape(self):
41 base = 1019227000
42 day = 24*3600
43 self.assertEqual(time2netscape(base), "Fri, 19-Apr-2002 14:36:40 GMT")
44 self.assertEqual(time2netscape(base+day),
45 "Sat, 20-Apr-2002 14:36:40 GMT")
46
47 self.assertEqual(time2netscape(base+2*day),
48 "Sun, 21-Apr-2002 14:36:40 GMT")
49
50 self.assertEqual(time2netscape(base+3*day),
51 "Mon, 22-Apr-2002 14:36:40 GMT")
52
53 az = time2netscape()
54 bz = time2netscape(500000)
55 for text in (az, bz):
56 # Format "%s, %02d-%s-%04d %02d:%02d:%02d GMT"
57 self.assertRegex(
58 text,
59 r"[a-zA-Z]{3}, \d{2}-[a-zA-Z]{3}-\d{4} \d{2}:\d{2}:\d{2} GMT$",
60 "bad time2netscape format: %s %s" % (az, bz))
61
62 def test_http2time(self):
63 def parse_date(text):
64 return time.gmtime(http2time(text))[:6]
65
66 self.assertEqual(parse_date("01 Jan 2001"), (2001, 1, 1, 0, 0, 0.0))
67
68 # this test will break around year 2070
69 self.assertEqual(parse_date("03-Feb-20"), (2020, 2, 3, 0, 0, 0.0))
70
71 # this test will break around year 2048
72 self.assertEqual(parse_date("03-Feb-98"), (1998, 2, 3, 0, 0, 0.0))
73
74 def test_http2time_formats(self):
75 # test http2time for supported dates. Test cases with 2 digit year
76 # will probably break in year 2044.
77 tests = [
78 'Thu, 03 Feb 1994 00:00:00 GMT', # proposed new HTTP format
79 'Thursday, 03-Feb-94 00:00:00 GMT', # old rfc850 HTTP format
80 'Thursday, 03-Feb-1994 00:00:00 GMT', # broken rfc850 HTTP format
81
82 '03 Feb 1994 00:00:00 GMT', # HTTP format (no weekday)
83 '03-Feb-94 00:00:00 GMT', # old rfc850 (no weekday)
84 '03-Feb-1994 00:00:00 GMT', # broken rfc850 (no weekday)
85 '03-Feb-1994 00:00 GMT', # broken rfc850 (no weekday, no seconds)
86 '03-Feb-1994 00:00', # broken rfc850 (no weekday, no seconds, no tz)
87 '02-Feb-1994 24:00', # broken rfc850 (no weekday, no seconds,
88 # no tz) using hour 24 with yesterday date
89
90 '03-Feb-94', # old rfc850 HTTP format (no weekday, no time)
91 '03-Feb-1994', # broken rfc850 HTTP format (no weekday, no time)
92 '03 Feb 1994', # proposed new HTTP format (no weekday, no time)
93
94 # A few tests with extra space at various places
95 ' 03 Feb 1994 0:00 ',
96 ' 03-Feb-1994 ',
97 ]
98
99 test_t = 760233600 # assume broken POSIX counting of seconds
100 result = time2isoz(test_t)
101 expected = "1994-02-03 00:00:00Z"
102 self.assertEqual(result, expected,
103 "%s => '%s' (%s)" % (test_t, result, expected))
104
105 for s in tests:
106 self.assertEqual(http2time(s), test_t, s)
107 self.assertEqual(http2time(s.lower()), test_t, s.lower())
108 self.assertEqual(http2time(s.upper()), test_t, s.upper())
109
110 @support.subTests('test', [
111 '',
112 'Garbage',
113 'Mandag 16. September 1996',
114 '01-00-1980',
115 '01-13-1980',
116 '00-01-1980',
117 '32-01-1980',
118 '01-01-1980 25:00:00',
119 '01-01-1980 00:61:00',
120 '01-01-1980 00:00:62',
121 '08-Oct-3697739',
122 '08-01-3697739',
123 '09 Feb 19942632 22:23:32 GMT',
124 'Wed, 09 Feb 1994834 22:23:32 GMT',
125 ])
126 def test_http2time_garbage(self, test):
127 self.assertIsNone(http2time(test))
128
129 def test_http2time_redos_regression_actually_completes(self):
130 # LOOSE_HTTP_DATE_RE was vulnerable to malicious input which caused catastrophic backtracking (REDoS).
131 # If we regress to cubic complexity, this test will take a very long time to succeed.
132 # If fixed, it should complete within a fraction of a second.
133 http2time("01 Jan 1970{}00:00:00 GMT!".format(" " * 10 ** 5))
134 http2time("01 Jan 1970 00:00:00{}GMT!".format(" " * 10 ** 5))
135
136 def test_iso2time(self):
137 def parse_date(text):
138 return time.gmtime(iso2time(text))[:6]
139
140 # ISO 8601 compact format
141 self.assertEqual(parse_date("19940203T141529Z"),
142 (1994, 2, 3, 14, 15, 29))
143
144 # ISO 8601 with time behind UTC
145 self.assertEqual(parse_date("1994-02-03 07:15:29 -0700"),
146 (1994, 2, 3, 14, 15, 29))
147
148 # ISO 8601 with time ahead of UTC
149 self.assertEqual(parse_date("1994-02-03 19:45:29 +0530"),
150 (1994, 2, 3, 14, 15, 29))
151
152 @support.subTests('s', [
153 '1994-02-03 00:00:00 -0000', # ISO 8601 format
154 '1994-02-03 00:00:00 +0000', # ISO 8601 format
155 '1994-02-03 00:00:00', # zone is optional
156 '1994-02-03', # only date
157 '1994-02-03T00:00:00', # Use T as separator
158 '19940203', # only date
159 '1994-02-02 24:00:00', # using hour-24 yesterday date
160 '19940203T000000Z', # ISO 8601 compact format
161
162 # A few tests with extra space at various places
163 ' 1994-02-03 ',
164 ' 1994-02-03T00:00:00 ',
165 ])
166 def test_iso2time_formats(self, s):
167 # test iso2time for supported dates.
168 test_t = 760233600 # assume broken POSIX counting of seconds
169 self.assertEqual(iso2time(s), test_t, s)
170 self.assertEqual(iso2time(s.lower()), test_t, s.lower())
171 self.assertEqual(iso2time(s.upper()), test_t, s.upper())
172
173 @support.subTests('test', [
174 '',
175 'Garbage',
176 'Thursday, 03-Feb-94 00:00:00 GMT',
177 '1980-00-01',
178 '1980-13-01',
179 '1980-01-00',
180 '1980-01-32',
181 '1980-01-01 25:00:00',
182 '1980-01-01 00:61:00',
183 '01-01-1980 00:00:62',
184 '01-01-1980T00:00:62',
185 '19800101T250000Z',
186 ])
187 def test_iso2time_garbage(self, test):
188 self.assertIsNone(iso2time(test))
189
190 def test_iso2time_performance_regression(self):
191 # If ISO_DATE_RE regresses to quadratic complexity, this test will take a very long time to succeed.
192 # If fixed, it should complete within a fraction of a second.
193 iso2time('1994-02-03{}14:15:29 -0100!'.format(' '*10**6))
194 iso2time('1994-02-03 14:15:29{}-0100!'.format(' '*10**6))
195
196
197 class HeaderTests(unittest.TestCase):
198
199 @support.subTests('hdr', [
200 'foo=bar; expires=01 Jan 2040 22:23:32 GMT',
201 'foo=bar; expires="01 Jan 2040 22:23:32 GMT"',
202 ])
203 def test_parse_ns_headers(self, hdr):
204 # quotes should be stripped
205 expected = [[('foo', 'bar'), ('expires', 2209069412), ('version', '0')]]
206 self.assertEqual(parse_ns_headers([hdr]), expected)
207
208 @support.subTests('hdr', [
209 'foo=bar; version="1"',
210 'foo=bar; Version="1"',
211 ])
212 def test_parse_ns_headers_version(self, hdr):
213 # quotes should be stripped
214 expected = [[('foo', 'bar'), ('version', '1')]]
215 self.assertEqual(parse_ns_headers([hdr]), expected)
216
217 def test_parse_ns_headers_special_names(self):
218 # names such as 'expires' are not special in first name=value pair
219 # of Set-Cookie: header
220 # Cookie with name 'expires'
221 hdr = 'expires=01 Jan 2040 22:23:32 GMT'
222 expected = [[("expires", "01 Jan 2040 22:23:32 GMT"), ("version", "0")]]
223 self.assertEqual(parse_ns_headers([hdr]), expected)
224
225 def test_join_header_words(self):
226 joined = join_header_words([[("foo", None), ("bar", "baz")]])
227 self.assertEqual(joined, "foo; bar=baz")
228
229 self.assertEqual(join_header_words([[]]), "")
230
231 @support.subTests('arg,expect', [
232 ("foo", [[("foo", None)]]),
233 ("foo=bar", [[("foo", "bar")]]),
234 (" foo ", [[("foo", None)]]),
235 (" foo= ", [[("foo", "")]]),
236 (" foo=", [[("foo", "")]]),
237 (" foo= ; ", [[("foo", "")]]),
238 (" foo= ; bar= baz ", [[("foo", ""), ("bar", "baz")]]),
239 ("foo=bar bar=baz", [[("foo", "bar"), ("bar", "baz")]]),
240 # doesn't really matter if this next fails, but it works ATM
241 ("foo= bar=baz", [[("foo", "bar=baz")]]),
242 ("foo=bar;bar=baz", [[("foo", "bar"), ("bar", "baz")]]),
243 ('foo bar baz', [[("foo", None), ("bar", None), ("baz", None)]]),
244 ("a, b, c", [[("a", None)], [("b", None)], [("c", None)]]),
245 (r'foo; bar=baz, spam=, foo="\,\;\"", bar= ',
246 [[("foo", None), ("bar", "baz")],
247 [("spam", "")], [("foo", ',;"')], [("bar", "")]]),
248 ])
249 def test_split_header_words(self, arg, expect):
250 try:
251 result = split_header_words([arg])
252 except:
253 import traceback, io
254 f = io.StringIO()
255 traceback.print_exc(None, f)
256 result = "(error -- traceback follows)\n\n%s" % f.getvalue()
257 self.assertEqual(result, expect, """
258 When parsing: '%s'
259 Expected: '%s'
260 Got: '%s'
261 """ % (arg, expect, result))
262
263 @support.subTests('arg,expect', [
264 ("foo", "foo"),
265 ("foo=bar", "foo=bar"),
266 (" foo ", "foo"),
267 ("foo=", 'foo=""'),
268 ("foo=bar bar=baz", "foo=bar; bar=baz"),
269 ("foo=bar;bar=baz", "foo=bar; bar=baz"),
270 ('foo bar baz', "foo; bar; baz"),
271 (r'foo="\"" bar="\\"', r'foo="\""; bar="\\"'),
272 ("föo=bär", 'föo="bär"'),
273 ('foo,,,bar', 'foo, bar'),
274 ('foo=bar,bar=baz', 'foo=bar, bar=baz'),
275 ("foo=\n", 'foo=""'),
276 ('foo="\n"', 'foo="\n"'),
277 ('foo=bar\n', 'foo=bar'),
278 ('foo="bar\n"', 'foo="bar\n"'),
279 ('foo=bar\nbaz', 'foo=bar; baz'),
280 ('foo="bar\nbaz"', 'foo="bar\nbaz"'),
281
282 ('text/html; charset=iso-8859-1',
283 'text/html; charset=iso-8859-1'),
284
285 ('text/html; charset="iso-8859/1"',
286 'text/html; charset="iso-8859/1"'),
287
288 ('foo="bar"; port="80,81"; discard, bar=baz',
289 'foo=bar; port="80,81"; discard, bar=baz'),
290
291 (r'Basic realm="\"foo\\\\bar\""',
292 r'Basic; realm="\"foo\\\\bar\""'),
293
294 ('n; foo="foo;_", bar="foo,_"',
295 'n; foo="foo;_", bar="foo,_"'),
296 ])
297 def test_roundtrip(self, arg, expect):
298 input = split_header_words([arg])
299 res = join_header_words(input)
300 self.assertEqual(res, expect, """
301 When parsing: '%s'
302 Expected: '%s'
303 Got: '%s'
304 Input was: '%s'
305 """ % (arg, expect, res, input))
306
307
308 class FakeResponse:
309 def __init__(self, headers=[], url=None):
310 """
311 headers: list of RFC822-style 'Key: value' strings
312 """
313 import email
314 self._headers = email.message_from_string("\n".join(headers))
315 self._url = url
316 def info(self): return self._headers
317
318 def interact_2965(cookiejar, url, *set_cookie_hdrs):
319 return _interact(cookiejar, url, set_cookie_hdrs, "Set-Cookie2")
320
321 def interact_netscape(cookiejar, url, *set_cookie_hdrs):
322 return _interact(cookiejar, url, set_cookie_hdrs, "Set-Cookie")
323
324 def _interact(cookiejar, url, set_cookie_hdrs, hdr_name):
325 """Perform a single request / response cycle, returning Cookie: header."""
326 req = urllib.request.Request(url)
327 cookiejar.add_cookie_header(req)
328 cookie_hdr = req.get_header("Cookie", "")
329 headers = []
330 for hdr in set_cookie_hdrs:
331 headers.append("%s: %s" % (hdr_name, hdr))
332 res = FakeResponse(headers, url)
333 cookiejar.extract_cookies(res, req)
334 return cookie_hdr
335
336
337 class FileCookieJarTests(unittest.TestCase):
338 def test_constructor_with_str(self):
339 filename = os_helper.TESTFN
340 c = LWPCookieJar(filename)
341 self.assertEqual(c.filename, filename)
342
343 def test_constructor_with_path_like(self):
344 filename = os_helper.TESTFN
345 c = LWPCookieJar(os_helper.FakePath(filename))
346 self.assertEqual(c.filename, filename)
347
348 def test_constructor_with_none(self):
349 c = LWPCookieJar(None)
350 self.assertIsNone(c.filename)
351
352 def test_constructor_with_other_types(self):
353 class A:
354 pass
355
356 for type_ in (int, float, A):
357 with self.subTest(filename=type_):
358 with self.assertRaises(TypeError):
359 instance = type_()
360 c = LWPCookieJar(filename=instance)
361
362 def test_lwp_valueless_cookie(self):
363 # cookies with no value should be saved and loaded consistently
364 filename = os_helper.TESTFN
365 c = LWPCookieJar()
366 interact_netscape(c, "http://www.acme.com/", 'boo')
367 self.assertEqual(c._cookies["www.acme.com"]["/"]["boo"].value, None)
368 try:
369 c.save(filename, ignore_discard=True)
370 c = LWPCookieJar()
371 c.load(filename, ignore_discard=True)
372 finally:
373 os_helper.unlink(filename)
374 self.assertEqual(c._cookies["www.acme.com"]["/"]["boo"].value, None)
375
376 @unittest.skipIf(mswindows, "windows file permissions are incompatible with file modes")
377 @os_helper.skip_unless_working_chmod
378 def test_lwp_filepermissions(self):
379 # Cookie file should only be readable by the creator
380 filename = os_helper.TESTFN
381 c = LWPCookieJar()
382 interact_netscape(c, "http://www.acme.com/", 'boo')
383 try:
384 c.save(filename, ignore_discard=True)
385 st = os.stat(filename)
386 self.assertEqual(stat.S_IMODE(st.st_mode), 0o600)
387 finally:
388 os_helper.unlink(filename)
389
390 @unittest.skipIf(mswindows, "windows file permissions are incompatible with file modes")
391 @os_helper.skip_unless_working_chmod
392 def test_mozilla_filepermissions(self):
393 # Cookie file should only be readable by the creator
394 filename = os_helper.TESTFN
395 c = MozillaCookieJar()
396 interact_netscape(c, "http://www.acme.com/", 'boo')
397 try:
398 c.save(filename, ignore_discard=True)
399 st = os.stat(filename)
400 self.assertEqual(stat.S_IMODE(st.st_mode), 0o600)
401 finally:
402 os_helper.unlink(filename)
403
404 @unittest.skipIf(mswindows, "windows file permissions are incompatible with file modes")
405 @os_helper.skip_unless_working_chmod
406 def test_cookie_files_are_truncated(self):
407 filename = os_helper.TESTFN
408 for cookiejar_class in (LWPCookieJar, MozillaCookieJar):
409 c = cookiejar_class(filename)
410
411 req = urllib.request.Request("http://www.acme.com/")
412 headers = ["Set-Cookie: pll_lang=en; Max-Age=31536000; path=/"]
413 res = FakeResponse(headers, "http://www.acme.com/")
414 c.extract_cookies(res, req)
415 self.assertEqual(len(c), 1)
416
417 try:
418 # Save the first version with contents:
419 c.save()
420 # Now, clear cookies and re-save:
421 c.clear()
422 c.save()
423 # Check that file was truncated:
424 c.load()
425 finally:
426 os_helper.unlink(filename)
427
428 self.assertEqual(len(c), 0)
429
430 def test_bad_magic(self):
431 # OSErrors (eg. file doesn't exist) are allowed to propagate
432 filename = os_helper.TESTFN
433 for cookiejar_class in LWPCookieJar, MozillaCookieJar:
434 c = cookiejar_class()
435 try:
436 c.load(filename="for this test to work, a file with this "
437 "filename should not exist")
438 except OSError as exc:
439 # an OSError subclass (likely FileNotFoundError), but not
440 # LoadError
441 self.assertIsNot(exc.__class__, LoadError)
442 else:
443 self.fail("expected OSError for invalid filename")
444 # Invalid contents of cookies file (eg. bad magic string)
445 # causes a LoadError.
446 try:
447 with open(filename, "w") as f:
448 f.write("oops\n")
449 for cookiejar_class in LWPCookieJar, MozillaCookieJar:
450 c = cookiejar_class()
451 self.assertRaises(LoadError, c.load, filename)
452 finally:
453 os_helper.unlink(filename)
454
455 class CookieTests(unittest.TestCase):
456 # XXX
457 # Get rid of string comparisons where not actually testing str / repr.
458 # .clear() etc.
459 # IP addresses like 50 (single number, no dot) and domain-matching
460 # functions (and is_HDN)? See draft RFC 2965 errata.
461 # Strictness switches
462 # is_third_party()
463 # unverifiability / third-party blocking
464 # Netscape cookies work the same as RFC 2965 with regard to port.
465 # Set-Cookie with negative max age.
466 # If turn RFC 2965 handling off, Set-Cookie2 cookies should not clobber
467 # Set-Cookie cookies.
468 # Cookie2 should be sent if *any* cookies are not V1 (ie. V0 OR V2 etc.).
469 # Cookies (V1 and V0) with no expiry date should be set to be discarded.
470 # RFC 2965 Quoting:
471 # Should accept unquoted cookie-attribute values? check errata draft.
472 # Which are required on the way in and out?
473 # Should always return quoted cookie-attribute values?
474 # Proper testing of when RFC 2965 clobbers Netscape (waiting for errata).
475 # Path-match on return (same for V0 and V1).
476 # RFC 2965 acceptance and returning rules
477 # Set-Cookie2 without version attribute is rejected.
478
479 # Netscape peculiarities list from Ronald Tschalar.
480 # The first two still need tests, the rest are covered.
481 ## - Quoting: only quotes around the expires value are recognized as such
482 ## (and yes, some folks quote the expires value); quotes around any other
483 ## value are treated as part of the value.
484 ## - White space: white space around names and values is ignored
485 ## - Default path: if no path parameter is given, the path defaults to the
486 ## path in the request-uri up to, but not including, the last '/'. Note
487 ## that this is entirely different from what the spec says.
488 ## - Commas and other delimiters: Netscape just parses until the next ';'.
489 ## This means it will allow commas etc inside values (and yes, both
490 ## commas and equals are commonly appear in the cookie value). This also
491 ## means that if you fold multiple Set-Cookie header fields into one,
492 ## comma-separated list, it'll be a headache to parse (at least my head
493 ## starts hurting every time I think of that code).
494 ## - Expires: You'll get all sorts of date formats in the expires,
495 ## including empty expires attributes ("expires="). Be as flexible as you
496 ## can, and certainly don't expect the weekday to be there; if you can't
497 ## parse it, just ignore it and pretend it's a session cookie.
498 ## - Domain-matching: Netscape uses the 2-dot rule for _all_ domains, not
499 ## just the 7 special TLD's listed in their spec. And folks rely on
500 ## that...
501
502 @support.subTests('url,domain,ok', [
503 ("http://foo.bar.com/", "blah.com", False),
504 ("http://foo.bar.com/", "rhubarb.blah.com", False),
505 ("http://foo.bar.com/", "rhubarb.foo.bar.com", False),
506 ("http://foo.bar.com/", ".foo.bar.com", True),
507 ("http://foo.bar.com/", "foo.bar.com", True),
508 ("http://foo.bar.com/", ".bar.com", True),
509 ("http://foo.bar.com/", "bar.com", True),
510 ("http://foo.bar.com/", "com", True),
511 ("http://foo.com/", "rhubarb.foo.com", False),
512 ("http://foo.com/", ".foo.com", True),
513 ("http://foo.com/", "foo.com", True),
514 ("http://foo.com/", "com", True),
515 ("http://foo/", "rhubarb.foo", False),
516 ("http://foo/", ".foo", True),
517 ("http://foo/", "foo", True),
518 ("http://foo/", "foo.local", True),
519 ("http://foo/", ".local", True),
520 ("http://barfoo.com", ".foo.com", False),
521 ("http://barfoo.com", "foo.com", False),
522 ])
523 def test_domain_return_ok(self, url, domain, ok):
524 # test optimization: .domain_return_ok() should filter out most
525 # domains in the CookieJar before we try to access them (because that
526 # may require disk access -- in particular, with MSIECookieJar)
527 # This is only a rough check for performance reasons, so it's not too
528 # critical as long as it's sufficiently liberal.
529 pol = DefaultCookiePolicy()
530 request = urllib.request.Request(url)
531 r = pol.domain_return_ok(domain, request)
532 if ok: self.assertTrue(r)
533 else: self.assertFalse(r)
534
535 def test_missing_value(self):
536 # missing = sign in Cookie: header is regarded by Mozilla as a missing
537 # name, and by http.cookiejar as a missing value
538 filename = os_helper.TESTFN
539 c = MozillaCookieJar(filename)
540 interact_netscape(c, "http://www.acme.com/", 'eggs')
541 interact_netscape(c, "http://www.acme.com/", '"spam"; path=/foo/')
542 cookie = c._cookies["www.acme.com"]["/"]["eggs"]
543 self.assertIsNone(cookie.value)
544 self.assertEqual(cookie.name, "eggs")
545 cookie = c._cookies["www.acme.com"]['/foo/']['"spam"']
546 self.assertIsNone(cookie.value)
547 self.assertEqual(cookie.name, '"spam"')
548 self.assertEqual(lwp_cookie_str(cookie), (
549 r'"spam"; path="/foo/"; domain=www.acme.com; '
550 'path_spec; discard; version=0'))
551 old_str = repr(c)
552 c.save(ignore_expires=True, ignore_discard=True)
553 try:
554 c = MozillaCookieJar(filename)
555 c.revert(ignore_expires=True, ignore_discard=True)
556 finally:
557 os_helper.unlink(c.filename)
558 # cookies unchanged apart from lost info re. whether path was specified
559 self.assertEqual(
560 repr(c),
561 re.sub("path_specified=%s" % True, "path_specified=%s" % False,
562 old_str)
563 )
564 self.assertEqual(interact_netscape(c, "http://www.acme.com/foo/"),
565 '"spam"; eggs')
566
567 @support.subTests('rfc2109_as_netscape,rfc2965,version', [
568 # default according to rfc2965 if not explicitly specified
569 (None, False, 0),
570 (None, True, 1),
571 # explicit rfc2109_as_netscape
572 (False, False, None), # version None here means no cookie stored
573 (False, True, 1),
574 (True, False, 0),
575 (True, True, 0),
576 ])
577 def test_rfc2109_handling(self, rfc2109_as_netscape, rfc2965, version):
578 # RFC 2109 cookies are handled as RFC 2965 or Netscape cookies,
579 # dependent on policy settings
580 policy = DefaultCookiePolicy(
581 rfc2109_as_netscape=rfc2109_as_netscape,
582 rfc2965=rfc2965)
583 c = CookieJar(policy)
584 interact_netscape(c, "http://www.example.com/", "ni=ni; Version=1")
585 try:
586 cookie = c._cookies["www.example.com"]["/"]["ni"]
587 except KeyError:
588 self.assertIsNone(version) # didn't expect a stored cookie
589 else:
590 self.assertEqual(cookie.version, version)
591 # 2965 cookies are unaffected
592 interact_2965(c, "http://www.example.com/",
593 "foo=bar; Version=1")
594 if rfc2965:
595 cookie2965 = c._cookies["www.example.com"]["/"]["foo"]
596 self.assertEqual(cookie2965.version, 1)
597
598 def test_ns_parser(self):
599 c = CookieJar()
600 interact_netscape(c, "http://www.acme.com/",
601 'spam=eggs; DoMain=.acme.com; port; blArgh="feep"')
602 interact_netscape(c, "http://www.acme.com/", 'ni=ni; port=80,8080')
603 interact_netscape(c, "http://www.acme.com:80/", 'nini=ni')
604 interact_netscape(c, "http://www.acme.com:80/", 'foo=bar; expires=')
605 interact_netscape(c, "http://www.acme.com:80/", 'spam=eggs; '
606 'expires="Foo Bar 25 33:22:11 3022"')
607 interact_netscape(c, 'http://www.acme.com/', 'fortytwo=')
608 interact_netscape(c, 'http://www.acme.com/', '=unladenswallow')
609 interact_netscape(c, 'http://www.acme.com/', 'holyhandgrenade')
610
611 cookie = c._cookies[".acme.com"]["/"]["spam"]
612 self.assertEqual(cookie.domain, ".acme.com")
613 self.assertTrue(cookie.domain_specified)
614 self.assertEqual(cookie.port, DEFAULT_HTTP_PORT)
615 self.assertFalse(cookie.port_specified)
616 # case is preserved
617 self.assertTrue(cookie.has_nonstandard_attr("blArgh"))
618 self.assertFalse(cookie.has_nonstandard_attr("blargh"))
619
620 cookie = c._cookies["www.acme.com"]["/"]["ni"]
621 self.assertEqual(cookie.domain, "www.acme.com")
622 self.assertFalse(cookie.domain_specified)
623 self.assertEqual(cookie.port, "80,8080")
624 self.assertTrue(cookie.port_specified)
625
626 cookie = c._cookies["www.acme.com"]["/"]["nini"]
627 self.assertIsNone(cookie.port)
628 self.assertFalse(cookie.port_specified)
629
630 # invalid expires should not cause cookie to be dropped
631 foo = c._cookies["www.acme.com"]["/"]["foo"]
632 spam = c._cookies["www.acme.com"]["/"]["foo"]
633 self.assertIsNone(foo.expires)
634 self.assertIsNone(spam.expires)
635
636 cookie = c._cookies['www.acme.com']['/']['fortytwo']
637 self.assertIsNotNone(cookie.value)
638 self.assertEqual(cookie.value, '')
639
640 # there should be a distinction between a present but empty value
641 # (above) and a value that's entirely missing (below)
642
643 cookie = c._cookies['www.acme.com']['/']['holyhandgrenade']
644 self.assertIsNone(cookie.value)
645
646 def test_ns_parser_special_names(self):
647 # names such as 'expires' are not special in first name=value pair
648 # of Set-Cookie: header
649 c = CookieJar()
650 interact_netscape(c, "http://www.acme.com/", 'expires=eggs')
651 interact_netscape(c, "http://www.acme.com/", 'version=eggs; spam=eggs')
652
653 cookies = c._cookies["www.acme.com"]["/"]
654 self.assertIn('expires', cookies)
655 self.assertIn('version', cookies)
656
657 def test_expires(self):
658 # if expires is in future, keep cookie...
659 c = CookieJar()
660 future = time2netscape(time.time()+3600)
661
662 with warnings_helper.check_no_warnings(self):
663 headers = [f"Set-Cookie: FOO=BAR; path=/; expires={future}"]
664 req = urllib.request.Request("http://www.coyote.com/")
665 res = FakeResponse(headers, "http://www.coyote.com/")
666 cookies = c.make_cookies(res, req)
667 self.assertEqual(len(cookies), 1)
668 self.assertEqual(time2netscape(cookies[0].expires), future)
669
670 interact_netscape(c, "http://www.acme.com/", 'spam="bar"; expires=%s' %
671 future)
672 self.assertEqual(len(c), 1)
673 now = time2netscape(time.time()-1)
674 # ... and if in past or present, discard it
675 interact_netscape(c, "http://www.acme.com/", 'foo="eggs"; expires=%s' %
676 now)
677 h = interact_netscape(c, "http://www.acme.com/")
678 self.assertEqual(len(c), 1)
679 self.assertIn('spam="bar"', h)
680 self.assertNotIn("foo", h)
681
682 # max-age takes precedence over expires, and zero max-age is request to
683 # delete both new cookie and any old matching cookie
684 interact_netscape(c, "http://www.acme.com/", 'eggs="bar"; expires=%s' %
685 future)
686 interact_netscape(c, "http://www.acme.com/", 'bar="bar"; expires=%s' %
687 future)
688 self.assertEqual(len(c), 3)
689 interact_netscape(c, "http://www.acme.com/", 'eggs="bar"; '
690 'expires=%s; max-age=0' % future)
691 interact_netscape(c, "http://www.acme.com/", 'bar="bar"; '
692 'max-age=0; expires=%s' % future)
693 h = interact_netscape(c, "http://www.acme.com/")
694 self.assertEqual(len(c), 1)
695
696 # test expiry at end of session for cookies with no expires attribute
697 interact_netscape(c, "http://www.rhubarb.net/", 'whum="fizz"')
698 self.assertEqual(len(c), 2)
699 c.clear_session_cookies()
700 self.assertEqual(len(c), 1)
701 self.assertIn('spam="bar"', h)
702
703 # test if fractional expiry is accepted
704 cookie = Cookie(0, "name", "value",
705 None, False, "www.python.org",
706 True, False, "/",
707 False, False, "1444312383.018307",
708 False, None, None,
709 {})
710 self.assertEqual(cookie.expires, 1444312383)
711
712 # XXX RFC 2965 expiry rules (some apply to V0 too)
713
714 def test_default_path(self):
715 # RFC 2965
716 pol = DefaultCookiePolicy(rfc2965=True)
717
718 c = CookieJar(pol)
719 interact_2965(c, "http://www.acme.com/", 'spam="bar"; Version="1"')
720 self.assertIn("/", c._cookies["www.acme.com"])
721
722 c = CookieJar(pol)
723 interact_2965(c, "http://www.acme.com/blah", 'eggs="bar"; Version="1"')
724 self.assertIn("/", c._cookies["www.acme.com"])
725
726 c = CookieJar(pol)
727 interact_2965(c, "http://www.acme.com/blah/rhubarb",
728 'eggs="bar"; Version="1"')
729 self.assertIn("/blah/", c._cookies["www.acme.com"])
730
731 c = CookieJar(pol)
732 interact_2965(c, "http://www.acme.com/blah/rhubarb/",
733 'eggs="bar"; Version="1"')
734 self.assertIn("/blah/rhubarb/", c._cookies["www.acme.com"])
735
736 # Netscape
737
738 c = CookieJar()
739 interact_netscape(c, "http://www.acme.com/", 'spam="bar"')
740 self.assertIn("/", c._cookies["www.acme.com"])
741
742 c = CookieJar()
743 interact_netscape(c, "http://www.acme.com/blah", 'eggs="bar"')
744 self.assertIn("/", c._cookies["www.acme.com"])
745
746 c = CookieJar()
747 interact_netscape(c, "http://www.acme.com/blah/rhubarb", 'eggs="bar"')
748 self.assertIn("/blah", c._cookies["www.acme.com"])
749
750 c = CookieJar()
751 interact_netscape(c, "http://www.acme.com/blah/rhubarb/", 'eggs="bar"')
752 self.assertIn("/blah/rhubarb", c._cookies["www.acme.com"])
753
754 def test_default_path_with_query(self):
755 cj = CookieJar()
756 uri = "http://example.com/?spam/eggs"
757 value = 'eggs="bar"'
758 interact_netscape(cj, uri, value)
759 # Default path does not include query, so is "/", not "/?spam".
760 self.assertIn("/", cj._cookies["example.com"])
761 # Cookie is sent back to the same URI.
762 self.assertEqual(interact_netscape(cj, uri), value)
763
764 @support.subTests('arg,result', [
765 # quoted safe
766 ("/foo%2f/bar", "/foo%2F/bar"),
767 ("/foo%2F/bar", "/foo%2F/bar"),
768 # quoted %
769 ("/foo%%/bar", "/foo%%/bar"),
770 # quoted unsafe
771 ("/fo%19o/bar", "/fo%19o/bar"),
772 ("/fo%7do/bar", "/fo%7Do/bar"),
773 # unquoted safe
774 ("/foo/bar&", "/foo/bar&"),
775 ("/foo//bar", "/foo//bar"),
776 ("\176/foo/bar", "\176/foo/bar"),
777 # unquoted unsafe
778 ("/foo\031/bar", "/foo%19/bar"),
779 ("/\175foo/bar", "/%7Dfoo/bar"),
780 # unicode, latin-1 range
781 ("/foo/bar\u00fc", "/foo/bar%C3%BC"), # UTF-8 encoded
782 # unicode
783 ("/foo/bar\uabcd", "/foo/bar%EA%AF%8D"), # UTF-8 encoded
784 ])
785 def test_escape_path(self, arg, result):
786 self.assertEqual(escape_path(arg), result)
787
788 def test_request_path(self):
789 # with parameters
790 req = urllib.request.Request(
791 "http://www.example.com/rheum/rhaponticum;"
792 "foo=bar;sing=song?apples=pears&spam=eggs#ni")
793 self.assertEqual(request_path(req),
794 "/rheum/rhaponticum;foo=bar;sing=song")
795 # without parameters
796 req = urllib.request.Request(
797 "http://www.example.com/rheum/rhaponticum?"
798 "apples=pears&spam=eggs#ni")
799 self.assertEqual(request_path(req), "/rheum/rhaponticum")
800 # missing final slash
801 req = urllib.request.Request("http://www.example.com")
802 self.assertEqual(request_path(req), "/")
803
804 def test_path_prefix_match(self):
805 pol = DefaultCookiePolicy()
806 strict_ns_path_pol = DefaultCookiePolicy(strict_ns_set_path=True)
807
808 c = CookieJar(pol)
809 base_url = "http://bar.com"
810 interact_netscape(c, base_url, 'spam=eggs; Path=/foo')
811 cookie = c._cookies['bar.com']['/foo']['spam']
812
813 for path, ok in [('/foo', True),
814 ('/foo/', True),
815 ('/foo/bar', True),
816 ('/', False),
817 ('/foobad/foo', False)]:
818 url = f'{base_url}{path}'
819 req = urllib.request.Request(url)
820 h = interact_netscape(c, url)
821 if ok:
822 self.assertIn('spam=eggs', h, f"cookie not set for {path}")
823 self.assertTrue(strict_ns_path_pol.set_ok_path(cookie, req))
824 else:
825 self.assertNotIn('spam=eggs', h, f"cookie set for {path}")
826 self.assertFalse(strict_ns_path_pol.set_ok_path(cookie, req))
827
828 def test_request_port(self):
829 req = urllib.request.Request("http://www.acme.com:1234/",
830 headers={"Host": "www.acme.com:4321"})
831 self.assertEqual(request_port(req), "1234")
832 req = urllib.request.Request("http://www.acme.com/",
833 headers={"Host": "www.acme.com:4321"})
834 self.assertEqual(request_port(req), DEFAULT_HTTP_PORT)
835
836 def test_request_host(self):
837 # this request is illegal (RFC2616, 14.2.3)
838 req = urllib.request.Request("http://1.1.1.1/",
839 headers={"Host": "www.acme.com:80"})
840 # libwww-perl wants this response, but that seems wrong (RFC 2616,
841 # section 5.2, point 1., and RFC 2965 section 1, paragraph 3)
842 #self.assertEqual(request_host(req), "www.acme.com")
843 self.assertEqual(request_host(req), "1.1.1.1")
844 req = urllib.request.Request("http://www.acme.com/",
845 headers={"Host": "irrelevant.com"})
846 self.assertEqual(request_host(req), "www.acme.com")
847 # port shouldn't be in request-host
848 req = urllib.request.Request("http://www.acme.com:2345/resource.html",
849 headers={"Host": "www.acme.com:5432"})
850 self.assertEqual(request_host(req), "www.acme.com")
851
852 def test_is_HDN(self):
853 self.assertTrue(is_HDN("foo.bar.com"))
854 self.assertTrue(is_HDN("1foo2.3bar4.5com"))
855 self.assertFalse(is_HDN("192.168.1.1"))
856 self.assertFalse(is_HDN(""))
857 self.assertFalse(is_HDN("."))
858 self.assertFalse(is_HDN(".foo.bar.com"))
859 self.assertFalse(is_HDN("..foo"))
860 self.assertFalse(is_HDN("foo."))
861
862 def test_reach(self):
863 self.assertEqual(reach("www.acme.com"), ".acme.com")
864 self.assertEqual(reach("acme.com"), "acme.com")
865 self.assertEqual(reach("acme.local"), ".local")
866 self.assertEqual(reach(".local"), ".local")
867 self.assertEqual(reach(".com"), ".com")
868 self.assertEqual(reach("."), ".")
869 self.assertEqual(reach(""), "")
870 self.assertEqual(reach("192.168.0.1"), "192.168.0.1")
871
872 def test_domain_match(self):
873 self.assertTrue(domain_match("192.168.1.1", "192.168.1.1"))
874 self.assertFalse(domain_match("192.168.1.1", ".168.1.1"))
875 self.assertTrue(domain_match("x.y.com", "x.Y.com"))
876 self.assertTrue(domain_match("x.y.com", ".Y.com"))
877 self.assertFalse(domain_match("x.y.com", "Y.com"))
878 self.assertTrue(domain_match("a.b.c.com", ".c.com"))
879 self.assertFalse(domain_match(".c.com", "a.b.c.com"))
880 self.assertTrue(domain_match("example.local", ".local"))
881 self.assertFalse(domain_match("blah.blah", ""))
882 self.assertFalse(domain_match("", ".rhubarb.rhubarb"))
883 self.assertTrue(domain_match("", ""))
884
885 self.assertTrue(user_domain_match("acme.com", "acme.com"))
886 self.assertFalse(user_domain_match("acme.com", ".acme.com"))
887 self.assertTrue(user_domain_match("rhubarb.acme.com", ".acme.com"))
888 self.assertTrue(user_domain_match("www.rhubarb.acme.com", ".acme.com"))
889 self.assertTrue(user_domain_match("x.y.com", "x.Y.com"))
890 self.assertTrue(user_domain_match("x.y.com", ".Y.com"))
891 self.assertFalse(user_domain_match("x.y.com", "Y.com"))
892 self.assertTrue(user_domain_match("y.com", "Y.com"))
893 self.assertFalse(user_domain_match(".y.com", "Y.com"))
894 self.assertTrue(user_domain_match(".y.com", ".Y.com"))
895 self.assertTrue(user_domain_match("x.y.com", ".com"))
896 self.assertFalse(user_domain_match("x.y.com", "com"))
897 self.assertFalse(user_domain_match("x.y.com", "m"))
898 self.assertFalse(user_domain_match("x.y.com", ".m"))
899 self.assertFalse(user_domain_match("x.y.com", ""))
900 self.assertFalse(user_domain_match("x.y.com", "."))
901 self.assertTrue(user_domain_match("192.168.1.1", "192.168.1.1"))
902 # not both HDNs, so must string-compare equal to match
903 self.assertFalse(user_domain_match("192.168.1.1", ".168.1.1"))
904 self.assertFalse(user_domain_match("192.168.1.1", "."))
905 # empty string is a special case
906 self.assertFalse(user_domain_match("192.168.1.1", ""))
907
908 def test_wrong_domain(self):
909 # Cookies whose effective request-host name does not domain-match the
910 # domain are rejected.
911
912 # XXX far from complete
913 c = CookieJar()
914 interact_2965(c, "http://www.nasty.com/",
915 'foo=bar; domain=friendly.org; Version="1"')
916 self.assertEqual(len(c), 0)
917
918 def test_strict_domain(self):
919 # Cookies whose domain is a country-code tld like .co.uk should
920 # not be set if CookiePolicy.strict_domain is true.
921 cp = DefaultCookiePolicy(strict_domain=True)
922 cj = CookieJar(policy=cp)
923 interact_netscape(cj, "http://example.co.uk/", 'no=problemo')
924 interact_netscape(cj, "http://example.co.uk/",
925 'okey=dokey; Domain=.example.co.uk')
926 self.assertEqual(len(cj), 2)
927 for pseudo_tld in [".co.uk", ".org.za", ".tx.us", ".name.us"]:
928 interact_netscape(cj, "http://example.%s/" % pseudo_tld,
929 'spam=eggs; Domain=.co.uk')
930 self.assertEqual(len(cj), 2)
931
932 def test_two_component_domain_ns(self):
933 # Netscape: .www.bar.com, www.bar.com, .bar.com, bar.com, no domain
934 # should all get accepted, as should .acme.com, acme.com and no domain
935 # for 2-component domains like acme.com.
936 c = CookieJar()
937
938 # two-component V0 domain is OK
939 interact_netscape(c, "http://foo.net/", 'ns=bar')
940 self.assertEqual(len(c), 1)
941 self.assertEqual(c._cookies["foo.net"]["/"]["ns"].value, "bar")
942 self.assertEqual(interact_netscape(c, "http://foo.net/"), "ns=bar")
943 # *will* be returned to any other domain (unlike RFC 2965)...
944 self.assertEqual(interact_netscape(c, "http://www.foo.net/"),
945 "ns=bar")
946 # ...unless requested otherwise
947 pol = DefaultCookiePolicy(
948 strict_ns_domain=DefaultCookiePolicy.DomainStrictNonDomain)
949 c.set_policy(pol)
950 self.assertEqual(interact_netscape(c, "http://www.foo.net/"), "")
951
952 # unlike RFC 2965, even explicit two-component domain is OK,
953 # because .foo.net matches foo.net
954 interact_netscape(c, "http://foo.net/foo/",
955 'spam1=eggs; domain=foo.net')
956 # even if starts with a dot -- in NS rules, .foo.net matches foo.net!
957 interact_netscape(c, "http://foo.net/foo/bar/",
958 'spam2=eggs; domain=.foo.net')
959 self.assertEqual(len(c), 3)
960 self.assertEqual(c._cookies[".foo.net"]["/foo"]["spam1"].value,
961 "eggs")
962 self.assertEqual(c._cookies[".foo.net"]["/foo/bar"]["spam2"].value,
963 "eggs")
964 self.assertEqual(interact_netscape(c, "http://foo.net/foo/bar/"),
965 "spam2=eggs; spam1=eggs; ns=bar")
966
967 # top-level domain is too general
968 interact_netscape(c, "http://foo.net/", 'nini="ni"; domain=.net')
969 self.assertEqual(len(c), 3)
970
971 ## # Netscape protocol doesn't allow non-special top level domains (such
972 ## # as co.uk) in the domain attribute unless there are at least three
973 ## # dots in it.
974 # Oh yes it does! Real implementations don't check this, and real
975 # cookies (of course) rely on that behaviour.
976 interact_netscape(c, "http://foo.co.uk", 'nasty=trick; domain=.co.uk')
977 ## self.assertEqual(len(c), 2)
978 self.assertEqual(len(c), 4)
979
980 def test_localhost_domain(self):
981 c = CookieJar()
982
983 interact_netscape(c, "http://localhost", "foo=bar; domain=localhost;")
984
985 self.assertEqual(len(c), 1)
986
987 def test_localhost_domain_contents(self):
988 c = CookieJar()
989
990 interact_netscape(c, "http://localhost", "foo=bar; domain=localhost;")
991
992 self.assertEqual(c._cookies[".localhost"]["/"]["foo"].value, "bar")
993
994 def test_localhost_domain_contents_2(self):
995 c = CookieJar()
996
997 interact_netscape(c, "http://localhost", "foo=bar;")
998
999 self.assertEqual(c._cookies["localhost.local"]["/"]["foo"].value, "bar")
1000
1001 def test_evil_nonlocal_domain(self):
1002 c = CookieJar()
1003
1004 interact_netscape(c, "http://evil.com", "foo=bar; domain=.localhost")
1005
1006 self.assertEqual(len(c), 0)
1007
1008 def test_evil_local_domain(self):
1009 c = CookieJar()
1010
1011 interact_netscape(c, "http://localhost", "foo=bar; domain=.evil.com")
1012
1013 self.assertEqual(len(c), 0)
1014
1015 def test_evil_local_domain_2(self):
1016 c = CookieJar()
1017
1018 interact_netscape(c, "http://localhost", "foo=bar; domain=.someother.local")
1019
1020 self.assertEqual(len(c), 0)
1021
1022 def test_two_component_domain_rfc2965(self):
1023 pol = DefaultCookiePolicy(rfc2965=True)
1024 c = CookieJar(pol)
1025
1026 # two-component V1 domain is OK
1027 interact_2965(c, "http://foo.net/", 'foo=bar; Version="1"')
1028 self.assertEqual(len(c), 1)
1029 self.assertEqual(c._cookies["foo.net"]["/"]["foo"].value, "bar")
1030 self.assertEqual(interact_2965(c, "http://foo.net/"),
1031 "$Version=1; foo=bar")
1032 # won't be returned to any other domain (because domain was implied)
1033 self.assertEqual(interact_2965(c, "http://www.foo.net/"), "")
1034
1035 # unless domain is given explicitly, because then it must be
1036 # rewritten to start with a dot: foo.net --> .foo.net, which does
1037 # not domain-match foo.net
1038 interact_2965(c, "http://foo.net/foo",
1039 'spam=eggs; domain=foo.net; path=/foo; Version="1"')
1040 self.assertEqual(len(c), 1)
1041 self.assertEqual(interact_2965(c, "http://foo.net/foo"),
1042 "$Version=1; foo=bar")
1043
1044 # explicit foo.net from three-component domain www.foo.net *does* get
1045 # set, because .foo.net domain-matches .foo.net
1046 interact_2965(c, "http://www.foo.net/foo/",
1047 'spam=eggs; domain=foo.net; Version="1"')
1048 self.assertEqual(c._cookies[".foo.net"]["/foo/"]["spam"].value,
1049 "eggs")
1050 self.assertEqual(len(c), 2)
1051 self.assertEqual(interact_2965(c, "http://foo.net/foo/"),
1052 "$Version=1; foo=bar")
1053 self.assertEqual(interact_2965(c, "http://www.foo.net/foo/"),
1054 '$Version=1; spam=eggs; $Domain="foo.net"')
1055
1056 # top-level domain is too general
1057 interact_2965(c, "http://foo.net/",
1058 'ni="ni"; domain=".net"; Version="1"')
1059 self.assertEqual(len(c), 2)
1060
1061 # RFC 2965 doesn't require blocking this
1062 interact_2965(c, "http://foo.co.uk/",
1063 'nasty=trick; domain=.co.uk; Version="1"')
1064 self.assertEqual(len(c), 3)
1065
1066 def test_domain_allow(self):
1067 c = CookieJar(policy=DefaultCookiePolicy(
1068 blocked_domains=["acme.com"],
1069 allowed_domains=["www.acme.com"]))
1070
1071 req = urllib.request.Request("http://acme.com/")
1072 headers = ["Set-Cookie: CUSTOMER=WILE_E_COYOTE; path=/"]
1073 res = FakeResponse(headers, "http://acme.com/")
1074 c.extract_cookies(res, req)
1075 self.assertEqual(len(c), 0)
1076
1077 req = urllib.request.Request("http://www.acme.com/")
1078 res = FakeResponse(headers, "http://www.acme.com/")
1079 c.extract_cookies(res, req)
1080 self.assertEqual(len(c), 1)
1081
1082 req = urllib.request.Request("http://www.coyote.com/")
1083 res = FakeResponse(headers, "http://www.coyote.com/")
1084 c.extract_cookies(res, req)
1085 self.assertEqual(len(c), 1)
1086
1087 # set a cookie with non-allowed domain...
1088 req = urllib.request.Request("http://www.coyote.com/")
1089 res = FakeResponse(headers, "http://www.coyote.com/")
1090 cookies = c.make_cookies(res, req)
1091 c.set_cookie(cookies[0])
1092 self.assertEqual(len(c), 2)
1093 # ... and check is doesn't get returned
1094 c.add_cookie_header(req)
1095 self.assertFalse(req.has_header("Cookie"))
1096
1097 def test_domain_block(self):
1098 pol = DefaultCookiePolicy(
1099 rfc2965=True, blocked_domains=[".acme.com"])
1100 c = CookieJar(policy=pol)
1101 headers = ["Set-Cookie: CUSTOMER=WILE_E_COYOTE; path=/"]
1102
1103 req = urllib.request.Request("http://www.acme.com/")
1104 res = FakeResponse(headers, "http://www.acme.com/")
1105 c.extract_cookies(res, req)
1106 self.assertEqual(len(c), 0)
1107
1108 p = pol.set_blocked_domains(["acme.com"])
1109 c.extract_cookies(res, req)
1110 self.assertEqual(len(c), 1)
1111
1112 c.clear()
1113 req = urllib.request.Request("http://www.roadrunner.net/")
1114 res = FakeResponse(headers, "http://www.roadrunner.net/")
1115 c.extract_cookies(res, req)
1116 self.assertEqual(len(c), 1)
1117 req = urllib.request.Request("http://www.roadrunner.net/")
1118 c.add_cookie_header(req)
1119 self.assertTrue(req.has_header("Cookie"))
1120 self.assertTrue(req.has_header("Cookie2"))
1121
1122 c.clear()
1123 pol.set_blocked_domains([".acme.com"])
1124 c.extract_cookies(res, req)
1125 self.assertEqual(len(c), 1)
1126
1127 # set a cookie with blocked domain...
1128 req = urllib.request.Request("http://www.acme.com/")
1129 res = FakeResponse(headers, "http://www.acme.com/")
1130 cookies = c.make_cookies(res, req)
1131 c.set_cookie(cookies[0])
1132 self.assertEqual(len(c), 2)
1133 # ... and check is doesn't get returned
1134 c.add_cookie_header(req)
1135 self.assertFalse(req.has_header("Cookie"))
1136
1137 c.clear()
1138
1139 pol.set_blocked_domains([])
1140 req = urllib.request.Request("http://acme.com/")
1141 res = FakeResponse(headers, "http://acme.com/")
1142 cookies = c.make_cookies(res, req)
1143 c.extract_cookies(res, req)
1144 self.assertEqual(len(c), 1)
1145
1146 req = urllib.request.Request("http://acme.com/")
1147 c.add_cookie_header(req)
1148 self.assertTrue(req.has_header("Cookie"))
1149
1150 req = urllib.request.Request("http://badacme.com/")
1151 c.add_cookie_header(req)
1152 self.assertFalse(pol.return_ok(cookies[0], req))
1153 self.assertFalse(req.has_header("Cookie"))
1154
1155 p = pol.set_blocked_domains(["acme.com"])
1156 req = urllib.request.Request("http://acme.com/")
1157 c.add_cookie_header(req)
1158 self.assertFalse(req.has_header("Cookie"))
1159
1160 req = urllib.request.Request("http://badacme.com/")
1161 c.add_cookie_header(req)
1162 self.assertFalse(req.has_header("Cookie"))
1163
1164 def test_secure(self):
1165 for ns in True, False:
1166 for whitespace in " ", "":
1167 c = CookieJar()
1168 if ns:
1169 pol = DefaultCookiePolicy(rfc2965=False)
1170 int = interact_netscape
1171 vs = ""
1172 else:
1173 pol = DefaultCookiePolicy(rfc2965=True)
1174 int = interact_2965
1175 vs = "; Version=1"
1176 c.set_policy(pol)
1177 url = "http://www.acme.com/"
1178 int(c, url, "foo1=bar%s%s" % (vs, whitespace))
1179 int(c, url, "foo2=bar%s; secure%s" % (vs, whitespace))
1180 self.assertFalse(
1181 c._cookies["www.acme.com"]["/"]["foo1"].secure,
1182 "non-secure cookie registered secure")
1183 self.assertTrue(
1184 c._cookies["www.acme.com"]["/"]["foo2"].secure,
1185 "secure cookie registered non-secure")
1186
1187 def test_secure_block(self):
1188 pol = DefaultCookiePolicy()
1189 c = CookieJar(policy=pol)
1190
1191 headers = ["Set-Cookie: session=narf; secure; path=/"]
1192 req = urllib.request.Request("https://www.acme.com/")
1193 res = FakeResponse(headers, "https://www.acme.com/")
1194 c.extract_cookies(res, req)
1195 self.assertEqual(len(c), 1)
1196
1197 req = urllib.request.Request("https://www.acme.com/")
1198 c.add_cookie_header(req)
1199 self.assertTrue(req.has_header("Cookie"))
1200
1201 req = urllib.request.Request("http://www.acme.com/")
1202 c.add_cookie_header(req)
1203 self.assertFalse(req.has_header("Cookie"))
1204
1205 # secure websocket protocol
1206 req = urllib.request.Request("wss://www.acme.com/")
1207 c.add_cookie_header(req)
1208 self.assertTrue(req.has_header("Cookie"))
1209
1210 # non-secure websocket protocol
1211 req = urllib.request.Request("ws://www.acme.com/")
1212 c.add_cookie_header(req)
1213 self.assertFalse(req.has_header("Cookie"))
1214
1215 def test_custom_secure_protocols(self):
1216 pol = DefaultCookiePolicy(secure_protocols=["foos"])
1217 c = CookieJar(policy=pol)
1218
1219 headers = ["Set-Cookie: session=narf; secure; path=/"]
1220 req = urllib.request.Request("https://www.acme.com/")
1221 res = FakeResponse(headers, "https://www.acme.com/")
1222 c.extract_cookies(res, req)
1223 self.assertEqual(len(c), 1)
1224
1225 # test https removed from secure protocol list
1226 req = urllib.request.Request("https://www.acme.com/")
1227 c.add_cookie_header(req)
1228 self.assertFalse(req.has_header("Cookie"))
1229
1230 req = urllib.request.Request("http://www.acme.com/")
1231 c.add_cookie_header(req)
1232 self.assertFalse(req.has_header("Cookie"))
1233
1234 req = urllib.request.Request("foos://www.acme.com/")
1235 c.add_cookie_header(req)
1236 self.assertTrue(req.has_header("Cookie"))
1237
1238 req = urllib.request.Request("foo://www.acme.com/")
1239 c.add_cookie_header(req)
1240 self.assertFalse(req.has_header("Cookie"))
1241
1242 def test_quote_cookie_value(self):
1243 c = CookieJar(policy=DefaultCookiePolicy(rfc2965=True))
1244 interact_2965(c, "http://www.acme.com/", r'foo=\b"a"r; Version=1')
1245 h = interact_2965(c, "http://www.acme.com/")
1246 self.assertEqual(h, r'$Version=1; foo=\\b\"a\"r')
1247
1248 def test_missing_final_slash(self):
1249 # Missing slash from request URL's abs_path should be assumed present.
1250 url = "http://www.acme.com"
1251 c = CookieJar(DefaultCookiePolicy(rfc2965=True))
1252 interact_2965(c, url, "foo=bar; Version=1")
1253 req = urllib.request.Request(url)
1254 self.assertEqual(len(c), 1)
1255 c.add_cookie_header(req)
1256 self.assertTrue(req.has_header("Cookie"))
1257
1258 def test_domain_mirror(self):
1259 pol = DefaultCookiePolicy(rfc2965=True)
1260
1261 c = CookieJar(pol)
1262 url = "http://foo.bar.com/"
1263 interact_2965(c, url, "spam=eggs; Version=1")
1264 h = interact_2965(c, url)
1265 self.assertNotIn("Domain", h,
1266 "absent domain returned with domain present")
1267
1268 c = CookieJar(pol)
1269 url = "http://foo.bar.com/"
1270 interact_2965(c, url, 'spam=eggs; Version=1; Domain=.bar.com')
1271 h = interact_2965(c, url)
1272 self.assertIn('$Domain=".bar.com"', h, "domain not returned")
1273
1274 c = CookieJar(pol)
1275 url = "http://foo.bar.com/"
1276 # note missing initial dot in Domain
1277 interact_2965(c, url, 'spam=eggs; Version=1; Domain=bar.com')
1278 h = interact_2965(c, url)
1279 self.assertIn('$Domain="bar.com"', h, "domain not returned")
1280
1281 def test_path_mirror(self):
1282 pol = DefaultCookiePolicy(rfc2965=True)
1283
1284 c = CookieJar(pol)
1285 url = "http://foo.bar.com/"
1286 interact_2965(c, url, "spam=eggs; Version=1")
1287 h = interact_2965(c, url)
1288 self.assertNotIn("Path", h, "absent path returned with path present")
1289
1290 c = CookieJar(pol)
1291 url = "http://foo.bar.com/"
1292 interact_2965(c, url, 'spam=eggs; Version=1; Path=/')
1293 h = interact_2965(c, url)
1294 self.assertIn('$Path="/"', h, "path not returned")
1295
1296 def test_port_mirror(self):
1297 pol = DefaultCookiePolicy(rfc2965=True)
1298
1299 c = CookieJar(pol)
1300 url = "http://foo.bar.com/"
1301 interact_2965(c, url, "spam=eggs; Version=1")
1302 h = interact_2965(c, url)
1303 self.assertNotIn("Port", h, "absent port returned with port present")
1304
1305 c = CookieJar(pol)
1306 url = "http://foo.bar.com/"
1307 interact_2965(c, url, "spam=eggs; Version=1; Port")
1308 h = interact_2965(c, url)
1309 self.assertRegex(h, r"\$Port([^=]|$)",
1310 "port with no value not returned with no value")
1311
1312 c = CookieJar(pol)
1313 url = "http://foo.bar.com/"
1314 interact_2965(c, url, 'spam=eggs; Version=1; Port="80"')
1315 h = interact_2965(c, url)
1316 self.assertIn('$Port="80"', h,
1317 "port with single value not returned with single value")
1318
1319 c = CookieJar(pol)
1320 url = "http://foo.bar.com/"
1321 interact_2965(c, url, 'spam=eggs; Version=1; Port="80,8080"')
1322 h = interact_2965(c, url)
1323 self.assertIn('$Port="80,8080"', h,
1324 "port with multiple values not returned with multiple "
1325 "values")
1326
1327 def test_no_return_comment(self):
1328 c = CookieJar(DefaultCookiePolicy(rfc2965=True))
1329 url = "http://foo.bar.com/"
1330 interact_2965(c, url, 'spam=eggs; Version=1; '
1331 'Comment="does anybody read these?"; '
1332 'CommentURL="http://foo.bar.net/comment.html"')
1333 h = interact_2965(c, url)
1334 self.assertNotIn("Comment", h,
1335 "Comment or CommentURL cookie-attributes returned to server")
1336
1337 def test_Cookie_iterator(self):
1338 cs = CookieJar(DefaultCookiePolicy(rfc2965=True))
1339 # add some random cookies
1340 interact_2965(cs, "http://blah.spam.org/", 'foo=eggs; Version=1; '
1341 'Comment="does anybody read these?"; '
1342 'CommentURL="http://foo.bar.net/comment.html"')
1343 interact_netscape(cs, "http://www.acme.com/blah/", "spam=bar; secure")
1344 interact_2965(cs, "http://www.acme.com/blah/",
1345 "foo=bar; secure; Version=1")
1346 interact_2965(cs, "http://www.acme.com/blah/",
1347 "foo=bar; path=/; Version=1")
1348 interact_2965(cs, "http://www.sol.no",
1349 r'bang=wallop; version=1; domain=".sol.no"; '
1350 r'port="90,100, 80,8080"; '
1351 r'max-age=100; Comment = "Just kidding! (\"|\\\\) "')
1352
1353 versions = [1, 0, 1, 1, 1]
1354 names = ["foo", "spam", "foo", "foo", "bang"]
1355 domains = ["blah.spam.org", "www.acme.com", "www.acme.com",
1356 "www.acme.com", ".sol.no"]
1357 paths = ["/", "/blah", "/blah/", "/", "/"]
1358
1359 for i in range(4):
1360 i = 0
1361 for c in cs:
1362 self.assertIsInstance(c, Cookie)
1363 self.assertEqual(c.version, versions[i])
1364 self.assertEqual(c.name, names[i])
1365 self.assertEqual(c.domain, domains[i])
1366 self.assertEqual(c.path, paths[i])
1367 i = i + 1
1368
1369 def test_parse_ns_headers(self):
1370 # missing domain value (invalid cookie)
1371 self.assertEqual(
1372 parse_ns_headers(["foo=bar; path=/; domain"]),
1373 [[("foo", "bar"),
1374 ("path", "/"), ("domain", None), ("version", "0")]]
1375 )
1376 # invalid expires value
1377 self.assertEqual(
1378 parse_ns_headers(["foo=bar; expires=Foo Bar 12 33:22:11 2000"]),
1379 [[("foo", "bar"), ("expires", None), ("version", "0")]]
1380 )
1381 # missing cookie value (valid cookie)
1382 self.assertEqual(
1383 parse_ns_headers(["foo"]),
1384 [[("foo", None), ("version", "0")]]
1385 )
1386 # missing cookie values for parsed attributes
1387 self.assertEqual(
1388 parse_ns_headers(['foo=bar; expires']),
1389 [[('foo', 'bar'), ('expires', None), ('version', '0')]])
1390 self.assertEqual(
1391 parse_ns_headers(['foo=bar; version']),
1392 [[('foo', 'bar'), ('version', None)]])
1393 # shouldn't add version if header is empty
1394 self.assertEqual(parse_ns_headers([""]), [])
1395
1396 def test_bad_cookie_header(self):
1397
1398 def cookiejar_from_cookie_headers(headers):
1399 c = CookieJar()
1400 req = urllib.request.Request("http://www.example.com/")
1401 r = FakeResponse(headers, "http://www.example.com/")
1402 c.extract_cookies(r, req)
1403 return c
1404
1405 future = time2netscape(time.time()+3600)
1406
1407 # none of these bad headers should cause an exception to be raised
1408 for headers in [
1409 ["Set-Cookie: "], # actually, nothing wrong with this
1410 ["Set-Cookie2: "], # ditto
1411 # missing domain value
1412 ["Set-Cookie2: a=foo; path=/; Version=1; domain"],
1413 # bad max-age
1414 ["Set-Cookie: b=foo; max-age=oops"],
1415 # bad version
1416 ["Set-Cookie: b=foo; version=spam"],
1417 ["Set-Cookie:; Expires=%s" % future],
1418 ]:
1419 c = cookiejar_from_cookie_headers(headers)
1420 # these bad cookies shouldn't be set
1421 self.assertEqual(len(c), 0)
1422
1423 # cookie with invalid expires is treated as session cookie
1424 headers = ["Set-Cookie: c=foo; expires=Foo Bar 12 33:22:11 2000"]
1425 c = cookiejar_from_cookie_headers(headers)
1426 cookie = c._cookies["www.example.com"]["/"]["c"]
1427 self.assertIsNone(cookie.expires)
1428
1429
1430 class LWPCookieTests(unittest.TestCase, ExtraAssertions):
1431 # Tests taken from libwww-perl, with a few modifications and additions.
1432
1433 def test_netscape_example_1(self):
1434 #-------------------------------------------------------------------
1435 # First we check that it works for the original example at
1436 # http://www.netscape.com/newsref/std/cookie_spec.html
1437
1438 # Client requests a document, and receives in the response:
1439 #
1440 # Set-Cookie: CUSTOMER=WILE_E_COYOTE; path=/; expires=Wednesday, 09-Nov-99 23:12:40 GMT
1441 #
1442 # When client requests a URL in path "/" on this server, it sends:
1443 #
1444 # Cookie: CUSTOMER=WILE_E_COYOTE
1445 #
1446 # Client requests a document, and receives in the response:
1447 #
1448 # Set-Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001; path=/
1449 #
1450 # When client requests a URL in path "/" on this server, it sends:
1451 #
1452 # Cookie: CUSTOMER=WILE_E_COYOTE; PART_NUMBER=ROCKET_LAUNCHER_0001
1453 #
1454 # Client receives:
1455 #
1456 # Set-Cookie: SHIPPING=FEDEX; path=/fo
1457 #
1458 # When client requests a URL in path "/" on this server, it sends:
1459 #
1460 # Cookie: CUSTOMER=WILE_E_COYOTE; PART_NUMBER=ROCKET_LAUNCHER_0001
1461 #
1462 # When client requests a URL in path "/foo" on this server, it sends:
1463 #
1464 # Cookie: CUSTOMER=WILE_E_COYOTE; PART_NUMBER=ROCKET_LAUNCHER_0001; SHIPPING=FEDEX
1465 #
1466 # The last Cookie is buggy, because both specifications say that the
1467 # most specific cookie must be sent first. SHIPPING=FEDEX is the
1468 # most specific and should thus be first.
1469
1470 year_plus_one = time.localtime()[0] + 1
1471
1472 headers = []
1473
1474 c = CookieJar(DefaultCookiePolicy(rfc2965 = True))
1475
1476 #req = urllib.request.Request("http://1.1.1.1/",
1477 # headers={"Host": "www.acme.com:80"})
1478 req = urllib.request.Request("http://www.acme.com:80/",
1479 headers={"Host": "www.acme.com:80"})
1480
1481 headers.append(
1482 "Set-Cookie: CUSTOMER=WILE_E_COYOTE; path=/ ; "
1483 "expires=Wednesday, 09-Nov-%d 23:12:40 GMT" % year_plus_one)
1484 res = FakeResponse(headers, "http://www.acme.com/")
1485 c.extract_cookies(res, req)
1486
1487 req = urllib.request.Request("http://www.acme.com/")
1488 c.add_cookie_header(req)
1489
1490 self.assertEqual(req.get_header("Cookie"), "CUSTOMER=WILE_E_COYOTE")
1491 self.assertEqual(req.get_header("Cookie2"), '$Version="1"')
1492
1493 headers.append("Set-Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001; path=/")
1494 res = FakeResponse(headers, "http://www.acme.com/")
1495 c.extract_cookies(res, req)
1496
1497 req = urllib.request.Request("http://www.acme.com/foo/bar")
1498 c.add_cookie_header(req)
1499
1500 h = req.get_header("Cookie")
1501 self.assertIn("PART_NUMBER=ROCKET_LAUNCHER_0001", h)
1502 self.assertIn("CUSTOMER=WILE_E_COYOTE", h)
1503
1504 headers.append('Set-Cookie: SHIPPING=FEDEX; path=/foo')
1505 res = FakeResponse(headers, "http://www.acme.com")
1506 c.extract_cookies(res, req)
1507
1508 req = urllib.request.Request("http://www.acme.com/")
1509 c.add_cookie_header(req)
1510
1511 h = req.get_header("Cookie")
1512 self.assertIn("PART_NUMBER=ROCKET_LAUNCHER_0001", h)
1513 self.assertIn("CUSTOMER=WILE_E_COYOTE", h)
1514 self.assertNotIn("SHIPPING=FEDEX", h)
1515
1516 req = urllib.request.Request("http://www.acme.com/foo/")
1517 c.add_cookie_header(req)
1518
1519 h = req.get_header("Cookie")
1520 self.assertIn("PART_NUMBER=ROCKET_LAUNCHER_0001", h)
1521 self.assertIn("CUSTOMER=WILE_E_COYOTE", h)
1522 self.assertStartsWith(h, "SHIPPING=FEDEX;")
1523
1524 def test_netscape_example_2(self):
1525 # Second Example transaction sequence:
1526 #
1527 # Assume all mappings from above have been cleared.
1528 #
1529 # Client receives:
1530 #
1531 # Set-Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001; path=/
1532 #
1533 # When client requests a URL in path "/" on this server, it sends:
1534 #
1535 # Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001
1536 #
1537 # Client receives:
1538 #
1539 # Set-Cookie: PART_NUMBER=RIDING_ROCKET_0023; path=/ammo
1540 #
1541 # When client requests a URL in path "/ammo" on this server, it sends:
1542 #
1543 # Cookie: PART_NUMBER=RIDING_ROCKET_0023; PART_NUMBER=ROCKET_LAUNCHER_0001
1544 #
1545 # NOTE: There are two name/value pairs named "PART_NUMBER" due to
1546 # the inheritance of the "/" mapping in addition to the "/ammo" mapping.
1547
1548 c = CookieJar()
1549 headers = []
1550
1551 req = urllib.request.Request("http://www.acme.com/")
1552 headers.append("Set-Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001; path=/")
1553 res = FakeResponse(headers, "http://www.acme.com/")
1554
1555 c.extract_cookies(res, req)
1556
1557 req = urllib.request.Request("http://www.acme.com/")
1558 c.add_cookie_header(req)
1559
1560 self.assertEqual(req.get_header("Cookie"),
1561 "PART_NUMBER=ROCKET_LAUNCHER_0001")
1562
1563 headers.append(
1564 "Set-Cookie: PART_NUMBER=RIDING_ROCKET_0023; path=/ammo")
1565 res = FakeResponse(headers, "http://www.acme.com/")
1566 c.extract_cookies(res, req)
1567
1568 req = urllib.request.Request("http://www.acme.com/ammo")
1569 c.add_cookie_header(req)
1570
1571 self.assertRegex(req.get_header("Cookie"),
1572 r"PART_NUMBER=RIDING_ROCKET_0023;\s*"
1573 "PART_NUMBER=ROCKET_LAUNCHER_0001")
1574
1575 def test_ietf_example_1(self):
1576 #-------------------------------------------------------------------
1577 # Then we test with the examples from draft-ietf-http-state-man-mec-03.txt
1578 #
1579 # 5. EXAMPLES
1580
1581 c = CookieJar(DefaultCookiePolicy(rfc2965=True))
1582
1583 #
1584 # 5.1 Example 1
1585 #
1586 # Most detail of request and response headers has been omitted. Assume
1587 # the user agent has no stored cookies.
1588 #
1589 # 1. User Agent -> Server
1590 #
1591 # POST /acme/login HTTP/1.1
1592 # [form data]
1593 #
1594 # User identifies self via a form.
1595 #
1596 # 2. Server -> User Agent
1597 #
1598 # HTTP/1.1 200 OK
1599 # Set-Cookie2: Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"
1600 #
1601 # Cookie reflects user's identity.
1602
1603 cookie = interact_2965(
1604 c, 'http://www.acme.com/acme/login',
1605 'Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"')
1606 self.assertFalse(cookie)
1607
1608 #
1609 # 3. User Agent -> Server
1610 #
1611 # POST /acme/pickitem HTTP/1.1
1612 # Cookie: $Version="1"; Customer="WILE_E_COYOTE"; $Path="/acme"
1613 # [form data]
1614 #
1615 # User selects an item for ``shopping basket.''
1616 #
1617 # 4. Server -> User Agent
1618 #
1619 # HTTP/1.1 200 OK
1620 # Set-Cookie2: Part_Number="Rocket_Launcher_0001"; Version="1";
1621 # Path="/acme"
1622 #
1623 # Shopping basket contains an item.
1624
1625 cookie = interact_2965(c, 'http://www.acme.com/acme/pickitem',
1626 'Part_Number="Rocket_Launcher_0001"; '
1627 'Version="1"; Path="/acme"');
1628 self.assertRegex(cookie,
1629 r'^\$Version="?1"?; Customer="?WILE_E_COYOTE"?; \$Path="/acme"$')
1630
1631 #
1632 # 5. User Agent -> Server
1633 #
1634 # POST /acme/shipping HTTP/1.1
1635 # Cookie: $Version="1";
1636 # Customer="WILE_E_COYOTE"; $Path="/acme";
1637 # Part_Number="Rocket_Launcher_0001"; $Path="/acme"
1638 # [form data]
1639 #
1640 # User selects shipping method from form.
1641 #
1642 # 6. Server -> User Agent
1643 #
1644 # HTTP/1.1 200 OK
1645 # Set-Cookie2: Shipping="FedEx"; Version="1"; Path="/acme"
1646 #
1647 # New cookie reflects shipping method.
1648
1649 cookie = interact_2965(c, "http://www.acme.com/acme/shipping",
1650 'Shipping="FedEx"; Version="1"; Path="/acme"')
1651
1652 self.assertRegex(cookie, r'^\$Version="?1"?;')
1653 self.assertRegex(cookie, r'Part_Number="?Rocket_Launcher_0001"?;'
1654 r'\s*\$Path="\/acme"')
1655 self.assertRegex(cookie, r'Customer="?WILE_E_COYOTE"?;'
1656 r'\s*\$Path="\/acme"')
1657
1658 #
1659 # 7. User Agent -> Server
1660 #
1661 # POST /acme/process HTTP/1.1
1662 # Cookie: $Version="1";
1663 # Customer="WILE_E_COYOTE"; $Path="/acme";
1664 # Part_Number="Rocket_Launcher_0001"; $Path="/acme";
1665 # Shipping="FedEx"; $Path="/acme"
1666 # [form data]
1667 #
1668 # User chooses to process order.
1669 #
1670 # 8. Server -> User Agent
1671 #
1672 # HTTP/1.1 200 OK
1673 #
1674 # Transaction is complete.
1675
1676 cookie = interact_2965(c, "http://www.acme.com/acme/process")
1677 self.assertRegex(cookie, r'Shipping="?FedEx"?;\s*\$Path="\/acme"')
1678 self.assertIn("WILE_E_COYOTE", cookie)
1679
1680 #
1681 # The user agent makes a series of requests on the origin server, after
1682 # each of which it receives a new cookie. All the cookies have the same
1683 # Path attribute and (default) domain. Because the request URLs all have
1684 # /acme as a prefix, and that matches the Path attribute, each request
1685 # contains all the cookies received so far.
1686
1687 def test_ietf_example_2(self):
1688 # 5.2 Example 2
1689 #
1690 # This example illustrates the effect of the Path attribute. All detail
1691 # of request and response headers has been omitted. Assume the user agent
1692 # has no stored cookies.
1693
1694 c = CookieJar(DefaultCookiePolicy(rfc2965=True))
1695
1696 # Imagine the user agent has received, in response to earlier requests,
1697 # the response headers
1698 #
1699 # Set-Cookie2: Part_Number="Rocket_Launcher_0001"; Version="1";
1700 # Path="/acme"
1701 #
1702 # and
1703 #
1704 # Set-Cookie2: Part_Number="Riding_Rocket_0023"; Version="1";
1705 # Path="/acme/ammo"
1706
1707 interact_2965(
1708 c, "http://www.acme.com/acme/ammo/specific",
1709 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"',
1710 'Part_Number="Riding_Rocket_0023"; Version="1"; Path="/acme/ammo"')
1711
1712 # A subsequent request by the user agent to the (same) server for URLs of
1713 # the form /acme/ammo/... would include the following request header:
1714 #
1715 # Cookie: $Version="1";
1716 # Part_Number="Riding_Rocket_0023"; $Path="/acme/ammo";
1717 # Part_Number="Rocket_Launcher_0001"; $Path="/acme"
1718 #
1719 # Note that the NAME=VALUE pair for the cookie with the more specific Path
1720 # attribute, /acme/ammo, comes before the one with the less specific Path
1721 # attribute, /acme. Further note that the same cookie name appears more
1722 # than once.
1723
1724 cookie = interact_2965(c, "http://www.acme.com/acme/ammo/...")
1725 self.assertRegex(cookie, r"Riding_Rocket_0023.*Rocket_Launcher_0001")
1726
1727 # A subsequent request by the user agent to the (same) server for a URL of
1728 # the form /acme/parts/ would include the following request header:
1729 #
1730 # Cookie: $Version="1"; Part_Number="Rocket_Launcher_0001"; $Path="/acme"
1731 #
1732 # Here, the second cookie's Path attribute /acme/ammo is not a prefix of
1733 # the request URL, /acme/parts/, so the cookie does not get forwarded to
1734 # the server.
1735
1736 cookie = interact_2965(c, "http://www.acme.com/acme/parts/")
1737 self.assertIn("Rocket_Launcher_0001", cookie)
1738 self.assertNotIn("Riding_Rocket_0023", cookie)
1739
1740 def test_rejection(self):
1741 # Test rejection of Set-Cookie2 responses based on domain, path, port.
1742 pol = DefaultCookiePolicy(rfc2965=True)
1743
1744 c = LWPCookieJar(policy=pol)
1745
1746 max_age = "max-age=3600"
1747
1748 # illegal domain (no embedded dots)
1749 cookie = interact_2965(c, "http://www.acme.com",
1750 'foo=bar; domain=".com"; version=1')
1751 self.assertFalse(c)
1752
1753 # legal domain
1754 cookie = interact_2965(c, "http://www.acme.com",
1755 'ping=pong; domain="acme.com"; version=1')
1756 self.assertEqual(len(c), 1)
1757
1758 # illegal domain (host prefix "www.a" contains a dot)
1759 cookie = interact_2965(c, "http://www.a.acme.com",
1760 'whiz=bang; domain="acme.com"; version=1')
1761 self.assertEqual(len(c), 1)
1762
1763 # legal domain
1764 cookie = interact_2965(c, "http://www.a.acme.com",
1765 'wow=flutter; domain=".a.acme.com"; version=1')
1766 self.assertEqual(len(c), 2)
1767
1768 # can't partially match an IP-address
1769 cookie = interact_2965(c, "http://125.125.125.125",
1770 'zzzz=ping; domain="125.125.125"; version=1')
1771 self.assertEqual(len(c), 2)
1772
1773 # illegal path (must be prefix of request path)
1774 cookie = interact_2965(c, "http://www.sol.no",
1775 'blah=rhubarb; domain=".sol.no"; path="/foo"; '
1776 'version=1')
1777 self.assertEqual(len(c), 2)
1778
1779 # legal path
1780 cookie = interact_2965(c, "http://www.sol.no/foo/bar",
1781 'bing=bong; domain=".sol.no"; path="/foo"; '
1782 'version=1')
1783 self.assertEqual(len(c), 3)
1784
1785 # illegal port (request-port not in list)
1786 cookie = interact_2965(c, "http://www.sol.no",
1787 'whiz=ffft; domain=".sol.no"; port="90,100"; '
1788 'version=1')
1789 self.assertEqual(len(c), 3)
1790
1791 # legal port
1792 cookie = interact_2965(
1793 c, "http://www.sol.no",
1794 r'bang=wallop; version=1; domain=".sol.no"; '
1795 r'port="90,100, 80,8080"; '
1796 r'max-age=100; Comment = "Just kidding! (\"|\\\\) "')
1797 self.assertEqual(len(c), 4)
1798
1799 # port attribute without any value (current port)
1800 cookie = interact_2965(c, "http://www.sol.no",
1801 'foo9=bar; version=1; domain=".sol.no"; port; '
1802 'max-age=100;')
1803 self.assertEqual(len(c), 5)
1804
1805 # encoded path
1806 # LWP has this test, but unescaping allowed path characters seems
1807 # like a bad idea, so I think this should fail:
1808 ## cookie = interact_2965(c, "http://www.sol.no/foo/",
1809 ## r'foo8=bar; version=1; path="/%66oo"')
1810 # but this is OK, because '<' is not an allowed HTTP URL path
1811 # character:
1812 cookie = interact_2965(c, "http://www.sol.no/<oo/",
1813 r'foo8=bar; version=1; path="/%3coo"')
1814 self.assertEqual(len(c), 6)
1815
1816 # save and restore
1817 filename = os_helper.TESTFN
1818
1819 try:
1820 c.save(filename, ignore_discard=True)
1821 old = repr(c)
1822
1823 c = LWPCookieJar(policy=pol)
1824 c.load(filename, ignore_discard=True)
1825 finally:
1826 os_helper.unlink(filename)
1827
1828 self.assertEqual(old, repr(c))
1829
1830 def test_url_encoding(self):
1831 # Try some URL encodings of the PATHs.
1832 # (the behaviour here has changed from libwww-perl)
1833 c = CookieJar(DefaultCookiePolicy(rfc2965=True))
1834 interact_2965(c, "http://www.acme.com/foo%2f%25/"
1835 "%3c%3c%0Anew%C3%A5/%C3%A5",
1836 "foo = bar; version = 1")
1837
1838 cookie = interact_2965(
1839 c, "http://www.acme.com/foo%2f%25/<<%0anew\345/\346\370\345",
1840 'bar=baz; path="/foo/"; version=1');
1841 version_re = re.compile(r'^\$version=\"?1\"?', re.I)
1842 self.assertIn("foo=bar", cookie)
1843 self.assertRegex(cookie, version_re)
1844
1845 cookie = interact_2965(
1846 c, "http://www.acme.com/foo/%25/<<%0anew\345/\346\370\345")
1847 self.assertFalse(cookie)
1848
1849 # unicode URL doesn't raise exception
1850 cookie = interact_2965(c, "http://www.acme.com/\xfc")
1851
1852 def test_mozilla(self):
1853 # Save / load Mozilla/Netscape cookie file format.
1854 year_plus_one = time.localtime()[0] + 1
1855
1856 filename = os_helper.TESTFN
1857
1858 c = MozillaCookieJar(filename,
1859 policy=DefaultCookiePolicy(rfc2965=True))
1860 interact_2965(c, "http://www.acme.com/",
1861 "foo1=bar; max-age=100; Version=1")
1862 interact_2965(c, "http://www.acme.com/",
1863 'foo2=bar; port="80"; max-age=100; Discard; Version=1')
1864 interact_2965(c, "http://www.acme.com/", "foo3=bar; secure; Version=1")
1865
1866 expires = "expires=09-Nov-%d 23:12:40 GMT" % (year_plus_one,)
1867 interact_netscape(c, "http://www.foo.com/",
1868 "fooa=bar; %s" % expires)
1869 interact_netscape(c, "http://www.foo.com/",
1870 "foob=bar; Domain=.foo.com; %s" % expires)
1871 interact_netscape(c, "http://www.foo.com/",
1872 "fooc=bar; Domain=www.foo.com; %s" % expires)
1873
1874 for cookie in c:
1875 if cookie.name == "foo1":
1876 cookie.set_nonstandard_attr("HTTPOnly", "")
1877
1878 def save_and_restore(cj, ignore_discard):
1879 try:
1880 cj.save(ignore_discard=ignore_discard)
1881 new_c = MozillaCookieJar(filename,
1882 DefaultCookiePolicy(rfc2965=True))
1883 new_c.load(ignore_discard=ignore_discard)
1884 finally:
1885 os_helper.unlink(filename)
1886 return new_c
1887
1888 new_c = save_and_restore(c, True)
1889 self.assertEqual(len(new_c), 6) # none discarded
1890 self.assertIn("name='foo1', value='bar'", repr(new_c))
1891 self.assertIn("rest={'HTTPOnly': ''}", repr(new_c))
1892
1893 new_c = save_and_restore(c, False)
1894 self.assertEqual(len(new_c), 4) # 2 of them discarded on save
1895 self.assertIn("name='foo1', value='bar'", repr(new_c))
1896
1897 def test_netscape_misc(self):
1898 # Some additional Netscape cookies tests.
1899 c = CookieJar()
1900 headers = []
1901 req = urllib.request.Request("http://foo.bar.acme.com/foo")
1902
1903 # Netscape allows a host part that contains dots
1904 headers.append("Set-Cookie: Customer=WILE_E_COYOTE; domain=.acme.com")
1905 res = FakeResponse(headers, "http://www.acme.com/foo")
1906 c.extract_cookies(res, req)
1907
1908 # and that the domain is the same as the host without adding a leading
1909 # dot to the domain. Should not quote even if strange chars are used
1910 # in the cookie value.
1911 headers.append("Set-Cookie: PART_NUMBER=3,4; domain=foo.bar.acme.com")
1912 res = FakeResponse(headers, "http://www.acme.com/foo")
1913 c.extract_cookies(res, req)
1914
1915 req = urllib.request.Request("http://foo.bar.acme.com/foo")
1916 c.add_cookie_header(req)
1917 self.assertIn("PART_NUMBER=3,4", req.get_header("Cookie"))
1918 self.assertIn("Customer=WILE_E_COYOTE",req.get_header("Cookie"))
1919
1920 def test_intranet_domains_2965(self):
1921 # Test handling of local intranet hostnames without a dot.
1922 c = CookieJar(DefaultCookiePolicy(rfc2965=True))
1923 interact_2965(c, "http://example/",
1924 "foo1=bar; PORT; Discard; Version=1;")
1925 cookie = interact_2965(c, "http://example/",
1926 'foo2=bar; domain=".local"; Version=1')
1927 self.assertIn("foo1=bar", cookie)
1928
1929 interact_2965(c, "http://example/", 'foo3=bar; Version=1')
1930 cookie = interact_2965(c, "http://example/")
1931 self.assertIn("foo2=bar", cookie)
1932 self.assertEqual(len(c), 3)
1933
1934 def test_intranet_domains_ns(self):
1935 c = CookieJar(DefaultCookiePolicy(rfc2965 = False))
1936 interact_netscape(c, "http://example/", "foo1=bar")
1937 cookie = interact_netscape(c, "http://example/",
1938 'foo2=bar; domain=.local')
1939 self.assertEqual(len(c), 2)
1940 self.assertIn("foo1=bar", cookie)
1941
1942 cookie = interact_netscape(c, "http://example/")
1943 self.assertIn("foo2=bar", cookie)
1944 self.assertEqual(len(c), 2)
1945
1946 def test_empty_path(self):
1947 # Test for empty path
1948 # Broken web-server ORION/1.3.38 returns to the client response like
1949 #
1950 # Set-Cookie: JSESSIONID=ABCDERANDOM123; Path=
1951 #
1952 # ie. with Path set to nothing.
1953 # In this case, extract_cookies() must set cookie to / (root)
1954 c = CookieJar(DefaultCookiePolicy(rfc2965 = True))
1955 headers = []
1956
1957 req = urllib.request.Request("http://www.ants.com/")
1958 headers.append("Set-Cookie: JSESSIONID=ABCDERANDOM123; Path=")
1959 res = FakeResponse(headers, "http://www.ants.com/")
1960 c.extract_cookies(res, req)
1961
1962 req = urllib.request.Request("http://www.ants.com/")
1963 c.add_cookie_header(req)
1964
1965 self.assertEqual(req.get_header("Cookie"),
1966 "JSESSIONID=ABCDERANDOM123")
1967 self.assertEqual(req.get_header("Cookie2"), '$Version="1"')
1968
1969 # missing path in the request URI
1970 req = urllib.request.Request("http://www.ants.com:8080")
1971 c.add_cookie_header(req)
1972
1973 self.assertEqual(req.get_header("Cookie"),
1974 "JSESSIONID=ABCDERANDOM123")
1975 self.assertEqual(req.get_header("Cookie2"), '$Version="1"')
1976
1977 def test_session_cookies(self):
1978 year_plus_one = time.localtime()[0] + 1
1979
1980 # Check session cookies are deleted properly by
1981 # CookieJar.clear_session_cookies method
1982
1983 req = urllib.request.Request('http://www.perlmeister.com/scripts')
1984 headers = []
1985 headers.append("Set-Cookie: s1=session;Path=/scripts")
1986 headers.append("Set-Cookie: p1=perm; Domain=.perlmeister.com;"
1987 "Path=/;expires=Fri, 02-Feb-%d 23:24:20 GMT" %
1988 year_plus_one)
1989 headers.append("Set-Cookie: p2=perm;Path=/;expires=Fri, "
1990 "02-Feb-%d 23:24:20 GMT" % year_plus_one)
1991 headers.append("Set-Cookie: s2=session;Path=/scripts;"
1992 "Domain=.perlmeister.com")
1993 headers.append('Set-Cookie2: s3=session;Version=1;Discard;Path="/"')
1994 res = FakeResponse(headers, 'http://www.perlmeister.com/scripts')
1995
1996 c = CookieJar()
1997 c.extract_cookies(res, req)
1998 # How many session/permanent cookies do we have?
1999 counter = {"session_after": 0,
2000 "perm_after": 0,
2001 "session_before": 0,
2002 "perm_before": 0}
2003 for cookie in c:
2004 key = "%s_before" % cookie.value
2005 counter[key] = counter[key] + 1
2006 c.clear_session_cookies()
2007 # How many now?
2008 for cookie in c:
2009 key = "%s_after" % cookie.value
2010 counter[key] = counter[key] + 1
2011
2012 # a permanent cookie got lost accidentally
2013 self.assertEqual(counter["perm_after"], counter["perm_before"])
2014 # a session cookie hasn't been cleared
2015 self.assertEqual(counter["session_after"], 0)
2016 # we didn't have session cookies in the first place
2017 self.assertNotEqual(counter["session_before"], 0)
2018
2019
2020 if __name__ == "__main__":
2021 unittest.main()