diff --git a/CLAUDE.md b/CLAUDE.md index fb2bd69..589be9b 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 """ + +# document.cookie in a cross-site frame (S024): the frame on 127.0.0.1:8767 writes a cookie from script, reads +# document.cookie and reports what it saw as /note?tag=T&seen=... (recorded in the request log). +JSTP_PAGE = """JSTP TAG + +""" +JSCOOKIE_PAGE = """JS cookie +""" + GIF = bytes.fromhex("47494638396101000100800000ffffff00000021f90401000000002c00000000010001000002024401003b") @@ -104,11 +134,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"), "lang": self.headers.get("Accept-Language")}) 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 +156,31 @@ 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 == "/login": + user = parse_qs(url.query).get("user", ["u"])[0] + cookie = f"session=nacre-test-session-{user}; Path=/; Max-Age=86400; HttpOnly" + return self.reply(f"Signed in {user}".encode(), "text/html", {"Set-Cookie": cookie}) + if path == "/whoami": + signed_in = re.search(r"(?:^|; )session=nacre-test-session-(\w+)", self.headers.get("Cookie", "")) + title = f"Signed in as {signed_in.group(1)}" if signed_in else "Signed out" + return self.reply(f"{title}".encode(), "text/html") + 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 in ("/jstp", "/jscookie"): + tag = parse_qs(url.query).get("tag", ["x"])[0] + return self.reply((JSTP_PAGE if path == "/jstp" else JSCOOKIE_PAGE).replace("TAG", tag).encode(), "text/html") + if path == "/note": + return self.reply(GIF, "image/gif") if path == "/ads.html": return self.reply(ADS_PAGE, "text/html") if path == "/ads/banner.js": diff --git a/tests/smoke/pages/fingerprint.html b/tests/smoke/pages/fingerprint.html new file mode 100644 index 0000000..61b245b --- /dev/null +++ b/tests/smoke/pages/fingerprint.html @@ -0,0 +1,136 @@ + + +Fingerprint + + +

reading…
+ + diff --git a/tests/smoke/pages/media.html b/tests/smoke/pages/media.html new file mode 100644 index 0000000..051c4dc --- /dev/null +++ b/tests/smoke/pages/media.html @@ -0,0 +1,16 @@ + + + +Smoke media page + + + +
SMOKE MEDIA
+ + + + diff --git a/tests/smoke/pages/spell.html b/tests/smoke/pages/spell.html new file mode 100644 index 0000000..b971a52 --- /dev/null +++ b/tests/smoke/pages/spell.html @@ -0,0 +1,5 @@ + + +spell + + diff --git a/tests/smoke/privacy-incognito.txt b/tests/smoke/privacy-incognito.txt new file mode 100644 index 0000000..664a796 --- /dev/null +++ b/tests/smoke/privacy-incognito.txt @@ -0,0 +1,17 @@ +# Incognito windows start with privacy mode on (S024): privacy.mode off, mode_incognito on (the default). +# SMOKE_ARGS=--incognito tools/smoke.sh tests/smoke/privacy-incognito.txt +wait 3 +set /vpn/enabled false +set /privacy/mode false +set /privacy/mode_incognito true +wait 1 +open @PAGES@/fingerprint.html +waitfor 30 document.title === "FP done" +save fp-incognito JSON.stringify(window.fp, null, 1) +shot fp-incognito +assert window.fp.hardwareConcurrency === 8 && window.fp.platform === "Linux x86_64" && window.fp.webgl.vendor === "Mozilla" +flyout shield +wait 1 +shot shield-incognito +status done +quit diff --git a/tests/smoke/privacy-mode.txt b/tests/smoke/privacy-mode.txt new file mode 100644 index 0000000..9bc47f0 --- /dev/null +++ b/tests/smoke/privacy-mode.txt @@ -0,0 +1,54 @@ +# Privacy mode's fingerprint protection (S024), offline: tests/smoke/pages/fingerprint.html reads every surface +# with privacy mode off and on and saves them as fp-off.json / fp-on.json (shots fp-off.png / fp-on.png). +# tools/smoke.sh tests/smoke/privacy-mode.txt +# Incognito windows start with it on (privacy.mode off, mode_incognito on): tests/smoke/privacy-incognito.txt. +wait 3 +set /vpn/enabled false +set /privacy/mode false +wait 1 +open @PAGES@/fingerprint.html +waitfor 30 document.title === "FP done" +save fp-off JSON.stringify(window.fp, null, 1) +shot fp-off +# The engine's own values: Servo's platform and appVersion, the real core count, the real screen. +assert window.fp.platform === "Linux" && window.fp.appVersion === "4.0" && window.fp.webgl.vendor === "Mozilla/Servo" && window.fp.languages.length === 1 +assert window.fp.screen !== "0 0 0 0 24 24" +set /privacy/mode true +wait 1 +# The real values go to the next load in the URL's hash (Servo doesn't keep window.name). +js location.href = "?on#" + encodeURIComponent(JSON.stringify({ canvas: window.fp.canvas, audio: window.fp.audio })) +wait 1 +waitfor 30 document.title === "FP done" +save fp-on JSON.stringify(window.fp, null, 1) +shot fp-on +js window.off = JSON.parse(decodeURIComponent(location.hash.slice(1))); JSON.stringify(window.off) +# Common values, consistent with the Firefox user agent. +assert window.fp.hardwareConcurrency === 8 && window.fp.platform === "Linux x86_64" && window.fp.appVersion === "5.0 (X11)" +assert window.fp.webgl.vendor === "Mozilla" && window.fp.webgl.renderer === "Mozilla" && window.fp.webgl.unmaskedVendor === "Mozilla" && window.fp.webgl.unmaskedRenderer === "Mozilla" +# Desktop Firefox: no touch points, touch events can't be created; the language list as Firefox sends it. +assert window.fp.touchEvents === "function NotSupportedError" && window.fp.maxTouchPoints === 0 +assert window.fp.languages.length === 2 && window.fp.languages[0] === window.fp.language && window.fp.language.startsWith(window.fp.languages[1] + "-") +assert ["1366 768", "1536 864", "1920 1080", "2560 1440", "3840 2160"].some(s => window.fp.screen === s + " " + s + " 24 24") && window.fp.availOrigin === "0 0" +# Noise: canvas and audio differ from the real values but stay stable within the page (no "!=" in the canvas read). +assert window.fp.canvas !== window.off.canvas && !window.fp.canvas.includes("!=") && window.fp.audio !== window.off.audio +# Every probed font measures as installed. +assert window.fp.fonts.count === 32 +# Replaced functions still look native; frames (markup and script-made) see the same values as the page. +assert window.fp.nativeLooking === true +assert window.fp.frameMismatch.static.length === 0 && window.fp.frameMismatch.scripted.length === 0 +# The time zone and language stay real. +assert window.fp.timezone === Intl.DateTimeFormat().resolvedOptions().timeZone && window.fp.language === navigator.language +# Same site, same run: the same canvas value after a reload. +js location.href = "?again#" + window.fp.canvas +wait 1 +waitfor 30 document.title === "FP done" +assert window.fp.canvas === location.hash.slice(1) +flyout shield +wait 1 +shot shield-on +flyout none +page nacre://settings/privacy_mode +wait 2 +shot settings-privacy-mode +status done +quit diff --git a/tests/smoke/privacy-net.txt b/tests/smoke/privacy-net.txt new file mode 100644 index 0000000..5f3c00d --- /dev/null +++ b/tests/smoke/privacy-net.txt @@ -0,0 +1,94 @@ +# Request headers and third-party cookies in the vendored servo-net (S023); frame document.cookie and privacy +# mode paused per site (S024). 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" +# document.cookie in a cross-site frame (S024, script layer): empty and not stored with blocking on, works off. +set /privacy/block_third_party true +wait 1 +open http://site.nacre.test:8766/jstp?tag=jon +waitfor 20 document.title === "JSTP jon done" +set /privacy/block_third_party false +wait 1 +open http://site.nacre.test:8766/jstp?tag=joff +waitfor 20 document.title === "JSTP joff done" +open http://127.0.0.1:8767/cookies +waitfor 20 document.title.startsWith("Cookies ") +assert !document.title.includes("jsjon") && document.title.includes("jsjoff=1") +# Privacy mode paused on one site (S024): common values on other sites, the engine's own on the paused one. +set /privacy/mode true +set /privacy/mode_off ["127.0.0.1"] +wait 1 +open http://site.nacre.test:8766/echo?pm +waitfor 20 document.title === "Echo pm" +assert navigator.hardwareConcurrency === 8 && navigator.platform === "Linux x86_64" && navigator.appVersion === "5.0 (X11)" +open http://127.0.0.1:8767/echo?paused +waitfor 20 document.title === "Echo paused" +assert navigator.platform === "Linux" && navigator.appVersion === "4.0" +set /privacy/mode_off [] +set /privacy/mode false +# 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")) +# The cross-site frame's document.cookie: empty when blocked, 127.0.0.1's cookies when not. +assert window.reqs.some(r => r.path === "/note?tag=jon&seen=") && window.reqs.some(r => r.path.startsWith("/note?tag=joff&seen=") && r.path.includes("fp%3D1")) +# Accept-Language: Firefox's list in privacy mode (S024), Servo's single locale otherwise. +assert window.reqs.filter(r => r.path === "/echo?pm").every(r => r.lang === navigator.language + "," + navigator.language.split("-")[0] + ";q=0.5") && window.reqs.filter(r => r.path === "/echo?nodnt").every(r => r.lang === navigator.language) +# 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/tools/smoke.sh b/tools/smoke.sh index c5ee72f..867bbad 100755 --- a/tools/smoke.sh +++ b/tools/smoke.sh @@ -15,7 +15,13 @@ # SMOKE_TIMEOUT=s kill the browser after s seconds (default 180) # SMOKE_SIZE=WxH screen size (default 1280x800) # SMOKE_BIN=path browser binary (default target/release/nacre) +# SMOKE_ARGS="..." extra command-line arguments for the browser (e.g. --incognito) # NACRE_NO_BRIDGE=1 passed through: no network bridge +# SMOKE_FAKE_DISCORD=1 start tests/smoke/net/fake-discord.py on $XDG_RUNTIME_DIR/discord-ipc-0; it logs every frame +# it gets to outdir/discord.log (one JSON line each) +# SMOKE_KEYRING=1 give the run its own session bus with a throwaway GNOME Keyring (password "smoke", unlocked) +# kept in home/, so the OS keyring path is used (cookie key, S025); SMOKE_HOME reruns find the +# same key. Without it the run has no session bus, hence no keyring. # SMOKE_VISIBLE=1 show the window on the user's screen (their Wayland display, niri monitor # SMOKE_MONITOR, default DP-1) with the real GPU instead of hidden Xvfb + software GL; # only the Wayland socket is shared, profile/runtime dir/bus stay throwaway @@ -56,6 +62,9 @@ chmod 700 "$runtime" xvfb_pid= cleanup() { [ -n "$xvfb_pid" ] && kill "$xvfb_pid" 2>/dev/null + [ -n "${discord_pid:-}" ] && kill "$discord_pid" 2>/dev/null + [ -n "${keyring_pid:-}" ] && kill "$keyring_pid" 2>/dev/null + [ -n "${bus_pid:-}" ] && kill "$bus_pid" 2>/dev/null rm -rf "$runtime" } trap cleanup EXIT @@ -79,13 +88,45 @@ else dispvars=(DISPLAY=":$display" XDG_SESSION_TYPE=x11 LIBGL_ALWAYS_SOFTWARE=1) fi +if [ -n "${SMOKE_FAKE_DISCORD:-}" ]; then + : >"$out/discord.log" + python3 "$root/tests/smoke/net/fake-discord.py" "$runtime/discord-ipc-0" "$out/discord.log" & + discord_pid=$! + for _ in $(seq 50); do [ -S "$runtime/discord-ipc-0" ] && break; sleep 0.1; done +fi + +busvars=() +if [ -n "${SMOKE_KEYRING:-}" ]; then + mkdir -p "$home/.local/share" + # A bus without service activation: only the keyring on it (no gvfs mounts, portals or the user's services). + cat >"$runtime/bus.conf" < +sessionunix:path=$runtime/bus + +CONF + env -i PATH="$PATH" HOME="$home" XDG_RUNTIME_DIR="$runtime" \ + dbus-daemon --config-file="$runtime/bus.conf" --nofork --nopidfile >"$out/bus.log" 2>&1 & + bus_pid=$! + for _ in $(seq 50); do [ -S "$runtime/bus" ] && break; sleep 0.1; done + busvars=(DBUS_SESSION_BUS_ADDRESS="unix:path=$runtime/bus") + # The login keyring's password is "smoke" (an empty one leaves no default collection). + printf 'smoke' | env -i PATH="$PATH" HOME="$home" XDG_DATA_HOME="$home/.local/share" XDG_RUNTIME_DIR="$runtime" \ + "${busvars[@]}" gnome-keyring-daemon --foreground --unlock --components=secrets >"$out/keyring.log" 2>&1 & + keyring_pid=$! + for _ in $(seq 50); do + env "${busvars[@]}" dbus-send --session --dest=org.freedesktop.DBus --print-reply /org/freedesktop/DBus org.freedesktop.DBus.NameHasOwner \ + string:org.freedesktop.secrets 2>/dev/null | grep -q true && break + sleep 0.1 + done +fi + env -u WAYLAND_DISPLAY -u DISPLAY -u DBUS_SESSION_BUS_ADDRESS -u NACRE_HOME \ -u http_proxy -u https_proxy -u all_proxy -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY \ - "${dispvars[@]}" \ + "${dispvars[@]}" "${busvars[@]}" \ HOME="$home" XDG_CONFIG_HOME="$home/.config" XDG_DATA_HOME="$home/.local/share" \ XDG_CACHE_HOME="$home/.cache" XDG_STATE_HOME="$home/.local/state" XDG_RUNTIME_DIR="$runtime" \ RUST_BACKTRACE=1 NACRE_SCRIPT="$out/script.txt" \ - timeout -k 10 "${SMOKE_TIMEOUT:-180}" "$bin" >"$out/nacre.log" 2>&1 + timeout -k 10 "${SMOKE_TIMEOUT:-180}" "$bin" ${SMOKE_ARGS:-} >"$out/nacre.log" 2>&1 code=$? fail=0 diff --git a/vendor/servo-net/Cargo.toml b/vendor/servo-net/Cargo.toml index b341f0b..d9ff1c0 100644 --- a/vendor/servo-net/Cargo.toml +++ b/vendor/servo-net/Cargo.toml @@ -266,6 +266,10 @@ version = "0.8.0" [dependencies.serde] version = "1.0.228" +# Nacre patch (S025): the cookie jar handed to and from the embedder (nacre.rs). +[dependencies.serde_json] +version = "1" + [dependencies.servo-base] version = "=0.7.0" diff --git a/vendor/servo-net/fetch/methods.rs b/vendor/servo-net/fetch/methods.rs index 5529c42..c24dec1 100644 --- a/vendor/servo-net/fetch/methods.rs +++ b/vendor/servo-net/fetch/methods.rs @@ -251,6 +251,8 @@ pub async fn fetch_with_cors_cache( // Step 12. If request’s header list does not contain `Accept-Language`, then user agents should // append (`Accept-Language, an appropriate header value) to request’s header list. + // Nacre patch (S024): privacy mode's Firefox-style language list goes in before Servo's single locale. + crate::nacre::append_accept_language(&mut request.headers); set_default_accept_language(&mut request.headers); // Step 15. If request’s internal priority is null, then use request’s priority, initiator, 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..c7440b5 --- /dev/null +++ b/vendor/servo-net/nacre.rs @@ -0,0 +1,206 @@ +/* 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::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, LazyLock, Weak}; + +use http::{HeaderMap, HeaderName, HeaderValue}; +use net_traits::pub_domains::reg_suffix; +use parking_lot::{Mutex, RwLock}; +use rustc_hash::FxHashMap; +use servo_base::id::WebViewId; +use servo_url::ServoUrl; + +use crate::cookie_storage::CookieStorage; +use crate::http_loader::HttpState; + +static EXTRA_HEADERS: RwLock> = RwLock::new(Vec::new()); +static BLOCK_THIRD_PARTY: AtomicBool = AtomicBool::new(false); +static LANGUAGE_LIST: AtomicBool = AtomicBool::new(false); +static TOP_SITES: LazyLock>> = LazyLock::new(Default::default); +static INITIAL_COOKIES: Mutex>> = Mutex::new(None); +static COOKIE_SAVER: RwLock>> = RwLock::new(None); +static PUBLIC_STATE: RwLock>> = RwLock::new(None); + +/// 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()); + } + } +} + +/// The languages pages are told about, Firefox-style: the locale and its bare language (`["en-US", "en"]`), or +/// the locale alone when it has no region. Servo itself sends only the locale (S024). +pub fn languages(locale: &str) -> Vec { + match locale.split_once('-') { + Some((language, _)) if !language.is_empty() => vec![locale.to_owned(), language.to_owned()], + _ => vec![locale.to_owned()], + } +} + +/// The Accept-Language value for `languages`, with Firefox's weights: "en-US,en;q=0.5". +pub fn accept_language(languages: &[String]) -> String { + let weighted: Vec = languages + .iter() + .enumerate() + .map(|(i, language)| match i { + 0 => language.clone(), + _ => format!("{language};q={:.1}", (1.0 - i as f32 * 0.5).max(0.1)), + }) + .collect(); + weighted.join(",") +} + +/// The system locale Servo uses for `navigator.language` and Accept-Language. +pub fn locale() -> String { + net_traits::get_current_locale().0.clone() +} + +/// Sends the Firefox-style language list instead of Servo's single locale (privacy mode). +pub fn set_language_list(on: bool) { + LANGUAGE_LIST.store(on, Ordering::Relaxed); +} + +/// Puts the language list in Accept-Language when it's on and the request has none yet or Servo's own single +/// locale (navigations arrive with it set); runs before Servo's default (fetch step 12). A page's own value stays. +pub fn append_accept_language(headers: &mut HeaderMap) { + if !LANGUAGE_LIST.load(Ordering::Relaxed) { + return; + } + if headers + .get(http::header::ACCEPT_LANGUAGE) + .is_some_and(|value| value.as_bytes() != locale().as_bytes()) + { + return; + } + if let Ok(value) = HeaderValue::from_str(&accept_language(&languages(&locale()))) { + headers.insert(http::header::ACCEPT_LANGUAGE, value); + } +} + +/// 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)) +} + +/// Hands the (public) cookie jar to the embedder (S025): Servo 0.7 keeps it as plain JSON in +/// `/cookie_jar.json`. Call before Servo starts. `initial` is a jar in that JSON format to start with +/// (`None`: an empty jar); `save` gets the jar as JSON when Servo exits. cookie_jar.json is neither read nor +/// written afterwards; the embedder can also take a copy at any time with `cookie_jar_snapshot`. +pub fn set_cookie_persistence(initial: Option>, save: Box) { + *INITIAL_COOKIES.lock() = initial; + *COOKIE_SAVER.write() = Some(save); +} + +/// Whether the embedder keeps the cookie jar (`set_cookie_persistence` was called). +pub(crate) fn embedder_keeps_cookies() -> bool { + COOKIE_SAVER.read().is_some() +} + +/// The embedder's starting jar, once. Unreadable JSON gives an empty jar (the embedder keeps its own copy). +pub(crate) fn take_initial_cookie_jar() -> Option { + let bytes = INITIAL_COOKIES.lock().take()?; + match serde_json::from_slice(&bytes) { + Ok(jar) => Some(jar), + Err(error) => { + log::warn!("embedder cookie jar unreadable: {error}"); + None + }, + } +} + +pub(crate) fn register_public_state(state: &Arc) { + *PUBLIC_STATE.write() = Some(Arc::downgrade(state)); +} + +/// The live public cookie jar as JSON, or `None` before Servo starts or after it has shut down. +pub fn cookie_jar_snapshot() -> Option> { + let state = PUBLIC_STATE.read().as_ref()?.upgrade()?; + let jar = state.cookie_jar.read(); + serde_json::to_vec(&*jar).ok() +} + +/// At exit: gives the public jar to the embedder's saver. True when the embedder keeps the cookies (then +/// nothing must go to cookie_jar.json, also not for another state). +pub(crate) fn save_cookie_jar_at_exit(state: &Arc) -> bool { + let saver = COOKIE_SAVER.read(); + let Some(save) = saver.as_ref() else { return false }; + let public = PUBLIC_STATE + .read() + .as_ref() + .is_some_and(|weak| std::ptr::eq(weak.as_ptr(), Arc::as_ptr(state))); + if public { + let json = serde_json::to_vec(&*state.cookie_jar.read()); + match json { + Ok(json) => save(&json), + Err(error) => log::warn!("cookie jar not serialized: {error}"), + } + } + true +} diff --git a/vendor/servo-net/resource_thread.rs b/vendor/servo-net/resource_thread.rs index 2255cc5..eeb434e 100644 --- a/vendor/servo-net/resource_thread.rs +++ b/vendor/servo-net/resource_thread.rs @@ -211,7 +211,13 @@ fn create_http_states( if let Some(config_dir) = config_dir { servo_base::read_json_from_file(&mut auth_cache, config_dir, "auth_cache.json"); servo_base::read_json_from_file(&mut hsts_list, config_dir, "hsts_list.json"); - servo_base::read_json_from_file(&mut cookie_jar, config_dir, "cookie_jar.json"); + // Nacre patch (S025): an embedder-held jar replaces cookie_jar.json. + if !crate::nacre::embedder_keeps_cookies() { + servo_base::read_json_from_file(&mut cookie_jar, config_dir, "cookie_jar.json"); + } + } + if let Some(jar) = crate::nacre::take_initial_cookie_jar() { + cookie_jar = jar; } let override_manager = CertificateErrorOverrideManager::new(); @@ -246,7 +252,9 @@ fn create_http_states( embedder_proxy, }; - (Arc::new(http_state), Arc::new(private_http_state)) + let http_state = Arc::new(http_state); + crate::nacre::register_public_state(&http_state); // Nacre patch (S025) + (http_state, Arc::new(private_http_state)) } impl ResourceChannelManager { @@ -665,11 +673,15 @@ impl ResourceChannelManager { CoreResourceMsg::Exit(sender) => { // Nacre patch: keep this session's HTTP cache for the next start. http_state.http_cache.flush_to_disk(); + // Nacre patch (S025): an embedder-held jar is saved through the embedder, never to cookie_jar.json. + let embedder_saved = crate::nacre::save_cookie_jar_at_exit(http_state); if let Some(ref config_dir) = self.config_dir { let auth_cache = http_state.auth_cache.read(); servo_base::write_json_to_file(&*auth_cache, config_dir, "auth_cache.json"); - let jar = http_state.cookie_jar.read(); - servo_base::write_json_to_file(&*jar, config_dir, "cookie_jar.json"); + if !embedder_saved { + let jar = http_state.cookie_jar.read(); + servo_base::write_json_to_file(&*jar, config_dir, "cookie_jar.json"); + } let hsts = http_state.hsts_list.read(); servo_base::write_json_to_file(&*hsts, config_dir, "hsts_list.json"); } 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