//! Groundwork slices 5b-i and 5b-ii: nothing but `revocation::revoke` writes//! a revocation mirror — `revoked_at`, and on `cotton_devices` also//! `revoked_by_device` and `revoked_reason` — on the four replicated tables//! that carry one. Two halves: `mint` refuses at run time any change naming a//! mirror that is not beside its fact, whatever the actor, and a scan of//! `crates/*/src` refuses any call site but the writer's own.//!//! Every row is synthetic ([nothing-real-ever-goes-in-cotton-s-public-tree]).use std::collections::BTreeSet;use std::path::{Path, PathBuf};use cotton_store::actor::{Actor, DeviceId, JobName, RunId};use cotton_store::fixtures::{file_at_version, seed_workspace_row, NOW, OWNER, WORKSPACE};use cotton_store::meta::{seed_meta, Meta};use cotton_store::mint::{changes_of, first_author, mint, Act, AuthorReason, Change, Clock, Held, History, IdSource};use cotton_store::outbox::LocalChange;use cotton_store::receipts::MIRROR_COLUMNS;use cotton_store::revocation::{revoke, RevokeAct, SUBJECT_TABLES};use cotton_store::schema::ddl::SCHEMA_VERSION;use cotton_store::Driver;use serde_json::{json, Map, Value};const DEVICE: &str = "device:01JTESTDEVICE000000000000000";constT0: i64 = 1_759_480_000_000;const ROW: &str = "device-row-1";const LATER: &str = "2026-10-02T09:00:00.000Z";structIds(u32);implIdSourceforIds {fn next_op_id(&mutself, _now_ms: i64) -> cotton_store::Result<String> {self.0 += 1;Ok(format!("op-{:04}", self.0)) }}fn fresh() -> Driver {let db = file_at_version(SCHEMA_VERSION); seed_meta( &db, &Meta { workspace_id: WORKSPACE.to_string(), owner_id: OWNER.to_string(), device_id: DEVICE.to_string(), last_server_seq: 0, last_hlc: None, }, SCHEMA_VERSION, ) .expect("seeds the identity"); seed_workspace_row(&db); first_author(&db, "key-of-this-device", None, AuthorReason::First, &Clock::wall(T0 - 1), &mutIds(900), Held::Served) .expect("the file's author"); db}fn object(value: Value) -> Map<String, Value> { value.as_object().expect("an object").clone()}fn job() -> Actor {Actor::job(JobName::named("devices").expect("a job name"))}fn write(db: &Driver, step: i64, changes: Vec<Change>) -> cotton_store::Result<()> { mint( db, &Act { actor: job(), verb: "test_write".to_string(), history: History::None, changes, }, &Clock::wall(T0 + step * 1_000), &mutIds(step as u32 * 100),Held::Served, ) .map(|_| ())}/// A device's birth, naming its mirror as NULL the way `birth_patch` does.fn born(db: &Driver) { write( db,1, vec![Change::create("cotton_devices", ROW, object(json!({"id": ROW,"workspace_id": WORKSPACE,"device_id": "a-synthetic-device-key","name": "An invented iPhone","scope": "runner", "takes_placements": false,"platform": "ios","approved_at": NOW,"approved_by_device": "self","revoked_at": null,"revoked_by_device": null,"revoked_reason": null,"created_at": NOW,"updated_at": NOW, })), )], ) .expect("a create naming a NULL mirror is accepted");}/// What `revoke` puts in an act for the device row.fn revocation(db: &Driver, at: &str) -> Vec<Change> {letmut changes: Vec<LocalChange> = Vec::new();letmut n = 0;letmut new_id = move || { n += 1; format!("fact-{at}-{n}") }; revoke( &mutRevokeAct { db, changes: &mut changes, workspace_id: WORKSPACE, actor: &job().to_wire(), by: "a-synthetic-revoker-key", at, new_id: &mut new_id, },"cotton_devices", ROW,"revoked",None,None, ) .expect("revoke queues its fact and mirror"); changes_of(db, &changes)}fn mirror(db: &Driver) -> Option<String> { db.get("SELECT revoked_at FROM cotton_devices WHERE id = ?", &[rusqlite::types::Value::Text(ROW.into())]) .expect("reads") .and_then(|row| row.text("revoked_at").map(str::to_string))}fn naming(column: &str, value: Value) -> Change {letmut patch = Map::new(); patch.insert(column.to_string(), value);Change::update("cotton_devices", ROW, patch)}/// RULE: mint refuses a change naming a revocation mirror unless revoke() wrote it beside its cotton_revocations fact for that row and moment, so a mirror never says revoked where no fact does.#[test]fn a_change_naming_a_mirror_is_refused_unless_revoke_wrote_it() {let db = fresh(); born(&db);for column in MIRROR_COLUMNS {let refused = write(&db, 2, vec![naming(column, json!(NOW))]); assert!(refused.is_err(), "a plain change naming {column} was minted"); }// A fact for ANOTHER row, or at another moment, does not carry the mirror.letmut forged = revocation(&db, NOW);for change in &mut forged {if change.table == "cotton_revocations" { change .patch .as_mut() .expect("a fact names its columns") .insert("revoked_at".into(), json!(LATER)); } } assert!(write(&db, 3, forged).is_err(), "a mirror beside a fact of another moment was minted"); assert_eq!(mirror(&db), None); write(&db, 4, revocation(&db, NOW)).expect("revoke's fact and mirror are minted"); assert_eq!(mirror(&db).as_deref(), Some(NOW));}/// RULE: A revocation mirror once set is never cleared or rewritten by a local write: mint refuses the change, and a later revoke() of the same row adds its fact and leaves the mirror.#[test]fn a_set_mirror_is_never_cleared_or_rewritten() {let db = fresh(); born(&db); write(&db, 2, revocation(&db, NOW)).expect("the revocation"); assert!(write(&db, 3, vec![naming("revoked_at", Value::Null)]).is_err(), "a mirror was cleared"); assert!(write(&db, 4, vec![naming("revoked_reason", Value::Null)]).is_err(), "a reason was cleared"); assert!(write(&db, 5, vec![naming("revoked_at", json!(LATER))]).is_err(), "a mirror was rewritten");let again = revocation(&db, LATER); assert_eq!(again.len(), 1, "a second revoke writes its fact alone"); write(&db, 6, again).expect("the second fact"); assert_eq!(mirror(&db).as_deref(), Some(NOW));}/// RULE: No actor may write a revocation mirror without its fact, the OAuth job, the runner sweep and an owner's device included: mint keeps no allow-list, so every mirror on the four tables is revoke()'s.#[test]fn no_actor_writes_a_mirror_without_its_fact() {let db = fresh(); born(&db);let owner = Actor::owner(DeviceId::in_file(&db, ROW).expect("the device row"));let cases = [ ("cotton_oauth_grants", Actor::job(JobName::named("oauth").expect("a job name"))), ("cotton_oauth_grants", owner.clone()), ("cotton_mcp_tokens", owner.clone()), ("cotton_mcp_tokens", Actor::job(JobName::named("oauth").expect("a job name"))), ("cotton_code_credentials", Actor::job(JobName::named("runner-registrations").expect("a job name"))), ("cotton_devices", owner), ];for (step, (table, actor)) in cases.into_iter().enumerate() {letmut patch = Map::new(); patch.insert("revoked_at".into(), json!(NOW));let refused = mint( &db, &Act { actor: actor.clone(), verb: "test_write".to_string(), history: History::None, changes: vec![Change::update(table, ROW, patch)], }, &Clock::wall(T0 + (10 + step as i64) * 1_000), &mutIds(5_000 + step as u32 * 100),Held::Served, ) .expect_err("a mirror with no fact beside it"); assert!( refused.to_string().contains("only revocation::revoke writes"),"{table} as {}: {refused}", actor.to_wire() ); }}/// RULE: A create may name a revocation mirror only as NULL, which mint drops from the receipt; a create naming a set mirror is refused, except the carry's import bringing a row across as the old file held it.#[test]fn a_create_naming_a_set_mirror_is_refused() {let db = fresh();let refused = write( &db,1, vec![Change::create("cotton_devices", ROW, object(json!({"id": ROW,"workspace_id": WORKSPACE,"device_id": "a-synthetic-device-key","name": "An invented iPhone","platform": "ios","approved_at": NOW,"approved_by_device": "self","revoked_at": NOW,"created_at": NOW,"updated_at": NOW, })), )], ); assert!(refused.is_err(), "a device was born revoked");// The carry's offline import brings a revoked row across as the old file// held it: a revocation the old build wrote stands as it stood.let carried = fresh();let run = RunId::minted(&mutIds(700), T0).expect("a run id"); mint( &carried, &Act { actor: Actor::import(run), verb: "move".to_string(), history: History::None, changes: vec![Change::create("cotton_devices", ROW, object(json!({"id": ROW,"workspace_id": WORKSPACE,"device_id": "a-synthetic-device-key","name": "An invented iPhone","platform": "ios","approved_at": NOW,"approved_by_device": "self","revoked_at": NOW,"revoked_reason": "lost","created_at": NOW,"updated_at": NOW, })), )], }, &Clock::wall(T0 + 1_000), &mutIds(800),Held::Offline, ) .expect("the carry's create of a revoked row is minted"); assert_eq!(mirror(&carried).as_deref(), Some(NOW)); born(&db);let fields: Vec<String> = cotton_store::receipts::of_row(&db, "cotton_devices", ROW) .expect("the receipts") .iter() .flat_map(|stored| stored.receipt.fields.keys().cloned().collect::<Vec<_>>()) .collect(); assert!( fields.iter().all(|field| !MIRROR_COLUMNS.contains(&field.as_str())),"a create's receipt names a mirror: {fields:?}" );}// ─── the scan ──────────────────────────────────────────────────────────────fn crates_root() -> PathBuf { cotton_store::manifest_dir() .parent() .expect("cotton-store sits in the crates directory") .to_path_buf()}/// Every production source file under `crates/*/src`, as (path from `crates/`,/// text with any trailing `#[cfg(test)] mod …` cut off and comments blanked).fn sources() -> Vec<(String, String)> {let root = crates_root();letmut found = Vec::new();letmut crates: Vec<PathBuf> = std::fs::read_dir(&root) .expect("the crates directory") .filter_map(Result::ok) .map(|entry| entry.path().join("src")) .filter(|src| src.is_dir()) .collect(); crates.sort();for src in crates { walk(&src, &root, &mut found); } assert!(found.len() > 200, "the scan found only {} files", found.len()); found}fn walk(dir: &Path, root: &Path, found: &mutVec<(String, String)>) {letOk(entries) = std::fs::read_dir(dir) else {return; };letmut paths: Vec<PathBuf> = entries.filter_map(Result::ok).map(|e| e.path()).collect(); paths.sort();for path in paths {if path.is_dir() { walk(&path, root, found);continue; }let name = path.file_name().and_then(|n| n.to_str()).unwrap_or_default();if !name.ends_with(".rs") || name.ends_with("_tests.rs") || name == "tests.rs" {continue; }letOk(text) = std::fs::read_to_string(&path) else {continue; };let relative = path.strip_prefix(root).unwrap_or(&path).to_string_lossy().replace('\\', "/"); found.push((relative, production_text(&text))); }}fn production_text(text: &str) -> String {let lines: Vec<&str> = text.lines().collect();letmut end = lines.len();for (index, line) in lines.iter().enumerate() {if line.trim() != "#[cfg(test)]" {continue; }let next = lines[index + 1..].iter().find(|l| !l.trim().is_empty());if next.is_some_and(|l| l.trim_start().starts_with("mod ") && l.trim_end().ends_with('{')) { end = index;break; } } lines[..end] .iter() .map(|line| match line.find("//") {Some(at) => &line[..at],None => line, }) .collect::<Vec<_>>() .join("\n")}/// The words of `text` with the line each is on: identifiers, SQL keywords/// and quoted names alike, every other character a separator.fn words(text: &str) -> Vec<(usize, String)> {letmut out = Vec::new();for (index, line) in text.lines().enumerate() {for word in line.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) {if !word.is_empty() { out.push((index + 1, word.to_string())); } } } out}/// The function each line is in: the last `fn <name>` at or above it.fn functions(text: &str) -> Vec<String> {letmut current = String::from("(top)");letmut out = Vec::new();for line in text.lines() {letmut parts = line.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')).filter(|w| !w.is_empty());whileletSome(word) = parts.next() {if word == "fn" {ifletSome(name) = parts.next() { current = name.to_string(); }break; } } out.push(current.clone()); } out}/// Where the store's own code names a mirror column on purpose: the writer/// itself, and the columns and DDL the schema declares.const THE_WRITER: [(&str, &str); 2] = [// The one writer of the mirror. ("cotton-store/src/revocation.rs", "revoke_row"),// The FACT's own `revoked_at` column, on cotton_revocations — no mirror. ("cotton-store/src/revocation.rs", "push_fact"),];/// Every write naming a mirror column in production code: (file, function,/// line). A patch built for a mint names it as `.insert("revoked_at", …)` or a/// `json!` key; a NULL value is a create naming the default, which mint drops/// and checks at run time. Raw SQL names it after `UPDATE <table> SET` or in/// an `INSERT INTO <table> (…)` column list, on one of the four tables.fn mirror_writes() -> Vec<(String, String, usize)> {letmut found = Vec::new();for (path, text) in sources() {// The schema's own columns and DDL.if path.starts_with("cotton-store/src/schema/") {continue; }let fns = functions(&text);for (index, line) in text.lines().enumerate() {for column in MIRROR_COLUMNS {let quoted = format!("\"{column}\"");letSome(at) = line.find("ed) else { continue };letmut after = line[at + quoted.len()..].trim_start();for owned in [".to_string()", ".into()", ".to_owned()"] { after = after.strip_prefix(owned).unwrap_or(after); }let patch = line[..at].trim_end().ends_with(".insert(") && after.starts_with(',');let keyed = after.starts_with(':') && !after.starts_with("::");let null = after.contains("Null") || after.trim_start_matches([',', ':', ' ']).starts_with("null");if (patch || keyed) && !null { found.push((path.clone(), fns[index].clone(), index + 1)); } } }let words = words(&text);for (at, (_, word)) in words.iter().enumerate() {let upper = word.to_ascii_uppercase();letSome((_, table)) = words.get(at + 1) else { continue };if !SUBJECT_TABLES.contains(&table.as_str()) {continue; }let (opens, stop): (bool, &[&str]) = match upper.as_str() {"UPDATE" => (words.get(at + 2).is_some_and(|(_, w)| w.eq_ignore_ascii_case("SET")), &["WHERE"]),"INTO" => (true, &["VALUES", "SELECT"]), _ => (false, &[]), };if !opens {continue; }for (line, next) in words.iter().skip(at + 2).take(60) {if stop.iter().any(|s| next.eq_ignore_ascii_case(s)) {break; }if MIRROR_COLUMNS.contains(&next.as_str()) { found.push((path.clone(), fns[line - 1].clone(), *line));break; } } } } found}/// RULE: Only revocation::revoke writes a revocation mirror on cotton_devices, cotton_oauth_grants, cotton_mcp_tokens or cotton_code_credentials; any other call site in crates/*/src fails, and no allow-list remains.//// Groundwork 5b-i landed this scan with an allow-list of the sites 5b-ii had// yet to move; 5b-ii moved them onto `revoke()` and deleted the list, so the// list is empty by not existing and a new site has nowhere to be excused.#[test]fn every_mirror_writer_goes_through_revoke_or_the_allow_list_and_the_list_is_empty_before_14() {let writes = mirror_writes();let offenders: Vec<String> = writes .iter() .filter(|(path, function, _)| !THE_WRITER.iter().any(|(file, f)| file == path && f == function)) .map(|(path, function, line)| format!("{path}:{line} (`{function}`) writes a mirror column")) .collect(); assert!( offenders.is_empty(),"a revocation mirror written outside `cotton_store::revocation::revoke` — call `revoke()` (or `Writer::revoke`), which writes the fact beside it:\n{}", offenders.join("\n") );let sites: BTreeSet<(&str, &str)> = writes.iter().map(|(p, f, _)| (p.as_str(), f.as_str())).collect();for writer in THE_WRITER { assert!(sites.contains(&writer), "the scan no longer sees the writer's own site {writer:?} — it has gone blind"); }}