svg: bounded parse refuses embedded SVG chains past the byte or nesting budget (#14356)

craft-svg counts an embedded SVG refused for the byte budget, the chain
depth, the shared XML depth or gzip inside gzip as one svg_limit image,
and charges it whatever the byte budget had left. c2689ba21 let a
non-strict bounded parse leave all of them out, so a chain of embedded
SVG images past the 16 MiB budget rendered with its innermost images
dropped instead of being refused.

The bounded resolver now also notes gzip-in-gzip images, and a non-strict
parse is refused when the byte budget is spent (unless a nested gzip
spent it) or the chain reached MAX_EMBEDDED_SVG_DEPTH. An image only
nested too deeply in XML, or holding gzip inside gzip, is still left out.
This commit is contained in:
RickiNano committed 2026-11-14 09:28:27 +01:00
1 parent 5b27ff6fe3
commit cc349b165f
2 files changed
+82 -13

No files matched your search

+41 -2
View File
@@ -10,6 +10,7 @@
//! stops and direction in the layer's own gradient fill, with a warning that the exact geometry
//! is not kept.
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, OnceLock, PoisonError};
use craft_svg::tree::draw::{self, tiny_skia};
@@ -544,7 +545,9 @@ fn parse_image_bounded_with(
budget.lock().unwrap_or_else(PoisonError::into_inner).fontless_text = true;
}
let resolver = Arc::clone(&budget.lock().unwrap_or_else(PoisonError::into_inner).resolver);
let opt = options_with_isolation(fontdb, xml_left, isolated, resolver);
let nested_gzip = Arc::new(AtomicBool::new(false));
let mut opt = options_with_isolation(fontdb, xml_left, isolated, Arc::clone(&resolver));
opt.image_href_resolver = noting_nested_gzip(opt.image_href_resolver, resolver, Arc::clone(&nested_gzip));
let text = std::str::from_utf8(&xml).map_err(|_| IoError::Svg("the SVG is not valid UTF-8".into()))?;
let limits = tree_limits(xml_left, MAX_RASTER_PIXELS);
let tree = guarded_parse(|| craft_svg::tree::parse_text(text, &limits, &opt))?;
@@ -557,7 +560,7 @@ fn parse_image_bounded_with(
counter.svg_chain = usage.embedded_svg_depth as u64;
if usage.raster_limit_images > 0 {
counter.error.get_or_insert_with(|| "embedded SVG raster images exceed the decoded pixel budget".into());
} else if counter.strict && usage.svg_limit_images > 0 {
} else if usage.svg_limit_images > 0 && (counter.strict || embedded_svg_over_budget(&usage, nested_gzip.load(Ordering::Relaxed))) {
counter.error.get_or_insert_with(|| "embedded SVG images exceed the byte or nesting budget".into());
} else if counter.strict && (usage.invalid_raster_images > 0 || usage.invalid_svg_images > 0) {
counter.error.get_or_insert_with(|| "can't parse an embedded SVG image".into());
@@ -583,6 +586,42 @@ fn parse_image_bounded_with(
})
}
/// `resolve`, also noting in `seen` an embedded SVG whose gzip holds gzip again, unpacked within
/// what the byte budget has left as craft-svg unpacks it. craft-svg refuses that image as over
/// the byte budget and charges it everything the budget had left, so afterwards a spent budget
/// no longer means the drawing's images were too large.
fn noting_nested_gzip(
resolve: usvg::ImageHrefResolver<'static>,
resolver: Arc<craft_svg::tree::ImageResolver>,
seen: Arc<AtomicBool>,
) -> usvg::ImageHrefResolver<'static> {
let usvg::ImageHrefResolver { resolve_data, resolve_string } = resolve;
usvg::ImageHrefResolver {
resolve_data: Box::new(move |mime, data, options| {
if matches!(mime, "image/svg+xml" | "text/plain") {
let left = usize::try_from(MAX_BOUNDED_SVG_BYTES).unwrap_or(usize::MAX).saturating_sub(resolver.usage().embedded_svg_bytes);
if matches!(craft_svg::svgz::inflate(&data, left), Err(craft_svg::svgz::Error::Nested(_))) {
seen.store(true, Ordering::Relaxed);
}
}
resolve_data(mime, data, options)
}),
resolve_string,
}
}
/// Whether craft-svg left an embedded SVG out because the drawing's SVG images were too large
/// together or nested more than [`MAX_EMBEDDED_SVG_DEPTH`] deep, which fails even a non-strict
/// parse, as the bounded path did before craft-svg. Its count of refused SVG images also covers
/// an image nested too deeply in XML and a gzip inside gzip, which only leave that image out.
/// A refused image is charged whatever the byte budget had left, so a spent budget means too
/// large unless a nested gzip spent it. A chain at the cap, or a spent budget, alongside an
/// image only too deep in XML is refused too: the counts can't tell them apart.
fn embedded_svg_over_budget(usage: &craft_svg::tree::ImageUsage, nested_gzip: bool) -> bool {
let spent = usage.embedded_svg_bytes >= usize::try_from(MAX_BOUNDED_SVG_BYTES).unwrap_or(usize::MAX);
(spent && !nested_gzip) || usage.embedded_svg_depth >= MAX_EMBEDDED_SVG_DEPTH
}
/// Used paint/effect resources can decode an image once per use. Ordinary paths, gradients,
/// clipping paths and blur filters without image references do not multiply unrelated photos.
fn repeatable_image_resources(tree: &usvg::Tree) -> (bool, bool) {
+41 -11
View File
@@ -60,6 +60,18 @@ fn image_svg(images: &str) -> String {
format!("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"1\" height=\"1\">{images}</svg>")
}
fn base64(bytes: &[u8]) -> String {
const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::new();
for chunk in bytes.chunks(3) {
let n = chunk.iter().enumerate().fold(0u32, |n, (i, b)| n | u32::from(*b) << (16 - 8 * i));
for i in 0..4 {
out.push(if i <= chunk.len() { T[(n >> (18 - 6 * i) & 63) as usize] as char } else { '=' });
}
}
out
}
fn png_dimensions(width: u32, height: u32) -> Vec<u8> {
let mut bytes = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR".to_vec();
bytes.extend_from_slice(&width.to_be_bytes());
@@ -1017,17 +1029,6 @@ fn bounded_embedded_svg_gets_only_the_nesting_depth_the_drawing_left() {
/// main-thread size); deeper ones are refused.
#[test]
fn the_deepest_chain_of_embedded_svg_images_fits_a_small_stack() {
fn base64(bytes: &[u8]) -> String {
const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::new();
for chunk in bytes.chunks(3) {
let n = chunk.iter().enumerate().fold(0u32, |n, (i, b)| n | u32::from(*b) << (16 - 8 * i));
for i in 0..4 {
out.push(if i <= chunk.len() { T[(n >> (18 - 6 * i) & 63) as usize] as char } else { '=' });
}
}
out
}
let chain = |levels: usize| {
let mut svg = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"8\" height=\"8\"><rect width=\"8\" height=\"8\"/></svg>".to_string();
for _ in 0..levels {
@@ -1058,6 +1059,35 @@ fn the_deepest_chain_of_embedded_svg_images_fits_a_small_stack() {
.unwrap();
}
/// gzipped at every level, a chain of SVG images stays small, so the byte budget never ends it:
/// one image past [`MAX_EMBEDDED_SVG_DEPTH`] is refused, not parsed with the innermost left out.
/// (Drawing such a chain is refused past craft-svg's own, lower limit of 24.)
#[test]
fn a_chain_of_svg_images_past_the_nesting_cap_is_refused() {
use std::io::Write;
let gz = |bytes: &[u8]| {
let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::best());
encoder.write_all(bytes).unwrap();
encoder.finish().unwrap()
};
let chain = |levels: usize| {
let mut svg = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"8\" height=\"8\"><rect width=\"8\" height=\"8\"/></svg>".to_string();
for _ in 0..levels {
svg = format!(
"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"8\" height=\"8\"><image width=\"8\" height=\"8\" href=\"data:image/svg+xml;base64,{}\"/></svg>",
base64(&gz(svg.as_bytes()))
);
}
svg
};
let deepest = chain(MAX_EMBEDDED_SVG_DEPTH);
assert!(deepest.len() < 1 << 20, "far below the byte budget: {} bytes", deepest.len());
let (_, chain_length) = parse_bounded_inner(deepest.as_bytes(), MAX_RASTER_PIXELS).unwrap();
assert_eq!(chain_length, MAX_EMBEDDED_SVG_DEPTH as u64, "every level parses");
let error = parse_bounded(chain(MAX_EMBEDDED_SVG_DEPTH + 1).as_bytes(), MAX_RASTER_PIXELS).unwrap_err();
assert!(error.to_string().contains("byte or nesting budget"), "{error}");
}
/// Only a stored display preview is strict about an embedded image it can't read; an edited SVG
/// saved back from an external editor leaves it out, as placement does.
#[test]