[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
+267
View File
@@ -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<u8> {
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"<x:xmpmeta xmlns:x='adobe:ns:meta/'><rdf:RDF xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'>\
<rdf:Description xmlns:dc='http://purl.org/dc/elements/1.1/'><dc:title>XMP-SECRET</dc:title></rdf:Description>\
</rdf:RDF></x:xmpmeta>"
.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<u8> {
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<Vec<u8>> {
let doc = Document::load_mem(bytes).expect("lopdf reloads the output");
let mut found = Vec::new();
fn walk(o: &Object, found: &mut Vec<Vec<u8>>) {
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<ObjectId> {
doc.get_pages().values().copied().collect()
}
/// A page's content, decompressed and concatenated.
pub fn page_content(doc: &Document, page: ObjectId) -> Vec<u8> {
doc.get_page_content(page)
}
+153
View File
@@ -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<ViewRect>) -> 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::<Vec<_>>()
};
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<Vec<u8>> {
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<Vec<u8>> = 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"
);
}