mirror of
https://github.com/storytold/photocraft.git
synced 2026-11-21 01:18:43 +00:00
SVG: a drawing the renderer panics on is an error, not a crash (#9404)
usvg, resvg and tiny-skia panic on some malformed drawings (an feOffset past the pixmap's size, an embedded SVG image of near-zero width). Parse and every render now run under catch_unwind, as the HEIF and JPEG XL decoders do: a parse panic is IoError::Svg, a panicking element is dropped with a warning and the rest opens, a smart-object render is an error, and an icon-theme mask is None. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b0622d20ca
commit
a617ba83fe
3 files changed
+72
-16
No files matched your search
@@ -202,17 +202,22 @@ pub fn rasterize_mask(svg: &[u8], px: u32) -> Option<Vec<u8>> {
|
||||
image_href_resolver: usvg::ImageHrefResolver { resolve_data: Box::new(|_, _, _| None), resolve_string: Box::new(|_, _| None) },
|
||||
..usvg::Options::default()
|
||||
};
|
||||
let tree = usvg::Tree::from_data(svg, &opts).ok()?;
|
||||
let size = tree.size();
|
||||
let side = size.width().max(size.height());
|
||||
if !side.is_finite() || side <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let s = px as f32 / side;
|
||||
let (dx, dy) = ((px as f32 - size.width() * s) / 2.0, (px as f32 - size.height() * s) / 2.0);
|
||||
let mut pixmap = tiny_skia::Pixmap::new(px, px)?;
|
||||
resvg::render(&tree, tiny_skia::Transform::from_scale(s, s).post_translate(dx, dy), &mut pixmap.as_mut());
|
||||
Some(pixmap.data().as_chunks::<4>().0.iter().map(|[_, _, _, a]| *a).collect())
|
||||
// usvg and resvg panic on some malformed drawings: such an icon is unreadable, not a crash.
|
||||
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
let tree = usvg::Tree::from_data(svg, &opts).ok()?;
|
||||
let size = tree.size();
|
||||
let side = size.width().max(size.height());
|
||||
if !side.is_finite() || side <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let s = px as f32 / side;
|
||||
let (dx, dy) = ((px as f32 - size.width() * s) / 2.0, (px as f32 - size.height() * s) / 2.0);
|
||||
let mut pixmap = tiny_skia::Pixmap::new(px, px)?;
|
||||
resvg::render(&tree, tiny_skia::Transform::from_scale(s, s).post_translate(dx, dy), &mut pixmap.as_mut());
|
||||
Some(pixmap.data().as_chunks::<4>().0.iter().map(|[_, _, _, a]| *a).collect())
|
||||
}))
|
||||
.ok()
|
||||
.flatten()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -303,6 +308,15 @@ mod tests {
|
||||
assert!(rasterize_mask(SQUARE.as_bytes(), 100_000).is_none());
|
||||
}
|
||||
|
||||
/// resvg panics rendering an offset past the pixmap's size: the icon is unreadable instead.
|
||||
#[test]
|
||||
fn a_mask_the_renderer_panics_on_is_none() {
|
||||
let svg = r##"<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16">
|
||||
<filter id="f"><feOffset dx="3e9" dy="-3e9"/></filter><rect width="16" height="16" filter="url(#f)"/>
|
||||
</svg>"##;
|
||||
assert!(rasterize_mask(svg.as_bytes(), 16).is_none());
|
||||
}
|
||||
|
||||
/// An icon's `<image>` is never loaded: not a device file, not an embedded picture.
|
||||
#[test]
|
||||
fn masks_load_no_images() {
|
||||
|
||||
+22
-5
@@ -274,10 +274,19 @@ fn parse_with(bytes: &[u8], fonts: fn() -> Arc<usvg::fontdb::Database>) -> Resul
|
||||
// re-checks the gzip magic and would decompress a second time without our size limit if
|
||||
// the inflated content happened to start with a nested gzip stream.
|
||||
let text = std::str::from_utf8(&xml).map_err(|_| IoError::Svg("the SVG is not valid UTF-8".into()))?;
|
||||
let tree = usvg::Tree::from_str(text, &opt).map_err(|e| IoError::Svg(e.to_string()))?;
|
||||
let tree = guarded(|| usvg::Tree::from_str(text, &opt))
|
||||
.ok_or_else(|| IoError::Svg("the SVG parser failed on this drawing".into()))?
|
||||
.map_err(|e| IoError::Svg(e.to_string()))?;
|
||||
Ok(Parsed { tree, fontless_text })
|
||||
}
|
||||
|
||||
/// `f` under `catch_unwind`, `None` when it panics: usvg, resvg and tiny-skia panic on some
|
||||
/// malformed drawings, which must fail like any unreadable file, not crash (as the HEIF and
|
||||
/// JPEG XL decoders are guarded). Where a panic aborts (wasm) this changes nothing.
|
||||
fn guarded<T>(f: impl FnOnce() -> T) -> Option<T> {
|
||||
std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).ok()
|
||||
}
|
||||
|
||||
/// The plain XML of `bytes`: itself, or the inflated content of a gzip `.svgz`, refused past
|
||||
/// [`MAX_INFLATED_BYTES`] (a decompression bomb) or when the stream is corrupt.
|
||||
fn inflate(bytes: &[u8]) -> Result<std::borrow::Cow<'_, [u8]>, IoError> {
|
||||
@@ -400,8 +409,11 @@ fn import_parsed_with_budget(name: &str, parsed: Parsed, max_group_depth: usize,
|
||||
conv.warnings.push(format!("SVG: more than {MAX_NODES} elements; opened as one pixel layer instead of shapes"));
|
||||
let (w, h) = (cv.size.width, cv.size.height);
|
||||
if let Some(mut pixmap) = pixmap(w, h) {
|
||||
resvg::render(&tree, global, &mut pixmap.as_mut());
|
||||
doc.layers.push(Layer::new("Background", LayerContent::Raster(surface(&pixmap, doc.bounds(), fmt))));
|
||||
if guarded(|| resvg::render(&tree, global, &mut pixmap.as_mut())).is_some() {
|
||||
doc.layers.push(Layer::new("Background", LayerContent::Raster(surface(&pixmap, doc.bounds(), fmt))));
|
||||
} else {
|
||||
conv.warnings.push("SVG: the drawing could not be rendered".to_string());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
doc.layers = conv.convert_children(tree.root().children(), 0, 0, tree.root().abs_transform());
|
||||
@@ -421,7 +433,8 @@ pub fn rasterize(bytes: &[u8], scale: f32) -> Result<photocraft_compose::Buffer,
|
||||
let side = |v: f32| ((v * k).ceil() as u32).max(1);
|
||||
let (w, h) = (side(tree.size().width()), side(tree.size().height()));
|
||||
let mut pixmap = pixmap(w, h).ok_or_else(|| IoError::Svg(format!("{w} × {h} px is too large to rasterise")))?;
|
||||
resvg::render(&tree, tiny_skia::Transform::from_scale(k, k), &mut pixmap.as_mut());
|
||||
guarded(|| resvg::render(&tree, tiny_skia::Transform::from_scale(k, k), &mut pixmap.as_mut()))
|
||||
.ok_or_else(|| IoError::Svg("the drawing could not be rendered".into()))?;
|
||||
let rect = Rect::new(0, 0, w as i32, h as i32);
|
||||
let px = pixmap.pixels().iter().map(|p| rgba(p.demultiply())).collect();
|
||||
Ok(photocraft_compose::Buffer { rect, px })
|
||||
@@ -798,7 +811,11 @@ impl Conv {
|
||||
// and shift so the pixmap starts at (x0, y0).
|
||||
let canvas = tiny_skia::Transform::from_row(k, 0.0, 0.0, k, -(x0 as f32), -(y0 as f32));
|
||||
let ts = canvas.pre_concat(parent).pre_translate(shift.x(), shift.y());
|
||||
resvg::render_node(node, ts, &mut pixmap.as_mut())?;
|
||||
let Some(rendered) = guarded(|| resvg::render_node(node, ts, &mut pixmap.as_mut())) else {
|
||||
self.note("raster-panic", "SVG: an element that could not be rendered was dropped".to_string());
|
||||
return None;
|
||||
};
|
||||
rendered?;
|
||||
let layer = Layer::new(name, LayerContent::Raster(surface(&pixmap, Rect::new(x0, y0, x1, y1), self.fmt)));
|
||||
let bytes = pixels * self.fmt.bytes_per_pixel() as u64;
|
||||
self.pixel_budget -= bytes;
|
||||
|
||||
@@ -413,6 +413,31 @@ fn rasterize_renders_the_whole_drawing_at_a_scale() {
|
||||
assert!(svg::rasterize(huge.as_bytes(), 64.0).is_err(), "a render past the pixel cap is an error, not an allocation");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drawings_the_svg_renderer_panics_on_are_errors_not_crashes() {
|
||||
// usvg panics laying out an embedded SVG image of a zero-ish width.
|
||||
let nested = "data:image/svg+xml;utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='10'%3E%3Crect width='10' height='10'/%3E%3C/svg%3E";
|
||||
let bad_image = format!("<svg {NS} width=\"100\" height=\"100\"><image width=\"1e-30\" height=\"50\" href=\"{nested}\"/></svg>");
|
||||
let e = import("image.svg", bad_image.as_bytes()).err().unwrap_or_else(|| panic!("opened"));
|
||||
assert!(matches!(e, IoError::Svg(_)), "{e}");
|
||||
// resvg panics rendering an offset past the pixmap's size: that element is dropped with a
|
||||
// warning, the rest of the drawing still opens.
|
||||
let offset = "<filter id=\"f\"><feOffset dx=\"3e9\" dy=\"-3e9\"/></filter>\
|
||||
<rect width=\"50\" height=\"50\" filter=\"url(#f)\"/><rect id=\"plain\" x=\"60\" y=\"60\" width=\"20\" height=\"20\"/>";
|
||||
let svg = format!("<svg {NS} width=\"100\" height=\"100\">{offset}</svg>");
|
||||
let r = open(&svg);
|
||||
assert_eq!(r.document.layers.len(), 1, "{:?}", r.document.layers.iter().map(|l| &l.name).collect::<Vec<_>>());
|
||||
assert!(matches!(r.document.layers[0].content, LayerContent::Shape(_)));
|
||||
assert!(r.warnings.iter().any(|w| w.contains("could not be rendered")), "{:?}", r.warnings);
|
||||
// The same drawing as a smart object, and past the element limit (opened as one pixel layer).
|
||||
let e = svg::rasterize(svg.as_bytes(), 1.0).err().unwrap_or_else(|| panic!("rendered"));
|
||||
assert!(matches!(e, IoError::Svg(_)), "{e}");
|
||||
let many = format!("<svg {NS} width=\"100\" height=\"100\">{offset}{}</svg>", "<rect width=\"1\" height=\"1\"/>".repeat(2_000));
|
||||
let r = open(&many);
|
||||
assert!(r.document.layers.is_empty());
|
||||
assert!(r.warnings.iter().any(|w| w.contains("could not be rendered")), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_svg_round_trips_through_pcraft_as_shapes() {
|
||||
let r = open(&format!(
|
||||
|
||||
Reference in new issue
Block a user