Skip to content

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

Merge main into fix/coderabbit-a1-audit

Dylan M. Taylor7345e5f5de82
diff --cc crates/audit/src/lib.rs
index 98efe2fed,35e90e2e1..f1f135098
--- a/crates/audit/src/lib.rs
+++ b/crates/audit/src/lib.rs
@@@ -101,94 -97,26 +101,96 @@@ const WORD_FRACTION: f64 = 0.5
const COVER_CONTRAST: f64 = 3.0;
/// Audit every page for faux redactions and unapplied redaction marks. Fails closed: any
-/// content that cannot be decoded is returned as an error, never as an empty finding list.
+/// content that cannot be decoded, or that needs more work or report than the audit's bounds, is
+/// returned as an error, never as an empty finding list.
+///
+/// When the document's permissions withhold copying (ISO 32000-2 Table 22, bit 5), findings are
+/// still reported but their `covered_text` is empty: the audit hands out no text that copying
+/// would refuse.
pub fn audit_redactions(doc: &Document) -> Result<Vec<AuditFinding>, AuditError> {
+ audit(doc, Limits::DEFAULT)
+}
+
+/// Work and output bounds for one audit.
+#[derive(Clone, Copy)]
+struct Limits {
+ /// Cover-against-line comparisons per page, counting a line once per word box it has (at
+ /// least once), since [`covers`] walks them.
+ comparisons: usize,
+ /// Bytes of covered text the findings report.
+ covered_text: usize,
+}
+
+impl Limits {
+ /// Every cover is compared with every line of its page, and each finding repeats the text
+ /// it covers, so both grow with the square of the content: a few megabytes of covers over
+ /// one long line would otherwise take hours and gigabytes.
+ const DEFAULT: Limits = Limits { comparisons: 50_000_000, covered_text: 64 << 20 };
+}
+
+/// The work and report the audit has spent against its [`Limits`].
+struct Budget {
+ limits: Limits,
+ comparisons: usize,
+ /// What comparing one cover with every line of the current page costs.
+ page_cost: usize,
+ covered_text: usize,
+}
+
+impl Budget {
+ /// Resets the comparison count for a page with these `lines`.
+ fn start_page(&mut self, lines: &[TextLine]) {
+ self.comparisons = 0;
+ self.page_cost = lines.iter().fold(0, |n, line| n.saturating_add(line.ink.len().max(1)));
+ }
+
+ /// The text of the `lines` that `hides`, joined with single spaces, or `None` when they show
+ /// no text. Without `copying` the text is empty and never assembled: one long line under many
+ /// covers would otherwise be copied once per cover, outside both bounds.
+ fn hidden_text(&mut self, lines: &[TextLine], copying: bool, hides: impl Fn(&TextLine) -> bool) -> Result<Option<String>, AuditError> {
+ self.comparisons = self.comparisons.saturating_add(self.page_cost);
+ if self.comparisons > self.limits.comparisons {
+ return Err(AuditError::TooManyComparisons);
+ }
+ if !copying {
+ return Ok(lines.iter().any(|line| hides(line) && !line.text.trim().is_empty()).then(String::new));
+ }
+ let mut covered = String::new();
+ for line in lines.iter().filter(|l| hides(l)) {
+ if !covered.is_empty() {
+ covered.push(' ');
+ }
+ covered.push_str(line.text.trim());
+ }
+ Ok((!covered.trim().is_empty()).then_some(covered))
+ }
+
+ /// The text a finding reports for `covered`: none when copying is withheld. Charges what it
+ /// reports against the output bound.
+ fn report_text(&mut self, covered: String, copying: bool) -> Result<String, AuditError> {
+ let reported = if copying { covered } else { String::new() };
+ self.covered_text = self.covered_text.saturating_add(reported.len());
+ if self.covered_text > self.limits.covered_text {
+ return Err(AuditError::TooMuchOutput);
+ }
+ Ok(reported)
+ }
+}
+
+fn audit(doc: &Document, limits: Limits) -> Result<Vec<AuditFinding>, AuditError> {
+ let copying = doc.permissions().is_none_or(|p| p.copy());
+ let mut budget = Budget { limits, comparisons: 0, page_cost: 0, covered_text: 0 };
let mut out = Vec::new();
for (n, page) in pdfcraft_model::pages(doc).iter().enumerate() {
- let lines = pdfcraft_edit::text_lines(doc, n).map_err(|e| AuditError::Text(n, e.to_string()))?;
+ // The glyphs themselves: `/ActualText` is the file's own claim about them, and an empty
+ // or substitute one must not hide text a cover sits on.
+ let lines = pdfcraft_edit::glyph_text_lines(doc, page).map_err(|e| AuditError::Text(n, e.to_string()))?;
+ budget.start_page(&lines);
// 1. Opaque filled rectangles over extractable text.
for r in cover::filled_rects(doc, &page.dict)? {
- let mut covered = String::new();
- for line in &lines {
- if is_cover(&r, line) {
- if !covered.is_empty() {
- covered.push(' ');
- }
- covered.push_str(line.text.trim());
- }
- }
- if !covered.trim().is_empty() {
- out.push(AuditFinding { page: n, kind: FindingKind::CoveredText, rect: r.rect, covered_text: covered });
+ if let Some(covered) = budget.hidden_text(&lines, copying, |line| is_cover(&r, line))? {
+ let covered_text = budget.report_text(covered, copying)?;
+ out.push(AuditFinding { page: n, kind: FindingKind::CoveredText, rect: r.rect, covered_text });
}
}
// 2. Annotation covers over extractable text.
diff --cc crates/audit/src/tests.rs
index 3b5c5c8c7,a76536532..3aca406e7
--- a/crates/audit/src/tests.rs
+++ b/crates/audit/src/tests.rs
@@@ -593,138 -593,19 +593,151 @@@ 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"));
+}
+
+ /// `/ActualText` is metadata the file's author controls: an empty or substitute replacement must
+ /// not hide the glyphs a cover sits on.
+ #[test]
+ fn a_cover_over_text_with_empty_or_substitute_actual_text_is_found() {
+ for actual in ["()", "(nothing here)"] {
+ let content =
+ format!("/Span << /ActualText {actual} >> BDC\nBT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\nEMC\n0 g\n100 688 220 32 re f\n");
+ let findings = audit_redactions(&open(one_page(content.as_bytes(), ""))).expect("audit must run");
+ assert_eq!(findings.len(), 1, "{actual}: {findings:?}");
+ assert!(findings[0].covered_text.contains("SECRET"), "{actual}: covered_text was {:?}", findings[0].covered_text);
+ }
+ }
+
#[test]
fn repeated_stream_references_share_one_decode_budget() {
use pdfcraft_cos::{Dict, Document, Object, Stream};