Skip to content

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

M8: redaction clears tag text of elements reached only through the parent or ID tree, and fails closed past the walk limit (#3302)

mtlcl410ce3c0e46c983
diff --git a/crates/redact/src/tags.rs b/crates/redact/src/tags.rs
index 2923061b0..a0883ad6a 100644
--- a/crates/redact/src/tags.rs
+++ b/crates/redact/src/tags.rs
@@ -103,6 +103,20 @@ pub(crate) fn clean(
stream: Option<(ObjRef, ObjRef)>,
changed: &HashSet<i64>,
empty: &HashSet<i64>,
+) -> Result<usize, pdfcraft_cos::CosError> {
+ clean_within(doc, page, stream, changed, empty, MAX_STRUCT_REFS)
+}
+
+/// [`clean`], visiting at most `limit` structure-tree references. A tree too large to walk in full
+/// could hide an element that repeats the redacted text, so then every element in the document
+/// loses its alternate and actual text instead (fail-closed, #3302).
+pub(crate) fn clean_within(
+ doc: &mut Document,
+ page: ObjRef,
+ stream: Option<(ObjRef, ObjRef)>,
+ changed: &HashSet<i64>,
+ empty: &HashSet<i64>,
+ limit: usize,
) -> Result<usize, pdfcraft_cos::CosError> {
if changed.is_empty() && stream.is_none() {
return Ok(0);
@@ -114,17 +128,25 @@ pub(crate) fn clean(
else {
return Ok(0);
};
- // Indirect elements with the page they inherit.
- let mut todo: Vec<(Object, Option<ObjRef>)> = root.get(b"K").map(|k| vec![(k.clone(), None)]).unwrap_or_default();
+ // Indirect elements with the page they inherit. Elements are reached from the root's /K, and
+ // also from the parent tree and the ID tree: one listed only there still owns marked content
+ // (#3302).
+ let mut todo: Vec<(Object, Option<ObjRef>)> =
+ [&b"K"[..], b"ParentTree", b"IDTree"].iter().filter_map(|key| root.get(key).cloned()).map(|k| (k, None)).collect();
let mut seen = HashSet::new();
let mut hits: Vec<(ObjRef, Dict, Option<ObjRef>, bool)> = Vec::new();
while let Some((k, pg)) = todo.pop() {
match k {
Object::Array(a) => todo.extend(a.into_iter().map(|x| (x, pg))),
+ // A number or name tree node written in place.
+ Object::Dict(d) if !d.contains(b"S") => todo.extend(tree_node_entries(&d).into_iter().map(|x| (x, pg))),
Object::Ref(r) => {
- if !seen.insert(r) || seen.len() > 2_000_000 {
+ if !seen.insert(r) {
continue;
}
+ if seen.len() > limit {
+ return clear_every_element(doc);
+ }
let object = doc.get(r);
if let Object::Array(a) = &*object {
todo.extend(a.iter().cloned().map(|x| (x, pg)));
@@ -132,6 +154,8 @@ pub(crate) fn clean(
}
let Some(d) = object.as_dict().cloned() else { continue };
if !d.contains(b"S") {
+ // A parent tree or ID tree node: its values may be elements.
+ todo.extend(tree_node_entries(&d).into_iter().map(|x| (x, pg)));
continue;
}
let pg = d.get(b"Pg").and_then(Object::as_ref).or(pg);
@@ -203,6 +227,30 @@ pub(crate) fn clean(
Ok(n)
}
+/// The fail-closed end of a walk that couldn't finish: every structure element in the document,
+/// found by reading each object rather than through the tree, loses the text that could repeat
+/// redacted words. Returns how many elements changed.
+fn clear_every_element(doc: &mut Document) -> Result<usize, pdfcraft_cos::CosError> {
+ let keys = [&b"Alt"[..], b"ActualText", b"E"];
+ let elements: Vec<ObjRef> = doc
+ .scan_objects()
+ .filter(|(_, o)| {
+ o.as_dict().is_some_and(|d| {
+ (d.name(b"Type") == Some(b"StructElem") || (d.contains(b"S") && d.contains(b"P"))) && keys.iter().any(|k| d.contains(k))
+ })
+ })
+ .map(|(r, _)| r)
+ .collect();
+ for &r in &elements {
+ doc.update_dict(r, |e| {
+ for key in keys {
+ e.remove(key);
+ }
+ })?;
+ }
+ Ok(elements.len())
+}
+
/// Whether `o` is an object reference (`/Type /OBJR`, direct or indirect) to one of `gone`.
fn refers_to(doc: &Document, o: &Object, gone: &HashSet<ObjRef>) -> bool {
doc.resolve(o)
diff --git a/crates/redact/src/tests.rs b/crates/redact/src/tests.rs
index 47b4d19da..f25ac197a 100644
--- a/crates/redact/src/tests.rs
+++ b/crates/redact/src/tests.rs
@@ -842,6 +842,63 @@ fn a_structure_tree_too_large_to_walk_is_removed_whole() {
assert!(!bytes.windows(14).any(|w| w == b"secret.example"), "the removed link can't be reached any more");
}
+/// #3302: an element listed only in the parent tree (not under the root's /K) still owns the
+/// marked content redaction changed, so its /ActualText and /Alt, which repeat the redacted
+/// words, go as they do for an element under /K.
+#[test]
+fn an_element_listed_only_in_the_parent_tree_loses_its_redacted_text() {
+ let objs: Vec<Vec<u8>> = vec![
+ b"<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 5 0 R /MarkInfo << /Marked true >> >>".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 /StructParents 0 /Resources << /Font << /F1 9 0 R >> >> >>".to_vec(),
+ stream("", b"/P <</MCID 0>> BDC BT /F1 14 Tf 20 150 Td (Codename Bluefin) Tj ET EMC"),
+ // The root's /K reaches only the empty document element 6; the paragraph 7 is in the
+ // parent tree only.
+ b"<< /Type /StructTreeRoot /K 6 0 R /ParentTree << /Nums [0 [7 0 R]] >> /ParentTreeNextKey 1 >>".to_vec(),
+ b"<< /Type /StructElem /S /Document /P 5 0 R >>".to_vec(),
+ b"<< /Type /StructElem /S /P /P 6 0 R /Pg 3 0 R /K 0 /ActualText (Codename Bluefin) /Alt (Codename Bluefin) >>".to_vec(),
+ b"<< /Type /StructElem /S /Note /P 6 0 R >>".to_vec(),
+ b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".to_vec(),
+ ];
+ let mut doc = pdf(objs);
+ mark(&mut doc, 0, &[[10.0, 140.0, 290.0, 170.0]], "");
+ let r = apply(&mut doc, None).unwrap();
+ assert!(r.glyphs > 0 && r.tags >= 1, "{r:?}");
+ let element = doc.get(ObjRef::new(7, 0)).as_dict().cloned().unwrap();
+ assert!(!element.contains(b"ActualText") && !element.contains(b"Alt"), "{element:?}");
+}
+
+/// #3302: a structure tree too large to walk in full fails closed: every element loses its
+/// alternate and actual text, found by reading each object, instead of the walk stopping and
+/// reporting success with elements never checked.
+#[test]
+fn a_tag_walk_cut_short_clears_every_element() {
+ let objs: Vec<Vec<u8>> = vec![
+ b"<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 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] /StructParents 0 >>".to_vec(),
+ b"<< >>".to_vec(),
+ b"<< /Type /StructTreeRoot /K 6 0 R >>".to_vec(),
+ b"<< /Type /StructElem /S /Document /P 5 0 R /K [7 0 R 8 0 R] >>".to_vec(),
+ b"<< /Type /StructElem /S /P /P 6 0 R /Pg 3 0 R /K 0 /ActualText (Codename Bluefin) >>".to_vec(),
+ b"<< /Type /StructElem /S /Figure /P 6 0 R /Alt (A chart) /E (chart) >>".to_vec(),
+ ];
+ let page = ObjRef::new(3, 0);
+ let changed: std::collections::HashSet<i64> = [0].into();
+ let mut doc = pdf(objs.clone());
+ crate::tags::clean_within(&mut doc, page, None, &changed, &Default::default(), 100).unwrap();
+ let figure = doc.get(ObjRef::new(8, 0)).as_dict().cloned().unwrap();
+ assert!(figure.contains(b"Alt"), "a walk that finishes keeps an unrelated element's text");
+
+ let mut doc = pdf(objs);
+ let n = crate::tags::clean_within(&mut doc, page, None, &changed, &Default::default(), 1).unwrap();
+ assert_eq!(n, 2, "both elements with text change");
+ for r in [7, 8] {
+ let e = doc.get(ObjRef::new(r, 0)).as_dict().cloned().unwrap();
+ assert!(!e.contains(b"ActualText") && !e.contains(b"Alt") && !e.contains(b"E"), "{r}: {e:?}");
+ }
+}
+
/// #2532 follow-up: an element reached only through the parent tree or the ID tree, not from
/// the root's /K, still points at a removed annotation, and the root keeps it reachable in a full
/// rewrite. Both trees are walked too, written in place or as their own objects.