//! The door's one write. Every name here is invented. use cotton_core::front_door::{Door, FrontDoor}; use serde_json::json; use super::*; use crate::shell::client::phone_tests::attached; use crate::shell::client::ClientController; /// The household's row as the file holds it now: its name and relay, then its door. fn row(client: &ClientController) -> ([Option; 3], FrontDoor) { client .with_writer(|replica| { let row = replica .driver .get( "SELECT relay_name, relay_domain, relay_tunnel_host FROM cotton_workspaces", &[], ) .map_err(|error| error.to_string())? .expect("the workspace"); let identity = ["relay_name", "relay_domain", "relay_tunnel_host"] .map(|column| row.text(column).map(str::to_string)); let door = cotton_tools::household_address::read_front_door(replica.driver, None)?; Ok((identity, door)) }) .expect("the row") } /// Through a signed write, as the Mac names a household: a row is what its /// ops fold to, and a value only SQL wrote is gone at the next signed write. fn name_the_household(client: &ClientController) { client .write_rows("tunnel.setName", &mut |ctx| { let id = ctx.workspace_id.to_string(); let mut patch = serde_json::Map::new(); patch.insert("relay_name".to_string(), json!("harbour-lamp")); update_row(ctx, "cotton_workspaces", &id, patch).map_err(|failure| failure.to_string())?; Ok(json!({})) }) .expect("the name"); } fn set(client: &ClientController, door: &FrontDoor) -> Result { client .write_rows("workspace.setReach", &mut |ctx| write_front_door(ctx, &door.clone().into())) .map(crate::authoring::own_answer) } /// RULE: Switching doors never drops the relay name — a household that goes from the relay to a direct door, to a Funnel, and back holds the same name under the same relay at every step, and the write that changes the door carries the door's two columns and nothing else. #[test] fn switching_doors_never_drops_the_relay_name() { let (_dir, client) = attached(); name_the_household(&client); let (named, door) = row(&client); assert_eq!(named[0].as_deref(), Some("harbour-lamp")); assert_eq!(door, FrontDoor::relay(), "a household nobody has asked is on the relay"); let steps = [ FrontDoor::new(Door::Direct, Some("home.example.org")).unwrap(), FrontDoor::new(Door::TailscaleFunnel, None).unwrap(), FrontDoor::new(Door::TailscaleFunnel, Some("study.tail1234.ts.net")).unwrap(), FrontDoor::relay(), ]; for step in steps { let answer = set(&client, &step).expect("the door is set"); assert_eq!(answer["through"], json!(step.door().as_str())); assert_eq!(answer["relayName"], json!("harbour-lamp")); let (still, now) = row(&client); assert_eq!(still, named, "{:?} moved the household's name", step.door()); assert_eq!(now, step); } // What travelled to the other devices: the door's two columns only. let written: Vec> = client .with_writer(|replica| { Ok(cotton_store::exchange::answer( replica.driver, &std::collections::BTreeMap::new(), 5_000, ) .map_err(|error| error.to_string())? .ops .into_iter() .filter(|op| op.table == "cotton_workspaces") .filter_map(|op| op.patch) .map(|patch| patch.keys().cloned().collect::>()) .filter(|keys| keys.iter().any(|key| key.starts_with("front_door"))) .collect()) }) .expect("the ops"); assert!(!written.is_empty(), "the door's change travels"); for keys in written { assert!( keys.iter().all(|key| key == "front_door" || key == "front_door_address"), "a door write carried {keys:?}" ); } } /// RULE: A door is checked before a row is touched — an unknown door, a direct door with no domain, a Funnel under a name that is not the tailnet's, and a relay given an address are each refused by name and leave the household where it was. #[test] fn a_door_that_cannot_be_opened_is_refused_before_anything_is_written() { for (request, says) in [ (json!({}), "relay, tailscale_funnel or direct"), (json!({ "door": "direct", "address": "home.example.org" }), "`through` is"), (json!({ "through": "carrier-pigeon" }), "relay, tailscale_funnel or direct"), (json!({ "through": "direct" }), "attach one of its domains"), (json!({ "through": "direct", "address": "https://home.example.org" }), "is not a hostname"), (json!({ "through": "tailscale_funnel", "address": "home.example.org" }), "is not a Tailscale name"), (json!({ "through": "relay", "address": "home.example.org" }), "takes no other address"), (json!({ "through": "direct", "address": 7 }), "a hostname, or nothing"), ] { let refused = asked(&request).expect_err("a refusal"); assert_eq!(refused.code, "bad_request", "{request}"); assert!(refused.message.contains(says), "{request}: {}", refused.message); } assert_eq!( asked(&json!({ "through": "direct", "address": "home.example.org" })).unwrap().door, FrontDoor::new(Door::Direct, Some("home.example.org")).unwrap() ); assert_eq!(asked(&json!({ "through": "relay", "address": null })).unwrap().door, FrontDoor::relay()); } /// RULE: The front door is the household's and is set in its personal database — a shared database is reached wherever its household is and is refused a door of its own. #[test] fn a_shared_database_has_no_door_of_its_own() { let (_dir, client) = attached(); client .with_writer(|replica| { replica .driver .exec("UPDATE cotton_workspaces SET kind = 'shared'") .map_err(|error| error.to_string())?; Ok(()) }) .expect("a shared database"); let refused = set(&client, &FrontDoor::new(Door::Direct, Some("home.example.org")).unwrap()) .expect_err("refused"); assert!(refused.contains("personal database"), "{refused}"); assert_eq!(row(&client).1, FrontDoor::relay()); } /// RULE: A page shows the two relays apart and the row keeps them as one door — a household on Cotton's relay reads as "Cotton relay" and may be set to it again, and asking it for a relay of its own is refused in words, never obeyed by staying put: which relay a household is on was written with its row. #[test] fn changing_the_relay_is_refused_and_address_changes_keep_their_undo() { let (_dir, client) = attached(); name_the_household(&client); let page = |client: &ClientController| { client .with_writer(|replica| Ok(page_answer(replica.driver, replica.workspace_id))) .expect("the page") }; let said = page(&client); assert_eq!(said["through"], json!("cotton_relay")); assert_eq!(said.get("reachedAt"), None, "where a household is reached is never a device's to say"); let ask = |request: serde_json::Value| { let asked = asked(&request).expect("a door"); client .write_rows("workspace.setReach", &mut |ctx| write_front_door(ctx, &asked)) .map(crate::authoring::own_answer) }; let refused = ask(json!({ "through": "own_relay" })).expect_err("not this household's relay"); assert!(refused.contains("made on Cotton's relay"), "{refused}"); assert_eq!(page(&client)["through"], json!("cotton_relay"), "nothing moved"); let chosen = ask(json!({ "through": "tailscale_funnel" })).expect("a Funnel, not yet open"); assert!(chosen["receipt"].is_string()); assert_eq!(chosen["undo"]["args"]["through"], json!("relay"), "the way back is where it was"); assert_eq!(page(&client)["through"], json!("tailscale_funnel")); ask(json!({ "through": "direct", "address": "home.example.org" })).expect("a direct door"); assert_eq!(page(&client)["through"], json!("direct")); ask(json!({ "through": "cotton_relay" })).expect("back on the relay it was made on"); assert_eq!(page(&client)["through"], json!("cotton_relay")); } /// RULE: The Devices read says how the world reaches the household off the file's own row, with the device whose page draws it — no network, so a phone draws it as readily as the serving Mac — and a row this build cannot read is said as unreadable, never as a door. #[test] fn the_devices_read_says_the_households_door_off_its_own_row() { let (_dir, client) = attached(); name_the_household(&client); let read = |client: &ClientController| { crate::phone::reads_work::devices(client, &serde_json::Map::new()).expect("read.devices") }; let said = read(&client); assert_eq!(said["reach"]["through"], json!("cotton_relay")); assert!(said["reach"].get("onDevice").is_some(), "the row that draws it is named, or null"); client .with_writer(|replica| { replica .driver .exec("UPDATE cotton_workspaces SET front_door = 'carrier-pigeon'") .map_err(|error| error.to_string())?; Ok(()) }) .expect("a door from a newer build"); let said = read(&client); assert_eq!(said["reach"].get("through"), None, "an unknown one is never drawn as one"); assert!( said["reach"]["unreadable"].as_str().is_some_and(|why| why.contains("is not a way a household is reached")), "{}", said["reach"] ); } /// RULE: A Funnel chosen on the Mac that serves is addressed to that Mac — its own name on its tailnet, as its Tailscale answered — and one chosen where no Tailscale answered is left chosen and unaddressed for the serving Mac; an address a person gave, and every other door, is never rewritten. #[test] fn a_funnel_chosen_on_the_serving_mac_is_addressed_to_that_mac() { let funnel = || Asked::from(FrontDoor::new(Door::TailscaleFunnel, None).unwrap()); let own = || Some(Ok("study.tail1234.ts.net".to_string())); assert_eq!( named_by_this_mac(funnel(), own()).door, FrontDoor::new(Door::TailscaleFunnel, Some("study.tail1234.ts.net")).unwrap() ); for unanswered in [None, Some(Err("Tailscale is not signed in".to_string())), Some(Ok("study.example.org".to_string()))] { assert_eq!(named_by_this_mac(funnel(), unanswered.clone()), funnel(), "{unanswered:?}"); } let given = Asked::from(FrontDoor::new(Door::TailscaleFunnel, Some("den.tail1234.ts.net")).unwrap()); assert_eq!(named_by_this_mac(given.clone(), own()), given, "another Mac's name was overwritten"); for other in [FrontDoor::relay(), FrontDoor::new(Door::Direct, Some("home.example.org")).unwrap()] { let asked = Asked::from(other); assert_eq!(named_by_this_mac(asked.clone(), own()), asked); } } /// RULE: A phone away from home is pointed, off its own copy of the household's row, at the address the household is reached at only while that is a Funnel or a direct address — on the relay, for a Funnel no Mac has opened, and for a row this build cannot read it is pointed nowhere new and dials its relay as before. #[test] fn a_phone_is_pointed_at_the_households_address_only_off_the_relay() { let (_dir, client) = attached(); name_the_household(&client); let away = |client: &ClientController| { client .with_writer(|replica| { let id = replica .driver .get("SELECT id FROM cotton_workspaces LIMIT 1", &[]) .map_err(|error| error.to_string())? .and_then(|row| row.text("id").map(str::to_string)) .ok_or("no household row")?; Ok(away_origin(replica.driver, &id)) }) .expect("the copy") }; assert_eq!(away(&client), None, "on the relay: its name under the relay, as remembered"); set(&client, &FrontDoor::new(Door::TailscaleFunnel, Some("study.tail1234.ts.net")).unwrap()).expect("Funnel"); assert_eq!(away(&client).as_deref(), Some("https://study.tail1234.ts.net")); set(&client, &FrontDoor::new(Door::Direct, Some("home.example.org")).unwrap()).expect("direct"); assert_eq!(away(&client).as_deref(), Some("https://home.example.org")); set(&client, &FrontDoor::new(Door::TailscaleFunnel, None).unwrap()).expect("an unopened Funnel"); assert_eq!(away(&client), None, "a Funnel no Mac has opened"); client .with_writer(|replica| { replica .driver .exec("UPDATE cotton_workspaces SET front_door = 'carrier-pigeon', front_door_address = 'x.example.org'") .map_err(|error| error.to_string()) }) .expect("a newer build's row"); assert_eq!(away(&client), None, "a row this build cannot read"); set(&client, &FrontDoor::relay()).expect("back on the relay"); assert_eq!(away(&client), None); }