Files
faunosteo/crates/core/tests/svg_scope.rs
T
bchanot a678faaa23 fix(anatomy): V1-2.2 read url() references in their strict spelling only
Security review BLOCK(1): url(#%61) passed the dangling check and the
per-view scoping and resolved in browsers. One strict reading now, other
spellings are active content; glued names are other functions; the
composer refuses an unscoped reference; owner export procedure.
2026-10-29 16:49:15 +01:00

345 lines
13 KiB
Rust

//! V1-2.2 owner decision 2026-10-29: SVG references and the isolation of views. A local
//! reference to an id the drawing does not define is refused by the reader, the cleaning, the
//! verdict and the preview; the canvas, inlined in the page, scopes every id and reference to
//! its view, so two drawings with the same ids never resolve into each other and a valid
//! reference keeps working; the composition is deterministic.
#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)]
use std::collections::HashMap;
use faunosteo_core::anatomy::svg::clean::{CleaningOutcome, clean_svg};
use faunosteo_core::anatomy::svg::sanitize::{local_reference_text, url_targets};
use faunosteo_core::anatomy::svg::tree::parse_svg;
use faunosteo_core::anatomy::svg::{Element, SvgRejection, read_svg};
use faunosteo_core::domain::sheet::preview::{
PreviewDrawing, PreviewDrawingStatus, PreviewInput, PreviewSheet, PreviewStatus,
};
use faunosteo_core::domain::sheet::verdict::{
DrawingResult, VerdictBinding, VerdictDrawing, VerdictInput, codes, compute_verdict, sha256_hex,
};
use faunosteo_core::facade::call_with_preview;
use serde_json::{Value, json};
const MAIN_ASSET: &str = "11111111-2222-4333-8444-555555555555";
const DETAIL_ASSET: &str = "66666666-7777-4888-9999-aaaaaaaaaaaa";
/// The opening of a drawing in its stored form (prolog, then the root as the core writes it).
const OPEN: &str = concat!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n",
r#"<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 10 10">"#
);
/// Valid references, one id named several times, by `href`, `xlink:href` and `url(…)`.
fn main_drawing() -> String {
format!(
"{OPEN}<defs><linearGradient id=\"g\"/><g id=\"big\"><path d=\"M0 0h1\"/></g></defs>\
<path fill=\"url(#g)\" d=\"M0 0h2\"/><use href=\"#big\"/><use xlink:href=\"#big\"/>\
<path stroke=\"url( '#g')\" style=\"fill:url(#g)\" d=\"M0 0h3\"/></svg>"
)
}
/// The same ids as the main drawing, with other content.
fn detail_drawing() -> String {
format!(
"{OPEN}<defs><radialGradient id=\"g\"/></defs><circle id=\"big\" r=\"1\"/>\
<path fill=\"url(#g)\" d=\"M0 0h4\"/><use href=\"#big\"/></svg>"
)
}
/// A detail drawing naming the main drawing's group, which it does not define.
fn cross_view_drawing() -> String {
format!("{OPEN}{}</svg>", "<use href=\"#big\"/>".repeat(256))
}
fn name(text: &str) -> Value {
json!({ "fr": text, "en": text })
}
fn document() -> String {
json!({
"schema_version": 2, "species_id": "canine", "name": name("Chien"),
"description": {}, "scope_disclaimer": { "fr": "Outil", "en": "Tool" },
"attribution": { "authors": ["A"], "license": null, "notes": null },
"vertebral_config": { "regions": [] }, "references": [],
"categories": [{ "id": "c", "name": name("C"), "color": null }],
"views": [
{ "id": "main", "kind": "main", "name": name("Vue"), "svg_asset_id": MAIN_ASSET, "view_box": null },
{ "id": "detail", "kind": "detail", "name": name("Tête"), "svg_asset_id": DETAIL_ASSET,
"view_box": null, "parent_view_id": "main" }
],
"annotations": [], "finding_zones": []
})
.to_string()
}
fn drawing(asset_id: &str, text: &str) -> PreviewDrawing {
PreviewDrawing {
asset_id: asset_id.to_owned(),
sha256: sha256_hex(text.as_bytes()),
bytes: text.as_bytes().to_vec(),
}
}
fn preview(detail: &str) -> PreviewSheet {
let input = PreviewInput {
status: PreviewStatus::Draft,
document: document(),
fingerprint: None,
};
let drawings = vec![
drawing(MAIN_ASSET, &main_drawing()),
drawing(DETAIL_ASSET, detail),
];
PreviewSheet::load(input, drawings).unwrap()
}
fn canvas_outcome(preview: &PreviewSheet, view: &str) -> Value {
let input = json!({ "viewId": view }).to_string();
serde_json::from_str(&call_with_preview(preview, "view.canvas", &input)).unwrap()
}
fn canvas(preview: &PreviewSheet, view: &str) -> String {
let outcome = canvas_outcome(preview, view);
assert_eq!(outcome["ok"], json!(true), "{outcome}");
outcome["value"]["svg"].as_str().unwrap().to_owned()
}
/// Ids in document order, and every reference (`href`, `xlink:href`, `url(#…)`).
fn ids_and_references(element: &Element, ids: &mut Vec<String>, refs: &mut Vec<String>) {
for attr in &element.attrs {
match attr.qname.as_str() {
"id" => ids.push(attr.value.clone()),
"href" | "xlink:href" => {
if let Some(id) = local_reference_text(&attr.value).strip_prefix('#') {
refs.push(id.to_owned());
}
}
_ => refs.extend(url_targets(&attr.value)),
}
}
for child in element.element_children() {
ids_and_references(child, ids, refs);
}
}
fn parsed(text: &str) -> (Vec<String>, Vec<String>) {
let (mut ids, mut refs) = (Vec::new(), Vec::new());
ids_and_references(&parse_svg(text).unwrap(), &mut ids, &mut refs);
(ids, refs)
}
#[test]
fn a_valid_local_reference_keeps_working_inside_its_view() {
let preview = preview(&detail_drawing());
let main = canvas(&preview, "main");
let (ids, refs) = parsed(&main);
assert!(ids.iter().all(|id| id.starts_with("fv.main.")), "{ids:?}");
assert!(!refs.is_empty());
for reference in &refs {
assert!(
ids.contains(reference),
"{reference} resolves in its canvas"
);
}
// The canvas reads back through the one reader: no reference dangles, none cycles.
assert!(read_svg(&main).is_ok());
}
#[test]
fn several_references_to_one_id_all_name_its_scoped_id() {
let main = canvas(&preview(&detail_drawing()), "main");
let (_, refs) = parsed(&main);
let count = |id: &str| refs.iter().filter(|r| r.as_str() == id).count();
assert_eq!(count("fv.main.big"), 2);
assert_eq!(count("fv.main.g"), 3);
assert_eq!(refs.len(), 5);
assert!(main.contains("url( '#fv.main.g')") && main.contains("fill:url(#fv.main.g)"));
}
#[test]
fn a_reference_to_an_absent_id_is_refused_everywhere() {
let dangling = format!("{OPEN}<path id=\"p\" fill=\"url(#missing)\"/><use href=\"#p\"/></svg>");
assert_eq!(
read_svg(&dangling).err(),
Some(SvgRejection::DanglingReference)
);
let cleaning = clean_svg(dangling.as_bytes());
assert_eq!(cleaning.outcome, CleaningOutcome::Rejected);
assert_eq!(cleaning.reason.as_deref(), Some("dangling_reference"));
assert!(cleaning.preview.is_none() && cleaning.sha256.is_none());
// The preview reports the drawing and draws nothing from it; the other view still draws.
let preview = preview(&dangling);
let state = preview.state().unwrap();
let detail = state
.drawings
.iter()
.find(|d| d.asset_id == DETAIL_ASSET)
.unwrap();
assert_eq!(detail.state, PreviewDrawingStatus::Rejected);
assert_eq!(detail.detail.as_deref(), Some("dangling_reference"));
let refused = canvas_outcome(&preview, "detail");
assert_eq!(
(refused["kind"].as_str(), refused["detail"].as_str()),
(Some("svg_rejected"), Some("dangling_reference"))
);
canvas(&preview, "main");
// The verdict refuses the stored drawing.
let main = main_drawing();
let document = document();
let row = |asset_id: &'static str, text: &str| VerdictDrawing {
asset_id,
sha256: Box::leak(sha256_hex(text.as_bytes()).into_boxed_str()),
byte_size: text.len() as u64,
bytes: Some(Box::leak(text.as_bytes().to_vec().into_boxed_slice())),
};
let verdict = compute_verdict(&VerdictInput {
binding: VerdictBinding {
sheet_id: "s".to_owned(),
version_id: "v".to_owned(),
revision: 1,
review_id: "r".to_owned(),
},
document: &document,
base_document: None,
drawings: vec![row(MAIN_ASSET, &main), row(DETAIL_ASSET, &dangling)],
});
assert!(verdict.failures.iter().any(|f| f == codes::SVG_REJECTED));
let checked = verdict
.drawings
.iter()
.find(|d| d.asset_id == DETAIL_ASSET)
.unwrap();
assert_eq!(checked.result, DrawingResult::SvgRejected);
assert_eq!(checked.detail.as_deref(), Some("dangling_reference"));
}
#[test]
fn a_view_cannot_name_an_element_of_another_view() {
let cross = cross_view_drawing();
assert_eq!(
read_svg(&cross).err(),
Some(SvgRejection::DanglingReference)
);
assert_eq!(
clean_svg(cross.as_bytes()).reason.as_deref(),
Some("dangling_reference")
);
let refused = canvas_outcome(&preview(&cross), "detail");
assert_eq!(refused["detail"], json!("dangling_reference"));
}
#[test]
fn identical_ids_in_two_views_resolve_each_in_its_own_view() {
let preview = preview(&detail_drawing());
let canvases = [canvas(&preview, "main"), canvas(&preview, "detail")];
// The page as a browser reads it: both canvases inlined, `#id` naming the first element
// with that id in document order.
let mut first_owner: HashMap<String, usize> = HashMap::new();
let mut references: Vec<(usize, String)> = Vec::new();
for (index, text) in canvases.iter().enumerate() {
let (ids, refs) = parsed(text);
for id in ids {
first_owner.entry(id).or_insert(index);
}
references.extend(refs.into_iter().map(|r| (index, r)));
}
assert!(references.iter().any(|(i, _)| *i == 1));
for (index, reference) in &references {
assert_eq!(first_owner.get(reference), Some(index), "{reference}");
}
let (main_ids, _) = parsed(&canvases[0]);
let (detail_ids, _) = parsed(&canvases[1]);
assert!(main_ids.iter().all(|id| !detail_ids.contains(id)));
assert!(detail_ids.contains(&"fv.detail.g".to_owned()));
}
#[test]
fn composition_is_deterministic_and_repeatable() {
let preview = preview(&detail_drawing());
let first = (canvas(&preview, "main"), canvas(&preview, "detail"));
let again = (canvas(&preview, "detail"), canvas(&preview, "main"));
assert_eq!(first, (again.1, again.0));
let other = self::preview(&detail_drawing());
assert_eq!(canvas(&other, "main"), first.0);
// Scoping is applied once per composition, never compounded.
assert!(!first.0.contains("fv.main.fv.main."));
// The stored bytes are not touched: the drawing still hashes to its row.
let state = preview.state().unwrap();
assert!(
state
.drawings
.iter()
.all(|d| d.state == PreviewDrawingStatus::Ok)
);
assert_eq!(preview.drawing_reads(), 2);
}
/// Every reference of `text` as a browser reads it, written apart from the core's reader:
/// each `href="…"` and each `url(…)` (any case), quotes and CSS whitespace trimmed, tab and
/// newline removed and `%XX` decoded as the URL parser does. Answers the fragment ids.
fn browser_references(text: &str) -> Vec<String> {
let normalise = |raw: &str| {
let trimmed = raw.trim_matches(|c: char| c.is_ascii_whitespace() || c == '\'' || c == '"');
let cleaned: String = trimmed
.chars()
.filter(|c| !matches!(c, '\t' | '\n' | '\r'))
.collect();
let mut bytes = Vec::new();
let raw = cleaned.as_bytes();
let mut i = 0;
while i < raw.len() {
let hex = raw
.get(i + 1..i + 3)
.and_then(|h| std::str::from_utf8(h).ok());
match (raw[i], hex.and_then(|h| u8::from_str_radix(h, 16).ok())) {
(b'%', Some(byte)) => {
bytes.push(byte);
i += 3;
}
(byte, _) => {
bytes.push(byte);
i += 1;
}
}
}
String::from_utf8_lossy(&bytes).into_owned()
};
let mut out = Vec::new();
for (index, _) in text.match_indices("href=\"") {
let rest = &text[index + 6..];
out.push(normalise(&rest[..rest.find('"').unwrap()]));
}
let lower = text.to_ascii_lowercase();
for (index, _) in lower.match_indices("url(") {
let rest = &text[index + 4..];
out.push(normalise(&rest[..rest.find(')').unwrap_or(rest.len())]));
}
out.into_iter()
.map(|reference| reference.strip_prefix('#').unwrap_or(&reference).to_owned())
.collect()
}
#[test]
fn every_reference_a_browser_reads_stays_in_its_view() {
let preview = preview(&detail_drawing());
for view in ["main", "detail"] {
let text = canvas(&preview, view);
let references = browser_references(&text);
assert!(references.len() >= 2, "{view}");
for reference in references {
assert!(
reference.starts_with(&format!("fv.{view}.")),
"{view}: {reference}"
);
}
}
// The hostile spellings never reach a canvas: the drawing is refused, nothing composed.
for value in ["url(#%66v.main.g)", "url(\'#\tg\')", "url(#%67)"] {
let hostile =
format!("{OPEN}<radialGradient id=\"g\"/><path fill=\"{value}\" d=\"M0 0\"/></svg>");
let refused = canvas_outcome(&self::preview(&hostile), "detail");
assert_eq!(refused["kind"], json!("svg_rejected"), "{value}");
}
}