SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Control channel: check the token before parsing the whole request (#6643)
DuBearte3726959d8212
diff --git a/Cargo.lock b/Cargo.lockindex 70a7f05d84..a13df3b6e5 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -4229,6 +4229,7 @@ dependencies = ["rfd","ron","rustls",+ "serde","serde_json","solidcraft-3dx-client","solidcraft-engine",diff --git a/apps/solidcraft/Cargo.toml b/apps/solidcraft/Cargo.tomlindex 53ea9b447e..85ba056600 100644--- a/apps/solidcraft/Cargo.toml+++ b/apps/solidcraft/Cargo.toml@@ -32,6 +32,7 @@ solidcraft-ui-egui = { workspace = true }solidcraft-space-mouse = { workspace = true }eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "wayland", "x11", "links"] }egui = { workspace = true }+serde = { workspace = true }serde_json = { workspace = true }log = { workspace = true }rfd = { workspace = true }diff --git a/apps/solidcraft/src/control_server.rs b/apps/solidcraft/src/control_server.rsindex f5185b356e..9602aa9d17 100644--- a/apps/solidcraft/src/control_server.rs+++ b/apps/solidcraft/src/control_server.rs@@ -187,6 +187,35 @@ fn send(out: &mut impl Write, reply: &Value) -> std::io::Result<()> {out.write_all(&line)}+/// The `"token"` of a request line that is a JSON object, read without building the rest of it.+/// Until a connection shows the token, a line costs only its own bytes: parsed whole, a 16 MiB+/// line of `[0,0,…]` is hundreds of MB, and 16 such connections could exhaust memory before any+/// token was checked.+fn token_of(line: &str) -> Option<String> {+ struct Token;+ impl<'de> serde::de::Visitor<'de> for Token {+ type Value = Option<String>;+ fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {+ f.write_str("a request object")+ }+ fn visit_map<A: serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {+ let mut token = None;+ while let Some(key) = map.next_key::<String>()? {+ if key == "token" {+ token = Some(map.next_value::<String>()?);+ } else {+ map.next_value::<serde::de::IgnoredAny>()?;+ }+ }+ Ok(token)+ }+ }+ let mut de = serde_json::Deserializer::from_str(line);+ let token = serde::Deserializer::deserialize_map(&mut de, Token).ok()?;+ de.end().ok()?;+ token+}+/// The reply to a connection that didn't show the token; the connection is then closed.fn unauthorized() -> Value {json!({"ok": false, "error": "unauthorized: send the control token as \"token\" (see docs/control-protocol.md)"})@@ -486,18 +515,18 @@ fn serve_with(if line.trim().is_empty() {continue;}+ // The first request must carry the token; later ones on the same connection may.+ if !authenticated {+ match token_of(&line) {+ Some(t) if control_auth::tokens_match(&t, token) => authenticated = true,+ _ => {+ refuse(&mut out, &mut reader);+ break;+ }+ }+ }let reply = match serde_json::from_str::<Value>(&line) {Ok(msg) => {- // The first request must carry the token; later ones on the same connection may.- if !authenticated {- match msg.get("token").and_then(Value::as_str) {- Some(t) if control_auth::tokens_match(t, token) => authenticated = true,- _ => {- refuse(&mut out, &mut reader);- break;- }- }- }let id = msg.get("id").cloned().unwrap_or(Value::Null);let method = msg.get("method").and_then(Value::as_str).unwrap_or("").to_string();let params = msg.get("params").cloned().unwrap_or(json!({}));@@ -563,10 +592,6 @@ fn serve_with(}r}- Err(_) if !authenticated => {- refuse(&mut out, &mut reader);- break;- }Err(e) => {bad += 1;json!({"ok": false, "error": format!("bad JSON: {e}")})@@ -869,6 +894,19 @@ mod tests {assert!(render.contains("will still write the file"), "{render}");}+ /// The token is read from a request object without building the rest of it: other fields,+ /// however large or nested, are only skipped. Anything but an object with a string token is+ /// no token.+ #[test]+ fn token_is_read_without_parsing_the_request() {+ assert_eq!(token_of(r#"{"id":1,"token":"abc","params":{"a":[1,[2,{"b":null}]]}}"#).as_deref(), Some("abc"));+ let flood = format!(r#"{{"params":[{}0],"token":"t"}}"#, "0,".repeat(1 << 20));+ assert_eq!(token_of(&flood).as_deref(), Some("t"));+ for no in [r#"["abc"]"#, r#"{"token":5}"#, r#"{"token":"a"} x"#, r#"{"id":1}"#, "GET / HTTP/1.1", r#""token""#] {+ assert_eq!(token_of(no), None, "{no}");+ }+ }+/// #205: a connection runs nothing until a request carries the launch's token; a wrong or/// missing token, or garbage, is refused and the connection closed. Once shown, the token/// need not be repeated on that connection.