Skip to main content

vector_core/
svg.rs

1//! Untrusted SVG, rendered to pixels in Rust: no SVG markup reaches a webview from here.
2//!
3//! Opened as a document, an SVG runs scripts, fetches, animates and exposes the browser engine's
4//! whole SVG implementation; as pixels it is only a picture. Rendering is still attackable by
5//! resources alone, so before resvg sees a document it is parsed once, node-capped, and walked the
6//! way rendering would expand it (`<use>` clones, pattern paints, marker vertices, masks, clips,
7//! filters, offscreen layers) against fixed budgets. That same parsed document is what usvg then
8//! converts, so the budget and the renderer can't read two different trees. usvg reads nothing from
9//! disk or the network: string hrefs are refused, embedded images are PNG/JPEG by their bytes and
10//! dimension-checked from their headers, and compressed SVG is never inflated.
11
12use std::collections::HashMap;
13use std::sync::atomic::{AtomicUsize, Ordering};
14use std::sync::Arc;
15
16use resvg::{tiny_skia, usvg};
17use roxmltree::Node;
18
19/// Largest SVG accepted, in bytes.
20pub const MAX_SVG_BYTES: usize = 8 * 1024 * 1024;
21/// Longest side a render may have.
22pub const MAX_RENDER_DIM: u32 = 4096;
23
24const MAX_XML_NODES: u32 = 200_000;
25/// Elements rendering may produce once every reference is expanded.
26const EXPANSION_BUDGET: u64 = 100_000;
27const MAX_DEPTH: u32 = 256;
28/// Offscreen layers stacked at once: opacity, masks, clips, filters and blends each render into one
29/// canvas-sized buffer, so a large canvas allows fewer (see `layer_limit`).
30const MAX_LAYERS: u32 = 16;
31const LAYER_MEMORY_BYTES: u64 = 256 * 1024 * 1024;
32/// Filter primitives applied across the whole document.
33const FILTER_BUDGET: u64 = 256;
34const MAX_EMBEDDED_IMAGE_BYTES: usize = 4 * 1024 * 1024;
35const MAX_EMBEDDED_TOTAL_BYTES: usize = 16 * 1024 * 1024;
36const MAX_EMBEDDED_DIM: u32 = 4096;
37
38/// A rendered SVG: straight (non-premultiplied) RGBA, `width * height * 4` bytes.
39pub struct Rendered {
40    pub width: u32,
41    pub height: u32,
42    pub rgba: Vec<u8>,
43}
44
45/// Render an untrusted SVG so its longest side is `max_dim` pixels (capped at [`MAX_RENDER_DIM`]).
46/// Refuses anything over budget rather than rendering part of it.
47pub fn rasterize(bytes: &[u8], max_dim: u32) -> Result<Rendered, String> {
48    if bytes.len() > MAX_SVG_BYTES {
49        return Err("SVG too large".into());
50    }
51    if bytes.starts_with(&[0x1f, 0x8b]) {
52        return Err("compressed SVG refused".into());
53    }
54    let text = std::str::from_utf8(bytes).map_err(|_| "SVG is not UTF-8".to_string())?;
55    let text = text.strip_prefix('\u{feff}').unwrap_or(text);
56    // roxmltree refuses entity expansion bombs and never resolves external entities.
57    let options = roxmltree::ParsingOptions { allow_dtd: true, nodes_limit: MAX_XML_NODES, ..Default::default() };
58    let doc = roxmltree::Document::parse_with_options(text, options).map_err(|e| format!("SVG parse: {e}"))?;
59    if doc.root_element().tag_name().name() != "svg" {
60        return Err("not an SVG document".into());
61    }
62    let max_dim = max_dim.clamp(1, MAX_RENDER_DIM);
63    preflight(&doc, layer_limit(max_dim))?;
64    if has_text(&doc) {
65        return Err("SVG contains text".into());
66    }
67
68    let _slot = RenderSlot::take();
69    let embedded = Arc::new(AtomicUsize::new(0));
70    let opts = usvg::Options {
71        resources_dir: None,
72        image_href_resolver: usvg::ImageHrefResolver {
73            resolve_data: Box::new(move |_mime, data, _| embedded_image(data, &embedded)),
74            resolve_string: Box::new(|_, _| None),
75        },
76        ..usvg::Options::default()
77    };
78    let tree = usvg::Tree::from_xmltree(&doc, &opts).map_err(|e| format!("SVG convert: {e}"))?;
79    render(&tree, max_dim)
80}
81
82/// How many canvas-sized layers fit the layer memory at this size (4 at the largest canvas).
83fn layer_limit(max_dim: u32) -> u32 {
84    let canvas = max_dim as u64 * max_dim as u64 * 4;
85    (LAYER_MEMORY_BYTES / canvas.max(1)).clamp(4, MAX_LAYERS as u64) as u32
86}
87
88/// Text needs fonts and a shaper, a megabyte of renderer most SVGs never use, so an SVG with any
89/// is refused like one over budget. Lettering already drawn as outlines is only paths.
90fn has_text(doc: &roxmltree::Document) -> bool {
91    doc.descendants()
92        .filter(|n| n.tag_name().name() == "text")
93        .any(|t| t.descendants().any(|d| d.is_text() && !d.text().unwrap_or("").trim().is_empty()))
94}
95
96/// [`rasterize`], encoded as PNG.
97pub fn rasterize_png(bytes: &[u8], max_dim: u32) -> Result<Vec<u8>, String> {
98    let r = rasterize(bytes, max_dim)?;
99    let img = image::RgbaImage::from_raw(r.width, r.height, r.rgba).ok_or("SVG canvas")?;
100    let mut png = Vec::new();
101    img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| e.to_string())?;
102    Ok(png)
103}
104
105/// Marks an SVG Vector wrote around a render, so a sweep never renders its own output again.
106const RASTER_MARKER: &str = "<!-- vector:raster -->";
107
108/// [`rasterize`], wrapped in a minimal SVG Vector writes itself: one `<image>` holding the rendered
109/// PNG. For a file whose `.svg` path is already stored and must keep working: the webview then
110/// parses markup Vector wrote, never the sender's.
111pub fn rasterize_wrapped(bytes: &[u8], max_dim: u32) -> Result<Vec<u8>, String> {
112    let png = rasterize_png(bytes, max_dim)?;
113    let (w, h) = image::ImageReader::new(std::io::Cursor::new(&png))
114        .with_guessed_format()
115        .map_err(|e| e.to_string())?
116        .into_dimensions()
117        .map_err(|e| e.to_string())?;
118    Ok(wrap_png(&png, w, h))
119}
120
121/// A blank wrapped SVG, for a file that refused to render: it shows nothing rather than the original.
122pub fn empty_wrapped() -> Vec<u8> {
123    format!(r#"{RASTER_MARKER}<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"/>"#).into_bytes()
124}
125
126/// Whether this is an SVG [`rasterize_wrapped`] or [`empty_wrapped`] wrote.
127pub fn is_raster_wrapped(bytes: &[u8]) -> bool {
128    bytes.starts_with(RASTER_MARKER.as_bytes())
129}
130
131/// The PNG inside a render Vector wrapped, or None for anything else (and for an empty one).
132pub fn unwrap_raster(bytes: &[u8]) -> Option<Vec<u8>> {
133    const OPEN: &[u8] = b"href=\"data:image/png;base64,";
134    if !is_raster_wrapped(bytes) {
135        return None;
136    }
137    let start = bytes.windows(OPEN.len()).position(|w| w == OPEN)? + OPEN.len();
138    let len = bytes[start..].iter().position(|&b| b == b'"')?;
139    crate::simd::base64::STANDARD.decode_to_vec(&bytes[start..start + len]).ok()
140}
141
142fn wrap_png(png: &[u8], w: u32, h: u32) -> Vec<u8> {
143    format!(
144        r#"{RASTER_MARKER}<svg xmlns="http://www.w3.org/2000/svg" width="{w}" height="{h}" viewBox="0 0 {w} {h}"><image width="{w}" height="{h}" href="data:image/png;base64,{}"/></svg>"#,
145        crate::simd::base64::STANDARD.encode_to_string(png)
146    )
147    .into_bytes()
148}
149
150/// Whether bytes read as an SVG document: an `<svg` tag near the start, past any BOM, XML
151/// declaration, comments or doctype. Only a routing hint; [`rasterize`] decides.
152pub fn looks_like_svg(bytes: &[u8]) -> bool {
153    if bytes.starts_with(&[0x1f, 0x8b]) {
154        return false;
155    }
156    let head = &bytes[..bytes.len().min(4096)];
157    let text = String::from_utf8_lossy(head);
158    let text = text.trim_start_matches('\u{feff}').trim_start();
159    text.starts_with('<') && text.contains("<svg")
160}
161
162fn render(tree: &usvg::Tree, max_dim: u32) -> Result<Rendered, String> {
163    let size = tree.size();
164    let (w, h) = (size.width(), size.height());
165    if !(w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0) {
166        return Err("SVG has no size".into());
167    }
168    let scale = max_dim as f32 / w.max(h);
169    let pw = ((w * scale).round() as u32).clamp(1, max_dim);
170    let ph = ((h * scale).round() as u32).clamp(1, max_dim);
171    let mut pixmap = tiny_skia::Pixmap::new(pw, ph).ok_or("SVG canvas")?;
172    resvg::render(tree, tiny_skia::Transform::from_scale(pw as f32 / w, ph as f32 / h), &mut pixmap.as_mut());
173    let mut rgba = pixmap.take();
174    for px in rgba.chunks_exact_mut(4) {
175        let a = px[3] as u32;
176        if a != 0 && a != 255 {
177            for c in &mut px[..3] {
178                *c = ((*c as u32 * 255 + a / 2) / a).min(255) as u8;
179            }
180        }
181    }
182    Ok(Rendered { width: pw, height: ph, rgba })
183}
184
185/// An embedded `data:` image, judged by its bytes rather than its declared type: PNG or JPEG
186/// only (never a nested SVG, which would bring its own budget), and dimensions read from the
187/// header before resvg decodes it without a limit.
188fn embedded_image(data: Arc<Vec<u8>>, total: &AtomicUsize) -> Option<usvg::ImageKind> {
189    if data.len() > MAX_EMBEDDED_IMAGE_BYTES
190        || total.fetch_add(data.len(), Ordering::Relaxed) + data.len() > MAX_EMBEDDED_TOTAL_BYTES
191    {
192        return None;
193    }
194    let png = data.starts_with(b"\x89PNG\r\n\x1a\n");
195    if !png && !data.starts_with(&[0xFF, 0xD8, 0xFF]) {
196        return None;
197    }
198    let (w, h) = image::ImageReader::new(std::io::Cursor::new(&data[..]))
199        .with_guessed_format()
200        .ok()?
201        .into_dimensions()
202        .ok()?;
203    if w > MAX_EMBEDDED_DIM || h > MAX_EMBEDDED_DIM {
204        return None;
205    }
206    Some(if png { usvg::ImageKind::PNG(data) } else { usvg::ImageKind::JPEG(data) })
207}
208
209/// At most two renders at once: each is bounded, but a burst of them shouldn't take every core.
210struct RenderSlot;
211
212#[cfg(not(target_arch = "wasm32"))]
213static SLOTS: (std::sync::Mutex<u8>, std::sync::Condvar) = (std::sync::Mutex::new(0), std::sync::Condvar::new());
214
215impl RenderSlot {
216    fn take() -> Self {
217        #[cfg(not(target_arch = "wasm32"))]
218        {
219            let mut busy = SLOTS.0.lock().unwrap_or_else(|e| e.into_inner());
220            while *busy >= 2 {
221                busy = SLOTS.1.wait(busy).unwrap_or_else(|e| e.into_inner());
222            }
223            *busy += 1;
224        }
225        RenderSlot
226    }
227}
228
229impl Drop for RenderSlot {
230    fn drop(&mut self) {
231        #[cfg(not(target_arch = "wasm32"))]
232        {
233            let mut busy = SLOTS.0.lock().unwrap_or_else(|e| e.into_inner());
234            *busy = busy.saturating_sub(1);
235            SLOTS.1.notify_one();
236        }
237    }
238}
239
240// ─── The budget walk ────────────────────────────────────────────────────────
241
242/// Walk the document as rendering would expand it. Every element visited costs one, so the walk
243/// itself is bounded by the budget it enforces, however the references are arranged.
244fn preflight(doc: &roxmltree::Document, max_layers: u32) -> Result<(), String> {
245    // First occurrence wins, as in usvg: a later duplicate id never renders through a reference.
246    let mut ids = HashMap::new();
247    for node in doc.descendants() {
248        if let Some(id) = node.attribute("id") {
249            ids.entry(id).or_insert(node);
250        }
251    }
252    let mut walk = Walk { ids, left: EXPANSION_BUDGET, filters_left: FILTER_BUDGET, max_layers, chain: Vec::new() };
253    walk.visit(doc.root_element(), Inherited::default(), 0, 0, false)?;
254    walk.style_sheets(doc)
255}
256
257/// Paint servers and markers a shape takes from its ancestors (both are inherited properties).
258#[derive(Clone, Copy, Default)]
259struct Inherited<'a, 'i> {
260    fill: Option<Node<'a, 'i>>,
261    stroke: Option<Node<'a, 'i>>,
262    markers: [Option<Node<'a, 'i>>; 3],
263}
264
265struct Walk<'a, 'i> {
266    ids: HashMap<&'a str, Node<'a, 'i>>,
267    left: u64,
268    filters_left: u64,
269    max_layers: u32,
270    /// The references being expanded right now, to refuse a document that reaches itself.
271    chain: Vec<roxmltree::NodeId>,
272}
273
274const SHAPES: &[&str] = &["path", "rect", "circle", "ellipse", "line", "polyline", "polygon", "text"];
275/// Containers that render only through a reference, never where they stand.
276const REFERENCED_ONLY: &[&str] = &[
277    "defs", "symbol", "pattern", "marker", "mask", "clipPath", "linearGradient", "radialGradient",
278    "filter", "style", "script", "title", "desc", "metadata", "foreignObject",
279];
280
281impl<'a, 'i> Walk<'a, 'i> {
282    fn charge(&mut self, n: u64) -> Result<(), String> {
283        if n > self.left {
284            return Err("SVG too complex to render".into());
285        }
286        self.left -= n;
287        Ok(())
288    }
289
290    fn visit(&mut self, node: Node<'a, 'i>, inh: Inherited<'a, 'i>, depth: u32, layers: u32, by_ref: bool) -> Result<(), String> {
291        if !node.is_element() {
292            return Ok(());
293        }
294        self.charge(1)?;
295        if depth > MAX_DEPTH {
296            return Err("SVG nested too deep".into());
297        }
298        let name = node.tag_name().name();
299        if !by_ref && REFERENCED_ONLY.contains(&name) {
300            return Ok(());
301        }
302
303        let inh = self.inherit(node, inh);
304        let mut layers = layers;
305        let isolating = ["mask", "clip-path", "filter"].iter().any(|p| prop(node, p).is_some_and(|v| v.contains("url(")))
306            || prop(node, "opacity").is_some_and(|v| v.trim().parse::<f32>().map_or(true, |o| o < 1.0))
307            || prop(node, "mix-blend-mode").is_some_and(|v| v.trim() != "normal")
308            || prop(node, "isolation").is_some_and(|v| v.trim() == "isolate");
309        if isolating {
310            layers += 1;
311            if layers > self.max_layers {
312                return Err("SVG stacks too many layers".into());
313            }
314        }
315        // Not inherited: each renders its target once, for this element.
316        for p in ["mask", "clip-path"] {
317            if let Some(target) = prop(node, p).and_then(|v| self.url(&v)) {
318                self.enter(target, Inherited::default(), depth, layers)?;
319            }
320        }
321        if let Some(filter) = prop(node, "filter").and_then(|v| self.url(&v)) {
322            self.filter(filter, depth, layers)?;
323        }
324
325        if SHAPES.contains(&name) {
326            for paint in [inh.fill, inh.stroke].into_iter().flatten() {
327                self.enter(paint, Inherited::default(), depth, layers)?;
328            }
329            if matches!(name, "path" | "line" | "polyline" | "polygon") {
330                let vertices = vertices(node);
331                for marker in inh.markers.into_iter().flatten() {
332                    let before = self.left;
333                    self.enter(marker, Inherited::default(), depth, layers)?;
334                    self.charge((before - self.left).saturating_mul(vertices.saturating_sub(1)))?;
335                }
336            }
337        }
338
339        if name == "use" {
340            if let Some(target) = self.href(node) {
341                self.enter(target, inh, depth, layers)?;
342            }
343            return Ok(());
344        }
345        // A referenced container renders its children; `<symbol>` too, through `<use>`.
346        for child in node.children() {
347            self.visit(child, inh, depth + 1, layers, false)?;
348        }
349        Ok(())
350    }
351
352    /// Render a referenced element once: its own subtree, or a pattern's (template-inherited) tiles.
353    fn enter(&mut self, target: Node<'a, 'i>, inh: Inherited<'a, 'i>, depth: u32, layers: u32) -> Result<(), String> {
354        if self.chain.contains(&target.id()) {
355            return Err("SVG references itself".into());
356        }
357        self.chain.push(target.id());
358        let target = if target.tag_name().name() == "pattern" { self.pattern_content(target) } else { target };
359        let result = self.visit(target, inh, depth + 1, layers, true);
360        self.chain.pop();
361        result
362    }
363
364    /// A pattern without children of its own draws its `href` template's.
365    fn pattern_content(&self, mut pattern: Node<'a, 'i>) -> Node<'a, 'i> {
366        for _ in 0..16 {
367            if pattern.children().any(|c| c.is_element()) {
368                break;
369            }
370            match self.href(pattern) {
371                Some(next) if next.tag_name().name() == "pattern" => pattern = next,
372                _ => break,
373            }
374        }
375        pattern
376    }
377
378    fn filter(&mut self, filter: Node<'a, 'i>, depth: u32, layers: u32) -> Result<(), String> {
379        for primitive in filter.children().filter(|c| c.is_element()) {
380            if self.filters_left == 0 {
381                return Err("SVG applies too many filters".into());
382            }
383            self.filters_left -= 1;
384            self.charge(1)?;
385            if primitive.tag_name().name() == "feImage" {
386                if let Some(target) = self.href(primitive) {
387                    self.enter(target, Inherited::default(), depth, layers)?;
388                }
389            }
390        }
391        Ok(())
392    }
393
394    /// Stylesheets can paint any element, so a reference made there is charged once per shape.
395    fn style_sheets(&mut self, doc: &'a roxmltree::Document<'i>) -> Result<(), String> {
396        let shapes = doc.descendants().filter(|n| SHAPES.contains(&n.tag_name().name())).count() as u64;
397        for sheet in doc.descendants().filter(|n| n.has_tag_name("style")) {
398            let Some(css) = sheet.text() else { continue };
399            let mut rest = css;
400            while let Some(at) = rest.find("url(") {
401                rest = &rest[at + 4..];
402                let Some(target) = self.url(&format!("url({rest}")) else { continue };
403                if !matches!(target.tag_name().name(), "pattern" | "marker" | "mask" | "clipPath" | "filter") {
404                    continue;
405                }
406                let before = self.left;
407                if target.tag_name().name() == "filter" {
408                    self.filter(target, 0, 0)?;
409                } else {
410                    self.enter(target, Inherited::default(), 0, 0)?;
411                }
412                self.charge((before - self.left).saturating_mul(shapes.saturating_sub(1)))?;
413            }
414        }
415        Ok(())
416    }
417
418    fn inherit(&self, node: Node<'a, 'i>, mut inh: Inherited<'a, 'i>) -> Inherited<'a, 'i> {
419        let paint = |value: Option<String>, current: Option<Node<'a, 'i>>| match value {
420            None => current,
421            Some(v) if v.trim() == "inherit" => current,
422            Some(v) => self.url(&v).filter(|t| t.tag_name().name() == "pattern"),
423        };
424        inh.fill = paint(prop(node, "fill"), inh.fill);
425        inh.stroke = paint(prop(node, "stroke"), inh.stroke);
426        let marker = |value: Option<String>, current: Option<Node<'a, 'i>>| match value {
427            None => current,
428            Some(v) if v.trim() == "inherit" => current,
429            Some(v) => self.url(&v).filter(|t| t.tag_name().name() == "marker"),
430        };
431        if let Some(all) = prop(node, "marker") {
432            inh.markers = [marker(Some(all.clone()), None), marker(Some(all.clone()), None), marker(Some(all), None)];
433        }
434        for (i, p) in ["marker-start", "marker-mid", "marker-end"].into_iter().enumerate() {
435            inh.markers[i] = marker(prop(node, p), inh.markers[i]);
436        }
437        inh
438    }
439
440    /// `href` before `xlink:href`, as usvg resolves them.
441    fn href(&self, node: Node<'a, 'i>) -> Option<Node<'a, 'i>> {
442        let value = node
443            .attributes()
444            .find(|a| a.name() == "href" && a.namespace().is_none())
445            .or_else(|| node.attributes().find(|a| a.name() == "href" && a.namespace() == Some("http://www.w3.org/1999/xlink")))?
446            .value();
447        self.ids.get(value.trim().strip_prefix('#')?).copied()
448    }
449
450    /// The element a `url(#id)` value names.
451    fn url(&self, value: &str) -> Option<Node<'a, 'i>> {
452        let start = value.find("url(")? + 4;
453        let inner = &value[start..];
454        let inner = &inner[..inner.find(')')?];
455        let id = inner.trim().trim_matches(|c| c == '"' || c == '\'').trim().strip_prefix('#')?;
456        self.ids.get(id).copied()
457    }
458}
459
460/// A property from the `style` attribute (which wins) or the presentation attribute.
461fn prop(node: Node, name: &str) -> Option<String> {
462    if let Some(style) = node.attribute("style") {
463        let mut found = None;
464        for decl in style.split(';') {
465            if let Some((k, v)) = decl.split_once(':') {
466                if k.trim() == name {
467                    found = Some(v.trim().trim_end_matches("!important").trim().to_string());
468                }
469            }
470        }
471        if found.is_some() {
472            return found;
473        }
474    }
475    node.attribute(name).map(str::to_string)
476}
477
478/// An upper bound on a shape's vertices, from how many numbers its geometry holds.
479fn vertices(node: Node) -> u64 {
480    let data = match node.tag_name().name() {
481        "path" => node.attribute("d"),
482        "polyline" | "polygon" => node.attribute("points"),
483        _ => return 2,
484    };
485    let mut numbers = 0u64;
486    let mut in_number = false;
487    for c in data.unwrap_or("").chars() {
488        let digit = c.is_ascii_digit();
489        if digit && !in_number {
490            numbers += 1;
491        }
492        in_number = digit || (in_number && matches!(c, '.' | 'e' | 'E'));
493    }
494    numbers / 2 + 1
495}
496
497#[cfg(test)]
498mod tests {
499    use super::*;
500
501    fn pixel(r: &Rendered, x: u32, y: u32) -> [u8; 4] {
502        let i = ((y * r.width + x) * 4) as usize;
503        [r.rgba[i], r.rgba[i + 1], r.rgba[i + 2], r.rgba[i + 3]]
504    }
505
506    #[test]
507    fn text_is_refused_but_empty_text_and_outlines_render() {
508        let text = br##"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="40"><g><text x="5" y="30"><tspan>Hi</tspan></text></g></svg>"##;
509        assert_eq!(rasterize(text, 100).err().as_deref(), Some("SVG contains text"));
510        let empty = br##"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><text x="1" y="1">  </text><rect width="10" height="10"/></svg>"##;
511        assert!(rasterize(empty, 10).is_ok());
512    }
513
514    #[test]
515    fn recognises_svg_documents_only() {
516        assert!(looks_like_svg(b"<svg xmlns='http://www.w3.org/2000/svg'/>"));
517        assert!(looks_like_svg(b"\xef\xbb\xbf  <?xml version='1.0'?>\n<!-- logo -->\n<!DOCTYPE svg><svg/>"));
518        assert!(!looks_like_svg(b"<?xml version='1.0'?><plist/>"));
519        assert!(!looks_like_svg(b"\x89PNG\r\n\x1a\n"));
520        let png = rasterize_png(br##"<svg xmlns="http://www.w3.org/2000/svg" width="4" height="4"><rect width="4" height="4"/></svg>"##, 8).unwrap();
521        assert!(png.starts_with(b"\x89PNG"));
522    }
523
524    #[test]
525    fn a_wrapped_render_is_ours_and_renders_back_the_same() {
526        let svg = br##"<svg xmlns="http://www.w3.org/2000/svg" width="20" height="10"><rect width="20" height="10" fill="#00ff00"/></svg>"##;
527        let wrapped = rasterize_wrapped(svg, 40).unwrap();
528        assert!(is_raster_wrapped(&wrapped) && !is_raster_wrapped(svg));
529        assert!(looks_like_svg(&wrapped), "still a valid .svg for paths that stored one");
530        // Rendering the wrapper again gives the same picture: one image, nothing to expand.
531        let again = rasterize(&wrapped, 40).unwrap();
532        assert_eq!((again.width, again.height), (40, 20));
533        assert_eq!(pixel(&again, 20, 10), [0, 255, 0, 255]);
534        assert!(is_raster_wrapped(&empty_wrapped()) && rasterize(&empty_wrapped(), 4).is_ok());
535    }
536
537    #[test]
538    fn renders_a_plain_svg_to_its_longest_side() {
539        let svg = br##"<svg xmlns="http://www.w3.org/2000/svg" width="20" height="10"><rect width="20" height="10" fill="#ff0000"/></svg>"##;
540        let r = rasterize(svg, 200).unwrap();
541        assert_eq!((r.width, r.height), (200, 100));
542        assert_eq!(pixel(&r, 100, 50), [255, 0, 0, 255]);
543    }
544
545    #[test]
546    fn scripts_and_foreign_content_never_render() {
547        let svg = br##"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" onload="alert(1)">
548            <script>alert(1)</script>
549            <foreignObject width="10" height="10"><div xmlns="http://www.w3.org/1999/xhtml" style="background:red;width:10px;height:10px"></div></foreignObject>
550        </svg>"##;
551        let r = rasterize(svg, 10).unwrap();
552        assert_eq!(pixel(&r, 5, 5)[3], 0, "nothing but pixels comes out, and these are empty");
553    }
554
555    #[test]
556    fn refuses_what_a_renderer_should_never_see() {
557        assert!(rasterize(&[0x1f, 0x8b, 8, 0], 64).is_err(), "SVGZ is never inflated");
558        assert!(rasterize(&[0xff, 0xfe, 0x3c, 0], 64).is_err(), "not UTF-8");
559        assert!(rasterize(b"<html><body/></html>", 64).is_err(), "not an <svg> root");
560        assert!(rasterize(&vec![b' '; MAX_SVG_BYTES + 1], 64).is_err(), "oversized");
561    }
562
563    #[test]
564    fn files_and_remote_urls_are_never_read() {
565        // A real image on disk: the renderer must not pull it into the picture.
566        let dir = std::env::temp_dir().join(format!("vector-svg-{}", std::process::id()));
567        std::fs::create_dir_all(&dir).unwrap();
568        let png = dir.join("secret.png");
569        image::RgbaImage::from_pixel(4, 4, image::Rgba([0, 255, 0, 255])).save(&png).unwrap();
570        let svg = format!(
571            r#"<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="4" height="4">
572                <image width="4" height="4" href="{p}"/><image width="4" height="4" xlink:href="file://{p}"/>
573                <image width="4" height="4" href="https://example.com/x.png"/></svg>"#,
574            p = png.display()
575        );
576        let r = rasterize(svg.as_bytes(), 4).unwrap();
577        let _ = std::fs::remove_dir_all(&dir);
578        assert_eq!(pixel(&r, 2, 2)[3], 0);
579    }
580
581    #[test]
582    fn embedded_images_are_raster_and_bounded() {
583        let mut png = Vec::new();
584        image::RgbaImage::from_pixel(2, 2, image::Rgba([0, 0, 255, 255]))
585            .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
586            .unwrap();
587        let b64 = crate::simd::base64::STANDARD.encode_to_string(&png);
588        let ok = format!(r#"<svg xmlns="http://www.w3.org/2000/svg" width="2" height="2"><image width="2" height="2" href="data:image/png;base64,{b64}"/></svg>"#);
589        assert_eq!(pixel(&rasterize(ok.as_bytes(), 2).unwrap(), 1, 1), [0, 0, 255, 255]);
590
591        // A nested SVG would bring its own document past the budget: never decoded.
592        let inner = crate::simd::base64::STANDARD.encode_to_string(br##"<svg xmlns="http://www.w3.org/2000/svg" width="2" height="2"><rect width="2" height="2" fill="#00ff00"/></svg>"##);
593        let nested = format!(r#"<svg xmlns="http://www.w3.org/2000/svg" width="2" height="2"><image width="2" height="2" href="data:image/svg+xml;base64,{inner}"/></svg>"#);
594        assert_eq!(pixel(&rasterize(nested.as_bytes(), 2).unwrap(), 1, 1)[3], 0);
595
596        // Past the dimension cap the header alone refuses it, before anything decodes it.
597        let mut wide = Vec::new();
598        image::RgbaImage::from_pixel(MAX_EMBEDDED_DIM + 1, 1, image::Rgba([0, 0, 0, 255]))
599            .write_to(&mut std::io::Cursor::new(&mut wide), image::ImageFormat::Png)
600            .unwrap();
601        assert!(embedded_image(Arc::new(wide), &AtomicUsize::new(0)).is_none());
602        assert!(embedded_image(Arc::new(png), &AtomicUsize::new(0)).is_some());
603    }
604
605    #[test]
606    fn entity_tricks_are_refused_or_inert() {
607        let laughs = br#"<?xml version="1.0"?><!DOCTYPE svg [<!ENTITY a "aaaaaaaaaa"><!ENTITY b "&a;&a;&a;&a;&a;&a;&a;&a;&a;&a;"><!ENTITY c "&b;&b;&b;&b;&b;&b;&b;&b;&b;&b;"><!ENTITY d "&c;&c;&c;&c;&c;&c;&c;&c;&c;&c;"><!ENTITY e "&d;&d;&d;&d;&d;&d;&d;&d;&d;&d;"><!ENTITY f "&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;"><!ENTITY g "&f;&f;&f;&f;&f;&f;&f;&f;&f;&f;">]><svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"><text>&g;</text></svg>"#;
608        assert!(rasterize(laughs, 8).is_err(), "exponential entities");
609        // An external entity is never fetched: the document fails to parse rather than read the file.
610        let xxe = br#"<?xml version="1.0"?><!DOCTYPE svg [<!ENTITY x SYSTEM "file:///etc/hosts">]><svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"><text>&x;</text></svg>"#;
611        assert!(rasterize(xxe, 8).is_err());
612    }
613
614    #[test]
615    fn a_use_bomb_is_refused() {
616        // Ten references per level, six levels: a million elements from a few hundred bytes.
617        let mut svg = String::from(r#"<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="10" height="10"><defs><rect id="l0" width="1" height="1"/>"#);
618        for level in 1..=6 {
619            svg += &format!(r#"<g id="l{level}">"#);
620            for _ in 0..10 {
621                svg += &format!(r##"<use xlink:href="#l{}"/>"##, level - 1);
622            }
623            svg += "</g>";
624        }
625        svg += r##"</defs><use xlink:href="#l6"/></svg>"##;
626        assert_eq!(rasterize(svg.as_bytes(), 10).err().as_deref(), Some("SVG too complex to render"));
627    }
628
629    #[test]
630    fn inherited_pattern_paint_is_charged_per_shape() {
631        // One fill on a group, a heavy pattern, and many shapes inheriting it.
632        let mut svg = String::from(r#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><defs><pattern id="p" width="1" height="1">"#);
633        svg += &"<rect width=\"1\" height=\"1\"/>".repeat(500);
634        svg += r##"</pattern></defs><g fill="url(#p)">"##;
635        svg += &"<rect width=\"1\" height=\"1\"/>".repeat(500);
636        svg += "</g></svg>";
637        assert_eq!(rasterize(svg.as_bytes(), 10).err().as_deref(), Some("SVG too complex to render"));
638    }
639
640    #[test]
641    fn markers_are_charged_per_vertex() {
642        let mut svg = String::from(r#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><defs><marker id="m">"#);
643        svg += &"<circle r=\"1\"/>".repeat(50);
644        svg += r##"</marker></defs><path marker-mid="url(#m)" d="M0 0"##;
645        svg += &" L1 1".repeat(5000);
646        svg += r#""/></svg>"#;
647        assert_eq!(rasterize(svg.as_bytes(), 10).err().as_deref(), Some("SVG too complex to render"));
648    }
649
650    #[test]
651    fn stylesheet_references_are_charged_per_shape() {
652        let mut svg = String::from(r##"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><style>rect { fill: url(#p) }</style><defs><pattern id="p" width="1" height="1">"##);
653        svg += &"<circle r=\"1\"/>".repeat(400);
654        svg += "</pattern></defs>";
655        svg += &"<rect width=\"1\" height=\"1\"/>".repeat(400);
656        svg += "</svg>";
657        assert!(rasterize(svg.as_bytes(), 10).is_err());
658    }
659
660    #[test]
661    fn a_larger_canvas_allows_fewer_layers() {
662        assert_eq!(layer_limit(1024), MAX_LAYERS);
663        assert_eq!(layer_limit(MAX_RENDER_DIM), 4);
664        let five = format!(
665            r#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10">{}<rect width="1" height="1"/>{}</svg>"#,
666            r#"<g opacity="0.5">"#.repeat(5),
667            "</g>".repeat(5)
668        );
669        assert!(rasterize(five.as_bytes(), 1024).is_ok());
670        assert_eq!(rasterize(five.as_bytes(), MAX_RENDER_DIM).err().as_deref(), Some("SVG stacks too many layers"));
671    }
672
673    #[test]
674    fn stacked_layers_and_cycles_are_refused() {
675        let deep = format!(
676            r#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10">{}<rect width="1" height="1"/>{}</svg>"#,
677            r#"<g opacity="0.5">"#.repeat(MAX_LAYERS as usize + 1),
678            "</g>".repeat(MAX_LAYERS as usize + 1)
679        );
680        assert_eq!(rasterize(deep.as_bytes(), 10).err().as_deref(), Some("SVG stacks too many layers"));
681
682        let cycle = br##"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><g id="a"><use href="#b"/></g><g id="b"><use href="#c"/></g><g id="c"><use href="#a"/></g></svg>"##;
683        assert_eq!(rasterize(cycle, 10).err().as_deref(), Some("SVG references itself"));
684    }
685
686    #[test]
687    fn a_duplicate_id_resolves_to_the_first_as_usvg_does() {
688        // The heavy element shares an id with a cheap one that comes first: nothing references it.
689        let mut svg = String::from(r##"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><defs><g id="x"><rect width="1" height="1"/></g><g id="x">"##);
690        svg += &"<rect width=\"1\" height=\"1\"/>".repeat(2000);
691        svg += "</g></defs>";
692        svg += &r##"<use href="#x"/>"##.repeat(100);
693        svg += "</svg>";
694        assert!(rasterize(svg.as_bytes(), 10).is_ok());
695    }
696}