255 lines · 13.7 KB · RustRaw
//! Rows recovered into a local SQLite file land on the object sealed, over//! HTTP against a stub that keeps `import_rows`' rules: parents first, every//! sealed row sealed with its tokens, a reaction's telling id keyed, nothing//! sent in the clear, a cut run resumed, and every landed row read back and//! opened to the file's columns. Synthetic key and rows only.//!//! cargo test -p cotton-mac --test seal_landmod support;use std::collections::BTreeMap;use std::sync::{Arc, Mutex};use cotton_core::seal::DataKey;use cotton_mac::object::ObjectClient;use cotton_mac::seal_land::{land, open_file, open_progress, report, LandOptions};use rusqlite::{params, Connection};use serde_json::{json, Map, Value};use support::{Answer, Request, TestServer};const DB: &str = "db-synthetic-seal-land";const SECRET: &str = "marigold";const PHONE: &str = "15550100777";#[derive(Default)]struct Object { version: i64, rows: BTreeMap<(String, String), (i64, Map<String, Value>)>, /// Refuse the Nth import_rows call (1-based), once. fail_call: Option<usize>, calls: usize, /// When a row the object holds last changed, where the test says. stamped: BTreeMap<(String, String), String>,}fn sealed_clear(table: &str) -> &'static [&'static str] { match table { "thread" => &["last_message_at", "kind"], "message" => &["thread_id", "sent_at", "channel"], "message_reaction" => &["thread_id", "message_id"], _ => &[], }}fn definitions() -> Value { json!({"business": {"database_id": DB}, "tables": [ {"id": "thread", "columns": [{"key": "last_message_at", "type": "date"}, {"key": "kind", "type": "choice"}, {"key": "title", "type": "text"}], "seal": {"clear": ["last_message_at", "kind"], "blind": ["title"]}}, {"id": "message", "columns": [{"key": "thread_id", "type": "link", "link_to": "thread"}, {"key": "sent_at", "type": "date"}, {"key": "channel", "type": "choice"}, {"key": "body", "type": "longtext"}, {"key": "external_id", "type": "text"}], "seal": {"clear": ["thread_id", "sent_at", "channel"], "blind": ["body"], "blind_exact": ["external_id"]}}, {"id": "message_reaction", "columns": [{"key": "thread_id", "type": "link", "link_to": "thread"}, {"key": "message_id", "type": "link", "link_to": "message"}, {"key": "actor", "type": "text"}, {"key": "emoji", "type": "text"}], "seal": {"clear": ["thread_id", "message_id"]}}, {"id": "todo", "columns": [{"key": "title", "type": "text"}]}, {"id": "seal_key", "columns": [{"key": "v", "type": "number"}]} ]})}fn handle(object: &Mutex<Object>, request: &Request) -> Answer { let mut o = object.lock().unwrap(); let route = request.path.split('?').next().unwrap_or(""); let q: BTreeMap<String, String> = request .path .split_once('?') .map(|(_, q)| url::form_urlencoded::parse(q.as_bytes()).into_owned().collect()) .unwrap_or_default(); match (request.method.as_str(), route) { ("GET", "/v1/definitions") => Answer::json(200, definitions()), ("GET", "/v1/sync") => { let table = q.get("tables").cloned().unwrap_or_default(); let rows: Vec<Value> = o .rows .iter() .filter(|((t, _), _)| *t == table) .map(|((t, id), (v, data))| { let mut row = json!({"table": t, "id": id, "version": v, "data": data}); if let Some(at) = o.stamped.get(&(t.clone(), id.clone())) { row["updated_at"] = json!(at); } row }) .collect(); Answer::json(200, json!({"version": o.version, "rows": rows})) } ("POST", "/v1/act") => { let body = request.json(); assert_eq!(body["act"], "import_rows"); o.calls += 1; if o.fail_call == Some(o.calls) { o.fail_call = None; return Answer::json(503, json!({"code": "busy", "message": "try again"})); } let rows = body["args"]["rows"].as_array().unwrap().clone(); assert!(rows.len() <= 500); for row in &rows { let table = row["table"].as_str().unwrap().to_string(); let id = row["id"].as_str().unwrap().to_string(); let data = row["data"].as_object().unwrap().clone(); // The object's rules: a sealed row comes sealed, no sealed column clear, tokens only beside a seal. if table != "todo" { assert!(data.contains_key("sealed_enc") && data.contains_key("dek_enc"), "{table}/{id} came unsealed"); for k in data.keys() { assert!(["sealed_enc", "dek_enc", "seal_v"].contains(&k.as_str()) || sealed_clear(&table).contains(&k.as_str()), "{table}/{id}: {k} in the clear"); } } // Parents first: a link names a row the object holds. for (col, parent) in [("thread_id", "thread"), ("message_id", "message")] { if let Some(p) = data.get(col).and_then(Value::as_str) { assert!(o.rows.contains_key(&(parent.to_string(), p.to_string())), "{table}/{id} links {parent}/{p} before it landed"); } } o.version += 1; let v = o.version; o.rows.insert((table, id), (v, data)); } Answer::json(200, json!({"made": {}, "changed": {}})) } _ => Answer::json(404, json!({"code": "not_found", "message": request.path})), }}fn recovered(path: &std::path::Path) { let conn = Connection::open(path).unwrap(); conn.execute_batch( "CREATE TABLE rows (table_id TEXT NOT NULL, id TEXT NOT NULL, data TEXT NOT NULL, created_at TEXT, updated_at TEXT, deleted INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (table_id, id));", ) .unwrap(); let put = |table: &str, id: &str, data: Value, deleted: i64| { conn.execute("INSERT INTO rows VALUES (?1, ?2, ?3, '2026-11-01T00:00:00Z', '2026-11-01T00:00:00Z', ?4)", params![table, id, data.to_string(), deleted]).unwrap(); }; // Children written first in the file: the verb orders by links, not by the file. for i in 0..7 { put("message", &format!("00000000-0000-4000-8000-00000000000{i}"), json!({"thread_id": "11111111-1111-4111-8111-111111111111", "sent_at": format!("2026-11-01T0{i}:00:00Z"), "channel": "whatsapp", "body": format!("{SECRET} note {i}"), "external_id": format!("wa-{i}"), "a_former_column": "kept here"}), 0); } put("message", "00000000-0000-4000-8000-0000000000ff", json!({"thread_id": "11111111-1111-4111-8111-111111111111", "sent_at": "2026-11-01T09:00:00Z", "channel": "whatsapp", "body": "gone"}), 1); put("message_reaction", &format!("react:00000000-0000-4000-8000-000000000001:{PHONE}"), json!({"thread_id": "11111111-1111-4111-8111-111111111111", "message_id": "00000000-0000-4000-8000-000000000001", "actor": PHONE, "emoji": "👍"}), 0); put("thread", "11111111-1111-4111-8111-111111111111", json!({"last_message_at": "2026-11-01T06:00:00Z", "kind": "dm", "title": format!("{SECRET} family")}), 0);}fn setup(fail_call: Option<usize>) -> (Arc<Mutex<Object>>, TestServer, tempfile::TempDir, ObjectClient) { let mut o = Object { fail_call, ..Object::default() }; o.version = 1; o.rows.insert(("seal_key".into(), "v:message".into()), (1, json!({"v": 2}).as_object().unwrap().clone())); let state = Arc::new(Mutex::new(o)); let server = TestServer::start({ let state = Arc::clone(&state); move |request| handle(&state, request) }); let dir = tempfile::tempdir().unwrap(); recovered(&dir.path().join("recovered.db")); let client = ObjectClient::new(server.url.clone(), Some("device-credential".into())).unwrap(); (state, server, dir, client)}/// RULE: every recovered row of a sealed table lands sealed, parents first,/// in batches, with a telling id keyed; nothing leaves in the clear; the run/// reads every row back and opens it to the file's columns.#[test]fn recovered_rows_land_sealed_and_read_back_whole() { let (state, server, dir, client) = setup(None); let file = open_file(&dir.path().join("recovered.db")).unwrap(); let progress = open_progress(&dir.path().join("landed.db")).unwrap(); let dk = DataKey::from_bytes([9; 32]); let options = LandOptions { batch: 3, ..LandOptions::default() }; let runs = land(&client, &file, &progress, DB, &dk, &options).expect("a run"); let order: Vec<&str> = runs.iter().map(|r| r.table.as_str()).collect(); assert_eq!(order, ["thread", "message", "message_reaction"]); for r in &runs { assert!(r.done(), "{r:?}"); } assert_eq!((runs[1].in_file, runs[1].sent, runs[1].verified), (7, 7, 7), "the deleted row stays behind"); let summary = report(&runs).to_string(); assert!(!summary.contains(SECRET) && !summary.contains(PHONE), "the summary names content"); for request in server.requests() { let body = String::from_utf8_lossy(&request.body); assert!(!body.contains(SECRET) && !body.contains(PHONE) && !body.contains("a_former_column"), "{} {} sent plaintext", request.method, request.path); } let o = state.lock().unwrap(); assert!(o.calls >= 4, "message's 7 rows went in batches of 3: {}", o.calls); let reactions: Vec<&String> = o.rows.keys().filter(|(t, _)| t == "message_reaction").map(|(_, id)| id).collect(); assert_eq!(reactions.len(), 1); assert!(!reactions[0].contains(PHONE) && reactions[0].len() == 36, "the reaction's id was keyed: {}", reactions[0]); assert_eq!(o.rows[&("message".to_string(), "00000000-0000-4000-8000-000000000001".to_string())].1["seal_v"], 2);}/// RULE: a run cut by a refused batch resumes where it stopped and sends no/// landed row again.#[test]fn a_cut_run_resumes_from_its_progress_file() { let (state, server, dir, client) = setup(Some(3)); let file = open_file(&dir.path().join("recovered.db")).unwrap(); let progress = open_progress(&dir.path().join("landed.db")).unwrap(); let dk = DataKey::from_bytes([9; 32]); let options = LandOptions { batch: 3, ..LandOptions::default() }; let cut = land(&client, &file, &progress, DB, &dk, &options).expect_err("the third batch was refused"); assert!(cut.contains("import_rows refused"), "{cut}"); let calls_before = state.lock().unwrap().calls; let again = land(&client, &file, &progress, DB, &dk, &options).expect("resumed"); assert!(again.iter().all(|r| r.done()), "{again:?}"); let message = again.iter().find(|r| r.table == "message").unwrap(); assert_eq!((message.already, message.sent), (3, 4), "{message:?}"); let third = land(&client, &file, &progress, DB, &dk, &options).expect("a third run"); assert!(third.iter().all(|r| r.sent == 0 && r.done())); assert!(state.lock().unwrap().calls > calls_before); drop(server);}/// RULE: a table the object does not seal is refused before anything is/// sent, unless the run says so; a key table is never landed.#[test]fn open_and_key_tables_are_refused_before_any_act() { let (_state, server, dir, client) = setup(None); { let conn = Connection::open(dir.path().join("recovered.db")).unwrap(); conn.execute("INSERT INTO rows VALUES ('todo', 't1', '{\"title\":\"buy\"}', NULL, NULL, 0)", []).unwrap(); conn.execute("INSERT INTO rows VALUES ('seal_key', 'dk', '{\"v\":1}', NULL, NULL, 0)", []).unwrap(); } let file = open_file(&dir.path().join("recovered.db")).unwrap(); let progress = open_progress(&dir.path().join("landed.db")).unwrap(); let dk = DataKey::from_bytes([9; 32]); let refused = land(&client, &file, &progress, DB, &dk, &LandOptions { tables: vec!["todo".into()], ..LandOptions::default() }).expect_err("open"); assert!(refused.starts_with("not_sealed"), "{refused}"); let refused = land(&client, &file, &progress, DB, &dk, &LandOptions::default()).expect_err("key table"); assert!(refused.starts_with("not_imported"), "{refused}"); assert!(server.requests().iter().all(|r| r.method == "GET"), "an act was posted"); let open = land(&client, &file, &progress, DB, &dk, &LandOptions { tables: vec!["todo".into()], allow_open: true, ..LandOptions::default() }).expect("allowed"); assert!(open[0].done() && !open[0].sealed);}/// RULE (STALE WRITES 2, 25 Nov 2026): a recovery file never seals its old copy over a row the object changed since it/// was dumped: that row is kept as the object holds it and counted, and the run is still done.#[test]fn a_row_the_object_changed_since_the_file_was_dumped_is_kept() { let (state, server, dir, client) = setup(None); let thread = ("thread".to_string(), "11111111-1111-4111-8111-111111111111".to_string()); { let mut o = state.lock().unwrap(); o.version += 1; let v = o.version; o.rows.insert(thread.clone(), (v, json!({"sealed_enc": "the phone's", "dek_enc": "x", "seal_v": 2}).as_object().unwrap().clone())); o.stamped.insert(thread.clone(), "2026-11-20T00:00:00Z".into()); } let file = open_file(&dir.path().join("recovered.db")).unwrap(); let progress = open_progress(&dir.path().join("landed.db")).unwrap(); let dk = DataKey::from_bytes([9; 32]); let runs = land(&client, &file, &progress, DB, &dk, &LandOptions::default()).expect("a run"); let threads = runs.iter().find(|r| r.table == "thread").unwrap(); assert_eq!((threads.sent, threads.kept_newer), (0, 1), "{threads:?}"); assert!(threads.done(), "{threads:?}"); assert_eq!(state.lock().unwrap().rows[&thread].1["sealed_enc"], "the phone's", "the object's newer row stands"); drop(server);}