//! Slice 4, the arrival fence widened (note 6.6): on the four mirror tables a //! receipt that names a mirror column as NULL is refused whatever its stamp //! and whatever the row holds on this device — a pure function of the //! receipt, so every device refuses the same receipts in any arrival order and //! a late clear never brings a revoked device, token, grant or credential back //! while its revocation fact stands. //! //! Every row is synthetic and every value invented //! ([nothing-real-ever-goes-in-cotton-s-public-tree]). use cotton_store::actor::{Actor, JobName}; use cotton_store::fold::{fold_ops, fold_pulled, FoldResult, MIRROR_TABLES}; use cotton_store::migrate::migrate_store; use cotton_store::mint::Change; use cotton_store::protocol::hlc::next_hlc; use cotton_store::protocol::types::CottonOp; use cotton_store::wire::op_of_change; use cotton_store::Driver; use rusqlite::types::Value; use serde_json::{json, Map, Value as JsonValue}; const WORKSPACE: &str = "11111111-1111-4111-8111-111111111111"; const NOW: &str = "2026-10-04T09:00:00.000Z"; const REVOKED: &str = "2026-10-04T10:00:00.000Z"; /// The Mac that revokes. const STUDY: &str = "device:01JSTUDYMAC0000000000000000"; /// A device that writes a clear — honest or not, its receipt is the same. const KITCHEN: &str = "device:01JKITCHENMAC000000000000000"; const ROW: &str = "row-1"; const T0: i64 = 1_790_000_000_000; fn text(value: &str) -> Value { Value::Text(value.to_string()) } fn file() -> Driver { let db = Driver::open_in_memory().expect("opens"); migrate_store(&db).expect("migrates"); db.run( "INSERT INTO cotton_workspaces (id, name, owner_user_id, created_at) VALUES (?,?,?,?)", &[text(WORKSPACE), text("A workspace"), text("owner-1"), text(NOW)], ) .expect("the workspace row"); db } fn object(value: JsonValue) -> Map { value.as_object().cloned().expect("an object") } thread_local! { static SCHEMA: Driver = file(); } fn receipt(change: Change, n: u32, author: &str, ms: i64) -> CottonOp { let hlc = next_hlc(author, None, ms).expect("a stamp"); let actor = Actor::device_job(JobName::named("test").expect("a job name")); SCHEMA .with(|db| op_of_change(db, &change, &hlc, author, &actor, format!("op-{n:06}"))) .expect("a receipt") } /// The whole row of `table`, as its honest create names it. fn body(table: &str) -> Map { object(match table { "cotton_devices" => json!({ "workspace_id": WORKSPACE, "device_id": "a-phone-key", "name": "An iPhone", "platform": "ios", "approved_at": NOW, "approved_by_device": "self", "scope": "runner", "takes_placements": false, "created_at": NOW, "updated_at": NOW, }), "cotton_mcp_tokens" => json!({ "workspace_id": WORKSPACE, "owner_user_id": "owner-1", "name": "a token", "token_hash": "0f".repeat(32), "scopes": "[]", "created_at": NOW, }), "cotton_oauth_grants" => json!({ "workspace_id": WORKSPACE, "client_id": "an-invented-client", "client_name": "An invented assistant", "scope": "read", "created_at": NOW, "token_id": "token-row-1", "refresh_generation": 0, }), "cotton_code_credentials" => json!({ "workspace_id": WORKSPACE, "device_id": "device:invented", "name": "the invented mini", "scope": "device", "created_at": NOW, }), other => panic!("not a mirror table: {other}"), }) } fn create(table: &str, n: u32, ms: i64) -> CottonOp { receipt(Change::create(table, ROW, body(table)), n, STUDY, ms) } /// The mirror columns `table` has. fn mirrors(table: &str) -> &'static [&'static str] { if table == "cotton_devices" { &["revoked_at", "revoked_by_device", "revoked_reason"] } else { &["revoked_at"] } } /// The revocation's mirror, as `revoke()` writes it. fn revoke(table: &str, n: u32, ms: i64) -> CottonOp { let mut patch = object(json!({ "revoked_at": REVOKED })); if table == "cotton_devices" { patch.insert("revoked_by_device".into(), json!("study")); patch.insert("revoked_reason".into(), json!("revoked")); } receipt(Change::update(table, ROW, patch), n, STUDY, ms) } /// A change naming `column` as NULL, beside an ordinary field. fn clear(table: &str, column: &str, n: u32, ms: i64) -> CottonOp { let mut patch = object(json!({ column: JsonValue::Null })); if table == "cotton_mcp_tokens" || table == "cotton_oauth_grants" { patch.insert(if table == "cotton_mcp_tokens" { "name" } else { "client_name" }.into(), json!("renamed")); } else { patch.insert("name".into(), json!("renamed")); } receipt(Change::update(table, ROW, patch), n, KITCHEN, ms) } fn mirror_of(db: &Driver, table: &str) -> Vec> { let row = db .get(&format!("SELECT * FROM {table} WHERE id = ?"), &[text(ROW)]) .expect("reads") .expect("the row"); mirrors(table).iter().map(|column| row.text(column).map(str::to_string)).collect() } /// Every column of the row, as text — what two devices compare. fn whole_row(db: &Driver, table: &str) -> Vec<(String, String)> { let row = db .get(&format!("SELECT * FROM {table} WHERE id = ?"), &[text(ROW)]) .expect("reads") .expect("the row"); row.columns().iter().map(|(column, value)| (column.clone(), format!("{value:?}"))).collect() } type Fold = fn(&Driver, &[CottonOp]) -> cotton_store::Result; /// Fold `ops` one at a time, answering every refusal. fn one_by_one(db: &Driver, fold: Fold, ops: &[CottonOp]) -> Vec { let mut refused = Vec::new(); for op in ops { let result = fold(db, std::slice::from_ref(op)).expect("folds"); refused.extend(result.rejected.into_iter().map(|r| format!("{}: {}", r.op_id, r.reason))); } refused } fn revoked_mirror(table: &str) -> Vec> { if table == "cotton_devices" { vec![Some(REVOKED.into()), Some("study".into()), Some("revoked".into())] } else { vec![Some(REVOKED.into())] } } /// RULE: A receipt that changes a device, MCP token, grant or code credential row and names a mirror column as NULL is refused on every device, whatever its stamp, the row's state or the arrival order, so a revoke is never cleared. #[test] fn arriving_receipt_that_clears_a_mirror_is_refused() { for table in MIRROR_TABLES { for column in mirrors(table) { // The clear stamped ABOVE the revoke, so last-writer-wins alone // would land it; then the clear arriving BEFORE the revoke, on a // row still live here; each pushed and pulled. let orders: [Vec; 2] = [ vec![create(table, 1, T0), revoke(table, 2, T0 + 1_000), clear(table, column, 3, T0 + 9_000)], vec![create(table, 1, T0), clear(table, column, 3, T0 + 9_000), revoke(table, 2, T0 + 1_000)], ]; for (how, fold) in [("pushed", fold_ops as Fold), ("pulled", fold_pulled as Fold)] { for ops in &orders { let db = file(); let refused = one_by_one(&db, fold, ops); assert_eq!(refused.len(), 1, "{how} {table}.{column}: refused {refused:?}"); assert!( refused[0].starts_with("op-000003: a revoked row is not un-revoked by a patch"), "{how} {table}.{column}: the clear is refused by the fence, got {refused:?}" ); assert_eq!(mirror_of(&db, table), revoked_mirror(table), "{how} {table}.{column}: the revoke stands"); } } } } } /// RULE: Two devices that get a mirror's clear and its revoke in opposite orders end with the same row, revoked: the fence refuses the clear on both, so neither keeps a value the other refused. #[test] fn clearing_receipt_arriving_before_the_revoke_ends_equal_on_every_device() { for table in MIRROR_TABLES { for column in mirrors(table) { let first = file(); let second = file(); one_by_one( &first, fold_ops, &[create(table, 1, T0), revoke(table, 2, T0 + 1_000), clear(table, column, 3, T0 + 9_000)], ); one_by_one( &second, fold_ops, &[create(table, 1, T0), clear(table, column, 3, T0 + 9_000), revoke(table, 2, T0 + 1_000)], ); assert_eq!(whole_row(&first, table), whole_row(&second, table), "{table}.{column}"); assert_eq!(mirror_of(&first, table), revoked_mirror(table), "{table}.{column}"); } } } /// A create of the row naming `column` as NULL, as no honest mint makes it /// (`mint` drops a create's NULL mirror) — a forged receipt, by `author`. fn forged_create(table: &str, column: &str, n: u32, author: &str, ms: i64) -> CottonOp { let honest = receipt(Change::create(table, ROW, body(table)), n, author, ms); let mut forged = cotton_store::canonical::decode(honest.receipt.as_bytes()).expect("decodes"); forged.fields.insert(column.to_string(), JsonValue::Null); cotton_store::wire::from_receipt(honest.op_id, &forged).expect("an op") } /// RULE: A create receipt naming a mirror column as NULL is refused on every device, so a re-create or premint stamped above a revoke never clears it, whichever of the two arrives first. #[test] fn create_naming_a_null_mirror_never_clears_a_revocation_in_either_order() { for table in MIRROR_TABLES { for column in mirrors(table) { let orders: [Vec; 2] = [ vec![create(table, 1, T0), revoke(table, 2, T0 + 1_000), forged_create(table, column, 3, KITCHEN, T0 + 9_000)], vec![create(table, 1, T0), forged_create(table, column, 3, KITCHEN, T0 + 9_000), revoke(table, 2, T0 + 1_000)], ]; for (how, fold) in [("pushed", fold_ops as Fold), ("pulled", fold_pulled as Fold)] { let mut rows = Vec::new(); for ops in &orders { let db = file(); let refused = one_by_one(&db, fold, ops); assert_eq!(refused.len(), 1, "{how} {table}.{column}: refused {refused:?}"); assert!( refused[0].starts_with("op-000003: a revoked row is not un-revoked by a patch"), "{how} {table}.{column}: the create is refused by the fence, got {refused:?}" ); assert_eq!(mirror_of(&db, table), revoked_mirror(table), "{how} {table}.{column}: the revoke stands"); rows.push(whole_row(&db, table)); } assert_eq!(rows[0], rows[1], "{how} {table}.{column}: both orders end equal"); } } } } fn retract(table: &str, n: u32, ms: i64) -> CottonOp { receipt(Change::retract(table, ROW), n, KITCHEN, ms) } /// RULE: A receipt that sets a mirror outlives a newer retract of its row whenever it arrives: one arriving after the retract is stored, not dropped as an earlier life's write, so a re-create comes back revoked on every device. #[test] fn a_mirror_arriving_after_a_newer_retract_still_outlives_it() { for table in MIRROR_TABLES { let born = create(table, 1, T0); let revoked = revoke(table, 2, T0 + 1_000); let gone = retract(table, 3, T0 + 2_000); let again = create(table, 4, T0 + 3_000); let orders: [Vec; 3] = [ vec![born.clone(), revoked.clone(), gone.clone(), again.clone()], vec![born.clone(), gone.clone(), again.clone(), revoked.clone()], vec![again.clone(), gone.clone(), revoked.clone(), born.clone()], ]; let mut rows = Vec::new(); for ops in &orders { let db = file(); let refused = one_by_one(&db, fold_ops, ops); assert!(refused.is_empty(), "{table}: refused {refused:?}"); assert_eq!(mirror_of(&db, table), revoked_mirror(table), "{table}: the re-created row is revoked"); rows.push(whole_row(&db, table)); } assert!(rows.windows(2).all(|pair| pair[0] == pair[1]), "{table}: every order ends equal"); } }