feat(mcp): the remote door and the sign-in behind it (P15 B1, D-83, D-86)

A second HTTP listener in the books server, on 127.0.0.1 only, off until the
app's admin request (RemoteStart) names the one public address. Every
connection begins with the relay's PROXY v2 header, whose address is the
caller's (never an HTTP header); the door speaks stateless plain-JSON MCP for
one company per path, and is its own OAuth 2.1 server: metadata at every
place products look, client ID metadata documents, dynamic registration and
a typed client id and secret, PKCE S256, exact redirects, single-use short
codes, rotated refresh tokens (a reused one ends its family), short access
tokens, the issuer pinned. /authorize never approves: it parks the request
and only the owner-only admin socket turns it into a code. An approval is one
principals token (so A4's list and revoke see it) plus a record naming the
product, which survives the product registering again. Read and draft by
default; posting raised per approval. Every table is bounded and expires;
secrets are kept as SHA-256 only. A stranger's unsigned request is a 401 with
the metadata pointer and is counted, never written to the books' record.

The access record gains an optional 'from' (the caller's address), kept as an
IP when it is one (the TIN masking would turn it to dots).

The tools a model reaches for first now carry the company's name and 'call
books.start first' in their own descriptions (plan 3.4), local and remote.

Dependencies: none new to the tree. reqwest (client documents, as ledger-host
already uses it), subtle, getrandom and hyper-util (already pulled in by
ledger-store and axum) are now declared by ledger-mcp; cargo deny and the
notices check pass unchanged.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-21 11:15:26 -07:00
1 parent eafd269ba0
commit e00e52f2f3
15 files changed
+5839 -41

No files matched your search

+271
View File
@@ -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<Box<dyn Future<Output = Result<Vec<u8>, 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<Box<dyn Future<Output = Result<Vec<u8>, 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<std::net::SocketAddr> =
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>), 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));
}
}
}
+611
View File
@@ -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<Books>,
public_url: &str,
port: Option<u16>,
) -> Result<RemoteInfo, String> {
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<Books>) {
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<Books>) -> 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<Arc<Door>, Box<Response>> {
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<Arc<Books>>, headers: HeaderMap) -> Response {
if let Err(r) = front(&books, &headers) {
return *r;
}
cors(StatusCode::NO_CONTENT.into_response())
}
fn parse_pairs(text: &str) -> BTreeMap<String, String> {
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<Arc<Books>>,
Extension(peer): Extension<Peer>,
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::<serde_json::Value>(&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<Arc<Books>>,
Extension(peer): Extension<Peer>,
headers: HeaderMap,
Query(q): Query<BTreeMap<String, String>>,
) -> 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<Arc<Books>>,
headers: HeaderMap,
Path(wait): Path<String>,
) -> Response {
if let Err(r) = front(&books, &headers) {
return *r;
}
answer(books.remote.wait(&wait))
}
async fn token(
State(books): State<Arc<Books>>,
Extension(peer): Extension<Peer>,
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::<BTreeMap<String, serde_json::Value>>(&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<serde_json::Value> {
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<Arc<Books>>,
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<Arc<Books>>,
Extension(peer): Extension<Peer>,
Path(book): Path<String>,
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::<String>()
);
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
}
File diff suppressed because it is too large. Load diff
@@ -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("&amp;"),
'<' => out.push_str("&lt;"),
'>' => out.push_str("&gt;"),
'"' => out.push_str("&quot;"),
'\'' => out.push_str("&#39;"),
c => out.push(c),
}
}
out
}
fn shell(title: &str, refresh: Option<&str>, body: &str) -> String {
let head = refresh
.map(|u| format!("<meta http-equiv=\"refresh\" content=\"2;url={}\">", esc(u)))
.unwrap_or_default();
format!(
"<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">\
<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\
<meta name=\"referrer\" content=\"no-referrer\">{head}<title>{}</title>\
<style>body{{font:16px/1.5 system-ui,sans-serif;max-width:32rem;margin:15vh auto;padding:0 1rem;color:#222}}\
h1{{font-size:1.4rem}}p{{color:#444}}</style></head><body>{body}</body></html>",
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!(
"<h1>Look at Wanderbooks</h1>\
<p><strong>{}</strong> is asking to connect to <strong>{}</strong>.</p>\
<p>Open the Wanderbooks window on your computer and choose <strong>Allow</strong> \
or <strong>Don't allow</strong>. This page continues by itself when you do.</p>\
<p>If you didn't ask an assistant to connect, choose Don't allow, or just close this page.</p>",
esc(client),
esc(company)
),
)
}
/// A plain problem, with nothing to click.
pub fn problem(title: &str, text: &str) -> String {
shell(
title,
None,
&format!("<h1>{}</h1><p>{}</p>", esc(title), esc(text)),
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_strangers_words_never_become_markup() {
let page = waiting("<script>alert(1)</script>", "\"><img src=x>", "w_abc");
assert!(!page.contains("<script>alert"));
assert!(!page.contains("<img src=x>"));
assert!(page.contains("&lt;script&gt;"));
assert!(!page.contains("<form"));
assert!(page.contains("url=/authorize/wait/w_abc"));
}
}
+274
View File
@@ -0,0 +1,274 @@
//! The caller's address, from the PROXY protocol version 2 header the
//! relay writes before a caller's first byte (crates/relay `proto.rs`,
//! WB-relay-6), and the listener that reads it.
//!
//! ```text
//! GOAL: the remote door knows the real address of every caller, from the
//! one place no caller can write: a header that comes before the
//! caller's own bytes, from the app that forwards them.
//! SOURCE: WB-remote-1 (the remote door), WB-relay-6 (the caller's
//! address); the PROXY protocol specification version 2;
//! plan/p15-app-and-relay.md 4, rule 8.
//! INVARIANTS:
//! 1. Every connection to the remote door starts with exactly the header
//! the relay writes: the 12-byte signature, version 2 with the PROXY
//! command, then TCP over IPv4 (length 12) or IPv6 (length 36) and
//! the addresses. A connection that starts with anything else, that
//! is cut short, or that is silent for HEADER_WAIT, is dropped before
//! a byte of HTTP is read.
//! 2. The header is read once, at the start. A second header, or one
//! sent by the caller inside its own bytes, is HTTP text to the
//! server and is refused as such: the address of a connection can
//! never change after its first bytes.
//! 3. No HTTP header ever names a caller's address for the server:
//! `X-Forwarded-For` and its kind are not read anywhere.
//! 4. The number of connections is bounded: a connection past
//! MAX_CONNECTIONS is closed at once, and a connection that waits for
//! its header holds one of them.
//! SCENARIOS:
//! 1. The relay's own header for IPv4 and for IPv6 reads back as its
//! source address; an IPv4-mapped IPv6 source is the IPv4 address.
//! 2. A header with another signature, version, command or length, one
//! cut short, and plain HTTP with no header, are each refused.
//! ```
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, ReadBuf};
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
/// The 12 bytes every PROXY protocol version 2 header begins with.
pub const SIGNATURE: [u8; 12] = [
0x0D, 0x0A, 0x0D, 0x0A, 0x00, 0x0D, 0x0A, 0x51, 0x55, 0x49, 0x54, 0x0A,
];
/// How long a connection has to send its header.
pub const HEADER_WAIT: Duration = Duration::from_secs(5);
/// The most connections the remote door holds at once (INVARIANT 4).
pub const MAX_CONNECTIONS: usize = 512;
/// Why a header is refused.
#[derive(Debug, PartialEq, Eq)]
pub enum Refused {
/// Not the relay's exact form.
NotAHeader,
/// The stream ended, or failed, inside it.
Cut,
}
/// Read the header from the front of `stream`, giving the caller's
/// address (the header's source). Exactly the forms the relay writes are
/// accepted (INVARIANT 1).
pub async fn read_header<R: AsyncRead + Unpin>(stream: &mut R) -> Result<SocketAddr, Refused> {
let mut head = [0u8; 16];
stream
.read_exact(&mut head)
.await
.map_err(|_| Refused::Cut)?;
if head[..12] != SIGNATURE || head[12] != 0x21 {
return Err(Refused::NotAHeader);
}
let len = usize::from(u16::from_be_bytes([head[14], head[15]]));
match (head[13], len) {
(0x11, 12) => {
let mut b = [0u8; 12];
stream.read_exact(&mut b).await.map_err(|_| Refused::Cut)?;
Ok(SocketAddr::new(
IpAddr::V4(Ipv4Addr::new(b[0], b[1], b[2], b[3])),
u16::from_be_bytes([b[8], b[9]]),
))
}
(0x21, 36) => {
let mut b = [0u8; 36];
stream.read_exact(&mut b).await.map_err(|_| Refused::Cut)?;
let mut octets = [0u8; 16];
octets.copy_from_slice(&b[..16]);
let ip = Ipv6Addr::from(octets);
let ip = ip.to_ipv4_mapped().map_or(IpAddr::V6(ip), IpAddr::V4);
Ok(SocketAddr::new(ip, u16::from_be_bytes([b[32], b[33]])))
}
_ => Err(Refused::NotAHeader),
}
}
/// The header for a caller `source` that reached `destination`, in the
/// form the relay writes (what the app writes to this door, B3; and the
/// tests).
#[allow(dead_code)] // the app writes it to this door (unit B3); the tests do now
pub fn encode(source: SocketAddr, destination: SocketAddr) -> Vec<u8> {
let mut out = Vec::with_capacity(52);
out.extend(SIGNATURE);
out.push(0x21);
match (source, destination) {
(SocketAddr::V4(s), SocketAddr::V4(d)) => {
out.push(0x11);
out.extend(12u16.to_be_bytes());
out.extend(s.ip().octets());
out.extend(d.ip().octets());
out.extend(s.port().to_be_bytes());
out.extend(d.port().to_be_bytes());
}
(s, d) => {
let v6 = |a: SocketAddr| match a {
SocketAddr::V6(v) => (v.ip().octets(), v.port()),
SocketAddr::V4(v) => (v.ip().to_ipv6_mapped().octets(), v.port()),
};
let ((si, sp), (di, dp)) = (v6(s), v6(d));
out.push(0x21);
out.extend(36u16.to_be_bytes());
out.extend(si);
out.extend(di);
out.extend(sp.to_be_bytes());
out.extend(dp.to_be_bytes());
}
}
out
}
/// A connection whose header was read: its stream, and who is on the
/// other end. It holds one of the door's connection places until dropped
/// (INVARIANT 4).
pub struct Proxied {
io: TcpStream,
_place: OwnedSemaphorePermit,
}
impl AsyncRead for Proxied {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<std::io::Result<()>> {
Pin::new(&mut self.io).poll_read(cx, buf)
}
}
impl AsyncWrite for Proxied {
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<std::io::Result<usize>> {
Pin::new(&mut self.io).poll_write(cx, buf)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
Pin::new(&mut self.io).poll_flush(cx)
}
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
Pin::new(&mut self.io).poll_shutdown(cx)
}
}
/// Accept connections on `listener` until `stop`, read each one's header
/// (INVARIANT 1), and hand on the ones that have one, with the address
/// they name. Never waits on one connection to accept another.
pub async fn accept_loop(
listener: TcpListener,
stop: tokio_util::sync::CancellationToken,
mut handle: impl FnMut(Proxied, SocketAddr) + Send + 'static,
) {
let places = std::sync::Arc::new(Semaphore::new(MAX_CONNECTIONS));
let (tx, mut rx) = tokio::sync::mpsc::channel::<(Proxied, SocketAddr)>(64);
let accepting = {
let stop = stop.clone();
async move {
loop {
let accepted = tokio::select! {
() = stop.cancelled() => break,
accepted = listener.accept() => accepted,
};
let Ok((mut io, _local_peer)) = accepted else {
// A failed accept (out of descriptors, a reset): try again
// after a breath, never spin.
tokio::time::sleep(Duration::from_millis(50)).await;
continue;
};
// Closed at once past the limit, before anything is read.
let Ok(place) = places.clone().try_acquire_owned() else {
drop(io);
continue;
};
let tx = tx.clone();
tokio::spawn(async move {
let read = tokio::time::timeout(HEADER_WAIT, read_header(&mut io)).await;
if let Ok(Ok(caller)) = read {
let _ = tx.send((Proxied { io, _place: place }, caller)).await;
}
});
}
}
};
tokio::pin!(accepting);
loop {
tokio::select! {
() = &mut accepting => break,
got = rx.recv() => match got {
Some((io, caller)) => handle(io, caller),
None => break,
},
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn addr(text: &str) -> SocketAddr {
text.parse().unwrap()
}
#[tokio::test]
async fn the_relays_header_reads_back_its_source() {
for (src, dst) in [
("203.0.113.9:51000", "198.51.100.1:443"),
("[2001:db8::7]:4000", "[2001:db8::1]:443"),
] {
let bytes = encode(addr(src), addr(dst));
let mut slice = &bytes[..];
assert_eq!(read_header(&mut slice).await, Ok(addr(src)));
assert!(slice.is_empty());
}
// An IPv4 caller on a dual-stack relay arrives as a mapped address.
let bytes = encode(addr("[::ffff:203.0.113.9]:5"), addr("[2001:db8::1]:443"));
let mut slice = &bytes[..];
assert_eq!(read_header(&mut slice).await, Ok(addr("203.0.113.9:5")));
}
#[tokio::test]
async fn anything_but_the_exact_form_is_refused() {
let good = encode(addr("203.0.113.9:51000"), addr("198.51.100.1:443"));
let mut cases: Vec<(&str, Vec<u8>, Refused)> = Vec::new();
let mut v = good.clone();
v[0] ^= 1;
cases.push(("signature", v, Refused::NotAHeader));
let mut v = good.clone();
v[12] = 0x20; // the LOCAL command: no address
cases.push(("local command", v, Refused::NotAHeader));
let mut v = good.clone();
v[12] = 0x11; // version 1
cases.push(("version", v, Refused::NotAHeader));
let mut v = good.clone();
v[13] = 0x12; // UDP
cases.push(("udp", v, Refused::NotAHeader));
let mut v = good.clone();
v[15] = 13; // a length the form never has
cases.push(("length", v, Refused::NotAHeader));
cases.push(("cut", good[..20].to_vec(), Refused::Cut));
cases.push((
"plain http",
b"GET /b/x/mcp HTTP/1.1\r\nHost: h\r\n\r\n".to_vec(),
Refused::NotAHeader,
));
for (what, bytes, why) in cases {
let mut slice = &bytes[..];
assert_eq!(read_header(&mut slice).await, Err(why), "{what}");
}
}
}
File diff suppressed because it is too large. Load diff