PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
fix(redact): apply redactions on a copy so a failure leaves the document as it was
aiongg0d216199b9df
diff --git a/crates/redact/src/lib.rs b/crates/redact/src/lib.rsindex fce9f432a..00fbbbd17 100644--- a/crates/redact/src/lib.rs+++ b/crates/redact/src/lib.rs@@ -357,10 +357,17 @@ fn localize_resources(doc: &mut Document, selected: &[usize]) -> Result<(), pdfc////// # Errors///-/// This operation is not transactional: an error may leave `doc` partially modified, with-/// sensitive content still present. Call this on a working clone and replace the original only-/// on success. On any error, discard the working clone; do not save or reuse it.+/// On any error `doc` is left as it was: the redaction runs on a copy (cheap: unchanged objects+/// are shared) that replaces `doc` only on success.pub fn apply(doc: &mut Document, pages: Option<&[usize]>) -> Result<Report, RedactError> {+ let mut work = doc.clone();+ let report = apply_to(&mut work, pages)?;+ *doc = work;+ Ok(report)+}++/// [`apply`] without the copy: an error can leave `doc` part redacted.+fn apply_to(doc: &mut Document, pages: Option<&[usize]>) -> Result<Report, RedactError> {let (all_marks, unreadable) = marks_checked(doc);// A mark with no readable area is not applied, and applying the others would look complete:// refuse before anything changes. Only the pages being applied count.diff --git a/crates/redact/src/tests.rs b/crates/redact/src/tests.rsindex 2478e0b31..e29cd9979 100644--- a/crates/redact/src/tests.rs+++ b/crates/redact/src/tests.rs@@ -1690,8 +1690,8 @@ fn bluefin_survives(doc: &Document) -> bool {/// #3285 review (the maintainer's probes): an element written in place in the parent tree that/// owns the redacted text can't be changed, so applying is refused; the same element as an object-/// of its own is cleaned, and nothing of the word is left in a full rewrite.-/// Refusal does not promise rollback: direct callers discard the failed working copy.+/// of its own is cleaned, and nothing of the word is left in a full rewrite. A refusal leaves the+/// document as it was.#[test]fn an_element_written_in_place_owning_redacted_text_is_refused() {let objs = |element: &str| -> Vec<Vec<u8>> {@@ -1711,17 +1711,13 @@ fn an_element_written_in_place_owning_redacted_text_is_refused() {let mut doc = pdf(objs("<< /Type /StructElem /S /P /P 6 0 R /Pg 3 0 R /K 0 /ActualText (Codename Bluefin) >>"));mark(&mut doc, 0, &[[10.0, 140.0, 290.0, 170.0]], "");let before = write_full(&doc, &SaveOptions::default()).unwrap();- let mut working = doc.clone();- let error = apply(&mut working, None).unwrap_err();+ let error = apply(&mut doc, None).unwrap_err();assert!(matches!(error, RedactError::Tags));assert_eq!(error.to_string(),"the document's tags can't be cleaned completely (an element written in place, or a structure tree too large or too deep to follow); the operation was refused");- assert!(!content(&working, 0).contains("Bluefin"), "the failed working copy was partially changed");- assert!(bluefin_survives(&working), "the failed working copy still holds the word in its tags");- drop(working);- assert_eq!(write_full(&doc, &SaveOptions::default()).unwrap(), before, "discarding the working copy preserves the original");+ assert_eq!(write_full(&doc, &SaveOptions::default()).unwrap(), before, "the refused document is unchanged");let mut doc = pdf(objs("7 0 R"));mark(&mut doc, 0, &[[10.0, 140.0, 290.0, 170.0]], "");let r = apply(&mut doc, None).unwrap();@@ -2745,3 +2741,24 @@ fn content_and_forms_share_one_budget_per_page() {mark(&mut doc, 0, &[[0.0, 90.0, 50.0, 120.0]], "");assert!(apply(&mut doc, None).is_err(), "the form past the page's allowance was read");}++/// A page that fails to read after another page was already redacted leaves the whole document as+/// it was, the shared resources the first page's rewrite localised included.+#[test]+fn a_failure_on_a_later_page_leaves_the_document_unchanged() {+ let mut doc = two_pages_one_resource_dictionary(true, false);+ let all = pdfcraft_model::pages(&doc);+ let (first, second, parent) = (all[0].obj, all[1].obj, doc.get(all[0].obj).as_dict().unwrap().reference(b"Parent").unwrap());+ let mut dct = Dict::new();+ dct.set(b"Filter".to_vec(), Object::name("DCTDecode"));+ let bad = doc.add(Object::Stream(Stream::from_raw(dct, b"garbage".to_vec())));+ doc.update_dict(second, |d| d.set(b"Contents".to_vec(), Object::Ref(bad))).unwrap();+ mark(&mut doc, 0, &[[0.0, 0.0, 300.0, 300.0]], "");+ mark(&mut doc, 1, &[[0.0, 0.0, 50.0, 50.0]], "");+ let before: Vec<Object> = [first, second, parent].iter().map(|r| (*doc.get(*r)).clone()).collect();+ let text = content(&doc, 0);+ assert_eq!(apply(&mut doc, None), Err(RedactError::Unreadable(2)));+ let after: Vec<Object> = [first, second, parent].iter().map(|r| (*doc.get(*r)).clone()).collect();+ assert_eq!(after, before);+ assert_eq!(content(&doc, 0), text);+}