Merge branch 't3/remote-mcp-oauth-signin': the remote door and sign-in for web assistants (P15 B1, D-83, D-86, D-90)
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
commit
5a98e417a1
27 files changed
+8578
-63
No files matched your search
Generated
+4
@@ -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",
|
||||
|
||||
@@ -149,7 +149,54 @@ impl ledger_gui::owner::Owner for ViewerOwner {
|
||||
created: t.created,
|
||||
})
|
||||
.collect();
|
||||
Ok(Roster { assistants, tokens })
|
||||
// The web assistants waiting, and those allowed: nothing when the
|
||||
// remote door was never turned on.
|
||||
let web = self
|
||||
.server
|
||||
.web_roster(std::time::Duration::from_secs(3))
|
||||
.unwrap_or_default();
|
||||
let web_pending = web
|
||||
.pending
|
||||
.into_iter()
|
||||
.map(|p| ledger_gui::owner::WebRequest {
|
||||
id: p.id,
|
||||
book: p.book,
|
||||
client_name: p.client_name,
|
||||
known_host: p.known_host,
|
||||
code: p.code,
|
||||
redirect: p.redirect,
|
||||
redirect_host: p.redirect_host,
|
||||
from: p.from,
|
||||
wants_post: p.wants_post,
|
||||
expires_in_secs: p.expires_in_secs,
|
||||
})
|
||||
.collect();
|
||||
let web_approvals = web
|
||||
.approvals
|
||||
.into_iter()
|
||||
.map(|a| ledger_gui::owner::WebApproval {
|
||||
id: a.id,
|
||||
book: a.book,
|
||||
label: a.label,
|
||||
token_id: a.token_id,
|
||||
may_post: a.may_post,
|
||||
last_used: a.last_used,
|
||||
})
|
||||
.collect();
|
||||
Ok(Roster {
|
||||
assistants,
|
||||
tokens,
|
||||
web_pending,
|
||||
web_approvals,
|
||||
})
|
||||
}
|
||||
|
||||
fn web_decide(&self, id: &str, approve: bool, post: bool) -> Result<String, String> {
|
||||
self.server.web_decide(id, approve, post)
|
||||
}
|
||||
|
||||
fn web_set_post(&self, approval: &str, post: bool) -> Result<String, String> {
|
||||
self.server.web_set_post(approval, post)
|
||||
}
|
||||
|
||||
fn serve_revoke(&self, book: &str, name: &str, id: &str) -> Result<String, String> {
|
||||
|
||||
@@ -574,6 +574,13 @@ impl CompanyView {
|
||||
if crate::connect::take_go(ui.ctx()) {
|
||||
self.nav.go(Route::Connect);
|
||||
}
|
||||
// A web assistant asking to connect is asked about over
|
||||
// whatever page this is (the Connect page has its own card).
|
||||
if route != Route::Connect {
|
||||
let spawner = self.jobs.spawner();
|
||||
self.connect
|
||||
.web_prompt(ui, &self.assist, &self.owner.clone(), &spawner);
|
||||
}
|
||||
if let Some(to) = self.palette.show(ui.ctx(), &books) {
|
||||
self.nav.go(to);
|
||||
}
|
||||
|
||||
@@ -44,8 +44,23 @@
|
||||
//! off the UI thread; what is shown while it is not known is "not
|
||||
//! known", never a guess.
|
||||
//! 7. The web half of the page (the switch, the address, the steps for
|
||||
//! Claude and ChatGPT) is unit B3's: `State::web_section` is its
|
||||
//! place, and it draws nothing until then.
|
||||
//! Claude and ChatGPT) is unit B3's. Unit B1's part of it is here: a
|
||||
//! web assistant that asks to connect is shown to the person, in
|
||||
//! words, as a card that says who is asking, where it is sent back
|
||||
//! to, the address it asked from and what it will be able to do, with
|
||||
//! Allow and Don't allow; it appears over any page of the company
|
||||
//! (`State::web_prompt`) and on this page (`State::web_section`).
|
||||
//! Nothing on the web page can approve: only these buttons do, through
|
||||
//! the owner. What is known is said in neutral words, where it will be
|
||||
//! sent back to first ("An assistant that will be sent back to
|
||||
//! claude.ai"), never as a known or trusted product on the strength of
|
||||
//! that address: a host is public, and says nothing of who asks. Each
|
||||
//! card shows its own short code, the one its browser page shows, and
|
||||
//! says to allow only on a match; at most MOST_CARDS cards are drawn
|
||||
//! at once, the newest, and the rest are counted. What the assistant
|
||||
//! calls itself is shown in quotes, after the address. Posting is off
|
||||
//! unless the person ticks it, per assistant, and can be turned on or
|
||||
//! off later; every Allow is a new approval with only what is ticked.
|
||||
//! ```
|
||||
|
||||
use crate::connections::{Connection, Link, Status, describe, program_name};
|
||||
@@ -400,6 +415,9 @@ pub struct State {
|
||||
confirm: Option<String>,
|
||||
/// A revoke ended: the state is read again.
|
||||
refresh: bool,
|
||||
/// The waiting web assistants the person has ticked "let it post
|
||||
/// entries too" for.
|
||||
post_asked: std::collections::BTreeSet<String>,
|
||||
}
|
||||
|
||||
/// The two lines an assistant set up by hand needs.
|
||||
@@ -433,10 +451,249 @@ impl State {
|
||||
self.confirm.as_deref()
|
||||
}
|
||||
|
||||
/// The web half of the page: "Allow web assistants", the address with
|
||||
/// Copy, and the steps for Claude and ChatGPT. Unit B3 draws it here;
|
||||
/// nothing until then (INVARIANT 7).
|
||||
fn web_section(&mut self, _ui: &mut Ui, _status: &Status) {}
|
||||
/// What the person is asked of a web assistant, and what they may do
|
||||
/// about the web connections already allowed (INVARIANT 7). Unit B3
|
||||
/// draws the switch, the address and the steps above this.
|
||||
fn web_section(
|
||||
&mut self,
|
||||
ui: &mut Ui,
|
||||
status: &Status,
|
||||
owner: &Option<Arc<dyn Owner>>,
|
||||
jobs: &crate::jobs::Spawner,
|
||||
) {
|
||||
if status.web_pending.is_empty() && status.web_approvals.is_empty() {
|
||||
return;
|
||||
}
|
||||
let p = pal(ui.ctx());
|
||||
ui.add_space(24.0);
|
||||
section(ui, "Assistants on the web");
|
||||
let mut want: Want = None;
|
||||
let (shown, more) = newest_waiting(&status.web_pending);
|
||||
for request in shown {
|
||||
if let Some(w) = self.pending_card(ui, status, request, owner) {
|
||||
want = Some(w);
|
||||
}
|
||||
ui.add_space(6.0);
|
||||
}
|
||||
say_more_waiting(ui, more);
|
||||
for a in &status.web_approvals {
|
||||
Frame::new()
|
||||
.fill(p.surface)
|
||||
.stroke(Stroke::new(1.0, p.border))
|
||||
.corner_radius(CornerRadius::same(8))
|
||||
.inner_margin(Margin::symmetric(12, 10))
|
||||
.show(ui, |ui| {
|
||||
ui.set_width(ui.available_width());
|
||||
ui.horizontal(|ui| {
|
||||
ui.vertical(|ui| {
|
||||
ui.label(RichText::new(&a.label).font(theme::semibold(13.5)));
|
||||
ui.label(
|
||||
RichText::new(if a.may_post {
|
||||
"Can read, draft and post entries."
|
||||
} else {
|
||||
"Can read and draft entries. It can't post them."
|
||||
})
|
||||
.font(theme::regular(12.5))
|
||||
.color(p.muted),
|
||||
);
|
||||
});
|
||||
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
|
||||
if owner.is_none() || self.job.is_some() {
|
||||
return;
|
||||
}
|
||||
let (label, to) = if a.may_post {
|
||||
("Stop letting it post", false)
|
||||
} else {
|
||||
("Let it post entries", true)
|
||||
};
|
||||
if ui.button(label).clicked() {
|
||||
let (o, id) = (owner.clone(), a.id.clone());
|
||||
if let Some(o) = o {
|
||||
want = Some((
|
||||
format!("Posting for {}", a.label),
|
||||
"Changing what an assistant may do".to_string(),
|
||||
Box::new(move || o.web_set_post(&id, to)),
|
||||
));
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
ui.add_space(6.0);
|
||||
}
|
||||
if let Some((what, keep, work)) = want {
|
||||
self.start(ui, jobs, what, &keep, work);
|
||||
}
|
||||
}
|
||||
|
||||
/// One assistant asking to connect: who, from where, what it will be
|
||||
/// able to do, and Allow and Don't allow. The answer to ask for, if
|
||||
/// the person gave one.
|
||||
fn pending_card(
|
||||
&mut self,
|
||||
ui: &mut Ui,
|
||||
status: &Status,
|
||||
request: &crate::owner::WebRequest,
|
||||
owner: &Option<Arc<dyn Owner>>,
|
||||
) -> Want {
|
||||
let can_answer = owner.is_some();
|
||||
let p = pal(ui.ctx());
|
||||
let mut answer: Option<(bool, bool)> = None;
|
||||
Frame::new()
|
||||
.fill(p.surface)
|
||||
.stroke(Stroke::new(1.5, p.accent))
|
||||
.corner_radius(CornerRadius::same(8))
|
||||
.inner_margin(Margin::symmetric(14, 12))
|
||||
.show(ui, |ui| {
|
||||
ui.set_width(ui.available_width());
|
||||
// What is known is said in neutral words: where it will be
|
||||
// sent back to first, never a product's name made from it.
|
||||
ui.label(
|
||||
RichText::new(format!(
|
||||
"An assistant that will be sent back to {} wants to connect to {}. Allow?",
|
||||
request.redirect_host, status.company
|
||||
))
|
||||
.font(theme::semibold(15.0)),
|
||||
);
|
||||
if !request.client_name.is_empty() {
|
||||
ui.label(
|
||||
RichText::new(format!(
|
||||
"It calls itself \u{201c}{}\u{201d}. That is only its own word for itself.",
|
||||
request.client_name
|
||||
))
|
||||
.font(theme::regular(13.0))
|
||||
.color(p.muted),
|
||||
);
|
||||
}
|
||||
ui.add_space(4.0);
|
||||
ui.label(
|
||||
RichText::new(format!("Code {}", request.code)).font(theme::semibold(22.0)),
|
||||
);
|
||||
ui.label(
|
||||
RichText::new(
|
||||
"Allow only if the page in your browser shows this same code. If it shows another code, or you didn't just ask an assistant to connect, choose Don't allow.",
|
||||
)
|
||||
.font(theme::regular(13.0))
|
||||
.color(p.muted),
|
||||
);
|
||||
if !request.known_host {
|
||||
ui.label(
|
||||
RichText::new(
|
||||
"Wanderbooks doesn't know this address. Don't allow it unless you just set this assistant up yourself.",
|
||||
)
|
||||
.font(theme::regular(13.0))
|
||||
.color(p.warning),
|
||||
);
|
||||
}
|
||||
ui.label(
|
||||
RichText::new(format!(
|
||||
"After you answer, it is sent back to {}. The request came from the internet address {}.",
|
||||
request.redirect_host, request.from
|
||||
))
|
||||
.font(theme::regular(12.5))
|
||||
.color(p.muted),
|
||||
);
|
||||
ui.label(
|
||||
RichText::new(
|
||||
"If you allow it, it can read these books and draft entries. It can't post entries unless you tick the box below.",
|
||||
)
|
||||
.font(theme::regular(12.5))
|
||||
.color(p.muted),
|
||||
);
|
||||
let mut post = self.post_asked.contains(&request.id);
|
||||
if ui
|
||||
.checkbox(
|
||||
&mut post,
|
||||
if request.wants_post {
|
||||
"Also let it post entries (it asked to)"
|
||||
} else {
|
||||
"Also let it post entries"
|
||||
},
|
||||
)
|
||||
.changed()
|
||||
{
|
||||
if post {
|
||||
self.post_asked.insert(request.id.clone());
|
||||
} else {
|
||||
self.post_asked.remove(&request.id);
|
||||
}
|
||||
}
|
||||
ui.add_space(6.0);
|
||||
ui.horizontal(|ui| {
|
||||
let enabled = can_answer && self.job.is_none();
|
||||
if ui.add_enabled(enabled, egui::Button::new("Allow")).clicked() {
|
||||
answer = Some((true, post));
|
||||
}
|
||||
if ui
|
||||
.add_enabled(enabled, egui::Button::new("Don't allow"))
|
||||
.clicked()
|
||||
{
|
||||
answer = Some((false, false));
|
||||
}
|
||||
ui.label(
|
||||
RichText::new(format!(
|
||||
"Waiting {} more minute(s)",
|
||||
request.expires_in_secs.div_ceil(60)
|
||||
))
|
||||
.font(theme::regular(12.0))
|
||||
.color(p.muted),
|
||||
);
|
||||
});
|
||||
});
|
||||
let (approve, post) = answer?;
|
||||
self.post_asked.remove(&request.id);
|
||||
let owner = owner.clone()?;
|
||||
let id = request.id.clone();
|
||||
let what = if approve {
|
||||
format!("Allow the assistant sent back to {}", request.redirect_host)
|
||||
} else {
|
||||
format!(
|
||||
"Don't allow the assistant sent back to {}",
|
||||
request.redirect_host
|
||||
)
|
||||
};
|
||||
Some((
|
||||
what,
|
||||
"Answering an assistant".to_string(),
|
||||
Box::new(move || owner.web_decide(&id, approve, post)),
|
||||
))
|
||||
}
|
||||
|
||||
/// The question over any page of the company: a web assistant asking
|
||||
/// to connect is not something to find by looking for it (INVARIANT 7).
|
||||
/// Not drawn on the Connect page, which has the same card.
|
||||
pub fn web_prompt(
|
||||
&mut self,
|
||||
ui: &Ui,
|
||||
status: &Status,
|
||||
owner: &Option<Arc<dyn Owner>>,
|
||||
jobs: &crate::jobs::Spawner,
|
||||
) {
|
||||
self.collect();
|
||||
if status.web_pending.is_empty() {
|
||||
return;
|
||||
}
|
||||
ui.ctx()
|
||||
.request_repaint_after(std::time::Duration::from_millis(500));
|
||||
let mut want: Want = None;
|
||||
egui::Window::new("An assistant wants to connect")
|
||||
.collapsible(false)
|
||||
.resizable(false)
|
||||
.anchor(egui::Align2::CENTER_CENTER, vec2(0.0, 0.0))
|
||||
.show(ui.ctx(), |win| {
|
||||
let (shown, more) = newest_waiting(&status.web_pending);
|
||||
for request in shown {
|
||||
if let Some(w) = self.pending_card(win, status, request, owner) {
|
||||
want = Some(w);
|
||||
}
|
||||
win.add_space(6.0);
|
||||
}
|
||||
say_more_waiting(win, more);
|
||||
});
|
||||
if let Some((what, keep, work)) = want {
|
||||
self.start(ui, jobs, what, &keep, work);
|
||||
}
|
||||
}
|
||||
|
||||
fn collect(&mut self) {
|
||||
if let Some((what, rx)) = &self.job
|
||||
@@ -444,7 +701,11 @@ impl State {
|
||||
{
|
||||
// Whatever came of it (a key already gone, a file left behind),
|
||||
// the list is read again.
|
||||
if what.starts_with("Revoke") {
|
||||
if what.starts_with("Revoke")
|
||||
|| what.starts_with("Allow")
|
||||
|| what.starts_with("Don't allow")
|
||||
|| what.starts_with("Posting")
|
||||
{
|
||||
self.refresh = true;
|
||||
}
|
||||
self.done = Some((what.clone(), result));
|
||||
@@ -558,7 +819,7 @@ impl State {
|
||||
),
|
||||
};
|
||||
}
|
||||
self.web_section(ui, status);
|
||||
self.web_section(ui, status, &owner, jobs);
|
||||
ui.add_space(24.0);
|
||||
self.connections(ui, status, book, &owner, jobs);
|
||||
});
|
||||
@@ -624,6 +885,36 @@ impl State {
|
||||
}
|
||||
}
|
||||
|
||||
/// The most requests drawn at once: a few addresses must not be able to
|
||||
/// bury the one the person is waiting for under a screenful.
|
||||
pub const MOST_CARDS: usize = 3;
|
||||
|
||||
/// The newest requests (the one just asked for is the one the person is
|
||||
/// looking for), and how many more are waiting.
|
||||
fn newest_waiting(all: &[crate::owner::WebRequest]) -> (Vec<&crate::owner::WebRequest>, usize) {
|
||||
let mut sorted: Vec<&crate::owner::WebRequest> = all.iter().collect();
|
||||
// Most time left is the newest.
|
||||
sorted.sort_by_key(|r| std::cmp::Reverse(r.expires_in_secs));
|
||||
let more = sorted.len().saturating_sub(MOST_CARDS);
|
||||
sorted.truncate(MOST_CARDS);
|
||||
(sorted, more)
|
||||
}
|
||||
|
||||
fn say_more_waiting(ui: &mut Ui, more: usize) {
|
||||
if more == 0 {
|
||||
return;
|
||||
}
|
||||
let p = pal(ui.ctx());
|
||||
ui.label(
|
||||
RichText::new(format!(
|
||||
"{more} more {} waiting. Answer these first; the next ones then show.",
|
||||
if more == 1 { "is" } else { "are" }
|
||||
))
|
||||
.font(theme::regular(12.5))
|
||||
.color(p.muted),
|
||||
);
|
||||
}
|
||||
|
||||
fn section(ui: &mut Ui, title: &str) {
|
||||
ui.label(RichText::new(title).font(theme::semibold(17.0)));
|
||||
ui.add_space(4.0);
|
||||
|
||||
@@ -34,7 +34,7 @@
|
||||
//! 5. Nothing here holds a token's text: the server never sends one.
|
||||
//! ```
|
||||
|
||||
use crate::owner::{Assistant, LastCall, Owner, Roster, TokenRow};
|
||||
use crate::owner::{Assistant, LastCall, Owner, Roster, TokenRow, WebApproval, WebRequest};
|
||||
use chrono::{DateTime, Utc};
|
||||
use egui_phosphor::regular as icon;
|
||||
use std::sync::{Arc, Mutex, MutexGuard};
|
||||
@@ -94,6 +94,10 @@ pub struct Status {
|
||||
pub assistants: Vec<Assistant>,
|
||||
/// The tokens of this company: who may connect.
|
||||
pub tokens: Vec<TokenRow>,
|
||||
/// Web assistants waiting for the person to allow them.
|
||||
pub web_pending: Vec<WebRequest>,
|
||||
/// The web connections the person allowed.
|
||||
pub web_approvals: Vec<WebApproval>,
|
||||
/// "Now", for "10 seconds ago" (fixed in tests and screenshots).
|
||||
pub now: DateTime<Utc>,
|
||||
}
|
||||
@@ -108,6 +112,8 @@ impl Status {
|
||||
link: Link::Unknown,
|
||||
assistants: Vec::new(),
|
||||
tokens: Vec::new(),
|
||||
web_pending: Vec::new(),
|
||||
web_approvals: Vec::new(),
|
||||
now: Utc::now(),
|
||||
}
|
||||
}
|
||||
@@ -561,6 +567,16 @@ impl Connections {
|
||||
.into_iter()
|
||||
.filter(|t| t.book == book)
|
||||
.collect();
|
||||
status.web_pending = roster
|
||||
.web_pending
|
||||
.into_iter()
|
||||
.filter(|r| r.book == book)
|
||||
.collect();
|
||||
status.web_approvals = roster
|
||||
.web_approvals
|
||||
.into_iter()
|
||||
.filter(|a| a.book == book)
|
||||
.collect();
|
||||
status.link = if status.assistants.is_empty() {
|
||||
Link::None
|
||||
} else if status.assistants.iter().any(|a| a.running > 0) {
|
||||
|
||||
@@ -203,6 +203,54 @@ pub struct TokenRow {
|
||||
pub created: String,
|
||||
}
|
||||
|
||||
/// A web assistant waiting for the person to allow it (plan P15 D-83): who
|
||||
/// is asking, as the server saw it. What it calls itself is its own word,
|
||||
/// cleaned and never trusted; where it is sent back to and the address it
|
||||
/// asked from are what the server saw.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct WebRequest {
|
||||
/// What an answer names.
|
||||
pub id: String,
|
||||
/// The company it asks to reach.
|
||||
pub book: String,
|
||||
/// What it calls itself: its own word, cleaned and short, possibly
|
||||
/// empty. Never a product's name made from where it is sent back to.
|
||||
pub client_name: String,
|
||||
/// Whether the address it is sent back to is one of the vendors' known
|
||||
/// hosts. Only the warning depends on it; nothing is shown as known or
|
||||
/// trusted for it.
|
||||
pub known_host: bool,
|
||||
/// The short code to match with the one its browser page shows.
|
||||
pub code: String,
|
||||
/// The address it is sent back to, in full.
|
||||
pub redirect: String,
|
||||
/// That address's host.
|
||||
pub redirect_host: String,
|
||||
/// The caller's address, as the relay said it.
|
||||
pub from: String,
|
||||
/// It asked to post entries too.
|
||||
pub wants_post: bool,
|
||||
/// Seconds until it is turned away unanswered.
|
||||
pub expires_in_secs: u64,
|
||||
}
|
||||
|
||||
/// A web connection the person allowed.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct WebApproval {
|
||||
/// Its id.
|
||||
pub id: String,
|
||||
/// The company.
|
||||
pub book: String,
|
||||
/// What it is called.
|
||||
pub label: String,
|
||||
/// The key that carries it: what "Who can reach these books" revokes.
|
||||
pub token_id: String,
|
||||
/// It may post entries (else read and draft).
|
||||
pub may_post: bool,
|
||||
/// When it last did anything (unix seconds).
|
||||
pub last_used: Option<i64>,
|
||||
}
|
||||
|
||||
/// Who is connected and who may connect, across the open companies.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Roster {
|
||||
@@ -210,6 +258,10 @@ pub struct Roster {
|
||||
pub assistants: Vec<Assistant>,
|
||||
/// Every live token.
|
||||
pub tokens: Vec<TokenRow>,
|
||||
/// Web assistants waiting for the person.
|
||||
pub web_pending: Vec<WebRequest>,
|
||||
/// Web connections the person allowed.
|
||||
pub web_approvals: Vec<WebApproval>,
|
||||
}
|
||||
|
||||
/// The owner's actions, done by the program the viewer runs in (ledger-cli
|
||||
@@ -272,6 +324,16 @@ pub trait Owner: Send + Sync {
|
||||
fn serve_revoke(&self, _book: &str, _name: &str, _id: &str) -> Result<String, String> {
|
||||
Err("not here".into())
|
||||
}
|
||||
/// The person's answer to a web assistant waiting to be allowed:
|
||||
/// `approve` it or refuse it; `post` lets it post entries too, not
|
||||
/// only read and draft. `Ok` says what was done, in words. Blocks.
|
||||
fn web_decide(&self, _id: &str, _approve: bool, _post: bool) -> Result<String, String> {
|
||||
Err("not here".into())
|
||||
}
|
||||
/// Let a web connection post entries, or take that away. Blocks.
|
||||
fn web_set_post(&self, _approval: &str, _post: bool) -> Result<String, String> {
|
||||
Err("not here".into())
|
||||
}
|
||||
/// This program run with `words`, as a line to type in a terminal (the
|
||||
/// program's own path, the words, the data root if one was named): what
|
||||
/// the Connect page shows for an assistant it has no button for.
|
||||
|
||||
@@ -42,7 +42,9 @@ use ledger_core::{AccountType, Currency};
|
||||
use ledger_gui::connections::Link;
|
||||
use ledger_gui::data::Source;
|
||||
use ledger_gui::nav::Route;
|
||||
use ledger_gui::owner::{Agent, Assistant, LastCall, Owner, RestorePlan, Roster, TokenRow};
|
||||
use ledger_gui::owner::{
|
||||
Agent, Assistant, LastCall, Owner, RestorePlan, Roster, TokenRow, WebApproval, WebRequest,
|
||||
};
|
||||
use ledger_gui::{App, Start};
|
||||
use ledger_store::root::{BookId, Root};
|
||||
use std::collections::HashMap;
|
||||
@@ -196,6 +198,44 @@ impl Owner for Fake {
|
||||
}
|
||||
Ok(format!("Ended {name:?}'s access to {book}."))
|
||||
}
|
||||
fn web_decide(&self, id: &str, approve: bool, post: bool) -> Result<String, String> {
|
||||
self.note(format!("web_decide {id} {approve} {post}"));
|
||||
// As the server does: it is no longer waiting, and an allowed one
|
||||
// is a connection.
|
||||
if let Some(Ok(r)) = self.roster.lock().unwrap().as_mut() {
|
||||
let gone: Vec<_> = r
|
||||
.web_pending
|
||||
.iter()
|
||||
.filter(|p| p.id == id)
|
||||
.cloned()
|
||||
.collect();
|
||||
r.web_pending.retain(|p| p.id != id);
|
||||
if approve {
|
||||
for p in gone {
|
||||
r.web_approvals.push(WebApproval {
|
||||
id: format!("apr_{id}"),
|
||||
book: p.book,
|
||||
label: p.client_name,
|
||||
token_id: "tok_1".into(),
|
||||
may_post: post,
|
||||
last_used: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok("done".into())
|
||||
}
|
||||
fn web_set_post(&self, approval: &str, post: bool) -> Result<String, String> {
|
||||
self.note(format!("web_set_post {approval} {post}"));
|
||||
if let Some(Ok(r)) = self.roster.lock().unwrap().as_mut() {
|
||||
for a in &mut r.web_approvals {
|
||||
if a.id == approval {
|
||||
a.may_post = post;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok("done".into())
|
||||
}
|
||||
fn command_line(&self, words: &[&str]) -> Result<String, String> {
|
||||
Ok(format!("/opt/wanderbooks {}", words.join(" ")))
|
||||
}
|
||||
@@ -257,7 +297,11 @@ fn token(book: &str, name: &str) -> TokenRow {
|
||||
}
|
||||
|
||||
fn roster(assistants: Vec<Assistant>, tokens: Vec<TokenRow>) -> Result<Roster, String> {
|
||||
Ok(Roster { assistants, tokens })
|
||||
Ok(Roster {
|
||||
assistants,
|
||||
tokens,
|
||||
..Roster::default()
|
||||
})
|
||||
}
|
||||
|
||||
/// The app over `ids` as tabs (the first in front), served by `owner`.
|
||||
@@ -1033,3 +1077,231 @@ fn pictures() {
|
||||
save(&mut tall, &format!("9-connect-another-{mode}"));
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 7: a web assistant asks to connect (plan P15 D-83, unit B1) --------------
|
||||
|
||||
fn asking(id: &str, name: &str, known_host: bool) -> WebRequest {
|
||||
WebRequest {
|
||||
id: id.into(),
|
||||
book: "alpha".into(),
|
||||
client_name: name.into(),
|
||||
known_host,
|
||||
code: format!("482 {}", 100 + id.len()),
|
||||
redirect: "https://claude.ai/api/mcp/auth_callback".into(),
|
||||
redirect_host: "claude.ai".into(),
|
||||
from: "203.0.113.9".into(),
|
||||
wants_post: false,
|
||||
expires_in_secs: 240,
|
||||
}
|
||||
}
|
||||
|
||||
fn with_pending(owner: &Fake, pending: Vec<WebRequest>, approvals: Vec<WebApproval>) {
|
||||
owner.answer(Ok(Roster {
|
||||
web_pending: pending,
|
||||
web_approvals: approvals,
|
||||
..Roster::default()
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_web_assistant_asking_is_put_to_the_person_over_any_page_in_plain_words() {
|
||||
let w = World::new(&[("alpha", "Wanderland Labs")]);
|
||||
let owner = Fake::new();
|
||||
with_pending(&owner, vec![asking("p_1", "Claude", true)], vec![]);
|
||||
let mut h = start(&w, &["alpha"], &owner);
|
||||
refresh(&mut h);
|
||||
// On the company's own page, not the Connect page.
|
||||
assert_ne!(h.state().route(), &Route::Connect);
|
||||
// Where it is sent back to first, in neutral words: a host says nothing
|
||||
// of who asks, so nothing is called a known product, and the one
|
||||
// address of a vendor is not warned about, nor praised.
|
||||
assert!(
|
||||
h.query_by_label_contains(
|
||||
"An assistant that will be sent back to claude.ai wants to connect to Wanderland Labs. Allow?"
|
||||
)
|
||||
.is_some()
|
||||
);
|
||||
assert!(h.query_by_label_contains("Claude on the web").is_none());
|
||||
assert!(
|
||||
h.query_by_label_contains("doesn't know this address")
|
||||
.is_none()
|
||||
);
|
||||
// What it calls itself, after the address, as its own word.
|
||||
assert!(h.query_by_label_contains("It calls itself").is_some());
|
||||
// The code to match with the one the browser's page shows.
|
||||
assert!(h.query_by_label_contains("Code 482 103").is_some());
|
||||
assert!(
|
||||
h.query_by_label_contains("Allow only if the page in your browser shows this same code")
|
||||
.is_some()
|
||||
);
|
||||
// Who, where it goes, from where: in words, nothing about OAuth.
|
||||
assert!(
|
||||
h.query_all_by_label_contains("The request came from the internet address 203.0.113.9")
|
||||
.next()
|
||||
.is_some()
|
||||
);
|
||||
assert!(
|
||||
h.query_by_label_contains("can't post entries unless you tick")
|
||||
.is_some()
|
||||
);
|
||||
for word in ["OAuth", "token", "MCP"] {
|
||||
assert!(
|
||||
h.query_by_label_contains(word).is_none(),
|
||||
"{word} is not a word for the person"
|
||||
);
|
||||
}
|
||||
// Nothing is decided by looking at it.
|
||||
assert!(!owner.said().iter().any(|s| s.starts_with("web_decide")));
|
||||
h.get_by_role_and_label(Role::Button, "Allow").click();
|
||||
h.run_steps(2);
|
||||
wait_for("the answer was given", || {
|
||||
owner
|
||||
.said()
|
||||
.contains(&"web_decide p_1 true false".to_string())
|
||||
});
|
||||
// Posting stayed off. The question goes away once the server stops
|
||||
// listing it.
|
||||
refresh(&mut h);
|
||||
assert!(h.query_by_label_contains("wants to connect").is_none());
|
||||
drop(h);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refusing_and_allowing_with_posting_are_their_own_answers() {
|
||||
let w = World::new(&[("alpha", "Wanderland Labs")]);
|
||||
let owner = Fake::new();
|
||||
with_pending(
|
||||
&owner,
|
||||
vec![asking("p_7", "Someone's assistant", false)],
|
||||
vec![],
|
||||
);
|
||||
let mut h = start(&w, &["alpha"], &owner);
|
||||
refresh(&mut h);
|
||||
// An address that isn't a known vendor's keeps its warning.
|
||||
assert!(
|
||||
h.query_by_label_contains("doesn't know this address")
|
||||
.is_some()
|
||||
);
|
||||
h.get_by_role_and_label(Role::Button, "Don't allow").click();
|
||||
h.run_steps(2);
|
||||
wait_for("the refusal was given", || {
|
||||
owner
|
||||
.said()
|
||||
.contains(&"web_decide p_7 false false".to_string())
|
||||
});
|
||||
refresh(&mut h);
|
||||
assert!(h.query_by_label_contains("wants to connect").is_none());
|
||||
// Another asks; this time posting is ticked, then allowed.
|
||||
with_pending(&owner, vec![asking("p_8", "Claude", true)], vec![]);
|
||||
refresh(&mut h);
|
||||
h.get_by_label("Also let it post entries").click();
|
||||
h.run_steps(2);
|
||||
h.get_by_role_and_label(Role::Button, "Allow").click();
|
||||
h.run_steps(2);
|
||||
wait_for("the answer with posting was given", || {
|
||||
owner
|
||||
.said()
|
||||
.contains(&"web_decide p_8 true true".to_string())
|
||||
});
|
||||
drop(h);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn waiting_requests_each_show_their_own_code_and_only_a_few_are_drawn() {
|
||||
let w = World::new(&[("alpha", "Wanderland Labs")]);
|
||||
let owner = Fake::new();
|
||||
let mut all = Vec::new();
|
||||
for (i, id) in ["p_a", "p_b", "p_c", "p_d", "p_e"].iter().enumerate() {
|
||||
let mut r = asking(id, "Claude", true);
|
||||
// Never merged: each has its own code.
|
||||
r.code = format!("{}{}{} 6{}{}", i, i, i, i, i);
|
||||
// The later the id, the newer it is (more time left).
|
||||
r.expires_in_secs = 100 + 10 * i as u64;
|
||||
all.push(r);
|
||||
}
|
||||
with_pending(&owner, all, vec![]);
|
||||
let mut h = start(&w, &["alpha"], &owner);
|
||||
refresh(&mut h);
|
||||
// The newest three, each with its own code; the rest are counted.
|
||||
for shown in ["444 644", "333 633", "222 622"] {
|
||||
assert!(
|
||||
h.query_by_label_contains(&format!("Code {shown}"))
|
||||
.is_some(),
|
||||
"{shown}"
|
||||
);
|
||||
}
|
||||
for hidden in ["111 611", "000 600"] {
|
||||
assert!(
|
||||
h.query_by_label_contains(&format!("Code {hidden}"))
|
||||
.is_none(),
|
||||
"{hidden}"
|
||||
);
|
||||
}
|
||||
// Three cards (their titles end in the question); the window has its own title.
|
||||
assert_eq!(h.query_all_by_label_contains("Allow?").count(), 3);
|
||||
assert!(h.query_by_label_contains("2 more are waiting").is_some());
|
||||
drop(h);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_request_that_ran_out_goes_away_and_posting_is_turned_on_and_off_on_the_connect_page() {
|
||||
let w = World::new(&[("alpha", "Wanderland Labs")]);
|
||||
let owner = Fake::new();
|
||||
with_pending(&owner, vec![asking("p_2", "Claude", true)], vec![]);
|
||||
let mut h = start(&w, &["alpha"], &owner);
|
||||
refresh(&mut h);
|
||||
assert!(
|
||||
h.query_all_by_label_contains("wants to connect")
|
||||
.next()
|
||||
.is_some()
|
||||
);
|
||||
// The server turned it away unanswered: it is not listed any more, and
|
||||
// the window never keeps what the server has dropped.
|
||||
with_pending(&owner, vec![], vec![]);
|
||||
refresh(&mut h);
|
||||
assert!(h.query_by_label_contains("wants to connect").is_none());
|
||||
// A connection that was allowed shows on the Connect page, with what
|
||||
// it may do, and the person raises and lowers it.
|
||||
with_pending(
|
||||
&owner,
|
||||
vec![],
|
||||
vec![WebApproval {
|
||||
id: "apr_1".into(),
|
||||
book: "alpha".into(),
|
||||
label: "Claude on the web".into(),
|
||||
token_id: "tok_1".into(),
|
||||
may_post: false,
|
||||
last_used: None,
|
||||
}],
|
||||
);
|
||||
refresh(&mut h);
|
||||
h.state_mut().view_mut(0).unwrap().goto(Route::Connect);
|
||||
h.run_steps(3);
|
||||
assert!(h.query_by_label_contains("Assistants on the web").is_some());
|
||||
assert!(
|
||||
h.query_by_label_contains("Can read and draft entries. It can't post them.")
|
||||
.is_some()
|
||||
);
|
||||
h.get_by_role_and_label(Role::Button, "Let it post entries")
|
||||
.click();
|
||||
h.run_steps(2);
|
||||
wait_for("posting was turned on", || {
|
||||
owner
|
||||
.said()
|
||||
.contains(&"web_set_post apr_1 true".to_string())
|
||||
});
|
||||
refresh(&mut h);
|
||||
assert!(
|
||||
h.query_by_label_contains("Can read, draft and post entries.")
|
||||
.is_some()
|
||||
);
|
||||
h.get_by_role_and_label(Role::Button, "Stop letting it post")
|
||||
.click();
|
||||
h.run_steps(2);
|
||||
wait_for("posting was turned off", || {
|
||||
owner
|
||||
.said()
|
||||
.contains(&"web_set_post apr_1 false".to_string())
|
||||
});
|
||||
drop(h);
|
||||
}
|
||||
@@ -154,6 +154,16 @@ pub struct Roster {
|
||||
pub tokens: Vec<admin::TokenInfo>,
|
||||
}
|
||||
|
||||
/// The web assistants waiting to be allowed, and the web connections that
|
||||
/// are (plan P15 B1): what the window's "Allow?" shows.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct WebRoster {
|
||||
/// Assistants waiting for the person.
|
||||
pub pending: Vec<admin::PendingInfo>,
|
||||
/// Connections the person allowed.
|
||||
pub approvals: Vec<admin::ApprovalInfo>,
|
||||
}
|
||||
|
||||
/// The books server, a child process of this one.
|
||||
pub struct AppServer {
|
||||
run: PathBuf,
|
||||
@@ -419,6 +429,69 @@ impl AppServer {
|
||||
Ok(Roster { sessions, tokens })
|
||||
}
|
||||
|
||||
/// The web assistants waiting for the person, and the web connections
|
||||
/// allowed: two quick requests, an `Err` while the server is starting or
|
||||
/// gone. A server whose remote door was never turned on answers both
|
||||
/// with nothing.
|
||||
pub fn web_roster(&self, wait: Duration) -> Result<WebRoster, String> {
|
||||
if !self.is_ready() {
|
||||
return Err(match self.exited() {
|
||||
Some(why) => why,
|
||||
None => "the books server is still starting".into(),
|
||||
});
|
||||
}
|
||||
let pending = match self.ask(Request::RemotePending, Some(wait))? {
|
||||
Response::RemotePending(p) => p,
|
||||
Response::Refused(why) => return Err(why),
|
||||
other => return Err(format!("the books server answered oddly: {other:?}")),
|
||||
};
|
||||
let approvals = match self.ask(Request::RemoteApprovals { book: None }, Some(wait))? {
|
||||
Response::RemoteApprovals(a) => a,
|
||||
Response::Refused(why) => return Err(why),
|
||||
other => return Err(format!("the books server answered oddly: {other:?}")),
|
||||
};
|
||||
Ok(WebRoster { pending, approvals })
|
||||
}
|
||||
|
||||
/// The person's answer to one waiting assistant: `Ok` says what was
|
||||
/// done, in words. `post` lets it post entries too, not only read and
|
||||
/// draft.
|
||||
pub fn web_decide(&self, id: &str, approve: bool, post: bool) -> Result<String, String> {
|
||||
self.wait_ready(READY_WAIT)?;
|
||||
match self.ask(
|
||||
Request::RemoteDecide {
|
||||
id: id.into(),
|
||||
approve,
|
||||
post,
|
||||
},
|
||||
Some(Duration::from_secs(30)),
|
||||
)? {
|
||||
Response::RemoteDecided { said, .. } => Ok(said),
|
||||
Response::Refused(why) => Err(why),
|
||||
other => Err(format!("the books server answered oddly: {other:?}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Raise a web connection to posting, or lower it.
|
||||
pub fn web_set_post(&self, approval: &str, post: bool) -> Result<String, String> {
|
||||
self.wait_ready(READY_WAIT)?;
|
||||
match self.ask(
|
||||
Request::RemoteSetPost {
|
||||
approval: approval.into(),
|
||||
post,
|
||||
},
|
||||
Some(Duration::from_secs(30)),
|
||||
)? {
|
||||
Response::RemoteApprovals(_) => Ok(if post {
|
||||
"It can post entries now.".into()
|
||||
} else {
|
||||
"It can read and draft, but not post.".into()
|
||||
}),
|
||||
Response::Refused(why) => Err(why),
|
||||
other => Err(format!("the books server answered oddly: {other:?}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// End the key `id`, named `name`, of the company `book`, as
|
||||
/// `wanderbooks token revoke` does (INVARIANT 12): the server ends that
|
||||
/// key and the sessions it opened, and the token file's copy is
|
||||
@@ -723,6 +796,21 @@ impl AppHost {
|
||||
self.running()?.revoke_token(book, name, id)
|
||||
}
|
||||
|
||||
/// The web assistants waiting, and the web connections allowed.
|
||||
pub fn web_roster(&self, wait: Duration) -> Result<WebRoster, String> {
|
||||
self.running()?.web_roster(wait)
|
||||
}
|
||||
|
||||
/// The person's answer to a waiting assistant.
|
||||
pub fn web_decide(&self, id: &str, approve: bool, post: bool) -> Result<String, String> {
|
||||
self.running()?.web_decide(id, approve, post)
|
||||
}
|
||||
|
||||
/// Raise a web connection to posting, or lower it.
|
||||
pub fn web_set_post(&self, approval: &str, post: bool) -> Result<String, String> {
|
||||
self.running()?.web_set_post(approval, post)
|
||||
}
|
||||
|
||||
/// The format upgrade of the company `id` (INVARIANT 10).
|
||||
pub fn upgrade_format(&self, id: &str, passphrase: &str) -> Result<Vec<String>, String> {
|
||||
match self.running() {
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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(_) => {
|
||||
|
||||
@@ -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,78 @@ impl From<&ledger_store::auth::Token> for TokenInfo {
|
||||
}
|
||||
}
|
||||
|
||||
/// The remote door, as it stands (INVARIANT 10).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct RemoteInfo {
|
||||
/// Where it listens on this computer (127.0.0.1:port), if it is on.
|
||||
pub listening: Option<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>,
|
||||
/// This start's secret, for the app only (the admin socket is the
|
||||
/// owner's): the 64 characters it writes at the very front of every
|
||||
/// connection it makes to the door, before the PROXY header
|
||||
/// (remote/proxy.rs INVARIANT 5). Never shown in a log.
|
||||
#[serde(default)]
|
||||
pub proxy_secret: Option<TokenText>,
|
||||
}
|
||||
|
||||
/// An assistant waiting for the person to allow it (INVARIANT 10): what
|
||||
/// the window shows. What the assistant calls itself is asserted, cleaned
|
||||
/// and never trusted; the address and the redirect are what the server saw.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct PendingInfo {
|
||||
/// The id the answer names.
|
||||
pub id: String,
|
||||
/// The company it asks to reach.
|
||||
pub book: String,
|
||||
/// What it calls itself: its own word, cleaned and short, possibly
|
||||
/// empty. Never a product's name made up from where it is sent back to.
|
||||
pub client_name: String,
|
||||
/// Whether the address it is sent back to is one of the vendors' known
|
||||
/// hosts: only the warning depends on it (a host that isn't gets one).
|
||||
pub known_host: bool,
|
||||
/// The short code the person matches with the one the assistant's
|
||||
/// browser page shows, to tell this request from any other waiting.
|
||||
pub code: String,
|
||||
/// The address it will be sent back to, in full.
|
||||
pub redirect: String,
|
||||
/// That address's host.
|
||||
pub redirect_host: String,
|
||||
/// The caller's address, as the relay said it (never a header the
|
||||
/// caller sent).
|
||||
pub from: String,
|
||||
/// It asked to post entries too.
|
||||
pub wants_post: bool,
|
||||
/// Seconds since it asked.
|
||||
pub age_secs: u64,
|
||||
/// Seconds until it is turned away unanswered.
|
||||
pub expires_in_secs: u64,
|
||||
}
|
||||
|
||||
/// A web connection the person allowed.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ApprovalInfo {
|
||||
/// Its id.
|
||||
pub id: String,
|
||||
/// The company.
|
||||
pub book: String,
|
||||
/// What it is called.
|
||||
pub label: String,
|
||||
/// The principals' token that carries it (what "Who can reach these
|
||||
/// books" lists and revokes).
|
||||
pub token_id: String,
|
||||
/// That token's name.
|
||||
pub token_name: String,
|
||||
/// It may post entries.
|
||||
pub may_post: bool,
|
||||
/// When it was allowed (unix seconds).
|
||||
pub created: i64,
|
||||
/// When it last did anything (unix seconds), if it has.
|
||||
pub last_used: Option<i64>,
|
||||
}
|
||||
|
||||
/// One book, as listed.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct BookStatus {
|
||||
@@ -630,6 +767,30 @@ pub enum Response {
|
||||
},
|
||||
/// Who is connected, for each open book (INVARIANT 9).
|
||||
Sessions(Vec<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 +841,22 @@ pub fn call_within(
|
||||
let not_sent = |why: String| CallError::NotSent(why);
|
||||
// A list changes nothing: its only question is whether it answered.
|
||||
let look = match request {
|
||||
Request::List | Request::TokenList | Request::TokenCheck { .. } | Request::Sessions => None,
|
||||
Request::List
|
||||
| Request::TokenList
|
||||
| Request::TokenCheck { .. }
|
||||
| Request::Sessions
|
||||
| Request::RemoteStatus
|
||||
| Request::RemotePending
|
||||
| Request::RemoteApprovals { .. } => None,
|
||||
Request::RemoteStart { .. }
|
||||
| Request::RemoteStop
|
||||
| Request::RemoteAllow { .. }
|
||||
| Request::RemoteDecide { .. }
|
||||
| Request::RemoteSetPost { .. }
|
||||
| Request::RemoteMakeKey { .. }
|
||||
| Request::RemoteMakeClient { .. } => {
|
||||
Some("ask the state of web assistants again to see whether it was done")
|
||||
}
|
||||
Request::OpenBook { .. } | Request::CloseBook { .. } => {
|
||||
Some("`wanderbooks books list` says whether the books are open")
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
+421
-40
@@ -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(
|
||||
@@ -1315,9 +1344,79 @@ impl Books {
|
||||
});
|
||||
if let (Response::TokenCreated { .. }, Some(old)) = (&answer, &replaced) {
|
||||
self.forget_sessions_of(old);
|
||||
self.remote.token_gone(old);
|
||||
}
|
||||
answer
|
||||
}
|
||||
Request::RemoteStart { public_url, port } => {
|
||||
// The door listens from this blocking task's runtime
|
||||
// (remote/http.rs `start_door`).
|
||||
match remote::start_door(self, &public_url, port) {
|
||||
Ok(info) => Response::Remote(info),
|
||||
Err(why) => Response::Refused(self.hide(why)),
|
||||
}
|
||||
}
|
||||
Request::RemoteStop => {
|
||||
remote::stop_door(self);
|
||||
Response::Remote(self.remote.info())
|
||||
}
|
||||
Request::RemoteAllow { book, allowed } => {
|
||||
let id = match BookId::parse(&book) {
|
||||
Ok(id) => id,
|
||||
Err(e) => return refused(e),
|
||||
};
|
||||
if !self.held().contains_key(id.as_str()) {
|
||||
return Response::Refused(format!(
|
||||
"there are no books called {id}: `wanderbooks books list` lists them"
|
||||
));
|
||||
}
|
||||
self.remote.set_allowed(id.as_str(), allowed);
|
||||
Response::Remote(self.remote.info())
|
||||
}
|
||||
Request::RemoteStatus => Response::Remote(self.remote.info()),
|
||||
Request::RemotePending => Response::RemotePending(self.remote.pending_list()),
|
||||
Request::RemoteDecide { id, approve, post } => {
|
||||
match self.remote.decide(self, &id, approve, post) {
|
||||
Ok((said, approval)) => Response::RemoteDecided { said, approval },
|
||||
Err(why) => Response::Refused(self.hide(why)),
|
||||
}
|
||||
}
|
||||
Request::RemoteApprovals { book } => {
|
||||
Response::RemoteApprovals(self.remote.approvals(self, book.as_deref()))
|
||||
}
|
||||
Request::RemoteSetPost { approval, post } => {
|
||||
match self.remote.set_post(self, &approval, post) {
|
||||
Ok(a) => Response::RemoteApprovals(
|
||||
self.remote
|
||||
.approvals(self, Some(&a.book))
|
||||
.into_iter()
|
||||
.filter(|i| i.id == a.id)
|
||||
.collect(),
|
||||
),
|
||||
Err(why) => Response::Refused(self.hide(why)),
|
||||
}
|
||||
}
|
||||
Request::RemoteMakeKey { book, name, post } => {
|
||||
match self.remote.make_key(self, &book, &name, post) {
|
||||
Ok((token, text)) => Response::RemoteSecret {
|
||||
id: token.id,
|
||||
secret: admin::TokenText(text),
|
||||
said: format!("Key {} made: shown once", token.name),
|
||||
},
|
||||
Err(why) => Response::Refused(self.hide(why)),
|
||||
}
|
||||
}
|
||||
Request::RemoteMakeClient {
|
||||
name,
|
||||
redirect_uris,
|
||||
} => match self.remote.make_client(self, &name, &redirect_uris) {
|
||||
Ok((id, secret)) => Response::RemoteSecret {
|
||||
id,
|
||||
secret: admin::TokenText(secret),
|
||||
said: "Client id and secret made: the secret is shown once".into(),
|
||||
},
|
||||
Err(why) => Response::Refused(self.hide(why)),
|
||||
},
|
||||
Request::TokenList => self.with_principals(|p| {
|
||||
Ok(Response::Tokens(
|
||||
p.tokens().iter().map(admin::TokenInfo::from).collect(),
|
||||
@@ -1337,12 +1436,25 @@ impl Books {
|
||||
Ok(id) => id,
|
||||
Err(e) => return refused(e),
|
||||
};
|
||||
let answer = self.with_principals(|p| {
|
||||
let mut answer = self.with_principals(|p| {
|
||||
p.revoke_if(&book, &name, id.as_deref())
|
||||
.map(|t| Response::TokenRevoked(admin::TokenInfo::from(&t)))
|
||||
});
|
||||
// A web connection's permissions were just changed and the
|
||||
// revoke named the token that was replaced: it is for the
|
||||
// one that replaced it (a revoke during the swap wins).
|
||||
if matches!(answer, Response::Refused(_))
|
||||
&& let Some(newer) = id.as_deref().and_then(|old| self.remote.successor_of(old))
|
||||
{
|
||||
answer = self.with_principals(|p| {
|
||||
p.revoke_if(&book, &name, Some(&newer))
|
||||
.map(|t| Response::TokenRevoked(admin::TokenInfo::from(&t)))
|
||||
});
|
||||
}
|
||||
if let Response::TokenRevoked(t) = &answer {
|
||||
self.forget_sessions_of(&t.id);
|
||||
// What a web connection or key under it held ends now.
|
||||
self.remote.token_gone(&t.id);
|
||||
}
|
||||
answer
|
||||
}
|
||||
@@ -2335,6 +2447,9 @@ const MAX_SESSIONS: usize = 100_000;
|
||||
struct Asked {
|
||||
action: &'static str,
|
||||
subject: String,
|
||||
/// Where the request came from, when it came through the remote door
|
||||
/// (the relay's PROXY header): recorded with a refusal too.
|
||||
from: Option<String>,
|
||||
}
|
||||
|
||||
impl Asked {
|
||||
@@ -2342,8 +2457,15 @@ impl Asked {
|
||||
Self {
|
||||
action: "connect",
|
||||
subject: method.as_str().to_string(),
|
||||
from: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// This request, from the address the relay says (remote door only).
|
||||
fn from(mut self, address: std::net::SocketAddr) -> Self {
|
||||
self.from = Some(address.ip().to_string());
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// A request refused at the door: recorded in the book's access log
|
||||
@@ -2365,7 +2487,12 @@ async fn refused_at_door(
|
||||
why: String,
|
||||
) -> axum::response::Response {
|
||||
use axum::response::IntoResponse;
|
||||
if let Book::Open { access, store, .. } = book {
|
||||
// A request from the remote door with no token that matched is never
|
||||
// written down: anyone on the internet could fill the record.
|
||||
let stranger = asked.from.is_some() && principal.id.is_empty();
|
||||
if let Book::Open { access, store, .. } = book
|
||||
&& !stranger
|
||||
{
|
||||
let access = access.clone();
|
||||
let record = Access {
|
||||
principal,
|
||||
@@ -2378,6 +2505,7 @@ async fn refused_at_door(
|
||||
result: Outcome::Refused(code.into()),
|
||||
head_after: None,
|
||||
agent: None,
|
||||
from: asked.from.clone(),
|
||||
};
|
||||
let written = tokio::task::spawn_blocking(move || {
|
||||
let _inside = inside;
|
||||
@@ -2434,6 +2562,150 @@ fn close_connection(response: &mut axum::response::Response) {
|
||||
);
|
||||
}
|
||||
|
||||
/// Whether the books `id` are open and served.
|
||||
fn book_is_open(books: &Books, id: &str) -> bool {
|
||||
matches!(books.held().get(id), Some(Book::Open { .. }))
|
||||
}
|
||||
|
||||
/// A company's name as a person is told it: the books' own setting, or
|
||||
/// their id when none is set.
|
||||
fn company_name(books: &Books, id: &str) -> String {
|
||||
let named = match books.held().get(id) {
|
||||
Some(Book::Open { served, .. }) => Some(
|
||||
served
|
||||
.settings
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.current()
|
||||
.company
|
||||
.name
|
||||
.clone(),
|
||||
),
|
||||
_ => None,
|
||||
};
|
||||
let unnamed = ledger_config::Company::default().name;
|
||||
match named {
|
||||
Some(n) if !n.trim().is_empty() && n.trim() != unnamed => remote::clean(&n, 60),
|
||||
_ => id.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The live token of `book` called `name` whose id is `id`.
|
||||
fn live_token(books: &Books, book: &str, name: &str, id: &str) -> Option<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()
|
||||
}
|
||||
|
||||
/// The ids of every live token.
|
||||
fn live_token_ids(books: &Books) -> std::collections::BTreeSet<String> {
|
||||
let guard = books.principals.read().unwrap_or_else(|e| e.into_inner());
|
||||
guard
|
||||
.as_ref()
|
||||
.map(|p| p.tokens().iter().map(|t| t.id.clone()).collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn token_is_live(books: &Books, book: &str, name: &str, id: &str) -> bool {
|
||||
live_token(books, book, name, id).is_some()
|
||||
}
|
||||
|
||||
/// The names of the live tokens of `book`.
|
||||
fn token_names(books: &Books, book: &str) -> std::collections::BTreeSet<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()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Make `book`'s token called `name` over with `scopes`, but only if the
|
||||
/// one live under that name is `old_id`: the check and the replacement are
|
||||
/// one hold of the principals, so a revoke that came first is not undone
|
||||
/// (the remote door's raising or lowering of posting).
|
||||
fn replace_token_if_live(
|
||||
books: &Books,
|
||||
book: &BookId,
|
||||
name: &str,
|
||||
old_id: &str,
|
||||
scopes: std::collections::BTreeSet<Scope>,
|
||||
) -> Result<Token, String> {
|
||||
let mut guard = books.principals.write().unwrap_or_else(|e| e.into_inner());
|
||||
let principals = guard.as_mut().map_err(|why| why.clone())?;
|
||||
let live = principals
|
||||
.tokens()
|
||||
.iter()
|
||||
.any(|t| t.book == book.as_str() && t.name == name && t.id == old_id);
|
||||
if !live {
|
||||
return Err("that connection was revoked".into());
|
||||
}
|
||||
match principals.create(book, name, scopes, true) {
|
||||
Ok((token, _)) => Ok(token),
|
||||
Err(e) => {
|
||||
if matches!(e, ledger_store::auth::AuthError::Log(_)) {
|
||||
*guard = books.load_principals();
|
||||
}
|
||||
Err(books.hide(e.to_string()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A token whose text nobody is given: the principal a web connection is
|
||||
/// carried by (its access tokens are the remote door's own).
|
||||
fn make_token(
|
||||
books: &Books,
|
||||
book: &BookId,
|
||||
name: &str,
|
||||
scopes: std::collections::BTreeSet<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 +2717,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 +2789,17 @@ async fn door(
|
||||
let Some(inside) = inside else {
|
||||
unreachable!("an open book was entered above")
|
||||
};
|
||||
let token = books.bearer(headers);
|
||||
// The token, from where this way in keeps them: a static token for the
|
||||
// local socket, a token the remote door made for the remote one
|
||||
// (remote/mod.rs INVARIANT 3, 6). `Err` is the code, the words, and
|
||||
// whether a token was presented that isn't good.
|
||||
let token = match via {
|
||||
Via::Local => books.bearer(headers).map_err(|(c, w)| (c, w, false)),
|
||||
Via::Remote(_) => books
|
||||
.remote
|
||||
.authenticate(books, headers)
|
||||
.map_err(|d| (d.code, d.why, d.invalid_token)),
|
||||
};
|
||||
let principal = |t: &Token| Principal {
|
||||
id: t.id.clone(),
|
||||
kind: "agent".into(),
|
||||
@@ -2540,7 +2823,25 @@ async fn door(
|
||||
}
|
||||
let token = match token {
|
||||
Ok(t) => t,
|
||||
Err((code, why)) => {
|
||||
Err((code, why, invalid)) => {
|
||||
// On the remote door a stranger's request with no good token
|
||||
// is counted, never written to the books' record (a stranger
|
||||
// could fill the disk): it is a 401 with the way to sign in.
|
||||
if matches!(via, Via::Remote(_)) {
|
||||
books.remote.count_unsigned();
|
||||
return Err(Box::new(match books.remote.door() {
|
||||
Some(door) => remote::unauthorized(
|
||||
&door,
|
||||
book,
|
||||
&remote::Denied {
|
||||
code,
|
||||
why,
|
||||
invalid_token: invalid,
|
||||
},
|
||||
),
|
||||
None => axum::http::StatusCode::SERVICE_UNAVAILABLE.into_response(),
|
||||
}));
|
||||
}
|
||||
return Err(refused_at_door(
|
||||
&held,
|
||||
inside,
|
||||
@@ -2554,6 +2855,39 @@ async fn door(
|
||||
.into());
|
||||
}
|
||||
};
|
||||
// The remote door counts a connection's calls before anything else is
|
||||
// asked of them, and counts, never writes, a call refused for rate or
|
||||
// for another company's books: a token holder can't fill the disk with
|
||||
// refusals (remote/mod.rs INVARIANT 3, 8).
|
||||
if let Via::Remote(_) = via {
|
||||
if books
|
||||
.remote
|
||||
.limited(books.remote.call_key(&token), remote::CALLS_PER_MINUTE, 60)
|
||||
{
|
||||
books.remote.count_refused();
|
||||
let mut refused = (
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
[(REFUSED_HEADER, "rate_limited")],
|
||||
"this connection is making too many calls: wait a minute",
|
||||
)
|
||||
.into_response();
|
||||
refused.headers_mut().insert(
|
||||
axum::http::header::RETRY_AFTER,
|
||||
axum::http::HeaderValue::from_static("60"),
|
||||
);
|
||||
return Err(refused.into());
|
||||
}
|
||||
if token.book != book {
|
||||
books.remote.count_refused();
|
||||
return Err((
|
||||
StatusCode::FORBIDDEN,
|
||||
[(REFUSED_HEADER, "wrong_books")],
|
||||
format!("this token is for the books {}, not {book}", token.book),
|
||||
)
|
||||
.into_response()
|
||||
.into());
|
||||
}
|
||||
}
|
||||
if token.book != book {
|
||||
return Err(refused_at_door(
|
||||
&held,
|
||||
@@ -2589,25 +2923,27 @@ async fn upload(
|
||||
let asked = Asked {
|
||||
action: "upload",
|
||||
subject: id.clone(),
|
||||
from: None,
|
||||
};
|
||||
let (held, token, inside) = match door(&books, &book, &asked, request.headers()).await {
|
||||
Ok(passed) => passed,
|
||||
Err(refused) => {
|
||||
// What was sent is read and dropped (up to the most an upload
|
||||
// can be: only this account reaches the socket), so the client
|
||||
// gets the refusal, not a connection cut mid-send.
|
||||
use futures_util::StreamExt;
|
||||
let mut rest = request.into_body().into_data_stream();
|
||||
let mut read = 0u64;
|
||||
while let Some(Ok(chunk)) = rest.next().await {
|
||||
read += chunk.len() as u64;
|
||||
if read > ledger_store::uploads::MAX_UPLOAD {
|
||||
break;
|
||||
let (held, token, inside) =
|
||||
match door(&books, &book, &asked, request.headers(), Via::Local).await {
|
||||
Ok(passed) => passed,
|
||||
Err(refused) => {
|
||||
// What was sent is read and dropped (up to the most an upload
|
||||
// can be: only this account reaches the socket), so the client
|
||||
// gets the refusal, not a connection cut mid-send.
|
||||
use futures_util::StreamExt;
|
||||
let mut rest = request.into_body().into_data_stream();
|
||||
let mut read = 0u64;
|
||||
while let Some(Ok(chunk)) = rest.next().await {
|
||||
read += chunk.len() as u64;
|
||||
if read > ledger_store::uploads::MAX_UPLOAD {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return *refused;
|
||||
}
|
||||
return *refused;
|
||||
}
|
||||
};
|
||||
};
|
||||
let Book::Open {
|
||||
access,
|
||||
uploads,
|
||||
@@ -2695,6 +3031,7 @@ async fn upload(
|
||||
result: outcome.clone(),
|
||||
head_after: None,
|
||||
agent: None,
|
||||
from: None,
|
||||
};
|
||||
let recorded = access.record(&record).is_ok();
|
||||
if !recorded && received.is_ok() {
|
||||
@@ -2783,11 +3120,13 @@ async fn fetch(
|
||||
let asked = Asked {
|
||||
action,
|
||||
subject: subject.clone(),
|
||||
from: None,
|
||||
};
|
||||
let (held, token, inside) = match door(&books, &book, &asked, request.headers()).await {
|
||||
Ok(passed) => passed,
|
||||
Err(refused) => return *refused,
|
||||
};
|
||||
let (held, token, inside) =
|
||||
match door(&books, &book, &asked, request.headers(), Via::Local).await {
|
||||
Ok(passed) => passed,
|
||||
Err(refused) => return *refused,
|
||||
};
|
||||
let Book::Open {
|
||||
access,
|
||||
store,
|
||||
@@ -2877,6 +3216,7 @@ async fn fetch(
|
||||
},
|
||||
head_after: None,
|
||||
agent: None,
|
||||
from: None,
|
||||
};
|
||||
let recorded = access.record(&record).is_ok();
|
||||
(found, recorded)
|
||||
@@ -2961,10 +3301,31 @@ fn disposition(name: &str) -> String {
|
||||
async fn mcp(
|
||||
axum::extract::State(books): axum::extract::State<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 +3336,24 @@ async fn mcp(
|
||||
// a close of the book waits for it, and its tools are counted by the
|
||||
// store (SharedStore INVARIANT 3).
|
||||
let (held, token, inside) =
|
||||
match door(&books, &book, &Asked::connect(&method), request.headers()).await {
|
||||
match door(&books, &book, &asked_of(&method), request.headers(), via).await {
|
||||
Ok(passed) => passed,
|
||||
Err(refused) => return *refused,
|
||||
};
|
||||
let Book::Open { service, board, .. } = &held else {
|
||||
let Book::Open {
|
||||
service,
|
||||
remote_service,
|
||||
board,
|
||||
..
|
||||
} = &held
|
||||
else {
|
||||
unreachable!("the door lets only open books through")
|
||||
};
|
||||
let (service, board) = ((**service).clone(), board.clone());
|
||||
let service = match via {
|
||||
Via::Local => (**service).clone(),
|
||||
Via::Remote(_) => (**remote_service).clone(),
|
||||
};
|
||||
let board = board.clone();
|
||||
let principal = |t: &Token| Principal {
|
||||
id: t.id.clone(),
|
||||
kind: "agent".into(),
|
||||
@@ -2993,6 +3364,11 @@ async fn mcp(
|
||||
let (rewatched, arrival) = inside.arriving(request);
|
||||
request = rewatched;
|
||||
let who = principal(&token);
|
||||
// The remote door keeps no session: whatever session a caller names is
|
||||
// not heard, so a call is the same call however it arrives.
|
||||
if remote_from.is_some() {
|
||||
request.headers_mut().remove(SESSION_HEADER);
|
||||
}
|
||||
let session = request
|
||||
.headers()
|
||||
.get(SESSION_HEADER)
|
||||
@@ -3027,14 +3403,14 @@ async fn mcp(
|
||||
opens
|
||||
};
|
||||
if arrival.was_cut() {
|
||||
return cut_by_the_close(&held, inside, who, &Asked::connect(&method)).await;
|
||||
return cut_by_the_close(&held, inside, who, &asked_of(&method)).await;
|
||||
}
|
||||
if full {
|
||||
return refused_at_door(
|
||||
&held,
|
||||
inside,
|
||||
principal(&token),
|
||||
&Asked::connect(&method),
|
||||
&asked_of(&method),
|
||||
"too_many_sessions",
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"the books server has too many sessions open: end some, then try again".into(),
|
||||
@@ -3046,7 +3422,7 @@ async fn mcp(
|
||||
&held,
|
||||
inside,
|
||||
principal(&token),
|
||||
&Asked::connect(&method),
|
||||
&asked_of(&method),
|
||||
"session_token",
|
||||
StatusCode::FORBIDDEN,
|
||||
"this session was opened with another token".into(),
|
||||
@@ -3054,9 +3430,10 @@ async fn mcp(
|
||||
.await;
|
||||
}
|
||||
let (token_id, token_name) = (token.id.clone(), token.name.clone());
|
||||
request
|
||||
.extensions_mut()
|
||||
.insert(crate::access::Caller { token });
|
||||
request.extensions_mut().insert(crate::access::Caller {
|
||||
token,
|
||||
from: remote_from.map(|a| a.ip().to_string()),
|
||||
});
|
||||
let response = match service.oneshot(request).await {
|
||||
Ok(response) => response,
|
||||
Err(never) => match never {},
|
||||
@@ -3067,7 +3444,7 @@ async fn mcp(
|
||||
// no call ran, nothing is in the journal.
|
||||
if arrival.was_cut() {
|
||||
drop(response);
|
||||
return cut_by_the_close(&held, inside, who, &Asked::connect(&method)).await;
|
||||
return cut_by_the_close(&held, inside, who, &asked_of(&method)).await;
|
||||
}
|
||||
// A session the answer opened is bound to the token that opened it;
|
||||
// one ended, or found gone, is forgotten.
|
||||
@@ -3077,6 +3454,7 @@ async fn mcp(
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner());
|
||||
if session.is_none()
|
||||
&& remote_from.is_none()
|
||||
&& let Some(sid) = response
|
||||
.headers()
|
||||
.get(SESSION_HEADER)
|
||||
@@ -3665,6 +4043,8 @@ async fn serve(
|
||||
() = stops.hurry.cancelled() => {}
|
||||
}
|
||||
shut.cancel();
|
||||
// The remote door goes with the server (remote/mod.rs INVARIANT 1).
|
||||
remote::stop_door(&books);
|
||||
match tokio::time::timeout(HTTP_GRACE, &mut http).await {
|
||||
Ok(Ok(Ok(()))) => {}
|
||||
Ok(Ok(Err(e))) => eprintln!("wanderbooks server: {e}"),
|
||||
@@ -4125,7 +4505,7 @@ mod tests {
|
||||
}
|
||||
|
||||
/// Make the books `id` through the admin request.
|
||||
fn create(books: &Books, id: &str) {
|
||||
fn create(books: &Arc<Books>, id: &str) {
|
||||
match books.admin(Request::Create {
|
||||
id: id.into(),
|
||||
currency: "USD".into(),
|
||||
@@ -4137,7 +4517,7 @@ mod tests {
|
||||
|
||||
/// A token for `book` named `name` with every scope (made, or made
|
||||
/// again): its id and its text.
|
||||
fn token(books: &Books, book: &str, name: &str) -> (String, String) {
|
||||
fn token(books: &Arc<Books>, book: &str, name: &str) -> (String, String) {
|
||||
match books.admin(Request::TokenCreate {
|
||||
book: book.into(),
|
||||
name: name.into(),
|
||||
@@ -4278,7 +4658,7 @@ mod tests {
|
||||
let refused = |books: Arc<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 +5035,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 +5349,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 +5942,7 @@ mod tests {
|
||||
result: Outcome::Refused("closing".into()),
|
||||
head_after: None,
|
||||
agent: None,
|
||||
from: None,
|
||||
};
|
||||
assert!(access.record(&late).is_err());
|
||||
uploads.sweep(now);
|
||||
|
||||
@@ -0,0 +1,290 @@
|
||||
//! Client ID metadata documents: a client whose id is an https address,
|
||||
//! at which it publishes who it is (the IETF draft "OAuth Client ID
|
||||
//! Metadata Document"; plan P15 section 4, rule 2).
|
||||
//!
|
||||
//! ```text
|
||||
//! GOAL: the door can learn what an unknown client says of itself from the
|
||||
//! address it gives as its id, without ever being made to reach into
|
||||
//! the owner's own network or to read more than a small document.
|
||||
//! SOURCE: WB-remote-4 (three ways to introduce a client); the draft above
|
||||
//! (the document's `client_id` is its own address; public clients
|
||||
//! only); plan/p15-app-and-relay.md 4, rule 2.
|
||||
//! INVARIANTS:
|
||||
//! 1. Only an https address with a host and a path, no userinfo and no
|
||||
//! fragment, is fetched; the host's addresses are all looked up
|
||||
//! first, and every one must be a public address (none loopback,
|
||||
//! private, link-local, shared, documentation, multicast or
|
||||
//! unspecified, and no form that carries an IPv4 address inside:
|
||||
//! mapped, compatible (::/96), NAT64, 6to4 (2002::/16)): a name that points
|
||||
//! into the owner's network is refused, and the connection is made to
|
||||
//! the address that was checked, not to a second lookup, and over no
|
||||
//! proxy from the environment.
|
||||
//! 2. No redirect is followed; the answer must be 200, at most
|
||||
//! MAX_DOCUMENT bytes, within FETCH_TIME.
|
||||
//! 3. The document's `client_id` must be exactly the address it was
|
||||
//! fetched from; its `redirect_uris` are 1 to MAX_REDIRECTS valid
|
||||
//! redirect addresses; its `token_endpoint_auth_method`, if given, is
|
||||
//! `none` (a document names no secret).
|
||||
//! SCENARIOS:
|
||||
//! 1. A document that names another client_id, or has no redirects, or
|
||||
//! names a secret method, is refused.
|
||||
//! 2. The checks on an address: loopback, private, link-local, shared and
|
||||
//! mapped addresses are not public; a documentation-free global
|
||||
//! address is.
|
||||
//! ```
|
||||
|
||||
use super::{MAX_REDIRECTS, clean, redirects_fit, valid_redirect};
|
||||
use std::future::Future;
|
||||
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
|
||||
use std::pin::Pin;
|
||||
use std::time::Duration;
|
||||
|
||||
/// The largest document read.
|
||||
pub const MAX_DOCUMENT: usize = 64 * 1024;
|
||||
/// How long a fetch may take.
|
||||
pub const FETCH_TIME: Duration = Duration::from_secs(5);
|
||||
|
||||
/// Where documents come from: the web in service, a table in the tests
|
||||
/// (nothing in a test touches a network).
|
||||
pub trait ClientDocs: Send + Sync {
|
||||
/// The bytes served at `url`, or why not.
|
||||
fn fetch<'a>(
|
||||
&'a self,
|
||||
url: &'a str,
|
||||
) -> Pin<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)
|
||||
// The forms that carry an IPv4 address inside: NAT64 (64:ff9b::/96),
|
||||
// IPv4-compatible (::/96) and 6to4 (2002::/16). None is a place a
|
||||
// document is served from, and each can name a private address.
|
||||
|| (s[0] == 0x0064 && s[1] == 0xff9b)
|
||||
|| s[..6].iter().all(|x| *x == 0)
|
||||
|| s[0] == 0x2002)
|
||||
}
|
||||
|
||||
/// Whether `ip` is a public address (INVARIANT 1).
|
||||
pub fn is_public(ip: IpAddr) -> bool {
|
||||
match ip {
|
||||
IpAddr::V4(a) => v4_public(a),
|
||||
IpAddr::V6(a) => v6_public(a),
|
||||
}
|
||||
}
|
||||
|
||||
impl ClientDocs for WebDocs {
|
||||
fn fetch<'a>(
|
||||
&'a self,
|
||||
url: &'a str,
|
||||
) -> Pin<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());
|
||||
}
|
||||
// No proxy from the environment: a proxy would be handed the
|
||||
// name, not the address that was checked (and the pin below
|
||||
// would be moot). The addresses checked are the ones used.
|
||||
let client = reqwest::Client::builder()
|
||||
.no_proxy()
|
||||
.redirect(reqwest::redirect::Policy::none())
|
||||
.timeout(FETCH_TIME)
|
||||
.https_only(true)
|
||||
// The connection goes to the addresses just checked.
|
||||
.resolve_to_addrs(&host, &addrs)
|
||||
.build()
|
||||
.map_err(|_| "no way to fetch the client's document".to_string())?;
|
||||
let mut response = client
|
||||
.get(url)
|
||||
.header("accept", "application/json")
|
||||
.send()
|
||||
.await
|
||||
.map_err(|_| "the client's document couldn't be fetched".to_string())?;
|
||||
if response.status() != reqwest::StatusCode::OK {
|
||||
return Err(format!(
|
||||
"the client's document answered {}",
|
||||
response.status().as_u16()
|
||||
));
|
||||
}
|
||||
let mut body = Vec::new();
|
||||
while let Some(chunk) = response
|
||||
.chunk()
|
||||
.await
|
||||
.map_err(|_| "the client's document couldn't be read".to_string())?
|
||||
{
|
||||
body.extend_from_slice(&chunk);
|
||||
if body.len() > MAX_DOCUMENT {
|
||||
return Err("the client's document is too large".into());
|
||||
}
|
||||
}
|
||||
Ok(body)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// What a document says (INVARIANT 3): the client's name and redirects.
|
||||
pub fn parse(url: &str, bytes: &[u8]) -> Result<(String, Vec<String>), String> {
|
||||
let doc: serde_json::Value = serde_json::from_slice(bytes)
|
||||
.map_err(|_| "the client's document isn't JSON".to_string())?;
|
||||
if doc.get("client_id").and_then(|v| v.as_str()) != Some(url) {
|
||||
return Err("the document's client_id isn't the address it came from".into());
|
||||
}
|
||||
if doc
|
||||
.get("token_endpoint_auth_method")
|
||||
.and_then(|v| v.as_str())
|
||||
.is_some_and(|m| m != "none")
|
||||
{
|
||||
return Err("a client document may not name a secret".into());
|
||||
}
|
||||
let uris = doc
|
||||
.get("redirect_uris")
|
||||
.and_then(|v| v.as_array())
|
||||
.filter(|a| !a.is_empty() && a.len() <= MAX_REDIRECTS)
|
||||
.ok_or("the document's redirect_uris are missing or too many")?;
|
||||
let mut redirects = Vec::new();
|
||||
for u in uris {
|
||||
let text = u.as_str().unwrap_or_default();
|
||||
if valid_redirect(text).is_none() {
|
||||
return Err("a redirect address in the document can't be used".into());
|
||||
}
|
||||
if !redirects.iter().any(|r| r == text) {
|
||||
redirects.push(text.to_string());
|
||||
}
|
||||
}
|
||||
if !redirects_fit(&redirects) {
|
||||
return Err("the document's redirect addresses together are too long".into());
|
||||
}
|
||||
let host = reqwest::Url::parse(url)
|
||||
.ok()
|
||||
.and_then(|u| u.host_str().map(str::to_string))
|
||||
.unwrap_or_default();
|
||||
let name = clean(
|
||||
doc.get("client_name")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or(""),
|
||||
100,
|
||||
);
|
||||
Ok((if name.is_empty() { host } else { name }, redirects))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn only_public_addresses_are_fetched() {
|
||||
for bad in [
|
||||
"127.0.0.1",
|
||||
"10.1.2.3",
|
||||
"172.16.0.1",
|
||||
"192.168.1.1",
|
||||
"169.254.169.254",
|
||||
"100.64.0.1",
|
||||
"0.0.0.0",
|
||||
"224.0.0.1",
|
||||
"198.18.0.1",
|
||||
"203.0.113.7",
|
||||
"::1",
|
||||
"::",
|
||||
"fe80::1",
|
||||
"fd12::1",
|
||||
"ff02::1",
|
||||
"2001:db8::1",
|
||||
"::ffff:10.0.0.1",
|
||||
"::ffff:127.0.0.1",
|
||||
"::10.0.0.1",
|
||||
"::127.0.0.1",
|
||||
"::8.8.8.8",
|
||||
"2002:c0a8:101::1",
|
||||
"2002:0808:0808::1",
|
||||
"64:ff9b::a00:1",
|
||||
] {
|
||||
assert!(!is_public(bad.parse().unwrap()), "{bad}");
|
||||
}
|
||||
for good in [
|
||||
"8.8.8.8",
|
||||
"93.184.216.34",
|
||||
"2606:4700:4700::1111",
|
||||
"::ffff:8.8.8.8",
|
||||
] {
|
||||
assert!(is_public(good.parse().unwrap()), "{good}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_document_must_be_what_it_says_it_is() {
|
||||
let url = "https://client.example/meta.json";
|
||||
let good = br#"{"client_id":"https://client.example/meta.json","client_name":"Fine","redirect_uris":["https://client.example/cb"]}"#;
|
||||
assert_eq!(
|
||||
parse(url, good).unwrap(),
|
||||
(
|
||||
"Fine".to_string(),
|
||||
vec!["https://client.example/cb".to_string()]
|
||||
)
|
||||
);
|
||||
for bad in [
|
||||
br#"{"client_id":"https://other.example/meta.json","redirect_uris":["https://client.example/cb"]}"# as &[u8],
|
||||
br#"{"client_id":"https://client.example/meta.json","redirect_uris":[]}"#,
|
||||
br#"{"client_id":"https://client.example/meta.json"}"#,
|
||||
br#"{"client_id":"https://client.example/meta.json","redirect_uris":["javascript:alert(1)"]}"#,
|
||||
br#"{"client_id":"https://client.example/meta.json","redirect_uris":["https://c.example/cb#x"]}"#,
|
||||
br#"{"client_id":"https://client.example/meta.json","redirect_uris":["https://c.example/cb"],"token_endpoint_auth_method":"client_secret_post"}"#,
|
||||
b"not json",
|
||||
] {
|
||||
assert!(parse(url, bad).is_err(), "{}", String::from_utf8_lossy(bad));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,642 @@
|
||||
//! The remote door's HTTP side: the listener, the routes (metadata,
|
||||
//! register, authorize, token, a company's MCP path), and the answers.
|
||||
//!
|
||||
//! ```text
|
||||
//! GOAL: every route of the remote door answers only for the one public
|
||||
//! address, in the forms the products expect, and refuses the rest.
|
||||
//! SOURCE: WB-remote-1 to WB-remote-4, WB-remote-8; RFC 9728 and RFC 8414
|
||||
//! (metadata and where it is found, including the forms products
|
||||
//! use that the specification only half allows), RFC 6750 (the
|
||||
//! 401 and its challenge); plan/p15-app-and-relay.md 4 rules 1, 4, 5.
|
||||
//! INVARIANTS:
|
||||
//! 1. A request is answered only while the door is on, and only if its
|
||||
//! Host (under HTTP/2, its authority) is the public address's host
|
||||
//! (421 otherwise); a request that
|
||||
//! has an Origin must have the public address's (403).
|
||||
//! 2. Every address in a metadata document is built from the public
|
||||
//! address the app gave and from nothing in the request.
|
||||
//! 3. The metadata is served at every place the products look: the
|
||||
//! protected-resource document at the root, after the well-known
|
||||
//! path with the resource's path appended, and before it; the
|
||||
//! authorization server's at its two well-known names, with a path
|
||||
//! appended or prepended too.
|
||||
//! 4. A company's path answers only for a company that is allowed and
|
||||
//! open, to a request with a good token (401 and a challenge
|
||||
//! otherwise, to `initialize` as to anything), over plain JSON with
|
||||
//! no session.
|
||||
//! 5. A request body is read to at most MAX_FORM bytes on the sign-in
|
||||
//! routes; a connection waits MAX_HEADER_WAIT for a request's
|
||||
//! headers and lives MAX_LIFE.
|
||||
//! SCENARIOS:
|
||||
//! 1. The metadata is the same whatever Host a caller claims, and a
|
||||
//! claim of another Host is refused.
|
||||
//! 2. `OPTIONS` on a sign-in route answers a browser's preflight.
|
||||
//! ```
|
||||
|
||||
use super::{Authorize, Caller, Denied, Door, OauthError, proxy};
|
||||
use crate::admin::RemoteInfo;
|
||||
use crate::local::{Books, REFUSED_HEADER};
|
||||
use axum::extract::{Extension, Path, Query, State};
|
||||
use axum::http::{HeaderMap, HeaderValue, Method, StatusCode, header};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use std::collections::BTreeMap;
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
/// The largest body of a sign-in route.
|
||||
const MAX_FORM: usize = 64 * 1024;
|
||||
/// How long a connection has to send a request's headers.
|
||||
const MAX_HEADER_WAIT: Duration = Duration::from_secs(15);
|
||||
/// The longest a connection lives.
|
||||
const MAX_LIFE: Duration = Duration::from_secs(30 * 60);
|
||||
|
||||
/// How a request reached the books' door.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(in crate::local) enum Via {
|
||||
/// The local socket (same-user): a static token.
|
||||
Local,
|
||||
/// The remote door: a token this door made, from this caller.
|
||||
Remote(SocketAddr),
|
||||
}
|
||||
|
||||
/// The caller of a connection, from its PROXY header.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Peer(SocketAddr);
|
||||
|
||||
/// Turn the door on at `public_url` (the one address, `https://…`), on
|
||||
/// 127.0.0.1 at `port` (any free one when None). Idempotent for the same
|
||||
/// address; another address restarts it.
|
||||
pub(in crate::local) fn start_door(
|
||||
books: &Arc<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();
|
||||
// The secret of this start: only the app, which is told it over the
|
||||
// admin socket, can say a caller's address (proxy.rs INVARIANT 5).
|
||||
let secret = proxy::new_secret()?;
|
||||
let door = Arc::new(Door {
|
||||
issuer: issuer.clone(),
|
||||
host: host_header_form(&issuer),
|
||||
listening,
|
||||
stop: stop.clone(),
|
||||
secret: secret.clone(),
|
||||
});
|
||||
remote.set_door(Some(door));
|
||||
let app = remote_router(books.clone());
|
||||
let accept_stop = stop.clone();
|
||||
handle.spawn(proxy::accept_loop(
|
||||
listener,
|
||||
stop,
|
||||
secret,
|
||||
move |io, caller| {
|
||||
let app = app.clone().layer(Extension(Peer(caller)));
|
||||
let stop = accept_stop.clone();
|
||||
tokio::spawn(serve_connection(io, app, stop));
|
||||
},
|
||||
));
|
||||
Ok(remote.info())
|
||||
}
|
||||
|
||||
/// Turn the door off: no new connection, and the ones open end.
|
||||
pub(in crate::local) fn stop_door(books: &Arc<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). The host is the `Host` header's; under HTTP/2 there is
|
||||
/// none, and it is the request address's authority (`:authority`).
|
||||
pub(super) fn front(
|
||||
books: &Books,
|
||||
headers: &HeaderMap,
|
||||
uri: &axum::http::Uri,
|
||||
) -> Result<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(),
|
||||
)));
|
||||
};
|
||||
// The host as the public address spells it: lowercase, and the scheme's
|
||||
// own port (443) left off whether or not the caller wrote it.
|
||||
let host = headers
|
||||
.get(header::HOST)
|
||||
.and_then(|h| h.to_str().ok())
|
||||
.or_else(|| uri.authority().map(|a| a.as_str()))
|
||||
.map(str::to_ascii_lowercase)
|
||||
.map(|h| {
|
||||
let plain = door.issuer.starts_with("https://");
|
||||
let default = if plain { ":443" } else { ":80" };
|
||||
h.strip_suffix(default).map(str::to_string).unwrap_or(h)
|
||||
});
|
||||
if host.as_deref() != Some(door.host.as_str()) {
|
||||
return Err(Box::new(no_store(
|
||||
(StatusCode::MISDIRECTED_REQUEST, "not this address").into_response(),
|
||||
)));
|
||||
}
|
||||
Ok(door)
|
||||
}
|
||||
|
||||
async fn preflight(
|
||||
State(books): State<Arc<Books>>,
|
||||
uri: axum::http::Uri,
|
||||
headers: HeaderMap,
|
||||
) -> Response {
|
||||
if let Err(r) = front(&books, &headers, &uri) {
|
||||
return *r;
|
||||
}
|
||||
cors(StatusCode::NO_CONTENT.into_response())
|
||||
}
|
||||
|
||||
fn parse_pairs(text: &str) -> BTreeMap<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>,
|
||||
uri: axum::http::Uri,
|
||||
headers: HeaderMap,
|
||||
body: axum::body::Body,
|
||||
) -> Response {
|
||||
if let Err(r) = front(&books, &headers, &uri) {
|
||||
return *r;
|
||||
}
|
||||
let Ok(bytes) = axum::body::to_bytes(body, MAX_FORM).await else {
|
||||
return oauth_error(OauthError {
|
||||
status: 413,
|
||||
error: "invalid_request",
|
||||
description: "the request is too large".into(),
|
||||
});
|
||||
};
|
||||
let Ok(meta) = serde_json::from_slice::<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, &Caller::new(peer.0.ip()))
|
||||
.await
|
||||
{
|
||||
Ok(out) => cors(json(201, &out)),
|
||||
Err(e) => oauth_error(e),
|
||||
}
|
||||
}
|
||||
|
||||
async fn authorize(
|
||||
State(books): State<Arc<Books>>,
|
||||
Extension(peer): Extension<Peer>,
|
||||
uri: axum::http::Uri,
|
||||
headers: HeaderMap,
|
||||
Query(q): Query<BTreeMap<String, String>>,
|
||||
) -> Response {
|
||||
let door = match front(&books, &headers, &uri) {
|
||||
Ok(d) => d,
|
||||
Err(r) => return *r,
|
||||
};
|
||||
answer(
|
||||
books
|
||||
.remote
|
||||
.authorize(&books, &door, &q, &Caller::new(peer.0.ip()))
|
||||
.await,
|
||||
)
|
||||
}
|
||||
|
||||
async fn wait(
|
||||
State(books): State<Arc<Books>>,
|
||||
uri: axum::http::Uri,
|
||||
headers: HeaderMap,
|
||||
Path(wait): Path<String>,
|
||||
) -> Response {
|
||||
if let Err(r) = front(&books, &headers, &uri) {
|
||||
return *r;
|
||||
}
|
||||
answer(books.remote.wait(&books, &wait))
|
||||
}
|
||||
|
||||
async fn token(
|
||||
State(books): State<Arc<Books>>,
|
||||
Extension(peer): Extension<Peer>,
|
||||
uri: axum::http::Uri,
|
||||
headers: HeaderMap,
|
||||
body: axum::body::Body,
|
||||
) -> Response {
|
||||
let door = match front(&books, &headers, &uri) {
|
||||
Ok(d) => d,
|
||||
Err(r) => return *r,
|
||||
};
|
||||
let bad = |d: &str| {
|
||||
oauth_error(OauthError {
|
||||
status: 400,
|
||||
error: "invalid_request",
|
||||
description: d.into(),
|
||||
})
|
||||
};
|
||||
let Ok(bytes) = axum::body::to_bytes(body, MAX_FORM).await else {
|
||||
return bad("the request is too large");
|
||||
};
|
||||
let form = if headers
|
||||
.get(header::CONTENT_TYPE)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.is_some_and(|t| t.contains("json"))
|
||||
{
|
||||
match serde_json::from_slice::<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, &Caller::new(peer.0.ip()))
|
||||
.await
|
||||
{
|
||||
Ok(out) => cors(json(200, &out)),
|
||||
Err(e) => oauth_error(e),
|
||||
}
|
||||
}
|
||||
|
||||
/// The protected-resource document of a company's address (RFC 9728).
|
||||
fn resource_document(books: &Books, door: &Door, book: &str) -> Option<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, &uri) {
|
||||
Ok(d) => d,
|
||||
Err(r) => return *r,
|
||||
};
|
||||
let not_found = || {
|
||||
cors(no_store(
|
||||
(StatusCode::NOT_FOUND, "not found").into_response(),
|
||||
))
|
||||
};
|
||||
let path = uri.path();
|
||||
if !path.contains("/.well-known/") {
|
||||
return not_found();
|
||||
}
|
||||
if method == Method::OPTIONS {
|
||||
return cors(StatusCode::NO_CONTENT.into_response());
|
||||
}
|
||||
if method != Method::GET && method != Method::HEAD {
|
||||
return cors(no_store(
|
||||
(StatusCode::METHOD_NOT_ALLOWED, "GET only").into_response(),
|
||||
));
|
||||
}
|
||||
if let Some(at) = path.find(PRM) {
|
||||
let before = &path[..at];
|
||||
let after = &path[at + PRM.len()..];
|
||||
let resource = if after.is_empty() { before } else { after };
|
||||
let resource = resource.trim_end_matches('/');
|
||||
let book = match resource
|
||||
.strip_prefix("/b/")
|
||||
.and_then(|r| r.strip_suffix("/mcp"))
|
||||
{
|
||||
Some(b) => Some(b.to_string()),
|
||||
None if resource.is_empty() => {
|
||||
// The root: the company, if only one is on offer.
|
||||
books.remote.only_open_book(&books)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
return match book.and_then(|b| resource_document(&books, &door, &b)) {
|
||||
Some(doc) => cors(json(200, &doc)),
|
||||
None => not_found(),
|
||||
};
|
||||
}
|
||||
if path.contains("/.well-known/oauth-authorization-server")
|
||||
|| path.contains("/.well-known/openid-configuration")
|
||||
{
|
||||
return cors(json(200, &server_document(&door)));
|
||||
}
|
||||
not_found()
|
||||
}
|
||||
|
||||
/// A company's MCP path on the remote door.
|
||||
async fn remote_mcp(
|
||||
State(books): State<Arc<Books>>,
|
||||
Extension(peer): Extension<Peer>,
|
||||
Path(book): Path<String>,
|
||||
request: axum::extract::Request,
|
||||
) -> Response {
|
||||
let door = match front(&books, request.headers(), request.uri()) {
|
||||
Ok(d) => d,
|
||||
Err(r) => return *r,
|
||||
};
|
||||
if let Some(origin) = request.headers().get(header::ORIGIN)
|
||||
&& origin.to_str().ok() != Some(door.issuer.as_str())
|
||||
{
|
||||
return no_store((StatusCode::FORBIDDEN, "origin not allowed").into_response());
|
||||
}
|
||||
// A company not on offer is not there at all.
|
||||
if !books.remote.is_allowed(&book) {
|
||||
return no_store(
|
||||
(
|
||||
StatusCode::NOT_FOUND,
|
||||
[(REFUSED_HEADER, "no-such-books")],
|
||||
"there are no books here",
|
||||
)
|
||||
.into_response(),
|
||||
);
|
||||
}
|
||||
crate::local::mcp_via(books, book, request, Via::Remote(peer.0)).await
|
||||
}
|
||||
|
||||
/// The 401 of a request with no good token (INVARIANT 3 of mod.rs): the
|
||||
/// challenge names the company's protected-resource metadata, so a client
|
||||
/// that was never told anything can find where to sign in.
|
||||
pub(in crate::local) fn unauthorized(door: &Door, book: &str, denied: &Denied) -> Response {
|
||||
let mut challenge = format!(
|
||||
"Bearer resource_metadata=\"{}/.well-known/oauth-protected-resource/b/{}/mcp\", scope=\"books:read books:write\"",
|
||||
door.issuer,
|
||||
book.chars()
|
||||
.filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_')
|
||||
.collect::<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,109 @@
|
||||
//! The two pages a person's browser sees during a sign-in: "look at
|
||||
//! Wanderbooks", and a plain problem. Plain words; the person may not know
|
||||
//! what any of this is called, and the word is "assistant".
|
||||
//!
|
||||
//! ```text
|
||||
//! GOAL: the browser page of a sign-in never approves anything and never
|
||||
//! carries text a stranger wrote unescaped.
|
||||
//! SOURCE: WB-remote-5 (approval is the person's, in the app's window);
|
||||
//! plan/p15-app-and-relay.md 3.3, D-83.
|
||||
//! INVARIANTS:
|
||||
//! 1. Every piece of text from outside (a client's name, a company's
|
||||
//! name) is HTML-escaped; the page has no script, no form, no link
|
||||
//! and no button that approves: it says to look at Wanderbooks and
|
||||
//! looks again by itself (a refresh), until the person decides.
|
||||
//! 2. The page shows the request's own short code, for the person to match
|
||||
//! with the window's card; it never says a request is a known product.
|
||||
//! 3. The page's only address is the relative one of the waiting
|
||||
//! request; nothing is built from the request's Host.
|
||||
//! ```
|
||||
|
||||
/// Escape text for HTML.
|
||||
pub fn esc(text: &str) -> String {
|
||||
let mut out = String::with_capacity(text.len());
|
||||
for c in text.chars() {
|
||||
match c {
|
||||
'&' => out.push_str("&"),
|
||||
'<' => out.push_str("<"),
|
||||
'>' => out.push_str(">"),
|
||||
'"' => out.push_str("""),
|
||||
'\'' => out.push_str("'"),
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn shell(title: &str, refresh: Option<&str>, body: &str) -> String {
|
||||
let head = refresh
|
||||
.map(|u| format!("<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, and match
|
||||
/// the code. What is known is said in neutral words: where the assistant
|
||||
/// will be sent back to first, then what it calls itself (its own word,
|
||||
/// escaped, never a name of a product made from the address).
|
||||
pub fn waiting(host: &str, name: &str, company: &str, code: &str, wait: &str) -> String {
|
||||
let calls = if name.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(" It calls itself \u{201c}{}\u{201d}.", esc(name))
|
||||
};
|
||||
shell(
|
||||
"Look at Wanderbooks",
|
||||
Some(&format!("/authorize/wait/{wait}")),
|
||||
&format!(
|
||||
"<h1>Look at Wanderbooks</h1>\
|
||||
<p>An assistant that will be sent back to <strong>{}</strong> is asking to connect to <strong>{}</strong>.{calls}</p>\
|
||||
<p>Your code is <strong style=\"font-size:1.6rem;letter-spacing:.1em\">{}</strong></p>\
|
||||
<p>Open the Wanderbooks window on your computer. Choose <strong>Allow</strong> \
|
||||
only if it shows this same code. This page continues by itself when you do.</p>\
|
||||
<p>If the code is different, or you didn't just ask an assistant to connect, \
|
||||
choose <strong>Don't allow</strong>, or just close this page.</p>",
|
||||
esc(host),
|
||||
esc(company),
|
||||
esc(code)
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/// A plain problem, with nothing to click.
|
||||
pub fn problem(title: &str, text: &str) -> String {
|
||||
shell(
|
||||
title,
|
||||
None,
|
||||
&format!("<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>",
|
||||
"<b>co</b>",
|
||||
"123 456",
|
||||
"w_abc",
|
||||
);
|
||||
assert!(!page.contains("<script>alert"));
|
||||
assert!(!page.contains("<img src=x>"));
|
||||
assert!(page.contains("<script>"));
|
||||
assert!(page.contains("123 456"));
|
||||
assert!(page.contains("<b>co"));
|
||||
assert!(!page.contains("<form"));
|
||||
assert!(page.contains("url=/authorize/wait/w_abc"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,353 @@
|
||||
//! 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:
|
||||
//! 5. Every connection starts with this start's secret, then the header:
|
||||
//! the first SECRET_LEN bytes are the 64 lowercase hex characters the
|
||||
//! server gave the app over the admin socket when the door started
|
||||
//! (`proxy_secret` of the remote status), compared in constant time. A
|
||||
//! connection that begins with anything else is dropped before a byte
|
||||
//! of anything is read, so only the app's relay line can state a
|
||||
//! caller's address: another process on this computer that finds the
|
||||
//! port cannot say a caller is anyone, nor use up what an address is
|
||||
//! limited to by saying it is another.
|
||||
//! 1. Every connection to the remote door, after the secret, 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,
|
||||
];
|
||||
|
||||
/// The length of the secret every connection begins with: 64 lowercase
|
||||
/// hexadecimal characters, the text of 32 random bytes.
|
||||
pub const SECRET_LEN: usize = 64;
|
||||
|
||||
/// A secret for one start of the door: 32 random bytes as 64 lowercase hex
|
||||
/// characters.
|
||||
pub fn new_secret() -> Result<String, String> {
|
||||
let mut bytes = [0u8; SECRET_LEN / 2];
|
||||
getrandom::getrandom(&mut bytes).map_err(|_| "the system gave no randomness".to_string())?;
|
||||
Ok(bytes.iter().map(|b| format!("{b:02x}")).collect())
|
||||
}
|
||||
|
||||
/// 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,
|
||||
/// It did not begin with this start's secret.
|
||||
BadSecret,
|
||||
}
|
||||
|
||||
/// Read this start's secret from the front of `stream` and compare it in
|
||||
/// constant time (INVARIANT 5).
|
||||
pub async fn read_secret<R: AsyncRead + Unpin>(
|
||||
stream: &mut R,
|
||||
secret: &str,
|
||||
) -> Result<(), Refused> {
|
||||
use subtle::ConstantTimeEq;
|
||||
let mut given = [0u8; SECRET_LEN];
|
||||
stream
|
||||
.read_exact(&mut given)
|
||||
.await
|
||||
.map_err(|_| Refused::Cut)?;
|
||||
let same: bool = given.as_slice().ct_eq(secret.as_bytes()).into();
|
||||
if secret.len() == SECRET_LEN && same {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Refused::BadSecret)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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, after the
|
||||
/// secret; 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,
|
||||
secret: String,
|
||||
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();
|
||||
let secret = secret.clone();
|
||||
tokio::spawn(async move {
|
||||
let read = tokio::time::timeout(HEADER_WAIT, async {
|
||||
read_secret(&mut io, &secret).await?;
|
||||
read_header(&mut io).await
|
||||
})
|
||||
.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 a_connection_must_begin_with_this_starts_secret() {
|
||||
let secret = new_secret().unwrap();
|
||||
assert_eq!(secret.len(), SECRET_LEN);
|
||||
assert!(
|
||||
secret
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
|
||||
);
|
||||
assert_ne!(secret, new_secret().unwrap());
|
||||
let mut good = secret.clone().into_bytes();
|
||||
good.extend(b"rest");
|
||||
let mut slice = &good[..];
|
||||
assert_eq!(read_secret(&mut slice, &secret).await, Ok(()));
|
||||
assert_eq!(slice, b"rest");
|
||||
// Another secret, one byte off, no secret, and a short one.
|
||||
let mut off = secret.clone().into_bytes();
|
||||
off[63] = if off[63] == b'0' { b'1' } else { b'0' };
|
||||
for (what, bytes) in [("off by one", off), ("other text", vec![b'x'; SECRET_LEN])] {
|
||||
let mut slice = &bytes[..];
|
||||
assert_eq!(
|
||||
read_secret(&mut slice, &secret).await,
|
||||
Err(Refused::BadSecret),
|
||||
"{what}"
|
||||
);
|
||||
}
|
||||
let mut short = &b"abc"[..];
|
||||
assert_eq!(read_secret(&mut short, &secret).await, Err(Refused::Cut));
|
||||
}
|
||||
|
||||
#[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
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -477,6 +477,87 @@ didn't open, with why). Protocol version 1: the requests are new, the
|
||||
that ended is not listed; nothing is kept across a server restart.
|
||||
`wanderbooks doctor` prints these lines under "Assistants connected".
|
||||
|
||||
### The remote door (plan/p15-app-and-relay.md section 4, unit B1; WB-remote-1 to 10)
|
||||
|
||||
Web assistants (Claude and ChatGPT on the web; Gemini, Grok and muse.ai best
|
||||
effort) call connectors from their vendor's cloud over HTTPS. The books server
|
||||
has a second HTTP listener for them, on **127.0.0.1 only and off until the app
|
||||
asks** (the relay, unit B2, and the app's line to it with its certificate, unit
|
||||
B3, put it on the internet). The admin socket's requests (owner only) are its
|
||||
whole control:
|
||||
|
||||
- `remote_start { public_url, port? }` turns it on as the **one public address**
|
||||
(`https://name`, no path: the issuer), on a free loopback port unless one is
|
||||
given, and answers where it listens and this start's `proxy_secret` (64 lowercase
|
||||
hex characters, for the app only, never printed in a log); the same address
|
||||
again is a no-op that answers the same secret, another restarts it with a new
|
||||
one. `remote_stop` turns it off (it also stops when the server closes).
|
||||
`remote_allow { book, allowed }` offers a company or withdraws it;
|
||||
`remote_status` says all of it.
|
||||
- `remote_pending` lists the assistants waiting to be allowed (what each calls
|
||||
itself, cleaned and short; the address it is sent back to; whether that host is
|
||||
a known vendor's; its six-digit code, which its browser page shows too; the
|
||||
caller's address; the company; whether posting was asked; the time left);
|
||||
`remote_decide { id, approve, post }` is the person's answer, and every Allow
|
||||
makes a new approval with exactly the permissions given. `remote_approvals { book? }` lists the connections
|
||||
allowed; `remote_set_post { approval, post }` raises or lowers one;
|
||||
`remote_make_key { book, name, post }` makes a key for a product that takes only
|
||||
a key, and `remote_make_client { name, redirect_uris }` a client id and secret
|
||||
to type into one: each secret is shown once, in the answer, never again.
|
||||
|
||||
**Every connection begins with this start's secret, then the relay's PROXY
|
||||
protocol version 2 header** (the exact form `crates/relay` writes: TCP over IPv4
|
||||
or IPv6, no extensions). The secret is the 64 characters of `proxy_secret` from
|
||||
`remote_start` or `remote_status`, written as they are, as the very first 64
|
||||
bytes, before anything; only the app, which is told it over the owner-only admin
|
||||
socket, can say a caller's address, not another process on this computer that
|
||||
finds the port. The address in the header is the caller's, and is what the access
|
||||
record (`from`) and the limits use (an IPv6 caller is counted by its /64). Anything
|
||||
else, a wrong secret included, is dropped before a byte of HTTP is read; no
|
||||
`X-Forwarded-For` is ever read. A request whose `Host` is not the public
|
||||
address's host is 421; one with another `Origin` is 403.
|
||||
|
||||
Routes (all for the public address only):
|
||||
|
||||
| Route | What |
|
||||
|---|---|
|
||||
| `/.well-known/oauth-protected-resource` (root, `…/b/{book}/mcp` appended, or `/b/{book}/mcp/…` before it) | RFC 9728 metadata for a company's address (the root's only while one company is offered) |
|
||||
| `/.well-known/oauth-authorization-server`, `/.well-known/openid-configuration` (and the same with a path either side) | RFC 8414 metadata; every address in it is the issuer's |
|
||||
| `POST /register` | dynamic registration (RFC 7591): 1 to 20 redirect addresses, 201 |
|
||||
| `GET /authorize` | always parks the request (never approves, and never because the product was allowed before: D-90) and answers a page with the request's code that says to look at Wanderbooks; an error is a page for a client nobody approved, a 302 for one the person has |
|
||||
| `GET /authorize/wait/{id}` | the page's own look: the same page while waiting, then a 302 with `code` (or `error=access_denied`), once |
|
||||
| `POST /token` | `authorization_code` (PKCE S256, `resource` checked) and `refresh_token` (rotated; one used twice ends its family); a client secret as Basic or in the body |
|
||||
| `/b/{book}/mcp` | the company's MCP, stateless, plain JSON, for a good token only: 401 with `WWW-Authenticate: Bearer resource_metadata="…"` otherwise, `initialize` included |
|
||||
|
||||
A client is one of: a client ID metadata document (an https `client_id`, fetched
|
||||
only when every address of its host is public, no redirect, no proxy, at most 64
|
||||
KiB, five seconds, and only when a sign-in begins, never at `/token`); a dynamic
|
||||
registration; or a client id and secret the app made. The redirect address must
|
||||
equal a registered one exactly (at most 512 bytes each, 4 KiB together). A
|
||||
registration is held in memory and reaches the file only when the person allows a
|
||||
sign-in of it. Access tokens last ten
|
||||
minutes and are kept in memory; refresh tokens last sixty days since last use and
|
||||
are kept (hashed) in `auth/remote.json`, 0600, so a refresh after the app was
|
||||
closed for days still works. Nothing is kept as text but a hash.
|
||||
|
||||
**An approval** is the owner's decision about one sign-in, a company and its
|
||||
permissions: one token of the books' principals (named `web-…`, listed by
|
||||
`token_list` and revoked by id like any, which ends every token and refresh token
|
||||
made under it at that moment) plus a record naming the connection. It is never
|
||||
reused (D-90): every new sign-in, of a product registering again or not, is asked
|
||||
in the window, with a short code to match with the browser's page, and an Allow
|
||||
makes a new approval with exactly the permissions ticked then. The window says
|
||||
where an assistant will be sent back to, never that it is a known product. A web approval grants `books:read` and `books:write`
|
||||
(drafts); `books:post` only when the person turns it on; `books:admin` never. A
|
||||
stranger's unsigned request is a 401 and is counted, not written to the access
|
||||
record, and a good token's refusal for rate or for another company's books is
|
||||
counted, not written (its other refusals are recorded with the caller's address). Calls go
|
||||
through the same server as local ones (`call_tool`): a write needs its
|
||||
`request_key`, a repeat returns the first answer. Nothing bans an address; what
|
||||
a request creates is bounded (2000 clients, 20 waiting requests and 5 per address,
|
||||
which give way to a newer one rather than turn it away, 600 calls a minute per
|
||||
approval, and so on).
|
||||
|
||||
## Server instructions
|
||||
|
||||
The MCP `initialize` response carries an `instructions` string, the
|
||||
@@ -518,6 +599,16 @@ overrides and zero-width spaces are dropped), cut to 56 characters.
|
||||
`instructions_budget` (the longest rule, every parties setting) and
|
||||
`the_company_name_is_one_plain_line` check it.
|
||||
|
||||
Some products keep only the first 512 characters of the instructions
|
||||
(ChatGPT) and one is reported to drop them (claude.ai, unverified since), so
|
||||
**the company and the entry point also begin the description of the tools a
|
||||
model reaches for first** (`books.start`, `books.handbook`, `books.chart`,
|
||||
`books.show`, `books.digest`, `books.search_entries`, `books.draft_entry`,
|
||||
`books.post_entry`): "For the books of Acme: call books.start first in every
|
||||
session." (at most 160 characters, added by `list_tools` to the tool's own text
|
||||
of at most 700), for local and remote callers alike.
|
||||
`the_company_and_the_entry_point_are_in_the_first_tools_too` pins both.
|
||||
|
||||
The long guidance is the **handbook**, compiled in from
|
||||
`ledger-mcp/handbook/*.md`, with the receipt rule in force rendered in:
|
||||
|
||||
|
||||
+15
-1
@@ -255,9 +255,23 @@ Three new rows, none above changed status, and the floor stands.
|
||||
|---|---|---|---|
|
||||
| Books home: a visible folder per book, `<Documents>/Wanderbooks/<id>`, holding `AGENTS.md`, `CLAUDE.md`, `.mcp.json` and `.claude/settings.json` and nothing of the books | A QBO/Xero company has no counterpart; the point is the agent's workplace (D-27) | partial | `books_home_holds_no_books_data`, `a_books_home_made_again_keeps_what_a_person_kept` (`crates/ledger-host/tests/books_home.rs`); `partial` until the macOS home is tried |
|
||||
| Agent dock: Claude Code or Codex in a terminal along the bottom of the viewer, started in the books home; never required | QBO's assistant panel is a cross-check only | partial | `dock_runs_the_chosen_agent`, `agent_missing_offers_the_installer` (`crates/ledger-gui/tests/dock.rs`); Linux checked; macOS by the CI run; Windows not offered (ConPTY unchecked) |
|
||||
| Assistants in the window: each company's state (none, connected, working) as a shape and a word, "Ask your assistant" where a button that edits would be, the Connect page (a row per local tool, the keys with who is on each, Revoke), and a warning before closing the window or a tab with an assistant connected (plan P15 3.3, D-79) | QBO's "Accountant" invitations and Xero's "Advisor" access are a cross-check only | partial | WB-assist-1 to WB-assist-4; `crates/ledger-gui/tests/assistants.rs`; local assistants only: the web half is plan units B1 and B3, the Claude desktop extension C1 |
|
||||
| Assistants in the window: each company's state (none, connected, working) as a shape and a word, "Ask your assistant" where a button that edits would be, the Connect page (a row per local tool, the keys with who is on each, Revoke), and a warning before closing the window or a tab with an assistant connected (plan P15 3.3, D-79) | QBO's "Accountant" invitations and Xero's "Advisor" access are a cross-check only | partial | WB-assist-1 to WB-assist-4; `crates/ledger-gui/tests/assistants.rs`; local assistants, and (unit B1) the question to the person when a web assistant asks and what each web connection may do; the web switch, address and steps are unit B3's, the Claude desktop extension C1 |
|
||||
| First run with no terminal: the viewer sets up the private folder, the owner passphrase, the first books and an agent | QBO's "set up your company" flow | partial | `first_run_onboards_with_no_terminal` (`crates/ledger-gui/tests/welcome.rs`); the AppImage's whole path is the EM's to try on a clean machine |
|
||||
|
||||
## P15 B1: the remote door (2026-11-21, D-83, D-86)
|
||||
|
||||
One new row below; none above changed status, so the floor stands. A second
|
||||
HTTP door in the books server, on 127.0.0.1 and off until the app asks, is the
|
||||
sign-in server web assistants knock on (WB-remote-1 to WB-remote-10,
|
||||
`docs/mcp-interface.md` "The remote door"); the window asks the person when a
|
||||
web assistant wants to connect. It is `partial`: the door is not on the
|
||||
internet until the relay's client and certificates (unit B3) exist, and no
|
||||
product's own sign-in has been tried against it yet.
|
||||
|
||||
| Area | Counterpart (a cross-check, not the spec) | Status | Notes |
|
||||
|---|---|---|---|
|
||||
| Web assistants reach a company over HTTPS and sign in with OAuth 2.1, approved by the person in the app's window; read and draft by default, posting per connection | QBO's and Xero's "connected apps" consent screens are a cross-check only | partial | WB-remote-1 to WB-remote-10, WB-assist-5; `ledger-mcp` unit tests in `src/local/remote/` (`tests.rs`, `proxy.rs`, `cimd.rs`, `pages.rs`), `ledger-gui` `tests/assistants.rs`; open: reached through the relay (B3), tried with Claude and ChatGPT on the web, uploads and downloads over this door |
|
||||
|
||||
## P15 T1: every write is one transaction, exactly once (2026-11-21, D-88, D-89)
|
||||
|
||||
| Area | Counterpart (a cross-check, not the spec) | Status | Notes |
|
||||
|
||||
@@ -88,11 +88,41 @@ when it connected and last acted, and "Revoke", asked once, which calls what
|
||||
`wanderbooks token revoke` calls (the server ends the key and the sessions on
|
||||
it; its copy in the token file is removed). The window writes no books. The
|
||||
web half of the page (the switch, the address, the steps for Claude and
|
||||
ChatGPT) is plan unit B3's; `connect::State::web_section` is its place, and
|
||||
the "Claude desktop app" row (a one-click extension) is unit C1's.
|
||||
ChatGPT) is plan unit B3's, and the "Claude desktop app" row (a one-click
|
||||
extension) is unit C1's. What unit B1 puts in `connect::State::web_section` is
|
||||
the question to the person when a web assistant asks to connect (WB-remote-5):
|
||||
a card that says who is asking, where it is sent back to, the address it asked
|
||||
from and what it will be able to do (read and draft; posting only if ticked),
|
||||
with "Allow" and "Don't allow", over any page of the company
|
||||
(`connect::State::web_prompt`) and on the Connect page; and, for each web
|
||||
connection allowed, what it may do, with "Let it post entries" and "Stop
|
||||
letting it post". Revoke is the same row of "Who can reach these books".
|
||||
*Enforced:* `ledger_gui::connect::State::show`, `ledger_host::commands`
|
||||
(`bridge_serve_args`, `command_line`, `ensure_key`, `forget_token_file`),
|
||||
`ledger_host::app_server::AppServer::revoke_token`.
|
||||
*Checked:* `ledger-gui` `tests/assistants.rs`
|
||||
(`the_top_bar_state_opens_the_connect_page_which_lists_and_revokes`,
|
||||
`the_connect_buttons_do_what_connect_does`).
|
||||
|
||||
**WB-assist-5** The company's name and "call books.start first" stand in the first tools' own descriptions too.
|
||||
|
||||
```text
|
||||
GOAL: a product that keeps only the first 512 characters of the server's
|
||||
instructions, or drops them, still tells its model which company this is
|
||||
and where to begin.
|
||||
SOURCE: plan/p15-app-and-relay.md 3.4 (ChatGPT uses only the first 512
|
||||
characters; claude.ai is reported to drop them, unverified since).
|
||||
INVARIANTS:
|
||||
1. The first 512 characters of the instructions stand alone and name the
|
||||
company, books.start and books.handbook.
|
||||
2. The descriptions of books.start and of the tools a model reaches for
|
||||
first begin with the company and "call books.start first in every
|
||||
session", for local and remote callers alike; the lead is at most 160
|
||||
characters.
|
||||
SCENARIOS:
|
||||
1. A list of tools names the company in each of the first tools and in
|
||||
no other.
|
||||
```
|
||||
|
||||
*Enforced:* `first_tools_lead`, `connect_text`, `list_tools` (the server's `BooksServer`).
|
||||
*Checked:* `ledger-mcp` unit test `the_company_and_the_entry_point_are_in_the_first_tools_too`.
|
||||
@@ -0,0 +1,353 @@
|
||||
# Claims: the remote door
|
||||
|
||||
The product rules of how web assistants (Claude and ChatGPT on the web; Gemini,
|
||||
Grok and muse.ai best effort) reach a company, and the sign-in behind it (plan
|
||||
P15, unit B1; decisions D-81, D-83, D-86, D-88 in `plan/p15-app-and-relay.md`;
|
||||
the ten sign-in rules of its section 4). No authority outside this product
|
||||
states them: they are wanderbooks' own (`WB-remote-<n>`). They stand on public
|
||||
specifications for the protocol (OAuth 2.1, RFC 7636, 7591, 8414, 8707, 9728 and
|
||||
9700, the MCP authorization specification) and on nothing else. The code is the
|
||||
`remote` module of the books server (`crates/ledger-mcp/src/local/remote/`).
|
||||
|
||||
The door listens on 127.0.0.1 only, off until the app asks. The relay (unit B2)
|
||||
and the app's line to it with its certificate (unit B3) put it on the internet;
|
||||
the relay writes the caller's address in a PROXY header before the caller's own
|
||||
bytes (WB-relay-6), and this door reads it.
|
||||
|
||||
Rules: none from bookspec.
|
||||
|
||||
---
|
||||
|
||||
## Product rules
|
||||
|
||||
**WB-remote-1** The door is off until asked, is loopback only, and knows each caller's address only from the relay's header.
|
||||
|
||||
```text
|
||||
GOAL: nothing reaches the books from the internet unless the app turned the
|
||||
door on, and the address of a caller is the one place no caller can
|
||||
write.
|
||||
SOURCE: WB-relay-6 (the caller's address), D-80, D-83 in
|
||||
plan/p15-app-and-relay.md; the PROXY protocol specification version 2;
|
||||
plan/p15-app-and-relay.md section 4, rule 8.
|
||||
INVARIANTS:
|
||||
1. The door listens only after a RemoteStart admin request, on 127.0.0.1;
|
||||
it stops on RemoteStop and when the server closes. It serves a company
|
||||
only while that company is offered (RemoteAllow) and open.
|
||||
2. Every connection begins with this start's secret, then the relay's exact
|
||||
header (a version 2 PROXY header for TCP over IPv4 or IPv6); anything
|
||||
else, a cut header, or silence for five seconds is dropped before a
|
||||
byte of HTTP is read. The secret is 64 lowercase hex characters made
|
||||
for each start of the door, given to the app over the owner-only admin
|
||||
socket (`proxy_secret` of the remote status, shown nowhere else and
|
||||
never in a log) and compared in constant time: so only the app's relay
|
||||
line can state a caller's address, not another process on this
|
||||
computer that finds the port. What the app (unit B3) writes first on
|
||||
every connection is exactly those 64 characters, then the header.
|
||||
3. The address in the header is what the access record and the limits use;
|
||||
no HTTP header (X-Forwarded-For and its kind) is read for it; a second
|
||||
header sent inside the caller's own bytes is HTTP text, refused as such.
|
||||
4. Connections are bounded, and a request's headers must arrive in time.
|
||||
SCENARIOS:
|
||||
1. A call through the door is recorded with the address in the header, not
|
||||
with the one a caller's forwarding headers claim.
|
||||
2. A connection with no secret, a wrong one, no header, or a header inside
|
||||
a request, gets nothing.
|
||||
3. The door is off before it is asked, and refuses connections after it is
|
||||
stopped.
|
||||
```
|
||||
|
||||
*Enforced:* `read_secret`, `new_secret`, `read_header`, `accept_loop`, `start_door`, `stop_door`, `Asked` (the server's `local` module).
|
||||
*Checked:* `ledger-mcp` unit tests `the_relays_header_reads_back_its_source`, `a_connection_must_begin_with_this_starts_secret`, `a_connection_without_the_secret_is_dropped_before_anything_is_read`, `anything_but_the_exact_form_is_refused`, `the_recorded_address_is_the_relays_and_a_forged_one_changes_nothing`, `the_door_is_off_until_asked_and_stops_when_told`.
|
||||
|
||||
**WB-remote-2** There is one public address, and every address the door says is built from it.
|
||||
|
||||
```text
|
||||
GOAL: a product that learns where to sign in is never told another place,
|
||||
whatever it sends in its request.
|
||||
SOURCE: RFC 9728 and RFC 8414 (the metadata documents and where they are
|
||||
found); plan/p15-app-and-relay.md section 4, rule 1 (a year of
|
||||
breakage in another project came of building these from the request).
|
||||
INVARIANTS:
|
||||
1. The issuer is the address given to RemoteStart (https, a host, no path)
|
||||
and no other; a request for another Host is refused (421). The host is
|
||||
the `Host` header's; under HTTP/2, which has none, it is the request
|
||||
address's authority, and the same check is made on it.
|
||||
2. The protected-resource document is served at the root, after the
|
||||
well-known name 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. Every address in them is the issuer's.
|
||||
3. A token, code or refresh token made under one issuer is refused under
|
||||
another.
|
||||
SCENARIOS:
|
||||
1. Every place a product looks answers the same document.
|
||||
2. The public address changes: what was made under the old one stops.
|
||||
```
|
||||
|
||||
*Enforced:* `start_door`, `front`, `server_document`, `resource_document`, `Remote::authenticate`.
|
||||
*Checked:* `ledger-mcp` unit tests `the_metadata_is_the_pinned_address_at_every_place_products_look`, `an_expired_token_and_a_token_for_another_issuer_are_refused`, `the_host_is_read_from_the_authority_when_there_is_no_host_header`.
|
||||
|
||||
**WB-remote-3** An unsigned request is a 401 that says where to sign in, `initialize` included, and is never written to the books' record.
|
||||
|
||||
```text
|
||||
GOAL: a product that was told nothing finds the sign-in; a stranger cannot
|
||||
fill the disk by knocking.
|
||||
SOURCE: RFC 6750 (the challenge), RFC 9728; plan/p15-app-and-relay.md section
|
||||
4, rule 4 (one product shows "connected" and never signs in when its
|
||||
first request is let through).
|
||||
INVARIANTS:
|
||||
1. A request to a company's path with no token, a wrong one or an expired
|
||||
one is a 401 whose WWW-Authenticate names that company's
|
||||
protected-resource metadata; a presented bad token adds
|
||||
error="invalid_token". `initialize` is no exception.
|
||||
2. A key made for the local socket opens nothing on this door.
|
||||
3. Such a request is counted in memory and not written to the access record
|
||||
(a request with a good token that is refused is).
|
||||
SCENARIOS:
|
||||
1. initialize, a tool call and a notification, unsigned, are each 401.
|
||||
2. Twenty more unsigned requests leave the access record where it was.
|
||||
```
|
||||
|
||||
*Enforced:* `unauthorized`, `Remote::authenticate`, `door` (the server's `local` module).
|
||||
*Checked:* `ledger-mcp` unit test `an_unsigned_request_is_a_401_that_says_where_to_sign_in_initialize_included`.
|
||||
|
||||
**WB-remote-4** A client introduces itself in one of three ways, and is sent back only to an address it registered.
|
||||
|
||||
```text
|
||||
GOAL: any of the products can sign in, and none can be sent to an address a
|
||||
stranger chose.
|
||||
SOURCE: RFC 7591 (dynamic registration), the IETF draft for OAuth client ID
|
||||
metadata documents, RFC 6749 section 10.15 (open redirectors), RFC
|
||||
7636 (PKCE), RFC 8707 (resource); plan/p15-app-and-relay.md section 4,
|
||||
rules 2 and 3.
|
||||
INVARIANTS:
|
||||
1. A client is a client ID metadata document (an https address, fetched
|
||||
only if every address its host has is public, with no redirect, no
|
||||
proxy from the environment, over the address that was checked, at most
|
||||
64 KiB, within five seconds, its client_id the address it came from),
|
||||
a dynamic registration, or a client id and secret the app made. The
|
||||
private forms inside IPv6 are refused too: IPv4-mapped, IPv4-compatible
|
||||
(::/96), NAT64 and 6to4 (2002::/16). A document is fetched only when a
|
||||
sign-in begins, never from the token endpoint; one we hold that is past
|
||||
its time is used as it stands when the fetch budget is spent.
|
||||
2. A redirect address is https, a loopback http address, or an app's own
|
||||
scheme, with no fragment or userinfo, at most 512 bytes; a client may
|
||||
carry up to twenty, at most 4 KiB together; the one asked for must
|
||||
equal one registered exactly. A mismatch is a page, never a redirect;
|
||||
and for a client nobody ever approved every error of a sign-in is a
|
||||
page too, never a redirect to the address it registered.
|
||||
3. PKCE with S256 is required, and its verifier is checked in constant
|
||||
time; `resource` must be one company's address under the issuer (or
|
||||
absent where one company is on offer); a code is single-use, lives
|
||||
sixty seconds, and ends what it made if used twice; the consent is a
|
||||
302.
|
||||
4. A secret (a client's, a code, a token) is kept as its SHA-256 only.
|
||||
SCENARIOS:
|
||||
1. Each of the three kinds signs in end to end and reads the books.
|
||||
2. Wrong redirect, no PKCE, the plain method, a wrong resource, a wrong
|
||||
verifier and a reused code are each refused.
|
||||
```
|
||||
|
||||
*Enforced:* `Remote::register`, `Remote::resolve_client`, `Remote::authorize`, `Remote::token`, `parse` (client documents), `is_public`, `valid_redirect`, `redirects_fit`.
|
||||
*Checked:* `ledger-mcp` unit tests `a_registered_client_signs_in_and_reads_the_books`, `a_client_metadata_document_signs_in`, `a_typed_client_id_and_secret_signs_in`, `a_redirect_that_is_not_registered_is_never_redirected_to`, `pkce_the_resource_and_the_verifier_are_required`, `only_public_addresses_are_fetched`, `a_document_must_be_what_it_says_it_is`, `nothing_is_ever_fetched_from_the_token_endpoint`, `a_stale_client_document_is_used_when_the_fetch_budget_is_spent`, `a_redirect_is_at_most_512_bytes_and_a_clients_together_a_few_kib`.
|
||||
|
||||
**WB-remote-5** No assistant connects without the person, in the app's window, and every sign-in is asked.
|
||||
|
||||
```text
|
||||
GOAL: nothing a stranger sends over the internet can approve a connection,
|
||||
and the secret address alone never opens the books.
|
||||
SOURCE: D-83 and D-90 in plan/p15-app-and-relay.md (a new assistant is
|
||||
approved in the app's window, by whoever is at the machine; every
|
||||
new sign-in is asked, an approval is never reused).
|
||||
INVARIANTS:
|
||||
1. /authorize never approves: it parks the request for five minutes and
|
||||
answers a page that says to look at Wanderbooks (no form, no button,
|
||||
no script, every outside word escaped) and looks again by itself.
|
||||
Every sign-in is parked, always (D-90): the app can tell which
|
||||
product asks (the redirect host is public), not whose account, so an
|
||||
earlier approval of the "same product" counts for nothing.
|
||||
2. Only an admin request (the owner-only admin socket) turns a waiting
|
||||
request into a code, by an id that is not the browser's: the page's own
|
||||
id only reads the outcome, once (302 with the code, or with
|
||||
access_denied after a refusal or a timeout, or temporarily_unavailable
|
||||
if a newer request made it give way).
|
||||
3. The window is told who is asking in neutral words: where it will be
|
||||
sent back to first ("An assistant that will be sent back to
|
||||
claude.ai"), then what it calls itself in quotes (cleaned of
|
||||
invisible and direction-changing characters, at most forty
|
||||
characters), the caller's address, the company, whether posting was
|
||||
asked for. No request is called a known or trusted product on the
|
||||
strength of its redirect host: a host is public. The warning ("doesn't
|
||||
know this address") is kept for hosts that are not a known vendor's.
|
||||
4. Each waiting request has its own six-digit code (two groups of three),
|
||||
never the same as another waiting one's, shown on the browser's page
|
||||
and on the window's card; the card says to allow only if the browser
|
||||
shows the same code. Requests are never merged.
|
||||
5. Waiting requests are bounded: twenty, five per address (an IPv6 /64 is
|
||||
one address). A new request is not turned away: an address at its limit
|
||||
gives up its oldest waiting request, and a full table the oldest of the
|
||||
address with the most waiting. The window draws the newest three and
|
||||
counts the rest.
|
||||
SCENARIOS:
|
||||
1. The person allows: the browser is sent back with a code.
|
||||
2. The person refuses, or no one answers: the browser is sent back with
|
||||
access_denied, and nothing was made.
|
||||
3. A guess of the browser's id decides nothing.
|
||||
4. A stranger registers a client with the callback of a product the person
|
||||
approved before, asks to sign in, and reads the 302: there is none; it
|
||||
is a page, and no code exists until an Allow.
|
||||
5. Eight requests from one address: five wait, the oldest three are told
|
||||
so; a full table still takes a real person's request.
|
||||
```
|
||||
|
||||
*Enforced:* `Remote::authorize`, `Remote::wait`, `Remote::decide`, `Remote::pending_list`, `Remote::make_pending_room`, `match_code`, `is_vendor_host`, `waiting` and `problem` (the page), `ledger_gui::connect::State::web_prompt`, `newest_waiting`, `ledger_host::app_server::AppServer::web_decide`.
|
||||
*Checked:* `ledger-mcp` unit tests `a_stranger_who_knows_the_product_gets_no_code_without_an_allow`, `the_window_is_told_who_asks_and_the_page_only_says_to_look`, `a_refusal_and_a_timeout_send_the_browser_back_denied_and_make_nothing`, `waiting_requests_give_way_and_never_fill_the_window_against_a_real_one`, `a_name_is_shown_without_invisible_or_direction_changing_characters_and_short`, `a_strangers_words_never_become_markup`; `ledger-gui` `tests/assistants.rs` (`a_web_assistant_asking_is_put_to_the_person_over_any_page_in_plain_words`, `waiting_requests_each_show_their_own_code_and_only_a_few_are_drawn`, `refusing_and_allowing_with_posting_are_their_own_answers`, `a_request_that_ran_out_goes_away_and_posting_is_turned_on_and_off_on_the_connect_page`).
|
||||
|
||||
**WB-remote-6** Every Allow is a new approval with exactly what was ticked; a revoke ends it at once and for good.
|
||||
|
||||
```text
|
||||
GOAL: the person's yes is for one sign-in; revoking ends everything made
|
||||
under the approval, and nothing brings it back.
|
||||
SOURCE: plan/p15-app-and-relay.md section 4, rule 6 as D-90 changed it; RFC
|
||||
9700 (refresh token rotation and reuse); D-86.
|
||||
INVARIANTS:
|
||||
1. An approval is one token of the books' principals (so "Who can reach
|
||||
these books" lists it, and revoking it by id ends it) plus a record
|
||||
naming the connection and the company. Every Allow makes a new
|
||||
approval with a new id and a new token, with exactly the permissions
|
||||
ticked then: nothing is carried over from an older approval of the
|
||||
same product, with posting or without; an older one stays as it is,
|
||||
to be revoked or kept on its own. Refresh within a sign-in is
|
||||
unchanged (an access token and its refresh token belong to one
|
||||
approval).
|
||||
2. An access token lives ten minutes and is memory only; a refresh token
|
||||
lives sixty days since last use, is kept (hashed) across restarts in a
|
||||
file only the owner can read (mode 0600; on Windows `set_owner_only`,
|
||||
the helper the token files use), is rotated at every use, and one used twice ends its whole family. The
|
||||
check that a refresh token is unused and its marking as used are one
|
||||
hold of the lock, with the minting of what replaces it: two refreshes
|
||||
at once, one wins and the other is a reuse that ends the family.
|
||||
3. A revoked connection's access token is a 401 at once, and its refresh
|
||||
token is invalid_grant: revoking (or making its token over by name)
|
||||
removes the approval, its refresh tokens, access tokens and codes under
|
||||
the lock at that moment, never when a list is next read. A later Allow
|
||||
of the same product is a new approval; none of the old tokens return.
|
||||
4. Raising or lowering posting swaps the connection's token in one step
|
||||
under the door's lock: no call lands between the old token's going and
|
||||
the new one's being named, the check that the connection is live and
|
||||
the replacement are one hold of the principals (a revoke that came
|
||||
first is not undone), and a revoke naming the token just replaced is
|
||||
for the one that replaced it.
|
||||
SCENARIOS:
|
||||
1. A second sign-in of Claude is a new question and a new approval.
|
||||
2. A refresh after ten days, and after a restart, still works.
|
||||
3. Revoke in the list ends access and refresh, and a new Allow does not
|
||||
revive them.
|
||||
```
|
||||
|
||||
*Enforced:* `Remote::decide`, `Remote::make_approval`, `Remote::token_gone`, `Remote::set_post`, `Remote::successor_of`, `replace_token_if_live`, `Remote::mint`, `Remote::refresh`, `Remote::authenticate`, `Remote::save`.
|
||||
*Checked:* `ledger-mcp` unit tests `an_allow_is_a_new_approval_with_exactly_the_permissions_ticked`, `revoke_then_allow_again_does_not_bring_the_old_tokens_back`, `raising_posting_is_one_step_and_a_revoke_during_it_wins`, `two_refreshes_at_once_never_both_succeed`, `a_code_used_twice_ends_what_it_made_and_so_does_a_refresh_token`, `revoking_the_connection_ends_the_access_token_and_the_refresh_token`, `refresh_tokens_survive_a_restart_and_only_their_hashes_are_kept`.
|
||||
|
||||
**WB-remote-7** A failure to sign in never bans an address; what a request creates is bounded.
|
||||
|
||||
```text
|
||||
GOAL: a stranger can fill neither memory nor disk, and a vendor's shared
|
||||
address is never shut out for another's failures.
|
||||
SOURCE: plan/p15-app-and-relay.md section 4, rule 7 (the vendors' addresses
|
||||
are shared; rate-limit per approval instead).
|
||||
INVARIANTS:
|
||||
1. Registered clients (2000 in all, thirty an hour from one address,
|
||||
600 an hour in all), waiting requests (twenty, five per address, which
|
||||
give way rather than turn a new one away), codes, access tokens,
|
||||
refresh tokens, approvals, families, fetches of client documents (30 a
|
||||
minute, 6 from one address) and the limiter's own table are all
|
||||
bounded. An address is an IPv4 address, an IPv6 caller's /64, and an
|
||||
IPv4-mapped address is the IPv4 one. When the table of per-address
|
||||
limits is full (10,000) the entries that began longest ago go; a
|
||||
connection's own limit (calls, token requests by client) is never
|
||||
evicted. The token endpoint is limited by address (300 a minute) and,
|
||||
once the client is known, by client (120 a minute).
|
||||
2. A registration is held in memory only: it reaches `remote.json` when
|
||||
the person allows a sign-in of it, and never for a stranger's
|
||||
registration. A redirect address is at most 512 bytes and a client's
|
||||
together at most 4 KiB. A registration nobody used for a sign-in goes
|
||||
after an hour; the oldest unused goes first when the table is full;
|
||||
none unused and full is a refusal. A revoked key frees its place among
|
||||
the fifty.
|
||||
3. Nothing bans an address; a refusal says to wait. An approval's own
|
||||
calls are limited to 600 a minute, asked before the company is, and a
|
||||
call refused for rate or for another company's books is counted, never
|
||||
written to the books' record.
|
||||
SCENARIOS:
|
||||
1. Thirty-one registrations from one address: the thirty-first waits;
|
||||
another address is not shut out.
|
||||
2. Unused registrations expire.
|
||||
```
|
||||
|
||||
*Enforced:* `Remote::allow`, `Remote::allow_address`, `address_key`, `Caller`, `Remote::make_room`, `Remote::sweep`, `Remote::make_key`, `Remote::count_refused`, `Remote::snapshot`.
|
||||
*Checked:* `ledger-mcp` unit tests `registration_is_bounded_and_unused_registrations_expire`, `limits_count_an_ipv6_64_as_one_caller_and_a_mapped_address_as_its_ipv4`, `a_full_limiter_table_evicts_addresses_never_a_connections_own_limit`, `a_registration_nobody_allowed_never_reaches_the_disk`, `a_revoked_key_frees_its_place`, `refused_calls_are_counted_not_written_and_the_limit_comes_before_the_company`.
|
||||
|
||||
**WB-remote-8** A token for one company never reaches another, and a company not offered is not there.
|
||||
|
||||
```text
|
||||
GOAL: the lock on the front door is per company.
|
||||
SOURCE: D-78 in plan/p15-app-and-relay.md (a connection names its company and
|
||||
is never redirected to another).
|
||||
INVARIANTS:
|
||||
1. An access token carries the company of its approval; at another
|
||||
company's path it is a 403, counted and not written (a token holder
|
||||
can't fill the books' record with refusals), after the call limit.
|
||||
2. A company that is not offered (or not open) answers 404 on its path and
|
||||
has no metadata.
|
||||
3. A code and a refresh token carry their company and never make a token
|
||||
for another.
|
||||
SCENARIOS:
|
||||
1. A token for acme at beta's path is 403; with beta not offered, 404.
|
||||
```
|
||||
|
||||
*Enforced:* `door` (the server's `local` module), `Remote::is_allowed`, `resource_document`.
|
||||
*Checked:* `ledger-mcp` unit test `a_token_for_one_company_never_reaches_another`.
|
||||
|
||||
**WB-remote-9** A web assistant may read and draft; posting is the owner's to turn on, per connection.
|
||||
|
||||
```text
|
||||
GOAL: an assistant that also reads email, and can be steered by it, cannot
|
||||
post by default.
|
||||
SOURCE: D-86 in plan/p15-app-and-relay.md.
|
||||
INVARIANTS:
|
||||
1. An approval grants read and write (drafts), not post and never admin;
|
||||
the access record (admin) is not reachable through this door whatever
|
||||
the token says.
|
||||
2. The owner raises or lowers posting per approval (RemoteSetPost): the
|
||||
token that carries it is replaced by one with the new scopes in one
|
||||
principals record, as one step (WB-remote-6), and the same access
|
||||
tokens carry on.
|
||||
3. A key made for an assistant that takes only a key (RemoteMakeKey) is a
|
||||
principals token the door accepts, shown once, with the same scopes;
|
||||
no other principals token is accepted here.
|
||||
SCENARIOS:
|
||||
1. A new connection can't post; raised, it can; lowered, it can't.
|
||||
```
|
||||
|
||||
*Enforced:* `scopes_for`, `Remote::set_post`, `Remote::make_key`, `Remote::authenticate`.
|
||||
*Checked:* `ledger-mcp` unit tests `the_default_is_read_and_draft_and_the_person_raises_it_to_post`, `an_unsigned_request_is_a_401_that_says_where_to_sign_in_initialize_included` (an agent's own key opens nothing here).
|
||||
|
||||
**WB-remote-10** A remote call is the same call: one write path, plain JSON, no session.
|
||||
|
||||
```text
|
||||
GOAL: a write through the door is exactly once (D-88), and the door adds no
|
||||
second way to the books.
|
||||
SOURCE: D-88 in plan/p15-app-and-relay.md; WB-format-8 to 10.
|
||||
INVARIANTS:
|
||||
1. Every remote call is handled by the same server as a local one
|
||||
(`call_tool`): a write without its request_key is refused, and a repeat
|
||||
of a key returns the first answer and writes nothing. The remote door
|
||||
has no tool of its own.
|
||||
2. It is stateless and answers plain JSON: no session id is made, and one
|
||||
a caller names is not heard.
|
||||
SCENARIOS:
|
||||
1. A draft without a key is refused; with one, twice, it is one draft and
|
||||
the same answer.
|
||||
```
|
||||
|
||||
*Enforced:* `mcp_via` (the server's `local` module), `call_tool` (the server's `BooksServer`).
|
||||
*Checked:* `ledger-mcp` unit tests `a_remote_write_needs_its_request_key_and_a_repeat_returns_the_first_answer`, `a_registered_client_signs_in_and_reads_the_books`.
|
||||
@@ -249,16 +249,30 @@ section 8):
|
||||
5. No per-session memory on the remote door, and plain JSON replies,
|
||||
never a stream (both cured failures behind tunnels). The local door
|
||||
keeps its sessions.
|
||||
6. An approval belongs to the owner's decision (this product, this
|
||||
company, these permissions), not to a registration: Claude and Grok
|
||||
register anew on most sign-ins, and the approval must survive that.
|
||||
Access tokens are short; refresh tokens are long and sliding; a
|
||||
refresh after the app was closed for days still works.
|
||||
6. Every new sign-in is asked in the window (D-90): an approval belongs to
|
||||
one sign-in, never to a product, and is never reused. The app can tell
|
||||
which product asks (the redirect host is public), not whose account, so
|
||||
a stranger with the secret address who registers a client with
|
||||
claude.ai's callback must not be handed a code because Claude was
|
||||
approved before. Every Allow makes a new approval with exactly the
|
||||
permissions ticked; revoking ends its tokens at once. Each waiting
|
||||
request has a short code shown on the browser's page and on the card,
|
||||
to be matched, and the window says where the assistant is sent back to
|
||||
in neutral words, never that it is a known product. Access tokens are
|
||||
short; refresh tokens are long and sliding, and refresh within a
|
||||
sign-in is unchanged: a refresh after the app was closed for days still
|
||||
works. (Claude and Grok register anew on most sign-ins, so they are
|
||||
asked each time; that is the price of the secret address not being
|
||||
enough.)
|
||||
7. Never ban an address for failed sign-ins: the vendors' addresses are
|
||||
shared. Rate-limit per approval instead.
|
||||
8. The relay passes the real caller's address to the app, and the app
|
||||
never treats a relayed request as local (Home Assistant's advisory
|
||||
GHSA-wx3j-3v2j-rf45).
|
||||
GHSA-wx3j-3v2j-rf45). The door gives a per-start secret to the app over
|
||||
the admin socket (`proxy_secret`, in the answer of `remote_start`), and
|
||||
refuses any connection that does not begin with it (the 64 characters,
|
||||
as given, before the PROXY header), so only the app's relay line can
|
||||
state a caller's address. Unit B3 writes exactly that first.
|
||||
9. A key for products that take only a key: made in the app, named,
|
||||
revocable, shown once, with the same permissions model.
|
||||
10. Read tools carry the read-only mark, so products ask before each
|
||||
|
||||
Reference in new issue
Block a user