fix(mcp): the remote door's limits, disk cost, names and front line after review (P15 B1)
Per-address limits count an IPv4 address or an IPv6 /64 (mapped addresses as the IPv4 one) and the table evicts per-address entries only, never a connection's own call limit; waiting requests give way to a new one (an address's oldest, or the fullest address's) instead of filling the window; a stale client document is used when the fetch budget is spent and nothing is fetched from /token. Registrations nobody allowed live in memory only, a redirect is at most 512 bytes and a client's together 4 KiB. An error of a sign-in for a client nobody approved is a page, never a redirect. Names lose invisible and direction-changing characters and are cut to forty; a revoked key frees its place; calls refused for rate or another company's books are counted, not written, the limit asked first. The client document fetch refuses ::/96 and 2002::/16, uses no proxy; the host is read from the request's authority under HTTP/2; remote.json is private on Windows too; every connection must begin with a per-start secret before the PROXY header, given to the app over the admin socket. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
c4fd1580d8
commit
32acdc1c44
8 files changed
+734
-117
No files matched your search
@@ -647,7 +647,10 @@ impl State {
|
|||||||
let what = if approve {
|
let what = if approve {
|
||||||
format!("Allow the assistant sent back to {}", request.redirect_host)
|
format!("Allow the assistant sent back to {}", request.redirect_host)
|
||||||
} else {
|
} else {
|
||||||
format!("Don't allow the assistant sent back to {}", request.redirect_host)
|
format!(
|
||||||
|
"Don't allow the assistant sent back to {}",
|
||||||
|
request.redirect_host
|
||||||
|
)
|
||||||
};
|
};
|
||||||
Some((
|
Some((
|
||||||
what,
|
what,
|
||||||
@@ -891,7 +894,7 @@ pub const MOST_CARDS: usize = 3;
|
|||||||
fn newest_waiting(all: &[crate::owner::WebRequest]) -> (Vec<&crate::owner::WebRequest>, usize) {
|
fn newest_waiting(all: &[crate::owner::WebRequest]) -> (Vec<&crate::owner::WebRequest>, usize) {
|
||||||
let mut sorted: Vec<&crate::owner::WebRequest> = all.iter().collect();
|
let mut sorted: Vec<&crate::owner::WebRequest> = all.iter().collect();
|
||||||
// Most time left is the newest.
|
// Most time left is the newest.
|
||||||
sorted.sort_by(|a, b| b.expires_in_secs.cmp(&a.expires_in_secs));
|
sorted.sort_by_key(|r| std::cmp::Reverse(r.expires_in_secs));
|
||||||
let more = sorted.len().saturating_sub(MOST_CARDS);
|
let more = sorted.len().saturating_sub(MOST_CARDS);
|
||||||
sorted.truncate(MOST_CARDS);
|
sorted.truncate(MOST_CARDS);
|
||||||
(sorted, more)
|
(sorted, more)
|
||||||
|
|||||||
@@ -1107,11 +1107,7 @@ fn with_pending(owner: &Fake, pending: Vec<WebRequest>, approvals: Vec<WebApprov
|
|||||||
fn a_web_assistant_asking_is_put_to_the_person_over_any_page_in_plain_words() {
|
fn a_web_assistant_asking_is_put_to_the_person_over_any_page_in_plain_words() {
|
||||||
let w = World::new(&[("alpha", "Wanderland Labs")]);
|
let w = World::new(&[("alpha", "Wanderland Labs")]);
|
||||||
let owner = Fake::new();
|
let owner = Fake::new();
|
||||||
with_pending(
|
with_pending(&owner, vec![asking("p_1", "Claude", true)], vec![]);
|
||||||
&owner,
|
|
||||||
vec![asking("p_1", "Claude", true)],
|
|
||||||
vec![],
|
|
||||||
);
|
|
||||||
let mut h = start(&w, &["alpha"], &owner);
|
let mut h = start(&w, &["alpha"], &owner);
|
||||||
refresh(&mut h);
|
refresh(&mut h);
|
||||||
// On the company's own page, not the Connect page.
|
// On the company's own page, not the Connect page.
|
||||||
@@ -1126,7 +1122,10 @@ fn a_web_assistant_asking_is_put_to_the_person_over_any_page_in_plain_words() {
|
|||||||
.is_some()
|
.is_some()
|
||||||
);
|
);
|
||||||
assert!(h.query_by_label_contains("Claude on the web").is_none());
|
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());
|
assert!(
|
||||||
|
h.query_by_label_contains("doesn't know this address")
|
||||||
|
.is_none()
|
||||||
|
);
|
||||||
// What it calls itself, after the address, as its own word.
|
// What it calls itself, after the address, as its own word.
|
||||||
assert!(h.query_by_label_contains("It calls itself").is_some());
|
assert!(h.query_by_label_contains("It calls itself").is_some());
|
||||||
// The code to match with the one the browser's page shows.
|
// The code to match with the one the browser's page shows.
|
||||||
@@ -1179,7 +1178,10 @@ fn refusing_and_allowing_with_posting_are_their_own_answers() {
|
|||||||
let mut h = start(&w, &["alpha"], &owner);
|
let mut h = start(&w, &["alpha"], &owner);
|
||||||
refresh(&mut h);
|
refresh(&mut h);
|
||||||
// An address that isn't a known vendor's keeps its warning.
|
// 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());
|
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.get_by_role_and_label(Role::Button, "Don't allow").click();
|
||||||
h.run_steps(2);
|
h.run_steps(2);
|
||||||
wait_for("the refusal was given", || {
|
wait_for("the refusal was given", || {
|
||||||
@@ -1190,11 +1192,7 @@ fn refusing_and_allowing_with_posting_are_their_own_answers() {
|
|||||||
refresh(&mut h);
|
refresh(&mut h);
|
||||||
assert!(h.query_by_label_contains("wants to connect").is_none());
|
assert!(h.query_by_label_contains("wants to connect").is_none());
|
||||||
// Another asks; this time posting is ticked, then allowed.
|
// Another asks; this time posting is ticked, then allowed.
|
||||||
with_pending(
|
with_pending(&owner, vec![asking("p_8", "Claude", true)], vec![]);
|
||||||
&owner,
|
|
||||||
vec![asking("p_8", "Claude", true)],
|
|
||||||
vec![],
|
|
||||||
);
|
|
||||||
refresh(&mut h);
|
refresh(&mut h);
|
||||||
h.get_by_label("Also let it post entries").click();
|
h.get_by_label("Also let it post entries").click();
|
||||||
h.run_steps(2);
|
h.run_steps(2);
|
||||||
@@ -1227,20 +1225,20 @@ fn waiting_requests_each_show_their_own_code_and_only_a_few_are_drawn() {
|
|||||||
// The newest three, each with its own code; the rest are counted.
|
// The newest three, each with its own code; the rest are counted.
|
||||||
for shown in ["444 644", "333 633", "222 622"] {
|
for shown in ["444 644", "333 633", "222 622"] {
|
||||||
assert!(
|
assert!(
|
||||||
h.query_by_label_contains(&format!("Code {shown}")).is_some(),
|
h.query_by_label_contains(&format!("Code {shown}"))
|
||||||
|
.is_some(),
|
||||||
"{shown}"
|
"{shown}"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
for hidden in ["111 611", "000 600"] {
|
for hidden in ["111 611", "000 600"] {
|
||||||
assert!(
|
assert!(
|
||||||
h.query_by_label_contains(&format!("Code {hidden}")).is_none(),
|
h.query_by_label_contains(&format!("Code {hidden}"))
|
||||||
|
.is_none(),
|
||||||
"{hidden}"
|
"{hidden}"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
assert_eq!(
|
// Three cards (their titles end in the question); the window has its own title.
|
||||||
h.query_all_by_label_contains("wants to connect").count(),
|
assert_eq!(h.query_all_by_label_contains("Allow?").count(), 3);
|
||||||
3
|
|
||||||
);
|
|
||||||
assert!(h.query_by_label_contains("2 more are waiting").is_some());
|
assert!(h.query_by_label_contains("2 more are waiting").is_some());
|
||||||
drop(h);
|
drop(h);
|
||||||
}
|
}
|
||||||
@@ -1249,11 +1247,7 @@ fn waiting_requests_each_show_their_own_code_and_only_a_few_are_drawn() {
|
|||||||
fn a_request_that_ran_out_goes_away_and_posting_is_turned_on_and_off_on_the_connect_page() {
|
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 w = World::new(&[("alpha", "Wanderland Labs")]);
|
||||||
let owner = Fake::new();
|
let owner = Fake::new();
|
||||||
with_pending(
|
with_pending(&owner, vec![asking("p_2", "Claude", true)], vec![]);
|
||||||
&owner,
|
|
||||||
vec![asking("p_2", "Claude", true)],
|
|
||||||
vec![],
|
|
||||||
);
|
|
||||||
let mut h = start(&w, &["alpha"], &owner);
|
let mut h = start(&w, &["alpha"], &owner);
|
||||||
refresh(&mut h);
|
refresh(&mut h);
|
||||||
assert!(
|
assert!(
|
||||||
|
|||||||
@@ -395,6 +395,12 @@ pub struct RemoteInfo {
|
|||||||
pub public_url: Option<String>,
|
pub public_url: Option<String>,
|
||||||
/// The books it offers.
|
/// The books it offers.
|
||||||
pub allowed: Vec<String>,
|
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
|
/// An assistant waiting for the person to allow it (INVARIANT 10): what
|
||||||
|
|||||||
@@ -14,9 +14,11 @@
|
|||||||
//! fragment, is fetched; the host's addresses are all looked up
|
//! fragment, is fetched; the host's addresses are all looked up
|
||||||
//! first, and every one must be a public address (none loopback,
|
//! first, and every one must be a public address (none loopback,
|
||||||
//! private, link-local, shared, documentation, multicast or
|
//! private, link-local, shared, documentation, multicast or
|
||||||
//! unspecified, and no IPv4-mapped form of one): a name that points
|
//! 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
|
//! into the owner's network is refused, and the connection is made to
|
||||||
//! the address that was checked, not to a second lookup.
|
//! 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
|
//! 2. No redirect is followed; the answer must be 200, at most
|
||||||
//! MAX_DOCUMENT bytes, within FETCH_TIME.
|
//! MAX_DOCUMENT bytes, within FETCH_TIME.
|
||||||
//! 3. The document's `client_id` must be exactly the address it was
|
//! 3. The document's `client_id` must be exactly the address it was
|
||||||
|
|||||||
@@ -10,7 +10,8 @@
|
|||||||
//! 401 and its challenge); plan/p15-app-and-relay.md 4 rules 1, 4, 5.
|
//! 401 and its challenge); plan/p15-app-and-relay.md 4 rules 1, 4, 5.
|
||||||
//! INVARIANTS:
|
//! INVARIANTS:
|
||||||
//! 1. A request is answered only while the door is on, and only if its
|
//! 1. A request is answered only while the door is on, and only if its
|
||||||
//! Host is the public address's host (421 otherwise); a request that
|
//! 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).
|
//! has an Origin must have the public address's (403).
|
||||||
//! 2. Every address in a metadata document is built from the public
|
//! 2. Every address in a metadata document is built from the public
|
||||||
//! address the app gave and from nothing in the request.
|
//! address the app gave and from nothing in the request.
|
||||||
@@ -114,20 +115,29 @@ pub(in crate::local) fn start_door(
|
|||||||
let listener = tokio::net::TcpListener::from_std(listener)
|
let listener = tokio::net::TcpListener::from_std(listener)
|
||||||
.map_err(|e| format!("the door can't listen ({})", e.kind()))?;
|
.map_err(|e| format!("the door can't listen ({})", e.kind()))?;
|
||||||
let stop = books.sessions.child_token();
|
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 {
|
let door = Arc::new(Door {
|
||||||
issuer: issuer.clone(),
|
issuer: issuer.clone(),
|
||||||
host: host_header_form(&issuer),
|
host: host_header_form(&issuer),
|
||||||
listening,
|
listening,
|
||||||
stop: stop.clone(),
|
stop: stop.clone(),
|
||||||
|
secret: secret.clone(),
|
||||||
});
|
});
|
||||||
remote.set_door(Some(door));
|
remote.set_door(Some(door));
|
||||||
let app = remote_router(books.clone());
|
let app = remote_router(books.clone());
|
||||||
let accept_stop = stop.clone();
|
let accept_stop = stop.clone();
|
||||||
handle.spawn(proxy::accept_loop(listener, stop, move |io, caller| {
|
handle.spawn(proxy::accept_loop(
|
||||||
let app = app.clone().layer(Extension(Peer(caller)));
|
listener,
|
||||||
let stop = accept_stop.clone();
|
stop,
|
||||||
tokio::spawn(serve_connection(io, app, 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())
|
Ok(remote.info())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -288,8 +298,13 @@ fn answer(a: Authorize) -> Response {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The door is on, and this request is for its one public host
|
/// The door is on, and this request is for its one public host
|
||||||
/// (INVARIANT 1).
|
/// (INVARIANT 1). The host is the `Host` header's; under HTTP/2 there is
|
||||||
fn front(books: &Books, headers: &HeaderMap) -> Result<Arc<Door>, Box<Response>> {
|
/// 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 {
|
let Some(door) = books.remote.door() else {
|
||||||
return Err(Box::new(no_store(
|
return Err(Box::new(no_store(
|
||||||
(StatusCode::SERVICE_UNAVAILABLE, "web assistants are off").into_response(),
|
(StatusCode::SERVICE_UNAVAILABLE, "web assistants are off").into_response(),
|
||||||
@@ -300,6 +315,7 @@ fn front(books: &Books, headers: &HeaderMap) -> Result<Arc<Door>, Box<Response>>
|
|||||||
let host = headers
|
let host = headers
|
||||||
.get(header::HOST)
|
.get(header::HOST)
|
||||||
.and_then(|h| h.to_str().ok())
|
.and_then(|h| h.to_str().ok())
|
||||||
|
.or_else(|| uri.authority().map(|a| a.as_str()))
|
||||||
.map(str::to_ascii_lowercase)
|
.map(str::to_ascii_lowercase)
|
||||||
.map(|h| {
|
.map(|h| {
|
||||||
let plain = door.issuer.starts_with("https://");
|
let plain = door.issuer.starts_with("https://");
|
||||||
@@ -314,8 +330,12 @@ fn front(books: &Books, headers: &HeaderMap) -> Result<Arc<Door>, Box<Response>>
|
|||||||
Ok(door)
|
Ok(door)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn preflight(State(books): State<Arc<Books>>, headers: HeaderMap) -> Response {
|
async fn preflight(
|
||||||
if let Err(r) = front(&books, &headers) {
|
State(books): State<Arc<Books>>,
|
||||||
|
uri: axum::http::Uri,
|
||||||
|
headers: HeaderMap,
|
||||||
|
) -> Response {
|
||||||
|
if let Err(r) = front(&books, &headers, &uri) {
|
||||||
return *r;
|
return *r;
|
||||||
}
|
}
|
||||||
cors(StatusCode::NO_CONTENT.into_response())
|
cors(StatusCode::NO_CONTENT.into_response())
|
||||||
@@ -334,10 +354,11 @@ fn parse_pairs(text: &str) -> BTreeMap<String, String> {
|
|||||||
async fn register(
|
async fn register(
|
||||||
State(books): State<Arc<Books>>,
|
State(books): State<Arc<Books>>,
|
||||||
Extension(peer): Extension<Peer>,
|
Extension(peer): Extension<Peer>,
|
||||||
|
uri: axum::http::Uri,
|
||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
body: axum::body::Body,
|
body: axum::body::Body,
|
||||||
) -> Response {
|
) -> Response {
|
||||||
if let Err(r) = front(&books, &headers) {
|
if let Err(r) = front(&books, &headers, &uri) {
|
||||||
return *r;
|
return *r;
|
||||||
}
|
}
|
||||||
let Ok(bytes) = axum::body::to_bytes(body, MAX_FORM).await else {
|
let Ok(bytes) = axum::body::to_bytes(body, MAX_FORM).await else {
|
||||||
@@ -367,10 +388,11 @@ async fn register(
|
|||||||
async fn authorize(
|
async fn authorize(
|
||||||
State(books): State<Arc<Books>>,
|
State(books): State<Arc<Books>>,
|
||||||
Extension(peer): Extension<Peer>,
|
Extension(peer): Extension<Peer>,
|
||||||
|
uri: axum::http::Uri,
|
||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
Query(q): Query<BTreeMap<String, String>>,
|
Query(q): Query<BTreeMap<String, String>>,
|
||||||
) -> Response {
|
) -> Response {
|
||||||
let door = match front(&books, &headers) {
|
let door = match front(&books, &headers, &uri) {
|
||||||
Ok(d) => d,
|
Ok(d) => d,
|
||||||
Err(r) => return *r,
|
Err(r) => return *r,
|
||||||
};
|
};
|
||||||
@@ -384,10 +406,11 @@ async fn authorize(
|
|||||||
|
|
||||||
async fn wait(
|
async fn wait(
|
||||||
State(books): State<Arc<Books>>,
|
State(books): State<Arc<Books>>,
|
||||||
|
uri: axum::http::Uri,
|
||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
Path(wait): Path<String>,
|
Path(wait): Path<String>,
|
||||||
) -> Response {
|
) -> Response {
|
||||||
if let Err(r) = front(&books, &headers) {
|
if let Err(r) = front(&books, &headers, &uri) {
|
||||||
return *r;
|
return *r;
|
||||||
}
|
}
|
||||||
answer(books.remote.wait(&books, &wait))
|
answer(books.remote.wait(&books, &wait))
|
||||||
@@ -396,10 +419,11 @@ async fn wait(
|
|||||||
async fn token(
|
async fn token(
|
||||||
State(books): State<Arc<Books>>,
|
State(books): State<Arc<Books>>,
|
||||||
Extension(peer): Extension<Peer>,
|
Extension(peer): Extension<Peer>,
|
||||||
|
uri: axum::http::Uri,
|
||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
body: axum::body::Body,
|
body: axum::body::Body,
|
||||||
) -> Response {
|
) -> Response {
|
||||||
let door = match front(&books, &headers) {
|
let door = match front(&books, &headers, &uri) {
|
||||||
Ok(d) => d,
|
Ok(d) => d,
|
||||||
Err(r) => return *r,
|
Err(r) => return *r,
|
||||||
};
|
};
|
||||||
@@ -504,7 +528,7 @@ async fn fallback(
|
|||||||
uri: axum::http::Uri,
|
uri: axum::http::Uri,
|
||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
) -> Response {
|
) -> Response {
|
||||||
let door = match front(&books, &headers) {
|
let door = match front(&books, &headers, &uri) {
|
||||||
Ok(d) => d,
|
Ok(d) => d,
|
||||||
Err(r) => return *r,
|
Err(r) => return *r,
|
||||||
};
|
};
|
||||||
@@ -561,7 +585,7 @@ async fn remote_mcp(
|
|||||||
Path(book): Path<String>,
|
Path(book): Path<String>,
|
||||||
request: axum::extract::Request,
|
request: axum::extract::Request,
|
||||||
) -> Response {
|
) -> Response {
|
||||||
let door = match front(&books, request.headers()) {
|
let door = match front(&books, request.headers(), request.uri()) {
|
||||||
Ok(d) => d,
|
Ok(d) => d,
|
||||||
Err(r) => return *r,
|
Err(r) => return *r,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -23,8 +23,10 @@
|
|||||||
//! 1. Off unless asked: the door listens on 127.0.0.1 only after an
|
//! 1. Off unless asked: the door listens on 127.0.0.1 only after an
|
||||||
//! admin request (`RemoteStart`) and stops on `RemoteStop` or when the
|
//! admin request (`RemoteStart`) and stops on `RemoteStop` or when the
|
||||||
//! server closes. It serves a company only while that company is
|
//! server closes. It serves a company only while that company is
|
||||||
//! allowed (`RemoteAllow`) AND open. Every connection begins with the
|
//! allowed (`RemoteAllow`) AND open. Every connection begins with this
|
||||||
//! relay's PROXY header (proxy.rs); the address in it is the caller's,
|
//! start's secret and then the relay's PROXY header (proxy.rs): only
|
||||||
|
//! the app, which is given the secret over the admin socket, can say a
|
||||||
|
//! caller's address. The address in the header is the caller's,
|
||||||
//! is what the access record and the limits use, and is never taken
|
//! is what the access record and the limits use, and is never taken
|
||||||
//! from an HTTP header. Nothing on this door is ever treated as local:
|
//! from an HTTP header. Nothing on this door is ever treated as local:
|
||||||
//! every request needs a token, and the local socket's same-user check
|
//! every request needs a token, and the local socket's same-user check
|
||||||
@@ -46,33 +48,42 @@
|
|||||||
//! carry up to MAX_REDIRECTS. PKCE with S256 is required; the
|
//! carry up to MAX_REDIRECTS. PKCE with S256 is required; the
|
||||||
//! `resource` must be the one company's address; a code is single-use
|
//! `resource` must be the one company's address; a code is single-use
|
||||||
//! and lives CODE_TTL; the consent ends in a 302.
|
//! and lives CODE_TTL; the consent ends in a 302.
|
||||||
//! 5. No approval without the person. `/authorize` never approves: it
|
//! 5. No approval without the person, and every sign-in is asked (D-90).
|
||||||
//! parks the request (PENDING_TTL), and only an admin request, which
|
//! `/authorize` never approves and always parks the request
|
||||||
//! the owner-only admin socket carries, turns a parked request into a
|
//! (PENDING_TTL), whatever the product and whatever was approved
|
||||||
//! code. A parked request is named by two unrelated random ids: the
|
//! before: the redirect host is public, so it says nothing of whose
|
||||||
//! one the window shows, and the one only the browser's page holds.
|
//! account asks. Only an admin request, which the owner-only admin
|
||||||
//! Neither a stranger's guess nor a replay approves anything: the
|
//! socket carries, turns a parked request into a code. A parked
|
||||||
//! second id only reads the outcome, once.
|
//! request is named by two unrelated random ids: the one the window
|
||||||
//! 6. An approval is the owner's decision about a product, a company and
|
//! shows, and the one only the browser's page holds; and carries a
|
||||||
//! a set of permissions, and survives a product registering again: it
|
//! short code shown on the page and on the card, for the person to
|
||||||
//! is one token of the books' principals (so "Who can reach these
|
//! match. Neither a stranger's guess nor a replay approves anything:
|
||||||
//! books" lists it, and revoking it by id ends every access and
|
//! the second id only reads the outcome, once. The window is told
|
||||||
//! refresh token made under it), plus a record here naming the
|
//! what is known in neutral words: where it is sent back to, and its
|
||||||
//! product. Access tokens live ACCESS_TTL; refresh tokens REFRESH_TTL
|
//! own cleaned word for itself; never "a known product".
|
||||||
//! since last use, rotated at every use, and a refresh token used
|
//! 6. An approval is the owner's decision about one sign-in, a company and
|
||||||
//! twice ends its whole family.
|
//! a set of permissions, never reused: it is one token of the books'
|
||||||
|
//! principals (so "Who can reach these books" lists it, and revoking
|
||||||
|
//! it by id ends every access and refresh token made under it, at
|
||||||
|
//! that moment), plus a record here. Every Allow makes a new one with
|
||||||
|
//! exactly the permissions ticked. Access tokens live ACCESS_TTL;
|
||||||
|
//! refresh tokens REFRESH_TTL since last use, rotated at every use
|
||||||
|
//! (checked and marked in one hold of the lock), and a refresh token
|
||||||
|
//! used twice ends its whole family.
|
||||||
//! 7. Secrets are never stored: codes, access tokens, refresh tokens and
|
//! 7. Secrets are never stored: codes, access tokens, refresh tokens and
|
||||||
//! client secrets are kept as SHA-256 only, and compared by hash (or
|
//! client secrets are kept as SHA-256 only, and compared by hash (or
|
||||||
//! in constant time where a hash is compared to a hash).
|
//! in constant time where a hash is compared to a hash).
|
||||||
//! 8. Every table is bounded (MAX_* below) and expires: registered
|
//! 8. Every table is bounded (MAX_* below) and expires: registered
|
||||||
//! clients unused for CLIENT_IDLE, pending requests, codes, access
|
//! clients unused for CLIENT_IDLE (held in memory until the person
|
||||||
//! tokens, refresh tokens. A stranger registering clients, or asking
|
//! allows one), pending requests (which give way to newer ones rather
|
||||||
//! to sign in, can fill none of them; a failure to sign in is never
|
//! than turn them away), codes, access tokens, refresh tokens. A
|
||||||
//! ground for banning an address (vendors share addresses), only the
|
//! stranger registering clients, or asking to sign in, can fill none
|
||||||
//! state a request creates is bounded, and an approval's own calls
|
//! of them, nor the file; a failure to sign in is never ground for
|
||||||
//! are limited.
|
//! banning an address (vendors share addresses), only the state a
|
||||||
|
//! request creates is bounded, and an approval's own calls are
|
||||||
|
//! limited. Addresses are counted per IPv4 address or IPv6 /64.
|
||||||
//! 9. No company mixing: a token for company A, presented at company
|
//! 9. No company mixing: a token for company A, presented at company
|
||||||
//! B's path, is refused (403, recorded as the token's own refusal); a
|
//! B's path, is refused (403, counted, not written); a
|
||||||
//! code and a refresh token carry their company and never issue a
|
//! code and a refresh token carry their company and never issue a
|
||||||
//! token for another.
|
//! token for another.
|
||||||
//! 10. Remote permissions: an approval grants read and draft; posting is
|
//! 10. Remote permissions: an approval grants read and draft; posting is
|
||||||
@@ -379,6 +390,9 @@ pub(super) struct Door {
|
|||||||
pub host: String,
|
pub host: String,
|
||||||
pub listening: SocketAddr,
|
pub listening: SocketAddr,
|
||||||
pub stop: CancellationToken,
|
pub stop: CancellationToken,
|
||||||
|
/// This start's secret: the app begins every connection with it
|
||||||
|
/// (proxy.rs INVARIANT 5).
|
||||||
|
pub secret: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Why a token is refused at the door.
|
/// Why a token is refused at the door.
|
||||||
@@ -967,7 +981,8 @@ impl Remote {
|
|||||||
let door = self.door();
|
let door = self.door();
|
||||||
RemoteInfo {
|
RemoteInfo {
|
||||||
listening: door.as_ref().map(|d| d.listening.to_string()),
|
listening: door.as_ref().map(|d| d.listening.to_string()),
|
||||||
public_url: door.map(|d| d.issuer.clone()),
|
public_url: door.as_ref().map(|d| d.issuer.clone()),
|
||||||
|
proxy_secret: door.map(|d| crate::admin::TokenText(d.secret.clone())),
|
||||||
allowed: self
|
allowed: self
|
||||||
.allowed
|
.allowed
|
||||||
.read()
|
.read()
|
||||||
@@ -1159,13 +1174,7 @@ impl Remote {
|
|||||||
None => None,
|
None => None,
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let unknown = || {
|
let unknown = || OauthError::new(401, "invalid_client", "that client_id isn't known here");
|
||||||
OauthError::new(
|
|
||||||
401,
|
|
||||||
"invalid_client",
|
|
||||||
"that client_id isn't known here",
|
|
||||||
)
|
|
||||||
};
|
|
||||||
if !id.starts_with("https://") || !may_fetch {
|
if !id.starts_with("https://") || !may_fetch {
|
||||||
return stale.ok_or_else(unknown);
|
return stale.ok_or_else(unknown);
|
||||||
}
|
}
|
||||||
@@ -1839,7 +1848,9 @@ impl Remote {
|
|||||||
.swapped
|
.swapped
|
||||||
.insert(approval.token_id.clone(), token.id.clone());
|
.insert(approval.token_id.clone(), token.id.clone());
|
||||||
approval.token_id = token.id;
|
approval.token_id = token.id;
|
||||||
inner.approvals.insert(approval.id.clone(), approval.clone());
|
inner
|
||||||
|
.approvals
|
||||||
|
.insert(approval.id.clone(), approval.clone());
|
||||||
approval
|
approval
|
||||||
};
|
};
|
||||||
self.save()?;
|
self.save()?;
|
||||||
@@ -2185,19 +2196,27 @@ impl Remote {
|
|||||||
let mut inner = self.inner();
|
let mut inner = self.inner();
|
||||||
self.sweep(&mut inner);
|
self.sweep(&mut inner);
|
||||||
match inner.refresh.get(&key).cloned() {
|
match inner.refresh.get(&key).cloned() {
|
||||||
None => Err((bad("that refresh token is invalid, used, or has expired"), false)),
|
None => Err((
|
||||||
|
bad("that refresh token is invalid, used, or has expired"),
|
||||||
|
false,
|
||||||
|
)),
|
||||||
Some(rec) if rec.used => {
|
Some(rec) if rec.used => {
|
||||||
// Used twice: the family is over (RFC 9700 4.14).
|
// Used twice: the family is over (RFC 9700 4.14).
|
||||||
inner.refresh.retain(|_, r| r.family != rec.family);
|
inner.refresh.retain(|_, r| r.family != rec.family);
|
||||||
inner.access.retain(|_, a| a.family != rec.family);
|
inner.access.retain(|_, a| a.family != rec.family);
|
||||||
Err((bad("that refresh token was already used: sign in again"), true))
|
Err((
|
||||||
}
|
bad("that refresh token was already used: sign in again"),
|
||||||
Some(rec) if rec.client != client.id => {
|
true,
|
||||||
Err((bad("that refresh token belongs to another assistant"), false))
|
))
|
||||||
}
|
|
||||||
Some(rec) if rec.issuer != door.issuer => {
|
|
||||||
Err((bad("that refresh token was made for another address"), false))
|
|
||||||
}
|
}
|
||||||
|
Some(rec) if rec.client != client.id => Err((
|
||||||
|
bad("that refresh token belongs to another assistant"),
|
||||||
|
false,
|
||||||
|
)),
|
||||||
|
Some(rec) if rec.issuer != door.issuer => Err((
|
||||||
|
bad("that refresh token was made for another address"),
|
||||||
|
false,
|
||||||
|
)),
|
||||||
Some(rec) => match inner.approvals.get(&rec.approval).cloned() {
|
Some(rec) => match inner.approvals.get(&rec.approval).cloned() {
|
||||||
None => Err((bad("that connection no longer exists"), false)),
|
None => Err((bad("that connection no longer exists"), false)),
|
||||||
Some(approval)
|
Some(approval)
|
||||||
|
|||||||
@@ -10,7 +10,16 @@
|
|||||||
//! address); the PROXY protocol specification version 2;
|
//! address); the PROXY protocol specification version 2;
|
||||||
//! plan/p15-app-and-relay.md 4, rule 8.
|
//! plan/p15-app-and-relay.md 4, rule 8.
|
||||||
//! INVARIANTS:
|
//! INVARIANTS:
|
||||||
//! 1. Every connection to the remote door starts with exactly the header
|
//! 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
|
//! the relay writes: the 12-byte signature, version 2 with the PROXY
|
||||||
//! command, then TCP over IPv4 (length 12) or IPv6 (length 36) and
|
//! command, then TCP over IPv4 (length 12) or IPv6 (length 36) and
|
||||||
//! the addresses. A connection that starts with anything else, that
|
//! the addresses. A connection that starts with anything else, that
|
||||||
@@ -45,6 +54,18 @@ pub const SIGNATURE: [u8; 12] = [
|
|||||||
0x0D, 0x0A, 0x0D, 0x0A, 0x00, 0x0D, 0x0A, 0x51, 0x55, 0x49, 0x54, 0x0A,
|
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.
|
/// How long a connection has to send its header.
|
||||||
pub const HEADER_WAIT: Duration = Duration::from_secs(5);
|
pub const HEADER_WAIT: Duration = Duration::from_secs(5);
|
||||||
|
|
||||||
@@ -58,6 +79,28 @@ pub enum Refused {
|
|||||||
NotAHeader,
|
NotAHeader,
|
||||||
/// The stream ended, or failed, inside it.
|
/// The stream ended, or failed, inside it.
|
||||||
Cut,
|
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
|
/// Read the header from the front of `stream`, giving the caller's
|
||||||
@@ -96,8 +139,8 @@ pub async fn read_header<R: AsyncRead + Unpin>(stream: &mut R) -> Result<SocketA
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The header for a caller `source` that reached `destination`, in the
|
/// The header for a caller `source` that reached `destination`, in the
|
||||||
/// form the relay writes (what the app writes to this door, B3; and the
|
/// form the relay writes (what the app writes to this door, B3, after the
|
||||||
/// tests).
|
/// secret; and the tests).
|
||||||
#[allow(dead_code)] // the app writes it to this door (unit B3); the tests do now
|
#[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> {
|
pub fn encode(source: SocketAddr, destination: SocketAddr) -> Vec<u8> {
|
||||||
let mut out = Vec::with_capacity(52);
|
let mut out = Vec::with_capacity(52);
|
||||||
@@ -171,6 +214,7 @@ impl AsyncWrite for Proxied {
|
|||||||
pub async fn accept_loop(
|
pub async fn accept_loop(
|
||||||
listener: TcpListener,
|
listener: TcpListener,
|
||||||
stop: tokio_util::sync::CancellationToken,
|
stop: tokio_util::sync::CancellationToken,
|
||||||
|
secret: String,
|
||||||
mut handle: impl FnMut(Proxied, SocketAddr) + Send + 'static,
|
mut handle: impl FnMut(Proxied, SocketAddr) + Send + 'static,
|
||||||
) {
|
) {
|
||||||
let places = std::sync::Arc::new(Semaphore::new(MAX_CONNECTIONS));
|
let places = std::sync::Arc::new(Semaphore::new(MAX_CONNECTIONS));
|
||||||
@@ -195,8 +239,13 @@ pub async fn accept_loop(
|
|||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
let tx = tx.clone();
|
let tx = tx.clone();
|
||||||
|
let secret = secret.clone();
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
let read = tokio::time::timeout(HEADER_WAIT, read_header(&mut io)).await;
|
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 {
|
if let Ok(Ok(caller)) = read {
|
||||||
let _ = tx.send((Proxied { io, _place: place }, caller)).await;
|
let _ = tx.send((Proxied { io, _place: place }, caller)).await;
|
||||||
}
|
}
|
||||||
@@ -241,6 +290,36 @@ mod tests {
|
|||||||
assert_eq!(read_header(&mut slice).await, Ok(addr("203.0.113.9:5")));
|
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]
|
#[tokio::test]
|
||||||
async fn anything_but_the_exact_form_is_refused() {
|
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 good = encode(addr("203.0.113.9:51000"), addr("198.51.100.1:443"));
|
||||||
|
|||||||
@@ -21,6 +21,8 @@ const CALLER: &str = "203.0.113.9";
|
|||||||
struct H {
|
struct H {
|
||||||
books: Arc<Books>,
|
books: Arc<Books>,
|
||||||
addr: SocketAddr,
|
addr: SocketAddr,
|
||||||
|
/// This start's secret, as the app is given it.
|
||||||
|
secret: String,
|
||||||
clock: Arc<AtomicI64>,
|
clock: Arc<AtomicI64>,
|
||||||
_home: Arc<tempfile::TempDir>,
|
_home: Arc<tempfile::TempDir>,
|
||||||
}
|
}
|
||||||
@@ -65,6 +67,7 @@ async fn harness() -> H {
|
|||||||
let mut h = H {
|
let mut h = H {
|
||||||
books,
|
books,
|
||||||
addr: "127.0.0.1:1".parse().unwrap(),
|
addr: "127.0.0.1:1".parse().unwrap(),
|
||||||
|
secret: String::new(),
|
||||||
clock,
|
clock,
|
||||||
_home: Arc::new(home),
|
_home: Arc::new(home),
|
||||||
};
|
};
|
||||||
@@ -83,7 +86,10 @@ impl H {
|
|||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
Response::Remote(info) => self.addr = info.listening.unwrap().parse().unwrap(),
|
Response::Remote(info) => {
|
||||||
|
self.addr = info.listening.unwrap().parse().unwrap();
|
||||||
|
self.secret = info.proxy_secret.unwrap().0;
|
||||||
|
}
|
||||||
other => panic!("{other:?}"),
|
other => panic!("{other:?}"),
|
||||||
}
|
}
|
||||||
for book in ["acme", "beta"] {
|
for book in ["acme", "beta"] {
|
||||||
@@ -207,10 +213,11 @@ async fn http_from(
|
|||||||
extra: &[(&str, &str)],
|
extra: &[(&str, &str)],
|
||||||
body: &str,
|
body: &str,
|
||||||
) -> Resp {
|
) -> Resp {
|
||||||
let mut bytes = proxy::encode(
|
let mut bytes = h.secret.clone().into_bytes();
|
||||||
|
bytes.extend(proxy::encode(
|
||||||
format!("{from}:40000").parse().unwrap(),
|
format!("{from}:40000").parse().unwrap(),
|
||||||
"198.51.100.1:443".parse().unwrap(),
|
"198.51.100.1:443".parse().unwrap(),
|
||||||
);
|
));
|
||||||
bytes.extend(request_bytes(&h.host(), method, path, extra, body));
|
bytes.extend(request_bytes(&h.host(), method, path, extra, body));
|
||||||
parse(&raw(h.addr, &bytes).await)
|
parse(&raw(h.addr, &bytes).await)
|
||||||
}
|
}
|
||||||
@@ -705,7 +712,11 @@ async fn the_default_is_read_and_draft_and_the_person_raises_it_to_post() {
|
|||||||
};
|
};
|
||||||
assert_eq!(approvals.len(), 1);
|
assert_eq!(approvals.len(), 1);
|
||||||
assert!(!approvals[0].may_post);
|
assert!(!approvals[0].may_post);
|
||||||
assert!(approvals[0].label.contains("claude.ai"), "{}", approvals[0].label);
|
assert!(
|
||||||
|
approvals[0].label.contains("claude.ai"),
|
||||||
|
"{}",
|
||||||
|
approvals[0].label
|
||||||
|
);
|
||||||
// The same connection is a row of "Who can reach these books".
|
// The same connection is a row of "Who can reach these books".
|
||||||
let listed = match admin(&h.books, Request::TokenList).await {
|
let listed = match admin(&h.books, Request::TokenList).await {
|
||||||
Response::Tokens(t) => t,
|
Response::Tokens(t) => t,
|
||||||
@@ -884,15 +895,7 @@ async fn a_stranger_who_knows_the_product_gets_no_code_without_an_allow() {
|
|||||||
decide(&h, &waiting[0].id, false, false).await,
|
decide(&h, &waiting[0].id, false, false).await,
|
||||||
Response::RemoteDecided { approval: None, .. }
|
Response::RemoteDecided { approval: None, .. }
|
||||||
));
|
));
|
||||||
let back = http_from(
|
let back = http_from(&h, "198.51.100.200", "GET", &wait_path(&asked), &[], "").await;
|
||||||
&h,
|
|
||||||
"198.51.100.200",
|
|
||||||
"GET",
|
|
||||||
&wait_path(&asked),
|
|
||||||
&[],
|
|
||||||
"",
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
let params = location_params(&back);
|
let params = location_params(&back);
|
||||||
assert_eq!(params["error"], "access_denied");
|
assert_eq!(params["error"], "access_denied");
|
||||||
assert!(!params.contains_key("code"));
|
assert!(!params.contains_key("code"));
|
||||||
@@ -924,7 +927,13 @@ async fn an_allow_is_a_new_approval_with_exactly_the_permissions_ticked() {
|
|||||||
assert_eq!(listed.len(), 2, "{listed:?}");
|
assert_eq!(listed.len(), 2, "{listed:?}");
|
||||||
let new = listed.iter().find(|a| a.id != first_approval).unwrap();
|
let new = listed.iter().find(|a| a.id != first_approval).unwrap();
|
||||||
assert!(!new.may_post, "nothing carried over from the first");
|
assert!(!new.may_post, "nothing carried over from the first");
|
||||||
assert!(listed.iter().find(|a| a.id == first_approval).unwrap().may_post);
|
assert!(
|
||||||
|
listed
|
||||||
|
.iter()
|
||||||
|
.find(|a| a.id == first_approval)
|
||||||
|
.unwrap()
|
||||||
|
.may_post
|
||||||
|
);
|
||||||
assert_ne!(new.token_id, first_token);
|
assert_ne!(new.token_id, first_token);
|
||||||
let post = call(
|
let post = call(
|
||||||
3,
|
3,
|
||||||
@@ -932,7 +941,11 @@ async fn an_allow_is_a_new_approval_with_exactly_the_permissions_ticked() {
|
|||||||
json!({"entry_id": 1, "confirmed": true, "request_key": "post-key-0002"}),
|
json!({"entry_id": 1, "confirmed": true, "request_key": "post-key-0002"}),
|
||||||
);
|
);
|
||||||
let refused = mcp(&h, Some(&second_access), "acme", post.clone()).await;
|
let refused = mcp(&h, Some(&second_access), "acme", post.clone()).await;
|
||||||
assert!(tool_text(&refused).contains("books:post"), "{}", refused.body);
|
assert!(
|
||||||
|
tool_text(&refused).contains("books:post"),
|
||||||
|
"{}",
|
||||||
|
refused.body
|
||||||
|
);
|
||||||
let allowed = mcp(&h, Some(&first_access), "acme", post).await;
|
let allowed = mcp(&h, Some(&first_access), "acme", post).await;
|
||||||
assert!(!tool_text(&allowed).contains("needs books:post"));
|
assert!(!tool_text(&allowed).contains("needs books:post"));
|
||||||
// And the other way: not ticked first, ticked second.
|
// And the other way: not ticked first, ticked second.
|
||||||
@@ -994,7 +1007,9 @@ async fn revoke_then_allow_again_does_not_bring_the_old_tokens_back() {
|
|||||||
// The new one works.
|
// The new one works.
|
||||||
let new_access = fresh.json()["access_token"].as_str().unwrap().to_string();
|
let new_access = fresh.json()["access_token"].as_str().unwrap().to_string();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
mcp(&h, Some(&new_access), "acme", initialize()).await.status,
|
mcp(&h, Some(&new_access), "acme", initialize())
|
||||||
|
.await
|
||||||
|
.status,
|
||||||
200
|
200
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1277,10 +1292,11 @@ async fn an_expired_token_and_a_token_for_another_issuer_are_refused() {
|
|||||||
h.start("https://other-name-tally-mint-ledger.wanderbooks.link")
|
h.start("https://other-name-tally-mint-ledger.wanderbooks.link")
|
||||||
.await;
|
.await;
|
||||||
let host = "other-name-tally-mint-ledger.wanderbooks.link";
|
let host = "other-name-tally-mint-ledger.wanderbooks.link";
|
||||||
let mut bytes = proxy::encode(
|
let mut bytes = h.secret.clone().into_bytes();
|
||||||
|
bytes.extend(proxy::encode(
|
||||||
"203.0.113.9:1".parse().unwrap(),
|
"203.0.113.9:1".parse().unwrap(),
|
||||||
"198.51.100.1:443".parse().unwrap(),
|
"198.51.100.1:443".parse().unwrap(),
|
||||||
);
|
));
|
||||||
bytes.extend(request_bytes(
|
bytes.extend(request_bytes(
|
||||||
host,
|
host,
|
||||||
"POST",
|
"POST",
|
||||||
@@ -1294,10 +1310,11 @@ async fn an_expired_token_and_a_token_for_another_issuer_are_refused() {
|
|||||||
));
|
));
|
||||||
let r = parse(&raw(h.addr, &bytes).await);
|
let r = parse(&raw(h.addr, &bytes).await);
|
||||||
assert_eq!(r.status, 401, "{}", r.body);
|
assert_eq!(r.status, 401, "{}", r.body);
|
||||||
let mut bytes = proxy::encode(
|
let mut bytes = h.secret.clone().into_bytes();
|
||||||
|
bytes.extend(proxy::encode(
|
||||||
"203.0.113.9:1".parse().unwrap(),
|
"203.0.113.9:1".parse().unwrap(),
|
||||||
"198.51.100.1:443".parse().unwrap(),
|
"198.51.100.1:443".parse().unwrap(),
|
||||||
);
|
));
|
||||||
let refresh_body = form(&[
|
let refresh_body = form(&[
|
||||||
("grant_type", "refresh_token"),
|
("grant_type", "refresh_token"),
|
||||||
("client_id", &client),
|
("client_id", &client),
|
||||||
@@ -1446,10 +1463,11 @@ async fn the_recorded_address_is_the_relays_and_a_forged_one_changes_nothing() {
|
|||||||
assert_eq!(last.access.subject, "books.start");
|
assert_eq!(last.access.subject, "books.start");
|
||||||
// A header a caller writes inside its own bytes is not a header: the
|
// A header a caller writes inside its own bytes is not a header: the
|
||||||
// door has read the real one, and this is HTTP text.
|
// door has read the real one, and this is HTTP text.
|
||||||
let mut bytes = proxy::encode(
|
let mut bytes = h.secret.clone().into_bytes();
|
||||||
|
bytes.extend(proxy::encode(
|
||||||
"198.51.100.77:1".parse().unwrap(),
|
"198.51.100.77:1".parse().unwrap(),
|
||||||
"198.51.100.1:443".parse().unwrap(),
|
"198.51.100.1:443".parse().unwrap(),
|
||||||
);
|
));
|
||||||
bytes.extend(proxy::encode(
|
bytes.extend(proxy::encode(
|
||||||
"10.9.9.9:1".parse().unwrap(),
|
"10.9.9.9:1".parse().unwrap(),
|
||||||
"198.51.100.1:443".parse().unwrap(),
|
"198.51.100.1:443".parse().unwrap(),
|
||||||
@@ -1485,8 +1503,7 @@ async fn the_recorded_address_is_the_relays_and_a_forged_one_changes_nothing() {
|
|||||||
.map(|(records, _)| records.len())
|
.map(|(records, _)| records.len())
|
||||||
.unwrap_or(0);
|
.unwrap_or(0);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
written,
|
written, 0,
|
||||||
0,
|
|
||||||
"a refusal for another company is counted, never written"
|
"a refusal for another company is counted, never written"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1704,7 +1721,10 @@ async fn waiting_requests_give_way_and_never_fill_the_window_against_a_real_one(
|
|||||||
let list = h.books.remote.pending_list();
|
let list = h.books.remote.pending_list();
|
||||||
let codes: BTreeSet<&String> = list.iter().map(|p| &p.code).collect();
|
let codes: BTreeSet<&String> = list.iter().map(|p| &p.code).collect();
|
||||||
assert_eq!(codes.len(), list.len());
|
assert_eq!(codes.len(), list.len());
|
||||||
assert!(list.iter().all(|p| p.code.len() == 7 && p.code.chars().nth(3) == Some(' ')));
|
assert!(
|
||||||
|
list.iter()
|
||||||
|
.all(|p| p.code.len() == 7 && p.code.chars().nth(3) == Some(' '))
|
||||||
|
);
|
||||||
// They expire unanswered.
|
// They expire unanswered.
|
||||||
h.advance(PENDING_TTL + 1);
|
h.advance(PENDING_TTL + 1);
|
||||||
assert!(pending(&h).await.is_empty());
|
assert!(pending(&h).await.is_empty());
|
||||||
@@ -1769,6 +1789,474 @@ async fn limits_count_an_ipv6_64_as_one_caller_and_a_mapped_address_as_its_ipv4(
|
|||||||
assert_eq!(other.status, 201);
|
assert_eq!(other.status, 201);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- one use of a refresh token ----------------------------------------------------
|
||||||
|
|
||||||
|
/// Two refreshes of one token at once: exactly one succeeds, and the other
|
||||||
|
/// is a reuse that ends the whole family (what the winner was given goes
|
||||||
|
/// too). Many rounds, many at once, so a check and a mark that were apart
|
||||||
|
/// would show.
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||||
|
async fn two_refreshes_at_once_never_both_succeed() {
|
||||||
|
let h = harness().await;
|
||||||
|
let c = register(&h, "Claude", &[CLAUDE_CB]).await;
|
||||||
|
let id = c["client_id"].as_str().unwrap().to_string();
|
||||||
|
for round in 0..12u32 {
|
||||||
|
let (code, verifier) = sign_in(&h, &id, CLAUDE_CB, "acme", 400 + round, false).await;
|
||||||
|
let first = exchange(&h, &id, &code, &verifier, CLAUDE_CB).await.json();
|
||||||
|
let token = first["refresh_token"].as_str().unwrap().to_string();
|
||||||
|
let mut tasks = Vec::new();
|
||||||
|
for _ in 0..8 {
|
||||||
|
let (h, id, token) = (h.clone(), id.clone(), token.clone());
|
||||||
|
tasks.push(tokio::spawn(async move { refresh(&h, &id, &token).await }));
|
||||||
|
}
|
||||||
|
let mut won = Vec::new();
|
||||||
|
for t in tasks {
|
||||||
|
let r = t.await.unwrap();
|
||||||
|
if r.status == 200 {
|
||||||
|
won.push(r.json());
|
||||||
|
} else {
|
||||||
|
assert_eq!(r.status, 400, "{}", r.body);
|
||||||
|
assert_eq!(r.json()["error"], "invalid_grant");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert_eq!(won.len(), 1, "round {round}: {} succeeded", won.len());
|
||||||
|
// The reuse ended the family: what the winner was given is dead.
|
||||||
|
let given = won[0]["refresh_token"].as_str().unwrap();
|
||||||
|
assert_eq!(refresh(&h, &id, given).await.status, 400, "round {round}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- what is fetched, and when --------------------------------------------------------
|
||||||
|
|
||||||
|
struct Counting {
|
||||||
|
fetched: std::sync::atomic::AtomicUsize,
|
||||||
|
redirect: &'static str,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ClientDocs for Counting {
|
||||||
|
fn fetch<'a>(
|
||||||
|
&'a self,
|
||||||
|
url: &'a str,
|
||||||
|
) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<Vec<u8>, String>> + Send + 'a>>
|
||||||
|
{
|
||||||
|
self.fetched.fetch_add(1, Ordering::SeqCst);
|
||||||
|
let doc = json!({"client_id": url, "client_name": "Doc",
|
||||||
|
"redirect_uris": [self.redirect]})
|
||||||
|
.to_string()
|
||||||
|
.into_bytes();
|
||||||
|
Box::pin(async move { Ok(doc) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The token endpoint never reaches out to the internet: a client id it
|
||||||
|
/// does not hold is unknown there, whatever address it is.
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn nothing_is_ever_fetched_from_the_token_endpoint() {
|
||||||
|
let h = harness().await;
|
||||||
|
let docs = Arc::new(Counting {
|
||||||
|
fetched: 0.into(),
|
||||||
|
redirect: "https://assistant.example/cb",
|
||||||
|
});
|
||||||
|
h.books.remote.set_docs(docs.clone());
|
||||||
|
for grant in ["authorization_code", "refresh_token"] {
|
||||||
|
let r = http(
|
||||||
|
&h,
|
||||||
|
"POST",
|
||||||
|
"/token",
|
||||||
|
&[("Content-Type", "application/x-www-form-urlencoded")],
|
||||||
|
&form(&[
|
||||||
|
("grant_type", grant),
|
||||||
|
("client_id", "https://assistant.example/client.json"),
|
||||||
|
("code", "x"),
|
||||||
|
("code_verifier", "x"),
|
||||||
|
("refresh_token", "x"),
|
||||||
|
]),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert!(
|
||||||
|
r.status == 401 || r.status == 400,
|
||||||
|
"{} {}",
|
||||||
|
r.status,
|
||||||
|
r.body
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert_eq!(docs.fetched.load(Ordering::SeqCst), 0);
|
||||||
|
// At sign-in it is fetched (once), and then the token endpoint uses
|
||||||
|
// what it holds, even when the hold has gone stale: no fetch there.
|
||||||
|
let id = "https://assistant.example/client.json";
|
||||||
|
let cb = "https://assistant.example/cb";
|
||||||
|
let (code, verifier) = sign_in(&h, id, cb, "acme", 500, false).await;
|
||||||
|
assert_eq!(docs.fetched.load(Ordering::SeqCst), 1);
|
||||||
|
let t = exchange(&h, id, &code, &verifier, cb).await;
|
||||||
|
assert_eq!(t.status, 200, "{}", t.body);
|
||||||
|
let first = t.json()["refresh_token"].as_str().unwrap().to_string();
|
||||||
|
h.advance(CIMD_TTL + 5);
|
||||||
|
let t = refresh(&h, id, &first).await;
|
||||||
|
assert_eq!(t.status, 200, "{}", t.body);
|
||||||
|
assert_eq!(docs.fetched.load(Ordering::SeqCst), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A document we hold that is past its time is used as it stands when the
|
||||||
|
/// fetch budget is spent (a person is not locked out by a limit).
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn a_stale_client_document_is_used_when_the_fetch_budget_is_spent() {
|
||||||
|
let h = harness().await;
|
||||||
|
let docs = Arc::new(Counting {
|
||||||
|
fetched: 0.into(),
|
||||||
|
redirect: "https://assistant.example/cb",
|
||||||
|
});
|
||||||
|
h.books.remote.set_docs(docs.clone());
|
||||||
|
let id = "https://assistant.example/client.json";
|
||||||
|
let cb = "https://assistant.example/cb";
|
||||||
|
let (code, verifier) = sign_in(&h, id, cb, "acme", 510, false).await;
|
||||||
|
assert_eq!(exchange(&h, id, &code, &verifier, cb).await.status, 200);
|
||||||
|
h.advance(CIMD_TTL + 5);
|
||||||
|
// The address spends its budget on other documents.
|
||||||
|
for n in 0..FETCH_PER_ADDRESS {
|
||||||
|
let other = format!("https://other{n}.example/client.json");
|
||||||
|
let _ = ask(&h, CALLER, &other, cb, 520 + n).await;
|
||||||
|
}
|
||||||
|
let before = docs.fetched.load(Ordering::SeqCst);
|
||||||
|
let page = ask(&h, CALLER, id, cb, 540).await;
|
||||||
|
assert_eq!(page.status, 200, "{}", page.body);
|
||||||
|
assert_eq!(docs.fetched.load(Ordering::SeqCst), before, "no fetch");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- the file, and what a registration costs --------------------------------------------
|
||||||
|
|
||||||
|
/// A registration nobody has allowed lives in memory only: the file is not
|
||||||
|
/// written for it. It is, once the person allows a sign-in of that client.
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn a_registration_nobody_allowed_never_reaches_the_disk() {
|
||||||
|
let h = harness().await;
|
||||||
|
let dir = h.books.root.auth_dir().unwrap();
|
||||||
|
let file = dir.join(FILE);
|
||||||
|
let before = std::fs::metadata(&file)
|
||||||
|
.ok()
|
||||||
|
.and_then(|m| m.modified().ok());
|
||||||
|
let mut ids = Vec::new();
|
||||||
|
for i in 0..5 {
|
||||||
|
let c = register(&h, &format!("Stranger {i}"), &["https://x.example/cb"]).await;
|
||||||
|
ids.push(c["client_id"].as_str().unwrap().to_string());
|
||||||
|
}
|
||||||
|
let after = std::fs::metadata(&file)
|
||||||
|
.ok()
|
||||||
|
.and_then(|m| m.modified().ok());
|
||||||
|
assert_eq!(before, after, "registering wrote the file");
|
||||||
|
if let Ok(text) = std::fs::read_to_string(&file) {
|
||||||
|
assert!(!text.contains(&ids[0]));
|
||||||
|
}
|
||||||
|
// Asking to sign in (parked, not yet allowed) writes nothing either.
|
||||||
|
let _ = ask(&h, CALLER, &ids[0], "https://x.example/cb", 600).await;
|
||||||
|
assert_eq!(
|
||||||
|
before,
|
||||||
|
std::fs::metadata(&file)
|
||||||
|
.ok()
|
||||||
|
.and_then(|m| m.modified().ok())
|
||||||
|
);
|
||||||
|
// The person allows it: now it is kept, with its approval.
|
||||||
|
let waiting = pending(&h).await;
|
||||||
|
assert!(matches!(
|
||||||
|
decide(&h, &waiting[0].id, true, false).await,
|
||||||
|
Response::RemoteDecided { .. }
|
||||||
|
));
|
||||||
|
let text = std::fs::read_to_string(&file).unwrap();
|
||||||
|
assert!(text.contains(&ids[0]));
|
||||||
|
assert!(!text.contains(&ids[1]));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn a_redirect_is_at_most_512_bytes_and_a_clients_together_a_few_kib() {
|
||||||
|
let h = harness().await;
|
||||||
|
let long = format!("https://x.example/{}", "a".repeat(MAX_REDIRECT_BYTES));
|
||||||
|
assert!(long.len() > MAX_REDIRECT_BYTES);
|
||||||
|
let ok = format!("https://x.example/{}", "a".repeat(MAX_REDIRECT_BYTES - 20));
|
||||||
|
assert!(ok.len() <= MAX_REDIRECT_BYTES);
|
||||||
|
let r = http(
|
||||||
|
&h,
|
||||||
|
"POST",
|
||||||
|
"/register",
|
||||||
|
&[("Content-Type", "application/json")],
|
||||||
|
&json!({"redirect_uris": [long]}).to_string(),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 400, "{}", r.body);
|
||||||
|
// Twenty of the longest allowed is over the client's total.
|
||||||
|
let many: Vec<String> = (0..MAX_REDIRECTS)
|
||||||
|
.map(|i| {
|
||||||
|
format!(
|
||||||
|
"https://x.example/{i:02}{}",
|
||||||
|
"a".repeat(MAX_REDIRECT_BYTES - 30)
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
assert!(many.iter().all(|u| valid_redirect(u).is_some()));
|
||||||
|
assert!(many.iter().map(String::len).sum::<usize>() > MAX_REDIRECTS_TOTAL);
|
||||||
|
let r = http(
|
||||||
|
&h,
|
||||||
|
"POST",
|
||||||
|
"/register",
|
||||||
|
&[("Content-Type", "application/json")],
|
||||||
|
&json!({"redirect_uris": many}).to_string(),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 400, "{}", r.body);
|
||||||
|
let r = http(
|
||||||
|
&h,
|
||||||
|
"POST",
|
||||||
|
"/register",
|
||||||
|
&[("Content-Type", "application/json")],
|
||||||
|
&json!({"redirect_uris": [ok]}).to_string(),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 201, "{}", r.body);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- what the window shows -----------------------------------------------------------------
|
||||||
|
|
||||||
|
/// A name an assistant gives itself carries no invisible or
|
||||||
|
/// direction-changing character into the window, and is cut short.
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn a_name_is_shown_without_invisible_or_direction_changing_characters_and_short() {
|
||||||
|
assert_eq!(
|
||||||
|
clean("Cla\u{202e}ude\u{200b} \u{2066}Web\u{2069}\u{feff}", 100),
|
||||||
|
"Claude Web"
|
||||||
|
);
|
||||||
|
assert_eq!(clean("a\u{200f}\u{061c}b\u{e0041}c", 100), "abc");
|
||||||
|
let h = harness().await;
|
||||||
|
let long = "N".repeat(200);
|
||||||
|
let c = register(
|
||||||
|
&h,
|
||||||
|
&format!("Anthropic\u{202e}\u{200b} {long}"),
|
||||||
|
&["https://assist.example/cb"],
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let id = c["client_id"].as_str().unwrap();
|
||||||
|
let page = ask(&h, CALLER, id, "https://assist.example/cb", 700).await;
|
||||||
|
assert_eq!(page.status, 200);
|
||||||
|
let p = &pending(&h).await[0];
|
||||||
|
assert!(
|
||||||
|
p.client_name.chars().count() <= MAX_NAME_SHOWN,
|
||||||
|
"{}",
|
||||||
|
p.client_name
|
||||||
|
);
|
||||||
|
assert!(p.client_name.starts_with("Anthropic N"));
|
||||||
|
assert!(!p.client_name.contains('\u{202e}') && !p.client_name.contains('\u{200b}'));
|
||||||
|
// The host is what comes first in the label of the connection made.
|
||||||
|
assert!(!p.known_host);
|
||||||
|
assert_eq!(p.redirect_host, "assist.example");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- keys, limits, refusals counted ------------------------------------------------------------
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn a_revoked_key_frees_its_place() {
|
||||||
|
let h = harness().await;
|
||||||
|
let mut last = None;
|
||||||
|
for i in 0..MAX_KEYS {
|
||||||
|
match admin(
|
||||||
|
&h.books,
|
||||||
|
Request::RemoteMakeKey {
|
||||||
|
book: "acme".into(),
|
||||||
|
name: format!("key {i}"),
|
||||||
|
post: false,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Response::RemoteSecret { id, .. } => last = Some(id),
|
||||||
|
other => panic!("{i}: {other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let full = admin(
|
||||||
|
&h.books,
|
||||||
|
Request::RemoteMakeKey {
|
||||||
|
book: "acme".into(),
|
||||||
|
name: "one more".into(),
|
||||||
|
post: false,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert!(matches!(full, Response::Refused(_)), "{full:?}");
|
||||||
|
let tokens = match admin(&h.books, Request::TokenList).await {
|
||||||
|
Response::Tokens(t) => t,
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
};
|
||||||
|
let gone = tokens
|
||||||
|
.iter()
|
||||||
|
.find(|t| Some(&t.id) == last.as_ref())
|
||||||
|
.unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
admin(
|
||||||
|
&h.books,
|
||||||
|
Request::TokenRevoke {
|
||||||
|
book: "acme".into(),
|
||||||
|
name: gone.name.clone(),
|
||||||
|
id: Some(gone.id.clone())
|
||||||
|
}
|
||||||
|
)
|
||||||
|
.await,
|
||||||
|
Response::TokenRevoked(_)
|
||||||
|
));
|
||||||
|
let again = admin(
|
||||||
|
&h.books,
|
||||||
|
Request::RemoteMakeKey {
|
||||||
|
book: "acme".into(),
|
||||||
|
name: "one more".into(),
|
||||||
|
post: false,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert!(matches!(again, Response::RemoteSecret { .. }), "{again:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// When the table of per-address limits is full, it is per-address entries
|
||||||
|
/// that go; a connection's own call limit is never evicted (that would
|
||||||
|
/// hand a caller a fresh allowance by filling the table).
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn a_full_limiter_table_evicts_addresses_never_a_connections_own_limit() {
|
||||||
|
let h = harness().await;
|
||||||
|
let remote = &h.books.remote;
|
||||||
|
// A connection that has used all its calls this minute.
|
||||||
|
for _ in 0..CALLS_PER_MINUTE {
|
||||||
|
assert!(!remote.limited("call:tok_mine".into(), CALLS_PER_MINUTE, 60));
|
||||||
|
}
|
||||||
|
assert!(remote.limited("call:tok_mine".into(), CALLS_PER_MINUTE, 60));
|
||||||
|
// Strangers fill the table of addresses, and then some.
|
||||||
|
{
|
||||||
|
let mut inner = remote.inner();
|
||||||
|
for i in 0..MAX_ADDRESS_LIMITS + 500 {
|
||||||
|
h.advance(0);
|
||||||
|
remote.allow_address(
|
||||||
|
&mut inner,
|
||||||
|
format!("register:10.{}.{}.{}", i / 65536, (i / 256) % 256, i % 256),
|
||||||
|
5,
|
||||||
|
3600,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert!(inner.address_limits.len() <= MAX_ADDRESS_LIMITS);
|
||||||
|
assert!(inner.limits.contains_key("call:tok_mine"));
|
||||||
|
}
|
||||||
|
// Still limited: it was not given a fresh allowance.
|
||||||
|
assert!(remote.limited("call:tok_mine".into(), CALLS_PER_MINUTE, 60));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A call refused for rate or for another company's books is counted and
|
||||||
|
/// not written to the record; and the call limit is asked first.
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn refused_calls_are_counted_not_written_and_the_limit_comes_before_the_company() {
|
||||||
|
let h = harness().await;
|
||||||
|
let (_, access, _) = claude(&h, "acme").await;
|
||||||
|
let token_id = approvals_of(&h, "acme").await[0].token_id.clone();
|
||||||
|
let dir = h.books.root.book_dir(&BookId::parse("acme").unwrap());
|
||||||
|
let written = || {
|
||||||
|
ledger_store::access::read(&dir)
|
||||||
|
.map(|(r, _)| r.len())
|
||||||
|
.unwrap_or(0)
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
mcp(&h, Some(&access), "acme", initialize()).await.status,
|
||||||
|
200
|
||||||
|
);
|
||||||
|
let before_records = written();
|
||||||
|
let before = h.books.remote.refused();
|
||||||
|
for _ in 0..CALLS_PER_MINUTE {
|
||||||
|
h.books
|
||||||
|
.remote
|
||||||
|
.limited(format!("call:{token_id}"), CALLS_PER_MINUTE, 60);
|
||||||
|
}
|
||||||
|
let limited = mcp(&h, Some(&access), "acme", initialize()).await;
|
||||||
|
assert_eq!(limited.status, 429, "{}", limited.body);
|
||||||
|
assert_eq!(limited.header("retry-after"), Some("60"));
|
||||||
|
// Another company's path from the same token: the limit answers first.
|
||||||
|
let other = mcp(&h, Some(&access), "beta", initialize()).await;
|
||||||
|
assert_eq!(other.status, 429, "{}", other.body);
|
||||||
|
assert_eq!(h.books.remote.refused(), before + 2);
|
||||||
|
assert_eq!(written(), before_records, "refusals were written");
|
||||||
|
// After the minute, the company check answers (403), still counted.
|
||||||
|
h.advance(61);
|
||||||
|
let wrong = mcp(&h, Some(&access), "beta", initialize()).await;
|
||||||
|
assert_eq!(wrong.status, 403, "{}", wrong.body);
|
||||||
|
assert_eq!(h.books.remote.refused(), before + 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- the front of the door ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// Only a connection that begins with this start's secret is read at all:
|
||||||
|
/// a process on this computer that finds the port and writes a PROXY
|
||||||
|
/// header of its own gets nothing.
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn a_connection_without_the_secret_is_dropped_before_anything_is_read() {
|
||||||
|
let h = harness().await;
|
||||||
|
let request = request_bytes(
|
||||||
|
&h.host(),
|
||||||
|
"GET",
|
||||||
|
"/.well-known/oauth-authorization-server",
|
||||||
|
&[],
|
||||||
|
"",
|
||||||
|
);
|
||||||
|
let header = proxy::encode(
|
||||||
|
"198.51.100.5:1".parse().unwrap(),
|
||||||
|
"198.51.100.1:443".parse().unwrap(),
|
||||||
|
);
|
||||||
|
// No secret: the PROXY header first, as the relay's line was before.
|
||||||
|
let mut bytes = header.clone();
|
||||||
|
bytes.extend(&request);
|
||||||
|
assert!(raw(h.addr, &bytes).await.is_empty());
|
||||||
|
// A wrong one, of the right length.
|
||||||
|
let mut wrong = vec![b'0'; proxy::SECRET_LEN];
|
||||||
|
wrong[0] = if h.secret.as_bytes()[0] == b'0' {
|
||||||
|
b'1'
|
||||||
|
} else {
|
||||||
|
b'0'
|
||||||
|
};
|
||||||
|
let mut bytes = wrong;
|
||||||
|
bytes.extend(&header);
|
||||||
|
bytes.extend(&request);
|
||||||
|
assert!(raw(h.addr, &bytes).await.is_empty());
|
||||||
|
// The right one: answered.
|
||||||
|
let mut bytes = h.secret.clone().into_bytes();
|
||||||
|
bytes.extend(&header);
|
||||||
|
bytes.extend(&request);
|
||||||
|
assert_eq!(parse(&raw(h.addr, &bytes).await).status, 200);
|
||||||
|
// The secret is never in what the admin side prints.
|
||||||
|
let info = match admin(&h.books, Request::RemoteStatus).await {
|
||||||
|
Response::Remote(i) => i,
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
};
|
||||||
|
assert!(!format!("{info:?}").contains(&h.secret));
|
||||||
|
assert_eq!(info.proxy_secret.unwrap().0, h.secret);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Under HTTP/2 there is no `Host` header: the host is the request
|
||||||
|
/// address's authority, and the same check is made on it.
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn the_host_is_read_from_the_authority_when_there_is_no_host_header() {
|
||||||
|
let h = harness().await;
|
||||||
|
let none = axum::http::HeaderMap::new();
|
||||||
|
let good: axum::http::Uri = format!("https://{}/token", h.host()).parse().unwrap();
|
||||||
|
assert!(super::http::front(&h.books, &none, &good).is_ok());
|
||||||
|
let loud: axum::http::Uri = format!("https://{}:443/token", h.host().to_uppercase())
|
||||||
|
.parse()
|
||||||
|
.unwrap();
|
||||||
|
assert!(super::http::front(&h.books, &none, &loud).is_ok());
|
||||||
|
let wrong: axum::http::Uri = "https://elsewhere.example/token".parse().unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
super::http::front(&h.books, &none, &wrong)
|
||||||
|
.err()
|
||||||
|
.unwrap()
|
||||||
|
.status(),
|
||||||
|
421
|
||||||
|
);
|
||||||
|
// No host anywhere is no host.
|
||||||
|
let bare: axum::http::Uri = "/token".parse().unwrap();
|
||||||
|
assert!(super::http::front(&h.books, &none, &bare).is_err());
|
||||||
|
// A Host header, when there is one, is what counts.
|
||||||
|
let mut host = axum::http::HeaderMap::new();
|
||||||
|
host.insert("host", h.host().parse().unwrap());
|
||||||
|
assert!(super::http::front(&h.books, &host, &bare).is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
// ---- the doors ------------------------------------------------------------------------
|
// ---- the doors ------------------------------------------------------------------------
|
||||||
|
|
||||||
#[tokio::test(flavor = "multi_thread")]
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
@@ -1838,10 +2326,11 @@ async fn the_metadata_is_the_pinned_address_at_every_place_products_look() {
|
|||||||
}
|
}
|
||||||
// Nothing is built from the request: another Host is not answered, and
|
// Nothing is built from the request: another Host is not answered, and
|
||||||
// a company not offered has no document.
|
// a company not offered has no document.
|
||||||
let mut bytes = proxy::encode(
|
let mut bytes = h.secret.clone().into_bytes();
|
||||||
|
bytes.extend(proxy::encode(
|
||||||
"203.0.113.9:1".parse().unwrap(),
|
"203.0.113.9:1".parse().unwrap(),
|
||||||
"198.51.100.1:443".parse().unwrap(),
|
"198.51.100.1:443".parse().unwrap(),
|
||||||
);
|
));
|
||||||
bytes.extend(request_bytes(
|
bytes.extend(request_bytes(
|
||||||
"evil.example",
|
"evil.example",
|
||||||
"GET",
|
"GET",
|
||||||
@@ -2045,10 +2534,11 @@ async fn a_key_made_for_a_product_that_takes_only_a_key_opens_the_door_with_the_
|
|||||||
#[tokio::test(flavor = "multi_thread")]
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
async fn a_host_with_the_default_port_is_the_same_host() {
|
async fn a_host_with_the_default_port_is_the_same_host() {
|
||||||
let h = harness().await;
|
let h = harness().await;
|
||||||
let mut bytes = proxy::encode(
|
let mut bytes = h.secret.clone().into_bytes();
|
||||||
|
bytes.extend(proxy::encode(
|
||||||
"203.0.113.9:1".parse().unwrap(),
|
"203.0.113.9:1".parse().unwrap(),
|
||||||
"198.51.100.1:443".parse().unwrap(),
|
"198.51.100.1:443".parse().unwrap(),
|
||||||
);
|
));
|
||||||
bytes.extend(request_bytes(
|
bytes.extend(request_bytes(
|
||||||
&format!("{}:443", h.host()),
|
&format!("{}:443", h.host()),
|
||||||
"GET",
|
"GET",
|
||||||
|
|||||||
Reference in new issue
Block a user