S044 (WIP): privacy rules and request policy out of hub.rs

net::privacy (headers, tracking strip, language list) and net::policy
(HubConfig, pure decide() -> Outcome) with tests; Hub::decide is a thin Servo
adapter. Build, 74 tests, smokes launch/basics/input/net-adblock/net-privacy
green. Boxes 3-4 (ViewId, neutral payload types) not done: see the plan's WIP note.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-13 02:09:07 -06:00
commit 043987a634
7 changed files with 349 additions and 204 deletions

View file

@ -13,8 +13,8 @@ The app still builds and runs on Servo at the end of this plan.
- `src/hub.rs` (whole), `src/tabs.rs` (types), `src/app.rs` `handle_event` (547–800), the `hub::` uses in `src/actions.rs` (grep).
## Steps
- [ ] Move `privacy_headers`, `strip_tracking`, the Firefox-style language list and third-party matching (from `hub.rs` / `net::nacre` callers) into `src/net/privacy.rs` with their unit tests (`privacy_language_list_is_firefox_style`, `privacy_headers_follow_the_settings_and_reach_requests`, `third_party_matching_keeps_same_site_subdomains`); Servo code calls the new module.
- [ ] Move `HubConfig` and the request decision (HTTPS-only upgrade, tracking strip, image permission, ad-block verdict → `Decision` enum with Block/Replace/Redirect/Allow) out of `Hub::decide` into an engine-neutral `fn decide(cfg, req) -> Decision` (pure, unit-tested); `load_web_resource` becomes a thin adapter.
- [x] Move `privacy_headers`, `strip_tracking`, the Firefox-style language list and third-party matching (from `hub.rs` / `net::nacre` callers) into `src/net/privacy.rs` with their unit tests (`privacy_language_list_is_firefox_style`, `privacy_headers_follow_the_settings_and_reach_requests`, `third_party_matching_keeps_same_site_subdomains`); Servo code calls the new module.
- [x] Move `HubConfig` and the request decision (HTTPS-only upgrade, tracking strip, image permission, ad-block verdict → `Decision` enum with Block/Replace/Redirect/Allow) out of `Hub::decide` into an engine-neutral `fn decide(cfg, req) -> Decision` (pure, unit-tested); `load_web_resource` becomes a thin adapter.
- [ ] Give tabs a Nacre-owned view id (`ViewId(u64)`, reuse `new_tab_id`) and make `hub::Event` carry it instead of `WebViewId`; one map `WebViewId → ViewId` lives in the Servo glue only.
- [ ] Replace Servo payload types in `Event` and `tabs.rs` (`LoadStatus`, `JSValue`, `ContextMenu`, `EmbedderControl`, `PermissionRequest`, `ConsoleLogLevel`, …) by small Nacre enums/structs (`LoadState`, `JsValue` = `serde_json::Value`, `PageMenuRequest`, `Control`, `PermissionAsk`, …) holding a glue-side handle (boxed responder closure) where Servo needs an answer object.
- [ ] Port `selftest.rs` JS-result matches and `fakeload` to the neutral types.
@ -22,6 +22,18 @@ The app still builds and runs on Servo at the end of this plan.
- [ ] Smoke on Servo still green: `tools/smoke.sh tests/smoke/launch.txt`, `basics.txt`, `input.txt` (hidden).
- [ ] PROGRESS entry, INDEX line, tracker, commit `S044: …`, push.
## WIP — stopped here (2026-11-13, context limit of the spike session)
- Done (boxes 1–2): `src/net/privacy.rs` (privacy headers, tracking strip, language list + tests), `src/net/policy.rs`
(`HubConfig`, `Request`, `Outcome`, pure `decide()` + 4 tests); `Hub::decide` is a thin Servo adapter. The third-party
test stays in `hub.rs` (it tests vendored servo-net; WebKit's cookie policy replaces it). Note: `Outcome`, not
`Decision` (name taken by `store::permissions`).
- Verified on the WIP: release build green, `cargo test` 74 green (was 70), smokes launch, basics, input, net-adblock,
net-privacy exit 0 (hidden, Servo).
- Not done: boxes 3–4 (ViewId, neutral payload types). Finding: 56 uses of Servo payload types outside `hub.rs` plus 14
`WebViewId` sites in app/actions; converting them now means new Servo adapters that S045/S048 delete again.
Recommendation for the orchestrator: fold boxes 3–4 into S045 (Event surface defined there directly on WebKit, with
the payload types S047/S048 need), then tick 5–7 here on what exists and close S044.
## End criteria
- `grep -rn "servo::" src --include=*.rs | grep -v -E "src/(hub|window|app|resources)\.rs"` lists only glue adapters (each named in PROGRESS); `src/net/privacy.rs` has no `servo` import.
- `cargo test` green, launch/basics/input smokes green.

View file

@ -399,7 +399,7 @@ impl App {
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_extra_request_headers(&crate::net::privacy::privacy_headers(&settings));
net::nacre::set_block_third_party_cookies(settings.privacy.block_third_party || self.privacy_mode_on(&settings));
net::nacre::set_language_list(self.privacy_mode_on(&settings));
}
@ -435,7 +435,7 @@ impl App {
seed: &self.shared.seed,
user_agent: &self.shared.user_agent.borrow(),
privacy_paused: &s.privacy.mode_off,
languages: &net::nacre::languages(&net::nacre::locale()),
languages: &crate::net::privacy::languages(&net::nacre::locale()),
block_third_party: s.privacy.block_third_party || privacy,
dnt: s.privacy.dnt,
force_dark: s.web.force_dark,

View file

@ -13,10 +13,10 @@ use servo::{
};
use url::Url;
use crate::adblock::{AdBlocker, Verdict};
use crate::adblock::AdBlocker;
use crate::inject::{self, PageMessage};
use crate::store::permissions::{Answer, Decision, Kind, Permissions};
use crate::store::settings::Settings;
pub use crate::net::policy::HubConfig;
use crate::net::policy::{self, Outcome, Request};
use crate::util;
pub enum Event {
@ -65,45 +65,6 @@ pub struct NetEntry {
const NET_LOG_LEN: usize = 400;
/// What the synchronous decisions need from the rest of the browser. The app keeps it current.
#[derive(Default)]
pub struct HubConfig {
pub adblock_enabled: bool,
pub adblock_allow: Vec<String>,
pub https_only: bool,
pub https_exceptions: Vec<String>,
pub strip_params: bool,
pub google_signin: bool,
/// Images permission: blocked unless a site says otherwise, and the sites that differ (host, blocked).
pub images_block_default: bool,
pub images_sites: Vec<(String, bool)>,
pub user_agent: String,
/// Tabs where the user chose "open over http anyway" this session (host).
pub http_allowed: Vec<String>,
}
impl HubConfig {
/// Whether pictures are blocked on pages of this host.
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)
}
pub fn from_settings(settings: &Settings, permissions: &Permissions, user_agent: &str, http_allowed: Vec<String>) -> HubConfig {
HubConfig {
adblock_enabled: settings.adblock.enabled,
adblock_allow: settings.adblock.allow.clone(),
https_only: settings.privacy.https_only,
https_exceptions: settings.privacy.https_exceptions.clone(),
strip_params: settings.privacy.strip_params,
google_signin: settings.privacy.google_signin,
images_block_default: permissions.answer(settings, "", Kind::Images) == Answer::Block,
images_sites: permissions.all().into_iter().filter(|(_, kind, _)| *kind == Kind::Images).map(|(host, _, decision)| (host, decision == Decision::Block)).collect(),
user_agent: user_agent.to_owned(),
http_allowed,
}
}
}
pub struct Hub {
pub events: RefCell<VecDeque<Event>>,
pub token: String,
@ -122,42 +83,6 @@ pub struct Hub {
pub screen: RefCell<Option<servo::ScreenGeometry>>,
}
/// Tracking parameters removed from links when "strip tracking parameters" is on.
const TRACKING_PARAMS: &[&str] = &[
"fbclid", "gclid", "dclid", "gbraid", "wbraid", "msclkid", "mc_eid", "mc_cid", "igshid", "yclid", "_hsenc", "_hsmi", "twclid", "ttclid", "li_fat_id", "oly_enc_id", "oly_anon_id", "vero_id", "wickedid", "_openstat", "mkt_tok", "s_cid", "srsltid", "rb_clickid", "epik", "ga_source",
];
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()?;
let pairs: Vec<(String, String)> = url.query_pairs().map(|(k, v)| (k.into_owned(), v.into_owned())).collect();
let keep: Vec<&(String, String)> = pairs.iter().filter(|(k, _)| { let k = k.to_ascii_lowercase(); !TRACKING_PARAMS.contains(&k.as_str()) && !TRACKING_PREFIXES.iter().any(|p| k.starts_with(p)) }).collect();
if keep.len() == pairs.len() {
return None;
}
let mut clean = url.clone();
if keep.is_empty() {
clean.set_query(None);
} else {
clean.query_pairs_mut().clear().extend_pairs(keep.iter().map(|(k, v)| (k.as_str(), v.as_str())));
}
Some(clean)
}
fn destination_name(d: &content_security_policy::Destination) -> String {
format!("{d:?}").to_ascii_lowercase()
}
@ -212,7 +137,7 @@ impl Hub {
/// Switch the user agent for Google's sign-in pages and back.
fn google_quirk(&self, url: &Url) {
let want = self.config.borrow().google_signin && url.host_str().is_some_and(|h| h == "accounts.google.com");
let want = self.config.borrow().wants_ua_quirk(url);
if *self.ua_quirk_on.borrow() == want {
return;
}
@ -230,92 +155,58 @@ impl Hub {
let method = request.method.as_str().to_owned();
let page = webview.and_then(WebView::url);
let id = webview.map(WebView::id);
let is_document = request.is_for_main_frame;
let config = self.config.borrow();
if is_document && matches!(url.scheme(), "http" | "https") {
drop(config);
let main_frame = request.is_for_main_frame;
if main_frame && matches!(url.scheme(), "http" | "https") {
self.google_quirk(&url);
let config = self.config.borrow();
// 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("").to_owned();
let excepted = crate::net::bridge::is_local_host(&host) || config.https_exceptions.iter().chain(&config.http_allowed).any(|h| util::host_matches(&host, h));
if !excepted {
let mut secure = url.clone();
if secure.set_scheme("https").is_ok() {
if secure.port() == Some(80) {
let _ = secure.set_port(None);
}
drop(config);
if let Some(id) = id {
self.push(Event::UpgradedToHttps(id, url.clone()));
}
Self::serve_page(load, inject::redirect_page(secure.as_str(), "Opening the secure version…"));
return;
}
}
}
if config.strip_params
&& let Some(clean) = strip_tracking(&url)
{
drop(config);
Self::serve_page(load, inject::redirect_page(clean.as_str(), "Removing tracking parameters…"));
return;
}
drop(config);
// A new page: count its blocked requests from zero. Here, not at LoadStatus::Started: the app
// sees that event after the page's first sub-resources were already decided and counted.
if let Some(id) = id {
self.blocked.borrow_mut().insert(id, 0);
self.log_request(id, &method, url.as_str(), &kind, false);
}
return;
}
// Sub-resources: the Images permission, then the ad blocker.
let page_url = page.as_ref().map(Url::as_str).unwrap_or("");
let page_host = util::host_of_str(page_url);
if kind == "image" && matches!(url.scheme(), "http" | "https") && !page_host.is_empty() && config.images_blocked(&page_host) {
drop(config);
load.intercept(WebResourceResponse::new(url).status_code(StatusCode::NO_CONTENT)).cancel();
return;
}
let paused = !config.adblock_enabled || config.adblock_allow.iter().any(|h| util::host_matches(&page_host, h));
drop(config);
if !paused && matches!(url.scheme(), "http" | "https" | "ws" | "wss") {
match self.adblock.check(url.as_str(), page_url, &kind) {
Verdict::Allow => {},
Verdict::Block => {
if let Some(id) = id {
*self.blocked.borrow_mut().entry(id).or_insert(0) += 1;
self.log_request(id, &method, url.as_str(), &kind, true);
}
*self.blocked_total.borrow_mut() += 1;
load.intercept(WebResourceResponse::new(url).status_code(StatusCode::NO_CONTENT)).cancel();
return;
},
Verdict::Replace(mime, body) => {
if let Some(id) = id {
*self.blocked.borrow_mut().entry(id).or_insert(0) += 1;
self.log_request(id, &method, url.as_str(), &kind, true);
}
*self.blocked_total.borrow_mut() += 1;
let mut headers = HeaderMap::new();
if let Ok(value) = HeaderValue::from_str(&mime) {
headers.insert(http::header::CONTENT_TYPE, value);
}
let mut intercepted = load.intercept(WebResourceResponse::new(url).headers(headers));
intercepted.send_body_data(body);
intercepted.finish();
return;
},
}
let outcome = policy::decide(&self.config.borrow(), &self.adblock, &Request { url: &url, kind: &kind, main_frame, page_url });
match outcome {
Outcome::Upgrade(secure) => {
if let Some(id) = id {
self.push(Event::UpgradedToHttps(id, url.clone()));
}
Self::serve_page(load, inject::redirect_page(secure.as_str(), "Opening the secure version…"));
},
Outcome::Strip(clean) => Self::serve_page(load, inject::redirect_page(clean.as_str(), "Removing tracking parameters…")),
Outcome::NewPage => {
// A new page: count its blocked requests from zero. Here, not at LoadStatus::Started: the app
// sees that event after the page's first sub-resources were already decided and counted.
if let Some(id) = id {
self.blocked.borrow_mut().insert(id, 0);
self.log_request(id, &method, url.as_str(), &kind, false);
}
},
Outcome::Block { counted: false } => load.intercept(WebResourceResponse::new(url).status_code(StatusCode::NO_CONTENT)).cancel(),
Outcome::Block { counted: true } => {
self.count_blocked(id, &method, url.as_str(), &kind);
load.intercept(WebResourceResponse::new(url).status_code(StatusCode::NO_CONTENT)).cancel();
},
Outcome::Replace(mime, body) => {
self.count_blocked(id, &method, url.as_str(), &kind);
let mut headers = HeaderMap::new();
if let Ok(value) = HeaderValue::from_str(&mime) {
headers.insert(http::header::CONTENT_TYPE, value);
}
let mut intercepted = load.intercept(WebResourceResponse::new(url).headers(headers));
intercepted.send_body_data(body);
intercepted.finish();
},
Outcome::Allow => {
if let Some(id) = id {
self.log_request(id, &method, url.as_str(), &kind, false);
}
// Dropping `load` lets it through.
},
}
}
fn count_blocked(&self, id: Option<WebViewId>, method: &str, url: &str, kind: &str) {
if let Some(id) = id {
self.log_request(id, &method, url.as_str(), &kind, false);
*self.blocked.borrow_mut().entry(id).or_insert(0) += 1;
self.log_request(id, method, url, kind, true);
}
// Dropping `load` lets it through.
*self.blocked_total.borrow_mut() += 1;
}
}
@ -444,23 +335,7 @@ mod tests {
use super::*;
#[test]
fn privacy_language_list_is_firefox_style() {
assert_eq!(net::nacre::languages("en-US"), vec!["en-US", "en"]);
assert_eq!(net::nacre::languages("pt-BR"), vec!["pt-BR", "pt"]);
assert_eq!(net::nacre::languages("en"), vec!["en"]);
assert_eq!(net::nacre::accept_language(&net::nacre::languages("en-US")), "en-US,en;q=0.5");
assert_eq!(net::nacre::accept_language(&net::nacre::languages("de")), "de");
}
#[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")]);
fn privacy_headers_reach_requests() {
// 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();
@ -496,27 +371,4 @@ mod tests {
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();
let mut permissions = Permissions::load(std::path::PathBuf::from("/nonexistent/permissions.json"), true);
assert!(!HubConfig::from_settings(&settings, &permissions, "", Vec::new()).images_blocked("a.example"));
permissions.set("a.example", Kind::Images, Some(Decision::Block));
let config = HubConfig::from_settings(&settings, &permissions, "", Vec::new());
assert!(config.images_blocked("a.example") && !config.images_blocked("b.example"));
settings.privacy.permission_defaults.insert("images".into(), crate::store::settings::PermissionDefault::Block);
permissions.set("b.example", Kind::Images, Some(Decision::Allow));
let config = HubConfig::from_settings(&settings, &permissions, "", Vec::new());
assert!(config.images_blocked("a.example") && config.images_blocked("c.example") && !config.images_blocked("b.example"));
}
#[test]
fn strips_tracking() {
let u = Url::parse("https://a.example/p?id=3&utm_source=x&fbclid=y").unwrap();
assert_eq!(strip_tracking(&u).unwrap().as_str(), "https://a.example/p?id=3");
let u = Url::parse("https://a.example/p?utm_medium=x").unwrap();
assert_eq!(strip_tracking(&u).unwrap().as_str(), "https://a.example/p");
assert!(strip_tracking(&Url::parse("https://a.example/p?q=1").unwrap()).is_none());
}
}

View file

@ -37,7 +37,7 @@ pub struct Options<'a> {
pub user_agent: &'a str,
/// Sites where privacy mode is paused.
pub privacy_paused: &'a [String],
/// `navigator.languages` in privacy mode, matching its Accept-Language (`net::nacre::languages`).
/// `navigator.languages` in privacy mode, matching its Accept-Language (`net::privacy::languages`).
pub languages: &'a [String],
/// Third-party cookies are blocked (the setting or privacy mode): `document.cookie` in cross-site frames too.
pub block_third_party: bool,

View file

@ -6,6 +6,8 @@ pub mod dlm;
pub mod dns;
pub mod download;
pub mod fetch;
pub mod policy;
pub mod privacy;
pub mod tor;
use crate::net::bridge::{Route, Upstream};

179
src/net/policy.rs Normal file
View file

@ -0,0 +1,179 @@
//! The decision for one request the engine is about to make: HTTPS-only upgrade and tracking-parameter strip for
//! pages, the Images permission and the ad blocker for sub-resources. Pure: the engine glue applies the outcome
//! (serve a redirect page, cancel, replace the body) and keeps the counts.
use url::Url;
use crate::adblock::{AdBlocker, Verdict};
use crate::net::privacy::strip_tracking;
use crate::store::permissions::{Answer, Decision, Kind, Permissions};
use crate::store::settings::Settings;
use crate::util;
/// What the request decisions need from the rest of the browser. The app keeps it current.
#[derive(Default)]
pub struct HubConfig {
pub adblock_enabled: bool,
pub adblock_allow: Vec<String>,
pub https_only: bool,
pub https_exceptions: Vec<String>,
pub strip_params: bool,
pub google_signin: bool,
/// Images permission: blocked unless a site says otherwise, and the sites that differ (host, blocked).
pub images_block_default: bool,
pub images_sites: Vec<(String, bool)>,
pub user_agent: String,
/// Tabs where the user chose "open over http anyway" this session (host).
pub http_allowed: Vec<String>,
}
impl HubConfig {
/// Whether pictures are blocked on pages of this host.
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)
}
pub fn from_settings(settings: &Settings, permissions: &Permissions, user_agent: &str, http_allowed: Vec<String>) -> HubConfig {
HubConfig {
adblock_enabled: settings.adblock.enabled,
adblock_allow: settings.adblock.allow.clone(),
https_only: settings.privacy.https_only,
https_exceptions: settings.privacy.https_exceptions.clone(),
strip_params: settings.privacy.strip_params,
google_signin: settings.privacy.google_signin,
images_block_default: permissions.answer(settings, "", Kind::Images) == Answer::Block,
images_sites: permissions.all().into_iter().filter(|(_, kind, _)| *kind == Kind::Images).map(|(host, _, decision)| (host, decision == Decision::Block)).collect(),
user_agent: user_agent.to_owned(),
http_allowed,
}
}
/// Whether this URL is Google's sign-in page and the Firefox user agent should be used for it.
pub fn wants_ua_quirk(&self, url: &Url) -> bool {
self.google_signin && url.host_str().is_some_and(|h| h == "accounts.google.com")
}
}
/// 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.
#[derive(Debug, PartialEq)]
pub enum Outcome {
/// Let it through.
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. `counted`: the ad blocker blocked it (the shield counts it); not counted for the Images permission.
Block { counted: bool },
/// Serve this body instead (ad blocker redirect resource): (mime, body). Counted as blocked.
Replace(String, Vec<u8>),
}
pub fn decide(config: &HubConfig, adblock: &AdBlocker, 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;
}
// Sub-resources: the Images permission, then the ad blocker.
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 { counted: false };
}
let paused = !config.adblock_enabled || config.adblock_allow.iter().any(|h| util::host_matches(&page_host, h));
if paused || !matches!(url.scheme(), "http" | "https" | "ws" | "wss") {
return Outcome::Allow;
}
match adblock.check(url.as_str(), req.page_url, req.kind) {
Verdict::Allow => Outcome::Allow,
Verdict::Block => Outcome::Block { counted: true },
Verdict::Replace(mime, body) => Outcome::Replace(mime, body),
}
}
#[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();
let mut permissions = Permissions::load(std::path::PathBuf::from("/nonexistent/permissions.json"), true);
assert!(!HubConfig::from_settings(&settings, &permissions, "", Vec::new()).images_blocked("a.example"));
permissions.set("a.example", Kind::Images, Some(Decision::Block));
let config = HubConfig::from_settings(&settings, &permissions, "", Vec::new());
assert!(config.images_blocked("a.example") && !config.images_blocked("b.example"));
settings.privacy.permission_defaults.insert("images".into(), crate::store::settings::PermissionDefault::Block);
permissions.set("b.example", Kind::Images, Some(Decision::Allow));
let config = HubConfig::from_settings(&settings, &permissions, "", Vec::new());
assert!(config.images_blocked("a.example") && config.images_blocked("c.example") && !config.images_blocked("b.example"));
}
#[test]
fn pages_are_upgraded_then_stripped() {
let adblock = AdBlocker::new();
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, &adblock, &req(&u, "document", true, "")), 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, &adblock, &req(&u, "document", true, "")), Outcome::Strip(Url::parse("https://a.example/p").unwrap()));
let u = Url::parse("http://old.example/").unwrap();
assert_eq!(decide(&config, &adblock, &req(&u, "document", true, "")), Outcome::NewPage);
let u = Url::parse("http://127.0.0.1:8000/").unwrap();
assert_eq!(decide(&config, &adblock, &req(&u, "document", true, "")), Outcome::NewPage);
config.http_allowed.push("a.example".into());
let u = Url::parse("http://a.example/").unwrap();
assert_eq!(decide(&config, &adblock, &req(&u, "document", true, "")), Outcome::NewPage);
}
#[test]
fn blocked_images_are_not_counted_and_paused_sites_pass() {
let adblock = AdBlocker::new();
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, &adblock, &req(&img, "image", false, "https://a.example/")), Outcome::Block { counted: false });
assert_eq!(decide(&config, &adblock, &req(&img, "image", false, "https://b.example/")), Outcome::Allow);
let data = Url::parse("data:image/png;base64,AA").unwrap();
assert_eq!(decide(&config, &adblock, &req(&data, "image", false, "https://c.example/")), Outcome::Allow);
}
#[test]
fn google_quirk_only_on_sign_in() {
let config = HubConfig { google_signin: true, ..Default::default() };
assert!(config.wants_ua_quirk(&Url::parse("https://accounts.google.com/x").unwrap()));
assert!(!config.wants_ua_quirk(&Url::parse("https://www.google.com/").unwrap()));
}
}

