Cotton code
240 lines · 10.5 KB · RustRaw
//! Device keys sign changes (keys slice KS1): a handle with a device key//! signs every receipt it mints, its author names that key, and the signature//! is kept and carried byte for byte beside the receipt's bytes.use std::sync::Arc;use cotton_store::exchange::{exchange_request, fold_incoming, Handover};use cotton_store::fixtures::{file_at_version, seed_workspace_row, NOW, OWNER, WORKSPACE};use cotton_store::meta::{seed_meta, Meta};use cotton_store::mint::{mint, Act, Change, Clock, Held, History, IdSource, Minted};use cotton_store::protocol::types::CottonOp;use cotton_store::schema::ddl::SCHEMA_VERSION;use cotton_store::signed::{verify_op, KeySigner, ReceiptSigner, Unverified};use cotton_store::Driver;use rusqlite::types::Value as SqlValue;use serde_json::{json, Map, Value};const AT: i64 = 1_790_000_000_000;struct Ids(u32, &'static str);impl IdSource for Ids {    fn next_op_id(&mut self, _now_ms: i64) -> cotton_store::Result<String> {        self.0 += 1;        Ok(format!("{}{:04}", self.1, self.0))    }}fn file(device: &str) -> 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);    db}fn todo(row: &str) -> Map<String, Value> {    json!({"id": row, "workspace_id": WORKSPACE, "title": row, "created_at": NOW, "updated_at": NOW})        .as_object()        .expect("an object")        .clone()}fn act(changes: Vec<Change>) -> Act {    Act {        actor: cotton_store::actor::Actor::device_job(cotton_store::actor::JobName::named("test-writer").expect("a name")),        verb: "write_todo".into(),        history: History::Kept,        changes,    }}fn create(db: &Driver, row: &str, ids: &mut Ids, held: Held) -> Minted {    mint(db, &act(vec![Change::create("cotton_todos", row, todo(row))]), &Clock::wall(AT), ids, held).expect("mints")}fn blob(db: &Driver, sql: &str, param: &str) -> Option<Vec<u8>> {    match db.get(sql, &[SqlValue::Text(param.to_string())]).expect("reads")?.get("sig") {        Some(SqlValue::Blob(sig)) => Some(sig.clone()),        _ => None,    }}fn device_of(db: &Driver) -> impl Fn(&str) -> Option<String> + '_ {    |author| cotton_store::fact_hooks::author_device(db, author).expect("reads")}// RULE: A handle with a device key signs every receipt it mints, and its author's fact names that key.#[test]fn a_signing_handle_signs_every_receipt_under_an_author_that_names_its_key() {    let signer = Arc::new(KeySigner::of_seed(7));    let key = signer.device_key();    // `_meta.device_id` is the file's old `device:<ulid>`: the author names the KEY all the same.    let db = file("device:01JREPLICA0000000000000000").signed_by(signer);    let minted = create(&db, "t1", &mut Ids(0, "a"), Held::Replica);    let author = minted.minted_author.expect("the first write mints the author");    assert_eq!(device_of(&db)(&author.id), Some(key));    assert_eq!(verify_op(&author.fact, WORKSPACE, device_of(&db)), Ok(()));    for op in &minted.ops {        assert_eq!(verify_op(op, WORKSPACE, device_of(&db)), Ok(()), "{}", op.op_id);    }    // A retract is a receipt too.    let retract = mint(&db, &act(vec![Change::retract("cotton_todos", "t1")]), &Clock::wall(AT + 1), &mut Ids(0, "b"), Held::Replica)        .expect("retracts");    assert_eq!(verify_op(&retract.ops[0], WORKSPACE, device_of(&db)), Ok(()));    assert!(blob(&db, "SELECT sig FROM _tombstones WHERE row_id = ?", "t1").is_some());}#[test]fn a_handle_with_no_device_key_mints_unsigned() {    let db = file("device:01JREPLICA0000000000000000");    let minted = create(&db, "t1", &mut Ids(0, "a"), Held::Replica);    assert_eq!(minted.ops[0].sig, None);    assert_eq!(verify_op(&minted.ops[0], WORKSPACE, device_of(&db)), Err(Unverified::Unsigned));}// RULE: A file whose author does not name the signing device's key moves to a fresh `keys` author that does, once.#[test]fn a_file_whose_author_names_no_key_moves_to_a_keys_author() {    let db = file("device:01JREPLICA0000000000000000");    let before = create(&db, "t1", &mut Ids(0, "a"), Held::Replica);    let old_author = before.minted_author.expect("the first author").id;    let signer = Arc::new(KeySigner::of_seed(7));    // The process learns its device key after the file is open: the late slot.    db.signer_slot().fill(signer.clone());    let after = create(&db, "t2", &mut Ids(0, "b"), Held::Replica);    let fresh = after.minted_author.expect("a keys author");    assert_ne!(fresh.id, old_author);    let reason = db        .get("SELECT reason FROM cotton_authors WHERE id = ?", &[SqlValue::Text(fresh.id.clone())])        .expect("reads")        .and_then(|row| row.text("reason").map(str::to_string));    assert_eq!(reason.as_deref(), Some("keys"));    assert_eq!(device_of(&db)(&fresh.id), Some(signer.device_key()));    assert_eq!(verify_op(&after.ops[0], WORKSPACE, device_of(&db)), Ok(()));    // Once: the next write stays on it.    let third = create(&db, "t3", &mut Ids(0, "c"), Held::Replica);    assert!(third.minted_author.is_none());    assert_eq!(third.ops[0].device_id, fresh.id);}// RULE: A receipt's signature is stored and carried byte for byte: outbox, wire, the receiver's _writes and what it serves on.#[test]fn sig_travels_byte_for_byte_through_outbox_wire_and_writes() {    let signer = Arc::new(KeySigner::of_seed(7));    let replica = file("device:01JREPLICA0000000000000000").signed_by(signer);    let minted = create(&replica, "t1", &mut Ids(0, "a"), Held::Replica);    let op = &minted.ops[0];    let sig = cotton_store::signed::sig_bytes(op).expect("64 bytes");    assert_eq!(blob(&replica, "SELECT sig FROM _writes WHERE op_id = ?", &op.op_id), Some(sig.clone()));    assert_eq!(blob(&replica, "SELECT sig FROM _outbox WHERE op_id = ?", &op.op_id), Some(sig.clone()));    // The request reads the outbox; the wire is JSON; the reader takes `sig` beside the bytes.    let handed = exchange_request(&replica, WORKSPACE, None, &mut Handover::shut()).expect("a request");    let wire: Value = serde_json::to_value(&handed.request.ops).expect("serializes");    let read: Vec<CottonOp> = cotton_store::wire::ops(wire.as_array().expect("an array"))        .into_iter()        .collect::<Result<_, _>>()        .expect("reads back");    let carried = read.iter().find(|o| o.op_id == op.op_id).expect("the write is in the request");    assert_eq!(carried.sig, op.sig);    assert_eq!(carried.receipt, op.receipt);    // The receiver keeps it, and serves it on as it took it.    let server = file("device:01JSERVER00000000000000000");    let folded = fold_incoming(&server, &read).expect("folds");    assert!(folded.rejected.is_empty(), "{:?}", folded.rejected);    assert_eq!(blob(&server, "SELECT sig FROM _writes WHERE op_id = ?", &op.op_id), Some(sig));    let served = cotton_store::changes::changes_since(&server, &op.device_id, "", 100).expect("a page");    for served in &served.ops {        assert_eq!(verify_op(served, WORKSPACE, device_of(&server)), Ok(()), "{}", served.op_id);    }    assert!(served.ops.iter().any(|o| o.op_id == op.op_id && o.sig == op.sig));}#[test]fn a_receipt_checked_against_its_authors_device() {    let signer = Arc::new(KeySigner::of_seed(7));    let db = file("device:01JREPLICA0000000000000000").signed_by(signer);    let minted = create(&db, "t1", &mut Ids(0, "a"), Held::Replica);    let op = minted.ops[0].clone();    // Signed by another device over the same bytes.    let forged = KeySigner::of_seed(8).sign_op(WORKSPACE, op.clone());    assert_eq!(verify_op(&forged, WORKSPACE, device_of(&db)), Err(Unverified::Mismatch));    // Bytes changed after signing.    let mut changed = op.clone();    changed.receipt = changed.receipt.replace("\"t1\"", "\"t9\"");    assert_eq!(verify_op(&changed, WORKSPACE, device_of(&db)), Err(Unverified::Mismatch));    // Another database.    assert_eq!(        verify_op(&op, "22222222-2222-4222-8222-222222222222", device_of(&db)),        Err(Unverified::Mismatch)    );    // Unsigned.    let mut bare = op.clone();    bare.sig = None;    assert_eq!(verify_op(&bare, WORKSPACE, device_of(&db)), Err(Unverified::Unsigned));    // An author nobody has introduced.    assert_eq!(verify_op(&op, WORKSPACE, |_| None), Err(Unverified::UnknownAuthor));}// RULE: A parked write keeps its signature, and a park offered again — requeued into the outbox or handed over — carries it byte for byte.//// The serving Mac's signature screen refuses an unsigned push outright, so a// park that dropped its `sig` was refused on every re-offer, whatever its cause.#[test]fn a_park_offered_again_carries_its_original_signature() {    let signer = Arc::new(KeySigner::of_seed(7));    let replica = file("device:01JREPLICA0000000000000000").signed_by(signer);    let minted = create(&replica, "t1", &mut Ids(0, "a"), Held::Replica);    let op = minted.ops[0].clone();    let sig = cotton_store::signed::sig_bytes(&op).expect("64 bytes");    // The serving Mac refused the push: it leaves the outbox and parks.    replica        .run("DELETE FROM _outbox WHERE op_id = ?", &[SqlValue::Text(op.op_id.clone())])        .expect("leaves the outbox");    cotton_store::rejected::park(        &replica,        &op,        cotton_store::rejected::Direction::Push,        cotton_store::rejected::Class::Conflict,        "refused by the serving Mac",        NOW,    )    .expect("parks");    assert_eq!(blob(&replica, "SELECT sig FROM _parked WHERE op_id = ?", &op.op_id), Some(sig.clone()));    // Handed over, from a start above its stamp.    let start = std::collections::BTreeMap::from([(op.device_id.clone(), "~".to_string())]);    let offered = cotton_store::rejected::parked_for_handover(&replica, &start, 2).expect("reads");    let handed = offered.iter().find(|o| o.op_id == op.op_id).expect("the park is offered");    assert_eq!(handed.sig, op.sig);    assert_eq!(verify_op(handed, WORKSPACE, device_of(&replica)), Ok(()));    // Requeued by a touch of its row.    let queued = cotton_store::rejected::requeue_touched_pushes(        &replica,        &[("cotton_todos".to_string(), "t1".to_string())],        NOW,    )    .expect("requeues");    assert_eq!(queued, vec![op.op_id.clone()]);    assert_eq!(blob(&replica, "SELECT sig FROM _outbox WHERE op_id = ?", &op.op_id), Some(sig));}