diff --git a/Cargo.lock b/Cargo.lock index de6d3aec..069e9e90 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4119,7 +4119,9 @@ dependencies = [ "base64 0.22.1", "chrono", "futures-util", + "getrandom 0.2.17", "http-body-util", + "hyper-util", "ledger-config", "ledger-core", "ledger-import", @@ -4127,12 +4129,14 @@ dependencies = [ "ledger-store", "ledger-vault", "libc", + "reqwest", "rmcp", "rust_decimal", "schemars", "serde", "serde_json", "sha2 0.10.9", + "subtle", "tempfile", "thiserror 2.0.21", "tokio", diff --git a/crates/ledger-cli/src/main.rs b/crates/ledger-cli/src/main.rs index 3a6bfb9e..d6b10dff 100644 --- a/crates/ledger-cli/src/main.rs +++ b/crates/ledger-cli/src/main.rs @@ -149,7 +149,54 @@ impl ledger_gui::owner::Owner for ViewerOwner { created: t.created, }) .collect(); - Ok(Roster { assistants, tokens }) + // The web assistants waiting, and those allowed: nothing when the + // remote door was never turned on. + let web = self + .server + .web_roster(std::time::Duration::from_secs(3)) + .unwrap_or_default(); + let web_pending = web + .pending + .into_iter() + .map(|p| ledger_gui::owner::WebRequest { + id: p.id, + book: p.book, + client_name: p.client_name, + known_host: p.known_host, + code: p.code, + redirect: p.redirect, + redirect_host: p.redirect_host, + from: p.from, + wants_post: p.wants_post, + expires_in_secs: p.expires_in_secs, + }) + .collect(); + let web_approvals = web + .approvals + .into_iter() + .map(|a| ledger_gui::owner::WebApproval { + id: a.id, + book: a.book, + label: a.label, + token_id: a.token_id, + may_post: a.may_post, + last_used: a.last_used, + }) + .collect(); + Ok(Roster { + assistants, + tokens, + web_pending, + web_approvals, + }) + } + + fn web_decide(&self, id: &str, approve: bool, post: bool) -> Result { + self.server.web_decide(id, approve, post) + } + + fn web_set_post(&self, approval: &str, post: bool) -> Result { + self.server.web_set_post(approval, post) } fn serve_revoke(&self, book: &str, name: &str, id: &str) -> Result { diff --git a/crates/ledger-gui/src/company.rs b/crates/ledger-gui/src/company.rs index 6d69b85e..0757b15d 100644 --- a/crates/ledger-gui/src/company.rs +++ b/crates/ledger-gui/src/company.rs @@ -574,6 +574,13 @@ impl CompanyView { if crate::connect::take_go(ui.ctx()) { self.nav.go(Route::Connect); } + // A web assistant asking to connect is asked about over + // whatever page this is (the Connect page has its own card). + if route != Route::Connect { + let spawner = self.jobs.spawner(); + self.connect + .web_prompt(ui, &self.assist, &self.owner.clone(), &spawner); + } if let Some(to) = self.palette.show(ui.ctx(), &books) { self.nav.go(to); } diff --git a/crates/ledger-gui/src/connect.rs b/crates/ledger-gui/src/connect.rs index ee75922a..00adcbdd 100644 --- a/crates/ledger-gui/src/connect.rs +++ b/crates/ledger-gui/src/connect.rs @@ -44,8 +44,23 @@ //! off the UI thread; what is shown while it is not known is "not //! known", never a guess. //! 7. The web half of the page (the switch, the address, the steps for -//! Claude and ChatGPT) is unit B3's: `State::web_section` is its -//! place, and it draws nothing until then. +//! Claude and ChatGPT) is unit B3's. Unit B1's part of it is here: a +//! web assistant that asks to connect is shown to the person, in +//! words, as a card that says who is asking, where it is sent back +//! to, the address it asked from and what it will be able to do, with +//! Allow and Don't allow; it appears over any page of the company +//! (`State::web_prompt`) and on this page (`State::web_section`). +//! Nothing on the web page can approve: only these buttons do, through +//! the owner. What is known is said in neutral words, where it will be +//! sent back to first ("An assistant that will be sent back to +//! claude.ai"), never as a known or trusted product on the strength of +//! that address: a host is public, and says nothing of who asks. Each +//! card shows its own short code, the one its browser page shows, and +//! says to allow only on a match; at most MOST_CARDS cards are drawn +//! at once, the newest, and the rest are counted. What the assistant +//! calls itself is shown in quotes, after the address. Posting is off +//! unless the person ticks it, per assistant, and can be turned on or +//! off later; every Allow is a new approval with only what is ticked. //! ``` use crate::connections::{Connection, Link, Status, describe, program_name}; @@ -400,6 +415,9 @@ pub struct State { confirm: Option, /// A revoke ended: the state is read again. refresh: bool, + /// The waiting web assistants the person has ticked "let it post + /// entries too" for. + post_asked: std::collections::BTreeSet, } /// The two lines an assistant set up by hand needs. @@ -433,10 +451,249 @@ impl State { self.confirm.as_deref() } - /// The web half of the page: "Allow web assistants", the address with - /// Copy, and the steps for Claude and ChatGPT. Unit B3 draws it here; - /// nothing until then (INVARIANT 7). - fn web_section(&mut self, _ui: &mut Ui, _status: &Status) {} + /// What the person is asked of a web assistant, and what they may do + /// about the web connections already allowed (INVARIANT 7). Unit B3 + /// draws the switch, the address and the steps above this. + fn web_section( + &mut self, + ui: &mut Ui, + status: &Status, + owner: &Option>, + jobs: &crate::jobs::Spawner, + ) { + if status.web_pending.is_empty() && status.web_approvals.is_empty() { + return; + } + let p = pal(ui.ctx()); + ui.add_space(24.0); + section(ui, "Assistants on the web"); + let mut want: Want = None; + let (shown, more) = newest_waiting(&status.web_pending); + for request in shown { + if let Some(w) = self.pending_card(ui, status, request, owner) { + want = Some(w); + } + ui.add_space(6.0); + } + say_more_waiting(ui, more); + for a in &status.web_approvals { + Frame::new() + .fill(p.surface) + .stroke(Stroke::new(1.0, p.border)) + .corner_radius(CornerRadius::same(8)) + .inner_margin(Margin::symmetric(12, 10)) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal(|ui| { + ui.vertical(|ui| { + ui.label(RichText::new(&a.label).font(theme::semibold(13.5))); + ui.label( + RichText::new(if a.may_post { + "Can read, draft and post entries." + } else { + "Can read and draft entries. It can't post them." + }) + .font(theme::regular(12.5)) + .color(p.muted), + ); + }); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + if owner.is_none() || self.job.is_some() { + return; + } + let (label, to) = if a.may_post { + ("Stop letting it post", false) + } else { + ("Let it post entries", true) + }; + if ui.button(label).clicked() { + let (o, id) = (owner.clone(), a.id.clone()); + if let Some(o) = o { + want = Some(( + format!("Posting for {}", a.label), + "Changing what an assistant may do".to_string(), + Box::new(move || o.web_set_post(&id, to)), + )); + } + } + }); + }); + }); + ui.add_space(6.0); + } + if let Some((what, keep, work)) = want { + self.start(ui, jobs, what, &keep, work); + } + } + + /// One assistant asking to connect: who, from where, what it will be + /// able to do, and Allow and Don't allow. The answer to ask for, if + /// the person gave one. + fn pending_card( + &mut self, + ui: &mut Ui, + status: &Status, + request: &crate::owner::WebRequest, + owner: &Option>, + ) -> Want { + let can_answer = owner.is_some(); + let p = pal(ui.ctx()); + let mut answer: Option<(bool, bool)> = None; + Frame::new() + .fill(p.surface) + .stroke(Stroke::new(1.5, p.accent)) + .corner_radius(CornerRadius::same(8)) + .inner_margin(Margin::symmetric(14, 12)) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + // What is known is said in neutral words: where it will be + // sent back to first, never a product's name made from it. + ui.label( + RichText::new(format!( + "An assistant that will be sent back to {} wants to connect to {}. Allow?", + request.redirect_host, status.company + )) + .font(theme::semibold(15.0)), + ); + if !request.client_name.is_empty() { + ui.label( + RichText::new(format!( + "It calls itself \u{201c}{}\u{201d}. That is only its own word for itself.", + request.client_name + )) + .font(theme::regular(13.0)) + .color(p.muted), + ); + } + ui.add_space(4.0); + ui.label( + RichText::new(format!("Code {}", request.code)).font(theme::semibold(22.0)), + ); + ui.label( + RichText::new( + "Allow only if the page in your browser shows this same code. If it shows another code, or you didn't just ask an assistant to connect, choose Don't allow.", + ) + .font(theme::regular(13.0)) + .color(p.muted), + ); + if !request.known_host { + ui.label( + RichText::new( + "Wanderbooks doesn't know this address. Don't allow it unless you just set this assistant up yourself.", + ) + .font(theme::regular(13.0)) + .color(p.warning), + ); + } + ui.label( + RichText::new(format!( + "After you answer, it is sent back to {}. The request came from the internet address {}.", + request.redirect_host, request.from + )) + .font(theme::regular(12.5)) + .color(p.muted), + ); + ui.label( + RichText::new( + "If you allow it, it can read these books and draft entries. It can't post entries unless you tick the box below.", + ) + .font(theme::regular(12.5)) + .color(p.muted), + ); + let mut post = self.post_asked.contains(&request.id); + if ui + .checkbox( + &mut post, + if request.wants_post { + "Also let it post entries (it asked to)" + } else { + "Also let it post entries" + }, + ) + .changed() + { + if post { + self.post_asked.insert(request.id.clone()); + } else { + self.post_asked.remove(&request.id); + } + } + ui.add_space(6.0); + ui.horizontal(|ui| { + let enabled = can_answer && self.job.is_none(); + if ui.add_enabled(enabled, egui::Button::new("Allow")).clicked() { + answer = Some((true, post)); + } + if ui + .add_enabled(enabled, egui::Button::new("Don't allow")) + .clicked() + { + answer = Some((false, false)); + } + ui.label( + RichText::new(format!( + "Waiting {} more minute(s)", + request.expires_in_secs.div_ceil(60) + )) + .font(theme::regular(12.0)) + .color(p.muted), + ); + }); + }); + let (approve, post) = answer?; + self.post_asked.remove(&request.id); + let owner = owner.clone()?; + let id = request.id.clone(); + let what = if approve { + format!("Allow the assistant sent back to {}", request.redirect_host) + } else { + format!( + "Don't allow the assistant sent back to {}", + request.redirect_host + ) + }; + Some(( + what, + "Answering an assistant".to_string(), + Box::new(move || owner.web_decide(&id, approve, post)), + )) + } + + /// The question over any page of the company: a web assistant asking + /// to connect is not something to find by looking for it (INVARIANT 7). + /// Not drawn on the Connect page, which has the same card. + pub fn web_prompt( + &mut self, + ui: &Ui, + status: &Status, + owner: &Option>, + jobs: &crate::jobs::Spawner, + ) { + self.collect(); + if status.web_pending.is_empty() { + return; + } + ui.ctx() + .request_repaint_after(std::time::Duration::from_millis(500)); + let mut want: Want = None; + egui::Window::new("An assistant wants to connect") + .collapsible(false) + .resizable(false) + .anchor(egui::Align2::CENTER_CENTER, vec2(0.0, 0.0)) + .show(ui.ctx(), |win| { + let (shown, more) = newest_waiting(&status.web_pending); + for request in shown { + if let Some(w) = self.pending_card(win, status, request, owner) { + want = Some(w); + } + win.add_space(6.0); + } + say_more_waiting(win, more); + }); + if let Some((what, keep, work)) = want { + self.start(ui, jobs, what, &keep, work); + } + } fn collect(&mut self) { if let Some((what, rx)) = &self.job @@ -444,7 +701,11 @@ impl State { { // Whatever came of it (a key already gone, a file left behind), // the list is read again. - if what.starts_with("Revoke") { + if what.starts_with("Revoke") + || what.starts_with("Allow") + || what.starts_with("Don't allow") + || what.starts_with("Posting") + { self.refresh = true; } self.done = Some((what.clone(), result)); @@ -558,7 +819,7 @@ impl State { ), }; } - self.web_section(ui, status); + self.web_section(ui, status, &owner, jobs); ui.add_space(24.0); self.connections(ui, status, book, &owner, jobs); }); @@ -624,6 +885,36 @@ impl State { } } +/// The most requests drawn at once: a few addresses must not be able to +/// bury the one the person is waiting for under a screenful. +pub const MOST_CARDS: usize = 3; + +/// The newest requests (the one just asked for is the one the person is +/// looking for), and how many more are waiting. +fn newest_waiting(all: &[crate::owner::WebRequest]) -> (Vec<&crate::owner::WebRequest>, usize) { + let mut sorted: Vec<&crate::owner::WebRequest> = all.iter().collect(); + // Most time left is the newest. + sorted.sort_by_key(|r| std::cmp::Reverse(r.expires_in_secs)); + let more = sorted.len().saturating_sub(MOST_CARDS); + sorted.truncate(MOST_CARDS); + (sorted, more) +} + +fn say_more_waiting(ui: &mut Ui, more: usize) { + if more == 0 { + return; + } + let p = pal(ui.ctx()); + ui.label( + RichText::new(format!( + "{more} more {} waiting. Answer these first; the next ones then show.", + if more == 1 { "is" } else { "are" } + )) + .font(theme::regular(12.5)) + .color(p.muted), + ); +} + fn section(ui: &mut Ui, title: &str) { ui.label(RichText::new(title).font(theme::semibold(17.0))); ui.add_space(4.0); diff --git a/crates/ledger-gui/src/connections.rs b/crates/ledger-gui/src/connections.rs index 6f458e12..8ecdc13e 100644 --- a/crates/ledger-gui/src/connections.rs +++ b/crates/ledger-gui/src/connections.rs @@ -34,7 +34,7 @@ //! 5. Nothing here holds a token's text: the server never sends one. //! ``` -use crate::owner::{Assistant, LastCall, Owner, Roster, TokenRow}; +use crate::owner::{Assistant, LastCall, Owner, Roster, TokenRow, WebApproval, WebRequest}; use chrono::{DateTime, Utc}; use egui_phosphor::regular as icon; use std::sync::{Arc, Mutex, MutexGuard}; @@ -94,6 +94,10 @@ pub struct Status { pub assistants: Vec, /// The tokens of this company: who may connect. pub tokens: Vec, + /// Web assistants waiting for the person to allow them. + pub web_pending: Vec, + /// The web connections the person allowed. + pub web_approvals: Vec, /// "Now", for "10 seconds ago" (fixed in tests and screenshots). pub now: DateTime, } @@ -108,6 +112,8 @@ impl Status { link: Link::Unknown, assistants: Vec::new(), tokens: Vec::new(), + web_pending: Vec::new(), + web_approvals: Vec::new(), now: Utc::now(), } } @@ -561,6 +567,16 @@ impl Connections { .into_iter() .filter(|t| t.book == book) .collect(); + status.web_pending = roster + .web_pending + .into_iter() + .filter(|r| r.book == book) + .collect(); + status.web_approvals = roster + .web_approvals + .into_iter() + .filter(|a| a.book == book) + .collect(); status.link = if status.assistants.is_empty() { Link::None } else if status.assistants.iter().any(|a| a.running > 0) { diff --git a/crates/ledger-gui/src/owner.rs b/crates/ledger-gui/src/owner.rs index 64d4b096..489b3ff7 100644 --- a/crates/ledger-gui/src/owner.rs +++ b/crates/ledger-gui/src/owner.rs @@ -203,6 +203,54 @@ pub struct TokenRow { pub created: String, } +/// A web assistant waiting for the person to allow it (plan P15 D-83): who +/// is asking, as the server saw it. What it calls itself is its own word, +/// cleaned and never trusted; where it is sent back to and the address it +/// asked from are what the server saw. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct WebRequest { + /// What an answer names. + pub id: String, + /// The company it asks to reach. + pub book: String, + /// What it calls itself: its own word, cleaned and short, possibly + /// empty. Never a product's name made from where it is sent back to. + pub client_name: String, + /// Whether the address it is sent back to is one of the vendors' known + /// hosts. Only the warning depends on it; nothing is shown as known or + /// trusted for it. + pub known_host: bool, + /// The short code to match with the one its browser page shows. + pub code: String, + /// The address it is sent back to, in full. + pub redirect: String, + /// That address's host. + pub redirect_host: String, + /// The caller's address, as the relay said it. + pub from: String, + /// It asked to post entries too. + pub wants_post: bool, + /// Seconds until it is turned away unanswered. + pub expires_in_secs: u64, +} + +/// A web connection the person allowed. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct WebApproval { + /// Its id. + pub id: String, + /// The company. + pub book: String, + /// What it is called. + pub label: String, + /// The key that carries it: what "Who can reach these books" revokes. + pub token_id: String, + /// It may post entries (else read and draft). + pub may_post: bool, + /// When it last did anything (unix seconds). + pub last_used: Option, +} + /// Who is connected and who may connect, across the open companies. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct Roster { @@ -210,6 +258,10 @@ pub struct Roster { pub assistants: Vec, /// Every live token. pub tokens: Vec, + /// Web assistants waiting for the person. + pub web_pending: Vec, + /// Web connections the person allowed. + pub web_approvals: Vec, } /// The owner's actions, done by the program the viewer runs in (ledger-cli @@ -272,6 +324,16 @@ pub trait Owner: Send + Sync { fn serve_revoke(&self, _book: &str, _name: &str, _id: &str) -> Result { Err("not here".into()) } + /// The person's answer to a web assistant waiting to be allowed: + /// `approve` it or refuse it; `post` lets it post entries too, not + /// only read and draft. `Ok` says what was done, in words. Blocks. + fn web_decide(&self, _id: &str, _approve: bool, _post: bool) -> Result { + Err("not here".into()) + } + /// Let a web connection post entries, or take that away. Blocks. + fn web_set_post(&self, _approval: &str, _post: bool) -> Result { + Err("not here".into()) + } /// This program run with `words`, as a line to type in a terminal (the /// program's own path, the words, the data root if one was named): what /// the Connect page shows for an assistant it has no button for. diff --git a/crates/ledger-gui/tests/assistants.rs b/crates/ledger-gui/tests/assistants.rs index 28ba5ceb..7bc1903a 100644 --- a/crates/ledger-gui/tests/assistants.rs +++ b/crates/ledger-gui/tests/assistants.rs @@ -42,7 +42,9 @@ use ledger_core::{AccountType, Currency}; use ledger_gui::connections::Link; use ledger_gui::data::Source; use ledger_gui::nav::Route; -use ledger_gui::owner::{Agent, Assistant, LastCall, Owner, RestorePlan, Roster, TokenRow}; +use ledger_gui::owner::{ + Agent, Assistant, LastCall, Owner, RestorePlan, Roster, TokenRow, WebApproval, WebRequest, +}; use ledger_gui::{App, Start}; use ledger_store::root::{BookId, Root}; use std::collections::HashMap; @@ -196,6 +198,44 @@ impl Owner for Fake { } Ok(format!("Ended {name:?}'s access to {book}.")) } + fn web_decide(&self, id: &str, approve: bool, post: bool) -> Result { + self.note(format!("web_decide {id} {approve} {post}")); + // As the server does: it is no longer waiting, and an allowed one + // is a connection. + if let Some(Ok(r)) = self.roster.lock().unwrap().as_mut() { + let gone: Vec<_> = r + .web_pending + .iter() + .filter(|p| p.id == id) + .cloned() + .collect(); + r.web_pending.retain(|p| p.id != id); + if approve { + for p in gone { + r.web_approvals.push(WebApproval { + id: format!("apr_{id}"), + book: p.book, + label: p.client_name, + token_id: "tok_1".into(), + may_post: post, + last_used: None, + }); + } + } + } + Ok("done".into()) + } + fn web_set_post(&self, approval: &str, post: bool) -> Result { + self.note(format!("web_set_post {approval} {post}")); + if let Some(Ok(r)) = self.roster.lock().unwrap().as_mut() { + for a in &mut r.web_approvals { + if a.id == approval { + a.may_post = post; + } + } + } + Ok("done".into()) + } fn command_line(&self, words: &[&str]) -> Result { Ok(format!("/opt/wanderbooks {}", words.join(" "))) } @@ -257,7 +297,11 @@ fn token(book: &str, name: &str) -> TokenRow { } fn roster(assistants: Vec, tokens: Vec) -> Result { - Ok(Roster { assistants, tokens }) + Ok(Roster { + assistants, + tokens, + ..Roster::default() + }) } /// The app over `ids` as tabs (the first in front), served by `owner`. @@ -1033,3 +1077,231 @@ fn pictures() { save(&mut tall, &format!("9-connect-another-{mode}")); } } + +// ---- 7: a web assistant asks to connect (plan P15 D-83, unit B1) -------------- + +fn asking(id: &str, name: &str, known_host: bool) -> WebRequest { + WebRequest { + id: id.into(), + book: "alpha".into(), + client_name: name.into(), + known_host, + code: format!("482 {}", 100 + id.len()), + redirect: "https://claude.ai/api/mcp/auth_callback".into(), + redirect_host: "claude.ai".into(), + from: "203.0.113.9".into(), + wants_post: false, + expires_in_secs: 240, + } +} + +fn with_pending(owner: &Fake, pending: Vec, approvals: Vec) { + owner.answer(Ok(Roster { + web_pending: pending, + web_approvals: approvals, + ..Roster::default() + })); +} + +#[test] +fn a_web_assistant_asking_is_put_to_the_person_over_any_page_in_plain_words() { + let w = World::new(&[("alpha", "Wanderland Labs")]); + let owner = Fake::new(); + with_pending(&owner, vec![asking("p_1", "Claude", true)], vec![]); + let mut h = start(&w, &["alpha"], &owner); + refresh(&mut h); + // On the company's own page, not the Connect page. + assert_ne!(h.state().route(), &Route::Connect); + // Where it is sent back to first, in neutral words: a host says nothing + // of who asks, so nothing is called a known product, and the one + // address of a vendor is not warned about, nor praised. + assert!( + h.query_by_label_contains( + "An assistant that will be sent back to claude.ai wants to connect to Wanderland Labs. Allow?" + ) + .is_some() + ); + assert!(h.query_by_label_contains("Claude on the web").is_none()); + assert!( + h.query_by_label_contains("doesn't know this address") + .is_none() + ); + // What it calls itself, after the address, as its own word. + assert!(h.query_by_label_contains("It calls itself").is_some()); + // The code to match with the one the browser's page shows. + assert!(h.query_by_label_contains("Code 482 103").is_some()); + assert!( + h.query_by_label_contains("Allow only if the page in your browser shows this same code") + .is_some() + ); + // Who, where it goes, from where: in words, nothing about OAuth. + assert!( + h.query_all_by_label_contains("The request came from the internet address 203.0.113.9") + .next() + .is_some() + ); + assert!( + h.query_by_label_contains("can't post entries unless you tick") + .is_some() + ); + for word in ["OAuth", "token", "MCP"] { + assert!( + h.query_by_label_contains(word).is_none(), + "{word} is not a word for the person" + ); + } + // Nothing is decided by looking at it. + assert!(!owner.said().iter().any(|s| s.starts_with("web_decide"))); + h.get_by_role_and_label(Role::Button, "Allow").click(); + h.run_steps(2); + wait_for("the answer was given", || { + owner + .said() + .contains(&"web_decide p_1 true false".to_string()) + }); + // Posting stayed off. The question goes away once the server stops + // listing it. + refresh(&mut h); + assert!(h.query_by_label_contains("wants to connect").is_none()); + drop(h); +} + +#[test] +fn refusing_and_allowing_with_posting_are_their_own_answers() { + let w = World::new(&[("alpha", "Wanderland Labs")]); + let owner = Fake::new(); + with_pending( + &owner, + vec![asking("p_7", "Someone's assistant", false)], + vec![], + ); + let mut h = start(&w, &["alpha"], &owner); + refresh(&mut h); + // An address that isn't a known vendor's keeps its warning. + assert!( + h.query_by_label_contains("doesn't know this address") + .is_some() + ); + h.get_by_role_and_label(Role::Button, "Don't allow").click(); + h.run_steps(2); + wait_for("the refusal was given", || { + owner + .said() + .contains(&"web_decide p_7 false false".to_string()) + }); + refresh(&mut h); + assert!(h.query_by_label_contains("wants to connect").is_none()); + // Another asks; this time posting is ticked, then allowed. + with_pending(&owner, vec![asking("p_8", "Claude", true)], vec![]); + refresh(&mut h); + h.get_by_label("Also let it post entries").click(); + h.run_steps(2); + h.get_by_role_and_label(Role::Button, "Allow").click(); + h.run_steps(2); + wait_for("the answer with posting was given", || { + owner + .said() + .contains(&"web_decide p_8 true true".to_string()) + }); + drop(h); +} + +#[test] +fn waiting_requests_each_show_their_own_code_and_only_a_few_are_drawn() { + let w = World::new(&[("alpha", "Wanderland Labs")]); + let owner = Fake::new(); + let mut all = Vec::new(); + for (i, id) in ["p_a", "p_b", "p_c", "p_d", "p_e"].iter().enumerate() { + let mut r = asking(id, "Claude", true); + // Never merged: each has its own code. + r.code = format!("{}{}{} 6{}{}", i, i, i, i, i); + // The later the id, the newer it is (more time left). + r.expires_in_secs = 100 + 10 * i as u64; + all.push(r); + } + with_pending(&owner, all, vec![]); + let mut h = start(&w, &["alpha"], &owner); + refresh(&mut h); + // The newest three, each with its own code; the rest are counted. + for shown in ["444 644", "333 633", "222 622"] { + assert!( + h.query_by_label_contains(&format!("Code {shown}")) + .is_some(), + "{shown}" + ); + } + for hidden in ["111 611", "000 600"] { + assert!( + h.query_by_label_contains(&format!("Code {hidden}")) + .is_none(), + "{hidden}" + ); + } + // Three cards (their titles end in the question); the window has its own title. + assert_eq!(h.query_all_by_label_contains("Allow?").count(), 3); + assert!(h.query_by_label_contains("2 more are waiting").is_some()); + drop(h); +} + +#[test] +fn a_request_that_ran_out_goes_away_and_posting_is_turned_on_and_off_on_the_connect_page() { + let w = World::new(&[("alpha", "Wanderland Labs")]); + let owner = Fake::new(); + with_pending(&owner, vec![asking("p_2", "Claude", true)], vec![]); + let mut h = start(&w, &["alpha"], &owner); + refresh(&mut h); + assert!( + h.query_all_by_label_contains("wants to connect") + .next() + .is_some() + ); + // The server turned it away unanswered: it is not listed any more, and + // the window never keeps what the server has dropped. + with_pending(&owner, vec![], vec![]); + refresh(&mut h); + assert!(h.query_by_label_contains("wants to connect").is_none()); + // A connection that was allowed shows on the Connect page, with what + // it may do, and the person raises and lowers it. + with_pending( + &owner, + vec![], + vec![WebApproval { + id: "apr_1".into(), + book: "alpha".into(), + label: "Claude on the web".into(), + token_id: "tok_1".into(), + may_post: false, + last_used: None, + }], + ); + refresh(&mut h); + h.state_mut().view_mut(0).unwrap().goto(Route::Connect); + h.run_steps(3); + assert!(h.query_by_label_contains("Assistants on the web").is_some()); + assert!( + h.query_by_label_contains("Can read and draft entries. It can't post them.") + .is_some() + ); + h.get_by_role_and_label(Role::Button, "Let it post entries") + .click(); + h.run_steps(2); + wait_for("posting was turned on", || { + owner + .said() + .contains(&"web_set_post apr_1 true".to_string()) + }); + refresh(&mut h); + assert!( + h.query_by_label_contains("Can read, draft and post entries.") + .is_some() + ); + h.get_by_role_and_label(Role::Button, "Stop letting it post") + .click(); + h.run_steps(2); + wait_for("posting was turned off", || { + owner + .said() + .contains(&"web_set_post apr_1 false".to_string()) + }); + drop(h); +} diff --git a/crates/ledger-host/src/app_server.rs b/crates/ledger-host/src/app_server.rs index 91b30fd8..1dff5a11 100644 --- a/crates/ledger-host/src/app_server.rs +++ b/crates/ledger-host/src/app_server.rs @@ -154,6 +154,16 @@ pub struct Roster { pub tokens: Vec, } +/// The web assistants waiting to be allowed, and the web connections that +/// are (plan P15 B1): what the window's "Allow?" shows. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct WebRoster { + /// Assistants waiting for the person. + pub pending: Vec, + /// Connections the person allowed. + pub approvals: Vec, +} + /// The books server, a child process of this one. pub struct AppServer { run: PathBuf, @@ -419,6 +429,69 @@ impl AppServer { Ok(Roster { sessions, tokens }) } + /// The web assistants waiting for the person, and the web connections + /// allowed: two quick requests, an `Err` while the server is starting or + /// gone. A server whose remote door was never turned on answers both + /// with nothing. + pub fn web_roster(&self, wait: Duration) -> Result { + if !self.is_ready() { + return Err(match self.exited() { + Some(why) => why, + None => "the books server is still starting".into(), + }); + } + let pending = match self.ask(Request::RemotePending, Some(wait))? { + Response::RemotePending(p) => p, + Response::Refused(why) => return Err(why), + other => return Err(format!("the books server answered oddly: {other:?}")), + }; + let approvals = match self.ask(Request::RemoteApprovals { book: None }, Some(wait))? { + Response::RemoteApprovals(a) => a, + Response::Refused(why) => return Err(why), + other => return Err(format!("the books server answered oddly: {other:?}")), + }; + Ok(WebRoster { pending, approvals }) + } + + /// The person's answer to one waiting assistant: `Ok` says what was + /// done, in words. `post` lets it post entries too, not only read and + /// draft. + pub fn web_decide(&self, id: &str, approve: bool, post: bool) -> Result { + self.wait_ready(READY_WAIT)?; + match self.ask( + Request::RemoteDecide { + id: id.into(), + approve, + post, + }, + Some(Duration::from_secs(30)), + )? { + Response::RemoteDecided { said, .. } => Ok(said), + Response::Refused(why) => Err(why), + other => Err(format!("the books server answered oddly: {other:?}")), + } + } + + /// Raise a web connection to posting, or lower it. + pub fn web_set_post(&self, approval: &str, post: bool) -> Result { + self.wait_ready(READY_WAIT)?; + match self.ask( + Request::RemoteSetPost { + approval: approval.into(), + post, + }, + Some(Duration::from_secs(30)), + )? { + Response::RemoteApprovals(_) => Ok(if post { + "It can post entries now.".into() + } else { + "It can read and draft, but not post.".into() + }), + Response::Refused(why) => Err(why), + other => Err(format!("the books server answered oddly: {other:?}")), + } + } + /// End the key `id`, named `name`, of the company `book`, as /// `wanderbooks token revoke` does (INVARIANT 12): the server ends that /// key and the sessions it opened, and the token file's copy is @@ -723,6 +796,21 @@ impl AppHost { self.running()?.revoke_token(book, name, id) } + /// The web assistants waiting, and the web connections allowed. + pub fn web_roster(&self, wait: Duration) -> Result { + self.running()?.web_roster(wait) + } + + /// The person's answer to a waiting assistant. + pub fn web_decide(&self, id: &str, approve: bool, post: bool) -> Result { + self.running()?.web_decide(id, approve, post) + } + + /// Raise a web connection to posting, or lower it. + pub fn web_set_post(&self, approval: &str, post: bool) -> Result { + self.running()?.web_set_post(approval, post) + } + /// The format upgrade of the company `id` (INVARIANT 10). pub fn upgrade_format(&self, id: &str, passphrase: &str) -> Result, String> { match self.running() { diff --git a/crates/ledger-mcp/Cargo.toml b/crates/ledger-mcp/Cargo.toml index a6e6d973..f7156f22 100644 --- a/crates/ledger-mcp/Cargo.toml +++ b/crates/ledger-mcp/Cargo.toml @@ -20,6 +20,15 @@ ledger-vault = { path = "../ledger-vault" } # the viewer. ledger-package = { path = "../ledger-package" } base64 = "0.22" +# The remote door's sign-in (local/remote/): a client's metadata document is +# fetched with it (cimd.rs), its secrets compared in constant time, its +# codes and tokens drawn from the system's randomness, and its connections +# served by hyper directly so a header-read timeout can be set. All were in +# the tree already (ledger-host, ledger-store, axum). +reqwest = "0.13" +subtle = "2" +getrandom = { version = "0.2", features = ["std"] } +hyper-util = { version = "0.1", features = ["server-auto", "service", "tokio", "http1", "http2"] } # A download's Repr-Digest (local.rs). sha2 = "0.10" rust_decimal = "1" diff --git a/crates/ledger-mcp/src/access.rs b/crates/ledger-mcp/src/access.rs index a06c1d3c..6d0da0a8 100644 --- a/crates/ledger-mcp/src/access.rs +++ b/crates/ledger-mcp/src/access.rs @@ -42,6 +42,10 @@ use std::sync::Arc; pub struct Caller { /// The token. pub token: Token, + /// The address the request came from, when it came through the remote + /// door (the relay's PROXY header, never a header the caller sent); + /// None on the local socket. + pub from: Option, } impl Caller { @@ -220,6 +224,7 @@ impl Call { result, head_after, agent: self.agent.clone(), + from: self.caller.as_ref().and_then(|c| c.from.clone()), }; match self.log.record(&access) { Ok(_) => { diff --git a/crates/ledger-mcp/src/admin.rs b/crates/ledger-mcp/src/admin.rs index f5656c54..6b403d30 100644 --- a/crates/ledger-mcp/src/admin.rs +++ b/crates/ledger-mcp/src/admin.rs @@ -204,6 +204,71 @@ pub enum Request { }, /// Who is connected to each open book (INVARIANT 9). Sessions, + /// Turn the remote door on (plan P15 B1): listen on 127.0.0.1 (a free + /// port when `port` is none) and sign web assistants in as the one + /// public address `public_url` (`https://name`, no path). The same + /// address is a no-op; another restarts the door. + RemoteStart { + /// The one public address, which is the issuer. + public_url: String, + /// The loopback port to listen on. + #[serde(default)] + port: Option, + }, + /// Turn the remote door off. + RemoteStop, + /// Offer a company to web assistants, or stop offering it. + RemoteAllow { + /// The books. + book: String, + /// Offered or not. + allowed: bool, + }, + /// Whether the door is on, where, as which address, for which books. + RemoteStatus, + /// The assistants waiting to be allowed. + RemotePending, + /// The person's answer to one waiting assistant (INVARIANT 10). + RemoteDecide { + /// The waiting request, by the id `RemotePending` gave. + id: String, + /// Allow it, or refuse it. + approve: bool, + /// Let it post entries too (not only read and draft). + #[serde(default)] + post: bool, + }, + /// The web connections that are allowed, for a company or all. + RemoteApprovals { + /// The books, or all. + #[serde(default)] + book: Option, + }, + /// Raise a web connection to posting, or lower it. + RemoteSetPost { + /// The connection's id. + approval: String, + /// May post entries. + post: bool, + }, + /// A key for an assistant that takes only a key: shown once. + RemoteMakeKey { + /// The books. + book: String, + /// What to call it. + name: String, + /// May post entries. + #[serde(default)] + post: bool, + }, + /// A client id and secret to type into an assistant that asks for + /// them: shown once. + RemoteMakeClient { + /// What to call it. + name: String, + /// The addresses it will be sent back to (exactly these). + redirect_uris: Vec, + }, /// End a token. TokenRevoke { /// Its books. @@ -321,6 +386,78 @@ impl From<&ledger_store::auth::Token> for TokenInfo { } } +/// The remote door, as it stands (INVARIANT 10). +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct RemoteInfo { + /// Where it listens on this computer (127.0.0.1:port), if it is on. + pub listening: Option, + /// The one public address it signs assistants in as, if it is on. + pub public_url: Option, + /// The books it offers. + pub allowed: Vec, + /// This start's secret, for the app only (the admin socket is the + /// owner's): the 64 characters it writes at the very front of every + /// connection it makes to the door, before the PROXY header + /// (remote/proxy.rs INVARIANT 5). Never shown in a log. + #[serde(default)] + pub proxy_secret: Option, +} + +/// An assistant waiting for the person to allow it (INVARIANT 10): what +/// the window shows. What the assistant calls itself is asserted, cleaned +/// and never trusted; the address and the redirect are what the server saw. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct PendingInfo { + /// The id the answer names. + pub id: String, + /// The company it asks to reach. + pub book: String, + /// What it calls itself: its own word, cleaned and short, possibly + /// empty. Never a product's name made up from where it is sent back to. + pub client_name: String, + /// Whether the address it is sent back to is one of the vendors' known + /// hosts: only the warning depends on it (a host that isn't gets one). + pub known_host: bool, + /// The short code the person matches with the one the assistant's + /// browser page shows, to tell this request from any other waiting. + pub code: String, + /// The address it will be sent back to, in full. + pub redirect: String, + /// That address's host. + pub redirect_host: String, + /// The caller's address, as the relay said it (never a header the + /// caller sent). + pub from: String, + /// It asked to post entries too. + pub wants_post: bool, + /// Seconds since it asked. + pub age_secs: u64, + /// Seconds until it is turned away unanswered. + pub expires_in_secs: u64, +} + +/// A web connection the person allowed. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ApprovalInfo { + /// Its id. + pub id: String, + /// The company. + pub book: String, + /// What it is called. + pub label: String, + /// The principals' token that carries it (what "Who can reach these + /// books" lists and revokes). + pub token_id: String, + /// That token's name. + pub token_name: String, + /// It may post entries. + pub may_post: bool, + /// When it was allowed (unix seconds). + pub created: i64, + /// When it last did anything (unix seconds), if it has. + pub last_used: Option, +} + /// One book, as listed. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct BookStatus { @@ -630,6 +767,30 @@ pub enum Response { }, /// Who is connected, for each open book (INVARIANT 9). Sessions(Vec), + /// The remote door's state (INVARIANT 10). + Remote(RemoteInfo), + /// The assistants waiting to be allowed. + RemotePending(Vec), + /// What the person's answer did. + RemoteDecided { + /// In words. + said: String, + /// The connection that was made or kept, when allowed. + #[serde(default, skip_serializing_if = "Option::is_none")] + approval: Option, + }, + /// The web connections that are allowed. + RemoteApprovals(Vec), + /// A key or a client id made: the secret, shown this once (as a + /// token's text is: INVARIANT 6). + RemoteSecret { + /// The key's token id, or the client id. + id: String, + /// The key, or the client's secret. + secret: TokenText, + /// In words. + said: String, + }, /// An attachment's text read and journaled (plan P6 step 2). Extracted { /// The attachment. @@ -680,7 +841,22 @@ pub fn call_within( let not_sent = |why: String| CallError::NotSent(why); // A list changes nothing: its only question is whether it answered. let look = match request { - Request::List | Request::TokenList | Request::TokenCheck { .. } | Request::Sessions => None, + Request::List + | Request::TokenList + | Request::TokenCheck { .. } + | Request::Sessions + | Request::RemoteStatus + | Request::RemotePending + | Request::RemoteApprovals { .. } => None, + Request::RemoteStart { .. } + | Request::RemoteStop + | Request::RemoteAllow { .. } + | Request::RemoteDecide { .. } + | Request::RemoteSetPost { .. } + | Request::RemoteMakeKey { .. } + | Request::RemoteMakeClient { .. } => { + Some("ask the state of web assistants again to see whether it was done") + } Request::OpenBook { .. } | Request::CloseBook { .. } => { Some("`wanderbooks books list` says whether the books are open") } diff --git a/crates/ledger-mcp/src/handbook.rs b/crates/ledger-mcp/src/handbook.rs index dd771edf..150f6a9f 100644 --- a/crates/ledger-mcp/src/handbook.rs +++ b/crates/ledger-mcp/src/handbook.rs @@ -32,10 +32,44 @@ //! for books that declared the journal feature //! `document_line_projects`; for the rest, that they wait for their //! format upgrade (BS-format-1, BS-statement-5 statement 6). +//! 7. The company's name and the entry point also stand in the +//! description of the tools a model reaches for first +//! ([`FIRST_TOOLS`], decorated in `list_tools` by +//! [`first_tools_lead`]), for local and remote callers alike: some +//! products keep only the first 512 characters of the instructions +//! (ChatGPT), and one is reported to drop them (claude.ai, 2026-03, +//! unverified since), while a tool's description always arrives +//! (plan/p15-app-and-relay.md 3.4, WB-assist-5). //! ``` use crate::settings::Settings; +/// The tools a model reaches for first: each one's description begins with +/// [`first_tools_lead`] (INVARIANT 7). +pub const FIRST_TOOLS: &[&str] = &[ + "books.start", + "books.handbook", + "books.chart", + "books.show", + "books.digest", + "books.search_entries", + "books.draft_entry", + "books.post_entry", +]; + +/// What begins the description of every tool in [`FIRST_TOOLS`]: the +/// company, and the entry point, so they reach a model whatever the +/// product does with the server's instructions. +pub fn first_tools_lead(settings: &Settings) -> String { + let unnamed = ledger_config::Company::default().name; + let name = if settings.company.name.trim() == unnamed { + shown_name("") + } else { + shown_name(&settings.company.name) + }; + format!("For the books of {name}: call books.start first in every session. ") +} + /// The most characters the connect text may have. pub const CONNECT_MAX: usize = 1400; diff --git a/crates/ledger-mcp/src/local.rs b/crates/ledger-mcp/src/local.rs index 4aed2d6b..8595e5bc 100644 --- a/crates/ledger-mcp/src/local.rs +++ b/crates/ledger-mcp/src/local.rs @@ -400,6 +400,9 @@ use std::time::{Duration, Instant}; use tokio_util::sync::CancellationToken; use tokio_util::task::TaskTracker; +mod remote; +use remote::Via; + /// What a restore or adoption that a close stopped after its point of no /// return says of the books it put in place (INVARIANT 10). const STOPPED_AFTER_PLACED: &str = "they are in place, but were not opened: the books server is closing. Open them when it runs again"; @@ -497,6 +500,12 @@ enum Book { Open { /// Its MCP service (boxed: the other variant is a line of text). service: Box, + /// The same book's service for the remote door: stateless, plain + /// JSON, no session kept (remote/mod.rs INVARIANT 10). + remote_service: Box, + /// What serves it, for what the remote door reads of it (the + /// company's name). + served: Box, /// Its store, closed when the server closes (INVARIANT 6). store: Arc, /// Its access log, where requests refused at the door are @@ -850,6 +859,8 @@ struct Books { isolation: Isolation, /// The periods and bounds (tests shorten them). timers: Timers, + /// What the remote door holds: web assistants' sign-in (remote/). + remote: Arc, } /// What the changes to ONE book share (`Books::lives`): the lock they are @@ -912,6 +923,7 @@ impl Books { server_stop: Arc::default(), isolation, timers: Timers::default(), + remote: Arc::new(remote::Remote::new()), } } @@ -1175,6 +1187,21 @@ impl Books { Arc::new(sessions()), config, ); + // The remote door's service: the same server made the same way, but + // with no session kept, plain JSON replies, and the Host checked by + // the door itself against the one public address (remote/http.rs). + let remote_parts = served.clone(); + let remote_service = StreamableHttpService::new( + move || Ok(BooksServer::new(&remote_parts)), + Arc::new(sessions()), + StreamableHttpServerConfig::default() + .with_legacy_session_mode(false) + .with_json_response(true) + .with_max_request_body_bytes(MAX_BODY) + .disable_allowed_hosts() + .with_cancellation_token(ended.clone()), + ); + let kept_served = served.clone(); let Served { store: shared, access, @@ -1218,6 +1245,8 @@ impl Books { ended, board, service: Box::new(service), + remote_service: Box::new(remote_service), + served: Box::new(kept_served), store: shared, access, uploads, @@ -1240,7 +1269,7 @@ impl Books { } /// Answer an admin request (blocking: it runs on its own thread). - fn admin(&self, request: Request) -> Response { + fn admin(self: &Arc, request: Request) -> Response { let refused = |e: RootError| Response::Refused(self.hide(e.to_string())); match request { Request::List => Response::Books( @@ -1315,9 +1344,79 @@ impl Books { }); if let (Response::TokenCreated { .. }, Some(old)) = (&answer, &replaced) { self.forget_sessions_of(old); + self.remote.token_gone(old); } answer } + Request::RemoteStart { public_url, port } => { + // The door listens from this blocking task's runtime + // (remote/http.rs `start_door`). + match remote::start_door(self, &public_url, port) { + Ok(info) => Response::Remote(info), + Err(why) => Response::Refused(self.hide(why)), + } + } + Request::RemoteStop => { + remote::stop_door(self); + Response::Remote(self.remote.info()) + } + Request::RemoteAllow { book, allowed } => { + let id = match BookId::parse(&book) { + Ok(id) => id, + Err(e) => return refused(e), + }; + if !self.held().contains_key(id.as_str()) { + return Response::Refused(format!( + "there are no books called {id}: `wanderbooks books list` lists them" + )); + } + self.remote.set_allowed(id.as_str(), allowed); + Response::Remote(self.remote.info()) + } + Request::RemoteStatus => Response::Remote(self.remote.info()), + Request::RemotePending => Response::RemotePending(self.remote.pending_list()), + Request::RemoteDecide { id, approve, post } => { + match self.remote.decide(self, &id, approve, post) { + Ok((said, approval)) => Response::RemoteDecided { said, approval }, + Err(why) => Response::Refused(self.hide(why)), + } + } + Request::RemoteApprovals { book } => { + Response::RemoteApprovals(self.remote.approvals(self, book.as_deref())) + } + Request::RemoteSetPost { approval, post } => { + match self.remote.set_post(self, &approval, post) { + Ok(a) => Response::RemoteApprovals( + self.remote + .approvals(self, Some(&a.book)) + .into_iter() + .filter(|i| i.id == a.id) + .collect(), + ), + Err(why) => Response::Refused(self.hide(why)), + } + } + Request::RemoteMakeKey { book, name, post } => { + match self.remote.make_key(self, &book, &name, post) { + Ok((token, text)) => Response::RemoteSecret { + id: token.id, + secret: admin::TokenText(text), + said: format!("Key {} made: shown once", token.name), + }, + Err(why) => Response::Refused(self.hide(why)), + } + } + Request::RemoteMakeClient { + name, + redirect_uris, + } => match self.remote.make_client(self, &name, &redirect_uris) { + Ok((id, secret)) => Response::RemoteSecret { + id, + secret: admin::TokenText(secret), + said: "Client id and secret made: the secret is shown once".into(), + }, + Err(why) => Response::Refused(self.hide(why)), + }, Request::TokenList => self.with_principals(|p| { Ok(Response::Tokens( p.tokens().iter().map(admin::TokenInfo::from).collect(), @@ -1337,12 +1436,25 @@ impl Books { Ok(id) => id, Err(e) => return refused(e), }; - let answer = self.with_principals(|p| { + let mut answer = self.with_principals(|p| { p.revoke_if(&book, &name, id.as_deref()) .map(|t| Response::TokenRevoked(admin::TokenInfo::from(&t))) }); + // A web connection's permissions were just changed and the + // revoke named the token that was replaced: it is for the + // one that replaced it (a revoke during the swap wins). + if matches!(answer, Response::Refused(_)) + && let Some(newer) = id.as_deref().and_then(|old| self.remote.successor_of(old)) + { + answer = self.with_principals(|p| { + p.revoke_if(&book, &name, Some(&newer)) + .map(|t| Response::TokenRevoked(admin::TokenInfo::from(&t))) + }); + } if let Response::TokenRevoked(t) = &answer { self.forget_sessions_of(&t.id); + // What a web connection or key under it held ends now. + self.remote.token_gone(&t.id); } answer } @@ -2335,6 +2447,9 @@ const MAX_SESSIONS: usize = 100_000; struct Asked { action: &'static str, subject: String, + /// Where the request came from, when it came through the remote door + /// (the relay's PROXY header): recorded with a refusal too. + from: Option, } impl Asked { @@ -2342,8 +2457,15 @@ impl Asked { Self { action: "connect", subject: method.as_str().to_string(), + from: None, } } + + /// This request, from the address the relay says (remote door only). + fn from(mut self, address: std::net::SocketAddr) -> Self { + self.from = Some(address.ip().to_string()); + self + } } /// A request refused at the door: recorded in the book's access log @@ -2365,7 +2487,12 @@ async fn refused_at_door( why: String, ) -> axum::response::Response { use axum::response::IntoResponse; - if let Book::Open { access, store, .. } = book { + // A request from the remote door with no token that matched is never + // written down: anyone on the internet could fill the record. + let stranger = asked.from.is_some() && principal.id.is_empty(); + if let Book::Open { access, store, .. } = book + && !stranger + { let access = access.clone(); let record = Access { principal, @@ -2378,6 +2505,7 @@ async fn refused_at_door( result: Outcome::Refused(code.into()), head_after: None, agent: None, + from: asked.from.clone(), }; let written = tokio::task::spawn_blocking(move || { let _inside = inside; @@ -2434,6 +2562,150 @@ fn close_connection(response: &mut axum::response::Response) { ); } +/// Whether the books `id` are open and served. +fn book_is_open(books: &Books, id: &str) -> bool { + matches!(books.held().get(id), Some(Book::Open { .. })) +} + +/// A company's name as a person is told it: the books' own setting, or +/// their id when none is set. +fn company_name(books: &Books, id: &str) -> String { + let named = match books.held().get(id) { + Some(Book::Open { served, .. }) => Some( + served + .settings + .lock() + .unwrap_or_else(|e| e.into_inner()) + .current() + .company + .name + .clone(), + ), + _ => None, + }; + let unnamed = ledger_config::Company::default().name; + match named { + Some(n) if !n.trim().is_empty() && n.trim() != unnamed => remote::clean(&n, 60), + _ => id.to_string(), + } +} + +/// The live token of `book` called `name` whose id is `id`. +fn live_token(books: &Books, book: &str, name: &str, id: &str) -> Option { + let guard = books.principals.read().unwrap_or_else(|e| e.into_inner()); + guard + .as_ref() + .ok()? + .tokens() + .iter() + .find(|t| t.book == book && t.name == name && t.id == id) + .cloned() +} + +/// The ids of every live token. +fn live_token_ids(books: &Books) -> std::collections::BTreeSet { + let guard = books.principals.read().unwrap_or_else(|e| e.into_inner()); + guard + .as_ref() + .map(|p| p.tokens().iter().map(|t| t.id.clone()).collect()) + .unwrap_or_default() +} + +fn token_is_live(books: &Books, book: &str, name: &str, id: &str) -> bool { + live_token(books, book, name, id).is_some() +} + +/// The names of the live tokens of `book`. +fn token_names(books: &Books, book: &str) -> std::collections::BTreeSet { + let guard = books.principals.read().unwrap_or_else(|e| e.into_inner()); + guard + .as_ref() + .map(|p| { + p.tokens() + .iter() + .filter(|t| t.book == book) + .map(|t| t.name.clone()) + .collect() + }) + .unwrap_or_default() +} + +/// Make a token for `book` in the principals, whose text is returned once +/// (auth.rs INVARIANT 1); a log that failed to write is read again, as +/// `with_principals` does. +fn create_token( + books: &Books, + book: &BookId, + name: &str, + scopes: std::collections::BTreeSet, + replace: bool, +) -> Result<(Token, String), String> { + let mut guard = books.principals.write().unwrap_or_else(|e| e.into_inner()); + let principals = guard.as_mut().map_err(|why| why.clone())?; + match principals.create(book, name, scopes, replace) { + Ok((token, text)) => Ok((token, text.expose().to_string())), + Err(e) => { + if matches!(e, ledger_store::auth::AuthError::Log(_)) { + *guard = books.load_principals(); + } + Err(books.hide(e.to_string())) + } + } +} + +/// Make `book`'s token called `name` over with `scopes`, but only if the +/// one live under that name is `old_id`: the check and the replacement are +/// one hold of the principals, so a revoke that came first is not undone +/// (the remote door's raising or lowering of posting). +fn replace_token_if_live( + books: &Books, + book: &BookId, + name: &str, + old_id: &str, + scopes: std::collections::BTreeSet, +) -> Result { + let mut guard = books.principals.write().unwrap_or_else(|e| e.into_inner()); + let principals = guard.as_mut().map_err(|why| why.clone())?; + let live = principals + .tokens() + .iter() + .any(|t| t.book == book.as_str() && t.name == name && t.id == old_id); + if !live { + return Err("that connection was revoked".into()); + } + match principals.create(book, name, scopes, true) { + Ok((token, _)) => Ok(token), + Err(e) => { + if matches!(e, ledger_store::auth::AuthError::Log(_)) { + *guard = books.load_principals(); + } + Err(books.hide(e.to_string())) + } + } +} + +/// A token whose text nobody is given: the principal a web connection is +/// carried by (its access tokens are the remote door's own). +fn make_token( + books: &Books, + book: &BookId, + name: &str, + scopes: std::collections::BTreeSet, + replace: bool, +) -> Result { + create_token(books, book, name, scopes, replace).map(|(t, _)| t) +} + +/// A token and its text, to be shown once. +fn make_token_with_text( + books: &Books, + book: &BookId, + name: &str, + scopes: std::collections::BTreeSet, +) -> Result<(Token, String), String> { + create_token(books, book, name, scopes, false) +} + /// The door to `book` (INVARIANT 8): the books held open, the server not /// closing, and a live token for those books; else the answer refusing /// the request (recorded in the books' access log, where there is one). @@ -2445,6 +2717,7 @@ async fn door( book: &str, asked: &Asked, headers: &axum::http::HeaderMap, + via: Via, ) -> Result<(Book, Token, Inside), Box> { use axum::http::StatusCode; use axum::response::IntoResponse; @@ -2516,7 +2789,17 @@ async fn door( let Some(inside) = inside else { unreachable!("an open book was entered above") }; - let token = books.bearer(headers); + // The token, from where this way in keeps them: a static token for the + // local socket, a token the remote door made for the remote one + // (remote/mod.rs INVARIANT 3, 6). `Err` is the code, the words, and + // whether a token was presented that isn't good. + let token = match via { + Via::Local => books.bearer(headers).map_err(|(c, w)| (c, w, false)), + Via::Remote(_) => books + .remote + .authenticate(books, headers) + .map_err(|d| (d.code, d.why, d.invalid_token)), + }; let principal = |t: &Token| Principal { id: t.id.clone(), kind: "agent".into(), @@ -2540,7 +2823,25 @@ async fn door( } let token = match token { Ok(t) => t, - Err((code, why)) => { + Err((code, why, invalid)) => { + // On the remote door a stranger's request with no good token + // is counted, never written to the books' record (a stranger + // could fill the disk): it is a 401 with the way to sign in. + if matches!(via, Via::Remote(_)) { + books.remote.count_unsigned(); + return Err(Box::new(match books.remote.door() { + Some(door) => remote::unauthorized( + &door, + book, + &remote::Denied { + code, + why, + invalid_token: invalid, + }, + ), + None => axum::http::StatusCode::SERVICE_UNAVAILABLE.into_response(), + })); + } return Err(refused_at_door( &held, inside, @@ -2554,6 +2855,39 @@ async fn door( .into()); } }; + // The remote door counts a connection's calls before anything else is + // asked of them, and counts, never writes, a call refused for rate or + // for another company's books: a token holder can't fill the disk with + // refusals (remote/mod.rs INVARIANT 3, 8). + if let Via::Remote(_) = via { + if books + .remote + .limited(books.remote.call_key(&token), remote::CALLS_PER_MINUTE, 60) + { + books.remote.count_refused(); + let mut refused = ( + StatusCode::TOO_MANY_REQUESTS, + [(REFUSED_HEADER, "rate_limited")], + "this connection is making too many calls: wait a minute", + ) + .into_response(); + refused.headers_mut().insert( + axum::http::header::RETRY_AFTER, + axum::http::HeaderValue::from_static("60"), + ); + return Err(refused.into()); + } + if token.book != book { + books.remote.count_refused(); + return Err(( + StatusCode::FORBIDDEN, + [(REFUSED_HEADER, "wrong_books")], + format!("this token is for the books {}, not {book}", token.book), + ) + .into_response() + .into()); + } + } if token.book != book { return Err(refused_at_door( &held, @@ -2589,25 +2923,27 @@ async fn upload( let asked = Asked { action: "upload", subject: id.clone(), + from: None, }; - let (held, token, inside) = match door(&books, &book, &asked, request.headers()).await { - Ok(passed) => passed, - Err(refused) => { - // What was sent is read and dropped (up to the most an upload - // can be: only this account reaches the socket), so the client - // gets the refusal, not a connection cut mid-send. - use futures_util::StreamExt; - let mut rest = request.into_body().into_data_stream(); - let mut read = 0u64; - while let Some(Ok(chunk)) = rest.next().await { - read += chunk.len() as u64; - if read > ledger_store::uploads::MAX_UPLOAD { - break; + let (held, token, inside) = + match door(&books, &book, &asked, request.headers(), Via::Local).await { + Ok(passed) => passed, + Err(refused) => { + // What was sent is read and dropped (up to the most an upload + // can be: only this account reaches the socket), so the client + // gets the refusal, not a connection cut mid-send. + use futures_util::StreamExt; + let mut rest = request.into_body().into_data_stream(); + let mut read = 0u64; + while let Some(Ok(chunk)) = rest.next().await { + read += chunk.len() as u64; + if read > ledger_store::uploads::MAX_UPLOAD { + break; + } } + return *refused; } - return *refused; - } - }; + }; let Book::Open { access, uploads, @@ -2695,6 +3031,7 @@ async fn upload( result: outcome.clone(), head_after: None, agent: None, + from: None, }; let recorded = access.record(&record).is_ok(); if !recorded && received.is_ok() { @@ -2783,11 +3120,13 @@ async fn fetch( let asked = Asked { action, subject: subject.clone(), + from: None, }; - let (held, token, inside) = match door(&books, &book, &asked, request.headers()).await { - Ok(passed) => passed, - Err(refused) => return *refused, - }; + let (held, token, inside) = + match door(&books, &book, &asked, request.headers(), Via::Local).await { + Ok(passed) => passed, + Err(refused) => return *refused, + }; let Book::Open { access, store, @@ -2877,6 +3216,7 @@ async fn fetch( }, head_after: None, agent: None, + from: None, }; let recorded = access.record(&record).is_ok(); (found, recorded) @@ -2961,10 +3301,31 @@ fn disposition(name: &str) -> String { async fn mcp( axum::extract::State(books): axum::extract::State>, axum::extract::Path(book): axum::extract::Path, + request: axum::extract::Request, +) -> axum::response::Response { + mcp_via(books, book, request, Via::Local).await +} + +/// [`mcp`] for either way in: the local socket's, or the remote door's +/// (remote/http.rs), which is the same door and the same tools with the +/// remote way's differences: its token is one the remote door made, it +/// keeps no session, and its caller's address is the relay's. +async fn mcp_via( + books: Arc, + book: String, mut request: axum::extract::Request, + via: Via, ) -> axum::response::Response { use axum::http::StatusCode; use tower::ServiceExt; + let remote_from = match via { + Via::Remote(addr) => Some(addr), + Via::Local => None, + }; + let asked_of = |method: &axum::http::Method| match remote_from { + Some(addr) => Asked::connect(method).from(addr), + None => Asked::connect(method), + }; // Counted before the closing check, so closing never misses it. let counted = (request.method() != axum::http::Method::GET).then(|| InFlight::new(&books)); books @@ -2975,14 +3336,24 @@ async fn mcp( // a close of the book waits for it, and its tools are counted by the // store (SharedStore INVARIANT 3). let (held, token, inside) = - match door(&books, &book, &Asked::connect(&method), request.headers()).await { + match door(&books, &book, &asked_of(&method), request.headers(), via).await { Ok(passed) => passed, Err(refused) => return *refused, }; - let Book::Open { service, board, .. } = &held else { + let Book::Open { + service, + remote_service, + board, + .. + } = &held + else { unreachable!("the door lets only open books through") }; - let (service, board) = ((**service).clone(), board.clone()); + let service = match via { + Via::Local => (**service).clone(), + Via::Remote(_) => (**remote_service).clone(), + }; + let board = board.clone(); let principal = |t: &Token| Principal { id: t.id.clone(), kind: "agent".into(), @@ -2993,6 +3364,11 @@ async fn mcp( let (rewatched, arrival) = inside.arriving(request); request = rewatched; let who = principal(&token); + // The remote door keeps no session: whatever session a caller names is + // not heard, so a call is the same call however it arrives. + if remote_from.is_some() { + request.headers_mut().remove(SESSION_HEADER); + } let session = request .headers() .get(SESSION_HEADER) @@ -3027,14 +3403,14 @@ async fn mcp( opens }; if arrival.was_cut() { - return cut_by_the_close(&held, inside, who, &Asked::connect(&method)).await; + return cut_by_the_close(&held, inside, who, &asked_of(&method)).await; } if full { return refused_at_door( &held, inside, principal(&token), - &Asked::connect(&method), + &asked_of(&method), "too_many_sessions", StatusCode::SERVICE_UNAVAILABLE, "the books server has too many sessions open: end some, then try again".into(), @@ -3046,7 +3422,7 @@ async fn mcp( &held, inside, principal(&token), - &Asked::connect(&method), + &asked_of(&method), "session_token", StatusCode::FORBIDDEN, "this session was opened with another token".into(), @@ -3054,9 +3430,10 @@ async fn mcp( .await; } let (token_id, token_name) = (token.id.clone(), token.name.clone()); - request - .extensions_mut() - .insert(crate::access::Caller { token }); + request.extensions_mut().insert(crate::access::Caller { + token, + from: remote_from.map(|a| a.ip().to_string()), + }); let response = match service.oneshot(request).await { Ok(response) => response, Err(never) => match never {}, @@ -3067,7 +3444,7 @@ async fn mcp( // no call ran, nothing is in the journal. if arrival.was_cut() { drop(response); - return cut_by_the_close(&held, inside, who, &Asked::connect(&method)).await; + return cut_by_the_close(&held, inside, who, &asked_of(&method)).await; } // A session the answer opened is bound to the token that opened it; // one ended, or found gone, is forgotten. @@ -3077,6 +3454,7 @@ async fn mcp( .lock() .unwrap_or_else(|e| e.into_inner()); if session.is_none() + && remote_from.is_none() && let Some(sid) = response .headers() .get(SESSION_HEADER) @@ -3665,6 +4043,8 @@ async fn serve( () = stops.hurry.cancelled() => {} } shut.cancel(); + // The remote door goes with the server (remote/mod.rs INVARIANT 1). + remote::stop_door(&books); match tokio::time::timeout(HTTP_GRACE, &mut http).await { Ok(Ok(Ok(()))) => {} Ok(Ok(Err(e))) => eprintln!("wanderbooks server: {e}"), @@ -4125,7 +4505,7 @@ mod tests { } /// Make the books `id` through the admin request. - fn create(books: &Books, id: &str) { + fn create(books: &Arc, id: &str) { match books.admin(Request::Create { id: id.into(), currency: "USD".into(), @@ -4137,7 +4517,7 @@ mod tests { /// A token for `book` named `name` with every scope (made, or made /// again): its id and its text. - fn token(books: &Books, book: &str, name: &str) -> (String, String) { + fn token(books: &Arc, book: &str, name: &str) -> (String, String) { match books.admin(Request::TokenCreate { book: book.into(), name: name.into(), @@ -4278,7 +4658,7 @@ mod tests { let refused = |books: Arc, book: &'static str| { let (asked, headers) = (&asked, &headers); async move { - match door(&books, book, asked, headers).await { + match door(&books, book, asked, headers, Via::Local).await { Ok(_) => panic!("{book}: let through"), Err(r) => answer(*r).await, } @@ -4655,7 +5035,7 @@ mod tests { } /// The books `id` as listed. - fn listed(books: &Books, id: &str) -> admin::BookStatus { + fn listed(books: &Arc, id: &str) -> admin::BookStatus { match books.admin(Request::List) { Response::Books(list) => list.into_iter().find(|b| b.id == id).unwrap(), other => panic!("{other:?}"), @@ -4969,7 +5349,7 @@ mod tests { bearer: &str, ) -> Option<(u16, Option, String)> { let asked = Asked::connect(&axum::http::Method::POST); - match door(books, book, &asked, &bearing(bearer)).await { + match door(books, book, &asked, &bearing(bearer), Via::Local).await { Ok(_) => None, Err(r) => Some(answer(*r).await), } @@ -5562,6 +5942,7 @@ mod tests { result: Outcome::Refused("closing".into()), head_after: None, agent: None, + from: None, }; assert!(access.record(&late).is_err()); uploads.sweep(now); diff --git a/crates/ledger-mcp/src/local/remote/cimd.rs b/crates/ledger-mcp/src/local/remote/cimd.rs new file mode 100644 index 00000000..bb015c3b --- /dev/null +++ b/crates/ledger-mcp/src/local/remote/cimd.rs @@ -0,0 +1,290 @@ +//! Client ID metadata documents: a client whose id is an https address, +//! at which it publishes who it is (the IETF draft "OAuth Client ID +//! Metadata Document"; plan P15 section 4, rule 2). +//! +//! ```text +//! GOAL: the door can learn what an unknown client says of itself from the +//! address it gives as its id, without ever being made to reach into +//! the owner's own network or to read more than a small document. +//! SOURCE: WB-remote-4 (three ways to introduce a client); the draft above +//! (the document's `client_id` is its own address; public clients +//! only); plan/p15-app-and-relay.md 4, rule 2. +//! INVARIANTS: +//! 1. Only an https address with a host and a path, no userinfo and no +//! fragment, is fetched; the host's addresses are all looked up +//! first, and every one must be a public address (none loopback, +//! private, link-local, shared, documentation, multicast or +//! unspecified, and no form that carries an IPv4 address inside: +//! mapped, compatible (::/96), NAT64, 6to4 (2002::/16)): a name that points +//! into the owner's network is refused, and the connection is made to +//! the address that was checked, not to a second lookup, and over no +//! proxy from the environment. +//! 2. No redirect is followed; the answer must be 200, at most +//! MAX_DOCUMENT bytes, within FETCH_TIME. +//! 3. The document's `client_id` must be exactly the address it was +//! fetched from; its `redirect_uris` are 1 to MAX_REDIRECTS valid +//! redirect addresses; its `token_endpoint_auth_method`, if given, is +//! `none` (a document names no secret). +//! SCENARIOS: +//! 1. A document that names another client_id, or has no redirects, or +//! names a secret method, is refused. +//! 2. The checks on an address: loopback, private, link-local, shared and +//! mapped addresses are not public; a documentation-free global +//! address is. +//! ``` + +use super::{MAX_REDIRECTS, clean, redirects_fit, valid_redirect}; +use std::future::Future; +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; +use std::pin::Pin; +use std::time::Duration; + +/// The largest document read. +pub const MAX_DOCUMENT: usize = 64 * 1024; +/// How long a fetch may take. +pub const FETCH_TIME: Duration = Duration::from_secs(5); + +/// Where documents come from: the web in service, a table in the tests +/// (nothing in a test touches a network). +pub trait ClientDocs: Send + Sync { + /// The bytes served at `url`, or why not. + fn fetch<'a>( + &'a self, + url: &'a str, + ) -> Pin, String>> + Send + 'a>>; +} + +/// The web, with the checks of INVARIANTS 1 and 2. +pub struct WebDocs; + +fn v4_public(a: Ipv4Addr) -> bool { + let [o0, o1, o2, _] = a.octets(); + !(a.is_unspecified() + || a.is_loopback() + || a.is_private() + || a.is_link_local() + || a.is_broadcast() + || a.is_multicast() + || o0 == 0 + // Shared address space (carrier-grade NAT), 100.64.0.0/10. + || (o0 == 100 && (o1 & 0xc0) == 64) + // IETF protocol assignments, 192.0.0.0/24; documentation ranges. + || (o0 == 192 && o1 == 0 && (o2 == 0 || o2 == 2)) + || (o0 == 198 && o1 == 51 && o2 == 100) + || (o0 == 203 && o1 == 0 && o2 == 113) + // Benchmarking, 198.18.0.0/15; reserved, 240.0.0.0/4. + || (o0 == 198 && (o1 & 0xfe) == 18) + || o0 >= 240) +} + +fn v6_public(a: Ipv6Addr) -> bool { + if let Some(v4) = a.to_ipv4_mapped() { + return v4_public(v4); + } + let s = a.segments(); + !(a.is_unspecified() + || a.is_loopback() + || a.is_multicast() + // Unique local fc00::/7, link-local fe80::/10. + || (s[0] & 0xfe00) == 0xfc00 + || (s[0] & 0xffc0) == 0xfe80 + // Documentation 2001:db8::/32, discard 100::/64. + || (s[0] == 0x2001 && s[1] == 0x0db8) + || (s[0] == 0x0100 && s[1] == 0 && s[2] == 0 && s[3] == 0) + // The forms that carry an IPv4 address inside: NAT64 (64:ff9b::/96), + // IPv4-compatible (::/96) and 6to4 (2002::/16). None is a place a + // document is served from, and each can name a private address. + || (s[0] == 0x0064 && s[1] == 0xff9b) + || s[..6].iter().all(|x| *x == 0) + || s[0] == 0x2002) +} + +/// Whether `ip` is a public address (INVARIANT 1). +pub fn is_public(ip: IpAddr) -> bool { + match ip { + IpAddr::V4(a) => v4_public(a), + IpAddr::V6(a) => v6_public(a), + } +} + +impl ClientDocs for WebDocs { + fn fetch<'a>( + &'a self, + url: &'a str, + ) -> Pin, String>> + Send + 'a>> { + Box::pin(async move { + let parsed = reqwest::Url::parse(url).map_err(|_| "not an address".to_string())?; + let host = parsed + .host_str() + .filter(|_| { + parsed.scheme() == "https" + && parsed.username().is_empty() + && parsed.password().is_none() + && parsed.fragment().is_none() + && parsed.path() != "/" + }) + .ok_or("the client_id must be an https address with a path")? + .to_string(); + let port = parsed.port_or_known_default().unwrap_or(443); + let addrs: Vec = + tokio::time::timeout(FETCH_TIME, tokio::net::lookup_host((host.as_str(), port))) + .await + .map_err(|_| "the client's host didn't answer in time".to_string())? + .map_err(|_| "the client's host can't be found".to_string())? + .collect(); + if addrs.is_empty() || addrs.iter().any(|a| !is_public(a.ip())) { + return Err("the client's host isn't a public address".into()); + } + // No proxy from the environment: a proxy would be handed the + // name, not the address that was checked (and the pin below + // would be moot). The addresses checked are the ones used. + let client = reqwest::Client::builder() + .no_proxy() + .redirect(reqwest::redirect::Policy::none()) + .timeout(FETCH_TIME) + .https_only(true) + // The connection goes to the addresses just checked. + .resolve_to_addrs(&host, &addrs) + .build() + .map_err(|_| "no way to fetch the client's document".to_string())?; + let mut response = client + .get(url) + .header("accept", "application/json") + .send() + .await + .map_err(|_| "the client's document couldn't be fetched".to_string())?; + if response.status() != reqwest::StatusCode::OK { + return Err(format!( + "the client's document answered {}", + response.status().as_u16() + )); + } + let mut body = Vec::new(); + while let Some(chunk) = response + .chunk() + .await + .map_err(|_| "the client's document couldn't be read".to_string())? + { + body.extend_from_slice(&chunk); + if body.len() > MAX_DOCUMENT { + return Err("the client's document is too large".into()); + } + } + Ok(body) + }) + } +} + +/// What a document says (INVARIANT 3): the client's name and redirects. +pub fn parse(url: &str, bytes: &[u8]) -> Result<(String, Vec), String> { + let doc: serde_json::Value = serde_json::from_slice(bytes) + .map_err(|_| "the client's document isn't JSON".to_string())?; + if doc.get("client_id").and_then(|v| v.as_str()) != Some(url) { + return Err("the document's client_id isn't the address it came from".into()); + } + if doc + .get("token_endpoint_auth_method") + .and_then(|v| v.as_str()) + .is_some_and(|m| m != "none") + { + return Err("a client document may not name a secret".into()); + } + let uris = doc + .get("redirect_uris") + .and_then(|v| v.as_array()) + .filter(|a| !a.is_empty() && a.len() <= MAX_REDIRECTS) + .ok_or("the document's redirect_uris are missing or too many")?; + let mut redirects = Vec::new(); + for u in uris { + let text = u.as_str().unwrap_or_default(); + if valid_redirect(text).is_none() { + return Err("a redirect address in the document can't be used".into()); + } + if !redirects.iter().any(|r| r == text) { + redirects.push(text.to_string()); + } + } + if !redirects_fit(&redirects) { + return Err("the document's redirect addresses together are too long".into()); + } + let host = reqwest::Url::parse(url) + .ok() + .and_then(|u| u.host_str().map(str::to_string)) + .unwrap_or_default(); + let name = clean( + doc.get("client_name") + .and_then(|v| v.as_str()) + .unwrap_or(""), + 100, + ); + Ok((if name.is_empty() { host } else { name }, redirects)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_public_addresses_are_fetched() { + for bad in [ + "127.0.0.1", + "10.1.2.3", + "172.16.0.1", + "192.168.1.1", + "169.254.169.254", + "100.64.0.1", + "0.0.0.0", + "224.0.0.1", + "198.18.0.1", + "203.0.113.7", + "::1", + "::", + "fe80::1", + "fd12::1", + "ff02::1", + "2001:db8::1", + "::ffff:10.0.0.1", + "::ffff:127.0.0.1", + "::10.0.0.1", + "::127.0.0.1", + "::8.8.8.8", + "2002:c0a8:101::1", + "2002:0808:0808::1", + "64:ff9b::a00:1", + ] { + assert!(!is_public(bad.parse().unwrap()), "{bad}"); + } + for good in [ + "8.8.8.8", + "93.184.216.34", + "2606:4700:4700::1111", + "::ffff:8.8.8.8", + ] { + assert!(is_public(good.parse().unwrap()), "{good}"); + } + } + + #[test] + fn a_document_must_be_what_it_says_it_is() { + let url = "https://client.example/meta.json"; + let good = br#"{"client_id":"https://client.example/meta.json","client_name":"Fine","redirect_uris":["https://client.example/cb"]}"#; + assert_eq!( + parse(url, good).unwrap(), + ( + "Fine".to_string(), + vec!["https://client.example/cb".to_string()] + ) + ); + for bad in [ + br#"{"client_id":"https://other.example/meta.json","redirect_uris":["https://client.example/cb"]}"# as &[u8], + br#"{"client_id":"https://client.example/meta.json","redirect_uris":[]}"#, + br#"{"client_id":"https://client.example/meta.json"}"#, + br#"{"client_id":"https://client.example/meta.json","redirect_uris":["javascript:alert(1)"]}"#, + br#"{"client_id":"https://client.example/meta.json","redirect_uris":["https://c.example/cb#x"]}"#, + br#"{"client_id":"https://client.example/meta.json","redirect_uris":["https://c.example/cb"],"token_endpoint_auth_method":"client_secret_post"}"#, + b"not json", + ] { + assert!(parse(url, bad).is_err(), "{}", String::from_utf8_lossy(bad)); + } + } +} diff --git a/crates/ledger-mcp/src/local/remote/http.rs b/crates/ledger-mcp/src/local/remote/http.rs new file mode 100644 index 00000000..d901d15b --- /dev/null +++ b/crates/ledger-mcp/src/local/remote/http.rs @@ -0,0 +1,642 @@ +//! The remote door's HTTP side: the listener, the routes (metadata, +//! register, authorize, token, a company's MCP path), and the answers. +//! +//! ```text +//! GOAL: every route of the remote door answers only for the one public +//! address, in the forms the products expect, and refuses the rest. +//! SOURCE: WB-remote-1 to WB-remote-4, WB-remote-8; RFC 9728 and RFC 8414 +//! (metadata and where it is found, including the forms products +//! use that the specification only half allows), RFC 6750 (the +//! 401 and its challenge); plan/p15-app-and-relay.md 4 rules 1, 4, 5. +//! INVARIANTS: +//! 1. A request is answered only while the door is on, and only if its +//! Host (under HTTP/2, its authority) is the public address's host +//! (421 otherwise); a request that +//! has an Origin must have the public address's (403). +//! 2. Every address in a metadata document is built from the public +//! address the app gave and from nothing in the request. +//! 3. The metadata is served at every place the products look: the +//! protected-resource document at the root, after the well-known +//! path with the resource's path appended, and before it; the +//! authorization server's at its two well-known names, with a path +//! appended or prepended too. +//! 4. A company's path answers only for a company that is allowed and +//! open, to a request with a good token (401 and a challenge +//! otherwise, to `initialize` as to anything), over plain JSON with +//! no session. +//! 5. A request body is read to at most MAX_FORM bytes on the sign-in +//! routes; a connection waits MAX_HEADER_WAIT for a request's +//! headers and lives MAX_LIFE. +//! SCENARIOS: +//! 1. The metadata is the same whatever Host a caller claims, and a +//! claim of another Host is refused. +//! 2. `OPTIONS` on a sign-in route answers a browser's preflight. +//! ``` + +use super::{Authorize, Caller, Denied, Door, OauthError, proxy}; +use crate::admin::RemoteInfo; +use crate::local::{Books, REFUSED_HEADER}; +use axum::extract::{Extension, Path, Query, State}; +use axum::http::{HeaderMap, HeaderValue, Method, StatusCode, header}; +use axum::response::{IntoResponse, Response}; +use std::collections::BTreeMap; +use std::net::SocketAddr; +use std::sync::Arc; +use std::time::Duration; +use tokio_util::sync::CancellationToken; + +/// The largest body of a sign-in route. +const MAX_FORM: usize = 64 * 1024; +/// How long a connection has to send a request's headers. +const MAX_HEADER_WAIT: Duration = Duration::from_secs(15); +/// The longest a connection lives. +const MAX_LIFE: Duration = Duration::from_secs(30 * 60); + +/// How a request reached the books' door. +#[derive(Clone, Copy)] +pub(in crate::local) enum Via { + /// The local socket (same-user): a static token. + Local, + /// The remote door: a token this door made, from this caller. + Remote(SocketAddr), +} + +/// The caller of a connection, from its PROXY header. +#[derive(Clone, Copy)] +struct Peer(SocketAddr); + +/// Turn the door on at `public_url` (the one address, `https://…`), on +/// 127.0.0.1 at `port` (any free one when None). Idempotent for the same +/// address; another address restarts it. +pub(in crate::local) fn start_door( + books: &Arc, + public_url: &str, + port: Option, +) -> Result { + let remote = &books.remote; + let url = reqwest::Url::parse(public_url) + .map_err(|_| "the public address isn't an address".to_string())?; + let local_host = matches!(url.host_str(), Some("localhost" | "127.0.0.1" | "[::1]")); + let host = url + .host_str() + .map(str::to_ascii_lowercase) + .filter(|_| { + (url.scheme() == "https" || (url.scheme() == "http" && local_host)) + && url.username().is_empty() + && url.password().is_none() + && url.query().is_none() + && url.fragment().is_none() + && matches!(url.path(), "" | "/") + }) + .ok_or("the public address must be https://name, with no path")?; + let authority = match url.port() { + Some(p) => format!("{host}:{p}"), + None => host, + }; + let issuer = format!("{}://{authority}", url.scheme()); + if let Some(on) = remote.door() { + if on.issuer == issuer && port.is_none_or(|p| p == on.listening.port()) { + return Ok(remote.info()); + } + stop_door(books); + } + remote.load(books)?; + let listener = std::net::TcpListener::bind(("127.0.0.1", port.unwrap_or(0))) + .map_err(|e| format!("the door can't listen on that port ({})", e.kind()))?; + listener + .set_nonblocking(true) + .map_err(|e| format!("the door can't listen ({})", e.kind()))?; + let listening = listener + .local_addr() + .map_err(|e| format!("the door can't listen ({})", e.kind()))?; + let handle = tokio::runtime::Handle::try_current() + .map_err(|_| "the server isn't running".to_string())?; + let _entered = handle.enter(); + let listener = tokio::net::TcpListener::from_std(listener) + .map_err(|e| format!("the door can't listen ({})", e.kind()))?; + let stop = books.sessions.child_token(); + // The secret of this start: only the app, which is told it over the + // admin socket, can say a caller's address (proxy.rs INVARIANT 5). + let secret = proxy::new_secret()?; + let door = Arc::new(Door { + issuer: issuer.clone(), + host: host_header_form(&issuer), + listening, + stop: stop.clone(), + secret: secret.clone(), + }); + remote.set_door(Some(door)); + let app = remote_router(books.clone()); + let accept_stop = stop.clone(); + handle.spawn(proxy::accept_loop( + listener, + stop, + secret, + move |io, caller| { + let app = app.clone().layer(Extension(Peer(caller))); + let stop = accept_stop.clone(); + tokio::spawn(serve_connection(io, app, stop)); + }, + )); + Ok(remote.info()) +} + +/// Turn the door off: no new connection, and the ones open end. +pub(in crate::local) fn stop_door(books: &Arc) { + if let Some(door) = books.remote.door() { + door.stop.cancel(); + } + books.remote.set_door(None); +} + +fn host_header_form(issuer: &str) -> String { + let rest = issuer.split_once("://").map_or(issuer, |(_, r)| r); + let https = issuer.starts_with("https://"); + let rest = if https { + rest.strip_suffix(":443").unwrap_or(rest) + } else { + rest.strip_suffix(":80").unwrap_or(rest) + }; + rest.to_ascii_lowercase() +} + +async fn serve_connection(io: proxy::Proxied, app: axum::Router, stop: CancellationToken) { + use hyper_util::rt::{TokioExecutor, TokioIo, TokioTimer}; + use hyper_util::server::conn::auto::Builder; + use hyper_util::service::TowerToHyperService; + let mut builder = Builder::new(TokioExecutor::new()); + builder + .http1() + .timer(TokioTimer::new()) + .header_read_timeout(MAX_HEADER_WAIT); + let conn = builder.serve_connection(TokioIo::new(io), TowerToHyperService::new(app)); + tokio::pin!(conn); + let life = tokio::time::sleep(MAX_LIFE); + tokio::pin!(life); + let mut ending = false; + loop { + tokio::select! { + _ = conn.as_mut() => break, + () = stop.cancelled(), if !ending => { + ending = true; + conn.as_mut().graceful_shutdown(); + } + () = &mut life, if !ending => { + ending = true; + conn.as_mut().graceful_shutdown(); + } + } + } +} + +pub(in crate::local) fn remote_router(books: Arc) -> axum::Router { + axum::Router::new() + .route("/b/{book}/mcp", axum::routing::any(remote_mcp)) + .route("/authorize", axum::routing::get(authorize)) + .route("/authorize/wait/{wait}", axum::routing::get(wait)) + .route("/token", axum::routing::post(token).options(preflight)) + .route( + "/register", + axum::routing::post(register).options(preflight), + ) + .fallback(fallback) + .with_state(books) +} + +fn no_store(mut response: Response) -> Response { + let h = response.headers_mut(); + h.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store")); + h.insert(header::PRAGMA, HeaderValue::from_static("no-cache")); + h.insert( + header::X_CONTENT_TYPE_OPTIONS, + HeaderValue::from_static("nosniff"), + ); + response +} + +fn cors(mut response: Response) -> Response { + let h = response.headers_mut(); + h.insert( + header::ACCESS_CONTROL_ALLOW_ORIGIN, + HeaderValue::from_static("*"), + ); + h.insert( + header::ACCESS_CONTROL_ALLOW_METHODS, + HeaderValue::from_static("GET, POST, OPTIONS"), + ); + h.insert( + header::ACCESS_CONTROL_ALLOW_HEADERS, + HeaderValue::from_static("authorization, content-type, mcp-protocol-version"), + ); + response +} + +fn html(status: u16, page: String) -> Response { + let mut r = ( + StatusCode::from_u16(status).unwrap_or(StatusCode::BAD_REQUEST), + [(header::CONTENT_TYPE, "text/html; charset=utf-8")], + page, + ) + .into_response(); + let h = r.headers_mut(); + h.insert( + header::CONTENT_SECURITY_POLICY, + HeaderValue::from_static( + "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'", + ), + ); + h.insert(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY")); + h.insert( + header::REFERRER_POLICY, + HeaderValue::from_static("no-referrer"), + ); + no_store(r) +} + +fn json(status: u16, value: &serde_json::Value) -> Response { + no_store( + ( + StatusCode::from_u16(status).unwrap_or(StatusCode::BAD_REQUEST), + [(header::CONTENT_TYPE, "application/json")], + value.to_string(), + ) + .into_response(), + ) +} + +fn oauth_error(e: OauthError) -> Response { + let mut r = json( + e.status, + &serde_json::json!({"error": e.error, "error_description": e.description}), + ); + if e.status == 401 && e.error == "invalid_client" { + r.headers_mut().insert( + header::WWW_AUTHENTICATE, + HeaderValue::from_static("Basic realm=\"wanderbooks\", charset=\"UTF-8\""), + ); + } + cors(r) +} + +fn redirect(to: &str) -> Response { + let mut r = no_store(StatusCode::FOUND.into_response()); + if let Ok(v) = HeaderValue::from_str(to) { + r.headers_mut().insert(header::LOCATION, v); + } + r.headers_mut().insert( + header::REFERRER_POLICY, + HeaderValue::from_static("no-referrer"), + ); + r +} + +fn answer(a: Authorize) -> Response { + match a { + Authorize::Page(status, page) => html(status, page), + Authorize::Redirect(to) => redirect(&to), + } +} + +/// The door is on, and this request is for its one public host +/// (INVARIANT 1). The host is the `Host` header's; under HTTP/2 there is +/// none, and it is the request address's authority (`:authority`). +pub(super) fn front( + books: &Books, + headers: &HeaderMap, + uri: &axum::http::Uri, +) -> Result, Box> { + let Some(door) = books.remote.door() else { + return Err(Box::new(no_store( + (StatusCode::SERVICE_UNAVAILABLE, "web assistants are off").into_response(), + ))); + }; + // The host as the public address spells it: lowercase, and the scheme's + // own port (443) left off whether or not the caller wrote it. + let host = headers + .get(header::HOST) + .and_then(|h| h.to_str().ok()) + .or_else(|| uri.authority().map(|a| a.as_str())) + .map(str::to_ascii_lowercase) + .map(|h| { + let plain = door.issuer.starts_with("https://"); + let default = if plain { ":443" } else { ":80" }; + h.strip_suffix(default).map(str::to_string).unwrap_or(h) + }); + if host.as_deref() != Some(door.host.as_str()) { + return Err(Box::new(no_store( + (StatusCode::MISDIRECTED_REQUEST, "not this address").into_response(), + ))); + } + Ok(door) +} + +async fn preflight( + State(books): State>, + uri: axum::http::Uri, + headers: HeaderMap, +) -> Response { + if let Err(r) = front(&books, &headers, &uri) { + return *r; + } + cors(StatusCode::NO_CONTENT.into_response()) +} + +fn parse_pairs(text: &str) -> BTreeMap { + reqwest::Url::parse(&format!("http://x/?{text}")) + .map(|u| { + u.query_pairs() + .map(|(k, v)| (k.into_owned(), v.into_owned())) + .collect() + }) + .unwrap_or_default() +} + +async fn register( + State(books): State>, + Extension(peer): Extension, + uri: axum::http::Uri, + headers: HeaderMap, + body: axum::body::Body, +) -> Response { + if let Err(r) = front(&books, &headers, &uri) { + return *r; + } + let Ok(bytes) = axum::body::to_bytes(body, MAX_FORM).await else { + return oauth_error(OauthError { + status: 413, + error: "invalid_request", + description: "the request is too large".into(), + }); + }; + let Ok(meta) = serde_json::from_slice::(&bytes) else { + return oauth_error(OauthError { + status: 400, + error: "invalid_client_metadata", + description: "the registration must be JSON".into(), + }); + }; + match books + .remote + .register(&books, &meta, &Caller::new(peer.0.ip())) + .await + { + Ok(out) => cors(json(201, &out)), + Err(e) => oauth_error(e), + } +} + +async fn authorize( + State(books): State>, + Extension(peer): Extension, + uri: axum::http::Uri, + headers: HeaderMap, + Query(q): Query>, +) -> Response { + let door = match front(&books, &headers, &uri) { + Ok(d) => d, + Err(r) => return *r, + }; + answer( + books + .remote + .authorize(&books, &door, &q, &Caller::new(peer.0.ip())) + .await, + ) +} + +async fn wait( + State(books): State>, + uri: axum::http::Uri, + headers: HeaderMap, + Path(wait): Path, +) -> Response { + if let Err(r) = front(&books, &headers, &uri) { + return *r; + } + answer(books.remote.wait(&books, &wait)) +} + +async fn token( + State(books): State>, + Extension(peer): Extension, + uri: axum::http::Uri, + headers: HeaderMap, + body: axum::body::Body, +) -> Response { + let door = match front(&books, &headers, &uri) { + Ok(d) => d, + Err(r) => return *r, + }; + let bad = |d: &str| { + oauth_error(OauthError { + status: 400, + error: "invalid_request", + description: d.into(), + }) + }; + let Ok(bytes) = axum::body::to_bytes(body, MAX_FORM).await else { + return bad("the request is too large"); + }; + let form = if headers + .get(header::CONTENT_TYPE) + .and_then(|v| v.to_str().ok()) + .is_some_and(|t| t.contains("json")) + { + match serde_json::from_slice::>(&bytes) { + Ok(m) => m + .into_iter() + .filter_map(|(k, v)| v.as_str().map(|s| (k, s.to_string()))) + .collect(), + Err(_) => return bad("the request isn't understood"), + } + } else { + match std::str::from_utf8(&bytes) { + Ok(t) => parse_pairs(t), + Err(_) => return bad("the request isn't understood"), + } + }; + let basic = headers + .get(header::AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.split_once(' ')) + .filter(|(scheme, _)| scheme.eq_ignore_ascii_case("basic")) + .and_then(|(_, b64)| { + use base64::Engine as _; + base64::engine::general_purpose::STANDARD + .decode(b64.trim()) + .ok() + }) + .and_then(|raw| String::from_utf8(raw).ok()) + .and_then(|text| { + let (id, secret) = text.split_once(':')?; + let decode = |s: &str| { + parse_pairs(&format!("v={s}")) + .remove("v") + .unwrap_or_default() + }; + Some((decode(id), decode(secret))) + }); + match books + .remote + .token(&books, &door, &form, basic, &Caller::new(peer.0.ip())) + .await + { + Ok(out) => cors(json(200, &out)), + Err(e) => oauth_error(e), + } +} + +/// The protected-resource document of a company's address (RFC 9728). +fn resource_document(books: &Books, door: &Door, book: &str) -> Option { + if !books.remote.is_allowed(book) || !crate::local::book_is_open(books, book) { + return None; + } + Some(serde_json::json!({ + "resource": format!("{}/b/{book}/mcp", door.issuer), + "authorization_servers": [door.issuer], + "scopes_supported": ["books:read", "books:write"], + "bearer_methods_supported": ["header"], + "resource_name": crate::local::company_name(books, book), + })) +} + +/// The authorization server's document (RFC 8414), every address from the +/// one public address (INVARIANT 2). +fn server_document(door: &Door) -> serde_json::Value { + let i = &door.issuer; + serde_json::json!({ + "issuer": i, + "authorization_endpoint": format!("{i}/authorize"), + "token_endpoint": format!("{i}/token"), + "registration_endpoint": format!("{i}/register"), + "scopes_supported": ["books:read", "books:write"], + "response_types_supported": ["code"], + "response_modes_supported": ["query"], + "grant_types_supported": ["authorization_code", "refresh_token"], + "token_endpoint_auth_methods_supported": ["none", "client_secret_post", "client_secret_basic"], + "code_challenge_methods_supported": ["S256"], + "client_id_metadata_document_supported": true, + "authorization_response_iss_parameter_supported": true, + }) +} + +const PRM: &str = "/.well-known/oauth-protected-resource"; + +async fn fallback( + State(books): State>, + method: Method, + uri: axum::http::Uri, + headers: HeaderMap, +) -> Response { + let door = match front(&books, &headers, &uri) { + Ok(d) => d, + Err(r) => return *r, + }; + let not_found = || { + cors(no_store( + (StatusCode::NOT_FOUND, "not found").into_response(), + )) + }; + let path = uri.path(); + if !path.contains("/.well-known/") { + return not_found(); + } + if method == Method::OPTIONS { + return cors(StatusCode::NO_CONTENT.into_response()); + } + if method != Method::GET && method != Method::HEAD { + return cors(no_store( + (StatusCode::METHOD_NOT_ALLOWED, "GET only").into_response(), + )); + } + if let Some(at) = path.find(PRM) { + let before = &path[..at]; + let after = &path[at + PRM.len()..]; + let resource = if after.is_empty() { before } else { after }; + let resource = resource.trim_end_matches('/'); + let book = match resource + .strip_prefix("/b/") + .and_then(|r| r.strip_suffix("/mcp")) + { + Some(b) => Some(b.to_string()), + None if resource.is_empty() => { + // The root: the company, if only one is on offer. + books.remote.only_open_book(&books) + } + None => None, + }; + return match book.and_then(|b| resource_document(&books, &door, &b)) { + Some(doc) => cors(json(200, &doc)), + None => not_found(), + }; + } + if path.contains("/.well-known/oauth-authorization-server") + || path.contains("/.well-known/openid-configuration") + { + return cors(json(200, &server_document(&door))); + } + not_found() +} + +/// A company's MCP path on the remote door. +async fn remote_mcp( + State(books): State>, + Extension(peer): Extension, + Path(book): Path, + request: axum::extract::Request, +) -> Response { + let door = match front(&books, request.headers(), request.uri()) { + Ok(d) => d, + Err(r) => return *r, + }; + if let Some(origin) = request.headers().get(header::ORIGIN) + && origin.to_str().ok() != Some(door.issuer.as_str()) + { + return no_store((StatusCode::FORBIDDEN, "origin not allowed").into_response()); + } + // A company not on offer is not there at all. + if !books.remote.is_allowed(&book) { + return no_store( + ( + StatusCode::NOT_FOUND, + [(REFUSED_HEADER, "no-such-books")], + "there are no books here", + ) + .into_response(), + ); + } + crate::local::mcp_via(books, book, request, Via::Remote(peer.0)).await +} + +/// The 401 of a request with no good token (INVARIANT 3 of mod.rs): the +/// challenge names the company's protected-resource metadata, so a client +/// that was never told anything can find where to sign in. +pub(in crate::local) fn unauthorized(door: &Door, book: &str, denied: &Denied) -> Response { + let mut challenge = format!( + "Bearer resource_metadata=\"{}/.well-known/oauth-protected-resource/b/{}/mcp\", scope=\"books:read books:write\"", + door.issuer, + book.chars() + .filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_') + .collect::() + ); + if denied.invalid_token { + challenge.push_str(", error=\"invalid_token\""); + } + let mut r = no_store( + ( + StatusCode::UNAUTHORIZED, + [(REFUSED_HEADER, denied.code)], + serde_json::json!({"error": "unauthorized", "error_description": denied.why}) + .to_string(), + ) + .into_response(), + ); + if let Ok(v) = HeaderValue::from_str(&challenge) { + r.headers_mut().insert(header::WWW_AUTHENTICATE, v); + } + r.headers_mut().insert( + header::CONTENT_TYPE, + HeaderValue::from_static("application/json"), + ); + r +} diff --git a/crates/ledger-mcp/src/local/remote/mod.rs b/crates/ledger-mcp/src/local/remote/mod.rs new file mode 100644 index 00000000..31b10f09 --- /dev/null +++ b/crates/ledger-mcp/src/local/remote/mod.rs @@ -0,0 +1,2594 @@ +//! The remote door: how web assistants (Claude and ChatGPT on the web, +//! others best effort) reach a company, and the sign-in behind it (plan +//! P15 unit B1; D-81, D-83, D-86, D-88). +//! +//! ```text +//! GOAL: a web assistant reaches ONE company's tools over HTTPS only after +//! the person at the machine has said yes in the app's window, with +//! only the permissions they gave, and loses that access the moment +//! they revoke it; and nothing a stranger on the internet sends can +//! approve a connection, reach another company, fill the server's +//! memory or disk, or make the server believe the caller is local. +//! SOURCE: WB-remote-1 to WB-remote-10 (docs/spec/claims/remote.md; the +//! ten sign-in rules of plan/p15-app-and-relay.md section 4); D-83 +//! (the app is its own sign-in server), D-86 (read and draft by +//! default), D-88 (every write is one transaction, once); OAuth +//! 2.1 (draft-ietf-oauth-v2-1), RFC 7636 (PKCE), RFC 7591 +//! (dynamic registration), RFC 8414 and RFC 9728 (metadata), +//! RFC 8707 (resource indicators), RFC 6749 section 10.4 and +//! RFC 9700 (refresh token rotation and reuse), the IETF draft +//! for OAuth client ID metadata documents; the MCP authorization +//! specification, revision 2026-07-28. +//! INVARIANTS: +//! 1. Off unless asked: the door listens on 127.0.0.1 only after an +//! admin request (`RemoteStart`) and stops on `RemoteStop` or when the +//! server closes. It serves a company only while that company is +//! allowed (`RemoteAllow`) AND open. Every connection begins with this +//! start's secret and then the relay's PROXY header (proxy.rs): only +//! the app, which is given the secret over the admin socket, can say a +//! caller's address. The address in the header is the caller's, +//! is what the access record and the limits use, and is never taken +//! from an HTTP header. Nothing on this door is ever treated as local: +//! every request needs a token, and the local socket's same-user check +//! is not a thing a request here can claim. +//! 2. One public address: the issuer is the URL the app gave `RemoteStart` +//! and no other. Every address in every metadata document is built +//! from it, never from the request's Host; a request whose Host is +//! not its host is refused (421). A token, code or refresh token made +//! for one issuer is refused under another. +//! 3. Unsigned is refused: every request to a company's path with no +//! token, a wrong one, or an expired one is a 401 with a +//! `WWW-Authenticate` that names the protected-resource metadata, +//! `initialize` included. Such a request is counted, not written to +//! the books' access record (a stranger can't fill the disk). +//! 4. Three ways to introduce a client: a client ID metadata document (an +//! https URL, fetched with the checks of cimd.rs), dynamic +//! registration, and a client id and secret the app made. A redirect +//! address must match one registered, exactly; a registration may +//! carry up to MAX_REDIRECTS. PKCE with S256 is required; the +//! `resource` must be the one company's address; a code is single-use +//! and lives CODE_TTL; the consent ends in a 302. +//! 5. No approval without the person, and every sign-in is asked (D-90). +//! `/authorize` never approves and always parks the request +//! (PENDING_TTL), whatever the product and whatever was approved +//! before: the redirect host is public, so it says nothing of whose +//! account asks. Only an admin request, which the owner-only admin +//! socket carries, turns a parked request into a code. A parked +//! request is named by two unrelated random ids: the one the window +//! shows, and the one only the browser's page holds; and carries a +//! short code shown on the page and on the card, for the person to +//! match. Neither a stranger's guess nor a replay approves anything: +//! the second id only reads the outcome, once. The window is told +//! what is known in neutral words: where it is sent back to, and its +//! own cleaned word for itself; never "a known product". +//! 6. An approval is the owner's decision about one sign-in, a company and +//! a set of permissions, never reused: it is one token of the books' +//! principals (so "Who can reach these books" lists it, and revoking +//! it by id ends every access and refresh token made under it, at +//! that moment), plus a record here. Every Allow makes a new one with +//! exactly the permissions ticked. Access tokens live ACCESS_TTL; +//! refresh tokens REFRESH_TTL since last use, rotated at every use +//! (checked and marked in one hold of the lock), and a refresh token +//! used twice ends its whole family. +//! 7. Secrets are never stored: codes, access tokens, refresh tokens and +//! client secrets are kept as SHA-256 only, and compared by hash (or +//! in constant time where a hash is compared to a hash). +//! 8. Every table is bounded (MAX_* below) and expires: registered +//! clients unused for CLIENT_IDLE (held in memory until the person +//! allows one), pending requests (which give way to newer ones rather +//! than turn them away), codes, access tokens, refresh tokens. A +//! stranger registering clients, or asking to sign in, can fill none +//! of them, nor the file; a failure to sign in is never ground for +//! banning an address (vendors share addresses), only the state a +//! request creates is bounded, and an approval's own calls are +//! limited. Addresses are counted per IPv4 address or IPv6 /64. +//! 9. No company mixing: a token for company A, presented at company +//! B's path, is refused (403, counted, not written); a +//! code and a refresh token carry their company and never issue a +//! token for another. +//! 10. Remote permissions: an approval grants read and draft; posting is +//! raised per approval by the owner (`RemoteSetPost`) and lowered the +//! same way; the access record's admin scope is never granted here. +//! Every call goes through the one write path (server.rs `call_tool`: +//! a write needs its request key, D-88) and is stateless and plain +//! JSON: no session is kept for a remote caller. +//! SCENARIOS: +//! 1. A client registers, asks to sign in, the person allows it in the +//! window, the browser is sent back with a code, the code gives an +//! access token and a refresh token, and the access token reads the +//! books. The same with a metadata-document client and with a typed +//! client id and secret. +//! 2. Every refusal: wrong redirect, no PKCE, a code used twice, a +//! refresh token used twice, a token for another issuer, an expired +//! token, an unsigned `initialize`, a token for another company. +//! 3. The person refuses, or no one decides in time: the browser is sent +//! back with `access_denied`; nothing was made. +//! 4. The person revokes the connection in the list: its access token +//! stops at once, its refresh token is refused. +//! 5. A caller's forged PROXY header, `X-Forwarded-For`, or second header +//! changes nothing: the recorded address is the first header's. +//! ``` + +mod cimd; +mod http; +mod pages; +pub(super) mod proxy; +#[cfg(test)] +mod tests; + +pub(super) use cimd::{ClientDocs, WebDocs}; +pub(super) use http::{Via, start_door, stop_door, unauthorized}; + +use super::Books; +use crate::admin::{ApprovalInfo, PendingInfo, RemoteInfo}; +use base64::Engine as _; +use ledger_store::auth::{Scope, Token}; +use ledger_store::root::BookId; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::net::{IpAddr, SocketAddr}; +use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, RwLock}; +use tokio_util::sync::CancellationToken; + +/// How long an access token lives (seconds): short, so a revoke that +/// somehow missed would still end soon, and the refresh token is the +/// long-lived thing. +pub const ACCESS_TTL: i64 = 600; +/// How long a code lives, and that it is good once. +pub const CODE_TTL: i64 = 60; +/// How long a request waits for the person. +pub const PENDING_TTL: i64 = 300; +/// How long a refresh token lives since it was last used: 60 days, so an +/// assistant that comes back after the app was closed for weeks still +/// works (rule 6). +pub const REFRESH_TTL: i64 = 60 * 24 * 3600; +/// How long a registration nobody used for a sign-in is kept. +pub const CLIENT_IDLE: i64 = 3600; +/// How long a fetched client metadata document is believed. +pub const CIMD_TTL: i64 = 3600; +/// Most registered clients (dynamic, document and typed), together. +pub const MAX_CLIENTS: usize = 2000; +/// Most redirect addresses one client may carry. +pub const MAX_REDIRECTS: usize = 20; +/// Most requests waiting for the person. A new one beyond it does not turn +/// away: the oldest request of the address with the most waiting gives way. +pub const MAX_PENDING: usize = 20; +/// Most requests one address may have waiting; its own oldest gives way to +/// a new one. +pub const MAX_PENDING_PER_ADDRESS: usize = 5; +/// The most a redirect address may be, and all of one client's together. +pub const MAX_REDIRECT_BYTES: usize = 512; +pub const MAX_REDIRECTS_TOTAL: usize = 4096; +/// The longest a name an assistant gave itself is shown. +pub const MAX_NAME_SHOWN: usize = 40; +/// Most codes, access tokens and refresh tokens held. +pub const MAX_CODES: usize = 2000; +/// Most access tokens held. +pub const MAX_ACCESS: usize = 20_000; +/// Most refresh tokens (live and used) held. +pub const MAX_REFRESH: usize = 20_000; +/// Most approvals (connections) held. +pub const MAX_APPROVALS: usize = 500; +/// Most refresh families of one approval. +pub const MAX_FAMILIES: usize = 10; +/// Most typed client ids the app has made. +pub const MAX_MANUAL: usize = 20; +/// Most keys the app has made for products that take only a key. +pub const MAX_KEYS: usize = 50; +/// Registrations one address may make in an hour. +const REGISTER_PER_ADDRESS: u32 = 30; +/// Registrations the door takes in an hour, together. +const REGISTER_TOTAL: u32 = 600; +/// Sign-in starts one address may make in ten minutes. +const AUTHORIZE_PER_ADDRESS: u32 = 60; +/// Client metadata fetches in a minute, together and from one address. +const FETCH_PER_MINUTE: u32 = 30; +const FETCH_PER_ADDRESS: u32 = 6; +/// Token requests a client may make in a minute, and one address. +const TOKEN_PER_CLIENT: u32 = 120; +const TOKEN_PER_ADDRESS: u32 = 300; +/// Calls an approval may make in a minute. +pub const CALLS_PER_MINUTE: u32 = 600; +/// The limiter's table of addresses is bounded too: past it the entries +/// that began longest ago go. (A connection's own limits are never evicted: +/// they are few by construction, one per approval, key and known client.) +const MAX_ADDRESS_LIMITS: usize = 10_000; +/// How long a used code is remembered, to end the family a replay shows. +const USED_CODE_KEPT: i64 = 600; +/// How many made-over tokens are remembered for a late revoke. +const MAX_SWAPPED: usize = 1000; +/// The persisted file, in the root's `auth/`. +pub const FILE: &str = "remote.json"; + +/// The scopes a web approval gets by default (D-86), and with posting +/// raised. Admin is never among them. +pub fn scopes_for(post: bool) -> BTreeSet { + let mut s = BTreeSet::from([Scope::Read, Scope::Write]); + if post { + s.insert(Scope::Post); + } + s +} + +/// How a client introduced itself. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Kind { + /// A client ID metadata document: its id is the https URL. + Document, + /// Dynamic registration. + Registered, + /// A client id and secret the app made, typed into the product. + Typed, +} + +/// A client the door knows. Never a secret: only the secret's hash. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct ClientRec { + pub id: String, + pub kind: Kind, + /// What it calls itself: asserted, cleaned, never trusted. + pub name: String, + /// The redirect addresses it may be sent back to, exactly. + pub redirects: Vec, + /// The SHA-256 (hex) of its secret, when it has one. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub secret_sha256: Option, + pub created: i64, + pub last_seen: i64, + /// Whether a sign-in was ever begun with it. + pub used: bool, + /// Whether the person ever said yes to a sign-in of it: only such a + /// client (and a typed one) is kept on disk, and only such a client is + /// ever sent an error as a redirect. + #[serde(default)] + pub approved: bool, + /// When its document was fetched (documents only). + #[serde(default)] + pub fetched: i64, +} + +/// The owner's decision: a product, a company, permissions. One token of +/// the books' principals carries what it may do. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Approval { + pub id: String, + pub book: String, + /// What the window and the list call it. + pub label: String, + /// The principals' token that carries the permissions. + pub token_name: String, + pub token_id: String, + pub created: i64, + pub last_used: i64, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +struct RefreshRec { + hash: String, + family: String, + approval: String, + client: String, + issuer: String, + exp: i64, + used: bool, + created: i64, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +struct KeyRec { + token_id: String, + book: String, + created: i64, +} + +#[derive(Default, Serialize, Deserialize)] +struct Saved { + version: u32, + clients: Vec, + approvals: Vec, + refresh: Vec, + keys: Vec, +} + +struct Code { + client: String, + approval: String, + family: String, + book: String, + issuer: String, + redirect: String, + challenge: String, + exp: i64, +} + +/// What a mint made: the access token and the refresh token (given once), +/// the refresh token's hash as kept, and the one it retired. +struct Minted { + access: String, + refresh: String, + new_hash: String, + undo: Option, +} + +struct AccessRec { + approval: String, + family: String, + book: String, + issuer: String, + exp: i64, +} + +enum Settled { + Waiting, + /// The person said yes: the code the browser is sent back with. + Allowed(String), + Refused, + /// Made way for a newer request when too many were waiting. + Crowded, +} + +struct Pending { + /// What the window names it by. + id: String, + /// What only the browser's page holds. + wait: String, + client: String, + /// What it calls itself, cleaned and short; may be empty. + client_name: String, + /// Whether the redirect host is one of the known vendors'. + known_host: bool, + /// The short code the person matches between the page and the card. + code: String, + redirect: String, + state: Option, + challenge: String, + book: String, + issuer: String, + from: String, + /// The address as the limits count it (a /64 for IPv6). + from_key: String, + wants_post: bool, + created: i64, + exp: i64, + settled: Settled, +} + +#[derive(Default)] +struct Inner { + loaded: bool, + clients: BTreeMap, + approvals: BTreeMap, + refresh: HashMap, + keys: BTreeMap, + codes: HashMap, + used_codes: HashMap, + access: HashMap, + pending: Vec, + /// A connection's own limits, and the few door-wide ones: never evicted. + limits: HashMap, + /// Per-address limits (start, count, window): evicted oldest first. + address_limits: HashMap, + /// A token that was made over (posting raised or lowered) and the one + /// that replaced it, for a revoke that names the old. + swapped: HashMap, + failed_docs: HashMap, + unsigned: u64, + /// Calls refused as another company's or for rate, counted, not written. + refused: u64, + last_sweep: i64, +} + +/// The door while it is on. +pub(super) struct Door { + /// The one public address, no trailing slash. + pub issuer: String, + /// Its host as a `Host` header says it. + pub host: String, + pub listening: SocketAddr, + pub stop: CancellationToken, + /// This start's secret: the app begins every connection with it + /// (proxy.rs INVARIANT 5). + pub secret: String, +} + +/// Why a token is refused at the door. +pub(super) struct Denied { + pub code: &'static str, + pub why: String, + /// The token was presented but is not good: `error="invalid_token"`. + pub invalid_token: bool, +} + +/// An OAuth error answer. +pub(super) struct OauthError { + pub status: u16, + pub error: &'static str, + pub description: String, +} + +impl OauthError { + fn new(status: u16, error: &'static str, description: impl Into) -> Self { + Self { + status, + error, + description: description.into(), + } + } +} + +/// What the remote door holds (invariants above). +pub(super) struct Remote { + inner: Mutex, + door: RwLock>>, + allowed: RwLock>, + clock: RwLock i64 + Send + Sync>>, + docs: RwLock>, + dir: Mutex>, + version: AtomicU64, + written: Mutex, +} + +fn sha_hex(text: &str) -> String { + hex_of(&Sha256::digest(text.as_bytes())) +} + +fn hex_of(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +/// `n` random bytes as unpadded base64url, behind `prefix`. +fn random(prefix: &str, n: usize) -> Result { + let mut buf = vec![0u8; n]; + getrandom::getrandom(&mut buf) + .map_err(|_| OauthError::new(500, "server_error", "the system gave no randomness"))?; + Ok(format!( + "{prefix}{}", + base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(buf) + )) +} + +/// Characters that draw nothing or turn text around (zero-width and joining +/// characters, direction marks and overrides, invisible operators, the soft +/// hyphen, variation selectors, tag characters): a name can't hide or +/// reorder anything with them. +fn is_invisible(c: char) -> bool { + matches!(c, + '\u{00AD}' | '\u{034F}' | '\u{061C}' | '\u{115F}' | '\u{1160}' + | '\u{17B4}' | '\u{17B5}' | '\u{180B}'..='\u{180F}' + | '\u{200B}'..='\u{200F}' | '\u{202A}'..='\u{202E}' + | '\u{2060}'..='\u{206F}' | '\u{3164}' | '\u{FE00}'..='\u{FE0F}' + | '\u{FEFF}' | '\u{FFA0}' | '\u{FFF9}'..='\u{FFFB}' + | '\u{1BCA0}'..='\u{1BCA3}' | '\u{1D173}'..='\u{1D17A}' + | '\u{E0000}'..='\u{E007F}' | '\u{E0100}'..='\u{E01EF}') +} + +/// A name, cleaned for showing and for storing: no control, invisible or +/// direction-changing characters, single spaces, at most `max` characters. +pub(super) fn clean(text: &str, max: usize) -> String { + let mut out = String::new(); + for word in text.split_whitespace() { + let word: String = word + .chars() + .filter(|c| !c.is_control() && !is_invisible(*c)) + .collect(); + if word.is_empty() { + continue; + } + if !out.is_empty() { + out.push(' '); + } + out.push_str(&word); + if out.chars().count() >= max { + break; + } + } + out.chars().take(max).collect() +} + +/// A redirect address, parsed if it may be one: https, or http on the +/// loopback, or a native app's own scheme; never a fragment or userinfo, +/// never a script or file scheme, never more than MAX_REDIRECT_BYTES. +pub(super) fn valid_redirect(text: &str) -> Option { + if text.len() > MAX_REDIRECT_BYTES || text.chars().any(char::is_control) { + return None; + } + let url = reqwest::Url::parse(text).ok()?; + if url.fragment().is_some() || !url.username().is_empty() || url.password().is_some() { + return None; + } + match url.scheme() { + "https" => { + let has_host = url.host_str().is_some_and(|h| !h.is_empty()); + has_host.then_some(url) + } + "http" => { + matches!(url.host_str(), Some("localhost" | "127.0.0.1" | "[::1]")).then_some(url) + } + "javascript" | "data" | "file" | "vbscript" | "about" | "blob" | "ftp" | "ws" | "wss" => { + None + } + s if s.len() >= 2 => Some(url), + _ => None, + } +} + +/// Whether all of one client's redirect addresses together are no more +/// than the table keeps (a registration is held in memory, and in the file +/// once the person has allowed it). +pub(super) fn redirects_fit(redirects: &[String]) -> bool { + redirects.iter().map(String::len).sum::() <= MAX_REDIRECTS_TOTAL +} + +/// What a redirect address shows the person: its host, or its scheme. +pub(super) fn redirect_host(url: &str) -> String { + reqwest::Url::parse(url) + .ok() + .map(|u| match u.host_str() { + Some(h) => h.to_string(), + None => format!("{}:", u.scheme()), + }) + .unwrap_or_else(|| "?".to_string()) +} + +/// The hosts of the vendors whose web assistants most people use (D-81: +/// Claude and ChatGPT). Only the *warning* depends on it: a request sent +/// back to one of them is not warned about, and is never called a known +/// product, because the host is public and says nothing of who asks. +const VENDOR_HOSTS: &[&str] = &[ + "claude.ai", + "claude.com", + "chatgpt.com", + "openai.com", + "platform.openai.com", +]; + +/// Whether this redirect address is on one of the vendors' hosts. +pub(super) fn is_vendor_host(redirect: &str) -> bool { + reqwest::Url::parse(redirect).ok().is_some_and(|u| { + u.scheme() == "https" + && u.host_str() + .is_some_and(|h| VENDOR_HOSTS.contains(&h.to_ascii_lowercase().as_str())) + }) +} + +/// What an assistant calls itself, as shown: cleaned and short; empty if +/// it gave none. +fn shown_name(client: &ClientRec) -> String { + clean(&client.name, MAX_NAME_SHOWN) +} + +/// What the window and the list call a connection: where it was sent back +/// to first, then its own word for itself, never a name of a product made +/// up from the host. +fn label_of(client: &ClientRec, redirect: &str) -> String { + let host = redirect_host(redirect); + let name = shown_name(client); + if name.is_empty() { + format!("An assistant sent back to {host}") + } else { + format!("{name} (sent back to {host})") + } +} + +/// A caller: its address as shown, and as the limits count it. +#[derive(Clone, Debug)] +pub(super) struct Caller { + pub shown: String, + pub key: String, +} + +impl Caller { + pub(super) fn new(ip: IpAddr) -> Self { + Self { + shown: canonical(ip).to_string(), + key: address_key(ip), + } + } +} + +/// An address with an IPv4-mapped form made the IPv4 address it is. +fn canonical(ip: IpAddr) -> IpAddr { + match ip { + IpAddr::V6(v6) => v6.to_ipv4_mapped().map_or(IpAddr::V6(v6), IpAddr::V4), + v4 => v4, + } +} + +/// What the per-address limits count by: an IPv4 address; an IPv6 caller's +/// /64 (one household or one host holds a whole one, and an attacker holds +/// billions of them, so a single address would be no limit at all); an +/// IPv4-mapped IPv6 address is the IPv4 one. +pub(super) fn address_key(ip: IpAddr) -> String { + match canonical(ip) { + IpAddr::V4(v4) => v4.to_string(), + IpAddr::V6(v6) => { + let s = v6.segments(); + format!("{:x}:{:x}:{:x}:{:x}::/64", s[0], s[1], s[2], s[3]) + } + } +} + +/// A short code for the person to match between the browser's page and the +/// window's card: six digits, in two groups, never the same as another +/// waiting request's. +fn match_code(inner: &Inner) -> Result { + for _ in 0..50 { + let mut b = [0u8; 4]; + getrandom::getrandom(&mut b) + .map_err(|_| OauthError::new(500, "server_error", "the system gave no randomness"))?; + let n = u32::from_be_bytes(b); + // Without bias: a number past the last whole million is thrown away. + if n >= 4_294_000_000 { + continue; + } + let n = n % 1_000_000; + let code = format!("{:03} {:03}", n / 1000, n % 1000); + if !inner.pending.iter().any(|p| p.code == code) { + return Ok(code); + } + } + Err(OauthError::new(503, "temporarily_unavailable", "busy")) +} + +/// A principals' token name from a label: lowercase letters, digits and +/// hyphens, at most 24 characters after `web-`. +fn token_slug(label: &str) -> String { + let mut slug = String::new(); + for c in label.chars() { + if c.is_ascii_alphanumeric() { + slug.push(c.to_ascii_lowercase()); + } else if !slug.ends_with('-') && !slug.is_empty() { + slug.push('-'); + } + } + let slug: String = slug.trim_matches('-').chars().take(24).collect(); + let slug = slug.trim_end_matches('-').to_string(); + format!( + "web-{}", + if slug.is_empty() { + "assistant".to_string() + } else { + slug + } + ) +} + +impl Remote { + pub(super) fn new() -> Self { + Self { + inner: Mutex::new(Inner::default()), + door: RwLock::new(None), + allowed: RwLock::new(BTreeSet::new()), + clock: RwLock::new(Arc::new(|| { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_secs() as i64) + })), + docs: RwLock::new(Arc::new(WebDocs)), + dir: Mutex::new(None), + version: AtomicU64::new(0), + written: Mutex::new(0), + } + } + + fn inner(&self) -> std::sync::MutexGuard<'_, Inner> { + self.inner.lock().unwrap_or_else(|e| e.into_inner()) + } + + pub(super) fn now(&self) -> i64 { + (self.clock.read().unwrap_or_else(|e| e.into_inner()))() + } + + /// Test seam: the clock. + #[cfg(test)] + pub(super) fn set_clock(&self, clock: Arc i64 + Send + Sync>) { + *self.clock.write().unwrap() = clock; + } + + /// Test seam: where client metadata documents come from. + #[cfg(test)] + pub(super) fn set_docs(&self, docs: Arc) { + *self.docs.write().unwrap() = docs; + } + + pub(super) fn door(&self) -> Option> { + self.door.read().unwrap_or_else(|e| e.into_inner()).clone() + } + + /// The one company on offer that is open, if there is exactly one. + pub(super) fn only_open_book(&self, books: &Books) -> Option { + let open: Vec = self + .allowed + .read() + .unwrap_or_else(|e| e.into_inner()) + .iter() + .filter(|b| super::book_is_open(books, b)) + .cloned() + .collect(); + match open.as_slice() { + [only] => Some(only.clone()), + _ => None, + } + } + + pub(super) fn is_allowed(&self, book: &str) -> bool { + self.allowed + .read() + .unwrap_or_else(|e| e.into_inner()) + .contains(book) + } + + /// Count a request refused for want of a good token (INVARIANT 3). + pub(super) fn count_unsigned(&self) { + let mut inner = self.inner(); + inner.unsigned = inner.unsigned.saturating_add(1); + } + + /// Requests refused for want of a good token, since the server began. + #[cfg(test)] + pub(super) fn unsigned(&self) -> u64 { + self.inner().unsigned + } + + // ---- persistence ------------------------------------------------------ + + /// Read what was kept, once (from the root's `auth/`). + fn load(&self, books: &Books) -> Result<(), String> { + let dir = books.root.auth_dir().map_err(|e| e.to_string())?; + *self.dir.lock().unwrap_or_else(|e| e.into_inner()) = Some(dir.clone()); + let mut inner = self.inner(); + if inner.loaded { + return Ok(()); + } + let saved: Saved = match std::fs::read(dir.join(FILE)) { + Ok(bytes) => serde_json::from_slice(&bytes) + .map_err(|_| "the record of web sign-ins can't be read".to_string())?, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Saved::default(), + Err(_) => return Err("the record of web sign-ins can't be read".into()), + }; + inner.clients = saved + .clients + .into_iter() + .map(|c| (c.id.clone(), c)) + .collect(); + inner.approvals = saved + .approvals + .into_iter() + .map(|a| (a.id.clone(), a)) + .collect(); + inner.refresh = saved + .refresh + .into_iter() + .map(|r| (r.hash.clone(), r)) + .collect(); + inner.keys = saved + .keys + .into_iter() + .map(|k| (k.token_id.clone(), k)) + .collect(); + inner.loaded = true; + Ok(()) + } + + fn snapshot(&self, inner: &Inner) -> (u64, String) { + let saved = Saved { + version: 1, + // A registration nobody ever allowed lives in memory only: a + // stranger's registrations cost the disk nothing. + clients: inner + .clients + .values() + .filter(|c| c.approved || c.kind == Kind::Typed) + .cloned() + .collect(), + approvals: inner.approvals.values().cloned().collect(), + refresh: inner.refresh.values().cloned().collect(), + keys: inner.keys.values().cloned().collect(), + }; + let v = self.version.fetch_add(1, Ordering::SeqCst) + 1; + (v, serde_json::to_string(&saved).unwrap_or_default()) + } + + /// Write the state (blocking), never letting an older snapshot + /// overwrite a newer one. Private to the owner (0600), whole or not at + /// all (written beside, then renamed over). + fn save(&self) -> Result<(), String> { + let (version, text) = self.snapshot(&self.inner()); + let dir = self + .dir + .lock() + .unwrap_or_else(|e| e.into_inner()) + .clone() + .ok_or_else(|| "the record of web sign-ins isn't open".to_string())?; + let mut written = self.written.lock().unwrap_or_else(|e| e.into_inner()); + if version < *written { + return Ok(()); + } + let tmp = dir.join(format!("{FILE}.tmp")); + { + use std::io::Write; + let mut options = std::fs::OpenOptions::new(); + options.write(true).create(true).truncate(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let mut file = options + .open(&tmp) + .map_err(|_| "the record of web sign-ins can't be written".to_string())?; + // Windows has no mode: the same owner-only helper the token + // files use, before anything is written into the file. + #[cfg(windows)] + ledger_store::winsec::set_owner_only(&tmp) + .map_err(|_| "the record of web sign-ins can't be made private".to_string())?; + file.write_all(text.as_bytes()) + .and_then(|()| file.sync_all()) + .map_err(|_| "the record of web sign-ins can't be written".to_string())?; + } + std::fs::rename(&tmp, dir.join(FILE)) + .map_err(|_| "the record of web sign-ins can't be written".to_string())?; + *written = version; + Ok(()) + } + + /// [`Remote::save`] off the async threads. + async fn save_async(self: &Arc) -> Result<(), String> { + let me = self.clone(); + tokio::task::spawn_blocking(move || me.save()) + .await + .unwrap_or_else(|_| Err("the record of web sign-ins can't be written".into())) + } + + // ---- limits and sweeps ------------------------------------------------ + + /// A fixed-window counter for a connection's own or a door-wide limit: + /// whether `key` may do one more thing in `window` seconds, `max` at + /// most. These keys are few by construction (one per approval, key or + /// known client, and a handful door-wide), so the table is never + /// evicted from: only what has expired is dropped. + fn allow(&self, inner: &mut Inner, key: String, max: u32, window: i64) -> bool { + let now = self.now(); + if inner.limits.len() >= MAX_ADDRESS_LIMITS && !inner.limits.contains_key(&key) { + inner.limits.retain(|_, (start, _)| now - *start < 3600); + } + let slot = inner.limits.entry(key).or_insert((now, 0)); + if now - slot.0 >= window { + *slot = (now, 0); + } + if slot.1 >= max { + return false; + } + slot.1 += 1; + true + } + + /// The same for a caller's address (INVARIANT 8): the table of these is + /// bounded, and when it is full it is the per-address entries that + /// began longest ago that go, never a connection's own limit. + fn allow_address(&self, inner: &mut Inner, key: String, max: u32, window: i64) -> bool { + let now = self.now(); + if inner.address_limits.len() >= MAX_ADDRESS_LIMITS + && !inner.address_limits.contains_key(&key) + { + inner + .address_limits + .retain(|_, (start, _, w)| now - *start < *w); + if inner.address_limits.len() >= MAX_ADDRESS_LIMITS { + let mut by_age: Vec<(i64, String)> = inner + .address_limits + .iter() + .map(|(k, (start, _, _))| (*start, k.clone())) + .collect(); + by_age.sort(); + for (_, k) in by_age.into_iter().take(MAX_ADDRESS_LIMITS / 10) { + inner.address_limits.remove(&k); + } + } + } + let slot = inner.address_limits.entry(key).or_insert((now, 0, window)); + if now - slot.0 >= window { + *slot = (now, 0, window); + } + if slot.1 >= max { + return false; + } + slot.1 += 1; + true + } + + /// Whether `key` may do one more thing in `window` seconds (callers + /// outside the lock). + pub(super) fn limited(&self, key: String, max: u32, window: i64) -> bool { + let mut inner = self.inner(); + !self.allow(&mut inner, key, max, window) + } + + /// Count a call refused as another company's or for rate: counted, not + /// written to the books' record (a token holder could fill the disk). + pub(super) fn count_refused(&self) { + let mut inner = self.inner(); + inner.refused = inner.refused.saturating_add(1); + } + + /// Calls refused as another company's or for rate, since the server began. + #[cfg(test)] + pub(super) fn refused(&self) -> u64 { + self.inner().refused + } + + /// Drop what has expired (INVARIANT 8). At most every few seconds. + fn sweep(&self, inner: &mut Inner) { + let now = self.now(); + if now - inner.last_sweep < 5 && now >= inner.last_sweep { + return; + } + inner.last_sweep = now; + inner.codes.retain(|_, c| c.exp > now); + inner.used_codes.retain(|_, (_, until)| *until > now); + inner.access.retain(|_, a| a.exp > now); + inner.refresh.retain(|_, r| r.exp > now); + inner.failed_docs.retain(|_, until| *until > now); + inner.limits.retain(|_, (start, _)| now - *start < 3600); + inner + .address_limits + .retain(|_, (start, _, w)| now - *start < (*w).max(3600)); + // A sign-in nobody decided is over (the page finds out on its + // next look); one decided and collected is gone. + for p in &mut inner.pending { + if p.exp <= now && matches!(p.settled, Settled::Waiting) { + p.settled = Settled::Refused; + } + } + inner + .pending + .retain(|p| p.exp + 60 > now || matches!(p.settled, Settled::Waiting)); + // A registration nobody used is kept an hour; one a sign-in used + // stays while a refresh token or an approval still names it. + let named: BTreeSet = inner.refresh.values().map(|r| r.client.clone()).collect(); + inner.clients.retain(|id, c| { + c.kind == Kind::Typed + || (c.used && (named.contains(id) || now - c.last_seen < CLIENT_IDLE)) + || (!c.used && now - c.created < CLIENT_IDLE) + }); + } + + // ---- the door's own state ---------------------------------------------- + + /// Turn the door's state on for `issuer`. Called by `RemoteStart`. + pub(super) fn set_door(&self, door: Option>) { + *self.door.write().unwrap_or_else(|e| e.into_inner()) = door; + } + + pub(super) fn set_allowed(&self, book: &str, allowed: bool) { + let mut set = self.allowed.write().unwrap_or_else(|e| e.into_inner()); + if allowed { + set.insert(book.to_string()); + } else { + set.remove(book); + drop(set); + // Nobody is left waiting for books that are no longer offered. + let mut inner = self.inner(); + inner.pending.retain(|p| p.book != book); + } + } + + pub(super) fn info(&self) -> RemoteInfo { + let door = self.door(); + RemoteInfo { + listening: door.as_ref().map(|d| d.listening.to_string()), + public_url: door.as_ref().map(|d| d.issuer.clone()), + proxy_secret: door.map(|d| crate::admin::TokenText(d.secret.clone())), + allowed: self + .allowed + .read() + .unwrap_or_else(|e| e.into_inner()) + .iter() + .cloned() + .collect(), + } + } + + // ---- clients ------------------------------------------------------------ + + /// Make room for one more client: the oldest unused registration goes + /// (INVARIANT 8); none unused and the table is full is a refusal. + fn make_room(&self, inner: &mut Inner) -> Result<(), OauthError> { + if inner.clients.len() < MAX_CLIENTS { + return Ok(()); + } + let oldest = inner + .clients + .values() + .filter(|c| !c.used && c.kind != Kind::Typed) + .min_by_key(|c| c.created) + .map(|c| c.id.clone()); + match oldest { + Some(id) => { + inner.clients.remove(&id); + Ok(()) + } + None => Err(OauthError::new( + 503, + "temporarily_unavailable", + "too many assistants are signed in to take another registration now", + )), + } + } + + /// Dynamic registration (RFC 7591): the answer's JSON, or why not. The + /// registration is held in memory only: it reaches the disk if and when + /// the person allows a sign-in of it (D-90, and no stranger writes the + /// file). + pub(super) async fn register( + self: &Arc, + books: &Arc, + meta: &serde_json::Value, + from: &Caller, + ) -> Result { + self.ready(books)?; + { + let mut inner = self.inner(); + self.sweep(&mut inner); + let ok = self.allow_address( + &mut inner, + format!("register:{}", from.key), + REGISTER_PER_ADDRESS, + 3600, + ) && self.allow(&mut inner, "register".into(), REGISTER_TOTAL, 3600); + if !ok { + return Err(OauthError::new( + 429, + "temporarily_unavailable", + "too many registrations just now: try again later", + )); + } + } + let bad = |d: &str| OauthError::new(400, "invalid_client_metadata", d); + let Some(obj) = meta.as_object() else { + return Err(bad("the registration must be a JSON object")); + }; + let uris = obj + .get("redirect_uris") + .and_then(|v| v.as_array()) + .ok_or_else(|| { + OauthError::new(400, "invalid_redirect_uri", "redirect_uris is required") + })?; + if uris.is_empty() || uris.len() > MAX_REDIRECTS { + return Err(OauthError::new( + 400, + "invalid_redirect_uri", + format!("give between 1 and {MAX_REDIRECTS} redirect_uris"), + )); + } + let mut redirects = Vec::new(); + for u in uris { + let text = u.as_str().unwrap_or_default(); + if valid_redirect(text).is_none() { + return Err(OauthError::new( + 400, + "invalid_redirect_uri", + "a redirect address isn't one this server can send you back to", + )); + } + if !redirects.iter().any(|r| r == text) { + redirects.push(text.to_string()); + } + } + if !redirects_fit(&redirects) { + return Err(OauthError::new( + 400, + "invalid_redirect_uri", + "the redirect addresses together are too long", + )); + } + let method = obj + .get("token_endpoint_auth_method") + .and_then(|v| v.as_str()) + .unwrap_or("none"); + if !["none", "client_secret_post", "client_secret_basic"].contains(&method) { + return Err(bad("that token_endpoint_auth_method isn't supported")); + } + let name = clean( + obj.get("client_name") + .and_then(|v| v.as_str()) + .unwrap_or(""), + 100, + ); + let id = random("dcr_", 18)?; + let secret = if method == "none" { + None + } else { + Some(random("", 32)?) + }; + let now = self.now(); + { + let mut inner = self.inner(); + self.make_room(&mut inner)?; + inner.clients.insert( + id.clone(), + ClientRec { + id: id.clone(), + kind: Kind::Registered, + name: name.clone(), + redirects: redirects.clone(), + secret_sha256: secret.as_deref().map(sha_hex), + created: now, + last_seen: now, + used: false, + approved: false, + fetched: 0, + }, + ); + } + let mut out = serde_json::json!({ + "client_id": id, + "client_id_issued_at": now, + "client_name": name, + "redirect_uris": redirects, + "token_endpoint_auth_method": method, + "grant_types": ["authorization_code", "refresh_token"], + "response_types": ["code"], + }); + if let Some(s) = secret { + out["client_secret"] = s.into(); + out["client_secret_expires_at"] = 0.into(); + } + Ok(out) + } + + /// The remote state is loaded (and its file readable). + fn ready(&self, books: &Books) -> Result<(), OauthError> { + self.load(books) + .map_err(|e| OauthError::new(503, "temporarily_unavailable", e)) + } + + /// The client `id` names: registered, typed, or (an https address) a + /// metadata document, fetched and kept. `may_fetch` is false on the + /// token endpoint, which never reaches out to the internet: a document + /// is only ever fetched when a sign-in begins. A document we hold that + /// is past its time is used as it is when the fetch budget is spent or + /// the fetch fails: a vendor's host being slow doesn't lock the person + /// out. + pub(super) async fn resolve_client( + self: &Arc, + books: &Arc, + id: &str, + from: &Caller, + may_fetch: bool, + ) -> Result { + self.ready(books)?; + let now = self.now(); + let stale = { + let mut inner = self.inner(); + self.sweep(&mut inner); + match inner.clients.get(id) { + Some(c) if c.kind != Kind::Document || now - c.fetched < CIMD_TTL => { + return Ok(c.clone()); + } + Some(c) => Some(c.clone()), + None => None, + } + }; + let unknown = || OauthError::new(401, "invalid_client", "that client_id isn't known here"); + if !id.starts_with("https://") || !may_fetch { + return stale.ok_or_else(unknown); + } + // A document: fetched outside the lock, within limits (the door + // must not be a way to make us fetch the internet). + { + let mut inner = self.inner(); + if inner.failed_docs.get(id).is_some_and(|until| *until > now) { + return stale.ok_or_else(|| { + OauthError::new( + 401, + "invalid_client", + "that client's metadata document couldn't be used a moment ago", + ) + }); + } + if !self.allow(&mut inner, "fetch".into(), FETCH_PER_MINUTE, 60) + || !self.allow_address( + &mut inner, + format!("fetch:{}", from.key), + FETCH_PER_ADDRESS, + 60, + ) + { + return stale.ok_or_else(|| { + OauthError::new( + 429, + "temporarily_unavailable", + "too many new assistants just now: try again in a minute", + ) + }); + } + } + let docs = self.docs.read().unwrap_or_else(|e| e.into_inner()).clone(); + let fetched = docs.fetch(id).await; + let parsed = fetched.and_then(|bytes| cimd::parse(id, &bytes)); + let mut inner = self.inner(); + match parsed { + Ok((name, redirects)) => { + let old = inner.clients.get(id).cloned(); + if old.is_none() { + self.make_room(&mut inner)?; + } + let rec = ClientRec { + id: id.to_string(), + kind: Kind::Document, + name, + redirects, + secret_sha256: None, + created: old.as_ref().map_or(now, |o| o.created), + last_seen: now, + used: old.as_ref().is_some_and(|o| o.used), + approved: old.as_ref().is_some_and(|o| o.approved), + fetched: now, + }; + inner.clients.insert(id.to_string(), rec.clone()); + Ok(rec) + } + Err(why) => { + // A client we knew whose host is unreachable keeps working + // from what we hold; a new one is refused. + if let Some(c) = inner.clients.get(id) { + return Ok(c.clone()); + } + if inner.failed_docs.len() < 1000 { + inner.failed_docs.insert(id.to_string(), now + 60); + } + Err(OauthError::new(401, "invalid_client", why)) + } + } + } + + /// A typed client id and secret, made by the app for a product that + /// takes them (rule 2): its id and secret, shown this once. + pub(super) fn make_client( + &self, + books: &Books, + name: &str, + redirect_uris: &[String], + ) -> Result<(String, String), String> { + self.load(books)?; + let name = clean(name, 60); + if name.is_empty() { + return Err("give the assistant a name".into()); + } + if redirect_uris.is_empty() || redirect_uris.len() > MAX_REDIRECTS { + return Err(format!( + "give between 1 and {MAX_REDIRECTS} addresses to send the assistant back to" + )); + } + for u in redirect_uris { + if valid_redirect(u).is_none() { + return Err("one of the addresses can't be used to send an assistant back".into()); + } + } + if !redirects_fit(redirect_uris) { + return Err("the addresses together are too long".into()); + } + let id = random("wbc_", 12).map_err(|e| e.description)?; + let secret = random("", 32).map_err(|e| e.description)?; + { + let mut inner = self.inner(); + if inner + .clients + .values() + .filter(|c| c.kind == Kind::Typed) + .count() + >= MAX_MANUAL + { + return Err("there are too many typed client ids; revoke some first".into()); + } + self.make_room(&mut inner).map_err(|e| e.description)?; + let now = self.now(); + inner.clients.insert( + id.clone(), + ClientRec { + id: id.clone(), + kind: Kind::Typed, + name, + redirects: redirect_uris.to_vec(), + secret_sha256: Some(sha_hex(&secret)), + created: now, + last_seen: now, + used: false, + // The owner made it: nothing here is a stranger's. + approved: true, + fetched: 0, + }, + ); + } + self.save()?; + Ok((id, secret)) + } + + // ---- authorize ----------------------------------------------------------- + + /// Which company a `resource` names: its path under the one issuer. + fn book_of_resource(&self, issuer: &str, resource: &str) -> Option { + let rest = resource.strip_prefix(issuer)?; + let rest = rest.strip_suffix('/').unwrap_or(rest); + let book = rest.strip_prefix("/b/")?.strip_suffix("/mcp")?; + (BookId::parse(book).is_ok()).then(|| book.to_string()) + } + + /// Make room for one more waiting request from `key`, without turning + /// the new one away (a few addresses must not be able to fill the + /// person's window): an address at its own limit gives up its oldest + /// waiting request; a full table takes the oldest waiting request of + /// the address with the most waiting. Those given up are told so. + fn make_pending_room(&self, inner: &mut Inner, key: &str) { + let waiting = |p: &Pending| matches!(p.settled, Settled::Waiting); + loop { + let mine = inner + .pending + .iter() + .position(|p| waiting(p) && p.from_key == key); + let mine_count = inner + .pending + .iter() + .filter(|p| waiting(p) && p.from_key == key) + .count(); + if mine_count >= MAX_PENDING_PER_ADDRESS { + if let Some(at) = mine { + inner.pending[at].settled = Settled::Crowded; + } + continue; + } + let total = inner.pending.iter().filter(|p| waiting(p)).count(); + if total < MAX_PENDING { + break; + } + // The address with the most waiting; of equals, the one whose + // oldest request is the oldest. + let mut counts: Vec<(String, usize, usize)> = Vec::new(); + for (at, p) in inner.pending.iter().enumerate().filter(|(_, p)| waiting(p)) { + match counts.iter_mut().find(|(k, _, _)| *k == p.from_key) { + Some(slot) => slot.1 += 1, + None => counts.push((p.from_key.clone(), 1, at)), + } + } + let Some((_, _, at)) = counts + .into_iter() + .max_by_key(|(_, n, first)| (*n, std::cmp::Reverse(*first))) + else { + break; + }; + inner.pending[at].settled = Settled::Crowded; + } + // What was given up and is waiting to be read is bounded too. + let keep = MAX_PENDING * 4; + while inner.pending.len() > keep { + match inner.pending.iter().position(|p| !waiting(p)) { + Some(at) => { + inner.pending.remove(at); + } + None => break, + } + } + } + + /// A sign-in begins (`GET /authorize`). Either an answer to send the + /// browser, or the request is parked: always parked, for the person to + /// decide in the window (D-90). + pub(super) async fn authorize( + self: &Arc, + books: &Arc, + door: &Door, + q: &BTreeMap, + from: &Caller, + ) -> Authorize { + { + let mut inner = self.inner(); + if !self.allow_address( + &mut inner, + format!("authorize:{}", from.key), + AUTHORIZE_PER_ADDRESS, + 600, + ) { + return Authorize::Page( + 429, + pages::problem("Too many tries", "Wait a few minutes, then try again."), + ); + } + } + let no_client = || { + Authorize::Page( + 400, + pages::problem( + "This assistant can't sign in", + "Wanderbooks doesn't know the assistant that sent you here. Start again from the assistant.", + ), + ) + }; + let Some(client_id) = q.get("client_id").filter(|s| !s.is_empty()) else { + return no_client(); + }; + let Ok(client) = self.resolve_client(books, client_id, from, true).await else { + return no_client(); + }; + // The redirect address: exactly one the client gave. Until it is + // proven, an error is a page here, never a redirect (no open + // redirect). + let redirect = match q.get("redirect_uri") { + Some(r) if client.redirects.iter().any(|x| x == r) => r.clone(), + None if client.redirects.len() == 1 => client.redirects[0].clone(), + _ => { + return Authorize::Page( + 400, + pages::problem( + "This assistant can't sign in", + "The address it asked to be sent back to isn't one it registered. Start again from the assistant.", + ), + ); + } + }; + let state = q.get("state").cloned(); + // A client nobody ever approved is anyone's: its error is a page, not + // a redirect to whatever address it registered (no open redirect + // through registration). One the person has approved before is + // sent its errors, as the specification has it. + let fail = |code: &str, why: &str| { + if client.approved { + Authorize::Redirect(error_redirect( + &redirect, + state.as_deref(), + code, + why, + &door.issuer, + )) + } else { + Authorize::Page( + 400, + pages::problem( + "This assistant can't sign in", + "Its request wasn't one Wanderbooks can take. Start again from the assistant.", + ), + ) + } + }; + if state.as_ref().is_some_and(|s| s.len() > 512) { + return fail("invalid_request", "state is too long"); + } + if q.get("response_type").map(String::as_str) != Some("code") { + return fail("unsupported_response_type", "response_type must be code"); + } + let challenge = q.get("code_challenge").cloned().unwrap_or_default(); + if q.get("code_challenge_method").map(String::as_str) != Some("S256") + || challenge.len() != 43 + || !challenge + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') + { + return fail( + "invalid_request", + "PKCE with code_challenge_method=S256 is required", + ); + } + let book = match q.get("resource") { + Some(r) => match self.book_of_resource(&door.issuer, r) { + Some(b) => b, + None => { + return fail( + "invalid_target", + "resource isn't one company's address here", + ); + } + }, + None => { + // A product that sends no resource: the only company on + // offer, if there is only one. + match self.only_open_book(books) { + Some(only) => only, + None => return fail("invalid_target", "say which company with resource"), + } + } + }; + if !self.is_allowed(&book) || !super::book_is_open(books, &book) { + return fail( + "invalid_target", + "those books aren't open to web assistants right now", + ); + } + let wants_post = q + .get("scope") + .is_some_and(|s| s.split_whitespace().any(|w| w == "books:post")); + let name = shown_name(&client); + let host = redirect_host(&redirect); + let now = self.now(); + // Every sign-in is asked in the window, always (D-90): an approval + // is never reused, however well the product is known, because who + // the product is is public and whose account it is is not known. + let (wait, code) = { + let mut inner = self.inner(); + self.sweep(&mut inner); + let (Ok(id), Ok(wait)) = (random("p_", 9), random("w_", 24)) else { + return fail("server_error", "no id could be made"); + }; + self.make_pending_room(&mut inner, &from.key); + let code = match match_code(&inner) { + Ok(c) => c, + Err(_) => return fail("temporarily_unavailable", "busy"), + }; + if let Some(c) = inner.clients.get_mut(&client.id) { + c.used = true; + c.last_seen = now; + } + inner.pending.push(Pending { + id, + wait: wait.clone(), + client: client.id.clone(), + client_name: name.clone(), + known_host: is_vendor_host(&redirect), + code: code.clone(), + redirect: redirect.clone(), + state: state.clone(), + challenge, + book: book.clone(), + issuer: door.issuer.clone(), + from: from.shown.clone(), + from_key: from.key.clone(), + wants_post, + created: now, + exp: now + PENDING_TTL, + settled: Settled::Waiting, + }); + (wait, code) + }; + let company = super::company_name(books, &book); + Authorize::Page(200, pages::waiting(&host, &name, &company, &code, &wait)) + } + + /// The page's next look (`GET /authorize/wait/{wait}`): still waiting, + /// or sent back with a code, or sent back refused. Read once. + pub(super) fn wait(&self, books: &Books, wait: &str) -> Authorize { + let now = self.now(); + let mut inner = self.inner(); + self.sweep(&mut inner); + let Some(at) = inner.pending.iter().position(|p| p.wait == wait) else { + return Authorize::Page( + 410, + pages::problem("This request has ended", "Start again from your assistant."), + ); + }; + if matches!(inner.pending[at].settled, Settled::Waiting) && inner.pending[at].exp <= now { + inner.pending[at].settled = Settled::Refused; + } + enum Seen { + Waiting, + Allowed(String), + Refused, + Crowded, + } + let seen = match &inner.pending[at].settled { + Settled::Waiting => Seen::Waiting, + Settled::Allowed(code) => Seen::Allowed(code.clone()), + Settled::Refused => Seen::Refused, + Settled::Crowded => Seen::Crowded, + }; + match seen { + Seen::Waiting => { + let p = &inner.pending[at]; + let company = super::company_name(books, &p.book); + Authorize::Page( + 200, + pages::waiting( + &redirect_host(&p.redirect), + &p.client_name, + &company, + &p.code, + wait, + ), + ) + } + Seen::Allowed(code) => { + let p = inner.pending.remove(at); + Authorize::Redirect(success_redirect( + &p.redirect, + p.state.as_deref(), + &code, + &p.issuer, + )) + } + Seen::Refused | Seen::Crowded => { + let crowded = matches!(seen, Seen::Crowded); + let p = inner.pending.remove(at); + let (error, why) = if crowded { + ( + "temporarily_unavailable", + "too many assistants were waiting: try again", + ) + } else if p.exp <= now { + ("access_denied", "nobody allowed it in time") + } else { + ("access_denied", "the owner didn't allow it") + }; + Authorize::Redirect(error_redirect( + &p.redirect, + p.state.as_deref(), + error, + why, + &p.issuer, + )) + } + } + } + + #[allow(clippy::too_many_arguments)] + fn new_code( + &self, + inner: &mut Inner, + client: &str, + approval: &Approval, + issuer: &str, + redirect: &str, + challenge: &str, + family: Option, + ) -> Result { + if inner.codes.len() >= MAX_CODES { + let now = self.now(); + inner.codes.retain(|_, c| c.exp > now); + if inner.codes.len() >= MAX_CODES { + return Err(OauthError::new(503, "temporarily_unavailable", "busy")); + } + } + let code = random("wbcode_", 32)?; + let family = match family { + Some(f) => f, + None => random("fam_", 12)?, + }; + inner.codes.insert( + sha_hex(&code), + Code { + client: client.to_string(), + approval: approval.id.clone(), + family, + book: approval.book.clone(), + issuer: issuer.to_string(), + redirect: redirect.to_string(), + challenge: challenge.to_string(), + exp: self.now() + CODE_TTL, + }, + ); + Ok(code) + } + + // ---- the person decides (admin socket only) -------------------------- + + pub(super) fn pending_list(&self) -> Vec { + let now = self.now(); + let mut inner = self.inner(); + self.sweep(&mut inner); + inner + .pending + .iter() + .filter(|p| matches!(p.settled, Settled::Waiting) && p.exp > now) + .map(|p| PendingInfo { + id: p.id.clone(), + book: p.book.clone(), + client_name: p.client_name.clone(), + known_host: p.known_host, + code: p.code.clone(), + redirect: p.redirect.clone(), + redirect_host: redirect_host(&p.redirect), + from: p.from.clone(), + wants_post: p.wants_post, + age_secs: (now - p.created).max(0) as u64, + expires_in_secs: (p.exp - now).max(0) as u64, + }) + .collect() + } + + /// The person's answer to one waiting request (INVARIANT 5): `post` + /// raises it beyond read and draft. + pub(super) fn decide( + &self, + books: &Books, + id: &str, + approve: bool, + post: bool, + ) -> Result<(String, Option), String> { + self.load(books)?; + let door = self.door().ok_or("web assistants are switched off")?; + let now = self.now(); + let (book, client_id, redirect, challenge) = { + let mut inner = self.inner(); + self.sweep(&mut inner); + let p = inner + .pending + .iter_mut() + .find(|p| p.id == id && matches!(p.settled, Settled::Waiting) && p.exp > now) + .ok_or("that request isn't waiting any more: it was decided, or it ran out")?; + if !approve { + p.settled = Settled::Refused; + return Ok(("Refused. The assistant was told no.".into(), None)); + } + ( + p.book.clone(), + p.client.clone(), + p.redirect.clone(), + p.challenge.clone(), + ) + }; + if !self.is_allowed(&book) || !super::book_is_open(books, &book) { + return Err("those books aren't open to web assistants now".into()); + } + let client = self + .inner() + .clients + .get(&client_id) + .cloned() + .ok_or("that assistant's registration ran out: ask it to start again")?; + // Every Allow is a new approval, with exactly the permissions + // ticked now and nothing carried over from an older one (D-90): an + // older connection of the same product stays as it is, to be + // revoked or kept on its own. + let approval = self.make_approval(books, &book, &client, &redirect, post)?; + if let Some(c) = self.inner().clients.get_mut(&client_id) { + // Now a client the person has approved: kept on disk with its + // approval, and sent its errors as redirects. + c.approved = true; + } + { + let mut inner = self.inner(); + let code = self + .new_code( + &mut inner, + &client_id, + &approval, + &door.issuer, + &redirect, + &challenge, + None, + ) + .map_err(|e| e.description)?; + if let Some(p) = inner.pending.iter_mut().find(|p| p.id == id) { + p.settled = Settled::Allowed(code); + } + if let Some(a) = inner.approvals.get_mut(&approval.id) { + a.last_used = now; + } + } + self.save()?; + let info = self.approval_info(books, &approval); + Ok(( + format!("Allowed. {} can reach these books.", approval.label), + info, + )) + } + + /// A new approval, and the principals' token that carries it: always + /// a new id and a new token, never the old one made over. + fn make_approval( + &self, + books: &Books, + book: &str, + client: &ClientRec, + redirect: &str, + post: bool, + ) -> Result { + let book_id = BookId::parse(book).map_err(|e| e.to_string())?; + { + let inner = self.inner(); + if inner.approvals.len() >= MAX_APPROVALS { + return Err("there are too many connections: revoke some first".into()); + } + } + let label = label_of(client, redirect); + let base = token_slug(&redirect_host(redirect)); + let taken: BTreeSet = super::token_names(books, book); + let name = (1..) + .map(|n| { + if n == 1 { + base.clone() + } else { + format!("{base}-{n}") + } + }) + .find(|n| n.len() <= 32 && !taken.contains(n)) + .ok_or("no name is free for this connection")?; + let token = super::make_token(books, &book_id, &name, scopes_for(post), false)?; + let now = self.now(); + let approval = Approval { + id: random("apr_", 9).map_err(|e| e.description)?, + book: book.to_string(), + label, + token_name: name, + token_id: token.id, + created: now, + last_used: now, + }; + self.inner() + .approvals + .insert(approval.id.clone(), approval.clone()); + Ok(approval) + } + + /// Raise or lower what an approval may do (rule 10): the token that + /// carries it is replaced by one with the new scopes, and the approval + /// names the new one, as one step. The door's lock is held across it, so + /// no call lands between the two (every call is let in under that lock); + /// and the check that the connection is live is made in the same hold of + /// the principals as the replacement, so a revoke that came first stays + /// a revoke, and one that comes after reaches the new token (see + /// [`Remote::successor_of`]). + pub(super) fn set_post( + &self, + books: &Books, + approval_id: &str, + post: bool, + ) -> Result { + self.load(books)?; + let approval = { + let mut inner = self.inner(); + let mut approval = inner + .approvals + .get(approval_id) + .cloned() + .ok_or("there is no such connection")?; + let book_id = BookId::parse(&approval.book).map_err(|e| e.to_string())?; + let token = super::replace_token_if_live( + books, + &book_id, + &approval.token_name, + &approval.token_id, + scopes_for(post), + )?; + if inner.swapped.len() >= MAX_SWAPPED { + inner.swapped.clear(); + } + inner + .swapped + .insert(approval.token_id.clone(), token.id.clone()); + approval.token_id = token.id; + inner + .approvals + .insert(approval.id.clone(), approval.clone()); + approval + }; + self.save()?; + Ok(approval) + } + + /// The token that took the place of `old_id` when an approval's + /// permissions were raised or lowered, if one did: a revoke that named + /// the old one a moment too late is for this one (it wins). + pub(super) fn successor_of(&self, old_id: &str) -> Option { + let inner = self.inner(); + // A connection raised and lowered several times: follow the chain + // to the token that stands now. + let mut at = inner.swapped.get(old_id)?; + for _ in 0..64 { + match inner.swapped.get(at) { + Some(next) => at = next, + None => break, + } + } + Some(at.clone()) + } + + /// The principals' token `token_id` is gone (revoked, or made over): + /// what it carried goes with it at once, not when a list is next read + /// (D-90): the approval, its refresh tokens, its access tokens, its + /// codes, and a key if it was one. + pub(super) fn token_gone(&self, token_id: &str) { + { + let mut inner = self.inner(); + let gone: Vec = inner + .approvals + .values() + .filter(|a| a.token_id == token_id) + .map(|a| a.id.clone()) + .collect(); + let had_key = inner.keys.remove(token_id).is_some(); + if gone.is_empty() && !had_key { + return; + } + for id in &gone { + inner.approvals.remove(id); + } + inner.refresh.retain(|_, r| !gone.contains(&r.approval)); + inner.access.retain(|_, r| !gone.contains(&r.approval)); + inner.codes.retain(|_, c| !gone.contains(&c.approval)); + } + let _ = self.save(); + } + + fn approval_info(&self, books: &Books, approval: &Approval) -> Option { + let token = super::live_token( + books, + &approval.book, + &approval.token_name, + &approval.token_id, + )?; + Some(ApprovalInfo { + id: approval.id.clone(), + book: approval.book.clone(), + label: approval.label.clone(), + token_id: token.id.clone(), + token_name: token.name.clone(), + may_post: token.scopes.contains(&Scope::Post), + created: approval.created, + last_used: (approval.last_used > approval.created).then_some(approval.last_used), + }) + } + + /// The live approvals (those whose token still stands), for `book` or + /// all; the ones revoked are forgotten, with their refresh tokens. + pub(super) fn approvals(&self, books: &Books, book: Option<&str>) -> Vec { + let _ = self.load(books); + let all: Vec = self.inner().approvals.values().cloned().collect(); + let mut gone = Vec::new(); + let mut out = Vec::new(); + for a in all { + match self.approval_info(books, &a) { + Some(info) => { + if book.is_none_or(|b| b == a.book) { + out.push(info); + } + } + None => gone.push(a.id), + } + } + if !gone.is_empty() { + let mut inner = self.inner(); + for id in &gone { + inner.approvals.remove(id); + } + inner.refresh.retain(|_, r| !gone.contains(&r.approval)); + inner.access.retain(|_, r| !gone.contains(&r.approval)); + drop(inner); + let _ = self.save(); + } + out + } + + /// A key for a product that takes only a key (rule 9): a token of the + /// books' principals the remote door accepts, read and draft (and + /// post if raised), shown once. + pub(super) fn make_key( + &self, + books: &Books, + book: &str, + name: &str, + post: bool, + ) -> Result<(Token, String), String> { + self.load(books)?; + let book_id = BookId::parse(book).map_err(|e| e.to_string())?; + if !super::book_is_open(books, book) { + return Err(format!("there are no open books called {book}")); + } + // A key that was revoked frees its place: only the keys whose + // token still stands are counted. + { + let live = super::live_token_ids(books); + let mut inner = self.inner(); + inner.keys.retain(|id, _| live.contains(id)); + if inner.keys.len() >= MAX_KEYS { + return Err("there are too many keys; revoke some first".into()); + } + } + let name = format!("key-{}", token_slug(name).trim_start_matches("web-")); + let (token, text) = super::make_token_with_text(books, &book_id, &name, scopes_for(post))?; + self.inner().keys.insert( + token.id.clone(), + KeyRec { + token_id: token.id.clone(), + book: book.to_string(), + created: self.now(), + }, + ); + self.save()?; + Ok((token, text)) + } + + // ---- the token endpoint ------------------------------------------------ + + /// A token request (`POST /token`): `form` is its parameters, `basic` + /// the client credentials of an Authorization header, if any. Nothing + /// is ever fetched from the internet here. + pub(super) async fn token( + self: &Arc, + books: &Arc, + door: &Door, + form: &BTreeMap, + basic: Option<(String, String)>, + from: &Caller, + ) -> Result { + let (client_id, secret) = match basic { + Some((id, s)) => (Some(id), Some(s)), + None => ( + form.get("client_id").cloned(), + form.get("client_secret").cloned(), + ), + }; + let Some(client_id) = client_id.filter(|s| !s.is_empty()) else { + return Err(OauthError::new(401, "invalid_client", "no client_id")); + }; + // The address's limit first, by what the stranger can't choose; the + // client's own after it is known, so a made-up client id fills no + // table. + { + let mut inner = self.inner(); + if !self.allow_address( + &mut inner, + format!("token:{}", from.key), + TOKEN_PER_ADDRESS, + 60, + ) { + return Err(OauthError::new( + 429, + "temporarily_unavailable", + "too many token requests: slow down", + )); + } + } + let grant = form.get("grant_type").map(String::as_str).unwrap_or(""); + let client = match self.resolve_client(books, &client_id, from, false).await { + Ok(c) => c, + Err(e) if grant == "refresh_token" && e.error == "invalid_client" => { + return Err(OauthError::new( + 400, + "invalid_grant", + "that refresh token isn't one this server knows", + )); + } + Err(e) => return Err(e), + }; + { + let mut inner = self.inner(); + if !self.allow( + &mut inner, + format!("token:{client_id}"), + TOKEN_PER_CLIENT, + 60, + ) { + return Err(OauthError::new( + 429, + "temporarily_unavailable", + "too many token requests: slow down", + )); + } + } + // A client with a secret proves it, in constant time, before + // anything is consumed. + if let Some(want) = &client.secret_sha256 { + use subtle::ConstantTimeEq; + let given = sha_hex(secret.as_deref().unwrap_or("")); + let same: bool = given.as_bytes().ct_eq(want.as_bytes()).into(); + if secret.is_none() || !same { + return Err(OauthError::new( + 401, + "invalid_client", + "client authentication failed", + )); + } + } + if let Some(r) = form.get("resource") + && self.book_of_resource(&door.issuer, r).is_none() + { + return Err(OauthError::new( + 400, + "invalid_target", + "resource isn't one company's address here", + )); + } + match grant { + "authorization_code" => self.exchange_code(books, door, &client, form).await, + "refresh_token" => self.refresh(books, door, &client, form).await, + _ => Err(OauthError::new( + 400, + "unsupported_grant_type", + "grant_type must be authorization_code or refresh_token", + )), + } + } + + async fn exchange_code( + self: &Arc, + books: &Arc, + door: &Door, + client: &ClientRec, + form: &BTreeMap, + ) -> Result { + let bad = |d: &str| OauthError::new(400, "invalid_grant", d); + let given = form.get("code").cloned().unwrap_or_default(); + let key = sha_hex(&given); + let now = self.now(); + let (taken, replay) = { + let mut inner = self.inner(); + self.sweep(&mut inner); + let taken = inner.codes.remove(&key); + // A code used before: whoever holds what it made may be a + // thief; end that family (RFC 9700 4.3). + let replay = if taken.is_none() { + inner.used_codes.get(&key).map(|(f, _)| f.clone()) + } else { + None + }; + if let Some(family) = &replay { + inner.refresh.retain(|_, r| r.family != *family); + inner.access.retain(|_, a| a.family != *family); + } + (taken, replay) + }; + let Some(code) = taken else { + if replay.is_some() { + let _ = self.save_async().await; + } + return Err(bad("that code is invalid, used, or has expired")); + }; + // Single use: remembered, so a replay is seen. + { + let mut inner = self.inner(); + if inner.used_codes.len() < MAX_CODES * 2 { + inner + .used_codes + .insert(key, (code.family.clone(), now + USED_CODE_KEPT)); + } + } + if code.exp <= now || code.client != client.id { + return Err(bad("that code is invalid, used, or has expired")); + } + if code.issuer != door.issuer { + return Err(bad("that code was made for another address")); + } + if let Some(r) = form.get("redirect_uri") + && *r != code.redirect + { + return Err(bad("redirect_uri isn't the one of the sign-in")); + } + let verifier = form.get("code_verifier").cloned().unwrap_or_default(); + let ok_shape = (43..=128).contains(&verifier.len()) + && verifier + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"-._~".contains(&b)); + let computed = base64::engine::general_purpose::URL_SAFE_NO_PAD + .encode(Sha256::digest(verifier.as_bytes())); + { + use subtle::ConstantTimeEq; + let same: bool = computed.as_bytes().ct_eq(code.challenge.as_bytes()).into(); + if !ok_shape || !same { + return Err(bad("the PKCE verifier doesn't match")); + } + } + let approval = self + .inner() + .approvals + .get(&code.approval) + .cloned() + .filter(|a| a.book == code.book) + .ok_or_else(|| bad("that connection no longer exists"))?; + if !super::token_is_live( + books, + &approval.book, + &approval.token_name, + &approval.token_id, + ) { + return Err(bad("that connection was revoked")); + } + self.issue(books, door, client, &approval, &code.family, None) + .await + } + + async fn refresh( + self: &Arc, + books: &Arc, + door: &Door, + client: &ClientRec, + form: &BTreeMap, + ) -> Result { + let bad = |d: &str| OauthError::new(400, "invalid_grant", d); + let given = form.get("refresh_token").cloned().unwrap_or_default(); + let key = sha_hex(&given); + // The check that the refresh token is good and unused, and its + // marking as used, are one hold of the lock (with the minting of + // what replaces it): two refreshes at once can't both succeed. A + // second use of it is a reuse, and ends the whole family. + let outcome = { + let mut inner = self.inner(); + self.sweep(&mut inner); + match inner.refresh.get(&key).cloned() { + None => Err(( + bad("that refresh token is invalid, used, or has expired"), + false, + )), + Some(rec) if rec.used => { + // Used twice: the family is over (RFC 9700 4.14). + inner.refresh.retain(|_, r| r.family != rec.family); + inner.access.retain(|_, a| a.family != rec.family); + Err(( + bad("that refresh token was already used: sign in again"), + true, + )) + } + Some(rec) if rec.client != client.id => Err(( + bad("that refresh token belongs to another assistant"), + false, + )), + Some(rec) if rec.issuer != door.issuer => Err(( + bad("that refresh token was made for another address"), + false, + )), + Some(rec) => match inner.approvals.get(&rec.approval).cloned() { + None => Err((bad("that connection no longer exists"), false)), + Some(approval) + if !super::token_is_live( + books, + &approval.book, + &approval.token_name, + &approval.token_id, + ) => + { + Err((bad("that connection was revoked"), false)) + } + Some(approval) => self + .mint( + &mut inner, + door, + client, + &approval, + &rec.family, + Some(key.clone()), + ) + .map(|minted| (approval, minted)) + .map_err(|e| (e, false)), + }, + } + }; + match outcome { + Ok((approval, minted)) => self.finish(books, &approval, minted).await, + Err((e, ended_family)) => { + if ended_family { + let _ = self.save_async().await; + } + Err(e) + } + } + } + + /// Mint an access token and a refresh token under `approval`, and (a + /// refresh) retire the refresh token it came from, all with the lock + /// held by the caller. + #[allow(clippy::too_many_arguments)] + fn mint( + &self, + inner: &mut Inner, + door: &Door, + client: &ClientRec, + approval: &Approval, + family: &str, + retire: Option, + ) -> Result { + let access = random("wba_", 32)?; + let refresh = random("wbr_", 32)?; + let now = self.now(); + if inner.access.len() >= MAX_ACCESS { + inner.access.retain(|_, a| a.exp > now); + if inner.access.len() >= MAX_ACCESS { + return Err(OauthError::new(503, "temporarily_unavailable", "busy")); + } + } + // The family's count of one approval is bounded: the one used + // longest ago goes. + let mut families: Vec<(String, i64)> = Vec::new(); + for r in inner.refresh.values().filter(|r| r.approval == approval.id) { + match families.iter_mut().find(|(f, _)| *f == r.family) { + Some(slot) => slot.1 = slot.1.max(r.created), + None => families.push((r.family.clone(), r.created)), + } + } + if !families.iter().any(|(f, _)| f == family) && families.len() >= MAX_FAMILIES { + families.sort_by_key(|(_, at)| *at); + let drop_family = families[0].0.clone(); + inner.refresh.retain(|_, r| r.family != drop_family); + } + if inner.refresh.len() >= MAX_REFRESH { + inner.refresh.retain(|_, r| r.exp > now); + if inner.refresh.len() >= MAX_REFRESH { + return Err(OauthError::new(503, "temporarily_unavailable", "busy")); + } + } + let new_hash = sha_hex(&refresh); + inner.refresh.insert( + new_hash.clone(), + RefreshRec { + hash: new_hash.clone(), + family: family.to_string(), + approval: approval.id.clone(), + client: client.id.clone(), + issuer: door.issuer.clone(), + exp: now + REFRESH_TTL, + used: false, + created: now, + }, + ); + if let Some(old) = &retire + && let Some(r) = inner.refresh.get_mut(old) + { + r.used = true; + // A used token is kept to see a replay, only as long as it + // would have lived, and no longer than a week. + r.exp = r.exp.min(now + 7 * 24 * 3600); + } + // The families keep at most two used tokens each. + let mut used: Vec<(String, i64)> = inner + .refresh + .values() + .filter(|r| r.family == family && r.used) + .map(|r| (r.hash.clone(), r.created)) + .collect(); + if used.len() > 2 { + used.sort_by_key(|(_, at)| *at); + for (h, _) in &used[..used.len() - 2] { + inner.refresh.remove(h); + } + } + inner.access.insert( + sha_hex(&access), + AccessRec { + approval: approval.id.clone(), + family: family.to_string(), + book: approval.book.clone(), + issuer: door.issuer.clone(), + exp: now + ACCESS_TTL, + }, + ); + if let Some(a) = inner.approvals.get_mut(&approval.id) { + a.last_used = now; + } + Ok(Minted { + access, + refresh, + new_hash, + undo: retire, + }) + } + + /// [`Remote::mint`] under a hold of its own, then [`Remote::finish`]. + async fn issue( + self: &Arc, + books: &Arc, + door: &Door, + client: &ClientRec, + approval: &Approval, + family: &str, + retire: Option, + ) -> Result { + let minted = { + let mut inner = self.inner(); + self.mint(&mut inner, door, client, approval, family, retire)? + }; + self.finish(books, approval, minted).await + } + + /// Keep what was minted before it is given (a refresh token this server + /// forgot would sign the person out): if it can't be kept, nothing was + /// made. Then the answer. + async fn finish( + self: &Arc, + books: &Arc, + approval: &Approval, + minted: Minted, + ) -> Result { + let Minted { + access, + refresh, + new_hash, + undo, + } = minted; + if let Err(e) = self.save_async().await { + let mut inner = self.inner(); + inner.refresh.remove(&new_hash); + inner.access.remove(&sha_hex(&access)); + if let Some(old) = undo + && let Some(r) = inner.refresh.get_mut(&old) + { + r.used = false; + } + return Err(OauthError::new(500, "server_error", e)); + } + let scope = super::live_token( + books, + &approval.book, + &approval.token_name, + &approval.token_id, + ) + .map(|t| { + t.scopes + .iter() + .map(|s| s.as_str()) + .collect::>() + .join(" ") + }) + .unwrap_or_default(); + Ok(serde_json::json!({ + "access_token": access, + "token_type": "Bearer", + "expires_in": ACCESS_TTL, + "refresh_token": refresh, + "scope": scope, + })) + } + + // ---- the door's check -------------------------------------------------- + + /// The token a request carries, if it is good here (INVARIANTS 3, 6, + /// 9): an access token made by this door, or a key the app made. + pub(super) fn authenticate( + &self, + books: &Books, + headers: &axum::http::HeaderMap, + ) -> Result { + let denied = |code: &'static str, why: &str, invalid: bool| Denied { + code, + why: why.to_string(), + invalid_token: invalid, + }; + let presented = headers + .get(axum::http::header::AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.split_once(' ')) + .filter(|(scheme, _)| scheme.eq_ignore_ascii_case("bearer")) + .map(|(_, token)| token.trim()); + let Some(presented) = presented.filter(|t| !t.is_empty()) else { + return Err(denied( + crate::access::UNAUTHORIZED, + "sign in to reach these books", + false, + )); + }; + let door = self + .door() + .ok_or_else(|| denied(crate::access::UNAUTHORIZED, "web assistants are off", false))?; + let now = self.now(); + let mut token = if presented.starts_with("wba_") { + let (approval, rec) = { + let mut inner = self.inner(); + self.sweep(&mut inner); + let rec = inner.access.get(&sha_hex(presented)).ok_or_else(|| { + denied( + crate::access::UNAUTHORIZED, + "that token isn't one these books know, or it has ended", + true, + ) + })?; + if rec.exp <= now { + return Err(denied( + crate::access::UNAUTHORIZED, + "that token has expired", + true, + )); + } + let rec = (rec.approval.clone(), rec.issuer.clone(), rec.book.clone()); + let approval = inner.approvals.get(&rec.0).cloned(); + (approval, rec) + }; + if rec.1 != door.issuer { + return Err(denied( + crate::access::UNAUTHORIZED, + "that token was made for another address", + true, + )); + } + let approval = approval.ok_or_else(|| { + denied( + crate::access::UNAUTHORIZED, + "that connection no longer exists", + true, + ) + })?; + // The company the token was made for is the approval's, always. + if rec.2 != approval.book { + return Err(denied( + crate::access::UNAUTHORIZED, + "that token isn't for these books", + true, + )); + } + let token = super::live_token( + books, + &approval.book, + &approval.token_name, + &approval.token_id, + ) + .ok_or_else(|| { + denied( + crate::access::UNAUTHORIZED, + "that connection was revoked", + true, + ) + })?; + if let Some(a) = self.inner().approvals.get_mut(&approval.id) { + a.last_used = now; + } + token + } else { + // A key the app made (rule 9): a principals' token, and only + // one of those, never an agent's own key for the local socket. + let guard = books.principals.read().unwrap_or_else(|e| e.into_inner()); + let found = guard + .as_ref() + .ok() + .and_then(|p| p.check(presented)) + .cloned(); + drop(guard); + let token = found.ok_or_else(|| { + denied( + crate::access::UNAUTHORIZED, + "that token isn't one these books know, or it was revoked", + true, + ) + })?; + if !self.inner().keys.contains_key(&token.id) { + return Err(denied( + crate::access::UNAUTHORIZED, + "that key isn't one for web assistants", + true, + )); + } + token + }; + // Never the access record, whatever the token says. + token.scopes.remove(&Scope::Admin); + Ok(token) + } + + /// The approval a token belongs to, for the call limit. + pub(super) fn call_key(&self, token: &Token) -> String { + format!("call:{}", token.id) + } +} + +/// What `/authorize` and its waiting page answer. +pub(super) enum Authorize { + /// An HTML page, with its status. + Page(u16, String), + /// A 302 to this address. + Redirect(String), +} + +fn with_query(base: &str, params: &[(&str, &str)]) -> String { + let mut url = match reqwest::Url::parse(base) { + Ok(u) => u, + Err(_) => return base.to_string(), + }; + { + let mut q = url.query_pairs_mut(); + for (k, v) in params { + q.append_pair(k, v); + } + } + url.to_string() +} + +fn success_redirect(redirect: &str, state: Option<&str>, code: &str, issuer: &str) -> String { + let mut params = vec![("code", code)]; + if let Some(s) = state { + params.push(("state", s)); + } + params.push(("iss", issuer)); + with_query(redirect, ¶ms) +} + +fn error_redirect( + redirect: &str, + state: Option<&str>, + error: &str, + why: &str, + issuer: &str, +) -> String { + let mut params = vec![("error", error), ("error_description", why)]; + if let Some(s) = state { + params.push(("state", s)); + } + params.push(("iss", issuer)); + with_query(redirect, ¶ms) +} diff --git a/crates/ledger-mcp/src/local/remote/pages.rs b/crates/ledger-mcp/src/local/remote/pages.rs new file mode 100644 index 00000000..92840760 --- /dev/null +++ b/crates/ledger-mcp/src/local/remote/pages.rs @@ -0,0 +1,109 @@ +//! The two pages a person's browser sees during a sign-in: "look at +//! Wanderbooks", and a plain problem. Plain words; the person may not know +//! what any of this is called, and the word is "assistant". +//! +//! ```text +//! GOAL: the browser page of a sign-in never approves anything and never +//! carries text a stranger wrote unescaped. +//! SOURCE: WB-remote-5 (approval is the person's, in the app's window); +//! plan/p15-app-and-relay.md 3.3, D-83. +//! INVARIANTS: +//! 1. Every piece of text from outside (a client's name, a company's +//! name) is HTML-escaped; the page has no script, no form, no link +//! and no button that approves: it says to look at Wanderbooks and +//! looks again by itself (a refresh), until the person decides. +//! 2. The page shows the request's own short code, for the person to match +//! with the window's card; it never says a request is a known product. +//! 3. The page's only address is the relative one of the waiting +//! request; nothing is built from the request's Host. +//! ``` + +/// Escape text for HTML. +pub fn esc(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + for c in text.chars() { + match c { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '"' => out.push_str("""), + '\'' => out.push_str("'"), + c => out.push(c), + } + } + out +} + +fn shell(title: &str, refresh: Option<&str>, body: &str) -> String { + let head = refresh + .map(|u| format!("", esc(u))) + .unwrap_or_default(); + format!( + "\ + \ + {head}{}\ + {body}", + esc(title) + ) +} + +/// The page while the person has not decided: look at the app, and match +/// the code. What is known is said in neutral words: where the assistant +/// will be sent back to first, then what it calls itself (its own word, +/// escaped, never a name of a product made from the address). +pub fn waiting(host: &str, name: &str, company: &str, code: &str, wait: &str) -> String { + let calls = if name.is_empty() { + String::new() + } else { + format!(" It calls itself \u{201c}{}\u{201d}.", esc(name)) + }; + shell( + "Look at Wanderbooks", + Some(&format!("/authorize/wait/{wait}")), + &format!( + "

Look at Wanderbooks

\ +

An assistant that will be sent back to {} is asking to connect to {}.{calls}

\ +

Your code is {}

\ +

Open the Wanderbooks window on your computer. Choose Allow \ + only if it shows this same code. This page continues by itself when you do.

\ +

If the code is different, or you didn't just ask an assistant to connect, \ + choose Don't allow, or just close this page.

", + esc(host), + esc(company), + esc(code) + ), + ) +} + +/// A plain problem, with nothing to click. +pub fn problem(title: &str, text: &str) -> String { + shell( + title, + None, + &format!("

{}

{}

", esc(title), esc(text)), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_strangers_words_never_become_markup() { + let page = waiting( + "", + "\">", + "co", + "123 456", + "w_abc", + ); + assert!(!page.contains("