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.
This commit is contained in:
bchanot committed 2026-10-30 18:56:48 +01:00
1 parent 81f7639c75
commit d8562f60f5
14 files changed
+509 -169

No files matched your search

+12
View File
@@ -13,12 +13,15 @@
//! own and keeps the drawing's ids, so it never holds one the composition writes
//! (`svg::refs::RESERVED_IDS`, the halo filter): the reader refuses such a drawing and both
//! composers refuse such a tree.
//! Both forms append the marker layer as the root's last child, so the root never hides it: a
//! root `visibility` other than `visible` is refused by the reader and by both composers.
use std::collections::HashSet;
use super::layer::{LayerError, find_view, render_layer, view_box_of};
pub use super::svg::refs::HALO_FILTER_ID;
use super::svg::refs::holds_reserved_id;
use super::svg::sanitize::check_root_visibility;
use super::svg::sanitize::{local_reference_text, scope_url_targets, url_targets, urls_are_local};
use super::svg::serialize::is_xml_text;
use super::svg::{Element, Node};
@@ -44,6 +47,9 @@ pub enum ComposeError {
/// composes it. Fail-closed: the reader refuses it (`reserved_id`), so only a tree that did
/// not come out of `read_svg` reaches it, a composed view given back included.
ReservedId,
/// The drawing's root carries a `visibility` other than `visible`, which the marker layer
/// would inherit. Fail-closed: the reader refuses it (`root_visibility`).
RootVisibility,
}
impl From<LayerError> for ComposeError {
@@ -82,6 +88,9 @@ pub fn compose_canvas(
if holds_reserved_id(asset) {
return Err(ComposeError::ReservedId);
}
if check_root_visibility(asset).is_err() {
return Err(ComposeError::RootVisibility);
}
let mut root = Element {
qname: "svg".to_owned(),
namespace: asset.namespace.clone(),
@@ -171,6 +180,9 @@ pub fn compose_highlight(
if holds_reserved_id(&asset) {
return Err(ComposeError::ReservedId);
}
if check_root_visibility(&asset).is_err() {
return Err(ComposeError::RootVisibility);
}
if let Some(view_box) = view_box_of(view) {
asset.set_attr("viewBox", view_box);
}
+7 -3
View File
@@ -6,7 +6,8 @@
//! instruction (`svg_active_content`, the names in `active`, a PI as `?<target>`), or, once
//! no active content is found, a reference to an id the drawing does not define, in the
//! file or after a removal (`dangling_reference`), then an id the composition writes
//! (`reserved_id`, `refs::RESERVED_IDS`); no cleaning is offered;
//! (`reserved_id`, `refs::RESERVED_IDS`), then a root `visibility` other than `visible`
//! (`root_visibility`); no cleaning is offered;
//! - cleanable: only other removals (editor metadata and namespaces, `data-*`, `<style>`,
//! `class` or `style` on the root, ids outside the grammar, unsupported elements, long
//! titles or descriptions): the admin confirms them;
@@ -25,6 +26,7 @@ use ts_rs::TS;
use super::prescan::SVG_CAPS;
use super::refs::{check_reserved_ids, check_targets};
use super::sanitize::check_root_visibility;
use super::serialize::{serialize, stored_form};
use super::{processing_instructions, read_svg, read_svg_for_cleaning};
use crate::domain::sheet::verdict::sha256_hex;
@@ -100,8 +102,10 @@ pub fn clean_svg(bytes: &[u8]) -> SvgCleaning {
if !active.is_empty() {
return rejected(ACTIVE_CONTENT, read.removed, active);
}
if let Err(rejection) = check_targets(&read.root).and_then(|()| check_reserved_ids(&read.root))
{
let checked = check_targets(&read.root)
.and_then(|()| check_reserved_ids(&read.root))
.and_then(|()| check_root_visibility(&read.root));
if let Err(rejection) = checked {
return rejected(rejection.reason(), read.removed, read.active);
}
let preview = serialize(&read.root);
+5 -3
View File
@@ -13,19 +13,21 @@ pub use sanitize::Sanitized;
pub use tree::{Element, Node, SvgRejection};
/// Bounds, parses, sanitises and checks the references of an SVG text: no cycle, within the
/// expansion budget, each naming an id the drawing defines; and no id the composition writes.
/// expansion budget, each naming an id the drawing defines; no id the composition writes and
/// no root `visibility` the marker layer would inherit.
pub fn read_svg(text: &str) -> Result<Sanitized, SvgRejection> {
let root = tree::parse_svg(text)?;
let sanitized = sanitize::sanitize(root)?;
refs::check_references(&sanitized.root)?;
refs::check_targets(&sanitized.root)?;
refs::check_reserved_ids(&sanitized.root)?;
sanitize::check_root_visibility(&sanitized.root)?;
Ok(sanitized)
}
/// `read_svg` as the cleaning reads a file picked for upload: an oversized `title` or `desc`
/// is a removal, not a refusal (`sanitize::sanitize_for_cleaning`); the targets and the
/// reserved ids are checked by the cleaning after it has classified active content
/// is a removal, not a refusal (`sanitize::sanitize_for_cleaning`); the targets, the reserved
/// ids and the root's visibility are checked by the cleaning after it has classified active content
/// (`clean::clean_svg`).
pub fn read_svg_for_cleaning(text: &str) -> Result<Sanitized, SvgRejection> {
let root = tree::parse_svg(text)?;
+19
View File
@@ -434,6 +434,25 @@ fn value_acceptable(qname: &str, value: &str) -> bool {
}
}
/// The root lets the engine's marker layer show: no `visibility`, or `visible` (CSS whitespace
/// and letter case aside). Both composers append the layer as the root's last child, so it
/// inherits the root's `visibility`, which the drawing's own children can set back to
/// `visible`: any other value, `hidden`, `collapse`, a CSS-wide keyword or an unreadable one,
/// is refused (V1-2.2 security review, owner brief 2026-10-30). The root's `style` and `class`
/// are removed by `sanitize`, so this attribute is the one way left to set it.
pub fn check_root_visibility(root: &Element) -> Result<(), SvgRejection> {
let visible = root.attr("visibility").is_none_or(|value| {
value
.trim_matches(is_css_space)
.eq_ignore_ascii_case("visible")
});
if visible {
Ok(())
} else {
Err(SvgRejection::RootVisibility)
}
}
/// CSS whitespace (what the tokenizer skips inside `url(`).
fn is_css_space(c: char) -> bool {
matches!(c, ' ' | '\t' | '\n' | '\r' | '\x0C')
+5
View File
@@ -111,6 +111,10 @@ pub enum SvgRejection {
/// An id the composition writes into the drawing's own document (`refs::RESERVED_IDS`):
/// the drawing's element would stand in for the engine's (V1-2.2, owner brief 2026-10-30).
ReservedId,
/// A `visibility` on the root other than `visible`: the engine's marker layer, appended as
/// the root's last child, inherits it, while the drawing's own children can set `visible`
/// back (V1-2.2 security review, owner brief 2026-10-30).
RootVisibility,
}
impl SvgRejection {
@@ -127,6 +131,7 @@ impl SvgRejection {
Self::ReferenceCycle => "reference_cycle",
Self::DanglingReference => "dangling_reference",
Self::ReservedId => "reserved_id",
Self::RootVisibility => "root_visibility",
}
}
}
+1
View File
@@ -479,6 +479,7 @@ fn canvas_of<'a>(
ComposeError::InvalidCharacter => Failure::new("invalid_character", view_id),
ComposeError::UnscopedReference => Failure::new("svg_rejected", "unscoped_reference"),
ComposeError::ReservedId => Failure::new("svg_rejected", "reserved_id"),
ComposeError::RootVisibility => Failure::new("svg_rejected", "root_visibility"),
})?;
let svg = serialize(&canvas);
if svg.len() > MAX_COMPOSED_BYTES {
+1
View File
@@ -7,6 +7,7 @@
)]
pub mod r4;
pub mod sheet_readers;
pub mod svg_tree;
use faunosteo_core::domain::js::{find_lone_surrogate, parse_json};
+160
View File
@@ -0,0 +1,160 @@
//! The product's readers of one drawing, for the reader-rule suites (`svg_reserved_ids`,
//! `svg_root_visibility`): a two-view sheet whose main view carries one point marker, its
//! preview, canvas and verdict, and the assertion that every reader refuses a drawing.
#![allow(dead_code, clippy::unwrap_used, clippy::expect_used)]
use faunosteo_core::anatomy::svg::clean::{CleaningOutcome, clean_svg};
use faunosteo_core::anatomy::svg::{Element, SvgRejection, read_svg};
use faunosteo_core::domain::sheet::AnatomicalSheetDocument;
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};
pub const MAIN_ASSET: &str = "11111111-2222-4333-8444-555555555555";
pub const DETAIL_ASSET: &str = "66666666-7777-4888-9999-aaaaaaaaaaaa";
pub 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">"#
);
pub fn svg(body: &str) -> String {
format!("{OPEN}{body}</svg>")
}
pub fn name(text: &str) -> Value {
json!({ "fr": text, "en": text })
}
/// A sheet with a main view (one point marker) and a detail view.
pub 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": [{
"id": "hock", "kind": "point", "view_id": "main", "category_id": "c",
"laterality": "unpaired", "geometry": { "type": "circle", "cx": 5, "cy": 5, "r": 1 },
"review_status": "reviewed", "name": name("Jarret"), "finding_zone_id": null,
"vertebral_region_code": null
}],
"finding_zones": []
})
.to_string()
}
pub fn sheet() -> AnatomicalSheetDocument {
serde_json::from_str(&document()).unwrap()
}
pub 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(),
}
}
pub fn preview(detail: &str) -> PreviewSheet {
let input = PreviewInput {
status: PreviewStatus::Draft,
document: document(),
fingerprint: None,
};
let main = svg("<path d=\"M0 0h1\"/>");
let drawings = vec![drawing(MAIN_ASSET, &main), drawing(DETAIL_ASSET, detail)];
PreviewSheet::load(input, drawings).unwrap()
}
pub 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()
}
pub fn verdict_detail(detail: &str) -> (bool, DrawingResult, Option<String>) {
let main = svg("<path d=\"M0 0h1\"/>");
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, detail)],
});
let checked = verdict
.drawings
.iter()
.find(|d| d.asset_id == DETAIL_ASSET)
.unwrap();
(
verdict.failures.iter().any(|f| f == codes::SVG_REJECTED),
checked.result,
checked.detail.clone(),
)
}
/// Every element holding `id`, in document order.
pub fn holders<'a>(element: &'a Element, id: &str, out: &mut Vec<&'a Element>) {
if element.attr("id") == Some(id) {
out.push(element);
}
for child in element.element_children() {
holders(child, id, out);
}
}
/// The drawing is refused with `reason` by every reader of the product: the reader, the
/// cleaning (no stored form), the preview and its canvas, the verdict.
pub fn assert_refused_everywhere(text: &str, reason: &str) {
assert_eq!(
read_svg(text).err().map(SvgRejection::reason),
Some(reason),
"{text}"
);
let cleaning = clean_svg(text.as_bytes());
assert_eq!(cleaning.outcome, CleaningOutcome::Rejected, "{text}");
assert_eq!(cleaning.reason.as_deref(), Some(reason), "{text}");
assert!(cleaning.preview.is_none() && cleaning.stored.is_none() && cleaning.sha256.is_none());
let preview = preview(text);
let state = preview.state().unwrap();
let detail = state
.drawings
.iter()
.find(|d| d.asset_id == DETAIL_ASSET)
.unwrap();
assert_eq!(detail.state, PreviewDrawingStatus::Rejected, "{text}");
assert_eq!(detail.detail.as_deref(), Some(reason), "{text}");
let refused = canvas_outcome(&preview, "detail");
assert_eq!(
(refused["kind"].as_str(), refused["detail"].as_str()),
(Some("svg_rejected"), Some(reason)),
"{text}"
);
let (failed, result, detail) = verdict_detail(text);
assert!(failed, "{text}");
assert_eq!(result, DrawingResult::SvgRejected, "{text}");
assert_eq!(detail.as_deref(), Some(reason), "{text}");
}
+5 -3
View File
@@ -30,9 +30,11 @@ covered above by a real 1.4.3 export). The owner opens `inkscape-source.svg` in
exports it unchanged and puts the files in `owner/`, named `<tool>-<version>-<date>-<variant>.svg`;
`owner/README.md` gives the exact steps. The suite reads every file there: each must be refused
(with a closed reason) or cleaned into a stored form that reads back with no removal, and a file
whose name contains `-active-` must be refused for active content. A6 (owner, 2026-10-30)
requires Figma and the real Adobe Illustrator; Affinity is optional. Status: Figma committed
and passing, Illustrator awaited, so A6 stays open.
whose name contains `-active-` must be refused for active content. A6's tested perimeter
(owner's final decision, 2026-10-30) is Figma, Inkscape, cairo and ImageMagick, all real
exports in this folder and in `owner/`. Adobe Illustrator and Affinity are optional: no
compatibility is claimed for either until a real export of it is committed here and read by
the suite.
| File | Tool | Expected |
|---|---|---|
+6 -5
View File
@@ -17,10 +17,11 @@ differently, and I could not check them here.
## Illustrator (Fichier › Ouvrir… a copy of `inkscape-source.svg`)
Required for A6 (owner, 2026-10-30), and only from the real Adobe Illustrator:
VectorCraft or another look-alike is not equivalent. Two files are still needed,
`…-presentation.svg` and `…-internal-css.svg`; until both are committed and read
by the suite, A6 stays open.
Optional since the owner's final decision of 2026-10-30: A6 is met without it, and
no Illustrator compatibility is claimed until real exports are committed here and
read by the suite. Only the real Adobe Illustrator counts: VectorCraft or another
look-alike is not equivalent. The two files to export, when it is tested, are
`…-presentation.svg` and `…-internal-css.svg`.
1. Copy `../inkscape-source.svg` outside the repository and open the copy
(File › Open…): a Save in Illustrator would overwrite the file it opened, and
@@ -67,7 +68,7 @@ Done on 2026-10-30: `figma-web-20261030-default.svg` and `figma-web-20261030-ids
- `…-ids.svg`: « Include "id" attribute » ticked, « Outline text » unticked
(text kept as text).
## Affinity (optional since the owner's decision of 2026-10-30)
## Affinity (optional, owner decisions of 2026-10-30)
File › Open `inkscape-source.svg`, then File › Export › SVG, preset « SVG (for
web) » (`…-web.svg`); if offered, a second with « SVG (digital – high quality) »
+26
View File
@@ -490,3 +490,29 @@ fn holders<'a>(element: &'a Element, id: &str, out: &mut Vec<&'a Element>) {
holders(child, id, out);
}
}
/// V1-2.2 owner brief 2026-10-30 (root visibility, `tests/svg_root_visibility.rs`): a snapshot
/// drawing whose root is not `visible`, its children set `visible` back, is refused at the gate
/// (`snapshot_invalid`, `asset root_visibility`): its markers would not show in the PDF.
#[test]
fn the_pdf_refuses_a_drawing_whose_root_hides_the_markers() {
for value in ["hidden", "collapse", "HIDDEN", "inherit"] {
let edit = move |svg: &str| {
let tagged = svg.replacen("<svg", &format!("<svg visibility=\"{value}\""), 1);
let open = tagged.find("<svg").unwrap();
let end = open + tagged[open..].find('>').unwrap() + 1;
format!(
"{}<g visibility=\"visible\">{}</g></svg>",
&tagged[..end],
tagged[end..].trim_end().trim_end_matches("</svg>")
)
};
match export_with_drawing(edit) {
Err(error) => {
assert_eq!(error.kind, ExportErrorKind::SnapshotInvalid, "{value}");
assert_eq!(error.detail, "asset root_visibility", "{value}");
}
Ok(_) => panic!("{value}: composed"),
}
}
}
+16 -155
View File
@@ -12,135 +12,30 @@ 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::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 faunosteo_core::domain::sheet::verdict::{DrawingResult, sha256_hex};
use serde::Deserialize;
use serde_json::{Value, json};
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";
const MAIN_ASSET: &str = "11111111-2222-4333-8444-555555555555";
const DETAIL_ASSET: &str = "66666666-7777-4888-9999-aaaaaaaaaaaa";
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">"#
);
/// 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>";
fn svg(body: &str) -> String {
format!("{OPEN}{body}</svg>")
}
fn name(text: &str) -> Value {
json!({ "fr": text, "en": text })
}
/// A sheet with a main view (one point marker) and a detail view.
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": [{
"id": "hock", "kind": "point", "view_id": "main", "category_id": "c",
"laterality": "unpaired", "geometry": { "type": "circle", "cx": 5, "cy": 5, "r": 1 },
"review_status": "reviewed", "name": name("Jarret"), "finding_zone_id": null,
"vertebral_region_code": null
}],
"finding_zones": []
})
.to_string()
}
fn sheet() -> AnatomicalSheetDocument {
serde_json::from_str(&document()).unwrap()
}
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 main = svg("<path d=\"M0 0h1\"/>");
let drawings = vec![drawing(MAIN_ASSET, &main), 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 verdict_detail(detail: &str) -> (bool, DrawingResult, Option<String>) {
let main = svg("<path d=\"M0 0h1\"/>");
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, detail)],
});
let checked = verdict
.drawings
.iter()
.find(|d| d.asset_id == DETAIL_ASSET)
.unwrap();
(
verdict.failures.iter().any(|f| f == codes::SVG_REJECTED),
checked.result,
checked.detail.clone(),
)
}
/// Every element holding `id`, in document order.
fn holders<'a>(element: &'a Element, id: &str, out: &mut Vec<&'a Element>) {
if element.attr("id") == Some(id) {
out.push(element);
}
for child in element.element_children() {
holders(child, id, out);
}
/// 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.
@@ -149,40 +44,6 @@ fn free_of_reserved(element: &Element) -> bool {
&& element.element_children().all(free_of_reserved)
}
/// The drawing is refused `reserved_id` by every reader of the product.
fn assert_refused_everywhere(text: &str) {
assert_eq!(
read_svg(text).err(),
Some(SvgRejection::ReservedId),
"{text}"
);
let cleaning = clean_svg(text.as_bytes());
assert_eq!(cleaning.outcome, CleaningOutcome::Rejected, "{text}");
assert_eq!(cleaning.reason.as_deref(), Some("reserved_id"), "{text}");
assert!(cleaning.preview.is_none() && cleaning.stored.is_none() && cleaning.sha256.is_none());
let preview = preview(text);
let state = preview.state().unwrap();
let detail = state
.drawings
.iter()
.find(|d| d.asset_id == DETAIL_ASSET)
.unwrap();
assert_eq!(detail.state, PreviewDrawingStatus::Rejected, "{text}");
assert_eq!(detail.detail.as_deref(), Some("reserved_id"), "{text}");
let refused = canvas_outcome(&preview, "detail");
assert_eq!(
(refused["kind"].as_str(), refused["detail"].as_str()),
(Some("svg_rejected"), Some("reserved_id")),
"{text}"
);
let (failed, result, reason) = verdict_detail(text);
assert!(failed, "{text}");
assert_eq!(result, DrawingResult::SvgRejected, "{text}");
assert_eq!(reason.as_deref(), Some("reserved_id"), "{text}");
}
#[test]
fn the_reserved_set_is_the_halo_filter_alone() {
assert_eq!(RESERVED_IDS, ["osteo-halo"]);
@@ -249,11 +110,11 @@ fn a_drawing_without_a_reserved_id_is_accepted_and_gets_the_engine_halo() {
/// 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(&svg(ERASER));
assert_refused_everywhere(&svg(&format!(
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(&svg(
assert_refused_everywhere_id(&svg(
"<filter id=\"osteo-halo\"><feGaussianBlur stdDeviation=\"18\"/></filter>",
));
}
@@ -287,10 +148,10 @@ fn the_reserved_id_on_any_kept_element_is_refused() {
"<g><g><g><path id=\"osteo-halo\" d=\"M0 0h1\"/></g></g></g>",
];
for body in elements {
assert_refused_everywhere(&svg(body));
assert_refused_everywhere_id(&svg(body));
}
let root = OPEN.replace("viewBox", "id=\"osteo-halo\" viewBox");
assert_refused_everywhere(&format!("{root}<path d=\"M0 0h1\"/></svg>"));
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
@@ -322,7 +183,7 @@ fn references_to_the_reserved_id_are_refused() {
Some("dangling_reference"),
"{reference}"
);
assert_refused_everywhere(&svg(&format!(
assert_refused_everywhere_id(&svg(&format!(
"<defs><filter id=\"osteo-halo\"/><g id=\"OSTEO-HALO\"/></defs>{reference}"
)));
}
@@ -344,7 +205,7 @@ fn adversarial_spellings_never_reach_the_composition() {
"oSTEO-hALO",
];
for id in decoded_to_reserved {
assert_refused_everywhere(&svg(&format!("<g id=\"{id}\"/>")));
assert_refused_everywhere_id(&svg(&format!("<g id=\"{id}\"/>")));
}
let removed = [
+240
View File
@@ -0,0 +1,240 @@
//! V1-2.2 owner brief 2026-10-30: the drawing's root never decides whether the engine's markers
//! show. Both composers append the marker layer as the root's last child (the PDF view keeps the
//! drawing's root, the canvas copies its attributes), so the layer inherits the root's
//! `visibility`; a drawing `<svg visibility="hidden">` whose children set `visible` back read
//! clean before and showed its drawing without a single marker (security review, MEDIUM). The
//! reader refuses a root `visibility` other than `visible` (`root_visibility`); the cleaning,
//! the preview, the verdict and the PDF snapshot gate answer it; both composers refuse such a
//! root. The other root properties are either removed by the reader already or affect the
//! drawing and the markers alike (see `other_root_properties_*`).
#![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, preview, sheet, 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::tree::parse_svg;
use faunosteo_core::anatomy::svg::{Element, read_svg};
use faunosteo_core::domain::sheet::verdict::DrawingResult;
use serde_json::json;
const BODY: &str = "<g visibility=\"visible\"><path d=\"M0 0h10v10z\"/></g>";
/// A drawing whose root opening tag carries `attrs`.
fn rooted(attrs: &str, body: &str) -> String {
let root = OPEN.replace("viewBox", &format!("{attrs} viewBox"));
format!("{root}{body}</svg>")
}
/// The composed view's marker layer is its root's last child and the root lets it show.
fn layer_shows(composed: &Element) -> bool {
let layer = composed.element_children().last().unwrap();
let root_visible = composed
.attr("visibility")
.is_none_or(|v| v.trim().eq_ignore_ascii_case("visible"));
layer.element_children().count() > 0 && root_visible
}
fn compose_both(tree: &Element) -> (Result<Element, ComposeError>, Result<Element, ComposeError>) {
let sheet = sheet();
let ids: HashSet<&str> = ["hock"].into_iter().collect();
(
compose_canvas(&sheet, "main", tree),
compose_highlight(&sheet, "main", tree.clone(), &ids, true),
)
}
#[test]
fn a_drawing_without_root_visibility_shows_its_markers() {
for root in [
"",
"visibility=\"visible\"",
"visibility=\"Visible\"",
"visibility=\" visible\t\"",
] {
let text = rooted(root, BODY);
let read = read_svg(&text).unwrap_or_else(|e| panic!("{root}: {e:?}"));
assert!(read.removed.is_empty(), "{root}");
let cleaning = clean_svg(text.as_bytes());
assert_eq!(cleaning.outcome, CleaningOutcome::Clean, "{root}");
// The verdict and the preview read the stored form, as uploaded.
let stored = cleaning.stored.unwrap();
assert_eq!(
verdict_detail(&stored),
(false, DrawingResult::Ok, None),
"{root}"
);
assert_eq!(
canvas_outcome(&preview(&stored), "detail")["ok"],
json!(true),
"{root}"
);
let (canvas, highlight) = compose_both(&read.root);
assert!(layer_shows(&canvas.unwrap()), "{root}");
assert!(layer_shows(&highlight.unwrap()), "{root}");
}
}
/// The reported drawing and every spelling of a non-visible root: refused by every reader.
#[test]
fn a_root_visibility_other_than_visible_is_refused_everywhere() {
let values = [
"hidden",
"collapse",
"HIDDEN",
"Hidden",
" hidden ",
"hidden\n",
"hid&#100;en",
"&#104;&#105;&#100;&#100;&#101;&#110;",
"inherit",
"initial",
"unset",
"revert",
"hidden !important",
"visible hidden",
"visibl",
"",
];
let bodies = [
BODY,
"<g style=\"visibility:visible\"><path d=\"M0 0h10v10z\"/></g>",
"<path visibility=\"visible\" d=\"M0 0h10v10z\"/>",
"<path d=\"M0 0h10v10z\"/>",
];
for value in values {
for body in bodies {
assert_refused_everywhere(
&rooted(&format!("visibility=\"{value}\""), body),
"root_visibility",
);
}
}
}
/// The composers stay fail-closed on a root that did not come out of the reader.
#[test]
fn the_composers_never_give_the_layer_a_hidden_root() {
for value in ["hidden", "collapse", "HIDDEN", "inherit"] {
let tree = parse_svg(&rooted(&format!("visibility=\"{value}\""), BODY)).unwrap();
let (canvas, highlight) = compose_both(&tree);
assert_eq!(canvas.unwrap_err(), ComposeError::RootVisibility, "{value}");
assert_eq!(
highlight.unwrap_err(),
ComposeError::RootVisibility,
"{value}"
);
}
}
/// The same property written another way never reaches the root: a root `style` or `class`
/// and a `<style>` element are removed (the cleaning offers the drawing without them, and its
/// stored form reads back clean), and a descendant's `visibility` stays in the drawing, never
/// on the layer's ancestors.
#[test]
fn equivalent_styles_never_hide_the_layer() {
let cleanable = [
(rooted("style=\"visibility:hidden\"", BODY), "svg@style"),
(rooted("style=\"VISIBILITY: hidden\"", BODY), "svg@style"),
(rooted("class=\"invisible\"", BODY), "svg@class"),
(
rooted(
"",
&format!("<style>svg{{visibility:hidden}}</style>{BODY}"),
),
"style",
),
(
rooted(
"",
&format!("<style>:root{{visibility:collapse}}</style>{BODY}"),
),
"style",
),
];
for (text, removal) in &cleanable {
let read = read_svg(text).unwrap();
assert!(
read.removed.iter().any(|r| r == removal),
"{text}: {:?}",
read.removed
);
let cleaning = clean_svg(text.as_bytes());
assert_eq!(cleaning.outcome, CleaningOutcome::Cleanable, "{text}");
let stored = cleaning.stored.unwrap();
let again = clean_svg(stored.as_bytes());
assert_eq!(
(again.outcome, again.stored.as_deref()),
(CleaningOutcome::Clean, Some(stored.as_str())),
"the stored form is a fixpoint: {text}"
);
let (canvas, highlight) = compose_both(&read_svg(&stored).unwrap().root);
assert!(
layer_shows(&canvas.unwrap()) && layer_shows(&highlight.unwrap()),
"{text}"
);
}
let descendant = rooted(
"",
"<g visibility=\"hidden\"><path d=\"M0 0h10v10z\"/></g><path style=\"visibility:collapse\" d=\"M0 0h1\"/>",
);
let read = read_svg(&descendant).unwrap();
assert!(read.removed.is_empty());
let (canvas, highlight) = compose_both(&read.root);
assert!(layer_shows(&canvas.unwrap()) && layer_shows(&highlight.unwrap()));
}
/// The other root properties that reach the layer. Removed by the reader before V1-2.2: the
/// paint servers and effects (`filter`, `mask`, `clip-path`), `transform`, `class`, `style`.
/// Kept: `opacity` and `display` act on the whole root, drawing and markers alike (the
/// browser proofs of RUST.md §12.10 show both); `fill` and `fill-opacity` are set on every PDF
/// marker. The stroke properties no marker sets (`stroke-opacity`, `stroke-dasharray`,
/// `stroke-width` on the hitbox) are an open owner decision, not covered here.
#[test]
fn other_root_properties_are_removed_or_act_on_the_whole_view() {
for name in ["filter", "mask", "clip-path"] {
let text = rooted(
&format!("{name}=\"url(#m)\""),
&format!("<mask id=\"m\"/>{BODY}"),
);
let read = read_svg(&text).unwrap();
assert!(read.removed.contains(&format!("svg@{name}")), "{name}");
assert!(read.root.attr(name).is_none(), "{name}");
}
let read = read_svg(&rooted("transform=\"scale(0)\"", BODY)).unwrap();
assert_eq!(read.removed, ["svg@transform"]);
for root in [
"opacity=\"0\"",
"display=\"none\"",
"fill=\"none\"",
"fill-opacity=\"0\"",
] {
let read = read_svg(&rooted(root, BODY)).unwrap_or_else(|e| panic!("{root}: {e:?}"));
assert!(read.removed.is_empty(), "{root}");
let ids: HashSet<&str> = ["hock"].into_iter().collect();
let composed = compose_highlight(&sheet(), "main", read.root, &ids, true).unwrap();
for marker in composed
.element_children()
.last()
.unwrap()
.element_children()
{
assert!(marker.attr("fill").is_some() && marker.attr("fill-opacity").is_some());
}
}
}
#[test]
fn the_equine_drawing_has_no_root_visibility() {
let horse = common::repo_file("supabase/seed/anatomical-sheets/equine/draft/assets/horse.svg");
let read = read_svg(&horse).unwrap();
assert!(read.root.attr("visibility").is_none() && read.removed.is_empty());
let (canvas, highlight) = compose_both(&read.root);
assert!(canvas.is_ok() && highlight.is_ok());
}
+6
View File
@@ -171,6 +171,12 @@ describe('clean_svg through the shipped module', () => {
const reserved = new TextEncoder().encode(`<svg xmlns="http://www.w3.org/2000/svg"><filter id="${id}"/></svg>`)
expect(value(glue.clean_svg(reserved)).reason, id).toBe('reserved_id')
}
for (const visibility of ['hidden', 'COLLAPSE', 'inherit']) {
const hiding = new TextEncoder().encode(
`<svg xmlns="http://www.w3.org/2000/svg" visibility="${visibility}"><g visibility="visible"><path d="M0 0h1"/></g></svg>`,
)
expect(value(glue.clean_svg(hiding)).reason, visibility).toBe('root_visibility')
}
const cairo = value(
glue.clean_svg(new Uint8Array(readFileSync(path(`${EXPORTS}cairo-1.18.4-pycairo-1.27.0-shapes.svg`)))),
)