From 2c1611b34a6d5a8d9d5d54b401560d964a088986 Mon Sep 17 00:00:00 2001 From: mnovak Date: Mon, 16 Nov 2026 13:26:02 +0100 Subject: [PATCH] [pdf] Redaction: rebuild redacted pages as one image, scrub hidden data, prune; reader and AES-256 protect/unlock --- Cargo.toml | 80 +++---- crates/pdf/Cargo.toml | 19 ++ crates/pdf/src/edit.rs | 1 + crates/pdf/src/engine.rs | 46 ++++ crates/pdf/src/error.rs | 70 ++++++ crates/pdf/src/geometry.rs | 92 ++++++++ crates/pdf/src/lib.rs | 47 ++++ crates/pdf/src/pages.rs | 1 + crates/pdf/src/reader.rs | 170 ++++++++++++++ crates/pdf/src/redact.rs | 406 +++++++++++++++++++++++++++++++++ crates/pdf/src/security.rs | 51 +++++ crates/pdf/tests/common/mod.rs | 267 ++++++++++++++++++++++ crates/pdf/tests/redaction.rs | 153 +++++++++++++ docs/DEPENDENCIES.md | 174 +++++++------- 14 files changed, 1452 insertions(+), 125 deletions(-) create mode 100644 crates/pdf/Cargo.toml create mode 100644 crates/pdf/src/edit.rs create mode 100644 crates/pdf/src/engine.rs create mode 100644 crates/pdf/src/error.rs create mode 100644 crates/pdf/src/geometry.rs create mode 100644 crates/pdf/src/lib.rs create mode 100644 crates/pdf/src/pages.rs create mode 100644 crates/pdf/src/reader.rs create mode 100644 crates/pdf/src/redact.rs create mode 100644 crates/pdf/src/security.rs create mode 100644 crates/pdf/tests/common/mod.rs create mode 100644 crates/pdf/tests/redaction.rs diff --git a/Cargo.toml b/Cargo.toml index 904f6dc..7c4a332 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,39 +1,41 @@ -[workspace] -resolver = "3" -members = ["crates/raster", "crates/pdf", "crates/meta", "crates/qr", "crates/save", "crates/worker"] - -[workspace.package] -version = "0.1.0" -edition = "2024" -license = "MPL-2.0" -repository = "https://gitea.marek-novak.cz/mnovak/Pictor-public" -rust-version = "1.88" - -# Every dependency here is listed with its licence in docs/DEPENDENCIES.md before it is used. -[workspace.dependencies] -pictor-raster = { path = "crates/raster" } -pictor-pdf = { path = "crates/pdf" } -pictor-meta = { path = "crates/meta" } -pictor-qr = { path = "crates/qr" } -pictor-save = { path = "crates/save" } - -thiserror = "2" -serde = { version = "1", features = ["derive"] } -serde_json = "1" -base64 = "0.22" -image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp", "bmp", "gif", "tiff", "ico"] } -kamadak-exif = "0.6" -img-parts = "0.4" -qrcode = { version = "0.14", default-features = false, features = ["svg"] } -lopdf = { version = "0.47", default-features = false } -pdfium-render = { version = "0.9.5", default-features = false, features = ["thread_safe", "image_latest", "pdfium_latest"] } -tempfile = "3" -sha2 = "0.11" -windows = "0.62" - -# dev-only -rqrr = "0.11" -proptest = "1" - -[profile.dev.package."*"] -opt-level = 2 +[workspace] +resolver = "3" +members = ["crates/raster", "crates/pdf", "crates/meta", "crates/qr", "crates/save", "crates/worker"] + +[workspace.package] +version = "0.1.0" +edition = "2024" +license = "MPL-2.0" +repository = "https://gitea.marek-novak.cz/mnovak/Pictor-public" +rust-version = "1.88" + +# Every dependency here is listed with its licence in docs/DEPENDENCIES.md before it is used. +[workspace.dependencies] +pictor-raster = { path = "crates/raster" } +pictor-pdf = { path = "crates/pdf" } +pictor-meta = { path = "crates/meta" } +pictor-qr = { path = "crates/qr" } +pictor-save = { path = "crates/save" } + +thiserror = "2" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +base64 = "0.22" +image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp", "bmp", "gif", "tiff", "ico"] } +kamadak-exif = "0.6" +img-parts = "0.4" +qrcode = { version = "0.14", default-features = false, features = ["svg"] } +lopdf = { version = "0.47", default-features = false } +pdfium-render = { version = "0.9.5", default-features = false, features = ["thread_safe", "image_latest", "pdfium_latest"] } +tempfile = "3" +sha2 = "0.11" +getrandom = "0.4" +flate2 = "1" +windows = "0.62" + +# dev-only +rqrr = "0.11" +proptest = "1" + +[profile.dev.package."*"] +opt-level = 2 diff --git a/crates/pdf/Cargo.toml b/crates/pdf/Cargo.toml new file mode 100644 index 0000000..ee43f81 --- /dev/null +++ b/crates/pdf/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "pictor-pdf" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + +[dependencies] +thiserror.workspace = true +serde.workspace = true +image.workspace = true +lopdf.workspace = true +pdfium-render.workspace = true +pictor-meta.workspace = true +getrandom.workspace = true + +[dev-dependencies] +flate2.workspace = true diff --git a/crates/pdf/src/edit.rs b/crates/pdf/src/edit.rs new file mode 100644 index 0000000..6354e9c --- /dev/null +++ b/crates/pdf/src/edit.rs @@ -0,0 +1 @@ +//! The edit pipeline (form fill, annotations, stamps, flatten, security). diff --git a/crates/pdf/src/engine.rs b/crates/pdf/src/engine.rs new file mode 100644 index 0000000..a63468f --- /dev/null +++ b/crates/pdf/src/engine.rs @@ -0,0 +1,46 @@ +use crate::PdfError; +use pdfium_render::prelude::*; +use std::path::Path; +use std::sync::OnceLock; + +/// The one pdfium instance of the process (pdfium is not thread-safe; pdfium-render's `thread_safe` feature +/// serialises calls). Load it once with [`Engine::load`]. +pub struct Engine { + pub(crate) pdfium: Pdfium, +} + +static ENGINE: OnceLock = OnceLock::new(); +static LOAD_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +impl Engine { + /// Loads pdfium.dll from `dir` (or from the system search path when `None`). Later calls return the same engine. + pub fn load(dir: Option<&Path>) -> Result<&'static Engine, PdfError> { + if let Some(e) = ENGINE.get() { + return Ok(e); + } + let _guard = LOAD_LOCK.lock().unwrap_or_else(|p| p.into_inner()); + if let Some(e) = ENGINE.get() { + return Ok(e); + } + let bindings = match dir { + Some(d) => Pdfium::bind_to_library(Pdfium::pdfium_platform_library_name_at_path(d)), + None => Pdfium::bind_to_system_library(), + } + .map_err(|e| PdfError::EngineMissing(e.to_string()))?; + let _ = ENGINE.set(Engine { pdfium: Pdfium::new(bindings) }); + Ok(ENGINE.get().expect("just set")) + } + + pub(crate) fn open<'a>(&'a self, bytes: &'a [u8], password: Option<&str>) -> Result, PdfError> { + self.pdfium.load_pdf_from_byte_slice(bytes, password).map_err(|e| PdfError::from_pdfium_open(e, password.is_some())) + } + + pub(crate) fn new_document(&self) -> Result, PdfError> { + self.pdfium.create_new_pdf().map_err(PdfError::from_pdfium) + } +} + +/// pdfium's save, with the security handler removed (Pictor re-encrypts with lopdf when asked). +pub(crate) fn pdfium_save(doc: &PdfDocument) -> Result, PdfError> { + doc.save_to_bytes().map_err(|e| PdfError::Write(e.to_string())) +} diff --git a/crates/pdf/src/error.rs b/crates/pdf/src/error.rs new file mode 100644 index 0000000..3d65fe1 --- /dev/null +++ b/crates/pdf/src/error.rs @@ -0,0 +1,70 @@ +use pdfium_render::prelude::{PdfiumError, PdfiumInternalError}; + +/// Errors shown to the user; the messages are plain sentences. +#[derive(Debug, thiserror::Error)] +pub enum PdfError { + #[error("Pictor's PDF engine (pdfium.dll) could not be loaded: {0}")] + EngineMissing(String), + #[error("This PDF is password-protected. Enter its password to open it.")] + NeedsPassword, + #[error("That password is not right for this PDF.")] + WrongPassword, + #[error("This file is not a PDF Pictor can read: {0}")] + Damaged(String), + #[error("This PDF uses a feature Pictor does not support: {0}")] + Unsupported(String), + #[error("Page {0} does not exist in this PDF.")] + NoSuchPage(usize), + #[error("{0}")] + Invalid(String), + #[error("Pictor could not write the PDF: {0}")] + Write(String), + #[error("This PDF is too large for Pictor: {0}")] + TooLarge(String), +} + +impl PdfError { + pub(crate) fn from_pdfium(e: PdfiumError) -> PdfError { + match e { + PdfiumError::PdfiumLibraryInternalError(PdfiumInternalError::PasswordError) => PdfError::WrongPassword, + PdfiumError::PdfiumLibraryInternalError(PdfiumInternalError::FormatError) => { + PdfError::Damaged("its structure is broken beyond repair".into()) + } + PdfiumError::PdfiumLibraryInternalError(PdfiumInternalError::FileError) => { + PdfError::Damaged("the file could not be read".into()) + } + PdfiumError::PdfiumLibraryInternalError(PdfiumInternalError::SecurityError) => { + PdfError::Unsupported("its encryption method".into()) + } + PdfiumError::PdfiumLibraryInternalError(PdfiumInternalError::PageError) => { + PdfError::Damaged("a page could not be read".into()) + } + other => PdfError::Damaged(other.to_string()), + } + } + + pub(crate) fn from_pdfium_open(e: PdfiumError, had_password: bool) -> PdfError { + match PdfError::from_pdfium(e) { + PdfError::WrongPassword if !had_password => PdfError::NeedsPassword, + other => other, + } + } + + pub(crate) fn from_lopdf(e: lopdf::Error, had_password: bool) -> PdfError { + use lopdf::Error as E; + let text = e.to_string(); + match e { + E::Decryption(_) | E::InvalidPassword if had_password => PdfError::WrongPassword, + E::Decryption(_) | E::InvalidPassword => PdfError::NeedsPassword, + _ if text.to_ascii_lowercase().contains("password") => { + if had_password { + PdfError::WrongPassword + } else { + PdfError::NeedsPassword + } + } + _ if text.to_ascii_lowercase().contains("limit") => PdfError::TooLarge(text), + _ => PdfError::Damaged(text), + } + } +} diff --git a/crates/pdf/src/geometry.rs b/crates/pdf/src/geometry.rs new file mode 100644 index 0000000..11412ae --- /dev/null +++ b/crates/pdf/src/geometry.rs @@ -0,0 +1,92 @@ +//! View space ↔ PDF user space. +//! +//! View space: points from the top-left corner of the page *as displayed* — the crop box, turned by `/Rotate` +//! (clockwise). That is what the UI draws and what the user drags on. PDF user space: the page's own coordinates, +//! origin bottom-left of the media box, before rotation. +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] +pub struct ViewPoint { + pub x: f32, + pub y: f32, +} + +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] +pub struct ViewRect { + pub x: f32, + pub y: f32, + pub w: f32, + pub h: f32, +} + +impl ViewRect { + pub fn is_empty(&self) -> bool { + !(self.w > 0.0 && self.h > 0.0) || !self.x.is_finite() || !self.y.is_finite() + } +} + +/// What view space needs to know about a page. +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] +pub struct PageFrame { + /// The crop box in user space: x0, y0, x1, y1 (normalised so x0 < x1, y0 < y1). + pub crop: [f32; 4], + /// `/Rotate`, normalised to 0, 90, 180 or 270. + pub rotate: u16, +} + +impl PageFrame { + /// The displayed size in points (width, height). + pub fn view_size(&self) -> (f32, f32) { + let (w, h) = (self.crop[2] - self.crop[0], self.crop[3] - self.crop[1]); + if self.rotate % 180 == 90 { (h, w) } else { (w, h) } + } + + /// A view-space point → user space. + pub fn to_user(&self, p: ViewPoint) -> (f32, f32) { + let [x0, y0, x1, y1] = self.crop; + match self.rotate { + 90 => (x0 + p.y, y0 + p.x), + 180 => (x1 - p.x, y0 + p.y), + 270 => (x1 - p.y, y1 - p.x), + _ => (x0 + p.x, y1 - p.y), + } + } + + /// A view-space rectangle → a user-space rectangle [x0, y0, x1, y1]. + pub fn rect_to_user(&self, r: ViewRect) -> [f32; 4] { + let (ax, ay) = self.to_user(ViewPoint { x: r.x, y: r.y }); + let (bx, by) = self.to_user(ViewPoint { x: r.x + r.w, y: r.y + r.h }); + [ax.min(bx), ay.min(by), ax.max(bx), ay.max(by)] + } +} + +pub(crate) fn normalise_rotate(r: i64) -> u16 { + (((r % 360) + 360) % 360 / 90 * 90) as u16 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn corners_map_for_every_rotation() { + let crop = [10.0, 20.0, 110.0, 220.0]; // 100 × 200 + let top_left = ViewPoint { x: 0.0, y: 0.0 }; + let f = |r| PageFrame { crop, rotate: r }; + assert_eq!(f(0).to_user(top_left), (10.0, 220.0)); + assert_eq!(f(90).to_user(top_left), (10.0, 20.0)); + assert_eq!(f(180).to_user(top_left), (110.0, 20.0)); + assert_eq!(f(270).to_user(top_left), (110.0, 220.0)); + assert_eq!(f(90).view_size(), (200.0, 100.0)); + // The far corner of the view is the opposite user corner. + let (w, h) = f(90).view_size(); + assert_eq!(f(90).to_user(ViewPoint { x: w, y: h }), (110.0, 220.0)); + } + + #[test] + fn rotate_is_normalised() { + assert_eq!(normalise_rotate(-90), 270); + assert_eq!(normalise_rotate(450), 90); + assert_eq!(normalise_rotate(45), 0); + } +} diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs new file mode 100644 index 0000000..1fe854d --- /dev/null +++ b/crates/pdf/src/lib.rs @@ -0,0 +1,47 @@ +//! Pictor's PDF engine: pdfium for everything that reads or draws a page, lopdf for structure that must be written +//! exactly (annotations, stamps, the redaction rebuild, encryption). Which library does which operation, and why, +//! is recorded in the app's `docs/01_v1.md` and in [`docs/FORMATS.md`](../../docs/FORMATS.md). +//! +//! Coordinates: the UI works in **view space** — PDF points (1/72 inch) from the top-left corner of the page as it +//! is displayed (crop box, `/Rotate` applied). [`geometry`] converts view space to a page's own user space. +//! +//! Every function takes the document as bytes plus an optional password and returns new bytes: nothing here touches +//! the file system. Outside files are hostile; call these only inside `pictor-worker`. + +mod edit; +mod engine; +mod error; +pub mod geometry; +mod pages; +mod reader; +mod redact; +mod security; + +pub use edit::*; +pub use engine::Engine; +pub use error::PdfError; +pub use geometry::{ViewRect, ViewPoint}; +pub use pages::*; +pub use reader::*; +pub use redact::{RedactOptions, Redacted, Redaction, redact}; +pub use security::{is_encrypted, protect, unlock}; + +/// lopdf loading with the caps Pictor uses everywhere (a stream may decompress to at most 256 MiB). +pub(crate) fn lopdf_load(bytes: &[u8], password: Option<&str>) -> Result { + let mut opts = lopdf::LoadOptions::default(); + opts.max_decompressed_size = Some(256 << 20); + if let Some(p) = password { + opts.password = Some(p.to_owned()); + } + match lopdf::Document::load_mem_with_options(bytes, opts) { + Ok(doc) if doc.is_encrypted() => Err(PdfError::NeedsPassword), + Ok(doc) => Ok(doc), + Err(e) => Err(PdfError::from_lopdf(e, password.is_some())), + } +} + +pub(crate) fn lopdf_save(doc: &mut lopdf::Document) -> Result, PdfError> { + let mut out = Vec::new(); + doc.save_to(&mut out).map_err(|e| PdfError::Write(e.to_string()))?; + Ok(out) +} diff --git a/crates/pdf/src/pages.rs b/crates/pdf/src/pages.rs new file mode 100644 index 0000000..e63a04d --- /dev/null +++ b/crates/pdf/src/pages.rs @@ -0,0 +1 @@ +//! Page operations, merge, split, images to PDF, PDF to images (pdfium). diff --git a/crates/pdf/src/reader.rs b/crates/pdf/src/reader.rs new file mode 100644 index 0000000..5a49583 --- /dev/null +++ b/crates/pdf/src/reader.rs @@ -0,0 +1,170 @@ +//! Reading: page sizes, rendering, text, search, outline. All through pdfium (it is what Chrome and Edge use, so a +//! file Edge opens, Pictor opens). +use crate::{Engine, PdfError, ViewRect}; +use image::DynamicImage; +use pdfium_render::prelude::*; +use serde::Serialize; + +/// Rendering never makes a bitmap larger than this many pixels (about 200 MB of RGBA). +pub const MAX_RENDER_PIXELS: i64 = 50_000_000; + +#[derive(Debug, Clone, Serialize)] +pub struct DocInfo { + pub pages: Vec, + pub outline: Vec, + pub has_form: bool, + pub encrypted: bool, +} + +#[derive(Debug, Clone, Serialize)] +pub struct PageInfo { + /// Displayed size in points. + pub width: f32, + pub height: f32, + pub label: Option, +} + +#[derive(Debug, Clone, Serialize)] +pub struct OutlineItem { + pub title: String, + pub page: Option, + pub depth: u32, +} + +#[derive(Debug, Clone, Serialize)] +pub struct SearchHit { + pub page: usize, + /// The hit's boxes in view space. + pub rects: Vec, +} + +pub fn info(engine: &Engine, bytes: &[u8], password: Option<&str>) -> Result { + let doc = engine.open(bytes, password)?; + let mut pages = Vec::new(); + for page in doc.pages().iter() { + pages.push(PageInfo { width: page.width().value, height: page.height().value, label: page.label().map(Into::into) }); + } + let mut outline = Vec::new(); + fn walk(b: PdfBookmark, depth: u32, out: &mut Vec, budget: &mut u32) { + if *budget == 0 || depth > 32 { + return; + } + *budget -= 1; + let page = b.destination().and_then(|d| d.page_index().ok()).map(|i| i as usize); + out.push(OutlineItem { title: b.title().unwrap_or_default(), page, depth }); + if let Some(child) = b.first_child() { + let mut next = Some(child); + while let Some(c) = next { + next = c.next_sibling(); + walk(c, depth + 1, out, budget); + } + } + } + let mut budget = 5000; + let mut next = doc.bookmarks().root(); + while let Some(b) = next { + next = b.next_sibling(); + walk(b, 0, &mut outline, &mut budget); + } + let has_form = doc.form().is_some(); + Ok(DocInfo { pages, outline, has_form, encrypted: password.is_some() }) +} + +/// The displayed size of every page, in points. +pub fn page_sizes(engine: &Engine, bytes: &[u8], password: Option<&str>) -> Result, PdfError> { + let doc = engine.open(bytes, password)?; + Ok(doc.pages().iter().map(|p| (p.width().value, p.height().value)).collect()) +} + +pub(crate) fn render_doc_page(doc: &PdfDocument, index: usize, width_px: u32, forms: bool) -> Result { + let page = doc.pages().get(index as i32).map_err(|_| PdfError::NoSuchPage(index + 1))?; + let (w, h) = (page.width().value.max(1.0), page.height().value.max(1.0)); + let width = width_px.clamp(1, 20_000) as i64; + let height = ((width as f32) * h / w).ceil().max(1.0) as i64; + if width * height > MAX_RENDER_PIXELS { + return Err(PdfError::TooLarge(format!("page {} would render at {width} × {height} pixels", index + 1))); + } + let cfg = PdfRenderConfig::new() + .set_target_size(width as i32, height as i32) + .render_form_data(forms) + .render_annotations(true) + .set_clear_color(PdfColor::WHITE); + page.render_with_config(&cfg).and_then(|b| b.as_image()).map_err(PdfError::from_pdfium) +} + +/// Renders page `index` (0-based) `width_px` pixels wide, with annotations and form fields drawn. +pub fn render_page( + engine: &Engine, + bytes: &[u8], + password: Option<&str>, + index: usize, + width_px: u32, +) -> Result { + let doc = engine.open(bytes, password)?; + render_doc_page(&doc, index, width_px, true) +} + +/// The text of every page, in order. +pub fn extract_text(engine: &Engine, bytes: &[u8], password: Option<&str>) -> Result, PdfError> { + let doc = engine.open(bytes, password)?; + let mut out = Vec::new(); + for page in doc.pages().iter() { + out.push(page.text().map(|t| t.all()).map_err(PdfError::from_pdfium)?); + } + Ok(out) +} + +/// Case-insensitive search over every page; at most `limit` hits. +pub fn search( + engine: &Engine, + bytes: &[u8], + password: Option<&str>, + query: &str, + limit: usize, +) -> Result, PdfError> { + if query.trim().is_empty() { + return Ok(Vec::new()); + } + let doc = engine.open(bytes, password)?; + let mut hits = Vec::new(); + for (i, page) in doc.pages().iter().enumerate() { + let frame = page_frame(&page); + let text = page.text().map_err(PdfError::from_pdfium)?; + let search = text.search(query, &PdfSearchOptions::new()).map_err(PdfError::from_pdfium)?; + while let Some(segments) = search.find_next() { + let rects = segments.iter().map(|s| frame.user_to_view(s.bounds())).collect(); + hits.push(SearchHit { page: i, rects }); + if hits.len() >= limit { + return Ok(hits); + } + } + } + Ok(hits) +} + +pub(crate) fn page_frame(page: &PdfPage) -> crate::geometry::PageFrame { + let crop = page.boundaries().crop().or_else(|_| page.boundaries().media()).map(|b| b.bounds).unwrap_or(PdfRect::ZERO); + let rotate = match page.rotation() { + Ok(PdfPageRenderRotation::Degrees90) => 90, + Ok(PdfPageRenderRotation::Degrees180) => 180, + Ok(PdfPageRenderRotation::Degrees270) => 270, + _ => 0, + }; + let c = [crop.left().value, crop.bottom().value, crop.right().value, crop.top().value]; + crate::geometry::PageFrame { crop: [c[0].min(c[2]), c[1].min(c[3]), c[0].max(c[2]), c[1].max(c[3])], rotate } +} + +impl crate::geometry::PageFrame { + /// A user-space rectangle → view space. + pub(crate) fn user_to_view(&self, r: PdfRect) -> ViewRect { + let [x0, y0, x1, y1] = self.crop; + let (l, b, rt, t) = (r.left().value, r.bottom().value, r.right().value, r.top().value); + let (vx0, vy0, vx1, vy1) = match self.rotate { + 90 => (b - y0, l - x0, t - y0, rt - x0), + 180 => (x1 - rt, b - y0, x1 - l, t - y0), + 270 => (y1 - t, x1 - rt, y1 - b, x1 - l), + _ => (l - x0, y1 - t, rt - x0, y1 - b), + }; + ViewRect { x: vx0.min(vx1), y: vy0.min(vy1), w: (vx1 - vx0).abs(), h: (vy1 - vy0).abs() } + } +} diff --git a/crates/pdf/src/redact.rs b/crates/pdf/src/redact.rs new file mode 100644 index 0000000..02045c7 --- /dev/null +++ b/crates/pdf/src/redact.rs @@ -0,0 +1,406 @@ +//! True redaction. Each redacted page is rendered by pdfium, the boxes are painted black into the pixels, and the +//! page is rebuilt by lopdf as that one image: no text, image, vector, annotation or form content of the old page +//! survives. The other pages are not touched (their objects are written back byte for byte). The document's +//! metadata and the places hidden text can live (XMP, /Info, the struct tree's ActualText, bookmarks, +//! attachments, JavaScript) are removed, every unreferenced object is pruned, and the file is written fresh (no +//! incremental history). +//! +//! The brief's alternative, rewriting the page's content stream to cut out only what lies under the box, is not +//! used: it needs a full content-stream interpreter (fonts, glyph positions, form XObjects, inline images, +//! clipping, shadings, Type 3 fonts) and any mistake leaves text behind. The cost of the chosen method: the text of +//! a redacted page is no longer selectable or searchable. docs/FORMATS.md records this. +use crate::{Engine, PdfError, ViewRect, lopdf_load, lopdf_save, reader::render_doc_page}; +use lopdf::{Dictionary, Document, Object, ObjectId, Stream, dictionary}; +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeSet, HashSet}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Redaction { + /// 0-based page index. + pub page: usize, + /// Boxes in view space (points, top-left origin of the displayed page). + pub rects: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct RedactOptions { + /// Resolution of the rebuilt pages. + pub dpi: u32, + pub jpeg_quality: u8, +} + +impl Default for RedactOptions { + fn default() -> Self { + RedactOptions { dpi: 200, jpeg_quality: 90 } + } +} + +#[derive(Debug, Clone)] +pub struct Redacted { + /// The new PDF, not encrypted. + pub bytes: Vec, + /// Plain sentences for the user (for example, hidden layers left on pages that were not redacted). + pub warnings: Vec, +} + +const IMAGE_NAME: &[u8] = b"PictorRedacted"; + +pub fn redact( + engine: &Engine, + bytes: &[u8], + password: Option<&str>, + redactions: &[Redaction], + opts: &RedactOptions, +) -> Result { + if redactions.is_empty() || redactions.iter().any(|r| r.rects.is_empty() || r.rects.iter().any(ViewRect::is_empty)) { + return Err(PdfError::Invalid("Draw at least one box to redact.".into())); + } + // 1. Render every redacted page with pdfium (annotations and form fields included) and burn the boxes in. + let pdfium_doc = engine.open(bytes, password)?; + let page_count = pdfium_doc.pages().len() as usize; + let mut images: Vec<(usize, Vec, u32, u32, f32, f32)> = Vec::new(); + let mut seen = BTreeSet::new(); + for r in redactions { + if r.page >= page_count { + return Err(PdfError::NoSuchPage(r.page + 1)); + } + if !seen.insert(r.page) { + continue; + } + let rects: Vec = redactions.iter().filter(|x| x.page == r.page).flat_map(|x| x.rects.clone()).collect(); + let page = pdfium_doc.pages().get(r.page as i32).map_err(PdfError::from_pdfium)?; + let (vw, vh) = (page.width().value, page.height().value); + drop(page); + let mut dpi = opts.dpi.clamp(72, 600) as f32; + while (vw * dpi / 72.0) * (vh * dpi / 72.0) > crate::reader::MAX_RENDER_PIXELS as f32 / 2.0 && dpi > 36.0 { + dpi *= 0.8; + } + let px_w = (vw * dpi / 72.0).round().max(1.0) as u32; + let mut img = render_doc_page(&pdfium_doc, r.page, px_w, true)?.to_rgb8(); + let scale = img.width() as f32 / vw; + for rect in &rects { + let x0 = ((rect.x * scale).floor() as i64 - 1).clamp(0, img.width() as i64) as u32; + let y0 = ((rect.y * scale).floor() as i64 - 1).clamp(0, img.height() as i64) as u32; + let x1 = (((rect.x + rect.w) * scale).ceil() as i64 + 1).clamp(0, img.width() as i64) as u32; + let y1 = (((rect.y + rect.h) * scale).ceil() as i64 + 1).clamp(0, img.height() as i64) as u32; + for y in y0..y1 { + for x in x0..x1 { + img.put_pixel(x, y, image::Rgb([0, 0, 0])); + } + } + } + let mut jpeg = Vec::new(); + image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, opts.jpeg_quality.clamp(50, 100)) + .encode_image(&img) + .map_err(|e| PdfError::Write(e.to_string()))?; + images.push((r.page, jpeg, img.width(), img.height(), vw, vh)); + } + drop(pdfium_doc); + + // 2. Rebuild those pages with lopdf. + let mut doc = lopdf_load(bytes, password)?; + let pages: Vec = doc.get_pages().values().copied().collect(); + if pages.len() != page_count { + return Err(PdfError::Damaged(format!( + "its page tree is inconsistent ({} pages by one reading, {} by another); Pictor will not redact it", + page_count, + pages.len() + ))); + } + let mut removed_annots: HashSet = HashSet::new(); + let redacted_pages: HashSet = images.iter().map(|i| pages[i.0]).collect(); + for (index, jpeg, pw, ph, vw, vh) in images { + let page_id = pages[index]; + let old = doc.get_dictionary(page_id).map_err(|e| PdfError::Damaged(e.to_string()))?.clone(); + if let Ok(annots) = old.get(b"Annots") { + let list = match annots { + Object::Reference(id) => doc.get_object(*id).and_then(Object::as_array).cloned().unwrap_or_default(), + Object::Array(a) => a.clone(), + _ => Vec::new(), + }; + for a in list { + if let Object::Reference(id) = a { + removed_annots.insert(id); + if let Ok(Object::Dictionary(d)) = doc.get_object(id) + && let Ok(Object::Reference(popup)) = d.get(b"Popup") + { + removed_annots.insert(*popup); + } + } + } + } + let mut image = Stream::new( + dictionary! { + "Type" => "XObject", "Subtype" => "Image", "Width" => pw as i64, "Height" => ph as i64, + "ColorSpace" => "DeviceRGB", "BitsPerComponent" => 8, "Filter" => "DCTDecode", + }, + jpeg, + ); + image.allows_compression = false; + let image_id = doc.add_object(image); + let content = format!("q {vw:.4} 0 0 {vh:.4} 0 0 cm /PictorRedacted Do Q").into_bytes(); + let content_id = doc.add_object(Stream::new(dictionary! {}, content)); + let bbox = vec![0.into(), 0.into(), Object::Real(vw), Object::Real(vh)]; + let mut fresh = dictionary! { + "Type" => "Page", + "MediaBox" => bbox.clone(), + "CropBox" => bbox, + "Rotate" => 0, + "Resources" => dictionary! { "XObject" => Dictionary::from_iter([(IMAGE_NAME.to_vec(), Object::Reference(image_id))]) }, + "Contents" => content_id, + }; + if let Ok(parent) = old.get(b"Parent") { + fresh.set("Parent", parent.clone()); + } + doc.objects.insert(page_id, Object::Dictionary(fresh)); + } + // The annotations of redacted pages go, even if something else still points at them. + for id in &removed_annots { + doc.objects.remove(id); + } + + // Resources inherited from a Pages node would keep the redacted page's old fonts and images alive: give each + // remaining page that relied on them its own copy, then remove them from the Pages nodes. + push_down_resources(&mut doc, &pages, &redacted_pages); + + // 3. The form: fields whose widgets were all on redacted pages go. + let mut warnings = Vec::new(); + prune_form(&mut doc, &removed_annots); + + // 4. Document-level hiding places. + scrub_document(&mut doc, &redacted_pages, &mut warnings); + + // 5. Drop everything no longer referenced and write a fresh file. + doc.prune_objects(); + let out = lopdf_save(&mut doc)?; + Ok(Redacted { bytes: out, warnings }) +} + +fn push_down_resources(doc: &mut Document, pages: &[ObjectId], redacted: &HashSet) { + let mut nodes = HashSet::new(); + for &page in pages { + // The nearest ancestor's /Resources, and every Pages node on the way up. + let mut inherited = None; + let mut current = doc.get_dictionary(page).ok().and_then(|d| d.get(b"Parent").ok()).and_then(|p| p.as_reference().ok()); + let mut depth = 0; + while let Some(id) = current { + if depth > 64 || !nodes.insert(id) && inherited.is_some() { + break; + } + depth += 1; + let Ok(d) = doc.get_dictionary(id) else { break }; + if inherited.is_none() + && let Ok(r) = d.get(b"Resources") + { + inherited = Some(r.clone()); + } + current = d.get(b"Parent").ok().and_then(|p| p.as_reference().ok()); + } + if redacted.contains(&page) { + continue; + } + if let (Some(r), Ok(d)) = (inherited, doc.get_dictionary_mut(page)) + && !d.has(b"Resources") + { + d.set("Resources", r); + } + } + for id in nodes { + if let Ok(d) = doc.get_dictionary_mut(id) { + d.remove(b"Resources"); + } + } +} + +fn prune_form(doc: &mut Document, removed: &HashSet) { + let Ok(catalog) = doc.catalog() else { return }; + let acroform = match catalog.get(b"AcroForm") { + Ok(Object::Reference(id)) => Some(*id), + _ => None, + }; + let fields: Vec = { + let form = match acroform { + Some(id) => doc.get_dictionary(id).ok(), + None => catalog.get(b"AcroForm").and_then(Object::as_dict).ok(), + }; + match form.and_then(|f| f.get(b"Fields").ok()) { + Some(Object::Array(a)) => a.clone(), + Some(Object::Reference(r)) => doc.get_object(*r).and_then(Object::as_array).cloned().unwrap_or_default(), + _ => Vec::new(), + } + }; + fn keep(doc: &mut Document, field: &Object, removed: &HashSet, depth: u32) -> bool { + let Object::Reference(id) = field else { return true }; + if removed.contains(id) { + return false; + } + if depth > 32 { + return true; + } + let kids = match doc.get_dictionary(*id).ok().and_then(|d| d.get(b"Kids").ok()) { + Some(Object::Array(a)) => a.clone(), + _ => return true, + }; + if kids.is_empty() { + return true; + } + let kept: Vec = kids.into_iter().filter(|k| keep(doc, k, removed, depth + 1)).collect(); + if kept.is_empty() { + return false; + } + if let Ok(d) = doc.get_dictionary_mut(*id) { + d.set("Kids", kept); + } + true + } + let kept: Vec = fields.iter().filter(|f| keep(doc, f, removed, 0)).cloned().collect(); + let changed = kept.len() != fields.len(); + let catalog_id = match doc.trailer.get(b"Root") { + Ok(Object::Reference(id)) => *id, + _ => return, + }; + if kept.is_empty() { + if let Ok(c) = doc.get_dictionary_mut(catalog_id) { + c.remove(b"AcroForm"); + } + return; + } + if changed { + let target = match acroform { + Some(id) => doc.get_dictionary_mut(id).ok(), + None => doc.get_dictionary_mut(catalog_id).ok().and_then(|c| c.get_mut(b"AcroForm").ok()).and_then(|o| o.as_dict_mut().ok()), + }; + if let Some(f) = target { + f.set("Fields", kept); + f.remove(b"CO"); + } + } +} + +/// Removes the document-level places where text can hide. Shared with [`crate::edit`]'s "remove hidden data". +pub(crate) fn scrub_document(doc: &mut Document, redacted_pages: &HashSet, warnings: &mut Vec) { + doc.trailer.remove(b"Info"); + let catalog_id = match doc.trailer.get(b"Root") { + Ok(Object::Reference(id)) => *id, + _ => return, + }; + // Hidden layers: drop the layer definitions only if no remaining page still uses one (else those pages would + // suddenly show their hidden content). + let pages: Vec = doc.get_pages().values().copied().collect(); + let mut oc_pages = Vec::new(); + for (i, p) in pages.iter().enumerate() { + if !redacted_pages.contains(p) && uses_optional_content(doc, *p) { + oc_pages.push(i + 1); + } + } + if let Ok(catalog) = doc.get_dictionary_mut(catalog_id) { + for key in [ + &b"Metadata"[..], + b"StructTreeRoot", + b"MarkInfo", + b"Outlines", + b"PieceInfo", + b"Threads", + b"AA", + b"Collection", + b"AF", + b"SpiderInfo", + b"Perms", + b"Legal", + ] { + catalog.remove(key); + } + if matches!(catalog.get(b"PageMode"), Ok(Object::Name(n)) if n == b"UseOutlines") { + catalog.remove(b"PageMode"); + } + if !matches!(catalog.get(b"OpenAction"), Ok(Object::Array(_))) { + catalog.remove(b"OpenAction"); + } + if oc_pages.is_empty() { + catalog.remove(b"OCProperties"); + } + } + if !oc_pages.is_empty() { + warnings.push(format!( + "Pages {} have hidden layers, which were left as they are. Redact those pages too to remove them.", + oc_pages.iter().map(|p| p.to_string()).collect::>().join(", ") + )); + } + // Names: attachments and document JavaScript go; destinations stay. + let names = match doc.get_dictionary(catalog_id).ok().and_then(|c| c.get(b"Names").ok()) { + Some(Object::Reference(id)) => Some(*id), + _ => None, + }; + let strip_names = |d: &mut Dictionary| { + d.remove(b"EmbeddedFiles"); + d.remove(b"JavaScript"); + }; + match names { + Some(id) => { + if let Ok(d) = doc.get_dictionary_mut(id) { + strip_names(d); + } + } + None => { + if let Ok(c) = doc.get_dictionary_mut(catalog_id) + && let Ok(Object::Dictionary(d)) = c.get_mut(b"Names") + { + strip_names(d); + } + } + } + // Every /Metadata and /PieceInfo on every object. + for o in doc.objects.values_mut() { + let d = match o { + Object::Dictionary(d) => d, + Object::Stream(s) => &mut s.dict, + _ => continue, + }; + d.remove(b"Metadata"); + d.remove(b"PieceInfo"); + } +} + +/// Whether a page (its resources, XObjects and annotations, followed by reference) uses optional content. +fn uses_optional_content(doc: &Document, page: ObjectId) -> bool { + let mut stack = vec![Object::Reference(page)]; + let mut seen = HashSet::new(); + let mut budget = 20_000u32; + while let Some(o) = stack.pop() { + if budget == 0 { + return true; // too deep to tell: be conservative and keep the layers + } + budget -= 1; + let o = match o { + Object::Reference(id) => { + if !seen.insert(id) { + continue; + } + match doc.get_object(id) { + Ok(o) => o.clone(), + Err(_) => continue, + } + } + o => o, + }; + let dict = match &o { + Object::Dictionary(d) => d, + Object::Stream(s) => &s.dict, + Object::Array(a) => { + stack.extend(a.iter().cloned()); + continue; + } + _ => continue, + }; + if dict.has(b"OC") || dict.has_type(b"OCG") || dict.has_type(b"OCMD") { + return true; + } + for (k, v) in dict.iter() { + if k == b"Parent" || k == b"P" { + continue; + } + stack.push(v.clone()); + } + } + false +} diff --git a/crates/pdf/src/security.rs b/crates/pdf/src/security.rs new file mode 100644 index 0000000..ca76a01 --- /dev/null +++ b/crates/pdf/src/security.rs @@ -0,0 +1,51 @@ +//! Password on and off. pdfium cannot write encryption, so lopdf does both: AES-256 (PDF 2.0, revision 6) to +//! protect, and a decrypting load plus a plain save to unlock. +use crate::{PdfError, lopdf_load, lopdf_save}; +use lopdf::encryption::crypt_filters::{Aes256CryptFilter, CryptFilter}; +use lopdf::{EncryptionState, EncryptionVersion, Permissions}; +use std::collections::BTreeMap; +use std::sync::Arc; + +/// Whether opening the document needs a password. +pub fn is_encrypted(bytes: &[u8]) -> bool { + matches!(lopdf_load(bytes, None), Err(PdfError::NeedsPassword)) +} + +/// Protects a document with `user_password` (needed to open it). `owner_password` defaults to the same password. +/// `current_password` opens an already protected document first. The result uses AES-256 and allows everything to +/// whoever opens it (Pictor does not set permission restrictions: they are not a security boundary). +pub fn protect( + bytes: &[u8], + current_password: Option<&str>, + user_password: &str, + owner_password: Option<&str>, +) -> Result, PdfError> { + if user_password.is_empty() { + return Err(PdfError::Invalid("Choose a password.".into())); + } + let mut doc = lopdf_load(bytes, current_password)?; + let mut key = [0u8; 32]; + getrandom::fill(&mut key).map_err(|e| PdfError::Write(format!("no random numbers from Windows: {e}")))?; + let filter: Arc = Arc::new(Aes256CryptFilter); + let state = EncryptionState::try_from(EncryptionVersion::V5 { + encrypt_metadata: true, + crypt_filters: BTreeMap::from([(b"StdCF".to_vec(), filter)]), + file_encryption_key: &key, + stream_filter: b"StdCF".to_vec(), + string_filter: b"StdCF".to_vec(), + owner_password: owner_password.filter(|p| !p.is_empty()).unwrap_or(user_password), + user_password, + permissions: Permissions::all(), + }) + .map_err(|e| PdfError::Write(e.to_string()))?; + doc.encrypt(&state).map_err(|e| PdfError::Write(e.to_string()))?; + key.fill(0); + lopdf_save(&mut doc) +} + +/// Removes the password from a document (the password must be right). +pub fn unlock(bytes: &[u8], password: &str) -> Result, PdfError> { + let mut doc = lopdf_load(bytes, Some(password))?; + doc.trailer.remove(b"Encrypt"); + lopdf_save(&mut doc) +} diff --git a/crates/pdf/tests/common/mod.rs b/crates/pdf/tests/common/mod.rs new file mode 100644 index 0000000..4638108 --- /dev/null +++ b/crates/pdf/tests/common/mod.rs @@ -0,0 +1,267 @@ +//! Fixtures built in code (nothing in git) and helpers shared by the pdf tests. +#![allow(dead_code)] +use lopdf::{Document, Object, ObjectId, Stream, StringFormat, dictionary}; +use std::path::PathBuf; + +pub fn engine() -> &'static pictor_pdf::Engine { + let dir = std::env::var_os("PDFIUM_DYNAMIC_LIB_PATH") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../third_party/pdfium/bin")); + pictor_pdf::Engine::load(Some(&dir)).expect("pdfium: run scripts/fetch-pdfium.ps1 first") +} + +/// Every string that sits under the redaction box (or in a hidden place of the document) in [`secret_pdf`]. +pub const SECRETS: &[&str] = &[ + "TOP-SECRET-ALPHA", + "HIDDEN-LAYER-SECRET", + "ANNOT-SECRET", + "FORM-SECRET", + "META-SECRET-TITLE", + "META-SECRET-AUTHOR", + "XMP-SECRET", + "OUTLINE-SECRET", + "STRUCT-SECRET", + "ATTACH-SECRET", + "IMAGE-SECRET", + "123.456 654.321", +]; + +/// The redaction box over page 1 in view space (points, top-left origin): it covers everything secret on page 1 +/// (y 590..760 in PDF space) and leaves "PUBLIC-LINE" (y 300) outside. +pub fn secret_box() -> pictor_pdf::ViewRect { + pictor_pdf::ViewRect { x: 50.0, y: 30.0, w: 500.0, h: 180.0 } +} + +pub const PAGE_TWO_CONTENT: &[u8] = b"BT /F2 14 Tf 72 720 Td (PAGE-TWO-KEEP) Tj ET\n"; + +fn s(text: &str) -> Object { + Object::String(text.as_bytes().to_vec(), StringFormat::Literal) +} + +pub struct Options { + pub compress: bool, + /// /Rotate on page 1. + pub rotate: i64, + /// Put Resources and Rotate on the Pages node (inherited) instead of page 1. + pub inherited: bool, +} + +impl Default for Options { + fn default() -> Self { + Options { compress: false, rotate: 0, inherited: false } + } +} + +/// Two US-Letter pages. Page 1 holds text, an image, a vector shape, a hidden layer, a note, a form field, all in +/// the box; the document holds Info, XMP, an outline, a struct tree and an attachment with secret strings. +/// Page 2 holds "PAGE-TWO-KEEP" and must come out byte-equal. +pub fn secret_pdf(opts: &Options) -> Vec { + let mut doc = Document::with_version("1.7"); + let pages_id = doc.new_object_id(); + let f1 = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica"}); + let f2 = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Times-Roman"}); + let mut pixels = Vec::new(); + while pixels.len() < 8 * 8 * 3 { + pixels.extend_from_slice(b"IMAGE-SECRET-PIXEL-DATA-"); + } + pixels.truncate(8 * 8 * 3); + let mut im = Stream::new( + dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => 8, "Height" => 8, + "ColorSpace" => "DeviceRGB", "BitsPerComponent" => 8}, + pixels, + ); + im.allows_compression = false; + let im1 = doc.add_object(im); + let oc1 = doc.add_object(dictionary! {"Type" => "OCG", "Name" => s("Hidden notes")}); + + let content1 = b"BT /F1 18 Tf 72 720 Td (TOP-SECRET-ALPHA) Tj ET\n\ +q 1 0 0 rg 123.456 654.321 m 300.5 650.25 l 300 600 l h f Q\n\ +q 100 0 0 50 72 610 cm /Im1 Do Q\n\ +/OC /oc1 BDC BT /F1 12 Tf 72 690 Td (HIDDEN-LAYER-SECRET) Tj ET EMC\n\ +BT /F1 12 Tf 72 300 Td (PUBLIC-LINE) Tj ET\n" + .to_vec(); + let c1 = doc.add_object(Stream::new(dictionary! {}, content1)); + let c2 = doc.add_object(Stream::new(dictionary! {}, PAGE_TWO_CONTENT.to_vec())); + + let helv = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica", + "Encoding" => "WinAnsiEncoding"}); + let field_ap = doc.add_object(Stream::new( + dictionary! {"Type" => "XObject", "Subtype" => "Form", "BBox" => vec![0.into(), 0.into(), 200.into(), 20.into()], + "Resources" => dictionary! {"Font" => dictionary! {"Helv" => helv}}}, + b"/Tx BMC BT /Helv 10 Tf 0 g 2 6 Td (FORM-SECRET) Tj ET EMC".to_vec(), + )); + let page1_id = doc.new_object_id(); + let field = doc.add_object(dictionary! { + "Type" => "Annot", "Subtype" => "Widget", "FT" => "Tx", "T" => s("Account"), "V" => s("FORM-SECRET"), + "DA" => s("/Helv 10 Tf 0 g"), "F" => 4, "P" => page1_id, + "Rect" => vec![300.into(), 700.into(), 500.into(), 720.into()], + "AP" => dictionary! {"N" => field_ap}, + }); + let note = doc.add_object(dictionary! { + "Type" => "Annot", "Subtype" => "Text", "Rect" => vec![80.into(), 700.into(), 100.into(), 720.into()], + "Contents" => s("ANNOT-SECRET"), "F" => 4, + }); + + let resources1 = dictionary! { + "Font" => dictionary! {"F1" => f1}, + "XObject" => dictionary! {"Im1" => im1}, + "Properties" => dictionary! {"oc1" => oc1}, + }; + let mut page1 = dictionary! { + "Type" => "Page", "Parent" => pages_id, "Contents" => c1, + "Annots" => vec![note.into(), field.into()], + "StructParents" => 0, + }; + if !opts.inherited { + page1.set("Resources", resources1.clone()); + if opts.rotate != 0 { + page1.set("Rotate", opts.rotate); + } + } + doc.objects.insert(page1_id, Object::Dictionary(page1)); + let page2_id = doc.add_object(dictionary! { + "Type" => "Page", "Parent" => pages_id, "Contents" => c2, + "Resources" => dictionary! {"Font" => dictionary! {"F2" => f2}}, + }); + let mut pages = dictionary! { + "Type" => "Pages", "Kids" => vec![page1_id.into(), page2_id.into()], "Count" => 2, + "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()], + }; + if opts.inherited { + pages.set("Resources", resources1); + if opts.rotate != 0 { + pages.set("Rotate", opts.rotate); + } + // Page 2 has its own Resources and must not inherit the rotation. + if let Ok(Object::Dictionary(p2)) = doc.get_object_mut(page2_id) { + p2.set("Rotate", 0); + } + } + doc.objects.insert(pages_id, Object::Dictionary(pages)); + + let xmp = doc.add_object(Stream::new( + dictionary! {"Type" => "Metadata", "Subtype" => "XML"}, + b"\ +XMP-SECRET\ +" + .to_vec(), + )); + let outlines_id = doc.new_object_id(); + let item = doc.add_object(dictionary! { + "Title" => s("OUTLINE-SECRET"), "Parent" => outlines_id, + "Dest" => vec![page1_id.into(), "Fit".into()], + }); + doc.objects.insert( + outlines_id, + Object::Dictionary(dictionary! {"Type" => "Outlines", "First" => item, "Last" => item, "Count" => 1}), + ); + let struct_root_id = doc.new_object_id(); + let elem = doc.add_object(dictionary! { + "Type" => "StructElem", "S" => "P", "P" => struct_root_id, "Pg" => page1_id, + "ActualText" => s("STRUCT-SECRET"), "K" => 0, + }); + doc.objects.insert( + struct_root_id, + Object::Dictionary(dictionary! {"Type" => "StructTreeRoot", "K" => vec![elem.into()]}), + ); + let attach = doc.add_object(Stream::new(dictionary! {"Type" => "EmbeddedFile"}, b"ATTACH-SECRET inside".to_vec())); + let filespec = doc.add_object(dictionary! { + "Type" => "Filespec", "F" => s("notes.txt"), "EF" => dictionary! {"F" => attach}, + }); + let catalog = doc.add_object(dictionary! { + "Type" => "Catalog", "Pages" => pages_id, "Metadata" => xmp, "Outlines" => outlines_id, + "PageMode" => "UseOutlines", + "StructTreeRoot" => struct_root_id, "MarkInfo" => dictionary! {"Marked" => true}, + "OCProperties" => dictionary! { + "OCGs" => vec![oc1.into()], + "D" => dictionary! {"OFF" => vec![oc1.into()], "Order" => vec![oc1.into()]}, + }, + "AcroForm" => dictionary! {"Fields" => vec![field.into()], "DA" => s("/Helv 10 Tf 0 g"), + "DR" => dictionary! {"Font" => dictionary! {"Helv" => helv}}}, + "Names" => dictionary! {"EmbeddedFiles" => dictionary! {"Names" => vec![s("notes.txt"), filespec.into()]}}, + }); + let info = doc.add_object(dictionary! { + "Title" => s("META-SECRET-TITLE"), "Author" => s("META-SECRET-AUTHOR"), "Producer" => s("fixture"), + }); + doc.trailer.set("Root", catalog); + doc.trailer.set("Info", info); + if opts.compress { + doc.compress(); + } + let mut out = Vec::new(); + doc.save_to(&mut out).unwrap(); + out +} + +/// A simple n-page document; page i says "Page i+1" (for page operations, merge and split). +pub fn numbered_pdf(n: usize, label: &str) -> Vec { + let mut doc = Document::with_version("1.7"); + let pages_id = doc.new_object_id(); + let font = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica"}); + let mut kids = Vec::new(); + for i in 0..n { + let content = format!("BT /F1 24 Tf 72 700 Td ({label} page {}) Tj ET", i + 1).into_bytes(); + let c = doc.add_object(Stream::new(dictionary! {}, content)); + let p = doc.add_object(dictionary! { + "Type" => "Page", "Parent" => pages_id, "Contents" => c, + "Resources" => dictionary! {"Font" => dictionary! {"F1" => font}}, + }); + kids.push(Object::Reference(p)); + } + doc.objects.insert( + pages_id, + Object::Dictionary(dictionary! {"Type" => "Pages", "Kids" => kids, "Count" => n as i64, + "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 out = Vec::new(); + doc.save_to(&mut out).unwrap(); + out +} + +/// Every byte string an "object scan" can see: string objects, names, and stream contents both raw and decompressed. +pub fn scan_objects(bytes: &[u8]) -> Vec> { + let doc = Document::load_mem(bytes).expect("lopdf reloads the output"); + let mut found = Vec::new(); + fn walk(o: &Object, found: &mut Vec>) { + match o { + Object::String(v, _) | Object::Name(v) => found.push(v.clone()), + Object::Array(a) => a.iter().for_each(|x| walk(x, found)), + Object::Dictionary(d) => d.iter().for_each(|(k, v)| { + found.push(k.clone()); + walk(v, found) + }), + Object::Stream(st) => { + st.dict.iter().for_each(|(k, v)| { + found.push(k.clone()); + walk(v, found) + }); + found.push(st.content.clone()); + if let Ok(d) = st.decompressed_content() { + found.push(d); + } + } + _ => {} + } + } + for o in doc.objects.values() { + walk(o, &mut found); + } + walk(&Object::Dictionary(doc.trailer.clone()), &mut found); + found +} + +pub fn contains(hay: &[u8], needle: &str) -> bool { + hay.windows(needle.len()).any(|w| w == needle.as_bytes()) +} + +/// The page dictionaries of a document, in order. +pub fn page_ids(doc: &Document) -> Vec { + doc.get_pages().values().copied().collect() +} + +/// A page's content, decompressed and concatenated. +pub fn page_content(doc: &Document, page: ObjectId) -> Vec { + doc.get_page_content(page) +} diff --git a/crates/pdf/tests/redaction.rs b/crates/pdf/tests/redaction.rs new file mode 100644 index 0000000..2ef49df --- /dev/null +++ b/crates/pdf/tests/redaction.rs @@ -0,0 +1,153 @@ +//! Mandatory test 1 (blocker): true redaction. After redacting the box on page 1, neither pdfium's text +//! extraction, a lopdf object scan (strings, names, raw and decompressed streams) nor a raw byte grep finds any +//! redacted string, the document's metadata and hidden parts are gone, and page 2 is byte-equal in content. +mod common; +use common::*; +use lopdf::Document; +use pictor_pdf::{Redaction, ViewRect}; + +fn redact(input: &[u8], rects: Vec) -> pictor_pdf::Redacted { + pictor_pdf::redact(engine(), input, None, &[Redaction { page: 0, rects }], &Default::default()) + .expect("redaction succeeds") +} + +fn assert_no_secrets(output: &[u8]) { + // 1. pdfium text extraction, every page. + let text = pictor_pdf::extract_text(engine(), output, None).expect("pdfium opens the output"); + let all: String = text.concat(); + for secret in SECRETS { + assert!(!all.contains(secret), "pdfium text extraction still finds {secret:?}"); + } + assert!(all.contains("PAGE-TWO-KEEP"), "page 2 lost its text: {all:?}"); + // 2. lopdf object scan. + for blob in scan_objects(output) { + for secret in SECRETS { + assert!(!contains(&blob, secret), "lopdf object scan still finds {secret:?}"); + } + } + // 3. Raw byte grep of the whole file. + for secret in SECRETS { + assert!(!contains(output, secret), "a raw byte grep still finds {secret:?}"); + } +} + +fn assert_page_two_unchanged(input: &[u8], output: &[u8]) { + let a = Document::load_mem(input).unwrap(); + let b = Document::load_mem(output).unwrap(); + let (pa, pb) = (page_ids(&a)[1], page_ids(&b)[1]); + assert_eq!(page_content(&a, pa), page_content(&b, pb), "page 2's content changed"); + let font = |d: &Document, p| { + let fonts = d.get_page_fonts(p).unwrap(); + fonts.iter().map(|(k, v)| (k.clone(), format!("{:?}", v))).collect::>() + }; + assert_eq!(font(&a, pa), font(&b, pb), "page 2's fonts changed"); + // The raw stream bytes too (lopdf writes untouched streams as they were). + let raw = |d: &Document, p| -> Vec> { + d.get_page_contents(p).iter().map(|id| d.get_object(*id).unwrap().as_stream().unwrap().content.clone()).collect() + }; + assert_eq!(raw(&a, pa), raw(&b, pb), "page 2's raw content stream bytes changed"); +} + +fn assert_hidden_parts_gone(output: &[u8]) { + let doc = Document::load_mem(output).unwrap(); + assert!(doc.trailer.get(b"Info").is_err(), "/Info survived"); + let catalog = doc.catalog().unwrap(); + for key in ["Metadata", "OCProperties", "StructTreeRoot", "Outlines", "AcroForm"] { + assert!(catalog.get(key.as_bytes()).is_err(), "catalog /{key} survived"); + } + for o in doc.objects.values() { + let dict = match o { + lopdf::Object::Dictionary(d) => d, + lopdf::Object::Stream(s) => &s.dict, + _ => continue, + }; + assert!(dict.get(b"Metadata").is_err(), "a /Metadata entry survived"); + assert!(!dict.has_type(b"OCG"), "an optional content group survived"); + assert!(!dict.has_type(b"EmbeddedFile"), "an attachment survived"); + } +} + +fn check(opts: Options, page1_size: (f32, f32)) { + let input = secret_pdf(&opts); + // The fixture really contains every secret before redaction (else the test proves nothing). + let before: Vec> = scan_objects(&input); + for secret in SECRETS { + assert!(before.iter().any(|b| contains(b, secret)), "fixture lacks {secret:?}"); + } + let rect = match opts.rotate { + 0 => secret_box(), + // For a page shown rotated, the same content sits elsewhere in view space; redact the whole page then. + _ => ViewRect { x: 0.0, y: 0.0, w: page1_size.0, h: page1_size.1 }, + }; + let out = redact(&input, vec![rect]); + assert_no_secrets(&out.bytes); + assert_page_two_unchanged(&input, &out.bytes); + assert_hidden_parts_gone(&out.bytes); + let sizes = pictor_pdf::page_sizes(engine(), &out.bytes, None).unwrap(); + assert_eq!(sizes.len(), 2); + assert!((sizes[0].0 - page1_size.0).abs() < 0.5 && (sizes[0].1 - page1_size.1).abs() < 0.5, "{sizes:?}"); +} + +#[test] +fn text_image_vector_hidden_layer_and_metadata_are_gone() { + check(Options::default(), (612.0, 792.0)); +} + +#[test] +fn compressed_streams_are_redacted_too() { + check(Options { compress: true, ..Default::default() }, (612.0, 792.0)); +} + +#[test] +fn a_rotated_page_keeps_its_displayed_size() { + check(Options { rotate: 90, ..Default::default() }, (792.0, 612.0)); +} + +#[test] +fn inherited_resources_and_rotation_are_handled() { + check(Options { inherited: true, rotate: 90, ..Default::default() }, (792.0, 612.0)); +} + +#[test] +fn the_box_is_black_and_the_rest_of_the_page_still_shows() { + let input = secret_pdf(&Options::default()); + let out = redact(&input, vec![secret_box()]); + let img = pictor_pdf::render_page(engine(), &out.bytes, None, 0, 612).unwrap().to_rgb8(); + // Inside the box (view 300, 100): black. + let p = img.get_pixel(300, 100); + assert!(p.0.iter().all(|&c| c < 16), "box not black: {p:?}"); + // "PUBLIC-LINE" at PDF (72, 300) → view y ≈ 492: some dark pixels remain in that band. + let dark = (480..500).flat_map(|y| (72..160).map(move |x| (x, y))).filter(|&(x, y)| img.get_pixel(x, y).0[0] < 100).count(); + assert!(dark > 20, "the text outside the box disappeared ({dark} dark pixels)"); +} + +#[test] +fn a_redacted_encrypted_document_needs_its_password_and_comes_out_clean() { + let input = secret_pdf(&Options::default()); + let locked = pictor_pdf::protect(&input, None, "open-sesame", None).unwrap(); + assert!( + pictor_pdf::redact(engine(), &locked, None, &[Redaction { page: 0, rects: vec![secret_box()] }], &Default::default()) + .is_err(), + "redacted without the password" + ); + let out = pictor_pdf::redact( + engine(), + &locked, + Some("open-sesame"), + &[Redaction { page: 0, rects: vec![secret_box()] }], + &Default::default(), + ) + .unwrap(); + assert_no_secrets(&out.bytes); +} + +#[test] +fn no_redaction_box_is_refused() { + let input = secret_pdf(&Options::default()); + assert!(pictor_pdf::redact(engine(), &input, None, &[Redaction { page: 0, rects: vec![] }], &Default::default()).is_err()); + assert!( + pictor_pdf::redact(engine(), &input, None, &[Redaction { page: 9, rects: vec![secret_box()] }], &Default::default()) + .is_err(), + "a page that does not exist was accepted" + ); +} diff --git a/docs/DEPENDENCIES.md b/docs/DEPENDENCIES.md index 2b24528..4796f4e 100644 --- a/docs/DEPENDENCIES.md +++ b/docs/DEPENDENCIES.md @@ -1,86 +1,88 @@ -# Dependencies and their licences - -Every crate and binary Pictor's core uses, with its licence, recorded **before** it is used. -The brief's rule: only components that need no licence deal — MIT, Apache-2.0, BSD, Zlib, MPL-2.0, or a codec the -OS already provides. Nothing paid, copyleft-to-bundle, patent-encumbered or non-commercial. - -## The allowed set, as checked by `scripts/deps.mjs` - -| Licence (SPDX) | Why it is allowed | -| :-- | :-- | -| MIT, MIT-0 | named in the brief | -| Apache-2.0, Apache-2.0 WITH LLVM-exception | named in the brief | -| BSD-2-Clause, BSD-3-Clause, 0BSD | named in the brief ("BSD") | -| Zlib | named in the brief | -| MPL-2.0 | named in the brief (file-level copyleft: our own changes to such files stay MPL, which suits this repo) | -| ISC | **interpretation, Mark to confirm**: the BSD-style licence of the ISC; OSI calls it functionally the simplified BSD licence | -| Unicode-3.0, Unicode-DFS-2016 | **interpretation, Mark to confirm**: the MIT-style licence of Unicode's data tables; every Rust program that parses identifiers or text pulls it in (`unicode-ident`) | -| BSL-1.0, CC0-1.0 | **interpretation, Mark to confirm**: Boost (MIT-like, no attribution in binaries) and public domain | - -An SPDX expression with `OR` passes when one branch passes; `AND` needs every part to pass. Anything else makes the -script exit 1, and the feature that needs it waits (the brief: "it never gets a fallback"). - -## Direct dependencies - -| Crate | Version | Licence | Used by | For | -| :-- | :-- | :-- | :-- | :-- | -| thiserror | 2 | MIT OR Apache-2.0 | all | error types | -| serde, serde_json | 1 | MIT OR Apache-2.0 | worker, pdf, meta, qr | the worker protocol, reports | -| base64 | 0.22 | MIT OR Apache-2.0 | worker | binary payloads in the protocol | -| image | 0.25 | MIT OR Apache-2.0 | raster, pdf, qr | PNG, JPG, WebP, BMP, GIF, TIFF, ICO decode/encode (no default features: only these codecs) | -| kamadak-exif | 0.6 | BSD-2-Clause | meta | reading EXIF (and writing EXIF fixtures in tests) | -| img-parts | 0.4 | MIT OR Apache-2.0 | meta | JPEG segments, PNG and WebP chunks, without re-encoding | -| qrcode | 0.14 | MIT OR Apache-2.0 | qr | QR matrix and SVG | -| lopdf | 0.47 | MIT | pdf, meta | PDF structure: annotations, stamps, the redaction rebuild, encryption, metadata | -| pdfium-render | 0.9.5 | MIT OR Apache-2.0 | pdf | bindings to pdfium (render, text, forms, pages) | -| tempfile | 3 | MIT OR Apache-2.0 | save (and tests) | temporary files next to the target | -| sha2 | 0.11 | MIT OR Apache-2.0 | worker, tests | hashes for fixtures and the fetch scripts' self-check | -| windows | 0.62 | MIT OR Apache-2.0 | raster (Windows only), worker | WIC (HEIC), Job Objects | -| rqrr | 0.11 (dev) | (MIT OR Apache-2.0) AND ISC | qr tests | decoding generated codes back (ISC: see above) | -| proptest | 1 (dev) | MIT OR Apache-2.0 | tests | property tests | - -## Binaries (fetched, never in git) - -| Binary | Licence | Fetched by | -| :-- | :-- | :-- | -| pdfium (bblanchon/pdfium-binaries, Windows x64) | see "pdfium" below | `scripts/fetch-pdfium.ps1`, sha256-pinned | - -### pdfium - -Release `chromium/8125` (PDFium 158.0.8125.0), `pdfium-win-x64.tgz`, sha256 -`9a964261760cff52570aabf038ab346d3a5034dd8b30d0d5fe8861235d356b8b`, built without V8 and XFA (`args.gn`). It matches -pdfium-render 0.9.5's `pdfium_latest` (= `pdfium_8125`). The archive's `LICENSE` and `licenses/` folder ship beside -the dll (the app's installer copies them). Read from those files on 2026-11-16: - -| Component inside pdfium.dll | Licence | In the allowed set? | -| :-- | :-- | :-- | -| the binary build (bblanchon/pdfium-binaries) | MIT | yes | -| PDFium | BSD-3-Clause (+ Apache-2.0 parts) | yes | -| abseil, highway | Apache-2.0 | yes | -| llvm-libc, dragonbox | Apache-2.0 WITH LLVM-exception (dragonbox also BSL-1.0) | yes | -| fast_float, simdutf | MIT | yes | -| lcms2, agg 2.3 | MIT-style permission notice | yes (MIT family) | -| OpenJPEG | BSD-2-Clause | yes | -| zlib | Zlib | yes | -| HarfBuzz | "Old MIT" | yes (MIT family) | -| ICU | Unicode-3.0 | **interpretation** (see above) | -| libpng | PNG Reference Library License v2 (Libpng-2.0, zlib-style) | **interpretation**: zlib-style permissive | -| libjpeg-turbo | IJG + BSD-3-Clause | **interpretation**: IJG is BSD-style (credit in documentation) | -| FreeType | The FreeType Project License (FTL; dual with GPL-2.0, we take FTL) | **interpretation**: BSD-style with a credit clause — the app's About box says "Portions of this software are copyright © The FreeType Project (www.freetype.org). All rights reserved." | - -None of these needs a licence deal, is paid, copyleft-to-bundle, patent-encumbered or non-commercial. The four marked -"interpretation" are not named in the brief's list; they are BSD/zlib-style, and **Mark should confirm** them (PDF -support depends on pdfium, which the brief chose). - -## OS codecs (not bundled) - -| Codec | Provided by | Used for | -| :-- | :-- | :-- | -| HEIF/HEIC through WIC | Windows (HEIF Image Extensions + an HEVC decoder from the Microsoft Store) | decoding iPhone photos; never bundled | - -## Every crate in Cargo.lock - -Generated by `node scripts/deps.mjs` from `cargo metadata`; do not edit by hand. - - - +# Dependencies and their licences + +Every crate and binary Pictor's core uses, with its licence, recorded **before** it is used. +The brief's rule: only components that need no licence deal — MIT, Apache-2.0, BSD, Zlib, MPL-2.0, or a codec the +OS already provides. Nothing paid, copyleft-to-bundle, patent-encumbered or non-commercial. + +## The allowed set, as checked by `scripts/deps.mjs` + +| Licence (SPDX) | Why it is allowed | +| :-- | :-- | +| MIT, MIT-0 | named in the brief | +| Apache-2.0, Apache-2.0 WITH LLVM-exception | named in the brief | +| BSD-2-Clause, BSD-3-Clause, 0BSD | named in the brief ("BSD") | +| Zlib | named in the brief | +| MPL-2.0 | named in the brief (file-level copyleft: our own changes to such files stay MPL, which suits this repo) | +| ISC | **interpretation, Mark to confirm**: the BSD-style licence of the ISC; OSI calls it functionally the simplified BSD licence | +| Unicode-3.0, Unicode-DFS-2016 | **interpretation, Mark to confirm**: the MIT-style licence of Unicode's data tables; every Rust program that parses identifiers or text pulls it in (`unicode-ident`) | +| BSL-1.0, CC0-1.0 | **interpretation, Mark to confirm**: Boost (MIT-like, no attribution in binaries) and public domain | + +An SPDX expression with `OR` passes when one branch passes; `AND` needs every part to pass. Anything else makes the +script exit 1, and the feature that needs it waits (the brief: "it never gets a fallback"). + +## Direct dependencies + +| Crate | Version | Licence | Used by | For | +| :-- | :-- | :-- | :-- | :-- | +| thiserror | 2 | MIT OR Apache-2.0 | all | error types | +| serde, serde_json | 1 | MIT OR Apache-2.0 | worker, pdf, meta, qr | the worker protocol, reports | +| base64 | 0.22 | MIT OR Apache-2.0 | worker | binary payloads in the protocol | +| image | 0.25 | MIT OR Apache-2.0 | raster, pdf, qr | PNG, JPG, WebP, BMP, GIF, TIFF, ICO decode/encode (no default features: only these codecs) | +| kamadak-exif | 0.6 | BSD-2-Clause | meta | reading EXIF (and writing EXIF fixtures in tests) | +| img-parts | 0.4 | MIT OR Apache-2.0 | meta | JPEG segments, PNG and WebP chunks, without re-encoding | +| qrcode | 0.14 | MIT OR Apache-2.0 | qr | QR matrix and SVG | +| lopdf | 0.47 | MIT | pdf, meta | PDF structure: annotations, stamps, the redaction rebuild, encryption, metadata | +| pdfium-render | 0.9.5 | MIT OR Apache-2.0 | pdf | bindings to pdfium (render, text, forms, pages) | +| tempfile | 3 | MIT OR Apache-2.0 | save (and tests) | temporary files next to the target | +| sha2 | 0.11 | MIT OR Apache-2.0 | worker, tests | hashes for fixtures and the fetch scripts' self-check | +| getrandom | 0.4 | MIT OR Apache-2.0 | pdf | the OS random generator, for the AES-256 file key of a password-protected PDF | +| flate2 | 1 (dev) | MIT OR Apache-2.0 | pdf tests | building compressed hostile fixtures (a deflate bomb) | +| windows | 0.62 | MIT OR Apache-2.0 | raster (Windows only), worker | WIC (HEIC), Job Objects | +| rqrr | 0.11 (dev) | (MIT OR Apache-2.0) AND ISC | qr tests | decoding generated codes back (ISC: see above) | +| proptest | 1 (dev) | MIT OR Apache-2.0 | tests | property tests | + +## Binaries (fetched, never in git) + +| Binary | Licence | Fetched by | +| :-- | :-- | :-- | +| pdfium (bblanchon/pdfium-binaries, Windows x64) | see "pdfium" below | `scripts/fetch-pdfium.ps1`, sha256-pinned | + +### pdfium + +Release `chromium/8125` (PDFium 158.0.8125.0), `pdfium-win-x64.tgz`, sha256 +`9a964261760cff52570aabf038ab346d3a5034dd8b30d0d5fe8861235d356b8b`, built without V8 and XFA (`args.gn`). It matches +pdfium-render 0.9.5's `pdfium_latest` (= `pdfium_8125`). The archive's `LICENSE` and `licenses/` folder ship beside +the dll (the app's installer copies them). Read from those files on 2026-11-16: + +| Component inside pdfium.dll | Licence | In the allowed set? | +| :-- | :-- | :-- | +| the binary build (bblanchon/pdfium-binaries) | MIT | yes | +| PDFium | BSD-3-Clause (+ Apache-2.0 parts) | yes | +| abseil, highway | Apache-2.0 | yes | +| llvm-libc, dragonbox | Apache-2.0 WITH LLVM-exception (dragonbox also BSL-1.0) | yes | +| fast_float, simdutf | MIT | yes | +| lcms2, agg 2.3 | MIT-style permission notice | yes (MIT family) | +| OpenJPEG | BSD-2-Clause | yes | +| zlib | Zlib | yes | +| HarfBuzz | "Old MIT" | yes (MIT family) | +| ICU | Unicode-3.0 | **interpretation** (see above) | +| libpng | PNG Reference Library License v2 (Libpng-2.0, zlib-style) | **interpretation**: zlib-style permissive | +| libjpeg-turbo | IJG + BSD-3-Clause | **interpretation**: IJG is BSD-style (credit in documentation) | +| FreeType | The FreeType Project License (FTL; dual with GPL-2.0, we take FTL) | **interpretation**: BSD-style with a credit clause — the app's About box says "Portions of this software are copyright © The FreeType Project (www.freetype.org). All rights reserved." | + +None of these needs a licence deal, is paid, copyleft-to-bundle, patent-encumbered or non-commercial. The four marked +"interpretation" are not named in the brief's list; they are BSD/zlib-style, and **Mark should confirm** them (PDF +support depends on pdfium, which the brief chose). + +## OS codecs (not bundled) + +| Codec | Provided by | Used for | +| :-- | :-- | :-- | +| HEIF/HEIC through WIC | Windows (HEIF Image Extensions + an HEVC decoder from the Microsoft Store) | decoding iPhone photos; never bundled | + +## Every crate in Cargo.lock + +Generated by `node scripts/deps.mjs` from `cargo metadata`; do not edit by hand. + + +