Skip to content

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

Merge remote-tracking branch 'origin/main' into HEAD

Dylan M. Taylor684226713a70
diff --cc crates/audit/src/lib.rs
index 5cbcb75bf,8277cb0aa..98efe2fed
--- a/crates/audit/src/lib.rs
+++ b/crates/audit/src/lib.rs
@@@ -77,12 -77,10 +77,14 @@@ pub enum AuditError
TooManyOps,
#[error("form XObjects nest deeper than the audit follows")]
TooDeep,
+ #[error("content walk entered more form XObjects than the audit follows")]
+ TooManyForms,
#[error("page has a malformed /Annots entry")]
BadAnnots,
+ #[error("page has more covers and text lines than the audit compares")]
+ TooManyComparisons,
+ #[error("covered text exceeds the audit's report budget")]
+ TooMuchOutput,
#[error(transparent)]
Cos(#[from] pdfcraft_cos::CosError),
#[error(transparent)]
diff --cc crates/audit/src/tests.rs
index ac02251c7,3d0c80e0b..3b5c5c8c7
--- a/crates/audit/src/tests.rs
+++ b/crates/audit/src/tests.rs
@@@ -593,134 -593,35 +593,167 @@@ fn reading_blocks_respect_stream_commen
}
}
+/// The current path is not graphics state: a rectangle built before `Q` and filled after it
+/// paints the box, so it is a cover.
+#[test]
+fn rectangle_filled_after_restore_is_a_cover() {
+ let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n0 g\nq 100 688 220 32 re Q f\n";
+ let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run");
+ assert_eq!(findings.len(), 1, "{findings:?}");
+ assert!(findings[0].covered_text.contains("SECRET"), "{findings:?}");
+}
+
+/// A `/Subtype` may be an indirect reference to the name, like any other value: a `/Redact`
+/// annotation and a covering form XObject named that way are still checked.
+#[test]
+fn indirect_subtype_is_resolved() {
+ let mut b = Builder::new();
+ b.add("<< /Type /Catalog /Pages 2 0 R >>");
+ b.add("<< /Type /Pages /Kids [3 0 R] /Count 1 >>");
+ b.add("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> /Annots [6 0 R] >>");
+ b.add_stream(b"BT /F1 24 Tf 100 700 Td (DO NOT SHARE) Tj ET\n");
+ b.add(FONT);
+ b.add("<< /Type /Annot /Subtype 7 0 R /Rect [95 685 305 725] >>");
+ b.add("/Redact");
+ let findings = audit_redactions(&open(b.build())).expect("audit must run");
+ assert_eq!(findings.len(), 1, "{findings:?}");
+ assert_eq!(findings[0].kind, FindingKind::UnappliedMark);
+
+ let mut b = Builder::new();
+ b.add("<< /Type /Catalog /Pages 2 0 R >>");
+ b.add("<< /Type /Pages /Kids [3 0 R] /Count 1 >>");
+ b.add("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 6 0 R >> /XObject << /X 5 0 R >> >> >>");
+ b.add_stream(b"BT /F1 24 Tf 100 700 Td (SECRET) Tj ET\n/X Do\n");
+ b.add_stream_with(b"0 g\n100 688 220 32 re f\n", "/Type /XObject /Subtype 7 0 R /BBox [0 0 612 792]");
+ b.add(FONT);
+ b.add("/Form");
+ let findings = audit_redactions(&open(b.build())).expect("audit must run");
+ assert_eq!(findings.len(), 1, "{findings:?}");
+ assert_eq!(findings[0].kind, FindingKind::CoveredText);
+}
+
+/// Text drawn after a cover on the same baseline joins the covered text in one line. The cover
+/// still hides the words painted before it.
+#[test]
+fn later_text_on_the_line_does_not_clear_an_earlier_cover() {
+ let content = b"0 g\nBT /F1 24 Tf 100 700 Td (SECRET) Tj ET\n98 688 94 32 re f\nBT /F1 24 Tf 200 700 Td (tail) Tj ET\n";
+ let doc = open(one_page(content, ""));
+ let lines = pdfcraft_edit::text_lines(&doc, 0).expect("text");
+ assert_eq!(lines.len(), 1, "the runs join one line: {:?}", lines.iter().map(|l| &l.text).collect::<Vec<_>>());
+ let findings = audit_redactions(&doc).expect("audit must run");
+ assert_eq!(findings.len(), 1, "{findings:?}");
+ assert!(findings[0].covered_text.contains("SECRET"), "{findings:?}");
+}
+
+/// Many covers over the same long line repeat its text in every finding: a small file must not
+/// expand into an unbounded report. Past the budget the audit fails rather than truncate.
+#[test]
+fn covered_text_across_findings_is_bounded() {
+ let text = "X".repeat(60_000);
+ let mut content = format!("BT /F1 1 Tf 0 700 Td ({text}) Tj ET\n0 g\n").into_bytes();
+ for i in 0..1_200 {
+ content.extend_from_slice(format!("-{i} 690 50000 20 re f\n").as_bytes());
+ }
+ let result = audit_redactions(&open(one_page(&content, "")));
+ assert!(matches!(result, Err(crate::AuditError::TooMuchOutput)), "{:?}", result.map(|f| f.len()));
+}
+
+/// Covers compared against lines are bounded per page, so content that is quadratic in its
+/// covers and lines fails the audit instead of running for hours. A line costs one comparison per
+/// word: 20 covers against 20 two-word lines are 800.
+#[test]
+fn cover_and_line_comparisons_are_bounded() {
+ let mut content = Vec::new();
+ for i in 0..20 {
+ content.extend_from_slice(format!("BT /F1 12 Tf 72 {} Td (Line {i}) Tj ET\n", 700 - 14 * i).as_bytes());
+ }
+ for _ in 0..20 {
+ content.extend_from_slice(b"1 g 0 0 10 10 re f\n");
+ }
+ let doc = open(one_page(&content, ""));
+ let limits = crate::Limits { comparisons: 799, covered_text: usize::MAX };
+ assert!(matches!(crate::audit(&doc, limits), Err(crate::AuditError::TooManyComparisons)));
+ let limits = crate::Limits { comparisons: 800, covered_text: usize::MAX };
+ assert!(crate::audit(&doc, limits).expect("within the budget").is_empty());
+}
+
+/// Covered text is document text: a document whose permissions withhold copying reports where
+/// its covers are but not what they hide, unless it was opened with the owner password.
+#[test]
+fn copy_restricted_documents_withhold_covered_text() {
+ let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n0 g\n100 688 220 32 re f\n";
+ let mut doc = open(one_page(content, ""));
+ doc.set_encryption(&pdfcraft_cos::NewEncryption {
+ algorithm: pdfcraft_cos::Algorithm::Aes256,
+ user_password: "",
+ owner_password: "owner",
+ permissions: -1 ^ 0b1_0000,
+ encrypt_metadata: true,
+ seed: [7; 32],
+ })
+ .expect("encrypt");
+ let bytes = Arc::new(pdfcraft_cos::write_full(&doc, &Default::default()).expect("save"));
+ let user = Document::open_with_password(bytes.clone(), None).expect("open");
+ let findings = audit_redactions(&user).expect("audit must run");
+ assert_eq!(findings.len(), 1, "the cover is still reported: {findings:?}");
+ assert_eq!(findings[0].covered_text, "");
+ // The output bound counts the text reported, so withheld text costs nothing.
+ let nothing = crate::Limits { comparisons: usize::MAX, covered_text: 0 };
+ assert_eq!(crate::audit(&user, nothing).expect("withheld text is not output").len(), 1);
+ let owner = Document::open_with_password(bytes, Some("owner")).expect("open");
+ let findings = audit_redactions(&owner).expect("audit must run");
+ assert_eq!(findings.len(), 1, "{findings:?}");
+ assert_eq!(findings[0].covered_text, "SECRET DATA 123");
+ let exact = crate::Limits { comparisons: usize::MAX, covered_text: "SECRET DATA 123".len() };
+ assert!(crate::audit(&owner, exact).is_ok());
+ let short = crate::Limits { covered_text: exact.covered_text - 1, ..exact };
+ assert!(matches!(crate::audit(&owner, short), Err(crate::AuditError::TooMuchOutput)));
+}
+
+/// Withheld text is never assembled: covers over one long line would otherwise copy the line once
+/// per cover, a volume neither the comparison nor the output bound charges.
+#[test]
+fn withheld_covered_text_is_not_assembled() {
+ let doc = open(one_page(b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n", ""));
+ let lines = pdfcraft_edit::text_lines(&doc, 0).expect("text");
+ let mut budget = crate::Budget { limits: crate::Limits::DEFAULT, comparisons: 0, page_cost: 0, covered_text: 0 };
+ budget.start_page(&lines);
+ let withheld = budget.hidden_text(&lines, false, |_| true).expect("within the budget");
+ assert_eq!(withheld.map(|t| t.capacity()), Some(0), "a finding, with no text built for it");
+ assert_eq!(budget.hidden_text(&lines, false, |_| false).expect("within the budget"), None);
+ let copied = budget.hidden_text(&lines, true, |_| true).expect("within the budget");
+ assert_eq!(copied.as_deref(), Some("SECRET DATA 123"));
+}
++
+ #[test]
+ fn repeated_stream_references_share_one_decode_budget() {
+ use pdfcraft_cos::{Dict, Document, Object, Stream};
+ // One 1 MiB stream of spaces (a kilobyte on disk), named 300 times: by the page's /Contents,
+ // and by 300 draws of a form holding it.
+ let mut doc = Document::new_empty();
+ let spaces = doc.add(Stream::flate(Dict::new(), &vec![b' '; 1 << 20]));
+ let contents: Dict = [(b"Contents".to_vec(), Object::Array(vec![Object::Ref(spaces); 300]))].into_iter().collect();
+ assert!(crate::cover::filled_rects(&doc, &contents).is_err(), "repeated content streams");
+
+ let form_dict: Dict = [(b"Subtype".to_vec(), Object::Name(b"Form".to_vec()))].into_iter().collect();
+ let form = doc.add(Stream::flate(form_dict, &vec![b' '; 1 << 20]));
+ let draws = doc.add(Stream::from_raw(Dict::new(), "/X Do ".repeat(300).into_bytes()));
+ let xobjects: Dict = [(b"X".to_vec(), Object::Ref(form))].into_iter().collect();
+ let resources: Dict = [(b"XObject".to_vec(), Object::Dict(xobjects))].into_iter().collect();
+ let page: Dict = [(b"Contents".to_vec(), Object::Ref(draws)), (b"Resources".to_vec(), Object::Dict(resources))].into_iter().collect();
+ assert!(crate::cover::filled_rects(&doc, &page).is_err(), "repeated form draws");
+ }
+
+ #[test]
+ fn form_entries_past_the_page_allowance_fail_the_audit() {
+ use pdfcraft_cos::{Dict, Document, Object, Stream};
+ // An empty form decodes to no bytes, so only the count of entries bounds drawing it again.
+ let mut doc = Document::new_empty();
+ let form_dict: Dict = [(b"Subtype".to_vec(), Object::Name(b"Form".to_vec()))].into_iter().collect();
+ let form = doc.add(Stream::from_raw(form_dict, Vec::new()));
+ let draws = doc.add(Stream::from_raw(Dict::new(), "/X Do ".repeat(pdfcraft_cos::MAX_PAGE_FORMS + 1).into_bytes()));
+ let xobjects: Dict = [(b"X".to_vec(), Object::Ref(form))].into_iter().collect();
+ let resources: Dict = [(b"XObject".to_vec(), Object::Dict(xobjects))].into_iter().collect();
+ let page: Dict = [(b"Contents".to_vec(), Object::Ref(draws)), (b"Resources".to_vec(), Object::Dict(resources))].into_iter().collect();
+ assert!(matches!(crate::cover::filled_rects(&doc, &page), Err(crate::AuditError::TooManyForms)));
+ }