fix(mcp): every web sign-in is asked in the window, with a matching code (P15 B1 review, D-90)

An approval is never reused for a new sign-in: the product's redirect host
is public, so a stranger registering a client with claude.ai's callback got
a code with no Allow. /authorize now always parks the request. Every Allow
is a new approval with exactly the permissions ticked, a revoke ends the
approval's tokens at once under the lock, and raising or lowering posting
swaps the token in one step (a revoke during it wins). The window shows a
short code the browser's page also shows, says what is known in neutral
words (where it is sent back to first), counts the requests beyond the
newest few, and no request is presented as a known product on the strength
of its host. Refresh checks and marks the token used in one hold of the
lock, so two refreshes at once cannot both succeed.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-21 12:05:09 -07:00
1 parent 0a91656f14
commit c4fd1580d8
11 files changed
+1461 -615

No files matched your search

+2 -1
View File
@@ -162,7 +162,8 @@ impl ledger_gui::owner::Owner for ViewerOwner {
id: p.id,
book: p.book,
client_name: p.client_name,
recognised: p.product.is_some(),
known_host: p.known_host,
code: p.code,
redirect: p.redirect,
redirect_host: p.redirect_host,
from: p.from,
+71 -16
View File
@@ -51,9 +51,16 @@
//! 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 the assistant calls itself is shown in quotes and
//! is never what names the product. Posting is off unless the person
//! ticks it, per assistant, and can be turned on or off later.
//! 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};
@@ -461,12 +468,14 @@ impl State {
ui.add_space(24.0);
section(ui, "Assistants on the web");
let mut want: Want = None;
for request in &status.web_pending {
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)
@@ -537,26 +546,40 @@ impl State {
.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!(
"{} wants to connect to {}. Allow?",
request.client_name, status.company
"An assistant that will be sent back to {} wants to connect to {}. Allow?",
request.redirect_host, status.company
))
.font(theme::semibold(15.0)),
);
ui.add_space(4.0);
if request.recognised {
if !request.client_name.is_empty() {
ui.label(
RichText::new(
"Only allow it if you just asked this assistant to connect.",
)
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),
);
} else {
}
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 recognise this assistant: it only gave this name for itself. Don't allow it unless you just set it up yourself.",
"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),
@@ -622,9 +645,9 @@ impl State {
let owner = owner.clone()?;
let id = request.id.clone();
let what = if approve {
format!("Allow {}", request.client_name)
format!("Allow the assistant sent back to {}", request.redirect_host)
} else {
format!("Don't allow {}", request.client_name)
format!("Don't allow the assistant sent back to {}", request.redirect_host)
};
Some((
what,
@@ -655,12 +678,14 @@ impl State {
.resizable(false)
.anchor(egui::Align2::CENTER_CENTER, vec2(0.0, 0.0))
.show(ui.ctx(), |win| {
for request in &status.web_pending {
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);
@@ -857,6 +882,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(|a, b| b.expires_in_secs.cmp(&a.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);
+8 -4
View File
@@ -213,11 +213,15 @@ pub struct WebRequest {
pub id: String,
/// The company it asks to reach.
pub book: String,
/// The product recognised by where it is sent back to ("Claude on
/// the web"), else what it calls itself.
/// 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 product is one Wanderbooks recognises.
pub recognised: bool,
/// 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.
+63 -13
View File
@@ -1080,12 +1080,13 @@ fn pictures() {
// ---- 7: a web assistant asks to connect (plan P15 D-83, unit B1) --------------
fn asking(id: &str, name: &str, recognised: bool) -> WebRequest {
fn asking(id: &str, name: &str, known_host: bool) -> WebRequest {
WebRequest {
id: id.into(),
book: "alpha".into(),
client_name: name.into(),
recognised,
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(),
@@ -1108,23 +1109,38 @@ fn a_web_assistant_asking_is_put_to_the_person_over_any_page_in_plain_words() {
let owner = Fake::new();
with_pending(
&owner,
vec![asking("p_1", "Claude on the web", true)],
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("Claude on the web wants to connect to Wanderland Labs. Allow?")
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_by_label_contains("sent back to claude.ai")
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("203.0.113.9").is_some());
assert!(
h.query_by_label_contains("can't post entries unless you tick")
.is_some()
@@ -1162,11 +1178,8 @@ fn refusing_and_allowing_with_posting_are_their_own_answers() {
);
let mut h = start(&w, &["alpha"], &owner);
refresh(&mut h);
// A product that is not recognised is said not to be.
assert!(
h.query_by_label_contains("doesn't recognise this assistant")
.is_some()
);
// 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", || {
@@ -1179,7 +1192,7 @@ fn refusing_and_allowing_with_posting_are_their_own_answers() {
// Another asks; this time posting is ticked, then allowed.
with_pending(
&owner,
vec![asking("p_8", "Claude on the web", true)],
vec![asking("p_8", "Claude", true)],
vec![],
);
refresh(&mut h);
@@ -1195,13 +1208,50 @@ fn refusing_and_allowing_with_posting_are_their_own_answers() {
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}"
);
}
assert_eq!(
h.query_all_by_label_contains("wants to connect").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 on the web", true)],
vec![asking("p_2", "Claude", true)],
vec![],
);
let mut h = start(&w, &["alpha"], &owner);
+8 -4
View File
@@ -406,11 +406,15 @@ pub struct PendingInfo {
pub id: String,
/// The company it asks to reach.
pub book: String,
/// The product we recognise by where it is sent back to ("Claude on
/// the web"), else what it calls itself.
/// 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,
/// The product recognised from its redirect host, if it is one.
pub product: Option<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.
+88 -21
View File
@@ -1344,6 +1344,7 @@ impl Books {
});
if let (Response::TokenCreated { .. }, Some(old)) = (&answer, &replaced) {
self.forget_sessions_of(old);
self.remote.token_gone(old);
}
answer
}
@@ -1435,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
}
@@ -2588,6 +2602,15 @@ fn live_token(books: &Books, book: &str, name: &str, id: &str) -> Option<Token>
.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()
}
@@ -2630,6 +2653,37 @@ fn create_token(
}
}
/// 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(
@@ -2801,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,
@@ -3281,26 +3368,6 @@ async fn mcp_via(
// not heard, so a call is the same call however it arrives.
if remote_from.is_some() {
request.headers_mut().remove(SESSION_HEADER);
if books
.remote
.limited(books.remote.call_key(&token), remote::CALLS_PER_MINUTE, 60)
{
let mut refused = refused_at_door(
&held,
inside,
who,
&asked_of(&method),
"rate_limited",
StatusCode::TOO_MANY_REQUESTS,
"this connection is making too many calls: wait a minute".into(),
)
.await;
refused.headers_mut().insert(
axum::http::header::RETRY_AFTER,
axum::http::HeaderValue::from_static("60"),
);
return refused;
}
}
let session = request
.headers()
+20 -3
View File
@@ -31,7 +31,7 @@
//! address is.
//! ```
use super::{MAX_REDIRECTS, clean, valid_redirect};
use super::{MAX_REDIRECTS, clean, redirects_fit, valid_redirect};
use std::future::Future;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::pin::Pin;
@@ -89,8 +89,12 @@ fn v6_public(a: Ipv6Addr) -> bool {
// Documentation 2001:db8::/32, discard 100::/64.
|| (s[0] == 0x2001 && s[1] == 0x0db8)
|| (s[0] == 0x0100 && s[1] == 0 && s[2] == 0 && s[3] == 0)
// IPv4-compatible and NAT64 forms of a private address.
|| (s[0] == 0x0064 && s[1] == 0xff9b))
// 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).
@@ -129,7 +133,11 @@ impl ClientDocs for WebDocs {
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)
@@ -194,6 +202,9 @@ pub fn parse(url: &str, bytes: &[u8]) -> Result<(String, Vec<String>), String> {
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))
@@ -232,6 +243,12 @@ mod tests {
"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}");
}
+5 -5
View File
@@ -32,7 +32,7 @@
//! 2. `OPTIONS` on a sign-in route answers a browser's preflight.
//! ```
use super::{Authorize, Denied, Door, OauthError, proxy};
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};
@@ -356,7 +356,7 @@ async fn register(
};
match books
.remote
.register(&books, &meta, &peer.0.ip().to_string())
.register(&books, &meta, &Caller::new(peer.0.ip()))
.await
{
Ok(out) => cors(json(201, &out)),
@@ -377,7 +377,7 @@ async fn authorize(
answer(
books
.remote
.authorize(&books, &door, &q, &peer.0.ip().to_string())
.authorize(&books, &door, &q, &Caller::new(peer.0.ip()))
.await,
)
}
@@ -390,7 +390,7 @@ async fn wait(
if let Err(r) = front(&books, &headers) {
return *r;
}
answer(books.remote.wait(&wait))
answer(books.remote.wait(&books, &wait))
}
async fn token(
@@ -454,7 +454,7 @@ async fn token(
});
match books
.remote
.token(&books, &door, &form, basic, &peer.0.ip().to_string())
.token(&books, &door, &form, basic, &Caller::new(peer.0.ip()))
.await
{
Ok(out) => cors(json(200, &out)),
File diff suppressed because it is too large. Load diff
+31 -10
View File
@@ -12,7 +12,9 @@
//! name) is HTML-escaped; the page has no script, no form, no link
//! and no button that approves: it says to look at Wanderbooks and
//! looks again by itself (a refresh), until the person decides.
//! 2. The page's only address is the relative one of the waiting
//! 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.
//! ```
@@ -46,19 +48,30 @@ fn shell(title: &str, refresh: Option<&str>, body: &str) -> String {
)
}
/// The page while the person has not decided: look at the app.
pub fn waiting(client: &str, company: &str, wait: &str) -> String {
/// 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><strong>{}</strong> is asking to connect to <strong>{}</strong>.</p>\
<p>Open the Wanderbooks window on your computer and choose <strong>Allow</strong> \
or <strong>Don't allow</strong>. This page continues by itself when you do.</p>\
<p>If you didn't ask an assistant to connect, choose Don't allow, or just close this page.</p>",
esc(client),
esc(company)
<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)
),
)
}
@@ -78,10 +91,18 @@ mod tests {
#[test]
fn a_strangers_words_never_become_markup() {
let page = waiting("<script>alert(1)</script>", "\"><img src=x>", "w_abc");
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("&lt;script&gt;"));
assert!(page.contains("123 456"));
assert!(page.contains("&lt;b&gt;co"));
assert!(!page.contains("<form"));
assert!(page.contains("url=/authorize/wait/w_abc"));
}
+423 -141
View File
@@ -17,11 +17,12 @@ const ISSUER: &str = "https://ledger-accrual-tally-mint.wanderbooks.link";
const CLAUDE_CB: &str = "https://claude.ai/api/mcp/auth_callback";
const CALLER: &str = "203.0.113.9";
#[derive(Clone)]
struct H {
books: Arc<Books>,
addr: SocketAddr,
clock: Arc<AtomicI64>,
_home: tempfile::TempDir,
_home: Arc<tempfile::TempDir>,
}
async fn admin(books: &Arc<Books>, request: Request) -> Response {
@@ -65,7 +66,7 @@ async fn harness() -> H {
books,
addr: "127.0.0.1:1".parse().unwrap(),
clock,
_home: home,
_home: Arc::new(home),
};
h.start(ISSUER).await;
h
@@ -423,6 +424,21 @@ async fn claude(h: &H, book: &str) -> (String, String, String) {
)
}
/// The words of a page, without markup.
fn waiting_text(page: &Resp) -> String {
let mut out = String::new();
let mut in_tag = false;
for c in page.body.chars() {
match c {
'<' => in_tag = true,
'>' => in_tag = false,
c if !in_tag => out.push(c),
_ => {}
}
}
out
}
fn tool_text(r: &Resp) -> String {
assert_eq!(r.status, 200, "{}", r.body);
r.json()["result"]["content"][0]["text"]
@@ -588,9 +604,15 @@ async fn the_window_is_told_who_asks_and_the_page_only_says_to_look() {
let waiting = pending(&h).await;
assert_eq!(waiting.len(), 1);
let p = &waiting[0];
// The product is named by where it is sent back, not by what it says.
assert_eq!(p.client_name, "Claude on the web");
assert_eq!(p.product.as_deref(), Some("Claude on the web"));
// What is known is its own word, cleaned (markup is just letters here),
// and where it is sent back: never a product's name made from the host.
assert_eq!(p.client_name, "Claude <b>web</b>");
assert!(p.known_host);
assert!(!page.body.contains("Claude on the web"));
assert!(!waiting_text(&page).contains("Claude on the web"));
// The code the card shows is the code the browser's page shows.
assert!(page.body.contains(&p.code), "{}", page.body);
assert_eq!(p.code.len(), 7);
assert_eq!(p.redirect, CLAUDE_CB);
assert_eq!(p.redirect_host, "claude.ai");
assert_eq!(p.from, CALLER);
@@ -683,7 +705,7 @@ async fn the_default_is_read_and_draft_and_the_person_raises_it_to_post() {
};
assert_eq!(approvals.len(), 1);
assert!(!approvals[0].may_post);
assert_eq!(approvals[0].label, "Claude on the web");
assert!(approvals[0].label.contains("claude.ai"), "{}", approvals[0].label);
// The same connection is a row of "Who can reach these books".
let listed = match admin(&h.books, Request::TokenList).await {
Response::Tokens(t) => t,
@@ -796,38 +818,248 @@ async fn revoking_the_connection_ends_the_access_token_and_the_refresh_token() {
assert_eq!(pending(&h).await.len(), 1);
}
/// The approvals the window lists for `book`.
async fn approvals_of(h: &H, book: &str) -> Vec<crate::admin::ApprovalInfo> {
match admin(
&h.books,
Request::RemoteApprovals {
book: Some(book.into()),
},
)
.await
{
Response::RemoteApprovals(a) => a,
other => panic!("{other:?}"),
}
}
/// The four steps a stranger who knows only public facts takes (D-90): the
/// address, a registration with a callback of the product the person
/// approved before, an authorize, and a read of the 302's `Location`. It
/// gets no code: nothing is approved but by an Allow in the window.
#[tokio::test(flavor = "multi_thread")]
async fn an_approval_survives_a_product_registering_again() {
async fn a_stranger_who_knows_the_product_gets_no_code_without_an_allow() {
let h = harness().await;
// The person approved Claude on the web before.
let (_, _, _) = claude(&h, "acme").await;
// Claude registers anew: a new client id, the same product.
let c = register(&h, "Claude", &[CLAUDE_CB]).await;
let id = c["client_id"].as_str().unwrap();
// 1 and 2: the stranger registers a client with Claude's own callback.
let c = http_from(
&h,
"198.51.100.200",
"POST",
"/register",
&[("Content-Type", "application/json")],
&json!({"client_name": "Claude", "redirect_uris": [CLAUDE_CB]}).to_string(),
)
.await;
assert_eq!(c.status, 201, "{}", c.body);
let id = c.json()["client_id"].as_str().unwrap().to_string();
let (verifier, challenge) = pkce(9);
let back = http(
// 3: it asks to sign in.
let asked = http_from(
&h,
"198.51.100.200",
"GET",
&authorize_path(id, CLAUDE_CB, &challenge, "acme", &[]),
&authorize_path(&id, CLAUDE_CB, &challenge, "acme", &[]),
&[],
"",
)
.await;
// No question to the person: the browser is sent straight back.
let params = location_params(&back);
assert!(pending(&h).await.is_empty());
let t = exchange(&h, id, &params["code"], &verifier, CLAUDE_CB).await;
assert_eq!(t.status, 200, "{}", t.body);
// The same product for another company is a new question.
let page = http(
&h,
"GET",
&authorize_path(id, CLAUDE_CB, &challenge, "beta", &[]),
&[],
"",
)
.await;
assert_eq!(page.status, 200);
// 4: there is no 302 with a code to read: it is a page that says to look
// at the window, and the request is parked for the person.
assert_eq!(asked.status, 200, "{}", asked.body);
assert!(asked.header("location").is_none());
assert!(!asked.body.contains("code="));
assert_eq!(pending(&h).await.len(), 1);
// Nothing it can send to the token endpoint gives it anything: it holds
// no code (a guess, a made-up one, or the pending ids).
for guess in ["wbcode_guess", &wait_path(&asked), "p_guess"] {
let r = exchange(&h, &id, guess, &verifier, CLAUDE_CB).await;
assert_eq!(r.status, 400, "{}", r.body);
assert_eq!(r.json()["error"], "invalid_grant");
}
// The person refuses it: the stranger's browser is told no, with no code.
let waiting = pending(&h).await;
assert!(matches!(
decide(&h, &waiting[0].id, false, false).await,
Response::RemoteDecided { approval: None, .. }
));
let back = http_from(
&h,
"198.51.100.200",
"GET",
&wait_path(&asked),
&[],
"",
)
.await;
let params = location_params(&back);
assert_eq!(params["error"], "access_denied");
assert!(!params.contains_key("code"));
}
/// An Allow makes a new connection with exactly what was ticked: nothing
/// is carried over from an older approval of the same product, with or
/// without posting (D-90).
#[tokio::test(flavor = "multi_thread")]
async fn an_allow_is_a_new_approval_with_exactly_the_permissions_ticked() {
let h = harness().await;
let c = register(&h, "Claude", &[CLAUDE_CB]).await;
let id = c["client_id"].as_str().unwrap().to_string();
// First: with posting ticked.
let (code, verifier) = sign_in(&h, &id, CLAUDE_CB, "acme", 1, true).await;
let first = exchange(&h, &id, &code, &verifier, CLAUDE_CB).await.json();
let first_access = first["access_token"].as_str().unwrap().to_string();
let listed = approvals_of(&h, "acme").await;
assert_eq!(listed.len(), 1);
assert!(listed[0].may_post);
let first_approval = listed[0].id.clone();
let first_token = listed[0].token_id.clone();
// The same product signs in again with posting not ticked: a new
// question, a new approval, and no posting; the old one is untouched.
let (code, verifier) = sign_in(&h, &id, CLAUDE_CB, "acme", 2, false).await;
let second = exchange(&h, &id, &code, &verifier, CLAUDE_CB).await.json();
let second_access = second["access_token"].as_str().unwrap().to_string();
let listed = approvals_of(&h, "acme").await;
assert_eq!(listed.len(), 2, "{listed:?}");
let new = listed.iter().find(|a| a.id != first_approval).unwrap();
assert!(!new.may_post, "nothing carried over from the first");
assert!(listed.iter().find(|a| a.id == first_approval).unwrap().may_post);
assert_ne!(new.token_id, first_token);
let post = call(
3,
"books.post_entry",
json!({"entry_id": 1, "confirmed": true, "request_key": "post-key-0002"}),
);
let refused = mcp(&h, Some(&second_access), "acme", post.clone()).await;
assert!(tool_text(&refused).contains("books:post"), "{}", refused.body);
let allowed = mcp(&h, Some(&first_access), "acme", post).await;
assert!(!tool_text(&allowed).contains("needs books:post"));
// And the other way: not ticked first, ticked second.
let (code, verifier) = sign_in(&h, &id, CLAUDE_CB, "acme", 3, true).await;
let third = exchange(&h, &id, &code, &verifier, CLAUDE_CB).await.json();
let listed = approvals_of(&h, "acme").await;
assert_eq!(listed.len(), 3);
assert_eq!(listed.iter().filter(|a| a.may_post).count(), 2);
assert!(third["scope"].as_str().unwrap().contains("books:post"));
assert!(!second["scope"].as_str().unwrap().contains("books:post"));
}
/// A revoked connection stays revoked: a later Allow of the same product
/// makes a new one, and none of the old tokens comes back, not at once and
/// not when the list is next read (D-90).
#[tokio::test(flavor = "multi_thread")]
async fn revoke_then_allow_again_does_not_bring_the_old_tokens_back() {
let h = harness().await;
let (client, access, refresh_token) = claude(&h, "acme").await;
let old = approvals_of(&h, "acme").await;
assert_eq!(old.len(), 1);
let t = match admin(&h.books, Request::TokenList).await {
Response::Tokens(t) => t[0].clone(),
other => panic!("{other:?}"),
};
assert!(matches!(
admin(
&h.books,
Request::TokenRevoke {
book: "acme".into(),
name: t.name.clone(),
id: Some(t.id.clone())
}
)
.await,
Response::TokenRevoked(_)
));
// At once, without the list being read: the records are gone.
{
let inner = h.books.remote.inner();
assert!(inner.approvals.is_empty());
assert!(inner.refresh.is_empty());
assert!(inner.access.is_empty());
}
// A new Allow of the same product, the same token name freed.
let (code, verifier) = sign_in(&h, &client, CLAUDE_CB, "acme", 4, false).await;
let fresh = exchange(&h, &client, &code, &verifier, CLAUDE_CB).await;
assert_eq!(fresh.status, 200, "{}", fresh.body);
let now = approvals_of(&h, "acme").await;
assert_eq!(now.len(), 1);
assert_ne!(now[0].id, old[0].id);
assert_ne!(now[0].token_id, old[0].token_id);
// The old tokens stay dead.
assert_eq!(
mcp(&h, Some(&access), "acme", initialize()).await.status,
401
);
assert_eq!(refresh(&h, &client, &refresh_token).await.status, 400);
// The new one works.
let new_access = fresh.json()["access_token"].as_str().unwrap().to_string();
assert_eq!(
mcp(&h, Some(&new_access), "acme", initialize()).await.status,
200
);
}
/// Raising and lowering posting swaps the connection's token in one step:
/// a call that arrives while it is going on is never refused or signed out,
/// and a revoke that names the token just replaced still wins.
#[tokio::test(flavor = "multi_thread")]
async fn raising_posting_is_one_step_and_a_revoke_during_it_wins() {
let h = harness().await;
let (client, access, refresh_token) = claude(&h, "acme").await;
let approval = approvals_of(&h, "acme").await[0].clone();
let calls = {
let h = h.clone();
let access = access.clone();
tokio::spawn(async move {
let mut statuses = Vec::new();
for _ in 0..60 {
statuses.push(mcp(&h, Some(&access), "acme", initialize()).await.status);
}
statuses
})
};
for n in 0..30 {
let raised = admin(
&h.books,
Request::RemoteSetPost {
approval: approval.id.clone(),
post: n % 2 == 0,
},
)
.await;
assert!(matches!(raised, Response::RemoteApprovals(_)), "{raised:?}");
}
let statuses = calls.await.unwrap();
assert!(statuses.iter().all(|s| *s == 200), "{statuses:?}");
// The token the window listed before the last swap is stale; a revoke
// naming it is for the one that replaced it.
let stale = {
let inner = h.books.remote.inner();
inner.swapped.keys().next().cloned().unwrap()
};
let live = approvals_of(&h, "acme").await[0].clone();
let listed = match admin(&h.books, Request::TokenList).await {
Response::Tokens(t) => t,
other => panic!("{other:?}"),
};
let name = listed[0].name.clone();
assert_ne!(stale, live.token_id);
let revoked = admin(
&h.books,
Request::TokenRevoke {
book: "acme".into(),
name,
id: Some(stale),
},
)
.await;
assert!(matches!(revoked, Response::TokenRevoked(_)), "{revoked:?}");
assert_eq!(
mcp(&h, Some(&access), "acme", initialize()).await.status,
401
);
assert_eq!(refresh(&h, &client, &refresh_token).await.status, 400);
assert!(approvals_of(&h, "acme").await.is_empty());
}
// ---- every refusal ------------------------------------------------------------
@@ -881,7 +1113,6 @@ async fn pkce_the_resource_and_the_verifier_are_required() {
let id = c["client_id"].as_str().unwrap().to_string();
let challenge = pkce(11).1;
let base = |extra: &[(&str, &str)]| authorize_path(&id, CLAUDE_CB, &challenge, "acme", extra);
// No challenge, and the plain method: sent back with invalid_request.
let no_pkce = format!(
"/authorize?{}",
form(&[
@@ -891,25 +1122,13 @@ async fn pkce_the_resource_and_the_verifier_are_required() {
("state", "s")
])
);
assert_eq!(
location_params(&http(&h, "GET", &no_pkce, &[], "").await)["error"],
"invalid_request"
);
let plain = base(&[("code_challenge_method", "plain")]).replace("S256", "plain");
assert_eq!(
location_params(&http(&h, "GET", &plain, &[], "").await)["error"],
"invalid_request"
);
// A resource that is another company's address elsewhere, or none at all
// where two are on offer.
let other = authorize_path(&id, CLAUDE_CB, &challenge, "acme", &[]).replace(
&form(&[("resource", &format!("{ISSUER}/b/acme/mcp"))]),
&form(&[("resource", "https://other.example/b/acme/mcp")]),
);
assert_eq!(
location_params(&http(&h, "GET", &other, &[], "").await)["error"],
"invalid_target"
);
let none = format!(
"/authorize?{}",
form(&[
@@ -920,13 +1139,32 @@ async fn pkce_the_resource_and_the_verifier_are_required() {
("code_challenge_method", "S256")
])
);
assert_eq!(
location_params(&http(&h, "GET", &none, &[], "").await)["error"],
"invalid_target"
);
// A client nobody ever approved is anyone's: every one of these is an
// error page, not a redirect to the address it registered (no open
// redirect through registration).
for bad in [&no_pkce, &plain, &other, &none] {
let r = http(&h, "GET", bad, &[], "").await;
assert_eq!(r.status, 400, "{}", r.body);
assert!(r.header("location").is_none(), "{bad}");
}
assert!(pending(&h).await.is_empty());
// Once the person has approved it, the specification's own way: sent
// back to its registered address with the error.
let (code, verifier) = sign_in(&h, &id, CLAUDE_CB, "acme", 12, false).await;
let expect = [
(&no_pkce, "invalid_request"),
(&plain, "invalid_request"),
(&other, "invalid_target"),
(&none, "invalid_target"),
];
for (path, error) in expect {
assert_eq!(
location_params(&http(&h, "GET", path, &[], "").await)["error"],
error
);
}
assert!(pending(&h).await.is_empty());
// A wrong verifier does not give a token, and spends the code.
let (code, verifier) = sign_in(&h, &id, CLAUDE_CB, "acme", 12, false).await;
let wrong = exchange(
&h,
&id,
@@ -939,19 +1177,7 @@ async fn pkce_the_resource_and_the_verifier_are_required() {
let spent = exchange(&h, &id, &code, &verifier, CLAUDE_CB).await;
assert_eq!(spent.json()["error"], "invalid_grant");
// A token request naming another address as its resource is refused.
let (code, verifier) = {
// A second approval for the same product is instant now.
let (v, ch) = pkce(13);
let back = http(
&h,
"GET",
&authorize_path(&id, CLAUDE_CB, &ch, "acme", &[]),
&[],
"",
)
.await;
(location_params(&back)["code"].clone(), v)
};
let (code, verifier) = sign_in(&h, &id, CLAUDE_CB, "acme", 13, false).await;
let r = http(
&h,
"POST",
@@ -996,18 +1222,7 @@ async fn a_code_used_twice_ends_what_it_made_and_so_does_a_refresh_token() {
);
// Refresh tokens rotate; the old one used again ends the family.
let (code, verifier) = {
let (v, ch) = pkce(15);
let back = http(
&h,
"GET",
&authorize_path(&id, CLAUDE_CB, &ch, "acme", &[]),
&[],
"",
)
.await;
(location_params(&back)["code"].clone(), v)
};
let (code, verifier) = sign_in(&h, &id, CLAUDE_CB, "acme", 15, false).await;
let t = exchange(&h, &id, &code, &verifier, CLAUDE_CB).await.json();
let r1 = t["refresh_token"].as_str().unwrap().to_string();
let second = refresh(&h, &id, &r1).await;
@@ -1025,18 +1240,7 @@ async fn a_code_used_twice_ends_what_it_made_and_so_does_a_refresh_token() {
// Another client's refresh token is not good for this one.
let other = register(&h, "Other", &["https://other.example/cb"]).await;
let other_id = other["client_id"].as_str().unwrap();
let (code, verifier) = {
let (v, ch) = pkce(16);
let back = http(
&h,
"GET",
&authorize_path(&id, CLAUDE_CB, &ch, "acme", &[]),
&[],
"",
)
.await;
(location_params(&back)["code"].clone(), v)
};
let (code, verifier) = sign_in(&h, &id, CLAUDE_CB, "acme", 16, false).await;
let t = exchange(&h, &id, &code, &verifier, CLAUDE_CB).await.json();
assert_eq!(
refresh(&h, other_id, t["refresh_token"].as_str().unwrap())
@@ -1270,14 +1474,20 @@ async fn the_recorded_address_is_the_relays_and_a_forged_one_changes_nothing() {
)
.await;
assert!(out.is_empty(), "{}", String::from_utf8_lossy(&out));
// A refusal at the door of a token holder carries the address too.
// A token holder's call for another company is refused, counted, and
// not written: it could otherwise fill the disk one call at a time.
let before = h.books.remote.refused();
let r = mcp_from(&h, "192.0.2.50", Some(&access), "beta", initialize()).await;
assert_eq!(r.status, 403);
assert_eq!(h.books.remote.refused(), before + 1);
let dir = h.books.root.book_dir(&BookId::parse("beta").unwrap());
let (records, _) = ledger_store::access::read(&dir).unwrap();
let written = ledger_store::access::read(&dir)
.map(|(records, _)| records.len())
.unwrap_or(0);
assert_eq!(
records.last().unwrap().access.from.as_deref(),
Some("192.0.2.50")
written,
0,
"a refusal for another company is counted, never written"
);
}
@@ -1412,6 +1622,7 @@ async fn registration_is_bounded_and_unused_registrations_expire() {
created: i as i64,
last_seen: 0,
used: false,
approved: false,
fetched: 0,
},
);
@@ -1428,71 +1639,136 @@ async fn registration_is_bounded_and_unused_registrations_expire() {
}
}
#[tokio::test(flavor = "multi_thread")]
async fn waiting_requests_are_bounded_per_address_and_in_all() {
let h = harness().await;
let c = register(&h, "Spam", &["https://spam.example/cb"]).await;
let id = c["client_id"].as_str().unwrap().to_string();
for i in 0..MAX_PENDING_PER_ADDRESS {
let page = http(
&h,
"GET",
&authorize_path(
&id,
"https://spam.example/cb",
&pkce(100 + i as u32).1,
"acme",
&[],
),
&[],
"",
)
.await;
assert_eq!(page.status, 200);
}
let page = http(
&h,
/// One sign-in request from `from` (a bare address; an IPv6 one in square
/// brackets): the page it got.
async fn ask(h: &H, from: &str, client: &str, redirect: &str, n: u32) -> Resp {
http_from(
h,
from,
"GET",
&authorize_path(&id, "https://spam.example/cb", &pkce(200).1, "acme", &[]),
&authorize_path(client, redirect, &pkce(n).1, "acme", &[]),
&[],
"",
)
.await;
assert_eq!(page.status, 429);
assert_eq!(pending(&h).await.len(), MAX_PENDING_PER_ADDRESS);
// Other addresses still get in, up to the whole table.
let mut got = MAX_PENDING_PER_ADDRESS;
for n in 0..10u8 {
let from = format!("198.51.100.{}", n + 10);
for i in 0..MAX_PENDING_PER_ADDRESS {
let page = http_from(
&h,
&from,
"GET",
&authorize_path(
&id,
"https://spam.example/cb",
&pkce(300 + i as u32).1,
"acme",
&[],
),
&[],
"",
)
.await;
if page.status == 200 {
got += 1;
} else {
assert_eq!(page.status, 429);
}
.await
}
fn waiting_from(h: &H) -> BTreeMap<String, usize> {
let mut by = BTreeMap::new();
for p in h.books.remote.pending_list() {
*by.entry(p.from).or_insert(0) += 1;
}
by
}
#[tokio::test(flavor = "multi_thread")]
async fn waiting_requests_give_way_and_never_fill_the_window_against_a_real_one() {
let h = harness().await;
let cb = "https://spam.example/cb";
let c = register(&h, "Spam", &[cb]).await;
let id = c["client_id"].as_str().unwrap().to_string();
// One address asks eight times: it is never turned away, but its oldest
// give way, and only five wait.
let mut waits = Vec::new();
for i in 0..8 {
let page = ask(&h, "198.51.100.9", &id, cb, 100 + i).await;
assert_eq!(page.status, 200, "{}", page.body);
waits.push(wait_path(&page));
}
assert_eq!(waiting_from(&h)["198.51.100.9"], MAX_PENDING_PER_ADDRESS);
// The three that gave way were sent back told so, not left hanging.
for gone in &waits[..3] {
let params = location_params(&http(&h, "GET", gone, &[], "").await);
assert_eq!(params["error"], "temporarily_unavailable");
}
// The newest are the ones still waiting.
let still = http(&h, "GET", &waits[7], &[], "").await;
assert_eq!(still.status, 200);
// Three more addresses fill the whole table (4 x 5 = 20) ...
for n in 0..3u8 {
let from = format!("198.51.100.{}", n + 20);
for i in 0..MAX_PENDING_PER_ADDRESS as u32 {
assert_eq!(ask(&h, &from, &id, cb, 200 + i).await.status, 200);
}
}
assert_eq!(got, MAX_PENDING);
assert_eq!(h.books.remote.pending_list().len(), MAX_PENDING);
// ... and a person who is not any of them still gets in: the oldest
// waiting request of the address with the most waiting gives way.
let real = ask(&h, "203.0.113.77", &id, cb, 300).await;
assert_eq!(real.status, 200, "{}", real.body);
let by = waiting_from(&h);
assert_eq!(h.books.remote.pending_list().len(), MAX_PENDING);
assert_eq!(by["203.0.113.77"], 1);
assert_eq!(by["198.51.100.9"], MAX_PENDING_PER_ADDRESS - 1);
// Each card has its own code, and no two waiting are alike.
let list = h.books.remote.pending_list();
let codes: BTreeSet<&String> = list.iter().map(|p| &p.code).collect();
assert_eq!(codes.len(), list.len());
assert!(list.iter().all(|p| p.code.len() == 7 && p.code.chars().nth(3) == Some(' ')));
// They expire unanswered.
h.advance(PENDING_TTL + 1);
assert!(pending(&h).await.is_empty());
}
/// An IPv6 caller is counted by its /64, and an IPv4-mapped IPv6 address
/// is the IPv4 one: neither is a way round a limit.
#[tokio::test(flavor = "multi_thread")]
async fn limits_count_an_ipv6_64_as_one_caller_and_a_mapped_address_as_its_ipv4() {
assert_eq!(
address_key("2001:db8:1:2::1".parse().unwrap()),
address_key("2001:db8:1:2:ffff:ffff:ffff:ffff".parse().unwrap())
);
assert_ne!(
address_key("2001:db8:1:2::1".parse().unwrap()),
address_key("2001:db8:1:3::1".parse().unwrap())
);
assert_eq!(
address_key("::ffff:203.0.113.9".parse().unwrap()),
address_key("203.0.113.9".parse().unwrap())
);
assert_eq!(
Caller::new("::ffff:203.0.113.9".parse().unwrap()).shown,
"203.0.113.9"
);
// End to end: registrations from many addresses of one /64 share its
// limit.
let h = harness().await;
for i in 0..REGISTER_PER_ADDRESS {
let from = format!("[2001:db8:1:2:{:x}::1]", i + 1);
let r = http_from(
&h,
&from,
"POST",
"/register",
&[("Content-Type", "application/json")],
&json!({"redirect_uris": ["https://x.example/cb"]}).to_string(),
)
.await;
assert_eq!(r.status, 201, "{i}");
}
let over = http_from(
&h,
"[2001:db8:1:2:ffff::1]",
"POST",
"/register",
&[("Content-Type", "application/json")],
&json!({"redirect_uris": ["https://x.example/cb"]}).to_string(),
)
.await;
assert_eq!(over.status, 429);
// Another /64 is not shut out for it.
let other = http_from(
&h,
"[2001:db8:1:9::1]",
"POST",
"/register",
&[("Content-Type", "application/json")],
&json!({"redirect_uris": ["https://x.example/cb"]}).to_string(),
)
.await;
assert_eq!(other.status, 201);
}
// ---- the doors ------------------------------------------------------------------------
#[tokio::test(flavor = "multi_thread")]
@@ -1702,7 +1978,13 @@ async fn refresh_tokens_survive_a_restart_and_only_their_hashes_are_kept() {
("refresh_token".to_string(), refresh_token.clone()),
]);
let out = again
.token(&h.books, &door, &form, None, "203.0.113.9")
.token(
&h.books,
&door,
&form,
None,
&Caller::new("203.0.113.9".parse().unwrap()),
)
.await
.unwrap_or_else(|e| panic!("{}", e.description));
assert!(out["access_token"].as_str().unwrap().starts_with("wba_"));