From 72a6c4fe012297f8e9cbdd854dababe61e084e4b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 07:56:22 -0800 Subject: [PATCH] MCP: a confined package searches the whole attachment tree and keeps its read roots when written later The search for a PDF's editing file stopped 16 levels deep in the attachment name tree, so an editing file listed deeper read as absent and a confined package copied the PDF without checking its stored paths. The search now walks the tree at any depth, each indirect node once, up to 65,536 nodes; a tree with more nodes counts as listing the editing file, so a confined package refuses the PDF. A prepared package (Session::prepare_package) now keeps the read roots in force where it was prepared, and Package::write collects under them on any thread. --- crates/engine/src/cmd/package.rs | 12 +++-- crates/engine/src/tests/package.rs | 6 +++ crates/pdf/src/editing.rs | 75 +++++++++++++++++++----------- crates/pdf/src/tests/editing.rs | 34 ++++++++++++++ 4 files changed, 96 insertions(+), 31 deletions(-) diff --git a/crates/engine/src/cmd/package.rs b/crates/engine/src/cmd/package.rs index 99bcf455b7..324b29b20b 100644 --- a/crates/engine/src/cmd/package.rs +++ b/crates/engine/src/cmd/package.rs @@ -521,6 +521,9 @@ pub struct Package { root: Option, info: Option, doc: std::sync::Arc, + /// The read roots in force where the package was prepared: [`Package::write`] collects under + /// them. + scope: crate::file_access::ScopeHandle, } impl Session { @@ -567,21 +570,22 @@ fn prepare(s: &mut Session, p: &Value) -> Result { let doc = s.doc()?.doc.clone(); let doc = if let std::borrow::Cow::Owned(kept) = super::fileio::with_readable_settings_folder(&doc) { std::sync::Arc::new(kept) } else { doc }; let links_from = s.doc()?.links_from.clone().unwrap_or_else(|| doc_path.clone()); - Ok(Package { o, doc_path, links_from, stem, name, root, info, doc }) + let scope = crate::file_access::ScopeHandle::capture(); + Ok(Package { o, doc_path, links_from, stem, name, root, info, doc, scope }) } impl Package { /// Collect the linked files and fonts and write the package's files with `write` into /// `folder/name`, making its folders first, or into the zip without a folder → the reply of - /// `file.package`. + /// `file.package`, with the read roots in force where it was prepared, on any thread. pub fn write(self, write: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result { - collect_and_write(self, write) + self.scope.clone().run(|| collect_and_write(self, write)) } } /// [`Package::write`]. fn collect_and_write(package: Package, write: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result { - let Package { o, doc_path, links_from, stem, name, root, info, doc: original } = package; + let Package { o, doc_path, links_from, stem, name, root, info, doc: original, scope: _ } = package; let mut doc = (*original).clone(); let doc_name = format!("{stem}.{}", vectorcraft_format::EXTENSION); let base = LinkBase { doc: Some(&doc_path), relative: Some(&links_from) }; diff --git a/crates/engine/src/tests/package.rs b/crates/engine/src/tests/package.rs index 1474a84569..040cd47424 100644 --- a/crates/engine/src/tests/package.rs +++ b/crates/engine/src/tests/package.rs @@ -508,6 +508,12 @@ fn a_confined_package_refuses_a_linked_file_whose_editing_data_cannot_be_read() write(&pdf, &locked); refused(&mut s, json!({"folder": out})); refused(&mut s, json!({"relink": false})); + // A package prepared in the confined request and written on another thread. + let prepared = crate::file_access::confine(Some(&roots), || s.prepare_package(&json!({"folder": out}))).unwrap(); + let e = + std::thread::spawn(move || prepared.write(&mut |_, _| Ok(())).map(|_| ()).map_err(|e| e.to_string())).join().unwrap().expect_err("refused"); + assert!(e.contains("a linked file's editing data can't be read to check it against the read roots"), "{e}"); + assert!(!std::path::Path::new(&out).exists()); assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package"); // A PDF listing the editing file without its data (`EF` renamed, the same length). let at = editable.windows(4).position(|w| w.starts_with(b"/EF") && !w[3].is_ascii_alphanumeric()).expect("the editing file's EF"); diff --git a/crates/pdf/src/editing.rs b/crates/pdf/src/editing.rs index bcdf6a9b1d..e19849f0d8 100644 --- a/crates/pdf/src/editing.rs +++ b/crates/pdf/src/editing.rs @@ -27,8 +27,8 @@ const DESCRIPTION: &str = "VectorCraft editing data; page hash "; /// Stands for the hash while the PDF is written: as long as a hash, so writing the hash over it /// keeps every offset. const PLACEHOLDER: &str = "0000000000000000"; -/// Deepest name tree searched for the editing file. -const MAX_DEPTH: usize = 16; +/// The most name tree nodes searched for the editing file. +const MAX_NODES: usize = 1 << 16; /// The native document a PDF carries ([`crate::PdfSettings::preserve_editing`]). #[derive(Clone, Debug, PartialEq, Eq)] @@ -78,7 +78,8 @@ pub fn editing_with(bytes: &[u8], password: Option<&str>) -> Option { } /// The file specification of the editing file among a parsed PDF's attachments, if any, and whether -/// a name tree key names the editing file (set also when its file specification can't be read). +/// the attachments may list it: a name tree key names the editing file (set also when its file +/// specification can't be read), or the name tree has more than [`MAX_NODES`] nodes to search. fn editing_file_spec(pdf: &Pdf) -> (Option>, bool) { let xref = pdf.xref(); let Some(tree) = xref @@ -88,17 +89,17 @@ fn editing_file_spec(pdf: &Pdf) -> (Option>, bool) { else { return (None, false); }; - let mut keyed = false; - let spec = editing_spec(&tree, 0, &mut HashSet::new(), &mut keyed, xref); - (spec, keyed) + let mut maybe = false; + let spec = editing_spec(tree, &mut maybe, xref); + (spec, maybe) } /// Does a parsed PDF list the editing file among its attachments, also when [`editing_in`] can't /// read it (its file specification, its `EF` dictionary or its `F` or `UF` stream can't be -/// resolved)? +/// resolved)? Also true when the name tree is too large to search to its end. pub(crate) fn has_editing_file_in(pdf: &Pdf) -> bool { - let (spec, keyed) = editing_file_spec(pdf); - spec.is_some() || keyed + let (spec, maybe) = editing_file_spec(pdf); + spec.is_some() || maybe } /// [`editing`] of a parsed PDF. @@ -117,10 +118,43 @@ pub(crate) fn editing_in(pdf: &Pdf) -> Option { Some(Editing { data, intact }) } -/// The file specification of the editing file in the name tree node `node`. `seen` holds the indirect -/// nodes already searched, so a node shared by many `Kids` arrays is searched once, not once per path. -/// `keyed` is set when a key searched names the editing file. -fn editing_spec<'a>(node: &Dict<'a>, depth: usize, seen: &mut HashSet, keyed: &mut bool, xref: &'a XRef) -> Option> { +/// The file specification of the editing file in the name tree `tree`, searched in order at any +/// depth, [`MAX_NODES`] nodes at most. An indirect node is searched once, so a node shared by many +/// `Kids` arrays is not searched once per path. `maybe` is set when a key searched names the editing +/// file, or when nodes are left unsearched. +fn editing_spec<'a>(tree: Dict<'a>, maybe: &mut bool, xref: &'a XRef) -> Option> { + let mut seen = HashSet::::new(); + let mut nodes = vec![tree]; + // Nodes still to be searched, counting the ones waiting in `nodes`. + let mut left = MAX_NODES - 1; + while let Some(node) = nodes.pop() { + if let Some(spec) = node_spec(&node, maybe, xref) { + return Some(spec); + } + let Some(kids) = node.get::>(b"Kids") else { continue }; + // Only a referenced kid can be shared (a direct kid's `obj_id` is the object holding it). The + // reference is checked before the kid is read, so a shared kid is read once. + let mut kids: Vec> = items(&kids) + .filter_map(|raw| match raw { + MaybeRef::Ref(r) if seen.insert(r.into()) => xref.get::>(r.into()), + MaybeRef::NotRef(Object::Dict(kid)) => Some(kid), + _ => None, + }) + .take(left.saturating_add(1)) + .collect(); + if kids.len() > left { + *maybe = true; + kids.truncate(left); + } + left -= kids.len(); + nodes.extend(kids.into_iter().rev()); + } + None +} + +/// The file specification of the editing file among the name tree node `node`'s own `Names`. +/// `keyed` is set when a key names the editing file. +fn node_spec<'a>(node: &Dict<'a>, keyed: &mut bool, xref: &'a XRef) -> Option> { if let Some(names) = node.get::>(b"Names") { // The keys read as written, so a value that can't be resolved doesn't shift the pairs. let mut raw = items(&names); @@ -143,20 +177,7 @@ fn editing_spec<'a>(node: &Dict<'a>, depth: usize, seen: &mut HashSet= MAX_DEPTH { - return None; - } - let kids = node.get::>(b"Kids")?; - // Only a referenced kid can be shared (a direct kid's `obj_id` is the object holding it). The - // reference is checked before the kid is read, so a shared kid is read once. - items(&kids).find_map(|raw| { - let kid = match raw { - MaybeRef::Ref(r) if seen.insert(r.into()) => xref.get::>(r.into())?, - MaybeRef::NotRef(Object::Dict(kid)) => kid, - _ => return None, - }; - editing_spec(&kid, depth + 1, seen, keyed, xref) - }) + None } /// A file specification naming the editing file (current or legacy name), in any text string diff --git a/crates/pdf/src/tests/editing.rs b/crates/pdf/src/tests/editing.rs index 4346bc068d..6417f6b231 100644 --- a/crates/pdf/src/tests/editing.rs +++ b/crates/pdf/src/tests/editing.rs @@ -279,3 +279,37 @@ fn an_editing_file_whose_data_cannot_be_resolved_is_still_listed() { let opened = open_pdf(&pdf_with(Some(b"native"), false).bytes, None).unwrap(); assert!(opened.editing().is_some() && opened.has_editing_file()); } + +#[test] +fn an_editing_file_deep_in_the_name_tree_is_found() { + // Objects 4..=203 are a chain of 200 name tree nodes, each listing the next one; the editing + // file sits in the leaf (object 204), with its data or naming data that can't be resolved. + for ef in ["/EF << /F 206 0 R >>", "/EF << /F 999 0 R >>"] { + let mut objects = vec![ + "<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(), + "<< /Type /Pages /Kids [207 0 R] /Count 1 >>".to_string(), + "<< /Kids [4 0 R] >>".to_string(), + ]; + for node in 4..=203 { + objects.push(format!("<< /Kids [{} 0 R] >>", node + 1)); + } + objects.push("<< /Names [(a) 205 0 R] >>".to_string()); + objects.push(format!("<< /Type /Filespec /UF ({EDITING_FILE}) {ef} >>")); + objects.push("<< /Length 5 >>\nstream\nhello\nendstream".to_string()); + objects.push("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string()); + let opened = open_pdf(&raw_pdf(&objects), None).unwrap(); + assert!(opened.has_editing_file(), "{ef}"); + let data = opened.editing().map(|e| e.data); + assert_eq!(data.as_deref(), ef.contains("206").then_some(&b"hello"[..]), "{ef}"); + } + // A name tree with more nodes than are searched may list it. + let objects = [ + "<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(), + "<< /Type /Pages /Kids [4 0 R] /Count 1 >>".to_string(), + format!("<< /Kids [{}] >>", "<< /Names [] >> ".repeat(70_000)), + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string(), + ]; + let opened = open_pdf(&raw_pdf(&objects), None).unwrap(); + assert_eq!(opened.editing(), None); + assert!(opened.has_editing_file()); +}