mirror of
https://github.com/storytold/designcraft.git
synced 2026-11-15 23:02:32 +00:00
MCP: cap one request line at 4 MiB (#2803)
* MCP: cap one request line at 4 MiB The stdio server read newline-delimited requests with read_until into a growing Vec, so a client that never sends a newline could grow it without bound. One line now stops at 4 MiB, answers with an invalid-request error and drops the rest of the line, then keeps serving the next request. * mcp: only discard the remainder of a line that was actually cut * mcp: serialize the too-long reply as JSON bytes * mcp: format the too-long-line reply * mcp: cover the line-cap discard and EOF paths
This commit is contained in:
1 parent
f5087eae96
commit
abac0a9bce
2 files changed
+81
-2
No files matched your search
@@ -1,6 +1,6 @@
|
||||
//! JSON-RPC 2.0 framing and the MCP lifecycle / tools / resources methods.
|
||||
|
||||
use std::io::{BufRead, Write};
|
||||
use std::io::{BufRead, Read, Write};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -18,6 +18,30 @@ const INVALID_PARAMS: i64 = -32602;
|
||||
const INTERNAL_ERROR: i64 = -32603;
|
||||
const RESOURCE_NOT_FOUND: i64 = -32002;
|
||||
|
||||
/// Most bytes one request line may hold. A client that never sends a newline must not grow the
|
||||
/// reader's buffer without bound (audit: DesignCraft #3).
|
||||
const MAX_LINE_BYTES: u64 = 4 << 20;
|
||||
|
||||
/// Drop the rest of an over-long request line without buffering it.
|
||||
fn discard_line(input: &mut impl BufRead) -> std::io::Result<()> {
|
||||
loop {
|
||||
let (consume, done) = {
|
||||
let available = input.fill_buf()?;
|
||||
if available.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
match available.iter().position(|&b| b == b'\n') {
|
||||
Some(i) => (i + 1, true),
|
||||
None => (available.len(), false),
|
||||
}
|
||||
};
|
||||
input.consume(consume);
|
||||
if done {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const INSTRUCTIONS: &str = "DesignCraft is a page-layout app (an InDesign clone). Coordinates are points in spread \
|
||||
space (y down; on a single-page spread the page's top-left is (0,0); a default Letter page is 612×792). Every action \
|
||||
is a command: find ids and parameters with list_commands and run them with execute (or several with batch). Typical \
|
||||
@@ -63,9 +87,23 @@ impl Server {
|
||||
let mut buf = Vec::new();
|
||||
loop {
|
||||
buf.clear();
|
||||
if input.read_until(b'\n', &mut buf)? == 0 {
|
||||
// A client that never sends a newline must not grow this buffer without bound
|
||||
// (audit: DesignCraft #3). Read one byte past the limit, then drop the rest.
|
||||
if (&mut input).take(MAX_LINE_BYTES + 1).read_until(b'\n', &mut buf)? == 0 {
|
||||
break;
|
||||
}
|
||||
if buf.len() as u64 > MAX_LINE_BYTES {
|
||||
// The terminator may already be in `buf` (a line exactly at the limit); only a
|
||||
// line cut before its newline leaves a rest to drop.
|
||||
if buf.last() != Some(&b'\n') {
|
||||
discard_line(&mut input)?;
|
||||
}
|
||||
let reply = serde_json::to_vec(&error(Value::Null, INVALID_REQUEST, "request line is too long")).map_err(std::io::Error::other)?;
|
||||
output.write_all(&reply)?;
|
||||
output.write_all(b"\n")?;
|
||||
output.flush()?;
|
||||
continue;
|
||||
}
|
||||
// Invalid UTF-8 becomes U+FFFD, so the line gets a parse error instead of ending the stream.
|
||||
let line = String::from_utf8_lossy(&buf);
|
||||
let line = line.trim_end_matches(['\r', '\n']);
|
||||
|
||||
@@ -98,6 +98,47 @@ fn serve_survives_invalid_utf8_line() {
|
||||
assert_eq!(lines[3]["id"], 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serve_rejects_an_over_long_line_and_keeps_serving() {
|
||||
let mut s = server();
|
||||
let mut input = vec![b'x'; 4 << 20];
|
||||
input.push(b'\n');
|
||||
input.extend_from_slice(json!({"jsonrpc":"2.0","id":7,"method":"ping"}).to_string().as_bytes());
|
||||
input.push(b'\n');
|
||||
let mut out = Vec::new();
|
||||
s.serve(input.as_slice(), &mut out).unwrap();
|
||||
let lines: Vec<Value> = String::from_utf8(out).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect();
|
||||
assert_eq!(lines.len(), 2, "{lines:?}");
|
||||
assert_eq!(lines[0]["error"]["code"], -32600);
|
||||
assert_eq!(lines[1]["id"], 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serve_discards_the_rest_of_an_over_long_line_without_a_newline() {
|
||||
let mut s = server();
|
||||
let mut input = vec![b'x'; (4 << 20) + 10];
|
||||
input.push(b'\n');
|
||||
input.extend_from_slice(json!({"jsonrpc":"2.0","id":8,"method":"ping"}).to_string().as_bytes());
|
||||
input.push(b'\n');
|
||||
let mut out = Vec::new();
|
||||
s.serve(input.as_slice(), &mut out).unwrap();
|
||||
let lines: Vec<Value> = String::from_utf8(out).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect();
|
||||
assert_eq!(lines.len(), 2, "{lines:?}");
|
||||
assert_eq!(lines[0]["error"]["code"], -32600);
|
||||
assert_eq!(lines[1]["id"], 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serve_stops_at_eof_in_an_over_long_line() {
|
||||
let mut s = server();
|
||||
let input = vec![b'x'; (4 << 20) + 10];
|
||||
let mut out = Vec::new();
|
||||
s.serve(input.as_slice(), &mut out).unwrap();
|
||||
let lines: Vec<Value> = String::from_utf8(out).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect();
|
||||
assert_eq!(lines.len(), 1, "{lines:?}");
|
||||
assert_eq!(lines[0]["error"]["code"], -32600);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn protocol_round_trip_over_serve() {
|
||||
let mut s = server();
|
||||
|
||||
Reference in new issue
Block a user