Compare commits

...
Author SHA1 Message Date
FredApps f526120996 cadcraft-cli: the mcp --connect test's stand-in app writes a token and answers the hello
Part of #1925.
2026-11-27 22:51:09 +07:00
FredApps 8eb26836e3 Control channel: the MCP bridge checks it is talking to the app, and tokenless connections close in 10 s
The MCP bridge (`Remote`) sent its requests to whatever accepted on the control
port. It now opens each connection with a `hello` carrying a fresh nonce and no
token; the app answers with HMAC-SHA-256 of the nonce keyed with the session
token. Without a token for the port, or without a valid proof (checked again
against the token file once, for a restarted app), the bridge sends nothing.

The control server answers `hello` before the token check without counting it
as authentication, and closes a connection that hasn't shown the token within
10 s of opening, however its bytes trickle in, so peers without the token can't
hold every connection slot until the 10-minute idle timeout. The bridge
replaces an unauthenticated connection close to that deadline before writing a
request to it.

Part of #1925.
2026-11-27 22:27:30 +07:00
9 changed files with 518 additions and 50 deletions
Generated
+12
View File
@@ -887,9 +887,11 @@ dependencies = [
"craft-jsonrpc",
"craft-mcp",
"getrandom 0.4.3",
"hmac",
"libc",
"log",
"serde_json",
"sha2",
"tiny-skia",
]
@@ -2065,6 +2067,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"crypto-common",
"subtle",
]
[[package]]
@@ -3230,6 +3233,15 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "hmac"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
dependencies = [
"digest",
]
[[package]]
name = "http"
version = "1.5.0"
+2 -2
View File
@@ -16,7 +16,7 @@ CADCraft treats these as untrusted, and a way past these defences is a vulnerabi
- **Drawing files.** Opening a DXF, DWG or other file must not run code, write outside the paths the user chose, or crash the app. Panics are bugs too, but memory exhaustion or a decoder abort on a crafted file is the more serious case.
- **AutoLISP in a drawing's folder.** A drawing must not run code that the user didn't choose to load.
- **The control channel.** It listens on loopback only and needs the session token from an owner-only file on every request. Another local account reaching it without that token is a vulnerability.
- **The control channel.** It listens on loopback only and needs the session token from an owner-only file on every request. Another local account reaching it without that token is a vulnerability. The MCP bridge sends requests only to a server that proves it holds the token, so a program listening on the port in the app's place gets none.
- **Temporary and autosave files.** Autosave files are unsaved drawings: another account must not be able to read them or redirect a write through them.
- **Updates.** A release must not be replaceable by someone other than the project.
@@ -25,7 +25,7 @@ CADCraft treats these as untrusted, and a way past these defences is a vulnerabi
These are known and being worked on, so they don't need a report:
- Agents connected through MCP or the control channel can read and write any path the user can. There are no workspace roots yet.
- A local process can make the control channel buffer up to 512 MiB before its token is checked. The total is capped, so this can slow the app but not exhaust memory without limit.
- A local process without the token can hold the control channel's 16 connections for up to 10 seconds at a time, with at most 64 KiB of request line each, so it can keep an agent from reaching the app while it keeps reconnecting. It can't make the app run anything.
- The DWG worker process has no memory limit of its own yet, so a crafted file can use a lot of memory before it stops. It ends that one open or save, not the app.
- The web build has no autosave yet.
+10
View File
@@ -60,10 +60,19 @@ fn no_connect_still_serves_headless() {
fn connect_with_address_routes_to_that_endpoint() {
let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback");
let addr = listener.local_addr().expect("local addr").to_string();
let port = listener.local_addr().expect("local addr").port();
// As the app does: write the session token, and prove holding it when the bridge says hello.
let token = cadcraft_mcp::control_token::issue(port).expect("issue token");
let server = std::thread::spawn(move || {
let (conn, _) = listener.accept().expect("accept");
let mut reader = BufReader::new(conn.try_clone().expect("clone"));
let mut line = String::new();
reader.read_line(&mut line).expect("read hello");
let hello: Value = serde_json::from_str(&line).expect("json hello");
assert_eq!(hello["method"], "hello", "the bridge says hello first: {line}");
let proof = cadcraft_mcp::control_token::server_proof(&token, hello["params"]["nonce"].as_str().unwrap_or_default());
writeln!(&conn, "{}", json!({"id": hello["id"], "ok": true, "result": {"proof": proof}})).expect("write proof");
line.clear();
reader.read_line(&mut line).expect("read request");
let req: Value = serde_json::from_str(&line).expect("json request");
let reply = json!({"id": req["id"], "ok": true, "result": {"fixture": "loopback"}});
@@ -75,6 +84,7 @@ fn connect_with_address_routes_to_that_endpoint() {
let out = mcp(&["--connect", &addr], &format!("{INIT}\n{call}\n"));
assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr));
let req = server.join().expect("server thread");
cadcraft_mcp::control_token::revoke(port);
assert_eq!(req["method"], "ui.inspect");
let r = replies(&out);
let instructions = r.iter().find(|v| v["id"] == 1).and_then(|v| v["result"]["instructions"].as_str()).unwrap_or_default();
+155 -6
View File
@@ -5,15 +5,19 @@
//! HTTP request line, a stray `nc`, binary data) gets one error reply and the connection is
//! closed, so nothing sent after it runs. Every resource a client can hold is bounded
//! ([`Limits`]): simultaneous connections, request line length (shorter until a request on the
//! connection has carried the token), queued requests, and how long a socket may sit idle or
//! blocked on a write.
//! connection has carried the token), queued requests, how long a connection may stay open before
//! it has shown the token, and how long a socket may sit idle or blocked on a write.
//!
//! A `hello` with a nonce is answered before the token check with a proof that the server holds
//! the token ([`cadcraft_mcp::control_token::server_proof`]), so a client can tell the app from
//! another program on the port before it sends anything else (#1925).
use std::io::{BufRead, BufReader, ErrorKind, Write};
use std::io::{BufRead, BufReader, ErrorKind, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{Receiver, SyncSender, TrySendError, sync_channel};
use std::time::Duration;
use std::time::{Duration, Instant};
use cadcraft_ui_egui::ControlRequest;
use serde_json::{Value, json};
@@ -33,6 +37,9 @@ struct Limits {
total_bytes: usize,
/// Requests waiting for the app at once; more are answered `busy`.
queue: usize,
/// How long a connection may stay open before a request on it has carried the right token; it
/// is closed then, so peers without the token can't hold the connection slots (#1925).
preauth_time: Duration,
/// How long a connection may go without sending a byte before it is closed.
idle_timeout: Duration,
/// How long a reply write may block before the connection is closed.
@@ -51,6 +58,7 @@ impl Default for Limits {
// Room for one maximal request plus smaller ones, not `max_clients` maximal ones.
total_bytes: 512 * 1024 * 1024,
queue: 64,
preauth_time: cadcraft_mcp::control_token::MAX_UNAUTHENTICATED_TIME,
idle_timeout: Duration::from_secs(600),
write_timeout: Duration::from_secs(30),
reply_timeout: Duration::from_secs(60),
@@ -338,6 +346,47 @@ fn is_http_request_line(text: &str) -> bool {
|| text.rsplit_once(' ').is_some_and(|(_, version)| version.starts_with("HTTP/"))
}
/// The method a client sends, before any request with the token, to have the server prove it holds
/// the token.
const HELLO: &str = "hello";
/// `hello`'s parameters.
#[derive(serde::Deserialize)]
struct HelloParams {
nonce: String,
}
/// The proof answering a `hello` with `params`, or the error that closes the connection.
fn hello_proof(params: Option<&serde_json::value::RawValue>, token: &str) -> Result<String, String> {
let nonce = params.and_then(|p| serde_json::from_str::<HelloParams>(p.get()).ok()).map(|p| p.nonce).unwrap_or_default();
if !cadcraft_mcp::control_token::valid_nonce(&nonce) {
let digits = &cadcraft_mcp::control_token::NONCE_DIGITS;
return Err(format!("`hello` needs a `nonce` of {} to {} hexadecimal digits; closing the connection", digits.start(), digits.end()));
}
Ok(cadcraft_mcp::control_token::server_proof(token, &nonce))
}
/// A connection's read side. Until `until` (the end of [`Limits::preauth_time`]), each read waits
/// at most until then, however the bytes trickle in; after it, reads fail as timed out.
struct Timed {
stream: TcpStream,
idle: Duration,
until: Option<Instant>,
}
impl Read for Timed {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
if let Some(until) = self.until {
let left = until.saturating_duration_since(Instant::now());
if left.is_zero() {
return Err(std::io::Error::new(ErrorKind::TimedOut, "no request with the control token in time"));
}
self.stream.set_read_timeout(Some(left.min(self.idle)))?;
}
self.stream.read(buf)
}
}
/// Serve bounded JSON lines, authenticating each request before enqueueing it for the UI.
/// Invalid credentials close the connection; queue and reply limits report whether a request ran.
fn serve(stream: TcpStream, tx: &SyncSender<ControlRequest>, ctx: &egui::Context, limits: Limits, token: &str, budget: Budget) {
@@ -346,7 +395,8 @@ fn serve(stream: TcpStream, tx: &SyncSender<ControlRequest>, ctx: &egui::Context
}
let Ok(read) = stream.try_clone() else { return };
let mut out = stream;
let mut reader = BufReader::new(read);
let until = Instant::now().checked_add(limits.preauth_time);
let mut reader = BufReader::new(Timed { stream: read, idle: limits.idle_timeout, until });
let mut buf = Vec::new();
let mut held = Held::new(budget);
// The token is checked only after the whole line is read, so until a request here has carried
@@ -368,6 +418,17 @@ fn serve(stream: TcpStream, tx: &SyncSender<ControlRequest>, ctx: &egui::Context
Ok(true) => match parse_line(&buf) {
Line::Blank => continue,
Line::Reject(e) => e,
// Answered without the token and without authenticating the connection: the proof
// shows the token is known here, not that the peer knows it.
Line::Request { id, method, params, .. } if method == HELLO => match hello_proof(params, token) {
Ok(proof) => {
if writeln!(out, "{}", json!({"id": id, "ok": true, "result": {"proof": proof}})).is_err() {
break;
}
continue;
}
Err(e) => e,
},
Line::Request { id, method, params, token: given } => {
// Authenticate the peer before dispatching: loopback TCP does not identify the
// OS user, so only a client holding the owner-only session token may drive the
@@ -380,7 +441,14 @@ fn serve(stream: TcpStream, tx: &SyncSender<ControlRequest>, ctx: &egui::Context
let _ = writeln!(out, "{r}");
break;
}
authenticated = true;
if !authenticated {
authenticated = true;
let timed = reader.get_mut();
timed.until = None;
if timed.stream.set_read_timeout(Some(limits.idle_timeout)).is_err() {
break;
}
}
// Absent `params` is `{}`; ones that cannot be decoded (an unpaired surrogate escape) are an
// error, not a request run with defaults.
let params = match params.map(|r| serde_json::from_str::<Value>(r.get())) {
@@ -744,6 +812,87 @@ mod tests {
assert_eq!((v["ok"].as_bool(), v["method"].as_str()), (Some(true), Some("ping")), "{line}");
}
/// A `hello` line with `nonce` and no token.
fn hello_line(nonce: &str) -> String {
json!({"id": "h", "method": "hello", "params": {"nonce": nonce}}).to_string() + "\n"
}
/// A `hello` is answered with a proof of the token before any token has been shown, and the
/// connection stays open for requests; the `hello` itself authenticates nothing.
#[test]
fn a_hello_is_answered_with_a_proof_of_the_token() {
let addr = serve_echo_with(preauth());
let mut c = TcpStream::connect(addr).unwrap();
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
let mut r = BufReader::new(c.try_clone().unwrap());
let nonce = cadcraft_mcp::control_token::new_nonce().unwrap();
c.write_all(hello_line(&nonce).as_bytes()).unwrap();
let mut line = String::new();
r.read_line(&mut line).unwrap();
let v: Value = serde_json::from_str(&line).unwrap();
assert_eq!(v["id"], "h", "{line}");
let proof = v["result"]["proof"].as_str().unwrap();
assert!(cadcraft_mcp::control_token::verify_server_proof(TEST_TOKEN, &nonce, proof), "{line}");
assert!(!line.contains(TEST_TOKEN), "the token itself is never sent");
// Still unauthenticated: a line past the preauth bound is refused…
let refused = exchange(addr, format!("{}{}", hello_line(&nonce), long_req_line(1, 2000)).as_bytes());
assert_eq!(refused.len(), 2, "{refused:?}");
assert!(refused[1]["error"].as_str().unwrap().contains("longer than 1000 bytes"), "{refused:?}");
// …and a request with the token after the hello goes through on the same connection.
c.write_all(req_line(2, "ping").as_bytes()).unwrap();
line.clear();
r.read_line(&mut line).unwrap();
let v: Value = serde_json::from_str(&line).unwrap();
assert_eq!((v["id"].as_i64(), v["method"].as_str()), (Some(2), Some("ping")), "{line}");
}
/// A `hello` without a usable nonce gets an error and the connection is closed.
#[test]
fn a_hello_without_a_usable_nonce_closes_the_connection() {
let addr = serve_echo();
for bad in [r#"{"method":"hello"}"#.to_string(), hello_line("abc").trim_end().to_string(), hello_line(&"z".repeat(64)).trim_end().to_string()]
{
let replies = exchange(addr, format!("{bad}\n{}", req_line(1, "ping")).as_bytes());
assert_eq!(replies.len(), 1, "{bad}: {replies:?}");
assert!(replies[0]["error"].as_str().unwrap().contains("`nonce`"), "{bad}: {replies:?}");
}
}
/// A connection that doesn't show the token within `preauth_time` is closed even while it keeps
/// sending (a byte at a time, or `hello`s), so peers without the token can't hold the slots;
/// one that has shown it stays open past that time.
#[test]
fn a_connection_that_never_shows_the_token_is_closed_in_time() {
let limits = Limits { preauth_time: Duration::from_millis(400), idle_timeout: Duration::from_secs(5), ..short() };
let addr = serve_echo_with(limits);
let nonce = cadcraft_mcp::control_token::new_nonce().unwrap();
for trickle in [b"{".to_vec(), hello_line(&nonce).into_bytes()] {
let mut c = TcpStream::connect(addr).unwrap();
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
let reader = std::thread::spawn({
let c = c.try_clone().unwrap();
move || BufReader::new(c).lines().count()
});
let t = std::time::Instant::now();
while c.write_all(&trickle).is_ok() && t.elapsed() < Duration::from_secs(4) && !reader.is_finished() {
std::thread::sleep(Duration::from_millis(50));
}
assert!(reader.is_finished() && t.elapsed() < Duration::from_secs(3), "still open after {:?}", t.elapsed());
let _ = reader.join();
}
let mut c = TcpStream::connect(addr).unwrap();
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
let mut r = BufReader::new(c.try_clone().unwrap());
let mut line = String::new();
c.write_all(req_line(1, "ping").as_bytes()).unwrap();
r.read_line(&mut line).unwrap();
std::thread::sleep(Duration::from_millis(700));
c.write_all(req_line(2, "pong").as_bytes()).unwrap();
line.clear();
r.read_line(&mut line).unwrap();
assert!(line.contains("pong"), "an authenticated connection outlives the preauth time: {line:?}");
}
#[test]
fn extra_connections_are_refused() {
let addr = serve_echo();
+3
View File
@@ -19,6 +19,9 @@ serde_json = { workspace = true }
log = { workspace = true }
# Secure randomness for the per-session control token (MIT OR Apache-2.0).
getrandom = "0.4"
# The control server's proof that it holds the session token (MIT OR Apache-2.0).
hmac = "0.12"
sha2 = "0.10"
[dev-dependencies]
# Reads the pixels of rendered PNGs in the tests.
+215 -33
View File
@@ -3,7 +3,7 @@
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{Ipv4Addr, SocketAddr, TcpStream, ToSocketAddrs};
use std::sync::Arc;
use std::time::Duration;
use std::time::{Duration, Instant};
use cadcraft_engine::Session;
use cadcraft_engine::file_access::{self, AutomationRoots};
@@ -35,6 +35,9 @@ pub struct Remote {
authed: bool,
/// Longest reply line accepted (`MAX_REPLY_LINE`; smaller in tests).
max_reply: usize,
/// When the current connection was opened: the server closes one that hasn't shown the token
/// within `MAX_UNAUTHENTICATED_TIME`.
opened: Option<Instant>,
}
/// The port component of a `HOST:PORT` address, for locating the token file.
@@ -50,6 +53,13 @@ const LAUNCH_WAIT: Duration = Duration::from_secs(30);
/// can't make the client allocate without bound (#1925).
const MAX_REPLY_LINE: usize = 256 * 1024 * 1024;
/// Longest reply to a `hello` the client reads: it comes before the peer has proved anything.
const MAX_HELLO_REPLY: usize = 4096;
/// How long before the server's `MAX_UNAUTHENTICATED_TIME` runs out an unauthenticated connection
/// is replaced instead of used, so a request is never written to a connection about to close.
const PREAUTH_MARGIN: Duration = Duration::from_secs(2);
/// Read one `\n`-terminated reply of at most `max` bytes (newline excluded). `Ok(0)` is end of
/// stream; a longer line is an `InvalidData` error and the rest of it stays unread.
fn read_reply_line(reader: &mut impl BufRead, reply: &mut String, max: usize) -> std::io::Result<usize> {
@@ -67,7 +77,7 @@ fn read_reply_line(reader: &mut impl BufRead, reply: &mut String, max: usize) ->
impl Remote {
/// Connect to a running control server; its session token is read lazily when the first request is sent.
pub fn connect(addr: &str) -> std::io::Result<Self> {
let mut r = Self { addr: addr.to_string(), conn: None, next_id: 1, launch: false, token: None, authed: false, max_reply: MAX_REPLY_LINE };
let mut r = Self::lazy(addr, false);
r.reconnect()?;
Ok(r)
}
@@ -75,12 +85,11 @@ impl Remote {
/// the server before the app is open. With `launch`, a call that finds nothing at `addr`
/// opens the app with that control port first (macOS) and waits for it.
pub fn lazy(addr: &str, launch: bool) -> Self {
Self { addr: addr.to_string(), conn: None, next_id: 1, launch, token: None, authed: false, max_reply: MAX_REPLY_LINE }
Self { addr: addr.to_string(), conn: None, next_id: 1, launch, token: None, authed: false, max_reply: MAX_REPLY_LINE, opened: None }
}
/// The per-session token for this port, read (and cached) from the owner-only token file. A
/// missing file is not fatal here: the request is sent without a token and the server replies
/// with an authentication error the user can act on.
/// The per-session token for this port, read (and cached) from the owner-only token file
/// (`None` when there is none; then nothing is sent, see [`Remote::prove_server`]).
///
/// The desktop app listens only on `127.0.0.1:PORT`, so the token goes only to that exact
/// peer: a name that also resolves elsewhere (`localhost` → `::1`, where another local account
@@ -134,15 +143,65 @@ impl Remote {
s.set_read_timeout(Some(Duration::from_secs(90))).ok();
let read = s.try_clone()?;
self.conn = Some((BufReader::new(read), s));
return Ok(());
self.opened = Some(Instant::now());
// A peer that can't prove it is the app gets nothing; another address may be.
match self.prove_server() {
Ok(()) => return Ok(()),
Err(e) => {
self.conn = None;
last = e;
}
}
}
Err(e) => last = e,
}
}
Err(last)
}
/// Have the peer just connected to prove it holds this port's session token before anything
/// else is sent to it: any program that listens on the port first would otherwise receive the
/// requests and could answer them (#1925). The `hello` carries a fresh nonce and no token; the
/// app answers with [`crate::control_token::server_proof`]. A proof made with another token is
/// checked once more against the token file, which a restarted app has rewritten.
fn prove_server(&mut self) -> std::io::Result<()> {
let refused = |addr: &str, why: &str| {
std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
format!(
"the program listening at {addr} {why}, so nothing was sent to it; is CADCraft running with its control port under this account?"
),
)
};
if self.token().is_none() {
return Err(refused(&self.addr, "is not a CADCraft session whose control token this account can read"));
}
let nonce = crate::control_token::new_nonce()?;
let hello = json!({"method": "hello", "params": {"nonce": nonce}}).to_string();
let reply = self.roundtrip_within(&hello, MAX_HELLO_REPLY).map_err(|(e, _)| e)?;
let reply = serde_json::from_str::<Value>(&reply).unwrap_or_default();
let Some(proof) = reply.pointer("/result/proof").and_then(Value::as_str) else {
// The app refuses a connection past its limit before reading anything: say why.
return Err(match reply.get("error").and_then(Value::as_str) {
Some(e) => std::io::Error::other(e.to_string()),
None => refused(&self.addr, "did not answer as CADCraft's control server does"),
});
};
let holds = |token: Option<&str>| token.is_some_and(|t| crate::control_token::verify_server_proof(t, &nonce, proof));
if holds(self.token.as_deref()) {
return Ok(());
}
self.token = None;
if holds(self.token()) {
return Ok(());
}
Err(refused(&self.addr, "could not prove it holds this account's control token"))
}
/// On failure the flag says whether the request may already have reached the server.
fn roundtrip(&mut self, line: &str) -> Result<String, (std::io::Error, bool)> {
self.roundtrip_within(line, self.max_reply)
}
/// [`Remote::roundtrip`], reading a reply of at most `max` bytes.
fn roundtrip_within(&mut self, line: &str, max: usize) -> Result<String, (std::io::Error, bool)> {
if self.conn.is_none() {
self.reach().map_err(|e| (e, false))?;
}
@@ -155,7 +214,7 @@ impl Remote {
return Err((e, true));
}
let mut reply = String::new();
match read_reply_line(reader, &mut reply, self.max_reply) {
match read_reply_line(reader, &mut reply, max) {
Ok(0) => {
self.conn = None;
Err((std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "connection closed"), true))
@@ -225,6 +284,11 @@ impl Remote {
/// passed the check (#1925), so a long request on a new connection goes after a `ping` with the
/// token; when the `ping` is refused its reply comes back instead and the request isn't sent.
fn sign_and_send(&mut self, req: &mut Value) -> Result<String, (std::io::Error, bool)> {
// The app closes a connection that hasn't shown the token in time; a request written to it
// then would be lost with its fate unknown, so such a connection is replaced first.
if !self.authed && self.opened.is_some_and(|t| t.elapsed() + PREAUTH_MARGIN >= crate::control_token::MAX_UNAUTHENTICATED_TIME) {
self.conn = None;
}
if self.conn.is_none() {
self.reach().map_err(|e| (e, false))?;
}
@@ -528,15 +592,40 @@ mod tests {
use std::net::TcpListener;
use std::sync::Arc;
/// The app's reply to `req` when it is a `hello`: a proof made with the token in this port's
/// file now (the app's own token).
fn hello_reply(req: &Value, port: u16) -> Option<Value> {
(req["method"] == "hello").then(|| {
let token = crate::control_token::read(port).unwrap_or_default();
let proof = crate::control_token::server_proof(&token, req["params"]["nonce"].as_str().unwrap_or_default());
json!({"ok": true, "result": {"proof": proof}})
})
}
/// Answer the `hello` a client opens a connection with, as the app does; `false` when the
/// client sent nothing.
fn answer_hello(reader: &mut impl BufRead, out: &mut impl Write, port: u16) -> bool {
let mut line = String::new();
if reader.read_line(&mut line).unwrap_or(0) == 0 {
return false;
}
let reply = hello_reply(&serde_json::from_str(&line).unwrap(), port).expect("a hello first");
writeln!(out, "{reply}").is_ok()
}
/// A peer squatting on the control port can't make the client buffer an endless reply line (#1925).
#[test]
fn an_overlong_reply_is_refused_without_buffering_it() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
let addr = listener.local_addr().unwrap().to_string();
crate::control_token::issue(port).unwrap();
let server = std::thread::spawn(move || {
let (mut conn, _) = listener.accept().unwrap();
let mut reader = BufReader::new(conn.try_clone().unwrap());
assert!(answer_hello(&mut reader, &mut conn, port));
let mut line = String::new();
BufReader::new(conn.try_clone().unwrap()).read_line(&mut line).unwrap();
reader.read_line(&mut line).unwrap();
// No newline: the reply never ends. A bounded client gives up after the limit.
let _ = conn.write_all(&[b'x'; 4096]);
let _ = conn.flush();
@@ -549,6 +638,7 @@ mod tests {
assert!(err.to_string().contains("longer than 100 bytes"), "{err}");
assert!(remote.conn.is_none());
server.join().unwrap();
crate::control_token::revoke(port);
}
#[test]
@@ -563,13 +653,17 @@ mod tests {
#[test]
fn lost_reply_to_a_mutation_is_not_resent() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
let addr = listener.local_addr().unwrap().to_string();
crate::control_token::issue(port).unwrap();
let server = std::thread::spawn(move || {
let mut requests = 0;
listener.set_nonblocking(false).unwrap();
let (conn, _) = listener.accept().unwrap();
let (mut conn, _) = listener.accept().unwrap();
let mut reader = BufReader::new(conn.try_clone().unwrap());
assert!(answer_hello(&mut reader, &mut conn, port));
let mut line = String::new();
BufReader::new(conn).read_line(&mut line).unwrap();
reader.read_line(&mut line).unwrap();
requests += 1;
// Anything arriving on a second connection would be a resend.
listener.set_nonblocking(true).unwrap();
@@ -582,6 +676,7 @@ mod tests {
let err = remote.call("engine.execute", json!({"command": "circle", "params": {}})).unwrap_err();
assert!(err.contains("may or may not have been applied"), "{err}");
assert_eq!(server.join().unwrap(), 1);
crate::control_token::revoke(port);
assert!(remote.token.is_none());
assert!(remote.conn.is_none());
}
@@ -591,18 +686,22 @@ mod tests {
fn timeout_reply_says_whether_a_retry_is_safe() {
for (state, want) in [("not-run", "safe to send again"), ("may-have-run", "Inspect the drawing first")] {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
let addr = listener.local_addr().unwrap().to_string();
crate::control_token::issue(port).unwrap();
let server = std::thread::spawn(move || {
let (conn, _) = listener.accept().unwrap();
let (mut out, _) = listener.accept().unwrap();
let mut reader = BufReader::new(out.try_clone().unwrap());
assert!(answer_hello(&mut reader, &mut out, port));
let mut line = String::new();
BufReader::new(conn.try_clone().unwrap()).read_line(&mut line).unwrap();
let mut out = conn;
reader.read_line(&mut line).unwrap();
writeln!(out, "{}", json!({"id": 1, "ok": false, "error": "timeout", "state": state})).unwrap();
});
let mut remote = Remote::connect(&addr).unwrap();
let err = remote.call("engine.execute", json!({"command": "circle", "params": {}})).unwrap_err();
assert!(err.starts_with("timeout") && err.contains(want), "{err}");
server.join().unwrap();
crate::control_token::revoke(port);
}
}
/// Retrying a read after a lost reply reloads the replacement server session token.
@@ -612,17 +711,21 @@ mod tests {
let addr = listener.local_addr().unwrap();
let old = crate::control_token::issue(addr.port()).unwrap();
let server = std::thread::spawn(move || {
let (conn, _) = listener.accept().unwrap();
let (mut conn, _) = listener.accept().unwrap();
let mut line = String::new();
let mut reader = BufReader::new(conn);
let mut reader = BufReader::new(conn.try_clone().unwrap());
assert!(answer_hello(&mut reader, &mut conn, addr.port()));
reader.read_line(&mut line).unwrap();
let first: Value = serde_json::from_str(&line).unwrap();
assert!(first["token"].as_str() == Some(old.as_str()));
let fresh = crate::control_token::issue(addr.port()).unwrap();
drop(reader);
drop((reader, conn));
let (mut conn, _) = listener.accept().unwrap();
line.clear();
BufReader::new(conn.try_clone().unwrap()).read_line(&mut line).unwrap();
let mut reader = BufReader::new(conn.try_clone().unwrap());
// The new session proves itself with its new token, which the client reads again.
assert!(answer_hello(&mut reader, &mut conn, addr.port()));
reader.read_line(&mut line).unwrap();
let retry: Value = serde_json::from_str(&line).unwrap();
assert!(retry["token"].as_str() == Some(fresh.as_str()));
writeln!(conn, "{}", json!({"ok": true, "result": "pong"})).unwrap();
@@ -636,6 +739,7 @@ mod tests {
/// and the connection number and says what to send back; the server closes after each reply.
/// Returns how many requests arrived, waiting a short while for each next connection.
fn fake_app(listener: TcpListener, reply: impl Fn(&Value, usize) -> Value + Send + 'static) -> std::thread::JoinHandle<usize> {
let port = listener.local_addr().unwrap().port();
std::thread::spawn(move || {
listener.set_nonblocking(true).unwrap();
let mut seen = 0;
@@ -648,11 +752,13 @@ mod tests {
Err(_) => break None,
}
};
let Some(conn) = conn else { return seen };
conn.set_nonblocking(false).unwrap();
let Some(mut out) = conn else { return seen };
out.set_nonblocking(false).unwrap();
let mut reader = BufReader::new(out.try_clone().unwrap());
let mut line = String::new();
BufReader::new(conn.try_clone().unwrap()).read_line(&mut line).unwrap();
let mut out = conn;
if !answer_hello(&mut reader, &mut out, port) || reader.read_line(&mut line).unwrap_or(0) == 0 {
continue;
}
writeln!(out, "{}", reply(&serde_json::from_str(&line).unwrap(), seen)).unwrap();
seen += 1;
}
@@ -660,21 +766,84 @@ mod tests {
}
/// A listener on another loopback address with the desktop's port (here `::1`) never receives
/// the desktop's token.
/// the desktop's token, nor any request: the client can't check it is the app.
#[test]
fn token_is_not_sent_to_another_loopback_listener() {
fn nothing_is_sent_to_another_loopback_listener() {
let Ok(listener) = TcpListener::bind("[::1]:0") else { return };
let addr = listener.local_addr().unwrap();
crate::control_token::issue(addr.port()).unwrap();
let server = fake_app(listener, move |req, _| {
assert!(req.get("token").is_none(), "token leaked to {addr}");
json!({"ok": true, "result": "x"})
let server = std::thread::spawn(move || {
let (conn, _) = listener.accept().unwrap();
let mut got = Vec::new();
BufReader::new(conn).read_to_end(&mut got).unwrap();
got
});
let mut remote = Remote::lazy(&addr.to_string(), false);
let got = remote.call("ping", json!({}));
drop(remote);
crate::control_token::revoke(addr.port());
assert_eq!(got, Ok(json!("x")));
assert_eq!(server.join().unwrap(), 1);
assert!(got.as_ref().is_err_and(|e| e.contains("nothing was sent")), "{got:?}");
assert!(server.join().unwrap().is_empty(), "the listener received bytes");
}
/// A program on the app's port that answers the `hello` without the token's proof (here it
/// echoes the nonce back, or another session's proof) gets no request, whatever it replies.
#[test]
fn a_peer_that_cannot_prove_the_token_gets_no_request() {
for forged in ["echo", "other session", "error"] {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
crate::control_token::issue(addr.port()).unwrap();
let server = std::thread::spawn(move || {
let mut lines = Vec::new();
listener.set_nonblocking(true).unwrap();
let start = Instant::now();
while start.elapsed() < Duration::from_millis(500) {
let Ok((mut out, _)) = listener.accept() else {
std::thread::sleep(Duration::from_millis(10));
continue;
};
out.set_nonblocking(false).unwrap();
for line in BufReader::new(out.try_clone().unwrap()).lines() {
let req: Value = serde_json::from_str(&line.unwrap()).unwrap();
let nonce = req["params"]["nonce"].as_str().unwrap_or_default().to_string();
lines.push(req["method"].as_str().unwrap_or_default().to_string());
let reply = match forged {
"echo" => json!({"ok": true, "result": {"proof": nonce}}),
"other session" => json!({"ok": true, "result": {"proof": crate::control_token::server_proof("another", &nonce)}}),
_ => json!({"ok": false, "error": "pretend error"}),
};
let _ = writeln!(out, "{reply}");
}
}
lines
});
let mut remote = Remote::lazy(&addr.to_string(), false);
let got = remote.call("engine.execute", json!({"command": "circle", "params": {}}));
drop(remote);
let lines = server.join().unwrap();
crate::control_token::revoke(addr.port());
assert!(got.is_err(), "{forged}: {got:?}");
assert!(lines.iter().all(|m| m == "hello"), "{forged}: {lines:?}");
}
}
/// An unauthenticated connection about to reach the app's `MAX_UNAUTHENTICATED_TIME` is
/// replaced before a request is written to it, so the request isn't lost when the app closes it.
#[test]
fn an_unauthenticated_connection_near_the_app_deadline_is_replaced() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
crate::control_token::issue(addr.port()).unwrap();
let server = fake_app(listener, |_, n| json!({"ok": true, "result": n}));
let mut remote = Remote::connect(&addr.to_string()).unwrap();
remote.opened = Some(Instant::now() - crate::control_token::MAX_UNAUTHENTICATED_TIME);
let got = remote.call("engine.execute", json!({"command": "circle", "params": {}}));
drop(remote);
let requests = server.join().unwrap();
crate::control_token::revoke(addr.port());
// The first connection only saw the `hello`; the request went on the second.
assert_eq!((got, requests), (Ok(json!(0)), 1));
}
/// `--launch` reads the token before it opens the app, so the first request carries the token
@@ -714,7 +883,9 @@ mod tests {
fn unauthorized_is_resent_at_most_once_and_only_when_not_run() {
for (state, connections) in [(Some("not-run"), 2), (Some("may-have-run"), 1), (None, 1)] {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
let addr = listener.local_addr().unwrap().to_string();
crate::control_token::issue(port).unwrap();
let server = fake_app(listener, move |_, _| {
let mut r = json!({"ok": false, "error": "unauthorized: missing or invalid control token"});
if let (Some(o), Some(state)) = (r.as_object_mut(), state) {
@@ -726,6 +897,7 @@ mod tests {
let err = remote.call("engine.execute", json!({"command": "circle", "params": {}})).unwrap_err();
assert!(err.starts_with("unauthorized"), "{err}");
assert_eq!(server.join().unwrap(), connections, "{state:?}");
crate::control_token::revoke(port);
assert!(remote.token.is_none() && remote.conn.is_none());
}
}
@@ -733,20 +905,25 @@ mod tests {
#[test]
fn failed_mutation_write_is_not_resent() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
let addr = listener.local_addr().unwrap().to_string();
let mut remote = Remote::connect(&addr).unwrap();
remote.conn.as_ref().unwrap().1.shutdown(std::net::Shutdown::Write).unwrap();
crate::control_token::issue(port).unwrap();
let server = std::thread::spawn(move || {
let (conn, _) = listener.accept().unwrap();
let (mut conn, _) = listener.accept().unwrap();
let mut reader = BufReader::new(conn.try_clone().unwrap());
assert!(answer_hello(&mut reader, &mut conn, port));
let mut line = String::new();
assert_eq!(BufReader::new(conn).read_line(&mut line).unwrap(), 0);
assert_eq!(reader.read_line(&mut line).unwrap(), 0);
listener.set_nonblocking(true).unwrap();
std::thread::sleep(Duration::from_millis(300));
listener.accept().is_ok()
});
let mut remote = Remote::connect(&addr).unwrap();
remote.conn.as_ref().unwrap().1.shutdown(std::net::Shutdown::Write).unwrap();
let error = remote.call("engine.execute", json!({"command": "circle", "params": {}})).unwrap_err();
assert!(error.contains("may or may not have been applied"));
assert!(!server.join().unwrap(), "a failed mutation write was retried");
crate::control_token::revoke(port);
assert!(remote.token.is_none());
}
@@ -761,6 +938,7 @@ mod tests {
listener: TcpListener,
mut valid: impl FnMut(usize) -> Result<String, Value> + Send + 'static,
) -> std::thread::JoinHandle<Vec<(usize, String, usize)>> {
let port = listener.local_addr().unwrap().port();
std::thread::spawn(move || {
listener.set_nonblocking(true).unwrap();
let mut seen = Vec::new();
@@ -783,6 +961,10 @@ mod tests {
let req: Value = serde_json::from_str(&line).unwrap();
let len = line.trim_end().len();
line.clear();
if let Some(reply) = hello_reply(&req, port) {
writeln!(out, "{reply}").unwrap();
continue;
}
seen.push((conn_no, req["method"].as_str().unwrap_or_default().to_string(), len));
let reply = if !authed && len > crate::control_token::MAX_UNAUTHENTICATED_LINE {
json!({"ok": false, "error": "request line too long before a request with the control token"})
+92 -6
View File
@@ -11,6 +11,9 @@
use std::io;
use std::path::PathBuf;
use hmac::{Hmac, Mac};
use sha2::Sha256;
/// Length of the token in bytes (256 bits), rendered as lowercase hex.
const TOKEN_BYTES: usize = 32;
@@ -21,6 +24,68 @@ const TOKEN_BYTES: usize = 32;
/// with the token has been answered on the same connection.
pub const MAX_UNAUTHENTICATED_LINE: usize = 64 * 1024;
/// How long a connection may stay open before a request on it has carried the right token; the
/// server closes it then, so peers without the token can't hold every connection slot until the
/// idle timeout (#1925). A client that keeps an unauthenticated connection this long opens a new one.
pub const MAX_UNAUTHENTICATED_TIME: std::time::Duration = std::time::Duration::from_secs(10);
/// Shortest and longest `hello` nonce, in hexadecimal digits.
pub const NONCE_DIGITS: std::ops::RangeInclusive<usize> = 32..=128;
/// What the server's proof is computed over besides the nonce, so a proof is never a valid token or
/// a MAC made for anything else.
const PROOF_LABEL: &[u8] = b"cadcraft control server proof v1\n";
/// A fresh nonce for a `hello` (256 bits of operating-system randomness, hex).
pub fn new_nonce() -> io::Result<String> {
random_hex()
}
/// Whether `nonce` is one the server answers: hexadecimal digits, [`NONCE_DIGITS`] long.
pub fn valid_nonce(nonce: &str) -> bool {
NONCE_DIGITS.contains(&nonce.len()) && nonce.bytes().all(|b| b.is_ascii_hexdigit())
}
/// HMAC-SHA-256 of the proof label and `nonce`, keyed with the session token (HMAC takes keys of
/// any length, so it is always `Some`).
fn proof_mac(token: &str, nonce: &str) -> Option<Hmac<Sha256>> {
let mut mac = <Hmac<Sha256> as Mac>::new_from_slice(token.as_bytes()).ok()?;
mac.update(PROOF_LABEL);
mac.update(nonce.as_bytes());
Some(mac)
}
/// The server's answer to a `hello` carrying `nonce`: it shows the server holds the session token
/// without sending the token, so a client can tell the app from another program listening on its
/// port before it sends a request (#1925).
pub fn server_proof(token: &str, nonce: &str) -> String {
proof_mac(token, nonce).map(|mac| hex(&mac.finalize().into_bytes())).unwrap_or_default()
}
/// Whether `proof` is [`server_proof`] for `token` and `nonce`, compared in constant time.
pub fn verify_server_proof(token: &str, nonce: &str, proof: &str) -> bool {
let (Some(bytes), Some(mac)) = (unhex(proof), proof_mac(token, nonce)) else { return false };
mac.verify_slice(&bytes).is_ok()
}
/// Lowercase hexadecimal.
fn hex(bytes: &[u8]) -> String {
let mut s = String::with_capacity(bytes.len() * 2);
for b in bytes {
use std::fmt::Write as _;
let _ = write!(s, "{b:02x}");
}
s
}
/// The bytes of an even-length hexadecimal string, or `None`.
fn unhex(text: &str) -> Option<Vec<u8>> {
if !text.len().is_multiple_of(2) {
return None;
}
text.as_bytes().chunks(2).map(|pair| std::str::from_utf8(pair).ok().and_then(|p| u8::from_str_radix(p, 16).ok())).collect()
}
/// The file holding the control token for `port`, inside a per-user private directory.
///
/// On Unix the runtime dir (`XDG_RUNTIME_DIR`, already `0700` and per-user) is preferred, else the
@@ -140,12 +205,7 @@ pub fn matches(expected: &str, given: &str) -> bool {
fn random_hex() -> io::Result<String> {
let mut bytes = [0u8; TOKEN_BYTES];
getrandom::fill(&mut bytes).map_err(|e| io::Error::other(format!("no secure randomness: {e}")))?;
let mut s = String::with_capacity(TOKEN_BYTES * 2);
for b in bytes {
use std::fmt::Write as _;
let _ = write!(s, "{b:02x}");
}
Ok(s)
Ok(hex(&bytes))
}
/// Replace a stale token with an exclusively created file using Unix mode `0600`, then flush its bytes.
@@ -175,6 +235,32 @@ fn write_private(path: &std::path::Path, bytes: &[u8]) -> io::Result<()> {
mod tests {
use super::*;
/// A proof checks out only for the token and nonce it was made with, and is neither the token
/// nor readable as one.
#[test]
fn a_server_proof_holds_only_for_its_token_and_nonce() {
let (token, nonce) = (random_hex().unwrap(), new_nonce().unwrap());
let proof = server_proof(&token, &nonce);
assert!(verify_server_proof(&token, &nonce, &proof));
assert!(!verify_server_proof(&random_hex().unwrap(), &nonce, &proof), "another token");
assert!(!verify_server_proof(&token, &new_nonce().unwrap(), &proof), "another nonce");
assert!(!matches(&token, &proof));
let mut flipped = proof.clone().into_bytes();
flipped[0] = if flipped[0] == b'0' { b'1' } else { b'0' };
for bad in [String::from_utf8(flipped).unwrap(), proof[1..].to_string(), format!("{}zz", &proof[2..]), String::new()] {
assert!(!verify_server_proof(&token, &nonce, &bad), "{bad:?}");
}
}
#[test]
fn nonces_are_hex_of_a_bounded_length() {
let nonce = new_nonce().unwrap();
assert!(valid_nonce(&nonce));
for bad in ["", "abc", &"0".repeat(*NONCE_DIGITS.end() + 1), &format!("{}g", &nonce[1..])] {
assert!(!valid_nonce(bad), "{bad:?}");
}
}
/// An issued token has the expected size, can be read back, and disappears after revocation.
#[test]
fn issue_then_read_round_trips() {
+11 -2
View File
@@ -261,19 +261,28 @@ fn a_lazy_bridge_starts_without_the_app_and_says_how_to_open_it() {
let msg = r["result"]["content"][0]["text"].as_str().unwrap();
assert!(msg.contains("not answering") && msg.contains("--control"), "{msg}");
// Once the app listens, the next call reaches it.
// Once the app listens (and has written its token), the next call reaches it.
let listener = std::net::TcpListener::bind(&addr).unwrap();
let port = listener.local_addr().unwrap().port();
let token = crate::control_token::issue(port).unwrap();
let app = std::thread::spawn(move || {
use std::io::{BufRead, Write};
let (sock, _) = listener.accept().unwrap();
let mut reader = std::io::BufReader::new(sock.try_clone().unwrap());
let mut line = String::new();
std::io::BufReader::new(sock.try_clone().unwrap()).read_line(&mut line).unwrap();
reader.read_line(&mut line).unwrap();
let hello = serde_json::from_str::<Value>(&line).unwrap();
let proof = crate::control_token::server_proof(&token, hello["params"]["nonce"].as_str().unwrap());
writeln!(&sock, "{}", json!({"ok": true, "result": {"proof": proof}})).unwrap();
line.clear();
reader.read_line(&mut line).unwrap();
let id = serde_json::from_str::<Value>(&line).unwrap()["id"].clone();
writeln!(&sock, "{}", json!({"id": id, "ok": true, "result": {"prompt": "Command:"}})).unwrap();
});
let r = call(&mut s, 4, "tools/call", json!({"name": "command_line", "arguments": {"text": ""}}));
assert_ne!(r["result"]["isError"], json!(true), "{r}");
app.join().unwrap();
crate::control_token::revoke(port);
}
/// The pixels of a `render` tool result.
+18 -1
View File
@@ -23,6 +23,22 @@ reply and the connection is closed. To send a longer request (a script, a drawin
new connection, first send a short one with the token, such as `ping`, and wait for its reply.
The MCP bridge does this too.
Any program can listen on the port while the app isn't, so a client can first ask the server to
prove it is the app, before it sends anything else on the connection:
```json
{"id": "h", "method": "hello", "params": {"nonce": "<32 to 128 hexadecimal digits>"}}
{"id": "h", "ok": true, "result": {"proof": "<64 hexadecimal digits>"}}
```
`hello` needs no token and doesn't count as showing it. The proof is HMAC-SHA-256 keyed with the
session token, over the bytes `cadcraft control server proof v1` and a newline followed by the
nonce, in lowercase hexadecimal. A client that computes the same value from the token file knows the
server holds the token; use a fresh random nonce each time. A `hello` without a valid nonce gets an
error and the connection is closed. The MCP bridge sends a `hello` on every new connection and
sends nothing more to a server that can't prove it holds the token, or when it can't read a token
for the port.
Errors come back as `{"id": …, "ok": false, "error": "message"}`. An unknown method's error points
to `control.methods`, which lists the methods the server answers.
@@ -32,7 +48,8 @@ after it runs. Blank lines are skipped.
The server bounds what a client can hold: 16 connections at once (more get an error line and are
closed), 256 MiB per request line (64 KiB until the connection has shown the token; longer closes
the connection), 64 queued requests (more are
the connection), 10 seconds from connecting to the first request with the token (then the
connection is closed, whatever it has sent), 64 queued requests (more are
answered `{"ok": false, "error": "busy: …", "state": "not-run"}`), and 10 minutes idle or 30 seconds
per blocked reply write before the socket is closed.