diff --git a/crates/audit/src/cover.rs b/crates/audit/src/cover.rs index 78b16e57ea..9bda6be30c 100644 --- a/crates/audit/src/cover.rs +++ b/crates/audit/src/cover.rs @@ -7,9 +7,12 @@ //! out ("marker" style), counts as the rectangle the stroke paints (#2385). Graphics state tracked //! here is deliberately small: the CTM stack (`q`/`Q`/`cm`), the colors (`g`/`rg`/`k` and //! `G`/`RG`/`K`), the line width (`w`) and what ExtGState sets of them (`gs` reading `/ca`, -//! `/CA` and `/LW`). Form XObjects are followed read-only with a depth cap. Anything fancier -//! (other filled paths, slanted or bent strokes, shadings, patterns) is out of scope and -//! documented as such. +//! `/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. //! //! 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 @@ -18,8 +21,11 @@ //! 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 std::ops::Range; + use pdfcraft_content::{Matrix, Op, Pieces, ops}; -use pdfcraft_cos::{DecodeBudget, Dict, Document, Object}; +use pdfcraft_cos::{DecodeBudget, Dict, Document, ObjRef, Object}; use crate::AuditError; @@ -40,6 +46,38 @@ 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, Debug, PartialEq)] +pub struct GlyphSource { + pub operators: Range, + pub painted: bool, +} + +#[derive(Clone, Copy)] +enum Clip { + Unbounded, + Rect([f64; 4]), + Empty, +} + +impl Clip { + fn visible_rect(self, rect: [f64; 4]) -> Option<[f64; 4]> { + match self { + Self::Unbounded => Some(rect), + Self::Rect(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 => None, + } + } + + fn intersect_rect(&mut self, rect: [f64; 4]) { + *self = self.visible_rect(rect).map_or(Self::Empty, Self::Rect); + } } #[derive(Clone)] @@ -49,6 +87,9 @@ struct Gs { alpha: f64, stroke: [f64; 3], stroke_alpha: f64, + clip: Clip, + 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. @@ -68,9 +109,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, } @@ -110,13 +151,11 @@ 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 pts = if pts.len() == 5 && same(pts[0][0], pts[4][0]) && same(pts[0][1], pts[4][1]) { &pts[..4] } else { pts }; let [a, b, c, d] = <[[f64; 2]; 4]>::try_from(pts).ok()?; let fits = |first_horizontal: bool| { [(a, b), (b, c), (c, d), (d, a)] @@ -139,7 +178,18 @@ fn lines_rect(mut pts: Vec<[f64; 2]>) -> Option<[f64; 4]> { impl Default for Gs { fn default() -> Self { - Gs { ctm: Matrix::IDENTITY, fill: [0.0, 0.0, 0.0], alpha: 1.0, stroke: [0.0, 0.0, 0.0], stroke_alpha: 1.0, width: 1.0, cap: 0 } + Gs { + ctm: Matrix::IDENTITY, + fill: [0.0, 0.0, 0.0], + alpha: 1.0, + stroke: [0.0, 0.0, 0.0], + stroke_alpha: 1.0, + clip: Clip::Unbounded, + text_render_mode: 0, + glyph_source: None, + width: 1.0, + cap: 0, + } } } @@ -151,6 +201,8 @@ struct Walker<'a> { /// Decoded bytes and form entries left for the page, its forms included: spending either /// fails the audit. budget: DecodeBudget, + off_layers: HashSet, + blank_clips: &'a HashSet, } impl<'a> Walker<'a> { @@ -162,6 +214,24 @@ impl<'a> Walker<'a> { Ok(()) } + fn push_cover(&mut self, rect: Option<[f64; 4]>, gs: &Gs, stroke: bool, pos: (usize, usize)) { + let (alpha, rgb) = if stroke { (gs.stroke_alpha, gs.stroke) } else { (gs.alpha, gs.fill) }; + if alpha >= 1.0 + && let Some(rect) = rect.and_then(|rect| gs.clip.visible_rect(rect)) + { + self.out.push(FilledRect { rect, rgb, pos, glyph_source: gs.glyph_source.clone() }); + } + } + + fn paint_path(&mut self, path: &Path, operator: &[u8], gs: &Gs, pos: (usize, usize)) { + if matches!(operator, b"B" | b"B*" | b"b" | b"b*" | b"S" | b"s") { + self.push_cover(path.stroked_rect(gs), gs, true, pos); + } + if !matches!(operator, b"S" | b"s" | b"n") { + self.push_cover(path.rect(), gs, false, pos); + } + } + /// Walk one stream's operators, read one at a time (a stream of millions of short operators /// is never held whole), with the given graphics state. `at_do` is the `Do` position to /// stamp on rectangles found inside a form XObject, or `None` at page level (where each @@ -176,6 +246,13 @@ impl<'a> Walker<'a> { at_do: Option<(usize, usize)>, ) -> Result<(), AuditError> { let mut path = Path::Empty; + let mut multiple_subpaths = false; + 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() { self.bump()?; let op = &op; @@ -245,6 +322,7 @@ impl<'a> Walker<'a> { } } b"re" => { + multiple_subpaths |= !matches!(path, Path::Empty); 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 { let r = gs.ctm.bbox([x.min(x + w), y.min(y + h), x.max(x + w), y.max(y + h)]); @@ -256,6 +334,7 @@ impl<'a> Walker<'a> { path = rect.map_or(Path::Other, Path::Rect); } b"m" => { + multiple_subpaths |= !matches!(path, Path::Empty); path = match (path, user_point(gs, op)) { (Path::Empty, Some(p)) => Path::Lines(vec![p], false), _ => Path::Other, @@ -279,38 +358,67 @@ impl<'a> Walker<'a> { _ => Path::Other, }; } - // `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*" => { + b"W" | b"W*" => clip_next = true, + b"f" | b"F" | b"f*" | b"B" | b"B*" | b"b" | b"b*" | b"S" | b"s" | b"n" => { let done = std::mem::replace(&mut path, Path::Empty); - if matches!(op.op.as_slice(), b"B" | b"B*" | b"b" | b"b*") - && let Some(r) = done.stroked_rect(gs) - && gs.stroke_alpha >= 1.0 - { - self.out.push(FilledRect { rect: r, rgb: gs.stroke, pos }); + if hidden_depth == 0 { + self.paint_path(&done, op.op.as_slice(), gs, pos); } - if let Some(r) = done.rect() - && gs.alpha >= 1.0 + // A clipping operator takes effect after the path-ending paint. + if clip_next + && !multiple_subpaths + && let Some(rect) = done.rect() { - self.out.push(FilledRect { rect: r, rgb: gs.fill, pos }); + gs.clip.intersect_rect(rect); + } + clip_next = false; + multiple_subpaths = false; + } + b"c" | b"v" | b"y" => path = Path::Other, + 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.text_render_mode = mode as u8; } } - b"S" | b"s" => { - if let Some(r) = std::mem::replace(&mut path, Path::Empty).stroked_rect(gs) - && gs.stroke_alpha >= 1.0 - { - self.out.push(FilledRect { rect: r, rgb: gs.stroke, pos }); + b"Tj" | b"TJ" | b"'" | b"\"" if shows_glyphs(op) => { + 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(GlyphSource { operators: text_start..i, painted: glyph_source_painted }); } } - b"n" => path = Path::Empty, - b"c" | b"v" | b"y" | b"W" | b"W*" => path = Path::Other, + b"BDC" => { + if hidden_depth > 0 || (op.name(0) == Some(b"OC") && self.layer_is_off(resources, op.operands.get(1))) { + hidden_depth += 1; + } + } + b"BMC" if hidden_depth > 0 => hidden_depth += 1, + b"EMC" => hidden_depth = hidden_depth.saturating_sub(1), b"Do" => { - if let Some(name) = op.name(0) { + if let Some(name) = op.name(0).filter(|_| hidden_depth == 0) { if depth >= MAX_DEPTH { return Err(AuditError::TooDeep); } self.walk_xobject(name, gs, resources, depth, pos)?; } path = Path::Empty; + clip_next = false; + multiple_subpaths = false; } _ => {} } @@ -318,6 +426,15 @@ impl<'a> Walker<'a> { Ok(()) } + fn layer_is_off(&self, resources: &Dict, property: Option<&Object>) -> bool { + let Object::Name(name) = property.unwrap_or(&Object::Null) else { + return matches!(property, Some(Object::Ref(id)) if self.off_layers.contains(id)); + }; + let props = resources.get(b"Properties").map(|value| self.doc.resolve(value)); + let layer = props.as_deref().and_then(Object::as_dict).and_then(|dict| dict.get(name)); + matches!(layer, Some(Object::Ref(id)) if self.off_layers.contains(id)) + } + /// Follow a form XObject read-only, composing its matrix onto the current CTM. State /// changes inside never leak out; every rectangle found is stamped with the `Do` /// position `pos`. @@ -331,6 +448,9 @@ impl<'a> Walker<'a> { if crate::subtype(self.doc, dict)?.as_deref() != Some(b"Form") { return Ok(()); } + if matches!(dict.get(b"OC"), Some(Object::Ref(id)) if self.off_layers.contains(id)) { + return Ok(()); + } let matrix = dict .get(b"Matrix") .map(|o| self.doc.resolve(o)) @@ -350,6 +470,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); + let bbox = dict.get(b"BBox").map(|value| self.doc.resolve(value)); + if let Some([x0, y0, x1, y1]) = + bbox.as_deref().and_then(Object::as_array).and_then(|operands| <&[Object; 4]>::try_from(operands.as_slice()).ok()).and_then(|values| { + let [x0, y0, x1, y1] = values.each_ref().map(|value| self.doc.resolve(value).as_f64()); + Some([x0?, y0?, x1?, y1?]).filter(|values| values.iter().all(|v| v.is_finite())) + }) + { + let bounds = [x0.min(x1), y0.min(y1), x0.max(x1), y0.max(y1)]; + let bbox = sub_gs.ctm.bbox(bounds); + if bbox.iter().all(|v| v.is_finite()) { + sub_gs.clip.intersect_rect(bbox); + } + } let mut sub_stack = Vec::new(); self.walk_ops(ops(&data), &mut sub_gs, &mut sub_stack, sub_resources, depth + 1, Some(pos)) } @@ -392,12 +525,37 @@ fn ext_state(doc: &Document, resources: &Dict, name: &[u8], gs: &mut Gs) { } } +/// 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() }; + let props = root.as_dict().and_then(|dict| dict.get(b"OCProperties")).map(|value| doc.resolve(value)); + let configuration = props.as_deref().and_then(Object::as_dict).and_then(|dict| dict.get(b"D")).map(|value| doc.resolve(value)); + let off = configuration.as_deref().and_then(Object::as_dict).and_then(|dict| dict.get(b"OFF")).map(|value| doc.resolve(value)); + off.as_deref() + .and_then(Object::as_array) + .into_iter() + .flatten() + .filter_map(|value| if let Object::Ref(id) = value { Some(*id) } else { None }) + .collect() +} + /// 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 /// 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(), @@ -414,7 +572,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 }; + 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..de29fb27a6 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,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 { - 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.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 436b2fc8c9..c7818365a6 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 @@ -1164,3 +1164,201 @@ fn every_finding_record_counts_against_the_output_bound() { let short = crate::Limits { covered_text: 3 * one - 1, ..exact }; assert!(matches!(crate::audit(&doc, short), Err(crate::AuditError::TooMuchOutput))); } + +#[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 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"; + 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(); + 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 rotation: keep the conservative bounding-box result. + 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_eq!(findings.len(), 1, "the rotated cover must still be reported: {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:?}"); +} diff --git a/crates/edit/src/lib.rs b/crates/edit/src/lib.rs index 365d06d776..64ff26c164 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 01a736ef9f..0a1714d761 100644 --- a/crates/edit/src/text.rs +++ b/crates/edit/src/text.rs @@ -69,7 +69,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 284914d4fa..166ffcd327 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, @@ -819,11 +821,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: @@ -942,6 +948,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 12f560a550..8e0d258ec6 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(); @@ -462,6 +487,9 @@ fn text_lines_in(doc: &Document, p: &pdfcraft_model::Page, actual_text: bool, in let properties = res.get(b"Properties").and_then(|o| doc.dict(o)).unwrap_or_default(); carry.containers = std::rc::Rc::new(super::containers::Containers::collect(doc, &ops, &res)); 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