feat(host): web assistants per company, joined to the remote door (P15 B3)
WebAssistants is the switch per company: turning one on makes the link's address, starts the books server's remote door at it (the door listens on 127.0.0.1 and gives the app its per-start secret), offers the company, and hands the link the door; turning off withdraws the company and, with none left, closes the line first and then the door. A new address stops the door, makes a new label, and restarts the door at the new issuer, so every token made at the old address is refused. The switches are kept in a private file and put back for the companies that are open at the next start. Nothing is half-on after a failed step. The line runs in the window's process (the viewer owner holds it), so it ends with the window and never outlives the books it offers. THIRD-PARTY-NOTICES.txt is regenerated with scripts/notices.sh: the app now links instant-acme, the relay crate's client side and hickory-proto. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
0f9420aa30
commit
861ed57d82
8 files changed
+2082
-23
No files matched your search
Generated
+14
@@ -4006,13 +4006,19 @@ name = "ledger-cli"
|
|||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"base64 0.22.1",
|
"base64 0.22.1",
|
||||||
|
"bytes",
|
||||||
"chrono",
|
"chrono",
|
||||||
|
"futures",
|
||||||
|
"http-body-util",
|
||||||
|
"hyper",
|
||||||
|
"hyper-util",
|
||||||
"jsonschema",
|
"jsonschema",
|
||||||
"ledger-config",
|
"ledger-config",
|
||||||
"ledger-core",
|
"ledger-core",
|
||||||
"ledger-gui",
|
"ledger-gui",
|
||||||
"ledger-host",
|
"ledger-host",
|
||||||
"ledger-import",
|
"ledger-import",
|
||||||
|
"ledger-link",
|
||||||
"ledger-mcp",
|
"ledger-mcp",
|
||||||
"ledger-package",
|
"ledger-package",
|
||||||
"ledger-store",
|
"ledger-store",
|
||||||
@@ -4020,14 +4026,20 @@ dependencies = [
|
|||||||
"libc",
|
"libc",
|
||||||
"minisign",
|
"minisign",
|
||||||
"proptest",
|
"proptest",
|
||||||
|
"rcgen",
|
||||||
|
"relay",
|
||||||
"reqwest",
|
"reqwest",
|
||||||
"rmcp",
|
"rmcp",
|
||||||
"rusqlite",
|
"rusqlite",
|
||||||
"rust_decimal",
|
"rust_decimal",
|
||||||
|
"rustls",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"sha2 0.10.9",
|
"sha2 0.10.9",
|
||||||
"tempfile",
|
"tempfile",
|
||||||
|
"time",
|
||||||
"tokio",
|
"tokio",
|
||||||
|
"tokio-rustls",
|
||||||
|
"zeroize",
|
||||||
"zip",
|
"zip",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -4085,6 +4097,7 @@ dependencies = [
|
|||||||
"ledger-config",
|
"ledger-config",
|
||||||
"ledger-core",
|
"ledger-core",
|
||||||
"ledger-import",
|
"ledger-import",
|
||||||
|
"ledger-link",
|
||||||
"ledger-package",
|
"ledger-package",
|
||||||
"ledger-store",
|
"ledger-store",
|
||||||
"ledger-vault",
|
"ledger-vault",
|
||||||
@@ -4105,6 +4118,7 @@ version = "0.1.0"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"base64 0.22.1",
|
"base64 0.22.1",
|
||||||
"ledger-core",
|
"ledger-core",
|
||||||
|
"ledger-link",
|
||||||
"ledger-mcp",
|
"ledger-mcp",
|
||||||
"ledger-store",
|
"ledger-store",
|
||||||
"libc",
|
"libc",
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -15,10 +15,11 @@ path = "src/main.rs"
|
|||||||
default = ["gui"]
|
default = ["gui"]
|
||||||
# The viewer. Off in the server-only build for another machine (plan
|
# The viewer. Off in the server-only build for another machine (plan
|
||||||
# D-22, P9), so a headless machine carries no window libraries.
|
# D-22, P9), so a headless machine carries no window libraries.
|
||||||
gui = ["dep:ledger-gui"]
|
gui = ["dep:ledger-gui", "dep:ledger-link"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
ledger-host = { path = "../ledger-host" }
|
ledger-host = { path = "../ledger-host" }
|
||||||
|
ledger-link = { path = "../ledger-link", optional = true }
|
||||||
ledger-mcp = { path = "../ledger-mcp" }
|
ledger-mcp = { path = "../ledger-mcp" }
|
||||||
ledger-store = { path = "../ledger-store" }
|
ledger-store = { path = "../ledger-store" }
|
||||||
ledger-gui = { path = "../ledger-gui", optional = true }
|
ledger-gui = { path = "../ledger-gui", optional = true }
|
||||||
@@ -36,7 +37,21 @@ reqwest = "0.13"
|
|||||||
rusqlite = { version = "0.41", features = ["bundled", "fallible_uint"] }
|
rusqlite = { version = "0.41", features = ["bundled", "fallible_uint"] }
|
||||||
rust_decimal = "1"
|
rust_decimal = "1"
|
||||||
rmcp = { version = "3", features = ["client", "transport-streamable-http-client-reqwest"] }
|
rmcp = { version = "3", features = ["client", "transport-streamable-http-client-reqwest"] }
|
||||||
tokio = { version = "1", features = ["macros", "rt-multi-thread", "time"] }
|
tokio = { version = "1", features = ["macros", "rt-multi-thread", "time", "net", "io-util"] }
|
||||||
|
# The web link end to end (tests/web_link.rs): an in-process relay and
|
||||||
|
# certificate authority, and a web caller that speaks HTTP/1.1 and HTTP/2.
|
||||||
|
relay = { path = "../relay" }
|
||||||
|
ledger-link = { path = "../ledger-link" }
|
||||||
|
rcgen = { version = "0.14", default-features = false, features = ["ring", "pem"] }
|
||||||
|
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
|
||||||
|
tokio-rustls = { version = "0.26", default-features = false, features = ["ring", "tls12"] }
|
||||||
|
hyper = { version = "1", features = ["client", "http2"] }
|
||||||
|
hyper-util = { version = "0.1", features = ["tokio"] }
|
||||||
|
http-body-util = "0.1"
|
||||||
|
bytes = "1"
|
||||||
|
futures = "0.3"
|
||||||
|
zeroize = "1"
|
||||||
|
time = "0.3"
|
||||||
ledger-config = { path = "../ledger-config" }
|
ledger-config = { path = "../ledger-config" }
|
||||||
ledger-core = { path = "../ledger-core" }
|
ledger-core = { path = "../ledger-core" }
|
||||||
ledger-package = { path = "../ledger-package" }
|
ledger-package = { path = "../ledger-package" }
|
||||||
|
|||||||
@@ -76,13 +76,22 @@ struct ViewerOwner {
|
|||||||
/// 3.1): started with the window, closed with it. All of what is done
|
/// 3.1): started with the window, closed with it. All of what is done
|
||||||
/// with it is `AppHost`'s, which the tests drive.
|
/// with it is `AppHost`'s, which the tests drive.
|
||||||
server: ledger_host::app_server::AppHost,
|
server: ledger_host::app_server::AppHost,
|
||||||
|
/// Web assistants: the switch per company, the address and the line to
|
||||||
|
/// the relay (ledger-host web.rs), in this window's process: the line
|
||||||
|
/// ends with the window.
|
||||||
|
web: ledger_host::web::WebAssistants,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "gui")]
|
#[cfg(feature = "gui")]
|
||||||
impl ViewerOwner {
|
impl ViewerOwner {
|
||||||
fn new(common: ledger_host::commands::Common) -> Self {
|
fn new(common: ledger_host::commands::Common) -> Self {
|
||||||
let server = ledger_host::app_server::AppHost::new(common.root.clone());
|
let server = ledger_host::app_server::AppHost::new(common.root.clone());
|
||||||
Self { common, server }
|
let web = ledger_host::web::WebAssistants::new(common.root.clone());
|
||||||
|
Self {
|
||||||
|
common,
|
||||||
|
server,
|
||||||
|
web,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -93,7 +102,11 @@ impl ledger_gui::owner::Owner for ViewerOwner {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn serve_start(&self, open: &[String]) -> Result<(), String> {
|
fn serve_start(&self, open: &[String]) -> Result<(), String> {
|
||||||
self.server.start(open)
|
self.server.start(open)?;
|
||||||
|
// What was on when the window closed is on again, for the
|
||||||
|
// companies that are open.
|
||||||
|
self.web.restore(&self.server, open);
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn serve_host_holds(&self) -> bool {
|
fn serve_host_holds(&self) -> bool {
|
||||||
@@ -105,7 +118,9 @@ impl ledger_gui::owner::Owner for ViewerOwner {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn serve_open(&self, book: &str) -> Result<Option<String>, String> {
|
fn serve_open(&self, book: &str) -> Result<Option<String>, String> {
|
||||||
self.server.open_book(book)
|
let opened = self.server.open_book(book)?;
|
||||||
|
self.web.restore(&self.server, &[book.to_string()]);
|
||||||
|
Ok(opened)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn serve_close(&self, book: &str) -> Result<Option<String>, String> {
|
fn serve_close(&self, book: &str) -> Result<Option<String>, String> {
|
||||||
@@ -117,6 +132,8 @@ impl ledger_gui::owner::Owner for ViewerOwner {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn serve_stop(&self) -> Result<Option<String>, String> {
|
fn serve_stop(&self) -> Result<Option<String>, String> {
|
||||||
|
// The line closes first: nothing arrives for books that are closing.
|
||||||
|
self.web.shutdown();
|
||||||
self.server.stop(ledger_host::app_server::STOP_WAIT)
|
self.server.stop(ledger_host::app_server::STOP_WAIT)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -207,6 +224,39 @@ impl ledger_gui::owner::Owner for ViewerOwner {
|
|||||||
self.server.web_set_post(approval, post)
|
self.server.web_set_post(approval, post)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn web_state(&self, book: &str) -> Option<ledger_gui::owner::WebConnect> {
|
||||||
|
use ledger_gui::owner::WebStep;
|
||||||
|
let s = self.web.state(book);
|
||||||
|
Some(ledger_gui::owner::WebConnect {
|
||||||
|
on: s.on,
|
||||||
|
step: match s.step {
|
||||||
|
ledger_link::Step::Off => WebStep::Off,
|
||||||
|
ledger_link::Step::GettingAddress => WebStep::GettingAddress,
|
||||||
|
ledger_link::Step::Connecting => WebStep::Connecting,
|
||||||
|
ledger_link::Step::GettingCertificate => WebStep::GettingCertificate,
|
||||||
|
ledger_link::Step::Connected => WebStep::Connected,
|
||||||
|
},
|
||||||
|
address: s.address,
|
||||||
|
connector: s.connector,
|
||||||
|
words: s.words,
|
||||||
|
problem: s.problem,
|
||||||
|
needs_person: s.needs_person,
|
||||||
|
kept: s.kept,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn web_turn_on(&self, book: &str) -> Result<String, String> {
|
||||||
|
self.web.turn_on(&self.server, book)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn web_turn_off(&self, book: &str) -> Result<String, String> {
|
||||||
|
self.web.turn_off(&self.server, book)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn web_new_address(&self, _book: &str) -> Result<String, String> {
|
||||||
|
self.web.new_address(&self.server)
|
||||||
|
}
|
||||||
|
|
||||||
fn serve_revoke(&self, book: &str, name: &str, id: &str) -> Result<String, String> {
|
fn serve_revoke(&self, book: &str, name: &str, id: &str) -> Result<String, String> {
|
||||||
self.server.revoke_token(book, name, id)
|
self.server.revoke_token(book, name, id)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ description = "wanderbooks: the books open while something holds them (the host,
|
|||||||
ledger-core = { path = "../ledger-core" }
|
ledger-core = { path = "../ledger-core" }
|
||||||
ledger-mcp = { path = "../ledger-mcp" }
|
ledger-mcp = { path = "../ledger-mcp" }
|
||||||
ledger-store = { path = "../ledger-store" }
|
ledger-store = { path = "../ledger-store" }
|
||||||
|
ledger-link = { path = "../ledger-link" }
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-util", "io-std", "sync", "net", "signal", "time", "process"] }
|
tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-util", "io-std", "sync", "net", "signal", "time", "process"] }
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ mod start;
|
|||||||
pub mod tokens;
|
pub mod tokens;
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
pub mod update;
|
pub mod update;
|
||||||
|
pub mod web;
|
||||||
|
|
||||||
/// How a mode stops when it can't go on: the reason is already printed,
|
/// How a mode stops when it can't go on: the reason is already printed,
|
||||||
/// and the number is the process's exit code.
|
/// and the number is the process's exit code.
|
||||||
|
|||||||
@@ -0,0 +1,434 @@
|
|||||||
|
//! Web assistants, from the app's side: the switch per company, the one
|
||||||
|
//! address, and the line to the relay, joined to the books server's remote
|
||||||
|
//! door (plan P15 unit B3; WB-link-6).
|
||||||
|
//!
|
||||||
|
//! ```text
|
||||||
|
//! GOAL: a person turns "Allow web assistants" on for a company and the
|
||||||
|
//! app offers that company at one durable public address, through
|
||||||
|
//! the relay, with the sign-in the books server's remote door gives;
|
||||||
|
//! turned off, the company is no longer offered, and when no company
|
||||||
|
//! is offered the line and the door are closed; and what was on when
|
||||||
|
//! the app closed is on again when it opens, once the books are.
|
||||||
|
//! SOURCE: plan/p15-app-and-relay.md 3.3 (a switch per company, off by
|
||||||
|
//! default; the address with Copy; "Turning it off closes the line
|
||||||
|
//! and the door; the name is kept"), 5 (one name per installation,
|
||||||
|
//! each company a path under it), D-80, D-84, WB-link-6.
|
||||||
|
//! INVARIANTS:
|
||||||
|
//! 1. Off by default, and per company: nothing is dialled, listened on
|
||||||
|
//! or offered until a person turns a company on, and only that
|
||||||
|
//! company is offered.
|
||||||
|
//! 2. The order is the door first, then the line when turning on (the
|
||||||
|
//! door listens on 127.0.0.1 only and wants the secret), and the line
|
||||||
|
//! first, then the door, when turning off: nothing arrives for a door
|
||||||
|
//! that is gone, and no door is open to a line that is gone.
|
||||||
|
//! 3. One address for every company: the address's path names the
|
||||||
|
//! company (`/b/<company>/mcp`), and a new address replaces the
|
||||||
|
//! secret label, restarts the door at the new issuer (so every token
|
||||||
|
//! and sign-in made at the old address is refused) and keeps the name.
|
||||||
|
//! 4. The switches are kept in a private file in the link folder, so
|
||||||
|
//! they are still on at the next start; a company that is not open
|
||||||
|
//! yet waits for its tab.
|
||||||
|
//! 5. The state is read from memory and never waits on the network or
|
||||||
|
//! the server: the window asks it every frame.
|
||||||
|
//! 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.
|
||||||
|
//! 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.
|
||||||
|
//! ```
|
||||||
|
|
||||||
|
use crate::app_server::AppHost;
|
||||||
|
use ledger_link::{DoorTarget, Link, LinkConfig, LinkStatus, Step, Trouble};
|
||||||
|
use ledger_mcp::admin::{Request, Response};
|
||||||
|
use std::collections::BTreeSet;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::sync::{Arc, Mutex, OnceLock};
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
/// The relay's domain and its own host name.
|
||||||
|
pub const DOMAIN: &str = "wanderbooks.link";
|
||||||
|
/// The relay's host, which its certificate is for.
|
||||||
|
pub const RELAY_HOST: &str = "relay.wanderbooks.link";
|
||||||
|
|
||||||
|
const SWITCHES: &str = "web.json";
|
||||||
|
const ADMIN_WAIT: Duration = Duration::from_secs(30);
|
||||||
|
|
||||||
|
/// What the Connect page shows of the web assistants of one company.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct WebState {
|
||||||
|
/// The switch for this company.
|
||||||
|
pub on: bool,
|
||||||
|
/// Where it has got to.
|
||||||
|
pub step: Step,
|
||||||
|
/// The address, while on.
|
||||||
|
pub address: Option<String>,
|
||||||
|
/// The address an assistant is given for this company.
|
||||||
|
pub connector: Option<String>,
|
||||||
|
/// A line of progress in words.
|
||||||
|
pub words: String,
|
||||||
|
/// What is wrong, in words.
|
||||||
|
pub problem: Option<String>,
|
||||||
|
/// Whether the problem needs the person (and is not just waiting).
|
||||||
|
pub needs_person: bool,
|
||||||
|
/// An address is kept for when it is turned on again.
|
||||||
|
pub kept: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WebState {
|
||||||
|
fn off(kept: bool) -> Self {
|
||||||
|
WebState {
|
||||||
|
on: false,
|
||||||
|
step: Step::Off,
|
||||||
|
address: None,
|
||||||
|
connector: None,
|
||||||
|
words: "Web assistants are off.".into(),
|
||||||
|
problem: None,
|
||||||
|
needs_person: false,
|
||||||
|
kept,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How the app reaches the books server's admin requests.
|
||||||
|
pub trait Admin: Send + Sync {
|
||||||
|
/// One admin request.
|
||||||
|
fn admin(&self, request: Request) -> Result<Response, String>;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Admin for AppHost {
|
||||||
|
fn admin(&self, request: Request) -> Result<Response, String> {
|
||||||
|
self.running()?.call(request, Some(ADMIN_WAIT))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How the link is made (tests give it a relay of their own).
|
||||||
|
pub type Maker = Box<dyn Fn(PathBuf) -> Result<LinkConfig, String> + Send + Sync>;
|
||||||
|
|
||||||
|
/// Web assistants for this window.
|
||||||
|
pub struct WebAssistants {
|
||||||
|
root: Option<PathBuf>,
|
||||||
|
make: Maker,
|
||||||
|
link: OnceLock<Result<Arc<Link>, String>>,
|
||||||
|
on: Mutex<BTreeSet<String>>,
|
||||||
|
/// An error from putting the switches back at the start.
|
||||||
|
restore_error: Mutex<Option<String>>,
|
||||||
|
// One change at a time.
|
||||||
|
busy: Mutex<()>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
|
||||||
|
m.lock().unwrap_or_else(|e| e.into_inner())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The program's own relay.
|
||||||
|
pub fn production(dir: PathBuf) -> Result<LinkConfig, String> {
|
||||||
|
Ok(LinkConfig {
|
||||||
|
issuer: Arc::new(ledger_link::AcmeIssuer::new(&dir)),
|
||||||
|
dir,
|
||||||
|
domain: DOMAIN.into(),
|
||||||
|
relay_host: RELAY_HOST.into(),
|
||||||
|
dial: ledger_link::Dial::Host(RELAY_HOST.into(), 443),
|
||||||
|
relay_tls: ledger_link::public_relay_tls().map_err(|e| e.to_string())?,
|
||||||
|
timing: ledger_link::Timing::default(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WebAssistants {
|
||||||
|
/// Web assistants for the data root `root` (else this account's).
|
||||||
|
pub fn new(root: Option<PathBuf>) -> Self {
|
||||||
|
Self::with_maker(root, Box::new(production))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// With a link made another way (tests).
|
||||||
|
pub fn with_maker(root: Option<PathBuf>, make: Maker) -> Self {
|
||||||
|
WebAssistants {
|
||||||
|
root,
|
||||||
|
make,
|
||||||
|
link: OnceLock::new(),
|
||||||
|
on: Mutex::new(BTreeSet::new()),
|
||||||
|
restore_error: Mutex::new(None),
|
||||||
|
busy: Mutex::new(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn dir(&self) -> Result<PathBuf, String> {
|
||||||
|
let root =
|
||||||
|
ledger_store::root::Root::find(self.root.as_deref()).map_err(|e| e.to_string())?;
|
||||||
|
Ok(root.path().join("link"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn link(&self) -> Result<&Arc<Link>, String> {
|
||||||
|
self.link
|
||||||
|
.get_or_init(|| {
|
||||||
|
let cfg = (self.make)(self.dir()?)?;
|
||||||
|
Link::start(cfg).map(Arc::new)
|
||||||
|
})
|
||||||
|
.as_ref()
|
||||||
|
.map_err(Clone::clone)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn save(&self, set: &BTreeSet<String>) -> Result<(), String> {
|
||||||
|
let dir = self.dir()?;
|
||||||
|
let text = serde_json::to_vec(&serde_json::json!({ "books": set }))
|
||||||
|
.map_err(|_| "can't keep the switches".to_string())?;
|
||||||
|
ledger_link::private::make_dir(&dir)
|
||||||
|
.map_err(|e| format!("can't keep the switches ({})", e.kind()))?;
|
||||||
|
ledger_link::private::write(&dir.join(SWITCHES), &text)
|
||||||
|
.map_err(|e| format!("can't keep the switches ({})", e.kind()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn load(&self) -> BTreeSet<String> {
|
||||||
|
let Ok(dir) = self.dir() else {
|
||||||
|
return BTreeSet::new();
|
||||||
|
};
|
||||||
|
std::fs::read(dir.join(SWITCHES))
|
||||||
|
.ok()
|
||||||
|
.and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).ok())
|
||||||
|
.and_then(|v| {
|
||||||
|
v["books"].as_array().map(|a| {
|
||||||
|
a.iter()
|
||||||
|
.filter_map(|s| s.as_str().map(str::to_owned))
|
||||||
|
.collect()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The state of one company's web assistants (INVARIANT 5).
|
||||||
|
pub fn state(&self, book: &str) -> WebState {
|
||||||
|
let on = lock(&self.on).contains(book);
|
||||||
|
let Some(Ok(link)) = self.link.get() else {
|
||||||
|
// The link was never made: nothing is on, and whether an address
|
||||||
|
// is kept is read lazily from the folder.
|
||||||
|
let kept = self
|
||||||
|
.dir()
|
||||||
|
.map(|d| d.join("identity.json").exists())
|
||||||
|
.unwrap_or(false);
|
||||||
|
let mut s = WebState::off(kept);
|
||||||
|
if on {
|
||||||
|
s.on = true;
|
||||||
|
s.step = Step::GettingAddress;
|
||||||
|
s.words = "Getting an address…".into();
|
||||||
|
}
|
||||||
|
return s;
|
||||||
|
};
|
||||||
|
let st = link.status();
|
||||||
|
let kept = link.kept_address().is_some();
|
||||||
|
if !on {
|
||||||
|
return WebState::off(kept);
|
||||||
|
}
|
||||||
|
Self::describe(book, &st, kept, lock(&self.restore_error).clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn describe(book: &str, st: &LinkStatus, kept: bool, restore: Option<String>) -> WebState {
|
||||||
|
let address = st.address.clone();
|
||||||
|
let needs_person = st
|
||||||
|
.trouble
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|t: &Trouble| !t.mends_itself());
|
||||||
|
WebState {
|
||||||
|
on: true,
|
||||||
|
step: st.step(),
|
||||||
|
connector: address.as_ref().map(|a| format!("{a}/b/{book}/mcp")),
|
||||||
|
address,
|
||||||
|
words: st.words(),
|
||||||
|
problem: st.problem().or(restore),
|
||||||
|
needs_person,
|
||||||
|
kept,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Turn web assistants on for `book` (INVARIANTS 1, 2, 6): its words
|
||||||
|
/// say what happens next.
|
||||||
|
pub fn turn_on(&self, admin: &dyn Admin, book: &str) -> Result<String, String> {
|
||||||
|
let _one = lock(&self.busy);
|
||||||
|
let link = self.link()?.clone();
|
||||||
|
let was = lock(&self.on).clone();
|
||||||
|
let door = self.start_door(admin, &link)?;
|
||||||
|
let offered = admin.admin(Request::RemoteAllow {
|
||||||
|
book: book.into(),
|
||||||
|
allowed: true,
|
||||||
|
});
|
||||||
|
match offered {
|
||||||
|
Ok(Response::Remote(_)) => {}
|
||||||
|
Ok(Response::Refused(why)) | Err(why) => {
|
||||||
|
self.unwind(admin, &link, &was);
|
||||||
|
return Err(why);
|
||||||
|
}
|
||||||
|
Ok(other) => {
|
||||||
|
self.unwind(admin, &link, &was);
|
||||||
|
return Err(format!("the books server answered oddly: {other:?}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut now = was.clone();
|
||||||
|
now.insert(book.to_owned());
|
||||||
|
if let Err(why) = self.save(&now) {
|
||||||
|
let _ = admin.admin(Request::RemoteAllow {
|
||||||
|
book: book.into(),
|
||||||
|
allowed: false,
|
||||||
|
});
|
||||||
|
self.unwind(admin, &link, &was);
|
||||||
|
return Err(why);
|
||||||
|
}
|
||||||
|
*lock(&self.on) = now;
|
||||||
|
*lock(&self.restore_error) = None;
|
||||||
|
link.set_door(Some(door));
|
||||||
|
Ok("Web assistants are on. Getting an address and a certificate takes a moment.".into())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The door first (it listens on this computer only), then the line:
|
||||||
|
/// the line is turned on, so the address is known, and the door is
|
||||||
|
/// started as that address.
|
||||||
|
fn start_door(&self, admin: &dyn Admin, link: &Arc<Link>) -> Result<DoorTarget, String> {
|
||||||
|
link.turn_on().map_err(|e| e.to_string())?;
|
||||||
|
let address = link
|
||||||
|
.status()
|
||||||
|
.address
|
||||||
|
.ok_or("Wanderbooks has no address for this yet")?;
|
||||||
|
let info = match admin.admin(Request::RemoteStart {
|
||||||
|
public_url: address,
|
||||||
|
port: None,
|
||||||
|
}) {
|
||||||
|
Ok(Response::Remote(info)) => info,
|
||||||
|
Ok(Response::Refused(why)) | Err(why) => {
|
||||||
|
if lock(&self.on).is_empty() {
|
||||||
|
link.turn_off();
|
||||||
|
}
|
||||||
|
return Err(why);
|
||||||
|
}
|
||||||
|
Ok(other) => {
|
||||||
|
if lock(&self.on).is_empty() {
|
||||||
|
link.turn_off();
|
||||||
|
}
|
||||||
|
return Err(format!("the books server answered oddly: {other:?}"));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let listening = info
|
||||||
|
.listening
|
||||||
|
.ok_or("the books server's door isn't listening")?
|
||||||
|
.parse()
|
||||||
|
.map_err(|_| "the books server's door has an odd address".to_string())?;
|
||||||
|
let secret = info
|
||||||
|
.proxy_secret
|
||||||
|
.ok_or("the books server gave no secret for its door")?;
|
||||||
|
DoorTarget::new(listening, &secret.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Put things back as they were `before` a failed change (INVARIANT 6).
|
||||||
|
fn unwind(&self, admin: &dyn Admin, link: &Arc<Link>, before: &BTreeSet<String>) {
|
||||||
|
if before.is_empty() {
|
||||||
|
link.turn_off();
|
||||||
|
link.set_door(None);
|
||||||
|
let _ = admin.admin(Request::RemoteStop);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Turn web assistants off for `book` (INVARIANT 2): with no company
|
||||||
|
/// left offered, the line closes first, then the door.
|
||||||
|
pub fn turn_off(&self, admin: &dyn Admin, book: &str) -> Result<String, String> {
|
||||||
|
let _one = lock(&self.busy);
|
||||||
|
let mut now = lock(&self.on).clone();
|
||||||
|
now.remove(book);
|
||||||
|
// Withdraw the company first: nothing new reaches its books.
|
||||||
|
let withdrawn = admin.admin(Request::RemoteAllow {
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
if now.is_empty()
|
||||||
|
&& let Some(Ok(link)) = self.link.get()
|
||||||
|
{
|
||||||
|
link.turn_off();
|
||||||
|
link.set_door(None);
|
||||||
|
let _ = admin.admin(Request::RemoteStop);
|
||||||
|
}
|
||||||
|
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(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A new address (INVARIANT 3): the one the web assistants use for
|
||||||
|
/// every company changes; the old one stops working.
|
||||||
|
pub fn new_address(&self, admin: &dyn Admin) -> Result<String, String> {
|
||||||
|
let _one = lock(&self.busy);
|
||||||
|
let link = self.link()?.clone();
|
||||||
|
let on = !lock(&self.on).is_empty();
|
||||||
|
if on {
|
||||||
|
// The old door goes first: nothing signs in at the old address
|
||||||
|
// while the new one is made.
|
||||||
|
let _ = admin.admin(Request::RemoteStop);
|
||||||
|
link.set_door(None);
|
||||||
|
}
|
||||||
|
let new = link.new_address().map_err(|e| e.to_string())?;
|
||||||
|
if on {
|
||||||
|
let door = self.start_door(admin, &link)?;
|
||||||
|
let allowed: Vec<String> = lock(&self.on).iter().cloned().collect();
|
||||||
|
for book in allowed {
|
||||||
|
let _ = admin.admin(Request::RemoteAllow {
|
||||||
|
book,
|
||||||
|
allowed: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
link.set_door(Some(door));
|
||||||
|
}
|
||||||
|
Ok(format!(
|
||||||
|
"Your new address is ready ({new}). The old one has stopped working: connect your assistants again with the new one."
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Put the switches back as they were when the app closed, for the
|
||||||
|
/// companies that are open (INVARIANT 4).
|
||||||
|
pub fn restore(&self, admin: &dyn Admin, open: &[String]) {
|
||||||
|
let kept = self.load();
|
||||||
|
for book in open {
|
||||||
|
if kept.contains(book)
|
||||||
|
&& !lock(&self.on).contains(book)
|
||||||
|
&& let Err(why) = self.turn_on(admin, book)
|
||||||
|
{
|
||||||
|
*lock(&self.restore_error) = Some(format!(
|
||||||
|
"Web assistants could not be turned back on for {book}: {why}"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The window is closing: nothing is dialled or listened on after
|
||||||
|
/// this. The switches stay as they are on disk.
|
||||||
|
pub fn shutdown(&self) {
|
||||||
|
if let Some(Ok(link)) = self.link.get() {
|
||||||
|
link.turn_off();
|
||||||
|
link.set_door(None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The network may have changed (a laptop woke): dial again now.
|
||||||
|
pub fn nudge(&self) {
|
||||||
|
if let Some(Ok(link)) = self.link.get() {
|
||||||
|
link.nudge();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The link's own status (tests).
|
||||||
|
pub fn link_status(&self) -> Option<LinkStatus> {
|
||||||
|
self.link
|
||||||
|
.get()
|
||||||
|
.and_then(|l| l.as_ref().ok())
|
||||||
|
.map(|l| l.status())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for WebAssistants {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.shutdown();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -34,6 +34,7 @@ struct Server {
|
|||||||
orders: Vec<Order>,
|
orders: Vec<Order>,
|
||||||
ari_gets: u32,
|
ari_gets: u32,
|
||||||
refuse_orders: bool,
|
refuse_orders: bool,
|
||||||
|
certs: HashMap<usize, String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
struct Order {
|
struct Order {
|
||||||
@@ -150,7 +151,11 @@ impl FakeAcme {
|
|||||||
if let Some(r) = replaces {
|
if let Some(r) = replaces {
|
||||||
order["replaces"] = r.into();
|
order["replaces"] = r.into();
|
||||||
}
|
}
|
||||||
with_nonce(json(201, vec![("location", format!("{BASE}/order/{id}"))], order))
|
with_nonce(json(
|
||||||
|
201,
|
||||||
|
vec![("location", format!("{BASE}/order/{id}"))],
|
||||||
|
order,
|
||||||
|
))
|
||||||
}
|
}
|
||||||
("POST", p) if p.starts_with("/authz/") => {
|
("POST", p) if p.starts_with("/authz/") => {
|
||||||
let id: usize = p[7..].parse().unwrap();
|
let id: usize = p[7..].parse().unwrap();
|
||||||
@@ -180,8 +185,7 @@ impl FakeAcme {
|
|||||||
B64.encode(Sha256::digest(ka.as_bytes())),
|
B64.encode(Sha256::digest(ka.as_bytes())),
|
||||||
)
|
)
|
||||||
};
|
};
|
||||||
let seen =
|
let seen = support::dns_txt(self.dns, &format!("_acme-challenge.{ident}.")).await;
|
||||||
support::dns_txt(self.dns, &format!("_acme-challenge.{ident}.")).await;
|
|
||||||
let ok = seen.contains(&expected);
|
let ok = seen.contains(&expected);
|
||||||
self.state.lock().unwrap().orders[id - 1].authz_valid = ok;
|
self.state.lock().unwrap().orders[id - 1].authz_valid = ok;
|
||||||
with_nonce(json(
|
with_nonce(json(
|
||||||
@@ -222,7 +226,8 @@ impl FakeAcme {
|
|||||||
let cert = params.signed_by(&self.ca).unwrap();
|
let cert = params.signed_by(&self.ca).unwrap();
|
||||||
let mut s = self.state.lock().unwrap();
|
let mut s = self.state.lock().unwrap();
|
||||||
s.orders[id - 1].done = true;
|
s.orders[id - 1].done = true;
|
||||||
CERTS.lock().unwrap().insert(id, format!("{}{}", cert.pem(), self.ca.pem()));
|
s.certs
|
||||||
|
.insert(id, format!("{}{}", cert.pem(), self.ca.pem()));
|
||||||
let o = &s.orders[id - 1];
|
let o = &s.orders[id - 1];
|
||||||
with_nonce(json(
|
with_nonce(json(
|
||||||
200,
|
200,
|
||||||
@@ -239,7 +244,7 @@ impl FakeAcme {
|
|||||||
}
|
}
|
||||||
("POST", p) if p.starts_with("/cert/") => {
|
("POST", p) if p.starts_with("/cert/") => {
|
||||||
let id: usize = p[6..].parse().unwrap();
|
let id: usize = p[6..].parse().unwrap();
|
||||||
let pem = CERTS.lock().unwrap()[&id].clone();
|
let pem = self.state.lock().unwrap().certs[&id].clone();
|
||||||
with_nonce((
|
with_nonce((
|
||||||
200,
|
200,
|
||||||
vec![("content-type", "application/pem-certificate-chain".into())],
|
vec![("content-type", "application/pem-certificate-chain".into())],
|
||||||
@@ -260,14 +265,15 @@ impl FakeAcme {
|
|||||||
serde_json::json!({"suggestedWindow":{"start":at(self.window.0),"end":at(self.window.1)}}),
|
serde_json::json!({"suggestedWindow":{"start":at(self.window.0),"end":at(self.window.1)}}),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
_ => json(404, vec![], serde_json::json!({"type":"urn:ietf:params:acme:error:malformed","detail":"no such path"})),
|
_ => json(
|
||||||
|
404,
|
||||||
|
vec![],
|
||||||
|
serde_json::json!({"type":"urn:ietf:params:acme:error:malformed","detail":"no such path"}),
|
||||||
|
),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static CERTS: std::sync::LazyLock<Mutex<HashMap<usize, String>>> =
|
|
||||||
std::sync::LazyLock::new(|| Mutex::new(HashMap::new()));
|
|
||||||
|
|
||||||
struct Http(Arc<FakeAcme>);
|
struct Http(Arc<FakeAcme>);
|
||||||
|
|
||||||
impl HttpClient for Http {
|
impl HttpClient for Http {
|
||||||
@@ -278,7 +284,11 @@ impl HttpClient for Http {
|
|||||||
let fake = self.0.clone();
|
let fake = self.0.clone();
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
let (parts, body) = req.into_parts();
|
let (parts, body) = req.into_parts();
|
||||||
let bytes = body.collect().await.map_err(|e| Error::Other(e.into()))?.to_bytes();
|
let bytes = body
|
||||||
|
.collect()
|
||||||
|
.await
|
||||||
|
.map_err(|e| Error::Other(e.into()))?
|
||||||
|
.to_bytes();
|
||||||
let path = parts.uri.path().to_owned();
|
let path = parts.uri.path().to_owned();
|
||||||
assert_eq!(parts.uri.host(), Some("acme.test"));
|
assert_eq!(parts.uri.host(), Some("acme.test"));
|
||||||
let (status, headers, out) = fake.handle(parts.method.as_str(), &path, &bytes).await;
|
let (status, headers, out) = fake.handle(parts.method.as_str(), &path, &bytes).await;
|
||||||
@@ -301,7 +311,11 @@ impl DnsProof for Proof {
|
|||||||
fn publish<'a>(&'a self, value: &'a str) -> BoxFuture<'a, Result<(), String>> {
|
fn publish<'a>(&'a self, value: &'a str) -> BoxFuture<'a, Result<(), String>> {
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
let r = self.0.publish_txt(value).await.map_err(|e| e.to_string())?;
|
let r = self.0.publish_txt(value).await.map_err(|e| e.to_string())?;
|
||||||
if r.ok { Ok(()) } else { Err(r.error.unwrap_or_default()) }
|
if r.ok {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(r.error.unwrap_or_default())
|
||||||
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
fn clear(&self) -> BoxFuture<'_, ()> {
|
fn clear(&self) -> BoxFuture<'_, ()> {
|
||||||
@@ -384,11 +398,13 @@ async fn an_order_goes_through_account_proof_finalize_and_download() {
|
|||||||
.unwrap();
|
.unwrap();
|
||||||
let der = leaf_der(&issued.chain_pem).unwrap();
|
let der = leaf_der(&issued.chain_pem).unwrap();
|
||||||
let (nb, na, names) = inspect(&der).unwrap();
|
let (nb, na, names) = inspect(&der).unwrap();
|
||||||
assert_eq!(names, [ident.clone()]);
|
assert_eq!(names, std::slice::from_ref(&ident));
|
||||||
assert!(nb < certs::now() && na > certs::now());
|
assert!(nb < certs::now() && na > certs::now());
|
||||||
assert!(issued.key_pem.contains("PRIVATE KEY"));
|
assert!(issued.key_pem.contains("PRIVATE KEY"));
|
||||||
// The certificate and key go together (the store checks it).
|
// The certificate and key go together (the store checks it).
|
||||||
assert!(certs::StoredCert::new("ledger-accrual-tally-mint", "fake", &issued, &ident, None).is_ok());
|
assert!(
|
||||||
|
certs::StoredCert::new("ledger-accrual-tally-mint", "fake", &issued, &ident, None).is_ok()
|
||||||
|
);
|
||||||
|
|
||||||
// The account is kept in a private file, with no contact in it.
|
// The account is kept in a private file, with no contact in it.
|
||||||
let file = r.dir.path().join("acme/fake.json");
|
let file = r.dir.path().join("acme/fake.json");
|
||||||
@@ -396,13 +412,22 @@ async fn an_order_goes_through_account_proof_finalize_and_download() {
|
|||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
{
|
{
|
||||||
use std::os::unix::fs::PermissionsExt;
|
use std::os::unix::fs::PermissionsExt;
|
||||||
assert_eq!(std::fs::metadata(&file).unwrap().permissions().mode() & 0o777, 0o600);
|
assert_eq!(
|
||||||
|
std::fs::metadata(&file).unwrap().permissions().mode() & 0o777,
|
||||||
|
0o600
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
{
|
||||||
let st = r.acme.state.lock().unwrap();
|
let st = r.acme.state.lock().unwrap();
|
||||||
|
|
||||||
assert_eq!(st.new_accounts.len(), 1);
|
assert_eq!(st.new_accounts.len(), 1);
|
||||||
assert!(st.new_accounts[0]["contact"].as_array().is_none_or(|c| c.is_empty()));
|
assert!(
|
||||||
|
st.new_accounts[0]["contact"]
|
||||||
|
.as_array()
|
||||||
|
.is_none_or(|c| c.is_empty())
|
||||||
|
);
|
||||||
assert_eq!(st.new_accounts[0]["termsOfServiceAgreed"], true);
|
assert_eq!(st.new_accounts[0]["termsOfServiceAgreed"], true);
|
||||||
drop(st);
|
}
|
||||||
// The relay holds no proof once the order is done.
|
// The relay holds no proof once the order is done.
|
||||||
let left = support::dns_txt(
|
let left = support::dns_txt(
|
||||||
r.env.relay.dns_udp_addr(),
|
r.env.relay.dns_udp_addr(),
|
||||||
@@ -441,7 +466,10 @@ async fn a_renewal_reuses_the_account_names_what_it_replaces_and_reads_the_windo
|
|||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert_ne!(first.chain_pem, second.chain_pem);
|
assert_ne!(first.chain_pem, second.chain_pem);
|
||||||
assert_ne!(*first.key_pem, *second.key_pem, "a fresh key for each certificate");
|
assert_ne!(
|
||||||
|
*first.key_pem, *second.key_pem,
|
||||||
|
"a fresh key for each certificate"
|
||||||
|
);
|
||||||
{
|
{
|
||||||
let st = r.acme.state.lock().unwrap();
|
let st = r.acme.state.lock().unwrap();
|
||||||
assert_eq!(st.new_accounts.len(), 1, "the account was reused");
|
assert_eq!(st.new_accounts.len(), 1, "the account was reused");
|
||||||
@@ -455,7 +483,10 @@ async fn a_renewal_reuses_the_account_names_what_it_replaces_and_reads_the_windo
|
|||||||
.await
|
.await
|
||||||
.expect("the authority offers a window");
|
.expect("the authority offers a window");
|
||||||
let now = certs::now();
|
let now = certs::now();
|
||||||
assert!((now + 590..=now + 610).contains(&s) && (now + 890..=now + 910).contains(&e), "{s} {e} {now}");
|
assert!(
|
||||||
|
(now + 590..=now + 610).contains(&s) && (now + 890..=now + 910).contains(&e),
|
||||||
|
"{s} {e} {now}"
|
||||||
|
);
|
||||||
assert_eq!(r.acme.state.lock().unwrap().ari_gets, 1);
|
assert_eq!(r.acme.state.lock().unwrap().ari_gets, 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user