diff --git a/Plans/08 WebKit engine/S050-net-privacy-downloads.md b/Plans/08 WebKit engine/S050-net-privacy-downloads.md index 8495c2e..d3caae7 100644 --- a/Plans/08 WebKit engine/S050-net-privacy-downloads.md +++ b/Plans/08 WebKit engine/S050-net-privacy-downloads.md @@ -14,13 +14,17 @@ download manager stubs, HTTP cache on disk. - `docs/engine/servo-removal.md` §3.6, §3.7, §3.12 (error pages); D-014; `src/net/bridge.rs` header; `tests/smoke/net-privacy.txt`, `net-downloads.txt` headers. ## Steps -- [ ] Proxy settings to the bridge per session; `NACRE_NO_BRIDGE=1` path; never a real proxy/Tor in tests. -- [ ] `decide-policy`: navigation actions → `actions::on_navigation` (app scope, external schemes, HTTPS-only upgrade, tracking strip); response policy → downloads (`download` for non-displayable MIME / Content-Disposition). -- [ ] `download-started` → Nacre's downloads store/UI or the custom manager hand-off; progress, cancel, destination, finished state. -- [ ] TLS errors → Nacre's certificate warning page; "continue" allows the cert for the host for the run. -- [ ] Error pages from Nacre's look (port `assets/servo/neterror.html`/`badcert.html` style into `nacre://` pages). +- [x] Proxy settings to the bridge per session; `NACRE_NO_BRIDGE=1` path; never a real proxy/Tor in tests. +- [x] `decide-policy`: navigation actions → `actions::on_navigation` (app scope, external schemes, HTTPS-only upgrade, tracking strip); response policy → downloads (`download` for non-displayable MIME / Content-Disposition). +- [x] `download-started` → Nacre's downloads store/UI or the custom manager hand-off; progress, cancel, destination, finished state. +- [x] TLS errors → Nacre's certificate warning page; "continue" allows the cert for the host for the run. +- [x] Error pages from Nacre's look (port `assets/servo/neterror.html`/`badcert.html` style into `nacre://` pages). - [ ] `CookieManager` accept policy (third-party), `set_preferred_languages`, privacy mode Accept-Language, per-view UA quirk. -- [ ] Loopback/127.0.0.1 and localhost bypass the bridge (today a loopback page ends in "Message was restarted too many times" with the URL rewritten to the bridge port; found in S046); regression smoke. +- [x] Loopback/127.0.0.1 and localhost bypass the bridge (today a loopback page ends in "Message was restarted too many times" with the URL rewritten to the bridge port; found in S046); regression smoke. +- [x] `net::policy::decide` wired on WebKit (main frames + images), including the images permission (handed over by S049). +- [ ] `privacy-net.txt` exits 0: `*.nacre.test` through the bridge's DoH, third-party cookies (handed over by S049). +- [x] Remove the stale PROGRESS "Later" line about the niri window rule (fixed by D-045, e434bd2). +- [ ] Navigation policy only for the tab's own (main frame) loads: WebKit's GTK API can't tell iframe navigations apart (`frame_name()` is empty for unnamed iframes), so HTTPS-only, the strip and the UA reload can take over a tab with a frame's URL today. Likely fix: the web process extension tells main-frame loads (found in S050). - [ ] Smoke (start `python3 tests/smoke/net/server.py &` / `cache/server.py &`): `net-privacy.txt`, `net-downloads.txt`, `privacy-net.txt`, `privacy-mode.txt`, `cache.txt` + `cache-restart.txt` green hidden. - [ ] PROGRESS entry, INDEX line, tracker, commit `S050: …`, push. @@ -33,3 +37,21 @@ download manager stubs, HTTP cache on disk. ## Handoff (→ PROGRESS.md) What still differs from the Servo-era behaviour. + +## Resume (S050 WIP, 2026-11-13) +State in commit `S050 (WIP)`. Verified hidden: `net-privacy.txt` and `net-downloads.txt` exit 0 (every assert answered), +`cargo test` 78 + webext 1. `privacy-net.txt`: everything passes except the Google UA quirk assert. +- WebKit reaches the bridge over **SOCKS5** (`Bridge::socks_url`; same port, login in the handshake): libsoup sends plain + http to an HTTP proxy without the password and then GETs the proxy itself (the S046 "restarted too many times" bug). + Loopback skips the proxy (`LOOPBACK` in host.rs). +- Third-party cookies: WebKit's NoThirdParty only stops storing; ITP (`set_itp_enabled`) keeps existing cookies off + cross-site requests. Cookies without SameSite are Lax in WebKit, and None needs Secure (https only), so the cookie + part of privacy-net now runs on https with `cdn.other.test` (server cert + DNS stub extended). +- selftest: `js`/`assert`/`save` now wait for the page's answer (before, a run could quit with asserts unanswered and + still pass; S046–S049 smokes may hide failures, rerun them). +- Open: (1) the main-frame box above; (2) UA quirk: `Engine::set_view_user_agent` swaps in a copied `Settings` with + Firefox's UA, the navigation is reloaded, but the request still carries WebKit's UA (check whether WebKit reads + `user-agent` from a view's new settings; else a per-view `set_settings` before the first load, or the extension + setting User-Agent in `send-request` for accounts.google.com); (3) `privacy-mode.txt`, `cache.txt` + + `cache-restart.txt` not run yet; (4) PROGRESS/INDEX/final commit. +- Not done on purpose: WebKit-only (`blob:`) downloads don't ask where to save and can't pause. diff --git a/assets/servo/badcert.html b/assets/pages/badcert.html similarity index 76% rename from assets/servo/badcert.html rename to assets/pages/badcert.html index 4bd3c5c..8227978 100644 --- a/assets/servo/badcert.html +++ b/assets/pages/badcert.html @@ -26,22 +26,8 @@
!

Connection not secure

This site's certificate can't be trusted, so someone could be reading or changing what you send. It's safest to go back.

-

Details: ${reason}

-
- - +

${url}

+

${reason}

