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 04002c9a..74dd3bb9 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,25 @@ 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; + } + // 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, + }; + // 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); kwargs.set_item("name", cookie.name()).unwrap_or_default(); @@ -36,12 +57,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.as_deref().unwrap_or(host)) .unwrap_or_default(); kwargs.set_item("comment", None::<&str>).unwrap_or_default(); kwargs @@ -59,13 +75,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.is_some()) .unwrap_or_default(); kwargs .set_item( @@ -119,6 +132,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,10 +145,17 @@ 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) { + if !path_matches(url.path(), &path) { return None; } if secure && !url.scheme().eq("https") { @@ -189,12 +213,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(); @@ -213,6 +241,19 @@ 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` or `github.io`. +/// +/// 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(); + + psl::suffix_str(&cookie_domain).is_some_and(|suffix| suffix == cookie_domain) +} + impl PythonCookieJar { pub fn new(py: Python<'_>, cookie_jar: Py) -> Self { let httpmodule = PyModule::import(py, "http.cookiejar").unwrap(); @@ -230,3 +271,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 e4ea4e50..31569000 100644 --- a/impit-python/test/async_client_test.py +++ b/impit-python/test/async_client_test.py @@ -3,8 +3,10 @@ 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 import pytest @@ -20,7 +22,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 @@ -192,7 +194,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;', ] }, ) @@ -229,9 +231,133 @@ 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 == '127.0.0.1' + # 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: + 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=.', + 'dots=5; Path=/; Domain=..', + 'suffix=6; Path=/; Domain=actor', + ] + }, + ) + + 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_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/', 'http://github.io/']: + response = await impit.get(url) + assert response.status_code == 200 + + # `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_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() + 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_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: diff --git a/impit-python/test/basic_client_test.py b/impit-python/test/basic_client_test.py index c94832ec..af32f219 100644 --- a/impit-python/test/basic_client_test.py +++ b/impit-python/test/basic_client_test.py @@ -3,8 +3,10 @@ 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 import pytest @@ -24,7 +26,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 @@ -165,7 +167,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;', ] }, ) @@ -202,9 +204,128 @@ 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 == '127.0.0.1' + # 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() + + 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=.', + 'dots=5; Path=/; Domain=..', + 'suffix=6; Path=/; Domain=actor', + ] + }, + ) + + 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_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/', 'http://github.io/']: + response = impit.get(url) + assert response.status_code == 200 + + # `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_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)]: + 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_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.""" diff --git a/impit-python/test/no_client_test.py b/impit-python/test/no_client_test.py index 6090b976..2ccf86c8 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;', ] }, ) @@ -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 == '127.0.0.1' + # 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'}) 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()