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.
This commit is contained in:
1 parent
2f1f0764bf
commit
08efd9a792
13 files changed
+781
-34
No files matched your search
@@ -10,11 +10,15 @@
|
||||
//! 2026-10-29), so a view never resolves into another view's drawing or the page, and the page
|
||||
//! never into a drawing. The reader already refused references to ids a drawing does not
|
||||
//! define. Stored bytes are never rewritten; the PDF view is rasterised as a document of its
|
||||
//! own and keeps the drawing's ids.
|
||||
//! 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.
|
||||
|
||||
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::{local_reference_text, scope_url_targets, url_targets, urls_are_local};
|
||||
use super::svg::serialize::is_xml_text;
|
||||
use super::svg::{Element, Node};
|
||||
@@ -22,7 +26,6 @@ use crate::domain::sheet::AnatomicalSheetDocument;
|
||||
|
||||
pub const HIGHLIGHT_FILL: &str = "#b85a3f";
|
||||
pub const HIGHLIGHT_FILL_OPACITY: &str = "0.85";
|
||||
pub const HALO_FILTER_ID: &str = "osteo-halo";
|
||||
const CANVAS_FALLBACK_VIEW_BOX: &str = "0 0 100 100";
|
||||
|
||||
/// Why a view cannot be composed.
|
||||
@@ -36,6 +39,11 @@ pub enum ComposeError {
|
||||
/// not read as a local reference (`sanitize::value_acceptable`), so only an element tree
|
||||
/// that did not come out of `read_svg` reaches it.
|
||||
UnscopedReference,
|
||||
/// The drawing holds an id the composition writes (`svg::refs::RESERVED_IDS`): in the PDF
|
||||
/// view its element would replace the halo filter or win its resolution; neither form
|
||||
/// 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,
|
||||
}
|
||||
|
||||
impl From<LayerError> for ComposeError {
|
||||
@@ -71,6 +79,9 @@ pub fn compose_canvas(
|
||||
asset: &Element,
|
||||
) -> Result<Element, ComposeError> {
|
||||
let view = find_view(document, view_id).ok_or(ComposeError::UnknownView)?;
|
||||
if holds_reserved_id(asset) {
|
||||
return Err(ComposeError::ReservedId);
|
||||
}
|
||||
let mut root = Element {
|
||||
qname: "svg".to_owned(),
|
||||
namespace: asset.namespace.clone(),
|
||||
@@ -147,7 +158,8 @@ fn scope_ids(element: &mut Element, scope: &str) {
|
||||
}
|
||||
|
||||
/// The PDF view of `view_id`: `asset` (sanitised, consumed) framed on the view, the markers
|
||||
/// of `annotation_ids` only, recoloured, with the halo filter when `halo`.
|
||||
/// of `annotation_ids` only, recoloured, with the halo filter when `halo`. The only element
|
||||
/// of the result holding a reserved id is the composition's own.
|
||||
pub fn compose_highlight(
|
||||
document: &AnatomicalSheetDocument,
|
||||
view_id: &str,
|
||||
@@ -156,13 +168,16 @@ pub fn compose_highlight(
|
||||
halo: bool,
|
||||
) -> Result<Element, ComposeError> {
|
||||
let view = find_view(document, view_id).ok_or(ComposeError::UnknownView)?;
|
||||
if holds_reserved_id(&asset) {
|
||||
return Err(ComposeError::ReservedId);
|
||||
}
|
||||
if let Some(view_box) = view_box_of(view) {
|
||||
asset.set_attr("viewBox", view_box);
|
||||
}
|
||||
asset.remove_attr("width");
|
||||
asset.remove_attr("height");
|
||||
if halo {
|
||||
ensure_halo_filter(&mut asset);
|
||||
add_halo_filter(&mut asset);
|
||||
}
|
||||
let layer = render_layer(document, view_id, &HashSet::new())?;
|
||||
let layer = highlight_layer(layer, annotation_ids, halo);
|
||||
@@ -198,24 +213,14 @@ fn highlight_element(mut element: Element, halo: bool) -> Element {
|
||||
element
|
||||
}
|
||||
|
||||
/// One halo filter per root: in the first `<defs>` of the drawing, else in a new `<defs>`
|
||||
/// placed first; nothing when a `filter#osteo-halo` already exists.
|
||||
fn ensure_halo_filter(root: &mut Element) {
|
||||
if has_halo_filter(root) {
|
||||
return;
|
||||
}
|
||||
/// The halo filter in the first `<defs>` of the drawing, else in a new `<defs>` placed first.
|
||||
fn add_halo_filter(root: &mut Element) {
|
||||
if !append_to_first_defs(root) {
|
||||
let defs = Element::svg("defs", Vec::new(), vec![Node::Element(halo_filter())]);
|
||||
root.children.insert(0, Node::Element(defs));
|
||||
}
|
||||
}
|
||||
|
||||
fn has_halo_filter(element: &Element) -> bool {
|
||||
element.element_children().any(|c| {
|
||||
(c.qname == "filter" && c.attr("id") == Some(HALO_FILTER_ID)) || has_halo_filter(c)
|
||||
})
|
||||
}
|
||||
|
||||
/// Appends the halo to the first `<defs>` below `element` (document order).
|
||||
fn append_to_first_defs(element: &mut Element) -> bool {
|
||||
for child in &mut element.children {
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
//! (`malformed`), or any removal of active or external content, or a processing
|
||||
//! 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`); no cleaning is offered;
|
||||
//! file or after a removal (`dangling_reference`), then an id the composition writes
|
||||
//! (`reserved_id`, `refs::RESERVED_IDS`); 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;
|
||||
@@ -23,7 +24,7 @@ use serde::Serialize;
|
||||
use ts_rs::TS;
|
||||
|
||||
use super::prescan::SVG_CAPS;
|
||||
use super::refs::check_targets;
|
||||
use super::refs::{check_reserved_ids, check_targets};
|
||||
use super::serialize::{serialize, stored_form};
|
||||
use super::{processing_instructions, read_svg, read_svg_for_cleaning};
|
||||
use crate::domain::sheet::verdict::sha256_hex;
|
||||
@@ -99,7 +100,8 @@ 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) {
|
||||
if let Err(rejection) = check_targets(&read.root).and_then(|()| check_reserved_ids(&read.root))
|
||||
{
|
||||
return rejected(rejection.reason(), read.removed, read.active);
|
||||
}
|
||||
let preview = serialize(&read.root);
|
||||
|
||||
@@ -13,18 +13,20 @@ 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.
|
||||
/// expansion budget, each naming an id the drawing defines; and no id the composition writes.
|
||||
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)?;
|
||||
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 are checked by
|
||||
/// the cleaning after it has classified active content (`clean::clean_svg`).
|
||||
/// 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
|
||||
/// (`clean::clean_svg`).
|
||||
pub fn read_svg_for_cleaning(text: &str) -> Result<Sanitized, SvgRejection> {
|
||||
let root = tree::parse_svg(text)?;
|
||||
let sanitized = sanitize::sanitize_for_cleaning(root)?;
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
//! chains are not bounded by the depth cap) and saturating, with an early exit.
|
||||
//! `check_targets` refuses a reference to an id the drawing does not define (owner decision
|
||||
//! 2026-10-29): once inlined in a page, `#id` would resolve against another view or the page.
|
||||
//! `check_reserved_ids` refuses an id the composition writes (owner brief 2026-10-30).
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
@@ -17,6 +18,39 @@ use super::tree::{Element, Node, SvgRejection};
|
||||
/// Expanded elements a drawing may instantiate (the product's drawing: a few thousand).
|
||||
pub const MAX_EXPANDED_ELEMENTS: u64 = 50_000;
|
||||
|
||||
/// The PDF highlight's filter (`compose::compose_highlight`), written into the drawing's own
|
||||
/// document: the PDF view keeps the drawing's ids.
|
||||
pub const HALO_FILTER_ID: &str = "osteo-halo";
|
||||
|
||||
/// Every id the composition writes next to the drawing's ids. A drawing defining one would
|
||||
/// replace the engine's element (a `filter#osteo-halo` of its own) or win its resolution (any
|
||||
/// element holding it before the engine's). Exact names, never a prefix: the historical
|
||||
/// drawings carry `osteo-overlays`.
|
||||
pub const RESERVED_IDS: [&str; 1] = [HALO_FILTER_ID];
|
||||
|
||||
/// `id` is a reserved id in any letter case. The reader keeps ASCII ids only
|
||||
/// (`sanitize::is_reference_name`), so no other spelling of one reaches the tree.
|
||||
pub fn is_reserved_id(id: &str) -> bool {
|
||||
RESERVED_IDS
|
||||
.iter()
|
||||
.any(|reserved| id.eq_ignore_ascii_case(reserved))
|
||||
}
|
||||
|
||||
/// No element of `root`, the root included, holds a reserved id.
|
||||
pub fn check_reserved_ids(root: &Element) -> Result<(), SvgRejection> {
|
||||
if holds_reserved_id(root) {
|
||||
Err(SvgRejection::ReservedId)
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// `element` or one of its descendants holds a reserved id (the composers' fail-closed check).
|
||||
pub fn holds_reserved_id(element: &Element) -> bool {
|
||||
element.attr("id").is_some_and(is_reserved_id)
|
||||
|| element.element_children().any(holds_reserved_id)
|
||||
}
|
||||
|
||||
struct Flat {
|
||||
edges: Vec<usize>,
|
||||
}
|
||||
|
||||
@@ -108,6 +108,9 @@ pub enum SvgRejection {
|
||||
/// inlined in a page it would resolve against another view or the page (owner decision
|
||||
/// 2026-10-29).
|
||||
DanglingReference,
|
||||
/// 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,
|
||||
}
|
||||
|
||||
impl SvgRejection {
|
||||
@@ -123,6 +126,7 @@ impl SvgRejection {
|
||||
Self::TooComplex => "too_complex",
|
||||
Self::ReferenceCycle => "reference_cycle",
|
||||
Self::DanglingReference => "dangling_reference",
|
||||
Self::ReservedId => "reserved_id",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -478,6 +478,7 @@ fn canvas_of<'a>(
|
||||
ComposeError::UnknownView => Failure::new("unknown_view", view_id),
|
||||
ComposeError::InvalidCharacter => Failure::new("invalid_character", view_id),
|
||||
ComposeError::UnscopedReference => Failure::new("svg_rejected", "unscoped_reference"),
|
||||
ComposeError::ReservedId => Failure::new("svg_rejected", "reserved_id"),
|
||||
})?;
|
||||
let svg = serialize(&canvas);
|
||||
if svg.len() > MAX_COMPOSED_BYTES {
|
||||
|
||||
@@ -14,7 +14,9 @@ use std::collections::HashSet;
|
||||
use common::svg_tree::{
|
||||
reread, tree_value, view_names, with_ids_scoped_per_view, with_trigger_names_per_language,
|
||||
};
|
||||
use faunosteo_core::anatomy::compose::{asset_id_of_view, compose_canvas, compose_highlight};
|
||||
use faunosteo_core::anatomy::compose::{
|
||||
ComposeError, asset_id_of_view, compose_canvas, compose_highlight,
|
||||
};
|
||||
use faunosteo_core::anatomy::layer::render_layer;
|
||||
use faunosteo_core::anatomy::svg::{Element, read_svg};
|
||||
use faunosteo_core::domain::sheet::AnatomicalSheetDocument;
|
||||
@@ -166,17 +168,20 @@ fn count(element: &Element, matches: &dyn Fn(&Element) -> bool) -> usize {
|
||||
}
|
||||
|
||||
/// `render.compose.test.ts` "never duplicates the filter on a root that already holds it"
|
||||
/// (R5.7): composing a drawing that already carries the halo filter adds no second filter and no
|
||||
/// second `<defs>` (the TypeScript composed twice on one DOM root; the core takes the root it
|
||||
/// returned).
|
||||
/// (R5.7): the composition writes one halo filter and one `<defs>`. Composing the root it
|
||||
/// returned (the TypeScript composed twice on one DOM root) is refused since V1-2.2 (owner
|
||||
/// brief 2026-10-30): that root holds the reserved `osteo-halo`, which no input may hold.
|
||||
#[test]
|
||||
fn the_halo_filter_is_never_duplicated_on_a_root_that_holds_it() {
|
||||
fn the_halo_filter_is_written_once_and_a_composed_root_is_refused() {
|
||||
let draft = draft();
|
||||
let ids: HashSet<&str> = ["hip"].into_iter().collect();
|
||||
let horse = sanitized(&common::repo_file(HORSE));
|
||||
let once = compose_highlight(&draft, "main", horse, &ids, true).unwrap();
|
||||
let twice = compose_highlight(&draft, "main", once, &ids, true).unwrap();
|
||||
let halo = |e: &Element| e.qname == "filter" && e.attr("id") == Some("osteo-halo");
|
||||
assert_eq!(count(&twice, &halo), 1);
|
||||
assert_eq!(count(&twice, &|e: &Element| e.qname == "defs"), 1);
|
||||
assert_eq!(count(&once, &halo), 1);
|
||||
assert_eq!(count(&once, &|e: &Element| e.qname == "defs"), 1);
|
||||
assert_eq!(
|
||||
compose_highlight(&draft, "main", once, &ids, true).unwrap_err(),
|
||||
ComposeError::ReservedId
|
||||
);
|
||||
}
|
||||
@@ -120,7 +120,7 @@ packages/anatomy/tests/r5.pipeline-oracles.test.ts R5.1 oracles (crates/core/tes
|
||||
packages/anatomy/tests/r5.review-synthetic-oracles.test.ts R5.4 synthetic review oracle > review-synthetic.json review files on synthetic cases (R5.4 oracle) replaced cargo curation_review::the_synthetic_review_cases_match_the_typescript_or_are_refused_as_declared ; cargo curation_review::a_label_the_drawing_cannot_carry_is_refused ; cargo curation_review::ids_and_field_segments_that_could_forge_report_structure_are_refused crates/core/tests/oracles/r5/review-synthetic.json generator; its 4 cases read (raw and aligned reports, overlays bytes, app drawings bytes or declared rule)
|
||||
packages/anatomy/tests/render.compose.test.ts composeViewSvg with a highlight > keeps both elements of a selected point and the selected spine zone, haloed on the main view view composition and highlight (SVG rendering) replaced cargo anatomy_compose::every_highlighted_view_equals_the_engine_tree crates/core/tests/oracles/r3/highlight.json hip (demo obs-demo-2) and cervical (obs-demo-3) haloed on main: circles r34/r22, polygon, #b85a3f, url(#osteo-halo), viewBox 0 0 2073.4 1629.4, no width/height; separate observations in the oracle
|
||||
packages/anatomy/tests/render.compose.test.ts composeViewSvg with a highlight > creates <defs> as the first child of an asset without one and fills it with the halo filter view composition and highlight (SVG rendering) replaced cargo anatomy_compose::every_highlighted_view_equals_the_engine_tree crates/core/tests/oracles/r3/highlight.json main cases carry the defs with the halo filter before the asset children; edge asset with nested defs gets the filter appended there; tree equality (filter attribute order not compared)
|
||||
packages/anatomy/tests/render.compose.test.ts composeViewSvg with a highlight > never duplicates the filter on a root that already holds it view composition and highlight (SVG rendering) ported cargo anatomy_compose::the_halo_filter_is_never_duplicated_on_a_root_that_holds_it - ported at R5.7: compose of a root already holding the filter
|
||||
packages/anatomy/tests/render.compose.test.ts composeViewSvg with a highlight > never duplicates the filter on a root that already holds it view composition and highlight (SVG rendering) ported cargo anatomy_compose::the_halo_filter_is_written_once_and_a_composed_root_is_refused - ported at R5.7: compose of a root already holding the filter; since V1-2.2 (reserved ids, 2026-10-30) one filter per composition and a composed root refused
|
||||
packages/anatomy/tests/render.compose.test.ts composeViewSvg with a highlight > frames the head view on its view box without any halo view composition and highlight (SVG rendering) replaced cargo anatomy_compose::every_highlighted_view_equals_the_engine_tree crates/core/tests/oracles/r3/highlight.json head cases (atm, frontal, occipital; TS used parietal): viewBox 60 100 500 380, no defs, #b85a3f circles without filter
|
||||
packages/anatomy/tests/render.compose.test.ts composeViewSvg with a highlight > leaves an empty layer when nothing is selected view composition and highlight (SVG rendering) replaced cargo anatomy_compose::every_highlighted_view_equals_the_engine_tree crates/core/tests/oracles/r3/highlight.json v2unresolved observations and edge-4 (no zones): empty layer
|
||||
packages/anatomy/tests/render.compose.test.ts composeViewSvg with a highlight > keeps the <title> of every kept marker and emits no data attribute view composition and highlight (SVG rendering) replaced cargo anatomy_compose::every_highlighted_view_equals_the_engine_tree crates/core/tests/oracles/r3/highlight.json titles are text nodes of the frozen trees, compared; no data-* attribute in any highlighted layer
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 12 and column 108.
|
@@ -13,11 +13,14 @@ use std::collections::HashSet;
|
||||
|
||||
use common::r4::{r4_oracle, repo_root, sha256_hex};
|
||||
use faunosteo_core::anatomy::compose::{asset_id_of_view, compose_highlight};
|
||||
use faunosteo_core::anatomy::svg::{read_svg, serialize::serialize};
|
||||
use faunosteo_core::anatomy::svg::tree::parse_svg;
|
||||
use faunosteo_core::anatomy::svg::{Element, read_svg, serialize::serialize};
|
||||
use faunosteo_core::domain::js::parse_json;
|
||||
use faunosteo_core::pdf::read::probe::{ProbeLimits, read_attached_document};
|
||||
use faunosteo_core::pdf::write::export::export_pdf;
|
||||
use faunosteo_core::pdf::write::input::{ExportInput, ExportWarning, LogoSlot, Rasters};
|
||||
use faunosteo_core::pdf::write::input::{
|
||||
ExportError, ExportErrorKind, ExportInput, ExportWarning, LogoSlot, Rasters,
|
||||
};
|
||||
use faunosteo_core::pdf::write::session::{
|
||||
ExportSession, ExportStep, SessionError, SessionRefusal, keyed,
|
||||
};
|
||||
@@ -380,3 +383,110 @@ fn the_one_shot_driver_reports_absent_rasters_as_failed() {
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// The demo export's input as JSON, before it is typed.
|
||||
fn demo_value() -> Value {
|
||||
let pdf = fixture("pdf/r3/demo.fr.logos.pdf");
|
||||
let located = read_attached_document(&pdf, ProbeLimits::UNBOUNDED).unwrap();
|
||||
let envelope: Value = parse_json(&located.text).unwrap();
|
||||
json!({
|
||||
"report": envelope["report"],
|
||||
"sheetSnapshot": envelope["sheetSnapshot"],
|
||||
"branding": envelope["branding"],
|
||||
"labels": envelope["labels"],
|
||||
"locale": envelope["locale"],
|
||||
"exportedAt": envelope["exportedAt"],
|
||||
})
|
||||
}
|
||||
|
||||
/// The demo export's snapshot with `edit` applied to its first drawing.
|
||||
fn export_with_drawing(edit: impl Fn(&str) -> String) -> Result<ExportSession, ExportError> {
|
||||
let mut input = demo_value();
|
||||
let svg = input["sheetSnapshot"]["assets"][0]["svg"].as_str().unwrap();
|
||||
input["sheetSnapshot"]["assets"][0]["svg"] = json!(edit(svg));
|
||||
ExportSession::new(serde_json::from_value(input).unwrap())
|
||||
}
|
||||
|
||||
/// The first drawing with `body` written right after its root's opening tag.
|
||||
fn inject(body: &'static str) -> impl Fn(&str) -> String {
|
||||
move |svg: &str| {
|
||||
let open = svg.find("<svg").unwrap();
|
||||
let end = open + svg[open..].find('>').unwrap() + 1;
|
||||
format!("{}{body}{}", &svg[..end], &svg[end..])
|
||||
}
|
||||
}
|
||||
|
||||
/// V1-2.2 owner brief 2026-10-30 (reserved ids, `tests/svg_reserved_ids.rs`): a snapshot
|
||||
/// drawing holding the reserved id is refused at the gate (`snapshot_invalid`, `asset
|
||||
/// reserved_id`), never composed; the demo export's views carry the engine's halo filter once,
|
||||
/// and every highlighted marker names it.
|
||||
#[test]
|
||||
fn the_pdf_refuses_a_reserved_id_and_keeps_its_own_halo() {
|
||||
for body in [
|
||||
"<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>",
|
||||
"<g id=\"osteo-halo\"/><defs/>",
|
||||
"<g id=\"Osteo-Halo\"/>",
|
||||
] {
|
||||
match export_with_drawing(inject(body)) {
|
||||
Err(error) => {
|
||||
assert_eq!(error.kind, ExportErrorKind::SnapshotInvalid, "{body}");
|
||||
assert_eq!(error.detail, "asset reserved_id", "{body}");
|
||||
}
|
||||
Ok(_) => panic!("{body}: composed"),
|
||||
}
|
||||
}
|
||||
|
||||
let mut session = export_with_drawing(str::to_owned).unwrap();
|
||||
let png = base64(TWO_BY_ONE_PNG);
|
||||
let mut haloed_views = 0;
|
||||
while let ExportStep::Rasters { requests } = session.next_step().unwrap() {
|
||||
for request in requests {
|
||||
let root = parse_svg(&request.svg).unwrap();
|
||||
let mut halos = Vec::new();
|
||||
holders(&root, "osteo-halo", &mut halos);
|
||||
if request.key.starts_with("view:") && request.svg.contains("url(#osteo-halo)") {
|
||||
haloed_views += 1;
|
||||
assert_eq!(halos.len(), 1, "{}", request.key);
|
||||
assert_eq!(halos[0].qname, "filter", "{}", request.key);
|
||||
assert_eq!(
|
||||
serialize(halos[0]),
|
||||
concat!(
|
||||
"<filter xmlns=\"http://www.w3.org/2000/svg\" id=\"osteo-halo\" x=\"-100%\" y=\"-100%\" width=\"300%\" ",
|
||||
"height=\"300%\" filterUnits=\"userSpaceOnUse\">",
|
||||
"<feGaussianBlur in=\"SourceGraphic\" stdDeviation=\"18\" result=\"haloWide\"/>",
|
||||
"<feGaussianBlur in=\"SourceGraphic\" stdDeviation=\"8\" result=\"haloTight\"/>",
|
||||
"<feMerge><feMergeNode in=\"haloWide\"/><feMergeNode in=\"haloWide\"/>",
|
||||
"<feMergeNode in=\"haloWide\"/><feMergeNode in=\"haloTight\"/>",
|
||||
"<feMergeNode in=\"haloTight\"/><feMergeNode in=\"SourceGraphic\"/></feMerge>",
|
||||
"</filter>"
|
||||
),
|
||||
"{}",
|
||||
request.key
|
||||
);
|
||||
let layer = root.element_children().last().unwrap();
|
||||
assert!(layer.element_children().count() > 0, "{}", request.key);
|
||||
for marker in layer.element_children() {
|
||||
assert_eq!(marker.attr("filter"), Some("url(#osteo-halo)"));
|
||||
assert_eq!(marker.attr("fill"), Some("#b85a3f"));
|
||||
}
|
||||
} else {
|
||||
assert!(halos.is_empty(), "{}", request.key);
|
||||
}
|
||||
session.add_raster(&request.key, &png).unwrap();
|
||||
}
|
||||
}
|
||||
assert!(haloed_views > 0);
|
||||
session.finish().unwrap();
|
||||
assert!(session.take_part().unwrap().starts_with(b"%PDF-1.7"));
|
||||
assert!(session.warnings().is_empty());
|
||||
}
|
||||
|
||||
/// 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);
|
||||
}
|
||||
}
|
||||
@@ -70,6 +70,8 @@ fn the_hostile_corpus_answers_as_the_contract_table() {
|
||||
Rejected,
|
||||
Some("dangling_reference"),
|
||||
),
|
||||
// An id the composition writes (owner brief 2026-10-30).
|
||||
("osteo-halo-id.svg", Rejected, Some("reserved_id")),
|
||||
// Other removals: cleaning offered.
|
||||
("id-grammar.svg", Cleanable, None),
|
||||
("long-title.svg", Cleanable, None),
|
||||
@@ -82,7 +84,6 @@ fn the_hostile_corpus_answers_as_the_contract_table() {
|
||||
("xlink-prefix-rebound.svg", Cleanable, None),
|
||||
// Nothing removed (comments, stray text and clamped values are no removal).
|
||||
("duplicate-ids.svg", Clean, None),
|
||||
("osteo-halo-id.svg", Clean, None),
|
||||
("root-without-namespace.svg", Clean, None),
|
||||
("std-deviation.svg", Clean, None),
|
||||
("viewbox-non-finite.svg", Clean, None),
|
||||
|
||||
@@ -0,0 +1,576 @@
|
||||
//! 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 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 serde::Deserialize;
|
||||
use serde_json::{Value, 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// 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)
|
||||
}
|
||||
|
||||
/// 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"]);
|
||||
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(&svg(ERASER));
|
||||
assert_refused_everywhere(&svg(&format!(
|
||||
"<defs>{ERASER}</defs><path filter=\"url(#osteo-halo)\" d=\"M0 0h1\"/>"
|
||||
)));
|
||||
assert_refused_everywhere(&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(&svg(body));
|
||||
}
|
||||
let root = OPEN.replace("viewBox", "id=\"osteo-halo\" viewBox");
|
||||
assert_refused_everywhere(&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("#osteo-halo")\" 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(&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-halo",
|
||||
"osteo-halo",
|
||||
"osteo-halo",
|
||||
"osteo-halo",
|
||||
"Osteo-halo",
|
||||
"OSTEO-HALO",
|
||||
"oSTEO-hALO",
|
||||
];
|
||||
for id in decoded_to_reserved {
|
||||
assert_refused_everywhere(&svg(&format!("<g id=\"{id}\"/>")));
|
||||
}
|
||||
|
||||
let removed = [
|
||||
("<g id=\" osteo-halo\"/>", "g@id"),
|
||||
("<g id=\"osteo-halo \"/>", "g@id"),
|
||||
("<g id=\"osteo-halo	\"/>", "g@id"),
|
||||
("<g id=\"osteo-halo \"/>", "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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -55,6 +55,9 @@ fn declared(file: &str) -> Option<Value> {
|
||||
// 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" => {
|
||||
|
||||
@@ -167,6 +167,10 @@ describe('clean_svg through the shipped module', () => {
|
||||
expect(cleanHorse.stored).toBe(new TextDecoder().decode(horse))
|
||||
const dangling = new TextEncoder().encode('<svg xmlns="http://www.w3.org/2000/svg"><use href="#nope"/></svg>')
|
||||
expect(value(glue.clean_svg(dangling)).reason).toBe('dangling_reference')
|
||||
for (const id of ['osteo-halo', 'OSTEO-HALO', 'osteo-halo']) {
|
||||
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')
|
||||
}
|
||||
const cairo = value(
|
||||
glue.clean_svg(new Uint8Array(readFileSync(path(`${EXPORTS}cairo-1.18.4-pycairo-1.27.0-shapes.svg`)))),
|
||||
)
|
||||
|
||||
Reference in new issue
Block a user