M6: svg import drops the scanners craft-svg replaced, so main builds and passes fmt again (#2468)

#2468 moved SVG import onto craft_svg::tree::parse, which runs the size,
entity, attribute and nesting checks itself, but left FigCraft's own
scanners (too_wide, too_deep, nesting) and import/budget.rs unused and
import.rs unformatted: main failed cargo fmt, clippy -D warnings and the
svg tests, which still passed budget::Limits to import_within.

The dead code goes; budget_tests use craft-svg's tree::Limits (bytes,
embedded_bytes, embedded_depth) and its error texts, and hostile_tests
check attribute width with craft_svg::guard::too_wide at the default
limits and the nesting refusal at craft-svg's 256 levels.
This commit is contained in:
bflatastic
2026-11-19 06:00:08 +07:00
parent f8b1dc7373
commit fb21b3c389
6 changed files with 20 additions and 284 deletions
+1 -141
View File
@@ -18,7 +18,6 @@
use craft_svg::tree::{self, usvg};
mod budget;
mod css_color;
mod fx;
mod paint;
@@ -703,137 +702,6 @@ fn simple_hash(b: &[u8]) -> String {
format!("{h1:016x}{h2:016x}")
}
/// Deepest element nesting the parser is given: deeper documents would exhaust the stack.
const MAX_NESTING: usize = 512;
/// The most attributes one element may have. The XML parser checks each attribute against the
/// earlier ones, so a huge count is quadratic work; real elements have a few dozen at most.
const MAX_ATTRIBUTES: usize = 4096;
/// How deep elements nest in `data`: a scan of its tags (comments, CDATA, declarations and quoted
/// attribute values skipped) that stops once past `limit`.
pub(crate) fn nesting(data: &[u8], limit: usize) -> usize {
scan(data, limit).0
}
/// The most the parser's duplicate-attribute checks may cost over a whole document, as the sum of
/// each element's attribute count squared (a real file with 100,000 elements of 20 attributes is
/// 40 million).
const MAX_ATTRIBUTE_WORK: usize = 1 << 28;
/// Whether an element of `data` has more than [`MAX_ATTRIBUTES`] attributes, or all of them cost
/// more than [`MAX_ATTRIBUTE_WORK`] (counted as quoted values, before the parser sees them; the
/// declarations of a DTD count as one element, as entities can hold elements).
pub(crate) fn too_wide(data: &[u8]) -> bool {
let (_, widest, work) = scan(data, usize::MAX);
widest > MAX_ATTRIBUTES || work > MAX_ATTRIBUTE_WORK
}
/// [`nesting`], the most attribute values on one element and the attribute work (see
/// [`MAX_ATTRIBUTE_WORK`]); stops once any is past its limit.
fn scan(data: &[u8], limit: usize) -> (usize, usize, usize) {
let find = |from: usize, pat: &[u8]| -> usize {
data.get(from..).and_then(|r| r.windows(pat.len()).position(|w| w == pat)).map_or(data.len(), |p| from + p + pat.len())
};
let (mut depth, mut max, mut i, mut widest, mut work) = (0usize, 0usize, 0usize, 0usize, 0usize);
while let Some(off) = data.get(i..).and_then(|r| r.iter().position(|b| *b == b'<')) {
i += off;
let rest = data.get(i..).unwrap_or(&[]);
if rest.starts_with(b"<!--") {
i = find(i + 4, b"-->");
} else if rest.starts_with(b"<![CDATA[") {
i = find(i + 9, b"]]>");
} else if rest.starts_with(b"<!DOCTYPE") {
// To the `]>` closing its subset (the first `>` when it has none).
let end = match (rest.iter().position(|b| *b == b'['), rest.iter().position(|b| *b == b'>')) {
(Some(o), Some(g)) if o < g => find(i, b"]>"),
_ => find(i, b">"),
};
let quotes = data.get(i..end).unwrap_or(&[]).iter().filter(|b| matches!(**b, b'"' | b'\'')).count();
widest = widest.max(quotes / 2);
work = work.saturating_add((quotes / 2).saturating_mul(quotes / 2));
if widest > MAX_ATTRIBUTES || work > MAX_ATTRIBUTE_WORK {
return (max, widest, work);
}
i = end;
} else if rest.starts_with(b"<?") || rest.starts_with(b"<!") {
i = find(i + 2, b">");
} else if rest.starts_with(b"</") {
depth = depth.saturating_sub(1);
i = find(i + 2, b">");
} else {
// A start tag: to its `>` outside quotes; `/>` closes it.
let (mut quote, mut j, mut closed, mut attrs) = (None, i + 1, false, 0usize);
while let Some(&c) = data.get(j) {
match quote {
Some(q) if c == q => quote = None,
Some(_) => {}
None if c == b'"' || c == b'\'' => {
quote = Some(c);
attrs += 1;
}
None if c == b'>' => {
closed = data.get(j.wrapping_sub(1)) == Some(&b'/');
break;
}
None => {}
}
j += 1;
}
widest = widest.max(attrs);
work = work.saturating_add(attrs * attrs);
if widest > MAX_ATTRIBUTES || work > MAX_ATTRIBUTE_WORK {
return (max, widest, work);
}
if !closed {
depth += 1;
max = max.max(depth);
if max > limit {
return (max, widest, work);
}
}
i = j + 1;
}
}
(max, widest, work)
}
/// Whether `data` nests elements more than [`MAX_NESTING`] deep: the byte scan first, then the
/// parsed tree (walked without recursion), which also counts what DTD entity references expand to.
pub(crate) fn too_deep(data: &[u8]) -> bool {
if nesting(data, MAX_NESTING) > MAX_NESTING {
return true;
}
let Ok(text) = std::str::from_utf8(data) else { return false };
let opt = usvg::roxmltree::ParsingOptions { allow_dtd: true, ..Default::default() };
let Ok(xml) = usvg::roxmltree::Document::parse_with_options(text, opt) else { return false };
// Depth-first by sibling and parent links; the root is depth 0, each child one deeper.
let (mut node, mut depth) = (xml.root(), 0usize);
loop {
if let Some(child) = node.first_child() {
node = child;
depth += 1;
if depth > MAX_NESTING {
return true;
}
continue;
}
loop {
if let Some(next) = node.next_sibling() {
node = next;
break;
}
match node.parent() {
Some(up) if depth > 0 => {
node = up;
depth -= 1;
}
_ => return false,
}
}
}
}
fn options(data: &[u8], limits: tree::Limits) -> usvg::Options<'static> {
// Only data URIs, within budgets: an opened or pasted SVG never pulls other files off the disk
// and never expands without limit.
@@ -918,15 +786,7 @@ pub fn import_svg_with_notes(doc: &mut Document, data: &[u8], parent: NodeId, x:
import_within(doc, data, parent, x, y, name, tree::Limits::default())
}
fn import_within(
doc: &mut Document,
data: &[u8],
parent: NodeId,
x: f64,
y: f64,
name: &str,
limits: tree::Limits,
) -> Result<Imported, ImportError> {
fn import_within(doc: &mut Document, data: &[u8], parent: NodeId, x: f64, y: f64, name: &str, limits: tree::Limits) -> Result<Imported, ImportError> {
// SVGZ is unpacked here, within a budget, so every check below sees the real document.
let text = craft_svg::svgz::text(data, limits.bytes).map_err(|e| ImportError(e.to_string()))?;
// usvg reads neither `color()` nor `color-mix()`: they are resolved first.
-121
View File
@@ -1,121 +0,0 @@
//! Resource budgets for what an SVG expands into while it is parsed: compressed (SVGZ) input,
//! and SVG documents embedded in `<image>` data URIs (themselves possibly compressed or nested).
//! usvg decompresses with no cap and parses embedded SVGs with no shared depth or byte limit, so
//! both are done here: a bounded gunzip before usvg sees the bytes, and our own data resolver.
use std::io::Read;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use usvg::{ImageHrefResolver, ImageKind, Options};
/// Largest document, once decompressed.
const MAX_DOCUMENT_BYTES: usize = 64 << 20;
/// Largest total of all embedded SVG documents, once decompressed.
const MAX_EMBEDDED_BYTES: usize = 32 << 20;
/// Most SVG documents embedded inside one another.
const MAX_EMBEDDED_DEPTH: usize = 4;
#[derive(Clone, Copy)]
pub(super) struct Limits {
pub document: usize,
pub embedded: usize,
pub depth: usize,
}
impl Default for Limits {
fn default() -> Self {
Limits { document: MAX_DOCUMENT_BYTES, embedded: MAX_EMBEDDED_BYTES, depth: MAX_EMBEDDED_DEPTH }
}
}
fn gzipped(data: &[u8]) -> bool {
data.starts_with(&[0x1f, 0x8b])
}
/// `data` as plain text bytes: gunzipped when compressed, never past `limit` bytes.
fn inflate(data: &[u8], limit: usize) -> Result<Vec<u8>, String> {
if !gzipped(data) {
return if data.len() > limit { Err(format!("SVG larger than {} MiB", limit >> 20)) } else { Ok(data.to_vec()) };
}
let mut out = Vec::new();
let cap = u64::try_from(limit).unwrap_or(u64::MAX).saturating_add(1);
flate2::read::GzDecoder::new(data).take(cap).read_to_end(&mut out).map_err(|_| "malformed compressed SVG".to_string())?;
if out.len() > limit {
return Err(format!("compressed SVG expands past {} MiB", limit >> 20));
}
// usvg gunzips what it is handed, with no limit: one layer is unpacked here, within the
// budget, and what comes out must be the document itself.
if gzipped(&out) {
return Err("compressed SVG holds another compressed file, not a document".into());
}
Ok(out)
}
/// The document `data` (SVG or SVGZ) as plain bytes, within the document budget.
pub(super) fn document(data: &[u8], limits: &Limits) -> Result<Vec<u8>, String> {
// The caller already holds a plain document; only what compression expands to is bounded.
if gzipped(data) { inflate(data, limits.document) } else { Ok(data.to_vec()) }
}
/// What the embedded SVGs of one import have used so far.
struct Used {
bytes: AtomicUsize,
depth: AtomicUsize,
}
fn raster(data: &[u8]) -> bool {
data.starts_with(b"\x89PNG")
|| data.starts_with(&[0xff, 0xd8, 0xff])
|| data.starts_with(b"GIF8")
|| (data.len() > 12 && data.get(8..12) == Some(b"WEBP"))
}
/// An embedded SVG document, if the budgets allow it.
fn embedded(used: &Used, limits: &Limits, data: &[u8], opts: &Options) -> Option<ImageKind> {
if used.depth.load(Ordering::Relaxed) >= limits.depth {
return None;
}
let left = limits.embedded.saturating_sub(used.bytes.load(Ordering::Relaxed));
let plain = match inflate(data, left) {
Ok(plain) => plain,
// What a refused document unpacked before it was refused was work too: it uses up what is
// left, so the next image can't repeat it.
Err(_) => {
used.bytes.fetch_add(left, Ordering::Relaxed);
return None;
}
};
used.bytes.fetch_add(plain.len(), Ordering::Relaxed);
if super::too_wide(&plain) || super::too_deep(&plain) {
return None;
}
used.depth.fetch_add(1, Ordering::Relaxed);
let tree = usvg::Tree::from_data_nested(&plain, opts);
used.depth.fetch_sub(1, Ordering::Relaxed);
tree.ok().map(ImageKind::SVG)
}
/// Resolve `<image>` data URIs: rasters as they are, SVGs within `limits`; nothing else.
pub(super) fn resolver(limits: Limits) -> ImageHrefResolver<'static> {
let used = Arc::new(Used { bytes: AtomicUsize::new(0), depth: AtomicUsize::new(0) });
ImageHrefResolver {
resolve_data: Box::new(move |mime, data, opts| match mime {
"image/jpg" | "image/jpeg" => Some(ImageKind::JPEG(data)),
"image/png" => Some(ImageKind::PNG(data)),
"image/gif" => Some(ImageKind::GIF(data)),
"image/webp" => Some(ImageKind::WEBP(data)),
"image/svg+xml" => embedded(&used, &limits, &data, opts),
"text/plain" if raster(&data) => match data.first() {
Some(0x89) => Some(ImageKind::PNG(data)),
Some(0xff) => Some(ImageKind::JPEG(data)),
Some(b'G') => Some(ImageKind::GIF(data)),
_ => Some(ImageKind::WEBP(data)),
},
"text/plain" => embedded(&used, &limits, &data, opts),
_ => None,
}),
// Linked files are never read.
resolve_string: Box::new(|_, _| None),
}
}
+9 -9
View File
@@ -6,8 +6,8 @@ use std::io::Write;
use base64::Engine as _;
use figcraft_doc::Document;
use super::budget::Limits;
use super::{import_svg, import_within};
use craft_svg::tree::Limits;
fn gzip(data: &[u8]) -> Vec<u8> {
let mut e = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
@@ -51,14 +51,14 @@ fn an_svgz_is_unpacked_and_imported() {
#[test]
fn an_svgz_that_expands_past_the_budget_is_refused_early() {
let limits = Limits { document: 4096, ..Limits::default() };
let limits = Limits { bytes: 4096, ..Limits::default() };
// Tiny compressed, far past 4 KiB expanded.
let z = gzip(svg(&" ".repeat(1 << 20)).as_bytes());
assert!(z.len() < 4096, "the bomb is small: {}", z.len());
let e = layers(&z, limits).unwrap_err();
assert!(e.contains("expands past"), "{e}");
assert!(e.contains("larger than the 4096 byte limit"), "{e}");
// The same document is fine within a bigger budget.
assert!(layers(&z, Limits { document: 2 << 20, ..Limits::default() }).is_ok());
assert!(layers(&z, Limits { bytes: 2 << 20, ..Limits::default() }).is_ok());
}
#[test]
@@ -72,7 +72,7 @@ fn a_compressed_document_is_checked_for_nesting_once_unpacked() {
fn embedded_svgs_nest_up_to_the_depth_budget_and_no_further() {
let data = nested(4).into_bytes();
let full = layers(&data, Limits::default()).unwrap();
let shallow = layers(&data, Limits { depth: 1, ..Limits::default() }).unwrap();
let shallow = layers(&data, Limits { embedded_depth: 1, ..Limits::default() }).unwrap();
assert!(shallow < full, "depth 1 drops the inner documents: {shallow} < {full}");
// Far deeper than the budget: still imports, bounded.
let deep = nested(40).into_bytes();
@@ -85,7 +85,7 @@ fn embedded_svgs_share_one_byte_budget() {
let one = format!(r##"<image width="10" height="10" xlink:href="{}"/>"##, uri(inner.as_bytes()));
let data = svg(&one.repeat(8)).into_bytes();
let all = layers(&data, Limits::default()).unwrap();
let limits = Limits { embedded: inner.len() * 3, ..Limits::default() };
let limits = Limits { embedded_bytes: inner.len() * 3, ..Limits::default() };
let some = layers(&data, limits).unwrap();
assert!(some < all, "the budget runs out part way: {some} < {all}");
}
@@ -98,7 +98,7 @@ fn an_embedded_compressed_bomb_is_dropped_not_expanded() {
base64::engine::general_purpose::STANDARD.encode(&bomb)
))
.into_bytes();
let limits = Limits { embedded: 4096, ..Limits::default() };
let limits = Limits { embedded_bytes: 4096, ..Limits::default() };
let with_bomb = layers(&data, limits).unwrap();
let empty = layers(svg("").as_bytes(), limits).unwrap();
assert_eq!(with_bomb, empty, "the oversized embedded document left nothing behind");
@@ -116,7 +116,7 @@ fn linked_files_and_other_mime_types_stay_unresolved() {
fn a_document_compressed_twice_is_refused_not_unpacked_again() {
// One gzip layer is unpacked within the budget; usvg would unpack a second one without any.
let twice = gzip(&gzip(svg(&" ".repeat(1 << 20)).as_bytes()));
let e = layers(&twice, Limits { document: 4 << 20, ..Limits::default() }).unwrap_err();
let e = layers(&twice, Limits { bytes: 4 << 20, ..Limits::default() }).unwrap_err();
assert!(e.contains("another compressed file"), "{e}");
// Embedded, the same is dropped.
let inner = svg(r##"<rect width="10" height="10"/>"##);
@@ -135,7 +135,7 @@ fn a_refused_embedded_bomb_uses_up_the_budget_for_the_images_after_it() {
let image = |href: String| format!(r##"<image width="10" height="10" xlink:href="{href}"/>"##);
let bomb_uri = format!("data:image/svg+xml;base64,{}", base64::engine::general_purpose::STANDARD.encode(&bomb));
let data = svg(&format!("{}{}", image(bomb_uri).repeat(8), image(uri(inner.as_bytes())))).into_bytes();
let limits = Limits { embedded: 4096, ..Limits::default() };
let limits = Limits { embedded_bytes: 4096, ..Limits::default() };
let empty = layers(svg("").as_bytes(), limits).unwrap();
assert_eq!(layers(&data, limits).unwrap(), empty, "the first bomb spends the allowance; nothing after it unpacks");
}
+6 -10
View File
@@ -154,14 +154,8 @@ fn the_corpus_mangled_byte_by_byte() {
}
#[test]
fn nesting_is_measured_before_parsing() {
use super::nesting;
assert_eq!(nesting(b"<svg><g><g/><g a='>' b=\"/>\"></g></g></svg>", 99), 3);
assert_eq!(nesting(b"<?xml version='1.0'?><!-- <g><g> --><svg><![CDATA[<g><g>]]></svg>", 99), 1);
assert_eq!(nesting(b"<svg><g", 99), 2);
fn far_too_deep_a_document_is_refused() {
let deep = format!("{}{}", "<g>".repeat(5000), "</g>".repeat(5000));
assert_eq!(nesting(deep.as_bytes(), 512), 513, "stops once past the limit");
// Far too deep for the parser's stack: refused.
let mut d = Document::new("t");
let p = d.first_page().unwrap();
assert!(import_svg(&mut d, &svg(&deep), p, 0.0, 0.0, "x").is_err());
@@ -179,12 +173,13 @@ fn entity_expansion_cannot_bypass_the_nesting_limit() {
let mut d = Document::new("t");
let p = d.first_page().unwrap();
let err = import_svg(&mut d, data.as_bytes(), p, 0.0, 0.0, "x").err().map(|e| e.to_string()).unwrap_or_default();
assert!(err.contains("nested more than 512 deep"), "{err:?}");
assert!(err.contains("nested more than 256 levels deep"), "{err:?}");
}
#[test]
fn an_element_with_thousands_of_attributes_is_refused_before_parsing() {
use super::too_wide;
let l = craft_svg::tree::Limits::default();
let too_wide = |s: &[u8]| craft_svg::guard::too_wide(std::str::from_utf8(s).unwrap(), l.attributes, l.attribute_work);
let many = |n: usize| (0..n).map(|i| format!(" a{i}=\"1\"")).collect::<String>();
assert!(!too_wide(format!("<svg{}/>", many(4096)).as_bytes()));
assert!(too_wide(format!("<svg><g{}/></svg>", many(4097)).as_bytes()));
@@ -196,7 +191,8 @@ fn an_element_with_thousands_of_attributes_is_refused_before_parsing() {
#[test]
fn attribute_work_is_bounded_over_the_whole_document_and_its_dtd() {
use super::too_wide;
let l = craft_svg::tree::Limits::default();
let too_wide = |s: &[u8]| craft_svg::guard::too_wide(std::str::from_utf8(s).unwrap(), l.attributes, l.attribute_work);
let many = |n: usize| (0..n).map(|i| format!(" a{i}=\"1\"")).collect::<String>();
let tag = format!("<g{}/>", many(4000));
assert!(!too_wide(format!("<svg>{}</svg>", tag.repeat(10)).as_bytes()));
File diff suppressed because one or more lines are too long
+2 -2
View File
@@ -1255,8 +1255,8 @@ layer; text on one `<textPath>` as text on a path, with its start offset and anc
image fills, and SVG images imported in place. CSS, `<use>`/`<symbol>`, units
and `viewBox`/`preserveAspectRatio` are resolved. The result's `warnings` list what was left out
(filters that aren't shadows or blurs, rotated repeating patterns, a clip path's own clip path).
Linked files are never read, only data URIs; documents nested more than 512 elements deep are
refused.
Linked files are never read, only data URIs; documents nested more than 256 elements deep
(references followed) are refused.
### Importing `.fig` files