Files
faunosteo/crates/core/tests/svg_sanitiser.rs
T
bchanot 08efd9a792 fix(anatomy): V1-2.2 reserve the PDF halo id in the reader and composers
A drawing defining filter#osteo-halo replaced the PDF halo (a transparent
filter erased the marker); an element holding the id before the first
defs won its resolution. The reader refuses the id in any letter case
(reserved_id), both composers refuse such a tree, the halo is always the
engine's. Exact name only: osteo-overlays stays.
2026-10-30 17:30:48 +01:00

310 lines
13 KiB
Rust

//! 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`/`transform`/`filter`/`mask`/`clip-path` on the root) are applied to the TS
//! tree before comparing.
#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)]
mod common;
use common::svg_tree::reread;
use faunosteo_core::anatomy::svg::sanitize::is_reference_name;
use faunosteo_core::anatomy::svg::tree::SVG_NS;
use faunosteo_core::anatomy::svg::{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 text: a `title`/`desc` text over 4 KiB is refused whole (TS keeps it).
"long-title.svg" => json!({ "rejected": "too_complex" }),
// 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 references: an href is local only as the URL parser reads it (ASCII whitespace
// stripped, nothing else); the TS trimmed JavaScript spaces (security audit R3).
"href-unicode-space.svg" => json!({ "removed": ["use@href", "use@xlink:href"],
"strip_unicode_spaced_refs": true }),
// C3 references: `url(` skips CSS whitespace only, as the browser's tokenizer does
// (security audit R3, pass 2): a Unicode space before `#` is not local.
"url-unicode-space.svg" => json!({ "removed": ["path@fill", "path@style"],
"strip": [["path", "fill"], ["path", "style"]] }),
// C3 root: nothing that paints outside the box on the inline root (security audit R3).
"root-presentation.svg" => {
json!({ "removed": ["svg@transform", "svg@filter", "svg@mask", "svg@clip-path"] })
}
// C2: the prescan's per-element attribute cap (TS removes the 3,000 data-like names).
"comment-desync-attributes.svg" => json!({ "rejected": "too_complex" }),
// V1-2.2 owner decision 2026-10-29: a reference to an id the drawing does not define
// is refused (TS dropped nothing; inlined, it would resolve against the page).
"dangling-references.svg" => json!({ "rejected": "dangling_reference" }),
// V1-2.2 owner brief 2026-10-30: the PDF halo's id is reserved (TS kept the group; the
// highlight then skipped or lost its own filter).
"osteo-halo-id.svg" => json!({ "rejected": "reserved_id" }),
// V1-2.2 owner decision 2026-10-29: a strict numeric `rgb()` colour is kept (TS removed
// any function); the five other styles stay removed.
"css.svg" => {
json!({ "removed": ["path@style", "path@style", "path@style", "path@style", "path@style"],
"rust_keeps": [["path", "style", "fill:rgb(1,2,3)"]] })
}
// 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,
}
}
/// 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
&& 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));
}
}
/// Removes the attribute holding exactly `value` from elements of that local name (a value
/// the Rust reader keeps on purpose); whether one was found.
fn strip_value(tree: &mut Value, element: &str, attribute: &str, value: &str) -> bool {
let mut found = false;
if tree["name"] == element
&& let Some(attrs) = tree["attrs"].as_object_mut()
&& attrs.get(attribute).and_then(Value::as_str) == Some(value)
{
attrs.remove(attribute);
found = true;
}
if let Some(children) = tree["children"].as_array_mut() {
for child in children {
found |= strip_value(child, element, attribute, value);
}
}
found
}
/// Removes `href`/`xlink:href` values that start with a non-ASCII character (a declared removal).
fn strip_unicode_spaced_refs(tree: &mut Value) {
if let Some(attrs) = tree["attrs"].as_object_mut() {
attrs.retain(|name, value| {
let spaced = value
.as_str()
.and_then(|v| v.chars().next())
.is_some_and(|c| !c.is_ascii());
!((name == "href" || name == "xlink:href") && spaced)
});
}
if let Some(children) = tree["children"].as_array_mut() {
children.iter_mut().for_each(strip_unicode_spaced_refs);
}
}
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 {
for name in ["class", "style", "transform", "filter", "mask", "clip-path"] {
attrs.remove(name);
}
}
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 rust = rust.clone();
for kept in expected["rust_keeps"].as_array().into_iter().flatten() {
let [element, attribute, value] = [0, 1, 2].map(|i| kept[i].as_str().unwrap());
assert!(
strip_value(&mut rust["tree"], element, attribute, value),
"{file}"
);
}
let mut tree = declared_tree(&ts["tree"], false, true).unwrap();
if expected["strip_unicode_spaced_refs"] == true {
strip_unicode_spaced_refs(&mut tree);
}
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));
}
}