Skip to content

Commit 5946c74

Browse files
CookieJar - return 'best-match' and not LIFO (#7577) (#7588)
Co-authored-by: marq24 <[email protected]> (cherry picked from commit 9c932f7) Co-authored-by: Matthias Marquardt <[email protected]>
1 parent 8c4ec62 commit 5946c74

File tree

4 files changed

+32
-1
lines changed

4 files changed

+32
-1
lines changed

Diff for: CHANGES/7577.bugfix

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix sorting in filter_cookies to use cookie with longest path -- by :user:`marq24`.

Diff for: CONTRIBUTORS.txt

+1
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,7 @@ Martin Melka
211211
Martin Richard
212212
Mathias Fröjdman
213213
Mathieu Dugré
214+
Matthias Marquardt
214215
Matthieu Hauglustaine
215216
Matthieu Rigal
216217
Meet Mangukiya

Diff for: aiohttp/cookiejar.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -251,7 +251,8 @@ def filter_cookies(
251251
and request_origin not in self._treat_as_secure_origin
252252
)
253253

254-
for cookie in self:
254+
# Point 2: https://www.rfc-editor.org/rfc/rfc6265.html#section-5.4
255+
for cookie in sorted(self, key=lambda c: len(c["path"])):
255256
name = cookie.key
256257
domain = cookie["domain"]
257258

Diff for: tests/test_cookiejar.py

+28
Original file line numberDiff line numberDiff line change
@@ -686,6 +686,34 @@ async def make_jar():
686686
self.assertEqual(len(jar_filtered), 1)
687687
self.assertEqual(jar_filtered["path-cookie"].value, "one")
688688

689+
def test_filter_cookies_order_by_path(self) -> None:
690+
async def make_jar():
691+
return CookieJar(unsafe=True)
692+
693+
jar = self.loop.run_until_complete(make_jar())
694+
jar.update_cookies(
695+
SimpleCookie("path-cookie=one; Domain=pathtest.com; Path=/one; ")
696+
)
697+
jar.update_cookies(
698+
SimpleCookie("path-cookie=zero; Domain=pathtest.com; Path=/; ")
699+
)
700+
jar.update_cookies(
701+
SimpleCookie("path-cookie=two; Domain=pathtest.com; Path=/second; ")
702+
)
703+
self.assertEqual(len(jar), 3)
704+
705+
jar_filtered = jar.filter_cookies(URL("http://pathtest.com/"))
706+
self.assertEqual(len(jar_filtered), 1)
707+
self.assertEqual(jar_filtered["path-cookie"].value, "zero")
708+
709+
jar_filtered = jar.filter_cookies(URL("http://pathtest.com/second"))
710+
self.assertEqual(len(jar_filtered), 1)
711+
self.assertEqual(jar_filtered["path-cookie"].value, "two")
712+
713+
jar_filtered = jar.filter_cookies(URL("http://pathtest.com/one"))
714+
self.assertEqual(len(jar_filtered), 1)
715+
self.assertEqual(jar_filtered["path-cookie"].value, "one")
716+
689717

690718
async def test_dummy_cookie_jar() -> None:
691719
cookie = SimpleCookie("foo=bar; Domain=example.com;")

0 commit comments

Comments
 (0)