feat(anatomy): Rust SVG reader: tree, allowlist sanitiser, reference graph, serialiser (O4/O5 green)

This commit is contained in:
bchanot committed 2026-10-14 23:46:10 +02:00
1 parent a7b3d7a4c1
commit 85c2183791
12 files changed
+10851 -6

No files matched your search

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg"><g id="1abc"/><g id="ok_1.a:b-c"/><g id="root"/><g id="a b"/></svg>

After

Width:  |  Height:  |  Size: 107 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" class="fixed inset-0 z-50" style="position:fixed;width:100vw"><g class="kept" style="opacity:0.5"><path d="M0 0h1"/></g></svg>

After

Width:  |  Height:  |  Size: 166 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://evil.test/ns"><linearGradient id="a"/><linearGradient id="b" xlink:href="#a"/></svg>

After

Width:  |  Height:  |  Size: 144 B

File diff suppressed because it is too large. Load diff
+262
View File
@@ -0,0 +1,262 @@
//! R3 O4 + O5: the Rust SVG reader against the TypeScript sanitiser's frozen verdicts
//! (`oracles/r3/sanitiser.json`, written by `packages/pdf/tests/r3.sanitiser-oracles.test.ts`
//! on the corpus `fixtures/svg/hostile` and the product SVGs). Every case gives the TS verdict,
//! except the differences the plan declares (rev 2 C2/C3), each listed below with the Rust
//! verdict; a case where Rust would be looser than the TS and is not listed fails.
//!
//! Trees are compared as structure: namespace, local name, attributes by qualified name,
//! children with text; the Rust tree is the reader's output serialised and read again. The
//! declared rules that change a tree (comments and PIs dropped, text only in `title`/`desc`,
//! elements outside the SVG namespace removed, ids outside the reference grammar removed, no
//! `class`/`style` on the root) are applied to the TS tree before comparing.
#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)]
mod common;
use std::collections::BTreeMap;
use faunosteo_core::anatomy::svg::sanitize::is_reference_name;
use faunosteo_core::anatomy::svg::serialize::serialize;
use faunosteo_core::anatomy::svg::tree::{SVG_NS, parse_svg};
use faunosteo_core::anatomy::svg::{Element, Node, SvgRejection, read_svg};
use serde_json::{Value, json};
/// Rust outcomes that differ from the TS on purpose: file → expected Rust verdict.
fn declared(file: &str) -> Option<Value> {
Some(match file {
// C3 reference graph: a `<use>` cycle is refused (TS accepts it).
"use-self-cycle.svg" | "use-mutual-cycle.svg" => json!({ "rejected": "reference_cycle" }),
// C3 namespace: `<path xmlns="evil">` is removed too (TS keeps it).
"namespaces.svg" => json!({ "removed": [
"svg@xmlns:s", "svg@xmlns:inkscape", "s:path", "path",
"path@inkscape:label", "path@xml:space", "path@xml:lang"
] }),
// C3 id grammar: an id holding a tab, a space or starting with a digit is removed.
"whitespace-references.svg" => json!({ "removed": ["path@id"] }),
"id-grammar.svg" => json!({ "removed": ["g@id", "g@id"] }),
// C3 namespace: `xlink:href` whose prefix is bound to another URI is removed.
"xlink-prefix-rebound.svg" => json!({ "removed": ["linearGradient@xlink:href"],
"strip": [["linearGradient", "xlink:href"]] }),
// C3 root: no class or style on the inline root.
"root-class-style.svg" => json!({ "removed": ["svg@class", "svg@style"] }),
_ => return None,
})
}
/// Generated cases with a declared Rust verdict (C2 bounds, C3 budget).
fn declared_spec(spec: &Value) -> Option<&'static str> {
match (spec["kind"].as_str()?, spec["n"].as_u64()) {
("chain", _) => Some("too_complex"),
("bytes", Some(n)) if n > 2 * 1024 * 1024 => Some("too_large"),
("attributes", _) => Some("too_complex"),
_ => None,
}
}
fn tree_value(element: &Element) -> Value {
let attrs: BTreeMap<&str, &str> = element
.attrs
.iter()
.map(|a| (a.qname.as_str(), a.value.as_str()))
.collect();
let children: Vec<Value> = element
.children
.iter()
.map(|n| match n {
Node::Element(e) => tree_value(e),
Node::Text(t) => json!({ "text": t }),
})
.collect();
json!({
"ns": element.namespace.as_deref().unwrap_or(SVG_NS),
"name": element.local_name(),
"attrs": attrs,
"children": children,
})
}
/// Removes the named attribute from every element of that local name (a declared removal).
fn strip(tree: &mut Value, element: &str, attribute: &str) {
if tree["name"] == element {
if let Some(attrs) = tree["attrs"].as_object_mut() {
attrs.remove(attribute);
}
}
if let Some(children) = tree["children"].as_array_mut() {
children
.iter_mut()
.for_each(|c| strip(c, element, attribute));
}
}
/// The Rust output read again, as a tree.
fn reread(element: &Element) -> Value {
tree_value(&parse_svg(&serialize(element)).unwrap())
}
fn is_space(text: &str) -> bool {
text.chars().all(|c| matches!(c, ' ' | '\t' | '\n' | '\r'))
}
/// The declared rules applied to a TS tree (see the header).
fn declared_tree(node: &Value, keeps_text: bool, root: bool) -> Option<Value> {
if node.get("comment").is_some() || node.get("pi").is_some() {
return None;
}
if let Some(text) = node["text"].as_str() {
return (keeps_text || is_space(text)).then(|| node.clone());
}
if node["ns"] != SVG_NS {
return None;
}
let name = node["name"].as_str().unwrap();
let mut attrs = node["attrs"].as_object().unwrap().clone();
if attrs
.get("id")
.and_then(Value::as_str)
.is_some_and(|id| !is_reference_name(id))
{
attrs.remove("id");
}
if root {
attrs.remove("class");
attrs.remove("style");
}
let text_inside = matches!(name, "title" | "desc");
let children: Vec<Value> = node["children"]
.as_array()
.unwrap()
.iter()
.filter_map(|c| declared_tree(c, text_inside, false))
.collect();
Some(json!({ "ns": node["ns"], "name": name, "attrs": attrs, "children": children }))
}
fn verdict(text: &str) -> Value {
match read_svg(text) {
Ok(s) => json!({ "removed": s.removed, "tree": reread(&s.root) }),
Err(e) => json!({ "rejected": e.reason() }),
}
}
#[test]
fn every_hostile_case_gives_the_typescript_verdict_or_a_declared_one() {
let (_, oracle) = common::oracle_file("r3/sanitiser.json");
let hostile = oracle["hostile"].as_object().unwrap();
assert!(hostile.len() >= 34);
for (file, ts) in hostile {
let text = common::repo_file(&format!("crates/core/tests/fixtures/svg/hostile/{file}"));
let rust = verdict(&text);
match declared(file) {
Some(expected) if expected.get("rejected").is_some() => {
assert_eq!(rust, expected, "{file}")
}
Some(expected) => {
assert_eq!(rust["removed"], expected["removed"], "{file}");
let mut tree = declared_tree(&ts["tree"], false, true).unwrap();
for pair in expected["strip"].as_array().into_iter().flatten() {
strip(
&mut tree,
pair[0].as_str().unwrap(),
pair[1].as_str().unwrap(),
);
}
assert_eq!(rust["tree"], tree, "{file}");
}
None if ts.get("rejected").is_some() => assert_eq!(rust, *ts, "{file}"),
None => {
assert_eq!(rust["removed"], ts["removed"], "{file}");
assert_eq!(
rust["tree"],
declared_tree(&ts["tree"], false, true).unwrap(),
"{file}"
);
}
}
}
}
/// `generated(spec)` of the TS generator, byte for byte.
fn generated(spec: &Value) -> String {
const OPEN: &str = "<svg xmlns=\"http://www.w3.org/2000/svg\">";
let n = spec["n"].as_u64().unwrap_or(0) as usize;
match spec["kind"].as_str().unwrap() {
"uses" => format!(
"{OPEN}<path id=\"p\" d=\"M0 0h1\"/>{}</svg>",
"<use href=\"#p\"/>".repeat(n)
),
"chain" => {
let mut body = String::from("<path id=\"l0\" d=\"M0 0h1\"/>");
let (levels, width) = (
spec["levels"].as_u64().unwrap(),
spec["width"].as_u64().unwrap() as usize,
);
for level in 1..=levels {
body.push_str(&format!(
"<g id=\"l{level}\">{}</g>",
format!("<use href=\"#l{}\"/>", level - 1).repeat(width)
));
}
format!("{OPEN}{body}</svg>")
}
"depth" => format!(
"{OPEN}{}{}</svg>",
"<g>".repeat(n - 1),
"</g>".repeat(n - 1)
),
"elements" => format!("{OPEN}{}</svg>", "<path/>".repeat(n - 1)),
"bytes" => {
let frame = format!("{OPEN}<!----></svg>");
format!("{OPEN}<!--{}--></svg>", "x".repeat(n - frame.len()))
}
"attributes" => {
let attrs: String = (0..n).map(|i| format!(" data-a{i}=\"{i}\"")).collect();
format!("{OPEN}<path d=\"M0 0h1\"{attrs}/></svg>")
}
other => panic!("unknown spec {other}"),
}
}
#[test]
fn every_generated_case_gives_the_typescript_verdict_or_a_declared_one() {
let (_, oracle) = common::oracle_file("r3/sanitiser.json");
for case in oracle["specs"].as_array().unwrap() {
let (spec, ts) = (&case["spec"], &case["verdict"]);
let rust = read_svg(&generated(spec));
match (declared_spec(spec), rust) {
(Some(reason), Err(e)) => assert_eq!(e.reason(), reason, "{spec}"),
(Some(reason), Ok(_)) => panic!("{spec}: expected {reason}"),
(None, Err(e)) => assert_eq!(ts["rejected"], e.reason(), "{spec}"),
(None, Ok(s)) => {
let mut removed = s.removed.clone();
removed.sort();
removed.dedup();
assert_eq!(json!(removed), ts["removed"], "{spec}");
}
}
}
}
#[test]
fn the_product_svgs_come_out_untouched() {
let (_, oracle) = common::oracle_file("r3/sanitiser.json");
for entry in oracle["legitimate"].as_array().unwrap() {
let path = entry["path"].as_str().unwrap();
let read = read_svg(&common::repo_file(path)).unwrap_or_else(|e| panic!("{path}: {e:?}"));
assert!(read.removed.is_empty(), "{path}: {:?}", read.removed);
assert_eq!(reread(&read.root), entry["tree"], "{path}");
}
}
#[test]
fn a_rejection_names_a_closed_reason() {
for (text, reason) in [
(
"<svg xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M0 0\"></svg>",
SvgRejection::Malformed,
),
("<html/>", SvgRejection::NotSvg),
] {
assert_eq!(read_svg(text).err(), Some(reason));
}
}