Cotton code
485 lines · 18.5 KB · RustRaw
//! The live fence over `GRANT_WRITE_ONCE_COLUMNS` and the device and grant//! row shapes, on a file this build creates.//!//! Kept when the ladder's per-rung tests were retired: the rungs are gone,//! but what they proved about a FRESH file still has to hold. A code//! credential's digest, device and minter are written once, with the row; a//! device key can hold a second approval row; a device row takes the shape the//! server writes; an OAuth grant's refresh digest names its writer.//!//! 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;use cotton_store::migrate::{current_version, migrate_store, SCHEMA_VERSION};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, Row};use rusqlite::types::Value;use serde_json::{json, Map, Value as JsonValue};const WORKSPACE: &str = "11111111-1111-4111-8111-111111111111";/// An explicit instant, never the wall clock.const NOW: &str = "2026-09-29T09:00:00.000Z";const COLUMN: &str = "token_digest";const MINTER: &str = "minted_by";/// An invented digest — 64 hex characters, the shape `code_tokens::digest`/// writes.const DIGEST: &str = "0f1e2d3c4b5a69788796a5b4c3d2e1f00f1e2d3c4b5a69788796a5b4c3d2e1f0";const OTHER_DIGEST: &str = "a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1";/// Two Macs of one household, as op AUTHORS.const STUDY: &str = "device:01JSTUDYMAC0000000000000000";const KITCHEN: &str = "device:01JKITCHENMAC000000000000000";fn text(value: &str) -> Value {    Value::Text(value.to_string())}fn columns_of(db: &Driver, table: &str) -> Vec<String> {    db.all(&format!("PRAGMA table_info({table})"), &[])        .expect("reads")        .iter()        .filter_map(|row| row.text("name").map(str::to_string))        .collect()}fn one(db: &Driver, sql: &str) -> Row {    db.get(sql, &[]).expect("reads").expect("a row")}fn object_exists(db: &Driver, name: &str) -> bool {    db.get(        "SELECT name FROM sqlite_master WHERE name = ?",        &[text(name)],    )    .expect("reads")    .is_some()}fn devices_table_sql(db: &Driver) -> String {    one(        db,        "SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'cotton_devices'",    )    .text("sql")    .expect("the table")    .to_string()}// ── the code-credential fence ───────────────────────────────────────────────fn fresh_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}thread_local! {    /// A file at this build's schema, which is all a receipt is built against.    static SCHEMA: Driver = {        let db = Driver::open_in_memory().expect("opens");        migrate_store(&db).expect("migrates");        db    };}/// The op for `change`, its receipt as `mint` would make it, under `author`/// at `ms`.fn receipt_op(change: Change, n: u32, author: &str, ms: i64) -> CottonOp {    let hlc = next_hlc(author, None, ms).expect("a stamp in range");    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")}/// A change to the credential row.fn grant_op(n: u32, author: &str, ms: i64, body: JsonValue) -> CottonOp {    let JsonValue::Object(patch) = body else {        panic!("a patch is an object");    };    receipt_op(Change::update("cotton_code_credentials", "cred-1", patch), n, author, ms)}/// The whole row, as the minting Mac writes it: the grant and its digest in/// ONE op.fn minted(n: u32, digest: Option<&str>) -> CottonOp {    minted_by(n, digest, None)}fn minted_by(n: u32, digest: Option<&str>, minter: Option<&str>) -> CottonOp {    let mut body: Map<String, JsonValue> = json!({        "workspace_id": WORKSPACE,        "device_id": "device:invented",        "name": "the invented mini",        "scope": "device",        "created_at": NOW,    })    .as_object()    .cloned()    .expect("an object");    if let Some(digest) = digest {        body.insert(COLUMN.to_string(), json!(digest));    }    if let Some(minter) = minter {        body.insert(MINTER.to_string(), json!(minter));    }    receipt_op(Change::create("cotton_code_credentials", "cred-1", body), n, STUDY, 0)}fn digest_of(db: &Driver) -> Option<String> {    one(db, "SELECT token_digest FROM cotton_code_credentials WHERE id = 'cred-1'")        .text(COLUMN)        .map(str::to_string)}/// RULE: A code credential's token digest is set only by the op that creates its grant row: the fold rejects a patch that changes, clears or adds the digest of a row that already exists, so a device that held the old workspace key cannot point a live grant at a token it forged.#[test]fn a_patch_that_swaps_or_clears_a_grants_digest_is_rejected_and_says_so() {    let db = fresh_file();    fold_ops(&db, &[minted(1, Some(DIGEST))]).expect("folds");    assert_eq!(digest_of(&db).as_deref(), Some(DIGEST));    // A later stamp from another Mac, re-pointing the row at another token.    // Under plain last-writer-wins it would land.    for (n, swapped) in [(2, json!(OTHER_DIGEST)), (3, JsonValue::Null)] {        let swap = grant_op(            n,            KITCHEN,            9_000,            json!({ COLUMN: swapped, "name": "a renamed mini" }),        );        let result = fold_ops(&db, &[swap]).expect("folds");        assert!(result.applied.is_empty(), "nothing of it lands");        assert_eq!(result.rejected.len(), 1);        assert!(            result.rejected[0]                .reason                .contains("a code credential's token_digest is written once, with its row"),            "the rejection names the rule, got {:?}",            result.rejected[0].reason        );        assert_eq!(digest_of(&db).as_deref(), Some(DIGEST));        assert_eq!(            one(&db, "SELECT name FROM cotton_code_credentials WHERE id = 'cred-1'").text("name"),            Some("the invented mini"),            "the rest of the patch does not sneak in behind the refused column"        );    }}#[test]fn the_same_digest_again_and_patches_that_do_not_name_it_still_land() {    let db = fresh_file();    fold_ops(&db, &[minted(1, Some(DIGEST))]).expect("folds");    // A replay of the mint — the same value — is not a rewrite.    let replay = grant_op(2, KITCHEN, 5_000, json!({ COLUMN: DIGEST }));    // A revocation and a last-used stamp say nothing about the digest.    let revoke = grant_op(3, KITCHEN, 6_000, json!({ "revoked_at": NOW }));    let stamp = grant_op(4, STUDY, 7_000, json!({ "last_used_at": NOW }));    let result = fold_ops(&db, &[replay, revoke, stamp]).expect("folds");    assert!(result.rejected.is_empty(), "{:?}", result.rejected);    assert_eq!(digest_of(&db).as_deref(), Some(DIGEST));    let row = one(&db, "SELECT * FROM cotton_code_credentials WHERE id = 'cred-1'");    assert_eq!(row.text("revoked_at"), Some(NOW));    assert_eq!(row.text("last_used_at"), Some(NOW));}#[test]fn a_grant_minted_before_the_rung_cannot_be_given_a_digest_afterwards() {    // A pre-rung grant carries no digest, and its token is refused after a    // rotation for that reason. A digest patched onto it later would be a    // token somebody CHOSE — the forgery the digest exists to stop, by the    // back door — so the column is set by the op that creates the row, or    // never.    let db = fresh_file();    fold_ops(&db, &[minted(1, None)]).expect("folds");    assert_eq!(digest_of(&db), None);    let planted = grant_op(2, KITCHEN, 9_000, json!({ COLUMN: OTHER_DIGEST }));    let result = fold_ops(&db, &[planted]).expect("folds");    assert_eq!(result.rejected.len(), 1, "{result:?}");    assert_eq!(digest_of(&db), None);    // Naming the column as NULL on such a row changes nothing, and lands.    let null = grant_op(        3,        KITCHEN,        9_500,        json!({ COLUMN: JsonValue::Null, "last_used_at": NOW }),    );    let result = fold_ops(&db, &[null]).expect("folds");    assert!(result.rejected.is_empty(), "{:?}", result.rejected);}/// RULE: The device a code credential's grant names and the Mac that minted it are set only by the op that creates the row: the fold rejects a patch that moves either, so a grant cannot be moved out of reach of the revocation that should end it.#[test]fn a_patch_that_moves_a_grants_device_or_minter_is_rejected() {    let db = fresh_file();    let mint = minted_by(1, Some(DIGEST), Some(STUDY));    fold_ops(&db, &[mint]).expect("folds");    for (n, column, moved) in [        (2, "device_id", json!("device:somebody-else")),        (3, MINTER, json!(KITCHEN)),        (4, MINTER, JsonValue::Null),    ] {        let patch = grant_op(n, KITCHEN, 9_000, json!({ column: moved }));        let result = fold_ops(&db, &[patch]).expect("folds");        assert!(result.applied.is_empty(), "nothing of it lands");        assert_eq!(result.rejected.len(), 1, "{result:?}");        assert!(            result.rejected[0]                .reason                .contains(&format!("a code credential's {column} is written once, with its row")),            "the rejection names the column, got {:?}",            result.rejected[0].reason        );    }    let row = one(&db, "SELECT * FROM cotton_code_credentials WHERE id = 'cred-1'");    assert_eq!(row.text("device_id"), Some("device:invented"));    assert_eq!(row.text(MINTER), Some(STUDY));    // A replay of the mint — the same values — is not a rewrite.    let replay = grant_op(        5,        STUDY,        9_500,        json!({ "device_id": "device:invented", MINTER: STUDY }),    );    let result = fold_ops(&db, &[replay]).expect("folds");    assert!(result.rejected.is_empty(), "{:?}", result.rejected);}// ── the device and grant row shapes ─────────────────────────────────────────#[test]fn a_file_this_build_creates_holds_no_one_row_per_key_constraint() {    let db = Driver::open_in_memory().expect("opens");    migrate_store(&db).expect("a fresh file");    assert_eq!(current_version(&db).expect("reads"), SCHEMA_VERSION);    assert!(!devices_table_sql(&db).contains("UNIQUE"));}/// A revoked approval of `laptop-key`, the row a re-approval sits beside.fn seed_a_revoked_approval(db: &Driver) {    db.run(        "INSERT INTO cotton_devices (id, workspace_id, device_id, name, platform, app_version, \         approved_at, approved_by_device, revoked_at, revoked_by_device, revoked_reason, \         created_at, updated_at) \         VALUES (?,?,?,?,'mac','0.18.0',?,?,?,?,?,?,?)",        &[            text("row-revoked"),            text(WORKSPACE),            text("laptop-key"),            text("The invented laptop"),            text("2026-09-18T10:37:17.779Z"),            text("desk-mac-key"),            text("2026-09-20T08:00:00.000Z"),            text("desk-mac-key"),            text("revoked"),            text("2026-09-18T10:37:17.779Z"),            text("2026-09-20T08:00:00.000Z"),        ],    )    .expect("the revoked row");}#[test]fn the_same_device_key_can_hold_a_second_approval_row() {    let db = fresh_file();    seed_a_revoked_approval(&db);    db.run(        "INSERT INTO cotton_devices (id, workspace_id, device_id, name, approved_at, \         approved_by_device, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?)",        &[            text("row-approved-again"),            text(WORKSPACE),            text("laptop-key"),            text("The invented laptop"),            text(NOW),            text("phone-key"),            text(NOW),            text(NOW),        ],    )    .expect("a re-approval is a new row beside the revoked one");    let live = one(        &db,        "SELECT count(*) AS c FROM cotton_devices WHERE device_id = 'laptop-key' \         AND revoked_at IS NULL",    );    assert_eq!(live.int("c"), Some(1));    assert_eq!(        one(            &db,            "SELECT count(*) AS c FROM cotton_devices WHERE device_id = 'laptop-key'"        )        .int("c"),        Some(2),        "the revoked approval stays, as history"    );    assert!(        db.all("PRAGMA foreign_key_check", &[])            .expect("reads")            .is_empty(),        "a dangling reference"    );    assert_eq!(        one(&db, "PRAGMA integrity_check")            .text("integrity_check")            .map(str::to_string),        Some("ok".to_string())    );}#[test]fn a_file_this_build_creates_has_the_shape_from_the_start() {    let db = Driver::open_in_memory().expect("opens");    migrate_store(&db).expect("creates");    assert_eq!(current_version(&db).expect("reads"), SCHEMA_VERSION);    for table in [        "cotton_devices",        "cotton_oauth_clients",        "cotton_oauth_grants",    ] {        assert!(object_exists(&db, table), "{table}");    }    assert!(columns_of(&db, "cotton_workspaces")        .iter()        .any(|name| name == "relay_name"));    for table in ["cotton_code_credentials", "cotton_repo_jobs"] {        assert!(columns_of(&db, table).iter().any(|column| column == COLUMN));    }    assert!(columns_of(&db, "cotton_code_credentials")        .iter()        .any(|column| column == MINTER));    for column in ["refresh_digest", MINTER] {        assert!(columns_of(&db, "cotton_oauth_grants")            .iter()            .any(|name| name == column));    }}#[test]fn a_device_row_takes_the_shape_the_server_writes_and_the_key_is_unique_per_workspace() {    let db = fresh_file();    let insert = "INSERT INTO cotton_devices (id, workspace_id, device_id, name, platform, \                  app_version, relay_identity_key, approved_at, approved_by_device, created_at, \                  updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?)";    let row = |id: &str, device: &str| -> Vec<Value> {        vec![            text(id),            text(WORKSPACE),            text(device),            text("An invented iPhone"),            text("ios"),            text("1.0.0"),            Value::Null,            text(NOW),            text("self"),            text(NOW),            text(NOW),        ]    };    db.run(insert, &row("dev-row-1", "AAAA_a_synthetic_key"))        .expect("the device row");    assert_eq!(        one(&db, "SELECT * FROM cotton_devices WHERE id = 'dev-row-1'").text("revoked_at"),        None,        "a live device carries no revocation"    );    // ONE ROW PER APPROVAL: a key re-approved after a revocation is a second    // row beside the revoked one, never the first row returning.    db.run(insert, &row("dev-row-2", "AAAA_a_synthetic_key"))        .expect("a second approval of the same key is a row of its own");    // And the pair a merge can land out of step is NOT held by a CHECK: the    // fold settles `revoked_at` by its own policy and `revoked_by_device` by    // the clock, so the two can arrive apart and a CHECK over them would turn    // an ordinary merge into a rejected revocation.    db.run(        "UPDATE cotton_devices SET revoked_at = ? WHERE id = 'dev-row-1'",        &[text(NOW)],    )    .expect("a revocation with no revoker yet");    let revoked = one(&db, "SELECT * FROM cotton_devices WHERE id = 'dev-row-1'");    assert_eq!(revoked.text("revoked_at"), Some(NOW));    assert_eq!(revoked.text("revoked_by_device"), None);}/// A consent with its chain seven rotations in.fn seed_a_grant(db: &Driver) {    db.run(        "INSERT INTO cotton_oauth_grants (id, workspace_id, client_id, client_name, scope, \         created_at, token_id, refresh_generation, refresh_rotated_at) \         VALUES ('grant-1', ?, 'an-invented-client', 'An invented assistant', 'read write', ?, \         'token-row-1', 7, ?)",        &[text(WORKSPACE), text(NOW), text(NOW)],    )    .expect("the grant row");}#[test]fn the_column_takes_a_digest_naming_its_writer_and_refuses_what_is_not_one_long() {    let db = fresh_file();    seed_a_grant(&db);    let digest = format!("{:010}:{}:{}", 8, "a".repeat(64), "c3R1ZHktbWFj");    db.run(        "UPDATE cotton_oauth_grants SET refresh_digest = ? WHERE id = 'grant-1'",        &[text(&digest)],    )    .expect("a digest");    assert_eq!(        one(&db, "SELECT * FROM cotton_oauth_grants WHERE id = 'grant-1'").text("refresh_digest"),        Some(digest.as_str())    );    let unwritten = format!("{:010}:{}", 8, "a".repeat(64));    let overlong = format!("{:010}:{}:{}", 8, "a".repeat(64), "w".repeat(129));    for refused in ["8:abc", "", unwritten.as_str(), overlong.as_str()] {        assert!(            db.run(                "UPDATE cotton_oauth_grants SET refresh_digest = ? WHERE id = 'grant-1'",                &[text(refused)],            )            .is_err(),            "{refused:?} is not a digest, and the column took it"        );    }    assert_eq!(        one(&db, "PRAGMA integrity_check")            .text("integrity_check")            .map(str::to_string),        Some("ok".to_string())    );}/// RULE: A synced patch cannot broaden an observer grant by clearing read_only or replacing its stored scope; the signed token and immutable grant must continue naming the same authority.#[test]fn a_read_only_grant_cannot_be_broadened_after_minting() {    let db = fresh_file();    let body = json!({"workspace_id":WORKSPACE,"device_id":"device:invented","name":"Observer","scope":"script","read_only":1,"created_at":NOW,"token_digest":DIGEST});    let mint = receipt_op(Change::create("cotton_code_credentials", "cred-1", body.as_object().unwrap().clone()), 1, STUDY, 0);    let result = fold_ops(&db, &[mint]).unwrap();    assert!(result.rejected.is_empty(), "{result:?}");    for (n, patch) in [(2, json!({"read_only":0})), (3, json!({"scope":"device"}))] {        let result = fold_ops(&db, &[grant_op(n, KITCHEN, 9_000, patch)]).unwrap();        assert_eq!(result.rejected.len(), 1, "{result:?}");    }    let replay = fold_ops(&db, &[grant_op(4, KITCHEN, 9_001, json!({"read_only":1,"scope":"script"}))]).unwrap();    assert!(replay.rejected.is_empty(), "{replay:?}");    assert_eq!(one(&db, "SELECT read_only FROM cotton_code_credentials WHERE id='cred-1'").int("read_only"), Some(1));}