diff --git a/impit-python/src/cookies.rs b/impit-python/src/cookies.rs index 74dd3bb9..6532c185 100644 --- a/impit-python/src/cookies.rs +++ b/impit-python/src/cookies.rs @@ -18,14 +18,20 @@ 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); 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()) + 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; + }; // 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. @@ -46,6 +52,32 @@ impl CookieStore for PythonCookieJar { // 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 stored_domain = domain.as_deref().unwrap_or(host); + 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); kwargs.set_item("name", cookie.name()).unwrap_or_default(); @@ -80,12 +112,7 @@ impl CookieStore for PythonCookieJar { kwargs .set_item("domain_initial_dot", domain.is_some()) .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); @@ -241,6 +268,34 @@ 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 +} + /// Returns `true` if `cookie_domain` is a public suffix, e.g. `com`, `co.uk` or `github.io`. /// /// Uses both sections of the [Public Suffix List](https://publicsuffix.org/), like browsers do. An unlisted @@ -255,6 +310,31 @@ fn is_public_suffix(cookie_domain: &str) -> bool { } impl PythonCookieJar { + /// 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; + }; + + 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 + && either_domain_matches(&attr("domain"), domain) + && path_matches(or_root(path), or_root(&attr("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(); @@ -272,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 31569000..e1f136ad 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, MozillaCookieJar from pathlib import Path @@ -359,6 +360,95 @@ async def test_cookie_path_matches_whole_segments(self, browser: Browser) -> Non response = await impit.get(get_httpbin_url('/cookies')) assert response.json()['cookies'] == {'root': '1', 'exact': '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={}, + ) + ) + + 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 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: """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 af32f219..3f9489b4 100644 --- a/impit-python/test/basic_client_test.py +++ b/impit-python/test/basic_client_test.py @@ -327,6 +327,92 @@ def test_cookie_path_matches_whole_segments(self, browser: Browser) -> None: response = impit.get(get_httpbin_url('/cookies')) assert response.json()['cookies'] == {'root': '1', 'exact': '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={}, + ) + ) + + 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 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."""