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

Generated
+4
View File
@@ -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",
+9
View File
@@ -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"
+5
View File
@@ -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<String>,
}
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(_) => {
+167 -1
View File
@@ -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<u16>,
},
/// 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<String>,
},
/// 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<String>,
},
/// 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<String>,
/// The one public address it signs assistants in as, if it is on.
pub public_url: Option<String>,
/// The books it offers.
pub allowed: Vec<String>,
}
/// 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<String>,
/// The address it will be sent back to, in full.
pub redirect: String,
/// That address's host.
pub redirect_host: String,
/// The caller's address, as the relay said it (never a header the
/// caller sent).
pub from: String,
/// It asked to post entries too.
pub wants_post: bool,
/// Seconds since it asked.
pub age_secs: u64,
/// Seconds until it is turned away unanswered.
pub expires_in_secs: u64,
}
/// A web connection the person allowed.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ApprovalInfo {
/// Its id.
pub id: String,
/// The company.
pub book: String,
/// What it is called.
pub label: String,
/// The principals' token that carries it (what "Who can reach these
/// books" lists and revokes).
pub token_id: String,
/// That token's name.
pub token_name: String,
/// It may post entries.
pub may_post: bool,
/// When it was allowed (unix seconds).
pub created: i64,
/// When it last did anything (unix seconds), if it has.
pub last_used: Option<i64>,
}
/// 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<BookSessions>),
/// The remote door's state (INVARIANT 10).
Remote(RemoteInfo),
/// The assistants waiting to be allowed.
RemotePending(Vec<PendingInfo>),
/// 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<ApprovalInfo>,
},
/// The web connections that are allowed.
RemoteApprovals(Vec<ApprovalInfo>),
/// 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")
}
+34
View File
@@ -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;
+353 -39
View File
@@ -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<Service>,
/// The same book's service for the remote door: stateless, plain
/// JSON, no session kept (remote/mod.rs INVARIANT 10).
remote_service: Box<Service>,
/// What serves it, for what the remote door reads of it (the
/// company's name).
served: Box<crate::server::Served>,
/// Its store, closed when the server closes (INVARIANT 6).
store: Arc<SharedStore>,
/// 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<remote::Remote>,
}
/// 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<Self>, 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<String>,
}
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<Token> {
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<String> {
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<Scope>,
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<Scope>,
replace: bool,
) -> Result<Token, String> {
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<Scope>,
) -> 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<axum::response::Response>> {
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<Arc<Books>>,
axum::extract::Path(book): axum::extract::Path<String>,
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<Books>,
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<Books>, 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<Books>, 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<Books>, 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<Books>, 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>, 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);
+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
+10
View File
@@ -2124,6 +2124,16 @@ impl ServerHandler for BooksServer {
// Every tool that can change the books takes a request key
// (calls.rs INVARIANT 1).
tools.iter_mut().for_each(calls::add_key_to_schema);
// The company and the entry point in the tools a model reaches for
// first (handbook.rs INVARIANT 7).
let lead = handbook::first_tools_lead(&self.settings());
for tool in tools
.iter_mut()
.filter(|t| handbook::FIRST_TOOLS.contains(&&*t.name))
{
let rest = tool.description.take().unwrap_or_default();
tool.description = Some(format!("{lead}{rest}").into());
}
// A token is shown what it can call (scopes.rs); the list then
// differs by caller, so it may be cached only for this one.
let scopes = crate::access::caller(&context)
+56 -1
View File
@@ -1137,7 +1137,9 @@ fn context(
sha256: String::new(),
};
let (mut parts, ()) = axum::http::Request::new(()).into_parts();
parts.extensions.insert(crate::access::Caller { token });
parts
.extensions
.insert(crate::access::Caller { token, from: None });
cx.extensions.insert(parts);
}
cx
@@ -1551,6 +1553,59 @@ fn a_tool_list_is_cached_only_for_its_caller() {
});
}
/// Plan P15 3.4 (handbook.rs INVARIANT 7): the company's name and "call
/// books.start first" are in the first 512 characters of the server's
/// instructions AND in the description of books.start and the tools a model
/// reaches for first, so a product that drops or cuts the instructions
/// still delivers them. The same list is served to local and remote callers.
#[test]
fn the_company_and_the_entry_point_are_in_the_first_tools_too() {
rt().block_on(async {
let s = session("first-tools").await;
let books = unit_dir("first-tools");
let server = served(store(&books));
let info = server.get_info();
let instructions = info.instructions.unwrap();
let lead: String = instructions.chars().take(handbook::CONNECT_LEAD).collect();
assert!(lead.contains("books.start"), "{lead}");
assert!(lead.contains("the double-entry books of"), "{lead}");
let list = server
.list_tools(None, context(&s.peer, Some(ALL)))
.await
.unwrap();
let name = {
let settings = server.settings();
handbook::first_tools_lead(&settings)
};
assert!(name.contains("books.start") && name.starts_with("For the books of "));
// The 700-character bound of a description (plan I-12) holds for
// the tool's own text; the lead is the most this adds to it.
assert!(name.chars().count() <= 160, "{name}");
for first in handbook::FIRST_TOOLS {
let tool = list
.tools
.iter()
.find(|t| t.name == *first)
.unwrap_or_else(|| panic!("{first} is not served"));
let description = tool.description.as_deref().unwrap_or_default();
assert!(description.starts_with(&name), "{first}: {description}");
}
// The others are left as they were.
let chart = list
.tools
.iter()
.find(|t| t.name == "books.trial_balance")
.unwrap();
assert!(
!chart
.description
.as_deref()
.unwrap_or_default()
.starts_with("For the books of")
);
});
}
/// Plan 4.6 (P5 step 1): the envelope is put on every result in one
/// place; a tool that can change the books answers with the journal's
/// `head` and at least one next step, whatever it said itself, and the
+18
View File
@@ -130,6 +130,13 @@ pub struct Access {
/// What the agent said about itself, on a `books.start` that said.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub agent: Option<Agent>,
/// The address a request came from, when it came through the remote
/// door: the real caller's, as the relay's PROXY header gave it
/// (plan P15 section 4, rule 8): an IP address, kept as it is; text that
/// is not one is masked and cut like any asserted text. None for a
/// request on the local socket.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub from: Option<String>,
}
/// Mask any full TIN in a client's text, then cut it to
@@ -217,6 +224,16 @@ impl AccessLog {
}
}
access.request_id = access.request_id.as_deref().map(asserted);
// An address is text the server made from a socket, not a client's:
// kept as it is when it is one (the masking of TIN-like digit runs
// would turn it to dots), masked like any asserted text if not.
access.from = access
.from
.as_deref()
.map(|f| match f.parse::<std::net::IpAddr>() {
Ok(ip) => ip.to_string(),
Err(_) => asserted(f),
});
access.subject = asserted(&access.subject);
let Value::Object(fields) = serde_json::to_value(&access).expect("a record serializes")
else {
@@ -298,6 +315,7 @@ mod tests {
result: Outcome::Ok,
head_after: None,
agent: None,
from: None,
}
}