diff --git a/Cargo.lock b/Cargo.lock index a020bf7d..d35475d5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5233,6 +5233,7 @@ version = "0.2.10" dependencies = [ "anyhow", "image", + "lopdf", "reqwest", "serde", "serde_json", diff --git a/crates/visualci-renderer/Cargo.toml b/crates/visualci-renderer/Cargo.toml index 1f3fe7ad..9d853a68 100644 --- a/crates/visualci-renderer/Cargo.toml +++ b/crates/visualci-renderer/Cargo.toml @@ -9,6 +9,7 @@ repository.workspace = true [dependencies] anyhow.workspace = true image.workspace = true +lopdf.workspace = true reqwest.workspace = true serde.workspace = true serde_json.workspace = true diff --git a/crates/visualci-renderer/src/budget.rs b/crates/visualci-renderer/src/budget.rs new file mode 100644 index 00000000..3494b3ba --- /dev/null +++ b/crates/visualci-renderer/src/budget.rs @@ -0,0 +1,148 @@ +//! A pixel budget, checked before rasterizing: a PDF can ask for a page a few metres wide, or thousands of pages, and +//! drawing that at a high DPI would hold a renderer for minutes and fill its disk. Page sizes come from each page's +//! CropBox (else MediaBox, inherited through the page tree) and UserUnit, in points (1/72 inch). + +use lopdf::{Dictionary, Document, Object}; + +/// The most pixels one page may have: about A1 at 300 DPI. +pub const MAX_PAGE_PIXELS: f64 = 110_000_000.0; +/// The most pixels a whole document may have: about 1,000 A4 pages at 150 DPI. +pub const MAX_TOTAL_PIXELS: f64 = 2_500_000_000.0; +/// The most pages a document may have. +pub const MAX_PAGES: usize = 2_000; + +/// Each page's size in points, or why it couldn't be read. +pub fn page_sizes(bytes: &[u8]) -> Result, String> { + let mut doc = Document::load_mem(bytes).map_err(|e| e.to_string())?; + if doc.is_encrypted() { + doc.decrypt("").map_err(|e| format!("encrypted: {e}"))?; + } + let ids: Vec<_> = doc.get_pages().into_values().collect(); + let mut out = Vec::with_capacity(ids.len()); + for id in ids { + let Ok(page) = doc.get_dictionary(id) else { continue }; + let b = inherited(&doc, page, b"CropBox").or_else(|| inherited(&doc, page, b"MediaBox")); + let Some(rect) = b.and_then(|o| numbers(&doc, &o)) else { continue }; + if rect.len() != 4 { + continue; + } + let unit = page.get(b"UserUnit").ok().and_then(|o| number(&doc, o)).unwrap_or(1.0).abs().max(f64::MIN_POSITIVE); + out.push(((rect[2] - rect[0]).abs() * unit, (rect[3] - rect[1]).abs() * unit)); + } + Ok(out) +} + +/// Whether drawing these pages at `dpi` stays within the budget; the error says what's too big. +pub fn check(sizes: &[(f64, f64)], dpi: u32) -> Result<(), String> { + if sizes.len() > MAX_PAGES { + return Err(format!("the PDF has {} pages; at most {MAX_PAGES} are drawn", sizes.len())); + } + let scale = f64::from(dpi) / 72.0; + let mut total = 0.0; + for (i, (w, h)) in sizes.iter().enumerate() { + let pixels = (w * scale) * (h * scale); + if pixels > MAX_PAGE_PIXELS { + return Err(format!( + "page {} is {:.0} × {:.0} points: {:.0} megapixels at {dpi} DPI, more than the {:.0} a page may have; lower \ + the project's DPI or fix the page size", + i + 1, + w, + h, + pixels / 1e6, + MAX_PAGE_PIXELS / 1e6 + )); + } + total += pixels; + } + if total > MAX_TOTAL_PIXELS { + return Err(format!( + "the PDF is {:.0} megapixels at {dpi} DPI, more than the {:.0} a document may have; lower the project's DPI or \ + split the document", + total / 1e6, + MAX_TOTAL_PIXELS / 1e6 + )); + } + Ok(()) +} + +fn inherited(doc: &Document, page: &Dictionary, key: &[u8]) -> Option { + let mut dict = page.clone(); + for _ in 0..64 { + if let Ok(value) = dict.get(key) { + return Some(value.clone()); + } + let parent = dict.get(b"Parent").ok()?.as_reference().ok()?; + dict = doc.get_dictionary(parent).ok()?.clone(); + } + None +} + +fn resolve<'a>(doc: &'a Document, object: &'a Object) -> Option<&'a Object> { + let mut object = object; + for _ in 0..32 { + match object { + Object::Reference(id) => object = doc.get_object(*id).ok()?, + other => return Some(other), + } + } + None +} + +fn number(doc: &Document, object: &Object) -> Option { + match resolve(doc, object)? { + Object::Integer(i) => Some(*i as f64), + Object::Real(r) => Some(f64::from(*r)), + _ => None, + } +} + +fn numbers(doc: &Document, object: &Object) -> Option> { + match resolve(doc, object)? { + Object::Array(items) => items.iter().map(|o| number(doc, o)).collect(), + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a4_at_a_normal_dpi_passes_and_a_huge_page_does_not() { + let a4 = (595.0, 842.0); + assert!(check(&[a4; 100], 140).is_ok()); + assert!(check(&[a4], 600).is_ok()); + // 200 inches square at 300 DPI: 3.6 gigapixels. + let e = check(&[(14_400.0, 14_400.0)], 300).unwrap_err(); + assert!(e.contains("page 1") && e.contains("megapixels"), "{e}"); + let e = check(&vec![a4; MAX_PAGES + 1], 72).unwrap_err(); + assert!(e.contains("pages"), "{e}"); + // Many ordinary pages at a high DPI: the document's budget. + let e = check(&vec![a4; 1_500], 300).unwrap_err(); + assert!(e.contains("the PDF is"), "{e}"); + } + + #[test] + fn reads_inherited_page_sizes() { + use lopdf::dictionary; + let mut doc = Document::with_version("1.5"); + let pages_id = doc.new_object_id(); + let page = doc.add_object(dictionary! { "Type" => "Page", "Parent" => pages_id }); + let big = doc.add_object(dictionary! { + "Type" => "Page", "Parent" => pages_id, "MediaBox" => vec![0.into(), 0.into(), 100.into(), 50.into()], + "UserUnit" => 2, + }); + doc.objects.insert( + pages_id, + Object::Dictionary(dictionary! { + "Type" => "Pages", "Kids" => vec![page.into(), big.into()], "Count" => 2, + "MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()], + }), + ); + let catalog = doc.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages_id }); + doc.trailer.set("Root", catalog); + let mut bytes = Vec::new(); + doc.save_to(&mut bytes).unwrap(); + assert_eq!(page_sizes(&bytes).unwrap(), vec![(595.0, 842.0), (200.0, 100.0)]); + } +} diff --git a/crates/visualci-renderer/src/main.rs b/crates/visualci-renderer/src/main.rs index 7c8145f8..e3ec7044 100644 --- a/crates/visualci-renderer/src/main.rs +++ b/crates/visualci-renderer/src/main.rs @@ -11,6 +11,7 @@ //! - `VISUALCI_HEARTBEAT_FILE`: touched after every poll, for the container's liveness probe. //! - `VISUALCI_ONCE`: process at most one render, then exit (tests). +mod budget; use std::path::{Path, PathBuf}; use std::time::Duration; @@ -222,6 +223,11 @@ async fn render(api: &Api, job: &Job) -> Result> { } tokio::fs::write(&pdf_path, &bytes).await?; + // Too many pixels for one page or the whole document: refused before an engine spends minutes drawing it. A PDF + // whose pages can't be read here is left to the engine (and its timeout). + if let Ok(sizes) = budget::page_sizes(&bytes) { + budget::check(&sizes, job.dpi).map_err(|e| anyhow!(e))?; + } let fingerprint = visualci_core::pdf::fingerprint_bytes(&bytes); let images = rasterize(&api.config, job, &pdf_path, dir.path()).await?; let texts = extract_text(&pdf_path, dir.path(), images.len()).await; diff --git a/docs/design.md b/docs/design.md index abe4bb78..0568297c 100644 --- a/docs/design.md +++ b/docs/design.md @@ -417,7 +417,9 @@ review is the publish step. Only images from the `ci` environment are published. - Blobs, renders and diffs are deduplicated globally by SHA256, as Argos does. - Customer documents are untrusted input: they're parsed and rendered only on the render node, under gVisor, with no network. The fingerprint parser runs in the same sandbox on the server (client-side hashing is for the client's - own files). + own files). Each claimed render gets its own token (its uploads and completion need it), the engines run with a + cleared environment, the download is capped as it streams, and a pixel budget is checked before drawing: at most + 110 megapixels a page, 2,500 a document and 2,000 pages at the job's DPI (`visualci-renderer`'s `budget`, sc-8726). - Its own namespace, default-deny NetworkPolicies, its own CNPG cluster and R2 bucket (the cluster's per-product rules). - Retention per plan, deletion of an organization's data on request, an audit log of approvals. - DocSpring's fixtures stay synthetic or blank templates someone has checked (spec/pdf_integration/AGENTS.md rules).