Skip to content

Commit 8f2c05d

Browse files
pythongh-108931: Remove expired cookies stored without a leading dot
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent dcf9087 commit 8f2c05d

3 files changed

Lines changed: 30 additions & 4 deletions

File tree

‎Lib/http/cookiejar.py‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1586,10 +1586,17 @@ def _cookie_from_cookie_tuple(self, tup, request):
15861586
# attribute does not match the request host (step 6) before an
15871587
# existing cookie is removed (steps 11-12)
15881588
if self._policy.set_ok(cookie, request):
1589-
try:
1590-
self.clear(domain, path, name)
1591-
except KeyError:
1592-
pass
1589+
domains = [domain]
1590+
if domain_specified:
1591+
# RFC 6265 ignores a leading dot in the Domain
1592+
# attribute, so also remove a matching cookie stored
1593+
# without it, e.g. one added with set_cookie().
1594+
domains.append(domain[1:])
1595+
for d in domains:
1596+
try:
1597+
self.clear(d, path, name)
1598+
except KeyError:
1599+
pass
15931600
_debug("Expiring cookie, domain='%s', path='%s', name='%s'",
15941601
domain, path, name)
15951602
return None

‎Lib/test/test_http_cookiejar.py‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -686,6 +686,21 @@ def test_ns_parser_special_names(self):
686686
self.assertIn('expires', cookies)
687687
self.assertIn('version', cookies)
688688

689+
def test_expire_cookie_set_without_leading_dot(self):
690+
# gh-108931: An expired cookie with a Domain attribute must also
691+
# remove a matching cookie stored without the leading dot, for
692+
# example one added with set_cookie(). RFC 6265 ignores the dot.
693+
for attr in ("www.acme.com", ".www.acme.com"):
694+
with self.subTest(domain=attr):
695+
c = CookieJar()
696+
c.set_cookie(Cookie(0, "foo", "bar", None, False,
697+
"www.acme.com", True, False, "/", True,
698+
False, None, False, None, None, {}))
699+
self.assertEqual(len(c), 1)
700+
interact_netscape(c, "http://www.acme.com/",
701+
f"foo=; Domain={attr}; Path=/; Max-Age=0")
702+
self.assertEqual(len(c), 0)
703+
689704
def test_expires(self):
690705
# if expires is in future, keep cookie...
691706
c = CookieJar()
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Fix :class:`http.cookiejar.CookieJar` not removing an expired cookie whose
2+
domain was stored without a leading dot, for example a cookie added with
3+
:meth:`~http.cookiejar.CookieJar.set_cookie`, when the server expires it with a
4+
Domain attribute.

0 commit comments

Comments
 (0)