MCP: a confined package refuses a PDF whose attachment search was cut short

When a PDF's attachment name tree has more nodes than the editing-file
search reads (65,536), a confined package still copied the PDF if the
search had found a readable editing file, so attachments past the limit
went unchecked. The search now walks on after finding the editing file,
reading only the Kids, and records whether nodes were left unsearched.
Under read roots, file.package refuses such a PDF with the error for
editing data that can't be read, even when an editing file was read.
Opening the PDF is unchanged: it reads the first editing file found.
This commit is contained in:
dotCooCoo
2026-11-16 09:25:44 -08:00
parent 72a6c4fe01
commit 466b93f4d0
5 changed files with 116 additions and 23 deletions
+5 -2
View File
@@ -122,8 +122,9 @@ enum Carried {
Readable(Box<Document>),
/// The file is a native document, or carries one, that can't be read: a damaged native file,
/// a PDF or `.ai` file that can't be opened without a password or can't be read at all, a PDF
/// or `.ai` file listing an editing file whose data can't be resolved, or editing data that
/// doesn't read as a native document.
/// or `.ai` file listing an editing file whose data can't be resolved, a PDF or `.ai` file
/// whose attachments are too many to search to their end, or editing data that doesn't read as
/// a native document.
Unreadable,
}
@@ -137,6 +138,8 @@ fn carried_document(name: &str, bytes: &[u8]) -> Carried {
if super::place::document::is_pdf(name, bytes) {
// A PDF that can't be opened may carry editing data all the same.
return match vectorcraft_pdf::open_pdf(bytes, None) {
// Attachments left unsearched may list another editing file, which can't be checked.
Ok(opened) if opened.editing_search_cut() => Carried::Unreadable,
// An editing file listed whose data can't be resolved can't be checked either.
Ok(opened) => match opened.editing() {
Some(e) => read(&e.data),
+40
View File
@@ -528,6 +528,14 @@ fn a_confined_package_refuses_a_linked_file_whose_editing_data_cannot_be_read()
write(&pdf, &plain);
assert_eq!(package(&mut s, json!({"folder": out})).unwrap()["links"], 1);
std::fs::remove_dir_all(&out).unwrap();
// A PDF whose attachments are too many to search to their end, with a readable editing file
// listed before the ones left unsearched.
let cut = attachments_cut_short(&vectorcraft_pdf::editing(&editable).unwrap().data);
assert!(vectorcraft_pdf::editing(&cut).is_some(), "the editing data is read");
write(&pdf, &cut);
refused(&mut s, json!({"folder": out}));
refused(&mut s, json!({"relink": false}));
assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package");
// A native document that doesn't load, rewritten or copied as it is.
let mut s = poster(&native);
write(&native, b"not a document");
@@ -536,6 +544,38 @@ fn a_confined_package_refuses_a_linked_file_whose_editing_data_cannot_be_read()
assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package");
}
/// A one-page PDF carrying `native` as its editing file, listed first in an attachment name tree
/// whose second subtree has 70,000 nodes, more than are searched.
fn attachments_cut_short(native: &[u8]) -> Vec<u8> {
let name = vectorcraft_pdf::EDITING_FILE;
let mut stream = format!("<< /Length {} >>\nstream\n", native.len()).into_bytes();
stream.extend_from_slice(native);
stream.extend_from_slice(b"\nendstream");
let objects = [
b"<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_vec(),
b"<< /Type /Pages /Kids [6 0 R] /Count 1 >>".to_vec(),
format!("<< /Kids [4 0 R << /Kids [{}] >>] >>", "<< /Names [] >> ".repeat(70_000)).into_bytes(),
format!("<< /Names [({name}) << /Type /Filespec /UF ({name}) /EF << /F 5 0 R >> >>] >>").into_bytes(),
stream,
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] >>".to_vec(),
];
let mut out = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::new();
for (i, body) in objects.iter().enumerate() {
offsets.push(out.len());
out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());
out.extend_from_slice(body);
out.extend_from_slice(b"\nendobj\n");
}
let xref = out.len();
out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", offsets.len() + 1).as_bytes());
for at in &offsets {
out.extend_from_slice(format!("{at:010} 00000 n \n").as_bytes());
}
out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", offsets.len() + 1).as_bytes());
out
}
/// A missing link stored as a path relative to the document names a file inside a confined
/// request's read root: the package report and Document Info give its stored path.
#[test]
+39 -20
View File
@@ -77,34 +77,50 @@ pub fn editing_with(bytes: &[u8], password: Option<&str>) -> Option<Editing> {
editing_in(&crate::pages::open(bytes, password).ok()?)
}
/// The file specification of the editing file among a parsed PDF's attachments, if any, and whether
/// 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<Dict<'_>>, bool) {
/// What the search of a parsed PDF's attachments for the editing file found ([`editing_file_spec`]).
struct Search<'a> {
/// The editing file's file specification, if one was found.
spec: Option<Dict<'a>>,
/// A name tree key searched names the editing file (set also when its file specification
/// can't be read).
keyed: bool,
/// The name tree has more than [`MAX_NODES`] nodes, so nodes were left unsearched.
cut: bool,
}
/// The search of a parsed PDF's attachments for the editing file.
fn editing_file_spec(pdf: &Pdf) -> Search<'_> {
let xref = pdf.xref();
let Some(tree) = xref
.get::<Dict<'_>>(xref.root_id())
.and_then(|catalog| catalog.get::<Dict<'_>>(b"Names"))
.and_then(|names| names.get::<Dict<'_>>(b"EmbeddedFiles"))
else {
return (None, false);
return Search { spec: None, keyed: false, cut: false };
};
let mut maybe = false;
let spec = editing_spec(tree, &mut maybe, xref);
(spec, maybe)
let (mut keyed, mut cut) = (false, false);
let spec = editing_spec(tree, &mut keyed, &mut cut, xref);
Search { spec, keyed, cut }
}
/// 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)? 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, maybe) = editing_file_spec(pdf);
spec.is_some() || maybe
let search = editing_file_spec(pdf);
search.spec.is_some() || search.keyed || search.cut
}
/// Is a parsed PDF's attachment name tree too large to search to its end (more than [`MAX_NODES`]
/// nodes)? It may then list an editing file that [`editing_in`] doesn't find, besides the one it
/// reads.
pub(crate) fn editing_search_cut_in(pdf: &Pdf) -> bool {
editing_file_spec(pdf).cut
}
/// [`editing`] of a parsed PDF.
pub(crate) fn editing_in(pdf: &Pdf) -> Option<Editing> {
let spec = editing_file_spec(pdf).0?;
let spec = editing_file_spec(pdf).spec?;
let files = spec.get::<Dict<'_>>(b"EF")?;
let stream = files.get::<Stream<'_>>(b"F").or_else(|| files.get::<Stream<'_>>(b"UF"))?;
let data = stream.decoded().map(|d| d.into_owned()).unwrap_or_default();
@@ -118,18 +134,21 @@ pub(crate) fn editing_in(pdf: &Pdf) -> Option<Editing> {
Some(Editing { data, intact })
}
/// 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<Dict<'a>> {
/// The first file specification of the editing file in the name tree `tree`, searched in order at
/// any depth, [`MAX_NODES`] nodes at most. After the editing file is found, the walk goes on to the
/// end of the tree, or to the node limit, without reading the nodes' `Names`. An indirect node is
/// searched once, so a node shared by many `Kids` arrays is not searched once per path. `keyed` is
/// set when a key searched names the editing file, and `cut` when nodes are left unsearched.
fn editing_spec<'a>(tree: Dict<'a>, keyed: &mut bool, cut: &mut bool, xref: &'a XRef) -> Option<Dict<'a>> {
let mut seen = HashSet::<ObjectIdentifier>::new();
let mut nodes = vec![tree];
let mut found = None;
// 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);
// Once the editing file is found, only the `Kids` are read, to learn whether the tree is cut.
if found.is_none() {
found = node_spec(&node, keyed, xref);
}
let Some(kids) = node.get::<Array<'a>>(b"Kids") else { continue };
// Only a referenced kid can be shared (a direct kid's `obj_id` is the object holding it). The
@@ -143,13 +162,13 @@ fn editing_spec<'a>(tree: Dict<'a>, maybe: &mut bool, xref: &'a XRef) -> Option<
.take(left.saturating_add(1))
.collect();
if kids.len() > left {
*maybe = true;
*cut = true;
kids.truncate(left);
}
left -= kids.len();
nodes.extend(kids.into_iter().rev());
}
None
found
}
/// The file specification of the editing file among the name tree node `node`'s own `Names`.
+6
View File
@@ -267,6 +267,12 @@ impl Opened {
crate::editing::has_editing_file_in(&self.pdf)
}
/// Is the PDF's attachment name tree too large to search to its end? It may then list an
/// editing file that [`editing`](Self::editing) doesn't find, besides the one it reads.
pub fn editing_search_cut(&self) -> bool {
crate::editing::editing_search_cut_in(&self.pdf)
}
/// The private data of an Illustrator `.ai`, as [`illustrator_data`] reads it.
pub fn illustrator_data(&self) -> Option<Vec<u8>> {
private_data(&self.pdf)
+26 -1
View File
@@ -311,5 +311,30 @@ fn an_editing_file_deep_in_the_name_tree_is_found() {
];
let opened = open_pdf(&raw_pdf(&objects), None).unwrap();
assert_eq!(opened.editing(), None);
assert!(opened.has_editing_file());
assert!(opened.has_editing_file() && opened.editing_search_cut());
// One that lists a readable editing file before the nodes left unsearched and another after
// them: the first is read, and the search reads as cut short.
let leaf = |stream: u32| format!("<< /Names [({EDITING_FILE}) << /Type /Filespec /UF ({EDITING_FILE}) /EF << /F {stream} 0 R >> >>] >>");
let objects = [
"<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(),
"<< /Type /Pages /Kids [8 0 R] /Count 1 >>".to_string(),
format!("<< /Kids [4 0 R {}5 0 R] >>", "<< /Names [] >> ".repeat(70_000)),
leaf(6),
leaf(7),
"<< /Length 5 >>\nstream\nfirst\nendstream".to_string(),
"<< /Length 6 >>\nstream\nsecond\nendstream".to_string(),
"<< /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().map(|e| e.data).as_deref(), Some(&b"first"[..]));
assert!(opened.has_editing_file() && opened.editing_search_cut());
// The same, with the nodes past the limit in a subtree after the one holding the first.
let mut objects = objects;
objects[2] = format!("<< /Kids [4 0 R << /Kids [{}5 0 R] >>] >>", "<< /Names [] >> ".repeat(70_000));
let opened = open_pdf(&raw_pdf(&objects), None).unwrap();
assert_eq!(opened.editing().map(|e| e.data).as_deref(), Some(&b"first"[..]));
assert!(opened.has_editing_file() && opened.editing_search_cut());
// A tree searched to its end.
let opened = open_pdf(&pdf_with(Some(b"native"), false).bytes, None).unwrap();
assert!(opened.editing().is_some() && !opened.editing_search_cut());
}