Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

Merge upstream/main into fix/coderabbit-b-shared

aiongga72845ad8075
diff --cc crates/optimize/src/images.rs
index 531c56ece,1d8a59e25..0eb882ec2
--- a/crates/optimize/src/images.rs
+++ b/crates/optimize/src/images.rs
@@@ -443,18 -453,21 +464,35 @@@ mod dimension_tests
let stream = Stream::from_raw(dict, vec![1, 2, 3, 4, 5]);
assert_eq!(pixels(&stream, 1), Some(vec![1, 2, 3, 4]));
}
+
+ /// A JPEG larger than its dictionary says is refused from its header, before its pixels are decoded.
+ #[test]
+ fn a_jpeg_of_another_size_than_its_dictionary_is_not_decoded() {
+ let data = jpeg(&vec![128; 1000 * 1000], 1, 1000, 1000, 50).unwrap_or_default();
+ let stream = |w: i64, h: i64| {
+ let mut dict = Dict::new();
+ dict.set(b"Width".to_vec(), Object::Int(w));
+ dict.set(b"Height".to_vec(), Object::Int(h));
+ dict.set(b"Filter".to_vec(), Object::name("DCTDecode"));
+ Stream::from_raw(dict, data.clone())
+ };
+ DECODED_PIXELS.with(|c| c.set(0));
+ assert!(pixels(&stream(10, 10), 1).is_none());
+ assert_eq!(DECODED_PIXELS.with(|c| c.get()), 0, "pixels decoded");
+ assert_eq!(pixels(&stream(1000, 1000), 1).map(|p| p.len()), Some(1000 * 1000));
+ }
}
+
+#[cfg(test)]
+mod tests {
+ use pdfcraft_cos::{DecodeBudget, Dict, Document, MAX_PAGE_DECODED, Object, Stream};
+
+ #[test]
+ fn repeated_content_references_share_one_decode_budget() {
+ let mut doc = Document::new_empty();
+ let stream = doc.add(Stream::flate(Dict::new(), &vec![b' '; 1 << 20]));
+ let contents = Object::Array(vec![Object::Ref(stream); 300]);
+ let data = super::content_bytes(&doc, &contents, &mut DecodeBudget::page());
+ assert!(data.is_none_or(|d| d.len() <= MAX_PAGE_DECODED + 300));
+ }
+}
diff --cc crates/print/src/lib.rs
index 05b0770ba,6839e5f6b..a6337026b
--- a/crates/print/src/lib.rs
+++ b/crates/print/src/lib.rs
@@@ -682,24 -676,45 +682,43 @@@ fn n(v: f64) -> String
if s == "-0" { "0".into() } else { s.into() }
}
-fn decoded_contents(doc: &Document, page: &Dict) -> Vec<u8> {
- let list: Vec<Object> = match page.get(b"Contents") {
- None => Vec::new(),
- Some(c) => match &*doc.resolve(c) {
- Object::Array(a) => a.clone(),
- _ => vec![c.clone()],
- },
- };
+/// The page's content streams decoded against `budget` and joined; streams that don't decode
+/// are left out. `None` when the budget ran out, so part of the content is missing.
+fn decoded_contents(doc: &Document, page: &Dict, budget: &mut DecodeBudget) -> Option<Vec<u8>> {
+ let Some(contents) = page.get(b"Contents") else { return Some(Vec::new()) };
let mut out = Vec::new();
- for o in list {
- if let Object::Stream(s) = &*doc.resolve(&o)
- && let Ok(d) = s.decoded()
- {
- out.extend_from_slice(&d);
- out.push(b'\n');
+ for data in budget.decode_contents(doc, contents) {
+ match data {
+ Ok(data) => {
+ out.extend_from_slice(&data);
+ out.push(b'\n');
+ }
+ Err(_) if budget.remaining() == 0 => return None,
+ Err(_) => {}
}
}
- out
+ Some(out)
}
+ /// Reduce `doc`'s pages to what [`impose`] draws of them under `content`: the annotations that
+ /// don't print are dropped, and with [`Content::FormFieldsOnly`] the page content too. For
+ /// printing pages as pictures, where a renderer draws each page as it stands.
+ pub fn keep_printed(doc: &mut Document, content: Content) {
+ for page in pdfcraft_model::pages(doc) {
+ let annots = page.dict.get(b"Annots").and_then(|a| doc.resolve(a).as_array().cloned()).unwrap_or_default();
+ let kept: Vec<Object> = annots.into_iter().filter(|a| doc.resolve(a).as_dict().is_some_and(|d| prints(doc, d, content))).collect();
+ // Fails only when the page object isn't a dictionary, and such a page draws nothing.
+ let _ = doc.update_dict(page.obj, |d| {
+ if content == Content::FormFieldsOnly {
+ d.remove(b"Contents");
+ }
+ if d.contains(b"Annots") {
+ d.set(b"Annots".to_vec(), Object::Array(kept));
+ }
+ });
+ }
+ }
+
/// Does annotation `d` print under `content`?
fn prints(doc: &Document, d: &Dict, content: Content) -> bool {
const HIDDEN: i64 = 2;
diff --cc crates/redact/src/interp.rs
index 5b3742385,b4186fd4e..0a3b730f6
--- a/crates/redact/src/interp.rs
+++ b/crates/redact/src/interp.rs
@@@ -1205,25 -1271,9 +1275,26 @@@ fn xobject
out.doomed.push(r);
return Some(None);
}
+ // Strict, like page content: a Form read only in part counts as undecodable.
- let data = match s.decoded_strict() {
+ let data = if scope.budget.enter_form() {
- scope.budget.decode(s)
++ scope.budget.decode_strict(s)
+ } else {
+ Err(CosError::Filter(format!("the page draws more than {MAX_PAGE_FORMS} form XObjects")))
+ };
+ let data = match data {
Ok(d) => d,
+ // Past the page's budget nothing more is read: apply refuses the page, and
+ // verification counts the form as content that may remain.
+ Err(e) if scope.budget.exhausted() => {
+ if scope.mode == Mode::Apply {
+ out.error = Some(e);
+ } else if scope.everywhere() {
+ scope.layer_blocks += 1;
+ } else {
+ out.residue += 1;
+ }
+ return None;
+ }
Err(_) if scope.mode == Mode::Apply => {
scope.report.forms_removed += 1;
out.replaced.push(name);
diff --cc crates/redact/src/lib.rs
index 8407e0c8f,e67b373a1..f84797720
--- a/crates/redact/src/lib.rs
+++ b/crates/redact/src/lib.rs
@@@ -230,10 -237,11 +238,12 @@@ pub(crate) fn page_streams(doc: &Docume
},
};
let mut data = Vec::new();
+ let mut budget = pdfcraft_cos::DecodeBudget::page();
for o in &list {
match &*doc.resolve(o) {
- Object::Stream(s) => data.push(budget.decode(s).map_err(|_| RedactError::Unreadable(index + 1))?),
+ // Strict: a tolerant decode keeps what precedes corruption and drops the rest, which
+ // still draws in viewers that read further; anything not read can't be cleaned.
- Object::Stream(s) => data.push(s.decoded_strict().map_err(|_| RedactError::Unreadable(index + 1))?),
++ Object::Stream(s) => data.push(budget.decode_strict(s).map_err(|_| RedactError::Unreadable(index + 1))?),
Object::Null => data.push(Vec::new()),
_ => return Err(RedactError::Unreadable(index + 1)),
}
diff --cc crates/redact/src/tests.rs
index 11cae9bb9,e35d4f907..550903e49
--- a/crates/redact/src/tests.rs
+++ b/crates/redact/src/tests.rs
@@@ -2473,19 -2478,221 +2478,238 @@@ fn a_tj_surplus_arrays_undrawn_glyphs_a
assert_eq!(under(&mut doc, 0, &[[10.0, 95.0, 45.0, 110.0]]), 7, "LASTARR's 7 glyphs, the one the page draws");
}
+#[test]
+fn form_entries_share_one_budget_per_page() {
+ // 20 draws of a form that draws the next 20 times, four levels down: 160,000 glyphs from a
+ // few hundred bytes.
+ let draws = "/X Do ".repeat(20);
+ let mut objs = vec![stream("/Type /XObject /Subtype /Form /Resources << /Font << /F1 5 0 R >> >>", b"BT /F1 10 Tf 10 100 Td (A) Tj ET")];
+ for inner in 7..10 {
+ objs.push(stream(&format!("/Type /XObject /Subtype /Form /Resources << /XObject << /X {inner} 0 R >> >>"), draws.as_bytes()));
+ }
+ let mut doc = one_page(draws.as_bytes(), "/XObject << /X 10 0 R >>", objs);
+ let residue = under(&mut doc, 0, &[[0.0, 90.0, 50.0, 120.0]]);
+ assert!(residue > 0 && residue <= pdfcraft_cos::MAX_PAGE_FORMS, "{residue} glyphs counted");
+ // Applying refuses the page rather than leave forms past the budget unread.
+ mark(&mut doc, 0, &[[0.0, 90.0, 50.0, 120.0]], "");
+ assert!(apply(&mut doc, None).is_err());
+}
++
+ /// A name tree whose levels each list the next level twice: a walk that follows every path
+ /// visits 2^levels nodes.
+ #[test]
+ fn a_name_tree_whose_nodes_share_kids_counts_each_entry_once() {
+ use crate::sanitize::{Hidden, scan};
+ let levels = 12;
+ let mut objs: Vec<Vec<u8>> = vec![
+ b"<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 5 0 R >> >>".to_vec(),
+ b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
+ b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R >>".to_vec(),
+ stream("", b"BT ET"),
+ ];
+ for k in 0..levels {
+ let next = 6 + k;
+ objs.push(format!("<< /Kids [{next} 0 R {next} 0 R] >>").into_bytes());
+ }
+ objs.push(b"<< /Names [(a.txt) << /Type /Filespec /F (a.txt) >>] >>".to_vec());
+ let doc = pdf(objs);
+ let counts: std::collections::HashMap<Hidden, usize> = scan(&doc).into_iter().collect();
+ assert_eq!(counts[&Hidden::Attachments], 1, "one entry, reached through 2^{levels} paths");
+ }
+
+ /// Page content that stops decoding at its start (`z` inside an ASCII85 group) while the rest of
+ /// the stream draws hidden text. A tolerant decode reads nothing, counts nothing and keeps the
+ /// stream; sanitizing must refuse instead.
+ #[test]
+ fn hidden_text_in_content_that_stops_decoding_is_refused() {
+ use crate::sanitize::{Hidden, remove_hidden, sanitize};
+ let encoded: &[u8] = br"!!z6<#'\7PQ#?0Ha>,+>Y->EZd(j+>PW)+B2ko-rWQ%;FOP6+B3(u78s~>";
+ let fresh = || {
+ let mut doc = one_page(b"", "", vec![stream("/Filter /ASCII85Decode", encoded)]);
+ doc.update_dict(ObjRef::new(3, 0), |d| d.set(b"Contents".to_vec(), Object::Ref(ObjRef::new(7, 0)))).unwrap();
+ doc
+ };
+ let mut doc = fresh();
+ let out = remove_hidden(&mut doc, &[Hidden::HiddenText]);
+ assert!(matches!(out, Err(RedactError::Unreadable(1))), "{out:?}");
+ let mut doc = fresh();
+ let out = sanitize(&mut doc);
+ assert!(matches!(out, Err(RedactError::Unreadable(1))), "{out:?}");
+ }
+
+ /// An array of references to objects `nums` (generation 0).
+ fn ref_array(nums: &[u32]) -> Object {
+ Object::Array(nums.iter().map(|&n| Object::Ref(ObjRef::new(n, 0))).collect())
+ }
+
+ /// An interactive form dictionary listing fields `nums`.
+ fn fields_dict(nums: &[u32]) -> Object {
+ let mut d = Dict::new();
+ d.set(b"Fields".to_vec(), ref_array(nums));
+ Object::Dict(d)
+ }
+
+ /// Flattening keeps hidden widgets (they draw nothing); removing form fields must still take them
+ /// and their values, and their parent field's value, out of the file.
+ #[test]
+ fn removing_form_fields_takes_hidden_widgets_and_their_values_out_of_the_file() {
+ use crate::sanitize::{Hidden, remove_hidden};
+ let mut doc = one_page(
+ b"BT /F1 10 Tf 10 100 Td (Visible) Tj ET",
+ "",
+ vec![
+ // 7 a hidden terminal field merged with its widget, 8 a parent field, 9 its hidden widget
+ b"<< /Type /Annot /Subtype /Widget /FT /Tx /T (own) /V (LEAK_WIDGET_VALUE) /F 2 /Rect [10 200 150 220] /AP << /N 10 0 R >> >>".to_vec(),
+ b"<< /FT /Tx /T (parent) /V (LEAK_PARENT_VALUE) /Kids [9 0 R] >>".to_vec(),
+ b"<< /Type /Annot /Subtype /Widget /Parent 8 0 R /F 32 /Rect [10 230 150 250] /AP << /N 10 0 R >> >>".to_vec(),
+ stream("/Type /XObject /Subtype /Form /BBox [0 0 140 20]", b"0 g"),
+ ],
+ );
+ doc.update_dict(doc.root().unwrap(), |d| d.set(b"AcroForm".to_vec(), fields_dict(&[7, 8]))).unwrap();
+ doc.update_dict(ObjRef::new(3, 0), |d| d.set(b"Annots".to_vec(), ref_array(&[7, 9]))).unwrap();
+ remove_hidden(&mut doc, &[Hidden::FormFields]).unwrap();
+ assert_no_secret(&doc, b"LEAK_");
+ assert!(annots_of(&doc, &pdfcraft_model::pages(&doc).swap_remove(0).dict).is_empty());
+ }
+
+ /// Removing hidden text cleans the structure tree as redaction does: the elements describing the
+ /// removed text lose their descriptions, and a reference into a rewritten Form points at the copy.
+ #[test]
+ fn removing_hidden_text_cleans_the_structure_tree() {
+ use crate::sanitize::{Hidden, remove_hidden};
+ let mut doc = one_page(
+ b"/P <</MCID 0>> BDC BT /F1 10 Tf 3 Tr 10 200 Td (SECRET) Tj ET EMC /P <</MCID 1>> BDC BT /F1 10 Tf 0 Tr 10 100 Td (Public) Tj ET EMC /Fm Do",
+ "/XObject << /Fm 7 0 R >>",
+ vec![
+ stream(
+ "/Type /XObject /Subtype /Form /BBox [0 0 300 300] /Resources << /Font << /F1 5 0 R >> >>",
+ b"/P <</MCID 0>> BDC BT /F1 10 Tf 3 Tr 10 150 Td (FORMSECRET) Tj ET EMC",
+ ),
+ b"<< /Type /StructTreeRoot /K 9 0 R >>".to_vec(),
+ b"<< /S /Document /P 8 0 R /K [10 0 R 11 0 R 12 0 R] >>".to_vec(),
+ b"<< /S /P /P 9 0 R /Pg 3 0 R /ActualText (LEAK_PAGE_TAG) /K 0 >>".to_vec(),
+ b"<< /S /P /P 9 0 R /Pg 3 0 R /ActualText (Public) /K 1 >>".to_vec(),
+ b"<< /S /P /P 9 0 R /Pg 3 0 R /Alt (LEAK_FORM_TAG) /K << /Type /MCR /Pg 3 0 R /Stm 7 0 R /MCID 0 >> >>".to_vec(),
+ ],
+ );
+ doc.update_dict(doc.root().unwrap(), |d| d.set(b"StructTreeRoot".to_vec(), Object::Ref(ObjRef::new(8, 0)))).unwrap();
+ doc.update_dict(ObjRef::new(3, 0), |d| d.set(b"StructParents".to_vec(), Object::Int(0))).unwrap();
+ remove_hidden(&mut doc, &[Hidden::HiddenText]).unwrap();
+ assert_no_secret(&doc, b"LEAK_");
+ assert_no_secret(&doc, b"SECRET");
+ assert!(doc.get(ObjRef::new(11, 0)).as_dict().unwrap().contains(b"ActualText"), "untouched content keeps its tags");
+ }
+
+ /// One page drawing image /Im (object 7) and form /Fm (object 8), with `extra` objects from 9 on.
+ fn owners_fixture(image: &str, form: &str, extra: Vec<Vec<u8>>) -> Document {
+ let mut objs = vec![
+ stream(&format!("/Type /XObject /Subtype /Image /Width 1 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8 {image}"), b"\x80"),
+ stream(&format!("/Type /XObject /Subtype /Form /BBox [0 0 10 10] {form}"), b"0 0 5 5 re f"),
+ ];
+ objs.extend(extra);
+ one_page(b"BT /F1 10 Tf 10 100 Td (Visible) Tj ET q 10 0 0 10 0 0 cm /Im Do Q /Fm Do", "/XObject << /Im 7 0 R /Fm 8 0 R >>", objs)
+ }
+
+ /// Removing one category and saving leaves none of `secret` in the file, and the scan counted it.
+ fn removes_from_every_owner(mut doc: Document, h: crate::sanitize::Hidden, secret: &[u8]) {
+ use crate::sanitize::{remove_hidden, scan};
+ let counts: std::collections::HashMap<_, usize> = scan(&doc).into_iter().collect();
+ assert!(counts[&h] > 0, "{h:?} is counted");
+ remove_hidden(&mut doc, &[h]).unwrap();
+ assert_no_secret(&doc, secret);
+ assert!(scan(&reopen(&doc)).into_iter().all(|(k, n)| k != h || n == 0 || h == crate::sanitize::Hidden::Metadata));
+ }
+
+ #[test]
+ fn private_data_of_a_form_xobject_is_removed() {
+ let doc = owners_fixture("", "/PieceInfo << /App << /Private (LEAK_PRIVATE) >> >>", vec![]);
+ removes_from_every_owner(doc, crate::sanitize::Hidden::PrivateData, b"LEAK_");
+ }
+
+ #[test]
+ fn metadata_of_an_image_is_removed() {
+ let doc = owners_fixture("/Metadata 9 0 R", "", vec![stream("/Type /Metadata /Subtype /XML", b"<x:xmpmeta>LEAK_XMP</x:xmpmeta>")]);
+ removes_from_every_owner(doc, crate::sanitize::Hidden::Metadata, b"LEAK_");
+ }
+
+ #[test]
+ fn a_pages_associated_files_are_removed_with_attachments() {
+ let mut doc = owners_fixture(
+ "",
+ "",
+ vec![b"<< /Type /Filespec /F (a.txt) /AFRelationship /Data /EF << /F 10 0 R >> >>".to_vec(), stream("/Type /EmbeddedFile", b"LEAK_ATTACHED")],
+ );
+ doc.update_dict(ObjRef::new(3, 0), |d| d.set(b"AF".to_vec(), ref_array(&[9]))).unwrap();
+ removes_from_every_owner(doc, crate::sanitize::Hidden::Attachments, b"LEAK_");
+ }
+
+ #[test]
+ fn a_fields_own_actions_are_removed_with_links_actions_and_scripts() {
+ let mut doc = owners_fixture(
+ "",
+ "",
+ vec![
+ b"<< /FT /Tx /T (total) /AA << /C << /S /JavaScript /JS (LEAK_SCRIPT) >> >> /Kids [10 0 R] >>".to_vec(),
+ b"<< /Type /Annot /Subtype /Widget /Parent 9 0 R /Rect [10 200 150 220] >>".to_vec(),
+ ],
+ );
+ doc.update_dict(doc.root().unwrap(), |d| d.set(b"AcroForm".to_vec(), fields_dict(&[9]))).unwrap();
+ doc.update_dict(ObjRef::new(3, 0), |d| d.set(b"Annots".to_vec(), ref_array(&[10]))).unwrap();
+ removes_from_every_owner(doc, crate::sanitize::Hidden::LinksActionsScripts, b"LEAK_");
+ }
+
+ /// Resource names are chosen by the producer: a font named like an owned entry stays.
+ #[test]
+ fn a_resource_named_like_an_owned_entry_is_kept() {
+ let mut doc = one_page(
+ b"BT /AF 10 Tf 10 100 Td (Visible) Tj ET",
+ "",
+ vec![b"<< /Type /Filespec /F (a.txt) /EF << /F 8 0 R >> >>".to_vec(), stream("/Type /EmbeddedFile", b"LEAK_ATTACHED")],
+ );
+ doc.update_dict(ObjRef::new(3, 0), |d| {
+ let mut fonts = Dict::new();
+ fonts.set(b"AF".to_vec(), Object::Ref(ObjRef::new(5, 0)));
+ let mut res = Dict::new();
+ res.set(b"Font".to_vec(), Object::Dict(fonts));
+ d.set(b"Resources".to_vec(), Object::Dict(res));
+ d.set(b"AF".to_vec(), ref_array(&[7]));
+ })
+ .unwrap();
+ removes_from_every_owner(doc.clone(), crate::sanitize::Hidden::Attachments, b"LEAK_");
+ crate::sanitize::remove_hidden(&mut doc, &[crate::sanitize::Hidden::Attachments]).unwrap();
+ let page = pdfcraft_model::pages(&doc).swap_remove(0);
+ let res = doc.resolve(page.dict.get(b"Resources").unwrap()).as_dict().cloned().unwrap();
+ assert!(res.get(b"Font").and_then(|f| f.as_dict()).is_some_and(|f| f.contains(b"AF")));
+ assert!(!page.dict.contains(b"AF"));
+ }
+
+ /// Owners written in place deeper than the sweep follows are refused, not skipped.
+ #[test]
+ fn owners_nested_too_deeply_are_refused() {
+ use crate::sanitize::{Hidden, remove_hidden};
+ let nested = format!("{}<< /AA << /O << /S /JavaScript /JS (LEAK_DEEP) >> >> >>{}", "[".repeat(100), "]".repeat(100));
+ let mut doc = one_page(b"BT ET", "", vec![format!("<< /Deep {nested} >>").into_bytes()]);
+ doc.update_dict(ObjRef::new(3, 0), |d| d.set(b"PieceInfo".to_vec(), Object::Ref(ObjRef::new(7, 0)))).unwrap();
+ let out = remove_hidden(&mut doc, &[Hidden::LinksActionsScripts]);
+ assert!(matches!(out, Err(RedactError::TooDeep)), "{out:?}");
+ }
+
+ /// A name tree node that lists the same kid more times than the node budget: each repeat costs a
+ /// step, so the walk stops at the budget instead of scanning every repeat, and the distinct kid
+ /// listed after them is never reached.
+ #[test]
+ fn repeated_name_tree_kids_count_towards_the_node_budget() {
+ use crate::sanitize::{Hidden, scan};
+ let repeats = "6 0 R ".repeat(100_010);
+ let doc = pdf(vec![
+ b"<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 5 0 R >> >>".to_vec(),
+ b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
+ b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R >>".to_vec(),
+ stream("", b"BT ET"),
+ format!("<< /Kids [{repeats}7 0 R] >>").into_bytes(),
+ b"<< /Names [(a.txt) << /Type /Filespec /F (a.txt) >>] >>".to_vec(),
+ b"<< /Names [(b.txt) << /Type /Filespec /F (b.txt) >>] >>".to_vec(),
+ ]);
+ let counts: std::collections::HashMap<Hidden, usize> = scan(&doc).into_iter().collect();
+ assert_eq!(counts[&Hidden::Attachments], 1, "the walk went past its node budget to the last kid");
+ }