[pdf] Redaction: rebuild redacted pages as one image, scrub hidden data, prune; reader and AES-256 protect/unlock

This commit is contained in:
2026-11-16 13:26:02 +01:00
parent b554d760e2
commit 2c1611b34a
14 changed files with 1452 additions and 125 deletions
+1
View File
@@ -0,0 +1 @@
//! The edit pipeline (form fill, annotations, stamps, flatten, security).
+46
View File
@@ -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<Engine> = 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<PdfDocument<'a>, 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<PdfDocument<'_>, 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<Vec<u8>, PdfError> {
doc.save_to_bytes().map_err(|e| PdfError::Write(e.to_string()))
}
+70
View File
@@ -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),
}
}
}
+92
View File
@@ -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);
}
}
+47
View File
@@ -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<lopdf::Document, PdfError> {
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<Vec<u8>, PdfError> {
let mut out = Vec::new();
doc.save_to(&mut out).map_err(|e| PdfError::Write(e.to_string()))?;
Ok(out)
}
+1
View File
@@ -0,0 +1 @@
//! Page operations, merge, split, images to PDF, PDF to images (pdfium).
+170
View File
@@ -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<PageInfo>,
pub outline: Vec<OutlineItem>,
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<String>,
}
#[derive(Debug, Clone, Serialize)]
pub struct OutlineItem {
pub title: String,
pub page: Option<usize>,
pub depth: u32,
}
#[derive(Debug, Clone, Serialize)]
pub struct SearchHit {
pub page: usize,
/// The hit's boxes in view space.
pub rects: Vec<ViewRect>,
}
pub fn info(engine: &Engine, bytes: &[u8], password: Option<&str>) -> Result<DocInfo, PdfError> {
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<OutlineItem>, 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<Vec<(f32, f32)>, 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<DynamicImage, PdfError> {
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<DynamicImage, PdfError> {
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<Vec<String>, 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<Vec<SearchHit>, 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() }
}
}
+406
View File
@@ -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<ViewRect>,
}
#[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<u8>,
/// Plain sentences for the user (for example, hidden layers left on pages that were not redacted).
pub warnings: Vec<String>,
}
const IMAGE_NAME: &[u8] = b"PictorRedacted";
pub fn redact(
engine: &Engine,
bytes: &[u8],
password: Option<&str>,
redactions: &[Redaction],
opts: &RedactOptions,
) -> Result<Redacted, PdfError> {
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<u8>, 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<ViewRect> = 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<ObjectId> = 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<ObjectId> = HashSet::new();
let redacted_pages: HashSet<ObjectId> = 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<ObjectId>) {
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<ObjectId>) {
let Ok(catalog) = doc.catalog() else { return };
let acroform = match catalog.get(b"AcroForm") {
Ok(Object::Reference(id)) => Some(*id),
_ => None,
};
let fields: Vec<Object> = {
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<ObjectId>, 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<Object> = 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<Object> = 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<ObjectId>, warnings: &mut Vec<String>) {
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<ObjectId> = 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::<Vec<_>>().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
}
+51
View File
@@ -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<Vec<u8>, 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<dyn CryptFilter> = 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<Vec<u8>, PdfError> {
let mut doc = lopdf_load(bytes, Some(password))?;
doc.trailer.remove(b"Encrypt");
lopdf_save(&mut doc)
}