pdf: append/extract now flatten inherited page attributes and stop leaking other pages
- Commit
8947d8e6ae556835487fa04c4b89d9da943db827- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-01 04:00 UTC (5 days ago)
- Parents
ec12b4f
Two defects in the page operations, both proven with crafted documents. (1) append_pdf copied only /MediaBox+/Resources: a page inheriting /Rotate 90 and /CropBox [10 20 310 420] from its /Pages node (both inheritable per ISO 32000 7.7.3.3/4) came out 612x792 unrotated and uncropped instead of 400x300; extract_page had the same /CropBox hole. (2) extract_page copied the entire source object graph and simply pointed /Kids at one page, so extracting page 0 of a two-page document shipped page 2's content stream verbatim. append and extract now resolve inheritable /MediaBox//CropBox//Rotate//Resources from the source page chain (new crop_box() accessor beside media_box()) and write the missing ones onto the moved page, preserving attributes the page carries itself; extract additionally runs prune_objects() (lopdf trailer reachability, the same rule save_compressed already applies) so only the extracted page's graph ships. /MediaBox-only inheritance was verified already correct and is pinned by a test. Three crafted-document regressions failed pre-fix (CropBox None twice, other-page marker present). Verified: cargo 674 passed, clippy clean for the new code; :pdf:testDevUnitTest NativeDocumentTest 4/4 against the rebuilt library.
Diff
pdf/src/main/rust/src/cov_docedit_tests.rs
diff --git a/pdf/src/main/rust/src/cov_docedit_tests.rs b/pdf/src/main/rust/src/cov_docedit_tests.rsindex e4feb64f89..9908f77c99 100644--- a/pdf/src/main/rust/src/cov_docedit_tests.rs+++ b/pdf/src/main/rust/src/cov_docedit_tests.rs@@ -121,6 +121,98 @@ fn remap_object_rewrites_nested_refs_and_streams() { assert_eq!(d.as_dict().unwrap().get(b"A").unwrap(), &Object::Reference((10, 0))); } +// --- Inherited page attributes (ISO 32000 §7.7.3.3/§7.7.3.4) ---------------+// Pages under an intermediate /Pages node carrying /MediaBox, /CropBox,+// /Rotate and /Resources only on that node. `own_crop` gives page 1 its own+// /CropBox, which flattening must preserve rather than overwrite.+fn inherited_doc_bytes(media: [i64; 4], crop: Option<[i64; 4]>, rotate: Option<i64>, own_crop: Option<[i64; 4]>) -> Vec<u8> {+ let mut doc = Document::with_version("1.7");+ let font_id = doc.add_object(dictionary! { "Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica" });+ let mut mid = dictionary! {+ "Type" => "Pages", "Kids" => Object::Array(vec![]), "Count" => 2,+ "MediaBox" => Object::Array(media.iter().map(|v| Object::Integer(*v)).collect::<Vec<_>>()),+ "Resources" => dictionary! { "Font" => dictionary! { "F1" => font_id } },+ };+ if let Some(c) = crop { mid.set("CropBox", Object::Array(c.iter().map(|v| Object::Integer(*v)).collect::<Vec<_>>())); }+ if let Some(r) = rotate { mid.set("Rotate", Object::Integer(r)); }+ let mid_id = doc.add_object(mid);+ let c1 = doc.add_object(Stream::new(dictionary! {}, b"PAGEONE_MARKER".to_vec()));+ let c2 = doc.add_object(Stream::new(dictionary! {}, b"PAGETWO_SECRET_MARKER".to_vec()));+ let mut p1 = dictionary! { "Type" => "Page", "Parent" => mid_id, "Contents" => c1 };+ if let Some(c) = own_crop { p1.set("CropBox", Object::Array(c.iter().map(|v| Object::Integer(*v)).collect::<Vec<_>>())); }+ let p1_id = doc.add_object(p1);+ let p2_id = doc.add_object(dictionary! { "Type" => "Page", "Parent" => mid_id, "Contents" => c2 });+ if let Ok(d) = doc.get_dictionary_mut(mid_id) { d.set("Kids", Object::Array(vec![p1_id.into(), p2_id.into()])); }+ let root_id = doc.add_object(dictionary! { "Type" => "Pages", "Kids" => Object::Array(vec![mid_id.into()]), "Count" => 2 });+ if let Ok(d) = doc.get_dictionary_mut(mid_id) { d.set("Parent", Object::Reference(root_id)); }+ let cat_id = doc.add_object(dictionary! { "Type" => "Catalog", "Pages" => root_id });+ doc.trailer.set("Root", cat_id);+ let mut buf = Vec::new();+ doc.save_to(&mut buf).expect("crafted doc saves");+ buf+}+fn rect_of(doc: &Document, page_id: ObjectId, key: &[u8]) -> Option<Vec<i64>> {+ doc.get_dictionary(page_id).ok()?.get(key).ok()?.as_array().ok().map(|a| a.iter().map(|o| o.as_i64().unwrap_or(-1)).collect())+}++#[test]+fn append_flattens_inherited_rotate_cropbox_mediabox() {+ let bytes = inherited_doc_bytes([0, 0, 612, 792], Some([10, 20, 310, 420]), Some(90), None);+ let dest = create_empty_document();+ assert_eq!(append_pdf(dest, &bytes), 2);+ let saved = save_document(dest).expect("appended saves");+ close_document(dest);+ let doc = Document::load_mem(&saved).expect("appended parses");+ let pages = doc.get_pages();+ assert_eq!(pages.len(), 2);+ for pid in pages.values() {+ let d = doc.get_dictionary(*pid).expect("page dict");+ assert_eq!(rect_of(&doc, *pid, b"MediaBox"), Some(vec![0, 0, 612, 792]), "inherited /MediaBox must be flattened");+ assert_eq!(rect_of(&doc, *pid, b"CropBox"), Some(vec![10, 20, 310, 420]), "inherited /CropBox must be flattened");+ assert_eq!(d.get(b"Rotate").expect("inherited /Rotate must be flattened").as_i64().unwrap(), 90);+ assert!(d.get(b"Resources").is_ok(), "inherited /Resources must be flattened");+ assert_eq!(page_display_size(&doc, *pid), (400.0, 300.0), "rotated+cropped display size");+ }+}++#[test]+fn append_flattens_inherited_mediabox_only_and_preserves_own_cropbox() {+ let bytes = inherited_doc_bytes([0, 0, 200, 400], None, None, Some([0, 0, 100, 100]));+ let dest = create_empty_document();+ assert_eq!(append_pdf(dest, &bytes), 2);+ let saved = save_document(dest).expect("appended saves");+ close_document(dest);+ let doc = Document::load_mem(&saved).expect("appended parses");+ let mut seen = Vec::new();+ for pid in doc.get_pages().values() { seen.push(rect_of(&doc, *pid, b"CropBox")); }+ assert!(seen.contains(&Some(vec![0, 0, 100, 100])), "page's own /CropBox must be preserved, got {seen:?}");+ for pid in doc.get_pages().values() {+ assert_eq!(rect_of(&doc, *pid, b"MediaBox"), Some(vec![0, 0, 200, 400]));+ }+}++#[test]+fn extract_flattens_inherited_attrs_and_excludes_other_pages() {+ let bytes = inherited_doc_bytes([0, 0, 612, 792], Some([10, 20, 310, 420]), Some(90), None);+ let h = open_document(&bytes);+ assert_ne!(h, 0);+ let one = extract_page(h, 0).expect("extract page 0");+ close_document(h);+ assert!(one.windows(14).any(|w| w == b"PAGEONE_MARKER"), "extracted page content present");+ assert!(!one.windows(18).any(|w| w == b"PAGETWO_SECRET_MAR"), "other page's content must not ship in extract, bytes: {}", one.len());+ let doc = Document::load_mem(&one).expect("extract parses");+ assert_eq!(doc.get_pages().len(), 1);+ let pid = *doc.get_pages().values().next().unwrap();+ let d = doc.get_dictionary(pid).expect("page dict");+ assert_eq!(rect_of(&doc, pid, b"MediaBox"), Some(vec![0, 0, 612, 792]));+ assert_eq!(rect_of(&doc, pid, b"CropBox"), Some(vec![10, 20, 310, 420]), "inherited /CropBox must be flattened on extract");+ assert_eq!(d.get(b"Rotate").expect("inherited /Rotate on extract").as_i64().unwrap(), 90);+ assert_eq!(page_display_size(&doc, pid), (400.0, 300.0));+ for obj in doc.objects.values() {+ if let Object::Stream(s) = obj { assert!(!s.content.windows(14).any(|w| w == b"PAGETWO_SECRET"), "other page stream object leaked"); }+ }+}+ #[test] fn append_kid_handles_indirect_kids_array() { let mut doc = Document::with_version("1.7");
pdf/src/main/rust/src/docedit.rs
diff --git a/pdf/src/main/rust/src/docedit.rs b/pdf/src/main/rust/src/docedit.rsindex 6c0cb3c673..e191a9130e 100644--- a/pdf/src/main/rust/src/docedit.rs+++ b/pdf/src/main/rust/src/docedit.rs@@ -81,6 +81,50 @@ pub(crate) fn remap_object(obj: &Object, map: &HashMap<ObjectId, ObjectId>) -> O } } +/// Inheritable page attributes (§7.7.3.3/§7.7.3.4: `/MediaBox`, `/CropBox`,+/// `/Rotate`, `/Resources`) resolved from `src` page `src_page_id`, with any+/// references remapped through `map` for the destination document.+struct FlattenedPageAttrs {+ media: [f64; 4],+ crop: Option<[f64; 4]>,+ rotate: i64,+ resources: Option<Object>,+}++fn collect_flattened_attrs(src: &Document, src_page_id: ObjectId, map: &HashMap<ObjectId, ObjectId>) -> FlattenedPageAttrs {+ FlattenedPageAttrs {+ media: media_box(src, src_page_id),+ crop: crop_box(src, src_page_id),+ rotate: page_rotation(src, src_page_id),+ resources: inherited(src, src_page_id, b"Resources").map(|o| remap_object(o, map)),+ }+}++/// Write `attrs` onto the imported page, without overwriting attributes the+/// page already carries itself. Its `/Parent` becomes the destination's+/// (attribute-less) `/Pages` root, so anything not written here is lost.+fn apply_flattened_attrs(dest: &mut Document, new_page_id: ObjectId, pages_id: ObjectId, attrs: &FlattenedPageAttrs) {+ if let Ok(pd) = dest.get_dictionary_mut(new_page_id) {+ pd.set("Parent", Object::Reference(pages_id));+ if pd.get(b"MediaBox").is_err() {+ pd.set("MediaBox", Object::Array(vec![attrs.media[0].into(), attrs.media[1].into(), attrs.media[2].into(), attrs.media[3].into()]));+ }+ if pd.get(b"CropBox").is_err() {+ if let Some(c) = attrs.crop {+ pd.set("CropBox", Object::Array(vec![c[0].into(), c[1].into(), c[2].into(), c[3].into()]));+ }+ }+ if pd.get(b"Resources").is_err() {+ if let Some(r) = &attrs.resources {+ pd.set("Resources", r.clone());+ }+ }+ if pd.get(b"Rotate").is_err() && attrs.rotate != 0 {+ pd.set("Rotate", Object::Integer(attrs.rotate));+ }+ }+}+ /// Append every page of the PDF in `bytes` to the document behind `handle`. /// Returns the number of pages added (0 on failure/encrypted source). pub(crate) fn append_pdf(handle: i64, bytes: &[u8]) -> i32 {@@ -123,24 +167,10 @@ pub(crate) fn append_pdf(handle: i64, bytes: &[u8]) -> i32 { Some(id) => *id, None => continue, };- // Resolve inherited MediaBox/Resources onto the imported page since its+ // Resolve inherited attributes onto the imported page since its // parent is now our (attribute-less) Pages root.- let mb = media_box(&src, src_page_id);- let res = inherited(&src, src_page_id, b"Resources").map(|o| remap_object(o, &map));- if let Ok(pd) = dest.get_dictionary_mut(new_page_id) {- pd.set("Parent", Object::Reference(pages_id));- if pd.get(b"MediaBox").is_err() {- pd.set(- "MediaBox",- Object::Array(vec![mb[0].into(), mb[1].into(), mb[2].into(), mb[3].into()]),- );- }- if pd.get(b"Resources").is_err() {- if let Some(r) = res {- pd.set("Resources", r);- }- }- }+ let attrs = collect_flattened_attrs(&src, src_page_id, &map);+ apply_flattened_attrs(dest, new_page_id, pages_id, &attrs); append_kid(dest, pages_id, new_page_id); added += 1; }@@ -298,29 +328,16 @@ pub(crate) fn extract_page(handle: i64, index: i32) -> Option<Vec<u8>> { out.objects.insert(map[old_id], remap_object(obj, &map)); } let new_page_id = *map.get(&src_page_id)?;- let mb = media_box(src, src_page_id);- let res = inherited(src, src_page_id, b"Resources").map(|o| remap_object(o, &map));- let rot = page_rotation(src, src_page_id);+ let attrs = collect_flattened_attrs(src, src_page_id, &map); drop(reg); - if let Ok(pd) = out.get_dictionary_mut(new_page_id) {- pd.set("Parent", Object::Reference(pages_id));- if pd.get(b"MediaBox").is_err() {- pd.set(- "MediaBox",- Object::Array(vec![mb[0].into(), mb[1].into(), mb[2].into(), mb[3].into()]),- );- }- if pd.get(b"Resources").is_err() {- if let Some(r) = res {- pd.set("Resources", r);- }- }- if rot != 0 {- pd.set("Rotate", Object::Integer(rot));- }- }+ apply_flattened_attrs(&mut out, new_page_id, pages_id, &attrs); append_kid(&mut out, pages_id, new_page_id);+ // The copy above brought the whole source graph; only the chosen page is+ // reachable from the new catalog. Prune the rest (other pages, the source+ // page tree, detached objects) so the standalone file ships just its page+ // — the same reachability rule `save_compressed` applies via lopdf.+ out.prune_objects(); let mut buf = Vec::new(); out.save_to(&mut buf).ok()?;
pdf/src/main/rust/src/geometry.rs
diff --git a/pdf/src/main/rust/src/geometry.rs b/pdf/src/main/rust/src/geometry.rsindex 8678d7caa2..de3bb56540 100644--- a/pdf/src/main/rust/src/geometry.rs+++ b/pdf/src/main/rust/src/geometry.rs@@ -75,6 +75,11 @@ pub(crate) fn media_box(doc: &Document, page_id: ObjectId) -> [f64; 4] { inherited_rect(doc, page_id, b"MediaBox").unwrap_or([0.0, 0.0, 612.0, 792.0]) } +/// Inherited `/CropBox` as `[x0, y0, x1, y1]`, if one is in effect.+pub(crate) fn crop_box(doc: &Document, page_id: ObjectId) -> Option<[f64; 4]> {+ inherited_rect(doc, page_id, b"CropBox")+}+ /// `/UserUnit` inherited, default 1.0, clamped to valid range per spec. /// /// Deliberately NOT used by the render path — see `page_visible_box`. Kept for a