diff --git a/ROADMAP.md b/ROADMAP.md index 39757bf47a..73aef0d191 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -362,6 +362,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md - **2026-10-26 (M3, view.text-select):** Text selection runs across pages: dragging onto another page (also a quick flick off the page, and the edge and wheel scrolling of #721/#1670) or ⇧-clicking there selects the rest of the first page, the pages between and the last page up to the pointer. Copy has each page's part on a line of its own, reading pages not yet read off the UI thread; highlight, underline, strikethrough and Redact put one mark on each page in one undo step (a tool that finishes first marks once the pages are read; Redact refuses a selection over a page whose text could not be read); Add comment and Replace text stay one-page. A drag from one page's text that is already over the next when it starts no longer begins a Redact or area-highlight box there. Estimates unchanged. - **2026-10-25 (M5, comment replies):** One reply can be deleted from the Comments panel without its thread. On the selected card each reply has its own "…" menu (Edit, Copy text, Delete); Delete takes that reply with its pop-up and the replies to it, as `comment_delete` already did headlessly, and the comment and its other replies stay. The card stays selected, and the panel's editor stays open, on what they were on though the delete moved it in `/Annots`. Undo and Redo close the editor, since either can move what it was open on. A locked reply can't be deleted. Estimates unchanged. - **2026-10-25 (M7, #2750):** Single-style Keep source fonts edits retain source glyphs and batch only missing glyphs in fallback fonts. Per-rewrite character eligibility and widths are cached; source and fallback edge spaces stay extractable. Estimates unchanged. +- **2026-10-25 (M2, #2670):** Malformed-object diagnostics share a bounded per-load budget across compressed objects and encrypted containers, with a strict-mode summary and silent metadata reads. Estimates unchanged. - **2026-10-25 (M4, #2725):** Dismissing the ordinary form-field reminder persists across launches, while security, repair and XFA notices keep their independent controls and defaults. Estimates unchanged. - **2026-10-25 (M10, #4399):** The printer picker has a wider searchable list, wrapped device names, stable selection while filtering, and Search and Save as PDF kept visible. Synthetic fleet UI regressions cover long lists and a smaller window. Estimates unchanged. - **2026-10-25 (web, same-document host mode):** A page that loads the PdfCraft web module into its own document (no iframe) can opt into the host bridge with `data-host="page"` on the app's canvas — the exact value `page`; any other value keeps the normal app with downloads, unless a same-origin framed `?host=parent` selects the parent bridge (unframed or cross-origin, `?host=parent` also keeps the normal app). It is the `?host=parent` bridge with the transport swapped: the same five messages travel as non-bubbling `CustomEvent`s on the canvas (`detail` holds the parent messages' fields without `type`; the host answers with a `pdfcraft:open` event), so saves reach the host instead of downloading and dirty and start-up-failure reporting are unchanged. Unit tests cover the opt-in rule; no parity or estimate changes. diff --git a/crates/a11y/src/autotag.rs b/crates/a11y/src/autotag.rs index 42dc37b978..ea04615ea4 100644 --- a/crates/a11y/src/autotag.rs +++ b/crates/a11y/src/autotag.rs @@ -138,6 +138,24 @@ fn page_fonts(doc: &Document, page: &Dict) -> Dict { .unwrap_or_default() } +/// Marked-content tags the text editor writes inside a text object. +const EDITOR_MARKS: [&[u8]; 4] = [b"Span", b"PCSoft", b"PCHard", b"P"]; + +/// Whether `op` opens one of the text editor's marked-content sequences. One that carries an +/// `/MCID` is another writer's structure content and would collide with the new MCIDs; `/OC` +/// layers and the like are not the editor's. An imported PDF can carry surplus operands, which the +/// renderer reads from the end, so the operand count (one for BMC, two for BDC) is checked first. +fn editor_mark(op: &Op) -> bool { + match (op.op.as_slice(), op.operands.len()) { + (b"BMC", 1) => op.name(0).is_some_and(|tag| EDITOR_MARKS.contains(&tag)), + (b"BDC", 2) => { + op.name(0).is_some_and(|tag| EDITOR_MARKS.contains(&tag)) + && op.operands.get(1).and_then(Object::as_dict).is_some_and(|d| !d.contains(b"MCID")) + } + _ => false, + } +} + fn harmless_outside(op: &[u8]) -> bool { matches!( op, @@ -151,6 +169,15 @@ fn harmless_outside(op: &[u8]) -> bool { | b"ri" | b"i" | b"gs" + // Text state is legal outside BT/ET and carries into the next text object; a text edit + // writes it there after its own text object. + | b"Tf" + | b"Tc" + | b"Tw" + | b"Tz" + | b"TL" + | b"Tr" + | b"Ts" | b"G" | b"g" | b"RG" @@ -251,14 +278,23 @@ fn plan_page( } let xobjects = page_xobjects(doc, &page.dict); let (mut start, mut has_text, mut spans, mut artifacts) = (None, false, Vec::new(), HashMap::new()); - // Marked-content boundaries must enclose the whole path, not just its paint operator. - let mut path = None; + // The text editor's own marked content (`/Span` keeps an /ActualText, `/PCSoft` and `/PCHard` + // mark wrapped lines, `/P` a paragraph), in or between text objects. It stays in the stream, + // around or inside the paragraph's own marked content, and must be balanced: `open` counts the + // sequences now open, `base` those open at the current BT, which an EMC inside it may not close. + let (mut open, mut base) = (0usize, 0usize); + // Marked-content boundaries must enclose the whole path, not just its paint operator. `events` + // counts every mark opened or closed so far and the path keeps its value at the first operator: + // any mark opened or closed inside the path (even one that leaves `open` as it was, such as a + // close followed by another open) would cross the artifact wrapper added around it. + let (mut events, mut path): (usize, Option<(usize, usize)>) = (0, None); for (at, op) in parsed.ops.iter().enumerate() { if path.is_some() && matches!(op.op.as_slice(), b"BT" | b"Do" | b"BI" | b"sh") { return Err(unsupported(index, "painted content interrupts an unfinished path")); } match op.op.as_slice() { - b"BT" if start.is_none() => (start, has_text) = (Some(at), false), + b"BT" if start.is_none() => (start, has_text, base) = (Some(at), false, open), + b"ET" if start.is_some() && open != base => return Err(unsupported(index, "unterminated marked content in a text object")), b"ET" => { let Some(first) = start.take() else { return Err(unsupported(index, "unmatched ET operator")) }; if has_text { @@ -270,16 +306,22 @@ fn plan_page( } b"Tj" | b"TJ" | b"'" | b"\"" if start.is_some() => has_text = true, name if start.is_some() && harmless_inside(name) => {} + b"BDC" | b"BMC" if editor_mark(op) => (open, events) = (open + 1, events + 1), + b"EMC" if op.operands.is_empty() && open > if start.is_some() { base } else { 0 } => (open, events) = (open - 1, events + 1), name if start.is_none() && harmless_outside(name) => match name { b"m" | b"re" => { - path.get_or_insert(at); + path.get_or_insert((at, events)); } b"n" => path = None, _ => {} }, _ if start.is_none() && painted_outside(doc, &xobjects, op) => { let first = if matches!(op.op.as_slice(), b"f" | b"F" | b"f*" | b"B" | b"B*" | b"b" | b"b*" | b"S" | b"s") { - path.take().unwrap_or(at) + match path.take() { + Some((_, seen)) if seen != events => return Err(unsupported(index, "marked content opens or closes inside a path")), + Some((first, _)) => first, + None => at, + } } else { at }; @@ -288,6 +330,9 @@ fn plan_page( _ => return Err(unsupported(index, format!("unsupported or painted operator {}", String::from_utf8_lossy(&op.op)))), } } + if open > 0 { + return Err(unsupported(index, "unterminated marked content")); + } if start.is_some() { return Err(unsupported(index, "unterminated BT text object")); } diff --git a/crates/a11y/tests/cross_stream.rs b/crates/a11y/tests/cross_stream.rs index d0a2f48204..b8fac8794f 100644 --- a/crates/a11y/tests/cross_stream.rs +++ b/crates/a11y/tests/cross_stream.rs @@ -258,3 +258,66 @@ fn mark_decorative_and_mark_artifact_keep_cross_stream_comment_hidden() { let report_after = check(&comment_only, &Options { rules: [Rule::TaggedContent].into(), pages: None }); assert_eq!(report_after.result(Rule::TaggedContent).expect("rule result").status, Status::Passed); } + +fn one_stream(content: &str) -> Document { + build_pdf(&[ + (1, "<< /Type /Catalog /Pages 2 0 R >>".into()), + (2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into()), + (3, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 5 0 R /Resources << /Font << /F1 4 0 R >> >> >>".into()), + (4, FONT.into()), + (5, stream(content)), + ]) +} + +/// #7416: the text editor's own balanced marked content, in and between text objects, does not +/// stop Auto-tag and stays in the stream. +#[test] +fn autotag_accepts_the_text_editors_balanced_marked_content() { + let content = "/P BMC /Span <> BDC BT /F1 12 Tf 72 700 Td (a) Tj /PCSoft <> BDC EMC (b) Tj /PCHard BMC EMC ET EMC EMC\n\ + /P BMC BT /F1 12 Tf 72 680 Td /Span <> BDC (c) Tj EMC ET EMC"; + let mut doc = one_stream(content); + let result = autotag_text(&mut doc).expect("autotag succeeds"); + assert_eq!(result.paragraphs, 2); + let (ops, skipped) = joined_ops(&doc); + assert_eq!(skipped, 0); + let count = |name: &str| ops.iter().filter(|op| op.is(name)).count(); + assert_eq!(count("BDC"), count("EMC") - count("BMC"), "every mark is closed"); + let mut open = Vec::new(); + for op in &ops { + if op.is("BDC") || op.is("BMC") { + open.push(op.name(0).unwrap().to_vec()); + } else if op.is("EMC") { + open.pop().expect("no stray EMC"); + } else if op.is("Tj") { + assert!(open.iter().any(|t| t == b"P"), "text sits inside a paragraph mark"); + } + } + assert!(open.is_empty()); + assert!( + ops.iter() + .any(|op| op.is("BDC") && op.name(0) == Some(b"Span".as_slice()) && op.operands[1].as_dict().is_some_and(|d| d.contains(b"ActualText"))) + ); +} + +/// What stays refused: marks that are not the editor's, or that are not balanced. +#[test] +fn autotag_refuses_marked_content_it_cannot_nest() { + for (why, content) in [ + ("an optional-content layer in a text object", "BT /F1 12 Tf 72 700 Td /OC /L BDC (a) Tj EMC ET"), + ("a stray EMC", "BT /F1 12 Tf 72 700 Td (a) Tj ET EMC"), + ("an EMC in a text object closing a mark opened before it", "/P BMC BT /F1 12 Tf 72 700 Td (a) Tj EMC ET"), + ("a span open at ET", "BT /F1 12 Tf 72 700 Td /Span <> BDC (a) Tj ET EMC"), + ("a span never closed", "/Span <> BDC BT /F1 12 Tf 72 700 Td (a) Tj ET"), + ("a span opened inside a path", "0 0 m /Span BMC 10 10 l S BT /F1 12 Tf 72 700 Td (a) Tj ET EMC"), + ("a span closed inside a path", "/Span BMC 0 0 m EMC 10 10 l S BT /F1 12 Tf 72 700 Td (a) Tj ET"), + ("a mark closed and another opened inside a path", "/P BMC 0 0 m EMC /Span BMC 10 10 l S BT /F1 12 Tf 72 700 Td (a) Tj ET EMC"), + ("surplus operands before BMC", "/P /OC BMC BT /F1 12 Tf 72 700 Td (a) Tj ET EMC"), + ("surplus operands before BDC", "/P <<>> /Span <> BDC BT /F1 12 Tf 72 700 Td (a) Tj ET EMC"), + ("an operand before EMC", "/P BMC BT /F1 12 Tf 72 700 Td (a) Tj ET /Unexpected EMC"), + ("another writer's span with an MCID", "/Span <> BDC BT /F1 12 Tf 72 700 Td (a) Tj ET EMC"), + ] { + let mut doc = one_stream(content); + let err = autotag_text(&mut doc).expect_err(why); + assert!(err.to_string().contains("unsupported") || err.to_string().contains("page 1"), "{why}: {err}"); + } +} diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index 1d87961cac..9154be186b 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -640,6 +640,89 @@ fn autotag_apply_writes_reviewable_tags_and_survives_save_reopen() { assert!(pages.iter().all(|page| page.dict.contains(b"StructParents"))); } +/// #7416: the text state a PDFCraft text edit writes after its text object (`0 Tc`, `0 Tw`, +/// `100 Tz`, `0 TL`, `0 Ts`) is legal outside BT/ET and must not stop Auto-tag. +#[test] +fn autotag_apply_accepts_text_state_written_by_a_text_edit() { + let dir = workdir("autotag-after-edit"); + let page = |text: &str| format!("BT /FR 12 Tf 1 0 0 1 40 180 Tm ({text}) Tj ET"); + std::fs::write(dir.join("moss.pdf"), bold_and_regular_pdf(&page("Moss stays green."), &page("Quiet control page."))).unwrap(); + let mut a = auto(&dir); + let doc = ok(&mut a, "doc_open", json!({ "path": "moss.pdf" }))["doc"].as_u64().unwrap(); + ok(&mut a, "text_edit", json!({ "doc": doc, "page": 1, "paragraph": 1, "text": "Fern stays green." })); + let applied = ok(&mut a, "accessibility_autotag_apply", json!({ "doc": doc })); + assert_eq!(applied["count"], 3, "Document plus one paragraph per page"); + assert_eq!(applied["tags"][1]["type"], "P"); + std::fs::remove_dir_all(dir).unwrap(); +} + +/// #7416: a wrapped edit in the repo font (Helvetica, no /Encoding) writes `/PCSoft BDC EMC` between +/// its lines inside the text object; Auto-tag takes it, keeps it in the stream inside the +/// paragraph's mark. (The `/Span` + `/ActualText` form is covered in the a11y tests.) +#[test] +fn autotag_apply_accepts_line_markers_written_by_a_text_edit() { + let dir = workdir("autotag-after-edit-span"); + std::fs::write(dir.join("one.pdf"), fixture(1)).unwrap(); + let mut a = auto(&dir); + let doc = ok(&mut a, "doc_open", json!({ "path": "one.pdf" }))["doc"].as_u64().unwrap(); + ok(&mut a, "text_edit", json!({ "doc": doc, "page": 1, "paragraph": 1, "text": "Fern stays green." })); + let applied = ok(&mut a, "accessibility_autotag_apply", json!({ "doc": doc })); + assert_eq!(applied["count"], 2, "Document plus the edited paragraph"); + assert_eq!(applied["tags"][1]["type"], "P"); + ok(&mut a, "doc_save", json!({ "doc": doc, "path": "tagged.pdf" })); + let re = ok(&mut a, "doc_open", json!({ "path": "tagged.pdf" }))["doc"].as_u64().unwrap(); + assert_eq!(page_text(&mut a, re), ["Fern stays\ngreen."]); + let content = page_content(&dir.join("tagged.pdf")); + assert!(content.find("/MCID").unwrap() < content.find("/PCSoft").unwrap(), "the line marker stays inside the paragraph's mark: {content}"); + std::fs::remove_dir_all(dir).unwrap(); +} + +/// #7416: a typed newline, mixed styles and text the font cannot show take the editor's rich path, which writes `/P BMC`, +/// `/PCHard BMC` and `/Span` marks between and around its text objects; Auto-tag takes them too. +#[test] +fn autotag_apply_accepts_a_newline_and_mixed_style_edit() { + for (name, edit) in [ + ("newline", json!({ "text": "a\nb" })), + ("fallback", json!({ "text": "Fern \u{3a9} stays" })), + ("ranges", json!({ "text": "Fern stays", "ranges": [{ "range": [0, 4], "size": 16, "color": "#cc0000" }] })), + ] { + let dir = workdir(&format!("autotag-rich-{name}")); + std::fs::write(dir.join("one.pdf"), fixture(1)).unwrap(); + let mut a = auto(&dir); + let doc = ok(&mut a, "doc_open", json!({ "path": "one.pdf" }))["doc"].as_u64().unwrap(); + let mut args = json!({ "doc": doc, "page": 1, "paragraph": 1 }); + args.as_object_mut().unwrap().extend(edit.as_object().unwrap().clone()); + ok(&mut a, "text_edit", args); + let applied = ok(&mut a, "accessibility_autotag_apply", json!({ "doc": doc })); + assert_eq!(applied["tags"][1]["type"], "P", "{name}"); + ok(&mut a, "doc_save", json!({ "doc": doc, "path": "tagged.pdf" })); + let content = page_content(&dir.join("tagged.pdf")); + assert!(content.contains("/MCID"), "{name}: {content}"); + let (begins, ends) = (content.matches("BDC").count() + content.matches("BMC").count(), content.matches("EMC").count()); + assert_eq!(begins, ends, "{name}: marks stay balanced: {content}"); + std::fs::remove_dir_all(dir).unwrap(); + } +} + +/// The decoded content stream of the first page of the PDF at `path`. +fn page_content(path: &Path) -> String { + let doc = pdfcraft_cos::Document::open(std::sync::Arc::new(std::fs::read(path).unwrap())).unwrap(); + let page = &pdfcraft_model::pages(&doc)[0]; + let contents = doc.resolve(page.dict.get(b"Contents").unwrap()); + let streams = match &*contents { + pdfcraft_cos::Object::Array(items) => items.iter().map(|i| doc.resolve(i)).collect(), + _ => vec![contents.clone()], + }; + streams + .iter() + .filter_map(|s| match &**s { + pdfcraft_cos::Object::Stream(s) => Some(String::from_utf8_lossy(&s.decoded().unwrap()).into_owned()), + _ => None, + }) + .collect::>() + .join("\n") +} + /// #7062: Apply tags short text larger than the body as headings, ranked across the pages, and /// the body text as paragraphs. #[test] diff --git a/crates/render/tests/object_load_logging.rs b/crates/render/tests/object_load_logging.rs new file mode 100644 index 0000000000..24002a9bc1 --- /dev/null +++ b/crates/render/tests/object_load_logging.rs @@ -0,0 +1,619 @@ +//! Keep compatibility-reader diagnostics useful when one damaged file has many bad objects. +//! This integration binary owns its logger; the lock isolates captures between tests, while +//! lopdf's default Rayon workers still execute concurrently inside each read. + +use std::sync::{Arc, Mutex, Once}; + +use log::{Level, LevelFilter, Log, Metadata, Record}; +use lopdf::{Document, LoadOptions}; + +static TEST_LOCK: Mutex<()> = Mutex::new(()); +static RECORDS: Mutex> = Mutex::new(Vec::new()); +static INIT: Once = Once::new(); +struct Capture; +impl Log for Capture { + /// Capture only diagnostics emitted by the compatibility reader. + fn enabled(&self, metadata: &Metadata<'_>) -> bool { + metadata.target().starts_with("lopdf::") + } + /// Record matching messages and severity for the serialized test capture. + fn log(&self, record: &Record<'_>) { + if self.enabled(record.metadata()) { + RECORDS.lock().unwrap_or_else(|e| e.into_inner()).push((record.level(), record.args().to_string())); + } + } + /// Keep captured records until the test explicitly clears them. + fn flush(&self) {} +} + +/// Install the shared logger once and clear records under the caller's test lock. +fn start_capture() { + INIT.call_once(|| { + log::set_logger(&Capture).unwrap(); + log::set_max_level(LevelFilter::Trace); + }); + RECORDS.lock().unwrap_or_else(|e| e.into_inner()).clear(); +} + +/// Snapshot captured diagnostics, recovering the test mutex after poisoning. +fn records() -> Vec<(Level, String)> { + RECORDS.lock().unwrap_or_else(|e| e.into_inner()).clone() +} + +/// Build a readable synthetic page with requested malformed objects and stream containers. +fn fixture(bad_objects: usize, bad_streams: usize) -> Vec { + // The page is readable even though unrelated indirect objects are not. + let names = if bad_objects > 0 { " /Names 6 0 R" } else { "" }; + let mut objects = vec![ + format!("<< /Type /Catalog /Pages 2 0 R{names} >>").into_bytes(), + b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 300] /Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>".to_vec(), + b"<< /Length 38 >>\nstream\nBT /F1 12 Tf 20 150 Td (Visible) Tj ET\nendstream".to_vec(), + b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_vec(), + ]; + objects.extend((0..bad_objects).map(|_| b"not-a-pdf-object".to_vec())); + objects.extend((0..bad_streams).map(|_| invalid_object_stream())); + pdf_with_objects(objects) +} + +/// An object stream whose member-header offset lies past its one-byte content. +fn invalid_object_stream() -> Vec { + b"<< /Type /ObjStm /N 1 /First 99 /Length 1 >>\nstream\nx\nendstream".to_vec() +} + +/// Serialize synthetic indirect objects with a classic cross-reference table. +fn pdf_with_objects(objects: Vec>) -> Vec { + let mut pdf = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, object) in objects.iter().enumerate() { + offsets.push(pdf.len()); + pdf.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes()); + pdf.extend_from_slice(object); + pdf.extend_from_slice(b"\nendobj\n"); + } + let xref = pdf.len(); + pdf.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes()); + for offset in offsets { + pdf.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes()); + } + pdf.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).as_bytes()); + pdf +} + +/// Misplace startxref to exercise compatibility inspection and its diagnostic budget. +fn compatibility_fixture() -> Vec { + // A known producer mistake: startxref points just after "xref", so COS records a repair + // and inspect uses the eager compatibility reader. The ordinary parser repairs it too. + let pdf = String::from_utf8(fixture(1250, 0)).unwrap(); + let xref = pdf.find("xref\n").unwrap(); + let start = pdf.rfind("startxref\n").unwrap(); + format!("{}startxref\n{}\n%%EOF\n", &pdf[..start], xref + 4).into_bytes() +} + +/// Require eight error details, one exact summary, and no unbudgeted messages. +fn assert_bounded(messages: &[(Level, String)], total: usize, streams: usize) { + let details = messages.iter().filter(|(_, s)| s.starts_with("Object load error") || s.starts_with("Object stream load error")).count(); + assert_eq!(details, 8, "expected bounded details, captured {} records", messages.len()); + let summaries: Vec<_> = messages.iter().filter(|(_, s)| s.starts_with("Object loading:")).collect(); + assert_eq!(summaries.len(), 1); + assert!(summaries[0].1.contains(&format!("{total} failed objects ({streams} object streams)")), "{summaries:?}"); + assert!(summaries[0].1.contains(&format!("{} additional messages suppressed", total - 8)), "{summaries:?}"); + assert_eq!(messages.len(), 9, "no extra per-object log sites should bypass the budget"); + assert!(messages.iter().all(|(level, _)| *level == Level::Error)); +} + +/// Keep a readable page while summarizing 1,250 malformed objects in nine records. +#[test] +fn malformed_objects_log_bounded_details_and_an_exact_summary() { + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + start_capture(); + let doc = Document::load_mem(&fixture(1250, 0)).unwrap(); + assert_eq!(doc.get_pages().len(), 1); + assert!(doc.get_object((5, 0)).is_ok(), "readable objects are retained"); + assert_bounded(&records(), 1250, 0); +} + +/// Count ordinary and compressed-object failures in the same eight-detail allowance. +#[test] +fn ordinary_and_object_stream_failures_share_one_log_budget() { + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + start_capture(); + let doc = Document::load_mem(&fixture(20, 30)).unwrap(); + assert_eq!(doc.get_pages().len(), 1); + assert_bounded(&records(), 50, 30); +} + +/// Give each compatibility inspection its own budget while retaining the xref repair warning. +#[test] +fn compatibility_inspection_gets_a_fresh_budget_on_every_open() { + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let pdf = Arc::new(compatibility_fixture()); + for _ in 0..2 { + start_capture(); + let info = pdfcraft_render::inspect(pdf.clone(), None).unwrap(); + assert_eq!(info.pages.len(), 1); + let messages = records(); + assert!(messages.iter().any(|(level, text)| *level == Level::Warn && text.starts_with("Cross-reference offset "))); + let object_messages: Vec<_> = messages.into_iter().filter(|(_, text)| !text.starts_with("Cross-reference offset ")).collect(); + assert_bounded(&object_messages, 1250, 0); + } +} + +/// Keep healthy reads silent and preserve every diagnostic within the allowance. +#[test] +fn healthy_and_small_damaged_files_keep_their_diagnostics() { + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + start_capture(); + Document::load_mem(&fixture(0, 0)).unwrap(); + assert!(records().is_empty()); + for count in [1, 3, 8] { + start_capture(); + Document::load_mem(&fixture(count, 0)).unwrap(); + let messages = records(); + assert_eq!(messages.len(), count); + assert!(messages.iter().all(|(level, s)| *level == Level::Error && s.starts_with("Object load error at offset "))); + } +} + +/// Preserve strict read errors while bounding diagnostics from concurrent workers. +#[test] +fn strict_loading_still_refuses_malformed_objects() { + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + for (objects, streams) in [(1250, 0), (0, 1250)] { + start_capture(); + let result = Document::load_mem_with_options(&fixture(objects, streams), LoadOptions { strict: true, ..Default::default() }); + assert!(result.is_err()); + let messages = records(); + assert!(!messages.is_empty()); + assert!(messages.len() <= 9, "strict Rayon reads also share a bounded budget"); + assert!(messages.iter().all(|(level, _)| *level == Level::Error)); + } +} + +/// Give concurrent documents separate detail allowances and summary totals. +#[test] +fn concurrent_document_reads_have_independent_budgets() { + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + start_capture(); + let a = std::thread::spawn(|| Document::load_mem(&fixture(50, 0)).unwrap().get_pages().len()); + let b = std::thread::spawn(|| Document::load_mem(&fixture(50, 0)).unwrap().get_pages().len()); + assert_eq!(a.join().unwrap(), 1); + assert_eq!(b.join().unwrap(), 1); + let messages = records(); + assert_eq!(messages.len(), 18, "two reads each get eight details and one summary"); + assert_eq!(messages.iter().filter(|(_, s)| s.starts_with("Object loading:") && s.contains("42 additional messages suppressed")).count(), 2); +} + +// Missing/broken indirect Length leaves a deferred stream; its later lookup also +// belongs to this read's budget, even though eager object collection has finished. +/// Charge missing and broken indirect lengths to the original read budget. +#[test] +fn deferred_stream_length_errors_share_the_load_budget() { + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + for length in ["", " /Length 999999 0 R"] { + start_capture(); + let objects = (0..1250).map(|_| format!("<<{length} >>\nstream\nx\nendstream").into_bytes()).collect(); + let doc = Document::load_mem(&pdf_with_objects(objects)).unwrap(); + assert_eq!(doc.objects.len(), 1250, "diagnostic suppression must retain the streams"); + let messages = records(); + assert_eq!(messages.len(), 9, "missing/broken Length logs bypass the budget"); + assert_eq!(messages.iter().filter(|(_, s)| s.contains("missing the Length entry")).count(), 8); + let summary = &messages.last().unwrap().1; + assert!(summary.contains("1250 stream length errors"), "{summary}"); + assert!(summary.contains("1242 additional messages suppressed"), "{summary}"); + assert!(messages.iter().all(|(level, _)| *level == Level::Error)); + } +} + +/// Build synthetic object-stream members with bad, duplicate, or empty offsets. +fn member_stream(count: usize, kind: &str) -> Vec { + let index: String = (0..count) + .map(|i| { + let offset = match kind { + "outside" => 10000, + "duplicate" => 0, + "whitespace" => i, + _ => unreachable!(), + }; + format!("{} {offset} ", 10000 + i) + }) + .collect(); + let body = if kind == "whitespace" { " ".repeat(count) } else { "42".to_owned() }; + let content = format!("{index}{body}"); + format!("<< /Type /ObjStm /N {count} /First {} /Length {} >>\nstream\n{content}\nendstream", index.len(), content.len()).into_bytes() +} + +/// Share one warning allowance across every object-stream member in a document. +#[test] +fn object_stream_member_warnings_are_bounded_across_all_streams() { + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + for kind in ["outside", "duplicate", "whitespace"] { + start_capture(); + Document::load_mem(&pdf_with_objects(vec![member_stream(1000, kind), member_stream(1000, kind)])).unwrap(); + let messages = records(); + let total = if kind == "duplicate" { 1998 } else { 2000 }; + assert_eq!(messages.len(), 9, "{kind}: per-member logs bypass the budget"); + let summary = &messages.last().unwrap().1; + assert!(summary.contains(&format!("{total} object stream warnings")), "{summary}"); + assert!(summary.contains(&format!("{} additional messages suppressed", total - 8)), "{summary}"); + assert!(messages.iter().all(|(level, _)| *level == Level::Warn)); + } +} + +/// Combine diagnostic categories in one summary at the highest encountered severity. +#[test] +fn mixed_errors_and_warnings_share_one_budget_and_summary() { + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + start_capture(); + let mut objects = vec![member_stream(1000, "outside"), b"not-an-object".to_vec()]; + objects.extend((0..20).map(|_| b"<< >>\nstream\nx\nendstream".to_vec())); + Document::load_mem(&pdf_with_objects(objects)).unwrap(); + let messages = records(); + assert_eq!(messages.len(), 9); + let (level, summary) = messages.last().unwrap(); + assert_eq!(*level, Level::Error, "the summary must retain the highest severity"); + for text in + ["1 failed objects (0 object streams)", "1000 object stream warnings", "20 stream length errors", "1013 additional messages suppressed"] + { + assert!(summary.contains(text), "{summary}"); + } +} + +/// Emit exact suppressed-message totals before returning a deterministic strict failure. +#[test] +fn strict_error_still_reports_the_suppressed_diagnostics() { + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + // The reader expands containers in object-number order after the ordinary-object pass. + // The first container consumes the allowance before the second produces a strict error. + start_capture(); + let pdf = pdf_with_objects(vec![member_stream(1000, "outside"), invalid_object_stream()]); + let result = Document::load_mem_with_options(&pdf, LoadOptions { strict: true, ..Default::default() }); + assert!(result.is_err(), "strict refusal must survive log suppression"); + let messages = records(); + assert_eq!(messages.len(), 9, "strict failure must emit the summary before returning"); + let (level, summary) = messages.last().unwrap(); + assert_eq!(*level, Level::Error); + assert!(summary.starts_with("Object loading:"), "{messages:?}"); + assert!(summary.contains("1 failed objects (1 object streams)"), "{summary}"); + assert!(summary.contains("1000 object stream warnings"), "{summary}"); + assert!(summary.contains("993 additional messages suppressed"), "{summary}"); +} + +/// Preserve small diagnostic batches and retain valid members despite duplicate offsets. +#[test] +fn small_stream_diagnostics_keep_their_text_level_and_objects() { + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + for count in [1, 8] { + start_capture(); + let doc = Document::load_mem(&pdf_with_objects(vec![member_stream(count, "outside")])).unwrap(); + assert_eq!(doc.objects.len(), 1, "the object-stream container is retained"); + let messages = records(); + assert_eq!(messages.len(), count); + assert!(messages.iter().all(|(level, text)| *level == Level::Warn && text == "out-of-bounds offset in object stream")); + start_capture(); + let objects = (0..count).map(|_| b"<< >>\nstream\nx\nendstream".to_vec()).collect(); + let doc = Document::load_mem(&pdf_with_objects(objects)).unwrap(); + assert_eq!(doc.objects.len(), count); + let messages = records(); + assert_eq!(messages.len(), count); + assert!(messages.iter().all(|(level, text)| *level == Level::Error && text.contains("missing the Length entry"))); + } + start_capture(); + let doc = Document::load_mem(&pdf_with_objects(vec![member_stream(1000, "duplicate")])).unwrap(); + assert_eq!(doc.get_object((10000, 0)).unwrap().as_i64().unwrap(), 42, "the first valid member survives duplicate offsets"); +} + +/// Bound standalone object-stream parsing, including its dictionary and member warnings. +#[test] +fn direct_object_stream_parsing_also_has_a_bounded_budget() { + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + start_capture(); + let index: String = (0..1000).map(|i| format!("{} 10000 ", i + 1)).collect(); + let mut dict = lopdf::Dictionary::new(); + dict.set("First", i64::try_from(index.len()).unwrap()); + dict.set("N", 999); // One dictionary warning and 1000 member warnings. + let stream = lopdf::Stream::new(dict, format!("{index}42").into_bytes()); + assert!(lopdf::ObjectStream::new(&stream).unwrap().objects.is_empty()); + let messages = records(); + assert_eq!(messages.len(), 9); + assert!(messages.last().unwrap().1.contains("1001 object stream warnings")); + assert!(messages.last().unwrap().1.contains("993 additional messages suppressed")); + assert!(messages.iter().all(|(level, _)| *level == Level::Warn)); +} + +/// Spending the last node preserves the first member and charges its warning to the same log. +#[test] +fn a_spent_node_budget_counts_toward_the_diagnostic_summary() { + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let mut index = String::from("1 0 2 3 "); + for id in 10..18 { + index.push_str(&format!("{id} 99 ")); + } + let mut dict = lopdf::Dictionary::new(); + dict.set("First", i64::try_from(index.len()).unwrap()); + dict.set("N", 10); + let stream = lopdf::Stream::new(dict, format!("{index}42 43").into_bytes()); + let budget = lopdf::NodeBudget::new(1); + start_capture(); + let parsed = lopdf::ObjectStream::new_within(&stream, None, &budget).unwrap(); + assert_eq!(parsed.objects.len(), 1); + assert_eq!(parsed.objects[&(1, 0)].as_i64().unwrap(), 42); + assert!(budget.spent()); + + let messages = records(); + assert_eq!(messages.len(), 9); + assert!(messages[..8].iter().all(|(level, text)| *level == Level::Warn && text == "out-of-bounds offset in object stream")); + let (level, summary) = &messages[8]; + assert_eq!(*level, Level::Warn); + assert!(summary.contains("9 object stream warnings") && summary.contains("1 additional messages suppressed"), "{summary}"); +} + +/// A valid compressed Length/Info pair in a stream whose N header is deliberately wrong. +/// Every content-stream lookup reparses that same container before eager collection completes. +fn compressed_lengths_fixture(count: usize) -> Vec { + let info = "<< /Title (Captured) >>"; + let index = format!("5 0 6 {} ", info.len() + 1); + let members = format!("{index}{info} 3"); + let mut objects = vec![ + (1usize, b"<< /Type /Catalog /Pages 2 0 R >>".to_vec()), + (2, b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec()), + (3, b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Resources << >> /Contents 7 0 R >>".to_vec()), + (4, format!("<< /Type /ObjStm /N 3 /First {} /Length {} >>\nstream\n{members}\nendstream", index.len(), members.len()).into_bytes()), + ]; + objects.extend((0..count).map(|i| (7 + i, b"<< /Length 6 0 R >>\nstream\nq Q\nendstream".to_vec()))); + let xref_id = 7 + count; + let mut offsets = vec![0u32; xref_id + 1]; + let mut pdf = b"%PDF-1.7\n".to_vec(); + for (id, object) in objects { + offsets[id] = u32::try_from(pdf.len()).unwrap(); + pdf.extend_from_slice(format!("{id} 0 obj\n").as_bytes()); + pdf.extend_from_slice(&object); + pdf.extend_from_slice(b"\nendobj\n"); + } + let xref = pdf.len(); + offsets[xref_id] = u32::try_from(xref).unwrap(); + let mut entries = Vec::new(); + for (id, offset) in offsets.into_iter().enumerate() { + let (kind, first, second): (u8, u32, u16) = match id { + 0 => (0, 0, 65535), + 5 => (2, 4, 0), + 6 => (2, 4, 1), + _ => (1, offset, 0), + }; + entries.push(kind); + entries.extend_from_slice(&first.to_be_bytes()); + entries.extend_from_slice(&second.to_be_bytes()); + } + pdf.extend_from_slice( + format!("{xref_id} 0 obj\n<< /Type /XRef /Size {} /Root 1 0 R /Info 5 0 R /W [1 4 2] /Length {} >>\nstream\n", xref_id + 1, entries.len()) + .as_bytes(), + ); + pdf.extend_from_slice(&entries); + pdf.extend_from_slice(format!("\nendstream\nendobj\nstartxref\n{xref}\n%%EOF\n").as_bytes()); + pdf +} + +/// Indirect compressed Length lookups share the eager budget, including strict reads. +#[test] +fn compressed_lengths_share_the_eager_load_budget() { + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + for strict in [false, true] { + for count in [1, 32] { + start_capture(); + let doc = Document::load_mem_with_options(&compressed_lengths_fixture(count), LoadOptions { strict, ..Default::default() }).unwrap(); + assert_eq!(doc.get_pages().len(), 1); + assert_eq!(doc.get_object((5, 0)).unwrap().as_dict().unwrap().get(b"Title").unwrap().as_str().unwrap(), b"Captured"); + for i in 0..count { + assert_eq!(doc.get_object((u32::try_from(7 + i).unwrap(), 0)).unwrap().as_stream().unwrap().content, b"q Q"); + } + let messages = records(); + let total = count + 1; // One header warning per lookup plus the eager container read. + assert_eq!(messages.len(), if total <= 8 { total } else { 9 }, "strict={strict}, count={count}: {messages:?}"); + assert!(messages.iter().all(|(level, _)| *level == Level::Warn)); + if total > 8 { + let summary = &messages.last().unwrap().1; + assert!(summary.starts_with("Object loading:"), "{summary}"); + assert!(summary.contains(&format!("{total} object stream warnings")), "{summary}"); + assert!(summary.contains(&format!("{} additional messages suppressed", total - 8)), "{summary}"); + } + } + } +} + +/// Lightweight metadata keeps compressed fields without creating standalone log batches. +#[test] +fn compressed_lengths_metadata_does_not_start_diagnostic_batches() { + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + start_capture(); + let metadata = Document::load_metadata_mem(&compressed_lengths_fixture(1)).unwrap(); + assert_eq!(metadata.title.as_deref(), Some("Captured")); + assert_eq!(metadata.page_count, 1); + assert!(records().is_empty(), "metadata lookups have no eager-load logging context: {:?}", records()); +} + +/// An encrypted fixture retains real compressed references in an incremental xref stream. +/// The writer omits existing containers, so retain them and add compressed references explicitly. +fn encrypted_container_fixture(count: usize) -> Vec { + encrypted_stream_fixture(count, false) +} + +/// Build encrypted compressed references, optionally replacing containers with malformed streams. +fn encrypted_stream_fixture(count: usize, broken: bool) -> Vec { + let mut doc = Document::load_mem(&fixture(0, 0)).unwrap(); + doc.trailer.set("ID", lopdf::Object::Array(vec![lopdf::Object::string_literal("BBBBBBBBBBBBBBBB"); 2])); + let mut containers = Vec::new(); + for i in 0..count { + let member = 10000 + u32::try_from(i).unwrap(); + let index = format!("{member} 0 "); + let mut dict = lopdf::Dictionary::new(); + // The writer omits existing ObjStm containers. Restore this same-length name after + // serialization; names are not encrypted and object offsets remain unchanged. + dict.set("Type", "ObjStx"); + dict.set("N", if broken { 1 } else { 2 }); // Otherwise one valid member with a wrong count. + dict.set("First", if broken { 99 } else { i64::try_from(index.len()).unwrap() }); + let container = doc.add_object(lopdf::Stream::new(dict, format!("{index}42").into_bytes())); + containers.push(container.0); + } + let version = lopdf::EncryptionVersion::V2 { + document: &doc, + owner_password: "owner", + user_password: "user", + key_length: 128, + permissions: lopdf::Permissions::all(), + }; + doc.encrypt(&lopdf::EncryptionState::try_from(version).unwrap()).unwrap(); + let encrypt = doc.trailer.get(b"Encrypt").unwrap().as_reference().unwrap(); + let mut pdf = Vec::new(); + doc.save_to(&mut pdf).unwrap(); + let mut restored = 0; + for i in 0..=pdf.len() - 6 { + if &pdf[i..i + 6] == b"ObjStx" { + pdf[i + 5] = b'm'; + restored += 1; + } + } + assert_eq!(restored, count); + let marker = b"startxref\n"; + let start = pdf.windows(marker.len()).rposition(|w| w == marker).unwrap() + marker.len(); + let prev: usize = std::str::from_utf8(&pdf[start..]).unwrap().lines().next().unwrap().parse().unwrap(); + let xref = pdf.len(); + let xref_id = 10000 + count; + let mut entries = Vec::new(); + for container in containers { + entries.push(2); + entries.extend_from_slice(&container.to_be_bytes()); + entries.extend_from_slice(&0u16.to_be_bytes()); + } + entries.push(1); + entries.extend_from_slice(&u32::try_from(xref).unwrap().to_be_bytes()); + entries.extend_from_slice(&0u16.to_be_bytes()); + let id = "42".repeat(16); + pdf.extend_from_slice(format!("\n{xref_id} 0 obj\n<< /Type /XRef /Size {} /Root 1 0 R /Encrypt {} {} R /ID [<{id}> <{id}>] /Prev {prev} /Index [10000 {}] /W [1 4 2] /Length {} >>\nstream\n", xref_id + 1, encrypt.0, encrypt.1, count + 1, entries.len()).as_bytes()); + pdf.extend_from_slice(&entries); + pdf.extend_from_slice(format!("\nendstream\nendobj\nstartxref\n{xref}\n%%EOF\n").as_bytes()); + pdf +} + +/// All encrypted containers share one budget, retaining their decrypted members and page. +#[test] +fn encrypted_object_streams_share_the_load_budget() { + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + for strict in [false, true] { + for count in [1, 32] { + let pdf = encrypted_container_fixture(count); + start_capture(); + let doc = Document::load_mem_with_options(&pdf, LoadOptions { strict, ..LoadOptions::with_password("user") }).unwrap(); + assert_eq!(doc.get_pages().len(), 1); + for i in 0..count { + let member = 10000 + u32::try_from(i).unwrap(); + let value = doc.get_object((member, 0)); + assert!( + value.is_ok(), + "missing member {member}: xref={:?}, container={:?}, logs={:?}", + doc.reference_table.get(member), + doc.get_object((6 + u32::try_from(i).unwrap(), 0)), + records() + ); + assert_eq!(value.unwrap().as_i64().unwrap(), 42); + } + let messages = records(); + assert_eq!(messages.len(), if count <= 8 { count } else { 9 }, "strict={strict}, count={count}: {messages:?}"); + assert!(messages.iter().all(|(level, _)| *level == Level::Warn)); + if count > 8 { + let summary = &messages.last().unwrap().1; + assert!(summary.starts_with("Object loading:"), "{summary}"); + assert!(summary.contains(&format!("{count} object stream warnings")), "{summary}"); + assert!(summary.contains(&format!("{} additional messages suppressed", count - 8)), "{summary}"); + } + } + } +} + +/// Count malformed encrypted containers without changing the diagnostic limit. +#[test] +fn encrypted_container_errors_are_counted_and_bounded() { + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + for strict in [false, true] { + for count in [1, 32] { + let pdf = encrypted_stream_fixture(count, true); + start_capture(); + let doc = Document::load_mem_with_options(&pdf, LoadOptions { strict, ..LoadOptions::with_password("user") }).unwrap(); + assert_eq!(doc.get_pages().len(), 1); + assert!(doc.get_object((10000, 0)).is_err(), "the bad container was not parsed"); + let messages = records(); + if count > 8 { + assert_bounded(&messages, count, count); + } else { + assert_eq!(messages.len(), count, "failed encrypted containers must be recorded: {messages:?}"); + assert!(messages.iter().all(|(level, text)| *level == Level::Error && text.starts_with("Object stream load error"))); + } + } + } +} + +/// Build cyclic or excessive indirect-Length chains that emit lookup warnings. +fn lookup_warning_fixture(count: usize, cycle: bool) -> Vec { + let mut objects = vec![ + b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(), + b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 4 0 R >>".to_vec(), + b"<< /Length 3 >>\nstream\nq Q\nendstream".to_vec(), + b"42".to_vec(), + ]; + let chain = if cycle { 1 } else { 18 }; + for i in 0..chain { + let length = if cycle { + "6 0 R".to_string() + } else if i + 1 == chain { + "1".to_string() + } else { + format!("{} 0 R", 7 + i) + }; + objects.push(format!("<< /Length {length} >>\nstream\nx\nendstream").into_bytes()); + } + objects.extend((0..count).map(|_| b"<< /Length 6 0 R >>\nstream\nx\nendstream".to_vec())); + String::from_utf8(pdf_with_objects(objects)).unwrap().replace("/Root 1 0 R", "/Root 1 0 R /Info 6 0 R").into_bytes() +} + +/// Charge cyclic and excessive-depth lookup warnings to the enclosing read budget. +#[test] +fn lookup_warnings_share_the_load_budget() { + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + for cycle in [false, true] { + for strict in [false, true] { + for count in [1, 32] { + let pdf = lookup_warning_fixture(count, cycle); + start_capture(); + let doc = Document::load_mem_with_options(&pdf, LoadOptions { strict, ..Default::default() }).unwrap(); + assert_eq!(doc.get_pages().len(), 1); + assert_eq!(doc.get_object((5, 0)).unwrap().as_i64().unwrap(), 42); + let messages = records(); + let warnings = count + 1; + let lengths = count + if cycle { 1 } else { 17 }; + let total = warnings + lengths; + assert_eq!(messages.len(), if total <= 8 { total } else { 9 }, "cycle={cycle}, strict={strict}, count={count}: {messages:?}"); + if total > 8 { + let (level, summary) = messages.last().unwrap(); + assert_eq!(*level, Level::Error); + assert!(summary.contains("0 failed objects (0 object streams)"), "{summary}"); + assert!(summary.contains(&format!("{warnings} object stream warnings")), "{summary}"); + assert!(summary.contains(&format!("{lengths} stream length errors")), "{summary}"); + assert!(summary.contains(&format!("{} additional messages suppressed", total - 8)), "{summary}"); + } + } + } + } +} + +/// Read lightweight metadata without starting object-load diagnostic batches. +#[test] +fn metadata_lookup_warnings_stay_silent() { + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + for cycle in [false, true] { + let pdf = lookup_warning_fixture(0, cycle); + start_capture(); + let info = Document::load_metadata_mem(&pdf).unwrap(); + assert_eq!(info.page_count, 1); + assert!(records().is_empty(), "metadata lookup diagnostics escaped the silent context: {:?}", records()); + } +} diff --git a/docs/roadmap.md b/docs/roadmap.md index c63c4d46a6..359ee45f48 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -256,7 +256,7 @@ total matches the parity estimate. |---|---|---|---|---|---| | M0 | Skeleton: workspace, xtask gates, CI | 15–30 | 98% | 1–2 | GitHub workflow, `deny.toml` (licence audit of every dependency), parity checklist (826 features, `xtask parity`) done. Missing: remaining crate stubs, testkit/oracle crates | | M1 | COS: filters, crypt, parser, xref, writer | 120–200 | 80% | 20–40 | Done:
- filters and crypt: every standard-security revision R2–R6 (RC4, AES-128/256), SASLprep, permissions, creating encryption;
- cos: parse and repair (including invalid xref object-number ranges), decoded-stream limits including unfiltered data, decrypt on load, re-encrypt on save, incremental and full writing.
Corpus: open/edit/save passes on 958 files, and all 7 password-protected files open.
Full saves now pack objects into compressed object streams. An unchanged incremental save of a classic table writes a zero-length cross-reference subsection instead of a section with no subsections (#1339). A full rewrite keeps unknown trailer entries, including objects reachable only from them (#1338). Fuzzing runs nightly (`xtask fuzz`). Raw-deflate fallback preserves decoding-limit errors, including through tolerant COS stream decoding. Refreshed against upstream `99941daa` (2026-10-15). COS reference lookups and full saves distinguish complete object references, so stale generations cannot expose replacement content. Snapshot restoration preserves edited nonzero-generation objects through incremental save/reopen. Synthetic regressions cover caches, overlays, snapshots, stream lengths and classic/packed saves. For damaged live rows, either the xref generation or a same-number header at its indexed offset may identify the object; neither-match and free slots remain null. Header probes read at most 128 bytes per candidate offset, and opening records at most 256 object disagreements plus a summary without expanding compact xref rows. Synthetic dictionary-edit and independent save/reopen controls cover this repair policy. Repair-aware preflight edits and restored snapshots retain both accepted aliases, with full rewrite for repaired edits; classic/packed output coalesces them to one object identity. Materialized diagnostics inspect retained primary/hybrid rows before folding, with the same cap. Done since: #2658: macOS atomic saves retain destination extended attributes, including Finder tags, and reject partial resource-fork reads after size changes. Metadata failures retain the original PDF and unsaved edit. Missing: ≥ 250 tests, own image codecs | -| M2 | Model, render, text | 200–350 | 15% | 130–230 | hayro bootstrap renderer (vendored patches); inspector predictor scratch is bounded by available input, and JPX sample rescaling handles 1–32 bits safely. Text extraction reaches word-F1 0.98 against pdftotext. Short same-line redraws split before placement rather than interleaving. Missing: model crate, fonts, DisplayList, renderer independent of hayro. Inspector page-label traversal and output are resource-bounded, with physical-number fallback warnings. Packed TIFF-predictor RGB rows retain later rows in decoding and rendering. Page marks, added content and print output retain small page-unit transform coefficients when serialized. Forms without Resources use page Properties for ActualText and layer visibility; own dictionaries stop fallback. Oversized missing inline-image samples, including header and terminator overhead, no longer pin the content window (#3107 / PR #3438); normal large streamed images retain deterministic sample boundaries. Radial luminosity fades have synthetic coverage for the existing #2132 mask guard, including per-pixel references, antialiased clips, previews, scales and tiles; no additional production fix was needed. Dotted TOC leaders no longer inflate letter tracking or hide word spaces (#3086); phrase search and selection are covered. Short tracked ellipses retain their gap samples and remain searchable. Missing spacing glyphs in non-embedded Japanese CID substitutes render blank without changing PDF advances or Unicode (#3601). The desktop viewer can use installed CJK fonts, including Windows GBK Song/Hei/Kai/FangSong and subset-prefixed Founder names; Combine thumbnails and accessibility figure previews use the same display-only fallback, without changing export or print font policy (#234, continuation of #1567, review #4172). Print previews exclude installed faces and isolate their font cache; GBK regressions cover view/print switching for inline and pooled whole-page/tile rendering. Installed-font helpers and their regression contracts have function documentation. GBK regression rasters match explicit-Unicode references with independently selected installed faces; wrong-glyph and wrong-family negative controls fail. Integration with main fa5f9f8c retains viewer fallback across the split engine session modules, renderer tests and Combine thumbnail workers. | +| M2 | Model, render, text | 200–350 | 15% | 130–230 | hayro bootstrap renderer (vendored patches); inspector predictor scratch is bounded by available input, and JPX sample rescaling handles 1–32 bits safely. Text extraction reaches word-F1 0.98 against pdftotext. Short same-line redraws split before placement rather than interleaving. Missing: model crate, fonts, DisplayList, renderer independent of hayro. Inspector page-label traversal and output are resource-bounded, with physical-number fallback warnings. Packed TIFF-predictor RGB rows retain later rows in decoding and rendering. Page marks, added content and print output retain small page-unit transform coefficients when serialized. Forms without Resources use page Properties for ActualText and layer visibility; own dictionaries stop fallback. Oversized missing inline-image samples, including header and terminator overhead, no longer pin the content window (#3107 / PR #3438); normal large streamed images retain deterministic sample boundaries. Radial luminosity fades have synthetic coverage for the existing #2132 mask guard, including per-pixel references, antialiased clips, previews, scales and tiles; no additional production fix was needed. Dotted TOC leaders no longer inflate letter tracking or hide word spaces (#3086); phrase search and selection are covered. Short tracked ellipses retain their gap samples and remain searchable. Missing spacing glyphs in non-embedded Japanese CID substitutes render blank without changing PDF advances or Unicode (#3601). The desktop viewer can use installed CJK fonts, including Windows GBK Song/Hei/Kai/FangSong and subset-prefixed Founder names; Combine thumbnails and accessibility figure previews use the same display-only fallback, without changing export or print font policy (#234, continuation of #1567, review #4172). Print previews exclude installed faces and isolate their font cache; GBK regressions cover view/print switching for inline and pooled whole-page/tile rendering. Installed-font helpers and their regression contracts have function documentation. GBK regression rasters match explicit-Unicode references with independently selected installed faces; wrong-glyph and wrong-family negative controls fail. Integration with main fa5f9f8c retains viewer fallback across the split engine session modules, renderer tests and Combine thumbnail workers. Candidate #2670: Malformed-object diagnostics share a bounded per-load budget across compressed objects and encrypted containers, with a strict-mode summary and silent metadata reads. | | M2 | Model, render, text | 200–350 | 15% | 130–230 | hayro bootstrap renderer (vendored patches); inspector predictor scratch is bounded by available input, and JPX sample rescaling handles 1–32 bits safely. Text extraction reaches word-F1 0.98 against pdftotext. Short same-line redraws split before placement rather than interleaving. Missing: model crate, fonts, DisplayList, renderer independent of hayro. Inspector page-label traversal and output are resource-bounded, with physical-number fallback warnings. Packed TIFF-predictor RGB rows retain later rows in decoding and rendering. The renderer keeps its one-point crop-size floor in physical points after UserUnit scaling, with regression coverage for crop origins, rotations and f32 reciprocal rounding. Existing unit policy and nearly-zero fallback are retained. | | M2 | Model, render, text | 200–350 | 15% | 130–230 | hayro bootstrap renderer (vendored patches); inspector predictor scratch is bounded by available input, and JPX sample rescaling handles 1–32 bits safely. Text extraction reaches word-F1 0.98 against pdftotext. Short same-line redraws split before placement rather than interleaving. Missing: model crate, fonts, DisplayList, renderer independent of hayro. Inspector page-label traversal and output are resource-bounded, with physical-number fallback warnings | | M3 | Viewer app (native + web) | 80–150 | 90% | 10–20 | Acrobat-style shell, find, select, panels, tiles, web build, UI control channel for agents (opt-in). #3808: the Pages inspector offers a 50–150% thumbnail slider and buttons, also available through `ui.set`. Missing: 60 fps test on a 500-page document, snapshot tests of every panel
Done since: fit visible, document title in the window; Linux middle-button scrolling; shared three-state theme preferences in the toolbar, View menu and control channel; numeric Linux portal events and idle wakeups completing #881, with native appearance inheritance retained (#446); late browser startup downloads preserve the current document and Save target (#171). Selected-text Copy in Edit and the canvas context menu is covered by focused regressions and native clipboard checks (#1225); document copy restrictions apply to the floating action too. #1364 candidate: absolute local GoToR links ask before target access; headless callers explicitly opt in. Native-opening candidate: chosen tools survive preparation and password retries; startup intake waits for pending preparation. Page-label navigation displays logical labels, retains the current page on unchanged submission and refreshes focused same-document replacements; clean file-watcher reload preserves the chosen scrolling mode, preventing a Single Page reader from jumping to page 1 during replacement. Synthetic control regressions cover these behaviors. #3149: page-list changes discard render demand based on old geometry; actual raster dimensions are checked against the GPU limit before upload. Synthetic crash and continued-rendering regressions cover the replacement path. Save-prompt shortcuts yield to dialogs above them; stacked link-consent UI regression covers Escape and Return. Comment hover follows individual marked lines and original annotation paint order (#3541/#3620), independently of spatial inspection sorting; synthetic rotation, differing-upper-edge overlap and unchanged-document regressions. Optional page gaps join page edges without cropping PDF margins; current-document toggle, persisted default and UI control options are covered by viewer tests. Gap changes in Organize Pages preserve document scroll position, and both comparison panes follow menu and control choices. Repeated window resizes by an edge and moves by the tab strip on GNOME/Wayland work without a click in between. Optional --two-paged applies noncontinuous two-page layout to explicitly opened CLI files without changing defaults; explicit --layout wins. Crop pages is directly available in the quick toolbar (#5330). Native Recent rows also offer Reveal in Finder / File Explorer (#5452). Opened from a launcher with startup notification (the Linux desktop entry), the first window hands the launcher's activation token back, so GNOME's busy cursor clears when the window appears instead of after 15 seconds. | @@ -392,6 +392,7 @@ Estimates unchanged. | 2026-11-07 | patch | M10 `ocr.ocr-web` ported onto #977's engines and preprocessing: the page prepares each page, a Web Worker runs ocrs, the downloaded models join the engine cache. Estimates unchanged. | | 2026-11-05 | patch | M7 #2964 / #3185: grouped text and Thai source-font preservation; limitations and estimates unchanged. | | 2026-10-25 | minor | M7, #2750: Single-style Keep source fonts edits retain source glyphs and batch only missing glyphs in fallback fonts. Per-rewrite character eligibility and widths are cached; source and fallback edge spaces stay extractable. Estimates unchanged. | +| 2026-10-25 | minor | M2, #2670: Malformed-object diagnostics share a bounded per-load budget across compressed objects and encrypted containers, with a strict-mode summary and silent metadata reads. Estimates unchanged. | | 2026-11-03 | minor | M11: Optimize's JBIG2 images share a symbol dictionary (`/JBIG2Globals`), up to 16 at a time and when smaller (`pdfcraft_filters::encode_jbig2_shared`): 41–46% smaller on rendered text in proportional fonts, 10% in Courier | | 2026-11-03 | patch | M5 #5850 review: indirect typewriter intent and composer edits preserve outer whitespace; movement regression commits by outside click; estimates unchanged. | | 2026-11-03 | patch | M5 #5850: Enter adds Fill & Sign line breaks; outside clicks commit, Escape cancels, and saved multiline appearances retain their text and height; estimates unchanged. | diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 2133376b91..ee8b6700d7 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -57,8 +57,8 @@ milestone = "M1" status = "shipped" commands = ["file.open"] tools = ["doc_open"] -evidence = ["craft-pdf::cos/document/tests.rs::damaged_xref_is_reconstructed", "craft-pdf::cos/parser.rs::indirect_stream_with_wrong_length_recovers", "craft-pdf::cos/document/tests.rs::self_referential_length_does_not_overflow", "crates/engine/src/tests.rs::a_repaired_file_is_rewritten_by_save_even_without_edits", "crates/automation/tests/it/automation.rs::saving_a_repaired_file_puts_the_repair_on_disk", "crates/engine/src/tests.rs::a_signed_repaired_file_keeps_its_bytes_when_saved_without_edits", "craft-pdf::cos/document/tests.rs::a_table_numbered_from_1_that_begins_with_object_0_is_read_from_0", "crates/render/src/raster/tests.rs::an_update_cut_off_before_its_trailer_shows_its_pages_as_the_model_reads_them", "craft-pdf::cos/document/tests.rs::an_update_without_prev_is_rebuilt_with_its_page_tree_and_a_repair_note", "crates/render/src/inspect/core.rs::an_update_without_prev_shows_the_page_tree_and_says_it_was_rebuilt", "craft-pdf::cos/document/tests.rs::a_hybrid_update_without_prev_is_rebuilt_too", "crates/render/src/inspect/core.rs::a_hybrid_update_without_prev_is_rebuilt_as_the_document_model_rebuilds_it"] -notes = "Save and doc_save write a reconstructed file in full even when nothing was edited, so the repair reaches the disk and the saved file opens without one (#1937); a signed one keeps its bytes, so its signatures stay valid. A repair does not mark the document as having unsaved changes, so closing it does not offer to save the repaired file. A classic table numbered 1 n that begins with object 0's free entry is read from 0 (#2676) and logged. A last update cut off before its trailer (objects after a last `startxref` more than 4 KiB from the end) is rebuilt from object headers by the renderer as by the document model, so both show its latest objects. A file whose last update has no /Prev (ISO 32000-2 §7.5.6, §7.5.8.2), so that its page tree is cut off the chain, (a hybrid section's /XRefStm stream counts as part of the same update) is rebuilt from its object headers by the document model and the renderer alike, with a repair note and an open warning (the signed PDFBOX-2720 and PDFBOX-2942 files)." +evidence = ["craft-pdf::cos/document/tests.rs::damaged_xref_is_reconstructed", "craft-pdf::cos/parser.rs::indirect_stream_with_wrong_length_recovers", "craft-pdf::cos/document/tests.rs::self_referential_length_does_not_overflow", "crates/engine/src/tests.rs::a_repaired_file_is_rewritten_by_save_even_without_edits", "crates/automation/tests/it/automation.rs::saving_a_repaired_file_puts_the_repair_on_disk", "crates/engine/src/tests.rs::a_signed_repaired_file_keeps_its_bytes_when_saved_without_edits", "craft-pdf::cos/document/tests.rs::a_table_numbered_from_1_that_begins_with_object_0_is_read_from_0", "crates/render/src/raster/tests.rs::an_update_cut_off_before_its_trailer_shows_its_pages_as_the_model_reads_them", "craft-pdf::cos/document/tests.rs::an_update_without_prev_is_rebuilt_with_its_page_tree_and_a_repair_note", "crates/render/src/inspect/core.rs::an_update_without_prev_shows_the_page_tree_and_says_it_was_rebuilt", "craft-pdf::cos/document/tests.rs::a_hybrid_update_without_prev_is_rebuilt_too", "crates/render/src/inspect/core.rs::a_hybrid_update_without_prev_is_rebuilt_as_the_document_model_rebuilds_it", "crates/render/tests/object_load_logging.rs::encrypted_container_errors_are_counted_and_bounded", "crates/render/tests/object_load_logging.rs::lookup_warnings_share_the_load_budget", "crates/render/tests/object_load_logging.rs::metadata_lookup_warnings_stay_silent", "crates/render/tests/object_load_logging.rs::compressed_lengths_share_the_eager_load_budget", "crates/render/tests/object_load_logging.rs::encrypted_object_streams_share_the_load_budget", "crates/render/tests/object_load_logging.rs::compressed_lengths_metadata_does_not_start_diagnostic_batches", "crates/render/tests/object_load_logging.rs::compatibility_inspection_gets_a_fresh_budget_on_every_open", "crates/render/tests/object_load_logging.rs::malformed_objects_log_bounded_details_and_an_exact_summary", "crates/render/tests/object_load_logging.rs::ordinary_and_object_stream_failures_share_one_log_budget", "crates/render/tests/object_load_logging.rs::deferred_stream_length_errors_share_the_load_budget", "crates/render/tests/object_load_logging.rs::object_stream_member_warnings_are_bounded_across_all_streams", "crates/render/tests/object_load_logging.rs::strict_error_still_reports_the_suppressed_diagnostics", "crates/render/tests/object_load_logging.rs::concurrent_document_reads_have_independent_budgets"] +notes = "The eager lopdf compatibility reader shares eight details across object errors, deferred missing/broken Length errors, object-stream warnings and encrypted skips, then emits a category summary at the highest observed severity (#2670 item 11). Encrypted object-stream containers share one warning budget for the load; failed containers contribute to failure/stream totals. Lookup-depth and cycle warnings share that budget and respect metadata-only silence. Indirect compressed-Length lookups share the same budget; lightweight metadata lookups do not create diagnostic batches. The summary is also emitted before strict refusal; concurrent reads have independent budgets. Recovery, small-file diagnostics and other parser warnings are unchanged. Direct ObjectStream calls have their own budget; this is not a global log limit or a repair for every damaged file. Save and doc_save write a reconstructed file in full even when nothing was edited, so the repair reaches the disk and the saved file opens without one (#1937); a signed one keeps its bytes, so its signatures stay valid. A repair does not mark the document as having unsaved changes, so closing it does not offer to save the repaired file. A classic table numbered 1 n that begins with object 0's free entry is read from 0 (#2676) and logged. A last update cut off before its trailer (objects after a last `startxref` more than 4 KiB from the end) is rebuilt from object headers by the renderer as by the document model, so both show its latest objects. A file whose last update has no /Prev (ISO 32000-2 §7.5.6, §7.5.8.2), so that its page tree is cut off the chain, (a hybrid section's /XRefStm stream counts as part of the same update) is rebuilt from its object headers by the document model and the renderer alike, with a repair note and an open warning (the signed PDFBOX-2720 and PDFBOX-2942 files)." [[feature]] id = "core.malformed-input-safety" diff --git a/vendor/README.md b/vendor/README.md index 71feee4fb7..f215452954 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -52,6 +52,27 @@ licence files unchanged. Every patch is marked `PdfCraft patch:` in the source, PdfCraft test, and should be proposed upstream. Remove the vendored copy once upstream releases the fix. Vendoring copyleft code is never allowed (plan/adr/0001). +Reader diagnostics (#2670, item 11): `lopdf::Reader::load_objects_raw` shares one +budget across eager object errors, encrypted skips, object-stream dictionary/member +warnings and deferred missing/broken `/Length` lookups. It logs at most eight details, +then one summary with category totals and the suppressed-message count. The summary +uses ERROR if an object/Length error occurred, otherwise WARN; each detail retains +its original level. It is emitted after deferred lookups, or before a strict error +returns. Counters saturate, recovery and small-file diagnostics are unchanged, and +concurrent reads have independent budgets. Direct `ObjectStream` parsing gets a fresh +budget per call. Indirect `/Length` lookups retain the eager load's budget while +reading compressed containers; lightweight metadata lookups use a silent context +instead of starting independent batches. Other parser diagnostics (including +stream-boundary recovery and reference-cycle warnings) are outside this scope. The encrypted +loader also shares one warning budget across every decrypted object-stream container. +Encrypted-container parse failures contribute to the shared failure/stream totals. +Lookup-depth and reference-cycle warnings use that same budget and stay silent +when only lightweight metadata is requested. + +Covered by the tests in `crates/render/tests/object_load_logging.rs`, including all +`lopdf::*` targets, the summary before a strict container error, and the shared +diagnostics for exhausted node budgets, plus the reader's `encrypted_load_logging` +unit test for the normally unused eager encrypted-skip branch. The TrueType name lookup patch probes Unicode `(0, *)` and Windows `(3, 10)` cmap records, recognizes post-name aliases, and retains known descriptor flags when unknown bits are present. `crates/render/tests/truetype_cmap.rs` covers these synthetic cases and verifies that Symbolic diff --git a/vendor/lopdf/src/object_stream.rs b/vendor/lopdf/src/object_stream.rs index e60a9f5e09..8b0e098e4d 100644 --- a/vendor/lopdf/src/object_stream.rs +++ b/vendor/lopdf/src/object_stream.rs @@ -1,4 +1,5 @@ use crate::parser; +use crate::reader::ObjectLoadLog; use crate::{Document, Error, Object, ObjectId, Result, Stream}; use std::cell::Cell; use std::collections::BTreeMap; @@ -132,7 +133,10 @@ impl ObjectStream { pub fn new_within( stream: &Stream, max_decompressed_size: Option, budget: &NodeBudget, ) -> Result { - Self::new_members_within(stream, max_decompressed_size, budget, |_| true) + let load_log = ObjectLoadLog::default(); + let parsed = Self::new_members_within(stream, max_decompressed_size, budget, &load_log, |_| true); + load_log.finish(); + parsed } /// PdfCraft patch: [`ObjectStream::new_within`], parsing only the members whose object @@ -140,7 +144,7 @@ impl ObjectStream { /// a loader passes the members it would add (not placed in another stream by the /// cross-reference table, and not already loaded), and a lookup the one member it wants. pub(crate) fn new_members_within( - stream: &Stream, max_decompressed_size: Option, budget: &NodeBudget, keep: impl Fn(u32) -> bool, + stream: &Stream, max_decompressed_size: Option, budget: &NodeBudget, load_log: &ObjectLoadLog, keep: impl Fn(u32) -> bool, ) -> Result { let content = match max_decompressed_size { // Object streams are decoded while the document is loaded, so @@ -175,10 +179,10 @@ impl ObjectStream { let len = numbers.len() / 2 * 2; // Ensure only pairs. let n = stream.dict.get(b"N").and_then(Object::as_i64)?; - if numbers.len().try_into().ok() != n.checked_mul(2) { + if numbers.len().try_into().ok() != n.checked_mul(2) && load_log.warning() { warn!("object stream: the object stream dictionary specifies a wrong number of objects") } - if usize::try_from(n).is_ok_and(|n| n > MAX_OBJECT_STREAM_MEMBERS) { + if usize::try_from(n).is_ok_and(|n| n > MAX_OBJECT_STREAM_MEMBERS) && load_log.warning() { warn!("object stream: /N {n} exceeds {MAX_OBJECT_STREAM_MEMBERS}; later members are ignored") } @@ -207,14 +211,18 @@ impl ObjectStream { let offset = first_offset.saturating_add(offset as usize); if offset >= content.len() { - warn!("out-of-bounds offset in object stream"); + if load_log.warning() { + warn!("out-of-bounds offset in object stream"); + } continue; } let Some(&(first_index, extent_end)) = extents.get(&offset) else { continue; }; if index != first_index { - warn!("duplicate offset in object stream"); + if load_log.warning() { + warn!("duplicate offset in object stream"); + } continue; } if !keep(id) { @@ -226,7 +234,9 @@ impl ObjectStream { start += 1; } if start >= extent_end { - warn!("only whitespace after offset in object stream"); + if load_log.warning() { + warn!("only whitespace after offset in object stream"); + } continue; } members.push((id, start, extent_end)); @@ -249,7 +259,7 @@ impl ObjectStream { .get(start..end) .and_then(|bytes| parser::direct_object_within(bytes, &nodes)); from.refund(nodes.get()); - if object.is_none() && nodes.get() == 0 { + if object.is_none() && nodes.get() == 0 && load_log.warning() { warn!("object stream: member {id} exceeds the object budget and was skipped"); } Some(((id, 0), object?)) @@ -279,7 +289,7 @@ impl ObjectStream { .filter_map(|member| parse_member(budget, member)) .collect() }; - if skipped.load(Ordering::Relaxed) { + if skipped.load(Ordering::Relaxed) && load_log.warning() { warn!("object stream: the object budget is spent; remaining members were skipped"); } diff --git a/vendor/lopdf/src/parser/mod.rs b/vendor/lopdf/src/parser/mod.rs index 2cc191419b..b084062f11 100644 --- a/vendor/lopdf/src/parser/mod.rs +++ b/vendor/lopdf/src/parser/mod.rs @@ -404,15 +404,18 @@ fn recover_stream_length(input: ParserInput) -> Option<(ParserInput, ParserInput recovered } +/// Parse a stream and resolve indirect lengths using the enclosing read's diagnostic budget. fn stream<'a>( input: ParserInput<'a>, reader: &Reader, already_seen: &mut HashSet, recover_length: bool, - recovery_bound: Option, + recovery_bound: Option, load_log: &crate::reader::ObjectLoadLog, ) -> NomResult<'a, Object> { let (i, dict) = terminated(dictionary, (space, tag(&b"stream"[..]), space0, eol)).parse(input)?; if let Ok(length) = dict.get(b"Length").and_then(|value| { if let Ok(id) = value.as_reference() { - reader.get_object(id, already_seen).and_then(|value| value.as_i64()) + reader + .get_object_with_log(id, already_seen, load_log) + .and_then(|value| value.as_i64()) } else { value.as_i64() } @@ -519,12 +522,12 @@ pub(crate) fn direct_object_within(input: ParserInput, nodes: &Cell) -> O /// An indirect object's body (a stream or a direct object), from a node budget of its own. fn object<'a>( input: ParserInput<'a>, reader: &Reader, already_seen: &mut HashSet, recover_stream_length: bool, - recovery_bound: Option, + recovery_bound: Option, load_log: &crate::reader::ObjectLoadLog, ) -> NomResult<'a, Object> { let nodes = Cell::new(MAX_NESTED_NODES); terminated( alt(( - |input| stream(input, reader, already_seen, recover_stream_length, recovery_bound), + |input| stream(input, reader, already_seen, recover_stream_length, recovery_bound, load_log), _direct_objects(crate::reader::MAX_NESTING_DEPTH, &nodes), )), space, @@ -532,9 +535,26 @@ fn object<'a>( .parse(input) } +/// Parse an indirect object with its recovery bound and silent lookup diagnostics. pub fn indirect_object( input: ParserInput, offset: usize, expected_id: Option, reader: &Reader, already_seen: &mut HashSet, recovery_bound: Option, +) -> crate::Result<(ObjectId, Object)> { + indirect_object_with_log( + input, + offset, + expected_id, + reader, + already_seen, + recovery_bound, + &crate::reader::ObjectLoadLog::silent(), + ) +} + +/// PdfCraft patch: eager reads retain their budget while resolving an indirect stream Length. +pub(crate) fn indirect_object_with_log( + input: ParserInput, offset: usize, expected_id: Option, reader: &Reader, + already_seen: &mut HashSet, recovery_bound: Option, load_log: &crate::reader::ObjectLoadLog, ) -> crate::Result<(ObjectId, Object)> { // Every downstream slice is a suffix of `input`, so express the absolute // end offset as the maximum length a suffix may have. @@ -545,8 +565,8 @@ pub fn indirect_object( expected_id, reader, already_seen, - true, - recovery_bound, + (true, recovery_bound), + load_log, )?; offset_stream(&mut object, offset); @@ -554,9 +574,10 @@ pub fn indirect_object( Ok((id, object)) } +/// Parse an indirect-object body and forward the read budget into nested stream parsing. fn _indirect_object<'a>( input: ParserInput<'a>, offset: usize, expected_id: Option, reader: &Reader, - already_seen: &mut HashSet, recover_stream_length: bool, recovery_bound: Option, + already_seen: &mut HashSet, recovery: (bool, Option), load_log: &crate::reader::ObjectLoadLog, ) -> crate::Result<(ObjectId, Object)> { let (i, (_, object_id)) = terminated((space, object_id), pair(tag(&b"obj"[..]), space)) .parse(input) @@ -569,7 +590,7 @@ fn _indirect_object<'a>( let object_offset = input.len() - i.len(); let (_, mut object) = terminated( - |i: ParserInput<'a>| object(i, reader, already_seen, recover_stream_length, recovery_bound), + |i: ParserInput<'a>| object(i, reader, already_seen, recovery.0, recovery.1, load_log), (space, opt(tag(&b"endobj"[..])), space), ) .parse(i) @@ -681,6 +702,7 @@ fn trailer(input: ParserInput) -> NomResult { delimited(pair(tag(&b"trailer"[..]), space), dictionary, space).parse(input) } +/// Parse a cross-reference table or stream without starting an object-load diagnostic batch. pub fn xref_and_trailer(input: ParserInput, reader: &Reader) -> crate::Result<(Xref, Dictionary)> { let xref_trailer = map(pair(|i| xref(i, reader.strict), trailer), |(mut xref, trailer)| { xref.size = trailer @@ -692,18 +714,26 @@ pub fn xref_and_trailer(input: ParserInput, reader: &Reader) -> crate::Result<(X alt(( xref_trailer, (|input| { - _indirect_object(input, 0, None, reader, &mut HashSet::new(), false, None) - .map(|(_, obj)| { - let res = match obj { - Object::Stream(stream) => decode_xref_stream_with_limit(stream, reader.max_decompressed_size), - _ => Err(crate::error::ParseError::InvalidXref.into()), - }; - (input, res) - }) - .map_err(|_| { - // artificial error kind is created to allow descriptive nom errors - nom::Err::Error(NomError::from_error_kind(input, ErrorKind::Fail)) - }) + _indirect_object( + input, + 0, + None, + reader, + &mut HashSet::new(), + (false, None), + &crate::reader::ObjectLoadLog::silent(), + ) + .map(|(_, obj)| { + let res = match obj { + Object::Stream(stream) => decode_xref_stream_with_limit(stream, reader.max_decompressed_size), + _ => Err(crate::error::ParseError::InvalidXref.into()), + }; + (input, res) + }) + .map_err(|_| { + // artificial error kind is created to allow descriptive nom errors + nom::Err::Error(NomError::from_error_kind(input, ErrorKind::Fail)) + }) }), )) .parse(input) diff --git a/vendor/lopdf/src/reader.rs b/vendor/lopdf/src/reader.rs index f4da53e3c1..f3871c8f84 100644 --- a/vendor/lopdf/src/reader.rs +++ b/vendor/lopdf/src/reader.rs @@ -8,6 +8,7 @@ use std::fs::File; use std::io::Read; use std::path::Path; use std::sync::{Mutex, PoisonError}; +use std::sync::atomic::{AtomicUsize, Ordering}; #[cfg(feature = "rayon")] use rayon::prelude::*; @@ -27,6 +28,98 @@ use crate::parser; use crate::xref::{Xref, XrefEntry, XrefType}; use crate::{Dictionary, Document, Error, IncrementalDocument, Object, ObjectId, Result}; +// PdfCraft patch (#2670, item 11): keep samples and exact diagnostic totals per +// eager load, shared by Rayon workers and the deferred stream-Length pass. +const MAX_OBJECT_LOAD_MESSAGES: usize = 8; + +#[derive(Default)] +pub(crate) struct ObjectLoadLog { + silent: bool, + messages: AtomicUsize, + failures: AtomicUsize, + streams: AtomicUsize, + lengths: AtomicUsize, + warnings: AtomicUsize, + encrypted: AtomicUsize, +} + +impl ObjectLoadLog { + /// Lookups outside an eager read must not start independent diagnostic batches. + pub(crate) fn silent() -> Self { + Self { + silent: true, + ..Self::default() + } + } + + /// Increment a diagnostic counter without wrapping at usize::MAX. + fn increment(counter: &AtomicUsize) -> usize { + // Member diagnostics can exceed the xref count. Saturate even if a + // hostile graph revisits a stream, rather than wrapping the budget. + counter + .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |n| Some(n.saturating_add(1))) + .unwrap_or_else(|n| n) + } + + /// Count a diagnostic unless silent, returning whether its detail fits the shared allowance. + fn message(&self, counter: &AtomicUsize) -> bool { + if self.silent { + return false; + } + Self::increment(counter); + Self::increment(&self.messages) < MAX_OBJECT_LOAD_MESSAGES + } + + /// Count an object-load failure and decide whether to emit its detail. + fn object(&self) -> bool { + self.message(&self.failures) + } + + /// Count a failed object-stream container as both a stream and an object failure. + fn stream(&self) -> bool { + Self::increment(&self.streams); + self.object() + } + + /// Count a stream-length error against the shared detail allowance. + fn length(&self) -> bool { + self.message(&self.lengths) + } + + /// Count an object-stream warning against the shared detail allowance. + pub(crate) fn warning(&self) -> bool { + self.message(&self.warnings) + } + + /// Count a skipped encrypted container against the shared detail allowance. + fn encrypted(&self) -> bool { + self.message(&self.encrypted) + } + + /// Emit one exact summary if details were suppressed, preserving error severity when needed. + pub(crate) fn finish(&self) { + let messages = self.messages.load(Ordering::Relaxed); + if messages <= MAX_OBJECT_LOAD_MESSAGES { + return; + } + let failures = self.failures.load(Ordering::Relaxed); + let lengths = self.lengths.load(Ordering::Relaxed); + let level = if failures > 0 || lengths > 0 { + log::Level::Error + } else { + log::Level::Warn + }; + log::log!( + level, + "Object loading: {failures} failed objects ({} object streams), {lengths} stream length errors, {} object stream warnings, {} encrypted skips; {} additional messages suppressed", + self.streams.load(Ordering::Relaxed), + self.warnings.load(Ordering::Relaxed), + self.encrypted.load(Ordering::Relaxed), + messages.saturating_sub(MAX_OBJECT_LOAD_MESSAGES), + ); + } +} + #[cfg(not(feature = "async"))] impl Document { /// Load a PDF document from a specified file path. @@ -908,6 +1001,8 @@ impl Reader<'_> { .push((obj_num, index)); } + // PdfCraft patch: encrypted containers share one budget for this document read. + let load_log = ObjectLoadLog::default(); for (container_id, objects_in_stream) in streams_to_process { if let Some(container_obj) = self.document.objects.get(&(container_id, 0)) && let Ok(stream) = container_obj.as_stream() @@ -916,7 +1011,7 @@ impl Reader<'_> { // the others spend nothing from the budget. let listed: BTreeSet = objects_in_stream.iter().map(|&(obj_num, _)| obj_num).collect(); let keep = |obj_num: u32| listed.contains(&obj_num); - match ObjectStream::new_members_within(stream, self.max_decompressed_size, &node_budget, keep) { + match ObjectStream::new_members_within(stream, self.max_decompressed_size, &node_budget, &load_log, keep) { Ok(object_stream) => { for (obj_num, _index) in objects_in_stream { let obj_id = (obj_num, 0); @@ -925,10 +1020,15 @@ impl Reader<'_> { } } } - Err(_e) => {} + Err(e) => { + if load_log.stream() { + error!("Object stream load error for container {container_id}: {e:?}"); + } + } } } } + load_log.finish(); let mut stored_state = state.clone(); // Record the /Encrypt dictionary's object id so that a later @@ -972,6 +1072,16 @@ impl Reader<'_> { /// Load every object in the cross-reference table, expanding object streams from one node /// budget shared by the whole load. fn load_objects_raw(&mut self, filter_func: Option) -> Result<()> { + let load_log = ObjectLoadLog::default(); + let result = self.load_objects_raw_with_log(filter_func, &load_log); + // The inner call joins its workers and completes deferred Length lookups. + // Report before propagating a strict error, as well as on success. + load_log.finish(); + result + } + + /// Load normal and compressed objects and deferred stream lengths through one diagnostic context. + fn load_objects_raw_with_log(&mut self, filter_func: Option, load_log: &ObjectLoadLog) -> Result<()> { let is_encrypted = self.document.trailer.get(b"Encrypt").is_ok(); let zero_length_streams = Mutex::new(vec![]); let object_stream_ids = Mutex::new(vec![]); @@ -1001,7 +1111,7 @@ impl Reader<'_> { let next_index = normal_offsets.partition_point(|&next| next <= offset); let next_object = normal_offsets.get(next_index).copied(); let end = self.object_end(offset, next_object); - let result = self.read_object_to(offset, end, None, &mut HashSet::new()); + let result = self.read_object_to(offset, end, None, &mut HashSet::new(), load_log); let (object_id, mut object) = match result { Ok(obj) => obj, Err(e) => { @@ -1009,11 +1119,15 @@ impl Reader<'_> { // Expected for some encrypted objects - but log which // ones. These failures stay non-fatal even in strict // mode because they do not indicate a malformed file. - warn!("Skipping encrypted object at offset {}: {:?}", offset, e); + if load_log.encrypted() { + warn!("Skipping encrypted object at offset {}: {:?}", offset, e); + } return Ok(None); } // Lenient loading logs and skips malformed objects; strict loading fails. - error!("Object load error at offset {}: {e:?}", offset); + if load_log.object() { + error!("Object load error at offset {}: {e:?}", offset); + } return if self.strict { Err(e) } else { Ok(None) }; } }; @@ -1030,7 +1144,7 @@ impl Reader<'_> { let mut object_stream_ids = object_stream_ids.lock().unwrap_or_else(PoisonError::into_inner); object_stream_ids.push(object_id); } else if stream.content.is_empty() { - let mut zero_length_streams = zero_length_streams.lock().unwrap(); + let mut zero_length_streams = zero_length_streams.lock().unwrap_or_else(|e| e.into_inner()); zero_length_streams.push(object_id); } } @@ -1042,27 +1156,25 @@ impl Reader<'_> { }; #[cfg(feature = "rayon")] - { - self.document.objects = self - .document - .reference_table - .entries - .par_iter() - .map(entries_filter_map) - .filter_map(Result::transpose) - .collect::>>()?; - } + let objects = self + .document + .reference_table + .entries + .par_iter() + .map(entries_filter_map) + .filter_map(Result::transpose) + .collect::>>(); #[cfg(not(feature = "rayon"))] - { - self.document.objects = self - .document - .reference_table - .entries - .iter() - .map(entries_filter_map) - .filter_map(Result::transpose) - .collect::>>()?; - } + let objects = self + .document + .reference_table + .entries + .iter() + .map(entries_filter_map) + .filter_map(Result::transpose) + .collect::>>(); + + self.document.objects = objects?; // PdfCraft patch: expand the object streams one at a time in object-number order, from one // node budget for the whole load, so many streams, each inside the decompression limit, @@ -1087,7 +1199,7 @@ impl Reader<'_> { }; let parsed = match loaded.get(&object_id).map(Object::as_stream) { Some(Ok(stream)) => { - ObjectStream::new_members_within(stream, self.max_decompressed_size, &node_budget, keep) + ObjectStream::new_members_within(stream, self.max_decompressed_size, &node_budget, load_log, keep) } _ => continue, }; @@ -1110,7 +1222,9 @@ impl Reader<'_> { // any other load error; a lenient load drops the stream, as it drops any object // that fails to load. Err(e) => { - error!("Object stream load error for {object_id:?}: {e:?}"); + if load_log.stream() { + error!("Object stream load error for {object_id:?}: {e:?}"); + } if self.strict { return Err(e); } @@ -1119,15 +1233,16 @@ impl Reader<'_> { } } - for object_id in zero_length_streams.into_inner().unwrap() { - let _ = self.read_stream_content(object_id); + for object_id in zero_length_streams.into_inner().unwrap_or_else(|e| e.into_inner()) { + let _ = self.read_stream_content(object_id, load_log); } Ok(()) } - fn read_stream_content(&mut self, object_id: ObjectId) -> Result<()> { - let length = self.get_stream_length(object_id)?; + /// Resolve a stream length and copy only a validated, in-bounds content range. + fn read_stream_content(&mut self, object_id: ObjectId, load_log: &ObjectLoadLog) -> Result<()> { + let length = self.get_stream_length(object_id, load_log)?; let stream = self .document .get_object_mut(object_id) @@ -1141,17 +1256,16 @@ impl Reader<'_> { } let length = usize::try_from(length).map_err(|e| Error::NumericCast(e.to_string()))?; - let end = start + length; - - if end > self.buffer.len() { - return Err(Error::InvalidStream("stream extends after document end.".to_string())); - } - - stream.set_content(self.buffer[start..end].to_vec()); + let content = start + .checked_add(length) + .and_then(|end| self.buffer.get(start..end)) + .ok_or_else(|| Error::InvalidStream("stream extends after document end.".to_string()))?; + stream.set_content(content.to_vec()); Ok(()) } - fn get_stream_length(&self, object_id: ObjectId) -> Result { + /// Resolve an integer-valued stream length, reporting lookup failures through the caller's budget. + fn get_stream_length(&self, object_id: ObjectId, load_log: &ObjectLoadLog) -> Result { let object = self.document.get_object(object_id)?; let stream = object.as_stream()?; stream @@ -1171,10 +1285,12 @@ impl Reader<'_> { }, }) .inspect_err(|_err| { - error!( - "stream dictionary of '{} {} R' is missing the Length entry", - object_id.0, object_id.1 - ); + if load_log.length() { + error!( + "stream dictionary of '{} {} R' is missing the Length entry", + object_id.0, object_id.1 + ); + } }) } @@ -1188,7 +1304,9 @@ impl Reader<'_> { } /// Load a compressed object from an object stream (for lightweight metadata extraction) - fn get_compressed_object(&self, id: ObjectId, already_seen: &mut HashSet) -> Result { + fn get_compressed_object( + &self, id: ObjectId, already_seen: &mut HashSet, load_log: &ObjectLoadLog, + ) -> Result { let entry = self.document.reference_table.get(id.0).ok_or(Error::MissingXrefEntry)?; let container_id = match entry { @@ -1207,27 +1325,42 @@ impl Reader<'_> { )); } let container_id = (container_id, 0); - let container_obj = self.get_object(container_id, already_seen)?; + let container_obj = self.get_object_with_log(container_id, already_seen, load_log)?; let container_stream = container_obj.as_stream()?; // PdfCraft patch: a lookup parses only the member it wants, from one object's budget // rather than a load's, so the members before it can't spend that budget first. let budget = NodeBudget::new(parser::MAX_OBJECT_NODES); let mut object_stream = - ObjectStream::new_members_within(container_stream, self.max_decompressed_size, &budget, |obj_num| { + ObjectStream::new_members_within(container_stream, self.max_decompressed_size, &budget, load_log, |obj_num| { obj_num == id.0 })?; object_stream.objects.remove(&id).ok_or(Error::MissingXrefEntry) } + /// Resolve an object quietly when no enclosing eager-read diagnostic batch exists. pub fn get_object(&self, id: ObjectId, already_seen: &mut HashSet) -> Result { + self.get_object_with_log(id, already_seen, &ObjectLoadLog::silent()) + } + + /// Retain one read's budget through nested container and indirect-Length lookups. + pub(crate) fn get_object_with_log( + &self, id: ObjectId, already_seen: &mut HashSet, load_log: &ObjectLoadLog, + ) -> Result { // PdfCraft patch: each top-level lookup starts with an empty set and every nested lookup adds one object, so // the set's size is the depth of the lookup chain. if already_seen.len() >= MAX_LOOKUP_DEPTH { - warn!("lookup chain deeper than {MAX_LOOKUP_DEPTH} at object {} {}", id.0, id.1); + if load_log.warning() { + warn!( + "lookup chain deeper than {MAX_LOOKUP_DEPTH} at object {} {}", + id.0, id.1 + ); + } return Err(Error::ReferenceLimit); } if already_seen.contains(&id) { - warn!("reference cycle detected resolving object {} {}", id.0, id.1); + if load_log.warning() { + warn!("reference cycle detected resolving object {} {}", id.0, id.1); + } return Err(Error::ReferenceCycle(id)); } already_seen.insert(id); @@ -1235,11 +1368,11 @@ impl Reader<'_> { if let Some(entry) = self.document.reference_table.get(id.0) && matches!(entry, XrefEntry::Compressed { .. }) { - return self.get_compressed_object(id, already_seen); + return self.get_compressed_object(id, already_seen, load_log); } let offset = self.get_offset(id)?; - let (_, mut obj) = self.read_object(offset as usize, Some(id), already_seen)?; + let (_, mut obj) = self.read_object(offset as usize, Some(id), already_seen, load_log)?; if let Some(ref state) = self.encryption_state { let encrypt_ref = self @@ -1258,11 +1391,17 @@ impl Reader<'_> { Ok(obj) } + /// Resolve encryption metadata without starting standalone diagnostic batches. fn parse_encryption_dictionary(&mut self) -> Result<()> { if let Ok(encrypt_ref) = self.document.trailer.get(b"Encrypt").and_then(|o| o.as_reference()) { if self.raw_objects.is_empty() { let offset = self.get_offset(encrypt_ref)?; - let (_, encrypt_obj) = self.read_object(offset as usize, Some(encrypt_ref), &mut HashSet::new())?; + let (_, encrypt_obj) = self.read_object( + offset as usize, + Some(encrypt_ref), + &mut HashSet::new(), + &ObjectLoadLog::silent(), + )?; self.document.objects.insert(encrypt_ref, encrypt_obj); } else if let Some(raw_bytes) = self.raw_objects.get(&encrypt_ref) && let Ok((_, obj)) = self.parse_raw_object(raw_bytes) @@ -1377,12 +1516,14 @@ impl Reader<'_> { Ok(((obj_num, obj_gen), raw_bytes)) } + /// Find the next normal-object boundary and parse with that recovery limit and read budget. fn read_object( &self, offset: usize, expected_id: Option, already_seen: &mut HashSet, + load_log: &ObjectLoadLog, ) -> Result<(ObjectId, Object)> { let next_index = self.normal_offsets.partition_point(|&next| next <= offset); let end = self.object_end(offset, self.normal_offsets.get(next_index).copied()); - self.read_object_to(offset, end, expected_id, already_seen) + self.read_object_to(offset, end, expected_id, already_seen, load_log) } fn object_end(&self, offset: usize, next_object: Option) -> usize { @@ -1395,8 +1536,10 @@ impl Reader<'_> { .min(self.buffer.len()) } + /// Parse at an offset with the supplied recovery boundary and diagnostic context. fn read_object_to( &self, offset: usize, end: usize, expected_id: Option, already_seen: &mut HashSet, + load_log: &ObjectLoadLog, ) -> Result<(ObjectId, Object)> { if offset > end || end > self.buffer.len() { return Err(Error::InvalidOffset(offset)); @@ -1405,7 +1548,15 @@ impl Reader<'_> { // Objects are parsed against the full buffer so a wrong *neighbor* // xref offset cannot truncate a well-formed object; `end` only limits // how far malformed-stream length recovery may scan. - parser::indirect_object(self.buffer, offset, expected_id, self, already_seen, Some(end)) + parser::indirect_object_with_log( + self.buffer, + offset, + expected_id, + self, + already_seen, + Some(end), + load_log, + ) } /// Parse the cross-reference section recorded at `offset`, first correcting @@ -2118,3 +2269,43 @@ fn object_marker_parsing_accepts_only_real_headers() { assert_eq!(Reader::parse_object_header(b"1 obj"), None); assert_eq!(Reader::parse_object_header(b"x 0 obj"), None); } + +#[cfg(test)] +mod encrypted_load_logging { + use super::*; + /// Keep encrypted skips nonfatal in strict mode while sharing one bounded diagnostic batch. + #[test] + fn encrypted_skips_share_the_budget_and_stay_nonfatal_in_strict_mode() { + // Exercise the eager reader's encrypted-skip branch directly. Public + // encrypted opens normally use load_encrypted_document instead. + let mut buffer = Vec::new(); + let mut xref = Xref::new(1251, XrefType::CrossReferenceTable); + for id in 1..=1250 { + let offset = u32::try_from(buffer.len()).unwrap(); + xref.insert(id, XrefEntry::Normal { offset, generation: 0 }); + buffer.extend_from_slice(format!("{id} 0 obj\nnot-an-object\nendobj\n").as_bytes()); + } + let mut document = Document::new(); + document.trailer.set("Encrypt", (9999, 0)); + let mut reader = Reader { + buffer: &buffer, + document, + encryption_state: None, + raw_objects: BTreeMap::new(), + password: None, + strict: true, + max_decompressed_size: None, + normal_offsets: Vec::new(), + }; + reader.set_reference_table(xref); + // Inspect the shared budget rather than installing another global logger + // in the vendor's unit-test binary (its parser tests use env_logger). + let load_log = ObjectLoadLog::default(); + reader.load_objects_raw_with_log(None, &load_log).unwrap(); + assert!(reader.document.objects.is_empty()); + assert_eq!(load_log.messages.load(Ordering::Relaxed), 1250); + assert_eq!(load_log.encrypted.load(Ordering::Relaxed), 1250); + assert_eq!(load_log.failures.load(Ordering::Relaxed), 0); + assert_eq!(load_log.lengths.load(Ordering::Relaxed), 0); + } +}