From 81bd633c7f384e6f964176eb0baa4b271f1c7f8e Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Fri, 13 Nov 2026 08:51:23 -0500 Subject: [PATCH] Expose checked SVG preflight and viewport rewrite --- crates/svg/src/guard.rs | 16 +++++-- crates/svg/src/preflight.rs | 11 ++++- crates/svg/src/tree.rs | 89 ++++++++++++++++++++++++++++++++++--- 3 files changed, 104 insertions(+), 12 deletions(-) diff --git a/crates/svg/src/guard.rs b/crates/svg/src/guard.rs index 073bfe34c..f3573e443 100644 --- a/crates/svg/src/guard.rs +++ b/crates/svg/src/guard.rs @@ -178,6 +178,10 @@ pub fn too_wide(svg: &str, most: usize, most_work: usize) -> bool { pub struct Prescan<'s> { /// Whether the elements nest deeper than the cap. The pass stops there. pub too_deep: bool, + /// Deepest element nesting observed (markup entities count ten times). + pub depth: usize, + /// Deepest stack of unclosed source elements, excluding self-closing leaves. + pub open_depth: usize, /// The text with each data URL in an element's attribute values left out: a `data:` value's /// quotes kept, a `url(…)`'s parentheses and quotes. Borrowed when there is none, and the /// whole text when `too_deep`. An embedded picture is a data URL and most of the text when @@ -250,7 +254,7 @@ pub fn prescan(svg: &str, most: usize) -> Prescan<'_> { (b.len(), false) }; // (now, deepest) of the elements, and of the markup inside the document type. - let (mut elements, mut entities) = ((0usize, 0usize), (0usize, 0usize)); + let (mut elements, mut entities, mut open_depth) = ((0usize, 0usize), (0usize, 0usize), 0usize); let mut doctype_end = 0; let mut i = 0; while let Some(at) = b.get(i..).and_then(|rest| rest.iter().position(|c| *c == b'<')).map(|at| i + at) { @@ -287,8 +291,14 @@ pub fn prescan(svg: &str, most: usize) -> Prescan<'_> { end }; if elements.1.saturating_add(entities.1.saturating_mul(10)) > most { - return Prescan { too_deep: true, markers: Cow::Borrowed(svg) }; + return Prescan { + too_deep: true, + depth: elements.1.saturating_add(entities.1.saturating_mul(10)), + open_depth, + markers: Cow::Borrowed(svg), + }; } + open_depth = open_depth.max(elements.0); } let markers = if data_values.is_empty() { Cow::Borrowed(svg) @@ -303,7 +313,7 @@ pub fn prescan(svg: &str, most: usize) -> Prescan<'_> { text.push_str(svg.get(from..).unwrap_or_default()); Cow::Owned(text) }; - Prescan { too_deep: false, markers } + Prescan { too_deep: false, depth: elements.1.saturating_add(entities.1.saturating_mul(10)), open_depth, markers } } #[cfg(test)] diff --git a/crates/svg/src/preflight.rs b/crates/svg/src/preflight.rs index 3ab381ff3..a11a5d9b7 100644 --- a/crates/svg/src/preflight.rs +++ b/crates/svg/src/preflight.rs @@ -71,6 +71,11 @@ pub fn text<'a>(bytes: &'a [u8], limits: &Limits) -> Result, Error> /// Parses already-decoded SVG text and checks it against `limits`. pub fn parse_text<'a>(svg: &'a str, limits: &Limits) -> Result, Error> { + parse_text_with_depth(svg, limits).map(|(xml, _, _)| xml) +} + +/// Parses and validates SVG text, returning its source nesting depth as well as its XML tree. +pub fn parse_text_with_depth<'a>(svg: &'a str, limits: &Limits) -> Result<(roxmltree::Document<'a>, usize, usize), Error> { if svg.len() > limits.bytes { return Err(Error::Text(crate::svgz::Error::TooLarge(limits.bytes))); } @@ -83,9 +88,11 @@ pub fn parse_text<'a>(svg: &'a str, limits: &Limits) -> Result(bytes: &'a [u8], limits: &Limits) -> Result, Error> { let text = svgz::text(bytes, limits.bytes)?; - checked(&text, limits)?; + preflight(&text, limits)?; Ok(text) } @@ -130,12 +136,30 @@ pub fn parse(bytes: &[u8], limits: &Limits, options: &usvg::Options<'_>) -> Resu /// [`parse`] for SVG text the caller already holds. pub fn parse_text(svg: &str, limits: &Limits, options: &usvg::Options<'_>) -> Result { - let xml = checked(svg, limits)?; - usvg::Tree::from_xmltree(&xml, options).map_err(|e| Error::Parse(e.to_string())) + preflight(svg, limits)?.parse(options) } -/// Every check on SVG text, cheapest first; the XML it parses to on the way. -fn checked<'s>(svg: &'s str, limits: &Limits) -> Result, Error> { +/// SVG text after shared byte, entity, attribute, XML and expansion-depth checks. +/// Keep it opaque so consumers use the same checked tree and don't reparse XML locally. +pub struct Preflight<'s> { + xml: roxmltree::Document<'s>, + depth: usize, +} + +impl Preflight<'_> { + /// Maximum source nesting depth before following references. + pub fn depth(&self) -> usize { + self.depth + } + + /// Converts this already-checked XML into the configured usvg tree. + pub fn parse(self, options: &usvg::Options<'_>) -> Result { + usvg::Tree::from_xmltree(&self.xml, options).map_err(|e| Error::Parse(e.to_string())) + } +} + +/// Checks already-decoded SVG text once, retaining the parsed XML for both depth policy and tree conversion. +pub fn preflight<'s>(svg: &'s str, limits: &Limits) -> Result, Error> { let preflight_limits = crate::preflight::Limits { bytes: limits.bytes, depth: limits.depth, @@ -145,7 +169,7 @@ fn checked<'s>(svg: &'s str, limits: &Limits) -> Result, attribute_work: limits.attribute_work, xml_nodes: limits.xml_nodes, }; - let xml = crate::preflight::parse_text(svg, &preflight_limits).map_err(|e| match e { + let (xml, _depth, depth) = crate::preflight::parse_text_with_depth(svg, &preflight_limits).map_err(|e| match e { crate::preflight::Error::Text(e) => Error::Text(e), crate::preflight::Error::Entities => Error::Entities, crate::preflight::Error::EntityMarkup => Error::EntityMarkup, @@ -156,7 +180,58 @@ fn checked<'s>(svg: &'s str, limits: &Limits) -> Result, if height(&xml, limits.tree_depth)?.is_none() { return Err(Error::TooDeep(limits.tree_depth)); } - Ok(xml) + Ok(Preflight { xml, depth }) +} + +/// Dimensions of an SVG viewport in SVG user units. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Viewport { + pub width: f64, + pub height: f64, +} + +/// Wraps a validated SVG root in a new viewport while preserving the original root as content. +/// The original root must have finite, positive pixel or point dimensions. +pub fn rewrite_root_viewport(svg: &str, target: Viewport, limits: &Limits, output_limit: usize) -> Result { + if !target.width.is_finite() || !target.height.is_finite() || target.width <= 0.0 || target.height <= 0.0 { + return Err(Error::Viewport("target dimensions must be finite and positive".into())); + } + let checked = preflight(svg, limits)?; + let root = checked.xml.root_element(); + if root.tag_name().name() != "svg" { + return Err(Error::Viewport("root element is not svg".into())); + } + let root_dimension = |key: &str| { + let value = root.attribute(key)?; + let (number, scale) = value.strip_suffix("pt").map_or((value, 1.0), |n| (n, 4.0 / 3.0)); + number.parse::().ok().map(|n| n * scale).filter(|n| n.is_finite() && *n > 0.0) + }; + let (width, height) = root_dimension("width") + .zip(root_dimension("height")) + .ok_or_else(|| Error::Viewport("source has no finite pixel or point dimensions".into()))?; + let range = root.range(); + let preamble = svg.get(..range.start).ok_or_else(|| Error::Viewport("invalid XML preamble range".into()))?; + let inner = svg.get(range).ok_or_else(|| Error::Viewport("invalid root element range".into()))?; + let prefix = format!( + r#""#, + target.width, target.height, width, height + ); + let len = preamble + .len() + .checked_add(prefix.len()) + .and_then(|n| n.checked_add(inner.len())) + .and_then(|n| n.checked_add(6)) + .ok_or(Error::OutputTooLarge(output_limit))?; + if len > output_limit { + return Err(Error::OutputTooLarge(output_limit)); + } + let mut output = String::new(); + output.try_reserve_exact(len).map_err(|_| Error::OutputTooLarge(output_limit))?; + output.push_str(preamble); + output.push_str(&prefix); + output.push_str(inner); + output.push_str(""); + Ok(output) } /// Properties whose value an element's descendants use too: the paint server they name is