diff --git a/Plans/02 Verify/S008-verify-stores.md b/Plans/02 Verify/S008-verify-stores.md index 73cedc0..cc60983 100644 --- a/Plans/02 Verify/S008-verify-stores.md +++ b/Plans/02 Verify/S008-verify-stores.md @@ -17,6 +17,7 @@ Verify passwords/vault and autofill, permissions prompts, history/bookmarks/down - [ ] History, bookmarks (add, folder, bookmarks bar, import/export HTML), downloads page lists entries - [ ] User scripts/styles apply on matching pages; install a site as an app and launch it - [ ] Importer: build a fake old-Nacre profile from `~/Documents/Apps/Nacre` config format in a temp dir (never the user's real profile) and import it +- [x] R1-20 per-site memory and enforcement: set per-site zoom, ad blocker on/off, privacy-mode flag (flag persistence only; internals are D-011) and other per-site choices; set per-site permissions (camera, mic, location, notifications, pop-ups, autoplay, …); quit, relaunch with `SMOKE_HOME=/home`, check values are in the stores and apply again on reopening the site; check each permission is enforced (blocked/allowed/asked per its stored value), not only stored; fix what is not - [ ] Change a sample of settings via `set` and via clicks; check `settings.json` and the effect; mark FEATURES rows - [ ] PROGRESS entry, INDEX line, commit `S008: …` and push diff --git a/src/actions.rs b/src/actions.rs index 4cf3222..684557f 100644 --- a/src/actions.rs +++ b/src/actions.rs @@ -2422,6 +2422,12 @@ impl App { /// The UI edits settings in place; this notices and applies what changed. pub fn apply_settings_if_changed(&mut self) { + let revision = self.shared.permissions.borrow().revision(); + if revision != self.permissions_seen { + self.permissions_seen = revision; + self.shared.permissions.borrow_mut().flush(); + self.refresh_hub_config(); + } let current = self.shared.settings.borrow().clone(); if current == self.applied { return; diff --git a/src/app.rs b/src/app.rs index 1abc2c1..9d3e3f6 100644 --- a/src/app.rs +++ b/src/app.rs @@ -182,6 +182,8 @@ pub struct App { pub gilrs: Option, pub gamepads: HashMap, pub applied: Settings, + /// `Permissions::revision` the hub and the file were last updated for. + pub permissions_seen: u64, pub exiting: bool, last_tick: Instant, last_save: Instant, @@ -307,6 +309,7 @@ impl App { gilrs: None, gamepads: HashMap::new(), applied: settings, + permissions_seen: 0, exiting: false, last_tick: Instant::now(), last_save: Instant::now(), @@ -392,7 +395,7 @@ 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.user_agent.borrow(), self.shared.http_allowed.borrow().clone()); + *self.hub.config.borrow_mut() = HubConfig::from_settings(&settings, &self.shared.permissions.borrow(), &self.shared.user_agent.borrow(), self.shared.http_allowed.borrow().clone()); } /// (Re)build the scripts every page gets. Applies on each page's next load. @@ -540,13 +543,16 @@ impl App { } } self.check_app_scope(window, id, &url); - if host_changed { - let zoom = self.shared.settings.borrow().zoom_for(&util::host_of(&url)); - if let Some(tab) = self.tab_mut(id) { - tab.zoom = zoom; - if let Some(web) = &tab.web { - web.webview.set_page_zoom(zoom); - } + // A zoom change is saved for the site at once, so the site's value is always the right one. Not only + // when the host changed: a new tab already holds its address when the first event arrives. + let zoom = self.shared.settings.borrow().zoom_for(&util::host_of(&url)); + if let Some(tab) = self.tab_mut(id) { + let differs = (tab.zoom - zoom).abs() > 0.001; + tab.zoom = zoom; + if (host_changed || differs) + && let Some(web) = &tab.web + { + web.webview.set_page_zoom(zoom); } } self.redraw(window); @@ -810,7 +816,7 @@ impl App { } // Mute state survives navigation. let shared = self.shared.clone(); - let muted = self.tab_mut(id).map(|t| t.muted || shared.settings.borrow().site_muted(&util::host_of_str(&t.url))).unwrap_or(false); + let muted = self.tab_mut(id).map(|t| t.muted || shared.settings.borrow().site_muted(&util::host_of_str(&t.url)) || shared.permissions.borrow().answer(&shared.settings.borrow(), &util::host_of_str(&t.url), crate::store::permissions::Kind::Sound) == crate::store::permissions::Answer::Block).unwrap_or(false); if muted && let Some(tab) = self.tab_mut(id) { tab.muted = true; if let Some(web) = &tab.web { diff --git a/src/hub.rs b/src/hub.rs index 9cc1e91..ace6fc6 100644 --- a/src/hub.rs +++ b/src/hub.rs @@ -15,6 +15,7 @@ use url::Url; use crate::adblock::{AdBlocker, Verdict}; use crate::inject::{self, PageMessage}; +use crate::store::permissions::{Answer, Decision, Kind, Permissions}; use crate::store::settings::Settings; use crate::util; @@ -73,13 +74,21 @@ pub struct HubConfig { pub https_exceptions: Vec, 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, } impl HubConfig { - pub fn from_settings(settings: &Settings, user_agent: &str, http_allowed: Vec) -> 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) -> HubConfig { HubConfig { adblock_enabled: settings.adblock.enabled, adblock_allow: settings.adblock.allow.clone(), @@ -87,6 +96,8 @@ impl HubConfig { 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, } @@ -245,9 +256,14 @@ impl Hub { return; } - // Sub-resources: the ad blocker. + // 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") { @@ -403,6 +419,20 @@ impl servo::GamepadDelegate for Gamepads { mod tests { use super::*; + #[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(); diff --git a/src/selftest.rs b/src/selftest.rs index 0ec2e71..d714731 100644 --- a/src/selftest.rs +++ b/src/selftest.rs @@ -10,6 +10,8 @@ //! resize resize the window (logical pixels) //! status save tabs, downloads, VPN, ad blocker and so on as .json //! set change a setting, e.g. `set /privacy/https_only true` +//! perm allow|block|default store a site's answer for a permission (kinds: store::permissions::Kind keys) +//! prompt allow|deny [remember] answer the active tab's first permission prompt //! flyout main, downloads, shield, vpn, media, siteinfo, profiles, apps, qr, tabmenu, back, //! bookmark (edit the current page's bookmark), none //! type put text in the address bar with its suggestions open @@ -271,6 +273,27 @@ impl App { } self.apply_settings_if_changed(); }, + "perm" => { + let parts: Vec<&str> = rest.split_whitespace().collect(); + let kind = parts.get(1).and_then(|k| crate::store::permissions::Kind::ALL.iter().find(|x| x.key() == *k)); + let decision = match parts.get(2).copied() { + Some("allow") => Some(Some(crate::store::permissions::Decision::Allow)), + Some("block") => Some(Some(crate::store::permissions::Decision::Block)), + Some("default") => Some(None), + _ => None, + }; + match (parts.first(), kind, decision) { + (Some(host), Some(kind), Some(decision)) => self.shared.permissions.borrow_mut().set(host, *kind, decision), + _ => self.selftest_log(&format!("perm: bad line {rest}")), + } + self.refresh_hub_config(); + }, + "prompt" => { + let remember = rest.contains("remember"); + let answer = if rest.starts_with("allow") { crate::actions::PromptAnswer::Allow { remember } } else { crate::actions::PromptAnswer::Deny { remember } }; + let tab = self.windows.get(&window).and_then(|w| w.tab()).map(|t| t.id).unwrap_or(0); + self.run_in(window, Command::Prompt { tab, answer }); + }, "flyout" => { let url = self.windows.get(&window).and_then(|w| w.tab()).map(|t| t.url.clone()).unwrap_or_default(); let tab = self.windows.get(&window).and_then(|w| w.tab()).map(|t| t.id).unwrap_or(0); @@ -676,6 +699,11 @@ impl App { "route": self.shared.bridge.as_ref().map(|b| format!("{:?}", b.route())), "bridge_bytes": self.shared.bridge.as_ref().map(|b| b.bytes.load(std::sync::atomic::Ordering::Relaxed)), "adblock": {"ready": self.shared.adblock.ready(), "rules": self.shared.adblock.rule_count(), "status": self.shared.adblock_status.borrow().clone(), "total": settings.adblock.total}, + "permissions": self.shared.permissions.borrow().all().iter().fold(serde_json::Map::new(), |mut m, (host, kind, decision)| { + m.entry(host.clone()).or_insert_with(|| serde_json::json!({})).as_object_mut().expect("object").insert(kind.key().to_owned(), serde_json::json!(format!("{decision:?}").to_lowercase())); + m + }), + "site_state": {"zoom_sites": settings.web.zoom_sites, "adblock_allow": settings.adblock.allow, "keep_active": settings.perf.keep_active, "muted_sites": settings.media.muted_sites, "https_exceptions": settings.privacy.https_exceptions}, "history": self.shared.history.borrow().len(), "bookmarks": self.shared.bookmarks.borrow().all().len(), "logins": self.shared.vault.borrow().contents.logins.len(), diff --git a/src/store/permissions.rs b/src/store/permissions.rs index 41eee72..19098ee 100644 --- a/src/store/permissions.rs +++ b/src/store/permissions.rs @@ -120,6 +120,18 @@ impl Kind { } } + /// Why Nacre can't enforce this one: Servo 0.7 has no per-site switch for it. Those rows show as unavailable. + pub fn engine_limit(self) -> Option<&'static str> { + match self { + Kind::Location => Some("Servo 0.7 never asks for the location: navigator.geolocation does nothing"), + Kind::Camera | Kind::Microphone | Kind::DeviceInfo => Some("Servo 0.7 has no navigator.mediaDevices, so no page can ask"), + Kind::Storage => Some("Servo 0.7 has no navigator.storage.persist(), so no page can ask"), + Kind::Javascript => Some("Servo 0.7 can't turn JavaScript off for one site"), + Kind::Clipboard => Some("Servo 0.7 doesn't ask before a page reads the clipboard"), + _ => None, + } + } + /// The answer when the user has set nothing: sensitive things ask, harmless ones are allowed. pub fn builtin_default(self) -> PermissionDefault { match self { @@ -150,12 +162,14 @@ pub struct Permissions { sites: BTreeMap>, dirty: bool, read_only: bool, + /// Counts every change, so the app notices edits made by menus and pages. + revision: u64, } impl Permissions { pub fn load(path: PathBuf, read_only: bool) -> Permissions { let sites = if read_only { BTreeMap::new() } else { util::load_json(&path) }; - Permissions { path, sites, dirty: false, read_only } + Permissions { path, sites, dirty: false, read_only, revision: 0 } } /// The decision stored for exactly this site, if any. @@ -198,6 +212,11 @@ impl Permissions { }, } self.dirty = true; + self.revision += 1; + } + + pub fn revision(&self) -> u64 { + self.revision } /// Every stored decision: (host, kind, decision). @@ -212,6 +231,7 @@ impl Permissions { pub fn clear_host(&mut self, host: &str) { if self.sites.remove(host).is_some() { self.dirty = true; + self.revision += 1; } } @@ -219,6 +239,7 @@ impl Permissions { if !self.sites.is_empty() { self.sites.clear(); self.dirty = true; + self.revision += 1; } } @@ -248,5 +269,6 @@ mod tests { assert_eq!(p.answer(&s, "a.example", Kind::Camera), Answer::Allow); p.set("a.example", Kind::Camera, None); assert!(p.all().is_empty()); + assert_eq!(p.revision(), 2); } } diff --git a/src/ui/pages/misc.rs b/src/ui/pages/misc.rs index 42f3f7a..4f55f07 100644 --- a/src/ui/pages/misc.rs +++ b/src/ui/pages/misc.rs @@ -3,7 +3,7 @@ use egui::{RichText, Sense, Stroke, Ui, vec2}; -use super::super::widgets::{ButtonKind, button, card, empty_state, icon, icon_button, icon_row, icon_link_row, list_item, page_column, page_header, row, search_pill, section, segmented, status_state, switch, switch_row}; +use super::super::widgets::{ButtonKind, button, card, empty_state, icon, icon_button, icon_row, icon_link_row, list_item, page_column, page_header, row, search_pill, section, segmented, status_state, switch, switch_row, unavailable_row}; use super::super::{Frame, paint}; use crate::actions::Command; use crate::store::permissions::{Decision, Kind}; @@ -73,6 +73,10 @@ pub fn site_settings(ui: &mut Ui, f: &mut Frame, host: &str) { section(ui, "Permissions"); card(ui, |ui| { for kind in Kind::ALL { + if let Some(reason) = kind.engine_limit() { + unavailable_row(ui, kind.label(), reason); + continue; + } let current = f.shared.permissions.borrow().site_decision(host, *kind); let mut value: u8 = match current { None => 0, diff --git a/src/ui/pages/settings.rs b/src/ui/pages/settings.rs index 1987730..1dc97dd 100644 --- a/src/ui/pages/settings.rs +++ b/src/ui/pages/settings.rs @@ -1293,6 +1293,10 @@ fn permissions(ui: &mut Ui, f: &mut Frame, s: &mut Settings) { section(ui, "Defaults"); card(ui, |ui| { for kind in crate::store::permissions::Kind::ALL { + if let Some(reason) = kind.engine_limit() { + unavailable_row(ui, kind.label(), reason); + continue; + } let mut value = s.privacy.permission_defaults.get(kind.key()).copied().unwrap_or_else(|| kind.builtin_default()); let before = value; row(ui, kind.label(), "", |ui| segmented(ui, &mut value, PermissionDefault::ALL)); diff --git a/tests/smoke/pages/site.html b/tests/smoke/pages/site.html new file mode 100644 index 0000000..55ee25e --- /dev/null +++ b/tests/smoke/pages/site.html @@ -0,0 +1,11 @@ + + +Site permissions probe + + diff --git a/tests/smoke/site-memory-restart.txt b/tests/smoke/site-memory-restart.txt new file mode 100644 index 0000000..02c8f9c --- /dev/null +++ b/tests/smoke/site-memory-restart.txt @@ -0,0 +1,36 @@ +# Per-site memory and permissions (S008, R1-20), part 2: run on part 1's home (SMOKE_HOME=/home). +# Everything set in part 1 is still stored, and applies again when the site is opened. +wait 3 +status stored +expect /permissions/127.0.0.1/notifications block +expect /permissions/127.0.0.1/popups block +expect /permissions/127.0.0.1/images block +expect /permissions/127.0.0.1/sound block +expect /site_state/adblock_allow/0 "127.0.0.1" +expect /site_state/keep_active/0 "127.0.0.1" +expect /site_state/muted_sites/0 "127.0.0.1" +expect /site_state/https_exceptions/0 "127.0.0.1" +expect /site_state/zoom_sites/127.0.0.1 > 1 +# Open the site fresh: zoom, mute, images and permissions apply again; a blocked pop-up stays blocked. +newtab http://127.0.0.1:8768/site.html +waitfor 20 window.res && window.res.img !== undefined +assert res.img === 'blocked' +wait 2 +status opened +expect /active/zoom > 1 +expect /active/muted true +js notif() +waitfor 10 res.notif === 'denied' +js pop() +wait 2 +status checked +expect /tab_count 2 +# Reset the images answer: the picture loads again, and the change is stored. +perm 127.0.0.1 images default +cmd reload +waitload +waitfor 20 window.res && window.res.img !== undefined +assert res.img === 'loaded' +shot images-back +status done +quit diff --git a/tests/smoke/site-memory.txt b/tests/smoke/site-memory.txt new file mode 100644 index 0000000..5b1cd5b --- /dev/null +++ b/tests/smoke/site-memory.txt @@ -0,0 +1,62 @@ +# Per-site memory and permissions (S008, R1-20), part 1: set values, then quit. +# Part 2 (site-memory-restart.txt) runs on the same home and checks they came back and still apply. Offline. +# python3 -m http.server 8768 --bind 127.0.0.1 --directory tests/smoke/pages & +# tools/smoke.sh tests/smoke/site-memory.txt (hidden) +# SMOKE_HOME=/home tools/smoke.sh tests/smoke/site-memory-restart.txt +wait 3 +open http://127.0.0.1:8768/site.html +waitfor 20 window.res && window.res.img !== undefined +assert res.img === 'loaded' +# Notifications: asks first; deny + remember; the next ask is refused without a prompt. +js notif() +wait 3 +status ask +expect /active/prompts 1 +prompt deny remember +waitfor 10 res.notif === 'denied' +js notif() +waitfor 10 res.notif === 'denied' +status notif +expect /active/prompts 0 +expect /permissions/127.0.0.1/notifications block +# Pop-ups: a new tab by default, none once blocked. +js pop() +wait 2 +status popup-default +expect /tab_count 2 +cmd close_tab +cmd select 0 +perm 127.0.0.1 popups block +js pop() +wait 2 +status popup +expect /tab_count 1 +# Images blocked for the site: the picture doesn't load after a reload. +perm 127.0.0.1 images block +cmd reload +waitload +waitfor 20 window.res && window.res.img !== undefined +assert res.img === 'blocked' +shot images-blocked +# Sound blocked: the tab is muted on load. +perm 127.0.0.1 sound block +cmd reload +waitload +wait 2 +status sound +expect /active/muted true +# Other per-site choices: zoom, ad blocker off, keep active, mute, HTTPS exception. +cmd zoom 1 +cmd zoom 1 +set /adblock/allow ["127.0.0.1"] +set /perf/keep_active ["127.0.0.1"] +set /media/muted_sites ["127.0.0.1"] +set /privacy/https_exceptions ["127.0.0.1"] +wait 1 +status set +expect /active/zoom > 1 +expect /site_state/adblock_allow/0 "127.0.0.1" +expect /permissions/127.0.0.1/images block +expect /permissions/127.0.0.1/popups block +status done +quit