mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-03 06:31:42 +01:00
svg: note each embedded SVG refusal's reason instead of inferring it
Review on #14385: inferring the reason from craft-svg's totals refused a drawing with a damaged embedded SVGZ (charged the whole byte budget like a nested gzip), and one with a chain at the cap beside an image only too deep in XML. The bounded resolver now repeats craft-svg's first two checks for each embedded SVG, in its order: the chain depth, then unpacking within what the byte budget has left. Only a refusal at the chain cap or for bytes fails a non-strict parse; an image that can't be unpacked is left out, and so are images refused for bytes after it spent the budget.
This commit is contained in:
1 parent
cc349b165f
commit
6b28346f2b
2 files changed
+106
-46
No files matched your search
+48
-26
@@ -10,7 +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::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Mutex, OnceLock, PoisonError};
|
||||
|
||||
use craft_svg::tree::draw::{self, tiny_skia};
|
||||
@@ -545,9 +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 nested_gzip = Arc::new(AtomicBool::new(false));
|
||||
let refusals = Arc::new(SvgRefusals::default());
|
||||
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));
|
||||
opt.image_href_resolver = noting_refusals(opt.image_href_resolver, resolver, Arc::clone(&refusals));
|
||||
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))?;
|
||||
@@ -560,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 usage.svg_limit_images > 0 && (counter.strict || embedded_svg_over_budget(&usage, nested_gzip.load(Ordering::Relaxed))) {
|
||||
} else if usage.svg_limit_images > 0 && (counter.strict || refusals.over_budget.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());
|
||||
@@ -586,42 +586,64 @@ 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(
|
||||
/// Why craft-svg left embedded SVG images out of one bounded parse. Its usage counts every
|
||||
/// refused SVG image together, but an image past [`MAX_EMBEDDED_SVG_DEPTH`] or the byte budget
|
||||
/// fails even a non-strict parse, as the bounded path did before craft-svg, while one nested
|
||||
/// too deeply in XML or that can't be unpacked (gzip inside gzip, a damaged stream, an unknown
|
||||
/// encoding) only leaves itself out.
|
||||
#[derive(Default)]
|
||||
struct SvgRefusals {
|
||||
/// Embedded SVG images being resolved around the current one.
|
||||
depth: AtomicUsize,
|
||||
/// An image was refused for the chain depth or the byte budget.
|
||||
over_budget: AtomicBool,
|
||||
/// craft-svg charged an image that couldn't be unpacked everything the byte budget had left:
|
||||
/// later images refused for bytes are left out with it, not counted as the drawing's excess.
|
||||
spent_by_unreadable: AtomicBool,
|
||||
}
|
||||
|
||||
/// `resolve`, also noting in `refusals` why craft-svg is about to refuse each embedded SVG. It
|
||||
/// repeats craft-svg's first two checks in their order: the chain depth, then unpacking within
|
||||
/// what the byte budget has left (`text/plain` data is an SVG unless it is a raster craft-svg
|
||||
/// draws).
|
||||
fn noting_refusals(
|
||||
resolve: usvg::ImageHrefResolver<'static>,
|
||||
resolver: Arc<craft_svg::tree::ImageResolver>,
|
||||
seen: Arc<AtomicBool>,
|
||||
refusals: Arc<SvgRefusals>,
|
||||
) -> 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 raster = matches!(
|
||||
photocraft_codecs::detect(&data),
|
||||
Some(photocraft_codecs::Format::Png | photocraft_codecs::Format::Jpeg | photocraft_codecs::Format::Gif | photocraft_codecs::Format::WebP)
|
||||
);
|
||||
if !(mime == "image/svg+xml" || (mime == "text/plain" && !raster)) {
|
||||
return resolve_data(mime, data, options);
|
||||
}
|
||||
if refusals.depth.load(Ordering::Relaxed) >= MAX_EMBEDDED_SVG_DEPTH {
|
||||
refusals.over_budget.store(true, Ordering::Relaxed);
|
||||
} else {
|
||||
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);
|
||||
match craft_svg::svgz::text(&data, left) {
|
||||
Ok(_) => {}
|
||||
Err(craft_svg::svgz::Error::TooLarge(_)) => {
|
||||
if !refusals.spent_by_unreadable.load(Ordering::Relaxed) {
|
||||
refusals.over_budget.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
Err(_) => refusals.spent_by_unreadable.store(true, Ordering::Relaxed),
|
||||
}
|
||||
}
|
||||
resolve_data(mime, data, options)
|
||||
refusals.depth.fetch_add(1, Ordering::Relaxed);
|
||||
let image = resolve_data(mime, data, options);
|
||||
refusals.depth.fetch_sub(1, Ordering::Relaxed);
|
||||
image
|
||||
}),
|
||||
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) {
|
||||
|
||||
+58
-20
@@ -1059,35 +1059,73 @@ 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.
|
||||
fn gzip(bytes: &[u8]) -> Vec<u8> {
|
||||
use std::io::Write;
|
||||
let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::best());
|
||||
encoder.write_all(bytes).unwrap();
|
||||
encoder.finish().unwrap()
|
||||
}
|
||||
|
||||
/// An `<image>` holding an 8 × 8 rect inside `levels` SVG images, each gzipped: small at any
|
||||
/// depth, so the byte budget never ends the chain.
|
||||
fn gzipped_chain_image(levels: usize) -> String {
|
||||
let mut svg = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"8\" height=\"8\"><rect width=\"8\" height=\"8\"/></svg>".to_string();
|
||||
for level in 0..levels {
|
||||
let image = format!("<image width=\"8\" height=\"8\" href=\"data:image/svg+xml;base64,{}\"/>", base64(&gzip(svg.as_bytes())));
|
||||
if level + 1 == levels {
|
||||
return image;
|
||||
}
|
||||
svg = format!("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"8\" height=\"8\">{image}</svg>");
|
||||
}
|
||||
String::new()
|
||||
}
|
||||
|
||||
fn chain_svg(images: &str) -> String {
|
||||
format!("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"8\" height=\"8\">{images}</svg>")
|
||||
}
|
||||
|
||||
/// 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);
|
||||
let deepest = chain_svg(&gzipped_chain_image(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();
|
||||
let error = parse_bounded(chain_svg(&gzipped_chain_image(MAX_EMBEDDED_SVG_DEPTH + 1)).as_bytes(), MAX_RASTER_PIXELS).unwrap_err();
|
||||
assert!(error.to_string().contains("byte or nesting budget"), "{error}");
|
||||
}
|
||||
|
||||
/// A chain that fits the cap beside an image only nested too deeply in XML: that image is left
|
||||
/// out, as on its own, and the chain still parses.
|
||||
#[test]
|
||||
fn a_chain_at_the_nesting_cap_beside_an_image_too_deep_in_xml_still_parses() {
|
||||
let deep = format!(
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"8\" height=\"8\">{}<rect width=\"8\" height=\"8\"/>{}</svg>",
|
||||
"<g>".repeat(MAX_XML_DEPTH - 1),
|
||||
"</g>".repeat(MAX_XML_DEPTH - 1)
|
||||
);
|
||||
let too_deep = embedded_image("image/svg+xml", deep.as_bytes());
|
||||
assert!(parse_bounded(image_svg(&too_deep).as_bytes(), MAX_RASTER_PIXELS).is_ok(), "on its own it is left out");
|
||||
let svg = chain_svg(&format!("{}{too_deep}", gzipped_chain_image(MAX_EMBEDDED_SVG_DEPTH)));
|
||||
let (_, chain_length) = parse_bounded_inner(svg.as_bytes(), MAX_RASTER_PIXELS).unwrap();
|
||||
assert_eq!(chain_length, MAX_EMBEDDED_SVG_DEPTH as u64);
|
||||
}
|
||||
|
||||
/// An embedded SVGZ whose gzip stream is cut short is left out like any unreadable image, though
|
||||
/// craft-svg charges it the rest of the byte budget; an image refused for bytes after it is too.
|
||||
#[test]
|
||||
fn a_damaged_embedded_svgz_is_left_out() {
|
||||
let svg = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"4\" height=\"4\"><rect width=\"4\" height=\"4\"/></svg>";
|
||||
let compressed = gzip(svg.as_bytes());
|
||||
let damaged = embedded_image("image/svg+xml", &compressed[..compressed.len() / 2]);
|
||||
let after = embedded_image("image/svg+xml", svg.as_bytes());
|
||||
let parsed = parse_bounded(image_svg(&format!("{damaged}{after}")).as_bytes(), MAX_RASTER_PIXELS).unwrap();
|
||||
assert!(!parsed.tree.root().has_children(), "both images are left out");
|
||||
// A stored preview must draw completely, so it is still refused there.
|
||||
assert!(parse_bounded_work_with(image_svg(&damaged).as_bytes(), MAX_RASTER_PIXELS, true, fonts).is_err());
|
||||
}
|
||||
|
||||
/// 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]
|
||||
|
||||
Reference in new issue
Block a user