//! The consent row travels, and what it says about a credential survives the //! journey (version 21). //! //! Since this rung the grant row is not a record of something that happened — //! it is the STATE a token is verified against, on every Mac of the household. //! `revoked_at` decides whether an assistant is still allowed in, and //! `refresh_generation` is the whole of replay detection. Both are now //! authentication inputs that arrive over sync, so both need the same two //! rules `cotton_devices` has had since version 9: //! //! 1. **The refresh chain is monotone** — `refresh_generation` by `MaxNonNull` //! (a chain cannot be wound back into the window where a spent token is //! honoured). `revoked_at` is the mirror of a revocation fact //! (`cotton_revocations`) and settles by the clock. //! 2. **A patch that clears the revocation is REJECTED** — the fence refuses //! it whole and says which op and why. //! //! 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::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, Row}; use rusqlite::types::Value; use serde_json::{json, Map, Value as JsonValue}; const WORKSPACE: &str = "11111111-1111-4111-8111-111111111111"; const GRANT: &str = "grant-row-1"; const NOW: &str = "2026-09-21T09:00:00.000Z"; const EARLY: &str = "2026-09-21T10:00:00.000Z"; const LATER: &str = "2026-09-21T18:00:00.000Z"; /// The Mac that answered for the household, as an op AUTHOR. const STUDY: &str = "device:01JSTUDYMAC0000000000000000"; /// The other Mac of the same household — the one that has not heard yet. const KITCHEN: &str = "device:01JKITCHENMAC000000000000000"; 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 patch(value: JsonValue) -> Option> { match value { JsonValue::Object(map) => Some(map), other => panic!("a patch is an object, got {other}"), } } 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. 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 grant row. fn op(n: u32, author: &str, ms: i64, body: JsonValue) -> CottonOp { let patch = patch(body).expect("a patch"); receipt_op(Change::update("cotton_oauth_grants", GRANT, patch), n, author, ms) } /// The whole row, as the Mac that took the consent first writes it. fn consent(n: u32, author: &str, ms: i64) -> CottonOp { consent_with(n, author, ms, json!({})) } /// The whole row, with `extra` columns beside it, in its creating op. fn consent_with(n: u32, author: &str, ms: i64, extra: JsonValue) -> CottonOp { let mut body = patch(json!({ "id": GRANT, "workspace_id": WORKSPACE, "client_id": "an-invented-client", "client_name": "An invented assistant", "scope": "read write", "created_at": NOW, "token_id": "token-row-1", "refresh_generation": 0, })) .expect("a patch"); body.extend(patch(extra).expect("a patch")); receipt_op(Change::create("cotton_oauth_grants", GRANT, body), n, author, ms) } fn row(db: &Driver) -> Row { db.get( "SELECT * FROM cotton_oauth_grants WHERE id = 'grant-row-1'", &[], ) .expect("reads") .expect("the grant row") } #[test] fn a_patch_that_clears_the_revocation_is_rejected_and_says_so() { // THE FENCE, on the row an assistant authenticates against. The clock alone // would let a later null win quietly, land the rest of the patch and tell // the pushing device it worked — and the one column that mattered would // have been the one nobody was told about. let db = file(); let revoke = op( 2, STUDY, 1_000, json!({ "revoked_at": EARLY, "client_name": "An invented assistant" }), ); fold_ops(&db, &[consent(1, STUDY, 0), revoke]).expect("folds"); assert_eq!(row(&db).text("revoked_at"), Some(EARLY)); let resurrect = op( 3, KITCHEN, 9_000, json!({ "revoked_at": JsonValue::Null, "client_name": "A renamed assistant" }), ); let result = fold_ops(&db, &[resurrect]).expect("folds"); assert!(result.applied.is_empty(), "nothing of it lands"); assert_eq!(result.rejected.len(), 1); assert!( result.rejected[0] .reason .contains("a revoked row is not un-revoked by a patch: cotton_oauth_grants"), "the rejection names the rule, got {:?}", result.rejected[0].reason ); assert_eq!(row(&db).text("revoked_at"), Some(EARLY)); assert_eq!( row(&db).text("client_name"), Some("An invented assistant"), "the rest of the patch does not sneak in behind the refused column" ); } /// `revoked_at` is the mirror of a revocation fact and settles by the clock: /// two Macs' writes end at the later STAMP's value in either order. Neither /// can clear it (the fence below), and the facts are the record of truth. #[test] fn two_mirror_writes_converge_on_the_later_stamp_in_either_order() { for order in [[0usize, 1], [1, 0]] { let db = file(); fold_ops(&db, &[consent(1, STUDY, 0)]).expect("folds"); let writes = [ op(2, STUDY, 5_000, json!({ "revoked_at": EARLY })), op(3, KITCHEN, 9_000, json!({ "revoked_at": LATER })), ]; let ordered: Vec = order.iter().map(|at| writes[*at].clone()).collect(); fold_ops(&db, &ordered).expect("folds"); assert_eq!( row(&db).text("revoked_at"), Some(LATER), "the later stamp's revocation stands in order {order:?}" ); } } #[test] fn the_refresh_chain_never_goes_backwards_whatever_order_it_hears_about() { // A Mac that had not heard of the last rotation must not be able to wind // the chain back: a lower generation is what replay detection reads as // "this token was already spent", so winding it back re-opens a window in // which a stolen token works. for order in [[0usize, 1], [1, 0]] { let db = file(); fold_ops(&db, &[consent(1, STUDY, 0)]).expect("folds"); let writes = [ op( 2, STUDY, 5_000, json!({ "refresh_generation": 7, "refresh_rotated_at": EARLY }), ), // LATER in wall-clock and LOWER in generation: the ordinary // last-write-wins would take this one. op( 3, KITCHEN, 9_000, json!({ "refresh_generation": 2, "refresh_rotated_at": LATER }), ), ]; let ordered: Vec = order.iter().map(|at| writes[*at].clone()).collect(); fold_ops(&db, &ordered).expect("folds"); assert_eq!( row(&db).int("refresh_generation"), Some(7), "the highest generation wins in order {order:?}" ); } } // ── version 45: the refresh digest ────────────────────────────────────────── // // `refresh_digest` is `::` of the // current generation's refresh token, the writer being the device id of the // Mac that moved the chain there. It lets a Mac admit a `ctr_` signed under a key // version the household has rotated past, so it is an authentication input // that arrives over sync — and the rule that bounds it is that it moves only // WITH the chain. These digests are invented hex, not the digest of anything. /// The device a digest names as its writer. Invented base64url. const WRITER: &str = "c3R1ZHktbWFjLWRldmljZS1pZC1pbnZlbnRlZA"; fn digest(generation: u32, fill: char) -> String { digest_by(generation, fill, WRITER) } fn digest_by(generation: u32, fill: char, writer: &str) -> String { format!("{generation:010}:{}:{writer}", fill.to_string().repeat(64)) } fn consent_with_digest(n: u32, author: &str, ms: i64, value: &str) -> CottonOp { consent_with(n, author, ms, json!({ "refresh_digest": value })) } fn rejected_for(result: &cotton_store::fold::FoldResult, why: &str) { assert!(result.applied.is_empty(), "nothing of it lands"); assert_eq!(result.rejected.len(), 1, "one rejection"); let reason = &result.rejected[0].reason; assert!( reason.contains("an OAuth grant's refresh digest moves only with its chain") && reason.contains(why), "the rejection names the rule ({why}), got {reason:?}" ); } #[test] fn a_grant_is_born_with_its_digest_and_a_rotation_moves_it_on() { let db = file(); let born = fold_ops(&db, &[consent_with_digest(1, STUDY, 0, &digest(0, 'a'))]).expect("folds"); assert!(born.rejected.is_empty(), "{:?}", born.rejected); assert_eq!(row(&db).text("refresh_digest"), Some(digest(0, 'a').as_str())); let rotate = op( 2, STUDY, 5_000, json!({ "refresh_generation": 1, "refresh_rotated_at": EARLY, "refresh_digest": digest(1, 'b') }), ); let moved = fold_ops(&db, std::slice::from_ref(&rotate)).expect("folds"); assert!(moved.rejected.is_empty(), "{:?}", moved.rejected); assert_eq!(row(&db).text("refresh_digest"), Some(digest(1, 'b').as_str())); // The same op arriving twice is a replay, not a swap. let again = fold_ops(&db, &[rotate]).expect("folds"); assert!(again.rejected.is_empty(), "{:?}", again.rejected); } #[test] fn the_digest_settles_with_the_generation_it_names_whatever_order_it_arrives_in() { // Two rotations arriving out of order: the later generation's op is // stamped EARLIER (another Mac, no causal link), so a clock would pick // the wrong digest. The value leads with the generation, and the higher // one wins everywhere. for order in [[0usize, 1], [1, 0]] { let db = file(); fold_ops(&db, &[consent_with_digest(1, STUDY, 0, &digest(0, 'a'))]).expect("folds"); let writes = [ op( 2, STUDY, 9_000, json!({ "refresh_generation": 1, "refresh_rotated_at": EARLY, "refresh_digest": digest(1, 'b') }), ), op( 3, KITCHEN, 5_000, json!({ "refresh_generation": 2, "refresh_rotated_at": LATER, "refresh_digest": digest(2, 'c') }), ), ]; let ordered: Vec = order.iter().map(|at| writes[*at].clone()).collect(); let result = fold_ops(&db, &ordered).expect("folds"); assert!( result.rejected.is_empty(), "a late honest rotation loses, it is not refused: {:?}", result.rejected ); assert_eq!(row(&db).int("refresh_generation"), Some(2), "order {order:?}"); assert_eq!( row(&db).text("refresh_digest"), Some(digest(2, 'c').as_str()), "the digest is the one the highest generation carried, in order {order:?}" ); } } /// RULE: A patch that swaps a different refresh digest onto the generation an OAuth grant's digest already names is rejected. #[test] fn a_different_digest_at_the_generation_the_row_names_is_refused() { // A digest is swapped onto an existing grant by nobody — a device // that could re-point the digest at a token it forged under the key it // holds would outlive its own revocation. let db = file(); fold_ops(&db, &[consent_with_digest(1, STUDY, 0, &digest(0, 'a'))]).expect("folds"); let swap = op( 2, KITCHEN, 5_000, json!({ "refresh_generation": 0, "refresh_digest": digest(0, 'f'), "client_name": "A renamed assistant" }), ); let result = fold_ops(&db, &[swap]).expect("folds"); rejected_for(&result, "a different digest at the generation"); assert_eq!(row(&db).text("refresh_digest"), Some(digest(0, 'a').as_str())); assert_eq!(row(&db).text("client_name"), Some("An invented assistant")); } #[test] fn a_digest_planted_on_a_grant_without_moving_its_chain_is_refused() { // A grant from before version 45 has no digest. Adding one at the // generation it stands at would let a forged token outlive the rotation // silently; only a rotation PAST where it stands may bring one. let db = file(); fold_ops( &db, &[ consent(1, STUDY, 0), op(2, STUDY, 1_000, json!({ "refresh_generation": 3, "refresh_rotated_at": EARLY })), ], ) .expect("folds"); let plant = op( 3, KITCHEN, 5_000, json!({ "refresh_generation": 3, "refresh_digest": digest(3, 'e') }), ); rejected_for( &fold_ops(&db, &[plant]).expect("folds"), "only by a rotation past where it stands", ); assert_eq!(row(&db).text("refresh_digest"), None); let rotation = op( 4, STUDY, 6_000, json!({ "refresh_generation": 4, "refresh_rotated_at": LATER, "refresh_digest": digest(4, 'd') }), ); let moved = fold_ops(&db, &[rotation]).expect("folds"); assert!(moved.rejected.is_empty(), "{:?}", moved.rejected); assert_eq!(row(&db).text("refresh_digest"), Some(digest(4, 'd').as_str())); } #[test] fn a_digest_without_its_rotation_is_refused() { let db = file(); fold_ops(&db, &[consent_with_digest(1, STUDY, 0, &digest(0, 'a'))]).expect("folds"); // Names a generation the patch does not move the chain to. let alone = op(2, KITCHEN, 5_000, json!({ "refresh_digest": digest(1, 'b') })); rejected_for( &fold_ops(&db, &[alone]).expect("folds"), "does not move the chain to the generation the digest names", ); let mismatched = op( 3, KITCHEN, 6_000, json!({ "refresh_generation": 2, "refresh_digest": digest(1, 'b') }), ); rejected_for( &fold_ops(&db, &[mismatched]).expect("folds"), "does not move the chain to the generation the digest names", ); } #[test] fn a_digest_is_never_cleared_and_never_malformed() { let db = file(); fold_ops(&db, &[consent_with_digest(1, STUDY, 0, &digest(0, 'a'))]).expect("folds"); let clear = op( 2, KITCHEN, 5_000, json!({ "refresh_generation": 1, "refresh_digest": JsonValue::Null }), ); rejected_for(&fold_ops(&db, &[clear]).expect("folds"), "a digest is never cleared"); for (n, bad) in [ format!("{:09}:{}:{WRITER}", 1, "b".repeat(65)), format!("{:010}:{}:{WRITER}", 1, "B".repeat(64)), format!("{:010};{}:{WRITER}", 1, "b".repeat(64)), format!("{:010}:{}:{WRITER}", 1, "g".repeat(64)), // No writer: a digest nobody can be held to. format!("{:010}:{}", 1, "b".repeat(64)), format!("{:010}:{}:", 1, "b".repeat(64)), format!("{:010}:{}:a mac", 1, "b".repeat(64)), format!("{:010}:{}:{}", 1, "b".repeat(64), "x".repeat(129)), ] .into_iter() .enumerate() { let malformed = op( 3 + n as u32, KITCHEN, 6_000 + n as i64, json!({ "refresh_generation": 1, "refresh_digest": bad }), ); rejected_for( &fold_ops(&db, &[malformed]).expect("folds"), "not a generation, a SHA-256 digest and the device that wrote it", ); } assert_eq!(row(&db).text("refresh_digest"), Some(digest(0, 'a').as_str())); } /// RULE: The device a refresh digest names as its writer is part of the value, so no push re-attributes a standing digest to another device. #[test] fn the_same_digest_naming_another_writer_is_a_swap() { // Revoking a device reaches every grant whose CURRENT digest it wrote. // If a push could put another device's name on a standing digest, a // device about to be revoked would move its planted digest out of reach // of its own revocation — so the writer is as fixed as the hash. let db = file(); fold_ops(&db, &[consent_with_digest(1, STUDY, 0, &digest(0, 'a'))]).expect("folds"); let relabel = op( 2, KITCHEN, 5_000, json!({ "refresh_generation": 0, "refresh_digest": digest_by(0, 'a', "another-device") }), ); rejected_for( &fold_ops(&db, &[relabel]).expect("folds"), "a different digest at the generation", ); assert_eq!(row(&db).text("refresh_digest"), Some(digest(0, 'a').as_str())); } // ── version 45: who minted the consent ────────────────────────────────────── // // `minted_by` is the device id of the Mac that took the consent. The sync // route takes the grant's writes from that device, and a revocation reaches // what the device minted — so the column, and `client_id`, are written once, // with the row, and by nothing after (`fold::no_grant_rewrite`). fn consent_minted_by(n: u32, author: &str, ms: i64, minter: &str) -> CottonOp { consent_with(n, author, ms, json!({ "minted_by": minter })) } fn rewrite_refused(result: &cotton_store::fold::FoldResult, column: &str) { assert!(result.applied.is_empty(), "nothing of it lands"); assert_eq!(result.rejected.len(), 1, "one rejection"); let reason = &result.rejected[0].reason; assert!( reason.contains(&format!("an OAuth grant's {column} is written once, with its row")), "the rejection names the rule, got {reason:?}" ); } /// RULE: An OAuth grant's minter and client are written once, with the row — a later patch that changes either, or adds a minter to a grant that has none, is rejected. #[test] fn a_grant_s_minter_and_client_are_written_once_with_its_row() { let db = file(); let born = fold_ops(&db, &[consent_minted_by(1, STUDY, 0, WRITER)]).expect("folds"); assert!(born.rejected.is_empty(), "{:?}", born.rejected); assert_eq!(row(&db).text("minted_by"), Some(WRITER)); // The same op again is a replay, not a rewrite. let again = fold_ops(&db, &[consent_minted_by(1, STUDY, 0, WRITER)]).expect("folds"); assert!(again.rejected.is_empty(), "{:?}", again.rejected); let moved = op(2, KITCHEN, 5_000, json!({ "minted_by": "another-device" })); rewrite_refused(&fold_ops(&db, &[moved]).expect("folds"), "minted_by"); let cleared = op(3, KITCHEN, 6_000, json!({ "minted_by": JsonValue::Null })); rewrite_refused(&fold_ops(&db, &[cleared]).expect("folds"), "minted_by"); let client = op(4, KITCHEN, 7_000, json!({ "client_id": "another-client" })); rewrite_refused(&fold_ops(&db, &[client]).expect("folds"), "client_id"); assert_eq!(row(&db).text("minted_by"), Some(WRITER)); assert_eq!(row(&db).text("client_id"), Some("an-invented-client")); // A grant from before the rung has no minter, and none is added later. let old = file(); fold_ops(&old, &[consent(1, STUDY, 0)]).expect("folds"); let adopted = op(2, KITCHEN, 5_000, json!({ "minted_by": WRITER })); rewrite_refused(&fold_ops(&old, &[adopted]).expect("folds"), "minted_by"); assert_eq!(row(&old).text("minted_by"), None); } #[test] fn a_consent_with_no_digest_travels_as_a_null_and_lands() { // The exchange hands a row over as a base op carrying EVERY column, so a // consent minted before version 45 — or for a client that takes no // refresh token — arrives saying `refresh_digest: null`. That clears // nothing, and refusing it would refuse the consent on every peer. let db = file(); let whole = consent_with(1, STUDY, 0, json!({ "refresh_digest": JsonValue::Null })); let landed = fold_ops(&db, std::slice::from_ref(&whole)).expect("folds"); assert!(landed.rejected.is_empty(), "{:?}", landed.rejected); assert_eq!(row(&db).text("refresh_digest"), None); // And again, once it is there. let again = fold_ops(&db, &[whole]).expect("folds"); assert!(again.rejected.is_empty(), "{:?}", again.rejected); } // ── slice 5b-i step 5: every rotation is also a fact ─────────────────────── /// The fact id a rotation of the test grant to `generation` takes: these /// files derive under the workspace's own id, as every file made after the /// stop does. fn rotation_id(generation: u32) -> String { cotton_store::protocol::derived_id::grant_rotation_id( &cotton_store::file_identity::Namespace::for_tests(WORKSPACE), GRANT, generation, ) } /// One rotation as a Mac's act writes it: the grant row moved, and its fact. fn rotation(n: u32, author: &str, ms: i64, generation: u32, token: &str, at: &str, fill: char) -> [CottonOp; 2] { let row_move = op( n, author, ms, json!({ "refresh_generation": generation, "refresh_rotated_at": at, "refresh_digest": digest_by(generation, fill, WRITER), }), ); let id = rotation_id(generation); let body = patch(json!({ "id": id, "workspace_id": WORKSPACE, "grant_id": GRANT, "generation": generation, "digest": cotton_store::grant_rotations::token_digest(token), "rotated_at": at, "actor": "job:oauth", })) .expect("a patch"); let fact = receipt_op( Change::create(cotton_store::grant_rotations::TABLE, &id, body), n + 1, author, ms + 1, ); [row_move, fact] } /// The highest generation the rotation facts reach, with its digest. fn highest_fact(db: &Driver) -> Option<(i64, String)> { db.get( "SELECT generation, digest FROM cotton_grant_rotations WHERE grant_id = ? ORDER BY generation DESC LIMIT 1", &[text(GRANT)], ) .expect("reads") .map(|row| { ( row.int("generation").expect("a generation"), row.text("digest").expect("a digest").to_string(), ) }) } /// RULE: Of two OAuth refresh rotations, the higher generation's row value and fact stand on every file in either arrival order, even when the lower one is stamped later by a Mac that had not heard. #[test] fn a_stale_generation_never_replaces_a_newer_one_in_any_arrival_order() { // The study Mac moved the chain to 2; the kitchen Mac, a step behind, // moved it to 1 LATER by the clock. Two files, each hearing the two acts // in the other order, end on generation 2 — row and facts alike — and // neither reads a fork: the two facts are at two generations. let newer = rotation(10, STUDY, 5_000, 2, "invented-token-two", EARLY, 'b'); let stale = rotation(20, KITCHEN, 9_000, 1, "invented-token-one", LATER, 'a'); for (name, first, second) in [("newer first", &newer, &stale), ("stale first", &stale, &newer)] { let db = file(); let born = fold_ops(&db, &[consent_with_digest(1, STUDY, 0, &digest(0, 'f'))]).expect("folds"); assert!(born.rejected.is_empty(), "{:?}", born.rejected); for act in [first, second] { let result = fold_ops(&db, act).expect("folds"); assert!(result.rejected.is_empty(), "{name}: {:?}", result.rejected); assert!(result.parked.is_empty(), "{name}: {:?}", result.parked); } let row = row(&db); assert_eq!(row.int("refresh_generation"), Some(2), "{name}"); assert_eq!( row.text("refresh_digest"), Some(digest_by(2, 'b', WRITER).as_str()), "{name}" ); assert_eq!( highest_fact(&db), Some((2, cotton_store::grant_rotations::token_digest("invented-token-two"))), "{name}" ); assert!( !cotton_store::grant_rotations::forked(&db, GRANT).expect("reads"), "{name}: two generations are a chain, not a fork" ); } } /// RULE: Two OAuth refresh rotations of one grant to one generation with different tokens leave a standing fact and a parked twin on both files, and grant_rotations::forked reads that as reuse; the same token twice does not. #[test] fn two_digests_at_one_generation_read_as_a_fork_on_both_files() { for (name, kitchen_token, reuse) in [ ("two tokens", "invented-token-kitchen", true), ("one token, two Macs", "invented-token-study", false), ] { let study = file(); let kitchen = file(); let born = consent_with_digest(1, STUDY, 0, &digest(0, 'f')); fold_ops(&study, std::slice::from_ref(&born)).expect("folds"); fold_ops(&kitchen, &[born]).expect("folds"); // Each Mac moves the chain to 1, unaware of the other. let at_study = rotation(10, STUDY, 5_000, 1, "invented-token-study", EARLY, 'a'); let at_kitchen = rotation(20, KITCHEN, 6_000, 1, kitchen_token, LATER, 'a'); fold_ops(&study, &at_study).expect("folds"); fold_ops(&kitchen, &at_kitchen).expect("folds"); // ...and then they meet. fold_ops(&study, &at_kitchen).expect("folds"); fold_ops(&kitchen, &at_study).expect("folds"); for (side, db) in [("study", &study), ("kitchen", &kitchen)] { assert_eq!( cotton_store::grant_rotations::forked(db, GRANT).expect("reads"), reuse, "{name}, on the {side} file" ); let standing = db .get( "SELECT actor, rotated_at FROM cotton_grant_rotations WHERE id = ?", &[text(&rotation_id(1))], ) .expect("reads") .expect("one fact stands"); assert_eq!( standing.text("rotated_at"), Some(EARLY), "{name}: the earlier stamp stands on the {side} file" ); } } }