diff --git a/crates/ledger-host/src/web.rs b/crates/ledger-host/src/web.rs index 96578c07..2f01f137 100644 --- a/crates/ledger-host/src/web.rs +++ b/crates/ledger-host/src/web.rs @@ -33,14 +33,25 @@ //! 6. A failure at any step leaves nothing half-on: the company is not //! offered, and if it was the only one the line and the door are //! closed again; the error is in words. +//! 7. Off is only off when the books server said so: a refusal or any +//! reply but its success leaves the company shown as on, with the +//! error in words; a server that cannot be reached at all closes the +//! whole line and the door (every company), and says so. A company is +//! never shown off while it can still be reached. +//! 8. The door is started as the address the relay has accepted: the +//! name is claimed and settled first (a name taken picks another), so +//! the address given to the door is the one the line and the +//! certificate carry. //! SCENARIOS: //! 1. See `crates/ledger-cli/tests/web_link.rs`: on, a web assistant //! signs in through the relay and reads the books, off, on again at -//! the same address, a new address, a restart. +//! the same address, a new address, a restart; and the tests below +//! (a books server that refuses or cannot be reached when a company +//! is turned off). //! ``` use crate::app_server::AppHost; -use ledger_link::{DoorTarget, Link, LinkConfig, LinkStatus, Step, Trouble}; +use ledger_link::{CertTrust, DoorTarget, Link, LinkConfig, LinkStatus, Step, Trouble}; use ledger_mcp::admin::{Request, Response}; use std::collections::BTreeSet; use std::path::PathBuf; @@ -54,6 +65,9 @@ pub const RELAY_HOST: &str = "relay.wanderbooks.link"; const SWITCHES: &str = "web.json"; const ADMIN_WAIT: Duration = Duration::from_secs(30); +/// How long to wait for the relay to accept the name before the door is +/// started as that address (INVARIANT 8). +const CLAIM_WAIT: Duration = Duration::from_secs(30); /// What the Connect page shows of the web assistants of one company. #[derive(Clone, Debug, PartialEq, Eq)] @@ -114,6 +128,7 @@ pub struct WebAssistants { on: Mutex>, /// An error from putting the switches back at the start. restore_error: Mutex>, + claim_wait: Duration, // One change at a time. busy: Mutex<()>, } @@ -126,6 +141,7 @@ fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> { pub fn production(dir: PathBuf) -> Result { Ok(LinkConfig { issuer: Arc::new(ledger_link::AcmeIssuer::new(&dir)), + trust: CertTrust::public()?, dir, domain: DOMAIN.into(), relay_host: RELAY_HOST.into(), @@ -149,10 +165,17 @@ impl WebAssistants { link: OnceLock::new(), on: Mutex::new(BTreeSet::new()), restore_error: Mutex::new(None), + claim_wait: CLAIM_WAIT, busy: Mutex::new(()), } } + /// Wait this long for the relay to accept the name (tests). + pub fn with_claim_wait(mut self, wait: Duration) -> Self { + self.claim_wait = wait; + self + } + fn dir(&self) -> Result { let root = ledger_store::root::Root::find(self.root.as_deref()).map_err(|e| e.to_string())?; @@ -283,6 +306,14 @@ impl WebAssistants { /// started as that address. fn start_door(&self, admin: &dyn Admin, link: &Arc) -> Result { link.turn_on().map_err(|e| e.to_string())?; + // The name is settled before the door is started as it (INVARIANT + // 8): the first claim may find it taken and pick another. + if let Err(why) = link.wait_settled(self.claim_wait) { + if lock(&self.on).is_empty() { + link.turn_off(); + } + return Err(why); + } let address = link .status() .address @@ -325,8 +356,8 @@ impl WebAssistants { } } - /// Turn web assistants off for `book` (INVARIANT 2): with no company - /// left offered, the line closes first, then the door. + /// Turn web assistants off for `book` (INVARIANTS 2 and 7): with no + /// company left offered, the line closes first, then the door. pub fn turn_off(&self, admin: &dyn Admin, book: &str) -> Result { let _one = lock(&self.busy); let mut now = lock(&self.on).clone(); @@ -336,24 +367,41 @@ impl WebAssistants { book: book.into(), allowed: false, }); - let mut note = None; - if let Err(why) = withdrawn { - // The server may be gone already (the books closed); what must - // still happen is the line closing. - note = Some(why); + let mut closed_all = false; + match withdrawn { + Ok(Response::Remote(_)) => {} + // The server answered, and did not withdraw the company: it can + // still be reached, so it stays shown as on, with the reason. + Ok(Response::Refused(why)) => { + return Err(format!( + "Web assistants are still on for this company: the books server would not turn them off ({why})." + )); + } + Ok(other) => { + return Err(format!( + "Web assistants are still on for this company: the books server answered in a way Wanderbooks did not expect ({other:?})." + )); + } + // The server cannot be reached at all, so nothing can be told + // about what it still offers: the safe side is to close the + // line and the door for every company. + Err(_) => closed_all = true, } - if now.is_empty() + if (now.is_empty() || closed_all) && let Some(Ok(link)) = self.link.get() { link.turn_off(); link.set_door(None); let _ = admin.admin(Request::RemoteStop); } + // What the person asked to be on stays on disk, so it is on again + // at the next start; what is open now is what is still offered. self.save(&now)?; - *lock(&self.on) = now; - Ok(match note { - Some(_) => "Web assistants are off.".into(), - None => "Web assistants are off for this company. Its address is kept for when you turn them on again.".into(), + *lock(&self.on) = if closed_all { BTreeSet::new() } else { now }; + Ok(if closed_all { + "Wanderbooks could not reach its books server to turn this off one company at a time, so it closed the connection to the internet for every company. Turn web assistants on again for the others if you want them.".into() + } else { + "Web assistants are off for this company. Its address is kept for when you turn them on again.".into() }) } @@ -432,3 +480,210 @@ impl Drop for WebAssistants { self.shutdown(); } } + +#[cfg(test)] +mod tests { + use super::*; + use ledger_mcp::admin::{RemoteInfo, TokenText}; + use std::sync::atomic::{AtomicU8, Ordering}; + + const SECRET: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + + /// What the books server does when a company is withdrawn. + const OK: u8 = 0; + const REFUSES: u8 = 1; + const UNREACHABLE: u8 = 2; + + /// A stand-in for the books server's admin socket: it keeps the set of + /// companies it offers and says what it was asked. + struct Server { + withdraw: AtomicU8, + offered: Mutex>, + asked: Mutex>, + door: Mutex, + } + + impl Server { + fn new() -> Server { + Server { + withdraw: AtomicU8::new(OK), + offered: Mutex::new(BTreeSet::new()), + asked: Mutex::new(vec![]), + door: Mutex::new(false), + } + } + + fn info(&self) -> RemoteInfo { + RemoteInfo { + listening: Some("127.0.0.1:9".into()), + public_url: None, + allowed: lock(&self.offered).iter().cloned().collect(), + proxy_secret: Some(TokenText(SECRET.into())), + } + } + + fn said(&self, what: &str) -> usize { + lock(&self.asked).iter().filter(|a| *a == what).count() + } + } + + impl Admin for Server { + fn admin(&self, request: Request) -> Result { + match request { + Request::RemoteStart { .. } => { + *lock(&self.door) = true; + Ok(Response::Remote(self.info())) + } + Request::RemoteStop => { + lock(&self.asked).push("stop".into()); + *lock(&self.door) = false; + lock(&self.offered).clear(); + Ok(Response::Remote(self.info())) + } + Request::RemoteAllow { + book, + allowed: true, + } => { + lock(&self.offered).insert(book); + Ok(Response::Remote(self.info())) + } + Request::RemoteAllow { + book, + allowed: false, + } => { + lock(&self.asked).push(format!("withdraw {book}")); + match self.withdraw.load(Ordering::SeqCst) { + REFUSES => Ok(Response::Refused("not today".into())), + UNREACHABLE => Err("the books server is not there".into()), + _ => { + lock(&self.offered).remove(&book); + Ok(Response::Remote(self.info())) + } + } + } + other => Err(format!("not asked in these tests: {other:?}")), + } + } + } + + /// Web assistants over a data root of their own, with a name the relay + /// already accepted (so the address is settled) and a relay that is + /// not there: the line cannot come up, which these tests do not need. + fn web() -> (tempfile::TempDir, WebAssistants) { + let dir = tempfile::tempdir().unwrap(); + let home = dir.path().join("home"); + std::fs::create_dir_all(&home).unwrap(); + let root = dir.path().join("root"); + ledger_store::root::Root::setup(&home, Some(&root), None).unwrap(); + let found = ledger_store::root::Root::find(Some(&root)).unwrap(); + let link = found.path().join("link"); + let mut id = ledger_link::identity::Identity::load_or_create(&link).unwrap(); + id.set_claimed().unwrap(); + let web = WebAssistants::with_maker( + Some(root), + Box::new(|dir| { + Ok(LinkConfig { + domain: DOMAIN.into(), + relay_host: RELAY_HOST.into(), + dial: ledger_link::Dial::Addr("127.0.0.1:1".parse().unwrap()), + relay_tls: ledger_link::public_relay_tls().map_err(|e| e.to_string())?, + // Never reached: the line cannot come up, so nothing is + // ordered. + issuer: Arc::new(ledger_link::AcmeIssuer::new(&dir)), + trust: CertTrust::public()?, + timing: ledger_link::Timing::default(), + dir, + }) + }), + ); + (dir, web) + } + + fn link_on(web: &WebAssistants) -> bool { + web.link_status().is_some_and(|s| s.on) + } + + /// The plain case: with another company still on, turning one off makes + /// it unreachable at once and the other keeps working. + #[test] + fn one_company_off_is_unreachable_at_once_while_another_still_works() { + let (_dir, web) = web(); + let server = Server::new(); + web.turn_on(&server, "alpha").unwrap(); + web.turn_on(&server, "beta").unwrap(); + assert_eq!(lock(&server.offered).len(), 2); + + let said = web.turn_off(&server, "alpha").unwrap(); + assert!(said.contains("off for this company"), "{said}"); + assert!(!web.state("alpha").on); + assert!(web.state("beta").on); + let offered = lock(&server.offered).clone(); + assert!( + !offered.contains("alpha"), + "alpha is not offered by the server" + ); + assert!(offered.contains("beta"), "beta still is"); + assert!(link_on(&web), "the line stays up for beta"); + assert!(*lock(&server.door), "and so does the door"); + assert_eq!(server.said("stop"), 0); + // The company left off stays off at the next start. + assert_eq!(web.load(), BTreeSet::from(["beta".to_string()])); + } + + /// The server refuses to withdraw the company: it is still reachable, + /// so it is still shown as on, with the reason in words; nothing else + /// changes. + #[test] + fn a_refusal_leaves_the_company_shown_as_on_with_the_reason() { + let (_dir, web) = web(); + let server = Server::new(); + web.turn_on(&server, "alpha").unwrap(); + web.turn_on(&server, "beta").unwrap(); + + server.withdraw.store(REFUSES, Ordering::SeqCst); + let err = web.turn_off(&server, "alpha").unwrap_err(); + assert!(err.contains("still on for this company"), "{err}"); + assert!(err.contains("not today"), "{err}"); + assert!(web.state("alpha").on, "alpha is reachable, so shown on"); + assert!(web.state("beta").on); + assert!(lock(&server.offered).contains("alpha")); + assert!(link_on(&web)); + assert_eq!(server.said("stop"), 0, "the door was not closed"); + // Nothing was saved off either. + assert_eq!( + web.load(), + BTreeSet::from(["alpha".to_string(), "beta".to_string()]) + ); + + // And once the server is willing, it works. + server.withdraw.store(OK, Ordering::SeqCst); + web.turn_off(&server, "alpha").unwrap(); + assert!(!web.state("alpha").on); + } + + /// The server cannot be reached at all: the safe side is the whole line + /// and door closed, and the person is told. + #[test] + fn an_unreachable_server_closes_the_whole_line_and_door_and_says_so() { + let (_dir, web) = web(); + let server = Server::new(); + web.turn_on(&server, "alpha").unwrap(); + web.turn_on(&server, "beta").unwrap(); + + server.withdraw.store(UNREACHABLE, Ordering::SeqCst); + let said = web.turn_off(&server, "alpha").unwrap(); + assert!( + said.contains("closed the connection to the internet for every company"), + "{said}" + ); + assert!(!link_on(&web), "the line is closed"); + assert!(!web.state("alpha").on); + assert!( + !web.state("beta").on, + "beta is not reachable either, so not shown on" + ); + assert_eq!(server.said("stop"), 1, "the door was told to close"); + // What the person had on is still wanted at the next start. + assert_eq!(web.load(), BTreeSet::from(["beta".to_string()])); + } +}