diff --git a/Lib/http/cookies.py b/Lib/http/cookies.py index 9a6f01dfb5e69a..2f13d4f37a2667 100644 --- a/Lib/http/cookies.py +++ b/Lib/http/cookies.py @@ -618,6 +618,8 @@ def __parse_string(self, str, patt=_CookiePattern): else: parsed_items.append((TYPE_ATTRIBUTE, key, _unquote(value))) elif value is not None: + if not _is_legal_key(key): + raise CookieError('Illegal key %r' % (key,)) parsed_items.append((TYPE_KEYVALUE, key, self.value_decode(value))) morsel_seen = True else: diff --git a/Lib/test/test_http_cookies.py b/Lib/test/test_http_cookies.py index d1df2ec42f0d14..7fde0bf46d5eb3 100644 --- a/Lib/test/test_http_cookies.py +++ b/Lib/test/test_http_cookies.py @@ -320,6 +320,12 @@ def test_illegal_chars(self): with self.assertRaises(cookies.CookieError): C.load(rawdata) + def test_illegal_key_no_partial_state(self): + C = cookies.SimpleCookie() + with self.assertRaises(cookies.CookieError): + C.load("a=1; b,c=2; d=3") + self.assertEqual(len(C), 0) + def test_comment_quoting(self): c = cookies.SimpleCookie() c['foo'] = '\N{COPYRIGHT SIGN}' diff --git a/Misc/NEWS.d/next/Library/2026-07-18-12-00-00.gh-issue-154546.CkPrt5.rst b/Misc/NEWS.d/next/Library/2026-07-18-12-00-00.gh-issue-154546.CkPrt5.rst new file mode 100644 index 00000000000000..cfbb9b63a2bb19 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-07-18-12-00-00.gh-issue-154546.CkPrt5.rst @@ -0,0 +1,4 @@ +Validate cookie key characters during parsing in +:meth:`http.cookies.BaseCookie.load` so that an illegal key raises +:exc:`~http.cookies.CookieError` before any cookies are applied. Patch by +tonghuaroot.