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 <[email protected]>
This commit is contained in:
astar76 2026-11-12 15:34:32 -06:00
commit 69b385f1da
19 changed files with 357 additions and 34 deletions

View file

@ -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=<file>` runs script commands (listed at its top) | now |
| `tools/smoke.sh <script> [outdir]` | smoke run on a hidden Xvfb display with a throwaway home and software GL; outdir (default `target/smoke/<name>-<time>`) gets `nacre.log`, `selftest.log`, `<shot>.png`, `<status>.json`, `home/`; exits non-zero on crash, panic, no `status done` or a failed `assert <js>`. Scripts in `tests/smoke/` (`launch.txt` offline, `https.txt` needs internet, `restore.txt` with `SMOKE_HOME=<launch outdir>/home`, `chrome.txt` chrome and every flyout dark and light, offline; `colours.txt` colours after welcome and site colour vs internal pages, hidden `SMOKE_SIZE=1280x1100`; `input.txt` real clicks, typing, right click, wheel on a web page, offline; `basics.txt` tabs, navigation, find, zoom, full screen, pop-ups, offline; `heavy-web.txt` DuckDuckGo, Wikipedia, YouTube, needs internet, `SMOKE_TIMEOUT=900`; `keys.txt` every shortcut action, offline; `site-doctor.txt` Google sign-in, captchas, Reddit, GitHub, needs internet; `cache.txt` HTTP cache, offline, start `python3 tests/smoke/cache/server.py &` first; selftest `launch <args>` checks single instance); header documents env vars and commands. `SMOKE_VISIBLE=1` shows the run on the user's screen (DP-1, real GPU, niri tiles the window so shots are narrower); use it whenever the user is watching (D-009). Read the PNGs | now (S003) |
| `tools/smoke.sh <script> [outdir]` | smoke run on a hidden Xvfb display with a throwaway home and software GL; outdir (default `target/smoke/<name>-<time>`) gets `nacre.log`, `selftest.log`, `<shot>.png`, `<status>.json`, `home/`; exits non-zero on crash, panic, no `status done` or a failed `assert <js>`. Scripts in `tests/smoke/` (`launch.txt` offline, `https.txt` needs internet, `restore.txt` with `SMOKE_HOME=<launch outdir>/home`, `chrome.txt` chrome and every flyout dark and light, offline; `colours.txt` colours after welcome and site colour vs internal pages, hidden `SMOKE_SIZE=1280x1100`; `input.txt` real clicks, typing, right click, wheel on a web page, offline; `basics.txt` tabs, navigation, find, zoom, full screen, pop-ups, offline; `heavy-web.txt` DuckDuckGo, Wikipedia, YouTube, needs internet, `SMOKE_TIMEOUT=900`; `keys.txt` every shortcut action, offline; `privacy-net.txt` DNT/GPC/Save-Data headers and third-party cookies on a loopback server, offline, start `python3 tests/smoke/net/server.py &` first; `site-doctor.txt` Google sign-in, captchas, Reddit, GitHub, needs internet; `cache.txt` HTTP cache, offline, start `python3 tests/smoke/cache/server.py &` first; selftest `launch <args>` checks single instance); header documents env vars and commands. `SMOKE_VISIBLE=1` shows the run on the user's screen (DP-1, real GPU, niri tiles the window so shots are narrower); use it whenever the user is watching (D-009). Read the PNGs | now (S003) |
| `nacre://gallery` + `SMOKE_SIZE=1400x2800 tools/smoke.sh tests/smoke/gallery.txt` | every design token and widget, dark and light (+ new tab and settings shots); read the PNGs | now (S015) |
| `SMOKE_SIZE=1400x1200 tools/smoke.sh tests/smoke/newtab.txt` | new tab page dark/light, nothing playing and a video playing, weather failed state, tall/narrow/phone widths (offline); `tests/smoke/newtab-weather.txt` shoots the real weather card (needs internet); read the PNGs | now (S017) |
| `SMOKE_SIZE=1400x900 tools/smoke.sh tests/smoke/backgrounds.txt` | every new tab background with the pointer, Customize panel dark/light, image + blur, GIF frames; `perf-*-a/b.json` `frames` (median/max draw ms, `drawn` count) per background at Lots/Fast, hidden tab, still, Motion off. Selftest `pointer x y`, `customize`; `@PAGESDIR@` = path of tests/smoke/pages | now (S018) |

