PhotoCraft: An open-source, photo editor written by scratch in pure Rust
fix(automation): downscale bridge screenshots before PNG budget (#753)
Alex Gorevski151afe47b6b3
diff --git a/book/src/security/automation-security.md b/book/src/security/automation-security.mdindex 71e5c2711..38504dba0 100644--- a/book/src/security/automation-security.md+++ b/book/src/security/automation-security.md@@ -19,7 +19,8 @@ Automation is a privilege boundary because requests can cause filesystem access,PNGs are limited to 5 MiB before base64 encoding or file writes. Trusted-local CLI renderingretains its existing behavior.- The MCP bridge bounds incoming replies and does not retry an operation after an oversized- reply. Screenshot decoding has separate dimension, pixel, and allocation ceilings.+ reply. Screenshots are decoded under separate dimension, pixel, and allocation ceilings before+ downscaling; the 5 MiB PNG limit applies to the returned image.- MCP normally uses stdio and can optionally bridge to loopback control TCP.- The bridge and UI request paths use timeouts.- Engine commands are expected to reject invalid parameters without panicking.diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rsindex 1ac57b82e..4cd8f3743 100644--- a/crates/automation/src/server.rs+++ b/crates/automation/src/server.rs@@ -309,14 +309,14 @@ impl PhotocraftMcp {Ok(bytes) => bytes,Err(error) => return Ok(fail(format!("app screenshot data: {error}"))),};- if let Err(error) = check_png(bytes.len()) {- return Ok(fail(error));- }let bytes = match downscale_png(&bytes, max_side.unwrap_or(0)) {Ok(Some(small)) => small,Ok(None) => bytes,Err(error) => return Ok(fail(error)),};+ if let Err(error) = check_png(bytes.len()) {+ return Ok(fail(error));+ }Ok(png_result(&bytes, "screenshot of the live app window".into()))}}@@ -699,6 +699,7 @@ mod tests {fn bridge_screenshot_decode_limits_apply_even_without_downscaling() {let image = photocraft_codecs::Image::from_u8(8193, 1, photocraft_codecs::ChannelLayout::Rgba, vec![0; 8193 * 4]).unwrap();let png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap();+ assert!(downscale_png(b"not a png", 32).is_err());assert!(downscale_png(&png, 0).is_err());assert!(downscale_png(&png, 1024).is_err());}diff --git a/crates/automation/tests/mcp.rs b/crates/automation/tests/mcp.rsindex 20eb83653..30c588b51 100644--- a/crates/automation/tests/mcp.rs+++ b/crates/automation/tests/mcp.rs@@ -399,6 +399,10 @@ async fn filesystem_policy_rejects_absolute_and_escaping_paths_before_effects()// ---------------------------------------------------------------------------async fn fake_app() -> (String, tokio::task::JoinHandle<Vec<Value>>) {+ fake_app_with_screenshot(None).await+}++async fn fake_app_with_screenshot(screenshot_png: Option<Vec<u8>>) -> (String, tokio::task::JoinHandle<Vec<Value>>) {let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();let addr = listener.local_addr().unwrap().to_string();let h = tokio::spawn(async move {@@ -430,8 +434,10 @@ async fn fake_app() -> (String, tokio::task::JoinHandle<Vec<Value>>) {}"ui.pointer" => json!({"id": id, "ok": true, "result": req["params"]}),"ui.screenshot" => {- let img = photocraft_codecs::Image::from_u8(40, 20, photocraft_codecs::ChannelLayout::Rgba, vec![9; 3200]).unwrap();- let bytes = photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap();+ let bytes = screenshot_png.clone().unwrap_or_else(|| {+ let img = photocraft_codecs::Image::from_u8(40, 20, photocraft_codecs::ChannelLayout::Rgba, vec![9; 3200]).unwrap();+ photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap()+ });let png = base64::engine::general_purpose::STANDARD.encode(bytes);json!({"id": id, "ok": true, "result": {"mimeType": "image/png", "base64": png}})}@@ -475,6 +481,44 @@ async fn bridge_forwards_to_control_protocol() {app.abort();}+#[tokio::test(flavor = "multi_thread")]+async fn bridge_previews_downscale_before_enforcing_the_png_budget() {+ use photocraft_automation::budgets::MAX_PNG_BYTES;++ let (width, height) = (1400, 1000);+ let mut pixels = vec![0; width * height * 4];+ let mut state = 0x6d2b_79f5_u32;+ for pixel in &mut pixels {+ state ^= state << 13;+ state ^= state >> 17;+ state ^= state << 5;+ *pixel = state as u8;+ }+ let image = photocraft_codecs::Image::from_u8(width as u32, height as u32, photocraft_codecs::ChannelLayout::Rgba, pixels).unwrap();+ let source_png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap();+ assert!(source_png.len() > MAX_PNG_BYTES, "fixture must exceed the PNG budget");++ let (addr, app) = fake_app_with_screenshot(Some(source_png)).await;+ let client = connect(PhotocraftMcp::bridge(&addr, CONTROL_TOKEN).unwrap()).await;++ for (tool, args) in [("ui_screenshot", json!({"max_side": 32})), ("doc_render_preview", json!({"max_side": 32}))] {+ let reply = call(&client, tool, args).await;+ assert_ne!(reply.is_error, Some(true), "{tool}: {}", text(&reply));+ let img = reply.content.iter().find_map(|content| content.as_image()).expect("preview image");+ let png = base64::engine::general_purpose::STANDARD.decode(&img.data).unwrap();+ assert!(png.len() <= MAX_PNG_BYTES, "{tool} returned {} bytes", png.len());+ let decoded = photocraft_codecs::decode(&png).unwrap();+ assert_eq!(decoded.dimensions(), (32, 22), "{tool}");+ }++ let full_size = call(&client, "ui_screenshot", json!({})).await;+ assert_eq!(full_size.is_error, Some(true));+ assert!(text(&full_size).contains("automation PNG exceeds"), "{}", text(&full_size));++ client.cancel().await.unwrap();+ app.abort();+}+#[test]fn bridge_rejects_non_loopback() {assert!(PhotocraftMcp::bridge("10.0.0.5:7878", CONTROL_TOKEN).is_err());