From a4e895e3525c9b7e7c8b37b0f1b4d10c1cf5b9f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Ad=C3=A1mek?= Date: Tue, 17 Nov 2026 15:27:15 +0100 Subject: [PATCH 1/6] fix(python): follow RFC 6265 domain rules in the custom cookie jar A custom cookie jar received every `Set-Cookie` as it was. A cookie with a `Domain` attribute is now stored only when that domain matches the host that sent it, an empty `Domain` is ignored, and a cookie without `Domain` is sent back only to the host that set it, not to its subdomains. --- impit-python/src/cookies.rs | 36 ++++++++++------ impit-python/test/async_client_test.py | 58 +++++++++++++++++++++++++- impit-python/test/basic_client_test.py | 56 ++++++++++++++++++++++++- impit-python/test/no_client_test.py | 4 +- 4 files changed, 136 insertions(+), 18 deletions(-) diff --git a/impit-python/src/cookies.rs b/impit-python/src/cookies.rs index 04002c9a..63e662de 100644 --- a/impit-python/src/cookies.rs +++ b/impit-python/src/cookies.rs @@ -18,6 +18,8 @@ impl CookieStore for PythonCookieJar { cookie_headers: &mut dyn Iterator, url: &Url, ) { + let host = url.host_str().unwrap_or_default(); + Python::attach(|py| { for header_value in cookie_headers { let cookie = std::str::from_utf8(header_value.as_bytes()) @@ -25,6 +27,13 @@ impl CookieStore for PythonCookieJar { .and_then(Cookie::parse) .unwrap_or(Cookie::new("", "")); + // RFC 6265 §5.3: a cookie whose `Domain` does not match the responding host is ignored. + // RFC 6265 §5.2.3: an empty `Domain` is ignored, leaving the cookie host-only. + let domain = cookie.domain().filter(|domain| !domain.is_empty()); + if domain.is_some_and(|domain| !domain_matches(host, domain)) { + continue; + } + let kwargs = PyDict::new(py); kwargs.set_item("name", cookie.name()).unwrap_or_default(); @@ -36,12 +45,7 @@ impl CookieStore for PythonCookieJar { .set_item("secure", cookie.secure().unwrap_or(false)) .unwrap_or_default(); kwargs - .set_item( - "domain", - cookie - .domain() - .unwrap_or_else(|| url.host_str().unwrap_or_default()), - ) + .set_item("domain", domain.unwrap_or(host)) .unwrap_or_default(); kwargs.set_item("comment", None::<&str>).unwrap_or_default(); kwargs @@ -59,13 +63,10 @@ impl CookieStore for PythonCookieJar { ) .unwrap_or_default(); kwargs - .set_item("domain_specified", cookie.domain().is_some()) + .set_item("domain_specified", domain.is_some()) .unwrap_or_default(); kwargs - .set_item( - "domain_initial_dot", - cookie.domain().map(|d| d.starts_with('.')), - ) + .set_item("domain_initial_dot", domain.map(|d| d.starts_with('.'))) .unwrap_or_default(); kwargs .set_item( @@ -119,6 +120,10 @@ impl CookieStore for PythonCookieJar { .getattr("domain") .and_then(|attr| attr.extract::()) .unwrap_or_default(); + let domain_specified = py_cookie + .getattr("domain_specified") + .and_then(|attr| attr.extract::()) + .unwrap_or(true); let path = py_cookie .getattr("path") .and_then(|attr| attr.extract::()) @@ -128,7 +133,14 @@ impl CookieStore for PythonCookieJar { .and_then(|attr| attr.extract::()) .unwrap_or_default(); - if !domain_matches(url.host_str().unwrap_or_default(), &domain) { + let host = url.host_str().unwrap_or_default(); + // RFC 6265 §5.4: a host-only cookie is returned only to the host that set it. + let host_matches = if domain_specified || domain.is_empty() { + domain_matches(host, &domain) + } else { + host.eq_ignore_ascii_case(&domain) + }; + if !host_matches { return None; } if !url.path().starts_with(&path) { diff --git a/impit-python/test/async_client_test.py b/impit-python/test/async_client_test.py index e4ea4e50..ae4178a3 100644 --- a/impit-python/test/async_client_test.py +++ b/impit-python/test/async_client_test.py @@ -192,7 +192,7 @@ async def test_complex_cookies(self, browser: Browser) -> None: 'strict=3; Path=/; SameSite=Strict', 'secure=4; Path=/; HttpOnly; Secure; SameSite=Strict', 'short=5; Path=/;', - 'domain=6; Path=/; Domain=.127.0.0.1;', + 'domain=6; Path=/; Domain=.httpbin.apify.actor;', ] }, ) @@ -231,7 +231,61 @@ async def test_complex_cookies(self, browser: Browser) -> None: assert cookie.secure is False # Crate cookies, ignores the starting dot in the domain # but it's ok - https://www.rfc-editor.org/rfc/rfc6265#section-4.1.2.3 - assert cookie.domain == '127.0.0.1' + assert cookie.domain == 'httpbin.apify.actor' + + @pytest.mark.asyncio + async def test_cookie_for_another_domain_is_not_stored(self, browser: Browser) -> None: + cookies_jar = CookieJar() + + impit = AsyncClient(browser=browser, cookie_jar=cookies_jar, follow_redirects=True) + + url = get_httpbin_url( + '/response-headers', + query={ + 'set-cookie': [ + 'own=1; Path=/', + 'parent=2; Path=/; Domain=apify.actor', + 'other=3; Path=/; Domain=example.com', + 'empty=4; Path=/; Domain=.', + ] + }, + ) + + response = await impit.get(url) + assert response.status_code == 200 + + assert {'own', 'parent', 'empty'} == {cookie.name for cookie in cookies_jar} + assert {'parent'} == {cookie.name for cookie in cookies_jar if cookie.domain_specified} + + @pytest.mark.asyncio + async def test_host_only_cookie_is_not_sent_to_subdomains(self, browser: Browser) -> None: + cookies_jar = CookieJar() + for name, domain_specified in [('host_only', False), ('domain', True)]: + cookies_jar.set_cookie( + Cookie( + version=0, + name=name, + value='1', + port=None, + port_specified=False, + domain='apify.actor', + domain_specified=domain_specified, + domain_initial_dot=False, + path='/', + path_specified=True, + secure=False, + expires=None, + discard=True, + comment=None, + comment_url=None, + rest={}, + ) + ) + + impit = AsyncClient(browser=browser, cookie_jar=cookies_jar) + + response = await impit.get(get_httpbin_url('/cookies')) + assert response.json()['cookies'] == {'domain': '1'} @pytest.mark.asyncio async def test_rejected_cookie_is_skipped_not_crashing(self, browser: Browser) -> None: diff --git a/impit-python/test/basic_client_test.py b/impit-python/test/basic_client_test.py index c94832ec..8d79d5d0 100644 --- a/impit-python/test/basic_client_test.py +++ b/impit-python/test/basic_client_test.py @@ -165,7 +165,7 @@ def test_complex_cookies(self, browser: Browser) -> None: 'strict=3; Path=/; SameSite=Strict', 'secure=4; Path=/; HttpOnly; Secure; SameSite=Strict', 'short=5; Path=/;', - 'domain=6; Path=/; Domain=.127.0.0.1;', + 'domain=6; Path=/; Domain=.httpbin.apify.actor;', ] }, ) @@ -204,7 +204,59 @@ def test_complex_cookies(self, browser: Browser) -> None: assert cookie.secure is False # Crate cookies, ignores the starting dot in the domain # but it's ok - https://www.rfc-editor.org/rfc/rfc6265#section-4.1.2.3 - assert cookie.domain == '127.0.0.1' + assert cookie.domain == 'httpbin.apify.actor' + + def test_cookie_for_another_domain_is_not_stored(self, browser: Browser) -> None: + cookies_jar = CookieJar() + + impit = Client(browser=browser, cookie_jar=cookies_jar, follow_redirects=True) + + url = get_httpbin_url( + '/response-headers', + query={ + 'set-cookie': [ + 'own=1; Path=/', + 'parent=2; Path=/; Domain=apify.actor', + 'other=3; Path=/; Domain=example.com', + 'empty=4; Path=/; Domain=.', + ] + }, + ) + + response = impit.get(url) + assert response.status_code == 200 + + assert {'own', 'parent', 'empty'} == {cookie.name for cookie in cookies_jar} + assert {'parent'} == {cookie.name for cookie in cookies_jar if cookie.domain_specified} + + def test_host_only_cookie_is_not_sent_to_subdomains(self, browser: Browser) -> None: + cookies_jar = CookieJar() + for name, domain_specified in [('host_only', False), ('domain', True)]: + cookies_jar.set_cookie( + Cookie( + version=0, + name=name, + value='1', + port=None, + port_specified=False, + domain='apify.actor', + domain_specified=domain_specified, + domain_initial_dot=False, + path='/', + path_specified=True, + secure=False, + expires=None, + discard=True, + comment=None, + comment_url=None, + rest={}, + ) + ) + + impit = Client(browser=browser, cookie_jar=cookies_jar) + + response = impit.get(get_httpbin_url('/cookies')) + assert response.json()['cookies'] == {'domain': '1'} def test_rejected_cookie_is_skipped_not_crashing(self, browser: Browser) -> None: """Cookies rejected by the cookie jar are skipped instead of aborting the process.""" diff --git a/impit-python/test/no_client_test.py b/impit-python/test/no_client_test.py index 6090b976..7718530d 100644 --- a/impit-python/test/no_client_test.py +++ b/impit-python/test/no_client_test.py @@ -103,7 +103,7 @@ def test_complex_cookies(self) -> None: 'strict=3; Path=/; SameSite=Strict', 'secure=4; Path=/; HttpOnly; Secure; SameSite=Strict', 'short=5; Path=/;', - 'domain=6; Path=/; Domain=.127.0.0.1;', + 'domain=6; Path=/; Domain=.httpbin.apify.actor;', ] }, ) @@ -142,7 +142,7 @@ def test_complex_cookies(self) -> None: assert cookie.secure is False # Crate cookies, ignores the starting dot in the domain # but it's ok - https://www.rfc-editor.org/rfc/rfc6265#section-4.1.2.3 - assert cookie.domain == '127.0.0.1' + assert cookie.domain == 'httpbin.apify.actor' def test_cookie_jar_works(self) -> None: cookies = Cookies({'preset-cookie': '123'}) From eb15bc72a0d6e38c34bae54c80926962473274bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Ad=C3=A1mek?= Date: Wed, 18 Nov 2026 14:21:39 +0100 Subject: [PATCH 2/6] fix(python): match cookie paths by whole segments A cookie path was compared as a plain string prefix, so a cookie for `/foo` was also sent to `/foobar`. The path now has to match up to a segment boundary, as described in RFC 6265. --- impit-python/src/cookies.rs | 18 ++++++++++++++- impit-python/test/async_client_test.py | 32 ++++++++++++++++++++++++++ impit-python/test/basic_client_test.py | 31 +++++++++++++++++++++++++ 3 files changed, 80 insertions(+), 1 deletion(-) diff --git a/impit-python/src/cookies.rs b/impit-python/src/cookies.rs index 63e662de..92845664 100644 --- a/impit-python/src/cookies.rs +++ b/impit-python/src/cookies.rs @@ -143,7 +143,7 @@ impl CookieStore for PythonCookieJar { if !host_matches { return None; } - if !url.path().starts_with(&path) { + if !path_matches(url.path(), &path) { return None; } if secure && !url.scheme().eq("https") { @@ -242,3 +242,19 @@ impl PythonCookieJar { .map(|jar| PythonCookieJar::new(py, jar)) } } + +/// Returns `true` if `request_path` path-matches `cookie_path`, as defined by +/// [RFC 6265, §5.1.4](https://www.rfc-editor.org/rfc/rfc6265#section-5.1.4). +/// +/// An empty cookie path imposes no path restriction. +fn path_matches(request_path: &str, cookie_path: &str) -> bool { + match request_path.strip_prefix(cookie_path) { + Some(rest) => { + rest.is_empty() + || rest.starts_with('/') + || cookie_path.is_empty() + || cookie_path.ends_with('/') + } + None => false, + } +} diff --git a/impit-python/test/async_client_test.py b/impit-python/test/async_client_test.py index ae4178a3..4d09699f 100644 --- a/impit-python/test/async_client_test.py +++ b/impit-python/test/async_client_test.py @@ -5,6 +5,7 @@ from collections.abc import AsyncIterator from http.cookiejar import Cookie, CookieJar from typing import Literal +from urllib.parse import urlparse import pytest @@ -287,6 +288,37 @@ async def test_host_only_cookie_is_not_sent_to_subdomains(self, browser: Browser response = await impit.get(get_httpbin_url('/cookies')) assert response.json()['cookies'] == {'domain': '1'} + @pytest.mark.asyncio + async def test_cookie_path_matches_whole_segments(self, browser: Browser) -> None: + cookies_jar = CookieJar() + host = urlparse(get_httpbin_url('/')).hostname or '' + for name, path in [('root', '/'), ('exact', '/cookies'), ('partial', '/cook'), ('other', '/cookies/set')]: + cookies_jar.set_cookie( + Cookie( + version=0, + name=name, + value='1', + port=None, + port_specified=False, + domain=host, + domain_specified=False, + domain_initial_dot=False, + path=path, + path_specified=True, + secure=False, + expires=None, + discard=True, + comment=None, + comment_url=None, + rest={}, + ) + ) + + impit = AsyncClient(browser=browser, cookie_jar=cookies_jar) + + response = await impit.get(get_httpbin_url('/cookies')) + assert response.json()['cookies'] == {'root': '1', 'exact': '1'} + @pytest.mark.asyncio async def test_rejected_cookie_is_skipped_not_crashing(self, browser: Browser) -> None: """Cookies rejected by the cookie jar are skipped instead of aborting the process.""" diff --git a/impit-python/test/basic_client_test.py b/impit-python/test/basic_client_test.py index 8d79d5d0..a7d102a1 100644 --- a/impit-python/test/basic_client_test.py +++ b/impit-python/test/basic_client_test.py @@ -5,6 +5,7 @@ from collections.abc import Iterator from http.cookiejar import Cookie, CookieJar from typing import Literal +from urllib.parse import urlparse import pytest @@ -258,6 +259,36 @@ def test_host_only_cookie_is_not_sent_to_subdomains(self, browser: Browser) -> N response = impit.get(get_httpbin_url('/cookies')) assert response.json()['cookies'] == {'domain': '1'} + def test_cookie_path_matches_whole_segments(self, browser: Browser) -> None: + cookies_jar = CookieJar() + host = urlparse(get_httpbin_url('/')).hostname or '' + for name, path in [('root', '/'), ('exact', '/cookies'), ('partial', '/cook'), ('other', '/cookies/set')]: + cookies_jar.set_cookie( + Cookie( + version=0, + name=name, + value='1', + port=None, + port_specified=False, + domain=host, + domain_specified=False, + domain_initial_dot=False, + path=path, + path_specified=True, + secure=False, + expires=None, + discard=True, + comment=None, + comment_url=None, + rest={}, + ) + ) + + impit = Client(browser=browser, cookie_jar=cookies_jar) + + response = impit.get(get_httpbin_url('/cookies')) + assert response.json()['cookies'] == {'root': '1', 'exact': '1'} + def test_rejected_cookie_is_skipped_not_crashing(self, browser: Browser) -> None: """Cookies rejected by the cookie jar are skipped instead of aborting the process.""" From 68097faa09ccd244e5d20bbc58db49a5c783943f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Ad=C3=A1mek?= Date: Thu, 19 Nov 2026 14:39:13 +0100 Subject: [PATCH 3/6] fix(python): ignore cookies with a dot-only or dotless domain A `Domain` of `..` was stored as `.` and matched every host, and a bare suffix like `com` was accepted from any host under it. Both are now ignored, the second the same way Python's `DefaultCookiePolicy` does it. --- impit-python/src/cookies.rs | 21 +++++++++++++++++++-- impit-python/test/async_client_test.py | 2 ++ impit-python/test/basic_client_test.py | 2 ++ 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/impit-python/src/cookies.rs b/impit-python/src/cookies.rs index 92845664..665f11be 100644 --- a/impit-python/src/cookies.rs +++ b/impit-python/src/cookies.rs @@ -33,6 +33,10 @@ impl CookieStore for PythonCookieJar { if domain.is_some_and(|domain| !domain_matches(host, domain)) { continue; } + // A domain without an inner dot (e.g. `com`) would cover every site under that suffix. + if domain.is_some_and(|domain| is_dotless_suffix(host, domain)) { + continue; + } let kwargs = PyDict::new(py); @@ -201,12 +205,16 @@ impl CookieStore for PythonCookieJar { /// /// An empty cookie domain imposes no host restriction and therefore matches any host. fn domain_matches(host: &str, cookie_domain: &str) -> bool { - let cookie_domain = cookie_domain.strip_prefix('.').unwrap_or(cookie_domain); - if cookie_domain.is_empty() { return true; } + // A domain made only of dots (e.g. `.`) is not empty and names no host, so it matches nothing. + let cookie_domain = cookie_domain.strip_prefix('.').unwrap_or(cookie_domain); + if cookie_domain.is_empty() { + return false; + } + // Host names are case-insensitive; normalise both sides instead of trusting the // caller to pass a lowercased host. let host = host.to_ascii_lowercase(); @@ -225,6 +233,15 @@ fn domain_matches(host: &str, cookie_domain: &str) -> bool { .is_some_and(|prefix| prefix.ends_with('.')) } +/// Returns `true` if `cookie_domain` has no inner dot and is not the host itself. +/// +/// Such a domain is a bare suffix like `com`, mirroring the check in Python's `DefaultCookiePolicy`. +fn is_dotless_suffix(host: &str, cookie_domain: &str) -> bool { + let cookie_domain = cookie_domain.strip_prefix('.').unwrap_or(cookie_domain); + + !cookie_domain.contains('.') && !host.eq_ignore_ascii_case(cookie_domain) +} + impl PythonCookieJar { pub fn new(py: Python<'_>, cookie_jar: Py) -> Self { let httpmodule = PyModule::import(py, "http.cookiejar").unwrap(); diff --git a/impit-python/test/async_client_test.py b/impit-python/test/async_client_test.py index 4d09699f..471a6803 100644 --- a/impit-python/test/async_client_test.py +++ b/impit-python/test/async_client_test.py @@ -248,6 +248,8 @@ async def test_cookie_for_another_domain_is_not_stored(self, browser: Browser) - 'parent=2; Path=/; Domain=apify.actor', 'other=3; Path=/; Domain=example.com', 'empty=4; Path=/; Domain=.', + 'dots=5; Path=/; Domain=..', + 'suffix=6; Path=/; Domain=actor', ] }, ) diff --git a/impit-python/test/basic_client_test.py b/impit-python/test/basic_client_test.py index a7d102a1..39eb3db2 100644 --- a/impit-python/test/basic_client_test.py +++ b/impit-python/test/basic_client_test.py @@ -220,6 +220,8 @@ def test_cookie_for_another_domain_is_not_stored(self, browser: Browser) -> None 'parent=2; Path=/; Domain=apify.actor', 'other=3; Path=/; Domain=example.com', 'empty=4; Path=/; Domain=.', + 'dots=5; Path=/; Domain=..', + 'suffix=6; Path=/; Domain=actor', ] }, ) From 4750384709894292677fcbd4e18db1a3ae370513 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Ad=C3=A1mek?= Date: Thu, 19 Nov 2026 16:54:51 +0100 Subject: [PATCH 4/6] fix(python): ignore cookies whose domain is a public suffix The dotless check let suffixes like `co.uk` or `github.io` through. The domain is now checked against the Public Suffix List instead. --- Cargo.lock | 10 ++++++++++ impit-python/Cargo.toml | 1 + impit-python/src/cookies.rs | 18 +++++++++++------- impit-python/test/async_client_test.py | 21 ++++++++++++++++++++- impit-python/test/basic_client_test.py | 20 +++++++++++++++++++- impit-python/test/servers.py | 26 ++++++++++++++++++++++++++ 6 files changed, 87 insertions(+), 9 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1ffa4a33..559a69c3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1350,6 +1350,7 @@ dependencies = [ "futures", "h2", "impit", + "psl", "pyo3", "pyo3-async-runtimes", "reqwest", @@ -1940,6 +1941,15 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "psl" +version = "2.1.255" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb40358efa8d957f3e793e45daedd2fef822c694e1e3a45b827b53de6175e724" +dependencies = [ + "psl-types", +] + [[package]] name = "psl-types" version = "2.0.11" diff --git a/impit-python/Cargo.toml b/impit-python/Cargo.toml index 6432bd8c..b207488a 100644 --- a/impit-python/Cargo.toml +++ b/impit-python/Cargo.toml @@ -19,5 +19,6 @@ pyo3-async-runtimes = { version = "0.29", features = ["attributes", "async-std-r urlencoding = "2.1.3" encoding = "0.2.33" cookie = "0.18.1" +psl = "2.1.255" futures = "0.3.31" either = "1.15.0" diff --git a/impit-python/src/cookies.rs b/impit-python/src/cookies.rs index 665f11be..a722f3e8 100644 --- a/impit-python/src/cookies.rs +++ b/impit-python/src/cookies.rs @@ -33,8 +33,8 @@ impl CookieStore for PythonCookieJar { if domain.is_some_and(|domain| !domain_matches(host, domain)) { continue; } - // A domain without an inner dot (e.g. `com`) would cover every site under that suffix. - if domain.is_some_and(|domain| is_dotless_suffix(host, domain)) { + // RFC 6265 §5.3: a public suffix (e.g. `com`, `co.uk`) would cover every site under it. + if domain.is_some_and(|domain| is_public_suffix(host, domain)) { continue; } @@ -233,13 +233,17 @@ fn domain_matches(host: &str, cookie_domain: &str) -> bool { .is_some_and(|prefix| prefix.ends_with('.')) } -/// Returns `true` if `cookie_domain` has no inner dot and is not the host itself. +/// Returns `true` if `cookie_domain` is a public suffix (e.g. `com`, `co.uk`, `github.io`) and not the host itself. /// -/// Such a domain is a bare suffix like `com`, mirroring the check in Python's `DefaultCookiePolicy`. -fn is_dotless_suffix(host: &str, cookie_domain: &str) -> bool { - let cookie_domain = cookie_domain.strip_prefix('.').unwrap_or(cookie_domain); +/// Uses the [Public Suffix List](https://publicsuffix.org/), where an unlisted top-level name counts as a suffix. +fn is_public_suffix(host: &str, cookie_domain: &str) -> bool { + let cookie_domain = cookie_domain + .strip_prefix('.') + .unwrap_or(cookie_domain) + .to_ascii_lowercase(); - !cookie_domain.contains('.') && !host.eq_ignore_ascii_case(cookie_domain) + !host.eq_ignore_ascii_case(&cookie_domain) + && psl::suffix_str(&cookie_domain).is_some_and(|suffix| suffix == cookie_domain) } impl PythonCookieJar { diff --git a/impit-python/test/async_client_test.py b/impit-python/test/async_client_test.py index 471a6803..ffd03c3c 100644 --- a/impit-python/test/async_client_test.py +++ b/impit-python/test/async_client_test.py @@ -21,7 +21,7 @@ ) from .httpbin import get_httpbin_url -from .servers import echoing_server +from .servers import echoing_server, set_cookie_server from .setup_proxy import start_proxy_server @@ -260,6 +260,25 @@ async def test_cookie_for_another_domain_is_not_stored(self, browser: Browser) - assert {'own', 'parent', 'empty'} == {cookie.name for cookie in cookies_jar} assert {'parent'} == {cookie.name for cookie in cookies_jar if cookie.domain_specified} + @pytest.mark.asyncio + async def test_cookie_for_public_suffix_is_not_stored(self, browser: Browser) -> None: + cookies_jar = CookieJar() + + set_cookies = [ + 'own=1; Path=/', + 'site=2; Path=/; Domain=example.co.uk', + 'suffix=3; Path=/; Domain=co.uk', + 'private=4; Path=/; Domain=github.io', + ] + with set_cookie_server(set_cookies) as port: + impit = AsyncClient(browser=browser, cookie_jar=cookies_jar, proxy=f'http://127.0.0.1:{port}') + + for url in ['http://shop.example.co.uk/', 'http://attacker.github.io/']: + response = await impit.get(url) + assert response.status_code == 200 + + assert {'own', 'site'} == {cookie.name for cookie in cookies_jar} + @pytest.mark.asyncio async def test_host_only_cookie_is_not_sent_to_subdomains(self, browser: Browser) -> None: cookies_jar = CookieJar() diff --git a/impit-python/test/basic_client_test.py b/impit-python/test/basic_client_test.py index 39eb3db2..8117b83f 100644 --- a/impit-python/test/basic_client_test.py +++ b/impit-python/test/basic_client_test.py @@ -25,7 +25,7 @@ ) from .httpbin import get_httpbin_url -from .servers import echoing_server +from .servers import echoing_server, set_cookie_server from .setup_proxy import start_proxy_server @@ -232,6 +232,24 @@ def test_cookie_for_another_domain_is_not_stored(self, browser: Browser) -> None assert {'own', 'parent', 'empty'} == {cookie.name for cookie in cookies_jar} assert {'parent'} == {cookie.name for cookie in cookies_jar if cookie.domain_specified} + def test_cookie_for_public_suffix_is_not_stored(self, browser: Browser) -> None: + cookies_jar = CookieJar() + + set_cookies = [ + 'own=1; Path=/', + 'site=2; Path=/; Domain=example.co.uk', + 'suffix=3; Path=/; Domain=co.uk', + 'private=4; Path=/; Domain=github.io', + ] + with set_cookie_server(set_cookies) as port: + impit = Client(browser=browser, cookie_jar=cookies_jar, proxy=f'http://127.0.0.1:{port}') + + for url in ['http://shop.example.co.uk/', 'http://attacker.github.io/']: + response = impit.get(url) + assert response.status_code == 200 + + assert {'own', 'site'} == {cookie.name for cookie in cookies_jar} + def test_host_only_cookie_is_not_sent_to_subdomains(self, browser: Browser) -> None: cookies_jar = CookieJar() for name, domain_specified in [('host_only', False), ('domain', True)]: diff --git a/impit-python/test/servers.py b/impit-python/test/servers.py index d05e61fd..5d6aa9e7 100644 --- a/impit-python/test/servers.py +++ b/impit-python/test/servers.py @@ -3,6 +3,7 @@ from __future__ import annotations import contextlib +import http.server import re import socket import threading @@ -52,3 +53,28 @@ def echo() -> None: finally: thread.join(5) server.close() + + +@contextlib.contextmanager +def set_cookie_server(cookies: list[str]) -> Iterator[int]: + """Answer every request with the given `Set-Cookie` headers over plain HTTP, and yield the port to call.""" + + class Handler(http.server.BaseHTTPRequestHandler): + def do_GET(self) -> None: + self.send_response(200) + for cookie in cookies: + self.send_header('Set-Cookie', cookie) + self.send_header('Content-Length', '0') + self.end_headers() + + def log_message(self, *_: object) -> None: + pass + + server = http.server.ThreadingHTTPServer(('127.0.0.1', 0), Handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + yield server.server_address[1] + finally: + server.shutdown() + server.server_close() From 613cef6c45f5eea17e606edd2d2c6db7b2fe1862 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Ad=C3=A1mek?= Date: Fri, 20 Nov 2026 06:31:22 +0100 Subject: [PATCH 5/6] fix(python): keep a public suffix cookie from its own host as host-only A host whose name is itself a public suffix can set a cookie for that name. Browsers then store it as a host-only cookie, so it is not sent to the sites below it. --- impit-python/src/cookies.rs | 24 +++++++++++++++--------- impit-python/test/async_client_test.py | 7 +++++-- impit-python/test/basic_client_test.py | 7 +++++-- 3 files changed, 25 insertions(+), 13 deletions(-) diff --git a/impit-python/src/cookies.rs b/impit-python/src/cookies.rs index a722f3e8..49229f6c 100644 --- a/impit-python/src/cookies.rs +++ b/impit-python/src/cookies.rs @@ -33,10 +33,16 @@ impl CookieStore for PythonCookieJar { if domain.is_some_and(|domain| !domain_matches(host, domain)) { continue; } - // RFC 6265 §5.3: a public suffix (e.g. `com`, `co.uk`) would cover every site under it. - if domain.is_some_and(|domain| is_public_suffix(host, domain)) { - continue; - } + // RFC 6265 §5.3: a public suffix is only accepted from the host of that name, as a host-only cookie. + let domain = match domain { + Some(domain) if is_public_suffix(domain) => { + if !host.eq_ignore_ascii_case(domain.strip_prefix('.').unwrap_or(domain)) { + continue; + } + None + } + domain => domain, + }; let kwargs = PyDict::new(py); @@ -233,17 +239,17 @@ fn domain_matches(host: &str, cookie_domain: &str) -> bool { .is_some_and(|prefix| prefix.ends_with('.')) } -/// Returns `true` if `cookie_domain` is a public suffix (e.g. `com`, `co.uk`, `github.io`) and not the host itself. +/// Returns `true` if `cookie_domain` is a public suffix, e.g. `com`, `co.uk` or `github.io`. /// -/// Uses the [Public Suffix List](https://publicsuffix.org/), where an unlisted top-level name counts as a suffix. -fn is_public_suffix(host: &str, cookie_domain: &str) -> bool { +/// Uses both sections of the [Public Suffix List](https://publicsuffix.org/), like browsers do. An unlisted +/// top-level name counts as a suffix. +fn is_public_suffix(cookie_domain: &str) -> bool { let cookie_domain = cookie_domain .strip_prefix('.') .unwrap_or(cookie_domain) .to_ascii_lowercase(); - !host.eq_ignore_ascii_case(&cookie_domain) - && psl::suffix_str(&cookie_domain).is_some_and(|suffix| suffix == cookie_domain) + psl::suffix_str(&cookie_domain).is_some_and(|suffix| suffix == cookie_domain) } impl PythonCookieJar { diff --git a/impit-python/test/async_client_test.py b/impit-python/test/async_client_test.py index ffd03c3c..32f6ead8 100644 --- a/impit-python/test/async_client_test.py +++ b/impit-python/test/async_client_test.py @@ -273,11 +273,14 @@ async def test_cookie_for_public_suffix_is_not_stored(self, browser: Browser) -> with set_cookie_server(set_cookies) as port: impit = AsyncClient(browser=browser, cookie_jar=cookies_jar, proxy=f'http://127.0.0.1:{port}') - for url in ['http://shop.example.co.uk/', 'http://attacker.github.io/']: + for url in ['http://shop.example.co.uk/', 'http://attacker.github.io/', 'http://github.io/']: response = await impit.get(url) assert response.status_code == 200 - assert {'own', 'site'} == {cookie.name for cookie in cookies_jar} + # `github.io` itself may set a cookie for its own name, which then stays host-only. + assert {'own', 'site', 'private'} == {cookie.name for cookie in cookies_jar} + assert {'site'} == {cookie.name for cookie in cookies_jar if cookie.domain_specified} + assert {'github.io'} == {cookie.domain for cookie in cookies_jar if cookie.name == 'private'} @pytest.mark.asyncio async def test_host_only_cookie_is_not_sent_to_subdomains(self, browser: Browser) -> None: diff --git a/impit-python/test/basic_client_test.py b/impit-python/test/basic_client_test.py index 8117b83f..d8ac370e 100644 --- a/impit-python/test/basic_client_test.py +++ b/impit-python/test/basic_client_test.py @@ -244,11 +244,14 @@ def test_cookie_for_public_suffix_is_not_stored(self, browser: Browser) -> None: with set_cookie_server(set_cookies) as port: impit = Client(browser=browser, cookie_jar=cookies_jar, proxy=f'http://127.0.0.1:{port}') - for url in ['http://shop.example.co.uk/', 'http://attacker.github.io/']: + for url in ['http://shop.example.co.uk/', 'http://attacker.github.io/', 'http://github.io/']: response = impit.get(url) assert response.status_code == 200 - assert {'own', 'site'} == {cookie.name for cookie in cookies_jar} + # `github.io` itself may set a cookie for its own name, which then stays host-only. + assert {'own', 'site', 'private'} == {cookie.name for cookie in cookies_jar} + assert {'site'} == {cookie.name for cookie in cookies_jar if cookie.domain_specified} + assert {'github.io'} == {cookie.domain for cookie in cookies_jar if cookie.name == 'private'} def test_host_only_cookie_is_not_sent_to_subdomains(self, browser: Browser) -> None: cookies_jar = CookieJar() From bcd445062d300281088c86d5a814d61515826647 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Ad=C3=A1mek?= Date: Fri, 20 Nov 2026 12:15:43 +0100 Subject: [PATCH 6/6] fix(python): store a domain cookie with a leading dot File cookie jars of `http.cookiejar` derive `domain_specified` from a leading dot when saving, so a cookie with a `Domain` turned into a host-only one after a save and load. --- impit-python/src/cookies.rs | 6 ++++-- impit-python/test/async_client_test.py | 24 ++++++++++++++++++++---- impit-python/test/basic_client_test.py | 23 +++++++++++++++++++---- impit-python/test/no_client_test.py | 5 ++--- 4 files changed, 45 insertions(+), 13 deletions(-) diff --git a/impit-python/src/cookies.rs b/impit-python/src/cookies.rs index 49229f6c..74dd3bb9 100644 --- a/impit-python/src/cookies.rs +++ b/impit-python/src/cookies.rs @@ -43,6 +43,8 @@ impl CookieStore for PythonCookieJar { } domain => domain, }; + // File cookie jars of `http.cookiejar` only keep `domain_specified` for a domain with a leading dot. + let domain = domain.map(|domain| format!(".{}", domain.trim_start_matches('.'))); let kwargs = PyDict::new(py); @@ -55,7 +57,7 @@ impl CookieStore for PythonCookieJar { .set_item("secure", cookie.secure().unwrap_or(false)) .unwrap_or_default(); kwargs - .set_item("domain", domain.unwrap_or(host)) + .set_item("domain", domain.as_deref().unwrap_or(host)) .unwrap_or_default(); kwargs.set_item("comment", None::<&str>).unwrap_or_default(); kwargs @@ -76,7 +78,7 @@ impl CookieStore for PythonCookieJar { .set_item("domain_specified", domain.is_some()) .unwrap_or_default(); kwargs - .set_item("domain_initial_dot", domain.map(|d| d.starts_with('.'))) + .set_item("domain_initial_dot", domain.is_some()) .unwrap_or_default(); kwargs .set_item( diff --git a/impit-python/test/async_client_test.py b/impit-python/test/async_client_test.py index 32f6ead8..31569000 100644 --- a/impit-python/test/async_client_test.py +++ b/impit-python/test/async_client_test.py @@ -3,7 +3,8 @@ import socket import threading from collections.abc import AsyncIterator -from http.cookiejar import Cookie, CookieJar +from http.cookiejar import Cookie, CookieJar, MozillaCookieJar +from pathlib import Path from typing import Literal from urllib.parse import urlparse @@ -230,9 +231,8 @@ async def test_complex_cookies(self, browser: Browser) -> None: elif cookie.name == 'domain': assert cookie.value == '6' assert cookie.secure is False - # Crate cookies, ignores the starting dot in the domain - # but it's ok - https://www.rfc-editor.org/rfc/rfc6265#section-4.1.2.3 - assert cookie.domain == 'httpbin.apify.actor' + # Stored with a leading dot, like `http.cookiejar` does for a cookie with a `Domain`. + assert cookie.domain == '.httpbin.apify.actor' @pytest.mark.asyncio async def test_cookie_for_another_domain_is_not_stored(self, browser: Browser) -> None: @@ -282,6 +282,22 @@ async def test_cookie_for_public_suffix_is_not_stored(self, browser: Browser) -> assert {'site'} == {cookie.name for cookie in cookies_jar if cookie.domain_specified} assert {'github.io'} == {cookie.domain for cookie in cookies_jar if cookie.name == 'private'} + @pytest.mark.asyncio + async def test_domain_cookie_survives_a_file_cookie_jar(self, browser: Browser, tmp_path: Path) -> None: + cookies_jar = MozillaCookieJar(tmp_path / 'cookies.txt') + + with set_cookie_server(['own=1; Path=/', 'site=2; Path=/; Domain=example.co.uk']) as port: + impit = AsyncClient(browser=browser, cookie_jar=cookies_jar, proxy=f'http://127.0.0.1:{port}') + response = await impit.get('http://shop.example.co.uk/') + assert response.status_code == 200 + + cookies_jar.save(ignore_discard=True) + loaded_jar = MozillaCookieJar(tmp_path / 'cookies.txt') + loaded_jar.load(ignore_discard=True) + + assert {'own', 'site'} == {cookie.name for cookie in loaded_jar} + assert {'site'} == {cookie.name for cookie in loaded_jar if cookie.domain_specified} + @pytest.mark.asyncio async def test_host_only_cookie_is_not_sent_to_subdomains(self, browser: Browser) -> None: cookies_jar = CookieJar() diff --git a/impit-python/test/basic_client_test.py b/impit-python/test/basic_client_test.py index d8ac370e..af32f219 100644 --- a/impit-python/test/basic_client_test.py +++ b/impit-python/test/basic_client_test.py @@ -3,7 +3,8 @@ import threading import time from collections.abc import Iterator -from http.cookiejar import Cookie, CookieJar +from http.cookiejar import Cookie, CookieJar, MozillaCookieJar +from pathlib import Path from typing import Literal from urllib.parse import urlparse @@ -203,9 +204,8 @@ def test_complex_cookies(self, browser: Browser) -> None: elif cookie.name == 'domain': assert cookie.value == '6' assert cookie.secure is False - # Crate cookies, ignores the starting dot in the domain - # but it's ok - https://www.rfc-editor.org/rfc/rfc6265#section-4.1.2.3 - assert cookie.domain == 'httpbin.apify.actor' + # Stored with a leading dot, like `http.cookiejar` does for a cookie with a `Domain`. + assert cookie.domain == '.httpbin.apify.actor' def test_cookie_for_another_domain_is_not_stored(self, browser: Browser) -> None: cookies_jar = CookieJar() @@ -253,6 +253,21 @@ def test_cookie_for_public_suffix_is_not_stored(self, browser: Browser) -> None: assert {'site'} == {cookie.name for cookie in cookies_jar if cookie.domain_specified} assert {'github.io'} == {cookie.domain for cookie in cookies_jar if cookie.name == 'private'} + def test_domain_cookie_survives_a_file_cookie_jar(self, browser: Browser, tmp_path: Path) -> None: + cookies_jar = MozillaCookieJar(tmp_path / 'cookies.txt') + + with set_cookie_server(['own=1; Path=/', 'site=2; Path=/; Domain=example.co.uk']) as port: + impit = Client(browser=browser, cookie_jar=cookies_jar, proxy=f'http://127.0.0.1:{port}') + response = impit.get('http://shop.example.co.uk/') + assert response.status_code == 200 + + cookies_jar.save(ignore_discard=True) + loaded_jar = MozillaCookieJar(tmp_path / 'cookies.txt') + loaded_jar.load(ignore_discard=True) + + assert {'own', 'site'} == {cookie.name for cookie in loaded_jar} + assert {'site'} == {cookie.name for cookie in loaded_jar if cookie.domain_specified} + def test_host_only_cookie_is_not_sent_to_subdomains(self, browser: Browser) -> None: cookies_jar = CookieJar() for name, domain_specified in [('host_only', False), ('domain', True)]: diff --git a/impit-python/test/no_client_test.py b/impit-python/test/no_client_test.py index 7718530d..2ccf86c8 100644 --- a/impit-python/test/no_client_test.py +++ b/impit-python/test/no_client_test.py @@ -140,9 +140,8 @@ def test_complex_cookies(self) -> None: elif cookie.name == 'domain': assert cookie.value == '6' assert cookie.secure is False - # Crate cookies, ignores the starting dot in the domain - # but it's ok - https://www.rfc-editor.org/rfc/rfc6265#section-4.1.2.3 - assert cookie.domain == 'httpbin.apify.actor' + # Stored with a leading dot, like `http.cookiejar` does for a cookie with a `Domain`. + assert cookie.domain == '.httpbin.apify.actor' def test_cookie_jar_works(self) -> None: cookies = Cookies({'preset-cookie': '123'})