+
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index d6cbd07..18328ff 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -403,7 +403,6 @@ Later: S010 list: user checks the Discord icon with their own client (the Discor ## Later - file:// media outside the XDG user folders doesn't play (WebKit sandbox, D-043). -- Visible runs need the user to add the niri window rule for `dev.nacre.Nacre` (tools/smoke.sh header, D-044). - 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). - Bookmark flyout stays open after switching tabs and shows the old page's bookmark (S006 keys.txt shot). diff --git a/src/actions.rs b/src/actions.rs index cafbffe..242f6bc 100644 --- a/src/actions.rs +++ b/src/actions.rs @@ -1274,6 +1274,24 @@ impl App { request.allow(); return; }; + // The certificate warning: its own load goes through, its "Open anyway" counts only from this tab while it + // shows; any other navigation ends it. + let tab = &mut self.windows.get_mut(&window).expect("found").tabs[index]; + if tab.cert_error.as_ref().is_some_and(|e| e.url == url) { + request.allow(); + return; + } + let cert_error = tab.cert_error.take(); + if url.as_str() == "nacre://allowcert" { + request.deny(); + if let (Some(error), Some(engine)) = (cert_error, &self.engine) { + engine.allow_certificate(&error); + if let Some(view) = tab.webview() { + view.load(&error.url); + } + } + return; + } match url.scheme() { "nacre" => { request.deny(); @@ -1302,8 +1320,40 @@ impl App { if download::looks_like_download(&url) { request.deny(); self.start_download(url, page, None); - } else { - request.allow(); + return; + } + let tab = &mut self.windows.get_mut(&window).expect("found").tabs[index]; + // HTTPS-only: the secure version sent the page back to plain http; ask rather than loop. + if request.redirect && url.scheme() == "http" && self.hub.config.borrow().https_only && tab.upgraded_from.as_ref().is_some_and(|from| from.host_str() == url.host_str()) { + request.deny(); + tab.upgraded_from = None; + tab.prompts.push_back(Prompt::HttpFallback { url }); + self.redraw(window); + return; + } + let outcome = crate::net::policy::decide(&self.hub.config.borrow(), &url); + let Some(view) = tab.webview().cloned() else { return request.allow() }; + match outcome { + crate::net::policy::Outcome::Upgrade(secure) => { + request.deny(); + tab.upgraded_from = Some(url); + view.load(&secure); + }, + crate::net::policy::Outcome::Strip(clean) => { + request.deny(); + view.load(&clean); + }, + crate::net::policy::Outcome::Allow => { + let quirk = self.hub.config.borrow().wants_ua_quirk(&url); + let changed = self.engine.as_ref().is_some_and(|e| e.set_view_user_agent(&view, quirk.then_some(crate::inject::FIREFOX_UA))); + // The request was made with the old user agent: load it again with the new one. + if changed && request.reloadable { + request.deny(); + view.load(&url); + } else { + request.allow(); + } + }, } }, "about" | "data" | "blob" | "file" | "javascript" => request.allow(), @@ -1763,7 +1813,34 @@ impl App { download::start(download::Job { id, url: item.url, path: item.path, headers, control }, self.downloads_tx.clone(), self.wake()); } + /// A download only WebKit can fetch (a page's `blob:` or `data:` file): saved in the downloads folder under the + /// name the page gave it (no "ask where", no pause: WebKit can't resume these). + pub fn on_web_download(&mut self, view: Option, item: crate::engine::WebDownload) { + let page = view.and_then(|v| self.tab_mut(v)).map(|t| t.url.clone()).unwrap_or_default(); + let settings = self.shared.settings.borrow().downloads.clone(); + let name = if item.suggested_name().is_empty() { "download".to_owned() } else { util::safe_file_name(item.suggested_name()) }; + let path = util::unused_path(&settings.dir, &name); + let _ = std::fs::create_dir_all(&settings.dir); + let id = self.shared.downloads.borrow_mut().add(&item.url(), &page, path.clone()); + let wake = self.wake(); + item.save_to(&path, id, self.downloads_tx.clone(), move || wake()); + self.web_downloads.insert(id, item); + if settings.auto_open + && let Some(w) = self.current_window() + && let Some(win) = self.windows.get_mut(&w) + { + win.ui.flyout = Some(crate::ui::Flyout::Downloads); + } + self.redraw_all(); + } + pub fn on_download_msg(&mut self, msg: download::Msg) { + if !matches!(msg, download::Msg::Progress { .. }) { + let id = match &msg { + download::Msg::Progress { id, .. } | download::Msg::Done { id, .. } | download::Msg::Failed { id, .. } | download::Msg::Paused { id, .. } | download::Msg::Cancelled { id } => *id, + }; + self.web_downloads.remove(&id); + } let mut downloads = self.shared.downloads.borrow_mut(); match msg { download::Msg::Progress { id, received, total, speed } => { @@ -1831,6 +1908,7 @@ impl App { self.begin_transfer(id); } }, + DownloadOp::Cancel(id) if self.web_downloads.contains_key(&id) => self.web_downloads[&id].cancel(), DownloadOp::Cancel(id) => match self.download_controls.get(&id) { Some(c) => c.store(download::CANCEL, Ordering::Relaxed), None => { @@ -1847,6 +1925,9 @@ impl App { if let Some(c) = self.download_controls.remove(&id) { c.store(download::CANCEL, Ordering::Relaxed); } + if let Some(d) = self.web_downloads.remove(&id) { + d.cancel(); + } self.shared.downloads.borrow_mut().remove(id); }, DownloadOp::Open(id) => { diff --git a/src/adblock.rs b/src/adblock.rs index 5a55b89..0c6a8d6 100644 --- a/src/adblock.rs +++ b/src/adblock.rs @@ -440,7 +440,7 @@ fn looks_like_hosts(text: &str) -> bool { } /// FNV-1a; only used to notice that the lists changed. -fn simple_hash(data: &[u8]) -> u64 { +pub(crate) fn simple_hash(data: &[u8]) -> u64 { let mut hash = 0xcbf2_9ce4_8422_2325u64; for b in data { hash ^= *b as u64; diff --git a/src/app.rs b/src/app.rs index b6e4d6a..7dbe883 100644 --- a/src/app.rs +++ b/src/app.rs @@ -217,6 +217,8 @@ pub struct App { /// Page notifications shown this run (self-test status). pub notifications_shown: u32, pub download_controls: HashMap>, + /// Downloads WebKit makes itself (`blob:`, `data:`), by downloads list id. + pub web_downloads: HashMap, pub presence: Option, pub presence_started: Option<(u64, String, i64)>, pub applied: Settings, @@ -340,6 +342,7 @@ impl App { next_pending: 1, notifications_shown: 0, download_controls: HashMap::new(), + web_downloads: HashMap::new(), presence: None, presence_started: None, applied: settings, @@ -388,7 +391,7 @@ impl App { let paths = &self.shared.paths; let setup = crate::engine::host::Setup { dirs: (!self.shared.incognito).then(|| (paths.webkit_data(), paths.webkit_cache())), - proxy: self.shared.bridge.as_ref().map(|b| b.proxy_url()), + proxy: self.shared.bridge.as_ref().map(|b| b.socks_url()), user_agent: settings.web.user_agent.clone(), dark_background: dark, developer_extras: true, @@ -419,12 +422,21 @@ 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()); - // Third-party cookies move to WebKit in S050; the language list is the engine's own setting; headers, - // tracking parameters on sub-resources and ad blocker stand-ins are the web process extension's (D-036). + // Headers, tracking parameters on sub-resources and ad blocker stand-ins are the web process extension's + // (D-036); third-party cookies, languages and the Images permission are WebKit's own settings. if let Some(engine) = &self.engine { - engine.set_languages(&crate::net::privacy::languages(&crate::net::privacy::locale())); + let privacy = self.privacy_mode_on(&settings); + engine.set_block_third_party_cookies(settings.privacy.block_third_party || privacy); + let languages = crate::net::privacy::languages(&crate::net::privacy::locale()); + engine.set_languages(&languages); + engine.set_images_filter(crate::net::policy::images_filter(&self.hub.config.borrow())); + let mut headers: Vec<(String, String)> = crate::net::privacy::privacy_headers(&settings).into_iter().map(|(k, v)| (k.to_owned(), v.to_owned())).collect(); + // Privacy mode: Accept-Language as Firefox sends it (WebKit weighs the same list its own way). + if privacy { + headers.push(("Accept-Language".to_owned(), crate::net::privacy::accept_language(&languages))); + } let config = crate::net::rules::Config { - headers: crate::net::privacy::privacy_headers(&settings).into_iter().map(|(k, v)| (k.to_owned(), v.to_owned())).collect(), + headers, strip: settings.privacy.strip_params, adblock: settings.adblock.enabled, paused: settings.adblock.allow.clone(), @@ -717,9 +729,19 @@ impl App { } }, Event::Navigation(id, request) => self.on_navigation(id, request), - Event::Download(id, url) => { + Event::Download(id, url, name) => { let page = self.tab_mut(id).map(|t| t.url.clone()).unwrap_or_default(); - self.start_download(url, page, None); + self.start_download(url, page, name); + }, + Event::WebDownload(id, download) => self.on_web_download(id, download), + Event::CertError(id, error) => { + let Some((w, i)) = self.find_webview(id) else { return }; + let tab = &mut self.windows.get_mut(&w).expect("found").tabs[i]; + if let Some(view) = tab.webview() { + view.show_html(&crate::resources::bad_cert_page(&error.url, &error.why), &error.url); + } + tab.cert_error = Some(error); + self.redraw(w); }, Event::LoadFailed(id, url, why) => { let Some((w, i)) = self.find_webview(id) else { return }; diff --git a/src/engine/host.rs b/src/engine/host.rs index 2cb1a7e..8123dde 100644 --- a/src/engine/host.rs +++ b/src/engine/host.rs @@ -10,14 +10,14 @@ use gtk::prelude::*; use url::Url; use webkit::prelude::*; -use super::{AuthRequest, ColorPicker, Control, Event, FilePicker, Hub, LoadState, NavigationRequest, Notification, PageAction, PageMenuRequest, PermissionAsk, SelectElement, SimpleDialog, UserStyle, View, ViewId}; +use super::{AuthRequest, CertError, ColorPicker, Control, Event, FilePicker, Hub, LoadState, NavigationRequest, Notification, PageAction, PageMenuRequest, PermissionAsk, SelectElement, SimpleDialog, UserStyle, View, ViewId, WebDownload}; use crate::store::permissions::Kind as Perm; /// Settings the engine starts with. pub struct Setup { /// Persistent data and cache folders; `None` = ephemeral (incognito). pub dirs: Option<(std::path::PathBuf, std::path::PathBuf)>, - /// Nacre's network bridge (`http://127.0.0.1:port`), if it runs. + /// Nacre's network bridge (`socks5://user:token@127.0.0.1:port`), if it runs. pub proxy: Option, /// User agent override; empty = WebKit's own. pub user_agent: String, @@ -51,8 +51,13 @@ pub struct Engine { filter_generation: Rc>, /// The web process extension's config JSON (`net::rules::Config`), also given to new web processes. webext_config: Rc>, + /// The Images permission's filter (pictures blocked per site), on every view whatever the ad blocker does. + images_filter: Rc>>, } +/// Hosts that never go through the bridge. +const LOOPBACK: &[&str] = &["localhost", "*.localhost", "127.0.0.0/8", "::1"]; + /// The folder WebKit loads Nacre's web process extension from: `NACRE_WEBEXT_DIR`, the package's `lib/nacre` /// beside `bin/`, or the build folder (cargo puts `libnacre_webext.so` next to the program). fn webext_dir() -> Option { @@ -63,10 +68,13 @@ fn webext_dir() -> Option { [exe_dir.join("../lib/nacre"), exe_dir].into_iter().find(|d| d.join("libnacre_webext.so").is_file()) } -/// Attach or detach the ad blocker filter for a view about to show a page of `host`. -fn attach_filters(web: &webkit::WebView, hub: &Hub, filters: &RefCell>, host: &str) { +/// Attach or detach the ad blocker filter for a view about to show a page of `host`; the Images filter always. +fn attach_filters(web: &webkit::WebView, hub: &Hub, filters: &RefCell>, images: &RefCell>, host: &str) { let Some(ucm) = web.user_content_manager() else { return }; ucm.remove_all_filters(); + if let Some(filter) = images.borrow().as_ref() { + ucm.add_filter(filter); + } let config = hub.config.borrow(); let paused = !config.adblock_enabled || config.adblock_allow.iter().any(|h| crate::util::host_matches(host, h)); if !paused { @@ -106,8 +114,10 @@ impl Engine { if let Some(manager) = session.website_data_manager() { manager.set_favicons_enabled(true); } + // Everything goes through Nacre's bridge except this machine's own addresses (the bridge would only send + // them straight back). SOCKS5: its login is part of the handshake, so plain http works too (S050). if let Some(proxy) = &setup.proxy { - let settings = webkit::NetworkProxySettings::new(Some(proxy), &[]); + let settings = webkit::NetworkProxySettings::new(Some(proxy), LOOPBACK); session.set_proxy_settings(webkit::NetworkProxyMode::Custom, Some(&settings)); } let context = match &pressure { @@ -174,7 +184,7 @@ impl Engine { let (allowed, blocked) = { let a = answers.borrow(); (origins(&a.0), origins(&a.1)) }; context.initialize_notification_permissions(&allowed.iter().collect::>(), &blocked.iter().collect::>()); }); - Rc::new(Engine { + let engine = Rc::new(Engine { hub, session, context, @@ -189,7 +199,79 @@ impl Engine { filters: Rc::default(), filter_generation: Rc::default(), webext_config, - }) + images_filter: Rc::default(), + }); + engine.watch_downloads(); + engine + } + + /// Downloads WebKit starts itself (``, a page's `blob:` file): web addresses go to Nacre's own + /// downloader like every other download (pause, resume, download managers); the rest only WebKit can fetch, so + /// it saves them where the app says. + fn watch_downloads(self: &Rc) { + let engine = Rc::downgrade(self); + self.session.connect_download_started(move |_, download| { + let Some(engine) = engine.upgrade() else { return }; + let view = download.web_view().and_then(|w| engine.view_id(&w)); + let url = download.request().and_then(|r| r.uri()).and_then(|u| Url::parse(&u).ok()); + if let (Some(url), Some(view)) = (&url, view) + && matches!(url.scheme(), "http" | "https") + { + download.cancel(); + engine.hub.push(Event::Download(view, url.clone(), None)); + return; + } + let hub = engine.hub.clone(); + download.connect_decide_destination(move |d, suggested| { + hub.push(Event::WebDownload(view, WebDownload::new(d.clone(), suggested.to_owned()))); + true + }); + }); + } + + fn view_id(&self, web: &webkit::WebView) -> Option { + self.views.borrow().iter().find(|(_, w)| w.upgrade().as_ref() == Some(web)).map(|(id, _)| *id) + } + + /// Third-party cookies: refused (`block`), or accepted like first-party ones. WebKit's no-third-party policy only + /// stops frames and pictures from storing cookies (and frames from reading them); its tracking prevention (ITP) + /// is what keeps their existing cookies off cross-site requests. + pub fn set_block_third_party_cookies(&self, block: bool) { + if let Some(cookies) = self.session.cookie_manager() { + cookies.set_accept_policy(if block { webkit::CookieAcceptPolicy::NoThirdParty } else { webkit::CookieAcceptPolicy::Always }); + } + if self.session.is_itp_enabled() != block { + self.session.set_itp_enabled(block); + } + } + + /// "Open anyway": trust this certificate for its host until Nacre quits. + pub fn allow_certificate(&self, error: &CertError) { + self.session.allow_tls_certificate_for_host(&error.certificate, &error.host); + } + + /// The Images permission as one more content filter: pictures blocked on the listed sites (or everywhere but + /// the listed ones); `None` = no site blocks them. Compiled once per rule set, like the ad blocker's. + pub fn set_images_filter(self: &Rc, json: Option) { + let Some(json) = json else { + *self.images_filter.borrow_mut() = None; + return self.refresh_filters(); + }; + let id = format!("nacre-images-{:016x}", crate::adblock::simple_hash(json.as_bytes())); + if self.images_filter.borrow().as_ref().is_some_and(|f| f.identifier().as_deref() == Some(id.as_str())) { + return; + } + let weak = Rc::downgrade(self); + self.filter_store.save(&id, &glib::Bytes::from_owned(json.into_bytes()), None::<>k::gio::Cancellable>, move |result| { + let Some(engine) = weak.upgrade() else { return }; + match result { + Ok(filter) => { + *engine.images_filter.borrow_mut() = Some(filter); + engine.refresh_filters(); + }, + Err(e) => eprintln!("images: WebKit couldn't compile the filter: {e}"), + } + }); } /// Use the ad blocker's content filters (D-036): each loaded from WebKit's store when it was compiled before, @@ -245,7 +327,7 @@ impl Engine { pub fn refresh_filters(&self) { for web in self.live_views() { let host = web.uri().and_then(|u| Url::parse(&u).ok()).and_then(|u| u.host_str().map(str::to_owned)).unwrap_or_default(); - attach_filters(&web, &self.hub, &self.filters, &host); + attach_filters(&web, &self.hub, &self.filters, &self.images_filter, &host); } } @@ -280,6 +362,36 @@ impl Engine { self.context.set_preferred_languages(&refs); } + /// A user agent for one view only (`None`: back to the shared settings). Google's sign-in refuses browsers it + /// doesn't know, so its pages get Firefox's (`HubConfig::wants_ua_quirk`). Whether the view's agent changed: a + /// navigation already on its way still carries the old one. + pub fn set_view_user_agent(&self, view: &View, ua: Option<&str>) -> bool { + let current = webkit::prelude::WebViewExt::settings(&view.web); + let own = current.as_ref() != Some(&self.settings); + match ua { + None if own => view.web.set_settings(&self.settings), + None => return false, + Some(ua) => { + if own && let Some(settings) = ¤t { + let changed = settings.user_agent().as_deref() != Some(ua); + settings.set_user_agent(Some(ua)); + return changed; + } + // A copy of the shared settings with only the user agent changed. + let copy = webkit::Settings::new(); + for spec in self.settings.list_properties().iter() { + let flags = spec.flags(); + if flags.contains(glib::ParamFlags::READWRITE) && !flags.intersects(glib::ParamFlags::CONSTRUCT_ONLY) { + copy.set_property_from_value(spec.name(), &self.settings.property_value(spec.name())); + } + } + copy.set_user_agent(Some(ua)); + view.web.set_settings(©); + }, + } + true + } + /// The colour a page shows before it paints (no white flash in dark mode). pub fn set_dark_background(&self, dark: bool) { let shade = if dark { 0.1 } else { 1.0 }; @@ -367,7 +479,7 @@ impl Engine { }; let web = builder.build(); web.set_background_color(&self.background.borrow()); - attach_filters(&web, &self.hub, &self.filters, ""); + attach_filters(&web, &self.hub, &self.filters, &self.images_filter, ""); self.views.borrow_mut().insert(id, web.downgrade()); let view = View::new(id, web); self.wire(&view); @@ -463,7 +575,14 @@ impl Engine { true }); let hub = self.hub.clone(); + web.connect_load_failed_with_tls_errors(move |_, uri, certificate, errors| { + let Ok(url) = Url::parse(uri) else { return false }; + hub.push(Event::CertError(id, CertError::new(url, certificate.clone(), errors))); + true + }); + let hub = self.hub.clone(); let filters = self.filters.clone(); + let images = self.images_filter.clone(); web.connect_decide_policy(move |web, decision, kind| match kind { webkit::PolicyDecisionType::NavigationAction => { let Some(nav) = decision.downcast_ref::() else { return false }; @@ -474,19 +593,31 @@ impl Engine { } let Some(url) = action.request().and_then(|r| r.uri()).and_then(|u| Url::parse(&u).ok()) else { return false }; // The filter is set for the page's site before it loads (paused sites go without). - attach_filters(web, &hub, &filters, url.host_str().unwrap_or("")); - hub.push(Event::Navigation(id, NavigationRequest::new(url, decision.clone()))); + attach_filters(web, &hub, &filters, &images, url.host_str().unwrap_or("")); + let get = action.request().and_then(|r| r.http_method()).is_none_or(|m| m.eq_ignore_ascii_case("GET")); + let reloadable = get && action.navigation_type() != webkit::NavigationType::BackForward; + hub.push(Event::Navigation(id, NavigationRequest::new(url, action.is_redirect(), reloadable, decision.clone()))); true }, webkit::PolicyDecisionType::Response => { let Some(response) = decision.downcast_ref::() else { return false }; - if response.is_mime_type_supported() || !response.is_main_frame_main_resource() { + if !response.is_main_frame_main_resource() { return false; } - // Nacre's own download manager takes it. + let reply = response.response(); + let attachment = reply.as_ref().and_then(|r| r.http_headers()).and_then(|h| h.one("Content-Disposition")).is_some_and(|v| v.trim_start().to_ascii_lowercase().starts_with("attachment")); + if response.is_mime_type_supported() && !attachment { + return false; + } + // Nacre's own downloader takes it (http and https; the rest WebKit saves itself). let Some(url) = response.request().and_then(|r| r.uri()).and_then(|u| Url::parse(&u).ok()) else { return false }; + if !matches!(url.scheme(), "http" | "https") { + decision.download(); + return true; + } decision.ignore(); - hub.push(Event::Download(id, url)); + let name = reply.and_then(|r| r.suggested_filename()).map(|n| n.to_string()).filter(|n| !n.is_empty()); + hub.push(Event::Download(id, url, name)); true }, _ => false, diff --git a/src/engine/mod.rs b/src/engine/mod.rs index fec9ff9..5a199e3 100644 --- a/src/engine/mod.rs +++ b/src/engine/mod.rs @@ -66,8 +66,13 @@ pub enum Event { Fullscreen(ViewId, bool), /// A main-frame navigation waits for `NavigationRequest::allow`/`deny`. Navigation(ViewId, NavigationRequest), - /// A response WebKit can't show: Nacre downloads it itself. - Download(ViewId, Url), + /// A response WebKit can't show, or one the server marked as an attachment: Nacre downloads it itself. The + /// file name the server suggested, if any. + Download(ViewId, Url, Option), + /// A download only WebKit can make (`blob:`, `data:`): it waits for `WebDownload::save_to`. + WebDownload(Option, WebDownload), + /// The page's certificate can't be trusted: Nacre shows its warning. + CertError(ViewId, CertError), /// A load failed (not a cancel): url, error text. LoadFailed(ViewId, String, String), /// A pop-up (`window.open`, target=_blank): its view, already made as a related view of the opener, and the @@ -152,12 +157,16 @@ impl Hub { /// A navigation waiting for the browser's answer (WebKit keeps the load on hold until then). pub struct NavigationRequest { pub url: Url, + /// The server sent the page here (an HTTP redirect), rather than a link or the address bar. + pub redirect: bool, + /// A plain GET that isn't a back/forward step: denying it and loading the URL again gives the same page. + pub reloadable: bool, decision: webkit::PolicyDecision, } impl NavigationRequest { - pub(crate) fn new(url: Url, decision: webkit::PolicyDecision) -> Self { - NavigationRequest { url, decision } + pub(crate) fn new(url: Url, redirect: bool, reloadable: bool, decision: webkit::PolicyDecision) -> Self { + NavigationRequest { url, redirect, reloadable, decision } } pub fn allow(self) { self.decision.use_(); @@ -167,6 +176,78 @@ impl NavigationRequest { } } +/// A page whose certificate failed the checks (self-signed, expired, wrong name, …). +pub struct CertError { + pub url: Url, + pub host: String, + /// What is wrong, in words. + pub why: String, + certificate: gtk::gio::TlsCertificate, +} + +impl CertError { + pub(crate) fn new(url: Url, certificate: gtk::gio::TlsCertificate, errors: gtk::gio::TlsCertificateFlags) -> Self { + use gtk::gio::TlsCertificateFlags as F; + let reasons = [ + (F::UNKNOWN_CA, "it isn't signed by an authority this computer trusts"), + (F::BAD_IDENTITY, "it belongs to another site"), + (F::NOT_ACTIVATED, "it isn't valid yet"), + (F::EXPIRED, "it has expired"), + (F::REVOKED, "it was revoked"), + (F::INSECURE, "it uses weak encryption"), + ]; + let found: Vec<&str> = reasons.iter().filter(|(flag, _)| errors.contains(*flag)).map(|(_, why)| *why).collect(); + let why = if found.is_empty() { "The certificate couldn't be checked.".to_owned() } else { format!("The certificate can't be trusted: {}.", found.join(", ")) }; + CertError { host: url.host_str().unwrap_or("").to_owned(), url, why, certificate } + } +} + +/// A download WebKit makes itself, reported back as `net::download::Msg`s with the downloads list's id. +pub struct WebDownload(webkit::Download, String); + +impl WebDownload { + pub(crate) fn new(download: webkit::Download, suggested: String) -> Self { + WebDownload(download, suggested) + } + pub fn url(&self) -> String { + self.0.request().and_then(|r| r.uri()).map(|u| u.to_string()).unwrap_or_default() + } + /// The name the page or server gave the file. + pub fn suggested_name(&self) -> &str { + &self.1 + } + /// Save it at `path` and report progress, the end or a failure to `tx`. + pub fn save_to(&self, path: &std::path::Path, id: u64, tx: std::sync::mpsc::Sender, wake: impl Fn() + Clone + 'static) { + use crate::net::download::Msg; + let d = &self.0; + let (t, w) = (tx.clone(), wake.clone()); + d.connect_received_data(move |d, _| { + let total = d.response().map(|r| r.content_length()).unwrap_or(0); + let _ = t.send(Msg::Progress { id, received: d.received_data_length(), total, speed: 0 }); + w(); + }); + let (t, w) = (tx.clone(), wake.clone()); + let done = path.to_owned(); + d.connect_finished(move |_| { + // `failed` comes first for a failed or cancelled download; then this one, which must not undo it. + if done.exists() { + let _ = t.send(Msg::Done { id, path: done.clone() }); + w(); + } + }); + d.connect_failed(move |_, error| { + let msg = if error.matches(webkit::DownloadError::CancelledByUser) { Msg::Cancelled { id } } else { Msg::Failed { id, error: error.message().to_owned() } }; + let _ = tx.send(msg); + wake(); + }); + d.set_allow_overwrite(false); + d.set_destination(&path.to_string_lossy()); + } + pub fn cancel(&self) { + self.0.cancel(); + } +} + /// A permission a page asked for. pub struct PermissionAsk(webkit::PermissionRequest); diff --git a/src/engine/view.rs b/src/engine/view.rs index d09595d..e2e3900 100644 --- a/src/engine/view.rs +++ b/src/engine/view.rs @@ -40,6 +40,11 @@ impl View { self.web.load_uri(url.as_str()); } + /// Show Nacre's own page (`html`) in place of `url`, which failed (the address bar and history keep `url`). + pub fn show_html(&self, html: &str, url: &Url) { + self.web.load_alternate_html(html, url.as_str(), None); + } + pub fn url(&self) -> Option { self.web.uri().and_then(|u| Url::parse(&u).ok()) } diff --git a/src/inject.rs b/src/inject.rs index c19c60c..9a7e9ff 100644 --- a/src/inject.rs +++ b/src/inject.rs @@ -117,10 +117,11 @@ const BRIDGE_JS: &str = r#"if (window.__nacre) return; // Private to Nacre's scripts: pages run later and can't reach it, or swap what it uses. const __send = (t, d) => { try { log(TOKEN + stringify({ t, d: d === undefined ? null : d })); } catch (e) {} }; Object.defineProperty(window, '__nacre', { value: {}, writable: false, configurable: false, enumerable: false }); - // and links the user asked to save go to Nacre's own download manager. + // web links go to Nacre's own download manager with the page's name; a page's blob:/data: file only + // WebKit can read, so it downloads those itself. document.addEventListener('click', e => { const a = e.target && e.target.closest && e.target.closest('a[download]'); - if (!a || !a.href || e.defaultPrevented) return; + if (!a || !/^https?:/.test(a.href) || e.defaultPrevented) return; e.preventDefault(); __send('download', { url: a.href, name: a.getAttribute('download') || '' }); }, true); diff --git a/src/net/bridge.rs b/src/net/bridge.rs index 7531830..9c1d581 100644 --- a/src/net/bridge.rs +++ b/src/net/bridge.rs @@ -9,7 +9,9 @@ //! - otherwise direct, with names looked up through secure DNS when that is on. //! Switching any of this takes effect for new connections immediately. //! -//! Only Nacre may use it: requests must carry `Proxy-Authorization` with the per-run token. +//! Only Nacre may use it: requests must carry `Proxy-Authorization` with the per-run token. The same port also +//! speaks SOCKS5 with that user name and token: WebKit uses it (libsoup sends plain http requests to an HTTP proxy +//! without the password and never retries them right; a SOCKS5 login is part of the handshake). use std::io::{self, BufRead, BufReader, Read, Write}; use std::net::{IpAddr, Shutdown, SocketAddr, TcpListener, TcpStream, ToSocketAddrs}; @@ -117,11 +119,16 @@ impl Bridge { Ok(bridge) } - /// Proxy URL with credentials, for Servo's prefs and ureq. + /// Proxy URL with credentials, for Nacre's own requests (ureq). pub fn proxy_url(&self) -> String { format!("http://{}:{}@127.0.0.1:{}", self.user, self.token, self.port) } + /// The same as a SOCKS5 URL, for WebKit (names go to the bridge unresolved). + pub fn socks_url(&self) -> String { + format!("socks5://{}:{}@127.0.0.1:{}", self.user, self.token, self.port) + } + pub fn set_route(&self, route: Route) { if let Ok(mut current) = self.route.write() { if current.doh != route.doh { @@ -137,6 +144,10 @@ impl Bridge { fn handle(&self, client: TcpStream) -> io::Result<()> { client.set_read_timeout(Some(Duration::from_secs(30)))?; + let mut first = [0u8; 1]; + if client.peek(&mut first)? == 1 && first[0] == 5 { + return self.handle_socks(client); + } let mut reader = BufReader::new(client.try_clone()?); let mut head = Vec::new(); // Read the request head. @@ -236,6 +247,67 @@ impl Bridge { Ok(()) } + /// SOCKS5 (RFC 1928, 1929): user name and password only, CONNECT only. + fn handle_socks(&self, client: TcpStream) -> io::Result<()> { + let mut c = &client; + let mut head = [0u8; 2]; + c.read_exact(&mut head)?; + let mut methods = vec![0u8; head[1] as usize]; + c.read_exact(&mut methods)?; + if !methods.contains(&2) { + return c.write_all(&[5, 0xff]); + } + c.write_all(&[5, 2])?; + let field = |c: &mut &TcpStream| -> io::Result> { + let mut len = [0u8; 1]; + c.read_exact(&mut len)?; + let mut value = vec![0u8; len[0] as usize]; + c.read_exact(&mut value)?; + Ok(value) + }; + let mut version = [0u8; 1]; + c.read_exact(&mut version)?; + let (user, password) = (field(&mut c)?, field(&mut c)?); + if user != self.user.as_bytes() || password != self.token.as_bytes() { + return c.write_all(&[1, 1]); + } + c.write_all(&[1, 0])?; + let mut request = [0u8; 4]; + c.read_exact(&mut request)?; + let host = match request[3] { + 1 => { + let mut ip = [0u8; 4]; + c.read_exact(&mut ip)?; + IpAddr::from(ip).to_string() + }, + 4 => { + let mut ip = [0u8; 16]; + c.read_exact(&mut ip)?; + IpAddr::from(ip).to_string() + }, + 3 => String::from_utf8_lossy(&field(&mut c)?).into_owned(), + _ => return c.write_all(&[5, 8, 0, 1, 0, 0, 0, 0, 0, 0]), + }; + let mut port = [0u8; 2]; + c.read_exact(&mut port)?; + let port = u16::from_be_bytes(port); + if request[1] != 1 { + return c.write_all(&[5, 7, 0, 1, 0, 0, 0, 0, 0, 0]); + } + client.set_read_timeout(None)?; + let upstream = match self.connect(&host, port) { + Ok(stream) => stream, + Err(error) => { + log::debug!("bridge: {host}:{port}: {error}"); + let code = if error.kind() == io::ErrorKind::ConnectionRefused { 5 } else { 4 }; + return c.write_all(&[5, code, 0, 1, 0, 0, 0, 0, 0, 0]); + }, + }; + c.write_all(&[5, 0, 0, 1, 0, 0, 0, 0, 0, 0])?; + pump(client, upstream, &self.bytes); + Ok(()) + } + /// Open a connection to `host:port` the way the current route says. pub fn connect(&self, host: &str, port: u16) -> io::Result { let route = self.route(); @@ -492,4 +564,30 @@ mod tests { }); assert!(counted, "bytes counted: {}", bridge.bytes.load(Ordering::Relaxed)); } + + /// WebKit's way in: SOCKS5 with the token as password, on the same port. + #[test] + fn socks5_on_loopback() { + let origin = TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let origin_port = origin.local_addr().unwrap().port(); + thread::spawn(move || { + let (mut s, _) = origin.accept().unwrap(); + let mut buf = [0u8; 5]; + s.read_exact(&mut buf).unwrap(); + s.write_all(b"pong!").unwrap(); + let _ = s.read(&mut buf); + }); + let bridge = Bridge::start().unwrap(); + let proxy = format!("127.0.0.1:{}", bridge.port); + let wrong = ("nacre".to_owned(), "nope".to_owned()); + assert_eq!(socks5_connect(&proxy, Some(&wrong), "localhost", origin_port).unwrap_err().kind(), io::ErrorKind::PermissionDenied); + assert!(socks5_connect(&proxy, None, "localhost", origin_port).is_err()); + let right = ("nacre".to_owned(), bridge.token.clone()); + let mut s = socks5_connect(&proxy, Some(&right), "localhost", origin_port).unwrap(); + s.write_all(b"ping!").unwrap(); + let mut reply = [0u8; 5]; + s.read_exact(&mut reply).unwrap(); + assert_eq!(&reply, b"pong!"); + assert!(bridge.socks_url().starts_with("socks5://nacre:")); + } } diff --git a/src/net/policy.rs b/src/net/policy.rs index 5226f54..7420a6b 100644 --- a/src/net/policy.rs +++ b/src/net/policy.rs @@ -1,6 +1,6 @@ -//! The decision for one request the engine is about to make: HTTPS-only upgrade and tracking-parameter strip for -//! pages, the Images permission for sub-resources. Pure: the engine glue applies the outcome. The ad blocker runs -//! inside WebKit (content filters and the web process extension, D-036), not here. +//! The browser's decisions about loads: HTTPS-only upgrade and tracking-parameter strip for pages, and the Images +//! permission as a WebKit content filter. Pure: the engine glue applies them. The ad blocker runs inside WebKit +//! (content filters and the web process extension, D-036), not here. use url::Url; @@ -27,7 +27,8 @@ pub struct HubConfig { } impl HubConfig { - /// Whether pictures are blocked on pages of this host. + /// Whether pictures are blocked on pages of this host (what `images_filter` makes WebKit do). + #[cfg(test)] pub fn images_blocked(&self, host: &str) -> bool { self.images_sites.iter().find(|(h, _)| h == host).map(|(_, block)| *block).unwrap_or(self.images_block_default) } @@ -53,70 +54,74 @@ impl HubConfig { } } -/// One request as the engine reports it. -pub struct Request<'a> { - pub url: &'a Url, - /// Lowercased resource kind ("document", "image", "script", …), as the ad blocker names them. - pub kind: &'a str, - pub main_frame: bool, - /// The page that makes the request ("" when unknown). - pub page_url: &'a str, -} - -/// What to do with a request. +/// What to do with a page the tab is about to open. #[derive(Debug, PartialEq)] pub enum Outcome { - /// Let it through. + /// Open it. Allow, - /// A new page starts loading: let it through and count its blocked requests from zero. - NewPage, /// HTTPS-only: open this https URL instead (the original was plain http). Upgrade(Url), /// Open this URL instead (tracking parameters removed). Strip(Url), - /// Cancel it (Images permission; not counted by the shield). - Block, } -pub fn decide(config: &HubConfig, req: &Request) -> Outcome { - let url = req.url; - if req.main_frame && matches!(url.scheme(), "http" | "https") { - // HTTPS-only: upgrade plain http documents (not local addresses, not exceptions). - if config.https_only && url.scheme() == "http" { - let host = url.host_str().unwrap_or(""); - let excepted = crate::net::bridge::is_local_host(host) || config.https_exceptions.iter().chain(&config.http_allowed).any(|h| util::host_matches(host, h)); - let mut secure = url.clone(); - if !excepted && secure.set_scheme("https").is_ok() { - if secure.port() == Some(80) { - let _ = secure.set_port(None); - } - return Outcome::Upgrade(secure); - } - } - if config.strip_params - && let Some(clean) = strip_tracking(url) - { - return Outcome::Strip(clean); - } - return Outcome::NewPage; +/// HTTPS-only upgrade and tracking-parameter strip for a page (main frame) navigation. +pub fn decide(config: &HubConfig, url: &Url) -> Outcome { + if !matches!(url.scheme(), "http" | "https") { + return Outcome::Allow; } - - // Sub-resources: the Images permission. - let page_host = util::host_of_str(req.page_url); - if req.kind == "image" && matches!(url.scheme(), "http" | "https") && !page_host.is_empty() && config.images_blocked(&page_host) { - return Outcome::Block; + // HTTPS-only: upgrade plain http documents (not local addresses, not exceptions). + if config.https_only && url.scheme() == "http" { + let host = url.host_str().unwrap_or(""); + let excepted = crate::net::bridge::is_local_host(host) || config.https_exceptions.iter().chain(&config.http_allowed).any(|h| util::host_matches(host, h)); + let mut secure = url.clone(); + if !excepted && secure.set_scheme("https").is_ok() { + if secure.port() == Some(80) { + let _ = secure.set_port(None); + } + return Outcome::Upgrade(secure); + } + } + if config.strip_params + && let Some(clean) = strip_tracking(url) + { + return Outcome::Strip(clean); } Outcome::Allow } +/// The Images permission as a WebKit content filter (JSON): pictures from the web blocked on the pages of the sites +/// that block them, or everywhere except the sites that allow them. `None` when no site blocks pictures. +pub fn images_filter(config: &HubConfig) -> Option { + let sites = |block: bool| -> Vec<&str> { config.images_sites.iter().filter(|(_, b)| *b == block).map(|(h, _)| h.as_str()).filter(|h| !h.is_empty()).collect() }; + let trigger = |domains: Option<(&str, Vec<&str>)>| { + let mut t = serde_json::json!({ "url-filter": "^https?://", "resource-type": ["image"] }); + if let Some((key, hosts)) = domains { + t[key] = serde_json::json!(hosts); + } + t + }; + let rules = if config.images_block_default { + let allowed = sites(false); + let mut rules = vec![serde_json::json!({ "trigger": trigger(None), "action": { "type": "block" } })]; + if !allowed.is_empty() { + rules.push(serde_json::json!({ "trigger": trigger(Some(("if-domain", allowed))), "action": { "type": "ignore-previous-rules" } })); + } + rules + } else { + let blocked = sites(true); + if blocked.is_empty() { + return None; + } + vec![serde_json::json!({ "trigger": trigger(Some(("if-domain", blocked))), "action": { "type": "block" } })] + }; + Some(serde_json::Value::Array(rules).to_string()) +} + #[cfg(test)] mod tests { use super::*; - fn req<'a>(url: &'a Url, kind: &'a str, main_frame: bool, page_url: &'a str) -> Request<'a> { - Request { url, kind, main_frame, page_url } - } - #[test] fn images_follow_the_site_answer_then_the_default() { let mut settings = Settings::default(); @@ -135,26 +140,34 @@ mod tests { fn pages_are_upgraded_then_stripped() { let mut config = HubConfig { https_only: true, strip_params: true, https_exceptions: vec!["old.example".into()], ..Default::default() }; let u = Url::parse("http://a.example:80/p?utm_source=x").unwrap(); - assert_eq!(decide(&config, &req(&u, "document", true, "")), Outcome::Upgrade(Url::parse("https://a.example/p?utm_source=x").unwrap())); + assert_eq!(decide(&config, &u), Outcome::Upgrade(Url::parse("https://a.example/p?utm_source=x").unwrap())); let u = Url::parse("https://a.example/p?utm_source=x").unwrap(); - assert_eq!(decide(&config, &req(&u, "document", true, "")), Outcome::Strip(Url::parse("https://a.example/p").unwrap())); + assert_eq!(decide(&config, &u), Outcome::Strip(Url::parse("https://a.example/p").unwrap())); let u = Url::parse("http://old.example/").unwrap(); - assert_eq!(decide(&config, &req(&u, "document", true, "")), Outcome::NewPage); + assert_eq!(decide(&config, &u), Outcome::Allow); let u = Url::parse("http://127.0.0.1:8000/").unwrap(); - assert_eq!(decide(&config, &req(&u, "document", true, "")), Outcome::NewPage); + assert_eq!(decide(&config, &u), Outcome::Allow); config.http_allowed.push("a.example".into()); let u = Url::parse("http://a.example/").unwrap(); - assert_eq!(decide(&config, &req(&u, "document", true, "")), Outcome::NewPage); + assert_eq!(decide(&config, &u), Outcome::Allow); + assert_eq!(decide(&config, &Url::parse("about:blank").unwrap()), Outcome::Allow); } #[test] - fn blocked_images_follow_the_site() { - let config = HubConfig { images_sites: vec![("a.example".into(), true)], adblock_enabled: true, adblock_allow: vec!["b.example".into()], ..Default::default() }; - let img = Url::parse("https://cdn.example/x.png").unwrap(); - assert_eq!(decide(&config, &req(&img, "image", false, "https://a.example/")), Outcome::Block); - assert_eq!(decide(&config, &req(&img, "image", false, "https://b.example/")), Outcome::Allow); - let data = Url::parse("data:image/png;base64,AA").unwrap(); - assert_eq!(decide(&config, &req(&data, "image", false, "https://c.example/")), Outcome::Allow); + fn images_filter_blocks_the_sites_that_say_so() { + assert_eq!(images_filter(&HubConfig::default()), None); + let config = HubConfig { images_sites: vec![("a.example".into(), true), ("b.example".into(), false)], ..Default::default() }; + let rules: serde_json::Value = serde_json::from_str(&images_filter(&config).unwrap()).unwrap(); + assert_eq!(rules.as_array().unwrap().len(), 1); + assert_eq!(rules[0]["trigger"]["if-domain"], serde_json::json!(["a.example"])); + assert_eq!(rules[0]["trigger"]["resource-type"], serde_json::json!(["image"])); + assert_eq!(rules[0]["action"]["type"], "block"); + // Blocked by default: everywhere, then the allowed sites are let off. + let config = HubConfig { images_block_default: true, ..config }; + let rules: serde_json::Value = serde_json::from_str(&images_filter(&config).unwrap()).unwrap(); + assert!(rules[0]["trigger"].get("if-domain").is_none()); + assert_eq!(rules[1]["trigger"]["if-domain"], serde_json::json!(["b.example"])); + assert_eq!(rules[1]["action"]["type"], "ignore-previous-rules"); } #[test] diff --git a/src/net/privacy.rs b/src/net/privacy.rs index 3eb8475..5bcf318 100644 --- a/src/net/privacy.rs +++ b/src/net/privacy.rs @@ -35,8 +35,6 @@ pub fn languages(locale: &str) -> Vec { } /// The Accept-Language value for `languages`, with Firefox's weights: "en-US,en;q=0.5". -// Used by the WebKit glue for Accept-Language (S050); Servo applies its own copy in servo-net. -#[allow(dead_code)] pub fn accept_language(languages: &[String]) -> String { let weighted: Vec = languages .iter() diff --git a/src/resources.rs b/src/resources.rs index 6fa7f6e..5e45d34 100644 --- a/src/resources.rs +++ b/src/resources.rs @@ -3,7 +3,14 @@ /// Title of the network error page; a tab showing it is treated as "failed to load". pub const ERROR_TITLE: &str = "Couldn't open this page"; -#[allow(dead_code)] pub const BAD_CERT_TITLE: &str = "Connection not secure"; #[allow(dead_code)] pub const CRASH_TITLE: &str = "This page crashed"; + +/// The certificate warning (shown in the page area in place of the site): `url` and what is wrong; its "Open +/// anyway" goes to `nacre://allowcert`, which the browser takes only from this tab while the warning is up. +pub fn bad_cert_page(url: &url::Url, why: &str) -> String { + let page = include_str!("../assets/pages/badcert.html").replace("${url}", &crate::util::html_escape(url.as_str())).replace("${reason}", &crate::util::html_escape(why)); + debug_assert!(page.contains(&format!("{BAD_CERT_TITLE}"))); + page +} diff --git a/src/selftest.rs b/src/selftest.rs index 9b37b69..bf2cf61 100644 --- a/src/selftest.rs +++ b/src/selftest.rs @@ -94,6 +94,9 @@ pub struct SelfTest { js_poll: std::sync::Arc>, /// A real input helper (wl-input, wtype) still sending; the script goes on once it exits. input: Option, + /// `js`/`assert`/`save` sent to the page: the next line waits for its answer (set when it came), at most until + /// the deadline. Without this a run could quit before its last asserts were answered, and they never counted. + js_wait: Option<(std::sync::Arc, Instant, String)>, } impl SelfTest { @@ -102,7 +105,7 @@ impl SelfTest { let text = std::fs::read_to_string(&path).ok()?; let dir = path.parent().map(|p| p.to_owned()).unwrap_or_else(|| PathBuf::from(".")); let lines = text.lines().map(|l| l.trim().to_owned()).filter(|l| !l.is_empty() && !l.starts_with('#')).collect(); - Some(SelfTest { lines, next: 0, wait_until: None, wait_load_until: None, dir, pending_shot: false, pending_release: None, held: None, located: Default::default(), wait_js: None, wait_status_until: None, js_poll: Default::default(), input: None }) + Some(SelfTest { lines, next: 0, wait_until: None, wait_load_until: None, dir, pending_shot: false, pending_release: None, held: None, located: Default::default(), wait_js: None, wait_status_until: None, js_poll: Default::default(), input: None, js_wait: None }) } fn log(&self, text: &str) { @@ -169,6 +172,19 @@ impl App { } continue; } + if let Some((answered, until, what)) = &test.js_wait { + if answered.load(std::sync::atomic::Ordering::Relaxed) { + test.js_wait = None; + continue; + } + if Instant::now() >= *until { + test.log(&format!("ASSERT FAILED (no answer from the page): {what}")); + test.js_wait = None; + continue; + } + test.wait_until = Some(Instant::now() + Duration::from_millis(50)); + return; + } if let Some((expr, until)) = test.wait_js.clone() { let (in_flight, done) = test.js_poll.lock().map(|p| *p).unwrap_or((false, false)); if done || Instant::now() >= until { @@ -477,7 +493,9 @@ impl App { let log_path = dir.join("selftest.log"); let assert = verb == "assert"; let script = rest.to_owned(); + let answered = self.selftest_js_wait(&format!("{verb} {rest}")); web.evaluate_javascript(rest.to_owned(), move |result| { + answered.store(true, std::sync::atomic::Ordering::Relaxed); use std::io::Write as _; if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&log_path) { if !assert { @@ -497,7 +515,9 @@ impl App { return; }; let (log_path, out) = (dir.join("selftest.log"), dir.join(format!("{name}.json"))); + let answered = self.selftest_js_wait(&format!("save {name}")); web.evaluate_javascript(script.to_owned(), move |result| { + answered.store(true, std::sync::atomic::Ordering::Relaxed); use std::io::Write as _; let line = match result { Ok(serde_json::Value::String(text)) => match std::fs::write(&out, text) { @@ -775,6 +795,15 @@ impl App { } } + /// Hold the script until the page answers this evaluation (15 s at most); the flag is set by its callback. + fn selftest_js_wait(&mut self, what: &str) -> std::sync::Arc { + let answered = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + if let Some(t) = self.selftest.as_mut() { + t.js_wait = Some((answered.clone(), Instant::now() + Duration::from_secs(15), what.to_owned())); + } + answered + } + /// A page point (CSS px from the page's top left, as `click`) on the nested output: the window fills the output /// from its top left corner in the hidden session (niri, no gaps). fn selftest_output_point(&self, window: WindowId, x: f64, y: f64) -> Option<(i32, i32)> { @@ -833,7 +862,7 @@ impl App { .collect() }) .unwrap_or_default(); - let downloads: Vec = self.shared.downloads.borrow().items.iter().map(|d| serde_json::json!({"id": d.id, "name": d.file_name(), "state": format!("{:?}", d.state), "received": d.received, "total": d.total, "error": d.error, "manager": d.manager})).collect(); + let downloads: Vec = self.shared.downloads.borrow().items.iter().map(|d| serde_json::json!({"id": d.id, "name": d.file_name(), "url": d.url, "state": format!("{:?}", d.state), "received": d.received, "total": d.total, "error": d.error, "manager": d.manager})).collect(); let settings = self.shared.settings.borrow(); // Draw times (ms) of the window's recent frames: median and slowest. let frames = self.windows.get(&window).map(|w| { diff --git a/src/tabs.rs b/src/tabs.rs index e21ebdd..18be1bd 100644 --- a/src/tabs.rs +++ b/src/tabs.rs @@ -184,6 +184,8 @@ pub struct Tab { pub closing: Option, /// HTTPS-only upgraded this load from this URL. pub upgraded_from: Option, + /// The certificate warning on show; its "Open anyway" (`nacre://allowcert`) trusts this one. + pub cert_error: Option, /// Page details from META_JS. pub theme_color: Option, pub site_name: String, @@ -236,6 +238,7 @@ impl Tab { closing: None, crashed: None, upgraded_from: None, + cert_error: None, theme_color: None, site_name: String::new(), page_image: String::new(), diff --git a/tests/smoke/net-downloads.txt b/tests/smoke/net-downloads.txt index c2d0ab6..9e15acb 100644 --- a/tests/smoke/net-downloads.txt +++ b/tests/smoke/net-downloads.txt @@ -4,7 +4,8 @@ # dummy FDM program, tests/smoke/net/fake-fdm.sh) and Nacre downloads it itself when the manager isn't there. # Offline. Never Tor or proxies. Start the server first: # python3 tests/smoke/net/server.py & then tools/smoke.sh tests/smoke/net-downloads.txt -# Afterwards: /home/saved/ has file.zip, report.txt, their (1) copies, big.bin (4194304 bytes, byte i = i % 251) and no .part; +# Afterwards: /home/saved/ has file.zip, report.txt, their (1) copies, named.zip (), made.txt (blob:), +# file (2).zip (manager fallback), big.bin (4194304 bytes, byte i = i % 251) and no .part; # /home/fdm-args.txt has the FDM link. wait 3 set /downloads/dir "@HOME@/saved" @@ -44,6 +45,21 @@ status links expect /downloads/0/name "report (1).txt" expect /downloads/0/state "Done" expect /active/url "http://127.0.0.1:8766/" +# (S050): a web link goes to Nacre's downloader under the page's name, a page's blob: file is +# saved by WebKit under the name the page gave it. +js const a = document.createElement("a"); a.href = "/file.zip?download-attr"; a.download = "named.zip"; document.body.append(a); a.click() +wait 3 +status download-attr +expect /downloads/0/name "named.zip" +expect /downloads/0/state "Done" +expect /downloads/0/url "http://127.0.0.1:8766/file.zip?download-attr" +js const b = document.createElement("a"); b.href = URL.createObjectURL(new Blob(["made by the page"], { type: "text/plain" })); b.download = "made.txt"; document.body.append(b); b.click() +wait 3 +status blob +expect /downloads/0/name "made.txt" +expect /downloads/0/state "Done" +expect /downloads/0/received 16 +expect /active/url "http://127.0.0.1:8766/" # Pause and resume: the rest comes with a Range request. cmd download http://127.0.0.1:8766/big.bin wait 2 diff --git a/tests/smoke/net-privacy.txt b/tests/smoke/net-privacy.txt index d1ca370..25dbcd7 100644 --- a/tests/smoke/net-privacy.txt +++ b/tests/smoke/net-privacy.txt @@ -1,4 +1,4 @@ -# Network pass (S007): secure DNS through a local stub, the bridge with the VPN off, HTTPS-only (upgrade, the +# Network pass (S007, WebKit S050): secure DNS through a local stub, the bridge with the VPN off, HTTPS-only (upgrade, the # certificate warning's "Open anyway", fallback prompt, local addresses stay http), tracking parameter stripping. # Offline: every name resolves through tests/smoke/net/server.py (*.nacre.test -> 127.0.0.1, the rest NXDOMAIN). # Never Tor or proxies. Start the server first: @@ -41,10 +41,14 @@ assert location.href === "http://plain.nacre.test:8767/" open http://plain.nacre.test:8767/echo?again waitfor 20 document.title === "Echo again" assert location.protocol === "http:" -# Local addresses are never upgraded. +# Local addresses are never upgraded, and they skip the bridge (S050: through it they ended in "Message was restarted +# too many times" on the bridge's own address). open http://127.0.0.1:8767/ waitfor 20 document.title === "Net test http" assert location.protocol === "http:" +open http://localhost:8767/echo?local +waitfor 20 document.title === "Echo local" +assert location.href === "http://localhost:8767/echo?local" # Tracking parameters: removed, the rest kept, and the page is the clean address. open http://127.0.0.1:8766/echo?utm_source=news&id=3&fbclid=abc&utm_medium=mail waitfor 20 document.title === "Echo id=3" @@ -57,5 +61,22 @@ js fetch("http://127.0.0.1:8766/log").then(r => r.json()).then(l => { window.net waitfor 5 window.netlog !== undefined js JSON.stringify(window.netlog.dns) assert window.netlog.dns.includes("site.nacre.test") && window.netlog.dns.includes("plain.nacre.test") +# The upgraded load reached the server over TLS. +assert window.netlog.tls > 0 +# The Images permission (S050: a WebKit content filter): pictures blocked on 127.0.0.1's pages, back once it's reset. +perm 127.0.0.1 images block +wait 3 +open http://127.0.0.1:8767/echo?images +waitfor 20 document.title === "Echo images" +js window.pic = new Image(); window.pic.onload = window.pic.onerror = () => { window.picDone = true; }; window.pic.src = "http://img.nacre.test:8766/pixel?images=off"; 1 +waitfor 10 window.picDone === true +assert window.pic.naturalWidth === 0 +perm 127.0.0.1 images default +wait 3 +open http://127.0.0.1:8767/echo?images2 +waitfor 20 document.title === "Echo images2" +js window.pic = new Image(); window.pic.onload = window.pic.onerror = () => { window.picDone = true; }; window.pic.src = "http://img.nacre.test:8766/pixel?images=on"; 1 +waitfor 10 window.picDone === true +assert window.pic.naturalWidth === 1 status done quit diff --git a/tests/smoke/net/server.py b/tests/smoke/net/server.py index 81aa4fe..f7c7dc8 100644 --- a/tests/smoke/net/server.py +++ b/tests/smoke/net/server.py @@ -4,7 +4,8 @@ Port 8766 speaks plain HTTP and HTTPS on the same socket (it looks at the first byte), with a throwaway self-signed certificate for *.nacre.test. Port 8767 speaks plain HTTP only (an HTTPS upgrade to it fails). - /dns-query DNS over HTTPS stub (RFC 8484 GET): *.nacre.test -> 127.0.0.1, every other name NXDOMAIN, so + /dns-query DNS over HTTPS stub (RFC 8484 GET): *.nacre.test, *.other.test, accounts.google.com -> 127.0.0.1, + other name NXDOMAIN, so secure DNS pointed here never reaches a public resolver /auth HTTP Basic sign-in (smoke / letmein), title "Auth ok" or "Auth needed" (S048) / "Net test" page with links to the downloads below; /echo shows the query string in the title @@ -16,16 +17,17 @@ 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 - /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 + /setcookie?name=N[&domain=D][&ss=lax|none] sets cookie N=1 (Path=/, SameSite=None; Secure, so https only, or + the ss= variant; 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 (https://cdn.other.test:8766) and a + same-site picture (https://img.nacre.test:8766), titled "TP T done" when loaded /login?user=U signs in: a persistent cookie session=nacre-test-session-U (Max-Age a day, HttpOnly); /whoami is titled "Signed in as U" or "Signed out" (S025 restart smoke; the value stays out of history) /jstp?tag=T page with a cross-site frame (/jscookie) that writes and reads document.cookie and reports what it read as /note?tag=T&seen=... (S024) /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) + each GET's host, path, Cookie, DNT, Sec-GPC, Save-Data, Accept-Language and User-Agent headers Runs until killed. Usage: python3 tests/smoke/net/server.py & """ import json @@ -54,7 +56,7 @@ def make_cert(): folder = tempfile.mkdtemp(prefix="nacre-net-") cert, key = os.path.join(folder, "cert.pem"), os.path.join(folder, "key.pem") subprocess.run(["openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes", "-days", "2", "-subj", "/CN=nacre.test", - "-addext", "subjectAltName=DNS:*.nacre.test,DNS:nacre.test", "-keyout", key, "-out", cert], + "-addext", "subjectAltName=DNS:*.nacre.test,DNS:nacre.test,DNS:*.other.test", "-keyout", key, "-out", cert], check=True, capture_output=True) context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) context.load_cert_chain(cert, key) @@ -71,7 +73,8 @@ def dns_answer(query): question = query[12:pos + 5] name = ".".join(labels).lower() record("dns", name) - ours = name == "nacre.test" or name.endswith(".nacre.test") + # accounts.google.com too, so the Google sign-in user agent quirk can be checked offline (S050). + ours = name == "nacre.test" or name.endswith(".nacre.test") or name.endswith(".other.test") or name == "accounts.google.com" flags = b"\x81\x80" if ours else b"\x81\x83" answers = b"" if ours and qtype == 1: @@ -107,9 +110,9 @@ nacre.test,127.0.0.1##.nacre-ad TP_PAGE = """TP TAG

Third-party test TAG - - - + + + """ JSCOOKIE_PAGE = """JS cookie -""" GIF = bytes.fromhex("47494638396101000100800000ffffff00000021f90401000000002c00000000010001000002024401003b") @@ -138,7 +141,8 @@ class Handler(BaseHTTPRequestHandler): 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")}) + "savedata": self.headers.get("Save-Data"), "lang": self.headers.get("Accept-Language"), + "ua": self.headers.get("User-Agent")}) if path == "/dns-query": import base64 wire = parse_qs(url.query).get("dns", [""])[0] @@ -165,7 +169,10 @@ class Handler(BaseHTTPRequestHandler): 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 "") + # SameSite=None; Secure: a cookie without SameSite is Lax in WebKit (and Chromium) and never goes to a + # cross-site frame or picture, so the third-party switch would have nothing to block; None needs Secure. + extra = {"lax": "", "none": "; SameSite=None"}.get(query.get("ss", [""])[0], "; SameSite=None; Secure") + cookie = f"{name}=1; Path=/{extra}" + (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] diff --git a/tests/smoke/privacy-net.txt b/tests/smoke/privacy-net.txt index 5f3c00d..b1fc7a5 100644 --- a/tests/smoke/privacy-net.txt +++ b/tests/smoke/privacy-net.txt @@ -1,7 +1,10 @@ -# 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: +# Request headers (S023; the web process extension since S049) and third-party cookies (WebKit's cookie policy since +# S050); 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, *.other.test -> 127.0.0.1). site.nacre.test and +# img.nacre.test are one site (nacre.test); cdn.other.test is another. The cookies are SameSite=None; Secure, so the +# cookie pages are https (WebKit, like Chromium, treats a cookie without SameSite as Lax: never cross-site, whatever +# the switch says); the server's self-signed certificate is allowed per host through Nacre's warning first. +# 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 @@ -17,56 +20,86 @@ 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 +# The test certificate, allowed for each https host ("Open anyway"). +open https://site.nacre.test:8766/ +waitfor 20 document.title === "Connection not secure" +locate #allow +wait 0.5 +click @ +waitfor 20 document.title === "Net test https" +open https://img.nacre.test:8766/ +waitfor 20 document.title === "Connection not secure" +locate #allow +wait 0.5 +click @ +waitfor 20 document.title === "Net test https" +open https://cdn.other.test:8766/ +waitfor 20 document.title === "Connection not secure" +locate #allow +wait 0.5 +click @ +waitfor 20 document.title === "Net test https" +# First-party cookies: one for cdn.other.test, one for the whole nacre.test site. +open https://cdn.other.test:8766/setcookie?name=fp waitfor 20 document.title === "Set fp" -open http://site.nacre.test:8766/setcookie?name=sub&domain=nacre.test +open https://site.nacre.test:8766/setcookie?name=sub&domain=nacre.test waitfor 20 document.title === "Set sub" -open http://127.0.0.1:8767/cookies +open https://cdn.other.test:8766/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 +open https://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 +open https://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 +open https://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 +# cdn.other.test's own jar: fp, plus tpoff from the unblocked run; never tpon or tpmode. +open https://cdn.other.test:8766/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 +open https://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 +open https://site.nacre.test:8766/jstp?tag=joff waitfor 20 document.title === "JSTP joff done" -open http://127.0.0.1:8767/cookies +open https://cdn.other.test:8766/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. +# Privacy mode paused on one site (S024): common values on other sites, the engine's own on the paused one. The +# real core count goes to the paused page in its hash, read on a page loaded before privacy mode was on. +open http://127.0.0.1:8767/echo?real +waitfor 20 document.title === "Echo real" set /privacy/mode true set /privacy/mode_off ["127.0.0.1"] wait 1 +js location.href = "/echo?paused#" + navigator.hardwareConcurrency +waitfor 20 document.title === "Echo paused" +assert navigator.hardwareConcurrency === Number(location.hash.slice(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" +# WebKit's user agent is Safari-style, so appVersion is the user agent after "Mozilla/" (S050). +assert navigator.hardwareConcurrency === 8 && navigator.platform === "Linux x86_64" && navigator.appVersion === navigator.userAgent.slice(8) set /privacy/mode_off [] set /privacy/mode false +# Google sign-in (S050): Firefox's user agent for accounts.google.com's view only (the stub resolves it here). +set /privacy/google_signin true +wait 1 +open http://accounts.google.com:8767/echo?ua +waitfor 20 document.title === "Echo ua" +open http://127.0.0.1:8767/echo?ua2 +waitfor 20 document.title === "Echo ua2" # Do Not Track off: the headers stop. set /privacy/dnt false set /privacy/save_data false @@ -80,15 +113,17 @@ js window.pick = (tag, host) => window.reqs.filter(r => r.path.includes("tag=" + 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", "cdn.other.test").length === 2 && window.pick("on", "cdn.other.test").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. +# Not blocked: the cross-site requests carry cdn.other.test's cookie. +assert window.pick("off", "cdn.other.test").length === 2 && window.pick("off", "cdn.other.test").every(r => (r.cookie || "").includes("fp=1")) +# The cross-site frame's document.cookie: empty when blocked, cdn.other.test'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) +# Accept-Language: Firefox's list in privacy mode (S024), WebKit's weights for the same list otherwise (S050). +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 + "," + navigator.language.split("-")[0] + ";q=0.90") +# The user agent quirk: on the sign-in page's requests, not after leaving it. +assert window.reqs.some(r => r.path === "/echo?ua") && window.reqs.filter(r => r.path === "/echo?ua").every(r => r.ua.includes("Firefox/")) && window.reqs.filter(r => r.path === "/echo?ua2").every(r => !r.ua.includes("Firefox/")) # 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) +assert window.pick("mode", "cdn.other.test").length === 2 && window.pick("mode", "cdn.other.test").every(r => r.cookie === null) status done quit