diff --git a/app/src/mcp/mod.rs b/app/src/mcp/mod.rs index 69487bd6..5e7206ce 100644 --- a/app/src/mcp/mod.rs +++ b/app/src/mcp/mod.rs @@ -114,10 +114,13 @@ fn user_id(rc: &RequestContext) -> Option { principal_of(rc).and_then(|p| p.user().map(|u| u.id)) } -/// Kind, fingerprint and content type of an uploaded file, as the CLI works them out. -fn classify(filename: Option<&str>, bytes: &[u8]) -> Result<(&'static str, String, &'static str), String> { +/// Kind, fingerprint and content type of an uploaded file. Only a text's fingerprint (its SHA-256) is worked out here: +/// nothing is parsed or decoded in this process (docs/design.md: customer PDFs are parsed only on the render node). +/// Images and PDFs are registered by their hash alone (sc-8999), and the server fingerprints them in processing (an +/// image) or takes the renderer's fingerprint once it's drawn (a PDF). +fn classify(filename: Option<&str>, bytes: &[u8]) -> (&'static str, Option, &'static str) { if bytes.starts_with(b"%PDF") { - return Ok(("document", visualci_core::pdf::fingerprint_bytes(bytes).document, "application/pdf")); + return ("document", None, "application/pdf"); } let ext = filename.and_then(|f| f.rsplit('.').next()).unwrap_or("").to_ascii_lowercase(); let image_type = match ext.as_str() { @@ -129,11 +132,10 @@ fn classify(filename: Option<&str>, bytes: &[u8]) -> Result<(&'static str, Strin _ => None, }; if let Some(content_type) = image_type { - let fp = visualci_core::image_hash::fingerprint_bytes(bytes).map_err(|e| format!("decoding the image: {e}"))?; - return Ok(("image", fp, content_type)); + return ("image", None, content_type); } let format = visualci_core::snapshot_text::Format::detect(None, None, filename); - Ok(("text", visualci_core::sha256_hex(bytes), format.content_type())) + ("text", Some(visualci_core::sha256_hex(bytes)), format.content_type()) } /// `let Some(x) = ... else return tool_error` for the `Result, ErrorData>` helpers. @@ -1894,10 +1896,7 @@ impl VisualCi { if total > MAX_UPLOAD_BYTES { return Ok(tool_error("more than 64 MB of files in one call: split them over several calls")); } - let (kind, fingerprint, content_type) = match classify(f.filename.as_deref(), &bytes) { - Ok(c) => c, - Err(e) => return Ok(tool_error(format!("{}: {e}", f.name))), - }; + let (kind, fingerprint, content_type) = classify(f.filename.as_deref(), &bytes); decoded.push((bytes, kind, fingerprint, content_type)); } let params: Vec = args @@ -1908,7 +1907,7 @@ impl VisualCi { name: f.name.clone(), platform: f.platform.clone(), kind: (*kind).to_string(), - fingerprint: Some(fingerprint.clone()), + fingerprint: fingerprint.clone(), sha256: visualci_core::sha256_hex(bytes), size: i64::try_from(bytes.len()).unwrap_or(i64::MAX), content_type: (*content_type).to_string(), diff --git a/app/tests/mcp_uploads.rs b/app/tests/mcp_uploads.rs new file mode 100644 index 00000000..07fee221 --- /dev/null +++ b/app/tests/mcp_uploads.rs @@ -0,0 +1,148 @@ +//! MCP `upload_snapshots` parses and decodes nothing in the app process (docs/design.md: customer PDFs are parsed +//! only on the render node): a PDF or image is registered by its hash alone, a PDF takes the fingerprint its renderer +//! reports once it's drawn, and an image's is computed in processing (sc-8999). + +use app::models::{Blob, Build, Snapshot}; +use app::testing::fixtures; +use base64::Engine; +use laravel::db; +use laravel::testing::prelude::*; +use serde_json::{Value, json}; + +const RENDERER: &str = "Bearer renderer-test-token"; + +async fn project_token() -> laravel::Result { + let org = fixtures::organization(&format!("org-{}", &laravel::str::uuid7().simple().to_string()[24..])).await?; + let project = fixtures::project(&org, "docs").await?; + let token = format!("vci_{}", laravel::str::uuid7().simple()); + let (hash, project_id) = (app::models::token_hash(&token), project.id); + db::query!( + "INSERT INTO project_tokens (project_id, name, token_hash, token_prefix, created_at, updated_at) \ + VALUES ({project_id}, 'CI', {hash}, 'vci_ab', now(), now())" + ) + .insert() + .await?; + Ok(token) +} + +/// Call an MCP tool: (is_error, structured content or the first text block). +async fn call(app: &Application, token: &str, tool: &str, args: Value) -> (bool, Value) { + let response = app + .post("/mcp") + .header("authorization", format!("Bearer {token}")) + .json( + json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": tool, "arguments": args } }), + ) + .header("accept", "application/json, text/event-stream") + .await; + response.assert_ok(); + let result = response.json()["result"].clone(); + let value = if result["structuredContent"].is_null() { + json!(result["content"][0]["text"]) + } else { + result["structuredContent"].clone() + }; + (result["isError"].as_bool().unwrap_or(false), value) +} + +fn png(rgb: [u8; 3]) -> Vec { + let image = image::RgbaImage::from_pixel(16, 16, image::Rgba([rgb[0], rgb[1], rgb[2], 255])); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).expect("a PNG encodes"); + bytes +} + +async fn put(url: &str, bytes: Vec, content_type: &str) { + let r = reqwest::Client::new().put(url).header("content-type", content_type).body(bytes).send().await.unwrap(); + assert!(r.status().is_success(), "uploading: {}", r.status()); +} + +async fn snapshot(name: &str) -> laravel::Result { + let build = Build::query().filter(Build::number.eq(1)).first().await?.expect("the build"); + Ok(app::domain::snapshots::named_in_build(build.id, name).await?.into_iter().next().expect("the snapshot")) +} + +#[laravel::test] +async fn an_mcp_upload_fingerprints_nothing_in_the_app_and_takes_the_renderers( + app: Application, +) -> laravel::Result<()> { + Box::pin(mcp_upload(app)).await +} + +async fn mcp_upload(app: Application) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + let (err, build) = call(&app, &token, "create_build", json!({ "commit": "abc", "branch": "main" })).await; + assert!(!err, "{build}"); + // Not a PDF lopdf can parse: had the app fingerprinted it, it would have the file's SHA-256 as its fingerprint. + let pdf = b"%PDF-1.4 an invoice from an agent".to_vec(); + let pdf_sha = visualci_core::sha256_hex(&pdf); + let shot = png([10, 200, 30]); + let b64 = base64::engine::general_purpose::STANDARD; + let (err, up) = call( + &app, + &token, + "upload_snapshots", + json!({ "build": 1, "files": [ + { "name": "invoice", "content_base64": b64.encode(&pdf), "filename": "invoice.pdf" }, + { "name": "home", "content_base64": b64.encode(&shot), "filename": "home.png" }, + ]}), + ) + .await; + assert!(!err, "{up}"); + assert_eq!(up["snapshots"][0]["stored"], true, "{up}"); + + // Registered by hash alone: no fingerprint worked out in this process, for the PDF or the image. + assert_eq!(snapshot("invoice").await?.source_fingerprint, ""); + assert_eq!(snapshot("home").await?.source_fingerprint, ""); + let blob = Blob::find(pdf_sha.clone()).await?.expect("the PDF's blob"); + assert_eq!((blob.pdf_fingerprint, blob.pixel_fingerprint), (None, None)); + + let (err, done) = call(&app, &token, "finalize_build", json!({ "build": 1 })).await; + assert!(!err, "{done}"); + assert_eq!(done["state"], "processing", "waiting for the PDF's render: {done}"); + // The image's fingerprint was computed in processing. + assert_eq!( + snapshot("home").await?.source_fingerprint, + visualci_core::image_hash::fingerprint_bytes(&shot).unwrap() + ); + + // The renderer draws the PDF and reports its fingerprint, which the blob and the snapshot take. + let claimed = app + .post("/internal/renderer/claim") + .header("authorization", RENDERER) + .json(json!({ "renderer_version": "1" })) + .await; + claimed.assert_ok(); + let job = claimed.json()["job"].clone(); + let (render_id, claim) = (job["id"].as_i64().expect("a render"), job["token"].as_str().unwrap().to_string()); + let page = png([40, 40, 40]); + let page_sha = visualci_core::sha256_hex(&page); + let uploads = app + .post(format!("/internal/renderer/renders/{render_id}/uploads")) + .header("authorization", RENDERER) + .header("x-render-token", &claim) + .json(json!({ "files": [{ "sha256": page_sha, "size": page.len(), "content_type": "image/png" }] })) + .await; + uploads.assert_ok(); + if let Some(url) = uploads.json()["upload_urls"][&page_sha].as_str() { + put(url, page.clone(), "image/png").await; + } + let drawn = "d".repeat(64); + app.post(format!("/internal/renderer/renders/{render_id}/complete")) + .header("authorization", RENDERER) + .header("x-render-token", &claim) + .json(json!({ + "pages": [{ "image": page_sha, "image_fingerprint": visualci_core::image_hash::fingerprint_bytes(&page).unwrap(), + "fingerprint": "e".repeat(64), "width": 16, "height": 16, "text": "Invoice" }], + "document_fingerprint": drawn, + })) + .await + .assert_ok(); + let invoice = snapshot("invoice").await?; + assert_eq!((invoice.state.as_str(), invoice.source_fingerprint.as_str()), ("added", drawn.as_str())); + assert_eq!(Blob::find(pdf_sha).await?.and_then(|b| b.pdf_fingerprint), Some(drawn)); + let build = Build::query().filter(Build::number.eq(1)).first().await?.expect("the build"); + assert_eq!(build.state, "completed"); + Ok(()) +}