100
src/net/privacy.rs Normal file
View file

@ -0,0 +1,100 @@
//! Privacy rules that don't depend on the engine: the extra request headers, tracking parameters and the
//! Firefox-style language list. The engine glue applies them (S023, S024).
use url::Url;
use crate::store::settings::Settings;
/// Tracking parameters removed from links when "strip tracking parameters" is on.
const TRACKING_PARAMS: &[&str] = &[
"fbclid", "gclid", "dclid", "gbraid", "wbraid", "msclkid", "mc_eid", "mc_cid", "igshid", "yclid", "_hsenc", "_hsmi", "twclid", "ttclid", "li_fat_id", "oly_enc_id", "oly_anon_id", "vero_id", "wickedid", "_openstat", "mkt_tok", "s_cid", "srsltid", "rb_clickid", "epik", "ga_source",
];
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.
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()?;
let pairs: Vec<(String, String)> = url.query_pairs().map(|(k, v)| (k.into_owned(), v.into_owned())).collect();
let keep: Vec<&(String, String)> = pairs.iter().filter(|(k, _)| { let k = k.to_ascii_lowercase(); !TRACKING_PARAMS.contains(&k.as_str()) && !TRACKING_PREFIXES.iter().any(|p| k.starts_with(p)) }).collect();
if keep.len() == pairs.len() {
return None;
}
let mut clean = url.clone();
if keep.is_empty() {
clean.set_query(None);
} else {
clean.query_pairs_mut().clear().extend_pairs(keep.iter().map(|(k, v)| (k.as_str(), v.as_str())));
}
Some(clean)
}
/// The languages pages are told about, Firefox-style: the locale and its bare language (`["en-US", "en"]`), or
/// the locale alone when it has no region.
pub fn languages(locale: &str) -> Vec<String> {
match locale.split_once('-') {
Some((language, _)) if !language.is_empty() => vec![locale.to_owned(), language.to_owned()],
_ => vec![locale.to_owned()],
}
}
/// The Accept-Language value for `languages`, with Firefox's weights: "en-US,en;q=0.5".
// 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<String> = languages
.iter()
.enumerate()
.map(|(i, language)| match i {
0 => language.clone(),
_ => format!("{language};q={:.1}", (1.0 - i as f32 * 0.5).max(0.1)),
})
.collect();
weighted.join(",")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn privacy_language_list_is_firefox_style() {
assert_eq!(languages("en-US"), vec!["en-US", "en"]);
assert_eq!(languages("pt-BR"), vec!["pt-BR", "pt"]);
assert_eq!(languages("en"), vec!["en"]);
assert_eq!(accept_language(&languages("en-US")), "en-US,en;q=0.5");
assert_eq!(accept_language(&languages("de")), "de");
}
#[test]
fn privacy_headers_follow_the_settings() {
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")]);
}
#[test]
fn strips_tracking() {
let u = Url::parse("https://a.example/p?id=3&utm_source=x&fbclid=y").unwrap();
assert_eq!(strip_tracking(&u).unwrap().as_str(), "https://a.example/p?id=3");
let u = Url::parse("https://a.example/p?utm_medium=x").unwrap();
assert_eq!(strip_tracking(&u).unwrap().as_str(), "https://a.example/p");
assert!(strip_tracking(&Url::parse("https://a.example/p?q=1").unwrap()).is_none());
}
}