//! 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 { Some(match file { // C3 reference graph: a `` cycle is refused (TS accepts it). "use-self-cycle.svg" | "use-mutual-cycle.svg" => json!({ "rejected": "reference_cycle" }), // C3 namespace: `` 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 = 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 { 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 = 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 = ""; let n = spec["n"].as_u64().unwrap_or(0) as usize; match spec["kind"].as_str().unwrap() { "uses" => format!( "{OPEN}{}", "".repeat(n) ), "chain" => { let mut body = String::from(""); let (levels, width) = ( spec["levels"].as_u64().unwrap(), spec["width"].as_u64().unwrap() as usize, ); for level in 1..=levels { body.push_str(&format!( "{}", format!("", level - 1).repeat(width) )); } format!("{OPEN}{body}") } "depth" => format!( "{OPEN}{}{}", "".repeat(n - 1), "".repeat(n - 1) ), "elements" => format!("{OPEN}{}", "".repeat(n - 1)), "bytes" => { let frame = format!("{OPEN}"); format!("{OPEN}", "x".repeat(n - frame.len())) } "attributes" => { let attrs: String = (0..n).map(|i| format!(" data-a{i}=\"{i}\"")).collect(); format!("{OPEN}") } 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 [ ( "", SvgRejection::Malformed, ), ("", SvgRejection::NotSvg), ] { assert_eq!(read_svg(text).err(), Some(reason)); } }