S051: WIP profile folder nacre-browser, sealed WebKit cookie store on tmpfs

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-14 07:49:56 -06:00
commit d967f2a539
10 changed files with 446 additions and 108 deletions

View file

@ -68,7 +68,7 @@ Never modify: `~/Documents/Apps/Nacre` (the original Python Nacre, reference onl
| `nacre://gallery` + `SMOKE_SIZE=1400x2800 tools/smoke.sh tests/smoke/gallery.txt` | every design token and widget, dark and light (+ new tab and settings shots); read the PNGs | now (S015) |
| `SMOKE_SIZE=1400x1200 tools/smoke.sh tests/smoke/newtab.txt` | new tab page dark/light, nothing playing and a video playing, weather failed state, tall/narrow/phone widths (offline); `tests/smoke/newtab-weather.txt` shoots the real weather card (needs internet); read the PNGs | now (S017) |
| `SMOKE_SIZE=1400x900 tools/smoke.sh tests/smoke/backgrounds.txt` | every new tab background with the pointer, Customize panel dark/light, image + blur, GIF frames; `perf-*-a/b.json` `frames` (median/max draw ms, `drawn` count) per background at Lots/Fast, hidden tab, still, Motion off. Selftest `pointer x y`, `customize`; `@PAGESDIR@` = path of tests/smoke/pages | now (S018) |
| `tools/smoke.sh tests/smoke/settings.txt` (+ `SMOKE_SIZE=1280x1100`) | every settings section and sub-page dark and light, search results (`nacre://settings/?search=…`), narrow width; `settings-write.txt` (hidden, `SMOKE_SIZE=1280x1100`, fresh outdir) taps controls with selftest `tap x y`, then check `home/.config/nacre-servo/Default/settings.json` (expected values in its header) | now (S019) |
| `tools/smoke.sh tests/smoke/settings.txt` (+ `SMOKE_SIZE=1280x1100`) | every settings section and sub-page dark and light, search results (`nacre://settings/?search=…`), narrow width; `settings-write.txt` (hidden, `SMOKE_SIZE=1280x1100`, fresh outdir) taps controls with selftest `tap x y`, then check `home/.config/nacre-browser/Default/settings.json` (expected values in its header) | now (S019) |
| `SMOKE_SIZE=1280x1600 tools/smoke.sh tests/smoke/sliders.txt` | controls hold still (R1-21): Interface size drag (value label while held, applied on release), Contrast live, Style chip pick; `SMOKE_VISIBLE=1 tools/smoke.sh tests/smoke/sliders-visible.txt` the same plus scrolling for the user's window (~772 px). Selftest `press`/`drag`/`release`, `scroll x y dy`; read the PNGs | now (R1-21) |
| `python3 tests/smoke/net/server.py &` + `tools/smoke.sh tests/smoke/net-{privacy,adblock,downloads}.txt` | network pass, offline: secure DNS through a local DoH stub (`*.nacre.test` → 127.0.0.1), HTTPS-only + certificate warning, tracking params, ad blocker with a local list, downloads + download manager stubs; the server's `/log` has requests, DNS names, Range headers, manager calls. `cache-restart.txt` with `SMOKE_HOME=<cache.txt outdir>/home`: disk cache. `net-real.txt` needs internet. `@HOME@` in scripts = the throwaway home | now (S007) |
| `SMOKE_TIMEOUT=400 tools/smoke.sh tests/smoke/mse.txt`, `…/mse-player.txt` | plain MSE tests on WebKit: chunk-appended fMP4, WebM and split A/V play; `mse-spec.html` spec cases (attach/detach, duration, buffered/seekable, remove, removeSourceBuffer, changeType, abort, reopen, sequence); player integration (attach, seeks, rate, ended, decode error, garbage append; `?only=<case>` in the page URL for one case). Offline, start `python3 -m http.server 8765 --bind 127.0.0.1 --directory tests/smoke/pages &` first (MSE needs an http origin). `youtube-mse.txt` is an internet probe | S022, S027, S028, S053 |

View file

@ -13,7 +13,7 @@ one MPRIS player.
- D-019, D-037, D-038, D-039; `docs/engine/servo-removal.md` §3.8, §3.9; `src/paths.rs`, `src/store/cookies.rs` (whole); `tests/smoke/cookies.txt` header.
## Steps
- [ ] `paths.rs`: `APP_DIR = "nacre-browser"`; migration (rename config/data/cache once if new missing and old present; delete Servo-only engine files after; log it); unit test with temp dirs; `~/.config/nacre` never touched.
- [x] `paths.rs`: `APP_DIR = "nacre-browser"`; migration (rename config/data/cache once if new missing and old present; delete Servo-only engine files after; log it); unit test with temp dirs; `~/.config/nacre` never touched.
- [ ] Cookies: persistent storage path in `$XDG_RUNTIME_DIR/nacre-<profile>/cookies.sqlite`; at start decrypt `cookies.bin` → `add_cookie` (or write the SQLite) ; seal at quit and 60 s after `changed`; no keyring → run-only; convert Servo-era `cookies.bin` when it parses, else move aside.
- [ ] Clear data / clear on exit / site info flyout on `WebsiteDataManager` (types + since-time) and `CookieManager::get_cookies`; drop the "Servo keeps no dates" text.
- [ ] Incognito: ephemeral session, nothing written; check the throwaway home after a run.
@ -30,3 +30,6 @@ one MPRIS player.
## Handoff (→ PROGRESS.md)
Migration behaviour, seal timing, MPRIS outcome (which player).
## Resume note (WIP)
- Box 2 code done (store/cookies.rs: tmpfs `nacre-<profile>-<hash>/cookies.sqlite` written with rusqlite from cookies.bin, sealed by reading the DB; engine `Setup::cookie_db`, `Event::CookiesChanged`, App `cookies` tick/finish); unit tests green. Next: release build, cookies smokes to verify box 2, then box 3.

View file

@ -238,6 +238,8 @@ pub struct App {
last_tick: Instant,
last_save: Instant,
last_slow: Instant,
/// Sealed cookies (D-037), `None` when they are kept for the run only.
cookies: Option<crate::store::cookies::Cookies>,
last_presence: Instant,
pub crashed_last_time: bool,
pub instance: Option<crate::instance::Server>,
@ -362,6 +364,7 @@ impl App {
last_tick: Instant::now(),
last_save: Instant::now(),
last_slow: Instant::now() - Duration::from_secs(3600),
cookies: None,
last_presence: Instant::now(),
crashed_last_time,
instance: None,
@ -399,6 +402,8 @@ impl App {
fn start_engine(&mut self) {
let settings = self.shared.settings.borrow().clone();
let dark = self.web_dark();
// WebKit's cookie store on tmpfs, sealed into cookies.bin (D-037); without it cookies stay in memory.
self.cookies = crate::store::cookies::start(&self.shared.paths.data, &self.shared.paths.profile, self.shared.incognito);
let paths = &self.shared.paths;
let setup = crate::engine::host::Setup {
dirs: (!self.shared.incognito).then(|| (paths.webkit_data(), paths.webkit_cache())),
@ -408,9 +413,8 @@ impl App {
developer_extras: true,
remote_inspector: settings.web.remote_debugging.then(|| "127.0.0.1:6080".to_owned()),
filter_store: paths.cache.join("content-filters"),
cookie_db: self.cookies.as_ref().map(|c| c.db().to_path_buf()),
};
// Cookies stay in WebKit's memory for the run until S051 seals them (D-037); never plain on disk.
crate::store::cookies::start(&self.shared.paths.data, &self.shared.paths.engine(), self.shared.incognito);
let engine = Engine::new(self.hub.clone(), &setup);
{
use crate::store::permissions::{Decision, Kind};
@ -808,6 +812,11 @@ impl App {
Event::Notification(id, notification) => self.on_notification(id, notification),
Event::Page(id, message) => self.on_page_message(id, message),
Event::Find(id, count) => self.on_find(id, count),
Event::CookiesChanged => {
if let Some(cookies) = &mut self.cookies {
cookies.changed(Instant::now());
}
},
}
}
@ -1152,6 +1161,9 @@ impl App {
self.last_slow = now;
self.slow_tick();
}
if let Some(cookies) = &mut self.cookies {
cookies.tick(now);
}
}
fn update_media_now(&mut self) {
@ -1645,6 +1657,9 @@ impl App {
self.shared.settings.borrow_mut().adblock.total += total;
self.save_settings();
self.clear_on_exit();
if let Some(cookies) = self.cookies.take() {
cookies.finish(self.shared.settings.borrow().privacy.clear_on_exit.iter().any(|w| w == "cookies"));
}
self.flush_stores();
for control in self.download_controls.values() {
control.store(download::PAUSE, Ordering::Relaxed);

View file

@ -27,6 +27,8 @@ pub struct Setup {
pub remote_inspector: Option<String>,
/// Where WebKit keeps the compiled ad blocker filters.
pub filter_store: std::path::PathBuf,
/// WebKit's SQLite cookie store (on tmpfs, sealed by `store::cookies`); `None` = cookies in memory only.
pub cookie_db: Option<std::path::PathBuf>,
}
pub struct Engine {
@ -135,6 +137,11 @@ impl Engine {
if let Some(manager) = session.website_data_manager() {
manager.set_favicons_enabled(true);
}
if let (Some(db), Some(cookies)) = (&setup.cookie_db, session.cookie_manager()) {
cookies.set_persistent_storage(&db.to_string_lossy(), webkit::CookiePersistentStorage::Sqlite);
let hub = hub.clone();
cookies.connect_changed(move |_| hub.push(Event::CookiesChanged));
}
// 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 {

View file

@ -87,6 +87,8 @@ pub enum Event {
Page(ViewId, PageMessage),
/// Find in page: how many matches the last search or step found (0: none).
Find(ViewId, u32),
/// A cookie was added, changed or deleted.
CookiesChanged,
}
/// A user style sheet (`store::scripts`), added at author level so it acts like the page's own last `<style>`.

View file

@ -1,13 +1,16 @@
//! Where Nacre keeps its files, and which profile is in use.
//!
//! Layout (Linux; other systems use their own base folders through `dirs`):
//! ~/.config/nacre-servo/profiles.json list of profiles, which one starts by default
//! ~/.config/nacre-servo/<profile>/settings.json settings of one profile
//! ~/.local/share/nacre-servo/<profile>/ history, bookmarks, vault, session, engine storage
//! ~/.cache/nacre-servo/<profile>/ filter lists, favicons, dictionaries
//! ~/.config/nacre-browser/profiles.json list of profiles, which one starts by default
//! ~/.config/nacre-browser/<profile>/settings.json settings of one profile
//! ~/.local/share/nacre-browser/<profile>/ history, bookmarks, vault, session, engine storage
//! ~/.cache/nacre-browser/<profile>/ filter lists, favicons, dictionaries
//!
//! `NACRE_HOME` puts all three under one folder (tests use a throwaway one). An incognito
//! process uses a temporary folder that is removed when it exits.
//!
//! Builds before WebKit used `nacre-servo`; the first start moves those folders once (D-038).
//! `~/.config/nacre` belongs to the original Python Nacre and is never touched.
use std::path::{Path, PathBuf};
@ -15,7 +18,11 @@ use serde::{Deserialize, Serialize};
use crate::util;
pub const APP_DIR: &str = "nacre-servo";
pub const APP_DIR: &str = "nacre-browser";
/// The folder name of the Servo builds, moved to `APP_DIR` once (D-038).
const OLD_APP_DIR: &str = "nacre-servo";
/// What the Servo engine kept in a profile's data folder; WebKit never reads it.
const SERVO_FILES: &[&str] = &["engine", "http-cache", "http-cache-shm", "http-cache-wal"];
pub const DEFAULT_PROFILE: &str = "Default";
#[derive(Clone, Debug)]
@ -46,12 +53,44 @@ fn roots() -> (PathBuf, PathBuf, PathBuf) {
return (home.join("config"), home.join("data"), home.join("cache"));
}
let fallback = dirs::home_dir().unwrap_or_else(|| PathBuf::from("."));
let config = dirs::config_dir().unwrap_or_else(|| fallback.join(".config")).join(APP_DIR);
let data = dirs::data_dir().unwrap_or_else(|| fallback.join(".local/share")).join(APP_DIR);
let cache = dirs::cache_dir().unwrap_or_else(|| fallback.join(".cache")).join(APP_DIR);
let bases = [
dirs::config_dir().unwrap_or_else(|| fallback.join(".config")),
dirs::data_dir().unwrap_or_else(|| fallback.join(".local/share")),
dirs::cache_dir().unwrap_or_else(|| fallback.join(".cache")),
];
for (i, base) in bases.iter().enumerate() {
move_old_folder(base, i == 1);
}
let [config, data, cache] = bases.map(|base| base.join(APP_DIR));
(config, data, cache)
}
/// Renames `base/nacre-servo` to `base/nacre-browser` when only the old one exists, then (`data`: the data base)
/// deletes the Servo engine's files in each profile. True when it moved.
fn move_old_folder(base: &Path, data: bool) -> bool {
let (old, new) = (base.join(OLD_APP_DIR), base.join(APP_DIR));
if new.exists() || !old.is_dir() {
return false;
}
if let Err(error) = std::fs::rename(&old, &new) {
eprintln!("profile: cannot move {} to {}: {error}", old.display(), new.display());
return false;
}
eprintln!("profile: moved {} to {}", old.display(), new.display());
if data {
for profile in std::fs::read_dir(&new).into_iter().flatten().flatten().filter(|e| e.path().is_dir()) {
for name in SERVO_FILES {
let path = profile.path().join(name);
let removed = if path.is_dir() { std::fs::remove_dir_all(&path) } else { std::fs::remove_file(&path) };
if removed.is_ok() {
eprintln!("profile: deleted the Servo engine's {}", path.display());
}
}
}
}
true
}
/// Profile names become folder names, so keep them simple.
pub fn clean_profile_name(name: &str) -> String {
let cleaned: String = name.trim().chars().filter(|c| c.is_alphanumeric() || matches!(c, ' ' | '-' | '_')).take(40).collect();
@ -196,7 +235,6 @@ impl Paths {
pub fn permissions(&self) -> PathBuf { self.data.join("permissions.json") }
pub fn apps(&self) -> PathBuf { self.data.join("apps.json") }
pub fn app_icons(&self) -> PathBuf { self.data.join("app-icons") }
pub fn engine(&self) -> PathBuf { self.data.join("engine") }
/// WebKit's site data (local storage, IndexedDB, …) and HTTP cache.
pub fn webkit_data(&self) -> PathBuf { self.data.join("webkit") }
pub fn webkit_cache(&self) -> PathBuf { self.cache.join("webkit") }
@ -211,3 +249,37 @@ impl Paths {
/// Port and token of the running instance for this profile (single instance).
pub fn instance_file(&self) -> PathBuf { self.data.join("instance.json") }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn moves_servo_folder_once() {
let base = std::env::temp_dir().join(format!("nacre-paths-{}", util::random_hex(6)));
let old = base.join(OLD_APP_DIR).join(DEFAULT_PROFILE);
std::fs::create_dir_all(old.join("engine/webstorage")).unwrap();
std::fs::write(old.join("history.json"), "[]").unwrap();
std::fs::write(old.join("http-cache"), "x").unwrap();
std::fs::create_dir_all(base.join("nacre")).unwrap();
std::fs::write(base.join("nacre/config.json"), "{}").unwrap();
assert!(move_old_folder(&base, true));
let new = base.join(APP_DIR).join(DEFAULT_PROFILE);
assert!(!base.join(OLD_APP_DIR).exists());
assert!(new.join("history.json").exists(), "profile files kept");
assert!(!new.join("engine").exists() && !new.join("http-cache").exists(), "Servo files deleted");
assert!(base.join("nacre/config.json").exists(), "the Python Nacre's folder untouched");
// Both present: nothing moves.
std::fs::create_dir_all(base.join(OLD_APP_DIR)).unwrap();
assert!(!move_old_folder(&base, true));
assert!(base.join(OLD_APP_DIR).exists());
// Config and cache keep everything.
let cfg = base.join("cfg");
std::fs::create_dir_all(cfg.join(OLD_APP_DIR).join(DEFAULT_PROFILE).join("engine")).unwrap();
assert!(move_old_folder(&cfg, false));
assert!(cfg.join(APP_DIR).join(DEFAULT_PROFILE).join("engine").exists());
let _ = std::fs::remove_dir_all(base);
}
}

View file

@ -1,36 +1,42 @@
//! Cookies encrypted at rest (R1-19).
//! Cookies encrypted at rest (R1-19, D-019, D-037).
//!
//! A plain cookie jar (`engine/cookie_jar.json`) can be replayed by an infostealer copying the profile to take over
//! signed-in sessions. Nacre keeps the jar in `cookies.bin` instead, sealed like the vault
//! (XChaCha20-Poly1305) with a 256-bit key held in the OS keyring: Secret Service (GNOME Keyring, KWallet) on Linux,
//! Credential Manager on Windows. The file alone is useless without the user's unlocked keyring.
//! A plain cookie store can be replayed by an infostealer copying the profile to take over signed-in sessions.
//! WebKit keeps its cookies in a SQLite file, so that file lives in the per-login tmpfs (`$XDG_RUNTIME_DIR`, 0700,
//! never on disk); Nacre seals its persistent cookies into `cookies.bin` like the vault (XChaCha20-Poly1305) with a
//! 256-bit key held in the OS keyring (Secret Service on Linux). The file alone is useless without the user's
//! unlocked keyring.
//!
//! - Loaded before the engine starts; saved every few seconds when the jar changed, and when the engine exits.
//! - A plain cookie_jar.json from older builds is read once and deleted after the first encrypted save reads back.
//! - No keyring: cookies stay in memory for this run only (nothing plain is written); Settings says so.
//! - A file that doesn't decrypt (key gone, keyring reset) is moved to `cookies-unreadable-<time>.bin`, never
//! deleted; it opens again if the old key comes back into the keyring.
//! - Incognito: nothing is read or written.
//! - At start `cookies.bin` is decrypted into a fresh `cookies.sqlite` before WebKit opens it. A database the last
//! run left behind (it crashed before sealing) is newer than the sealed file and is kept instead.
//! - Sealed 60 s after WebKit reports a change and at quit; the tmpfs folder is removed after the last seal.
//! - Session cookies (no expiry) are not kept, as in WebKit's own store and the original Nacre.
//! - A Servo-era `cookies.bin` (its JSON cookie jar) is converted; one that doesn't decrypt or parse is moved to
//! `cookies-unreadable-<time>.bin`, never deleted.
//! - No keyring or no `$XDG_RUNTIME_DIR`: cookies stay in WebKit's memory for this run only; Settings says so.
//! - Incognito: an ephemeral WebKit session, nothing read or written.
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::Duration;
use std::sync::{Mutex, OnceLock};
use std::time::{Duration, Instant};
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD as B64;
use serde::{Deserialize, Serialize};
use crate::store::vault::{seal, unseal};
use crate::util;
pub const FILE: &str = "cookies.bin";
/// The plain jar older builds wrote into the engine's config dir.
pub const PLAIN_FILE: &str = "cookie_jar.json";
const DB: &str = "cookies.sqlite";
const MAGIC: &[u8] = b"NACRECK1";
const AAD: &[u8] = b"nacre-cookies-v1";
const KEYRING_SERVICE: &str = "Nacre";
const SAVE_EVERY: Duration = Duration::from_secs(5);
/// How long after a change the cookies are sealed (D-037).
const SEAL_AFTER: Duration = Duration::from_secs(60);
/// libsoup's cookie table (`SoupCookieJarDB`), which WebKit opens.
const SCHEMA: &str = "CREATE TABLE moz_cookies (id INTEGER PRIMARY KEY, name TEXT, value TEXT, host TEXT, path TEXT, expiry INTEGER, lastAccessed INTEGER, isSecure INTEGER, isHttpOnly INTEGER, sameSite INTEGER)";
static KEEPING: OnceLock<Keeping> = OnceLock::new();
@ -40,7 +46,7 @@ pub enum Keeping {
Encrypted,
NoKeyring,
Incognito,
/// WebKit keeps cookies in memory until S051 seals its store (D-037).
/// No private temporary folder (`$XDG_RUNTIME_DIR`) for WebKit's store.
RunOnly,
}
@ -50,7 +56,7 @@ impl Keeping {
Keeping::Encrypted => "Encrypted on disk with a key in your system keyring",
Keeping::NoKeyring => "No system keyring found: cookies are kept until Nacre closes, never written unencrypted",
Keeping::Incognito => "Incognito: cookies are never written to disk",
Keeping::RunOnly => "Cookies are kept until Nacre closes; saving them encrypted comes back in a later update",
Keeping::RunOnly => "No private temporary folder (XDG_RUNTIME_DIR): cookies are kept until Nacre closes, never written unencrypted",
}
}
}
@ -60,6 +66,120 @@ pub fn keeping() -> Option<Keeping> {
KEEPING.get().copied()
}
/// One persistent cookie, as libsoup's table holds it. `host` starts with a dot for a domain cookie.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Cookie {
pub name: String,
pub value: String,
pub host: String,
pub path: String,
/// Unix seconds.
pub expiry: i64,
pub secure: bool,
pub http_only: bool,
/// libsoup's `SoupSameSitePolicy`: 0 none, 1 lax, 2 strict.
pub same_site: i64,
}
#[derive(Serialize, Deserialize)]
struct Sealed {
version: u32,
cookies: Vec<Cookie>,
}
/// The sealed contents: Nacre's list, or the Servo builds' cookie jar converted. `None` when neither parses.
fn parse_sealed(json: &[u8]) -> Option<Vec<Cookie>> {
if let Ok(sealed) = serde_json::from_slice::<Sealed>(json) {
return Some(sealed.cookies);
}
from_servo_jar(json)
}
/// Servo's jar: `{"cookies_map": {key: [{"cookie": "<Set-Cookie string>", "host_only", "persistent",
/// "expiry_time": {"secs_since_epoch", …}}]}}`. Servo always set the Domain attribute; host-only cookies get no dot.
fn from_servo_jar(json: &[u8]) -> Option<Vec<Cookie>> {
#[derive(Deserialize)]
struct Time {
secs_since_epoch: i64,
}
#[derive(Deserialize)]
struct ServoCookie {
cookie: String,
host_only: bool,
persistent: bool,
expiry_time: Option<Time>,
}
#[derive(Deserialize)]
struct Jar {
cookies_map: std::collections::HashMap<String, Vec<ServoCookie>>,
}
let jar: Jar = serde_json::from_slice(json).ok()?;
let now = util::now() as i64;
let mut out = Vec::new();
for (key, cookies) in jar.cookies_map {
for c in cookies {
let Some(expiry) = c.expiry_time.filter(|_| c.persistent).map(|t| t.secs_since_epoch).filter(|e| *e > now) else { continue };
let mut parts = c.cookie.split(';');
let Some((name, value)) = parts.next().and_then(|nv| nv.split_once('=')) else { continue };
let mut cookie = Cookie { name: name.trim().into(), value: value.trim().into(), host: key.clone(), path: "/".into(), expiry, secure: false, http_only: false, same_site: 0 };
for attr in parts {
let (k, v) = attr.split_once('=').unwrap_or((attr, ""));
match k.trim().to_ascii_lowercase().as_str() {
"domain" => cookie.host = v.trim().trim_start_matches('.').to_ascii_lowercase(),
"path" if !v.trim().is_empty() => cookie.path = v.trim().into(),
"secure" => cookie.secure = true,
"httponly" => cookie.http_only = true,
"samesite" => cookie.same_site = match v.trim().to_ascii_lowercase().as_str() {
"lax" => 1,
"strict" => 2,
_ => 0,
},
_ => {},
}
}
if !c.host_only {
cookie.host.insert(0, '.');
}
out.push(cookie);
}
}
Some(out)
}
/// Writes a fresh libsoup cookie database at `db` holding `cookies`.
fn write_db(db: &Path, cookies: &[Cookie]) -> rusqlite::Result<()> {
let mut conn = rusqlite::Connection::open(db)?;
conn.execute_batch(SCHEMA)?;
let tx = conn.transaction()?;
{
let mut insert = tx.prepare("INSERT INTO moz_cookies VALUES (NULL, ?1, ?2, ?3, ?4, ?5, NULL, ?6, ?7, ?8)")?;
for c in cookies {
insert.execute(rusqlite::params![c.name, c.value, c.host, c.path, c.expiry, c.secure, c.http_only, c.same_site])?;
}
}
tx.commit()
}
/// The unexpired cookies in WebKit's database.
fn read_db(db: &Path) -> rusqlite::Result<Vec<Cookie>> {
let conn = rusqlite::Connection::open_with_flags(db, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)?;
conn.busy_timeout(Duration::from_secs(2))?;
let mut select = conn.prepare("SELECT name, value, host, path, expiry, isSecure, isHttpOnly, sameSite FROM moz_cookies WHERE expiry > ?1 ORDER BY id")?;
let rows = select.query_map([util::now() as i64], |r| {
Ok(Cookie {
name: r.get::<_, Option<String>>(0)?.unwrap_or_default(),
value: r.get::<_, Option<String>>(1)?.unwrap_or_default(),
host: r.get::<_, Option<String>>(2)?.unwrap_or_default(),
path: r.get::<_, Option<String>>(3)?.unwrap_or_default(),
expiry: r.get(4)?,
secure: r.get::<_, Option<i64>>(5)?.unwrap_or(0) != 0,
http_only: r.get::<_, Option<i64>>(6)?.unwrap_or(0) != 0,
same_site: r.get::<_, Option<i64>>(7)?.unwrap_or(0),
})
})?;
rows.collect()
}
pub fn encrypt(key: &[u8; 32], json: &[u8]) -> Vec<u8> {
let mut out = MAGIC.to_vec();
out.extend(seal(key, AAD, json));
@ -78,11 +198,9 @@ fn digest(json: &[u8]) -> u64 {
#[derive(Default)]
struct SaveState {
/// Digest of the jar last written, to skip unchanged saves.
/// Digest of the contents last written, to skip unchanged saves.
last: Option<u64>,
/// A plain jar still waiting to be deleted once the encrypted copy is safe.
plain: Option<PathBuf>,
/// The engine has exited and the final jar is written: later saves would be older.
/// The final seal is written: later saves would be older.
closed: bool,
}
@ -93,154 +211,275 @@ pub struct CookieStore {
}
impl CookieStore {
/// Opens `dir/cookies.bin` and returns the jar to start with: the decrypted file, or else the plain jar at
/// `plain` (migration). A file that doesn't decrypt is moved aside.
pub fn open(dir: &Path, plain: &Path, key: [u8; 32]) -> (CookieStore, Option<Vec<u8>>) {
/// Opens `dir/cookies.bin` and returns the cookies to start with. A file that doesn't decrypt or parse is moved
/// aside.
pub fn open(dir: &Path, key: [u8; 32]) -> (CookieStore, Option<Vec<Cookie>>) {
let path = dir.join(FILE);
let mut initial = None;
match std::fs::read(&path) {
Ok(bytes) => match decrypt(&key, &bytes) {
Some(json) => initial = Some(json),
Ok(bytes) => match decrypt(&key, &bytes).and_then(|json| parse_sealed(&json)) {
Some(cookies) => initial = Some(cookies),
None => {
let aside = dir.join(format!("cookies-unreadable-{}.bin", util::now()));
log::warn!("cookies: {} doesn't decrypt with the keyring key; moved to {}", path.display(), aside.display());
eprintln!("cookies: {} doesn't decrypt with the keyring key or isn't a cookie list; moved to {}", path.display(), aside.display());
if let Err(e) = std::fs::rename(&path, &aside) {
log::warn!("cookies: could not move it aside: {e}");
eprintln!("cookies: could not move it aside: {e}");
}
}
},
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => log::warn!("cookies: can't read {}: {e}", path.display()),
Err(e) => eprintln!("cookies: can't read {}: {e}", path.display()),
}
let plain = plain.exists().then(|| plain.to_path_buf());
if let (None, Some(plain)) = (&initial, &plain) {
log::info!("cookies: moving the plain cookie jar into the encrypted store");
initial = std::fs::read(plain).ok();
}
let state = SaveState { plain, ..SaveState::default() };
(CookieStore { path, key, state: Mutex::new(state) }, initial)
(CookieStore { path, key, state: Mutex::new(SaveState::default()) }, initial)
}
/// Writes the jar if it changed. True when written.
pub fn save(&self, json: &[u8]) -> bool {
/// Seals `cookies` if they changed. True when written.
pub fn save(&self, cookies: &[Cookie]) -> bool {
let json = serde_json::to_vec(&Sealed { version: 2, cookies: cookies.to_vec() }).unwrap_or_default();
let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
let digest = digest(json);
let digest = digest(&json);
if state.closed || state.last == Some(digest) {
return false;
}
if let Err(e) = util::write_atomic(&self.path, &encrypt(&self.key, json), true) {
log::warn!("cookies: not saved: {e}");
if let Err(e) = util::write_atomic(&self.path, &encrypt(&self.key, &json), true) {
eprintln!("cookies: not saved: {e}");
return false;
}
state.last = Some(digest);
if let Some(plain) = state.plain.take() {
let reads_back = std::fs::read(&self.path).ok().and_then(|b| decrypt(&self.key, &b)).is_some_and(|b| b == json);
if reads_back && std::fs::remove_file(&plain).is_ok() {
log::info!("cookies: plain cookie jar deleted");
} else {
state.plain = Some(plain);
}
}
true
}
/// The last save (the engine's exit): nothing after it may overwrite the file.
/// The last save (quit): nothing after it may overwrite the file.
pub fn close(&self) {
self.state.lock().unwrap_or_else(|e| e.into_inner()).closed = true;
}
}
fn closed(&self) -> bool {
self.state.lock().unwrap_or_else(|e| e.into_inner()).closed
/// The sealed store and WebKit's database on tmpfs for one run (`Keeping::Encrypted`).
pub struct Cookies {
store: CookieStore,
db: PathBuf,
changed: Option<Instant>,
}
impl Cookies {
/// WebKit's SQLite cookie database (`CookieManager::set_persistent_storage`).
pub fn db(&self) -> &Path {
&self.db
}
/// WebKit reported a cookie change: seal within `SEAL_AFTER`.
pub fn changed(&mut self, now: Instant) {
self.changed.get_or_insert(now);
}
/// Seals when a change is `SEAL_AFTER` old.
pub fn tick(&mut self, now: Instant) {
if self.changed.is_some_and(|t| now.duration_since(t) >= SEAL_AFTER) {
self.changed = None;
self.seal();
}
}
/// Seals WebKit's database into `cookies.bin`. True when written.
pub fn seal(&self) -> bool {
match read_db(&self.db) {
Ok(cookies) => self.store.save(&cookies),
Err(e) => {
eprintln!("cookies: can't read {}: {e}", self.db.display());
false
},
}
}
/// Quit: the last seal (`cleared`: the cookies are being deleted, seal none), then the tmpfs folder goes.
pub fn finish(&self, cleared: bool) {
if cleared {
self.store.save(&[]);
} else {
self.seal();
}
self.store.close();
if let Some(dir) = self.db.parent() {
let _ = std::fs::remove_dir_all(dir);
}
}
}
/// The cookie key from the OS keyring, made on first use. `None` when there is no usable keyring.
fn keyring_key(account: &str) -> Option<[u8; 32]> {
let entry = keyring::Entry::new(KEYRING_SERVICE, account).map_err(|e| log::warn!("cookies: no keyring: {e}")).ok()?;
/// `old`: the account of the same profile before its folder moved (D-038), whose key is taken over.
fn keyring_key(account: &str, old: &str) -> Option<[u8; 32]> {
let entry = keyring::Entry::new(KEYRING_SERVICE, account).map_err(|e| eprintln!("cookies: no keyring: {e}")).ok()?;
let text = match entry.get_password() {
Ok(text) => text,
Err(keyring::Error::NoEntry) => {
let mut key = [0u8; 32];
util::random_bytes(&mut key);
let text = B64.encode(key);
let moved = (old != account).then(|| keyring::Entry::new(KEYRING_SERVICE, old).and_then(|e| e.get_password()).ok()).flatten();
let text = moved.unwrap_or_else(|| {
let mut key = [0u8; 32];
util::random_bytes(&mut key);
B64.encode(key)
});
if let Err(e) = entry.set_password(&text) {
log::warn!("cookies: keyring refused the key: {e}");
eprintln!("cookies: keyring refused the key: {e}");
return None;
}
log::info!("cookies: new key stored in the keyring");
// Read it back: a keyring that drops what it is given would lose every cookie at the next start.
entry.get_password().ok().filter(|t| *t == text)?
}
Err(e) => {
log::warn!("cookies: keyring unavailable: {e}");
eprintln!("cookies: keyring unavailable: {e}");
return None;
}
};
B64.decode(text.trim()).ok()?.try_into().ok()
}
/// Sets how this run keeps cookies. WebKit keeps them in memory (its store is not given a file) until S051 wires
/// the sealed `cookies.bin` to it (D-037), so nothing is written unencrypted meanwhile.
pub fn start(_data: &Path, _engine: &Path, incognito: bool) -> Keeping {
let keeping = if incognito { Keeping::Incognito } else { Keeping::RunOnly };
/// Prepares WebKit's database in `dir` (tmpfs) from the sealed file. A database left by a run that didn't finish
/// is newer than the sealed file and stays.
fn open(data: &Path, dir: &Path, key: [u8; 32]) -> Option<Cookies> {
let (store, initial) = CookieStore::open(data, key);
let db = dir.join(DB);
let made = std::fs::create_dir_all(dir).and_then(|_| {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?;
}
Ok(())
});
if let Err(e) = made {
eprintln!("cookies: can't make {}: {e}", dir.display());
return None;
}
if read_db(&db).is_ok() {
eprintln!("cookies: using the database the last run left in {}", dir.display());
} else {
for name in [DB.to_owned(), format!("{DB}-wal"), format!("{DB}-shm"), format!("{DB}-journal")] {
let _ = std::fs::remove_file(dir.join(name));
}
if let Err(e) = write_db(&db, initial.as_deref().unwrap_or_default()) {
eprintln!("cookies: can't write {}: {e}", db.display());
return None;
}
}
Some(Cookies { store, db, changed: None })
}
/// Sets how this run keeps cookies. `Some` for `Keeping::Encrypted`: WebKit's database is ready at `Cookies::db`.
pub fn start(data: &Path, profile: &str, incognito: bool) -> Option<Cookies> {
let runtime = std::env::var_os("XDG_RUNTIME_DIR").filter(|v| !v.is_empty()).map(PathBuf::from).filter(|d| d.is_dir());
let (keeping, cookies) = if incognito {
(Keeping::Incognito, None)
} else if let Some(runtime) = runtime {
let account = format!("cookies {}", data.display());
let old = account.replace(&format!("/{}/", crate::paths::APP_DIR), "/nacre-servo/");
match keyring_key(&account, &old) {
// One folder per profile folder, so a test home never meets the user's running browser.
Some(key) => match open(data, &runtime.join(format!("nacre-{profile}-{:08x}", digest(account.as_bytes()) as u32)), key) {
Some(cookies) => (Keeping::Encrypted, Some(cookies)),
None => (Keeping::RunOnly, None),
},
None => (Keeping::NoKeyring, None),
}
} else {
(Keeping::RunOnly, None)
};
let _ = KEEPING.set(keeping);
log::info!("cookies: {keeping:?}");
keeping
eprintln!("cookies: {keeping:?}");
cookies
}
#[cfg(test)]
mod tests {
use super::*;
const JAR: &[u8] = br#"{"version":1,"cookies_map":{"example.com":[]},"max_per_host":150}"#;
fn temp_dir(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("nacre-cookies-{name}-{}", util::random_hex(6)));
std::fs::create_dir_all(&dir).unwrap();
dir
}
fn cookie(name: &str, expiry: i64) -> Cookie {
Cookie { name: name.into(), value: format!("secret-{name}"), host: ".example.com".into(), path: "/".into(), expiry, secure: true, http_only: true, same_site: 1 }
}
#[test]
fn round_trip() {
let dir = temp_dir("round");
let key = [7u8; 32];
let (store, initial) = CookieStore::open(&dir, &dir.join(PLAIN_FILE), key);
let (store, initial) = CookieStore::open(&dir, key);
assert!(initial.is_none());
assert!(store.save(JAR));
assert!(!store.save(JAR), "unchanged jar is not written again");
let jar = vec![cookie("a", 4_000_000_000)];
assert!(store.save(&jar));
assert!(!store.save(&jar), "unchanged cookies are not written again");
let bytes = std::fs::read(dir.join(FILE)).unwrap();
assert!(!bytes.windows(11).any(|w| w == b"example.com"), "no plain text on disk");
assert!(!bytes.windows(8).any(|w| w == b"secret-a"), "no plain text on disk");
assert!(decrypt(&[8u8; 32], &bytes).is_none(), "unreadable without the key");
let (_, initial) = CookieStore::open(&dir, &dir.join(PLAIN_FILE), key);
assert_eq!(initial.as_deref(), Some(JAR));
let (_, initial) = CookieStore::open(&dir, key);
assert_eq!(initial, Some(jar));
store.close();
assert!(!store.save(b"{}"), "nothing after the exit save");
assert!(!store.save(&[]), "nothing after the last seal");
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn migrates_plain_jar() {
let dir = temp_dir("migrate");
let plain = dir.join(PLAIN_FILE);
std::fs::write(&plain, JAR).unwrap();
let (store, initial) = CookieStore::open(&dir, &plain, [1u8; 32]);
assert_eq!(initial.as_deref(), Some(JAR));
assert!(plain.exists(), "plain jar kept until the encrypted copy is saved");
assert!(store.save(JAR));
assert!(!plain.exists());
fn database_round_trip() {
let dir = temp_dir("db");
let db = dir.join(DB);
let now = util::now() as i64;
write_db(&db, &[cookie("live", now + 3600), cookie("old", now - 10)]).unwrap();
assert_eq!(read_db(&db).unwrap(), vec![cookie("live", now + 3600)], "expired cookies are not sealed");
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn wrong_key_moves_file_aside() {
fn open_fills_database_and_finish_seals() {
let (data, tmp) = (temp_dir("data"), temp_dir("tmp").join("nacre-Default"));
let key = [3u8; 32];
let later = util::now() as i64 + 3600;
CookieStore::open(&data, key).0.save(&[cookie("a", later)]);
let cookies = open(&data, &tmp, key).unwrap();
assert_eq!(read_db(cookies.db()).unwrap(), vec![cookie("a", later)]);
// WebKit adds a cookie; the last run's database wins over the sealed file at the next start.
rusqlite::Connection::open(cookies.db()).unwrap().execute("INSERT INTO moz_cookies VALUES (NULL, 'b', 'v', 'x.org', '/', ?1, NULL, 0, 0, 0)", [later]).unwrap();
assert_eq!(open(&data, &tmp, key).unwrap().db(), cookies.db());
assert_eq!(read_db(cookies.db()).unwrap().len(), 2);
cookies.finish(false);
assert!(!tmp.exists(), "tmpfs folder removed");
assert_eq!(CookieStore::open(&data, key).1.map(|c| c.len()), Some(2));
let cookies = open(&data, &tmp, key).unwrap();
cookies.finish(true);
assert_eq!(CookieStore::open(&data, key).1, Some(vec![]), "cleared at quit");
let _ = std::fs::remove_dir_all(data);
}
#[test]
fn converts_servo_jar() {
let jar = br#"{"cookies_map":{"example.com":[
{"cookie":"session=abc; Path=/app; Domain=example.com; Secure; HttpOnly; SameSite=Strict","host_only":true,"persistent":true,
"creation_time":{"secs_since_epoch":1,"nanos_since_epoch":0},"last_access":{"secs_since_epoch":1,"nanos_since_epoch":0},
"expiry_time":{"secs_since_epoch":4000000000,"nanos_since_epoch":0}},
{"cookie":"wide=1; Domain=example.com","host_only":false,"persistent":true,"expiry_time":{"secs_since_epoch":4000000000,"nanos_since_epoch":0}},
{"cookie":"temp=1; Domain=example.com","host_only":true,"persistent":false,"expiry_time":null}]},"max_per_host":150}"#;
let cookies = parse_sealed(jar).unwrap();
assert_eq!(cookies.len(), 2, "session cookies dropped");
let s = cookies.iter().find(|c| c.name == "session").unwrap();
assert_eq!((s.value.as_str(), s.host.as_str(), s.path.as_str(), s.secure, s.http_only, s.same_site, s.expiry), ("abc", "example.com", "/app", true, true, 2, 4_000_000_000));
assert_eq!(cookies.iter().find(|c| c.name == "wide").unwrap().host, ".example.com");
assert!(parse_sealed(b"{}").is_none());
}
#[test]
fn unreadable_file_moves_aside() {
let dir = temp_dir("aside");
let (store, _) = CookieStore::open(&dir, &dir.join(PLAIN_FILE), [1u8; 32]);
store.save(JAR);
let (_, initial) = CookieStore::open(&dir, &dir.join(PLAIN_FILE), [2u8; 32]);
CookieStore::open(&dir, [1u8; 32]).0.save(&[cookie("a", 4_000_000_000)]);
let (_, initial) = CookieStore::open(&dir, [2u8; 32]);
assert!(initial.is_none());
assert!(!dir.join(FILE).exists());
let aside: Vec<_> = std::fs::read_dir(&dir).unwrap().flatten().filter(|e| e.file_name().to_string_lossy().starts_with("cookies-unreadable-")).collect();
assert_eq!(aside.len(), 1, "the unreadable file is kept");
std::fs::write(dir.join(FILE), encrypt(&[1u8; 32], b"not json")).unwrap();
assert!(CookieStore::open(&dir, [1u8; 32]).1.is_none());
let aside = std::fs::read_dir(&dir).unwrap().flatten().filter(|e| e.file_name().to_string_lossy().starts_with("cookies-unreadable-")).count();
assert!(aside >= 1, "unreadable files are kept");
let _ = std::fs::remove_dir_all(dir);
}
}

View file

@ -1,7 +1,7 @@
# Integrations pass (S009): spell check. Offline: a tiny en_US hunspell dictionary (tests/smoke/data/dict) is copied
# into the throwaway cache first. Run:
# h=target/smoke/integ-spell-home; rm -rf $h; mkdir -p $h/.cache/nacre-servo/dictionaries
# cp tests/smoke/data/dict/en_US.* $h/.cache/nacre-servo/dictionaries/
# h=target/smoke/integ-spell-home; rm -rf $h; mkdir -p $h/.cache/nacre-browser/dictionaries
# cp tests/smoke/data/dict/en_US.* $h/.cache/nacre-browser/dictionaries/
# python3 -m http.server 8768 --bind 127.0.0.1 --directory tests/smoke/pages &
# SMOKE_HOME=$PWD/$h tools/smoke.sh tests/smoke/integ-spell.txt target/smoke/integ-spell
# Read spell-menu.png: the page menu over the misspelled word lists "mistake" and "Add ... to the dictionary".

View file

@ -3,7 +3,7 @@
# (no chip moves). Needs the hidden tall layout (drag positions): SMOKE_SIZE=1280x1600, no SMOKE_VISIBLE.
# Expect: drag-held shows the 125 % label over the handle and the page still at 100 %; released shows the page at
# 125 %; chip-picked (back at 100 %) has Vibrant checked and no chip moved; contrast-held shows the scheme and the
# "Medium" label changed while held. home/.config/nacre-servo/Default/settings.json ends with ui.scale 1.0.
# "Medium" label changed while held. home/.config/nacre-browser/Default/settings.json ends with ui.scale 1.0.
wait 3
resize 1280 1560
set /theme/mode "light"

View file

@ -3,7 +3,7 @@
# CSV export has the login. Usage: tests/smoke/stores-vault-check.sh <outdir>
set -eu
out=${1:?outdir}
data=$out/home/.local/share/nacre-servo/Default
data=$out/home/.local/share/nacre-browser/Default
fail=0
for secret in s3cret-Pa55 alice 127.0.0.1 'Tr0ub4dor' carol; do
if grep -q -- "$secret" "$data/vault.json"; then echo "FAIL: vault.json contains '$secret'"; fail=1; fi