From a05a0f1053264e113a76a1680dced3fc5aab509e Mon Sep 17 00:00:00 2001 From: Taha Zarif Date: Fri, 23 Oct 2026 13:43:52 +0000 Subject: [PATCH] Fix/mcp stdio bounded request lines (#4972) * test(mcp): reproduce whitespace bypass of request-size limit Add a source-level regression that rejects a JSON-RPC request larger than MAX_LINE even when most of it is whitespace, plus bounded-stdio framing coverage and invalid UTF-8 recovery. * fix(mcp): bound stdio line buffering and validate raw request size Consume oversize JSON-RPC lines in bounded memory while keeping the following request available. Reject whitespace-padded lines before trimming, preventing a request-size cap bypass. * docs(mcp): keep server framing comment idiomatic --- crates/mcp/src/server.rs | 61 +++++++++++++++++++++++++++++----------- crates/mcp/src/tests.rs | 40 ++++++++++++++++++++++++++ 2 files changed, 84 insertions(+), 17 deletions(-) diff --git a/crates/mcp/src/server.rs b/crates/mcp/src/server.rs index 584f5b4f9..adfe1567a 100644 --- a/crates/mcp/src/server.rs +++ b/crates/mcp/src/server.rs @@ -65,22 +65,48 @@ impl Server { } /// Serve newline-delimited JSON-RPC until `input` closes. Only protocol messages go to - /// `output`; diagnostics belong on stderr. - pub fn serve(&mut self, input: impl BufRead, mut output: impl Write) -> std::io::Result<()> { - for line in input.lines() { - let line = match line { - Ok(l) => l, - // Not UTF-8: answer with a parse error and keep serving. - Err(e) if e.kind() == std::io::ErrorKind::InvalidData => { - let reply = error(Value::Null, PARSE_ERROR, "parse error: input is not UTF-8").to_string(); - output.write_all(reply.as_bytes())?; - output.write_all(b"\n")?; - output.flush()?; - continue; + /// `output`; diagnostics belong on stderr. Consume oversized lines in bounded space so an + /// agent cannot exhaust memory by sending an arbitrarily long request without a newline. + pub fn serve(&mut self, mut input: impl BufRead, mut output: impl Write) -> std::io::Result<()> { + loop { + let mut line = Vec::new(); + let mut oversized = false; + let mut received = false; + loop { + let chunk = input.fill_buf()?; + if chunk.is_empty() { + break; + } + let count = chunk.iter().position(|&byte| byte == b'\n').map_or(chunk.len(), |i| i + 1); + let newline = chunk[count - 1] == b'\n'; + let content_len = count - usize::from(newline); + if !oversized { + if line.len().saturating_add(content_len) > MAX_LINE { + oversized = true; + line.clear(); + } else { + line.extend_from_slice(&chunk[..content_len]); + } + } + input.consume(count); + received = true; + if newline { + break; + } + } + if !received { + break; + } + let reply = if oversized { + Some(error(Value::Null, INVALID_REQUEST, "request too large").to_string()) + } else { + match String::from_utf8(line) { + Ok(line) => self.handle_line(&line), + // Not UTF-8: answer with a parse error and keep serving. + Err(_) => Some(error(Value::Null, PARSE_ERROR, "parse error: input is not UTF-8").to_string()), } - Err(e) => return Err(e), }; - if let Some(reply) = self.handle_line(&line) { + if let Some(reply) = reply { output.write_all(reply.as_bytes())?; output.write_all(b"\n")?; output.flush()?; @@ -91,13 +117,14 @@ impl Server { /// One line in, at most one line out (notifications get no reply). pub fn handle_line(&mut self, line: &str) -> Option { + // Check the raw input before trimming: a huge whitespace prefix is still a huge line. + if line.len() > MAX_LINE { + return Some(error(Value::Null, INVALID_REQUEST, "request too large").to_string()); + } let line = line.trim(); if line.is_empty() { return None; } - if line.len() > MAX_LINE { - return Some(error(Value::Null, INVALID_REQUEST, "request too large").to_string()); - } let reply = match serde_json::from_str::(line) { Ok(Value::Array(batch)) if batch.is_empty() => Some(error(Value::Null, INVALID_REQUEST, "empty batch")), Ok(Value::Array(batch)) if batch.len() > MAX_BATCH => Some(error(Value::Null, INVALID_REQUEST, "batch too large")), diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index c17e332b6..fdd13a831 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -48,6 +48,46 @@ fn tool(s: &mut Server, name: &str, args: Value) -> Value { if c["type"] == "text" { serde_json::from_str(c["text"].as_str().unwrap()).unwrap_or(Value::Null) } else { c.clone() } } +/// A large whitespace prefix must not evade the raw 16 MiB JSON-RPC line limit. +#[test] +fn whitespace_does_not_bypass_mcp_request_limit() { + let mut s = server(); + let request = format!("{}{}", " ".repeat(solidcraft_engine::MAX_LINE), r#"{"jsonrpc":"2.0","id":1,"method":"ping"}"#); + let reply: Value = serde_json::from_str(&s.handle_line(&request).expect("size error")).unwrap(); + assert_eq!(reply["error"]["code"], -32600, "{reply}"); + assert!(reply["result"].is_null(), "oversized request must not execute: {reply}"); +} + +/// The transport must discard an oversized line in bounded space and resume on the next one. +#[test] +fn oversized_mcp_stdio_line_does_not_poison_the_next_request() { + let mut bytes = vec![b'X'; solidcraft_engine::MAX_LINE + 1]; + bytes.extend_from_slice(b"\n{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"ping\"}\n"); + let input = std::io::BufReader::with_capacity(64, std::io::Cursor::new(bytes)); + let mut output = Vec::new(); + server().serve(input, &mut output).unwrap(); + let text = String::from_utf8(output).unwrap(); + let replies: Vec = text.lines().map(|line| serde_json::from_str(line).unwrap()).collect(); + assert_eq!(replies.len(), 2, "{text}"); + assert_eq!(replies[0]["error"]["code"], -32600, "{}", replies[0]); + assert_eq!(replies[1]["id"], 2, "{}", replies[1]); + assert_eq!(replies[1]["result"], json!({}), "{}", replies[1]); +} + +/// Preserve parse-error framing and accept an unterminated final line. +#[test] +fn mcp_stdio_recovers_after_invalid_utf8_and_accepts_eof() { + let input = b"\xff\n{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"ping\"}"; + let mut output = Vec::new(); + server().serve(std::io::Cursor::new(input), &mut output).unwrap(); + let text = String::from_utf8(output).unwrap(); + let replies: Vec = text.lines().map(|line| serde_json::from_str(line).unwrap()).collect(); + assert_eq!(replies.len(), 2, "{text}"); + assert_eq!(replies[0]["error"]["code"], -32700); + assert_eq!(replies[1]["id"], 3); + assert_eq!(replies[1]["result"], json!({})); +} + #[test] fn crash_reports_are_listed_and_read_without_changing_the_design() { let mut s = server();