From 1335b996f95a96bf04aad9648d128f139a0b49ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Ad=C3=A1mek?= Date: Thu, 19 Nov 2026 14:46:46 +0100 Subject: [PATCH 1/2] fix(python): honor Max-Age and apply the Secure and prefix rules when storing cookies - `Max-Age` was ignored, so such cookies never expired and `Max-Age=0` did not remove a cookie. It now takes precedence over `Expires`, and an already expired cookie removes the stored one. - A `Set-Cookie` header that fails to parse was stored as a placeholder cookie. It is skipped now. - A `Secure` cookie is only stored from HTTPS or a loopback host, and a response from elsewhere can't replace one. - The `__Secure-` and `__Host-` name prefixes are checked. --- impit-python/src/cookies.rs | 98 +++++++++++++++++++++++--- impit-python/test/async_client_test.py | 84 +++++++++++++++++++++- impit-python/test/basic_client_test.py | 80 ++++++++++++++++++++- impit-python/test/servers.py | 26 +++++++ 4 files changed, 278 insertions(+), 10 deletions(-) diff --git a/impit-python/src/cookies.rs b/impit-python/src/cookies.rs index 04002c9a..85288e1c 100644 --- a/impit-python/src/cookies.rs +++ b/impit-python/src/cookies.rs @@ -18,12 +18,47 @@ impl CookieStore for PythonCookieJar { cookie_headers: &mut dyn Iterator, url: &Url, ) { + let secure_origin = is_secure_origin(url); + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |now| now.as_secs() as i64); + Python::attach(|py| { for header_value in cookie_headers { - let cookie = std::str::from_utf8(header_value.as_bytes()) + let Ok(cookie) = std::str::from_utf8(header_value.as_bytes()) .map_err(cookie::ParseError::from) .and_then(Cookie::parse) - .unwrap_or(Cookie::new("", "")); + else { + continue; + }; + + let stored_domain = cookie + .domain() + .unwrap_or_else(|| url.host_str().unwrap_or_default()); + let stored_path = cookie.path().unwrap_or(""); + + // RFC 6265bis §5.7: only a secure origin may set a `Secure` cookie or replace one. + if !secure_origin + && (cookie.secure().unwrap_or(false) + || self.has_secure_cookie(py, cookie.name(), stored_domain, stored_path)) + { + continue; + } + if !prefix_rules_hold(&cookie) { + continue; + } + + // RFC 6265 §5.3: `Max-Age` takes precedence over `Expires`. + let expires = cookie + .max_age() + .map(|age| now.saturating_add(age.whole_seconds())) + .or_else(|| cookie.expires_datetime().map(|f| f.unix_timestamp())); + // An already expired cookie removes the stored one, as `CookieJar.extract_cookies` does. + if expires.is_some_and(|expires| expires <= now) { + let key = (stored_domain, stored_path, cookie.name()); + let _ = self.cookie_jar.call_method1(py, "clear", key); + continue; + } let kwargs = PyDict::new(py); @@ -67,12 +102,7 @@ impl CookieStore for PythonCookieJar { cookie.domain().map(|d| d.starts_with('.')), ) .unwrap_or_default(); - kwargs - .set_item( - "expires", - cookie.expires_datetime().map(|f| f.unix_timestamp()), - ) - .unwrap_or_default(); + kwargs.set_item("expires", expires).unwrap_or_default(); kwargs.set_item("version", 0).unwrap_or_default(); let rest = PyDict::new(py); @@ -213,7 +243,59 @@ fn domain_matches(host: &str, cookie_domain: &str) -> bool { .is_some_and(|prefix| prefix.ends_with('.')) } +/// Returns `true` if `url` may set or replace `Secure` cookies: HTTPS, or a loopback host as in browsers. +fn is_secure_origin(url: &Url) -> bool { + let host = url.host_str().unwrap_or_default(); + let host = host.trim_start_matches('[').trim_end_matches(']'); + + url.scheme() == "https" + || host == "localhost" + || host.ends_with(".localhost") + || host + .parse::() + .is_ok_and(|ip| ip.is_loopback()) +} + +/// Checks the `__Secure-` and `__Host-` cookie name prefix rules of +/// [RFC 6265bis, §4.1.3](https://www.ietf.org/archive/id/draft-ietf-httpbis-rfc6265bis-22.html#name-cookie-name-prefixes). +fn prefix_rules_hold(cookie: &Cookie) -> bool { + let name = cookie.name().to_ascii_lowercase(); + let secure = cookie.secure().unwrap_or(false); + + if name.starts_with("__secure-") { + return secure; + } + if name.starts_with("__host-") { + return secure && cookie.domain().is_none() && cookie.path() == Some("/"); + } + true +} + impl PythonCookieJar { + /// Returns `true` if the jar holds a `Secure` cookie with the given name, domain and path. + fn has_secure_cookie(&self, py: Python<'_>, name: &str, domain: &str, path: &str) -> bool { + let Ok(cookies) = PyIterator::from_object(&self.cookie_jar.bind_borrowed(py)) else { + return false; + }; + + cookies.flatten().any(|cookie| { + let attr = |key: &str| { + cookie + .getattr(key) + .and_then(|value| value.extract::()) + .unwrap_or_default() + }; + + cookie + .getattr("secure") + .and_then(|value| value.extract::()) + .unwrap_or(false) + && attr("name") == name + && attr("domain").eq_ignore_ascii_case(domain) + && attr("path") == path + }) + } + pub fn new(py: Python<'_>, cookie_jar: Py) -> Self { let httpmodule = PyModule::import(py, "http.cookiejar").unwrap(); let cookie_constructor = httpmodule.getattr("Cookie").unwrap().into(); diff --git a/impit-python/test/async_client_test.py b/impit-python/test/async_client_test.py index e4ea4e50..5e3ebf3f 100644 --- a/impit-python/test/async_client_test.py +++ b/impit-python/test/async_client_test.py @@ -2,6 +2,7 @@ import json import socket import threading +import time from collections.abc import AsyncIterator from http.cookiejar import Cookie, CookieJar from typing import Literal @@ -20,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 @@ -233,6 +234,87 @@ async def test_complex_cookies(self, browser: Browser) -> None: # but it's ok - https://www.rfc-editor.org/rfc/rfc6265#section-4.1.2.3 assert cookie.domain == '127.0.0.1' + @pytest.mark.asyncio + async def test_cookie_storage_rules(self, browser: Browser) -> None: + cookies_jar = CookieJar() + + impit = AsyncClient(browser=browser, cookie_jar=cookies_jar) + + url = get_httpbin_url( + '/response-headers', + query={ + 'set-cookie': [ + 'plain=1; Path=/', + 'malformed', + '__Secure-plain=1; Path=/', + '__Secure-ok=1; Path=/; Secure', + '__Host-ok=1; Path=/; Secure', + '__Host-domain=1; Path=/; Secure; Domain=httpbin.apify.actor', + '__Host-path=1; Path=/cookies; Secure', + ] + }, + ) + + response = await impit.get(url) + assert response.status_code == 200 + + assert {'plain', '__Secure-ok', '__Host-ok'} == {cookie.name for cookie in cookies_jar} + + @pytest.mark.asyncio + async def test_cookie_max_age(self, browser: Browser) -> None: + cookies_jar = CookieJar() + + impit = AsyncClient(browser=browser, cookie_jar=cookies_jar) + + url = get_httpbin_url( + '/response-headers', query={'set-cookie': ['kept=1; Path=/; Max-Age=3600', 'removed=1; Path=/']} + ) + response = await impit.get(url) + assert response.status_code == 200 + + cookies = {cookie.name: cookie for cookie in cookies_jar} + assert {'kept', 'removed'} == set(cookies) + assert cookies['kept'].expires is not None + assert 3500 < cookies['kept'].expires - time.time() <= 3600 + + url = get_httpbin_url('/response-headers', query={'set-cookie': ['removed=; Path=/; Max-Age=0']}) + response = await impit.get(url) + assert response.status_code == 200 + + assert {'kept'} == {cookie.name for cookie in cookies_jar} + + @pytest.mark.asyncio + async def test_secure_cookie_needs_secure_origin(self, browser: Browser) -> None: + cookies_jar = CookieJar() + cookies_jar.set_cookie( + Cookie( + version=0, + name='session', + value='secret', + port=None, + port_specified=False, + domain='insecure.test', + domain_specified=False, + domain_initial_dot=False, + path='/', + path_specified=True, + secure=True, + expires=None, + discard=True, + comment=None, + comment_url=None, + rest={}, + ) + ) + + with set_cookie_server(['plain=1; Path=/', 'secure=1; Path=/; Secure', 'session=replaced; Path=/']) as port: + impit = AsyncClient(browser=browser, cookie_jar=cookies_jar, proxy=f'http://127.0.0.1:{port}') + + response = await impit.get('http://insecure.test/') + assert response.status_code == 200 + + assert {cookie.name: cookie.value for cookie in cookies_jar} == {'plain': '1', 'session': 'secret'} + @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 c94832ec..1699b9b6 100644 --- a/impit-python/test/basic_client_test.py +++ b/impit-python/test/basic_client_test.py @@ -24,7 +24,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 @@ -206,6 +206,84 @@ def test_complex_cookies(self, browser: Browser) -> None: # but it's ok - https://www.rfc-editor.org/rfc/rfc6265#section-4.1.2.3 assert cookie.domain == '127.0.0.1' + def test_cookie_storage_rules(self, browser: Browser) -> None: + cookies_jar = CookieJar() + + impit = Client(browser=browser, cookie_jar=cookies_jar) + + url = get_httpbin_url( + '/response-headers', + query={ + 'set-cookie': [ + 'plain=1; Path=/', + 'malformed', + '__Secure-plain=1; Path=/', + '__Secure-ok=1; Path=/; Secure', + '__Host-ok=1; Path=/; Secure', + '__Host-domain=1; Path=/; Secure; Domain=httpbin.apify.actor', + '__Host-path=1; Path=/cookies; Secure', + ] + }, + ) + + response = impit.get(url) + assert response.status_code == 200 + + assert {'plain', '__Secure-ok', '__Host-ok'} == {cookie.name for cookie in cookies_jar} + + def test_cookie_max_age(self, browser: Browser) -> None: + cookies_jar = CookieJar() + + impit = Client(browser=browser, cookie_jar=cookies_jar) + + url = get_httpbin_url( + '/response-headers', query={'set-cookie': ['kept=1; Path=/; Max-Age=3600', 'removed=1; Path=/']} + ) + response = impit.get(url) + assert response.status_code == 200 + + cookies = {cookie.name: cookie for cookie in cookies_jar} + assert {'kept', 'removed'} == set(cookies) + assert cookies['kept'].expires is not None + assert 3500 < cookies['kept'].expires - time.time() <= 3600 + + url = get_httpbin_url('/response-headers', query={'set-cookie': ['removed=; Path=/; Max-Age=0']}) + response = impit.get(url) + assert response.status_code == 200 + + assert {'kept'} == {cookie.name for cookie in cookies_jar} + + def test_secure_cookie_needs_secure_origin(self, browser: Browser) -> None: + cookies_jar = CookieJar() + cookies_jar.set_cookie( + Cookie( + version=0, + name='session', + value='secret', + port=None, + port_specified=False, + domain='insecure.test', + domain_specified=False, + domain_initial_dot=False, + path='/', + path_specified=True, + secure=True, + expires=None, + discard=True, + comment=None, + comment_url=None, + rest={}, + ) + ) + + with set_cookie_server(['plain=1; Path=/', 'secure=1; Path=/; Secure', 'session=replaced; Path=/']) as port: + impit = Client(browser=browser, cookie_jar=cookies_jar, proxy=f'http://127.0.0.1:{port}') + + response = impit.get('http://insecure.test/') + assert response.status_code == 200 + + assert {cookie.name: cookie.value for cookie in cookies_jar} == {'plain': '1', 'session': 'secret'} + 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/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 c6813d4ee15c88f38fcf6e88364932a260602d1d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Ad=C3=A1mek?= Date: Fri, 20 Nov 2026 15:28:49 +0100 Subject: [PATCH 2/2] fix(python): compare domains and paths by their matching rules when protecting a secure cookie --- impit-python/src/cookies.rs | 26 +++++++++++++++++++++++--- impit-python/test/async_client_test.py | 12 ++++++++++-- impit-python/test/basic_client_test.py | 12 ++++++++++-- 3 files changed, 43 insertions(+), 7 deletions(-) diff --git a/impit-python/src/cookies.rs b/impit-python/src/cookies.rs index 0a5aa6ee..6532c185 100644 --- a/impit-python/src/cookies.rs +++ b/impit-python/src/cookies.rs @@ -310,7 +310,8 @@ fn is_public_suffix(cookie_domain: &str) -> bool { } impl PythonCookieJar { - /// Returns `true` if the jar holds a `Secure` cookie with the given name, domain and path. + /// Returns `true` if the jar holds a `Secure` cookie that a cookie with the given name, domain and path + /// would shadow, see [RFC 6265bis, §5.7](https://www.ietf.org/archive/id/draft-ietf-httpbis-rfc6265bis-22.html#section-5.7). fn has_secure_cookie(&self, py: Python<'_>, name: &str, domain: &str, path: &str) -> bool { let Ok(cookies) = PyIterator::from_object(&self.cookie_jar.bind_borrowed(py)) else { return false; @@ -329,8 +330,8 @@ impl PythonCookieJar { .and_then(|value| value.extract::()) .unwrap_or(false) && attr("name") == name - && attr("domain").eq_ignore_ascii_case(domain) - && attr("path") == path + && either_domain_matches(&attr("domain"), domain) + && path_matches(or_root(path), or_root(&attr("path"))) }) } @@ -351,6 +352,25 @@ impl PythonCookieJar { } } +/// Returns `true` if one of the two cookie domains domain-matches the other. +fn either_domain_matches(first: &str, second: &str) -> bool { + let first = first.strip_prefix('.').unwrap_or(first); + let second = second.strip_prefix('.').unwrap_or(second); + + !first.is_empty() + && !second.is_empty() + && (domain_matches(first, second) || domain_matches(second, first)) +} + +/// An empty cookie path covers the whole host, the same as `/`. +fn or_root(path: &str) -> &str { + if path.is_empty() { + "/" + } else { + path + } +} + /// 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). /// diff --git a/impit-python/test/async_client_test.py b/impit-python/test/async_client_test.py index d240d21a..e1f136ad 100644 --- a/impit-python/test/async_client_test.py +++ b/impit-python/test/async_client_test.py @@ -433,13 +433,21 @@ async def test_secure_cookie_needs_secure_origin(self, browser: Browser) -> None ) ) - with set_cookie_server(['plain=1; Path=/', 'secure=1; Path=/; Secure', 'session=replaced; Path=/']) as port: + set_cookies = [ + 'plain=1; Path=/', + 'secure=1; Path=/; Secure', + 'session=replaced; Path=/', + 'session=no-path', + 'session=deeper; Path=/account', + 'session=parent; Path=/; Domain=insecure.test', + ] + with set_cookie_server(set_cookies) as port: impit = AsyncClient(browser=browser, cookie_jar=cookies_jar, proxy=f'http://127.0.0.1:{port}') response = await impit.get('http://insecure.test/') assert response.status_code == 200 - assert {cookie.name: cookie.value for cookie in cookies_jar} == {'plain': '1', 'session': 'secret'} + assert sorted((cookie.name, cookie.value) for cookie in cookies_jar) == [('plain', '1'), ('session', 'secret')] @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 e9086eba..3f9489b4 100644 --- a/impit-python/test/basic_client_test.py +++ b/impit-python/test/basic_client_test.py @@ -397,13 +397,21 @@ def test_secure_cookie_needs_secure_origin(self, browser: Browser) -> None: ) ) - with set_cookie_server(['plain=1; Path=/', 'secure=1; Path=/; Secure', 'session=replaced; Path=/']) as port: + set_cookies = [ + 'plain=1; Path=/', + 'secure=1; Path=/; Secure', + 'session=replaced; Path=/', + 'session=no-path', + 'session=deeper; Path=/account', + 'session=parent; Path=/; Domain=insecure.test', + ] + with set_cookie_server(set_cookies) as port: impit = Client(browser=browser, cookie_jar=cookies_jar, proxy=f'http://127.0.0.1:{port}') response = impit.get('http://insecure.test/') assert response.status_code == 200 - assert {cookie.name: cookie.value for cookie in cookies_jar} == {'plain': '1', 'session': 'secret'} + assert sorted((cookie.name, cookie.value) for cookie in cookies_jar) == [('plain', '1'), ('session', 'secret')] 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."""