1
Cargo.lock generated
View file

@ -4907,6 +4907,7 @@ dependencies = [
"serde",
"serde_json",
"servo",
"servo-net",
"spellbook",
"ureq",
"url",

View file

@ -47,6 +47,9 @@ rustls = { version = "0.23", default-features = false, features = ["aws_lc_rs",
content-security-policy = "0.9"
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "ico", "webp", "gif", "bmp"] }
log = "0.4"
# The vendored servo-net (see [patch.crates-io]): Nacre sets request headers and third-party cookie blocking
# through its `nacre` module (S023).
servo-net = "=0.7.0"
# Ad blocking
adblock = { version = "0.13.5", default-features = false, features = ["embedded-domain-resolver", "full-regex-handling"] }
@ -93,7 +96,8 @@ opt-level = 2
# epaint 0.37.0 panics when Servo's canvas enables vello_cpu/multithreading; the vendored copy renders glyphs
# single-threaded (vendor/epaint/src/text/font_face.rs, end of file). Drop when egui ships a fix.
# servo-net 0.7.0 keeps hyper's 16 KiB HTTP/2 header limit, which breaks YouTube; the vendored copy raises it
# (vendor/servo-net/connector.rs, create_http_client). Drop when Servo sets it.
# (vendor/servo-net/connector.rs, create_http_client). Drop when Servo sets it. Every servo-net patch is listed in
# docs/DESIGN.md "Vendored servo-net patches".
[patch.crates-io]
epaint = { path = "vendor/epaint" }
servo-net = { path = "vendor/servo-net" }

View file

@ -11,13 +11,13 @@ Two Servo 0.7 engine limits sit in servo-net, which Nacre already vendors (D-012
- `vendor/servo-net/http_loader.rs` (request header assembly), `cookie_storage.rs`, `cookie.rs` (where cookies are set and sent; how the top-level site of a request is known)
## Steps
- [ ] Find where outgoing headers are built and where cookies are stored/sent with the request's top-level origin; write the minimal patch points in DESIGN.md
- [ ] Extra request headers: a process-wide, embedder-set list (e.g. `DNT: 1`, `Sec-GPC: 1`) read in http_loader; Nacre sets it from settings; unit test in the vendored crate or a loopback test
- [ ] Third-party cookie blocking: when on, don't store or send cookies whose domain doesn't match the top-level site (keep same-site subdomains); setting in Settings → Privacy, privacy mode turns it on; unit tests for the site matching
- [ ] Settings rows: DNT / GPC and third-party cookies move from limited/unavailable to working rows
- [ ] Verify against a loopback HTTP server (headers echoed, cookies on a cross-site iframe) in a smoke script; no internet needed
- [ ] Keep every servo-net patch listed in DESIGN.md (file, function, why) so a Servo upgrade can re-apply them
- [ ] PROGRESS entry, INDEX line, commit `S023: …` and push
- [x] Find where outgoing headers are built and where cookies are stored/sent with the request's top-level origin; write the minimal patch points in DESIGN.md
- [x] Extra request headers: a process-wide, embedder-set list (e.g. `DNT: 1`, `Sec-GPC: 1`) read in http_loader; Nacre sets it from settings; unit test in the vendored crate or a loopback test
- [x] Third-party cookie blocking: when on, don't store or send cookies whose domain doesn't match the top-level site (keep same-site subdomains); setting in Settings → Privacy, privacy mode turns it on; unit tests for the site matching
- [x] Settings rows: DNT / GPC and third-party cookies move from limited/unavailable to working rows
- [x] Verify against a loopback HTTP server (headers echoed, cookies on a cross-site iframe) in a smoke script; no internet needed
- [x] Keep every servo-net patch listed in DESIGN.md (file, function, why) so a Servo upgrade can re-apply them
- [x] PROGRESS entry, INDEX line, commit `S023: …` and push
## End criteria
- The loopback smoke shows the headers arriving and third-party cookies not stored/sent when blocking is on (and still working when off).

View file

@ -42,6 +42,6 @@ Tracker: https://claude.ai/artifact/9AD7fPfwJ4ASFzVTJGKU4h
- [ ] [S030 — Ship GStreamer with MSE (AppImage and Windows)](05%20Engine/S030-media-packaging.md) · Opus medium
## 06 Privacy
- [ ] [S023 — Request headers and third-party cookies in servo-net](06%20Privacy/S023-net-headers-cookies.md) · Opus medium
- [x] [S023 — Request headers and third-party cookies in servo-net](06%20Privacy/S023-net-headers-cookies.md) · Opus medium
- [ ] [S024 — Privacy mode that holds up](06%20Privacy/S024-privacy-mode.md) · Opus high
- [ ] [S025 — Cookies encrypted at rest](06%20Privacy/S025-cookie-encryption.md) · Opus medium

View file

@ -19,3 +19,4 @@
- D-014 — 2026-11-12 — Two more Nacre patches in the vendored servo-net (D-012), marked "Nacre patch": `fetch/methods.rs` lets the certificate warning's `chrome:allowcert` request through (it ended as UnsupportedScheme, so "Open anyway" never worked); `http_cache.rs` `flush_to_disk` + `resource_thread.rs` Exit write the memory HTTP cache to the disk cache at quit (Servo only wrote evicted entries, so a session's cache was lost). — Both are Servo 0.7 bugs the embedder can't work around. — any plan that upgrades Servo: re-check both, re-run `tests/smoke/net-privacy.txt` and `cache.txt` + `cache-restart.txt`
- D-015 — 2026-11-12 — MSE: go, option A (S022). Keep GStreamer's gst_mse library for parsing and coded frame processing; Nacre fixes its three 1.28.9 defects (early update-end, idle ticks, split A/V init segments) in its own copy of the library and plugin, plus a thin MSE DOM in the vendored `servo-script`/`servo-script-bindings`/`servo-media*` crates (`[patch.crates-io]`, like D-012). Option B (an own MSE core in Rust feeding appsrc) is the fallback only if bug 3 can't be fixed in msesrc. Plans S026–S030 run after S009 and before S023–S025. The prototype branch `s022-mse-proto` carries S026–S027 and merges into main in S028. — Decided by the orchestrator overnight on the user's standing OK; the user wants engine fixes, not workarounds (no yt-dlp). The spike showed gst_mse does the hard parts, and the blockers are concrete (docs/engine/mse-spike.md). — S026–S030, any Servo upgrade (drop the patches when Servo ships MSE)
- D-016 — 2026-11-12 — Patched gst_mse loading (S026). Nacre ships its own `libgstmse-1.0.so.0` and `mse` plugin built from `vendor/gst-mse` (`tools/gst-mse.sh`). Release layout: library in `<exe dir>/lib/`, plugin in `<exe dir>/lib/gstreamer-1.0/`; a dev build uses `target/gst-mse/{lib,gstreamer-1.0}`. The binary's RUNPATH (`$ORIGIN/lib:$ORIGIN/../gst-mse/lib`, from `build.rs`) finds the library ahead of the system copy (same soname), and `main.rs` prepends the plugin dir to `GST_PLUGIN_PATH` before GStreamer starts (paths in GST_PLUGIN_PATH beat the system plugin of the same name). Windows: the DLLs sit next to `nacre.exe` / in `lib\gstreamer-1.0` (unverified). — RUNPATH needs no wrapper script or re-exec; LD_LIBRARY_PATH would have to be set before the process starts. — S030 packaging (AppImage, tarball, Windows), S028 merge
- D-017 — 2026-11-12 — Request headers and third-party cookie blocking are Nacre patches in the vendored servo-net (S023): new module `nacre.rs` holds embedder-set state (extra headers, block switch, top-level site per webview); `http_loader.rs` and `websocket_loader.rs` read it. A request is third-party when its host's registrable domain differs from its webview's top-level site; blocking is on when the setting or privacy mode is on (`App::refresh_hub_config`). — Servo 0.7 has neither; the user wants engine fixes. `document.cookie` in cross-site frames stays uncovered (script isn't vendored). — S024 (privacy mode only needs `privacy_mode_on`), any Servo upgrade (re-apply from DESIGN.md "Vendored servo-net patches", re-run `privacy-net.txt`)

View file

@ -145,6 +145,30 @@ picture-in-picture, extensions, password capture, printing.
(`inject.rs`) copies each icon's computed colour into its `color` attribute (hover colours not followed).
- CSS `mask-image` icons (e.g. Wikipedia's) paint as solid squares. HTTP/2 header limit: see D-012.
## Vendored servo-net patches
`vendor/servo-net` is servo-net 0.7.0 through `[patch.crates-io]` (D-012). Every Nacre change is marked
`Nacre patch` in the code; a Servo upgrade re-applies the ones upstream still needs, then re-runs the smoke scripts named.
| File, function | What and why | Re-check |
|---|---|---|
| `connector.rs` `create_http_client` | `http2_max_header_list_size(256 KiB)`: hyper's 16 KiB default refuses YouTube's response headers (D-012) | `heavy-web.txt` |
| `fetch/methods.rs` `main_fetch` (scheme fetch) | lets the certificate warning's `chrome:allowcert` request through; it ended as UnsupportedScheme (D-014) | `net-privacy.txt` |
| `http_cache.rs` `flush_to_disk`, `resource_thread.rs` Exit | writes the memory HTTP cache to the disk cache at quit (D-014) | `cache.txt`, `cache-restart.txt` |
| `nacre.rs` (new module, `pub mod nacre` in `lib.rs`) | embedder-set state the patches below read: extra request headers, the third-party cookie switch, the top-level site per webview, site matching (S023) | `privacy-net.txt` |
| `http_loader.rs` `http_network_or_cache_fetch` (step 8.15) | appends the embedder's extra headers (`DNT`, `Sec-GPC`, `Save-Data`) unless the request already has them; records a `Document` request's site as its webview's top-level site; skips the `Cookie` header for a third-party request (S023) | `privacy-net.txt` |
| `http_loader.rs` `http_network_fetch` (step 15) | doesn't store `Set-Cookie` from a third-party response (S023) | `privacy-net.txt` |
| `websocket_loader.rs` `create_handshake_request`, `process_ws_response` | the same third-party rule for WebSocket handshakes (S023) | unit tests only |
Third-party rule (S023): a request is third-party when its host's site (registrable domain, eTLD+1; an IP address
or a single-label host stands for itself) differs from the top-level site of its webview. Scheme and port don't
count, so `a.example.com` on `example.com` stays first-party. The top-level site comes from the last `Document`
request of that webview (net sees it before any subresource) and from the hub's `notify_url_changed` (history
navigations without a request, downloads that didn't replace the page); `notify_closed` forgets it. Requests with no
webview or no known top-level site are never blocked. `Document` requests are never blocked; `IFrame` documents are
checked like any subresource. Not covered: `document.cookie` and the Cookie Store API in a third-party frame
(script sends those to net with no webview id; servo-script isn't vendored).
## UI system (S015)
Everything the interface draws takes its colours, radii, sizes and springs from `src/theme.rs`; widgets live in

View file

@ -72,7 +72,7 @@ written.
| Preload pages | written (DNS warm-up) |
| Smooth scrolling | written (CSS) |
| Still new tab background | written |
| Save data | partial: JS hint, no request header |
| Save data | verified S023 (privacy-net.txt): `Save-Data: on` header (vendored servo-net) plus the JS hint |
| Hardware acceleration | written (software GL, restart) |
## Privacy
@ -84,9 +84,9 @@ written.
| HTTPS-only mode with fallback prompt and exceptions | verified S007 (net-privacy.txt: upgrade via the `location.replace()` page, certificate warning "Open anyway" (fixed: servo-net patch), fallback prompt + Open anyway, site stays http this session, local addresses never upgraded); "Always for this site" not tapped |
| Site settings (defaults and per-site) | verified S008 (site-memory*.txt, restart): stored per site, applied again after a restart. Enforced: pop-ups, notifications, images (hub blocks image requests), sound (tab muted on load), Servo's own requests, open-other-apps. Shown as "Not available" (Servo 0.7): location (navigator.geolocation never answers), camera, microphone, device list (no navigator.mediaDevices), persistent storage (no navigator.storage), clipboard, JavaScript. Per-site privacy-mode flag does not exist (privacy mode is global; S024) |
| Delete browsing data (+ on exit) | written |
| Send Do Not Track and GPC | partial: JS only (no headers in Servo 0.7) |
| Send Do Not Track and GPC | verified S023 (privacy-net.txt): `DNT: 1` + `Sec-GPC: 1` on every request (vendored servo-net), plus the JS properties |
| Remove tracking parameters | verified S007 (net-privacy.txt: utm_*/fbclid removed, other parameters kept, off keeps all) |
| Block third-party cookies | engine limit, shown as unavailable |
| Block third-party cookies | verified S023 (privacy-net.txt): cross-site requests send and store no cookies (vendored servo-net), same-site subdomains keep theirs, on in privacy mode. `document.cookie` in a cross-site frame isn't covered |
| Google sign-in quirk | written (UA switch + JS) |
| Sites where ad blocking is paused | verified S007 (net-adblock.txt), persisted S008 (site-memory*.txt) |
| Remote debugging, user agent | written |

View file

@ -286,6 +286,15 @@ Done: Discord against a fake IPC server (`SMOKE_FAKE_DISCORD=1`, `tests/smoke/ne
Not done: real Discord, real gamepad, spell dictionary download/add word/other languages, per-site Discord IDs, media flyout/visualizer/mute (S005 did PiP).
Later: S010 list: user checks the Discord icon with their own client (the Discord client may refuse a `.ico` icon; then a PNG source is needed), plays a real gamepad, tries the dictionary download.
## S023 — Request headers and third-party cookies in servo-net (2026-11-12)
- Done: `vendor/servo-net/nacre.rs` (Nacre patch, D-017): embedder-set extra headers, third-party cookie switch, top-level site per webview (from Document requests and `notify_url_changed`, forgotten on close). `http_loader.rs` adds the headers and skips sending/storing cookies for third-party requests; same for WebSocket handshakes. Nacre sets them in `refresh_hub_config` (`hub::privacy_headers`: DNT + Sec-GPC, Save-Data).
- Settings: "Send Do Not Track and GPC", "Save data" and "Block third-party cookies" are plain working switches; blocking is also on in privacy mode (`App::privacy_mode_on`).
- Tests: 2 new unit tests (headers; site matching incl. subdomains, eTLD+1, IPs), 64 green. `tests/smoke/privacy-net.txt` (loopback; server routes /setcookie, /cookies, /tp, /pixel, /reset, `reqs` log) green twice: cross-site frame and picture get and store no cookies when on, do when off, blocked again in privacy mode; same-site subdomain keeps its cookie; headers present, gone with DNT off. net-privacy and launch still green.
- Patch list for Servo upgrades: DESIGN.md "Vendored servo-net patches" (all patch sites).
- Not done: `document.cookie` / Cookie Store API in cross-site frames (script sends no webview id; servo-script not vendored). No real-site login check with blocking on (Google/GitHub sign-in) — for the user.
- Handoff to S024: privacy mode already turns third-party cookie blocking on; S024 only extends `App::privacy_mode_on` if it adds per-window/per-site modes.
- Later: a test server left by an older session held ports 8766/8767 with stale code; stop old ones before net smokes.
## Later
- Turnstile widget paints as a black half-disc (Servo painting of its iframe/shadow DOM, S006 site doctor).
- Google sign-in past the email step: press Next with a real account, by the user (S006).

View file

@ -4,9 +4,8 @@ Things to check or fix in the review passes before the first build. Remove an it
- discord.rs on Windows: named-pipe reads block (no read timeout on `File`). Read only during the handshake
there, or use a reader thread.
- Servo can't add request headers or strip cookies per request, so "Send Do Not Track & GPC" only sets
`navigator.globalPrivacyControl`/`doNotTrack` in pages, and "Block third-party cookies" is not possible.
Settings must say so (shown as "partial" / "not available with this engine").
- Done in S023: request headers (DNT, Sec-GPC, Save-Data) and third-party cookie blocking are patches in the
vendored servo-net (docs/DESIGN.md "Vendored servo-net patches"); `document.cookie` in cross-site frames is not covered.
- Servo's request interceptor holds a global lock while the embedder answers: `load_web_resource` must answer
synchronously, never keep a `WebResourceLoad` waiting.
- Intercepted responses skip redirect handling, so HTTPS-only and tracking-parameter stripping serve a tiny page

View file

@ -396,6 +396,14 @@ impl App {
pub fn refresh_hub_config(&self) {
let settings = self.shared.settings.borrow();
*self.hub.config.borrow_mut() = HubConfig::from_settings(&settings, &self.shared.permissions.borrow(), &self.shared.user_agent.borrow(), self.shared.http_allowed.borrow().clone());
// Request headers and the cookie policy live in the vendored servo-net (S023).
net::nacre::set_extra_request_headers(&crate::hub::privacy_headers(&settings));
net::nacre::set_block_third_party_cookies(settings.privacy.block_third_party || self.privacy_mode_on(&settings));
}
/// Privacy mode: on everywhere, or in incognito windows when the user chose that.
fn privacy_mode_on(&self, s: &Settings) -> bool {
s.privacy.mode || (self.shared.incognito && s.privacy.mode_incognito)
}
/// (Re)build the scripts every page gets. Applies on each page's next load.
@ -405,7 +413,7 @@ impl App {
ucm.remove_script(script);
}
let s = self.shared.settings.borrow().clone();
let privacy = s.privacy.mode || (self.shared.incognito && s.privacy.mode_incognito);
let privacy = self.privacy_mode_on(&s);
let options = inject::Options {
token: &self.hub.token,
privacy_mode: privacy,

View file

@ -125,6 +125,19 @@ const TRACKING_PARAMS: &[&str] = &[
];
const TRACKING_PREFIXES: &[&str] = &["utm_", "pk_", "mtm_", "hsa_"];
/// Headers every request carries for the privacy settings: Do Not Track with Global Privacy Control, and
/// Save-Data. Applied in the vendored servo-net (S023).
pub fn privacy_headers(settings: &Settings) -> Vec<(&'static str, &'static str)> {
let mut headers = Vec::new();
if settings.privacy.dnt {
headers.extend([("DNT", "1"), ("Sec-GPC", "1")]);
}
if settings.privacy.save_data {
headers.push(("Save-Data", "on"));
}
headers
}
/// The URL without tracking parameters, if it had any.
pub fn strip_tracking(url: &Url) -> Option<Url> {
url.query()?;
@ -304,6 +317,8 @@ impl Hub {
impl WebViewDelegate for Hub {
fn notify_url_changed(&self, webview: WebView, url: Url) {
// Covers pages shown without a request (history) and downloads that kept the old page.
net::nacre::set_top_level_url(webview.id(), &servo::ServoUrl::from_url(url.clone()));
self.push(Event::UrlChanged(webview.id(), url));
}
fn notify_page_title_changed(&self, webview: WebView, title: Option<String>) {
@ -331,6 +346,7 @@ impl WebViewDelegate for Hub {
self.push(Event::History(webview.id(), entries, current));
}
fn notify_closed(&self, webview: WebView) {
net::nacre::forget_webview(webview.id());
self.push(Event::Closed(webview.id()));
}
fn notify_crashed(&self, webview: WebView, reason: String, backtrace: Option<String>) {
@ -419,6 +435,51 @@ impl servo::GamepadDelegate for Gamepads {
mod tests {
use super::*;
#[test]
fn privacy_headers_follow_the_settings_and_reach_requests() {
let mut settings = Settings::default();
settings.privacy.dnt = true;
settings.privacy.save_data = false;
assert_eq!(privacy_headers(&settings), vec![("DNT", "1"), ("Sec-GPC", "1")]);
settings.privacy.dnt = false;
settings.privacy.save_data = true;
assert_eq!(privacy_headers(&settings), vec![("Save-Data", "on")]);
// servo-net adds them to a request unless the page set the header itself.
net::nacre::set_extra_request_headers(&[("DNT", "1"), ("Sec-GPC", "1"), ("Bad Name", "x")]);
let mut headers = HeaderMap::new();
headers.insert("Sec-GPC", HeaderValue::from_static("0"));
net::nacre::append_extra_headers(&mut headers);
assert_eq!(headers.len(), 2);
assert_eq!(headers["dnt"], "1");
assert_eq!(headers["sec-gpc"], "0");
net::nacre::set_extra_request_headers(&[]);
}
#[test]
fn third_party_matching_keeps_same_site_subdomains() {
use net::nacre::{is_third_party, site_of_host};
let url = |s: &str| servo::ServoUrl::parse(s).unwrap();
assert_eq!(site_of_host("www.Example.com"), "example.com");
assert_eq!(site_of_host("a.b.example.co.uk"), "example.co.uk");
assert_eq!(site_of_host("site.nacre.test"), "nacre.test");
assert_eq!(site_of_host("127.0.0.1"), "127.0.0.1");
assert_eq!(site_of_host("[::1]"), "[::1]");
assert_eq!(site_of_host("localhost"), "localhost");
let top = site_of_host("www.example.com");
assert!(!is_third_party(&top, &url("https://login.example.com/x")));
assert!(!is_third_party(&top, &url("http://example.com:8080/")));
assert!(is_third_party(&top, &url("https://tracker.net/p.gif")));
assert!(is_third_party(&top, &url("https://example.co.uk/")));
// Different users' sites under one public suffix are different sites.
let top = site_of_host("alice.github.io");
assert!(is_third_party(&top, &url("https://bob.github.io/")));
assert!(!is_third_party(&top, &url("https://alice.github.io/repo")));
// IP addresses only match themselves; URLs without a host are never third-party.
let top = site_of_host("127.0.0.1");
assert!(is_third_party(&top, &url("http://127.0.0.2/")));
assert!(!is_third_party(&top, &url("data:text/plain,x")));
}
#[test]
fn images_follow_the_site_answer_then_the_default() {
let mut settings = Settings::default();

View file

@ -717,7 +717,7 @@ fn performance(ui: &mut Ui, f: &mut Frame, s: &mut Settings) {
switch_row(ui, "Preload pages", "Looks up the addresses of links on a page ahead of time", &mut s.web.preload);
switch_row(ui, "Smooth scrolling", "Animated scrolling (off in low-memory mode)", &mut s.web.smooth_scroll);
switch_row(ui, "Still new tab background", "No animation on the new tab page", &mut s.perf.still_ntp);
limited_row(ui, "Save data", "Tells pages to be lighter and stops videos preloading", "Servo can't send the Save-Data header", |ui| switch(ui, &mut s.privacy.save_data));
switch_row(ui, "Save data", "Sends Save-Data so pages can be lighter, and stops videos preloading", &mut s.privacy.save_data);
row(ui, "Hardware acceleration", "Use the GPU. Turn off if pages show up black or blank; Off uses software rendering (restart to apply)", |ui| segmented(ui, &mut s.web.gpu, AutoOnOff::ALL));
});
}
@ -753,9 +753,9 @@ fn privacy(ui: &mut Ui, f: &mut Frame, s: &mut Settings) {
card(ui, |ui| {
row(ui, "Privacy mode", "Hides your browser's fingerprint (canvas, WebGL, screen and hardware details)", |ui| switch(ui, &mut s.privacy.mode));
switch_row(ui, "Privacy mode in incognito windows", "", &mut s.privacy.mode_incognito);
limited_row(ui, "Send Do Not Track and Global Privacy Control", "Pages see navigator.globalPrivacyControl", "Servo can't add the request headers yet", |ui| switch(ui, &mut s.privacy.dnt));
switch_row(ui, "Send Do Not Track and Global Privacy Control", "Asks every site not to sell or share your data (DNT and Sec-GPC headers)", &mut s.privacy.dnt);
switch_row(ui, "Remove tracking parameters", "Strips utm_, fbclid, gclid and similar from links before they load", &mut s.privacy.strip_params);
unavailable_row(ui, "Block third-party cookies", "Servo 0.7 has no cookie policy setting");
switch_row(ui, "Block third-party cookies", "Sites inside a page (ads, trackers) can't send or store cookies; always on in privacy mode", &mut s.privacy.block_third_party);
switch_row(ui, "Google sign-in", "Looks like Firefox on accounts.google.com so Google lets you sign in", &mut s.privacy.google_signin);
});
section(ui, "Site data");

View file

@ -15,7 +15,12 @@ certificate for *.nacre.test. Port 8767 speaks plain HTTP only (an HTTPS upgrade
/attachment small file with Content-Disposition: attachment (a download by its headers); /report the same
file at a path that gives no hint
/add, /jsonrpc, /flashgot stubs for AB Download Manager, aria2 and JDownloader 2
/log JSON: every request path, DNS name asked, Range header and download manager call
/setcookie?name=N[&domain=D] sets cookie N=1 (Path=/, Domain=D if given); /cookies shows the Cookie header in
the title; /pixel is a 1x1 GIF; /tp?tag=T is a page with a cross-site iframe and picture
(127.0.0.1:8767) and a same-site picture (img.nacre.test:8766), titled "TP T done" when loaded
/reset empties the "reqs" list of /log
/log JSON: every request path, DNS name asked, Range header and download manager call; "reqs" has
each GET's host, path, Cookie, DNT, Sec-GPC and Save-Data headers (S023)
Runs until killed. Usage: python3 tests/smoke/net/server.py &
"""
import json
@ -30,7 +35,7 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlsplit
BIG = 4 * 1024 * 1024
log = {"paths": [], "dns": [], "ranges": [], "dlm": [], "tls": 0}
log = {"paths": [], "dns": [], "ranges": [], "dlm": [], "tls": 0, "reqs": []}
lock = threading.Lock()
@ -94,6 +99,17 @@ nacre.test,127.0.0.1##.nacre-ad
###nacre-generic-ad
"""
TP_PAGE = """<!doctype html><meta charset=utf-8><title>TP TAG</title>
<p>Third-party test TAG
<iframe id=frame src="http://127.0.0.1:8767/setcookie?name=tpTAG&tag=TAG"></iframe>
<img id=cross src="http://127.0.0.1:8767/pixel?tag=TAG">
<img id=same src="http://img.nacre.test:8766/pixel?tag=TAG">
<script>
let left = 3;
const one = () => { if (--left === 0) document.title = "TP TAG done"; };
for (const e of [frame, cross, same]) { e.onload = one; e.onerror = one; }
</script>"""
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"<!doctype html><title>Reset</title>", "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"<!doctype html><title>Net test {scheme}</title><p>Net test over {scheme}{links}".encode(), "text/html")
if path == "/echo":
return self.reply(f"<!doctype html><title>Echo {url.query}</title><p>{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"<!doctype html><title>Set {name}</title><p>Set {name}".encode(), "text/html", {"Set-Cookie": cookie})
if path == "/cookies":
return self.reply(f"<!doctype html><title>Cookies {self.headers.get('Cookie', '')}</title>".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":

View file

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

View file

@ -1495,6 +1495,8 @@ async fn http_network_or_cache_fetch(
.headers
.typed_insert::<UserAgent>(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, &current_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(
&current_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, &current_url) {
set_request_cookies(
&current_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

View file

@ -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;

94
vendor/servo-net/nacre.rs vendored Normal file
View file

@ -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<Vec<(HeaderName, HeaderValue)>> = RwLock::new(Vec::new());
static BLOCK_THIRD_PARTY: AtomicBool = AtomicBool::new(false);
static TOP_SITES: LazyLock<RwLock<FxHashMap<WebViewId, String>>> = 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::<IpAddr>().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<WebViewId>, 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))
}

View file

@ -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<servo_base::id::WebViewId>,
) -> Result<Option<String>, 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