From a7b3d7a4c1e9940a209273f227435512bc6de99a Mon Sep 17 00:00:00 2001 From: bchanot Date: Wed, 14 Oct 2026 23:38:54 +0200 Subject: [PATCH] feat(anatomy): prescan caps attributes, namespace declarations and raw markup counts --- crates/core/src/anatomy/svg/prescan.rs | 148 +++++++++++++++++++------ 1 file changed, 113 insertions(+), 35 deletions(-) diff --git a/crates/core/src/anatomy/svg/prescan.rs b/crates/core/src/anatomy/svg/prescan.rs index 02ea16f3..09471564 100644 --- a/crates/core/src/anatomy/svg/prescan.rs +++ b/crates/core/src/anatomy/svg/prescan.rs @@ -1,9 +1,12 @@ -//! Bounds an SVG text before any XML parser sees it (plan R3 C2). roxmltree builds its tree -//! recursively enough to overflow the 1 MiB wasm stack between 1,000 and 3,000 nesting -//! levels (measured 2026-10-14), so the depth and the element count are taken here by a -//! markup scanner: comments, CDATA sections, processing instructions and quoted attribute -//! values are skipped as the XML grammar defines them, never by pattern matching. The scan -//! is an upper bound of what a parser would build; anything it cannot close is malformed. +//! Bounds an SVG text before any XML parser sees it (plan R3 C2). roxmltree 0.21 builds its +//! tree recursively, one level per element, enough to overflow the 1 MiB wasm stack between +//! 1,000 and 3,000 nesting levels (measured 2026-10-14); it also pre-allocates on the raw +//! counts of `<` and `=`, checks duplicate attributes quadratically and copies inherited +//! namespaces per declaring element. So the depth, the element, attribute and namespace +//! counts are taken here by a markup scanner: comments, CDATA sections, processing +//! instructions and quoted attribute values are skipped as the XML grammar defines them, +//! never by pattern matching. The scan is an upper bound of what a parser would build; +//! anything it cannot close is malformed. /// The resource limits of one SVG text. #[derive(Debug, Clone, Copy)] @@ -14,14 +17,27 @@ pub struct SvgCaps { pub max_elements: usize, /// Nesting depth, the root at depth 1. pub max_depth: usize, + /// Attributes of one element (roxmltree's duplicate check is quadratic in it). + pub max_attributes_per_element: usize, + pub max_attributes: usize, + /// `xmlns` and `xmlns:*` declarations. + pub max_namespace_declarations: usize, + /// Raw `<` and `=` bytes, comments and text included. + pub max_open_brackets: usize, + pub max_equals: usize, } -/// The engine's caps (`packages/pdf/src/svg/sanitize.ts` SANITIZER_CAPS) plus the byte cap -/// R3 adds before parsing. +/// The engine's caps (`packages/pdf/src/svg/sanitize.ts` SANITIZER_CAPS) plus the bounds R3 +/// adds before parsing. pub const SVG_CAPS: SvgCaps = SvgCaps { max_bytes: 2 * 1024 * 1024, max_elements: 20_000, max_depth: 64, + max_attributes_per_element: 256, + max_attributes: 100_000, + max_namespace_declarations: 16, + max_open_brackets: 100_000, + max_equals: 200_000, }; /// Why a text is refused before parsing. @@ -32,6 +48,8 @@ pub enum PrescanError { Doctype, TooDeep, TooManyElements, + /// Attribute, namespace or raw markup counts over their caps. + TooComplex, Malformed, } @@ -47,19 +65,20 @@ pub fn prescan(text: &str, caps: &SvgCaps) -> Result { if text.len() > caps.max_bytes { return Err(PrescanError::TooLarge); } - if declares_doctype(text.as_bytes()) { + // xmldom refuses a byte order mark; roxmltree would skip it. + if text.starts_with('\u{feff}') { + return Err(PrescanError::Malformed); + } + let bytes = text.as_bytes(); + if declares_doctype(bytes) { return Err(PrescanError::Doctype); } - let mut scan = Scan { - bytes: text.as_bytes(), - at: 0, - depth: 0, - counted: Prescan { - elements: 0, - depth: 0, - }, - }; - while let Some(open) = find(scan.bytes, b"<", scan.at) { + let count = |b: u8| bytes.iter().filter(|&&x| x == b).count(); + if count(b'<') > caps.max_open_brackets || count(b'=') > caps.max_equals { + return Err(PrescanError::TooComplex); + } + let mut scan = Scan::new(bytes); + while let Some(open) = find(bytes, b"<", scan.at) { scan.at = open; scan.markup(caps)?; } @@ -73,10 +92,33 @@ struct Scan<'a> { bytes: &'a [u8], at: usize, depth: usize, + attributes: usize, + declarations: usize, counted: Prescan, } -impl Scan<'_> { +/// What one start tag holds. +struct Tag { + self_closing: bool, + attributes: usize, + declarations: usize, +} + +impl<'a> Scan<'a> { + fn new(bytes: &'a [u8]) -> Self { + Self { + bytes, + at: 0, + depth: 0, + attributes: 0, + declarations: 0, + counted: Prescan { + elements: 0, + depth: 0, + }, + } + } + /// Consumes the markup starting at `self.at` (a `<`). fn markup(&mut self, caps: &SvgCaps) -> Result<(), PrescanError> { let rest = &self.bytes[self.at..]; @@ -97,8 +139,21 @@ impl Scan<'_> { self.depth = self.depth.checked_sub(1).ok_or(PrescanError::Malformed)?; return Ok(()); } - let self_closing = self.skip_tag()?; - self.open_element(self_closing, caps) + let tag = self.skip_tag()?; + self.count_attributes(&tag, caps)?; + self.open_element(tag.self_closing, caps) + } + + fn count_attributes(&mut self, tag: &Tag, caps: &SvgCaps) -> Result<(), PrescanError> { + self.attributes += tag.attributes; + self.declarations += tag.declarations; + if tag.attributes > caps.max_attributes_per_element + || self.attributes > caps.max_attributes + || self.declarations > caps.max_namespace_declarations + { + return Err(PrescanError::TooComplex); + } + Ok(()) } fn open_element(&mut self, self_closing: bool, caps: &SvgCaps) -> Result<(), PrescanError> { @@ -123,8 +178,14 @@ impl Scan<'_> { Ok(()) } - /// Skips a start tag, quoted values included; answers whether it ends with `/>`. - fn skip_tag(&mut self) -> Result { + /// Skips a start tag, quoted values included, counting its attributes (an `=` outside + /// quotes) and its namespace declarations (an attribute name starting with `xmlns`). + fn skip_tag(&mut self) -> Result { + let mut tag = Tag { + self_closing: false, + attributes: 0, + declarations: 0, + }; let mut quote: Option = None; let mut i = self.at + 1; while let Some(&b) = self.bytes.get(i) { @@ -133,10 +194,13 @@ impl Scan<'_> { (Some(_), _) => {} (None, b'"' | b'\'') => quote = Some(b), (None, b'<') => return Err(PrescanError::Malformed), + (None, b'=') => tag.attributes += 1, (None, b'>') => { self.at = i + 1; - return Ok(i > 0 && self.bytes[i - 1] == b'/'); + tag.self_closing = self.bytes[i - 1] == b'/'; + return Ok(tag); } + (None, _) if declaration_at(self.bytes, i) => tag.declarations += 1, (None, _) => {} } i += 1; @@ -145,6 +209,11 @@ impl Scan<'_> { } } +/// An attribute name starting with `xmlns` begins at `i` (right after whitespace). +fn declaration_at(bytes: &[u8], i: usize) -> bool { + bytes[i - 1].is_ascii_whitespace() && bytes[i..].starts_with(b"xmlns") +} + fn find(haystack: &[u8], needle: &[u8], from: usize) -> Option { haystack .get(from..)? @@ -207,8 +276,8 @@ mod tests { #[test] fn stops_a_deep_text_at_the_cap_without_recursion() { - // 300,000 levels: the parser would overflow the wasm stack; the scan stops at 65. - let text = format!("{SVG}{}", "".repeat(300_000)); + // 99,000 levels (under the `<` cap): the parser would overflow the wasm stack; the scan stops at 65. + let text = format!("{SVG}{}", "".repeat(99_000)); assert_eq!(prescan(&text, &SVG_CAPS), Err(PrescanError::TooDeep)); } @@ -239,14 +308,23 @@ mod tests { depth: 2 }) ); - let text = format!("{SVG}]]>?>"); - assert_eq!( - prescan(&text, &SVG_CAPS), - Ok(Prescan { - elements: 2, - depth: 2 - }) - ); + } + + #[test] + fn refuses_attribute_namespace_and_markup_floods() { + let attrs = |n: usize| (0..n).map(|i| format!(" a{i}=\"{i}\"")).collect::(); + let one = |n: usize| format!("{SVG}", attrs(n)); + assert!(prescan(&one(256), &SVG_CAPS).is_ok()); + assert_eq!(prescan(&one(257), &SVG_CAPS), Err(PrescanError::TooComplex)); + let declarations = (0..16) + .map(|i| format!(" xmlns:n{i}=\"u{i}\"")) + .collect::(); + let ns = format!(""); + assert_eq!(prescan(&ns, &SVG_CAPS), Err(PrescanError::TooComplex)); + let brackets = format!("{SVG}", "<".repeat(100_001)); + assert_eq!(prescan(&brackets, &SVG_CAPS), Err(PrescanError::TooComplex)); + let bom = format!("\u{feff}{SVG}"); + assert_eq!(prescan(&bom, &SVG_CAPS), Err(PrescanError::Malformed)); } #[test]