From bd3a9d318ed46f13ac4eb5b27578becd4122a3e7 Mon Sep 17 00:00:00 2001 From: Zach Shallbetter Date: Sat, 17 Oct 2026 21:22:19 -0700 Subject: [PATCH 1/3] audit: track clipping paths, form BBox, and color spaces in redaction cover scan Prevent false-positive faux redactions where drawing occurs outside an active clipping path (re W n), outside a form XObject's /BBox, inside a default-off optional content layer (/OC OFF), or through text clipping modes (Tr 4-7). Also track cs, sc, and scn non-stroking color space operators so dark fills following a white g are not missed. Treat non-rectangular clipping paths and unknown color spaces as fail-closed. Refs #3117, refs #3118 --- crates/audit/src/cover.rs | 250 +++++++++++++++++++++++++++++++++++--- crates/audit/src/tests.rs | 209 +++++++++++++++++++++++++++++++ 2 files changed, 440 insertions(+), 19 deletions(-) diff --git a/crates/audit/src/cover.rs b/crates/audit/src/cover.rs index 3df666c190..60852c3123 100644 --- a/crates/audit/src/cover.rs +++ b/crates/audit/src/cover.rs @@ -4,9 +4,12 @@ //! color (`re` + `f`) is the classic way a "redaction" is faked. A single closed `m`/`l` subpath //! whose four corners form an axis-aligned rectangle in user space is the same shape and counts //! too (#1510). Graphics state tracked here is deliberately small: the CTM stack (`q`/`Q`/`cm`), -//! the non-stroking color (`g`/`rg`/`k`) and the non-stroking alpha from ExtGState (`gs` reading -//! `/ca`). Form XObjects are followed read-only with a depth cap. Anything fancier (other filled paths, shadings, patterns) is -//! out of scope and documented as such. +//! the non-stroking color (`g`/`rg`/`k`, `cs`, `sc`, `scn`, defaulting unknown color spaces to +//! black fail-closed), the clipping state (`re W n`, form `/BBox`, and text clipping modes `Tr 4..=7`), +//! optional content layer visibility (`/OC BDC`/`EMC`), and the non-stroking alpha from ExtGState +//! (`gs` reading `/ca`). Form XObjects are followed read-only with a depth cap. Anything fancier +//! (other filled paths, non-axis-aligned rotations, shadings, patterns) is out of scope and +//! documented as such. //! //! Paint order: a page's content streams are one stream in pieces (ISO 32000-2 §7.8.2), so they //! are parsed joined and walked once with a single graphics state — state set in an earlier @@ -15,8 +18,10 @@ //! the joined stream)`; rectangles inside a form XObject carry the `Do` operator's position. //! Positions compare lexicographically in paint order. +use std::collections::HashSet; + use pdfcraft_content::{Matrix, Op, Pieces, parse}; -use pdfcraft_cos::{Dict, Document, Object}; +use pdfcraft_cos::{Dict, Document, ObjRef, Object}; use crate::AuditError; @@ -39,11 +44,41 @@ pub struct FilledRect { pub pos: (usize, usize), } +/// Active clipping state in page user space. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Clip { + /// No clipping has been applied yet. + None, + /// An axis-aligned clipping rectangle in user space. + Rect([f64; 4]), + /// Text glyph clipping active (`Tr 4..=7`). Fills through this clip paint the text glyphs, not a rectangle cover. + Glyphs, + /// Non-rectangular or complex clipping path (fail-closed: do not prune candidate covers). + Unknown, +} + +impl Clip { + fn intersect_rect(self, r: [f64; 4]) -> Clip { + match self { + Clip::None => Clip::Rect(r), + Clip::Rect(c) => match intersect(c, r) { + Some(cr) => Clip::Rect(cr), + None => Clip::Rect([0.0, 0.0, 0.0, 0.0]), + }, + Clip::Glyphs => Clip::Glyphs, + Clip::Unknown => Clip::Unknown, + } + } +} + #[derive(Clone)] struct Gs { ctm: Matrix, fill: [f64; 3], alpha: f64, + clip: Clip, + tr: u32, + space: usize, } /// The path under construction, as far as the audit cares about it. @@ -59,9 +94,9 @@ enum Path { impl Path { /// The rectangle a fill of this path paints, if the path is one. - fn rect(self) -> Option<[f64; 4]> { + fn rect(&self) -> Option<[f64; 4]> { match self { - Path::Rect(r) => Some(r), + Path::Rect(r) => Some(*r), Path::Lines(pts, _) => lines_rect(pts), Path::Empty | Path::Other => None, } @@ -71,14 +106,12 @@ impl Path { /// The bounding box of a closed polygon that is an axis-aligned rectangle, or `None`. A repeated /// start point is dropped first; the remaining four corners must alternate horizontal and /// vertical edges. -fn lines_rect(mut pts: Vec<[f64; 2]>) -> Option<[f64; 4]> { +fn lines_rect(pts: &[[f64; 2]]) -> Option<[f64; 4]> { // CTM products leave rounding noise, so corners compare with a tolerance (in points). const EPS: f64 = 1e-6; let same = |a: f64, b: f64| (a - b).abs() <= EPS; - if pts.len() == 5 && same(pts[0][0], pts[4][0]) && same(pts[0][1], pts[4][1]) { - pts.pop(); - } - let [a, b, c, d] = <[[f64; 2]; 4]>::try_from(pts).ok()?; + let slice = if pts.len() == 5 && same(pts[0][0], pts[4][0]) && same(pts[0][1], pts[4][1]) { pts.get(..4)? } else { pts }; + let [a, b, c, d] = <[[f64; 2]; 4]>::try_from(slice).ok()?; let fits = |first_horizontal: bool| { [(a, b), (b, c), (c, d), (d, a)] .iter() @@ -98,9 +131,19 @@ fn lines_rect(mut pts: Vec<[f64; 2]>) -> Option<[f64; 4]> { (r[2] - r[0] > EPS && r[3] - r[1] > EPS).then_some(r) } +fn axis_aligned(m: &Matrix) -> bool { + let [a, b, c, d, ..] = m.0; + (b.abs() < 1e-9 && c.abs() < 1e-9) || (a.abs() < 1e-9 && d.abs() < 1e-9) +} + +fn intersect(a: [f64; 4], b: [f64; 4]) -> Option<[f64; 4]> { + let r = [a[0].max(b[0]), a[1].max(b[1]), a[2].min(b[2]), a[3].min(b[3])]; + (r.iter().all(|v| v.is_finite()) && r[2] > r[0] && r[3] > r[1]).then_some(r) +} + impl Default for Gs { fn default() -> Self { - Gs { ctm: Matrix::IDENTITY, fill: [0.0, 0.0, 0.0], alpha: 1.0 } + Gs { ctm: Matrix::IDENTITY, fill: [0.0, 0.0, 0.0], alpha: 1.0, clip: Clip::None, tr: 0, space: 1 } } } @@ -109,6 +152,8 @@ struct Walker<'a> { pieces: &'a Pieces, out: Vec, ops_seen: usize, + off_layers: HashSet, + oc_hidden_depth: usize, } impl<'a> Walker<'a> { @@ -133,6 +178,7 @@ impl<'a> Walker<'a> { at_do: Option<(usize, usize)>, ) -> Result<(), AuditError> { let mut path = Path::Empty; + let mut clip_next = false; for (i, op) in ops.iter().enumerate() { self.bump()?; // Paint position of this operator: its own `(piece, joined index)` at page level, @@ -148,6 +194,7 @@ impl<'a> Walker<'a> { *gs = g; } path = Path::Empty; + clip_next = false; } b"cm" => { let before = gs.ctm; @@ -163,12 +210,14 @@ impl<'a> Walker<'a> { } } b"g" => { + gs.space = 1; if let Some(v) = op.num(0).filter(|v| v.is_finite()) { let v = v.clamp(0.0, 1.0); gs.fill = [v, v, v]; } } b"rg" => { + gs.space = 3; if let Some([r, g, b]) = op.nums::<3>() && [r, g, b].iter().all(|v| v.is_finite()) { @@ -176,6 +225,7 @@ impl<'a> Walker<'a> { } } b"k" => { + gs.space = 4; if let Some([c, m, y, k]) = op.nums::<4>() && [c, m, y, k].iter().all(|v| v.is_finite()) { @@ -184,6 +234,43 @@ impl<'a> Walker<'a> { gs.fill = [(1.0 - c) * (1.0 - k), (1.0 - m) * (1.0 - k), (1.0 - y) * (1.0 - k)]; } } + b"cs" => { + if let Some(name) = op.name(0) { + gs.space = match name { + b"DeviceGray" => 1, + b"DeviceRGB" => 3, + b"DeviceCMYK" => 4, + _ => 0, + }; + gs.fill = [0.0, 0.0, 0.0]; + } + } + b"sc" | b"scn" => match gs.space { + 1 => { + if let Some(v) = op.num(0).filter(|v| v.is_finite()) { + let v = v.clamp(0.0, 1.0); + gs.fill = [v, v, v]; + } + } + 3 => { + if let Some([r, g, b]) = op.nums::<3>() + && [r, g, b].iter().all(|v| v.is_finite()) + { + gs.fill = [r.clamp(0.0, 1.0), g.clamp(0.0, 1.0), b.clamp(0.0, 1.0)]; + } + } + 4 => { + if let Some([c, m, y, k]) = op.nums::<4>() + && [c, m, y, k].iter().all(|v| v.is_finite()) + { + let (c, m, y, k) = (c.clamp(0.0, 1.0), m.clamp(0.0, 1.0), y.clamp(0.0, 1.0), k.clamp(0.0, 1.0)); + gs.fill = [(1.0 - c) * (1.0 - k), (1.0 - m) * (1.0 - k), (1.0 - y) * (1.0 - k)]; + } + } + _ => { + gs.fill = [0.0, 0.0, 0.0]; + } + }, b"gs" => { if let Some(name) = op.name(0) { gs.alpha = ext_alpha(self.doc, resources, name); @@ -191,7 +278,7 @@ impl<'a> Walker<'a> { } b"re" => { let rect = op.nums::<4>().and_then(|[x, y, w, h]| { - if [x, y, w, h].iter().all(|v| v.is_finite()) && w != 0.0 && h != 0.0 { + if [x, y, w, h].iter().all(|v| v.is_finite()) && w != 0.0 && h != 0.0 && axis_aligned(&gs.ctm) { let r = gs.ctm.bbox([x.min(x + w), y.min(y + h), x.max(x + w), y.max(y + h)]); (r[2] > r[0] && r[3] > r[1]).then_some(r) } else { @@ -224,16 +311,82 @@ impl<'a> Walker<'a> { _ => Path::Other, }; } + b"W" | b"W*" => clip_next = true, + b"n" => { + if clip_next { + if let Some(r) = path.rect() { + gs.clip = gs.clip.intersect_rect(r); + } else { + gs.clip = Clip::Unknown; + } + clip_next = false; + } + path = Path::Empty; + } // `b`/`b*` close the path before filling it, which the fill does anyway. b"f" | b"F" | b"f*" | b"B" | b"B*" | b"b" | b"b*" => { - if let Some(r) = std::mem::replace(&mut path, Path::Empty).rect() + let p = std::mem::replace(&mut path, Path::Empty); + if clip_next { + if let Some(r) = p.rect() { + gs.clip = gs.clip.intersect_rect(r); + } else { + gs.clip = Clip::Unknown; + } + clip_next = false; + } + if self.oc_hidden_depth == 0 && gs.alpha >= 1.0 + && let Some(r) = p.rect() { - self.out.push(FilledRect { rect: r, rgb: gs.fill, pos }); + let visible_r = match gs.clip { + Clip::None | Clip::Unknown => Some(r), + Clip::Rect(c) => intersect(r, c), + Clip::Glyphs => None, + }; + if let Some(r) = visible_r { + self.out.push(FilledRect { rect: r, rgb: gs.fill, pos }); + } + } + } + b"S" | b"s" => { + if clip_next { + if let Some(r) = path.rect() { + gs.clip = gs.clip.intersect_rect(r); + } else { + gs.clip = Clip::Unknown; + } + clip_next = false; + } + path = Path::Empty; + } + b"c" | b"v" | b"y" => path = Path::Other, + b"Tr" => { + if let Some(mode) = op.num(0).and_then(|v| (v.is_finite() && v >= 0.0).then_some(v as u32)) { + gs.tr = mode; + } + } + b"Tj" | b"TJ" | b"'" | b"\"" => { + if (4..=7).contains(&gs.tr) { + gs.clip = Clip::Glyphs; + } + } + b"BDC" => { + let is_off = + if op.name(0) == Some(b"OC") { is_layer_off(self.doc, resources, &self.off_layers, op.operands.get(1)) } else { false }; + if is_off || self.oc_hidden_depth > 0 { + self.oc_hidden_depth += 1; + } + } + b"BMC" => { + if self.oc_hidden_depth > 0 { + self.oc_hidden_depth += 1; + } + } + b"EMC" => { + if self.oc_hidden_depth > 0 { + self.oc_hidden_depth -= 1; } } - b"S" | b"s" | b"n" => path = Path::Empty, - b"c" | b"v" | b"y" | b"W" | b"W*" => path = Path::Other, b"Do" => { if let Some(name) = op.name(0) { if depth >= MAX_DEPTH { @@ -253,6 +406,9 @@ impl<'a> Walker<'a> { /// changes inside never leak out; every rectangle found is stamped with the `Do` /// position `pos`. fn walk_xobject(&mut self, name: &[u8], gs: &Gs, resources: &Dict, depth: usize, pos: (usize, usize)) -> Result<(), AuditError> { + if self.oc_hidden_depth > 0 { + return Ok(()); + } let xobjects = resources.get(b"XObject").map(|o| self.doc.resolve(o)).and_then(|o| o.as_dict().cloned()).unwrap_or_default(); let Some(entry) = xobjects.get(name) else { return Ok(()) }; let resolved = self.doc.resolve(entry); @@ -261,6 +417,11 @@ impl<'a> Walker<'a> { if dict.name(b"Subtype") != Some(b"Form") { return Ok(()); } + if let Some(Object::Ref(r)) = dict.get(b"OC") + && self.off_layers.contains(r) + { + return Ok(()); + } let matrix = dict .get(b"Matrix") .map(|o| self.doc.resolve(o)) @@ -270,6 +431,10 @@ impl<'a> Walker<'a> { (v.len() == 6 && v.iter().all(|x| x.is_finite())).then(|| Matrix([v[0], v[1], v[2], v[3], v[4], v[5]])) }) .unwrap_or(Matrix::IDENTITY); + let bbox = dict.get(b"BBox").map(|o| self.doc.resolve(o)).and_then(|o| o.as_array().map(|a| a.to_vec())).and_then(|a| { + let v: Vec = a.iter().filter_map(|o| self.doc.resolve(o).as_f64()).collect(); + (v.len() == 4 && v.iter().all(|x| x.is_finite())).then(|| [v[0].min(v[2]), v[1].min(v[3]), v[0].max(v[2]), v[1].max(v[3])]) + }); let sub_resources = dict.get(b"Resources").map(|o| self.doc.resolve(o)).and_then(|o| o.as_dict().cloned()).unwrap_or_default(); // A form stream that cannot be decoded fails the audit: it might hide a cover. let data = stream.decoded_strict()?; @@ -277,8 +442,19 @@ impl<'a> Walker<'a> { // The XObject matrix maps form space into the user space active at `Do`. let mut sub_gs = gs.clone(); sub_gs.ctm = matrix.then(&gs.ctm); + if let Some(bbox) = bbox { + if axis_aligned(&sub_gs.ctm) { + let form_box = sub_gs.ctm.bbox(bbox); + sub_gs.clip = sub_gs.clip.intersect_rect(form_box); + } else { + sub_gs.clip = Clip::Unknown; + } + } + let saved_oc_depth = self.oc_hidden_depth; let mut sub_stack = Vec::new(); - self.walk_ops(&ops, &mut sub_gs, &mut sub_stack, &sub_resources, depth + 1, Some(pos)) + let res = self.walk_ops(&ops, &mut sub_gs, &mut sub_stack, &sub_resources, depth + 1, Some(pos)); + self.oc_hidden_depth = saved_oc_depth; + res } } @@ -301,6 +477,41 @@ fn ext_alpha(doc: &Document, resources: &Dict, name: &[u8]) -> f64 { alpha.filter(|a| a.is_finite()).map(|a| a.clamp(0.0, 1.0)).unwrap_or(1.0) } +fn off_layers(doc: &Document) -> HashSet { + let mut off_set = HashSet::new(); + let Some(root) = doc.trailer().get(b"Root").map(|r| doc.resolve(r)) else { return off_set }; + let Some(catalog) = root.as_dict() else { return off_set }; + let Some(oc_props) = catalog.get(b"OCProperties").map(|o| doc.resolve(o)).and_then(|o| o.as_dict().cloned()) else { + return off_set; + }; + let Some(d) = oc_props.get(b"D").map(|o| doc.resolve(o)).and_then(|o| o.as_dict().cloned()) else { + return off_set; + }; + if let Some(off_arr) = d.get(b"OFF").map(|o| doc.resolve(o)).and_then(|o| o.as_array().cloned()) { + for item in off_arr { + if let Object::Ref(r) = item { + off_set.insert(r); + } + } + } + off_set +} + +fn is_layer_off(doc: &Document, resources: &Dict, off_layers: &HashSet, prop: Option<&Object>) -> bool { + let Some(prop) = prop else { return false }; + match prop { + Object::Ref(r) => off_layers.contains(r), + Object::Name(name) => { + let Some(props) = resources.get(b"Properties").map(|o| doc.resolve(o)).and_then(|o| o.as_dict().cloned()) else { + return false; + }; + let Some(entry) = props.get(name) else { return false }; + if let Object::Ref(r) = entry { off_layers.contains(r) } else { false } + } + _ => false, + } +} + /// Every opaque filled rectangle drawn by a page's content (and its form XObjects), with paint /// positions. A page's content streams are walked once, joined, with one graphics state, so /// state set in an earlier stream is still in force in the later ones. Any content stream that @@ -322,7 +533,8 @@ pub fn filled_rects(doc: &Document, page: &Dict) -> Result, Audi } let pieces = Pieces::join(&streams); let parsed = pieces.parse(); - let mut w = Walker { doc, pieces: &pieces, out: Vec::new(), ops_seen: 0 }; + let off = off_layers(doc); + let mut w = Walker { doc, pieces: &pieces, out: Vec::new(), ops_seen: 0, off_layers: off, oc_hidden_depth: 0 }; let mut gs = Gs::default(); let mut stack = Vec::new(); w.walk_ops(&parsed.ops, &mut gs, &mut stack, &resources, 0, None)?; diff --git a/crates/audit/src/tests.rs b/crates/audit/src/tests.rs index 63d9220cca..448c68f74e 100644 --- a/crates/audit/src/tests.rs +++ b/crates/audit/src/tests.rs @@ -529,3 +529,212 @@ fn reading_blocks_respect_stream_comments_and_split_operands() { assert_eq!(text, "Replacement text", "{}", String::from_utf8_lossy(s1)); } } + +#[test] +fn clipping_path_prunes_clipped_out_box() { + // Negative control (#3118): box is drawn outside the active clip, so it hides nothing. + let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\nq 0 0 10 10 re W n 0 g 100 688 220 32 re f Q\n"; + let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run"); + assert!(findings.is_empty(), "{findings:?}"); + + // Paired positive control: clipping path contains the box, so the cover is detected. + let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\nq 90 680 240 50 re W n 0 g 100 688 220 32 re f Q\n"; + let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run"); + assert_eq!(findings.len(), 1, "{findings:?}"); + assert_eq!(findings[0].kind, FindingKind::CoveredText); + assert!(findings[0].covered_text.contains("SECRET")); + + // Disjoint clips leave an empty intersection so nothing visible is painted. + let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\nq 0 0 10 10 re W n 50 50 10 10 re W n 0 g 100 688 220 32 re f Q\n"; + let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run"); + assert!(findings.is_empty(), "disjoint clips leave nothing visible: {findings:?}"); + + // A clip that is not an axis-aligned rectangle fails closed as unknown and keeps the candidate cover. + let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\nq 0 0 m 612 0 l 306 792 l h W n 0 g 100 688 220 32 re f Q\n"; + let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run"); + assert_eq!(findings.len(), 1, "non-rectangular clip path fails closed: {findings:?}"); + assert!(findings[0].covered_text.contains("SECRET")); +} + +#[test] +fn form_bbox_clips_contained_drawing() { + // Negative control (#3118): form BBox does not reach the text. + 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 << /Fm 5 0 R >> >> >>"); + b.add_stream(b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n/Fm Do\n"); + b.add_stream_with(b"0 g\n100 688 220 32 re f\n", "/Type /XObject /Subtype /Form /BBox [0 0 10 10]"); + b.add(FONT); + let findings = audit_redactions(&open(b.build())).expect("audit must run"); + assert!(findings.is_empty(), "{findings:?}"); + + // Paired positive control: form BBox covers the text. + 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 << /Fm 5 0 R >> >> >>"); + b.add_stream(b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n/Fm Do\n"); + b.add_stream_with(b"0 g\n100 688 220 32 re f\n", "/Type /XObject /Subtype /Form /BBox [0 0 612 792]"); + b.add(FONT); + let findings = audit_redactions(&open(b.build())).expect("audit must run"); + assert_eq!(findings.len(), 1, "{findings:?}"); + assert!(findings[0].covered_text.contains("SECRET")); +} + +#[test] +fn optional_content_hidden_layer_is_not_reported() { + // Negative control (#3118): box is drawn inside a layer that is default OFF. + let mut b = Builder::new(); + b.add("<< /Type /Catalog /Pages 2 0 R /OCProperties << /OCGs [6 0 R] /D << /OFF [6 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 >> /Properties << /L1 6 0 R >> >> >>", + ); + b.add_stream(b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n/OC /L1 BDC\n0 g\n100 688 220 32 re f\nEMC\n"); + b.add(FONT); + b.add("<< /Type /OCG /Name (Hidden) >>"); + let findings = audit_redactions(&open(b.build())).expect("audit must run"); + assert!(findings.is_empty(), "{findings:?}"); + + // Paired positive control: box is drawn inside a layer that is visible. + let mut b = Builder::new(); + b.add("<< /Type /Catalog /Pages 2 0 R /OCProperties << /OCGs [6 0 R] /D << /Order [6 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 >> /Properties << /L1 6 0 R >> >> >>", + ); + b.add_stream(b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n/OC /L1 BDC\n0 g\n100 688 220 32 re f\nEMC\n"); + b.add(FONT); + b.add("<< /Type /OCG /Name (Visible) >>"); + let findings = audit_redactions(&open(b.build())).expect("audit must run"); + assert_eq!(findings.len(), 1, "{findings:?}"); + assert!(findings[0].covered_text.contains("SECRET")); +} + +#[test] +fn text_clipping_mode_fill_is_not_reported_as_cover() { + // Negative control (#3118): fill through Tr 7 text clip fills the glyphs, not a page cover. + let content = b"q BT /F1 24 Tf 7 Tr 100 700 Td (SECRET DATA 123) Tj ET 0 0 0.5 rg 0 0 612 792 re f Q\n"; + let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run"); + assert!(findings.is_empty(), "{findings:?}"); + + // Paired positive control: after Q restores normal clipping (or with 0 Tr), fill is detected. + let content = b"q BT /F1 24 Tf 7 Tr 100 700 Td (SECRET DATA 123) Tj ET Q 0 g 100 688 220 32 re 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")); + + // 4 Tr clips like 7 Tr: text clipping modes 4..=7 fill glyphs, not a page cover. + let content = b"q BT /F1 24 Tf 4 Tr 100 700 Td (SECRET DATA 123) Tj ET 0 g 0 0 612 792 re f Q\n"; + let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run"); + assert!(findings.is_empty(), "Tr 4 text clip fills glyphs: {findings:?}"); + + // 3 Tr (neither stroke nor fill) does not clip: a black box over invisible, extractable text is still a cover. + let content = b"BT /F1 24 Tf 3 Tr 100 700 Td (SECRET DATA 123) Tj ET\n0 g 100 688 220 32 re f\n"; + let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run"); + assert_eq!(findings.len(), 1, "Tr 3 text does not clip: {findings:?}"); + assert!(findings[0].covered_text.contains("SECRET")); +} + +#[test] +fn color_set_with_cs_sc_and_scn_controls() { + // 1. DeviceGray via cs / sc + let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n1 g 0 0 1 1 re f /DeviceGray cs 0 sc 100 688 220 32 re f\n"; + let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run"); + assert_eq!(findings.len(), 1, "DeviceGray cs/sc: {findings:?}"); + assert!(findings[0].covered_text.contains("SECRET")); + + // 2. DeviceRGB via cs / sc + let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n1 g 0 0 1 1 re f /DeviceRGB cs 0 0 0 sc 100 688 220 32 re f\n"; + let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run"); + assert_eq!(findings.len(), 1, "DeviceRGB cs/sc: {findings:?}"); + assert!(findings[0].covered_text.contains("SECRET")); + + // 3. DeviceCMYK via cs / sc + let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n1 g 0 0 1 1 re f /DeviceCMYK cs 0 0 0 1 sc 100 688 220 32 re f\n"; + let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run"); + assert_eq!(findings.len(), 1, "DeviceCMYK cs/sc: {findings:?}"); + assert!(findings[0].covered_text.contains("SECRET")); + + // 4. scn operator with DeviceRGB + let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n1 g 0 0 1 1 re f /DeviceRGB cs 0.05 0.05 0.05 scn 100 688 220 32 re f\n"; + let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run"); + assert_eq!(findings.len(), 1, "scn operator: {findings:?}"); + assert!(findings[0].covered_text.contains("SECRET")); + + // 5. Fail-closed: unknown color space defaults to black + let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n1 g 0 0 1 1 re f /CustomSeparation cs 0.5 sc 100 688 220 32 re f\n"; + let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run"); + assert_eq!(findings.len(), 1, "unknown color space fail-closed: {findings:?}"); + assert!(findings[0].covered_text.contains("SECRET")); + + // 6. Negative control: light color set via cs / sc is not reported as cover + let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n0 g 0 0 1 1 re f /DeviceGray cs 1 sc 100 688 220 32 re f\n"; + let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run"); + assert!(findings.is_empty(), "light color via cs/sc must not be reported: {findings:?}"); + + // 7. White CMYK fill set through cs / sc is not a cover + let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n/DeviceCMYK cs 0 0 0 0 sc 100 688 220 32 re f\n"; + let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run"); + assert!(findings.is_empty(), "white CMYK fill via cs/sc is not a cover: {findings:?}"); + + // 8. Unknown color space is treated as black regardless of sc components + let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n/CS9 cs 1 1 1 sc 100 688 220 32 re f\n"; + let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run"); + assert_eq!(findings.len(), 1, "unknown color space treated as black: {findings:?}"); + assert!(findings[0].covered_text.contains("SECRET")); +} + +#[test] +fn unclosed_oc_in_form_xobject_does_not_leak_to_parent() { + let mut b = Builder::new(); + b.add("<< /Type /Catalog /Pages 2 0 R /OCProperties << /OCGs [6 0 R] /D << /OFF [6 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 >> /XObject << /Fm 7 0 R >> /Properties << /L1 6 0 R >> >> >>", + ); + // Page: text, then /Fm Do (which has unclosed /OC /L1 BDC), then genuine cover over text. + b.add_stream(b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n/Fm Do\n0 g\n100 688 220 32 re f\n"); + b.add(FONT); + b.add("<< /Type /OCG /Name (Hidden) >>"); + // Form Fm leaves /OC /L1 unclosed (no EMC) + b.add_stream_with( + b"/OC /L1 BDC\n0 g\n0 0 10 10 re f\n", + "/Type /XObject /Subtype /Form /BBox [0 0 10 10] /Resources << /Properties << /L1 6 0 R >> >>", + ); + let findings = audit_redactions(&open(b.build())).expect("audit must run"); + assert_eq!(findings.len(), 1, "genuine cover following unclosed form OC must not be suppressed: {findings:?}"); + assert!(findings[0].covered_text.contains("SECRET")); +} + +#[test] +fn rotated_re_cover_detection() { + // 90-degree axis-aligned rotation: (x_user, y_user) = (800 - y, x) + // with rect [688, 480, 32, 220] mapping to user space [100, 688, 320, 720] over the text. + let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\nq 0 1 -1 0 800 0 cm 0 g 688 480 32 220 re f Q\n"; + let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run"); + assert_eq!(findings.len(), 1, "90-deg rotated axis-aligned rect is detected: {findings:?}"); + assert!(findings[0].covered_text.contains("SECRET")); + + // 45-degree non-axis-aligned rotation: bounding box overlaps text, but non-axis-aligned geometry is excluded. + let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\nq 0.7071 0.7071 -0.7071 0.7071 200 550 cm 0 g 10 10 160 160 re f Q\n"; + let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run"); + assert!(findings.is_empty(), "non-axis-aligned path is not a rectangular cover: {findings:?}"); +} + +#[test] +fn nested_marked_content_inside_hidden_oc_is_not_reported() { + let mut b = Builder::new(); + b.add("<< /Type /Catalog /Pages 2 0 R /OCProperties << /OCGs [6 0 R] /D << /OFF [6 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 >> /Properties << /L1 6 0 R >> >> >>", + ); + // Nested marked content (/Span) inside hidden layer (/OC /L1): box remains on hidden layer after inner EMC. + b.add_stream(b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n/OC /L1 BDC\n/Span << >> BDC\nEMC\n0 g\n100 688 220 32 re f\nEMC\n"); + b.add(FONT); + b.add("<< /Type /OCG /Name (Hidden) >>"); + let findings = audit_redactions(&open(b.build())).expect("audit must run"); + assert!(findings.is_empty(), "box inside nested marked content on hidden OC layer must not be reported: {findings:?}"); +} From a840e0787c8da2f4ba83e62f0f402f8e42240f31 Mon Sep 17 00:00:00 2001 From: Zach Shallbetter Date: Tue, 24 Nov 2026 05:12:05 -0800 Subject: [PATCH 2/3] Keep potential covers through glyph clips --- crates/audit/src/cover.rs | 51 +++++++++++++++++++++++++--------- crates/audit/src/lib.rs | 10 ++++--- crates/audit/src/tests.rs | 27 ++++++++++++++++-- crates/edit/src/lib.rs | 4 +-- crates/edit/src/text.rs | 2 +- crates/edit/src/text/interp.rs | 7 +++++ crates/edit/src/text/lines.rs | 36 +++++++++++++++++++++--- 7 files changed, 110 insertions(+), 27 deletions(-) diff --git a/crates/audit/src/cover.rs b/crates/audit/src/cover.rs index c614bdfa3c..739d8ac302 100644 --- a/crates/audit/src/cover.rs +++ b/crates/audit/src/cover.rs @@ -9,6 +9,8 @@ //! `G`/`RG`/`K`), the line width (`w`) and what ExtGState sets of them (`gs` reading `/ca`, //! `/CA` and `/LW`), rectangular and glyph clipping, form bounds, and default-off //! optional-content groups. Rotated rectangles are conservatively bounded in user space. +//! If only the source of a glyph clip is known, the audit excludes fills of that text object +//! from its own cover findings and retains potential covers on independently drawn text. //! Form XObjects are followed read-only with a depth and decode budget. Other filled paths, //! slanted or bent strokes, shadings and patterns remain out of scope. //! @@ -20,6 +22,7 @@ //! Positions compare lexicographically in paint order. use std::collections::HashSet; +use std::ops::Range; use pdfcraft_content::{Matrix, Op, Pieces, ops}; use pdfcraft_cos::{DecodeBudget, Dict, Document, ObjRef, Object}; @@ -43,6 +46,8 @@ pub struct FilledRect { /// Paint position: `(content-stream index, operator index in the joined stream)`. /// Rectangles inside a form XObject carry the `Do` operator's position. pub pos: (usize, usize), + /// Page operators of the text object whose own glyphs this paint fills. + pub glyph_source: Option>, } #[derive(Clone, Copy)] @@ -50,7 +55,6 @@ enum Clip { Unbounded, Rect([f64; 4]), Empty, - Glyphs, } impl Clip { @@ -61,15 +65,12 @@ impl Clip { let intersection = [rect[0].max(clip[0]), rect[1].max(clip[1]), rect[2].min(clip[2]), rect[3].min(clip[3])]; (intersection[0] < intersection[2] && intersection[1] < intersection[3]).then_some(intersection) } - Self::Empty | Self::Glyphs => None, + Self::Empty => None, } } fn intersect_rect(&mut self, rect: [f64; 4]) { - // Preserve an existing glyph clip. Its shape is already narrower than a rectangle. - if !matches!(self, Self::Glyphs) { - *self = self.visible_rect(rect).map_or(Self::Empty, Self::Rect); - } + *self = self.visible_rect(rect).map_or(Self::Empty, Self::Rect); } } @@ -82,6 +83,7 @@ struct Gs { stroke_alpha: f64, clip: Clip, glyph_clip_mode: bool, + glyph_source: Option>, /// Line width, in the space the path is drawn in. width: f64, /// Line cap (`J`, `/LC`): 0 butt, 1 round, 2 projecting square. @@ -178,6 +180,7 @@ impl Default for Gs { stroke_alpha: 1.0, clip: Clip::Unbounded, glyph_clip_mode: false, + glyph_source: None, width: 1.0, cap: 0, } @@ -193,6 +196,7 @@ struct Walker<'a> { /// fails the audit. budget: DecodeBudget, off_layers: HashSet, + blank_clips: &'a HashSet, } impl<'a> Walker<'a> { @@ -209,7 +213,7 @@ impl<'a> Walker<'a> { if alpha >= 1.0 && let Some(rect) = rect.and_then(|rect| gs.clip.visible_rect(rect)) { - self.out.push(FilledRect { rect, rgb, pos }); + self.out.push(FilledRect { rect, rgb, pos, glyph_source: gs.glyph_source.clone() }); } } @@ -239,6 +243,8 @@ impl<'a> Walker<'a> { let mut multiple_subpaths = false; let mut clip_next = false; let mut glyph_clip_pending = false; + let mut glyph_only_text = false; + let mut text_start = 0; let mut hidden_depth = 0usize; for (i, op) in ops.enumerate() { self.bump()?; @@ -362,16 +368,25 @@ impl<'a> Walker<'a> { multiple_subpaths = false; } b"c" | b"v" | b"y" => path = Path::Other, - b"BT" => glyph_clip_pending = false, + b"BT" => { + glyph_clip_pending = false; + glyph_only_text = true; + text_start = i; + } b"Tr" => { if let Some(mode) = op.num(0).filter(|v| (0.0..=7.0).contains(v) && v.fract() == 0.0) { gs.glyph_clip_mode = mode >= 4.0; } } - b"Tj" | b"TJ" | b"'" | b"\"" => glyph_clip_pending |= gs.glyph_clip_mode && hidden_depth == 0, + b"Tj" | b"TJ" | b"'" | b"\"" if shows_glyphs(op) => { + glyph_clip_pending |= gs.glyph_clip_mode && (at_do.is_some() || !self.blank_clips.contains(&i)); + glyph_only_text &= gs.glyph_clip_mode; + } b"ET" => { if std::mem::take(&mut glyph_clip_pending) { - gs.clip = Clip::Glyphs; + // Without glyph outlines, retain the rectangular bound as a conservative + // estimate. Paint through the clip can still cover independently drawn text. + gs.glyph_source = (glyph_only_text && at_do.is_none()).then_some(text_start..i); } } b"BDC" => { @@ -497,7 +512,17 @@ fn ext_state(doc: &Document, resources: &Dict, name: &[u8], gs: &mut Gs) { } } -/// Only explicit default-off groups suppress covers. Other configurations and +/// Empty shows and TJ positioning adjustments contribute no outline to a text clip. +fn shows_glyphs(op: &Op) -> bool { + let nonempty = |value: &Object| matches!(value, Object::String(text) if !text.bytes.is_empty()); + match op.operands.last() { + Some(Object::Array(items)) if op.is("TJ") => items.iter().any(nonempty), + Some(value) if !op.is("TJ") => nonempty(value), + _ => false, + } +} + +/// Only explicit groups in `/D /OFF` suppress covers. `/BaseState`, `/ON` and /// optional-content membership dictionaries stay visible to the audit. fn off_layers(doc: &Document) -> HashSet { let Some(root) = doc.trailer().get(b"Root").map(|value| doc.resolve(value)) else { return HashSet::new() }; @@ -517,7 +542,7 @@ fn off_layers(doc: &Document) -> HashSet { /// state set in an earlier stream is still in force in the later ones. Any content stream that /// cannot be decoded, or content and forms that decode or enter past one page's [`DecodeBudget`] /// in all, is an audit failure, never an empty result. -pub fn filled_rects(doc: &Document, page: &Dict) -> Result, AuditError> { +pub fn filled_rects(doc: &Document, page: &Dict, blank_clips: &HashSet) -> Result, AuditError> { let resources = page.get(b"Resources").map(|o| doc.resolve(o)).and_then(|o| o.as_dict().cloned()).unwrap_or_default(); let contents: Vec = match page.get(b"Contents") { None => Vec::new(), @@ -534,7 +559,7 @@ pub fn filled_rects(doc: &Document, page: &Dict) -> Result, Audi } } let pieces = Pieces::join(&streams); - let mut w = Walker { doc, pieces: &pieces, out: Vec::new(), ops_seen: 0, budget, off_layers: off_layers(doc) }; + let mut w = Walker { doc, pieces: &pieces, out: Vec::new(), ops_seen: 0, budget, off_layers: off_layers(doc), blank_clips }; let mut gs = Gs::default(); let mut stack = Vec::new(); // Read one operator at a time: the joined stream can hold millions of them within the diff --git a/crates/audit/src/lib.rs b/crates/audit/src/lib.rs index 2cc221d562..ca0030566d 100644 --- a/crates/audit/src/lib.rs +++ b/crates/audit/src/lib.rs @@ -234,10 +234,11 @@ fn audit(doc: &Document, limits: Limits) -> Result, AuditError for (n, page) in pdfcraft_model::pages(doc).iter().enumerate() { // 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()))?; + let mut blank_clips = std::collections::HashSet::new(); + let lines = pdfcraft_edit::glyph_text_lines_with_blank_clips(doc, page, &mut blank_clips).map_err(|e| AuditError::Text(n, e.to_string()))?; budget.start_page(&lines); // 1. Opaque rectangles (filled, or painted by a thick stroke) over extractable text. - for r in cover::filled_rects(doc, &page.dict)? { + for r in cover::filled_rects(doc, &page.dict, &blank_clips)? { if let Some(covered) = budget.hidden_text(&lines, copying, std::slice::from_ref(&r.rect), |line| hides(&r, line))? { let covered_text = budget.report_text(covered, copying)?; out.push(AuditFinding { page: n, kind: rect_kind(&r), rect: r.rect, covered_text }); @@ -282,10 +283,11 @@ fn rect_kind(rect: &cover::FilledRect) -> FindingKind { /// Does `rect` hide `line`: painted after the start of the line and over it, and white or a cover /// ([`is_cover`]). Light covers in between (table shading) are not flagged. fn hides(rect: &cover::FilledRect, line: &TextLine) -> bool { - match rect_kind(rect) { + let hides = match rect_kind(rect) { FindingKind::HiddenUnderWhite => rect.pos > line.first_paint_pos() && covers(&rect.rect, line), _ => is_cover(rect, line), - } + }; + hides && !rect.glyph_source.as_ref().is_some_and(|source| line.drawn_within(source)) } /// Does `cover` hide a substantial part of what `line` draws? Three ways, any is enough: diff --git a/crates/audit/src/tests.rs b/crates/audit/src/tests.rs index 2e5074b84a..c94b497046 100644 --- a/crates/audit/src/tests.rs +++ b/crates/audit/src/tests.rs @@ -1091,7 +1091,7 @@ fn repeated_stream_references_share_one_decode_budget() { 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"); + assert!(crate::cover::filled_rects(&doc, &contents, &Default::default()).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])); @@ -1099,7 +1099,7 @@ fn repeated_stream_references_share_one_decode_budget() { 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"); + assert!(crate::cover::filled_rects(&doc, &page, &Default::default()).is_err(), "repeated form draws"); } #[test] @@ -1113,7 +1113,7 @@ fn form_entries_past_the_page_allowance_fail_the_audit() { 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))); + assert!(matches!(crate::cover::filled_rects(&doc, &page, &Default::default()), Err(crate::AuditError::TooManyForms))); } /// Copying a covered line's text walks all of it, padding included, so a long padded line under @@ -1272,6 +1272,27 @@ fn text_clipping_mode_fill_is_not_reported_as_cover() { assert!(findings[0].covered_text.contains("SECRET")); } +#[test] +fn glyph_clipping_keeps_covers_over_independent_text() { + let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET q BT /F1 24 Tf 7 Tr 100 700 Td (MASK) Tj ET 0 g 100 688 220 32 re f Q"; + let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run"); + assert!(findings.iter().any(|finding| finding.covered_text.contains("SECRET")), "{findings:?}"); +} + +#[test] +fn empty_glyph_shows_leave_clipping_unchanged() { + let blank = r#"BT /F1 24 Tf 7 Tr () Tj [() 120 ()] TJ () ' 0 0 () " /F1 0 Tf (TEXT) Tj ET"#; + let fill = "0 g 100 688 220 32 re f"; + let content = format!("BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET {blank} {fill}"); + let findings = audit_redactions(&open(one_page(content.as_bytes(), ""))).expect("audit must run"); + assert_eq!(findings.len(), 1, "{findings:?}"); + assert!(findings[0].covered_text.contains("SECRET")); + + let content = format!("BT /F1 24 Tf 7 Tr 100 700 Td (MASK) Tj ET {blank} {fill}"); + let findings = audit_redactions(&open(one_page(content.as_bytes(), ""))).expect("audit must run"); + assert!(findings.is_empty(), "a blank show must preserve the previous text clip: {findings:?}"); +} + #[test] fn unclosed_oc_in_form_xobject_does_not_leak_to_parent() { let mut b = Builder::new(); diff --git a/crates/edit/src/lib.rs b/crates/edit/src/lib.rs index 886bfc3522..876df14199 100644 --- a/crates/edit/src/lib.rs +++ b/crates/edit/src/lib.rs @@ -62,8 +62,8 @@ pub mod paragraph_align; pub mod text; pub use text::{ BlockKey, BlockStyle, LineEdit, MAX_FORM_DEPTH, MAX_FORM_VISITS, RangeStyle, ReadingBlocks, RunSources, TextBlock, TextLine, TextSession, - block_overlapping, clear_block, glyph_text_lines, reading_blocks, reading_blocks_checked, replace_block, replace_line, rewrite_block, - text_blocks, text_lines, + block_overlapping, clear_block, glyph_text_lines, glyph_text_lines_with_blank_clips, reading_blocks, reading_blocks_checked, replace_block, + replace_line, rewrite_block, text_blocks, text_lines, }; pub mod printer_marks; pub use printer_marks::{PrinterMarks, add_printer_marks}; diff --git a/crates/edit/src/text.rs b/crates/edit/src/text.rs index 0bcd48cc8e..3b938878f4 100644 --- a/crates/edit/src/text.rs +++ b/crates/edit/src/text.rs @@ -64,7 +64,7 @@ pub(crate) use lines::{ ContentStream, FormBudget, Read, content_streams, content_streams_within, dict_in_place, drawn_before_damage, dropped_advances, dropped_side_effects, first_op_after_damage, form_call, joined, reopen_text_object, resource_dict, rewritten_contents, splice, }; -pub use lines::{MAX_FORM_DEPTH, MAX_FORM_VISITS, glyph_text_lines, text_lines}; +pub use lines::{MAX_FORM_DEPTH, MAX_FORM_VISITS, glyph_text_lines, glyph_text_lines_with_blank_clips, text_lines}; use lines::{page_dict, word_lines}; pub use rewrite::{LineEdit, replace_line, rewrite_block}; use rewrite::{coincident_ops, rewrite_block_from}; diff --git a/crates/edit/src/text/interp.rs b/crates/edit/src/text/interp.rs index cf9e0beef2..7ada4a5182 100644 --- a/crates/edit/src/text/interp.rs +++ b/crates/edit/src/text/interp.rs @@ -449,6 +449,8 @@ pub(super) struct Shown { pub(super) extra_ops: Vec, /// Encoded glyphs, not bytes or Unicode characters (a ligature can represent several). pub(super) glyph_count: usize, + /// A glyph has an outline, or its font could not establish that it is empty. + pub(super) may_draw_outline: bool, /// Advance in text space, including spacing and TJ adjustments. pub(super) advance: f64, pub(super) tracking: f64, @@ -806,11 +808,15 @@ fn show_text(op: &Op, i: usize, state: &mut TextRunState<'_>) -> Result<(), Edit // before may have ended in one: a justified line can be split over `TJ` and `Tj`. let mut gap_space = std::mem::take(&mut carry.gap_space); let mut glyph_count = 0_usize; + let mut may_draw_outline = false; for p in &pieces { match p { Object::String(s) => { for (code, len) in m.codes(&s.bytes) { glyph_count = glyph_count.saturating_add(1); + if (4..=7).contains(&ts.render_mode) && ts.size != 0.0 && ts.scale != 0.0 { + may_draw_outline |= m.past_allowance || m.codespaces_dropped || m.has_outline(code) != Some(false); + } let shown = m.text_of(code); let blank = m.is_space(code, len) || shown.as_deref().is_some_and(|t| !t.is_empty() && t.chars().all(char::is_whitespace)); // A space glyph right after a gap that read as a space is that space: @@ -929,6 +935,7 @@ fn show_text(op: &Op, i: usize, state: &mut TextRunState<'_>) -> Result<(), Edit op: i, extra_ops: Vec::new(), glyph_count, + may_draw_outline, // Vertical text: the TJ adjustment that undoes the run is n = -1000 y / size; the // preview divides by size × `Tz`, so `Tz` is put back here. advance: if vertical.is_some() { y_text * ts.scale } else { x_text }, diff --git a/crates/edit/src/text/lines.rs b/crates/edit/src/text/lines.rs index 43b2c84d4e..1eb35c818e 100644 --- a/crates/edit/src/text/lines.rs +++ b/crates/edit/src/text/lines.rs @@ -19,6 +19,16 @@ impl TextLine { (self.stream, self.ops.iter().min().copied().unwrap_or(0)) } + /// Whether all the line's drawing operators are inside one text object in the joined + /// page stream. A line can join runs from several text objects. + pub fn drawn_within(&self, operators: &std::ops::Range) -> bool { + if self.actual_text { + return !self.ops.is_empty() && self.ops.iter().all(|op| operators.contains(op)); + } + // Glyph shows are appended in stream order. + self.ops.first().zip(self.ops.last()).is_some_and(|(first, last)| operators.contains(first) && operators.contains(last)) + } + /// The runs of text the line joins, in content order: each run's text as its glyphs show it, /// the boxes of its words (a part of `ink`), and whether joining put a space between it and /// the run before (`text` has one there; runs closer together join with none, so one word @@ -431,13 +441,13 @@ fn fill_color(fill: &[Op]) -> [f64; 3] { /// The lines of text on a page (0-based), in content order. pub fn text_lines(doc: &Document, page: usize) -> Result, EditError> { - text_lines_in(doc, &page_dict(doc, page)?, true, false) + text_lines_in(doc, &page_dict(doc, page)?, true, false, None) } /// [`text_lines`] with every show of invisible text a line of its own, however alike its /// neighbours: an OCR layer's words, which an edit can keep or change one by one. pub(crate) fn word_lines(doc: &Document, page: usize) -> Result, EditError> { - text_lines_in(doc, &page_dict(doc, page)?, true, true) + text_lines_in(doc, &page_dict(doc, page)?, true, true, None) } /// The lines `page`'s glyphs show, in content order, without `/ActualText` replacements: what the @@ -445,12 +455,27 @@ pub(crate) fn word_lines(doc: &Document, page: usize) -> Result, E /// not trust that metadata (the redaction audit). Takes the page itself, so a caller going /// through every page doesn't walk the page tree again for each. pub fn glyph_text_lines(doc: &Document, page: &pdfcraft_model::Page) -> Result, EditError> { - text_lines_in(doc, page, false, false) + text_lines_in(doc, page, false, false, None) +} + +/// Extracts the glyph lines and records text-clipping shows whose glyphs have no outlines. +pub fn glyph_text_lines_with_blank_clips( + doc: &Document, + page: &pdfcraft_model::Page, + blank_clips: &mut std::collections::HashSet, +) -> Result, EditError> { + text_lines_in(doc, page, false, false, Some(blank_clips)) } /// [`text_lines`] of `p`; with `actual_text`, `/ActualText` replaces the glyphs it spans, and with /// `invisible_apart`, no show of invisible text joins the one before it. -fn text_lines_in(doc: &Document, p: &pdfcraft_model::Page, actual_text: bool, invisible_apart: bool) -> Result, EditError> { +fn text_lines_in( + doc: &Document, + p: &pdfcraft_model::Page, + actual_text: bool, + invisible_apart: bool, + blank_clips: Option<&mut std::collections::HashSet>, +) -> Result, EditError> { let res = p.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default(); let mut cache = HashMap::new(); let mut lines: Vec = Vec::new(); @@ -461,6 +486,9 @@ fn text_lines_in(doc: &Document, p: &pdfcraft_model::Page, actual_text: bool, in let ops = pieces.parse().ops; let properties = res.get(b"Properties").and_then(|o| doc.dict(o)).unwrap_or_default(); let shown = interpret(doc, &ops, &res, &mut cache, &mut carry, None, actual_text.then_some(&properties))?; + if let Some(blank_clips) = blank_clips { + blank_clips.extend(shown.iter().filter(|s| (4..=7).contains(&s.state.render_mode) && !s.may_draw_outline).map(|s| s.op)); + } let mut last: Option<(usize, Pen)> = None; // the stream piece and where its last run ended for mut s in shown { // A single RTL glyph's ActualText (e.g. lam-alef) is an inline ligature, not a From 843da52ceccc7e9cf5b1016ced549ca11a724b43 Mon Sep 17 00:00:00 2001 From: Zach Shallbetter Date: Tue, 24 Nov 2026 17:41:11 -0800 Subject: [PATCH 3/3] Distinguish painted glyphs from clip-only text in the audit --- crates/audit/src/cover.rs | 29 +++++++++++++++++++++-------- crates/audit/src/lib.rs | 9 +++++++-- crates/audit/src/tests.rs | 17 +++++++++++++++++ 3 files changed, 45 insertions(+), 10 deletions(-) diff --git a/crates/audit/src/cover.rs b/crates/audit/src/cover.rs index 739d8ac302..9bda6be30c 100644 --- a/crates/audit/src/cover.rs +++ b/crates/audit/src/cover.rs @@ -47,7 +47,13 @@ pub struct FilledRect { /// Rectangles inside a form XObject carry the `Do` operator's position. pub pos: (usize, usize), /// Page operators of the text object whose own glyphs this paint fills. - pub glyph_source: Option>, + pub glyph_source: Option, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct GlyphSource { + pub operators: Range, + pub painted: bool, } #[derive(Clone, Copy)] @@ -82,8 +88,8 @@ struct Gs { stroke: [f64; 3], stroke_alpha: f64, clip: Clip, - glyph_clip_mode: bool, - glyph_source: Option>, + text_render_mode: u8, + glyph_source: Option, /// Line width, in the space the path is drawn in. width: f64, /// Line cap (`J`, `/LC`): 0 butt, 1 round, 2 projecting square. @@ -179,7 +185,7 @@ impl Default for Gs { stroke: [0.0, 0.0, 0.0], stroke_alpha: 1.0, clip: Clip::Unbounded, - glyph_clip_mode: false, + text_render_mode: 0, glyph_source: None, width: 1.0, cap: 0, @@ -244,6 +250,7 @@ impl<'a> Walker<'a> { let mut clip_next = false; let mut glyph_clip_pending = false; let mut glyph_only_text = false; + let mut glyph_source_painted = false; let mut text_start = 0; let mut hidden_depth = 0usize; for (i, op) in ops.enumerate() { @@ -371,22 +378,28 @@ impl<'a> Walker<'a> { b"BT" => { glyph_clip_pending = false; glyph_only_text = true; + glyph_source_painted = false; text_start = i; } b"Tr" => { if let Some(mode) = op.num(0).filter(|v| (0.0..=7.0).contains(v) && v.fract() == 0.0) { - gs.glyph_clip_mode = mode >= 4.0; + gs.text_render_mode = mode as u8; } } b"Tj" | b"TJ" | b"'" | b"\"" if shows_glyphs(op) => { - glyph_clip_pending |= gs.glyph_clip_mode && (at_do.is_some() || !self.blank_clips.contains(&i)); - glyph_only_text &= gs.glyph_clip_mode; + let clips = gs.text_render_mode >= 4; + glyph_clip_pending |= clips && (at_do.is_some() || !self.blank_clips.contains(&i)); + glyph_only_text &= clips; + glyph_source_painted |= hidden_depth == 0 + && ((matches!(gs.text_render_mode, 4 | 6) && gs.alpha > 0.0) + || (matches!(gs.text_render_mode, 5 | 6) && gs.stroke_alpha > 0.0)); } b"ET" => { if std::mem::take(&mut glyph_clip_pending) { // Without glyph outlines, retain the rectangular bound as a conservative // estimate. Paint through the clip can still cover independently drawn text. - gs.glyph_source = (glyph_only_text && at_do.is_none()).then_some(text_start..i); + gs.glyph_source = + (glyph_only_text && at_do.is_none()).then_some(GlyphSource { operators: text_start..i, painted: glyph_source_painted }); } } b"BDC" => { diff --git a/crates/audit/src/lib.rs b/crates/audit/src/lib.rs index ca0030566d..de29fb27a6 100644 --- a/crates/audit/src/lib.rs +++ b/crates/audit/src/lib.rs @@ -283,11 +283,16 @@ fn rect_kind(rect: &cover::FilledRect) -> FindingKind { /// Does `rect` hide `line`: painted after the start of the line and over it, and white or a cover /// ([`is_cover`]). Light covers in between (table shading) are not flagged. fn hides(rect: &cover::FilledRect, line: &TextLine) -> bool { - let hides = match rect_kind(rect) { + let kind = rect_kind(rect); + let hides = match kind { FindingKind::HiddenUnderWhite => rect.pos > line.first_paint_pos() && covers(&rect.rect, line), _ => is_cover(rect, line), }; - hides && !rect.glyph_source.as_ref().is_some_and(|source| line.drawn_within(source)) + hides + && !rect + .glyph_source + .as_ref() + .is_some_and(|source| line.drawn_within(&source.operators) && !(source.painted && kind == FindingKind::HiddenUnderWhite)) } /// Does `cover` hide a substantial part of what `line` draws? Three ways, any is enough: diff --git a/crates/audit/src/tests.rs b/crates/audit/src/tests.rs index c94b497046..c7818365a6 100644 --- a/crates/audit/src/tests.rs +++ b/crates/audit/src/tests.rs @@ -1272,6 +1272,23 @@ fn text_clipping_mode_fill_is_not_reported_as_cover() { assert!(findings[0].covered_text.contains("SECRET")); } +#[test] +fn white_cover_distinguishes_painted_and_clip_only_glyph_sources() { + let doc = open(one_page(b"BT /F1 24 Tf 100 700 Td (Sample) Tj ET", "")); + let lines = pdfcraft_edit::glyph_text_lines(&doc, &pdfcraft_model::pages(&doc)[0]).expect("text"); + let line = &lines[0]; + let mut cover = crate::cover::FilledRect { + rect: line.rect, + rgb: [1.0; 3], + pos: (0, 10), + glyph_source: Some(crate::cover::GlyphSource { operators: 0..5, painted: false }), + }; + + assert!(!crate::hides(&cover, line)); + cover.glyph_source.as_mut().unwrap().painted = true; + assert!(crate::hides(&cover, line)); +} + #[test] fn glyph_clipping_keeps_covers_over_independent_text() { let content = b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET q BT /F1 24 Tf 7 Tr 100 700 Td (MASK) Tj ET 0 g 100 688 220 32 re f Q";