Skip to content

Commit 9c932f7

Browse files
marq24marq24
and
marq24
authored
CookieJar - return 'best-match' and not LIFO (#7577)
Co-authored-by: marq24 <[email protected]>
1 parent aa3554d commit 9c932f7

File tree

4 files changed

+34
-1
lines changed

4 files changed

+34
-1
lines changed

CHANGES/7577.bugfix

Lines changed: 1 addition & 0 deletions
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`.

CONTRIBUTORS.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,7 @@ Martin Richard
228228
Mathias Fröjdman
229229
Mathieu Dugré
230230
Matt VanEseltine
231+
Matthias Marquardt
231232
Matthieu Hauglustaine
232233
Matthieu Rigal
233234
Matvey Tingaev

aiohttp/cookiejar.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -256,7 +256,8 @@ def filter_cookies(
256256
and request_origin not in self._treat_as_secure_origin
257257
)
258258

259-
for cookie in self:
259+
# Point 2: https://www.rfc-editor.org/rfc/rfc6265.html#section-5.4
260+
for cookie in sorted(self, key=lambda c: len(c["path"])):
260261
name = cookie.key
261262
domain = cookie["domain"]
262263

tests/test_cookiejar.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -704,6 +704,36 @@ async def make_jar():
704704
self.assertEqual(len(jar_filtered), 1)
705705
self.assertEqual(jar_filtered["path-cookie"].value, "one")
706706

707+
def test_path_filter_diff_folder_same_name_return_best_match_independent_from_put_order(
708+
self,
709+
) -> None:
710+
async def make_jar():
711+
return CookieJar(unsafe=True)
712+
713+
jar = self.loop.run_until_complete(make_jar())
714+
jar.update_cookies(
715+
SimpleCookie("path-cookie=one; Domain=pathtest.com; Path=/one; ")
716+
)
717+
jar.update_cookies(
718+
SimpleCookie("path-cookie=zero; Domain=pathtest.com; Path=/; ")
719+
)
720+
jar.update_cookies(
721+
SimpleCookie("path-cookie=two; Domain=pathtest.com; Path=/second; ")
722+
)
723+
self.assertEqual(len(jar), 3)
724+
725+
jar_filtered = jar.filter_cookies(URL("http://pathtest.com/"))
726+
self.assertEqual(len(jar_filtered), 1)
727+
self.assertEqual(jar_filtered["path-cookie"].value, "zero")
728+
729+
jar_filtered = jar.filter_cookies(URL("http://pathtest.com/second"))
730+
self.assertEqual(len(jar_filtered), 1)
731+
self.assertEqual(jar_filtered["path-cookie"].value, "two")
732+
733+
jar_filtered = jar.filter_cookies(URL("http://pathtest.com/one"))
734+
self.assertEqual(len(jar_filtered), 1)
735+
self.assertEqual(jar_filtered["path-cookie"].value, "one")
736+
707737

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

0 commit comments

Comments
 (0)