PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
M8: Applying redactions cleans the tags: elements of changed marked content lose Alt/ActualText/E, empty marked content leaves them
Brandon Thomas294cbd671676
diff --git a/crates/redact/src/lib.rs b/crates/redact/src/lib.rsindex 1ca84454c..069d0604a 100644--- a/crates/redact/src/lib.rs+++ b/crates/redact/src/lib.rs@@ -19,6 +19,7 @@ mod image;mod interp;pub mod patterns;pub mod sanitize;+mod tags;#[cfg(test)]mod tests;@@ -102,6 +103,8 @@ pub struct Report {pub forms_removed: usize,pub annotations: usize,pub fields: usize,+ /// Structure elements that lost alternate/actual text or emptied marked content.+ pub tags: usize,}fn rect_of(doc: &Document, o: Option<&Object>) -> Option<[f64; 4]> {@@ -311,6 +314,11 @@ pub fn apply(doc: &mut Document, pages: Option<&[usize]>) -> Result<Report, Redad.set(b"Contents".to_vec(), Object::Array(new_list));d.set(b"Resources".to_vec(), Object::Dict(res));})?;+ // Tags must not keep what the page no longer shows.+ let after = doc.get(page.obj).as_dict().cloned().unwrap_or_default();+ let (_, new_data) = page_streams(doc, &after, pi)?;+ let (changed_ids, empty_ids) = tags::touched(&data.join(&b'\n'), &new_data.join(&b'\n'));+ report.tags += tags::clean(doc, page.obj, &changed_ids, &empty_ids)?;}// 2. Annotations: the marks, and whatever lies under them (with their pop-ups).diff --git a/crates/redact/src/tags.rs b/crates/redact/src/tags.rsnew file mode 100644index 000000000..5df296a4f--- /dev/null+++ b/crates/redact/src/tags.rs@@ -0,0 +1,156 @@+//! Redaction and the structure tree: tags must not keep what was removed from the page.+//!+//! Marked content (MCIDs) that applying redactions changed is found by comparing each MCID's+//! operators before and after. Elements owning such content lose their alternate text, actual+//! text and expansion (which may spell out the removed words); references to marked content that+//! is now empty are dropped from the element.++use std::collections::{HashMap, HashSet};++use printcraft_cos::{Dict, Document, ObjRef, Object};++/// Each MCID's operators (serialized), and whether anything is still drawn inside it.+fn by_mcid(data: &[u8]) -> HashMap<i64, (Vec<u8>, bool)> {+ let mut out: HashMap<i64, (Vec<u8>, bool)> = HashMap::new();+ let mut stack: Vec<Option<i64>> = Vec::new();+ for op in printcraft_content::parse(data).ops {+ match op.op.as_slice() {+ b"BDC" => {+ let id = match op.operands.get(1) {+ Some(Object::Dict(d)) => d.get(b"MCID").and_then(Object::as_int),+ _ => None,+ };+ if let Some(id) = id {+ out.entry(id).or_default();+ }+ stack.push(id);+ continue;+ }+ b"BMC" => {+ stack.push(None);+ continue;+ }+ b"EMC" => {+ stack.pop();+ continue;+ }+ _ => {}+ }+ let draws = match op.op.as_slice() {+ b"Tj" | b"'" | b"\"" => op.operands.last().and_then(Object::as_string).is_some_and(|s| !s.bytes.is_empty()),+ b"TJ" => {+ op.operands.first().and_then(Object::as_array).is_some_and(|a| a.iter().any(|x| x.as_string().is_some_and(|s| !s.bytes.is_empty())))+ }+ b"f" | b"F" | b"f*" | b"B" | b"B*" | b"b" | b"b*" | b"S" | b"s" | b"sh" | b"Do" | b"BI" => true,+ _ => false,+ };+ let mut bytes = Vec::new();+ printcraft_content::write_op(&op, &mut bytes);+ for id in stack.iter().flatten() {+ let e = out.entry(*id).or_default();+ e.0.extend_from_slice(&bytes);+ e.1 |= draws;+ }+ }+ out+}++/// The MCIDs whose content changed between `before` and `after`, and those left empty.+pub(crate) fn touched(before: &[u8], after: &[u8]) -> (HashSet<i64>, HashSet<i64>) {+ let (b, a) = (by_mcid(before), by_mcid(after));+ let mut changed = HashSet::new();+ let mut empty = HashSet::new();+ for (id, (ops, _)) in &b {+ match a.get(id) {+ Some((new, draws)) => {+ if new != ops {+ changed.insert(*id);+ }+ if !draws {+ empty.insert(*id);+ }+ }+ None => {+ changed.insert(*id);+ empty.insert(*id);+ }+ }+ }+ (changed, empty)+}++fn mcid_of(o: &Object, page: Option<ObjRef>, target: ObjRef) -> Option<i64> {+ match o {+ Object::Int(n) if page == Some(target) => Some(*n),+ Object::Dict(m) if m.name(b"Type") == Some(b"MCR") => {+ let pg = m.get(b"Pg").and_then(Object::as_ref).or(page);+ (pg == Some(target)).then(|| m.get(b"MCID").and_then(Object::as_int)).flatten()+ }+ _ => None,+ }+}++/// Clean the elements owning `changed` marked content on `page`; returns how many changed.+pub(crate) fn clean(doc: &mut Document, page: ObjRef, changed: &HashSet<i64>, empty: &HashSet<i64>) -> Result<usize, printcraft_cos::CosError> {+ if changed.is_empty() {+ return Ok(0);+ }+ let Some(root) = doc+ .root()+ .and_then(|r| doc.get(r).as_dict().cloned())+ .and_then(|c| c.get(b"StructTreeRoot").map(|s| doc.resolve(s)).and_then(|s| s.as_dict().cloned()))+ 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();+ let mut seen = HashSet::new();+ let mut hits: Vec<(ObjRef, Dict, Option<ObjRef>)> = Vec::new();+ while let Some((k, pg)) = todo.pop() {+ match k {+ Object::Array(a) => todo.extend(a.into_iter().map(|x| (x, pg))),+ Object::Ref(r) => {+ if !seen.insert(r) || seen.len() > 2_000_000 {+ continue;+ }+ let Some(d) = doc.get(r).as_dict().cloned() else { continue };+ if !d.contains(b"S") {+ continue;+ }+ let pg = d.get(b"Pg").and_then(Object::as_ref).or(pg);+ let kids: Vec<Object> = match d.get(b"K") {+ Some(Object::Array(a)) => a.clone(),+ Some(o) => vec![o.clone()],+ None => Vec::new(),+ };+ if kids.iter().any(|x| mcid_of(x, pg, page).is_some_and(|m| changed.contains(&m))) {+ hits.push((r, d.clone(), pg));+ }+ todo.extend(kids.into_iter().map(|x| (x, pg)));+ }+ _ => {}+ }+ }+ let mut n = 0;+ for (r, d, pg) in hits {+ let kids = d.get(b"K").cloned();+ doc.update_dict(r, |e| {+ for key in [&b"Alt"[..], b"ActualText", b"E"] {+ e.remove(key);+ }+ // Marked content that is now empty no longer belongs to the element.+ match kids {+ Some(Object::Array(a)) => {+ let keep: Vec<Object> = a.into_iter().filter(|x| !mcid_of(x, pg, page).is_some_and(|m| empty.contains(&m))).collect();+ e.set(b"K".to_vec(), Object::Array(keep));+ }+ Some(o) if mcid_of(&o, pg, page).is_some_and(|m| empty.contains(&m)) => {+ e.remove(b"K");+ }+ _ => {}+ }+ })?;+ n += 1;+ }+ Ok(n)+}diff --git a/crates/redact/src/tests.rs b/crates/redact/src/tests.rsindex 4ca27394f..21c87f1ad 100644--- a/crates/redact/src/tests.rs+++ b/crates/redact/src/tests.rs@@ -376,3 +376,29 @@ fn overlay_text_takes_its_font_size_colour_alignment_and_repeats() {.unwrap();assert!(fonts.contains(b"PCCour") && !fonts.contains(b"PCTimes"));}++#[test]+fn tags_lose_what_redaction_removed() {+ let content = b"/P <</MCID 0>> BDC BT /F1 10 Tf 10 200 Td (SECRET) Tj ET EMC /P <</MCID 1>> BDC BT /F1 10 Tf 10 100 Td (Public) Tj ET EMC";+ let mut doc = pdf(vec![+ b"<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 7 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 5 0 R >> >> >>".to_vec(),+ stream("", content),+ FONT.replace("95 0 R", "6 0 R").into_bytes(),+ widths(),+ b"<< /Type /StructTreeRoot /K 8 0 R >>".to_vec(),+ b"<< /S /Document /P 7 0 R /K [9 0 R 10 0 R] >>".to_vec(),+ b"<< /S /P /P 8 0 R /Pg 3 0 R /ActualText (SECRET) /Alt (the secret) /K 0 >>".to_vec(),+ b"<< /S /P /P 8 0 R /Pg 3 0 R /ActualText (Public) /K 1 >>".to_vec(),+ ]);+ mark(&mut doc, 0, &[[5.0, 195.0, 60.0, 212.0]], "");+ let report = apply(&mut doc, None).unwrap();+ assert_eq!(report.tags, 1);+ let secret = doc.get(printcraft_cos::ObjRef::new(9, 0)).as_dict().cloned().unwrap();+ assert!(secret.get(b"ActualText").is_none() && secret.get(b"Alt").is_none());+ assert!(secret.get(b"K").is_none(), "its marked content is empty now");+ let public = doc.get(printcraft_cos::ObjRef::new(10, 0)).as_dict().cloned().unwrap();+ assert_eq!(public.get(b"K").and_then(Object::as_int), Some(1));+ assert!(public.get(b"ActualText").is_some(), "untouched content keeps its tags");+}diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.tomlindex 076540939..d20971f7d 100644--- a/parity/acrobat-features.toml+++ b/parity/acrobat-features.toml@@ -5611,11 +5611,11 @@ title = "Remove redacted content from tags and alternate text"area = "G"tier = "P0"milestone = "M8"-status = "planned"-commands = []-tools = []-evidence = []-notes = ""+status = "shipped"+commands = ["redact.apply"]+tools = ["redact_apply"]+evidence = ["crates/redact/src/tests.rs::tags_lose_what_redaction_removed"]+notes = "marked content changed by redaction is found by comparing each MCID before and after; its elements lose Alt, ActualText and E, and references to now-empty marked content are dropped; untouched tags stay"[[feature]]id = "protect.redaction-verification"