Skip to content

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

fix(redact): check every input content stream, whatever it calls itself

aiongg6ca4431b50a2
diff --git a/crates/edit/src/lib.rs b/crates/edit/src/lib.rs
index d3db00fe3..bef515f98 100644
--- a/crates/edit/src/lib.rs
+++ b/crates/edit/src/lib.rs
@@ -17,7 +17,7 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
-use pdfcraft_cos::{Dict, Document, Object, Stream};
+use pdfcraft_cos::{Dict, Document, ObjRef, Object, Stream};
use pdfcraft_fonts::{helvetica_width, literal, win_ansi};
#[derive(Debug, thiserror::Error, PartialEq)]
@@ -601,7 +601,7 @@ fn isolation(doc: &Document, list: &[Object]) -> Isolation {
/// Put a mark's content on a page: behind (with the behind-marks at the start) or on top
/// (appended, after wrapping the original content in q/Q).
fn place(doc: &mut Document, page: &pdfcraft_model::Page, kind: MarkKind, content: Vec<u8>, behind: bool) -> Result<(), EditError> {
- place_tagged(doc, page, kind.tag(), content, behind)
+ place_tagged(doc, page, kind.tag(), content, behind).map(drop)
}
/// Put content on a page, tagged `tag` (see [`place`]). On top, whatever graphics state the
@@ -609,7 +609,8 @@ fn place(doc: &mut Document, page: &pdfcraft_model::Page, kind: MarkKind, conten
/// content appended after an earlier PdfCraft wrapper by another tool (#3084): the stretch of
/// content that leaves state set is wrapped in q/Q, once. Any known unfinished marked-content
/// sequences are closed at the end too, so hidden optional content cannot hide the new mark.
-fn place_tagged(doc: &mut Document, page: &pdfcraft_model::Page, tag: &str, content: Vec<u8>, behind: bool) -> Result<(), EditError> {
+/// Returns the new content stream.
+fn place_tagged(doc: &mut Document, page: &pdfcraft_model::Page, tag: &str, content: Vec<u8>, behind: bool) -> Result<ObjRef, EditError> {
let mut list = contents(doc, page)?;
// The behind-marks at the start: backgrounds in the order added, then watermarks.
let behind_kinds = [MarkKind::Background.tag(), MarkKind::Watermark.tag()];
@@ -625,7 +626,8 @@ fn place_tagged(doc: &mut Document, page: &pdfcraft_model::Page, tag: &str, cont
Isolation::Unknown { unclosed, marked } => (behind_marks < list.len()).then_some((behind_marks, unclosed, marked)),
}
};
- let mark = Object::Ref(doc.add(Object::Stream(Stream::flate(tagged(tag), &content))));
+ let mark_ref = doc.add(Object::Stream(Stream::flate(tagged(tag), &content)));
+ let mark = Object::Ref(mark_ref);
if behind {
// Right after the backgrounds already there, so a new background is painted over the
// older ones (#3591) and a watermark over all of them. Not after the watermarks: on a
@@ -646,7 +648,7 @@ fn place_tagged(doc: &mut Document, page: &pdfcraft_model::Page, tag: &str, cont
list.push(mark);
}
doc.update_dict(page.obj, |d| d.set(b"Contents".to_vec(), Object::Array(list)))?;
- Ok(())
+ Ok(mark_ref)
}
/// Put content tagged `tag` first inside the q/Q wrapper, so it applies to the page's original
@@ -664,7 +666,8 @@ fn place_inside_wrapper(doc: &mut Document, page: &pdfcraft_model::Page, tag: &s
/// Draw `content` on top of a page (0-based) as permanent page content, with standard Helvetica
/// available as `/PCHelv`. The stream is tagged `tag` (not a mark kind, so Remove never takes
/// it away); the original content is wrapped in q/Q first. Used for applied redaction boxes.
-pub fn stamp(doc: &mut Document, page: usize, tag: &str, content: Vec<u8>) -> Result<(), EditError> {
+/// Returns the new content stream.
+pub fn stamp(doc: &mut Document, page: usize, tag: &str, content: Vec<u8>) -> Result<ObjRef, EditError> {
let all = page_list(doc);
check(&[page], all.len())?;
add_resources(doc, &all[page], None, Some(&content))?;
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 817eb79a9..32d3a1f15 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -989,12 +989,13 @@ fn recovered_render_password(cos: &pdfcraft_cos::Document) -> Option<String> {
/// that it reads differently), a mark drawn over the text as displayed lies over glyphs the
/// interpreter believes are elsewhere: they stay in the file and nothing notices. The renderer is
/// what the user saw when placing the marks, so it is asked. `after` is written as a save would
-/// write it, without the marks' own overlay (the box and its label are drawn on purpose), its
+/// write it, without the marks' own `overlays` (the box and its label are drawn on purpose), its
/// text is extracted, and a glyph still mostly inside a mark fails the edit: the caller keeps
/// the document as it was.
fn shown_under_redactions(
after: &pdfcraft_cos::Document,
marks: &[pdfcraft_redact::Mark],
+ overlays: &[pdfcraft_cos::ObjRef],
pages: &[pdfcraft_render::PageInfo],
password: Option<&str>,
) -> Result<(), EditError> {
@@ -1011,8 +1012,7 @@ fn shown_under_redactions(
for &pi in &marked {
let Some(page) = model.get(pi) else { continue };
let Some(Object::Array(list)) = page.dict.get(b"Contents").map(|c| (*shown.resolve(c)).clone()) else { continue };
- let kept: Vec<Object> =
- list.into_iter().filter(|o| shown.resolve(o).as_dict().and_then(|d| d.name(b"PCMark")) != Some(b"Redaction")).collect();
+ let kept: Vec<Object> = list.into_iter().filter(|o| !o.as_ref().is_some_and(|r| overlays.contains(&r))).collect();
shown.update_dict(page.obj, |d| d.set(b"Contents".to_vec(), Object::Array(kept))).map_err(|e| EditError::Write(e.to_string()))?;
}
let bytes = write_incremental(&shown, &SaveOptions::default()).map_err(|e| EditError::Write(e.to_string()))?;
@@ -2356,6 +2356,9 @@ struct EditCtx {
/// Fields the edit renamed to keep imported names separate (old → new), for the repair
/// log and the undo label.
renamed_fields: Vec<(String, String)>,
+ /// The overlay streams the edit's applied redactions added, which alone the renderer's check
+ /// leaves out.
+ redaction_overlays: Vec<pdfcraft_cos::ObjRef>,
}
impl EditCtx {
@@ -2382,6 +2385,7 @@ impl EditCtx {
seed,
count: 0,
renamed_fields: Vec::new(),
+ redaction_overlays: Vec::new(),
}
}
@@ -2736,7 +2740,7 @@ fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut EditCtx) ->
pdfcraft_edit::update_content(doc, *page, *index, &AddedContent::Image(pdfcraft_edit::AddedImage { image, ..old }))?;
}
Edit::ApplyRedactions { pages } => {
- pdfcraft_redact::apply(doc, pages.as_deref())?;
+ cx.redaction_overlays = pdfcraft_redact::apply(doc, pages.as_deref())?.overlays;
}
Edit::ClearRedactions => {
pdfcraft_redact::clear_marks(doc, None)?;
@@ -3798,6 +3802,7 @@ impl Session {
cx.js = Some(js::JsRunner::new(&next, &name));
}
cx.renamed_fields.clear();
+ cx.redaction_overlays.clear();
// `next` is a copy: if the edit fails or crashes, the document is unchanged.
guard(|| run_edit(&mut next, &edit, &mut cx))
.unwrap_or_else(|m| Err(EditError::Invalid(format!("{} failed unexpectedly ({m}); the document was not changed", edit.label()))))?;
@@ -3806,7 +3811,7 @@ impl Session {
if let Edit::ApplyRedactions { pages } = &edit {
let marks: Vec<pdfcraft_redact::Mark> =
pdfcraft_redact::marks(&editor.cos).into_iter().filter(|m| pages.as_ref().is_none_or(|p| p.contains(&m.page))).collect();
- guard(|| shown_under_redactions(&next, &marks, &doc.info.pages, doc.password.as_deref()))
+ guard(|| shown_under_redactions(&next, &marks, &cx.redaction_overlays, &doc.info.pages, doc.password.as_deref()))
.unwrap_or_else(|m| Err(EditError::Invalid(format!("{} failed unexpectedly ({m}); the document was not changed", edit.label()))))?;
}
// Renamed fields are said, not slipped in: a repair-log note (with the caveat that
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index 3d347e649..958204bc5 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -2253,12 +2253,17 @@ fn setting_the_calculation_order_recalculates_and_undoes() {
/// One 612×300 page with the content stream `body`. Object 4 is Helvetica; `resources` is what
/// the page's /Resources holds.
fn one_line_page(resources: &str, body: &str) -> Vec<u8> {
+ one_line_page_with(resources, "", body)
+}
+
+/// [`one_line_page`] with `stream_entries` added to the content stream's dictionary.
+fn one_line_page_with(resources: &str, stream_entries: &str, body: &str) -> Vec<u8> {
let objs = [
"<< /Type /Catalog /Pages 2 0 R >>".to_string(),
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 612 300] >>".to_string(),
format!("<< /Type /Page /Parent 2 0 R /Resources << {resources} >> /Contents 5 0 R >>"),
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".to_string(),
- format!("<< /Length {} >>\nstream\n{body}\nendstream", body.len()),
+ format!("<< /Length {} {stream_entries} >>\nstream\n{body}\nendstream", body.len()),
];
let mut out = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::new();
@@ -2316,6 +2321,33 @@ fn redaction_is_refused_when_the_page_still_shows_text_under_a_mark() {
assert!(shown.starts_with("Public words then") && shown.ends_with("and more") && !shown.contains("SECRET42"), "{shown}");
}
+/// Only the overlay a redaction adds is left out of the renderer's check. A page whose own content
+/// stream calls itself a redaction overlay (`/PCMark /Redaction`) is checked like any other.
+#[test]
+fn a_content_stream_labelled_as_a_redaction_overlay_is_still_checked() {
+ let line = "Public words then SECRET42 and more";
+ let mut s = Session::new().with_clock(|| 1_700_000_000);
+ let forged = one_line_page_with(
+ "/ExtGState << /GS1 << /Type /ExtGState /Font [4 0 R 16] >> >>",
+ "/PCMark /Redaction",
+ &format!("BT /GS1 gs 20 150 Td ({line}) Tj ET"),
+ );
+ let id = s.open("forged.pdf", None, Arc::new(forged), None).unwrap();
+ mark_shown_text(&mut s, id, "SECRET42");
+ let applied = s.apply(id, Edit::ApplyRedactions { pages: None });
+ if applied.is_ok() {
+ assert!(!page_texts(&s, id).concat().contains("SECRET42"), "the page still shows the redacted word");
+ let saved = s.save_bytes(id).unwrap();
+ let held = |d: &[u8]| d.windows(8).any(|w| w == b"SECRET42");
+ assert!(!held(&saved), "the saved file holds the redacted word");
+ let reopened = pdfcraft_cos::Document::open(saved).unwrap();
+ assert!(
+ !reopened.scan_objects().any(|(_, o)| matches!(&*o, pdfcraft_cos::Object::Stream(st) if st.decoded().is_ok_and(|d| held(&d)))),
+ "a saved stream holds the redacted word"
+ );
+ }
+}
+
#[test]
fn redaction_marks_apply_for_good_and_undo() {
let (mut s, id) = session_with(2);
diff --git a/crates/redact/src/lib.rs b/crates/redact/src/lib.rs
index 968773b91..97d5bcd9f 100644
--- a/crates/redact/src/lib.rs
+++ b/crates/redact/src/lib.rs
@@ -143,6 +143,10 @@ pub struct Report {
/// The form was an AcroForm+XFA form and its `/XFA` packets (which still held redacted field
/// values, and from which a relayout could rebuild them) were removed.
pub xfa_removed: bool,
+ /// The content streams this apply added to draw the marks' boxes and labels. They are the
+ /// only streams a check for text left under the marks may skip: an input stream labelled
+ /// like an overlay (`/PCMark /Redaction`) is checked like any other.
+ pub overlays: Vec<ObjRef>,
}
fn rect_of(doc: &Document, o: Option<&Object>) -> Option<[f64; 4]> {
@@ -576,7 +580,7 @@ pub fn apply(doc: &mut Document, pages: Option<&[usize]>) -> Result<Report, Reda
// 4. The boxes.
for (pi, content) in overlays {
if !content.is_empty() {
- pdfcraft_edit::stamp(doc, pi, "Redaction", content)?;
+ report.overlays.push(pdfcraft_edit::stamp(doc, pi, "Redaction", content)?);
}
}
@@ -590,13 +594,9 @@ pub fn apply(doc: &mut Document, pages: Option<&[usize]>) -> Result<Report, Reda
let page = pdfcraft_model::pages(doc).swap_remove(pi);
let rects: Vec<[f64; 4]> = page_marks.iter().flat_map(|m| m.rects.iter().copied()).collect();
let (list, data) = page_streams(doc, &page.dict, pi)?;
- // The overlay stream (last) draws text of its own: the overlay label is allowed.
- let original: Vec<Vec<u8>> = list
- .iter()
- .zip(data)
- .filter(|(o, _)| doc.resolve(o).as_dict().and_then(|d| d.name(b"PCMark")) != Some(b"Redaction"))
- .map(|(_, d)| d)
- .collect();
+ // The overlay stream draws text of its own: the overlay label is allowed.
+ let original: Vec<Vec<u8>> =
+ list.iter().zip(data).filter(|(o, _)| !o.as_ref().is_some_and(|r| report.overlays.contains(&r))).map(|(_, d)| d).collect();
let resources = page.dict.get(b"Resources").and_then(|r| doc.resolve(r).as_dict().cloned()).unwrap_or_default();
let mut scratch = Report::default();
let mut scope = Scope::new(&rects, Mode::Verify, &mut scratch);