189 lines · 8.8 KB · RustRaw
//! The Mac's seal migration over HTTP against a stub object that keeps the//! Worker's migration rules (apps/business/src/seal_migration.ts): the Mac//! reads the sealed tables from the definitions, learns the seal versions,//! stages, reads the twins back, commits, purges, and keeps each table's//! progress in importer.db. Synthetic key and rows only.//!//! cargo test -p cotton-mac --test seal_migratemod support;use std::collections::BTreeMap;use std::sync::{Arc, Mutex};use cotton_client::seal::{DataKeyStore, HeldDataKeys, Sealer};use cotton_core::seal::DataKey;use cotton_mac::object::ObjectClient;use cotton_mac::seal_migrate::{report, run, StoreProgress};use cotton_mac::store::Store;use serde_json::{json, Map, Value};use support::{Answer, Request, TestServer};const DB: &str = "db-synthetic-mac-seal";const SECRET: &str = "tamarind";#[derive(Default)]struct Object { version: i64, rows: BTreeMap<(String, String), (i64, Map<String, Value>)>, twins: BTreeMap<String, (String, String, i64, Value, Value)>, purged: Vec<String>,}impl Object { fn put(&mut self, table: &str, id: &str, data: Value) { self.version += 1; self.rows.insert((table.into(), id.into()), (self.version, data.as_object().cloned().unwrap())); }}fn query(path: &str) -> BTreeMap<String, String> { let Some((_, q)) = path.split_once('?') else { return BTreeMap::new() }; url::form_urlencoded::parse(q.as_bytes()).into_owned().collect()}fn seals(column: &str) -> bool { !["day", "keep_open", "id"].contains(&column)}fn handle(object: &Mutex<Object>, request: &Request) -> Answer { let mut o = object.lock().unwrap(); let route = request.path.split('?').next().unwrap_or(""); let q = query(&request.path); match (request.method.as_str(), route) { ("GET", "/v1/definitions") => Answer::json( 200, json!({"business": {"database_id": DB}, "tables": [ {"id": "jot", "columns": [{"key": "day", "type": "date"}, {"key": "text", "type": "longtext"}, {"key": "keep_open", "type": "boolean"}], "seal": {"clear": ["day", "keep_open"], "blind": ["text"]}}, {"id": "todo", "columns": [{"key": "title", "type": "text"}]} ]}), ), ("GET", "/v1/sync") => { let since: i64 = q.get("since").and_then(|s| s.parse().ok()).unwrap_or(0); let table = q.get("tables").cloned().unwrap_or_default(); let rows: Vec<Value> = o .rows .iter() .filter(|((t, _), (v, _))| *t == table && *v > since) .map(|((t, id), (v, data))| json!({"table": t, "id": id, "version": v, "data": data})) .collect(); Answer::json(200, json!({"version": o.version, "rows": rows})) } ("GET", "/v1/seal/twins") => { let names: Vec<&str> = q.get("twins").map(|s| s.split(',').collect()).unwrap_or_default(); let twins: Vec<Value> = names .iter() .filter_map(|n| o.twins.get(*n).map(|(_, id, v, data, blind)| json!({"twin": n, "id": id, "expect_version": v, "data": data, "blind": blind}))) .collect(); Answer::json(200, json!({"twins": twins})) } ("POST", "/v1/act") => { let body = request.json(); let args = &body["args"]; let table = args["table"].as_str().unwrap().to_string(); match body["act"].as_str().unwrap() { "seal_stage" => { let mut staged = Vec::new(); for row in args["rows"].as_array().unwrap() { let id = row["id"].as_str().unwrap().to_string(); let twin = format!("twin-{id}"); o.twins.insert(twin.clone(), (table.clone(), id.clone(), row["expect_version"].as_i64().unwrap(), row["data"].clone(), row["blind"].clone())); staged.push(json!({"id": id, "twin": twin})); } Answer::json(200, json!({"staged": staged, "left": []})) } "seal_commit" => { let mut sealed = Vec::new(); for name in args["twins"].as_array().unwrap() { let (t, id, _, data, _) = o.twins.remove(name.as_str().unwrap()).unwrap(); let (_, held) = o.rows[&(t.clone(), id.clone())].clone(); let mut next: Map<String, Value> = held.into_iter().filter(|(k, _)| !seals(k)).collect(); next.extend(data.as_object().unwrap().clone()); o.put(&t, &id, Value::Object(next)); sealed.push(json!(id)); } Answer::json(200, json!({"sealed": sealed, "left": []})) } "seal_purge" => { o.purged.push(table.clone()); Answer::json(200, json!({"table": table, "scrubbed": 2})) } other => Answer::json(400, json!({"code": "no_such_act", "message": other})), } } _ => Answer::json(404, json!({"code": "not_found", "message": request.path})), }}fn object() -> Arc<Mutex<Object>> { let mut o = Object::default(); o.put("seal_key", "v:jot", json!({"v": 3})); for i in 0..12 { o.put("jot", &format!("j-{i}"), json!({"day": "2026-11-11", "text": format!("{SECRET} line {i}")})); } o.put("jot", "kept", json!({"day": "2026-11-11", "text": "kept", "keep_open": true})); Arc::new(Mutex::new(o))}/// RULE (§7 step 3, Q21): the Mac migrates every sealed table the object/// defines through verified twins, keeps each table's progress in/// importer.db, sends no sealed text in the clear, and a second run resumes/// past what the first read, sealing nothing.#[test]fn the_mac_migrates_each_sealed_table_and_keeps_its_progress() { let state = object(); let server = TestServer::start({ let state = Arc::clone(&state); move |request| handle(&state, request) }); let dir = tempfile::tempdir().unwrap(); let store = Store::open(&dir.path().join("importer.db")).unwrap(); let client = ObjectClient::new(server.url.clone(), Some("device-credential".into())).unwrap(); let dk = DataKey::from_bytes([4; 32]); let runs = run(&client, &store, DB, &dk, &[]).expect("a run"); assert_eq!(runs.len(), 1, "only the sealed table"); assert_eq!((runs[0].table.as_str(), runs[0].sealed, runs[0].kept_open, runs[0].done), ("jot", 12, 1, true)); assert_eq!(state.lock().unwrap().purged, ["jot"]); let summary = report(&runs).to_string(); assert!(!summary.contains(SECRET), "the summary names content"); // Nothing the Mac sent held the secret in the clear. for request in server.requests() { assert!(!String::from_utf8_lossy(&request.body).contains(SECRET), "{} {} sent plaintext", request.method, request.path); } // Every row opens under the version the object holds, to what it held. let keys = HeldDataKeys::new(); keys.hold(DB, &dk); let sealer = Sealer::new(DB, keys as Arc<dyn DataKeyStore>); for i in 0..12 { let (_, data) = state.lock().unwrap().rows[&("jot".to_string(), format!("j-{i}"))].clone(); assert_eq!(data["seal_v"], 3); assert_eq!(sealer.open("jot", &format!("j-{i}"), &data).unwrap()["text"], json!(format!("{SECRET} line {i}"))); } // importer.db holds where the table got to; the next run reads from there. let since = store.cursor(&StoreProgress::source("jot")).unwrap().expect("kept"); let before = server.requests().len(); let again = run(&client, &store, DB, &dk, &["jot".to_string()]).expect("again"); assert_eq!((again[0].sealed, again[0].done), (0, true)); let syncs: Vec<String> = server.requests()[before..].iter().filter(|r| r.path.starts_with("/v1/sync") && r.path.contains("tables=jot")).map(|r| r.path.clone()).collect(); assert!(!syncs.is_empty() && syncs.iter().all(|p| p.contains(&format!("since={since}"))), "{syncs:?}");}/// RULE: a table the object does not seal is refused before anything is sent.#[test]fn a_table_the_object_does_not_seal_is_refused_before_any_act() { let state = object(); let server = TestServer::start({ let state = Arc::clone(&state); move |request| handle(&state, request) }); let dir = tempfile::tempdir().unwrap(); let store = Store::open(&dir.path().join("importer.db")).unwrap(); let client = ObjectClient::new(server.url.clone(), Some("device-credential".into())).unwrap(); let refused = run(&client, &store, DB, &DataKey::from_bytes([4; 32]), &["todo".to_string()]).expect_err("refused"); assert!(refused.starts_with("not_sealed"), "{refused}"); assert!(server.requests().iter().all(|r| r.method == "GET"), "an act was posted");}