Files
faunosteo/crates/core/tests/svg_reserved_ids.rs
T
bchanot d8562f60f5 fix(anatomy): V1-2.2 refuse a root visibility that hides the markers
Both composers append the marker layer as the root's last child, so a
root visibility="hidden" whose children set visible back drew the
drawing without a marker (0 marker pixels in Chromium and Firefox, PDF
and canvas). The reader refuses any root visibility but visible
(root_visibility); cleaning, verdict, preview, PDF gate and both
composers answer it.
2026-10-30 18:56:48 +01:00

438 lines
17 KiB
Rust

//! V1-2.2 owner brief 2026-10-30: the ids the composition writes are reserved. The PDF view
//! keeps the drawing's ids and gets the halo filter `osteo-halo` written next to them; a
//! drawing defining that id replaced the filter (a `filter#osteo-halo` of its own, which the
//! composition then did not write) or won its resolution (any element holding it before the
//! engine's). The reader refuses such a drawing (`reserved_id`) in any letter case and through
//! any spelling XML decodes; the cleaning, the preview, the verdict and the PDF snapshot gate
//! answer with it; both composers refuse a tree holding it; the PDF view's halo is the
//! engine's, once; the historical drawings (`osteo-overlays`) read as before.
#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)]
mod common;
use std::collections::HashSet;
use common::sheet_readers::{
OPEN, assert_refused_everywhere, canvas_outcome, holders, preview, sheet, svg, verdict_detail,
};
use faunosteo_core::anatomy::compose::{ComposeError, compose_canvas, compose_highlight};
use faunosteo_core::anatomy::svg::clean::{CleaningOutcome, clean_svg};
use faunosteo_core::anatomy::svg::refs::{RESERVED_IDS, is_reserved_id};
use faunosteo_core::anatomy::svg::tree::parse_svg;
use faunosteo_core::anatomy::svg::{Element, SvgRejection, read_svg};
use faunosteo_core::domain::sheet::AnatomicalSheetDocument;
use faunosteo_core::domain::sheet::verdict::{DrawingResult, sha256_hex};
use serde::Deserialize;
use serde_json::json;
const HORSE: &str = "supabase/seed/anatomical-sheets/equine/draft/assets/horse.svg";
/// The DEV equine object (contract §9.3): its bytes are the committed draft drawing.
const HORSE_SHA256: &str = "0ea5202fa3b95bac167b87c12ee969ab0272e085b60c2d34dbca6202c5f08541";
/// The filter a hostile drawing put in the engine's place: every pixel transparent.
const ERASER: &str = "<filter id=\"osteo-halo\"><feColorMatrix type=\"matrix\" \
values=\"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\"/></filter>";
/// The drawing is refused `reserved_id` by every reader of the product.
fn assert_refused_everywhere_id(text: &str) {
assert_refused_everywhere(text, "reserved_id");
}
/// No element of the tree holds a reserved id, in any case.
fn free_of_reserved(element: &Element) -> bool {
!element.attr("id").is_some_and(is_reserved_id)
&& element.element_children().all(free_of_reserved)
}
#[test]
fn the_reserved_set_is_the_halo_filter_alone() {
assert_eq!(RESERVED_IDS, ["osteo-halo"]);
for id in ["osteo-halo", "OSTEO-HALO", "Osteo-Halo", "osteo-HALO"] {
assert!(is_reserved_id(id), "{id}");
}
for id in [
"osteo-overlays",
"osteo-halo2",
"osteo-halo-x",
"xosteo-halo",
"osteo_halo",
"osteo.halo",
"osteohalo",
"haloWide",
"haloTight",
"",
] {
assert!(!is_reserved_id(id), "{id}");
}
}
/// 1. A drawing with no reserved id: read, cleaned, previewed, verified and composed, with the
/// engine's halo once and every marker naming it.
#[test]
fn a_drawing_without_a_reserved_id_is_accepted_and_gets_the_engine_halo() {
let text = svg(
"<defs><filter id=\"glow\"><feGaussianBlur stdDeviation=\"1\" result=\"haloWide\"/>\
</filter></defs><g id=\"osteo-overlays\"><path id=\"osteo-halo2\" filter=\"url(#glow)\" \
d=\"M0 0h1\"/></g>",
);
let read = read_svg(&text).unwrap();
assert!(read.removed.is_empty());
assert_eq!(clean_svg(text.as_bytes()).outcome, CleaningOutcome::Clean);
assert_eq!(
verdict_detail(&text),
(false, DrawingResult::Ok, None),
"the verdict keeps it"
);
assert_eq!(canvas_outcome(&preview(&text), "detail")["ok"], json!(true));
let ids: HashSet<&str> = ["hock"].into_iter().collect();
let composed = compose_highlight(&sheet(), "main", read.root, &ids, true).unwrap();
let mut halos = Vec::new();
holders(&composed, "osteo-halo", &mut halos);
assert_eq!(halos.len(), 1);
assert_eq!(halos[0].qname, "filter");
assert_eq!(
halos[0].element_children().count(),
3,
"two blurs and the merge"
);
let marker = composed
.element_children()
.last()
.unwrap()
.element_children()
.next()
.unwrap();
assert_eq!(marker.attr("filter"), Some("url(#osteo-halo)"));
assert_eq!(marker.attr("fill"), Some("#b85a3f"));
}
/// 2. A filter of its own named `osteo-halo`, referenced or not, eraser or harmless.
#[test]
fn a_filter_named_osteo_halo_is_refused() {
assert_refused_everywhere_id(&svg(ERASER));
assert_refused_everywhere_id(&svg(&format!(
"<defs>{ERASER}</defs><path filter=\"url(#osteo-halo)\" d=\"M0 0h1\"/>"
)));
assert_refused_everywhere_id(&svg(
"<filter id=\"osteo-halo\"><feGaussianBlur stdDeviation=\"18\"/></filter>",
));
}
/// 3. The id on any element the reader keeps, the root included.
#[test]
fn the_reserved_id_on_any_kept_element_is_refused() {
let elements = [
"<g id=\"osteo-halo\"/>",
"<g id=\"osteo-halo\"/><defs/>",
"<path id=\"osteo-halo\" d=\"M0 0h1\"/>",
"<circle id=\"osteo-halo\" r=\"1\"/>",
"<ellipse id=\"osteo-halo\" rx=\"1\" ry=\"1\"/>",
"<rect id=\"osteo-halo\" width=\"1\" height=\"1\"/>",
"<line id=\"osteo-halo\"/>",
"<polyline id=\"osteo-halo\" points=\"0 0 1 1\"/>",
"<polygon id=\"osteo-halo\" points=\"0 0 1 1 1 0\"/>",
"<defs id=\"osteo-halo\"/>",
"<linearGradient id=\"osteo-halo\"/>",
"<radialGradient id=\"osteo-halo\"/>",
"<linearGradient id=\"g\"><stop id=\"osteo-halo\" offset=\"0\"/></linearGradient>",
"<filter id=\"f\"><feGaussianBlur id=\"osteo-halo\" stdDeviation=\"1\"/></filter>",
"<filter id=\"f\"><feMerge><feMergeNode id=\"osteo-halo\"/></feMerge></filter>",
"<filter id=\"f\"><feFlood id=\"osteo-halo\"/></filter>",
"<clipPath id=\"osteo-halo\"/>",
"<mask id=\"osteo-halo\"/>",
"<title id=\"osteo-halo\">t</title>",
"<desc id=\"osteo-halo\">d</desc>",
"<switch id=\"osteo-halo\"/>",
"<path id=\"p\" d=\"M0 0h1\"/><use id=\"osteo-halo\" href=\"#p\"/>",
"<g><g><g><path id=\"osteo-halo\" d=\"M0 0h1\"/></g></g></g>",
];
for body in elements {
assert_refused_everywhere_id(&svg(body));
}
let root = OPEN.replace("viewBox", "id=\"osteo-halo\" viewBox");
assert_refused_everywhere_id(&format!("{root}<path d=\"M0 0h1\"/></svg>"));
}
/// 4. References to the reserved id: dangling when the drawing does not define it (already
/// refused), reserved when it does, whatever the spelling of the reference.
#[test]
fn references_to_the_reserved_id_are_refused() {
let references = [
"<path filter=\"url(#osteo-halo)\" d=\"M0 0h1\"/>",
"<path style=\"filter:url(#osteo-halo)\" d=\"M0 0h1\"/>",
"<path filter=\"url( '#osteo-halo' )\" d=\"M0 0h1\"/>",
"<path filter=\"url(&quot;#osteo-halo&quot;)\" d=\"M0 0h1\"/>",
"<path fill=\"url(#osteo-halo) red\" d=\"M0 0h1\"/>",
"<path clip-path=\"url(#osteo-halo)\" mask=\"url(#osteo-halo)\" d=\"M0 0h1\"/>",
"<use href=\"#osteo-halo\"/>",
"<use xlink:href=\"#osteo-halo\"/>",
"<use href=\" #osteo-halo \"/>",
"<linearGradient id=\"g\" xlink:href=\"#osteo-halo\"/>",
"<path filter=\"url(#OSTEO-HALO)\" d=\"M0 0h1\"/>",
];
for reference in references {
let alone = svg(reference);
assert_eq!(
read_svg(&alone).err(),
Some(SvgRejection::DanglingReference),
"{reference}"
);
assert_eq!(
clean_svg(alone.as_bytes()).reason.as_deref(),
Some("dangling_reference"),
"{reference}"
);
assert_refused_everywhere_id(&svg(&format!(
"<defs><filter id=\"osteo-halo\"/><g id=\"OSTEO-HALO\"/></defs>{reference}"
)));
}
}
/// 5. Adversarial spellings. What XML decodes to the reserved id (character references, any
/// letter case) is refused; what is not the id grammar (spaces, look-alikes, invisible
/// characters, prefixed or `xml:` names, prefixed SVG elements) is removed, so the tree
/// the composition receives holds no reserved id; a backslash escape is active content.
#[test]
fn adversarial_spellings_never_reach_the_composition() {
let decoded_to_reserved = [
"osteo&#45;halo",
"osteo&#x2D;halo",
"osteo&#x2d;halo",
"&#111;&#115;&#116;&#101;&#111;&#45;&#104;&#97;&#108;&#111;",
"&#x4F;steo-halo",
"OSTEO-HALO",
"oSTEO-hALO",
];
for id in decoded_to_reserved {
assert_refused_everywhere_id(&svg(&format!("<g id=\"{id}\"/>")));
}
let removed = [
("<g id=\" osteo-halo\"/>", "g@id"),
("<g id=\"osteo-halo \"/>", "g@id"),
("<g id=\"osteo-halo&#9;\"/>", "g@id"),
("<g id=\"osteo-halo&#10;\"/>", "g@id"),
("<g id=\"osteo\u{2010}halo\"/>", "g@id"),
("<g id=\"osteo\u{2011}halo\"/>", "g@id"),
("<g id=\"o\u{17f}teo-halo\"/>", "g@id"),
("<g id=\"\u{43e}steo-halo\"/>", "g@id"),
("<g id=\"\u{ff4f}steo-halo\"/>", "g@id"),
("<g id=\"osteo-\u{200b}halo\"/>", "g@id"),
("<g id=\"osteo-halo\u{ad}\"/>", "g@id"),
("<g xml:id=\"osteo-halo\"/>", "g@xml:id"),
(
"<g xmlns:s=\"http://www.w3.org/2000/svg\" s:id=\"osteo-halo\"/>",
"g@s:id",
),
(
"<s:filter xmlns:s=\"http://www.w3.org/2000/svg\" id=\"osteo-halo\"/>",
"s:filter",
),
("<text id=\"osteo-halo\">t</text>", "text"),
];
let sheet = sheet();
let ids: HashSet<&str> = ["hock"].into_iter().collect();
for (body, removal) in removed {
let text = svg(body);
let read = read_svg(&text).unwrap_or_else(|e| panic!("{body}: {e:?}"));
assert!(
read.removed.iter().any(|r| r == removal),
"{body}: {:?}",
read.removed
);
assert!(free_of_reserved(&read.root), "{body}");
let cleaning = clean_svg(text.as_bytes());
assert_eq!(cleaning.outcome, CleaningOutcome::Cleanable, "{body}");
let stored = read_svg(cleaning.stored.as_deref().unwrap()).unwrap();
assert!(free_of_reserved(&stored.root), "{body}");
let composed = compose_highlight(&sheet, "main", read.root, &ids, true).unwrap();
let mut halos = Vec::new();
holders(&composed, "osteo-halo", &mut halos);
assert_eq!(halos.len(), 1, "{body}");
assert_eq!(halos[0].qname, "filter", "{body}");
}
// A CSS escape or a percent-encoded target never names the id: the reader removes the
// attribute as active content (a backslash, a reference outside the document) and the
// cleaning refuses the file.
for body in [
"<filter id=\"f\"/><path filter=\"url(#osteo\\2d halo)\" d=\"M0 0\"/>",
"<filter id=\"f\"/><path filter=\"url(#osteo%2Dhalo)\" d=\"M0 0\"/>",
] {
let text = svg(body);
let read = read_svg(&text).unwrap();
assert_eq!(read.removed, ["path@filter"], "{body}");
assert_eq!(read.active, ["path@filter"], "{body}");
assert_eq!(
clean_svg(text.as_bytes()).reason.as_deref(),
Some("svg_active_content"),
"{body}"
);
}
}
/// 5 (sweep). Every letter case of the id, and each of its characters written as a decimal
/// or a hexadecimal character reference, is refused; each character replaced by a look-alike
/// outside ASCII is removed and composes with the engine's halo only.
#[test]
fn every_case_and_character_reference_of_the_id_is_refused() {
let id = "osteo-halo";
let letters: Vec<usize> = id
.char_indices()
.filter(|(_, c)| c.is_ascii_alphabetic())
.map(|(i, _)| i)
.collect();
let mut spellings = Vec::new();
for mask in 0u32..1 << letters.len() {
let mut chars: Vec<char> = id.chars().collect();
for (bit, &index) in letters.iter().enumerate() {
if mask & (1 << bit) != 0 {
chars[index] = chars[index].to_ascii_uppercase();
}
}
spellings.push(chars.into_iter().collect::<String>());
}
for (index, c) in id.char_indices() {
let code = c as u32;
for reference in [
format!("&#{code};"),
format!("&#x{code:X};"),
format!("&#x{code:04x};"),
] {
spellings.push(format!("{}{reference}{}", &id[..index], &id[index + 1..]));
}
}
assert_eq!(spellings.len(), 512 + 30);
for spelling in &spellings {
let text = svg(&format!("<filter id=\"{spelling}\"/>"));
assert_eq!(
read_svg(&text).err(),
Some(SvgRejection::ReservedId),
"{spelling}"
);
assert_eq!(
clean_svg(text.as_bytes()).reason.as_deref(),
Some("reserved_id"),
"{spelling}"
);
}
let look_alikes = [
'\u{2010}', '\u{2212}', '\u{fe63}', '\u{ff0d}', '\u{43e}', '\u{3bf}', '\u{17f}',
'\u{1d0f}', '\u{200d}',
];
let sheet = sheet();
let ids: HashSet<&str> = ["hock"].into_iter().collect();
for index in 0..id.len() {
for look_alike in look_alikes {
let spelling = format!("{}{look_alike}{}", &id[..index], &id[index + 1..]);
let read = read_svg(&svg(&format!("<filter id=\"{spelling}\"/>"))).unwrap();
assert_eq!(read.removed, ["filter@id"], "{spelling}");
let composed = compose_highlight(&sheet, "main", read.root, &ids, true).unwrap();
let mut halos = Vec::new();
holders(&composed, "osteo-halo", &mut halos);
assert_eq!(halos.len(), 1, "{spelling}");
}
}
}
/// The composers stay fail-closed on a tree that did not come out of the reader, a composed
/// PDF view given back included.
#[test]
fn both_composers_refuse_a_tree_holding_a_reserved_id() {
let sheet = sheet();
let ids: HashSet<&str> = ["hock"].into_iter().collect();
for (element, id) in [
("filter", "osteo-halo"),
("g", "osteo-halo"),
("path", "OSTEO-HALO"),
("svg", "osteo-halo"),
] {
let mut root = parse_svg(&svg("<path d=\"M0 0h1\"/>")).unwrap();
if element == "svg" {
root.set_attr("id", id.to_owned());
} else {
let parsed = parse_svg(&svg(&format!("<{element}/>"))).unwrap();
let mut child = parsed.element_children().next().unwrap().clone();
child.set_attr("id", id.to_owned());
root.children
.push(faunosteo_core::anatomy::svg::Node::Element(child));
}
assert_eq!(
compose_canvas(&sheet, "detail", &root).unwrap_err(),
ComposeError::ReservedId,
"{element}#{id}"
);
for halo in [true, false] {
assert_eq!(
compose_highlight(&sheet, "main", root.clone(), &ids, halo).unwrap_err(),
ComposeError::ReservedId,
"{element}#{id} halo {halo}"
);
}
}
let read = read_svg(&svg("<path d=\"M0 0h1\"/>")).unwrap();
let composed = compose_highlight(&sheet, "main", read.root, &ids, true).unwrap();
assert_eq!(
compose_highlight(&sheet, "main", composed, &ids, true).unwrap_err(),
ComposeError::ReservedId
);
}
/// 7. The equine drawing (the DEV object's bytes) reads with nothing removed, keeps its
/// historical `osteo-overlays` group, composes every view; no committed drawing but the
/// hostile fixture holds a reserved id.
#[test]
fn the_historical_drawings_read_as_before() {
let horse = common::repo_file(HORSE);
assert_eq!(sha256_hex(horse.as_bytes()), HORSE_SHA256);
let read = read_svg(&horse).unwrap();
assert!(read.removed.is_empty());
let mut overlays = Vec::new();
holders(&read.root, "osteo-overlays", &mut overlays);
assert_eq!(overlays.len(), 1);
assert_eq!(clean_svg(horse.as_bytes()).outcome, CleaningOutcome::Clean);
let (_, draft) = common::oracle_file("sheet.draft.json");
let draft = AnatomicalSheetDocument::deserialize(&draft["output"]).unwrap();
let ids: HashSet<&str> = draft.annotations.iter().map(|a| a.id()).collect();
for view in &draft.views {
compose_canvas(&draft, view.id(), &read.root).unwrap();
compose_highlight(&draft, view.id(), read.root.clone(), &ids, view.is_main()).unwrap();
}
let mut files = Vec::new();
collect_svgs(std::path::Path::new(&common::repo_path("")), &mut files);
assert!(files.len() > 60, "{} drawings", files.len());
for path in files {
let Ok(text) = std::fs::read_to_string(&path) else {
continue;
};
let reserved = path.ends_with("hostile/osteo-halo-id.svg");
assert_eq!(
read_svg(&text).err() == Some(SvgRejection::ReservedId),
reserved,
"{}",
path.display()
);
}
}
fn collect_svgs(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
for entry in std::fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
let name = path.file_name().unwrap().to_string_lossy();
if path.is_dir() {
if !matches!(
name.as_ref(),
"node_modules" | "target" | ".git" | "pkg" | "pkg-proofs" | "dist"
) {
collect_svgs(&path, out);
}
} else if name.ends_with(".svg") {
out.push(path);
}
}
}