Skip to content

Commit

Permalink
CookieJar - return 'best-match' and not LIFO (#7577) (#7588)
Browse files Browse the repository at this point in the history
Co-authored-by: marq24 <marq24@emac.de>
(cherry picked from commit 9c932f7)

Co-authored-by: Matthias Marquardt <marquardt24@gmail.com>
  • Loading branch information
Dreamsorcerer and marq24 committed Sep 7, 2023
1 parent 8c4ec62 commit 5946c74
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGES/7577.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix sorting in filter_cookies to use cookie with longest path -- by :user:`marq24`.
1 change: 1 addition & 0 deletions CONTRIBUTORS.txt
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,7 @@ Martin Melka
Martin Richard
Mathias Fröjdman
Mathieu Dugré
Matthias Marquardt
Matthieu Hauglustaine
Matthieu Rigal
Meet Mangukiya
Expand Down
3 changes: 2 additions & 1 deletion aiohttp/cookiejar.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]

Expand Down
28 changes: 28 additions & 0 deletions tests/test_cookiejar.py
Original file line number Diff line number Diff line change
Expand Up @@ -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;")
Expand Down

0 comments on commit 5946c74

Please sign in to comment.