Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions impit-python/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
87 changes: 72 additions & 15 deletions impit-python/src/cookies.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,34 @@ impl CookieStore for PythonCookieJar {
cookie_headers: &mut dyn Iterator<Item = &reqwest::header::HeaderValue>,
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())
.map_err(cookie::ParseError::from)
.and_then(Cookie::parse)
.unwrap_or(Cookie::new("<cookie-name>", "<cookie-value>"));

// 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();
Expand All @@ -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
Expand All @@ -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(
Expand Down Expand Up @@ -119,6 +132,10 @@ impl CookieStore for PythonCookieJar {
.getattr("domain")
.and_then(|attr| attr.extract::<String>())
.unwrap_or_default();
let domain_specified = py_cookie
.getattr("domain_specified")
.and_then(|attr| attr.extract::<bool>())
.unwrap_or(true);
let path = py_cookie
.getattr("path")
.and_then(|attr| attr.extract::<String>())
Expand All @@ -128,10 +145,17 @@ impl CookieStore for PythonCookieJar {
.and_then(|attr| attr.extract::<bool>())
.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") {
Expand Down Expand Up @@ -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();
Expand All @@ -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<PyAny>) -> Self {
let httpmodule = PyModule::import(py, "http.cookiejar").unwrap();
Expand All @@ -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,
}
}
138 changes: 132 additions & 6 deletions impit-python/test/async_client_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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


Expand Down Expand Up @@ -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;',
]
},
)
Expand Down Expand Up @@ -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:
Expand Down
Loading
Loading