//! A database joined at another person's Mac: recorded with its origin and //! its Mac, listed by that Mac alone, and pinned to it. use std::sync::Arc; use cotton_core::device::server_id::{server_id_of, SERVER_ID_HEADER}; use super::*; use crate::connection::list::{ListedDatabase, Listing}; use crate::connection::{ConnectionFile, ConnectionMode}; use crate::identity::DeviceIdentity; use crate::seams::{FixedClock, SeededRandom}; use crate::test_support::{hold_joined, temp_layout, write_record, WORKSPACE}; use crate::transport::refusal::RefusalMemory; use crate::transport::scripted::{Reply, ScriptedExchange}; use crate::transport::signed_http::OTHER_SERVER; use crate::transport::signer::RequestSigner; use crate::transport::{ClientRequest, Exchange, ServerAddress, ServerFetch, SignedHttp}; const NOW: &str = "2026-09-08T10:00:00.000Z"; const HOME_PLACE: &str = "22222222-2222-4222-8222-222222222222"; const GARDEN: &str = "33333333-3333-4333-8333-333333333333"; const OTHER_MAC: &str = "https://garden.relay.cottondb.com"; const OTHER_MAC_KEY: &str = "synthetic-mac-device-key"; fn listing(ids: &[&str]) -> Listing { Listing { databases: ids .iter() .map(|id| ListedDatabase { id: (*id).to_string(), name: "A synthetic database".to_string(), kind: "shared".to_string(), schema_version: 1, }) .collect(), } } /// The transport a joined database gets: its own address, its own refusal /// memory, pinned to the Mac the invite named. fn pinned(replies: Vec) -> (SignedHttp, Arc, Arc) { let exchange = ScriptedExchange::new(replies); let clock = FixedClock::default_start(); let signer = RequestSigner::new( Arc::new(DeviceIdentity::from_secret(&[7u8; 32]).expect("an identity")), Arc::new(clock.clone()), Arc::new(SeededRandom::default()), ); let refusals = Arc::new(RefusalMemory::default()); let http = SignedHttp::new( signer, Arc::new(JoinedAddress::at(OTHER_MAC)) as Arc, Arc::clone(&refusals), Arc::clone(&exchange) as Arc, Arc::new(clock), ) .pinned_to(OTHER_MAC_KEY); (http, exchange, refusals) } fn from(device_id: &str, reply: Reply) -> Reply { reply.with_header(SERVER_ID_HEADER, &server_id_of(device_id)) } #[test] fn a_database_joined_at_another_mac_is_grouped_by_its_origin_and_its_mac() { let (_dir, layout) = temp_layout(); write_record(&layout, WORKSPACE, ConnectionMode::Remote, &[HOME_PLACE]); hold_joined(&layout, GARDEN, OTHER_MAC, OTHER_MAC_KEY); let connection = ConnectionFile::at(layout.connection_json()); let record = connection.read_record().expect("a record"); let entry = record.places.iter().find(|place| place.id == GARDEN).expect("held"); assert_eq!(entry.origin.as_deref(), Some(OTHER_MAC)); assert_eq!(entry.server_device_id.as_deref(), Some(OTHER_MAC_KEY)); assert_eq!(connection.mine_id().as_deref(), Some(WORKSPACE)); let groups = origin_groups(&record); assert_eq!(groups[0].origin, None); assert_eq!(groups[0].databases, [WORKSPACE, HOME_PLACE]); assert_eq!(groups[1].origin.as_deref(), Some(OTHER_MAC)); assert_eq!(groups[1].databases, [GARDEN]); } /// RULE: A server's list of databases changes only the databases held at that server: the household's list never drops one joined at another person's Mac, and another Mac's list never adds one. #[test] fn each_servers_list_speaks_only_for_the_databases_held_there() { let (_dir, layout) = temp_layout(); write_record(&layout, WORKSPACE, ConnectionMode::Remote, &[HOME_PLACE]); hold_joined(&layout, GARDEN, OTHER_MAC, OTHER_MAC_KEY); let connection = ConnectionFile::at(layout.connection_json()); // The household lists its own two and has never heard of the garden. let home = connection .apply_listing(&listing(&[WORKSPACE, HOME_PLACE]), NOW) .expect("applied"); assert!(home.gone.is_empty(), "{home:?}"); // The other Mac lists the garden and a database nobody invited this // device to: nothing is new, and the household's entry is not its to drop. let stranger = "99999999-9999-4999-8999-999999999999"; let other = connection .apply_listing_at(OTHER_MAC, &listing(&[GARDEN, stranger]), NOW) .expect("applied"); assert_eq!(other, crate::connection::list::ListChange::default()); // It stops listing the garden: that entry alone goes unavailable. let dropped = connection .apply_listing_at(OTHER_MAC, &listing(&[]), NOW) .expect("applied"); assert_eq!(dropped.gone, [GARDEN]); let record = connection.read_record().expect("a record"); assert!(record.places.iter().find(|p| p.id == HOME_PLACE).expect("held").available); } #[test] fn a_removal_is_kept_through_a_listing() { let (_dir, layout) = temp_layout(); write_record(&layout, WORKSPACE, ConnectionMode::Remote, &[HOME_PLACE]); hold_joined(&layout, GARDEN, OTHER_MAC, OTHER_MAC_KEY); let connection = ConnectionFile::at(layout.connection_json()); assert!(connection.mark_removed(GARDEN, NOW, Some("Asha")).expect("written")); connection .apply_listing_at(OTHER_MAC, &listing(&[GARDEN]), NOW) .expect("applied"); let entry = |connection: &ConnectionFile| { connection .read_record() .expect("a record") .places .into_iter() .find(|place| place.id == GARDEN) .expect("kept") }; assert!(!entry(&connection).syncs(), "a listing never lifts a removal"); assert_eq!(entry(&connection).removed_by.as_deref(), Some("Asha")); } /// RULE: A database joined at another person's Mac is signed to that Mac only: a server that answers as any other machine is sent nothing, and nothing it says is recorded. #[test] fn a_joined_entry_refuses_a_mac_whose_key_is_not_the_pinned_one() { // Another Mac answers the name: asked who it is, unsigned, and then // nothing is signed to it. let (http, exchange, refusals) = pinned(vec![from("some-other-mac", Reply::ok("{}"))]); let refused = http .call(ClientRequest::get("/v1/me/databases")) .expect_err("not the pinned Mac"); assert_eq!(refused.code.as_deref(), Some(OTHER_SERVER)); assert_eq!(exchange.calls(), 1); assert_eq!(exchange.only().path, "/health"); assert!(exchange .only() .headers .iter() .all(|(name, _)| !name.to_ascii_lowercase().starts_with("x-cotton-device"))); assert!(refusals.standing().is_none()); // A server that names no machine at all is not the pinned one either. let (http, exchange, _) = pinned(vec![Reply::ok("{}")]); let refused = http .call(ClientRequest::get("/v1/me/databases")) .expect_err("it did not say"); assert_eq!(refused.code.as_deref(), Some(OTHER_SERVER)); assert_eq!(exchange.calls(), 1); // The pinned Mac answered the check, and then the name passed to another // Mac that says this device is revoked: its verdict is not taken. let (http, exchange, refusals) = pinned(vec![ from(OTHER_MAC_KEY, Reply::ok("{}")), from( "some-other-mac", Reply::json(403, r#"{"error":"revoked","code":"device_revoked"}"#), ), from("some-other-mac", Reply::ok("{}")), ]); let refused = http .call(ClientRequest::get("/v1/me/databases")) .expect_err("another Mac's verdict"); assert_eq!(refused.code.as_deref(), Some(OTHER_SERVER)); assert!(refusals.standing().is_none(), "nothing was recorded"); // And the origin is asked again who it is before anything else is signed. let again = http .call(ClientRequest::get("/v1/me/databases")) .expect_err("still another Mac"); assert_eq!(again.code.as_deref(), Some(OTHER_SERVER)); assert_eq!(exchange.nth(2).path, "/health"); } #[test] fn the_pinned_mac_is_asked_once_and_then_signed_to() { let (http, exchange, _) = pinned(vec![ from(OTHER_MAC_KEY, Reply::ok("{}")), from(OTHER_MAC_KEY, Reply::ok(r#"{"databases":[]}"#)), from(OTHER_MAC_KEY, Reply::ok(r#"{"databases":[]}"#)), ]); http.call(ClientRequest::get("/v1/me/databases")).expect("answered"); http.call(ClientRequest::get("/v1/me/databases")).expect("answered"); assert_eq!(exchange.calls(), 3, "one check, two requests"); assert_eq!(exchange.nth(1).origin, OTHER_MAC); } #[test] fn another_origins_refusal_note_is_its_own_file() { let (_dir, layout) = temp_layout(); let path = refusal_note_path(&layout.connection_json(), OTHER_MAC); assert_eq!(path.parent(), layout.connection_json().parent()); assert_ne!(path.file_name().and_then(|name| name.to_str()), Some("refusal.json")); assert_ne!( path, refusal_note_path(&layout.connection_json(), "https://kitchen.relay.cottondb.com") ); } /// RULE: A change to the connection record is made over the file as it is now, never over a remembered copy: two writers of one record never drop each other's entries. #[test] fn a_change_is_written_over_the_file_as_it_is_now() { let (_dir, layout) = temp_layout(); write_record(&layout, WORKSPACE, ConnectionMode::Remote, &[]); let one = ConnectionFile::at(layout.connection_json()); let other = ConnectionFile::at(layout.connection_json()); assert!(one.read_record().expect("a record").places.is_empty(), "now remembered"); other.add_made_place(GARDEN, "Garden", None).expect("recorded by the other writer"); let mine = one.read().expect("Mine"); one.write(mine).expect("Mine rewritten"); let record = crate::connection::read_record(&layout.connection_json()) .expect("a read") .expect("a record"); assert_eq!(record.places.len(), 1, "the other writer's entry is kept"); } #[test] fn another_persons_database_selects_only_its_pinned_mac() { let record: ConnectionRecord = serde_json::from_value(serde_json::json!({ "mode": "remote", "workspaceId": "mine", "baseUrl": "https://home.invalid", "places": [ {"id":"garden", "available":true, "origin":"https://garden.invalid", "serverDeviceId":"garden-mac"}, {"id":"removed", "available":true, "origin":"https://other.invalid", "serverDeviceId":"other-mac", "removedAt":"2026-10-04T00:00:00Z"}, {"id":"unlisted", "available":false}, {"id":"no-pin", "available":true, "origin":"https://unknown.invalid"} ] })).unwrap(); assert_eq!(served_at(&record, "mine"), Ok(ServedAt::Household)); assert_eq!( served_at(&record, "garden"), Ok(ServedAt::Joined { origin: "https://garden.invalid".into(), server_device_id: "garden-mac".into(), }) ); for id in ["removed", "unlisted", "no-pin", "missing"] { assert!(served_at(&record, id).is_err(), "{id}"); } }