diff --git a/crates/docx/src/flat.rs b/crates/docx/src/flat.rs index b88211805f..5fd20ecb23 100644 --- a/crates/docx/src/flat.rs +++ b/crates/docx/src/flat.rs @@ -116,6 +116,10 @@ fn room(total: u64) -> u64 { /// Unpack a Flat OPC file into its parts, with a `[Content_Types].xml` made from the parts' /// content types (unless the file carries one). pub(crate) fn unpack(bytes: &[u8]) -> Result { + unpack_within(bytes, MAX_PART_ELEMENTS) +} + +fn unpack_within(bytes: &[u8], part_elements: usize) -> Result { let text = utf8_text(bytes); let src: &[u8] = text.as_ref(); let mut r = NsReader::from_reader(src); @@ -150,7 +154,7 @@ pub(crate) fn unpack(bytes: &[u8]) -> Result { } } elements += 1; - if elements > MAX_PART_ELEMENTS { + if elements > part_elements { return Err(DocxError::Limit("too many XML elements".into())); } let local = e.local_name().as_ref().to_vec(); @@ -552,6 +556,27 @@ mod tests { assert_eq!(out.matches("xmlns:p").count(), 256); } + #[test] + fn part_element_budget_counts_parts_that_are_not_read() { + assert_eq!(MAX_PART_ELEMENTS, 8_000_002); + let cap = 100; + let inline = |children| format!("{}", "".repeat(children)); + let part = |name: &str, xml: &str| format!("{xml}"); + let package = |parts: &str| format!("{parts}"); + // The part, xmlData and r wrappers count too: 97 children make exactly 100. + let xml = inline(97); + let first = part("/word/unused.xml", &xml); + let at_cap = unpack_within(package(&first).as_bytes(), cap).unwrap(); + assert_eq!(at_cap.get("word/unused.xml"), Some(xml.as_bytes())); + let over = part("/word/unused.xml", &inline(98)); + assert!(matches!(unpack_within(package(&over).as_bytes(), cap), Err(DocxError::Limit(_)))); + // Each package child has its own allowance, even though neither part is read. + let two = format!("{first}{}", part("/word/also-unused.xml", &xml)); + let reset = unpack_within(package(&two).as_bytes(), cap).unwrap(); + assert_eq!(reset.get("word/unused.xml"), Some(xml.as_bytes())); + assert_eq!(reset.get("word/also-unused.xml"), Some(xml.as_bytes())); + } + #[test] fn nesting_is_capped_where_the_xml_tree_reader_stops() { let inline = |levels: usize| format!("{}{}", "".repeat(levels), "".repeat(levels));