From 5946c7436044bae14617ef06ee7c530ed72622da Mon Sep 17 00:00:00 2001 From: Sam Bull Date: Thu, 7 Sep 2023 18:14:34 +0100 Subject: [PATCH] CookieJar - return 'best-match' and not LIFO (#7577) (#7588) Co-authored-by: marq24 (cherry picked from commit 9c932f71ec5a450954cee92ff9450974414ac1d8) Co-authored-by: Matthias Marquardt --- CHANGES/7577.bugfix | 1 + CONTRIBUTORS.txt | 1 + aiohttp/cookiejar.py | 3 ++- tests/test_cookiejar.py | 28 ++++++++++++++++++++++++++++ 4 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 CHANGES/7577.bugfix diff --git a/CHANGES/7577.bugfix b/CHANGES/7577.bugfix new file mode 100644 index 00000000000..361497fd780 --- /dev/null +++ b/CHANGES/7577.bugfix @@ -0,0 +1 @@ +Fix sorting in filter_cookies to use cookie with longest path -- by :user:`marq24`. diff --git a/CONTRIBUTORS.txt b/CONTRIBUTORS.txt index 8e31468aee6..c1d93268978 100644 --- a/CONTRIBUTORS.txt +++ b/CONTRIBUTORS.txt @@ -211,6 +211,7 @@ Martin Melka Martin Richard Mathias Fröjdman Mathieu Dugré +Matthias Marquardt Matthieu Hauglustaine Matthieu Rigal Meet Mangukiya diff --git a/aiohttp/cookiejar.py b/aiohttp/cookiejar.py index 6c88b47e358..e395b7403ae 100644 --- a/aiohttp/cookiejar.py +++ b/aiohttp/cookiejar.py @@ -251,7 +251,8 @@ def filter_cookies( and request_origin not in self._treat_as_secure_origin ) - for cookie in self: + # Point 2: https://www.rfc-editor.org/rfc/rfc6265.html#section-5.4 + for cookie in sorted(self, key=lambda c: len(c["path"])): name = cookie.key domain = cookie["domain"] diff --git a/tests/test_cookiejar.py b/tests/test_cookiejar.py index 66f18c31d72..73e12536d6d 100644 --- a/tests/test_cookiejar.py +++ b/tests/test_cookiejar.py @@ -686,6 +686,34 @@ async def make_jar(): self.assertEqual(len(jar_filtered), 1) self.assertEqual(jar_filtered["path-cookie"].value, "one") + def test_filter_cookies_order_by_path(self) -> None: + async def make_jar(): + return CookieJar(unsafe=True) + + jar = self.loop.run_until_complete(make_jar()) + jar.update_cookies( + SimpleCookie("path-cookie=one; Domain=pathtest.com; Path=/one; ") + ) + jar.update_cookies( + SimpleCookie("path-cookie=zero; Domain=pathtest.com; Path=/; ") + ) + jar.update_cookies( + SimpleCookie("path-cookie=two; Domain=pathtest.com; Path=/second; ") + ) + self.assertEqual(len(jar), 3) + + jar_filtered = jar.filter_cookies(URL("http://pathtest.com/")) + self.assertEqual(len(jar_filtered), 1) + self.assertEqual(jar_filtered["path-cookie"].value, "zero") + + jar_filtered = jar.filter_cookies(URL("http://pathtest.com/second")) + self.assertEqual(len(jar_filtered), 1) + self.assertEqual(jar_filtered["path-cookie"].value, "two") + + jar_filtered = jar.filter_cookies(URL("http://pathtest.com/one")) + self.assertEqual(len(jar_filtered), 1) + self.assertEqual(jar_filtered["path-cookie"].value, "one") + async def test_dummy_cookie_jar() -> None: cookie = SimpleCookie("foo=bar; Domain=example.com;")