From 69b385f1da1698e82a8261628197f75a357aacfc Mon Sep 17 00:00:00 2001 From: astar76 Date: Thu, 12 Nov 2026 15:34:32 -0600 Subject: [PATCH] S023: request headers (DNT, Sec-GPC, Save-Data) and third-party cookie blocking in the vendored servo-net New vendor/servo-net/nacre.rs holds embedder-set state; http_loader and websocket_loader read it. Settings rows are working switches; privacy mode turns blocking on. Loopback smoke tests/smoke/privacy-net.txt, unit tests for site matching. Patch list in DESIGN.md, D-017. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- Cargo.lock | 1 + Cargo.toml | 6 +- Plans/06 Privacy/S023-net-headers-cookies.md | 14 +-- Plans/INDEX.md | 2 +- docs/DECISIONS.md | 1 + docs/DESIGN.md | 24 +++++ docs/FEATURES.md | 6 +- docs/PROGRESS.md | 9 ++ docs/REVIEW.md | 5 +- src/app.rs | 10 ++- src/hub.rs | 61 +++++++++++++ src/ui/pages/settings.rs | 6 +- tests/smoke/net/server.py | 40 ++++++++- tests/smoke/privacy-net.txt | 65 ++++++++++++++ vendor/servo-net/http_loader.rs | 25 ++++-- vendor/servo-net/lib.rs | 2 + vendor/servo-net/nacre.rs | 94 ++++++++++++++++++++ vendor/servo-net/websocket_loader.rs | 18 ++-- 19 files changed, 357 insertions(+), 34 deletions(-) create mode 100644 tests/smoke/privacy-net.txt create mode 100644 vendor/servo-net/nacre.rs diff --git a/CLAUDE.md b/CLAUDE.md index b15ff09..b465e15 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -65,7 +65,7 @@ Never modify: `~/Documents/Apps/Nacre` (the original Python Nacre, reference onl | `nice cargo build --release -j 2` | compile check, produces `target/release/nacre` | now | | `nice cargo test --release -j 2` | unit tests (44, ~16 s test-profile build then <1 s run; shares the S001 build) (util, settings, history, bookmarks, permissions, vault, dns, bridge loopback, download, adblock, keys, scripts, updates, inject, hub, theme, ui::widgets input, ui::paint, ui::pages::newtab) | first successful build; not alongside a build | | `src/selftest.rs` | in-app self test: `NACRE_SCRIPT=` runs script commands (listed at its top) | now | -| `tools/smoke.sh """ + GIF = bytes.fromhex("47494638396101000100800000ffffff00000021f90401000000002c00000000010001000002024401003b") @@ -104,11 +120,19 @@ class Handler(BaseHTTPRequestHandler): url = urlsplit(self.path) path = url.path record("paths", self.path) + if path != "/log": + record("reqs", {"host": self.headers.get("Host", ""), "path": self.path, "cookie": self.headers.get("Cookie"), + "dnt": self.headers.get("DNT"), "gpc": self.headers.get("Sec-GPC"), + "savedata": self.headers.get("Save-Data")}) if path == "/dns-query": import base64 wire = parse_qs(url.query).get("dns", [""])[0] query = base64.urlsafe_b64decode(wire + "=" * (-len(wire) % 4)) return self.reply(dns_answer(query), "application/dns-message") + if path == "/reset": + with lock: + log["reqs"].clear() + return self.reply(b"Reset", "text/html") if path == "/log": with lock: return self.reply(json.dumps(log).encode(), "application/json") @@ -118,6 +142,18 @@ class Handler(BaseHTTPRequestHandler): return self.reply(f"Net test {scheme}

Net test over {scheme}{links}".encode(), "text/html") if path == "/echo": return self.reply(f"Echo {url.query}

{url.query}".encode(), "text/html") + if path == "/setcookie": + query = parse_qs(url.query) + name = query.get("name", ["c"])[0] + cookie = f"{name}=1; Path=/" + (f"; Domain={query['domain'][0]}" if "domain" in query else "") + return self.reply(f"Set {name}

Set {name}".encode(), "text/html", {"Set-Cookie": cookie}) + if path == "/cookies": + return self.reply(f"Cookies {self.headers.get('Cookie', '')}".encode(), "text/html") + if path == "/pixel": + return self.reply(GIF, "image/gif") + if path == "/tp": + tag = parse_qs(url.query).get("tag", ["x"])[0] + return self.reply(TP_PAGE.replace("TAG", tag).encode(), "text/html") if path == "/ads.html": return self.reply(ADS_PAGE, "text/html") if path == "/ads/banner.js": diff --git a/tests/smoke/privacy-net.txt b/tests/smoke/privacy-net.txt new file mode 100644 index 0000000..1a05822 --- /dev/null +++ b/tests/smoke/privacy-net.txt @@ -0,0 +1,65 @@ +# Request headers and third-party cookies in the vendored servo-net (S023). Offline: names resolve through the +# secure DNS stub in tests/smoke/net/server.py (*.nacre.test -> 127.0.0.1). site.nacre.test and img.nacre.test are +# one site (nacre.test); 127.0.0.1 is another. Never Tor or proxies. Start the server first: +# python3 tests/smoke/net/server.py & then tools/smoke.sh tests/smoke/privacy-net.txt +wait 3 +set /vpn/enabled false +set /privacy/doh_custom "http://127.0.0.1:8766/dns-query" +set /privacy/doh "custom" +set /privacy/https_only false +set /privacy/dnt true +set /privacy/save_data true +set /privacy/mode false +set /privacy/block_third_party true +# The ad blocker would take the test pictures (/pixel); this run is about cookies. +set /adblock/enabled false +wait 1 +open http://127.0.0.1:8767/reset +waitfor 20 document.title === "Reset" +# First-party cookies: one for 127.0.0.1, one for the whole nacre.test site. +open http://127.0.0.1:8767/setcookie?name=fp +waitfor 20 document.title === "Set fp" +open http://site.nacre.test:8766/setcookie?name=sub&domain=nacre.test +waitfor 20 document.title === "Set sub" +open http://127.0.0.1:8767/cookies +waitfor 20 document.title === "Cookies fp=1" +# Blocking on: the cross-site frame and picture get no cookie and can't store one; the same-site picture keeps its. +open http://site.nacre.test:8766/tp?tag=on +waitfor 20 document.title === "TP on done" +shot blocked +# Blocking off: the same page sends and stores third-party cookies again. +set /privacy/block_third_party false +wait 1 +open http://site.nacre.test:8766/tp?tag=off +waitfor 20 document.title === "TP off done" +# Privacy mode turns blocking on even with the switch off. +set /privacy/mode true +wait 1 +open http://site.nacre.test:8766/tp?tag=mode +waitfor 20 document.title === "TP mode done" +set /privacy/mode false +# 127.0.0.1's own jar: fp, plus tpoff from the unblocked run; never tpon or tpmode. +open http://127.0.0.1:8767/cookies +waitfor 20 document.title.startsWith("Cookies ") +assert document.title === "Cookies fp=1; tpoff=1" +# Do Not Track off: the headers stop. +set /privacy/dnt false +set /privacy/save_data false +wait 1 +open http://127.0.0.1:8767/echo?nodnt +waitfor 20 document.title === "Echo nodnt" +js fetch("/log").then(r => r.json()).then(l => { window.reqs = l.reqs; }) +waitfor 5 window.reqs !== undefined +js window.pick = (tag, host) => window.reqs.filter(r => r.path.includes("tag=" + tag) && r.host.startsWith(host)); JSON.stringify(window.reqs.filter(r => r.path.includes("tag="))) +# Headers: every request with the switches on carried DNT, Sec-GPC and Save-Data; the last one none. +assert window.reqs.filter(r => r.path.startsWith("/tp")).every(r => r.dnt === "1" && r.gpc === "1" && r.savedata === "on") +assert window.reqs.some(r => r.path === "/echo?nodnt") && window.reqs.filter(r => r.path === "/echo?nodnt").every(r => r.dnt === null && r.gpc === null && r.savedata === null) +# Blocked: cross-site frame and picture without cookies, the same-site picture with sub=1. +assert window.pick("on", "127.0.0.1").length === 2 && window.pick("on", "127.0.0.1").every(r => r.cookie === null) +assert window.pick("on", "img.nacre.test").length === 1 && window.pick("on", "img.nacre.test")[0].cookie === "sub=1" +# Not blocked: the cross-site requests carry 127.0.0.1's cookie. +assert window.pick("off", "127.0.0.1").length === 2 && window.pick("off", "127.0.0.1").every(r => (r.cookie || "").includes("fp=1")) +# Privacy mode: blocked again. +assert window.pick("mode", "127.0.0.1").length === 2 && window.pick("mode", "127.0.0.1").every(r => r.cookie === null) +status done +quit diff --git a/vendor/servo-net/http_loader.rs b/vendor/servo-net/http_loader.rs index 14d50af..f042bae 100644 --- a/vendor/servo-net/http_loader.rs +++ b/vendor/servo-net/http_loader.rs @@ -1495,6 +1495,8 @@ async fn http_network_or_cache_fetch( .headers .typed_insert::(context.user_agent.parse().unwrap()); } + // Nacre patch (S023): the embedder's extra headers (Do Not Track, Global Privacy Control, Save-Data). + crate::nacre::append_extra_headers(&mut http_request.headers); // Steps 8.16 to 8.18 append_cache_data_to_headers(http_request); @@ -1518,15 +1520,25 @@ async fn http_network_or_cache_fetch( // Step 8.21: If includeCredentials is true, then: // TODO some of this step can't be implemented yet + // Nacre patch (S023): a top-level document request names its webview's site; the page's other requests + // are judged against it. + if http_request.destination == Destination::Document && + let Some(webview) = http_request.target_webview_id + { + crate::nacre::set_top_level_url(webview, ¤t_url); + } if include_credentials { // Substep 1 // TODO http://mxr.mozilla.org/servo/source/components/net/http_loader.rs#504 // XXXManishearth http_loader has block_cookies: support content blocking here too - set_request_cookies( - ¤t_url, - &mut http_request.headers, - &context.state.cookie_jar, - ); + // Nacre patch (S023): no cookies on third-party requests while blocking is on. + if !crate::nacre::cookies_blocked(http_request.target_webview_id, ¤t_url) { + set_request_cookies( + ¤t_url, + &mut http_request.headers, + &context.state.cookie_jar, + ); + } // Substep 2 if !http_request.headers.contains_key(header::AUTHORIZATION) { // Substep 3 @@ -2436,7 +2448,8 @@ async fn http_network_fetch( // TODO this step isn't possible yet // Step 15 - if credentials_flag { + // Nacre patch (S023): a third-party response stores no cookies while blocking is on. + if credentials_flag && !crate::nacre::cookies_blocked(request.target_webview_id, &url) { set_cookies_from_headers(&url, &response.headers, &context.state.cookie_jar); } context diff --git a/vendor/servo-net/lib.rs b/vendor/servo-net/lib.rs index c5ca178..d132818 100644 --- a/vendor/servo-net/lib.rs +++ b/vendor/servo-net/lib.rs @@ -14,6 +14,8 @@ mod disk_cache; pub mod embedder; pub mod filemanager_thread; mod hosts; +/// Nacre patch (S023): embedder-set request headers and third-party cookie blocking. +pub mod nacre; pub mod hsts; pub mod http_cache; pub mod http_loader; diff --git a/vendor/servo-net/nacre.rs b/vendor/servo-net/nacre.rs new file mode 100644 index 0000000..37c6562 --- /dev/null +++ b/vendor/servo-net/nacre.rs @@ -0,0 +1,94 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +//! Nacre patch (S023): state the embedder sets and the network code reads. Servo 0.7 has no way for an +//! embedder to add request headers or to block third-party cookies, so Nacre keeps both here. +//! Every use is marked "Nacre patch"; the list is in Nacre's docs/DESIGN.md "Vendored servo-net patches". + +use std::net::IpAddr; +use std::sync::LazyLock; +use std::sync::atomic::{AtomicBool, Ordering}; + +use http::{HeaderMap, HeaderName, HeaderValue}; +use net_traits::pub_domains::reg_suffix; +use parking_lot::RwLock; +use rustc_hash::FxHashMap; +use servo_base::id::WebViewId; +use servo_url::ServoUrl; + +static EXTRA_HEADERS: RwLock> = RwLock::new(Vec::new()); +static BLOCK_THIRD_PARTY: AtomicBool = AtomicBool::new(false); +static TOP_SITES: LazyLock>> = LazyLock::new(Default::default); + +/// Headers added to every HTTP request that doesn't already carry them (e.g. `DNT: 1`, `Sec-GPC: 1`). +/// Invalid names or values are skipped. +pub fn set_extra_request_headers(headers: &[(&str, &str)]) { + *EXTRA_HEADERS.write() = headers + .iter() + .filter_map(|(name, value)| { + Some(( + HeaderName::from_bytes(name.as_bytes()).ok()?, + HeaderValue::from_str(value).ok()?, + )) + }) + .collect(); +} + +/// Appends the embedder's extra headers that `headers` doesn't have yet. +pub fn append_extra_headers(headers: &mut HeaderMap) { + for (name, value) in EXTRA_HEADERS.read().iter() { + if !headers.contains_key(name) { + headers.insert(name.clone(), value.clone()); + } + } +} + +/// Turns third-party cookie blocking on or off. +pub fn set_block_third_party_cookies(on: bool) { + BLOCK_THIRD_PARTY.store(on, Ordering::Relaxed); +} + +/// Records the page a webview shows, so its requests can be judged first- or third-party. A URL with no +/// host (about:, data:, file:) forgets the webview: nothing is blocked there. +pub fn set_top_level_url(webview: WebViewId, url: &ServoUrl) { + match url.host_str() { + Some(host) => { + TOP_SITES.write().insert(webview, site_of_host(host)); + }, + None => forget_webview(webview), + } +} + +/// Drops what is known about a closed webview. +pub fn forget_webview(webview: WebViewId) { + TOP_SITES.write().remove(&webview); +} + +/// The site of a host: its registrable domain (eTLD+1), lowercased. An IP address or a single-label host +/// (e.g. `localhost`) stands for itself; an unlisted top-level domain counts as a public suffix. +pub fn site_of_host(host: &str) -> String { + let host = host.trim_end_matches('.').to_ascii_lowercase(); + if host.trim_matches(['[', ']']).parse::().is_ok() { + return host; + } + reg_suffix(&host).to_owned() +} + +/// Whether a request for `url` on a page of site `top_site` is third-party. Scheme and port don't count. +pub fn is_third_party(top_site: &str, url: &ServoUrl) -> bool { + url.host_str().is_some_and(|host| site_of_host(host) != top_site) +} + +/// Whether cookies must not be sent with, or stored from, a request for `url` made by `webview`. Never for +/// unknown webviews or pages without a host, nor while blocking is off. +pub fn cookies_blocked(webview: Option, url: &ServoUrl) -> bool { + if !BLOCK_THIRD_PARTY.load(Ordering::Relaxed) { + return false; + } + let Some(webview) = webview else { return false }; + TOP_SITES + .read() + .get(&webview) + .is_some_and(|top| is_third_party(top, url)) +} diff --git a/vendor/servo-net/websocket_loader.rs b/vendor/servo-net/websocket_loader.rs index 8e6b344..1c57ff6 100644 --- a/vendor/servo-net/websocket_loader.rs +++ b/vendor/servo-net/websocket_loader.rs @@ -101,10 +101,13 @@ pub fn create_handshake_request( headers.insert("Sec-WebSocket-Protocol", HeaderValue::from_str(&protocols)?); } - let mut cookie_jar = http_state.cookie_jar.write(); - cookie_jar.remove_expired_cookies_for_url(&request.url); - if let Some(cookie_list) = cookie_jar.cookies_for_url(&request.url, CookieSource::HTTP) { - headers.insert("Cookie", HeaderValue::from_str(&cookie_list)?); + // Nacre patch (S023): no cookies on a third-party handshake while blocking is on. + if !crate::nacre::cookies_blocked(request.target_webview_id, &request.url) { + let mut cookie_jar = http_state.cookie_jar.write(); + cookie_jar.remove_expired_cookies_for_url(&request.url); + if let Some(cookie_list) = cookie_jar.cookies_for_url(&request.url, CookieSource::HTTP) { + headers.insert("Cookie", HeaderValue::from_str(&cookie_list)?); + } } if request.url.password().is_some() || request.url.username() != "" { @@ -125,6 +128,7 @@ fn process_ws_response( response: &Response, resource_url: &ServoUrl, protocols: &[String], + webview: Option, ) -> Result, Error> { trace!("processing websocket http response for {}", resource_url); let mut protocol_in_use = None; @@ -139,8 +143,10 @@ fn process_ws_response( } let mut jar = http_state.cookie_jar.write(); + // Nacre patch (S023): a third-party handshake stores no cookies while blocking is on. + let blocked = crate::nacre::cookies_blocked(webview, resource_url); // TODO(eijebong): Replace thise once typed headers settled on a cookie impl - for cookie in response.headers().get_all(header::SET_COOKIE) { + for cookie in response.headers().get_all(header::SET_COOKIE).iter().filter(|_| !blocked) { let cookie_bytes = cookie.as_bytes(); if !ServoCookie::is_valid_name_or_value(cookie_bytes) { continue; @@ -352,7 +358,7 @@ pub(crate) async fn start_websocket( let (stream, response) = client_async_tls_with_connector_and_config(builder, socket, Some(connector), None).await?; - let protocol_in_use = process_ws_response(&http_state, &response, &url, protocols)?; + let protocol_in_use = process_ws_response(&http_state, &response, &url, protocols, client.target_webview_id)?; if !initiated_close.load(Ordering::SeqCst) { if resource_event_sender