use super::*; use crate::signed::{KeySigner, ReceiptSigner}; use crate::test_support::{fold_create, seeded_file, WORKSPACE}; use std::sync::Arc; const NOW: i64 = 1_791_000_000_000; fn ids() -> impl crate::outbox::IdSource { crate::protocol::ulid::Monotonic::new(crate::test_support::counter_seed()) } const TARGET_HOST: &str = "https://synthetic-phone-handover.example"; fn owner_grant(offer: &Offer) -> crate::serving_grant::ServingGrant { let owner = KeySigner::of_seed(90); let mut grant = crate::serving_grant::ServingGrant { kind: crate::serving_grant::GrantKind::ServingGrant, database_id: offer.database.clone(), source_host: "https://synthetic-source.example".into(), source_epoch: offer.epoch, target_host: offer.target_host.clone(), target_key_fingerprint: crate::serving_grant::fingerprint(&offer.target).unwrap(), new_epoch: offer.epoch + 1, grant_id: "synthetic-move".into(), issued_at: crate::protocol::js::to_iso_string(NOW + 40).unwrap(), owner_signature: String::new(), }; grant.owner_signature = URL_SAFE_NO_PAD.encode(owner.sign(&grant.signing_bytes()).unwrap()); grant } fn fixture() -> (Driver, Arc, Arc) { let phone = Arc::new(KeySigner::of_seed(71)); let mac = Arc::new(KeySigner::of_seed(72)); let db = seeded_file(&phone.device_key()).signed_by(phone.clone()); let mut random = ids(); crate::mint::first_author( &db, &phone.device_key(), None, AuthorReason::First, &Clock::wall(NOW), &mut random, Held::Served, ) .unwrap(); for (key, platform) in [(&phone, "ios"), (&mac, "mac")] { fold_create( &db, "cotton_devices", &key.device_key(), serde_json::json!({ "id":key.device_key(), "workspace_id":WORKSPACE, "device_id":key.device_key(), "name":"Synthetic device", "platform":platform, "approved_at":"2026-10-03T00:00:00.000Z", "approved_by_device":"self", "created_at":"2026-10-03T00:00:00.000Z", "updated_at":"2026-10-03T00:00:00.000Z", // The key a Mac dials the relay with: the serving fact the // grant writes records it, never null. "relay_identity_key": (platform == "mac").then_some("synthetic-relay-key-of-the-mac") }), "device:seed", 10, ); } let owner = KeySigner::of_seed(90).device_key(); db.run("INSERT INTO cotton_admissions (id,workspace_id,person_key,person_name,rights,admitted_by_person,p_sig,admitted_at,_hlc) VALUES ('synthetic-owner-birth',?,?,'Synthetic owner','owner',?,'synthetic-birth','2026-10-03T00:00:00.000Z','1791000000015:0000:device:seed')", &[text(WORKSPACE),text(&owner),text(&owner)]).unwrap(); found(&db, WORKSPACE, &Clock::wall(NOW + 10), &mut random).unwrap(); (db, phone, mac) } fn copy(db: &Driver, path: &std::path::Path, key: Arc) -> Driver { db.run("VACUUM INTO ?", &[text(path.to_str().unwrap())]) .unwrap(); Driver::open(path).unwrap().signed_by(key) } fn todo(db: &Driver, id: &str, at: i64, held: Held) -> crate::mint::Minted { crate::mint::mint( db, &Act { actor: Actor::device_job(crate::actor::JobName::named("test").unwrap()), verb: "test".into(), history: History::None, changes: vec![Change::create( "cotton_todos", id, serde_json::json!({ "workspace_id":WORKSPACE,"title":id,"created_at":"2026-10-03T00:00:00.000Z", "updated_at":"2026-10-03T00:00:00.000Z" }) .as_object() .unwrap() .clone(), )], }, &Clock::wall(at), &mut ids(), held, ) .unwrap() } // RULE: The phone commits one chosen server before copying; its applied writes during that copy queue under a new client author and survive the shared fold, because the old serving author's cutoff must never discard a phone edit. #[test] fn serving_handover_keeps_writes_before_during_and_after_the_whole_copy() { let (phone, phone_key, mac_key) = fixture(); let tmp = tempfile::tempdir().unwrap(); todo(&phone, "before", NOW + 20, Held::Served); let staging = copy(&phone, &tmp.path().join("offer.db"), mac_key.clone()); let offer = prepare( &staging, WORKSPACE, TARGET_HOST, &Clock::wall(NOW + 30), &mut ids(), ) .unwrap(); assert_eq!( activate(&staging, &offer).unwrap_err().code(), "handover_not_granted" ); assert!( crate::serving::served_elsewhere(&staging, WORKSPACE, Some(&mac_key.device_key())) .unwrap() .is_some() ); let granted = relinquish( &phone, &offer, &owner_grant(&offer), &Clock::wall(NOW + 40), &mut ids(), ) .unwrap(); assert_eq!(granted.epoch, 2); assert_eq!( relinquish( &phone, &offer, &owner_grant(&offer), &Clock::wall(NOW + 41), &mut ids() ) .unwrap(), granted ); assert!( crate::serving::served_elsewhere(&phone, WORKSPACE, Some(&phone_key.device_key())) .unwrap() .is_some() ); todo(&phone, "during", NOW + 50, Held::Served); let target = copy(&phone, &tmp.path().join("whole.db"), mac_key.clone()); activate(&target, &offer).unwrap(); activate(&target, &offer).unwrap(); // Even the chosen device cannot redirect the phone to a host the owner did not sign. let mut proof = WholeCopy { offer: offer.clone(), grant: owner_grant(&offer), sha256: "synthetic-hash".into(), bytes: 1, signature: String::new(), }; proof.signature = URL_SAFE_NO_PAD.encode( phone_key .sign(&crate::signed::signed_string(WORKSPACE, &proof.intent())) .unwrap(), ); let mut wrong_host = Ready { origin: "https://ungranted.example".into(), signature: String::new(), }; wrong_host.signature = URL_SAFE_NO_PAD.encode( mac_key .sign(&crate::signed::signed_string( WORKSPACE, &wrong_host.intent(&proof), )) .unwrap(), ); assert_eq!( wrong_host.confirm(&phone, &proof).unwrap_err().code(), "serving_grant_wrong_target_host" ); let after = todo(&phone, "after", NOW + 60, Held::Served); assert!(!after.held, "an applied write travels immediately"); assert!(crate::serving::past_the_cut_off( &phone, &crate::mint::file_author(&phone).unwrap(), &after.ops[0].hlc ) .unwrap() .is_none()); let outbox: Vec<_> = phone .all("SELECT * FROM _outbox ORDER BY hlc", &[]) .unwrap() .iter() .map(|row| crate::stored::outbox_row(row).unwrap()) .collect(); assert!(outbox.iter().any(|op| op.row_id == "during")); assert!(outbox.iter().any(|op| op.row_id == "after")); let folded = crate::fold::fold_ops(&target, &outbox).unwrap(); assert!(folded.rejected.is_empty(), "{folded:?}"); for id in ["before", "during", "after"] { assert!(target .get("SELECT id FROM cotton_todos WHERE id = ?", &[text(id)]) .unwrap() .is_some()); } assert_eq!( crate::serving::serving_fact(&target, WORKSPACE) .unwrap() .unwrap() .device_credential_id, mac_key.device_key() ); assert!(crate::serving::is_serving_author( &target, &crate::mint::file_author(&target).unwrap() ) .unwrap()); let engine = Act { actor: Actor::Job(crate::actor::JobName::named("test").unwrap()), verb: "test".into(), history: History::None, changes: vec![Change::create( "cotton_todos", "stale-engine", serde_json::json!({"workspace_id":WORKSPACE,"title":"stale engine"}) .as_object() .unwrap() .clone(), )], }; let refused = crate::mint::mint( &phone, &engine, &Clock::wall(NOW + 70), &mut ids(), Held::Served, ) .unwrap_err(); assert!(refused.to_string().contains("not_served_here")); } // RULE: A target that keeps NO copy of the database — a Mac that has just joined as a device — prepares its offer from its own device key and the source's seed alone: the offer is the one a copy would give (its author first-stamped above the source file's clock), the source relinquishes and the whole copy activates under it exactly as for an offer prepared on a copy, the scratch file is gone afterwards, and a seed naming this device as the server or another schema is refused. #[test] fn a_target_that_keeps_no_copy_prepares_its_offer_from_the_sources_seed() { let (phone, _, mac_key) = fixture(); let tmp = tempfile::tempdir().unwrap(); todo(&phone, "before", NOW + 20, Held::Served); let seeded = seed(&phone, WORKSPACE).unwrap(); assert_eq!((seeded.epoch, seeded.source.as_str()), (1, KeySigner::of_seed(71).device_key().as_str())); let scratch = tmp.path().join("offer.db"); let offer = prepare_from_seed(&scratch, &seeded, TARGET_HOST, mac_key.clone(), &Clock::wall(NOW + 30), &mut ids()).unwrap(); assert!(!scratch.exists(), "the scratch file is the target's for a moment, and gone"); offer.verify().unwrap(); assert_eq!((offer.epoch, offer.source.clone(), offer.target.clone()), (1, seeded.source.clone(), mac_key.device_key())); assert!( offer.author.hlc.as_str() > seeded.last_hlc.as_deref().unwrap(), "the author starts above the source file's clock" ); relinquish(&phone, &offer, &owner_grant(&offer), &Clock::wall(NOW + 40), &mut ids()).unwrap(); let target = copy(&phone, &tmp.path().join("whole.db"), mac_key.clone()); let granted = activate(&target, &offer).unwrap(); assert_eq!(granted.epoch, 2); assert_eq!(crate::mint::file_author(&target).unwrap(), offer.author.row_id); let mut serving_here = seeded.clone(); serving_here.source = mac_key.device_key(); assert_eq!( prepare_from_seed(&scratch, &serving_here, TARGET_HOST, mac_key.clone(), &Clock::wall(NOW + 50), &mut ids()).unwrap_err().code(), "already_serving" ); let mut older = seeded; older.schema_version -= 1; assert_eq!( prepare_from_seed(&scratch, &older, TARGET_HOST, mac_key, &Clock::wall(NOW + 50), &mut ids()).unwrap_err().code(), "schema_differs" ); assert!(!scratch.exists()); } // RULE: A retry cannot choose a second Mac or accept a forged or stale intent; the serving phone alone grants the next epoch so interruption cannot create two servers. #[test] fn serving_handover_refuses_forged_wrong_epoch_and_unapproved_targets_without_writes() { let (phone, _, mac_key) = fixture(); let tmp = tempfile::tempdir().unwrap(); let staging = copy(&phone, &tmp.path().join("offer.db"), mac_key); let offer = prepare( &staging, WORKSPACE, TARGET_HOST, &Clock::wall(NOW + 30), &mut ids(), ) .unwrap(); let mut forged = offer.clone(); forged.epoch += 1; assert_eq!( relinquish( &phone, &forged, &owner_grant(&offer), &Clock::wall(NOW + 40), &mut ids() ) .unwrap_err() .code(), "invalid_handover_offer" ); assert_eq!( crate::serving::serving_fact(&phone, WORKSPACE) .unwrap() .unwrap() .epoch, 1 ); phone .run( "UPDATE cotton_devices SET revoked_at = '2026-10-03T00:00:00Z' WHERE device_id = ?", &[text(&offer.target)], ) .unwrap(); assert_eq!( relinquish( &phone, &offer, &owner_grant(&offer), &Clock::wall(NOW + 40), &mut ids() ) .unwrap_err() .code(), "handover_target_not_approved" ); } // RULE: An applied edit awaiting checked time cannot be stranded inside a transferred snapshot; the phone keeps serving until its existing release pass can make that edit travel. #[test] fn serving_handover_keeps_authority_until_applied_held_edits_can_travel() { let (phone, _, mac_key) = fixture(); let tmp = tempfile::tempdir().unwrap(); let staging = copy(&phone, &tmp.path().join("offer.db"), mac_key); let offer = prepare( &staging, WORKSPACE, TARGET_HOST, &Clock::wall(NOW + 30), &mut ids(), ) .unwrap(); phone .run( "UPDATE _writes SET held = 1 WHERE tbl = 'cotton_workspaces'", &[], ) .unwrap(); assert_eq!( relinquish( &phone, &offer, &owner_grant(&offer), &Clock::wall(NOW + 40), &mut ids() ) .unwrap_err() .code(), "handover_writes_held" ); assert_eq!( crate::serving::serving_fact(&phone, WORKSPACE) .unwrap() .unwrap() .epoch, 1 ); } // RULE: Every server move retains the same owner proof; a retry is harmless, // a different act for the same epoch loses, and only the named target activates. #[test] fn serving_grant_commits_once_and_a_unit_only_adopts_the_retained_epoch() { use crate::serving_grant::{self, MoveStatus, Refused}; let (source, source_key, target_key) = fixture(); let tmp = tempfile::tempdir().unwrap(); let preliminary = copy( &source, &tmp.path().join("preliminary.db"), target_key.clone(), ); let offer = prepare( &preliminary, WORKSPACE, TARGET_HOST, &Clock::wall(NOW + 30), &mut ids(), ) .unwrap(); let grant = owner_grant(&offer); let commit = |grant: &ServingGrant| { serving_grant::commit( &source, grant, &grant.source_host, &target_key.device_key(), "synthetic-relay-key-of-the-target", None, &Clock::wall(NOW + 40), &mut ids(), ) }; assert_eq!( serving_grant::commit( &source, &grant, "https://wrong-source.example", &target_key.device_key(), "synthetic-relay-key-of-the-target", None, &Clock::wall(NOW + 40), &mut ids() ), Err(Refused::NotCurrentServer) ); assert_eq!( serving_grant::commit( &preliminary, &grant, &grant.source_host, &target_key.device_key(), "synthetic-relay-key-of-the-target", None, &Clock::wall(NOW + 40), &mut ids() ), Err(Refused::NotCurrentServer) ); assert_eq!( serving_grant::activate( &preliminary, &grant, TARGET_HOST, &Clock::wall(NOW + 50), &mut ids() ), Err(Refused::NotRetained) ); let mut forged = grant.clone(); forged.owner_signature = URL_SAFE_NO_PAD.encode(source_key.sign(&forged.signing_bytes()).unwrap()); assert_eq!(commit(&forged), Err(Refused::OwnerSignatureInvalid)); assert!(!serving_grant::source_archived(&source, WORKSPACE).unwrap()); commit(&grant).unwrap(); assert!(serving_grant::source_archived(&source, WORKSPACE).unwrap()); commit(&grant).unwrap(); assert_eq!( serving_grant::retained(&source, WORKSPACE).unwrap(), Some(grant.clone()) ); let mut competing = grant.clone(); competing.grant_id = "another-owner-act".into(); competing.owner_signature = URL_SAFE_NO_PAD.encode( KeySigner::of_seed(90) .sign(&competing.signing_bytes()) .unwrap(), ); assert_eq!(commit(&competing), Err(Refused::EpochConflict)); let target = copy(&source, &tmp.path().join("unit.db"), target_key); assert_eq!( serving_grant::activate( &source, &grant, TARGET_HOST, &Clock::wall(NOW + 50), &mut ids() ), Err(Refused::WrongTargetKey) ); assert_eq!( serving_grant::activate( &target, &grant, "https://wrong.example", &Clock::wall(NOW + 50), &mut ids() ), Err(Refused::WrongTargetHost) ); assert!(serving_grant::source_archived(&target, WORKSPACE).unwrap()); // RULE: Activation changes local custody, never the existing device or // receipt rows the new unit inherited from the source. let devices = target .all("SELECT * FROM cotton_devices ORDER BY id", &[]) .unwrap(); let receipts = target .all("SELECT * FROM _writes ORDER BY op_id", &[]) .unwrap(); let tombstones = target .all("SELECT * FROM _tombstones ORDER BY op_id", &[]) .unwrap(); let author = serving_grant::activate( &target, &grant, TARGET_HOST, &Clock::wall(NOW + 50), &mut ids(), ) .unwrap(); assert_eq!( serving_grant::activate( &target, &grant, TARGET_HOST, &Clock::wall(NOW + 51), &mut ids() ) .unwrap(), author ); assert!(crate::serving::is_serving_author(&target, &author).unwrap()); assert!(!serving_grant::source_archived(&target, WORKSPACE).unwrap()); assert_eq!( target .all("SELECT * FROM cotton_devices ORDER BY id", &[]) .unwrap(), devices ); assert_eq!( target .all("SELECT * FROM _tombstones ORDER BY op_id", &[]) .unwrap(), tombstones ); for receipt in receipts { assert_eq!( target .get( "SELECT * FROM _writes WHERE op_id = ?", &[text(receipt.text("op_id").unwrap())] ) .unwrap(), Some(receipt) ); } assert_eq!( crate::serving::serving_fact(&target, WORKSPACE) .unwrap() .unwrap() .epoch, 2 ); assert!( crate::serving::served_elsewhere(&source, WORKSPACE, Some(&source_key.device_key())) .unwrap() .is_some() ); // The exact expiry boundary is shared by every relay; it never falls back to serving. let issued = NOW + 40; assert!(matches!( serving_grant::moved( &source, WORKSPACE, &grant.source_host, issued + 30 * 24 * 60 * 60 * 1000 - 1 ) .unwrap(), Some(MoveStatus::Moved(_)) )); assert!(matches!( serving_grant::moved( &source, WORKSPACE, &grant.source_host, issued + 30 * 24 * 60 * 60 * 1000 ) .unwrap(), Some(MoveStatus::Expired(_)) )); } // RULE: A later owner handover cannot invalidate the serving grant already // committed by the previous owner. Authority is resolved at the fact's HLC, // from the file's own admission chain; a journal cannot supply another key. #[test] fn a_retained_serving_grant_survives_a_later_owner_handover() { use crate::serving_grant; let (source, _, target_key) = fixture(); let tmp = tempfile::tempdir().unwrap(); let preliminary = copy( &source, &tmp.path().join("preliminary.db"), target_key.clone(), ); let offer = prepare( &preliminary, WORKSPACE, TARGET_HOST, &Clock::wall(NOW + 30), &mut ids(), ) .unwrap(); let grant = owner_grant(&offer); serving_grant::commit( &source, &grant, &grant.source_host, &target_key.device_key(), "synthetic-relay-key-of-the-target", None, &Clock::wall(NOW + 40), &mut ids(), ) .unwrap(); let target = copy(&source, &tmp.path().join("unit.db"), target_key.clone()); let activated = serving_grant::activate( &target, &grant, TARGET_HOST, &Clock::wall(NOW + 50), &mut ids(), ) .unwrap(); let old_owner = KeySigner::of_seed(90).device_key(); let new_owner = KeySigner::of_seed(91).device_key(); for db in [&source, &target] { db.run("INSERT INTO cotton_admissions(id,workspace_id,person_key,person_name,rights,admitted_by_person,p_sig,admitted_at,_hlc) VALUES ('synthetic-owner-handover',?,?,'Next synthetic owner','owner',?,'synthetic-owner-act','2026-10-03T00:01:00.000Z',?)", &[text(WORKSPACE),text(&new_owner),text(&old_owner),text(&format!("{}:0000:synthetic-owner-author",NOW+100))]).unwrap(); assert_eq!( crate::membership::owner(db).unwrap(), Some(new_owner.clone()) ); grant.verify_copy(db).unwrap(); serving_grant::verify_retained(db, &grant, TARGET_HOST, &target_key.device_key()).unwrap(); let fact = crate::serving::serving_fact(db, WORKSPACE) .unwrap() .unwrap(); let row = db .get( "SELECT * FROM _writes WHERE tbl = 'cotton_serving_machine' AND row_id = ?", &[text(&fact.id)], ) .unwrap() .unwrap(); let op = crate::stored::receipt_row(&row).unwrap(); let receipt = crate::canonical::decode(op.receipt.as_bytes()).unwrap(); assert!(serving_grant::fact_refusal( db, &receipt.fields, &receipt.author, &receipt.row_id, &receipt.stamp ) .unwrap() .is_none()); } assert!(serving_grant::source_archived(&source, WORKSPACE).unwrap()); assert!(!serving_grant::source_archived(&target, WORKSPACE).unwrap()); assert_eq!( serving_grant::activate( &target, &grant, TARGET_HOST, &Clock::wall(NOW + 200), &mut ids() ) .unwrap(), activated ); assert!( serving_grant::moved(&source, WORKSPACE, &grant.source_host, NOW + 200) .unwrap() .is_some() ); // A former owner cannot issue a fresh grant after giving ownership away. let mut fresh = grant.clone(); fresh.source_epoch = 2; fresh.new_epoch = 3; fresh.owner_signature = URL_SAFE_NO_PAD.encode(KeySigner::of_seed(90).sign(&fresh.signing_bytes()).unwrap()); assert_eq!( fresh.verify_copy(&target), Err(serving_grant::Refused::OwnerSignatureInvalid) ); // Changing the in-file issuer to today's owner cannot rewrite who was // authorized when the original grant receipt was minted. target .run( "UPDATE cotton_serving_machine SET confirmed_by = ? WHERE epoch = 2", &[text(&new_owner)], ) .unwrap(); assert!( serving_grant::verify_retained(&target, &grant, TARGET_HOST, &target_key.device_key()) .is_err() ); let mut unhistorical = grant.clone(); unhistorical.owner_signature = URL_SAFE_NO_PAD.encode( KeySigner::of_seed(91) .sign(&unhistorical.signing_bytes()) .unwrap(), ); target .run( "UPDATE cotton_serving_machine SET start_positions = ? WHERE epoch = 2", &[ serde_json::json!({"positions":{},"skipped":[],"serving_grant":unhistorical}) .to_string() .into(), ], ) .unwrap(); assert_eq!( unhistorical.verify_copy(&target), Err(serving_grant::Refused::OwnerSignatureInvalid) ); } // RULE: The joining Mac's Offer is preparation, never a second grant. Even // a valid target signature cannot replace the owner's shared ServingGrant; // refusal leaves the phone serving and its receipts and author untouched. #[test] fn serving_handover_offer_cannot_substitute_for_the_owner_grant() { let (phone, _, mac_key) = fixture(); let tmp = tempfile::tempdir().unwrap(); let staging = copy(&phone, &tmp.path().join("preliminary.db"), mac_key.clone()); let offer = prepare( &staging, WORKSPACE, TARGET_HOST, &Clock::wall(NOW + 30), &mut ids(), ) .unwrap(); offer.verify().unwrap(); let before_author = crate::mint::file_author(&phone).unwrap(); let before_receipts = phone .all("SELECT op_id FROM _writes ORDER BY op_id", &[]) .unwrap() .iter() .map(|row| row.text("op_id").unwrap().to_string()) .collect::>(); let grant = owner_grant(&offer); let mut target_signed = grant.clone(); target_signed.owner_signature = URL_SAFE_NO_PAD.encode(mac_key.sign(&target_signed.signing_bytes()).unwrap()); assert_eq!( relinquish( &phone, &offer, &target_signed, &Clock::wall(NOW + 40), &mut ids() ) .unwrap_err() .code(), "serving_grant_owner_signature_invalid" ); assert!(crate::serving_grant::retained(&phone, WORKSPACE) .unwrap() .is_none()); assert_eq!( crate::serving::serving_fact(&phone, WORKSPACE) .unwrap() .unwrap() .epoch, offer.epoch ); assert_eq!(crate::mint::file_author(&phone).unwrap(), before_author); let after_receipts = phone .all("SELECT op_id FROM _writes ORDER BY op_id", &[]) .unwrap() .iter() .map(|row| row.text("op_id").unwrap().to_string()) .collect::>(); assert_eq!(after_receipts, before_receipts); relinquish(&phone, &offer, &grant, &Clock::wall(NOW + 40), &mut ids()).unwrap(); assert_eq!( crate::serving_grant::retained(&phone, WORKSPACE).unwrap(), Some(grant) ); assert!(crate::serving_grant::source_archived(&phone, WORKSPACE).unwrap()); }