diff --git a/Cargo.lock b/Cargo.lock index 6c43b6ed..edb18e7a 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-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..a1d69252 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,68 @@ 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, +} + +/// 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, + /// The product we recognise by where it is sent back to ("Claude on + /// the web"), else what it calls itself. + pub client_name: String, + /// The product recognised from its redirect host, if it is one. + pub product: Option, + /// 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 +757,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 +831,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..f10acf76 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( @@ -1318,6 +1347,75 @@ impl Books { } 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(), @@ -2335,6 +2433,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 +2443,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 +2473,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 +2491,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 +2548,110 @@ 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() +} + +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())) + } + } +} + +/// 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 +2663,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 +2735,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 +2769,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, @@ -2589,25 +2836,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 +2944,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 +3033,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 +3129,7 @@ async fn fetch( }, head_after: None, agent: None, + from: None, }; let recorded = access.record(&record).is_ok(); (found, recorded) @@ -2961,10 +3214,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 +3249,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 +3277,31 @@ 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); + if books + .remote + .limited(books.remote.call_key(&token), remote::CALLS_PER_MINUTE, 60) + { + let mut refused = refused_at_door( + &held, + inside, + who, + &asked_of(&method), + "rate_limited", + StatusCode::TOO_MANY_REQUESTS, + "this connection is making too many calls: wait a minute".into(), + ) + .await; + refused.headers_mut().insert( + axum::http::header::RETRY_AFTER, + axum::http::HeaderValue::from_static("60"), + ); + return refused; + } + } let session = request .headers() .get(SESSION_HEADER) @@ -3027,14 +3336,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 +3355,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 +3363,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 +3377,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 +3387,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 +3976,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 +4438,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 +4450,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 +4591,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 +4968,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 +5282,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 +5875,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..9504eca6 --- /dev/null +++ b/crates/ledger-mcp/src/local/remote/cimd.rs @@ -0,0 +1,271 @@ +//! 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 IPv4-mapped form of one): 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. +//! 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, 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) + // IPv4-compatible and NAT64 forms of a private address. + || (s[0] == 0x0064 && s[1] == 0xff9b)) +} + +/// 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()); + } + let client = reqwest::Client::builder() + .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()); + } + } + 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", + ] { + 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..205a10f5 --- /dev/null +++ b/crates/ledger-mcp/src/local/remote/http.rs @@ -0,0 +1,611 @@ +//! 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 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, 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(); + let door = Arc::new(Door { + issuer: issuer.clone(), + host: host_header_form(&issuer), + listening, + stop: stop.clone(), + }); + remote.set_door(Some(door)); + let app = remote_router(books.clone()); + let accept_stop = stop.clone(); + handle.spawn(proxy::accept_loop(listener, stop, 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). +fn front(books: &Books, headers: &HeaderMap) -> Result, Box> { + let Some(door) = books.remote.door() else { + return Err(Box::new(no_store( + (StatusCode::SERVICE_UNAVAILABLE, "web assistants are off").into_response(), + ))); + }; + let host = headers + .get(header::HOST) + .and_then(|h| h.to_str().ok()) + .map(str::to_ascii_lowercase); + 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>, headers: HeaderMap) -> Response { + if let Err(r) = front(&books, &headers) { + 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, + headers: HeaderMap, + body: axum::body::Body, +) -> Response { + if let Err(r) = front(&books, &headers) { + 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, &peer.0.ip().to_string()) + .await + { + Ok(out) => cors(json(201, &out)), + Err(e) => oauth_error(e), + } +} + +async fn authorize( + State(books): State>, + Extension(peer): Extension, + headers: HeaderMap, + Query(q): Query>, +) -> Response { + let door = match front(&books, &headers) { + Ok(d) => d, + Err(r) => return *r, + }; + answer( + books + .remote + .authorize(&books, &door, &q, &peer.0.ip().to_string()) + .await, + ) +} + +async fn wait( + State(books): State>, + headers: HeaderMap, + Path(wait): Path, +) -> Response { + if let Err(r) = front(&books, &headers) { + return *r; + } + answer(books.remote.wait(&wait)) +} + +async fn token( + State(books): State>, + Extension(peer): Extension, + headers: HeaderMap, + body: axum::body::Body, +) -> Response { + let door = match front(&books, &headers) { + 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, &peer.0.ip().to_string()) + .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) { + 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()) { + 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..ead6deae --- /dev/null +++ b/crates/ledger-mcp/src/local/remote/mod.rs @@ -0,0 +1,2230 @@ +//! 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 the +//! relay's PROXY header (proxy.rs); the address in it 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. `/authorize` never approves: it +//! parks the request (PENDING_TTL), and 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. +//! Neither a stranger's guess nor a replay approves anything: the +//! second id only reads the outcome, once. +//! 6. An approval is the owner's decision about a product, a company and +//! a set of permissions, and survives a product registering again: 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), plus a record here naming the +//! product. Access tokens live ACCESS_TTL; refresh tokens REFRESH_TTL +//! since last use, rotated at every use, 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, pending requests, codes, access +//! tokens, refresh tokens. A stranger registering clients, or asking +//! to sign in, can fill none of them; 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. +//! 9. No company mixing: a token for company A, presented at company +//! B's path, is refused (403, recorded as the token's own refusal); 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::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, and from one address. +pub const MAX_PENDING: usize = 20; +/// Most requests one address may have waiting. +pub const MAX_PENDING_PER_ADDRESS: usize = 5; +/// 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. +const TOKEN_PER_CLIENT: u32 = 120; +/// Calls an approval may make in a minute. +pub const CALLS_PER_MINUTE: u32 = 600; +/// The limiter's own table is bounded too. +const MAX_LIMITS: usize = 10_000; +/// How long a used code is remembered, to end the family a replay shows. +const USED_CODE_KEPT: i64 = 600; +/// 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, + /// 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 identifies the product across registrations. + pub product: 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, +} + +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, +} + +struct Pending { + /// What the window names it by. + id: String, + /// What only the browser's page holds. + wait: String, + client: String, + client_name: String, + product: Option, + redirect: String, + state: Option, + challenge: String, + book: String, + issuer: String, + from: 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, + limits: HashMap, + failed_docs: HashMap, + unsigned: 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, +} + +/// 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) + )) +} + +/// A name, cleaned for showing and for storing: no control 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()).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. +pub(super) fn valid_redirect(text: &str) -> Option { + if text.len() > 2048 || 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, + } +} + +/// 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 products whose own redirect hosts we recognise (D-81: Claude and +/// ChatGPT). The name comes from where the browser is sent back, which a +/// client cannot fake, never from what it calls itself. +const KNOWN: &[(&str, &[&str])] = &[ + ("Claude on the web", &["claude.ai", "claude.com"]), + ( + "ChatGPT on the web", + &["chatgpt.com", "openai.com", "platform.openai.com"], + ), +]; + +/// The product whose hosts every redirect address is on, if one. +pub(super) fn known_product(redirects: &[String]) -> Option<&'static str> { + KNOWN.iter().find_map(|(label, hosts)| { + let all = !redirects.is_empty() + && redirects.iter().all(|r| { + reqwest::Url::parse(r).ok().is_some_and(|u| { + u.scheme() == "https" + && u.host_str() + .is_some_and(|h| hosts.contains(&h.to_ascii_lowercase().as_str())) + }) + }); + all.then_some(*label) + }) +} + +/// What identifies a product across registrations (rule 6). +fn product_key(client: &ClientRec) -> String { + match (client.kind, known_product(&client.redirects)) { + (_, Some(label)) => format!("known:{label}"), + (Kind::Document | Kind::Typed, None) => format!("{:?}:{}", client.kind, client.id), + (Kind::Registered, None) => { + let mut redirects = client.redirects.clone(); + redirects.sort(); + format!( + "registered:{}|{}", + client.name.to_lowercase(), + redirects.join(" ") + ) + } + } +} + +/// What the window calls a client: the product we recognise, else what it +/// calls itself. +fn label_of(client: &ClientRec) -> String { + known_product(&client.redirects) + .map(str::to_string) + .unwrap_or_else(|| { + let n = clean(&client.name, 60); + if n.is_empty() { + "An assistant".to_string() + } else { + n + } + }) +} + +/// 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, + clients: inner.clients.values().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())?; + 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: whether `key` may do one more thing in + /// `window` seconds, `max` at most. The table is bounded (INVARIANT 8). + fn allow(&self, inner: &mut Inner, key: String, max: u32, window: i64) -> bool { + let now = self.now(); + if inner.limits.len() >= MAX_LIMITS && !inner.limits.contains_key(&key) { + inner.limits.retain(|_, (start, _)| now - *start < 3600); + if inner.limits.len() >= MAX_LIMITS { + inner.limits.clear(); + } + } + 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 + } + + /// 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) + } + + /// 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); + // 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.map(|d| d.issuer.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. + pub(super) async fn register( + self: &Arc, + books: &Arc, + meta: &serde_json::Value, + from: &str, + ) -> Result { + self.ready(books)?; + { + let mut inner = self.inner(); + self.sweep(&mut inner); + let ok = self.allow( + &mut inner, + format!("register:{from}"), + 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()); + } + } + 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, + fetched: 0, + }, + ); + } + // A registration that can't be kept is not given: the client would + // hold an id this server forgets. + if let Err(e) = self.save_async().await { + self.inner().clients.remove(&id); + return Err(OauthError::new(500, "server_error", e)); + } + 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. + pub(super) async fn resolve_client( + self: &Arc, + books: &Arc, + id: &str, + from: &str, + ) -> Result { + self.ready(books)?; + let now = self.now(); + { + let mut inner = self.inner(); + self.sweep(&mut inner); + if let Some(c) = inner.clients.get(id) { + let fresh = c.kind != Kind::Document || now - c.fetched < CIMD_TTL; + if fresh { + return Ok(c.clone()); + } + } + } + if !id.starts_with("https://") { + return Err(OauthError::new( + 401, + "invalid_client", + "that client_id isn't known here", + )); + } + // 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 Err(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(&mut inner, format!("fetch:{from}"), FETCH_PER_ADDRESS, 60) + { + return Err(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), + 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()); + } + } + 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, + 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()) + } + + /// A sign-in begins (`GET /authorize`). Either an answer to send the + /// browser, or the request is parked. + pub(super) async fn authorize( + self: &Arc, + books: &Arc, + door: &Door, + q: &BTreeMap, + from: &str, + ) -> Authorize { + { + let mut inner = self.inner(); + if !self.allow( + &mut inner, + format!("authorize:{from}"), + 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).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(); + let fail = |code: &str, why: &str| { + Authorize::Redirect(error_redirect( + &redirect, + state.as_deref(), + code, + why, + &door.issuer, + )) + }; + 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 product = product_key(&client); + let label = label_of(&client); + let now = self.now(); + // An approval the person already gave this product for this + // company stands, however many times the product registers again + // (rule 6): its principals' token must still be live. + let existing = { + let inner = self.inner(); + inner + .approvals + .values() + .find(|a| a.book == book && a.product == product) + .cloned() + }; + if let Some(approval) = existing + && now - approval.last_used < REFRESH_TTL + && super::token_is_live( + books, + &approval.book, + &approval.token_name, + &approval.token_id, + ) + { + let code = { + let mut inner = self.inner(); + if let Some(c) = inner.clients.get_mut(&client.id) { + c.used = true; + c.last_seen = now; + } + self.new_code( + &mut inner, + &client.id, + &approval, + &door.issuer, + &redirect, + &challenge, + None, + ) + }; + return match code { + Ok(code) => Authorize::Redirect(success_redirect( + &redirect, + state.as_deref(), + &code, + &door.issuer, + )), + Err(_) => fail("server_error", "no code could be made"), + }; + } + // Parked, for the person to decide in the app's window (rule 5). + let parked = { + let mut inner = self.inner(); + self.sweep(&mut inner); + let total = inner + .pending + .iter() + .filter(|p| matches!(p.settled, Settled::Waiting)) + .count(); + let mine = inner + .pending + .iter() + .filter(|p| matches!(p.settled, Settled::Waiting) && p.from == from) + .count(); + if total >= MAX_PENDING || mine >= MAX_PENDING_PER_ADDRESS { + return Authorize::Page( + 429, + pages::problem( + "Wanderbooks is busy", + "Too many assistants are waiting to be allowed. Try again in a few minutes.", + ), + ); + } + let (Ok(id), Ok(wait)) = (random("p_", 9), random("w_", 24)) else { + return fail("server_error", "no id could be made"); + }; + 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: label.clone(), + product: known_product(&client.redirects).map(str::to_string), + redirect: redirect.clone(), + state: state.clone(), + challenge, + book: book.clone(), + issuer: door.issuer.clone(), + from: from.to_string(), + wants_post, + created: now, + exp: now + PENDING_TTL, + settled: Settled::Waiting, + }); + wait + }; + let company = super::company_name(books, &book); + Authorize::Page(200, pages::waiting(&label, &company, &parked)) + } + + /// 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, 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; + } + let settled = match &inner.pending[at].settled { + Settled::Waiting => None, + Settled::Allowed(code) => Some(Some(code.clone())), + Settled::Refused => Some(None), + }; + match settled { + None => { + let p = &inner.pending[at]; + let company = p.book.clone(); + Authorize::Page(200, pages::waiting(&p.client_name, &company, wait)) + } + Some(Some(code)) => { + let p = inner.pending.remove(at); + Authorize::Redirect(success_redirect( + &p.redirect, + p.state.as_deref(), + &code, + &p.issuer, + )) + } + Some(None) => { + let p = inner.pending.remove(at); + let why = if p.exp <= now { + "nobody allowed it in time" + } else { + "the owner didn't allow it" + }; + Authorize::Redirect(error_redirect( + &p.redirect, + p.state.as_deref(), + "access_denied", + 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(), + product: p.product.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")?; + let product = product_key(&client); + let existing = self + .inner() + .approvals + .values() + .find(|a| a.book == book && a.product == product) + .cloned(); + let approval = match existing { + Some(a) if super::token_is_live(books, &a.book, &a.token_name, &a.token_id) => { + if post && !self.may_post(books, &a) { + self.set_post(books, &a.id, true)? + } else { + a + } + } + old => self.make_approval(books, &book, &client, &product, post, old)?, + }; + { + 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, + )) + } + + fn may_post(&self, books: &Books, a: &Approval) -> bool { + super::live_token(books, &a.book, &a.token_name, &a.token_id) + .is_some_and(|t| t.scopes.contains(&Scope::Post)) + } + + /// A new approval, and the principals' token that carries it. + fn make_approval( + &self, + books: &Books, + book: &str, + client: &ClientRec, + product: &str, + post: bool, + old: Option, + ) -> Result { + let book_id = BookId::parse(book).map_err(|e| e.to_string())?; + { + let inner = self.inner(); + if old.is_none() && inner.approvals.len() >= MAX_APPROVALS { + return Err("there are too many connections: revoke some first".into()); + } + } + let label = label_of(client); + let base = token_slug(&label); + 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: old + .as_ref() + .map(|o| o.id.clone()) + .unwrap_or(random("apr_", 9).map_err(|e| e.description)?), + book: book.to_string(), + product: product.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, in one record. + pub(super) fn set_post( + &self, + books: &Books, + approval_id: &str, + post: bool, + ) -> Result { + self.load(books)?; + let mut approval = self + .inner() + .approvals + .get(approval_id) + .cloned() + .ok_or("there is no such connection")?; + if !super::token_is_live( + books, + &approval.book, + &approval.token_name, + &approval.token_id, + ) { + return Err("that connection was revoked".into()); + } + let book_id = BookId::parse(&approval.book).map_err(|e| e.to_string())?; + let token = super::make_token( + books, + &book_id, + &approval.token_name, + scopes_for(post), + true, + )?; + approval.token_id = token.id; + self.inner() + .approvals + .insert(approval.id.clone(), approval.clone()); + self.save()?; + Ok(approval) + } + + 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}")); + } + if self.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. + pub(super) async fn token( + self: &Arc, + books: &Arc, + door: &Door, + form: &BTreeMap, + basic: Option<(String, String)>, + from: &str, + ) -> 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")); + }; + { + 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", + )); + } + } + let grant = form.get("grant_type").map(String::as_str).unwrap_or(""); + let client = match self.resolve_client(books, &client_id, from).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), + }; + // 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); + let _now = self.now(); + let (found, reused) = { + let mut inner = self.inner(); + self.sweep(&mut inner); + let found = inner.refresh.get(&key).cloned(); + let reused = found.as_ref().is_some_and(|r| r.used); + if let Some(rec) = found.as_ref().filter(|r| r.used) { + // Used twice: the family is over (RFC 9700 4.14). + let family = rec.family.clone(); + inner.refresh.retain(|_, r| r.family != family); + inner.access.retain(|_, a| a.family != family); + } + (found, reused) + }; + let Some(rec) = found else { + return Err(bad("that refresh token is invalid, used, or has expired")); + }; + if reused { + let _ = self.save_async().await; + return Err(bad("that refresh token was already used: sign in again")); + } + if rec.client != client.id { + return Err(bad("that refresh token belongs to another assistant")); + } + if rec.issuer != door.issuer { + return Err(bad("that refresh token was made for another address")); + } + let approval = self + .inner() + .approvals + .get(&rec.approval) + .cloned() + .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, &rec.family, Some(key)) + .await + } + + /// Mint an access token and a refresh token under `approval`, and (a + /// refresh) retire the refresh token it came from. + async fn issue( + self: &Arc, + books: &Arc, + 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(); + let (new_hash, undo) = { + let mut inner = self.inner(); + 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; + } + (new_hash, retire.clone()) + }; + // Kept before it is given (a refresh token this server forgot + // would sign the person out): if it can't be kept, nothing was made. + 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..c90f5613 --- /dev/null +++ b/crates/ledger-mcp/src/local/remote/pages.rs @@ -0,0 +1,88 @@ +//! 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'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. +pub fn waiting(client: &str, company: &str, wait: &str) -> String { + shell( + "Look at Wanderbooks", + Some(&format!("/authorize/wait/{wait}")), + &format!( + "

Look at Wanderbooks

\ +

{} is asking to connect to {}.

\ +

Open the Wanderbooks window on your computer and choose Allow \ + or Don't allow. This page continues by itself when you do.

\ +

If you didn't ask an assistant to connect, choose Don't allow, or just close this page.

", + esc(client), + esc(company) + ), + ) +} + +/// 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("", "\">", "w_abc"); + assert!(!page.contains("